diff --git a/.agent/.DS_Store b/.agent/.DS_Store new file mode 100644 index 000000000..1f2c43e08 Binary files /dev/null and b/.agent/.DS_Store differ diff --git a/.agent/workflows/update_clawdbot.md b/.agent/workflows/update_clawdbot.md new file mode 100644 index 000000000..692ee84e4 --- /dev/null +++ b/.agent/workflows/update_clawdbot.md @@ -0,0 +1,366 @@ +--- +description: Update Clawdbot from upstream when branch has diverged (ahead/behind) +--- + +# Clawdbot Upstream Sync Workflow + +Use this workflow when your fork has diverged from upstream (e.g., "18 commits ahead, 29 commits behind"). + +## Quick Reference + +```bash +# Check divergence status +git fetch upstream && git rev-list --left-right --count main...upstream/main + +# Full sync (rebase preferred) +git fetch upstream && git rebase upstream/main && pnpm install && pnpm build && ./scripts/restart-mac.sh + +# Check for Swift 6.2 issues after sync +grep -r "FileManager\.default\|Thread\.isMainThread" src/ apps/ --include="*.swift" +``` + +--- + +## Step 1: Assess Divergence + +```bash +git fetch upstream +git log --oneline --left-right main...upstream/main | head -20 +``` + +This shows: +- `<` = your local commits (ahead) +- `>` = upstream commits you're missing (behind) + +**Decision point:** +- Few local commits, many upstream → **Rebase** (cleaner history) +- Many local commits or shared branch → **Merge** (preserves history) + +--- + +## Step 2A: Rebase Strategy (Preferred) + +Replays your commits on top of upstream. Results in linear history. + +```bash +# Ensure working tree is clean +git status + +# Rebase onto upstream +git rebase upstream/main +``` + +### Handling Rebase Conflicts + +```bash +# When conflicts occur: +# 1. Fix conflicts in the listed files +# 2. Stage resolved files +git add + +# 3. Continue rebase +git rebase --continue + +# If a commit is no longer needed (already in upstream): +git rebase --skip + +# To abort and return to original state: +git rebase --abort +``` + +### Common Conflict Patterns + +| File | Resolution | +|------|------------| +| `package.json` | Take upstream deps, keep local scripts if needed | +| `pnpm-lock.yaml` | Accept upstream, regenerate with `pnpm install` | +| `*.patch` files | Usually take upstream version | +| Source files | Merge logic carefully, prefer upstream structure | + +--- + +## Step 2B: Merge Strategy (Alternative) + +Preserves all history with a merge commit. + +```bash +git merge upstream/main --no-edit +``` + +Resolve conflicts same as rebase, then: +```bash +git add +git commit +``` + +--- + +## Step 3: Rebuild Everything + +After sync completes: + +```bash +# Install dependencies (regenerates lock if needed) +pnpm install + +# Build TypeScript +pnpm build + +# Build UI assets +pnpm ui:build + +# Run diagnostics +pnpm clawdbot doctor +``` + +--- + +## Step 4: Rebuild macOS App + +```bash +# Full rebuild, sign, and launch +./scripts/restart-mac.sh + +# Or just package without restart +pnpm mac:package +``` + +### Install to /Applications + +```bash +# Kill running app +pkill -x "Clawdbot" || true + +# Move old version +mv /Applications/Clawdbot.app /tmp/Clawdbot-backup.app + +# Install new build +cp -R dist/Clawdbot.app /Applications/ + +# Launch +open /Applications/Clawdbot.app +``` + +--- + +## Step 4A: Verify macOS App & Agent + +After rebuilding the macOS app, always verify it works correctly: + +```bash +# Check gateway health +pnpm clawdbot health + +# Verify no zombie processes +ps aux | grep -E "(clawdbot|gateway)" | grep -v grep + +# Test agent functionality by sending a verification message +pnpm clawdbot agent --message "Verification: macOS app rebuild successful - agent is responding." --session-id YOUR_TELEGRAM_SESSION_ID + +# Confirm the message was received on Telegram +# (Check your Telegram chat with the bot) +``` + +**Important:** Always wait for the Telegram verification message before proceeding. If the agent doesn't respond, troubleshoot the gateway or model configuration before pushing. + +--- + +## Step 5: Handle Swift/macOS Build Issues (Common After Upstream Sync) + +Upstream updates may introduce Swift 6.2 / macOS 26 SDK incompatibilities. Use analyze-mode for systematic debugging: + +### Analyze-Mode Investigation +```bash +# Gather context with parallel agents +morph-mcp_warpgrep_codebase_search search_string="Find deprecated FileManager.default and Thread.isMainThread usages in Swift files" repo_path="/Volumes/Main SSD/Developer/clawdis" +morph-mcp_warpgrep_codebase_search search_string="Locate Peekaboo submodule and macOS app Swift files with concurrency issues" repo_path="/Volumes/Main SSD/Developer/clawdis" +``` + +### Common Swift 6.2 Fixes + +**FileManager.default Deprecation:** +```bash +# Search for deprecated usage +grep -r "FileManager\.default" src/ apps/ --include="*.swift" + +# Replace with proper initialization +# OLD: FileManager.default +# NEW: FileManager() +``` + +**Thread.isMainThread Deprecation:** +```bash +# Search for deprecated usage +grep -r "Thread\.isMainThread" src/ apps/ --include="*.swift" + +# Replace with modern concurrency check +# OLD: Thread.isMainThread +# NEW: await MainActor.run { ... } or DispatchQueue.main.sync { ... } +``` + +### Peekaboo Submodule Fixes +```bash +# Check Peekaboo for concurrency issues +cd src/canvas-host/a2ui +grep -r "Thread\.isMainThread\|FileManager\.default" . --include="*.swift" + +# Fix and rebuild submodule +cd /Volumes/Main SSD/Developer/clawdis +pnpm canvas:a2ui:bundle +``` + +### macOS App Concurrency Fixes +```bash +# Check macOS app for issues +grep -r "Thread\.isMainThread\|FileManager\.default" apps/macos/ --include="*.swift" + +# Clean and rebuild after fixes +cd apps/macos && rm -rf .build .swiftpm +./scripts/restart-mac.sh +``` + +### Model Configuration Updates +If upstream introduced new model configurations: +```bash +# Check for OpenRouter API key requirements +grep -r "openrouter\|OPENROUTER" src/ --include="*.ts" --include="*.js" + +# Update clawdbot.json with fallback chains +# Add model fallback configurations as needed +``` + +--- + +## Step 6: Verify & Push + +```bash +# Verify everything works +pnpm clawdbot health +pnpm test + +# Push (force required after rebase) +git push origin main --force-with-lease + +# Or regular push after merge +git push origin main +``` + +--- + +## Troubleshooting + +### Build Fails After Sync + +```bash +# Clean and rebuild +rm -rf node_modules dist +pnpm install +pnpm build +``` + +### Type Errors (Bun/Node Incompatibility) + +Common issue: `fetch.preconnect` type mismatch. Fix by using `FetchLike` type instead of `typeof fetch`. + +### macOS App Crashes on Launch + +Usually resource bundle mismatch. Full rebuild required: +```bash +cd apps/macos && rm -rf .build .swiftpm +./scripts/restart-mac.sh +``` + +### Patch Failures + +```bash +# Check patch status +pnpm install 2>&1 | grep -i patch + +# If patches fail, they may need updating for new dep versions +# Check patches/ directory against package.json patchedDependencies +``` + +### Swift 6.2 / macOS 26 SDK Build Failures + +**Symptoms:** Build fails with deprecation warnings about `FileManager.default` or `Thread.isMainThread` + +**Search-Mode Investigation:** +```bash +# Exhaustive search for deprecated APIs +morph-mcp_warpgrep_codebase_search search_string="Find all Swift files using deprecated FileManager.default or Thread.isMainThread" repo_path="/Volumes/Main SSD/Developer/clawdis" +``` + +**Quick Fix Commands:** +```bash +# Find all affected files +find . -name "*.swift" -exec grep -l "FileManager\.default\|Thread\.isMainThread" {} \; + +# Replace FileManager.default with FileManager() +find . -name "*.swift" -exec sed -i '' 's/FileManager\.default/FileManager()/g' {} \; + +# For Thread.isMainThread, need manual review of each usage +grep -rn "Thread\.isMainThread" --include="*.swift" . +``` + +**Rebuild After Fixes:** +```bash +# Clean all build artifacts +rm -rf apps/macos/.build apps/macos/.swiftpm +rm -rf src/canvas-host/a2ui/.build + +# Rebuild Peekaboo bundle +pnpm canvas:a2ui:bundle + +# Full macOS rebuild +./scripts/restart-mac.sh +``` + +--- + +## Automation Script + +Save as `scripts/sync-upstream.sh`: + +```bash +#!/usr/bin/env bash +set -euo pipefail + +echo "==> Fetching upstream..." +git fetch upstream + +echo "==> Current divergence:" +git rev-list --left-right --count main...upstream/main + +echo "==> Rebasing onto upstream/main..." +git rebase upstream/main + +echo "==> Installing dependencies..." +pnpm install + +echo "==> Building..." +pnpm build +pnpm ui:build + +echo "==> Running doctor..." +pnpm clawdbot doctor + +echo "==> Rebuilding macOS app..." +./scripts/restart-mac.sh + +echo "==> Verifying gateway health..." +pnpm clawdbot health + +echo "==> Checking for Swift 6.2 compatibility issues..." +if grep -r "FileManager\.default\|Thread\.isMainThread" src/ apps/ --include="*.swift" --quiet; then + echo "⚠️ Found potential Swift 6.2 deprecated API usage" + echo " Run manual fixes or use analyze-mode investigation" +else + echo "✅ No obvious Swift deprecation issues found" +fi + +echo "==> Testing agent functionality..." +# Note: Update YOUR_TELEGRAM_SESSION_ID with actual session ID +pnpm clawdbot agent --message "Verification: Upstream sync and macOS rebuild completed successfully." --session-id YOUR_TELEGRAM_SESSION_ID || echo "Warning: Agent test failed - check Telegram for verification message" + +echo "==> Done! Check Telegram for verification message, then run 'git push --force-with-lease' when ready." +``` diff --git a/.detect-secrets.cfg b/.detect-secrets.cfg index 66ed5236e..38912567c 100644 --- a/.detect-secrets.cfg +++ b/.detect-secrets.cfg @@ -7,6 +7,10 @@ [exclude-files] # pnpm lockfiles contain lots of high-entropy package integrity blobs. pattern = (^|/)pnpm-lock\.yaml$ +# Generated output and vendored assets. +pattern = (^|/)(dist|vendor)/ +# Local config file with allowlist patterns. +pattern = (^|/)\.detect-secrets\.cfg$ [exclude-lines] # Fastlane checks for private key marker; not a real key. diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 000000000..bcfdefcdd --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,17 @@ +# actionlint configuration +# https://github.com/rhysd/actionlint/blob/main/docs/config.md + +self-hosted-runner: + labels: + # Blacksmith CI runners + - blacksmith-4vcpu-ubuntu-2404 + - blacksmith-4vcpu-windows-2025 + +# Ignore patterns for known issues +paths: + .github/workflows/**/*.yml: + ignore: + # Ignore shellcheck warnings (we run shellcheck separately) + - 'shellcheck reported issue.+' + # Ignore intentional if: false for disabled jobs + - 'constant expression "false" in condition' diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..c0e1d465b --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,113 @@ +# Dependabot configuration +# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 + +registries: + npm-npmjs: + type: npm-registry + url: https://registry.npmjs.org + replaces-base: true + +updates: + # npm dependencies (root) + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + production: + dependency-type: production + update-types: + - minor + - patch + development: + dependency-type: development + update-types: + - minor + - patch + open-pull-requests-limit: 10 + registries: + - npm-npmjs + + # GitHub Actions + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + actions: + patterns: + - "*" + update-types: + - minor + - patch + open-pull-requests-limit: 5 + + # Swift Package Manager - macOS app + - package-ecosystem: swift + directory: /apps/macos + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + swift-deps: + patterns: + - "*" + update-types: + - minor + - patch + open-pull-requests-limit: 5 + + # Swift Package Manager - shared ClawdbotKit + - package-ecosystem: swift + directory: /apps/shared/ClawdbotKit + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + swift-deps: + patterns: + - "*" + update-types: + - minor + - patch + open-pull-requests-limit: 5 + + # Swift Package Manager - Swabble + - package-ecosystem: swift + directory: /Swabble + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + swift-deps: + patterns: + - "*" + update-types: + - minor + - patch + open-pull-requests-limit: 5 + + # Gradle - Android app + - package-ecosystem: gradle + directory: /apps/android + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + android-deps: + patterns: + - "*" + update-types: + - minor + - patch + open-pull-requests-limit: 5 diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 000000000..5d2837a6c --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,174 @@ +"channel: bluebubbles": + - changed-files: + - any-glob-to-any-file: + - "extensions/bluebubbles/**" + - "docs/channels/bluebubbles.md" +"channel: discord": + - changed-files: + - any-glob-to-any-file: + - "src/discord/**" + - "extensions/discord/**" + - "docs/channels/discord.md" +"channel: googlechat": + - changed-files: + - any-glob-to-any-file: + - "extensions/googlechat/**" + - "docs/channels/googlechat.md" +"channel: imessage": + - changed-files: + - any-glob-to-any-file: + - "src/imessage/**" + - "extensions/imessage/**" + - "docs/channels/imessage.md" +"channel: line": + - changed-files: + - any-glob-to-any-file: + - "extensions/line/**" +"channel: matrix": + - changed-files: + - any-glob-to-any-file: + - "extensions/matrix/**" + - "docs/channels/matrix.md" +"channel: mattermost": + - changed-files: + - any-glob-to-any-file: + - "extensions/mattermost/**" + - "docs/channels/mattermost.md" +"channel: msteams": + - changed-files: + - any-glob-to-any-file: + - "extensions/msteams/**" + - "docs/channels/msteams.md" +"channel: nextcloud-talk": + - changed-files: + - any-glob-to-any-file: + - "extensions/nextcloud-talk/**" + - "docs/channels/nextcloud-talk.md" +"channel: nostr": + - changed-files: + - any-glob-to-any-file: + - "extensions/nostr/**" + - "docs/channels/nostr.md" +"channel: signal": + - changed-files: + - any-glob-to-any-file: + - "src/signal/**" + - "extensions/signal/**" + - "docs/channels/signal.md" +"channel: slack": + - changed-files: + - any-glob-to-any-file: + - "src/slack/**" + - "extensions/slack/**" + - "docs/channels/slack.md" +"channel: telegram": + - changed-files: + - any-glob-to-any-file: + - "src/telegram/**" + - "extensions/telegram/**" + - "docs/channels/telegram.md" +"channel: tlon": + - changed-files: + - any-glob-to-any-file: + - "extensions/tlon/**" + - "docs/channels/tlon.md" +"channel: voice-call": + - changed-files: + - any-glob-to-any-file: + - "extensions/voice-call/**" +"channel: whatsapp-web": + - changed-files: + - any-glob-to-any-file: + - "src/web/**" + - "extensions/whatsapp/**" + - "docs/channels/whatsapp.md" +"channel: zalo": + - changed-files: + - any-glob-to-any-file: + - "extensions/zalo/**" + - "docs/channels/zalo.md" +"channel: zalouser": + - changed-files: + - any-glob-to-any-file: + - "extensions/zalouser/**" + - "docs/channels/zalouser.md" + +"app: android": + - changed-files: + - any-glob-to-any-file: + - "apps/android/**" + - "docs/platforms/android.md" +"app: ios": + - changed-files: + - any-glob-to-any-file: + - "apps/ios/**" + - "docs/platforms/ios.md" +"app: macos": + - changed-files: + - any-glob-to-any-file: + - "apps/macos/**" + - "docs/platforms/macos.md" + - "docs/platforms/mac/**" +"app: web-ui": + - changed-files: + - any-glob-to-any-file: + - "ui/**" + - "src/gateway/control-ui.ts" + - "src/gateway/control-ui-shared.ts" + - "src/gateway/protocol/**" + - "src/gateway/server-methods/chat.ts" + - "src/infra/control-ui-assets.ts" + +"gateway": + - changed-files: + - any-glob-to-any-file: + - "src/gateway/**" + - "src/daemon/**" + - "docs/gateway/**" + +"docs": + - changed-files: + - any-glob-to-any-file: + - "docs/**" + - "docs.acp.md" + +"extensions: copilot-proxy": + - changed-files: + - any-glob-to-any-file: + - "extensions/copilot-proxy/**" +"extensions: diagnostics-otel": + - changed-files: + - any-glob-to-any-file: + - "extensions/diagnostics-otel/**" +"extensions: google-antigravity-auth": + - changed-files: + - any-glob-to-any-file: + - "extensions/google-antigravity-auth/**" +"extensions: google-gemini-cli-auth": + - changed-files: + - any-glob-to-any-file: + - "extensions/google-gemini-cli-auth/**" +"extensions: llm-task": + - changed-files: + - any-glob-to-any-file: + - "extensions/llm-task/**" +"extensions: lobster": + - changed-files: + - any-glob-to-any-file: + - "extensions/lobster/**" +"extensions: memory-core": + - changed-files: + - any-glob-to-any-file: + - "extensions/memory-core/**" +"extensions: memory-lancedb": + - changed-files: + - any-glob-to-any-file: + - "extensions/memory-lancedb/**" +"extensions: open-prose": + - changed-files: + - any-glob-to-any-file: + - "extensions/open-prose/**" +"extensions: qwen-portal-auth": + - changed-files: + - any-glob-to-any-file: + - "extensions/qwen-portal-auth/**" diff --git a/.github/workflows/auto-response.yml b/.github/workflows/auto-response.yml new file mode 100644 index 000000000..7f242a094 --- /dev/null +++ b/.github/workflows/auto-response.yml @@ -0,0 +1,59 @@ +name: Auto response + +on: + issues: + types: [labeled] + pull_request: + types: [labeled] + +permissions: + issues: write + pull-requests: write + +jobs: + auto-response: + runs-on: ubuntu-latest + steps: + - name: Handle labeled items + uses: actions/github-script@v7 + with: + script: | + const rules = [ + { + label: "skill-clawdhub", + close: true, + message: + "Thanks for the contribution! New skills should be published to Clawdhub for everyone to use. We’re keeping the core lean on skills, so I’m closing this out.", + }, + ]; + + const labelName = context.payload.label?.name; + if (!labelName) { + return; + } + + const rule = rules.find((item) => item.label === labelName); + if (!rule) { + return; + } + + const issueNumber = context.payload.issue?.number ?? context.payload.pull_request?.number; + if (!issueNumber) { + return; + } + + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + body: rule.message, + }); + + if (rule.close) { + await github.rest.issues.update({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + state: "closed", + }); + } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index be0d8926f..8cc86bd63 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,20 +32,29 @@ jobs: node-version: 22.x check-latest: true + - name: Setup pnpm (corepack retry) + run: | + set -euo pipefail + corepack enable + for attempt in 1 2 3; do + if corepack prepare pnpm@10.23.0 --activate; then + pnpm -v + exit 0 + fi + echo "corepack prepare failed (attempt $attempt/3). Retrying..." + sleep $((attempt * 10)) + done + exit 1 + - name: Runtime versions run: | node -v npm -v + pnpm -v - name: Capture node path run: echo "NODE_BIN=$(dirname \"$(node -p \"process.execPath\")\")" >> "$GITHUB_ENV" - - name: Enable corepack and pin pnpm - run: | - corepack enable - corepack prepare pnpm@10.23.0 --activate - pnpm -v - - name: Install dependencies (frozen) env: CI: true @@ -108,6 +117,20 @@ jobs: node-version: 22.x check-latest: true + - name: Setup pnpm (corepack retry) + run: | + set -euo pipefail + corepack enable + for attempt in 1 2 3; do + if corepack prepare pnpm@10.23.0 --activate; then + pnpm -v + exit 0 + fi + echo "corepack prepare failed (attempt $attempt/3). Retrying..." + sleep $((attempt * 10)) + done + exit 1 + - name: Setup Bun uses: oven-sh/setup-bun@v2 with: @@ -118,16 +141,11 @@ jobs: node -v npm -v bun -v + pnpm -v - name: Capture node path run: echo "NODE_BIN=$(dirname \"$(node -p \"process.execPath\")\")" >> "$GITHUB_ENV" - - name: Enable corepack and pin pnpm - run: | - corepack enable - corepack prepare pnpm@10.23.0 --activate - pnpm -v - - name: Install dependencies env: CI: true @@ -168,6 +186,8 @@ jobs: checks-windows: runs-on: blacksmith-4vcpu-windows-2025 + env: + NODE_OPTIONS: --max-old-space-size=4096 defaults: run: shell: bash @@ -212,6 +232,20 @@ jobs: node-version: 22.x check-latest: true + - name: Setup pnpm (corepack retry) + run: | + set -euo pipefail + corepack enable + for attempt in 1 2 3; do + if corepack prepare pnpm@10.23.0 --activate; then + pnpm -v + exit 0 + fi + echo "corepack prepare failed (attempt $attempt/3). Retrying..." + sleep $((attempt * 10)) + done + exit 1 + - name: Setup Bun uses: oven-sh/setup-bun@v2 with: @@ -222,16 +256,11 @@ jobs: node -v npm -v bun -v + pnpm -v - name: Capture node path run: echo "NODE_BIN=$(dirname \"$(node -p \"process.execPath\")\")" >> "$GITHUB_ENV" - - name: Enable corepack and pin pnpm - run: | - corepack enable - corepack prepare pnpm@10.23.0 --activate - pnpm -v - - name: Install dependencies env: CI: true @@ -279,20 +308,29 @@ jobs: node-version: 22.x check-latest: true + - name: Setup pnpm (corepack retry) + run: | + set -euo pipefail + corepack enable + for attempt in 1 2 3; do + if corepack prepare pnpm@10.23.0 --activate; then + pnpm -v + exit 0 + fi + echo "corepack prepare failed (attempt $attempt/3). Retrying..." + sleep $((attempt * 10)) + done + exit 1 + - name: Runtime versions run: | node -v npm -v + pnpm -v - name: Capture node path run: echo "NODE_BIN=$(dirname \"$(node -p \"process.execPath\")\")" >> "$GITHUB_ENV" - - name: Enable corepack and pin pnpm - run: | - corepack enable - corepack prepare pnpm@10.23.0 --activate - pnpm -v - - name: Install dependencies env: CI: true @@ -304,6 +342,8 @@ jobs: pnpm install --frozen-lockfile --ignore-scripts=false --config.engine-strict=false --config.enable-pre-post-scripts=true || pnpm install --frozen-lockfile --ignore-scripts=false --config.engine-strict=false --config.enable-pre-post-scripts=true - name: Run ${{ matrix.task }} + env: + NODE_OPTIONS: --max-old-space-size=4096 run: ${{ matrix.command }} macos-app: @@ -590,6 +630,8 @@ jobs: - name: Setup Gradle uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: 8.11.1 - name: Install Android SDK packages run: | diff --git a/.github/workflows/docker-release.yml b/.github/workflows/docker-release.yml new file mode 100644 index 000000000..aa175961d --- /dev/null +++ b/.github/workflows/docker-release.yml @@ -0,0 +1,143 @@ +name: Docker Release + +on: + push: + branches: + - main + tags: + - "v*" + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + # Build amd64 image + build-amd64: + runs-on: ubuntu-latest + permissions: + packages: write + contents: read + outputs: + image-digest: ${{ steps.build.outputs.digest }} + image-metadata: ${{ steps.meta.outputs.json }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + type=semver,pattern={{version}},suffix=-amd64 + type=semver,pattern={{version}},suffix=-arm64 + type=ref,event=branch,suffix=-amd64 + type=ref,event=branch,suffix=-arm64 + + - name: Build and push amd64 image + id: build + uses: docker/build-push-action@v6 + with: + context: . + platforms: linux/amd64 + labels: ${{ steps.meta.outputs.labels }} + tags: ${{ steps.meta.outputs.tags }} + cache-from: type=gha + cache-to: type=gha,mode=max + provenance: false + push: true + + # Build arm64 image + build-arm64: + runs-on: ubuntu-24.04-arm + permissions: + packages: write + contents: read + outputs: + image-digest: ${{ steps.build.outputs.digest }} + image-metadata: ${{ steps.meta.outputs.json }} + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + type=semver,pattern={{version}},suffix=-amd64 + type=semver,pattern={{version}},suffix=-arm64 + type=ref,event=branch,suffix=-amd64 + type=ref,event=branch,suffix=-arm64 + + - name: Build and push arm64 image + id: build + uses: docker/build-push-action@v6 + with: + context: . + platforms: linux/arm64 + labels: ${{ steps.meta.outputs.labels }} + tags: ${{ steps.meta.outputs.tags }} + cache-from: type=gha + cache-to: type=gha,mode=max + provenance: false + push: true + + # Create multi-platform manifest + create-manifest: + runs-on: ubuntu-latest + permissions: + packages: write + contents: read + needs: [build-amd64, build-arm64] + steps: + - name: Login to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata for manifest + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + + - name: Create and push manifest + run: | + docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \ + ${{ needs.build-amd64.outputs.image-digest }} \ + ${{ needs.build-arm64.outputs.image-digest }} + env: + DOCKER_METADATA_OUTPUT_JSON: ${{ steps.meta.outputs.json }} diff --git a/.github/workflows/install-smoke.yml b/.github/workflows/install-smoke.yml index b7e8e274e..16eba4eed 100644 --- a/.github/workflows/install-smoke.yml +++ b/.github/workflows/install-smoke.yml @@ -13,12 +13,19 @@ jobs: - name: Checkout CLI uses: actions/checkout@v4 - - name: Setup pnpm - uses: pnpm/action-setup@v3 - with: - version: 10 - - name: Enable Corepack - run: corepack enable + - name: Setup pnpm (corepack retry) + run: | + set -euo pipefail + corepack enable + for attempt in 1 2 3; do + if corepack prepare pnpm@10.23.0 --activate; then + pnpm -v + exit 0 + fi + echo "corepack prepare failed (attempt $attempt/3). Retrying..." + sleep $((attempt * 10)) + done + exit 1 - name: Install pnpm deps (minimal) run: pnpm install --ignore-scripts --frozen-lockfile @@ -29,5 +36,6 @@ jobs: CLAWDBOT_INSTALL_CLI_URL: https://clawd.bot/install-cli.sh CLAWDBOT_NO_ONBOARD: "1" CLAWDBOT_INSTALL_SMOKE_SKIP_CLI: "1" + CLAWDBOT_INSTALL_SMOKE_SKIP_NONROOT: ${{ github.event_name == 'pull_request' && '1' || '0' }} CLAWDBOT_INSTALL_SMOKE_PREVIOUS: "2026.1.11-4" run: pnpm test:install:smoke diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 000000000..8d078774b --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,23 @@ +name: Labeler + +on: + pull_request_target: + types: [opened, synchronize, reopened] + +permissions: + contents: read + pull-requests: write + +jobs: + label: + runs-on: ubuntu-latest + steps: + - uses: actions/create-github-app-token@v1 + id: app-token + with: + app-id: "2729701" + private-key: ${{ secrets.GH_APP_PRIVATE_KEY }} + - uses: actions/labeler@v5 + with: + configuration-path: .github/labeler.yml + repo-token: ${{ steps.app-token.outputs.token }} diff --git a/.gitignore b/.gitignore index 147a3a32f..b2c1de9a2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ node_modules +**/node_modules/ .env docker-compose.extra.yml dist @@ -31,6 +32,11 @@ apps/ios/*.xcodeproj/ apps/ios/*.xcworkspace/ apps/ios/.swiftpm/ vendor/ +apps/ios/Clawdbot.xcodeproj/ +apps/ios/Clawdbot.xcodeproj/** +apps/macos/.build/** +**/*.bun-build +apps/ios/*.xcfilelist # Vendor build artifacts vendor/a2ui/renderers/lit/dist/ @@ -43,6 +49,8 @@ apps/ios/fastlane/Preview.html apps/ios/fastlane/screenshots/ apps/ios/fastlane/test_output/ apps/ios/fastlane/logs/ +apps/ios/fastlane/.env +apps/ios/fastlane/report.xml # fastlane build artifacts (local) apps/ios/*.ipa @@ -55,3 +63,9 @@ apps/ios/*.mobileprovision # Local untracked files .local/ .vscode/ +IDENTITY.md +USER.md +.tgz + +# local tooling +.serena/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 096e18c88..000000000 --- a/.gitmodules +++ /dev/null @@ -1,4 +0,0 @@ -[submodule "Peekaboo"] - path = Peekaboo - url = https://github.com/steipete/Peekaboo.git - branch = main diff --git a/.npmrc b/.npmrc index 4b549ab44..f0c783cb6 100644 --- a/.npmrc +++ b/.npmrc @@ -1 +1 @@ -allow-build-scripts=@whiskeysockets/baileys,sharp,esbuild,protobufjs,fs-ext,node-pty +allow-build-scripts=@whiskeysockets/baileys,sharp,esbuild,protobufjs,fs-ext,node-pty,@lydell/node-pty,@matrix-org/matrix-sdk-crypto-nodejs diff --git a/.oxlintrc.json b/.oxlintrc.json new file mode 100644 index 000000000..3876f8e04 --- /dev/null +++ b/.oxlintrc.json @@ -0,0 +1,12 @@ +{ + "$schema": "./node_modules/oxlint/configuration_schema.json", + "plugins": [ + "unicorn", + "typescript", + "oxc" + ], + "categories": { + "correctness": "error" + }, + "ignorePatterns": ["src/canvas-host/a2ui/a2ui.bundle.js"] +} diff --git a/.oxlintrc.jsonc b/.oxlintrc.jsonc deleted file mode 100644 index 115aa1a81..000000000 --- a/.oxlintrc.jsonc +++ /dev/null @@ -1,4 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/oxlintrc", - "extends": ["recommended"] -} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000..80813a0d3 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,105 @@ +# Pre-commit hooks for clawdbot +# Install: prek install +# Run manually: prek run --all-files +# +# See https://pre-commit.com for more information + +repos: + # Basic file hygiene + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + - id: trailing-whitespace + exclude: '^(docs/|dist/|vendor/|.*\.snap$)' + - id: end-of-file-fixer + exclude: '^(docs/|dist/|vendor/|.*\.snap$)' + - id: check-yaml + args: [--allow-multiple-documents] + - id: check-added-large-files + args: [--maxkb=500] + - id: check-merge-conflict + + # Secret detection (same as CI) + - repo: https://github.com/Yelp/detect-secrets + rev: v1.5.0 + hooks: + - id: detect-secrets + args: + - --baseline + - .secrets.baseline + - --exclude-files + - '(^|/)(dist/|vendor/|pnpm-lock\.yaml$|\.detect-secrets\.cfg$)' + - --exclude-lines + - 'key_content\.include\?\("BEGIN PRIVATE KEY"\)' + - --exclude-lines + - 'case \.apiKeyEnv: "API key \(env var\)"' + - --exclude-lines + - 'case apikey = "apiKey"' + - --exclude-lines + - '"gateway\.remote\.password"' + - --exclude-lines + - '"gateway\.auth\.password"' + - --exclude-lines + - '"talk\.apiKey"' + - --exclude-lines + - '=== "string"' + - --exclude-lines + - 'typeof remote\?\.password === "string"' + + # Shell script linting + - repo: https://github.com/koalaman/shellcheck-precommit + rev: v0.11.0 + hooks: + - id: shellcheck + args: [--severity=error] # Only fail on errors, not warnings/info + # Exclude vendor and scripts with embedded code or known issues + exclude: '^(vendor/|scripts/e2e/)' + + # GitHub Actions linting + - repo: https://github.com/rhysd/actionlint + rev: v1.7.10 + hooks: + - id: actionlint + + # GitHub Actions security audit + - repo: https://github.com/zizmorcore/zizmor-pre-commit + rev: v1.22.0 + hooks: + - id: zizmor + args: [--persona=regular, --min-severity=medium, --min-confidence=medium] + exclude: '^(vendor/|Swabble/)' + + # Project checks (same commands as CI) + - repo: local + hooks: + # oxlint --type-aware src test + - id: oxlint + name: oxlint + entry: scripts/pre-commit/run-node-tool.sh oxlint --type-aware src test + language: system + pass_filenames: false + types_or: [javascript, jsx, ts, tsx] + + # oxfmt --check src test + - id: oxfmt + name: oxfmt + entry: scripts/pre-commit/run-node-tool.sh oxfmt --check src test + language: system + pass_filenames: false + types_or: [javascript, jsx, ts, tsx] + + # swiftlint (same as CI) + - id: swiftlint + name: swiftlint + entry: swiftlint --config .swiftlint.yml + language: system + pass_filenames: false + types: [swift] + + # swiftformat --lint (same as CI) + - id: swiftformat + name: swiftformat + entry: swiftformat --lint apps/macos/Sources --config .swiftformat + language: system + pass_filenames: false + types: [swift] diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..6333f297c --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +src/canvas-host/a2ui/a2ui.bundle.js diff --git a/.secrets.baseline b/.secrets.baseline index 4c0ca50a4..826d5b4de 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -159,23 +159,23 @@ { "type": "Base64 High Entropy String", "filename": "appcast.xml", - "hashed_secret": "1b1c2b73eca84e441a823c37a06c71c9fadcfe24", + "hashed_secret": "4e5f0a148d9ef42afeb73b1c77643e2ef2dee0b9", "is_verified": false, - "line_number": 19 + "line_number": 90 }, { "type": "Base64 High Entropy String", "filename": "appcast.xml", - "hashed_secret": "5c47736fee5151b26b3bb61bb38955da0e8937c6", + "hashed_secret": "f1ccdaf78c308ec2cf608818da13f5f1e4809ed1", "is_verified": false, - "line_number": 35 + "line_number": 138 }, { "type": "Base64 High Entropy String", "filename": "appcast.xml", - "hashed_secret": "bbbca47179268f154c63affa0ca441c6e49e650f", + "hashed_secret": "2691dc9c9ded92ba62a2d8ee589e2d78e2aa0479", "is_verified": false, - "line_number": 52 + "line_number": 212 } ], "apps/macos/Tests/ClawdbotIPCTests/AnthropicAuthResolverTests.swift": [ @@ -194,13 +194,22 @@ "line_number": 42 } ], - "apps/macos/Tests/ClawdbotIPCTests/ConnectionsSettingsSmokeTests.swift": [ + "apps/macos/Tests/ClawdbotIPCTests/GatewayEndpointStoreTests.swift": [ { "type": "Secret Keyword", - "filename": "apps/macos/Tests/ClawdbotIPCTests/ConnectionsSettingsSmokeTests.swift", - "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "filename": "apps/macos/Tests/ClawdbotIPCTests/GatewayEndpointStoreTests.swift", + "hashed_secret": "19dad5cecb110281417d1db56b60e1b006d55bb4", "is_verified": false, - "line_number": 83 + "line_number": 61 + } + ], + "apps/macos/Tests/ClawdbotIPCTests/GatewayLaunchAgentManagerTests.swift": [ + { + "type": "Secret Keyword", + "filename": "apps/macos/Tests/ClawdbotIPCTests/GatewayLaunchAgentManagerTests.swift", + "hashed_secret": "1a91d62f7ca67399625a4368a6ab5d4a3baa6073", + "is_verified": false, + "line_number": 13 } ], "apps/macos/Tests/ClawdbotIPCTests/TailscaleIntegrationSectionTests.swift": [ @@ -212,109 +221,919 @@ "line_number": 27 } ], - "docs/configuration.md": [ + "apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayChannel.swift": [ { "type": "Secret Keyword", - "filename": "docs/configuration.md", - "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "filename": "apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayChannel.swift", + "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", "is_verified": false, - "line_number": 268 - }, + "line_number": 100 + } + ], + "docs/brave-search.md": [ { "type": "Secret Keyword", - "filename": "docs/configuration.md", - "hashed_secret": "1188d5a8ed7edcff5144a9472af960243eacf12e", + "filename": "docs/brave-search.md", + "hashed_secret": "491d458f895b9213facb2ee9375b1b044eaea3ac", "is_verified": false, - "line_number": 465 - }, + "line_number": 26 + } + ], + "docs/channels/bluebubbles.md": [ { "type": "Secret Keyword", - "filename": "docs/configuration.md", - "hashed_secret": "22af290a1a3d5e941193a41a3d3a9e4ca8da5e27", + "filename": "docs/channels/bluebubbles.md", + "hashed_secret": "555da20df20d4172e00f1b73d7c3943802055270", "is_verified": false, - "line_number": 718 - }, + "line_number": 32 + } + ], + "docs/channels/matrix.md": [ { "type": "Secret Keyword", - "filename": "docs/configuration.md", - "hashed_secret": "16c249e04e2be318050cb883c40137361c0c7209", - "is_verified": false, - "line_number": 760 - }, - { - "type": "Secret Keyword", - "filename": "docs/configuration.md", - "hashed_secret": "c1e6ee547fd492df1441ac492e8bb294974712bd", - "is_verified": false, - "line_number": 859 - }, - { - "type": "Secret Keyword", - "filename": "docs/configuration.md", + "filename": "docs/channels/matrix.md", "hashed_secret": "45d676e7c6ab44cf4b8fa366ef2d8fccd3e6d6e6", "is_verified": false, - "line_number": 982 + "line_number": 58 } ], - "docs/faq.md": [ + "docs/channels/nextcloud-talk.md": [ { "type": "Secret Keyword", - "filename": "docs/faq.md", - "hashed_secret": "a219d7693c25cd2d93313512e200ff3eb374d281", + "filename": "docs/channels/nextcloud-talk.md", + "hashed_secret": "76ed0a056aa77060de25754586440cff390791d0", "is_verified": false, - "line_number": 593 + "line_number": 47 + } + ], + "docs/channels/nostr.md": [ + { + "type": "Secret Keyword", + "filename": "docs/channels/nostr.md", + "hashed_secret": "edeb23e25a619c434d22bb7f1c3ca4841166b4e8", + "is_verified": false, + "line_number": 65 + } + ], + "docs/channels/slack.md": [ + { + "type": "Secret Keyword", + "filename": "docs/channels/slack.md", + "hashed_secret": "3f4800fb7c1fb79a9a48bfd562d90bc6b2e2b718", + "is_verified": false, + "line_number": 141 + } + ], + "docs/concepts/memory.md": [ + { + "type": "Secret Keyword", + "filename": "docs/concepts/memory.md", + "hashed_secret": "39d711243bfcee9fec8299b204e1aa9c3430fa12", + "is_verified": false, + "line_number": 108 }, { "type": "Secret Keyword", - "filename": "docs/faq.md", + "filename": "docs/concepts/memory.md", + "hashed_secret": "1a8abbf465c52363ab4c9c6ad945b8e857cbea55", + "is_verified": false, + "line_number": 131 + }, + { + "type": "Secret Keyword", + "filename": "docs/concepts/memory.md", + "hashed_secret": "b9f640d6095b9f6b5a65983f7b76dbbb254e0044", + "is_verified": false, + "line_number": 373 + } + ], + "docs/concepts/model-providers.md": [ + { + "type": "Secret Keyword", + "filename": "docs/concepts/model-providers.md", "hashed_secret": "ec3810e10fb78db55ce38b9c18d1c3eb1db739e0", "is_verified": false, - "line_number": 650 - } - ], - "docs/skills-config.md": [ + "line_number": 168 + }, { "type": "Secret Keyword", - "filename": "docs/skills-config.md", + "filename": "docs/concepts/model-providers.md", + "hashed_secret": "ef83ad68b9b66e008727b7c417c6a8f618b5177e", + "is_verified": false, + "line_number": 255 + } + ], + "docs/environment.md": [ + { + "type": "Secret Keyword", + "filename": "docs/environment.md", + "hashed_secret": "a219d7693c25cd2d93313512e200ff3eb374d281", + "is_verified": false, + "line_number": 29 + }, + { + "type": "Secret Keyword", + "filename": "docs/environment.md", + "hashed_secret": "b6f56e5e92078ed7c078c46fbfeedcbe5719bc25", + "is_verified": false, + "line_number": 31 + } + ], + "docs/gateway/configuration-examples.md": [ + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration-examples.md", + "hashed_secret": "a219d7693c25cd2d93313512e200ff3eb374d281", + "is_verified": false, + "line_number": 53 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration-examples.md", + "hashed_secret": "b6f56e5e92078ed7c078c46fbfeedcbe5719bc25", + "is_verified": false, + "line_number": 55 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration-examples.md", + "hashed_secret": "22af290a1a3d5e941193a41a3d3a9e4ca8da5e27", + "is_verified": false, + "line_number": 319 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration-examples.md", "hashed_secret": "c1e6ee547fd492df1441ac492e8bb294974712bd", "is_verified": false, - "line_number": 28 - } - ], - "docs/skills.md": [ + "line_number": 414 + }, { "type": "Secret Keyword", - "filename": "docs/skills.md", + "filename": "docs/gateway/configuration-examples.md", + "hashed_secret": "16c249e04e2be318050cb883c40137361c0c7209", + "is_verified": false, + "line_number": 548 + } + ], + "docs/gateway/configuration.md": [ + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration.md", + "hashed_secret": "a219d7693c25cd2d93313512e200ff3eb374d281", + "is_verified": false, + "line_number": 272 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration.md", + "hashed_secret": "b6f56e5e92078ed7c078c46fbfeedcbe5719bc25", + "is_verified": false, + "line_number": 274 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration.md", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 1029 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration.md", + "hashed_secret": "1188d5a8ed7edcff5144a9472af960243eacf12e", + "is_verified": false, + "line_number": 1470 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration.md", + "hashed_secret": "bde4db9b4c3be4049adc3b9a69851d7c35119770", + "is_verified": false, + "line_number": 1486 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration.md", + "hashed_secret": "22af290a1a3d5e941193a41a3d3a9e4ca8da5e27", + "is_verified": false, + "line_number": 2268 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration.md", + "hashed_secret": "ec3810e10fb78db55ce38b9c18d1c3eb1db739e0", + "is_verified": false, + "line_number": 2344 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/configuration.md", "hashed_secret": "c1e6ee547fd492df1441ac492e8bb294974712bd", "is_verified": false, - "line_number": 97 - } - ], - "docs/tailscale.md": [ + "line_number": 2658 + }, { "type": "Secret Keyword", - "filename": "docs/tailscale.md", + "filename": "docs/gateway/configuration.md", + "hashed_secret": "45d676e7c6ab44cf4b8fa366ef2d8fccd3e6d6e6", + "is_verified": false, + "line_number": 2844 + } + ], + "docs/gateway/local-models.md": [ + { + "type": "Secret Keyword", + "filename": "docs/gateway/local-models.md", + "hashed_secret": "16c249e04e2be318050cb883c40137361c0c7209", + "is_verified": false, + "line_number": 32 + }, + { + "type": "Secret Keyword", + "filename": "docs/gateway/local-models.md", + "hashed_secret": "49fd535e63175a827aab3eff9ac58a9e82460ac9", + "is_verified": false, + "line_number": 121 + } + ], + "docs/gateway/tailscale.md": [ + { + "type": "Secret Keyword", + "filename": "docs/gateway/tailscale.md", "hashed_secret": "9cb0dc5383312aa15b9dc6745645bde18ff5ade9", "is_verified": false, - "line_number": 52 + "line_number": 75 } ], - "docs/talk.md": [ + "docs/help/faq.md": [ { "type": "Secret Keyword", - "filename": "docs/talk.md", + "filename": "docs/help/faq.md", + "hashed_secret": "491d458f895b9213facb2ee9375b1b044eaea3ac", + "is_verified": false, + "line_number": 925 + }, + { + "type": "Secret Keyword", + "filename": "docs/help/faq.md", + "hashed_secret": "a219d7693c25cd2d93313512e200ff3eb374d281", + "is_verified": false, + "line_number": 1113 + }, + { + "type": "Secret Keyword", + "filename": "docs/help/faq.md", + "hashed_secret": "b6f56e5e92078ed7c078c46fbfeedcbe5719bc25", + "is_verified": false, + "line_number": 1114 + }, + { + "type": "Secret Keyword", + "filename": "docs/help/faq.md", + "hashed_secret": "ec3810e10fb78db55ce38b9c18d1c3eb1db739e0", + "is_verified": false, + "line_number": 1439 + }, + { + "type": "Secret Keyword", + "filename": "docs/help/faq.md", + "hashed_secret": "45d676e7c6ab44cf4b8fa366ef2d8fccd3e6d6e6", + "is_verified": false, + "line_number": 1715 + } + ], + "docs/nodes/talk.md": [ + { + "type": "Secret Keyword", + "filename": "docs/nodes/talk.md", "hashed_secret": "1188d5a8ed7edcff5144a9472af960243eacf12e", "is_verified": false, "line_number": 50 } ], - "docs/telegram.md": [ + "docs/perplexity.md": [ { "type": "Secret Keyword", - "filename": "docs/telegram.md", - "hashed_secret": "e9fe51f94eadabf54dbf2fbbd57188b9abee436e", + "filename": "docs/perplexity.md", + "hashed_secret": "6b26c117c66a0c030e239eef595c1e18865132a8", "is_verified": false, - "line_number": 57 + "line_number": 35 + } + ], + "docs/providers/anthropic.md": [ + { + "type": "Secret Keyword", + "filename": "docs/providers/anthropic.md", + "hashed_secret": "c7a8c334eef5d1749fface7d42c66f9ae5e8cf36", + "is_verified": false, + "line_number": 32 + } + ], + "docs/providers/glm.md": [ + { + "type": "Secret Keyword", + "filename": "docs/providers/glm.md", + "hashed_secret": "ec3810e10fb78db55ce38b9c18d1c3eb1db739e0", + "is_verified": false, + "line_number": 22 + } + ], + "docs/providers/minimax.md": [ + { + "type": "Secret Keyword", + "filename": "docs/providers/minimax.md", + "hashed_secret": "ec3810e10fb78db55ce38b9c18d1c3eb1db739e0", + "is_verified": false, + "line_number": 49 + }, + { + "type": "Secret Keyword", + "filename": "docs/providers/minimax.md", + "hashed_secret": "16c249e04e2be318050cb883c40137361c0c7209", + "is_verified": false, + "line_number": 118 + } + ], + "docs/providers/moonshot.md": [ + { + "type": "Secret Keyword", + "filename": "docs/providers/moonshot.md", + "hashed_secret": "ec3810e10fb78db55ce38b9c18d1c3eb1db739e0", + "is_verified": false, + "line_number": 39 + } + ], + "docs/providers/openai.md": [ + { + "type": "Secret Keyword", + "filename": "docs/providers/openai.md", + "hashed_secret": "ec3810e10fb78db55ce38b9c18d1c3eb1db739e0", + "is_verified": false, + "line_number": 31 + } + ], + "docs/providers/opencode.md": [ + { + "type": "Secret Keyword", + "filename": "docs/providers/opencode.md", + "hashed_secret": "ec3810e10fb78db55ce38b9c18d1c3eb1db739e0", + "is_verified": false, + "line_number": 25 + } + ], + "docs/providers/openrouter.md": [ + { + "type": "Secret Keyword", + "filename": "docs/providers/openrouter.md", + "hashed_secret": "a219d7693c25cd2d93313512e200ff3eb374d281", + "is_verified": false, + "line_number": 22 + } + ], + "docs/providers/synthetic.md": [ + { + "type": "Secret Keyword", + "filename": "docs/providers/synthetic.md", + "hashed_secret": "ec3810e10fb78db55ce38b9c18d1c3eb1db739e0", + "is_verified": false, + "line_number": 31 + } + ], + "docs/providers/zai.md": [ + { + "type": "Secret Keyword", + "filename": "docs/providers/zai.md", + "hashed_secret": "ec3810e10fb78db55ce38b9c18d1c3eb1db739e0", + "is_verified": false, + "line_number": 25 + } + ], + "docs/tools/browser.md": [ + { + "type": "Basic Auth Credentials", + "filename": "docs/tools/browser.md", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_verified": false, + "line_number": 163 + } + ], + "docs/tools/firecrawl.md": [ + { + "type": "Secret Keyword", + "filename": "docs/tools/firecrawl.md", + "hashed_secret": "674397e2c0c2faaa85961c708d2a96a7cc7af217", + "is_verified": false, + "line_number": 28 + } + ], + "docs/tools/skills-config.md": [ + { + "type": "Secret Keyword", + "filename": "docs/tools/skills-config.md", + "hashed_secret": "c1e6ee547fd492df1441ac492e8bb294974712bd", + "is_verified": false, + "line_number": 30 + } + ], + "docs/tools/skills.md": [ + { + "type": "Secret Keyword", + "filename": "docs/tools/skills.md", + "hashed_secret": "c1e6ee547fd492df1441ac492e8bb294974712bd", + "is_verified": false, + "line_number": 160 + } + ], + "docs/tools/web.md": [ + { + "type": "Secret Keyword", + "filename": "docs/tools/web.md", + "hashed_secret": "6b26c117c66a0c030e239eef595c1e18865132a8", + "is_verified": false, + "line_number": 61 + }, + { + "type": "Secret Keyword", + "filename": "docs/tools/web.md", + "hashed_secret": "96c682c88ed551f22fe76d206c2dfb7df9221ad9", + "is_verified": false, + "line_number": 112 + }, + { + "type": "Secret Keyword", + "filename": "docs/tools/web.md", + "hashed_secret": "491d458f895b9213facb2ee9375b1b044eaea3ac", + "is_verified": false, + "line_number": 160 + }, + { + "type": "Secret Keyword", + "filename": "docs/tools/web.md", + "hashed_secret": "674397e2c0c2faaa85961c708d2a96a7cc7af217", + "is_verified": false, + "line_number": 223 + } + ], + "docs/tts.md": [ + { + "type": "Secret Keyword", + "filename": "docs/tts.md", + "hashed_secret": "bde4db9b4c3be4049adc3b9a69851d7c35119770", + "is_verified": false, + "line_number": 72 + }, + { + "type": "Secret Keyword", + "filename": "docs/tts.md", + "hashed_secret": "1188d5a8ed7edcff5144a9472af960243eacf12e", + "is_verified": false, + "line_number": 77 + } + ], + "extensions/bluebubbles/src/actions.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/actions.test.ts", + "hashed_secret": "789cbe0407840b1c2041cb33452ff60f19bf58cc", + "is_verified": false, + "line_number": 73 + } + ], + "extensions/bluebubbles/src/attachments.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/attachments.test.ts", + "hashed_secret": "789cbe0407840b1c2041cb33452ff60f19bf58cc", + "is_verified": false, + "line_number": 35 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/attachments.test.ts", + "hashed_secret": "db1530e1ea43af094d3d75b8dbaf19a4a182a318", + "is_verified": false, + "line_number": 99 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/attachments.test.ts", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 117 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/attachments.test.ts", + "hashed_secret": "052f076c732648ab32d2fcde9fe255319bfa0c7b", + "is_verified": false, + "line_number": 229 + } + ], + "extensions/bluebubbles/src/chat.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/chat.test.ts", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 33 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/chat.test.ts", + "hashed_secret": "789cbe0407840b1c2041cb33452ff60f19bf58cc", + "is_verified": false, + "line_number": 68 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/chat.test.ts", + "hashed_secret": "5c5a15a8b0b3e154d77746945e563ba40100681b", + "is_verified": false, + "line_number": 85 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/chat.test.ts", + "hashed_secret": "faacad0ce4ea1c19b46e128fd79679d37d3d331d", + "is_verified": false, + "line_number": 134 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/chat.test.ts", + "hashed_secret": "4dcc26a1d99532846fedf1265df4f40f4e0005b8", + "is_verified": false, + "line_number": 219 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/chat.test.ts", + "hashed_secret": "fd2a721f7be1ee3d691a011affcdb11d0ca365a8", + "is_verified": false, + "line_number": 282 + } + ], + "extensions/bluebubbles/src/monitor.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/monitor.test.ts", + "hashed_secret": "789cbe0407840b1c2041cb33452ff60f19bf58cc", + "is_verified": false, + "line_number": 187 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/monitor.test.ts", + "hashed_secret": "1ae0af3fe72b3ba394f9fa95a6cffc090d726c23", + "is_verified": false, + "line_number": 394 + } + ], + "extensions/bluebubbles/src/reactions.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/reactions.test.ts", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 38 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/reactions.test.ts", + "hashed_secret": "789cbe0407840b1c2041cb33452ff60f19bf58cc", + "is_verified": false, + "line_number": 179 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/reactions.test.ts", + "hashed_secret": "a4a05c9a6449eb9d6cdac81dd7edc49230e327e6", + "is_verified": false, + "line_number": 210 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/reactions.test.ts", + "hashed_secret": "a2833da9f0a16f09994754d0a31749cecf8c8c77", + "is_verified": false, + "line_number": 316 + } + ], + "extensions/bluebubbles/src/send.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/send.test.ts", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 38 + }, + { + "type": "Secret Keyword", + "filename": "extensions/bluebubbles/src/send.test.ts", + "hashed_secret": "faacad0ce4ea1c19b46e128fd79679d37d3d331d", + "is_verified": false, + "line_number": 675 + } + ], + "extensions/bluebubbles/src/targets.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "extensions/bluebubbles/src/targets.test.ts", + "hashed_secret": "a3af2fb0c1e2a30bb038049e1e4b401593af6225", + "is_verified": false, + "line_number": 62 + } + ], + "extensions/bluebubbles/src/targets.ts": [ + { + "type": "Hex High Entropy String", + "filename": "extensions/bluebubbles/src/targets.ts", + "hashed_secret": "a3af2fb0c1e2a30bb038049e1e4b401593af6225", + "is_verified": false, + "line_number": 214 + } + ], + "extensions/copilot-proxy/index.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/copilot-proxy/index.ts", + "hashed_secret": "50f013532a9770a2c2cfdc38b7581dd01df69b70", + "is_verified": false, + "line_number": 4 + } + ], + "extensions/google-antigravity-auth/index.ts": [ + { + "type": "Base64 High Entropy String", + "filename": "extensions/google-antigravity-auth/index.ts", + "hashed_secret": "709d0f232b6ac4f8d24dec3e4fabfdb14257174f", + "is_verified": false, + "line_number": 9 + } + ], + "extensions/matrix/src/matrix/accounts.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/matrix/src/matrix/accounts.test.ts", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 75 + } + ], + "extensions/matrix/src/matrix/client.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/matrix/src/matrix/client.test.ts", + "hashed_secret": "fe7fcdaea49ece14677acd32374d2f1225819d5c", + "is_verified": false, + "line_number": 14 + }, + { + "type": "Secret Keyword", + "filename": "extensions/matrix/src/matrix/client.test.ts", + "hashed_secret": "3dc927d80543dc0f643940b70d066bd4b4c4b78e", + "is_verified": false, + "line_number": 24 + } + ], + "extensions/matrix/src/matrix/client/storage.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/matrix/src/matrix/client/storage.ts", + "hashed_secret": "7505d64a54e061b7acd54ccd58b49dc43500b635", + "is_verified": false, + "line_number": 9 + } + ], + "extensions/memory-lancedb/config.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/memory-lancedb/config.ts", + "hashed_secret": "ecb252044b5ea0f679ee78ec1a12904739e2904d", + "is_verified": false, + "line_number": 70 + } + ], + "extensions/memory-lancedb/index.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/memory-lancedb/index.test.ts", + "hashed_secret": "ed65c049bb2f78ee4f703b2158ba9cc6ea31fb7e", + "is_verified": false, + "line_number": 70 + } + ], + "extensions/msteams/src/probe.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/msteams/src/probe.test.ts", + "hashed_secret": "1a91d62f7ca67399625a4368a6ab5d4a3baa6073", + "is_verified": false, + "line_number": 34 + } + ], + "extensions/nextcloud-talk/src/accounts.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/nextcloud-talk/src/accounts.ts", + "hashed_secret": "920f8f5815b381ea692e9e7c2f7119f2b1aa620a", + "is_verified": false, + "line_number": 26 + }, + { + "type": "Secret Keyword", + "filename": "extensions/nextcloud-talk/src/accounts.ts", + "hashed_secret": "71f8e7976e4cbc4561c9d62fb283e7f788202acb", + "is_verified": false, + "line_number": 139 + } + ], + "extensions/nextcloud-talk/src/channel.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/nextcloud-talk/src/channel.ts", + "hashed_secret": "71f8e7976e4cbc4561c9d62fb283e7f788202acb", + "is_verified": false, + "line_number": 390 + } + ], + "extensions/nostr/README.md": [ + { + "type": "Secret Keyword", + "filename": "extensions/nostr/README.md", + "hashed_secret": "edeb23e25a619c434d22bb7f1c3ca4841166b4e8", + "is_verified": false, + "line_number": 43 + } + ], + "extensions/nostr/src/channel.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/channel.test.ts", + "hashed_secret": "ce4303f6b22257d9c9cf314ef1dee4707c6e1c13", + "is_verified": false, + "line_number": 48 + }, + { + "type": "Secret Keyword", + "filename": "extensions/nostr/src/channel.test.ts", + "hashed_secret": "ce4303f6b22257d9c9cf314ef1dee4707c6e1c13", + "is_verified": false, + "line_number": 48 + } + ], + "extensions/nostr/src/nostr-bus.fuzz.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/nostr-bus.fuzz.test.ts", + "hashed_secret": "2b4489606a23fb31fcdc849fa7e577ba90f6d39a", + "is_verified": false, + "line_number": 202 + }, + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/nostr-bus.fuzz.test.ts", + "hashed_secret": "ce4303f6b22257d9c9cf314ef1dee4707c6e1c13", + "is_verified": false, + "line_number": 203 + }, + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/nostr-bus.fuzz.test.ts", + "hashed_secret": "b84cb0c3925d34496e6c8b0e55b8c1664a438035", + "is_verified": false, + "line_number": 208 + } + ], + "extensions/nostr/src/nostr-bus.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/nostr-bus.test.ts", + "hashed_secret": "ce4303f6b22257d9c9cf314ef1dee4707c6e1c13", + "is_verified": false, + "line_number": 11 + }, + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/nostr-bus.test.ts", + "hashed_secret": "7258e28563f03fb4c5994e8402e6f610d1f0f110", + "is_verified": false, + "line_number": 33 + }, + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/nostr-bus.test.ts", + "hashed_secret": "2b4489606a23fb31fcdc849fa7e577ba90f6d39a", + "is_verified": false, + "line_number": 101 + }, + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/nostr-bus.test.ts", + "hashed_secret": "ef717286343f6da3f4e6f68c6de02a5148a801c4", + "is_verified": false, + "line_number": 106 + }, + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/nostr-bus.test.ts", + "hashed_secret": "98b35fe4c45011220f509ebb5546d3889b55a891", + "is_verified": false, + "line_number": 111 + } + ], + "extensions/nostr/src/nostr-profile.fuzz.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/nostr-profile.fuzz.test.ts", + "hashed_secret": "ce4303f6b22257d9c9cf314ef1dee4707c6e1c13", + "is_verified": false, + "line_number": 12 + } + ], + "extensions/nostr/src/nostr-profile.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/nostr-profile.test.ts", + "hashed_secret": "ce4303f6b22257d9c9cf314ef1dee4707c6e1c13", + "is_verified": false, + "line_number": 14 + } + ], + "extensions/nostr/src/types.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "extensions/nostr/src/types.test.ts", + "hashed_secret": "ce4303f6b22257d9c9cf314ef1dee4707c6e1c13", + "is_verified": false, + "line_number": 8 + }, + { + "type": "Secret Keyword", + "filename": "extensions/nostr/src/types.test.ts", + "hashed_secret": "ce4303f6b22257d9c9cf314ef1dee4707c6e1c13", + "is_verified": false, + "line_number": 8 + }, + { + "type": "Secret Keyword", + "filename": "extensions/nostr/src/types.test.ts", + "hashed_secret": "3bee216ebc256d692260fc3adc765050508fef5e", + "is_verified": false, + "line_number": 127 + } + ], + "extensions/open-prose/skills/prose/SKILL.md": [ + { + "type": "Basic Auth Credentials", + "filename": "extensions/open-prose/skills/prose/SKILL.md", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_verified": false, + "line_number": 200 + } + ], + "extensions/open-prose/skills/prose/state/postgres.md": [ + { + "type": "Secret Keyword", + "filename": "extensions/open-prose/skills/prose/state/postgres.md", + "hashed_secret": "fa9beb99e4029ad5a6615399e7bbae21356086b3", + "is_verified": false, + "line_number": 75 + }, + { + "type": "Basic Auth Credentials", + "filename": "extensions/open-prose/skills/prose/state/postgres.md", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_verified": false, + "line_number": 198 + } + ], + "extensions/zalo/README.md": [ + { + "type": "Secret Keyword", + "filename": "extensions/zalo/README.md", + "hashed_secret": "f51aaee16a4a756d287f126b99c081b73cba7f15", + "is_verified": false, + "line_number": 41 + } + ], + "extensions/zalo/src/monitor.webhook.test.ts": [ + { + "type": "Secret Keyword", + "filename": "extensions/zalo/src/monitor.webhook.test.ts", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 43 + } + ], + "skills/1password/references/cli-examples.md": [ + { + "type": "Secret Keyword", + "filename": "skills/1password/references/cli-examples.md", + "hashed_secret": "9dda0987cc3054773a2df97e352d4f64d233ef10", + "is_verified": false, + "line_number": 17 } ], "skills/local-places/SERVER_README.md": [ @@ -344,50 +1163,395 @@ "line_number": 18 } ], - "src/agents/models-config.test.ts": [ + "src/agents/memory-search.test.ts": [ { "type": "Secret Keyword", - "filename": "src/agents/models-config.test.ts", - "hashed_secret": "7cf31e8b6cda49f70c31f1f25af05d46f924142d", + "filename": "src/agents/memory-search.test.ts", + "hashed_secret": "a1b49d68a91fdf9c9217773f3fac988d77fa0f50", "is_verified": false, - "line_number": 25 - }, - { - "type": "Secret Keyword", - "filename": "src/agents/models-config.test.ts", - "hashed_secret": "3a81eb091f80c845232225be5663d270e90dacb7", - "is_verified": false, - "line_number": 90 + "line_number": 164 } ], - "src/agents/skills.test.ts": [ + "src/agents/model-auth.test.ts": [ { "type": "Secret Keyword", - "filename": "src/agents/skills.test.ts", - "hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f", + "filename": "src/agents/model-auth.test.ts", + "hashed_secret": "07a6b9cec637c806195e8aa7e5c0851ab03dc35e", "is_verified": false, - "line_number": 158 + "line_number": 211 }, { "type": "Secret Keyword", - "filename": "src/agents/skills.test.ts", - "hashed_secret": "7a85f4764bbd6daf1c3545efbbf0f279a6dc0beb", + "filename": "src/agents/model-auth.test.ts", + "hashed_secret": "21f296583ccd80c5ab9b3330a8b0d47e4a409fb9", "is_verified": false, - "line_number": 265 + "line_number": 240 }, { "type": "Secret Keyword", - "filename": "src/agents/skills.test.ts", + "filename": "src/agents/model-auth.test.ts", + "hashed_secret": "77e991e9f56e6fa4ed1a908208048421f1214c07", + "is_verified": false, + "line_number": 264 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/model-auth.test.ts", + "hashed_secret": "dff6d4ff5dc357cf451d1855ab9cbda562645c9f", + "is_verified": false, + "line_number": 295 + } + ], + "src/agents/model-auth.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/model-auth.ts", + "hashed_secret": "8956265d216d474a080edaa97880d37fc1386f33", + "is_verified": false, + "line_number": 22 + } + ], + "src/agents/models-config.auto-injects-github-copilot-provider-token-is.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.auto-injects-github-copilot-provider-token-is.test.ts", + "hashed_secret": "7cf31e8b6cda49f70c31f1f25af05d46f924142d", + "is_verified": false, + "line_number": 16 + } + ], + "src/agents/models-config.falls-back-default-baseurl-token-exchange-fails.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.falls-back-default-baseurl-token-exchange-fails.test.ts", + "hashed_secret": "7cf31e8b6cda49f70c31f1f25af05d46f924142d", + "is_verified": false, + "line_number": 16 + } + ], + "src/agents/models-config.fills-missing-provider-apikey-from-env-var.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.fills-missing-provider-apikey-from-env-var.test.ts", + "hashed_secret": "7cf31e8b6cda49f70c31f1f25af05d46f924142d", + "is_verified": false, + "line_number": 16 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.fills-missing-provider-apikey-from-env-var.test.ts", + "hashed_secret": "fcdd655b11f33ba4327695084a347b2ba192976c", + "is_verified": false, + "line_number": 50 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.fills-missing-provider-apikey-from-env-var.test.ts", + "hashed_secret": "3a81eb091f80c845232225be5663d270e90dacb7", + "is_verified": false, + "line_number": 108 + } + ], + "src/agents/models-config.normalizes-gemini-3-ids-preview-google-providers.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.normalizes-gemini-3-ids-preview-google-providers.test.ts", + "hashed_secret": "7cf31e8b6cda49f70c31f1f25af05d46f924142d", + "is_verified": false, + "line_number": 16 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.normalizes-gemini-3-ids-preview-google-providers.test.ts", + "hashed_secret": "980d02eb9335ae7c9e9984f6c8ad432352a0d2ac", + "is_verified": false, + "line_number": 57 + } + ], + "src/agents/models-config.skips-writing-models-json-no-env-token.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.skips-writing-models-json-no-env-token.test.ts", + "hashed_secret": "7cf31e8b6cda49f70c31f1f25af05d46f924142d", + "is_verified": false, + "line_number": 16 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.skips-writing-models-json-no-env-token.test.ts", + "hashed_secret": "fcdd655b11f33ba4327695084a347b2ba192976c", + "is_verified": false, + "line_number": 112 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.skips-writing-models-json-no-env-token.test.ts", + "hashed_secret": "94c4be5a1976115e8152960c21e04400a4fccdf6", + "is_verified": false, + "line_number": 146 + } + ], + "src/agents/models-config.uses-first-github-copilot-profile-env-tokens.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/models-config.uses-first-github-copilot-profile-env-tokens.test.ts", + "hashed_secret": "7cf31e8b6cda49f70c31f1f25af05d46f924142d", + "is_verified": false, + "line_number": 16 + } + ], + "src/agents/openai-responses.reasoning-replay.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/openai-responses.reasoning-replay.test.ts", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 124 + } + ], + "src/agents/pi-embedded-runner.applygoogleturnorderingfix.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/pi-embedded-runner.applygoogleturnorderingfix.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 58 + } + ], + "src/agents/pi-embedded-runner.buildembeddedsandboxinfo.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/pi-embedded-runner.buildembeddedsandboxinfo.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 57 + } + ], + "src/agents/pi-embedded-runner.createsystempromptoverride.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/pi-embedded-runner.createsystempromptoverride.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 56 + } + ], + "src/agents/pi-embedded-runner.get-dm-history-limit-from-session-key.falls-back-provider-default-per-dm-not.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/pi-embedded-runner.get-dm-history-limit-from-session-key.falls-back-provider-default-per-dm-not.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 56 + } + ], + "src/agents/pi-embedded-runner.get-dm-history-limit-from-session-key.returns-undefined-sessionkey-is-undefined.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/pi-embedded-runner.get-dm-history-limit-from-session-key.returns-undefined-sessionkey-is-undefined.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 56 + } + ], + "src/agents/pi-embedded-runner.limithistoryturns.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/pi-embedded-runner.limithistoryturns.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 57 + } + ], + "src/agents/pi-embedded-runner.resolvesessionagentids.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/pi-embedded-runner.resolvesessionagentids.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 56 + } + ], + "src/agents/pi-embedded-runner.splitsdktools.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/pi-embedded-runner.splitsdktools.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 57 + } + ], + "src/agents/pi-embedded-runner.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/pi-embedded-runner.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 117 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/pi-embedded-runner.test.ts", + "hashed_secret": "fcdd655b11f33ba4327695084a347b2ba192976c", + "is_verified": false, + "line_number": 178 + } + ], + "src/agents/skills.applyskillenvoverrides.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/skills.applyskillenvoverrides.test.ts", "hashed_secret": "5df3a673d724e8a1eb673a8baf623e183940804d", "is_verified": false, - "line_number": 462 + "line_number": 54 }, { "type": "Secret Keyword", - "filename": "src/agents/skills.test.ts", + "filename": "src/agents/skills.applyskillenvoverrides.test.ts", "hashed_secret": "8921daaa546693e52bc1f9c40bdcf15e816e0448", "is_verified": false, - "line_number": 490 + "line_number": 80 + } + ], + "src/agents/skills.build-workspace-skills-prompt.prefers-workspace-skills-managed-skills.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/skills.build-workspace-skills-prompt.prefers-workspace-skills-managed-skills.test.ts", + "hashed_secret": "7a85f4764bbd6daf1c3545efbbf0f279a6dc0beb", + "is_verified": false, + "line_number": 124 + } + ], + "src/agents/skills.build-workspace-skills-prompt.syncs-merged-skills-into-target-workspace.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/skills.build-workspace-skills-prompt.syncs-merged-skills-into-target-workspace.test.ts", + "hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f", + "is_verified": false, + "line_number": 102 + } + ], + "src/agents/tools/web-fetch.ssrf.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/tools/web-fetch.ssrf.test.ts", + "hashed_secret": "5ce8e9d54c77266fff990194d2219a708c59b76c", + "is_verified": false, + "line_number": 55 + } + ], + "src/agents/tools/web-search.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/tools/web-search.ts", + "hashed_secret": "dfba7aade0868074c2861c98e2a9a92f3178a51b", + "is_verified": false, + "line_number": 85 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/tools/web-search.ts", + "hashed_secret": "71f8e7976e4cbc4561c9d62fb283e7f788202acb", + "is_verified": false, + "line_number": 190 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/tools/web-search.ts", + "hashed_secret": "c4865ff9250aca23b0d98eb079dad70ebec1cced", + "is_verified": false, + "line_number": 198 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/tools/web-search.ts", + "hashed_secret": "527ee41f36386e85fa932ef09471ca017f3c95c8", + "is_verified": false, + "line_number": 199 + } + ], + "src/agents/tools/web-tools.enabled-defaults.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/tools/web-tools.enabled-defaults.test.ts", + "hashed_secret": "47b249a75ca78fdb578d0f28c33685e27ea82684", + "is_verified": false, + "line_number": 213 + }, + { + "type": "Secret Keyword", + "filename": "src/agents/tools/web-tools.enabled-defaults.test.ts", + "hashed_secret": "d0ffd81d6d7ad1bc3c365660fe8882480c9a986e", + "is_verified": false, + "line_number": 242 + } + ], + "src/agents/tools/web-tools.fetch.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/agents/tools/web-tools.fetch.test.ts", + "hashed_secret": "5ce8e9d54c77266fff990194d2219a708c59b76c", + "is_verified": false, + "line_number": 101 + } + ], + "src/auto-reply/reply.directive.directive-behavior.prefers-alias-matches-fuzzy-selection-is-ambiguous.e2e.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/auto-reply/reply.directive.directive-behavior.prefers-alias-matches-fuzzy-selection-is-ambiguous.e2e.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 90 + }, + { + "type": "Secret Keyword", + "filename": "src/auto-reply/reply.directive.directive-behavior.prefers-alias-matches-fuzzy-selection-is-ambiguous.e2e.test.ts", + "hashed_secret": "16c249e04e2be318050cb883c40137361c0c7209", + "is_verified": false, + "line_number": 96 + } + ], + "src/auto-reply/reply.directive.directive-behavior.supports-fuzzy-model-matches-model-directive.e2e.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/auto-reply/reply.directive.directive-behavior.supports-fuzzy-model-matches-model-directive.e2e.test.ts", + "hashed_secret": "e9a5f12a8ecbb3eb46eca5096b5c52aa5e7c9fdd", + "is_verified": false, + "line_number": 87 + }, + { + "type": "Secret Keyword", + "filename": "src/auto-reply/reply.directive.directive-behavior.supports-fuzzy-model-matches-model-directive.e2e.test.ts", + "hashed_secret": "16c249e04e2be318050cb883c40137361c0c7209", + "is_verified": false, + "line_number": 228 + } + ], + "src/auto-reply/status.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/auto-reply/status.test.ts", + "hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f", + "is_verified": false, + "line_number": 20 + } + ], + "src/browser/cdp.helpers.test.ts": [ + { + "type": "Basic Auth Credentials", + "filename": "src/browser/cdp.helpers.test.ts", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_verified": false, + "line_number": 22 + } + ], + "src/browser/cdp.test.ts": [ + { + "type": "Basic Auth Credentials", + "filename": "src/browser/cdp.test.ts", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_verified": false, + "line_number": 172 } ], "src/browser/target-id.test.ts": [ @@ -396,57 +1560,386 @@ "filename": "src/browser/target-id.test.ts", "hashed_secret": "4e126c049580d66ca1549fa534d95a7263f27f46", "is_verified": false, - "line_number": 16 + "line_number": 13 } ], - "src/commands/antigravity-oauth.ts": [ + "src/cli/update-cli.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "src/cli/update-cli.test.ts", + "hashed_secret": "e4f91dd323bac5bfc4f60a6e433787671dc2421d", + "is_verified": false, + "line_number": 112 + } + ], + "src/commands/auth-choice.preferred-provider.ts": [ + { + "type": "Secret Keyword", + "filename": "src/commands/auth-choice.preferred-provider.ts", + "hashed_secret": "c03a8d10174dd7eb2b3288b570a5a74fdd9ae05d", + "is_verified": false, + "line_number": 8 + } + ], + "src/commands/auth-choice.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/commands/auth-choice.test.ts", + "hashed_secret": "2480500ff391183070fe22ba8665a8be19350833", + "is_verified": false, + "line_number": 289 + }, + { + "type": "Secret Keyword", + "filename": "src/commands/auth-choice.test.ts", + "hashed_secret": "77e991e9f56e6fa4ed1a908208048421f1214c07", + "is_verified": false, + "line_number": 350 + }, + { + "type": "Secret Keyword", + "filename": "src/commands/auth-choice.test.ts", + "hashed_secret": "1b4d8423b11d32dd0c466428ac81de84a4a9442b", + "is_verified": false, + "line_number": 528 + } + ], + "src/commands/configure.gateway-auth.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/commands/configure.gateway-auth.test.ts", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 8 + } + ], + "src/commands/models/list.status.test.ts": [ { "type": "Base64 High Entropy String", - "filename": "src/commands/antigravity-oauth.ts", - "hashed_secret": "709d0f232b6ac4f8d24dec3e4fabfdb14257174f", + "filename": "src/commands/models/list.status.test.ts", + "hashed_secret": "d6ae2508a78a232d5378ef24b85ce40cbb4d7ff0", "is_verified": false, - "line_number": 17 + "line_number": 11 }, { "type": "Base64 High Entropy String", - "filename": "src/commands/antigravity-oauth.ts", - "hashed_secret": "3848603b8e866f62d07c206ff622279b9dcb0238", + "filename": "src/commands/models/list.status.test.ts", + "hashed_secret": "2d8012102440ea97852b3152239218f00579bafa", "is_verified": false, - "line_number": 20 - } - ], - "src/commands/onboard-auth.ts": [ + "line_number": 18 + }, + { + "type": "Base64 High Entropy String", + "filename": "src/commands/models/list.status.test.ts", + "hashed_secret": "51848e2be4b461a549218d3167f19c01be6b98b8", + "is_verified": false, + "line_number": 46 + }, { "type": "Secret Keyword", - "filename": "src/commands/onboard-auth.ts", + "filename": "src/commands/models/list.status.test.ts", + "hashed_secret": "51848e2be4b461a549218d3167f19c01be6b98b8", + "is_verified": false, + "line_number": 46 + }, + { + "type": "Secret Keyword", + "filename": "src/commands/models/list.status.test.ts", + "hashed_secret": "1c1e381bfb72d3b7bfca9437053d9875356680f0", + "is_verified": false, + "line_number": 52 + } + ], + "src/commands/onboard-auth.config-minimax.ts": [ + { + "type": "Secret Keyword", + "filename": "src/commands/onboard-auth.config-minimax.ts", "hashed_secret": "16c249e04e2be318050cb883c40137361c0c7209", "is_verified": false, + "line_number": 30 + }, + { + "type": "Secret Keyword", + "filename": "src/commands/onboard-auth.config-minimax.ts", + "hashed_secret": "ddcb713196b974770575a9bea5a4e7d46361f8e9", + "is_verified": false, + "line_number": 85 + } + ], + "src/commands/onboard-auth.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/commands/onboard-auth.test.ts", + "hashed_secret": "666c100dab549a6f56da7da546bd848ed5086541", + "is_verified": false, + "line_number": 230 + }, + { + "type": "Secret Keyword", + "filename": "src/commands/onboard-auth.test.ts", + "hashed_secret": "e184b402822abc549b37689c84e8e0e33c39a1f1", + "is_verified": false, + "line_number": 262 + } + ], + "src/commands/onboard-non-interactive.ai-gateway.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/commands/onboard-non-interactive.ai-gateway.test.ts", + "hashed_secret": "77e991e9f56e6fa4ed1a908208048421f1214c07", + "is_verified": false, "line_number": 50 } ], - "src/config/config.test.ts": [ + "src/commands/onboard-non-interactive/api-keys.ts": [ { "type": "Secret Keyword", - "filename": "src/config/config.test.ts", - "hashed_secret": "bea2f7b64fab8d1d414d0449530b1e088d36d5b1", + "filename": "src/commands/onboard-non-interactive/api-keys.ts", + "hashed_secret": "112f3a99b283a4e1788dedd8e0e5d35375c33747", "is_verified": false, - "line_number": 520 + "line_number": 10 } ], - "src/gateway/server.auth.test.ts": [ + "src/config/config.env-vars.test.ts": [ { "type": "Secret Keyword", - "filename": "src/gateway/server.auth.test.ts", - "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "filename": "src/config/config.env-vars.test.ts", + "hashed_secret": "a24ef9c1a27cac44823571ceef2e8262718eee36", "is_verified": false, - "line_number": 89 + "line_number": 15 }, { "type": "Secret Keyword", - "filename": "src/gateway/server.auth.test.ts", + "filename": "src/config/config.env-vars.test.ts", + "hashed_secret": "29d5f92e9ee44d4854d6dfaeefc3dc27d779fdf3", + "is_verified": false, + "line_number": 47 + }, + { + "type": "Secret Keyword", + "filename": "src/config/config.env-vars.test.ts", + "hashed_secret": "1672b6a1e7956c6a70f45d699aa42a351b1f8b80", + "is_verified": false, + "line_number": 63 + } + ], + "src/config/config.talk-api-key-fallback.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/config/config.talk-api-key-fallback.test.ts", + "hashed_secret": "bea2f7b64fab8d1d414d0449530b1e088d36d5b1", + "is_verified": false, + "line_number": 42 + } + ], + "src/config/config.web-search-provider.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/config/config.web-search-provider.test.ts", + "hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f", + "is_verified": false, + "line_number": 14 + } + ], + "src/config/env-substitution.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/config/env-substitution.test.ts", + "hashed_secret": "f2b14f68eb995facb3a1c35287b778d5bd785511", + "is_verified": false, + "line_number": 38 + }, + { + "type": "Secret Keyword", + "filename": "src/config/env-substitution.test.ts", + "hashed_secret": "ec417f567082612f8fd6afafe1abcab831fca840", + "is_verified": false, + "line_number": 69 + }, + { + "type": "Secret Keyword", + "filename": "src/config/env-substitution.test.ts", + "hashed_secret": "520bd69c3eb1646d9a78181ecb4c90c51fdf428d", + "is_verified": false, + "line_number": 70 + }, + { + "type": "Secret Keyword", + "filename": "src/config/env-substitution.test.ts", + "hashed_secret": "f136444bf9b3d01a9f9b772b80ac6bf7b6a43ef0", + "is_verified": false, + "line_number": 228 + } + ], + "src/config/schema.ts": [ + { + "type": "Secret Keyword", + "filename": "src/config/schema.ts", + "hashed_secret": "e73c9fcad85cd4eecc74181ec4bdb31064d68439", + "is_verified": false, + "line_number": 184 + }, + { + "type": "Secret Keyword", + "filename": "src/config/schema.ts", + "hashed_secret": "2eda7cd978f39eebec3bf03e4410a40e14167fff", + "is_verified": false, + "line_number": 220 + }, + { + "type": "Secret Keyword", + "filename": "src/config/schema.ts", + "hashed_secret": "9f4cda226d3868676ac7f86f59e4190eb94bd208", + "is_verified": false, + "line_number": 418 + }, + { + "type": "Secret Keyword", + "filename": "src/config/schema.ts", + "hashed_secret": "01822c8bbf6a8b136944b14182cb885100ec2eae", + "is_verified": false, + "line_number": 437 + }, + { + "type": "Secret Keyword", + "filename": "src/config/schema.ts", + "hashed_secret": "bb7dfd9746e660e4a4374951ec5938ef0e343255", + "is_verified": false, + "line_number": 487 + } + ], + "src/config/slack-http-config.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/config/slack-http-config.test.ts", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 11 + } + ], + "src/gateway/auth.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/gateway/auth.test.ts", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 43 + }, + { + "type": "Secret Keyword", + "filename": "src/gateway/auth.test.ts", "hashed_secret": "a4b48a81cdab1e1a5dd37907d6c85ca1c61ddc7c", "is_verified": false, - "line_number": 109 + "line_number": 51 + } + ], + "src/gateway/call.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/gateway/call.test.ts", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 285 + }, + { + "type": "Secret Keyword", + "filename": "src/gateway/call.test.ts", + "hashed_secret": "e493f561d90c6638c1f51c5a8a069c3b129b79ed", + "is_verified": false, + "line_number": 295 + }, + { + "type": "Secret Keyword", + "filename": "src/gateway/call.test.ts", + "hashed_secret": "2e07956ffc9bc4fd624064c40b7495c85d5f1467", + "is_verified": false, + "line_number": 300 + }, + { + "type": "Secret Keyword", + "filename": "src/gateway/call.test.ts", + "hashed_secret": "bddc29032de580fb53b3a9a0357dd409086db800", + "is_verified": false, + "line_number": 313 + } + ], + "src/gateway/client.test.ts": [ + { + "type": "Private Key", + "filename": "src/gateway/client.test.ts", + "hashed_secret": "1348b145fa1a555461c1b790a2f66614781091e9", + "is_verified": false, + "line_number": 83 + } + ], + "src/gateway/gateway-cli-backend.live.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "src/gateway/gateway-cli-backend.live.test.ts", + "hashed_secret": "3e2fd4a90d5afbd27974730c4d6a9592fe300825", + "is_verified": false, + "line_number": 38 + } + ], + "src/gateway/gateway-models.profiles.live.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "src/gateway/gateway-models.profiles.live.test.ts", + "hashed_secret": "3e2fd4a90d5afbd27974730c4d6a9592fe300825", + "is_verified": false, + "line_number": 219 + } + ], + "src/gateway/gateway.e2e.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/gateway/gateway.e2e.test.ts", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 73 + } + ], + "src/gateway/server.auth.e2e.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/gateway/server.auth.e2e.test.ts", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 179 + }, + { + "type": "Secret Keyword", + "filename": "src/gateway/server.auth.e2e.test.ts", + "hashed_secret": "a4b48a81cdab1e1a5dd37907d6c85ca1c61ddc7c", + "is_verified": false, + "line_number": 197 + } + ], + "src/gateway/session-utils.test.ts": [ + { + "type": "Base64 High Entropy String", + "filename": "src/gateway/session-utils.test.ts", + "hashed_secret": "bb9a5d9483409d2c60b28268a0efcb93324d4cda", + "is_verified": false, + "line_number": 156 + } + ], + "src/gateway/tools-invoke-http.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/gateway/tools-invoke-http.test.ts", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 56 + } + ], + "src/gateway/ws-log.test.ts": [ + { + "type": "Base64 High Entropy String", + "filename": "src/gateway/ws-log.test.ts", + "hashed_secret": "edd2e7ac4f61d0c606e80a0919d727540842a307", + "is_verified": false, + "line_number": 22 } ], "src/infra/env.test.ts": [ @@ -465,34 +1958,214 @@ "line_number": 25 } ], + "src/infra/outbound/message-action-runner.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "src/infra/outbound/message-action-runner.test.ts", + "hashed_secret": "804ec071803318791b835cffd6e509c8d32239db", + "is_verified": false, + "line_number": 88 + }, + { + "type": "Secret Keyword", + "filename": "src/infra/outbound/message-action-runner.test.ts", + "hashed_secret": "789cbe0407840b1c2041cb33452ff60f19bf58cc", + "is_verified": false, + "line_number": 385 + } + ], + "src/infra/outbound/outbound-policy.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "src/infra/outbound/outbound-policy.test.ts", + "hashed_secret": "804ec071803318791b835cffd6e509c8d32239db", + "is_verified": false, + "line_number": 33 + } + ], "src/infra/shell-env.test.ts": [ { "type": "Secret Keyword", "filename": "src/infra/shell-env.test.ts", "hashed_secret": "65c10dc3549fe07424148a8a4790a3341ecbc253", "is_verified": false, - "line_number": 35 - }, - { - "type": "Base64 High Entropy String", - "filename": "src/infra/shell-env.test.ts", - "hashed_secret": "64db6bf7f0e5a0491df4419f0eb1bbcc402989e8", - "is_verified": false, - "line_number": 56 + "line_number": 27 }, { "type": "Secret Keyword", "filename": "src/infra/shell-env.test.ts", "hashed_secret": "e013ffda590d2178607c16d11b1ea42f75ceb0e7", "is_verified": false, - "line_number": 73 + "line_number": 59 }, { "type": "Base64 High Entropy String", "filename": "src/infra/shell-env.test.ts", "hashed_secret": "be6ee9a6bf9f2dad84a5a67d6c0576a5bacc391e", "is_verified": false, - "line_number": 75 + "line_number": 61 + } + ], + "src/logging/redact.test.ts": [ + { + "type": "Base64 High Entropy String", + "filename": "src/logging/redact.test.ts", + "hashed_secret": "dd7754662b89333191ff45e8257a3e6d3fcd3990", + "is_verified": false, + "line_number": 9 + }, + { + "type": "Private Key", + "filename": "src/logging/redact.test.ts", + "hashed_secret": "1348b145fa1a555461c1b790a2f66614781091e9", + "is_verified": false, + "line_number": 64 + }, + { + "type": "Hex High Entropy String", + "filename": "src/logging/redact.test.ts", + "hashed_secret": "7992945213f7d76889fa83ff0f2be352409c837e", + "is_verified": false, + "line_number": 65 + }, + { + "type": "Base64 High Entropy String", + "filename": "src/logging/redact.test.ts", + "hashed_secret": "063995ecb4fa5afe2460397d322925cd867b7d74", + "is_verified": false, + "line_number": 79 + } + ], + "src/media-understanding/apply.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/media-understanding/apply.test.ts", + "hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f", + "is_verified": false, + "line_number": 14 + } + ], + "src/media-understanding/providers/deepgram/audio.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/media-understanding/providers/deepgram/audio.test.ts", + "hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f", + "is_verified": false, + "line_number": 31 + } + ], + "src/media-understanding/providers/google/video.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/media-understanding/providers/google/video.test.ts", + "hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f", + "is_verified": false, + "line_number": 28 + } + ], + "src/media-understanding/providers/openai/audio.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/media-understanding/providers/openai/audio.test.ts", + "hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f", + "is_verified": false, + "line_number": 26 + } + ], + "src/media-understanding/runner.auto-audio.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/media-understanding/runner.auto-audio.test.ts", + "hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f", + "is_verified": false, + "line_number": 42 + } + ], + "src/media-understanding/runner.deepgram.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/media-understanding/runner.deepgram.test.ts", + "hashed_secret": "3acfb2c2b433c0ea7ff107e33df91b18e52f960f", + "is_verified": false, + "line_number": 46 + } + ], + "src/memory/embeddings.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/memory/embeddings.test.ts", + "hashed_secret": "a47110e348a3063541fb1f1f640d635d457181a0", + "is_verified": false, + "line_number": 32 + }, + { + "type": "Secret Keyword", + "filename": "src/memory/embeddings.test.ts", + "hashed_secret": "c734e47630dda71619c696d88381f06f7511bd78", + "is_verified": false, + "line_number": 149 + }, + { + "type": "Secret Keyword", + "filename": "src/memory/embeddings.test.ts", + "hashed_secret": "56e1d57b8db262b08bc73c60ed08d8c92e59503f", + "is_verified": false, + "line_number": 179 + } + ], + "src/pairing/pairing-store.ts": [ + { + "type": "Base64 High Entropy String", + "filename": "src/pairing/pairing-store.ts", + "hashed_secret": "f8c6f1ff98c5ee78c27d34a3ca68f35ad79847af", + "is_verified": false, + "line_number": 12 + } + ], + "src/security/audit.test.ts": [ + { + "type": "Hex High Entropy String", + "filename": "src/security/audit.test.ts", + "hashed_secret": "b1775a785f09a6ebaf2dc33d6eaeb98974d9cdb8", + "is_verified": false, + "line_number": 180 + }, + { + "type": "Hex High Entropy String", + "filename": "src/security/audit.test.ts", + "hashed_secret": "fa8da98a5bdb77b4902cbb4338e6e94ea825300e", + "is_verified": false, + "line_number": 209 + }, + { + "type": "Secret Keyword", + "filename": "src/security/audit.test.ts", + "hashed_secret": "21f688ab56f76a99e5c6ed342291422f4e57e47f", + "is_verified": false, + "line_number": 1046 + }, + { + "type": "Secret Keyword", + "filename": "src/security/audit.test.ts", + "hashed_secret": "3dc927d80543dc0f643940b70d066bd4b4c4b78e", + "is_verified": false, + "line_number": 1077 + } + ], + "src/tts/tts.test.ts": [ + { + "type": "Secret Keyword", + "filename": "src/tts/tts.test.ts", + "hashed_secret": "2e7a7ee14caebf378fc32d6cf6f557f347c96773", + "is_verified": false, + "line_number": 33 + }, + { + "type": "Hex High Entropy String", + "filename": "src/tts/tts.test.ts", + "hashed_secret": "b214f706bb602c1cc2adc5c6165e73622305f4bb", + "is_verified": false, + "line_number": 68 } ], "src/web/qr-image.test.ts": [ @@ -504,15 +2177,15 @@ "line_number": 12 } ], - "vendor/a2ui/README.md": [ + "test/provider-timeout.e2e.test.ts": [ { "type": "Secret Keyword", - "filename": "vendor/a2ui/README.md", - "hashed_secret": "2619a5397a5d054dab3fe24e6a8da1fbd76ec3a6", + "filename": "test/provider-timeout.e2e.test.ts", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", "is_verified": false, - "line_number": 123 + "line_number": 182 } ] }, - "generated_at": "2026-01-05T13:01:00Z" + "generated_at": "2026-01-25T10:55:04Z" } diff --git a/.shellcheckrc b/.shellcheckrc new file mode 100644 index 000000000..515f25a5f --- /dev/null +++ b/.shellcheckrc @@ -0,0 +1,25 @@ +# ShellCheck configuration +# https://www.shellcheck.net/wiki/ + +# Disable common false positives and style suggestions + +# SC2034: Variable appears unused (often exported or used indirectly) +disable=SC2034 + +# SC2155: Declare and assign separately (common idiom, rarely causes issues) +disable=SC2155 + +# SC2295: Expansions inside ${..} need quoting (info-level, rarely causes issues) +disable=SC2295 + +# SC1012: \r is literal (tr -d '\r' works as intended on most systems) +disable=SC1012 + +# SC2026: Word outside quotes (info-level, often intentional) +disable=SC2026 + +# SC2016: Expressions don't expand in single quotes (often intentional in sed/awk) +disable=SC2016 + +# SC2129: Consider using { cmd1; cmd2; } >> file (style preference) +disable=SC2129 diff --git a/.swiftformat b/.swiftformat index e0d3bc8b6..6622d0b01 100644 --- a/.swiftformat +++ b/.swiftformat @@ -23,7 +23,7 @@ # Whitespace --trimwhitespace always --emptybraces no-space ---nospaceoperators ...,..< +--nospaceoperators ...,..< --ranges no-space --someAny true --voidtype void diff --git a/AGENTS.md b/AGENTS.md index 64727e1e0..ac85a00d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,30 +1,49 @@ # Repository Guidelines - Repo: https://github.com/clawdbot/clawdbot -- GitHub issues: use literal multiline strings or $'...' for newlines; avoid "\\n" escapes in `gh issue create/edit`. +- GitHub issues/comments/PR comments: use literal multiline strings or `-F - <<'EOF'` (or $'...') for real newlines; never embed "\\n". ## Project Structure & Module Organization - Source code: `src/` (CLI wiring in `src/cli`, commands in `src/commands`, web provider in `src/provider-web.ts`, infra in `src/infra`, media pipeline in `src/media`). - Tests: colocated `*.test.ts`. - Docs: `docs/` (images, queue, Pi config). Built output lives in `dist/`. - Plugins/extensions: live under `extensions/*` (workspace packages). Keep plugin-only deps in the extension `package.json`; do not add them to the root `package.json` unless core uses them. +- Plugins: install runs `npm install --omit=dev` in plugin dir; runtime deps must live in `dependencies`. Avoid `workspace:*` in `dependencies` (npm install breaks); put `clawdbot` in `devDependencies` or `peerDependencies` instead (runtime resolves `clawdbot/plugin-sdk` via jiti alias). - Installers served from `https://clawd.bot/*`: live in the sibling repo `../clawd.bot` (`public/install.sh`, `public/install-cli.sh`, `public/install.ps1`). +- Messaging channels: always consider **all** built-in + extension channels when refactoring shared logic (routing, allowlists, pairing, command gating, onboarding, docs). + - Core channel docs: `docs/channels/` + - Core channel code: `src/telegram`, `src/discord`, `src/slack`, `src/signal`, `src/imessage`, `src/web` (WhatsApp web), `src/channels`, `src/routing` + - Extensions (channel plugins): `extensions/*` (e.g. `extensions/msteams`, `extensions/matrix`, `extensions/zalo`, `extensions/zalouser`, `extensions/voice-call`) +- When adding channels/extensions/apps/docs, review `.github/labeler.yml` for label coverage. ## Docs Linking (Mintlify) - Docs are hosted on Mintlify (docs.clawd.bot). - Internal doc links in `docs/**/*.md`: root-relative, no `.md`/`.mdx` (example: `[Config](/configuration)`). - Section cross-references: use anchors on root-relative paths (example: `[Hooks](/configuration#hooks)`). +- Doc headings and anchors: avoid em dashes and apostrophes in headings because they break Mintlify anchor links. - When Peter asks for links, reply with full `https://docs.clawd.bot/...` URLs (not root-relative). - When you touch docs, end the reply with the `https://docs.clawd.bot/...` URLs you referenced. - README (GitHub): keep absolute docs URLs (`https://docs.clawd.bot/...`) so links work on GitHub. - Docs content must be generic: no personal device names/hostnames/paths; use placeholders like `user@gateway-host` and “gateway host”. +## exe.dev VM ops (general) +- Access: stable path is `ssh exe.dev` then `ssh vm-name` (assume SSH key already set). +- SSH flaky: use exe.dev web terminal or Shelley (web agent); keep a tmux session for long ops. +- Update: `sudo npm i -g clawdbot@latest` (global install needs root on `/usr/lib/node_modules`). +- Config: use `clawdbot config set ...`; ensure `gateway.mode=local` is set. +- Discord: store raw token only (no `DISCORD_BOT_TOKEN=` prefix). +- Restart: stop old gateway and run: + `pkill -9 -f clawdbot-gateway || true; nohup clawdbot gateway run --bind loopback --port 18789 --force > /tmp/clawdbot-gateway.log 2>&1 &` +- Verify: `clawdbot channels status --probe`, `ss -ltnp | rg 18789`, `tail -n 120 /tmp/clawdbot-gateway.log`. + ## Build, Test, and Development Commands - Runtime baseline: Node **22+** (keep Node + Bun paths working). - Install deps: `pnpm install` +- Pre-commit hooks: `prek install` (runs same checks as CI) - Also supported: `bun install` (keep `pnpm-lock.yaml` + Bun patching in sync when touching deps/patches). - Prefer Bun for TypeScript execution (scripts, dev, tests): `bun ` / `bunx `. - Run CLI in dev: `pnpm clawdbot ...` (bun) or `pnpm dev`. - Node remains supported for running built output (`dist/*`) and production installs. +- Mac packaging (dev): `scripts/package-mac-app.sh` defaults to current arch. Release checklist: `docs/platforms/mac/release.md`. - Type-check/build: `pnpm build` (tsc) - Lint/format: `pnpm lint` (oxlint), `pnpm format` (oxfmt) - Tests: `pnpm test` (vitest); coverage: `pnpm test:coverage` @@ -37,10 +56,16 @@ - Aim to keep files under ~700 LOC; guideline only (not a hard guardrail). Split/refactor when it improves clarity or testability. - Naming: use **Clawdbot** for product/app/docs headings; use `clawdbot` for CLI command, package/binary, paths, and config keys. +## Release Channels (Naming) +- stable: tagged releases only (e.g. `vYYYY.M.D`), npm dist-tag `latest`. +- beta: prerelease tags `vYYYY.M.D-beta.N`, npm dist-tag `beta` (may ship without macOS app). +- dev: moving head on `main` (no tag; git checkout main). + ## Testing Guidelines - Framework: Vitest with V8 coverage thresholds (70% lines/branches/functions/statements). - Naming: match source names with `*.test.ts`; e2e in `*.e2e.test.ts`. - Run `pnpm test` (or `pnpm test:coverage`) before pushing when you touch logic. +- Do not set test workers above 16; tried already. - Live tests (real keys): `CLAWDBOT_LIVE_TEST=1 pnpm test:live` (Clawdbot-only) or `LIVE=1 pnpm test:live` (includes provider live tests). Docker: `pnpm test:docker:live-models`, `pnpm test:docker:live-gateway`. Onboarding Docker E2E: `pnpm test:docker:onboard`. - Full kit + what’s covered: `docs/testing.md`. - Pure test additions/fixes generally do **not** need a changelog entry unless they alter user-facing behavior or the user asks for one. @@ -53,7 +78,11 @@ - Changelog workflow: keep latest released version at top (no `Unreleased`); after publishing, bump version and start a new top section. - PRs should summarize scope, note testing performed, and mention any user-facing changes or new flags. - PR review flow: when given a PR link, review via `gh pr view`/`gh pr diff` and do **not** change branches. +- PR review calls: prefer a single `gh pr view --json ...` to batch metadata/comments; run `gh pr diff` only when needed. +- Before starting a review when a GH Issue/PR is pasted: run `git pull`; if there are local changes or unpushed commits, stop and alert the user before reviewing. +- Goal: merge PRs. Prefer **rebase** when commits are clean; **squash** when history is messy. - PR merge flow: create a temp branch from `main`, merge the PR branch into it (prefer squash unless commit history is important; use rebase/merge when it is). Always try to merge the PR unless it’s truly difficult, then use another approach. If we squash, add the PR author as a co-contributor. Apply fixes, add changelog entry (include PR # + thanks), run full gate before the final commit, commit, merge back to `main`, delete the temp branch, and end on `main`. +- If you review a PR and later do work on it, land via merge/squash (no direct-main commits) and always add the PR author as a co-contributor. - When working on a PR: add a changelog entry with the PR number and thank the contributor. - When working on an issue: reference the issue in the changelog entry. - When merging a PR: leave a PR comment that explains exactly what we did and include the SHA hashes. @@ -61,7 +90,7 @@ - After merging a PR: run `bun scripts/update-clawtributors.ts` if the contributor is missing, then commit the regenerated README. ## Shorthand Commands -- `sync up`: if working tree is dirty, commit all changes (pick a sensible Conventional Commit message), then `git pull --rebase`; if rebase conflicts and cannot resolve, stop; otherwise `git push`. +- `sync`: if working tree is dirty, commit all changes (pick a sensible Conventional Commit message), then `git pull --rebase`; if rebase conflicts and cannot resolve, stop; otherwise `git push`. ### PR Workflow (Review vs Land) - **Review mode (PR link only):** read `gh pr view/diff`; **do not** switch branches; **do not** change code. @@ -72,20 +101,24 @@ - Pi sessions live under `~/.clawdbot/sessions/` by default; the base directory is not configurable. - Environment variables: see `~/.profile`. - Never commit or publish real phone numbers, videos, or live configuration values. Use obviously fake placeholders in docs, tests, and examples. + - Release flow: always read `docs/reference/RELEASING.md` and `docs/platforms/mac/release.md` before any release work; do not ask routine questions once those docs answer them. ## Troubleshooting - Rebrand/migration issues or legacy config/service warnings: run `clawdbot doctor` (see `docs/gateway/doctor.md`). ## Agent-Specific Notes - Vocabulary: "makeup" = "mac app". +- Never edit `node_modules` (global/Homebrew/npm/git installs too). Updates overwrite. Skill notes go in `tools.md` or `AGENTS.md`. +- Signal: "update fly" => `fly ssh console -a flawd-bot -C "bash -lc 'cd /data/clawd/clawdbot && git pull --rebase origin main'"` then `fly machines restart e825232f34d058 -a flawd-bot`. - When working on a GitHub Issue or PR, print the full URL at the end of the task. - When answering questions, respond with high-confidence answers only: verify in code; do not guess. - Never update the Carbon dependency. - Any dependency with `pnpm.patchedDependencies` must use an exact version (no `^`/`~`). +- Patching dependencies (pnpm patches, overrides, or vendored changes) requires explicit approval; do not do this by default. - CLI progress: use `src/cli/progress.ts` (`osc-progress` + `@clack/prompts` spinner); don’t hand-roll spinners/bars. - Status output: keep tables + ANSI-safe wrapping (`src/terminal/table.ts`); `status --all` = read-only/pasteable, `status --deep` = probes. - Gateway currently runs only as the menubar app; there is no separate LaunchAgent/helper label installed. Restart via the Clawdbot Mac app or `scripts/restart-mac.sh`; to verify/kill use `launchctl print gui/$UID | grep clawdbot` rather than assuming a fixed label. **When debugging on macOS, start/stop the gateway via the app, not ad-hoc tmux sessions; kill any temporary tunnels before handoff.** -- macOS logs: use `./scripts/clawlog.sh` (aka `vtlog`) to query unified logs for the Clawdbot subsystem; it supports follow/tail/category filters and expects passwordless sudo for `/usr/bin/log`. +- macOS logs: use `./scripts/clawlog.sh` to query unified logs for the Clawdbot subsystem; it supports follow/tail/category filters and expects passwordless sudo for `/usr/bin/log`. - If shared guardrails are available locally, review them; otherwise follow this repo's guidance. - SwiftUI state management (iOS/macOS): prefer the `Observation` framework (`@Observable`, `@Bindable`) over `ObservableObject`/`@StateObject`; don’t introduce new `ObservableObject` unless required for compatibility, and migrate existing usages when touching related code. - Connection providers: when adding a new connection, update every UI surface and docs (macOS app, web UI, mobile if applicable, onboarding/overview docs) and add matching status + configuration forms so provider lists and settings stay in sync. @@ -102,19 +135,24 @@ - **Multi-agent safety:** do **not** switch branches / check out a different branch unless explicitly requested. - **Multi-agent safety:** running multiple agents is OK as long as each agent has its own session. - **Multi-agent safety:** when you see unrecognized files, keep going; focus on your changes and commit only those. +- Lint/format churn: + - If staged+unstaged diffs are formatting-only, auto-resolve without asking. + - If commit/push already requested, auto-stage and include formatting-only follow-ups in the same commit (or a tiny follow-up commit if needed), no extra confirmation. + - Only ask when changes are semantic (logic/data/behavior). - Lobster seam: use the shared CLI palette in `src/terminal/palette.ts` (no hardcoded colors); apply palette to onboarding/config prompts and other TTY UI output as needed. - **Multi-agent safety:** focus reports on your edits; avoid guard-rail disclaimers unless truly blocked; when multiple agents touch the same file, continue if safe; end with a brief “other files present” note only if relevant. - Bug investigations: read source code of relevant npm dependencies and all related local code before concluding; aim for high-confidence root cause. - Code style: add brief comments for tricky logic; keep files under ~500 LOC when feasible (split/refactor as needed). - Tool schema guardrails (google-antigravity): avoid `Type.Union` in tool input schemas; no `anyOf`/`oneOf`/`allOf`. Use `stringEnum`/`optionalStringEnum` (Type.Unsafe enum) for string lists, and `Type.Optional(...)` instead of `... | null`. Keep top-level tool schema as `type: "object"` with `properties`. -- When asked to open a “session” file, open the Pi session logs under `~/.clawdbot/agents/main/sessions/*.jsonl` (newest unless a specific ID is given), not the default `sessions.json`. If logs are needed from another machine, SSH via Tailscale and read the same path there. -- Menubar dimming + restart flow mirrors Trimmy: use `scripts/restart-mac.sh` (kills all Clawdbot variants, runs `swift build`, packages, relaunches). Icon dimming depends on MenuBarExtraAccess wiring in AppMain; keep `appearsDisabled` updates intact when touching the status item. +- Tool schema guardrails: avoid raw `format` property names in tool schemas; some validators treat `format` as a reserved keyword and reject the schema. +- When asked to open a “session” file, open the Pi session logs under `~/.clawdbot/agents//sessions/*.jsonl` (use the `agent=` value in the Runtime line of the system prompt; newest unless a specific ID is given), not the default `sessions.json`. If logs are needed from another machine, SSH via Tailscale and read the same path there. - Do not rebuild the macOS app over SSH; rebuilds must be run directly on the Mac. - Never send streaming/partial replies to external messaging surfaces (WhatsApp, Telegram); only final replies should be delivered there. Streaming/tool events may still go to internal UIs/control channel. - Voice wake forwarding tips: - Command template should stay `clawdbot-mac agent --message "${text}" --thinking low`; `VoiceWakeForwarder` already shell-escapes `${text}`. Don’t add extra quotes. - launchd PATH is minimal; ensure the app’s launch agent PATH includes standard system paths plus your pnpm bin (typically `$HOME/Library/pnpm`) so `pnpm`/`clawdbot` binaries resolve when invoked via `clawdbot-mac`. - For manual `clawdbot message send` messages that include `!`, use the heredoc pattern noted below to avoid the Bash tool’s escaping. +- Release guardrails: do not change version numbers without operator’s explicit consent; always ask permission before running any npm publish/release step. ## NPM + 1Password (publish/verify) - Use the 1password skill; all `op` commands must run inside a fresh tmux session. @@ -123,19 +161,3 @@ - Publish: `npm publish --access public --otp=""` (run from the package dir). - Verify without local npmrc side effects: `npm view version --userconfig "$(mktemp)"`. - Kill the tmux session after publish. - -## Exclamation Mark Escaping Workaround -The Claude Code Bash tool escapes `!` to `\\!` in command arguments. When using `clawdbot message send` with messages containing exclamation marks, use heredoc syntax: - -```bash -# WRONG - will send "Hello\\!" with backslash -clawdbot message send --to "+1234" --message 'Hello!' - -# CORRECT - use heredoc to avoid escaping -clawdbot message send --to "+1234" --message "$(cat <<'EOF' -Hello! -EOF -)" -``` - -This is a Claude Code quirk, not a clawdbot bug. diff --git a/CHANGELOG.md b/CHANGELOG.md index d978f8bdb..9742150a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,576 @@ # Changelog -## 2026.1.15 (unreleased) +Docs: https://docs.clawd.bot + +## 2026.1.25 +Status: unreleased. + +### Changes +- Doctor: warn on gateway exposure without auth. (#2016) Thanks @Alex-Alaniz. +- Docs: add Vercel AI Gateway to providers sidebar. (#1901) Thanks @jerilynzheng. +- Agents: expand cron tool description with full schema docs. (#1988) Thanks @tomascupr. +- Skills: add missing dependency metadata for GitHub, Notion, Slack, Discord. (#1995) Thanks @jackheuberger. +- Docs: add Render deployment guide. (#1975) Thanks @anurag. +- Docs: add Claude Max API Proxy guide. (#1875) Thanks @atalovesyou. +- Docs: add DigitalOcean deployment guide. (#1870) Thanks @0xJonHoldsCrypto. +- Docs: add Raspberry Pi install guide. (#1871) Thanks @0xJonHoldsCrypto. +- Docs: add GCP Compute Engine deployment guide. (#1848) Thanks @hougangdev. +- Docs: credit both contributors for Control UI refresh. (#1852) Thanks @EnzeD. +- Onboarding: add Venice API key to non-interactive flow. (#1893) Thanks @jonisjongithub. +- Tlon: format thread reply IDs as @ud. (#1837) Thanks @wca4a. +- Gateway: prefer newest session metadata when combining stores. (#1823) Thanks @emanuelst. +- Web UI: keep sub-agent announce replies visible in WebChat. (#1977) Thanks @andrescardonas7. +- CI: increase Node heap size for macOS checks. (#1890) Thanks @realZachi. +- macOS: avoid crash when rendering code blocks by bumping Textual to 0.3.1. (#2033) Thanks @garricn. +- Browser: fall back to URL matching for extension relay target resolution. (#1999) Thanks @jonit-dev. +- Update: ignore dist/control-ui for dirty checks and restore after ui builds. (#1976) Thanks @Glucksberg. +- Telegram: allow caption param for media sends. (#1888) Thanks @mguellsegarra. +- Telegram: avoid block replies when streaming is disabled. (#1885) Thanks @ivancasco. +- Auth: show copyable Google auth URL after ASCII prompt. (#1787) Thanks @robbyczgw-cla. +- Routing: precompile session key regexes. (#1697) Thanks @Ray0907. +- TUI: avoid width overflow when rendering selection lists. (#1686) Thanks @mossein. +- Telegram: keep topic IDs in restart sentinel notifications. (#1807) Thanks @hsrvc. +- Config: apply config.env before ${VAR} substitution. (#1813) Thanks @spanishflu-est1918. +- Slack: clear ack reaction after streamed replies. (#2044) Thanks @fancyboi999. +- macOS: keep custom SSH usernames in remote target. (#2046) Thanks @algal. + +### Fixes +- Web UI: improve WebChat image paste previews and allow image-only sends. (#1925) Thanks @smartprogrammer93. + +## 2026.1.24-3 + +### Fixes +- Gateway: harden reverse proxy handling for local-client detection and unauthenticated proxied connects. (#1795) Thanks @orlyjamie. +- Security audit: flag loopback Control UI with auth disabled as critical. (#1795) Thanks @orlyjamie. +- CLI: resume claude-cli sessions and stream CLI replies to TUI clients. (#1921) Thanks @rmorse. + +## 2026.1.24-2 + +### Fixes +- Packaging: include dist/link-understanding output in npm tarball (fixes missing apply.js import on install). + +## 2026.1.24-1 + +### Fixes +- Packaging: include dist/shared output in npm tarball (fixes missing reasoning-tags import on install). + +## 2026.1.24 + +### Highlights +- Providers: Ollama discovery + docs; Venice guide upgrades + cross-links. (#1606) Thanks @abhaymundhara. https://docs.clawd.bot/providers/ollama https://docs.clawd.bot/providers/venice +- Channels: LINE plugin (Messaging API) with rich replies + quick replies. (#1630) Thanks @plum-dawg. +- TTS: Edge fallback (keyless) + `/tts` auto modes. (#1668, #1667) Thanks @steipete, @sebslight. https://docs.clawd.bot/tts +- Exec approvals: approve in-chat via `/approve` across all channels (including plugins). (#1621) Thanks @czekaj. https://docs.clawd.bot/tools/exec-approvals https://docs.clawd.bot/tools/slash-commands +- Telegram: DM topics as separate sessions + outbound link preview toggle. (#1597, #1700) Thanks @rohannagpal, @zerone0x. https://docs.clawd.bot/channels/telegram + +### Changes +- Channels: add LINE plugin (Messaging API) with rich replies, quick replies, and plugin HTTP registry. (#1630) Thanks @plum-dawg. +- TTS: add Edge TTS provider fallback, defaulting to keyless Edge with MP3 retry on format failures. (#1668) Thanks @steipete. https://docs.clawd.bot/tts +- TTS: add auto mode enum (off/always/inbound/tagged) with per-session `/tts` override. (#1667) Thanks @sebslight. https://docs.clawd.bot/tts +- Telegram: treat DM topics as separate sessions and keep DM history limits stable with thread suffixes. (#1597) Thanks @rohannagpal. +- Telegram: add `channels.telegram.linkPreview` to toggle outbound link previews. (#1700) Thanks @zerone0x. https://docs.clawd.bot/channels/telegram +- Web search: add Brave freshness filter parameter for time-scoped results. (#1688) Thanks @JonUleis. https://docs.clawd.bot/tools/web +- UI: refresh Control UI dashboard design system (colors, icons, typography). (#1745, #1786) Thanks @EnzeD, @mousberg. +- Exec approvals: forward approval prompts to chat with `/approve` for all channels (including plugins). (#1621) Thanks @czekaj. https://docs.clawd.bot/tools/exec-approvals https://docs.clawd.bot/tools/slash-commands +- Gateway: expose config.patch in the gateway tool with safe partial updates + restart sentinel. (#1653) Thanks @Glucksberg. +- Diagnostics: add diagnostic flags for targeted debug logs (config + env override). https://docs.clawd.bot/diagnostics/flags +- Docs: expand FAQ (migration, scheduling, concurrency, model recommendations, OpenAI subscription auth, Pi sizing, hackable install, docs SSL workaround). +- Docs: add verbose installer troubleshooting guidance. +- Docs: add macOS VM guide with local/hosted options + VPS/nodes guidance. (#1693) Thanks @f-trycua. +- Docs: add Bedrock EC2 instance role setup + IAM steps. (#1625) Thanks @sergical. https://docs.clawd.bot/bedrock +- Docs: update Fly.io guide notes. +- Dev: add prek pre-commit hooks + dependabot config for weekly updates. (#1720) Thanks @dguido. + +### Fixes +- Web UI: fix config/debug layout overflow, scrolling, and code block sizing. (#1715) Thanks @saipreetham589. +- Web UI: show Stop button during active runs, swap back to New session when idle. (#1664) Thanks @ndbroadbent. +- Web UI: clear stale disconnect banners on reconnect; allow form saves with unsupported schema paths but block missing schema. (#1707) Thanks @Glucksberg. +- Web UI: hide internal `message_id` hints in chat bubbles. +- Gateway: allow Control UI token-only auth to skip device pairing even when device identity is present (`gateway.controlUi.allowInsecureAuth`). (#1679) Thanks @steipete. +- Matrix: decrypt E2EE media attachments with preflight size guard. (#1744) Thanks @araa47. +- BlueBubbles: route phone-number targets to DMs, avoid leaking routing IDs, and auto-create missing DMs (Private API required). (#1751) Thanks @tyler6204. https://docs.clawd.bot/channels/bluebubbles +- BlueBubbles: keep part-index GUIDs in reply tags when short IDs are missing. +- iMessage: normalize chat_id/chat_guid/chat_identifier prefixes case-insensitively and keep service-prefixed handles stable. (#1708) Thanks @aaronn. +- Signal: repair reaction sends (group/UUID targets + CLI author flags). (#1651) Thanks @vilkasdev. +- Signal: add configurable signal-cli startup timeout + external daemon mode docs. (#1677) https://docs.clawd.bot/channels/signal +- Telegram: set fetch duplex="half" for uploads on Node 22 to avoid sendPhoto failures. (#1684) Thanks @commdata2338. +- Telegram: use wrapped fetch for long-polling on Node to normalize AbortSignal handling. (#1639) +- Telegram: honor per-account proxy for outbound API calls. (#1774) Thanks @radek-paclt. +- Telegram: fall back to text when voice notes are blocked by privacy settings. (#1725) Thanks @foeken. +- Voice Call: return stream TwiML for outbound conversation calls on initial Twilio webhook. (#1634) +- Voice Call: serialize Twilio TTS playback and cancel on barge-in to prevent overlap. (#1713) Thanks @dguido. +- Google Chat: tighten email allowlist matching, typing cleanup, media caps, and onboarding/docs/tests. (#1635) Thanks @iHildy. +- Google Chat: normalize space targets without double `spaces/` prefix. +- Agents: auto-compact on context overflow prompt errors before failing. (#1627) Thanks @rodrigouroz. +- Agents: use the active auth profile for auto-compaction recovery. +- Media understanding: skip image understanding when the primary model already supports vision. (#1747) Thanks @tyler6204. +- Models: default missing custom provider fields so minimal configs are accepted. +- Messaging: keep newline chunking safe for fenced markdown blocks across channels. +- Messaging: treat newline chunking as paragraph-aware (blank-line splits) to keep lists and headings together. (#1726) Thanks @tyler6204. +- TUI: reload history after gateway reconnect to restore session state. (#1663) +- Heartbeat: normalize target identifiers for consistent routing. +- Exec: keep approvals for elevated ask unless full mode. (#1616) Thanks @ivancasco. +- Exec: treat Windows platform labels as Windows for node shell selection. (#1760) Thanks @ymat19. +- Gateway: include inline config env vars in service install environments. (#1735) Thanks @Seredeep. +- Gateway: skip Tailscale DNS probing when tailscale.mode is off. (#1671) +- Gateway: reduce log noise for late invokes + remote node probes; debounce skills refresh. (#1607) Thanks @petter-b. +- Gateway: clarify Control UI/WebChat auth error hints for missing tokens. (#1690) +- Gateway: listen on IPv6 loopback when bound to 127.0.0.1 so localhost webhooks work. +- Gateway: store lock files in the temp directory to avoid stale locks on persistent volumes. (#1676) +- macOS: default direct-transport `ws://` URLs to port 18789; document `gateway.remote.transport`. (#1603) Thanks @ngutman. +- Tests: cap Vitest workers on CI macOS to reduce timeouts. (#1597) Thanks @rohannagpal. +- Tests: avoid fake-timer dependency in embedded runner stream mock to reduce CI flakes. (#1597) Thanks @rohannagpal. +- Tests: increase embedded runner ordering test timeout to reduce CI flakes. (#1597) Thanks @rohannagpal. + +## 2026.1.23-1 + +### Fixes +- Packaging: include dist/tts output in npm tarball (fixes missing dist/tts/tts.js). + +## 2026.1.23 + +### Highlights +- TTS: move Telegram TTS into core + enable model-driven TTS tags by default for expressive audio replies. (#1559) Thanks @Glucksberg. https://docs.clawd.bot/tts +- Gateway: add `/tools/invoke` HTTP endpoint for direct tool calls (auth + tool policy enforced). (#1575) Thanks @vignesh07. https://docs.clawd.bot/gateway/tools-invoke-http-api +- Heartbeat: per-channel visibility controls (OK/alerts/indicator). (#1452) Thanks @dlauer. https://docs.clawd.bot/gateway/heartbeat +- Deploy: add Fly.io deployment support + guide. (#1570) https://docs.clawd.bot/platforms/fly +- Channels: add Tlon/Urbit channel plugin (DMs, group mentions, thread replies). (#1544) Thanks @wca4a. https://docs.clawd.bot/channels/tlon + +### Changes +- Channels: allow per-group tool allow/deny policies across built-in + plugin channels. (#1546) Thanks @adam91holt. https://docs.clawd.bot/multi-agent-sandbox-tools +- Agents: add Bedrock auto-discovery defaults + config overrides. (#1553) Thanks @fal3. https://docs.clawd.bot/bedrock +- CLI: add `clawdbot system` for system events + heartbeat controls; remove standalone `wake`. (commit 71203829d) https://docs.clawd.bot/cli/system +- CLI: add live auth probes to `clawdbot models status` for per-profile verification. (commit 40181afde) https://docs.clawd.bot/cli/models +- CLI: restart the gateway by default after `clawdbot update`; add `--no-restart` to skip it. (commit 2c85b1b40) +- Browser: add node-host proxy auto-routing for remote gateways (configurable per gateway/node). (commit c3cb26f7c) +- Plugins: add optional `llm-task` JSON-only tool for workflows. (#1498) Thanks @vignesh07. https://docs.clawd.bot/tools/llm-task +- Markdown: add per-channel table conversion (bullets for Signal/WhatsApp, code blocks elsewhere). (#1495) Thanks @odysseus0. +- Agents: keep system prompt time zone-only and move current time to `session_status` for better cache hits. (commit 66eec295b) +- Agents: remove redundant bash tool alias from tool registration/display. (#1571) Thanks @Takhoffman. +- Docs: add cron vs heartbeat decision guide (with Lobster workflow notes). (#1533) Thanks @JustYannicc. https://docs.clawd.bot/automation/cron-vs-heartbeat +- Docs: clarify HEARTBEAT.md empty file skips heartbeats, missing file still runs. (#1535) Thanks @JustYannicc. https://docs.clawd.bot/gateway/heartbeat + +### Fixes +- Sessions: accept non-UUID sessionIds for history/send/status while preserving agent scoping. (#1518) +- Heartbeat: accept plugin channel ids for heartbeat target validation + UI hints. +- Messaging/Sessions: mirror outbound sends into target session keys (threads + dmScope), create session entries on send, and normalize session key casing. (#1520, commit 4b6cdd1d3) +- Sessions: reject array-backed session stores to prevent silent wipes. (#1469) +- Gateway: compare Linux process start time to avoid PID recycling lock loops; keep locks unless stale. (#1572) Thanks @steipete. +- Gateway: accept null optional fields in exec approval requests. (#1511) Thanks @pvoo. +- Exec approvals: persist allowlist entry ids to keep macOS allowlist rows stable. (#1521) Thanks @ngutman. +- Exec: honor tools.exec ask/security defaults for elevated approvals (avoid unwanted prompts). (commit 5662a9cdf) +- Daemon: use platform PATH delimiters when building minimal service paths. (commit a4e57d3ac) +- Linux: include env-configured user bin roots in systemd PATH and align PATH audits. (#1512) Thanks @robbyczgw-cla. +- Tailscale: retry serve/funnel with sudo only for permission errors and keep original failure details. (#1551) Thanks @sweepies. +- Docker: update gateway command in docker-compose and Hetzner guide. (#1514) +- Agents: show tool error fallback when the last assistant turn only invoked tools (prevents silent stops). (commit 8ea8801d0) +- Agents: ignore IDENTITY.md template placeholders when parsing identity. (#1556) +- Agents: drop orphaned OpenAI Responses reasoning blocks on model switches. (#1562) Thanks @roshanasingh4. +- Agents: add CLI log hint to "agent failed before reply" messages. (#1550) Thanks @sweepies. +- Agents: warn and ignore tool allowlists that only reference unknown or unloaded plugin tools. (#1566) +- Agents: treat plugin-only tool allowlists as opt-ins; keep core tools enabled. (#1467) +- Agents: honor enqueue overrides for embedded runs to avoid queue deadlocks in tests. (commit 084002998) +- Slack: honor open groupPolicy for unlisted channels in message + slash gating. (#1563) Thanks @itsjaydesu. +- Discord: limit autoThread mention bypass to bot-owned threads; keep ack reactions mention-gated. (#1511) Thanks @pvoo. +- Discord: retry rate-limited allowlist resolution + command deploy to avoid gateway crashes. (commit f70ac0c7c) +- Mentions: ignore mentionPattern matches when another explicit mention is present in group chats (Slack/Discord/Telegram/WhatsApp). (commit d905ca0e0) +- Telegram: render markdown in media captions. (#1478) +- MS Teams: remove `.default` suffix from Graph scopes and Bot Framework probe scopes. (#1507, #1574) Thanks @Evizero. +- Browser: keep extension relay tabs controllable when the extension reuses a session id after switching tabs. (#1160) +- Voice wake: auto-save wake words on blur/submit across iOS/Android and align limits with macOS. (commit 69f645c66) +- UI: keep the Control UI sidebar visible while scrolling long pages. (#1515) Thanks @pookNast. +- UI: cache Control UI markdown rendering + memoize chat text extraction to reduce Safari typing jank. (commit d57cb2e1a) +- TUI: forward unknown slash commands, include Gateway commands in autocomplete, and render slash replies as system output. (commit 1af227b61, commit 8195497ce, commit 6fba598ea) +- CLI: auth probe output polish (table output, inline errors, reduced noise, and wrap fixes in `clawdbot models status`). (commit da3f2b489, commit 00ae21bed, commit 31e59cd58, commit f7dc27f2d, commit 438e782f8, commit 886752217, commit aabe0bed3, commit 81535d512, commit c63144ab1) +- Media: only parse `MEDIA:` tags when they start the line to avoid stripping prose mentions. (#1206) +- Media: preserve PNG alpha when possible; fall back to JPEG when still over size cap. (#1491) Thanks @robbyczgw-cla. +- Skills: gate bird Homebrew install to macOS. (#1569) Thanks @bradleypriest. + +## 2026.1.22 + +### Changes +- Highlight: Compaction safeguard now uses adaptive chunking, progressive fallback, and UI status + retries. (#1466) Thanks @dlauer. +- Providers: add Antigravity usage tracking to status output. (#1490) Thanks @patelhiren. +- Slack: add chat-type reply threading overrides via `replyToModeByChatType`. (#1442) Thanks @stefangalescu. +- BlueBubbles: add `asVoice` support for MP3/CAF voice memos in sendAttachment. (#1477, #1482) Thanks @Nicell. +- Onboarding: add hatch choice (TUI/Web/Later), token explainer, background dashboard seed on macOS, and showcase link. + +### Fixes +- BlueBubbles: stop typing indicator on idle/no-reply. (#1439) Thanks @Nicell. +- Message tool: keep path/filePath as-is for send; hydrate buffers only for sendAttachment. (#1444) Thanks @hopyky. +- Auto-reply: only report a model switch when session state is available. (#1465) Thanks @robbyczgw-cla. +- Control UI: resolve local avatar URLs with basePath across injection + identity RPC. (#1457) Thanks @dlauer. +- Agents: sanitize assistant history text to strip tool-call markers. (#1456) Thanks @zerone0x. +- Discord: clarify Message Content Intent onboarding hint. (#1487) Thanks @kyleok. +- Gateway: stop the service before uninstalling and fail if it remains loaded. +- Agents: surface concrete API error details instead of generic AI service errors. +- Exec: fall back to non-PTY when PTY spawn fails (EBADF). (#1484) +- Exec approvals: allow per-segment allowlists for chained shell commands on gateway + node hosts. (#1458) Thanks @czekaj. +- Agents: make OpenAI sessions image-sanitize-only; gate tool-id/repair sanitization by provider. +- Doctor: honor CLAWDBOT_GATEWAY_TOKEN for auth checks and security audit token reuse. (#1448) Thanks @azade-c. +- Agents: make tool summaries more readable and only show optional params when set. +- Agents: honor SOUL.md guidance even when the file is nested or path-qualified. (#1434) Thanks @neooriginal. +- Matrix (plugin): persist m.direct for resolved DMs and harden room fallback. (#1436, #1486) Thanks @sibbl. +- CLI: prefer `~` for home paths in output. +- Mattermost (plugin): enforce pairing/allowlist gating, keep @username targets, and clarify plugin-only docs. (#1428) Thanks @damoahdominic. +- Agents: centralize transcript sanitization in the runner; keep tags and error turns intact. +- Auth: skip auth profiles in cooldown during initial selection and rotation. (#1316) Thanks @odrobnik. +- Agents/TUI: honor user-pinned auth profiles during cooldown and preserve search picker ranking. (#1432) Thanks @tobiasbischoff. +- Docs: fix gog auth services example to include docs scope. (#1454) Thanks @zerone0x. +- Slack: reduce WebClient retries to avoid duplicate sends. (#1481) +- Slack: read thread replies for message reads when threadId is provided (replies-only). (#1450) Thanks @rodrigouroz. +- Discord: honor accountId across message actions and cron deliveries. (#1492) Thanks @svkozak. +- macOS: prefer linked channels in gateway summary to avoid false “not linked” status. +- macOS/tests: fix gateway summary lookup after guard unwrap; prevent browser opens during tests. (ECID-1483) + +## 2026.1.21-2 + +### Fixes +- Control UI: ignore bootstrap identity placeholder text for avatar values and fall back to the default avatar. https://docs.clawd.bot/cli/agents https://docs.clawd.bot/web/control-ui +- Slack: remove deprecated `filetype` field from `files.uploadV2` to eliminate API warnings. (#1447) + +## 2026.1.21 + +### Changes +- Highlight: Lobster optional plugin tool for typed workflows + approval gates. https://docs.clawd.bot/tools/lobster +- Lobster: allow workflow file args via `argsJson` in the plugin tool. https://docs.clawd.bot/tools/lobster +- Heartbeat: allow running heartbeats in an explicit session key. (#1256) Thanks @zknicker. +- CLI: default exec approvals to the local host, add gateway/node targeting flags, and show target details in allowlist output. +- CLI: exec approvals mutations render tables instead of raw JSON. +- Exec approvals: support wildcard agent allowlists (`*`) across all agents. +- Exec approvals: allowlist matches resolved binary paths only, add safe stdin-only bins, and tighten allowlist shell parsing. +- Nodes: expose node PATH in status/describe and bootstrap PATH for node-host execution. +- CLI: flatten node service commands under `clawdbot node` and remove `service node` docs. +- CLI: move gateway service commands under `clawdbot gateway` and add `gateway probe` for reachability. +- Sessions: add per-channel reset overrides via `session.resetByChannel`. (#1353) Thanks @cash-echo-bot. +- Agents: add identity avatar config support and Control UI avatar rendering. (#1329, #1424) Thanks @dlauer. +- UI: show per-session assistant identity in the Control UI. (#1420) Thanks @robbyczgw-cla. +- CLI: add `clawdbot update wizard` for interactive channel selection and restart prompts. https://docs.clawd.bot/cli/update +- Signal: add typing indicators and DM read receipts via signal-cli. +- MSTeams: add file uploads, adaptive cards, and attachment handling improvements. (#1410) Thanks @Evizero. +- Onboarding: remove the run setup-token auth option (paste setup-token or reuse CLI creds instead). +- Docs: add troubleshooting entry for gateway.mode blocking gateway start. https://docs.clawd.bot/gateway/troubleshooting +- Docs: add /model allowlist troubleshooting note. (#1405) +- Docs: add per-message Gmail search example for gog. (#1220) Thanks @mbelinky. + +### Breaking +- **BREAKING:** Control UI now rejects insecure HTTP without device identity by default. Use HTTPS (Tailscale Serve) or set `gateway.controlUi.allowInsecureAuth: true` to allow token-only auth. https://docs.clawd.bot/web/control-ui#insecure-http +- **BREAKING:** Envelope and system event timestamps now default to host-local time (was UTC) so agents don’t have to constantly convert. + +### Fixes +- Nodes/macOS: prompt on allowlist miss for node exec approvals, persist allowlist decisions, and flatten node invoke errors. (#1394) Thanks @ngutman. +- Gateway: keep auto bind loopback-first and add explicit tailnet binding to avoid Tailscale taking over local UI. (#1380) +- Memory: prevent CLI hangs by deferring vector probes, adding sqlite-vec/embedding timeouts, and showing sync progress early. +- Agents: enforce 9-char alphanumeric tool call ids for Mistral providers. (#1372) Thanks @zerone0x. +- Embedded runner: persist injected history images so attachments aren’t reloaded each turn. (#1374) Thanks @Nicell. +- Nodes tool: include agent/node/gateway context in tool failure logs to speed approval debugging. +- macOS: exec approvals now respect wildcard agent allowlists (`*`). +- macOS: allow SSH agent auth when no identity file is set. (#1384) Thanks @ameno-. +- Gateway: prevent multiple gateways from sharing the same config/state at once (singleton lock). +- UI: remove the chat stop button and keep the composer aligned to the bottom edge. +- Typing: start instant typing indicators at run start so DMs and mentions show immediately. +- Configure: restrict the model allowlist picker to OAuth-compatible Anthropic models and preselect Opus 4.5. +- Configure: seed model fallbacks from the allowlist selection when multiple models are chosen. +- Model picker: list the full catalog when no model allowlist is configured. +- Discord: honor wildcard channel configs via shared match helpers. (#1334) Thanks @pvoo. +- BlueBubbles: resolve short message IDs safely and expose full IDs in templates. (#1387) Thanks @tyler6204. +- Infra: preserve fetch helper methods when wrapping abort signals. (#1387) +- macOS: default distribution packaging to universal binaries. (#1396) Thanks @JustYannicc. + +## 2026.1.20 + +### Changes +- Control UI: add copy-as-markdown with error feedback. (#1345) https://docs.clawd.bot/web/control-ui +- Control UI: drop the legacy list view. (#1345) https://docs.clawd.bot/web/control-ui +- TUI: add syntax highlighting for code blocks. (#1200) https://docs.clawd.bot/tui +- TUI: session picker shows derived titles, fuzzy search, relative times, and last message preview. (#1271) https://docs.clawd.bot/tui +- TUI: add a searchable model picker for quicker model selection. (#1198) https://docs.clawd.bot/tui +- TUI: add input history (up/down) for submitted messages. (#1348) https://docs.clawd.bot/tui +- ACP: add `clawdbot acp` for IDE integrations. https://docs.clawd.bot/cli/acp +- ACP: add `clawdbot acp client` interactive harness for debugging. https://docs.clawd.bot/cli/acp +- Skills: add download installs with OS-filtered options. https://docs.clawd.bot/tools/skills +- Skills: add the local sherpa-onnx-tts skill. https://docs.clawd.bot/tools/skills +- Memory: add hybrid BM25 + vector search (FTS5) with weighted merging and fallback. https://docs.clawd.bot/concepts/memory +- Memory: add SQLite embedding cache to speed up reindexing and frequent updates. https://docs.clawd.bot/concepts/memory +- Memory: add OpenAI batch indexing for embeddings when configured. https://docs.clawd.bot/concepts/memory +- Memory: enable OpenAI batch indexing by default for OpenAI embeddings. https://docs.clawd.bot/concepts/memory +- Memory: allow parallel OpenAI batch indexing jobs (default concurrency: 2). https://docs.clawd.bot/concepts/memory +- Memory: render progress immediately, color batch statuses in verbose logs, and poll OpenAI batch status every 2s by default. https://docs.clawd.bot/concepts/memory +- Memory: add `--verbose` logging for memory status + batch indexing details. https://docs.clawd.bot/concepts/memory +- Memory: add native Gemini embeddings provider for memory search. (#1151) https://docs.clawd.bot/concepts/memory +- Browser: allow config defaults for efficient snapshots in the tool/CLI. (#1336) https://docs.clawd.bot/tools/browser +- Nostr: add the Nostr channel plugin with profile management + onboarding defaults. (#1323) https://docs.clawd.bot/channels/nostr +- Matrix: migrate to matrix-bot-sdk with E2EE support, location handling, and group allowlist upgrades. (#1298) https://docs.clawd.bot/channels/matrix +- Slack: add HTTP webhook mode via Bolt HTTP receiver. (#1143) https://docs.clawd.bot/channels/slack +- Telegram: enrich forwarded-message context with normalized origin details + legacy fallback. (#1090) https://docs.clawd.bot/channels/telegram +- Discord: fall back to `/skill` when native command limits are exceeded. (#1287) +- Discord: expose `/skill` globally. (#1287) +- Zalouser: add channel dock metadata, config schema, setup wiring, probe, and status issues. (#1219) https://docs.clawd.bot/plugins/zalouser +- Plugins: require manifest-embedded config schemas with preflight validation warnings. (#1272) https://docs.clawd.bot/plugins/manifest +- Plugins: move channel catalog metadata into plugin manifests. (#1290) https://docs.clawd.bot/plugins/manifest +- Plugins: align Nextcloud Talk policy helpers with core patterns. (#1290) https://docs.clawd.bot/plugins/manifest +- Plugins/UI: let channel plugin metadata drive UI labels/icons and cron channel options. (#1306) https://docs.clawd.bot/web/control-ui +- Agents/UI: add agent avatar support in identity config, IDENTITY.md, and the Control UI. (#1329) https://docs.clawd.bot/gateway/configuration +- Plugins: add plugin slots with a dedicated memory slot selector. https://docs.clawd.bot/plugins/agent-tools +- Plugins: ship the bundled BlueBubbles channel plugin (disabled by default). https://docs.clawd.bot/channels/bluebubbles +- Plugins: migrate bundled messaging extensions to the plugin SDK and resolve plugin-sdk imports in the loader. +- Plugins: migrate the Zalo plugin to the shared plugin SDK runtime. https://docs.clawd.bot/channels/zalo +- Plugins: migrate the Zalo Personal plugin to the shared plugin SDK runtime. https://docs.clawd.bot/plugins/zalouser +- Plugins: allow optional agent tools with explicit allowlists and add the plugin tool authoring guide. https://docs.clawd.bot/plugins/agent-tools +- Plugins: auto-enable bundled channel/provider plugins when configuration is present. +- Plugins: sync plugin sources on channel switches and update npm-installed plugins during `clawdbot update`. +- Plugins: share npm plugin update logic between `clawdbot update` and `clawdbot plugins update`. + +- Gateway/API: add `/v1/responses` (OpenResponses) with item-based input + semantic streaming events. (#1229) +- Gateway/API: expand `/v1/responses` to support file/image inputs, tool_choice, usage, and output limits. (#1229) +- Usage: add `/usage cost` summaries and macOS menu cost charts. https://docs.clawd.bot/reference/api-usage-costs +- Security: warn when <=300B models run without sandboxing while web tools are enabled. https://docs.clawd.bot/cli/security +- Exec: add host/security/ask routing for gateway + node exec. https://docs.clawd.bot/tools/exec +- Exec: add `/exec` directive for per-session exec defaults (host/security/ask/node). https://docs.clawd.bot/tools/exec +- Exec approvals: migrate approvals to `~/.clawdbot/exec-approvals.json` with per-agent allowlists + skill auto-allow toggle, and add approvals UI + node exec lifecycle events. https://docs.clawd.bot/tools/exec-approvals +- Nodes: add headless node host (`clawdbot node start`) for `system.run`/`system.which`. https://docs.clawd.bot/cli/node +- Nodes: add node daemon service install/status/start/stop/restart. https://docs.clawd.bot/cli/node +- Bridge: add `skills.bins` RPC to support node host auto-allow skill bins. +- Sessions: add daily reset policy with per-type overrides and idle windows (default 4am local), preserving legacy idle-only configs. (#1146) https://docs.clawd.bot/concepts/session +- Sessions: allow `sessions_spawn` to override thinking level for sub-agent runs. https://docs.clawd.bot/tools/subagents +- Channels: unify thread/topic allowlist matching + command/mention gating helpers across core providers. https://docs.clawd.bot/concepts/groups +- Models: add Qwen Portal OAuth provider support. (#1120) https://docs.clawd.bot/providers/qwen +- Onboarding: add allowlist prompts and username-to-id resolution across core and extension channels. https://docs.clawd.bot/start/onboarding +- Docs: clarify allowlist input types and onboarding behavior for messaging channels. https://docs.clawd.bot/start/onboarding +- Docs: refresh Android node discovery docs for the Gateway WS service type. https://docs.clawd.bot/platforms/android +- Docs: surface Amazon Bedrock in provider lists and clarify Bedrock auth env vars. (#1289) https://docs.clawd.bot/bedrock +- Docs: clarify WhatsApp voice notes. https://docs.clawd.bot/channels/whatsapp +- Docs: clarify Windows WSL portproxy LAN access notes. https://docs.clawd.bot/platforms/windows +- Docs: refresh bird skill install metadata and usage notes. (#1302) https://docs.clawd.bot/tools/browser-login +- Agents: add local docs path resolution and include docs/mirror/source/community pointers in the system prompt. +- Agents: clarify node_modules read-only guidance in agent instructions. +- Config: stamp last-touched metadata on write and warn if the config is newer than the running build. +- macOS: hide usage section when usage is unavailable instead of showing provider errors. +- Android: migrate node transport to the Gateway WebSocket protocol with TLS pinning support + gateway discovery naming. +- Android: send structured payloads in node events/invokes and include user-agent metadata in gateway connects. +- Android: remove legacy bridge transport code now that nodes use the gateway protocol. +- Android: bump okhttp + dnsjava to satisfy lint dependency checks. +- Build: update workspace + core/plugin deps. +- Build: use tsgo for dev/watch builds by default (opt out with `CLAWDBOT_TS_COMPILER=tsc`). +- Repo: remove the Peekaboo git submodule now that the SPM release is used. +- macOS: switch PeekabooBridge integration to the tagged Swift Package Manager release. +- macOS: stop syncing Peekaboo in postinstall. +- Swabble: use the tagged Commander Swift package release. + +### Breaking +- **BREAKING:** Reject invalid/unknown config entries and refuse to start the gateway for safety. Run `clawdbot doctor --fix` to repair, then update plugins (`clawdbot plugins update`) if you use any. + +### Fixes +- Discovery: shorten Bonjour DNS-SD service type to `_clawdbot-gw._tcp` and update discovery clients/docs. +- Diagnostics: export OTLP logs, correct queue depth tracking, and document message-flow telemetry. +- Diagnostics: emit message-flow diagnostics across channels via shared dispatch. (#1244) +- Diagnostics: gate heartbeat/webhook logging. (#1244) +- Gateway: strip inbound envelope headers from chat history messages to keep clients clean. +- Gateway: clarify unauthorized handshake responses with token/password mismatch guidance. +- Gateway: allow mobile node client ids for iOS + Android handshake validation. (#1354) +- Gateway: clarify connect/validation errors for gateway params. (#1347) +- Gateway: preserve restart wake routing + thread replies across restarts. (#1337) +- Gateway: reschedule per-agent heartbeats on config hot reload without restarting the runner. +- Gateway: require authorized restarts for SIGUSR1 (restart/apply/update) so config gating can't be bypassed. +- Cron: auto-deliver isolated agent output to explicit targets without tool calls. (#1285) +- Agents: preserve subagent announce thread/topic routing + queued replies across channels. (#1241) +- Agents: propagate accountId into embedded runs so sub-agent announce routing honors the originating account. (#1058) +- Agents: avoid treating timeout errors with "aborted" messages as user aborts, so model fallback still runs. (#1137) +- Agents: sanitize oversized image payloads before send and surface image-dimension errors. +- Sessions: fall back to session labels when listing display names. (#1124) +- Compaction: include tool failure summaries in safeguard compaction to prevent retry loops. (#1084) +- Config: log invalid config issues once per run and keep invalid-config errors stackless. +- Config: allow Perplexity as a web_search provider in config validation. (#1230) +- Config: allow custom fields under `skills.entries..config` for skill credentials/config. (#1226) +- Doctor: clarify plugin auto-enable hint text in the startup banner. +- Doctor: canonicalize legacy session keys in session stores to prevent stale metadata. (#1169) +- Docs: make docs:list fail fast with a clear error if the docs directory is missing. +- Plugins: add Nextcloud Talk manifest for plugin config validation. (#1297) +- Plugins: surface plugin load/register/config errors in gateway logs with plugin/source context. +- CLI: preserve cron delivery settings when editing message payloads. (#1322) +- CLI: keep `clawdbot logs` output resilient to broken pipes while preserving progress output. +- CLI: avoid duplicating --profile/--dev flags when formatting commands. +- CLI: centralize CLI command registration to keep fast-path routing and program wiring in sync. (#1207) +- CLI: keep banners on routed commands, restore config guarding outside fast-path routing, and tighten fast-path flag parsing while skipping console capture for extra speed. (#1195) +- CLI: skip runner rebuilds when dist is fresh. (#1231) +- CLI: add WSL2/systemd unavailable hints in daemon status/doctor output. +- Status: route native `/status` to the active agent so model selection reflects the correct profile. (#1301) +- Status: show both usage windows with reset hints when usage data is available. (#1101) +- UI: keep config form enums typed, preserve empty strings, protect sensitive defaults, and deepen config search. (#1315) +- UI: preserve ordered list numbering in chat markdown. (#1341) +- UI: allow Control UI to read gatewayUrl from URL params for remote WebSocket targets. (#1342) +- UI: prevent double-scroll in Control UI chat by locking chat layout to the viewport. (#1283) +- UI: enable shell mode for sync Windows spawns to avoid `pnpm ui:build` EINVAL. (#1212) +- TUI: keep thinking blocks ordered before content during streaming and isolate per-run assembly. (#1202) +- TUI: align custom editor initialization with the latest pi-tui API. (#1298) +- TUI: show generic empty-state text for searchable pickers. (#1201) +- TUI: highlight model search matches and stabilize search ordering. +- Configure: hide OpenRouter auto routing model from the model picker. (#1182) +- Memory: show total file counts + scan issues in `clawdbot memory status`. +- Memory: fall back to non-batch embeddings after repeated batch failures. +- Memory: apply OpenAI batch defaults even without explicit remote config. +- Memory: index atomically so failed reindex preserves the previous memory database. (#1151) +- Memory: avoid sqlite-vec unique constraint failures when reindexing duplicate chunk ids. (#1151) +- Memory: retry transient 5xx errors (Cloudflare) during embedding indexing. +- Memory: parallelize embedding indexing with rate-limit retries. +- Memory: split overly long lines to keep embeddings under token limits. +- Memory: skip empty chunks to avoid invalid embedding inputs. +- Memory: split embedding batches to avoid OpenAI token limits during indexing. +- Memory: probe sqlite-vec availability in `clawdbot memory status`. +- Exec approvals: enforce allowlist when ask is off. +- Exec approvals: prefer raw command for node approvals/events. +- Tools: show exec elevated flag before the command and keep it outside markdown in tool summaries. +- Tools: return a companion-app-required message when node exec is requested with no paired node. +- Tools: return a companion-app-required message when `system.run` is requested without a supporting node. +- Exec: default gateway/node exec security to allowlist when unset (sandbox stays deny). +- Exec: prefer bash when fish is default shell, falling back to sh if bash is missing. (#1297) +- Exec: merge login-shell PATH for host=gateway exec while keeping daemon PATH minimal. (#1304) +- Streaming: emit assistant deltas for OpenAI-compatible SSE chunks. (#1147) +- Discord: make resolve warnings avoid raw JSON payloads on rate limits. +- Discord: process message handlers in parallel across sessions to avoid event queue blocking. (#1295) +- Discord: stop reconnecting the gateway after aborts to prevent duplicate listeners. +- Discord: only emit slow listener warnings after 30s. +- Discord: inherit parent channel allowlists for thread slash commands and reactions. (#1123) +- Telegram: honor pairing allowlists for native slash commands. +- Telegram: preserve hidden text_link URLs by expanding entities in inbound text. (#1118) +- Slack: resolve Bolt import interop for Bun + Node. (#1191) +- Web search: infer Perplexity base URL from API key source (direct vs OpenRouter). +- Web fetch: harden SSRF protection with shared hostname checks and redirect limits. (#1346) +- Browser: register AI snapshot refs for act commands. (#1282) +- Voice call: include request query in Twilio webhook verification when publicUrl is set. (#864) +- Anthropic: default API prompt caching to 1h with configurable TTL override. +- Anthropic: ignore TTL for OAuth. +- Auth profiles: keep auto-pinned preference while allowing rotation on failover. (#1138) +- Auth profiles: user pins stay locked. (#1138) +- Model catalog: avoid caching import failures, log transient discovery errors, and keep partial results. (#1332) +- Tests: stabilize Windows gateway/CLI tests by skipping sidecars, normalizing argv, and extending timeouts. +- Tests: stabilize plugin SDK resolution and embedded agent timeouts. +- Windows: install gateway scheduled task as the current user. +- Windows: show friendly guidance instead of failing on access denied. +- macOS: load menu session previews asynchronously so items populate while the menu is open. +- macOS: use label colors for session preview text so previews render in menu subviews. +- macOS: suppress usage error text in the menubar cost view. +- macOS: Doctor repairs LaunchAgent bootstrap issues for Gateway + Node when listed but not loaded. (#1166) +- macOS: avoid touching launchd in Remote over SSH so quitting the app no longer disables the remote gateway. (#1105) +- macOS: bundle Textual resources in packaged app builds to avoid code block crashes. (#1006) +- Daemon: include HOME in service environments to avoid missing HOME errors. (#1214) + +Thanks @AlexMikhalev, @CoreyH, @John-Rood, @KrauseFx, @MaudeBot, @Nachx639, @NicholaiVogel, @RyanLisse, @ThePickle31, @VACInc, @Whoaa512, @YuriNachos, @aaronveklabs, @abdaraxus, @alauppe, @ameno-, @artuskg, @austinm911, @bradleypriest, @cheeeee, @dougvk, @fogboots, @gnarco, @gumadeiras, @jdrhyne, @joelklabo, @longmaba, @mukhtharcm, @odysseus0, @oscargavin, @rhjoh, @sebslight, @sibbl, @sleontenko, @steipete, @suminhthanh, @thewilloftheshadow, @tyler6204, @vignesh07, @visionik, @ysqander, @zerone0x. + +## 2026.1.16-2 + +### Changes +- CLI: stamp build commit into dist metadata so banners show the commit in npm installs. +- CLI: close memory manager after memory commands to avoid hanging processes. (#1127) — thanks @NicholasSpisak. + +## 2026.1.16-1 + +### Highlights +- Hooks: add hooks system with bundled hooks, CLI tooling, and docs. (#1028) — thanks @ThomsenDrake. https://docs.clawd.bot/hooks +- Media: add inbound media understanding (image/audio/video) with provider + CLI fallbacks. https://docs.clawd.bot/nodes/media-understanding +- Plugins: add Zalo Personal plugin (`@clawdbot/zalouser`) and unify channel directory for plugins. (#1032) — thanks @suminhthanh. https://docs.clawd.bot/plugins/zalouser +- Models: add Vercel AI Gateway auth choice + onboarding updates. (#1016) — thanks @timolins. https://docs.clawd.bot/providers/vercel-ai-gateway +- Sessions: add `session.identityLinks` for cross-platform DM session li nking. (#1033) — thanks @thewilloftheshadow. https://docs.clawd.bot/concepts/session +- Web search: add `country`/`language` parameters (schema + Brave API) and docs. (#1046) — thanks @YuriNachos. https://docs.clawd.bot/tools/web + +### Breaking +- **BREAKING:** `clawdbot message` and message tool now require `target` (dropping `to`/`channelId` for destinations). (#1034) — thanks @tobalsan. +- **BREAKING:** Channel auth now prefers config over env for Discord/Telegram/Matrix (env is fallback only). (#1040) — thanks @thewilloftheshadow. +- **BREAKING:** Drop legacy `chatType: "room"` support; use `chatType: "channel"`. +- **BREAKING:** remove legacy provider-specific target resolution fallbacks; target resolution is centralized with plugin hints + directory lookups. +- **BREAKING:** `clawdbot hooks` is now `clawdbot webhooks`; hooks live under `clawdbot hooks`. https://docs.clawd.bot/cli/webhooks +- **BREAKING:** `clawdbot plugins install ` now copies into `~/.clawdbot/extensions` (use `--link` to keep path-based loading). + +### Changes +- Plugins: ship bundled plugins disabled by default and allow overrides by installed versions. (#1066) — thanks @ItzR3NO. +- Plugins: add bundled Antigravity + Gemini CLI OAuth + Copilot Proxy provider plugins. (#1066) — thanks @ItzR3NO. +- Tools: improve `web_fetch` extraction using Readability (with fallback). +- Tools: add Firecrawl fallback for `web_fetch` when configured. +- Tools: send Chrome-like headers by default for `web_fetch` to improve extraction on bot-sensitive sites. +- Tools: Firecrawl fallback now uses bot-circumvention + cache by default; remove basic HTML fallback when extraction fails. +- Tools: default `exec` exit notifications and auto-migrate legacy `tools.bash` to `tools.exec`. +- Tools: add `exec` PTY support for interactive sessions. https://docs.clawd.bot/tools/exec +- Tools: add tmux-style `process send-keys` and bracketed paste helpers for PTY sessions. +- Tools: add `process submit` helper to send CR for PTY sessions. +- Tools: respond to PTY cursor position queries to unblock interactive TUIs. +- Tools: include tool outputs in verbose mode and expand verbose tool feedback. +- Skills: update coding-agent guidance to prefer PTY-enabled exec runs and simplify tmux usage. +- TUI: refresh session token counts after runs complete or fail. (#1079) — thanks @d-ploutarchos. +- Status: trim `/status` to current-provider usage only and drop the OAuth/token block. +- Directory: unify `clawdbot directory` across channels and plugin channels. +- UI: allow deleting sessions from the Control UI. +- Memory: add sqlite-vec vector acceleration with CLI status details. +- Memory: add experimental session transcript indexing for memory_search (opt-in via memorySearch.experimental.sessionMemory + sources). +- Skills: add user-invocable skill commands and expanded skill command registration. +- Telegram: default reaction level to minimal and enable reaction notifications by default. +- Telegram: allow reply-chain messages to bypass mention gating in groups. (#1038) — thanks @adityashaw2. +- iMessage: add remote attachment support for VM/SSH deployments. +- Messages: refresh live directory cache results when resolving targets. +- Messages: mirror delivered outbound text/media into session transcripts. (#1031) — thanks @TSavo. +- Messages: avoid redundant sender envelopes for iMessage + Signal group chats. (#1080) — thanks @tyler6204. +- Media: normalize Deepgram audio upload bytes for fetch compatibility. +- Cron: isolated cron jobs now start a fresh session id on every run to prevent context buildup. +- Docs: add `/help` hub, Node/npm PATH guide, and expand directory CLI docs. +- Config: support env var substitution in config values. (#1044) — thanks @sebslight. +- Health: add per-agent session summaries and account-level health details, and allow selective probes. (#1047) — thanks @gumadeiras. +- Hooks: add hook pack installs (npm/path/zip/tar) with `clawdbot.hooks` manifests and `clawdbot hooks install/update`. +- Plugins: add zip installs and `--link` to avoid copying local paths. + +### Fixes +- macOS: drain subprocess pipes before waiting to avoid deadlocks. (#1081) — thanks @thesash. +- Verbose: wrap tool summaries/output in markdown only for markdown-capable channels. +- Tools: include provider/session context in elevated exec denial errors. +- Tools: normalize exec tool alias naming in tool error logs. +- Logging: reuse shared ANSI stripping to keep console capture lint-clean. +- Logging: prefix nested agent output with session/run/channel context. +- Telegram: accept tg/group/telegram prefixes + topic targets for inline button validation. (#1072) — thanks @danielz1z. +- Telegram: split long captions into follow-up messages. +- Config: block startup on invalid config, preserve best-effort doctor config, and keep rolling config backups. (#1083) — thanks @mukhtharcm. +- Sub-agents: normalize announce delivery origin + queue bucketing by accountId to keep multi-account routing stable. (#1061, #1058) — thanks @adam91holt. +- Sessions: include deliveryContext in sessions.list and reuse normalized delivery routing for announce/restart fallbacks. (#1058) +- Sessions: propagate deliveryContext into last-route updates to keep account/channel routing stable. (#1058) +- Sessions: preserve overrides on `/new` reset. +- Memory: prevent unhandled rejections when watch/interval sync fails. (#1076) — thanks @roshanasingh4. +- Memory: avoid gateway crash when embeddings return 429/insufficient_quota (disable tool + surface error). (#1004) +- Gateway: honor explicit delivery targets without implicit accountId fallback; preserve lastAccountId for implicit routing. +- Gateway: avoid reusing last-to/accountId when the requested channel differs; sync deliveryContext with last route fields. +- Build: allow `@lydell/node-pty` builds on supported platforms. +- Repo: fix oxlint config filename and move ignore pattern into config. (#1064) — thanks @connorshea. +- Messages: `/stop` now hard-aborts queued followups and sub-agent runs; suppress zero-count stop notes. +- Messages: honor message tool channel when deduping sends. +- Messages: include sender labels for live group messages across channels, matching queued/history formatting. (#1059) +- Sessions: reset `compactionCount` on `/new` and `/reset`, and preserve `sessions.json` file mode (0600). +- Sessions: repair orphaned user turns before embedded prompts. +- Sessions: hard-stop `sessions.delete` cleanup. +- Channels: treat replies to the bot as implicit mentions across supported channels. +- Channels: normalize object-format capabilities in channel capability parsing. +- Security: default-deny slash/control commands unless a channel computed `CommandAuthorized` (fixes accidental “open” behavior), and ensure WhatsApp + Zalo plugin channels gate inline `/…` tokens correctly. https://docs.clawd.bot/gateway/security +- Security: redact sensitive text in gateway WS logs. +- Tools: cap pending `exec` process output to avoid unbounded buffers. +- CLI: speed up `clawdbot sandbox-explain` by avoiding heavy plugin imports when normalizing channel ids. +- Browser: remote profile tab operations prefer persistent Playwright and avoid silent HTTP fallbacks. (#1057) — thanks @mukhtharcm. +- Browser: remote profile tab ops follow-up: shared Playwright loader, Playwright-based focus, and more coverage (incl. opt-in live Browserless test). (follow-up to #1057) — thanks @mukhtharcm. +- Browser: refresh extension relay tab metadata after navigation so `/json/list` stays current. (#1073) — thanks @roshanasingh4. +- WhatsApp: scope self-chat response prefix; inject pending-only group history and clear after any processed message. +- WhatsApp: include `linked` field in `describeAccount`. +- Agents: drop unsigned Gemini tool calls and avoid JSON Schema `format` keyword collisions. +- Agents: hide the image tool when the primary model already supports images. +- Agents: avoid duplicate sends by replying with `NO_REPLY` after `message` tool sends. +- Auth: inherit/merge sub-agent auth profiles from the main agent. +- Gateway: resolve local auth for security probe and validate gateway token/password file modes. (#1011, #1022) — thanks @ivanrvpereira, @kkarimi. +- Signal/iMessage: bound transport readiness waits to 30s with periodic logging. (#1014) — thanks @Szpadel. +- iMessage: avoid RPC restart loops. +- OpenAI image-gen: handle URL + `b64_json` responses and remove deprecated `response_format` (use URL downloads). +- CLI: auto-update global installs when installed via a package manager. +- Routing: migrate legacy `accountID` bindings to `accountId` and remove legacy fallback lookups. (#1047) — thanks @gumadeiras. +- Discord: truncate skill command descriptions to 100 chars for slash command limits. (#1018) — thanks @evalexpr. +- Security: bump `tar` to 7.5.3. +- Models: align ZAI thinking toggles. +- iMessage/Signal: include sender metadata for non-queued group messages. (#1059) +- Discord: preserve whitespace when chunking long lines so message splits keep spacing intact. +- Skills: fix skills watcher ignored list typing (tsc). + +## 2026.1.15 ### Highlights - Plugins: add provider auth registry + `clawdbot models auth login` for plugin-driven OAuth/API key flows. @@ -11,17 +581,24 @@ ### Breaking - **BREAKING:** iOS minimum version is now 18.0 to support Textual markdown rendering in native chat. (#702) - **BREAKING:** Microsoft Teams is now a plugin; install `@clawdbot/msteams` via `clawdbot plugins install @clawdbot/msteams`. +- **BREAKING:** Channel auth now prefers config over env for Discord/Telegram/Matrix (env is fallback only). (#1040) — thanks @thewilloftheshadow. ### Changes +- UI/Apps: move channel/config settings to schema-driven forms and rename Connections → Channels. (#1040) — thanks @thewilloftheshadow. - CLI: set process titles to `clawdbot-` for clearer process listings. - CLI/macOS: sync remote SSH target/identity to config and let `gateway status` auto-infer SSH targets (ssh-config aware). +- Telegram: scope inline buttons with allowlist default + callback gating in DMs/groups. +- Telegram: default reaction notifications to own. +- Tools: improve `web_fetch` extraction using Readability (with fallback). - Heartbeat: tighten prompt guidance + suppress duplicate alerts for 24h. (#980) — thanks @voidserf. +- Repo: ignore local identity files to avoid accidental commits. (#1001) — thanks @gerardward2007. - Sessions/Security: add `session.dmScope` for multi-user DM isolation and audit warnings. (#948) — thanks @Alphonse-arianee. - Plugins: add provider auth registry + `clawdbot models auth login` for plugin-driven OAuth/API key flows. - Onboarding: switch channels setup to a single-select loop with per-channel actions and disabled hints in the picker. - TUI: show provider/model labels for the active session and default model. - Heartbeat: add per-agent heartbeat configuration and multi-agent docs example. - UI: show gateway auth guidance + doc link on unauthorized Control UI connections. +- UI: add session deletion action in Control UI sessions list. (#1017) — thanks @Szpadel. - Security: warn on weak model tiers (Haiku, below GPT-5, below Claude 4.5) in `clawdbot security audit`. - Apps: store node auth tokens encrypted (Keychain/SecurePrefs). - Daemon: share profile/state-dir resolution across service helpers and honor `CLAWDBOT_STATE_DIR` for Windows task scripts. @@ -46,6 +623,17 @@ - Discord: allow emoji/sticker uploads + channel actions in config defaults. (#870) — thanks @JDIVE. ### Fixes +- Messages: make `/stop` clear queued followups and pending session lane work for a hard abort. +- Messages: make `/stop` abort active sub-agent runs spawned from the requester session and report how many were stopped. +- WhatsApp: report linked status consistently in channel status. (#1050) — thanks @YuriNachos. +- Sessions: keep per-session overrides when `/new` resets compaction counters. (#1050) — thanks @YuriNachos. +- Skills: allow OpenAI image-gen helper to handle URL or base64 responses. (#1050) — thanks @YuriNachos. +- WhatsApp: default response prefix only for self-chat, using identity name when set. +- Signal/iMessage: bound transport readiness waits to 30s with periodic logging. (#1014) — thanks @Szpadel. +- iMessage: treat missing `imsg rpc` support as fatal to avoid restart loops. +- Auth: merge main auth profiles into per-agent stores for sub-agents and document inheritance. (#1013) — thanks @marcmarg. +- Agents: avoid JSON Schema `format` collisions in tool params by renaming snapshot format fields. (#1013) — thanks @marcmarg. +- Fix: make `clawdbot update` auto-update global installs when installed via a package manager. - Fix: list model picker entries as provider/model pairs for explicit selection. (#970) — thanks @mcinteerj. - Fix: align OpenAI image-gen defaults with DALL-E 3 standard quality and document output formats. (#880) — thanks @mkbehr. - Fix: persist `gateway.mode=local` after selecting Local run mode in `clawdbot configure`, even if no other sections are chosen. @@ -57,6 +645,7 @@ - Fix: refactor session store updates, add chat.inject, and harden subagent cleanup flow. (#944) — thanks @tyler6204. - Fix: clean up suspended CLI processes across backends. (#978) — thanks @Nachx639. - Fix: support MiniMax coding plan usage responses with `model_remains`/`current_interval_*` payloads. +- Fix: honor message tool channel for duplicate suppression (prefer `NO_REPLY` after `message` tool sends). (#1053) — thanks @sashcatanzarite. - Fix: suppress WhatsApp pairing replies for historical catch-up DMs on initial link. (#904) - Browser: extension mode recovers when only one tab is attached (stale targetId fallback). - Browser: fix `tab not found` for extension relay snapshots/actions when Playwright blocks `newCDPSession` (use the single available Page). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7b37ea389..d6eb0532f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,3 +40,13 @@ Please include in your PR: - [ ] Confirm you understand what the code does AI PRs are first-class citizens here. We just want transparency so reviewers know what to look for. + +## Current Focus & Roadmap 🗺 + +We are currently prioritizing: +- **Stability**: Fixing edge cases in channel connections (WhatsApp/Telegram). +- **UX**: Improving the onboarding wizard and error messages. +- **Skills**: Expanding the library of bundled skills and improving the Skill Creation developer experience. +- **Performance**: Optimizing token usage and compaction logic. + +Check the [GitHub Issues](https://github.com/clawdbot/clawdbot/issues) for "good first issue" labels! diff --git a/Peekaboo b/Peekaboo deleted file mode 160000 index 5c195f5e4..000000000 --- a/Peekaboo +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5c195f5e46ebfcc953af74fdd05fbc962d05a50c diff --git a/README.md b/README.md index c288d6858..217a4b61c 100644 --- a/README.md +++ b/README.md @@ -11,12 +11,13 @@

CI status GitHub release + DeepWiki Discord MIT License

**Clawdbot** is a *personal AI assistant* you run on your own devices. -It answers you on the channels you already use (WhatsApp, Telegram, Slack, Discord, Signal, iMessage, Microsoft Teams, WebChat), can speak and listen on macOS/iOS/Android, and can render a live Canvas you control. The Gateway is just the control plane — the product is the assistant. +It answers you on the channels you already use (WhatsApp, Telegram, Slack, Discord, Google Chat, Signal, iMessage, Microsoft Teams, WebChat), plus extension channels like BlueBubbles, Matrix, Zalo, and Zalo Personal. It can speak and listen on macOS/iOS/Android, and can render a live Canvas you control. The Gateway is just the control plane — the product is the assistant. If you want a personal, single-user assistant that feels local, fast, and always-on, this is it. @@ -64,12 +65,21 @@ clawdbot gateway --port 18789 --verbose # Send a message clawdbot message send --to +1234567890 --message "Hello from Clawdbot" -# Talk to the assistant (optionally deliver back to WhatsApp/Telegram/Slack/Discord/Microsoft Teams) +# Talk to the assistant (optionally deliver back to any connected channel: WhatsApp/Telegram/Slack/Discord/Google Chat/Signal/iMessage/BlueBubbles/Microsoft Teams/Matrix/Zalo/Zalo Personal/WebChat) clawdbot agent --message "Ship checklist" --thinking high ``` Upgrading? [Updating guide](https://docs.clawd.bot/install/updating) (and run `clawdbot doctor`). +## Development channels + +- **stable**: tagged releases (`vYYYY.M.D` or `vYYYY.M.D-`), npm dist-tag `latest`. +- **beta**: prerelease tags (`vYYYY.M.D-beta.N`), npm dist-tag `beta` (macOS app may be missing). +- **dev**: moving head of `main`, npm dist-tag `dev` (when published). + +Switch channels (git + npm): `clawdbot update --channel stable|beta|dev`. +Details: [Development channels](https://docs.clawd.bot/install/development-channels). + ## From source (development) Prefer `pnpm` for builds from source. Bun is optional for running TypeScript directly. @@ -96,7 +106,7 @@ Clawdbot connects to real messaging surfaces. Treat inbound DMs as **untrusted i Full security guide: [Security](https://docs.clawd.bot/gateway/security) -Default behavior on Telegram/WhatsApp/Signal/iMessage/Microsoft Teams/Discord/Slack: +Default behavior on Telegram/WhatsApp/Signal/iMessage/Microsoft Teams/Discord/Google Chat/Slack: - **DM pairing** (`dmPolicy="pairing"` / `channels.discord.dm.policy="pairing"` / `channels.slack.dm.policy="pairing"`): unknown senders receive a short pairing code and the bot does not process their message. - Approve with: `clawdbot pairing approve ` (then the sender is added to a local allowlist store). - Public inbound DMs require an explicit opt-in: set `dmPolicy="open"` and include `"*"` in the channel allowlist (`allowFrom` / `channels.discord.dm.allowFrom` / `channels.slack.dm.allowFrom`). @@ -106,7 +116,7 @@ Run `clawdbot doctor` to surface risky/misconfigured DM policies. ## Highlights - **[Local-first Gateway](https://docs.clawd.bot/gateway)** — single control plane for sessions, channels, tools, and events. -- **[Multi-channel inbox](https://docs.clawd.bot/channels)** — WhatsApp, Telegram, Slack, Discord, Signal, iMessage, Microsoft Teams, WebChat, macOS, iOS/Android. +- **[Multi-channel inbox](https://docs.clawd.bot/channels)** — WhatsApp, Telegram, Slack, Discord, Google Chat, Signal, iMessage, BlueBubbles, Microsoft Teams, Matrix, Zalo, Zalo Personal, WebChat, macOS, iOS/Android. - **[Multi-agent routing](https://docs.clawd.bot/gateway/configuration)** — route inbound channels/accounts/peers to isolated agents (workspaces + per-agent sessions). - **[Voice Wake](https://docs.clawd.bot/nodes/voicewake) + [Talk Mode](https://docs.clawd.bot/nodes/talk)** — always-on speech for macOS/iOS/Android with ElevenLabs. - **[Live Canvas](https://docs.clawd.bot/platforms/mac/canvas)** — agent-driven visual workspace with [A2UI](https://docs.clawd.bot/platforms/mac/canvas#canvas-a2ui). @@ -128,7 +138,7 @@ Run `clawdbot doctor` to surface risky/misconfigured DM policies. - [Media pipeline](https://docs.clawd.bot/nodes/images): images/audio/video, transcription hooks, size caps, temp file lifecycle. Audio details: [Audio](https://docs.clawd.bot/nodes/audio). ### Channels -- [Channels](https://docs.clawd.bot/channels): [WhatsApp](https://docs.clawd.bot/channels/whatsapp) (Baileys), [Telegram](https://docs.clawd.bot/channels/telegram) (grammY), [Slack](https://docs.clawd.bot/channels/slack) (Bolt), [Discord](https://docs.clawd.bot/channels/discord) (discord.js), [Signal](https://docs.clawd.bot/channels/signal) (signal-cli), [iMessage](https://docs.clawd.bot/channels/imessage) (imsg), [Microsoft Teams](https://docs.clawd.bot/channels/msteams) (Bot Framework), [WebChat](https://docs.clawd.bot/web/webchat). +- [Channels](https://docs.clawd.bot/channels): [WhatsApp](https://docs.clawd.bot/channels/whatsapp) (Baileys), [Telegram](https://docs.clawd.bot/channels/telegram) (grammY), [Slack](https://docs.clawd.bot/channels/slack) (Bolt), [Discord](https://docs.clawd.bot/channels/discord) (discord.js), [Google Chat](https://docs.clawd.bot/channels/googlechat) (Chat API), [Signal](https://docs.clawd.bot/channels/signal) (signal-cli), [iMessage](https://docs.clawd.bot/channels/imessage) (imsg), [BlueBubbles](https://docs.clawd.bot/channels/bluebubbles) (extension), [Microsoft Teams](https://docs.clawd.bot/channels/msteams) (extension), [Matrix](https://docs.clawd.bot/channels/matrix) (extension), [Zalo](https://docs.clawd.bot/channels/zalo) (extension), [Zalo Personal](https://docs.clawd.bot/channels/zalouser) (extension), [WebChat](https://docs.clawd.bot/web/webchat). - [Group routing](https://docs.clawd.bot/concepts/group-messages): mention gating, reply tags, per-channel chunking and routing. Channel rules: [Channels](https://docs.clawd.bot/channels). ### Apps + nodes @@ -159,7 +169,7 @@ Run `clawdbot doctor` to surface risky/misconfigured DM policies. ## How it works (short) ``` -WhatsApp / Telegram / Slack / Discord / Signal / iMessage / Microsoft Teams / WebChat +WhatsApp / Telegram / Slack / Discord / Google Chat / Signal / iMessage / BlueBubbles / Microsoft Teams / Matrix / Zalo / Zalo Personal / WebChat │ ▼ ┌───────────────────────────────┐ @@ -242,14 +252,14 @@ ClawdHub is a minimal skill registry. With ClawdHub enabled, the agent can searc ## Chat commands -Send these in WhatsApp/Telegram/Slack/Microsoft Teams/WebChat (group commands are owner-only): +Send these in WhatsApp/Telegram/Slack/Google Chat/Microsoft Teams/WebChat (group commands are owner-only): - `/status` — compact session status (model + tokens, cost when available) - `/new` or `/reset` — reset the session - `/compact` — compact session context (summary) - `/think ` — off|minimal|low|medium|high|xhigh (GPT-5.2 + Codex models only) - `/verbose on|off` -- `/cost on|off` — append per-response token/cost usage lines +- `/usage off|tokens|full` — per-response usage footer - `/restart` — restart the gateway (owner-only in groups) - `/activation mention|always` — group activation toggle (groups only) @@ -257,12 +267,7 @@ Send these in WhatsApp/Telegram/Slack/Microsoft Teams/WebChat (group commands ar The Gateway alone delivers a great experience. All apps are optional and add extra features. -If you plan to build/run companion apps, initialize submodules first: - -```bash -git submodule update --init --recursive -./scripts/restart-mac.sh -``` +If you plan to build/run companion apps, follow the platform runbooks below. ### macOS (Clawdbot.app) (optional) @@ -454,7 +459,7 @@ Use these when you’re past the onboarding flow and want the deeper reference. ## Clawd -Clawdbot was built for **Clawd**, a space lobster AI assistant. 🦞 +Clawdbot was built for **Clawd**, a space lobster AI assistant. 🦞 by Peter Steinberger and the community. - [clawd.me](https://clawd.me) @@ -463,34 +468,43 @@ by Peter Steinberger and the community. ## Community -See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines, maintainers, and how to submit PRs. +See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines, maintainers, and how to submit PRs. AI/vibe-coded PRs welcome! 🤖 -Special thanks to @andrewting19 for the Anthropic OAuth tool-name fix. - -Core contributors: -- @cpojer — Telegram onboarding UX + docs +Special thanks to [Mario Zechner](https://mariozechner.at/) for his support and for +[pi-mono](https://github.com/badlogic/pi-mono). Thanks to all clawtributors:

- steipete bohdanpodvirnyi joaohlisboa mneves75 rahthakor vrknetha joshp123 mukhtharcm maxsumrall xadenryan - Tobias Bischoff juanpablodlc hsrvc magimetal meaningfool NicholasSpisak abhisekbasu1 claude jamesgroat Hyaxia - dantelex daveonkels radek-paclt mteam88 Eng. Juan Combetto dbhurley Mariano Belinky julianengel benithors nachx639 - sreekaransrinath gupsammy cristip73 nachoiacovino Vasanth Rao Naik Sabavat lc0rp scald andranik-sahakyan davidguttman sleontenko - sircrumpet peschee rafaelreis-r ratulsarna lutr0 thewilloftheshadow gumadeiras emanuelst KristijanJovanovski CashWilliams - rdev osolmaz kiranjd sebslight sheeek onutc manuelhettich minghinmatthewlam myfunc buddyh - mcinteerj timkrase obviyus azade-c bjesuiter danielz1z Josh Phillips roshanasingh4 superman32432432 Yurii Chukhlib - antons austinm911 blacksmith-sh[bot] grp06 HeimdallStrategy imfing jalehman jarvis-medmatic mahmoudashraf93 petter-b - pkrmf RandyVentures dan-dr erikpr1994 jonasjancarik Keith the Silly Goose kkarimi L36 Server mitschabaude-bot neist - chrisrodz Friederike Seiler gabriel-trigo iamadig Kit koala73 manmal ngutman ogulcancelik pasogott - petradonka VACInc zats Chris Taylor Django Navarro pcty-nextgen-service-account rubyrunsstuff Syhids Aaron Konyer adam91holt - erik-agens evalexpr fcatuhe henrino3 jayhickey jeffersonwarrior jeffersonwarrior Jonathan D. Rhyne (DJ-D) jverdi mickahouan - mjrussell oswalpalash p6l-richard philipp-spiess robaxelsen Sash Catanzarite VAC zknicker alejandro maza andrewting19 - Asleep123 bolismauro cash-echo-bot Clawd conhecendocontato Drake Thomsen gtsifrikas HazAT hrdwdmrbl hugobarauna - Jarvis Jefferson Nunn kitze levifig Lloyd loukotal Marc martinpucik Miles mrdbstn - MSch Mustafa Tag Eldeen ndraiman nexty5870 prathamdby reeltimeapps RLTCmpe Rolf Fredheim Rony Kelner Samrat Jha - siraht snopoke The Admiral voidserf wes-davis wstock YuriNachos Zach Knickerbocker Alphonse-arianee Azade - carlulsoe cpojer ddyo Erik latitudeki5223 longmaba Manuel Maly Mourad Boustani pcty-nextgen-ios-builder Quentin - Randy Torres ronak-guliani thesash William Stock + steipete plum-dawg bohdanpodvirnyi iHildy joaohlisboa mneves75 MatthieuBizien MaudeBot Glucksberg rahthakor + vrknetha radek-paclt Tobias Bischoff joshp123 czekaj mukhtharcm sebslight maxsumrall xadenryan rodrigouroz + juanpablodlc hsrvc magimetal meaningfool tyler6204 patelhiren NicholasSpisak jonisjongithub zerone0x abhisekbasu1 + jamesgroat claude JustYannicc Hyaxia dantelex SocialNerd42069 daveonkels google-labs-jules[bot] lc0rp mousberg + vignesh07 mteam88 dbhurley Mariano Belinky Eng. Juan Combetto TSavo julianengel bradleypriest benithors rohannagpal + timolins f-trycua benostein nachx639 pvoo sreekaransrinath gupsammy cristip73 stefangalescu nachoiacovino + Vasanth Rao Naik Sabavat petter-b cpojer scald gumadeiras andranik-sahakyan davidguttman sleontenko denysvitali orlyjamie + thewilloftheshadow sircrumpet peschee rafaelreis-r ratulsarna lutr0 danielz1z emanuelst KristijanJovanovski rdev + joshrad-dev kiranjd osolmaz adityashaw2 CashWilliams sheeek artuskg Takhoffman onutc pauloportella + neooriginal manuelhettich minghinmatthewlam myfunc travisirby buddyh connorshea kyleok mcinteerj dependabot[bot] + John-Rood timkrase uos-status gerardward2007 obviyus roshanasingh4 tosh-hamburg azade-c JonUleis bjesuiter + cheeeee Josh Phillips robbyczgw-cla dlauer pookNast Whoaa512 YuriNachos chriseidhof ngutman ysqander + aj47 superman32432432 Yurii Chukhlib grp06 antons austinm911 blacksmith-sh[bot] damoahdominic dan-dr HeimdallStrategy + imfing jalehman jarvis-medmatic kkarimi mahmoudashraf93 pkrmf RandyVentures Ryan Lisse dougvk erikpr1994 + Ghost jonasjancarik Keith the Silly Goose L36 Server Marc mitschabaude-bot mkbehr neist sibbl chrisrodz + Friederike Seiler gabriel-trigo iamadig Jonathan D. Rhyne (DJ-D) Kit koala73 manmal ogulcancelik pasogott petradonka + rubyrunsstuff siddhantjain suminhthanh svkozak VACInc wes-davis zats 24601 adam91holt ameno- + Chris Taylor Django Navarro evalexpr henrino3 humanwritten larlyssa odysseus0 oswalpalash pcty-nextgen-service-account rmorse + Syhids Aaron Konyer aaronveklabs andreabadesso Andrii cash-echo-bot Clawd ClawdFx dguido EnzeD + erik-agens Evizero fcatuhe itsjaydesu ivancasco ivanrvpereira jayhickey jeffersonwarrior jeffersonwarrior jverdi + longmaba mickahouan mjrussell odnxe p6l-richard philipp-spiess robaxelsen Sash Catanzarite T5-AndyML travisp + VAC william arzt zknicker abhaymundhara alejandro maza andrewting19 anpoirier arthyn Asleep123 bolismauro + conhecendoia dasilva333 Developer Dimitrios Ploutarchos Drake Thomsen fal3 Felix Krause foeken ganghyun kim grrowl + gtsifrikas HazAT hrdwdmrbl hugobarauna Jamie Openshaw Jarvis Jefferson Nunn Kevin Lin kitze levifig + Lloyd loukotal louzhixian martinpucik Matt mini Miles mrdbstn MSch Mustafa Tag Eldeen ndraiman + nexty5870 Noctivoro prathamdby ptn1411 reeltimeapps RLTCmpe Rolf Fredheim Rony Kelner Samrat Jha senoldogann + Seredeep sergical shiv19 shiyuanhai siraht snopoke testingabc321 The Admiral thesash Ubuntu + voidserf Vultr-Clawd Admin Wimmie wstock yazinsai ymat19 Zach Knickerbocker 0xJonHoldsCrypto aaronn Alphonse-arianee + atalovesyou Azade carlulsoe ddyo Erik hougangdev latitudeki5223 Manuel Maly Mourad Boustani odrobnik + pcty-nextgen-ios-builder Quentin Randy Torres rhjoh ronak-guliani William Stock

diff --git a/SECURITY.md b/SECURITY.md index d2af462ba..43d493996 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -12,4 +12,3 @@ If you believe you’ve found a security issue in Clawdbot, please report it pri For threat model + hardening guidance (including `clawdbot security audit --deep` and `--fix`), see: - `https://docs.clawd.bot/gateway/security` - diff --git a/Swabble/Package.resolved b/Swabble/Package.resolved index 2b2b7f857..24de6ea3a 100644 --- a/Swabble/Package.resolved +++ b/Swabble/Package.resolved @@ -1,13 +1,13 @@ { - "originHash" : "5d29ee82825e0764775562242cfa1ff4dc79584797dd638f76c9876545454748", + "originHash" : "c0677e232394b5f6b0191b6dbb5bae553d55264f65ae725cd03a8ffdfda9cdd3", "pins" : [ { - "identity" : "elevenlabskit", + "identity" : "commander", "kind" : "remoteSourceControl", - "location" : "https://github.com/steipete/ElevenLabsKit", + "location" : "https://github.com/steipete/Commander.git", "state" : { - "revision" : "c8679fbd37416a8780fe43be88a497ff16209e2d", - "version" : "0.1.0" + "revision" : "9e349575c8e3c6745e81fe19e5bb5efa01b078ce", + "version" : "0.2.1" } }, { diff --git a/Swabble/Package.swift b/Swabble/Package.swift index 70448139e..9f5a00036 100644 --- a/Swabble/Package.swift +++ b/Swabble/Package.swift @@ -13,7 +13,7 @@ let package = Package( .executable(name: "swabble", targets: ["SwabbleCLI"]), ], dependencies: [ - .package(path: "../Peekaboo/Commander"), + .package(url: "https://github.com/steipete/Commander.git", exact: "0.2.1"), .package(url: "https://github.com/apple/swift-testing", from: "0.99.0"), ], targets: [ diff --git a/Swabble/README.md b/Swabble/README.md index 7a5015460..bf6dc3dc8 100644 --- a/Swabble/README.md +++ b/Swabble/README.md @@ -101,8 +101,8 @@ Environment variables: - Authorization requested at first start; requires macOS 26 + new Speech.framework APIs. ## Development -- Format: `./scripts/format.sh` (uses ../peekaboo/.swiftformat if present) -- Lint: `./scripts/lint.sh` (uses ../peekaboo/.swiftlint.yml if present) +- Format: `./scripts/format.sh` (uses local `.swiftformat`) +- Lint: `./scripts/lint.sh` (uses local `.swiftlint.yml`) - Tests: `swift test` (uses swift-testing package) ## Roadmap diff --git a/Swabble/scripts/format.sh b/Swabble/scripts/format.sh index 0ce82a7fb..dd12e45bb 100755 --- a/Swabble/scripts/format.sh +++ b/Swabble/scripts/format.sh @@ -1,10 +1,5 @@ #!/bin/bash set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" -PEEKABOO_ROOT="${ROOT}/../peekaboo" -if [ -f "${PEEKABOO_ROOT}/.swiftformat" ]; then - CONFIG="${PEEKABOO_ROOT}/.swiftformat" -else - CONFIG="${ROOT}/.swiftformat" -fi +CONFIG="${ROOT}/.swiftformat" swiftformat --config "$CONFIG" "$ROOT/Sources" diff --git a/Swabble/scripts/lint.sh b/Swabble/scripts/lint.sh index 650f09176..d674628d0 100755 --- a/Swabble/scripts/lint.sh +++ b/Swabble/scripts/lint.sh @@ -1,12 +1,7 @@ #!/bin/bash set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" -PEEKABOO_ROOT="${ROOT}/../peekaboo" -if [ -f "${PEEKABOO_ROOT}/.swiftlint.yml" ]; then - CONFIG="${PEEKABOO_ROOT}/.swiftlint.yml" -else - CONFIG="$ROOT/.swiftlint.yml" -fi +CONFIG="${ROOT}/.swiftlint.yml" if ! command -v swiftlint >/dev/null; then echo "swiftlint not installed" >&2 exit 1 diff --git a/appcast.xml b/appcast.xml index 038abc8c4..8158ac244 100644 --- a/appcast.xml +++ b/appcast.xml @@ -3,209 +3,186 @@ Clawdbot - 2026.1.14-1 - Thu, 15 Jan 2026 11:14:40 +0000 + 2026.1.24-1 + Sun, 25 Jan 2026 14:05:25 +0000 https://raw.githubusercontent.com/clawdbot/clawdbot/main/appcast.xml - 5825 - 2026.1.14-1 + 7952 + 2026.1.24-1 15.0 - Clawdbot 2026.1.14-1 + Clawdbot 2026.1.24-1 +

Fixes

+
    +
  • Packaging: include dist/shared output in npm tarball (fixes missing reasoning-tags import on install).
  • +
+

View full changelog

+]]>
+ +
+ + 2026.1.24 + Sun, 25 Jan 2026 13:31:05 +0000 + https://raw.githubusercontent.com/clawdbot/clawdbot/main/appcast.xml + 7944 + 2026.1.24 + 15.0 + Clawdbot 2026.1.24

Highlights

    -
  • Web search: web_search/web_fetch tools (Brave API) + first-time setup in onboarding/configure.
  • -
  • Browser control: Chrome extension relay takeover mode + remote browser control via clawdbot browser serve.
  • -
  • Plugins: channel plugins (gateway HTTP hooks) + Zalo plugin + onboarding install flow. (#854) — thanks @longmaba.
  • -
  • Security: expanded clawdbot security audit (+ --fix), detect-secrets CI scan, and a SECURITY.md reporting policy.
  • +
  • Providers: Ollama discovery + docs; Venice guide upgrades + cross-links. (#1606) Thanks @abhaymundhara. https://docs.clawd.bot/providers/ollama https://docs.clawd.bot/providers/venice
  • +
  • Channels: LINE plugin (Messaging API) with rich replies + quick replies. (#1630) Thanks @plum-dawg.
  • +
  • TTS: Edge fallback (keyless) + /tts auto modes. (#1668, #1667) Thanks @steipete, @sebslight. https://docs.clawd.bot/tts
  • +
  • Exec approvals: approve in-chat via /approve across all channels (including plugins). (#1621) Thanks @czekaj. https://docs.clawd.bot/tools/exec-approvals https://docs.clawd.bot/tools/slash-commands
  • +
  • Telegram: DM topics as separate sessions + outbound link preview toggle. (#1597, #1700) Thanks @rohannagpal, @zerone0x. https://docs.clawd.bot/channels/telegram

Changes

-

Web Tools

    -
  • Tools: add web_search/web_fetch (Brave API), including helpful setup hints when the key is missing.
  • -
  • Tools: enable web_fetch by default (unless explicitly disabled in config).
  • -
  • CLI/Docs: add clawdbot configure --section web for storing Brave API keys and update onboarding tips.
  • -
-

Browser / Control UI

-
    -
  • Browser: add Chrome extension relay takeover mode (toolbar button) + clawdbot browser serve remote control + browser.controlToken.
  • -
  • Browser: ship a built-in chrome profile for extension relay and start the relay automatically when running locally.
  • -
  • Browser: default browser.defaultProfile to chrome (existing Chrome takeover mode).
  • -
  • Browser: add clawdbot browser extension install/path and copy extension path to clipboard.
  • -
  • Browser: add snapshot refs=aria (Playwright aria-ref ids) for self-resolving refs across snapshotact.
  • -
  • Browser: profile="chrome" now defaults to host control and returns clearer “attach a tab” errors.
  • -
  • Browser: extension mode recovers when only one tab is attached (stale targetId fallback).
  • -
  • Control UI: show raw any-map entries in config views; move Docs link into the left nav.
  • -
-

Plugins

-
    -
  • Plugins: add plugin HTTP hooks + loader updates to support channel plugins. (#854) — thanks @longmaba.
  • -
  • Plugins: add onboarding plugin install flow. (#854) — thanks @longmaba.
  • -
  • Channels: add Matrix plugin (external) with docs + onboarding hooks.
  • -
  • Voice Call: add Plivo provider (no SDK dependency). (#846) — thanks @vrknetha.
  • -
-

Security

-
    -
  • Security: expand clawdbot security audit checks and publish a SECURITY.md reporting policy.
  • -
  • Security: extend clawdbot security audit --fix to tighten more sensitive state paths.
  • -
  • Security: add detect-secrets CI scan and baseline guidance. (#227) — thanks @Hyaxia.
  • -
-

Onboarding / Daemon

-
    -
  • Onboarding: add a security checkpoint prompt (docs link + sandboxing hint); require --accept-risk for --non-interactive.
  • -
  • Daemon: support profile-aware service names for multi-gateway setups. (#671) — thanks @bjesuiter.
  • -
-

Auth / Usage / Config

-
    -
  • Usage: add MiniMax coding plan usage tracking.
  • -
  • Auth: label Claude Code CLI auth options. (#915) — thanks @SeanZoR.
  • -
  • Agents: add optional auth-profile copy prompt on agents add and improve auth error messaging.
  • -
  • Auth: add dynamic template variables to messages.responsePrefix. (#928) — thanks @sebslight.
  • -
  • Config: add channels..configWrites gating for channel-initiated config writes; migrate Slack channel IDs.
  • -
-

Channels

-
    -
  • Telegram: add message delete action in the message tool. (#903) — thanks @sleontenko.
  • -
  • WhatsApp: add channels.whatsapp.sendReadReceipts to disable auto read receipts. (#882) — thanks @chrisrodz.
  • -
-

Docs

-
    -
  • Docs: clarify per-agent auth stores, sandboxed skill binaries, and elevated semantics.
  • -
  • Docs: add FAQ entries for missing provider auth after adding agents and Gemini thinking signature errors.
  • -
  • Docs: expand gateway security hardening guidance and incident response checklist.
  • -
  • Docs: document DM history limits for channel DMs. (#883) — thanks @pkrmf.
  • -
  • Docs: standardize Claude Code CLI naming across docs and prompts. (follow-up to #915)
  • -
  • Docs: add per-command CLI doc pages and link them from clawdbot --help.
  • -
  • Docs: add multi-gateway guide (sidebar + nav).
  • +
  • Channels: add LINE plugin (Messaging API) with rich replies, quick replies, and plugin HTTP registry. (#1630) Thanks @plum-dawg.
  • +
  • TTS: add Edge TTS provider fallback, defaulting to keyless Edge with MP3 retry on format failures. (#1668) Thanks @steipete. https://docs.clawd.bot/tts
  • +
  • TTS: add auto mode enum (off/always/inbound/tagged) with per-session /tts override. (#1667) Thanks @sebslight. https://docs.clawd.bot/tts
  • +
  • Telegram: treat DM topics as separate sessions and keep DM history limits stable with thread suffixes. (#1597) Thanks @rohannagpal.
  • +
  • Telegram: add channels.telegram.linkPreview to toggle outbound link previews. (#1700) Thanks @zerone0x. https://docs.clawd.bot/channels/telegram
  • +
  • Web search: add Brave freshness filter parameter for time-scoped results. (#1688) Thanks @JonUleis. https://docs.clawd.bot/tools/web
  • +
  • UI: refresh Control UI dashboard design system (typography, colors, spacing). (#1786) Thanks @mousberg.
  • +
  • Exec approvals: forward approval prompts to chat with /approve for all channels (including plugins). (#1621) Thanks @czekaj. https://docs.clawd.bot/tools/exec-approvals https://docs.clawd.bot/tools/slash-commands
  • +
  • Gateway: expose config.patch in the gateway tool with safe partial updates + restart sentinel. (#1653) Thanks @Glucksberg.
  • +
  • Diagnostics: add diagnostic flags for targeted debug logs (config + env override). https://docs.clawd.bot/diagnostics/flags
  • +
  • Docs: expand FAQ (migration, scheduling, concurrency, model recommendations, OpenAI subscription auth, Pi sizing, hackable install, docs SSL workaround).
  • +
  • Docs: add verbose installer troubleshooting guidance.
  • +
  • Docs: add macOS VM guide with local/hosted options + VPS/nodes guidance. (#1693) Thanks @f-trycua.
  • +
  • Docs: add Bedrock EC2 instance role setup + IAM steps. (#1625) Thanks @sergical. https://docs.clawd.bot/bedrock
  • +
  • Docs: update Fly.io guide notes.
  • +
  • Dev: add prek pre-commit hooks + dependabot config for weekly updates. (#1720) Thanks @dguido.

Fixes

-

Gateway / Daemon / Sessions

    -
  • Gateway: forward termination signals to respawned CLI child processes to avoid orphaned systemd runs. (#933) — thanks @roshanasingh4.
  • -
  • Gateway/UI: ship session defaults in the hello snapshot so the Control UI canonicalizes main session keys (no bare main alias).
  • -
  • Agents: skip thinking/final tag stripping inside Markdown code spans. (#939) — thanks @ngutman.
  • -
  • Browser: add tests for snapshot labels/efficient query params and labeled image responses.
  • -
  • Browser: persist role snapshot refs per CDP target so snapshotact clicks work even if Playwright returns a different Page instance.
  • -
  • macOS: ensure launchd log directory exists with a test-only override. (#909) — thanks @roshanasingh4.
  • -
  • macOS: format ConnectionsStore config to satisfy SwiftFormat lint. (#852) — thanks @mneves75.
  • -
  • Packaging: run pnpm build on prepack so npm publishes include fresh dist/ output.
  • -
  • Telegram: register dock native commands with underscores to avoid BOT_COMMAND_INVALID (#929, fixes #901) — thanks @grp06.
  • -
  • Google: downgrade unsigned thinking blocks before send to avoid missing signature errors.
  • -
  • Agents: make user time zone and 24-hour time explicit in the system prompt. (#859) — thanks @CashWilliams.
  • -
  • Agents: strip downgraded tool call text without eating adjacent replies and filter thinking-tag leaks. (#905) — thanks @erikpr1994.
  • -
  • Agents: cap tool call IDs for OpenAI/OpenRouter to avoid request rejections. (#875) — thanks @j1philli.
  • -
  • Doctor: avoid re-adding WhatsApp config when only legacy ack reactions are set. (#927, fixes #900) — thanks @grp06.
  • -
  • Agents: scrub tuple items schemas for Gemini tool calls. (#926, fixes #746) — thanks @grp06.
  • -
  • Agents: stabilize sub-agent announce status from runtime outcomes and normalize Result/Notes. (#835) — thanks @roshanasingh4.
  • -
  • Apps: use canonical main session keys from gateway defaults across macOS/iOS/Android to avoid creating bare main sessions.
  • -
  • Embedded runner: suppress raw API error payloads from replies. (#924) — thanks @grp06.
  • -
  • Auth: normalize Claude Code CLI profile mode to oauth and auto-migrate config. (#855) — thanks @sebslight.
  • -
  • Daemon: clear persisted launchd disabled state before bootstrap (fixes daemon install after uninstall). (#849) — thanks @ndraiman.
  • -
  • Sessions: return deep clones (structuredClone) so cached session entries can't be mutated. (#934) — thanks @ronak-guliani.
  • -
  • Heartbeat: keep updatedAt monotonic when restoring heartbeat sessions. (#934) — thanks @ronak-guliani.
  • -
  • Agent: clear run context after CLI runs (clearAgentRunContext) to avoid runaway contexts. (#934) — thanks @ronak-guliani.
  • -
  • Gateway/Dev: ensure pnpm gateway:dev always uses the dev profile config + state (~/.clawdbot-dev).
  • -
-

CLI / Onboarding

-
    -
  • Onboarding: show web search setup at the end (not the beginning).
  • -
  • Onboarding: show daemon install/restart progress (avoid “blinking cursor”) and fix daemon install output formatting.
  • -
  • Health: colorize “not configured” provider lines for easier scanning.
  • -
-

Control UI / TUI

-
    -
  • Control UI: load cron run history on job selection and clarify empty-state messaging. (#866)
  • -
  • UI: use application-defined WebSocket close code and fix dashboard auth query items. (#918) — thanks @rahthakor.
  • -
  • UI: always apply ?token= from URL (fixes unauthorized after re-onboard).
  • -
  • Browser: add tests for snapshot labels/efficient query params and labeled image responses.
  • -
  • TUI: render picker overlays via the overlay stack so /models and /settings display. (#921) — thanks @grizzdank.
  • -
  • TUI: add a bright spinner + elapsed time in the status line for send/stream/run states.
  • -
  • TUI: show LLM error messages (rate limits, auth, etc.) instead of (no output).
  • -
-

Agents / Auth / Tools / Sandbox

-
    -
  • Agents: make user time zone and 24-hour time explicit in the system prompt. (#859) — thanks @CashWilliams.
  • -
  • Agents: strip downgraded tool call text without eating adjacent replies and filter thinking-tag leaks. (#905) — thanks @erikpr1994.
  • -
  • Agents: cap tool call IDs for OpenAI/OpenRouter to avoid request rejections. (#875) — thanks @j1philli.
  • -
  • Agents: scrub tuple items schemas for Gemini tool calls. (#926, fixes #746) — thanks @grp06.
  • -
  • Agents: stabilize sub-agent announce status from runtime outcomes and normalize Result/Notes. (#835) — thanks @roshanasingh4.
  • -
  • Auth: normalize Claude Code CLI profile mode to oauth and auto-migrate config. (#855) — thanks @sebslight.
  • -
  • Embedded runner: suppress raw API error payloads from replies. (#924) — thanks @grp06.
  • -
  • Logging: tolerate EIO from console writes to avoid gateway crashes. (#925, fixes #878) — thanks @grp06.
  • -
  • Sandbox: restore docker.binds config validation and preserve configured PATH for docker exec. (#873) — thanks @akonyer.
  • -
  • Google: downgrade unsigned thinking blocks before send to avoid missing signature errors.
  • -
-

macOS / Apps

-
    -
  • macOS: ensure launchd log directory exists with a test-only override. (#909) — thanks @roshanasingh4.
  • -
  • macOS: format ConnectionsStore config to satisfy SwiftFormat lint. (#852) — thanks @mneves75.
  • -
  • macOS: pass auth token/password to dashboard URL for authenticated access. (#918) — thanks @rahthakor.
  • -
  • macOS: reuse launchd gateway auth and skip wizard when gateway config already exists. (#917)
  • -
  • Apps: use canonical main session keys from gateway defaults across macOS/iOS/Android to avoid creating bare main sessions.
  • -
  • macOS: fix cron preview/testing payload to use channel key. (#867) — thanks @wes-davis.
  • -
  • macOS: update cron testing channel arg. (#896) — thanks @ngutman.
  • -
-

Channels / Messaging

-
    -
  • Slack: isolate thread history and avoid inheriting channel transcripts for new threads by default. (#758)
  • -
  • Slack: respect channels.slack.requireMention default when resolving channel mention gating. (#850) — thanks @evalexpr.
  • -
  • Slack: drop Socket Mode events with mismatched api_app_id/team_id. (#889) — thanks @roshanasingh4.
  • -
  • Commands: add native command argument menus across Discord/Slack/Telegram. (#936) — thanks @thewilloftheshadow.
  • -
  • Discord: isolate autoThread thread context. (#856) — thanks @davidguttman.
  • -
  • Telegram: honor channels.telegram.timeoutSeconds for grammY API requests. (#863) — thanks @Snaver.
  • -
  • Telegram: aggregate split inbound messages into one prompt (reduces “one reply per fragment”).
  • -
  • Telegram: let control commands bypass per-chat sequentialization; always allow abort triggers.
  • -
  • Telegram: split long captions into media + follow-up text messages. (#907) — thanks @jalehman.
  • -
  • Telegram: migrate group config when supergroups change chat IDs. (#906) — thanks @sleontenko.
  • -
  • Telegram: register dock native commands with underscores to avoid BOT_COMMAND_INVALID (#929, fixes #901) — thanks @grp06.
  • -
  • Messaging: unify markdown formatting + format-first chunking for Slack/Telegram/Signal. (#920) — thanks @TheSethRose.
  • -
  • iMessage: prefer handle routing for direct-message replies; include imsg RPC error details. (#935)
  • -
  • WhatsApp: fix context isolation using wrong ID (was bot's number, now conversation ID). (#911) — thanks @tristanmanchester.
  • -
  • WhatsApp: normalize user JIDs with device suffix for allowlist checks in groups. (#838) — thanks @peschee.
  • -
  • WhatsApp: harden owner command auth.
  • -
  • Auto-reply: treat trailing NO_REPLY tokens as silent replies.
  • -
-

Config / Doctor / Packaging

-
    -
  • Config: prevent partial config writes from clobbering unrelated settings (base hash guard + merge patch for connection saves).
  • -
  • Config/Doctor: remove legacy Clawdis env fallbacks and config/service migrations (Clawdbot-only).
  • -
  • Doctor: avoid re-adding WhatsApp config when only legacy ack reactions are set. (#927, fixes #900) — thanks @grp06.
  • -
  • Packaging: run pnpm build on prepack so npm publishes include fresh dist/ output.
  • +
  • Web UI: fix config/debug layout overflow, scrolling, and code block sizing. (#1715) Thanks @saipreetham589.
  • +
  • Web UI: show Stop button during active runs, swap back to New session when idle. (#1664) Thanks @ndbroadbent.
  • +
  • Web UI: clear stale disconnect banners on reconnect; allow form saves with unsupported schema paths but block missing schema. (#1707) Thanks @Glucksberg.
  • +
  • Web UI: hide internal message_id hints in chat bubbles.
  • +
  • Gateway: allow Control UI token-only auth to skip device pairing even when device identity is present (gateway.controlUi.allowInsecureAuth). (#1679) Thanks @steipete.
  • +
  • Matrix: decrypt E2EE media attachments with preflight size guard. (#1744) Thanks @araa47.
  • +
  • BlueBubbles: route phone-number targets to DMs, avoid leaking routing IDs, and auto-create missing DMs (Private API required). (#1751) Thanks @tyler6204. https://docs.clawd.bot/channels/bluebubbles
  • +
  • BlueBubbles: keep part-index GUIDs in reply tags when short IDs are missing.
  • +
  • Signal: repair reaction sends (group/UUID targets + CLI author flags). (#1651) Thanks @vilkasdev.
  • +
  • Signal: add configurable signal-cli startup timeout + external daemon mode docs. (#1677) https://docs.clawd.bot/channels/signal
  • +
  • Telegram: set fetch duplex="half" for uploads on Node 22 to avoid sendPhoto failures. (#1684) Thanks @commdata2338.
  • +
  • Telegram: use wrapped fetch for long-polling on Node to normalize AbortSignal handling. (#1639)
  • +
  • Telegram: honor per-account proxy for outbound API calls. (#1774) Thanks @radek-paclt.
  • +
  • Telegram: fall back to text when voice notes are blocked by privacy settings. (#1725) Thanks @foeken.
  • +
  • Voice Call: return stream TwiML for outbound conversation calls on initial Twilio webhook. (#1634)
  • +
  • Voice Call: serialize Twilio TTS playback and cancel on barge-in to prevent overlap. (#1713) Thanks @dguido.
  • +
  • Google Chat: tighten email allowlist matching, typing cleanup, media caps, and onboarding/docs/tests. (#1635) Thanks @iHildy.
  • +
  • Google Chat: normalize space targets without double spaces/ prefix.
  • +
  • Agents: auto-compact on context overflow prompt errors before failing. (#1627) Thanks @rodrigouroz.
  • +
  • Agents: use the active auth profile for auto-compaction recovery.
  • +
  • Media understanding: skip image understanding when the primary model already supports vision. (#1747) Thanks @tyler6204.
  • +
  • Models: default missing custom provider fields so minimal configs are accepted.
  • +
  • Messaging: keep newline chunking safe for fenced markdown blocks across channels.
  • +
  • TUI: reload history after gateway reconnect to restore session state. (#1663)
  • +
  • Heartbeat: normalize target identifiers for consistent routing.
  • +
  • Exec: keep approvals for elevated ask unless full mode. (#1616) Thanks @ivancasco.
  • +
  • Exec: treat Windows platform labels as Windows for node shell selection. (#1760) Thanks @ymat19.
  • +
  • Gateway: include inline config env vars in service install environments. (#1735) Thanks @Seredeep.
  • +
  • Gateway: skip Tailscale DNS probing when tailscale.mode is off. (#1671)
  • +
  • Gateway: reduce log noise for late invokes + remote node probes; debounce skills refresh. (#1607) Thanks @petter-b.
  • +
  • Gateway: clarify Control UI/WebChat auth error hints for missing tokens. (#1690)
  • +
  • Gateway: listen on IPv6 loopback when bound to 127.0.0.1 so localhost webhooks work.
  • +
  • Gateway: store lock files in the temp directory to avoid stale locks on persistent volumes. (#1676)
  • +
  • macOS: default direct-transport ws:// URLs to port 18789; document gateway.remote.transport. (#1603) Thanks @ngutman.
  • +
  • Tests: cap Vitest workers on CI macOS to reduce timeouts. (#1597) Thanks @rohannagpal.
  • +
  • Tests: avoid fake-timer dependency in embedded runner stream mock to reduce CI flakes. (#1597) Thanks @rohannagpal.
  • +
  • Tests: increase embedded runner ordering test timeout to reduce CI flakes. (#1597) Thanks @rohannagpal.

View full changelog

]]>
- +
- 2026.1.12-2 - Tue, 13 Jan 2026 10:05:25 +0000 + 2026.1.23 + Sat, 24 Jan 2026 13:02:18 +0000 https://raw.githubusercontent.com/clawdbot/clawdbot/main/appcast.xml - 5534 - 2026.1.12-2 + 7750 + 2026.1.23 15.0 - Clawdbot 2026.1.12-2 + Clawdbot 2026.1.23 +

Highlights

+
    +
  • TTS: allow model-driven TTS tags by default for expressive audio replies (laughter, singing cues, etc.).
  • +
+

Changes

+
    +
  • Gateway: add /tools/invoke HTTP endpoint for direct tool calls and document it. (#1575) Thanks @vignesh07.
  • +
  • Agents: keep system prompt time zone-only and move current time to session_status for better cache hits.
  • +
  • Agents: remove redundant bash tool alias from tool registration/display. (#1571) Thanks @Takhoffman.
  • +
  • Browser: add node-host proxy auto-routing for remote gateways (configurable per gateway/node).
  • +
  • Heartbeat: add per-channel visibility controls (OK/alerts/indicator). (#1452) Thanks @dlauer.
  • +
  • Plugins: add optional llm-task JSON-only tool for workflows. (#1498) Thanks @vignesh07.
  • +
  • CLI: restart the gateway by default after clawdbot update; add --no-restart to skip it.
  • +
  • CLI: add live auth probes to clawdbot models status for per-profile verification.
  • +
  • CLI: add clawdbot system for system events + heartbeat controls; remove standalone wake.
  • +
  • Agents: add Bedrock auto-discovery defaults + config overrides. (#1553) Thanks @fal3.
  • +
  • Docs: add cron vs heartbeat decision guide (with Lobster workflow notes). (#1533) Thanks @JustYannicc.
  • +
  • Docs: clarify HEARTBEAT.md empty file skips heartbeats, missing file still runs. (#1535) Thanks @JustYannicc.
  • +
  • Markdown: add per-channel table conversion (bullets for Signal/WhatsApp, code blocks elsewhere). (#1495) Thanks @odysseus0.
  • +
  • Tlon: add Urbit channel plugin (DMs, group mentions, thread replies). (#1544) Thanks @wca4a.
  • +
  • Channels: allow per-group tool allow/deny policies across built-in + plugin channels. (#1546) Thanks @adam91holt.
  • +
  • TTS: move Telegram TTS into core with auto-replies, commands, and gateway methods. (#1559) Thanks @Glucksberg.
  • +

Fixes

    -
  • Packaging: include dist/memory/** in the npm tarball (fixes ERR_MODULE_NOT_FOUND for dist/memory/index.js).
  • +
  • Sessions: accept non-UUID sessionIds for history/send/status while preserving agent scoping. (#1518)
  • +
  • Gateway: compare Linux process start time to avoid PID recycling lock loops; keep locks unless stale. (#1572) Thanks @steipete.
  • +
  • Messaging: mirror outbound sends into target session keys (threads + dmScope) and create session entries on send. (#1520)
  • +
  • Sessions: normalize session key casing to lowercase for consistent routing.
  • +
  • BlueBubbles: normalize group session keys for outbound mirroring. (#1520)
  • +
  • Skills: gate bird Homebrew install to macOS. (#1569) Thanks @bradleypriest.
  • +
  • Slack: honor open groupPolicy for unlisted channels in message + slash gating. (#1563) Thanks @itsjaydesu.
  • +
  • Agents: show tool error fallback when the last assistant turn only invoked tools (prevents silent stops).
  • +
  • Agents: ignore IDENTITY.md template placeholders when parsing identity to avoid placeholder replies. (#1556)
  • +
  • Agents: drop orphaned OpenAI Responses reasoning blocks on model switches. (#1562) Thanks @roshanasingh4.
  • +
  • Docker: update gateway command in docker-compose and Hetzner guide. (#1514)
  • +
  • Sessions: reject array-backed session stores to prevent silent wipes. (#1469)
  • +
  • Voice wake: auto-save wake words on blur/submit across iOS/Android and align limits with macOS.
  • +
  • UI: keep the Control UI sidebar visible while scrolling long pages. (#1515) Thanks @pookNast.
  • +
  • UI: cache Control UI markdown rendering + memoize chat text extraction to reduce Safari typing jank.
  • +
  • Tailscale: retry serve/funnel with sudo only for permission errors and keep original failure details. (#1551) Thanks @sweepies.
  • +
  • Agents: add CLI log hint to "agent failed before reply" messages. (#1550) Thanks @sweepies.
  • +
  • Discord: limit autoThread mention bypass to bot-owned threads; keep ack reactions mention-gated. (#1511) Thanks @pvoo.
  • +
  • Discord: retry rate-limited allowlist resolution + command deploy to avoid gateway crashes.
  • +
  • Mentions: ignore mentionPattern matches when another explicit mention is present in group chats (Slack/Discord/Telegram/WhatsApp).
  • +
  • Gateway: accept null optional fields in exec approval requests. (#1511) Thanks @pvoo.
  • +
  • Exec: honor tools.exec ask/security defaults for elevated approvals (avoid unwanted prompts).
  • +
  • TUI: forward unknown slash commands (for example, /context) to the Gateway.
  • +
  • TUI: include Gateway slash commands in autocomplete and /help.
  • +
  • CLI: skip usage lines in clawdbot models status when provider usage is unavailable.
  • +
  • CLI: suppress diagnostic session/run noise during auth probes.
  • +
  • CLI: hide auth probe timeout warnings from embedded runs.
  • +
  • CLI: render auth probe results as a table in clawdbot models status.
  • +
  • CLI: suppress probe-only embedded logs unless --verbose is set.
  • +
  • CLI: move auth probe errors below the table to reduce wrapping.
  • +
  • CLI: prevent ANSI color bleed when table cells wrap.
  • +
  • CLI: explain when auth profiles are excluded by auth.order in probe details.
  • +
  • CLI: drop the em dash when the banner tagline wraps to a second line.
  • +
  • CLI: inline auth probe errors in status rows to reduce wrapping.
  • +
  • Telegram: render markdown in media captions. (#1478)
  • +
  • Agents: honor enqueue overrides for embedded runs to avoid queue deadlocks in tests.
  • +
  • Agents: trigger model fallback when auth profiles are all in cooldown or unavailable. (#1522)
  • +
  • Daemon: use platform PATH delimiters when building minimal service paths.
  • +
  • Tests: skip embedded runner ordering assertion on Windows to avoid CI timeouts.
  • +
  • Linux: include env-configured user bin roots in systemd PATH and align PATH audits. (#1512) Thanks @robbyczgw-cla.
  • +
  • TUI: render Gateway slash-command replies as system output (for example, /context).
  • +
  • Media: only parse MEDIA: tags when they start the line to avoid stripping prose mentions. (#1206)
  • +
  • Media: preserve PNG alpha when possible; fall back to JPEG when still over size cap. (#1491) Thanks @robbyczgw-cla.
  • +
  • Agents: treat plugin-only tool allowlists as opt-ins; keep core tools enabled. (#1467)
  • +
  • Exec approvals: persist allowlist entry ids to keep macOS allowlist rows stable. (#1521) Thanks @ngutman.
  • +
  • MS Teams (plugin): remove .default suffix from Graph scopes to avoid double-appending. (#1507) Thanks @Evizero.
  • +
  • MS Teams (plugin): remove .default suffix from Bot Framework probe scope to avoid double-appending. (#1574) Thanks @Evizero.
  • +
  • Browser: keep extension relay tabs controllable when the extension reuses a session id after switching tabs. (#1160)
  • +
  • Agents: warn and ignore tool allowlists that only reference unknown or unloaded plugin tools. (#1566)

View full changelog

]]>
- -
- - 2026.1.11-3 - Mon, 12 Jan 2026 10:40:23 +0000 - https://raw.githubusercontent.com/clawdbot/clawdbot/main/appcast.xml - 5212 - 2026.1.11-3 - 15.0 - Clawdbot 2026.1.11-3 -

Fixes

-
    -
  • CLI: avoid top-level await warnings in the entrypoint on fresh installs.
  • -
  • CLI: show a commit hash in the banner for npm installs (package.json gitHead fallback).
  • -
-

View full changelog

-]]>
- +
\ No newline at end of file diff --git a/apps/android/README.md b/apps/android/README.md index 02908b82d..ca0967643 100644 --- a/apps/android/README.md +++ b/apps/android/README.md @@ -1,6 +1,6 @@ ## Clawdbot Node (Android) (internal) -Modern Android node app: connects to the **Gateway-owned bridge** (`_clawdbot-bridge._tcp`) over TCP and exposes **Canvas + Chat + Camera**. +Modern Android node app: connects to the **Gateway WebSocket** (`_clawdbot-gw._tcp`) and exposes **Canvas + Chat + Camera**. Notes: - The node keeps the connection alive via a **foreground service** (persistent notification with a Disconnect action). @@ -30,7 +30,7 @@ pnpm clawdbot gateway --port 18789 --verbose 2) In the Android app: - Open **Settings** -- Either select a discovered bridge under **Discovered Bridges**, or use **Advanced → Manual Bridge** (host + port). +- Either select a discovered gateway under **Discovered Gateways**, or use **Advanced → Manual Gateway** (host + port). 3) Approve pairing (on the gateway machine): ```bash @@ -38,7 +38,7 @@ clawdbot nodes pending clawdbot nodes approve ``` -More details: `docs/android/connect.md`. +More details: `docs/platforms/android.md`. ## Permissions diff --git a/apps/android/app/build.gradle.kts b/apps/android/app/build.gradle.kts index 7b245a0a3..a015c0e36 100644 --- a/apps/android/app/build.gradle.kts +++ b/apps/android/app/build.gradle.kts @@ -21,8 +21,8 @@ android { applicationId = "com.clawdbot.android" minSdk = 31 targetSdk = 36 - versionCode = 202601114 - versionName = "2026.1.11-4" + versionCode = 202601250 + versionName = "2026.1.25" } buildTypes { @@ -103,6 +103,7 @@ dependencies { implementation("androidx.security:security-crypto:1.1.0") implementation("androidx.exifinterface:exifinterface:1.4.2") + implementation("com.squareup.okhttp3:okhttp:5.3.2") // CameraX (for node.invoke camera.* parity) implementation("androidx.camera:camera-core:1.5.2") @@ -112,7 +113,7 @@ dependencies { implementation("androidx.camera:camera-view:1.5.2") // Unicast DNS-SD (Wide-Area Bonjour) for tailnet discovery domains. - implementation("dnsjava:dnsjava:3.6.3") + implementation("dnsjava:dnsjava:3.6.4") testImplementation("junit:junit:4.13.2") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2") diff --git a/apps/android/app/src/main/java/com/clawdbot/android/CameraHudState.kt b/apps/android/app/src/main/java/com/clawdbot/android/CameraHudState.kt index 1d876903a..1c9b3986f 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/CameraHudState.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/CameraHudState.kt @@ -12,4 +12,3 @@ data class CameraHudState( val kind: CameraHudKind, val message: String, ) - diff --git a/apps/android/app/src/main/java/com/clawdbot/android/MainViewModel.kt b/apps/android/app/src/main/java/com/clawdbot/android/MainViewModel.kt index 021ebf587..1329f06d4 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/MainViewModel.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/MainViewModel.kt @@ -2,7 +2,7 @@ package com.clawdbot.android import android.app.Application import androidx.lifecycle.AndroidViewModel -import com.clawdbot.android.bridge.BridgeEndpoint +import com.clawdbot.android.gateway.GatewayEndpoint import com.clawdbot.android.chat.OutgoingAttachment import com.clawdbot.android.node.CameraCaptureManager import com.clawdbot.android.node.CanvasController @@ -18,7 +18,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) { val screenRecorder: ScreenRecordManager = runtime.screenRecorder val sms: SmsManager = runtime.sms - val bridges: StateFlow> = runtime.bridges + val gateways: StateFlow> = runtime.gateways val discoveryStatusText: StateFlow = runtime.discoveryStatusText val isConnected: StateFlow = runtime.isConnected @@ -50,6 +50,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) { val manualEnabled: StateFlow = runtime.manualEnabled val manualHost: StateFlow = runtime.manualHost val manualPort: StateFlow = runtime.manualPort + val manualTls: StateFlow = runtime.manualTls val canvasDebugStatusEnabled: StateFlow = runtime.canvasDebugStatusEnabled val chatSessionKey: StateFlow = runtime.chatSessionKey @@ -99,6 +100,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) { runtime.setManualPort(value) } + fun setManualTls(value: Boolean) { + runtime.setManualTls(value) + } + fun setCanvasDebugStatusEnabled(value: Boolean) { runtime.setCanvasDebugStatusEnabled(value) } @@ -119,11 +124,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) { runtime.setTalkEnabled(enabled) } - fun refreshBridgeHello() { - runtime.refreshBridgeHello() + fun refreshGatewayConnection() { + runtime.refreshGatewayConnection() } - fun connect(endpoint: BridgeEndpoint) { + fun connect(endpoint: GatewayEndpoint) { runtime.connect(endpoint) } diff --git a/apps/android/app/src/main/java/com/clawdbot/android/NodeRuntime.kt b/apps/android/app/src/main/java/com/clawdbot/android/NodeRuntime.kt index 83054c4e1..603e4b82b 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/NodeRuntime.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/NodeRuntime.kt @@ -12,11 +12,14 @@ import com.clawdbot.android.chat.ChatMessage import com.clawdbot.android.chat.ChatPendingToolCall import com.clawdbot.android.chat.ChatSessionEntry import com.clawdbot.android.chat.OutgoingAttachment -import com.clawdbot.android.bridge.BridgeDiscovery -import com.clawdbot.android.bridge.BridgeEndpoint -import com.clawdbot.android.bridge.BridgePairingClient -import com.clawdbot.android.bridge.BridgeSession -import com.clawdbot.android.bridge.BridgeTlsParams +import com.clawdbot.android.gateway.DeviceAuthStore +import com.clawdbot.android.gateway.DeviceIdentityStore +import com.clawdbot.android.gateway.GatewayClientInfo +import com.clawdbot.android.gateway.GatewayConnectOptions +import com.clawdbot.android.gateway.GatewayDiscovery +import com.clawdbot.android.gateway.GatewayEndpoint +import com.clawdbot.android.gateway.GatewaySession +import com.clawdbot.android.gateway.GatewayTlsParams import com.clawdbot.android.node.CameraCaptureManager import com.clawdbot.android.node.LocationCaptureManager import com.clawdbot.android.BuildConfig @@ -60,6 +63,7 @@ class NodeRuntime(context: Context) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) val prefs = SecurePrefs(appContext) + private val deviceAuthStore = DeviceAuthStore(prefs) val canvas = CanvasController() val camera = CameraCaptureManager(appContext) val location = LocationCaptureManager(appContext) @@ -74,7 +78,7 @@ class NodeRuntime(context: Context) { context = appContext, scope = scope, onCommand = { command -> - session.sendEvent( + nodeSession.sendNodeEvent( event = "agent.request", payloadJson = buildJsonObject { @@ -103,10 +107,12 @@ class NodeRuntime(context: Context) { val talkIsSpeaking: StateFlow get() = talkMode.isSpeaking - private val discovery = BridgeDiscovery(appContext, scope = scope) - val bridges: StateFlow> = discovery.bridges + private val discovery = GatewayDiscovery(appContext, scope = scope) + val gateways: StateFlow> = discovery.gateways val discoveryStatusText: StateFlow = discovery.statusText + private val identityStore = DeviceIdentityStore(appContext) + private val _isConnected = MutableStateFlow(false) val isConnected: StateFlow = _isConnected.asStateFlow() @@ -139,52 +145,89 @@ class NodeRuntime(context: Context) { val isForeground: StateFlow = _isForeground.asStateFlow() private var lastAutoA2uiUrl: String? = null + private var operatorConnected = false + private var nodeConnected = false + private var operatorStatusText: String = "Offline" + private var nodeStatusText: String = "Offline" + private var connectedEndpoint: GatewayEndpoint? = null - private val session = - BridgeSession( + private val operatorSession = + GatewaySession( scope = scope, + identityStore = identityStore, + deviceAuthStore = deviceAuthStore, onConnected = { name, remote, mainSessionKey -> - _statusText.value = "Connected" + operatorConnected = true + operatorStatusText = "Connected" _serverName.value = name _remoteAddress.value = remote - _isConnected.value = true _seamColorArgb.value = DEFAULT_SEAM_COLOR_ARGB applyMainSessionKey(mainSessionKey) + updateStatus() scope.launch { refreshBrandingFromGateway() } scope.launch { refreshWakeWordsFromGateway() } + }, + onDisconnected = { message -> + operatorConnected = false + operatorStatusText = message + _serverName.value = null + _remoteAddress.value = null + _seamColorArgb.value = DEFAULT_SEAM_COLOR_ARGB + if (!isCanonicalMainSessionKey(_mainSessionKey.value)) { + _mainSessionKey.value = "main" + } + val mainKey = resolveMainSessionKey() + talkMode.setMainSessionKey(mainKey) + chat.applyMainSessionKey(mainKey) + chat.onDisconnected(message) + updateStatus() + }, + onEvent = { event, payloadJson -> + handleGatewayEvent(event, payloadJson) + }, + ) + + private val nodeSession = + GatewaySession( + scope = scope, + identityStore = identityStore, + deviceAuthStore = deviceAuthStore, + onConnected = { _, _, _ -> + nodeConnected = true + nodeStatusText = "Connected" + updateStatus() maybeNavigateToA2uiOnConnect() }, - onDisconnected = { message -> handleSessionDisconnected(message) }, - onEvent = { event, payloadJson -> - handleBridgeEvent(event, payloadJson) + onDisconnected = { message -> + nodeConnected = false + nodeStatusText = message + updateStatus() + showLocalCanvasOnDisconnect() }, + onEvent = { _, _ -> }, onInvoke = { req -> handleInvoke(req.command, req.paramsJson) }, onTlsFingerprint = { stableId, fingerprint -> - prefs.saveBridgeTlsFingerprint(stableId, fingerprint) + prefs.saveGatewayTlsFingerprint(stableId, fingerprint) }, ) - private val chat = ChatController(scope = scope, session = session, json = json) + private val chat: ChatController = + ChatController( + scope = scope, + session = operatorSession, + json = json, + supportsChatSubscribe = false, + ) private val talkMode: TalkModeManager by lazy { - TalkModeManager(context = appContext, scope = scope).also { it.attachSession(session) } - } - - private fun handleSessionDisconnected(message: String) { - _statusText.value = message - _serverName.value = null - _remoteAddress.value = null - _isConnected.value = false - _seamColorArgb.value = DEFAULT_SEAM_COLOR_ARGB - if (!isCanonicalMainSessionKey(_mainSessionKey.value)) { - _mainSessionKey.value = "main" - } - val mainKey = resolveMainSessionKey() - talkMode.setMainSessionKey(mainKey) - chat.applyMainSessionKey(mainKey) - chat.onDisconnected(message) - showLocalCanvasOnDisconnect() + TalkModeManager( + context = appContext, + scope = scope, + session = operatorSession, + supportsChatSubscribe = false, + isConnected = { operatorConnected }, + ) } private fun applyMainSessionKey(candidate: String?) { @@ -197,6 +240,18 @@ class NodeRuntime(context: Context) { chat.applyMainSessionKey(trimmed) } + private fun updateStatus() { + _isConnected.value = operatorConnected + _statusText.value = + when { + operatorConnected && nodeConnected -> "Connected" + operatorConnected && !nodeConnected -> "Connected (node offline)" + !operatorConnected && nodeConnected -> "Connected (operator offline)" + operatorStatusText.isNotBlank() && operatorStatusText != "Offline" -> operatorStatusText + else -> nodeStatusText + } + } + private fun resolveMainSessionKey(): String { val trimmed = _mainSessionKey.value.trim() return if (trimmed.isEmpty()) "main" else trimmed @@ -228,6 +283,7 @@ class NodeRuntime(context: Context) { val manualEnabled: StateFlow = prefs.manualEnabled val manualHost: StateFlow = prefs.manualHost val manualPort: StateFlow = prefs.manualPort + val manualTls: StateFlow = prefs.manualTls val lastDiscoveredStableId: StateFlow = prefs.lastDiscoveredStableId val canvasDebugStatusEnabled: StateFlow = prefs.canvasDebugStatusEnabled @@ -288,24 +344,21 @@ class NodeRuntime(context: Context) { } scope.launch(Dispatchers.Default) { - bridges.collect { list -> + gateways.collect { list -> if (list.isNotEmpty()) { - // Persist the last discovered bridge (best-effort UX parity with iOS). + // Persist the last discovered gateway (best-effort UX parity with iOS). prefs.setLastDiscoveredStableId(list.last().stableId) } if (didAutoConnect) return@collect if (_isConnected.value) return@collect - val token = prefs.loadBridgeToken() - if (token.isNullOrBlank()) return@collect - if (manualEnabled.value) { val host = manualHost.value.trim() val port = manualPort.value if (host.isNotEmpty() && port in 1..65535) { didAutoConnect = true - connect(BridgeEndpoint.manual(host = host, port = port)) + connect(GatewayEndpoint.manual(host = host, port = port)) } return@collect } @@ -371,6 +424,10 @@ class NodeRuntime(context: Context) { prefs.setManualPort(value) } + fun setManualTls(value: Boolean) { + prefs.setManualTls(value) + } + fun setCanvasDebugStatusEnabled(value: Boolean) { prefs.setCanvasDebugStatusEnabled(value) } @@ -429,99 +486,87 @@ class NodeRuntime(context: Context) { } } - private fun buildPairingHello(token: String?): BridgePairingClient.Hello { - val modelIdentifier = listOfNotNull(Build.MANUFACTURER, Build.MODEL) - .joinToString(" ") - .trim() - .ifEmpty { null } + private fun resolvedVersionName(): String { val versionName = BuildConfig.VERSION_NAME.trim().ifEmpty { "dev" } - val advertisedVersion = - if (BuildConfig.DEBUG && !versionName.contains("dev", ignoreCase = true)) { - "$versionName-dev" - } else { - versionName - } - return BridgePairingClient.Hello( - nodeId = instanceId.value, - displayName = displayName.value, - token = token, - platform = "Android", - version = advertisedVersion, - deviceFamily = "Android", - modelIdentifier = modelIdentifier, - caps = buildCapabilities(), - commands = buildInvokeCommands(), - ) - } - - private fun buildSessionHello(token: String?): BridgeSession.Hello { - val modelIdentifier = listOfNotNull(Build.MANUFACTURER, Build.MODEL) - .joinToString(" ") - .trim() - .ifEmpty { null } - val versionName = BuildConfig.VERSION_NAME.trim().ifEmpty { "dev" } - val advertisedVersion = - if (BuildConfig.DEBUG && !versionName.contains("dev", ignoreCase = true)) { - "$versionName-dev" - } else { - versionName - } - return BridgeSession.Hello( - nodeId = instanceId.value, - displayName = displayName.value, - token = token, - platform = "Android", - version = advertisedVersion, - deviceFamily = "Android", - modelIdentifier = modelIdentifier, - caps = buildCapabilities(), - commands = buildInvokeCommands(), - ) - } - - fun refreshBridgeHello() { - scope.launch { - if (!_isConnected.value) return@launch - val token = prefs.loadBridgeToken() - if (token.isNullOrBlank()) return@launch - session.updateHello(buildSessionHello(token)) + return if (BuildConfig.DEBUG && !versionName.contains("dev", ignoreCase = true)) { + "$versionName-dev" + } else { + versionName } } - fun connect(endpoint: BridgeEndpoint) { - scope.launch { - _statusText.value = "Connecting…" - val storedToken = prefs.loadBridgeToken() - val tls = resolveTlsParams(endpoint) - val resolved = - if (storedToken.isNullOrBlank()) { - _statusText.value = "Pairing…" - BridgePairingClient().pairAndHello( - endpoint = endpoint, - hello = buildPairingHello(token = null), - tls = tls, - onTlsFingerprint = { fingerprint -> - prefs.saveBridgeTlsFingerprint(endpoint.stableId, fingerprint) - }, - ) - } else { - BridgePairingClient.PairResult(ok = true, token = storedToken.trim()) - } + private fun resolveModelIdentifier(): String? { + return listOfNotNull(Build.MANUFACTURER, Build.MODEL) + .joinToString(" ") + .trim() + .ifEmpty { null } + } - if (!resolved.ok || resolved.token.isNullOrBlank()) { - val errorMessage = resolved.error?.trim().orEmpty().ifEmpty { "pairing required" } - _statusText.value = "Failed: $errorMessage" - return@launch - } + private fun buildUserAgent(): String { + val version = resolvedVersionName() + val release = Build.VERSION.RELEASE?.trim().orEmpty() + val releaseLabel = if (release.isEmpty()) "unknown" else release + return "ClawdbotAndroid/$version (Android $releaseLabel; SDK ${Build.VERSION.SDK_INT})" + } - val authToken = requireNotNull(resolved.token).trim() - prefs.saveBridgeToken(authToken) - session.connect( - endpoint = endpoint, - hello = buildSessionHello(token = authToken), - tls = tls, - ) - } + private fun buildClientInfo(clientId: String, clientMode: String): GatewayClientInfo { + return GatewayClientInfo( + id = clientId, + displayName = displayName.value, + version = resolvedVersionName(), + platform = "android", + mode = clientMode, + instanceId = instanceId.value, + deviceFamily = "Android", + modelIdentifier = resolveModelIdentifier(), + ) + } + + private fun buildNodeConnectOptions(): GatewayConnectOptions { + return GatewayConnectOptions( + role = "node", + scopes = emptyList(), + caps = buildCapabilities(), + commands = buildInvokeCommands(), + permissions = emptyMap(), + client = buildClientInfo(clientId = "clawdbot-android", clientMode = "node"), + userAgent = buildUserAgent(), + ) + } + + private fun buildOperatorConnectOptions(): GatewayConnectOptions { + return GatewayConnectOptions( + role = "operator", + scopes = emptyList(), + caps = emptyList(), + commands = emptyList(), + permissions = emptyMap(), + client = buildClientInfo(clientId = "clawdbot-control-ui", clientMode = "ui"), + userAgent = buildUserAgent(), + ) + } + + fun refreshGatewayConnection() { + val endpoint = connectedEndpoint ?: return + val token = prefs.loadGatewayToken() + val password = prefs.loadGatewayPassword() + val tls = resolveTlsParams(endpoint) + operatorSession.connect(endpoint, token, password, buildOperatorConnectOptions(), tls) + nodeSession.connect(endpoint, token, password, buildNodeConnectOptions(), tls) + operatorSession.reconnect() + nodeSession.reconnect() + } + + fun connect(endpoint: GatewayEndpoint) { + connectedEndpoint = endpoint + operatorStatusText = "Connecting…" + nodeStatusText = "Connecting…" + updateStatus() + val token = prefs.loadGatewayToken() + val password = prefs.loadGatewayPassword() + val tls = resolveTlsParams(endpoint) + operatorSession.connect(endpoint, token, password, buildOperatorConnectOptions(), tls) + nodeSession.connect(endpoint, token, password, buildNodeConnectOptions(), tls) } private fun hasRecordAudioPermission(): Boolean { @@ -559,20 +604,32 @@ class NodeRuntime(context: Context) { _statusText.value = "Failed: invalid manual host/port" return } - connect(BridgeEndpoint.manual(host = host, port = port)) + connect(GatewayEndpoint.manual(host = host, port = port)) } fun disconnect() { - session.disconnect() + connectedEndpoint = null + operatorSession.disconnect() + nodeSession.disconnect() } - private fun resolveTlsParams(endpoint: BridgeEndpoint): BridgeTlsParams? { - val stored = prefs.loadBridgeTlsFingerprint(endpoint.stableId) + private fun resolveTlsParams(endpoint: GatewayEndpoint): GatewayTlsParams? { + val stored = prefs.loadGatewayTlsFingerprint(endpoint.stableId) val hinted = endpoint.tlsEnabled || !endpoint.tlsFingerprintSha256.isNullOrBlank() val manual = endpoint.stableId.startsWith("manual|") + if (manual) { + if (!manualTls.value) return null + return GatewayTlsParams( + required = true, + expectedFingerprint = endpoint.tlsFingerprintSha256 ?: stored, + allowTOFU = stored == null, + stableId = endpoint.stableId, + ) + } + if (hinted) { - return BridgeTlsParams( + return GatewayTlsParams( required = true, expectedFingerprint = endpoint.tlsFingerprintSha256 ?: stored, allowTOFU = stored == null, @@ -581,7 +638,7 @@ class NodeRuntime(context: Context) { } if (!stored.isNullOrBlank()) { - return BridgeTlsParams( + return GatewayTlsParams( required = true, expectedFingerprint = stored, allowTOFU = false, @@ -589,15 +646,6 @@ class NodeRuntime(context: Context) { ) } - if (manual) { - return BridgeTlsParams( - required = false, - expectedFingerprint = null, - allowTOFU = true, - stableId = endpoint.stableId, - ) - } - return null } @@ -637,11 +685,11 @@ class NodeRuntime(context: Context) { contextJson = contextJson, ) - val connected = isConnected.value + val connected = nodeConnected var error: String? = null if (connected) { try { - session.sendEvent( + nodeSession.sendNodeEvent( event = "agent.request", payloadJson = buildJsonObject { @@ -656,7 +704,7 @@ class NodeRuntime(context: Context) { error = e.message ?: "send failed" } } else { - error = "bridge not connected" + error = "gateway not connected" } try { @@ -702,7 +750,7 @@ class NodeRuntime(context: Context) { chat.sendMessage(message = message, thinkingLevel = thinking, attachments = attachments) } - private fun handleBridgeEvent(event: String, payloadJson: String?) { + private fun handleGatewayEvent(event: String, payloadJson: String?) { if (event == "voicewake.changed") { if (payloadJson.isNullOrBlank()) return try { @@ -716,8 +764,8 @@ class NodeRuntime(context: Context) { return } - talkMode.handleBridgeEvent(event, payloadJson) - chat.handleBridgeEvent(event, payloadJson) + talkMode.handleGatewayEvent(event, payloadJson) + chat.handleGatewayEvent(event, payloadJson) } private fun applyWakeWordsFromGateway(words: List) { @@ -738,7 +786,7 @@ class NodeRuntime(context: Context) { val jsonList = snapshot.joinToString(separator = ",") { it.toJsonString() } val params = """{"triggers":[$jsonList]}""" try { - session.request("voicewake.set", params) + operatorSession.request("voicewake.set", params) } catch (_: Throwable) { // ignore } @@ -748,7 +796,7 @@ class NodeRuntime(context: Context) { private suspend fun refreshWakeWordsFromGateway() { if (!_isConnected.value) return try { - val res = session.request("voicewake.get", "{}") + val res = operatorSession.request("voicewake.get", "{}") val payload = json.parseToJsonElement(res).asObjectOrNull() ?: return val array = payload["triggers"] as? JsonArray ?: return val triggers = array.mapNotNull { it.asStringOrNull() } @@ -761,7 +809,7 @@ class NodeRuntime(context: Context) { private suspend fun refreshBrandingFromGateway() { if (!_isConnected.value) return try { - val res = session.request("config.get", "{}") + val res = operatorSession.request("config.get", "{}") val root = json.parseToJsonElement(res).asObjectOrNull() val config = root?.get("config").asObjectOrNull() val ui = config?.get("ui").asObjectOrNull() @@ -777,7 +825,7 @@ class NodeRuntime(context: Context) { } } - private suspend fun handleInvoke(command: String, paramsJson: String?): BridgeSession.InvokeResult { + private suspend fun handleInvoke(command: String, paramsJson: String?): GatewaySession.InvokeResult { if ( command.startsWith(ClawdbotCanvasCommand.NamespacePrefix) || command.startsWith(ClawdbotCanvasA2UICommand.NamespacePrefix) || @@ -785,14 +833,14 @@ class NodeRuntime(context: Context) { command.startsWith(ClawdbotScreenCommand.NamespacePrefix) ) { if (!isForeground.value) { - return BridgeSession.InvokeResult.error( + return GatewaySession.InvokeResult.error( code = "NODE_BACKGROUND_UNAVAILABLE", message = "NODE_BACKGROUND_UNAVAILABLE: canvas/camera/screen commands require foreground", ) } } if (command.startsWith(ClawdbotCameraCommand.NamespacePrefix) && !cameraEnabled.value) { - return BridgeSession.InvokeResult.error( + return GatewaySession.InvokeResult.error( code = "CAMERA_DISABLED", message = "CAMERA_DISABLED: enable Camera in Settings", ) @@ -800,7 +848,7 @@ class NodeRuntime(context: Context) { if (command.startsWith(ClawdbotLocationCommand.NamespacePrefix) && locationMode.value == LocationMode.Off ) { - return BridgeSession.InvokeResult.error( + return GatewaySession.InvokeResult.error( code = "LOCATION_DISABLED", message = "LOCATION_DISABLED: enable Location in Settings", ) @@ -810,18 +858,18 @@ class NodeRuntime(context: Context) { ClawdbotCanvasCommand.Present.rawValue -> { val url = CanvasController.parseNavigateUrl(paramsJson) canvas.navigate(url) - BridgeSession.InvokeResult.ok(null) + GatewaySession.InvokeResult.ok(null) } - ClawdbotCanvasCommand.Hide.rawValue -> BridgeSession.InvokeResult.ok(null) + ClawdbotCanvasCommand.Hide.rawValue -> GatewaySession.InvokeResult.ok(null) ClawdbotCanvasCommand.Navigate.rawValue -> { val url = CanvasController.parseNavigateUrl(paramsJson) canvas.navigate(url) - BridgeSession.InvokeResult.ok(null) + GatewaySession.InvokeResult.ok(null) } ClawdbotCanvasCommand.Eval.rawValue -> { val js = CanvasController.parseEvalJs(paramsJson) - ?: return BridgeSession.InvokeResult.error( + ?: return GatewaySession.InvokeResult.error( code = "INVALID_REQUEST", message = "INVALID_REQUEST: javaScript required", ) @@ -829,12 +877,12 @@ class NodeRuntime(context: Context) { try { canvas.eval(js) } catch (err: Throwable) { - return BridgeSession.InvokeResult.error( + return GatewaySession.InvokeResult.error( code = "NODE_BACKGROUND_UNAVAILABLE", message = "NODE_BACKGROUND_UNAVAILABLE: canvas unavailable", ) } - BridgeSession.InvokeResult.ok("""{"result":${result.toJsonString()}}""") + GatewaySession.InvokeResult.ok("""{"result":${result.toJsonString()}}""") } ClawdbotCanvasCommand.Snapshot.rawValue -> { val snapshotParams = CanvasController.parseSnapshotParams(paramsJson) @@ -846,51 +894,51 @@ class NodeRuntime(context: Context) { maxWidth = snapshotParams.maxWidth, ) } catch (err: Throwable) { - return BridgeSession.InvokeResult.error( + return GatewaySession.InvokeResult.error( code = "NODE_BACKGROUND_UNAVAILABLE", message = "NODE_BACKGROUND_UNAVAILABLE: canvas unavailable", ) } - BridgeSession.InvokeResult.ok("""{"format":"${snapshotParams.format.rawValue}","base64":"$base64"}""") + GatewaySession.InvokeResult.ok("""{"format":"${snapshotParams.format.rawValue}","base64":"$base64"}""") } ClawdbotCanvasA2UICommand.Reset.rawValue -> { val a2uiUrl = resolveA2uiHostUrl() - ?: return BridgeSession.InvokeResult.error( + ?: return GatewaySession.InvokeResult.error( code = "A2UI_HOST_NOT_CONFIGURED", message = "A2UI_HOST_NOT_CONFIGURED: gateway did not advertise canvas host", ) val ready = ensureA2uiReady(a2uiUrl) if (!ready) { - return BridgeSession.InvokeResult.error( + return GatewaySession.InvokeResult.error( code = "A2UI_HOST_UNAVAILABLE", message = "A2UI host not reachable", ) } val res = canvas.eval(a2uiResetJS) - BridgeSession.InvokeResult.ok(res) + GatewaySession.InvokeResult.ok(res) } ClawdbotCanvasA2UICommand.Push.rawValue, ClawdbotCanvasA2UICommand.PushJSONL.rawValue -> { val messages = try { decodeA2uiMessages(command, paramsJson) } catch (err: Throwable) { - return BridgeSession.InvokeResult.error(code = "INVALID_REQUEST", message = err.message ?: "invalid A2UI payload") + return GatewaySession.InvokeResult.error(code = "INVALID_REQUEST", message = err.message ?: "invalid A2UI payload") } val a2uiUrl = resolveA2uiHostUrl() - ?: return BridgeSession.InvokeResult.error( + ?: return GatewaySession.InvokeResult.error( code = "A2UI_HOST_NOT_CONFIGURED", message = "A2UI_HOST_NOT_CONFIGURED: gateway did not advertise canvas host", ) val ready = ensureA2uiReady(a2uiUrl) if (!ready) { - return BridgeSession.InvokeResult.error( + return GatewaySession.InvokeResult.error( code = "A2UI_HOST_UNAVAILABLE", message = "A2UI host not reachable", ) } val js = a2uiApplyMessagesJS(messages) val res = canvas.eval(js) - BridgeSession.InvokeResult.ok(res) + GatewaySession.InvokeResult.ok(res) } ClawdbotCameraCommand.Snap.rawValue -> { showCameraHud(message = "Taking photo…", kind = CameraHudKind.Photo) @@ -901,10 +949,10 @@ class NodeRuntime(context: Context) { } catch (err: Throwable) { val (code, message) = invokeErrorFromThrowable(err) showCameraHud(message = message, kind = CameraHudKind.Error, autoHideMs = 2200) - return BridgeSession.InvokeResult.error(code = code, message = message) + return GatewaySession.InvokeResult.error(code = code, message = message) } showCameraHud(message = "Photo captured", kind = CameraHudKind.Success, autoHideMs = 1600) - BridgeSession.InvokeResult.ok(res.payloadJson) + GatewaySession.InvokeResult.ok(res.payloadJson) } ClawdbotCameraCommand.Clip.rawValue -> { val includeAudio = paramsJson?.contains("\"includeAudio\":true") != false @@ -917,10 +965,10 @@ class NodeRuntime(context: Context) { } catch (err: Throwable) { val (code, message) = invokeErrorFromThrowable(err) showCameraHud(message = message, kind = CameraHudKind.Error, autoHideMs = 2400) - return BridgeSession.InvokeResult.error(code = code, message = message) + return GatewaySession.InvokeResult.error(code = code, message = message) } showCameraHud(message = "Clip captured", kind = CameraHudKind.Success, autoHideMs = 1800) - BridgeSession.InvokeResult.ok(res.payloadJson) + GatewaySession.InvokeResult.ok(res.payloadJson) } finally { if (includeAudio) externalAudioCaptureActive.value = false } @@ -928,19 +976,19 @@ class NodeRuntime(context: Context) { ClawdbotLocationCommand.Get.rawValue -> { val mode = locationMode.value if (!isForeground.value && mode != LocationMode.Always) { - return BridgeSession.InvokeResult.error( + return GatewaySession.InvokeResult.error( code = "LOCATION_BACKGROUND_UNAVAILABLE", message = "LOCATION_BACKGROUND_UNAVAILABLE: background location requires Always", ) } if (!hasFineLocationPermission() && !hasCoarseLocationPermission()) { - return BridgeSession.InvokeResult.error( + return GatewaySession.InvokeResult.error( code = "LOCATION_PERMISSION_REQUIRED", message = "LOCATION_PERMISSION_REQUIRED: grant Location permission", ) } if (!isForeground.value && mode == LocationMode.Always && !hasBackgroundLocationPermission()) { - return BridgeSession.InvokeResult.error( + return GatewaySession.InvokeResult.error( code = "LOCATION_PERMISSION_REQUIRED", message = "LOCATION_PERMISSION_REQUIRED: enable Always in system Settings", ) @@ -967,15 +1015,15 @@ class NodeRuntime(context: Context) { timeoutMs = timeoutMs, isPrecise = accuracy == "precise", ) - BridgeSession.InvokeResult.ok(payload.payloadJson) + GatewaySession.InvokeResult.ok(payload.payloadJson) } catch (err: TimeoutCancellationException) { - BridgeSession.InvokeResult.error( + GatewaySession.InvokeResult.error( code = "LOCATION_TIMEOUT", message = "LOCATION_TIMEOUT: no fix in time", ) } catch (err: Throwable) { val message = err.message ?: "LOCATION_UNAVAILABLE: no fix" - BridgeSession.InvokeResult.error(code = "LOCATION_UNAVAILABLE", message = message) + GatewaySession.InvokeResult.error(code = "LOCATION_UNAVAILABLE", message = message) } } ClawdbotScreenCommand.Record.rawValue -> { @@ -987,9 +1035,9 @@ class NodeRuntime(context: Context) { screenRecorder.record(paramsJson) } catch (err: Throwable) { val (code, message) = invokeErrorFromThrowable(err) - return BridgeSession.InvokeResult.error(code = code, message = message) + return GatewaySession.InvokeResult.error(code = code, message = message) } - BridgeSession.InvokeResult.ok(res.payloadJson) + GatewaySession.InvokeResult.ok(res.payloadJson) } finally { _screenRecordActive.value = false } @@ -997,16 +1045,16 @@ class NodeRuntime(context: Context) { ClawdbotSmsCommand.Send.rawValue -> { val res = sms.send(paramsJson) if (res.ok) { - BridgeSession.InvokeResult.ok(res.payloadJson) + GatewaySession.InvokeResult.ok(res.payloadJson) } else { val error = res.error ?: "SMS_SEND_FAILED" val idx = error.indexOf(':') val code = if (idx > 0) error.substring(0, idx).trim() else "SMS_SEND_FAILED" - BridgeSession.InvokeResult.error(code = code, message = error) + GatewaySession.InvokeResult.error(code = code, message = error) } } else -> - BridgeSession.InvokeResult.error( + GatewaySession.InvokeResult.error( code = "INVALID_REQUEST", message = "INVALID_REQUEST: unknown command", ) @@ -1062,7 +1110,9 @@ class NodeRuntime(context: Context) { } private fun resolveA2uiHostUrl(): String? { - val raw = session.currentCanvasHostUrl()?.trim().orEmpty() + val nodeRaw = nodeSession.currentCanvasHostUrl()?.trim().orEmpty() + val operatorRaw = operatorSession.currentCanvasHostUrl()?.trim().orEmpty() + val raw = if (nodeRaw.isNotBlank()) nodeRaw else operatorRaw if (raw.isBlank()) return null val base = raw.trimEnd('/') return "${base}/__clawdbot__/a2ui/?platform=android" diff --git a/apps/android/app/src/main/java/com/clawdbot/android/SecurePrefs.kt b/apps/android/app/src/main/java/com/clawdbot/android/SecurePrefs.kt index 3b02c88a5..cd6270dd5 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/SecurePrefs.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/SecurePrefs.kt @@ -58,17 +58,30 @@ class SecurePrefs(context: Context) { private val _preventSleep = MutableStateFlow(prefs.getBoolean("screen.preventSleep", true)) val preventSleep: StateFlow = _preventSleep - private val _manualEnabled = MutableStateFlow(prefs.getBoolean("bridge.manual.enabled", false)) + private val _manualEnabled = + MutableStateFlow(readBoolWithMigration("gateway.manual.enabled", "bridge.manual.enabled", false)) val manualEnabled: StateFlow = _manualEnabled - private val _manualHost = MutableStateFlow(prefs.getString("bridge.manual.host", "")!!) + private val _manualHost = + MutableStateFlow(readStringWithMigration("gateway.manual.host", "bridge.manual.host", "")) val manualHost: StateFlow = _manualHost - private val _manualPort = MutableStateFlow(prefs.getInt("bridge.manual.port", 18790)) + private val _manualPort = + MutableStateFlow(readIntWithMigration("gateway.manual.port", "bridge.manual.port", 18789)) val manualPort: StateFlow = _manualPort + private val _manualTls = + MutableStateFlow(readBoolWithMigration("gateway.manual.tls", null, true)) + val manualTls: StateFlow = _manualTls + private val _lastDiscoveredStableId = - MutableStateFlow(prefs.getString("bridge.lastDiscoveredStableId", "")!!) + MutableStateFlow( + readStringWithMigration( + "gateway.lastDiscoveredStableID", + "bridge.lastDiscoveredStableId", + "", + ), + ) val lastDiscoveredStableId: StateFlow = _lastDiscoveredStableId private val _canvasDebugStatusEnabled = @@ -86,7 +99,7 @@ class SecurePrefs(context: Context) { fun setLastDiscoveredStableId(value: String) { val trimmed = value.trim() - prefs.edit { putString("bridge.lastDiscoveredStableId", trimmed) } + prefs.edit { putString("gateway.lastDiscoveredStableID", trimmed) } _lastDiscoveredStableId.value = trimmed } @@ -117,46 +130,77 @@ class SecurePrefs(context: Context) { } fun setManualEnabled(value: Boolean) { - prefs.edit { putBoolean("bridge.manual.enabled", value) } + prefs.edit { putBoolean("gateway.manual.enabled", value) } _manualEnabled.value = value } fun setManualHost(value: String) { val trimmed = value.trim() - prefs.edit { putString("bridge.manual.host", trimmed) } + prefs.edit { putString("gateway.manual.host", trimmed) } _manualHost.value = trimmed } fun setManualPort(value: Int) { - prefs.edit { putInt("bridge.manual.port", value) } + prefs.edit { putInt("gateway.manual.port", value) } _manualPort.value = value } + fun setManualTls(value: Boolean) { + prefs.edit { putBoolean("gateway.manual.tls", value) } + _manualTls.value = value + } + fun setCanvasDebugStatusEnabled(value: Boolean) { prefs.edit { putBoolean("canvas.debugStatusEnabled", value) } _canvasDebugStatusEnabled.value = value } - fun loadBridgeToken(): String? { - val key = "bridge.token.${_instanceId.value}" - return prefs.getString(key, null) + fun loadGatewayToken(): String? { + val key = "gateway.token.${_instanceId.value}" + val stored = prefs.getString(key, null)?.trim() + if (!stored.isNullOrEmpty()) return stored + val legacy = prefs.getString("bridge.token.${_instanceId.value}", null)?.trim() + return legacy?.takeIf { it.isNotEmpty() } } - fun saveBridgeToken(token: String) { - val key = "bridge.token.${_instanceId.value}" + fun saveGatewayToken(token: String) { + val key = "gateway.token.${_instanceId.value}" prefs.edit { putString(key, token.trim()) } } - fun loadBridgeTlsFingerprint(stableId: String): String? { - val key = "bridge.tls.$stableId" + fun loadGatewayPassword(): String? { + val key = "gateway.password.${_instanceId.value}" + val stored = prefs.getString(key, null)?.trim() + return stored?.takeIf { it.isNotEmpty() } + } + + fun saveGatewayPassword(password: String) { + val key = "gateway.password.${_instanceId.value}" + prefs.edit { putString(key, password.trim()) } + } + + fun loadGatewayTlsFingerprint(stableId: String): String? { + val key = "gateway.tls.$stableId" return prefs.getString(key, null)?.trim()?.takeIf { it.isNotEmpty() } } - fun saveBridgeTlsFingerprint(stableId: String, fingerprint: String) { - val key = "bridge.tls.$stableId" + fun saveGatewayTlsFingerprint(stableId: String, fingerprint: String) { + val key = "gateway.tls.$stableId" prefs.edit { putString(key, fingerprint.trim()) } } + fun getString(key: String): String? { + return prefs.getString(key, null) + } + + fun putString(key: String, value: String) { + prefs.edit { putString(key, value) } + } + + fun remove(key: String) { + prefs.edit { remove(key) } + } + private fun loadOrCreateInstanceId(): String { val existing = prefs.getString("node.instanceId", null)?.trim() if (!existing.isNullOrBlank()) return existing @@ -225,4 +269,40 @@ class SecurePrefs(context: Context) { defaultWakeWords } } + + private fun readBoolWithMigration(newKey: String, oldKey: String?, defaultValue: Boolean): Boolean { + if (prefs.contains(newKey)) { + return prefs.getBoolean(newKey, defaultValue) + } + if (oldKey != null && prefs.contains(oldKey)) { + val value = prefs.getBoolean(oldKey, defaultValue) + prefs.edit { putBoolean(newKey, value) } + return value + } + return defaultValue + } + + private fun readStringWithMigration(newKey: String, oldKey: String?, defaultValue: String): String { + if (prefs.contains(newKey)) { + return prefs.getString(newKey, defaultValue) ?: defaultValue + } + if (oldKey != null && prefs.contains(oldKey)) { + val value = prefs.getString(oldKey, defaultValue) ?: defaultValue + prefs.edit { putString(newKey, value) } + return value + } + return defaultValue + } + + private fun readIntWithMigration(newKey: String, oldKey: String?, defaultValue: Int): Int { + if (prefs.contains(newKey)) { + return prefs.getInt(newKey, defaultValue) + } + if (oldKey != null && prefs.contains(oldKey)) { + val value = prefs.getInt(oldKey, defaultValue) + prefs.edit { putInt(newKey, value) } + return value + } + return defaultValue + } } diff --git a/apps/android/app/src/main/java/com/clawdbot/android/VoiceWakeMode.kt b/apps/android/app/src/main/java/com/clawdbot/android/VoiceWakeMode.kt index e8a6eff15..6c3e2c201 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/VoiceWakeMode.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/VoiceWakeMode.kt @@ -12,4 +12,3 @@ enum class VoiceWakeMode(val rawValue: String) { } } } - diff --git a/apps/android/app/src/main/java/com/clawdbot/android/WakeWords.kt b/apps/android/app/src/main/java/com/clawdbot/android/WakeWords.kt index 855a0de7c..d54ed1e08 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/WakeWords.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/WakeWords.kt @@ -8,10 +8,14 @@ object WakeWords { return input.split(",").map { it.trim() }.filter { it.isNotEmpty() } } + fun parseIfChanged(input: String, current: List): List? { + val parsed = parseCommaSeparated(input) + return if (parsed == current) null else parsed + } + fun sanitize(words: List, defaults: List): List { val cleaned = words.map { it.trim() }.filter { it.isNotEmpty() }.take(maxWords).map { it.take(maxWordLength) } return cleaned.ifEmpty { defaults } } } - diff --git a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgePairingClient.kt b/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgePairingClient.kt deleted file mode 100644 index 00ecbd25e..000000000 --- a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgePairingClient.kt +++ /dev/null @@ -1,158 +0,0 @@ -package com.clawdbot.android.bridge - -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.JsonNull -import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.buildJsonObject -import java.io.BufferedReader -import java.io.BufferedWriter -import java.io.InputStreamReader -import java.io.OutputStreamWriter -import java.net.InetSocketAddress - -class BridgePairingClient { - private val json = Json { ignoreUnknownKeys = true } - - data class Hello( - val nodeId: String, - val displayName: String?, - val token: String?, - val platform: String?, - val version: String?, - val deviceFamily: String?, - val modelIdentifier: String?, - val caps: List?, - val commands: List?, - ) - - data class PairResult(val ok: Boolean, val token: String?, val error: String? = null) - - suspend fun pairAndHello( - endpoint: BridgeEndpoint, - hello: Hello, - tls: BridgeTlsParams? = null, - onTlsFingerprint: ((String) -> Unit)? = null, - ): PairResult = - withContext(Dispatchers.IO) { - if (tls != null) { - try { - return@withContext pairAndHelloWithTls(endpoint, hello, tls, onTlsFingerprint) - } catch (e: Exception) { - if (tls.required) throw e - } - } - pairAndHelloWithTls(endpoint, hello, null, null) - } - - private fun pairAndHelloWithTls( - endpoint: BridgeEndpoint, - hello: Hello, - tls: BridgeTlsParams?, - onTlsFingerprint: ((String) -> Unit)?, - ): PairResult { - val socket = - createBridgeSocket(tls) { fingerprint -> - onTlsFingerprint?.invoke(fingerprint) - } - socket.tcpNoDelay = true - try { - socket.connect(InetSocketAddress(endpoint.host, endpoint.port), 8_000) - socket.soTimeout = 60_000 - startTlsHandshakeIfNeeded(socket) - - val reader = BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.UTF_8)) - val writer = BufferedWriter(OutputStreamWriter(socket.getOutputStream(), Charsets.UTF_8)) - - fun send(line: String) { - writer.write(line) - writer.write("\n") - writer.flush() - } - - fun sendJson(obj: JsonObject) = send(obj.toString()) - - sendJson( - buildJsonObject { - put("type", JsonPrimitive("hello")) - put("nodeId", JsonPrimitive(hello.nodeId)) - hello.displayName?.let { put("displayName", JsonPrimitive(it)) } - hello.token?.let { put("token", JsonPrimitive(it)) } - hello.platform?.let { put("platform", JsonPrimitive(it)) } - hello.version?.let { put("version", JsonPrimitive(it)) } - hello.deviceFamily?.let { put("deviceFamily", JsonPrimitive(it)) } - hello.modelIdentifier?.let { put("modelIdentifier", JsonPrimitive(it)) } - hello.caps?.let { put("caps", JsonArray(it.map(::JsonPrimitive))) } - hello.commands?.let { put("commands", JsonArray(it.map(::JsonPrimitive))) } - }, - ) - - val firstObj = json.parseToJsonElement(reader.readLine()).asObjectOrNull() - ?: return PairResult(ok = false, token = null, error = "unexpected bridge response") - return when (firstObj["type"].asStringOrNull()) { - "hello-ok" -> PairResult(ok = true, token = hello.token) - "error" -> { - val code = firstObj["code"].asStringOrNull() ?: "UNAVAILABLE" - val message = firstObj["message"].asStringOrNull() ?: "pairing required" - if (code != "NOT_PAIRED" && code != "UNAUTHORIZED") { - return PairResult(ok = false, token = null, error = "$code: $message") - } - - sendJson( - buildJsonObject { - put("type", JsonPrimitive("pair-request")) - put("nodeId", JsonPrimitive(hello.nodeId)) - hello.displayName?.let { put("displayName", JsonPrimitive(it)) } - hello.platform?.let { put("platform", JsonPrimitive(it)) } - hello.version?.let { put("version", JsonPrimitive(it)) } - hello.deviceFamily?.let { put("deviceFamily", JsonPrimitive(it)) } - hello.modelIdentifier?.let { put("modelIdentifier", JsonPrimitive(it)) } - hello.caps?.let { put("caps", JsonArray(it.map(::JsonPrimitive))) } - hello.commands?.let { put("commands", JsonArray(it.map(::JsonPrimitive))) } - }, - ) - - while (true) { - val nextLine = reader.readLine() ?: break - val next = json.parseToJsonElement(nextLine).asObjectOrNull() ?: continue - when (next["type"].asStringOrNull()) { - "pair-ok" -> { - val token = next["token"].asStringOrNull() - return PairResult(ok = !token.isNullOrBlank(), token = token) - } - "error" -> { - val c = next["code"].asStringOrNull() ?: "UNAVAILABLE" - val m = next["message"].asStringOrNull() ?: "pairing failed" - return PairResult(ok = false, token = null, error = "$c: $m") - } - } - } - PairResult(ok = false, token = null, error = "pairing failed") - } - else -> PairResult(ok = false, token = null, error = "unexpected bridge response") - } - } catch (e: Exception) { - val message = e.message?.trim().orEmpty().ifEmpty { "gateway unreachable" } - return PairResult(ok = false, token = null, error = message) - } finally { - try { - socket.close() - } catch (_: Throwable) { - // ignore - } - } - } -} - -private fun JsonElement?.asObjectOrNull(): JsonObject? = this as? JsonObject - -private fun JsonElement?.asStringOrNull(): String? = - when (this) { - is JsonNull -> null - is JsonPrimitive -> content - else -> null - } diff --git a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeSession.kt b/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeSession.kt deleted file mode 100644 index 768ec9128..000000000 --- a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeSession.kt +++ /dev/null @@ -1,398 +0,0 @@ -package com.clawdbot.android.bridge - -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.cancelAndJoin -import kotlinx.coroutines.delay -import kotlinx.coroutines.isActive -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import kotlinx.coroutines.withContext -import com.clawdbot.android.BuildConfig -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonNull -import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.buildJsonObject -import java.io.BufferedReader -import java.io.BufferedWriter -import java.io.InputStreamReader -import java.io.OutputStreamWriter -import java.net.InetSocketAddress -import java.net.URI -import java.net.Socket -import java.util.UUID -import java.util.concurrent.ConcurrentHashMap - -class BridgeSession( - private val scope: CoroutineScope, - private val onConnected: (serverName: String, remoteAddress: String?, mainSessionKey: String?) -> Unit, - private val onDisconnected: (message: String) -> Unit, - private val onEvent: (event: String, payloadJson: String?) -> Unit, - private val onInvoke: suspend (InvokeRequest) -> InvokeResult, - private val onTlsFingerprint: ((stableId: String, fingerprint: String) -> Unit)? = null, -) { - data class Hello( - val nodeId: String, - val displayName: String?, - val token: String?, - val platform: String?, - val version: String?, - val deviceFamily: String?, - val modelIdentifier: String?, - val caps: List?, - val commands: List?, - ) - - data class InvokeRequest(val id: String, val command: String, val paramsJson: String?) - - data class InvokeResult(val ok: Boolean, val payloadJson: String?, val error: ErrorShape?) { - companion object { - fun ok(payloadJson: String?) = InvokeResult(ok = true, payloadJson = payloadJson, error = null) - fun error(code: String, message: String) = - InvokeResult(ok = false, payloadJson = null, error = ErrorShape(code = code, message = message)) - } - } - - data class ErrorShape(val code: String, val message: String) - - private val json = Json { ignoreUnknownKeys = true } - private val writeLock = Mutex() - private val pending = ConcurrentHashMap>() - @Volatile private var canvasHostUrl: String? = null - @Volatile private var mainSessionKey: String? = null - - private data class DesiredConnection( - val endpoint: BridgeEndpoint, - val hello: Hello, - val tls: BridgeTlsParams?, - ) - - private var desired: DesiredConnection? = null - private var job: Job? = null - - fun connect(endpoint: BridgeEndpoint, hello: Hello, tls: BridgeTlsParams? = null) { - desired = DesiredConnection(endpoint, hello, tls) - if (job == null) { - job = scope.launch(Dispatchers.IO) { runLoop() } - } - } - - suspend fun updateHello(hello: Hello) { - val target = desired ?: return - desired = target.copy(hello = hello) - val conn = currentConnection ?: return - conn.sendJson(buildHelloJson(hello)) - } - - fun disconnect() { - desired = null - // Unblock connectOnce() read loop. Coroutine cancellation alone won't interrupt BufferedReader.readLine(). - currentConnection?.closeQuietly() - scope.launch(Dispatchers.IO) { - job?.cancelAndJoin() - job = null - canvasHostUrl = null - mainSessionKey = null - onDisconnected("Offline") - } - } - - fun currentCanvasHostUrl(): String? = canvasHostUrl - fun currentMainSessionKey(): String? = mainSessionKey - - suspend fun sendEvent(event: String, payloadJson: String?) { - val conn = currentConnection ?: return - conn.sendJson( - buildJsonObject { - put("type", JsonPrimitive("event")) - put("event", JsonPrimitive(event)) - if (payloadJson != null) put("payloadJSON", JsonPrimitive(payloadJson)) else put("payloadJSON", JsonNull) - }, - ) - } - - suspend fun request(method: String, paramsJson: String?): String { - val conn = currentConnection ?: throw IllegalStateException("not connected") - val id = UUID.randomUUID().toString() - val deferred = CompletableDeferred() - pending[id] = deferred - conn.sendJson( - buildJsonObject { - put("type", JsonPrimitive("req")) - put("id", JsonPrimitive(id)) - put("method", JsonPrimitive(method)) - if (paramsJson != null) put("paramsJSON", JsonPrimitive(paramsJson)) else put("paramsJSON", JsonNull) - }, - ) - val res = deferred.await() - if (res.ok) return res.payloadJson ?: "" - val err = res.error - throw IllegalStateException("${err?.code ?: "UNAVAILABLE"}: ${err?.message ?: "request failed"}") - } - - private data class RpcResponse(val id: String, val ok: Boolean, val payloadJson: String?, val error: ErrorShape?) - - private class Connection(private val socket: Socket, private val reader: BufferedReader, private val writer: BufferedWriter, private val writeLock: Mutex) { - val remoteAddress: String? = - socket.inetAddress?.hostAddress?.takeIf { it.isNotBlank() }?.let { "${it}:${socket.port}" } - - suspend fun sendJson(obj: JsonObject) { - writeLock.withLock { - writer.write(obj.toString()) - writer.write("\n") - writer.flush() - } - } - - fun closeQuietly() { - try { - socket.close() - } catch (_: Throwable) { - // ignore - } - } - } - - @Volatile private var currentConnection: Connection? = null - - private suspend fun runLoop() { - var attempt = 0 - while (scope.isActive) { - val target = desired - if (target == null) { - currentConnection?.closeQuietly() - currentConnection = null - delay(250) - continue - } - - val (endpoint, hello, tls) = target - try { - onDisconnected(if (attempt == 0) "Connecting…" else "Reconnecting…") - connectOnce(endpoint, hello, tls) - attempt = 0 - } catch (err: Throwable) { - attempt += 1 - onDisconnected("Bridge error: ${err.message ?: err::class.java.simpleName}") - val sleepMs = minOf(8_000L, (350.0 * Math.pow(1.7, attempt.toDouble())).toLong()) - delay(sleepMs) - } - } - } - - private fun invokeErrorFromThrowable(err: Throwable): InvokeResult { - val msg = err.message?.trim().takeIf { !it.isNullOrEmpty() } ?: err::class.java.simpleName - val parts = msg.split(":", limit = 2) - if (parts.size == 2) { - val code = parts[0].trim() - val rest = parts[1].trim() - if (code.isNotEmpty() && code.all { it.isUpperCase() || it == '_' }) { - return InvokeResult.error(code = code, message = rest.ifEmpty { msg }) - } - } - return InvokeResult.error(code = "UNAVAILABLE", message = msg) - } - - private suspend fun connectOnce(endpoint: BridgeEndpoint, hello: Hello, tls: BridgeTlsParams?) = - withContext(Dispatchers.IO) { - if (tls != null) { - try { - connectWithSocket(endpoint, hello, tls) - return@withContext - } catch (err: Throwable) { - if (tls.required) throw err - } - } - connectWithSocket(endpoint, hello, null) - } - - private suspend fun connectWithSocket(endpoint: BridgeEndpoint, hello: Hello, tls: BridgeTlsParams?) { - val socket = - createBridgeSocket(tls) { fingerprint -> - onTlsFingerprint?.invoke(tls?.stableId ?: endpoint.stableId, fingerprint) - } - socket.tcpNoDelay = true - socket.connect(InetSocketAddress(endpoint.host, endpoint.port), 8_000) - socket.soTimeout = 0 - startTlsHandshakeIfNeeded(socket) - - val reader = BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.UTF_8)) - val writer = BufferedWriter(OutputStreamWriter(socket.getOutputStream(), Charsets.UTF_8)) - - val conn = Connection(socket, reader, writer, writeLock) - currentConnection = conn - - try { - conn.sendJson(buildHelloJson(hello)) - - val firstLine = reader.readLine() ?: throw IllegalStateException("bridge closed connection") - val first = json.parseToJsonElement(firstLine).asObjectOrNull() - ?: throw IllegalStateException("unexpected bridge response") - when (first["type"].asStringOrNull()) { - "hello-ok" -> { - val name = first["serverName"].asStringOrNull() ?: "Bridge" - val rawCanvasUrl = first["canvasHostUrl"].asStringOrNull()?.trim()?.ifEmpty { null } - val rawMainSessionKey = first["mainSessionKey"].asStringOrNull()?.trim()?.ifEmpty { null } - canvasHostUrl = normalizeCanvasHostUrl(rawCanvasUrl, endpoint) - mainSessionKey = rawMainSessionKey - if (BuildConfig.DEBUG) { - // Local JVM unit tests use android.jar stubs; Log.d can throw "not mocked". - runCatching { - android.util.Log.d( - "ClawdbotBridge", - "canvasHostUrl resolved=${canvasHostUrl ?: "none"} (raw=${rawCanvasUrl ?: "none"})", - ) - } - } - onConnected(name, conn.remoteAddress, rawMainSessionKey) - } - "error" -> { - val code = first["code"].asStringOrNull() ?: "UNAVAILABLE" - val msg = first["message"].asStringOrNull() ?: "connect failed" - throw IllegalStateException("$code: $msg") - } - else -> throw IllegalStateException("unexpected bridge response") - } - - while (scope.isActive) { - val line = reader.readLine() ?: break - val frame = json.parseToJsonElement(line).asObjectOrNull() ?: continue - when (frame["type"].asStringOrNull()) { - "event" -> { - val event = frame["event"].asStringOrNull() ?: continue - val payload = frame["payloadJSON"].asStringOrNull() - onEvent(event, payload) - } - "ping" -> { - val id = frame["id"].asStringOrNull() ?: "" - conn.sendJson(buildJsonObject { put("type", JsonPrimitive("pong")); put("id", JsonPrimitive(id)) }) - } - "res" -> { - val id = frame["id"].asStringOrNull() ?: continue - val ok = frame["ok"].asBooleanOrNull() ?: false - val payloadJson = frame["payloadJSON"].asStringOrNull() - val error = - frame["error"]?.let { - val obj = it.asObjectOrNull() ?: return@let null - val code = obj["code"].asStringOrNull() ?: "UNAVAILABLE" - val msg = obj["message"].asStringOrNull() ?: "request failed" - ErrorShape(code, msg) - } - pending.remove(id)?.complete(RpcResponse(id, ok, payloadJson, error)) - } - "invoke" -> { - val id = frame["id"].asStringOrNull() ?: continue - val command = frame["command"].asStringOrNull() ?: "" - val params = frame["paramsJSON"].asStringOrNull() - val result = - try { - onInvoke(InvokeRequest(id, command, params)) - } catch (err: Throwable) { - invokeErrorFromThrowable(err) - } - conn.sendJson( - buildJsonObject { - put("type", JsonPrimitive("invoke-res")) - put("id", JsonPrimitive(id)) - put("ok", JsonPrimitive(result.ok)) - if (result.payloadJson != null) put("payloadJSON", JsonPrimitive(result.payloadJson)) - if (result.error != null) { - put( - "error", - buildJsonObject { - put("code", JsonPrimitive(result.error.code)) - put("message", JsonPrimitive(result.error.message)) - }, - ) - } - }, - ) - } - "invoke-res" -> { - // gateway->node only (ignore) - } - } - } - } finally { - currentConnection = null - for ((_, waiter) in pending) { - waiter.cancel() - } - pending.clear() - conn.closeQuietly() - } - } - - private fun buildHelloJson(hello: Hello): JsonObject = - buildJsonObject { - put("type", JsonPrimitive("hello")) - put("nodeId", JsonPrimitive(hello.nodeId)) - hello.displayName?.let { put("displayName", JsonPrimitive(it)) } - hello.token?.let { put("token", JsonPrimitive(it)) } - hello.platform?.let { put("platform", JsonPrimitive(it)) } - hello.version?.let { put("version", JsonPrimitive(it)) } - hello.deviceFamily?.let { put("deviceFamily", JsonPrimitive(it)) } - hello.modelIdentifier?.let { put("modelIdentifier", JsonPrimitive(it)) } - hello.caps?.let { put("caps", JsonArray(it.map(::JsonPrimitive))) } - hello.commands?.let { put("commands", JsonArray(it.map(::JsonPrimitive))) } - } - - private fun normalizeCanvasHostUrl(raw: String?, endpoint: BridgeEndpoint): String? { - val trimmed = raw?.trim().orEmpty() - val parsed = trimmed.takeIf { it.isNotBlank() }?.let { runCatching { URI(it) }.getOrNull() } - val host = parsed?.host?.trim().orEmpty() - val port = parsed?.port ?: -1 - val scheme = parsed?.scheme?.trim().orEmpty().ifBlank { "http" } - - if (trimmed.isNotBlank() && !isLoopbackHost(host)) { - return trimmed - } - - val fallbackHost = - endpoint.tailnetDns?.trim().takeIf { !it.isNullOrEmpty() } - ?: endpoint.lanHost?.trim().takeIf { !it.isNullOrEmpty() } - ?: endpoint.host.trim() - if (fallbackHost.isEmpty()) return trimmed.ifBlank { null } - - val fallbackPort = endpoint.canvasPort ?: if (port > 0) port else 18793 - val formattedHost = if (fallbackHost.contains(":")) "[${fallbackHost}]" else fallbackHost - return "$scheme://$formattedHost:$fallbackPort" - } - - private fun isLoopbackHost(raw: String?): Boolean { - val host = raw?.trim()?.lowercase().orEmpty() - if (host.isEmpty()) return false - if (host == "localhost") return true - if (host == "::1") return true - if (host == "0.0.0.0" || host == "::") return true - return host.startsWith("127.") - } -} - -private fun JsonElement?.asObjectOrNull(): JsonObject? = this as? JsonObject - -private fun JsonElement?.asStringOrNull(): String? = - when (this) { - is JsonNull -> null - is JsonPrimitive -> content - else -> null - } - -private fun JsonElement?.asBooleanOrNull(): Boolean? = - when (this) { - is JsonPrimitive -> { - val c = content.trim() - when { - c.equals("true", ignoreCase = true) -> true - c.equals("false", ignoreCase = true) -> false - else -> null - } - } - else -> null - } diff --git a/apps/android/app/src/main/java/com/clawdbot/android/chat/ChatController.kt b/apps/android/app/src/main/java/com/clawdbot/android/chat/ChatController.kt index 794bd9edf..a8e64048c 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/chat/ChatController.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/chat/ChatController.kt @@ -1,6 +1,6 @@ package com.clawdbot.android.chat -import com.clawdbot.android.bridge.BridgeSession +import com.clawdbot.android.gateway.GatewaySession import java.util.UUID import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.CoroutineScope @@ -20,8 +20,9 @@ import kotlinx.serialization.json.buildJsonObject class ChatController( private val scope: CoroutineScope, - private val session: BridgeSession, + private val session: GatewaySession, private val json: Json, + private val supportsChatSubscribe: Boolean, ) { private val _sessionKey = MutableStateFlow("main") val sessionKey: StateFlow = _sessionKey.asStateFlow() @@ -224,7 +225,7 @@ class ChatController( } } - fun handleBridgeEvent(event: String, payloadJson: String?) { + fun handleGatewayEvent(event: String, payloadJson: String?) { when (event) { "tick" -> { scope.launch { pollHealthIfNeeded(force = false) } @@ -259,10 +260,12 @@ class ChatController( val key = _sessionKey.value try { - try { - session.sendEvent("chat.subscribe", """{"sessionKey":"$key"}""") - } catch (_: Throwable) { - // best-effort + if (supportsChatSubscribe) { + try { + session.sendNodeEvent("chat.subscribe", """{"sessionKey":"$key"}""") + } catch (_: Throwable) { + // best-effort + } } val historyJson = session.request("chat.history", """{"sessionKey":"$key"}""") diff --git a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BonjourEscapes.kt b/apps/android/app/src/main/java/com/clawdbot/android/gateway/BonjourEscapes.kt similarity index 96% rename from apps/android/app/src/main/java/com/clawdbot/android/bridge/BonjourEscapes.kt rename to apps/android/app/src/main/java/com/clawdbot/android/gateway/BonjourEscapes.kt index 9334572fd..c05d41b4b 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BonjourEscapes.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/gateway/BonjourEscapes.kt @@ -1,4 +1,4 @@ -package com.clawdbot.android.bridge +package com.clawdbot.android.gateway object BonjourEscapes { fun decode(input: String): String { diff --git a/apps/android/app/src/main/java/com/clawdbot/android/gateway/DeviceAuthStore.kt b/apps/android/app/src/main/java/com/clawdbot/android/gateway/DeviceAuthStore.kt new file mode 100644 index 000000000..88643d8d7 --- /dev/null +++ b/apps/android/app/src/main/java/com/clawdbot/android/gateway/DeviceAuthStore.kt @@ -0,0 +1,26 @@ +package com.clawdbot.android.gateway + +import com.clawdbot.android.SecurePrefs + +class DeviceAuthStore(private val prefs: SecurePrefs) { + fun loadToken(deviceId: String, role: String): String? { + val key = tokenKey(deviceId, role) + return prefs.getString(key)?.trim()?.takeIf { it.isNotEmpty() } + } + + fun saveToken(deviceId: String, role: String, token: String) { + val key = tokenKey(deviceId, role) + prefs.putString(key, token.trim()) + } + + fun clearToken(deviceId: String, role: String) { + val key = tokenKey(deviceId, role) + prefs.remove(key) + } + + private fun tokenKey(deviceId: String, role: String): String { + val normalizedDevice = deviceId.trim().lowercase() + val normalizedRole = role.trim().lowercase() + return "gateway.deviceToken.$normalizedDevice.$normalizedRole" + } +} diff --git a/apps/android/app/src/main/java/com/clawdbot/android/gateway/DeviceIdentityStore.kt b/apps/android/app/src/main/java/com/clawdbot/android/gateway/DeviceIdentityStore.kt new file mode 100644 index 000000000..72500b750 --- /dev/null +++ b/apps/android/app/src/main/java/com/clawdbot/android/gateway/DeviceIdentityStore.kt @@ -0,0 +1,146 @@ +package com.clawdbot.android.gateway + +import android.content.Context +import android.util.Base64 +import java.io.File +import java.security.KeyFactory +import java.security.KeyPairGenerator +import java.security.MessageDigest +import java.security.Signature +import java.security.spec.PKCS8EncodedKeySpec +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +@Serializable +data class DeviceIdentity( + val deviceId: String, + val publicKeyRawBase64: String, + val privateKeyPkcs8Base64: String, + val createdAtMs: Long, +) + +class DeviceIdentityStore(context: Context) { + private val json = Json { ignoreUnknownKeys = true } + private val identityFile = File(context.filesDir, "clawdbot/identity/device.json") + + @Synchronized + fun loadOrCreate(): DeviceIdentity { + val existing = load() + if (existing != null) { + val derived = deriveDeviceId(existing.publicKeyRawBase64) + if (derived != null && derived != existing.deviceId) { + val updated = existing.copy(deviceId = derived) + save(updated) + return updated + } + return existing + } + val fresh = generate() + save(fresh) + return fresh + } + + fun signPayload(payload: String, identity: DeviceIdentity): String? { + return try { + val privateKeyBytes = Base64.decode(identity.privateKeyPkcs8Base64, Base64.DEFAULT) + val keySpec = PKCS8EncodedKeySpec(privateKeyBytes) + val keyFactory = KeyFactory.getInstance("Ed25519") + val privateKey = keyFactory.generatePrivate(keySpec) + val signature = Signature.getInstance("Ed25519") + signature.initSign(privateKey) + signature.update(payload.toByteArray(Charsets.UTF_8)) + base64UrlEncode(signature.sign()) + } catch (_: Throwable) { + null + } + } + + fun publicKeyBase64Url(identity: DeviceIdentity): String? { + return try { + val raw = Base64.decode(identity.publicKeyRawBase64, Base64.DEFAULT) + base64UrlEncode(raw) + } catch (_: Throwable) { + null + } + } + + private fun load(): DeviceIdentity? { + return try { + if (!identityFile.exists()) return null + val raw = identityFile.readText(Charsets.UTF_8) + val decoded = json.decodeFromString(DeviceIdentity.serializer(), raw) + if (decoded.deviceId.isBlank() || + decoded.publicKeyRawBase64.isBlank() || + decoded.privateKeyPkcs8Base64.isBlank() + ) { + null + } else { + decoded + } + } catch (_: Throwable) { + null + } + } + + private fun save(identity: DeviceIdentity) { + try { + identityFile.parentFile?.mkdirs() + val encoded = json.encodeToString(DeviceIdentity.serializer(), identity) + identityFile.writeText(encoded, Charsets.UTF_8) + } catch (_: Throwable) { + // best-effort only + } + } + + private fun generate(): DeviceIdentity { + val keyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair() + val spki = keyPair.public.encoded + val rawPublic = stripSpkiPrefix(spki) + val deviceId = sha256Hex(rawPublic) + val privateKey = keyPair.private.encoded + return DeviceIdentity( + deviceId = deviceId, + publicKeyRawBase64 = Base64.encodeToString(rawPublic, Base64.NO_WRAP), + privateKeyPkcs8Base64 = Base64.encodeToString(privateKey, Base64.NO_WRAP), + createdAtMs = System.currentTimeMillis(), + ) + } + + private fun deriveDeviceId(publicKeyRawBase64: String): String? { + return try { + val raw = Base64.decode(publicKeyRawBase64, Base64.DEFAULT) + sha256Hex(raw) + } catch (_: Throwable) { + null + } + } + + private fun stripSpkiPrefix(spki: ByteArray): ByteArray { + if (spki.size == ED25519_SPKI_PREFIX.size + 32 && + spki.copyOfRange(0, ED25519_SPKI_PREFIX.size).contentEquals(ED25519_SPKI_PREFIX) + ) { + return spki.copyOfRange(ED25519_SPKI_PREFIX.size, spki.size) + } + return spki + } + + private fun sha256Hex(data: ByteArray): String { + val digest = MessageDigest.getInstance("SHA-256").digest(data) + val out = StringBuilder(digest.size * 2) + for (byte in digest) { + out.append(String.format("%02x", byte)) + } + return out.toString() + } + + private fun base64UrlEncode(data: ByteArray): String { + return Base64.encodeToString(data, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING) + } + + companion object { + private val ED25519_SPKI_PREFIX = + byteArrayOf( + 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, + ) + } +} diff --git a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeDiscovery.kt b/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayDiscovery.kt similarity index 93% rename from apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeDiscovery.kt rename to apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayDiscovery.kt index d619200bf..121a95485 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeDiscovery.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayDiscovery.kt @@ -1,4 +1,4 @@ -package com.clawdbot.android.bridge +package com.clawdbot.android.gateway import android.content.Context import android.net.ConnectivityManager @@ -44,21 +44,21 @@ import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException @Suppress("DEPRECATION") -class BridgeDiscovery( +class GatewayDiscovery( context: Context, private val scope: CoroutineScope, ) { private val nsd = context.getSystemService(NsdManager::class.java) private val connectivity = context.getSystemService(ConnectivityManager::class.java) private val dns = DnsResolver.getInstance() - private val serviceType = "_clawdbot-bridge._tcp." + private val serviceType = "_clawdbot-gw._tcp." private val wideAreaDomain = "clawdbot.internal." - private val logTag = "Clawdbot/BridgeDiscovery" + private val logTag = "Clawdbot/GatewayDiscovery" - private val localById = ConcurrentHashMap() - private val unicastById = ConcurrentHashMap() - private val _bridges = MutableStateFlow>(emptyList()) - val bridges: StateFlow> = _bridges.asStateFlow() + private val localById = ConcurrentHashMap() + private val unicastById = ConcurrentHashMap() + private val _gateways = MutableStateFlow>(emptyList()) + val gateways: StateFlow> = _gateways.asStateFlow() private val _statusText = MutableStateFlow("Searching…") val statusText: StateFlow = _statusText.asStateFlow() @@ -77,7 +77,7 @@ class BridgeDiscovery( override fun onDiscoveryStopped(serviceType: String) {} override fun onServiceFound(serviceInfo: NsdServiceInfo) { - if (serviceInfo.serviceType != this@BridgeDiscovery.serviceType) return + if (serviceInfo.serviceType != this@GatewayDiscovery.serviceType) return resolve(serviceInfo) } @@ -141,13 +141,12 @@ class BridgeDiscovery( val lanHost = txt(resolved, "lanHost") val tailnetDns = txt(resolved, "tailnetDns") val gatewayPort = txtInt(resolved, "gatewayPort") - val bridgePort = txtInt(resolved, "bridgePort") val canvasPort = txtInt(resolved, "canvasPort") - val tlsEnabled = txtBool(resolved, "bridgeTls") - val tlsFingerprint = txt(resolved, "bridgeTlsSha256") + val tlsEnabled = txtBool(resolved, "gatewayTls") + val tlsFingerprint = txt(resolved, "gatewayTlsSha256") val id = stableId(serviceName, "local.") localById[id] = - BridgeEndpoint( + GatewayEndpoint( stableId = id, name = displayName, host = host, @@ -155,7 +154,6 @@ class BridgeDiscovery( lanHost = lanHost, tailnetDns = tailnetDns, gatewayPort = gatewayPort, - bridgePort = bridgePort, canvasPort = canvasPort, tlsEnabled = tlsEnabled, tlsFingerprintSha256 = tlsFingerprint, @@ -167,7 +165,7 @@ class BridgeDiscovery( } private fun publish() { - _bridges.value = + _gateways.value = (localById.values + unicastById.values).sortedBy { it.name.lowercase() } _statusText.value = buildStatusText() } @@ -186,7 +184,7 @@ class BridgeDiscovery( } return when { - localCount == 0 && wideRcode == null -> "Searching for bridges…" + localCount == 0 && wideRcode == null -> "Searching for gateways…" localCount == 0 -> "$wide" else -> "Local: $localCount • $wide" } @@ -223,7 +221,7 @@ class BridgeDiscovery( val ptrMsg = lookupUnicastMessage(ptrName, Type.PTR) ?: return val ptrRecords = records(ptrMsg, Section.ANSWER).mapNotNull { it as? PTRRecord } - val next = LinkedHashMap() + val next = LinkedHashMap() for (ptr in ptrRecords) { val instanceFqdn = ptr.target.toString() val srv = @@ -259,13 +257,12 @@ class BridgeDiscovery( val lanHost = txtValue(txt, "lanHost") val tailnetDns = txtValue(txt, "tailnetDns") val gatewayPort = txtIntValue(txt, "gatewayPort") - val bridgePort = txtIntValue(txt, "bridgePort") val canvasPort = txtIntValue(txt, "canvasPort") - val tlsEnabled = txtBoolValue(txt, "bridgeTls") - val tlsFingerprint = txtValue(txt, "bridgeTlsSha256") + val tlsEnabled = txtBoolValue(txt, "gatewayTls") + val tlsFingerprint = txtValue(txt, "gatewayTlsSha256") val id = stableId(instanceName, domain) next[id] = - BridgeEndpoint( + GatewayEndpoint( stableId = id, name = displayName, host = host, @@ -273,7 +270,6 @@ class BridgeDiscovery( lanHost = lanHost, tailnetDns = tailnetDns, gatewayPort = gatewayPort, - bridgePort = bridgePort, canvasPort = canvasPort, tlsEnabled = tlsEnabled, tlsFingerprintSha256 = tlsFingerprint, diff --git a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeEndpoint.kt b/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayEndpoint.kt similarity index 68% rename from apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeEndpoint.kt rename to apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayEndpoint.kt index c86352d76..ab8aeacc9 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeEndpoint.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayEndpoint.kt @@ -1,6 +1,6 @@ -package com.clawdbot.android.bridge +package com.clawdbot.android.gateway -data class BridgeEndpoint( +data class GatewayEndpoint( val stableId: String, val name: String, val host: String, @@ -8,15 +8,14 @@ data class BridgeEndpoint( val lanHost: String? = null, val tailnetDns: String? = null, val gatewayPort: Int? = null, - val bridgePort: Int? = null, val canvasPort: Int? = null, val tlsEnabled: Boolean = false, val tlsFingerprintSha256: String? = null, ) { companion object { - fun manual(host: String, port: Int): BridgeEndpoint = - BridgeEndpoint( - stableId = "manual|$host|$port", + fun manual(host: String, port: Int): GatewayEndpoint = + GatewayEndpoint( + stableId = "manual|${host.lowercase()}|$port", name = "$host:$port", host = host, port = port, diff --git a/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayProtocol.kt b/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayProtocol.kt new file mode 100644 index 000000000..4873de122 --- /dev/null +++ b/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayProtocol.kt @@ -0,0 +1,3 @@ +package com.clawdbot.android.gateway + +const val GATEWAY_PROTOCOL_VERSION = 3 diff --git a/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewaySession.kt b/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewaySession.kt new file mode 100644 index 000000000..ddd249a8e --- /dev/null +++ b/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewaySession.kt @@ -0,0 +1,683 @@ +package com.clawdbot.android.gateway + +import android.util.Log +import java.util.Locale +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener + +data class GatewayClientInfo( + val id: String, + val displayName: String?, + val version: String, + val platform: String, + val mode: String, + val instanceId: String?, + val deviceFamily: String?, + val modelIdentifier: String?, +) + +data class GatewayConnectOptions( + val role: String, + val scopes: List, + val caps: List, + val commands: List, + val permissions: Map, + val client: GatewayClientInfo, + val userAgent: String? = null, +) + +class GatewaySession( + private val scope: CoroutineScope, + private val identityStore: DeviceIdentityStore, + private val deviceAuthStore: DeviceAuthStore, + private val onConnected: (serverName: String?, remoteAddress: String?, mainSessionKey: String?) -> Unit, + private val onDisconnected: (message: String) -> Unit, + private val onEvent: (event: String, payloadJson: String?) -> Unit, + private val onInvoke: (suspend (InvokeRequest) -> InvokeResult)? = null, + private val onTlsFingerprint: ((stableId: String, fingerprint: String) -> Unit)? = null, +) { + data class InvokeRequest( + val id: String, + val nodeId: String, + val command: String, + val paramsJson: String?, + val timeoutMs: Long?, + ) + + data class InvokeResult(val ok: Boolean, val payloadJson: String?, val error: ErrorShape?) { + companion object { + fun ok(payloadJson: String?) = InvokeResult(ok = true, payloadJson = payloadJson, error = null) + fun error(code: String, message: String) = + InvokeResult(ok = false, payloadJson = null, error = ErrorShape(code = code, message = message)) + } + } + + data class ErrorShape(val code: String, val message: String) + + private val json = Json { ignoreUnknownKeys = true } + private val writeLock = Mutex() + private val pending = ConcurrentHashMap>() + + @Volatile private var canvasHostUrl: String? = null + @Volatile private var mainSessionKey: String? = null + + private data class DesiredConnection( + val endpoint: GatewayEndpoint, + val token: String?, + val password: String?, + val options: GatewayConnectOptions, + val tls: GatewayTlsParams?, + ) + + private var desired: DesiredConnection? = null + private var job: Job? = null + @Volatile private var currentConnection: Connection? = null + + fun connect( + endpoint: GatewayEndpoint, + token: String?, + password: String?, + options: GatewayConnectOptions, + tls: GatewayTlsParams? = null, + ) { + desired = DesiredConnection(endpoint, token, password, options, tls) + if (job == null) { + job = scope.launch(Dispatchers.IO) { runLoop() } + } + } + + fun disconnect() { + desired = null + currentConnection?.closeQuietly() + scope.launch(Dispatchers.IO) { + job?.cancelAndJoin() + job = null + canvasHostUrl = null + mainSessionKey = null + onDisconnected("Offline") + } + } + + fun reconnect() { + currentConnection?.closeQuietly() + } + + fun currentCanvasHostUrl(): String? = canvasHostUrl + fun currentMainSessionKey(): String? = mainSessionKey + + suspend fun sendNodeEvent(event: String, payloadJson: String?) { + val conn = currentConnection ?: return + val parsedPayload = payloadJson?.let { parseJsonOrNull(it) } + val params = + buildJsonObject { + put("event", JsonPrimitive(event)) + if (parsedPayload != null) { + put("payload", parsedPayload) + } else if (payloadJson != null) { + put("payloadJSON", JsonPrimitive(payloadJson)) + } else { + put("payloadJSON", JsonNull) + } + } + try { + conn.request("node.event", params, timeoutMs = 8_000) + } catch (err: Throwable) { + Log.w("ClawdbotGateway", "node.event failed: ${err.message ?: err::class.java.simpleName}") + } + } + + suspend fun request(method: String, paramsJson: String?, timeoutMs: Long = 15_000): String { + val conn = currentConnection ?: throw IllegalStateException("not connected") + val params = + if (paramsJson.isNullOrBlank()) { + null + } else { + json.parseToJsonElement(paramsJson) + } + val res = conn.request(method, params, timeoutMs) + if (res.ok) return res.payloadJson ?: "" + val err = res.error + throw IllegalStateException("${err?.code ?: "UNAVAILABLE"}: ${err?.message ?: "request failed"}") + } + + private data class RpcResponse(val id: String, val ok: Boolean, val payloadJson: String?, val error: ErrorShape?) + + private inner class Connection( + private val endpoint: GatewayEndpoint, + private val token: String?, + private val password: String?, + private val options: GatewayConnectOptions, + private val tls: GatewayTlsParams?, + ) { + private val connectDeferred = CompletableDeferred() + private val closedDeferred = CompletableDeferred() + private val isClosed = AtomicBoolean(false) + private val connectNonceDeferred = CompletableDeferred() + private val client: OkHttpClient = buildClient() + private var socket: WebSocket? = null + private val loggerTag = "ClawdbotGateway" + + val remoteAddress: String = + if (endpoint.host.contains(":")) { + "[${endpoint.host}]:${endpoint.port}" + } else { + "${endpoint.host}:${endpoint.port}" + } + + suspend fun connect() { + val scheme = if (tls != null) "wss" else "ws" + val url = "$scheme://${endpoint.host}:${endpoint.port}" + val request = Request.Builder().url(url).build() + socket = client.newWebSocket(request, Listener()) + try { + connectDeferred.await() + } catch (err: Throwable) { + throw err + } + } + + suspend fun request(method: String, params: JsonElement?, timeoutMs: Long): RpcResponse { + val id = UUID.randomUUID().toString() + val deferred = CompletableDeferred() + pending[id] = deferred + val frame = + buildJsonObject { + put("type", JsonPrimitive("req")) + put("id", JsonPrimitive(id)) + put("method", JsonPrimitive(method)) + if (params != null) put("params", params) + } + sendJson(frame) + return try { + withTimeout(timeoutMs) { deferred.await() } + } catch (err: TimeoutCancellationException) { + pending.remove(id) + throw IllegalStateException("request timeout") + } + } + + suspend fun sendJson(obj: JsonObject) { + val jsonString = obj.toString() + writeLock.withLock { + socket?.send(jsonString) + } + } + + suspend fun awaitClose() = closedDeferred.await() + + fun closeQuietly() { + if (isClosed.compareAndSet(false, true)) { + socket?.close(1000, "bye") + socket = null + closedDeferred.complete(Unit) + } + } + + private fun buildClient(): OkHttpClient { + val builder = OkHttpClient.Builder() + val tlsConfig = buildGatewayTlsConfig(tls) { fingerprint -> + onTlsFingerprint?.invoke(tls?.stableId ?: endpoint.stableId, fingerprint) + } + if (tlsConfig != null) { + builder.sslSocketFactory(tlsConfig.sslSocketFactory, tlsConfig.trustManager) + builder.hostnameVerifier(tlsConfig.hostnameVerifier) + } + return builder.build() + } + + private inner class Listener : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) { + scope.launch { + try { + val nonce = awaitConnectNonce() + sendConnect(nonce) + } catch (err: Throwable) { + connectDeferred.completeExceptionally(err) + closeQuietly() + } + } + } + + override fun onMessage(webSocket: WebSocket, text: String) { + scope.launch { handleMessage(text) } + } + + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + if (!connectDeferred.isCompleted) { + connectDeferred.completeExceptionally(t) + } + if (isClosed.compareAndSet(false, true)) { + failPending() + closedDeferred.complete(Unit) + onDisconnected("Gateway error: ${t.message ?: t::class.java.simpleName}") + } + } + + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { + if (!connectDeferred.isCompleted) { + connectDeferred.completeExceptionally(IllegalStateException("Gateway closed: $reason")) + } + if (isClosed.compareAndSet(false, true)) { + failPending() + closedDeferred.complete(Unit) + onDisconnected("Gateway closed: $reason") + } + } + } + + private suspend fun sendConnect(connectNonce: String?) { + val identity = identityStore.loadOrCreate() + val storedToken = deviceAuthStore.loadToken(identity.deviceId, options.role) + val trimmedToken = token?.trim().orEmpty() + val authToken = if (storedToken.isNullOrBlank()) trimmedToken else storedToken + val canFallbackToShared = !storedToken.isNullOrBlank() && trimmedToken.isNotBlank() + val payload = buildConnectParams(identity, connectNonce, authToken, password?.trim()) + val res = request("connect", payload, timeoutMs = 8_000) + if (!res.ok) { + val msg = res.error?.message ?: "connect failed" + if (canFallbackToShared) { + deviceAuthStore.clearToken(identity.deviceId, options.role) + } + throw IllegalStateException(msg) + } + val payloadJson = res.payloadJson ?: throw IllegalStateException("connect failed: missing payload") + val obj = json.parseToJsonElement(payloadJson).asObjectOrNull() ?: throw IllegalStateException("connect failed") + val serverName = obj["server"].asObjectOrNull()?.get("host").asStringOrNull() + val authObj = obj["auth"].asObjectOrNull() + val deviceToken = authObj?.get("deviceToken").asStringOrNull() + val authRole = authObj?.get("role").asStringOrNull() ?: options.role + if (!deviceToken.isNullOrBlank()) { + deviceAuthStore.saveToken(identity.deviceId, authRole, deviceToken) + } + val rawCanvas = obj["canvasHostUrl"].asStringOrNull() + canvasHostUrl = normalizeCanvasHostUrl(rawCanvas, endpoint) + val sessionDefaults = + obj["snapshot"].asObjectOrNull() + ?.get("sessionDefaults").asObjectOrNull() + mainSessionKey = sessionDefaults?.get("mainSessionKey").asStringOrNull() + onConnected(serverName, remoteAddress, mainSessionKey) + connectDeferred.complete(Unit) + } + + private fun buildConnectParams( + identity: DeviceIdentity, + connectNonce: String?, + authToken: String, + authPassword: String?, + ): JsonObject { + val client = options.client + val locale = Locale.getDefault().toLanguageTag() + val clientObj = + buildJsonObject { + put("id", JsonPrimitive(client.id)) + client.displayName?.let { put("displayName", JsonPrimitive(it)) } + put("version", JsonPrimitive(client.version)) + put("platform", JsonPrimitive(client.platform)) + put("mode", JsonPrimitive(client.mode)) + client.instanceId?.let { put("instanceId", JsonPrimitive(it)) } + client.deviceFamily?.let { put("deviceFamily", JsonPrimitive(it)) } + client.modelIdentifier?.let { put("modelIdentifier", JsonPrimitive(it)) } + } + + val password = authPassword?.trim().orEmpty() + val authJson = + when { + authToken.isNotEmpty() -> + buildJsonObject { + put("token", JsonPrimitive(authToken)) + } + password.isNotEmpty() -> + buildJsonObject { + put("password", JsonPrimitive(password)) + } + else -> null + } + + val signedAtMs = System.currentTimeMillis() + val payload = + buildDeviceAuthPayload( + deviceId = identity.deviceId, + clientId = client.id, + clientMode = client.mode, + role = options.role, + scopes = options.scopes, + signedAtMs = signedAtMs, + token = if (authToken.isNotEmpty()) authToken else null, + nonce = connectNonce, + ) + val signature = identityStore.signPayload(payload, identity) + val publicKey = identityStore.publicKeyBase64Url(identity) + val deviceJson = + if (!signature.isNullOrBlank() && !publicKey.isNullOrBlank()) { + buildJsonObject { + put("id", JsonPrimitive(identity.deviceId)) + put("publicKey", JsonPrimitive(publicKey)) + put("signature", JsonPrimitive(signature)) + put("signedAt", JsonPrimitive(signedAtMs)) + if (!connectNonce.isNullOrBlank()) { + put("nonce", JsonPrimitive(connectNonce)) + } + } + } else { + null + } + + return buildJsonObject { + put("minProtocol", JsonPrimitive(GATEWAY_PROTOCOL_VERSION)) + put("maxProtocol", JsonPrimitive(GATEWAY_PROTOCOL_VERSION)) + put("client", clientObj) + if (options.caps.isNotEmpty()) put("caps", JsonArray(options.caps.map(::JsonPrimitive))) + if (options.commands.isNotEmpty()) put("commands", JsonArray(options.commands.map(::JsonPrimitive))) + if (options.permissions.isNotEmpty()) { + put( + "permissions", + buildJsonObject { + options.permissions.forEach { (key, value) -> + put(key, JsonPrimitive(value)) + } + }, + ) + } + put("role", JsonPrimitive(options.role)) + if (options.scopes.isNotEmpty()) put("scopes", JsonArray(options.scopes.map(::JsonPrimitive))) + authJson?.let { put("auth", it) } + deviceJson?.let { put("device", it) } + put("locale", JsonPrimitive(locale)) + options.userAgent?.trim()?.takeIf { it.isNotEmpty() }?.let { + put("userAgent", JsonPrimitive(it)) + } + } + } + + private suspend fun handleMessage(text: String) { + val frame = json.parseToJsonElement(text).asObjectOrNull() ?: return + when (frame["type"].asStringOrNull()) { + "res" -> handleResponse(frame) + "event" -> handleEvent(frame) + } + } + + private fun handleResponse(frame: JsonObject) { + val id = frame["id"].asStringOrNull() ?: return + val ok = frame["ok"].asBooleanOrNull() ?: false + val payloadJson = frame["payload"]?.let { payload -> payload.toString() } + val error = + frame["error"]?.asObjectOrNull()?.let { obj -> + val code = obj["code"].asStringOrNull() ?: "UNAVAILABLE" + val msg = obj["message"].asStringOrNull() ?: "request failed" + ErrorShape(code, msg) + } + pending.remove(id)?.complete(RpcResponse(id, ok, payloadJson, error)) + } + + private fun handleEvent(frame: JsonObject) { + val event = frame["event"].asStringOrNull() ?: return + val payloadJson = + frame["payload"]?.let { it.toString() } ?: frame["payloadJSON"].asStringOrNull() + if (event == "connect.challenge") { + val nonce = extractConnectNonce(payloadJson) + if (!connectNonceDeferred.isCompleted) { + connectNonceDeferred.complete(nonce) + } + return + } + if (event == "node.invoke.request" && payloadJson != null && onInvoke != null) { + handleInvokeEvent(payloadJson) + return + } + onEvent(event, payloadJson) + } + + private suspend fun awaitConnectNonce(): String? { + if (isLoopbackHost(endpoint.host)) return null + return try { + withTimeout(2_000) { connectNonceDeferred.await() } + } catch (_: Throwable) { + null + } + } + + private fun extractConnectNonce(payloadJson: String?): String? { + if (payloadJson.isNullOrBlank()) return null + val obj = parseJsonOrNull(payloadJson)?.asObjectOrNull() ?: return null + return obj["nonce"].asStringOrNull() + } + + private fun handleInvokeEvent(payloadJson: String) { + val payload = + try { + json.parseToJsonElement(payloadJson).asObjectOrNull() + } catch (_: Throwable) { + null + } ?: return + val id = payload["id"].asStringOrNull() ?: return + val nodeId = payload["nodeId"].asStringOrNull() ?: return + val command = payload["command"].asStringOrNull() ?: return + val params = + payload["paramsJSON"].asStringOrNull() + ?: payload["params"]?.let { value -> if (value is JsonNull) null else value.toString() } + val timeoutMs = payload["timeoutMs"].asLongOrNull() + scope.launch { + val result = + try { + onInvoke?.invoke(InvokeRequest(id, nodeId, command, params, timeoutMs)) + ?: InvokeResult.error("UNAVAILABLE", "invoke handler missing") + } catch (err: Throwable) { + invokeErrorFromThrowable(err) + } + sendInvokeResult(id, nodeId, result) + } + } + + private suspend fun sendInvokeResult(id: String, nodeId: String, result: InvokeResult) { + val parsedPayload = result.payloadJson?.let { parseJsonOrNull(it) } + val params = + buildJsonObject { + put("id", JsonPrimitive(id)) + put("nodeId", JsonPrimitive(nodeId)) + put("ok", JsonPrimitive(result.ok)) + if (parsedPayload != null) { + put("payload", parsedPayload) + } else if (result.payloadJson != null) { + put("payloadJSON", JsonPrimitive(result.payloadJson)) + } + result.error?.let { err -> + put( + "error", + buildJsonObject { + put("code", JsonPrimitive(err.code)) + put("message", JsonPrimitive(err.message)) + }, + ) + } + } + try { + request("node.invoke.result", params, timeoutMs = 15_000) + } catch (err: Throwable) { + Log.w(loggerTag, "node.invoke.result failed: ${err.message ?: err::class.java.simpleName}") + } + } + + private fun invokeErrorFromThrowable(err: Throwable): InvokeResult { + val msg = err.message?.trim().takeIf { !it.isNullOrEmpty() } ?: err::class.java.simpleName + val parts = msg.split(":", limit = 2) + if (parts.size == 2) { + val code = parts[0].trim() + val rest = parts[1].trim() + if (code.isNotEmpty() && code.all { it.isUpperCase() || it == '_' }) { + return InvokeResult.error(code = code, message = rest.ifEmpty { msg }) + } + } + return InvokeResult.error(code = "UNAVAILABLE", message = msg) + } + + private fun failPending() { + for ((_, waiter) in pending) { + waiter.cancel() + } + pending.clear() + } + } + + private suspend fun runLoop() { + var attempt = 0 + while (scope.isActive) { + val target = desired + if (target == null) { + currentConnection?.closeQuietly() + currentConnection = null + delay(250) + continue + } + + try { + onDisconnected(if (attempt == 0) "Connecting…" else "Reconnecting…") + connectOnce(target) + attempt = 0 + } catch (err: Throwable) { + attempt += 1 + onDisconnected("Gateway error: ${err.message ?: err::class.java.simpleName}") + val sleepMs = minOf(8_000L, (350.0 * Math.pow(1.7, attempt.toDouble())).toLong()) + delay(sleepMs) + } + } + } + + private suspend fun connectOnce(target: DesiredConnection) = withContext(Dispatchers.IO) { + val conn = Connection(target.endpoint, target.token, target.password, target.options, target.tls) + currentConnection = conn + try { + conn.connect() + conn.awaitClose() + } finally { + currentConnection = null + canvasHostUrl = null + mainSessionKey = null + } + } + + private fun buildDeviceAuthPayload( + deviceId: String, + clientId: String, + clientMode: String, + role: String, + scopes: List, + signedAtMs: Long, + token: String?, + nonce: String?, + ): String { + val scopeString = scopes.joinToString(",") + val authToken = token.orEmpty() + val version = if (nonce.isNullOrBlank()) "v1" else "v2" + val parts = + mutableListOf( + version, + deviceId, + clientId, + clientMode, + role, + scopeString, + signedAtMs.toString(), + authToken, + ) + if (!nonce.isNullOrBlank()) { + parts.add(nonce) + } + return parts.joinToString("|") + } + + private fun normalizeCanvasHostUrl(raw: String?, endpoint: GatewayEndpoint): String? { + val trimmed = raw?.trim().orEmpty() + val parsed = trimmed.takeIf { it.isNotBlank() }?.let { runCatching { java.net.URI(it) }.getOrNull() } + val host = parsed?.host?.trim().orEmpty() + val port = parsed?.port ?: -1 + val scheme = parsed?.scheme?.trim().orEmpty().ifBlank { "http" } + + if (trimmed.isNotBlank() && !isLoopbackHost(host)) { + return trimmed + } + + val fallbackHost = + endpoint.tailnetDns?.trim().takeIf { !it.isNullOrEmpty() } + ?: endpoint.lanHost?.trim().takeIf { !it.isNullOrEmpty() } + ?: endpoint.host.trim() + if (fallbackHost.isEmpty()) return trimmed.ifBlank { null } + + val fallbackPort = endpoint.canvasPort ?: if (port > 0) port else 18793 + val formattedHost = if (fallbackHost.contains(":")) "[${fallbackHost}]" else fallbackHost + return "$scheme://$formattedHost:$fallbackPort" + } + + private fun isLoopbackHost(raw: String?): Boolean { + val host = raw?.trim()?.lowercase().orEmpty() + if (host.isEmpty()) return false + if (host == "localhost") return true + if (host == "::1") return true + if (host == "0.0.0.0" || host == "::") return true + return host.startsWith("127.") + } +} + +private fun JsonElement?.asObjectOrNull(): JsonObject? = this as? JsonObject + +private fun JsonElement?.asStringOrNull(): String? = + when (this) { + is JsonNull -> null + is JsonPrimitive -> content + else -> null + } + +private fun JsonElement?.asBooleanOrNull(): Boolean? = + when (this) { + is JsonPrimitive -> { + val c = content.trim() + when { + c.equals("true", ignoreCase = true) -> true + c.equals("false", ignoreCase = true) -> false + else -> null + } + } + else -> null + } + +private fun JsonElement?.asLongOrNull(): Long? = + when (this) { + is JsonPrimitive -> content.toLongOrNull() + else -> null + } + +private fun parseJsonOrNull(payload: String): JsonElement? { + val trimmed = payload.trim() + if (trimmed.isEmpty()) return null + return try { + Json.parseToJsonElement(trimmed) + } catch (_: Throwable) { + null + } +} diff --git a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeTls.kt b/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayTls.kt similarity index 71% rename from apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeTls.kt rename to apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayTls.kt index 1a3afd148..bcca51583 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/bridge/BridgeTls.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/gateway/GatewayTls.kt @@ -1,25 +1,34 @@ -package com.clawdbot.android.bridge +package com.clawdbot.android.gateway import android.annotation.SuppressLint -import java.net.Socket import java.security.MessageDigest import java.security.SecureRandom import java.security.cert.CertificateException import java.security.cert.X509Certificate +import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLContext -import javax.net.ssl.SSLSocket +import javax.net.ssl.SSLSocketFactory import javax.net.ssl.TrustManagerFactory import javax.net.ssl.X509TrustManager -data class BridgeTlsParams( +data class GatewayTlsParams( val required: Boolean, val expectedFingerprint: String?, val allowTOFU: Boolean, val stableId: String, ) -fun createBridgeSocket(params: BridgeTlsParams?, onStore: ((String) -> Unit)? = null): Socket { - if (params == null) return Socket() +data class GatewayTlsConfig( + val sslSocketFactory: SSLSocketFactory, + val trustManager: X509TrustManager, + val hostnameVerifier: HostnameVerifier, +) + +fun buildGatewayTlsConfig( + params: GatewayTlsParams?, + onStore: ((String) -> Unit)? = null, +): GatewayTlsConfig? { + if (params == null) return null val expected = params.expectedFingerprint?.let(::normalizeFingerprint) val defaultTrust = defaultTrustManager() @SuppressLint("CustomX509TrustManager") @@ -34,7 +43,7 @@ fun createBridgeSocket(params: BridgeTlsParams?, onStore: ((String) -> Unit)? = val fingerprint = sha256Hex(chain[0].encoded) if (expected != null) { if (fingerprint != expected) { - throw CertificateException("bridge TLS fingerprint mismatch") + throw CertificateException("gateway TLS fingerprint mismatch") } return } @@ -50,13 +59,11 @@ fun createBridgeSocket(params: BridgeTlsParams?, onStore: ((String) -> Unit)? = val context = SSLContext.getInstance("TLS") context.init(null, arrayOf(trustManager), SecureRandom()) - return context.socketFactory.createSocket() -} - -fun startTlsHandshakeIfNeeded(socket: Socket) { - if (socket is SSLSocket) { - socket.startHandshake() - } + return GatewayTlsConfig( + sslSocketFactory = context.socketFactory, + trustManager = trustManager, + hostnameVerifier = HostnameVerifier { _, _ -> true }, + ) } private fun defaultTrustManager(): X509TrustManager { @@ -77,5 +84,7 @@ private fun sha256Hex(data: ByteArray): String { } private fun normalizeFingerprint(raw: String): String { - return raw.lowercase().filter { it in '0'..'9' || it in 'a'..'f' } + val stripped = raw.trim() + .replace(Regex("^sha-?256\\s*:?\\s*", RegexOption.IGNORE_CASE), "") + return stripped.lowercase().filter { it in '0'..'9' || it in 'a'..'f' } } diff --git a/apps/android/app/src/main/java/com/clawdbot/android/node/SmsManager.kt b/apps/android/app/src/main/java/com/clawdbot/android/node/SmsManager.kt index e449993d2..3e12a56df 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/node/SmsManager.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/node/SmsManager.kt @@ -135,7 +135,7 @@ class SmsManager(private val context: Context) { /** * Send an SMS message. - * + * * @param paramsJson JSON with "to" (phone number) and "message" (text) fields * @return SendResult indicating success or failure */ diff --git a/apps/android/app/src/main/java/com/clawdbot/android/ui/RootScreen.kt b/apps/android/app/src/main/java/com/clawdbot/android/ui/RootScreen.kt index 10b74926a..96d2543a7 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/ui/RootScreen.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/ui/RootScreen.kt @@ -118,7 +118,7 @@ fun RootScreen(viewModel: MainViewModel) { contentDescription = "Approval pending", ) } - // Avoid duplicating the primary bridge status ("Connecting…") in the activity slot. + // Avoid duplicating the primary gateway status ("Connecting…") in the activity slot. if (screenRecordActive) { return@remember StatusActivity( @@ -179,14 +179,14 @@ fun RootScreen(viewModel: MainViewModel) { null } - val bridgeState = + val gatewayState = remember(serverName, statusText) { when { - serverName != null -> BridgeState.Connected + serverName != null -> GatewayState.Connected statusText.contains("connecting", ignoreCase = true) || - statusText.contains("reconnecting", ignoreCase = true) -> BridgeState.Connecting - statusText.contains("error", ignoreCase = true) -> BridgeState.Error - else -> BridgeState.Disconnected + statusText.contains("reconnecting", ignoreCase = true) -> GatewayState.Connecting + statusText.contains("error", ignoreCase = true) -> GatewayState.Error + else -> GatewayState.Disconnected } } @@ -206,7 +206,7 @@ fun RootScreen(viewModel: MainViewModel) { // Keep the overlay buttons above the WebView canvas (AndroidView), otherwise they may not receive touches. Popup(alignment = Alignment.TopStart, properties = PopupProperties(focusable = false)) { StatusPill( - bridge = bridgeState, + gateway = gatewayState, voiceEnabled = voiceEnabled, activity = activity, onClick = { sheet = Sheet.Settings }, diff --git a/apps/android/app/src/main/java/com/clawdbot/android/ui/SettingsSheet.kt b/apps/android/app/src/main/java/com/clawdbot/android/ui/SettingsSheet.kt index a140f3344..e3a9b3ecb 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/ui/SettingsSheet.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/ui/SettingsSheet.kt @@ -28,6 +28,8 @@ import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore @@ -48,7 +50,11 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat @@ -57,6 +63,7 @@ import com.clawdbot.android.LocationMode import com.clawdbot.android.MainViewModel import com.clawdbot.android.NodeForegroundService import com.clawdbot.android.VoiceWakeMode +import com.clawdbot.android.WakeWords @Composable fun SettingsSheet(viewModel: MainViewModel) { @@ -74,16 +81,19 @@ fun SettingsSheet(viewModel: MainViewModel) { val manualEnabled by viewModel.manualEnabled.collectAsState() val manualHost by viewModel.manualHost.collectAsState() val manualPort by viewModel.manualPort.collectAsState() + val manualTls by viewModel.manualTls.collectAsState() val canvasDebugStatusEnabled by viewModel.canvasDebugStatusEnabled.collectAsState() val statusText by viewModel.statusText.collectAsState() val serverName by viewModel.serverName.collectAsState() val remoteAddress by viewModel.remoteAddress.collectAsState() - val bridges by viewModel.bridges.collectAsState() + val gateways by viewModel.gateways.collectAsState() val discoveryStatusText by viewModel.discoveryStatusText.collectAsState() val listState = rememberLazyListState() val (wakeWordsText, setWakeWordsText) = remember { mutableStateOf("") } val (advancedExpanded, setAdvancedExpanded) = remember { mutableStateOf(false) } + val focusManager = LocalFocusManager.current + var wakeWordsHadFocus by remember { mutableStateOf(false) } val deviceModel = remember { listOfNotNull(Build.MANUFACTURER, Build.MODEL) @@ -102,6 +112,12 @@ fun SettingsSheet(viewModel: MainViewModel) { } LaunchedEffect(wakeWords) { setWakeWordsText(wakeWords.joinToString(", ")) } + val commitWakeWords = { + val parsed = WakeWords.parseIfChanged(wakeWordsText, wakeWords) + if (parsed != null) { + viewModel.setWakeWords(parsed) + } + } val permissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { perms -> @@ -163,7 +179,7 @@ fun SettingsSheet(viewModel: MainViewModel) { val smsPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> smsPermissionGranted = granted - viewModel.refreshBridgeHello() + viewModel.refreshGatewayConnection() } fun setCameraEnabledChecked(checked: Boolean) { @@ -223,20 +239,20 @@ fun SettingsSheet(viewModel: MainViewModel) { } } - val visibleBridges = + val visibleGateways = if (isConnected && remoteAddress != null) { - bridges.filterNot { "${it.host}:${it.port}" == remoteAddress } + gateways.filterNot { "${it.host}:${it.port}" == remoteAddress } } else { - bridges + gateways } - val bridgeDiscoveryFooterText = - if (visibleBridges.isEmpty()) { + val gatewayDiscoveryFooterText = + if (visibleGateways.isEmpty()) { discoveryStatusText } else if (isConnected) { - "Discovery active • ${visibleBridges.size} other bridge${if (visibleBridges.size == 1) "" else "s"} found" + "Discovery active • ${visibleGateways.size} other gateway${if (visibleGateways.size == 1) "" else "s"} found" } else { - "Discovery active • ${visibleBridges.size} bridge${if (visibleBridges.size == 1) "" else "s"} found" + "Discovery active • ${visibleGateways.size} gateway${if (visibleGateways.size == 1) "" else "s"} found" } LazyColumn( @@ -250,7 +266,7 @@ fun SettingsSheet(viewModel: MainViewModel) { contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { - // Order parity: Node → Bridge → Voice → Camera → Messaging → Location → Screen. + // Order parity: Node → Gateway → Voice → Camera → Messaging → Location → Screen. item { Text("Node", style = MaterialTheme.typography.titleSmall) } item { OutlinedTextField( @@ -266,8 +282,8 @@ fun SettingsSheet(viewModel: MainViewModel) { item { HorizontalDivider() } - // Bridge - item { Text("Bridge", style = MaterialTheme.typography.titleSmall) } + // Gateway + item { Text("Gateway", style = MaterialTheme.typography.titleSmall) } item { ListItem(headlineContent = { Text("Status") }, supportingContent = { Text(statusText) }) } if (serverName != null) { item { ListItem(headlineContent = { Text("Server") }, supportingContent = { Text(serverName!!) }) } @@ -291,31 +307,30 @@ fun SettingsSheet(viewModel: MainViewModel) { item { HorizontalDivider() } - if (!isConnected || visibleBridges.isNotEmpty()) { + if (!isConnected || visibleGateways.isNotEmpty()) { item { Text( - if (isConnected) "Other Bridges" else "Discovered Bridges", + if (isConnected) "Other Gateways" else "Discovered Gateways", style = MaterialTheme.typography.titleSmall, ) } - if (!isConnected && visibleBridges.isEmpty()) { - item { Text("No bridges found yet.", color = MaterialTheme.colorScheme.onSurfaceVariant) } + if (!isConnected && visibleGateways.isEmpty()) { + item { Text("No gateways found yet.", color = MaterialTheme.colorScheme.onSurfaceVariant) } } else { - items(items = visibleBridges, key = { it.stableId }) { bridge -> + items(items = visibleGateways, key = { it.stableId }) { gateway -> val detailLines = buildList { - add("IP: ${bridge.host}:${bridge.port}") - bridge.lanHost?.let { add("LAN: $it") } - bridge.tailnetDns?.let { add("Tailnet: $it") } - if (bridge.gatewayPort != null || bridge.bridgePort != null || bridge.canvasPort != null) { - val gw = bridge.gatewayPort?.toString() ?: "—" - val br = (bridge.bridgePort ?: bridge.port).toString() - val canvas = bridge.canvasPort?.toString() ?: "—" - add("Ports: gw $gw · bridge $br · canvas $canvas") + add("IP: ${gateway.host}:${gateway.port}") + gateway.lanHost?.let { add("LAN: $it") } + gateway.tailnetDns?.let { add("Tailnet: $it") } + if (gateway.gatewayPort != null || gateway.canvasPort != null) { + val gw = (gateway.gatewayPort ?: gateway.port).toString() + val canvas = gateway.canvasPort?.toString() ?: "—" + add("Ports: gw $gw · canvas $canvas") } } ListItem( - headlineContent = { Text(bridge.name) }, + headlineContent = { Text(gateway.name) }, supportingContent = { Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { detailLines.forEach { line -> @@ -327,7 +342,7 @@ fun SettingsSheet(viewModel: MainViewModel) { Button( onClick = { NodeForegroundService.start(context) - viewModel.connect(bridge) + viewModel.connect(gateway) }, ) { Text("Connect") @@ -338,7 +353,7 @@ fun SettingsSheet(viewModel: MainViewModel) { } item { Text( - bridgeDiscoveryFooterText, + gatewayDiscoveryFooterText, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.labelMedium, @@ -352,7 +367,7 @@ fun SettingsSheet(viewModel: MainViewModel) { item { ListItem( headlineContent = { Text("Advanced") }, - supportingContent = { Text("Manual bridge connection") }, + supportingContent = { Text("Manual gateway connection") }, trailingContent = { Icon( imageVector = if (advancedExpanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, @@ -369,7 +384,7 @@ fun SettingsSheet(viewModel: MainViewModel) { AnimatedVisibility(visible = advancedExpanded) { Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) { ListItem( - headlineContent = { Text("Use Manual Bridge") }, + headlineContent = { Text("Use Manual Gateway") }, supportingContent = { Text("Use this when discovery is blocked.") }, trailingContent = { Switch(checked = manualEnabled, onCheckedChange = viewModel::setManualEnabled) }, ) @@ -388,6 +403,12 @@ fun SettingsSheet(viewModel: MainViewModel) { modifier = Modifier.fillMaxWidth(), enabled = manualEnabled, ) + ListItem( + headlineContent = { Text("Require TLS") }, + supportingContent = { Text("Pin the gateway certificate on first connect.") }, + trailingContent = { Switch(checked = manualTls, onCheckedChange = viewModel::setManualTls, enabled = manualEnabled) }, + modifier = Modifier.alpha(if (manualEnabled) 1f else 0.5f), + ) val hostOk = manualHost.trim().isNotEmpty() val portOk = manualPort in 1..65535 @@ -474,29 +495,31 @@ fun SettingsSheet(viewModel: MainViewModel) { value = wakeWordsText, onValueChange = setWakeWordsText, label = { Text("Wake Words (comma-separated)") }, - modifier = Modifier.fillMaxWidth(), + modifier = + Modifier.fillMaxWidth().onFocusChanged { focusState -> + if (focusState.isFocused) { + wakeWordsHadFocus = true + } else if (wakeWordsHadFocus) { + wakeWordsHadFocus = false + commitWakeWords() + } + }, singleLine = true, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), + keyboardActions = + KeyboardActions( + onDone = { + commitWakeWords() + focusManager.clearFocus() + }, + ), ) } - item { - Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Button( - onClick = { - val parsed = com.clawdbot.android.WakeWords.parseCommaSeparated(wakeWordsText) - viewModel.setWakeWords(parsed) - }, - enabled = isConnected, - ) { - Text("Save + Sync") - } - - Button(onClick = viewModel::resetWakeWordsDefaults) { Text("Reset defaults") } - } - } + item { Button(onClick = viewModel::resetWakeWordsDefaults) { Text("Reset defaults") } } item { Text( if (isConnected) { - "Any node can edit wake words. Changes sync via the gateway bridge." + "Any node can edit wake words. Changes sync via the gateway." } else { "Connect to a gateway to sync wake words globally." }, @@ -511,7 +534,7 @@ fun SettingsSheet(viewModel: MainViewModel) { item { ListItem( headlineContent = { Text("Allow Camera") }, - supportingContent = { Text("Allows the bridge to request photos or short video clips (foreground only).") }, + supportingContent = { Text("Allows the gateway to request photos or short video clips (foreground only).") }, trailingContent = { Switch(checked = cameraEnabled, onCheckedChange = ::setCameraEnabledChecked) }, ) } @@ -538,7 +561,7 @@ fun SettingsSheet(viewModel: MainViewModel) { supportingContent = { Text( if (smsPermissionAvailable) { - "Allow the bridge to send SMS from this device." + "Allow the gateway to send SMS from this device." } else { "SMS requires a device with telephony hardware." }, diff --git a/apps/android/app/src/main/java/com/clawdbot/android/ui/StatusPill.kt b/apps/android/app/src/main/java/com/clawdbot/android/ui/StatusPill.kt index 669d448ad..564d96b52 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/ui/StatusPill.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/ui/StatusPill.kt @@ -26,7 +26,7 @@ import androidx.compose.ui.unit.dp @Composable fun StatusPill( - bridge: BridgeState, + gateway: GatewayState, voiceEnabled: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, @@ -49,11 +49,11 @@ fun StatusPill( Surface( modifier = Modifier.size(9.dp), shape = CircleShape, - color = bridge.color, + color = gateway.color, ) {} Text( - text = bridge.title, + text = gateway.title, style = MaterialTheme.typography.labelLarge, ) } @@ -106,7 +106,7 @@ data class StatusActivity( val tint: Color? = null, ) -enum class BridgeState(val title: String, val color: Color) { +enum class GatewayState(val title: String, val color: Color) { Connected("Connected", Color(0xFF2ECC71)), Connecting("Connecting…", Color(0xFFF1C40F)), Error("Error", Color(0xFFE74C3C)), diff --git a/apps/android/app/src/main/java/com/clawdbot/android/voice/TalkModeManager.kt b/apps/android/app/src/main/java/com/clawdbot/android/voice/TalkModeManager.kt index 919a0ce3c..41f98140d 100644 --- a/apps/android/app/src/main/java/com/clawdbot/android/voice/TalkModeManager.kt +++ b/apps/android/app/src/main/java/com/clawdbot/android/voice/TalkModeManager.kt @@ -20,7 +20,7 @@ import android.speech.tts.TextToSpeech import android.speech.tts.UtteranceProgressListener import android.util.Log import androidx.core.content.ContextCompat -import com.clawdbot.android.bridge.BridgeSession +import com.clawdbot.android.gateway.GatewaySession import com.clawdbot.android.isCanonicalMainSessionKey import com.clawdbot.android.normalizeMainKey import java.net.HttpURLConnection @@ -46,6 +46,9 @@ import kotlin.math.max class TalkModeManager( private val context: Context, private val scope: CoroutineScope, + private val session: GatewaySession, + private val supportsChatSubscribe: Boolean, + private val isConnected: () -> Boolean, ) { companion object { private const val tag = "TalkMode" @@ -99,7 +102,6 @@ class TalkModeManager( private var modelOverrideActive = false private var mainSessionKey: String = "main" - private var session: BridgeSession? = null private var pendingRunId: String? = null private var pendingFinal: CompletableDeferred? = null private var chatSubscribedSessionKey: String? = null @@ -112,11 +114,6 @@ class TalkModeManager( private var systemTtsPending: CompletableDeferred? = null private var systemTtsPendingId: String? = null - fun attachSession(session: BridgeSession) { - this.session = session - chatSubscribedSessionKey = null - } - fun setMainSessionKey(sessionKey: String?) { val trimmed = sessionKey?.trim().orEmpty() if (trimmed.isEmpty()) return @@ -136,7 +133,7 @@ class TalkModeManager( } } - fun handleBridgeEvent(event: String, payloadJson: String?) { + fun handleGatewayEvent(event: String, payloadJson: String?) { if (event != "chat") return if (payloadJson.isNullOrBlank()) return val pending = pendingRunId ?: return @@ -306,25 +303,24 @@ class TalkModeManager( reloadConfig() val prompt = buildPrompt(transcript) - val bridge = session - if (bridge == null) { - _statusText.value = "Bridge not connected" - Log.w(tag, "finalize: bridge not connected") + if (!isConnected()) { + _statusText.value = "Gateway not connected" + Log.w(tag, "finalize: gateway not connected") start() return } try { val startedAt = System.currentTimeMillis().toDouble() / 1000.0 - subscribeChatIfNeeded(bridge = bridge, sessionKey = mainSessionKey) + subscribeChatIfNeeded(session = session, sessionKey = mainSessionKey) Log.d(tag, "chat.send start sessionKey=${mainSessionKey.ifBlank { "main" }} chars=${prompt.length}") - val runId = sendChat(prompt, bridge) + val runId = sendChat(prompt, session) Log.d(tag, "chat.send ok runId=$runId") val ok = waitForChatFinal(runId) if (!ok) { Log.w(tag, "chat final timeout runId=$runId; attempting history fallback") } - val assistant = waitForAssistantText(bridge, startedAt, if (ok) 12_000 else 25_000) + val assistant = waitForAssistantText(session, startedAt, if (ok) 12_000 else 25_000) if (assistant.isNullOrBlank()) { _statusText.value = "No reply" Log.w(tag, "assistant text timeout runId=$runId") @@ -343,12 +339,13 @@ class TalkModeManager( } } - private suspend fun subscribeChatIfNeeded(bridge: BridgeSession, sessionKey: String) { + private suspend fun subscribeChatIfNeeded(session: GatewaySession, sessionKey: String) { + if (!supportsChatSubscribe) return val key = sessionKey.trim() if (key.isEmpty()) return if (chatSubscribedSessionKey == key) return try { - bridge.sendEvent("chat.subscribe", """{"sessionKey":"$key"}""") + session.sendNodeEvent("chat.subscribe", """{"sessionKey":"$key"}""") chatSubscribedSessionKey = key Log.d(tag, "chat.subscribe ok sessionKey=$key") } catch (err: Throwable) { @@ -370,7 +367,7 @@ class TalkModeManager( return lines.joinToString("\n") } - private suspend fun sendChat(message: String, bridge: BridgeSession): String { + private suspend fun sendChat(message: String, session: GatewaySession): String { val runId = UUID.randomUUID().toString() val params = buildJsonObject { @@ -380,7 +377,7 @@ class TalkModeManager( put("timeoutMs", JsonPrimitive(30_000)) put("idempotencyKey", JsonPrimitive(runId)) } - val res = bridge.request("chat.send", params.toString()) + val res = session.request("chat.send", params.toString()) val parsed = parseRunId(res) ?: runId if (parsed != runId) { pendingRunId = parsed @@ -411,13 +408,13 @@ class TalkModeManager( } private suspend fun waitForAssistantText( - bridge: BridgeSession, + session: GatewaySession, sinceSeconds: Double, timeoutMs: Long, ): String? { val deadline = SystemClock.elapsedRealtime() + timeoutMs while (SystemClock.elapsedRealtime() < deadline) { - val text = fetchLatestAssistantText(bridge, sinceSeconds) + val text = fetchLatestAssistantText(session, sinceSeconds) if (!text.isNullOrBlank()) return text delay(300) } @@ -425,11 +422,11 @@ class TalkModeManager( } private suspend fun fetchLatestAssistantText( - bridge: BridgeSession, + session: GatewaySession, sinceSeconds: Double? = null, ): String? { val key = mainSessionKey.ifBlank { "main" } - val res = bridge.request("chat.history", "{\"sessionKey\":\"$key\"}") + val res = session.request("chat.history", "{\"sessionKey\":\"$key\"}") val root = json.parseToJsonElement(res).asObjectOrNull() ?: return null val messages = root["messages"] as? JsonArray ?: return null for (item in messages.reversed()) { @@ -813,12 +810,11 @@ class TalkModeManager( } private suspend fun reloadConfig() { - val bridge = session ?: return val envVoice = System.getenv("ELEVENLABS_VOICE_ID")?.trim() val sagVoice = System.getenv("SAG_VOICE_ID")?.trim() val envKey = System.getenv("ELEVENLABS_API_KEY")?.trim() try { - val res = bridge.request("config.get", "{}") + val res = session.request("config.get", "{}") val root = json.parseToJsonElement(res).asObjectOrNull() val config = root?.get("config").asObjectOrNull() val talk = config?.get("talk").asObjectOrNull() diff --git a/apps/android/app/src/main/res/values/colors.xml b/apps/android/app/src/main/res/values/colors.xml index 6e79939c6..dfadc94cf 100644 --- a/apps/android/app/src/main/res/values/colors.xml +++ b/apps/android/app/src/main/res/values/colors.xml @@ -1,4 +1,3 @@ #0A0A0A - diff --git a/apps/android/app/src/main/res/values/strings.xml b/apps/android/app/src/main/res/values/strings.xml index 5e4d8a77d..3665960c2 100644 --- a/apps/android/app/src/main/res/values/strings.xml +++ b/apps/android/app/src/main/res/values/strings.xml @@ -1,4 +1,3 @@ Clawdbot Node - diff --git a/apps/android/app/src/test/java/com/clawdbot/android/WakeWordsTest.kt b/apps/android/app/src/test/java/com/clawdbot/android/WakeWordsTest.kt index 1d61383e8..9363e810c 100644 --- a/apps/android/app/src/test/java/com/clawdbot/android/WakeWordsTest.kt +++ b/apps/android/app/src/test/java/com/clawdbot/android/WakeWordsTest.kt @@ -1,6 +1,7 @@ package com.clawdbot.android import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Test class WakeWordsTest { @@ -32,5 +33,18 @@ class WakeWordsTest { assertEquals("w1", sanitized.first()) assertEquals("w${WakeWords.maxWords}", sanitized.last()) } -} + @Test + fun parseIfChangedSkipsWhenUnchanged() { + val current = listOf("clawd", "claude") + val parsed = WakeWords.parseIfChanged(" clawd , claude ", current) + assertNull(parsed) + } + + @Test + fun parseIfChangedReturnsUpdatedList() { + val current = listOf("clawd") + val parsed = WakeWords.parseIfChanged(" clawd , jarvis ", current) + assertEquals(listOf("clawd", "jarvis"), parsed) + } +} diff --git a/apps/android/app/src/test/java/com/clawdbot/android/bridge/BridgeEndpointKotestTest.kt b/apps/android/app/src/test/java/com/clawdbot/android/bridge/BridgeEndpointKotestTest.kt deleted file mode 100644 index 524267650..000000000 --- a/apps/android/app/src/test/java/com/clawdbot/android/bridge/BridgeEndpointKotestTest.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.clawdbot.android.bridge - -import io.kotest.core.spec.style.StringSpec -import io.kotest.matchers.shouldBe - -class BridgeEndpointKotestTest : StringSpec({ - "manual endpoint builds stable id + name" { - val endpoint = BridgeEndpoint.manual("10.0.0.5", 18790) - endpoint.stableId shouldBe "manual|10.0.0.5|18790" - endpoint.name shouldBe "10.0.0.5:18790" - endpoint.host shouldBe "10.0.0.5" - endpoint.port shouldBe 18790 - } -}) diff --git a/apps/android/app/src/test/java/com/clawdbot/android/bridge/BridgePairingClientTest.kt b/apps/android/app/src/test/java/com/clawdbot/android/bridge/BridgePairingClientTest.kt deleted file mode 100644 index 7fa6fa6ac..000000000 --- a/apps/android/app/src/test/java/com/clawdbot/android/bridge/BridgePairingClientTest.kt +++ /dev/null @@ -1,108 +0,0 @@ -package com.clawdbot.android.bridge - -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.async -import kotlinx.coroutines.runBlocking -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Test -import java.io.BufferedReader -import java.io.BufferedWriter -import java.io.InputStreamReader -import java.io.OutputStreamWriter -import java.net.ServerSocket - -class BridgePairingClientTest { - @Test - fun helloOkReturnsExistingToken() = runBlocking { - val serverSocket = ServerSocket(0) - val port = serverSocket.localPort - - val server = - async(Dispatchers.IO) { - serverSocket.use { ss -> - val sock = ss.accept() - sock.use { s -> - val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8)) - val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8)) - - val hello = reader.readLine() - assertTrue(hello.contains("\"type\":\"hello\"")) - writer.write("""{"type":"hello-ok","serverName":"Test Bridge"}""") - writer.write("\n") - writer.flush() - } - } - } - - val client = BridgePairingClient() - val res = - client.pairAndHello( - endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port), - hello = - BridgePairingClient.Hello( - nodeId = "node-1", - displayName = "Android Node", - token = "token-123", - platform = "Android", - version = "test", - deviceFamily = "Android", - modelIdentifier = "SM-X000", - caps = null, - commands = null, - ), - ) - assertTrue(res.ok) - assertEquals("token-123", res.token) - server.await() - } - - @Test - fun notPairedTriggersPairRequestAndReturnsToken() = runBlocking { - val serverSocket = ServerSocket(0) - val port = serverSocket.localPort - - val server = - async(Dispatchers.IO) { - serverSocket.use { ss -> - val sock = ss.accept() - sock.use { s -> - val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8)) - val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8)) - - reader.readLine() // hello - writer.write("""{"type":"error","code":"NOT_PAIRED","message":"not paired"}""") - writer.write("\n") - writer.flush() - - val pairReq = reader.readLine() - assertTrue(pairReq.contains("\"type\":\"pair-request\"")) - writer.write("""{"type":"pair-ok","token":"new-token"}""") - writer.write("\n") - writer.flush() - } - } - } - - val client = BridgePairingClient() - val res = - client.pairAndHello( - endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port), - hello = - BridgePairingClient.Hello( - nodeId = "node-1", - displayName = "Android Node", - token = null, - platform = "Android", - version = "test", - deviceFamily = "Android", - modelIdentifier = "SM-X000", - caps = null, - commands = null, - ), - ) - assertTrue(res.ok) - assertEquals("new-token", res.token) - server.await() - } -} diff --git a/apps/android/app/src/test/java/com/clawdbot/android/bridge/BridgeSessionTest.kt b/apps/android/app/src/test/java/com/clawdbot/android/bridge/BridgeSessionTest.kt deleted file mode 100644 index 4310228e2..000000000 --- a/apps/android/app/src/test/java/com/clawdbot/android/bridge/BridgeSessionTest.kt +++ /dev/null @@ -1,307 +0,0 @@ -package com.clawdbot.android.bridge - -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.async -import kotlinx.coroutines.cancel -import kotlinx.coroutines.runBlocking -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Test -import java.io.BufferedReader -import java.io.BufferedWriter -import java.io.InputStreamReader -import java.io.OutputStreamWriter -import java.net.ServerSocket -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit - -class BridgeSessionTest { - @Test - fun requestReturnsPayloadJson() = runBlocking { - val serverSocket = ServerSocket(0) - val port = serverSocket.localPort - - val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - val connected = CompletableDeferred() - - val session = - BridgeSession( - scope = scope, - onConnected = { _, _, _ -> connected.complete(Unit) }, - onDisconnected = { /* ignore */ }, - onEvent = { _, _ -> /* ignore */ }, - onInvoke = { BridgeSession.InvokeResult.ok(null) }, - ) - - val server = - async(Dispatchers.IO) { - serverSocket.use { ss -> - val sock = ss.accept() - sock.use { s -> - val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8)) - val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8)) - - val hello = reader.readLine() - assertTrue(hello.contains("\"type\":\"hello\"")) - writer.write("""{"type":"hello-ok","serverName":"Test Bridge","canvasHostUrl":"http://127.0.0.1:18789"}""") - writer.write("\n") - writer.flush() - - val req = reader.readLine() - assertTrue(req.contains("\"type\":\"req\"")) - val id = extractJsonString(req, "id") - writer.write("""{"type":"res","id":"$id","ok":true,"payloadJSON":"{\"value\":123}"}""") - writer.write("\n") - writer.flush() - } - } - } - - session.connect( - endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port), - hello = - BridgeSession.Hello( - nodeId = "node-1", - displayName = "Android Node", - token = null, - platform = "Android", - version = "test", - deviceFamily = null, - modelIdentifier = null, - caps = null, - commands = null, - ), - ) - - connected.await() - assertEquals("http://127.0.0.1:18789", session.currentCanvasHostUrl()) - val payload = session.request(method = "health", paramsJson = null) - assertEquals("""{"value":123}""", payload) - server.await() - - session.disconnect() - scope.cancel() - } - - @Test - fun requestThrowsOnErrorResponse() = runBlocking { - val serverSocket = ServerSocket(0) - val port = serverSocket.localPort - - val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - val connected = CompletableDeferred() - - val session = - BridgeSession( - scope = scope, - onConnected = { _, _, _ -> connected.complete(Unit) }, - onDisconnected = { /* ignore */ }, - onEvent = { _, _ -> /* ignore */ }, - onInvoke = { BridgeSession.InvokeResult.ok(null) }, - ) - - val server = - async(Dispatchers.IO) { - serverSocket.use { ss -> - val sock = ss.accept() - sock.use { s -> - val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8)) - val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8)) - - reader.readLine() // hello - writer.write("""{"type":"hello-ok","serverName":"Test Bridge"}""") - writer.write("\n") - writer.flush() - - val req = reader.readLine() - val id = extractJsonString(req, "id") - writer.write( - """{"type":"res","id":"$id","ok":false,"error":{"code":"FORBIDDEN","message":"nope"}}""", - ) - writer.write("\n") - writer.flush() - } - } - } - - session.connect( - endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port), - hello = - BridgeSession.Hello( - nodeId = "node-1", - displayName = "Android Node", - token = null, - platform = "Android", - version = "test", - deviceFamily = null, - modelIdentifier = null, - caps = null, - commands = null, - ), - ) - connected.await() - - try { - session.request(method = "chat.history", paramsJson = """{"sessionKey":"main"}""") - throw AssertionError("expected request() to throw") - } catch (e: IllegalStateException) { - assertTrue(e.message?.contains("FORBIDDEN: nope") == true) - } - server.await() - - session.disconnect() - scope.cancel() - } - - @Test - fun invokeResReturnsErrorWhenHandlerThrows() = runBlocking { - val serverSocket = ServerSocket(0) - val port = serverSocket.localPort - - val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - val connected = CompletableDeferred() - - val session = - BridgeSession( - scope = scope, - onConnected = { _, _, _ -> connected.complete(Unit) }, - onDisconnected = { /* ignore */ }, - onEvent = { _, _ -> /* ignore */ }, - onInvoke = { throw IllegalStateException("FOO_BAR: boom") }, - ) - - val invokeResLine = CompletableDeferred() - val server = - async(Dispatchers.IO) { - serverSocket.use { ss -> - val sock = ss.accept() - sock.use { s -> - val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8)) - val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8)) - - reader.readLine() // hello - writer.write("""{"type":"hello-ok","serverName":"Test Bridge"}""") - writer.write("\n") - writer.flush() - - // Ask the node to invoke something; handler will throw. - writer.write("""{"type":"invoke","id":"i1","command":"canvas.snapshot","paramsJSON":null}""") - writer.write("\n") - writer.flush() - - val res = reader.readLine() - invokeResLine.complete(res) - } - } - } - - session.connect( - endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port), - hello = - BridgeSession.Hello( - nodeId = "node-1", - displayName = "Android Node", - token = null, - platform = "Android", - version = "test", - deviceFamily = null, - modelIdentifier = null, - caps = null, - commands = null, - ), - ) - connected.await() - - // Give the reader loop time to process. - val line = invokeResLine.await() - assertTrue(line.contains("\"type\":\"invoke-res\"")) - assertTrue(line.contains("\"ok\":false")) - assertTrue(line.contains("\"code\":\"FOO_BAR\"")) - assertTrue(line.contains("\"message\":\"boom\"")) - server.await() - - session.disconnect() - scope.cancel() - } - - @Test(timeout = 12_000) - fun reconnectsAfterBridgeClosesDuringHello() = runBlocking { - val serverSocket = ServerSocket(0) - val port = serverSocket.localPort - - val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - val connected = CountDownLatch(1) - val connectionsSeen = CountDownLatch(2) - - val session = - BridgeSession( - scope = scope, - onConnected = { _, _, _ -> connected.countDown() }, - onDisconnected = { /* ignore */ }, - onEvent = { _, _ -> /* ignore */ }, - onInvoke = { BridgeSession.InvokeResult.ok(null) }, - ) - - val server = - async(Dispatchers.IO) { - serverSocket.use { ss -> - // First connection: read hello, then close (no response). - val sock1 = ss.accept() - sock1.use { s -> - val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8)) - reader.readLine() // hello - connectionsSeen.countDown() - } - - // Second connection: complete hello. - val sock2 = ss.accept() - sock2.use { s -> - val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8)) - val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8)) - reader.readLine() // hello - writer.write("""{"type":"hello-ok","serverName":"Test Bridge"}""") - writer.write("\n") - writer.flush() - connectionsSeen.countDown() - Thread.sleep(200) - } - } - } - - session.connect( - endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port), - hello = - BridgeSession.Hello( - nodeId = "node-1", - displayName = "Android Node", - token = null, - platform = "Android", - version = "test", - deviceFamily = null, - modelIdentifier = null, - caps = null, - commands = null, - ), - ) - - assertTrue("expected two connection attempts", connectionsSeen.await(8, TimeUnit.SECONDS)) - assertTrue("expected session to connect", connected.await(8, TimeUnit.SECONDS)) - - session.disconnect() - scope.cancel() - server.await() - } -} - -private fun extractJsonString(raw: String, key: String): String { - val needle = "\"$key\":\"" - val start = raw.indexOf(needle) - if (start < 0) throw IllegalArgumentException("missing key $key in $raw") - val from = start + needle.length - val end = raw.indexOf('"', from) - if (end < 0) throw IllegalArgumentException("unterminated string for $key in $raw") - return raw.substring(from, end) -} diff --git a/apps/android/app/src/test/java/com/clawdbot/android/bridge/BonjourEscapesTest.kt b/apps/android/app/src/test/java/com/clawdbot/android/gateway/BonjourEscapesTest.kt similarity index 93% rename from apps/android/app/src/test/java/com/clawdbot/android/bridge/BonjourEscapesTest.kt rename to apps/android/app/src/test/java/com/clawdbot/android/gateway/BonjourEscapesTest.kt index 5abf4519e..8952ed6cf 100644 --- a/apps/android/app/src/test/java/com/clawdbot/android/bridge/BonjourEscapesTest.kt +++ b/apps/android/app/src/test/java/com/clawdbot/android/gateway/BonjourEscapesTest.kt @@ -1,4 +1,4 @@ -package com.clawdbot.android.bridge +package com.clawdbot.android.gateway import org.junit.Assert.assertEquals import org.junit.Test diff --git a/apps/android/app/src/test/java/com/clawdbot/android/voice/VoiceWakeCommandExtractorTest.kt b/apps/android/app/src/test/java/com/clawdbot/android/voice/VoiceWakeCommandExtractorTest.kt index bdcee3284..f6e512fa3 100644 --- a/apps/android/app/src/test/java/com/clawdbot/android/voice/VoiceWakeCommandExtractorTest.kt +++ b/apps/android/app/src/test/java/com/clawdbot/android/voice/VoiceWakeCommandExtractorTest.kt @@ -23,4 +23,3 @@ class VoiceWakeCommandExtractorTest { assertNull(VoiceWakeCommandExtractor.extractCommand("hey claude!", listOf("claude"))) } } - diff --git a/apps/android/settings.gradle.kts b/apps/android/settings.gradle.kts index 05466f48f..d9d0158c9 100644 --- a/apps/android/settings.gradle.kts +++ b/apps/android/settings.gradle.kts @@ -16,4 +16,3 @@ dependencyResolutionManagement { rootProject.name = "ClawdbotNodeAndroid" include(":app") - diff --git a/apps/ios/.swiftlint.yml b/apps/ios/.swiftlint.yml index 7b64147b5..fc8509c83 100644 --- a/apps/ios/.swiftlint.yml +++ b/apps/ios/.swiftlint.yml @@ -3,4 +3,3 @@ parent_config: ../../.swiftlint.yml included: - Sources - ../shared/ClawdisNodeKit/Sources - diff --git a/apps/ios/Sources/Bridge/BridgeClient.swift b/apps/ios/Sources/Bridge/BridgeClient.swift deleted file mode 100644 index f880e6896..000000000 --- a/apps/ios/Sources/Bridge/BridgeClient.swift +++ /dev/null @@ -1,244 +0,0 @@ -import ClawdbotKit -import Foundation -import Network - -actor BridgeClient { - private let encoder = JSONEncoder() - private let decoder = JSONDecoder() - private var lineBuffer = Data() - - func pairAndHello( - endpoint: NWEndpoint, - hello: BridgeHello, - tls: BridgeTLSParams? = nil, - onStatus: (@Sendable (String) -> Void)? = nil) async throws -> String - { - do { - return try await self.pairAndHelloOnce( - endpoint: endpoint, - hello: hello, - tls: tls, - onStatus: onStatus) - } catch { - if let tls, !tls.required { - return try await self.pairAndHelloOnce( - endpoint: endpoint, - hello: hello, - tls: nil, - onStatus: onStatus) - } - throw error - } - } - - private func pairAndHelloOnce( - endpoint: NWEndpoint, - hello: BridgeHello, - tls: BridgeTLSParams?, - onStatus: (@Sendable (String) -> Void)? = nil) async throws -> String - { - self.lineBuffer = Data() - let params = self.makeParameters(tls: tls) - let connection = NWConnection(to: endpoint, using: params) - let queue = DispatchQueue(label: "com.clawdbot.ios.bridge-client") - defer { connection.cancel() } - try await self.withTimeout(seconds: 8, purpose: "connect") { - try await self.startAndWaitForReady(connection, queue: queue) - } - - onStatus?("Authenticating…") - try await self.send(hello, over: connection) - - let first = try await self.withTimeout(seconds: 10, purpose: "hello") { () -> ReceivedFrame in - guard let frame = try await self.receiveFrame(over: connection) else { - throw NSError(domain: "Bridge", code: 0, userInfo: [ - NSLocalizedDescriptionKey: "Bridge closed connection during hello", - ]) - } - return frame - } - - switch first.base.type { - case "hello-ok": - // We only return a token if we have one; callers should treat empty as "no token yet". - return hello.token ?? "" - - case "error": - let err = try self.decoder.decode(BridgeErrorFrame.self, from: first.data) - if err.code != "NOT_PAIRED", err.code != "UNAUTHORIZED" { - throw NSError(domain: "Bridge", code: 1, userInfo: [ - NSLocalizedDescriptionKey: "\(err.code): \(err.message)", - ]) - } - - onStatus?("Requesting approval…") - try await self.send( - BridgePairRequest( - nodeId: hello.nodeId, - displayName: hello.displayName, - platform: hello.platform, - version: hello.version, - deviceFamily: hello.deviceFamily, - modelIdentifier: hello.modelIdentifier, - caps: hello.caps, - commands: hello.commands), - over: connection) - - onStatus?("Waiting for approval…") - let ok = try await self.withTimeout(seconds: 60, purpose: "pairing approval") { - while let next = try await self.receiveFrame(over: connection) { - switch next.base.type { - case "pair-ok": - return try self.decoder.decode(BridgePairOk.self, from: next.data) - case "error": - let e = try self.decoder.decode(BridgeErrorFrame.self, from: next.data) - throw NSError(domain: "Bridge", code: 2, userInfo: [ - NSLocalizedDescriptionKey: "\(e.code): \(e.message)", - ]) - default: - continue - } - } - throw NSError(domain: "Bridge", code: 3, userInfo: [ - NSLocalizedDescriptionKey: "Pairing failed: bridge closed connection", - ]) - } - - return ok.token - - default: - throw NSError(domain: "Bridge", code: 0, userInfo: [ - NSLocalizedDescriptionKey: "Unexpected bridge response", - ]) - } - } - - private func send(_ obj: some Encodable, over connection: NWConnection) async throws { - let data = try self.encoder.encode(obj) - var line = Data() - line.append(data) - line.append(0x0A) - try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation) in - connection.send(content: line, completion: .contentProcessed { err in - if let err { cont.resume(throwing: err) } else { cont.resume(returning: ()) } - }) - } - } - - private struct ReceivedFrame { - var base: BridgeBaseFrame - var data: Data - } - - private func receiveFrame(over connection: NWConnection) async throws -> ReceivedFrame? { - guard let lineData = try await self.receiveLineData(over: connection) else { - return nil - } - let base = try self.decoder.decode(BridgeBaseFrame.self, from: lineData) - return ReceivedFrame(base: base, data: lineData) - } - - private func receiveChunk(over connection: NWConnection) async throws -> Data { - try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation) in - connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { data, _, isComplete, error in - if let error { - cont.resume(throwing: error) - return - } - if isComplete { - cont.resume(returning: Data()) - return - } - cont.resume(returning: data ?? Data()) - } - } - } - - private func receiveLineData(over connection: NWConnection) async throws -> Data? { - while true { - if let idx = self.lineBuffer.firstIndex(of: 0x0A) { - let line = self.lineBuffer.prefix(upTo: idx) - self.lineBuffer.removeSubrange(...idx) - return Data(line) - } - - let chunk = try await self.receiveChunk(over: connection) - if chunk.isEmpty { return nil } - self.lineBuffer.append(chunk) - } - } - - private func makeParameters(tls: BridgeTLSParams?) -> NWParameters { - if let tlsOptions = makeBridgeTLSOptions(tls) { - let tcpOptions = NWProtocolTCP.Options() - let params = NWParameters(tls: tlsOptions, tcp: tcpOptions) - params.includePeerToPeer = true - return params - } - let params = NWParameters.tcp - params.includePeerToPeer = true - return params - } - - private struct TimeoutError: LocalizedError, Sendable { - var purpose: String - var seconds: Int - - var errorDescription: String? { - if self.purpose == "pairing approval" { - return - "Timed out waiting for approval (\(self.seconds)s). " + - "Approve the node on your gateway and try again." - } - return "Timed out during \(self.purpose) (\(self.seconds)s)." - } - } - - private func withTimeout( - seconds: Int, - purpose: String, - _ op: @escaping @Sendable () async throws -> T) async throws -> T - { - try await AsyncTimeout.withTimeout( - seconds: Double(seconds), - onTimeout: { TimeoutError(purpose: purpose, seconds: seconds) }, - operation: op) - } - - private func startAndWaitForReady(_ connection: NWConnection, queue: DispatchQueue) async throws { - try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation) in - final class ResumeFlag: @unchecked Sendable { - private let lock = NSLock() - private var value = false - - func trySet() -> Bool { - self.lock.lock() - defer { self.lock.unlock() } - if self.value { return false } - self.value = true - return true - } - } - let didResume = ResumeFlag() - connection.stateUpdateHandler = { state in - switch state { - case .ready: - if didResume.trySet() { cont.resume(returning: ()) } - case let .failed(err): - if didResume.trySet() { cont.resume(throwing: err) } - case let .waiting(err): - if didResume.trySet() { cont.resume(throwing: err) } - case .cancelled: - if didResume.trySet() { - cont.resume(throwing: NSError(domain: "Bridge", code: 50, userInfo: [ - NSLocalizedDescriptionKey: "Connection cancelled", - ])) - } - default: - break - } - } - connection.start(queue: queue) - } - } -} diff --git a/apps/ios/Sources/Bridge/BridgeEndpointID.swift b/apps/ios/Sources/Bridge/BridgeEndpointID.swift deleted file mode 100644 index 40cb9fee1..000000000 --- a/apps/ios/Sources/Bridge/BridgeEndpointID.swift +++ /dev/null @@ -1,26 +0,0 @@ -import ClawdbotKit -import Foundation -import Network - -enum BridgeEndpointID { - static func stableID(_ endpoint: NWEndpoint) -> String { - switch endpoint { - case let .service(name, type, domain, _): - // Keep this stable across encode/decode differences (e.g. `\032` for spaces). - let normalizedName = Self.normalizeServiceNameForID(name) - return "\(type)|\(domain)|\(normalizedName)" - default: - return String(describing: endpoint) - } - } - - static func prettyDescription(_ endpoint: NWEndpoint) -> String { - BonjourEscapes.decode(String(describing: endpoint)) - } - - private static func normalizeServiceNameForID(_ rawName: String) -> String { - let decoded = BonjourEscapes.decode(rawName) - let normalized = decoded.split(whereSeparator: \.isWhitespace).joined(separator: " ") - return normalized.trimmingCharacters(in: .whitespacesAndNewlines) - } -} diff --git a/apps/ios/Sources/Bridge/BridgeSession.swift b/apps/ios/Sources/Bridge/BridgeSession.swift deleted file mode 100644 index adc3e0c00..000000000 --- a/apps/ios/Sources/Bridge/BridgeSession.swift +++ /dev/null @@ -1,422 +0,0 @@ -import ClawdbotKit -import Foundation -import Network - -actor BridgeSession { - private struct TimeoutError: LocalizedError { - var message: String - var errorDescription: String? { self.message } - } - - enum State: Sendable, Equatable { - case idle - case connecting - case connected(serverName: String) - case failed(message: String) - } - - private let encoder = JSONEncoder() - private let decoder = JSONDecoder() - - private var connection: NWConnection? - private var queue: DispatchQueue? - private var buffer = Data() - private var pendingRPC: [String: CheckedContinuation] = [:] - private var serverEventSubscribers: [UUID: AsyncStream.Continuation] = [:] - - private(set) var state: State = .idle - private var canvasHostUrl: String? - private var mainSessionKey: String? - - func currentCanvasHostUrl() -> String? { - self.canvasHostUrl - } - - func currentRemoteAddress() -> String? { - guard let endpoint = self.connection?.currentPath?.remoteEndpoint else { return nil } - return Self.prettyRemoteEndpoint(endpoint) - } - - private static func prettyRemoteEndpoint(_ endpoint: NWEndpoint) -> String? { - switch endpoint { - case let .hostPort(host, port): - let hostString = Self.prettyHostString(host) - if hostString.contains(":") { - return "[\(hostString)]:\(port)" - } - return "\(hostString):\(port)" - default: - return String(describing: endpoint) - } - } - - private static func prettyHostString(_ host: NWEndpoint.Host) -> String { - var hostString = String(describing: host) - hostString = hostString.replacingOccurrences(of: "::ffff:", with: "") - - guard let percentIndex = hostString.firstIndex(of: "%") else { return hostString } - - let prefix = hostString[.. Void)? = nil, - onInvoke: @escaping @Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse) - async throws - { - await self.disconnect() - self.state = .connecting - do { - try await self.connectOnce( - endpoint: endpoint, - hello: hello, - tls: tls, - onConnected: onConnected, - onInvoke: onInvoke) - } catch { - if let tls, !tls.required { - try await self.connectOnce( - endpoint: endpoint, - hello: hello, - tls: nil, - onConnected: onConnected, - onInvoke: onInvoke) - return - } - throw error - } - } - - private func connectOnce( - endpoint: NWEndpoint, - hello: BridgeHello, - tls: BridgeTLSParams?, - onConnected: (@Sendable (String, String?) async -> Void)?, - onInvoke: @escaping @Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse) async throws - { - let params = self.makeParameters(tls: tls) - let connection = NWConnection(to: endpoint, using: params) - let queue = DispatchQueue(label: "com.clawdbot.ios.bridge-session") - self.connection = connection - self.queue = queue - - let stateStream = Self.makeStateStream(for: connection) - connection.start(queue: queue) - - try await Self.waitForReady(stateStream, timeoutSeconds: 6) - - try await Self.withTimeout(seconds: 6) { - try await self.send(hello) - } - - guard let line = try await Self.withTimeout(seconds: 6, operation: { - try await self.receiveLine() - }), - let data = line.data(using: .utf8), - let base = try? self.decoder.decode(BridgeBaseFrame.self, from: data) - else { - await self.disconnect() - throw NSError(domain: "Bridge", code: 1, userInfo: [ - NSLocalizedDescriptionKey: "Unexpected bridge response", - ]) - } - - if base.type == "hello-ok" { - let ok = try self.decoder.decode(BridgeHelloOk.self, from: data) - self.state = .connected(serverName: ok.serverName) - self.canvasHostUrl = ok.canvasHostUrl?.trimmingCharacters(in: .whitespacesAndNewlines) - let mainKey = ok.mainSessionKey?.trimmingCharacters(in: .whitespacesAndNewlines) - self.mainSessionKey = (mainKey?.isEmpty == false) ? mainKey : nil - await onConnected?(ok.serverName, self.mainSessionKey) - } else if base.type == "error" { - let err = try self.decoder.decode(BridgeErrorFrame.self, from: data) - self.state = .failed(message: "\(err.code): \(err.message)") - await self.disconnect() - throw NSError(domain: "Bridge", code: 2, userInfo: [ - NSLocalizedDescriptionKey: "\(err.code): \(err.message)", - ]) - } else { - self.state = .failed(message: "Unexpected bridge response") - await self.disconnect() - throw NSError(domain: "Bridge", code: 3, userInfo: [ - NSLocalizedDescriptionKey: "Unexpected bridge response", - ]) - } - - while true { - guard let next = try await self.receiveLine() else { break } - guard let nextData = next.data(using: .utf8) else { continue } - guard let nextBase = try? self.decoder.decode(BridgeBaseFrame.self, from: nextData) else { continue } - - switch nextBase.type { - case "res": - let res = try self.decoder.decode(BridgeRPCResponse.self, from: nextData) - if let cont = self.pendingRPC.removeValue(forKey: res.id) { - cont.resume(returning: res) - } - - case "event": - let evt = try self.decoder.decode(BridgeEventFrame.self, from: nextData) - self.broadcastServerEvent(evt) - - case "ping": - let ping = try self.decoder.decode(BridgePing.self, from: nextData) - try await self.send(BridgePong(type: "pong", id: ping.id)) - - case "invoke": - let req = try self.decoder.decode(BridgeInvokeRequest.self, from: nextData) - let res = await onInvoke(req) - try await self.send(res) - - default: - continue - } - } - - await self.disconnect() - } - - func sendEvent(event: String, payloadJSON: String?) async throws { - try await self.send(BridgeEventFrame(type: "event", event: event, payloadJSON: payloadJSON)) - } - - func request(method: String, paramsJSON: String?, timeoutSeconds: Int = 15) async throws -> Data { - guard self.connection != nil else { - throw NSError(domain: "Bridge", code: 11, userInfo: [ - NSLocalizedDescriptionKey: "not connected", - ]) - } - - let id = UUID().uuidString - let req = BridgeRPCRequest(type: "req", id: id, method: method, paramsJSON: paramsJSON) - - let timeoutTask = Task { - try await Task.sleep(nanoseconds: UInt64(timeoutSeconds) * 1_000_000_000) - await self.timeoutRPC(id: id) - } - defer { timeoutTask.cancel() } - - let res: BridgeRPCResponse = try await withCheckedThrowingContinuation { cont in - Task { [weak self] in - guard let self else { return } - await self.beginRPC(id: id, request: req, continuation: cont) - } - } - - if res.ok { - let payload = res.payloadJSON ?? "" - guard let data = payload.data(using: .utf8) else { - throw NSError(domain: "Bridge", code: 12, userInfo: [ - NSLocalizedDescriptionKey: "Bridge response not UTF-8", - ]) - } - return data - } - - let code = res.error?.code ?? "UNAVAILABLE" - let message = res.error?.message ?? "request failed" - throw NSError(domain: "Bridge", code: 13, userInfo: [ - NSLocalizedDescriptionKey: "\(code): \(message)", - ]) - } - - func subscribeServerEvents(bufferingNewest: Int = 200) -> AsyncStream { - let id = UUID() - let session = self - return AsyncStream(bufferingPolicy: .bufferingNewest(bufferingNewest)) { continuation in - self.serverEventSubscribers[id] = continuation - continuation.onTermination = { @Sendable _ in - Task { await session.removeServerEventSubscriber(id) } - } - } - } - - func disconnect() async { - self.connection?.cancel() - self.connection = nil - self.queue = nil - self.buffer = Data() - self.canvasHostUrl = nil - self.mainSessionKey = nil - - let pending = self.pendingRPC.values - self.pendingRPC.removeAll() - for cont in pending { - cont.resume(throwing: NSError(domain: "Bridge", code: 14, userInfo: [ - NSLocalizedDescriptionKey: "UNAVAILABLE: connection closed", - ])) - } - - for (_, cont) in self.serverEventSubscribers { - cont.finish() - } - self.serverEventSubscribers.removeAll() - - self.state = .idle - } - - func currentMainSessionKey() -> String? { - self.mainSessionKey - } - - private func beginRPC( - id: String, - request: BridgeRPCRequest, - continuation: CheckedContinuation) async - { - self.pendingRPC[id] = continuation - do { - try await self.send(request) - } catch { - await self.failRPC(id: id, error: error) - } - } - - private func makeParameters(tls: BridgeTLSParams?) -> NWParameters { - if let tlsOptions = makeBridgeTLSOptions(tls) { - let tcpOptions = NWProtocolTCP.Options() - let params = NWParameters(tls: tlsOptions, tcp: tcpOptions) - params.includePeerToPeer = true - return params - } - let params = NWParameters.tcp - params.includePeerToPeer = true - return params - } - - private func timeoutRPC(id: String) async { - guard let cont = self.pendingRPC.removeValue(forKey: id) else { return } - cont.resume(throwing: NSError(domain: "Bridge", code: 15, userInfo: [ - NSLocalizedDescriptionKey: "UNAVAILABLE: request timeout", - ])) - } - - private func failRPC(id: String, error: Error) async { - guard let cont = self.pendingRPC.removeValue(forKey: id) else { return } - cont.resume(throwing: error) - } - - private func broadcastServerEvent(_ evt: BridgeEventFrame) { - for (_, cont) in self.serverEventSubscribers { - cont.yield(evt) - } - } - - private func removeServerEventSubscriber(_ id: UUID) { - self.serverEventSubscribers[id] = nil - } - - private func send(_ obj: some Encodable) async throws { - guard let connection = self.connection else { - throw NSError(domain: "Bridge", code: 10, userInfo: [ - NSLocalizedDescriptionKey: "not connected", - ]) - } - let data = try self.encoder.encode(obj) - var line = Data() - line.append(data) - line.append(0x0A) - try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation) in - connection.send(content: line, completion: .contentProcessed { err in - if let err { cont.resume(throwing: err) } else { cont.resume(returning: ()) } - }) - } - } - - private func receiveLine() async throws -> String? { - while true { - if let idx = self.buffer.firstIndex(of: 0x0A) { - let lineData = self.buffer.prefix(upTo: idx) - self.buffer.removeSubrange(...idx) - return String(data: lineData, encoding: .utf8) - } - - let chunk = try await self.receiveChunk() - if chunk.isEmpty { return nil } - self.buffer.append(chunk) - } - } - - private func receiveChunk() async throws -> Data { - guard let connection = self.connection else { return Data() } - return try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation) in - connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { data, _, isComplete, error in - if let error { - cont.resume(throwing: error) - return - } - if isComplete { - cont.resume(returning: Data()) - return - } - cont.resume(returning: data ?? Data()) - } - } - } - - private static func withTimeout( - seconds: Double, - operation: @escaping @Sendable () async throws -> T) async throws -> T - { - try await AsyncTimeout.withTimeout( - seconds: seconds, - onTimeout: { TimeoutError(message: "UNAVAILABLE: connection timeout") }, - operation: operation) - } - - private static func makeStateStream(for connection: NWConnection) -> AsyncStream { - AsyncStream { continuation in - continuation.onTermination = { @Sendable _ in - connection.stateUpdateHandler = nil - } - - connection.stateUpdateHandler = { state in - continuation.yield(state) - switch state { - case .ready, .cancelled, .failed, .waiting: - continuation.finish() - case .setup, .preparing: - break - @unknown default: - break - } - } - } - } - - private static func waitForReady( - _ stateStream: AsyncStream, - timeoutSeconds: Double) async throws - { - try await self.withTimeout(seconds: timeoutSeconds) { - for await state in stateStream { - switch state { - case .ready: - return - case let .failed(error): - throw error - case let .waiting(error): - throw error - case .cancelled: - throw TimeoutError(message: "UNAVAILABLE: connection cancelled") - case .setup, .preparing: - break - @unknown default: - break - } - } - - throw TimeoutError(message: "UNAVAILABLE: connection ended") - } - } -} diff --git a/apps/ios/Sources/Bridge/BridgeSettingsStore.swift b/apps/ios/Sources/Bridge/BridgeSettingsStore.swift deleted file mode 100644 index 7d0766235..000000000 --- a/apps/ios/Sources/Bridge/BridgeSettingsStore.swift +++ /dev/null @@ -1,112 +0,0 @@ -import Foundation - -enum BridgeSettingsStore { - private static let bridgeService = "com.clawdbot.bridge" - private static let nodeService = "com.clawdbot.node" - - private static let instanceIdDefaultsKey = "node.instanceId" - private static let preferredBridgeStableIDDefaultsKey = "bridge.preferredStableID" - private static let lastDiscoveredBridgeStableIDDefaultsKey = "bridge.lastDiscoveredStableID" - - private static let instanceIdAccount = "instanceId" - private static let preferredBridgeStableIDAccount = "preferredStableID" - private static let lastDiscoveredBridgeStableIDAccount = "lastDiscoveredStableID" - - static func bootstrapPersistence() { - self.ensureStableInstanceID() - self.ensurePreferredBridgeStableID() - self.ensureLastDiscoveredBridgeStableID() - } - - static func loadStableInstanceID() -> String? { - KeychainStore.loadString(service: self.nodeService, account: self.instanceIdAccount)? - .trimmingCharacters(in: .whitespacesAndNewlines) - } - - static func saveStableInstanceID(_ instanceId: String) { - _ = KeychainStore.saveString(instanceId, service: self.nodeService, account: self.instanceIdAccount) - } - - static func loadPreferredBridgeStableID() -> String? { - KeychainStore.loadString(service: self.bridgeService, account: self.preferredBridgeStableIDAccount)? - .trimmingCharacters(in: .whitespacesAndNewlines) - } - - static func savePreferredBridgeStableID(_ stableID: String) { - _ = KeychainStore.saveString( - stableID, - service: self.bridgeService, - account: self.preferredBridgeStableIDAccount) - } - - static func loadLastDiscoveredBridgeStableID() -> String? { - KeychainStore.loadString(service: self.bridgeService, account: self.lastDiscoveredBridgeStableIDAccount)? - .trimmingCharacters(in: .whitespacesAndNewlines) - } - - static func saveLastDiscoveredBridgeStableID(_ stableID: String) { - _ = KeychainStore.saveString( - stableID, - service: self.bridgeService, - account: self.lastDiscoveredBridgeStableIDAccount) - } - - private static func ensureStableInstanceID() { - let defaults = UserDefaults.standard - - if let existing = defaults.string(forKey: self.instanceIdDefaultsKey)? - .trimmingCharacters(in: .whitespacesAndNewlines), - !existing.isEmpty - { - if self.loadStableInstanceID() == nil { - self.saveStableInstanceID(existing) - } - return - } - - if let stored = self.loadStableInstanceID(), !stored.isEmpty { - defaults.set(stored, forKey: self.instanceIdDefaultsKey) - return - } - - let fresh = UUID().uuidString - self.saveStableInstanceID(fresh) - defaults.set(fresh, forKey: self.instanceIdDefaultsKey) - } - - private static func ensurePreferredBridgeStableID() { - let defaults = UserDefaults.standard - - if let existing = defaults.string(forKey: self.preferredBridgeStableIDDefaultsKey)? - .trimmingCharacters(in: .whitespacesAndNewlines), - !existing.isEmpty - { - if self.loadPreferredBridgeStableID() == nil { - self.savePreferredBridgeStableID(existing) - } - return - } - - if let stored = self.loadPreferredBridgeStableID(), !stored.isEmpty { - defaults.set(stored, forKey: self.preferredBridgeStableIDDefaultsKey) - } - } - - private static func ensureLastDiscoveredBridgeStableID() { - let defaults = UserDefaults.standard - - if let existing = defaults.string(forKey: self.lastDiscoveredBridgeStableIDDefaultsKey)? - .trimmingCharacters(in: .whitespacesAndNewlines), - !existing.isEmpty - { - if self.loadLastDiscoveredBridgeStableID() == nil { - self.saveLastDiscoveredBridgeStableID(existing) - } - return - } - - if let stored = self.loadLastDiscoveredBridgeStableID(), !stored.isEmpty { - defaults.set(stored, forKey: self.lastDiscoveredBridgeStableIDDefaultsKey) - } - } -} diff --git a/apps/ios/Sources/Bridge/BridgeTLS.swift b/apps/ios/Sources/Bridge/BridgeTLS.swift deleted file mode 100644 index 5ede00d3f..000000000 --- a/apps/ios/Sources/Bridge/BridgeTLS.swift +++ /dev/null @@ -1,66 +0,0 @@ -import CryptoKit -import Foundation -import Network -import Security - -struct BridgeTLSParams: Sendable { - let required: Bool - let expectedFingerprint: String? - let allowTOFU: Bool - let storeKey: String? -} - -enum BridgeTLSStore { - private static let service = "com.clawdbot.bridge.tls" - - static func loadFingerprint(stableID: String) -> String? { - KeychainStore.loadString(service: service, account: stableID)?.trimmingCharacters(in: .whitespacesAndNewlines) - } - - static func saveFingerprint(_ value: String, stableID: String) { - _ = KeychainStore.saveString(value, service: service, account: stableID) - } -} - -func makeBridgeTLSOptions(_ params: BridgeTLSParams?) -> NWProtocolTLS.Options? { - guard let params else { return nil } - let options = NWProtocolTLS.Options() - let expected = params.expectedFingerprint.map(normalizeBridgeFingerprint) - let allowTOFU = params.allowTOFU - let storeKey = params.storeKey - - sec_protocol_options_set_verify_block( - options.securityProtocolOptions, - { _, trust, complete in - let trustRef = sec_trust_copy_ref(trust).takeRetainedValue() - if let chain = SecTrustCopyCertificateChain(trustRef) as? [SecCertificate], - let cert = chain.first - { - let data = SecCertificateCopyData(cert) as Data - let fingerprint = sha256Hex(data) - if let expected { - complete(fingerprint == expected) - return - } - if allowTOFU { - if let storeKey { BridgeTLSStore.saveFingerprint(fingerprint, stableID: storeKey) } - complete(true) - return - } - } - let ok = SecTrustEvaluateWithError(trustRef, nil) - complete(ok) - }, - DispatchQueue(label: "com.clawdbot.bridge.tls.verify")) - - return options -} - -private func sha256Hex(_ data: Data) -> String { - let digest = SHA256.hash(data: data) - return digest.map { String(format: "%02x", $0) }.joined() -} - -private func normalizeBridgeFingerprint(_ raw: String) -> String { - raw.lowercased().filter { $0.isHexDigit } -} diff --git a/apps/ios/Sources/Camera/CameraController.swift b/apps/ios/Sources/Camera/CameraController.swift index e2ea47e05..b33f40a00 100644 --- a/apps/ios/Sources/Camera/CameraController.swift +++ b/apps/ios/Sources/Camera/CameraController.swift @@ -44,7 +44,7 @@ actor CameraController { { let facing = params.facing ?? .front let format = params.format ?? .jpg - // Default to a reasonable max width to keep bridge payload sizes manageable. + // Default to a reasonable max width to keep gateway payload sizes manageable. // If you need the full-res photo, explicitly request a larger maxWidth. let maxWidth = params.maxWidth.flatMap { $0 > 0 ? $0 : nil } ?? 1600 let quality = Self.clampQuality(params.quality) @@ -160,14 +160,14 @@ actor CameraController { defer { session.stopRunning() } await Self.warmUpCaptureSession() - let movURL = FileManager.default.temporaryDirectory + let movURL = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-camera-\(UUID().uuidString).mov") - let mp4URL = FileManager.default.temporaryDirectory + let mp4URL = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-camera-\(UUID().uuidString).mp4") defer { - try? FileManager.default.removeItem(at: movURL) - try? FileManager.default.removeItem(at: mp4URL) + try? FileManager().removeItem(at: movURL) + try? FileManager().removeItem(at: mp4URL) } var delegate: MovieFileDelegate? @@ -270,7 +270,7 @@ actor CameraController { nonisolated static func clampDurationMs(_ ms: Int?) -> Int { let v = ms ?? 3000 - // Keep clips short by default; avoid huge base64 payloads on the bridge. + // Keep clips short by default; avoid huge base64 payloads on the gateway. return min(60000, max(250, v)) } diff --git a/apps/ios/Sources/Chat/ChatSheet.swift b/apps/ios/Sources/Chat/ChatSheet.swift index 0db033238..c0e5593ff 100644 --- a/apps/ios/Sources/Chat/ChatSheet.swift +++ b/apps/ios/Sources/Chat/ChatSheet.swift @@ -1,4 +1,5 @@ import ClawdbotChatUI +import ClawdbotKit import SwiftUI struct ChatSheet: View { @@ -6,8 +7,8 @@ struct ChatSheet: View { @State private var viewModel: ClawdbotChatViewModel private let userAccent: Color? - init(bridge: BridgeSession, sessionKey: String, userAccent: Color? = nil) { - let transport = IOSBridgeChatTransport(bridge: bridge) + init(gateway: GatewayNodeSession, sessionKey: String, userAccent: Color? = nil) { + let transport = IOSGatewayChatTransport(gateway: gateway) self._viewModel = State( initialValue: ClawdbotChatViewModel( sessionKey: sessionKey, diff --git a/apps/ios/Sources/Chat/IOSBridgeChatTransport.swift b/apps/ios/Sources/Chat/IOSGatewayChatTransport.swift similarity index 66% rename from apps/ios/Sources/Chat/IOSBridgeChatTransport.swift rename to apps/ios/Sources/Chat/IOSGatewayChatTransport.swift index f6d3cc4a0..f7ee4aa79 100644 --- a/apps/ios/Sources/Chat/IOSBridgeChatTransport.swift +++ b/apps/ios/Sources/Chat/IOSGatewayChatTransport.swift @@ -1,12 +1,13 @@ import ClawdbotChatUI import ClawdbotKit +import ClawdbotProtocol import Foundation -struct IOSBridgeChatTransport: ClawdbotChatTransport, Sendable { - private let bridge: BridgeSession +struct IOSGatewayChatTransport: ClawdbotChatTransport, Sendable { + private let gateway: GatewayNodeSession - init(bridge: BridgeSession) { - self.bridge = bridge + init(gateway: GatewayNodeSession) { + self.gateway = gateway } func abortRun(sessionKey: String, runId: String) async throws { @@ -16,7 +17,7 @@ struct IOSBridgeChatTransport: ClawdbotChatTransport, Sendable { } let data = try JSONEncoder().encode(Params(sessionKey: sessionKey, runId: runId)) let json = String(data: data, encoding: .utf8) - _ = try await self.bridge.request(method: "chat.abort", paramsJSON: json, timeoutSeconds: 10) + _ = try await self.gateway.request(method: "chat.abort", paramsJSON: json, timeoutSeconds: 10) } func listSessions(limit: Int?) async throws -> ClawdbotChatSessionsListResponse { @@ -27,7 +28,7 @@ struct IOSBridgeChatTransport: ClawdbotChatTransport, Sendable { } let data = try JSONEncoder().encode(Params(includeGlobal: true, includeUnknown: false, limit: limit)) let json = String(data: data, encoding: .utf8) - let res = try await self.bridge.request(method: "sessions.list", paramsJSON: json, timeoutSeconds: 15) + let res = try await self.gateway.request(method: "sessions.list", paramsJSON: json, timeoutSeconds: 15) return try JSONDecoder().decode(ClawdbotChatSessionsListResponse.self, from: res) } @@ -35,14 +36,14 @@ struct IOSBridgeChatTransport: ClawdbotChatTransport, Sendable { struct Subscribe: Codable { var sessionKey: String } let data = try JSONEncoder().encode(Subscribe(sessionKey: sessionKey)) let json = String(data: data, encoding: .utf8) - try await self.bridge.sendEvent(event: "chat.subscribe", payloadJSON: json) + await self.gateway.sendEvent(event: "chat.subscribe", payloadJSON: json) } func requestHistory(sessionKey: String) async throws -> ClawdbotChatHistoryPayload { struct Params: Codable { var sessionKey: String } let data = try JSONEncoder().encode(Params(sessionKey: sessionKey)) let json = String(data: data, encoding: .utf8) - let res = try await self.bridge.request(method: "chat.history", paramsJSON: json, timeoutSeconds: 15) + let res = try await self.gateway.request(method: "chat.history", paramsJSON: json, timeoutSeconds: 15) return try JSONDecoder().decode(ClawdbotChatHistoryPayload.self, from: res) } @@ -71,20 +72,20 @@ struct IOSBridgeChatTransport: ClawdbotChatTransport, Sendable { idempotencyKey: idempotencyKey) let data = try JSONEncoder().encode(params) let json = String(data: data, encoding: .utf8) - let res = try await self.bridge.request(method: "chat.send", paramsJSON: json, timeoutSeconds: 35) + let res = try await self.gateway.request(method: "chat.send", paramsJSON: json, timeoutSeconds: 35) return try JSONDecoder().decode(ClawdbotChatSendResponse.self, from: res) } func requestHealth(timeoutMs: Int) async throws -> Bool { let seconds = max(1, Int(ceil(Double(timeoutMs) / 1000.0))) - let res = try await self.bridge.request(method: "health", paramsJSON: nil, timeoutSeconds: seconds) + let res = try await self.gateway.request(method: "health", paramsJSON: nil, timeoutSeconds: seconds) return (try? JSONDecoder().decode(ClawdbotGatewayHealthOK.self, from: res))?.ok ?? true } func events() -> AsyncStream { AsyncStream { continuation in let task = Task { - let stream = await self.bridge.subscribeServerEvents() + let stream = await self.gateway.subscribeServerEvents() for await evt in stream { if Task.isCancelled { return } switch evt.event { @@ -93,18 +94,26 @@ struct IOSBridgeChatTransport: ClawdbotChatTransport, Sendable { case "seqGap": continuation.yield(.seqGap) case "health": - guard let json = evt.payloadJSON, let data = json.data(using: .utf8) else { break } - let ok = (try? JSONDecoder().decode(ClawdbotGatewayHealthOK.self, from: data))?.ok ?? true + guard let payload = evt.payload else { break } + let ok = (try? GatewayPayloadDecoding.decode( + payload, + as: ClawdbotGatewayHealthOK.self))?.ok ?? true continuation.yield(.health(ok: ok)) case "chat": - guard let json = evt.payloadJSON, let data = json.data(using: .utf8) else { break } - if let payload = try? JSONDecoder().decode(ClawdbotChatEventPayload.self, from: data) { - continuation.yield(.chat(payload)) + guard let payload = evt.payload else { break } + if let chatPayload = try? GatewayPayloadDecoding.decode( + payload, + as: ClawdbotChatEventPayload.self) + { + continuation.yield(.chat(chatPayload)) } case "agent": - guard let json = evt.payloadJSON, let data = json.data(using: .utf8) else { break } - if let payload = try? JSONDecoder().decode(ClawdbotAgentEventPayload.self, from: data) { - continuation.yield(.agent(payload)) + guard let payload = evt.payload else { break } + if let agentPayload = try? GatewayPayloadDecoding.decode( + payload, + as: ClawdbotAgentEventPayload.self) + { + continuation.yield(.agent(agentPayload)) } default: break diff --git a/apps/ios/Sources/ClawdbotApp.swift b/apps/ios/Sources/ClawdbotApp.swift index c29572e30..3ed8933b6 100644 --- a/apps/ios/Sources/ClawdbotApp.swift +++ b/apps/ios/Sources/ClawdbotApp.swift @@ -3,14 +3,14 @@ import SwiftUI @main struct ClawdbotApp: App { @State private var appModel: NodeAppModel - @State private var bridgeController: BridgeConnectionController + @State private var gatewayController: GatewayConnectionController @Environment(\.scenePhase) private var scenePhase init() { - BridgeSettingsStore.bootstrapPersistence() + GatewaySettingsStore.bootstrapPersistence() let appModel = NodeAppModel() _appModel = State(initialValue: appModel) - _bridgeController = State(initialValue: BridgeConnectionController(appModel: appModel)) + _gatewayController = State(initialValue: GatewayConnectionController(appModel: appModel)) } var body: some Scene { @@ -18,13 +18,13 @@ struct ClawdbotApp: App { RootCanvas() .environment(self.appModel) .environment(self.appModel.voiceWake) - .environment(self.bridgeController) + .environment(self.gatewayController) .onOpenURL { url in Task { await self.appModel.handleDeepLink(url: url) } } .onChange(of: self.scenePhase) { _, newValue in self.appModel.setScenePhase(newValue) - self.bridgeController.setScenePhase(newValue) + self.gatewayController.setScenePhase(newValue) } } } diff --git a/apps/ios/Sources/Bridge/BridgeConnectionController.swift b/apps/ios/Sources/Gateway/GatewayConnectionController.swift similarity index 52% rename from apps/ios/Sources/Bridge/BridgeConnectionController.swift rename to apps/ios/Sources/Gateway/GatewayConnectionController.swift index 01a6c6c0a..0f1cd02cf 100644 --- a/apps/ios/Sources/Bridge/BridgeConnectionController.swift +++ b/apps/ios/Sources/Gateway/GatewayConnectionController.swift @@ -6,40 +6,23 @@ import Observation import SwiftUI import UIKit -protocol BridgePairingClient: Sendable { - func pairAndHello( - endpoint: NWEndpoint, - hello: BridgeHello, - tls: BridgeTLSParams?, - onStatus: (@Sendable (String) -> Void)?) async throws -> String -} - -extension BridgeClient: BridgePairingClient {} - @MainActor @Observable -final class BridgeConnectionController { - private(set) var bridges: [BridgeDiscoveryModel.DiscoveredBridge] = [] +final class GatewayConnectionController { + private(set) var gateways: [GatewayDiscoveryModel.DiscoveredGateway] = [] private(set) var discoveryStatusText: String = "Idle" - private(set) var discoveryDebugLog: [BridgeDiscoveryModel.DebugLogEntry] = [] + private(set) var discoveryDebugLog: [GatewayDiscoveryModel.DebugLogEntry] = [] - private let discovery = BridgeDiscoveryModel() + private let discovery = GatewayDiscoveryModel() private weak var appModel: NodeAppModel? private var didAutoConnect = false - private let bridgeClientFactory: @Sendable () -> any BridgePairingClient - - init( - appModel: NodeAppModel, - startDiscovery: Bool = true, - bridgeClientFactory: @escaping @Sendable () -> any BridgePairingClient = { BridgeClient() }) - { + init(appModel: NodeAppModel, startDiscovery: Bool = true) { self.appModel = appModel - self.bridgeClientFactory = bridgeClientFactory - BridgeSettingsStore.bootstrapPersistence() + GatewaySettingsStore.bootstrapPersistence() let defaults = UserDefaults.standard - self.discovery.setDebugLoggingEnabled(defaults.bool(forKey: "bridge.discovery.debugLogs")) + self.discovery.setDebugLoggingEnabled(defaults.bool(forKey: "gateway.discovery.debugLogs")) self.updateFromDiscovery() self.observeDiscovery() @@ -64,18 +47,61 @@ final class BridgeConnectionController { } } + func connect(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) async { + let instanceId = UserDefaults.standard.string(forKey: "node.instanceId")? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let token = GatewaySettingsStore.loadGatewayToken(instanceId: instanceId) + let password = GatewaySettingsStore.loadGatewayPassword(instanceId: instanceId) + guard let host = self.resolveGatewayHost(gateway) else { return } + let port = gateway.gatewayPort ?? 18789 + let tlsParams = self.resolveDiscoveredTLSParams(gateway: gateway) + guard let url = self.buildGatewayURL( + host: host, + port: port, + useTLS: tlsParams?.required == true) + else { return } + self.didAutoConnect = true + self.startAutoConnect( + url: url, + gatewayStableID: gateway.stableID, + tls: tlsParams, + token: token, + password: password) + } + + func connectManual(host: String, port: Int, useTLS: Bool) async { + let instanceId = UserDefaults.standard.string(forKey: "node.instanceId")? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let token = GatewaySettingsStore.loadGatewayToken(instanceId: instanceId) + let password = GatewaySettingsStore.loadGatewayPassword(instanceId: instanceId) + let stableID = self.manualStableID(host: host, port: port) + let tlsParams = self.resolveManualTLSParams(stableID: stableID, tlsEnabled: useTLS) + guard let url = self.buildGatewayURL( + host: host, + port: port, + useTLS: tlsParams?.required == true) + else { return } + self.didAutoConnect = true + self.startAutoConnect( + url: url, + gatewayStableID: stableID, + tls: tlsParams, + token: token, + password: password) + } + private func updateFromDiscovery() { - let newBridges = self.discovery.bridges - self.bridges = newBridges + let newGateways = self.discovery.gateways + self.gateways = newGateways self.discoveryStatusText = self.discovery.statusText self.discoveryDebugLog = self.discovery.debugLog - self.updateLastDiscoveredBridge(from: newBridges) + self.updateLastDiscoveredGateway(from: newGateways) self.maybeAutoConnect() } private func observeDiscovery() { withObservationTracking { - _ = self.discovery.bridges + _ = self.discovery.gateways _ = self.discovery.statusText _ = self.discovery.debugLog } onChange: { [weak self] in @@ -90,181 +116,176 @@ final class BridgeConnectionController { private func maybeAutoConnect() { guard !self.didAutoConnect else { return } guard let appModel = self.appModel else { return } - guard appModel.bridgeServerName == nil else { return } + guard appModel.gatewayServerName == nil else { return } let defaults = UserDefaults.standard - let manualEnabled = defaults.bool(forKey: "bridge.manual.enabled") + let manualEnabled = defaults.bool(forKey: "gateway.manual.enabled") let instanceId = defaults.string(forKey: "node.instanceId")? .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" guard !instanceId.isEmpty else { return } - let token = KeychainStore.loadString( - service: "com.clawdbot.bridge", - account: self.keychainAccount(instanceId: instanceId))? - .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - guard !token.isEmpty else { return } + let token = GatewaySettingsStore.loadGatewayToken(instanceId: instanceId) + let password = GatewaySettingsStore.loadGatewayPassword(instanceId: instanceId) if manualEnabled { - let manualHost = defaults.string(forKey: "bridge.manual.host")? + let manualHost = defaults.string(forKey: "gateway.manual.host")? .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" guard !manualHost.isEmpty else { return } - let manualPort = defaults.integer(forKey: "bridge.manual.port") - let resolvedPort = manualPort > 0 ? manualPort : 18790 - guard let port = NWEndpoint.Port(rawValue: UInt16(resolvedPort)) else { return } + let manualPort = defaults.integer(forKey: "gateway.manual.port") + let resolvedPort = manualPort > 0 ? manualPort : 18789 + let manualTLS = defaults.bool(forKey: "gateway.manual.tls") + + let stableID = self.manualStableID(host: manualHost, port: resolvedPort) + let tlsParams = self.resolveManualTLSParams(stableID: stableID, tlsEnabled: manualTLS) + + guard let url = self.buildGatewayURL( + host: manualHost, + port: resolvedPort, + useTLS: tlsParams?.required == true) + else { return } self.didAutoConnect = true - let endpoint = NWEndpoint.hostPort(host: NWEndpoint.Host(manualHost), port: port) - let stableID = BridgeEndpointID.stableID(endpoint) - let tlsParams = self.resolveManualTLSParams(stableID: stableID) self.startAutoConnect( - endpoint: endpoint, - bridgeStableID: stableID, + url: url, + gatewayStableID: stableID, tls: tlsParams, token: token, - instanceId: instanceId) + password: password) return } - let preferredStableID = defaults.string(forKey: "bridge.preferredStableID")? + let preferredStableID = defaults.string(forKey: "gateway.preferredStableID")? .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - let lastDiscoveredStableID = defaults.string(forKey: "bridge.lastDiscoveredStableID")? + let lastDiscoveredStableID = defaults.string(forKey: "gateway.lastDiscoveredStableID")? .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" let candidates = [preferredStableID, lastDiscoveredStableID].filter { !$0.isEmpty } guard let targetStableID = candidates.first(where: { id in - self.bridges.contains(where: { $0.stableID == id }) + self.gateways.contains(where: { $0.stableID == id }) }) else { return } - guard let target = self.bridges.first(where: { $0.stableID == targetStableID }) else { return } + guard let target = self.gateways.first(where: { $0.stableID == targetStableID }) else { return } + guard let host = self.resolveGatewayHost(target) else { return } + let port = target.gatewayPort ?? 18789 + let tlsParams = self.resolveDiscoveredTLSParams(gateway: target) + guard let url = self.buildGatewayURL(host: host, port: port, useTLS: tlsParams?.required == true) + else { return } - let tlsParams = self.resolveDiscoveredTLSParams(bridge: target) self.didAutoConnect = true self.startAutoConnect( - endpoint: target.endpoint, - bridgeStableID: target.stableID, + url: url, + gatewayStableID: target.stableID, tls: tlsParams, token: token, - instanceId: instanceId) + password: password) } - private func updateLastDiscoveredBridge(from bridges: [BridgeDiscoveryModel.DiscoveredBridge]) { + private func updateLastDiscoveredGateway(from gateways: [GatewayDiscoveryModel.DiscoveredGateway]) { let defaults = UserDefaults.standard - let preferred = defaults.string(forKey: "bridge.preferredStableID")? + let preferred = defaults.string(forKey: "gateway.preferredStableID")? .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - let existingLast = defaults.string(forKey: "bridge.lastDiscoveredStableID")? + let existingLast = defaults.string(forKey: "gateway.lastDiscoveredStableID")? .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" // Avoid overriding user intent (preferred/lastDiscovered are also set on manual Connect). guard preferred.isEmpty, existingLast.isEmpty else { return } - guard let first = bridges.first else { return } + guard let first = gateways.first else { return } - defaults.set(first.stableID, forKey: "bridge.lastDiscoveredStableID") - BridgeSettingsStore.saveLastDiscoveredBridgeStableID(first.stableID) - } - - private func makeHello(token: String) -> BridgeHello { - let defaults = UserDefaults.standard - let nodeId = defaults.string(forKey: "node.instanceId") ?? "ios-node" - let displayName = self.resolvedDisplayName(defaults: defaults) - - return BridgeHello( - nodeId: nodeId, - displayName: displayName, - token: token, - platform: self.platformString(), - version: self.appVersion(), - deviceFamily: self.deviceFamily(), - modelIdentifier: self.modelIdentifier(), - caps: self.currentCaps(), - commands: self.currentCommands()) - } - - private func keychainAccount(instanceId: String) -> String { - "bridge-token.\(instanceId)" + defaults.set(first.stableID, forKey: "gateway.lastDiscoveredStableID") + GatewaySettingsStore.saveLastDiscoveredGatewayStableID(first.stableID) } private func startAutoConnect( - endpoint: NWEndpoint, - bridgeStableID: String, - tls: BridgeTLSParams?, - token: String, - instanceId: String) + url: URL, + gatewayStableID: String, + tls: GatewayTLSParams?, + token: String?, + password: String?) { guard let appModel else { return } + let connectOptions = self.makeConnectOptions() + Task { [weak self] in guard let self else { return } - do { - let hello = self.makeHello(token: token) - let refreshed = try await self.bridgeClientFactory().pairAndHello( - endpoint: endpoint, - hello: hello, - tls: tls, - onStatus: { status in - Task { @MainActor in - appModel.bridgeStatusText = status - } - }) - let resolvedToken = refreshed.isEmpty ? token : refreshed - if !refreshed.isEmpty, refreshed != token { - _ = KeychainStore.saveString( - refreshed, - service: "com.clawdbot.bridge", - account: self.keychainAccount(instanceId: instanceId)) - } - appModel.connectToBridge( - endpoint: endpoint, - bridgeStableID: bridgeStableID, - tls: tls, - hello: self.makeHello(token: resolvedToken)) - } catch { - await MainActor.run { - appModel.bridgeStatusText = "Bridge error: \(error.localizedDescription)" - } + await MainActor.run { + appModel.gatewayStatusText = "Connecting…" } + appModel.connectToGateway( + url: url, + gatewayStableID: gatewayStableID, + tls: tls, + token: token, + password: password, + connectOptions: connectOptions) } } - private func resolveDiscoveredTLSParams( - bridge: BridgeDiscoveryModel.DiscoveredBridge) -> BridgeTLSParams? - { - let stableID = bridge.stableID - let stored = BridgeTLSStore.loadFingerprint(stableID: stableID) + private func resolveDiscoveredTLSParams(gateway: GatewayDiscoveryModel.DiscoveredGateway) -> GatewayTLSParams? { + let stableID = gateway.stableID + let stored = GatewayTLSStore.loadFingerprint(stableID: stableID) - if bridge.tlsEnabled || bridge.tlsFingerprintSha256 != nil { - return BridgeTLSParams( + if gateway.tlsEnabled || gateway.tlsFingerprintSha256 != nil || stored != nil { + return GatewayTLSParams( required: true, - expectedFingerprint: bridge.tlsFingerprintSha256 ?? stored, + expectedFingerprint: gateway.tlsFingerprintSha256 ?? stored, allowTOFU: stored == nil, storeKey: stableID) } - if let stored { - return BridgeTLSParams( - required: true, - expectedFingerprint: stored, - allowTOFU: false, - storeKey: stableID) - } - return nil } - private func resolveManualTLSParams(stableID: String) -> BridgeTLSParams? { - if let stored = BridgeTLSStore.loadFingerprint(stableID: stableID) { - return BridgeTLSParams( + private func resolveManualTLSParams(stableID: String, tlsEnabled: Bool) -> GatewayTLSParams? { + let stored = GatewayTLSStore.loadFingerprint(stableID: stableID) + if tlsEnabled || stored != nil { + return GatewayTLSParams( required: true, expectedFingerprint: stored, - allowTOFU: false, + allowTOFU: stored == nil, storeKey: stableID) } - return BridgeTLSParams( - required: false, - expectedFingerprint: nil, - allowTOFU: true, - storeKey: stableID) + return nil + } + + private func resolveGatewayHost(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) -> String? { + if let lanHost = gateway.lanHost?.trimmingCharacters(in: .whitespacesAndNewlines), !lanHost.isEmpty { + return lanHost + } + if let tailnet = gateway.tailnetDns?.trimmingCharacters(in: .whitespacesAndNewlines), !tailnet.isEmpty { + return tailnet + } + return nil + } + + private func buildGatewayURL(host: String, port: Int, useTLS: Bool) -> URL? { + let scheme = useTLS ? "wss" : "ws" + var components = URLComponents() + components.scheme = scheme + components.host = host + components.port = port + return components.url + } + + private func manualStableID(host: String, port: Int) -> String { + "manual|\(host.lowercased())|\(port)" + } + + private func makeConnectOptions() -> GatewayConnectOptions { + let defaults = UserDefaults.standard + let displayName = self.resolvedDisplayName(defaults: defaults) + + return GatewayConnectOptions( + role: "node", + scopes: [], + caps: self.currentCaps(), + commands: self.currentCommands(), + permissions: [:], + clientId: "clawdbot-ios", + clientMode: "node", + clientDisplayName: displayName) } private func resolvedDisplayName(defaults: UserDefaults) -> String { @@ -313,6 +334,11 @@ final class BridgeConnectionController { ClawdbotCanvasA2UICommand.pushJSONL.rawValue, ClawdbotCanvasA2UICommand.reset.rawValue, ClawdbotScreenCommand.record.rawValue, + ClawdbotSystemCommand.notify.rawValue, + ClawdbotSystemCommand.which.rawValue, + ClawdbotSystemCommand.run.rawValue, + ClawdbotSystemCommand.execApprovalsGet.rawValue, + ClawdbotSystemCommand.execApprovalsSet.rawValue, ] let caps = Set(self.currentCaps()) @@ -368,11 +394,7 @@ final class BridgeConnectionController { } #if DEBUG -extension BridgeConnectionController { - func _test_makeHello(token: String) -> BridgeHello { - self.makeHello(token: token) - } - +extension GatewayConnectionController { func _test_resolvedDisplayName(defaults: UserDefaults) -> String { self.resolvedDisplayName(defaults: defaults) } @@ -401,8 +423,8 @@ extension BridgeConnectionController { self.appVersion() } - func _test_setBridges(_ bridges: [BridgeDiscoveryModel.DiscoveredBridge]) { - self.bridges = bridges + func _test_setGateways(_ gateways: [GatewayDiscoveryModel.DiscoveredGateway]) { + self.gateways = gateways } func _test_triggerAutoConnect() { diff --git a/apps/ios/Sources/Bridge/BridgeDiscoveryDebugLogView.swift b/apps/ios/Sources/Gateway/GatewayDiscoveryDebugLogView.swift similarity index 79% rename from apps/ios/Sources/Bridge/BridgeDiscoveryDebugLogView.swift rename to apps/ios/Sources/Gateway/GatewayDiscoveryDebugLogView.swift index 26a946213..830722540 100644 --- a/apps/ios/Sources/Bridge/BridgeDiscoveryDebugLogView.swift +++ b/apps/ios/Sources/Gateway/GatewayDiscoveryDebugLogView.swift @@ -1,9 +1,9 @@ import SwiftUI import UIKit -struct BridgeDiscoveryDebugLogView: View { - @Environment(BridgeConnectionController.self) private var bridgeController - @AppStorage("bridge.discovery.debugLogs") private var debugLogsEnabled: Bool = false +struct GatewayDiscoveryDebugLogView: View { + @Environment(GatewayConnectionController.self) private var gatewayController + @AppStorage("gateway.discovery.debugLogs") private var debugLogsEnabled: Bool = false var body: some View { List { @@ -12,11 +12,11 @@ struct BridgeDiscoveryDebugLogView: View { .foregroundStyle(.secondary) } - if self.bridgeController.discoveryDebugLog.isEmpty { + if self.gatewayController.discoveryDebugLog.isEmpty { Text("No log entries yet.") .foregroundStyle(.secondary) } else { - ForEach(self.bridgeController.discoveryDebugLog) { entry in + ForEach(self.gatewayController.discoveryDebugLog) { entry in VStack(alignment: .leading, spacing: 2) { Text(Self.formatTime(entry.ts)) .font(.caption) @@ -35,13 +35,13 @@ struct BridgeDiscoveryDebugLogView: View { Button("Copy") { UIPasteboard.general.string = self.formattedLog() } - .disabled(self.bridgeController.discoveryDebugLog.isEmpty) + .disabled(self.gatewayController.discoveryDebugLog.isEmpty) } } } private func formattedLog() -> String { - self.bridgeController.discoveryDebugLog + self.gatewayController.discoveryDebugLog .map { "\(Self.formatISO($0.ts)) \($0.message)" } .joined(separator: "\n") } diff --git a/apps/ios/Sources/Bridge/BridgeDiscoveryModel.swift b/apps/ios/Sources/Gateway/GatewayDiscoveryModel.swift similarity index 86% rename from apps/ios/Sources/Bridge/BridgeDiscoveryModel.swift rename to apps/ios/Sources/Gateway/GatewayDiscoveryModel.swift index ad7d010bd..a40a62397 100644 --- a/apps/ios/Sources/Bridge/BridgeDiscoveryModel.swift +++ b/apps/ios/Sources/Gateway/GatewayDiscoveryModel.swift @@ -5,14 +5,14 @@ import Observation @MainActor @Observable -final class BridgeDiscoveryModel { +final class GatewayDiscoveryModel { struct DebugLogEntry: Identifiable, Equatable { var id = UUID() var ts: Date var message: String } - struct DiscoveredBridge: Identifiable, Equatable { + struct DiscoveredGateway: Identifiable, Equatable { var id: String { self.stableID } var name: String var endpoint: NWEndpoint @@ -21,19 +21,18 @@ final class BridgeDiscoveryModel { var lanHost: String? var tailnetDns: String? var gatewayPort: Int? - var bridgePort: Int? var canvasPort: Int? var tlsEnabled: Bool var tlsFingerprintSha256: String? var cliPath: String? } - var bridges: [DiscoveredBridge] = [] + var gateways: [DiscoveredGateway] = [] var statusText: String = "Idle" private(set) var debugLog: [DebugLogEntry] = [] private var browsers: [String: NWBrowser] = [:] - private var bridgesByDomain: [String: [DiscoveredBridge]] = [:] + private var gatewaysByDomain: [String: [DiscoveredGateway]] = [:] private var statesByDomain: [String: NWBrowser.State] = [:] private var debugLoggingEnabled = false private var lastStableIDs = Set() @@ -45,7 +44,7 @@ final class BridgeDiscoveryModel { self.debugLog = [] } else if !wasEnabled { self.appendDebugLog("debug logging enabled") - self.appendDebugLog("snapshot: status=\(self.statusText) bridges=\(self.bridges.count)") + self.appendDebugLog("snapshot: status=\(self.statusText) gateways=\(self.gateways.count)") } } @@ -53,11 +52,11 @@ final class BridgeDiscoveryModel { if !self.browsers.isEmpty { return } self.appendDebugLog("start()") - for domain in ClawdbotBonjour.bridgeServiceDomains { + for domain in ClawdbotBonjour.gatewayServiceDomains { let params = NWParameters.tcp params.includePeerToPeer = true let browser = NWBrowser( - for: .bonjour(type: ClawdbotBonjour.bridgeServiceType, domain: domain), + for: .bonjour(type: ClawdbotBonjour.gatewayServiceType, domain: domain), using: params) browser.stateUpdateHandler = { [weak self] state in @@ -72,7 +71,7 @@ final class BridgeDiscoveryModel { browser.browseResultsChangedHandler = { [weak self] results, _ in Task { @MainActor in guard let self else { return } - self.bridgesByDomain[domain] = results.compactMap { result -> DiscoveredBridge? in + self.gatewaysByDomain[domain] = results.compactMap { result -> DiscoveredGateway? in switch result.endpoint { case let .service(name, _, _, _): let decodedName = BonjourEscapes.decode(name) @@ -82,18 +81,17 @@ final class BridgeDiscoveryModel { .map(Self.prettifyInstanceName) .flatMap { $0.isEmpty ? nil : $0 } let prettyName = prettyAdvertised ?? Self.prettifyInstanceName(decodedName) - return DiscoveredBridge( + return DiscoveredGateway( name: prettyName, endpoint: result.endpoint, - stableID: BridgeEndpointID.stableID(result.endpoint), - debugID: BridgeEndpointID.prettyDescription(result.endpoint), + stableID: GatewayEndpointID.stableID(result.endpoint), + debugID: GatewayEndpointID.prettyDescription(result.endpoint), lanHost: Self.txtValue(txt, key: "lanHost"), tailnetDns: Self.txtValue(txt, key: "tailnetDns"), gatewayPort: Self.txtIntValue(txt, key: "gatewayPort"), - bridgePort: Self.txtIntValue(txt, key: "bridgePort"), canvasPort: Self.txtIntValue(txt, key: "canvasPort"), - tlsEnabled: Self.txtBoolValue(txt, key: "bridgeTls"), - tlsFingerprintSha256: Self.txtValue(txt, key: "bridgeTlsSha256"), + tlsEnabled: Self.txtBoolValue(txt, key: "gatewayTls"), + tlsFingerprintSha256: Self.txtValue(txt, key: "gatewayTlsSha256"), cliPath: Self.txtValue(txt, key: "cliPath")) default: return nil @@ -101,12 +99,12 @@ final class BridgeDiscoveryModel { } .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } - self.recomputeBridges() + self.recomputeGateways() } } self.browsers[domain] = browser - browser.start(queue: DispatchQueue(label: "com.clawdbot.ios.bridge-discovery.\(domain)")) + browser.start(queue: DispatchQueue(label: "com.clawdbot.ios.gateway-discovery.\(domain)")) } } @@ -116,14 +114,14 @@ final class BridgeDiscoveryModel { browser.cancel() } self.browsers = [:] - self.bridgesByDomain = [:] + self.gatewaysByDomain = [:] self.statesByDomain = [:] - self.bridges = [] + self.gateways = [] self.statusText = "Stopped" } - private func recomputeBridges() { - let next = self.bridgesByDomain.values + private func recomputeGateways() { + let next = self.gatewaysByDomain.values .flatMap(\.self) .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } @@ -134,7 +132,7 @@ final class BridgeDiscoveryModel { self.appendDebugLog("results: total=\(next.count) added=\(added.count) removed=\(removed.count)") } self.lastStableIDs = nextIDs - self.bridges = next + self.gateways = next } private func updateStatusText() { diff --git a/apps/ios/Sources/Gateway/GatewaySettingsStore.swift b/apps/ios/Sources/Gateway/GatewaySettingsStore.swift new file mode 100644 index 000000000..52ada8d80 --- /dev/null +++ b/apps/ios/Sources/Gateway/GatewaySettingsStore.swift @@ -0,0 +1,226 @@ +import Foundation + +enum GatewaySettingsStore { + private static let gatewayService = "com.clawdbot.gateway" + private static let legacyBridgeService = "com.clawdbot.bridge" + private static let nodeService = "com.clawdbot.node" + + private static let instanceIdDefaultsKey = "node.instanceId" + private static let preferredGatewayStableIDDefaultsKey = "gateway.preferredStableID" + private static let lastDiscoveredGatewayStableIDDefaultsKey = "gateway.lastDiscoveredStableID" + private static let manualEnabledDefaultsKey = "gateway.manual.enabled" + private static let manualHostDefaultsKey = "gateway.manual.host" + private static let manualPortDefaultsKey = "gateway.manual.port" + private static let manualTlsDefaultsKey = "gateway.manual.tls" + private static let discoveryDebugLogsDefaultsKey = "gateway.discovery.debugLogs" + + private static let legacyPreferredBridgeStableIDDefaultsKey = "bridge.preferredStableID" + private static let legacyLastDiscoveredBridgeStableIDDefaultsKey = "bridge.lastDiscoveredStableID" + private static let legacyManualEnabledDefaultsKey = "bridge.manual.enabled" + private static let legacyManualHostDefaultsKey = "bridge.manual.host" + private static let legacyManualPortDefaultsKey = "bridge.manual.port" + private static let legacyDiscoveryDebugLogsDefaultsKey = "bridge.discovery.debugLogs" + + private static let instanceIdAccount = "instanceId" + private static let preferredGatewayStableIDAccount = "preferredStableID" + private static let lastDiscoveredGatewayStableIDAccount = "lastDiscoveredStableID" + + static func bootstrapPersistence() { + self.ensureStableInstanceID() + self.ensurePreferredGatewayStableID() + self.ensureLastDiscoveredGatewayStableID() + self.migrateLegacyDefaults() + } + + static func loadStableInstanceID() -> String? { + KeychainStore.loadString(service: self.nodeService, account: self.instanceIdAccount)? + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + static func saveStableInstanceID(_ instanceId: String) { + _ = KeychainStore.saveString(instanceId, service: self.nodeService, account: self.instanceIdAccount) + } + + static func loadPreferredGatewayStableID() -> String? { + KeychainStore.loadString(service: self.gatewayService, account: self.preferredGatewayStableIDAccount)? + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + static func savePreferredGatewayStableID(_ stableID: String) { + _ = KeychainStore.saveString( + stableID, + service: self.gatewayService, + account: self.preferredGatewayStableIDAccount) + } + + static func loadLastDiscoveredGatewayStableID() -> String? { + KeychainStore.loadString(service: self.gatewayService, account: self.lastDiscoveredGatewayStableIDAccount)? + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + static func saveLastDiscoveredGatewayStableID(_ stableID: String) { + _ = KeychainStore.saveString( + stableID, + service: self.gatewayService, + account: self.lastDiscoveredGatewayStableIDAccount) + } + + static func loadGatewayToken(instanceId: String) -> String? { + let account = self.gatewayTokenAccount(instanceId: instanceId) + let token = KeychainStore.loadString(service: self.gatewayService, account: account)? + .trimmingCharacters(in: .whitespacesAndNewlines) + if token?.isEmpty == false { return token } + + let legacyAccount = self.legacyBridgeTokenAccount(instanceId: instanceId) + let legacy = KeychainStore.loadString(service: self.legacyBridgeService, account: legacyAccount)? + .trimmingCharacters(in: .whitespacesAndNewlines) + if let legacy, !legacy.isEmpty { + _ = KeychainStore.saveString(legacy, service: self.gatewayService, account: account) + return legacy + } + return nil + } + + static func saveGatewayToken(_ token: String, instanceId: String) { + _ = KeychainStore.saveString( + token, + service: self.gatewayService, + account: self.gatewayTokenAccount(instanceId: instanceId)) + } + + static func loadGatewayPassword(instanceId: String) -> String? { + KeychainStore.loadString( + service: self.gatewayService, + account: self.gatewayPasswordAccount(instanceId: instanceId))? + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + static func saveGatewayPassword(_ password: String, instanceId: String) { + _ = KeychainStore.saveString( + password, + service: self.gatewayService, + account: self.gatewayPasswordAccount(instanceId: instanceId)) + } + + private static func gatewayTokenAccount(instanceId: String) -> String { + "gateway-token.\(instanceId)" + } + + private static func legacyBridgeTokenAccount(instanceId: String) -> String { + "bridge-token.\(instanceId)" + } + + private static func gatewayPasswordAccount(instanceId: String) -> String { + "gateway-password.\(instanceId)" + } + + private static func ensureStableInstanceID() { + let defaults = UserDefaults.standard + + if let existing = defaults.string(forKey: self.instanceIdDefaultsKey)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !existing.isEmpty + { + if self.loadStableInstanceID() == nil { + self.saveStableInstanceID(existing) + } + return + } + + if let stored = self.loadStableInstanceID(), !stored.isEmpty { + defaults.set(stored, forKey: self.instanceIdDefaultsKey) + return + } + + let fresh = UUID().uuidString + self.saveStableInstanceID(fresh) + defaults.set(fresh, forKey: self.instanceIdDefaultsKey) + } + + private static func ensurePreferredGatewayStableID() { + let defaults = UserDefaults.standard + + if let existing = defaults.string(forKey: self.preferredGatewayStableIDDefaultsKey)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !existing.isEmpty + { + if self.loadPreferredGatewayStableID() == nil { + self.savePreferredGatewayStableID(existing) + } + return + } + + if let stored = self.loadPreferredGatewayStableID(), !stored.isEmpty { + defaults.set(stored, forKey: self.preferredGatewayStableIDDefaultsKey) + } + } + + private static func ensureLastDiscoveredGatewayStableID() { + let defaults = UserDefaults.standard + + if let existing = defaults.string(forKey: self.lastDiscoveredGatewayStableIDDefaultsKey)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !existing.isEmpty + { + if self.loadLastDiscoveredGatewayStableID() == nil { + self.saveLastDiscoveredGatewayStableID(existing) + } + return + } + + if let stored = self.loadLastDiscoveredGatewayStableID(), !stored.isEmpty { + defaults.set(stored, forKey: self.lastDiscoveredGatewayStableIDDefaultsKey) + } + } + + private static func migrateLegacyDefaults() { + let defaults = UserDefaults.standard + + if defaults.string(forKey: self.preferredGatewayStableIDDefaultsKey)?.isEmpty != false, + let legacy = defaults.string(forKey: self.legacyPreferredBridgeStableIDDefaultsKey), + !legacy.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + { + defaults.set(legacy, forKey: self.preferredGatewayStableIDDefaultsKey) + self.savePreferredGatewayStableID(legacy) + } + + if defaults.string(forKey: self.lastDiscoveredGatewayStableIDDefaultsKey)?.isEmpty != false, + let legacy = defaults.string(forKey: self.legacyLastDiscoveredBridgeStableIDDefaultsKey), + !legacy.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + { + defaults.set(legacy, forKey: self.lastDiscoveredGatewayStableIDDefaultsKey) + self.saveLastDiscoveredGatewayStableID(legacy) + } + + if defaults.object(forKey: self.manualEnabledDefaultsKey) == nil, + defaults.object(forKey: self.legacyManualEnabledDefaultsKey) != nil + { + defaults.set( + defaults.bool(forKey: self.legacyManualEnabledDefaultsKey), + forKey: self.manualEnabledDefaultsKey) + } + + if defaults.string(forKey: self.manualHostDefaultsKey)?.isEmpty != false, + let legacy = defaults.string(forKey: self.legacyManualHostDefaultsKey), + !legacy.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + { + defaults.set(legacy, forKey: self.manualHostDefaultsKey) + } + + if defaults.integer(forKey: self.manualPortDefaultsKey) == 0, + defaults.integer(forKey: self.legacyManualPortDefaultsKey) > 0 + { + defaults.set( + defaults.integer(forKey: self.legacyManualPortDefaultsKey), + forKey: self.manualPortDefaultsKey) + } + + if defaults.object(forKey: self.discoveryDebugLogsDefaultsKey) == nil, + defaults.object(forKey: self.legacyDiscoveryDebugLogsDefaultsKey) != nil + { + defaults.set( + defaults.bool(forKey: self.legacyDiscoveryDebugLogsDefaultsKey), + forKey: self.discoveryDebugLogsDefaultsKey) + } + } +} diff --git a/apps/ios/Sources/Bridge/KeychainStore.swift b/apps/ios/Sources/Gateway/KeychainStore.swift similarity index 100% rename from apps/ios/Sources/Bridge/KeychainStore.swift rename to apps/ios/Sources/Gateway/KeychainStore.swift diff --git a/apps/ios/Sources/Info.plist b/apps/ios/Sources/Info.plist index a75e27741..e1cf2b71d 100644 --- a/apps/ios/Sources/Info.plist +++ b/apps/ios/Sources/Info.plist @@ -19,9 +19,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 2026.1.11-4 + 2026.1.25 CFBundleVersion - 202601113 + 20260125 NSAppTransportSecurity NSAllowsArbitraryLoadsInWebContent @@ -29,12 +29,12 @@ NSBonjourServices - _clawdbot-bridge._tcp + _clawdbot-gw._tcp NSCameraUsageDescription - Clawdbot can capture photos or short video clips when requested via the bridge. + Clawdbot can capture photos or short video clips when requested via the gateway. NSLocalNetworkUsageDescription - Clawdbot discovers and connects to your Clawdbot bridge on the local network. + Clawdbot discovers and connects to your Clawdbot gateway on the local network. NSLocationAlwaysAndWhenInUseUsageDescription Clawdbot can share your location in the background when you enable Always. NSLocationWhenInUseUsageDescription diff --git a/apps/ios/Sources/Model/NodeAppModel.swift b/apps/ios/Sources/Model/NodeAppModel.swift index 258d79f4a..2830f17d7 100644 --- a/apps/ios/Sources/Model/NodeAppModel.swift +++ b/apps/ios/Sources/Model/NodeAppModel.swift @@ -18,15 +18,15 @@ final class NodeAppModel { let screen = ScreenController() let camera = CameraController() private let screenRecorder = ScreenRecordService() - var bridgeStatusText: String = "Offline" - var bridgeServerName: String? - var bridgeRemoteAddress: String? - var connectedBridgeID: String? + var gatewayStatusText: String = "Offline" + var gatewayServerName: String? + var gatewayRemoteAddress: String? + var connectedGatewayID: String? var seamColorHex: String? var mainSessionKey: String = "main" - private let bridge = BridgeSession() - private var bridgeTask: Task? + private let gateway = GatewayNodeSession() + private var gatewayTask: Task? private var voiceWakeSyncTask: Task? @ObservationIgnored private var cameraHUDDismissTask: Task? let voiceWake = VoiceWakeManager() @@ -34,7 +34,8 @@ final class NodeAppModel { private let locationService = LocationService() private var lastAutoA2uiURL: String? - var bridgeSession: BridgeSession { self.bridge } + private var gatewayConnected = false + var gatewaySession: GatewayNodeSession { self.gateway } var cameraHUDText: String? var cameraHUDKind: CameraHUDKind? @@ -54,7 +55,7 @@ final class NodeAppModel { let enabled = UserDefaults.standard.bool(forKey: "voiceWake.enabled") self.voiceWake.setEnabled(enabled) - self.talkMode.attachBridge(self.bridge) + self.talkMode.attachGateway(self.gateway) let talkEnabled = UserDefaults.standard.bool(forKey: "talk.enabled") self.talkMode.setEnabled(talkEnabled) @@ -120,9 +121,9 @@ final class NodeAppModel { let ok: Bool var errorText: String? - if await !self.isBridgeConnected() { + if await !self.isGatewayConnected() { ok = false - errorText = "bridge not connected" + errorText = "gateway not connected" } else { do { try await self.sendAgentRequest(link: AgentDeepLink( @@ -150,7 +151,7 @@ final class NodeAppModel { } private func resolveA2UIHostURL() async -> String? { - guard let raw = await self.bridge.currentCanvasHostUrl() else { return nil } + guard let raw = await self.gateway.currentCanvasHostUrl() else { return nil } let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty, let base = URL(string: trimmed) else { return nil } return base.appendingPathComponent("__clawdbot__/a2ui/").absoluteString + "?platform=ios" @@ -202,56 +203,70 @@ final class NodeAppModel { } } - func connectToBridge( - endpoint: NWEndpoint, - bridgeStableID: String, - tls: BridgeTLSParams?, - hello: BridgeHello) + func connectToGateway( + url: URL, + gatewayStableID: String, + tls: GatewayTLSParams?, + token: String?, + password: String?, + connectOptions: GatewayConnectOptions) { - self.bridgeTask?.cancel() - self.bridgeServerName = nil - self.bridgeRemoteAddress = nil - let id = bridgeStableID.trimmingCharacters(in: .whitespacesAndNewlines) - self.connectedBridgeID = id.isEmpty ? BridgeEndpointID.stableID(endpoint) : id + self.gatewayTask?.cancel() + self.gatewayServerName = nil + self.gatewayRemoteAddress = nil + let id = gatewayStableID.trimmingCharacters(in: .whitespacesAndNewlines) + self.connectedGatewayID = id.isEmpty ? url.absoluteString : id + self.gatewayConnected = false self.voiceWakeSyncTask?.cancel() self.voiceWakeSyncTask = nil + let sessionBox = tls.map { WebSocketSessionBox(session: GatewayTLSPinningSession(params: $0)) } - self.bridgeTask = Task { + self.gatewayTask = Task { var attempt = 0 while !Task.isCancelled { await MainActor.run { if attempt == 0 { - self.bridgeStatusText = "Connecting…" + self.gatewayStatusText = "Connecting…" } else { - self.bridgeStatusText = "Reconnecting…" + self.gatewayStatusText = "Reconnecting…" } - self.bridgeServerName = nil - self.bridgeRemoteAddress = nil + self.gatewayServerName = nil + self.gatewayRemoteAddress = nil } do { - try await self.bridge.connect( - endpoint: endpoint, - hello: hello, - tls: tls, - onConnected: { [weak self] serverName, mainSessionKey in + try await self.gateway.connect( + url: url, + token: token, + password: password, + connectOptions: connectOptions, + sessionBox: sessionBox, + onConnected: { [weak self] in guard let self else { return } await MainActor.run { - self.bridgeStatusText = "Connected" - self.bridgeServerName = serverName + self.gatewayStatusText = "Connected" + self.gatewayServerName = url.host ?? "gateway" + self.gatewayConnected = true } - await MainActor.run { - self.applyMainSessionKey(mainSessionKey) - } - if let addr = await self.bridge.currentRemoteAddress() { + if let addr = await self.gateway.currentRemoteAddress() { await MainActor.run { - self.bridgeRemoteAddress = addr + self.gatewayRemoteAddress = addr } } await self.refreshBrandingFromGateway() await self.startVoiceWakeSync() await self.showA2UIOnConnectIfNeeded() }, + onDisconnected: { [weak self] reason in + guard let self else { return } + await MainActor.run { + self.gatewayStatusText = "Disconnected" + self.gatewayRemoteAddress = nil + self.gatewayConnected = false + self.showLocalCanvasOnDisconnect() + self.gatewayStatusText = "Disconnected: \(reason)" + } + }, onInvoke: { [weak self] req in guard let self else { return BridgeInvokeResponse( @@ -265,19 +280,16 @@ final class NodeAppModel { }) if Task.isCancelled { break } - await MainActor.run { - self.showLocalCanvasOnDisconnect() - } - attempt += 1 - let sleepSeconds = min(6.0, 0.35 * pow(1.7, Double(attempt))) - try? await Task.sleep(nanoseconds: UInt64(sleepSeconds * 1_000_000_000)) + attempt = 0 + try? await Task.sleep(nanoseconds: 1_000_000_000) } catch { if Task.isCancelled { break } attempt += 1 await MainActor.run { - self.bridgeStatusText = "Bridge error: \(error.localizedDescription)" - self.bridgeServerName = nil - self.bridgeRemoteAddress = nil + self.gatewayStatusText = "Gateway error: \(error.localizedDescription)" + self.gatewayServerName = nil + self.gatewayRemoteAddress = nil + self.gatewayConnected = false self.showLocalCanvasOnDisconnect() } let sleepSeconds = min(8.0, 0.5 * pow(1.7, Double(attempt))) @@ -286,10 +298,11 @@ final class NodeAppModel { } await MainActor.run { - self.bridgeStatusText = "Offline" - self.bridgeServerName = nil - self.bridgeRemoteAddress = nil - self.connectedBridgeID = nil + self.gatewayStatusText = "Offline" + self.gatewayServerName = nil + self.gatewayRemoteAddress = nil + self.connectedGatewayID = nil + self.gatewayConnected = false self.seamColorHex = nil if !SessionKey.isCanonicalMainSessionKey(self.mainSessionKey) { self.mainSessionKey = "main" @@ -300,16 +313,17 @@ final class NodeAppModel { } } - func disconnectBridge() { - self.bridgeTask?.cancel() - self.bridgeTask = nil + func disconnectGateway() { + self.gatewayTask?.cancel() + self.gatewayTask = nil self.voiceWakeSyncTask?.cancel() self.voiceWakeSyncTask = nil - Task { await self.bridge.disconnect() } - self.bridgeStatusText = "Offline" - self.bridgeServerName = nil - self.bridgeRemoteAddress = nil - self.connectedBridgeID = nil + Task { await self.gateway.disconnect() } + self.gatewayStatusText = "Offline" + self.gatewayServerName = nil + self.gatewayRemoteAddress = nil + self.connectedGatewayID = nil + self.gatewayConnected = false self.seamColorHex = nil if !SessionKey.isCanonicalMainSessionKey(self.mainSessionKey) { self.mainSessionKey = "main" @@ -347,7 +361,7 @@ final class NodeAppModel { private func refreshBrandingFromGateway() async { do { - let res = try await self.bridge.request(method: "config.get", paramsJSON: "{}", timeoutSeconds: 8) + let res = try await self.gateway.request(method: "config.get", paramsJSON: "{}", timeoutSeconds: 8) guard let json = try JSONSerialization.jsonObject(with: res) as? [String: Any] else { return } guard let config = json["config"] as? [String: Any] else { return } let ui = config["ui"] as? [String: Any] @@ -378,7 +392,7 @@ final class NodeAppModel { else { return } do { - _ = try await self.bridge.request(method: "voicewake.set", paramsJSON: json, timeoutSeconds: 12) + _ = try await self.gateway.request(method: "voicewake.set", paramsJSON: json, timeoutSeconds: 12) } catch { // Best-effort only. } @@ -391,12 +405,14 @@ final class NodeAppModel { await self.refreshWakeWordsFromGateway() - let stream = await self.bridge.subscribeServerEvents(bufferingNewest: 200) + let stream = await self.gateway.subscribeServerEvents(bufferingNewest: 200) for await evt in stream { if Task.isCancelled { return } guard evt.event == "voicewake.changed" else { continue } - guard let payloadJSON = evt.payloadJSON else { continue } - guard let triggers = VoiceWakePreferences.decodeGatewayTriggers(from: payloadJSON) else { continue } + guard let payload = evt.payload else { continue } + struct Payload: Decodable { var triggers: [String] } + guard let decoded = try? GatewayPayloadDecoding.decode(payload, as: Payload.self) else { continue } + let triggers = VoiceWakePreferences.sanitizeTriggerWords(decoded.triggers) VoiceWakePreferences.saveTriggerWords(triggers) } } @@ -404,7 +420,7 @@ final class NodeAppModel { private func refreshWakeWordsFromGateway() async { do { - let data = try await self.bridge.request(method: "voicewake.get", paramsJSON: "{}", timeoutSeconds: 8) + let data = try await self.gateway.request(method: "voicewake.get", paramsJSON: "{}", timeoutSeconds: 8) guard let triggers = VoiceWakePreferences.decodeGatewayTriggers(from: data) else { return } VoiceWakePreferences.saveTriggerWords(triggers) } catch { @@ -413,6 +429,11 @@ final class NodeAppModel { } func sendVoiceTranscript(text: String, sessionKey: String?) async throws { + if await !self.isGatewayConnected() { + throw NSError(domain: "Gateway", code: 10, userInfo: [ + NSLocalizedDescriptionKey: "Gateway not connected", + ]) + } struct Payload: Codable { var text: String var sessionKey: String? @@ -424,7 +445,7 @@ final class NodeAppModel { NSLocalizedDescriptionKey: "Failed to encode voice transcript payload as UTF-8", ]) } - try await self.bridge.sendEvent(event: "voice.transcript", payloadJSON: json) + await self.gateway.sendEvent(event: "voice.transcript", payloadJSON: json) } func handleDeepLink(url: URL) async { @@ -445,8 +466,8 @@ final class NodeAppModel { return } - guard await self.isBridgeConnected() else { - self.screen.errorText = "Bridge not connected (cannot forward deep link)." + guard await self.isGatewayConnected() else { + self.screen.errorText = "Gateway not connected (cannot forward deep link)." return } @@ -465,7 +486,7 @@ final class NodeAppModel { ]) } - // iOS bridge forwards to the gateway; no local auth prompts here. + // iOS gateway forwards to the gateway; no local auth prompts here. // (Key-based unattended auth is handled on macOS for clawdbot:// links.) let data = try JSONEncoder().encode(link) guard let json = String(bytes: data, encoding: .utf8) else { @@ -473,12 +494,11 @@ final class NodeAppModel { NSLocalizedDescriptionKey: "Failed to encode agent request payload as UTF-8", ]) } - try await self.bridge.sendEvent(event: "agent.request", payloadJSON: json) + await self.gateway.sendEvent(event: "agent.request", payloadJSON: json) } - private func isBridgeConnected() async -> Bool { - if case .connected = await self.bridge.state { return true } - return false + private func isGatewayConnected() async -> Bool { + self.gatewayConnected } private func handleInvoke(_ req: BridgeInvokeRequest) async -> BridgeInvokeResponse { @@ -817,7 +837,7 @@ final class NodeAppModel { fps: params.fps, includeAudio: params.includeAudio, outPath: nil) - defer { try? FileManager.default.removeItem(atPath: path) } + defer { try? FileManager().removeItem(atPath: path) } let data = try Data(contentsOf: URL(fileURLWithPath: path)) struct Payload: Codable { var format: String @@ -837,26 +857,29 @@ final class NodeAppModel { return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: payload) } - private func locationMode() -> ClawdbotLocationMode { +} + +private extension NodeAppModel { + func locationMode() -> ClawdbotLocationMode { let raw = UserDefaults.standard.string(forKey: "location.enabledMode") ?? "off" return ClawdbotLocationMode(rawValue: raw) ?? .off } - private func isLocationPreciseEnabled() -> Bool { + func isLocationPreciseEnabled() -> Bool { if UserDefaults.standard.object(forKey: "location.preciseEnabled") == nil { return true } return UserDefaults.standard.bool(forKey: "location.preciseEnabled") } - private static func decodeParams(_ type: T.Type, from json: String?) throws -> T { + static func decodeParams(_ type: T.Type, from json: String?) throws -> T { guard let json, let data = json.data(using: .utf8) else { - throw NSError(domain: "Bridge", code: 20, userInfo: [ + throw NSError(domain: "Gateway", code: 20, userInfo: [ NSLocalizedDescriptionKey: "INVALID_REQUEST: paramsJSON required", ]) } return try JSONDecoder().decode(type, from: data) } - private static func encodePayload(_ obj: some Encodable) throws -> String { + static func encodePayload(_ obj: some Encodable) throws -> String { let data = try JSONEncoder().encode(obj) guard let json = String(bytes: data, encoding: .utf8) else { throw NSError(domain: "NodeAppModel", code: 21, userInfo: [ @@ -866,17 +889,17 @@ final class NodeAppModel { return json } - private func isCameraEnabled() -> Bool { + func isCameraEnabled() -> Bool { // Default-on: if the key doesn't exist yet, treat it as enabled. if UserDefaults.standard.object(forKey: "camera.enabled") == nil { return true } return UserDefaults.standard.bool(forKey: "camera.enabled") } - private func triggerCameraFlash() { + func triggerCameraFlash() { self.cameraFlashNonce &+= 1 } - private func showCameraHUD(text: String, kind: CameraHUDKind, autoHideSeconds: Double? = nil) { + func showCameraHUD(text: String, kind: CameraHUDKind, autoHideSeconds: Double? = nil) { self.cameraHUDDismissTask?.cancel() withAnimation(.spring(response: 0.25, dampingFraction: 0.85)) { diff --git a/apps/ios/Sources/RootCanvas.swift b/apps/ios/Sources/RootCanvas.swift index bd3fefc52..93cb81627 100644 --- a/apps/ios/Sources/RootCanvas.swift +++ b/apps/ios/Sources/RootCanvas.swift @@ -29,7 +29,7 @@ struct RootCanvas: View { ZStack { CanvasContent( systemColorScheme: self.systemColorScheme, - bridgeStatus: self.bridgeStatus, + gatewayStatus: self.gatewayStatus, voiceWakeEnabled: self.voiceWakeEnabled, voiceWakeToastText: self.voiceWakeToastText, cameraHUDText: self.appModel.cameraHUDText, @@ -52,7 +52,7 @@ struct RootCanvas: View { SettingsTab() case .chat: ChatSheet( - bridge: self.appModel.bridgeSession, + gateway: self.appModel.gatewaySession, sessionKey: self.appModel.mainSessionKey, userAccent: self.appModel.seamColor) } @@ -62,9 +62,9 @@ struct RootCanvas: View { .onChange(of: self.scenePhase) { _, _ in self.updateIdleTimer() } .onAppear { self.updateCanvasDebugStatus() } .onChange(of: self.canvasDebugStatusEnabled) { _, _ in self.updateCanvasDebugStatus() } - .onChange(of: self.appModel.bridgeStatusText) { _, _ in self.updateCanvasDebugStatus() } - .onChange(of: self.appModel.bridgeServerName) { _, _ in self.updateCanvasDebugStatus() } - .onChange(of: self.appModel.bridgeRemoteAddress) { _, _ in self.updateCanvasDebugStatus() } + .onChange(of: self.appModel.gatewayStatusText) { _, _ in self.updateCanvasDebugStatus() } + .onChange(of: self.appModel.gatewayServerName) { _, _ in self.updateCanvasDebugStatus() } + .onChange(of: self.appModel.gatewayRemoteAddress) { _, _ in self.updateCanvasDebugStatus() } .onChange(of: self.voiceWake.lastTriggeredCommand) { _, newValue in guard let newValue else { return } let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) @@ -91,10 +91,10 @@ struct RootCanvas: View { } } - private var bridgeStatus: StatusPill.BridgeState { - if self.appModel.bridgeServerName != nil { return .connected } + private var gatewayStatus: StatusPill.GatewayState { + if self.appModel.gatewayServerName != nil { return .connected } - let text = self.appModel.bridgeStatusText.trimmingCharacters(in: .whitespacesAndNewlines) + let text = self.appModel.gatewayStatusText.trimmingCharacters(in: .whitespacesAndNewlines) if text.localizedCaseInsensitiveContains("connecting") || text.localizedCaseInsensitiveContains("reconnecting") { @@ -115,8 +115,8 @@ struct RootCanvas: View { private func updateCanvasDebugStatus() { self.appModel.screen.setDebugStatusEnabled(self.canvasDebugStatusEnabled) guard self.canvasDebugStatusEnabled else { return } - let title = self.appModel.bridgeStatusText.trimmingCharacters(in: .whitespacesAndNewlines) - let subtitle = self.appModel.bridgeServerName ?? self.appModel.bridgeRemoteAddress + let title = self.appModel.gatewayStatusText.trimmingCharacters(in: .whitespacesAndNewlines) + let subtitle = self.appModel.gatewayServerName ?? self.appModel.gatewayRemoteAddress self.appModel.screen.updateDebugStatus(title: title, subtitle: subtitle) } } @@ -126,7 +126,7 @@ private struct CanvasContent: View { @AppStorage("talk.enabled") private var talkEnabled: Bool = false @AppStorage("talk.button.enabled") private var talkButtonEnabled: Bool = true var systemColorScheme: ColorScheme - var bridgeStatus: StatusPill.BridgeState + var gatewayStatus: StatusPill.GatewayState var voiceWakeEnabled: Bool var voiceWakeToastText: String? var cameraHUDText: String? @@ -177,7 +177,7 @@ private struct CanvasContent: View { } .overlay(alignment: .topLeading) { StatusPill( - bridge: self.bridgeStatus, + gateway: self.gatewayStatus, voiceWakeEnabled: self.voiceWakeEnabled, activity: self.statusActivity, brighten: self.brightenButtons, @@ -208,15 +208,15 @@ private struct CanvasContent: View { tint: .orange) } - let bridgeStatus = self.appModel.bridgeStatusText.trimmingCharacters(in: .whitespacesAndNewlines) - let bridgeLower = bridgeStatus.lowercased() - if bridgeLower.contains("repair") { + let gatewayStatus = self.appModel.gatewayStatusText.trimmingCharacters(in: .whitespacesAndNewlines) + let gatewayLower = gatewayStatus.lowercased() + if gatewayLower.contains("repair") { return StatusPill.Activity(title: "Repairing…", systemImage: "wrench.and.screwdriver", tint: .orange) } - if bridgeLower.contains("approval") || bridgeLower.contains("pairing") { + if gatewayLower.contains("approval") || gatewayLower.contains("pairing") { return StatusPill.Activity(title: "Approval pending", systemImage: "person.crop.circle.badge.clock") } - // Avoid duplicating the primary bridge status ("Connecting…") in the activity slot. + // Avoid duplicating the primary gateway status ("Connecting…") in the activity slot. if self.appModel.screenRecordActive { return StatusPill.Activity(title: "Recording screen…", systemImage: "record.circle.fill", tint: .red) diff --git a/apps/ios/Sources/RootTabs.swift b/apps/ios/Sources/RootTabs.swift index e76d357a0..f7b3fd822 100644 --- a/apps/ios/Sources/RootTabs.swift +++ b/apps/ios/Sources/RootTabs.swift @@ -24,7 +24,7 @@ struct RootTabs: View { } .overlay(alignment: .topLeading) { StatusPill( - bridge: self.bridgeStatus, + gateway: self.gatewayStatus, voiceWakeEnabled: self.voiceWakeEnabled, activity: self.statusActivity, onTap: { self.selectedTab = 2 }) @@ -64,10 +64,10 @@ struct RootTabs: View { } } - private var bridgeStatus: StatusPill.BridgeState { - if self.appModel.bridgeServerName != nil { return .connected } + private var gatewayStatus: StatusPill.GatewayState { + if self.appModel.gatewayServerName != nil { return .connected } - let text = self.appModel.bridgeStatusText.trimmingCharacters(in: .whitespacesAndNewlines) + let text = self.appModel.gatewayStatusText.trimmingCharacters(in: .whitespacesAndNewlines) if text.localizedCaseInsensitiveContains("connecting") || text.localizedCaseInsensitiveContains("reconnecting") { @@ -90,15 +90,15 @@ struct RootTabs: View { tint: .orange) } - let bridgeStatus = self.appModel.bridgeStatusText.trimmingCharacters(in: .whitespacesAndNewlines) - let bridgeLower = bridgeStatus.lowercased() - if bridgeLower.contains("repair") { + let gatewayStatus = self.appModel.gatewayStatusText.trimmingCharacters(in: .whitespacesAndNewlines) + let gatewayLower = gatewayStatus.lowercased() + if gatewayLower.contains("repair") { return StatusPill.Activity(title: "Repairing…", systemImage: "wrench.and.screwdriver", tint: .orange) } - if bridgeLower.contains("approval") || bridgeLower.contains("pairing") { + if gatewayLower.contains("approval") || gatewayLower.contains("pairing") { return StatusPill.Activity(title: "Approval pending", systemImage: "person.crop.circle.badge.clock") } - // Avoid duplicating the primary bridge status ("Connecting…") in the activity slot. + // Avoid duplicating the primary gateway status ("Connecting…") in the activity slot. if self.appModel.screenRecordActive { return StatusPill.Activity(title: "Recording screen…", systemImage: "record.circle.fill", tint: .red) diff --git a/apps/ios/Sources/Screen/ScreenRecordService.swift b/apps/ios/Sources/Screen/ScreenRecordService.swift index e31762e51..6bccae5f9 100644 --- a/apps/ios/Sources/Screen/ScreenRecordService.swift +++ b/apps/ios/Sources/Screen/ScreenRecordService.swift @@ -91,7 +91,7 @@ final class ScreenRecordService: @unchecked Sendable { let includeAudio = includeAudio ?? true let outURL = self.makeOutputURL(outPath: outPath) - try? FileManager.default.removeItem(at: outURL) + try? FileManager().removeItem(at: outURL) return RecordConfig( durationMs: durationMs, @@ -104,7 +104,7 @@ final class ScreenRecordService: @unchecked Sendable { if let outPath, !outPath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return URL(fileURLWithPath: outPath) } - return FileManager.default.temporaryDirectory + return FileManager().temporaryDirectory .appendingPathComponent("clawdbot-screen-record-\(UUID().uuidString).mp4") } diff --git a/apps/ios/Sources/Settings/SettingsTab.swift b/apps/ios/Sources/Settings/SettingsTab.swift index bc474ff00..431761617 100644 --- a/apps/ios/Sources/Settings/SettingsTab.swift +++ b/apps/ios/Sources/Settings/SettingsTab.swift @@ -15,7 +15,7 @@ extension ConnectStatusStore: @unchecked Sendable {} struct SettingsTab: View { @Environment(NodeAppModel.self) private var appModel: NodeAppModel @Environment(VoiceWakeManager.self) private var voiceWake: VoiceWakeManager - @Environment(BridgeConnectionController.self) private var bridgeController: BridgeConnectionController + @Environment(GatewayConnectionController.self) private var gatewayController: GatewayConnectionController @Environment(\.dismiss) private var dismiss @AppStorage("node.displayName") private var displayName: String = "iOS Node" @AppStorage("node.instanceId") private var instanceId: String = UUID().uuidString @@ -26,17 +26,20 @@ struct SettingsTab: View { @AppStorage("location.enabledMode") private var locationEnabledModeRaw: String = ClawdbotLocationMode.off.rawValue @AppStorage("location.preciseEnabled") private var locationPreciseEnabled: Bool = true @AppStorage("screen.preventSleep") private var preventSleep: Bool = true - @AppStorage("bridge.preferredStableID") private var preferredBridgeStableID: String = "" - @AppStorage("bridge.lastDiscoveredStableID") private var lastDiscoveredBridgeStableID: String = "" - @AppStorage("bridge.manual.enabled") private var manualBridgeEnabled: Bool = false - @AppStorage("bridge.manual.host") private var manualBridgeHost: String = "" - @AppStorage("bridge.manual.port") private var manualBridgePort: Int = 18790 - @AppStorage("bridge.discovery.debugLogs") private var discoveryDebugLogsEnabled: Bool = false + @AppStorage("gateway.preferredStableID") private var preferredGatewayStableID: String = "" + @AppStorage("gateway.lastDiscoveredStableID") private var lastDiscoveredGatewayStableID: String = "" + @AppStorage("gateway.manual.enabled") private var manualGatewayEnabled: Bool = false + @AppStorage("gateway.manual.host") private var manualGatewayHost: String = "" + @AppStorage("gateway.manual.port") private var manualGatewayPort: Int = 18789 + @AppStorage("gateway.manual.tls") private var manualGatewayTLS: Bool = true + @AppStorage("gateway.discovery.debugLogs") private var discoveryDebugLogsEnabled: Bool = false @AppStorage("canvas.debugStatusEnabled") private var canvasDebugStatusEnabled: Bool = false @State private var connectStatus = ConnectStatusStore() - @State private var connectingBridgeID: String? + @State private var connectingGatewayID: String? @State private var localIPAddress: String? @State private var lastLocationModeRaw: String = ClawdbotLocationMode.off.rawValue + @State private var gatewayToken: String = "" + @State private var gatewayPassword: String = "" var body: some View { NavigationStack { @@ -61,12 +64,12 @@ struct SettingsTab: View { LabeledContent("Model", value: self.modelIdentifier()) } - Section("Bridge") { - LabeledContent("Discovery", value: self.bridgeController.discoveryStatusText) - LabeledContent("Status", value: self.appModel.bridgeStatusText) - if let serverName = self.appModel.bridgeServerName { + Section("Gateway") { + LabeledContent("Discovery", value: self.gatewayController.discoveryStatusText) + LabeledContent("Status", value: self.appModel.gatewayStatusText) + if let serverName = self.appModel.gatewayServerName { LabeledContent("Server", value: serverName) - if let addr = self.appModel.bridgeRemoteAddress { + if let addr = self.appModel.gatewayRemoteAddress { let parts = Self.parseHostPort(from: addr) let urlString = Self.httpURLString(host: parts?.host, port: parts?.port, fallback: addr) LabeledContent("Address") { @@ -96,12 +99,12 @@ struct SettingsTab: View { } Button("Disconnect", role: .destructive) { - self.appModel.disconnectBridge() + self.appModel.disconnectGateway() } - self.bridgeList(showing: .availableOnly) + self.gatewayList(showing: .availableOnly) } else { - self.bridgeList(showing: .all) + self.gatewayList(showing: .all) } if let text = self.connectStatus.text { @@ -111,19 +114,21 @@ struct SettingsTab: View { } DisclosureGroup("Advanced") { - Toggle("Use Manual Bridge", isOn: self.$manualBridgeEnabled) + Toggle("Use Manual Gateway", isOn: self.$manualGatewayEnabled) - TextField("Host", text: self.$manualBridgeHost) + TextField("Host", text: self.$manualGatewayHost) .textInputAutocapitalization(.never) .autocorrectionDisabled() - TextField("Port", value: self.$manualBridgePort, format: .number) + TextField("Port", value: self.$manualGatewayPort, format: .number) .keyboardType(.numberPad) + Toggle("Use TLS", isOn: self.$manualGatewayTLS) + Button { Task { await self.connectManual() } } label: { - if self.connectingBridgeID == "manual" { + if self.connectingGatewayID == "manual" { HStack(spacing: 8) { ProgressView() .progressViewStyle(.circular) @@ -133,26 +138,32 @@ struct SettingsTab: View { Text("Connect (Manual)") } } - .disabled(self.connectingBridgeID != nil || self.manualBridgeHost + .disabled(self.connectingGatewayID != nil || self.manualGatewayHost .trimmingCharacters(in: .whitespacesAndNewlines) - .isEmpty || self.manualBridgePort <= 0 || self.manualBridgePort > 65535) + .isEmpty || self.manualGatewayPort <= 0 || self.manualGatewayPort > 65535) Text( "Use this when mDNS/Bonjour discovery is blocked. " - + "The bridge runs on the gateway (default port 18790).") + + "The gateway WebSocket listens on port 18789 by default.") .font(.footnote) .foregroundStyle(.secondary) Toggle("Discovery Debug Logs", isOn: self.$discoveryDebugLogsEnabled) .onChange(of: self.discoveryDebugLogsEnabled) { _, newValue in - self.bridgeController.setDiscoveryDebugLoggingEnabled(newValue) + self.gatewayController.setDiscoveryDebugLoggingEnabled(newValue) } NavigationLink("Discovery Logs") { - BridgeDiscoveryDebugLogView() + GatewayDiscoveryDebugLogView() } Toggle("Debug Canvas Status", isOn: self.$canvasDebugStatusEnabled) + + TextField("Gateway Token", text: self.$gatewayToken) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + + SecureField("Gateway Password", text: self.$gatewayPassword) } } @@ -179,7 +190,7 @@ struct SettingsTab: View { Section("Camera") { Toggle("Allow Camera", isOn: self.$cameraEnabled) - Text("Allows the bridge to request photos or short video clips (foreground only).") + Text("Allows the gateway to request photos or short video clips (foreground only).") .font(.footnote) .foregroundStyle(.secondary) } @@ -221,13 +232,30 @@ struct SettingsTab: View { .onAppear { self.localIPAddress = Self.primaryIPv4Address() self.lastLocationModeRaw = self.locationEnabledModeRaw + let trimmedInstanceId = self.instanceId.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmedInstanceId.isEmpty { + self.gatewayToken = GatewaySettingsStore.loadGatewayToken(instanceId: trimmedInstanceId) ?? "" + self.gatewayPassword = GatewaySettingsStore.loadGatewayPassword(instanceId: trimmedInstanceId) ?? "" + } } - .onChange(of: self.preferredBridgeStableID) { _, newValue in + .onChange(of: self.preferredGatewayStableID) { _, newValue in let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return } - BridgeSettingsStore.savePreferredBridgeStableID(trimmed) + GatewaySettingsStore.savePreferredGatewayStableID(trimmed) } - .onChange(of: self.appModel.bridgeServerName) { _, _ in + .onChange(of: self.gatewayToken) { _, newValue in + let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) + let instanceId = self.instanceId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !instanceId.isEmpty else { return } + GatewaySettingsStore.saveGatewayToken(trimmed, instanceId: instanceId) + } + .onChange(of: self.gatewayPassword) { _, newValue in + let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) + let instanceId = self.instanceId.trimmingCharacters(in: .whitespacesAndNewlines) + guard !instanceId.isEmpty else { return } + GatewaySettingsStore.saveGatewayPassword(trimmed, instanceId: instanceId) + } + .onChange(of: self.appModel.gatewayServerName) { _, _ in self.connectStatus.text = nil } .onChange(of: self.locationEnabledModeRaw) { _, newValue in @@ -248,14 +276,14 @@ struct SettingsTab: View { } @ViewBuilder - private func bridgeList(showing: BridgeListMode) -> some View { - if self.bridgeController.bridges.isEmpty { - Text("No bridges found yet.") + private func gatewayList(showing: GatewayListMode) -> some View { + if self.gatewayController.gateways.isEmpty { + Text("No gateways found yet.") .foregroundStyle(.secondary) } else { - let connectedID = self.appModel.connectedBridgeID - let rows = self.bridgeController.bridges.filter { bridge in - let isConnected = bridge.stableID == connectedID + let connectedID = self.appModel.connectedGatewayID + let rows = self.gatewayController.gateways.filter { gateway in + let isConnected = gateway.stableID == connectedID switch showing { case .all: return true @@ -265,14 +293,14 @@ struct SettingsTab: View { } if rows.isEmpty, showing == .availableOnly { - Text("No other bridges found.") + Text("No other gateways found.") .foregroundStyle(.secondary) } else { - ForEach(rows) { bridge in + ForEach(rows) { gateway in HStack { VStack(alignment: .leading, spacing: 2) { - Text(bridge.name) - let detailLines = self.bridgeDetailLines(bridge) + Text(gateway.name) + let detailLines = self.gatewayDetailLines(gateway) ForEach(detailLines, id: \.self) { line in Text(line) .font(.footnote) @@ -282,31 +310,27 @@ struct SettingsTab: View { Spacer() Button { - Task { await self.connect(bridge) } + Task { await self.connect(gateway) } } label: { - if self.connectingBridgeID == bridge.id { + if self.connectingGatewayID == gateway.id { ProgressView() .progressViewStyle(.circular) } else { Text("Connect") } } - .disabled(self.connectingBridgeID != nil) + .disabled(self.connectingGatewayID != nil) } } } } } - private enum BridgeListMode: Equatable { + private enum GatewayListMode: Equatable { case all case availableOnly } - private func keychainAccount() -> String { - "bridge-token.\(self.instanceId)" - } - private func platformString() -> String { let v = ProcessInfo.processInfo.operatingSystemVersion return "iOS \(v.majorVersion).\(v.minorVersion).\(v.patchVersion)" @@ -341,228 +365,37 @@ struct SettingsTab: View { return trimmed.isEmpty ? "unknown" : trimmed } - private func currentCaps() -> [String] { - var caps = [ClawdbotCapability.canvas.rawValue, ClawdbotCapability.screen.rawValue] + private func connect(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) async { + self.connectingGatewayID = gateway.id + self.manualGatewayEnabled = false + self.preferredGatewayStableID = gateway.stableID + GatewaySettingsStore.savePreferredGatewayStableID(gateway.stableID) + self.lastDiscoveredGatewayStableID = gateway.stableID + GatewaySettingsStore.saveLastDiscoveredGatewayStableID(gateway.stableID) + defer { self.connectingGatewayID = nil } - let cameraEnabled = - UserDefaults.standard.object(forKey: "camera.enabled") == nil - ? true - : UserDefaults.standard.bool(forKey: "camera.enabled") - if cameraEnabled { caps.append(ClawdbotCapability.camera.rawValue) } - - let voiceWakeEnabled = UserDefaults.standard.bool(forKey: VoiceWakePreferences.enabledKey) - if voiceWakeEnabled { caps.append(ClawdbotCapability.voiceWake.rawValue) } - - return caps - } - - private func currentCommands() -> [String] { - var commands: [String] = [ - ClawdbotCanvasCommand.present.rawValue, - ClawdbotCanvasCommand.hide.rawValue, - ClawdbotCanvasCommand.navigate.rawValue, - ClawdbotCanvasCommand.evalJS.rawValue, - ClawdbotCanvasCommand.snapshot.rawValue, - ClawdbotCanvasA2UICommand.push.rawValue, - ClawdbotCanvasA2UICommand.pushJSONL.rawValue, - ClawdbotCanvasA2UICommand.reset.rawValue, - ClawdbotScreenCommand.record.rawValue, - ] - - let caps = Set(self.currentCaps()) - if caps.contains(ClawdbotCapability.camera.rawValue) { - commands.append(ClawdbotCameraCommand.list.rawValue) - commands.append(ClawdbotCameraCommand.snap.rawValue) - commands.append(ClawdbotCameraCommand.clip.rawValue) - } - - return commands - } - - private func connect(_ bridge: BridgeDiscoveryModel.DiscoveredBridge) async { - self.connectingBridgeID = bridge.id - self.manualBridgeEnabled = false - self.preferredBridgeStableID = bridge.stableID - BridgeSettingsStore.savePreferredBridgeStableID(bridge.stableID) - self.lastDiscoveredBridgeStableID = bridge.stableID - BridgeSettingsStore.saveLastDiscoveredBridgeStableID(bridge.stableID) - defer { self.connectingBridgeID = nil } - - do { - let statusStore = self.connectStatus - let existing = KeychainStore.loadString( - service: "com.clawdbot.bridge", - account: self.keychainAccount()) - let existingToken = (existing?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false) ? - existing : - nil - - let hello = BridgeHello( - nodeId: self.instanceId, - displayName: self.displayName, - token: existingToken, - platform: self.platformString(), - version: self.appVersion(), - deviceFamily: self.deviceFamily(), - modelIdentifier: self.modelIdentifier(), - caps: self.currentCaps(), - commands: self.currentCommands()) - let tlsParams = self.resolveDiscoveredTLSParams(bridge: bridge) - let token = try await BridgeClient().pairAndHello( - endpoint: bridge.endpoint, - hello: hello, - tls: tlsParams, - onStatus: { status in - Task { @MainActor in - statusStore.text = status - } - }) - - if !token.isEmpty, token != existingToken { - _ = KeychainStore.saveString( - token, - service: "com.clawdbot.bridge", - account: self.keychainAccount()) - } - - self.appModel.connectToBridge( - endpoint: bridge.endpoint, - bridgeStableID: bridge.stableID, - tls: tlsParams, - hello: BridgeHello( - nodeId: self.instanceId, - displayName: self.displayName, - token: token, - platform: self.platformString(), - version: self.appVersion(), - deviceFamily: self.deviceFamily(), - modelIdentifier: self.modelIdentifier(), - caps: self.currentCaps(), - commands: self.currentCommands())) - - } catch { - self.connectStatus.text = "Failed: \(error.localizedDescription)" - } + await self.gatewayController.connect(gateway) } private func connectManual() async { - let host = self.manualBridgeHost.trimmingCharacters(in: .whitespacesAndNewlines) + let host = self.manualGatewayHost.trimmingCharacters(in: .whitespacesAndNewlines) guard !host.isEmpty else { self.connectStatus.text = "Failed: host required" return } - guard self.manualBridgePort > 0, self.manualBridgePort <= 65535 else { - self.connectStatus.text = "Failed: invalid port" - return - } - guard let port = NWEndpoint.Port(rawValue: UInt16(self.manualBridgePort)) else { + guard self.manualGatewayPort > 0, self.manualGatewayPort <= 65535 else { self.connectStatus.text = "Failed: invalid port" return } - self.connectingBridgeID = "manual" - self.manualBridgeEnabled = true - defer { self.connectingBridgeID = nil } + self.connectingGatewayID = "manual" + self.manualGatewayEnabled = true + defer { self.connectingGatewayID = nil } - let endpoint: NWEndpoint = .hostPort(host: NWEndpoint.Host(host), port: port) - let stableID = BridgeEndpointID.stableID(endpoint) - let tlsParams = self.resolveManualTLSParams(stableID: stableID) - - do { - let statusStore = self.connectStatus - let existing = KeychainStore.loadString( - service: "com.clawdbot.bridge", - account: self.keychainAccount()) - let existingToken = (existing?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false) ? - existing : - nil - - let hello = BridgeHello( - nodeId: self.instanceId, - displayName: self.displayName, - token: existingToken, - platform: self.platformString(), - version: self.appVersion(), - deviceFamily: self.deviceFamily(), - modelIdentifier: self.modelIdentifier(), - caps: self.currentCaps(), - commands: self.currentCommands()) - let token = try await BridgeClient().pairAndHello( - endpoint: endpoint, - hello: hello, - tls: tlsParams, - onStatus: { status in - Task { @MainActor in - statusStore.text = status - } - }) - - if !token.isEmpty, token != existingToken { - _ = KeychainStore.saveString( - token, - service: "com.clawdbot.bridge", - account: self.keychainAccount()) - } - - self.appModel.connectToBridge( - endpoint: endpoint, - bridgeStableID: stableID, - tls: tlsParams, - hello: BridgeHello( - nodeId: self.instanceId, - displayName: self.displayName, - token: token, - platform: self.platformString(), - version: self.appVersion(), - deviceFamily: self.deviceFamily(), - modelIdentifier: self.modelIdentifier(), - caps: self.currentCaps(), - commands: self.currentCommands())) - - } catch { - self.connectStatus.text = "Failed: \(error.localizedDescription)" - } - } - - private func resolveDiscoveredTLSParams( - bridge: BridgeDiscoveryModel.DiscoveredBridge) -> BridgeTLSParams? - { - let stableID = bridge.stableID - let stored = BridgeTLSStore.loadFingerprint(stableID: stableID) - - if bridge.tlsEnabled || bridge.tlsFingerprintSha256 != nil { - return BridgeTLSParams( - required: true, - expectedFingerprint: bridge.tlsFingerprintSha256 ?? stored, - allowTOFU: stored == nil, - storeKey: stableID) - } - - if let stored { - return BridgeTLSParams( - required: true, - expectedFingerprint: stored, - allowTOFU: false, - storeKey: stableID) - } - - return nil - } - - private func resolveManualTLSParams(stableID: String) -> BridgeTLSParams? { - if let stored = BridgeTLSStore.loadFingerprint(stableID: stableID) { - return BridgeTLSParams( - required: true, - expectedFingerprint: stored, - allowTOFU: false, - storeKey: stableID) - } - - return BridgeTLSParams( - required: false, - expectedFingerprint: nil, - allowTOFU: true, - storeKey: stableID) + await self.gatewayController.connectManual( + host: host, + port: self.manualGatewayPort, + useTLS: self.manualGatewayTLS) } private static func primaryIPv4Address() -> String? { @@ -611,23 +444,21 @@ struct SettingsTab: View { SettingsNetworkingHelpers.httpURLString(host: host, port: port, fallback: fallback) } - private func bridgeDetailLines(_ bridge: BridgeDiscoveryModel.DiscoveredBridge) -> [String] { + private func gatewayDetailLines(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) -> [String] { var lines: [String] = [] - if let lanHost = bridge.lanHost { lines.append("LAN: \(lanHost)") } - if let tailnet = bridge.tailnetDns { lines.append("Tailnet: \(tailnet)") } + if let lanHost = gateway.lanHost { lines.append("LAN: \(lanHost)") } + if let tailnet = gateway.tailnetDns { lines.append("Tailnet: \(tailnet)") } - let gatewayPort = bridge.gatewayPort - let bridgePort = bridge.bridgePort - let canvasPort = bridge.canvasPort - if gatewayPort != nil || bridgePort != nil || canvasPort != nil { + let gatewayPort = gateway.gatewayPort + let canvasPort = gateway.canvasPort + if gatewayPort != nil || canvasPort != nil { let gw = gatewayPort.map(String.init) ?? "—" - let br = bridgePort.map(String.init) ?? "—" let canvas = canvasPort.map(String.init) ?? "—" - lines.append("Ports: gw \(gw) · bridge \(br) · canvas \(canvas)") + lines.append("Ports: gateway \(gw) · canvas \(canvas)") } if lines.isEmpty { - lines.append(bridge.debugID) + lines.append(gateway.debugID) } return lines diff --git a/apps/ios/Sources/Settings/VoiceWakeWordsSettingsView.swift b/apps/ios/Sources/Settings/VoiceWakeWordsSettingsView.swift index 405444534..5aef87b0c 100644 --- a/apps/ios/Sources/Settings/VoiceWakeWordsSettingsView.swift +++ b/apps/ios/Sources/Settings/VoiceWakeWordsSettingsView.swift @@ -1,8 +1,10 @@ import SwiftUI +import Combine struct VoiceWakeWordsSettingsView: View { @Environment(NodeAppModel.self) private var appModel @State private var triggerWords: [String] = VoiceWakePreferences.loadTriggerWords() + @FocusState private var focusedTriggerIndex: Int? @State private var syncTask: Task? var body: some View { @@ -12,6 +14,10 @@ struct VoiceWakeWordsSettingsView: View { TextField("Wake word", text: self.binding(for: index)) .textInputAutocapitalization(.never) .autocorrectionDisabled() + .focused(self.$focusedTriggerIndex, equals: index) + .onSubmit { + self.commitTriggerWords() + } } .onDelete(perform: self.removeWords) @@ -39,17 +45,18 @@ struct VoiceWakeWordsSettingsView: View { .onAppear { if self.triggerWords.isEmpty { self.triggerWords = VoiceWakePreferences.defaultTriggerWords + self.commitTriggerWords() } } - .onChange(of: self.triggerWords) { _, newValue in - // Keep local voice wake responsive even if bridge isn't connected yet. - VoiceWakePreferences.saveTriggerWords(newValue) - - let snapshot = VoiceWakePreferences.sanitizeTriggerWords(newValue) - self.syncTask?.cancel() - self.syncTask = Task { [snapshot, weak appModel = self.appModel] in - try? await Task.sleep(nanoseconds: 650_000_000) - await appModel?.setGlobalWakeWords(snapshot) + .onChange(of: self.focusedTriggerIndex) { oldValue, newValue in + guard oldValue != nil, oldValue != newValue else { return } + self.commitTriggerWords() + } + .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in + guard self.focusedTriggerIndex == nil else { return } + let updated = VoiceWakePreferences.loadTriggerWords() + if updated != self.triggerWords { + self.triggerWords = updated } } } @@ -63,6 +70,7 @@ struct VoiceWakeWordsSettingsView: View { if self.triggerWords.isEmpty { self.triggerWords = VoiceWakePreferences.defaultTriggerWords } + self.commitTriggerWords() } private func binding(for index: Int) -> Binding { @@ -76,4 +84,15 @@ struct VoiceWakeWordsSettingsView: View { self.triggerWords[index] = newValue }) } + + private func commitTriggerWords() { + VoiceWakePreferences.saveTriggerWords(self.triggerWords) + + let snapshot = VoiceWakePreferences.sanitizeTriggerWords(self.triggerWords) + self.syncTask?.cancel() + self.syncTask = Task { [snapshot, weak appModel = self.appModel] in + try? await Task.sleep(nanoseconds: 650_000_000) + await appModel?.setGlobalWakeWords(snapshot) + } + } } diff --git a/apps/ios/Sources/Status/StatusPill.swift b/apps/ios/Sources/Status/StatusPill.swift index 1e30ad16d..cd81c011b 100644 --- a/apps/ios/Sources/Status/StatusPill.swift +++ b/apps/ios/Sources/Status/StatusPill.swift @@ -3,7 +3,7 @@ import SwiftUI struct StatusPill: View { @Environment(\.scenePhase) private var scenePhase - enum BridgeState: Equatable { + enum GatewayState: Equatable { case connected case connecting case error @@ -34,7 +34,7 @@ struct StatusPill: View { var tint: Color? } - var bridge: BridgeState + var gateway: GatewayState var voiceWakeEnabled: Bool var activity: Activity? var brighten: Bool = false @@ -47,12 +47,12 @@ struct StatusPill: View { HStack(spacing: 10) { HStack(spacing: 8) { Circle() - .fill(self.bridge.color) + .fill(self.gateway.color) .frame(width: 9, height: 9) - .scaleEffect(self.bridge == .connecting ? (self.pulse ? 1.15 : 0.85) : 1.0) - .opacity(self.bridge == .connecting ? (self.pulse ? 1.0 : 0.6) : 1.0) + .scaleEffect(self.gateway == .connecting ? (self.pulse ? 1.15 : 0.85) : 1.0) + .opacity(self.gateway == .connecting ? (self.pulse ? 1.0 : 0.6) : 1.0) - Text(self.bridge.title) + Text(self.gateway.title) .font(.system(size: 13, weight: .semibold)) .foregroundStyle(.primary) } @@ -95,26 +95,26 @@ struct StatusPill: View { .buttonStyle(.plain) .accessibilityLabel("Status") .accessibilityValue(self.accessibilityValue) - .onAppear { self.updatePulse(for: self.bridge, scenePhase: self.scenePhase) } + .onAppear { self.updatePulse(for: self.gateway, scenePhase: self.scenePhase) } .onDisappear { self.pulse = false } - .onChange(of: self.bridge) { _, newValue in + .onChange(of: self.gateway) { _, newValue in self.updatePulse(for: newValue, scenePhase: self.scenePhase) } .onChange(of: self.scenePhase) { _, newValue in - self.updatePulse(for: self.bridge, scenePhase: newValue) + self.updatePulse(for: self.gateway, scenePhase: newValue) } .animation(.easeInOut(duration: 0.18), value: self.activity?.title) } private var accessibilityValue: String { if let activity { - return "\(self.bridge.title), \(activity.title)" + return "\(self.gateway.title), \(activity.title)" } - return "\(self.bridge.title), Voice Wake \(self.voiceWakeEnabled ? "enabled" : "disabled")" + return "\(self.gateway.title), Voice Wake \(self.voiceWakeEnabled ? "enabled" : "disabled")" } - private func updatePulse(for bridge: BridgeState, scenePhase: ScenePhase) { - guard bridge == .connecting, scenePhase == .active else { + private func updatePulse(for gateway: GatewayState, scenePhase: ScenePhase) { + guard gateway == .connecting, scenePhase == .active else { withAnimation(.easeOut(duration: 0.2)) { self.pulse = false } return } diff --git a/apps/ios/Sources/Voice/TalkModeManager.swift b/apps/ios/Sources/Voice/TalkModeManager.swift index 9c0e1303d..16ae245eb 100644 --- a/apps/ios/Sources/Voice/TalkModeManager.swift +++ b/apps/ios/Sources/Voice/TalkModeManager.swift @@ -1,5 +1,6 @@ import AVFAudio import ClawdbotKit +import ClawdbotProtocol import Foundation import Observation import OSLog @@ -42,15 +43,15 @@ final class TalkModeManager: NSObject { var pcmPlayer: PCMStreamingAudioPlaying = PCMStreamingAudioPlayer.shared var mp3Player: StreamingAudioPlaying = StreamingAudioPlayer.shared - private var bridge: BridgeSession? + private var gateway: GatewayNodeSession? private let silenceWindow: TimeInterval = 0.7 private var chatSubscribedSessionKeys = Set() private let logger = Logger(subsystem: "com.clawdbot", category: "TalkMode") - func attachBridge(_ bridge: BridgeSession) { - self.bridge = bridge + func attachGateway(_ gateway: GatewayNodeSession) { + self.gateway = gateway } func updateMainSessionKey(_ sessionKey: String?) { @@ -131,6 +132,12 @@ final class TalkModeManager: NSObject { } private func startRecognition() throws { + #if targetEnvironment(simulator) + throw NSError(domain: "TalkMode", code: 2, userInfo: [ + NSLocalizedDescriptionKey: "Talk mode is not supported on the iOS simulator", + ]) + #endif + self.stopRecognition() self.speechRecognizer = SFSpeechRecognizer() guard let recognizer = self.speechRecognizer else { @@ -145,6 +152,11 @@ final class TalkModeManager: NSObject { let input = self.audioEngine.inputNode let format = input.outputFormat(forBus: 0) + guard format.sampleRate > 0, format.channelCount > 0 else { + throw NSError(domain: "TalkMode", code: 3, userInfo: [ + NSLocalizedDescriptionKey: "Invalid audio input format", + ]) + } input.removeTap(onBus: 0) let tapBlock = Self.makeAudioTapAppendCallback(request: request) input.installTap(onBus: 0, bufferSize: 2048, format: format, block: tapBlock) @@ -232,9 +244,9 @@ final class TalkModeManager: NSObject { await self.reloadConfig() let prompt = self.buildPrompt(transcript: transcript) - guard let bridge else { - self.statusText = "Bridge not connected" - self.logger.warning("finalize: bridge not connected") + guard let gateway else { + self.statusText = "Gateway not connected" + self.logger.warning("finalize: gateway not connected") await self.start() return } @@ -245,9 +257,9 @@ final class TalkModeManager: NSObject { await self.subscribeChatIfNeeded(sessionKey: sessionKey) self.logger.info( "chat.send start sessionKey=\(sessionKey, privacy: .public) chars=\(prompt.count, privacy: .public)") - let runId = try await self.sendChat(prompt, bridge: bridge) + let runId = try await self.sendChat(prompt, gateway: gateway) self.logger.info("chat.send ok runId=\(runId, privacy: .public)") - let completion = await self.waitForChatCompletion(runId: runId, bridge: bridge, timeoutSeconds: 120) + let completion = await self.waitForChatCompletion(runId: runId, gateway: gateway, timeoutSeconds: 120) if completion == .timeout { self.logger.warning( "chat completion timeout runId=\(runId, privacy: .public); attempting history fallback") @@ -264,7 +276,7 @@ final class TalkModeManager: NSObject { } guard let assistantText = try await self.waitForAssistantText( - bridge: bridge, + gateway: gateway, since: startedAt, timeoutSeconds: completion == .final ? 12 : 25) else { @@ -286,31 +298,22 @@ final class TalkModeManager: NSObject { private func subscribeChatIfNeeded(sessionKey: String) async { let key = sessionKey.trimmingCharacters(in: .whitespacesAndNewlines) guard !key.isEmpty else { return } - guard let bridge else { return } + guard let gateway else { return } guard !self.chatSubscribedSessionKeys.contains(key) else { return } - do { - let payload = "{\"sessionKey\":\"\(key)\"}" - try await bridge.sendEvent(event: "chat.subscribe", payloadJSON: payload) - self.chatSubscribedSessionKeys.insert(key) - self.logger.info("chat.subscribe ok sessionKey=\(key, privacy: .public)") - } catch { - let err = error.localizedDescription - self.logger.warning("chat.subscribe failed key=\(key, privacy: .public) err=\(err, privacy: .public)") - } + let payload = "{\"sessionKey\":\"\(key)\"}" + await gateway.sendEvent(event: "chat.subscribe", payloadJSON: payload) + self.chatSubscribedSessionKeys.insert(key) + self.logger.info("chat.subscribe ok sessionKey=\(key, privacy: .public)") } private func unsubscribeAllChats() async { - guard let bridge else { return } + guard let gateway else { return } let keys = self.chatSubscribedSessionKeys self.chatSubscribedSessionKeys.removeAll() for key in keys { - do { - let payload = "{\"sessionKey\":\"\(key)\"}" - try await bridge.sendEvent(event: "chat.unsubscribe", payloadJSON: payload) - } catch { - // ignore - } + let payload = "{\"sessionKey\":\"\(key)\"}" + await gateway.sendEvent(event: "chat.unsubscribe", payloadJSON: payload) } } @@ -336,7 +339,7 @@ final class TalkModeManager: NSObject { } } - private func sendChat(_ message: String, bridge: BridgeSession) async throws -> String { + private func sendChat(_ message: String, gateway: GatewayNodeSession) async throws -> String { struct SendResponse: Decodable { let runId: String } let payload: [String: Any] = [ "sessionKey": self.mainSessionKey, @@ -352,26 +355,27 @@ final class TalkModeManager: NSObject { code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to encode chat payload"]) } - let res = try await bridge.request(method: "chat.send", paramsJSON: json, timeoutSeconds: 30) + let res = try await gateway.request(method: "chat.send", paramsJSON: json, timeoutSeconds: 30) let decoded = try JSONDecoder().decode(SendResponse.self, from: res) return decoded.runId } private func waitForChatCompletion( runId: String, - bridge: BridgeSession, + gateway: GatewayNodeSession, timeoutSeconds: Int = 120) async -> ChatCompletionState { - let stream = await bridge.subscribeServerEvents(bufferingNewest: 200) + let stream = await gateway.subscribeServerEvents(bufferingNewest: 200) return await withTaskGroup(of: ChatCompletionState.self) { group in group.addTask { [runId] in for await evt in stream { if Task.isCancelled { return .timeout } - guard evt.event == "chat", let payload = evt.payloadJSON else { continue } - guard let data = payload.data(using: .utf8) else { continue } - guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { continue } - if (json["runId"] as? String) != runId { continue } - if let state = json["state"] as? String { + guard evt.event == "chat", let payload = evt.payload else { continue } + guard let chatEvent = try? GatewayPayloadDecoding.decode(payload, as: ChatEvent.self) else { + continue + } + guard chatEvent.runid == runId else { continue } + if let state = chatEvent.state.value as? String { switch state { case "final": return .final case "aborted": return .aborted @@ -393,13 +397,13 @@ final class TalkModeManager: NSObject { } private func waitForAssistantText( - bridge: BridgeSession, + gateway: GatewayNodeSession, since: Double, timeoutSeconds: Int) async throws -> String? { let deadline = Date().addingTimeInterval(TimeInterval(timeoutSeconds)) while Date() < deadline { - if let text = try await self.fetchLatestAssistantText(bridge: bridge, since: since) { + if let text = try await self.fetchLatestAssistantText(gateway: gateway, since: since) { return text } try? await Task.sleep(nanoseconds: 300_000_000) @@ -407,8 +411,8 @@ final class TalkModeManager: NSObject { return nil } - private func fetchLatestAssistantText(bridge: BridgeSession, since: Double? = nil) async throws -> String? { - let res = try await bridge.request( + private func fetchLatestAssistantText(gateway: GatewayNodeSession, since: Double? = nil) async throws -> String? { + let res = try await gateway.request( method: "chat.history", paramsJSON: "{\"sessionKey\":\"\(self.mainSessionKey)\"}", timeoutSeconds: 15) @@ -649,9 +653,9 @@ final class TalkModeManager: NSObject { } private func reloadConfig() async { - guard let bridge else { return } + guard let gateway else { return } do { - let res = try await bridge.request(method: "config.get", paramsJSON: "{}", timeoutSeconds: 8) + let res = try await gateway.request(method: "config.get", paramsJSON: "{}", timeoutSeconds: 8) guard let json = try JSONSerialization.jsonObject(with: res) as? [String: Any] else { return } guard let config = json["config"] as? [String: Any] else { return } let talk = config["talk"] as? [String: Any] diff --git a/apps/ios/Sources/Voice/VoiceWakePreferences.swift b/apps/ios/Sources/Voice/VoiceWakePreferences.swift index 96f46518e..4c75c22a6 100644 --- a/apps/ios/Sources/Voice/VoiceWakePreferences.swift +++ b/apps/ios/Sources/Voice/VoiceWakePreferences.swift @@ -6,6 +6,8 @@ enum VoiceWakePreferences { // Keep defaults aligned with the mac app. static let defaultTriggerWords: [String] = ["clawd", "claude"] + static let maxWords = 32 + static let maxWordLength = 64 static func decodeGatewayTriggers(from payloadJSON: String) -> [String]? { guard let data = payloadJSON.data(using: .utf8) else { return nil } @@ -30,6 +32,8 @@ enum VoiceWakePreferences { let cleaned = words .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } + .prefix(Self.maxWords) + .map { String($0.prefix(Self.maxWordLength)) } return cleaned.isEmpty ? Self.defaultTriggerWords : cleaned } diff --git a/apps/ios/SwiftSources.input.xcfilelist b/apps/ios/SwiftSources.input.xcfilelist index 0598b0e4e..70d0f39d6 100644 --- a/apps/ios/SwiftSources.input.xcfilelist +++ b/apps/ios/SwiftSources.input.xcfilelist @@ -1,15 +1,13 @@ -Sources/Bridge/BridgeClient.swift -Sources/Bridge/BridgeConnectionController.swift -Sources/Bridge/BridgeDiscoveryDebugLogView.swift -Sources/Bridge/BridgeDiscoveryModel.swift -Sources/Bridge/BridgeEndpointID.swift -Sources/Bridge/BridgeSession.swift -Sources/Bridge/BridgeSettingsStore.swift -Sources/Bridge/KeychainStore.swift +Sources/Gateway/GatewayConnectionController.swift +Sources/Gateway/GatewayDiscoveryDebugLogView.swift +Sources/Gateway/GatewayDiscoveryModel.swift +Sources/Gateway/GatewaySettingsStore.swift +Sources/Gateway/KeychainStore.swift Sources/Camera/CameraController.swift Sources/Chat/ChatSheet.swift -Sources/Chat/IOSBridgeChatTransport.swift +Sources/Chat/IOSGatewayChatTransport.swift Sources/ClawdbotApp.swift +Sources/Location/LocationService.swift Sources/Model/NodeAppModel.swift Sources/RootCanvas.swift Sources/RootTabs.swift @@ -17,6 +15,7 @@ Sources/Screen/ScreenController.swift Sources/Screen/ScreenRecordService.swift Sources/Screen/ScreenTab.swift Sources/Screen/ScreenWebView.swift +Sources/SessionKey.swift Sources/Settings/SettingsNetworkingHelpers.swift Sources/Settings/SettingsTab.swift Sources/Settings/VoiceWakeWordsSettingsView.swift diff --git a/apps/ios/Tests/BridgeClientTests.swift b/apps/ios/Tests/BridgeClientTests.swift deleted file mode 100644 index 21869b1cf..000000000 --- a/apps/ios/Tests/BridgeClientTests.swift +++ /dev/null @@ -1,196 +0,0 @@ -import ClawdbotKit -import Foundation -import Network -import Testing -@testable import Clawdbot - -@Suite struct BridgeClientTests { - private final class LineServer: @unchecked Sendable { - private let queue = DispatchQueue(label: "com.clawdbot.tests.bridge-client-server") - private let listener: NWListener - private var connection: NWConnection? - private var buffer = Data() - - init() throws { - self.listener = try NWListener(using: .tcp, on: .any) - } - - func start() async throws -> NWEndpoint.Port { - try await withCheckedThrowingContinuation(isolation: nil) { cont in - self.listener.stateUpdateHandler = { state in - switch state { - case .ready: - if let port = self.listener.port { - cont.resume(returning: port) - } else { - cont.resume( - throwing: NSError(domain: "LineServer", code: 1, userInfo: [ - NSLocalizedDescriptionKey: "listener missing port", - ])) - } - case let .failed(err): - cont.resume(throwing: err) - default: - break - } - } - - self.listener.newConnectionHandler = { [weak self] conn in - guard let self else { return } - self.connection = conn - conn.start(queue: self.queue) - } - - self.listener.start(queue: self.queue) - } - } - - func stop() { - self.connection?.cancel() - self.connection = nil - self.listener.cancel() - } - - func waitForConnection(timeoutMs: Int = 2000) async throws -> NWConnection { - let deadline = Date().addingTimeInterval(Double(timeoutMs) / 1000.0) - while Date() < deadline { - if let connection = self.connection { return connection } - try await Task.sleep(nanoseconds: 10_000_000) - } - throw NSError(domain: "LineServer", code: 2, userInfo: [ - NSLocalizedDescriptionKey: "timed out waiting for connection", - ]) - } - - func receiveLine(timeoutMs: Int = 2000) async throws -> Data? { - let connection = try await self.waitForConnection(timeoutMs: timeoutMs) - let deadline = Date().addingTimeInterval(Double(timeoutMs) / 1000.0) - - while Date() < deadline { - if let idx = self.buffer.firstIndex(of: 0x0A) { - let line = self.buffer.prefix(upTo: idx) - self.buffer.removeSubrange(...idx) - return Data(line) - } - - let chunk = try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation< - Data, - Error, - >) in - connection - .receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { data, _, isComplete, error in - if let error { - cont.resume(throwing: error) - return - } - if isComplete { - cont.resume(returning: Data()) - return - } - cont.resume(returning: data ?? Data()) - } - } - - if chunk.isEmpty { return nil } - self.buffer.append(chunk) - } - - throw NSError(domain: "LineServer", code: 3, userInfo: [ - NSLocalizedDescriptionKey: "timed out waiting for line", - ]) - } - - func sendLine(_ line: String) async throws { - let connection = try await self.waitForConnection() - var data = Data(line.utf8) - data.append(0x0A) - try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation) in - connection.send(content: data, completion: .contentProcessed { err in - if let err { cont.resume(throwing: err) } else { cont.resume(returning: ()) } - }) - } - } - } - - @Test func helloOkReturnsExistingToken() async throws { - let server = try LineServer() - let port = try await server.start() - defer { server.stop() } - - let serverTask = Task { - let line = try await server.receiveLine() - #expect(line != nil) - _ = try JSONDecoder().decode(BridgeHello.self, from: line ?? Data()) - try await server.sendLine(#"{"type":"hello-ok","serverName":"Test Gateway"}"#) - } - defer { serverTask.cancel() } - - let client = BridgeClient() - let token = try await client.pairAndHello( - endpoint: .hostPort(host: NWEndpoint.Host("127.0.0.1"), port: port), - hello: BridgeHello( - nodeId: "ios-node", - displayName: "iOS", - token: "existing-token", - platform: "ios", - version: "1"), - onStatus: nil) - - #expect(token == "existing-token") - _ = try await serverTask.value - } - - @Test func notPairedTriggersPairRequestAndReturnsToken() async throws { - let server = try LineServer() - let port = try await server.start() - defer { server.stop() } - - let serverTask = Task { - let helloLine = try await server.receiveLine() - #expect(helloLine != nil) - _ = try JSONDecoder().decode(BridgeHello.self, from: helloLine ?? Data()) - try await server.sendLine(#"{"type":"error","code":"NOT_PAIRED","message":"not paired"}"#) - - let pairLine = try await server.receiveLine() - #expect(pairLine != nil) - _ = try JSONDecoder().decode(BridgePairRequest.self, from: pairLine ?? Data()) - try await server.sendLine(#"{"type":"pair-ok","token":"paired-token"}"#) - } - defer { serverTask.cancel() } - - let client = BridgeClient() - let token = try await client.pairAndHello( - endpoint: .hostPort(host: NWEndpoint.Host("127.0.0.1"), port: port), - hello: BridgeHello(nodeId: "ios-node", displayName: "iOS", token: nil, platform: "ios", version: "1"), - onStatus: nil) - - #expect(token == "paired-token") - _ = try await serverTask.value - } - - @Test func unexpectedErrorIsSurfaced() async { - do { - let server = try LineServer() - let port = try await server.start() - defer { server.stop() } - - let serverTask = Task { - let helloLine = try await server.receiveLine() - #expect(helloLine != nil) - _ = try JSONDecoder().decode(BridgeHello.self, from: helloLine ?? Data()) - try await server.sendLine(#"{"type":"error","code":"NOPE","message":"nope"}"#) - } - defer { serverTask.cancel() } - - let client = BridgeClient() - _ = try await client.pairAndHello( - endpoint: .hostPort(host: NWEndpoint.Host("127.0.0.1"), port: port), - hello: BridgeHello(nodeId: "ios-node", displayName: "iOS", token: nil, platform: "ios", version: "1"), - onStatus: nil) - - Issue.record("Expected pairAndHello to throw for unexpected error code") - } catch { - #expect(error.localizedDescription.contains("NOPE")) - } - } -} diff --git a/apps/ios/Tests/BridgeConnectionControllerTests.swift b/apps/ios/Tests/BridgeConnectionControllerTests.swift deleted file mode 100644 index df6198623..000000000 --- a/apps/ios/Tests/BridgeConnectionControllerTests.swift +++ /dev/null @@ -1,347 +0,0 @@ -import ClawdbotKit -import Foundation -import Network -import Testing -import UIKit -@testable import Clawdbot - -private struct KeychainEntry: Hashable { - let service: String - let account: String -} - -private let bridgeService = "com.clawdbot.bridge" -private let nodeService = "com.clawdbot.node" -private let instanceIdEntry = KeychainEntry(service: nodeService, account: "instanceId") -private let preferredBridgeEntry = KeychainEntry(service: bridgeService, account: "preferredStableID") -private let lastBridgeEntry = KeychainEntry(service: bridgeService, account: "lastDiscoveredStableID") - -private actor MockBridgePairingClient: BridgePairingClient { - private(set) var lastToken: String? - private let resultToken: String - - init(resultToken: String) { - self.resultToken = resultToken - } - - func pairAndHello( - endpoint: NWEndpoint, - hello: BridgeHello, - tls: BridgeTLSParams?, - onStatus: (@Sendable (String) -> Void)?) async throws -> String - { - self.lastToken = hello.token - onStatus?("Testing…") - return self.resultToken - } -} - -private func withUserDefaults(_ updates: [String: Any?], _ body: () throws -> T) rethrows -> T { - let defaults = UserDefaults.standard - var snapshot: [String: Any?] = [:] - for key in updates.keys { - snapshot[key] = defaults.object(forKey: key) - } - for (key, value) in updates { - if let value { - defaults.set(value, forKey: key) - } else { - defaults.removeObject(forKey: key) - } - } - defer { - for (key, value) in snapshot { - if let value { - defaults.set(value, forKey: key) - } else { - defaults.removeObject(forKey: key) - } - } - } - return try body() -} - -@MainActor -private func withUserDefaults( - _ updates: [String: Any?], - _ body: () async throws -> T) async rethrows -> T -{ - let defaults = UserDefaults.standard - var snapshot: [String: Any?] = [:] - for key in updates.keys { - snapshot[key] = defaults.object(forKey: key) - } - for (key, value) in updates { - if let value { - defaults.set(value, forKey: key) - } else { - defaults.removeObject(forKey: key) - } - } - defer { - for (key, value) in snapshot { - if let value { - defaults.set(value, forKey: key) - } else { - defaults.removeObject(forKey: key) - } - } - } - return try await body() -} - -private func withKeychainValues(_ updates: [KeychainEntry: String?], _ body: () throws -> T) rethrows -> T { - var snapshot: [KeychainEntry: String?] = [:] - for entry in updates.keys { - snapshot[entry] = KeychainStore.loadString(service: entry.service, account: entry.account) - } - for (entry, value) in updates { - if let value { - _ = KeychainStore.saveString(value, service: entry.service, account: entry.account) - } else { - _ = KeychainStore.delete(service: entry.service, account: entry.account) - } - } - defer { - for (entry, value) in snapshot { - if let value { - _ = KeychainStore.saveString(value, service: entry.service, account: entry.account) - } else { - _ = KeychainStore.delete(service: entry.service, account: entry.account) - } - } - } - return try body() -} - -@MainActor -private func withKeychainValues( - _ updates: [KeychainEntry: String?], - _ body: () async throws -> T) async rethrows -> T -{ - var snapshot: [KeychainEntry: String?] = [:] - for entry in updates.keys { - snapshot[entry] = KeychainStore.loadString(service: entry.service, account: entry.account) - } - for (entry, value) in updates { - if let value { - _ = KeychainStore.saveString(value, service: entry.service, account: entry.account) - } else { - _ = KeychainStore.delete(service: entry.service, account: entry.account) - } - } - defer { - for (entry, value) in snapshot { - if let value { - _ = KeychainStore.saveString(value, service: entry.service, account: entry.account) - } else { - _ = KeychainStore.delete(service: entry.service, account: entry.account) - } - } - } - return try await body() -} - -@Suite(.serialized) struct BridgeConnectionControllerTests { - @Test @MainActor func resolvedDisplayNameSetsDefaultWhenMissing() { - let defaults = UserDefaults.standard - let displayKey = "node.displayName" - - withKeychainValues([instanceIdEntry: nil, preferredBridgeEntry: nil, lastBridgeEntry: nil]) { - withUserDefaults([displayKey: nil, "node.instanceId": "ios-test"]) { - let appModel = NodeAppModel() - let controller = BridgeConnectionController(appModel: appModel, startDiscovery: false) - - let resolved = controller._test_resolvedDisplayName(defaults: defaults) - #expect(!resolved.isEmpty) - #expect(defaults.string(forKey: displayKey) == resolved) - } - } - } - - @Test @MainActor func resolvedDisplayNamePreservesCustomValue() { - let defaults = UserDefaults.standard - let displayKey = "node.displayName" - - withKeychainValues([instanceIdEntry: nil, preferredBridgeEntry: nil, lastBridgeEntry: nil]) { - withUserDefaults([displayKey: "My iOS Node", "node.instanceId": "ios-test"]) { - let appModel = NodeAppModel() - let controller = BridgeConnectionController(appModel: appModel, startDiscovery: false) - - let resolved = controller._test_resolvedDisplayName(defaults: defaults) - #expect(resolved == "My iOS Node") - #expect(defaults.string(forKey: displayKey) == "My iOS Node") - } - } - } - - @Test @MainActor func makeHelloBuildsCapsAndCommands() { - let voiceWakeKey = VoiceWakePreferences.enabledKey - - withKeychainValues([instanceIdEntry: nil, preferredBridgeEntry: nil, lastBridgeEntry: nil]) { - withUserDefaults([ - "node.instanceId": "ios-test", - "node.displayName": "Test Node", - "camera.enabled": false, - voiceWakeKey: true, - ]) { - let appModel = NodeAppModel() - let controller = BridgeConnectionController(appModel: appModel, startDiscovery: false) - let hello = controller._test_makeHello(token: "token-123") - - #expect(hello.nodeId == "ios-test") - #expect(hello.displayName == "Test Node") - #expect(hello.token == "token-123") - - let caps = Set(hello.caps ?? []) - #expect(caps.contains(ClawdbotCapability.canvas.rawValue)) - #expect(caps.contains(ClawdbotCapability.screen.rawValue)) - #expect(caps.contains(ClawdbotCapability.voiceWake.rawValue)) - #expect(!caps.contains(ClawdbotCapability.camera.rawValue)) - - let commands = Set(hello.commands ?? []) - #expect(commands.contains(ClawdbotCanvasCommand.present.rawValue)) - #expect(commands.contains(ClawdbotScreenCommand.record.rawValue)) - #expect(!commands.contains(ClawdbotCameraCommand.snap.rawValue)) - - #expect(!(hello.platform ?? "").isEmpty) - #expect(!(hello.deviceFamily ?? "").isEmpty) - #expect(!(hello.modelIdentifier ?? "").isEmpty) - #expect(!(hello.version ?? "").isEmpty) - } - } - } - - @Test @MainActor func makeHelloIncludesCameraCommandsWhenEnabled() { - withKeychainValues([instanceIdEntry: nil, preferredBridgeEntry: nil, lastBridgeEntry: nil]) { - withUserDefaults([ - "node.instanceId": "ios-test", - "node.displayName": "Test Node", - "camera.enabled": true, - VoiceWakePreferences.enabledKey: false, - ]) { - let appModel = NodeAppModel() - let controller = BridgeConnectionController(appModel: appModel, startDiscovery: false) - let hello = controller._test_makeHello(token: "token-456") - - let caps = Set(hello.caps ?? []) - #expect(caps.contains(ClawdbotCapability.camera.rawValue)) - - let commands = Set(hello.commands ?? []) - #expect(commands.contains(ClawdbotCameraCommand.snap.rawValue)) - #expect(commands.contains(ClawdbotCameraCommand.clip.rawValue)) - } - } - } - - @Test @MainActor func autoConnectRefreshesTokenOnUnauthorized() async { - let bridge = BridgeDiscoveryModel.DiscoveredBridge( - name: "Gateway", - endpoint: .hostPort(host: NWEndpoint.Host("127.0.0.1"), port: 18790), - stableID: "bridge-1", - debugID: "bridge-debug", - lanHost: "Mac.local", - tailnetDns: nil, - gatewayPort: 18789, - bridgePort: 18790, - canvasPort: 18793, - tlsEnabled: false, - tlsFingerprintSha256: nil, - cliPath: nil) - let mock = MockBridgePairingClient(resultToken: "new-token") - let account = "bridge-token.ios-test" - - await withKeychainValues([ - instanceIdEntry: nil, - preferredBridgeEntry: nil, - lastBridgeEntry: nil, - KeychainEntry(service: bridgeService, account: account): "old-token", - ]) { - await withUserDefaults([ - "node.instanceId": "ios-test", - "bridge.lastDiscoveredStableID": "bridge-1", - "bridge.manual.enabled": false, - ]) { - let appModel = NodeAppModel() - let controller = BridgeConnectionController( - appModel: appModel, - startDiscovery: false, - bridgeClientFactory: { mock }) - controller._test_setBridges([bridge]) - controller._test_triggerAutoConnect() - - for _ in 0..<20 { - if appModel.connectedBridgeID == bridge.stableID { break } - try? await Task.sleep(nanoseconds: 50_000_000) - } - - #expect(appModel.connectedBridgeID == bridge.stableID) - let stored = KeychainStore.loadString(service: bridgeService, account: account) - #expect(stored == "new-token") - let lastToken = await mock.lastToken - #expect(lastToken == "old-token") - } - } - } - - @Test @MainActor func autoConnectPrefersPreferredBridgeOverLastDiscovered() async { - let bridgeA = BridgeDiscoveryModel.DiscoveredBridge( - name: "Gateway A", - endpoint: .hostPort(host: NWEndpoint.Host("127.0.0.1"), port: 18790), - stableID: "bridge-1", - debugID: "bridge-a", - lanHost: "MacA.local", - tailnetDns: nil, - gatewayPort: 18789, - bridgePort: 18790, - canvasPort: 18793, - tlsEnabled: false, - tlsFingerprintSha256: nil, - cliPath: nil) - let bridgeB = BridgeDiscoveryModel.DiscoveredBridge( - name: "Gateway B", - endpoint: .hostPort(host: NWEndpoint.Host("127.0.0.1"), port: 28790), - stableID: "bridge-2", - debugID: "bridge-b", - lanHost: "MacB.local", - tailnetDns: nil, - gatewayPort: 28789, - bridgePort: 28790, - canvasPort: 28793, - tlsEnabled: false, - tlsFingerprintSha256: nil, - cliPath: nil) - - let mock = MockBridgePairingClient(resultToken: "token-ok") - let account = "bridge-token.ios-test" - - await withKeychainValues([ - instanceIdEntry: nil, - preferredBridgeEntry: nil, - lastBridgeEntry: nil, - KeychainEntry(service: bridgeService, account: account): "old-token", - ]) { - await withUserDefaults([ - "node.instanceId": "ios-test", - "bridge.preferredStableID": "bridge-2", - "bridge.lastDiscoveredStableID": "bridge-1", - "bridge.manual.enabled": false, - ]) { - let appModel = NodeAppModel() - let controller = BridgeConnectionController( - appModel: appModel, - startDiscovery: false, - bridgeClientFactory: { mock }) - controller._test_setBridges([bridgeA, bridgeB]) - controller._test_triggerAutoConnect() - - for _ in 0..<20 { - if appModel.connectedBridgeID == bridgeB.stableID { break } - try? await Task.sleep(nanoseconds: 50_000_000) - } - - #expect(appModel.connectedBridgeID == bridgeB.stableID) - } - } - } -} diff --git a/apps/ios/Tests/BridgeSessionTests.swift b/apps/ios/Tests/BridgeSessionTests.swift deleted file mode 100644 index 470441251..000000000 --- a/apps/ios/Tests/BridgeSessionTests.swift +++ /dev/null @@ -1,48 +0,0 @@ -import Foundation -import Testing -@testable import Clawdbot - -@Suite struct BridgeSessionTests { - @Test func initialStateIsIdle() async { - let session = BridgeSession() - #expect(await session.state == .idle) - } - - @Test func requestFailsWhenNotConnected() async { - let session = BridgeSession() - - do { - _ = try await session.request(method: "health", paramsJSON: nil, timeoutSeconds: 1) - Issue.record("Expected request to throw when not connected") - } catch let error as NSError { - #expect(error.domain == "Bridge") - #expect(error.code == 11) - } - } - - @Test func sendEventFailsWhenNotConnected() async { - let session = BridgeSession() - - do { - try await session.sendEvent(event: "tick", payloadJSON: nil) - Issue.record("Expected sendEvent to throw when not connected") - } catch let error as NSError { - #expect(error.domain == "Bridge") - #expect(error.code == 10) - } - } - - @Test func disconnectFinishesServerEventStreams() async throws { - let session = BridgeSession() - let stream = await session.subscribeServerEvents(bufferingNewest: 1) - - let consumer = Task { @Sendable in - for await _ in stream {} - } - - await session.disconnect() - - _ = await consumer.result - #expect(await session.state == .idle) - } -} diff --git a/apps/ios/Tests/GatewayConnectionControllerTests.swift b/apps/ios/Tests/GatewayConnectionControllerTests.swift new file mode 100644 index 000000000..3e892a7b2 --- /dev/null +++ b/apps/ios/Tests/GatewayConnectionControllerTests.swift @@ -0,0 +1,79 @@ +import ClawdbotKit +import Foundation +import Testing +import UIKit +@testable import Clawdbot + +private func withUserDefaults(_ updates: [String: Any?], _ body: () throws -> T) rethrows -> T { + let defaults = UserDefaults.standard + var snapshot: [String: Any?] = [:] + for key in updates.keys { + snapshot[key] = defaults.object(forKey: key) + } + for (key, value) in updates { + if let value { + defaults.set(value, forKey: key) + } else { + defaults.removeObject(forKey: key) + } + } + defer { + for (key, value) in snapshot { + if let value { + defaults.set(value, forKey: key) + } else { + defaults.removeObject(forKey: key) + } + } + } + return try body() +} + +@Suite(.serialized) struct GatewayConnectionControllerTests { + @Test @MainActor func resolvedDisplayNameSetsDefaultWhenMissing() { + let defaults = UserDefaults.standard + let displayKey = "node.displayName" + + withUserDefaults([displayKey: nil, "node.instanceId": "ios-test"]) { + let appModel = NodeAppModel() + let controller = GatewayConnectionController(appModel: appModel, startDiscovery: false) + + let resolved = controller._test_resolvedDisplayName(defaults: defaults) + #expect(!resolved.isEmpty) + #expect(defaults.string(forKey: displayKey) == resolved) + } + } + + @Test @MainActor func currentCapsReflectToggles() { + withUserDefaults([ + "node.instanceId": "ios-test", + "node.displayName": "Test Node", + "camera.enabled": true, + "location.enabledMode": ClawdbotLocationMode.always.rawValue, + VoiceWakePreferences.enabledKey: true, + ]) { + let appModel = NodeAppModel() + let controller = GatewayConnectionController(appModel: appModel, startDiscovery: false) + let caps = Set(controller._test_currentCaps()) + + #expect(caps.contains(ClawdbotCapability.canvas.rawValue)) + #expect(caps.contains(ClawdbotCapability.screen.rawValue)) + #expect(caps.contains(ClawdbotCapability.camera.rawValue)) + #expect(caps.contains(ClawdbotCapability.location.rawValue)) + #expect(caps.contains(ClawdbotCapability.voiceWake.rawValue)) + } + } + + @Test @MainActor func currentCommandsIncludeLocationWhenEnabled() { + withUserDefaults([ + "node.instanceId": "ios-test", + "location.enabledMode": ClawdbotLocationMode.whileUsing.rawValue, + ]) { + let appModel = NodeAppModel() + let controller = GatewayConnectionController(appModel: appModel, startDiscovery: false) + let commands = Set(controller._test_currentCommands()) + + #expect(commands.contains(ClawdbotLocationCommand.get.rawValue)) + } + } +} diff --git a/apps/ios/Tests/BridgeDiscoveryModelTests.swift b/apps/ios/Tests/GatewayDiscoveryModelTests.swift similarity index 77% rename from apps/ios/Tests/BridgeDiscoveryModelTests.swift rename to apps/ios/Tests/GatewayDiscoveryModelTests.swift index 0b9f8793a..2298647c8 100644 --- a/apps/ios/Tests/BridgeDiscoveryModelTests.swift +++ b/apps/ios/Tests/GatewayDiscoveryModelTests.swift @@ -1,9 +1,9 @@ import Testing @testable import Clawdbot -@Suite(.serialized) struct BridgeDiscoveryModelTests { +@Suite(.serialized) struct GatewayDiscoveryModelTests { @Test @MainActor func debugLoggingCapturesLifecycleAndResets() { - let model = BridgeDiscoveryModel() + let model = GatewayDiscoveryModel() #expect(model.debugLog.isEmpty) #expect(model.statusText == "Idle") @@ -13,7 +13,7 @@ import Testing model.stop() #expect(model.statusText == "Stopped") - #expect(model.bridges.isEmpty) + #expect(model.gateways.isEmpty) #expect(model.debugLog.count >= 3) model.setDebugLoggingEnabled(false) diff --git a/apps/ios/Tests/BridgeEndpointIDTests.swift b/apps/ios/Tests/GatewayEndpointIDTests.swift similarity index 60% rename from apps/ios/Tests/BridgeEndpointIDTests.swift rename to apps/ios/Tests/GatewayEndpointIDTests.swift index b1fe95cf8..37dbba5b3 100644 --- a/apps/ios/Tests/BridgeEndpointIDTests.swift +++ b/apps/ios/Tests/GatewayEndpointIDTests.swift @@ -3,30 +3,30 @@ import Network import Testing @testable import Clawdbot -@Suite struct BridgeEndpointIDTests { +@Suite struct GatewayEndpointIDTests { @Test func stableIDForServiceDecodesAndNormalizesName() { let endpoint = NWEndpoint.service( - name: "Clawdbot\\032Bridge \\032 Node\n", - type: "_clawdbot-bridge._tcp", + name: "Clawdbot\\032Gateway \\032 Node\n", + type: "_clawdbot-gw._tcp", domain: "local.", interface: nil) - #expect(BridgeEndpointID.stableID(endpoint) == "_clawdbot-bridge._tcp|local.|Clawdbot Bridge Node") + #expect(GatewayEndpointID.stableID(endpoint) == "_clawdbot-gw._tcp|local.|Clawdbot Gateway Node") } @Test func stableIDForNonServiceUsesEndpointDescription() { let endpoint = NWEndpoint.hostPort(host: NWEndpoint.Host("127.0.0.1"), port: 4242) - #expect(BridgeEndpointID.stableID(endpoint) == String(describing: endpoint)) + #expect(GatewayEndpointID.stableID(endpoint) == String(describing: endpoint)) } @Test func prettyDescriptionDecodesBonjourEscapes() { let endpoint = NWEndpoint.service( - name: "Clawdbot\\032Bridge", - type: "_clawdbot-bridge._tcp", + name: "Clawdbot\\032Gateway", + type: "_clawdbot-gw._tcp", domain: "local.", interface: nil) - let pretty = BridgeEndpointID.prettyDescription(endpoint) + let pretty = GatewayEndpointID.prettyDescription(endpoint) #expect(pretty == BonjourEscapes.decode(String(describing: endpoint))) #expect(!pretty.localizedCaseInsensitiveContains("\\032")) } diff --git a/apps/ios/Tests/BridgeSettingsStoreTests.swift b/apps/ios/Tests/GatewaySettingsStoreTests.swift similarity index 64% rename from apps/ios/Tests/BridgeSettingsStoreTests.swift rename to apps/ios/Tests/GatewaySettingsStoreTests.swift index d2840c11f..a93072ef6 100644 --- a/apps/ios/Tests/BridgeSettingsStoreTests.swift +++ b/apps/ios/Tests/GatewaySettingsStoreTests.swift @@ -7,11 +7,11 @@ private struct KeychainEntry: Hashable { let account: String } -private let bridgeService = "com.clawdbot.bridge" +private let gatewayService = "com.clawdbot.gateway" private let nodeService = "com.clawdbot.node" private let instanceIdEntry = KeychainEntry(service: nodeService, account: "instanceId") -private let preferredBridgeEntry = KeychainEntry(service: bridgeService, account: "preferredStableID") -private let lastBridgeEntry = KeychainEntry(service: bridgeService, account: "lastDiscoveredStableID") +private let preferredGatewayEntry = KeychainEntry(service: gatewayService, account: "preferredStableID") +private let lastGatewayEntry = KeychainEntry(service: gatewayService, account: "lastDiscoveredStableID") private func snapshotDefaults(_ keys: [String]) -> [String: Any?] { let defaults = UserDefaults.standard @@ -59,14 +59,14 @@ private func restoreKeychain(_ snapshot: [KeychainEntry: String?]) { applyKeychain(snapshot) } -@Suite(.serialized) struct BridgeSettingsStoreTests { +@Suite(.serialized) struct GatewaySettingsStoreTests { @Test func bootstrapCopiesDefaultsToKeychainWhenMissing() { let defaultsKeys = [ "node.instanceId", - "bridge.preferredStableID", - "bridge.lastDiscoveredStableID", + "gateway.preferredStableID", + "gateway.lastDiscoveredStableID", ] - let entries = [instanceIdEntry, preferredBridgeEntry, lastBridgeEntry] + let entries = [instanceIdEntry, preferredGatewayEntry, lastGatewayEntry] let defaultsSnapshot = snapshotDefaults(defaultsKeys) let keychainSnapshot = snapshotKeychain(entries) defer { @@ -76,29 +76,29 @@ private func restoreKeychain(_ snapshot: [KeychainEntry: String?]) { applyDefaults([ "node.instanceId": "node-test", - "bridge.preferredStableID": "preferred-test", - "bridge.lastDiscoveredStableID": "last-test", + "gateway.preferredStableID": "preferred-test", + "gateway.lastDiscoveredStableID": "last-test", ]) applyKeychain([ instanceIdEntry: nil, - preferredBridgeEntry: nil, - lastBridgeEntry: nil, + preferredGatewayEntry: nil, + lastGatewayEntry: nil, ]) - BridgeSettingsStore.bootstrapPersistence() + GatewaySettingsStore.bootstrapPersistence() #expect(KeychainStore.loadString(service: nodeService, account: "instanceId") == "node-test") - #expect(KeychainStore.loadString(service: bridgeService, account: "preferredStableID") == "preferred-test") - #expect(KeychainStore.loadString(service: bridgeService, account: "lastDiscoveredStableID") == "last-test") + #expect(KeychainStore.loadString(service: gatewayService, account: "preferredStableID") == "preferred-test") + #expect(KeychainStore.loadString(service: gatewayService, account: "lastDiscoveredStableID") == "last-test") } @Test func bootstrapCopiesKeychainToDefaultsWhenMissing() { let defaultsKeys = [ "node.instanceId", - "bridge.preferredStableID", - "bridge.lastDiscoveredStableID", + "gateway.preferredStableID", + "gateway.lastDiscoveredStableID", ] - let entries = [instanceIdEntry, preferredBridgeEntry, lastBridgeEntry] + let entries = [instanceIdEntry, preferredGatewayEntry, lastGatewayEntry] let defaultsSnapshot = snapshotDefaults(defaultsKeys) let keychainSnapshot = snapshotKeychain(entries) defer { @@ -108,20 +108,20 @@ private func restoreKeychain(_ snapshot: [KeychainEntry: String?]) { applyDefaults([ "node.instanceId": nil, - "bridge.preferredStableID": nil, - "bridge.lastDiscoveredStableID": nil, + "gateway.preferredStableID": nil, + "gateway.lastDiscoveredStableID": nil, ]) applyKeychain([ instanceIdEntry: "node-from-keychain", - preferredBridgeEntry: "preferred-from-keychain", - lastBridgeEntry: "last-from-keychain", + preferredGatewayEntry: "preferred-from-keychain", + lastGatewayEntry: "last-from-keychain", ]) - BridgeSettingsStore.bootstrapPersistence() + GatewaySettingsStore.bootstrapPersistence() let defaults = UserDefaults.standard #expect(defaults.string(forKey: "node.instanceId") == "node-from-keychain") - #expect(defaults.string(forKey: "bridge.preferredStableID") == "preferred-from-keychain") - #expect(defaults.string(forKey: "bridge.lastDiscoveredStableID") == "last-from-keychain") + #expect(defaults.string(forKey: "gateway.preferredStableID") == "preferred-from-keychain") + #expect(defaults.string(forKey: "gateway.lastDiscoveredStableID") == "last-from-keychain") } } diff --git a/apps/ios/Tests/IOSBridgeChatTransportTests.swift b/apps/ios/Tests/IOSGatewayChatTransportTests.swift similarity index 54% rename from apps/ios/Tests/IOSBridgeChatTransportTests.swift rename to apps/ios/Tests/IOSGatewayChatTransportTests.swift index 437437119..723a93146 100644 --- a/apps/ios/Tests/IOSBridgeChatTransportTests.swift +++ b/apps/ios/Tests/IOSGatewayChatTransportTests.swift @@ -1,19 +1,15 @@ +import ClawdbotKit import Testing @testable import Clawdbot -@Suite struct IOSBridgeChatTransportTests { - @Test func requestsFailFastWhenBridgeNotConnected() async { - let bridge = BridgeSession() - let transport = IOSBridgeChatTransport(bridge: bridge) - - do { - try await transport.setActiveSessionKey("node-test") - Issue.record("Expected setActiveSessionKey to throw when bridge not connected") - } catch {} +@Suite struct IOSGatewayChatTransportTests { + @Test func requestsFailFastWhenGatewayNotConnected() async { + let gateway = GatewayNodeSession() + let transport = IOSGatewayChatTransport(gateway: gateway) do { _ = try await transport.requestHistory(sessionKey: "node-test") - Issue.record("Expected requestHistory to throw when bridge not connected") + Issue.record("Expected requestHistory to throw when gateway not connected") } catch {} do { @@ -23,11 +19,12 @@ import Testing thinking: "low", idempotencyKey: "idempotency", attachments: []) - Issue.record("Expected sendMessage to throw when bridge not connected") + Issue.record("Expected sendMessage to throw when gateway not connected") } catch {} do { _ = try await transport.requestHealth(timeoutMs: 250) + Issue.record("Expected requestHealth to throw when gateway not connected") } catch {} } } diff --git a/apps/ios/Tests/Info.plist b/apps/ios/Tests/Info.plist index 0213b646b..6ff977b05 100644 --- a/apps/ios/Tests/Info.plist +++ b/apps/ios/Tests/Info.plist @@ -17,8 +17,8 @@ CFBundlePackageType BNDL CFBundleShortVersionString - 2026.1.11-4 + 2026.1.25 CFBundleVersion - 202601113 + 20260125 diff --git a/apps/ios/Tests/NodeAppModelInvokeTests.swift b/apps/ios/Tests/NodeAppModelInvokeTests.swift index 436635a84..6f0d99906 100644 --- a/apps/ios/Tests/NodeAppModelInvokeTests.swift +++ b/apps/ios/Tests/NodeAppModelInvokeTests.swift @@ -159,7 +159,7 @@ private func withUserDefaults(_ updates: [String: Any?], _ body: () throws -> let appModel = NodeAppModel() let url = URL(string: "clawdbot://agent?message=hello")! await appModel.handleDeepLink(url: url) - #expect(appModel.screen.errorText?.contains("Bridge not connected") == true) + #expect(appModel.screen.errorText?.contains("Gateway not connected") == true) } @Test @MainActor func handleDeepLinkRejectsOversizedMessage() async { @@ -170,7 +170,7 @@ private func withUserDefaults(_ updates: [String: Any?], _ body: () throws -> #expect(appModel.screen.errorText?.contains("Deep link too large") == true) } - @Test @MainActor func sendVoiceTranscriptThrowsWhenBridgeOffline() async { + @Test @MainActor func sendVoiceTranscriptThrowsWhenGatewayOffline() async { let appModel = NodeAppModel() await #expect(throws: Error.self) { try await appModel.sendVoiceTranscript(text: "hello", sessionKey: "main") diff --git a/apps/ios/Tests/SwiftUIRenderSmokeTests.swift b/apps/ios/Tests/SwiftUIRenderSmokeTests.swift index 53e100448..4fe7fe88e 100644 --- a/apps/ios/Tests/SwiftUIRenderSmokeTests.swift +++ b/apps/ios/Tests/SwiftUIRenderSmokeTests.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import SwiftUI import Testing import UIKit @@ -14,35 +15,35 @@ import UIKit } @Test @MainActor func statusPillConnectingBuildsAViewHierarchy() { - let root = StatusPill(bridge: .connecting, voiceWakeEnabled: true, brighten: true) {} + let root = StatusPill(gateway: .connecting, voiceWakeEnabled: true, brighten: true) {} _ = Self.host(root) } @Test @MainActor func statusPillDisconnectedBuildsAViewHierarchy() { - let root = StatusPill(bridge: .disconnected, voiceWakeEnabled: false) {} + let root = StatusPill(gateway: .disconnected, voiceWakeEnabled: false) {} _ = Self.host(root) } @Test @MainActor func settingsTabBuildsAViewHierarchy() { let appModel = NodeAppModel() - let bridgeController = BridgeConnectionController(appModel: appModel, startDiscovery: false) + let gatewayController = GatewayConnectionController(appModel: appModel, startDiscovery: false) let root = SettingsTab() .environment(appModel) .environment(appModel.voiceWake) - .environment(bridgeController) + .environment(gatewayController) _ = Self.host(root) } @Test @MainActor func rootTabsBuildAViewHierarchy() { let appModel = NodeAppModel() - let bridgeController = BridgeConnectionController(appModel: appModel, startDiscovery: false) + let gatewayController = GatewayConnectionController(appModel: appModel, startDiscovery: false) let root = RootTabs() .environment(appModel) .environment(appModel.voiceWake) - .environment(bridgeController) + .environment(gatewayController) _ = Self.host(root) } @@ -66,8 +67,8 @@ import UIKit @Test @MainActor func chatSheetBuildsAViewHierarchy() { let appModel = NodeAppModel() - let bridge = BridgeSession() - let root = ChatSheet(bridge: bridge, sessionKey: "test") + let gateway = GatewayNodeSession() + let root = ChatSheet(gateway: gateway, sessionKey: "test") .environment(appModel) .environment(appModel.voiceWake) _ = Self.host(root) diff --git a/apps/ios/Tests/VoiceWakePreferencesTests.swift b/apps/ios/Tests/VoiceWakePreferencesTests.swift index acf501654..ec4a63afa 100644 --- a/apps/ios/Tests/VoiceWakePreferencesTests.swift +++ b/apps/ios/Tests/VoiceWakePreferencesTests.swift @@ -11,6 +11,18 @@ import Testing #expect(VoiceWakePreferences.sanitizeTriggerWords(["", " "]) == VoiceWakePreferences.defaultTriggerWords) } + @Test func sanitizeTriggerWordsLimitsWordLength() { + let long = String(repeating: "x", count: VoiceWakePreferences.maxWordLength + 5) + let cleaned = VoiceWakePreferences.sanitizeTriggerWords(["ok", long]) + #expect(cleaned[1].count == VoiceWakePreferences.maxWordLength) + } + + @Test func sanitizeTriggerWordsLimitsWordCount() { + let words = (1...VoiceWakePreferences.maxWords + 3).map { "w\($0)" } + let cleaned = VoiceWakePreferences.sanitizeTriggerWords(words) + #expect(cleaned.count == VoiceWakePreferences.maxWords) + } + @Test func displayStringUsesSanitizedWords() { #expect(VoiceWakePreferences.displayString(for: ["", " "]) == "clawd, claude") } diff --git a/apps/ios/project.yml b/apps/ios/project.yml index d1b0c2fee..0073b4ef9 100644 --- a/apps/ios/project.yml +++ b/apps/ios/project.yml @@ -35,6 +35,8 @@ targets: - package: ClawdbotKit - package: ClawdbotKit product: ClawdbotChatUI + - package: ClawdbotKit + product: ClawdbotProtocol - package: Swabble product: SwabbleKit - sdk: AppIntents.framework @@ -79,19 +81,19 @@ targets: properties: CFBundleDisplayName: Clawdbot CFBundleIconName: AppIcon - CFBundleShortVersionString: "2026.1.9" - CFBundleVersion: "20260109" + CFBundleShortVersionString: "2026.1.25" + CFBundleVersion: "20260125" UILaunchScreen: {} UIApplicationSceneManifest: UIApplicationSupportsMultipleScenes: false UIBackgroundModes: - audio - NSLocalNetworkUsageDescription: Clawdbot discovers and connects to your Clawdbot bridge on the local network. + NSLocalNetworkUsageDescription: Clawdbot discovers and connects to your Clawdbot gateway on the local network. NSAppTransportSecurity: NSAllowsArbitraryLoadsInWebContent: true NSBonjourServices: - - _clawdbot-bridge._tcp - NSCameraUsageDescription: Clawdbot can capture photos or short video clips when requested via the bridge. + - _clawdbot-gw._tcp + NSCameraUsageDescription: Clawdbot can capture photos or short video clips when requested via the gateway. NSLocationWhenInUseUsageDescription: Clawdbot uses your location when you allow location sharing. NSLocationAlwaysAndWhenInUseUsageDescription: Clawdbot can share your location in the background when you enable Always. NSMicrophoneUsageDescription: Clawdbot needs microphone access for voice wake. @@ -128,5 +130,5 @@ targets: path: Tests/Info.plist properties: CFBundleDisplayName: ClawdbotTests - CFBundleShortVersionString: "2026.1.9" - CFBundleVersion: "20260109" + CFBundleShortVersionString: "2026.1.25" + CFBundleVersion: "20260125" diff --git a/apps/macos/Icon.icon/icon.json b/apps/macos/Icon.icon/icon.json index 32754bd18..33ba22b1c 100644 --- a/apps/macos/Icon.icon/icon.json +++ b/apps/macos/Icon.icon/icon.json @@ -33,4 +33,4 @@ ], "squares" : "shared" } -} \ No newline at end of file +} diff --git a/apps/macos/Package.resolved b/apps/macos/Package.resolved index 2bad2ca2f..ef9609649 100644 --- a/apps/macos/Package.resolved +++ b/apps/macos/Package.resolved @@ -1,6 +1,24 @@ { - "originHash" : "7eec77e2b399c480e76fdfc7dc3162652f5c775530e9fc282953de38ef2de79b", + "originHash" : "f847d54db16b371dbb1a79271d50436cdec572179b0f0cf14cfe1b75df8dfbc2", "pins" : [ + { + "identity" : "axorcist", + "kind" : "remoteSourceControl", + "location" : "https://github.com/steipete/AXorcist.git", + "state" : { + "revision" : "c75d06f7f93e264a9786edc2b78c04973061cb2f", + "version" : "0.1.0" + } + }, + { + "identity" : "commander", + "kind" : "remoteSourceControl", + "location" : "https://github.com/steipete/Commander.git", + "state" : { + "revision" : "9e349575c8e3c6745e81fe19e5bb5efa01b078ce", + "version" : "0.2.1" + } + }, { "identity" : "elevenlabskit", "kind" : "remoteSourceControl", @@ -10,15 +28,6 @@ "version" : "0.1.0" } }, - { - "identity" : "eventsource", - "kind" : "remoteSourceControl", - "location" : "https://github.com/mattt/eventsource.git", - "state" : { - "revision" : "ca2a9d90cbe49e09b92f4b6ebd922c03ebea51d0", - "version" : "1.3.0" - } - }, { "identity" : "menubarextraaccess", "kind" : "remoteSourceControl", @@ -28,6 +37,15 @@ "version" : "1.2.2" } }, + { + "identity" : "peekaboo", + "kind" : "remoteSourceControl", + "location" : "https://github.com/steipete/Peekaboo.git", + "state" : { + "branch" : "main", + "revision" : "bace59f90bb276f1c6fb613acfda3935ec4a7a90" + } + }, { "identity" : "sparkle", "kind" : "remoteSourceControl", @@ -46,33 +64,6 @@ "version" : "1.2.1" } }, - { - "identity" : "swift-asn1", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-asn1.git", - "state" : { - "revision" : "810496cf121e525d660cd0ea89a758740476b85f", - "version" : "1.5.1" - } - }, - { - "identity" : "swift-async-algorithms", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-async-algorithms", - "state" : { - "revision" : "6c050d5ef8e1aa6342528460db614e9770d7f804", - "version" : "1.1.1" - } - }, - { - "identity" : "swift-collections", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-collections", - "state" : { - "branch" : "main", - "revision" : "8e5e4a8f3617283b556064574651fc0869943c9a" - } - }, { "identity" : "swift-concurrency-extras", "kind" : "remoteSourceControl", @@ -82,24 +73,6 @@ "version" : "1.3.2" } }, - { - "identity" : "swift-configuration", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-configuration", - "state" : { - "revision" : "3528deb75256d7dcbb0d71fa75077caae0a8c749", - "version" : "1.0.0" - } - }, - { - "identity" : "swift-crypto", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-crypto.git", - "state" : { - "revision" : "6f70fa9eab24c1fd982af18c281c4525d05e3095", - "version" : "4.2.0" - } - }, { "identity" : "swift-log", "kind" : "remoteSourceControl", @@ -118,24 +91,6 @@ "version" : "1.1.1" } }, - { - "identity" : "swift-sdk", - "kind" : "remoteSourceControl", - "location" : "https://github.com/modelcontextprotocol/swift-sdk.git", - "state" : { - "revision" : "c0407a0b52677cb395d824cac2879b963075ba8c", - "version" : "0.10.2" - } - }, - { - "identity" : "swift-service-lifecycle", - "kind" : "remoteSourceControl", - "location" : "https://github.com/swift-server/swift-service-lifecycle", - "state" : { - "revision" : "1de37290c0ab3c5a96028e0f02911b672fd42348", - "version" : "2.9.1" - } - }, { "identity" : "swift-subprocess", "kind" : "remoteSourceControl", @@ -168,8 +123,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/gonzalezreal/textual", "state" : { - "revision" : "a03c1e103d88de4ea0dd8320ea1611ec0d4b29b3", - "version" : "0.2.0" + "revision" : "5b06b811c0f5313b6b84bbef98c635a630638c38", + "version" : "0.3.1" } } ], diff --git a/apps/macos/Package.swift b/apps/macos/Package.swift index 36928c71c..99ae0f991 100644 --- a/apps/macos/Package.swift +++ b/apps/macos/Package.swift @@ -12,27 +12,18 @@ let package = Package( .library(name: "ClawdbotIPC", targets: ["ClawdbotIPC"]), .library(name: "ClawdbotDiscovery", targets: ["ClawdbotDiscovery"]), .executable(name: "Clawdbot", targets: ["Clawdbot"]), - .executable(name: "clawdbot-mac-discovery", targets: ["ClawdbotDiscoveryCLI"]), - .executable(name: "clawdbot-mac-wizard", targets: ["ClawdbotWizardCLI"]), + .executable(name: "clawdbot-mac", targets: ["ClawdbotMacCLI"]), ], dependencies: [ .package(url: "https://github.com/orchetect/MenuBarExtraAccess", exact: "1.2.2"), .package(url: "https://github.com/swiftlang/swift-subprocess.git", from: "0.1.0"), .package(url: "https://github.com/apple/swift-log.git", from: "1.8.0"), .package(url: "https://github.com/sparkle-project/Sparkle", from: "2.8.1"), + .package(url: "https://github.com/steipete/Peekaboo.git", branch: "main"), .package(path: "../shared/ClawdbotKit"), .package(path: "../../Swabble"), - .package(path: "../../Peekaboo/Core/PeekabooCore"), - .package(path: "../../Peekaboo/Core/PeekabooAutomationKit"), ], targets: [ - .target( - name: "ClawdbotProtocol", - dependencies: [], - path: "Sources/ClawdbotProtocol", - swiftSettings: [ - .enableUpcomingFeature("StrictConcurrency"), - ]), .target( name: "ClawdbotIPC", dependencies: [], @@ -53,16 +44,16 @@ let package = Package( dependencies: [ "ClawdbotIPC", "ClawdbotDiscovery", - "ClawdbotProtocol", .product(name: "ClawdbotKit", package: "ClawdbotKit"), .product(name: "ClawdbotChatUI", package: "ClawdbotKit"), + .product(name: "ClawdbotProtocol", package: "ClawdbotKit"), .product(name: "SwabbleKit", package: "swabble"), .product(name: "MenuBarExtraAccess", package: "MenuBarExtraAccess"), .product(name: "Subprocess", package: "swift-subprocess"), .product(name: "Logging", package: "swift-log"), .product(name: "Sparkle", package: "Sparkle"), - .product(name: "PeekabooBridge", package: "PeekabooCore"), - .product(name: "PeekabooAutomationKit", package: "PeekabooAutomationKit"), + .product(name: "PeekabooBridge", package: "Peekaboo"), + .product(name: "PeekabooAutomationKit", package: "Peekaboo"), ], exclude: [ "Resources/Info.plist", @@ -75,20 +66,13 @@ let package = Package( .enableUpcomingFeature("StrictConcurrency"), ]), .executableTarget( - name: "ClawdbotDiscoveryCLI", + name: "ClawdbotMacCLI", dependencies: [ "ClawdbotDiscovery", + .product(name: "ClawdbotKit", package: "ClawdbotKit"), + .product(name: "ClawdbotProtocol", package: "ClawdbotKit"), ], - path: "Sources/ClawdbotDiscoveryCLI", - swiftSettings: [ - .enableUpcomingFeature("StrictConcurrency"), - ]), - .executableTarget( - name: "ClawdbotWizardCLI", - dependencies: [ - "ClawdbotProtocol", - ], - path: "Sources/ClawdbotWizardCLI", + path: "Sources/ClawdbotMacCLI", swiftSettings: [ .enableUpcomingFeature("StrictConcurrency"), ]), @@ -98,7 +82,7 @@ let package = Package( "ClawdbotIPC", "Clawdbot", "ClawdbotDiscovery", - "ClawdbotProtocol", + .product(name: "ClawdbotProtocol", package: "ClawdbotKit"), .product(name: "SwabbleKit", package: "swabble"), ], swiftSettings: [ diff --git a/apps/macos/README.md b/apps/macos/README.md new file mode 100644 index 000000000..ae35b772e --- /dev/null +++ b/apps/macos/README.md @@ -0,0 +1,64 @@ +# Clawdbot macOS app (dev + signing) + +## Quick dev run + +```bash +# from repo root +scripts/restart-mac.sh +``` + +Options: + +```bash +scripts/restart-mac.sh --no-sign # fastest dev; ad-hoc signing (TCC permissions do not stick) +scripts/restart-mac.sh --sign # force code signing (requires cert) +``` + +## Packaging flow + +```bash +scripts/package-mac-app.sh +``` + +Creates `dist/Clawdbot.app` and signs it via `scripts/codesign-mac-app.sh`. + +## Signing behavior + +Auto-selects identity (first match): +1) Developer ID Application +2) Apple Distribution +3) Apple Development +4) first available identity + +If none found: +- errors by default +- set `ALLOW_ADHOC_SIGNING=1` or `SIGN_IDENTITY="-"` to ad-hoc sign + +## Team ID audit (Sparkle mismatch guard) + +After signing, we read the app bundle Team ID and compare every Mach-O inside the app. +If any embedded binary has a different Team ID, signing fails. + +Skip the audit: +```bash +SKIP_TEAM_ID_CHECK=1 scripts/package-mac-app.sh +``` + +## Library validation workaround (dev only) + +If Sparkle Team ID mismatch blocks loading (common with Apple Development certs), opt in: + +```bash +DISABLE_LIBRARY_VALIDATION=1 scripts/package-mac-app.sh +``` + +This adds `com.apple.security.cs.disable-library-validation` to app entitlements. +Use for local dev only; keep off for release builds. + +## Useful env flags + +- `SIGN_IDENTITY="Apple Development: Your Name (TEAMID)"` +- `ALLOW_ADHOC_SIGNING=1` (ad-hoc, TCC permissions do not persist) +- `CODESIGN_TIMESTAMP=off` (offline debug) +- `DISABLE_LIBRARY_VALIDATION=1` (dev-only Sparkle workaround) +- `SKIP_TEAM_ID_CHECK=1` (bypass audit) diff --git a/apps/macos/Sources/Clawdbot/AgentEventsWindow.swift b/apps/macos/Sources/Clawdbot/AgentEventsWindow.swift index e3ccc87bc..43b60a270 100644 --- a/apps/macos/Sources/Clawdbot/AgentEventsWindow.swift +++ b/apps/macos/Sources/Clawdbot/AgentEventsWindow.swift @@ -81,7 +81,7 @@ private struct EventRow: View { return f.string(from: date) } - private func prettyJSON(_ dict: [String: AnyCodable]) -> String? { + private func prettyJSON(_ dict: [String: ClawdbotProtocol.AnyCodable]) -> String? { let normalized = dict.mapValues { $0.value } guard JSONSerialization.isValidJSONObject(normalized), let data = try? JSONSerialization.data(withJSONObject: normalized, options: [.prettyPrinted]), @@ -98,7 +98,10 @@ struct AgentEventsWindow_Previews: PreviewProvider { seq: 1, stream: "tool", ts: Date().timeIntervalSince1970 * 1000, - data: ["phase": AnyCodable("start"), "name": AnyCodable("bash")], + data: [ + "phase": ClawdbotProtocol.AnyCodable("start"), + "name": ClawdbotProtocol.AnyCodable("bash"), + ], summary: nil) AgentEventStore.shared.append(sample) return AgentEventsWindow() diff --git a/apps/macos/Sources/Clawdbot/AgentWorkspace.swift b/apps/macos/Sources/Clawdbot/AgentWorkspace.swift index 8906f2f4c..f63c1dd4d 100644 --- a/apps/macos/Sources/Clawdbot/AgentWorkspace.swift +++ b/apps/macos/Sources/Clawdbot/AgentWorkspace.swift @@ -23,7 +23,7 @@ enum AgentWorkspace { } static func displayPath(for url: URL) -> String { - let home = FileManager.default.homeDirectoryForCurrentUser.path + let home = FileManager().homeDirectoryForCurrentUser.path let path = url.path if path == home { return "~" } if path.hasPrefix(home + "/") { @@ -44,12 +44,12 @@ enum AgentWorkspace { } static func workspaceEntries(workspaceURL: URL) throws -> [String] { - let contents = try FileManager.default.contentsOfDirectory(atPath: workspaceURL.path) + let contents = try FileManager().contentsOfDirectory(atPath: workspaceURL.path) return contents.filter { !self.ignoredEntries.contains($0) } } static func isWorkspaceEmpty(workspaceURL: URL) -> Bool { - let fm = FileManager.default + let fm = FileManager() var isDir: ObjCBool = false if !fm.fileExists(atPath: workspaceURL.path, isDirectory: &isDir) { return true @@ -66,7 +66,7 @@ enum AgentWorkspace { } static func bootstrapSafety(for workspaceURL: URL) -> BootstrapSafety { - let fm = FileManager.default + let fm = FileManager() var isDir: ObjCBool = false if !fm.fileExists(atPath: workspaceURL.path, isDirectory: &isDir) { return .safe @@ -90,29 +90,29 @@ enum AgentWorkspace { static func bootstrap(workspaceURL: URL) throws -> URL { let shouldSeedBootstrap = self.isWorkspaceEmpty(workspaceURL: workspaceURL) - try FileManager.default.createDirectory(at: workspaceURL, withIntermediateDirectories: true) + try FileManager().createDirectory(at: workspaceURL, withIntermediateDirectories: true) let agentsURL = self.agentsURL(workspaceURL: workspaceURL) - if !FileManager.default.fileExists(atPath: agentsURL.path) { + if !FileManager().fileExists(atPath: agentsURL.path) { try self.defaultTemplate().write(to: agentsURL, atomically: true, encoding: .utf8) self.logger.info("Created AGENTS.md at \(agentsURL.path, privacy: .public)") } let soulURL = workspaceURL.appendingPathComponent(self.soulFilename) - if !FileManager.default.fileExists(atPath: soulURL.path) { + if !FileManager().fileExists(atPath: soulURL.path) { try self.defaultSoulTemplate().write(to: soulURL, atomically: true, encoding: .utf8) self.logger.info("Created SOUL.md at \(soulURL.path, privacy: .public)") } let identityURL = workspaceURL.appendingPathComponent(self.identityFilename) - if !FileManager.default.fileExists(atPath: identityURL.path) { + if !FileManager().fileExists(atPath: identityURL.path) { try self.defaultIdentityTemplate().write(to: identityURL, atomically: true, encoding: .utf8) self.logger.info("Created IDENTITY.md at \(identityURL.path, privacy: .public)") } let userURL = workspaceURL.appendingPathComponent(self.userFilename) - if !FileManager.default.fileExists(atPath: userURL.path) { + if !FileManager().fileExists(atPath: userURL.path) { try self.defaultUserTemplate().write(to: userURL, atomically: true, encoding: .utf8) self.logger.info("Created USER.md at \(userURL.path, privacy: .public)") } let bootstrapURL = workspaceURL.appendingPathComponent(self.bootstrapFilename) - if shouldSeedBootstrap, !FileManager.default.fileExists(atPath: bootstrapURL.path) { + if shouldSeedBootstrap, !FileManager().fileExists(atPath: bootstrapURL.path) { try self.defaultBootstrapTemplate().write(to: bootstrapURL, atomically: true, encoding: .utf8) self.logger.info("Created BOOTSTRAP.md at \(bootstrapURL.path, privacy: .public)") } @@ -120,7 +120,7 @@ enum AgentWorkspace { } static func needsBootstrap(workspaceURL: URL) -> Bool { - let fm = FileManager.default + let fm = FileManager() var isDir: ObjCBool = false if !fm.fileExists(atPath: workspaceURL.path, isDirectory: &isDir) { return true @@ -305,7 +305,7 @@ enum AgentWorkspace { if let dev = self.devTemplateURL(named: named) { urls.append(dev) } - let cwd = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) + let cwd = URL(fileURLWithPath: FileManager().currentDirectoryPath) urls.append(cwd.appendingPathComponent("docs") .appendingPathComponent(self.templateDirname) .appendingPathComponent(named)) diff --git a/apps/macos/Sources/Clawdbot/AnthropicAuthControls.swift b/apps/macos/Sources/Clawdbot/AnthropicAuthControls.swift index 42106e50d..0f5f1d61c 100644 --- a/apps/macos/Sources/Clawdbot/AnthropicAuthControls.swift +++ b/apps/macos/Sources/Clawdbot/AnthropicAuthControls.swift @@ -45,7 +45,7 @@ struct AnthropicAuthControls: View { NSWorkspace.shared.activateFileViewerSelecting([ClawdbotOAuthStore.oauthURL()]) } .buttonStyle(.bordered) - .disabled(!FileManager.default.fileExists(atPath: ClawdbotOAuthStore.oauthURL().path)) + .disabled(!FileManager().fileExists(atPath: ClawdbotOAuthStore.oauthURL().path)) Button("Refresh") { self.refresh() diff --git a/apps/macos/Sources/Clawdbot/AnthropicOAuth.swift b/apps/macos/Sources/Clawdbot/AnthropicOAuth.swift index 09113324a..4ea7f7fb9 100644 --- a/apps/macos/Sources/Clawdbot/AnthropicOAuth.swift +++ b/apps/macos/Sources/Clawdbot/AnthropicOAuth.swift @@ -234,7 +234,7 @@ enum ClawdbotOAuthStore { return URL(fileURLWithPath: expanded, isDirectory: true) } - return FileManager.default.homeDirectoryForCurrentUser + return FileManager().homeDirectoryForCurrentUser .appendingPathComponent(".clawdbot", isDirectory: true) .appendingPathComponent("credentials", isDirectory: true) } @@ -253,7 +253,7 @@ enum ClawdbotOAuthStore { urls.append(URL(fileURLWithPath: expanded, isDirectory: true).appendingPathComponent(self.oauthFilename)) } - let home = FileManager.default.homeDirectoryForCurrentUser + let home = FileManager().homeDirectoryForCurrentUser urls.append(home.appendingPathComponent(".pi/agent/\(self.oauthFilename)")) urls.append(home.appendingPathComponent(".claude/\(self.oauthFilename)")) urls.append(home.appendingPathComponent(".config/claude/\(self.oauthFilename)")) @@ -270,10 +270,10 @@ enum ClawdbotOAuthStore { static func importLegacyAnthropicOAuthIfNeeded() -> URL? { let dest = self.oauthURL() - guard !FileManager.default.fileExists(atPath: dest.path) else { return nil } + guard !FileManager().fileExists(atPath: dest.path) else { return nil } for url in self.legacyOAuthURLs() { - guard FileManager.default.fileExists(atPath: url.path) else { continue } + guard FileManager().fileExists(atPath: url.path) else { continue } guard self.anthropicOAuthStatus(at: url).isConnected else { continue } guard let storage = self.loadStorage(at: url) else { continue } do { @@ -296,7 +296,7 @@ enum ClawdbotOAuthStore { } static func anthropicOAuthStatus(at url: URL) -> AnthropicOAuthStatus { - guard FileManager.default.fileExists(atPath: url.path) else { return .missingFile } + guard FileManager().fileExists(atPath: url.path) else { return .missingFile } guard let data = try? Data(contentsOf: url) else { return .unreadableFile } guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else { return .invalidJSON } @@ -360,7 +360,7 @@ enum ClawdbotOAuthStore { private static func saveStorage(_ storage: [String: Any]) throws { let dir = self.oauthDir() - try FileManager.default.createDirectory( + try FileManager().createDirectory( at: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) @@ -370,7 +370,7 @@ enum ClawdbotOAuthStore { withJSONObject: storage, options: [.prettyPrinted, .sortedKeys]) try data.write(to: url, options: [.atomic]) - try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) + try FileManager().setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) } } diff --git a/apps/macos/Sources/Clawdbot/AnyCodable+Helpers.swift b/apps/macos/Sources/Clawdbot/AnyCodable+Helpers.swift index bada8e26a..831076040 100644 --- a/apps/macos/Sources/Clawdbot/AnyCodable+Helpers.swift +++ b/apps/macos/Sources/Clawdbot/AnyCodable+Helpers.swift @@ -1,6 +1,11 @@ +import ClawdbotKit import ClawdbotProtocol import Foundation +// Prefer the ClawdbotKit wrapper to keep gateway request payloads consistent. +typealias AnyCodable = ClawdbotKit.AnyCodable +typealias InstanceIdentity = ClawdbotKit.InstanceIdentity + extension AnyCodable { var stringValue: String? { self.value as? String } var boolValue: Bool? { self.value as? Bool } @@ -20,3 +25,23 @@ extension AnyCodable { } } } + +extension ClawdbotProtocol.AnyCodable { + var stringValue: String? { self.value as? String } + var boolValue: Bool? { self.value as? Bool } + var intValue: Int? { self.value as? Int } + var doubleValue: Double? { self.value as? Double } + var dictionaryValue: [String: ClawdbotProtocol.AnyCodable]? { self.value as? [String: ClawdbotProtocol.AnyCodable] } + var arrayValue: [ClawdbotProtocol.AnyCodable]? { self.value as? [ClawdbotProtocol.AnyCodable] } + + var foundationValue: Any { + switch self.value { + case let dict as [String: ClawdbotProtocol.AnyCodable]: + dict.mapValues { $0.foundationValue } + case let array as [ClawdbotProtocol.AnyCodable]: + array.map(\.foundationValue) + default: + self.value + } + } +} diff --git a/apps/macos/Sources/Clawdbot/AppState.swift b/apps/macos/Sources/Clawdbot/AppState.swift index dbf29c000..6ccb83369 100644 --- a/apps/macos/Sources/Clawdbot/AppState.swift +++ b/apps/macos/Sources/Clawdbot/AppState.swift @@ -24,6 +24,11 @@ final class AppState { case remote } + enum RemoteTransport: String { + case ssh + case direct + } + var isPaused: Bool { didSet { self.ifNotPreview { UserDefaults.standard.set(self.isPaused, forKey: pauseDefaultsKey) } } } @@ -166,12 +171,23 @@ final class AppState { } } + var remoteTransport: RemoteTransport { + didSet { self.syncGatewayConfigIfNeeded() } + } + var canvasEnabled: Bool { didSet { self.ifNotPreview { UserDefaults.standard.set(self.canvasEnabled, forKey: canvasEnabledKey) } } } - var systemRunPolicy: SystemRunPolicy { - didSet { self.ifNotPreview { MacNodeConfigFile.setSystemRunPolicy(self.systemRunPolicy) } } + var execApprovalMode: ExecApprovalQuickMode { + didSet { + self.ifNotPreview { + ExecApprovalsStore.updateDefaults { defaults in + defaults.security = self.execApprovalMode.security + defaults.ask = self.execApprovalMode.ask + } + } + } } /// Tracks whether the Canvas panel is currently visible (not persisted). @@ -193,6 +209,10 @@ final class AppState { } } + var remoteUrl: String { + didSet { self.syncGatewayConfigIfNeeded() } + } + var remoteIdentity: String { didSet { self.ifNotPreview { UserDefaults.standard.set(self.remoteIdentity, forKey: remoteIdentityKey) } } } @@ -256,35 +276,15 @@ final class AppState { } let configRoot = ClawdbotConfigFile.loadDict() - let configGateway = configRoot["gateway"] as? [String: Any] - let configModeRaw = (configGateway?["mode"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) - let configMode: ConnectionMode? = switch configModeRaw { - case "local": - .local - case "remote": - .remote - default: - nil - } - let configRemoteUrl = (configGateway?["remote"] as? [String: Any])?["url"] as? String - let configHasRemoteUrl = !(configRemoteUrl? - .trimmingCharacters(in: .whitespacesAndNewlines) - .isEmpty ?? true) - - let storedMode = UserDefaults.standard.string(forKey: connectionModeKey) - let resolvedConnectionMode: ConnectionMode = if let configMode { - configMode - } else if configHasRemoteUrl { - .remote - } else if let storedMode { - ConnectionMode(rawValue: storedMode) ?? .local - } else { - onboardingSeen ? .local : .unconfigured - } + let configRemoteUrl = GatewayRemoteConfig.resolveUrlString(root: configRoot) + let configRemoteTransport = GatewayRemoteConfig.resolveTransport(root: configRoot) + let resolvedConnectionMode = ConnectionModeResolver.resolve(root: configRoot).mode + self.remoteTransport = configRemoteTransport self.connectionMode = resolvedConnectionMode let storedRemoteTarget = UserDefaults.standard.string(forKey: remoteTargetKey) ?? "" if resolvedConnectionMode == .remote, + configRemoteTransport != .direct, storedRemoteTarget.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, let host = AppState.remoteHost(from: configRemoteUrl) { @@ -292,11 +292,13 @@ final class AppState { } else { self.remoteTarget = storedRemoteTarget } + self.remoteUrl = configRemoteUrl ?? "" self.remoteIdentity = UserDefaults.standard.string(forKey: remoteIdentityKey) ?? "" self.remoteProjectRoot = UserDefaults.standard.string(forKey: remoteProjectRootKey) ?? "" self.remoteCliPath = UserDefaults.standard.string(forKey: remoteCliPathKey) ?? "" self.canvasEnabled = UserDefaults.standard.object(forKey: canvasEnabledKey) as? Bool ?? true - self.systemRunPolicy = SystemRunPolicy.load() + let execDefaults = ExecApprovalsStore.resolveDefaults() + self.execApprovalMode = ExecApprovalQuickMode.from(security: execDefaults.security, ask: execDefaults.ask) self.peekabooBridgeEnabled = UserDefaults.standard .object(forKey: peekabooBridgeEnabledKey) as? Bool ?? true if !self.isPreview { @@ -368,10 +370,11 @@ final class AppState { private func applyConfigOverrides(_ root: [String: Any]) { let gateway = root["gateway"] as? [String: Any] let modeRaw = (gateway?["mode"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) - let remoteUrl = (gateway?["remote"] as? [String: Any])?["url"] as? String + let remoteUrl = GatewayRemoteConfig.resolveUrlString(root: root) let hasRemoteUrl = !(remoteUrl? .trimmingCharacters(in: .whitespacesAndNewlines) .isEmpty ?? true) + let remoteTransport = GatewayRemoteConfig.resolveTransport(root: root) let desiredMode: ConnectionMode? = switch modeRaw { case "local": @@ -392,8 +395,17 @@ final class AppState { self.connectionMode = .remote } + if remoteTransport != self.remoteTransport { + self.remoteTransport = remoteTransport + } + let remoteUrlText = remoteUrl ?? "" + if remoteUrlText != self.remoteUrl { + self.remoteUrl = remoteUrlText + } + let targetMode = desiredMode ?? self.connectionMode if targetMode == .remote, + remoteTransport != .direct, let host = AppState.remoteHost(from: remoteUrl) { self.updateRemoteTarget(host: host) @@ -401,10 +413,17 @@ final class AppState { } private func updateRemoteTarget(host: String) { - let parsed = CommandResolver.parseSSHTarget(self.remoteTarget) - let user = parsed?.user ?? NSUserName() - let port = parsed?.port ?? 22 - let assembled = port == 22 ? "\(user)@\(host)" : "\(user)@\(host):\(port)" + let trimmed = self.remoteTarget.trimmingCharacters(in: .whitespacesAndNewlines) + guard let parsed = CommandResolver.parseSSHTarget(trimmed) else { return } + let trimmedUser = parsed.user?.trimmingCharacters(in: .whitespacesAndNewlines) + let user = (trimmedUser?.isEmpty ?? true) ? nil : trimmedUser + let port = parsed.port + let assembled: String + if let user { + assembled = port == 22 ? "\(user)@\(host)" : "\(user)@\(host):\(port)" + } else { + assembled = port == 22 ? host : "\(host):\(port)" + } if assembled != self.remoteTarget { self.remoteTarget = assembled } @@ -416,6 +435,8 @@ final class AppState { let connectionMode = self.connectionMode let remoteTarget = self.remoteTarget let remoteIdentity = self.remoteIdentity + let remoteTransport = self.remoteTransport + let remoteUrl = self.remoteUrl let desiredMode: String? = switch connectionMode { case .local: "local" @@ -449,39 +470,63 @@ final class AppState { var remote = gateway["remote"] as? [String: Any] ?? [:] var remoteChanged = false - if let host = remoteHost { - let existingUrl = (remote["url"] as? String)? - .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - let parsedExisting = existingUrl.isEmpty ? nil : URL(string: existingUrl) - let scheme = parsedExisting?.scheme?.isEmpty == false ? parsedExisting?.scheme : "ws" - let port = parsedExisting?.port ?? 18789 - let desiredUrl = "\(scheme ?? "ws")://\(host):\(port)" - if existingUrl != desiredUrl { - remote["url"] = desiredUrl + if remoteTransport == .direct { + let trimmedUrl = remoteUrl.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedUrl.isEmpty { + if remote["url"] != nil { + remote.removeValue(forKey: "url") + remoteChanged = true + } + } else { + let normalizedUrl = GatewayRemoteConfig.normalizeGatewayUrlString(trimmedUrl) ?? trimmedUrl + if (remote["url"] as? String) != normalizedUrl { + remote["url"] = normalizedUrl + remoteChanged = true + } + } + if (remote["transport"] as? String) != RemoteTransport.direct.rawValue { + remote["transport"] = RemoteTransport.direct.rawValue remoteChanged = true } - } + } else { + if remote["transport"] != nil { + remote.removeValue(forKey: "transport") + remoteChanged = true + } + if let host = remoteHost { + let existingUrl = (remote["url"] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let parsedExisting = existingUrl.isEmpty ? nil : URL(string: existingUrl) + let scheme = parsedExisting?.scheme?.isEmpty == false ? parsedExisting?.scheme : "ws" + let port = parsedExisting?.port ?? 18789 + let desiredUrl = "\(scheme ?? "ws")://\(host):\(port)" + if existingUrl != desiredUrl { + remote["url"] = desiredUrl + remoteChanged = true + } + } - let sanitizedTarget = Self.sanitizeSSHTarget(remoteTarget) - if !sanitizedTarget.isEmpty { - if (remote["sshTarget"] as? String) != sanitizedTarget { - remote["sshTarget"] = sanitizedTarget + let sanitizedTarget = Self.sanitizeSSHTarget(remoteTarget) + if !sanitizedTarget.isEmpty { + if (remote["sshTarget"] as? String) != sanitizedTarget { + remote["sshTarget"] = sanitizedTarget + remoteChanged = true + } + } else if remote["sshTarget"] != nil { + remote.removeValue(forKey: "sshTarget") remoteChanged = true } - } else if remote["sshTarget"] != nil { - remote.removeValue(forKey: "sshTarget") - remoteChanged = true - } - let trimmedIdentity = remoteIdentity.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmedIdentity.isEmpty { - if (remote["sshIdentity"] as? String) != trimmedIdentity { - remote["sshIdentity"] = trimmedIdentity + let trimmedIdentity = remoteIdentity.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmedIdentity.isEmpty { + if (remote["sshIdentity"] as? String) != trimmedIdentity { + remote["sshIdentity"] = trimmedIdentity + remoteChanged = true + } + } else if remote["sshIdentity"] != nil { + remote.removeValue(forKey: "sshIdentity") remoteChanged = true } - } else if remote["sshIdentity"] != nil { - remote.removeValue(forKey: "sshIdentity") - remoteChanged = true } if remoteChanged { @@ -635,8 +680,10 @@ extension AppState { state.iconOverride = .system state.heartbeatsEnabled = true state.connectionMode = .local + state.remoteTransport = .ssh state.canvasEnabled = true state.remoteTarget = "user@example.com" + state.remoteUrl = "wss://gateway.example.ts.net" state.remoteIdentity = "~/.ssh/id_ed25519" state.remoteProjectRoot = "~/Projects/clawdbot" state.remoteCliPath = "" diff --git a/apps/macos/Sources/Clawdbot/Bridge/BridgeConnectionHandler.swift b/apps/macos/Sources/Clawdbot/Bridge/BridgeConnectionHandler.swift deleted file mode 100644 index ebe753e5d..000000000 --- a/apps/macos/Sources/Clawdbot/Bridge/BridgeConnectionHandler.swift +++ /dev/null @@ -1,454 +0,0 @@ -import ClawdbotKit -import Foundation -import Network -import OSLog - -struct BridgeNodeInfo: Sendable { - var nodeId: String - var displayName: String? - var platform: String? - var version: String? - var deviceFamily: String? - var modelIdentifier: String? - var remoteAddress: String? - var caps: [String]? -} - -actor BridgeConnectionHandler { - private let connection: NWConnection - private let logger: Logger - private let decoder = JSONDecoder() - private let encoder = JSONEncoder() - private let queue = DispatchQueue(label: "com.clawdbot.bridge.connection") - - private var buffer = Data() - private var isAuthenticated = false - private var nodeId: String? - private var pendingInvokes: [String: CheckedContinuation] = [:] - private var isClosed = false - - init(connection: NWConnection, logger: Logger) { - self.connection = connection - self.logger = logger - } - - enum AuthResult: Sendable { - case ok - case notPaired - case unauthorized - case error(code: String, message: String) - } - - enum PairResult: Sendable { - case ok(token: String) - case rejected - case error(code: String, message: String) - } - - private struct FrameContext: Sendable { - var serverName: String - var resolveAuth: @Sendable (BridgeHello) async -> AuthResult - var handlePair: @Sendable (BridgePairRequest) async -> PairResult - var onAuthenticated: (@Sendable (BridgeNodeInfo) async -> Void)? - var onEvent: (@Sendable (String, BridgeEventFrame) async -> Void)? - var onRequest: (@Sendable (String, BridgeRPCRequest) async -> BridgeRPCResponse)? - } - - func run( - resolveAuth: @escaping @Sendable (BridgeHello) async -> AuthResult, - handlePair: @escaping @Sendable (BridgePairRequest) async -> PairResult, - onAuthenticated: (@Sendable (BridgeNodeInfo) async -> Void)? = nil, - onDisconnected: (@Sendable (String) async -> Void)? = nil, - onEvent: (@Sendable (String, BridgeEventFrame) async -> Void)? = nil, - onRequest: (@Sendable (String, BridgeRPCRequest) async -> BridgeRPCResponse)? = nil) async - { - self.configureStateLogging() - self.connection.start(queue: self.queue) - - let context = FrameContext( - serverName: Host.current().localizedName ?? ProcessInfo.processInfo.hostName, - resolveAuth: resolveAuth, - handlePair: handlePair, - onAuthenticated: onAuthenticated, - onEvent: onEvent, - onRequest: onRequest) - - while true { - do { - guard let line = try await self.receiveLine() else { break } - guard let data = line.data(using: .utf8) else { continue } - let base = try self.decoder.decode(BridgeBaseFrame.self, from: data) - try await self.handleFrame( - baseType: base.type, - data: data, - context: context) - } catch { - await self.sendError(code: "INVALID_REQUEST", message: error.localizedDescription) - } - } - - await self.close(with: onDisconnected) - } - - private func configureStateLogging() { - self.connection.stateUpdateHandler = { [logger] state in - switch state { - case .ready: - logger.debug("bridge conn ready") - case let .failed(err): - logger.error("bridge conn failed: \(err.localizedDescription, privacy: .public)") - default: - break - } - } - } - - private func handleFrame( - baseType: String, - data: Data, - context: FrameContext) async throws - { - switch baseType { - case "hello": - await self.handleHelloFrame( - data: data, - context: context) - case "pair-request": - await self.handlePairRequestFrame( - data: data, - context: context) - case "event": - await self.handleEventFrame(data: data, onEvent: context.onEvent) - case "req": - try await self.handleRPCRequestFrame(data: data, onRequest: context.onRequest) - case "ping": - try await self.handlePingFrame(data: data) - case "invoke-res": - await self.handleInvokeResponseFrame(data: data) - default: - await self.sendError(code: "INVALID_REQUEST", message: "unknown type") - } - } - - private func handleHelloFrame( - data: Data, - context: FrameContext) async - { - do { - let hello = try self.decoder.decode(BridgeHello.self, from: data) - let nodeId = hello.nodeId.trimmingCharacters(in: .whitespacesAndNewlines) - self.nodeId = nodeId - let result = await context.resolveAuth(hello) - await self.handleAuthResult(result, serverName: context.serverName) - if case .ok = result { - await context.onAuthenticated?( - BridgeNodeInfo( - nodeId: nodeId, - displayName: hello.displayName, - platform: hello.platform, - version: hello.version, - deviceFamily: hello.deviceFamily, - modelIdentifier: hello.modelIdentifier, - remoteAddress: self.remoteAddressString(), - caps: hello.caps)) - } - } catch { - await self.sendError(code: "INVALID_REQUEST", message: error.localizedDescription) - } - } - - private func handlePairRequestFrame( - data: Data, - context: FrameContext) async - { - do { - let req = try self.decoder.decode(BridgePairRequest.self, from: data) - let nodeId = req.nodeId.trimmingCharacters(in: .whitespacesAndNewlines) - self.nodeId = nodeId - let enriched = BridgePairRequest( - type: req.type, - nodeId: nodeId, - displayName: req.displayName, - platform: req.platform, - version: req.version, - deviceFamily: req.deviceFamily, - modelIdentifier: req.modelIdentifier, - caps: req.caps, - commands: req.commands, - remoteAddress: self.remoteAddressString(), - silent: req.silent) - let result = await context.handlePair(enriched) - await self.handlePairResult(result, serverName: context.serverName) - if case .ok = result { - await context.onAuthenticated?( - BridgeNodeInfo( - nodeId: nodeId, - displayName: enriched.displayName, - platform: enriched.platform, - version: enriched.version, - deviceFamily: enriched.deviceFamily, - modelIdentifier: enriched.modelIdentifier, - remoteAddress: enriched.remoteAddress, - caps: enriched.caps)) - } - } catch { - await self.sendError(code: "INVALID_REQUEST", message: error.localizedDescription) - } - } - - private func handleEventFrame( - data: Data, - onEvent: (@Sendable (String, BridgeEventFrame) async -> Void)?) async - { - guard self.isAuthenticated, let nodeId = self.nodeId else { - await self.sendError(code: "UNAUTHORIZED", message: "not authenticated") - return - } - do { - let evt = try self.decoder.decode(BridgeEventFrame.self, from: data) - await onEvent?(nodeId, evt) - } catch { - await self.sendError(code: "INVALID_REQUEST", message: error.localizedDescription) - } - } - - private func handleRPCRequestFrame( - data: Data, - onRequest: (@Sendable (String, BridgeRPCRequest) async -> BridgeRPCResponse)?) async throws - { - let req = try self.decoder.decode(BridgeRPCRequest.self, from: data) - guard self.isAuthenticated, let nodeId = self.nodeId else { - try await self.send( - BridgeRPCResponse( - id: req.id, - ok: false, - error: BridgeRPCError(code: "UNAUTHORIZED", message: "not authenticated"))) - return - } - - if let onRequest { - let res = await onRequest(nodeId, req) - try await self.send(res) - } else { - try await self.send( - BridgeRPCResponse( - id: req.id, - ok: false, - error: BridgeRPCError(code: "UNAVAILABLE", message: "RPC not supported"))) - } - } - - private func handlePingFrame(data: Data) async throws { - guard self.isAuthenticated else { - await self.sendError(code: "UNAUTHORIZED", message: "not authenticated") - return - } - let ping = try self.decoder.decode(BridgePing.self, from: data) - try await self.send(BridgePong(type: "pong", id: ping.id)) - } - - private func handleInvokeResponseFrame(data: Data) async { - guard self.isAuthenticated else { - await self.sendError(code: "UNAUTHORIZED", message: "not authenticated") - return - } - do { - let res = try self.decoder.decode(BridgeInvokeResponse.self, from: data) - if let cont = self.pendingInvokes.removeValue(forKey: res.id) { - cont.resume(returning: res) - } - } catch { - await self.sendError(code: "INVALID_REQUEST", message: error.localizedDescription) - } - } - - private func remoteAddressString() -> String? { - switch self.connection.endpoint { - case let .hostPort(host: host, port: _): - let value = String(describing: host) - return value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : value - default: - return nil - } - } - - func remoteAddress() -> String? { - self.remoteAddressString() - } - - private func handlePairResult(_ result: PairResult, serverName: String) async { - switch result { - case let .ok(token): - do { - try await self.send(BridgePairOk(type: "pair-ok", token: token)) - self.isAuthenticated = true - let mainSessionKey = await GatewayConnection.shared.mainSessionKey() - try await self.send( - BridgeHelloOk( - type: "hello-ok", - serverName: serverName, - mainSessionKey: mainSessionKey)) - } catch { - self.logger.error("bridge send pair-ok failed: \(error.localizedDescription, privacy: .public)") - } - case .rejected: - await self.sendError(code: "UNAUTHORIZED", message: "pairing rejected") - case let .error(code, message): - await self.sendError(code: code, message: message) - } - } - - private func handleAuthResult(_ result: AuthResult, serverName: String) async { - switch result { - case .ok: - self.isAuthenticated = true - do { - let mainSessionKey = await GatewayConnection.shared.mainSessionKey() - try await self.send( - BridgeHelloOk( - type: "hello-ok", - serverName: serverName, - mainSessionKey: mainSessionKey)) - } catch { - self.logger.error("bridge send hello-ok failed: \(error.localizedDescription, privacy: .public)") - } - case .notPaired: - await self.sendError(code: "NOT_PAIRED", message: "pairing required") - case .unauthorized: - await self.sendError(code: "UNAUTHORIZED", message: "invalid token") - case let .error(code, message): - await self.sendError(code: code, message: message) - } - } - - private func sendError(code: String, message: String) async { - do { - try await self.send(BridgeErrorFrame(type: "error", code: code, message: message)) - } catch { - self.logger.error("bridge send error failed: \(error.localizedDescription, privacy: .public)") - } - } - - func invoke(command: String, paramsJSON: String?) async throws -> BridgeInvokeResponse { - guard self.isAuthenticated else { - throw NSError(domain: "Bridge", code: 1, userInfo: [ - NSLocalizedDescriptionKey: "UNAUTHORIZED: not authenticated", - ]) - } - let id = UUID().uuidString - let req = BridgeInvokeRequest(type: "invoke", id: id, command: command, paramsJSON: paramsJSON) - - let timeoutTask = Task { - try await Task.sleep(nanoseconds: 15 * 1_000_000_000) - await self.timeoutInvoke(id: id) - } - defer { timeoutTask.cancel() } - - return try await withCheckedThrowingContinuation { cont in - Task { [weak self] in - guard let self else { return } - await self.beginInvoke(id: id, request: req, continuation: cont) - } - } - } - - private func beginInvoke( - id: String, - request: BridgeInvokeRequest, - continuation: CheckedContinuation) async - { - self.pendingInvokes[id] = continuation - do { - try await self.send(request) - } catch { - await self.failInvoke(id: id, error: error) - } - } - - private func timeoutInvoke(id: String) async { - guard let cont = self.pendingInvokes.removeValue(forKey: id) else { return } - cont.resume(throwing: NSError(domain: "Bridge", code: 3, userInfo: [ - NSLocalizedDescriptionKey: "UNAVAILABLE: invoke timeout", - ])) - } - - private func failInvoke(id: String, error: Error) async { - guard let cont = self.pendingInvokes.removeValue(forKey: id) else { return } - cont.resume(throwing: error) - } - - private func send(_ obj: some Encodable) async throws { - let data = try self.encoder.encode(obj) - var line = Data() - line.append(data) - line.append(0x0A) // \n - let _: Void = try await withCheckedThrowingContinuation { cont in - self.connection.send(content: line, completion: .contentProcessed { err in - if let err { - cont.resume(throwing: err) - } else { - cont.resume(returning: ()) - } - }) - } - } - - func sendServerEvent(event: String, payloadJSON: String?) async { - guard self.isAuthenticated else { return } - do { - try await self.send(BridgeEventFrame(type: "event", event: event, payloadJSON: payloadJSON)) - } catch { - self.logger.error("bridge send event failed: \(error.localizedDescription, privacy: .public)") - } - } - - private func receiveLine() async throws -> String? { - while true { - if let idx = self.buffer.firstIndex(of: 0x0A) { - let lineData = self.buffer.prefix(upTo: idx) - self.buffer.removeSubrange(...idx) - return String(data: lineData, encoding: .utf8) - } - - let chunk = try await self.receiveChunk() - if chunk.isEmpty { return nil } - self.buffer.append(chunk) - } - } - - private func receiveChunk() async throws -> Data { - try await withCheckedThrowingContinuation { cont in - self.connection - .receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { data, _, isComplete, error in - if let error { - cont.resume(throwing: error) - return - } - if isComplete { - cont.resume(returning: Data()) - return - } - cont.resume(returning: data ?? Data()) - } - } - } - - private func close(with onDisconnected: (@Sendable (String) async -> Void)? = nil) async { - if self.isClosed { return } - self.isClosed = true - - let nodeId = self.nodeId - let pending = self.pendingInvokes.values - self.pendingInvokes.removeAll() - for cont in pending { - cont.resume(throwing: NSError(domain: "Bridge", code: 4, userInfo: [ - NSLocalizedDescriptionKey: "UNAVAILABLE: connection closed", - ])) - } - - self.connection.cancel() - if let nodeId { - await onDisconnected?(nodeId) - } - } -} diff --git a/apps/macos/Sources/Clawdbot/Bridge/BridgeServer.swift b/apps/macos/Sources/Clawdbot/Bridge/BridgeServer.swift deleted file mode 100644 index f45dcae20..000000000 --- a/apps/macos/Sources/Clawdbot/Bridge/BridgeServer.swift +++ /dev/null @@ -1,542 +0,0 @@ -import AppKit -import ClawdbotKit -import ClawdbotProtocol -import Foundation -import Network -import OSLog - -actor BridgeServer { - static let shared = BridgeServer() - - private let logger = Logger(subsystem: "com.clawdbot", category: "bridge") - private var listener: NWListener? - private var isRunning = false - private var store: PairedNodesStore? - private var connections: [String: BridgeConnectionHandler] = [:] - private var nodeInfoById: [String: BridgeNodeInfo] = [:] - private var presenceTasks: [String: Task] = [:] - private var chatSubscriptions: [String: Set] = [:] - private var gatewayPushTask: Task? - - func start() async { - if self.isRunning { return } - self.isRunning = true - - do { - let storeURL = try Self.defaultStoreURL() - let store = PairedNodesStore(fileURL: storeURL) - await store.load() - self.store = store - - let params = NWParameters.tcp - params.includePeerToPeer = true - let listener = try NWListener(using: params, on: .any) - - listener.newConnectionHandler = { [weak self] connection in - guard let self else { return } - Task { await self.handle(connection: connection) } - } - - listener.stateUpdateHandler = { [weak self] state in - guard let self else { return } - Task { await self.handleListenerState(state) } - } - - listener.start(queue: DispatchQueue(label: "com.clawdbot.bridge")) - self.listener = listener - } catch { - self.logger.error("bridge start failed: \(error.localizedDescription, privacy: .public)") - self.isRunning = false - } - } - - func stop() async { - self.isRunning = false - self.listener?.cancel() - self.listener = nil - } - - private func handleListenerState(_ state: NWListener.State) { - switch state { - case .ready: - self.logger.info("bridge listening") - case let .failed(err): - self.logger.error("bridge listener failed: \(err.localizedDescription, privacy: .public)") - case .cancelled: - self.logger.info("bridge listener cancelled") - case .waiting: - self.logger.info("bridge listener waiting") - case .setup: - break - @unknown default: - break - } - } - - private func handle(connection: NWConnection) async { - let handler = BridgeConnectionHandler(connection: connection, logger: self.logger) - await handler.run( - resolveAuth: { [weak self] hello in - await self?.authorize(hello: hello) ?? .error(code: "UNAVAILABLE", message: "bridge unavailable") - }, - handlePair: { [weak self] request in - await self?.pair(request: request) ?? .error(code: "UNAVAILABLE", message: "bridge unavailable") - }, - onAuthenticated: { [weak self] node in - await self?.registerConnection(handler: handler, node: node) - }, - onDisconnected: { [weak self] nodeId in - await self?.unregisterConnection(nodeId: nodeId) - }, - onEvent: { [weak self] nodeId, evt in - await self?.handleEvent(nodeId: nodeId, evt: evt) - }, - onRequest: { [weak self] nodeId, req in - await self?.handleRequest(nodeId: nodeId, req: req) - ?? BridgeRPCResponse( - id: req.id, - ok: false, - error: BridgeRPCError(code: "UNAVAILABLE", message: "bridge unavailable")) - }) - } - - func invoke(nodeId: String, command: String, paramsJSON: String?) async throws -> BridgeInvokeResponse { - guard let handler = self.connections[nodeId] else { - throw NSError(domain: "Bridge", code: 10, userInfo: [ - NSLocalizedDescriptionKey: "UNAVAILABLE: node not connected", - ]) - } - return try await handler.invoke(command: command, paramsJSON: paramsJSON) - } - - func connectedNodeIds() -> [String] { - Array(self.connections.keys).sorted() - } - - func connectedNodes() -> [BridgeNodeInfo] { - self.nodeInfoById.values.sorted { a, b in - (a.displayName ?? a.nodeId) < (b.displayName ?? b.nodeId) - } - } - - func pairedNodes() async -> [PairedNode] { - guard let store = self.store else { return [] } - return await store.all() - } - - private func registerConnection(handler: BridgeConnectionHandler, node: BridgeNodeInfo) async { - self.connections[node.nodeId] = handler - self.nodeInfoById[node.nodeId] = node - await self.beaconPresence(nodeId: node.nodeId, reason: "connect") - self.startPresenceTask(nodeId: node.nodeId) - self.ensureGatewayPushTask() - } - - private func unregisterConnection(nodeId: String) async { - await self.beaconPresence(nodeId: nodeId, reason: "disconnect") - self.stopPresenceTask(nodeId: nodeId) - self.connections.removeValue(forKey: nodeId) - self.nodeInfoById.removeValue(forKey: nodeId) - self.chatSubscriptions[nodeId] = nil - self.stopGatewayPushTaskIfIdle() - } - - private struct VoiceTranscriptPayload: Codable, Sendable { - var text: String - var sessionKey: String? - } - - private func handleEvent(nodeId: String, evt: BridgeEventFrame) async { - switch evt.event { - case "chat.subscribe": - guard let json = evt.payloadJSON, let data = json.data(using: .utf8) else { return } - struct Subscribe: Codable { var sessionKey: String } - guard let payload = try? JSONDecoder().decode(Subscribe.self, from: data) else { return } - let key = payload.sessionKey.trimmingCharacters(in: .whitespacesAndNewlines) - guard !key.isEmpty else { return } - var set = self.chatSubscriptions[nodeId] ?? Set() - set.insert(key) - self.chatSubscriptions[nodeId] = set - - case "chat.unsubscribe": - guard let json = evt.payloadJSON, let data = json.data(using: .utf8) else { return } - struct Unsubscribe: Codable { var sessionKey: String } - guard let payload = try? JSONDecoder().decode(Unsubscribe.self, from: data) else { return } - let key = payload.sessionKey.trimmingCharacters(in: .whitespacesAndNewlines) - guard !key.isEmpty else { return } - var set = self.chatSubscriptions[nodeId] ?? Set() - set.remove(key) - self.chatSubscriptions[nodeId] = set.isEmpty ? nil : set - - case "voice.transcript": - guard let json = evt.payloadJSON, let data = json.data(using: .utf8) else { - return - } - guard let payload = try? JSONDecoder().decode(VoiceTranscriptPayload.self, from: data) else { - return - } - let text = payload.text.trimmingCharacters(in: .whitespacesAndNewlines) - guard !text.isEmpty else { return } - - let sessionKey = payload.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - ?? "main" - - _ = await GatewayConnection.shared.sendAgent(GatewayAgentInvocation( - message: text, - sessionKey: sessionKey, - thinking: "low", - deliver: false, - to: nil, - channel: .last)) - - case "agent.request": - guard let json = evt.payloadJSON, let data = json.data(using: .utf8) else { - return - } - guard let link = try? JSONDecoder().decode(AgentDeepLink.self, from: data) else { - return - } - - let message = link.message.trimmingCharacters(in: .whitespacesAndNewlines) - guard !message.isEmpty else { return } - guard message.count <= 20000 else { return } - - let sessionKey = link.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - ?? "node-\(nodeId)" - let thinking = link.thinking?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - let to = link.to?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - let channel = GatewayAgentChannel(raw: link.channel) - - _ = await GatewayConnection.shared.sendAgent(GatewayAgentInvocation( - message: message, - sessionKey: sessionKey, - thinking: thinking, - deliver: link.deliver, - to: to, - channel: channel)) - - default: - break - } - } - - private func handleRequest(nodeId: String, req: BridgeRPCRequest) async -> BridgeRPCResponse { - let allowed: Set = ["chat.history", "chat.send", "health"] - guard allowed.contains(req.method) else { - return BridgeRPCResponse( - id: req.id, - ok: false, - error: BridgeRPCError(code: "FORBIDDEN", message: "Method not allowed")) - } - - let params: [String: ClawdbotProtocol.AnyCodable]? - if let json = req.paramsJSON?.trimmingCharacters(in: .whitespacesAndNewlines), !json.isEmpty { - guard let data = json.data(using: .utf8) else { - return BridgeRPCResponse( - id: req.id, - ok: false, - error: BridgeRPCError(code: "INVALID_REQUEST", message: "paramsJSON not UTF-8")) - } - do { - params = try JSONDecoder().decode([String: ClawdbotProtocol.AnyCodable].self, from: data) - } catch { - return BridgeRPCResponse( - id: req.id, - ok: false, - error: BridgeRPCError(code: "INVALID_REQUEST", message: error.localizedDescription)) - } - } else { - params = nil - } - - do { - let data = try await GatewayConnection.shared.request(method: req.method, params: params, timeoutMs: 30000) - guard let json = String(data: data, encoding: .utf8) else { - return BridgeRPCResponse( - id: req.id, - ok: false, - error: BridgeRPCError(code: "UNAVAILABLE", message: "Response not UTF-8")) - } - return BridgeRPCResponse(id: req.id, ok: true, payloadJSON: json) - } catch { - return BridgeRPCResponse( - id: req.id, - ok: false, - error: BridgeRPCError(code: "UNAVAILABLE", message: error.localizedDescription)) - } - } - - private func ensureGatewayPushTask() { - if self.gatewayPushTask != nil { return } - self.gatewayPushTask = Task { [weak self] in - guard let self else { return } - do { - try await GatewayConnection.shared.refresh() - } catch { - // We'll still forward events once the gateway comes up. - } - let stream = await GatewayConnection.shared.subscribe() - for await push in stream { - if Task.isCancelled { return } - await self.forwardGatewayPush(push) - } - } - } - - private func stopGatewayPushTaskIfIdle() { - guard self.connections.isEmpty else { return } - self.gatewayPushTask?.cancel() - self.gatewayPushTask = nil - } - - private func forwardGatewayPush(_ push: GatewayPush) async { - let subscribedNodes = self.chatSubscriptions.keys.filter { self.connections[$0] != nil } - guard !subscribedNodes.isEmpty else { return } - - switch push { - case let .snapshot(hello): - let payloadJSON = (try? JSONEncoder().encode(hello.snapshot.health)) - .flatMap { String(data: $0, encoding: .utf8) } - for nodeId in subscribedNodes { - await self.connections[nodeId]?.sendServerEvent(event: "health", payloadJSON: payloadJSON) - } - case let .event(evt): - switch evt.event { - case "health": - guard let payload = evt.payload else { return } - let payloadJSON = (try? JSONEncoder().encode(payload)) - .flatMap { String(data: $0, encoding: .utf8) } - for nodeId in subscribedNodes { - await self.connections[nodeId]?.sendServerEvent(event: "health", payloadJSON: payloadJSON) - } - case "tick": - for nodeId in subscribedNodes { - await self.connections[nodeId]?.sendServerEvent(event: "tick", payloadJSON: nil) - } - case "chat": - guard let payload = evt.payload else { return } - let payloadData = try? JSONEncoder().encode(payload) - let payloadJSON = payloadData.flatMap { String(data: $0, encoding: .utf8) } - - struct MinimalChat: Codable { var sessionKey: String } - let sessionKey = payloadData.flatMap { try? JSONDecoder().decode(MinimalChat.self, from: $0) }? - .sessionKey - if let sessionKey { - for nodeId in subscribedNodes { - guard self.chatSubscriptions[nodeId]?.contains(sessionKey) == true else { continue } - await self.connections[nodeId]?.sendServerEvent(event: "chat", payloadJSON: payloadJSON) - } - } else { - for nodeId in subscribedNodes { - await self.connections[nodeId]?.sendServerEvent(event: "chat", payloadJSON: payloadJSON) - } - } - default: - break - } - case .seqGap: - for nodeId in subscribedNodes { - await self.connections[nodeId]?.sendServerEvent(event: "seqGap", payloadJSON: nil) - } - } - } - - private func beaconPresence(nodeId: String, reason: String) async { - let paired = await self.store?.find(nodeId: nodeId) - let host = paired?.displayName?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - ?? nodeId - let version = paired?.version?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - let platform = paired?.platform?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - let ip = await self.connections[nodeId]?.remoteAddress() - - var tags: [String] = ["node", "ios"] - if let platform { tags.append(platform) } - - let summary = [ - "Node: \(host)\(ip.map { " (\($0))" } ?? "")", - platform.map { "platform \($0)" }, - version.map { "app \($0)" }, - "mode node", - "reason \(reason)", - ].compactMap(\.self).joined(separator: " · ") - - var params: [String: ClawdbotProtocol.AnyCodable] = [ - "text": ClawdbotProtocol.AnyCodable(summary), - "instanceId": ClawdbotProtocol.AnyCodable(nodeId), - "host": ClawdbotProtocol.AnyCodable(host), - "mode": ClawdbotProtocol.AnyCodable("node"), - "reason": ClawdbotProtocol.AnyCodable(reason), - "tags": ClawdbotProtocol.AnyCodable(tags), - ] - if let ip { params["ip"] = ClawdbotProtocol.AnyCodable(ip) } - if let version { params["version"] = ClawdbotProtocol.AnyCodable(version) } - await GatewayConnection.shared.sendSystemEvent(params) - } - - private func startPresenceTask(nodeId: String) { - self.presenceTasks[nodeId]?.cancel() - self.presenceTasks[nodeId] = Task.detached { [weak self] in - while !Task.isCancelled { - try? await Task.sleep(nanoseconds: 180 * 1_000_000_000) - if Task.isCancelled { return } - await self?.beaconPresence(nodeId: nodeId, reason: "periodic") - } - } - } - - private func stopPresenceTask(nodeId: String) { - self.presenceTasks[nodeId]?.cancel() - self.presenceTasks.removeValue(forKey: nodeId) - } - - private func authorize(hello: BridgeHello) async -> BridgeConnectionHandler.AuthResult { - let nodeId = hello.nodeId.trimmingCharacters(in: .whitespacesAndNewlines) - if nodeId.isEmpty { - return .error(code: "INVALID_REQUEST", message: "nodeId required") - } - guard let store = self.store else { - return .error(code: "UNAVAILABLE", message: "store unavailable") - } - guard let paired = await store.find(nodeId: nodeId) else { - return .notPaired - } - guard let token = hello.token, token == paired.token else { - return .unauthorized - } - - do { - var updated = paired - let name = hello.displayName?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - let platform = hello.platform?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - let version = hello.version?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - let deviceFamily = hello.deviceFamily?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - let modelIdentifier = hello.modelIdentifier?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - - if updated.displayName != name { updated.displayName = name } - if updated.platform != platform { updated.platform = platform } - if updated.version != version { updated.version = version } - if updated.deviceFamily != deviceFamily { updated.deviceFamily = deviceFamily } - if updated.modelIdentifier != modelIdentifier { updated.modelIdentifier = modelIdentifier } - - if updated != paired { - try await store.upsert(updated) - } else { - try await store.touchSeen(nodeId: nodeId) - } - } catch { - // ignore - } - return .ok - } - - private func pair(request: BridgePairRequest) async -> BridgeConnectionHandler.PairResult { - let nodeId = request.nodeId.trimmingCharacters(in: .whitespacesAndNewlines) - if nodeId.isEmpty { - return .error(code: "INVALID_REQUEST", message: "nodeId required") - } - guard let store = self.store else { - return .error(code: "UNAVAILABLE", message: "store unavailable") - } - let existing = await store.find(nodeId: nodeId) - - let approved = await BridgePairingApprover.approve(request: request, isRepair: existing != nil) - if !approved { - return .rejected - } - - let token = UUID().uuidString.replacingOccurrences(of: "-", with: "") - let nowMs = Int(Date().timeIntervalSince1970 * 1000) - let node = PairedNode( - nodeId: nodeId, - displayName: request.displayName, - platform: request.platform, - version: request.version, - deviceFamily: request.deviceFamily, - modelIdentifier: request.modelIdentifier, - token: token, - createdAtMs: nowMs, - lastSeenAtMs: nowMs) - do { - try await store.upsert(node) - return .ok(token: token) - } catch { - return .error(code: "UNAVAILABLE", message: "failed to persist pairing") - } - } - - private static func defaultStoreURL() throws -> URL { - let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first - guard let base else { - throw NSError( - domain: "Bridge", - code: 1, - userInfo: [NSLocalizedDescriptionKey: "Application Support unavailable"]) - } - return base - .appendingPathComponent("Clawdbot", isDirectory: true) - .appendingPathComponent("bridge", isDirectory: true) - .appendingPathComponent("paired-nodes.json", isDirectory: false) - } -} - -@MainActor -enum BridgePairingApprover { - static func approve(request: BridgePairRequest, isRepair: Bool) async -> Bool { - await withCheckedContinuation { cont in - let name = request.displayName ?? request.nodeId - let remote = request.remoteAddress?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty - let alert = NSAlert() - alert.messageText = isRepair ? "Re-pair Clawdbot Node?" : "Pair Clawdbot Node?" - alert.informativeText = """ - Node: \(name) - IP: \(remote ?? "unknown") - Platform: \(request.platform ?? "unknown") - Version: \(request.version ?? "unknown") - """ - alert.addButton(withTitle: "Approve") - alert.addButton(withTitle: "Reject") - if #available(macOS 11.0, *), alert.buttons.indices.contains(1) { - alert.buttons[1].hasDestructiveAction = true - } - let resp = alert.runModal() - cont.resume(returning: resp == .alertFirstButtonReturn) - } - } -} - -#if DEBUG -extension BridgeServer { - func exerciseForTesting() async { - let conn = NWConnection(to: .hostPort(host: "127.0.0.1", port: 22), using: .tcp) - let handler = BridgeConnectionHandler(connection: conn, logger: self.logger) - self.connections["node-1"] = handler - self.nodeInfoById["node-1"] = BridgeNodeInfo( - nodeId: "node-1", - displayName: "Node One", - platform: "macOS", - version: "1.0.0", - deviceFamily: "Mac", - modelIdentifier: "MacBookPro18,1", - remoteAddress: "127.0.0.1", - caps: ["chat", "voice"]) - - _ = self.connectedNodeIds() - _ = self.connectedNodes() - - self.handleListenerState(.ready) - self.handleListenerState(.failed(NWError.posix(.ECONNREFUSED))) - self.handleListenerState(.waiting(NWError.posix(.ETIMEDOUT))) - self.handleListenerState(.cancelled) - self.handleListenerState(.setup) - - let subscribe = BridgeEventFrame(event: "chat.subscribe", payloadJSON: "{\"sessionKey\":\"main\"}") - await self.handleEvent(nodeId: "node-1", evt: subscribe) - - let unsubscribe = BridgeEventFrame(event: "chat.unsubscribe", payloadJSON: "{\"sessionKey\":\"main\"}") - await self.handleEvent(nodeId: "node-1", evt: unsubscribe) - - let invalid = BridgeRPCRequest(id: "req-1", method: "invalid.method", paramsJSON: nil) - _ = await self.handleRequest(nodeId: "node-1", req: invalid) - } -} -#endif diff --git a/apps/macos/Sources/Clawdbot/Bridge/PairedNodesStore.swift b/apps/macos/Sources/Clawdbot/Bridge/PairedNodesStore.swift deleted file mode 100644 index e78215635..000000000 --- a/apps/macos/Sources/Clawdbot/Bridge/PairedNodesStore.swift +++ /dev/null @@ -1,59 +0,0 @@ -import Foundation - -struct PairedNode: Codable, Equatable { - var nodeId: String - var displayName: String? - var platform: String? - var version: String? - var deviceFamily: String? - var modelIdentifier: String? - var token: String - var createdAtMs: Int - var lastSeenAtMs: Int? -} - -actor PairedNodesStore { - private let fileURL: URL - private var nodes: [String: PairedNode] = [:] - - init(fileURL: URL) { - self.fileURL = fileURL - } - - func load() { - do { - let data = try Data(contentsOf: self.fileURL) - let decoded = try JSONDecoder().decode([String: PairedNode].self, from: data) - self.nodes = decoded - } catch { - self.nodes = [:] - } - } - - func all() -> [PairedNode] { - self.nodes.values.sorted { a, b in (a.displayName ?? a.nodeId) < (b.displayName ?? b.nodeId) } - } - - func find(nodeId: String) -> PairedNode? { - self.nodes[nodeId] - } - - func upsert(_ node: PairedNode) async throws { - self.nodes[node.nodeId] = node - try await self.persist() - } - - func touchSeen(nodeId: String) async throws { - guard var node = self.nodes[nodeId] else { return } - node.lastSeenAtMs = Int(Date().timeIntervalSince1970 * 1000) - self.nodes[nodeId] = node - try await self.persist() - } - - private func persist() async throws { - let dir = self.fileURL.deletingLastPathComponent() - try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) - let data = try JSONEncoder().encode(self.nodes) - try data.write(to: self.fileURL, options: [.atomic]) - } -} diff --git a/apps/macos/Sources/Clawdbot/CLIInstaller.swift b/apps/macos/Sources/Clawdbot/CLIInstaller.swift index 41abb29e6..b9113e27a 100644 --- a/apps/macos/Sources/Clawdbot/CLIInstaller.swift +++ b/apps/macos/Sources/Clawdbot/CLIInstaller.swift @@ -35,7 +35,7 @@ enum CLIInstaller { } static func install(statusHandler: @escaping @MainActor @Sendable (String) async -> Void) async { - let expected = GatewayEnvironment.expectedGatewayVersion()?.description ?? "latest" + let expected = GatewayEnvironment.expectedGatewayVersionString() ?? "latest" let prefix = Self.installPrefix() await statusHandler("Installing clawdbot CLI…") let cmd = self.installScriptCommand(version: expected, prefix: prefix) @@ -61,7 +61,7 @@ enum CLIInstaller { } private static func installPrefix() -> String { - FileManager.default.homeDirectoryForCurrentUser + FileManager().homeDirectoryForCurrentUser .appendingPathComponent(".clawdbot") .path } diff --git a/apps/macos/Sources/Clawdbot/CameraCaptureService.swift b/apps/macos/Sources/Clawdbot/CameraCaptureService.swift index b7a7de308..c9893bbfb 100644 --- a/apps/macos/Sources/Clawdbot/CameraCaptureService.swift +++ b/apps/macos/Sources/Clawdbot/CameraCaptureService.swift @@ -167,20 +167,20 @@ actor CameraCaptureService { defer { session.stopRunning() } await Self.warmUpCaptureSession() - let tmpMovURL = FileManager.default.temporaryDirectory + let tmpMovURL = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-camera-\(UUID().uuidString).mov") - defer { try? FileManager.default.removeItem(at: tmpMovURL) } + defer { try? FileManager().removeItem(at: tmpMovURL) } let outputURL: URL = { if let outPath, !outPath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return URL(fileURLWithPath: outPath) } - return FileManager.default.temporaryDirectory + return FileManager().temporaryDirectory .appendingPathComponent("clawdbot-camera-\(UUID().uuidString).mp4") }() // Ensure we don't fail exporting due to an existing file. - try? FileManager.default.removeItem(at: outputURL) + try? FileManager().removeItem(at: outputURL) let logger = self.logger var delegate: MovieFileDelegate? diff --git a/apps/macos/Sources/Clawdbot/CanvasManager.swift b/apps/macos/Sources/Clawdbot/CanvasManager.swift index 2c0f73253..f65c123ca 100644 --- a/apps/macos/Sources/Clawdbot/CanvasManager.swift +++ b/apps/macos/Sources/Clawdbot/CanvasManager.swift @@ -1,5 +1,6 @@ import AppKit import ClawdbotIPC +import ClawdbotKit import Foundation import OSLog @@ -24,7 +25,7 @@ final class CanvasManager { var defaultAnchorProvider: (() -> NSRect?)? private nonisolated static let canvasRoot: URL = { - let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! + let base = FileManager().urls(for: .applicationSupportDirectory, in: .userDomainMask).first! return base.appendingPathComponent("Clawdbot/canvas", isDirectory: true) }() @@ -82,7 +83,7 @@ final class CanvasManager { self.panelSessionKey = nil Self.logger.debug("showDetailed ensure canvas root dir") - try FileManager.default.createDirectory(at: Self.canvasRoot, withIntermediateDirectories: true) + try FileManager().createDirectory(at: Self.canvasRoot, withIntermediateDirectories: true) Self.logger.debug("showDetailed init CanvasWindowController") let controller = try CanvasWindowController( sessionKey: session, @@ -257,7 +258,7 @@ final class CanvasManager { // (Avoid treating Canvas routes like "/" as filesystem paths.) if trimmed.hasPrefix("/") { var isDir: ObjCBool = false - if FileManager.default.fileExists(atPath: trimmed, isDirectory: &isDir), !isDir.boolValue { + if FileManager().fileExists(atPath: trimmed, isDirectory: &isDir), !isDir.boolValue { return URL(fileURLWithPath: trimmed) } } @@ -292,7 +293,7 @@ final class CanvasManager { } private static func localStatus(sessionDir: URL, target: String) -> CanvasShowStatus { - let fm = FileManager.default + let fm = FileManager() let trimmed = target.trimmingCharacters(in: .whitespacesAndNewlines) let withoutQuery = trimmed.split(separator: "?", maxSplits: 1, omittingEmptySubsequences: false).first .map(String.init) ?? trimmed @@ -330,7 +331,7 @@ final class CanvasManager { } private static func indexExists(in dir: URL) -> Bool { - let fm = FileManager.default + let fm = FileManager() let a = dir.appendingPathComponent("index.html", isDirectory: false) if fm.fileExists(atPath: a.path) { return true } let b = dir.appendingPathComponent("index.htm", isDirectory: false) diff --git a/apps/macos/Sources/Clawdbot/CanvasSchemeHandler.swift b/apps/macos/Sources/Clawdbot/CanvasSchemeHandler.swift index 8617a2d49..27dbd93bf 100644 --- a/apps/macos/Sources/Clawdbot/CanvasSchemeHandler.swift +++ b/apps/macos/Sources/Clawdbot/CanvasSchemeHandler.swift @@ -69,8 +69,8 @@ final class CanvasSchemeHandler: NSObject, WKURLSchemeHandler { if path.isEmpty { let indexA = sessionRoot.appendingPathComponent("index.html", isDirectory: false) let indexB = sessionRoot.appendingPathComponent("index.htm", isDirectory: false) - if !FileManager.default.fileExists(atPath: indexA.path), - !FileManager.default.fileExists(atPath: indexB.path) + if !FileManager().fileExists(atPath: indexA.path), + !FileManager().fileExists(atPath: indexB.path) { return self.scaffoldPage(sessionRoot: sessionRoot) } @@ -106,7 +106,7 @@ final class CanvasSchemeHandler: NSObject, WKURLSchemeHandler { } private func resolveFileURL(sessionRoot: URL, requestPath: String) -> URL? { - let fm = FileManager.default + let fm = FileManager() var candidate = sessionRoot.appendingPathComponent(requestPath, isDirectory: false) var isDir: ObjCBool = false @@ -137,7 +137,7 @@ final class CanvasSchemeHandler: NSObject, WKURLSchemeHandler { } private func resolveIndex(in dir: URL) -> URL? { - let fm = FileManager.default + let fm = FileManager() let a = dir.appendingPathComponent("index.html", isDirectory: false) if fm.fileExists(atPath: a.path) { return a } let b = dir.appendingPathComponent("index.htm", isDirectory: false) diff --git a/apps/macos/Sources/Clawdbot/CanvasWindowController.swift b/apps/macos/Sources/Clawdbot/CanvasWindowController.swift index d0d4e4ff5..b119efd85 100644 --- a/apps/macos/Sources/Clawdbot/CanvasWindowController.swift +++ b/apps/macos/Sources/Clawdbot/CanvasWindowController.swift @@ -32,7 +32,7 @@ final class CanvasWindowController: NSWindowController, WKNavigationDelegate, NS let safeSessionKey = CanvasWindowController.sanitizeSessionKey(sessionKey) canvasWindowLogger.debug("CanvasWindowController init sanitized session=\(safeSessionKey, privacy: .public)") self.sessionDir = root.appendingPathComponent(safeSessionKey, isDirectory: true) - try FileManager.default.createDirectory(at: self.sessionDir, withIntermediateDirectories: true) + try FileManager().createDirectory(at: self.sessionDir, withIntermediateDirectories: true) canvasWindowLogger.debug("CanvasWindowController init session dir ready") self.schemeHandler = CanvasSchemeHandler(root: root) @@ -143,8 +143,8 @@ final class CanvasWindowController: NSWindowController, WKNavigationDelegate, NS if path == "/" || path.isEmpty { let indexA = sessionDir.appendingPathComponent("index.html", isDirectory: false) let indexB = sessionDir.appendingPathComponent("index.htm", isDirectory: false) - if !FileManager.default.fileExists(atPath: indexA.path), - !FileManager.default.fileExists(atPath: indexB.path) + if !FileManager().fileExists(atPath: indexA.path), + !FileManager().fileExists(atPath: indexB.path) { return } @@ -233,7 +233,7 @@ final class CanvasWindowController: NSWindowController, WKNavigationDelegate, NS // (Avoid treating Canvas routes like "/" as filesystem paths.) if trimmed.hasPrefix("/") { var isDir: ObjCBool = false - if FileManager.default.fileExists(atPath: trimmed, isDirectory: &isDir), !isDir.boolValue { + if FileManager().fileExists(atPath: trimmed, isDirectory: &isDir), !isDir.boolValue { let url = URL(fileURLWithPath: trimmed) canvasWindowLogger.debug("canvas load file \(url.absoluteString, privacy: .public)") self.loadFile(url) diff --git a/apps/macos/Sources/Clawdbot/ChannelConfigForm.swift b/apps/macos/Sources/Clawdbot/ChannelConfigForm.swift new file mode 100644 index 000000000..d00725be7 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/ChannelConfigForm.swift @@ -0,0 +1,363 @@ +import SwiftUI + +struct ConfigSchemaForm: View { + @Bindable var store: ChannelsStore + let schema: ConfigSchemaNode + let path: ConfigPath + + var body: some View { + self.renderNode(self.schema, path: self.path) + } + + private func renderNode(_ schema: ConfigSchemaNode, path: ConfigPath) -> AnyView { + let storedValue = self.store.configValue(at: path) + let value = storedValue ?? schema.explicitDefault + let label = hintForPath(path, hints: store.configUiHints)?.label ?? schema.title + let help = hintForPath(path, hints: store.configUiHints)?.help ?? schema.description + let variants = schema.anyOf.isEmpty ? schema.oneOf : schema.anyOf + + if !variants.isEmpty { + let nonNull = variants.filter { !$0.isNullSchema } + if nonNull.count == 1, let only = nonNull.first { + return self.renderNode(only, path: path) + } + let literals = nonNull.compactMap(\.literalValue) + if !literals.isEmpty, literals.count == nonNull.count { + return AnyView( + VStack(alignment: .leading, spacing: 6) { + if let label { Text(label).font(.callout.weight(.semibold)) } + if let help { + Text(help) + .font(.caption) + .foregroundStyle(.secondary) + } + Picker( + "", + selection: self.enumBinding( + path, + options: literals, + defaultValue: schema.explicitDefault)) + { + Text("Select…").tag(-1) + ForEach(literals.indices, id: \ .self) { index in + Text(String(describing: literals[index])).tag(index) + } + } + .pickerStyle(.menu) + }) + } + } + + switch schema.schemaType { + case "object": + return AnyView( + VStack(alignment: .leading, spacing: 12) { + if let label { + Text(label) + .font(.callout.weight(.semibold)) + } + if let help { + Text(help) + .font(.caption) + .foregroundStyle(.secondary) + } + let properties = schema.properties + let sortedKeys = properties.keys.sorted { lhs, rhs in + let orderA = hintForPath(path + [.key(lhs)], hints: store.configUiHints)?.order ?? 0 + let orderB = hintForPath(path + [.key(rhs)], hints: store.configUiHints)?.order ?? 0 + if orderA != orderB { return orderA < orderB } + return lhs < rhs + } + ForEach(sortedKeys, id: \ .self) { key in + if let child = properties[key] { + self.renderNode(child, path: path + [.key(key)]) + } + } + if schema.allowsAdditionalProperties { + self.renderAdditionalProperties(schema, path: path, value: value) + } + }) + case "array": + return AnyView(self.renderArray(schema, path: path, value: value, label: label, help: help)) + case "boolean": + return AnyView( + Toggle(isOn: self.boolBinding(path, defaultValue: schema.explicitDefault as? Bool)) { + if let label { Text(label) } else { Text("Enabled") } + } + .help(help ?? "")) + case "number", "integer": + return AnyView(self.renderNumberField(schema, path: path, label: label, help: help)) + case "string": + return AnyView(self.renderStringField(schema, path: path, label: label, help: help)) + default: + return AnyView( + VStack(alignment: .leading, spacing: 6) { + if let label { Text(label).font(.callout.weight(.semibold)) } + Text("Unsupported field type.") + .font(.caption) + .foregroundStyle(.secondary) + }) + } + } + + @ViewBuilder + private func renderStringField( + _ schema: ConfigSchemaNode, + path: ConfigPath, + label: String?, + help: String?) -> some View + { + let hint = hintForPath(path, hints: store.configUiHints) + let placeholder = hint?.placeholder ?? "" + let sensitive = hint?.sensitive ?? isSensitivePath(path) + let defaultValue = schema.explicitDefault as? String + VStack(alignment: .leading, spacing: 6) { + if let label { Text(label).font(.callout.weight(.semibold)) } + if let help { + Text(help) + .font(.caption) + .foregroundStyle(.secondary) + } + if let options = schema.enumValues { + Picker("", selection: self.enumBinding(path, options: options, defaultValue: schema.explicitDefault)) { + Text("Select…").tag(-1) + ForEach(options.indices, id: \ .self) { index in + Text(String(describing: options[index])).tag(index) + } + } + .pickerStyle(.menu) + } else if sensitive { + SecureField(placeholder, text: self.stringBinding(path, defaultValue: defaultValue)) + .textFieldStyle(.roundedBorder) + } else { + TextField(placeholder, text: self.stringBinding(path, defaultValue: defaultValue)) + .textFieldStyle(.roundedBorder) + } + } + } + + @ViewBuilder + private func renderNumberField( + _ schema: ConfigSchemaNode, + path: ConfigPath, + label: String?, + help: String?) -> some View + { + let defaultValue = (schema.explicitDefault as? Double) + ?? (schema.explicitDefault as? Int).map(Double.init) + VStack(alignment: .leading, spacing: 6) { + if let label { Text(label).font(.callout.weight(.semibold)) } + if let help { + Text(help) + .font(.caption) + .foregroundStyle(.secondary) + } + TextField( + "", + text: self.numberBinding( + path, + isInteger: schema.schemaType == "integer", + defaultValue: defaultValue)) + .textFieldStyle(.roundedBorder) + } + } + + @ViewBuilder + private func renderArray( + _ schema: ConfigSchemaNode, + path: ConfigPath, + value: Any?, + label: String?, + help: String?) -> some View + { + let items = value as? [Any] ?? [] + let itemSchema = schema.items + VStack(alignment: .leading, spacing: 10) { + if let label { Text(label).font(.callout.weight(.semibold)) } + if let help { + Text(help) + .font(.caption) + .foregroundStyle(.secondary) + } + ForEach(items.indices, id: \ .self) { index in + HStack(alignment: .top, spacing: 8) { + if let itemSchema { + self.renderNode(itemSchema, path: path + [.index(index)]) + } else { + Text(String(describing: items[index])) + } + Button("Remove") { + var next = items + next.remove(at: index) + self.store.updateConfigValue(path: path, value: next) + } + .buttonStyle(.bordered) + .controlSize(.small) + } + } + Button("Add") { + var next = items + if let itemSchema { + next.append(itemSchema.defaultValue) + } else { + next.append("") + } + self.store.updateConfigValue(path: path, value: next) + } + .buttonStyle(.bordered) + .controlSize(.small) + } + } + + @ViewBuilder + private func renderAdditionalProperties( + _ schema: ConfigSchemaNode, + path: ConfigPath, + value: Any?) -> some View + { + if let additionalSchema = schema.additionalProperties { + let dict = value as? [String: Any] ?? [:] + let reserved = Set(schema.properties.keys) + let extras = dict.keys.filter { !reserved.contains($0) }.sorted() + + VStack(alignment: .leading, spacing: 8) { + Text("Extra entries") + .font(.callout.weight(.semibold)) + if extras.isEmpty { + Text("No extra entries yet.") + .font(.caption) + .foregroundStyle(.secondary) + } else { + ForEach(extras, id: \ .self) { key in + let itemPath: ConfigPath = path + [.key(key)] + HStack(alignment: .top, spacing: 8) { + TextField("Key", text: self.mapKeyBinding(path: path, key: key)) + .textFieldStyle(.roundedBorder) + .frame(width: 160) + self.renderNode(additionalSchema, path: itemPath) + Button("Remove") { + var next = dict + next.removeValue(forKey: key) + self.store.updateConfigValue(path: path, value: next) + } + .buttonStyle(.bordered) + .controlSize(.small) + } + } + } + Button("Add") { + var next = dict + var index = 1 + var key = "new-\(index)" + while next[key] != nil { + index += 1 + key = "new-\(index)" + } + next[key] = additionalSchema.defaultValue + self.store.updateConfigValue(path: path, value: next) + } + .buttonStyle(.bordered) + .controlSize(.small) + } + } + } + + private func stringBinding(_ path: ConfigPath, defaultValue: String?) -> Binding { + Binding( + get: { + if let value = store.configValue(at: path) as? String { return value } + return defaultValue ?? "" + }, + set: { newValue in + let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) + self.store.updateConfigValue(path: path, value: trimmed.isEmpty ? nil : trimmed) + }) + } + + private func boolBinding(_ path: ConfigPath, defaultValue: Bool?) -> Binding { + Binding( + get: { + if let value = store.configValue(at: path) as? Bool { return value } + return defaultValue ?? false + }, + set: { newValue in + self.store.updateConfigValue(path: path, value: newValue) + }) + } + + private func numberBinding( + _ path: ConfigPath, + isInteger: Bool, + defaultValue: Double?) -> Binding + { + Binding( + get: { + if let value = store.configValue(at: path) { return String(describing: value) } + guard let defaultValue else { return "" } + return isInteger ? String(Int(defaultValue)) : String(defaultValue) + }, + set: { newValue in + let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + self.store.updateConfigValue(path: path, value: nil) + } else if let value = Double(trimmed) { + self.store.updateConfigValue(path: path, value: isInteger ? Int(value) : value) + } + }) + } + + private func enumBinding( + _ path: ConfigPath, + options: [Any], + defaultValue: Any?) -> Binding + { + Binding( + get: { + let value = self.store.configValue(at: path) ?? defaultValue + guard let value else { return -1 } + return options.firstIndex { option in + String(describing: option) == String(describing: value) + } ?? -1 + }, + set: { index in + guard index >= 0, index < options.count else { + self.store.updateConfigValue(path: path, value: nil) + return + } + self.store.updateConfigValue(path: path, value: options[index]) + }) + } + + private func mapKeyBinding(path: ConfigPath, key: String) -> Binding { + Binding( + get: { key }, + set: { newValue in + let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + guard trimmed != key else { return } + let current = self.store.configValue(at: path) as? [String: Any] ?? [:] + guard current[trimmed] == nil else { return } + var next = current + next[trimmed] = current[key] + next.removeValue(forKey: key) + self.store.updateConfigValue(path: path, value: next) + }) + } +} + +struct ChannelConfigForm: View { + @Bindable var store: ChannelsStore + let channelId: String + + var body: some View { + if self.store.configSchemaLoading { + ProgressView().controlSize(.small) + } else if let schema = store.channelConfigSchema(for: channelId) { + ConfigSchemaForm(store: self.store, schema: schema, path: [.key("channels"), .key(self.channelId)]) + } else { + Text("Schema unavailable for this channel.") + .font(.caption) + .foregroundStyle(.secondary) + } + } +} diff --git a/apps/macos/Sources/Clawdbot/ChannelsSettings+ChannelSections.swift b/apps/macos/Sources/Clawdbot/ChannelsSettings+ChannelSections.swift new file mode 100644 index 000000000..ea82aac01 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/ChannelsSettings+ChannelSections.swift @@ -0,0 +1,139 @@ +import SwiftUI + +extension ChannelsSettings { + func formSection(_ title: String, @ViewBuilder content: () -> some View) -> some View { + GroupBox(title) { + VStack(alignment: .leading, spacing: 10) { + content() + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + + @ViewBuilder + func channelHeaderActions(_ channel: ChannelItem) -> some View { + HStack(spacing: 8) { + if channel.id == "whatsapp" { + Button("Logout") { + Task { await self.store.logoutWhatsApp() } + } + .buttonStyle(.bordered) + .disabled(self.store.whatsappBusy) + } + + if channel.id == "telegram" { + Button("Logout") { + Task { await self.store.logoutTelegram() } + } + .buttonStyle(.bordered) + .disabled(self.store.telegramBusy) + } + + Button { + Task { await self.store.refresh(probe: true) } + } label: { + if self.store.isRefreshing { + ProgressView().controlSize(.small) + } else { + Text("Refresh") + } + } + .buttonStyle(.bordered) + .disabled(self.store.isRefreshing) + } + .controlSize(.small) + } + + var whatsAppSection: some View { + VStack(alignment: .leading, spacing: 16) { + self.formSection("Linking") { + if let message = self.store.whatsappLoginMessage { + Text(message) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + + if let qr = self.store.whatsappLoginQrDataUrl, let image = self.qrImage(from: qr) { + Image(nsImage: image) + .resizable() + .interpolation(.none) + .frame(width: 180, height: 180) + .cornerRadius(8) + } + + HStack(spacing: 12) { + Button { + Task { await self.store.startWhatsAppLogin(force: false) } + } label: { + if self.store.whatsappBusy { + ProgressView().controlSize(.small) + } else { + Text("Show QR") + } + } + .buttonStyle(.borderedProminent) + .disabled(self.store.whatsappBusy) + + Button("Relink") { + Task { await self.store.startWhatsAppLogin(force: true) } + } + .buttonStyle(.bordered) + .disabled(self.store.whatsappBusy) + } + .font(.caption) + } + + self.configEditorSection(channelId: "whatsapp") + } + } + + @ViewBuilder + func genericChannelSection(_ channel: ChannelItem) -> some View { + VStack(alignment: .leading, spacing: 16) { + self.configEditorSection(channelId: channel.id) + } + } + + @ViewBuilder + private func configEditorSection(channelId: String) -> some View { + self.formSection("Configuration") { + ChannelConfigForm(store: self.store, channelId: channelId) + } + + self.configStatusMessage + + HStack(spacing: 12) { + Button { + Task { await self.store.saveConfigDraft() } + } label: { + if self.store.isSavingConfig { + ProgressView().controlSize(.small) + } else { + Text("Save") + } + } + .buttonStyle(.borderedProminent) + .disabled(self.store.isSavingConfig || !self.store.configDirty) + + Button("Reload") { + Task { await self.store.reloadConfigDraft() } + } + .buttonStyle(.bordered) + .disabled(self.store.isSavingConfig) + + Spacer() + } + .font(.caption) + } + + @ViewBuilder + var configStatusMessage: some View { + if let status = self.store.configStatus { + Text(status) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } +} diff --git a/apps/macos/Sources/Clawdbot/ConnectionsSettings+ChannelState.swift b/apps/macos/Sources/Clawdbot/ChannelsSettings+ChannelState.swift similarity index 62% rename from apps/macos/Sources/Clawdbot/ConnectionsSettings+ChannelState.swift rename to apps/macos/Sources/Clawdbot/ChannelsSettings+ChannelState.swift index 58d602223..efce42781 100644 --- a/apps/macos/Sources/Clawdbot/ConnectionsSettings+ChannelState.swift +++ b/apps/macos/Sources/Clawdbot/ChannelsSettings+ChannelState.swift @@ -1,6 +1,7 @@ +import ClawdbotProtocol import SwiftUI -extension ConnectionsSettings { +extension ChannelsSettings { private func channelStatus( _ id: String, as type: T.Type) -> T? @@ -39,6 +40,16 @@ extension ConnectionsSettings { return .orange } + var googlechatTint: Color { + guard let status = self.channelStatus("googlechat", as: ChannelsStatusSnapshot.GoogleChatStatus.self) + else { return .secondary } + if !status.configured { return .secondary } + if status.lastError != nil { return .orange } + if status.probe?.ok == false { return .orange } + if status.running { return .green } + return .orange + } + var signalTint: Color { guard let status = self.channelStatus("signal", as: ChannelsStatusSnapshot.SignalStatus.self) else { return .secondary } @@ -84,6 +95,14 @@ extension ConnectionsSettings { return "Configured" } + var googlechatSummary: String { + guard let status = self.channelStatus("googlechat", as: ChannelsStatusSnapshot.GoogleChatStatus.self) + else { return "Checking…" } + if !status.configured { return "Not configured" } + if status.running { return "Running" } + return "Configured" + } + var signalSummary: String { guard let status = self.channelStatus("signal", as: ChannelsStatusSnapshot.SignalStatus.self) else { return "Checking…" } @@ -192,6 +211,37 @@ extension ConnectionsSettings { return lines.isEmpty ? nil : lines.joined(separator: " · ") } + var googlechatDetails: String? { + guard let status = self.channelStatus("googlechat", as: ChannelsStatusSnapshot.GoogleChatStatus.self) + else { return nil } + var lines: [String] = [] + if let source = status.credentialSource { + lines.append("Credential: \(source)") + } + if let audienceType = status.audienceType { + let audience = status.audience ?? "" + let label = audience.isEmpty ? audienceType : "\(audienceType) \(audience)" + lines.append("Audience: \(label)") + } + if let probe = status.probe { + if probe.ok { + if let elapsed = probe.elapsedMs { + lines.append("Probe \(Int(elapsed))ms") + } + } else { + let code = probe.status.map { String($0) } ?? "unknown" + lines.append("Probe failed (\(code))") + } + } + if let last = self.date(fromMs: status.lastProbeAt) { + lines.append("Last probe \(relativeAge(from: last))") + } + if let err = status.lastError, !err.isEmpty { + lines.append("Error: \(err)") + } + return lines.isEmpty ? nil : lines.joined(separator: " · ") + } + var signalDetails: String? { guard let status = self.channelStatus("signal", as: ChannelsStatusSnapshot.SignalStatus.self) else { return nil } @@ -242,16 +292,18 @@ extension ConnectionsSettings { return lines.isEmpty ? nil : lines.joined(separator: " · ") } - var isTelegramTokenLocked: Bool { - self.channelStatus("telegram", as: ChannelsStatusSnapshot.TelegramStatus.self)?.tokenSource == "env" - } - - var isDiscordTokenLocked: Bool { - self.channelStatus("discord", as: ChannelsStatusSnapshot.DiscordStatus.self)?.tokenSource == "env" - } - - var orderedChannels: [ConnectionChannel] { - ConnectionChannel.allCases.sorted { lhs, rhs in + var orderedChannels: [ChannelItem] { + let fallback = ["whatsapp", "telegram", "discord", "googlechat", "slack", "signal", "imessage"] + let order = self.store.snapshot?.channelOrder ?? fallback + let channels = order.enumerated().map { index, id in + ChannelItem( + id: id, + title: self.resolveChannelTitle(id), + detailTitle: self.resolveChannelDetailTitle(id), + systemImage: self.resolveChannelSystemImage(id), + sortOrder: index) + } + return channels.sorted { lhs, rhs in let lhsEnabled = self.channelEnabled(lhs) let rhsEnabled = self.channelEnabled(rhs) if lhsEnabled != rhsEnabled { return lhsEnabled && !rhsEnabled } @@ -259,11 +311,11 @@ extension ConnectionsSettings { } } - var enabledChannels: [ConnectionChannel] { + var enabledChannels: [ChannelItem] { self.orderedChannels.filter { self.channelEnabled($0) } } - var availableChannels: [ConnectionChannel] { + var availableChannels: [ChannelItem] { self.orderedChannels.filter { !self.channelEnabled($0) } } @@ -277,143 +329,180 @@ extension ConnectionsSettings { } } - func channelEnabled(_ channel: ConnectionChannel) -> Bool { - switch channel { - case .whatsapp: - guard let status = self.channelStatus("whatsapp", as: ChannelsStatusSnapshot.WhatsAppStatus.self) - else { return false } - return status.configured || status.linked || status.running - case .telegram: - guard let status = self.channelStatus("telegram", as: ChannelsStatusSnapshot.TelegramStatus.self) - else { return false } - return status.configured || status.running - case .discord: - guard let status = self.channelStatus("discord", as: ChannelsStatusSnapshot.DiscordStatus.self) - else { return false } - return status.configured || status.running - case .signal: - guard let status = self.channelStatus("signal", as: ChannelsStatusSnapshot.SignalStatus.self) - else { return false } - return status.configured || status.running - case .imessage: - guard let status = self.channelStatus("imessage", as: ChannelsStatusSnapshot.IMessageStatus.self) - else { return false } - return status.configured || status.running - } + func channelEnabled(_ channel: ChannelItem) -> Bool { + let status = self.channelStatusDictionary(channel.id) + let configured = status?["configured"]?.boolValue ?? false + let running = status?["running"]?.boolValue ?? false + let connected = status?["connected"]?.boolValue ?? false + let accountActive = self.store.snapshot?.channelAccounts[channel.id]?.contains( + where: { $0.configured == true || $0.running == true || $0.connected == true }) ?? false + return configured || running || connected || accountActive } @ViewBuilder - func channelSection(_ channel: ConnectionChannel) -> some View { - switch channel { - case .whatsapp: + func channelSection(_ channel: ChannelItem) -> some View { + if channel.id == "whatsapp" { self.whatsAppSection - case .telegram: - self.telegramSection - case .discord: - self.discordSection - case .signal: - self.signalSection - case .imessage: - self.imessageSection + } else { + self.genericChannelSection(channel) } } - func channelTint(_ channel: ConnectionChannel) -> Color { - switch channel { - case .whatsapp: - self.whatsAppTint - case .telegram: - self.telegramTint - case .discord: - self.discordTint - case .signal: - self.signalTint - case .imessage: - self.imessageTint + func channelTint(_ channel: ChannelItem) -> Color { + switch channel.id { + case "whatsapp": + return self.whatsAppTint + case "telegram": + return self.telegramTint + case "discord": + return self.discordTint + case "googlechat": + return self.googlechatTint + case "signal": + return self.signalTint + case "imessage": + return self.imessageTint + default: + if self.channelHasError(channel) { return .orange } + if self.channelEnabled(channel) { return .green } + return .secondary } } - func channelSummary(_ channel: ConnectionChannel) -> String { - switch channel { - case .whatsapp: - self.whatsAppSummary - case .telegram: - self.telegramSummary - case .discord: - self.discordSummary - case .signal: - self.signalSummary - case .imessage: - self.imessageSummary + func channelSummary(_ channel: ChannelItem) -> String { + switch channel.id { + case "whatsapp": + return self.whatsAppSummary + case "telegram": + return self.telegramSummary + case "discord": + return self.discordSummary + case "googlechat": + return self.googlechatSummary + case "signal": + return self.signalSummary + case "imessage": + return self.imessageSummary + default: + if self.channelHasError(channel) { return "Error" } + if self.channelEnabled(channel) { return "Active" } + return "Not configured" } } - func channelDetails(_ channel: ConnectionChannel) -> String? { - switch channel { - case .whatsapp: - self.whatsAppDetails - case .telegram: - self.telegramDetails - case .discord: - self.discordDetails - case .signal: - self.signalDetails - case .imessage: - self.imessageDetails + func channelDetails(_ channel: ChannelItem) -> String? { + switch channel.id { + case "whatsapp": + return self.whatsAppDetails + case "telegram": + return self.telegramDetails + case "discord": + return self.discordDetails + case "googlechat": + return self.googlechatDetails + case "signal": + return self.signalDetails + case "imessage": + return self.imessageDetails + default: + let status = self.channelStatusDictionary(channel.id) + if let err = status?["lastError"]?.stringValue, !err.isEmpty { + return "Error: \(err)" + } + return nil } } - func channelLastCheckText(_ channel: ConnectionChannel) -> String { + func channelLastCheckText(_ channel: ChannelItem) -> String { guard let date = self.channelLastCheck(channel) else { return "never" } return relativeAge(from: date) } - func channelLastCheck(_ channel: ConnectionChannel) -> Date? { - switch channel { - case .whatsapp: + func channelLastCheck(_ channel: ChannelItem) -> Date? { + switch channel.id { + case "whatsapp": guard let status = self.channelStatus("whatsapp", as: ChannelsStatusSnapshot.WhatsAppStatus.self) else { return nil } return self.date(fromMs: status.lastEventAt ?? status.lastMessageAt ?? status.lastConnectedAt) - case .telegram: + case "telegram": return self .date(fromMs: self.channelStatus("telegram", as: ChannelsStatusSnapshot.TelegramStatus.self)? .lastProbeAt) - case .discord: + case "discord": return self .date(fromMs: self.channelStatus("discord", as: ChannelsStatusSnapshot.DiscordStatus.self)? .lastProbeAt) - case .signal: + case "googlechat": + return self + .date(fromMs: self.channelStatus("googlechat", as: ChannelsStatusSnapshot.GoogleChatStatus.self)? + .lastProbeAt) + case "signal": return self .date(fromMs: self.channelStatus("signal", as: ChannelsStatusSnapshot.SignalStatus.self)?.lastProbeAt) - case .imessage: + case "imessage": return self .date(fromMs: self.channelStatus("imessage", as: ChannelsStatusSnapshot.IMessageStatus.self)? .lastProbeAt) + default: + let status = self.channelStatusDictionary(channel.id) + if let probeAt = status?["lastProbeAt"]?.doubleValue { + return self.date(fromMs: probeAt) + } + if let accounts = self.store.snapshot?.channelAccounts[channel.id] { + let last = accounts.compactMap { $0.lastInboundAt ?? $0.lastOutboundAt }.max() + return self.date(fromMs: last) + } + return nil } } - func channelHasError(_ channel: ConnectionChannel) -> Bool { - switch channel { - case .whatsapp: + func channelHasError(_ channel: ChannelItem) -> Bool { + switch channel.id { + case "whatsapp": guard let status = self.channelStatus("whatsapp", as: ChannelsStatusSnapshot.WhatsAppStatus.self) else { return false } return status.lastError?.isEmpty == false || status.lastDisconnect?.loggedOut == true - case .telegram: + case "telegram": guard let status = self.channelStatus("telegram", as: ChannelsStatusSnapshot.TelegramStatus.self) else { return false } return status.lastError?.isEmpty == false || status.probe?.ok == false - case .discord: + case "discord": guard let status = self.channelStatus("discord", as: ChannelsStatusSnapshot.DiscordStatus.self) else { return false } return status.lastError?.isEmpty == false || status.probe?.ok == false - case .signal: + case "googlechat": + guard let status = self.channelStatus("googlechat", as: ChannelsStatusSnapshot.GoogleChatStatus.self) + else { return false } + return status.lastError?.isEmpty == false || status.probe?.ok == false + case "signal": guard let status = self.channelStatus("signal", as: ChannelsStatusSnapshot.SignalStatus.self) else { return false } return status.lastError?.isEmpty == false || status.probe?.ok == false - case .imessage: + case "imessage": guard let status = self.channelStatus("imessage", as: ChannelsStatusSnapshot.IMessageStatus.self) else { return false } return status.lastError?.isEmpty == false || status.probe?.ok == false + default: + let status = self.channelStatusDictionary(channel.id) + return status?["lastError"]?.stringValue?.isEmpty == false } } + + private func resolveChannelTitle(_ id: String) -> String { + let label = self.store.resolveChannelLabel(id) + if label != id { return label } + return id.prefix(1).uppercased() + id.dropFirst() + } + + private func resolveChannelDetailTitle(_ id: String) -> String { + self.store.resolveChannelDetailLabel(id) + } + + private func resolveChannelSystemImage(_ id: String) -> String { + self.store.resolveChannelSystemImage(id) + } + + private func channelStatusDictionary(_ id: String) -> [String: AnyCodable]? { + self.store.snapshot?.channels[id]?.dictionaryValue + } } diff --git a/apps/macos/Sources/Clawdbot/ConnectionsSettings+Helpers.swift b/apps/macos/Sources/Clawdbot/ChannelsSettings+Helpers.swift similarity index 94% rename from apps/macos/Sources/Clawdbot/ConnectionsSettings+Helpers.swift rename to apps/macos/Sources/Clawdbot/ChannelsSettings+Helpers.swift index abfdb61de..05b79ca04 100644 --- a/apps/macos/Sources/Clawdbot/ConnectionsSettings+Helpers.swift +++ b/apps/macos/Sources/Clawdbot/ChannelsSettings+Helpers.swift @@ -1,6 +1,6 @@ import AppKit -extension ConnectionsSettings { +extension ChannelsSettings { func date(fromMs ms: Double?) -> Date? { guard let ms else { return nil } return Date(timeIntervalSince1970: ms / 1000) diff --git a/apps/macos/Sources/Clawdbot/ConnectionsSettings+View.swift b/apps/macos/Sources/Clawdbot/ChannelsSettings+View.swift similarity index 95% rename from apps/macos/Sources/Clawdbot/ConnectionsSettings+View.swift rename to apps/macos/Sources/Clawdbot/ChannelsSettings+View.swift index 817c719eb..d1ed16bf6 100644 --- a/apps/macos/Sources/Clawdbot/ConnectionsSettings+View.swift +++ b/apps/macos/Sources/Clawdbot/ChannelsSettings+View.swift @@ -1,6 +1,6 @@ import SwiftUI -extension ConnectionsSettings { +extension ChannelsSettings { var body: some View { HStack(spacing: 0) { self.sidebar @@ -57,7 +57,7 @@ extension ConnectionsSettings { private var emptyDetail: some View { VStack(alignment: .leading, spacing: 8) { - Text("Connections") + Text("Channels") .font(.title3.weight(.semibold)) Text("Select a channel to view status and settings.") .font(.callout) @@ -67,7 +67,7 @@ extension ConnectionsSettings { .padding(.vertical, 18) } - private func channelDetail(_ channel: ConnectionChannel) -> some View { + private func channelDetail(_ channel: ChannelItem) -> some View { ScrollView(.vertical) { VStack(alignment: .leading, spacing: 16) { self.detailHeader(for: channel) @@ -81,7 +81,7 @@ extension ConnectionsSettings { } } - private func sidebarRow(_ channel: ConnectionChannel) -> some View { + private func sidebarRow(_ channel: ChannelItem) -> some View { let isSelected = self.selectedChannel == channel return Button { self.selectedChannel = channel @@ -119,7 +119,7 @@ extension ConnectionsSettings { .padding(.top, 2) } - private func detailHeader(for channel: ConnectionChannel) -> some View { + private func detailHeader(for channel: ChannelItem) -> some View { VStack(alignment: .leading, spacing: 8) { HStack(alignment: .firstTextBaseline, spacing: 10) { Label(channel.detailTitle, systemImage: channel.systemImage) diff --git a/apps/macos/Sources/Clawdbot/ChannelsSettings.swift b/apps/macos/Sources/Clawdbot/ChannelsSettings.swift new file mode 100644 index 000000000..b1177f003 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/ChannelsSettings.swift @@ -0,0 +1,19 @@ +import AppKit +import SwiftUI + +struct ChannelsSettings: View { + struct ChannelItem: Identifiable, Hashable { + let id: String + let title: String + let detailTitle: String + let systemImage: String + let sortOrder: Int + } + + @Bindable var store: ChannelsStore + @State var selectedChannel: ChannelItem? + + init(store: ChannelsStore = .shared) { + self.store = store + } +} diff --git a/apps/macos/Sources/Clawdbot/ChannelsStore+Config.swift b/apps/macos/Sources/Clawdbot/ChannelsStore+Config.swift new file mode 100644 index 000000000..c4c73b769 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/ChannelsStore+Config.swift @@ -0,0 +1,154 @@ +import ClawdbotProtocol +import Foundation + +extension ChannelsStore { + func loadConfigSchema() async { + guard !self.configSchemaLoading else { return } + self.configSchemaLoading = true + defer { self.configSchemaLoading = false } + + do { + let res: ConfigSchemaResponse = try await GatewayConnection.shared.requestDecoded( + method: .configSchema, + params: nil, + timeoutMs: 8000) + let schemaValue = res.schema.foundationValue + self.configSchema = ConfigSchemaNode(raw: schemaValue) + let hintValues = res.uihints.mapValues { $0.foundationValue } + self.configUiHints = decodeUiHints(hintValues) + } catch { + self.configStatus = error.localizedDescription + } + } + + func loadConfig() async { + do { + let snap: ConfigSnapshot = try await GatewayConnection.shared.requestDecoded( + method: .configGet, + params: nil, + timeoutMs: 10000) + self.configStatus = snap.valid == false + ? "Config invalid; fix it in ~/.clawdbot/clawdbot.json." + : nil + self.configRoot = snap.config?.mapValues { $0.foundationValue } ?? [:] + self.configDraft = cloneConfigValue(self.configRoot) as? [String: Any] ?? self.configRoot + self.configDirty = false + self.configLoaded = true + + self.applyUIConfig(snap) + } catch { + self.configStatus = error.localizedDescription + } + } + + private func applyUIConfig(_ snap: ConfigSnapshot) { + let ui = snap.config?["ui"]?.dictionaryValue + let rawSeam = ui?["seamColor"]?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + AppStateStore.shared.seamColorHex = rawSeam.isEmpty ? nil : rawSeam + } + + func channelConfigSchema(for channelId: String) -> ConfigSchemaNode? { + guard let root = self.configSchema else { return nil } + return root.node(at: [.key("channels"), .key(channelId)]) + } + + func configValue(at path: ConfigPath) -> Any? { + if let value = valueAtPath(self.configDraft, path: path) { + return value + } + guard path.count >= 2 else { return nil } + if case .key("channels") = path[0], case .key = path[1] { + let fallbackPath = Array(path.dropFirst()) + return valueAtPath(self.configDraft, path: fallbackPath) + } + return nil + } + + func updateConfigValue(path: ConfigPath, value: Any?) { + var root: Any = self.configDraft + setValue(&root, path: path, value: value) + self.configDraft = root as? [String: Any] ?? self.configDraft + self.configDirty = true + } + + func saveConfigDraft() async { + guard !self.isSavingConfig else { return } + self.isSavingConfig = true + defer { self.isSavingConfig = false } + + do { + try await ConfigStore.save(self.configDraft) + await self.loadConfig() + } catch { + self.configStatus = error.localizedDescription + } + } + + func reloadConfigDraft() async { + await self.loadConfig() + } +} + +private func valueAtPath(_ root: Any, path: ConfigPath) -> Any? { + var current: Any? = root + for segment in path { + switch segment { + case let .key(key): + guard let dict = current as? [String: Any] else { return nil } + current = dict[key] + case let .index(index): + guard let array = current as? [Any], array.indices.contains(index) else { return nil } + current = array[index] + } + } + return current +} + +private func setValue(_ root: inout Any, path: ConfigPath, value: Any?) { + guard let segment = path.first else { return } + switch segment { + case let .key(key): + var dict = root as? [String: Any] ?? [:] + if path.count == 1 { + if let value { + dict[key] = value + } else { + dict.removeValue(forKey: key) + } + root = dict + return + } + var child = dict[key] ?? [:] + setValue(&child, path: Array(path.dropFirst()), value: value) + dict[key] = child + root = dict + case let .index(index): + var array = root as? [Any] ?? [] + if index >= array.count { + array.append(contentsOf: repeatElement(NSNull() as Any, count: index - array.count + 1)) + } + if path.count == 1 { + if let value { + array[index] = value + } else if array.indices.contains(index) { + array.remove(at: index) + } + root = array + return + } + var child = array[index] + setValue(&child, path: Array(path.dropFirst()), value: value) + array[index] = child + root = array + } +} + +private func cloneConfigValue(_ value: Any) -> Any { + guard JSONSerialization.isValidJSONObject(value) else { return value } + do { + let data = try JSONSerialization.data(withJSONObject: value, options: []) + return try JSONSerialization.jsonObject(with: data, options: []) + } catch { + return value + } +} diff --git a/apps/macos/Sources/Clawdbot/ConnectionsStore+Lifecycle.swift b/apps/macos/Sources/Clawdbot/ChannelsStore+Lifecycle.swift similarity index 98% rename from apps/macos/Sources/Clawdbot/ConnectionsStore+Lifecycle.swift rename to apps/macos/Sources/Clawdbot/ChannelsStore+Lifecycle.swift index f24cc3dfb..9ebed11a9 100644 --- a/apps/macos/Sources/Clawdbot/ConnectionsStore+Lifecycle.swift +++ b/apps/macos/Sources/Clawdbot/ChannelsStore+Lifecycle.swift @@ -1,13 +1,14 @@ import ClawdbotProtocol import Foundation -extension ConnectionsStore { +extension ChannelsStore { func start() { guard !self.isPreview else { return } guard self.pollTask == nil else { return } self.pollTask = Task.detached { [weak self] in guard let self else { return } await self.refresh(probe: true) + await self.loadConfigSchema() await self.loadConfig() while !Task.isCancelled { try? await Task.sleep(nanoseconds: UInt64(self.interval * 1_000_000_000)) diff --git a/apps/macos/Sources/Clawdbot/ConnectionsStore.swift b/apps/macos/Sources/Clawdbot/ChannelsStore.swift similarity index 62% rename from apps/macos/Sources/Clawdbot/ConnectionsStore.swift rename to apps/macos/Sources/Clawdbot/ChannelsStore.swift index fe0aa337b..1cbeca381 100644 --- a/apps/macos/Sources/Clawdbot/ConnectionsStore.swift +++ b/apps/macos/Sources/Clawdbot/ChannelsStore.swift @@ -85,6 +85,28 @@ struct ChannelsStatusSnapshot: Codable { let lastProbeAt: Double? } + struct GoogleChatProbe: Codable { + let ok: Bool + let status: Int? + let error: String? + let elapsedMs: Double? + } + + struct GoogleChatStatus: Codable { + let configured: Bool + let credentialSource: String? + let audienceType: String? + let audience: String? + let webhookPath: String? + let webhookUrl: String? + let running: Bool + let lastStartAt: Double? + let lastStopAt: Double? + let lastError: String? + let probe: GoogleChatProbe? + let lastProbeAt: Double? + } + struct SignalProbe: Codable { let ok: Bool let status: Int? @@ -153,9 +175,19 @@ struct ChannelsStatusSnapshot: Codable { let application: AnyCodable? } + struct ChannelUiMetaEntry: Codable { + let id: String + let label: String + let detailLabel: String + let systemImage: String? + } + let ts: Double let channelOrder: [String] let channelLabels: [String: String] + let channelDetailLabels: [String: String]? + let channelSystemImages: [String: String]? + let channelMeta: [ChannelUiMetaEntry]? let channels: [String: AnyCodable] let channelAccounts: [String: [ChannelAccountSnapshot]] let channelDefaultAccountId: [String: String] @@ -187,49 +219,10 @@ struct ConfigSnapshot: Codable { let issues: [Issue]? } -struct DiscordGuildChannelForm: Identifiable { - let id = UUID() - var key: String - var allow: Bool - var requireMention: Bool - - init(key: String = "", allow: Bool = true, requireMention: Bool = false) { - self.key = key - self.allow = allow - self.requireMention = requireMention - } -} - -struct DiscordGuildForm: Identifiable { - let id = UUID() - var key: String - var slug: String - var requireMention: Bool - var reactionNotifications: String - var users: String - var channels: [DiscordGuildChannelForm] - - init( - key: String = "", - slug: String = "", - requireMention: Bool = false, - reactionNotifications: String = "own", - users: String = "", - channels: [DiscordGuildChannelForm] = []) - { - self.key = key - self.slug = slug - self.requireMention = requireMention - self.reactionNotifications = reactionNotifications - self.users = users - self.channels = channels - } -} - @MainActor @Observable -final class ConnectionsStore { - static let shared = ConnectionsStore() +final class ChannelsStore { + static let shared = ChannelsStore() var snapshot: ChannelsStatusSnapshot? var lastError: String? @@ -240,75 +233,62 @@ final class ConnectionsStore { var whatsappLoginQrDataUrl: String? var whatsappLoginConnected: Bool? var whatsappBusy = false - - var telegramToken: String = "" - var telegramRequireMention = true - var telegramAllowFrom: String = "" - var telegramProxy: String = "" - var telegramWebhookUrl: String = "" - var telegramWebhookSecret: String = "" - var telegramWebhookPath: String = "" var telegramBusy = false - var discordEnabled = true - var discordToken: String = "" - var discordDmEnabled = true - var discordAllowFrom: String = "" - var discordGroupEnabled = false - var discordGroupChannels: String = "" - var discordMediaMaxMb: String = "" - var discordHistoryLimit: String = "" - var discordTextChunkLimit: String = "" - var discordReplyToMode: String = "off" - var discordGuilds: [DiscordGuildForm] = [] - var discordActionReactions = true - var discordActionStickers = true - var discordActionPolls = true - var discordActionPermissions = true - var discordActionMessages = true - var discordActionThreads = true - var discordActionPins = true - var discordActionSearch = true - var discordActionMemberInfo = true - var discordActionRoleInfo = true - var discordActionChannelInfo = true - var discordActionVoiceStatus = true - var discordActionEvents = true - var discordActionRoles = false - var discordActionModeration = false - var discordSlashEnabled = false - var discordSlashName: String = "" - var discordSlashSessionPrefix: String = "" - var discordSlashEphemeral = true - var signalEnabled = true - var signalAccount: String = "" - var signalHttpUrl: String = "" - var signalHttpHost: String = "" - var signalHttpPort: String = "" - var signalCliPath: String = "" - var signalAutoStart = true - var signalReceiveMode: String = "" - var signalIgnoreAttachments = false - var signalIgnoreStories = false - var signalSendReadReceipts = false - var signalAllowFrom: String = "" - var signalMediaMaxMb: String = "" - var imessageEnabled = true - var imessageCliPath: String = "" - var imessageDbPath: String = "" - var imessageService: String = "auto" - var imessageRegion: String = "" - var imessageAllowFrom: String = "" - var imessageIncludeAttachments = false - var imessageMediaMaxMb: String = "" + var configStatus: String? var isSavingConfig = false + var configSchemaLoading = false + var configSchema: ConfigSchemaNode? + var configUiHints: [String: ConfigUiHint] = [:] + var configDraft: [String: Any] = [:] + var configDirty = false let interval: TimeInterval = 45 let isPreview: Bool var pollTask: Task? var configRoot: [String: Any] = [:] var configLoaded = false - var configHash: String? + + func channelMetaEntry(_ id: String) -> ChannelsStatusSnapshot.ChannelUiMetaEntry? { + self.snapshot?.channelMeta?.first(where: { $0.id == id }) + } + + func resolveChannelLabel(_ id: String) -> String { + if let meta = self.channelMetaEntry(id), !meta.label.isEmpty { + return meta.label + } + if let label = self.snapshot?.channelLabels[id], !label.isEmpty { + return label + } + return id + } + + func resolveChannelDetailLabel(_ id: String) -> String { + if let meta = self.channelMetaEntry(id), !meta.detailLabel.isEmpty { + return meta.detailLabel + } + if let detail = self.snapshot?.channelDetailLabels?[id], !detail.isEmpty { + return detail + } + return self.resolveChannelLabel(id) + } + + func resolveChannelSystemImage(_ id: String) -> String { + if let meta = self.channelMetaEntry(id), let symbol = meta.systemImage, !symbol.isEmpty { + return symbol + } + if let symbol = self.snapshot?.channelSystemImages?[id], !symbol.isEmpty { + return symbol + } + return "message" + } + + func orderedChannelIds() -> [String] { + if let meta = self.snapshot?.channelMeta, !meta.isEmpty { + return meta.map(\.id) + } + return self.snapshot?.channelOrder ?? [] + } init(isPreview: Bool = ProcessInfo.processInfo.isPreview) { self.isPreview = isPreview diff --git a/apps/macos/Sources/Clawdbot/ClawdbotConfigFile.swift b/apps/macos/Sources/Clawdbot/ClawdbotConfigFile.swift index 6b2169010..1c054b557 100644 --- a/apps/macos/Sources/Clawdbot/ClawdbotConfigFile.swift +++ b/apps/macos/Sources/Clawdbot/ClawdbotConfigFile.swift @@ -18,7 +18,7 @@ enum ClawdbotConfigFile { static func loadDict() -> [String: Any] { let url = self.url() - guard FileManager.default.fileExists(atPath: url.path) else { return [:] } + guard FileManager().fileExists(atPath: url.path) else { return [:] } do { let data = try Data(contentsOf: url) guard let root = self.parseConfigData(data) else { @@ -38,7 +38,7 @@ enum ClawdbotConfigFile { do { let data = try JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted, .sortedKeys]) let url = self.url() - try FileManager.default.createDirectory( + try FileManager().createDirectory( at: url.deletingLastPathComponent(), withIntermediateDirectories: true) try data.write(to: url, options: [.atomic]) diff --git a/apps/macos/Sources/Clawdbot/ClawdbotPaths.swift b/apps/macos/Sources/Clawdbot/ClawdbotPaths.swift index 3e32782c0..7cda49ea6 100644 --- a/apps/macos/Sources/Clawdbot/ClawdbotPaths.swift +++ b/apps/macos/Sources/Clawdbot/ClawdbotPaths.swift @@ -21,7 +21,7 @@ enum ClawdbotPaths { if let override = ClawdbotEnv.path(self.stateDirEnv) { return URL(fileURLWithPath: override, isDirectory: true) } - return FileManager.default.homeDirectoryForCurrentUser + return FileManager().homeDirectoryForCurrentUser .appendingPathComponent(".clawdbot", isDirectory: true) } diff --git a/apps/macos/Sources/Clawdbot/CommandResolver.swift b/apps/macos/Sources/Clawdbot/CommandResolver.swift index f4fb5c2b1..7661c48f1 100644 --- a/apps/macos/Sources/Clawdbot/CommandResolver.swift +++ b/apps/macos/Sources/Clawdbot/CommandResolver.swift @@ -6,9 +6,9 @@ enum CommandResolver { static func gatewayEntrypoint(in root: URL) -> String? { let distEntry = root.appendingPathComponent("dist/index.js").path - if FileManager.default.isReadableFile(atPath: distEntry) { return distEntry } + if FileManager().isReadableFile(atPath: distEntry) { return distEntry } let binEntry = root.appendingPathComponent("bin/clawdbot.js").path - if FileManager.default.isReadableFile(atPath: binEntry) { return binEntry } + if FileManager().isReadableFile(atPath: binEntry) { return binEntry } return nil } @@ -47,16 +47,16 @@ enum CommandResolver { static func projectRoot() -> URL { if let stored = UserDefaults.standard.string(forKey: self.projectRootDefaultsKey), let url = self.expandPath(stored), - FileManager.default.fileExists(atPath: url.path) + FileManager().fileExists(atPath: url.path) { return url } - let fallback = FileManager.default.homeDirectoryForCurrentUser + let fallback = FileManager().homeDirectoryForCurrentUser .appendingPathComponent("Projects/clawdbot") - if FileManager.default.fileExists(atPath: fallback.path) { + if FileManager().fileExists(atPath: fallback.path) { return fallback } - return FileManager.default.homeDirectoryForCurrentUser + return FileManager().homeDirectoryForCurrentUser } static func setProjectRoot(_ path: String) { @@ -70,7 +70,7 @@ enum CommandResolver { static func preferredPaths() -> [String] { let current = ProcessInfo.processInfo.environment["PATH"]? .split(separator: ":").map(String.init) ?? [] - let home = FileManager.default.homeDirectoryForCurrentUser + let home = FileManager().homeDirectoryForCurrentUser let projectRoot = self.projectRoot() return self.preferredPaths(home: home, current: current, projectRoot: projectRoot) } @@ -99,10 +99,10 @@ enum CommandResolver { let bin = base.appendingPathComponent("bin") let nodeBin = base.appendingPathComponent("tools/node/bin") var paths: [String] = [] - if FileManager.default.fileExists(atPath: bin.path) { + if FileManager().fileExists(atPath: bin.path) { paths.append(bin.path) } - if FileManager.default.fileExists(atPath: nodeBin.path) { + if FileManager().fileExists(atPath: nodeBin.path) { paths.append(nodeBin.path) } return paths @@ -113,13 +113,13 @@ enum CommandResolver { // Volta let volta = home.appendingPathComponent(".volta/bin") - if FileManager.default.fileExists(atPath: volta.path) { + if FileManager().fileExists(atPath: volta.path) { bins.append(volta.path) } // asdf let asdf = home.appendingPathComponent(".asdf/shims") - if FileManager.default.fileExists(atPath: asdf.path) { + if FileManager().fileExists(atPath: asdf.path) { bins.append(asdf.path) } @@ -137,10 +137,10 @@ enum CommandResolver { } private static func versionedNodeBinPaths(base: URL, suffix: String) -> [String] { - guard FileManager.default.fileExists(atPath: base.path) else { return [] } + guard FileManager().fileExists(atPath: base.path) else { return [] } let entries: [String] do { - entries = try FileManager.default.contentsOfDirectory(atPath: base.path) + entries = try FileManager().contentsOfDirectory(atPath: base.path) } catch { return [] } @@ -167,7 +167,7 @@ enum CommandResolver { for entry in sorted { let binDir = base.appendingPathComponent(entry).appendingPathComponent(suffix) let node = binDir.appendingPathComponent("node") - if FileManager.default.isExecutableFile(atPath: node.path) { + if FileManager().isExecutableFile(atPath: node.path) { paths.append(binDir.path) } } @@ -177,7 +177,7 @@ enum CommandResolver { static func findExecutable(named name: String, searchPaths: [String]? = nil) -> String? { for dir in searchPaths ?? self.preferredPaths() { let candidate = (dir as NSString).appendingPathComponent(name) - if FileManager.default.isExecutableFile(atPath: candidate) { + if FileManager().isExecutableFile(atPath: candidate) { return candidate } } @@ -191,12 +191,12 @@ enum CommandResolver { static func projectClawdbotExecutable(projectRoot: URL? = nil) -> String? { let root = projectRoot ?? self.projectRoot() let candidate = root.appendingPathComponent("node_modules/.bin").appendingPathComponent(self.helperName).path - return FileManager.default.isExecutableFile(atPath: candidate) ? candidate : nil + return FileManager().isExecutableFile(atPath: candidate) ? candidate : nil } static func nodeCliPath() -> String? { let candidate = self.projectRoot().appendingPathComponent("bin/clawdbot.js").path - return FileManager.default.isReadableFile(atPath: candidate) ? candidate : nil + return FileManager().isReadableFile(atPath: candidate) ? candidate : nil } static func hasAnyClawdbotInvoker(searchPaths: [String]? = nil) -> Bool { @@ -214,9 +214,10 @@ enum CommandResolver { subcommand: String, extraArgs: [String] = [], defaults: UserDefaults = .standard, + configRoot: [String: Any]? = nil, searchPaths: [String]? = nil) -> [String] { - let settings = self.connectionSettings(defaults: defaults) + let settings = self.connectionSettings(defaults: defaults, configRoot: configRoot) if settings.mode == .remote, let ssh = self.sshNodeCommand( subcommand: subcommand, extraArgs: extraArgs, @@ -264,12 +265,14 @@ enum CommandResolver { subcommand: String, extraArgs: [String] = [], defaults: UserDefaults = .standard, + configRoot: [String: Any]? = nil, searchPaths: [String]? = nil) -> [String] { self.clawdbotNodeCommand( subcommand: subcommand, extraArgs: extraArgs, defaults: defaults, + configRoot: configRoot, searchPaths: searchPaths) } @@ -281,13 +284,16 @@ enum CommandResolver { var args: [String] = [ "-o", "BatchMode=yes", - "-o", "IdentitiesOnly=yes", "-o", "StrictHostKeyChecking=accept-new", "-o", "UpdateHostKeys=yes", ] if parsed.port > 0 { args.append(contentsOf: ["-p", String(parsed.port)]) } - if !settings.identity.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - args.append(contentsOf: ["-i", settings.identity]) + let identity = settings.identity.trimmingCharacters(in: .whitespacesAndNewlines) + if !identity.isEmpty { + // Only use IdentitiesOnly when an explicit identity file is provided. + // This allows 1Password SSH agent and other SSH agents to provide keys. + args.append(contentsOf: ["-o", "IdentitiesOnly=yes"]) + args.append(contentsOf: ["-i", identity]) } let userHost = parsed.user.map { "\($0)@\(parsed.host)" } ?? parsed.host args.append(userHost) @@ -384,15 +390,12 @@ enum CommandResolver { let cliPath: String } - static func connectionSettings(defaults: UserDefaults = .standard) -> RemoteSettings { - let modeRaw = defaults.string(forKey: connectionModeKey) - let mode: AppState.ConnectionMode - if let modeRaw { - mode = AppState.ConnectionMode(rawValue: modeRaw) ?? .local - } else { - let seen = defaults.bool(forKey: "clawdbot.onboardingSeen") - mode = seen ? .local : .unconfigured - } + static func connectionSettings( + defaults: UserDefaults = .standard, + configRoot: [String: Any]? = nil) -> RemoteSettings + { + let root = configRoot ?? ClawdbotConfigFile.loadDict() + let mode = ConnectionModeResolver.resolve(root: root, defaults: defaults).mode let target = defaults.string(forKey: remoteTargetKey) ?? "" let identity = defaults.string(forKey: remoteIdentityKey) ?? "" let projectRoot = defaults.string(forKey: remoteProjectRootKey) ?? "" @@ -459,7 +462,7 @@ enum CommandResolver { private static func expandPath(_ path: String) -> URL? { var expanded = path if expanded.hasPrefix("~") { - let home = FileManager.default.homeDirectoryForCurrentUser.path + let home = FileManager().homeDirectoryForCurrentUser.path expanded.replaceSubrange(expanded.startIndex...expanded.startIndex, with: home) } return URL(fileURLWithPath: expanded) diff --git a/apps/macos/Sources/Clawdbot/ConfigSchemaSupport.swift b/apps/macos/Sources/Clawdbot/ConfigSchemaSupport.swift new file mode 100644 index 000000000..4a7d4e0a4 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/ConfigSchemaSupport.swift @@ -0,0 +1,204 @@ +import Foundation + +enum ConfigPathSegment: Hashable { + case key(String) + case index(Int) +} + +typealias ConfigPath = [ConfigPathSegment] + +struct ConfigUiHint { + let label: String? + let help: String? + let order: Double? + let advanced: Bool? + let sensitive: Bool? + let placeholder: String? + + init(raw: [String: Any]) { + self.label = raw["label"] as? String + self.help = raw["help"] as? String + if let order = raw["order"] as? Double { + self.order = order + } else if let orderInt = raw["order"] as? Int { + self.order = Double(orderInt) + } else { + self.order = nil + } + self.advanced = raw["advanced"] as? Bool + self.sensitive = raw["sensitive"] as? Bool + self.placeholder = raw["placeholder"] as? String + } +} + +struct ConfigSchemaNode { + let raw: [String: Any] + + init?(raw: Any) { + guard let dict = raw as? [String: Any] else { return nil } + self.raw = dict + } + + var title: String? { self.raw["title"] as? String } + var description: String? { self.raw["description"] as? String } + var enumValues: [Any]? { self.raw["enum"] as? [Any] } + var constValue: Any? { self.raw["const"] } + var explicitDefault: Any? { self.raw["default"] } + var requiredKeys: Set { + Set((self.raw["required"] as? [String]) ?? []) + } + + var typeList: [String] { + if let type = self.raw["type"] as? String { return [type] } + if let types = self.raw["type"] as? [String] { return types } + return [] + } + + var schemaType: String? { + let filtered = self.typeList.filter { $0 != "null" } + if let first = filtered.first { return first } + return self.typeList.first + } + + var isNullSchema: Bool { + let types = self.typeList + return types.count == 1 && types.first == "null" + } + + var properties: [String: ConfigSchemaNode] { + guard let props = self.raw["properties"] as? [String: Any] else { return [:] } + return props.compactMapValues { ConfigSchemaNode(raw: $0) } + } + + var anyOf: [ConfigSchemaNode] { + guard let raw = self.raw["anyOf"] as? [Any] else { return [] } + return raw.compactMap { ConfigSchemaNode(raw: $0) } + } + + var oneOf: [ConfigSchemaNode] { + guard let raw = self.raw["oneOf"] as? [Any] else { return [] } + return raw.compactMap { ConfigSchemaNode(raw: $0) } + } + + var literalValue: Any? { + if let constValue { return constValue } + if let enumValues, enumValues.count == 1 { return enumValues[0] } + return nil + } + + var items: ConfigSchemaNode? { + if let items = self.raw["items"] as? [Any], let first = items.first { + return ConfigSchemaNode(raw: first) + } + if let items = self.raw["items"] { + return ConfigSchemaNode(raw: items) + } + return nil + } + + var additionalProperties: ConfigSchemaNode? { + if let additional = self.raw["additionalProperties"] as? [String: Any] { + return ConfigSchemaNode(raw: additional) + } + return nil + } + + var allowsAdditionalProperties: Bool { + if let allow = self.raw["additionalProperties"] as? Bool { return allow } + return self.additionalProperties != nil + } + + var defaultValue: Any { + if let value = self.raw["default"] { return value } + switch self.schemaType { + case "object": + return [String: Any]() + case "array": + return [Any]() + case "boolean": + return false + case "integer": + return 0 + case "number": + return 0.0 + case "string": + return "" + default: + return "" + } + } + + func node(at path: ConfigPath) -> ConfigSchemaNode? { + var current: ConfigSchemaNode? = self + for segment in path { + guard let node = current else { return nil } + switch segment { + case let .key(key): + if node.schemaType == "object" { + if let next = node.properties[key] { + current = next + continue + } + if let additional = node.additionalProperties { + current = additional + continue + } + return nil + } + return nil + case .index: + guard node.schemaType == "array" else { return nil } + current = node.items + } + } + return current + } +} + +func decodeUiHints(_ raw: [String: Any]) -> [String: ConfigUiHint] { + raw.reduce(into: [:]) { result, entry in + if let hint = entry.value as? [String: Any] { + result[entry.key] = ConfigUiHint(raw: hint) + } + } +} + +func hintForPath(_ path: ConfigPath, hints: [String: ConfigUiHint]) -> ConfigUiHint? { + let key = pathKey(path) + if let direct = hints[key] { return direct } + let segments = key.split(separator: ".").map(String.init) + for (hintKey, hint) in hints { + guard hintKey.contains("*") else { continue } + let hintSegments = hintKey.split(separator: ".").map(String.init) + guard hintSegments.count == segments.count else { continue } + var match = true + for (index, seg) in segments.enumerated() { + let hintSegment = hintSegments[index] + if hintSegment != "*", hintSegment != seg { + match = false + break + } + } + if match { return hint } + } + return nil +} + +func isSensitivePath(_ path: ConfigPath) -> Bool { + let key = pathKey(path).lowercased() + return key.contains("token") + || key.contains("password") + || key.contains("secret") + || key.contains("apikey") + || key.hasSuffix("key") +} + +func pathKey(_ path: ConfigPath) -> String { + path.compactMap { segment -> String? in + switch segment { + case let .key(key): return key + case .index: return nil + } + } + .joined(separator: ".") +} diff --git a/apps/macos/Sources/Clawdbot/ConfigSettings.swift b/apps/macos/Sources/Clawdbot/ConfigSettings.swift index dac397822..3846ec55f 100644 --- a/apps/macos/Sources/Clawdbot/ConfigSettings.swift +++ b/apps/macos/Sources/Clawdbot/ConfigSettings.swift @@ -4,933 +4,388 @@ import SwiftUI struct ConfigSettings: View { private let isPreview = ProcessInfo.processInfo.isPreview private let isNixMode = ProcessInfo.processInfo.isNixMode - private let state = AppStateStore.shared - private let labelColumnWidth: CGFloat = 120 - private static let browserAttachOnlyHelp = - "When enabled, the browser server will only connect if the clawd browser is already running." - private static let browserProfileNote = - "Clawd uses a separate Chrome profile and ports (default 18791/18792) " - + "so it won’t interfere with your daily browser." - @State private var configModel: String = "" - @State private var configSaving = false + @Bindable var store: ChannelsStore @State private var hasLoaded = false - @State private var models: [ModelChoice] = [] - @State private var modelsLoading = false - @State private var modelSearchQuery: String = "" - @State private var isModelPickerOpen = false - @State private var modelError: String? - @State private var modelsSourceLabel: String? - @AppStorage(modelCatalogPathKey) private var modelCatalogPath: String = ModelCatalogLoader.defaultPath - @AppStorage(modelCatalogReloadKey) private var modelCatalogReloadBump: Int = 0 - @State private var allowAutosave = false - @State private var heartbeatMinutes: Int? - @State private var heartbeatBody: String = "HEARTBEAT" + @State private var activeSectionKey: String? + @State private var activeSubsection: SubsectionSelection? - // clawd browser settings (stored in ~/.clawdbot/clawdbot.json under "browser") - @State private var browserEnabled: Bool = true - @State private var browserControlUrl: String = "http://127.0.0.1:18791" - @State private var browserColorHex: String = "#FF4500" - @State private var browserAttachOnly: Bool = false - - // Talk mode settings (stored in ~/.clawdbot/clawdbot.json under "talk") - @State private var talkVoiceId: String = "" - @State private var talkInterruptOnSpeech: Bool = true - @State private var talkApiKey: String = "" - @State private var gatewayApiKeyFound = false - @FocusState private var modelSearchFocused: Bool - - private struct ConfigDraft { - let configModel: String - let heartbeatMinutes: Int? - let heartbeatBody: String - let browserEnabled: Bool - let browserControlUrl: String - let browserColorHex: String - let browserAttachOnly: Bool - let talkVoiceId: String - let talkApiKey: String - let talkInterruptOnSpeech: Bool + init(store: ChannelsStore = .shared) { + self.store = store } var body: some View { - ScrollView { self.content } - .onChange(of: self.modelCatalogPath) { _, _ in - Task { await self.loadModels() } - } - .onChange(of: self.modelCatalogReloadBump) { _, _ in - Task { await self.loadModels() } - } - .task { - guard !self.hasLoaded else { return } - guard !self.isPreview else { return } - self.hasLoaded = true - await self.loadConfig() - await self.loadModels() - await self.refreshGatewayTalkApiKey() - self.allowAutosave = true - } + HStack(spacing: 16) { + self.sidebar + self.detail + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .task { + guard !self.hasLoaded else { return } + guard !self.isPreview else { return } + self.hasLoaded = true + await self.store.loadConfigSchema() + await self.store.loadConfig() + } + .onAppear { self.ensureSelection() } + .onChange(of: self.store.configSchemaLoading) { _, loading in + if !loading { self.ensureSelection() } + } } } extension ConfigSettings { - private var content: some View { - VStack(alignment: .leading, spacing: 14) { - self.header - self.agentSection - .disabled(self.isNixMode) - self.heartbeatSection - .disabled(self.isNixMode) - self.talkSection - .disabled(self.isNixMode) - self.browserSection - .disabled(self.isNixMode) - Spacer(minLength: 0) + private enum SubsectionSelection: Hashable { + case all + case key(String) + } + + private struct ConfigSection: Identifiable { + let key: String + let label: String + let help: String? + let node: ConfigSchemaNode + + var id: String { self.key } + } + + private struct ConfigSubsection: Identifiable { + let key: String + let label: String + let help: String? + let node: ConfigSchemaNode + let path: ConfigPath + + var id: String { self.key } + } + + private var sections: [ConfigSection] { + guard let schema = self.store.configSchema else { return [] } + return self.resolveSections(schema) + } + + private var activeSection: ConfigSection? { + self.sections.first { $0.key == self.activeSectionKey } + } + + private var sidebar: some View { + ScrollView { + LazyVStack(alignment: .leading, spacing: 8) { + if self.sections.isEmpty { + Text("No config sections available.") + .font(.caption) + .foregroundStyle(.secondary) + .padding(.horizontal, 6) + .padding(.vertical, 4) + } else { + ForEach(self.sections) { section in + self.sidebarRow(section) + } + } + } + .padding(.vertical, 10) + .padding(.horizontal, 10) + } + .frame(minWidth: 220, idealWidth: 240, maxWidth: 280, maxHeight: .infinity, alignment: .topLeading) + .background( + RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(Color(nsColor: .windowBackgroundColor))) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + } + + private var detail: some View { + VStack(alignment: .leading, spacing: 16) { + if self.store.configSchemaLoading { + ProgressView().controlSize(.small) + } else if let section = self.activeSection { + self.sectionDetail(section) + } else if self.store.configSchema != nil { + self.emptyDetail + } else { + Text("Schema unavailable.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + .frame(minWidth: 460, maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } + + private var emptyDetail: some View { + VStack(alignment: .leading, spacing: 8) { + self.header + Text("Select a config section to view settings.") + .font(.callout) + .foregroundStyle(.secondary) } - .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 24) .padding(.vertical, 18) - .groupBoxStyle(PlainSettingsGroupBoxStyle()) + } + + private func sectionDetail(_ section: ConfigSection) -> some View { + ScrollView(.vertical) { + VStack(alignment: .leading, spacing: 16) { + self.header + if let status = self.store.configStatus { + Text(status) + .font(.callout) + .foregroundStyle(.secondary) + } + self.actionRow + self.sectionHeader(section) + self.subsectionNav(section) + self.sectionForm(section) + if self.store.configDirty, !self.isNixMode { + Text("Unsaved changes") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer(minLength: 0) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 24) + .padding(.vertical, 18) + .groupBoxStyle(PlainSettingsGroupBoxStyle()) + } } @ViewBuilder private var header: some View { - Text("Clawdbot CLI config") + Text("Config") .font(.title3.weight(.semibold)) Text(self.isNixMode ? "This tab is read-only in Nix mode. Edit config via Nix and rebuild." - : "Edit ~/.clawdbot/clawdbot.json (agent / session / routing / messages).") + : "Edit ~/.clawdbot/clawdbot.json using the schema-driven form.") .font(.callout) .foregroundStyle(.secondary) } - private var agentSection: some View { - GroupBox("Agent") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 10) { - GridRow { - self.gridLabel("Model") - VStack(alignment: .leading, spacing: 6) { - self.modelPickerField - self.modelMetaLabels - } - } + private func sectionHeader(_ section: ConfigSection) -> some View { + VStack(alignment: .leading, spacing: 6) { + Text(section.label) + .font(.title3.weight(.semibold)) + if let help = section.help { + Text(help) + .font(.callout) + .foregroundStyle(.secondary) } } - .frame(maxWidth: .infinity, alignment: .leading) } - private var modelPickerField: some View { - Button { - guard !self.modelsLoading else { return } - self.isModelPickerOpen = true + private var actionRow: some View { + HStack(spacing: 10) { + Button("Reload") { + Task { await self.store.reloadConfigDraft() } + } + .disabled(!self.store.configLoaded) + + Button(self.store.isSavingConfig ? "Saving…" : "Save") { + Task { await self.store.saveConfigDraft() } + } + .disabled(self.isNixMode || self.store.isSavingConfig || !self.store.configDirty) + } + .buttonStyle(.bordered) + } + + private func sidebarRow(_ section: ConfigSection) -> some View { + let isSelected = self.activeSectionKey == section.key + return Button { + self.selectSection(section) } label: { - HStack(spacing: 8) { - Text(self.modelPickerLabel) - .foregroundStyle(self.modelPickerLabelIsPlaceholder ? .secondary : .primary) - .lineLimit(1) - .truncationMode(.tail) - Spacer(minLength: 8) - Image(systemName: "chevron.up.chevron.down") - .foregroundStyle(.secondary) + VStack(alignment: .leading, spacing: 2) { + Text(section.label) + if let help = section.help { + Text(help) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + } } .padding(.vertical, 6) .padding(.horizontal, 8) + .frame(maxWidth: .infinity, alignment: .leading) + .background(isSelected ? Color.accentColor.opacity(0.18) : Color.clear) + .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) + .background(Color.clear) + .contentShape(Rectangle()) } - .buttonStyle(.plain) .frame(maxWidth: .infinity, alignment: .leading) + .buttonStyle(.plain) .contentShape(Rectangle()) - .background( - RoundedRectangle(cornerRadius: 6) - .fill( - Color(nsColor: .textBackgroundColor))) - .overlay( - RoundedRectangle(cornerRadius: 6) - .stroke( - Color.secondary.opacity(0.25), - lineWidth: 1)) - .popover(isPresented: self.$isModelPickerOpen, arrowEdge: .bottom) { - self.modelPickerPopover - } - .disabled(self.modelsLoading || (!self.modelError.isNilOrEmpty && self.models.isEmpty)) - .onChange(of: self.isModelPickerOpen) { _, isOpen in - if isOpen { - self.modelSearchQuery = "" - self.modelSearchFocused = true - } - } - } - - private var modelPickerPopover: some View { - VStack(alignment: .leading, spacing: 10) { - TextField("Search models", text: self.$modelSearchQuery) - .textFieldStyle(.roundedBorder) - .focused(self.$modelSearchFocused) - .controlSize(.small) - .onSubmit { - if let exact = self.exactMatchForQuery() { - self.selectModel(exact) - return - } - if let manual = self.manualEntryCandidate { - self.selectManualModel(manual) - return - } - if self.modelSearchMatches.count == 1 { - self.selectModel(self.modelSearchMatches[0]) - } - } - List { - if self.modelSearchMatches.isEmpty { - Text("No models match \"\(self.modelSearchQuery)\"") - .font(.footnote) - .foregroundStyle(.secondary) - } else { - ForEach(self.modelSearchMatches) { choice in - Button { - self.selectModel(choice) - } label: { - HStack(spacing: 8) { - Text(choice.name) - .lineLimit(1) - Spacer(minLength: 8) - Text(choice.provider.uppercased()) - .font(.caption2.weight(.semibold)) - .foregroundStyle(.secondary) - .padding(.vertical, 2) - .padding(.horizontal, 6) - .background(Color.secondary.opacity(0.15)) - .clipShape(RoundedRectangle(cornerRadius: 4)) - } - .padding(.vertical, 2) - } - .buttonStyle(.plain) - .listRowInsets(EdgeInsets(top: 4, leading: 8, bottom: 4, trailing: 8)) - } - } - - if let manual = self.manualEntryCandidate { - Button("Use \"\(manual)\"") { - self.selectManualModel(manual) - } - .listRowInsets(EdgeInsets(top: 4, leading: 8, bottom: 4, trailing: 8)) - } - } - .listStyle(.inset) - } - .frame(width: 340, height: 260) - .padding(8) } @ViewBuilder - private var modelMetaLabels: some View { - if self.shouldShowProviderHintForSelection { - self.statusLine(label: "Tip: prefer provider/model (e.g. openai-codex/gpt-5.2)", color: .orange) - } - - if let contextLabel = self.selectedContextLabel { - Text(contextLabel) - .font(.footnote) - .foregroundStyle(.secondary) - } - - if let authMode = self.selectedAnthropicAuthMode { - HStack(spacing: 8) { - Circle() - .fill(authMode.isConfigured ? Color.green : Color.orange) - .frame(width: 8, height: 8) - Text("Anthropic auth: \(authMode.shortLabel)") - } - .font(.footnote) - .foregroundStyle(authMode.isConfigured ? Color.secondary : Color.orange) - .help(self.anthropicAuthHelpText) - - AnthropicAuthControls(connectionMode: self.state.connectionMode) - } - - if let modelError { - Text(modelError) - .font(.footnote) - .foregroundStyle(.secondary) - } - - if let modelsSourceLabel { - Text("Model catalog: \(modelsSourceLabel)") - .font(.footnote) - .foregroundStyle(.secondary) - } - } - - private var anthropicAuthHelpText: String { - "Determined from Clawdbot OAuth token file (~/.clawdbot/credentials/oauth.json) " + - "or environment variables (ANTHROPIC_OAUTH_TOKEN / ANTHROPIC_API_KEY)." - } - - private var heartbeatSection: some View { - GroupBox("Heartbeat") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 10) { - GridRow { - self.gridLabel("Schedule") - VStack(alignment: .leading, spacing: 6) { - HStack(spacing: 12) { - Stepper( - value: Binding( - get: { self.heartbeatMinutes ?? 10 }, - set: { self.heartbeatMinutes = $0; self.autosaveConfig() }), - in: 0...720) - { - Text("Every \(self.heartbeatMinutes ?? 10) min") - .frame(width: 150, alignment: .leading) - } - .help("Set to 0 to disable automatic heartbeats") - - TextField("HEARTBEAT", text: self.$heartbeatBody) - .textFieldStyle(.roundedBorder) - .frame(maxWidth: .infinity) - .onChange(of: self.heartbeatBody) { _, _ in - self.autosaveConfig() - } - .help("Message body sent on each heartbeat") - } - Text("Heartbeats keep agent sessions warm; 0 minutes disables them.") - .font(.footnote) - .foregroundStyle(.secondary) + private func subsectionNav(_ section: ConfigSection) -> some View { + let subsections = self.resolveSubsections(for: section) + if subsections.isEmpty { + EmptyView() + } else { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + self.subsectionButton( + title: "All", + isSelected: self.activeSubsection == .all) + { + self.activeSubsection = .all } - } - } - } - .frame(maxWidth: .infinity, alignment: .leading) - } - - private var browserSection: some View { - GroupBox("Browser (clawd)") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 10) { - GridRow { - self.gridLabel("Enabled") - Toggle("", isOn: self.$browserEnabled) - .labelsHidden() - .toggleStyle(.checkbox) - .onChange(of: self.browserEnabled) { _, _ in self.autosaveConfig() } - } - GridRow { - self.gridLabel("Control URL") - TextField("http://127.0.0.1:18791", text: self.$browserControlUrl) - .textFieldStyle(.roundedBorder) - .frame(maxWidth: .infinity) - .disabled(!self.browserEnabled) - .onChange(of: self.browserControlUrl) { _, _ in self.autosaveConfig() } - } - GridRow { - self.gridLabel("Browser path") - VStack(alignment: .leading, spacing: 2) { - if let label = self.browserPathLabel { - Text(label) - .font(.caption.monospaced()) - .foregroundStyle(.secondary) - .textSelection(.enabled) - .lineLimit(1) - .truncationMode(.middle) - } else { - Text("—") - .foregroundStyle(.secondary) - } - } - .frame(maxWidth: .infinity, alignment: .leading) - } - GridRow { - self.gridLabel("Accent") - HStack(spacing: 8) { - TextField("#FF4500", text: self.$browserColorHex) - .textFieldStyle(.roundedBorder) - .frame(width: 120) - .disabled(!self.browserEnabled) - .onChange(of: self.browserColorHex) { _, _ in self.autosaveConfig() } - Circle() - .fill(self.browserColor) - .frame(width: 12, height: 12) - .overlay(Circle().stroke(Color.secondary.opacity(0.25), lineWidth: 1)) - Text("lobster-orange") - .font(.footnote) - .foregroundStyle(.secondary) - } - } - GridRow { - self.gridLabel("Attach only") - Toggle("", isOn: self.$browserAttachOnly) - .labelsHidden() - .toggleStyle(.checkbox) - .disabled(!self.browserEnabled) - .onChange(of: self.browserAttachOnly) { _, _ in self.autosaveConfig() } - .help(Self.browserAttachOnlyHelp) - } - GridRow { - Color.clear - .frame(width: self.labelColumnWidth, height: 1) - Text(Self.browserProfileNote) - .font(.footnote) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .leading) - } - } - } - .frame(maxWidth: .infinity, alignment: .leading) - } - - private var talkSection: some View { - GroupBox("Talk Mode") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 10) { - GridRow { - self.gridLabel("Voice ID") - VStack(alignment: .leading, spacing: 6) { - HStack(spacing: 8) { - TextField("ElevenLabs voice ID", text: self.$talkVoiceId) - .textFieldStyle(.roundedBorder) - .frame(maxWidth: .infinity) - .onChange(of: self.talkVoiceId) { _, _ in self.autosaveConfig() } - if !self.talkVoiceSuggestions.isEmpty { - Menu { - ForEach(self.talkVoiceSuggestions, id: \.self) { value in - Button(value) { - self.talkVoiceId = value - self.autosaveConfig() - } - } - } label: { - Label("Suggestions", systemImage: "chevron.up.chevron.down") - } - .fixedSize() - } - } - Text("Defaults to ELEVENLABS_VOICE_ID / SAG_VOICE_ID if unset.") - .font(.footnote) - .foregroundStyle(.secondary) - } - } - GridRow { - self.gridLabel("API key") - VStack(alignment: .leading, spacing: 6) { - HStack(spacing: 8) { - SecureField("ELEVENLABS_API_KEY", text: self.$talkApiKey) - .textFieldStyle(.roundedBorder) - .frame(maxWidth: .infinity) - .disabled(self.hasEnvApiKey) - .onChange(of: self.talkApiKey) { _, _ in self.autosaveConfig() } - if !self.hasEnvApiKey, !self.talkApiKey.isEmpty { - Button("Clear") { - self.talkApiKey = "" - self.autosaveConfig() - } - } - } - self.statusLine(label: self.apiKeyStatusLabel, color: self.apiKeyStatusColor) - if self.hasEnvApiKey { - Text("Using ELEVENLABS_API_KEY from the environment.") - .font(.footnote) - .foregroundStyle(.secondary) - } else if self.gatewayApiKeyFound, - self.talkApiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + ForEach(subsections) { subsection in + self.subsectionButton( + title: subsection.label, + isSelected: self.activeSubsection == .key(subsection.key)) { - Text("Using API key from the gateway profile.") - .font(.footnote) - .foregroundStyle(.secondary) + self.activeSubsection = .key(subsection.key) } } } - GridRow { - self.gridLabel("Interrupt") - Toggle("Stop speaking when you start talking", isOn: self.$talkInterruptOnSpeech) - .labelsHidden() - .toggleStyle(.checkbox) - .onChange(of: self.talkInterruptOnSpeech) { _, _ in self.autosaveConfig() } - } + .padding(.vertical, 2) } } - .frame(maxWidth: .infinity, alignment: .leading) } - private func gridLabel(_ text: String) -> some View { - Text(text) - .foregroundStyle(.secondary) - .frame(width: self.labelColumnWidth, alignment: .leading) - } - - private func statusLine(label: String, color: Color) -> some View { - HStack(spacing: 6) { - Circle() - .fill(color) - .frame(width: 6, height: 6) - Text(label) - .font(.footnote) - .foregroundStyle(.secondary) + private func subsectionButton( + title: String, + isSelected: Bool, + action: @escaping () -> Void) -> some View + { + Button(action: action) { + Text(title) + .font(.callout.weight(.semibold)) + .foregroundStyle(isSelected ? Color.accentColor : .primary) + .padding(.horizontal, 10) + .padding(.vertical, 6) + .background(isSelected ? Color.accentColor.opacity(0.18) : Color(nsColor: .controlBackgroundColor)) + .clipShape(Capsule()) } - .padding(.top, 2) + .buttonStyle(.plain) } -} -extension ConfigSettings { - private func loadConfig() async { - let parsed = await ConfigStore.load() - let agents = parsed["agents"] as? [String: Any] - let defaults = agents?["defaults"] as? [String: Any] - let heartbeat = defaults?["heartbeat"] as? [String: Any] - let heartbeatEvery = heartbeat?["every"] as? String - let heartbeatBody = heartbeat?["prompt"] as? String - let browser = parsed["browser"] as? [String: Any] - let talk = parsed["talk"] as? [String: Any] - - let loadedModel: String = { - if let raw = defaults?["model"] as? String { return raw } - if let modelDict = defaults?["model"] as? [String: Any], - let primary = modelDict["primary"] as? String { return primary } - return "" + private func sectionForm(_ section: ConfigSection) -> some View { + let subsection = self.activeSubsection + let defaultPath: ConfigPath = [.key(section.key)] + let subsections = self.resolveSubsections(for: section) + let resolved: (ConfigSchemaNode, ConfigPath) = { + if case let .key(key) = subsection, + let match = subsections.first(where: { $0.key == key }) + { + return (match.node, match.path) + } + return (self.resolvedSchemaNode(section.node), defaultPath) }() - if !loadedModel.isEmpty { - self.configModel = loadedModel - } else { - self.configModel = SessionLoader.fallbackModel + + return ConfigSchemaForm(store: self.store, schema: resolved.0, path: resolved.1) + .disabled(self.isNixMode) + } + + private func ensureSelection() { + guard let schema = self.store.configSchema else { return } + let sections = self.resolveSections(schema) + guard !sections.isEmpty else { return } + + let active = sections.first { $0.key == self.activeSectionKey } ?? sections[0] + if self.activeSectionKey != active.key { + self.activeSectionKey = active.key + } + self.ensureSubsection(for: active) + } + + private func ensureSubsection(for section: ConfigSection) { + let subsections = self.resolveSubsections(for: section) + guard !subsections.isEmpty else { + self.activeSubsection = nil + return } - if let heartbeatEvery { - let digits = heartbeatEvery.trimmingCharacters(in: .whitespacesAndNewlines) - .prefix { $0.isNumber } - if let minutes = Int(digits) { - self.heartbeatMinutes = minutes - } - } - if let heartbeatBody, !heartbeatBody.isEmpty { self.heartbeatBody = heartbeatBody } - - if let browser { - if let enabled = browser["enabled"] as? Bool { self.browserEnabled = enabled } - if let url = browser["controlUrl"] as? String, !url.isEmpty { self.browserControlUrl = url } - if let color = browser["color"] as? String, !color.isEmpty { self.browserColorHex = color } - if let attachOnly = browser["attachOnly"] as? Bool { self.browserAttachOnly = attachOnly } + switch self.activeSubsection { + case .all: + return + case let .key(key): + if subsections.contains(where: { $0.key == key }) { return } + case .none: + break } - if let talk { - if let voice = talk["voiceId"] as? String { self.talkVoiceId = voice } - if let apiKey = talk["apiKey"] as? String { self.talkApiKey = apiKey } - if let interrupt = talk["interruptOnSpeech"] as? Bool { - self.talkInterruptOnSpeech = interrupt - } + if let first = subsections.first { + self.activeSubsection = .key(first.key) } } - private func refreshGatewayTalkApiKey() async { - do { - let snap: ConfigSnapshot = try await GatewayConnection.shared.requestDecoded( - method: .configGet, - params: nil, - timeoutMs: 8000) - let talk = snap.config?["talk"]?.dictionaryValue - let apiKey = talk?["apiKey"]?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines) - self.gatewayApiKeyFound = !(apiKey ?? "").isEmpty - } catch { - self.gatewayApiKeyFound = false + private func selectSection(_ section: ConfigSection) { + guard self.activeSectionKey != section.key else { return } + self.activeSectionKey = section.key + let subsections = self.resolveSubsections(for: section) + if let first = subsections.first { + self.activeSubsection = .key(first.key) + } else { + self.activeSubsection = nil } } - private func autosaveConfig() { - guard self.allowAutosave, !self.isNixMode else { return } - Task { await self.saveConfig() } - } + private func resolveSections(_ root: ConfigSchemaNode) -> [ConfigSection] { + let node = self.resolvedSchemaNode(root) + let hints = self.store.configUiHints + let keys = node.properties.keys.sorted { lhs, rhs in + let orderA = hintForPath([.key(lhs)], hints: hints)?.order ?? 0 + let orderB = hintForPath([.key(rhs)], hints: hints)?.order ?? 0 + if orderA != orderB { return orderA < orderB } + return lhs < rhs + } - private func saveConfig() async { - guard !self.configSaving else { return } - self.configSaving = true - defer { self.configSaving = false } - - let configModel = self.configModel - let heartbeatMinutes = self.heartbeatMinutes - let heartbeatBody = self.heartbeatBody - let browserEnabled = self.browserEnabled - let browserControlUrl = self.browserControlUrl - let browserColorHex = self.browserColorHex - let browserAttachOnly = self.browserAttachOnly - let talkVoiceId = self.talkVoiceId - let talkApiKey = self.talkApiKey - let talkInterruptOnSpeech = self.talkInterruptOnSpeech - - let draft = ConfigDraft( - configModel: configModel, - heartbeatMinutes: heartbeatMinutes, - heartbeatBody: heartbeatBody, - browserEnabled: browserEnabled, - browserControlUrl: browserControlUrl, - browserColorHex: browserColorHex, - browserAttachOnly: browserAttachOnly, - talkVoiceId: talkVoiceId, - talkApiKey: talkApiKey, - talkInterruptOnSpeech: talkInterruptOnSpeech) - - let errorMessage = await ConfigSettings.buildAndSaveConfig(draft) - - if let errorMessage { - self.modelError = errorMessage + return keys.compactMap { key in + guard let child = node.properties[key] else { return nil } + let path: ConfigPath = [.key(key)] + let hint = hintForPath(path, hints: hints) + let label = hint?.label + ?? child.title + ?? self.humanize(key) + let help = hint?.help ?? child.description + return ConfigSection(key: key, label: label, help: help, node: child) } } - @MainActor - private static func buildAndSaveConfig(_ draft: ConfigDraft) async -> String? { - var root = await ConfigStore.load() - var agents = root["agents"] as? [String: Any] ?? [:] - var defaults = agents["defaults"] as? [String: Any] ?? [:] - var browser = root["browser"] as? [String: Any] ?? [:] - var talk = root["talk"] as? [String: Any] ?? [:] - - let chosenModel = draft.configModel.trimmingCharacters(in: .whitespacesAndNewlines) - let trimmedModel = chosenModel - if !trimmedModel.isEmpty { - var model = defaults["model"] as? [String: Any] ?? [:] - model["primary"] = trimmedModel - defaults["model"] = model - - var models = defaults["models"] as? [String: Any] ?? [:] - if models[trimmedModel] == nil { - models[trimmedModel] = [:] - } - defaults["models"] = models + private func resolveSubsections(for section: ConfigSection) -> [ConfigSubsection] { + let node = self.resolvedSchemaNode(section.node) + guard node.schemaType == "object" else { return [] } + let hints = self.store.configUiHints + let keys = node.properties.keys.sorted { lhs, rhs in + let orderA = hintForPath([.key(section.key), .key(lhs)], hints: hints)?.order ?? 0 + let orderB = hintForPath([.key(section.key), .key(rhs)], hints: hints)?.order ?? 0 + if orderA != orderB { return orderA < orderB } + return lhs < rhs } - if let heartbeatMinutes = draft.heartbeatMinutes { - var heartbeat = defaults["heartbeat"] as? [String: Any] ?? [:] - heartbeat["every"] = "\(heartbeatMinutes)m" - defaults["heartbeat"] = heartbeat + return keys.compactMap { key in + guard let child = node.properties[key] else { return nil } + let path: ConfigPath = [.key(section.key), .key(key)] + let hint = hintForPath(path, hints: hints) + let label = hint?.label + ?? child.title + ?? self.humanize(key) + let help = hint?.help ?? child.description + return ConfigSubsection( + key: key, + label: label, + help: help, + node: child, + path: path) } + } - let trimmedBody = draft.heartbeatBody.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmedBody.isEmpty { - var heartbeat = defaults["heartbeat"] as? [String: Any] ?? [:] - heartbeat["prompt"] = trimmedBody - defaults["heartbeat"] = heartbeat + private func resolvedSchemaNode(_ node: ConfigSchemaNode) -> ConfigSchemaNode { + let variants = node.anyOf.isEmpty ? node.oneOf : node.anyOf + if !variants.isEmpty { + let nonNull = variants.filter { !$0.isNullSchema } + if nonNull.count == 1, let only = nonNull.first { return only } } + return node + } - if defaults.isEmpty { - agents.removeValue(forKey: "defaults") - } else { - agents["defaults"] = defaults - } - if agents.isEmpty { - root.removeValue(forKey: "agents") - } else { - root["agents"] = agents - } - - browser["enabled"] = draft.browserEnabled - let trimmedUrl = draft.browserControlUrl.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmedUrl.isEmpty { browser["controlUrl"] = trimmedUrl } - let trimmedColor = draft.browserColorHex.trimmingCharacters(in: .whitespacesAndNewlines) - if !trimmedColor.isEmpty { browser["color"] = trimmedColor } - browser["attachOnly"] = draft.browserAttachOnly - root["browser"] = browser - - let trimmedVoice = draft.talkVoiceId.trimmingCharacters(in: .whitespacesAndNewlines) - if trimmedVoice.isEmpty { - talk.removeValue(forKey: "voiceId") - } else { - talk["voiceId"] = trimmedVoice - } - let trimmedApiKey = draft.talkApiKey.trimmingCharacters(in: .whitespacesAndNewlines) - if trimmedApiKey.isEmpty { - talk.removeValue(forKey: "apiKey") - } else { - talk["apiKey"] = trimmedApiKey - } - talk["interruptOnSpeech"] = draft.talkInterruptOnSpeech - root["talk"] = talk - - do { - try await ConfigStore.save(root) - return nil - } catch { - return error.localizedDescription - } + private func humanize(_ key: String) -> String { + key.replacingOccurrences(of: "_", with: " ") + .replacingOccurrences(of: "-", with: " ") + .capitalized } } -extension ConfigSettings { - private var browserColor: Color { - let raw = self.browserColorHex.trimmingCharacters(in: .whitespacesAndNewlines) - let hex = raw.hasPrefix("#") ? String(raw.dropFirst()) : raw - guard hex.count == 6, let value = Int(hex, radix: 16) else { return .orange } - let r = Double((value >> 16) & 0xFF) / 255.0 - let g = Double((value >> 8) & 0xFF) / 255.0 - let b = Double(value & 0xFF) / 255.0 - return Color(red: r, green: g, blue: b) - } - - private var talkVoiceSuggestions: [String] { - let env = ProcessInfo.processInfo.environment - let candidates = [ - self.talkVoiceId, - env["ELEVENLABS_VOICE_ID"] ?? "", - env["SAG_VOICE_ID"] ?? "", - ] - var seen = Set() - return candidates - .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty } - .filter { seen.insert($0).inserted } - } - - private var hasEnvApiKey: Bool { - let raw = ProcessInfo.processInfo.environment["ELEVENLABS_API_KEY"] ?? "" - return !raw.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - } - - private var apiKeyStatusLabel: String { - if self.hasEnvApiKey { return "ElevenLabs API key: found (environment)" } - if !self.talkApiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - return "ElevenLabs API key: stored in config" - } - if self.gatewayApiKeyFound { return "ElevenLabs API key: found (gateway)" } - return "ElevenLabs API key: missing" - } - - private var apiKeyStatusColor: Color { - if self.hasEnvApiKey { return .green } - if !self.talkApiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return .green } - if self.gatewayApiKeyFound { return .green } - return .red - } - - private var browserPathLabel: String? { - guard self.browserEnabled else { return nil } - - let host = (URL(string: self.browserControlUrl)?.host ?? "").lowercased() - if !host.isEmpty, !Self.isLoopbackHost(host) { - return "remote (\(host))" - } - - guard let candidate = Self.detectedBrowserCandidate() else { return nil } - return candidate.executablePath ?? candidate.appPath - } - - private struct BrowserCandidate { - let name: String - let appPath: String - let executablePath: String? - } - - private static func detectedBrowserCandidate() -> BrowserCandidate? { - let candidates: [(name: String, appName: String)] = [ - ("Google Chrome Canary", "Google Chrome Canary.app"), - ("Chromium", "Chromium.app"), - ("Google Chrome", "Google Chrome.app"), - ] - - let roots = [ - "/Applications", - "\(NSHomeDirectory())/Applications", - ] - - let fm = FileManager.default - for (name, appName) in candidates { - for root in roots { - let appPath = "\(root)/\(appName)" - if fm.fileExists(atPath: appPath) { - let bundle = Bundle(url: URL(fileURLWithPath: appPath)) - let exec = bundle?.executableURL?.path - return BrowserCandidate(name: name, appPath: appPath, executablePath: exec) - } - } - } - - return nil - } - - private static func isLoopbackHost(_ host: String) -> Bool { - if host == "localhost" { return true } - if host == "127.0.0.1" { return true } - if host == "::1" { return true } - return false - } -} - -extension ConfigSettings { - private func loadModels() async { - guard !self.modelsLoading else { return } - self.modelsLoading = true - self.modelError = nil - self.modelsSourceLabel = nil - do { - let res: ModelsListResult = - try await GatewayConnection.shared - .requestDecoded( - method: .modelsList, - timeoutMs: 15000) - self.models = res.models - self.modelsSourceLabel = "gateway" - } catch { - do { - let loaded = try await ModelCatalogLoader.load(from: self.modelCatalogPath) - self.models = loaded - self.modelsSourceLabel = "local fallback" - } catch { - self.modelError = error.localizedDescription - self.models = [] - } - } - self.modelsLoading = false - } - - private struct ModelsListResult: Decodable { - let models: [ModelChoice] - } - - private var modelSearchMatches: [ModelChoice] { - let raw = self.modelSearchQuery.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() - guard !raw.isEmpty else { return self.models } - let tokens = raw - .split(whereSeparator: { $0.isWhitespace }) - .map { token in - token.trimmingCharacters(in: CharacterSet(charactersIn: "%")) - } - .filter { !$0.isEmpty } - guard !tokens.isEmpty else { return self.models } - return self.models.filter { choice in - let haystack = [ - choice.id, - choice.name, - choice.provider, - self.modelRef(for: choice), - ] - .joined(separator: " ") - .lowercased() - return tokens.allSatisfy { haystack.contains($0) } - } - } - - private var selectedModelChoice: ModelChoice? { - guard !self.configModel.isEmpty else { return nil } - return self.models.first(where: { self.matchesConfigModel($0) }) - } - - private var modelPickerLabel: String { - if let choice = self.selectedModelChoice { - return "\(choice.name) — \(choice.provider.uppercased())" - } - if !self.configModel.isEmpty { return self.configModel } - return "Select model" - } - - private var modelPickerLabelIsPlaceholder: Bool { - self.configModel.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - } - - private var manualEntryCandidate: String? { - let trimmed = self.modelSearchQuery.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return nil } - let cleaned = trimmed.trimmingCharacters(in: CharacterSet(charactersIn: "%")) - guard !cleaned.isEmpty else { return nil } - guard !self.isKnownModelRef(cleaned) else { return nil } - return cleaned - } - - private func isKnownModelRef(_ value: String) -> Bool { - let needle = value.lowercased() - return self.models.contains { choice in - choice.id.lowercased() == needle - || self.modelRef(for: choice).lowercased() == needle - } - } - - private func modelRef(for choice: ModelChoice) -> String { - let id = choice.id.trimmingCharacters(in: .whitespacesAndNewlines) - let provider = choice.provider.trimmingCharacters(in: .whitespacesAndNewlines) - guard !provider.isEmpty else { return id } - let normalizedProvider = provider.lowercased() - if id.lowercased().hasPrefix("\(normalizedProvider)/") { - return id - } - return "\(normalizedProvider)/\(id)" - } - - private func matchesConfigModel(_ choice: ModelChoice) -> Bool { - let configured = self.configModel.trimmingCharacters(in: .whitespacesAndNewlines) - guard !configured.isEmpty else { return false } - if configured.caseInsensitiveCompare(choice.id) == .orderedSame { return true } - let ref = self.modelRef(for: choice) - return configured.caseInsensitiveCompare(ref) == .orderedSame - } - - private func exactMatchForQuery() -> ModelChoice? { - let trimmed = self.modelSearchQuery.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return nil } - let cleaned = trimmed.trimmingCharacters(in: CharacterSet(charactersIn: "%")).lowercased() - guard !cleaned.isEmpty else { return nil } - return self.models.first(where: { choice in - let id = choice.id.lowercased() - if id == cleaned { return true } - return self.modelRef(for: choice).lowercased() == cleaned - }) - } - - private var shouldShowProviderHint: Bool { - let trimmed = self.modelSearchQuery.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return false } - let cleaned = trimmed.trimmingCharacters(in: CharacterSet(charactersIn: "%")) - return !cleaned.contains("/") - } - - private var shouldShowProviderHintForSelection: Bool { - let trimmed = self.configModel.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return false } - return !trimmed.contains("/") - } - - private func selectModel(_ choice: ModelChoice) { - self.configModel = self.modelRef(for: choice) - self.autosaveConfig() - self.isModelPickerOpen = false - } - - private func selectManualModel(_ value: String) { - let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) - if let slash = trimmed.firstIndex(of: "/") { - let provider = trimmed[..= 1000 ? "\(context / 1000)k" : "\(context)" - return "Context window: \(human) tokens" - } - - private var selectedAnthropicAuthMode: AnthropicAuthMode? { - guard let choice = self.selectedModelChoice else { return nil } - guard choice.provider.lowercased() == "anthropic" else { return nil } - return AnthropicAuthResolver.resolve() - } - - private struct PlainSettingsGroupBoxStyle: GroupBoxStyle { - func makeBody(configuration: Configuration) -> some View { - VStack(alignment: .leading, spacing: 10) { - configuration.label - .font(.caption.weight(.semibold)) - .foregroundStyle(.secondary) - configuration.content - } - .frame(maxWidth: .infinity, alignment: .leading) - } - } -} - -#if DEBUG struct ConfigSettings_Previews: PreviewProvider { static var previews: some View { ConfigSettings() - .frame(width: SettingsTab.windowWidth, height: SettingsTab.windowHeight) } } -#endif diff --git a/apps/macos/Sources/Clawdbot/ConnectionModeCoordinator.swift b/apps/macos/Sources/Clawdbot/ConnectionModeCoordinator.swift index 1f6d829f1..00f93bd85 100644 --- a/apps/macos/Sources/Clawdbot/ConnectionModeCoordinator.swift +++ b/apps/macos/Sources/Clawdbot/ConnectionModeCoordinator.swift @@ -6,12 +6,20 @@ final class ConnectionModeCoordinator { static let shared = ConnectionModeCoordinator() private let logger = Logger(subsystem: "com.clawdbot", category: "connection") + private var lastMode: AppState.ConnectionMode? /// Apply the requested connection mode by starting/stopping local gateway, /// managing the control-channel SSH tunnel, and cleaning up chat windows/panels. func apply(mode: AppState.ConnectionMode, paused: Bool) async { + if let lastMode = self.lastMode, lastMode != mode { + GatewayProcessManager.shared.clearLastFailure() + NodesStore.shared.lastError = nil + } + self.lastMode = mode switch mode { case .unconfigured: + _ = await NodeServiceManager.stop() + NodesStore.shared.lastError = nil await RemoteTunnelManager.shared.stopAll() WebChatManager.shared.resetTunnels() GatewayProcessManager.shared.stop() @@ -20,6 +28,8 @@ final class ConnectionModeCoordinator { Task.detached { await PortGuardian.shared.sweep(mode: .unconfigured) } case .local: + _ = await NodeServiceManager.stop() + NodesStore.shared.lastError = nil await RemoteTunnelManager.shared.stopAll() WebChatManager.shared.resetTunnels() let shouldStart = GatewayAutostartPolicy.shouldStartGateway(mode: .local, paused: paused) @@ -50,6 +60,10 @@ final class ConnectionModeCoordinator { WebChatManager.shared.resetTunnels() do { + NodesStore.shared.lastError = nil + if let error = await NodeServiceManager.start() { + NodesStore.shared.lastError = "Node service start failed: \(error)" + } _ = try await GatewayEndpointStore.shared.ensureRemoteControlTunnel() let settings = CommandResolver.connectionSettings() try await ControlChannel.shared.configure(mode: .remote( diff --git a/apps/macos/Sources/Clawdbot/ConnectionModeResolver.swift b/apps/macos/Sources/Clawdbot/ConnectionModeResolver.swift new file mode 100644 index 000000000..f0aeb4960 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/ConnectionModeResolver.swift @@ -0,0 +1,49 @@ +import Foundation + +enum EffectiveConnectionModeSource: Sendable, Equatable { + case configMode + case configRemoteURL + case userDefaults + case onboarding +} + +struct EffectiveConnectionMode: Sendable, Equatable { + let mode: AppState.ConnectionMode + let source: EffectiveConnectionModeSource +} + +enum ConnectionModeResolver { + static func resolve( + root: [String: Any], + defaults: UserDefaults = .standard) -> EffectiveConnectionMode + { + let gateway = root["gateway"] as? [String: Any] + let configModeRaw = (gateway?["mode"] as? String) ?? "" + let configMode = configModeRaw + .trimmingCharacters(in: .whitespacesAndNewlines) + .lowercased() + + switch configMode { + case "local": + return EffectiveConnectionMode(mode: .local, source: .configMode) + case "remote": + return EffectiveConnectionMode(mode: .remote, source: .configMode) + default: + break + } + + let remoteURLRaw = ((gateway?["remote"] as? [String: Any])?["url"] as? String) ?? "" + let remoteURL = remoteURLRaw.trimmingCharacters(in: .whitespacesAndNewlines) + if !remoteURL.isEmpty { + return EffectiveConnectionMode(mode: .remote, source: .configRemoteURL) + } + + if let storedModeRaw = defaults.string(forKey: connectionModeKey) { + let storedMode = AppState.ConnectionMode(rawValue: storedModeRaw) ?? .local + return EffectiveConnectionMode(mode: storedMode, source: .userDefaults) + } + + let seen = defaults.bool(forKey: "clawdbot.onboardingSeen") + return EffectiveConnectionMode(mode: seen ? .local : .unconfigured, source: .onboarding) + } +} diff --git a/apps/macos/Sources/Clawdbot/ConnectionsSettings+ChannelSections.swift b/apps/macos/Sources/Clawdbot/ConnectionsSettings+ChannelSections.swift deleted file mode 100644 index 8ad413b0a..000000000 --- a/apps/macos/Sources/Clawdbot/ConnectionsSettings+ChannelSections.swift +++ /dev/null @@ -1,707 +0,0 @@ -import SwiftUI - -extension ConnectionsSettings { - func formSection(_ title: String, @ViewBuilder content: () -> some View) -> some View { - GroupBox(title) { - VStack(alignment: .leading, spacing: 10) { - content() - } - .frame(maxWidth: .infinity, alignment: .leading) - } - } - - @ViewBuilder - func channelHeaderActions(_ channel: ConnectionChannel) -> some View { - HStack(spacing: 8) { - if channel == .whatsapp { - Button("Logout") { - Task { await self.store.logoutWhatsApp() } - } - .buttonStyle(.bordered) - .disabled(self.store.whatsappBusy) - } - - if channel == .telegram { - Button("Logout") { - Task { await self.store.logoutTelegram() } - } - .buttonStyle(.bordered) - .disabled(self.store.telegramBusy) - } - - Button { - Task { await self.store.refresh(probe: true) } - } label: { - if self.store.isRefreshing { - ProgressView().controlSize(.small) - } else { - Text("Refresh") - } - } - .buttonStyle(.bordered) - .disabled(self.store.isRefreshing) - } - .controlSize(.small) - } - - var whatsAppSection: some View { - VStack(alignment: .leading, spacing: 16) { - self.formSection("Linking") { - if let message = self.store.whatsappLoginMessage { - Text(message) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - - if let qr = self.store.whatsappLoginQrDataUrl, let image = self.qrImage(from: qr) { - Image(nsImage: image) - .resizable() - .interpolation(.none) - .frame(width: 180, height: 180) - .cornerRadius(8) - } - - HStack(spacing: 12) { - Button { - Task { await self.store.startWhatsAppLogin(force: false) } - } label: { - if self.store.whatsappBusy { - ProgressView().controlSize(.small) - } else { - Text("Show QR") - } - } - .buttonStyle(.borderedProminent) - .disabled(self.store.whatsappBusy) - - Button("Relink") { - Task { await self.store.startWhatsAppLogin(force: true) } - } - .buttonStyle(.bordered) - .disabled(self.store.whatsappBusy) - } - .font(.caption) - } - } - } - - var telegramSection: some View { - VStack(alignment: .leading, spacing: 16) { - self.formSection("Authentication") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Bot token") - if self.showTelegramToken { - TextField("123:abc", text: self.$store.telegramToken) - .textFieldStyle(.roundedBorder) - .disabled(self.isTelegramTokenLocked) - } else { - SecureField("123:abc", text: self.$store.telegramToken) - .textFieldStyle(.roundedBorder) - .disabled(self.isTelegramTokenLocked) - } - Toggle("Show", isOn: self.$showTelegramToken) - .toggleStyle(.switch) - .disabled(self.isTelegramTokenLocked) - } - } - } - - self.formSection("Access") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Require mention") - Toggle("", isOn: self.$store.telegramRequireMention) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Allow from") - TextField("123456789, @team", text: self.$store.telegramAllowFrom) - .textFieldStyle(.roundedBorder) - } - } - } - - self.formSection("Webhook") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Webhook URL") - TextField("https://example.com/telegram-webhook", text: self.$store.telegramWebhookUrl) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Webhook secret") - TextField("secret", text: self.$store.telegramWebhookSecret) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Webhook path") - TextField("/telegram-webhook", text: self.$store.telegramWebhookPath) - .textFieldStyle(.roundedBorder) - } - } - } - - self.formSection("Network") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Proxy") - TextField("socks5://localhost:9050", text: self.$store.telegramProxy) - .textFieldStyle(.roundedBorder) - } - } - } - - if self.isTelegramTokenLocked { - Text("Token set via TELEGRAM_BOT_TOKEN env; config edits won’t override it.") - .font(.caption) - .foregroundStyle(.secondary) - } - - self.configStatusMessage - - HStack(spacing: 12) { - Button { - Task { await self.store.saveTelegramConfig() } - } label: { - if self.store.isSavingConfig { - ProgressView().controlSize(.small) - } else { - Text("Save") - } - } - .buttonStyle(.borderedProminent) - .disabled(self.store.isSavingConfig) - - Spacer() - } - .font(.caption) - } - } - - var discordSection: some View { - VStack(alignment: .leading, spacing: 16) { - self.formSection("Authentication") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Enabled") - Toggle("", isOn: self.$store.discordEnabled) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Bot token") - if self.showDiscordToken { - TextField("bot token", text: self.$store.discordToken) - .textFieldStyle(.roundedBorder) - .disabled(self.isDiscordTokenLocked) - } else { - SecureField("bot token", text: self.$store.discordToken) - .textFieldStyle(.roundedBorder) - .disabled(self.isDiscordTokenLocked) - } - Toggle("Show", isOn: self.$showDiscordToken) - .toggleStyle(.switch) - .disabled(self.isDiscordTokenLocked) - } - } - } - - self.formSection("Messages") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Allow DMs from") - TextField("123456789, username#1234", text: self.$store.discordAllowFrom) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("DMs enabled") - Toggle("", isOn: self.$store.discordDmEnabled) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Group DMs") - Toggle("", isOn: self.$store.discordGroupEnabled) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Group channels") - TextField("channelId1, channelId2", text: self.$store.discordGroupChannels) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Reply to mode") - Picker("", selection: self.$store.discordReplyToMode) { - Text("off").tag("off") - Text("first").tag("first") - Text("all").tag("all") - } - .labelsHidden() - } - } - } - - self.formSection("Limits") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Media max MB") - TextField("8", text: self.$store.discordMediaMaxMb) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("History limit") - TextField("20", text: self.$store.discordHistoryLimit) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Text chunk limit") - TextField("2000", text: self.$store.discordTextChunkLimit) - .textFieldStyle(.roundedBorder) - } - } - } - - self.formSection("Slash command") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Enabled") - Toggle("", isOn: self.$store.discordSlashEnabled) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Slash name") - TextField("clawd", text: self.$store.discordSlashName) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Session prefix") - TextField("discord:slash", text: self.$store.discordSlashSessionPrefix) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Ephemeral") - Toggle("", isOn: self.$store.discordSlashEphemeral) - .labelsHidden() - .toggleStyle(.checkbox) - } - } - } - - GroupBox("Guilds") { - VStack(alignment: .leading, spacing: 12) { - ForEach(self.$store.discordGuilds) { $guild in - VStack(alignment: .leading, spacing: 10) { - HStack { - TextField("guild id or slug", text: $guild.key) - .textFieldStyle(.roundedBorder) - Button("Remove") { - self.store.discordGuilds.removeAll { $0.id == guild.id } - } - .buttonStyle(.bordered) - } - - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Slug") - TextField("optional slug", text: $guild.slug) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Require mention") - Toggle("", isOn: $guild.requireMention) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Reaction notifications") - Picker("", selection: $guild.reactionNotifications) { - Text("Off").tag("off") - Text("Own").tag("own") - Text("All").tag("all") - Text("Allowlist").tag("allowlist") - } - .labelsHidden() - .pickerStyle(.segmented) - } - GridRow { - self.gridLabel("Users allowlist") - TextField("123456789, username#1234", text: $guild.users) - .textFieldStyle(.roundedBorder) - } - } - - Text("Channels") - .font(.caption) - .foregroundStyle(.secondary) - - VStack(alignment: .leading, spacing: 8) { - ForEach($guild.channels) { $channel in - HStack(spacing: 10) { - TextField("channel id or slug", text: $channel.key) - .textFieldStyle(.roundedBorder) - Toggle("Allow", isOn: $channel.allow) - .toggleStyle(.checkbox) - Toggle("Require mention", isOn: $channel.requireMention) - .toggleStyle(.checkbox) - Button("Remove") { - guild.channels.removeAll { $0.id == channel.id } - } - .buttonStyle(.bordered) - } - } - Button("Add channel") { - guild.channels.append(DiscordGuildChannelForm()) - } - .buttonStyle(.bordered) - } - } - .padding(10) - .background(Color.secondary.opacity(0.08)) - .clipShape(RoundedRectangle(cornerRadius: 8)) - } - - Button("Add guild") { - self.store.discordGuilds.append(DiscordGuildForm()) - } - .buttonStyle(.bordered) - } - .frame(maxWidth: .infinity, alignment: .leading) - } - - GroupBox("Tool actions") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Reactions") - Toggle("", isOn: self.$store.discordActionReactions) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Stickers") - Toggle("", isOn: self.$store.discordActionStickers) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Polls") - Toggle("", isOn: self.$store.discordActionPolls) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Permissions") - Toggle("", isOn: self.$store.discordActionPermissions) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Messages") - Toggle("", isOn: self.$store.discordActionMessages) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Threads") - Toggle("", isOn: self.$store.discordActionThreads) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Pins") - Toggle("", isOn: self.$store.discordActionPins) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Search") - Toggle("", isOn: self.$store.discordActionSearch) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Member info") - Toggle("", isOn: self.$store.discordActionMemberInfo) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Role info") - Toggle("", isOn: self.$store.discordActionRoleInfo) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Channel info") - Toggle("", isOn: self.$store.discordActionChannelInfo) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Voice status") - Toggle("", isOn: self.$store.discordActionVoiceStatus) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Events") - Toggle("", isOn: self.$store.discordActionEvents) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Role changes") - Toggle("", isOn: self.$store.discordActionRoles) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Moderation") - Toggle("", isOn: self.$store.discordActionModeration) - .labelsHidden() - .toggleStyle(.checkbox) - } - } - .frame(maxWidth: .infinity, alignment: .leading) - } - - if self.isDiscordTokenLocked { - Text("Token set via DISCORD_BOT_TOKEN env; config edits won’t override it.") - .font(.caption) - .foregroundStyle(.secondary) - } - - self.configStatusMessage - - HStack(spacing: 12) { - Button { - Task { await self.store.saveDiscordConfig() } - } label: { - if self.store.isSavingConfig { - ProgressView().controlSize(.small) - } else { - Text("Save") - } - } - .buttonStyle(.borderedProminent) - .disabled(self.store.isSavingConfig) - - Spacer() - } - .font(.caption) - } - } - - var signalSection: some View { - VStack(alignment: .leading, spacing: 16) { - self.formSection("Connection") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Enabled") - Toggle("", isOn: self.$store.signalEnabled) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Account") - TextField("+15551234567", text: self.$store.signalAccount) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("HTTP URL") - TextField("http://127.0.0.1:8080", text: self.$store.signalHttpUrl) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("HTTP host") - TextField("127.0.0.1", text: self.$store.signalHttpHost) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("HTTP port") - TextField("8080", text: self.$store.signalHttpPort) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("CLI path") - TextField("signal-cli", text: self.$store.signalCliPath) - .textFieldStyle(.roundedBorder) - } - } - } - - self.formSection("Behavior") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Auto start") - Toggle("", isOn: self.$store.signalAutoStart) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Receive mode") - Picker("", selection: self.$store.signalReceiveMode) { - Text("Default").tag("") - Text("on-start").tag("on-start") - Text("manual").tag("manual") - } - .labelsHidden() - .pickerStyle(.menu) - } - GridRow { - self.gridLabel("Ignore attachments") - Toggle("", isOn: self.$store.signalIgnoreAttachments) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Ignore stories") - Toggle("", isOn: self.$store.signalIgnoreStories) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Read receipts") - Toggle("", isOn: self.$store.signalSendReadReceipts) - .labelsHidden() - .toggleStyle(.checkbox) - } - } - } - - self.formSection("Access & limits") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Allow from") - TextField("12345, +1555", text: self.$store.signalAllowFrom) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Media max MB") - TextField("8", text: self.$store.signalMediaMaxMb) - .textFieldStyle(.roundedBorder) - } - } - } - - self.configStatusMessage - - HStack(spacing: 12) { - Button { - Task { await self.store.saveSignalConfig() } - } label: { - if self.store.isSavingConfig { - ProgressView().controlSize(.small) - } else { - Text("Save") - } - } - .buttonStyle(.borderedProminent) - .disabled(self.store.isSavingConfig) - - Spacer() - } - .font(.caption) - } - } - - var imessageSection: some View { - VStack(alignment: .leading, spacing: 16) { - self.formSection("Connection") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Enabled") - Toggle("", isOn: self.$store.imessageEnabled) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("CLI path") - TextField("imsg", text: self.$store.imessageCliPath) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("DB path") - TextField("~/Library/Messages/chat.db", text: self.$store.imessageDbPath) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Service") - Picker("", selection: self.$store.imessageService) { - Text("auto").tag("auto") - Text("imessage").tag("imessage") - Text("sms").tag("sms") - } - .labelsHidden() - .pickerStyle(.menu) - } - } - } - - self.formSection("Behavior") { - Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 14, verticalSpacing: 8) { - GridRow { - self.gridLabel("Region") - TextField("US", text: self.$store.imessageRegion) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Allow from") - TextField("chat_id:101, +1555", text: self.$store.imessageAllowFrom) - .textFieldStyle(.roundedBorder) - } - GridRow { - self.gridLabel("Attachments") - Toggle("", isOn: self.$store.imessageIncludeAttachments) - .labelsHidden() - .toggleStyle(.checkbox) - } - GridRow { - self.gridLabel("Media max MB") - TextField("16", text: self.$store.imessageMediaMaxMb) - .textFieldStyle(.roundedBorder) - } - } - } - - self.configStatusMessage - - HStack(spacing: 12) { - Button { - Task { await self.store.saveIMessageConfig() } - } label: { - if self.store.isSavingConfig { - ProgressView().controlSize(.small) - } else { - Text("Save") - } - } - .buttonStyle(.borderedProminent) - .disabled(self.store.isSavingConfig) - - Spacer() - } - .font(.caption) - } - } - - @ViewBuilder - var configStatusMessage: some View { - if let status = self.store.configStatus { - Text(status) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - } - - func gridLabel(_ text: String) -> some View { - Text(text) - .font(.callout.weight(.semibold)) - .frame(width: 140, alignment: .leading) - } -} diff --git a/apps/macos/Sources/Clawdbot/ConnectionsSettings.swift b/apps/macos/Sources/Clawdbot/ConnectionsSettings.swift deleted file mode 100644 index 0976f7397..000000000 --- a/apps/macos/Sources/Clawdbot/ConnectionsSettings.swift +++ /dev/null @@ -1,63 +0,0 @@ -import AppKit -import SwiftUI - -struct ConnectionsSettings: View { - enum ConnectionChannel: String, CaseIterable, Identifiable, Hashable { - case whatsapp - case telegram - case discord - case signal - case imessage - - var id: String { self.rawValue } - - var sortOrder: Int { - switch self { - case .whatsapp: 0 - case .telegram: 1 - case .discord: 2 - case .signal: 3 - case .imessage: 4 - } - } - - var title: String { - switch self { - case .whatsapp: "WhatsApp" - case .telegram: "Telegram" - case .discord: "Discord" - case .signal: "Signal" - case .imessage: "iMessage" - } - } - - var detailTitle: String { - switch self { - case .whatsapp: "WhatsApp Web" - case .telegram: "Telegram Bot" - case .discord: "Discord Bot" - case .signal: "Signal REST" - case .imessage: "iMessage (imsg)" - } - } - - var systemImage: String { - switch self { - case .whatsapp: "message" - case .telegram: "paperplane" - case .discord: "bubble.left.and.bubble.right" - case .signal: "antenna.radiowaves.left.and.right" - case .imessage: "message.fill" - } - } - } - - @Bindable var store: ConnectionsStore - @State var selectedChannel: ConnectionChannel? - @State var showTelegramToken = false - @State var showDiscordToken = false - - init(store: ConnectionsStore = .shared) { - self.store = store - } -} diff --git a/apps/macos/Sources/Clawdbot/ConnectionsStore+Config.swift b/apps/macos/Sources/Clawdbot/ConnectionsStore+Config.swift deleted file mode 100644 index 076693db4..000000000 --- a/apps/macos/Sources/Clawdbot/ConnectionsStore+Config.swift +++ /dev/null @@ -1,594 +0,0 @@ -import ClawdbotProtocol -import Foundation - -extension ConnectionsStore { - var isTelegramTokenLocked: Bool { - self.snapshot?.decodeChannel("telegram", as: ChannelsStatusSnapshot.TelegramStatus.self)? - .tokenSource == "env" - } - - var isDiscordTokenLocked: Bool { - self.snapshot?.decodeChannel("discord", as: ChannelsStatusSnapshot.DiscordStatus.self)? - .tokenSource == "env" - } - - func loadConfig() async { - do { - let snap: ConfigSnapshot = try await GatewayConnection.shared.requestDecoded( - method: .configGet, - params: nil, - timeoutMs: 10000) - self.configStatus = snap.valid == false - ? "Config invalid; fix it in ~/.clawdbot/clawdbot.json." - : nil - self.configRoot = snap.config?.mapValues { $0.foundationValue } ?? [:] - self.configHash = snap.hash - self.configLoaded = true - - self.applyUIConfig(snap) - self.applyTelegramConfig(snap) - self.applyDiscordConfig(snap) - self.applySignalConfig(snap) - self.applyIMessageConfig(snap) - } catch { - self.configStatus = error.localizedDescription - } - } - - private func applyUIConfig(_ snap: ConfigSnapshot) { - let ui = snap.config?[ - "ui", - ]?.dictionaryValue - let rawSeam = ui?[ - "seamColor", - ]?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - AppStateStore.shared.seamColorHex = rawSeam.isEmpty ? nil : rawSeam - } - - private func resolveChannelConfig(_ snap: ConfigSnapshot, key: String) -> [String: AnyCodable]? { - if let channels = snap.config?["channels"]?.dictionaryValue, - let entry = channels[key]?.dictionaryValue - { - return entry - } - return snap.config?[key]?.dictionaryValue - } - - private func applyTelegramConfig(_ snap: ConfigSnapshot) { - let telegram = self.resolveChannelConfig(snap, key: "telegram") - self.telegramToken = telegram?["botToken"]?.stringValue ?? "" - let groups = telegram?["groups"]?.dictionaryValue - let defaultGroup = groups?["*"]?.dictionaryValue - self.telegramRequireMention = defaultGroup?["requireMention"]?.boolValue - ?? telegram?["requireMention"]?.boolValue - ?? true - self.telegramAllowFrom = self.stringList(from: telegram?["allowFrom"]?.arrayValue) - self.telegramProxy = telegram?["proxy"]?.stringValue ?? "" - self.telegramWebhookUrl = telegram?["webhookUrl"]?.stringValue ?? "" - self.telegramWebhookSecret = telegram?["webhookSecret"]?.stringValue ?? "" - self.telegramWebhookPath = telegram?["webhookPath"]?.stringValue ?? "" - } - - private func applyDiscordConfig(_ snap: ConfigSnapshot) { - let discord = self.resolveChannelConfig(snap, key: "discord") - self.discordEnabled = discord?["enabled"]?.boolValue ?? true - self.discordToken = discord?["token"]?.stringValue ?? "" - - let discordDm = discord?["dm"]?.dictionaryValue - self.discordDmEnabled = discordDm?["enabled"]?.boolValue ?? true - self.discordAllowFrom = self.stringList(from: discordDm?["allowFrom"]?.arrayValue) - self.discordGroupEnabled = discordDm?["groupEnabled"]?.boolValue ?? false - self.discordGroupChannels = self.stringList(from: discordDm?["groupChannels"]?.arrayValue) - self.discordMediaMaxMb = self.numberString(from: discord?["mediaMaxMb"]) - self.discordHistoryLimit = self.numberString(from: discord?["historyLimit"]) - self.discordTextChunkLimit = self.numberString(from: discord?["textChunkLimit"]) - self.discordReplyToMode = self.replyMode(from: discord?["replyToMode"]?.stringValue) - self.discordGuilds = self.decodeDiscordGuilds(discord?["guilds"]?.dictionaryValue) - - let discordActions = discord?["actions"]?.dictionaryValue - self.discordActionReactions = discordActions?["reactions"]?.boolValue ?? true - self.discordActionStickers = discordActions?["stickers"]?.boolValue ?? true - self.discordActionPolls = discordActions?["polls"]?.boolValue ?? true - self.discordActionPermissions = discordActions?["permissions"]?.boolValue ?? true - self.discordActionMessages = discordActions?["messages"]?.boolValue ?? true - self.discordActionThreads = discordActions?["threads"]?.boolValue ?? true - self.discordActionPins = discordActions?["pins"]?.boolValue ?? true - self.discordActionSearch = discordActions?["search"]?.boolValue ?? true - self.discordActionMemberInfo = discordActions?["memberInfo"]?.boolValue ?? true - self.discordActionRoleInfo = discordActions?["roleInfo"]?.boolValue ?? true - self.discordActionChannelInfo = discordActions?["channelInfo"]?.boolValue ?? true - self.discordActionVoiceStatus = discordActions?["voiceStatus"]?.boolValue ?? true - self.discordActionEvents = discordActions?["events"]?.boolValue ?? true - self.discordActionRoles = discordActions?["roles"]?.boolValue ?? false - self.discordActionModeration = discordActions?["moderation"]?.boolValue ?? false - - let slash = discord?["slashCommand"]?.dictionaryValue - self.discordSlashEnabled = slash?["enabled"]?.boolValue ?? false - self.discordSlashName = slash?["name"]?.stringValue ?? "" - self.discordSlashSessionPrefix = slash?["sessionPrefix"]?.stringValue ?? "" - self.discordSlashEphemeral = slash?["ephemeral"]?.boolValue ?? true - } - - private func decodeDiscordGuilds(_ guilds: [String: AnyCodable]?) -> [DiscordGuildForm] { - guard let guilds else { return [] } - return guilds - .map { key, value in - let entry = value.dictionaryValue ?? [:] - let slug = entry["slug"]?.stringValue ?? "" - let requireMention = entry["requireMention"]?.boolValue ?? false - let reactionModeRaw = entry["reactionNotifications"]?.stringValue ?? "" - let reactionNotifications = ["off", "own", "all", "allowlist"].contains(reactionModeRaw) - ? reactionModeRaw - : "own" - let users = self.stringList(from: entry["users"]?.arrayValue) - let channels: [DiscordGuildChannelForm] = if let channelMap = entry["channels"]?.dictionaryValue { - channelMap.map { channelKey, channelValue in - let channelEntry = channelValue.dictionaryValue ?? [:] - let allow = channelEntry["allow"]?.boolValue ?? true - let channelRequireMention = channelEntry["requireMention"]?.boolValue ?? false - return DiscordGuildChannelForm( - key: channelKey, - allow: allow, - requireMention: channelRequireMention) - } - } else { - [] - } - return DiscordGuildForm( - key: key, - slug: slug, - requireMention: requireMention, - reactionNotifications: reactionNotifications, - users: users, - channels: channels) - } - .sorted { $0.key < $1.key } - } - - private func applySignalConfig(_ snap: ConfigSnapshot) { - let signal = self.resolveChannelConfig(snap, key: "signal") - self.signalEnabled = signal?["enabled"]?.boolValue ?? true - self.signalAccount = signal?["account"]?.stringValue ?? "" - self.signalHttpUrl = signal?["httpUrl"]?.stringValue ?? "" - self.signalHttpHost = signal?["httpHost"]?.stringValue ?? "" - self.signalHttpPort = self.numberString(from: signal?["httpPort"]) - self.signalCliPath = signal?["cliPath"]?.stringValue ?? "" - self.signalAutoStart = signal?["autoStart"]?.boolValue ?? true - self.signalReceiveMode = signal?["receiveMode"]?.stringValue ?? "" - self.signalIgnoreAttachments = signal?["ignoreAttachments"]?.boolValue ?? false - self.signalIgnoreStories = signal?["ignoreStories"]?.boolValue ?? false - self.signalSendReadReceipts = signal?["sendReadReceipts"]?.boolValue ?? false - self.signalAllowFrom = self.stringList(from: signal?["allowFrom"]?.arrayValue) - self.signalMediaMaxMb = self.numberString(from: signal?["mediaMaxMb"]) - } - - private func applyIMessageConfig(_ snap: ConfigSnapshot) { - let imessage = self.resolveChannelConfig(snap, key: "imessage") - self.imessageEnabled = imessage?["enabled"]?.boolValue ?? true - self.imessageCliPath = imessage?["cliPath"]?.stringValue ?? "" - self.imessageDbPath = imessage?["dbPath"]?.stringValue ?? "" - self.imessageService = imessage?["service"]?.stringValue ?? "auto" - self.imessageRegion = imessage?["region"]?.stringValue ?? "" - self.imessageAllowFrom = self.stringList(from: imessage?["allowFrom"]?.arrayValue) - self.imessageIncludeAttachments = imessage?["includeAttachments"]?.boolValue ?? false - self.imessageMediaMaxMb = self.numberString(from: imessage?["mediaMaxMb"]) - } - - private func channelConfigRoot(for key: String) -> [String: Any] { - if let channels = self.configRoot["channels"] as? [String: Any], - let entry = channels[key] as? [String: Any] - { - return entry - } - return self.configRoot[key] as? [String: Any] ?? [:] - } - - func saveTelegramConfig() async { - guard !self.isSavingConfig else { return } - self.isSavingConfig = true - defer { self.isSavingConfig = false } - if !self.configLoaded { - await self.loadConfig() - } - - var telegram: [String: Any] = [:] - if !self.isTelegramTokenLocked { - self.setPatchString(&telegram, key: "botToken", value: self.telegramToken) - } - telegram["requireMention"] = NSNull() - telegram["groups"] = [ - "*": [ - "requireMention": self.telegramRequireMention, - ], - ] - let allow = self.splitCsv(self.telegramAllowFrom) - self.setPatchList(&telegram, key: "allowFrom", values: allow) - self.setPatchString(&telegram, key: "proxy", value: self.telegramProxy) - self.setPatchString(&telegram, key: "webhookUrl", value: self.telegramWebhookUrl) - self.setPatchString(&telegram, key: "webhookSecret", value: self.telegramWebhookSecret) - self.setPatchString(&telegram, key: "webhookPath", value: self.telegramWebhookPath) - - await self.persistChannelPatch("telegram", payload: telegram) - } - - func saveDiscordConfig() async { - guard !self.isSavingConfig else { return } - self.isSavingConfig = true - defer { self.isSavingConfig = false } - if !self.configLoaded { - await self.loadConfig() - } - - let base = self.channelConfigRoot(for: "discord") - let discord = self.buildDiscordPatch(base: base) - await self.persistChannelPatch("discord", payload: discord) - } - - func saveSignalConfig() async { - guard !self.isSavingConfig else { return } - self.isSavingConfig = true - defer { self.isSavingConfig = false } - if !self.configLoaded { - await self.loadConfig() - } - - var signal: [String: Any] = [:] - self.setPatchBool(&signal, key: "enabled", value: self.signalEnabled, defaultValue: true) - self.setPatchString(&signal, key: "account", value: self.signalAccount) - self.setPatchString(&signal, key: "httpUrl", value: self.signalHttpUrl) - self.setPatchString(&signal, key: "httpHost", value: self.signalHttpHost) - self.setPatchNumber(&signal, key: "httpPort", value: self.signalHttpPort) - self.setPatchString(&signal, key: "cliPath", value: self.signalCliPath) - self.setPatchBool(&signal, key: "autoStart", value: self.signalAutoStart, defaultValue: true) - self.setPatchString(&signal, key: "receiveMode", value: self.signalReceiveMode) - self.setPatchBool(&signal, key: "ignoreAttachments", value: self.signalIgnoreAttachments, defaultValue: false) - self.setPatchBool(&signal, key: "ignoreStories", value: self.signalIgnoreStories, defaultValue: false) - self.setPatchBool(&signal, key: "sendReadReceipts", value: self.signalSendReadReceipts, defaultValue: false) - let allow = self.splitCsv(self.signalAllowFrom) - self.setPatchList(&signal, key: "allowFrom", values: allow) - self.setPatchNumber(&signal, key: "mediaMaxMb", value: self.signalMediaMaxMb) - - await self.persistChannelPatch("signal", payload: signal) - } - - func saveIMessageConfig() async { - guard !self.isSavingConfig else { return } - self.isSavingConfig = true - defer { self.isSavingConfig = false } - if !self.configLoaded { - await self.loadConfig() - } - - var imessage: [String: Any] = [:] - self.setPatchBool(&imessage, key: "enabled", value: self.imessageEnabled, defaultValue: true) - self.setPatchString(&imessage, key: "cliPath", value: self.imessageCliPath) - self.setPatchString(&imessage, key: "dbPath", value: self.imessageDbPath) - - let service = self.trimmed(self.imessageService) - if service.isEmpty || service == "auto" { - imessage["service"] = NSNull() - } else { - imessage["service"] = service - } - - self.setPatchString(&imessage, key: "region", value: self.imessageRegion) - - let allow = self.splitCsv(self.imessageAllowFrom) - self.setPatchList(&imessage, key: "allowFrom", values: allow) - - self.setPatchBool( - &imessage, - key: "includeAttachments", - value: self.imessageIncludeAttachments, - defaultValue: false) - self.setPatchNumber(&imessage, key: "mediaMaxMb", value: self.imessageMediaMaxMb) - - await self.persistChannelPatch("imessage", payload: imessage) - } - - private func buildDiscordPatch(base: [String: Any]) -> [String: Any] { - var discord: [String: Any] = [:] - self.setPatchBool(&discord, key: "enabled", value: self.discordEnabled, defaultValue: true) - if !self.isDiscordTokenLocked { - self.setPatchString(&discord, key: "token", value: self.discordToken) - } - - if let dm = self.buildDiscordDmPatch() { - discord["dm"] = dm - } else { - discord["dm"] = NSNull() - } - - self.setPatchNumber(&discord, key: "mediaMaxMb", value: self.discordMediaMaxMb) - self.setPatchInt(&discord, key: "historyLimit", value: self.discordHistoryLimit, allowZero: true) - self.setPatchInt(&discord, key: "textChunkLimit", value: self.discordTextChunkLimit, allowZero: false) - - let replyToMode = self.trimmed(self.discordReplyToMode) - if replyToMode.isEmpty || replyToMode == "off" || !["first", "all"].contains(replyToMode) { - discord["replyToMode"] = NSNull() - } else { - discord["replyToMode"] = replyToMode - } - - let baseGuilds = base["guilds"] as? [String: Any] ?? [:] - if let guilds = self.buildDiscordGuildsPatch(base: baseGuilds) { - discord["guilds"] = guilds - } else { - discord["guilds"] = NSNull() - } - - if let actions = self.buildDiscordActionsPatch() { - discord["actions"] = actions - } else { - discord["actions"] = NSNull() - } - - if let slash = self.buildDiscordSlashPatch() { - discord["slashCommand"] = slash - } else { - discord["slashCommand"] = NSNull() - } - - return discord - } - - private func buildDiscordDmPatch() -> [String: Any]? { - var dm: [String: Any] = [:] - self.setPatchBool(&dm, key: "enabled", value: self.discordDmEnabled, defaultValue: true) - let allow = self.splitCsv(self.discordAllowFrom) - self.setPatchList(&dm, key: "allowFrom", values: allow) - self.setPatchBool(&dm, key: "groupEnabled", value: self.discordGroupEnabled, defaultValue: false) - let groupChannels = self.splitCsv(self.discordGroupChannels) - self.setPatchList(&dm, key: "groupChannels", values: groupChannels) - return dm.isEmpty ? nil : dm - } - - private func buildDiscordGuildsPatch(base: [String: Any]) -> Any? { - if self.discordGuilds.isEmpty { - return NSNull() - } - var patch: [String: Any] = [:] - let baseKeys = Set(base.keys) - var formKeys = Set() - for entry in self.discordGuilds { - let key = self.trimmed(entry.key) - guard !key.isEmpty else { continue } - formKeys.insert(key) - let baseGuild = base[key] as? [String: Any] ?? [:] - patch[key] = self.buildDiscordGuildPatch(entry, base: baseGuild) - } - for key in baseKeys.subtracting(formKeys) { - patch[key] = NSNull() - } - return patch.isEmpty ? NSNull() : patch - } - - private func buildDiscordGuildPatch(_ entry: DiscordGuildForm, base: [String: Any]) -> [String: Any] { - var payload: [String: Any] = [:] - let slug = self.trimmed(entry.slug) - if slug.isEmpty { - payload["slug"] = NSNull() - } else { - payload["slug"] = slug - } - if entry.requireMention { - payload["requireMention"] = true - } else { - payload["requireMention"] = NSNull() - } - if ["off", "all", "allowlist"].contains(entry.reactionNotifications) { - payload["reactionNotifications"] = entry.reactionNotifications - } else { - payload["reactionNotifications"] = NSNull() - } - let users = self.splitCsv(entry.users) - self.setPatchList(&payload, key: "users", values: users) - - let baseChannels = base["channels"] as? [String: Any] ?? [:] - if let channels = self.buildDiscordChannelsPatch(base: baseChannels, forms: entry.channels) { - payload["channels"] = channels - } else { - payload["channels"] = NSNull() - } - return payload - } - - private func buildDiscordChannelsPatch(base: [String: Any], forms: [DiscordGuildChannelForm]) -> Any? { - if forms.isEmpty { - return NSNull() - } - var patch: [String: Any] = [:] - let baseKeys = Set(base.keys) - var formKeys = Set() - for channel in forms { - let channelKey = self.trimmed(channel.key) - guard !channelKey.isEmpty else { continue } - formKeys.insert(channelKey) - var channelPayload: [String: Any] = [:] - self.setPatchBool(&channelPayload, key: "allow", value: channel.allow, defaultValue: true) - self.setPatchBool( - &channelPayload, - key: "requireMention", - value: channel.requireMention, - defaultValue: false) - patch[channelKey] = channelPayload - } - for key in baseKeys.subtracting(formKeys) { - patch[key] = NSNull() - } - return patch.isEmpty ? NSNull() : patch - } - - private func buildDiscordActionsPatch() -> [String: Any]? { - var actions: [String: Any] = [:] - self.setAction(&actions, key: "reactions", value: self.discordActionReactions, defaultValue: true) - self.setAction(&actions, key: "stickers", value: self.discordActionStickers, defaultValue: true) - self.setAction(&actions, key: "polls", value: self.discordActionPolls, defaultValue: true) - self.setAction(&actions, key: "permissions", value: self.discordActionPermissions, defaultValue: true) - self.setAction(&actions, key: "messages", value: self.discordActionMessages, defaultValue: true) - self.setAction(&actions, key: "threads", value: self.discordActionThreads, defaultValue: true) - self.setAction(&actions, key: "pins", value: self.discordActionPins, defaultValue: true) - self.setAction(&actions, key: "search", value: self.discordActionSearch, defaultValue: true) - self.setAction(&actions, key: "memberInfo", value: self.discordActionMemberInfo, defaultValue: true) - self.setAction(&actions, key: "roleInfo", value: self.discordActionRoleInfo, defaultValue: true) - self.setAction(&actions, key: "channelInfo", value: self.discordActionChannelInfo, defaultValue: true) - self.setAction(&actions, key: "voiceStatus", value: self.discordActionVoiceStatus, defaultValue: true) - self.setAction(&actions, key: "events", value: self.discordActionEvents, defaultValue: true) - self.setAction(&actions, key: "roles", value: self.discordActionRoles, defaultValue: false) - self.setAction(&actions, key: "moderation", value: self.discordActionModeration, defaultValue: false) - return actions.isEmpty ? nil : actions - } - - private func buildDiscordSlashPatch() -> [String: Any]? { - var slash: [String: Any] = [:] - self.setPatchBool(&slash, key: "enabled", value: self.discordSlashEnabled, defaultValue: false) - self.setPatchString(&slash, key: "name", value: self.discordSlashName) - self.setPatchString(&slash, key: "sessionPrefix", value: self.discordSlashSessionPrefix) - self.setPatchBool(&slash, key: "ephemeral", value: self.discordSlashEphemeral, defaultValue: true) - return slash.isEmpty ? nil : slash - } - - private func persistChannelPatch(_ channelId: String, payload: [String: Any]) async { - do { - guard let baseHash = self.configHash else { - self.configStatus = "Config hash missing; reload and retry." - return - } - let data = try JSONSerialization.data( - withJSONObject: ["channels": [channelId: payload]], - options: [.prettyPrinted, .sortedKeys]) - guard let raw = String(data: data, encoding: .utf8) else { - self.configStatus = "Failed to encode config." - return - } - let params: [String: AnyCodable] = [ - "raw": AnyCodable(raw), - "baseHash": AnyCodable(baseHash), - ] - _ = try await GatewayConnection.shared.requestRaw( - method: .configPatch, - params: params, - timeoutMs: 10000) - self.configStatus = "Saved to ~/.clawdbot/clawdbot.json." - await self.loadConfig() - await self.refresh(probe: true) - } catch { - self.configStatus = error.localizedDescription - } - } - - private func stringList(from values: [AnyCodable]?) -> String { - guard let values else { return "" } - let strings = values.compactMap { entry -> String? in - if let str = entry.stringValue { return str } - if let intVal = entry.intValue { return String(intVal) } - if let doubleVal = entry.doubleValue { return String(Int(doubleVal)) } - return nil - } - return strings.joined(separator: ", ") - } - - private func numberString(from value: AnyCodable?) -> String { - if let number = value?.doubleValue ?? value?.intValue.map(Double.init) { - return String(Int(number)) - } - return "" - } - - private func replyMode(from value: String?) -> String { - if let value, ["off", "first", "all"].contains(value) { - return value - } - return "off" - } - - private func splitCsv(_ value: String) -> [String] { - value - .split(separator: ",") - .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty } - } - - private func trimmed(_ value: String) -> String { - value.trimmingCharacters(in: .whitespacesAndNewlines) - } - - private func setPatchString(_ target: inout [String: Any], key: String, value: String) { - let trimmed = self.trimmed(value) - if trimmed.isEmpty { - target[key] = NSNull() - } else { - target[key] = trimmed - } - } - - private func setPatchNumber(_ target: inout [String: Any], key: String, value: String) { - let trimmed = self.trimmed(value) - if trimmed.isEmpty { - target[key] = NSNull() - return - } - if let number = Double(trimmed) { - target[key] = number - } else { - target[key] = NSNull() - } - } - - private func setPatchInt( - _ target: inout [String: Any], - key: String, - value: String, - allowZero: Bool) - { - let trimmed = self.trimmed(value) - if trimmed.isEmpty { - target[key] = NSNull() - return - } - guard let number = Int(trimmed) else { - target[key] = NSNull() - return - } - let isValid = allowZero ? number >= 0 : number > 0 - guard isValid else { - target[key] = NSNull() - return - } - target[key] = number - } - - private func setPatchBool( - _ target: inout [String: Any], - key: String, - value: Bool, - defaultValue: Bool) - { - if value == defaultValue { - target[key] = NSNull() - } else { - target[key] = value - } - } - - private func setPatchList(_ target: inout [String: Any], key: String, values: [String]) { - if values.isEmpty { - target[key] = NSNull() - } else { - target[key] = values - } - } - - private func setAction( - _ actions: inout [String: Any], - key: String, - value: Bool, - defaultValue: Bool) - { - if value == defaultValue { - actions[key] = NSNull() - } else { - actions[key] = value - } - } -} diff --git a/apps/macos/Sources/Clawdbot/Constants.swift b/apps/macos/Sources/Clawdbot/Constants.swift index 25f2589e3..b55bd6d20 100644 --- a/apps/macos/Sources/Clawdbot/Constants.swift +++ b/apps/macos/Sources/Clawdbot/Constants.swift @@ -12,6 +12,8 @@ let voiceWakeTriggerChimeKey = "clawdbot.voiceWakeTriggerChime" let voiceWakeSendChimeKey = "clawdbot.voiceWakeSendChime" let showDockIconKey = "clawdbot.showDockIcon" let defaultVoiceWakeTriggers = ["clawd", "claude"] +let voiceWakeMaxWords = 32 +let voiceWakeMaxWordLength = 64 let voiceWakeMicKey = "clawdbot.voiceWakeMicID" let voiceWakeMicNameKey = "clawdbot.voiceWakeMicName" let voiceWakeLocaleKey = "clawdbot.voiceWakeLocaleID" diff --git a/apps/macos/Sources/Clawdbot/ControlChannel.swift b/apps/macos/Sources/Clawdbot/ControlChannel.swift index 78160a43a..4c47ee26e 100644 --- a/apps/macos/Sources/Clawdbot/ControlChannel.swift +++ b/apps/macos/Sources/Clawdbot/ControlChannel.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import ClawdbotProtocol import Foundation import Observation @@ -19,7 +20,7 @@ struct ControlAgentEvent: Codable, Sendable, Identifiable { let seq: Int let stream: String let ts: Double - let data: [String: AnyCodable] + let data: [String: ClawdbotProtocol.AnyCodable] let summary: String? } @@ -73,6 +74,7 @@ final class ControlChannel { } private(set) var lastPingMs: Double? + private(set) var authSourceLabel: String? private let logger = Logger(subsystem: "com.clawdbot", category: "control") @@ -86,15 +88,7 @@ final class ControlChannel { func configure() async { self.logger.info("control channel configure mode=local") - self.state = .connecting - do { - try await GatewayConnection.shared.refresh() - self.state = .connected - PresenceReporter.shared.sendImmediate(reason: "connect") - } catch { - let message = self.friendlyGatewayMessage(error) - self.state = .degraded(message) - } + await self.refreshEndpoint(reason: "configure") } func configure(mode: Mode = .local) async throws { @@ -110,7 +104,7 @@ final class ControlChannel { "target=\(target, privacy: .public) identitySet=\(idSet, privacy: .public)") self.state = .connecting _ = try await GatewayEndpointStore.shared.ensureRemoteControlTunnel() - await self.configure() + await self.refreshEndpoint(reason: "configure") } catch { self.state = .degraded(error.localizedDescription) throw error @@ -118,10 +112,24 @@ final class ControlChannel { } } + func refreshEndpoint(reason: String) async { + self.logger.info("control channel refresh endpoint reason=\(reason, privacy: .public)") + self.state = .connecting + do { + try await self.establishGatewayConnection() + self.state = .connected + PresenceReporter.shared.sendImmediate(reason: "connect") + } catch { + let message = self.friendlyGatewayMessage(error) + self.state = .degraded(message) + } + } + func disconnect() async { await GatewayConnection.shared.shutdown() self.state = .disconnected self.lastPingMs = nil + self.authSourceLabel = nil } func health(timeout: TimeInterval? = nil) async throws -> Data { @@ -155,8 +163,8 @@ final class ControlChannel { timeoutMs: Double? = nil) async throws -> Data { do { - let rawParams = params?.reduce(into: [String: AnyCodable]()) { - $0[$1.key] = AnyCodable($1.value.base) + let rawParams = params?.reduce(into: [String: ClawdbotKit.AnyCodable]()) { + $0[$1.key] = ClawdbotKit.AnyCodable($1.value.base) } let data = try await GatewayConnection.shared.request( method: method, @@ -182,8 +190,11 @@ final class ControlChannel { urlErr.code == .dataNotAllowed // used for WS close 1008 auth failures { let reason = urlErr.failureURLString ?? urlErr.localizedDescription + let tokenKey = CommandResolver.connectionModeIsRemote() + ? "gateway.remote.token" + : "gateway.auth.token" return - "Gateway rejected token; set gateway.auth.token (or CLAWDBOT_GATEWAY_TOKEN) " + + "Gateway rejected token; set \(tokenKey) (or CLAWDBOT_GATEWAY_TOKEN) " + "or clear it on the gateway. " + "Reason: \(reason)" } @@ -274,18 +285,49 @@ final class ControlChannel { } } - do { - try await GatewayConnection.shared.refresh() + await self.refreshEndpoint(reason: "recovery:\(reasonText)") + if case .connected = self.state { self.logger.info("control channel recovery finished") - } catch { - self.logger.error( - "control channel recovery failed \(error.localizedDescription, privacy: .public)") + } else if case let .degraded(message) = self.state { + self.logger.error("control channel recovery failed \(message, privacy: .public)") } self.recoveryTask = nil } } + private func establishGatewayConnection(timeoutMs: Int = 5000) async throws { + try await GatewayConnection.shared.refresh() + let ok = try await GatewayConnection.shared.healthOK(timeoutMs: timeoutMs) + if ok == false { + throw NSError( + domain: "Gateway", + code: 0, + userInfo: [NSLocalizedDescriptionKey: "gateway health not ok"]) + } + await self.refreshAuthSourceLabel() + } + + private func refreshAuthSourceLabel() async { + let isRemote = CommandResolver.connectionModeIsRemote() + let authSource = await GatewayConnection.shared.authSource() + self.authSourceLabel = Self.formatAuthSource(authSource, isRemote: isRemote) + } + + private static func formatAuthSource(_ source: GatewayAuthSource?, isRemote: Bool) -> String? { + guard let source else { return nil } + switch source { + case .deviceToken: + return "Auth: device token (paired device)" + case .sharedToken: + return "Auth: shared token (\(isRemote ? "gateway.remote.token" : "gateway.auth.token"))" + case .password: + return "Auth: password (\(isRemote ? "gateway.remote.password" : "gateway.auth.password"))" + case .none: + return "Auth: none" + } + } + func sendSystemEvent(_ text: String, params: [String: AnyHashable] = [:]) async throws { var merged = params merged["text"] = AnyHashable(text) @@ -345,7 +387,7 @@ final class ControlChannel { let phase = event.data["phase"]?.value as? String ?? "" let name = event.data["name"]?.value as? String let meta = event.data["meta"]?.value as? String - let args = event.data["args"]?.value as? [String: AnyCodable] + let args = Self.bridgeToProtocolArgs(event.data["args"]) WorkActivityStore.shared.handleTool( sessionKey: sessionKey, phase: phase, @@ -356,6 +398,27 @@ final class ControlChannel { break } } + + private static func bridgeToProtocolArgs( + _ value: ClawdbotProtocol.AnyCodable?) -> [String: ClawdbotProtocol.AnyCodable]? + { + guard let value else { return nil } + if let dict = value.value as? [String: ClawdbotProtocol.AnyCodable] { + return dict + } + if let dict = value.value as? [String: ClawdbotKit.AnyCodable], + let data = try? JSONEncoder().encode(dict), + let decoded = try? JSONDecoder().decode([String: ClawdbotProtocol.AnyCodable].self, from: data) + { + return decoded + } + if let data = try? JSONEncoder().encode(value), + let decoded = try? JSONDecoder().decode([String: ClawdbotProtocol.AnyCodable].self, from: data) + { + return decoded + } + return nil + } } extension Notification.Name { diff --git a/apps/macos/Sources/Clawdbot/CostUsageMenuView.swift b/apps/macos/Sources/Clawdbot/CostUsageMenuView.swift new file mode 100644 index 000000000..c94a4de35 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/CostUsageMenuView.swift @@ -0,0 +1,99 @@ +import Charts +import SwiftUI + +struct CostUsageHistoryMenuView: View { + let summary: GatewayCostUsageSummary + let width: CGFloat + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + self.header + self.chart + self.footer + } + .padding(.horizontal, 12) + .padding(.vertical, 10) + .frame(width: max(1, self.width), alignment: .leading) + } + + private var header: some View { + let todayKey = CostUsageMenuDateParser.format(Date()) + let todayEntry = self.summary.daily.first { $0.date == todayKey } + let todayCost = CostUsageFormatting.formatUsd(todayEntry?.totalCost) ?? "n/a" + let totalCost = CostUsageFormatting.formatUsd(self.summary.totals.totalCost) ?? "n/a" + + return HStack(alignment: .firstTextBaseline, spacing: 12) { + VStack(alignment: .leading, spacing: 2) { + Text("Today") + .font(.caption2) + .foregroundStyle(.secondary) + Text(todayCost) + .font(.system(size: 14, weight: .semibold)) + } + VStack(alignment: .leading, spacing: 2) { + Text("Last \(self.summary.days)d") + .font(.caption2) + .foregroundStyle(.secondary) + Text(totalCost) + .font(.system(size: 14, weight: .semibold)) + } + Spacer() + } + } + + private var chart: some View { + let entries = self.summary.daily.compactMap { entry -> (Date, Double)? in + guard let date = CostUsageMenuDateParser.parse(entry.date) else { return nil } + return (date, entry.totalCost) + } + + return Chart(entries, id: \.0) { entry in + BarMark( + x: .value("Day", entry.0), + y: .value("Cost", entry.1)) + .foregroundStyle(Color.accentColor) + .cornerRadius(3) + } + .chartXAxis { + AxisMarks(values: .stride(by: .day, count: 7)) { + AxisGridLine().foregroundStyle(.clear) + AxisValueLabel(format: .dateTime.month().day()) + } + } + .chartYAxis { + AxisMarks(position: .leading) { + AxisGridLine() + AxisValueLabel() + } + } + .frame(height: 110) + } + + private var footer: some View { + if self.summary.totals.missingCostEntries == 0 { + return AnyView(EmptyView()) + } + return AnyView( + Text("Partial: \(self.summary.totals.missingCostEntries) entries missing cost") + .font(.caption2) + .foregroundStyle(.secondary)) + } +} + +private enum CostUsageMenuDateParser { + static let formatter: DateFormatter = { + let formatter = DateFormatter() + formatter.dateFormat = "yyyy-MM-dd" + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone.current + return formatter + }() + + static func parse(_ value: String) -> Date? { + self.formatter.date(from: value) + } + + static func format(_ date: Date) -> String { + self.formatter.string(from: date) + } +} diff --git a/apps/macos/Sources/Clawdbot/CronJobEditor+Helpers.swift b/apps/macos/Sources/Clawdbot/CronJobEditor+Helpers.swift index 52a18df0d..4bac28c4f 100644 --- a/apps/macos/Sources/Clawdbot/CronJobEditor+Helpers.swift +++ b/apps/macos/Sources/Clawdbot/CronJobEditor+Helpers.swift @@ -42,7 +42,8 @@ extension CronJobEditor { self.thinking = thinking ?? "" self.timeoutSeconds = timeoutSeconds.map(String.init) ?? "" self.deliver = deliver ?? false - self.channel = GatewayAgentChannel(raw: channel) + let trimmed = (channel ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + self.channel = trimmed.isEmpty ? "last" : trimmed self.to = to ?? "" self.bestEffortDeliver = bestEffortDeliver ?? false } @@ -210,7 +211,8 @@ extension CronJobEditor { if let n = Int(self.timeoutSeconds), n > 0 { payload["timeoutSeconds"] = n } payload["deliver"] = self.deliver if self.deliver { - payload["channel"] = self.channel.rawValue + let trimmed = self.channel.trimmingCharacters(in: .whitespacesAndNewlines) + payload["channel"] = trimmed.isEmpty ? "last" : trimmed let to = self.to.trimmingCharacters(in: .whitespacesAndNewlines) if !to.isEmpty { payload["to"] = to } payload["bestEffortDeliver"] = self.bestEffortDeliver diff --git a/apps/macos/Sources/Clawdbot/CronJobEditor+Testing.swift b/apps/macos/Sources/Clawdbot/CronJobEditor+Testing.swift index 603180b45..0d4c46523 100644 --- a/apps/macos/Sources/Clawdbot/CronJobEditor+Testing.swift +++ b/apps/macos/Sources/Clawdbot/CronJobEditor+Testing.swift @@ -14,7 +14,7 @@ extension CronJobEditor { self.payloadKind = .agentTurn self.agentMessage = "Run diagnostic" self.deliver = true - self.channel = .last + self.channel = "last" self.to = "+15551230000" self.thinking = "low" self.timeoutSeconds = "90" diff --git a/apps/macos/Sources/Clawdbot/CronJobEditor.swift b/apps/macos/Sources/Clawdbot/CronJobEditor.swift index 05659d179..cec2b96a6 100644 --- a/apps/macos/Sources/Clawdbot/CronJobEditor.swift +++ b/apps/macos/Sources/Clawdbot/CronJobEditor.swift @@ -1,10 +1,12 @@ import ClawdbotProtocol +import Observation import SwiftUI struct CronJobEditor: View { let job: CronJob? @Binding var isSaving: Bool @Binding var error: String? + @Bindable var channelsStore: ChannelsStore let onCancel: () -> Void let onSave: ([String: AnyCodable]) -> Void @@ -45,13 +47,29 @@ struct CronJobEditor: View { @State var systemEventText: String = "" @State var agentMessage: String = "" @State var deliver: Bool = false - @State var channel: GatewayAgentChannel = .last + @State var channel: String = "last" @State var to: String = "" @State var thinking: String = "" @State var timeoutSeconds: String = "" @State var bestEffortDeliver: Bool = false @State var postPrefix: String = "Cron" + var channelOptions: [String] { + let ordered = self.channelsStore.orderedChannelIds() + var options = ["last"] + ordered + let trimmed = self.channel.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty, !options.contains(trimmed) { + options.append(trimmed) + } + var seen = Set() + return options.filter { seen.insert($0).inserted } + } + + func channelLabel(for id: String) -> String { + if id == "last" { return "last" } + return self.channelsStore.resolveChannelLabel(id) + } + var body: some View { VStack(alignment: .leading, spacing: 16) { VStack(alignment: .leading, spacing: 6) { @@ -333,13 +351,9 @@ struct CronJobEditor: View { GridRow { self.gridLabel("Channel") Picker("", selection: self.$channel) { - Text("last").tag(GatewayAgentChannel.last) - Text("whatsapp").tag(GatewayAgentChannel.whatsapp) - Text("telegram").tag(GatewayAgentChannel.telegram) - Text("discord").tag(GatewayAgentChannel.discord) - Text("slack").tag(GatewayAgentChannel.slack) - Text("signal").tag(GatewayAgentChannel.signal) - Text("imessage").tag(GatewayAgentChannel.imessage) + ForEach(self.channelOptions, id: \.self) { channel in + Text(self.channelLabel(for: channel)).tag(channel) + } } .labelsHidden() .pickerStyle(.segmented) diff --git a/apps/macos/Sources/Clawdbot/CronJobsStore.swift b/apps/macos/Sources/Clawdbot/CronJobsStore.swift index b3e363bf9..b44f9cb3a 100644 --- a/apps/macos/Sources/Clawdbot/CronJobsStore.swift +++ b/apps/macos/Sources/Clawdbot/CronJobsStore.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import ClawdbotProtocol import Foundation import Observation diff --git a/apps/macos/Sources/Clawdbot/CronSettings+Layout.swift b/apps/macos/Sources/Clawdbot/CronSettings+Layout.swift index f1891bd3e..11c7c0a0e 100644 --- a/apps/macos/Sources/Clawdbot/CronSettings+Layout.swift +++ b/apps/macos/Sources/Clawdbot/CronSettings+Layout.swift @@ -8,13 +8,20 @@ extension CronSettings { self.content Spacer(minLength: 0) } - .onAppear { self.store.start() } - .onDisappear { self.store.stop() } + .onAppear { + self.store.start() + self.channelsStore.start() + } + .onDisappear { + self.store.stop() + self.channelsStore.stop() + } .sheet(isPresented: self.$showEditor) { CronJobEditor( job: self.editingJob, isSaving: self.$isSaving, error: self.$editorError, + channelsStore: self.channelsStore, onCancel: { self.showEditor = false self.editingJob = nil diff --git a/apps/macos/Sources/Clawdbot/CronSettings+Testing.swift b/apps/macos/Sources/Clawdbot/CronSettings+Testing.swift index 9a767c374..976049f66 100644 --- a/apps/macos/Sources/Clawdbot/CronSettings+Testing.swift +++ b/apps/macos/Sources/Clawdbot/CronSettings+Testing.swift @@ -47,7 +47,7 @@ struct CronSettings_Previews: PreviewProvider { durationMs: 1234, nextRunAtMs: nil), ] - return CronSettings(store: store) + return CronSettings(store: store, channelsStore: ChannelsStore(isPreview: true)) .frame(width: SettingsTab.windowWidth, height: SettingsTab.windowHeight) } } @@ -103,7 +103,7 @@ extension CronSettings { store.selectedJobId = job.id store.runEntries = [run] - let view = CronSettings(store: store) + let view = CronSettings(store: store, channelsStore: ChannelsStore(isPreview: true)) _ = view.body _ = view.jobRow(job) _ = view.jobContextMenu(job) diff --git a/apps/macos/Sources/Clawdbot/CronSettings.swift b/apps/macos/Sources/Clawdbot/CronSettings.swift index d19a419b3..999712a59 100644 --- a/apps/macos/Sources/Clawdbot/CronSettings.swift +++ b/apps/macos/Sources/Clawdbot/CronSettings.swift @@ -3,13 +3,15 @@ import SwiftUI struct CronSettings: View { @Bindable var store: CronJobsStore + @Bindable var channelsStore: ChannelsStore @State var showEditor = false @State var editingJob: CronJob? @State var editorError: String? @State var isSaving = false @State var confirmDelete: CronJob? - init(store: CronJobsStore = .shared) { + init(store: CronJobsStore = .shared, channelsStore: ChannelsStore = .shared) { self.store = store + self.channelsStore = channelsStore } } diff --git a/apps/macos/Sources/Clawdbot/DebugActions.swift b/apps/macos/Sources/Clawdbot/DebugActions.swift index 1bfbeeb24..f0f84ed3c 100644 --- a/apps/macos/Sources/Clawdbot/DebugActions.swift +++ b/apps/macos/Sources/Clawdbot/DebugActions.swift @@ -26,7 +26,7 @@ enum DebugActions { static func openLog() { let path = self.pinoLogPath() let url = URL(fileURLWithPath: path) - guard FileManager.default.fileExists(atPath: path) else { + guard FileManager().fileExists(atPath: path) else { let alert = NSAlert() alert.messageText = "Log file not found" alert.informativeText = path @@ -38,7 +38,7 @@ enum DebugActions { @MainActor static func openConfigFolder() { - let url = FileManager.default + let url = FileManager() .homeDirectoryForCurrentUser .appendingPathComponent(".clawdbot", isDirectory: true) NSWorkspace.shared.activateFileViewerSelecting([url]) @@ -55,7 +55,7 @@ enum DebugActions { } let path = self.resolveSessionStorePath() let url = URL(fileURLWithPath: path) - if FileManager.default.fileExists(atPath: path) { + if FileManager().fileExists(atPath: path) { NSWorkspace.shared.activateFileViewerSelecting([url]) } else { NSWorkspace.shared.open(url.deletingLastPathComponent()) @@ -195,7 +195,7 @@ enum DebugActions { @MainActor private static func resolveSessionStorePath() -> String { let defaultPath = SessionLoader.defaultStorePath - let configURL = FileManager.default.homeDirectoryForCurrentUser + let configURL = FileManager().homeDirectoryForCurrentUser .appendingPathComponent(".clawdbot/clawdbot.json") guard let data = try? Data(contentsOf: configURL), diff --git a/apps/macos/Sources/Clawdbot/DebugSettings.swift b/apps/macos/Sources/Clawdbot/DebugSettings.swift index e5b9c4a4c..ec313b2a0 100644 --- a/apps/macos/Sources/Clawdbot/DebugSettings.swift +++ b/apps/macos/Sources/Clawdbot/DebugSettings.swift @@ -16,6 +16,8 @@ struct DebugSettings: View { @State private var modelsError: String? private let gatewayManager = GatewayProcessManager.shared private let healthStore = HealthStore.shared + @State private var launchAgentWriteDisabled = GatewayLaunchAgentManager.isLaunchAgentWriteDisabled() + @State private var launchAgentWriteError: String? @State private var gatewayRootInput: String = GatewayProcessManager.shared.projectRootPath() @State private var sessionStorePath: String = SessionLoader.defaultStorePath @State private var sessionStoreSaveError: String? @@ -47,6 +49,7 @@ struct DebugSettings: View { VStack(alignment: .leading, spacing: 14) { self.header + self.launchdSection self.appInfoSection self.gatewaySection self.logsSection @@ -79,6 +82,41 @@ struct DebugSettings: View { } } + private var launchdSection: some View { + GroupBox("Gateway startup") { + VStack(alignment: .leading, spacing: 8) { + Toggle("Attach only (skip launchd install)", isOn: self.$launchAgentWriteDisabled) + .onChange(of: self.launchAgentWriteDisabled) { _, newValue in + self.launchAgentWriteError = GatewayLaunchAgentManager.setLaunchAgentWriteDisabled(newValue) + if self.launchAgentWriteError != nil { + self.launchAgentWriteDisabled = GatewayLaunchAgentManager.isLaunchAgentWriteDisabled() + return + } + if newValue { + Task { + _ = await GatewayLaunchAgentManager.set( + enabled: false, + bundlePath: Bundle.main.bundlePath, + port: GatewayEnvironment.gatewayPort()) + } + } + } + + Text( + "When enabled, Clawdbot won't install or manage \(gatewayLaunchdLabel). " + + "It will only attach to an existing Gateway.") + .font(.caption) + .foregroundStyle(.secondary) + + if let launchAgentWriteError { + Text(launchAgentWriteError) + .font(.caption) + .foregroundStyle(.red) + } + } + } + } + private var header: some View { VStack(alignment: .leading, spacing: 6) { Text("Debug") @@ -354,7 +392,7 @@ struct DebugSettings: View { Button("Save") { self.saveRelayRoot() } .buttonStyle(.borderedProminent) Button("Reset") { - let def = FileManager.default.homeDirectoryForCurrentUser + let def = FileManager().homeDirectoryForCurrentUser .appendingPathComponent("Projects/clawdbot").path self.gatewayRootInput = def self.saveRelayRoot() @@ -484,6 +522,22 @@ struct DebugSettings: View { } } + VStack(alignment: .leading, spacing: 6) { + Text( + "Note: macOS may require restarting Clawdbot after enabling Accessibility or Screen Recording.") + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + + Button { + LaunchdManager.startClawdbot() + } label: { + Label("Restart Clawdbot", systemImage: "arrow.counterclockwise") + } + .buttonStyle(.bordered) + .controlSize(.small) + } + HStack(spacing: 8) { Button("Restart app") { DebugActions.restartApp() } Button("Restart onboarding") { DebugActions.restartOnboarding() } @@ -743,7 +797,7 @@ struct DebugSettings: View { do { let data = try JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys]) - try FileManager.default.createDirectory( + try FileManager().createDirectory( at: url.deletingLastPathComponent(), withIntermediateDirectories: true) try data.write(to: url, options: [.atomic]) @@ -776,7 +830,7 @@ struct DebugSettings: View { } private func configURL() -> URL { - FileManager.default.homeDirectoryForCurrentUser + FileManager().homeDirectoryForCurrentUser .appendingPathComponent(".clawdbot") .appendingPathComponent("clawdbot.json") } @@ -900,7 +954,7 @@ extension DebugSettings { } } -private struct PlainSettingsGroupBoxStyle: GroupBoxStyle { +struct PlainSettingsGroupBoxStyle: GroupBoxStyle { func makeBody(configuration: Configuration) -> some View { VStack(alignment: .leading, spacing: 10) { configuration.label diff --git a/apps/macos/Sources/Clawdbot/DevicePairingApprovalPrompter.swift b/apps/macos/Sources/Clawdbot/DevicePairingApprovalPrompter.swift new file mode 100644 index 000000000..81d87c7d3 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/DevicePairingApprovalPrompter.swift @@ -0,0 +1,334 @@ +import AppKit +import ClawdbotKit +import ClawdbotProtocol +import Foundation +import Observation +import OSLog + +@MainActor +@Observable +final class DevicePairingApprovalPrompter { + static let shared = DevicePairingApprovalPrompter() + + private let logger = Logger(subsystem: "com.clawdbot", category: "device-pairing") + private var task: Task? + private var isStopping = false + private var isPresenting = false + private var queue: [PendingRequest] = [] + var pendingCount: Int = 0 + var pendingRepairCount: Int = 0 + private var activeAlert: NSAlert? + private var activeRequestId: String? + private var alertHostWindow: NSWindow? + private var resolvedByRequestId: Set = [] + + private final class AlertHostWindow: NSWindow { + override var canBecomeKey: Bool { true } + override var canBecomeMain: Bool { true } + } + + private struct PairingList: Codable { + let pending: [PendingRequest] + let paired: [PairedDevice]? + } + + private struct PairedDevice: Codable, Equatable { + let deviceId: String + let approvedAtMs: Double? + let displayName: String? + let platform: String? + let remoteIp: String? + } + + private struct PendingRequest: Codable, Equatable, Identifiable { + let requestId: String + let deviceId: String + let publicKey: String + let displayName: String? + let platform: String? + let clientId: String? + let clientMode: String? + let role: String? + let scopes: [String]? + let remoteIp: String? + let silent: Bool? + let isRepair: Bool? + let ts: Double + + var id: String { self.requestId } + } + + private struct PairingResolvedEvent: Codable { + let requestId: String + let deviceId: String + let decision: String + let ts: Double + } + + private enum PairingResolution: String { + case approved + case rejected + } + + func start() { + guard self.task == nil else { return } + self.isStopping = false + self.task = Task { [weak self] in + guard let self else { return } + _ = try? await GatewayConnection.shared.refresh() + await self.loadPendingRequestsFromGateway() + let stream = await GatewayConnection.shared.subscribe(bufferingNewest: 200) + for await push in stream { + if Task.isCancelled { return } + await MainActor.run { [weak self] in self?.handle(push: push) } + } + } + } + + func stop() { + self.isStopping = true + self.endActiveAlert() + self.task?.cancel() + self.task = nil + self.queue.removeAll(keepingCapacity: false) + self.updatePendingCounts() + self.isPresenting = false + self.activeRequestId = nil + self.alertHostWindow?.orderOut(nil) + self.alertHostWindow?.close() + self.alertHostWindow = nil + self.resolvedByRequestId.removeAll(keepingCapacity: false) + } + + private func loadPendingRequestsFromGateway() async { + do { + let list: PairingList = try await GatewayConnection.shared.requestDecoded(method: .devicePairList) + await self.apply(list: list) + } catch { + self.logger.error("failed to load device pairing requests: \(error.localizedDescription, privacy: .public)") + } + } + + private func apply(list: PairingList) async { + self.queue = list.pending.sorted(by: { $0.ts > $1.ts }) + self.updatePendingCounts() + self.presentNextIfNeeded() + } + + private func updatePendingCounts() { + self.pendingCount = self.queue.count + self.pendingRepairCount = self.queue.count(where: { $0.isRepair == true }) + } + + private func presentNextIfNeeded() { + guard !self.isStopping else { return } + guard !self.isPresenting else { return } + guard let next = self.queue.first else { return } + self.isPresenting = true + self.presentAlert(for: next) + } + + private func presentAlert(for req: PendingRequest) { + self.logger.info("presenting device pairing alert requestId=\(req.requestId, privacy: .public)") + NSApp.activate(ignoringOtherApps: true) + + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = "Allow device to connect?" + alert.informativeText = Self.describe(req) + alert.addButton(withTitle: "Later") + alert.addButton(withTitle: "Approve") + alert.addButton(withTitle: "Reject") + if #available(macOS 11.0, *), alert.buttons.indices.contains(2) { + alert.buttons[2].hasDestructiveAction = true + } + + self.activeAlert = alert + self.activeRequestId = req.requestId + let hostWindow = self.requireAlertHostWindow() + + let sheetSize = alert.window.frame.size + if let screen = hostWindow.screen ?? NSScreen.main { + let bounds = screen.visibleFrame + let x = bounds.midX - (sheetSize.width / 2) + let sheetOriginY = bounds.midY - (sheetSize.height / 2) + let hostY = sheetOriginY + sheetSize.height - hostWindow.frame.height + hostWindow.setFrameOrigin(NSPoint(x: x, y: hostY)) + } else { + hostWindow.center() + } + + hostWindow.makeKeyAndOrderFront(nil) + alert.beginSheetModal(for: hostWindow) { [weak self] response in + Task { @MainActor [weak self] in + guard let self else { return } + self.activeRequestId = nil + self.activeAlert = nil + await self.handleAlertResponse(response, request: req) + hostWindow.orderOut(nil) + } + } + } + + private func handleAlertResponse(_ response: NSApplication.ModalResponse, request: PendingRequest) async { + var shouldRemove = response != .alertFirstButtonReturn + defer { + if shouldRemove { + if self.queue.first == request { + self.queue.removeFirst() + } else { + self.queue.removeAll { $0 == request } + } + } + self.updatePendingCounts() + self.isPresenting = false + self.presentNextIfNeeded() + } + + guard !self.isStopping else { return } + + if self.resolvedByRequestId.remove(request.requestId) != nil { + return + } + + switch response { + case .alertFirstButtonReturn: + shouldRemove = false + if let idx = self.queue.firstIndex(of: request) { + self.queue.remove(at: idx) + } + self.queue.append(request) + return + case .alertSecondButtonReturn: + _ = await self.approve(requestId: request.requestId) + case .alertThirdButtonReturn: + await self.reject(requestId: request.requestId) + default: + return + } + } + + private func approve(requestId: String) async -> Bool { + do { + try await GatewayConnection.shared.devicePairApprove(requestId: requestId) + self.logger.info("approved device pairing requestId=\(requestId, privacy: .public)") + return true + } catch { + self.logger.error("approve failed requestId=\(requestId, privacy: .public)") + self.logger.error("approve failed: \(error.localizedDescription, privacy: .public)") + return false + } + } + + private func reject(requestId: String) async { + do { + try await GatewayConnection.shared.devicePairReject(requestId: requestId) + self.logger.info("rejected device pairing requestId=\(requestId, privacy: .public)") + } catch { + self.logger.error("reject failed requestId=\(requestId, privacy: .public)") + self.logger.error("reject failed: \(error.localizedDescription, privacy: .public)") + } + } + + private func endActiveAlert() { + guard let alert = self.activeAlert else { return } + if let parent = alert.window.sheetParent { + parent.endSheet(alert.window, returnCode: .abort) + } + self.activeAlert = nil + self.activeRequestId = nil + } + + private func requireAlertHostWindow() -> NSWindow { + if let alertHostWindow { + return alertHostWindow + } + + let window = AlertHostWindow( + contentRect: NSRect(x: 0, y: 0, width: 520, height: 1), + styleMask: [.borderless], + backing: .buffered, + defer: false) + window.title = "" + window.isReleasedWhenClosed = false + window.level = .floating + window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary] + window.isOpaque = false + window.hasShadow = false + window.backgroundColor = .clear + window.ignoresMouseEvents = true + + self.alertHostWindow = window + return window + } + + private func handle(push: GatewayPush) { + switch push { + case let .event(evt) where evt.event == "device.pair.requested": + guard let payload = evt.payload else { return } + do { + let req = try GatewayPayloadDecoding.decode(payload, as: PendingRequest.self) + self.enqueue(req) + } catch { + self.logger + .error("failed to decode device pairing request: \(error.localizedDescription, privacy: .public)") + } + case let .event(evt) where evt.event == "device.pair.resolved": + guard let payload = evt.payload else { return } + do { + let resolved = try GatewayPayloadDecoding.decode(payload, as: PairingResolvedEvent.self) + self.handleResolved(resolved) + } catch { + self.logger + .error( + "failed to decode device pairing resolution: \(error.localizedDescription, privacy: .public)") + } + default: + break + } + } + + private func enqueue(_ req: PendingRequest) { + guard !self.queue.contains(req) else { return } + self.queue.append(req) + self.updatePendingCounts() + self.presentNextIfNeeded() + } + + private func handleResolved(_ resolved: PairingResolvedEvent) { + let resolution = resolved.decision == PairingResolution.approved.rawValue ? PairingResolution + .approved : .rejected + if let activeRequestId, activeRequestId == resolved.requestId { + self.resolvedByRequestId.insert(resolved.requestId) + self.endActiveAlert() + let decision = resolution.rawValue + self.logger.info( + "device pairing resolved while active requestId=\(resolved.requestId, privacy: .public) " + + "decision=\(decision, privacy: .public)") + return + } + self.queue.removeAll { $0.requestId == resolved.requestId } + self.updatePendingCounts() + } + + private static func describe(_ req: PendingRequest) -> String { + var lines: [String] = [] + lines.append("Device: \(req.displayName ?? req.deviceId)") + if let platform = req.platform { + lines.append("Platform: \(platform)") + } + if let role = req.role { + lines.append("Role: \(role)") + } + if let scopes = req.scopes, !scopes.isEmpty { + lines.append("Scopes: \(scopes.joined(separator: ", "))") + } + if let remoteIp = req.remoteIp { + lines.append("IP: \(remoteIp)") + } + if req.isRepair == true { + lines.append("Repair: yes") + } + return lines.joined(separator: "\n") + } +} diff --git a/apps/macos/Sources/Clawdbot/DiagnosticsFileLog.swift b/apps/macos/Sources/Clawdbot/DiagnosticsFileLog.swift index f62dd2c07..d42b76081 100644 --- a/apps/macos/Sources/Clawdbot/DiagnosticsFileLog.swift +++ b/apps/macos/Sources/Clawdbot/DiagnosticsFileLog.swift @@ -20,8 +20,8 @@ actor DiagnosticsFileLog { } nonisolated static func logDirectoryURL() -> URL { - let library = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first - ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library", isDirectory: true) + let library = FileManager().urls(for: .libraryDirectory, in: .userDomainMask).first + ?? FileManager().homeDirectoryForCurrentUser.appendingPathComponent("Library", isDirectory: true) return library .appendingPathComponent("Logs", isDirectory: true) .appendingPathComponent("Clawdbot", isDirectory: true) @@ -43,7 +43,7 @@ actor DiagnosticsFileLog { } func clear() throws { - let fm = FileManager.default + let fm = FileManager() let base = Self.logFileURL() if fm.fileExists(atPath: base.path) { try fm.removeItem(at: base) @@ -67,7 +67,7 @@ actor DiagnosticsFileLog { } private func ensureDirectory() throws { - try FileManager.default.createDirectory( + try FileManager().createDirectory( at: Self.logDirectoryURL(), withIntermediateDirectories: true) } @@ -79,7 +79,7 @@ actor DiagnosticsFileLog { line.append(data) line.append(0x0A) // newline - let fm = FileManager.default + let fm = FileManager() if !fm.fileExists(atPath: url.path) { fm.createFile(atPath: url.path, contents: nil) } @@ -92,13 +92,13 @@ actor DiagnosticsFileLog { private func rotateIfNeeded() throws { let url = Self.logFileURL() - guard let attrs = try? FileManager.default.attributesOfItem(atPath: url.path), + guard let attrs = try? FileManager().attributesOfItem(atPath: url.path), let size = attrs[.size] as? NSNumber else { return } if size.int64Value < self.maxBytes { return } - let fm = FileManager.default + let fm = FileManager() let oldest = self.rotatedURL(index: self.maxBackups) if fm.fileExists(atPath: oldest.path) { diff --git a/apps/macos/Sources/Clawdbot/ExecApprovals.swift b/apps/macos/Sources/Clawdbot/ExecApprovals.swift new file mode 100644 index 000000000..c6f413922 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/ExecApprovals.swift @@ -0,0 +1,790 @@ +import CryptoKit +import Foundation +import OSLog +import Security + +enum ExecSecurity: String, CaseIterable, Codable, Identifiable { + case deny + case allowlist + case full + + var id: String { self.rawValue } + + var title: String { + switch self { + case .deny: "Deny" + case .allowlist: "Allowlist" + case .full: "Always Allow" + } + } +} + +enum ExecApprovalQuickMode: String, CaseIterable, Identifiable { + case deny + case ask + case allow + + var id: String { self.rawValue } + + var title: String { + switch self { + case .deny: "Deny" + case .ask: "Always Ask" + case .allow: "Always Allow" + } + } + + var security: ExecSecurity { + switch self { + case .deny: .deny + case .ask: .allowlist + case .allow: .full + } + } + + var ask: ExecAsk { + switch self { + case .deny: .off + case .ask: .onMiss + case .allow: .off + } + } + + static func from(security: ExecSecurity, ask: ExecAsk) -> ExecApprovalQuickMode { + switch security { + case .deny: + .deny + case .full: + .allow + case .allowlist: + .ask + } + } +} + +enum ExecAsk: String, CaseIterable, Codable, Identifiable { + case off + case onMiss = "on-miss" + case always + + var id: String { self.rawValue } + + var title: String { + switch self { + case .off: "Never Ask" + case .onMiss: "Ask on Allowlist Miss" + case .always: "Always Ask" + } + } +} + +enum ExecApprovalDecision: String, Codable, Sendable { + case allowOnce = "allow-once" + case allowAlways = "allow-always" + case deny +} + +struct ExecAllowlistEntry: Codable, Hashable, Identifiable { + var id: UUID + var pattern: String + var lastUsedAt: Double? + var lastUsedCommand: String? + var lastResolvedPath: String? + + init( + id: UUID = UUID(), + pattern: String, + lastUsedAt: Double? = nil, + lastUsedCommand: String? = nil, + lastResolvedPath: String? = nil) + { + self.id = id + self.pattern = pattern + self.lastUsedAt = lastUsedAt + self.lastUsedCommand = lastUsedCommand + self.lastResolvedPath = lastResolvedPath + } + + private enum CodingKeys: String, CodingKey { + case id + case pattern + case lastUsedAt + case lastUsedCommand + case lastResolvedPath + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() + self.pattern = try container.decode(String.self, forKey: .pattern) + self.lastUsedAt = try container.decodeIfPresent(Double.self, forKey: .lastUsedAt) + self.lastUsedCommand = try container.decodeIfPresent(String.self, forKey: .lastUsedCommand) + self.lastResolvedPath = try container.decodeIfPresent(String.self, forKey: .lastResolvedPath) + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(self.id, forKey: .id) + try container.encode(self.pattern, forKey: .pattern) + try container.encodeIfPresent(self.lastUsedAt, forKey: .lastUsedAt) + try container.encodeIfPresent(self.lastUsedCommand, forKey: .lastUsedCommand) + try container.encodeIfPresent(self.lastResolvedPath, forKey: .lastResolvedPath) + } +} + +struct ExecApprovalsDefaults: Codable { + var security: ExecSecurity? + var ask: ExecAsk? + var askFallback: ExecSecurity? + var autoAllowSkills: Bool? +} + +struct ExecApprovalsAgent: Codable { + var security: ExecSecurity? + var ask: ExecAsk? + var askFallback: ExecSecurity? + var autoAllowSkills: Bool? + var allowlist: [ExecAllowlistEntry]? + + var isEmpty: Bool { + self.security == nil && self.ask == nil && self.askFallback == nil && self + .autoAllowSkills == nil && (self.allowlist?.isEmpty ?? true) + } +} + +struct ExecApprovalsSocketConfig: Codable { + var path: String? + var token: String? +} + +struct ExecApprovalsFile: Codable { + var version: Int + var socket: ExecApprovalsSocketConfig? + var defaults: ExecApprovalsDefaults? + var agents: [String: ExecApprovalsAgent]? +} + +struct ExecApprovalsSnapshot: Codable { + var path: String + var exists: Bool + var hash: String + var file: ExecApprovalsFile +} + +struct ExecApprovalsResolved { + let url: URL + let socketPath: String + let token: String + let defaults: ExecApprovalsResolvedDefaults + let agent: ExecApprovalsResolvedDefaults + let allowlist: [ExecAllowlistEntry] + var file: ExecApprovalsFile +} + +struct ExecApprovalsResolvedDefaults { + var security: ExecSecurity + var ask: ExecAsk + var askFallback: ExecSecurity + var autoAllowSkills: Bool +} + +enum ExecApprovalsStore { + private static let logger = Logger(subsystem: "com.clawdbot", category: "exec-approvals") + private static let defaultAgentId = "main" + private static let defaultSecurity: ExecSecurity = .deny + private static let defaultAsk: ExecAsk = .onMiss + private static let defaultAskFallback: ExecSecurity = .deny + private static let defaultAutoAllowSkills = false + + static func fileURL() -> URL { + ClawdbotPaths.stateDirURL.appendingPathComponent("exec-approvals.json") + } + + static func socketPath() -> String { + ClawdbotPaths.stateDirURL.appendingPathComponent("exec-approvals.sock").path + } + + static func normalizeIncoming(_ file: ExecApprovalsFile) -> ExecApprovalsFile { + let socketPath = file.socket?.path?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let token = file.socket?.token?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + var agents = file.agents ?? [:] + if let legacyDefault = agents["default"] { + if let main = agents[self.defaultAgentId] { + agents[self.defaultAgentId] = self.mergeAgents(current: main, legacy: legacyDefault) + } else { + agents[self.defaultAgentId] = legacyDefault + } + agents.removeValue(forKey: "default") + } + return ExecApprovalsFile( + version: 1, + socket: ExecApprovalsSocketConfig( + path: socketPath.isEmpty ? nil : socketPath, + token: token.isEmpty ? nil : token), + defaults: file.defaults, + agents: agents) + } + + static func readSnapshot() -> ExecApprovalsSnapshot { + let url = self.fileURL() + guard FileManager().fileExists(atPath: url.path) else { + return ExecApprovalsSnapshot( + path: url.path, + exists: false, + hash: self.hashRaw(nil), + file: ExecApprovalsFile(version: 1, socket: nil, defaults: nil, agents: [:])) + } + let raw = try? String(contentsOf: url, encoding: .utf8) + let data = raw.flatMap { $0.data(using: .utf8) } + let decoded: ExecApprovalsFile = { + if let data, let file = try? JSONDecoder().decode(ExecApprovalsFile.self, from: data), file.version == 1 { + return file + } + return ExecApprovalsFile(version: 1, socket: nil, defaults: nil, agents: [:]) + }() + return ExecApprovalsSnapshot( + path: url.path, + exists: true, + hash: self.hashRaw(raw), + file: decoded) + } + + static func redactForSnapshot(_ file: ExecApprovalsFile) -> ExecApprovalsFile { + let socketPath = file.socket?.path?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if socketPath.isEmpty { + return ExecApprovalsFile( + version: file.version, + socket: nil, + defaults: file.defaults, + agents: file.agents) + } + return ExecApprovalsFile( + version: file.version, + socket: ExecApprovalsSocketConfig(path: socketPath, token: nil), + defaults: file.defaults, + agents: file.agents) + } + + static func loadFile() -> ExecApprovalsFile { + let url = self.fileURL() + guard FileManager().fileExists(atPath: url.path) else { + return ExecApprovalsFile(version: 1, socket: nil, defaults: nil, agents: [:]) + } + do { + let data = try Data(contentsOf: url) + let decoded = try JSONDecoder().decode(ExecApprovalsFile.self, from: data) + if decoded.version != 1 { + return ExecApprovalsFile(version: 1, socket: nil, defaults: nil, agents: [:]) + } + return decoded + } catch { + self.logger.warning("exec approvals load failed: \(error.localizedDescription, privacy: .public)") + return ExecApprovalsFile(version: 1, socket: nil, defaults: nil, agents: [:]) + } + } + + static func saveFile(_ file: ExecApprovalsFile) { + do { + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let data = try encoder.encode(file) + let url = self.fileURL() + try FileManager().createDirectory( + at: url.deletingLastPathComponent(), + withIntermediateDirectories: true) + try data.write(to: url, options: [.atomic]) + try? FileManager().setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) + } catch { + self.logger.error("exec approvals save failed: \(error.localizedDescription, privacy: .public)") + } + } + + static func ensureFile() -> ExecApprovalsFile { + var file = self.loadFile() + if file.socket == nil { file.socket = ExecApprovalsSocketConfig(path: nil, token: nil) } + let path = file.socket?.path?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if path.isEmpty { + file.socket?.path = self.socketPath() + } + let token = file.socket?.token?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if token.isEmpty { + file.socket?.token = self.generateToken() + } + if file.agents == nil { file.agents = [:] } + self.saveFile(file) + return file + } + + static func resolve(agentId: String?) -> ExecApprovalsResolved { + let file = self.ensureFile() + let defaults = file.defaults ?? ExecApprovalsDefaults() + let resolvedDefaults = ExecApprovalsResolvedDefaults( + security: defaults.security ?? self.defaultSecurity, + ask: defaults.ask ?? self.defaultAsk, + askFallback: defaults.askFallback ?? self.defaultAskFallback, + autoAllowSkills: defaults.autoAllowSkills ?? self.defaultAutoAllowSkills) + let key = self.agentKey(agentId) + let agentEntry = file.agents?[key] ?? ExecApprovalsAgent() + let wildcardEntry = file.agents?["*"] ?? ExecApprovalsAgent() + let resolvedAgent = ExecApprovalsResolvedDefaults( + security: agentEntry.security ?? wildcardEntry.security ?? resolvedDefaults.security, + ask: agentEntry.ask ?? wildcardEntry.ask ?? resolvedDefaults.ask, + askFallback: agentEntry.askFallback ?? wildcardEntry.askFallback + ?? resolvedDefaults.askFallback, + autoAllowSkills: agentEntry.autoAllowSkills ?? wildcardEntry.autoAllowSkills + ?? resolvedDefaults.autoAllowSkills) + let allowlist = ((wildcardEntry.allowlist ?? []) + (agentEntry.allowlist ?? [])) + .map { entry in + ExecAllowlistEntry( + id: entry.id, + pattern: entry.pattern.trimmingCharacters(in: .whitespacesAndNewlines), + lastUsedAt: entry.lastUsedAt, + lastUsedCommand: entry.lastUsedCommand, + lastResolvedPath: entry.lastResolvedPath) + } + .filter { !$0.pattern.isEmpty } + let socketPath = self.expandPath(file.socket?.path ?? self.socketPath()) + let token = file.socket?.token ?? "" + return ExecApprovalsResolved( + url: self.fileURL(), + socketPath: socketPath, + token: token, + defaults: resolvedDefaults, + agent: resolvedAgent, + allowlist: allowlist, + file: file) + } + + static func resolveDefaults() -> ExecApprovalsResolvedDefaults { + let file = self.ensureFile() + let defaults = file.defaults ?? ExecApprovalsDefaults() + return ExecApprovalsResolvedDefaults( + security: defaults.security ?? self.defaultSecurity, + ask: defaults.ask ?? self.defaultAsk, + askFallback: defaults.askFallback ?? self.defaultAskFallback, + autoAllowSkills: defaults.autoAllowSkills ?? self.defaultAutoAllowSkills) + } + + static func saveDefaults(_ defaults: ExecApprovalsDefaults) { + self.updateFile { file in + file.defaults = defaults + } + } + + static func updateDefaults(_ mutate: (inout ExecApprovalsDefaults) -> Void) { + self.updateFile { file in + var defaults = file.defaults ?? ExecApprovalsDefaults() + mutate(&defaults) + file.defaults = defaults + } + } + + static func saveAgent(_ agent: ExecApprovalsAgent, agentId: String?) { + self.updateFile { file in + var agents = file.agents ?? [:] + let key = self.agentKey(agentId) + if agent.isEmpty { + agents.removeValue(forKey: key) + } else { + agents[key] = agent + } + file.agents = agents.isEmpty ? nil : agents + } + } + + static func addAllowlistEntry(agentId: String?, pattern: String) { + let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + self.updateFile { file in + let key = self.agentKey(agentId) + var agents = file.agents ?? [:] + var entry = agents[key] ?? ExecApprovalsAgent() + var allowlist = entry.allowlist ?? [] + if allowlist.contains(where: { $0.pattern == trimmed }) { return } + allowlist.append(ExecAllowlistEntry(pattern: trimmed, lastUsedAt: Date().timeIntervalSince1970 * 1000)) + entry.allowlist = allowlist + agents[key] = entry + file.agents = agents + } + } + + static func recordAllowlistUse( + agentId: String?, + pattern: String, + command: String, + resolvedPath: String?) + { + self.updateFile { file in + let key = self.agentKey(agentId) + var agents = file.agents ?? [:] + var entry = agents[key] ?? ExecApprovalsAgent() + let allowlist = (entry.allowlist ?? []).map { item -> ExecAllowlistEntry in + guard item.pattern == pattern else { return item } + return ExecAllowlistEntry( + id: item.id, + pattern: item.pattern, + lastUsedAt: Date().timeIntervalSince1970 * 1000, + lastUsedCommand: command, + lastResolvedPath: resolvedPath) + } + entry.allowlist = allowlist + agents[key] = entry + file.agents = agents + } + } + + static func updateAllowlist(agentId: String?, allowlist: [ExecAllowlistEntry]) { + self.updateFile { file in + let key = self.agentKey(agentId) + var agents = file.agents ?? [:] + var entry = agents[key] ?? ExecApprovalsAgent() + let cleaned = allowlist + .map { item in + ExecAllowlistEntry( + id: item.id, + pattern: item.pattern.trimmingCharacters(in: .whitespacesAndNewlines), + lastUsedAt: item.lastUsedAt, + lastUsedCommand: item.lastUsedCommand, + lastResolvedPath: item.lastResolvedPath) + } + .filter { !$0.pattern.isEmpty } + entry.allowlist = cleaned + agents[key] = entry + file.agents = agents + } + } + + static func updateAgentSettings(agentId: String?, mutate: (inout ExecApprovalsAgent) -> Void) { + self.updateFile { file in + let key = self.agentKey(agentId) + var agents = file.agents ?? [:] + var entry = agents[key] ?? ExecApprovalsAgent() + mutate(&entry) + if entry.isEmpty { + agents.removeValue(forKey: key) + } else { + agents[key] = entry + } + file.agents = agents.isEmpty ? nil : agents + } + } + + private static func updateFile(_ mutate: (inout ExecApprovalsFile) -> Void) { + var file = self.ensureFile() + mutate(&file) + self.saveFile(file) + } + + private static func generateToken() -> String { + var bytes = [UInt8](repeating: 0, count: 24) + let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) + if status == errSecSuccess { + return Data(bytes) + .base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + } + return UUID().uuidString + } + + private static func hashRaw(_ raw: String?) -> String { + let data = Data((raw ?? "").utf8) + let digest = SHA256.hash(data: data) + return digest.map { String(format: "%02x", $0) }.joined() + } + + private static func expandPath(_ raw: String) -> String { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed == "~" { + return FileManager().homeDirectoryForCurrentUser.path + } + if trimmed.hasPrefix("~/") { + let suffix = trimmed.dropFirst(2) + return FileManager().homeDirectoryForCurrentUser + .appendingPathComponent(String(suffix)).path + } + return trimmed + } + + private static func agentKey(_ agentId: String?) -> String { + let trimmed = agentId?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? self.defaultAgentId : trimmed + } + + private static func normalizedPattern(_ pattern: String?) -> String? { + let trimmed = pattern?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? nil : trimmed.lowercased() + } + + private static func mergeAgents( + current: ExecApprovalsAgent, + legacy: ExecApprovalsAgent) -> ExecApprovalsAgent + { + var seen = Set() + var allowlist: [ExecAllowlistEntry] = [] + func append(_ entry: ExecAllowlistEntry) { + guard let key = self.normalizedPattern(entry.pattern), !seen.contains(key) else { + return + } + seen.insert(key) + allowlist.append(entry) + } + for entry in current.allowlist ?? [] { + append(entry) + } + for entry in legacy.allowlist ?? [] { + append(entry) + } + + return ExecApprovalsAgent( + security: current.security ?? legacy.security, + ask: current.ask ?? legacy.ask, + askFallback: current.askFallback ?? legacy.askFallback, + autoAllowSkills: current.autoAllowSkills ?? legacy.autoAllowSkills, + allowlist: allowlist.isEmpty ? nil : allowlist) + } +} + +struct ExecCommandResolution: Sendable { + let rawExecutable: String + let resolvedPath: String? + let executableName: String + let cwd: String? + + static func resolve( + command: [String], + rawCommand: String?, + cwd: String?, + env: [String: String]?) -> ExecCommandResolution? + { + let trimmedRaw = rawCommand?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !trimmedRaw.isEmpty, let token = self.parseFirstToken(trimmedRaw) { + return self.resolveExecutable(rawExecutable: token, cwd: cwd, env: env) + } + return self.resolve(command: command, cwd: cwd, env: env) + } + + static func resolve(command: [String], cwd: String?, env: [String: String]?) -> ExecCommandResolution? { + guard let raw = command.first?.trimmingCharacters(in: .whitespacesAndNewlines), !raw.isEmpty else { + return nil + } + return self.resolveExecutable(rawExecutable: raw, cwd: cwd, env: env) + } + + private static func resolveExecutable( + rawExecutable: String, + cwd: String?, + env: [String: String]?) -> ExecCommandResolution? + { + let expanded = rawExecutable.hasPrefix("~") ? (rawExecutable as NSString).expandingTildeInPath : rawExecutable + let hasPathSeparator = expanded.contains("/") || expanded.contains("\\") + let resolvedPath: String? = { + if hasPathSeparator { + if expanded.hasPrefix("/") { + return expanded + } + let base = cwd?.trimmingCharacters(in: .whitespacesAndNewlines) + let root = (base?.isEmpty == false) ? base! : FileManager().currentDirectoryPath + return URL(fileURLWithPath: root).appendingPathComponent(expanded).path + } + let searchPaths = self.searchPaths(from: env) + return CommandResolver.findExecutable(named: expanded, searchPaths: searchPaths) + }() + let name = resolvedPath.map { URL(fileURLWithPath: $0).lastPathComponent } ?? expanded + return ExecCommandResolution( + rawExecutable: expanded, + resolvedPath: resolvedPath, + executableName: name, + cwd: cwd) + } + + private static func parseFirstToken(_ command: String) -> String? { + let trimmed = command.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return nil } + guard let first = trimmed.first else { return nil } + if first == "\"" || first == "'" { + let rest = trimmed.dropFirst() + if let end = rest.firstIndex(of: first) { + return String(rest[.. [String] { + let raw = env?["PATH"] + if let raw, !raw.isEmpty { + return raw.split(separator: ":").map(String.init) + } + return CommandResolver.preferredPaths() + } +} + +enum ExecCommandFormatter { + static func displayString(for argv: [String]) -> String { + argv.map { arg in + let trimmed = arg.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return "\"\"" } + let needsQuotes = trimmed.contains { $0.isWhitespace || $0 == "\"" } + if !needsQuotes { return trimmed } + let escaped = trimmed.replacingOccurrences(of: "\"", with: "\\\"") + return "\"\(escaped)\"" + }.joined(separator: " ") + } + + static func displayString(for argv: [String], rawCommand: String?) -> String { + let trimmed = rawCommand?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !trimmed.isEmpty { return trimmed } + return self.displayString(for: argv) + } +} + +enum ExecApprovalHelpers { + static func parseDecision(_ raw: String?) -> ExecApprovalDecision? { + let trimmed = raw?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard !trimmed.isEmpty else { return nil } + return ExecApprovalDecision(rawValue: trimmed) + } + + static func requiresAsk( + ask: ExecAsk, + security: ExecSecurity, + allowlistMatch: ExecAllowlistEntry?, + skillAllow: Bool) -> Bool + { + if ask == .always { return true } + if ask == .onMiss, security == .allowlist, allowlistMatch == nil, !skillAllow { return true } + return false + } + + static func allowlistPattern(command: [String], resolution: ExecCommandResolution?) -> String? { + let pattern = resolution?.resolvedPath ?? resolution?.rawExecutable ?? command.first ?? "" + return pattern.isEmpty ? nil : pattern + } +} + +enum ExecAllowlistMatcher { + static func match(entries: [ExecAllowlistEntry], resolution: ExecCommandResolution?) -> ExecAllowlistEntry? { + guard let resolution, !entries.isEmpty else { return nil } + let rawExecutable = resolution.rawExecutable + let resolvedPath = resolution.resolvedPath + let executableName = resolution.executableName + + for entry in entries { + let pattern = entry.pattern.trimmingCharacters(in: .whitespacesAndNewlines) + if pattern.isEmpty { continue } + let hasPath = pattern.contains("/") || pattern.contains("~") || pattern.contains("\\") + if hasPath { + let target = resolvedPath ?? rawExecutable + if self.matches(pattern: pattern, target: target) { return entry } + } else if self.matches(pattern: pattern, target: executableName) { + return entry + } + } + return nil + } + + private static func matches(pattern: String, target: String) -> Bool { + let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return false } + let expanded = trimmed.hasPrefix("~") ? (trimmed as NSString).expandingTildeInPath : trimmed + let normalizedPattern = self.normalizeMatchTarget(expanded) + let normalizedTarget = self.normalizeMatchTarget(target) + guard let regex = self.regex(for: normalizedPattern) else { return false } + let range = NSRange(location: 0, length: normalizedTarget.utf16.count) + return regex.firstMatch(in: normalizedTarget, options: [], range: range) != nil + } + + private static func normalizeMatchTarget(_ value: String) -> String { + value.replacingOccurrences(of: "\\\\", with: "/").lowercased() + } + + private static func regex(for pattern: String) -> NSRegularExpression? { + var regex = "^" + var idx = pattern.startIndex + while idx < pattern.endIndex { + let ch = pattern[idx] + if ch == "*" { + let next = pattern.index(after: idx) + if next < pattern.endIndex, pattern[next] == "*" { + regex += ".*" + idx = pattern.index(after: next) + } else { + regex += "[^/]*" + idx = next + } + continue + } + if ch == "?" { + regex += "." + idx = pattern.index(after: idx) + continue + } + regex += NSRegularExpression.escapedPattern(for: String(ch)) + idx = pattern.index(after: idx) + } + regex += "$" + return try? NSRegularExpression(pattern: regex, options: [.caseInsensitive]) + } +} + +struct ExecEventPayload: Codable, Sendable { + var sessionKey: String + var runId: String + var host: String + var command: String? + var exitCode: Int? + var timedOut: Bool? + var success: Bool? + var output: String? + var reason: String? + + static func truncateOutput(_ raw: String, maxChars: Int = 20000) -> String? { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return nil } + if trimmed.count <= maxChars { return trimmed } + let suffix = trimmed.suffix(maxChars) + return "... (truncated) \(suffix)" + } +} + +actor SkillBinsCache { + static let shared = SkillBinsCache() + + private var bins: Set = [] + private var lastRefresh: Date? + private let refreshInterval: TimeInterval = 90 + + func currentBins(force: Bool = false) async -> Set { + if force || self.isStale() { + await self.refresh() + } + return self.bins + } + + func refresh() async { + do { + let report = try await GatewayConnection.shared.skillsStatus() + var next = Set() + for skill in report.skills { + for bin in skill.requirements.bins { + let trimmed = bin.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { next.insert(trimmed) } + } + } + self.bins = next + self.lastRefresh = Date() + } catch { + if self.lastRefresh == nil { + self.bins = [] + } + } + } + + private func isStale() -> Bool { + guard let lastRefresh else { return true } + return Date().timeIntervalSince(lastRefresh) > self.refreshInterval + } +} diff --git a/apps/macos/Sources/Clawdbot/ExecApprovalsGatewayPrompter.swift b/apps/macos/Sources/Clawdbot/ExecApprovalsGatewayPrompter.swift new file mode 100644 index 000000000..dbe80ecfe --- /dev/null +++ b/apps/macos/Sources/Clawdbot/ExecApprovalsGatewayPrompter.swift @@ -0,0 +1,123 @@ +import ClawdbotKit +import ClawdbotProtocol +import CoreGraphics +import Foundation +import OSLog + +@MainActor +final class ExecApprovalsGatewayPrompter { + static let shared = ExecApprovalsGatewayPrompter() + + private let logger = Logger(subsystem: "com.clawdbot", category: "exec-approvals.gateway") + private var task: Task? + + struct GatewayApprovalRequest: Codable, Sendable { + var id: String + var request: ExecApprovalPromptRequest + var createdAtMs: Int + var expiresAtMs: Int + } + + func start() { + guard self.task == nil else { return } + self.task = Task { [weak self] in + await self?.run() + } + } + + func stop() { + self.task?.cancel() + self.task = nil + } + + private func run() async { + let stream = await GatewayConnection.shared.subscribe(bufferingNewest: 200) + for await push in stream { + if Task.isCancelled { return } + await self.handle(push: push) + } + } + + private func handle(push: GatewayPush) async { + guard case let .event(evt) = push else { return } + guard evt.event == "exec.approval.requested" else { return } + guard let payload = evt.payload else { return } + do { + let data = try JSONEncoder().encode(payload) + let request = try JSONDecoder().decode(GatewayApprovalRequest.self, from: data) + guard self.shouldPresent(request: request) else { return } + let decision = ExecApprovalsPromptPresenter.prompt(request.request) + try await GatewayConnection.shared.requestVoid( + method: .execApprovalResolve, + params: [ + "id": AnyCodable(request.id), + "decision": AnyCodable(decision.rawValue), + ], + timeoutMs: 10000) + } catch { + self.logger.error("exec approval handling failed \(error.localizedDescription, privacy: .public)") + } + } + + private func shouldPresent(request: GatewayApprovalRequest) -> Bool { + let mode = AppStateStore.shared.connectionMode + let activeSession = WebChatManager.shared.activeSessionKey?.trimmingCharacters(in: .whitespacesAndNewlines) + let requestSession = request.request.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines) + return Self.shouldPresent( + mode: mode, + activeSession: activeSession, + requestSession: requestSession, + lastInputSeconds: Self.lastInputSeconds(), + thresholdSeconds: 120) + } + + private static func shouldPresent( + mode: AppState.ConnectionMode, + activeSession: String?, + requestSession: String?, + lastInputSeconds: Int?, + thresholdSeconds: Int) -> Bool + { + let active = activeSession?.trimmingCharacters(in: .whitespacesAndNewlines) + let requested = requestSession?.trimmingCharacters(in: .whitespacesAndNewlines) + let recentlyActive = lastInputSeconds.map { $0 <= thresholdSeconds } ?? (mode == .local) + + if let session = requested, !session.isEmpty { + if let active, !active.isEmpty { + return active == session + } + return recentlyActive + } + + if let active, !active.isEmpty { + return true + } + return mode == .local + } + + private static func lastInputSeconds() -> Int? { + let anyEvent = CGEventType(rawValue: UInt32.max) ?? .null + let seconds = CGEventSource.secondsSinceLastEventType(.combinedSessionState, eventType: anyEvent) + if seconds.isNaN || seconds.isInfinite || seconds < 0 { return nil } + return Int(seconds.rounded()) + } +} + +#if DEBUG +extension ExecApprovalsGatewayPrompter { + static func _testShouldPresent( + mode: AppState.ConnectionMode, + activeSession: String?, + requestSession: String?, + lastInputSeconds: Int?, + thresholdSeconds: Int = 120) -> Bool + { + self.shouldPresent( + mode: mode, + activeSession: activeSession, + requestSession: requestSession, + lastInputSeconds: lastInputSeconds, + thresholdSeconds: thresholdSeconds) + } +} +#endif diff --git a/apps/macos/Sources/Clawdbot/ExecApprovalsSocket.swift b/apps/macos/Sources/Clawdbot/ExecApprovalsSocket.swift new file mode 100644 index 000000000..68f8e906d --- /dev/null +++ b/apps/macos/Sources/Clawdbot/ExecApprovalsSocket.swift @@ -0,0 +1,831 @@ +import AppKit +import ClawdbotKit +import CryptoKit +import Darwin +import Foundation +import OSLog + +struct ExecApprovalPromptRequest: Codable, Sendable { + var command: String + var cwd: String? + var host: String? + var security: String? + var ask: String? + var agentId: String? + var resolvedPath: String? + var sessionKey: String? +} + +private struct ExecApprovalSocketRequest: Codable { + var type: String + var token: String + var id: String + var request: ExecApprovalPromptRequest +} + +private struct ExecApprovalSocketDecision: Codable { + var type: String + var id: String + var decision: ExecApprovalDecision +} + +private struct ExecHostSocketRequest: Codable { + var type: String + var id: String + var nonce: String + var ts: Int + var hmac: String + var requestJson: String +} + +private struct ExecHostRequest: Codable { + var command: [String] + var rawCommand: String? + var cwd: String? + var env: [String: String]? + var timeoutMs: Int? + var needsScreenRecording: Bool? + var agentId: String? + var sessionKey: String? + var approvalDecision: ExecApprovalDecision? +} + +private struct ExecHostRunResult: Codable { + var exitCode: Int? + var timedOut: Bool + var success: Bool + var stdout: String + var stderr: String + var error: String? +} + +private struct ExecHostError: Codable { + var code: String + var message: String + var reason: String? +} + +private struct ExecHostResponse: Codable { + var type: String + var id: String + var ok: Bool + var payload: ExecHostRunResult? + var error: ExecHostError? +} + +enum ExecApprovalsSocketClient { + private struct TimeoutError: LocalizedError { + var message: String + var errorDescription: String? { self.message } + } + + static func requestDecision( + socketPath: String, + token: String, + request: ExecApprovalPromptRequest, + timeoutMs: Int = 15000) async -> ExecApprovalDecision? + { + let trimmedPath = socketPath.trimmingCharacters(in: .whitespacesAndNewlines) + let trimmedToken = token.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedPath.isEmpty, !trimmedToken.isEmpty else { return nil } + do { + return try await AsyncTimeout.withTimeoutMs( + timeoutMs: timeoutMs, + onTimeout: { + TimeoutError(message: "exec approvals socket timeout") + }, + operation: { + try await Task.detached { + try self.requestDecisionSync( + socketPath: trimmedPath, + token: trimmedToken, + request: request) + }.value + }) + } catch { + return nil + } + } + + private static func requestDecisionSync( + socketPath: String, + token: String, + request: ExecApprovalPromptRequest) throws -> ExecApprovalDecision? + { + let fd = socket(AF_UNIX, SOCK_STREAM, 0) + guard fd >= 0 else { + throw NSError(domain: "ExecApprovals", code: 1, userInfo: [ + NSLocalizedDescriptionKey: "socket create failed", + ]) + } + + var addr = sockaddr_un() + addr.sun_family = sa_family_t(AF_UNIX) + let maxLen = MemoryLayout.size(ofValue: addr.sun_path) + if socketPath.utf8.count >= maxLen { + throw NSError(domain: "ExecApprovals", code: 2, userInfo: [ + NSLocalizedDescriptionKey: "socket path too long", + ]) + } + socketPath.withCString { cstr in + withUnsafeMutablePointer(to: &addr.sun_path) { ptr in + let raw = UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: Int8.self) + strncpy(raw, cstr, maxLen - 1) + } + } + let size = socklen_t(MemoryLayout.size(ofValue: addr)) + let result = withUnsafePointer(to: &addr) { ptr in + ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { rebound in + connect(fd, rebound, size) + } + } + if result != 0 { + throw NSError(domain: "ExecApprovals", code: 3, userInfo: [ + NSLocalizedDescriptionKey: "socket connect failed", + ]) + } + + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + + let message = ExecApprovalSocketRequest( + type: "request", + token: token, + id: UUID().uuidString, + request: request) + let data = try JSONEncoder().encode(message) + var payload = data + payload.append(0x0A) + try handle.write(contentsOf: payload) + + guard let line = try self.readLine(from: handle, maxBytes: 256_000), + let lineData = line.data(using: .utf8) + else { return nil } + let response = try JSONDecoder().decode(ExecApprovalSocketDecision.self, from: lineData) + return response.decision + } + + private static func readLine(from handle: FileHandle, maxBytes: Int) throws -> String? { + var buffer = Data() + while buffer.count < maxBytes { + let chunk = try handle.read(upToCount: 4096) ?? Data() + if chunk.isEmpty { break } + buffer.append(chunk) + if buffer.contains(0x0A) { break } + } + guard let newlineIndex = buffer.firstIndex(of: 0x0A) else { + guard !buffer.isEmpty else { return nil } + return String(data: buffer, encoding: .utf8) + } + let lineData = buffer.subdata(in: 0.. ExecApprovalDecision { + NSApp.activate(ignoringOtherApps: true) + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = "Allow this command?" + alert.informativeText = "Review the command details before allowing." + alert.accessoryView = self.buildAccessoryView(request) + + alert.addButton(withTitle: "Allow Once") + alert.addButton(withTitle: "Always Allow") + alert.addButton(withTitle: "Don't Allow") + if #available(macOS 11.0, *), alert.buttons.indices.contains(2) { + alert.buttons[2].hasDestructiveAction = true + } + + switch alert.runModal() { + case .alertFirstButtonReturn: + return .allowOnce + case .alertSecondButtonReturn: + return .allowAlways + default: + return .deny + } + } + + @MainActor + private static func buildAccessoryView(_ request: ExecApprovalPromptRequest) -> NSView { + let stack = NSStackView() + stack.orientation = .vertical + stack.spacing = 8 + stack.alignment = .leading + + let commandTitle = NSTextField(labelWithString: "Command") + commandTitle.font = NSFont.boldSystemFont(ofSize: NSFont.systemFontSize) + stack.addArrangedSubview(commandTitle) + + let commandText = NSTextView() + commandText.isEditable = false + commandText.isSelectable = true + commandText.drawsBackground = true + commandText.backgroundColor = NSColor.textBackgroundColor + commandText.font = NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular) + commandText.string = request.command + commandText.textContainerInset = NSSize(width: 6, height: 6) + commandText.textContainer?.lineFragmentPadding = 0 + commandText.textContainer?.widthTracksTextView = true + commandText.isHorizontallyResizable = false + commandText.isVerticallyResizable = false + + let commandScroll = NSScrollView() + commandScroll.borderType = .lineBorder + commandScroll.hasVerticalScroller = false + commandScroll.hasHorizontalScroller = false + commandScroll.documentView = commandText + commandScroll.translatesAutoresizingMaskIntoConstraints = false + commandScroll.widthAnchor.constraint(lessThanOrEqualToConstant: 440).isActive = true + commandScroll.heightAnchor.constraint(greaterThanOrEqualToConstant: 56).isActive = true + stack.addArrangedSubview(commandScroll) + + let contextTitle = NSTextField(labelWithString: "Context") + contextTitle.font = NSFont.boldSystemFont(ofSize: NSFont.systemFontSize) + stack.addArrangedSubview(contextTitle) + + let contextStack = NSStackView() + contextStack.orientation = .vertical + contextStack.spacing = 4 + contextStack.alignment = .leading + + let trimmedCwd = request.cwd?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !trimmedCwd.isEmpty { + self.addDetailRow(title: "Working directory", value: trimmedCwd, to: contextStack) + } + let trimmedAgent = request.agentId?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !trimmedAgent.isEmpty { + self.addDetailRow(title: "Agent", value: trimmedAgent, to: contextStack) + } + let trimmedPath = request.resolvedPath?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !trimmedPath.isEmpty { + self.addDetailRow(title: "Executable", value: trimmedPath, to: contextStack) + } + let trimmedHost = request.host?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if !trimmedHost.isEmpty { + self.addDetailRow(title: "Host", value: trimmedHost, to: contextStack) + } + if let security = request.security?.trimmingCharacters(in: .whitespacesAndNewlines), !security.isEmpty { + self.addDetailRow(title: "Security", value: security, to: contextStack) + } + if let ask = request.ask?.trimmingCharacters(in: .whitespacesAndNewlines), !ask.isEmpty { + self.addDetailRow(title: "Ask mode", value: ask, to: contextStack) + } + + if contextStack.arrangedSubviews.isEmpty { + let empty = NSTextField(labelWithString: "No additional context provided.") + empty.textColor = NSColor.secondaryLabelColor + empty.font = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize) + contextStack.addArrangedSubview(empty) + } + + stack.addArrangedSubview(contextStack) + + let footer = NSTextField(labelWithString: "This runs on this machine.") + footer.textColor = NSColor.secondaryLabelColor + footer.font = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize) + stack.addArrangedSubview(footer) + + return stack + } + + @MainActor + private static func addDetailRow(title: String, value: String, to stack: NSStackView) { + let row = NSStackView() + row.orientation = .horizontal + row.spacing = 6 + row.alignment = .firstBaseline + + let titleLabel = NSTextField(labelWithString: "\(title):") + titleLabel.font = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize, weight: .semibold) + titleLabel.textColor = NSColor.secondaryLabelColor + + let valueLabel = NSTextField(labelWithString: value) + valueLabel.font = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize) + valueLabel.lineBreakMode = .byTruncatingMiddle + valueLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + + row.addArrangedSubview(titleLabel) + row.addArrangedSubview(valueLabel) + stack.addArrangedSubview(row) + } +} + +@MainActor +private enum ExecHostExecutor { + private struct ExecApprovalContext { + let command: [String] + let displayCommand: String + let trimmedAgent: String? + let approvals: ExecApprovalsResolved + let security: ExecSecurity + let ask: ExecAsk + let autoAllowSkills: Bool + let env: [String: String]? + let resolution: ExecCommandResolution? + let allowlistMatch: ExecAllowlistEntry? + let skillAllow: Bool + } + + private static let blockedEnvKeys: Set = [ + "PATH", + "NODE_OPTIONS", + "PYTHONHOME", + "PYTHONPATH", + "PERL5LIB", + "PERL5OPT", + "RUBYOPT", + ] + + private static let blockedEnvPrefixes: [String] = [ + "DYLD_", + "LD_", + ] + + static func handle(_ request: ExecHostRequest) async -> ExecHostResponse { + let command = request.command.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + guard !command.isEmpty else { + return self.errorResponse( + code: "INVALID_REQUEST", + message: "command required", + reason: "invalid") + } + + let context = await self.buildContext(request: request, command: command) + if context.security == .deny { + return self.errorResponse( + code: "UNAVAILABLE", + message: "SYSTEM_RUN_DISABLED: security=deny", + reason: "security=deny") + } + + let approvalDecision = request.approvalDecision + if approvalDecision == .deny { + return self.errorResponse( + code: "UNAVAILABLE", + message: "SYSTEM_RUN_DENIED: user denied", + reason: "user-denied") + } + + var approvedByAsk = approvalDecision != nil + if ExecApprovalHelpers.requiresAsk( + ask: context.ask, + security: context.security, + allowlistMatch: context.allowlistMatch, + skillAllow: context.skillAllow), + approvalDecision == nil + { + let decision = ExecApprovalsPromptPresenter.prompt( + ExecApprovalPromptRequest( + command: context.displayCommand, + cwd: request.cwd, + host: "node", + security: context.security.rawValue, + ask: context.ask.rawValue, + agentId: context.trimmedAgent, + resolvedPath: context.resolution?.resolvedPath, + sessionKey: request.sessionKey)) + + switch decision { + case .deny: + return self.errorResponse( + code: "UNAVAILABLE", + message: "SYSTEM_RUN_DENIED: user denied", + reason: "user-denied") + case .allowAlways: + approvedByAsk = true + self.persistAllowlistEntry(decision: decision, context: context) + case .allowOnce: + approvedByAsk = true + } + } + + self.persistAllowlistEntry(decision: approvalDecision, context: context) + + if context.security == .allowlist, + context.allowlistMatch == nil, + !context.skillAllow, + !approvedByAsk + { + return self.errorResponse( + code: "UNAVAILABLE", + message: "SYSTEM_RUN_DENIED: allowlist miss", + reason: "allowlist-miss") + } + + if let match = context.allowlistMatch { + ExecApprovalsStore.recordAllowlistUse( + agentId: context.trimmedAgent, + pattern: match.pattern, + command: context.displayCommand, + resolvedPath: context.resolution?.resolvedPath) + } + + if let errorResponse = await self.ensureScreenRecordingAccess(request.needsScreenRecording) { + return errorResponse + } + + return await self.runCommand( + command: command, + cwd: request.cwd, + env: context.env, + timeoutMs: request.timeoutMs) + } + + private static func buildContext(request: ExecHostRequest, command: [String]) async -> ExecApprovalContext { + let displayCommand = ExecCommandFormatter.displayString( + for: command, + rawCommand: request.rawCommand) + let agentId = request.agentId?.trimmingCharacters(in: .whitespacesAndNewlines) + let trimmedAgent = (agentId?.isEmpty == false) ? agentId : nil + let approvals = ExecApprovalsStore.resolve(agentId: trimmedAgent) + let security = approvals.agent.security + let ask = approvals.agent.ask + let autoAllowSkills = approvals.agent.autoAllowSkills + let env = self.sanitizedEnv(request.env) + let resolution = ExecCommandResolution.resolve( + command: command, + rawCommand: request.rawCommand, + cwd: request.cwd, + env: env) + let allowlistMatch = security == .allowlist + ? ExecAllowlistMatcher.match(entries: approvals.allowlist, resolution: resolution) + : nil + let skillAllow: Bool + if autoAllowSkills, let name = resolution?.executableName { + let bins = await SkillBinsCache.shared.currentBins() + skillAllow = bins.contains(name) + } else { + skillAllow = false + } + return ExecApprovalContext( + command: command, + displayCommand: displayCommand, + trimmedAgent: trimmedAgent, + approvals: approvals, + security: security, + ask: ask, + autoAllowSkills: autoAllowSkills, + env: env, + resolution: resolution, + allowlistMatch: allowlistMatch, + skillAllow: skillAllow) + } + + private static func persistAllowlistEntry( + decision: ExecApprovalDecision?, + context: ExecApprovalContext) + { + guard decision == .allowAlways, context.security == .allowlist else { return } + guard let pattern = ExecApprovalHelpers.allowlistPattern( + command: context.command, + resolution: context.resolution) + else { + return + } + ExecApprovalsStore.addAllowlistEntry(agentId: context.trimmedAgent, pattern: pattern) + } + + private static func ensureScreenRecordingAccess(_ needsScreenRecording: Bool?) async -> ExecHostResponse? { + guard needsScreenRecording == true else { return nil } + let authorized = await PermissionManager + .status([.screenRecording])[.screenRecording] ?? false + if authorized { return nil } + return self.errorResponse( + code: "UNAVAILABLE", + message: "PERMISSION_MISSING: screenRecording", + reason: "permission:screenRecording") + } + + private static func runCommand( + command: [String], + cwd: String?, + env: [String: String]?, + timeoutMs: Int?) async -> ExecHostResponse + { + let timeoutSec = timeoutMs.flatMap { Double($0) / 1000.0 } + let result = await Task.detached { () -> ShellExecutor.ShellResult in + await ShellExecutor.runDetailed( + command: command, + cwd: cwd, + env: env, + timeout: timeoutSec) + }.value + let payload = ExecHostRunResult( + exitCode: result.exitCode, + timedOut: result.timedOut, + success: result.success, + stdout: result.stdout, + stderr: result.stderr, + error: result.errorMessage) + return self.successResponse(payload) + } + + private static func errorResponse( + code: String, + message: String, + reason: String?) -> ExecHostResponse + { + ExecHostResponse( + type: "exec-res", + id: UUID().uuidString, + ok: false, + payload: nil, + error: ExecHostError(code: code, message: message, reason: reason)) + } + + private static func successResponse(_ payload: ExecHostRunResult) -> ExecHostResponse { + ExecHostResponse( + type: "exec-res", + id: UUID().uuidString, + ok: true, + payload: payload, + error: nil) + } + + private static func sanitizedEnv(_ overrides: [String: String]?) -> [String: String]? { + guard let overrides else { return nil } + var merged = ProcessInfo.processInfo.environment + for (rawKey, value) in overrides { + let key = rawKey.trimmingCharacters(in: .whitespacesAndNewlines) + guard !key.isEmpty else { continue } + let upper = key.uppercased() + if self.blockedEnvKeys.contains(upper) { continue } + if self.blockedEnvPrefixes.contains(where: { upper.hasPrefix($0) }) { continue } + merged[key] = value + } + return merged + } +} + +private final class ExecApprovalsSocketServer: @unchecked Sendable { + private let logger = Logger(subsystem: "com.clawdbot", category: "exec-approvals.socket") + private let socketPath: String + private let token: String + private let onPrompt: @Sendable (ExecApprovalPromptRequest) async -> ExecApprovalDecision + private let onExec: @Sendable (ExecHostRequest) async -> ExecHostResponse + private var socketFD: Int32 = -1 + private var acceptTask: Task? + private var isRunning = false + + init( + socketPath: String, + token: String, + onPrompt: @escaping @Sendable (ExecApprovalPromptRequest) async -> ExecApprovalDecision, + onExec: @escaping @Sendable (ExecHostRequest) async -> ExecHostResponse) + { + self.socketPath = socketPath + self.token = token + self.onPrompt = onPrompt + self.onExec = onExec + } + + func start() { + guard !self.isRunning else { return } + self.isRunning = true + self.acceptTask = Task.detached { [weak self] in + await self?.runAcceptLoop() + } + } + + func stop() { + self.isRunning = false + self.acceptTask?.cancel() + self.acceptTask = nil + if self.socketFD >= 0 { + close(self.socketFD) + self.socketFD = -1 + } + if !self.socketPath.isEmpty { + unlink(self.socketPath) + } + } + + private func runAcceptLoop() async { + let fd = self.openSocket() + guard fd >= 0 else { + self.isRunning = false + return + } + self.socketFD = fd + while self.isRunning { + var addr = sockaddr_un() + var len = socklen_t(MemoryLayout.size(ofValue: addr)) + let client = withUnsafeMutablePointer(to: &addr) { ptr in + ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { rebound in + accept(fd, rebound, &len) + } + } + if client < 0 { + if errno == EINTR { continue } + break + } + Task.detached { [weak self] in + await self?.handleClient(fd: client) + } + } + } + + private func openSocket() -> Int32 { + let fd = socket(AF_UNIX, SOCK_STREAM, 0) + guard fd >= 0 else { + self.logger.error("exec approvals socket create failed") + return -1 + } + unlink(self.socketPath) + var addr = sockaddr_un() + addr.sun_family = sa_family_t(AF_UNIX) + let maxLen = MemoryLayout.size(ofValue: addr.sun_path) + if self.socketPath.utf8.count >= maxLen { + self.logger.error("exec approvals socket path too long") + close(fd) + return -1 + } + self.socketPath.withCString { cstr in + withUnsafeMutablePointer(to: &addr.sun_path) { ptr in + let raw = UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: Int8.self) + memset(raw, 0, maxLen) + strncpy(raw, cstr, maxLen - 1) + } + } + let size = socklen_t(MemoryLayout.size(ofValue: addr)) + let result = withUnsafePointer(to: &addr) { ptr in + ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { rebound in + bind(fd, rebound, size) + } + } + if result != 0 { + self.logger.error("exec approvals socket bind failed") + close(fd) + return -1 + } + if listen(fd, 16) != 0 { + self.logger.error("exec approvals socket listen failed") + close(fd) + return -1 + } + chmod(self.socketPath, 0o600) + self.logger.info("exec approvals socket listening at \(self.socketPath, privacy: .public)") + return fd + } + + private func handleClient(fd: Int32) async { + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + do { + guard self.isAllowedPeer(fd: fd) else { + try self.sendApprovalResponse(handle: handle, id: UUID().uuidString, decision: .deny) + return + } + guard let line = try self.readLine(from: handle, maxBytes: 256_000), + let data = line.data(using: .utf8) + else { + return + } + guard + let envelope = try JSONSerialization.jsonObject(with: data) as? [String: Any], + let type = envelope["type"] as? String + else { + return + } + + if type == "request" { + let request = try JSONDecoder().decode(ExecApprovalSocketRequest.self, from: data) + guard request.token == self.token else { + try self.sendApprovalResponse(handle: handle, id: request.id, decision: .deny) + return + } + let decision = await self.onPrompt(request.request) + try self.sendApprovalResponse(handle: handle, id: request.id, decision: decision) + return + } + + if type == "exec" { + let request = try JSONDecoder().decode(ExecHostSocketRequest.self, from: data) + let response = await self.handleExecRequest(request) + try self.sendExecResponse(handle: handle, response: response) + return + } + } catch { + self.logger.error("exec approvals socket handling failed: \(error.localizedDescription, privacy: .public)") + } + } + + private func readLine(from handle: FileHandle, maxBytes: Int) throws -> String? { + var buffer = Data() + while buffer.count < maxBytes { + let chunk = try handle.read(upToCount: 4096) ?? Data() + if chunk.isEmpty { break } + buffer.append(chunk) + if buffer.contains(0x0A) { break } + } + guard let newlineIndex = buffer.firstIndex(of: 0x0A) else { + guard !buffer.isEmpty else { return nil } + return String(data: buffer, encoding: .utf8) + } + let lineData = buffer.subdata(in: 0.. Bool { + var uid = uid_t(0) + var gid = gid_t(0) + if getpeereid(fd, &uid, &gid) != 0 { + return false + } + return uid == geteuid() + } + + private func handleExecRequest(_ request: ExecHostSocketRequest) async -> ExecHostResponse { + let nowMs = Int(Date().timeIntervalSince1970 * 1000) + if abs(nowMs - request.ts) > 10000 { + return ExecHostResponse( + type: "exec-res", + id: request.id, + ok: false, + payload: nil, + error: ExecHostError(code: "INVALID_REQUEST", message: "expired request", reason: "ttl")) + } + let expected = self.hmacHex(nonce: request.nonce, ts: request.ts, requestJson: request.requestJson) + if expected != request.hmac { + return ExecHostResponse( + type: "exec-res", + id: request.id, + ok: false, + payload: nil, + error: ExecHostError(code: "INVALID_REQUEST", message: "invalid auth", reason: "hmac")) + } + guard let requestData = request.requestJson.data(using: .utf8), + let payload = try? JSONDecoder().decode(ExecHostRequest.self, from: requestData) + else { + return ExecHostResponse( + type: "exec-res", + id: request.id, + ok: false, + payload: nil, + error: ExecHostError(code: "INVALID_REQUEST", message: "invalid payload", reason: "json")) + } + let response = await self.onExec(payload) + return ExecHostResponse( + type: "exec-res", + id: request.id, + ok: response.ok, + payload: response.payload, + error: response.error) + } + + private func hmacHex(nonce: String, ts: Int, requestJson: String) -> String { + let key = SymmetricKey(data: Data(self.token.utf8)) + let message = "\(nonce):\(ts):\(requestJson)" + let mac = HMAC.authenticationCode(for: Data(message.utf8), using: key) + return mac.map { String(format: "%02x", $0) }.joined() + } +} diff --git a/apps/macos/Sources/Clawdbot/GatewayConnection.swift b/apps/macos/Sources/Clawdbot/GatewayConnection.swift index 2c61d1cd0..7facc6d61 100644 --- a/apps/macos/Sources/Clawdbot/GatewayConnection.swift +++ b/apps/macos/Sources/Clawdbot/GatewayConnection.swift @@ -1,4 +1,5 @@ import ClawdbotChatUI +import ClawdbotKit import ClawdbotProtocol import Foundation import OSLog @@ -10,10 +11,12 @@ enum GatewayAgentChannel: String, Codable, CaseIterable, Sendable { case whatsapp case telegram case discord + case googlechat case slack case signal case imessage case msteams + case bluebubbles case webchat init(raw: String?) { @@ -56,6 +59,7 @@ actor GatewayConnection { case configGet = "config.get" case configSet = "config.set" case configPatch = "config.patch" + case configSchema = "config.schema" case wizardStart = "wizard.start" case wizardNext = "wizard.next" case wizardCancel = "wizard.cancel" @@ -66,6 +70,7 @@ actor GatewayConnection { case channelsLogout = "channels.logout" case modelsList = "models.list" case chatHistory = "chat.history" + case sessionsPreview = "sessions.preview" case chatSend = "chat.send" case chatAbort = "chat.abort" case skillsStatus = "skills.status" @@ -75,6 +80,10 @@ actor GatewayConnection { case voicewakeSet = "voicewake.set" case nodePairApprove = "node.pair.approve" case nodePairReject = "node.pair.reject" + case devicePairList = "device.pair.list" + case devicePairApprove = "device.pair.approve" + case devicePairReject = "device.pair.reject" + case execApprovalResolve = "exec.approval.resolve" case cronList = "cron.list" case cronRuns = "cron.runs" case cronRun = "cron.run" @@ -141,6 +150,27 @@ actor GatewayConnection { } } + let nsError = lastError as NSError + if nsError.domain == URLError.errorDomain, + let fallback = await GatewayEndpointStore.shared.maybeFallbackToTailnet(from: cfg.url) + { + await self.configure(url: fallback.url, token: fallback.token, password: fallback.password) + for delayMs in [150, 400, 900] { + try await Task.sleep(nanoseconds: UInt64(delayMs) * 1_000_000) + do { + guard let client = self.client else { + throw NSError( + domain: "Gateway", + code: 0, + userInfo: [NSLocalizedDescriptionKey: "gateway not configured"]) + } + return try await client.request(method: method, params: params, timeoutMs: timeoutMs) + } catch { + lastError = error + } + } + } + throw lastError case .remote: let nsError = error as NSError @@ -221,6 +251,11 @@ actor GatewayConnection { await self.configure(url: cfg.url, token: cfg.token, password: cfg.password) } + func authSource() async -> GatewayAuthSource? { + guard let client else { return nil } + return await client.authSource() + } + func shutdown() async { if let client { await client.shutdown() @@ -237,9 +272,9 @@ actor GatewayConnection { return trimmed.isEmpty ? nil : trimmed } - private func sessionDefaultString(_ defaults: [String: AnyCodable]?, key: String) -> String { - (defaults?[key]?.stringValue ?? "") - .trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) + private func sessionDefaultString(_ defaults: [String: ClawdbotProtocol.AnyCodable]?, key: String) -> String { + let raw = defaults?[key]?.value as? String + return (raw ?? "").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } func cachedMainSessionKey() -> String? { @@ -248,6 +283,13 @@ actor GatewayConnection { return trimmed.isEmpty ? nil : trimmed } + func cachedGatewayVersion() -> String? { + guard let snapshot = self.lastSnapshot else { return nil } + let raw = snapshot.server["version"]?.value as? String + let trimmed = raw?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? nil : trimmed + } + func snapshotPaths() -> (configPath: String?, stateDir: String?) { guard let snapshot = self.lastSnapshot else { return (nil, nil) } let configPath = snapshot.snapshot.configpath?.trimmingCharacters(in: .whitespacesAndNewlines) @@ -500,6 +542,30 @@ extension GatewayConnection { return try await self.requestDecoded(method: .skillsUpdate, params: params) } + // MARK: - Sessions + + func sessionsPreview( + keys: [String], + limit: Int? = nil, + maxChars: Int? = nil, + timeoutMs: Int? = nil) async throws -> ClawdbotSessionsPreviewPayload + { + let resolvedKeys = keys + .map { self.canonicalizeSessionKey($0) } + .filter { !$0.isEmpty } + if resolvedKeys.isEmpty { + return ClawdbotSessionsPreviewPayload(ts: 0, previews: []) + } + var params: [String: AnyCodable] = ["keys": AnyCodable(resolvedKeys)] + if let limit { params["limit"] = AnyCodable(limit) } + if let maxChars { params["maxChars"] = AnyCodable(maxChars) } + let timeout = timeoutMs.map { Double($0) } + return try await self.requestDecoded( + method: .sessionsPreview, + params: params, + timeoutMs: timeout) + } + // MARK: - Chat func chatHistory( @@ -602,6 +668,22 @@ extension GatewayConnection { timeoutMs: 10000) } + // MARK: - Device pairing + + func devicePairApprove(requestId: String) async throws { + try await self.requestVoid( + method: .devicePairApprove, + params: ["requestId": AnyCodable(requestId)], + timeoutMs: 10000) + } + + func devicePairReject(requestId: String) async throws { + try await self.requestVoid( + method: .devicePairReject, + params: ["requestId": AnyCodable(requestId)], + timeoutMs: 10000) + } + // MARK: - Cron struct CronSchedulerStatus: Decodable, Sendable { diff --git a/apps/macos/Sources/Clawdbot/GatewayConnectivityCoordinator.swift b/apps/macos/Sources/Clawdbot/GatewayConnectivityCoordinator.swift new file mode 100644 index 000000000..ac65ec0ac --- /dev/null +++ b/apps/macos/Sources/Clawdbot/GatewayConnectivityCoordinator.swift @@ -0,0 +1,63 @@ +import Foundation +import Observation +import OSLog + +@MainActor +@Observable +final class GatewayConnectivityCoordinator { + static let shared = GatewayConnectivityCoordinator() + + private let logger = Logger(subsystem: "com.clawdbot", category: "gateway.connectivity") + private var endpointTask: Task? + private var lastResolvedURL: URL? + + private(set) var endpointState: GatewayEndpointState? + private(set) var resolvedURL: URL? + private(set) var resolvedMode: AppState.ConnectionMode? + private(set) var resolvedHostLabel: String? + + private init() { + self.start() + } + + func start() { + guard self.endpointTask == nil else { return } + self.endpointTask = Task { [weak self] in + guard let self else { return } + let stream = await GatewayEndpointStore.shared.subscribe() + for await state in stream { + await MainActor.run { self.handleEndpointState(state) } + } + } + } + + var localEndpointHostLabel: String? { + guard self.resolvedMode == .local, let url = self.resolvedURL else { return nil } + return Self.hostLabel(for: url) + } + + private func handleEndpointState(_ state: GatewayEndpointState) { + self.endpointState = state + switch state { + case let .ready(mode, url, _, _): + self.resolvedMode = mode + self.resolvedURL = url + self.resolvedHostLabel = Self.hostLabel(for: url) + let urlChanged = self.lastResolvedURL?.absoluteString != url.absoluteString + if urlChanged { + self.lastResolvedURL = url + Task { await ControlChannel.shared.refreshEndpoint(reason: "endpoint changed") } + } + case let .connecting(mode, _): + self.resolvedMode = mode + case let .unavailable(mode, _): + self.resolvedMode = mode + } + } + + private static func hostLabel(for url: URL) -> String { + let host = url.host ?? url.absoluteString + if let port = url.port { return "\(host):\(port)" } + return host + } +} diff --git a/apps/macos/Sources/Clawdbot/GatewayDiscoveryHelpers.swift b/apps/macos/Sources/Clawdbot/GatewayDiscoveryHelpers.swift new file mode 100644 index 000000000..2bb0aaf15 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/GatewayDiscoveryHelpers.swift @@ -0,0 +1,47 @@ +import ClawdbotDiscovery +import Foundation + +enum GatewayDiscoveryHelpers { + static func sshTarget(for gateway: GatewayDiscoveryModel.DiscoveredGateway) -> String? { + let host = self.sanitizedTailnetHost(gateway.tailnetDns) ?? gateway.lanHost + guard let host = self.trimmed(host), !host.isEmpty else { return nil } + let user = NSUserName() + var target = "\(user)@\(host)" + if gateway.sshPort != 22 { + target += ":\(gateway.sshPort)" + } + return target + } + + static func directUrl(for gateway: GatewayDiscoveryModel.DiscoveredGateway) -> String? { + self.directGatewayUrl( + tailnetDns: gateway.tailnetDns, + lanHost: gateway.lanHost, + gatewayPort: gateway.gatewayPort) + } + + static func directGatewayUrl( + tailnetDns: String?, + lanHost: String?, + gatewayPort: Int?) -> String? + { + if let tailnetDns = self.sanitizedTailnetHost(tailnetDns) { + return "wss://\(tailnetDns)" + } + guard let lanHost = self.trimmed(lanHost), !lanHost.isEmpty else { return nil } + let port = gatewayPort ?? 18789 + return "ws://\(lanHost):\(port)" + } + + static func sanitizedTailnetHost(_ host: String?) -> String? { + guard let host = self.trimmed(host), !host.isEmpty else { return nil } + if host.hasSuffix(".internal.") || host.hasSuffix(".internal") { + return nil + } + return host + } + + private static func trimmed(_ value: String?) -> String? { + value?.trimmingCharacters(in: .whitespacesAndNewlines) + } +} diff --git a/apps/macos/Sources/Clawdbot/GatewayDiscoveryMenu.swift b/apps/macos/Sources/Clawdbot/GatewayDiscoveryMenu.swift index f0e5a40a0..2a4c571eb 100644 --- a/apps/macos/Sources/Clawdbot/GatewayDiscoveryMenu.swift +++ b/apps/macos/Sources/Clawdbot/GatewayDiscoveryMenu.swift @@ -4,6 +4,8 @@ import SwiftUI struct GatewayDiscoveryInlineList: View { var discovery: GatewayDiscoveryModel var currentTarget: String? + var currentUrl: String? + var transport: AppState.RemoteTransport var onSelect: (GatewayDiscoveryModel.DiscoveredGateway) -> Void @State private var hoveredGatewayID: GatewayDiscoveryModel.DiscoveredGateway.ID? @@ -19,15 +21,14 @@ struct GatewayDiscoveryInlineList: View { } if self.discovery.gateways.isEmpty { - Text("No bridges found yet.") + Text("No gateways found yet.") .font(.caption) .foregroundStyle(.secondary) } else { VStack(alignment: .leading, spacing: 6) { ForEach(self.discovery.gateways.prefix(6)) { gateway in - let target = self.suggestedSSHTarget(gateway) - let selected = (target != nil && self.currentTarget? - .trimmingCharacters(in: .whitespacesAndNewlines) == target) + let display = self.displayInfo(for: gateway) + let selected = display.selected Button { withAnimation(.spring(response: 0.25, dampingFraction: 0.9)) { @@ -40,7 +41,7 @@ struct GatewayDiscoveryInlineList: View { .font(.callout.weight(.semibold)) .lineLimit(1) .truncationMode(.tail) - Text(target ?? "Bridge pairing only") + Text(display.label) .font(.caption.monospaced()) .foregroundStyle(.secondary) .lineLimit(1) @@ -83,27 +84,26 @@ struct GatewayDiscoveryInlineList: View { .fill(Color(NSColor.controlBackgroundColor))) } } - .help("Click a discovered bridge to fill the SSH target.") + .help(self.transport == .direct + ? "Click a discovered gateway to fill the gateway URL." + : "Click a discovered gateway to fill the SSH target.") } - private func suggestedSSHTarget(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) -> String? { - let host = self.sanitizedTailnetHost(gateway.tailnetDns) ?? gateway.lanHost - guard let host else { return nil } - let user = NSUserName() - return GatewayDiscoveryModel.buildSSHTarget( - user: user, - host: host, - port: gateway.sshPort) - } - - private func sanitizedTailnetHost(_ host: String?) -> String? { - guard let host else { return nil } - let trimmed = host.trimmingCharacters(in: .whitespacesAndNewlines) - if trimmed.isEmpty { return nil } - if trimmed.hasSuffix(".internal.") || trimmed.hasSuffix(".internal") { - return nil + private func displayInfo( + for gateway: GatewayDiscoveryModel.DiscoveredGateway) -> (label: String, selected: Bool) + { + switch self.transport { + case .direct: + let url = GatewayDiscoveryHelpers.directUrl(for: gateway) + let label = url ?? "Gateway pairing only" + let selected = url != nil && self.trimmed(self.currentUrl) == url + return (label, selected) + case .ssh: + let target = GatewayDiscoveryHelpers.sshTarget(for: gateway) + let label = target ?? "Gateway pairing only" + let selected = target != nil && self.trimmed(self.currentTarget) == target + return (label, selected) } - return trimmed } private func rowBackground(selected: Bool, hovered: Bool) -> Color { @@ -111,6 +111,10 @@ struct GatewayDiscoveryInlineList: View { if hovered { return Color.secondary.opacity(0.08) } return Color.clear } + + private func trimmed(_ value: String?) -> String { + value?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + } } struct GatewayDiscoveryMenu: View { @@ -130,6 +134,6 @@ struct GatewayDiscoveryMenu: View { } label: { Image(systemName: "dot.radiowaves.left.and.right") } - .help("Discover Clawdbot bridges on your LAN") + .help("Discover Clawdbot gateways on your LAN") } } diff --git a/apps/macos/Sources/Clawdbot/BridgeDiscoveryPreferences.swift b/apps/macos/Sources/Clawdbot/GatewayDiscoveryPreferences.swift similarity index 51% rename from apps/macos/Sources/Clawdbot/BridgeDiscoveryPreferences.swift rename to apps/macos/Sources/Clawdbot/GatewayDiscoveryPreferences.swift index 6147bbfd2..d725fdba5 100644 --- a/apps/macos/Sources/Clawdbot/BridgeDiscoveryPreferences.swift +++ b/apps/macos/Sources/Clawdbot/GatewayDiscoveryPreferences.swift @@ -1,10 +1,13 @@ import Foundation -enum BridgeDiscoveryPreferences { - private static let preferredStableIDKey = "bridge.preferredStableID" +enum GatewayDiscoveryPreferences { + private static let preferredStableIDKey = "gateway.preferredStableID" + private static let legacyPreferredStableIDKey = "bridge.preferredStableID" static func preferredStableID() -> String? { - let raw = UserDefaults.standard.string(forKey: self.preferredStableIDKey) + let defaults = UserDefaults.standard + let raw = defaults.string(forKey: self.preferredStableIDKey) + ?? defaults.string(forKey: self.legacyPreferredStableIDKey) let trimmed = raw?.trimmingCharacters(in: .whitespacesAndNewlines) return trimmed?.isEmpty == false ? trimmed : nil } @@ -13,8 +16,10 @@ enum BridgeDiscoveryPreferences { let trimmed = stableID?.trimmingCharacters(in: .whitespacesAndNewlines) if let trimmed, !trimmed.isEmpty { UserDefaults.standard.set(trimmed, forKey: self.preferredStableIDKey) + UserDefaults.standard.removeObject(forKey: self.legacyPreferredStableIDKey) } else { UserDefaults.standard.removeObject(forKey: self.preferredStableIDKey) + UserDefaults.standard.removeObject(forKey: self.legacyPreferredStableIDKey) } } } diff --git a/apps/macos/Sources/Clawdbot/GatewayEndpointStore.swift b/apps/macos/Sources/Clawdbot/GatewayEndpointStore.swift index 9043fc17e..d9385bc79 100644 --- a/apps/macos/Sources/Clawdbot/GatewayEndpointStore.swift +++ b/apps/macos/Sources/Clawdbot/GatewayEndpointStore.swift @@ -1,3 +1,4 @@ +import ConcurrencyExtras import Foundation import OSLog @@ -14,8 +15,21 @@ enum GatewayEndpointState: Sendable, Equatable { /// - The endpoint store owns observation + explicit "ensure tunnel" actions. actor GatewayEndpointStore { static let shared = GatewayEndpointStore() - private static let supportedBindModes: Set = ["loopback", "tailnet", "lan", "auto"] + private static let supportedBindModes: Set = [ + "loopback", + "tailnet", + "lan", + "auto", + "custom", + ] private static let remoteConnectingDetail = "Connecting to remote gateway…" + private static let staticLogger = Logger(subsystem: "com.clawdbot", category: "gateway-endpoint") + private enum EnvOverrideWarningKind: Sendable { + case token + case password + } + + private static let envOverrideWarnings = LockIsolated((token: false, password: false)) struct Deps: Sendable { let mode: @Sendable () async -> AppState.ConnectionMode @@ -30,16 +44,18 @@ actor GatewayEndpointStore { mode: { await MainActor.run { AppStateStore.shared.connectionMode } }, token: { let root = ClawdbotConfigFile.loadDict() + let isRemote = ConnectionModeResolver.resolve(root: root).mode == .remote return GatewayEndpointStore.resolveGatewayToken( - isRemote: CommandResolver.connectionModeIsRemote(), + isRemote: isRemote, root: root, env: ProcessInfo.processInfo.environment, launchdSnapshot: GatewayLaunchAgentManager.launchdConfigSnapshot()) }, password: { let root = ClawdbotConfigFile.loadDict() + let isRemote = ConnectionModeResolver.resolve(root: root).mode == .remote return GatewayEndpointStore.resolveGatewayPassword( - isRemote: CommandResolver.connectionModeIsRemote(), + isRemote: isRemote, root: root, env: ProcessInfo.processInfo.environment, launchdSnapshot: GatewayLaunchAgentManager.launchdConfigSnapshot()) @@ -50,9 +66,12 @@ actor GatewayEndpointStore { let bind = GatewayEndpointStore.resolveGatewayBindMode( root: root, env: ProcessInfo.processInfo.environment) + let customBindHost = GatewayEndpointStore.resolveGatewayCustomBindHost(root: root) let tailscaleIP = await MainActor.run { TailscaleService.shared.tailscaleIP } + ?? TailscaleService.fallbackTailnetIPv4() return GatewayEndpointStore.resolveLocalGatewayHost( bindMode: bind, + customBindHost: customBindHost, tailscaleIP: tailscaleIP) }, remotePortIfRunning: { await RemoteTunnelManager.shared.controlTunnelPortIfRunning() }, @@ -68,6 +87,14 @@ actor GatewayEndpointStore { let raw = env["CLAWDBOT_GATEWAY_PASSWORD"] ?? "" let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) if !trimmed.isEmpty { + if let configPassword = self.resolveConfigPassword(isRemote: isRemote, root: root), + !configPassword.isEmpty + { + self.warnEnvOverrideOnce( + kind: .password, + envVar: "CLAWDBOT_GATEWAY_PASSWORD", + configKey: isRemote ? "gateway.remote.password" : "gateway.auth.password") + } return trimmed } if isRemote { @@ -99,6 +126,26 @@ actor GatewayEndpointStore { return nil } + private static func resolveConfigPassword(isRemote: Bool, root: [String: Any]) -> String? { + if isRemote { + if let gateway = root["gateway"] as? [String: Any], + let remote = gateway["remote"] as? [String: Any], + let password = remote["password"] as? String + { + return password.trimmingCharacters(in: .whitespacesAndNewlines) + } + return nil + } + + if let gateway = root["gateway"] as? [String: Any], + let auth = gateway["auth"] as? [String: Any], + let password = auth["password"] as? String + { + return password.trimmingCharacters(in: .whitespacesAndNewlines) + } + return nil + } + private static func resolveGatewayToken( isRemote: Bool, root: [String: Any], @@ -108,37 +155,80 @@ actor GatewayEndpointStore { let raw = env["CLAWDBOT_GATEWAY_TOKEN"] ?? "" let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) if !trimmed.isEmpty { + if let configToken = self.resolveConfigToken(isRemote: isRemote, root: root), + !configToken.isEmpty, + configToken != trimmed + { + self.warnEnvOverrideOnce( + kind: .token, + envVar: "CLAWDBOT_GATEWAY_TOKEN", + configKey: isRemote ? "gateway.remote.token" : "gateway.auth.token") + } return trimmed } + + if let configToken = self.resolveConfigToken(isRemote: isRemote, root: root), + !configToken.isEmpty + { + return configToken + } + if isRemote { - if let gateway = root["gateway"] as? [String: Any], - let remote = gateway["remote"] as? [String: Any], - let token = remote["token"] as? String - { - let value = token.trimmingCharacters(in: .whitespacesAndNewlines) - if !value.isEmpty { - return value - } - } return nil } - if let gateway = root["gateway"] as? [String: Any], - let auth = gateway["auth"] as? [String: Any], - let token = auth["token"] as? String - { - let value = token.trimmingCharacters(in: .whitespacesAndNewlines) - if !value.isEmpty { - return value - } - } + if let token = launchdSnapshot?.token?.trimmingCharacters(in: .whitespacesAndNewlines), !token.isEmpty { return token } + return nil } + private static func resolveConfigToken(isRemote: Bool, root: [String: Any]) -> String? { + if isRemote { + if let gateway = root["gateway"] as? [String: Any], + let remote = gateway["remote"] as? [String: Any], + let token = remote["token"] as? String + { + return token.trimmingCharacters(in: .whitespacesAndNewlines) + } + return nil + } + + if let gateway = root["gateway"] as? [String: Any], + let auth = gateway["auth"] as? [String: Any], + let token = auth["token"] as? String + { + return token.trimmingCharacters(in: .whitespacesAndNewlines) + } + return nil + } + + private static func warnEnvOverrideOnce( + kind: EnvOverrideWarningKind, + envVar: String, + configKey: String) + { + let shouldWarn = Self.envOverrideWarnings.withValue { state in + switch kind { + case .token: + guard !state.token else { return false } + state.token = true + return true + case .password: + guard !state.password else { return false } + state.password = true + return true + } + } + guard shouldWarn else { return } + Self.staticLogger.warning( + "\(envVar, privacy: .public) is set and overrides \(configKey, privacy: .public). " + + "If this is unintentional, clear it with: launchctl unsetenv \(envVar, privacy: .public)") + } + private let deps: Deps private let logger = Logger(subsystem: "com.clawdbot", category: "gateway-endpoint") @@ -161,14 +251,21 @@ actor GatewayEndpointStore { let bind = GatewayEndpointStore.resolveGatewayBindMode( root: ClawdbotConfigFile.loadDict(), env: ProcessInfo.processInfo.environment) - let host = GatewayEndpointStore.resolveLocalGatewayHost(bindMode: bind, tailscaleIP: nil) + let customBindHost = GatewayEndpointStore.resolveGatewayCustomBindHost(root: ClawdbotConfigFile.loadDict()) + let scheme = GatewayEndpointStore.resolveGatewayScheme( + root: ClawdbotConfigFile.loadDict(), + env: ProcessInfo.processInfo.environment) + let host = GatewayEndpointStore.resolveLocalGatewayHost( + bindMode: bind, + customBindHost: customBindHost, + tailscaleIP: nil) let token = deps.token() let password = deps.password() switch initialMode { case .local: self.state = .ready( mode: .local, - url: URL(string: "ws://\(host):\(port)")!, + url: URL(string: "\(scheme)://\(host):\(port)")!, token: token, password: password) case .remote: @@ -205,12 +302,28 @@ actor GatewayEndpointStore { self.cancelRemoteEnsure() let port = self.deps.localPort() let host = await self.deps.localHost() + let scheme = GatewayEndpointStore.resolveGatewayScheme( + root: ClawdbotConfigFile.loadDict(), + env: ProcessInfo.processInfo.environment) self.setState(.ready( mode: .local, - url: URL(string: "ws://\(host):\(port)")!, + url: URL(string: "\(scheme)://\(host):\(port)")!, token: token, password: password)) case .remote: + let root = ClawdbotConfigFile.loadDict() + if GatewayRemoteConfig.resolveTransport(root: root) == .direct { + guard let url = GatewayRemoteConfig.resolveGatewayUrl(root: root) else { + self.cancelRemoteEnsure() + self.setState(.unavailable( + mode: .remote, + reason: "gateway.remote.url missing or invalid for direct transport")) + return + } + self.cancelRemoteEnsure() + self.setState(.ready(mode: .remote, url: url, token: token, password: password)) + return + } let port = await self.deps.remotePortIfRunning() guard let port else { self.setState(.connecting(mode: .remote, detail: Self.remoteConnectingDetail)) @@ -218,9 +331,12 @@ actor GatewayEndpointStore { return } self.cancelRemoteEnsure() + let scheme = GatewayEndpointStore.resolveGatewayScheme( + root: ClawdbotConfigFile.loadDict(), + env: ProcessInfo.processInfo.environment) self.setState(.ready( mode: .remote, - url: URL(string: "ws://127.0.0.1:\(Int(port))")!, + url: URL(string: "\(scheme)://127.0.0.1:\(Int(port))")!, token: token, password: password)) case .unconfigured: @@ -238,6 +354,25 @@ actor GatewayEndpointStore { code: 1, userInfo: [NSLocalizedDescriptionKey: "Remote mode is not enabled"]) } + let root = ClawdbotConfigFile.loadDict() + if GatewayRemoteConfig.resolveTransport(root: root) == .direct { + guard let url = GatewayRemoteConfig.resolveGatewayUrl(root: root) else { + throw NSError( + domain: "GatewayEndpoint", + code: 1, + userInfo: [NSLocalizedDescriptionKey: "gateway.remote.url missing or invalid"]) + } + guard let port = GatewayRemoteConfig.defaultPort(for: url), + let portInt = UInt16(exactly: port) + else { + throw NSError( + domain: "GatewayEndpoint", + code: 1, + userInfo: [NSLocalizedDescriptionKey: "Invalid gateway.remote.url port"]) + } + self.logger.info("remote transport direct; skipping SSH tunnel") + return portInt + } let config = try await self.ensureRemoteConfig(detail: Self.remoteConnectingDetail) guard let portInt = config.0.port, let port = UInt16(exactly: portInt) else { throw NSError( @@ -298,6 +433,21 @@ actor GatewayEndpointStore { userInfo: [NSLocalizedDescriptionKey: "Remote mode is not enabled"]) } + let root = ClawdbotConfigFile.loadDict() + if GatewayRemoteConfig.resolveTransport(root: root) == .direct { + guard let url = GatewayRemoteConfig.resolveGatewayUrl(root: root) else { + throw NSError( + domain: "GatewayEndpoint", + code: 1, + userInfo: [NSLocalizedDescriptionKey: "gateway.remote.url missing or invalid"]) + } + let token = self.deps.token() + let password = self.deps.password() + self.cancelRemoteEnsure() + self.setState(.ready(mode: .remote, url: url, token: token, password: password)) + return (url, token, password) + } + self.kickRemoteEnsureIfNeeded(detail: detail) guard let ensure = self.remoteEnsure else { throw NSError(domain: "GatewayEndpoint", code: 1, userInfo: [NSLocalizedDescriptionKey: "Connecting…"]) @@ -319,7 +469,10 @@ actor GatewayEndpointStore { let token = self.deps.token() let password = self.deps.password() - let url = URL(string: "ws://127.0.0.1:\(Int(forwarded))")! + let scheme = GatewayEndpointStore.resolveGatewayScheme( + root: ClawdbotConfigFile.loadDict(), + env: ProcessInfo.processInfo.environment) + let url = URL(string: "\(scheme)://127.0.0.1:\(Int(forwarded))")! self.setState(.ready(mode: .remote, url: url, token: token, password: password)) return (url, token, password) } catch let err as CancellationError { @@ -368,6 +521,36 @@ actor GatewayEndpointStore { } } + func maybeFallbackToTailnet(from currentURL: URL) async -> GatewayConnection.Config? { + let mode = await self.deps.mode() + guard mode == .local else { return nil } + + let root = ClawdbotConfigFile.loadDict() + let bind = GatewayEndpointStore.resolveGatewayBindMode( + root: root, + env: ProcessInfo.processInfo.environment) + guard bind == "tailnet" else { return nil } + + let currentHost = currentURL.host?.lowercased() ?? "" + guard currentHost == "127.0.0.1" || currentHost == "localhost" else { return nil } + + let tailscaleIP = await MainActor.run { TailscaleService.shared.tailscaleIP } + ?? TailscaleService.fallbackTailnetIPv4() + guard let tailscaleIP, !tailscaleIP.isEmpty else { return nil } + + let scheme = GatewayEndpointStore.resolveGatewayScheme( + root: root, + env: ProcessInfo.processInfo.environment) + let port = self.deps.localPort() + let token = self.deps.token() + let password = self.deps.password() + let url = URL(string: "\(scheme)://\(tailscaleIP):\(port)")! + + self.logger.info("auto bind fallback to tailnet host=\(tailscaleIP, privacy: .public)") + self.setState(.ready(mode: .local, url: url, token: token, password: password)) + return (url, token, password) + } + private static func resolveGatewayBindMode( root: [String: Any], env: [String: String]) -> String? @@ -389,13 +572,46 @@ actor GatewayEndpointStore { return nil } + private static func resolveGatewayCustomBindHost(root: [String: Any]) -> String? { + if let gateway = root["gateway"] as? [String: Any], + let customBindHost = gateway["customBindHost"] as? String + { + let trimmed = customBindHost.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } + return nil + } + + private static func resolveGatewayScheme( + root: [String: Any], + env: [String: String]) -> String + { + if let envValue = env["CLAWDBOT_GATEWAY_TLS"]?.trimmingCharacters(in: .whitespacesAndNewlines), + !envValue.isEmpty + { + return (envValue == "1" || envValue.lowercased() == "true") ? "wss" : "ws" + } + if let gateway = root["gateway"] as? [String: Any], + let tls = gateway["tls"] as? [String: Any], + let enabled = tls["enabled"] as? Bool + { + return enabled ? "wss" : "ws" + } + return "ws" + } + private static func resolveLocalGatewayHost( bindMode: String?, + customBindHost: String?, tailscaleIP: String?) -> String { switch bindMode { - case "tailnet", "auto": + case "tailnet": tailscaleIP ?? "127.0.0.1" + case "auto": + "127.0.0.1" + case "custom": + customBindHost ?? "127.0.0.1" default: "127.0.0.1" } @@ -468,9 +684,13 @@ extension GatewayEndpointStore { static func _testResolveLocalGatewayHost( bindMode: String?, - tailscaleIP: String?) -> String + tailscaleIP: String?, + customBindHost: String? = nil) -> String { - self.resolveLocalGatewayHost(bindMode: bindMode, tailscaleIP: tailscaleIP) + self.resolveLocalGatewayHost( + bindMode: bindMode, + customBindHost: customBindHost, + tailscaleIP: tailscaleIP) } } #endif diff --git a/apps/macos/Sources/Clawdbot/GatewayEnvironment.swift b/apps/macos/Sources/Clawdbot/GatewayEnvironment.swift index d1371cdf1..5817a8b3b 100644 --- a/apps/macos/Sources/Clawdbot/GatewayEnvironment.swift +++ b/apps/macos/Sources/Clawdbot/GatewayEnvironment.swift @@ -25,8 +25,14 @@ struct Semver: Comparable, CustomStringConvertible, Sendable { let major = Int(parts[0]), let minor = Int(parts[1]) else { return nil } - let patch = Int(parts[2]) ?? 0 - return Semver(major: major, minor: minor, patch: patch) + // Strip prerelease suffix (e.g., "11-4" → "11", "5-beta.1" → "5") + let patchRaw = String(parts[2]) + guard let patchToken = patchRaw.split(whereSeparator: { $0 == "-" || $0 == "+" }).first, + let patchNumeric = Int(patchToken) + else { + return nil + } + return Semver(major: major, minor: minor, patch: patchNumeric) } func compatible(with required: Semver) -> Bool { @@ -78,8 +84,13 @@ enum GatewayEnvironment { } static func expectedGatewayVersion() -> Semver? { + Semver.parse(self.expectedGatewayVersionString()) + } + + static func expectedGatewayVersionString() -> String? { let bundleVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String - return Semver.parse(bundleVersion) + let trimmed = bundleVersion?.trimmingCharacters(in: .whitespacesAndNewlines) + return (trimmed?.isEmpty == false) ? trimmed : nil } // Exposed for tests so we can inject fake version checks without rewriting bundle metadata. @@ -98,6 +109,7 @@ enum GatewayEnvironment { } } let expected = self.expectedGatewayVersion() + let expectedString = self.expectedGatewayVersionString() let projectRoot = CommandResolver.projectRoot() let projectEntrypoint = CommandResolver.gatewayEntrypoint(in: projectRoot) @@ -108,7 +120,7 @@ enum GatewayEnvironment { kind: .missingNode, nodeVersion: nil, gatewayVersion: nil, - requiredGateway: expected?.description, + requiredGateway: expectedString, message: RuntimeLocator.describeFailure(err)) case let .success(runtime): let gatewayBin = CommandResolver.clawdbotExecutable() @@ -118,7 +130,7 @@ enum GatewayEnvironment { kind: .missingGateway, nodeVersion: runtime.version.description, gatewayVersion: nil, - requiredGateway: expected?.description, + requiredGateway: expectedString, message: "clawdbot CLI not found in PATH; install the CLI.") } @@ -126,13 +138,14 @@ enum GatewayEnvironment { ?? self.readLocalGatewayVersion(projectRoot: projectRoot) if let expected, let installed, !installed.compatible(with: expected) { + let expectedText = expectedString ?? expected.description return GatewayEnvironmentStatus( - kind: .incompatible(found: installed.description, required: expected.description), + kind: .incompatible(found: installed.description, required: expectedText), nodeVersion: runtime.version.description, gatewayVersion: installed.description, - requiredGateway: expected.description, + requiredGateway: expectedText, message: """ - Gateway version \(installed.description) is incompatible with app \(expected.description); + Gateway version \(installed.description) is incompatible with app \(expectedText); install or update the global package. """) } @@ -150,7 +163,7 @@ enum GatewayEnvironment { kind: .ok, nodeVersion: runtime.version.description, gatewayVersion: gatewayVersionText, - requiredGateway: expected?.description, + requiredGateway: expectedString, message: "Node \(runtime.version.description); gateway \(gatewayVersionText) \(gatewayLabelText)") } } @@ -218,8 +231,17 @@ enum GatewayEnvironment { } static func installGlobal(version: Semver?, statusHandler: @escaping @Sendable (String) -> Void) async { + await self.installGlobal(versionString: version?.description, statusHandler: statusHandler) + } + + static func installGlobal(versionString: String?, statusHandler: @escaping @Sendable (String) -> Void) async { let preferred = CommandResolver.preferredPaths().joined(separator: ":") - let target = version?.description ?? "latest" + let trimmed = versionString?.trimmingCharacters(in: .whitespacesAndNewlines) + let target: String = if let trimmed, !trimmed.isEmpty { + trimmed + } else { + "latest" + } let npm = CommandResolver.findExecutable(named: "npm") let pnpm = CommandResolver.findExecutable(named: "pnpm") let bun = CommandResolver.findExecutable(named: "bun") @@ -278,8 +300,7 @@ enum GatewayEnvironment { process.standardOutput = pipe process.standardError = pipe do { - try process.run() - process.waitUntilExit() + let data = try process.runAndReadToEnd(from: pipe) let elapsedMs = Int(Date().timeIntervalSince(start) * 1000) if elapsedMs > 500 { self.logger.warning( @@ -294,7 +315,6 @@ enum GatewayEnvironment { bin=\(binary, privacy: .public) """) } - let data = pipe.fileHandleForReading.readToEndSafely() let raw = String(data: data, encoding: .utf8)? .trimmingCharacters(in: .whitespacesAndNewlines) return Semver.parse(raw) diff --git a/apps/macos/Sources/Clawdbot/GatewayLaunchAgentManager.swift b/apps/macos/Sources/Clawdbot/GatewayLaunchAgentManager.swift index 6f484cc80..f0896e691 100644 --- a/apps/macos/Sources/Clawdbot/GatewayLaunchAgentManager.swift +++ b/apps/macos/Sources/Clawdbot/GatewayLaunchAgentManager.swift @@ -4,11 +4,46 @@ enum GatewayLaunchAgentManager { private static let logger = Logger(subsystem: "com.clawdbot", category: "gateway.launchd") private static let disableLaunchAgentMarker = ".clawdbot/disable-launchagent" + private static var disableLaunchAgentMarkerURL: URL { + FileManager().homeDirectoryForCurrentUser + .appendingPathComponent(self.disableLaunchAgentMarker) + } + private static var plistURL: URL { - FileManager.default.homeDirectoryForCurrentUser + FileManager().homeDirectoryForCurrentUser .appendingPathComponent("Library/LaunchAgents/\(gatewayLaunchdLabel).plist") } + static func isLaunchAgentWriteDisabled() -> Bool { + FileManager().fileExists(atPath: self.disableLaunchAgentMarkerURL.path) + } + + static func setLaunchAgentWriteDisabled(_ disabled: Bool) -> String? { + let marker = self.disableLaunchAgentMarkerURL + if disabled { + do { + try FileManager().createDirectory( + at: marker.deletingLastPathComponent(), + withIntermediateDirectories: true) + if !FileManager().fileExists(atPath: marker.path) { + FileManager().createFile(atPath: marker.path, contents: nil) + } + } catch { + return error.localizedDescription + } + return nil + } + + if FileManager().fileExists(atPath: marker.path) { + do { + try FileManager().removeItem(at: marker) + } catch { + return error.localizedDescription + } + } + return nil + } + static func isLoaded() async -> Bool { guard let loaded = await self.readDaemonLoaded() else { return false } return loaded @@ -16,6 +51,10 @@ enum GatewayLaunchAgentManager { static func set(enabled: Bool, bundlePath: String, port: Int) async -> String? { _ = bundlePath + guard !CommandResolver.connectionModeIsRemote() else { + self.logger.info("launchd change skipped (remote mode)") + return nil + } if enabled, self.isLaunchAgentWriteDisabled() { self.logger.info("launchd enable skipped (disable marker set)") return nil @@ -62,12 +101,6 @@ enum GatewayLaunchAgentManager { } extension GatewayLaunchAgentManager { - private static func isLaunchAgentWriteDisabled() -> Bool { - let marker = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent(self.disableLaunchAgentMarker) - return FileManager.default.fileExists(atPath: marker.path) - } - private static func readDaemonLoaded() async -> Bool? { let result = await self.runDaemonCommandResult( ["status", "--json", "--no-probe"], @@ -111,8 +144,10 @@ extension GatewayLaunchAgentManager { quiet: Bool) async -> CommandResult { let command = CommandResolver.clawdbotCommand( - subcommand: "daemon", - extraArgs: self.withJsonFlag(args)) + subcommand: "gateway", + extraArgs: self.withJsonFlag(args), + // Launchd management must always run locally, even if remote mode is configured. + configRoot: ["gateway": ["mode": "local"]]) var env = ProcessInfo.processInfo.environment env["PATH"] = CommandResolver.preferredPaths().joined(separator: ":") let response = await ShellExecutor.runDetailed(command: command, cwd: nil, env: env, timeout: timeout) diff --git a/apps/macos/Sources/Clawdbot/GatewayPayloadDecoding.swift b/apps/macos/Sources/Clawdbot/GatewayPayloadDecoding.swift deleted file mode 100644 index e0ad02aa4..000000000 --- a/apps/macos/Sources/Clawdbot/GatewayPayloadDecoding.swift +++ /dev/null @@ -1,16 +0,0 @@ -import ClawdbotProtocol -import Foundation - -enum GatewayPayloadDecoding { - static func decode(_ payload: ClawdbotProtocol.AnyCodable, as _: T.Type = T.self) throws -> T { - let data = try JSONEncoder().encode(payload) - return try JSONDecoder().decode(T.self, from: data) - } - - static func decodeIfPresent(_ payload: ClawdbotProtocol.AnyCodable?, as _: T.Type = T.self) throws - -> T? - { - guard let payload else { return nil } - return try self.decode(payload, as: T.self) - } -} diff --git a/apps/macos/Sources/Clawdbot/GatewayProcessManager.swift b/apps/macos/Sources/Clawdbot/GatewayProcessManager.swift index 8369dbb93..60964fa39 100644 --- a/apps/macos/Sources/Clawdbot/GatewayProcessManager.swift +++ b/apps/macos/Sources/Clawdbot/GatewayProcessManager.swift @@ -42,10 +42,20 @@ final class GatewayProcessManager { private var environmentRefreshTask: Task? private var lastEnvironmentRefresh: Date? private var logRefreshTask: Task? + #if DEBUG + private var testingConnection: GatewayConnection? + #endif private let logger = Logger(subsystem: "com.clawdbot", category: "gateway.process") private let logLimit = 20000 // characters to keep in-memory private let environmentRefreshMinInterval: TimeInterval = 30 + private var connection: GatewayConnection { + #if DEBUG + return self.testingConnection ?? .shared + #else + return .shared + #endif + } func setActive(_ active: Bool) { // Remote mode should never spawn a local gateway; treat as stopped. @@ -69,6 +79,11 @@ final class GatewayProcessManager { func ensureLaunchAgentEnabledIfNeeded() async { guard !CommandResolver.connectionModeIsRemote() else { return } + if GatewayLaunchAgentManager.isLaunchAgentWriteDisabled() { + self.appendLog("[gateway] launchd auto-enable skipped (attach-only)\n") + self.logger.info("gateway launchd auto-enable skipped (disable marker set)") + return + } let enabled = await GatewayLaunchAgentManager.isLoaded() guard !enabled else { return } let bundlePath = Bundle.main.bundleURL.path @@ -114,6 +129,9 @@ final class GatewayProcessManager { self.lastFailureReason = nil self.status = .stopped self.logger.info("gateway stop requested") + if CommandResolver.connectionModeIsRemote() { + return + } let bundlePath = Bundle.main.bundleURL.path Task { _ = await GatewayLaunchAgentManager.set( @@ -123,6 +141,10 @@ final class GatewayProcessManager { } } + func clearLastFailure() { + self.lastFailureReason = nil + } + func refreshEnvironmentStatus(force: Bool = false) { let now = Date() if !force { @@ -175,7 +197,7 @@ final class GatewayProcessManager { let hasListener = instance != nil let attemptAttach = { - try await GatewayConnection.shared.requestRaw(method: .health, timeoutMs: 2000) + try await self.connection.requestRaw(method: .health, timeoutMs: 2000) } for attempt in 0..<(hasListener ? 3 : 1) { @@ -184,6 +206,7 @@ final class GatewayProcessManager { let snap = decodeHealthSnapshot(from: data) let details = self.describe(details: instanceText, port: port, snap: snap) self.existingGatewayDetails = details + self.clearLastFailure() self.status = .attachedExisting(details: details) self.appendLog("[gateway] using existing instance: \(details)\n") self.logger.info("gateway using existing instance details=\(details)") @@ -219,19 +242,17 @@ final class GatewayProcessManager { private func describe(details instance: String?, port: Int, snap: HealthSnapshot?) -> String { let instanceText = instance ?? "pid unknown" if let snap { - let linkId = snap.channelOrder?.first(where: { - if let summary = snap.channels[$0] { return summary.linked != nil } - return false - }) ?? snap.channels.keys.first(where: { - if let summary = snap.channels[$0] { return summary.linked != nil } - return false - }) - let linked = linkId.flatMap { snap.channels[$0]?.linked } ?? false - let authAge = linkId.flatMap { snap.channels[$0]?.authAgeMs }.flatMap(msToAge) ?? "unknown age" + let order = snap.channelOrder ?? Array(snap.channels.keys) + let linkId = order.first(where: { snap.channels[$0]?.linked == true }) + ?? order.first(where: { snap.channels[$0]?.linked != nil }) + guard let linkId else { + return "port \(port), health probe succeeded, \(instanceText)" + } + let linked = snap.channels[linkId]?.linked ?? false + let authAge = snap.channels[linkId]?.authAgeMs.flatMap(msToAge) ?? "unknown age" let label = - linkId.flatMap { snap.channelLabels?[$0] } ?? - linkId?.capitalized ?? - "channel" + snap.channelLabels?[linkId] ?? + linkId.capitalized let linkText = linked ? "linked" : "not linked" return "port \(port), \(label) \(linkText), auth \(authAge), \(instanceText)" } @@ -290,6 +311,15 @@ final class GatewayProcessManager { return } + if GatewayLaunchAgentManager.isLaunchAgentWriteDisabled() { + let message = "Launchd disabled; start the Gateway manually or disable attach-only." + self.status = .failed(message) + self.lastFailureReason = "launchd disabled" + self.appendLog("[gateway] launchd disabled; skipping auto-start\n") + self.logger.info("gateway launchd enable skipped (disable marker set)") + return + } + let bundlePath = Bundle.main.bundleURL.path let port = GatewayEnvironment.gatewayPort() self.appendLog("[gateway] enabling launchd job (\(gatewayLaunchdLabel)) on port \(port)\n") @@ -307,9 +337,10 @@ final class GatewayProcessManager { while Date() < deadline { if !self.desiredActive { return } do { - _ = try await GatewayConnection.shared.requestRaw(method: .health, timeoutMs: 1500) + _ = try await self.connection.requestRaw(method: .health, timeoutMs: 1500) let instance = await PortGuardian.shared.describe(port: port) let details = instance.map { "pid \($0.pid)" } + self.clearLastFailure() self.status = .running(details: details) self.logger.info("gateway started details=\(details ?? "ok")") self.refreshControlChannelIfNeeded(reason: "gateway started") @@ -349,7 +380,8 @@ final class GatewayProcessManager { while Date() < deadline { if !self.desiredActive { return false } do { - _ = try await GatewayConnection.shared.requestRaw(method: .health, timeoutMs: 1500) + _ = try await self.connection.requestRaw(method: .health, timeoutMs: 1500) + self.clearLastFailure() return true } catch { try? await Task.sleep(nanoseconds: 300_000_000) @@ -362,7 +394,7 @@ final class GatewayProcessManager { func clearLog() { self.log = "" - try? FileManager.default.removeItem(atPath: GatewayLaunchAgentManager.launchdGatewayLogPath()) + try? FileManager().removeItem(atPath: GatewayLaunchAgentManager.launchdGatewayLogPath()) self.logger.debug("gateway log cleared") } @@ -375,10 +407,26 @@ final class GatewayProcessManager { } private nonisolated static func readGatewayLog(path: String, limit: Int) -> String { - guard FileManager.default.fileExists(atPath: path) else { return "" } + guard FileManager().fileExists(atPath: path) else { return "" } guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return "" } let text = String(data: data, encoding: .utf8) ?? "" if text.count <= limit { return text } return String(text.suffix(limit)) } } + +#if DEBUG +extension GatewayProcessManager { + func setTestingConnection(_ connection: GatewayConnection?) { + self.testingConnection = connection + } + + func setTestingDesiredActive(_ active: Bool) { + self.desiredActive = active + } + + func setTestingLastFailureReason(_ reason: String?) { + self.lastFailureReason = reason + } +} +#endif diff --git a/apps/macos/Sources/Clawdbot/GatewayRemoteConfig.swift b/apps/macos/Sources/Clawdbot/GatewayRemoteConfig.swift new file mode 100644 index 000000000..0b8ab3515 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/GatewayRemoteConfig.swift @@ -0,0 +1,64 @@ +import Foundation + +enum GatewayRemoteConfig { + static func resolveTransport(root: [String: Any]) -> AppState.RemoteTransport { + guard let gateway = root["gateway"] as? [String: Any], + let remote = gateway["remote"] as? [String: Any], + let raw = remote["transport"] as? String + else { + return .ssh + } + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + return trimmed == AppState.RemoteTransport.direct.rawValue ? .direct : .ssh + } + + static func resolveUrlString(root: [String: Any]) -> String? { + guard let gateway = root["gateway"] as? [String: Any], + let remote = gateway["remote"] as? [String: Any], + let urlRaw = remote["url"] as? String + else { + return nil + } + let trimmed = urlRaw.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } + + static func resolveGatewayUrl(root: [String: Any]) -> URL? { + guard let raw = self.resolveUrlString(root: root) else { return nil } + return self.normalizeGatewayUrl(raw) + } + + static func normalizeGatewayUrlString(_ raw: String) -> String? { + self.normalizeGatewayUrl(raw)?.absoluteString + } + + static func normalizeGatewayUrl(_ raw: String) -> URL? { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, let url = URL(string: trimmed) else { return nil } + let scheme = url.scheme?.lowercased() ?? "" + guard scheme == "ws" || scheme == "wss" else { return nil } + let host = url.host?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + guard !host.isEmpty else { return nil } + if scheme == "ws", url.port == nil { + guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { + return url + } + components.port = 18789 + return components.url + } + return url + } + + static func defaultPort(for url: URL) -> Int? { + if let port = url.port { return port } + let scheme = url.scheme?.lowercased() ?? "" + switch scheme { + case "wss": + return 443 + case "ws": + return 18789 + default: + return nil + } + } +} diff --git a/apps/macos/Sources/Clawdbot/GeneralSettings.swift b/apps/macos/Sources/Clawdbot/GeneralSettings.swift index 5a5dc05d8..18dd423a2 100644 --- a/apps/macos/Sources/Clawdbot/GeneralSettings.swift +++ b/apps/macos/Sources/Clawdbot/GeneralSettings.swift @@ -2,52 +2,26 @@ import AppKit import ClawdbotDiscovery import ClawdbotIPC import ClawdbotKit -import CoreLocation import Observation import SwiftUI struct GeneralSettings: View { @Bindable var state: AppState @AppStorage(cameraEnabledKey) private var cameraEnabled: Bool = false - @AppStorage(locationModeKey) private var locationModeRaw: String = ClawdbotLocationMode.off.rawValue - @AppStorage(locationPreciseKey) private var locationPreciseEnabled: Bool = true private let healthStore = HealthStore.shared private let gatewayManager = GatewayProcessManager.shared @State private var gatewayDiscovery = GatewayDiscoveryModel( localDisplayName: InstanceIdentity.displayName) - @State private var isInstallingCLI = false - @State private var cliStatus: String? - @State private var cliInstalled = false - @State private var cliInstallLocation: String? @State private var gatewayStatus: GatewayEnvironmentStatus = .checking @State private var remoteStatus: RemoteStatus = .idle @State private var showRemoteAdvanced = false private let isPreview = ProcessInfo.processInfo.isPreview private var isNixMode: Bool { ProcessInfo.processInfo.isNixMode } - @State private var lastLocationModeRaw: String = ClawdbotLocationMode.off.rawValue + private var remoteLabelWidth: CGFloat { 88 } var body: some View { ScrollView(.vertical) { VStack(alignment: .leading, spacing: 18) { - if !self.state.onboardingSeen { - Button { - DebugActions.restartOnboarding() - } label: { - HStack(spacing: 8) { - Label("Complete onboarding to finish setup", systemImage: "arrow.counterclockwise") - .font(.callout.weight(.semibold)) - .foregroundStyle(Color.accentColor) - Spacer(minLength: 0) - Image(systemName: "chevron.right") - .font(.caption.weight(.semibold)) - .foregroundStyle(.tertiary) - } - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .padding(.bottom, 2) - } - VStack(alignment: .leading, spacing: 12) { SettingsToggleRow( title: "Clawdbot active", @@ -83,49 +57,6 @@ struct GeneralSettings: View { subtitle: "Allow the agent to capture a photo or short video via the built-in camera.", binding: self.$cameraEnabled) - VStack(alignment: .leading, spacing: 6) { - Text("Node Run Commands") - .font(.body) - - Picker("", selection: self.$state.systemRunPolicy) { - ForEach(SystemRunPolicy.allCases) { policy in - Text(policy.title).tag(policy) - } - } - .labelsHidden() - .pickerStyle(.menu) - - Text(""" - Controls remote command execution on this Mac when it is paired as a node. \ - "Always Ask" prompts on each command; "Always Allow" runs without prompts; \ - "Never" disables `system.run`. - """) - .font(.footnote) - .foregroundStyle(.tertiary) - .fixedSize(horizontal: false, vertical: true) - } - - VStack(alignment: .leading, spacing: 6) { - Text("Location Access") - .font(.body) - - Picker("", selection: self.$locationModeRaw) { - Text("Off").tag(ClawdbotLocationMode.off.rawValue) - Text("While Using").tag(ClawdbotLocationMode.whileUsing.rawValue) - Text("Always").tag(ClawdbotLocationMode.always.rawValue) - } - .labelsHidden() - .pickerStyle(.menu) - - Toggle("Precise Location", isOn: self.$locationPreciseEnabled) - .disabled(self.locationMode == .off) - - Text("Always may require System Settings to approve background location.") - .font(.footnote) - .foregroundStyle(.tertiary) - .fixedSize(horizontal: false, vertical: true) - } - SettingsToggleRow( title: "Enable Peekaboo Bridge", subtitle: "Allow signed tools (e.g. `peekaboo`) to drive UI automation via PeekabooBridge.", @@ -150,29 +81,13 @@ struct GeneralSettings: View { } .onAppear { guard !self.isPreview else { return } - self.refreshCLIStatus() self.refreshGatewayStatus() - self.lastLocationModeRaw = self.locationModeRaw } .onChange(of: self.state.canvasEnabled) { _, enabled in if !enabled { CanvasManager.shared.hideAll() } } - .onChange(of: self.locationModeRaw) { _, newValue in - let previous = self.lastLocationModeRaw - self.lastLocationModeRaw = newValue - guard let mode = ClawdbotLocationMode(rawValue: newValue) else { return } - Task { - let granted = await self.requestLocationAuthorization(mode: mode) - if !granted { - await MainActor.run { - self.locationModeRaw = previous - self.lastLocationModeRaw = previous - } - } - } - } } private var activeBinding: Binding { @@ -181,39 +96,20 @@ struct GeneralSettings: View { set: { self.state.isPaused = !$0 }) } - private var locationMode: ClawdbotLocationMode { - ClawdbotLocationMode(rawValue: self.locationModeRaw) ?? .off - } - - private func requestLocationAuthorization(mode: ClawdbotLocationMode) async -> Bool { - guard mode != .off else { return true } - guard CLLocationManager.locationServicesEnabled() else { - await MainActor.run { LocationPermissionHelper.openSettings() } - return false - } - - let status = CLLocationManager().authorizationStatus - let requireAlways = mode == .always - if PermissionManager.isLocationAuthorized(status: status, requireAlways: requireAlways) { - return true - } - let updated = await LocationPermissionRequester.shared.request(always: requireAlways) - return PermissionManager.isLocationAuthorized(status: updated, requireAlways: requireAlways) - } - private var connectionSection: some View { VStack(alignment: .leading, spacing: 10) { Text("Clawdbot runs") .font(.title3.weight(.semibold)) .frame(maxWidth: .infinity, alignment: .leading) - Picker("", selection: self.$state.connectionMode) { + Picker("Mode", selection: self.$state.connectionMode) { Text("Not configured").tag(AppState.ConnectionMode.unconfigured) Text("Local (this Mac)").tag(AppState.ConnectionMode.local) - Text("Remote over SSH").tag(AppState.ConnectionMode.remote) + Text("Remote (another host)").tag(AppState.ConnectionMode.remote) } - .pickerStyle(.segmented) - .frame(width: 380, alignment: .leading) + .pickerStyle(.menu) + .labelsHidden() + .frame(width: 260, alignment: .leading) if self.state.connectionMode == .unconfigured { Text("Pick Local or Remote to start the Gateway.") @@ -236,67 +132,56 @@ struct GeneralSettings: View { if self.state.connectionMode == .remote { self.remoteCard } - - self.cliInstaller } } private var remoteCard: some View { VStack(alignment: .leading, spacing: 10) { - HStack(alignment: .center, spacing: 10) { - Text("SSH") - .font(.callout.weight(.semibold)) - .frame(width: 48, alignment: .leading) - TextField("user@host[:22]", text: self.$state.remoteTarget) - .textFieldStyle(.roundedBorder) - .frame(maxWidth: .infinity) - Button { - Task { await self.testRemote() } - } label: { - if self.remoteStatus == .checking { - ProgressView().controlSize(.small) - } else { - Text("Test remote") - } - } - .buttonStyle(.borderedProminent) - .disabled(self.remoteStatus == .checking || self.state.remoteTarget - .trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + self.remoteTransportRow + + if self.state.remoteTransport == .ssh { + self.remoteSshRow + } else { + self.remoteDirectRow } GatewayDiscoveryInlineList( discovery: self.gatewayDiscovery, - currentTarget: self.state.remoteTarget) + currentTarget: self.state.remoteTarget, + currentUrl: self.state.remoteUrl, + transport: self.state.remoteTransport) { gateway in self.applyDiscoveredGateway(gateway) } - .padding(.leading, 58) + .padding(.leading, self.remoteLabelWidth + 10) self.remoteStatusView - .padding(.leading, 58) + .padding(.leading, self.remoteLabelWidth + 10) - DisclosureGroup(isExpanded: self.$showRemoteAdvanced) { - VStack(alignment: .leading, spacing: 8) { - LabeledContent("Identity file") { - TextField("/Users/you/.ssh/id_ed25519", text: self.$state.remoteIdentity) - .textFieldStyle(.roundedBorder) - .frame(width: 280) - } - LabeledContent("Project root") { - TextField("/home/you/Projects/clawdbot", text: self.$state.remoteProjectRoot) - .textFieldStyle(.roundedBorder) - .frame(width: 280) - } - LabeledContent("CLI path") { - TextField("/Applications/Clawdbot.app/.../clawdbot", text: self.$state.remoteCliPath) - .textFieldStyle(.roundedBorder) - .frame(width: 280) + if self.state.remoteTransport == .ssh { + DisclosureGroup(isExpanded: self.$showRemoteAdvanced) { + VStack(alignment: .leading, spacing: 8) { + LabeledContent("Identity file") { + TextField("/Users/you/.ssh/id_ed25519", text: self.$state.remoteIdentity) + .textFieldStyle(.roundedBorder) + .frame(width: 280) + } + LabeledContent("Project root") { + TextField("/home/you/Projects/clawdbot", text: self.$state.remoteProjectRoot) + .textFieldStyle(.roundedBorder) + .frame(width: 280) + } + LabeledContent("CLI path") { + TextField("/Applications/Clawdbot.app/.../clawdbot", text: self.$state.remoteCliPath) + .textFieldStyle(.roundedBorder) + .frame(width: 280) + } } + .padding(.top, 4) + } label: { + Text("Advanced") + .font(.callout.weight(.semibold)) } - .padding(.top, 4) - } label: { - Text("Advanced") - .font(.callout.weight(.semibold)) } // Diagnostics @@ -319,18 +204,96 @@ struct GeneralSettings: View { .font(.caption) .foregroundStyle(.secondary) } + if let authLabel = ControlChannel.shared.authSourceLabel { + Text(authLabel) + .font(.caption) + .foregroundStyle(.secondary) + } } - Text("Tip: enable Tailscale for stable remote access.") - .font(.footnote) - .foregroundStyle(.secondary) - .lineLimit(1) + if self.state.remoteTransport == .ssh { + Text("Tip: enable Tailscale for stable remote access.") + .font(.footnote) + .foregroundStyle(.secondary) + .lineLimit(1) + } else { + Text("Tip: use Tailscale Serve so the gateway has a valid HTTPS cert.") + .font(.footnote) + .foregroundStyle(.secondary) + .lineLimit(2) + } } .transition(.opacity) .onAppear { self.gatewayDiscovery.start() } .onDisappear { self.gatewayDiscovery.stop() } } + private var remoteTransportRow: some View { + HStack(alignment: .center, spacing: 10) { + Text("Transport") + .font(.callout.weight(.semibold)) + .frame(width: self.remoteLabelWidth, alignment: .leading) + Picker("Transport", selection: self.$state.remoteTransport) { + Text("SSH tunnel").tag(AppState.RemoteTransport.ssh) + Text("Direct (ws/wss)").tag(AppState.RemoteTransport.direct) + } + .pickerStyle(.segmented) + .frame(maxWidth: 320) + } + } + + private var remoteSshRow: some View { + HStack(alignment: .center, spacing: 10) { + Text("SSH target") + .font(.callout.weight(.semibold)) + .frame(width: self.remoteLabelWidth, alignment: .leading) + TextField("user@host[:22]", text: self.$state.remoteTarget) + .textFieldStyle(.roundedBorder) + .frame(maxWidth: .infinity) + Button { + Task { await self.testRemote() } + } label: { + if self.remoteStatus == .checking { + ProgressView().controlSize(.small) + } else { + Text("Test remote") + } + } + .buttonStyle(.borderedProminent) + .disabled(self.remoteStatus == .checking || self.state.remoteTarget + .trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + + private var remoteDirectRow: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(alignment: .center, spacing: 10) { + Text("Gateway") + .font(.callout.weight(.semibold)) + .frame(width: self.remoteLabelWidth, alignment: .leading) + TextField("wss://gateway.example.ts.net", text: self.$state.remoteUrl) + .textFieldStyle(.roundedBorder) + .frame(maxWidth: .infinity) + Button { + Task { await self.testRemote() } + } label: { + if self.remoteStatus == .checking { + ProgressView().controlSize(.small) + } else { + Text("Test remote") + } + } + .buttonStyle(.borderedProminent) + .disabled(self.remoteStatus == .checking || self.state.remoteUrl + .trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + Text("Direct mode requires a ws:// or wss:// URL (Tailscale Serve uses wss://).") + .font(.caption) + .foregroundStyle(.secondary) + .padding(.leading, self.remoteLabelWidth + 10) + } + } + private var controlStatusLine: String { switch ControlChannel.shared.state { case .connected: "Connected" @@ -366,59 +329,6 @@ struct GeneralSettings: View { return message == self.controlStatusLine } - private var cliInstaller: some View { - VStack(alignment: .leading, spacing: 8) { - HStack(spacing: 10) { - Button { - Task { await self.installCLI() } - } label: { - let title = self.cliInstalled ? "Reinstall CLI" : "Install CLI" - ZStack { - Text(title) - .opacity(self.isInstallingCLI ? 0 : 1) - if self.isInstallingCLI { - ProgressView() - .controlSize(.mini) - } - } - .frame(minWidth: 150) - } - .disabled(self.isInstallingCLI) - - if self.isInstallingCLI { - Text("Working...") - .font(.callout) - .foregroundStyle(.secondary) - } else if self.cliInstalled { - Label("Installed", systemImage: "checkmark.circle.fill") - .font(.callout) - .foregroundStyle(.secondary) - } else { - Text("Not installed") - .font(.callout) - .foregroundStyle(.secondary) - } - } - - if let status = cliStatus { - Text(status) - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(2) - } else if let installLocation = self.cliInstallLocation { - Text("Found at \(installLocation)") - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(2) - } else { - Text("Installs a user-space Node 22+ runtime and the CLI (no Homebrew).") - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(2) - } - } - } - private var gatewayInstallerCard: some View { VStack(alignment: .leading, spacing: 8) { HStack(spacing: 10) { @@ -474,22 +384,6 @@ struct GeneralSettings: View { .cornerRadius(10) } - private func installCLI() async { - guard !self.isInstallingCLI else { return } - self.isInstallingCLI = true - defer { isInstallingCLI = false } - await CLIInstaller.install { status in - self.cliStatus = status - self.refreshCLIStatus() - } - } - - private func refreshCLIStatus() { - let installLocation = CLIInstaller.installedLocation() - self.cliInstallLocation = installLocation - self.cliInstalled = installLocation != nil - } - private func refreshGatewayStatus() { Task { let status = await Task.detached(priority: .utility) { @@ -629,24 +523,36 @@ extension GeneralSettings { func testRemote() async { self.remoteStatus = .checking let settings = CommandResolver.connectionSettings() - guard !settings.target.isEmpty else { - self.remoteStatus = .failed("Set an SSH target first") - return + if self.state.remoteTransport == .direct { + let trimmedUrl = self.state.remoteUrl.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedUrl.isEmpty else { + self.remoteStatus = .failed("Set a gateway URL first") + return + } + guard Self.isValidWsUrl(trimmedUrl) else { + self.remoteStatus = .failed("Gateway URL must start with ws:// or wss://") + return + } + } else { + guard !settings.target.isEmpty else { + self.remoteStatus = .failed("Set an SSH target first") + return + } + + // Step 1: basic SSH reachability check + let sshResult = await ShellExecutor.run( + command: Self.sshCheckCommand(target: settings.target, identity: settings.identity), + cwd: nil, + env: nil, + timeout: 8) + + guard sshResult.ok else { + self.remoteStatus = .failed(self.formatSSHFailure(sshResult, target: settings.target)) + return + } } - // Step 1: basic SSH reachability check - let sshResult = await ShellExecutor.run( - command: Self.sshCheckCommand(target: settings.target, identity: settings.identity), - cwd: nil, - env: nil, - timeout: 8) - - guard sshResult.ok else { - self.remoteStatus = .failed(self.formatSSHFailure(sshResult, target: settings.target)) - return - } - - // Step 2: control channel health over tunnel + // Step 2: control channel health check let originalMode = AppStateStore.shared.connectionMode do { try await ControlChannel.shared.configure(mode: .remote( @@ -673,6 +579,14 @@ extension GeneralSettings { } } + private static func isValidWsUrl(_ raw: String) -> Bool { + guard let url = URL(string: raw.trimmingCharacters(in: .whitespacesAndNewlines)) else { return false } + let scheme = url.scheme?.lowercased() ?? "" + guard scheme == "ws" || scheme == "wss" else { return false } + let host = url.host?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return !host.isEmpty + } + private static func sshCheckCommand(target: String, identity: String) -> [String] { var args: [String] = [ "/usr/bin/ssh", @@ -736,17 +650,23 @@ extension GeneralSettings { } private func applyDiscoveredGateway(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) { - MacNodeModeCoordinator.shared.setPreferredBridgeStableID(gateway.stableID) + MacNodeModeCoordinator.shared.setPreferredGatewayStableID(gateway.stableID) let host = gateway.tailnetDns ?? gateway.lanHost guard let host else { return } let user = NSUserName() - self.state.remoteTarget = GatewayDiscoveryModel.buildSSHTarget( - user: user, - host: host, - port: gateway.sshPort) - self.state.remoteCliPath = gateway.cliPath ?? "" - ClawdbotConfigFile.setRemoteGatewayUrl(host: host, port: gateway.gatewayPort) + if self.state.remoteTransport == .direct { + if let url = GatewayDiscoveryHelpers.directUrl(for: gateway) { + self.state.remoteUrl = url + } + } else { + self.state.remoteTarget = GatewayDiscoveryModel.buildSSHTarget( + user: user, + host: host, + port: gateway.sshPort) + self.state.remoteCliPath = gateway.cliPath ?? "" + ClawdbotConfigFile.setRemoteGatewayUrl(host: host, port: gateway.gatewayPort) + } } } @@ -769,7 +689,9 @@ extension GeneralSettings { static func exerciseForTesting() { let state = AppState(preview: true) state.connectionMode = .remote + state.remoteTransport = .ssh state.remoteTarget = "user@host:2222" + state.remoteUrl = "wss://gateway.example.ts.net" state.remoteIdentity = "/tmp/id_ed25519" state.remoteProjectRoot = "/tmp/clawdbot" state.remoteCliPath = "/tmp/clawdbot" @@ -783,9 +705,6 @@ extension GeneralSettings { message: "Gateway ready") view.remoteStatus = .failed("SSH failed") view.showRemoteAdvanced = true - view.cliInstalled = true - view.cliInstallLocation = "/usr/local/bin/clawdbot" - view.cliStatus = "Installed" _ = view.body state.connectionMode = .unconfigured diff --git a/apps/macos/Sources/Clawdbot/HealthStore.swift b/apps/macos/Sources/Clawdbot/HealthStore.swift index 668056e00..44ebcc053 100644 --- a/apps/macos/Sources/Clawdbot/HealthStore.swift +++ b/apps/macos/Sources/Clawdbot/HealthStore.swift @@ -166,6 +166,11 @@ final class HealthStore { _ snap: HealthSnapshot) -> (id: String, summary: HealthSnapshot.ChannelSummary)? { let order = snap.channelOrder ?? Array(snap.channels.keys) + for id in order { + if let summary = snap.channels[id], summary.linked == true { + return (id: id, summary: summary) + } + } for id in order { if let summary = snap.channels[id], summary.linked != nil { return (id: id, summary: summary) @@ -235,8 +240,8 @@ final class HealthStore { let lower = error.lowercased() if lower.contains("connection refused") { let port = GatewayEnvironment.gatewayPort() - return "The gateway control port (127.0.0.1:\(port)) isn’t listening — " + - "restart Clawdbot to bring it back." + let host = GatewayConnectivityCoordinator.shared.localEndpointHostLabel ?? "127.0.0.1:\(port)" + return "The gateway control port (\(host)) isn’t listening — restart Clawdbot to bring it back." } if lower.contains("timeout") { return "Timed out waiting for the control server; the gateway may be crashed or still starting." diff --git a/apps/macos/Sources/Clawdbot/InstanceIdentity.swift b/apps/macos/Sources/Clawdbot/InstanceIdentity.swift deleted file mode 100644 index 2bd2e6ea6..000000000 --- a/apps/macos/Sources/Clawdbot/InstanceIdentity.swift +++ /dev/null @@ -1,47 +0,0 @@ -import Darwin -import Foundation - -enum InstanceIdentity { - private static let suiteName = "com.clawdbot.shared" - private static let instanceIdKey = "instanceId" - - private static var defaults: UserDefaults { - UserDefaults(suiteName: suiteName) ?? .standard - } - - static let instanceId: String = { - let defaults = Self.defaults - if let existing = defaults.string(forKey: instanceIdKey)? - .trimmingCharacters(in: .whitespacesAndNewlines), - !existing.isEmpty - { - return existing - } - - let id = UUID().uuidString.lowercased() - defaults.set(id, forKey: instanceIdKey) - return id - }() - - static let displayName: String = { - if let name = Host.current().localizedName?.trimmingCharacters(in: .whitespacesAndNewlines), - !name.isEmpty - { - return name - } - return "clawdbot" - }() - - static let modelIdentifier: String? = { - var size = 0 - guard sysctlbyname("hw.model", nil, &size, nil, 0) == 0, size > 1 else { return nil } - - var buffer = [CChar](repeating: 0, count: size) - guard sysctlbyname("hw.model", &buffer, &size, nil, 0) == 0 else { return nil } - - let bytes = buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) } - guard let raw = String(bytes: bytes, encoding: .utf8) else { return nil } - let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? nil : trimmed - }() -} diff --git a/apps/macos/Sources/Clawdbot/InstancesStore.swift b/apps/macos/Sources/Clawdbot/InstancesStore.swift index 196737f07..c12f8c2e0 100644 --- a/apps/macos/Sources/Clawdbot/InstancesStore.swift +++ b/apps/macos/Sources/Clawdbot/InstancesStore.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import ClawdbotProtocol import Cocoa import Foundation diff --git a/apps/macos/Sources/Clawdbot/LaunchAgentManager.swift b/apps/macos/Sources/Clawdbot/LaunchAgentManager.swift index 8c525129a..ca967a133 100644 --- a/apps/macos/Sources/Clawdbot/LaunchAgentManager.swift +++ b/apps/macos/Sources/Clawdbot/LaunchAgentManager.swift @@ -3,17 +3,17 @@ import Foundation enum LaunchAgentManager { private static let legacyLaunchdLabel = "com.steipete.clawdbot" private static var plistURL: URL { - FileManager.default.homeDirectoryForCurrentUser + FileManager().homeDirectoryForCurrentUser .appendingPathComponent("Library/LaunchAgents/com.clawdbot.mac.plist") } private static var legacyPlistURL: URL { - FileManager.default.homeDirectoryForCurrentUser + FileManager().homeDirectoryForCurrentUser .appendingPathComponent("Library/LaunchAgents/\(legacyLaunchdLabel).plist") } static func status() async -> Bool { - guard FileManager.default.fileExists(atPath: self.plistURL.path) else { return false } + guard FileManager().fileExists(atPath: self.plistURL.path) else { return false } let result = await self.runLaunchctl(["print", "gui/\(getuid())/\(launchdLabel)"]) return result == 0 } @@ -21,7 +21,7 @@ enum LaunchAgentManager { static func set(enabled: Bool, bundlePath: String) async { if enabled { _ = await self.runLaunchctl(["bootout", "gui/\(getuid())/\(self.legacyLaunchdLabel)"]) - try? FileManager.default.removeItem(at: self.legacyPlistURL) + try? FileManager().removeItem(at: self.legacyPlistURL) self.writePlist(bundlePath: bundlePath) _ = await self.runLaunchctl(["bootout", "gui/\(getuid())/\(launchdLabel)"]) _ = await self.runLaunchctl(["bootstrap", "gui/\(getuid())", self.plistURL.path]) @@ -29,7 +29,7 @@ enum LaunchAgentManager { } else { // Disable autostart going forward but leave the current app running. // bootout would terminate the launchd job immediately (and crash the app if launched via agent). - try? FileManager.default.removeItem(at: self.plistURL) + try? FileManager().removeItem(at: self.plistURL) } } @@ -46,7 +46,7 @@ enum LaunchAgentManager { \(bundlePath)/Contents/MacOS/Clawdbot WorkingDirectory - \(FileManager.default.homeDirectoryForCurrentUser.path) + \(FileManager().homeDirectoryForCurrentUser.path) RunAtLoad KeepAlive @@ -72,11 +72,11 @@ enum LaunchAgentManager { let process = Process() process.launchPath = "/bin/launchctl" process.arguments = args - process.standardOutput = Pipe() - process.standardError = Pipe() + let pipe = Pipe() + process.standardOutput = pipe + process.standardError = pipe do { - try process.run() - process.waitUntilExit() + _ = try process.runAndReadToEnd(from: pipe) return process.terminationStatus } catch { return -1 diff --git a/apps/macos/Sources/Clawdbot/Launchctl.swift b/apps/macos/Sources/Clawdbot/Launchctl.swift index 74690f7b9..4059a1e20 100644 --- a/apps/macos/Sources/Clawdbot/Launchctl.swift +++ b/apps/macos/Sources/Clawdbot/Launchctl.swift @@ -16,9 +16,7 @@ enum Launchctl { process.standardOutput = pipe process.standardError = pipe do { - try process.run() - process.waitUntilExit() - let data = pipe.fileHandleForReading.readToEndSafely() + let data = try process.runAndReadToEnd(from: pipe) let output = String(data: data, encoding: .utf8) ?? "" return Result(status: process.terminationStatus, output: output) } catch { diff --git a/apps/macos/Sources/Clawdbot/LogLocator.swift b/apps/macos/Sources/Clawdbot/LogLocator.swift index 8714f7d0c..0ce7eea2f 100644 --- a/apps/macos/Sources/Clawdbot/LogLocator.swift +++ b/apps/macos/Sources/Clawdbot/LogLocator.swift @@ -18,7 +18,7 @@ enum LogLocator { } private static func ensureLogDirExists() { - try? FileManager.default.createDirectory(at: self.logDir, withIntermediateDirectories: true) + try? FileManager().createDirectory(at: self.logDir, withIntermediateDirectories: true) } private static func modificationDate(for url: URL) -> Date { @@ -28,7 +28,7 @@ enum LogLocator { /// Returns the newest log file under /tmp/clawdbot/ (rolling or stdout), or nil if none exist. static func bestLogFile() -> URL? { self.ensureLogDirExists() - let fm = FileManager.default + let fm = FileManager() let files = (try? fm.contentsOfDirectory( at: self.logDir, includingPropertiesForKeys: [.contentModificationDateKey], diff --git a/apps/macos/Sources/Clawdbot/MacNodeConfigFile.swift b/apps/macos/Sources/Clawdbot/MacNodeConfigFile.swift deleted file mode 100644 index 7b5f9934f..000000000 --- a/apps/macos/Sources/Clawdbot/MacNodeConfigFile.swift +++ /dev/null @@ -1,81 +0,0 @@ -import Foundation -import OSLog - -enum MacNodeConfigFile { - private static let logger = Logger(subsystem: "com.clawdbot", category: "mac-node-config") - - static func url() -> URL { - ClawdbotPaths.stateDirURL.appendingPathComponent("macos-node.json") - } - - static func loadDict() -> [String: Any] { - let url = self.url() - guard FileManager.default.fileExists(atPath: url.path) else { return [:] } - do { - let data = try Data(contentsOf: url) - guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { - self.logger.warning("mac node config JSON root invalid") - return [:] - } - return root - } catch { - self.logger.warning("mac node config read failed: \(error.localizedDescription, privacy: .public)") - return [:] - } - } - - static func saveDict(_ dict: [String: Any]) { - do { - let data = try JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted, .sortedKeys]) - let url = self.url() - try FileManager.default.createDirectory( - at: url.deletingLastPathComponent(), - withIntermediateDirectories: true) - try data.write(to: url, options: [.atomic]) - try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) - } catch { - self.logger.error("mac node config save failed: \(error.localizedDescription, privacy: .public)") - } - } - - static func systemRunPolicy() -> SystemRunPolicy? { - let root = self.loadDict() - let systemRun = root["systemRun"] as? [String: Any] - let raw = systemRun?["policy"] as? String - guard let raw, let policy = SystemRunPolicy(rawValue: raw) else { return nil } - return policy - } - - static func setSystemRunPolicy(_ policy: SystemRunPolicy) { - var root = self.loadDict() - var systemRun = root["systemRun"] as? [String: Any] ?? [:] - systemRun["policy"] = policy.rawValue - root["systemRun"] = systemRun - self.saveDict(root) - } - - static func systemRunAllowlist() -> [String]? { - let root = self.loadDict() - let systemRun = root["systemRun"] as? [String: Any] - return systemRun?["allowlist"] as? [String] - } - - static func setSystemRunAllowlist(_ allowlist: [String]) { - let cleaned = allowlist - .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty } - var root = self.loadDict() - var systemRun = root["systemRun"] as? [String: Any] ?? [:] - if cleaned.isEmpty { - systemRun.removeValue(forKey: "allowlist") - } else { - systemRun["allowlist"] = cleaned - } - if systemRun.isEmpty { - root.removeValue(forKey: "systemRun") - } else { - root["systemRun"] = systemRun - } - self.saveDict(root) - } -} diff --git a/apps/macos/Sources/Clawdbot/MenuBar.swift b/apps/macos/Sources/Clawdbot/MenuBar.swift index 696322648..26a467e91 100644 --- a/apps/macos/Sources/Clawdbot/MenuBar.swift +++ b/apps/macos/Sources/Clawdbot/MenuBar.swift @@ -3,6 +3,7 @@ import Darwin import Foundation import MenuBarExtraAccess import Observation +import OSLog import Security import SwiftUI @@ -10,9 +11,11 @@ import SwiftUI struct ClawdbotApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) private var delegate @State private var state: AppState + private static let logger = Logger(subsystem: "com.clawdbot", category: "app") private let gatewayManager = GatewayProcessManager.shared private let controlChannel = ControlChannel.shared private let activityStore = WorkActivityStore.shared + private let connectivityCoordinator = GatewayConnectivityCoordinator.shared @State private var statusItem: NSStatusItem? @State private var isMenuPresented = false @State private var isPanelVisible = false @@ -30,6 +33,7 @@ struct ClawdbotApp: App { init() { ClawdbotLogging.bootstrapIfNeeded() + Self.applyAttachOnlyOverrideIfNeeded() _state = State(initialValue: AppStateStore.shared) } @@ -90,6 +94,22 @@ struct ClawdbotApp: App { self.statusItem?.button?.appearsDisabled = paused || sleeping } + private static func applyAttachOnlyOverrideIfNeeded() { + let args = CommandLine.arguments + guard args.contains("--attach-only") || args.contains("--no-launchd") else { return } + if let error = GatewayLaunchAgentManager.setLaunchAgentWriteDisabled(true) { + Self.logger.error("attach-only flag failed: \(error, privacy: .public)") + return + } + Task { + _ = await GatewayLaunchAgentManager.set( + enabled: false, + bundlePath: Bundle.main.bundlePath, + port: GatewayEnvironment.gatewayPort()) + } + Self.logger.info("attach-only flag enabled") + } + private var isGatewaySleeping: Bool { if self.state.isPaused { return false } switch self.state.connectionMode { @@ -256,6 +276,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } TerminationSignalWatcher.shared.start() NodePairingApprovalPrompter.shared.start() + DevicePairingApprovalPrompter.shared.start() + ExecApprovalsPromptServer.shared.start() + ExecApprovalsGatewayPrompter.shared.start() MacNodeModeCoordinator.shared.start() VoiceWakeGlobalSettingsSync.shared.start() Task { PresenceReporter.shared.start() } @@ -280,6 +303,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillTerminate(_ notification: Notification) { PresenceReporter.shared.stop() NodePairingApprovalPrompter.shared.stop() + DevicePairingApprovalPrompter.shared.stop() + ExecApprovalsPromptServer.shared.stop() + ExecApprovalsGatewayPrompter.shared.stop() MacNodeModeCoordinator.shared.stop() TerminationSignalWatcher.shared.stop() VoiceWakeGlobalSettingsSync.shared.stop() diff --git a/apps/macos/Sources/Clawdbot/MenuContentView.swift b/apps/macos/Sources/Clawdbot/MenuContentView.swift index 34773bd8b..8dbeb8f44 100644 --- a/apps/macos/Sources/Clawdbot/MenuContentView.swift +++ b/apps/macos/Sources/Clawdbot/MenuContentView.swift @@ -15,6 +15,7 @@ struct MenuContent: View { private let controlChannel = ControlChannel.shared private let activityStore = WorkActivityStore.shared @Bindable private var pairingPrompter = NodePairingApprovalPrompter.shared + @Bindable private var devicePairingPrompter = DevicePairingApprovalPrompter.shared @Environment(\.openSettings) private var openSettings @State private var availableMics: [AudioInputDevice] = [] @State private var loadingMics = false @@ -31,10 +32,10 @@ struct MenuContent: View { self._updateStatus = Bindable(wrappedValue: updater?.updateStatus ?? UpdateStatus.disabled) } - private var systemRunPolicyBinding: Binding { + private var execApprovalModeBinding: Binding { Binding( - get: { self.state.systemRunPolicy }, - set: { self.state.systemRunPolicy = $0 }) + get: { self.state.execApprovalMode }, + set: { self.state.execApprovalMode = $0 }) } var body: some View { @@ -50,6 +51,13 @@ struct MenuContent: View { label: "Pairing approval pending (\(self.pairingPrompter.pendingCount))\(repairSuffix)", color: .orange) } + if self.devicePairingPrompter.pendingCount > 0 { + let repairCount = self.devicePairingPrompter.pendingRepairCount + let repairSuffix = repairCount > 0 ? " · \(repairCount) repair" : "" + self.statusLine( + label: "Device pairing pending (\(self.devicePairingPrompter.pendingCount))\(repairSuffix)", + color: .orange) + } } } .disabled(self.state.connectionMode == .unconfigured) @@ -74,12 +82,12 @@ struct MenuContent: View { Toggle(isOn: self.$cameraEnabled) { Label("Allow Camera", systemImage: "camera") } - Picker(selection: self.systemRunPolicyBinding) { - ForEach(SystemRunPolicy.allCases) { policy in - Text(policy.title).tag(policy) + Picker(selection: self.execApprovalModeBinding) { + ForEach(ExecApprovalQuickMode.allCases) { mode in + Text(mode.title).tag(mode) } } label: { - Label("Node Run Commands", systemImage: "terminal") + Label("Exec Approvals", systemImage: "terminal") } Toggle(isOn: Binding(get: { self.state.canvasEnabled }, set: { self.state.canvasEnabled = $0 })) { Label("Allow Canvas", systemImage: "rectangle.and.pencil.and.ellipsis") diff --git a/apps/macos/Sources/Clawdbot/MenuSessionsInjector.swift b/apps/macos/Sources/Clawdbot/MenuSessionsInjector.swift index 7092598fa..7ab9a64ca 100644 --- a/apps/macos/Sources/Clawdbot/MenuSessionsInjector.swift +++ b/apps/macos/Sources/Clawdbot/MenuSessionsInjector.swift @@ -1,4 +1,6 @@ import AppKit +import Foundation +import Observation import SwiftUI @MainActor @@ -14,9 +16,11 @@ final class MenuSessionsInjector: NSObject, NSMenuDelegate { private weak var statusItem: NSStatusItem? private var loadTask: Task? private var nodesLoadTask: Task? + private var previewTasks: [Task] = [] private var isMenuOpen = false private var lastKnownMenuWidth: CGFloat? private var menuOpenWidth: CGFloat? + private var isObservingControlChannel = false private var cachedSnapshot: SessionStoreSnapshot? private var cachedErrorText: String? @@ -26,6 +30,10 @@ final class MenuSessionsInjector: NSObject, NSMenuDelegate { private var cachedUsageErrorText: String? private var usageCacheUpdatedAt: Date? private let usageRefreshIntervalSeconds: TimeInterval = 30 + private var cachedCostSummary: GatewayCostUsageSummary? + private var cachedCostErrorText: String? + private var costCacheUpdatedAt: Date? + private let costRefreshIntervalSeconds: TimeInterval = 45 private let nodesStore = NodesStore.shared #if DEBUG private var testControlChannelConnected: Bool? @@ -45,6 +53,7 @@ final class MenuSessionsInjector: NSObject, NSMenuDelegate { self.loadTask = Task { await self.refreshCache(force: true) } } + self.startControlChannelObservation() self.nodesStore.start() } @@ -63,6 +72,7 @@ final class MenuSessionsInjector: NSObject, NSMenuDelegate { guard let self else { return } await self.refreshCache(force: forceRefresh) await self.refreshUsageCache(force: forceRefresh) + await self.refreshCostUsageCache(force: forceRefresh) await MainActor.run { guard self.isMenuOpen else { return } self.inject(into: menu) @@ -87,6 +97,51 @@ final class MenuSessionsInjector: NSObject, NSMenuDelegate { self.menuOpenWidth = nil self.loadTask?.cancel() self.nodesLoadTask?.cancel() + self.cancelPreviewTasks() + } + + private func startControlChannelObservation() { + guard !self.isObservingControlChannel else { return } + self.isObservingControlChannel = true + self.observeControlChannelState() + } + + private func observeControlChannelState() { + withObservationTracking { + _ = ControlChannel.shared.state + } onChange: { [weak self] in + Task { @MainActor [weak self] in + guard let self else { return } + self.handleControlChannelStateChange() + self.observeControlChannelState() + } + } + } + + private func handleControlChannelStateChange() { + guard self.isMenuOpen, let menu = self.statusItem?.menu else { return } + self.loadTask?.cancel() + self.loadTask = Task { [weak self, weak menu] in + guard let self, let menu else { return } + await self.refreshCache(force: true) + await self.refreshUsageCache(force: true) + await self.refreshCostUsageCache(force: true) + await MainActor.run { + guard self.isMenuOpen else { return } + self.inject(into: menu) + self.injectNodes(into: menu) + } + } + + self.nodesLoadTask?.cancel() + self.nodesLoadTask = Task { [weak self, weak menu] in + guard let self, let menu else { return } + await self.nodesStore.refresh() + await MainActor.run { + guard self.isMenuOpen else { return } + self.injectNodes(into: menu) + } + } } func menuNeedsUpdate(_ menu: NSMenu) { @@ -107,6 +162,7 @@ extension MenuSessionsInjector { private var mainSessionKey: String { WorkActivityStore.shared.mainSessionKey } private func inject(into menu: NSMenu) { + self.cancelPreviewTasks() // Remove any previous injected items. for item in menu.items where item.tag == self.tag { menu.removeItem(item) @@ -133,14 +189,23 @@ extension MenuSessionsInjector { if rhs.key == mainKey { return false } return (lhs.updatedAt ?? .distantPast) > (rhs.updatedAt ?? .distantPast) } + if !rows.isEmpty { + let previewKeys = rows.prefix(20).map(\.key) + let task = Task { + await SessionMenuPreviewLoader.prewarm(sessionKeys: previewKeys, maxItems: 10) + } + self.previewTasks.append(task) + } let headerItem = NSMenuItem() headerItem.tag = self.tag headerItem.isEnabled = false + let statusText = self + .cachedErrorText ?? (isConnected ? nil : self.controlChannelStatusText(for: channelState)) let hosted = self.makeHostedView( rootView: AnyView(MenuSessionsHeaderView( count: rows.count, - statusText: isConnected ? nil : self.controlChannelStatusText(for: channelState))), + statusText: statusText)), width: width, highlighted: false) headerItem.view = hosted @@ -197,6 +262,7 @@ extension MenuSessionsInjector { } cursor = self.insertUsageSection(into: menu, at: cursor, width: width) + cursor = self.insertCostUsageSection(into: menu, at: cursor, width: width) DispatchQueue.main.async { [weak self, weak headerView] in guard let self, let headerView else { return } @@ -280,9 +346,7 @@ extension MenuSessionsInjector { private func insertUsageSection(into menu: NSMenu, at cursor: Int, width: CGFloat) -> Int { let rows = self.usageRows - let errorText = self.cachedUsageErrorText - - if rows.isEmpty, errorText == nil { + if rows.isEmpty { return cursor } @@ -306,25 +370,6 @@ extension MenuSessionsInjector { menu.insertItem(headerItem, at: cursor) cursor += 1 - if let errorText = errorText?.nonEmpty, !rows.isEmpty { - menu.insertItem( - self.makeMessageItem( - text: errorText, - symbolName: "exclamationmark.triangle", - width: width, - maxLines: 2), - at: cursor) - cursor += 1 - } - - if rows.isEmpty { - menu.insertItem( - self.makeMessageItem(text: errorText ?? "No usage available", symbolName: "minus", width: width), - at: cursor) - cursor += 1 - return cursor - } - if let selectedProvider = self.selectedUsageProviderId, let primary = rows.first(where: { $0.providerId.lowercased() == selectedProvider }), rows.count > 1 @@ -362,6 +407,28 @@ extension MenuSessionsInjector { return cursor } + private func insertCostUsageSection(into menu: NSMenu, at cursor: Int, width: CGFloat) -> Int { + guard self.isControlChannelConnected else { return cursor } + guard let submenu = self.buildCostUsageSubmenu(width: width) else { return cursor } + var cursor = cursor + + if cursor > 0, !menu.items[cursor - 1].isSeparatorItem { + let separator = NSMenuItem.separator() + separator.tag = self.tag + menu.insertItem(separator, at: cursor) + cursor += 1 + } + + let item = NSMenuItem(title: "Usage cost (30 days)", action: nil, keyEquivalent: "") + item.tag = self.tag + item.isEnabled = true + item.image = NSImage(systemSymbolName: "chart.bar.xaxis", accessibilityDescription: nil) + item.submenu = submenu + menu.insertItem(item, at: cursor) + cursor += 1 + return cursor + } + private var selectedUsageProviderId: String? { guard let model = self.cachedSnapshot?.defaults.model.nonEmpty else { return nil } let trimmed = model.trimmingCharacters(in: .whitespacesAndNewlines) @@ -411,6 +478,36 @@ extension MenuSessionsInjector { } } + private func buildCostUsageSubmenu(width: CGFloat) -> NSMenu? { + if let error = self.cachedCostErrorText, !error.isEmpty, self.cachedCostSummary == nil { + let menu = NSMenu() + let item = NSMenuItem(title: error, action: nil, keyEquivalent: "") + item.isEnabled = false + menu.addItem(item) + return menu + } + + guard let summary = self.cachedCostSummary else { return nil } + guard !summary.daily.isEmpty else { return nil } + + let menu = NSMenu() + menu.delegate = self + + let chartView = CostUsageHistoryMenuView(summary: summary, width: width) + let hosting = NSHostingView(rootView: AnyView(chartView)) + let controller = NSHostingController(rootView: AnyView(chartView)) + let size = controller.sizeThatFits(in: CGSize(width: width, height: .greatestFiniteMagnitude)) + hosting.frame = NSRect(origin: .zero, size: NSSize(width: width, height: size.height)) + + let chartItem = NSMenuItem() + chartItem.view = hosting + chartItem.isEnabled = false + chartItem.representedObject = "costUsageChart" + menu.addItem(chartItem) + + return menu + } + private func gatewayEntry() -> NodeInfo? { let mode = AppStateStore.shared.connectionMode let isConnected = self.isControlChannelConnected @@ -421,15 +518,29 @@ extension MenuSessionsInjector { switch mode { case .remote: platform = "remote" - let target = AppStateStore.shared.remoteTarget - if let parsed = CommandResolver.parseSSHTarget(target) { - host = parsed.port == 22 ? parsed.host : "\(parsed.host):\(parsed.port)" + if AppStateStore.shared.remoteTransport == .direct { + let trimmedUrl = AppStateStore.shared.remoteUrl + .trimmingCharacters(in: .whitespacesAndNewlines) + if let url = URL(string: trimmedUrl), let urlHost = url.host, !urlHost.isEmpty { + if let port = url.port { + host = "\(urlHost):\(port)" + } else { + host = urlHost + } + } else { + host = trimmedUrl.nonEmpty + } } else { - host = target.nonEmpty + let target = AppStateStore.shared.remoteTarget + if let parsed = CommandResolver.parseSSHTarget(target) { + host = parsed.port == 22 ? parsed.host : "\(parsed.host):\(parsed.port)" + } else { + host = target.nonEmpty + } } case .local: platform = "local" - host = "127.0.0.1:\(port)" + host = GatewayConnectivityCoordinator.shared.localEndpointHostLabel ?? "127.0.0.1:\(port)" case .unconfigured: platform = nil host = nil @@ -440,6 +551,8 @@ extension MenuSessionsInjector { displayName: "Gateway", platform: platform, version: nil, + coreVersion: nil, + uiVersion: nil, deviceFamily: nil, modelIdentifier: nil, remoteIp: host, @@ -473,15 +586,46 @@ extension MenuSessionsInjector { item.tag = self.tag item.isEnabled = false let view = AnyView(SessionMenuPreviewView( - sessionKey: sessionKey, width: width, - maxItems: 10, maxLines: maxLines, - title: title)) - item.view = self.makeHostedView(rootView: view, width: width, highlighted: false) + title: title, + items: [], + status: .loading)) + let hosting = NSHostingView(rootView: view) + hosting.frame.size.width = max(1, width) + let size = hosting.fittingSize + hosting.frame = NSRect(origin: .zero, size: NSSize(width: width, height: size.height)) + item.view = hosting + + let task = Task { [weak hosting] in + let snapshot = await SessionMenuPreviewLoader.load(sessionKey: sessionKey, maxItems: 10) + guard !Task.isCancelled else { return } + await MainActor.run { + guard let hosting else { return } + let nextView = AnyView(SessionMenuPreviewView( + width: width, + maxLines: maxLines, + title: title, + items: snapshot.items, + status: snapshot.status)) + hosting.rootView = nextView + hosting.invalidateIntrinsicContentSize() + hosting.frame.size.width = max(1, width) + let size = hosting.fittingSize + hosting.frame.size.height = size.height + } + } + self.previewTasks.append(task) return item } + private func cancelPreviewTasks() { + for task in self.previewTasks { + task.cancel() + } + self.previewTasks.removeAll() + } + private func makeMessageItem(text: String, symbolName: String, width: CGFloat, maxLines: Int? = 2) -> NSMenuItem { let view = AnyView( HStack(alignment: .top, spacing: 8) { @@ -525,8 +669,11 @@ extension MenuSessionsInjector { } guard self.isControlChannelConnected else { - self.cachedSnapshot = nil - self.cachedErrorText = nil + if self.cachedSnapshot != nil { + self.cachedErrorText = "Gateway disconnected (showing cached)" + } else { + self.cachedErrorText = nil + } self.cacheUpdatedAt = Date() return } @@ -551,22 +698,40 @@ extension MenuSessionsInjector { } guard self.isControlChannelConnected else { - self.cachedUsageSummary = nil - self.cachedUsageErrorText = nil self.usageCacheUpdatedAt = Date() return } do { self.cachedUsageSummary = try await UsageLoader.loadSummary() - self.cachedUsageErrorText = nil - self.usageCacheUpdatedAt = Date() } catch { - if self.cachedUsageSummary == nil { - self.cachedUsageErrorText = self.compactUsageError(error) - } - self.usageCacheUpdatedAt = Date() + self.cachedUsageSummary = nil + self.cachedUsageErrorText = nil } + self.usageCacheUpdatedAt = Date() + } + + private func refreshCostUsageCache(force: Bool) async { + if !force, + let updated = self.costCacheUpdatedAt, + Date().timeIntervalSince(updated) < self.costRefreshIntervalSeconds + { + return + } + + guard self.isControlChannelConnected else { + self.costCacheUpdatedAt = Date() + return + } + + do { + self.cachedCostSummary = try await CostUsageLoader.loadSummary() + self.cachedCostErrorText = nil + } catch { + self.cachedCostSummary = nil + self.cachedCostErrorText = self.compactUsageError(error) + } + self.costCacheUpdatedAt = Date() } private func compactUsageError(_ error: Error) -> String { @@ -747,8 +912,8 @@ extension MenuSessionsInjector { menu.addItem(self.makeNodeCopyItem(label: "Platform", value: platform)) } - if let version = entry.version?.nonEmpty { - menu.addItem(self.makeNodeCopyItem(label: "Version", value: self.formatVersionLabel(version))) + if let version = NodeMenuEntryFormatter.detailRightVersion(entry)?.nonEmpty { + menu.addItem(self.makeNodeCopyItem(label: "Version", value: version)) } menu.addItem(self.makeNodeDetailItem(label: "Connected", value: entry.isConnected ? "Yes" : "No")) diff --git a/apps/macos/Sources/Clawdbot/ModelCatalogLoader.swift b/apps/macos/Sources/Clawdbot/ModelCatalogLoader.swift index bf55c564e..2f1c75fe6 100644 --- a/apps/macos/Sources/Clawdbot/ModelCatalogLoader.swift +++ b/apps/macos/Sources/Clawdbot/ModelCatalogLoader.swift @@ -2,14 +2,28 @@ import Foundation import JavaScriptCore enum ModelCatalogLoader { - static let defaultPath: String = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Projects/pi-mono/packages/ai/src/models.generated.ts").path + static var defaultPath: String { self.resolveDefaultPath() } private static let logger = Logger(subsystem: "com.clawdbot", category: "models") + private nonisolated static let appSupportDir: URL = { + let base = FileManager().urls(for: .applicationSupportDirectory, in: .userDomainMask).first! + return base.appendingPathComponent("Clawdbot", isDirectory: true) + }() + + private static var cachePath: URL { + self.appSupportDir.appendingPathComponent("model-catalog/models.generated.js", isDirectory: false) + } static func load(from path: String) async throws -> [ModelChoice] { let expanded = (path as NSString).expandingTildeInPath - self.logger.debug("model catalog load start file=\(URL(fileURLWithPath: expanded).lastPathComponent)") - let source = try String(contentsOfFile: expanded, encoding: .utf8) + guard let resolved = self.resolvePath(preferred: expanded) else { + self.logger.error("model catalog load failed: file not found") + throw NSError( + domain: "ModelCatalogLoader", + code: 1, + userInfo: [NSLocalizedDescriptionKey: "Model catalog file not found"]) + } + self.logger.debug("model catalog load start file=\(URL(fileURLWithPath: resolved.path).lastPathComponent)") + let source = try String(contentsOfFile: resolved.path, encoding: .utf8) let sanitized = self.sanitize(source: source) let ctx = JSContext() @@ -45,9 +59,82 @@ enum ModelCatalogLoader { return lhs.provider.localizedCaseInsensitiveCompare(rhs.provider) == .orderedAscending } self.logger.debug("model catalog loaded providers=\(rawModels.count) models=\(sorted.count)") + if resolved.shouldCache { + self.cacheCatalog(sourcePath: resolved.path) + } return sorted } + private static func resolveDefaultPath() -> String { + let cache = self.cachePath.path + if FileManager().isReadableFile(atPath: cache) { return cache } + if let bundlePath = self.bundleCatalogPath() { return bundlePath } + if let nodePath = self.nodeModulesCatalogPath() { return nodePath } + return cache + } + + private static func resolvePath(preferred: String) -> (path: String, shouldCache: Bool)? { + if FileManager().isReadableFile(atPath: preferred) { + return (preferred, preferred != self.cachePath.path) + } + + if let bundlePath = self.bundleCatalogPath(), bundlePath != preferred { + self.logger.warning("model catalog path missing; falling back to bundled catalog") + return (bundlePath, true) + } + + let cache = self.cachePath.path + if cache != preferred, FileManager().isReadableFile(atPath: cache) { + self.logger.warning("model catalog path missing; falling back to cached catalog") + return (cache, false) + } + + if let nodePath = self.nodeModulesCatalogPath(), nodePath != preferred { + self.logger.warning("model catalog path missing; falling back to node_modules catalog") + return (nodePath, true) + } + + return nil + } + + private static func bundleCatalogPath() -> String? { + guard let url = Bundle.main.url(forResource: "models.generated", withExtension: "js") else { + return nil + } + return url.path + } + + private static func nodeModulesCatalogPath() -> String? { + let roots = [ + URL(fileURLWithPath: CommandResolver.projectRootPath()), + URL(fileURLWithPath: FileManager().currentDirectoryPath), + ] + for root in roots { + let candidate = root + .appendingPathComponent("node_modules/@mariozechner/pi-ai/dist/models.generated.js") + if FileManager().isReadableFile(atPath: candidate.path) { + return candidate.path + } + } + return nil + } + + private static func cacheCatalog(sourcePath: String) { + let destination = self.cachePath + do { + try FileManager().createDirectory( + at: destination.deletingLastPathComponent(), + withIntermediateDirectories: true) + if FileManager().fileExists(atPath: destination.path) { + try FileManager().removeItem(at: destination) + } + try FileManager().copyItem(atPath: sourcePath, toPath: destination.path) + self.logger.debug("model catalog cached file=\(destination.lastPathComponent)") + } catch { + self.logger.warning("model catalog cache failed: \(error.localizedDescription)") + } + } + private static func sanitize(source: String) -> String { guard let exportRange = source.range(of: "export const MODELS"), let firstBrace = source[exportRange.upperBound...].firstIndex(of: "{"), diff --git a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeBridgePairingClient.swift b/apps/macos/Sources/Clawdbot/NodeMode/MacNodeBridgePairingClient.swift deleted file mode 100644 index 38b4877bc..000000000 --- a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeBridgePairingClient.swift +++ /dev/null @@ -1,236 +0,0 @@ -import ClawdbotKit -import Foundation -import Network - -actor MacNodeBridgePairingClient { - private let encoder = JSONEncoder() - private let decoder = JSONDecoder() - private var lineBuffer = Data() - - func pairAndHello( - endpoint: NWEndpoint, - hello: BridgeHello, - silent: Bool, - tls: MacNodeBridgeTLSParams? = nil, - onStatus: (@Sendable (String) -> Void)? = nil) async throws -> String - { - do { - return try await self.pairAndHelloOnce( - endpoint: endpoint, - hello: hello, - silent: silent, - tls: tls, - onStatus: onStatus) - } catch { - if let tls, !tls.required { - return try await self.pairAndHelloOnce( - endpoint: endpoint, - hello: hello, - silent: silent, - tls: nil, - onStatus: onStatus) - } - throw error - } - } - - private func pairAndHelloOnce( - endpoint: NWEndpoint, - hello: BridgeHello, - silent: Bool, - tls: MacNodeBridgeTLSParams?, - onStatus: (@Sendable (String) -> Void)? = nil) async throws -> String - { - self.lineBuffer = Data() - let params = self.makeParameters(tls: tls) - let connection = NWConnection(to: endpoint, using: params) - let queue = DispatchQueue(label: "com.clawdbot.macos.bridge-client") - defer { connection.cancel() } - try await AsyncTimeout.withTimeout( - seconds: 8, - onTimeout: { - NSError(domain: "Bridge", code: 0, userInfo: [ - NSLocalizedDescriptionKey: "connect timed out", - ]) - }, - operation: { - try await self.startAndWaitForReady(connection, queue: queue) - }) - - onStatus?("Authenticating…") - try await self.send(hello, over: connection) - - let first = try await AsyncTimeout.withTimeout( - seconds: 10, - onTimeout: { - NSError(domain: "Bridge", code: 0, userInfo: [ - NSLocalizedDescriptionKey: "hello timed out", - ]) - }, - operation: { () -> ReceivedFrame in - guard let frame = try await self.receiveFrame(over: connection) else { - throw NSError(domain: "Bridge", code: 0, userInfo: [ - NSLocalizedDescriptionKey: "Bridge closed connection during hello", - ]) - } - return frame - }) - - switch first.base.type { - case "hello-ok": - return hello.token ?? "" - - case "error": - let err = try self.decoder.decode(BridgeErrorFrame.self, from: first.data) - if err.code != "NOT_PAIRED", err.code != "UNAUTHORIZED" { - throw NSError(domain: "Bridge", code: 1, userInfo: [ - NSLocalizedDescriptionKey: "\(err.code): \(err.message)", - ]) - } - - onStatus?("Requesting approval…") - try await self.send( - BridgePairRequest( - nodeId: hello.nodeId, - displayName: hello.displayName, - platform: hello.platform, - version: hello.version, - deviceFamily: hello.deviceFamily, - modelIdentifier: hello.modelIdentifier, - caps: hello.caps, - commands: hello.commands, - silent: silent), - over: connection) - - onStatus?("Waiting for approval…") - let ok = try await AsyncTimeout.withTimeout( - seconds: 60, - onTimeout: { - NSError(domain: "Bridge", code: 0, userInfo: [ - NSLocalizedDescriptionKey: "pairing approval timed out", - ]) - }, - operation: { - while let next = try await self.receiveFrame(over: connection) { - switch next.base.type { - case "pair-ok": - return try self.decoder.decode(BridgePairOk.self, from: next.data) - case "error": - let e = try self.decoder.decode(BridgeErrorFrame.self, from: next.data) - throw NSError(domain: "Bridge", code: 2, userInfo: [ - NSLocalizedDescriptionKey: "\(e.code): \(e.message)", - ]) - default: - continue - } - } - throw NSError(domain: "Bridge", code: 3, userInfo: [ - NSLocalizedDescriptionKey: "Pairing failed: bridge closed connection", - ]) - }) - - return ok.token - - default: - throw NSError(domain: "Bridge", code: 0, userInfo: [ - NSLocalizedDescriptionKey: "Unexpected bridge response", - ]) - } - } - - private func send(_ obj: some Encodable, over connection: NWConnection) async throws { - let data = try self.encoder.encode(obj) - var line = Data() - line.append(data) - line.append(0x0A) - try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation) in - connection.send(content: line, completion: .contentProcessed { err in - if let err { cont.resume(throwing: err) } else { cont.resume(returning: ()) } - }) - } - } - - private struct ReceivedFrame { - var base: BridgeBaseFrame - var data: Data - } - - private func receiveFrame(over connection: NWConnection) async throws -> ReceivedFrame? { - guard let lineData = try await self.receiveLineData(over: connection) else { - return nil - } - let base = try self.decoder.decode(BridgeBaseFrame.self, from: lineData) - return ReceivedFrame(base: base, data: lineData) - } - - private func receiveChunk(over connection: NWConnection) async throws -> Data { - try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation) in - connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { data, _, isComplete, error in - if let error { - cont.resume(throwing: error) - return - } - if isComplete { - cont.resume(returning: Data()) - return - } - cont.resume(returning: data ?? Data()) - } - } - } - - private func receiveLineData(over connection: NWConnection) async throws -> Data? { - while true { - if let idx = self.lineBuffer.firstIndex(of: 0x0A) { - let line = self.lineBuffer.prefix(upTo: idx) - self.lineBuffer.removeSubrange(...idx) - return Data(line) - } - - let chunk = try await self.receiveChunk(over: connection) - if chunk.isEmpty { return nil } - self.lineBuffer.append(chunk) - } - } - - private func makeParameters(tls: MacNodeBridgeTLSParams?) -> NWParameters { - let tcpOptions = NWProtocolTCP.Options() - if let tlsOptions = makeMacNodeTLSOptions(tls) { - let params = NWParameters(tls: tlsOptions, tcp: tcpOptions) - params.includePeerToPeer = true - return params - } - let params = NWParameters.tcp - params.includePeerToPeer = true - return params - } - - private func startAndWaitForReady( - _ connection: NWConnection, - queue: DispatchQueue) async throws - { - let states = AsyncStream { continuation in - connection.stateUpdateHandler = { state in - continuation.yield(state) - if case .ready = state { continuation.finish() } - if case .failed = state { continuation.finish() } - if case .cancelled = state { continuation.finish() } - } - } - connection.start(queue: queue) - for await state in states { - switch state { - case .ready: - return - case let .failed(err): - throw err - case .cancelled: - throw NSError(domain: "Bridge", code: 0, userInfo: [ - NSLocalizedDescriptionKey: "Bridge connection cancelled", - ]) - default: - continue - } - } - } -} diff --git a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeBridgeSession.swift b/apps/macos/Sources/Clawdbot/NodeMode/MacNodeBridgeSession.swift deleted file mode 100644 index c739cd389..000000000 --- a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeBridgeSession.swift +++ /dev/null @@ -1,519 +0,0 @@ -import ClawdbotKit -import Foundation -import Network -import OSLog - -actor MacNodeBridgeSession { - private struct TimeoutError: LocalizedError { - var message: String - var errorDescription: String? { self.message } - } - - enum State: Sendable, Equatable { - case idle - case connecting - case connected(serverName: String) - case failed(message: String) - } - - private let logger = Logger(subsystem: "com.clawdbot", category: "node.bridge-session") - private let encoder = JSONEncoder() - private let decoder = JSONDecoder() - private let clock = ContinuousClock() - private var disconnectHandler: (@Sendable (String) async -> Void)? - - private var connection: NWConnection? - private var queue: DispatchQueue? - private var buffer = Data() - private var pendingRPC: [String: CheckedContinuation] = [:] - private var serverEventSubscribers: [UUID: AsyncStream.Continuation] = [:] - private var invokeTasks: [UUID: Task] = [:] - private var pingTask: Task? - private var lastPongAt: ContinuousClock.Instant? - - private(set) var state: State = .idle - - func connect( - endpoint: NWEndpoint, - hello: BridgeHello, - tls: MacNodeBridgeTLSParams? = nil, - onConnected: (@Sendable (String, String?) async -> Void)? = nil, - onDisconnected: (@Sendable (String) async -> Void)? = nil, - onInvoke: @escaping @Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse) - async throws - { - await self.disconnect() - self.disconnectHandler = onDisconnected - self.state = .connecting - do { - try await self.connectOnce( - endpoint: endpoint, - hello: hello, - tls: tls, - onConnected: onConnected, - onInvoke: onInvoke) - } catch { - if let tls, !tls.required { - try await self.connectOnce( - endpoint: endpoint, - hello: hello, - tls: nil, - onConnected: onConnected, - onInvoke: onInvoke) - return - } - throw error - } - } - - private func connectOnce( - endpoint: NWEndpoint, - hello: BridgeHello, - tls: MacNodeBridgeTLSParams?, - onConnected: (@Sendable (String, String?) async -> Void)? = nil, - onInvoke: @escaping @Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse) async throws - { - let params = self.makeParameters(tls: tls) - let connection = NWConnection(to: endpoint, using: params) - let queue = DispatchQueue(label: "com.clawdbot.macos.bridge-session") - self.connection = connection - self.queue = queue - - let stateStream = Self.makeStateStream(for: connection) - connection.start(queue: queue) - - try await Self.waitForReady(stateStream, timeoutSeconds: 6) - connection.stateUpdateHandler = { [weak self] state in - guard let self else { return } - Task { await self.handleConnectionState(state) } - } - - try await AsyncTimeout.withTimeout( - seconds: 6, - onTimeout: { - TimeoutError(message: "operation timed out") - }, - operation: { - try await self.send(hello) - }) - - guard let line = try await AsyncTimeout.withTimeout( - seconds: 6, - onTimeout: { - TimeoutError(message: "operation timed out") - }, - operation: { - try await self.receiveLine() - }), - let data = line.data(using: .utf8), - let base = try? self.decoder.decode(BridgeBaseFrame.self, from: data) - else { - self.logger.error("node bridge hello failed (unexpected response)") - await self.disconnect() - throw NSError(domain: "Bridge", code: 1, userInfo: [ - NSLocalizedDescriptionKey: "Unexpected bridge response", - ]) - } - - if base.type == "hello-ok" { - let ok = try self.decoder.decode(BridgeHelloOk.self, from: data) - self.state = .connected(serverName: ok.serverName) - self.startPingLoop() - let mainKey = ok.mainSessionKey?.trimmingCharacters(in: .whitespacesAndNewlines) - await onConnected?(ok.serverName, mainKey?.isEmpty == false ? mainKey : nil) - } else if base.type == "error" { - let err = try self.decoder.decode(BridgeErrorFrame.self, from: data) - self.state = .failed(message: "\(err.code): \(err.message)") - self.logger.error("node bridge hello error: \(err.code, privacy: .public)") - await self.disconnect() - throw NSError(domain: "Bridge", code: 2, userInfo: [ - NSLocalizedDescriptionKey: "\(err.code): \(err.message)", - ]) - } else { - self.state = .failed(message: "Unexpected bridge response") - self.logger.error("node bridge hello failed (unexpected frame)") - await self.disconnect() - throw NSError(domain: "Bridge", code: 3, userInfo: [ - NSLocalizedDescriptionKey: "Unexpected bridge response", - ]) - } - - do { - while true { - guard let next = try await self.receiveLine() else { break } - guard let nextData = next.data(using: .utf8) else { continue } - guard let nextBase = try? self.decoder.decode(BridgeBaseFrame.self, from: nextData) else { continue } - - switch nextBase.type { - case "res": - let res = try self.decoder.decode(BridgeRPCResponse.self, from: nextData) - if let cont = self.pendingRPC.removeValue(forKey: res.id) { - cont.resume(returning: res) - } - - case "event": - let evt = try self.decoder.decode(BridgeEventFrame.self, from: nextData) - self.broadcastServerEvent(evt) - - case "ping": - let ping = try self.decoder.decode(BridgePing.self, from: nextData) - try await self.send(BridgePong(type: "pong", id: ping.id)) - - case "pong": - let pong = try self.decoder.decode(BridgePong.self, from: nextData) - self.notePong(pong) - - case "invoke": - let req = try self.decoder.decode(BridgeInvokeRequest.self, from: nextData) - let taskID = UUID() - let task = Task { [weak self] in - let res = await onInvoke(req) - guard let self else { return } - await self.sendInvokeResponse(res, taskID: taskID) - } - self.invokeTasks[taskID] = task - - default: - continue - } - } - - await self.handleDisconnect(reason: "connection closed") - } catch { - self.logger.error( - "node bridge receive failed: \(error.localizedDescription, privacy: .public)") - await self.handleDisconnect(reason: "receive failed") - throw error - } - } - - func sendEvent(event: String, payloadJSON: String?) async throws { - try await self.send(BridgeEventFrame(type: "event", event: event, payloadJSON: payloadJSON)) - } - - func request(method: String, paramsJSON: String?, timeoutSeconds: Int = 15) async throws -> Data { - guard self.connection != nil else { - throw NSError(domain: "Bridge", code: 11, userInfo: [ - NSLocalizedDescriptionKey: "not connected", - ]) - } - - let id = UUID().uuidString - let req = BridgeRPCRequest(type: "req", id: id, method: method, paramsJSON: paramsJSON) - - let timeoutTask = Task { - try await Task.sleep(nanoseconds: UInt64(timeoutSeconds) * 1_000_000_000) - await self.timeoutRPC(id: id) - } - defer { timeoutTask.cancel() } - - let res: BridgeRPCResponse = try await withCheckedThrowingContinuation { cont in - Task { [weak self] in - guard let self else { return } - await self.beginRPC(id: id, request: req, continuation: cont) - } - } - - if res.ok { - let payload = res.payloadJSON ?? "" - guard let data = payload.data(using: .utf8) else { - throw NSError(domain: "Bridge", code: 12, userInfo: [ - NSLocalizedDescriptionKey: "Bridge response not UTF-8", - ]) - } - return data - } - - let code = res.error?.code ?? "UNAVAILABLE" - let message = res.error?.message ?? "request failed" - throw NSError(domain: "Bridge", code: 13, userInfo: [ - NSLocalizedDescriptionKey: "\(code): \(message)", - ]) - } - - func subscribeServerEvents(bufferingNewest: Int = 200) -> AsyncStream { - let id = UUID() - let session = self - return AsyncStream(bufferingPolicy: .bufferingNewest(bufferingNewest)) { continuation in - self.serverEventSubscribers[id] = continuation - continuation.onTermination = { @Sendable _ in - Task { await session.removeServerEventSubscriber(id) } - } - } - } - - func disconnect() async { - self.pingTask?.cancel() - self.pingTask = nil - self.lastPongAt = nil - self.disconnectHandler = nil - self.cancelInvokeTasks() - - self.connection?.cancel() - self.connection = nil - self.queue = nil - self.buffer = Data() - - let pending = self.pendingRPC.values - self.pendingRPC.removeAll() - for cont in pending { - cont.resume(throwing: NSError(domain: "Bridge", code: 14, userInfo: [ - NSLocalizedDescriptionKey: "UNAVAILABLE: connection closed", - ])) - } - - for (_, cont) in self.serverEventSubscribers { - cont.finish() - } - self.serverEventSubscribers.removeAll() - - self.state = .idle - } - - private func beginRPC( - id: String, - request: BridgeRPCRequest, - continuation: CheckedContinuation) async - { - self.pendingRPC[id] = continuation - do { - try await self.send(request) - } catch { - await self.failRPC(id: id, error: error) - } - } - - private func makeParameters(tls: MacNodeBridgeTLSParams?) -> NWParameters { - let tcpOptions = NWProtocolTCP.Options() - tcpOptions.enableKeepalive = true - tcpOptions.keepaliveIdle = 30 - tcpOptions.keepaliveInterval = 15 - tcpOptions.keepaliveCount = 3 - - if let tlsOptions = makeMacNodeTLSOptions(tls) { - let params = NWParameters(tls: tlsOptions, tcp: tcpOptions) - params.includePeerToPeer = true - return params - } - - let params = NWParameters.tcp - params.includePeerToPeer = true - params.defaultProtocolStack.transportProtocol = tcpOptions - return params - } - - private func failRPC(id: String, error: Error) async { - if let cont = self.pendingRPC.removeValue(forKey: id) { - cont.resume(throwing: error) - } - } - - private func timeoutRPC(id: String) async { - if let cont = self.pendingRPC.removeValue(forKey: id) { - cont.resume(throwing: TimeoutError(message: "request timed out")) - } - } - - private func removeServerEventSubscriber(_ id: UUID) { - self.serverEventSubscribers[id] = nil - } - - private func broadcastServerEvent(_ evt: BridgeEventFrame) { - for (_, cont) in self.serverEventSubscribers { - cont.yield(evt) - } - } - - private func send(_ obj: some Encodable) async throws { - guard let connection = self.connection else { - throw NSError(domain: "Bridge", code: 15, userInfo: [ - NSLocalizedDescriptionKey: "not connected", - ]) - } - let data = try self.encoder.encode(obj) - var line = Data() - line.append(data) - line.append(0x0A) - try await withCheckedThrowingContinuation(isolation: self) { (cont: CheckedContinuation) in - connection.send(content: line, completion: .contentProcessed { err in - if let err { cont.resume(throwing: err) } else { cont.resume(returning: ()) } - }) - } - } - - private func receiveLine() async throws -> String? { - while true { - if let idx = self.buffer.firstIndex(of: 0x0A) { - let line = self.buffer.prefix(upTo: idx) - self.buffer.removeSubrange(...idx) - return String(data: line, encoding: .utf8) - } - let chunk = try await self.receiveChunk() - if chunk.isEmpty { return nil } - self.buffer.append(chunk) - } - } - - private func receiveChunk() async throws -> Data { - guard let connection else { return Data() } - return try await withCheckedThrowingContinuation(isolation: self) { (cont: CheckedContinuation) in - connection.receive(minimumIncompleteLength: 1, maximumLength: 64 * 1024) { data, _, isComplete, error in - if let error { - cont.resume(throwing: error) - return - } - if isComplete { - cont.resume(returning: Data()) - return - } - cont.resume(returning: data ?? Data()) - } - } - } - - private func startPingLoop() { - self.pingTask?.cancel() - self.lastPongAt = self.clock.now - self.logger.debug("node bridge ping loop started") - self.pingTask = Task { [weak self] in - guard let self else { return } - await self.runPingLoop() - } - } - - private func runPingLoop() async { - let interval: Duration = .seconds(15) - let timeout: Duration = .seconds(45) - - while !Task.isCancelled { - try? await Task.sleep(for: interval) - - guard self.connection != nil else { return } - - if let last = self.lastPongAt { - let now = self.clock.now - if now > last.advanced(by: timeout) { - let age = last.duration(to: now) - let ageDescription = String(describing: age) - let message = - "Node bridge heartbeat timed out; disconnecting " + - "(age: \(ageDescription, privacy: .public))." - self.logger.warning(message) - await self.handleDisconnect(reason: "ping timeout") - return - } - } - - let id = UUID().uuidString - do { - try await self.send(BridgePing(type: "ping", id: id)) - } catch { - let errorDescription = String(describing: error) - let message = - "Node bridge ping send failed; disconnecting " + - "(error: \(errorDescription, privacy: .public))." - self.logger.warning(message) - await self.handleDisconnect(reason: "ping send failed") - return - } - } - } - - private func notePong(_ pong: BridgePong) { - _ = pong - self.lastPongAt = self.clock.now - } - - private func handleConnectionState(_ state: NWConnection.State) async { - switch state { - case let .failed(error): - let errorDescription = String(describing: error) - let message = - "Node bridge connection failed; disconnecting " + - "(error: \(errorDescription, privacy: .public))." - self.logger.warning(message) - await self.handleDisconnect(reason: "connection failed") - case .cancelled: - self.logger.warning("Node bridge connection cancelled; disconnecting.") - await self.handleDisconnect(reason: "connection cancelled") - default: - break - } - } - - private func handleDisconnect(reason: String) async { - self.logger.info("node bridge disconnect reason=\(reason, privacy: .public)") - if let handler = self.disconnectHandler { - await handler(reason) - } - await self.disconnect() - } - - private func logInvokeSendFailure(_ error: Error) { - self.logger.error( - "node bridge invoke response send failed: \(error.localizedDescription, privacy: .public)") - } - - private func sendInvokeResponse(_ response: BridgeInvokeResponse, taskID: UUID) async { - defer { self.invokeTasks[taskID] = nil } - if Task.isCancelled { return } - do { - try await self.send(response) - } catch { - self.logInvokeSendFailure(error) - } - } - - private func cancelInvokeTasks() { - for task in self.invokeTasks.values { - task.cancel() - } - self.invokeTasks.removeAll() - } - - private static func makeStateStream( - for connection: NWConnection) -> AsyncStream - { - AsyncStream { continuation in - connection.stateUpdateHandler = { state in - continuation.yield(state) - switch state { - case .ready, .failed, .cancelled: - continuation.finish() - default: - break - } - } - } - } - - private static func waitForReady( - _ stream: AsyncStream, - timeoutSeconds: Double) async throws - { - try await AsyncTimeout.withTimeout( - seconds: timeoutSeconds, - onTimeout: { - TimeoutError(message: "operation timed out") - }, - operation: { - for await state in stream { - switch state { - case .ready: - return - case let .failed(err): - throw err - case .cancelled: - throw NSError(domain: "Bridge", code: 20, userInfo: [ - NSLocalizedDescriptionKey: "Connection cancelled", - ]) - default: - continue - } - } - throw NSError(domain: "Bridge", code: 21, userInfo: [ - NSLocalizedDescriptionKey: "Connection closed", - ]) - }) - } -} diff --git a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeBridgeTLS.swift b/apps/macos/Sources/Clawdbot/NodeMode/MacNodeBridgeTLS.swift deleted file mode 100644 index cd6d32f29..000000000 --- a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeBridgeTLS.swift +++ /dev/null @@ -1,74 +0,0 @@ -import CryptoKit -import Foundation -import Network -import Security - -struct MacNodeBridgeTLSParams: Sendable { - let required: Bool - let expectedFingerprint: String? - let allowTOFU: Bool - let storeKey: String? -} - -enum MacNodeBridgeTLSStore { - private static let suiteName = "com.clawdbot.shared" - private static let keyPrefix = "mac.node.bridge.tls." - - private static var defaults: UserDefaults { - UserDefaults(suiteName: suiteName) ?? .standard - } - - static func loadFingerprint(stableID: String) -> String? { - let key = self.keyPrefix + stableID - let raw = self.defaults.string(forKey: key)?.trimmingCharacters(in: .whitespacesAndNewlines) - return raw?.isEmpty == false ? raw : nil - } - - static func saveFingerprint(_ value: String, stableID: String) { - let key = self.keyPrefix + stableID - self.defaults.set(value, forKey: key) - } -} - -func makeMacNodeTLSOptions(_ params: MacNodeBridgeTLSParams?) -> NWProtocolTLS.Options? { - guard let params else { return nil } - let options = NWProtocolTLS.Options() - let expected = params.expectedFingerprint.map(normalizeMacNodeFingerprint) - let allowTOFU = params.allowTOFU - let storeKey = params.storeKey - - sec_protocol_options_set_verify_block( - options.securityProtocolOptions, - { _, trust, complete in - let trustRef = sec_trust_copy_ref(trust).takeRetainedValue() - if let chain = SecTrustCopyCertificateChain(trustRef) as? [SecCertificate], - let cert = chain.first - { - let data = SecCertificateCopyData(cert) as Data - let fingerprint = sha256Hex(data) - if let expected { - complete(fingerprint == expected) - return - } - if allowTOFU { - if let storeKey { MacNodeBridgeTLSStore.saveFingerprint(fingerprint, stableID: storeKey) } - complete(true) - return - } - } - let ok = SecTrustEvaluateWithError(trustRef, nil) - complete(ok) - }, - DispatchQueue(label: "com.clawdbot.macos.bridge.tls.verify")) - - return options -} - -private func sha256Hex(_ data: Data) -> String { - let digest = SHA256.hash(data: data) - return digest.map { String(format: "%02x", $0) }.joined() -} - -private func normalizeMacNodeFingerprint(_ raw: String) -> String { - raw.lowercased().filter(\.isHexDigit) -} diff --git a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeModeCoordinator.swift b/apps/macos/Sources/Clawdbot/NodeMode/MacNodeModeCoordinator.swift index 7bfa8c15b..3d86bc4e9 100644 --- a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeModeCoordinator.swift +++ b/apps/macos/Sources/Clawdbot/NodeMode/MacNodeModeCoordinator.swift @@ -1,15 +1,7 @@ -import ClawdbotDiscovery import ClawdbotKit import Foundation -import Network import OSLog -private struct BridgeTarget { - let endpoint: NWEndpoint - let stableID: String - let tls: MacNodeBridgeTLSParams? -} - @MainActor final class MacNodeModeCoordinator { static let shared = MacNodeModeCoordinator() @@ -17,8 +9,7 @@ final class MacNodeModeCoordinator { private let logger = Logger(subsystem: "com.clawdbot", category: "mac-node") private var task: Task? private let runtime = MacNodeRuntime() - private let session = MacNodeBridgeSession() - private var tunnel: RemotePortTunnel? + private let session = GatewayNodeSession() func start() { guard self.task == nil else { return } @@ -31,20 +22,18 @@ final class MacNodeModeCoordinator { self.task?.cancel() self.task = nil Task { await self.session.disconnect() } - self.tunnel?.terminate() - self.tunnel = nil } - func setPreferredBridgeStableID(_ stableID: String?) { - BridgeDiscoveryPreferences.setPreferredStableID(stableID) + func setPreferredGatewayStableID(_ stableID: String?) { + GatewayDiscoveryPreferences.setPreferredStableID(stableID) Task { await self.session.disconnect() } } private func run() async { var retryDelay: UInt64 = 1_000_000_000 var lastCameraEnabled: Bool? - var lastSystemRunPolicy: SystemRunPolicy? let defaults = UserDefaults.standard + while !Task.isCancelled { if await MainActor.run(body: { AppStateStore.shared.isPaused }) { try? await Task.sleep(nanoseconds: 1_000_000_000) @@ -60,38 +49,42 @@ final class MacNodeModeCoordinator { try? await Task.sleep(nanoseconds: 200_000_000) } - let systemRunPolicy = SystemRunPolicy.load() - if lastSystemRunPolicy == nil { - lastSystemRunPolicy = systemRunPolicy - } else if lastSystemRunPolicy != systemRunPolicy { - lastSystemRunPolicy = systemRunPolicy - await self.session.disconnect() - try? await Task.sleep(nanoseconds: 200_000_000) - } - - guard let target = await self.resolveBridgeEndpoint(timeoutSeconds: 5) else { - try? await Task.sleep(nanoseconds: min(retryDelay, 5_000_000_000)) - retryDelay = min(retryDelay * 2, 10_000_000_000) - continue - } - - retryDelay = 1_000_000_000 do { - let hello = await self.makeHello() - self.logger.info( - "mac node bridge connecting endpoint=\(target.endpoint, privacy: .public)") + let config = try await GatewayEndpointStore.shared.requireConfig() + let caps = self.currentCaps() + let commands = self.currentCommands(caps: caps) + let permissions = await self.currentPermissions() + let connectOptions = GatewayConnectOptions( + role: "node", + scopes: [], + caps: caps, + commands: commands, + permissions: permissions, + clientId: "clawdbot-macos", + clientMode: "node", + clientDisplayName: InstanceIdentity.displayName) + let sessionBox = self.buildSessionBox(url: config.url) + try await self.session.connect( - endpoint: target.endpoint, - hello: hello, - tls: target.tls, - onConnected: { [weak self] serverName, mainSessionKey in - self?.logger.info("mac node connected to \(serverName, privacy: .public)") - if let mainSessionKey { - await self?.runtime.updateMainSessionKey(mainSessionKey) + url: config.url, + token: config.token, + password: config.password, + connectOptions: connectOptions, + sessionBox: sessionBox, + onConnected: { [weak self] in + guard let self else { return } + self.logger.info("mac node connected to gateway") + let mainSessionKey = await GatewayConnection.shared.mainSessionKey() + await self.runtime.updateMainSessionKey(mainSessionKey) + await self.runtime.setEventSender { [weak self] event, payload in + guard let self else { return } + await self.session.sendEvent(event: event, payloadJSON: payload) } }, - onDisconnected: { reason in - await MacNodeModeCoordinator.handleBridgeDisconnect(reason: reason) + onDisconnected: { [weak self] reason in + guard let self else { return } + await self.runtime.setEventSender(nil) + self.logger.error("mac node disconnected: \(reason, privacy: .public)") }, onInvoke: { [weak self] req in guard let self else { @@ -102,36 +95,17 @@ final class MacNodeModeCoordinator { } return await self.runtime.handleInvoke(req) }) + + retryDelay = 1_000_000_000 + try? await Task.sleep(nanoseconds: 1_000_000_000) } catch { - if await self.tryPair(target: target, error: error) { - continue - } - self.logger.error( - "mac node bridge connect failed: \(error.localizedDescription, privacy: .public)") - try? await Task.sleep(nanoseconds: min(retryDelay, 5_000_000_000)) + self.logger.error("mac node gateway connect failed: \(error.localizedDescription, privacy: .public)") + try? await Task.sleep(nanoseconds: min(retryDelay, 10_000_000_000)) retryDelay = min(retryDelay * 2, 10_000_000_000) } } } - private func makeHello() async -> BridgeHello { - let token = MacNodeTokenStore.loadToken() - let caps = self.currentCaps() - let commands = self.currentCommands(caps: caps) - let permissions = await self.currentPermissions() - return BridgeHello( - nodeId: Self.nodeId(), - displayName: InstanceIdentity.displayName, - token: token, - platform: "macos", - version: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, - deviceFamily: "Mac", - modelIdentifier: InstanceIdentity.modelIdentifier, - caps: caps, - commands: commands, - permissions: permissions) - } - private func currentCaps() -> [String] { var caps: [String] = [ClawdbotCapability.canvas.rawValue, ClawdbotCapability.screen.rawValue] if UserDefaults.standard.object(forKey: cameraEnabledKey) as? Bool ?? false { @@ -161,13 +135,12 @@ final class MacNodeModeCoordinator { ClawdbotCanvasA2UICommand.reset.rawValue, MacNodeScreenCommand.record.rawValue, ClawdbotSystemCommand.notify.rawValue, + ClawdbotSystemCommand.which.rawValue, + ClawdbotSystemCommand.run.rawValue, + ClawdbotSystemCommand.execApprovalsGet.rawValue, + ClawdbotSystemCommand.execApprovalsSet.rawValue, ] - if SystemRunPolicy.load() != .never { - commands.append(ClawdbotSystemCommand.which.rawValue) - commands.append(ClawdbotSystemCommand.run.rawValue) - } - let capsSet = Set(caps) if capsSet.contains(ClawdbotCapability.camera.rawValue) { commands.append(ClawdbotCameraCommand.list.rawValue) @@ -181,370 +154,18 @@ final class MacNodeModeCoordinator { return commands } - private func tryPair(target: BridgeTarget, error: Error) async -> Bool { - let text = error.localizedDescription.uppercased() - guard text.contains("NOT_PAIRED") || text.contains("UNAUTHORIZED") else { return false } - - do { - let shouldSilent = await MainActor.run { - AppStateStore.shared.connectionMode == .remote - } - let hello = await self.makeHello() - let token = try await MacNodeBridgePairingClient().pairAndHello( - endpoint: target.endpoint, - hello: hello, - silent: shouldSilent, - tls: target.tls, - onStatus: { [weak self] status in - self?.logger.info("mac node pairing: \(status, privacy: .public)") - }) - if !token.isEmpty { - MacNodeTokenStore.saveToken(token) - } - return true - } catch { - self.logger.error("mac node pairing failed: \(error.localizedDescription, privacy: .public)") - return false - } - } - - private static func nodeId() -> String { - "mac-\(InstanceIdentity.instanceId)" - } - - private func resolveLoopbackBridgeEndpoint(timeoutSeconds: Double) async -> BridgeTarget? { - guard let port = Self.loopbackBridgePort(), - let endpointPort = NWEndpoint.Port(rawValue: port) - else { - return nil - } - let endpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: endpointPort) - let reachable = await Self.probeEndpoint(endpoint, timeoutSeconds: timeoutSeconds) - guard reachable else { return nil } - let stableID = BridgeEndpointID.stableID(endpoint) - let tlsParams = Self.resolveManualTLSParams(stableID: stableID) - return BridgeTarget(endpoint: endpoint, stableID: stableID, tls: tlsParams) - } - - static func loopbackBridgePort() -> UInt16? { - if let raw = ProcessInfo.processInfo.environment["CLAWDBOT_BRIDGE_PORT"], - let parsed = Int(raw.trimmingCharacters(in: .whitespacesAndNewlines)), - parsed > 0, - parsed <= Int(UInt16.max) - { - return UInt16(parsed) - } - return 18790 - } - - static func remoteBridgePort() -> Int { - let fallback = Int(Self.loopbackBridgePort() ?? 18790) - let settings = CommandResolver.connectionSettings() - let sshHost = CommandResolver.parseSSHTarget(settings.target)?.host ?? "" - let base = - ClawdbotConfigFile.remoteGatewayPort(matchingHost: sshHost) ?? - GatewayEnvironment.gatewayPort() - guard base > 0 else { return fallback } - return Self.derivePort(base: base, offset: 1, fallback: fallback) - } - - private static func derivePort(base: Int, offset: Int, fallback: Int) -> Int { - let derived = base + offset - guard derived > 0, derived <= Int(UInt16.max) else { return fallback } - return derived - } - - static func probeEndpoint(_ endpoint: NWEndpoint, timeoutSeconds: Double) async -> Bool { - let connection = NWConnection(to: endpoint, using: .tcp) - let stream = Self.makeStateStream(for: connection) - connection.start(queue: DispatchQueue(label: "com.clawdbot.macos.bridge-loopback-probe")) - do { - try await Self.waitForReady(stream, timeoutSeconds: timeoutSeconds) - connection.cancel() - return true - } catch { - connection.cancel() - return false - } - } - - private static func makeStateStream( - for connection: NWConnection) -> AsyncStream - { - AsyncStream { continuation in - connection.stateUpdateHandler = { state in - continuation.yield(state) - switch state { - case .ready, .failed, .cancelled: - continuation.finish() - default: - break - } - } - } - } - - private static func waitForReady( - _ stream: AsyncStream, - timeoutSeconds: Double) async throws - { - try await AsyncTimeout.withTimeout( - seconds: timeoutSeconds, - onTimeout: { - NSError(domain: "Bridge", code: 22, userInfo: [ - NSLocalizedDescriptionKey: "operation timed out", - ]) - }, - operation: { - for await state in stream { - switch state { - case .ready: - return - case let .failed(err): - throw err - case .cancelled: - throw NSError(domain: "Bridge", code: 20, userInfo: [ - NSLocalizedDescriptionKey: "Connection cancelled", - ]) - default: - continue - } - } - throw NSError(domain: "Bridge", code: 21, userInfo: [ - NSLocalizedDescriptionKey: "Connection closed", - ]) - }) - } - - private func resolveBridgeEndpoint(timeoutSeconds: Double) async -> BridgeTarget? { - let mode = await MainActor.run(body: { AppStateStore.shared.connectionMode }) - if mode == .remote { - do { - if let tunnel = self.tunnel, - tunnel.process.isRunning, - let localPort = tunnel.localPort - { - let healthy = await self.bridgeTunnelHealthy(localPort: localPort, timeoutSeconds: 1.0) - if healthy, let port = NWEndpoint.Port(rawValue: localPort) { - self.logger.info( - "reusing mac node bridge tunnel localPort=\(localPort, privacy: .public)") - let endpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: port) - let stableID = BridgeEndpointID.stableID(endpoint) - let tlsParams = Self.resolveManualTLSParams(stableID: stableID) - return BridgeTarget(endpoint: endpoint, stableID: stableID, tls: tlsParams) - } - self.logger.error( - "mac node bridge tunnel unhealthy localPort=\(localPort, privacy: .public); restarting") - tunnel.terminate() - self.tunnel = nil - } - - let remotePort = Self.remoteBridgePort() - let preferredLocalPort = Self.loopbackBridgePort() - if let preferredLocalPort { - self.logger.info( - "mac node bridge tunnel starting " + - "preferredLocalPort=\(preferredLocalPort, privacy: .public) " + - "remotePort=\(remotePort, privacy: .public)") - } else { - self.logger.info( - "mac node bridge tunnel starting " + - "preferredLocalPort=none " + - "remotePort=\(remotePort, privacy: .public)") - } - self.tunnel = try await RemotePortTunnel.create( - remotePort: remotePort, - preferredLocalPort: preferredLocalPort, - allowRemoteUrlOverride: false, - allowRandomLocalPort: true) - if let localPort = self.tunnel?.localPort, - let port = NWEndpoint.Port(rawValue: localPort) - { - self.logger.info( - "mac node bridge tunnel ready " + - "localPort=\(localPort, privacy: .public) " + - "remotePort=\(remotePort, privacy: .public)") - let endpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: port) - let stableID = BridgeEndpointID.stableID(endpoint) - let tlsParams = Self.resolveManualTLSParams(stableID: stableID) - return BridgeTarget(endpoint: endpoint, stableID: stableID, tls: tlsParams) - } - } catch { - self.logger.error("mac node bridge tunnel failed: \(error.localizedDescription, privacy: .public)") - self.tunnel?.terminate() - self.tunnel = nil - } - } else if let tunnel = self.tunnel { - tunnel.terminate() - self.tunnel = nil - } - if mode == .local, let target = await self.resolveLoopbackBridgeEndpoint(timeoutSeconds: 0.4) { - return target - } - return await Self.discoverBridgeEndpoint(timeoutSeconds: timeoutSeconds) - } - - @MainActor - private static func handleBridgeDisconnect(reason: String) async { - guard reason.localizedCaseInsensitiveContains("ping") else { return } - let coordinator = MacNodeModeCoordinator.shared - coordinator.logger.error( - "mac node bridge disconnected (\(reason, privacy: .public)); resetting tunnel") - coordinator.tunnel?.terminate() - coordinator.tunnel = nil - } - - private func bridgeTunnelHealthy(localPort: UInt16, timeoutSeconds: Double) async -> Bool { - guard let port = NWEndpoint.Port(rawValue: localPort) else { return false } - return await Self.probeEndpoint(.hostPort(host: "127.0.0.1", port: port), timeoutSeconds: timeoutSeconds) - } - - private static func discoverBridgeEndpoint(timeoutSeconds: Double) async -> BridgeTarget? { - final class DiscoveryState: @unchecked Sendable { - let lock = NSLock() - var resolved = false - var browsers: [NWBrowser] = [] - var continuation: CheckedContinuation? - - func finish(_ target: BridgeTarget?) { - self.lock.lock() - defer { lock.unlock() } - if self.resolved { return } - self.resolved = true - for browser in self.browsers { - browser.cancel() - } - self.continuation?.resume(returning: target) - self.continuation = nil - } - } - - return await withCheckedContinuation { cont in - let state = DiscoveryState() - state.continuation = cont - - let params = NWParameters.tcp - params.includePeerToPeer = true - - for domain in ClawdbotBonjour.bridgeServiceDomains { - let browser = NWBrowser( - for: .bonjour(type: ClawdbotBonjour.bridgeServiceType, domain: domain), - using: params) - browser.browseResultsChangedHandler = { results, _ in - let preferred = BridgeDiscoveryPreferences.preferredStableID() - if let preferred, - let match = results.first(where: { - if case .service = $0.endpoint { - return BridgeEndpointID.stableID($0.endpoint) == preferred - } - return false - }) - { - state.finish(Self.targetFromResult(match)) - return - } - - if let result = results.first(where: { if case .service = $0.endpoint { true } else { false } }) { - state.finish(Self.targetFromResult(result)) - } - } - browser.stateUpdateHandler = { browserState in - if case .failed = browserState { - state.finish(nil) - } - } - state.browsers.append(browser) - browser.start(queue: DispatchQueue(label: "com.clawdbot.macos.bridge-discovery.\(domain)")) - } - - Task { - try? await Task.sleep(nanoseconds: UInt64(timeoutSeconds * 1_000_000_000)) - state.finish(nil) - } - } - } - - private nonisolated static func targetFromResult(_ result: NWBrowser.Result) -> BridgeTarget? { - let endpoint = result.endpoint - guard case .service = endpoint else { return nil } - let stableID = BridgeEndpointID.stableID(endpoint) - let txt = result.endpoint.txtRecord?.dictionary ?? [:] - let tlsEnabled = Self.txtBoolValue(txt, key: "bridgeTls") - let tlsFingerprint = Self.txtValue(txt, key: "bridgeTlsSha256") - let tlsParams = Self.resolveDiscoveredTLSParams( - stableID: stableID, - tlsEnabled: tlsEnabled, - tlsFingerprintSha256: tlsFingerprint) - return BridgeTarget(endpoint: endpoint, stableID: stableID, tls: tlsParams) - } - - private nonisolated static func resolveDiscoveredTLSParams( - stableID: String, - tlsEnabled: Bool, - tlsFingerprintSha256: String?) -> MacNodeBridgeTLSParams? - { - let stored = MacNodeBridgeTLSStore.loadFingerprint(stableID: stableID) - - if tlsEnabled || tlsFingerprintSha256 != nil { - return MacNodeBridgeTLSParams( - required: true, - expectedFingerprint: tlsFingerprintSha256 ?? stored, - allowTOFU: stored == nil, - storeKey: stableID) - } - - if let stored { - return MacNodeBridgeTLSParams( - required: true, - expectedFingerprint: stored, - allowTOFU: false, - storeKey: stableID) - } - - return nil - } - - private nonisolated static func resolveManualTLSParams(stableID: String) -> MacNodeBridgeTLSParams? { - if let stored = MacNodeBridgeTLSStore.loadFingerprint(stableID: stableID) { - return MacNodeBridgeTLSParams( - required: true, - expectedFingerprint: stored, - allowTOFU: false, - storeKey: stableID) - } - - return MacNodeBridgeTLSParams( - required: false, - expectedFingerprint: nil, - allowTOFU: true, + private func buildSessionBox(url: URL) -> WebSocketSessionBox? { + guard url.scheme?.lowercased() == "wss" else { return nil } + let host = url.host ?? "gateway" + let port = url.port ?? 443 + let stableID = "\(host):\(port)" + let stored = GatewayTLSStore.loadFingerprint(stableID: stableID) + let params = GatewayTLSParams( + required: true, + expectedFingerprint: stored, + allowTOFU: stored == nil, storeKey: stableID) - } - - private nonisolated static func txtValue(_ dict: [String: String], key: String) -> String? { - let raw = dict[key]?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - return raw.isEmpty ? nil : raw - } - - private nonisolated static func txtBoolValue(_ dict: [String: String], key: String) -> Bool { - guard let raw = self.txtValue(dict, key: key)?.lowercased() else { return false } - return raw == "1" || raw == "true" || raw == "yes" - } -} - -enum MacNodeTokenStore { - private static let suiteName = "com.clawdbot.shared" - private static let tokenKey = "mac.node.bridge.token" - - private static var defaults: UserDefaults { - UserDefaults(suiteName: suiteName) ?? .standard - } - - static func loadToken() -> String? { - let raw = self.defaults.string(forKey: self.tokenKey)?.trimmingCharacters(in: .whitespacesAndNewlines) - return raw?.isEmpty == false ? raw : nil - } - - static func saveToken(_ token: String) { - self.defaults.set(token, forKey: self.tokenKey) + let session = GatewayTLSPinningSession(params: params) + return WebSocketSessionBox(session: session) } } diff --git a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeRuntime.swift b/apps/macos/Sources/Clawdbot/NodeMode/MacNodeRuntime.swift index e0bcbfae3..c3eacb8a1 100644 --- a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeRuntime.swift +++ b/apps/macos/Sources/Clawdbot/NodeMode/MacNodeRuntime.swift @@ -8,6 +8,7 @@ actor MacNodeRuntime { private let makeMainActorServices: () async -> any MacNodeRuntimeMainActorServices private var cachedMainActorServices: (any MacNodeRuntimeMainActorServices)? private var mainSessionKey: String = "main" + private var eventSender: (@Sendable (String, String?) async -> Void)? init( makeMainActorServices: @escaping () async -> any MacNodeRuntimeMainActorServices = { @@ -23,6 +24,10 @@ actor MacNodeRuntime { self.mainSessionKey = trimmed } + func setEventSender(_ sender: (@Sendable (String, String?) async -> Void)?) { + self.eventSender = sender + } + func handleInvoke(_ req: BridgeInvokeRequest) async -> BridgeInvokeResponse { let command = req.command if self.isCanvasCommand(command), !Self.canvasEnabled() { @@ -59,6 +64,10 @@ actor MacNodeRuntime { return try await self.handleSystemWhich(req) case ClawdbotSystemCommand.notify.rawValue: return try await self.handleSystemNotify(req) + case ClawdbotSystemCommand.execApprovalsGet.rawValue: + return try await self.handleSystemExecApprovalsGet(req) + case ClawdbotSystemCommand.execApprovalsSet.rawValue: + return try await self.handleSystemExecApprovalsSet(req) default: return Self.errorResponse(req, code: .invalidRequest, message: "INVALID_REQUEST: unknown command") } @@ -124,7 +133,7 @@ actor MacNodeRuntime { let sessionKey = self.mainSessionKey let path = try await CanvasManager.shared.snapshot(sessionKey: sessionKey, outPath: nil) - defer { try? FileManager.default.removeItem(atPath: path) } + defer { try? FileManager().removeItem(atPath: path) } let data = try Data(contentsOf: URL(fileURLWithPath: path)) guard let image = NSImage(data: data) else { return Self.errorResponse(req, code: .unavailable, message: "canvas snapshot decode failed") @@ -197,7 +206,7 @@ actor MacNodeRuntime { includeAudio: params.includeAudio ?? true, deviceId: params.deviceId, outPath: nil) - defer { try? FileManager.default.removeItem(atPath: res.path) } + defer { try? FileManager().removeItem(atPath: res.path) } let data = try Data(contentsOf: URL(fileURLWithPath: res.path)) struct ClipPayload: Encodable { var format: String @@ -303,7 +312,7 @@ actor MacNodeRuntime { fps: params.fps, includeAudio: params.includeAudio, outPath: nil) - defer { try? FileManager.default.removeItem(atPath: res.path) } + defer { try? FileManager().removeItem(atPath: res.path) } let data = try Data(contentsOf: URL(fileURLWithPath: res.path)) struct ScreenPayload: Encodable { var format: String @@ -427,42 +436,107 @@ actor MacNodeRuntime { guard !command.isEmpty else { return Self.errorResponse(req, code: .invalidRequest, message: "INVALID_REQUEST: command required") } + let displayCommand = ExecCommandFormatter.displayString(for: command, rawCommand: params.rawCommand) - let wasAllowlisted = SystemRunAllowlist.contains(command) - switch Self.systemRunPolicy() { - case .never: + let trimmedAgent = params.agentId?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let agentId = trimmedAgent.isEmpty ? nil : trimmedAgent + let approvals = ExecApprovalsStore.resolve(agentId: agentId) + let security = approvals.agent.security + let ask = approvals.agent.ask + let autoAllowSkills = approvals.agent.autoAllowSkills + let sessionKey = (params.sessionKey?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false) + ? params.sessionKey!.trimmingCharacters(in: .whitespacesAndNewlines) + : self.mainSessionKey + let runId = UUID().uuidString + let env = Self.sanitizedEnv(params.env) + let resolution = ExecCommandResolution.resolve( + command: command, + rawCommand: params.rawCommand, + cwd: params.cwd, + env: env) + let allowlistMatch = security == .allowlist + ? ExecAllowlistMatcher.match(entries: approvals.allowlist, resolution: resolution) + : nil + let skillAllow: Bool + if autoAllowSkills, let name = resolution?.executableName { + let bins = await SkillBinsCache.shared.currentBins() + skillAllow = bins.contains(name) + } else { + skillAllow = false + } + + if security == .deny { + await self.emitExecEvent( + "exec.denied", + payload: ExecEventPayload( + sessionKey: sessionKey, + runId: runId, + host: "node", + command: displayCommand, + reason: "security=deny")) return Self.errorResponse( req, code: .unavailable, - message: "SYSTEM_RUN_DISABLED: policy=never") - case .always: - break - case .ask: - if !wasAllowlisted { - let services = await self.mainActorServices() - let decision = await services.confirmSystemRun( - command: SystemRunAllowlist.displayString(for: command), - cwd: params.cwd) - switch decision { - case .allowOnce: - break - case .allowAlways: - SystemRunAllowlist.add(command) - case .deny: - return Self.errorResponse( - req, - code: .unavailable, - message: "SYSTEM_RUN_DENIED: user denied") - } - } + message: "SYSTEM_RUN_DISABLED: security=deny") } - let env = Self.sanitizedEnv(params.env) + let approval = await self.resolveSystemRunApproval( + req: req, + params: params, + context: ExecRunContext( + displayCommand: displayCommand, + security: security, + ask: ask, + agentId: agentId, + resolution: resolution, + allowlistMatch: allowlistMatch, + skillAllow: skillAllow, + sessionKey: sessionKey, + runId: runId)) + if let response = approval.response { return response } + let approvedByAsk = approval.approvedByAsk + let persistAllowlist = approval.persistAllowlist + if persistAllowlist, security == .allowlist, + let pattern = ExecApprovalHelpers.allowlistPattern(command: command, resolution: resolution) + { + ExecApprovalsStore.addAllowlistEntry(agentId: agentId, pattern: pattern) + } + + if security == .allowlist, allowlistMatch == nil, !skillAllow, !approvedByAsk { + await self.emitExecEvent( + "exec.denied", + payload: ExecEventPayload( + sessionKey: sessionKey, + runId: runId, + host: "node", + command: displayCommand, + reason: "allowlist-miss")) + return Self.errorResponse( + req, + code: .unavailable, + message: "SYSTEM_RUN_DENIED: allowlist miss") + } + + if let match = allowlistMatch { + ExecApprovalsStore.recordAllowlistUse( + agentId: agentId, + pattern: match.pattern, + command: displayCommand, + resolvedPath: resolution?.resolvedPath) + } if params.needsScreenRecording == true { let authorized = await PermissionManager .status([.screenRecording])[.screenRecording] ?? false if !authorized { + await self.emitExecEvent( + "exec.denied", + payload: ExecEventPayload( + sessionKey: sessionKey, + runId: runId, + host: "node", + command: displayCommand, + reason: "permission:screenRecording")) return Self.errorResponse( req, code: .unavailable, @@ -471,11 +545,33 @@ actor MacNodeRuntime { } let timeoutSec = params.timeoutMs.flatMap { Double($0) / 1000.0 } + await self.emitExecEvent( + "exec.started", + payload: ExecEventPayload( + sessionKey: sessionKey, + runId: runId, + host: "node", + command: displayCommand)) let result = await ShellExecutor.runDetailed( command: command, cwd: params.cwd, env: env, timeout: timeoutSec) + let combined = [result.stdout, result.stderr, result.errorMessage] + .compactMap(\.self) + .filter { !$0.isEmpty } + .joined(separator: "\n") + await self.emitExecEvent( + "exec.finished", + payload: ExecEventPayload( + sessionKey: sessionKey, + runId: runId, + host: "node", + command: displayCommand, + exitCode: result.exitCode, + timedOut: result.timedOut, + success: result.success, + output: ExecEventPayload.truncateOutput(combined))) struct RunPayload: Encodable { var exitCode: Int? @@ -523,6 +619,176 @@ actor MacNodeRuntime { return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: payload) } + private struct ExecApprovalOutcome { + var approvedByAsk: Bool + var persistAllowlist: Bool + var response: BridgeInvokeResponse? + } + + private struct ExecRunContext { + var displayCommand: String + var security: ExecSecurity + var ask: ExecAsk + var agentId: String? + var resolution: ExecCommandResolution? + var allowlistMatch: ExecAllowlistEntry? + var skillAllow: Bool + var sessionKey: String + var runId: String + } + + private func resolveSystemRunApproval( + req: BridgeInvokeRequest, + params: ClawdbotSystemRunParams, + context: ExecRunContext) async -> ExecApprovalOutcome + { + let requiresAsk = ExecApprovalHelpers.requiresAsk( + ask: context.ask, + security: context.security, + allowlistMatch: context.allowlistMatch, + skillAllow: context.skillAllow) + + let decisionFromParams = ExecApprovalHelpers.parseDecision(params.approvalDecision) + var approvedByAsk = params.approved == true || decisionFromParams != nil + var persistAllowlist = decisionFromParams == .allowAlways + if decisionFromParams == .deny { + await self.emitExecEvent( + "exec.denied", + payload: ExecEventPayload( + sessionKey: context.sessionKey, + runId: context.runId, + host: "node", + command: context.displayCommand, + reason: "user-denied")) + return ExecApprovalOutcome( + approvedByAsk: approvedByAsk, + persistAllowlist: persistAllowlist, + response: Self.errorResponse( + req, + code: .unavailable, + message: "SYSTEM_RUN_DENIED: user denied")) + } + + if requiresAsk, !approvedByAsk { + let decision = await MainActor.run { + ExecApprovalsPromptPresenter.prompt( + ExecApprovalPromptRequest( + command: context.displayCommand, + cwd: params.cwd, + host: "node", + security: context.security.rawValue, + ask: context.ask.rawValue, + agentId: context.agentId, + resolvedPath: context.resolution?.resolvedPath, + sessionKey: context.sessionKey)) + } + switch decision { + case .deny: + await self.emitExecEvent( + "exec.denied", + payload: ExecEventPayload( + sessionKey: context.sessionKey, + runId: context.runId, + host: "node", + command: context.displayCommand, + reason: "user-denied")) + return ExecApprovalOutcome( + approvedByAsk: approvedByAsk, + persistAllowlist: persistAllowlist, + response: Self.errorResponse( + req, + code: .unavailable, + message: "SYSTEM_RUN_DENIED: user denied")) + case .allowAlways: + approvedByAsk = true + persistAllowlist = true + case .allowOnce: + approvedByAsk = true + } + } + + return ExecApprovalOutcome( + approvedByAsk: approvedByAsk, + persistAllowlist: persistAllowlist, + response: nil) + } + + private func handleSystemExecApprovalsGet(_ req: BridgeInvokeRequest) async throws -> BridgeInvokeResponse { + _ = ExecApprovalsStore.ensureFile() + let snapshot = ExecApprovalsStore.readSnapshot() + let redacted = ExecApprovalsSnapshot( + path: snapshot.path, + exists: snapshot.exists, + hash: snapshot.hash, + file: ExecApprovalsStore.redactForSnapshot(snapshot.file)) + let payload = try Self.encodePayload(redacted) + return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: payload) + } + + private func handleSystemExecApprovalsSet(_ req: BridgeInvokeRequest) async throws -> BridgeInvokeResponse { + struct SetParams: Decodable { + var file: ExecApprovalsFile + var baseHash: String? + } + + let params = try Self.decodeParams(SetParams.self, from: req.paramsJSON) + let current = ExecApprovalsStore.ensureFile() + let snapshot = ExecApprovalsStore.readSnapshot() + if snapshot.exists { + if snapshot.hash.isEmpty { + return Self.errorResponse( + req, + code: .invalidRequest, + message: "INVALID_REQUEST: exec approvals base hash unavailable; reload and retry") + } + let baseHash = params.baseHash?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + if baseHash.isEmpty { + return Self.errorResponse( + req, + code: .invalidRequest, + message: "INVALID_REQUEST: exec approvals base hash required; reload and retry") + } + if baseHash != snapshot.hash { + return Self.errorResponse( + req, + code: .invalidRequest, + message: "INVALID_REQUEST: exec approvals changed; reload and retry") + } + } + + var normalized = ExecApprovalsStore.normalizeIncoming(params.file) + let socketPath = normalized.socket?.path?.trimmingCharacters(in: .whitespacesAndNewlines) + let token = normalized.socket?.token?.trimmingCharacters(in: .whitespacesAndNewlines) + let resolvedPath = (socketPath?.isEmpty == false) + ? socketPath! + : current.socket?.path?.trimmingCharacters(in: .whitespacesAndNewlines) ?? + ExecApprovalsStore.socketPath() + let resolvedToken = (token?.isEmpty == false) + ? token! + : current.socket?.token?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + normalized.socket = ExecApprovalsSocketConfig(path: resolvedPath, token: resolvedToken) + + ExecApprovalsStore.saveFile(normalized) + let nextSnapshot = ExecApprovalsStore.readSnapshot() + let redacted = ExecApprovalsSnapshot( + path: nextSnapshot.path, + exists: nextSnapshot.exists, + hash: nextSnapshot.hash, + file: ExecApprovalsStore.redactForSnapshot(nextSnapshot.file)) + let payload = try Self.encodePayload(redacted) + return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: payload) + } + + private func emitExecEvent(_ event: String, payload: ExecEventPayload) async { + guard let sender = self.eventSender else { return } + guard let data = try? JSONEncoder().encode(payload), + let json = String(data: data, encoding: .utf8) + else { + return + } + await sender(event, json) + } + private func handleSystemNotify(_ req: BridgeInvokeRequest) async throws -> BridgeInvokeResponse { let params = try Self.decodeParams(ClawdbotSystemNotifyParams.self, from: req.paramsJSON) let title = params.title.trimmingCharacters(in: .whitespacesAndNewlines) @@ -561,10 +827,12 @@ actor MacNodeRuntime { return BridgeInvokeResponse(id: req.id, ok: true) } } +} +extension MacNodeRuntime { private static func decodeParams(_ type: T.Type, from json: String?) throws -> T { guard let json, let data = json.data(using: .utf8) else { - throw NSError(domain: "Bridge", code: 20, userInfo: [ + throw NSError(domain: "Gateway", code: 20, userInfo: [ NSLocalizedDescriptionKey: "INVALID_REQUEST: paramsJSON required", ]) } @@ -589,10 +857,6 @@ actor MacNodeRuntime { UserDefaults.standard.object(forKey: cameraEnabledKey) as? Bool ?? false } - private nonisolated static func systemRunPolicy() -> SystemRunPolicy { - SystemRunPolicy.load() - } - private static let blockedEnvKeys: Set = [ "PATH", "NODE_OPTIONS", diff --git a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeRuntimeMainActorServices.swift b/apps/macos/Sources/Clawdbot/NodeMode/MacNodeRuntimeMainActorServices.swift index 5f5008713..a6e03e3e3 100644 --- a/apps/macos/Sources/Clawdbot/NodeMode/MacNodeRuntimeMainActorServices.swift +++ b/apps/macos/Sources/Clawdbot/NodeMode/MacNodeRuntimeMainActorServices.swift @@ -1,14 +1,7 @@ -import AppKit import ClawdbotKit import CoreLocation import Foundation -enum SystemRunDecision: Sendable { - case allowOnce - case allowAlways - case deny -} - @MainActor protocol MacNodeRuntimeMainActorServices: Sendable { func recordScreen( @@ -24,8 +17,6 @@ protocol MacNodeRuntimeMainActorServices: Sendable { desiredAccuracy: ClawdbotLocationAccuracy, maxAgeMs: Int?, timeoutMs: Int?) async throws -> CLLocation - - func confirmSystemRun(command: String, cwd: String?) async -> SystemRunDecision } @MainActor @@ -66,31 +57,4 @@ final class LiveMacNodeRuntimeMainActorServices: MacNodeRuntimeMainActorServices maxAgeMs: maxAgeMs, timeoutMs: timeoutMs) } - - func confirmSystemRun(command: String, cwd: String?) async -> SystemRunDecision { - let alert = NSAlert() - alert.alertStyle = .warning - alert.messageText = "Allow this command?" - - var details = "Clawdbot wants to run:\n\n\(command)" - let trimmedCwd = cwd?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - if !trimmedCwd.isEmpty { - details += "\n\nWorking directory:\n\(trimmedCwd)" - } - details += "\n\nThis runs on this Mac via node mode." - alert.informativeText = details - - alert.addButton(withTitle: "Allow Once") - alert.addButton(withTitle: "Always Allow") - alert.addButton(withTitle: "Don't Allow") - - switch alert.runModal() { - case .alertFirstButtonReturn: - return .allowOnce - case .alertSecondButtonReturn: - return .allowAlways - default: - return .deny - } - } } diff --git a/apps/macos/Sources/Clawdbot/NodePairingApprovalPrompter.swift b/apps/macos/Sources/Clawdbot/NodePairingApprovalPrompter.swift index 01f0879a5..b3f7e9295 100644 --- a/apps/macos/Sources/Clawdbot/NodePairingApprovalPrompter.swift +++ b/apps/macos/Sources/Clawdbot/NodePairingApprovalPrompter.swift @@ -1,6 +1,7 @@ import AppKit import ClawdbotDiscovery import ClawdbotIPC +import ClawdbotKit import ClawdbotProtocol import Foundation import Observation @@ -543,7 +544,7 @@ final class NodePairingApprovalPrompter { try? await Task.sleep(nanoseconds: 200_000_000) } - let preferred = BridgeDiscoveryPreferences.preferredStableID() + let preferred = GatewayDiscoveryPreferences.preferredStableID() let gateway = model.gateways.first { $0.stableID == preferred } ?? model.gateways.first guard let gateway else { return nil } let host = (gateway.tailnetDns?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? @@ -580,11 +581,10 @@ final class NodePairingApprovalPrompter { process.standardError = pipe do { - try process.run() + _ = try process.runAndReadToEnd(from: pipe) } catch { return false } - process.waitUntilExit() return process.terminationStatus == 0 }.value } diff --git a/apps/macos/Sources/Clawdbot/NodeServiceManager.swift b/apps/macos/Sources/Clawdbot/NodeServiceManager.swift new file mode 100644 index 000000000..2dd62d1e6 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/NodeServiceManager.swift @@ -0,0 +1,150 @@ +import Foundation +import OSLog + +enum NodeServiceManager { + private static let logger = Logger(subsystem: "com.clawdbot", category: "node.service") + + static func start() async -> String? { + let result = await self.runServiceCommandResult( + ["node", "start"], + timeout: 20, + quiet: false) + if let error = self.errorMessage(from: result, treatNotLoadedAsError: true) { + self.logger.error("node service start failed: \(error, privacy: .public)") + return error + } + return nil + } + + static func stop() async -> String? { + let result = await self.runServiceCommandResult( + ["node", "stop"], + timeout: 15, + quiet: false) + if let error = self.errorMessage(from: result, treatNotLoadedAsError: false) { + self.logger.error("node service stop failed: \(error, privacy: .public)") + return error + } + return nil + } +} + +extension NodeServiceManager { + private struct CommandResult { + let success: Bool + let payload: Data? + let message: String? + let parsed: ParsedServiceJson? + } + + private struct ParsedServiceJson { + let text: String + let object: [String: Any] + let ok: Bool? + let result: String? + let message: String? + let error: String? + let hints: [String] + } + + private static func runServiceCommandResult( + _ args: [String], + timeout: Double, + quiet: Bool) async -> CommandResult + { + let command = CommandResolver.clawdbotCommand( + subcommand: "service", + extraArgs: self.withJsonFlag(args), + // Service management must always run locally, even if remote mode is configured. + configRoot: ["gateway": ["mode": "local"]]) + var env = ProcessInfo.processInfo.environment + env["PATH"] = CommandResolver.preferredPaths().joined(separator: ":") + let response = await ShellExecutor.runDetailed(command: command, cwd: nil, env: env, timeout: timeout) + let parsed = self.parseServiceJson(from: response.stdout) ?? self.parseServiceJson(from: response.stderr) + let ok = parsed?.ok + let message = parsed?.error ?? parsed?.message + let payload = parsed?.text.data(using: .utf8) + ?? (response.stdout.isEmpty ? response.stderr : response.stdout).data(using: .utf8) + let success = ok ?? response.success + if success { + return CommandResult(success: true, payload: payload, message: nil, parsed: parsed) + } + + if quiet { + return CommandResult(success: false, payload: payload, message: message, parsed: parsed) + } + + let detail = message ?? self.summarize(response.stderr) ?? self.summarize(response.stdout) + let exit = response.exitCode.map { "exit \($0)" } ?? (response.errorMessage ?? "failed") + let fullMessage = detail.map { "Node service command failed (\(exit)): \($0)" } + ?? "Node service command failed (\(exit))" + self.logger.error("\(fullMessage, privacy: .public)") + return CommandResult(success: false, payload: payload, message: detail, parsed: parsed) + } + + private static func errorMessage(from result: CommandResult, treatNotLoadedAsError: Bool) -> String? { + if !result.success { + return result.message ?? "Node service command failed" + } + guard let parsed = result.parsed else { return nil } + if parsed.ok == false { + return self.mergeHints(message: parsed.error ?? parsed.message, hints: parsed.hints) + } + if treatNotLoadedAsError, parsed.result == "not-loaded" { + let base = parsed.message ?? "Node service not loaded." + return self.mergeHints(message: base, hints: parsed.hints) + } + return nil + } + + private static func withJsonFlag(_ args: [String]) -> [String] { + if args.contains("--json") { return args } + return args + ["--json"] + } + + private static func parseServiceJson(from raw: String) -> ParsedServiceJson? { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard let start = trimmed.firstIndex(of: "{"), + let end = trimmed.lastIndex(of: "}") + else { + return nil + } + let jsonText = String(trimmed[start...end]) + guard let data = jsonText.data(using: .utf8) else { return nil } + guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil } + let ok = object["ok"] as? Bool + let result = object["result"] as? String + let message = object["message"] as? String + let error = object["error"] as? String + let hints = (object["hints"] as? [String]) ?? [] + return ParsedServiceJson( + text: jsonText, + object: object, + ok: ok, + result: result, + message: message, + error: error, + hints: hints) + } + + private static func mergeHints(message: String?, hints: [String]) -> String? { + let trimmed = message?.trimmingCharacters(in: .whitespacesAndNewlines) + let nonEmpty = trimmed?.isEmpty == false ? trimmed : nil + guard !hints.isEmpty else { return nonEmpty } + let hintText = hints.prefix(2).joined(separator: " · ") + if let nonEmpty { + return "\(nonEmpty) (\(hintText))" + } + return hintText + } + + private static func summarize(_ text: String) -> String? { + let lines = text + .split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + guard let last = lines.last else { return nil } + let normalized = last.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression) + return normalized.count > 200 ? String(normalized.prefix(199)) + "…" : normalized + } +} diff --git a/apps/macos/Sources/Clawdbot/NodesMenu.swift b/apps/macos/Sources/Clawdbot/NodesMenu.swift index 3ba560aaf..f88177d8d 100644 --- a/apps/macos/Sources/Clawdbot/NodesMenu.swift +++ b/apps/macos/Sources/Clawdbot/NodesMenu.swift @@ -35,8 +35,9 @@ struct NodeMenuEntryFormatter { if let platform = self.platformText(entry) { parts.append("platform \(platform)") } - if let version = entry.version?.nonEmpty { - parts.append("app \(self.compactVersion(version))") + let versionLabels = self.versionLabels(entry) + if !versionLabels.isEmpty { + parts.append(versionLabels.joined(separator: " · ")) } parts.append("status \(self.roleText(entry))") return parts.joined(separator: " · ") @@ -60,8 +61,9 @@ struct NodeMenuEntryFormatter { } static func detailRightVersion(_ entry: NodeInfo) -> String? { - guard let version = entry.version?.nonEmpty else { return nil } - return self.shortVersionLabel(version) + let labels = self.versionLabels(entry, compact: false) + if labels.isEmpty { return nil } + return labels.joined(separator: " · ") } static func platformText(_ entry: NodeInfo) -> String? { @@ -127,6 +129,39 @@ struct NodeMenuEntryFormatter { return compact } + private static func versionLabels(_ entry: NodeInfo, compact: Bool = true) -> [String] { + let (core, ui) = self.resolveVersions(entry) + var labels: [String] = [] + if let core { + let label = compact ? self.compactVersion(core) : self.shortVersionLabel(core) + labels.append("core \(label)") + } + if let ui { + let label = compact ? self.compactVersion(ui) : self.shortVersionLabel(ui) + labels.append("ui \(label)") + } + return labels + } + + private static func resolveVersions(_ entry: NodeInfo) -> (core: String?, ui: String?) { + let core = entry.coreVersion?.nonEmpty + let ui = entry.uiVersion?.nonEmpty + if core != nil || ui != nil { + return (core, ui) + } + guard let legacy = entry.version?.nonEmpty else { return (nil, nil) } + if self.isHeadlessPlatform(entry) { + return (legacy, nil) + } + return (nil, legacy) + } + + private static func isHeadlessPlatform(_ entry: NodeInfo) -> Bool { + let raw = entry.platform?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() ?? "" + if raw == "darwin" || raw == "linux" || raw == "win32" || raw == "windows" { return true } + return false + } + static func leadingSymbol(_ entry: NodeInfo) -> String { if self.isGateway(entry) { return self.safeSystemSymbol( diff --git a/apps/macos/Sources/Clawdbot/NodesStore.swift b/apps/macos/Sources/Clawdbot/NodesStore.swift index 24501bc6f..51d43336d 100644 --- a/apps/macos/Sources/Clawdbot/NodesStore.swift +++ b/apps/macos/Sources/Clawdbot/NodesStore.swift @@ -7,6 +7,8 @@ struct NodeInfo: Identifiable, Codable { let displayName: String? let platform: String? let version: String? + let coreVersion: String? + let uiVersion: String? let deviceFamily: String? let modelIdentifier: String? let remoteIp: String? diff --git a/apps/macos/Sources/Clawdbot/Onboarding.swift b/apps/macos/Sources/Clawdbot/Onboarding.swift index 0af5e94e5..f45eee8ce 100644 --- a/apps/macos/Sources/Clawdbot/Onboarding.swift +++ b/apps/macos/Sources/Clawdbot/Onboarding.swift @@ -155,7 +155,7 @@ struct OnboardingView: View { var canAdvance: Bool { !self.isWizardBlocking } var devLinkCommand: String { - let version = GatewayEnvironment.expectedGatewayVersion()?.description ?? "latest" + let version = GatewayEnvironment.expectedGatewayVersionString() ?? "latest" return "npm install -g clawdbot@\(version)" } diff --git a/apps/macos/Sources/Clawdbot/OnboardingView+Actions.swift b/apps/macos/Sources/Clawdbot/OnboardingView+Actions.swift index b84ca5e8d..874ae28a2 100644 --- a/apps/macos/Sources/Clawdbot/OnboardingView+Actions.swift +++ b/apps/macos/Sources/Clawdbot/OnboardingView+Actions.swift @@ -9,7 +9,7 @@ extension OnboardingView { self.state.connectionMode = .local self.preferredGatewayID = nil self.showAdvancedConnection = false - BridgeDiscoveryPreferences.setPreferredStableID(nil) + GatewayDiscoveryPreferences.setPreferredStableID(nil) } func selectUnconfiguredGateway() { @@ -17,15 +17,19 @@ extension OnboardingView { self.state.connectionMode = .unconfigured self.preferredGatewayID = nil self.showAdvancedConnection = false - BridgeDiscoveryPreferences.setPreferredStableID(nil) + GatewayDiscoveryPreferences.setPreferredStableID(nil) } func selectRemoteGateway(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) { Task { await self.onboardingWizard.cancelIfRunning() } self.preferredGatewayID = gateway.stableID - BridgeDiscoveryPreferences.setPreferredStableID(gateway.stableID) + GatewayDiscoveryPreferences.setPreferredStableID(gateway.stableID) - if let host = gateway.tailnetDns ?? gateway.lanHost { + if self.state.remoteTransport == .direct { + if let url = GatewayDiscoveryHelpers.directUrl(for: gateway) { + self.state.remoteUrl = url + } + } else if let host = GatewayDiscoveryHelpers.sanitizedTailnetHost(gateway.tailnetDns) ?? gateway.lanHost { let user = NSUserName() self.state.remoteTarget = GatewayDiscoveryModel.buildSSHTarget( user: user, @@ -36,7 +40,7 @@ extension OnboardingView { self.state.remoteCliPath = gateway.cliPath ?? "" self.state.connectionMode = .remote - MacNodeModeCoordinator.shared.setPreferredBridgeStableID(gateway.stableID) + MacNodeModeCoordinator.shared.setPreferredGatewayStableID(gateway.stableID) } func openSettings(tab: SettingsTab) { diff --git a/apps/macos/Sources/Clawdbot/OnboardingView+Layout.swift b/apps/macos/Sources/Clawdbot/OnboardingView+Layout.swift index f369b12af..1fb1e65a0 100644 --- a/apps/macos/Sources/Clawdbot/OnboardingView+Layout.swift +++ b/apps/macos/Sources/Clawdbot/OnboardingView+Layout.swift @@ -63,7 +63,7 @@ extension OnboardingView { await self.ensureDefaultWorkspace() self.refreshAnthropicOAuthStatus() self.refreshBootstrapStatus() - self.preferredGatewayID = BridgeDiscoveryPreferences.preferredStableID() + self.preferredGatewayID = GatewayDiscoveryPreferences.preferredStableID() } } @@ -210,6 +210,7 @@ extension OnboardingView { title: String, subtitle: String, systemImage: String, + buttonTitle: String, action: @escaping () -> Void) -> some View { HStack(alignment: .top, spacing: 12) { @@ -222,7 +223,7 @@ extension OnboardingView { Text(subtitle) .font(.subheadline) .foregroundStyle(.secondary) - Button("Open Settings → Skills", action: action) + Button(buttonTitle, action: action) .buttonStyle(.link) .padding(.top, 2) } diff --git a/apps/macos/Sources/Clawdbot/OnboardingView+Pages.swift b/apps/macos/Sources/Clawdbot/OnboardingView+Pages.swift index 4ad376db7..5c5eead34 100644 --- a/apps/macos/Sources/Clawdbot/OnboardingView+Pages.swift +++ b/apps/macos/Sources/Clawdbot/OnboardingView+Pages.swift @@ -77,7 +77,7 @@ extension OnboardingView { .font(.largeTitle.weight(.semibold)) Text( "Clawdbot uses a single Gateway that stays running. Pick this Mac, " + - "connect to a discovered bridge nearby for pairing, or configure later.") + "connect to a discovered gateway nearby, or configure later.") .font(.body) .foregroundStyle(.secondary) .multilineTextAlignment(.center) @@ -126,13 +126,13 @@ extension OnboardingView { } if self.gatewayDiscovery.gateways.isEmpty { - Text("Searching for nearby bridges…") + Text("Searching for nearby gateways…") .font(.caption) .foregroundStyle(.secondary) .padding(.leading, 4) } else { VStack(alignment: .leading, spacing: 6) { - Text("Nearby bridges (pairing only)") + Text("Nearby gateways") .font(.caption) .foregroundStyle(.secondary) .padding(.leading, 4) @@ -177,42 +177,67 @@ extension OnboardingView { VStack(alignment: .leading, spacing: 10) { Grid(alignment: .leading, horizontalSpacing: 12, verticalSpacing: 8) { GridRow { - Text("SSH target") + Text("Transport") .font(.callout.weight(.semibold)) .frame(width: labelWidth, alignment: .leading) - TextField("user@host[:port]", text: self.$state.remoteTarget) - .textFieldStyle(.roundedBorder) - .frame(width: fieldWidth) + Picker("Transport", selection: self.$state.remoteTransport) { + Text("SSH tunnel").tag(AppState.RemoteTransport.ssh) + Text("Direct (ws/wss)").tag(AppState.RemoteTransport.direct) + } + .pickerStyle(.segmented) + .frame(width: fieldWidth) } - GridRow { - Text("Identity file") - .font(.callout.weight(.semibold)) - .frame(width: labelWidth, alignment: .leading) - TextField("/Users/you/.ssh/id_ed25519", text: self.$state.remoteIdentity) - .textFieldStyle(.roundedBorder) - .frame(width: fieldWidth) + if self.state.remoteTransport == .direct { + GridRow { + Text("Gateway URL") + .font(.callout.weight(.semibold)) + .frame(width: labelWidth, alignment: .leading) + TextField("wss://gateway.example.ts.net", text: self.$state.remoteUrl) + .textFieldStyle(.roundedBorder) + .frame(width: fieldWidth) + } } - GridRow { - Text("Project root") - .font(.callout.weight(.semibold)) - .frame(width: labelWidth, alignment: .leading) - TextField("/home/you/Projects/clawdbot", text: self.$state.remoteProjectRoot) - .textFieldStyle(.roundedBorder) - .frame(width: fieldWidth) - } - GridRow { - Text("CLI path") - .font(.callout.weight(.semibold)) - .frame(width: labelWidth, alignment: .leading) - TextField( - "/Applications/Clawdbot.app/.../clawdbot", - text: self.$state.remoteCliPath) - .textFieldStyle(.roundedBorder) - .frame(width: fieldWidth) + if self.state.remoteTransport == .ssh { + GridRow { + Text("SSH target") + .font(.callout.weight(.semibold)) + .frame(width: labelWidth, alignment: .leading) + TextField("user@host[:port]", text: self.$state.remoteTarget) + .textFieldStyle(.roundedBorder) + .frame(width: fieldWidth) + } + GridRow { + Text("Identity file") + .font(.callout.weight(.semibold)) + .frame(width: labelWidth, alignment: .leading) + TextField("/Users/you/.ssh/id_ed25519", text: self.$state.remoteIdentity) + .textFieldStyle(.roundedBorder) + .frame(width: fieldWidth) + } + GridRow { + Text("Project root") + .font(.callout.weight(.semibold)) + .frame(width: labelWidth, alignment: .leading) + TextField("/home/you/Projects/clawdbot", text: self.$state.remoteProjectRoot) + .textFieldStyle(.roundedBorder) + .frame(width: fieldWidth) + } + GridRow { + Text("CLI path") + .font(.callout.weight(.semibold)) + .frame(width: labelWidth, alignment: .leading) + TextField( + "/Applications/Clawdbot.app/.../clawdbot", + text: self.$state.remoteCliPath) + .textFieldStyle(.roundedBorder) + .frame(width: fieldWidth) + } } } - Text("Tip: keep Tailscale enabled so your gateway stays reachable.") + Text(self.state.remoteTransport == .direct + ? "Tip: use Tailscale Serve so the gateway has a valid HTTPS cert." + : "Tip: keep Tailscale enabled so your gateway stays reachable.") .font(.footnote) .foregroundStyle(.secondary) .lineLimit(1) @@ -225,16 +250,19 @@ extension OnboardingView { } func gatewaySubtitle(for gateway: GatewayDiscoveryModel.DiscoveredGateway) -> String? { - if let host = gateway.tailnetDns ?? gateway.lanHost { + if self.state.remoteTransport == .direct { + return GatewayDiscoveryHelpers.directUrl(for: gateway) ?? "Gateway pairing only" + } + if let host = GatewayDiscoveryHelpers.sanitizedTailnetHost(gateway.tailnetDns) ?? gateway.lanHost { let portSuffix = gateway.sshPort != 22 ? " · ssh \(gateway.sshPort)" : "" return "\(host)\(portSuffix)" } - return "Bridge pairing only" + return "Gateway pairing only" } func isSelectedGateway(_ gateway: GatewayDiscoveryModel.DiscoveredGateway) -> Bool { guard self.state.connectionMode == .remote else { return false } - let preferred = self.preferredGatewayID ?? BridgeDiscoveryPreferences.preferredStableID() + let preferred = self.preferredGatewayID ?? GatewayDiscoveryPreferences.preferredStableID() return preferred == gateway.stableID } @@ -694,10 +722,11 @@ extension OnboardingView { systemImage: "bubble.left.and.bubble.right") self.featureActionRow( title: "Connect WhatsApp or Telegram", - subtitle: "Open Settings → Connections to link channels and monitor status.", - systemImage: "link") + subtitle: "Open Settings → Channels to link channels and monitor status.", + systemImage: "link", + buttonTitle: "Open Settings → Channels") { - self.openSettings(tab: .connections) + self.openSettings(tab: .channels) } self.featureRow( title: "Try Voice Wake", @@ -711,7 +740,8 @@ extension OnboardingView { self.featureActionRow( title: "Give your agent more powers", subtitle: "Enable optional skills (Peekaboo, oracle, camsnap, …) from Settings → Skills.", - systemImage: "sparkles") + systemImage: "sparkles", + buttonTitle: "Open Settings → Skills") { self.openSettings(tab: .skills) } diff --git a/apps/macos/Sources/Clawdbot/OnboardingView+Testing.swift b/apps/macos/Sources/Clawdbot/OnboardingView+Testing.swift index f7a5920e4..33726b7c4 100644 --- a/apps/macos/Sources/Clawdbot/OnboardingView+Testing.swift +++ b/apps/macos/Sources/Clawdbot/OnboardingView+Testing.swift @@ -9,14 +9,14 @@ extension OnboardingView { let discovery = GatewayDiscoveryModel(localDisplayName: InstanceIdentity.displayName) discovery.statusText = "Searching..." let gateway = GatewayDiscoveryModel.DiscoveredGateway( - displayName: "Test Bridge", - lanHost: "bridge.local", - tailnetDns: "bridge.ts.net", + displayName: "Test Gateway", + lanHost: "gateway.local", + tailnetDns: "gateway.ts.net", sshPort: 2222, gatewayPort: 18789, cliPath: "/usr/local/bin/clawdbot", - stableID: "bridge-1", - debugID: "bridge-1", + stableID: "gateway-1", + debugID: "gateway-1", isLocal: false) discovery.gateways = [gateway] @@ -78,6 +78,7 @@ extension OnboardingView { title: "Action", subtitle: "Action subtitle", systemImage: "gearshape", + buttonTitle: "Action", action: {}) _ = view.gatewaySubtitle(for: gateway) _ = view.isSelectedGateway(gateway) diff --git a/apps/macos/Sources/Clawdbot/OnboardingWizard.swift b/apps/macos/Sources/Clawdbot/OnboardingWizard.swift index dc37ac86b..e9d071328 100644 --- a/apps/macos/Sources/Clawdbot/OnboardingWizard.swift +++ b/apps/macos/Sources/Clawdbot/OnboardingWizard.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import ClawdbotProtocol import Foundation import Observation @@ -216,7 +217,7 @@ final class OnboardingWizardModel { struct OnboardingWizardStepView: View { let step: WizardStep let isSubmitting: Bool - let onSubmit: (AnyCodable?) -> Void + let onStepSubmit: (AnyCodable?) -> Void @State private var textValue: String @State private var confirmValue: Bool @@ -228,7 +229,7 @@ struct OnboardingWizardStepView: View { init(step: WizardStep, isSubmitting: Bool, onSubmit: @escaping (AnyCodable?) -> Void) { self.step = step self.isSubmitting = isSubmitting - self.onSubmit = onSubmit + self.onStepSubmit = onSubmit let options = parseWizardOptions(step.options).enumerated().map { index, option in WizardOptionItem(index: index, option: option) } @@ -378,27 +379,27 @@ struct OnboardingWizardStepView: View { private func submit() { switch wizardStepType(self.step) { case "note", "progress": - self.onSubmit(nil) + self.onStepSubmit(nil) case "text": - self.onSubmit(AnyCodable(self.textValue)) + self.onStepSubmit(AnyCodable(self.textValue)) case "confirm": - self.onSubmit(AnyCodable(self.confirmValue)) + self.onStepSubmit(AnyCodable(self.confirmValue)) case "select": guard self.optionItems.indices.contains(self.selectedIndex) else { - self.onSubmit(nil) + self.onStepSubmit(nil) return } let option = self.optionItems[self.selectedIndex].option - self.onSubmit(bridgeToLocal(option.value) ?? AnyCodable(option.label)) + self.onStepSubmit(bridgeToLocal(option.value) ?? AnyCodable(option.label)) case "multiselect": let values = self.optionItems .filter { self.selectedIndices.contains($0.index) } .map { bridgeToLocal($0.option.value) ?? AnyCodable($0.option.label) } - self.onSubmit(AnyCodable(values)) + self.onStepSubmit(AnyCodable(values)) case "action": - self.onSubmit(AnyCodable(true)) + self.onStepSubmit(AnyCodable(true)) default: - self.onSubmit(nil) + self.onStepSubmit(nil) } } } diff --git a/apps/macos/Sources/Clawdbot/PermissionsSettings.swift b/apps/macos/Sources/Clawdbot/PermissionsSettings.swift index d7ee5339c..f5a926032 100644 --- a/apps/macos/Sources/Clawdbot/PermissionsSettings.swift +++ b/apps/macos/Sources/Clawdbot/PermissionsSettings.swift @@ -1,4 +1,6 @@ import ClawdbotIPC +import ClawdbotKit +import CoreLocation import SwiftUI struct PermissionsSettings: View { @@ -8,6 +10,8 @@ struct PermissionsSettings: View { var body: some View { VStack(alignment: .leading, spacing: 14) { + SystemRunSettingsView() + Text("Allow these so Clawdbot can notify and capture when needed.") .padding(.top, 4) @@ -15,6 +19,8 @@ struct PermissionsSettings: View { .padding(.horizontal, 2) .padding(.vertical, 6) + LocationAccessSettings() + Button("Restart onboarding") { self.showOnboarding() } .buttonStyle(.bordered) Spacer() @@ -24,6 +30,72 @@ struct PermissionsSettings: View { } } +private struct LocationAccessSettings: View { + @AppStorage(locationModeKey) private var locationModeRaw: String = ClawdbotLocationMode.off.rawValue + @AppStorage(locationPreciseKey) private var locationPreciseEnabled: Bool = true + @State private var lastLocationModeRaw: String = ClawdbotLocationMode.off.rawValue + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + Text("Location Access") + .font(.body) + + Picker("", selection: self.$locationModeRaw) { + Text("Off").tag(ClawdbotLocationMode.off.rawValue) + Text("While Using").tag(ClawdbotLocationMode.whileUsing.rawValue) + Text("Always").tag(ClawdbotLocationMode.always.rawValue) + } + .labelsHidden() + .pickerStyle(.menu) + + Toggle("Precise Location", isOn: self.$locationPreciseEnabled) + .disabled(self.locationMode == .off) + + Text("Always may require System Settings to approve background location.") + .font(.footnote) + .foregroundStyle(.tertiary) + .fixedSize(horizontal: false, vertical: true) + } + .onAppear { + self.lastLocationModeRaw = self.locationModeRaw + } + .onChange(of: self.locationModeRaw) { _, newValue in + let previous = self.lastLocationModeRaw + self.lastLocationModeRaw = newValue + guard let mode = ClawdbotLocationMode(rawValue: newValue) else { return } + Task { + let granted = await self.requestLocationAuthorization(mode: mode) + if !granted { + await MainActor.run { + self.locationModeRaw = previous + self.lastLocationModeRaw = previous + } + } + } + } + } + + private var locationMode: ClawdbotLocationMode { + ClawdbotLocationMode(rawValue: self.locationModeRaw) ?? .off + } + + private func requestLocationAuthorization(mode: ClawdbotLocationMode) async -> Bool { + guard mode != .off else { return true } + guard CLLocationManager.locationServicesEnabled() else { + await MainActor.run { LocationPermissionHelper.openSettings() } + return false + } + + let status = CLLocationManager().authorizationStatus + let requireAlways = mode == .always + if PermissionManager.isLocationAuthorized(status: status, requireAlways: requireAlways) { + return true + } + let updated = await LocationPermissionRequester.shared.request(always: requireAlways) + return PermissionManager.isLocationAuthorized(status: updated, requireAlways: requireAlways) + } +} + struct PermissionStatusList: View { let status: [Capability: Bool] let refresh: () async -> Void @@ -45,25 +117,6 @@ struct PermissionStatusList: View { .font(.footnote) .padding(.top, 2) .help("Refresh status") - - if (self.status[.accessibility] ?? false) == false || (self.status[.screenRecording] ?? false) == false { - VStack(alignment: .leading, spacing: 8) { - Text( - "Note: macOS may require restarting Clawdbot after enabling Accessibility or Screen Recording.") - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - - Button { - LaunchdManager.startClawdbot() - } label: { - Label("Restart Clawdbot", systemImage: "arrow.counterclockwise") - } - .buttonStyle(.bordered) - .controlSize(.small) - } - .padding(.top, 4) - } } } diff --git a/apps/macos/Sources/Clawdbot/PortGuardian.swift b/apps/macos/Sources/Clawdbot/PortGuardian.swift index fb9adf52b..422300d59 100644 --- a/apps/macos/Sources/Clawdbot/PortGuardian.swift +++ b/apps/macos/Sources/Clawdbot/PortGuardian.swift @@ -24,7 +24,7 @@ actor PortGuardian { private var records: [Record] = [] private let logger = Logger(subsystem: "com.clawdbot", category: "portguard") private nonisolated static let appSupportDir: URL = { - let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! + let base = FileManager().urls(for: .applicationSupportDirectory, in: .userDomainMask).first! return base.appendingPathComponent("Clawdbot", isDirectory: true) }() @@ -71,7 +71,7 @@ actor PortGuardian { } func record(port: Int, pid: Int32, command: String, mode: AppState.ConnectionMode) async { - try? FileManager.default.createDirectory(at: Self.appSupportDir, withIntermediateDirectories: true) + try? FileManager().createDirectory(at: Self.appSupportDir, withIntermediateDirectories: true) self.records.removeAll { $0.pid == pid } self.records.append( Record( @@ -184,6 +184,14 @@ actor PortGuardian { } } + func isListening(port: Int, pid: Int32? = nil) async -> Bool { + let listeners = await self.listeners(on: port) + if let pid { + return listeners.contains(where: { $0.pid == pid }) + } + return !listeners.isEmpty + } + private func listeners(on port: Int) async -> [Listener] { let res = await ShellExecutor.run( command: ["lsof", "-nP", "-iTCP:\(port)", "-sTCP:LISTEN", "-Fpcn"], @@ -203,15 +211,13 @@ actor PortGuardian { proc.standardOutput = pipe proc.standardError = Pipe() do { - try proc.run() - proc.waitUntilExit() + let data = try proc.runAndReadToEnd(from: pipe) + guard !data.isEmpty else { return nil } + return String(data: data, encoding: .utf8)? + .trimmingCharacters(in: .whitespacesAndNewlines) } catch { return nil } - let data = pipe.fileHandleForReading.readToEndSafely() - guard !data.isEmpty else { return nil } - return String(data: data, encoding: .utf8)? - .trimmingCharacters(in: .whitespacesAndNewlines) } private static func parseListeners(from text: String) -> [Listener] { diff --git a/apps/macos/Sources/Clawdbot/Process+PipeRead.swift b/apps/macos/Sources/Clawdbot/Process+PipeRead.swift new file mode 100644 index 000000000..7c0f7fe0c --- /dev/null +++ b/apps/macos/Sources/Clawdbot/Process+PipeRead.swift @@ -0,0 +1,11 @@ +import Foundation + +extension Process { + /// Runs the process and drains the given pipe before waiting to avoid blocking on full buffers. + func runAndReadToEnd(from pipe: Pipe) throws -> Data { + try self.run() + let data = pipe.fileHandleForReading.readToEndSafely() + self.waitUntilExit() + return data + } +} diff --git a/apps/macos/Sources/Clawdbot/RemotePortTunnel.swift b/apps/macos/Sources/Clawdbot/RemotePortTunnel.swift index ccbeb6e8d..8eaee1c05 100644 --- a/apps/macos/Sources/Clawdbot/RemotePortTunnel.swift +++ b/apps/macos/Sources/Clawdbot/RemotePortTunnel.swift @@ -72,7 +72,6 @@ final class RemotePortTunnel { } var args: [String] = [ "-o", "BatchMode=yes", - "-o", "IdentitiesOnly=yes", "-o", "ExitOnForwardFailure=yes", "-o", "StrictHostKeyChecking=accept-new", "-o", "UpdateHostKeys=yes", @@ -84,7 +83,12 @@ final class RemotePortTunnel { ] if parsed.port > 0 { args.append(contentsOf: ["-p", String(parsed.port)]) } let identity = settings.identity.trimmingCharacters(in: .whitespacesAndNewlines) - if !identity.isEmpty { args.append(contentsOf: ["-i", identity]) } + if !identity.isEmpty { + // Only use IdentitiesOnly when an explicit identity file is provided. + // This allows 1Password SSH agent and other SSH agents to provide keys. + args.append(contentsOf: ["-o", "IdentitiesOnly=yes"]) + args.append(contentsOf: ["-i", identity]) + } let userHost = parsed.user.map { "\($0)@\(parsed.host)" } ?? parsed.host args.append(userHost) diff --git a/apps/macos/Sources/Clawdbot/RemoteTunnelManager.swift b/apps/macos/Sources/Clawdbot/RemoteTunnelManager.swift index 5e42fbd05..898b1b482 100644 --- a/apps/macos/Sources/Clawdbot/RemoteTunnelManager.swift +++ b/apps/macos/Sources/Clawdbot/RemoteTunnelManager.swift @@ -20,11 +20,13 @@ actor RemoteTunnelManager { tunnel.process.isRunning, let local = tunnel.localPort { - if await self.isTunnelHealthy(port: local) { + let pid = tunnel.process.processIdentifier + if await PortGuardian.shared.isListening(port: Int(local), pid: pid) { self.logger.info("reusing active SSH tunnel localPort=\(local, privacy: .public)") return local } - self.logger.error("active SSH tunnel on port \(local, privacy: .public) is unhealthy; restarting") + self.logger.error( + "active SSH tunnel on port \(local, privacy: .public) is not listening; restarting") await self.beginRestart() tunnel.terminate() self.controlTunnel = nil @@ -35,19 +37,11 @@ actor RemoteTunnelManager { if let desc = await PortGuardian.shared.describe(port: Int(desiredPort)), self.isSshProcess(desc) { - if await self.isTunnelHealthy(port: desiredPort) { - self.logger.info( - "reusing existing SSH tunnel listener " + - "localPort=\(desiredPort, privacy: .public) " + - "pid=\(desc.pid, privacy: .public)") - return desiredPort - } - if self.restartInFlight { - self.logger.info("control tunnel restart in flight; skip stale tunnel cleanup") - return nil - } - await self.beginRestart() - await self.cleanupStaleTunnel(desc: desc, port: desiredPort) + self.logger.info( + "reusing existing SSH tunnel listener " + + "localPort=\(desiredPort, privacy: .public) " + + "pid=\(desc.pid, privacy: .public)") + return desiredPort } return nil } @@ -88,10 +82,6 @@ actor RemoteTunnelManager { self.controlTunnel = nil } - private func isTunnelHealthy(port: UInt16) async -> Bool { - await PortGuardian.shared.probeGatewayHealth(port: Int(port)) - } - private func isSshProcess(_ desc: PortGuardian.Descriptor) -> Bool { let cmd = desc.command.lowercased() if cmd.contains("ssh") { return true } @@ -128,21 +118,5 @@ actor RemoteTunnelManager { try? await Task.sleep(nanoseconds: UInt64(remaining * 1_000_000_000)) } - private func cleanupStaleTunnel(desc: PortGuardian.Descriptor, port: UInt16) async { - let pid = desc.pid - self.logger.error( - "stale SSH tunnel detected on port \(port, privacy: .public) pid \(pid, privacy: .public)") - let killed = await self.kill(pid: pid) - if !killed { - self.logger.error("failed to terminate stale SSH tunnel pid \(pid, privacy: .public)") - } - await PortGuardian.shared.removeRecord(pid: pid) - } - - private func kill(pid: Int32) async -> Bool { - let term = await ShellExecutor.run(command: ["kill", "-TERM", "\(pid)"], cwd: nil, env: nil, timeout: 2) - if term.ok { return true } - let sigkill = await ShellExecutor.run(command: ["kill", "-KILL", "\(pid)"], cwd: nil, env: nil, timeout: 2) - return sigkill.ok - } + // Keep tunnel reuse lightweight; restart only when the listener disappears. } diff --git a/apps/macos/Sources/Clawdbot/Resources/DeviceModels/LICENSE.apple-device-identifiers.txt b/apps/macos/Sources/Clawdbot/Resources/DeviceModels/LICENSE.apple-device-identifiers.txt index 4592f65f5..d1b9e4b3c 100644 --- a/apps/macos/Sources/Clawdbot/Resources/DeviceModels/LICENSE.apple-device-identifiers.txt +++ b/apps/macos/Sources/Clawdbot/Resources/DeviceModels/LICENSE.apple-device-identifiers.txt @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/apps/macos/Sources/Clawdbot/Resources/DeviceModels/ios-device-identifiers.json b/apps/macos/Sources/Clawdbot/Resources/DeviceModels/ios-device-identifiers.json index 236ac2f0e..76caa5452 100644 --- a/apps/macos/Sources/Clawdbot/Resources/DeviceModels/ios-device-identifiers.json +++ b/apps/macos/Sources/Clawdbot/Resources/DeviceModels/ios-device-identifiers.json @@ -173,4 +173,4 @@ "iPod5,1": "iPod touch (5th generation)", "iPod7,1": "iPod touch (6th generation)", "iPod9,1": "iPod touch (7th generation)" -} \ No newline at end of file +} diff --git a/apps/macos/Sources/Clawdbot/Resources/DeviceModels/mac-device-identifiers.json b/apps/macos/Sources/Clawdbot/Resources/DeviceModels/mac-device-identifiers.json index 2b7483581..03d5a5ecc 100644 --- a/apps/macos/Sources/Clawdbot/Resources/DeviceModels/mac-device-identifiers.json +++ b/apps/macos/Sources/Clawdbot/Resources/DeviceModels/mac-device-identifiers.json @@ -211,4 +211,4 @@ "Mac Pro (2019)", "Mac Pro (Rack, 2019)" ] -} \ No newline at end of file +} diff --git a/apps/macos/Sources/Clawdbot/Resources/Info.plist b/apps/macos/Sources/Clawdbot/Resources/Info.plist index 77501e4d1..ee9e3113d 100644 --- a/apps/macos/Sources/Clawdbot/Resources/Info.plist +++ b/apps/macos/Sources/Clawdbot/Resources/Info.plist @@ -15,9 +15,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 2026.1.11-4 + 2026.1.25 CFBundleVersion - 202601113 + 202601250 CFBundleIconFile Clawdbot CFBundleURLTypes diff --git a/apps/macos/Sources/Clawdbot/RuntimeLocator.swift b/apps/macos/Sources/Clawdbot/RuntimeLocator.swift index 8fd47073f..aadbe2d21 100644 --- a/apps/macos/Sources/Clawdbot/RuntimeLocator.swift +++ b/apps/macos/Sources/Clawdbot/RuntimeLocator.swift @@ -111,7 +111,7 @@ enum RuntimeLocator { // MARK: - Internals private static func findExecutable(named name: String, searchPaths: [String]) -> String? { - let fm = FileManager.default + let fm = FileManager() for dir in searchPaths { let candidate = (dir as NSString).appendingPathComponent(name) if fm.isExecutableFile(atPath: candidate) { @@ -133,8 +133,7 @@ enum RuntimeLocator { process.standardError = pipe do { - try process.run() - process.waitUntilExit() + let data = try process.runAndReadToEnd(from: pipe) let elapsedMs = Int(Date().timeIntervalSince(start) * 1000) if elapsedMs > 500 { self.logger.warning( @@ -149,7 +148,6 @@ enum RuntimeLocator { bin=\(binary, privacy: .public) """) } - let data = pipe.fileHandleForReading.readToEndSafely() return String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) } catch { let elapsedMs = Int(Date().timeIntervalSince(start) * 1000) diff --git a/apps/macos/Sources/Clawdbot/ScreenRecordService.swift b/apps/macos/Sources/Clawdbot/ScreenRecordService.swift index d48538e26..e0878a5c9 100644 --- a/apps/macos/Sources/Clawdbot/ScreenRecordService.swift +++ b/apps/macos/Sources/Clawdbot/ScreenRecordService.swift @@ -42,10 +42,10 @@ final class ScreenRecordService { if let outPath, !outPath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return URL(fileURLWithPath: outPath) } - return FileManager.default.temporaryDirectory + return FileManager().temporaryDirectory .appendingPathComponent("clawdbot-screen-record-\(UUID().uuidString).mp4") }() - try? FileManager.default.removeItem(at: outURL) + try? FileManager().removeItem(at: outURL) let content = try await SCShareableContent.current let displays = content.displays.sorted { $0.displayID < $1.displayID } diff --git a/apps/macos/Sources/Clawdbot/SessionActions.swift b/apps/macos/Sources/Clawdbot/SessionActions.swift index 6315f08c7..6e11c93cb 100644 --- a/apps/macos/Sources/Clawdbot/SessionActions.swift +++ b/apps/macos/Sources/Clawdbot/SessionActions.swift @@ -66,12 +66,12 @@ enum SessionActions { let dir = URL(fileURLWithPath: storePath).deletingLastPathComponent() urls.append(dir.appendingPathComponent("\(sessionId).jsonl")) } - let home = FileManager.default.homeDirectoryForCurrentUser + let home = FileManager().homeDirectoryForCurrentUser urls.append(home.appendingPathComponent(".clawdbot/sessions/\(sessionId).jsonl")) return urls }() - let existing = candidates.first(where: { FileManager.default.fileExists(atPath: $0.path) }) + let existing = candidates.first(where: { FileManager().fileExists(atPath: $0.path) }) guard let url = existing else { let alert = NSAlert() alert.messageText = "Session log not found" diff --git a/apps/macos/Sources/Clawdbot/SessionData.swift b/apps/macos/Sources/Clawdbot/SessionData.swift index 7ce1dc8fc..d4c85a4a2 100644 --- a/apps/macos/Sources/Clawdbot/SessionData.swift +++ b/apps/macos/Sources/Clawdbot/SessionData.swift @@ -246,7 +246,7 @@ enum SessionLoader { static let fallbackContextTokens = 200_000 static let defaultStorePath = standardize( - FileManager.default.homeDirectoryForCurrentUser + FileManager().homeDirectoryForCurrentUser .appendingPathComponent(".clawdbot/sessions/sessions.json").path) static func loadSnapshot( diff --git a/apps/macos/Sources/Clawdbot/SessionMenuPreviewView.swift b/apps/macos/Sources/Clawdbot/SessionMenuPreviewView.swift index 76bf271fd..e7d81659e 100644 --- a/apps/macos/Sources/Clawdbot/SessionMenuPreviewView.swift +++ b/apps/macos/Sources/Clawdbot/SessionMenuPreviewView.swift @@ -1,15 +1,16 @@ import ClawdbotChatUI import ClawdbotKit +import ClawdbotProtocol import OSLog import SwiftUI -private struct SessionPreviewItem: Identifiable, Sendable { +struct SessionPreviewItem: Identifiable, Sendable { let id: String let role: PreviewRole let text: String } -private enum PreviewRole: String, Sendable { +enum PreviewRole: String, Sendable { case user case assistant case tool @@ -27,50 +28,107 @@ private enum PreviewRole: String, Sendable { } } -private actor SessionPreviewCache { +actor SessionPreviewCache { static let shared = SessionPreviewCache() private struct CacheEntry { - let items: [SessionPreviewItem] + let snapshot: SessionMenuPreviewSnapshot let updatedAt: Date } private var entries: [String: CacheEntry] = [:] - func cachedItems(for sessionKey: String, maxAge: TimeInterval) -> [SessionPreviewItem]? { + func cachedSnapshot(for sessionKey: String, maxAge: TimeInterval) -> SessionMenuPreviewSnapshot? { guard let entry = self.entries[sessionKey] else { return nil } guard Date().timeIntervalSince(entry.updatedAt) < maxAge else { return nil } - return entry.items + return entry.snapshot } - func store(items: [SessionPreviewItem], for sessionKey: String) { - self.entries[sessionKey] = CacheEntry(items: items, updatedAt: Date()) + func store(snapshot: SessionMenuPreviewSnapshot, for sessionKey: String) { + self.entries[sessionKey] = CacheEntry(snapshot: snapshot, updatedAt: Date()) } - func lastItems(for sessionKey: String) -> [SessionPreviewItem]? { - self.entries[sessionKey]?.items + func lastSnapshot(for sessionKey: String) -> SessionMenuPreviewSnapshot? { + self.entries[sessionKey]?.snapshot } } -struct SessionMenuPreviewView: View { - private static let logger = Logger(subsystem: "com.clawdbot", category: "SessionPreview") - private static let previewTimeoutSeconds: Double = 4 +actor SessionPreviewLimiter { + static let shared = SessionPreviewLimiter(maxConcurrent: 2) - let sessionKey: String - let width: CGFloat - let maxItems: Int - let maxLines: Int - let title: String + private let maxConcurrent: Int + private var available: Int + private var waitQueue: [UUID] = [] + private var waiters: [UUID: CheckedContinuation] = [:] - @Environment(\.menuItemHighlighted) private var isHighlighted - @State private var items: [SessionPreviewItem] = [] - @State private var status: LoadStatus = .loading - - private struct PreviewTimeoutError: LocalizedError { - var errorDescription: String? { "preview timeout" } + init(maxConcurrent: Int) { + let normalized = max(1, maxConcurrent) + self.maxConcurrent = normalized + self.available = normalized } - private enum LoadStatus: Equatable { + func withPermit(_ operation: () async throws -> T) async throws -> T { + await self.acquire() + defer { self.release() } + if Task.isCancelled { throw CancellationError() } + return try await operation() + } + + private func acquire() async { + if self.available > 0 { + self.available -= 1 + return + } + let id = UUID() + await withCheckedContinuation { cont in + self.waitQueue.append(id) + self.waiters[id] = cont + } + } + + private func release() { + if let id = self.waitQueue.first { + self.waitQueue.removeFirst() + if let cont = self.waiters.removeValue(forKey: id) { + cont.resume() + } + return + } + self.available = min(self.available + 1, self.maxConcurrent) + } +} + +#if DEBUG +extension SessionPreviewCache { + func _testSet( + snapshot: SessionMenuPreviewSnapshot, + for sessionKey: String, + updatedAt: Date = Date()) + { + self.entries[sessionKey] = CacheEntry(snapshot: snapshot, updatedAt: updatedAt) + } + + func _testReset() { + self.entries = [:] + } +} +#endif + +struct SessionMenuPreviewSnapshot: Sendable { + let items: [SessionPreviewItem] + let status: SessionMenuPreviewView.LoadStatus +} + +struct SessionMenuPreviewView: View { + let width: CGFloat + let maxLines: Int + let title: String + let items: [SessionPreviewItem] + let status: LoadStatus + + @Environment(\.menuItemHighlighted) private var isHighlighted + + enum LoadStatus: Equatable { case loading case ready case empty @@ -78,15 +136,17 @@ struct SessionMenuPreviewView: View { } private var primaryColor: Color { - self.isHighlighted ? Color(nsColor: .selectedMenuItemTextColor) : .primary + if self.isHighlighted { + return Color(nsColor: .selectedMenuItemTextColor) + } + return Color(nsColor: .labelColor) } private var secondaryColor: Color { - self.isHighlighted ? Color(nsColor: .selectedMenuItemTextColor).opacity(0.85) : .secondary - } - - private var previewLimit: Int { - min(max(self.maxItems * 3, 20), 120) + if self.isHighlighted { + return Color(nsColor: .selectedMenuItemTextColor).opacity(0.85) + } + return Color(nsColor: .secondaryLabelColor) } var body: some View { @@ -100,21 +160,19 @@ struct SessionMenuPreviewView: View { switch self.status { case .loading: - Text("Loading preview…") - .font(.caption) - .foregroundStyle(self.secondaryColor) + self.placeholder("Loading preview…") case .empty: - Text("No recent messages") - .font(.caption) - .foregroundStyle(self.secondaryColor) + self.placeholder("No recent messages") case let .error(message): - Text(message) - .font(.caption) - .foregroundStyle(self.secondaryColor) + self.placeholder(message) case .ready: - VStack(alignment: .leading, spacing: 6) { - ForEach(self.items) { item in - self.previewRow(item) + if self.items.isEmpty { + self.placeholder("No recent messages") + } else { + VStack(alignment: .leading, spacing: 6) { + ForEach(self.items) { item in + self.previewRow(item) + } } } } @@ -123,9 +181,6 @@ struct SessionMenuPreviewView: View { .padding(.leading, 16) .padding(.trailing, 11) .frame(width: max(1, self.width), alignment: .leading) - .task(id: self.sessionKey) { - await self.loadPreview() - } } @ViewBuilder @@ -157,59 +212,179 @@ struct SessionMenuPreviewView: View { } } - private func loadPreview() async { - if let cached = await SessionPreviewCache.shared.cachedItems(for: self.sessionKey, maxAge: 12) { - await MainActor.run { - self.items = cached - self.status = cached.isEmpty ? .empty : .ready - } - return - } + @ViewBuilder + private func placeholder(_ text: String) -> some View { + Text(text) + .font(.caption) + .foregroundStyle(self.primaryColor) + } +} - await MainActor.run { - self.status = .loading +enum SessionMenuPreviewLoader { + private static let logger = Logger(subsystem: "com.clawdbot", category: "SessionPreview") + private static let previewTimeoutSeconds: Double = 4 + private static let cacheMaxAgeSeconds: TimeInterval = 30 + private static let previewMaxChars = 240 + + private struct PreviewTimeoutError: LocalizedError { + var errorDescription: String? { "preview timeout" } + } + + static func prewarm(sessionKeys: [String], maxItems: Int) async { + let keys = self.uniqueKeys(sessionKeys) + guard !keys.isEmpty else { return } + do { + let payload = try await self.requestPreview(keys: keys, maxItems: maxItems) + await self.cache(payload: payload, maxItems: maxItems) + } catch { + if self.isUnknownMethodError(error) { return } + let errorDescription = String(describing: error) + Self.logger.debug( + "Session preview prewarm failed count=\(keys.count, privacy: .public) " + + "error=\(errorDescription, privacy: .public)") + } + } + + static func load(sessionKey: String, maxItems: Int) async -> SessionMenuPreviewSnapshot { + if let cached = await SessionPreviewCache.shared.cachedSnapshot( + for: sessionKey, + maxAge: cacheMaxAgeSeconds) + { + return cached } do { - let timeoutMs = Int(Self.previewTimeoutSeconds * 1000) - let payload = try await AsyncTimeout.withTimeout( - seconds: Self.previewTimeoutSeconds, - onTimeout: { PreviewTimeoutError() }, - operation: { - try await GatewayConnection.shared.chatHistory( - sessionKey: self.sessionKey, - limit: self.previewLimit, - timeoutMs: timeoutMs) - }) - let built = Self.previewItems(from: payload, maxItems: self.maxItems) - await SessionPreviewCache.shared.store(items: built, for: self.sessionKey) - await MainActor.run { - self.items = built - self.status = built.isEmpty ? .empty : .ready - } + let snapshot = try await self.fetchSnapshot(sessionKey: sessionKey, maxItems: maxItems) + await SessionPreviewCache.shared.store(snapshot: snapshot, for: sessionKey) + return snapshot } catch is CancellationError { - return + return SessionMenuPreviewSnapshot(items: [], status: .loading) } catch { - let fallback = await SessionPreviewCache.shared.lastItems(for: self.sessionKey) - await MainActor.run { - if let fallback { - self.items = fallback - self.status = fallback.isEmpty ? .empty : .ready - } else { - self.status = .error("Preview unavailable") - } + if let fallback = await SessionPreviewCache.shared.lastSnapshot(for: sessionKey) { + return fallback } let errorDescription = String(describing: error) Self.logger.warning( - "Session preview failed session=\(self.sessionKey, privacy: .public) " + + "Session preview failed session=\(sessionKey, privacy: .public) " + "error=\(errorDescription, privacy: .public)") + return SessionMenuPreviewSnapshot(items: [], status: .error("Preview unavailable")) } } + private static func fetchSnapshot(sessionKey: String, maxItems: Int) async throws -> SessionMenuPreviewSnapshot { + do { + let payload = try await self.requestPreview(keys: [sessionKey], maxItems: maxItems) + if let entry = payload.previews.first(where: { $0.key == sessionKey }) ?? payload.previews.first { + return self.snapshot(from: entry, maxItems: maxItems) + } + return SessionMenuPreviewSnapshot(items: [], status: .error("Preview unavailable")) + } catch { + if self.isUnknownMethodError(error) { + return try await self.fetchHistorySnapshot(sessionKey: sessionKey, maxItems: maxItems) + } + throw error + } + } + + private static func requestPreview( + keys: [String], + maxItems: Int) async throws -> ClawdbotSessionsPreviewPayload + { + let boundedItems = self.normalizeMaxItems(maxItems) + let timeoutMs = Int(self.previewTimeoutSeconds * 1000) + return try await SessionPreviewLimiter.shared.withPermit { + try await AsyncTimeout.withTimeout( + seconds: self.previewTimeoutSeconds, + onTimeout: { PreviewTimeoutError() }, + operation: { + try await GatewayConnection.shared.sessionsPreview( + keys: keys, + limit: boundedItems, + maxChars: self.previewMaxChars, + timeoutMs: timeoutMs) + }) + } + } + + private static func fetchHistorySnapshot( + sessionKey: String, + maxItems: Int) async throws -> SessionMenuPreviewSnapshot + { + let timeoutMs = Int(self.previewTimeoutSeconds * 1000) + let payload = try await SessionPreviewLimiter.shared.withPermit { + try await AsyncTimeout.withTimeout( + seconds: self.previewTimeoutSeconds, + onTimeout: { PreviewTimeoutError() }, + operation: { + try await GatewayConnection.shared.chatHistory( + sessionKey: sessionKey, + limit: self.previewLimit(for: maxItems), + timeoutMs: timeoutMs) + }) + } + let built = Self.previewItems(from: payload, maxItems: maxItems) + return Self.snapshot(from: built) + } + + private static func snapshot(from items: [SessionPreviewItem]) -> SessionMenuPreviewSnapshot { + SessionMenuPreviewSnapshot(items: items, status: items.isEmpty ? .empty : .ready) + } + + private static func snapshot( + from entry: ClawdbotSessionPreviewEntry, + maxItems: Int) -> SessionMenuPreviewSnapshot + { + let items = self.previewItems(from: entry, maxItems: maxItems) + let normalized = entry.status.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + switch normalized { + case "ok": + return SessionMenuPreviewSnapshot(items: items, status: items.isEmpty ? .empty : .ready) + case "empty": + return SessionMenuPreviewSnapshot(items: items, status: .empty) + case "missing": + return SessionMenuPreviewSnapshot(items: items, status: .error("Session missing")) + default: + return SessionMenuPreviewSnapshot(items: items, status: .error("Preview unavailable")) + } + } + + private static func cache(payload: ClawdbotSessionsPreviewPayload, maxItems: Int) async { + for entry in payload.previews { + let snapshot = self.snapshot(from: entry, maxItems: maxItems) + await SessionPreviewCache.shared.store(snapshot: snapshot, for: entry.key) + } + } + + private static func previewLimit(for maxItems: Int) -> Int { + let boundedItems = self.normalizeMaxItems(maxItems) + return min(max(boundedItems * 3, 20), 120) + } + + private static func normalizeMaxItems(_ maxItems: Int) -> Int { + max(1, min(maxItems, 50)) + } + + private static func previewItems( + from entry: ClawdbotSessionPreviewEntry, + maxItems: Int) -> [SessionPreviewItem] + { + let boundedItems = self.normalizeMaxItems(maxItems) + let built: [SessionPreviewItem] = entry.items.enumerated().compactMap { index, item in + let text = item.text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !text.isEmpty else { return nil } + let role = self.previewRoleFromRaw(item.role) + return SessionPreviewItem(id: "\(entry.key)-\(index)", role: role, text: text) + } + + let trimmed = built.suffix(boundedItems) + return Array(trimmed.reversed()) + } + private static func previewItems( from payload: ClawdbotChatHistoryPayload, maxItems: Int) -> [SessionPreviewItem] { + let boundedItems = self.normalizeMaxItems(maxItems) let raw: [ClawdbotKit.AnyCodable] = payload.messages ?? [] let messages = self.decodeMessages(raw) let built = messages.compactMap { message -> SessionPreviewItem? in @@ -220,7 +395,7 @@ struct SessionMenuPreviewView: View { return SessionPreviewItem(id: id, role: role, text: text) } - let trimmed = built.suffix(maxItems) + let trimmed = built.suffix(boundedItems) return Array(trimmed.reversed()) } @@ -233,12 +408,16 @@ struct SessionMenuPreviewView: View { private static func previewRole(_ raw: String, isTool: Bool) -> PreviewRole { if isTool { return .tool } + return self.previewRoleFromRaw(raw) + } + + private static func previewRoleFromRaw(_ raw: String) -> PreviewRole { switch raw.lowercased() { - case "user": return .user - case "assistant": return .assistant - case "system": return .system - case "tool": return .tool - default: return .other + case "user": .user + case "assistant": .assistant + case "system": .system + case "tool": .tool + default: .other } } @@ -301,4 +480,16 @@ struct SessionMenuPreviewView: View { } return result } + + private static func uniqueKeys(_ keys: [String]) -> [String] { + let trimmed = keys.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + return self.dedupePreservingOrder(trimmed.filter { !$0.isEmpty }) + } + + private static func isUnknownMethodError(_ error: Error) -> Bool { + guard let response = error as? GatewayResponseError else { return false } + guard response.code == ErrorCode.invalidRequest.rawValue else { return false } + let message = response.message.lowercased() + return message.contains("unknown method") + } } diff --git a/apps/macos/Sources/Clawdbot/SettingsRootView.swift b/apps/macos/Sources/Clawdbot/SettingsRootView.swift index 87ecd3800..a261d53b4 100644 --- a/apps/macos/Sources/Clawdbot/SettingsRootView.swift +++ b/apps/macos/Sources/Clawdbot/SettingsRootView.swift @@ -27,9 +27,9 @@ struct SettingsRootView: View { .tabItem { Label("General", systemImage: "gearshape") } .tag(SettingsTab.general) - ConnectionsSettings() - .tabItem { Label("Connections", systemImage: "link") } - .tag(SettingsTab.connections) + ChannelsSettings() + .tabItem { Label("Channels", systemImage: "link") } + .tag(SettingsTab.channels) VoiceWakeSettings(state: self.state, isActive: self.selectedTab == .voiceWake) .tabItem { Label("Voice Wake", systemImage: "waveform.circle") } @@ -176,13 +176,13 @@ struct SettingsRootView: View { } enum SettingsTab: CaseIterable { - case general, connections, skills, sessions, cron, config, instances, voiceWake, permissions, debug, about + case general, channels, skills, sessions, cron, config, instances, voiceWake, permissions, debug, about static let windowWidth: CGFloat = 824 // wider static let windowHeight: CGFloat = 790 // +10% (more room) var title: String { switch self { case .general: "General" - case .connections: "Connections" + case .channels: "Channels" case .skills: "Skills" case .sessions: "Sessions" case .cron: "Cron" @@ -198,7 +198,7 @@ enum SettingsTab: CaseIterable { var systemImage: String { switch self { case .general: "gearshape" - case .connections: "link" + case .channels: "link" case .skills: "sparkles" case .sessions: "clock.arrow.circlepath" case .cron: "calendar" diff --git a/apps/macos/Sources/Clawdbot/SoundEffects.swift b/apps/macos/Sources/Clawdbot/SoundEffects.swift index c1f0cb9b4..b32123829 100644 --- a/apps/macos/Sources/Clawdbot/SoundEffects.swift +++ b/apps/macos/Sources/Clawdbot/SoundEffects.swift @@ -44,7 +44,7 @@ enum SoundEffectCatalog { ] private static let searchRoots: [URL] = [ - FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Sounds"), + FileManager().homeDirectoryForCurrentUser.appendingPathComponent("Library/Sounds"), URL(fileURLWithPath: "/Library/Sounds"), URL(fileURLWithPath: "/System/Applications/Mail.app/Contents/Resources"), // Mail “swoosh” URL(fileURLWithPath: "/System/Library/Sounds"), @@ -53,7 +53,7 @@ enum SoundEffectCatalog { private static let discoveredSoundMap: [String: URL] = { var map: [String: URL] = [:] for root in Self.searchRoots { - guard let contents = try? FileManager.default.contentsOfDirectory( + guard let contents = try? FileManager().contentsOfDirectory( at: root, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) diff --git a/apps/macos/Sources/Clawdbot/SystemRunPolicy.swift b/apps/macos/Sources/Clawdbot/SystemRunPolicy.swift deleted file mode 100644 index b38734bc3..000000000 --- a/apps/macos/Sources/Clawdbot/SystemRunPolicy.swift +++ /dev/null @@ -1,89 +0,0 @@ -import Foundation - -enum SystemRunPolicy: String, CaseIterable, Identifiable { - case never - case ask - case always - - var id: String { self.rawValue } - - var title: String { - switch self { - case .never: - "Never" - case .ask: - "Always Ask" - case .always: - "Always Allow" - } - } - - static func load(from defaults: UserDefaults = .standard) -> SystemRunPolicy { - if let policy = MacNodeConfigFile.systemRunPolicy() { - return policy - } - if let raw = defaults.string(forKey: systemRunPolicyKey), - let policy = SystemRunPolicy(rawValue: raw) - { - MacNodeConfigFile.setSystemRunPolicy(policy) - return policy - } - if let legacy = defaults.object(forKey: systemRunEnabledKey) as? Bool { - let policy: SystemRunPolicy = legacy ? .ask : .never - MacNodeConfigFile.setSystemRunPolicy(policy) - return policy - } - let fallback: SystemRunPolicy = .ask - MacNodeConfigFile.setSystemRunPolicy(fallback) - return fallback - } -} - -enum SystemRunAllowlist { - static func key(for argv: [String]) -> String { - let trimmed = argv.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } - guard !trimmed.isEmpty else { return "" } - if let data = try? JSONEncoder().encode(trimmed), - let json = String(data: data, encoding: .utf8) - { - return json - } - return trimmed.joined(separator: " ") - } - - static func displayString(for argv: [String]) -> String { - argv.map { arg in - let trimmed = arg.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return "\"\"" } - let needsQuotes = trimmed.contains { $0.isWhitespace || $0 == "\"" } - if !needsQuotes { return trimmed } - let escaped = trimmed.replacingOccurrences(of: "\"", with: "\\\"") - return "\"\(escaped)\"" - }.joined(separator: " ") - } - - static func load(from defaults: UserDefaults = .standard) -> Set { - if let allowlist = MacNodeConfigFile.systemRunAllowlist() { - return Set(allowlist) - } - if let legacy = defaults.stringArray(forKey: systemRunAllowlistKey), !legacy.isEmpty { - MacNodeConfigFile.setSystemRunAllowlist(legacy) - return Set(legacy) - } - return [] - } - - static func contains(_ argv: [String], defaults: UserDefaults = .standard) -> Bool { - let key = key(for: argv) - return self.load(from: defaults).contains(key) - } - - static func add(_ argv: [String], defaults: UserDefaults = .standard) { - let key = key(for: argv) - guard !key.isEmpty else { return } - var allowlist = self.load(from: defaults) - if allowlist.insert(key).inserted { - MacNodeConfigFile.setSystemRunAllowlist(Array(allowlist).sorted()) - } - } -} diff --git a/apps/macos/Sources/Clawdbot/SystemRunSettingsView.swift b/apps/macos/Sources/Clawdbot/SystemRunSettingsView.swift new file mode 100644 index 000000000..eef826c3f --- /dev/null +++ b/apps/macos/Sources/Clawdbot/SystemRunSettingsView.swift @@ -0,0 +1,412 @@ +import Foundation +import Observation +import SwiftUI + +struct SystemRunSettingsView: View { + @State private var model = ExecApprovalsSettingsModel() + @State private var tab: ExecApprovalsSettingsTab = .policy + @State private var newPattern: String = "" + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .center, spacing: 12) { + Text("Exec approvals") + .font(.body) + Spacer(minLength: 0) + Picker("Agent", selection: Binding( + get: { self.model.selectedAgentId }, + set: { self.model.selectAgent($0) })) + { + ForEach(self.model.agentPickerIds, id: \.self) { id in + Text(self.model.label(for: id)).tag(id) + } + } + .pickerStyle(.menu) + .frame(width: 180, alignment: .trailing) + } + + Picker("", selection: self.$tab) { + ForEach(ExecApprovalsSettingsTab.allCases) { tab in + Text(tab.title).tag(tab) + } + } + .pickerStyle(.segmented) + .frame(width: 320) + + if self.tab == .policy { + self.policyView + } else { + self.allowlistView + } + } + .task { await self.model.refresh() } + .onChange(of: self.tab) { _, _ in + Task { await self.model.refreshSkillBins() } + } + } + + private var policyView: some View { + VStack(alignment: .leading, spacing: 8) { + Picker("", selection: Binding( + get: { self.model.security }, + set: { self.model.setSecurity($0) })) + { + ForEach(ExecSecurity.allCases) { security in + Text(security.title).tag(security) + } + } + .labelsHidden() + .pickerStyle(.menu) + + Picker("", selection: Binding( + get: { self.model.ask }, + set: { self.model.setAsk($0) })) + { + ForEach(ExecAsk.allCases) { ask in + Text(ask.title).tag(ask) + } + } + .labelsHidden() + .pickerStyle(.menu) + + Picker("", selection: Binding( + get: { self.model.askFallback }, + set: { self.model.setAskFallback($0) })) + { + ForEach(ExecSecurity.allCases) { mode in + Text("Fallback: \(mode.title)").tag(mode) + } + } + .labelsHidden() + .pickerStyle(.menu) + + Text(self.scopeMessage) + .font(.footnote) + .foregroundStyle(.tertiary) + .fixedSize(horizontal: false, vertical: true) + } + } + + private var allowlistView: some View { + VStack(alignment: .leading, spacing: 10) { + Toggle("Auto-allow skill CLIs", isOn: Binding( + get: { self.model.autoAllowSkills }, + set: { self.model.setAutoAllowSkills($0) })) + + if self.model.autoAllowSkills, !self.model.skillBins.isEmpty { + Text("Skill CLIs: \(self.model.skillBins.joined(separator: ", "))") + .font(.footnote) + .foregroundStyle(.secondary) + } + + if self.model.isDefaultsScope { + Text("Allowlists are per-agent. Select an agent to edit its allowlist.") + .font(.footnote) + .foregroundStyle(.secondary) + } else { + HStack(spacing: 8) { + TextField("Add allowlist pattern (case-insensitive globs)", text: self.$newPattern) + .textFieldStyle(.roundedBorder) + Button("Add") { + let pattern = self.newPattern.trimmingCharacters(in: .whitespacesAndNewlines) + guard !pattern.isEmpty else { return } + self.model.addEntry(pattern) + self.newPattern = "" + } + .buttonStyle(.bordered) + .disabled(self.newPattern.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + + if self.model.entries.isEmpty { + Text("No allowlisted commands yet.") + .font(.footnote) + .foregroundStyle(.secondary) + } else { + VStack(alignment: .leading, spacing: 8) { + ForEach(self.model.entries, id: \.id) { entry in + ExecAllowlistRow( + entry: Binding( + get: { self.model.entry(for: entry.id) ?? entry }, + set: { self.model.updateEntry($0, id: entry.id) }), + onRemove: { self.model.removeEntry(id: entry.id) }) + } + } + } + } + } + } + + private var scopeMessage: String { + if self.model.isDefaultsScope { + return "Defaults apply when an agent has no overrides. " + + "Ask controls prompt behavior; fallback is used when no companion UI is reachable." + } + return "Security controls whether system.run can execute on this Mac when paired as a node. " + + "Ask controls prompt behavior; fallback is used when no companion UI is reachable." + } +} + +private enum ExecApprovalsSettingsTab: String, CaseIterable, Identifiable { + case policy + case allowlist + + var id: String { self.rawValue } + + var title: String { + switch self { + case .policy: "Access" + case .allowlist: "Allowlist" + } + } +} + +struct ExecAllowlistRow: View { + @Binding var entry: ExecAllowlistEntry + let onRemove: () -> Void + @State private var draftPattern: String = "" + + private static let relativeFormatter: RelativeDateTimeFormatter = { + let formatter = RelativeDateTimeFormatter() + formatter.unitsStyle = .short + return formatter + }() + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 8) { + TextField("Pattern", text: self.patternBinding) + .textFieldStyle(.roundedBorder) + + Button(role: .destructive) { + self.onRemove() + } label: { + Image(systemName: "trash") + } + .buttonStyle(.borderless) + } + + if let lastUsedAt = self.entry.lastUsedAt { + let date = Date(timeIntervalSince1970: lastUsedAt / 1000.0) + Text("Last used \(Self.relativeFormatter.localizedString(for: date, relativeTo: Date()))") + .font(.caption) + .foregroundStyle(.secondary) + } + + if let lastUsedCommand = self.entry.lastUsedCommand, !lastUsedCommand.isEmpty { + Text("Last command: \(lastUsedCommand)") + .font(.caption) + .foregroundStyle(.secondary) + } + + if let lastResolvedPath = self.entry.lastResolvedPath, !lastResolvedPath.isEmpty { + Text("Resolved path: \(lastResolvedPath)") + .font(.caption) + .foregroundStyle(.secondary) + } + } + .onAppear { + self.draftPattern = self.entry.pattern + } + } + + private var patternBinding: Binding { + Binding( + get: { self.draftPattern.isEmpty ? self.entry.pattern : self.draftPattern }, + set: { newValue in + self.draftPattern = newValue + self.entry.pattern = newValue + }) + } +} + +@MainActor +@Observable +final class ExecApprovalsSettingsModel { + private static let defaultsScopeId = "__defaults__" + var agentIds: [String] = [] + var selectedAgentId: String = "main" + var defaultAgentId: String = "main" + var security: ExecSecurity = .deny + var ask: ExecAsk = .onMiss + var askFallback: ExecSecurity = .deny + var autoAllowSkills = false + var entries: [ExecAllowlistEntry] = [] + var skillBins: [String] = [] + + var agentPickerIds: [String] { + [Self.defaultsScopeId] + self.agentIds + } + + var isDefaultsScope: Bool { + self.selectedAgentId == Self.defaultsScopeId + } + + func label(for id: String) -> String { + if id == Self.defaultsScopeId { return "Defaults" } + return id + } + + func refresh() async { + await self.refreshAgents() + self.loadSettings(for: self.selectedAgentId) + await self.refreshSkillBins() + } + + func refreshAgents() async { + let root = await ConfigStore.load() + let agents = root["agents"] as? [String: Any] + let list = agents?["list"] as? [[String: Any]] ?? [] + var ids: [String] = [] + var seen = Set() + var defaultId: String? + for entry in list { + guard let raw = entry["id"] as? String else { continue } + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { continue } + if !seen.insert(trimmed).inserted { continue } + ids.append(trimmed) + if (entry["default"] as? Bool) == true, defaultId == nil { + defaultId = trimmed + } + } + if ids.isEmpty { + ids = ["main"] + defaultId = "main" + } else if defaultId == nil { + defaultId = ids.first + } + self.agentIds = ids + self.defaultAgentId = defaultId ?? "main" + if self.selectedAgentId == Self.defaultsScopeId { + return + } + if !self.agentIds.contains(self.selectedAgentId) { + self.selectedAgentId = self.defaultAgentId + } + } + + func selectAgent(_ id: String) { + self.selectedAgentId = id + self.loadSettings(for: id) + Task { await self.refreshSkillBins() } + } + + func loadSettings(for agentId: String) { + if agentId == Self.defaultsScopeId { + let defaults = ExecApprovalsStore.resolveDefaults() + self.security = defaults.security + self.ask = defaults.ask + self.askFallback = defaults.askFallback + self.autoAllowSkills = defaults.autoAllowSkills + self.entries = [] + return + } + let resolved = ExecApprovalsStore.resolve(agentId: agentId) + self.security = resolved.agent.security + self.ask = resolved.agent.ask + self.askFallback = resolved.agent.askFallback + self.autoAllowSkills = resolved.agent.autoAllowSkills + self.entries = resolved.allowlist + .sorted { $0.pattern.localizedCaseInsensitiveCompare($1.pattern) == .orderedAscending } + } + + func setSecurity(_ security: ExecSecurity) { + self.security = security + if self.isDefaultsScope { + ExecApprovalsStore.updateDefaults { defaults in + defaults.security = security + } + } else { + ExecApprovalsStore.updateAgentSettings(agentId: self.selectedAgentId) { entry in + entry.security = security + } + } + self.syncQuickMode() + } + + func setAsk(_ ask: ExecAsk) { + self.ask = ask + if self.isDefaultsScope { + ExecApprovalsStore.updateDefaults { defaults in + defaults.ask = ask + } + } else { + ExecApprovalsStore.updateAgentSettings(agentId: self.selectedAgentId) { entry in + entry.ask = ask + } + } + self.syncQuickMode() + } + + func setAskFallback(_ mode: ExecSecurity) { + self.askFallback = mode + if self.isDefaultsScope { + ExecApprovalsStore.updateDefaults { defaults in + defaults.askFallback = mode + } + } else { + ExecApprovalsStore.updateAgentSettings(agentId: self.selectedAgentId) { entry in + entry.askFallback = mode + } + } + } + + func setAutoAllowSkills(_ enabled: Bool) { + self.autoAllowSkills = enabled + if self.isDefaultsScope { + ExecApprovalsStore.updateDefaults { defaults in + defaults.autoAllowSkills = enabled + } + } else { + ExecApprovalsStore.updateAgentSettings(agentId: self.selectedAgentId) { entry in + entry.autoAllowSkills = enabled + } + } + Task { await self.refreshSkillBins(force: enabled) } + } + + func addEntry(_ pattern: String) { + guard !self.isDefaultsScope else { return } + let trimmed = pattern.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return } + self.entries.append(ExecAllowlistEntry(pattern: trimmed, lastUsedAt: nil)) + ExecApprovalsStore.updateAllowlist(agentId: self.selectedAgentId, allowlist: self.entries) + } + + func updateEntry(_ entry: ExecAllowlistEntry, id: UUID) { + guard !self.isDefaultsScope else { return } + guard let index = self.entries.firstIndex(where: { $0.id == id }) else { return } + self.entries[index] = entry + ExecApprovalsStore.updateAllowlist(agentId: self.selectedAgentId, allowlist: self.entries) + } + + func removeEntry(id: UUID) { + guard !self.isDefaultsScope else { return } + guard let index = self.entries.firstIndex(where: { $0.id == id }) else { return } + self.entries.remove(at: index) + ExecApprovalsStore.updateAllowlist(agentId: self.selectedAgentId, allowlist: self.entries) + } + + func entry(for id: UUID) -> ExecAllowlistEntry? { + self.entries.first(where: { $0.id == id }) + } + + func refreshSkillBins(force: Bool = false) async { + guard self.autoAllowSkills else { + self.skillBins = [] + return + } + let bins = await SkillBinsCache.shared.currentBins(force: force) + self.skillBins = bins.sorted() + } + + private func syncQuickMode() { + if self.isDefaultsScope { + AppStateStore.shared.execApprovalMode = ExecApprovalQuickMode.from(security: self.security, ask: self.ask) + return + } + if self.selectedAgentId == self.defaultAgentId || self.agentIds.count <= 1 { + AppStateStore.shared.execApprovalMode = ExecApprovalQuickMode.from(security: self.security, ask: self.ask) + } + } +} diff --git a/apps/macos/Sources/Clawdbot/TailscaleService.swift b/apps/macos/Sources/Clawdbot/TailscaleService.swift index 262ac371e..413e8d0c8 100644 --- a/apps/macos/Sources/Clawdbot/TailscaleService.swift +++ b/apps/macos/Sources/Clawdbot/TailscaleService.swift @@ -2,6 +2,9 @@ import AppKit import Foundation import Observation import os +#if canImport(Darwin) +import Darwin +#endif /// Manages Tailscale integration and status checking. @Observable @@ -53,7 +56,7 @@ final class TailscaleService { #endif func checkAppInstallation() -> Bool { - let installed = FileManager.default.fileExists(atPath: "/Applications/Tailscale.app") + let installed = FileManager().fileExists(atPath: "/Applications/Tailscale.app") self.logger.info("Tailscale app installed: \(installed)") return installed } @@ -100,16 +103,14 @@ final class TailscaleService { } func checkTailscaleStatus() async { + let previousIP = self.tailscaleIP self.isInstalled = self.checkAppInstallation() - guard self.isInstalled else { + if !self.isInstalled { self.isRunning = false self.tailscaleHostname = nil self.tailscaleIP = nil self.statusError = "Tailscale is not installed" - return - } - - if let apiResponse = await fetchTailscaleStatus() { + } else if let apiResponse = await fetchTailscaleStatus() { self.isRunning = apiResponse.status.lowercased() == "running" if self.isRunning { @@ -138,6 +139,19 @@ final class TailscaleService { self.statusError = "Please start the Tailscale app" self.logger.info("Tailscale API not responding; app likely not running") } + + if self.tailscaleIP == nil, let fallback = Self.detectTailnetIPv4() { + self.tailscaleIP = fallback + if !self.isRunning { + self.isRunning = true + } + self.statusError = nil + self.logger.info("Tailscale interface IP detected (fallback) ip=\(fallback, privacy: .public)") + } + + if previousIP != self.tailscaleIP { + await GatewayEndpointStore.shared.refresh() + } } func openTailscaleApp() { @@ -163,4 +177,50 @@ final class TailscaleService { NSWorkspace.shared.open(url) } } + + private nonisolated static func isTailnetIPv4(_ address: String) -> Bool { + let parts = address.split(separator: ".") + guard parts.count == 4 else { return false } + let octets = parts.compactMap { Int($0) } + guard octets.count == 4 else { return false } + let a = octets[0] + let b = octets[1] + return a == 100 && b >= 64 && b <= 127 + } + + private nonisolated static func detectTailnetIPv4() -> String? { + var addrList: UnsafeMutablePointer? + guard getifaddrs(&addrList) == 0, let first = addrList else { return nil } + defer { freeifaddrs(addrList) } + + for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) { + let flags = Int32(ptr.pointee.ifa_flags) + let isUp = (flags & IFF_UP) != 0 + let isLoopback = (flags & IFF_LOOPBACK) != 0 + let family = ptr.pointee.ifa_addr.pointee.sa_family + if !isUp || isLoopback || family != UInt8(AF_INET) { continue } + + var addr = ptr.pointee.ifa_addr.pointee + var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST)) + let result = getnameinfo( + &addr, + socklen_t(ptr.pointee.ifa_addr.pointee.sa_len), + &buffer, + socklen_t(buffer.count), + nil, + 0, + NI_NUMERICHOST) + guard result == 0 else { continue } + let len = buffer.prefix { $0 != 0 } + let bytes = len.map { UInt8(bitPattern: $0) } + guard let ip = String(bytes: bytes, encoding: .utf8) else { continue } + if Self.isTailnetIPv4(ip) { return ip } + } + + return nil + } + + nonisolated static func fallbackTailnetIPv4() -> String? { + self.detectTailnetIPv4() + } } diff --git a/apps/macos/Sources/Clawdbot/TerminationSignalWatcher.swift b/apps/macos/Sources/Clawdbot/TerminationSignalWatcher.swift index e00188521..7994016ef 100644 --- a/apps/macos/Sources/Clawdbot/TerminationSignalWatcher.swift +++ b/apps/macos/Sources/Clawdbot/TerminationSignalWatcher.swift @@ -42,6 +42,7 @@ final class TerminationSignalWatcher { self.logger.info("received signal \(sig, privacy: .public); terminating") // Ensure any pairing prompt can't accidentally approve during shutdown. NodePairingApprovalPrompter.shared.stop() + DevicePairingApprovalPrompter.shared.stop() NSApp.terminate(nil) // Safety net: don't hang forever if something blocks termination. diff --git a/apps/macos/Sources/Clawdbot/UsageCostData.swift b/apps/macos/Sources/Clawdbot/UsageCostData.swift new file mode 100644 index 000000000..ca1fb5cc3 --- /dev/null +++ b/apps/macos/Sources/Clawdbot/UsageCostData.swift @@ -0,0 +1,60 @@ +import Foundation + +struct GatewayCostUsageTotals: Codable { + let input: Int + let output: Int + let cacheRead: Int + let cacheWrite: Int + let totalTokens: Int + let totalCost: Double + let missingCostEntries: Int +} + +struct GatewayCostUsageDay: Codable { + let date: String + let input: Int + let output: Int + let cacheRead: Int + let cacheWrite: Int + let totalTokens: Int + let totalCost: Double + let missingCostEntries: Int +} + +struct GatewayCostUsageSummary: Codable { + let updatedAt: Double + let days: Int + let daily: [GatewayCostUsageDay] + let totals: GatewayCostUsageTotals +} + +enum CostUsageFormatting { + static func formatUsd(_ value: Double?) -> String? { + guard let value, value.isFinite else { return nil } + if value >= 1 { return String(format: "$%.2f", value) } + if value >= 0.01 { return String(format: "$%.2f", value) } + return String(format: "$%.4f", value) + } + + static func formatTokenCount(_ value: Int?) -> String? { + guard let value else { return nil } + let safe = max(0, value) + if safe >= 1_000_000 { return String(format: "%.1fm", Double(safe) / 1_000_000.0) } + if safe >= 1000 { return safe >= 10000 + ? String(format: "%.0fk", Double(safe) / 1000.0) + : String(format: "%.1fk", Double(safe) / 1000.0) + } + return String(safe) + } +} + +@MainActor +enum CostUsageLoader { + static func loadSummary() async throws -> GatewayCostUsageSummary { + let data = try await ControlChannel.shared.request( + method: "usage.cost", + params: nil, + timeoutMs: 7000) + return try JSONDecoder().decode(GatewayCostUsageSummary.self, from: data) + } +} diff --git a/apps/macos/Sources/Clawdbot/UsageData.swift b/apps/macos/Sources/Clawdbot/UsageData.swift index c291519b6..7800054c6 100644 --- a/apps/macos/Sources/Clawdbot/UsageData.swift +++ b/apps/macos/Sources/Clawdbot/UsageData.swift @@ -75,18 +75,6 @@ struct UsageRow: Identifiable { extension GatewayUsageSummary { func primaryRows() -> [UsageRow] { self.providers.compactMap { provider in - if let error = provider.error, provider.windows.isEmpty { - return UsageRow( - id: provider.provider, - providerId: provider.provider, - displayName: provider.displayName, - plan: provider.plan, - windowLabel: nil, - usedPercent: nil, - resetAt: nil, - error: error) - } - guard let window = provider.windows.max(by: { $0.usedPercent < $1.usedPercent }) else { return nil } @@ -99,7 +87,7 @@ extension GatewayUsageSummary { windowLabel: window.label, usedPercent: window.usedPercent, resetAt: window.resetAt.map { Date(timeIntervalSince1970: $0 / 1000) }, - error: provider.error) + error: nil) } } } diff --git a/apps/macos/Sources/Clawdbot/UsageMenuLabelView.swift b/apps/macos/Sources/Clawdbot/UsageMenuLabelView.swift index 5e3a52687..c7f95e476 100644 --- a/apps/macos/Sources/Clawdbot/UsageMenuLabelView.swift +++ b/apps/macos/Sources/Clawdbot/UsageMenuLabelView.swift @@ -37,14 +37,12 @@ struct UsageMenuLabelView: View { Spacer(minLength: 4) - if !self.row.hasError { - Text(self.row.detailText()) - .font(.caption.monospacedDigit()) - .foregroundStyle(self.secondaryTextColor) - .lineLimit(1) - .truncationMode(.tail) - .layoutPriority(2) - } + Text(self.row.detailText()) + .font(.caption.monospacedDigit()) + .foregroundStyle(self.secondaryTextColor) + .lineLimit(1) + .truncationMode(.tail) + .layoutPriority(2) if self.showsChevron { Image(systemName: "chevron.right") @@ -53,16 +51,6 @@ struct UsageMenuLabelView: View { .padding(.leading, 2) } } - - if let error = self.row.error?.nonEmpty { - Text(error) - .font(.caption) - .foregroundStyle(self.secondaryTextColor) - .multilineTextAlignment(.leading) - .lineLimit(2) - .truncationMode(.tail) - .fixedSize(horizontal: false, vertical: true) - } } .padding(.vertical, 10) .padding(.leading, self.paddingLeading) diff --git a/apps/macos/Sources/Clawdbot/VoicePushToTalk.swift b/apps/macos/Sources/Clawdbot/VoicePushToTalk.swift index 5984a8641..2bb1ec1f5 100644 --- a/apps/macos/Sources/Clawdbot/VoicePushToTalk.swift +++ b/apps/macos/Sources/Clawdbot/VoicePushToTalk.swift @@ -37,7 +37,7 @@ final class VoicePushToTalkHotkey: @unchecked Sendable { } private func startMonitoring() { - assert(Thread.isMainThread) + // assert(Thread.isMainThread) - Removed for Swift 6 guard self.globalMonitor == nil, self.localMonitor == nil else { return } // Listen-only global monitor; we rely on Input Monitoring permission to receive events. self.globalMonitor = NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged) { [weak self] event in @@ -55,7 +55,7 @@ final class VoicePushToTalkHotkey: @unchecked Sendable { } private func stopMonitoring() { - assert(Thread.isMainThread) + // assert(Thread.isMainThread) - Removed for Swift 6 if let globalMonitor { NSEvent.removeMonitor(globalMonitor) self.globalMonitor = nil @@ -75,15 +75,11 @@ final class VoicePushToTalkHotkey: @unchecked Sendable { } private func withMainThread(_ block: @escaping @Sendable () -> Void) { - if Thread.isMainThread { - block() - } else { - DispatchQueue.main.async(execute: block) - } + DispatchQueue.main.async(execute: block) } private func updateModifierState(keyCode: UInt16, modifierFlags: NSEvent.ModifierFlags) { - assert(Thread.isMainThread) + // assert(Thread.isMainThread) - Removed for Swift 6 // Right Option (keyCode 61) acts as a hold-to-talk modifier. if keyCode == 61 { self.optionDown = modifierFlags.contains(.option) diff --git a/apps/macos/Sources/Clawdbot/VoiceWakeGlobalSettingsSync.swift b/apps/macos/Sources/Clawdbot/VoiceWakeGlobalSettingsSync.swift index 95ea5e364..9a12486cb 100644 --- a/apps/macos/Sources/Clawdbot/VoiceWakeGlobalSettingsSync.swift +++ b/apps/macos/Sources/Clawdbot/VoiceWakeGlobalSettingsSync.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import Foundation import OSLog diff --git a/apps/macos/Sources/Clawdbot/VoiceWakeHelpers.swift b/apps/macos/Sources/Clawdbot/VoiceWakeHelpers.swift index a60aa7d7c..98cdc0cb5 100644 --- a/apps/macos/Sources/Clawdbot/VoiceWakeHelpers.swift +++ b/apps/macos/Sources/Clawdbot/VoiceWakeHelpers.swift @@ -4,6 +4,8 @@ func sanitizeVoiceWakeTriggers(_ words: [String]) -> [String] { let cleaned = words .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } .filter { !$0.isEmpty } + .prefix(voiceWakeMaxWords) + .map { String($0.prefix(voiceWakeMaxWordLength)) } return cleaned.isEmpty ? defaultVoiceWakeTriggers : cleaned } diff --git a/apps/macos/Sources/Clawdbot/VoiceWakeSettings.swift b/apps/macos/Sources/Clawdbot/VoiceWakeSettings.swift index 176980cc5..a41e8bb1f 100644 --- a/apps/macos/Sources/Clawdbot/VoiceWakeSettings.swift +++ b/apps/macos/Sources/Clawdbot/VoiceWakeSettings.swift @@ -21,6 +21,7 @@ struct VoiceWakeSettings: View { @State private var micObserver = AudioInputDeviceObserver() @State private var micRefreshTask: Task? @State private var availableLocales: [Locale] = [] + @State private var triggerEntries: [TriggerEntry] = [] private let fieldLabelWidth: CGFloat = 140 private let controlWidth: CGFloat = 240 private let isPreview = ProcessInfo.processInfo.isPreview @@ -31,9 +32,9 @@ struct VoiceWakeSettings: View { var id: String { self.uid } } - private struct IndexedWord: Identifiable { - let id: Int - let value: String + private struct TriggerEntry: Identifiable { + let id: UUID + var value: String } private var voiceWakeBinding: Binding { @@ -105,6 +106,7 @@ struct VoiceWakeSettings: View { .onAppear { guard !self.isPreview else { return } self.startMicObserver() + self.loadTriggerEntries() } .onChange(of: self.state.voiceWakeMicID) { _, _ in guard !self.isPreview else { return } @@ -122,8 +124,10 @@ struct VoiceWakeSettings: View { self.micRefreshTask = nil Task { await self.meter.stop() } self.micObserver.stop() + self.syncTriggerEntriesToState() } else { self.startMicObserver() + self.loadTriggerEntries() } } .onDisappear { @@ -136,11 +140,16 @@ struct VoiceWakeSettings: View { self.micRefreshTask = nil self.micObserver.stop() Task { await self.meter.stop() } + self.syncTriggerEntriesToState() } } - private var indexedWords: [IndexedWord] { - self.state.swabbleTriggerWords.enumerated().map { IndexedWord(id: $0.offset, value: $0.element) } + private func loadTriggerEntries() { + self.triggerEntries = self.state.swabbleTriggerWords.map { TriggerEntry(id: UUID(), value: $0) } + } + + private func syncTriggerEntriesToState() { + self.state.swabbleTriggerWords = self.triggerEntries.map(\.value) } private var triggerTable: some View { @@ -154,29 +163,42 @@ struct VoiceWakeSettings: View { } label: { Label("Add word", systemImage: "plus") } - .disabled(self.state.swabbleTriggerWords - .contains(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty })) + .disabled(self.triggerEntries + .contains(where: { $0.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty })) - Button("Reset defaults") { self.state.swabbleTriggerWords = defaultVoiceWakeTriggers } + Button("Reset defaults") { + self.triggerEntries = defaultVoiceWakeTriggers.map { TriggerEntry(id: UUID(), value: $0) } + self.syncTriggerEntriesToState() + } } - Table(self.indexedWords) { - TableColumn("Word") { row in - TextField("Wake word", text: self.binding(for: row.id)) - .textFieldStyle(.roundedBorder) - } - TableColumn("") { row in - Button { - self.removeWord(at: row.id) - } label: { - Image(systemName: "trash") + VStack(spacing: 0) { + ForEach(self.$triggerEntries) { $entry in + HStack(spacing: 8) { + TextField("Wake word", text: $entry.value) + .textFieldStyle(.roundedBorder) + .onSubmit { + self.syncTriggerEntriesToState() + } + + Button { + self.removeWord(id: entry.id) + } label: { + Image(systemName: "trash") + } + .buttonStyle(.borderless) + .help("Remove trigger word") + .frame(width: 24) + } + .padding(8) + + if entry.id != self.triggerEntries.last?.id { + Divider() } - .buttonStyle(.borderless) - .help("Remove trigger word") } - .width(36) } - .frame(minHeight: 180) + .frame(maxWidth: .infinity, minHeight: 180, alignment: .topLeading) + .background(Color(nsColor: .textBackgroundColor)) .clipShape(RoundedRectangle(cornerRadius: 6)) .overlay( RoundedRectangle(cornerRadius: 6) @@ -211,24 +233,12 @@ struct VoiceWakeSettings: View { } private func addWord() { - self.state.swabbleTriggerWords.append("") + self.triggerEntries.append(TriggerEntry(id: UUID(), value: "")) } - private func removeWord(at index: Int) { - guard self.state.swabbleTriggerWords.indices.contains(index) else { return } - self.state.swabbleTriggerWords.remove(at: index) - } - - private func binding(for index: Int) -> Binding { - Binding( - get: { - guard self.state.swabbleTriggerWords.indices.contains(index) else { return "" } - return self.state.swabbleTriggerWords[index] - }, - set: { newValue in - guard self.state.swabbleTriggerWords.indices.contains(index) else { return } - self.state.swabbleTriggerWords[index] = newValue - }) + private func removeWord(id: UUID) { + self.triggerEntries.removeAll { $0.id == id } + self.syncTriggerEntriesToState() } private func toggleTest() { @@ -638,13 +648,14 @@ extension VoiceWakeSettings { state.voicePushToTalkEnabled = true state.swabbleTriggerWords = ["Claude", "Hey"] - let view = VoiceWakeSettings(state: state, isActive: true) + var view = VoiceWakeSettings(state: state, isActive: true) view.availableMics = [AudioInputDevice(uid: "mic-1", name: "Built-in")] view.availableLocales = [Locale(identifier: "en_US")] view.meterLevel = 0.42 view.meterError = "No input" view.testState = .detected("ok") view.isTesting = true + view.triggerEntries = [TriggerEntry(id: UUID(), value: "Claude")] _ = view.body _ = view.localePicker @@ -654,8 +665,9 @@ extension VoiceWakeSettings { _ = view.chimeSection view.addWord() - _ = view.binding(for: 0).wrappedValue - view.removeWord(at: 0) + if let entryId = view.triggerEntries.first?.id { + view.removeWord(id: entryId) + } } } #endif diff --git a/apps/macos/Sources/Clawdbot/WebChatSwiftUI.swift b/apps/macos/Sources/Clawdbot/WebChatSwiftUI.swift index 0910fb798..665416d31 100644 --- a/apps/macos/Sources/Clawdbot/WebChatSwiftUI.swift +++ b/apps/macos/Sources/Clawdbot/WebChatSwiftUI.swift @@ -1,5 +1,6 @@ import AppKit import ClawdbotChatUI +import ClawdbotKit import ClawdbotProtocol import Foundation import OSLog diff --git a/apps/macos/Sources/ClawdbotDiscovery/GatewayDiscoveryModel.swift b/apps/macos/Sources/ClawdbotDiscovery/GatewayDiscoveryModel.swift index 9fced5a7d..4d953baac 100644 --- a/apps/macos/Sources/ClawdbotDiscovery/GatewayDiscoveryModel.swift +++ b/apps/macos/Sources/ClawdbotDiscovery/GatewayDiscoveryModel.swift @@ -81,11 +81,11 @@ public final class GatewayDiscoveryModel { public func start() { if !self.browsers.isEmpty { return } - for domain in ClawdbotBonjour.bridgeServiceDomains { + for domain in ClawdbotBonjour.gatewayServiceDomains { let params = NWParameters.tcp params.includePeerToPeer = true let browser = NWBrowser( - for: .bonjour(type: ClawdbotBonjour.bridgeServiceType, domain: domain), + for: .bonjour(type: ClawdbotBonjour.gatewayServiceType, domain: domain), using: params) browser.stateUpdateHandler = { [weak self] state in @@ -113,7 +113,7 @@ public final class GatewayDiscoveryModel { } public func refreshWideAreaFallbackNow(timeoutSeconds: TimeInterval = 5.0) { - let domain = ClawdbotBonjour.wideAreaBridgeServiceDomain + let domain = ClawdbotBonjour.wideAreaGatewayServiceDomain Task.detached(priority: .utility) { [weak self] in guard let self else { return } let beacons = WideAreaGatewayDiscovery.discover(timeoutSeconds: timeoutSeconds) @@ -174,7 +174,7 @@ public final class GatewayDiscoveryModel { } // Bonjour can return only "local" results for the wide-area domain (or no results at all), - // which makes onboarding look empty even though Tailscale DNS-SD can already see bridges. + // which makes onboarding look empty even though Tailscale DNS-SD can already see gateways. guard !self.wideAreaFallbackGateways.isEmpty else { self.gateways = primaryFiltered return @@ -194,7 +194,7 @@ public final class GatewayDiscoveryModel { guard case let .service(name, type, resultDomain, _) = result.endpoint else { return nil } let decodedName = BonjourEscapes.decode(name) - let stableID = BridgeEndpointID.stableID(result.endpoint) + let stableID = GatewayEndpointID.stableID(result.endpoint) let resolvedTXT = self.resolvedTXTByID[stableID] ?? [:] let txt = Self.txtDictionary(from: result).merging( resolvedTXT, @@ -230,12 +230,12 @@ public final class GatewayDiscoveryModel { gatewayPort: parsedTXT.gatewayPort, cliPath: parsedTXT.cliPath, stableID: stableID, - debugID: BridgeEndpointID.prettyDescription(result.endpoint), + debugID: GatewayEndpointID.prettyDescription(result.endpoint), isLocal: isLocal) } .sorted { $0.displayName.localizedCaseInsensitiveCompare($1.displayName) == .orderedAscending } - if domain == ClawdbotBonjour.wideAreaBridgeServiceDomain, + if domain == ClawdbotBonjour.wideAreaGatewayServiceDomain, self.hasUsableWideAreaResults { self.wideAreaFallbackGateways = [] @@ -243,7 +243,7 @@ public final class GatewayDiscoveryModel { } private func scheduleWideAreaFallback() { - let domain = ClawdbotBonjour.wideAreaBridgeServiceDomain + let domain = ClawdbotBonjour.wideAreaGatewayServiceDomain if Self.isRunningTests { return } guard self.wideAreaFallbackTask == nil else { return } self.wideAreaFallbackTask = Task.detached(priority: .utility) { [weak self] in @@ -276,7 +276,7 @@ public final class GatewayDiscoveryModel { } private var hasUsableWideAreaResults: Bool { - let domain = ClawdbotBonjour.wideAreaBridgeServiceDomain + let domain = ClawdbotBonjour.wideAreaGatewayServiceDomain guard let gateways = self.gatewaysByDomain[domain], !gateways.isEmpty else { return false } if !self.filterLocalGateways { return true } return gateways.contains(where: { !$0.isLocal }) @@ -462,7 +462,7 @@ public final class GatewayDiscoveryModel { private nonisolated static func prettifyServiceName(_ decodedName: String) -> String { let normalized = Self.prettifyInstanceName(decodedName) - var cleaned = normalized.replacingOccurrences(of: #"\s*-?bridge$"#, with: "", options: .regularExpression) + var cleaned = normalized.replacingOccurrences(of: #"\s*-?gateway$"#, with: "", options: .regularExpression) cleaned = cleaned .replacingOccurrences(of: "_", with: " ") .replacingOccurrences(of: "-", with: " ") @@ -598,11 +598,11 @@ public final class GatewayDiscoveryModel { private nonisolated static func normalizeServiceHostToken(_ raw: String?) -> String? { guard let raw else { return nil } let prettified = Self.prettifyInstanceName(raw) - let strippedBridge = prettified.replacingOccurrences( - of: #"\s*-?\s*bridge$"#, + let strippedGateway = prettified.replacingOccurrences( + of: #"\s*-?\s*gateway$"#, with: "", options: .regularExpression) - return self.normalizeHostToken(strippedBridge) + return self.normalizeHostToken(strippedGateway) } } diff --git a/apps/macos/Sources/ClawdbotDiscovery/WideAreaGatewayDiscovery.swift b/apps/macos/Sources/ClawdbotDiscovery/WideAreaGatewayDiscovery.swift index f70e862a0..64d9353c2 100644 --- a/apps/macos/Sources/ClawdbotDiscovery/WideAreaGatewayDiscovery.swift +++ b/apps/macos/Sources/ClawdbotDiscovery/WideAreaGatewayDiscovery.swift @@ -9,7 +9,6 @@ struct WideAreaGatewayBeacon: Sendable, Equatable { var lanHost: String? var tailnetDns: String? var gatewayPort: Int? - var bridgePort: Int? var sshPort: Int? var cliPath: String? } @@ -51,9 +50,9 @@ enum WideAreaGatewayDiscovery { return [] } - let domain = ClawdbotBonjour.wideAreaBridgeServiceDomain + let domain = ClawdbotBonjour.wideAreaGatewayServiceDomain let domainTrimmed = domain.trimmingCharacters(in: CharacterSet(charactersIn: ".")) - let probeName = "_clawdbot-bridge._tcp.\(domainTrimmed)" + let probeName = "_clawdbot-gw._tcp.\(domainTrimmed)" guard let ptrLines = context.dig( ["+short", "+time=1", "+tries=1", "@\(nameserver)", probeName, "PTR"], min(defaultTimeoutSeconds, remaining()))?.split(whereSeparator: \.isNewline), @@ -67,7 +66,7 @@ enum WideAreaGatewayDiscovery { let ptr = raw.trimmingCharacters(in: .whitespacesAndNewlines) if ptr.isEmpty { continue } let ptrName = ptr.hasSuffix(".") ? String(ptr.dropLast()) : ptr - let suffix = "._clawdbot-bridge._tcp.\(domainTrimmed)" + let suffix = "._clawdbot-gw._tcp.\(domainTrimmed)" let rawInstanceName = ptrName.hasSuffix(suffix) ? String(ptrName.dropLast(suffix.count)) : ptrName @@ -94,7 +93,6 @@ enum WideAreaGatewayDiscovery { lanHost: txt["lanHost"], tailnetDns: txt["tailnetDns"], gatewayPort: parseInt(txt["gatewayPort"]), - bridgePort: parseInt(txt["bridgePort"]), sshPort: parseInt(txt["sshPort"]), cliPath: txt["cliPath"]) beacons.append(beacon) @@ -156,9 +154,9 @@ enum WideAreaGatewayDiscovery { remaining: () -> TimeInterval, dig: @escaping @Sendable (_ args: [String], _ timeout: TimeInterval) -> String?) -> String? { - let domain = ClawdbotBonjour.wideAreaBridgeServiceDomain + let domain = ClawdbotBonjour.wideAreaGatewayServiceDomain let domainTrimmed = domain.trimmingCharacters(in: CharacterSet(charactersIn: ".")) - let probeName = "_clawdbot-bridge._tcp.\(domainTrimmed)" + let probeName = "_clawdbot-gw._tcp.\(domainTrimmed)" let ips = candidates candidates.removeAll(keepingCapacity: true) diff --git a/apps/macos/Sources/ClawdbotDiscoveryCLI/main.swift b/apps/macos/Sources/ClawdbotDiscoveryCLI/main.swift deleted file mode 100644 index d5fc5789c..000000000 --- a/apps/macos/Sources/ClawdbotDiscoveryCLI/main.swift +++ /dev/null @@ -1,150 +0,0 @@ -import ClawdbotDiscovery -import Foundation - -struct DiscoveryOptions { - var timeoutMs: Int = 2000 - var json: Bool = false - var includeLocal: Bool = false - var help: Bool = false - - static func parse(_ args: [String]) -> DiscoveryOptions { - var opts = DiscoveryOptions() - var i = 0 - while i < args.count { - let arg = args[i] - switch arg { - case "-h", "--help": - opts.help = true - case "--json": - opts.json = true - case "--include-local": - opts.includeLocal = true - case "--timeout": - let next = (i + 1 < args.count) ? args[i + 1] : nil - if let next, let parsed = Int(next.trimmingCharacters(in: .whitespacesAndNewlines)) { - opts.timeoutMs = max(100, parsed) - i += 1 - } - default: - break - } - i += 1 - } - return opts - } -} - -struct DiscoveryOutput: Encodable { - struct Gateway: Encodable { - var displayName: String - var lanHost: String? - var tailnetDns: String? - var sshPort: Int - var gatewayPort: Int? - var cliPath: String? - var stableID: String - var debugID: String - var isLocal: Bool - } - - var status: String - var timeoutMs: Int - var includeLocal: Bool - var count: Int - var gateways: [Gateway] -} - -@main -struct ClawdbotDiscoveryCLI { - static func main() async { - let opts = DiscoveryOptions.parse(Array(CommandLine.arguments.dropFirst())) - if opts.help { - print(""" - clawdbot-mac-discovery - - Usage: - clawdbot-mac-discovery [--timeout ] [--json] [--include-local] - - Options: - --timeout Discovery window in milliseconds (default: 2000) - --json Emit JSON - --include-local Include gateways considered local - -h, --help Show help - """) - return - } - - let displayName = Host.current().localizedName ?? ProcessInfo.processInfo.hostName - let model = GatewayDiscoveryModel( - localDisplayName: displayName, - filterLocalGateways: !opts.includeLocal) - - await MainActor.run { - model.start() - } - - let nanos = UInt64(max(100, opts.timeoutMs)) * 1_000_000 - try? await Task.sleep(nanoseconds: nanos) - - let gateways = await MainActor.run { model.gateways } - let status = await MainActor.run { model.statusText } - - await MainActor.run { - model.stop() - } - - if opts.json { - let payload = DiscoveryOutput( - status: status, - timeoutMs: opts.timeoutMs, - includeLocal: opts.includeLocal, - count: gateways.count, - gateways: gateways.map { - DiscoveryOutput.Gateway( - displayName: $0.displayName, - lanHost: $0.lanHost, - tailnetDns: $0.tailnetDns, - sshPort: $0.sshPort, - gatewayPort: $0.gatewayPort, - cliPath: $0.cliPath, - stableID: $0.stableID, - debugID: $0.debugID, - isLocal: $0.isLocal) - }) - let encoder = JSONEncoder() - encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - if let data = try? encoder.encode(payload), - let json = String(data: data, encoding: .utf8) - { - print(json) - } else { - print("{\"error\":\"failed to encode JSON\"}") - } - return - } - - print("Gateway Discovery (macOS NWBrowser)") - print("Status: \(status)") - print("Found \(gateways.count) gateway(s)\(opts.includeLocal ? "" : " (local filtered)")") - if gateways.isEmpty { return } - - for gateway in gateways { - let hosts = [gateway.tailnetDns, gateway.lanHost] - .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty } - .joined(separator: ", ") - print("- \(gateway.displayName)") - print(" hosts: \(hosts.isEmpty ? "(none)" : hosts)") - print(" ssh: \(gateway.sshPort)") - if let port = gateway.gatewayPort { - print(" gatewayPort: \(port)") - } - if let cliPath = gateway.cliPath { - print(" cliPath: \(cliPath)") - } - print(" isLocal: \(gateway.isLocal)") - print(" stableID: \(gateway.stableID)") - print(" debugID: \(gateway.debugID)") - } - } -} diff --git a/apps/macos/Sources/ClawdbotIPC/IPC.swift b/apps/macos/Sources/ClawdbotIPC/IPC.swift index dc066a10d..058cb0508 100644 --- a/apps/macos/Sources/ClawdbotIPC/IPC.swift +++ b/apps/macos/Sources/ClawdbotIPC/IPC.swift @@ -408,8 +408,7 @@ extension Request: Codable { } // Shared transport settings -public let controlSocketPath = - FileManager.default - .homeDirectoryForCurrentUser - .appendingPathComponent("Library/Application Support/clawdbot/control.sock") - .path +public let controlSocketPath = FileManager() + .homeDirectoryForCurrentUser + .appendingPathComponent("Library/Application Support/clawdbot/control.sock") + .path diff --git a/apps/macos/Sources/ClawdbotMacCLI/ConnectCommand.swift b/apps/macos/Sources/ClawdbotMacCLI/ConnectCommand.swift new file mode 100644 index 000000000..4df1c96a1 --- /dev/null +++ b/apps/macos/Sources/ClawdbotMacCLI/ConnectCommand.swift @@ -0,0 +1,359 @@ +import ClawdbotKit +import ClawdbotProtocol +import Foundation +#if canImport(Darwin) +import Darwin +#endif + +struct ConnectOptions { + var url: String? + var token: String? + var password: String? + var mode: String? + var timeoutMs: Int = 15000 + var json: Bool = false + var probe: Bool = false + var clientId: String = "clawdbot-macos" + var clientMode: String = "ui" + var displayName: String? + var role: String = "operator" + var scopes: [String] = ["operator.admin", "operator.approvals", "operator.pairing"] + var help: Bool = false + + static func parse(_ args: [String]) -> ConnectOptions { + var opts = ConnectOptions() + let flagHandlers: [String: (inout ConnectOptions) -> Void] = [ + "-h": { $0.help = true }, + "--help": { $0.help = true }, + "--json": { $0.json = true }, + "--probe": { $0.probe = true }, + ] + let valueHandlers: [String: (inout ConnectOptions, String) -> Void] = [ + "--url": { $0.url = $1 }, + "--token": { $0.token = $1 }, + "--password": { $0.password = $1 }, + "--mode": { $0.mode = $1 }, + "--timeout": { opts, raw in + if let parsed = Int(raw.trimmingCharacters(in: .whitespacesAndNewlines)) { + opts.timeoutMs = max(250, parsed) + } + }, + "--client-id": { $0.clientId = $1 }, + "--client-mode": { $0.clientMode = $1 }, + "--display-name": { $0.displayName = $1 }, + "--role": { $0.role = $1 }, + "--scopes": { opts, raw in + opts.scopes = raw.split(separator: ",").map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + }, + ] + var i = 0 + while i < args.count { + let arg = args[i] + if let handler = flagHandlers[arg] { + handler(&opts) + i += 1 + continue + } + if let handler = valueHandlers[arg], let value = self.nextValue(args, index: &i) { + handler(&opts, value) + i += 1 + continue + } + i += 1 + } + return opts + } + + private static func nextValue(_ args: [String], index: inout Int) -> String? { + guard index + 1 < args.count else { return nil } + index += 1 + return args[index].trimmingCharacters(in: .whitespacesAndNewlines) + } +} + +struct ConnectOutput: Encodable { + var status: String + var url: String + var mode: String + var role: String + var clientId: String + var clientMode: String + var scopes: [String] + var snapshot: HelloOk? + var health: ProtoAnyCodable? + var error: String? +} + +actor SnapshotStore { + private var value: HelloOk? + + func set(_ snapshot: HelloOk) { + self.value = snapshot + } + + func get() -> HelloOk? { + self.value + } +} + +func runConnect(_ args: [String]) async { + let opts = ConnectOptions.parse(args) + if opts.help { + print(""" + clawdbot-mac connect + + Usage: + clawdbot-mac connect [--url ] [--token ] [--password ] + [--mode ] [--timeout ] [--probe] [--json] + [--client-id ] [--client-mode ] [--display-name ] + [--role ] [--scopes ] + + Options: + --url Gateway WebSocket URL (overrides config) + --token Gateway token (if required) + --password Gateway password (if required) + --mode Resolve from config: local|remote (default: config or local) + --timeout Request timeout (default: 15000) + --probe Force a fresh health probe + --json Emit JSON + --client-id Override client id (default: clawdbot-macos) + --client-mode Override client mode (default: ui) + --display-name Override display name + --role Override role (default: operator) + --scopes Override scopes list + -h, --help Show help + """) + return + } + + let config = loadGatewayConfig() + do { + let endpoint = try resolveGatewayEndpoint(opts: opts, config: config) + let displayName = opts.displayName ?? Host.current().localizedName ?? "Clawdbot macOS Debug CLI" + let connectOptions = GatewayConnectOptions( + role: opts.role, + scopes: opts.scopes, + caps: [], + commands: [], + permissions: [:], + clientId: opts.clientId, + clientMode: opts.clientMode, + clientDisplayName: displayName) + + let snapshotStore = SnapshotStore() + let channel = GatewayChannelActor( + url: endpoint.url, + token: endpoint.token, + password: endpoint.password, + pushHandler: { push in + if case let .snapshot(ok) = push { + await snapshotStore.set(ok) + } + }, + connectOptions: connectOptions) + + let params: [String: KitAnyCodable]? = opts.probe ? ["probe": KitAnyCodable(true)] : nil + let data = try await channel.request( + method: "health", + params: params, + timeoutMs: Double(opts.timeoutMs)) + let health = try? JSONDecoder().decode(ProtoAnyCodable.self, from: data) + let snapshot = await snapshotStore.get() + await channel.shutdown() + + let output = ConnectOutput( + status: "ok", + url: endpoint.url.absoluteString, + mode: endpoint.mode, + role: opts.role, + clientId: opts.clientId, + clientMode: opts.clientMode, + scopes: opts.scopes, + snapshot: snapshot, + health: health, + error: nil) + printConnectOutput(output, json: opts.json) + } catch { + let endpoint = bestEffortEndpoint(opts: opts, config: config) + let fallbackMode = (opts.mode ?? config.mode ?? "local").lowercased() + let output = ConnectOutput( + status: "error", + url: endpoint?.url.absoluteString ?? "unknown", + mode: endpoint?.mode ?? fallbackMode, + role: opts.role, + clientId: opts.clientId, + clientMode: opts.clientMode, + scopes: opts.scopes, + snapshot: nil, + health: nil, + error: error.localizedDescription) + printConnectOutput(output, json: opts.json) + exit(1) + } +} + +private func printConnectOutput(_ output: ConnectOutput, json: Bool) { + if json { + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + if let data = try? encoder.encode(output), + let text = String(data: data, encoding: .utf8) + { + print(text) + } else { + print("{\"error\":\"failed to encode JSON\"}") + } + return + } + + print("Clawdbot macOS Gateway Connect") + print("Status: \(output.status)") + print("URL: \(output.url)") + print("Mode: \(output.mode)") + print("Client: \(output.clientId) (\(output.clientMode))") + print("Role: \(output.role)") + print("Scopes: \(output.scopes.joined(separator: ", "))") + if let snapshot = output.snapshot { + print("Protocol: \(snapshot._protocol)") + if let version = snapshot.server["version"]?.value as? String { + print("Server: \(version)") + } + } + if let health = output.health, + let ok = (health.value as? [String: ProtoAnyCodable])?["ok"]?.value as? Bool + { + print("Health: \(ok ? "ok" : "error")") + } else if output.health != nil { + print("Health: received") + } + if let error = output.error { + print("Error: \(error)") + } +} + +private func resolveGatewayEndpoint(opts: ConnectOptions, config: GatewayConfig) throws -> GatewayEndpoint { + let resolvedMode = (opts.mode ?? config.mode ?? "local").lowercased() + if let raw = opts.url, !raw.isEmpty { + guard let url = URL(string: raw) else { + throw NSError(domain: "Gateway", code: 1, userInfo: [NSLocalizedDescriptionKey: "invalid url: \(raw)"]) + } + return GatewayEndpoint( + url: url, + token: resolvedToken(opts: opts, mode: resolvedMode, config: config), + password: resolvedPassword(opts: opts, mode: resolvedMode, config: config), + mode: resolvedMode) + } + + if resolvedMode == "remote" { + guard let raw = config.remoteUrl?.trimmingCharacters(in: .whitespacesAndNewlines), + !raw.isEmpty + else { + throw NSError( + domain: "Gateway", + code: 1, + userInfo: [NSLocalizedDescriptionKey: "gateway.remote.url is missing"]) + } + guard let url = URL(string: raw) else { + throw NSError(domain: "Gateway", code: 1, userInfo: [NSLocalizedDescriptionKey: "invalid url: \(raw)"]) + } + return GatewayEndpoint( + url: url, + token: resolvedToken(opts: opts, mode: resolvedMode, config: config), + password: resolvedPassword(opts: opts, mode: resolvedMode, config: config), + mode: resolvedMode) + } + + let port = config.port ?? 18789 + let host = resolveLocalHost(bind: config.bind) + guard let url = URL(string: "ws://\(host):\(port)") else { + throw NSError( + domain: "Gateway", + code: 1, + userInfo: [NSLocalizedDescriptionKey: "invalid url: ws://\(host):\(port)"]) + } + return GatewayEndpoint( + url: url, + token: resolvedToken(opts: opts, mode: resolvedMode, config: config), + password: resolvedPassword(opts: opts, mode: resolvedMode, config: config), + mode: resolvedMode) +} + +private func bestEffortEndpoint(opts: ConnectOptions, config: GatewayConfig) -> GatewayEndpoint? { + try? resolveGatewayEndpoint(opts: opts, config: config) +} + +private func resolvedToken(opts: ConnectOptions, mode: String, config: GatewayConfig) -> String? { + if let token = opts.token, !token.isEmpty { return token } + if let token = ProcessInfo.processInfo.environment["CLAWDBOT_GATEWAY_TOKEN"], !token.isEmpty { + return token + } + if mode == "remote" { + return config.remoteToken + } + return config.token +} + +private func resolvedPassword(opts: ConnectOptions, mode: String, config: GatewayConfig) -> String? { + if let password = opts.password, !password.isEmpty { return password } + if let password = ProcessInfo.processInfo.environment["CLAWDBOT_GATEWAY_PASSWORD"], !password.isEmpty { + return password + } + if mode == "remote" { + return config.remotePassword + } + return config.password +} + +private func resolveLocalHost(bind: String?) -> String { + let normalized = (bind ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + let tailnetIP = detectTailnetIPv4() + switch normalized { + case "tailnet": + return tailnetIP ?? "127.0.0.1" + default: + return "127.0.0.1" + } +} + +private func detectTailnetIPv4() -> String? { + var addrList: UnsafeMutablePointer? + guard getifaddrs(&addrList) == 0, let first = addrList else { return nil } + defer { freeifaddrs(addrList) } + + for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) { + let flags = Int32(ptr.pointee.ifa_flags) + let isUp = (flags & IFF_UP) != 0 + let isLoopback = (flags & IFF_LOOPBACK) != 0 + let family = ptr.pointee.ifa_addr.pointee.sa_family + if !isUp || isLoopback || family != UInt8(AF_INET) { continue } + + var addr = ptr.pointee.ifa_addr.pointee + var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST)) + let result = getnameinfo( + &addr, + socklen_t(ptr.pointee.ifa_addr.pointee.sa_len), + &buffer, + socklen_t(buffer.count), + nil, + 0, + NI_NUMERICHOST) + guard result == 0 else { continue } + let len = buffer.prefix { $0 != 0 } + let bytes = len.map { UInt8(bitPattern: $0) } + guard let ip = String(bytes: bytes, encoding: .utf8) else { continue } + if isTailnetIPv4(ip) { return ip } + } + + return nil +} + +private func isTailnetIPv4(_ address: String) -> Bool { + let parts = address.split(separator: ".") + guard parts.count == 4 else { return false } + let octets = parts.compactMap { Int($0) } + guard octets.count == 4 else { return false } + let a = octets[0] + let b = octets[1] + return a == 100 && b >= 64 && b <= 127 +} diff --git a/apps/macos/Sources/ClawdbotMacCLI/DiscoverCommand.swift b/apps/macos/Sources/ClawdbotMacCLI/DiscoverCommand.swift new file mode 100644 index 000000000..12fe1ea37 --- /dev/null +++ b/apps/macos/Sources/ClawdbotMacCLI/DiscoverCommand.swift @@ -0,0 +1,149 @@ +import ClawdbotDiscovery +import Foundation + +struct DiscoveryOptions { + var timeoutMs: Int = 2000 + var json: Bool = false + var includeLocal: Bool = false + var help: Bool = false + + static func parse(_ args: [String]) -> DiscoveryOptions { + var opts = DiscoveryOptions() + var i = 0 + while i < args.count { + let arg = args[i] + switch arg { + case "-h", "--help": + opts.help = true + case "--json": + opts.json = true + case "--include-local": + opts.includeLocal = true + case "--timeout": + let next = (i + 1 < args.count) ? args[i + 1] : nil + if let next, let parsed = Int(next.trimmingCharacters(in: .whitespacesAndNewlines)) { + opts.timeoutMs = max(100, parsed) + i += 1 + } + default: + break + } + i += 1 + } + return opts + } +} + +struct DiscoveryOutput: Encodable { + struct Gateway: Encodable { + var displayName: String + var lanHost: String? + var tailnetDns: String? + var sshPort: Int + var gatewayPort: Int? + var cliPath: String? + var stableID: String + var debugID: String + var isLocal: Bool + } + + var status: String + var timeoutMs: Int + var includeLocal: Bool + var count: Int + var gateways: [Gateway] +} + +func runDiscover(_ args: [String]) async { + let opts = DiscoveryOptions.parse(args) + if opts.help { + print(""" + clawdbot-mac discover + + Usage: + clawdbot-mac discover [--timeout ] [--json] [--include-local] + + Options: + --timeout Discovery window in milliseconds (default: 2000) + --json Emit JSON + --include-local Include gateways considered local + -h, --help Show help + """) + return + } + + let displayName = Host.current().localizedName ?? ProcessInfo.processInfo.hostName + let model = await MainActor.run { + GatewayDiscoveryModel( + localDisplayName: displayName, + filterLocalGateways: !opts.includeLocal) + } + + await MainActor.run { + model.start() + } + + let nanos = UInt64(max(100, opts.timeoutMs)) * 1_000_000 + try? await Task.sleep(nanoseconds: nanos) + + let gateways = await MainActor.run { model.gateways } + let status = await MainActor.run { model.statusText } + + await MainActor.run { + model.stop() + } + + if opts.json { + let payload = DiscoveryOutput( + status: status, + timeoutMs: opts.timeoutMs, + includeLocal: opts.includeLocal, + count: gateways.count, + gateways: gateways.map { + DiscoveryOutput.Gateway( + displayName: $0.displayName, + lanHost: $0.lanHost, + tailnetDns: $0.tailnetDns, + sshPort: $0.sshPort, + gatewayPort: $0.gatewayPort, + cliPath: $0.cliPath, + stableID: $0.stableID, + debugID: $0.debugID, + isLocal: $0.isLocal) + }) + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + if let data = try? encoder.encode(payload), + let json = String(data: data, encoding: .utf8) + { + print(json) + } else { + print("{\"error\":\"failed to encode JSON\"}") + } + return + } + + print("Gateway Discovery (macOS NWBrowser)") + print("Status: \(status)") + print("Found \(gateways.count) gateway(s)\(opts.includeLocal ? "" : " (local filtered)")") + if gateways.isEmpty { return } + + for gateway in gateways { + let hosts = [gateway.tailnetDns, gateway.lanHost] + .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + .joined(separator: ", ") + print("- \(gateway.displayName)") + print(" hosts: \(hosts.isEmpty ? "(none)" : hosts)") + print(" ssh: \(gateway.sshPort)") + if let port = gateway.gatewayPort { + print(" gatewayPort: \(port)") + } + if let cliPath = gateway.cliPath { + print(" cliPath: \(cliPath)") + } + print(" isLocal: \(gateway.isLocal)") + print(" stableID: \(gateway.stableID)") + print(" debugID: \(gateway.debugID)") + } +} diff --git a/apps/macos/Sources/ClawdbotMacCLI/EntryPoint.swift b/apps/macos/Sources/ClawdbotMacCLI/EntryPoint.swift new file mode 100644 index 000000000..58f4501ae --- /dev/null +++ b/apps/macos/Sources/ClawdbotMacCLI/EntryPoint.swift @@ -0,0 +1,56 @@ +import Foundation + +private struct RootCommand { + var name: String + var args: [String] +} + +@main +struct ClawdbotMacCLI { + static func main() async { + let args = Array(CommandLine.arguments.dropFirst()) + let command = parseRootCommand(args) + switch command?.name { + case nil: + printUsage() + case "-h", "--help", "help": + printUsage() + case "connect": + await runConnect(command?.args ?? []) + case "discover": + await runDiscover(command?.args ?? []) + case "wizard": + await runWizardCommand(command?.args ?? []) + default: + fputs("clawdbot-mac: unknown command\n", stderr) + printUsage() + exit(1) + } + } +} + +private func parseRootCommand(_ args: [String]) -> RootCommand? { + guard let first = args.first else { return nil } + return RootCommand(name: first, args: Array(args.dropFirst())) +} + +private func printUsage() { + print(""" + clawdbot-mac + + Usage: + clawdbot-mac connect [--url ] [--token ] [--password ] + [--mode ] [--timeout ] [--probe] [--json] + [--client-id ] [--client-mode ] [--display-name ] + [--role ] [--scopes ] + clawdbot-mac discover [--timeout ] [--json] [--include-local] + clawdbot-mac wizard [--url ] [--token ] [--password ] + [--mode ] [--workspace ] [--json] + + Examples: + clawdbot-mac connect + clawdbot-mac connect --url ws://127.0.0.1:18789 --json + clawdbot-mac discover --timeout 3000 --json + clawdbot-mac wizard --mode local + """) +} diff --git a/apps/macos/Sources/ClawdbotMacCLI/GatewayConfig.swift b/apps/macos/Sources/ClawdbotMacCLI/GatewayConfig.swift new file mode 100644 index 000000000..d39572396 --- /dev/null +++ b/apps/macos/Sources/ClawdbotMacCLI/GatewayConfig.swift @@ -0,0 +1,60 @@ +import Foundation + +struct GatewayConfig { + var mode: String? + var bind: String? + var port: Int? + var remoteUrl: String? + var token: String? + var password: String? + var remoteToken: String? + var remotePassword: String? +} + +struct GatewayEndpoint { + let url: URL + let token: String? + let password: String? + let mode: String +} + +func loadGatewayConfig() -> GatewayConfig { + let url = FileManager().homeDirectoryForCurrentUser + .appendingPathComponent(".clawdbot") + .appendingPathComponent("clawdbot.json") + guard let data = try? Data(contentsOf: url) else { return GatewayConfig() } + guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { + return GatewayConfig() + } + + var cfg = GatewayConfig() + if let gateway = json["gateway"] as? [String: Any] { + cfg.mode = gateway["mode"] as? String + cfg.bind = gateway["bind"] as? String + cfg.port = gateway["port"] as? Int ?? parseInt(gateway["port"]) + + if let auth = gateway["auth"] as? [String: Any] { + cfg.token = auth["token"] as? String + cfg.password = auth["password"] as? String + } + if let remote = gateway["remote"] as? [String: Any] { + cfg.remoteUrl = remote["url"] as? String + cfg.remoteToken = remote["token"] as? String + cfg.remotePassword = remote["password"] as? String + } + } + return cfg +} + +func parseInt(_ value: Any?) -> Int? { + switch value { + case let number as Int: + number + case let number as Double: + Int(number) + case let raw as String: + Int(raw.trimmingCharacters(in: .whitespacesAndNewlines)) + default: + nil + } +} diff --git a/apps/macos/Sources/ClawdbotMacCLI/TypeAliases.swift b/apps/macos/Sources/ClawdbotMacCLI/TypeAliases.swift new file mode 100644 index 000000000..191b8976b --- /dev/null +++ b/apps/macos/Sources/ClawdbotMacCLI/TypeAliases.swift @@ -0,0 +1,5 @@ +import ClawdbotKit +import ClawdbotProtocol + +typealias ProtoAnyCodable = ClawdbotProtocol.AnyCodable +typealias KitAnyCodable = ClawdbotKit.AnyCodable diff --git a/apps/macos/Sources/ClawdbotWizardCLI/main.swift b/apps/macos/Sources/ClawdbotMacCLI/WizardCommand.swift similarity index 67% rename from apps/macos/Sources/ClawdbotWizardCLI/main.swift rename to apps/macos/Sources/ClawdbotMacCLI/WizardCommand.swift index bf328b87c..6b7e342e5 100644 --- a/apps/macos/Sources/ClawdbotWizardCLI/main.swift +++ b/apps/macos/Sources/ClawdbotMacCLI/WizardCommand.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import ClawdbotProtocol import Darwin import Foundation @@ -48,17 +49,6 @@ struct WizardCliOptions { } } -struct GatewayConfig { - var mode: String? - var bind: String? - var port: Int? - var remoteUrl: String? - var token: String? - var password: String? - var remoteToken: String? - var remotePassword: String? -} - enum WizardCliError: Error, CustomStringConvertible { case invalidUrl(String) case missingRemoteUrl @@ -77,68 +67,56 @@ enum WizardCliError: Error, CustomStringConvertible { } } -@main -struct ClawdbotWizardCLI { - static func main() async { - let opts = WizardCliOptions.parse(Array(CommandLine.arguments.dropFirst())) - if opts.help { - printUsage() - return - } +func runWizardCommand(_ args: [String]) async { + let opts = WizardCliOptions.parse(args) + if opts.help { + print(""" + clawdbot-mac wizard - let config = loadGatewayConfig() - do { - guard isatty(STDIN_FILENO) != 0 else { - throw WizardCliError.gatewayError("Wizard requires an interactive TTY.") - } - let endpoint = try resolveGatewayEndpoint(opts: opts, config: config) - let client = GatewayWizardClient( - url: endpoint.url, - token: endpoint.token, - password: endpoint.password, - json: opts.json) - try await client.connect() - defer { Task { await client.close() } } - try await runWizard(client: client, opts: opts) - } catch { - fputs("wizard: \(error)\n", stderr) - exit(1) + Usage: + clawdbot-mac wizard [--url ] [--token ] [--password ] + [--mode ] [--workspace ] [--json] + + Options: + --url Gateway WebSocket URL (overrides config) + --token Gateway token (if required) + --password Gateway password (if required) + --mode Wizard mode (local|remote). Default: local + --workspace Wizard workspace override + --json Print raw wizard responses + -h, --help Show help + """) + return + } + + let config = loadGatewayConfig() + do { + guard isatty(STDIN_FILENO) != 0 else { + throw WizardCliError.gatewayError("Wizard requires an interactive TTY.") } + let endpoint = try resolveWizardGatewayEndpoint(opts: opts, config: config) + let client = GatewayWizardClient( + url: endpoint.url, + token: endpoint.token, + password: endpoint.password, + json: opts.json) + try await client.connect() + defer { Task { await client.close() } } + try await runWizard(client: client, opts: opts) + } catch { + fputs("wizard: \(error)\n", stderr) + exit(1) } } -private struct GatewayEndpoint { - let url: URL - let token: String? - let password: String? -} - -private func printUsage() { - print(""" - clawdbot-mac-wizard - - Usage: - clawdbot-mac-wizard [--url ] [--token ] [--password ] - [--mode ] [--workspace ] [--json] - - Options: - --url Gateway WebSocket URL (overrides config) - --token Gateway token (if required) - --password Gateway password (if required) - --mode Wizard mode (local|remote). Default: local - --workspace Wizard workspace override - --json Print raw wizard responses - -h, --help Show help - """) -} - -private func resolveGatewayEndpoint(opts: WizardCliOptions, config: GatewayConfig) throws -> GatewayEndpoint { +private func resolveWizardGatewayEndpoint(opts: WizardCliOptions, config: GatewayConfig) throws -> GatewayEndpoint { if let raw = opts.url, !raw.isEmpty { guard let url = URL(string: raw) else { throw WizardCliError.invalidUrl(raw) } return GatewayEndpoint( url: url, token: resolvedToken(opts: opts, config: config), - password: resolvedPassword(opts: opts, config: config)) + password: resolvedPassword(opts: opts, config: config), + mode: (config.mode ?? "local").lowercased()) } let mode = (config.mode ?? "local").lowercased() @@ -150,7 +128,8 @@ private func resolveGatewayEndpoint(opts: WizardCliOptions, config: GatewayConfi return GatewayEndpoint( url: url, token: resolvedToken(opts: opts, config: config), - password: resolvedPassword(opts: opts, config: config)) + password: resolvedPassword(opts: opts, config: config), + mode: mode) } let port = config.port ?? 18789 @@ -161,7 +140,8 @@ private func resolveGatewayEndpoint(opts: WizardCliOptions, config: GatewayConfi return GatewayEndpoint( url: url, token: resolvedToken(opts: opts, config: config), - password: resolvedPassword(opts: opts, config: config)) + password: resolvedPassword(opts: opts, config: config), + mode: mode) } private func resolvedToken(opts: WizardCliOptions, config: GatewayConfig) -> String? { @@ -186,48 +166,11 @@ private func resolvedPassword(opts: WizardCliOptions, config: GatewayConfig) -> return config.password } -private func loadGatewayConfig() -> GatewayConfig { - let url = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent(".clawdbot") - .appendingPathComponent("clawdbot.json") - guard let data = try? Data(contentsOf: url) else { return GatewayConfig() } - guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { - return GatewayConfig() - } - - var cfg = GatewayConfig() - if let gateway = json["gateway"] as? [String: Any] { - cfg.mode = gateway["mode"] as? String - cfg.bind = gateway["bind"] as? String - cfg.port = gateway["port"] as? Int ?? parseInt(gateway["port"]) - - if let auth = gateway["auth"] as? [String: Any] { - cfg.token = auth["token"] as? String - cfg.password = auth["password"] as? String - } - if let remote = gateway["remote"] as? [String: Any] { - cfg.remoteUrl = remote["url"] as? String - cfg.remoteToken = remote["token"] as? String - cfg.remotePassword = remote["password"] as? String - } - } - return cfg -} - -private func parseInt(_ value: Any?) -> Int? { - switch value { - case let number as Int: - number - case let number as Double: - Int(number) - case let raw as String: - Int(raw.trimmingCharacters(in: .whitespacesAndNewlines)) - default: - nil - } -} - actor GatewayWizardClient { + private enum ConnectChallengeError: Error { + case timeout + } + private let url: URL private let token: String? private let password: String? @@ -235,6 +178,7 @@ actor GatewayWizardClient { private let encoder = JSONEncoder() private let decoder = JSONDecoder() private let session = URLSession(configuration: .default) + private let connectChallengeTimeoutSeconds: Double = 0.75 private var task: URLSessionWebSocketTask? init(url: URL, token: String?, password: String?, json: Bool) { @@ -257,7 +201,7 @@ actor GatewayWizardClient { self.task = nil } - func request(method: String, params: [String: AnyCodable]?) async throws -> ResponseFrame { + func request(method: String, params: [String: ProtoAnyCodable]?) async throws -> ResponseFrame { guard let task = self.task else { throw WizardCliError.gatewayError("gateway not connected") } @@ -266,7 +210,7 @@ actor GatewayWizardClient { type: "req", id: id, method: method, - params: params.map { AnyCodable($0) }) + params: params.map { ProtoAnyCodable($0) }) let data = try self.encoder.encode(frame) try await task.send(.data(data)) @@ -309,28 +253,66 @@ actor GatewayWizardClient { } let osVersion = ProcessInfo.processInfo.operatingSystemVersion let platform = "macos \(osVersion.majorVersion).\(osVersion.minorVersion).\(osVersion.patchVersion)" - let client: [String: AnyCodable] = [ - "id": AnyCodable("clawdbot-macos"), - "displayName": AnyCodable(Host.current().localizedName ?? "Clawdbot macOS Wizard CLI"), - "version": AnyCodable("dev"), - "platform": AnyCodable(platform), - "deviceFamily": AnyCodable("Mac"), - "mode": AnyCodable("ui"), - "instanceId": AnyCodable(UUID().uuidString), + let clientId = "clawdbot-macos" + let clientMode = "ui" + let role = "operator" + let scopes: [String] = [] + let client: [String: ProtoAnyCodable] = [ + "id": ProtoAnyCodable(clientId), + "displayName": ProtoAnyCodable(Host.current().localizedName ?? "Clawdbot macOS Wizard CLI"), + "version": ProtoAnyCodable("dev"), + "platform": ProtoAnyCodable(platform), + "deviceFamily": ProtoAnyCodable("Mac"), + "mode": ProtoAnyCodable(clientMode), + "instanceId": ProtoAnyCodable(UUID().uuidString), ] - var params: [String: AnyCodable] = [ - "minProtocol": AnyCodable(GATEWAY_PROTOCOL_VERSION), - "maxProtocol": AnyCodable(GATEWAY_PROTOCOL_VERSION), - "client": AnyCodable(client), - "caps": AnyCodable([String]()), - "locale": AnyCodable(Locale.preferredLanguages.first ?? Locale.current.identifier), - "userAgent": AnyCodable(ProcessInfo.processInfo.operatingSystemVersionString), + var params: [String: ProtoAnyCodable] = [ + "minProtocol": ProtoAnyCodable(GATEWAY_PROTOCOL_VERSION), + "maxProtocol": ProtoAnyCodable(GATEWAY_PROTOCOL_VERSION), + "client": ProtoAnyCodable(client), + "caps": ProtoAnyCodable([String]()), + "locale": ProtoAnyCodable(Locale.preferredLanguages.first ?? Locale.current.identifier), + "userAgent": ProtoAnyCodable(ProcessInfo.processInfo.operatingSystemVersionString), + "role": ProtoAnyCodable(role), + "scopes": ProtoAnyCodable(scopes), ] if let token = self.token { - params["auth"] = AnyCodable(["token": AnyCodable(token)]) + params["auth"] = ProtoAnyCodable(["token": ProtoAnyCodable(token)]) } else if let password = self.password { - params["auth"] = AnyCodable(["password": AnyCodable(password)]) + params["auth"] = ProtoAnyCodable(["password": ProtoAnyCodable(password)]) + } + let connectNonce = try await self.waitForConnectChallenge() + let identity = DeviceIdentityStore.loadOrCreate() + let signedAtMs = Int(Date().timeIntervalSince1970 * 1000) + let scopesValue = scopes.joined(separator: ",") + var payloadParts = [ + connectNonce == nil ? "v1" : "v2", + identity.deviceId, + clientId, + clientMode, + role, + scopesValue, + String(signedAtMs), + self.token ?? "", + ] + if let connectNonce { + payloadParts.append(connectNonce) + } + let payload = payloadParts.joined(separator: "|") + if let signature = DeviceIdentityStore.signPayload(payload, identity: identity), + let publicKey = DeviceIdentityStore.publicKeyBase64Url(identity) + { + var device: [String: ProtoAnyCodable] = [ + "id": ProtoAnyCodable(identity.deviceId), + "publicKey": ProtoAnyCodable(publicKey), + "signature": ProtoAnyCodable(signature), + "signedAt": ProtoAnyCodable(signedAtMs), + ] + if let connectNonce { + device["nonce"] = ProtoAnyCodable(connectNonce) + } + params["device"] = ProtoAnyCodable(device) } let reqId = UUID().uuidString @@ -338,31 +320,58 @@ actor GatewayWizardClient { type: "req", id: reqId, method: "connect", - params: AnyCodable(params)) + params: ProtoAnyCodable(params)) let data = try self.encoder.encode(frame) try await task.send(.data(data)) - let message = try await task.receive() - let frameResponse = try decodeFrame(message) - guard case let .res(res) = frameResponse, res.id == reqId else { - throw WizardCliError.gatewayError("connect failed (unexpected response)") + while true { + let message = try await task.receive() + let frameResponse = try decodeFrame(message) + if case let .res(res) = frameResponse, res.id == reqId { + if res.ok == false { + let msg = (res.error?["message"]?.value as? String) ?? "gateway connect failed" + throw WizardCliError.gatewayError(msg) + } + _ = try self.decodePayload(res, as: HelloOk.self) + return + } } - if res.ok == false { - let msg = (res.error?["message"]?.value as? String) ?? "gateway connect failed" - throw WizardCliError.gatewayError(msg) + } + + private func waitForConnectChallenge() async throws -> String? { + guard let task = self.task else { return nil } + do { + return try await AsyncTimeout.withTimeout( + seconds: self.connectChallengeTimeoutSeconds, + onTimeout: { ConnectChallengeError.timeout }, + operation: { + while true { + let message = try await task.receive() + let frame = try await self.decodeFrame(message) + if case let .event(evt) = frame, evt.event == "connect.challenge" { + if let payload = evt.payload?.value as? [String: ProtoAnyCodable], + let nonce = payload["nonce"]?.value as? String + { + return nonce + } + } + } + }) + } catch { + if error is ConnectChallengeError { return nil } + throw error } - _ = try self.decodePayload(res, as: HelloOk.self) } } private func runWizard(client: GatewayWizardClient, opts: WizardCliOptions) async throws { - var params: [String: AnyCodable] = [:] + var params: [String: ProtoAnyCodable] = [:] let mode = opts.mode.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() if mode == "local" || mode == "remote" { - params["mode"] = AnyCodable(mode) + params["mode"] = ProtoAnyCodable(mode) } if let workspace = opts.workspace?.trimmingCharacters(in: .whitespacesAndNewlines), !workspace.isEmpty { - params["workspace"] = AnyCodable(workspace) + params["workspace"] = ProtoAnyCodable(workspace) } let startResponse = try await client.request(method: "wizard.start", params: params) @@ -395,17 +404,17 @@ private func runWizard(client: GatewayWizardClient, opts: WizardCliOptions) asyn if let step = decodeWizardStep(nextResult.step) { let answer = try promptAnswer(for: step) - var answerPayload: [String: AnyCodable] = [ - "stepId": AnyCodable(step.id), + var answerPayload: [String: ProtoAnyCodable] = [ + "stepId": ProtoAnyCodable(step.id), ] if !(answer is NSNull) { - answerPayload["value"] = AnyCodable(answer) + answerPayload["value"] = ProtoAnyCodable(answer) } let response = try await client.request( method: "wizard.next", params: [ - "sessionId": AnyCodable(sessionId), - "answer": AnyCodable(answerPayload), + "sessionId": ProtoAnyCodable(sessionId), + "answer": ProtoAnyCodable(answerPayload), ]) nextResult = try await client.decodePayload(response, as: WizardNextResult.self) if opts.json { @@ -414,7 +423,7 @@ private func runWizard(client: GatewayWizardClient, opts: WizardCliOptions) asyn } else { let response = try await client.request( method: "wizard.next", - params: ["sessionId": AnyCodable(sessionId)]) + params: ["sessionId": ProtoAnyCodable(sessionId)]) nextResult = try await client.decodePayload(response, as: WizardNextResult.self) if opts.json { dumpResult(response) @@ -424,7 +433,7 @@ private func runWizard(client: GatewayWizardClient, opts: WizardCliOptions) asyn } catch WizardCliError.cancelled { _ = try? await client.request( method: "wizard.cancel", - params: ["sessionId": AnyCodable(sessionId)]) + params: ["sessionId": ProtoAnyCodable(sessionId)]) throw WizardCliError.cancelled } } diff --git a/apps/macos/Sources/ClawdbotProtocol/GatewayModels.swift b/apps/macos/Sources/ClawdbotProtocol/GatewayModels.swift index 6be608f70..9d2ca5ed4 100644 --- a/apps/macos/Sources/ClawdbotProtocol/GatewayModels.swift +++ b/apps/macos/Sources/ClawdbotProtocol/GatewayModels.swift @@ -5,6 +5,7 @@ public let GATEWAY_PROTOCOL_VERSION = 3 public enum ErrorCode: String, Codable, Sendable { case notLinked = "NOT_LINKED" + case notPaired = "NOT_PAIRED" case agentTimeout = "AGENT_TIMEOUT" case invalidRequest = "INVALID_REQUEST" case unavailable = "UNAVAILABLE" @@ -15,6 +16,12 @@ public struct ConnectParams: Codable, Sendable { public let maxprotocol: Int public let client: [String: AnyCodable] public let caps: [String]? + public let commands: [String]? + public let permissions: [String: AnyCodable]? + public let pathenv: String? + public let role: String? + public let scopes: [String]? + public let device: [String: AnyCodable]? public let auth: [String: AnyCodable]? public let locale: String? public let useragent: String? @@ -24,6 +31,12 @@ public struct ConnectParams: Codable, Sendable { maxprotocol: Int, client: [String: AnyCodable], caps: [String]?, + commands: [String]?, + permissions: [String: AnyCodable]?, + pathenv: String?, + role: String?, + scopes: [String]?, + device: [String: AnyCodable]?, auth: [String: AnyCodable]?, locale: String?, useragent: String? @@ -32,6 +45,12 @@ public struct ConnectParams: Codable, Sendable { self.maxprotocol = maxprotocol self.client = client self.caps = caps + self.commands = commands + self.permissions = permissions + self.pathenv = pathenv + self.role = role + self.scopes = scopes + self.device = device self.auth = auth self.locale = locale self.useragent = useragent @@ -41,6 +60,12 @@ public struct ConnectParams: Codable, Sendable { case maxprotocol = "maxProtocol" case client case caps + case commands + case permissions + case pathenv = "pathEnv" + case role + case scopes + case device case auth case locale case useragent = "userAgent" @@ -54,6 +79,7 @@ public struct HelloOk: Codable, Sendable { public let features: [String: AnyCodable] public let snapshot: Snapshot public let canvashosturl: String? + public let auth: [String: AnyCodable]? public let policy: [String: AnyCodable] public init( @@ -63,6 +89,7 @@ public struct HelloOk: Codable, Sendable { features: [String: AnyCodable], snapshot: Snapshot, canvashosturl: String?, + auth: [String: AnyCodable]?, policy: [String: AnyCodable] ) { self.type = type @@ -71,6 +98,7 @@ public struct HelloOk: Codable, Sendable { self.features = features self.snapshot = snapshot self.canvashosturl = canvashosturl + self.auth = auth self.policy = policy } private enum CodingKeys: String, CodingKey { @@ -80,6 +108,7 @@ public struct HelloOk: Codable, Sendable { case features case snapshot case canvashosturl = "canvasHostUrl" + case auth case policy } } @@ -180,6 +209,9 @@ public struct PresenceEntry: Codable, Sendable { public let tags: [String]? public let text: String? public let ts: Int + public let deviceid: String? + public let roles: [String]? + public let scopes: [String]? public let instanceid: String? public init( @@ -195,6 +227,9 @@ public struct PresenceEntry: Codable, Sendable { tags: [String]?, text: String?, ts: Int, + deviceid: String?, + roles: [String]?, + scopes: [String]?, instanceid: String? ) { self.host = host @@ -209,6 +244,9 @@ public struct PresenceEntry: Codable, Sendable { self.tags = tags self.text = text self.ts = ts + self.deviceid = deviceid + self.roles = roles + self.scopes = scopes self.instanceid = instanceid } private enum CodingKeys: String, CodingKey { @@ -224,6 +262,9 @@ public struct PresenceEntry: Codable, Sendable { case tags case text case ts + case deviceid = "deviceId" + case roles + case scopes case instanceid = "instanceId" } } @@ -344,35 +385,43 @@ public struct SendParams: Codable, Sendable { public let to: String public let message: String public let mediaurl: String? + public let mediaurls: [String]? public let gifplayback: Bool? public let channel: String? public let accountid: String? + public let sessionkey: String? public let idempotencykey: String public init( to: String, message: String, mediaurl: String?, + mediaurls: [String]?, gifplayback: Bool?, channel: String?, accountid: String?, + sessionkey: String?, idempotencykey: String ) { self.to = to self.message = message self.mediaurl = mediaurl + self.mediaurls = mediaurls self.gifplayback = gifplayback self.channel = channel self.accountid = accountid + self.sessionkey = sessionkey self.idempotencykey = idempotencykey } private enum CodingKeys: String, CodingKey { case to case message case mediaurl = "mediaUrl" + case mediaurls = "mediaUrls" case gifplayback = "gifPlayback" case channel case accountid = "accountId" + case sessionkey = "sessionKey" case idempotencykey = "idempotencyKey" } } @@ -420,13 +469,22 @@ public struct PollParams: Codable, Sendable { public struct AgentParams: Codable, Sendable { public let message: String + public let agentid: String? public let to: String? + public let replyto: String? public let sessionid: String? public let sessionkey: String? public let thinking: String? public let deliver: Bool? public let attachments: [AnyCodable]? public let channel: String? + public let replychannel: String? + public let accountid: String? + public let replyaccountid: String? + public let threadid: String? + public let groupid: String? + public let groupchannel: String? + public let groupspace: String? public let timeout: Int? public let lane: String? public let extrasystemprompt: String? @@ -436,13 +494,22 @@ public struct AgentParams: Codable, Sendable { public init( message: String, + agentid: String?, to: String?, + replyto: String?, sessionid: String?, sessionkey: String?, thinking: String?, deliver: Bool?, attachments: [AnyCodable]?, channel: String?, + replychannel: String?, + accountid: String?, + replyaccountid: String?, + threadid: String?, + groupid: String?, + groupchannel: String?, + groupspace: String?, timeout: Int?, lane: String?, extrasystemprompt: String?, @@ -451,13 +518,22 @@ public struct AgentParams: Codable, Sendable { spawnedby: String? ) { self.message = message + self.agentid = agentid self.to = to + self.replyto = replyto self.sessionid = sessionid self.sessionkey = sessionkey self.thinking = thinking self.deliver = deliver self.attachments = attachments self.channel = channel + self.replychannel = replychannel + self.accountid = accountid + self.replyaccountid = replyaccountid + self.threadid = threadid + self.groupid = groupid + self.groupchannel = groupchannel + self.groupspace = groupspace self.timeout = timeout self.lane = lane self.extrasystemprompt = extrasystemprompt @@ -467,13 +543,22 @@ public struct AgentParams: Codable, Sendable { } private enum CodingKeys: String, CodingKey { case message + case agentid = "agentId" case to + case replyto = "replyTo" case sessionid = "sessionId" case sessionkey = "sessionKey" case thinking case deliver case attachments case channel + case replychannel = "replyChannel" + case accountid = "accountId" + case replyaccountid = "replyAccountId" + case threadid = "threadId" + case groupid = "groupId" + case groupchannel = "groupChannel" + case groupspace = "groupSpace" case timeout case lane case extrasystemprompt = "extraSystemPrompt" @@ -483,6 +568,44 @@ public struct AgentParams: Codable, Sendable { } } +public struct AgentIdentityParams: Codable, Sendable { + public let agentid: String? + public let sessionkey: String? + + public init( + agentid: String?, + sessionkey: String? + ) { + self.agentid = agentid + self.sessionkey = sessionkey + } + private enum CodingKeys: String, CodingKey { + case agentid = "agentId" + case sessionkey = "sessionKey" + } +} + +public struct AgentIdentityResult: Codable, Sendable { + public let agentid: String + public let name: String? + public let avatar: String? + + public init( + agentid: String, + name: String?, + avatar: String? + ) { + self.agentid = agentid + self.name = name + self.avatar = avatar + } + private enum CodingKeys: String, CodingKey { + case agentid = "agentId" + case name + case avatar + } +} + public struct AgentWaitParams: Codable, Sendable { public let runid: String public let timeoutms: Int? @@ -522,6 +645,8 @@ public struct NodePairRequestParams: Codable, Sendable { public let displayname: String? public let platform: String? public let version: String? + public let coreversion: String? + public let uiversion: String? public let devicefamily: String? public let modelidentifier: String? public let caps: [String]? @@ -534,6 +659,8 @@ public struct NodePairRequestParams: Codable, Sendable { displayname: String?, platform: String?, version: String?, + coreversion: String?, + uiversion: String?, devicefamily: String?, modelidentifier: String?, caps: [String]?, @@ -545,6 +672,8 @@ public struct NodePairRequestParams: Codable, Sendable { self.displayname = displayname self.platform = platform self.version = version + self.coreversion = coreversion + self.uiversion = uiversion self.devicefamily = devicefamily self.modelidentifier = modelidentifier self.caps = caps @@ -557,6 +686,8 @@ public struct NodePairRequestParams: Codable, Sendable { case displayname = "displayName" case platform case version + case coreversion = "coreVersion" + case uiversion = "uiVersion" case devicefamily = "deviceFamily" case modelidentifier = "modelIdentifier" case caps @@ -674,45 +805,166 @@ public struct NodeInvokeParams: Codable, Sendable { } } +public struct NodeInvokeResultParams: Codable, Sendable { + public let id: String + public let nodeid: String + public let ok: Bool + public let payload: AnyCodable? + public let payloadjson: String? + public let error: [String: AnyCodable]? + + public init( + id: String, + nodeid: String, + ok: Bool, + payload: AnyCodable?, + payloadjson: String?, + error: [String: AnyCodable]? + ) { + self.id = id + self.nodeid = nodeid + self.ok = ok + self.payload = payload + self.payloadjson = payloadjson + self.error = error + } + private enum CodingKeys: String, CodingKey { + case id + case nodeid = "nodeId" + case ok + case payload + case payloadjson = "payloadJSON" + case error + } +} + +public struct NodeEventParams: Codable, Sendable { + public let event: String + public let payload: AnyCodable? + public let payloadjson: String? + + public init( + event: String, + payload: AnyCodable?, + payloadjson: String? + ) { + self.event = event + self.payload = payload + self.payloadjson = payloadjson + } + private enum CodingKeys: String, CodingKey { + case event + case payload + case payloadjson = "payloadJSON" + } +} + +public struct NodeInvokeRequestEvent: Codable, Sendable { + public let id: String + public let nodeid: String + public let command: String + public let paramsjson: String? + public let timeoutms: Int? + public let idempotencykey: String? + + public init( + id: String, + nodeid: String, + command: String, + paramsjson: String?, + timeoutms: Int?, + idempotencykey: String? + ) { + self.id = id + self.nodeid = nodeid + self.command = command + self.paramsjson = paramsjson + self.timeoutms = timeoutms + self.idempotencykey = idempotencykey + } + private enum CodingKeys: String, CodingKey { + case id + case nodeid = "nodeId" + case command + case paramsjson = "paramsJSON" + case timeoutms = "timeoutMs" + case idempotencykey = "idempotencyKey" + } +} + public struct SessionsListParams: Codable, Sendable { public let limit: Int? public let activeminutes: Int? public let includeglobal: Bool? public let includeunknown: Bool? + public let includederivedtitles: Bool? + public let includelastmessage: Bool? public let label: String? public let spawnedby: String? public let agentid: String? + public let search: String? public init( limit: Int?, activeminutes: Int?, includeglobal: Bool?, includeunknown: Bool?, + includederivedtitles: Bool?, + includelastmessage: Bool?, label: String?, spawnedby: String?, - agentid: String? + agentid: String?, + search: String? ) { self.limit = limit self.activeminutes = activeminutes self.includeglobal = includeglobal self.includeunknown = includeunknown + self.includederivedtitles = includederivedtitles + self.includelastmessage = includelastmessage self.label = label self.spawnedby = spawnedby self.agentid = agentid + self.search = search } private enum CodingKeys: String, CodingKey { case limit case activeminutes = "activeMinutes" case includeglobal = "includeGlobal" case includeunknown = "includeUnknown" + case includederivedtitles = "includeDerivedTitles" + case includelastmessage = "includeLastMessage" case label case spawnedby = "spawnedBy" case agentid = "agentId" + case search + } +} + +public struct SessionsPreviewParams: Codable, Sendable { + public let keys: [String] + public let limit: Int? + public let maxchars: Int? + + public init( + keys: [String], + limit: Int?, + maxchars: Int? + ) { + self.keys = keys + self.limit = limit + self.maxchars = maxchars + } + private enum CodingKeys: String, CodingKey { + case keys + case limit + case maxchars = "maxChars" } } public struct SessionsResolveParams: Codable, Sendable { public let key: String? + public let sessionid: String? public let label: String? public let agentid: String? public let spawnedby: String? @@ -721,6 +973,7 @@ public struct SessionsResolveParams: Codable, Sendable { public init( key: String?, + sessionid: String?, label: String?, agentid: String?, spawnedby: String?, @@ -728,6 +981,7 @@ public struct SessionsResolveParams: Codable, Sendable { includeunknown: Bool? ) { self.key = key + self.sessionid = sessionid self.label = label self.agentid = agentid self.spawnedby = spawnedby @@ -736,6 +990,7 @@ public struct SessionsResolveParams: Codable, Sendable { } private enum CodingKeys: String, CodingKey { case key + case sessionid = "sessionId" case label case agentid = "agentId" case spawnedby = "spawnedBy" @@ -752,6 +1007,10 @@ public struct SessionsPatchParams: Codable, Sendable { public let reasoninglevel: AnyCodable? public let responseusage: AnyCodable? public let elevatedlevel: AnyCodable? + public let exechost: AnyCodable? + public let execsecurity: AnyCodable? + public let execask: AnyCodable? + public let execnode: AnyCodable? public let model: AnyCodable? public let spawnedby: AnyCodable? public let sendpolicy: AnyCodable? @@ -765,6 +1024,10 @@ public struct SessionsPatchParams: Codable, Sendable { reasoninglevel: AnyCodable?, responseusage: AnyCodable?, elevatedlevel: AnyCodable?, + exechost: AnyCodable?, + execsecurity: AnyCodable?, + execask: AnyCodable?, + execnode: AnyCodable?, model: AnyCodable?, spawnedby: AnyCodable?, sendpolicy: AnyCodable?, @@ -777,6 +1040,10 @@ public struct SessionsPatchParams: Codable, Sendable { self.reasoninglevel = reasoninglevel self.responseusage = responseusage self.elevatedlevel = elevatedlevel + self.exechost = exechost + self.execsecurity = execsecurity + self.execask = execask + self.execnode = execnode self.model = model self.spawnedby = spawnedby self.sendpolicy = sendpolicy @@ -790,6 +1057,10 @@ public struct SessionsPatchParams: Codable, Sendable { case reasoninglevel = "reasoningLevel" case responseusage = "responseUsage" case elevatedlevel = "elevatedLevel" + case exechost = "execHost" + case execsecurity = "execSecurity" + case execask = "execAsk" + case execnode = "execNode" case model case spawnedby = "spawnedBy" case sendpolicy = "sendPolicy" @@ -896,17 +1167,29 @@ public struct ConfigApplyParams: Codable, Sendable { public struct ConfigPatchParams: Codable, Sendable { public let raw: String public let basehash: String? + public let sessionkey: String? + public let note: String? + public let restartdelayms: Int? public init( raw: String, - basehash: String? + basehash: String?, + sessionkey: String?, + note: String?, + restartdelayms: Int? ) { self.raw = raw self.basehash = basehash + self.sessionkey = sessionkey + self.note = note + self.restartdelayms = restartdelayms } private enum CodingKeys: String, CodingKey { case raw case basehash = "baseHash" + case sessionkey = "sessionKey" + case note + case restartdelayms = "restartDelayMs" } } @@ -1152,6 +1435,9 @@ public struct ChannelsStatusResult: Codable, Sendable { public let ts: Int public let channelorder: [String] public let channellabels: [String: AnyCodable] + public let channeldetaillabels: [String: AnyCodable]? + public let channelsystemimages: [String: AnyCodable]? + public let channelmeta: [[String: AnyCodable]]? public let channels: [String: AnyCodable] public let channelaccounts: [String: AnyCodable] public let channeldefaultaccountid: [String: AnyCodable] @@ -1160,6 +1446,9 @@ public struct ChannelsStatusResult: Codable, Sendable { ts: Int, channelorder: [String], channellabels: [String: AnyCodable], + channeldetaillabels: [String: AnyCodable]?, + channelsystemimages: [String: AnyCodable]?, + channelmeta: [[String: AnyCodable]]?, channels: [String: AnyCodable], channelaccounts: [String: AnyCodable], channeldefaultaccountid: [String: AnyCodable] @@ -1167,6 +1456,9 @@ public struct ChannelsStatusResult: Codable, Sendable { self.ts = ts self.channelorder = channelorder self.channellabels = channellabels + self.channeldetaillabels = channeldetaillabels + self.channelsystemimages = channelsystemimages + self.channelmeta = channelmeta self.channels = channels self.channelaccounts = channelaccounts self.channeldefaultaccountid = channeldefaultaccountid @@ -1175,6 +1467,9 @@ public struct ChannelsStatusResult: Codable, Sendable { case ts case channelorder = "channelOrder" case channellabels = "channelLabels" + case channeldetaillabels = "channelDetailLabels" + case channelsystemimages = "channelSystemImages" + case channelmeta = "channelMeta" case channels case channelaccounts = "channelAccounts" case channeldefaultaccountid = "channelDefaultAccountId" @@ -1243,17 +1538,21 @@ public struct WebLoginWaitParams: Codable, Sendable { public struct AgentSummary: Codable, Sendable { public let id: String public let name: String? + public let identity: [String: AnyCodable]? public init( id: String, - name: String? + name: String?, + identity: [String: AnyCodable]? ) { self.id = id self.name = name + self.identity = identity } private enum CodingKeys: String, CodingKey { case id case name + case identity } } @@ -1333,6 +1632,22 @@ public struct ModelsListResult: Codable, Sendable { public struct SkillsStatusParams: Codable, Sendable { } +public struct SkillsBinsParams: Codable, Sendable { +} + +public struct SkillsBinsResult: Codable, Sendable { + public let bins: [String] + + public init( + bins: [String] + ) { + self.bins = bins + } + private enum CodingKeys: String, CodingKey { + case bins + } +} + public struct SkillsInstallParams: Codable, Sendable { public let name: String public let installid: String @@ -1608,6 +1923,308 @@ public struct LogsTailResult: Codable, Sendable { } } +public struct ExecApprovalsGetParams: Codable, Sendable { +} + +public struct ExecApprovalsSetParams: Codable, Sendable { + public let file: [String: AnyCodable] + public let basehash: String? + + public init( + file: [String: AnyCodable], + basehash: String? + ) { + self.file = file + self.basehash = basehash + } + private enum CodingKeys: String, CodingKey { + case file + case basehash = "baseHash" + } +} + +public struct ExecApprovalsNodeGetParams: Codable, Sendable { + public let nodeid: String + + public init( + nodeid: String + ) { + self.nodeid = nodeid + } + private enum CodingKeys: String, CodingKey { + case nodeid = "nodeId" + } +} + +public struct ExecApprovalsNodeSetParams: Codable, Sendable { + public let nodeid: String + public let file: [String: AnyCodable] + public let basehash: String? + + public init( + nodeid: String, + file: [String: AnyCodable], + basehash: String? + ) { + self.nodeid = nodeid + self.file = file + self.basehash = basehash + } + private enum CodingKeys: String, CodingKey { + case nodeid = "nodeId" + case file + case basehash = "baseHash" + } +} + +public struct ExecApprovalsSnapshot: Codable, Sendable { + public let path: String + public let exists: Bool + public let hash: String + public let file: [String: AnyCodable] + + public init( + path: String, + exists: Bool, + hash: String, + file: [String: AnyCodable] + ) { + self.path = path + self.exists = exists + self.hash = hash + self.file = file + } + private enum CodingKeys: String, CodingKey { + case path + case exists + case hash + case file + } +} + +public struct ExecApprovalRequestParams: Codable, Sendable { + public let id: String? + public let command: String + public let cwd: AnyCodable? + public let host: AnyCodable? + public let security: AnyCodable? + public let ask: AnyCodable? + public let agentid: AnyCodable? + public let resolvedpath: AnyCodable? + public let sessionkey: AnyCodable? + public let timeoutms: Int? + + public init( + id: String?, + command: String, + cwd: AnyCodable?, + host: AnyCodable?, + security: AnyCodable?, + ask: AnyCodable?, + agentid: AnyCodable?, + resolvedpath: AnyCodable?, + sessionkey: AnyCodable?, + timeoutms: Int? + ) { + self.id = id + self.command = command + self.cwd = cwd + self.host = host + self.security = security + self.ask = ask + self.agentid = agentid + self.resolvedpath = resolvedpath + self.sessionkey = sessionkey + self.timeoutms = timeoutms + } + private enum CodingKeys: String, CodingKey { + case id + case command + case cwd + case host + case security + case ask + case agentid = "agentId" + case resolvedpath = "resolvedPath" + case sessionkey = "sessionKey" + case timeoutms = "timeoutMs" + } +} + +public struct ExecApprovalResolveParams: Codable, Sendable { + public let id: String + public let decision: String + + public init( + id: String, + decision: String + ) { + self.id = id + self.decision = decision + } + private enum CodingKeys: String, CodingKey { + case id + case decision + } +} + +public struct DevicePairListParams: Codable, Sendable { +} + +public struct DevicePairApproveParams: Codable, Sendable { + public let requestid: String + + public init( + requestid: String + ) { + self.requestid = requestid + } + private enum CodingKeys: String, CodingKey { + case requestid = "requestId" + } +} + +public struct DevicePairRejectParams: Codable, Sendable { + public let requestid: String + + public init( + requestid: String + ) { + self.requestid = requestid + } + private enum CodingKeys: String, CodingKey { + case requestid = "requestId" + } +} + +public struct DeviceTokenRotateParams: Codable, Sendable { + public let deviceid: String + public let role: String + public let scopes: [String]? + + public init( + deviceid: String, + role: String, + scopes: [String]? + ) { + self.deviceid = deviceid + self.role = role + self.scopes = scopes + } + private enum CodingKeys: String, CodingKey { + case deviceid = "deviceId" + case role + case scopes + } +} + +public struct DeviceTokenRevokeParams: Codable, Sendable { + public let deviceid: String + public let role: String + + public init( + deviceid: String, + role: String + ) { + self.deviceid = deviceid + self.role = role + } + private enum CodingKeys: String, CodingKey { + case deviceid = "deviceId" + case role + } +} + +public struct DevicePairRequestedEvent: Codable, Sendable { + public let requestid: String + public let deviceid: String + public let publickey: String + public let displayname: String? + public let platform: String? + public let clientid: String? + public let clientmode: String? + public let role: String? + public let roles: [String]? + public let scopes: [String]? + public let remoteip: String? + public let silent: Bool? + public let isrepair: Bool? + public let ts: Int + + public init( + requestid: String, + deviceid: String, + publickey: String, + displayname: String?, + platform: String?, + clientid: String?, + clientmode: String?, + role: String?, + roles: [String]?, + scopes: [String]?, + remoteip: String?, + silent: Bool?, + isrepair: Bool?, + ts: Int + ) { + self.requestid = requestid + self.deviceid = deviceid + self.publickey = publickey + self.displayname = displayname + self.platform = platform + self.clientid = clientid + self.clientmode = clientmode + self.role = role + self.roles = roles + self.scopes = scopes + self.remoteip = remoteip + self.silent = silent + self.isrepair = isrepair + self.ts = ts + } + private enum CodingKeys: String, CodingKey { + case requestid = "requestId" + case deviceid = "deviceId" + case publickey = "publicKey" + case displayname = "displayName" + case platform + case clientid = "clientId" + case clientmode = "clientMode" + case role + case roles + case scopes + case remoteip = "remoteIp" + case silent + case isrepair = "isRepair" + case ts + } +} + +public struct DevicePairResolvedEvent: Codable, Sendable { + public let requestid: String + public let deviceid: String + public let decision: String + public let ts: Int + + public init( + requestid: String, + deviceid: String, + decision: String, + ts: Int + ) { + self.requestid = requestid + self.deviceid = deviceid + self.decision = decision + self.ts = ts + } + private enum CodingKeys: String, CodingKey { + case requestid = "requestId" + case deviceid = "deviceId" + case decision + case ts + } +} + public struct ChatHistoryParams: Codable, Sendable { public let sessionkey: String public let limit: Int? diff --git a/apps/macos/Tests/ClawdbotIPCTests/AgentWorkspaceTests.swift b/apps/macos/Tests/ClawdbotIPCTests/AgentWorkspaceTests.swift index 320a44c39..9368f643c 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/AgentWorkspaceTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/AgentWorkspaceTests.swift @@ -6,7 +6,7 @@ import Testing struct AgentWorkspaceTests { @Test func displayPathUsesTildeForHome() { - let home = FileManager.default.homeDirectoryForCurrentUser + let home = FileManager().homeDirectoryForCurrentUser #expect(AgentWorkspace.displayPath(for: home) == "~") let inside = home.appendingPathComponent("Projects", isDirectory: true) @@ -28,12 +28,12 @@ struct AgentWorkspaceTests { @Test func bootstrapCreatesAgentsFileWhenMissing() throws { - let tmp = FileManager.default.temporaryDirectory + let tmp = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-ws-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: tmp) } + defer { try? FileManager().removeItem(at: tmp) } let agentsURL = try AgentWorkspace.bootstrap(workspaceURL: tmp) - #expect(FileManager.default.fileExists(atPath: agentsURL.path)) + #expect(FileManager().fileExists(atPath: agentsURL.path)) let contents = try String(contentsOf: agentsURL, encoding: .utf8) #expect(contents.contains("# AGENTS.md")) @@ -41,9 +41,9 @@ struct AgentWorkspaceTests { let identityURL = tmp.appendingPathComponent(AgentWorkspace.identityFilename) let userURL = tmp.appendingPathComponent(AgentWorkspace.userFilename) let bootstrapURL = tmp.appendingPathComponent(AgentWorkspace.bootstrapFilename) - #expect(FileManager.default.fileExists(atPath: identityURL.path)) - #expect(FileManager.default.fileExists(atPath: userURL.path)) - #expect(FileManager.default.fileExists(atPath: bootstrapURL.path)) + #expect(FileManager().fileExists(atPath: identityURL.path)) + #expect(FileManager().fileExists(atPath: userURL.path)) + #expect(FileManager().fileExists(atPath: bootstrapURL.path)) let second = try AgentWorkspace.bootstrap(workspaceURL: tmp) #expect(second == agentsURL) @@ -51,10 +51,10 @@ struct AgentWorkspaceTests { @Test func bootstrapSafetyRejectsNonEmptyFolderWithoutAgents() throws { - let tmp = FileManager.default.temporaryDirectory + let tmp = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-ws-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: tmp) } - try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true) + defer { try? FileManager().removeItem(at: tmp) } + try FileManager().createDirectory(at: tmp, withIntermediateDirectories: true) let marker = tmp.appendingPathComponent("notes.txt") try "hello".write(to: marker, atomically: true, encoding: .utf8) @@ -69,10 +69,10 @@ struct AgentWorkspaceTests { @Test func bootstrapSafetyAllowsExistingAgentsFile() throws { - let tmp = FileManager.default.temporaryDirectory + let tmp = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-ws-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: tmp) } - try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true) + defer { try? FileManager().removeItem(at: tmp) } + try FileManager().createDirectory(at: tmp, withIntermediateDirectories: true) let agents = tmp.appendingPathComponent(AgentWorkspace.agentsFilename) try "# AGENTS.md".write(to: agents, atomically: true, encoding: .utf8) @@ -87,25 +87,25 @@ struct AgentWorkspaceTests { @Test func bootstrapSkipsBootstrapFileWhenWorkspaceHasContent() throws { - let tmp = FileManager.default.temporaryDirectory + let tmp = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-ws-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: tmp) } - try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true) + defer { try? FileManager().removeItem(at: tmp) } + try FileManager().createDirectory(at: tmp, withIntermediateDirectories: true) let marker = tmp.appendingPathComponent("notes.txt") try "hello".write(to: marker, atomically: true, encoding: .utf8) _ = try AgentWorkspace.bootstrap(workspaceURL: tmp) let bootstrapURL = tmp.appendingPathComponent(AgentWorkspace.bootstrapFilename) - #expect(!FileManager.default.fileExists(atPath: bootstrapURL.path)) + #expect(!FileManager().fileExists(atPath: bootstrapURL.path)) } @Test func needsBootstrapFalseWhenIdentityAlreadySet() throws { - let tmp = FileManager.default.temporaryDirectory + let tmp = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-ws-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: tmp) } - try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true) + defer { try? FileManager().removeItem(at: tmp) } + try FileManager().createDirectory(at: tmp, withIntermediateDirectories: true) let identityURL = tmp.appendingPathComponent(AgentWorkspace.identityFilename) try """ # IDENTITY.md - Agent Identity diff --git a/apps/macos/Tests/ClawdbotIPCTests/AnthropicAuthResolverTests.swift b/apps/macos/Tests/ClawdbotIPCTests/AnthropicAuthResolverTests.swift index 41f9ffefb..1af9108c2 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/AnthropicAuthResolverTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/AnthropicAuthResolverTests.swift @@ -6,9 +6,9 @@ import Testing struct AnthropicAuthResolverTests { @Test func prefersOAuthFileOverEnv() throws { - let dir = FileManager.default.temporaryDirectory + let dir = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-oauth-\(UUID().uuidString)", isDirectory: true) - try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try FileManager().createDirectory(at: dir, withIntermediateDirectories: true) let oauthFile = dir.appendingPathComponent("oauth.json") let payload = [ "anthropic": [ diff --git a/apps/macos/Tests/ClawdbotIPCTests/BridgeServerTests.swift b/apps/macos/Tests/ClawdbotIPCTests/BridgeServerTests.swift deleted file mode 100644 index 9b43d669b..000000000 --- a/apps/macos/Tests/ClawdbotIPCTests/BridgeServerTests.swift +++ /dev/null @@ -1,10 +0,0 @@ -import Testing -@testable import Clawdbot - -@Suite(.serialized) -struct BridgeServerTests { - @Test func bridgeServerExercisesPaths() async { - let server = BridgeServer() - await server.exerciseForTesting() - } -} diff --git a/apps/macos/Tests/ClawdbotIPCTests/CLIInstallerTests.swift b/apps/macos/Tests/ClawdbotIPCTests/CLIInstallerTests.swift index 829dd28a4..46144a455 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/CLIInstallerTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/CLIInstallerTests.swift @@ -6,7 +6,7 @@ import Testing @MainActor struct CLIInstallerTests { @Test func installedLocationFindsExecutable() throws { - let fm = FileManager.default + let fm = FileManager() let root = fm.temporaryDirectory.appendingPathComponent( "clawdbot-cli-installer-\(UUID().uuidString)") defer { try? fm.removeItem(at: root) } diff --git a/apps/macos/Tests/ClawdbotIPCTests/CanvasFileWatcherTests.swift b/apps/macos/Tests/ClawdbotIPCTests/CanvasFileWatcherTests.swift index 03fe58fda..28093abc8 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/CanvasFileWatcherTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/CanvasFileWatcherTests.swift @@ -7,13 +7,13 @@ import Testing private func makeTempDir() throws -> URL { let base = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) let dir = base.appendingPathComponent("clawdbot-canvaswatch-\(UUID().uuidString)", isDirectory: true) - try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try FileManager().createDirectory(at: dir, withIntermediateDirectories: true) return dir } @Test func detectsInPlaceFileWrites() async throws { let dir = try self.makeTempDir() - defer { try? FileManager.default.removeItem(at: dir) } + defer { try? FileManager().removeItem(at: dir) } let file = dir.appendingPathComponent("index.html") try "hello".write(to: file, atomically: false, encoding: .utf8) diff --git a/apps/macos/Tests/ClawdbotIPCTests/CanvasWindowSmokeTests.swift b/apps/macos/Tests/ClawdbotIPCTests/CanvasWindowSmokeTests.swift index 1168802b2..92f20bf0b 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/CanvasWindowSmokeTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/CanvasWindowSmokeTests.swift @@ -8,10 +8,10 @@ import Testing @MainActor struct CanvasWindowSmokeTests { @Test func panelControllerShowsAndHides() async throws { - let root = FileManager.default.temporaryDirectory + let root = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-canvas-test-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: root) } + try FileManager().createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager().removeItem(at: root) } let anchor = { NSRect(x: 200, y: 400, width: 40, height: 40) } let controller = try CanvasWindowController( @@ -31,10 +31,10 @@ struct CanvasWindowSmokeTests { } @Test func windowControllerShowsAndCloses() async throws { - let root = FileManager.default.temporaryDirectory + let root = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-canvas-test-\(UUID().uuidString)") - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: root) } + try FileManager().createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager().removeItem(at: root) } let controller = try CanvasWindowController( sessionKey: "main", diff --git a/apps/macos/Tests/ClawdbotIPCTests/ConnectionsSettingsSmokeTests.swift b/apps/macos/Tests/ClawdbotIPCTests/ChannelsSettingsSmokeTests.swift similarity index 83% rename from apps/macos/Tests/ClawdbotIPCTests/ConnectionsSettingsSmokeTests.swift rename to apps/macos/Tests/ClawdbotIPCTests/ChannelsSettingsSmokeTests.swift index 9bca297bd..2b1eced84 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/ConnectionsSettingsSmokeTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/ChannelsSettingsSmokeTests.swift @@ -3,11 +3,13 @@ import SwiftUI import Testing @testable import Clawdbot +private typealias SnapshotAnyCodable = Clawdbot.AnyCodable + @Suite(.serialized) @MainActor -struct ConnectionsSettingsSmokeTests { - @Test func connectionsSettingsBuildsBodyWithSnapshot() { - let store = ConnectionsStore(isPreview: true) +struct ChannelsSettingsSmokeTests { + @Test func channelsSettingsBuildsBodyWithSnapshot() { + let store = ChannelsStore(isPreview: true) store.snapshot = ChannelsStatusSnapshot( ts: 1_700_000_000_000, channelOrder: ["whatsapp", "telegram", "signal", "imessage"], @@ -17,8 +19,11 @@ struct ConnectionsSettingsSmokeTests { "signal": "Signal", "imessage": "iMessage", ], + channelDetailLabels: nil, + channelSystemImages: nil, + channelMeta: nil, channels: [ - "whatsapp": AnyCodable([ + "whatsapp": SnapshotAnyCodable([ "configured": true, "linked": true, "authAgeMs": 86_400_000, @@ -37,7 +42,7 @@ struct ConnectionsSettingsSmokeTests { "lastEventAt": 1_700_000_060_000, "lastError": "needs login", ]), - "telegram": AnyCodable([ + "telegram": SnapshotAnyCodable([ "configured": true, "tokenSource": "env", "running": true, @@ -52,7 +57,7 @@ struct ConnectionsSettingsSmokeTests { ], "lastProbeAt": 1_700_000_050_000, ]), - "signal": AnyCodable([ + "signal": SnapshotAnyCodable([ "configured": true, "baseUrl": "http://127.0.0.1:8080", "running": true, @@ -65,7 +70,7 @@ struct ConnectionsSettingsSmokeTests { ], "lastProbeAt": 1_700_000_050_000, ]), - "imessage": AnyCodable([ + "imessage": SnapshotAnyCodable([ "configured": false, "running": false, "lastError": "not configured", @@ -84,20 +89,13 @@ struct ConnectionsSettingsSmokeTests { store.whatsappLoginMessage = "Scan QR" store.whatsappLoginQrDataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMB/ay7pS8AAAAASUVORK5CYII=" - store.telegramToken = "123:abc" - store.telegramRequireMention = false - store.telegramAllowFrom = "123456789" - store.telegramProxy = "socks5://localhost:9050" - store.telegramWebhookUrl = "https://example.com/telegram" - store.telegramWebhookSecret = "secret" - store.telegramWebhookPath = "/telegram" - let view = ConnectionsSettings(store: store) + let view = ChannelsSettings(store: store) _ = view.body } - @Test func connectionsSettingsBuildsBodyWithoutSnapshot() { - let store = ConnectionsStore(isPreview: true) + @Test func channelsSettingsBuildsBodyWithoutSnapshot() { + let store = ChannelsStore(isPreview: true) store.snapshot = ChannelsStatusSnapshot( ts: 1_700_000_000_000, channelOrder: ["whatsapp", "telegram", "signal", "imessage"], @@ -107,15 +105,18 @@ struct ConnectionsSettingsSmokeTests { "signal": "Signal", "imessage": "iMessage", ], + channelDetailLabels: nil, + channelSystemImages: nil, + channelMeta: nil, channels: [ - "whatsapp": AnyCodable([ + "whatsapp": SnapshotAnyCodable([ "configured": false, "linked": false, "running": false, "connected": false, "reconnectAttempts": 0, ]), - "telegram": AnyCodable([ + "telegram": SnapshotAnyCodable([ "configured": false, "running": false, "lastError": "bot missing", @@ -127,7 +128,7 @@ struct ConnectionsSettingsSmokeTests { ], "lastProbeAt": 1_700_000_100_000, ]), - "signal": AnyCodable([ + "signal": SnapshotAnyCodable([ "configured": false, "baseUrl": "http://127.0.0.1:8080", "running": false, @@ -140,7 +141,7 @@ struct ConnectionsSettingsSmokeTests { ], "lastProbeAt": 1_700_000_200_000, ]), - "imessage": AnyCodable([ + "imessage": SnapshotAnyCodable([ "configured": false, "running": false, "lastError": "not configured", @@ -157,7 +158,7 @@ struct ConnectionsSettingsSmokeTests { "imessage": "default", ]) - let view = ConnectionsSettings(store: store) + let view = ChannelsSettings(store: store) _ = view.body } } diff --git a/apps/macos/Tests/ClawdbotIPCTests/ClawdbotConfigFileTests.swift b/apps/macos/Tests/ClawdbotIPCTests/ClawdbotConfigFileTests.swift index 9ee97e22c..15a0f3905 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/ClawdbotConfigFileTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/ClawdbotConfigFileTests.swift @@ -6,7 +6,7 @@ import Testing struct ClawdbotConfigFileTests { @Test func configPathRespectsEnvOverride() async { - let override = FileManager.default.temporaryDirectory + let override = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-config-\(UUID().uuidString)") .appendingPathComponent("clawdbot.json") .path @@ -19,7 +19,7 @@ struct ClawdbotConfigFileTests { @MainActor @Test func remoteGatewayPortParsesAndMatchesHost() async { - let override = FileManager.default.temporaryDirectory + let override = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-config-\(UUID().uuidString)") .appendingPathComponent("clawdbot.json") .path @@ -28,13 +28,13 @@ struct ClawdbotConfigFileTests { ClawdbotConfigFile.saveDict([ "gateway": [ "remote": [ - "url": "ws://bridge.ts.net:19999", + "url": "ws://gateway.ts.net:19999", ], ], ]) #expect(ClawdbotConfigFile.remoteGatewayPort() == 19999) - #expect(ClawdbotConfigFile.remoteGatewayPort(matchingHost: "bridge.ts.net") == 19999) - #expect(ClawdbotConfigFile.remoteGatewayPort(matchingHost: "bridge") == 19999) + #expect(ClawdbotConfigFile.remoteGatewayPort(matchingHost: "gateway.ts.net") == 19999) + #expect(ClawdbotConfigFile.remoteGatewayPort(matchingHost: "gateway") == 19999) #expect(ClawdbotConfigFile.remoteGatewayPort(matchingHost: "other.ts.net") == nil) } } @@ -42,7 +42,7 @@ struct ClawdbotConfigFileTests { @MainActor @Test func setRemoteGatewayUrlPreservesScheme() async { - let override = FileManager.default.temporaryDirectory + let override = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-config-\(UUID().uuidString)") .appendingPathComponent("clawdbot.json") .path @@ -64,7 +64,7 @@ struct ClawdbotConfigFileTests { @Test func stateDirOverrideSetsConfigPath() async { - let dir = FileManager.default.temporaryDirectory + let dir = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-state-\(UUID().uuidString)", isDirectory: true) .path diff --git a/apps/macos/Tests/ClawdbotIPCTests/ClawdbotOAuthStoreTests.swift b/apps/macos/Tests/ClawdbotIPCTests/ClawdbotOAuthStoreTests.swift index 4f4c8542a..0fcfdec84 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/ClawdbotOAuthStoreTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/ClawdbotOAuthStoreTests.swift @@ -6,7 +6,7 @@ import Testing struct ClawdbotOAuthStoreTests { @Test func returnsMissingWhenFileAbsent() { - let url = FileManager.default.temporaryDirectory + let url = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-oauth-\(UUID().uuidString)") .appendingPathComponent("oauth.json") #expect(ClawdbotOAuthStore.anthropicOAuthStatus(at: url) == .missingFile) @@ -24,7 +24,7 @@ struct ClawdbotOAuthStoreTests { } } - let dir = FileManager.default.temporaryDirectory + let dir = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-oauth-\(UUID().uuidString)", isDirectory: true) setenv(key, dir.path, 1) @@ -85,9 +85,9 @@ struct ClawdbotOAuthStoreTests { } private func writeOAuthFile(_ json: [String: Any]) throws -> URL { - let dir = FileManager.default.temporaryDirectory + let dir = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-oauth-\(UUID().uuidString)", isDirectory: true) - try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try FileManager().createDirectory(at: dir, withIntermediateDirectories: true) let url = dir.appendingPathComponent("oauth.json") let data = try JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted, .sortedKeys]) diff --git a/apps/macos/Tests/ClawdbotIPCTests/CommandResolverTests.swift b/apps/macos/Tests/ClawdbotIPCTests/CommandResolverTests.swift index 2830f0929..827057888 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/CommandResolverTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/CommandResolverTests.swift @@ -12,16 +12,16 @@ import Testing private func makeTempDir() throws -> URL { let base = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) let dir = base.appendingPathComponent(UUID().uuidString, isDirectory: true) - try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try FileManager().createDirectory(at: dir, withIntermediateDirectories: true) return dir } private func makeExec(at path: URL) throws { - try FileManager.default.createDirectory( + try FileManager().createDirectory( at: path.deletingLastPathComponent(), withIntermediateDirectories: true) - FileManager.default.createFile(atPath: path.path, contents: Data("echo ok\n".utf8)) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path.path) + FileManager().createFile(atPath: path.path, contents: Data("echo ok\n".utf8)) + try FileManager().setAttributes([.posixPermissions: 0o755], ofItemAtPath: path.path) } @Test func prefersClawdbotBinary() async throws { @@ -34,7 +34,7 @@ import Testing let clawdbotPath = tmp.appendingPathComponent("node_modules/.bin/clawdbot") try self.makeExec(at: clawdbotPath) - let cmd = CommandResolver.clawdbotCommand(subcommand: "gateway", defaults: defaults) + let cmd = CommandResolver.clawdbotCommand(subcommand: "gateway", defaults: defaults, configRoot: [:]) #expect(cmd.prefix(2).elementsEqual([clawdbotPath.path, "gateway"])) } @@ -49,12 +49,13 @@ import Testing let scriptPath = tmp.appendingPathComponent("bin/clawdbot.js") try self.makeExec(at: nodePath) try "#!/bin/sh\necho v22.0.0\n".write(to: nodePath, atomically: true, encoding: .utf8) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: nodePath.path) + try FileManager().setAttributes([.posixPermissions: 0o755], ofItemAtPath: nodePath.path) try self.makeExec(at: scriptPath) let cmd = CommandResolver.clawdbotCommand( subcommand: "rpc", defaults: defaults, + configRoot: [:], searchPaths: [tmp.appendingPathComponent("node_modules/.bin").path]) #expect(cmd.count >= 3) @@ -75,7 +76,7 @@ import Testing let pnpmPath = tmp.appendingPathComponent("node_modules/.bin/pnpm") try self.makeExec(at: pnpmPath) - let cmd = CommandResolver.clawdbotCommand(subcommand: "rpc", defaults: defaults) + let cmd = CommandResolver.clawdbotCommand(subcommand: "rpc", defaults: defaults, configRoot: [:]) #expect(cmd.prefix(4).elementsEqual([pnpmPath.path, "--silent", "clawdbot", "rpc"])) } @@ -93,7 +94,8 @@ import Testing let cmd = CommandResolver.clawdbotCommand( subcommand: "health", extraArgs: ["--json", "--timeout", "5"], - defaults: defaults) + defaults: defaults, + configRoot: [:]) #expect(cmd.prefix(5).elementsEqual([pnpmPath.path, "--silent", "clawdbot", "health", "--json"])) #expect(cmd.suffix(2).elementsEqual(["--timeout", "5"])) @@ -114,7 +116,11 @@ import Testing defaults.set("/tmp/id_ed25519", forKey: remoteIdentityKey) defaults.set("/srv/clawdbot", forKey: remoteProjectRootKey) - let cmd = CommandResolver.clawdbotCommand(subcommand: "status", extraArgs: ["--json"], defaults: defaults) + let cmd = CommandResolver.clawdbotCommand( + subcommand: "status", + extraArgs: ["--json"], + defaults: defaults, + configRoot: [:]) #expect(cmd.first == "/usr/bin/ssh") #expect(cmd.contains("clawd@example.com")) @@ -128,4 +134,27 @@ import Testing #expect(script.contains("CLI=")) } } + + @Test func configRootLocalOverridesRemoteDefaults() async throws { + let defaults = self.makeDefaults() + defaults.set(AppState.ConnectionMode.remote.rawValue, forKey: connectionModeKey) + defaults.set("clawd@example.com:2222", forKey: remoteTargetKey) + + let tmp = try makeTempDir() + CommandResolver.setProjectRoot(tmp.path) + + let clawdbotPath = tmp.appendingPathComponent("node_modules/.bin/clawdbot") + try self.makeExec(at: clawdbotPath) + + let cmd = CommandResolver.clawdbotCommand( + subcommand: "daemon", + defaults: defaults, + configRoot: ["gateway": ["mode": "local"]]) + + #expect(cmd.first == clawdbotPath.path) + #expect(cmd.count >= 2) + if cmd.count >= 2 { + #expect(cmd[1] == "daemon") + } + } } diff --git a/apps/macos/Tests/ClawdbotIPCTests/CronJobEditorSmokeTests.swift b/apps/macos/Tests/ClawdbotIPCTests/CronJobEditorSmokeTests.swift index 02e8c1e69..1a0fbf786 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/CronJobEditorSmokeTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/CronJobEditorSmokeTests.swift @@ -11,16 +11,19 @@ struct CronJobEditorSmokeTests { } @Test func cronJobEditorBuildsBodyForNewJob() { + let channelsStore = ChannelsStore(isPreview: true) let view = CronJobEditor( job: nil, isSaving: .constant(false), error: .constant(nil), + channelsStore: channelsStore, onCancel: {}, onSave: { _ in }) _ = view.body } @Test func cronJobEditorBuildsBodyForExistingJob() { + let channelsStore = ChannelsStore(isPreview: true) let job = CronJob( id: "job-1", agentId: "ops", @@ -54,31 +57,36 @@ struct CronJobEditorSmokeTests { job: job, isSaving: .constant(false), error: .constant(nil), + channelsStore: channelsStore, onCancel: {}, onSave: { _ in }) _ = view.body } @Test func cronJobEditorExercisesBuilders() { + let channelsStore = ChannelsStore(isPreview: true) var view = CronJobEditor( job: nil, isSaving: .constant(false), error: .constant(nil), + channelsStore: channelsStore, onCancel: {}, onSave: { _ in }) view.exerciseForTesting() } @Test func cronJobEditorIncludesDeleteAfterRunForAtSchedule() throws { + let channelsStore = ChannelsStore(isPreview: true) let view = CronJobEditor( job: nil, isSaving: .constant(false), error: .constant(nil), + channelsStore: channelsStore, onCancel: {}, onSave: { _ in }) var root: [String: Any] = [:] - view.applyDeleteAfterRun(to: &root, scheduleKind: .at, deleteAfterRun: true) + view.applyDeleteAfterRun(to: &root, scheduleKind: CronJobEditor.ScheduleKind.at, deleteAfterRun: true) let raw = root["deleteAfterRun"] as? Bool #expect(raw == true) } diff --git a/apps/macos/Tests/ClawdbotIPCTests/ExecAllowlistTests.swift b/apps/macos/Tests/ClawdbotIPCTests/ExecAllowlistTests.swift new file mode 100644 index 000000000..5d03344d9 --- /dev/null +++ b/apps/macos/Tests/ClawdbotIPCTests/ExecAllowlistTests.swift @@ -0,0 +1,49 @@ +import Foundation +import Testing +@testable import Clawdbot + +struct ExecAllowlistTests { + @Test func matchUsesResolvedPath() { + let entry = ExecAllowlistEntry(pattern: "/opt/homebrew/bin/rg") + let resolution = ExecCommandResolution( + rawExecutable: "rg", + resolvedPath: "/opt/homebrew/bin/rg", + executableName: "rg", + cwd: nil) + let match = ExecAllowlistMatcher.match(entries: [entry], resolution: resolution) + #expect(match?.pattern == entry.pattern) + } + + @Test func matchUsesBasenameForSimplePattern() { + let entry = ExecAllowlistEntry(pattern: "rg") + let resolution = ExecCommandResolution( + rawExecutable: "rg", + resolvedPath: "/opt/homebrew/bin/rg", + executableName: "rg", + cwd: nil) + let match = ExecAllowlistMatcher.match(entries: [entry], resolution: resolution) + #expect(match?.pattern == entry.pattern) + } + + @Test func matchIsCaseInsensitive() { + let entry = ExecAllowlistEntry(pattern: "RG") + let resolution = ExecCommandResolution( + rawExecutable: "rg", + resolvedPath: "/opt/homebrew/bin/rg", + executableName: "rg", + cwd: nil) + let match = ExecAllowlistMatcher.match(entries: [entry], resolution: resolution) + #expect(match?.pattern == entry.pattern) + } + + @Test func matchSupportsGlobStar() { + let entry = ExecAllowlistEntry(pattern: "/opt/**/rg") + let resolution = ExecCommandResolution( + rawExecutable: "rg", + resolvedPath: "/opt/homebrew/bin/rg", + executableName: "rg", + cwd: nil) + let match = ExecAllowlistMatcher.match(entries: [entry], resolution: resolution) + #expect(match?.pattern == entry.pattern) + } +} diff --git a/apps/macos/Tests/ClawdbotIPCTests/ExecApprovalHelpersTests.swift b/apps/macos/Tests/ClawdbotIPCTests/ExecApprovalHelpersTests.swift new file mode 100644 index 000000000..a1774d49f --- /dev/null +++ b/apps/macos/Tests/ClawdbotIPCTests/ExecApprovalHelpersTests.swift @@ -0,0 +1,60 @@ +import Foundation +import Testing +@testable import Clawdbot + +@Suite struct ExecApprovalHelpersTests { + @Test func parseDecisionTrimsAndRejectsInvalid() { + #expect(ExecApprovalHelpers.parseDecision("allow-once") == .allowOnce) + #expect(ExecApprovalHelpers.parseDecision(" allow-always ") == .allowAlways) + #expect(ExecApprovalHelpers.parseDecision("deny") == .deny) + #expect(ExecApprovalHelpers.parseDecision("") == nil) + #expect(ExecApprovalHelpers.parseDecision("nope") == nil) + } + + @Test func allowlistPatternPrefersResolution() { + let resolved = ExecCommandResolution( + rawExecutable: "rg", + resolvedPath: "/opt/homebrew/bin/rg", + executableName: "rg", + cwd: nil) + #expect(ExecApprovalHelpers.allowlistPattern(command: ["rg"], resolution: resolved) == resolved.resolvedPath) + + let rawOnly = ExecCommandResolution( + rawExecutable: "rg", + resolvedPath: nil, + executableName: "rg", + cwd: nil) + #expect(ExecApprovalHelpers.allowlistPattern(command: ["rg"], resolution: rawOnly) == "rg") + #expect(ExecApprovalHelpers.allowlistPattern(command: ["rg"], resolution: nil) == "rg") + #expect(ExecApprovalHelpers.allowlistPattern(command: [], resolution: nil) == nil) + } + + @Test func requiresAskMatchesPolicy() { + let entry = ExecAllowlistEntry(pattern: "/bin/ls", lastUsedAt: nil, lastUsedCommand: nil, lastResolvedPath: nil) + #expect(ExecApprovalHelpers.requiresAsk( + ask: .always, + security: .deny, + allowlistMatch: nil, + skillAllow: false)) + #expect(ExecApprovalHelpers.requiresAsk( + ask: .onMiss, + security: .allowlist, + allowlistMatch: nil, + skillAllow: false)) + #expect(!ExecApprovalHelpers.requiresAsk( + ask: .onMiss, + security: .allowlist, + allowlistMatch: entry, + skillAllow: false)) + #expect(!ExecApprovalHelpers.requiresAsk( + ask: .onMiss, + security: .allowlist, + allowlistMatch: nil, + skillAllow: true)) + #expect(!ExecApprovalHelpers.requiresAsk( + ask: .off, + security: .allowlist, + allowlistMatch: nil, + skillAllow: false)) + } +} diff --git a/apps/macos/Tests/ClawdbotIPCTests/ExecApprovalsGatewayPrompterTests.swift b/apps/macos/Tests/ClawdbotIPCTests/ExecApprovalsGatewayPrompterTests.swift new file mode 100644 index 000000000..88fb02f2b --- /dev/null +++ b/apps/macos/Tests/ClawdbotIPCTests/ExecApprovalsGatewayPrompterTests.swift @@ -0,0 +1,56 @@ +import Testing +@testable import Clawdbot + +@Suite +@MainActor +struct ExecApprovalsGatewayPrompterTests { + @Test func sessionMatchPrefersActiveSession() { + let matches = ExecApprovalsGatewayPrompter._testShouldPresent( + mode: .remote, + activeSession: " main ", + requestSession: "main", + lastInputSeconds: nil) + #expect(matches) + + let mismatched = ExecApprovalsGatewayPrompter._testShouldPresent( + mode: .remote, + activeSession: "other", + requestSession: "main", + lastInputSeconds: 0) + #expect(!mismatched) + } + + @Test func sessionFallbackUsesRecentActivity() { + let recent = ExecApprovalsGatewayPrompter._testShouldPresent( + mode: .remote, + activeSession: nil, + requestSession: "main", + lastInputSeconds: 10, + thresholdSeconds: 120) + #expect(recent) + + let stale = ExecApprovalsGatewayPrompter._testShouldPresent( + mode: .remote, + activeSession: nil, + requestSession: "main", + lastInputSeconds: 200, + thresholdSeconds: 120) + #expect(!stale) + } + + @Test func defaultBehaviorMatchesMode() { + let local = ExecApprovalsGatewayPrompter._testShouldPresent( + mode: .local, + activeSession: nil, + requestSession: nil, + lastInputSeconds: 400) + #expect(local) + + let remote = ExecApprovalsGatewayPrompter._testShouldPresent( + mode: .remote, + activeSession: nil, + requestSession: nil, + lastInputSeconds: 400) + #expect(!remote) + } +} diff --git a/apps/macos/Tests/ClawdbotIPCTests/FileHandleLegacyAPIGuardTests.swift b/apps/macos/Tests/ClawdbotIPCTests/FileHandleLegacyAPIGuardTests.swift index 5e30cf584..2de87f693 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/FileHandleLegacyAPIGuardTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/FileHandleLegacyAPIGuardTests.swift @@ -32,7 +32,7 @@ import Testing } private static func swiftFiles(under root: URL) throws -> [URL] { - let fm = FileManager.default + let fm = FileManager() guard let enumerator = fm.enumerator(at: root, includingPropertiesForKeys: [.isRegularFileKey]) else { return [] } diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayAgentChannelTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayAgentChannelTests.swift index 248712262..5db5476cb 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/GatewayAgentChannelTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayAgentChannelTests.swift @@ -11,6 +11,8 @@ import Testing #expect(GatewayAgentChannel.last.shouldDeliver(true) == true) #expect(GatewayAgentChannel.whatsapp.shouldDeliver(true) == true) #expect(GatewayAgentChannel.telegram.shouldDeliver(true) == true) + #expect(GatewayAgentChannel.googlechat.shouldDeliver(true) == true) + #expect(GatewayAgentChannel.bluebubbles.shouldDeliver(true) == true) #expect(GatewayAgentChannel.last.shouldDeliver(false) == false) } @@ -18,6 +20,8 @@ import Testing #expect(GatewayAgentChannel(raw: nil) == .last) #expect(GatewayAgentChannel(raw: " ") == .last) #expect(GatewayAgentChannel(raw: "WEBCHAT") == .webchat) + #expect(GatewayAgentChannel(raw: "googlechat") == .googlechat) + #expect(GatewayAgentChannel(raw: "BLUEBUBBLES") == .bluebubbles) #expect(GatewayAgentChannel(raw: "unknown") == .last) } } diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelConfigureTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelConfigureTests.swift index 22c83d4fd..8ae9c3c0d 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelConfigureTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelConfigureTests.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import Foundation import os import Testing diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelConnectTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelConnectTests.swift index 5b1892d80..624392cb9 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelConnectTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelConnectTests.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import Foundation import os import Testing diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelRequestTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelRequestTests.swift index d231bed4b..1e7a1740e 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelRequestTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelRequestTests.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import Foundation import os import Testing diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelShutdownTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelShutdownTests.swift index 0f1560cbd..be6ab91f8 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelShutdownTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayChannelShutdownTests.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import Foundation import os import Testing diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayConnectionControlTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayConnectionControlTests.swift index 83d01b96f..a7b1c857b 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/GatewayConnectionControlTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayConnectionControlTests.swift @@ -1,3 +1,4 @@ +import ClawdbotKit import Foundation import Testing @testable import Clawdbot diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayDiscoveryModelTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayDiscoveryModelTests.swift index 214cb7390..55c128a2f 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/GatewayDiscoveryModelTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayDiscoveryModelTests.swift @@ -48,7 +48,7 @@ struct GatewayDiscoveryModelTests { lanHost: "other.local", tailnetDns: "other.tailnet.example", displayName: "Other Mac", - serviceName: "other-bridge", + serviceName: "other-gateway", local: local)) } @@ -60,7 +60,7 @@ struct GatewayDiscoveryModelTests { lanHost: nil, tailnetDns: nil, displayName: nil, - serviceName: "studio-bridge", + serviceName: "studio-gateway", local: local)) } diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayEndpointStoreTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayEndpointStoreTests.swift index dd795f80c..8cefe75e2 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/GatewayEndpointStoreTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayEndpointStoreTests.swift @@ -3,6 +3,13 @@ import Testing @testable import Clawdbot @Suite struct GatewayEndpointStoreTests { + private func makeDefaults() -> UserDefaults { + let suiteName = "GatewayEndpointStoreTests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suiteName)! + defaults.removePersistentDomain(forName: suiteName) + return defaults + } + @Test func resolveGatewayTokenPrefersEnvAndFallsBackToLaunchd() { let snapshot = LaunchAgentPlistSnapshot( programArguments: [], @@ -66,4 +73,112 @@ import Testing launchdSnapshot: snapshot) #expect(password == "launchd-pass") } + + @Test func connectionModeResolverPrefersConfigModeOverDefaults() { + let defaults = self.makeDefaults() + defaults.set("remote", forKey: connectionModeKey) + + let root: [String: Any] = [ + "gateway": [ + "mode": " local ", + ], + ] + + let resolved = ConnectionModeResolver.resolve(root: root, defaults: defaults) + #expect(resolved.mode == .local) + } + + @Test func connectionModeResolverTrimsConfigMode() { + let defaults = self.makeDefaults() + defaults.set("local", forKey: connectionModeKey) + + let root: [String: Any] = [ + "gateway": [ + "mode": " remote ", + ], + ] + + let resolved = ConnectionModeResolver.resolve(root: root, defaults: defaults) + #expect(resolved.mode == .remote) + } + + @Test func connectionModeResolverFallsBackToDefaultsWhenMissingConfig() { + let defaults = self.makeDefaults() + defaults.set("remote", forKey: connectionModeKey) + + let resolved = ConnectionModeResolver.resolve(root: [:], defaults: defaults) + #expect(resolved.mode == .remote) + } + + @Test func connectionModeResolverFallsBackToDefaultsOnUnknownConfig() { + let defaults = self.makeDefaults() + defaults.set("local", forKey: connectionModeKey) + + let root: [String: Any] = [ + "gateway": [ + "mode": "staging", + ], + ] + + let resolved = ConnectionModeResolver.resolve(root: root, defaults: defaults) + #expect(resolved.mode == .local) + } + + @Test func connectionModeResolverPrefersRemoteURLWhenModeMissing() { + let defaults = self.makeDefaults() + defaults.set("local", forKey: connectionModeKey) + + let root: [String: Any] = [ + "gateway": [ + "remote": [ + "url": " ws://umbrel:18789 ", + ], + ], + ] + + let resolved = ConnectionModeResolver.resolve(root: root, defaults: defaults) + #expect(resolved.mode == .remote) + } + + @Test func resolveLocalGatewayHostUsesLoopbackForAutoEvenWithTailnet() { + let host = GatewayEndpointStore._testResolveLocalGatewayHost( + bindMode: "auto", + tailscaleIP: "100.64.1.2") + #expect(host == "127.0.0.1") + } + + @Test func resolveLocalGatewayHostUsesLoopbackForAutoWithoutTailnet() { + let host = GatewayEndpointStore._testResolveLocalGatewayHost( + bindMode: "auto", + tailscaleIP: nil) + #expect(host == "127.0.0.1") + } + + @Test func resolveLocalGatewayHostPrefersTailnetForTailnetMode() { + let host = GatewayEndpointStore._testResolveLocalGatewayHost( + bindMode: "tailnet", + tailscaleIP: "100.64.1.5") + #expect(host == "100.64.1.5") + } + + @Test func resolveLocalGatewayHostFallsBackToLoopbackForTailnetMode() { + let host = GatewayEndpointStore._testResolveLocalGatewayHost( + bindMode: "tailnet", + tailscaleIP: nil) + #expect(host == "127.0.0.1") + } + + @Test func resolveLocalGatewayHostUsesCustomBindHost() { + let host = GatewayEndpointStore._testResolveLocalGatewayHost( + bindMode: "custom", + tailscaleIP: "100.64.1.9", + customBindHost: "192.168.1.10") + #expect(host == "192.168.1.10") + } + + @Test func normalizeGatewayUrlAddsDefaultPortForWs() { + let url = GatewayRemoteConfig.normalizeGatewayUrl("ws://gateway") + #expect(url?.port == 18789) + #expect(url?.absoluteString == "ws://gateway:18789") + } } diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayEnvironmentTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayEnvironmentTests.swift index 20d5b5973..9446919e7 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/GatewayEnvironmentTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayEnvironmentTests.swift @@ -5,16 +5,28 @@ import Testing @Suite struct GatewayEnvironmentTests { @Test func semverParsesCommonForms() { #expect(Semver.parse("1.2.3") == Semver(major: 1, minor: 2, patch: 3)) + #expect(Semver.parse(" v1.2.3 \n") == Semver(major: 1, minor: 2, patch: 3)) #expect(Semver.parse("v2.0.0") == Semver(major: 2, minor: 0, patch: 0)) - #expect(Semver.parse("3.4.5-beta.1") == Semver(major: 3, minor: 4, patch: 0)) // patch drops trailing text + #expect(Semver.parse("3.4.5-beta.1") == Semver(major: 3, minor: 4, patch: 5)) // prerelease suffix stripped + #expect(Semver.parse("2026.1.11-4") == Semver(major: 2026, minor: 1, patch: 11)) // build suffix stripped + #expect(Semver.parse("1.0.5+build.123") == Semver(major: 1, minor: 0, patch: 5)) // metadata suffix stripped + #expect(Semver.parse("v1.2.3+build.9") == Semver(major: 1, minor: 2, patch: 3)) + #expect(Semver.parse("1.2.3+build.123") == Semver(major: 1, minor: 2, patch: 3)) + #expect(Semver.parse("1.2.3-rc.1+build.7") == Semver(major: 1, minor: 2, patch: 3)) + #expect(Semver.parse("v1.2.3-rc.1") == Semver(major: 1, minor: 2, patch: 3)) + #expect(Semver.parse("1.2.0") == Semver(major: 1, minor: 2, patch: 0)) #expect(Semver.parse(nil) == nil) #expect(Semver.parse("invalid") == nil) + #expect(Semver.parse("1.2") == nil) + #expect(Semver.parse("1.2.x") == nil) } @Test func semverCompatibilityRequiresSameMajorAndNotOlder() { let required = Semver(major: 2, minor: 1, patch: 0) #expect(Semver(major: 2, minor: 1, patch: 0).compatible(with: required)) #expect(Semver(major: 2, minor: 2, patch: 0).compatible(with: required)) + #expect(Semver(major: 2, minor: 1, patch: 1).compatible(with: required)) + #expect(Semver(major: 2, minor: 0, patch: 9).compatible(with: required) == false) #expect(Semver(major: 3, minor: 0, patch: 0).compatible(with: required) == false) #expect(Semver(major: 1, minor: 9, patch: 9).compatible(with: required) == false) } @@ -36,6 +48,10 @@ import Testing @Test func expectedGatewayVersionFromStringUsesParser() { #expect(GatewayEnvironment.expectedGatewayVersion(from: "v9.1.2") == Semver(major: 9, minor: 1, patch: 2)) + #expect(GatewayEnvironment.expectedGatewayVersion(from: "2026.1.11-4") == Semver( + major: 2026, + minor: 1, + patch: 11)) #expect(GatewayEnvironment.expectedGatewayVersion(from: nil) == nil) } } diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayLaunchAgentManagerTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayLaunchAgentManagerTests.swift index ae8357b0c..af41a2a8e 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/GatewayLaunchAgentManagerTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayLaunchAgentManagerTests.swift @@ -4,7 +4,7 @@ import Testing @Suite struct GatewayLaunchAgentManagerTests { @Test func launchAgentPlistSnapshotParsesArgsAndEnv() throws { - let url = FileManager.default.temporaryDirectory + let url = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-launchd-\(UUID().uuidString).plist") let plist: [String: Any] = [ "ProgramArguments": ["clawdbot", "gateway-daemon", "--port", "18789", "--bind", "loopback"], @@ -15,7 +15,7 @@ import Testing ] let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) try data.write(to: url, options: [.atomic]) - defer { try? FileManager.default.removeItem(at: url) } + defer { try? FileManager().removeItem(at: url) } let snapshot = try #require(LaunchAgentPlist.snapshot(url: url)) #expect(snapshot.port == 18789) @@ -25,14 +25,14 @@ import Testing } @Test func launchAgentPlistSnapshotAllowsMissingBind() throws { - let url = FileManager.default.temporaryDirectory + let url = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-launchd-\(UUID().uuidString).plist") let plist: [String: Any] = [ "ProgramArguments": ["clawdbot", "gateway-daemon", "--port", "18789"], ] let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) try data.write(to: url, options: [.atomic]) - defer { try? FileManager.default.removeItem(at: url) } + defer { try? FileManager().removeItem(at: url) } let snapshot = try #require(LaunchAgentPlist.snapshot(url: url)) #expect(snapshot.port == 18789) diff --git a/apps/macos/Tests/ClawdbotIPCTests/GatewayProcessManagerTests.swift b/apps/macos/Tests/ClawdbotIPCTests/GatewayProcessManagerTests.swift new file mode 100644 index 000000000..05c96f8be --- /dev/null +++ b/apps/macos/Tests/ClawdbotIPCTests/GatewayProcessManagerTests.swift @@ -0,0 +1,147 @@ +import ClawdbotKit +import Foundation +import os +import Testing +@testable import Clawdbot + +@Suite(.serialized) +@MainActor +struct GatewayProcessManagerTests { + private final class FakeWebSocketTask: WebSocketTasking, @unchecked Sendable { + private let connectRequestID = OSAllocatedUnfairLock(initialState: nil) + private let pendingReceiveHandler = + OSAllocatedUnfairLock<(@Sendable (Result) + -> Void)?>(initialState: nil) + private let cancelCount = OSAllocatedUnfairLock(initialState: 0) + private let sendCount = OSAllocatedUnfairLock(initialState: 0) + + var state: URLSessionTask.State = .suspended + + func resume() { + self.state = .running + } + + func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + _ = (closeCode, reason) + self.state = .canceling + self.cancelCount.withLock { $0 += 1 } + let handler = self.pendingReceiveHandler.withLock { handler in + defer { handler = nil } + return handler + } + handler?(Result.failure(URLError(.cancelled))) + } + + func send(_ message: URLSessionWebSocketTask.Message) async throws { + let currentSendCount = self.sendCount.withLock { count in + defer { count += 1 } + return count + } + + if currentSendCount == 0 { + guard case let .data(data) = message else { return } + if let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + (obj["type"] as? String) == "req", + (obj["method"] as? String) == "connect", + let id = obj["id"] as? String + { + self.connectRequestID.withLock { $0 = id } + } + return + } + + guard case let .data(data) = message else { return } + guard + let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + (obj["type"] as? String) == "req", + let id = obj["id"] as? String + else { + return + } + + let response = Self.responseData(id: id) + let handler = self.pendingReceiveHandler.withLock { $0 } + handler?(Result.success(.data(response))) + } + + func receive() async throws -> URLSessionWebSocketTask.Message { + let id = self.connectRequestID.withLock { $0 } ?? "connect" + return .data(Self.connectOkData(id: id)) + } + + func receive( + completionHandler: @escaping @Sendable (Result) -> Void) + { + self.pendingReceiveHandler.withLock { $0 = completionHandler } + } + + private static func connectOkData(id: String) -> Data { + let json = """ + { + "type": "res", + "id": "\(id)", + "ok": true, + "payload": { + "type": "hello-ok", + "protocol": 2, + "server": { "version": "test", "connId": "test" }, + "features": { "methods": [], "events": [] }, + "snapshot": { + "presence": [ { "ts": 1 } ], + "health": {}, + "stateVersion": { "presence": 0, "health": 0 }, + "uptimeMs": 0 + }, + "policy": { "maxPayload": 1, "maxBufferedBytes": 1, "tickIntervalMs": 30000 } + } + } + """ + return Data(json.utf8) + } + + private static func responseData(id: String) -> Data { + let json = """ + { + "type": "res", + "id": "\(id)", + "ok": true, + "payload": { "ok": true } + } + """ + return Data(json.utf8) + } + } + + private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable { + private let tasks = OSAllocatedUnfairLock(initialState: [FakeWebSocketTask]()) + + func makeWebSocketTask(url: URL) -> WebSocketTaskBox { + _ = url + let task = FakeWebSocketTask() + self.tasks.withLock { $0.append(task) } + return WebSocketTaskBox(task: task) + } + } + + @Test func clearsLastFailureWhenHealthSucceeds() async { + let session = FakeWebSocketSession() + let url = URL(string: "ws://example.invalid")! + let connection = GatewayConnection( + configProvider: { (url: url, token: nil, password: nil) }, + sessionBox: WebSocketSessionBox(session: session)) + + let manager = GatewayProcessManager.shared + manager.setTestingConnection(connection) + manager.setTestingDesiredActive(true) + manager.setTestingLastFailureReason("health failed") + defer { + manager.setTestingConnection(nil) + manager.setTestingDesiredActive(false) + manager.setTestingLastFailureReason(nil) + } + + let ready = await manager.waitForGatewayReady(timeout: 0.5) + #expect(ready) + #expect(manager.lastFailureReason == nil) + } +} diff --git a/apps/macos/Tests/ClawdbotIPCTests/LogLocatorTests.swift b/apps/macos/Tests/ClawdbotIPCTests/LogLocatorTests.swift index bc29f9e2b..6d87208ea 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/LogLocatorTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/LogLocatorTests.swift @@ -5,7 +5,7 @@ import Testing @Suite struct LogLocatorTests { @Test func launchdGatewayLogPathEnsuresTmpDirExists() throws { - let fm = FileManager.default + let fm = FileManager() let baseDir = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) let logDir = baseDir.appendingPathComponent("clawdbot-tests-\(UUID().uuidString)") diff --git a/apps/macos/Tests/ClawdbotIPCTests/LowCoverageHelperTests.swift b/apps/macos/Tests/ClawdbotIPCTests/LowCoverageHelperTests.swift index b68f98cb9..16d919225 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/LowCoverageHelperTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/LowCoverageHelperTests.swift @@ -7,15 +7,17 @@ import Testing @Suite(.serialized) struct LowCoverageHelperTests { + private typealias ProtoAnyCodable = ClawdbotProtocol.AnyCodable + @Test func anyCodableHelperAccessors() throws { - let payload: [String: AnyCodable] = [ - "title": AnyCodable("Hello"), - "flag": AnyCodable(true), - "count": AnyCodable(3), - "ratio": AnyCodable(1.25), - "list": AnyCodable([AnyCodable("a"), AnyCodable(2)]), + let payload: [String: ProtoAnyCodable] = [ + "title": ProtoAnyCodable("Hello"), + "flag": ProtoAnyCodable(true), + "count": ProtoAnyCodable(3), + "ratio": ProtoAnyCodable(1.25), + "list": ProtoAnyCodable([ProtoAnyCodable("a"), ProtoAnyCodable(2)]), ] - let any = AnyCodable(payload) + let any = ProtoAnyCodable(payload) let dict = try #require(any.dictionaryValue) #expect(dict["title"]?.stringValue == "Hello") #expect(dict["flag"]?.boolValue == true) @@ -76,31 +78,27 @@ struct LowCoverageHelperTests { #expect(result.stderr.contains("stderr-1999")) } - @Test func pairedNodesStorePersists() async throws { - let dir = FileManager.default.temporaryDirectory - .appendingPathComponent("paired-\(UUID().uuidString)", isDirectory: true) - try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) - let url = dir.appendingPathComponent("nodes.json") - let store = PairedNodesStore(fileURL: url) - await store.load() - #expect(await store.all().isEmpty) - - let node = PairedNode( + @Test func nodeInfoCodableRoundTrip() throws { + let info = NodeInfo( nodeId: "node-1", displayName: "Node One", platform: "macOS", version: "1.0", + coreVersion: "1.0-core", + uiVersion: "1.0-ui", deviceFamily: "Mac", modelIdentifier: "MacBookPro", - token: "token", - createdAtMs: 1, - lastSeenAtMs: nil) - try await store.upsert(node) - #expect(await store.find(nodeId: "node-1")?.displayName == "Node One") - - try await store.touchSeen(nodeId: "node-1") - let updated = await store.find(nodeId: "node-1") - #expect(updated?.lastSeenAtMs != nil) + remoteIp: "192.168.1.2", + caps: ["chat"], + commands: ["send"], + permissions: ["send": true], + paired: true, + connected: false) + let data = try JSONEncoder().encode(info) + let decoded = try JSONDecoder().decode(NodeInfo.self, from: data) + #expect(decoded.nodeId == "node-1") + #expect(decoded.isPaired == true) + #expect(decoded.isConnected == false) } @Test @MainActor func presenceReporterHelpers() { @@ -143,12 +141,12 @@ struct LowCoverageHelperTests { } @Test @MainActor func canvasSchemeHandlerResolvesFilesAndErrors() throws { - let root = FileManager.default.temporaryDirectory + let root = FileManager().temporaryDirectory .appendingPathComponent("canvas-\(UUID().uuidString)", isDirectory: true) - defer { try? FileManager.default.removeItem(at: root) } - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager().removeItem(at: root) } + try FileManager().createDirectory(at: root, withIntermediateDirectories: true) let session = root.appendingPathComponent("main", isDirectory: true) - try FileManager.default.createDirectory(at: session, withIntermediateDirectories: true) + try FileManager().createDirectory(at: session, withIntermediateDirectories: true) let index = session.appendingPathComponent("index.html") try "

Hello

".write(to: index, atomically: true, encoding: .utf8) diff --git a/apps/macos/Tests/ClawdbotIPCTests/MacGatewayChatTransportMappingTests.swift b/apps/macos/Tests/ClawdbotIPCTests/MacGatewayChatTransportMappingTests.swift index 00cff847b..3e24dc5cb 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/MacGatewayChatTransportMappingTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/MacGatewayChatTransportMappingTests.swift @@ -21,6 +21,7 @@ import Testing features: [:], snapshot: snapshot, canvashosturl: nil, + auth: nil, policy: [:]) let mapped = MacGatewayChatTransport.mapPushToTransportEvent(.snapshot(hello)) diff --git a/apps/macos/Tests/ClawdbotIPCTests/MacNodeBridgeDiscoveryTests.swift b/apps/macos/Tests/ClawdbotIPCTests/MacNodeBridgeDiscoveryTests.swift deleted file mode 100644 index 3863f331c..000000000 --- a/apps/macos/Tests/ClawdbotIPCTests/MacNodeBridgeDiscoveryTests.swift +++ /dev/null @@ -1,215 +0,0 @@ -import Darwin -import Foundation -import Network -import Testing -@testable import Clawdbot - -@Suite struct MacNodeBridgeDiscoveryTests { - @MainActor - @Test func loopbackBridgePortDefaultsAndOverrides() { - withEnv("CLAWDBOT_BRIDGE_PORT", value: nil) { - #expect(MacNodeModeCoordinator.loopbackBridgePort() == 18790) - } - withEnv("CLAWDBOT_BRIDGE_PORT", value: "19991") { - #expect(MacNodeModeCoordinator.loopbackBridgePort() == 19991) - } - withEnv("CLAWDBOT_BRIDGE_PORT", value: "not-a-port") { - #expect(MacNodeModeCoordinator.loopbackBridgePort() == 18790) - } - } - - @MainActor - @Test func probeEndpointSucceedsForOpenPort() async throws { - let listener = try NWListener(using: .tcp, on: .any) - listener.newConnectionHandler = { connection in - connection.cancel() - } - listener.start(queue: DispatchQueue(label: "com.clawdbot.tests.bridge-listener")) - try await waitForListenerReady(listener, timeoutSeconds: 1.0) - - guard let port = listener.port else { - listener.cancel() - throw TestError(message: "listener port missing") - } - - let endpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: port) - let ok = await MacNodeModeCoordinator.probeEndpoint(endpoint, timeoutSeconds: 0.6) - listener.cancel() - #expect(ok == true) - } - - @MainActor - @Test func probeEndpointFailsForClosedPort() async throws { - let port = try reserveEphemeralPort() - let endpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: port) - let ok = await MacNodeModeCoordinator.probeEndpoint(endpoint, timeoutSeconds: 0.4) - #expect(ok == false) - } - - @MainActor - @Test func remoteBridgePortUsesMatchingRemoteUrlPort() { - let configPath = FileManager.default.temporaryDirectory - .appendingPathComponent("clawdbot-config-\(UUID().uuidString)") - .appendingPathComponent("clawdbot.json") - .path - - let defaults = UserDefaults.standard - let prevTarget = defaults.string(forKey: remoteTargetKey) - defer { - if let prevTarget { - defaults.set(prevTarget, forKey: remoteTargetKey) - } else { - defaults.removeObject(forKey: remoteTargetKey) - } - } - - withEnv("CLAWDBOT_CONFIG_PATH", value: configPath) { - withEnv("CLAWDBOT_GATEWAY_PORT", value: "20000") { - defaults.set("user@bridge.ts.net", forKey: remoteTargetKey) - ClawdbotConfigFile.saveDict([ - "gateway": [ - "remote": [ - "url": "ws://bridge.ts.net:25000", - ], - ], - ]) - #expect(MacNodeModeCoordinator.remoteBridgePort() == 25001) - } - } - } - - @MainActor - @Test func remoteBridgePortFallsBackWhenRemoteUrlHostMismatch() { - let configPath = FileManager.default.temporaryDirectory - .appendingPathComponent("clawdbot-config-\(UUID().uuidString)") - .appendingPathComponent("clawdbot.json") - .path - - let defaults = UserDefaults.standard - let prevTarget = defaults.string(forKey: remoteTargetKey) - defer { - if let prevTarget { - defaults.set(prevTarget, forKey: remoteTargetKey) - } else { - defaults.removeObject(forKey: remoteTargetKey) - } - } - - withEnv("CLAWDBOT_CONFIG_PATH", value: configPath) { - withEnv("CLAWDBOT_GATEWAY_PORT", value: "20000") { - defaults.set("user@other.ts.net", forKey: remoteTargetKey) - ClawdbotConfigFile.saveDict([ - "gateway": [ - "remote": [ - "url": "ws://bridge.ts.net:25000", - ], - ], - ]) - #expect(MacNodeModeCoordinator.remoteBridgePort() == 20001) - } - } - } -} - -private struct TestError: Error { - let message: String -} - -private struct ListenerTimeoutError: Error {} - -private func waitForListenerReady(_ listener: NWListener, timeoutSeconds: Double) async throws { - try await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - try await withCheckedThrowingContinuation { cont in - final class ListenerState: @unchecked Sendable { - let lock = NSLock() - var finished = false - } - let state = ListenerState() - let finish: @Sendable (Result) -> Void = { result in - state.lock.lock() - defer { state.lock.unlock() } - guard !state.finished else { return } - state.finished = true - cont.resume(with: result) - } - - listener.stateUpdateHandler = { state in - switch state { - case .ready: - finish(.success(())) - case let .failed(err): - finish(.failure(err)) - case .cancelled: - finish(.failure(ListenerTimeoutError())) - default: - break - } - } - } - } - group.addTask { - try await Task.sleep(nanoseconds: UInt64(timeoutSeconds * 1_000_000_000)) - throw ListenerTimeoutError() - } - _ = try await group.next() - group.cancelAll() - } -} - -private func withEnv(_ key: String, value: String?, _ body: () -> Void) { - let existing = getenv(key).map { String(cString: $0) } - if let value { - setenv(key, value, 1) - } else { - unsetenv(key) - } - defer { - if let existing { - setenv(key, existing, 1) - } else { - unsetenv(key) - } - } - body() -} - -private func reserveEphemeralPort() throws -> NWEndpoint.Port { - let fd = socket(AF_INET, SOCK_STREAM, 0) - if fd < 0 { - throw TestError(message: "socket failed") - } - defer { close(fd) } - - var addr = sockaddr_in() - addr.sin_len = UInt8(MemoryLayout.size) - addr.sin_family = sa_family_t(AF_INET) - addr.sin_port = in_port_t(0) - addr.sin_addr = in_addr(s_addr: inet_addr("127.0.0.1")) - - let bindResult = withUnsafePointer(to: &addr) { pointer -> Int32 in - pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { - Darwin.bind(fd, $0, socklen_t(MemoryLayout.size)) - } - } - if bindResult != 0 { - throw TestError(message: "bind failed") - } - - var resolved = sockaddr_in() - var length = socklen_t(MemoryLayout.size) - let nameResult = withUnsafeMutablePointer(to: &resolved) { pointer -> Int32 in - pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { - getsockname(fd, $0, &length) - } - } - if nameResult != 0 { - throw TestError(message: "getsockname failed") - } - - let port = UInt16(bigEndian: resolved.sin_port) - guard let endpointPort = NWEndpoint.Port(rawValue: port), endpointPort.rawValue != 0 else { - throw TestError(message: "ephemeral port missing") - } - return endpointPort -} diff --git a/apps/macos/Tests/ClawdbotIPCTests/MacNodeBridgeSessionTests.swift b/apps/macos/Tests/ClawdbotIPCTests/MacNodeBridgeSessionTests.swift deleted file mode 100644 index e7f2b8651..000000000 --- a/apps/macos/Tests/ClawdbotIPCTests/MacNodeBridgeSessionTests.swift +++ /dev/null @@ -1,19 +0,0 @@ -import Foundation -import Testing -@testable import Clawdbot - -@Suite -struct MacNodeBridgeSessionTests { - @Test func sendEventThrowsWhenNotConnected() async { - let session = MacNodeBridgeSession() - - do { - try await session.sendEvent(event: "test", payloadJSON: "{}") - Issue.record("Expected sendEvent to throw when disconnected") - } catch { - let ns = error as NSError - #expect(ns.domain == "Bridge") - #expect(ns.code == 15) - } - } -} diff --git a/apps/macos/Tests/ClawdbotIPCTests/MacNodeRuntimeTests.swift b/apps/macos/Tests/ClawdbotIPCTests/MacNodeRuntimeTests.swift index 45943904c..6c7343725 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/MacNodeRuntimeTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/MacNodeRuntimeTests.swift @@ -59,7 +59,7 @@ struct MacNodeRuntimeTests { includeAudio: Bool?, outPath: String?) async throws -> (path: String, hasAudio: Bool) { - let url = FileManager.default.temporaryDirectory + let url = FileManager().temporaryDirectory .appendingPathComponent("clawdbot-test-screen-record-\(UUID().uuidString).mp4") try Data("ok".utf8).write(to: url) return (path: url.path, hasAudio: false) @@ -74,10 +74,6 @@ struct MacNodeRuntimeTests { { CLLocation(latitude: 0, longitude: 0) } - - func confirmSystemRun(command: String, cwd: String?) async -> SystemRunDecision { - .allowOnce - } } let services = await MainActor.run { FakeMainActorServices() } diff --git a/apps/macos/Tests/ClawdbotIPCTests/ModelCatalogLoaderTests.swift b/apps/macos/Tests/ClawdbotIPCTests/ModelCatalogLoaderTests.swift index d446dad64..7b87dc5ec 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/ModelCatalogLoaderTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/ModelCatalogLoaderTests.swift @@ -19,9 +19,9 @@ struct ModelCatalogLoaderTests { }; """ - let tmp = FileManager.default.temporaryDirectory + let tmp = FileManager().temporaryDirectory .appendingPathComponent("models-\(UUID().uuidString).ts") - defer { try? FileManager.default.removeItem(at: tmp) } + defer { try? FileManager().removeItem(at: tmp) } try src.write(to: tmp, atomically: true, encoding: .utf8) let choices = try await ModelCatalogLoader.load(from: tmp.path) @@ -42,9 +42,9 @@ struct ModelCatalogLoaderTests { @Test func loadWithNoExportReturnsEmptyChoices() async throws { let src = "const NOPE = 1;" - let tmp = FileManager.default.temporaryDirectory + let tmp = FileManager().temporaryDirectory .appendingPathComponent("models-\(UUID().uuidString).ts") - defer { try? FileManager.default.removeItem(at: tmp) } + defer { try? FileManager().removeItem(at: tmp) } try src.write(to: tmp, atomically: true, encoding: .utf8) let choices = try await ModelCatalogLoader.load(from: tmp.path) diff --git a/apps/macos/Tests/ClawdbotIPCTests/NodeManagerPathsTests.swift b/apps/macos/Tests/ClawdbotIPCTests/NodeManagerPathsTests.swift index 1300cbf7e..bd4a3c0f9 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/NodeManagerPathsTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/NodeManagerPathsTests.swift @@ -6,16 +6,16 @@ import Testing private func makeTempDir() throws -> URL { let base = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) let dir = base.appendingPathComponent(UUID().uuidString, isDirectory: true) - try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try FileManager().createDirectory(at: dir, withIntermediateDirectories: true) return dir } private func makeExec(at path: URL) throws { - try FileManager.default.createDirectory( + try FileManager().createDirectory( at: path.deletingLastPathComponent(), withIntermediateDirectories: true) - FileManager.default.createFile(atPath: path.path, contents: Data("echo ok\n".utf8)) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path.path) + FileManager().createFile(atPath: path.path, contents: Data("echo ok\n".utf8)) + try FileManager().setAttributes([.posixPermissions: 0o755], ofItemAtPath: path.path) } @Test func fnmNodeBinsPreferNewestInstalledVersion() throws { @@ -37,7 +37,7 @@ import Testing let home = try self.makeTempDir() let missingNodeBin = home .appendingPathComponent(".local/share/fnm/node-versions/v99.0.0/installation/bin") - try FileManager.default.createDirectory(at: missingNodeBin, withIntermediateDirectories: true) + try FileManager().createDirectory(at: missingNodeBin, withIntermediateDirectories: true) let bins = CommandResolver._testNodeManagerBinPaths(home: home) #expect(!bins.contains(missingNodeBin.path)) diff --git a/apps/macos/Tests/ClawdbotIPCTests/OnboardingWizardStepViewTests.swift b/apps/macos/Tests/ClawdbotIPCTests/OnboardingWizardStepViewTests.swift index 7fd9b9929..3ce965325 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/OnboardingWizardStepViewTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/OnboardingWizardStepViewTests.swift @@ -3,13 +3,15 @@ import SwiftUI import Testing @testable import Clawdbot +private typealias ProtoAnyCodable = ClawdbotProtocol.AnyCodable + @Suite(.serialized) @MainActor struct OnboardingWizardStepViewTests { @Test func noteStepBuilds() { let step = WizardStep( id: "step-1", - type: AnyCodable("note"), + type: ProtoAnyCodable("note"), title: "Welcome", message: "Hello", options: nil, @@ -22,17 +24,17 @@ struct OnboardingWizardStepViewTests { } @Test func selectStepBuilds() { - let options: [[String: AnyCodable]] = [ - ["value": AnyCodable("local"), "label": AnyCodable("Local"), "hint": AnyCodable("This Mac")], - ["value": AnyCodable("remote"), "label": AnyCodable("Remote")], + let options: [[String: ProtoAnyCodable]] = [ + ["value": ProtoAnyCodable("local"), "label": ProtoAnyCodable("Local"), "hint": ProtoAnyCodable("This Mac")], + ["value": ProtoAnyCodable("remote"), "label": ProtoAnyCodable("Remote")], ] let step = WizardStep( id: "step-2", - type: AnyCodable("select"), + type: ProtoAnyCodable("select"), title: "Mode", message: "Choose a mode", options: options, - initialvalue: AnyCodable("local"), + initialvalue: ProtoAnyCodable("local"), placeholder: nil, sensitive: nil, executor: nil) diff --git a/apps/macos/Tests/ClawdbotIPCTests/RuntimeLocatorTests.swift b/apps/macos/Tests/ClawdbotIPCTests/RuntimeLocatorTests.swift index c1bcc957f..81d2c7494 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/RuntimeLocatorTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/RuntimeLocatorTests.swift @@ -6,10 +6,10 @@ import Testing private func makeTempExecutable(contents: String) throws -> URL { let dir = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) .appendingPathComponent(UUID().uuidString, isDirectory: true) - try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + try FileManager().createDirectory(at: dir, withIntermediateDirectories: true) let path = dir.appendingPathComponent("node") try contents.write(to: path, atomically: true, encoding: .utf8) - try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path.path) + try FileManager().setAttributes([.posixPermissions: 0o755], ofItemAtPath: path.path) return path } diff --git a/apps/macos/Tests/ClawdbotIPCTests/SessionMenuPreviewTests.swift b/apps/macos/Tests/ClawdbotIPCTests/SessionMenuPreviewTests.swift new file mode 100644 index 000000000..af25d5246 --- /dev/null +++ b/apps/macos/Tests/ClawdbotIPCTests/SessionMenuPreviewTests.swift @@ -0,0 +1,28 @@ +import Foundation +import Testing +@testable import Clawdbot + +@Suite(.serialized) +struct SessionMenuPreviewTests { + @Test func loaderReturnsCachedItems() async { + await SessionPreviewCache.shared._testReset() + let items = [SessionPreviewItem(id: "1", role: .user, text: "Hi")] + let snapshot = SessionMenuPreviewSnapshot(items: items, status: .ready) + await SessionPreviewCache.shared._testSet(snapshot: snapshot, for: "main") + + let loaded = await SessionMenuPreviewLoader.load(sessionKey: "main", maxItems: 10) + #expect(loaded.status == .ready) + #expect(loaded.items.count == 1) + #expect(loaded.items.first?.text == "Hi") + } + + @Test func loaderReturnsEmptyWhenCachedEmpty() async { + await SessionPreviewCache.shared._testReset() + let snapshot = SessionMenuPreviewSnapshot(items: [], status: .empty) + await SessionPreviewCache.shared._testSet(snapshot: snapshot, for: "main") + + let loaded = await SessionMenuPreviewLoader.load(sessionKey: "main", maxItems: 10) + #expect(loaded.status == .empty) + #expect(loaded.items.isEmpty) + } +} diff --git a/apps/macos/Tests/ClawdbotIPCTests/TestIsolation.swift b/apps/macos/Tests/ClawdbotIPCTests/TestIsolation.swift index c15606a06..6207df141 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/TestIsolation.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/TestIsolation.swift @@ -109,7 +109,7 @@ enum TestIsolation { } nonisolated static func tempConfigPath() -> String { - FileManager.default.temporaryDirectory + FileManager().temporaryDirectory .appendingPathComponent("clawdbot-test-config-\(UUID().uuidString).json") .path } diff --git a/apps/macos/Tests/ClawdbotIPCTests/UtilitiesTests.swift b/apps/macos/Tests/ClawdbotIPCTests/UtilitiesTests.swift index 5033cb9cc..7b8753ef1 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/UtilitiesTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/UtilitiesTests.swift @@ -37,7 +37,7 @@ import Testing defaults.set(AppState.ConnectionMode.remote.rawValue, forKey: connectionModeKey) defaults.set("ssh alice@example.com", forKey: remoteTargetKey) - let settings = CommandResolver.connectionSettings(defaults: defaults) + let settings = CommandResolver.connectionSettings(defaults: defaults, configRoot: [:]) #expect(settings.mode == .remote) #expect(settings.target == "alice@example.com") } @@ -47,17 +47,17 @@ import Testing .appendingPathComponent(UUID().uuidString, isDirectory: true) let dist = tmp.appendingPathComponent("dist/index.js") let bin = tmp.appendingPathComponent("bin/clawdbot.js") - try FileManager.default.createDirectory(at: dist.deletingLastPathComponent(), withIntermediateDirectories: true) - try FileManager.default.createDirectory(at: bin.deletingLastPathComponent(), withIntermediateDirectories: true) - FileManager.default.createFile(atPath: dist.path, contents: Data()) - FileManager.default.createFile(atPath: bin.path, contents: Data()) + try FileManager().createDirectory(at: dist.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager().createDirectory(at: bin.deletingLastPathComponent(), withIntermediateDirectories: true) + FileManager().createFile(atPath: dist.path, contents: Data()) + FileManager().createFile(atPath: bin.path, contents: Data()) let entry = CommandResolver.gatewayEntrypoint(in: tmp) #expect(entry == dist.path) } @Test func logLocatorPicksNewestLogFile() throws { - let fm = FileManager.default + let fm = FileManager() let dir = URL(fileURLWithPath: "/tmp/clawdbot", isDirectory: true) try? fm.createDirectory(at: dir, withIntermediateDirectories: true) diff --git a/apps/macos/Tests/ClawdbotIPCTests/VoiceWakeHelpersTests.swift b/apps/macos/Tests/ClawdbotIPCTests/VoiceWakeHelpersTests.swift index e7f7e06fc..49ad5a124 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/VoiceWakeHelpersTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/VoiceWakeHelpersTests.swift @@ -12,6 +12,18 @@ struct VoiceWakeHelpersTests { #expect(cleaned == defaultVoiceWakeTriggers) } + @Test func sanitizeTriggersLimitsWordLength() { + let long = String(repeating: "x", count: voiceWakeMaxWordLength + 5) + let cleaned = sanitizeVoiceWakeTriggers(["ok", long]) + #expect(cleaned[1].count == voiceWakeMaxWordLength) + } + + @Test func sanitizeTriggersLimitsWordCount() { + let words = (1...voiceWakeMaxWords + 3).map { "w\($0)" } + let cleaned = sanitizeVoiceWakeTriggers(words) + #expect(cleaned.count == voiceWakeMaxWords) + } + @Test func normalizeLocaleStripsCollation() { #expect(normalizeLocaleIdentifier("en_US@collation=phonebook") == "en_US") } diff --git a/apps/macos/Tests/ClawdbotIPCTests/WideAreaGatewayDiscoveryTests.swift b/apps/macos/Tests/ClawdbotIPCTests/WideAreaGatewayDiscoveryTests.swift index 4f081538b..d1dbf7962 100644 --- a/apps/macos/Tests/ClawdbotIPCTests/WideAreaGatewayDiscoveryTests.swift +++ b/apps/macos/Tests/ClawdbotIPCTests/WideAreaGatewayDiscoveryTests.swift @@ -20,15 +20,15 @@ struct WideAreaGatewayDiscoveryTests { let nameserver = args.first(where: { $0.hasPrefix("@") }) ?? "" if recordType == "PTR" { if nameserver == "@100.123.224.76" { - return "steipetacstudio-bridge._clawdbot-bridge._tcp.clawdbot.internal.\n" + return "steipetacstudio-gateway._clawdbot-gw._tcp.clawdbot.internal.\n" } return "" } if recordType == "SRV" { - return "0 0 18790 steipetacstudio.clawdbot.internal." + return "0 0 18789 steipetacstudio.clawdbot.internal." } if recordType == "TXT" { - return "\"displayName=Peter\\226\\128\\153s Mac Studio (Clawdbot)\" \"transport=bridge\" \"bridgePort=18790\" \"gatewayPort=18789\" \"tailnetDns=peters-mac-studio-1.sheep-coho.ts.net\" \"cliPath=/Users/steipete/clawdbot/src/entry.ts\"" + return "\"displayName=Peter\\226\\128\\153s Mac Studio (Clawdbot)\" \"gatewayPort=18789\" \"tailnetDns=peters-mac-studio-1.sheep-coho.ts.net\" \"cliPath=/Users/steipete/clawdbot/src/entry.ts\"" } return "" }) @@ -41,7 +41,7 @@ struct WideAreaGatewayDiscoveryTests { let beacon = beacons[0] let expectedDisplay = "Peter\u{2019}s Mac Studio (Clawdbot)" #expect(beacon.displayName == expectedDisplay) - #expect(beacon.bridgePort == 18790) + #expect(beacon.port == 18789) #expect(beacon.gatewayPort == 18789) #expect(beacon.tailnetDns == "peters-mac-studio-1.sheep-coho.ts.net") #expect(beacon.cliPath == "/Users/steipete/clawdbot/src/entry.ts") diff --git a/apps/shared/ClawdbotKit/Package.swift b/apps/shared/ClawdbotKit/Package.swift index b094e0a1c..88dc28b5c 100644 --- a/apps/shared/ClawdbotKit/Package.swift +++ b/apps/shared/ClawdbotKit/Package.swift @@ -9,17 +9,24 @@ let package = Package( .macOS(.v15), ], products: [ + .library(name: "ClawdbotProtocol", targets: ["ClawdbotProtocol"]), .library(name: "ClawdbotKit", targets: ["ClawdbotKit"]), .library(name: "ClawdbotChatUI", targets: ["ClawdbotChatUI"]), ], dependencies: [ .package(url: "https://github.com/steipete/ElevenLabsKit", exact: "0.1.0"), - .package(url: "https://github.com/gonzalezreal/textual", exact: "0.2.0"), + .package(url: "https://github.com/gonzalezreal/textual", exact: "0.3.1"), ], targets: [ + .target( + name: "ClawdbotProtocol", + swiftSettings: [ + .enableUpcomingFeature("StrictConcurrency"), + ]), .target( name: "ClawdbotKit", dependencies: [ + "ClawdbotProtocol", .product(name: "ElevenLabsKit", package: "ElevenLabsKit"), ], resources: [ diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotChatUI/ChatModels.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotChatUI/ChatModels.swift index ab86f6b53..da18963f4 100644 --- a/apps/shared/ClawdbotKit/Sources/ClawdbotChatUI/ChatModels.swift +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotChatUI/ChatModels.swift @@ -235,6 +235,27 @@ public struct ClawdbotChatHistoryPayload: Codable, Sendable { public let thinkingLevel: String? } +public struct ClawdbotSessionPreviewItem: Codable, Hashable, Sendable { + public let role: String + public let text: String +} + +public struct ClawdbotSessionPreviewEntry: Codable, Sendable { + public let key: String + public let status: String + public let items: [ClawdbotSessionPreviewItem] +} + +public struct ClawdbotSessionsPreviewPayload: Codable, Sendable { + public let ts: Int + public let previews: [ClawdbotSessionPreviewEntry] + + public init(ts: Int, previews: [ClawdbotSessionPreviewEntry]) { + self.ts = ts + self.previews = previews + } +} + public struct ClawdbotChatSendResponse: Codable, Sendable { public let runId: String public let status: String diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotChatUI/ChatView.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotChatUI/ChatView.swift index d243f6a96..44399a3e6 100644 --- a/apps/shared/ClawdbotKit/Sources/ClawdbotChatUI/ChatView.swift +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotChatUI/ChatView.swift @@ -12,6 +12,7 @@ public struct ClawdbotChatView: View { @State private var scrollPosition: UUID? @State private var showSessions = false @State private var hasPerformedInitialScroll = false + @State private var isPinnedToBottom = true private let showsSessionSwitcher: Bool private let style: Style private let markdownVariant: ChatMarkdownVariant @@ -87,36 +88,28 @@ public struct ClawdbotChatView: View { private var messageList: some View { ZStack { ScrollView { - #if os(macOS) - VStack(spacing: 0) { - LazyVStack(spacing: Layout.messageSpacing) { - self.messageListRows - } - - Color.clear - .frame(height: Layout.messageListPaddingBottom) - .id(self.scrollerBottomID) - } - // Use scroll targets for stable auto-scroll without ScrollViewReader relayout glitches. - .scrollTargetLayout() - .padding(.top, Layout.messageListPaddingTop) - .padding(.horizontal, Layout.messageListPaddingHorizontal) - #else LazyVStack(spacing: Layout.messageSpacing) { self.messageListRows Color.clear + #if os(macOS) + .frame(height: Layout.messageListPaddingBottom) + #else .frame(height: Layout.messageListPaddingBottom + 1) + #endif .id(self.scrollerBottomID) } // Use scroll targets for stable auto-scroll without ScrollViewReader relayout glitches. .scrollTargetLayout() .padding(.top, Layout.messageListPaddingTop) .padding(.horizontal, Layout.messageListPaddingHorizontal) - #endif } // Keep the scroll pinned to the bottom for new messages. .scrollPosition(id: self.$scrollPosition, anchor: .bottom) + .onChange(of: self.scrollPosition) { _, position in + guard let position else { return } + self.isPinnedToBottom = position == self.scrollerBottomID + } if self.viewModel.isLoading { ProgressView() @@ -133,18 +126,26 @@ public struct ClawdbotChatView: View { guard !isLoading, !self.hasPerformedInitialScroll else { return } self.scrollPosition = self.scrollerBottomID self.hasPerformedInitialScroll = true + self.isPinnedToBottom = true } .onChange(of: self.viewModel.sessionKey) { _, _ in self.hasPerformedInitialScroll = false + self.isPinnedToBottom = true } .onChange(of: self.viewModel.messages.count) { _, _ in - guard self.hasPerformedInitialScroll else { return } + guard self.hasPerformedInitialScroll, self.isPinnedToBottom else { return } withAnimation(.snappy(duration: 0.22)) { self.scrollPosition = self.scrollerBottomID } } .onChange(of: self.viewModel.pendingRunCount) { _, _ in - guard self.hasPerformedInitialScroll else { return } + guard self.hasPerformedInitialScroll, self.isPinnedToBottom else { return } + withAnimation(.snappy(duration: 0.22)) { + self.scrollPosition = self.scrollerBottomID + } + } + .onChange(of: self.viewModel.streamingAssistantText) { _, _ in + guard self.hasPerformedInitialScroll, self.isPinnedToBottom else { return } withAnimation(.snappy(duration: 0.22)) { self.scrollPosition = self.scrollerBottomID } diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/BonjourTypes.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/BonjourTypes.swift index 8f9df3617..4af6c5668 100644 --- a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/BonjourTypes.swift +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/BonjourTypes.swift @@ -2,24 +2,24 @@ import Foundation public enum ClawdbotBonjour { // v0: internal-only, subject to rename. - public static let bridgeServiceType = "_clawdbot-bridge._tcp" - public static let bridgeServiceDomain = "local." - public static let wideAreaBridgeServiceDomain = "clawdbot.internal." + public static let gatewayServiceType = "_clawdbot-gw._tcp" + public static let gatewayServiceDomain = "local." + public static let wideAreaGatewayServiceDomain = "clawdbot.internal." - public static let bridgeServiceDomains = [ - bridgeServiceDomain, - wideAreaBridgeServiceDomain, + public static let gatewayServiceDomains = [ + gatewayServiceDomain, + wideAreaGatewayServiceDomain, ] public static func normalizeServiceDomain(_ raw: String?) -> String { let trimmed = (raw ?? "").trimmingCharacters(in: .whitespacesAndNewlines) if trimmed.isEmpty { - return self.bridgeServiceDomain + return self.gatewayServiceDomain } let lower = trimmed.lowercased() if lower == "local" || lower == "local." { - return self.bridgeServiceDomain + return self.gatewayServiceDomain } return lower.hasSuffix(".") ? lower : (lower + ".") diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/BridgeFrames.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/BridgeFrames.swift index 833a3c96b..5d45ab269 100644 --- a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/BridgeFrames.swift +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/BridgeFrames.swift @@ -63,6 +63,8 @@ public struct BridgeHello: Codable, Sendable { public let token: String? public let platform: String? public let version: String? + public let coreVersion: String? + public let uiVersion: String? public let deviceFamily: String? public let modelIdentifier: String? public let caps: [String]? @@ -76,6 +78,8 @@ public struct BridgeHello: Codable, Sendable { token: String?, platform: String?, version: String?, + coreVersion: String? = nil, + uiVersion: String? = nil, deviceFamily: String? = nil, modelIdentifier: String? = nil, caps: [String]? = nil, @@ -88,6 +92,8 @@ public struct BridgeHello: Codable, Sendable { self.token = token self.platform = platform self.version = version + self.coreVersion = coreVersion + self.uiVersion = uiVersion self.deviceFamily = deviceFamily self.modelIdentifier = modelIdentifier self.caps = caps @@ -121,6 +127,8 @@ public struct BridgePairRequest: Codable, Sendable { public let displayName: String? public let platform: String? public let version: String? + public let coreVersion: String? + public let uiVersion: String? public let deviceFamily: String? public let modelIdentifier: String? public let caps: [String]? @@ -135,6 +143,8 @@ public struct BridgePairRequest: Codable, Sendable { displayName: String?, platform: String?, version: String?, + coreVersion: String? = nil, + uiVersion: String? = nil, deviceFamily: String? = nil, modelIdentifier: String? = nil, caps: [String]? = nil, @@ -148,6 +158,8 @@ public struct BridgePairRequest: Codable, Sendable { self.displayName = displayName self.platform = platform self.version = version + self.coreVersion = coreVersion + self.uiVersion = uiVersion self.deviceFamily = deviceFamily self.modelIdentifier = modelIdentifier self.caps = caps diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/DeviceAuthStore.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/DeviceAuthStore.swift new file mode 100644 index 000000000..80ff20c3f --- /dev/null +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/DeviceAuthStore.swift @@ -0,0 +1,107 @@ +import Foundation + +public struct DeviceAuthEntry: Codable, Sendable { + public let token: String + public let role: String + public let scopes: [String] + public let updatedAtMs: Int + + public init(token: String, role: String, scopes: [String], updatedAtMs: Int) { + self.token = token + self.role = role + self.scopes = scopes + self.updatedAtMs = updatedAtMs + } +} + +private struct DeviceAuthStoreFile: Codable { + var version: Int + var deviceId: String + var tokens: [String: DeviceAuthEntry] +} + +public enum DeviceAuthStore { + private static let fileName = "device-auth.json" + + public static func loadToken(deviceId: String, role: String) -> DeviceAuthEntry? { + guard let store = readStore(), store.deviceId == deviceId else { return nil } + let role = normalizeRole(role) + return store.tokens[role] + } + + public static func storeToken( + deviceId: String, + role: String, + token: String, + scopes: [String] = [] + ) -> DeviceAuthEntry { + let normalizedRole = normalizeRole(role) + var next = readStore() + if next?.deviceId != deviceId { + next = DeviceAuthStoreFile(version: 1, deviceId: deviceId, tokens: [:]) + } + let entry = DeviceAuthEntry( + token: token, + role: normalizedRole, + scopes: normalizeScopes(scopes), + updatedAtMs: Int(Date().timeIntervalSince1970 * 1000) + ) + if next == nil { + next = DeviceAuthStoreFile(version: 1, deviceId: deviceId, tokens: [:]) + } + next?.tokens[normalizedRole] = entry + if let store = next { + writeStore(store) + } + return entry + } + + public static func clearToken(deviceId: String, role: String) { + guard var store = readStore(), store.deviceId == deviceId else { return } + let normalizedRole = normalizeRole(role) + guard store.tokens[normalizedRole] != nil else { return } + store.tokens.removeValue(forKey: normalizedRole) + writeStore(store) + } + + private static func normalizeRole(_ role: String) -> String { + role.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private static func normalizeScopes(_ scopes: [String]) -> [String] { + let trimmed = scopes + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty } + return Array(Set(trimmed)).sorted() + } + + private static func fileURL() -> URL { + DeviceIdentityPaths.stateDirURL() + .appendingPathComponent("identity", isDirectory: true) + .appendingPathComponent(fileName, isDirectory: false) + } + + private static func readStore() -> DeviceAuthStoreFile? { + let url = fileURL() + guard let data = try? Data(contentsOf: url) else { return nil } + guard let decoded = try? JSONDecoder().decode(DeviceAuthStoreFile.self, from: data) else { + return nil + } + guard decoded.version == 1 else { return nil } + return decoded + } + + private static func writeStore(_ store: DeviceAuthStoreFile) { + let url = fileURL() + do { + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), + withIntermediateDirectories: true) + let data = try JSONEncoder().encode(store) + try data.write(to: url, options: [.atomic]) + try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) + } catch { + // best-effort only + } + } +} diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/DeviceIdentity.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/DeviceIdentity.swift new file mode 100644 index 000000000..3a3244614 --- /dev/null +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/DeviceIdentity.swift @@ -0,0 +1,110 @@ +import CryptoKit +import Foundation + +public struct DeviceIdentity: Codable, Sendable { + public var deviceId: String + public var publicKey: String + public var privateKey: String + public var createdAtMs: Int + + public init(deviceId: String, publicKey: String, privateKey: String, createdAtMs: Int) { + self.deviceId = deviceId + self.publicKey = publicKey + self.privateKey = privateKey + self.createdAtMs = createdAtMs + } +} + +enum DeviceIdentityPaths { + private static let stateDirEnv = "CLAWDBOT_STATE_DIR" + + static func stateDirURL() -> URL { + if let raw = getenv(self.stateDirEnv) { + let value = String(cString: raw).trimmingCharacters(in: .whitespacesAndNewlines) + if !value.isEmpty { + return URL(fileURLWithPath: value, isDirectory: true) + } + } + + if let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first { + return appSupport.appendingPathComponent("clawdbot", isDirectory: true) + } + + return FileManager.default.temporaryDirectory.appendingPathComponent("clawdbot", isDirectory: true) + } +} + +public enum DeviceIdentityStore { + private static let fileName = "device.json" + + public static func loadOrCreate() -> DeviceIdentity { + let url = self.fileURL() + if let data = try? Data(contentsOf: url), + let decoded = try? JSONDecoder().decode(DeviceIdentity.self, from: data), + !decoded.deviceId.isEmpty, + !decoded.publicKey.isEmpty, + !decoded.privateKey.isEmpty { + return decoded + } + let identity = self.generate() + self.save(identity) + return identity + } + + public static func signPayload(_ payload: String, identity: DeviceIdentity) -> String? { + guard let privateKeyData = Data(base64Encoded: identity.privateKey) else { return nil } + do { + let privateKey = try Curve25519.Signing.PrivateKey(rawRepresentation: privateKeyData) + let signature = try privateKey.signature(for: Data(payload.utf8)) + return self.base64UrlEncode(signature) + } catch { + return nil + } + } + + private static func generate() -> DeviceIdentity { + let privateKey = Curve25519.Signing.PrivateKey() + let publicKey = privateKey.publicKey + let publicKeyData = publicKey.rawRepresentation + let privateKeyData = privateKey.rawRepresentation + let deviceId = SHA256.hash(data: publicKeyData).compactMap { String(format: "%02x", $0) }.joined() + return DeviceIdentity( + deviceId: deviceId, + publicKey: publicKeyData.base64EncodedString(), + privateKey: privateKeyData.base64EncodedString(), + createdAtMs: Int(Date().timeIntervalSince1970 * 1000)) + } + + private static func base64UrlEncode(_ data: Data) -> String { + let base64 = data.base64EncodedString() + return base64 + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + } + + public static func publicKeyBase64Url(_ identity: DeviceIdentity) -> String? { + guard let data = Data(base64Encoded: identity.publicKey) else { return nil } + return self.base64UrlEncode(data) + } + + private static func save(_ identity: DeviceIdentity) { + let url = self.fileURL() + do { + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), + withIntermediateDirectories: true) + let data = try JSONEncoder().encode(identity) + try data.write(to: url, options: [.atomic]) + } catch { + // best-effort only + } + } + + private static func fileURL() -> URL { + let base = DeviceIdentityPaths.stateDirURL() + return base + .appendingPathComponent("identity", isDirectory: true) + .appendingPathComponent(fileName, isDirectory: false) + } +} diff --git a/apps/macos/Sources/Clawdbot/GatewayChannel.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayChannel.swift similarity index 59% rename from apps/macos/Sources/Clawdbot/GatewayChannel.swift rename to apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayChannel.swift index 81fe805cb..819014cda 100644 --- a/apps/macos/Sources/Clawdbot/GatewayChannel.swift +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayChannel.swift @@ -1,9 +1,8 @@ -import ClawdbotKit import ClawdbotProtocol import Foundation import OSLog -protocol WebSocketTasking: AnyObject { +public protocol WebSocketTasking: AnyObject { var state: URLSessionTask.State { get } func resume() func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) @@ -14,36 +13,41 @@ protocol WebSocketTasking: AnyObject { extension URLSessionWebSocketTask: WebSocketTasking {} -struct WebSocketTaskBox: @unchecked Sendable { - let task: any WebSocketTasking +public struct WebSocketTaskBox: @unchecked Sendable { + public let task: any WebSocketTasking + public init(task: any WebSocketTasking) { + self.task = task + } - var state: URLSessionTask.State { self.task.state } + public var state: URLSessionTask.State { self.task.state } - func resume() { self.task.resume() } + public func resume() { self.task.resume() } - func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + public func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { self.task.cancel(with: closeCode, reason: reason) } - func send(_ message: URLSessionWebSocketTask.Message) async throws { + public func send(_ message: URLSessionWebSocketTask.Message) async throws { try await self.task.send(message) } - func receive() async throws -> URLSessionWebSocketTask.Message { + public func receive() async throws -> URLSessionWebSocketTask.Message { try await self.task.receive() } - func receive(completionHandler: @escaping @Sendable (Result) -> Void) { + public func receive( + completionHandler: @escaping @Sendable (Result) -> Void) + { self.task.receive(completionHandler: completionHandler) } } -protocol WebSocketSessioning: AnyObject { +public protocol WebSocketSessioning: AnyObject { func makeWebSocketTask(url: URL) -> WebSocketTaskBox } extension URLSession: WebSocketSessioning { - func makeWebSocketTask(url: URL) -> WebSocketTaskBox { + public func makeWebSocketTask(url: URL) -> WebSocketTaskBox { let task = self.webSocketTask(with: url) // Avoid "Message too long" receive errors for large snapshots / history payloads. task.maximumMessageSize = 16 * 1024 * 1024 // 16 MB @@ -51,14 +55,60 @@ extension URLSession: WebSocketSessioning { } } -struct WebSocketSessionBox: @unchecked Sendable { - let session: any WebSocketSessioning +public struct WebSocketSessionBox: @unchecked Sendable { + public let session: any WebSocketSessioning + + public init(session: any WebSocketSessioning) { + self.session = session + } +} + +public struct GatewayConnectOptions: Sendable { + public var role: String + public var scopes: [String] + public var caps: [String] + public var commands: [String] + public var permissions: [String: Bool] + public var clientId: String + public var clientMode: String + public var clientDisplayName: String? + + public init( + role: String, + scopes: [String], + caps: [String], + commands: [String], + permissions: [String: Bool], + clientId: String, + clientMode: String, + clientDisplayName: String?) + { + self.role = role + self.scopes = scopes + self.caps = caps + self.commands = commands + self.permissions = permissions + self.clientId = clientId + self.clientMode = clientMode + self.clientDisplayName = clientDisplayName + } +} + +public enum GatewayAuthSource: String, Sendable { + case deviceToken = "device-token" + case sharedToken = "shared-token" + case password = "password" + case none = "none" } // Avoid ambiguity with the app's own AnyCodable type. private typealias ProtoAnyCodable = ClawdbotProtocol.AnyCodable -actor GatewayChannelActor { +private enum ConnectChallengeError: Error { + case timeout +} + +public actor GatewayChannelActor { private let logger = Logger(subsystem: "com.clawdbot", category: "gateway") private var task: WebSocketTaskBox? private var pending: [String: CheckedContinuation] = [:] @@ -74,32 +124,42 @@ actor GatewayChannelActor { private var lastSeq: Int? private var lastTick: Date? private var tickIntervalMs: Double = 30000 + private var lastAuthSource: GatewayAuthSource = .none private let decoder = JSONDecoder() private let encoder = JSONEncoder() private let connectTimeoutSeconds: Double = 6 + private let connectChallengeTimeoutSeconds: Double = 0.75 private var watchdogTask: Task? private var tickTask: Task? private let defaultRequestTimeoutMs: Double = 15000 private let pushHandler: (@Sendable (GatewayPush) async -> Void)? + private let connectOptions: GatewayConnectOptions? + private let disconnectHandler: (@Sendable (String) async -> Void)? - init( + public init( url: URL, token: String?, password: String? = nil, session: WebSocketSessionBox? = nil, - pushHandler: (@Sendable (GatewayPush) async -> Void)? = nil) + pushHandler: (@Sendable (GatewayPush) async -> Void)? = nil, + connectOptions: GatewayConnectOptions? = nil, + disconnectHandler: (@Sendable (String) async -> Void)? = nil) { self.url = url self.token = token self.password = password self.session = session?.session ?? URLSession(configuration: .default) self.pushHandler = pushHandler + self.connectOptions = connectOptions + self.disconnectHandler = disconnectHandler Task { [weak self] in await self?.startWatchdog() } } - func shutdown() async { + public func authSource() -> GatewayAuthSource { self.lastAuthSource } + + public func shutdown() async { self.shouldReconnect = false self.connected = false @@ -150,7 +210,7 @@ actor GatewayChannelActor { } } - func connect() async throws { + public func connect() async throws { if self.connected, self.task?.state == .running { return } if self.isConnecting { try await withCheckedThrowingContinuation { cont in @@ -178,6 +238,7 @@ actor GatewayChannelActor { let wrapped = self.wrap(error, context: "connect to gateway @ \(self.url.absoluteString)") self.connected = false self.task?.cancel(with: .goingAway, reason: nil) + await self.disconnectHandler?("connect failed: \(wrapped.localizedDescription)") let waiters = self.connectWaiters self.connectWaiters.removeAll() for waiter in waiters { @@ -199,11 +260,22 @@ actor GatewayChannelActor { } private func sendConnect() async throws { - let osVersion = ProcessInfo.processInfo.operatingSystemVersion - let platform = "macos \(osVersion.majorVersion).\(osVersion.minorVersion).\(osVersion.patchVersion)" + let platform = InstanceIdentity.platformString let primaryLocale = Locale.preferredLanguages.first ?? Locale.current.identifier - let clientDisplayName = InstanceIdentity.displayName - let clientId = "clawdbot-macos" + let options = self.connectOptions ?? GatewayConnectOptions( + role: "operator", + scopes: ["operator.admin", "operator.approvals", "operator.pairing"], + caps: [], + commands: [], + permissions: [:], + clientId: "clawdbot-macos", + clientMode: "ui", + clientDisplayName: InstanceIdentity.displayName) + let clientDisplayName = options.clientDisplayName ?? InstanceIdentity.displayName + let clientId = options.clientId + let clientMode = options.clientMode + let role = options.role + let scopes = options.scopes let reqId = UUID().uuidString var client: [String: ProtoAnyCodable] = [ @@ -212,10 +284,10 @@ actor GatewayChannelActor { "version": ProtoAnyCodable( Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev"), "platform": ProtoAnyCodable(platform), - "mode": ProtoAnyCodable("ui"), + "mode": ProtoAnyCodable(clientMode), "instanceId": ProtoAnyCodable(InstanceIdentity.instanceId), ] - client["deviceFamily"] = ProtoAnyCodable("Mac") + client["deviceFamily"] = ProtoAnyCodable(InstanceIdentity.deviceFamily) if let model = InstanceIdentity.modelIdentifier { client["modelIdentifier"] = ProtoAnyCodable(model) } @@ -223,15 +295,69 @@ actor GatewayChannelActor { "minProtocol": ProtoAnyCodable(GATEWAY_PROTOCOL_VERSION), "maxProtocol": ProtoAnyCodable(GATEWAY_PROTOCOL_VERSION), "client": ProtoAnyCodable(client), - "caps": ProtoAnyCodable([] as [String]), + "caps": ProtoAnyCodable(options.caps), "locale": ProtoAnyCodable(primaryLocale), "userAgent": ProtoAnyCodable(ProcessInfo.processInfo.operatingSystemVersionString), + "role": ProtoAnyCodable(role), + "scopes": ProtoAnyCodable(scopes), ] - if let token = self.token { - params["auth"] = ProtoAnyCodable(["token": ProtoAnyCodable(token)]) + if !options.commands.isEmpty { + params["commands"] = ProtoAnyCodable(options.commands) + } + if !options.permissions.isEmpty { + params["permissions"] = ProtoAnyCodable(options.permissions) + } + let identity = DeviceIdentityStore.loadOrCreate() + let storedToken = DeviceAuthStore.loadToken(deviceId: identity.deviceId, role: role)?.token + let authToken = storedToken ?? self.token + let authSource: GatewayAuthSource + if storedToken != nil { + authSource = .deviceToken + } else if authToken != nil { + authSource = .sharedToken + } else if self.password != nil { + authSource = .password + } else { + authSource = .none + } + self.lastAuthSource = authSource + self.logger.info("gateway connect auth=\(authSource.rawValue, privacy: .public)") + let canFallbackToShared = storedToken != nil && self.token != nil + if let authToken { + params["auth"] = ProtoAnyCodable(["token": ProtoAnyCodable(authToken)]) } else if let password = self.password { params["auth"] = ProtoAnyCodable(["password": ProtoAnyCodable(password)]) } + let signedAtMs = Int(Date().timeIntervalSince1970 * 1000) + let connectNonce = try await self.waitForConnectChallenge() + let scopesValue = scopes.joined(separator: ",") + var payloadParts = [ + connectNonce == nil ? "v1" : "v2", + identity.deviceId, + clientId, + clientMode, + role, + scopesValue, + String(signedAtMs), + authToken ?? "", + ] + if let connectNonce { + payloadParts.append(connectNonce) + } + let payload = payloadParts.joined(separator: "|") + if let signature = DeviceIdentityStore.signPayload(payload, identity: identity), + let publicKey = DeviceIdentityStore.publicKeyBase64Url(identity) { + var device: [String: ProtoAnyCodable] = [ + "id": ProtoAnyCodable(identity.deviceId), + "publicKey": ProtoAnyCodable(publicKey), + "signature": ProtoAnyCodable(signature), + "signedAt": ProtoAnyCodable(signedAtMs), + ] + if let connectNonce { + device["nonce"] = ProtoAnyCodable(connectNonce) + } + params["device"] = ProtoAnyCodable(device) + } let frame = RequestFrame( type: "req", @@ -240,40 +366,22 @@ actor GatewayChannelActor { params: ProtoAnyCodable(params)) let data = try self.encoder.encode(frame) try await self.task?.send(.data(data)) - guard let msg = try await task?.receive() else { - throw NSError( - domain: "Gateway", - code: 1, - userInfo: [NSLocalizedDescriptionKey: "connect failed (no response)"]) + do { + let response = try await self.waitForConnectResponse(reqId: reqId) + try await self.handleConnectResponse(response, identity: identity, role: role) + } catch { + if canFallbackToShared { + DeviceAuthStore.clearToken(deviceId: identity.deviceId, role: role) + } + throw error } - try await self.handleConnectResponse(msg, reqId: reqId) } - private func handleConnectResponse(_ msg: URLSessionWebSocketTask.Message, reqId: String) async throws { - let data: Data? = switch msg { - case let .data(d): d - case let .string(s): s.data(using: .utf8) - @unknown default: nil - } - guard let data else { - throw NSError( - domain: "Gateway", - code: 1, - userInfo: [NSLocalizedDescriptionKey: "connect failed (empty response)"]) - } - let decoder = JSONDecoder() - guard let frame = try? decoder.decode(GatewayFrame.self, from: data) else { - throw NSError( - domain: "Gateway", - code: 1, - userInfo: [NSLocalizedDescriptionKey: "connect failed (invalid response)"]) - } - guard case let .res(res) = frame, res.id == reqId else { - throw NSError( - domain: "Gateway", - code: 1, - userInfo: [NSLocalizedDescriptionKey: "connect failed (unexpected response)"]) - } + private func handleConnectResponse( + _ res: ResponseFrame, + identity: DeviceIdentity, + role: String + ) async throws { if res.ok == false { let msg = (res.error?["message"]?.value as? String) ?? "gateway connect failed" throw NSError(domain: "Gateway", code: 1008, userInfo: [NSLocalizedDescriptionKey: msg]) @@ -291,6 +399,17 @@ actor GatewayChannelActor { } else if let tick = ok.policy["tickIntervalMs"]?.value as? Int { self.tickIntervalMs = Double(tick) } + if let auth = ok.auth, + let deviceToken = auth["deviceToken"]?.value as? String { + let authRole = auth["role"]?.value as? String ?? role + let scopes = (auth["scopes"]?.value as? [ProtoAnyCodable])? + .compactMap { $0.value as? String } ?? [] + _ = DeviceAuthStore.storeToken( + deviceId: identity.deviceId, + role: authRole, + token: deviceToken, + scopes: scopes) + } self.lastTick = Date() self.tickTask?.cancel() self.tickTask = Task { [weak self] in @@ -319,6 +438,7 @@ actor GatewayChannelActor { let wrapped = self.wrap(err, context: "gateway receive") self.logger.error("gateway ws receive failed \(wrapped.localizedDescription, privacy: .public)") self.connected = false + await self.disconnectHandler?("receive failed: \(wrapped.localizedDescription)") await self.failPending(wrapped) await self.scheduleReconnect() } @@ -341,6 +461,7 @@ actor GatewayChannelActor { waiter.resume(returning: .res(res)) } case let .event(evt): + if evt.event == "connect.challenge" { return } if let seq = evt.seq { if let last = lastSeq, seq > last + 1 { await self.pushHandler?(.seqGap(expected: last + 1, received: seq)) @@ -354,6 +475,63 @@ actor GatewayChannelActor { } } + private func waitForConnectChallenge() async throws -> String? { + guard let task = self.task else { return nil } + do { + return try await AsyncTimeout.withTimeout( + seconds: self.connectChallengeTimeoutSeconds, + onTimeout: { ConnectChallengeError.timeout }, + operation: { [weak self] in + guard let self else { return nil } + while true { + let msg = try await task.receive() + guard let data = self.decodeMessageData(msg) else { continue } + guard let frame = try? self.decoder.decode(GatewayFrame.self, from: data) else { continue } + if case let .event(evt) = frame, evt.event == "connect.challenge" { + if let payload = evt.payload?.value as? [String: ProtoAnyCodable], + let nonce = payload["nonce"]?.value as? String { + return nonce + } + } + } + }) + } catch { + if error is ConnectChallengeError { return nil } + throw error + } + } + + private func waitForConnectResponse(reqId: String) async throws -> ResponseFrame { + guard let task = self.task else { + throw NSError( + domain: "Gateway", + code: 1, + userInfo: [NSLocalizedDescriptionKey: "connect failed (no response)"]) + } + while true { + let msg = try await task.receive() + guard let data = self.decodeMessageData(msg) else { continue } + guard let frame = try? self.decoder.decode(GatewayFrame.self, from: data) else { + throw NSError( + domain: "Gateway", + code: 1, + userInfo: [NSLocalizedDescriptionKey: "connect failed (invalid response)"]) + } + if case let .res(res) = frame, res.id == reqId { + return res + } + } + } + + private nonisolated func decodeMessageData(_ msg: URLSessionWebSocketTask.Message) -> Data? { + let data: Data? = switch msg { + case let .data(data): data + case let .string(text): text.data(using: .utf8) + @unknown default: nil + } + return data + } + private func watchTicks() async { let tolerance = self.tickIntervalMs * 2 while self.connected { @@ -391,44 +569,27 @@ actor GatewayChannelActor { } } - func request( + public func request( method: String, - params: [String: ClawdbotProtocol.AnyCodable]?, + params: [String: AnyCodable]?, timeoutMs: Double? = nil) async throws -> Data { - do { - try await self.connect() - } catch { - throw self.wrap(error, context: "gateway connect") - } - let id = UUID().uuidString + try await self.connectOrThrow(context: "gateway connect") let effectiveTimeout = timeoutMs ?? self.defaultRequestTimeoutMs - // Encode request using the generated models to avoid JSONSerialization/ObjC bridging pitfalls. - let paramsObject: ProtoAnyCodable? = params.map { entries in - let dict = entries.reduce(into: [String: ProtoAnyCodable]()) { dict, entry in - dict[entry.key] = ProtoAnyCodable(entry.value.value) - } - return ProtoAnyCodable(dict) - } - let frame = RequestFrame( - type: "req", - id: id, - method: method, - params: paramsObject) - let data = try self.encoder.encode(frame) + let payload = try self.encodeRequest(method: method, params: params, kind: "request") let response = try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in - self.pending[id] = cont + self.pending[payload.id] = cont Task { [weak self] in guard let self else { return } try? await Task.sleep(nanoseconds: UInt64(effectiveTimeout * 1_000_000)) - await self.timeoutRequest(id: id, timeoutMs: effectiveTimeout) + await self.timeoutRequest(id: payload.id, timeoutMs: effectiveTimeout) } Task { do { - try await self.task?.send(.data(data)) + try await self.task?.send(.data(payload.data)) } catch { let wrapped = self.wrap(error, context: "gateway send \(method)") - let waiter = self.pending.removeValue(forKey: id) + let waiter = self.pending.removeValue(forKey: payload.id) // Treat send failures as a broken socket: mark disconnected and trigger reconnect. self.connected = false self.task?.cancel(with: .goingAway, reason: nil) @@ -446,8 +607,8 @@ actor GatewayChannelActor { if res.ok == false { let code = res.error?["code"]?.value as? String let msg = res.error?["message"]?.value as? String - let details: [String: ClawdbotProtocol.AnyCodable] = (res.error ?? [:]).reduce(into: [:]) { acc, pair in - acc[pair.key] = ClawdbotProtocol.AnyCodable(pair.value.value) + let details: [String: AnyCodable] = (res.error ?? [:]).reduce(into: [:]) { acc, pair in + acc[pair.key] = AnyCodable(pair.value.value) } throw GatewayResponseError(method: method, code: code, message: msg, details: details) } @@ -458,6 +619,29 @@ actor GatewayChannelActor { return Data() // Should not happen, but tolerate empty payloads. } + public func send(method: String, params: [String: AnyCodable]?) async throws { + try await self.connectOrThrow(context: "gateway connect") + let payload = try self.encodeRequest(method: method, params: params, kind: "send") + guard let task = self.task else { + throw NSError( + domain: "Gateway", + code: 5, + userInfo: [NSLocalizedDescriptionKey: "gateway socket unavailable"]) + } + do { + try await task.send(.data(payload.data)) + } catch { + let wrapped = self.wrap(error, context: "gateway send \(method)") + self.connected = false + self.task?.cancel(with: .goingAway, reason: nil) + Task { [weak self] in + guard let self else { return } + await self.scheduleReconnect() + } + throw wrapped + } + } + // Wrap low-level URLSession/WebSocket errors with context so UI can surface them. private func wrap(_ error: Error, context: String) -> Error { if let urlError = error as? URLError { @@ -472,6 +656,42 @@ actor GatewayChannelActor { return NSError(domain: ns.domain, code: ns.code, userInfo: [NSLocalizedDescriptionKey: "\(context): \(desc)"]) } + private func connectOrThrow(context: String) async throws { + do { + try await self.connect() + } catch { + throw self.wrap(error, context: context) + } + } + + private func encodeRequest( + method: String, + params: [String: AnyCodable]?, + kind: String) throws -> (id: String, data: Data) + { + let id = UUID().uuidString + // Encode request using the generated models to avoid JSONSerialization/ObjC bridging pitfalls. + let paramsObject: ProtoAnyCodable? = params.map { entries in + let dict = entries.reduce(into: [String: ProtoAnyCodable]()) { dict, entry in + dict[entry.key] = ProtoAnyCodable(entry.value.value) + } + return ProtoAnyCodable(dict) + } + let frame = RequestFrame( + type: "req", + id: id, + method: method, + params: paramsObject) + do { + let data = try self.encoder.encode(frame) + return (id: id, data: data) + } catch { + self.logger.error( + "gateway \(kind) encode failed \(method, privacy: .public) error=\(error.localizedDescription, privacy: .public)") + throw error + } + } + private func failPending(_ error: Error) async { let waiters = self.pending self.pending.removeAll() diff --git a/apps/macos/Sources/ClawdbotDiscovery/BridgeEndpointID.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayEndpointID.swift similarity index 94% rename from apps/macos/Sources/ClawdbotDiscovery/BridgeEndpointID.swift rename to apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayEndpointID.swift index c89348122..eb2e94f51 100644 --- a/apps/macos/Sources/ClawdbotDiscovery/BridgeEndpointID.swift +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayEndpointID.swift @@ -1,8 +1,7 @@ -import ClawdbotKit import Foundation import Network -public enum BridgeEndpointID { +public enum GatewayEndpointID { public static func stableID(_ endpoint: NWEndpoint) -> String { switch endpoint { case let .service(name, type, domain, _): diff --git a/apps/macos/Sources/Clawdbot/GatewayErrors.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayErrors.swift similarity index 52% rename from apps/macos/Sources/Clawdbot/GatewayErrors.swift rename to apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayErrors.swift index 961880d76..6ff8b8293 100644 --- a/apps/macos/Sources/Clawdbot/GatewayErrors.swift +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayErrors.swift @@ -2,13 +2,13 @@ import ClawdbotProtocol import Foundation /// Structured error surfaced when the gateway responds with `{ ok: false }`. -struct GatewayResponseError: LocalizedError, @unchecked Sendable { - let method: String - let code: String - let message: String - let details: [String: AnyCodable] +public struct GatewayResponseError: LocalizedError, @unchecked Sendable { + public let method: String + public let code: String + public let message: String + public let details: [String: AnyCodable] - init(method: String, code: String?, message: String?, details: [String: AnyCodable]?) { + public init(method: String, code: String?, message: String?, details: [String: AnyCodable]?) { self.method = method self.code = (code?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false) ? code!.trimmingCharacters(in: .whitespacesAndNewlines) @@ -19,15 +19,20 @@ struct GatewayResponseError: LocalizedError, @unchecked Sendable { self.details = details ?? [:] } - var errorDescription: String? { + public var errorDescription: String? { if self.code == "GATEWAY_ERROR" { return "\(self.method): \(self.message)" } return "\(self.method): [\(self.code)] \(self.message)" } } -struct GatewayDecodingError: LocalizedError, Sendable { - let method: String - let message: String +public struct GatewayDecodingError: LocalizedError, Sendable { + public let method: String + public let message: String - var errorDescription: String? { "\(self.method): \(self.message)" } + public init(method: String, message: String) { + self.method = method + self.message = message + } + + public var errorDescription: String? { "\(self.method): \(self.message)" } } diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayNodeSession.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayNodeSession.swift new file mode 100644 index 000000000..122231f02 --- /dev/null +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayNodeSession.swift @@ -0,0 +1,262 @@ +import ClawdbotProtocol +import Foundation +import OSLog + +private struct NodeInvokeRequestPayload: Codable, Sendable { + var id: String + var nodeId: String + var command: String + var paramsJSON: String? + var timeoutMs: Int? + var idempotencyKey: String? +} + +public actor GatewayNodeSession { + private let logger = Logger(subsystem: "com.clawdbot", category: "node.gateway") + private let decoder = JSONDecoder() + private let encoder = JSONEncoder() + private var channel: GatewayChannelActor? + private var activeURL: URL? + private var activeToken: String? + private var activePassword: String? + private var connectOptions: GatewayConnectOptions? + private var onConnected: (@Sendable () async -> Void)? + private var onDisconnected: (@Sendable (String) async -> Void)? + private var onInvoke: (@Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse)? + + static func invokeWithTimeout( + request: BridgeInvokeRequest, + timeoutMs: Int?, + onInvoke: @escaping @Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse + ) async -> BridgeInvokeResponse { + let timeout = max(0, timeoutMs ?? 0) + guard timeout > 0 else { + return await onInvoke(request) + } + + return await withTaskGroup(of: BridgeInvokeResponse.self) { group in + group.addTask { await onInvoke(request) } + group.addTask { + try? await Task.sleep(nanoseconds: UInt64(timeout) * 1_000_000) + return BridgeInvokeResponse( + id: request.id, + ok: false, + error: ClawdbotNodeError( + code: .unavailable, + message: "node invoke timed out") + ) + } + + let first = await group.next()! + group.cancelAll() + return first + } + } + private var serverEventSubscribers: [UUID: AsyncStream.Continuation] = [:] + private var canvasHostUrl: String? + + public init() {} + + public func connect( + url: URL, + token: String?, + password: String?, + connectOptions: GatewayConnectOptions, + sessionBox: WebSocketSessionBox?, + onConnected: @escaping @Sendable () async -> Void, + onDisconnected: @escaping @Sendable (String) async -> Void, + onInvoke: @escaping @Sendable (BridgeInvokeRequest) async -> BridgeInvokeResponse + ) async throws { + let shouldReconnect = self.activeURL != url || + self.activeToken != token || + self.activePassword != password || + self.channel == nil + + self.connectOptions = connectOptions + self.onConnected = onConnected + self.onDisconnected = onDisconnected + self.onInvoke = onInvoke + + if shouldReconnect { + if let existing = self.channel { + await existing.shutdown() + } + let channel = GatewayChannelActor( + url: url, + token: token, + password: password, + session: sessionBox, + pushHandler: { [weak self] push in + await self?.handlePush(push) + }, + connectOptions: connectOptions, + disconnectHandler: { [weak self] reason in + await self?.onDisconnected?(reason) + }) + self.channel = channel + self.activeURL = url + self.activeToken = token + self.activePassword = password + } + + guard let channel = self.channel else { + throw NSError(domain: "Gateway", code: 0, userInfo: [ + NSLocalizedDescriptionKey: "gateway channel unavailable", + ]) + } + + do { + try await channel.connect() + await onConnected() + } catch { + await onDisconnected(error.localizedDescription) + throw error + } + } + + public func disconnect() async { + await self.channel?.shutdown() + self.channel = nil + self.activeURL = nil + self.activeToken = nil + self.activePassword = nil + } + + public func currentCanvasHostUrl() -> String? { + self.canvasHostUrl + } + + public func currentRemoteAddress() -> String? { + guard let url = self.activeURL else { return nil } + guard let host = url.host else { return url.absoluteString } + let port = url.port ?? (url.scheme == "wss" ? 443 : 80) + if host.contains(":") { + return "[\(host)]:\(port)" + } + return "\(host):\(port)" + } + + public func sendEvent(event: String, payloadJSON: String?) async { + guard let channel = self.channel else { return } + let params: [String: AnyCodable] = [ + "event": AnyCodable(event), + "payloadJSON": AnyCodable(payloadJSON ?? NSNull()), + ] + do { + try await channel.send(method: "node.event", params: params) + } catch { + self.logger.error("node event failed: \(error.localizedDescription, privacy: .public)") + } + } + + public func request(method: String, paramsJSON: String?, timeoutSeconds: Int = 15) async throws -> Data { + guard let channel = self.channel else { + throw NSError(domain: "Gateway", code: 11, userInfo: [ + NSLocalizedDescriptionKey: "not connected", + ]) + } + + let params = try self.decodeParamsJSON(paramsJSON) + return try await channel.request( + method: method, + params: params, + timeoutMs: Double(timeoutSeconds * 1000)) + } + + public func subscribeServerEvents(bufferingNewest: Int = 200) -> AsyncStream { + let id = UUID() + let session = self + return AsyncStream(bufferingPolicy: .bufferingNewest(bufferingNewest)) { continuation in + self.serverEventSubscribers[id] = continuation + continuation.onTermination = { @Sendable _ in + Task { await session.removeServerEventSubscriber(id) } + } + } + } + + private func handlePush(_ push: GatewayPush) async { + switch push { + case let .snapshot(ok): + let raw = ok.canvashosturl?.trimmingCharacters(in: .whitespacesAndNewlines) + self.canvasHostUrl = (raw?.isEmpty == false) ? raw : nil + await self.onConnected?() + case let .event(evt): + await self.handleEvent(evt) + default: + break + } + } + + private func handleEvent(_ evt: EventFrame) async { + self.broadcastServerEvent(evt) + guard evt.event == "node.invoke.request" else { return } + guard let payload = evt.payload else { return } + do { + let data = try self.encoder.encode(payload) + let request = try self.decoder.decode(NodeInvokeRequestPayload.self, from: data) + guard let onInvoke else { return } + let req = BridgeInvokeRequest(id: request.id, command: request.command, paramsJSON: request.paramsJSON) + let response = await Self.invokeWithTimeout( + request: req, + timeoutMs: request.timeoutMs, + onInvoke: onInvoke + ) + await self.sendInvokeResult(request: request, response: response) + } catch { + self.logger.error("node invoke decode failed: \(error.localizedDescription, privacy: .public)") + } + } + + private func sendInvokeResult(request: NodeInvokeRequestPayload, response: BridgeInvokeResponse) async { + guard let channel = self.channel else { return } + var params: [String: AnyCodable] = [ + "id": AnyCodable(request.id), + "nodeId": AnyCodable(request.nodeId), + "ok": AnyCodable(response.ok), + ] + if let payloadJSON = response.payloadJSON { + params["payloadJSON"] = AnyCodable(payloadJSON) + } + if let error = response.error { + params["error"] = AnyCodable([ + "code": error.code.rawValue, + "message": error.message, + ]) + } + do { + try await channel.send(method: "node.invoke.result", params: params) + } catch { + self.logger.error("node invoke result failed: \(error.localizedDescription, privacy: .public)") + } + } + + private func decodeParamsJSON( + _ paramsJSON: String?) throws -> [String: AnyCodable]? + { + guard let paramsJSON, !paramsJSON.isEmpty else { return nil } + guard let data = paramsJSON.data(using: .utf8) else { + throw NSError(domain: "Gateway", code: 12, userInfo: [ + NSLocalizedDescriptionKey: "paramsJSON not UTF-8", + ]) + } + let raw = try JSONSerialization.jsonObject(with: data) + guard let dict = raw as? [String: Any] else { + return nil + } + return dict.reduce(into: [:]) { acc, entry in + acc[entry.key] = AnyCodable(entry.value) + } + } + + private func broadcastServerEvent(_ evt: EventFrame) { + for (id, continuation) in self.serverEventSubscribers { + if case .terminated = continuation.yield(evt) { + self.serverEventSubscribers.removeValue(forKey: id) + } + } + } + + private func removeServerEventSubscriber(_ id: UUID) { + self.serverEventSubscribers.removeValue(forKey: id) + } +} diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayPayloadDecoding.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayPayloadDecoding.swift new file mode 100644 index 000000000..1895189f1 --- /dev/null +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayPayloadDecoding.swift @@ -0,0 +1,36 @@ +import ClawdbotProtocol +import Foundation + +public enum GatewayPayloadDecoding { + public static func decode( + _ payload: ClawdbotProtocol.AnyCodable, + as _: T.Type = T.self) throws -> T + { + let data = try JSONEncoder().encode(payload) + return try JSONDecoder().decode(T.self, from: data) + } + + public static func decode( + _ payload: AnyCodable, + as _: T.Type = T.self) throws -> T + { + let data = try JSONEncoder().encode(payload) + return try JSONDecoder().decode(T.self, from: data) + } + + public static func decodeIfPresent( + _ payload: ClawdbotProtocol.AnyCodable?, + as _: T.Type = T.self) throws -> T? + { + guard let payload else { return nil } + return try self.decode(payload, as: T.self) + } + + public static func decodeIfPresent( + _ payload: AnyCodable?, + as _: T.Type = T.self) throws -> T? + { + guard let payload else { return nil } + return try self.decode(payload, as: T.self) + } +} diff --git a/apps/macos/Sources/Clawdbot/GatewayPush.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayPush.swift similarity index 92% rename from apps/macos/Sources/Clawdbot/GatewayPush.swift rename to apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayPush.swift index 2183977fe..1e9b0e43b 100644 --- a/apps/macos/Sources/Clawdbot/GatewayPush.swift +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayPush.swift @@ -3,7 +3,7 @@ import ClawdbotProtocol /// Server-push messages from the gateway websocket. /// /// This is the in-process replacement for the legacy `NotificationCenter` fan-out. -enum GatewayPush: Sendable { +public enum GatewayPush: Sendable { /// A full snapshot that arrives on connect (or reconnect). case snapshot(HelloOk) /// A server push event frame. diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayTLSPinning.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayTLSPinning.swift new file mode 100644 index 000000000..f22505eff --- /dev/null +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/GatewayTLSPinning.swift @@ -0,0 +1,118 @@ +import CryptoKit +import Foundation +import Security + +public struct GatewayTLSParams: Sendable { + public let required: Bool + public let expectedFingerprint: String? + public let allowTOFU: Bool + public let storeKey: String? + + public init(required: Bool, expectedFingerprint: String?, allowTOFU: Bool, storeKey: String?) { + self.required = required + self.expectedFingerprint = expectedFingerprint + self.allowTOFU = allowTOFU + self.storeKey = storeKey + } +} + +public enum GatewayTLSStore { + private static let suiteName = "com.clawdbot.shared" + private static let keyPrefix = "gateway.tls." + + private static var defaults: UserDefaults { + UserDefaults(suiteName: suiteName) ?? .standard + } + + public static func loadFingerprint(stableID: String) -> String? { + let key = self.keyPrefix + stableID + let raw = self.defaults.string(forKey: key)?.trimmingCharacters(in: .whitespacesAndNewlines) + return raw?.isEmpty == false ? raw : nil + } + + public static func saveFingerprint(_ value: String, stableID: String) { + let key = self.keyPrefix + stableID + self.defaults.set(value, forKey: key) + } +} + +public final class GatewayTLSPinningSession: NSObject, WebSocketSessioning, URLSessionDelegate, @unchecked Sendable { + private let params: GatewayTLSParams + private lazy var session: URLSession = { + let config = URLSessionConfiguration.default + config.waitsForConnectivity = true + return URLSession(configuration: config, delegate: self, delegateQueue: nil) + }() + + public init(params: GatewayTLSParams) { + self.params = params + super.init() + } + + public func makeWebSocketTask(url: URL) -> WebSocketTaskBox { + let task = self.session.webSocketTask(with: url) + task.maximumMessageSize = 16 * 1024 * 1024 + return WebSocketTaskBox(task: task) + } + + public func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void + ) { + guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, + let trust = challenge.protectionSpace.serverTrust + else { + completionHandler(.performDefaultHandling, nil) + return + } + + let expected = params.expectedFingerprint.map(normalizeFingerprint) + if let fingerprint = certificateFingerprint(trust) { + if let expected { + if fingerprint == expected { + completionHandler(.useCredential, URLCredential(trust: trust)) + } else { + completionHandler(.cancelAuthenticationChallenge, nil) + } + return + } + if params.allowTOFU { + if let storeKey = params.storeKey { + GatewayTLSStore.saveFingerprint(fingerprint, stableID: storeKey) + } + completionHandler(.useCredential, URLCredential(trust: trust)) + return + } + } + + let ok = SecTrustEvaluateWithError(trust, nil) + if ok || !params.required { + completionHandler(.useCredential, URLCredential(trust: trust)) + } else { + completionHandler(.cancelAuthenticationChallenge, nil) + } + } +} + +private func certificateFingerprint(_ trust: SecTrust) -> String? { + guard let chain = SecTrustCopyCertificateChain(trust) as? [SecCertificate], + let cert = chain.first + else { + return nil + } + return sha256Hex(SecCertificateCopyData(cert) as Data) +} + +private func sha256Hex(_ data: Data) -> String { + let digest = SHA256.hash(data: data) + return digest.map { String(format: "%02x", $0) }.joined() +} + +private func normalizeFingerprint(_ raw: String) -> String { + let stripped = raw.replacingOccurrences( + of: #"(?i)^sha-?256\s*:?\s*"#, + with: "", + options: .regularExpression) + return stripped.lowercased().filter(\.isHexDigit) +} diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/InstanceIdentity.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/InstanceIdentity.swift new file mode 100644 index 000000000..56be75e04 --- /dev/null +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/InstanceIdentity.swift @@ -0,0 +1,108 @@ +import Foundation + +#if canImport(UIKit) +import UIKit +#endif + +public enum InstanceIdentity { + private static let suiteName = "com.clawdbot.shared" + private static let instanceIdKey = "instanceId" + + private static var defaults: UserDefaults { + UserDefaults(suiteName: suiteName) ?? .standard + } + +#if canImport(UIKit) + private static func readMainActor(_ body: @MainActor () -> T) -> T { + if Thread.isMainThread { + return MainActor.assumeIsolated { body() } + } + return DispatchQueue.main.sync { + MainActor.assumeIsolated { body() } + } + } +#endif + + public static let instanceId: String = { + let defaults = Self.defaults + if let existing = defaults.string(forKey: instanceIdKey)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !existing.isEmpty + { + return existing + } + + let id = UUID().uuidString.lowercased() + defaults.set(id, forKey: instanceIdKey) + return id + }() + + public static let displayName: String = { +#if canImport(UIKit) + let name = Self.readMainActor { + UIDevice.current.name.trimmingCharacters(in: .whitespacesAndNewlines) + } + return name.isEmpty ? "clawdbot" : name +#else + if let name = Host.current().localizedName?.trimmingCharacters(in: .whitespacesAndNewlines), + !name.isEmpty + { + return name + } + return "clawdbot" +#endif + }() + + public static let modelIdentifier: String? = { +#if canImport(UIKit) + var systemInfo = utsname() + uname(&systemInfo) + let machine = withUnsafeBytes(of: &systemInfo.machine) { ptr in + String(bytes: ptr.prefix { $0 != 0 }, encoding: .utf8) + } + let trimmed = machine?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return trimmed.isEmpty ? nil : trimmed +#else + var size = 0 + guard sysctlbyname("hw.model", nil, &size, nil, 0) == 0, size > 1 else { return nil } + + var buffer = [CChar](repeating: 0, count: size) + guard sysctlbyname("hw.model", &buffer, &size, nil, 0) == 0 else { return nil } + + let bytes = buffer.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) } + guard let raw = String(bytes: bytes, encoding: .utf8) else { return nil } + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed +#endif + }() + + public static let deviceFamily: String = { +#if canImport(UIKit) + return Self.readMainActor { + switch UIDevice.current.userInterfaceIdiom { + case .pad: return "iPad" + case .phone: return "iPhone" + default: return "iOS" + } + } +#else + return "Mac" +#endif + }() + + public static let platformString: String = { + let v = ProcessInfo.processInfo.operatingSystemVersion +#if canImport(UIKit) + let name = Self.readMainActor { + switch UIDevice.current.userInterfaceIdiom { + case .pad: return "iPadOS" + case .phone: return "iOS" + default: return "iOS" + } + } + return "\(name) \(v.majorVersion).\(v.minorVersion).\(v.patchVersion)" +#else + return "macOS \(v.majorVersion).\(v.minorVersion).\(v.patchVersion)" +#endif + }() +} diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/StoragePaths.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/StoragePaths.swift index bcea1aaab..b785efee7 100644 --- a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/StoragePaths.swift +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/StoragePaths.swift @@ -2,7 +2,7 @@ import Foundation public enum ClawdbotNodeStorage { public static func appSupportDir() throws -> URL { - let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first + let base = FileManager().urls(for: .applicationSupportDirectory, in: .userDomainMask).first guard let base else { throw NSError(domain: "ClawdbotNodeStorage", code: 1, userInfo: [ NSLocalizedDescriptionKey: "Application Support directory unavailable", @@ -19,7 +19,7 @@ public enum ClawdbotNodeStorage { } public static func cachesDir() throws -> URL { - let base = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first + let base = FileManager().urls(for: .cachesDirectory, in: .userDomainMask).first guard let base else { throw NSError(domain: "ClawdbotNodeStorage", code: 2, userInfo: [ NSLocalizedDescriptionKey: "Caches directory unavailable", diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/SystemCommands.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/SystemCommands.swift index ca35a25b3..bfe980f41 100644 --- a/apps/shared/ClawdbotKit/Sources/ClawdbotKit/SystemCommands.swift +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotKit/SystemCommands.swift @@ -4,6 +4,8 @@ public enum ClawdbotSystemCommand: String, Codable, Sendable { case run = "system.run" case which = "system.which" case notify = "system.notify" + case execApprovalsGet = "system.execApprovals.get" + case execApprovalsSet = "system.execApprovals.set" } public enum ClawdbotNotificationPriority: String, Codable, Sendable { @@ -20,23 +22,38 @@ public enum ClawdbotNotificationDelivery: String, Codable, Sendable { public struct ClawdbotSystemRunParams: Codable, Sendable, Equatable { public var command: [String] + public var rawCommand: String? public var cwd: String? public var env: [String: String]? public var timeoutMs: Int? public var needsScreenRecording: Bool? + public var agentId: String? + public var sessionKey: String? + public var approved: Bool? + public var approvalDecision: String? public init( command: [String], + rawCommand: String? = nil, cwd: String? = nil, env: [String: String]? = nil, timeoutMs: Int? = nil, - needsScreenRecording: Bool? = nil) + needsScreenRecording: Bool? = nil, + agentId: String? = nil, + sessionKey: String? = nil, + approved: Bool? = nil, + approvalDecision: String? = nil) { self.command = command + self.rawCommand = rawCommand self.cwd = cwd self.env = env self.timeoutMs = timeoutMs self.needsScreenRecording = needsScreenRecording + self.agentId = agentId + self.sessionKey = sessionKey + self.approved = approved + self.approvalDecision = approvalDecision } } diff --git a/apps/macos/Sources/ClawdbotProtocol/AnyCodable.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotProtocol/AnyCodable.swift similarity index 100% rename from apps/macos/Sources/ClawdbotProtocol/AnyCodable.swift rename to apps/shared/ClawdbotKit/Sources/ClawdbotProtocol/AnyCodable.swift diff --git a/apps/shared/ClawdbotKit/Sources/ClawdbotProtocol/GatewayModels.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotProtocol/GatewayModels.swift new file mode 100644 index 000000000..9d2ca5ed4 --- /dev/null +++ b/apps/shared/ClawdbotKit/Sources/ClawdbotProtocol/GatewayModels.swift @@ -0,0 +1,2454 @@ +// Generated by scripts/protocol-gen-swift.ts — do not edit by hand +import Foundation + +public let GATEWAY_PROTOCOL_VERSION = 3 + +public enum ErrorCode: String, Codable, Sendable { + case notLinked = "NOT_LINKED" + case notPaired = "NOT_PAIRED" + case agentTimeout = "AGENT_TIMEOUT" + case invalidRequest = "INVALID_REQUEST" + case unavailable = "UNAVAILABLE" +} + +public struct ConnectParams: Codable, Sendable { + public let minprotocol: Int + public let maxprotocol: Int + public let client: [String: AnyCodable] + public let caps: [String]? + public let commands: [String]? + public let permissions: [String: AnyCodable]? + public let pathenv: String? + public let role: String? + public let scopes: [String]? + public let device: [String: AnyCodable]? + public let auth: [String: AnyCodable]? + public let locale: String? + public let useragent: String? + + public init( + minprotocol: Int, + maxprotocol: Int, + client: [String: AnyCodable], + caps: [String]?, + commands: [String]?, + permissions: [String: AnyCodable]?, + pathenv: String?, + role: String?, + scopes: [String]?, + device: [String: AnyCodable]?, + auth: [String: AnyCodable]?, + locale: String?, + useragent: String? + ) { + self.minprotocol = minprotocol + self.maxprotocol = maxprotocol + self.client = client + self.caps = caps + self.commands = commands + self.permissions = permissions + self.pathenv = pathenv + self.role = role + self.scopes = scopes + self.device = device + self.auth = auth + self.locale = locale + self.useragent = useragent + } + private enum CodingKeys: String, CodingKey { + case minprotocol = "minProtocol" + case maxprotocol = "maxProtocol" + case client + case caps + case commands + case permissions + case pathenv = "pathEnv" + case role + case scopes + case device + case auth + case locale + case useragent = "userAgent" + } +} + +public struct HelloOk: Codable, Sendable { + public let type: String + public let _protocol: Int + public let server: [String: AnyCodable] + public let features: [String: AnyCodable] + public let snapshot: Snapshot + public let canvashosturl: String? + public let auth: [String: AnyCodable]? + public let policy: [String: AnyCodable] + + public init( + type: String, + _protocol: Int, + server: [String: AnyCodable], + features: [String: AnyCodable], + snapshot: Snapshot, + canvashosturl: String?, + auth: [String: AnyCodable]?, + policy: [String: AnyCodable] + ) { + self.type = type + self._protocol = _protocol + self.server = server + self.features = features + self.snapshot = snapshot + self.canvashosturl = canvashosturl + self.auth = auth + self.policy = policy + } + private enum CodingKeys: String, CodingKey { + case type + case _protocol = "protocol" + case server + case features + case snapshot + case canvashosturl = "canvasHostUrl" + case auth + case policy + } +} + +public struct RequestFrame: Codable, Sendable { + public let type: String + public let id: String + public let method: String + public let params: AnyCodable? + + public init( + type: String, + id: String, + method: String, + params: AnyCodable? + ) { + self.type = type + self.id = id + self.method = method + self.params = params + } + private enum CodingKeys: String, CodingKey { + case type + case id + case method + case params + } +} + +public struct ResponseFrame: Codable, Sendable { + public let type: String + public let id: String + public let ok: Bool + public let payload: AnyCodable? + public let error: [String: AnyCodable]? + + public init( + type: String, + id: String, + ok: Bool, + payload: AnyCodable?, + error: [String: AnyCodable]? + ) { + self.type = type + self.id = id + self.ok = ok + self.payload = payload + self.error = error + } + private enum CodingKeys: String, CodingKey { + case type + case id + case ok + case payload + case error + } +} + +public struct EventFrame: Codable, Sendable { + public let type: String + public let event: String + public let payload: AnyCodable? + public let seq: Int? + public let stateversion: [String: AnyCodable]? + + public init( + type: String, + event: String, + payload: AnyCodable?, + seq: Int?, + stateversion: [String: AnyCodable]? + ) { + self.type = type + self.event = event + self.payload = payload + self.seq = seq + self.stateversion = stateversion + } + private enum CodingKeys: String, CodingKey { + case type + case event + case payload + case seq + case stateversion = "stateVersion" + } +} + +public struct PresenceEntry: Codable, Sendable { + public let host: String? + public let ip: String? + public let version: String? + public let platform: String? + public let devicefamily: String? + public let modelidentifier: String? + public let mode: String? + public let lastinputseconds: Int? + public let reason: String? + public let tags: [String]? + public let text: String? + public let ts: Int + public let deviceid: String? + public let roles: [String]? + public let scopes: [String]? + public let instanceid: String? + + public init( + host: String?, + ip: String?, + version: String?, + platform: String?, + devicefamily: String?, + modelidentifier: String?, + mode: String?, + lastinputseconds: Int?, + reason: String?, + tags: [String]?, + text: String?, + ts: Int, + deviceid: String?, + roles: [String]?, + scopes: [String]?, + instanceid: String? + ) { + self.host = host + self.ip = ip + self.version = version + self.platform = platform + self.devicefamily = devicefamily + self.modelidentifier = modelidentifier + self.mode = mode + self.lastinputseconds = lastinputseconds + self.reason = reason + self.tags = tags + self.text = text + self.ts = ts + self.deviceid = deviceid + self.roles = roles + self.scopes = scopes + self.instanceid = instanceid + } + private enum CodingKeys: String, CodingKey { + case host + case ip + case version + case platform + case devicefamily = "deviceFamily" + case modelidentifier = "modelIdentifier" + case mode + case lastinputseconds = "lastInputSeconds" + case reason + case tags + case text + case ts + case deviceid = "deviceId" + case roles + case scopes + case instanceid = "instanceId" + } +} + +public struct StateVersion: Codable, Sendable { + public let presence: Int + public let health: Int + + public init( + presence: Int, + health: Int + ) { + self.presence = presence + self.health = health + } + private enum CodingKeys: String, CodingKey { + case presence + case health + } +} + +public struct Snapshot: Codable, Sendable { + public let presence: [PresenceEntry] + public let health: AnyCodable + public let stateversion: StateVersion + public let uptimems: Int + public let configpath: String? + public let statedir: String? + public let sessiondefaults: [String: AnyCodable]? + + public init( + presence: [PresenceEntry], + health: AnyCodable, + stateversion: StateVersion, + uptimems: Int, + configpath: String?, + statedir: String?, + sessiondefaults: [String: AnyCodable]? + ) { + self.presence = presence + self.health = health + self.stateversion = stateversion + self.uptimems = uptimems + self.configpath = configpath + self.statedir = statedir + self.sessiondefaults = sessiondefaults + } + private enum CodingKeys: String, CodingKey { + case presence + case health + case stateversion = "stateVersion" + case uptimems = "uptimeMs" + case configpath = "configPath" + case statedir = "stateDir" + case sessiondefaults = "sessionDefaults" + } +} + +public struct ErrorShape: Codable, Sendable { + public let code: String + public let message: String + public let details: AnyCodable? + public let retryable: Bool? + public let retryafterms: Int? + + public init( + code: String, + message: String, + details: AnyCodable?, + retryable: Bool?, + retryafterms: Int? + ) { + self.code = code + self.message = message + self.details = details + self.retryable = retryable + self.retryafterms = retryafterms + } + private enum CodingKeys: String, CodingKey { + case code + case message + case details + case retryable + case retryafterms = "retryAfterMs" + } +} + +public struct AgentEvent: Codable, Sendable { + public let runid: String + public let seq: Int + public let stream: String + public let ts: Int + public let data: [String: AnyCodable] + + public init( + runid: String, + seq: Int, + stream: String, + ts: Int, + data: [String: AnyCodable] + ) { + self.runid = runid + self.seq = seq + self.stream = stream + self.ts = ts + self.data = data + } + private enum CodingKeys: String, CodingKey { + case runid = "runId" + case seq + case stream + case ts + case data + } +} + +public struct SendParams: Codable, Sendable { + public let to: String + public let message: String + public let mediaurl: String? + public let mediaurls: [String]? + public let gifplayback: Bool? + public let channel: String? + public let accountid: String? + public let sessionkey: String? + public let idempotencykey: String + + public init( + to: String, + message: String, + mediaurl: String?, + mediaurls: [String]?, + gifplayback: Bool?, + channel: String?, + accountid: String?, + sessionkey: String?, + idempotencykey: String + ) { + self.to = to + self.message = message + self.mediaurl = mediaurl + self.mediaurls = mediaurls + self.gifplayback = gifplayback + self.channel = channel + self.accountid = accountid + self.sessionkey = sessionkey + self.idempotencykey = idempotencykey + } + private enum CodingKeys: String, CodingKey { + case to + case message + case mediaurl = "mediaUrl" + case mediaurls = "mediaUrls" + case gifplayback = "gifPlayback" + case channel + case accountid = "accountId" + case sessionkey = "sessionKey" + case idempotencykey = "idempotencyKey" + } +} + +public struct PollParams: Codable, Sendable { + public let to: String + public let question: String + public let options: [String] + public let maxselections: Int? + public let durationhours: Int? + public let channel: String? + public let accountid: String? + public let idempotencykey: String + + public init( + to: String, + question: String, + options: [String], + maxselections: Int?, + durationhours: Int?, + channel: String?, + accountid: String?, + idempotencykey: String + ) { + self.to = to + self.question = question + self.options = options + self.maxselections = maxselections + self.durationhours = durationhours + self.channel = channel + self.accountid = accountid + self.idempotencykey = idempotencykey + } + private enum CodingKeys: String, CodingKey { + case to + case question + case options + case maxselections = "maxSelections" + case durationhours = "durationHours" + case channel + case accountid = "accountId" + case idempotencykey = "idempotencyKey" + } +} + +public struct AgentParams: Codable, Sendable { + public let message: String + public let agentid: String? + public let to: String? + public let replyto: String? + public let sessionid: String? + public let sessionkey: String? + public let thinking: String? + public let deliver: Bool? + public let attachments: [AnyCodable]? + public let channel: String? + public let replychannel: String? + public let accountid: String? + public let replyaccountid: String? + public let threadid: String? + public let groupid: String? + public let groupchannel: String? + public let groupspace: String? + public let timeout: Int? + public let lane: String? + public let extrasystemprompt: String? + public let idempotencykey: String + public let label: String? + public let spawnedby: String? + + public init( + message: String, + agentid: String?, + to: String?, + replyto: String?, + sessionid: String?, + sessionkey: String?, + thinking: String?, + deliver: Bool?, + attachments: [AnyCodable]?, + channel: String?, + replychannel: String?, + accountid: String?, + replyaccountid: String?, + threadid: String?, + groupid: String?, + groupchannel: String?, + groupspace: String?, + timeout: Int?, + lane: String?, + extrasystemprompt: String?, + idempotencykey: String, + label: String?, + spawnedby: String? + ) { + self.message = message + self.agentid = agentid + self.to = to + self.replyto = replyto + self.sessionid = sessionid + self.sessionkey = sessionkey + self.thinking = thinking + self.deliver = deliver + self.attachments = attachments + self.channel = channel + self.replychannel = replychannel + self.accountid = accountid + self.replyaccountid = replyaccountid + self.threadid = threadid + self.groupid = groupid + self.groupchannel = groupchannel + self.groupspace = groupspace + self.timeout = timeout + self.lane = lane + self.extrasystemprompt = extrasystemprompt + self.idempotencykey = idempotencykey + self.label = label + self.spawnedby = spawnedby + } + private enum CodingKeys: String, CodingKey { + case message + case agentid = "agentId" + case to + case replyto = "replyTo" + case sessionid = "sessionId" + case sessionkey = "sessionKey" + case thinking + case deliver + case attachments + case channel + case replychannel = "replyChannel" + case accountid = "accountId" + case replyaccountid = "replyAccountId" + case threadid = "threadId" + case groupid = "groupId" + case groupchannel = "groupChannel" + case groupspace = "groupSpace" + case timeout + case lane + case extrasystemprompt = "extraSystemPrompt" + case idempotencykey = "idempotencyKey" + case label + case spawnedby = "spawnedBy" + } +} + +public struct AgentIdentityParams: Codable, Sendable { + public let agentid: String? + public let sessionkey: String? + + public init( + agentid: String?, + sessionkey: String? + ) { + self.agentid = agentid + self.sessionkey = sessionkey + } + private enum CodingKeys: String, CodingKey { + case agentid = "agentId" + case sessionkey = "sessionKey" + } +} + +public struct AgentIdentityResult: Codable, Sendable { + public let agentid: String + public let name: String? + public let avatar: String? + + public init( + agentid: String, + name: String?, + avatar: String? + ) { + self.agentid = agentid + self.name = name + self.avatar = avatar + } + private enum CodingKeys: String, CodingKey { + case agentid = "agentId" + case name + case avatar + } +} + +public struct AgentWaitParams: Codable, Sendable { + public let runid: String + public let timeoutms: Int? + + public init( + runid: String, + timeoutms: Int? + ) { + self.runid = runid + self.timeoutms = timeoutms + } + private enum CodingKeys: String, CodingKey { + case runid = "runId" + case timeoutms = "timeoutMs" + } +} + +public struct WakeParams: Codable, Sendable { + public let mode: AnyCodable + public let text: String + + public init( + mode: AnyCodable, + text: String + ) { + self.mode = mode + self.text = text + } + private enum CodingKeys: String, CodingKey { + case mode + case text + } +} + +public struct NodePairRequestParams: Codable, Sendable { + public let nodeid: String + public let displayname: String? + public let platform: String? + public let version: String? + public let coreversion: String? + public let uiversion: String? + public let devicefamily: String? + public let modelidentifier: String? + public let caps: [String]? + public let commands: [String]? + public let remoteip: String? + public let silent: Bool? + + public init( + nodeid: String, + displayname: String?, + platform: String?, + version: String?, + coreversion: String?, + uiversion: String?, + devicefamily: String?, + modelidentifier: String?, + caps: [String]?, + commands: [String]?, + remoteip: String?, + silent: Bool? + ) { + self.nodeid = nodeid + self.displayname = displayname + self.platform = platform + self.version = version + self.coreversion = coreversion + self.uiversion = uiversion + self.devicefamily = devicefamily + self.modelidentifier = modelidentifier + self.caps = caps + self.commands = commands + self.remoteip = remoteip + self.silent = silent + } + private enum CodingKeys: String, CodingKey { + case nodeid = "nodeId" + case displayname = "displayName" + case platform + case version + case coreversion = "coreVersion" + case uiversion = "uiVersion" + case devicefamily = "deviceFamily" + case modelidentifier = "modelIdentifier" + case caps + case commands + case remoteip = "remoteIp" + case silent + } +} + +public struct NodePairListParams: Codable, Sendable { +} + +public struct NodePairApproveParams: Codable, Sendable { + public let requestid: String + + public init( + requestid: String + ) { + self.requestid = requestid + } + private enum CodingKeys: String, CodingKey { + case requestid = "requestId" + } +} + +public struct NodePairRejectParams: Codable, Sendable { + public let requestid: String + + public init( + requestid: String + ) { + self.requestid = requestid + } + private enum CodingKeys: String, CodingKey { + case requestid = "requestId" + } +} + +public struct NodePairVerifyParams: Codable, Sendable { + public let nodeid: String + public let token: String + + public init( + nodeid: String, + token: String + ) { + self.nodeid = nodeid + self.token = token + } + private enum CodingKeys: String, CodingKey { + case nodeid = "nodeId" + case token + } +} + +public struct NodeRenameParams: Codable, Sendable { + public let nodeid: String + public let displayname: String + + public init( + nodeid: String, + displayname: String + ) { + self.nodeid = nodeid + self.displayname = displayname + } + private enum CodingKeys: String, CodingKey { + case nodeid = "nodeId" + case displayname = "displayName" + } +} + +public struct NodeListParams: Codable, Sendable { +} + +public struct NodeDescribeParams: Codable, Sendable { + public let nodeid: String + + public init( + nodeid: String + ) { + self.nodeid = nodeid + } + private enum CodingKeys: String, CodingKey { + case nodeid = "nodeId" + } +} + +public struct NodeInvokeParams: Codable, Sendable { + public let nodeid: String + public let command: String + public let params: AnyCodable? + public let timeoutms: Int? + public let idempotencykey: String + + public init( + nodeid: String, + command: String, + params: AnyCodable?, + timeoutms: Int?, + idempotencykey: String + ) { + self.nodeid = nodeid + self.command = command + self.params = params + self.timeoutms = timeoutms + self.idempotencykey = idempotencykey + } + private enum CodingKeys: String, CodingKey { + case nodeid = "nodeId" + case command + case params + case timeoutms = "timeoutMs" + case idempotencykey = "idempotencyKey" + } +} + +public struct NodeInvokeResultParams: Codable, Sendable { + public let id: String + public let nodeid: String + public let ok: Bool + public let payload: AnyCodable? + public let payloadjson: String? + public let error: [String: AnyCodable]? + + public init( + id: String, + nodeid: String, + ok: Bool, + payload: AnyCodable?, + payloadjson: String?, + error: [String: AnyCodable]? + ) { + self.id = id + self.nodeid = nodeid + self.ok = ok + self.payload = payload + self.payloadjson = payloadjson + self.error = error + } + private enum CodingKeys: String, CodingKey { + case id + case nodeid = "nodeId" + case ok + case payload + case payloadjson = "payloadJSON" + case error + } +} + +public struct NodeEventParams: Codable, Sendable { + public let event: String + public let payload: AnyCodable? + public let payloadjson: String? + + public init( + event: String, + payload: AnyCodable?, + payloadjson: String? + ) { + self.event = event + self.payload = payload + self.payloadjson = payloadjson + } + private enum CodingKeys: String, CodingKey { + case event + case payload + case payloadjson = "payloadJSON" + } +} + +public struct NodeInvokeRequestEvent: Codable, Sendable { + public let id: String + public let nodeid: String + public let command: String + public let paramsjson: String? + public let timeoutms: Int? + public let idempotencykey: String? + + public init( + id: String, + nodeid: String, + command: String, + paramsjson: String?, + timeoutms: Int?, + idempotencykey: String? + ) { + self.id = id + self.nodeid = nodeid + self.command = command + self.paramsjson = paramsjson + self.timeoutms = timeoutms + self.idempotencykey = idempotencykey + } + private enum CodingKeys: String, CodingKey { + case id + case nodeid = "nodeId" + case command + case paramsjson = "paramsJSON" + case timeoutms = "timeoutMs" + case idempotencykey = "idempotencyKey" + } +} + +public struct SessionsListParams: Codable, Sendable { + public let limit: Int? + public let activeminutes: Int? + public let includeglobal: Bool? + public let includeunknown: Bool? + public let includederivedtitles: Bool? + public let includelastmessage: Bool? + public let label: String? + public let spawnedby: String? + public let agentid: String? + public let search: String? + + public init( + limit: Int?, + activeminutes: Int?, + includeglobal: Bool?, + includeunknown: Bool?, + includederivedtitles: Bool?, + includelastmessage: Bool?, + label: String?, + spawnedby: String?, + agentid: String?, + search: String? + ) { + self.limit = limit + self.activeminutes = activeminutes + self.includeglobal = includeglobal + self.includeunknown = includeunknown + self.includederivedtitles = includederivedtitles + self.includelastmessage = includelastmessage + self.label = label + self.spawnedby = spawnedby + self.agentid = agentid + self.search = search + } + private enum CodingKeys: String, CodingKey { + case limit + case activeminutes = "activeMinutes" + case includeglobal = "includeGlobal" + case includeunknown = "includeUnknown" + case includederivedtitles = "includeDerivedTitles" + case includelastmessage = "includeLastMessage" + case label + case spawnedby = "spawnedBy" + case agentid = "agentId" + case search + } +} + +public struct SessionsPreviewParams: Codable, Sendable { + public let keys: [String] + public let limit: Int? + public let maxchars: Int? + + public init( + keys: [String], + limit: Int?, + maxchars: Int? + ) { + self.keys = keys + self.limit = limit + self.maxchars = maxchars + } + private enum CodingKeys: String, CodingKey { + case keys + case limit + case maxchars = "maxChars" + } +} + +public struct SessionsResolveParams: Codable, Sendable { + public let key: String? + public let sessionid: String? + public let label: String? + public let agentid: String? + public let spawnedby: String? + public let includeglobal: Bool? + public let includeunknown: Bool? + + public init( + key: String?, + sessionid: String?, + label: String?, + agentid: String?, + spawnedby: String?, + includeglobal: Bool?, + includeunknown: Bool? + ) { + self.key = key + self.sessionid = sessionid + self.label = label + self.agentid = agentid + self.spawnedby = spawnedby + self.includeglobal = includeglobal + self.includeunknown = includeunknown + } + private enum CodingKeys: String, CodingKey { + case key + case sessionid = "sessionId" + case label + case agentid = "agentId" + case spawnedby = "spawnedBy" + case includeglobal = "includeGlobal" + case includeunknown = "includeUnknown" + } +} + +public struct SessionsPatchParams: Codable, Sendable { + public let key: String + public let label: AnyCodable? + public let thinkinglevel: AnyCodable? + public let verboselevel: AnyCodable? + public let reasoninglevel: AnyCodable? + public let responseusage: AnyCodable? + public let elevatedlevel: AnyCodable? + public let exechost: AnyCodable? + public let execsecurity: AnyCodable? + public let execask: AnyCodable? + public let execnode: AnyCodable? + public let model: AnyCodable? + public let spawnedby: AnyCodable? + public let sendpolicy: AnyCodable? + public let groupactivation: AnyCodable? + + public init( + key: String, + label: AnyCodable?, + thinkinglevel: AnyCodable?, + verboselevel: AnyCodable?, + reasoninglevel: AnyCodable?, + responseusage: AnyCodable?, + elevatedlevel: AnyCodable?, + exechost: AnyCodable?, + execsecurity: AnyCodable?, + execask: AnyCodable?, + execnode: AnyCodable?, + model: AnyCodable?, + spawnedby: AnyCodable?, + sendpolicy: AnyCodable?, + groupactivation: AnyCodable? + ) { + self.key = key + self.label = label + self.thinkinglevel = thinkinglevel + self.verboselevel = verboselevel + self.reasoninglevel = reasoninglevel + self.responseusage = responseusage + self.elevatedlevel = elevatedlevel + self.exechost = exechost + self.execsecurity = execsecurity + self.execask = execask + self.execnode = execnode + self.model = model + self.spawnedby = spawnedby + self.sendpolicy = sendpolicy + self.groupactivation = groupactivation + } + private enum CodingKeys: String, CodingKey { + case key + case label + case thinkinglevel = "thinkingLevel" + case verboselevel = "verboseLevel" + case reasoninglevel = "reasoningLevel" + case responseusage = "responseUsage" + case elevatedlevel = "elevatedLevel" + case exechost = "execHost" + case execsecurity = "execSecurity" + case execask = "execAsk" + case execnode = "execNode" + case model + case spawnedby = "spawnedBy" + case sendpolicy = "sendPolicy" + case groupactivation = "groupActivation" + } +} + +public struct SessionsResetParams: Codable, Sendable { + public let key: String + + public init( + key: String + ) { + self.key = key + } + private enum CodingKeys: String, CodingKey { + case key + } +} + +public struct SessionsDeleteParams: Codable, Sendable { + public let key: String + public let deletetranscript: Bool? + + public init( + key: String, + deletetranscript: Bool? + ) { + self.key = key + self.deletetranscript = deletetranscript + } + private enum CodingKeys: String, CodingKey { + case key + case deletetranscript = "deleteTranscript" + } +} + +public struct SessionsCompactParams: Codable, Sendable { + public let key: String + public let maxlines: Int? + + public init( + key: String, + maxlines: Int? + ) { + self.key = key + self.maxlines = maxlines + } + private enum CodingKeys: String, CodingKey { + case key + case maxlines = "maxLines" + } +} + +public struct ConfigGetParams: Codable, Sendable { +} + +public struct ConfigSetParams: Codable, Sendable { + public let raw: String + public let basehash: String? + + public init( + raw: String, + basehash: String? + ) { + self.raw = raw + self.basehash = basehash + } + private enum CodingKeys: String, CodingKey { + case raw + case basehash = "baseHash" + } +} + +public struct ConfigApplyParams: Codable, Sendable { + public let raw: String + public let basehash: String? + public let sessionkey: String? + public let note: String? + public let restartdelayms: Int? + + public init( + raw: String, + basehash: String?, + sessionkey: String?, + note: String?, + restartdelayms: Int? + ) { + self.raw = raw + self.basehash = basehash + self.sessionkey = sessionkey + self.note = note + self.restartdelayms = restartdelayms + } + private enum CodingKeys: String, CodingKey { + case raw + case basehash = "baseHash" + case sessionkey = "sessionKey" + case note + case restartdelayms = "restartDelayMs" + } +} + +public struct ConfigPatchParams: Codable, Sendable { + public let raw: String + public let basehash: String? + public let sessionkey: String? + public let note: String? + public let restartdelayms: Int? + + public init( + raw: String, + basehash: String?, + sessionkey: String?, + note: String?, + restartdelayms: Int? + ) { + self.raw = raw + self.basehash = basehash + self.sessionkey = sessionkey + self.note = note + self.restartdelayms = restartdelayms + } + private enum CodingKeys: String, CodingKey { + case raw + case basehash = "baseHash" + case sessionkey = "sessionKey" + case note + case restartdelayms = "restartDelayMs" + } +} + +public struct ConfigSchemaParams: Codable, Sendable { +} + +public struct ConfigSchemaResponse: Codable, Sendable { + public let schema: AnyCodable + public let uihints: [String: AnyCodable] + public let version: String + public let generatedat: String + + public init( + schema: AnyCodable, + uihints: [String: AnyCodable], + version: String, + generatedat: String + ) { + self.schema = schema + self.uihints = uihints + self.version = version + self.generatedat = generatedat + } + private enum CodingKeys: String, CodingKey { + case schema + case uihints = "uiHints" + case version + case generatedat = "generatedAt" + } +} + +public struct WizardStartParams: Codable, Sendable { + public let mode: AnyCodable? + public let workspace: String? + + public init( + mode: AnyCodable?, + workspace: String? + ) { + self.mode = mode + self.workspace = workspace + } + private enum CodingKeys: String, CodingKey { + case mode + case workspace + } +} + +public struct WizardNextParams: Codable, Sendable { + public let sessionid: String + public let answer: [String: AnyCodable]? + + public init( + sessionid: String, + answer: [String: AnyCodable]? + ) { + self.sessionid = sessionid + self.answer = answer + } + private enum CodingKeys: String, CodingKey { + case sessionid = "sessionId" + case answer + } +} + +public struct WizardCancelParams: Codable, Sendable { + public let sessionid: String + + public init( + sessionid: String + ) { + self.sessionid = sessionid + } + private enum CodingKeys: String, CodingKey { + case sessionid = "sessionId" + } +} + +public struct WizardStatusParams: Codable, Sendable { + public let sessionid: String + + public init( + sessionid: String + ) { + self.sessionid = sessionid + } + private enum CodingKeys: String, CodingKey { + case sessionid = "sessionId" + } +} + +public struct WizardStep: Codable, Sendable { + public let id: String + public let type: AnyCodable + public let title: String? + public let message: String? + public let options: [[String: AnyCodable]]? + public let initialvalue: AnyCodable? + public let placeholder: String? + public let sensitive: Bool? + public let executor: AnyCodable? + + public init( + id: String, + type: AnyCodable, + title: String?, + message: String?, + options: [[String: AnyCodable]]?, + initialvalue: AnyCodable?, + placeholder: String?, + sensitive: Bool?, + executor: AnyCodable? + ) { + self.id = id + self.type = type + self.title = title + self.message = message + self.options = options + self.initialvalue = initialvalue + self.placeholder = placeholder + self.sensitive = sensitive + self.executor = executor + } + private enum CodingKeys: String, CodingKey { + case id + case type + case title + case message + case options + case initialvalue = "initialValue" + case placeholder + case sensitive + case executor + } +} + +public struct WizardNextResult: Codable, Sendable { + public let done: Bool + public let step: [String: AnyCodable]? + public let status: AnyCodable? + public let error: String? + + public init( + done: Bool, + step: [String: AnyCodable]?, + status: AnyCodable?, + error: String? + ) { + self.done = done + self.step = step + self.status = status + self.error = error + } + private enum CodingKeys: String, CodingKey { + case done + case step + case status + case error + } +} + +public struct WizardStartResult: Codable, Sendable { + public let sessionid: String + public let done: Bool + public let step: [String: AnyCodable]? + public let status: AnyCodable? + public let error: String? + + public init( + sessionid: String, + done: Bool, + step: [String: AnyCodable]?, + status: AnyCodable?, + error: String? + ) { + self.sessionid = sessionid + self.done = done + self.step = step + self.status = status + self.error = error + } + private enum CodingKeys: String, CodingKey { + case sessionid = "sessionId" + case done + case step + case status + case error + } +} + +public struct WizardStatusResult: Codable, Sendable { + public let status: AnyCodable + public let error: String? + + public init( + status: AnyCodable, + error: String? + ) { + self.status = status + self.error = error + } + private enum CodingKeys: String, CodingKey { + case status + case error + } +} + +public struct TalkModeParams: Codable, Sendable { + public let enabled: Bool + public let phase: String? + + public init( + enabled: Bool, + phase: String? + ) { + self.enabled = enabled + self.phase = phase + } + private enum CodingKeys: String, CodingKey { + case enabled + case phase + } +} + +public struct ChannelsStatusParams: Codable, Sendable { + public let probe: Bool? + public let timeoutms: Int? + + public init( + probe: Bool?, + timeoutms: Int? + ) { + self.probe = probe + self.timeoutms = timeoutms + } + private enum CodingKeys: String, CodingKey { + case probe + case timeoutms = "timeoutMs" + } +} + +public struct ChannelsStatusResult: Codable, Sendable { + public let ts: Int + public let channelorder: [String] + public let channellabels: [String: AnyCodable] + public let channeldetaillabels: [String: AnyCodable]? + public let channelsystemimages: [String: AnyCodable]? + public let channelmeta: [[String: AnyCodable]]? + public let channels: [String: AnyCodable] + public let channelaccounts: [String: AnyCodable] + public let channeldefaultaccountid: [String: AnyCodable] + + public init( + ts: Int, + channelorder: [String], + channellabels: [String: AnyCodable], + channeldetaillabels: [String: AnyCodable]?, + channelsystemimages: [String: AnyCodable]?, + channelmeta: [[String: AnyCodable]]?, + channels: [String: AnyCodable], + channelaccounts: [String: AnyCodable], + channeldefaultaccountid: [String: AnyCodable] + ) { + self.ts = ts + self.channelorder = channelorder + self.channellabels = channellabels + self.channeldetaillabels = channeldetaillabels + self.channelsystemimages = channelsystemimages + self.channelmeta = channelmeta + self.channels = channels + self.channelaccounts = channelaccounts + self.channeldefaultaccountid = channeldefaultaccountid + } + private enum CodingKeys: String, CodingKey { + case ts + case channelorder = "channelOrder" + case channellabels = "channelLabels" + case channeldetaillabels = "channelDetailLabels" + case channelsystemimages = "channelSystemImages" + case channelmeta = "channelMeta" + case channels + case channelaccounts = "channelAccounts" + case channeldefaultaccountid = "channelDefaultAccountId" + } +} + +public struct ChannelsLogoutParams: Codable, Sendable { + public let channel: String + public let accountid: String? + + public init( + channel: String, + accountid: String? + ) { + self.channel = channel + self.accountid = accountid + } + private enum CodingKeys: String, CodingKey { + case channel + case accountid = "accountId" + } +} + +public struct WebLoginStartParams: Codable, Sendable { + public let force: Bool? + public let timeoutms: Int? + public let verbose: Bool? + public let accountid: String? + + public init( + force: Bool?, + timeoutms: Int?, + verbose: Bool?, + accountid: String? + ) { + self.force = force + self.timeoutms = timeoutms + self.verbose = verbose + self.accountid = accountid + } + private enum CodingKeys: String, CodingKey { + case force + case timeoutms = "timeoutMs" + case verbose + case accountid = "accountId" + } +} + +public struct WebLoginWaitParams: Codable, Sendable { + public let timeoutms: Int? + public let accountid: String? + + public init( + timeoutms: Int?, + accountid: String? + ) { + self.timeoutms = timeoutms + self.accountid = accountid + } + private enum CodingKeys: String, CodingKey { + case timeoutms = "timeoutMs" + case accountid = "accountId" + } +} + +public struct AgentSummary: Codable, Sendable { + public let id: String + public let name: String? + public let identity: [String: AnyCodable]? + + public init( + id: String, + name: String?, + identity: [String: AnyCodable]? + ) { + self.id = id + self.name = name + self.identity = identity + } + private enum CodingKeys: String, CodingKey { + case id + case name + case identity + } +} + +public struct AgentsListParams: Codable, Sendable { +} + +public struct AgentsListResult: Codable, Sendable { + public let defaultid: String + public let mainkey: String + public let scope: AnyCodable + public let agents: [AgentSummary] + + public init( + defaultid: String, + mainkey: String, + scope: AnyCodable, + agents: [AgentSummary] + ) { + self.defaultid = defaultid + self.mainkey = mainkey + self.scope = scope + self.agents = agents + } + private enum CodingKeys: String, CodingKey { + case defaultid = "defaultId" + case mainkey = "mainKey" + case scope + case agents + } +} + +public struct ModelChoice: Codable, Sendable { + public let id: String + public let name: String + public let provider: String + public let contextwindow: Int? + public let reasoning: Bool? + + public init( + id: String, + name: String, + provider: String, + contextwindow: Int?, + reasoning: Bool? + ) { + self.id = id + self.name = name + self.provider = provider + self.contextwindow = contextwindow + self.reasoning = reasoning + } + private enum CodingKeys: String, CodingKey { + case id + case name + case provider + case contextwindow = "contextWindow" + case reasoning + } +} + +public struct ModelsListParams: Codable, Sendable { +} + +public struct ModelsListResult: Codable, Sendable { + public let models: [ModelChoice] + + public init( + models: [ModelChoice] + ) { + self.models = models + } + private enum CodingKeys: String, CodingKey { + case models + } +} + +public struct SkillsStatusParams: Codable, Sendable { +} + +public struct SkillsBinsParams: Codable, Sendable { +} + +public struct SkillsBinsResult: Codable, Sendable { + public let bins: [String] + + public init( + bins: [String] + ) { + self.bins = bins + } + private enum CodingKeys: String, CodingKey { + case bins + } +} + +public struct SkillsInstallParams: Codable, Sendable { + public let name: String + public let installid: String + public let timeoutms: Int? + + public init( + name: String, + installid: String, + timeoutms: Int? + ) { + self.name = name + self.installid = installid + self.timeoutms = timeoutms + } + private enum CodingKeys: String, CodingKey { + case name + case installid = "installId" + case timeoutms = "timeoutMs" + } +} + +public struct SkillsUpdateParams: Codable, Sendable { + public let skillkey: String + public let enabled: Bool? + public let apikey: String? + public let env: [String: AnyCodable]? + + public init( + skillkey: String, + enabled: Bool?, + apikey: String?, + env: [String: AnyCodable]? + ) { + self.skillkey = skillkey + self.enabled = enabled + self.apikey = apikey + self.env = env + } + private enum CodingKeys: String, CodingKey { + case skillkey = "skillKey" + case enabled + case apikey = "apiKey" + case env + } +} + +public struct CronJob: Codable, Sendable { + public let id: String + public let agentid: String? + public let name: String + public let description: String? + public let enabled: Bool + public let deleteafterrun: Bool? + public let createdatms: Int + public let updatedatms: Int + public let schedule: AnyCodable + public let sessiontarget: AnyCodable + public let wakemode: AnyCodable + public let payload: AnyCodable + public let isolation: [String: AnyCodable]? + public let state: [String: AnyCodable] + + public init( + id: String, + agentid: String?, + name: String, + description: String?, + enabled: Bool, + deleteafterrun: Bool?, + createdatms: Int, + updatedatms: Int, + schedule: AnyCodable, + sessiontarget: AnyCodable, + wakemode: AnyCodable, + payload: AnyCodable, + isolation: [String: AnyCodable]?, + state: [String: AnyCodable] + ) { + self.id = id + self.agentid = agentid + self.name = name + self.description = description + self.enabled = enabled + self.deleteafterrun = deleteafterrun + self.createdatms = createdatms + self.updatedatms = updatedatms + self.schedule = schedule + self.sessiontarget = sessiontarget + self.wakemode = wakemode + self.payload = payload + self.isolation = isolation + self.state = state + } + private enum CodingKeys: String, CodingKey { + case id + case agentid = "agentId" + case name + case description + case enabled + case deleteafterrun = "deleteAfterRun" + case createdatms = "createdAtMs" + case updatedatms = "updatedAtMs" + case schedule + case sessiontarget = "sessionTarget" + case wakemode = "wakeMode" + case payload + case isolation + case state + } +} + +public struct CronListParams: Codable, Sendable { + public let includedisabled: Bool? + + public init( + includedisabled: Bool? + ) { + self.includedisabled = includedisabled + } + private enum CodingKeys: String, CodingKey { + case includedisabled = "includeDisabled" + } +} + +public struct CronStatusParams: Codable, Sendable { +} + +public struct CronAddParams: Codable, Sendable { + public let name: String + public let agentid: AnyCodable? + public let description: String? + public let enabled: Bool? + public let deleteafterrun: Bool? + public let schedule: AnyCodable + public let sessiontarget: AnyCodable + public let wakemode: AnyCodable + public let payload: AnyCodable + public let isolation: [String: AnyCodable]? + + public init( + name: String, + agentid: AnyCodable?, + description: String?, + enabled: Bool?, + deleteafterrun: Bool?, + schedule: AnyCodable, + sessiontarget: AnyCodable, + wakemode: AnyCodable, + payload: AnyCodable, + isolation: [String: AnyCodable]? + ) { + self.name = name + self.agentid = agentid + self.description = description + self.enabled = enabled + self.deleteafterrun = deleteafterrun + self.schedule = schedule + self.sessiontarget = sessiontarget + self.wakemode = wakemode + self.payload = payload + self.isolation = isolation + } + private enum CodingKeys: String, CodingKey { + case name + case agentid = "agentId" + case description + case enabled + case deleteafterrun = "deleteAfterRun" + case schedule + case sessiontarget = "sessionTarget" + case wakemode = "wakeMode" + case payload + case isolation + } +} + +public struct CronRunLogEntry: Codable, Sendable { + public let ts: Int + public let jobid: String + public let action: String + public let status: AnyCodable? + public let error: String? + public let summary: String? + public let runatms: Int? + public let durationms: Int? + public let nextrunatms: Int? + + public init( + ts: Int, + jobid: String, + action: String, + status: AnyCodable?, + error: String?, + summary: String?, + runatms: Int?, + durationms: Int?, + nextrunatms: Int? + ) { + self.ts = ts + self.jobid = jobid + self.action = action + self.status = status + self.error = error + self.summary = summary + self.runatms = runatms + self.durationms = durationms + self.nextrunatms = nextrunatms + } + private enum CodingKeys: String, CodingKey { + case ts + case jobid = "jobId" + case action + case status + case error + case summary + case runatms = "runAtMs" + case durationms = "durationMs" + case nextrunatms = "nextRunAtMs" + } +} + +public struct LogsTailParams: Codable, Sendable { + public let cursor: Int? + public let limit: Int? + public let maxbytes: Int? + + public init( + cursor: Int?, + limit: Int?, + maxbytes: Int? + ) { + self.cursor = cursor + self.limit = limit + self.maxbytes = maxbytes + } + private enum CodingKeys: String, CodingKey { + case cursor + case limit + case maxbytes = "maxBytes" + } +} + +public struct LogsTailResult: Codable, Sendable { + public let file: String + public let cursor: Int + public let size: Int + public let lines: [String] + public let truncated: Bool? + public let reset: Bool? + + public init( + file: String, + cursor: Int, + size: Int, + lines: [String], + truncated: Bool?, + reset: Bool? + ) { + self.file = file + self.cursor = cursor + self.size = size + self.lines = lines + self.truncated = truncated + self.reset = reset + } + private enum CodingKeys: String, CodingKey { + case file + case cursor + case size + case lines + case truncated + case reset + } +} + +public struct ExecApprovalsGetParams: Codable, Sendable { +} + +public struct ExecApprovalsSetParams: Codable, Sendable { + public let file: [String: AnyCodable] + public let basehash: String? + + public init( + file: [String: AnyCodable], + basehash: String? + ) { + self.file = file + self.basehash = basehash + } + private enum CodingKeys: String, CodingKey { + case file + case basehash = "baseHash" + } +} + +public struct ExecApprovalsNodeGetParams: Codable, Sendable { + public let nodeid: String + + public init( + nodeid: String + ) { + self.nodeid = nodeid + } + private enum CodingKeys: String, CodingKey { + case nodeid = "nodeId" + } +} + +public struct ExecApprovalsNodeSetParams: Codable, Sendable { + public let nodeid: String + public let file: [String: AnyCodable] + public let basehash: String? + + public init( + nodeid: String, + file: [String: AnyCodable], + basehash: String? + ) { + self.nodeid = nodeid + self.file = file + self.basehash = basehash + } + private enum CodingKeys: String, CodingKey { + case nodeid = "nodeId" + case file + case basehash = "baseHash" + } +} + +public struct ExecApprovalsSnapshot: Codable, Sendable { + public let path: String + public let exists: Bool + public let hash: String + public let file: [String: AnyCodable] + + public init( + path: String, + exists: Bool, + hash: String, + file: [String: AnyCodable] + ) { + self.path = path + self.exists = exists + self.hash = hash + self.file = file + } + private enum CodingKeys: String, CodingKey { + case path + case exists + case hash + case file + } +} + +public struct ExecApprovalRequestParams: Codable, Sendable { + public let id: String? + public let command: String + public let cwd: AnyCodable? + public let host: AnyCodable? + public let security: AnyCodable? + public let ask: AnyCodable? + public let agentid: AnyCodable? + public let resolvedpath: AnyCodable? + public let sessionkey: AnyCodable? + public let timeoutms: Int? + + public init( + id: String?, + command: String, + cwd: AnyCodable?, + host: AnyCodable?, + security: AnyCodable?, + ask: AnyCodable?, + agentid: AnyCodable?, + resolvedpath: AnyCodable?, + sessionkey: AnyCodable?, + timeoutms: Int? + ) { + self.id = id + self.command = command + self.cwd = cwd + self.host = host + self.security = security + self.ask = ask + self.agentid = agentid + self.resolvedpath = resolvedpath + self.sessionkey = sessionkey + self.timeoutms = timeoutms + } + private enum CodingKeys: String, CodingKey { + case id + case command + case cwd + case host + case security + case ask + case agentid = "agentId" + case resolvedpath = "resolvedPath" + case sessionkey = "sessionKey" + case timeoutms = "timeoutMs" + } +} + +public struct ExecApprovalResolveParams: Codable, Sendable { + public let id: String + public let decision: String + + public init( + id: String, + decision: String + ) { + self.id = id + self.decision = decision + } + private enum CodingKeys: String, CodingKey { + case id + case decision + } +} + +public struct DevicePairListParams: Codable, Sendable { +} + +public struct DevicePairApproveParams: Codable, Sendable { + public let requestid: String + + public init( + requestid: String + ) { + self.requestid = requestid + } + private enum CodingKeys: String, CodingKey { + case requestid = "requestId" + } +} + +public struct DevicePairRejectParams: Codable, Sendable { + public let requestid: String + + public init( + requestid: String + ) { + self.requestid = requestid + } + private enum CodingKeys: String, CodingKey { + case requestid = "requestId" + } +} + +public struct DeviceTokenRotateParams: Codable, Sendable { + public let deviceid: String + public let role: String + public let scopes: [String]? + + public init( + deviceid: String, + role: String, + scopes: [String]? + ) { + self.deviceid = deviceid + self.role = role + self.scopes = scopes + } + private enum CodingKeys: String, CodingKey { + case deviceid = "deviceId" + case role + case scopes + } +} + +public struct DeviceTokenRevokeParams: Codable, Sendable { + public let deviceid: String + public let role: String + + public init( + deviceid: String, + role: String + ) { + self.deviceid = deviceid + self.role = role + } + private enum CodingKeys: String, CodingKey { + case deviceid = "deviceId" + case role + } +} + +public struct DevicePairRequestedEvent: Codable, Sendable { + public let requestid: String + public let deviceid: String + public let publickey: String + public let displayname: String? + public let platform: String? + public let clientid: String? + public let clientmode: String? + public let role: String? + public let roles: [String]? + public let scopes: [String]? + public let remoteip: String? + public let silent: Bool? + public let isrepair: Bool? + public let ts: Int + + public init( + requestid: String, + deviceid: String, + publickey: String, + displayname: String?, + platform: String?, + clientid: String?, + clientmode: String?, + role: String?, + roles: [String]?, + scopes: [String]?, + remoteip: String?, + silent: Bool?, + isrepair: Bool?, + ts: Int + ) { + self.requestid = requestid + self.deviceid = deviceid + self.publickey = publickey + self.displayname = displayname + self.platform = platform + self.clientid = clientid + self.clientmode = clientmode + self.role = role + self.roles = roles + self.scopes = scopes + self.remoteip = remoteip + self.silent = silent + self.isrepair = isrepair + self.ts = ts + } + private enum CodingKeys: String, CodingKey { + case requestid = "requestId" + case deviceid = "deviceId" + case publickey = "publicKey" + case displayname = "displayName" + case platform + case clientid = "clientId" + case clientmode = "clientMode" + case role + case roles + case scopes + case remoteip = "remoteIp" + case silent + case isrepair = "isRepair" + case ts + } +} + +public struct DevicePairResolvedEvent: Codable, Sendable { + public let requestid: String + public let deviceid: String + public let decision: String + public let ts: Int + + public init( + requestid: String, + deviceid: String, + decision: String, + ts: Int + ) { + self.requestid = requestid + self.deviceid = deviceid + self.decision = decision + self.ts = ts + } + private enum CodingKeys: String, CodingKey { + case requestid = "requestId" + case deviceid = "deviceId" + case decision + case ts + } +} + +public struct ChatHistoryParams: Codable, Sendable { + public let sessionkey: String + public let limit: Int? + + public init( + sessionkey: String, + limit: Int? + ) { + self.sessionkey = sessionkey + self.limit = limit + } + private enum CodingKeys: String, CodingKey { + case sessionkey = "sessionKey" + case limit + } +} + +public struct ChatSendParams: Codable, Sendable { + public let sessionkey: String + public let message: String + public let thinking: String? + public let deliver: Bool? + public let attachments: [AnyCodable]? + public let timeoutms: Int? + public let idempotencykey: String + + public init( + sessionkey: String, + message: String, + thinking: String?, + deliver: Bool?, + attachments: [AnyCodable]?, + timeoutms: Int?, + idempotencykey: String + ) { + self.sessionkey = sessionkey + self.message = message + self.thinking = thinking + self.deliver = deliver + self.attachments = attachments + self.timeoutms = timeoutms + self.idempotencykey = idempotencykey + } + private enum CodingKeys: String, CodingKey { + case sessionkey = "sessionKey" + case message + case thinking + case deliver + case attachments + case timeoutms = "timeoutMs" + case idempotencykey = "idempotencyKey" + } +} + +public struct ChatAbortParams: Codable, Sendable { + public let sessionkey: String + public let runid: String? + + public init( + sessionkey: String, + runid: String? + ) { + self.sessionkey = sessionkey + self.runid = runid + } + private enum CodingKeys: String, CodingKey { + case sessionkey = "sessionKey" + case runid = "runId" + } +} + +public struct ChatInjectParams: Codable, Sendable { + public let sessionkey: String + public let message: String + public let label: String? + + public init( + sessionkey: String, + message: String, + label: String? + ) { + self.sessionkey = sessionkey + self.message = message + self.label = label + } + private enum CodingKeys: String, CodingKey { + case sessionkey = "sessionKey" + case message + case label + } +} + +public struct ChatEvent: Codable, Sendable { + public let runid: String + public let sessionkey: String + public let seq: Int + public let state: AnyCodable + public let message: AnyCodable? + public let errormessage: String? + public let usage: AnyCodable? + public let stopreason: String? + + public init( + runid: String, + sessionkey: String, + seq: Int, + state: AnyCodable, + message: AnyCodable?, + errormessage: String?, + usage: AnyCodable?, + stopreason: String? + ) { + self.runid = runid + self.sessionkey = sessionkey + self.seq = seq + self.state = state + self.message = message + self.errormessage = errormessage + self.usage = usage + self.stopreason = stopreason + } + private enum CodingKeys: String, CodingKey { + case runid = "runId" + case sessionkey = "sessionKey" + case seq + case state + case message + case errormessage = "errorMessage" + case usage + case stopreason = "stopReason" + } +} + +public struct UpdateRunParams: Codable, Sendable { + public let sessionkey: String? + public let note: String? + public let restartdelayms: Int? + public let timeoutms: Int? + + public init( + sessionkey: String?, + note: String?, + restartdelayms: Int?, + timeoutms: Int? + ) { + self.sessionkey = sessionkey + self.note = note + self.restartdelayms = restartdelayms + self.timeoutms = timeoutms + } + private enum CodingKeys: String, CodingKey { + case sessionkey = "sessionKey" + case note + case restartdelayms = "restartDelayMs" + case timeoutms = "timeoutMs" + } +} + +public struct TickEvent: Codable, Sendable { + public let ts: Int + + public init( + ts: Int + ) { + self.ts = ts + } + private enum CodingKeys: String, CodingKey { + case ts + } +} + +public struct ShutdownEvent: Codable, Sendable { + public let reason: String + public let restartexpectedms: Int? + + public init( + reason: String, + restartexpectedms: Int? + ) { + self.reason = reason + self.restartexpectedms = restartexpectedms + } + private enum CodingKeys: String, CodingKey { + case reason + case restartexpectedms = "restartExpectedMs" + } +} + +public enum GatewayFrame: Codable, Sendable { + case req(RequestFrame) + case res(ResponseFrame) + case event(EventFrame) + case unknown(type: String, raw: [String: AnyCodable]) + + private enum CodingKeys: String, CodingKey { + case type + } + + public init(from decoder: Decoder) throws { + let typeContainer = try decoder.container(keyedBy: CodingKeys.self) + let type = try typeContainer.decode(String.self, forKey: .type) + switch type { + case "req": + self = .req(try RequestFrame(from: decoder)) + case "res": + self = .res(try ResponseFrame(from: decoder)) + case "event": + self = .event(try EventFrame(from: decoder)) + default: + let container = try decoder.singleValueContainer() + let raw = try container.decode([String: AnyCodable].self) + self = .unknown(type: type, raw: raw) + } + } + + public func encode(to encoder: Encoder) throws { + switch self { + case .req(let v): try v.encode(to: encoder) + case .res(let v): try v.encode(to: encoder) + case .event(let v): try v.encode(to: encoder) + case .unknown(_, let raw): + var container = encoder.singleValueContainer() + try container.encode(raw) + } + } + +} diff --git a/apps/macos/Sources/ClawdbotProtocol/WizardHelpers.swift b/apps/shared/ClawdbotKit/Sources/ClawdbotProtocol/WizardHelpers.swift similarity index 100% rename from apps/macos/Sources/ClawdbotProtocol/WizardHelpers.swift rename to apps/shared/ClawdbotKit/Sources/ClawdbotProtocol/WizardHelpers.swift diff --git a/apps/shared/ClawdbotKit/Tests/ClawdbotKitTests/GatewayNodeSessionTests.swift b/apps/shared/ClawdbotKit/Tests/ClawdbotKitTests/GatewayNodeSessionTests.swift new file mode 100644 index 000000000..0fc688f63 --- /dev/null +++ b/apps/shared/ClawdbotKit/Tests/ClawdbotKitTests/GatewayNodeSessionTests.swift @@ -0,0 +1,56 @@ +import Foundation +import Testing +@testable import ClawdbotKit +import ClawdbotProtocol + +struct GatewayNodeSessionTests { + @Test + func invokeWithTimeoutReturnsUnderlyingResponseBeforeTimeout() async { + let request = BridgeInvokeRequest(id: "1", command: "x", paramsJSON: nil) + let response = await GatewayNodeSession.invokeWithTimeout( + request: request, + timeoutMs: 50, + onInvoke: { req in + #expect(req.id == "1") + return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: "{}", error: nil) + } + ) + + #expect(response.ok == true) + #expect(response.error == nil) + #expect(response.payloadJSON == "{}") + } + + @Test + func invokeWithTimeoutReturnsTimeoutError() async { + let request = BridgeInvokeRequest(id: "abc", command: "x", paramsJSON: nil) + let response = await GatewayNodeSession.invokeWithTimeout( + request: request, + timeoutMs: 10, + onInvoke: { _ in + try? await Task.sleep(nanoseconds: 200_000_000) // 200ms + return BridgeInvokeResponse(id: "abc", ok: true, payloadJSON: "{}", error: nil) + } + ) + + #expect(response.ok == false) + #expect(response.error?.code == .unavailable) + #expect(response.error?.message.contains("timed out") == true) + } + + @Test + func invokeWithTimeoutZeroDisablesTimeout() async { + let request = BridgeInvokeRequest(id: "1", command: "x", paramsJSON: nil) + let response = await GatewayNodeSession.invokeWithTimeout( + request: request, + timeoutMs: 0, + onInvoke: { req in + try? await Task.sleep(nanoseconds: 5_000_000) + return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: nil, error: nil) + } + ) + + #expect(response.ok == true) + #expect(response.error == nil) + } +} diff --git a/dist/control-ui/assets/index-08nzABV3.css b/dist/control-ui/assets/index-08nzABV3.css new file mode 100644 index 000000000..58e39560c --- /dev/null +++ b/dist/control-ui/assets/index-08nzABV3.css @@ -0,0 +1 @@ +@import"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap";:root{--bg: #0c0d12;--bg-accent: #0d0e14;--bg-elevated: #181a21;--bg-hover: #252830;--bg-muted: #252830;--card: #13151c;--card-foreground: #f8fafc;--card-highlight: rgba(255, 255, 255, .04);--popover: #13151c;--popover-foreground: #f8fafc;--panel: #0c0d12;--panel-strong: #181a21;--panel-hover: #252830;--chrome: rgba(12, 13, 18, .95);--chrome-strong: rgba(12, 13, 18, .98);--text: #f8fafc;--text-strong: #ffffff;--chat-text: #f8fafc;--muted: #94a3b8;--muted-strong: #64748b;--muted-foreground: #94a3b8;--border: #333842;--border-strong: #454d5c;--border-hover: #5a6373;--input: #333842;--ring: #ff4d4d;--accent: #ff4d4d;--accent-hover: #ff6666;--accent-muted: #ff4d4d;--accent-subtle: rgba(255, 77, 77, .12);--accent-foreground: #f8fafc;--primary: #ff4d4d;--primary-foreground: #ffffff;--secondary: #252830;--secondary-foreground: #f8fafc;--accent-2: #3b82f6;--accent-2-muted: rgba(59, 130, 246, .7);--ok: #22c55e;--ok-muted: rgba(34, 197, 94, .7);--ok-subtle: rgba(34, 197, 94, .1);--destructive: #ef4444;--destructive-foreground: #fafafa;--warn: #eab308;--warn-muted: rgba(234, 179, 8, .7);--warn-subtle: rgba(234, 179, 8, .1);--danger: #ef4444;--danger-muted: rgba(239, 68, 68, .7);--danger-subtle: rgba(239, 68, 68, .1);--info: #3b82f6;--focus: rgba(255, 77, 77, .2);--focus-ring: 0 0 0 2px var(--bg), 0 0 0 4px var(--ring);--grid-line: rgba(255, 255, 255, .03);--theme-switch-x: 50%;--theme-switch-y: 50%;--mono: "JetBrains Mono", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, monospace;--font-body: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;--font-display: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, .05);--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, .1), 0 2px 4px -2px rgba(0, 0, 0, .1);--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, .1), 0 4px 6px -4px rgba(0, 0, 0, .1);--shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, .1), 0 8px 10px -6px rgba(0, 0, 0, .1);--radius-sm: 4px;--radius-md: 6px;--radius-lg: 8px;--radius-xl: 12px;--radius-full: 9999px;--radius: 6px;--ease-out: cubic-bezier(.16, 1, .3, 1);--ease-in-out: cubic-bezier(.4, 0, .2, 1);--duration-fast: .15s;--duration-normal: .2s;--duration-slow: .3s;color-scheme:dark}:root[data-theme=light]{--bg: #f8f8f7;--bg-accent: #f3f2f0;--bg-elevated: #ffffff;--bg-hover: #eae8e6;--bg-muted: #eae8e6;--bg-content: #f0efed;--card: #ffffff;--card-foreground: #1c1917;--card-highlight: rgba(0, 0, 0, .04);--popover: #ffffff;--popover-foreground: #1c1917;--panel: #f8f8f7;--panel-strong: #f0efed;--panel-hover: #e5e3e1;--chrome: rgba(248, 248, 247, .95);--chrome-strong: rgba(248, 248, 247, .98);--text: #44403c;--text-strong: #292524;--chat-text: #44403c;--muted: #5c5856;--muted-strong: #44403c;--muted-foreground: #5c5856;--border: #e0dedc;--border-strong: #d6d3d1;--border-hover: #a8a5a0;--input: #e0dedc;--accent: #b91c1c;--accent-hover: #dc2626;--accent-muted: #b91c1c;--accent-subtle: rgba(185, 28, 28, .18);--accent-foreground: #ffffff;--primary: #b91c1c;--primary-foreground: #ffffff;--secondary: #eae8e6;--secondary-foreground: #44403c;--ok: #15803d;--ok-muted: rgba(21, 128, 61, .75);--ok-subtle: rgba(21, 128, 61, .12);--destructive: #b91c1c;--destructive-foreground: #fafafa;--warn: #a16207;--warn-muted: rgba(161, 98, 7, .75);--warn-subtle: rgba(161, 98, 7, .12);--danger: #b91c1c;--danger-muted: rgba(185, 28, 28, .75);--danger-subtle: rgba(185, 28, 28, .12);--info: #1d4ed8;--focus: rgba(185, 28, 28, .25);--grid-line: rgba(0, 0, 0, .06);color-scheme:light}*{box-sizing:border-box}html,body{height:100%}body{margin:0;font:400 14px/1.5 var(--font-body);letter-spacing:-.011em;background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}@keyframes theme-circle-transition{0%{clip-path:circle(0% at var(--theme-switch-x, 50%) var(--theme-switch-y, 50%))}to{clip-path:circle(150% at var(--theme-switch-x, 50%) var(--theme-switch-y, 50%))}}html.theme-transition{view-transition-name:theme}html.theme-transition::view-transition-old(theme){mix-blend-mode:normal;animation:none;z-index:1}html.theme-transition::view-transition-new(theme){mix-blend-mode:normal;z-index:2;animation:theme-circle-transition .4s var(--ease-out) forwards}@media(prefers-reduced-motion:reduce){html.theme-transition::view-transition-old(theme),html.theme-transition::view-transition-new(theme){animation:none!important}}clawdbot-app{display:block;position:relative;z-index:1;min-height:100vh}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}button,input,textarea,select{font:inherit;color:inherit}::selection{background:var(--accent-subtle);color:var(--text-strong)}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--border);border-radius:var(--radius-full)}::-webkit-scrollbar-thumb:hover{background:var(--border-strong)}@keyframes rise{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}@keyframes fade-in{0%{opacity:0}to{opacity:1}}@keyframes scale-in{0%{opacity:0;transform:scale(.96)}to{opacity:1;transform:scale(1)}}@keyframes dashboard-enter{0%{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}@keyframes shimmer{0%{background-position:-200% 0}to{background-position:200% 0}}:focus-visible{outline:none;box-shadow:var(--focus-ring)}.shell{--shell-pad: 16px;--shell-gap: 16px;--shell-nav-width: 220px;--shell-topbar-height: 56px;--shell-focus-duration: .2s;--shell-focus-ease: var(--ease-out);height:100vh;display:grid;grid-template-columns:var(--shell-nav-width) minmax(0,1fr);grid-template-rows:var(--shell-topbar-height) 1fr;grid-template-areas:"topbar topbar" "nav content";gap:0;animation:dashboard-enter .4s var(--ease-out);transition:grid-template-columns var(--shell-focus-duration) var(--shell-focus-ease);overflow:hidden}@supports (height: 100dvh){.shell{height:100dvh}}.shell--chat{min-height:100vh;height:100vh;overflow:hidden}@supports (height: 100dvh){.shell--chat{height:100dvh}}.shell--nav-collapsed,.shell--chat-focus{grid-template-columns:0px minmax(0,1fr)}.shell--onboarding{grid-template-rows:0 1fr}.shell--onboarding .topbar{display:none}.shell--onboarding .content{padding-top:0}.shell--chat-focus .content{padding-top:0;gap:0}.topbar{grid-area:topbar;position:sticky;top:0;z-index:40;display:flex;justify-content:space-between;align-items:center;gap:16px;padding:0 20px;height:var(--shell-topbar-height);border-bottom:1px solid var(--border);background:var(--bg)}.topbar-left{display:flex;align-items:center;gap:12px}.topbar .nav-collapse-toggle{width:36px;height:36px;margin-bottom:0}.topbar .nav-collapse-toggle__icon{width:20px;height:20px}.topbar .nav-collapse-toggle__icon svg{width:20px;height:20px}.brand{display:flex;align-items:center;gap:10px}.brand-logo{width:28px;height:28px;flex-shrink:0}.brand-logo img{width:100%;height:100%;object-fit:contain}.brand-text{display:flex;flex-direction:column;gap:1px}.brand-title{font-size:15px;font-weight:600;letter-spacing:-.02em;line-height:1.1;color:var(--text-strong)}.brand-sub{font-size:11px;font-weight:500;color:var(--muted);letter-spacing:.02em;line-height:1}.topbar-status{display:flex;align-items:center;gap:8px}.topbar-status .pill{padding:6px 10px;gap:6px;font-size:12px;font-weight:500;height:32px;box-sizing:border-box}.topbar-status .pill .mono{display:flex;align-items:center;line-height:1;margin-top:0}.topbar-status .statusDot{width:6px;height:6px}.topbar-status .theme-toggle{--theme-item: 24px;--theme-gap: 2px;--theme-pad: 3px}.topbar-status .theme-icon{width:12px;height:12px}.nav{grid-area:nav;overflow-y:auto;overflow-x:hidden;padding:16px 12px;border-right:1px solid var(--border);background:var(--bg);transition:width var(--shell-focus-duration) var(--shell-focus-ease),padding var(--shell-focus-duration) var(--shell-focus-ease),opacity var(--shell-focus-duration) var(--shell-focus-ease);min-height:0}.shell--chat-focus .nav{width:0;padding:0;border-width:0;overflow:hidden;pointer-events:none;opacity:0}.nav--collapsed{width:0;min-width:0;padding:0;overflow:hidden;border:none;opacity:0;pointer-events:none}.nav-collapse-toggle{width:32px;height:32px;display:flex;align-items:center;justify-content:center;background:transparent;border:1px solid transparent;border-radius:var(--radius-md);cursor:pointer;transition:background var(--duration-fast) ease,border-color var(--duration-fast) ease;margin-bottom:16px}.nav-collapse-toggle:hover{background:var(--bg-hover);border-color:var(--border)}.nav-collapse-toggle__icon{display:flex;align-items:center;justify-content:center;width:18px;height:18px;color:var(--muted);transition:color var(--duration-fast) ease}.nav-collapse-toggle__icon svg{width:18px;height:18px;stroke:currentColor;fill:none;stroke-width:1.5px;stroke-linecap:round;stroke-linejoin:round}.nav-collapse-toggle:hover .nav-collapse-toggle__icon{color:var(--text)}.nav-group{margin-bottom:20px;display:grid;gap:2px}.nav-group:last-child{margin-bottom:0}.nav-group__items{display:grid;gap:1px}.nav-group--collapsed .nav-group__items{display:none}.nav-label{display:flex;align-items:center;justify-content:space-between;gap:8px;width:100%;padding:6px 10px;font-size:11px;font-weight:500;color:var(--muted);margin-bottom:4px;background:transparent;border:none;cursor:pointer;text-align:left;border-radius:var(--radius-sm);transition:color var(--duration-fast) ease,background var(--duration-fast) ease}.nav-label:hover{color:var(--text);background:var(--bg-hover)}.nav-label--static{cursor:default}.nav-label--static:hover{color:var(--muted);background:transparent}.nav-label__text{flex:1}.nav-label__chevron{font-size:10px;opacity:.5;transition:transform var(--duration-fast) ease}.nav-group--collapsed .nav-label__chevron{transform:rotate(-90deg)}.nav-item{position:relative;display:flex;align-items:center;justify-content:flex-start;gap:10px;padding:8px 10px;border-radius:var(--radius-md);border:1px solid transparent;background:transparent;color:var(--muted);cursor:pointer;text-decoration:none;transition:border-color var(--duration-fast) ease,background var(--duration-fast) ease,color var(--duration-fast) ease}.nav-item__icon{width:16px;height:16px;display:flex;align-items:center;justify-content:center;flex-shrink:0;opacity:.7;transition:opacity var(--duration-fast) ease}.nav-item__icon svg{width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:1.5px;stroke-linecap:round;stroke-linejoin:round}.nav-item__text{font-size:13px;font-weight:500;white-space:nowrap}.nav-item:hover{color:var(--text);background:var(--bg-hover);text-decoration:none}.nav-item:hover .nav-item__icon{opacity:1}.nav-item.active{color:var(--text-strong);background:var(--accent-subtle)}.nav-item.active .nav-item__icon{opacity:1;color:var(--accent)}.content{grid-area:content;padding:8px 8px 24px;display:flex;flex-direction:column;gap:20px;min-height:0;overflow-y:auto;overflow-x:hidden}:root[data-theme=light] .content{background:var(--bg-content)}.content--chat{overflow:hidden;padding-bottom:0}.content-header{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;padding:4px 8px;overflow:hidden;transform-origin:top center;transition:opacity var(--shell-focus-duration) var(--shell-focus-ease),transform var(--shell-focus-duration) var(--shell-focus-ease),max-height var(--shell-focus-duration) var(--shell-focus-ease),padding var(--shell-focus-duration) var(--shell-focus-ease);max-height:80px}.shell--chat-focus .content-header{opacity:0;transform:translateY(-8px);max-height:0px;padding:0;pointer-events:none}.page-title{font-size:24px;font-weight:600;letter-spacing:-.02em;line-height:1.2;color:var(--text-strong)}.page-sub{color:var(--muted);font-size:13px;font-weight:400;margin-top:4px}.page-meta{display:flex;gap:8px}.content--chat .content-header{flex-direction:row;align-items:center;justify-content:space-between;gap:16px}.content--chat .content-header>div:first-child{text-align:left}.content--chat .page-meta{justify-content:flex-start}.content--chat .chat-controls{flex-shrink:0}.grid{display:grid;gap:16px}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.stat-grid{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(140px,1fr))}.note-grid{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(200px,1fr))}.row{display:flex;gap:10px;align-items:center}.stack{display:grid;gap:12px}.filters{display:flex;flex-wrap:wrap;gap:8px;align-items:center}@media(max-width:1100px){.shell{--shell-pad: 12px;--shell-gap: 12px;grid-template-columns:1fr;grid-template-rows:auto auto 1fr;grid-template-areas:"topbar" "nav" "content"}.nav{position:static;max-height:none;display:flex;gap:6px;overflow-x:auto;border-right:none;border-bottom:1px solid var(--border);padding:10px 14px;background:var(--bg)}.nav-group{grid-auto-flow:column;grid-template-columns:repeat(auto-fit,minmax(100px,1fr));margin-bottom:0}.grid-cols-2,.grid-cols-3{grid-template-columns:1fr}.topbar{position:static;padding:12px 14px;gap:10px}.topbar-status{flex-wrap:wrap}.table-head,.table-row,.list-item{grid-template-columns:1fr}}@media(max-width:1100px){.nav{display:flex;flex-direction:row;flex-wrap:nowrap;gap:4px;padding:10px 14px;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none}.nav::-webkit-scrollbar{display:none}.nav-group,.nav-group__items{display:contents}.nav-label{display:none}.nav-group--collapsed .nav-group__items{display:contents}.nav-item{padding:8px 14px;font-size:13px;border-radius:var(--radius-md);white-space:nowrap;flex-shrink:0}}@media(max-width:600px){.shell{--shell-pad: 8px;--shell-gap: 8px}.topbar{padding:10px 12px;gap:8px;flex-direction:row;flex-wrap:wrap;justify-content:space-between;align-items:center}.brand{flex:1;min-width:0}.brand-title{font-size:14px}.brand-sub{display:none}.topbar-status{gap:6px;width:auto;flex-wrap:nowrap}.topbar-status .pill{padding:4px 8px;font-size:11px;gap:4px}.topbar-status .pill .mono{display:none}.topbar-status .pill span:nth-child(2){display:none}.nav{padding:8px 10px;gap:4px;-webkit-overflow-scrolling:touch;scrollbar-width:none}.nav::-webkit-scrollbar{display:none}.nav-group{display:contents}.nav-label{display:none}.nav-item{padding:6px 10px;font-size:12px;border-radius:var(--radius-md);white-space:nowrap;flex-shrink:0}.content-header{display:none}.content{padding:4px 4px 16px;gap:12px}.card{padding:12px;border-radius:var(--radius-md)}.card-title{font-size:13px}.stat-grid{gap:8px;grid-template-columns:repeat(2,1fr)}.stat{padding:10px;border-radius:var(--radius-md)}.stat-label{font-size:11px}.stat-value{font-size:18px}.note-grid{grid-template-columns:1fr;gap:8px}.form-grid{grid-template-columns:1fr;gap:10px}.field input,.field textarea,.field select{padding:8px 10px;border-radius:var(--radius-md);font-size:14px}.btn{padding:8px 12px;font-size:12px}.pill{padding:4px 10px;font-size:12px}.chat-header{flex-direction:column;align-items:stretch;gap:8px}.chat-header__left{flex-direction:column;align-items:stretch}.chat-header__right{justify-content:space-between}.chat-session{min-width:unset;width:100%}.chat-thread{margin-top:8px;padding:12px 8px}.chat-msg{max-width:90%}.chat-bubble{padding:8px 12px;border-radius:var(--radius-md)}.chat-compose{gap:8px}.chat-compose__field textarea{min-height:60px;padding:8px 10px;border-radius:var(--radius-md);font-size:14px}.log-stream{border-radius:var(--radius-md);max-height:380px}.log-row{grid-template-columns:1fr;gap:4px;padding:8px}.log-time{font-size:10px}.log-level{font-size:9px}.log-subsystem{font-size:11px}.log-message{font-size:12px}.list-item{padding:10px;border-radius:var(--radius-md)}.list-title{font-size:13px}.list-sub{font-size:11px}.code-block{padding:8px;border-radius:var(--radius-md);font-size:11px}.theme-toggle{--theme-item: 24px;--theme-gap: 2px;--theme-pad: 3px}.theme-icon{width:12px;height:12px}}@media(max-width:400px){.shell{--shell-pad: 4px}.topbar{padding:8px 10px}.brand-title{font-size:13px}.nav{padding:6px 8px}.nav-item{padding:6px 8px;font-size:11px}.content{padding:4px 4px 12px;gap:10px}.card{padding:10px}.stat{padding:8px}.stat-value{font-size:16px}.chat-bubble{padding:8px 10px}.chat-compose__field textarea{min-height:52px;padding:8px 10px;font-size:13px}.btn{padding:6px 10px;font-size:11px}.topbar-status .pill{padding:3px 6px;font-size:10px}.theme-toggle{--theme-item: 22px;--theme-gap: 2px;--theme-pad: 2px}.theme-icon{width:11px;height:11px}}.chat{position:relative;display:flex;flex-direction:column;flex:1 1 0;height:100%;min-height:0;overflow:hidden;background:transparent!important;border:none!important;box-shadow:none!important}.chat-header{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:nowrap;flex-shrink:0;padding-bottom:12px;margin-bottom:12px;background:transparent}.chat-header__left{display:flex;align-items:center;gap:12px;flex-wrap:wrap;min-width:0}.chat-session{min-width:180px}.chat-thread{flex:1 1 0;overflow-y:auto;overflow-x:hidden;padding:12px 4px;margin:0 -4px;min-height:0;border-radius:12px;background:transparent}.chat-focus-exit{position:absolute;top:12px;right:12px;z-index:100;width:32px;height:32px;border-radius:50%;border:1px solid var(--border);background:var(--panel);color:var(--muted);font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background .15s ease-out,color .15s ease-out,border-color .15s ease-out;box-shadow:0 4px 12px #0003}.chat-focus-exit:hover{background:var(--panel-strong);color:var(--text);border-color:var(--accent)}.chat-focus-exit svg{width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:2px;stroke-linecap:round;stroke-linejoin:round}.chat-compose{position:sticky;bottom:0;flex-shrink:0;display:flex;align-items:stretch;gap:12px;margin-top:auto;padding:12px 4px 4px;background:linear-gradient(to bottom,transparent,var(--bg) 20%);z-index:10}:root[data-theme=light] .chat-compose{background:linear-gradient(to bottom,transparent,var(--bg-content) 20%)}.chat-compose__field{flex:1 1 auto;min-width:0;display:flex;align-items:stretch}.chat-compose__field>span{display:none}.chat-compose .chat-compose__field textarea{width:100%;height:40px;min-height:40px;max-height:150px;padding:9px 12px;border-radius:8px;resize:vertical;white-space:pre-wrap;font-family:var(--font-body);font-size:14px;line-height:1.45}.chat-compose__field textarea:disabled{opacity:.7;cursor:not-allowed}.chat-compose__actions{flex-shrink:0;display:flex;align-items:stretch;gap:8px}.chat-compose .chat-compose__actions .btn{padding:0 16px;font-size:13px;height:40px;min-height:40px;max-height:40px;line-height:1;white-space:nowrap;box-sizing:border-box}.chat-controls{display:flex;align-items:center;justify-content:flex-start;gap:12px;flex-wrap:wrap}.chat-controls__session{min-width:140px}.chat-controls__thinking{display:flex;align-items:center;gap:6px;font-size:13px}.btn--icon{padding:8px!important;min-width:36px;height:36px;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--border);background:#ffffff0f}.chat-controls__separator{color:#fff6;font-size:18px;margin:0 8px;font-weight:300}:root[data-theme=light] .chat-controls__separator{color:#1018284d}.btn--icon:hover{background:#ffffff1f;border-color:#fff3}:root[data-theme=light] .btn--icon{background:#fff;border-color:var(--border);box-shadow:0 1px 2px #1018280d;color:var(--muted)}:root[data-theme=light] .btn--icon:hover{background:#fff;border-color:var(--border-strong);color:var(--text)}.btn--icon svg{display:block;width:18px;height:18px;stroke:currentColor;fill:none;stroke-width:1.5px;stroke-linecap:round;stroke-linejoin:round}.chat-controls__session select{padding:6px 10px;font-size:13px}.chat-controls__thinking{display:flex;align-items:center;gap:4px;font-size:12px;padding:4px 10px;background:#ffffff0a;border-radius:6px;border:1px solid var(--border)}:root[data-theme=light] .chat-controls__thinking{background:#ffffffe6;border-color:#10182826}@media(max-width:640px){.chat-session{min-width:140px}.chat-compose{grid-template-columns:1fr}.chat-controls{flex-wrap:wrap;gap:8px}.chat-controls__session{min-width:120px}}.chat-thinking{margin-bottom:10px;padding:10px 12px;border-radius:10px;border:1px dashed rgba(255,255,255,.18);background:#ffffff0a;color:var(--muted);font-size:12px;line-height:1.4}:root[data-theme=light] .chat-thinking{border-color:#10182840;background:#1018280a}.chat-text{font-size:14px;line-height:1.5;word-wrap:break-word;overflow-wrap:break-word}.chat-text :where(p+p,p+ul,p+ol,p+pre,p+blockquote){margin-top:.75em}.chat-text :where(ul,ol){padding-left:1.5em}.chat-text :where(a){color:var(--accent);text-decoration:underline;text-underline-offset:2px}.chat-text :where(a:hover){opacity:.8}.chat-text :where(:not(pre)>code){background:#00000026;padding:.15em .4em;border-radius:4px}.chat-text :where(pre){background:#00000026;border-radius:6px;padding:10px 12px;overflow-x:auto}.chat-text :where(pre code){background:none;padding:0}.chat-text :where(blockquote){border-left:3px solid var(--border-strong);margin-left:0;color:var(--muted);background:#ffffff05;padding:8px 12px;border-radius:0 var(--radius-sm) var(--radius-sm) 0}.chat-text :where(blockquote blockquote){margin-top:8px;border-left-color:var(--border-hover);background:#ffffff08}.chat-text :where(blockquote blockquote blockquote){border-left-color:var(--muted-strong);background:#ffffff0a}:root[data-theme=light] .chat-text :where(blockquote){background:#00000008}:root[data-theme=light] .chat-text :where(blockquote blockquote){background:#0000000d}:root[data-theme=light] .chat-text :where(blockquote blockquote blockquote){background:#0000000a}:root[data-theme=light] .chat-text :where(:not(pre)>code){background:#00000014;border:1px solid rgba(0,0,0,.1)}:root[data-theme=light] .chat-text :where(pre){background:#0000000d;border:1px solid rgba(0,0,0,.1)}.chat-text :where(hr){border:none;border-top:1px solid var(--border);margin:1em 0}.chat-group{display:flex;gap:12px;align-items:flex-start;margin-bottom:16px;margin-left:4px;margin-right:16px}.chat-group.user{flex-direction:row-reverse;justify-content:flex-start}.chat-group-messages{display:flex;flex-direction:column;gap:2px;max-width:min(900px,calc(100% - 60px))}.chat-group.user .chat-group-messages{align-items:flex-end}.chat-group.user .chat-group-footer{justify-content:flex-end}.chat-group-footer{display:flex;gap:8px;align-items:baseline;margin-top:6px}.chat-sender-name{font-weight:500;font-size:12px;color:var(--muted)}.chat-group-timestamp{font-size:11px;color:var(--muted);opacity:.7}.chat-avatar{width:40px;height:40px;border-radius:8px;background:var(--panel-strong);display:grid;place-items:center;font-weight:600;font-size:14px;flex-shrink:0;align-self:flex-end;margin-bottom:4px}.chat-avatar.user{background:var(--accent-subtle);color:var(--accent)}.chat-avatar.assistant,.chat-avatar.other,.chat-avatar.tool{background:var(--secondary);color:var(--muted)}img.chat-avatar{display:block;object-fit:cover;object-position:center}.chat-bubble{position:relative;display:inline-block;border:1px solid transparent;background:var(--card);border-radius:var(--radius-lg);padding:10px 14px;box-shadow:none;transition:background .15s ease-out,border-color .15s ease-out;max-width:100%;word-wrap:break-word}.chat-bubble.has-copy{padding-right:36px}.chat-copy-btn{position:absolute;top:6px;right:8px;border:1px solid var(--border);background:var(--bg);color:var(--muted);border-radius:var(--radius-md);padding:4px 6px;font-size:14px;line-height:1;cursor:pointer;opacity:0;pointer-events:none;transition:opacity .12s ease-out,background .12s ease-out}.chat-copy-btn__icon{display:inline-flex;width:14px;height:14px;position:relative}.chat-copy-btn__icon svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:1.5px;stroke-linecap:round;stroke-linejoin:round}.chat-copy-btn__icon-copy,.chat-copy-btn__icon-check{position:absolute;top:0;left:0;transition:opacity .15s ease}.chat-copy-btn__icon-check,.chat-copy-btn[data-copied="1"] .chat-copy-btn__icon-copy{opacity:0}.chat-copy-btn[data-copied="1"] .chat-copy-btn__icon-check{opacity:1}.chat-bubble:hover .chat-copy-btn{opacity:1;pointer-events:auto}.chat-copy-btn:hover{background:var(--bg-hover)}.chat-copy-btn[data-copying="1"]{opacity:0;pointer-events:none}.chat-copy-btn[data-error="1"]{opacity:1;pointer-events:auto;border-color:var(--danger-subtle);background:var(--danger-subtle);color:var(--danger)}.chat-copy-btn[data-copied="1"]{opacity:1;pointer-events:auto;border-color:var(--ok-subtle);background:var(--ok-subtle);color:var(--ok)}.chat-copy-btn:focus-visible{opacity:1;pointer-events:auto;outline:2px solid var(--accent);outline-offset:2px}@media(hover:none){.chat-copy-btn{opacity:1;pointer-events:auto}}:root[data-theme=light] .chat-bubble{border-color:var(--border);box-shadow:inset 0 1px 0 var(--card-highlight)}.chat-bubble:hover{background:var(--bg-hover)}.chat-group.user .chat-bubble{background:var(--accent-subtle);border-color:transparent}:root[data-theme=light] .chat-group.user .chat-bubble{border-color:#ea580c33;background:#fb923c1f}.chat-group.user .chat-bubble:hover{background:#ff4d4d26}.chat-bubble.streaming{animation:pulsing-border 1.5s ease-out infinite}@keyframes pulsing-border{0%,to{border-color:var(--border)}50%{border-color:var(--accent)}}.chat-bubble.fade-in{animation:fade-in .2s ease-out}@keyframes fade-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}.chat-tool-card{border:1px solid var(--border);border-radius:8px;padding:12px;margin-top:8px;background:var(--card);box-shadow:inset 0 1px 0 var(--card-highlight);transition:border-color .15s ease-out,background .15s ease-out;max-height:120px;overflow:hidden}.chat-tool-card:hover{border-color:var(--border-strong);background:var(--bg-hover)}.chat-tool-card:first-child{margin-top:0}.chat-tool-card--clickable{cursor:pointer}.chat-tool-card--clickable:focus{outline:2px solid var(--accent);outline-offset:2px}.chat-tool-card__header{display:flex;justify-content:space-between;align-items:center;gap:8px}.chat-tool-card__title{display:inline-flex;align-items:center;gap:6px;font-weight:600;font-size:13px;line-height:1.2}.chat-tool-card__icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;flex-shrink:0}.chat-tool-card__icon svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:1.5px;stroke-linecap:round;stroke-linejoin:round}.chat-tool-card__action{display:inline-flex;align-items:center;gap:4px;font-size:12px;color:var(--accent);opacity:.8;transition:opacity .15s ease-out}.chat-tool-card__action svg{width:12px;height:12px;stroke:currentColor;fill:none;stroke-width:1.5px;stroke-linecap:round;stroke-linejoin:round}.chat-tool-card--clickable:hover .chat-tool-card__action{opacity:1}.chat-tool-card__status{display:inline-flex;align-items:center;color:var(--ok)}.chat-tool-card__status svg{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:2px;stroke-linecap:round;stroke-linejoin:round}.chat-tool-card__status-text{font-size:11px;margin-top:4px}.chat-tool-card__detail{font-size:12px;color:var(--muted);margin-top:4px}.chat-tool-card__preview{font-size:11px;color:var(--muted);margin-top:8px;padding:8px 10px;background:var(--secondary);border-radius:var(--radius-md);white-space:pre-wrap;overflow:hidden;max-height:44px;line-height:1.4;border:1px solid var(--border)}.chat-tool-card--clickable:hover .chat-tool-card__preview{background:var(--bg-hover);border-color:var(--border-strong)}.chat-tool-card__inline{font-size:11px;color:var(--text);margin-top:6px;padding:6px 8px;background:var(--secondary);border-radius:var(--radius-sm);white-space:pre-wrap;word-break:break-word}.chat-reading-indicator{background:transparent;border:1px solid var(--border);padding:12px;display:inline-flex}.chat-reading-indicator__dots{display:flex;gap:6px;align-items:center}.chat-reading-indicator__dots span{width:6px;height:6px;border-radius:50%;background:var(--muted);animation:reading-pulse 1.4s ease-in-out infinite}.chat-reading-indicator__dots span:nth-child(1){animation-delay:0s}.chat-reading-indicator__dots span:nth-child(2){animation-delay:.2s}.chat-reading-indicator__dots span:nth-child(3){animation-delay:.4s}@keyframes reading-pulse{0%,60%,to{opacity:.3;transform:scale(.8)}30%{opacity:1;transform:scale(1)}}.chat-split-container{display:flex;gap:0;flex:1;min-height:0;height:100%}.chat-main{min-width:400px;display:flex;flex-direction:column;overflow:hidden;transition:flex .25s ease-out}.chat-sidebar{flex:1;min-width:300px;border-left:1px solid var(--border);display:flex;flex-direction:column;overflow:hidden;animation:slide-in .2s ease-out}@keyframes slide-in{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}.sidebar-panel{display:flex;flex-direction:column;height:100%;background:var(--panel)}.sidebar-header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid var(--border);flex-shrink:0;position:sticky;top:0;z-index:10;background:var(--panel)}.sidebar-header .btn{padding:4px 8px;font-size:14px;min-width:auto;line-height:1}.sidebar-title{font-weight:600;font-size:14px}.sidebar-content{flex:1;overflow:auto;padding:16px}.sidebar-markdown{font-size:14px;line-height:1.5}.sidebar-markdown pre{background:#0000001f;border-radius:4px;padding:12px;overflow-x:auto}.sidebar-markdown code{font-family:var(--mono);font-size:13px}@media(max-width:768px){.chat-split-container--open{position:fixed;inset:0;z-index:1000}.chat-split-container--open .chat-main{display:none}.chat-split-container--open .chat-sidebar{width:100%;min-width:0;border-left:none}}.card{border:1px solid var(--border);background:var(--card);border-radius:var(--radius-lg);padding:16px;animation:rise .3s var(--ease-out);transition:border-color var(--duration-fast) ease;box-shadow:inset 0 1px 0 var(--card-highlight)}.card:hover{border-color:var(--border-strong)}.card-title{font-size:14px;font-weight:600;color:var(--text-strong)}.card-sub{color:var(--muted);font-size:13px;margin-top:4px}.stat{background:var(--card);border-radius:var(--radius-md);padding:12px 14px;border:1px solid var(--border);transition:border-color var(--duration-fast) ease;box-shadow:inset 0 1px 0 var(--card-highlight)}.stat:hover{border-color:var(--border-strong)}.stat-label{color:var(--muted);font-size:12px;font-weight:500}.stat-value{font-size:20px;font-weight:600;margin-top:4px;letter-spacing:-.02em}.stat-value.ok{color:var(--ok)}.stat-value.warn{color:var(--warn)}.stat-card{display:grid;gap:4px}.note-title{font-weight:600}.status-list{display:grid;gap:8px}.status-list div{display:flex;justify-content:space-between;gap:12px;padding:8px 0;border-bottom:1px solid var(--border)}.status-list div:last-child{border-bottom:none}.account-count{margin-top:10px;font-size:12px;font-weight:500;color:var(--muted)}.account-card-list{margin-top:16px;display:grid;gap:12px}.account-card{border:1px solid var(--border);border-radius:var(--radius-md);padding:12px;background:var(--bg-elevated);transition:border-color var(--duration-fast) ease}.account-card:hover{border-color:var(--border-strong)}.account-card-header{display:flex;justify-content:space-between;align-items:baseline;gap:12px}.account-card-title{font-weight:500}.account-card-id{font-family:var(--mono);font-size:12px;color:var(--muted)}.account-card-status{margin-top:10px;font-size:13px}.account-card-status div{padding:4px 0}.account-card-error{margin-top:8px;color:var(--danger);font-size:12px}.label{color:var(--muted);font-size:12px;font-weight:500}.pill{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--border);padding:6px 12px;border-radius:var(--radius-full);background:var(--secondary);font-size:13px;font-weight:500;transition:border-color var(--duration-fast) ease}.pill:hover{border-color:var(--border-strong)}.pill.danger{border-color:var(--danger-subtle);background:var(--danger-subtle);color:var(--danger)}.theme-toggle{--theme-item: 28px;--theme-gap: 2px;--theme-pad: 4px;position:relative}.theme-toggle__track{position:relative;display:grid;grid-template-columns:repeat(3,var(--theme-item));gap:var(--theme-gap);padding:var(--theme-pad);border-radius:var(--radius-full);border:1px solid var(--border);background:var(--secondary)}.theme-toggle__indicator{position:absolute;top:50%;left:var(--theme-pad);width:var(--theme-item);height:var(--theme-item);border-radius:var(--radius-full);transform:translateY(-50%) translate(calc(var(--theme-index, 0) * (var(--theme-item) + var(--theme-gap))));background:var(--accent);transition:transform var(--duration-normal) var(--ease-out);z-index:0}.theme-toggle__button{height:var(--theme-item);width:var(--theme-item);display:grid;place-items:center;border:0;border-radius:var(--radius-full);background:transparent;color:var(--muted);cursor:pointer;position:relative;z-index:1;transition:color var(--duration-fast) ease}.theme-toggle__button:hover{color:var(--text)}.theme-toggle__button.active{color:var(--accent-foreground)}.theme-toggle__button.active .theme-icon{stroke:var(--accent-foreground)}.theme-icon{width:14px;height:14px;stroke:currentColor;fill:none;stroke-width:1.5px;stroke-linecap:round;stroke-linejoin:round}.statusDot{width:8px;height:8px;border-radius:var(--radius-full);background:var(--danger)}.statusDot.ok{background:var(--ok)}.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;border:1px solid var(--border);background:var(--bg-elevated);padding:8px 14px;border-radius:var(--radius-md);font-size:13px;font-weight:500;cursor:pointer;transition:border-color var(--duration-fast) ease,background var(--duration-fast) ease}.btn:hover{background:var(--bg-hover);border-color:var(--border-strong)}.btn:active{background:var(--secondary)}.btn svg{width:16px;height:16px;stroke:currentColor;fill:none;stroke-width:1.5px;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}.btn.primary{border-color:var(--accent);background:var(--accent);color:var(--primary-foreground)}.btn.primary:hover{background:var(--accent-hover);border-color:var(--accent-hover)}.btn-kbd{display:inline-flex;align-items:center;justify-content:center;margin-left:6px;padding:2px 5px;font-family:var(--mono);font-size:11px;font-weight:500;line-height:1;border-radius:4px;background:#ffffff26;color:inherit;opacity:.8}.btn.primary .btn-kbd{background:#fff3}:root[data-theme=light] .btn-kbd{background:#00000014}:root[data-theme=light] .btn.primary .btn-kbd{background:#ffffff40}.btn.active{border-color:var(--accent);background:var(--accent-subtle);color:var(--accent)}.btn.danger{border-color:transparent;background:var(--danger-subtle);color:var(--danger)}.btn.danger:hover{background:#ef444426}.btn--sm{padding:6px 10px;font-size:12px}.btn:disabled{opacity:.5;cursor:not-allowed}.field{display:grid;gap:6px}.field.full{grid-column:1 / -1}.field span{color:var(--muted);font-size:13px;font-weight:500}.field input,.field textarea,.field select{border:1px solid var(--input);background:var(--card);border-radius:var(--radius-md);padding:8px 12px;outline:none;box-shadow:inset 0 1px 0 var(--card-highlight);transition:border-color var(--duration-fast) ease,box-shadow var(--duration-fast) ease}.field input:focus,.field textarea:focus,.field select:focus{border-color:var(--ring);box-shadow:var(--focus-ring)}.field select{appearance:none;padding-right:36px;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23a1a1aa' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 10px center;cursor:pointer}.field textarea{font-family:var(--mono);min-height:160px;resize:vertical;white-space:pre;line-height:1.5}.field.checkbox{grid-template-columns:auto 1fr;align-items:center}.config-form .field.checkbox{grid-template-columns:18px minmax(0,1fr);column-gap:10px}.config-form .field.checkbox input[type=checkbox]{margin:0;width:16px;height:16px;accent-color:var(--accent)}.form-grid{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(200px,1fr))}:root[data-theme=light] .field input,:root[data-theme=light] .field textarea,:root[data-theme=light] .field select{background:var(--card);border-color:var(--input)}:root[data-theme=light] .btn{background:var(--bg);border-color:var(--input)}:root[data-theme=light] .btn:hover{background:var(--bg-hover)}:root[data-theme=light] .btn.primary{background:var(--accent);border-color:var(--accent)}.muted{color:var(--muted)}.mono{font-family:var(--mono)}.callout{padding:12px 14px;border-radius:var(--radius-md);background:var(--secondary);border:1px solid var(--border);font-size:13px}.callout.danger{border-color:var(--danger-subtle);background:var(--danger-subtle);color:var(--danger)}.callout.info{border-color:#3b82f633;background:#3b82f61a;color:var(--info)}.callout.success{border-color:var(--ok-subtle);background:var(--ok-subtle);color:var(--ok)}.compaction-indicator{font-size:13px;padding:10px 12px;margin-bottom:8px;animation:fade-in .2s var(--ease-out)}.compaction-indicator--active{animation:compaction-pulse 1.5s ease-in-out infinite}.compaction-indicator--complete{animation:fade-in .2s var(--ease-out)}@keyframes compaction-pulse{0%,to{opacity:.7}50%{opacity:1}}.code-block{font-family:var(--mono);font-size:13px;line-height:1.5;background:var(--secondary);padding:12px;border-radius:var(--radius-md);border:1px solid var(--border);max-height:360px;overflow:auto}:root[data-theme=light] .code-block,:root[data-theme=light] .list-item,:root[data-theme=light] .table-row,:root[data-theme=light] .chip{background:var(--bg)}.list{display:grid;gap:8px;container-type:inline-size}.list-item{display:grid;grid-template-columns:minmax(0,1fr) minmax(200px,260px);gap:16px;align-items:start;border:1px solid var(--border);border-radius:var(--radius-md);padding:12px;background:var(--card);transition:border-color var(--duration-fast) ease}.list-item-clickable{cursor:pointer}.list-item-clickable:hover{border-color:var(--border-strong)}.list-item-selected{border-color:var(--accent);box-shadow:var(--focus-ring)}.list-main{display:grid;gap:4px;min-width:0}.list-title{font-weight:500}.list-sub{color:var(--muted);font-size:12px}.list-meta{text-align:right;color:var(--muted);font-size:12px;display:grid;gap:4px;min-width:200px}.list-meta .btn{padding:6px 10px}.list-meta .field input,.list-meta .field textarea,.list-meta .field select{width:100%}@container (max-width: 560px){.list-item{grid-template-columns:1fr}.list-meta{min-width:0;text-align:left}}.chip-row{display:flex;flex-wrap:wrap;gap:6px}.chip{font-size:12px;font-weight:500;border:1px solid var(--border);border-radius:var(--radius-full);padding:4px 10px;color:var(--muted);background:var(--secondary);transition:border-color var(--duration-fast) ease}.chip input{margin-right:6px}.chip-ok{color:var(--ok);border-color:var(--ok-subtle)}.chip-warn{color:var(--warn);border-color:var(--warn-subtle)}.table{display:grid;gap:6px}.table-head,.table-row{display:grid;grid-template-columns:1.4fr 1fr .8fr .7fr .8fr .8fr .8fr .8fr .6fr;gap:12px;align-items:center}.table-head{font-size:12px;font-weight:500;color:var(--muted);padding:0 12px}.table-row{border:1px solid var(--border);padding:10px 12px;border-radius:var(--radius-md);background:var(--card);transition:border-color var(--duration-fast) ease}.table-row:hover{border-color:var(--border-strong)}.session-link{text-decoration:none;color:var(--accent);font-weight:500}.session-link:hover{text-decoration:underline}.log-stream{border:1px solid var(--border);border-radius:var(--radius-md);background:var(--card);max-height:500px;overflow:auto;container-type:inline-size}.log-row{display:grid;grid-template-columns:90px 70px minmax(140px,200px) minmax(0,1fr);gap:12px;align-items:start;padding:8px 12px;border-bottom:1px solid var(--border);font-size:12px;transition:background var(--duration-fast) ease}.log-row:hover{background:var(--bg-hover)}.log-row:last-child{border-bottom:none}.log-time{color:var(--muted);font-family:var(--mono)}.log-level{font-size:11px;font-weight:500;border:1px solid var(--border);border-radius:var(--radius-sm);padding:2px 6px;width:fit-content}.log-level.trace,.log-level.debug{color:var(--muted)}.log-level.info{color:var(--info);border-color:#3b82f64d}.log-level.warn{color:var(--warn);border-color:var(--warn-subtle)}.log-level.error,.log-level.fatal{color:var(--danger);border-color:var(--danger-subtle)}.log-chip.trace,.log-chip.debug{color:var(--muted)}.log-chip.info{color:var(--info);border-color:#3b82f64d}.log-chip.warn{color:var(--warn);border-color:var(--warn-subtle)}.log-chip.error,.log-chip.fatal{color:var(--danger);border-color:var(--danger-subtle)}.log-subsystem{color:var(--muted);font-family:var(--mono)}.log-message{white-space:pre-wrap;word-break:break-word;font-family:var(--mono)}@container (max-width: 620px){.log-row{grid-template-columns:70px 60px minmax(0,1fr)}.log-subsystem{display:none}}.chat{display:flex;flex-direction:column;min-height:0}.shell--chat .chat{flex:1}.chat-header{display:flex;justify-content:space-between;align-items:flex-end;gap:16px;flex-wrap:wrap}.chat-header__left{display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap;min-width:0}.chat-header__right{display:flex;align-items:center;gap:8px}.chat-session{min-width:240px}.chat-thread{margin-top:16px;display:flex;flex-direction:column;gap:12px;flex:1;min-height:0;overflow-y:auto;overflow-x:hidden;padding:16px 12px;min-width:0;border-radius:0;border:none;background:transparent}.chat-queue{margin-top:12px;padding:12px;border-radius:var(--radius-lg);border:1px solid var(--border);background:var(--card);display:grid;gap:8px}.chat-queue__title{font-family:var(--mono);font-size:12px;font-weight:500;color:var(--muted)}.chat-queue__list{display:grid;gap:8px}.chat-queue__item{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:start;gap:12px;padding:10px 12px;border-radius:var(--radius-md);border:1px dashed var(--border-strong);background:var(--secondary)}.chat-queue__text{color:var(--chat-text);font-size:13px;line-height:1.45;white-space:pre-wrap;overflow:hidden;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical}.chat-queue__remove{align-self:start;padding:4px 10px;font-size:12px;line-height:1}.chat-line{display:flex}.chat-line.user{justify-content:flex-end}.chat-line.assistant,.chat-line.other{justify-content:flex-start}.chat-msg{display:grid;gap:6px;max-width:min(700px,82%)}.chat-line.user .chat-msg{justify-items:end}.chat-bubble{border:1px solid transparent;background:var(--card);border-radius:var(--radius-lg);padding:10px 14px;min-width:0}:root[data-theme=light] .chat-bubble{border-color:var(--border);background:var(--bg)}.chat-line.user .chat-bubble{border-color:transparent;background:var(--accent-subtle)}:root[data-theme=light] .chat-line.user .chat-bubble{border-color:#ea580c33;background:#fb923c1f}.chat-line.assistant .chat-bubble{border-color:transparent;background:var(--secondary)}:root[data-theme=light] .chat-line.assistant .chat-bubble{border-color:var(--border);background:var(--bg-muted)}@keyframes chatStreamPulse{0%,to{border-color:var(--border)}50%{border-color:var(--accent)}}.chat-bubble.streaming{animation:chatStreamPulse 1.5s ease-in-out infinite}@media(prefers-reduced-motion:reduce){.chat-bubble.streaming{animation:none;border-color:var(--accent)}}.chat-bubble.chat-reading-indicator{width:fit-content;padding:10px 16px}.chat-reading-indicator__dots{display:inline-flex;align-items:center;gap:4px;height:12px}.chat-reading-indicator__dots>span{display:inline-block;width:6px;height:6px;border-radius:var(--radius-full);background:var(--muted);opacity:.6;transform:translateY(0);animation:chatReadingDot 1.2s ease-in-out infinite;will-change:transform,opacity}.chat-reading-indicator__dots>span:nth-child(2){animation-delay:.15s}.chat-reading-indicator__dots>span:nth-child(3){animation-delay:.3s}@keyframes chatReadingDot{0%,80%,to{opacity:.4;transform:translateY(0)}40%{opacity:1;transform:translateY(-3px)}}@media(prefers-reduced-motion:reduce){.chat-reading-indicator__dots>span{animation:none;opacity:.6}}.chat-text{overflow-wrap:anywhere;word-break:break-word;color:var(--chat-text);line-height:1.5}.chat-text :where(p,ul,ol,pre,blockquote,table){margin:0}.chat-text :where(p+p,p+ul,p+ol,p+pre,p+blockquote,p+table){margin-top:.75em}.chat-text :where(ul,ol){padding-left:1.2em}.chat-text :where(li+li){margin-top:.25em}.chat-text :where(a){color:var(--accent)}.chat-text :where(a:hover){text-decoration:underline}.chat-text :where(blockquote){border-left:2px solid var(--border-strong);padding-left:12px;color:var(--muted)}.chat-text :where(hr){border:0;border-top:1px solid var(--border);margin:1em 0}.chat-text :where(code){font-family:var(--mono);font-size:.9em}.chat-text :where(:not(pre)>code){padding:.15em .35em;border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--secondary)}:root[data-theme=light] .chat-text :where(:not(pre)>code){background:var(--bg-muted)}.chat-text :where(pre){margin-top:.75em;padding:10px 12px;border-radius:var(--radius-md);border:1px solid var(--border);background:var(--secondary);overflow:auto}:root[data-theme=light] .chat-text :where(pre){background:var(--bg-muted)}.chat-text :where(pre code){font-size:12px;white-space:pre}.chat-text :where(table){margin-top:.75em;border-collapse:collapse;width:100%;font-size:13px}.chat-text :where(th,td){border:1px solid var(--border);padding:6px 10px;vertical-align:top}.chat-text :where(th){font-family:var(--mono);font-weight:500;color:var(--muted);background:var(--secondary)}.chat-tool-card{margin-top:8px;padding:10px 12px;border-radius:var(--radius-md);border:1px solid var(--border);background:var(--secondary);display:grid;gap:4px}:root[data-theme=light] .chat-tool-card{background:var(--bg-muted)}.chat-tool-card__title{font-family:var(--mono);font-size:12px;font-weight:500;color:var(--text)}.chat-tool-card__detail{font-family:var(--mono);font-size:11px;color:var(--muted)}.chat-tool-card__details{margin-top:6px}.chat-tool-card__summary{font-family:var(--mono);font-size:11px;color:var(--muted);cursor:pointer;list-style:none;display:inline-flex;align-items:center;gap:6px}.chat-tool-card__summary::-webkit-details-marker{display:none}.chat-tool-card__summary-meta{color:var(--muted);opacity:.7}.chat-tool-card__details[open] .chat-tool-card__summary{color:var(--text)}.chat-tool-card__output{margin-top:8px;font-family:var(--mono);font-size:11px;line-height:1.5;white-space:pre-wrap;color:var(--chat-text);padding:8px 10px;border-radius:var(--radius-md);border:1px solid var(--border);background:var(--card)}:root[data-theme=light] .chat-tool-card__output{background:var(--bg)}.chat-stamp{font-size:11px;color:var(--muted)}.chat-line.user .chat-stamp{text-align:right}.chat-compose{margin-top:12px;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px}.shell--chat .chat-compose{position:sticky;bottom:0;z-index:5;margin-top:0;padding-top:12px;background:linear-gradient(180deg,transparent 0%,var(--bg) 40%)}.shell--chat-focus .chat-compose{bottom:calc(var(--shell-pad) + 8px);padding-bottom:calc(12px + env(safe-area-inset-bottom,0px));border-bottom-left-radius:var(--radius-lg);border-bottom-right-radius:var(--radius-lg)}.chat-compose__field{gap:4px}.chat-compose__field textarea{min-height:72px;padding:10px 14px;border-radius:var(--radius-lg);resize:vertical;white-space:pre-wrap;font-family:var(--font-body);line-height:1.5;border:1px solid var(--input);background:var(--card);box-shadow:inset 0 1px 0 var(--card-highlight);transition:border-color var(--duration-fast) ease,box-shadow var(--duration-fast) ease}.chat-compose__field textarea:focus{border-color:var(--ring);box-shadow:var(--focus-ring)}.chat-compose__field textarea:disabled{opacity:.5;cursor:not-allowed}.chat-compose__actions{justify-content:flex-end;align-self:end}@media(max-width:900px){.chat-session{min-width:180px}.chat-compose{grid-template-columns:1fr}}.qr-wrap{margin-top:16px;border-radius:var(--radius-md);background:var(--card);border:1px dashed var(--border-strong);padding:16px;display:inline-flex}.qr-wrap img{width:160px;height:160px;border-radius:var(--radius-sm);image-rendering:pixelated}.exec-approval-overlay{position:fixed;inset:0;background:#000c;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center;padding:24px;z-index:200}.exec-approval-card{width:min(540px,100%);background:var(--card);border:1px solid var(--border);border-radius:var(--radius-lg);padding:20px;animation:scale-in .2s var(--ease-out)}.exec-approval-header{display:flex;align-items:center;justify-content:space-between;gap:16px}.exec-approval-title{font-size:14px;font-weight:600}.exec-approval-sub{color:var(--muted);font-size:13px;margin-top:4px}.exec-approval-queue{font-size:11px;font-weight:500;color:var(--muted);border:1px solid var(--border);border-radius:var(--radius-full);padding:4px 10px}.exec-approval-command{margin-top:12px;padding:10px 12px;background:var(--secondary);border:1px solid var(--border);border-radius:var(--radius-md);word-break:break-word;white-space:pre-wrap;font-family:var(--mono);font-size:13px}.exec-approval-meta{margin-top:12px;display:grid;gap:6px;font-size:13px;color:var(--muted)}.exec-approval-meta-row{display:flex;justify-content:space-between;gap:12px}.exec-approval-meta-row span:last-child{color:var(--text);font-family:var(--mono)}.exec-approval-error{margin-top:10px;font-size:13px;color:var(--danger)}.exec-approval-actions{margin-top:16px;display:flex;flex-wrap:wrap;gap:8px}.config-layout{display:grid;grid-template-columns:260px minmax(0,1fr);gap:0;min-height:calc(100vh - 160px);margin:-16px;border-radius:var(--radius-xl);overflow:hidden;border:1px solid var(--border);background:var(--panel)}.config-sidebar{display:flex;flex-direction:column;background:var(--bg-accent);border-right:1px solid var(--border)}:root[data-theme=light] .config-sidebar{background:var(--bg-hover)}.config-sidebar__header{display:flex;align-items:center;justify-content:space-between;padding:18px;border-bottom:1px solid var(--border)}.config-sidebar__title{font-weight:600;font-size:14px;letter-spacing:-.01em}.config-sidebar__footer{margin-top:auto;padding:14px;border-top:1px solid var(--border)}.config-search{position:relative;padding:14px;border-bottom:1px solid var(--border)}.config-search__icon{position:absolute;left:28px;top:50%;transform:translateY(-50%);width:16px;height:16px;color:var(--muted);pointer-events:none}.config-search__input{width:100%;padding:11px 36px 11px 42px;border:1px solid var(--border);border-radius:var(--radius-md);background:var(--bg-elevated);font-size:13px;outline:none;transition:border-color var(--duration-fast) ease,box-shadow var(--duration-fast) ease,background var(--duration-fast) ease}.config-search__input::placeholder{color:var(--muted)}.config-search__input:focus{border-color:var(--accent);box-shadow:var(--focus-ring);background:var(--bg-hover)}:root[data-theme=light] .config-search__input{background:#fff}:root[data-theme=light] .config-search__input:focus{background:#fff}.config-search__clear{position:absolute;right:22px;top:50%;transform:translateY(-50%);width:22px;height:22px;border:none;border-radius:var(--radius-full);background:var(--bg-hover);color:var(--muted);font-size:14px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background var(--duration-fast) ease,color var(--duration-fast) ease}.config-search__clear:hover{background:var(--border-strong);color:var(--text)}.config-nav{flex:1;overflow-y:auto;padding:10px}.config-nav__item{display:flex;align-items:center;gap:12px;width:100%;padding:11px 14px;border:none;border-radius:var(--radius-md);background:transparent;color:var(--muted);font-size:13px;font-weight:500;text-align:left;cursor:pointer;transition:background var(--duration-fast) ease,color var(--duration-fast) ease}.config-nav__item:hover{background:var(--bg-hover);color:var(--text)}:root[data-theme=light] .config-nav__item:hover{background:#0000000a}.config-nav__item.active{background:var(--accent-subtle);color:var(--accent)}.config-nav__icon{width:20px;height:20px;display:flex;align-items:center;justify-content:center;font-size:15px;opacity:.7}.config-nav__item:hover .config-nav__icon,.config-nav__item.active .config-nav__icon{opacity:1}.config-nav__icon svg{width:18px;height:18px;stroke:currentColor;fill:none}.config-nav__label{flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.config-mode-toggle{display:flex;padding:4px;background:var(--bg-elevated);border-radius:var(--radius-md);border:1px solid var(--border)}:root[data-theme=light] .config-mode-toggle{background:#fff}.config-mode-toggle__btn{flex:1;padding:9px 14px;border:none;border-radius:var(--radius-sm);background:transparent;color:var(--muted);font-size:12px;font-weight:600;cursor:pointer;transition:background var(--duration-fast) ease,color var(--duration-fast) ease,box-shadow var(--duration-fast) ease}.config-mode-toggle__btn:hover{color:var(--text)}.config-mode-toggle__btn.active{background:var(--accent);color:#fff;box-shadow:var(--shadow-sm)}.config-main{display:flex;flex-direction:column;min-width:0;background:var(--panel)}.config-actions{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:14px 22px;background:var(--bg-accent);border-bottom:1px solid var(--border)}:root[data-theme=light] .config-actions{background:var(--bg-hover)}.config-actions__left,.config-actions__right{display:flex;align-items:center;gap:10px}.config-changes-badge{padding:6px 14px;border-radius:var(--radius-full);background:var(--accent-subtle);border:1px solid rgba(255,77,77,.3);color:var(--accent);font-size:12px;font-weight:600}.config-status{font-size:13px;color:var(--muted)}.config-diff{margin:18px 22px 0;border:1px solid rgba(255,77,77,.25);border-radius:var(--radius-lg);background:var(--accent-subtle);overflow:hidden}.config-diff__summary{display:flex;align-items:center;justify-content:space-between;padding:14px 18px;cursor:pointer;font-size:13px;font-weight:600;color:var(--accent);list-style:none}.config-diff__summary::-webkit-details-marker{display:none}.config-diff__chevron{width:16px;height:16px;transition:transform var(--duration-normal) var(--ease-out)}.config-diff__chevron svg{width:100%;height:100%}.config-diff[open] .config-diff__chevron{transform:rotate(180deg)}.config-diff__content{padding:0 18px 18px;display:grid;gap:10px}.config-diff__item{display:flex;align-items:baseline;gap:14px;padding:10px 14px;border-radius:var(--radius-md);background:var(--bg-elevated);font-size:12px;font-family:var(--mono)}:root[data-theme=light] .config-diff__item{background:#fff}.config-diff__path{font-weight:600;color:var(--text);flex-shrink:0}.config-diff__values{display:flex;align-items:baseline;gap:10px;min-width:0;flex-wrap:wrap}.config-diff__from{color:var(--danger);opacity:.85}.config-diff__arrow{color:var(--muted)}.config-diff__to{color:var(--ok)}.config-section-hero{display:flex;align-items:center;gap:16px;padding:16px 22px;border-bottom:1px solid var(--border);background:var(--bg-accent)}:root[data-theme=light] .config-section-hero{background:var(--bg-hover)}.config-section-hero__icon{width:30px;height:30px;color:var(--accent);display:flex;align-items:center;justify-content:center}.config-section-hero__icon svg{width:100%;height:100%;stroke:currentColor;fill:none}.config-section-hero__text{display:grid;gap:3px;min-width:0}.config-section-hero__title{font-size:16px;font-weight:600;letter-spacing:-.01em}.config-section-hero__desc{font-size:13px;color:var(--muted)}.config-subnav{display:flex;gap:8px;padding:12px 22px 14px;border-bottom:1px solid var(--border);background:var(--bg-accent);overflow-x:auto}:root[data-theme=light] .config-subnav{background:var(--bg-hover)}.config-subnav__item{border:1px solid transparent;border-radius:var(--radius-full);padding:7px 14px;font-size:12px;font-weight:600;color:var(--muted);background:var(--bg-elevated);cursor:pointer;transition:background var(--duration-fast) ease,color var(--duration-fast) ease,border-color var(--duration-fast) ease;white-space:nowrap}:root[data-theme=light] .config-subnav__item{background:#fff}.config-subnav__item:hover{color:var(--text);border-color:var(--border)}.config-subnav__item.active{color:var(--accent);border-color:#ff4d4d66;background:var(--accent-subtle)}.config-content{flex:1;overflow-y:auto;padding:22px}.config-raw-field textarea{min-height:500px;font-family:var(--mono);font-size:13px;line-height:1.55}.config-loading{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;padding:80px 24px;color:var(--muted)}.config-loading__spinner{width:40px;height:40px;border:3px solid var(--border);border-top-color:var(--accent);border-radius:var(--radius-full);animation:spin .75s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.config-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;padding:80px 24px;text-align:center}.config-empty__icon{font-size:56px;opacity:.35}.config-empty__text{color:var(--muted);font-size:15px}.config-form--modern{display:grid;gap:26px}.config-section-card{border:1px solid var(--border);border-radius:var(--radius-lg);background:var(--bg-elevated);overflow:hidden;transition:border-color var(--duration-fast) ease}.config-section-card:hover{border-color:var(--border-strong)}:root[data-theme=light] .config-section-card{background:#fff}.config-section-card__header{display:flex;align-items:flex-start;gap:16px;padding:20px 22px;background:var(--bg-accent);border-bottom:1px solid var(--border)}:root[data-theme=light] .config-section-card__header{background:var(--bg-hover)}.config-section-card__icon{width:34px;height:34px;color:var(--accent);flex-shrink:0}.config-section-card__icon svg{width:100%;height:100%}.config-section-card__titles{flex:1;min-width:0}.config-section-card__title{margin:0;font-size:17px;font-weight:600;letter-spacing:-.01em}.config-section-card__desc{margin:5px 0 0;font-size:13px;color:var(--muted);line-height:1.45}.config-section-card__content{padding:22px}.cfg-fields{display:grid;gap:22px}.cfg-field{display:grid;gap:8px}.cfg-field--error{padding:14px;border-radius:var(--radius-md);background:var(--danger-subtle);border:1px solid rgba(239,68,68,.3)}.cfg-field__label{font-size:13px;font-weight:600;color:var(--text)}.cfg-field__help{font-size:12px;color:var(--muted);line-height:1.45}.cfg-field__error{font-size:12px;color:var(--danger)}.cfg-input-wrap{display:flex;gap:10px}.cfg-input{flex:1;padding:11px 14px;border:1px solid var(--border-strong);border-radius:var(--radius-md);background:var(--bg-accent);font-size:14px;outline:none;transition:border-color var(--duration-fast) ease,box-shadow var(--duration-fast) ease,background var(--duration-fast) ease}.cfg-input::placeholder{color:var(--muted);opacity:.7}.cfg-input:focus{border-color:var(--accent);box-shadow:var(--focus-ring);background:var(--bg-hover)}:root[data-theme=light] .cfg-input{background:#fff}:root[data-theme=light] .cfg-input:focus{background:#fff}.cfg-input--sm{padding:9px 12px;font-size:13px}.cfg-input__reset{padding:10px 14px;border:1px solid var(--border);border-radius:var(--radius-md);background:var(--bg-elevated);color:var(--muted);font-size:14px;cursor:pointer;transition:background var(--duration-fast) ease,color var(--duration-fast) ease}.cfg-input__reset:hover:not(:disabled){background:var(--bg-hover);color:var(--text)}.cfg-input__reset:disabled{opacity:.5;cursor:not-allowed}.cfg-textarea{width:100%;padding:12px 14px;border:1px solid var(--border-strong);border-radius:var(--radius-md);background:var(--bg-accent);font-family:var(--mono);font-size:13px;line-height:1.55;resize:vertical;outline:none;transition:border-color var(--duration-fast) ease,box-shadow var(--duration-fast) ease}.cfg-textarea:focus{border-color:var(--accent);box-shadow:var(--focus-ring)}:root[data-theme=light] .cfg-textarea{background:#fff}.cfg-textarea--sm{padding:10px 12px;font-size:12px}.cfg-number{display:inline-flex;border:1px solid var(--border-strong);border-radius:var(--radius-md);overflow:hidden;background:var(--bg-accent)}:root[data-theme=light] .cfg-number{background:#fff}.cfg-number__btn{width:44px;border:none;background:var(--bg-elevated);color:var(--text);font-size:18px;font-weight:300;cursor:pointer;transition:background var(--duration-fast) ease}.cfg-number__btn:hover:not(:disabled){background:var(--bg-hover)}.cfg-number__btn:disabled{opacity:.4;cursor:not-allowed}:root[data-theme=light] .cfg-number__btn{background:var(--bg-hover)}:root[data-theme=light] .cfg-number__btn:hover:not(:disabled){background:var(--border)}.cfg-number__input{width:85px;padding:11px;border:none;border-left:1px solid var(--border);border-right:1px solid var(--border);background:transparent;font-size:14px;text-align:center;outline:none;-moz-appearance:textfield}.cfg-number__input::-webkit-outer-spin-button,.cfg-number__input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}.cfg-select{padding:11px 40px 11px 14px;border:1px solid var(--border-strong);border-radius:var(--radius-md);background-color:var(--bg-accent);background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 12px center;font-size:14px;cursor:pointer;outline:none;appearance:none;transition:border-color var(--duration-fast) ease,box-shadow var(--duration-fast) ease}.cfg-select:focus{border-color:var(--accent);box-shadow:var(--focus-ring)}:root[data-theme=light] .cfg-select{background-color:#fff}.cfg-segmented{display:inline-flex;padding:4px;border:1px solid var(--border);border-radius:var(--radius-md);background:var(--bg-accent)}:root[data-theme=light] .cfg-segmented{background:var(--bg-hover)}.cfg-segmented__btn{padding:9px 18px;border:none;border-radius:var(--radius-sm);background:transparent;color:var(--muted);font-size:13px;font-weight:500;cursor:pointer;transition:background var(--duration-fast) ease,color var(--duration-fast) ease,box-shadow var(--duration-fast) ease}.cfg-segmented__btn:hover:not(:disabled):not(.active){color:var(--text)}.cfg-segmented__btn.active{background:var(--accent);color:#fff;box-shadow:var(--shadow-sm)}.cfg-segmented__btn:disabled{opacity:.5;cursor:not-allowed}.cfg-toggle-row{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:16px 18px;border:1px solid var(--border);border-radius:var(--radius-lg);background:var(--bg-accent);cursor:pointer;transition:background var(--duration-fast) ease,border-color var(--duration-fast) ease}.cfg-toggle-row:hover:not(.disabled){background:var(--bg-hover);border-color:var(--border-strong)}.cfg-toggle-row.disabled{opacity:.55;cursor:not-allowed}:root[data-theme=light] .cfg-toggle-row{background:#fff}:root[data-theme=light] .cfg-toggle-row:hover:not(.disabled){background:var(--bg-hover)}.cfg-toggle-row__content{flex:1;min-width:0}.cfg-toggle-row__label{display:block;font-size:14px;font-weight:500;color:var(--text)}.cfg-toggle-row__help{display:block;margin-top:3px;font-size:12px;color:var(--muted);line-height:1.45}.cfg-toggle{position:relative;flex-shrink:0}.cfg-toggle input{position:absolute;opacity:0;width:0;height:0}.cfg-toggle__track{display:block;width:50px;height:28px;background:var(--bg-elevated);border:1px solid var(--border-strong);border-radius:var(--radius-full);position:relative;transition:background var(--duration-normal) ease,border-color var(--duration-normal) ease}:root[data-theme=light] .cfg-toggle__track{background:var(--border)}.cfg-toggle__track:after{content:"";position:absolute;top:3px;left:3px;width:20px;height:20px;background:var(--text);border-radius:var(--radius-full);box-shadow:var(--shadow-sm);transition:transform var(--duration-normal) var(--ease-out),background var(--duration-normal) ease}.cfg-toggle input:checked+.cfg-toggle__track{background:var(--ok-subtle);border-color:#22c55e66}.cfg-toggle input:checked+.cfg-toggle__track:after{transform:translate(22px);background:var(--ok)}.cfg-toggle input:focus+.cfg-toggle__track{box-shadow:var(--focus-ring)}.cfg-object{border:1px solid var(--border);border-radius:var(--radius-lg);background:var(--bg-accent);overflow:hidden}:root[data-theme=light] .cfg-object{background:#fff}.cfg-object__header{display:flex;align-items:center;justify-content:space-between;padding:14px 18px;cursor:pointer;list-style:none;transition:background var(--duration-fast) ease}.cfg-object__header:hover{background:var(--bg-hover)}.cfg-object__header::-webkit-details-marker{display:none}.cfg-object__title{font-size:14px;font-weight:600;color:var(--text)}.cfg-object__chevron{width:18px;height:18px;color:var(--muted);transition:transform var(--duration-normal) var(--ease-out)}.cfg-object__chevron svg{width:100%;height:100%}.cfg-object[open] .cfg-object__chevron{transform:rotate(180deg)}.cfg-object__help{padding:0 18px 14px;font-size:12px;color:var(--muted);border-bottom:1px solid var(--border)}.cfg-object__content{padding:18px;display:grid;gap:18px}.cfg-array{border:1px solid var(--border);border-radius:var(--radius-lg);overflow:hidden}.cfg-array__header{display:flex;align-items:center;gap:14px;padding:14px 18px;background:var(--bg-accent);border-bottom:1px solid var(--border)}:root[data-theme=light] .cfg-array__header{background:var(--bg-hover)}.cfg-array__label{flex:1;font-size:14px;font-weight:600;color:var(--text)}.cfg-array__count{font-size:12px;color:var(--muted);padding:4px 10px;background:var(--bg-elevated);border-radius:var(--radius-full)}:root[data-theme=light] .cfg-array__count{background:#fff}.cfg-array__add{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border:1px solid var(--border);border-radius:var(--radius-md);background:var(--bg-elevated);color:var(--text);font-size:12px;font-weight:500;cursor:pointer;transition:background var(--duration-fast) ease}.cfg-array__add:hover:not(:disabled){background:var(--bg-hover)}.cfg-array__add:disabled{opacity:.5;cursor:not-allowed}.cfg-array__add-icon{width:14px;height:14px}.cfg-array__add-icon svg{width:100%;height:100%}.cfg-array__help{padding:12px 18px;font-size:12px;color:var(--muted);border-bottom:1px solid var(--border)}.cfg-array__empty{padding:36px 18px;text-align:center;color:var(--muted);font-size:13px}.cfg-array__items{display:grid;gap:1px;background:var(--border)}.cfg-array__item{background:var(--panel)}.cfg-array__item-header{display:flex;align-items:center;justify-content:space-between;padding:12px 18px;background:var(--bg-accent);border-bottom:1px solid var(--border)}:root[data-theme=light] .cfg-array__item-header{background:var(--bg-hover)}.cfg-array__item-index{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.05em}.cfg-array__item-remove{width:30px;height:30px;display:flex;align-items:center;justify-content:center;border:none;border-radius:var(--radius-md);background:transparent;color:var(--muted);cursor:pointer;transition:background var(--duration-fast) ease,color var(--duration-fast) ease}.cfg-array__item-remove svg{width:16px;height:16px}.cfg-array__item-remove:hover:not(:disabled){background:var(--danger-subtle);color:var(--danger)}.cfg-array__item-remove:disabled{opacity:.4;cursor:not-allowed}.cfg-array__item-content{padding:18px}.cfg-map{border:1px solid var(--border);border-radius:var(--radius-lg);overflow:hidden}.cfg-map__header{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:14px 18px;background:var(--bg-accent);border-bottom:1px solid var(--border)}:root[data-theme=light] .cfg-map__header{background:var(--bg-hover)}.cfg-map__label{font-size:13px;font-weight:600;color:var(--muted)}.cfg-map__add{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border:1px solid var(--border);border-radius:var(--radius-md);background:var(--bg-elevated);color:var(--text);font-size:12px;font-weight:500;cursor:pointer;transition:background var(--duration-fast) ease}.cfg-map__add:hover:not(:disabled){background:var(--bg-hover)}.cfg-map__add-icon{width:14px;height:14px}.cfg-map__add-icon svg{width:100%;height:100%}.cfg-map__empty{padding:28px 18px;text-align:center;color:var(--muted);font-size:13px}.cfg-map__items{display:grid;gap:10px;padding:14px}.cfg-map__item{display:grid;grid-template-columns:150px 1fr auto;gap:10px;align-items:start}.cfg-map__item-key,.cfg-map__item-value{min-width:0}.cfg-map__item-remove{width:34px;height:34px;display:flex;align-items:center;justify-content:center;border:none;border-radius:var(--radius-md);background:transparent;color:var(--muted);cursor:pointer;transition:background var(--duration-fast) ease,color var(--duration-fast) ease}.cfg-map__item-remove svg{width:16px;height:16px}.cfg-map__item-remove:hover:not(:disabled){background:var(--danger-subtle);color:var(--danger)}.pill--sm{padding:5px 12px;font-size:11px}.pill--ok{border-color:#22c55e59;color:var(--ok)}.pill--danger{border-color:#ef444459;color:var(--danger)}@media(max-width:768px){.config-layout{grid-template-columns:1fr}.config-sidebar{border-right:none;border-bottom:1px solid var(--border)}.config-sidebar__header{padding:14px 16px}.config-nav{display:flex;flex-wrap:nowrap;gap:6px;padding:10px 14px;overflow-x:auto;-webkit-overflow-scrolling:touch}.config-nav__item{flex:0 0 auto;padding:9px 14px;white-space:nowrap}.config-nav__label{display:inline}.config-sidebar__footer{display:none}.config-actions{flex-wrap:wrap;padding:14px 16px}.config-actions__left,.config-actions__right{width:100%;justify-content:center}.config-section-hero{padding:14px 16px}.config-subnav{padding:10px 16px 12px}.config-content{padding:18px}.config-section-card__header{padding:16px 18px}.config-section-card__content{padding:18px}.cfg-toggle-row{padding:14px 16px}.cfg-map__item{grid-template-columns:1fr;gap:10px}.cfg-map__item-remove{justify-self:end}}@media(max-width:480px){.config-nav__icon{width:26px;height:26px;font-size:17px}.config-nav__label{display:none}.config-section-card__icon{width:30px;height:30px}.config-section-card__title{font-size:16px}.cfg-segmented{flex-wrap:wrap}.cfg-segmented__btn{flex:1 0 auto;min-width:70px}} diff --git a/dist/control-ui/assets/index-DQcOTEYz.js b/dist/control-ui/assets/index-DQcOTEYz.js new file mode 100644 index 000000000..e897319f1 --- /dev/null +++ b/dist/control-ui/assets/index-DQcOTEYz.js @@ -0,0 +1,3119 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function s(i){if(i.ep)return;i.ep=!0;const a=n(i);fetch(i.href,a)}})();const qt=globalThis,Ts=qt.ShadowRoot&&(qt.ShadyCSS===void 0||qt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Cs=Symbol(),Pi=new WeakMap;let qa=class{constructor(t,n,s){if(this._$cssResult$=!0,s!==Cs)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n}get styleSheet(){let t=this.o;const n=this.t;if(Ts&&t===void 0){const s=n!==void 0&&n.length===1;s&&(t=Pi.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Pi.set(n,t))}return t}toString(){return this.cssText}};const Or=e=>new qa(typeof e=="string"?e:e+"",void 0,Cs),Dr=(e,...t)=>{const n=e.length===1?e[0]:t.reduce((s,i,a)=>s+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[a+1],e[0]);return new qa(n,e,Cs)},Br=(e,t)=>{if(Ts)e.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(const n of t){const s=document.createElement("style"),i=qt.litNonce;i!==void 0&&s.setAttribute("nonce",i),s.textContent=n.cssText,e.appendChild(s)}},Ni=Ts?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let n="";for(const s of t.cssRules)n+=s.cssText;return Or(n)})(e):e;const{is:Fr,defineProperty:Ur,getOwnPropertyDescriptor:Kr,getOwnPropertyNames:Hr,getOwnPropertySymbols:zr,getPrototypeOf:jr}=Object,nn=globalThis,Oi=nn.trustedTypes,qr=Oi?Oi.emptyScript:"",Vr=nn.reactiveElementPolyfillSupport,bt=(e,t)=>e,Gt={toAttribute(e,t){switch(t){case Boolean:e=e?qr:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},Es=(e,t)=>!Fr(e,t),Di={attribute:!0,type:String,converter:Gt,reflect:!1,useDefault:!1,hasChanged:Es};Symbol.metadata??=Symbol("metadata"),nn.litPropertyMetadata??=new WeakMap;let Ye=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=Di){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){const s=Symbol(),i=this.getPropertyDescriptor(t,s,n);i!==void 0&&Ur(this.prototype,t,i)}}static getPropertyDescriptor(t,n,s){const{get:i,set:a}=Kr(this.prototype,t)??{get(){return this[n]},set(o){this[n]=o}};return{get:i,set(o){const c=i?.call(this);a?.call(this,o),this.requestUpdate(t,c,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Di}static _$Ei(){if(this.hasOwnProperty(bt("elementProperties")))return;const t=jr(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(bt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(bt("properties"))){const n=this.properties,s=[...Hr(n),...zr(n)];for(const i of s)this.createProperty(i,n[i])}const t=this[Symbol.metadata];if(t!==null){const n=litPropertyMetadata.get(t);if(n!==void 0)for(const[s,i]of n)this.elementProperties.set(s,i)}this._$Eh=new Map;for(const[n,s]of this.elementProperties){const i=this._$Eu(n,s);i!==void 0&&this._$Eh.set(i,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const n=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const i of s)n.unshift(Ni(i))}else t!==void 0&&n.push(Ni(t));return n}static _$Eu(t,n){const s=n.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,n=this.constructor.elementProperties;for(const s of n.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Br(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,n,s){this._$AK(t,s)}_$ET(t,n){const s=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,s);if(i!==void 0&&s.reflect===!0){const a=(s.converter?.toAttribute!==void 0?s.converter:Gt).toAttribute(n,s.type);this._$Em=t,a==null?this.removeAttribute(i):this.setAttribute(i,a),this._$Em=null}}_$AK(t,n){const s=this.constructor,i=s._$Eh.get(t);if(i!==void 0&&this._$Em!==i){const a=s.getPropertyOptions(i),o=typeof a.converter=="function"?{fromAttribute:a.converter}:a.converter?.fromAttribute!==void 0?a.converter:Gt;this._$Em=i;const c=o.fromAttribute(n,a.type);this[i]=c??this._$Ej?.get(i)??c,this._$Em=null}}requestUpdate(t,n,s,i=!1,a){if(t!==void 0){const o=this.constructor;if(i===!1&&(a=this[t]),s??=o.getPropertyOptions(t),!((s.hasChanged??Es)(a,n)||s.useDefault&&s.reflect&&a===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,s))))return;this.C(t,n,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,n,{useDefault:s,reflect:i,wrapped:a},o){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??n??this[t]),a!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(n=void 0),this._$AL.set(t,n)),i===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(n){Promise.reject(n)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[i,a]of this._$Ep)this[i]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[i,a]of s){const{wrapped:o}=a,c=this[i];o!==!0||this._$AL.has(i)||c===void 0||this.C(i,void 0,a,c)}}let t=!1;const n=this._$AL;try{t=this.shouldUpdate(n),t?(this.willUpdate(n),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(n)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(n)}willUpdate(t){}_$AE(t){this._$EO?.forEach(n=>n.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(n=>this._$ET(n,this[n])),this._$EM()}updated(t){}firstUpdated(t){}};Ye.elementStyles=[],Ye.shadowRootOptions={mode:"open"},Ye[bt("elementProperties")]=new Map,Ye[bt("finalized")]=new Map,Vr?.({ReactiveElement:Ye}),(nn.reactiveElementVersions??=[]).push("2.1.2");const Ls=globalThis,Bi=e=>e,Yt=Ls.trustedTypes,Fi=Yt?Yt.createPolicy("lit-html",{createHTML:e=>e}):void 0,Va="$lit$",xe=`lit$${Math.random().toFixed(9).slice(2)}$`,Wa="?"+xe,Wr=`<${Wa}>`,Oe=document,$t=()=>Oe.createComment(""),xt=e=>e===null||typeof e!="object"&&typeof e!="function",Ms=Array.isArray,Gr=e=>Ms(e)||typeof e?.[Symbol.iterator]=="function",On=`[ +\f\r]`,rt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ui=/-->/g,Ki=/>/g,Le=RegExp(`>|${On}(?:([^\\s"'>=/]+)(${On}*=${On}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),Hi=/'/g,zi=/"/g,Ga=/^(?:script|style|textarea|title)$/i,Yr=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),r=Yr(1),Se=Symbol.for("lit-noChange"),g=Symbol.for("lit-nothing"),ji=new WeakMap,Pe=Oe.createTreeWalker(Oe,129);function Ya(e,t){if(!Ms(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Fi!==void 0?Fi.createHTML(t):t}const Qr=(e,t)=>{const n=e.length-1,s=[];let i,a=t===2?"":t===3?"":"",o=rt;for(let c=0;c"?(o=i??rt,u=-1):d[1]===void 0?u=-2:(u=o.lastIndex-d[2].length,p=d[1],o=d[3]===void 0?Le:d[3]==='"'?zi:Hi):o===zi||o===Hi?o=Le:o===Ui||o===Ki?o=rt:(o=Le,i=void 0);const v=o===Le&&e[c+1].startsWith("/>")?" ":"";a+=o===rt?l+Wr:u>=0?(s.push(p),l.slice(0,u)+Va+l.slice(u)+xe+v):l+xe+(u===-2?c:v)}return[Ya(e,a+(e[n]||"")+(t===2?"":t===3?"":"")),s]};let ts=class Qa{constructor({strings:t,_$litType$:n},s){let i;this.parts=[];let a=0,o=0;const c=t.length-1,l=this.parts,[p,d]=Qr(t,n);if(this.el=Qa.createElement(p,s),Pe.currentNode=this.el.content,n===2||n===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(i=Pe.nextNode())!==null&&l.length0){i.textContent=Yt?Yt.emptyScript:"";for(let v=0;v2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=g}_$AI(t,n=this,s,i){const a=this.strings;let o=!1;if(a===void 0)t=Je(this,t,n,0),o=!xt(t)||t!==this._$AH&&t!==Se,o&&(this._$AH=t);else{const c=t;let l,p;for(t=a[0],l=0;l{const s=n?.renderBefore??t;let i=s._$litPart$;if(i===void 0){const a=n?.renderBefore??null;s._$litPart$=i=new sn(t.insertBefore($t(),a),a,void 0,n??{})}return i._$AI(e),i};const Is=globalThis;let Ze=class extends Ye{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const n=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=il(n,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Se}};Ze._$litElement$=!0,Ze.finalized=!0,Is.litElementHydrateSupport?.({LitElement:Ze});const al=Is.litElementPolyfillSupport;al?.({LitElement:Ze});(Is.litElementVersions??=[]).push("4.2.2");const Ja=e=>(t,n)=>{n!==void 0?n.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const ol={attribute:!0,type:String,converter:Gt,reflect:!1,hasChanged:Es},rl=(e=ol,t,n)=>{const{kind:s,metadata:i}=n;let a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),s==="accessor"){const{name:o}=n;return{set(c){const l=t.get.call(this);t.set.call(this,c),this.requestUpdate(o,l,e,!0,c)},init(c){return c!==void 0&&this.C(o,void 0,e,c),c}}}if(s==="setter"){const{name:o}=n;return function(c){const l=this[o];t.call(this,c),this.requestUpdate(o,l,e,!0,c)}}throw Error("Unsupported decorator location: "+s)};function on(e){return(t,n)=>typeof n=="object"?rl(e,t,n):((s,i,a)=>{const o=i.hasOwnProperty(a);return i.constructor.createProperty(a,s),o?Object.getOwnPropertyDescriptor(i,a):void 0})(e,t,n)}function y(e){return on({...e,state:!0,attribute:!1})}const ll=50,cl=200,dl="Assistant";function qi(e,t){if(typeof e!="string")return;const n=e.trim();if(n)return n.length<=t?n:n.slice(0,t)}function ns(e){const t=qi(e?.name,ll)??dl,n=qi(e?.avatar??void 0,cl)??null;return{agentId:typeof e?.agentId=="string"&&e.agentId.trim()?e.agentId.trim():null,name:t,avatar:n}}function ul(){return ns(typeof window>"u"?{}:{name:window.__CLAWDBOT_ASSISTANT_NAME__,avatar:window.__CLAWDBOT_ASSISTANT_AVATAR__})}const Xa="clawdbot.control.settings.v1";function pl(){const t={gatewayUrl:`${location.protocol==="https:"?"wss":"ws"}://${location.host}`,token:"",sessionKey:"main",lastActiveSessionKey:"main",theme:"system",chatFocusMode:!1,chatShowThinking:!0,splitRatio:.6,navCollapsed:!1,navGroupsCollapsed:{}};try{const n=localStorage.getItem(Xa);if(!n)return t;const s=JSON.parse(n);return{gatewayUrl:typeof s.gatewayUrl=="string"&&s.gatewayUrl.trim()?s.gatewayUrl.trim():t.gatewayUrl,token:typeof s.token=="string"?s.token:t.token,sessionKey:typeof s.sessionKey=="string"&&s.sessionKey.trim()?s.sessionKey.trim():t.sessionKey,lastActiveSessionKey:typeof s.lastActiveSessionKey=="string"&&s.lastActiveSessionKey.trim()?s.lastActiveSessionKey.trim():typeof s.sessionKey=="string"&&s.sessionKey.trim()||t.lastActiveSessionKey,theme:s.theme==="light"||s.theme==="dark"||s.theme==="system"?s.theme:t.theme,chatFocusMode:typeof s.chatFocusMode=="boolean"?s.chatFocusMode:t.chatFocusMode,chatShowThinking:typeof s.chatShowThinking=="boolean"?s.chatShowThinking:t.chatShowThinking,splitRatio:typeof s.splitRatio=="number"&&s.splitRatio>=.4&&s.splitRatio<=.7?s.splitRatio:t.splitRatio,navCollapsed:typeof s.navCollapsed=="boolean"?s.navCollapsed:t.navCollapsed,navGroupsCollapsed:typeof s.navGroupsCollapsed=="object"&&s.navGroupsCollapsed!==null?s.navGroupsCollapsed:t.navGroupsCollapsed}}catch{return t}}function fl(e){localStorage.setItem(Xa,JSON.stringify(e))}function eo(e){const t=(e??"").trim();if(!t)return null;const n=t.split(":").filter(Boolean);if(n.length<3||n[0]!=="agent")return null;const s=n[1]?.trim(),i=n.slice(2).join(":");return!s||!i?null:{agentId:s,rest:i}}const hl=[{label:"Chat",tabs:["chat"]},{label:"Control",tabs:["overview","channels","instances","sessions","cron"]},{label:"Agent",tabs:["skills","nodes"]},{label:"Settings",tabs:["config","debug","logs"]}],to={overview:"/overview",channels:"/channels",instances:"/instances",sessions:"/sessions",cron:"/cron",skills:"/skills",nodes:"/nodes",chat:"/chat",config:"/config",debug:"/debug",logs:"/logs"},no=new Map(Object.entries(to).map(([e,t])=>[t,e]));function rn(e){if(!e)return"";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t==="/"?"":(t.endsWith("/")&&(t=t.slice(0,-1)),t)}function kt(e){if(!e)return"/";let t=e.trim();return t.startsWith("/")||(t=`/${t}`),t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t}function Rs(e,t=""){const n=rn(t),s=to[e];return n?`${n}${s}`:s}function so(e,t=""){const n=rn(t);let s=e||"/";n&&(s===n?s="/":s.startsWith(`${n}/`)&&(s=s.slice(n.length)));let i=kt(s).toLowerCase();return i.endsWith("/index.html")&&(i="/"),i==="/"?"chat":no.get(i)??null}function gl(e){let t=kt(e);if(t.endsWith("/index.html")&&(t=kt(t.slice(0,-11))),t==="/")return"";const n=t.split("/").filter(Boolean);if(n.length===0)return"";for(let s=0;s`,barChart:r``,link:r``,radio:r``,fileText:r``,zap:r``,monitor:r``,settings:r``,bug:r``,scrollText:r``,folder:r``,menu:r``,x:r``,check:r``,copy:r``,search:r``,brain:r``,book:r``,loader:r``,wrench:r``,fileCode:r``,edit:r``,penLine:r``,paperclip:r``,globe:r``,image:r``,smartphone:r``,plug:r``,circle:r``,puzzle:r``},bl=/<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i,Dt=/<\s*\/?\s*final\b[^>]*>/gi,Vi=/<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^>]*>/gi;function yl(e,t){return e.trimStart()}function wl(e,t){if(!e||!bl.test(e))return e;let n=e;Dt.test(n)?(Dt.lastIndex=0,n=n.replace(Dt,"")):Dt.lastIndex=0,Vi.lastIndex=0;let s="",i=0,a=!1;for(const o of n.matchAll(Vi)){const c=o.index??0,l=o[1]==="/";a?l&&(a=!1):(s+=n.slice(i,c),l||(a=!0)),i=c+o[0].length}return s+=n.slice(i),yl(s)}function At(e){return!e&&e!==0?"n/a":new Date(e).toLocaleString()}function O(e){if(!e&&e!==0)return"n/a";const t=Date.now()-e;if(t<0)return"just now";const n=Math.round(t/1e3);if(n<60)return`${n}s ago`;const s=Math.round(n/60);if(s<60)return`${s}m ago`;const i=Math.round(s/60);return i<48?`${i}h ago`:`${Math.round(i/24)}d ago`}function io(e){if(!e&&e!==0)return"n/a";if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.round(t/60);if(n<60)return`${n}m`;const s=Math.round(n/60);return s<48?`${s}h`:`${Math.round(s/24)}d`}function is(e){return!e||e.length===0?"none":e.filter(t=>!!(t&&t.trim())).join(", ")}function as(e,t=120){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}…`}function ao(e,t){return e.length<=t?{text:e,truncated:!1,total:e.length}:{text:e.slice(0,Math.max(0,t)),truncated:!0,total:e.length}}function Qt(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function Dn(e){return wl(e)}const $l=/^\[([^\]]+)\]\s*/,xl=["WebChat","WhatsApp","Telegram","Signal","Slack","Discord","iMessage","Teams","Matrix","Zalo","Zalo Personal","BlueBubbles"],Bn=new WeakMap,Fn=new WeakMap;function kl(e){return/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z\b/.test(e)||/\d{4}-\d{2}-\d{2} \d{2}:\d{2}\b/.test(e)?!0:xl.some(t=>e.startsWith(`${t} `))}function Un(e){const t=e.match($l);if(!t)return e;const n=t[1]??"";return kl(n)?e.slice(t[0].length):e}function os(e){const t=e,n=typeof t.role=="string"?t.role:"",s=t.content;if(typeof s=="string")return n==="assistant"?Dn(s):Un(s);if(Array.isArray(s)){const i=s.map(a=>{const o=a;return o.type==="text"&&typeof o.text=="string"?o.text:null}).filter(a=>typeof a=="string");if(i.length>0){const a=i.join(` +`);return n==="assistant"?Dn(a):Un(a)}}return typeof t.text=="string"?n==="assistant"?Dn(t.text):Un(t.text):null}function oo(e){if(!e||typeof e!="object")return os(e);const t=e;if(Bn.has(t))return Bn.get(t)??null;const n=os(e);return Bn.set(t,n),n}function Wi(e){const n=e.content,s=[];if(Array.isArray(n))for(const c of n){const l=c;if(l.type==="thinking"&&typeof l.thinking=="string"){const p=l.thinking.trim();p&&s.push(p)}}if(s.length>0)return s.join(` +`);const i=Sl(e);if(!i)return null;const o=[...i.matchAll(/<\s*think(?:ing)?\s*>([\s\S]*?)<\s*\/\s*think(?:ing)?\s*>/gi)].map(c=>(c[1]??"").trim()).filter(Boolean);return o.length>0?o.join(` +`):null}function Al(e){if(!e||typeof e!="object")return Wi(e);const t=e;if(Fn.has(t))return Fn.get(t)??null;const n=Wi(e);return Fn.set(t,n),n}function Sl(e){const t=e,n=t.content;if(typeof n=="string")return n;if(Array.isArray(n)){const s=n.map(i=>{const a=i;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(i=>typeof i=="string");if(s.length>0)return s.join(` +`)}return typeof t.text=="string"?t.text:null}function _l(e){const t=e.trim();if(!t)return"";const n=t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).map(s=>`_${s}_`);return n.length?["_Reasoning:_",...n].join(` +`):""}function Gi(e){e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n>>8&255,e[2]^=t>>>16&255,e[3]^=t>>>24&255,e}function Ps(e=globalThis.crypto){if(e&&typeof e.randomUUID=="function")return e.randomUUID();if(e&&typeof e.getRandomValues=="function"){const t=new Uint8Array(16);return e.getRandomValues(t),Gi(t)}return Gi(Tl())}async function Xe(e){if(!(!e.client||!e.connected)){e.chatLoading=!0,e.lastError=null;try{const t=await e.client.request("chat.history",{sessionKey:e.sessionKey,limit:200});e.chatMessages=Array.isArray(t.messages)?t.messages:[],e.chatThinkingLevel=t.thinkingLevel??null}catch(t){e.lastError=String(t)}finally{e.chatLoading=!1}}}async function Cl(e,t){if(!e.client||!e.connected)return!1;const n=t.trim();if(!n)return!1;const s=Date.now();e.chatMessages=[...e.chatMessages,{role:"user",content:[{type:"text",text:n}],timestamp:s}],e.chatSending=!0,e.lastError=null;const i=Ps();e.chatRunId=i,e.chatStream="",e.chatStreamStartedAt=s;try{return await e.client.request("chat.send",{sessionKey:e.sessionKey,message:n,deliver:!1,idempotencyKey:i}),!0}catch(a){const o=String(a);return e.chatRunId=null,e.chatStream=null,e.chatStreamStartedAt=null,e.lastError=o,e.chatMessages=[...e.chatMessages,{role:"assistant",content:[{type:"text",text:"Error: "+o}],timestamp:Date.now()}],!1}finally{e.chatSending=!1}}async function El(e){if(!e.client||!e.connected)return!1;const t=e.chatRunId;try{return await e.client.request("chat.abort",t?{sessionKey:e.sessionKey,runId:t}:{sessionKey:e.sessionKey}),!0}catch(n){return e.lastError=String(n),!1}}function Ll(e,t){if(!t||t.sessionKey!==e.sessionKey||t.runId&&e.chatRunId&&t.runId!==e.chatRunId)return null;if(t.state==="delta"){const n=os(t.message);if(typeof n=="string"){const s=e.chatStream??"";(!s||n.length>=s.length)&&(e.chatStream=n)}}else t.state==="final"||t.state==="aborted"?(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null):t.state==="error"&&(e.chatStream=null,e.chatRunId=null,e.chatStreamStartedAt=null,e.lastError=t.errorMessage??"chat error");return t.state}async function st(e){if(!(!e.client||!e.connected)&&!e.sessionsLoading){e.sessionsLoading=!0,e.sessionsError=null;try{const t={includeGlobal:e.sessionsIncludeGlobal,includeUnknown:e.sessionsIncludeUnknown},n=Qt(e.sessionsFilterActive,0),s=Qt(e.sessionsFilterLimit,0);n>0&&(t.activeMinutes=n),s>0&&(t.limit=s);const i=await e.client.request("sessions.list",t);i&&(e.sessionsResult=i)}catch(t){e.sessionsError=String(t)}finally{e.sessionsLoading=!1}}}async function Ml(e,t,n){if(!e.client||!e.connected)return;const s={key:t};"label"in n&&(s.label=n.label),"thinkingLevel"in n&&(s.thinkingLevel=n.thinkingLevel),"verboseLevel"in n&&(s.verboseLevel=n.verboseLevel),"reasoningLevel"in n&&(s.reasoningLevel=n.reasoningLevel);try{await e.client.request("sessions.patch",s),await st(e)}catch(i){e.sessionsError=String(i)}}async function Il(e,t){if(!(!e.client||!e.connected||e.sessionsLoading||!window.confirm(`Delete session "${t}"? + +Deletes the session entry and archives its transcript.`))){e.sessionsLoading=!0,e.sessionsError=null;try{await e.client.request("sessions.delete",{key:t,deleteTranscript:!0}),await st(e)}catch(s){e.sessionsError=String(s)}finally{e.sessionsLoading=!1}}}const Yi=50,Rl=80,Pl=12e4;function Nl(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.text=="string")return t.text;const n=t.content;if(!Array.isArray(n))return null;const s=n.map(i=>{if(!i||typeof i!="object")return null;const a=i;return a.type==="text"&&typeof a.text=="string"?a.text:null}).filter(i=>!!i);return s.length===0?null:s.join(` +`)}function Qi(e){if(e==null)return null;if(typeof e=="number"||typeof e=="boolean")return String(e);const t=Nl(e);let n;if(typeof e=="string")n=e;else if(t)n=t;else try{n=JSON.stringify(e,null,2)}catch{n=String(e)}const s=ao(n,Pl);return s.truncated?`${s.text} + +… truncated (${s.total} chars, showing first ${s.text.length}).`:s.text}function Ol(e){const t=[];return t.push({type:"toolcall",name:e.name,arguments:e.args??{}}),e.output&&t.push({type:"toolresult",name:e.name,text:e.output}),{role:"assistant",toolCallId:e.toolCallId,runId:e.runId,content:t,timestamp:e.startedAt}}function Dl(e){if(e.toolStreamOrder.length<=Yi)return;const t=e.toolStreamOrder.length-Yi,n=e.toolStreamOrder.splice(0,t);for(const s of n)e.toolStreamById.delete(s)}function Bl(e){e.chatToolMessages=e.toolStreamOrder.map(t=>e.toolStreamById.get(t)?.message).filter(t=>!!t)}function rs(e){e.toolStreamSyncTimer!=null&&(clearTimeout(e.toolStreamSyncTimer),e.toolStreamSyncTimer=null),Bl(e)}function Fl(e,t=!1){if(t){rs(e);return}e.toolStreamSyncTimer==null&&(e.toolStreamSyncTimer=window.setTimeout(()=>rs(e),Rl))}function Ns(e){e.toolStreamById.clear(),e.toolStreamOrder=[],e.chatToolMessages=[],rs(e)}const Ul=5e3;function Kl(e,t){const n=t.data??{},s=typeof n.phase=="string"?n.phase:"";e.compactionClearTimer!=null&&(window.clearTimeout(e.compactionClearTimer),e.compactionClearTimer=null),s==="start"?e.compactionStatus={active:!0,startedAt:Date.now(),completedAt:null}:s==="end"&&(e.compactionStatus={active:!1,startedAt:e.compactionStatus?.startedAt??null,completedAt:Date.now()},e.compactionClearTimer=window.setTimeout(()=>{e.compactionStatus=null,e.compactionClearTimer=null},Ul))}function Hl(e,t){if(!t)return;if(t.stream==="compaction"){Kl(e,t);return}if(t.stream!=="tool")return;const n=typeof t.sessionKey=="string"?t.sessionKey:void 0;if(n&&n!==e.sessionKey||!n&&e.chatRunId&&t.runId!==e.chatRunId||e.chatRunId&&t.runId!==e.chatRunId||!e.chatRunId)return;const s=t.data??{},i=typeof s.toolCallId=="string"?s.toolCallId:"";if(!i)return;const a=typeof s.name=="string"?s.name:"tool",o=typeof s.phase=="string"?s.phase:"",c=o==="start"?s.args:void 0,l=o==="update"?Qi(s.partialResult):o==="result"?Qi(s.result):void 0,p=Date.now();let d=e.toolStreamById.get(i);d?(d.name=a,c!==void 0&&(d.args=c),l!==void 0&&(d.output=l),d.updatedAt=p):(d={toolCallId:i,runId:t.runId,sessionKey:n,name:a,args:c,output:l,startedAt:typeof t.ts=="number"?t.ts:p,updatedAt:p,message:{}},e.toolStreamById.set(i,d),e.toolStreamOrder.push(i)),d.message=Ol(d),Dl(e),Fl(e,o==="result")}function ln(e,t=!1){e.chatScrollFrame&&cancelAnimationFrame(e.chatScrollFrame),e.chatScrollTimeout!=null&&(clearTimeout(e.chatScrollTimeout),e.chatScrollTimeout=null);const n=()=>{const s=e.querySelector(".chat-thread");if(s){const i=getComputedStyle(s).overflowY;if(i==="auto"||i==="scroll"||s.scrollHeight-s.clientHeight>1)return s}return document.scrollingElement??document.documentElement};e.updateComplete.then(()=>{e.chatScrollFrame=requestAnimationFrame(()=>{e.chatScrollFrame=null;const s=n();if(!s)return;const i=s.scrollHeight-s.scrollTop-s.clientHeight;if(!(t||e.chatUserNearBottom||i<200))return;t&&(e.chatHasAutoScrolled=!0),s.scrollTop=s.scrollHeight,e.chatUserNearBottom=!0;const o=t?150:120;e.chatScrollTimeout=window.setTimeout(()=>{e.chatScrollTimeout=null;const c=n();if(!c)return;const l=c.scrollHeight-c.scrollTop-c.clientHeight;(t||e.chatUserNearBottom||l<200)&&(c.scrollTop=c.scrollHeight,e.chatUserNearBottom=!0)},o)})})}function ro(e,t=!1){e.logsScrollFrame&&cancelAnimationFrame(e.logsScrollFrame),e.updateComplete.then(()=>{e.logsScrollFrame=requestAnimationFrame(()=>{e.logsScrollFrame=null;const n=e.querySelector(".log-stream");if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;(t||s<80)&&(n.scrollTop=n.scrollHeight)})})}function zl(e,t){const n=t.currentTarget;if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;e.chatUserNearBottom=s<200}function jl(e,t){const n=t.currentTarget;if(!n)return;const s=n.scrollHeight-n.scrollTop-n.clientHeight;e.logsAtBottom=s<80}function ql(e){e.chatHasAutoScrolled=!1,e.chatUserNearBottom=!0}function Vl(e,t){if(e.length===0)return;const n=new Blob([`${e.join(` +`)} +`],{type:"text/plain"}),s=URL.createObjectURL(n),i=document.createElement("a"),a=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");i.href=s,i.download=`clawdbot-logs-${t}-${a}.log`,i.click(),URL.revokeObjectURL(s)}function Wl(e){if(typeof ResizeObserver>"u")return;const t=e.querySelector(".topbar");if(!t)return;const n=()=>{const{height:s}=t.getBoundingClientRect();e.style.setProperty("--topbar-height",`${s}px`)};n(),e.topbarObserver=new ResizeObserver(()=>n()),e.topbarObserver.observe(t)}function De(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}function et(e){return`${JSON.stringify(e,null,2).trimEnd()} +`}function lo(e,t,n){if(t.length===0)return;let s=e;for(let a=0;a0&&(n.timeoutSeconds=s),n}async function ec(e){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{const t=Jl(e.cronForm),n=Xl(e.cronForm),s=e.cronForm.agentId.trim(),i={name:e.cronForm.name.trim(),description:e.cronForm.description.trim()||void 0,agentId:s||void 0,enabled:e.cronForm.enabled,schedule:t,sessionTarget:e.cronForm.sessionTarget,wakeMode:e.cronForm.wakeMode,payload:n,isolation:e.cronForm.postToMainPrefix.trim()&&e.cronForm.sessionTarget==="isolated"?{postToMainPrefix:e.cronForm.postToMainPrefix.trim()}:void 0};if(!i.name)throw new Error("Name required.");await e.client.request("cron.add",i),e.cronForm={...e.cronForm,name:"",description:"",payloadText:""},await cn(e),await Tt(e)}catch(t){e.cronError=String(t)}finally{e.cronBusy=!1}}}async function tc(e,t,n){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.update",{id:t.id,patch:{enabled:n}}),await cn(e),await Tt(e)}catch(s){e.cronError=String(s)}finally{e.cronBusy=!1}}}async function nc(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.run",{id:t.id,mode:"force"}),await po(e,t.id)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function sc(e,t){if(!(!e.client||!e.connected||e.cronBusy)){e.cronBusy=!0,e.cronError=null;try{await e.client.request("cron.remove",{id:t.id}),e.cronRunsJobId===t.id&&(e.cronRunsJobId=null,e.cronRuns=[]),await cn(e),await Tt(e)}catch(n){e.cronError=String(n)}finally{e.cronBusy=!1}}}async function po(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("cron.runs",{id:t,limit:50});e.cronRunsJobId=t,e.cronRuns=Array.isArray(n.entries)?n.entries:[]}catch(n){e.cronError=String(n)}}async function oe(e,t){if(!(!e.client||!e.connected)&&!e.channelsLoading){e.channelsLoading=!0,e.channelsError=null;try{const n=await e.client.request("channels.status",{probe:t,timeoutMs:8e3});e.channelsSnapshot=n,e.channelsLastSuccess=Date.now()}catch(n){e.channelsError=String(n)}finally{e.channelsLoading=!1}}}async function ic(e,t){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{const n=await e.client.request("web.login.start",{force:t,timeoutMs:3e4});e.whatsappLoginMessage=n.message??null,e.whatsappLoginQrDataUrl=n.qrDataUrl??null,e.whatsappLoginConnected=null}catch(n){e.whatsappLoginMessage=String(n),e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null}finally{e.whatsappBusy=!1}}}async function ac(e){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{const t=await e.client.request("web.login.wait",{timeoutMs:12e4});e.whatsappLoginMessage=t.message??null,e.whatsappLoginConnected=t.connected??null,t.connected&&(e.whatsappLoginQrDataUrl=null)}catch(t){e.whatsappLoginMessage=String(t),e.whatsappLoginConnected=null}finally{e.whatsappBusy=!1}}}async function oc(e){if(!(!e.client||!e.connected||e.whatsappBusy)){e.whatsappBusy=!0;try{await e.client.request("channels.logout",{channel:"whatsapp"}),e.whatsappLoginMessage="Logged out.",e.whatsappLoginQrDataUrl=null,e.whatsappLoginConnected=null}catch(t){e.whatsappLoginMessage=String(t)}finally{e.whatsappBusy=!1}}}async function dn(e){if(!(!e.client||!e.connected)&&!e.debugLoading){e.debugLoading=!0;try{const[t,n,s,i]=await Promise.all([e.client.request("status",{}),e.client.request("health",{}),e.client.request("models.list",{}),e.client.request("last-heartbeat",{})]);e.debugStatus=t,e.debugHealth=n;const a=s;e.debugModels=Array.isArray(a?.models)?a?.models:[],e.debugHeartbeat=i}catch(t){e.debugCallError=String(t)}finally{e.debugLoading=!1}}}async function rc(e){if(!(!e.client||!e.connected)){e.debugCallError=null,e.debugCallResult=null;try{const t=e.debugCallParams.trim()?JSON.parse(e.debugCallParams):{},n=await e.client.request(e.debugCallMethod.trim(),t);e.debugCallResult=JSON.stringify(n,null,2)}catch(t){e.debugCallError=String(t)}}}const lc=2e3,cc=new Set(["trace","debug","info","warn","error","fatal"]);function dc(e){if(typeof e!="string")return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);return!n||typeof n!="object"?null:n}catch{return null}}function uc(e){if(typeof e!="string")return null;const t=e.toLowerCase();return cc.has(t)?t:null}function pc(e){if(!e.trim())return{raw:e,message:e};try{const t=JSON.parse(e),n=t&&typeof t._meta=="object"&&t._meta!==null?t._meta:null,s=typeof t.time=="string"?t.time:typeof n?.date=="string"?n?.date:null,i=uc(n?.logLevelName??n?.level),a=typeof t[0]=="string"?t[0]:typeof n?.name=="string"?n?.name:null,o=dc(a);let c=null;o&&(typeof o.subsystem=="string"?c=o.subsystem:typeof o.module=="string"&&(c=o.module)),!c&&a&&a.length<120&&(c=a);let l=null;return typeof t[1]=="string"?l=t[1]:!o&&typeof t[0]=="string"?l=t[0]:typeof t.message=="string"&&(l=t.message),{raw:e,time:s,level:i,subsystem:c,message:l??e,meta:n??void 0}}catch{return{raw:e,message:e}}}async function Os(e,t){if(!(!e.client||!e.connected)&&!(e.logsLoading&&!t?.quiet)){t?.quiet||(e.logsLoading=!0),e.logsError=null;try{const s=await e.client.request("logs.tail",{cursor:t?.reset?void 0:e.logsCursor??void 0,limit:e.logsLimit,maxBytes:e.logsMaxBytes}),a=(Array.isArray(s.lines)?s.lines.filter(c=>typeof c=="string"):[]).map(pc),o=!!(t?.reset||s.reset||e.logsCursor==null);e.logsEntries=o?a:[...e.logsEntries,...a].slice(-lc),typeof s.cursor=="number"&&(e.logsCursor=s.cursor),typeof s.file=="string"&&(e.logsFile=s.file),e.logsTruncated=!!s.truncated,e.logsLastFetchAt=Date.now()}catch(n){e.logsError=String(n)}finally{t?.quiet||(e.logsLoading=!1)}}}const fo={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:V,n:Vt,Gx:Ji,Gy:Xi,a:Kn,d:Hn,h:fc}=fo,Be=32,Ds=64,hc=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},H=(e="")=>{const t=new Error(e);throw hc(t,H),t},gc=e=>typeof e=="bigint",vc=e=>typeof e=="string",mc=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",_e=(e,t,n="")=>{const s=mc(e),i=e?.length,a=t!==void 0;if(!s||a&&i!==t){const o=n&&`"${n}" `,c=a?` of length ${t}`:"",l=s?`length=${i}`:`type=${typeof e}`;H(o+"expected Uint8Array"+c+", got "+l)}return e},un=e=>new Uint8Array(e),ho=e=>Uint8Array.from(e),go=(e,t)=>e.toString(16).padStart(t,"0"),vo=e=>Array.from(_e(e)).map(t=>go(t,2)).join(""),ve={_0:48,_9:57,A:65,F:70,a:97,f:102},ea=e=>{if(e>=ve._0&&e<=ve._9)return e-ve._0;if(e>=ve.A&&e<=ve.F)return e-(ve.A-10);if(e>=ve.a&&e<=ve.f)return e-(ve.a-10)},mo=e=>{const t="hex invalid";if(!vc(e))return H(t);const n=e.length,s=n/2;if(n%2)return H(t);const i=un(s);for(let a=0,o=0;aglobalThis?.crypto,bc=()=>bo()?.subtle??H("crypto.subtle must be defined, consider polyfill"),St=(...e)=>{const t=un(e.reduce((s,i)=>s+_e(i).length,0));let n=0;return e.forEach(s=>{t.set(s,n),n+=s.length}),t},yc=(e=Be)=>bo().getRandomValues(un(e)),Zt=BigInt,Re=(e,t,n,s="bad number: out of range")=>gc(e)&&t<=e&&e{const n=e%t;return n>=0n?n:t+n},yo=e=>A(e,Vt),wc=(e,t)=>{(e===0n||t<=0n)&&H("no inverse n="+e+" mod="+t);let n=A(e,t),s=t,i=0n,a=1n;for(;n!==0n;){const o=s/n,c=s%n,l=i-a*o;s=n,n=c,i=a,a=l}return s===1n?A(i,t):H("no inverse")},$c=e=>{const t=ko[e];return typeof t!="function"&&H("hashes."+e+" not set"),t},zn=e=>e instanceof ee?e:H("Point expected"),cs=2n**256n;class ee{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,s,i){const a=cs;this.X=Re(t,0n,a),this.Y=Re(n,0n,a),this.Z=Re(s,1n,a),this.T=Re(i,0n,a),Object.freeze(this)}static CURVE(){return fo}static fromAffine(t){return new ee(t.x,t.y,1n,A(t.x*t.y))}static fromBytes(t,n=!1){const s=Hn,i=ho(_e(t,Be)),a=t[31];i[31]=a&-129;const o=$o(i);Re(o,0n,n?cs:V);const l=A(o*o),p=A(l-1n),d=A(s*l+1n);let{isValid:u,value:h}=kc(p,d);u||H("bad point: y not sqrt");const v=(h&1n)===1n,w=(a&128)!==0;return!n&&h===0n&&w&&H("bad point: x==0, isLastByteOdd"),w!==v&&(h=A(-h)),new ee(h,o,1n,A(h*o))}static fromHex(t,n){return ee.fromBytes(mo(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){const t=Kn,n=Hn,s=this;if(s.is0())return H("bad point: ZERO");const{X:i,Y:a,Z:o,T:c}=s,l=A(i*i),p=A(a*a),d=A(o*o),u=A(d*d),h=A(l*t),v=A(d*A(h+p)),w=A(u+A(n*A(l*p)));if(v!==w)return H("bad point: equation left != right (1)");const $=A(i*a),k=A(o*c);return $!==k?H("bad point: equation left != right (2)"):this}equals(t){const{X:n,Y:s,Z:i}=this,{X:a,Y:o,Z:c}=zn(t),l=A(n*c),p=A(a*i),d=A(s*c),u=A(o*i);return l===p&&d===u}is0(){return this.equals(Qe)}negate(){return new ee(A(-this.X),this.Y,this.Z,A(-this.T))}double(){const{X:t,Y:n,Z:s}=this,i=Kn,a=A(t*t),o=A(n*n),c=A(2n*A(s*s)),l=A(i*a),p=t+n,d=A(A(p*p)-a-o),u=l+o,h=u-c,v=l-o,w=A(d*h),$=A(u*v),k=A(d*v),T=A(h*u);return new ee(w,$,T,k)}add(t){const{X:n,Y:s,Z:i,T:a}=this,{X:o,Y:c,Z:l,T:p}=zn(t),d=Kn,u=Hn,h=A(n*o),v=A(s*c),w=A(a*u*p),$=A(i*l),k=A((n+s)*(o+c)-h-v),T=A($-w),M=A($+w),P=A(v-d*h),L=A(k*T),C=A(M*P),E=A(k*P),pe=A(T*M);return new ee(L,C,pe,E)}subtract(t){return this.add(zn(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return Qe;if(Re(t,1n,Vt),t===1n)return this;if(this.equals(Fe))return Pc(t).p;let s=Qe,i=Fe;for(let a=this;t>0n;a=a.double(),t>>=1n)t&1n?s=s.add(a):n&&(i=i.add(a));return s}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){const{X:t,Y:n,Z:s}=this;if(this.equals(Qe))return{x:0n,y:1n};const i=wc(s,V);A(s*i)!==1n&&H("invalid inverse");const a=A(t*i),o=A(n*i);return{x:a,y:o}}toBytes(){const{x:t,y:n}=this.assertValidity().toAffine(),s=wo(n);return s[31]|=t&1n?128:0,s}toHex(){return vo(this.toBytes())}clearCofactor(){return this.multiply(Zt(fc),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Vt/2n,!1).double();return Vt%2n&&(t=t.add(this)),t.is0()}}const Fe=new ee(Ji,Xi,1n,A(Ji*Xi)),Qe=new ee(0n,1n,1n,0n);ee.BASE=Fe;ee.ZERO=Qe;const wo=e=>mo(go(Re(e,0n,cs),Ds)).reverse(),$o=e=>Zt("0x"+vo(ho(_e(e)).reverse())),ce=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=V;return n},xc=e=>{const n=e*e%V*e%V,s=ce(n,2n)*n%V,i=ce(s,1n)*e%V,a=ce(i,5n)*i%V,o=ce(a,10n)*a%V,c=ce(o,20n)*o%V,l=ce(c,40n)*c%V,p=ce(l,80n)*l%V,d=ce(p,80n)*l%V,u=ce(d,10n)*a%V;return{pow_p_5_8:ce(u,2n)*e%V,b2:n}},ta=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,kc=(e,t)=>{const n=A(t*t*t),s=A(n*n*t),i=xc(e*s).pow_p_5_8;let a=A(e*n*i);const o=A(t*a*a),c=a,l=A(a*ta),p=o===e,d=o===A(-e),u=o===A(-e*ta);return p&&(a=c),(d||u)&&(a=l),(A(a)&1n)===1n&&(a=A(-a)),{isValid:p||d,value:a}},ds=e=>yo($o(e)),Bs=(...e)=>ko.sha512Async(St(...e)),Ac=(...e)=>$c("sha512")(St(...e)),xo=e=>{const t=e.slice(0,Be);t[0]&=248,t[31]&=127,t[31]|=64;const n=e.slice(Be,Ds),s=ds(t),i=Fe.multiply(s),a=i.toBytes();return{head:t,prefix:n,scalar:s,point:i,pointBytes:a}},Fs=e=>Bs(_e(e,Be)).then(xo),Sc=e=>xo(Ac(_e(e,Be))),_c=e=>Fs(e).then(t=>t.pointBytes),Tc=e=>Bs(e.hashable).then(e.finish),Cc=(e,t,n)=>{const{pointBytes:s,scalar:i}=e,a=ds(t),o=Fe.multiply(a).toBytes();return{hashable:St(o,s,n),finish:p=>{const d=yo(a+ds(p)*i);return _e(St(o,wo(d)),Ds)}}},Ec=async(e,t)=>{const n=_e(e),s=await Fs(t),i=await Bs(s.prefix,n);return Tc(Cc(s,i,n))},ko={sha512Async:async e=>{const t=bc(),n=St(e);return un(await t.digest("SHA-512",n.buffer))},sha512:void 0},Lc=(e=yc(Be))=>e,Mc={getExtendedPublicKeyAsync:Fs,getExtendedPublicKey:Sc,randomSecretKey:Lc},Jt=8,Ic=256,Ao=Math.ceil(Ic/Jt)+1,us=2**(Jt-1),Rc=()=>{const e=[];let t=Fe,n=t;for(let s=0;s{const n=t.negate();return e?n:t},Pc=e=>{const t=na||(na=Rc());let n=Qe,s=Fe;const i=2**Jt,a=i,o=Zt(i-1),c=Zt(Jt);for(let l=0;l>=c,p>us&&(p-=a,e+=1n);const d=l*us,u=d,h=d+Math.abs(p)-1,v=l%2!==0,w=p<0;p===0?s=s.add(sa(v,t[u])):n=n.add(sa(w,t[h]))}return e!==0n&&H("invalid wnaf"),{p:n,f:s}},jn="clawdbot-device-identity-v1";function ps(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll("+","-").replaceAll("/","_").replace(/=+$/g,"")}function So(e){const t=e.replaceAll("-","+").replaceAll("_","/"),n=t+"=".repeat((4-t.length%4)%4),s=atob(n),i=new Uint8Array(s.length);for(let a=0;at.toString(16).padStart(2,"0")).join("")}async function _o(e){const t=await crypto.subtle.digest("SHA-256",e);return Nc(new Uint8Array(t))}async function Oc(){const e=Mc.randomSecretKey(),t=await _c(e);return{deviceId:await _o(t),publicKey:ps(t),privateKey:ps(e)}}async function Us(){try{const n=localStorage.getItem(jn);if(n){const s=JSON.parse(n);if(s?.version===1&&typeof s.deviceId=="string"&&typeof s.publicKey=="string"&&typeof s.privateKey=="string"){const i=await _o(So(s.publicKey));if(i!==s.deviceId){const a={...s,deviceId:i};return localStorage.setItem(jn,JSON.stringify(a)),{deviceId:i,publicKey:s.publicKey,privateKey:s.privateKey}}return{deviceId:s.deviceId,publicKey:s.publicKey,privateKey:s.privateKey}}}}catch{}const e=await Oc(),t={version:1,deviceId:e.deviceId,publicKey:e.publicKey,privateKey:e.privateKey,createdAtMs:Date.now()};return localStorage.setItem(jn,JSON.stringify(t)),e}async function Dc(e,t){const n=So(e),s=new TextEncoder().encode(t),i=await Ec(s,n);return ps(i)}const To="clawdbot.device.auth.v1";function Ks(e){return e.trim()}function Bc(e){if(!Array.isArray(e))return[];const t=new Set;for(const n of e){const s=n.trim();s&&t.add(s)}return[...t].sort()}function Hs(){try{const e=window.localStorage.getItem(To);if(!e)return null;const t=JSON.parse(e);return!t||t.version!==1||!t.deviceId||typeof t.deviceId!="string"||!t.tokens||typeof t.tokens!="object"?null:t}catch{return null}}function Co(e){try{window.localStorage.setItem(To,JSON.stringify(e))}catch{}}function Fc(e){const t=Hs();if(!t||t.deviceId!==e.deviceId)return null;const n=Ks(e.role),s=t.tokens[n];return!s||typeof s.token!="string"?null:s}function Eo(e){const t=Ks(e.role),n={version:1,deviceId:e.deviceId,tokens:{}},s=Hs();s&&s.deviceId===e.deviceId&&(n.tokens={...s.tokens});const i={token:e.token,role:t,scopes:Bc(e.scopes),updatedAtMs:Date.now()};return n.tokens[t]=i,Co(n),i}function Lo(e){const t=Hs();if(!t||t.deviceId!==e.deviceId)return;const n=Ks(e.role);if(!t.tokens[n])return;const s={...t,tokens:{...t.tokens}};delete s.tokens[n],Co(s)}async function Te(e,t){if(!(!e.client||!e.connected)&&!e.devicesLoading){e.devicesLoading=!0,t?.quiet||(e.devicesError=null);try{const n=await e.client.request("device.pair.list",{});e.devicesList={pending:Array.isArray(n?.pending)?n.pending:[],paired:Array.isArray(n?.paired)?n.paired:[]}}catch(n){t?.quiet||(e.devicesError=String(n))}finally{e.devicesLoading=!1}}}async function Uc(e,t){if(!(!e.client||!e.connected))try{await e.client.request("device.pair.approve",{requestId:t}),await Te(e)}catch(n){e.devicesError=String(n)}}async function Kc(e,t){if(!(!e.client||!e.connected||!window.confirm("Reject this device pairing request?")))try{await e.client.request("device.pair.reject",{requestId:t}),await Te(e)}catch(s){e.devicesError=String(s)}}async function Hc(e,t){if(!(!e.client||!e.connected))try{const n=await e.client.request("device.token.rotate",t);if(n?.token){const s=await Us(),i=n.role??t.role;(n.deviceId===s.deviceId||t.deviceId===s.deviceId)&&Eo({deviceId:s.deviceId,role:i,token:n.token,scopes:n.scopes??t.scopes??[]}),window.prompt("New device token (copy and store securely):",n.token)}await Te(e)}catch(n){e.devicesError=String(n)}}async function zc(e,t){if(!(!e.client||!e.connected||!window.confirm(`Revoke token for ${t.deviceId} (${t.role})?`)))try{await e.client.request("device.token.revoke",t);const s=await Us();t.deviceId===s.deviceId&&Lo({deviceId:s.deviceId,role:t.role}),await Te(e)}catch(s){e.devicesError=String(s)}}async function pn(e,t){if(!(!e.client||!e.connected)&&!e.nodesLoading){e.nodesLoading=!0,t?.quiet||(e.lastError=null);try{const n=await e.client.request("node.list",{});e.nodes=Array.isArray(n.nodes)?n.nodes:[]}catch(n){t?.quiet||(e.lastError=String(n))}finally{e.nodesLoading=!1}}}function jc(e){if(!e||e.kind==="gateway")return{method:"exec.approvals.get",params:{}};const t=e.nodeId.trim();return t?{method:"exec.approvals.node.get",params:{nodeId:t}}:null}function qc(e,t){if(!e||e.kind==="gateway")return{method:"exec.approvals.set",params:t};const n=e.nodeId.trim();return n?{method:"exec.approvals.node.set",params:{...t,nodeId:n}}:null}async function zs(e,t){if(!(!e.client||!e.connected)&&!e.execApprovalsLoading){e.execApprovalsLoading=!0,e.lastError=null;try{const n=jc(t);if(!n){e.lastError="Select a node before loading exec approvals.";return}const s=await e.client.request(n.method,n.params);Vc(e,s)}catch(n){e.lastError=String(n)}finally{e.execApprovalsLoading=!1}}}function Vc(e,t){e.execApprovalsSnapshot=t,e.execApprovalsDirty||(e.execApprovalsForm=De(t.file??{}))}async function Wc(e,t){if(!(!e.client||!e.connected)){e.execApprovalsSaving=!0,e.lastError=null;try{const n=e.execApprovalsSnapshot?.hash;if(!n){e.lastError="Exec approvals hash missing; reload and retry.";return}const s=e.execApprovalsForm??e.execApprovalsSnapshot?.file??{},i=qc(t,{file:s,baseHash:n});if(!i){e.lastError="Select a node before saving exec approvals.";return}await e.client.request(i.method,i.params),e.execApprovalsDirty=!1,await zs(e,t)}catch(n){e.lastError=String(n)}finally{e.execApprovalsSaving=!1}}}function Gc(e,t,n){const s=De(e.execApprovalsForm??e.execApprovalsSnapshot?.file??{});lo(s,t,n),e.execApprovalsForm=s,e.execApprovalsDirty=!0}function Yc(e,t){const n=De(e.execApprovalsForm??e.execApprovalsSnapshot?.file??{});co(n,t),e.execApprovalsForm=n,e.execApprovalsDirty=!0}async function js(e){if(!(!e.client||!e.connected)&&!e.presenceLoading){e.presenceLoading=!0,e.presenceError=null,e.presenceStatus=null;try{const t=await e.client.request("system-presence",{});Array.isArray(t)?(e.presenceEntries=t,e.presenceStatus=t.length===0?"No instances yet.":null):(e.presenceEntries=[],e.presenceStatus="No presence payload.")}catch(t){e.presenceError=String(t)}finally{e.presenceLoading=!1}}}function tt(e,t,n){if(!t.trim())return;const s={...e.skillMessages};n?s[t]=n:delete s[t],e.skillMessages=s}function fn(e){return e instanceof Error?e.message:String(e)}async function Ct(e,t){if(t?.clearMessages&&Object.keys(e.skillMessages).length>0&&(e.skillMessages={}),!(!e.client||!e.connected)&&!e.skillsLoading){e.skillsLoading=!0,e.skillsError=null;try{const n=await e.client.request("skills.status",{});n&&(e.skillsReport=n)}catch(n){e.skillsError=fn(n)}finally{e.skillsLoading=!1}}}function Qc(e,t,n){e.skillEdits={...e.skillEdits,[t]:n}}async function Zc(e,t,n){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{await e.client.request("skills.update",{skillKey:t,enabled:n}),await Ct(e),tt(e,t,{kind:"success",message:n?"Skill enabled":"Skill disabled"})}catch(s){const i=fn(s);e.skillsError=i,tt(e,t,{kind:"error",message:i})}finally{e.skillsBusyKey=null}}}async function Jc(e,t){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const n=e.skillEdits[t]??"";await e.client.request("skills.update",{skillKey:t,apiKey:n}),await Ct(e),tt(e,t,{kind:"success",message:"API key saved"})}catch(n){const s=fn(n);e.skillsError=s,tt(e,t,{kind:"error",message:s})}finally{e.skillsBusyKey=null}}}async function Xc(e,t,n,s){if(!(!e.client||!e.connected)){e.skillsBusyKey=t,e.skillsError=null;try{const i=await e.client.request("skills.install",{name:n,installId:s,timeoutMs:12e4});await Ct(e),tt(e,t,{kind:"success",message:i?.message??"Installed"})}catch(i){const a=fn(i);e.skillsError=a,tt(e,t,{kind:"error",message:a})}finally{e.skillsBusyKey=null}}}function ed(){return typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function qs(e){return e==="system"?ed():e}const Ft=e=>Number.isNaN(e)?.5:e<=0?0:e>=1?1:e,td=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches??!1,Ut=e=>{e.classList.remove("theme-transition"),e.style.removeProperty("--theme-switch-x"),e.style.removeProperty("--theme-switch-y")},nd=({nextTheme:e,applyTheme:t,context:n,currentTheme:s})=>{if(s===e)return;const i=globalThis.document??null;if(!i){t();return}const a=i.documentElement,o=i,c=td();if(!!o.startViewTransition&&!c){let p=.5,d=.5;if(n?.pointerClientX!==void 0&&n?.pointerClientY!==void 0&&typeof window<"u")p=Ft(n.pointerClientX/window.innerWidth),d=Ft(n.pointerClientY/window.innerHeight);else if(n?.element){const u=n.element.getBoundingClientRect();u.width>0&&u.height>0&&typeof window<"u"&&(p=Ft((u.left+u.width/2)/window.innerWidth),d=Ft((u.top+u.height/2)/window.innerHeight))}a.style.setProperty("--theme-switch-x",`${p*100}%`),a.style.setProperty("--theme-switch-y",`${d*100}%`),a.classList.add("theme-transition");try{const u=o.startViewTransition?.(()=>{t()});u?.finished?u.finished.finally(()=>Ut(a)):Ut(a)}catch{Ut(a),t()}return}t(),Ut(a)};function sd(e){e.nodesPollInterval==null&&(e.nodesPollInterval=window.setInterval(()=>{pn(e,{quiet:!0})},5e3))}function id(e){e.nodesPollInterval!=null&&(clearInterval(e.nodesPollInterval),e.nodesPollInterval=null)}function Vs(e){e.logsPollInterval==null&&(e.logsPollInterval=window.setInterval(()=>{e.tab==="logs"&&Os(e,{quiet:!0})},2e3))}function Ws(e){e.logsPollInterval!=null&&(clearInterval(e.logsPollInterval),e.logsPollInterval=null)}function Gs(e){e.debugPollInterval==null&&(e.debugPollInterval=window.setInterval(()=>{e.tab==="debug"&&dn(e)},3e3))}function Ys(e){e.debugPollInterval!=null&&(clearInterval(e.debugPollInterval),e.debugPollInterval=null)}function ke(e,t){const n={...t,lastActiveSessionKey:t.lastActiveSessionKey?.trim()||t.sessionKey.trim()||"main"};e.settings=n,fl(n),t.theme!==e.theme&&(e.theme=t.theme,hn(e,qs(t.theme))),e.applySessionKey=e.settings.lastActiveSessionKey}function Mo(e,t){const n=t.trim();n&&e.settings.lastActiveSessionKey!==n&&ke(e,{...e.settings,lastActiveSessionKey:n})}function ad(e){if(!window.location.search)return;const t=new URLSearchParams(window.location.search),n=t.get("token"),s=t.get("password"),i=t.get("session"),a=t.get("gatewayUrl");let o=!1;if(n!=null){const l=n.trim();l&&l!==e.settings.token&&ke(e,{...e.settings,token:l}),t.delete("token"),o=!0}if(s!=null){const l=s.trim();l&&(e.password=l),t.delete("password"),o=!0}if(i!=null){const l=i.trim();l&&(e.sessionKey=l,ke(e,{...e.settings,sessionKey:l,lastActiveSessionKey:l}))}if(a!=null){const l=a.trim();l&&l!==e.settings.gatewayUrl&&ke(e,{...e.settings,gatewayUrl:l}),t.delete("gatewayUrl"),o=!0}if(!o)return;const c=new URL(window.location.href);c.search=t.toString(),window.history.replaceState({},"",c.toString())}function od(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?Vs(e):Ws(e),t==="debug"?Gs(e):Ys(e),Qs(e),Ro(e,t,!1)}function rd(e,t,n){nd({nextTheme:t,applyTheme:()=>{e.theme=t,ke(e,{...e.settings,theme:t}),hn(e,qs(t))},context:n,currentTheme:e.theme})}async function Qs(e){e.tab==="overview"&&await Po(e),e.tab==="channels"&&await gd(e),e.tab==="instances"&&await js(e),e.tab==="sessions"&&await st(e),e.tab==="cron"&&await Zs(e),e.tab==="skills"&&await Ct(e),e.tab==="nodes"&&(await pn(e),await Te(e),await be(e),await zs(e)),e.tab==="chat"&&(await wd(e),ln(e,!e.chatHasAutoScrolled)),e.tab==="config"&&(await uo(e),await be(e)),e.tab==="debug"&&(await dn(e),e.eventLog=e.eventLogBuffer),e.tab==="logs"&&(e.logsAtBottom=!0,await Os(e,{reset:!0}),ro(e,!0))}function ld(){if(typeof window>"u")return"";const e=window.__CLAWDBOT_CONTROL_UI_BASE_PATH__;return typeof e=="string"&&e.trim()?rn(e):gl(window.location.pathname)}function cd(e){e.theme=e.settings.theme??"system",hn(e,qs(e.theme))}function hn(e,t){if(e.themeResolved=t,typeof document>"u")return;const n=document.documentElement;n.dataset.theme=t,n.style.colorScheme=t}function dd(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;if(e.themeMedia=window.matchMedia("(prefers-color-scheme: dark)"),e.themeMediaHandler=n=>{e.theme==="system"&&hn(e,n.matches?"dark":"light")},typeof e.themeMedia.addEventListener=="function"){e.themeMedia.addEventListener("change",e.themeMediaHandler);return}e.themeMedia.addListener(e.themeMediaHandler)}function ud(e){if(!e.themeMedia||!e.themeMediaHandler)return;if(typeof e.themeMedia.removeEventListener=="function"){e.themeMedia.removeEventListener("change",e.themeMediaHandler);return}e.themeMedia.removeListener(e.themeMediaHandler),e.themeMedia=null,e.themeMediaHandler=null}function pd(e,t){if(typeof window>"u")return;const n=so(window.location.pathname,e.basePath)??"chat";Io(e,n),Ro(e,n,t)}function fd(e){if(typeof window>"u")return;const t=so(window.location.pathname,e.basePath);if(!t)return;const s=new URL(window.location.href).searchParams.get("session")?.trim();s&&(e.sessionKey=s,ke(e,{...e.settings,sessionKey:s,lastActiveSessionKey:s})),Io(e,t)}function Io(e,t){e.tab!==t&&(e.tab=t),t==="chat"&&(e.chatHasAutoScrolled=!1),t==="logs"?Vs(e):Ws(e),t==="debug"?Gs(e):Ys(e),e.connected&&Qs(e)}function Ro(e,t,n){if(typeof window>"u")return;const s=kt(Rs(t,e.basePath)),i=kt(window.location.pathname),a=new URL(window.location.href);t==="chat"&&e.sessionKey?a.searchParams.set("session",e.sessionKey):a.searchParams.delete("session"),i!==s&&(a.pathname=s),n?window.history.replaceState({},"",a.toString()):window.history.pushState({},"",a.toString())}function hd(e,t,n){if(typeof window>"u")return;const s=new URL(window.location.href);s.searchParams.set("session",t),window.history.replaceState({},"",s.toString())}async function Po(e){await Promise.all([oe(e,!1),js(e),st(e),Tt(e),dn(e)])}async function gd(e){await Promise.all([oe(e,!0),uo(e),be(e)])}async function Zs(e){await Promise.all([oe(e,!1),Tt(e),cn(e)])}function No(e){return e.chatSending||!!e.chatRunId}function vd(e){const t=e.trim();if(!t)return!1;const n=t.toLowerCase();return n==="/stop"?!0:n==="stop"||n==="esc"||n==="abort"||n==="wait"||n==="exit"}async function Oo(e){e.connected&&(e.chatMessage="",await El(e))}function md(e,t){const n=t.trim();n&&(e.chatQueue=[...e.chatQueue,{id:Ps(),text:n,createdAt:Date.now()}])}async function Do(e,t,n){Ns(e);const s=await Cl(e,t);return!s&&n?.previousDraft!=null&&(e.chatMessage=n.previousDraft),s&&Mo(e,e.sessionKey),s&&n?.restoreDraft&&n.previousDraft?.trim()&&(e.chatMessage=n.previousDraft),ln(e),s&&!e.chatRunId&&Bo(e),s}async function Bo(e){if(!e.connected||No(e))return;const[t,...n]=e.chatQueue;if(!t)return;e.chatQueue=n,await Do(e,t.text)||(e.chatQueue=[t,...e.chatQueue])}function bd(e,t){e.chatQueue=e.chatQueue.filter(n=>n.id!==t)}async function yd(e,t,n){if(!e.connected)return;const s=e.chatMessage,i=(t??e.chatMessage).trim();if(i){if(vd(i)){await Oo(e);return}if(t==null&&(e.chatMessage=""),No(e)){md(e,i);return}await Do(e,i,{previousDraft:t==null?s:void 0,restoreDraft:!!(t&&n?.restoreDraft)})}}async function wd(e){await Promise.all([Xe(e),st(e),fs(e)]),ln(e,!0)}const $d=Bo;function xd(e){const t=eo(e.sessionKey);return t?.agentId?t.agentId:e.hello?.snapshot?.sessionDefaults?.defaultAgentId?.trim()||"main"}function kd(e,t){const n=rn(e),s=encodeURIComponent(t);return n?`${n}/avatar/${s}?meta=1`:`/avatar/${s}?meta=1`}async function fs(e){if(!e.connected){e.chatAvatarUrl=null;return}const t=xd(e);if(!t){e.chatAvatarUrl=null;return}e.chatAvatarUrl=null;const n=kd(e.basePath,t);try{const s=await fetch(n,{method:"GET"});if(!s.ok){e.chatAvatarUrl=null;return}const i=await s.json(),a=typeof i.avatarUrl=="string"?i.avatarUrl.trim():"";e.chatAvatarUrl=a||null}catch{e.chatAvatarUrl=null}}const Fo={CHILD:2},Uo=e=>(...t)=>({_$litDirective$:e,values:t});let Ko=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,n,s){this._$Ct=t,this._$AM=n,this._$Ci=s}_$AS(t,n){return this.update(t,n)}update(t,n){return this.render(...n)}};const{I:Ad}=nl,ia=e=>e,aa=()=>document.createComment(""),lt=(e,t,n)=>{const s=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0){const a=s.insertBefore(aa(),i),o=s.insertBefore(aa(),i);n=new Ad(a,o,e,e.options)}else{const a=n._$AB.nextSibling,o=n._$AM,c=o!==e;if(c){let l;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(l=e._$AU)!==o._$AU&&n._$AP(l)}if(a!==i||c){let l=n._$AA;for(;l!==a;){const p=ia(l).nextSibling;ia(s).insertBefore(l,i),l=p}}}return n},Me=(e,t,n=e)=>(e._$AI(t,n),e),Sd={},_d=(e,t=Sd)=>e._$AH=t,Td=e=>e._$AH,qn=e=>{e._$AR(),e._$AA.remove()};const oa=(e,t,n)=>{const s=new Map;for(let i=t;i<=n;i++)s.set(e[i],i);return s},Ho=Uo(class extends Ko{constructor(e){if(super(e),e.type!==Fo.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,n){let s;n===void 0?n=t:t!==void 0&&(s=t);const i=[],a=[];let o=0;for(const c of e)i[o]=s?s(c,o):o,a[o]=n(c,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,s]){const i=Td(e),{values:a,keys:o}=this.dt(t,n,s);if(!Array.isArray(i))return this.ut=o,a;const c=this.ut??=[],l=[];let p,d,u=0,h=i.length-1,v=0,w=a.length-1;for(;u<=h&&v<=w;)if(i[u]===null)u++;else if(i[h]===null)h--;else if(c[u]===o[v])l[v]=Me(i[u],a[v]),u++,v++;else if(c[h]===o[w])l[w]=Me(i[h],a[w]),h--,w--;else if(c[u]===o[w])l[w]=Me(i[u],a[w]),lt(e,l[w+1],i[u]),u++,w--;else if(c[h]===o[v])l[v]=Me(i[h],a[v]),lt(e,i[u],i[h]),h--,v++;else if(p===void 0&&(p=oa(o,v,w),d=oa(c,u,h)),p.has(c[u]))if(p.has(c[h])){const $=d.get(o[v]),k=$!==void 0?i[$]:null;if(k===null){const T=lt(e,i[u]);Me(T,a[v]),l[v]=T}else l[v]=Me(k,a[v]),lt(e,i[u],k),i[$]=null;v++}else qn(i[h]),h--;else qn(i[u]),u++;for(;v<=w;){const $=lt(e,l[w+1]);Me($,a[v]),l[v++]=$}for(;u<=h;){const $=i[u++];$!==null&&qn($)}return this.ut=o,_d(e,l),Se}});function zo(e){const t=e;let n=typeof t.role=="string"?t.role:"unknown";const s=typeof t.toolCallId=="string"||typeof t.tool_call_id=="string",i=t.content,a=Array.isArray(i)?i:null,o=Array.isArray(a)&&a.some(u=>{const v=String(u.type??"").toLowerCase();return v==="toolresult"||v==="tool_result"}),c=typeof t.toolName=="string"||typeof t.tool_name=="string";(s||o||c)&&(n="toolResult");let l=[];typeof t.content=="string"?l=[{type:"text",text:t.content}]:Array.isArray(t.content)?l=t.content.map(u=>({type:u.type||"text",text:u.text,name:u.name,args:u.args||u.arguments})):typeof t.text=="string"&&(l=[{type:"text",text:t.text}]);const p=typeof t.timestamp=="number"?t.timestamp:Date.now(),d=typeof t.id=="string"?t.id:void 0;return{role:n,content:l,timestamp:p,id:d}}function Js(e){const t=e.toLowerCase();return e==="user"||e==="User"?e:e==="assistant"?"assistant":e==="system"?"system":t==="toolresult"||t==="tool_result"||t==="tool"||t==="function"?"tool":e}function jo(e){const t=e,n=typeof t.role=="string"?t.role.toLowerCase():"";return n==="toolresult"||n==="tool_result"}class hs extends Ko{constructor(t){if(super(t),this.it=g,t.type!==Fo.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===g||t==null)return this._t=void 0,this.it=t;if(t===Se)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const n=[t];return n.raw=n,this._t={_$litType$:this.constructor.resultType,strings:n,values:[]}}}hs.directiveName="unsafeHTML",hs.resultType=1;const gs=Uo(hs);const{entries:qo,setPrototypeOf:ra,isFrozen:Cd,getPrototypeOf:Ed,getOwnPropertyDescriptor:Ld}=Object;let{freeze:Z,seal:ne,create:vs}=Object,{apply:ms,construct:bs}=typeof Reflect<"u"&&Reflect;Z||(Z=function(t){return t});ne||(ne=function(t){return t});ms||(ms=function(t,n){for(var s=arguments.length,i=new Array(s>2?s-2:0),a=2;a1?n-1:0),i=1;i1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:Wt;ra&&ra(e,null);let s=t.length;for(;s--;){let i=t[s];if(typeof i=="string"){const a=n(i);a!==i&&(Cd(t)||(t[s]=a),i=a)}e[i]=!0}return e}function Od(e){for(let t=0;t/gm),Kd=ne(/\$\{[\w\W]*/gm),Hd=ne(/^data-[\-\w.\u00B7-\uFFFF]+$/),zd=ne(/^aria-[\-\w]+$/),Vo=ne(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),jd=ne(/^(?:\w+script|data):/i),qd=ne(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Wo=ne(/^html$/i),Vd=ne(/^[a-z][.\w]*(-[.\w]+)+$/i);var fa=Object.freeze({__proto__:null,ARIA_ATTR:zd,ATTR_WHITESPACE:qd,CUSTOM_ELEMENT:Vd,DATA_ATTR:Hd,DOCTYPE_NAME:Wo,ERB_EXPR:Ud,IS_ALLOWED_URI:Vo,IS_SCRIPT_OR_DATA:jd,MUSTACHE_EXPR:Fd,TMPLIT_EXPR:Kd});const ft={element:1,text:3,progressingInstruction:7,comment:8,document:9},Wd=function(){return typeof window>"u"?null:window},Gd=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(s=n.getAttribute(i));const a="dompurify"+(s?"#"+s:"");try{return t.createPolicy(a,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},ha=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Go(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Wd();const t=_=>Go(_);if(t.version="3.3.1",t.removed=[],!e||!e.document||e.document.nodeType!==ft.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const s=n,i=s.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:c,Element:l,NodeFilter:p,NamedNodeMap:d=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:u,DOMParser:h,trustedTypes:v}=e,w=l.prototype,$=pt(w,"cloneNode"),k=pt(w,"remove"),T=pt(w,"nextSibling"),M=pt(w,"childNodes"),P=pt(w,"parentNode");if(typeof o=="function"){const _=n.createElement("template");_.content&&_.content.ownerDocument&&(n=_.content.ownerDocument)}let L,C="";const{implementation:E,createNodeIterator:pe,createDocumentFragment:yn,getElementsByTagName:wn}=n,{importNode:kr}=s;let W=ha();t.isSupported=typeof qo=="function"&&typeof P=="function"&&E&&E.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:$n,ERB_EXPR:xn,TMPLIT_EXPR:kn,DATA_ATTR:Ar,ARIA_ATTR:Sr,IS_SCRIPT_OR_DATA:_r,ATTR_WHITESPACE:di,CUSTOM_ELEMENT:Tr}=fa;let{IS_ALLOWED_URI:ui}=fa,K=null;const pi=I({},[...ca,...Gn,...Yn,...Qn,...da]);let z=null;const fi=I({},[...ua,...Zn,...pa,...Ht]);let B=Object.seal(vs(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),it=null,An=null;const He=Object.seal(vs(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let hi=!0,Sn=!0,gi=!1,vi=!0,ze=!1,Lt=!0,Ce=!1,_n=!1,Tn=!1,je=!1,Mt=!1,It=!1,mi=!0,bi=!1;const Cr="user-content-";let Cn=!0,at=!1,qe={},re=null;const En=I({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let yi=null;const wi=I({},["audio","video","img","source","image","track"]);let Ln=null;const $i=I({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Rt="http://www.w3.org/1998/Math/MathML",Pt="http://www.w3.org/2000/svg",fe="http://www.w3.org/1999/xhtml";let Ve=fe,Mn=!1,In=null;const Er=I({},[Rt,Pt,fe],Vn);let Nt=I({},["mi","mo","mn","ms","mtext"]),Ot=I({},["annotation-xml"]);const Lr=I({},["title","style","font","a","script"]);let ot=null;const Mr=["application/xhtml+xml","text/html"],Ir="text/html";let U=null,We=null;const Rr=n.createElement("form"),xi=function(f){return f instanceof RegExp||f instanceof Function},Rn=function(){let f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(We&&We===f)){if((!f||typeof f!="object")&&(f={}),f=de(f),ot=Mr.indexOf(f.PARSER_MEDIA_TYPE)===-1?Ir:f.PARSER_MEDIA_TYPE,U=ot==="application/xhtml+xml"?Vn:Wt,K=se(f,"ALLOWED_TAGS")?I({},f.ALLOWED_TAGS,U):pi,z=se(f,"ALLOWED_ATTR")?I({},f.ALLOWED_ATTR,U):fi,In=se(f,"ALLOWED_NAMESPACES")?I({},f.ALLOWED_NAMESPACES,Vn):Er,Ln=se(f,"ADD_URI_SAFE_ATTR")?I(de($i),f.ADD_URI_SAFE_ATTR,U):$i,yi=se(f,"ADD_DATA_URI_TAGS")?I(de(wi),f.ADD_DATA_URI_TAGS,U):wi,re=se(f,"FORBID_CONTENTS")?I({},f.FORBID_CONTENTS,U):En,it=se(f,"FORBID_TAGS")?I({},f.FORBID_TAGS,U):de({}),An=se(f,"FORBID_ATTR")?I({},f.FORBID_ATTR,U):de({}),qe=se(f,"USE_PROFILES")?f.USE_PROFILES:!1,hi=f.ALLOW_ARIA_ATTR!==!1,Sn=f.ALLOW_DATA_ATTR!==!1,gi=f.ALLOW_UNKNOWN_PROTOCOLS||!1,vi=f.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ze=f.SAFE_FOR_TEMPLATES||!1,Lt=f.SAFE_FOR_XML!==!1,Ce=f.WHOLE_DOCUMENT||!1,je=f.RETURN_DOM||!1,Mt=f.RETURN_DOM_FRAGMENT||!1,It=f.RETURN_TRUSTED_TYPE||!1,Tn=f.FORCE_BODY||!1,mi=f.SANITIZE_DOM!==!1,bi=f.SANITIZE_NAMED_PROPS||!1,Cn=f.KEEP_CONTENT!==!1,at=f.IN_PLACE||!1,ui=f.ALLOWED_URI_REGEXP||Vo,Ve=f.NAMESPACE||fe,Nt=f.MATHML_TEXT_INTEGRATION_POINTS||Nt,Ot=f.HTML_INTEGRATION_POINTS||Ot,B=f.CUSTOM_ELEMENT_HANDLING||{},f.CUSTOM_ELEMENT_HANDLING&&xi(f.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(B.tagNameCheck=f.CUSTOM_ELEMENT_HANDLING.tagNameCheck),f.CUSTOM_ELEMENT_HANDLING&&xi(f.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(B.attributeNameCheck=f.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),f.CUSTOM_ELEMENT_HANDLING&&typeof f.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(B.allowCustomizedBuiltInElements=f.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ze&&(Sn=!1),Mt&&(je=!0),qe&&(K=I({},da),z=[],qe.html===!0&&(I(K,ca),I(z,ua)),qe.svg===!0&&(I(K,Gn),I(z,Zn),I(z,Ht)),qe.svgFilters===!0&&(I(K,Yn),I(z,Zn),I(z,Ht)),qe.mathMl===!0&&(I(K,Qn),I(z,pa),I(z,Ht))),f.ADD_TAGS&&(typeof f.ADD_TAGS=="function"?He.tagCheck=f.ADD_TAGS:(K===pi&&(K=de(K)),I(K,f.ADD_TAGS,U))),f.ADD_ATTR&&(typeof f.ADD_ATTR=="function"?He.attributeCheck=f.ADD_ATTR:(z===fi&&(z=de(z)),I(z,f.ADD_ATTR,U))),f.ADD_URI_SAFE_ATTR&&I(Ln,f.ADD_URI_SAFE_ATTR,U),f.FORBID_CONTENTS&&(re===En&&(re=de(re)),I(re,f.FORBID_CONTENTS,U)),f.ADD_FORBID_CONTENTS&&(re===En&&(re=de(re)),I(re,f.ADD_FORBID_CONTENTS,U)),Cn&&(K["#text"]=!0),Ce&&I(K,["html","head","body"]),K.table&&(I(K,["tbody"]),delete it.tbody),f.TRUSTED_TYPES_POLICY){if(typeof f.TRUSTED_TYPES_POLICY.createHTML!="function")throw ut('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof f.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ut('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');L=f.TRUSTED_TYPES_POLICY,C=L.createHTML("")}else L===void 0&&(L=Gd(v,i)),L!==null&&typeof C=="string"&&(C=L.createHTML(""));Z&&Z(f),We=f}},ki=I({},[...Gn,...Yn,...Dd]),Ai=I({},[...Qn,...Bd]),Pr=function(f){let x=P(f);(!x||!x.tagName)&&(x={namespaceURI:Ve,tagName:"template"});const S=Wt(f.tagName),D=Wt(x.tagName);return In[f.namespaceURI]?f.namespaceURI===Pt?x.namespaceURI===fe?S==="svg":x.namespaceURI===Rt?S==="svg"&&(D==="annotation-xml"||Nt[D]):!!ki[S]:f.namespaceURI===Rt?x.namespaceURI===fe?S==="math":x.namespaceURI===Pt?S==="math"&&Ot[D]:!!Ai[S]:f.namespaceURI===fe?x.namespaceURI===Pt&&!Ot[D]||x.namespaceURI===Rt&&!Nt[D]?!1:!Ai[S]&&(Lr[S]||!ki[S]):!!(ot==="application/xhtml+xml"&&In[f.namespaceURI]):!1},le=function(f){ct(t.removed,{element:f});try{P(f).removeChild(f)}catch{k(f)}},Ee=function(f,x){try{ct(t.removed,{attribute:x.getAttributeNode(f),from:x})}catch{ct(t.removed,{attribute:null,from:x})}if(x.removeAttribute(f),f==="is")if(je||Mt)try{le(x)}catch{}else try{x.setAttribute(f,"")}catch{}},Si=function(f){let x=null,S=null;if(Tn)f=""+f;else{const F=Wn(f,/^[\r\n\t ]+/);S=F&&F[0]}ot==="application/xhtml+xml"&&Ve===fe&&(f=''+f+"");const D=L?L.createHTML(f):f;if(Ve===fe)try{x=new h().parseFromString(D,ot)}catch{}if(!x||!x.documentElement){x=E.createDocument(Ve,"template",null);try{x.documentElement.innerHTML=Mn?C:D}catch{}}const q=x.body||x.documentElement;return f&&S&&q.insertBefore(n.createTextNode(S),q.childNodes[0]||null),Ve===fe?wn.call(x,Ce?"html":"body")[0]:Ce?x.documentElement:q},_i=function(f){return pe.call(f.ownerDocument||f,f,p.SHOW_ELEMENT|p.SHOW_COMMENT|p.SHOW_TEXT|p.SHOW_PROCESSING_INSTRUCTION|p.SHOW_CDATA_SECTION,null)},Pn=function(f){return f instanceof u&&(typeof f.nodeName!="string"||typeof f.textContent!="string"||typeof f.removeChild!="function"||!(f.attributes instanceof d)||typeof f.removeAttribute!="function"||typeof f.setAttribute!="function"||typeof f.namespaceURI!="string"||typeof f.insertBefore!="function"||typeof f.hasChildNodes!="function")},Ti=function(f){return typeof c=="function"&&f instanceof c};function he(_,f,x){Kt(_,S=>{S.call(t,f,x,We)})}const Ci=function(f){let x=null;if(he(W.beforeSanitizeElements,f,null),Pn(f))return le(f),!0;const S=U(f.nodeName);if(he(W.uponSanitizeElement,f,{tagName:S,allowedTags:K}),Lt&&f.hasChildNodes()&&!Ti(f.firstElementChild)&&G(/<[/\w!]/g,f.innerHTML)&&G(/<[/\w!]/g,f.textContent)||f.nodeType===ft.progressingInstruction||Lt&&f.nodeType===ft.comment&&G(/<[/\w]/g,f.data))return le(f),!0;if(!(He.tagCheck instanceof Function&&He.tagCheck(S))&&(!K[S]||it[S])){if(!it[S]&&Li(S)&&(B.tagNameCheck instanceof RegExp&&G(B.tagNameCheck,S)||B.tagNameCheck instanceof Function&&B.tagNameCheck(S)))return!1;if(Cn&&!re[S]){const D=P(f)||f.parentNode,q=M(f)||f.childNodes;if(q&&D){const F=q.length;for(let X=F-1;X>=0;--X){const ge=$(q[X],!0);ge.__removalCount=(f.__removalCount||0)+1,D.insertBefore(ge,T(f))}}}return le(f),!0}return f instanceof l&&!Pr(f)||(S==="noscript"||S==="noembed"||S==="noframes")&&G(/<\/no(script|embed|frames)/i,f.innerHTML)?(le(f),!0):(ze&&f.nodeType===ft.text&&(x=f.textContent,Kt([$n,xn,kn],D=>{x=dt(x,D," ")}),f.textContent!==x&&(ct(t.removed,{element:f.cloneNode()}),f.textContent=x)),he(W.afterSanitizeElements,f,null),!1)},Ei=function(f,x,S){if(mi&&(x==="id"||x==="name")&&(S in n||S in Rr))return!1;if(!(Sn&&!An[x]&&G(Ar,x))){if(!(hi&&G(Sr,x))){if(!(He.attributeCheck instanceof Function&&He.attributeCheck(x,f))){if(!z[x]||An[x]){if(!(Li(f)&&(B.tagNameCheck instanceof RegExp&&G(B.tagNameCheck,f)||B.tagNameCheck instanceof Function&&B.tagNameCheck(f))&&(B.attributeNameCheck instanceof RegExp&&G(B.attributeNameCheck,x)||B.attributeNameCheck instanceof Function&&B.attributeNameCheck(x,f))||x==="is"&&B.allowCustomizedBuiltInElements&&(B.tagNameCheck instanceof RegExp&&G(B.tagNameCheck,S)||B.tagNameCheck instanceof Function&&B.tagNameCheck(S))))return!1}else if(!Ln[x]){if(!G(ui,dt(S,di,""))){if(!((x==="src"||x==="xlink:href"||x==="href")&&f!=="script"&&Rd(S,"data:")===0&&yi[f])){if(!(gi&&!G(_r,dt(S,di,"")))){if(S)return!1}}}}}}}return!0},Li=function(f){return f!=="annotation-xml"&&Wn(f,Tr)},Mi=function(f){he(W.beforeSanitizeAttributes,f,null);const{attributes:x}=f;if(!x||Pn(f))return;const S={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:z,forceKeepAttr:void 0};let D=x.length;for(;D--;){const q=x[D],{name:F,namespaceURI:X,value:ge}=q,Ge=U(F),Nn=ge;let j=F==="value"?Nn:Pd(Nn);if(S.attrName=Ge,S.attrValue=j,S.keepAttr=!0,S.forceKeepAttr=void 0,he(W.uponSanitizeAttribute,f,S),j=S.attrValue,bi&&(Ge==="id"||Ge==="name")&&(Ee(F,f),j=Cr+j),Lt&&G(/((--!?|])>)|<\/(style|title|textarea)/i,j)){Ee(F,f);continue}if(Ge==="attributename"&&Wn(j,"href")){Ee(F,f);continue}if(S.forceKeepAttr)continue;if(!S.keepAttr){Ee(F,f);continue}if(!vi&&G(/\/>/i,j)){Ee(F,f);continue}ze&&Kt([$n,xn,kn],Ri=>{j=dt(j,Ri," ")});const Ii=U(f.nodeName);if(!Ei(Ii,Ge,j)){Ee(F,f);continue}if(L&&typeof v=="object"&&typeof v.getAttributeType=="function"&&!X)switch(v.getAttributeType(Ii,Ge)){case"TrustedHTML":{j=L.createHTML(j);break}case"TrustedScriptURL":{j=L.createScriptURL(j);break}}if(j!==Nn)try{X?f.setAttributeNS(X,F,j):f.setAttribute(F,j),Pn(f)?le(f):la(t.removed)}catch{Ee(F,f)}}he(W.afterSanitizeAttributes,f,null)},Nr=function _(f){let x=null;const S=_i(f);for(he(W.beforeSanitizeShadowDOM,f,null);x=S.nextNode();)he(W.uponSanitizeShadowNode,x,null),Ci(x),Mi(x),x.content instanceof a&&_(x.content);he(W.afterSanitizeShadowDOM,f,null)};return t.sanitize=function(_){let f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},x=null,S=null,D=null,q=null;if(Mn=!_,Mn&&(_=""),typeof _!="string"&&!Ti(_))if(typeof _.toString=="function"){if(_=_.toString(),typeof _!="string")throw ut("dirty is not a string, aborting")}else throw ut("toString is not a function");if(!t.isSupported)return _;if(_n||Rn(f),t.removed=[],typeof _=="string"&&(at=!1),at){if(_.nodeName){const ge=U(_.nodeName);if(!K[ge]||it[ge])throw ut("root node is forbidden and cannot be sanitized in-place")}}else if(_ instanceof c)x=Si(""),S=x.ownerDocument.importNode(_,!0),S.nodeType===ft.element&&S.nodeName==="BODY"||S.nodeName==="HTML"?x=S:x.appendChild(S);else{if(!je&&!ze&&!Ce&&_.indexOf("<")===-1)return L&&It?L.createHTML(_):_;if(x=Si(_),!x)return je?null:It?C:""}x&&Tn&&le(x.firstChild);const F=_i(at?_:x);for(;D=F.nextNode();)Ci(D),Mi(D),D.content instanceof a&&Nr(D.content);if(at)return _;if(je){if(Mt)for(q=yn.call(x.ownerDocument);x.firstChild;)q.appendChild(x.firstChild);else q=x;return(z.shadowroot||z.shadowrootmode)&&(q=kr.call(s,q,!0)),q}let X=Ce?x.outerHTML:x.innerHTML;return Ce&&K["!doctype"]&&x.ownerDocument&&x.ownerDocument.doctype&&x.ownerDocument.doctype.name&&G(Wo,x.ownerDocument.doctype.name)&&(X=" +`+X),ze&&Kt([$n,xn,kn],ge=>{X=dt(X,ge," ")}),L&&It?L.createHTML(X):X},t.setConfig=function(){let _=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Rn(_),_n=!0},t.clearConfig=function(){We=null,_n=!1},t.isValidAttribute=function(_,f,x){We||Rn({});const S=U(_),D=U(f);return Ei(S,D,x)},t.addHook=function(_,f){typeof f=="function"&&ct(W[_],f)},t.removeHook=function(_,f){if(f!==void 0){const x=Md(W[_],f);return x===-1?void 0:Id(W[_],x,1)[0]}return la(W[_])},t.removeHooks=function(_){W[_]=[]},t.removeAllHooks=function(){W=ha()},t}var ys=Go();function Xs(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ke=Xs();function Yo(e){Ke=e}var yt={exec:()=>null};function R(e,t=""){let n=typeof e=="string"?e:e.source,s={replace:(i,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(Y.caret,"$1"),n=n.replace(i,o),s},getRegex:()=>new RegExp(n,t)};return s}var Yd=(()=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},Qd=/^(?:[ \t]*(?:\n|$))+/,Zd=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Jd=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Et=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Xd=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ei=/(?:[*+-]|\d{1,9}[.)])/,Qo=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Zo=R(Qo).replace(/bull/g,ei).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),eu=R(Qo).replace(/bull/g,ei).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ti=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,tu=/^[^\n]+/,ni=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,nu=R(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ni).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),su=R(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,ei).getRegex(),gn="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",si=/|$))/,iu=R("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",si).replace("tag",gn).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Jo=R(ti).replace("hr",Et).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",gn).getRegex(),au=R(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Jo).getRegex(),ii={blockquote:au,code:Zd,def:nu,fences:Jd,heading:Xd,hr:Et,html:iu,lheading:Zo,list:su,newline:Qd,paragraph:Jo,table:yt,text:tu},ga=R("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Et).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",gn).getRegex(),ou={...ii,lheading:eu,table:ga,paragraph:R(ti).replace("hr",Et).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ga).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",gn).getRegex()},ru={...ii,html:R(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",si).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:yt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:R(ti).replace("hr",Et).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",Zo).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},lu=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,cu=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Xo=/^( {2,}|\\)\n(?!\s*$)/,du=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Yd?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),nr=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,gu=R(nr,"u").replace(/punct/g,vn).getRegex(),vu=R(nr,"u").replace(/punct/g,tr).getRegex(),sr="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",mu=R(sr,"gu").replace(/notPunctSpace/g,er).replace(/punctSpace/g,ai).replace(/punct/g,vn).getRegex(),bu=R(sr,"gu").replace(/notPunctSpace/g,fu).replace(/punctSpace/g,pu).replace(/punct/g,tr).getRegex(),yu=R("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,er).replace(/punctSpace/g,ai).replace(/punct/g,vn).getRegex(),wu=R(/\\(punct)/,"gu").replace(/punct/g,vn).getRegex(),$u=R(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),xu=R(si).replace("(?:-->|$)","-->").getRegex(),ku=R("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",xu).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Xt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Au=R(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Xt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ir=R(/^!?\[(label)\]\[(ref)\]/).replace("label",Xt).replace("ref",ni).getRegex(),ar=R(/^!?\[(ref)\](?:\[\])?/).replace("ref",ni).getRegex(),Su=R("reflink|nolink(?!\\()","g").replace("reflink",ir).replace("nolink",ar).getRegex(),va=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,oi={_backpedal:yt,anyPunctuation:wu,autolink:$u,blockSkip:hu,br:Xo,code:cu,del:yt,emStrongLDelim:gu,emStrongRDelimAst:mu,emStrongRDelimUnd:yu,escape:lu,link:Au,nolink:ar,punctuation:uu,reflink:ir,reflinkSearch:Su,tag:ku,text:du,url:yt},_u={...oi,link:R(/^!?\[(label)\]\((.*?)\)/).replace("label",Xt).getRegex(),reflink:R(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Xt).getRegex()},ws={...oi,emStrongRDelimAst:bu,emStrongLDelim:vu,url:R(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",va).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:R(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},ma=e=>Cu[e];function me(e,t){if(t){if(Y.escapeTest.test(e))return e.replace(Y.escapeReplace,ma)}else if(Y.escapeTestNoEncode.test(e))return e.replace(Y.escapeReplaceNoEncode,ma);return e}function ba(e){try{e=encodeURI(e).replace(Y.percentDecode,"%")}catch{return null}return e}function ya(e,t){let n=e.replace(Y.findPipe,(a,o,c)=>{let l=!1,p=o;for(;--p>=0&&c[p]==="\\";)l=!l;return l?"|":" |"}),s=n.split(Y.splitPipe),i=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length0?-2:-1}function wa(e,t,n,s,i){let a=t.href,o=t.title||null,c=e[1].replace(i.other.outputLinkReplace,"$1");s.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:a,title:o,text:c,tokens:s.inlineTokens(c)};return s.state.inLink=!1,l}function Lu(e,t,n){let s=e.match(n.other.indentCodeCompensation);if(s===null)return t;let i=s[1];return t.split(` +`).map(a=>{let o=a.match(n.other.beginningSpace);if(o===null)return a;let[c]=o;return c.length>=i.length?a.slice(i.length):a}).join(` +`)}var en=class{options;rules;lexer;constructor(e){this.options=e||Ke}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:gt(n,` +`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=Lu(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=gt(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:gt(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=gt(t[0],` +`).split(` +`),s="",i="",a=[];for(;n.length>0;){let o=!1,c=[],l;for(l=0;l1,i={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let l=!1,p="",d="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let u=t[2].split(` +`,1)[0].replace(this.rules.other.listReplaceTabs,$=>" ".repeat(3*$.length)),h=e.split(` +`,1)[0],v=!u.trim(),w=0;if(this.options.pedantic?(w=2,d=u.trimStart()):v?w=t[1].length+1:(w=t[2].search(this.rules.other.nonSpaceChar),w=w>4?1:w,d=u.slice(w),w+=t[1].length),v&&this.rules.other.blankLine.test(h)&&(p+=h+` +`,e=e.substring(h.length+1),l=!0),!l){let $=this.rules.other.nextBulletRegex(w),k=this.rules.other.hrRegex(w),T=this.rules.other.fencesBeginRegex(w),M=this.rules.other.headingBeginRegex(w),P=this.rules.other.htmlBeginRegex(w);for(;e;){let L=e.split(` +`,1)[0],C;if(h=L,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),C=h):C=h.replace(this.rules.other.tabCharGlobal," "),T.test(h)||M.test(h)||P.test(h)||$.test(h)||k.test(h))break;if(C.search(this.rules.other.nonSpaceChar)>=w||!h.trim())d+=` +`+C.slice(w);else{if(v||u.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||T.test(u)||M.test(u)||k.test(u))break;d+=` +`+h}!v&&!h.trim()&&(v=!0),p+=L+` +`,e=e.substring(L.length+1),u=C.slice(w)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(o=!0)),i.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]}),i.raw+=p}let c=i.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.items){if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),l.task){if(l.text=l.text.replace(this.rules.other.listReplaceTask,""),l.tokens[0]?.type==="text"||l.tokens[0]?.type==="paragraph"){l.tokens[0].raw=l.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),l.tokens[0].text=l.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}}let p=this.rules.other.listTaskCheckbox.exec(l.raw);if(p){let d={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};l.checked=d.checked,i.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=d.raw+l.tokens[0].raw,l.tokens[0].text=d.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(d)):l.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):l.tokens.unshift(d)}}if(!i.loose){let p=l.tokens.filter(u=>u.type==="space"),d=p.length>0&&p.some(u=>this.rules.other.anyLine.test(u.raw));i.loose=d}}if(i.loose)for(let l of i.items){l.loose=!0;for(let p of l.tokens)p.type==="text"&&(p.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:s,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=ya(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` +`):[],a={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o({text:c,tokens:this.lexer.inline(c),header:!1,align:a.align[l]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let a=gt(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=Eu(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let s=t[2],i="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(s);a&&(s=a[1],i=a[3])}else i=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),wa(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[s.toLowerCase()];if(!i){let a=n[0].charAt(0);return{type:"text",raw:a,text:a}}return wa(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[2])||!n||this.rules.inline.punctuation.exec(n))){let i=[...s[0]].length-1,a,o,c=i,l=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+i);(s=p.exec(t))!=null;){if(a=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!a)continue;if(o=[...a].length,s[3]||s[4]){c+=o;continue}else if((s[5]||s[6])&&i%3&&!((i+o)%3)){l+=o;continue}if(c-=o,c>0)continue;o=Math.min(o,o+c+l);let d=[...s[0]][0].length,u=e.slice(0,i+s.index+d+o);if(Math.min(i,o)%2){let v=u.slice(1,-1);return{type:"em",raw:u,text:v,tokens:this.lexer.inlineTokens(v)}}let h=u.slice(2,-2);return{type:"strong",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},ie=class $s{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ke,this.options.tokenizer=this.options.tokenizer||new en,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:Y,block:zt.normal,inline:ht.normal};this.options.pedantic?(n.block=zt.pedantic,n.inline=ht.pedantic):this.options.gfm&&(n.block=zt.gfm,this.options.breaks?n.inline=ht.breaks:n.inline=ht.gfm),this.tokenizer.rules=n}static get rules(){return{block:zt,inline:ht}}static lex(t,n){return new $s(n).lex(t)}static lexInline(t,n){return new $s(n).inlineTokens(t)}lex(t){t=t.replace(Y.carriageReturn,` +`),this.blockTokens(t,this.tokens);for(let n=0;n(i=o.call({lexer:this},t,n))?(t=t.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.space(t)){t=t.substring(i.raw.length);let o=n.at(-1);i.raw.length===1&&o!==void 0?o.raw+=` +`:n.push(i);continue}if(i=this.tokenizer.code(t)){t=t.substring(i.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+i.raw,o.text+=` +`+i.text,this.inlineQueue.at(-1).src=o.text):n.push(i);continue}if(i=this.tokenizer.fences(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.heading(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.hr(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.blockquote(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.list(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.html(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.def(t)){t=t.substring(i.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+i.raw,o.text+=` +`+i.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},n.push(i));continue}if(i=this.tokenizer.table(t)){t=t.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.lheading(t)){t=t.substring(i.raw.length),n.push(i);continue}let a=t;if(this.options.extensions?.startBlock){let o=1/0,c=t.slice(1),l;this.options.extensions.startBlock.forEach(p=>{l=p.call({lexer:this},c),typeof l=="number"&&l>=0&&(o=Math.min(o,l))}),o<1/0&&o>=0&&(a=t.substring(0,o+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let o=n.at(-1);s&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+i.raw,o.text+=` +`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(i),s=a.length!==t.length,t=t.substring(i.raw.length);continue}if(i=this.tokenizer.text(t)){t=t.substring(i.raw.length);let o=n.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+i.raw,o.text+=` +`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(i);continue}if(t){let o="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let s=t,i=null;if(this.tokens.links){let l=Object.keys(this.tokens.links);if(l.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)l.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,i.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let a;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)a=i[2]?i[2].length:0,s=s.slice(0,i.index+a)+"["+"a".repeat(i[0].length-a-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let o=!1,c="";for(;t;){o||(c=""),o=!1;let l;if(this.options.extensions?.inline?.some(d=>(l=d.call({lexer:this},t,n))?(t=t.substring(l.raw.length),n.push(l),!0):!1))continue;if(l=this.tokenizer.escape(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.tag(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.link(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(l.raw.length);let d=n.at(-1);l.type==="text"&&d?.type==="text"?(d.raw+=l.raw,d.text+=l.text):n.push(l);continue}if(l=this.tokenizer.emStrong(t,s,c)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.codespan(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.br(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.del(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.autolink(t)){t=t.substring(l.raw.length),n.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(t))){t=t.substring(l.raw.length),n.push(l);continue}let p=t;if(this.options.extensions?.startInline){let d=1/0,u=t.slice(1),h;this.options.extensions.startInline.forEach(v=>{h=v.call({lexer:this},u),typeof h=="number"&&h>=0&&(d=Math.min(d,h))}),d<1/0&&d>=0&&(p=t.substring(0,d+1))}if(l=this.tokenizer.inlineText(p)){t=t.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(c=l.raw.slice(-1)),o=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=l.raw,d.text+=l.text):n.push(l);continue}if(t){let d="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw new Error(d)}}return n}},tn=class{options;parser;constructor(e){this.options=e||Ke}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(Y.notSpaceStart)?.[0],i=e.replace(Y.endingNewline,"")+` +`;return s?'
'+(n?i:me(i,!0))+`
+`:"
"+(n?i:me(i,!0))+`
+`}blockquote({tokens:e}){return`
+${this.parser.parse(e)}
+`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} +`}hr(e){return`
+`}list(e){let t=e.ordered,n=e.start,s="";for(let o=0;o +`+s+" +`}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • +`}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t="",n="";for(let i=0;i${s}`),` + +`+t+` +`+s+`
    +`}tablerow({text:e}){return` +${e} +`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${me(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),i=ba(e);if(i===null)return s;e=i;let a='
    ",a}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let i=ba(e);if(i===null)return me(n);e=i;let a=`${n}{let o=i[a].flat(1/0);n=n.concat(this.walkTokens(o,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let a=t.renderers[i.name];a?t.renderers[i.name]=function(...o){let c=i.renderer.apply(this,o);return c===!1&&(c=a.apply(this,o)),c}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=t[i.level];a?a.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),s.extensions=t),n.renderer){let i=this.defaults.renderer||new tn(this.defaults);for(let a in n.renderer){if(!(a in i))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,c=n.renderer[o],l=i[o];i[o]=(...p)=>{let d=c.apply(i,p);return d===!1&&(d=l.apply(i,p)),d||""}}s.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new en(this.defaults);for(let a in n.tokenizer){if(!(a in i))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,c=n.tokenizer[o],l=i[o];i[o]=(...p)=>{let d=c.apply(i,p);return d===!1&&(d=l.apply(i,p)),d}}s.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new vt;for(let a in n.hooks){if(!(a in i))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,c=n.hooks[o],l=i[o];vt.passThroughHooks.has(a)?i[o]=p=>{if(this.defaults.async&&vt.passThroughHooksRespectAsync.has(a))return(async()=>{let u=await c.call(i,p);return l.call(i,u)})();let d=c.call(i,p);return l.call(i,d)}:i[o]=(...p)=>{if(this.defaults.async)return(async()=>{let u=await c.apply(i,p);return u===!1&&(u=await l.apply(i,p)),u})();let d=c.apply(i,p);return d===!1&&(d=l.apply(i,p)),d}}s.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,a=n.walkTokens;s.walkTokens=function(o){let c=[];return c.push(a.call(this,o)),i&&(c=c.concat(i.call(this,o))),c}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ie.lex(e,t??this.defaults)}parser(e,t){return ae.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},i={...this.defaults,...s},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&s.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let o=i.hooks?await i.hooks.preprocess(t):t,c=await(i.hooks?await i.hooks.provideLexer():e?ie.lex:ie.lexInline)(o,i),l=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(l,i.walkTokens));let p=await(i.hooks?await i.hooks.provideParser():e?ae.parse:ae.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(p):p})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let o=(i.hooks?i.hooks.provideLexer():e?ie.lex:ie.lexInline)(t,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let c=(i.hooks?i.hooks.provideParser():e?ae.parse:ae.parseInline)(o,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(o){return a(o)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let s="

    An error occurred:

    "+me(n.message+"",!0)+"
    ";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},Ue=new Mu;function N(e,t){return Ue.parse(e,t)}N.options=N.setOptions=function(e){return Ue.setOptions(e),N.defaults=Ue.defaults,Yo(N.defaults),N};N.getDefaults=Xs;N.defaults=Ke;N.use=function(...e){return Ue.use(...e),N.defaults=Ue.defaults,Yo(N.defaults),N};N.walkTokens=function(e,t){return Ue.walkTokens(e,t)};N.parseInline=Ue.parseInline;N.Parser=ae;N.parser=ae.parse;N.Renderer=tn;N.TextRenderer=ri;N.Lexer=ie;N.lexer=ie.lex;N.Tokenizer=en;N.Hooks=vt;N.parse=N;N.options;N.setOptions;N.use;N.walkTokens;N.parseInline;ae.parse;ie.lex;N.setOptions({gfm:!0,breaks:!0,mangle:!1});const $a=["a","b","blockquote","br","code","del","em","h1","h2","h3","h4","hr","i","li","ol","p","pre","strong","table","tbody","td","th","thead","tr","ul"],xa=["class","href","rel","target","title","start"];let ka=!1;const Iu=14e4,Ru=4e4,Pu=200,Jn=5e4,Ne=new Map;function Nu(e){const t=Ne.get(e);return t===void 0?null:(Ne.delete(e),Ne.set(e,t),t)}function Aa(e,t){if(Ne.set(e,t),Ne.size<=Pu)return;const n=Ne.keys().next().value;n&&Ne.delete(n)}function Ou(){ka||(ka=!0,ys.addHook("afterSanitizeAttributes",e=>{!(e instanceof HTMLAnchorElement)||!e.getAttribute("href")||(e.setAttribute("rel","noreferrer noopener"),e.setAttribute("target","_blank"))}))}function ks(e){const t=e.trim();if(!t)return"";if(Ou(),t.length<=Jn){const o=Nu(t);if(o!==null)return o}const n=ao(t,Iu),s=n.truncated?` + +… truncated (${n.total} chars, showing first ${n.text.length}).`:"";if(n.text.length>Ru){const c=`
    ${Du(`${n.text}${s}`)}
    `,l=ys.sanitize(c,{ALLOWED_TAGS:$a,ALLOWED_ATTR:xa});return t.length<=Jn&&Aa(t,l),l}const i=N.parse(`${n.text}${s}`),a=ys.sanitize(i,{ALLOWED_TAGS:$a,ALLOWED_ATTR:xa});return t.length<=Jn&&Aa(t,a),a}function Du(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}const Bu=1500,Fu=2e3,or="Copy as markdown",Uu="Copied",Ku="Copy failed";async function Hu(e){if(!e)return!1;try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function jt(e,t){e.title=t,e.setAttribute("aria-label",t)}function zu(e){const t=e.label??or;return r` + + `}function ju(e){return zu({text:()=>e,label:or})}const qu={icon:"puzzle",detailKeys:["command","path","url","targetUrl","targetId","ref","element","node","nodeId","id","requestId","to","channelId","guildId","userId","name","query","pattern","messageId"]},Vu={bash:{icon:"wrench",title:"Bash",detailKeys:["command"]},process:{icon:"wrench",title:"Process",detailKeys:["sessionId"]},read:{icon:"fileText",title:"Read",detailKeys:["path"]},write:{icon:"edit",title:"Write",detailKeys:["path"]},edit:{icon:"penLine",title:"Edit",detailKeys:["path"]},attach:{icon:"paperclip",title:"Attach",detailKeys:["path","url","fileName"]},browser:{icon:"globe",title:"Browser",actions:{status:{label:"status"},start:{label:"start"},stop:{label:"stop"},tabs:{label:"tabs"},open:{label:"open",detailKeys:["targetUrl"]},focus:{label:"focus",detailKeys:["targetId"]},close:{label:"close",detailKeys:["targetId"]},snapshot:{label:"snapshot",detailKeys:["targetUrl","targetId","ref","element","format"]},screenshot:{label:"screenshot",detailKeys:["targetUrl","targetId","ref","element"]},navigate:{label:"navigate",detailKeys:["targetUrl","targetId"]},console:{label:"console",detailKeys:["level","targetId"]},pdf:{label:"pdf",detailKeys:["targetId"]},upload:{label:"upload",detailKeys:["paths","ref","inputRef","element","targetId"]},dialog:{label:"dialog",detailKeys:["accept","promptText","targetId"]},act:{label:"act",detailKeys:["request.kind","request.ref","request.selector","request.text","request.value"]}}},canvas:{icon:"image",title:"Canvas",actions:{present:{label:"present",detailKeys:["target","node","nodeId"]},hide:{label:"hide",detailKeys:["node","nodeId"]},navigate:{label:"navigate",detailKeys:["url","node","nodeId"]},eval:{label:"eval",detailKeys:["javaScript","node","nodeId"]},snapshot:{label:"snapshot",detailKeys:["format","node","nodeId"]},a2ui_push:{label:"A2UI push",detailKeys:["jsonlPath","node","nodeId"]},a2ui_reset:{label:"A2UI reset",detailKeys:["node","nodeId"]}}},nodes:{icon:"smartphone",title:"Nodes",actions:{status:{label:"status"},describe:{label:"describe",detailKeys:["node","nodeId"]},pending:{label:"pending"},approve:{label:"approve",detailKeys:["requestId"]},reject:{label:"reject",detailKeys:["requestId"]},notify:{label:"notify",detailKeys:["node","nodeId","title","body"]},camera_snap:{label:"camera snap",detailKeys:["node","nodeId","facing","deviceId"]},camera_list:{label:"camera list",detailKeys:["node","nodeId"]},camera_clip:{label:"camera clip",detailKeys:["node","nodeId","facing","duration","durationMs"]},screen_record:{label:"screen record",detailKeys:["node","nodeId","duration","durationMs","fps","screenIndex"]}}},cron:{icon:"loader",title:"Cron",actions:{status:{label:"status"},list:{label:"list"},add:{label:"add",detailKeys:["job.name","job.id","job.schedule","job.cron"]},update:{label:"update",detailKeys:["id"]},remove:{label:"remove",detailKeys:["id"]},run:{label:"run",detailKeys:["id"]},runs:{label:"runs",detailKeys:["id"]},wake:{label:"wake",detailKeys:["text","mode"]}}},gateway:{icon:"plug",title:"Gateway",actions:{restart:{label:"restart",detailKeys:["reason","delayMs"]},"config.get":{label:"config get"},"config.schema":{label:"config schema"},"config.apply":{label:"config apply",detailKeys:["restartDelayMs"]},"update.run":{label:"update run",detailKeys:["restartDelayMs"]}}},whatsapp_login:{icon:"circle",title:"WhatsApp Login",actions:{start:{label:"start"},wait:{label:"wait"}}},discord:{icon:"messageSquare",title:"Discord",actions:{react:{label:"react",detailKeys:["channelId","messageId","emoji"]},reactions:{label:"reactions",detailKeys:["channelId","messageId"]},sticker:{label:"sticker",detailKeys:["to","stickerIds"]},poll:{label:"poll",detailKeys:["question","to"]},permissions:{label:"permissions",detailKeys:["channelId"]},readMessages:{label:"read messages",detailKeys:["channelId","limit"]},sendMessage:{label:"send",detailKeys:["to","content"]},editMessage:{label:"edit",detailKeys:["channelId","messageId"]},deleteMessage:{label:"delete",detailKeys:["channelId","messageId"]},threadCreate:{label:"thread create",detailKeys:["channelId","name"]},threadList:{label:"thread list",detailKeys:["guildId","channelId"]},threadReply:{label:"thread reply",detailKeys:["channelId","content"]},pinMessage:{label:"pin",detailKeys:["channelId","messageId"]},unpinMessage:{label:"unpin",detailKeys:["channelId","messageId"]},listPins:{label:"list pins",detailKeys:["channelId"]},searchMessages:{label:"search",detailKeys:["guildId","content"]},memberInfo:{label:"member",detailKeys:["guildId","userId"]},roleInfo:{label:"roles",detailKeys:["guildId"]},emojiList:{label:"emoji list",detailKeys:["guildId"]},roleAdd:{label:"role add",detailKeys:["guildId","userId","roleId"]},roleRemove:{label:"role remove",detailKeys:["guildId","userId","roleId"]},channelInfo:{label:"channel",detailKeys:["channelId"]},channelList:{label:"channels",detailKeys:["guildId"]},voiceStatus:{label:"voice",detailKeys:["guildId","userId"]},eventList:{label:"events",detailKeys:["guildId"]},eventCreate:{label:"event create",detailKeys:["guildId","name"]},timeout:{label:"timeout",detailKeys:["guildId","userId"]},kick:{label:"kick",detailKeys:["guildId","userId"]},ban:{label:"ban",detailKeys:["guildId","userId"]}}},slack:{icon:"messageSquare",title:"Slack",actions:{react:{label:"react",detailKeys:["channelId","messageId","emoji"]},reactions:{label:"reactions",detailKeys:["channelId","messageId"]},sendMessage:{label:"send",detailKeys:["to","content"]},editMessage:{label:"edit",detailKeys:["channelId","messageId"]},deleteMessage:{label:"delete",detailKeys:["channelId","messageId"]},readMessages:{label:"read messages",detailKeys:["channelId","limit"]},pinMessage:{label:"pin",detailKeys:["channelId","messageId"]},unpinMessage:{label:"unpin",detailKeys:["channelId","messageId"]},listPins:{label:"list pins",detailKeys:["channelId"]},memberInfo:{label:"member",detailKeys:["userId"]},emojiList:{label:"emoji list"}}}},Wu={fallback:qu,tools:Vu},rr=Wu,Sa=rr.fallback??{icon:"puzzle"},Gu=rr.tools??{};function Yu(e){return(e??"tool").trim()}function Qu(e){const t=e.replace(/_/g," ").trim();return t?t.split(/\s+/).map(n=>n.length<=2&&n.toUpperCase()===n?n:`${n.at(0)?.toUpperCase()??""}${n.slice(1)}`).join(" "):"Tool"}function Zu(e){const t=e?.trim();if(t)return t.replace(/_/g," ")}function lr(e){if(e!=null){if(typeof e=="string"){const t=e.trim();if(!t)return;const n=t.split(/\r?\n/)[0]?.trim()??"";return n?n.length>160?`${n.slice(0,157)}…`:n:void 0}if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e)){const t=e.map(s=>lr(s)).filter(s=>!!s);if(t.length===0)return;const n=t.slice(0,3).join(", ");return t.length>3?`${n}…`:n}}}function Ju(e,t){if(!e||typeof e!="object")return;let n=e;for(const s of t.split(".")){if(!s||!n||typeof n!="object")return;n=n[s]}return n}function Xu(e,t){for(const n of t){const s=Ju(e,n),i=lr(s);if(i)return i}}function ep(e){if(!e||typeof e!="object")return;const t=e,n=typeof t.path=="string"?t.path:void 0;if(!n)return;const s=typeof t.offset=="number"?t.offset:void 0,i=typeof t.limit=="number"?t.limit:void 0;return s!==void 0&&i!==void 0?`${n}:${s}-${s+i}`:n}function tp(e){if(!e||typeof e!="object")return;const t=e;return typeof t.path=="string"?t.path:void 0}function np(e,t){if(!(!e||!t))return e.actions?.[t]??void 0}function sp(e){const t=Yu(e.name),n=t.toLowerCase(),s=Gu[n],i=s?.icon??Sa.icon??"puzzle",a=s?.title??Qu(t),o=s?.label??t,c=e.args&&typeof e.args=="object"?e.args.action:void 0,l=typeof c=="string"?c.trim():void 0,p=np(s,l),d=Zu(p?.label??l);let u;n==="read"&&(u=ep(e.args)),!u&&(n==="write"||n==="edit"||n==="attach")&&(u=tp(e.args));const h=p?.detailKeys??s?.detailKeys??Sa.detailKeys??[];return!u&&h.length>0&&(u=Xu(e.args,h)),!u&&e.meta&&(u=e.meta),u&&(u=ap(u)),{name:t,icon:i,title:a,label:o,verb:d,detail:u}}function ip(e){const t=[];if(e.verb&&t.push(e.verb),e.detail&&t.push(e.detail),t.length!==0)return t.join(" · ")}function ap(e){return e&&e.replace(/\/Users\/[^/]+/g,"~").replace(/\/home\/[^/]+/g,"~")}const op=80,rp=2,_a=100;function lp(e){const t=e.trim();if(t.startsWith("{")||t.startsWith("["))try{const n=JSON.parse(t);return"```json\n"+JSON.stringify(n,null,2)+"\n```"}catch{}return e}function cp(e){const t=e.split(` +`),n=t.slice(0,rp),s=n.join(` +`);return s.length>_a?s.slice(0,_a)+"…":n.lengthi.kind==="result")){const i=typeof t.toolName=="string"&&t.toolName||typeof t.tool_name=="string"&&t.tool_name||"tool",a=oo(e)??void 0;s.push({kind:"result",name:i,text:a})}return s}function Ta(e,t){const n=sp({name:e.name,args:e.args}),s=ip(n),i=!!e.text?.trim(),a=!!t,o=a?()=>{if(i){t(lp(e.text));return}const u=`## ${n.label} + +${s?`**Command:** \`${s}\` + +`:""}*No output — tool completed successfully.*`;t(u)}:void 0,c=i&&(e.text?.length??0)<=op,l=i&&!c,p=i&&c,d=!i;return r` +
    {u.key!=="Enter"&&u.key!==" "||(u.preventDefault(),o?.())}:g} + > +
    +
    + ${Q[n.icon]} + ${n.label} +
    + ${a?r`${i?"View":""} ${Q.check}`:g} + ${d&&!a?r`${Q.check}`:g} +
    + ${s?r`
    ${s}
    `:g} + ${d?r`
    Completed
    `:g} + ${l?r`
    ${cp(e.text)}
    `:g} + ${p?r`
    ${e.text}
    `:g} +
    + `}function up(e){return Array.isArray(e)?e.filter(Boolean):[]}function pp(e){if(typeof e!="string")return e;const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function fp(e){if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content}function hp(e){return r` +
    + ${li("assistant",e)} +
    + +
    +
    + `}function gp(e,t,n,s){const i=new Date(t).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),a=s?.name??"Assistant";return r` +
    + ${li("assistant",s)} +
    + ${cr({role:"assistant",content:[{type:"text",text:e}],timestamp:t},{isStreaming:!0,showReasoning:!1},n)} + +
    +
    + `}function vp(e,t){const n=Js(e.role),s=t.assistantName??"Assistant",i=n==="user"?"You":n==="assistant"?s:n,a=n==="user"?"user":n==="assistant"?"assistant":"other",o=new Date(e.timestamp).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"});return r` +
    + ${li(e.role,{name:s,avatar:t.assistantAvatar??null})} +
    + ${e.messages.map((c,l)=>cr(c.message,{isStreaming:e.isStreaming&&l===e.messages.length-1,showReasoning:t.showReasoning},t.onOpenSidebar))} + +
    +
    + `}function li(e,t){const n=Js(e),s=t?.name?.trim()||"Assistant",i=t?.avatar?.trim()||"",a=n==="user"?"U":n==="assistant"?s.charAt(0).toUpperCase()||"A":n==="tool"?"⚙":"?",o=n==="user"?"user":n==="assistant"?"assistant":n==="tool"?"tool":"other";return i&&n==="assistant"?mp(i)?r`${s}`:r`
    ${i}
    `:r`
    ${a}
    `}function mp(e){return/^https?:\/\//i.test(e)||/^data:image\//i.test(e)||/^\//.test(e)}function cr(e,t,n){const s=e,i=typeof s.role=="string"?s.role:"unknown",a=jo(e)||i.toLowerCase()==="toolresult"||i.toLowerCase()==="tool_result"||typeof s.toolCallId=="string"||typeof s.tool_call_id=="string",o=dp(e),c=o.length>0,l=oo(e),p=t.showReasoning&&i==="assistant"?Al(e):null,d=l?.trim()?l:null,u=p?_l(p):null,h=d,v=i==="assistant"&&!!h?.trim(),w=["chat-bubble",v?"has-copy":"",t.isStreaming?"streaming":"","fade-in"].filter(Boolean).join(" ");return!h&&c&&a?r`${o.map($=>Ta($,n))}`:!h&&!c?g:r` +
    + ${v?ju(h):g} + ${u?r`
    ${gs(ks(u))}
    `:g} + ${h?r`
    ${gs(ks(h))}
    `:g} + ${o.map($=>Ta($,n))} +
    + `}function bp(e){return r` + + `}var yp=Object.defineProperty,wp=Object.getOwnPropertyDescriptor,mn=(e,t,n,s)=>{for(var i=s>1?void 0:s?wp(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(s?o(t,n,i):o(i))||i);return s&&i&&yp(t,n,i),i};let nt=class extends Ze{constructor(){super(...arguments),this.splitRatio=.6,this.minRatio=.4,this.maxRatio=.7,this.isDragging=!1,this.startX=0,this.startRatio=0,this.handleMouseDown=e=>{this.isDragging=!0,this.startX=e.clientX,this.startRatio=this.splitRatio,this.classList.add("dragging"),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),e.preventDefault()},this.handleMouseMove=e=>{if(!this.isDragging)return;const t=this.parentElement;if(!t)return;const n=t.getBoundingClientRect().width,i=(e.clientX-this.startX)/n;let a=this.startRatio+i;a=Math.max(this.minRatio,Math.min(this.maxRatio,a)),this.dispatchEvent(new CustomEvent("resize",{detail:{splitRatio:a},bubbles:!0,composed:!0}))},this.handleMouseUp=()=>{this.isDragging=!1,this.classList.remove("dragging"),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}}render(){return r``}connectedCallback(){super.connectedCallback(),this.addEventListener("mousedown",this.handleMouseDown)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("mousedown",this.handleMouseDown),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}};nt.styles=Dr` + :host { + width: 4px; + cursor: col-resize; + background: var(--border, #333); + transition: background 150ms ease-out; + flex-shrink: 0; + position: relative; + } + + :host::before { + content: ""; + position: absolute; + top: 0; + left: -4px; + right: -4px; + bottom: 0; + } + + :host(:hover) { + background: var(--accent, #007bff); + } + + :host(.dragging) { + background: var(--accent, #007bff); + } + `;mn([on({type:Number})],nt.prototype,"splitRatio",2);mn([on({type:Number})],nt.prototype,"minRatio",2);mn([on({type:Number})],nt.prototype,"maxRatio",2);nt=mn([Ja("resizable-divider")],nt);const $p=5e3;function xp(e){return e?e.active?r` +
    + ${Q.loader} Compacting context... +
    + `:e.completedAt&&Date.now()-e.completedAt<$p?r` +
    + ${Q.check} Context compacted +
    + `:g:g}function kp(e){const t=e.connected,n=e.sending||e.stream!==null,s=!!(e.canAbort&&e.onAbort),a=e.sessions?.sessions?.find(h=>h.key===e.sessionKey)?.reasoningLevel??"off",o=e.showThinking&&a!=="off",c={name:e.assistantName,avatar:e.assistantAvatar??e.assistantAvatarUrl??null},l=e.connected?"Message (↩ to send, Shift+↩ for line breaks)":"Connect to the gateway to start chatting…",p=e.splitRatio??.6,d=!!(e.sidebarOpen&&e.onCloseSidebar),u=r` +
    + ${e.loading?r`
    Loading chat…
    `:g} + ${Ho(Sp(e),h=>h.key,h=>h.kind==="reading-indicator"?hp(c):h.kind==="stream"?gp(h.text,h.startedAt,e.onOpenSidebar,c):h.kind==="group"?vp(h,{onOpenSidebar:e.onOpenSidebar,showReasoning:o,assistantName:e.assistantName,assistantAvatar:c.avatar}):g)} +
    + `;return r` +
    + ${e.disabledReason?r`
    ${e.disabledReason}
    `:g} + + ${e.error?r`
    ${e.error}
    `:g} + + ${xp(e.compactionStatus)} + + ${e.focusMode?r` + + `:g} + +
    +
    + ${u} +
    + + ${d?r` + e.onSplitRatioChange?.(h.detail.splitRatio)} + > +
    + ${bp({content:e.sidebarContent??null,error:e.sidebarError??null,onClose:e.onCloseSidebar,onViewRawText:()=>{!e.sidebarContent||!e.onOpenSidebar||e.onOpenSidebar(`\`\`\` +${e.sidebarContent} +\`\`\``)}})} +
    + `:g} +
    + + ${e.queue.length?r` +
    +
    Queued (${e.queue.length})
    +
    + ${e.queue.map(h=>r` +
    +
    ${h.text}
    + +
    + `)} +
    +
    + `:g} + +
    + +
    + + +
    +
    +
    + `}const Ca=200;function Ap(e){const t=[];let n=null;for(const s of e){if(s.kind!=="message"){n&&(t.push(n),n=null),t.push(s);continue}const i=zo(s.message),a=Js(i.role),o=i.timestamp||Date.now();!n||n.role!==a?(n&&t.push(n),n={kind:"group",key:`group:${a}:${s.key}`,role:a,messages:[{message:s.message,key:s.key}],timestamp:o,isStreaming:!1}):n.messages.push({message:s.message,key:s.key})}return n&&t.push(n),t}function Sp(e){const t=[],n=Array.isArray(e.messages)?e.messages:[],s=Array.isArray(e.toolMessages)?e.toolMessages:[],i=Math.max(0,n.length-Ca);i>0&&t.push({kind:"message",key:"chat:history:notice",message:{role:"system",content:`Showing last ${Ca} messages (${i} hidden).`,timestamp:Date.now()}});for(let a=i;a0?t.push({kind:"stream",key:a,text:e.stream,startedAt:e.streamStartedAt??Date.now()}):t.push({kind:"reading-indicator",key:a})}return Ap(t)}function Ea(e,t){const n=e,s=typeof n.toolCallId=="string"?n.toolCallId:"";if(s)return`tool:${s}`;const i=typeof n.id=="string"?n.id:"";if(i)return`msg:${i}`;const a=typeof n.messageId=="string"?n.messageId:"";if(a)return`msg:${a}`;const o=typeof n.timestamp=="number"?n.timestamp:null,c=typeof n.role=="string"?n.role:"unknown";return o!=null?`msg:${c}:${o}:${t}`:`msg:${c}:${t}`}function ue(e){if(e)return Array.isArray(e.type)?e.type.filter(n=>n!=="null")[0]??e.type[0]:e.type}function dr(e){if(!e)return"";if(e.default!==void 0)return e.default;switch(ue(e)){case"object":return{};case"array":return[];case"boolean":return!1;case"number":case"integer":return 0;case"string":return"";default:return""}}function bn(e){return e.filter(t=>typeof t=="string").join(".")}function te(e,t){const n=bn(e),s=t[n];if(s)return s;const i=n.split(".");for(const[a,o]of Object.entries(t)){if(!a.includes("*"))continue;const c=a.split(".");if(c.length!==i.length)continue;let l=!0;for(let p=0;pt.toUpperCase())}function _p(e){const t=bn(e).toLowerCase();return t.includes("token")||t.includes("password")||t.includes("secret")||t.includes("apikey")||t.endsWith("key")}const Tp=new Set(["title","description","default","nullable"]);function Cp(e){return Object.keys(e??{}).filter(n=>!Tp.has(n)).length===0}function Ep(e){if(e===void 0)return"";try{return JSON.stringify(e,null,2)??""}catch{return""}}const _t={chevronDown:r``,plus:r``,minus:r``,trash:r``,edit:r``};function ye(e){const{schema:t,value:n,path:s,hints:i,unsupported:a,disabled:o,onPatch:c}=e,l=e.showLabel??!0,p=ue(t),d=te(s,i),u=d?.label??t.title??we(String(s.at(-1))),h=d?.help??t.description,v=bn(s);if(a.has(v))return r`
    +
    ${u}
    +
    Unsupported schema node. Use Raw mode.
    +
    `;if(t.anyOf||t.oneOf){const $=(t.anyOf??t.oneOf??[]).filter(C=>!(C.type==="null"||Array.isArray(C.type)&&C.type.includes("null")));if($.length===1)return ye({...e,schema:$[0]});const k=C=>{if(C.const!==void 0)return C.const;if(C.enum&&C.enum.length===1)return C.enum[0]},T=$.map(k),M=T.every(C=>C!==void 0);if(M&&T.length>0&&T.length<=5){const C=n??t.default;return r` +
    + ${l?r``:g} + ${h?r`
    ${h}
    `:g} +
    + ${T.map((E,pe)=>r` + + `)} +
    +
    + `}if(M&&T.length>5)return Ma({...e,options:T,value:n??t.default});const P=new Set($.map(C=>ue(C)).filter(Boolean)),L=new Set([...P].map(C=>C==="integer"?"number":C));if([...L].every(C=>["string","number","boolean"].includes(C))){const C=L.has("string"),E=L.has("number");if(L.has("boolean")&&L.size===1)return ye({...e,schema:{...t,type:"boolean",anyOf:void 0,oneOf:void 0}});if(C||E)return La({...e,inputType:E&&!C?"number":"text"})}}if(t.enum){const w=t.enum;if(w.length<=5){const $=n??t.default;return r` +
    + ${l?r``:g} + ${h?r`
    ${h}
    `:g} +
    + ${w.map(k=>r` + + `)} +
    +
    + `}return Ma({...e,options:w,value:n??t.default})}if(p==="object")return Mp(e);if(p==="array")return Ip(e);if(p==="boolean"){const w=typeof n=="boolean"?n:typeof t.default=="boolean"?t.default:!1;return r` + + `}return p==="number"||p==="integer"?Lp(e):p==="string"?La({...e,inputType:"text"}):r` +
    +
    ${u}
    +
    Unsupported type: ${p}. Use Raw mode.
    +
    + `}function La(e){const{schema:t,value:n,path:s,hints:i,disabled:a,onPatch:o,inputType:c}=e,l=e.showLabel??!0,p=te(s,i),d=p?.label??t.title??we(String(s.at(-1))),u=p?.help??t.description,h=p?.sensitive??_p(s),v=p?.placeholder??(h?"••••":t.default!==void 0?`Default: ${t.default}`:""),w=n??"";return r` +
    + ${l?r``:g} + ${u?r`
    ${u}
    `:g} +
    + {const k=$.target.value;if(c==="number"){if(k.trim()===""){o(s,void 0);return}const T=Number(k);o(s,Number.isNaN(T)?k:T);return}o(s,k)}} + /> + ${t.default!==void 0?r` + + `:g} +
    +
    + `}function Lp(e){const{schema:t,value:n,path:s,hints:i,disabled:a,onPatch:o}=e,c=e.showLabel??!0,l=te(s,i),p=l?.label??t.title??we(String(s.at(-1))),d=l?.help??t.description,u=n??t.default??"",h=typeof u=="number"?u:0;return r` +
    + ${c?r``:g} + ${d?r`
    ${d}
    `:g} +
    + + {const w=v.target.value,$=w===""?void 0:Number(w);o(s,$)}} + /> + +
    +
    + `}function Ma(e){const{schema:t,value:n,path:s,hints:i,disabled:a,options:o,onPatch:c}=e,l=e.showLabel??!0,p=te(s,i),d=p?.label??t.title??we(String(s.at(-1))),u=p?.help??t.description,h=n??t.default,v=o.findIndex($=>$===h||String($)===String(h)),w="__unset__";return r` +
    + ${l?r``:g} + ${u?r`
    ${u}
    `:g} + +
    + `}function Mp(e){const{schema:t,value:n,path:s,hints:i,unsupported:a,disabled:o,onPatch:c}=e;e.showLabel;const l=te(s,i),p=l?.label??t.title??we(String(s.at(-1))),d=l?.help??t.description,u=n??t.default,h=u&&typeof u=="object"&&!Array.isArray(u)?u:{},v=t.properties??{},$=Object.entries(v).sort((P,L)=>{const C=te([...s,P[0]],i)?.order??0,E=te([...s,L[0]],i)?.order??0;return C!==E?C-E:P[0].localeCompare(L[0])}),k=new Set(Object.keys(v)),T=t.additionalProperties,M=!!T&&typeof T=="object";return s.length===1?r` +
    + ${$.map(([P,L])=>ye({schema:L,value:h[P],path:[...s,P],hints:i,unsupported:a,disabled:o,onPatch:c}))} + ${M?Ia({schema:T,value:h,path:s,hints:i,unsupported:a,disabled:o,reservedKeys:k,onPatch:c}):g} +
    + `:r` +
    + + ${p} + ${_t.chevronDown} + + ${d?r`
    ${d}
    `:g} +
    + ${$.map(([P,L])=>ye({schema:L,value:h[P],path:[...s,P],hints:i,unsupported:a,disabled:o,onPatch:c}))} + ${M?Ia({schema:T,value:h,path:s,hints:i,unsupported:a,disabled:o,reservedKeys:k,onPatch:c}):g} +
    +
    + `}function Ip(e){const{schema:t,value:n,path:s,hints:i,unsupported:a,disabled:o,onPatch:c}=e,l=e.showLabel??!0,p=te(s,i),d=p?.label??t.title??we(String(s.at(-1))),u=p?.help??t.description,h=Array.isArray(t.items)?t.items[0]:t.items;if(!h)return r` +
    +
    ${d}
    +
    Unsupported array schema. Use Raw mode.
    +
    + `;const v=Array.isArray(n)?n:Array.isArray(t.default)?t.default:[];return r` +
    +
    + ${l?r`${d}`:g} + ${v.length} item${v.length!==1?"s":""} + +
    + ${u?r`
    ${u}
    `:g} + + ${v.length===0?r` +
    + No items yet. Click "Add" to create one. +
    + `:r` +
    + ${v.map((w,$)=>r` +
    +
    + #${$+1} + +
    +
    + ${ye({schema:h,value:w,path:[...s,$],hints:i,unsupported:a,disabled:o,showLabel:!1,onPatch:c})} +
    +
    + `)} +
    + `} +
    + `}function Ia(e){const{schema:t,value:n,path:s,hints:i,unsupported:a,disabled:o,reservedKeys:c,onPatch:l}=e,p=Cp(t),d=Object.entries(n??{}).filter(([u])=>!c.has(u));return r` +
    +
    + Custom entries + +
    + + ${d.length===0?r` +
    No custom entries.
    + `:r` +
    + ${d.map(([u,h])=>{const v=[...s,u],w=Ep(h);return r` +
    +
    + {const k=$.target.value.trim();if(!k||k===u)return;const T={...n??{}};k in T||(T[k]=T[u],delete T[u],l(s,T))}} + /> +
    +
    + ${p?r` + + `:ye({schema:t,value:h,path:v,hints:i,unsupported:a,disabled:o,showLabel:!1,onPatch:l})} +
    + +
    + `})} +
    + `} +
    + `}const Ra={env:r``,update:r``,agents:r``,auth:r``,channels:r``,messages:r``,commands:r``,hooks:r``,skills:r``,tools:r``,gateway:r``,wizard:r``,meta:r``,logging:r``,browser:r``,ui:r``,models:r``,bindings:r``,broadcast:r``,audio:r``,session:r``,cron:r``,web:r``,discovery:r``,canvasHost:r``,talk:r``,plugins:r``,default:r``},ci={env:{label:"Environment Variables",description:"Environment variables passed to the gateway process"},update:{label:"Updates",description:"Auto-update settings and release channel"},agents:{label:"Agents",description:"Agent configurations, models, and identities"},auth:{label:"Authentication",description:"API keys and authentication profiles"},channels:{label:"Channels",description:"Messaging channels (Telegram, Discord, Slack, etc.)"},messages:{label:"Messages",description:"Message handling and routing settings"},commands:{label:"Commands",description:"Custom slash commands"},hooks:{label:"Hooks",description:"Webhooks and event hooks"},skills:{label:"Skills",description:"Skill packs and capabilities"},tools:{label:"Tools",description:"Tool configurations (browser, search, etc.)"},gateway:{label:"Gateway",description:"Gateway server settings (port, auth, binding)"},wizard:{label:"Setup Wizard",description:"Setup wizard state and history"},meta:{label:"Metadata",description:"Gateway metadata and version information"},logging:{label:"Logging",description:"Log levels and output configuration"},browser:{label:"Browser",description:"Browser automation settings"},ui:{label:"UI",description:"User interface preferences"},models:{label:"Models",description:"AI model configurations and providers"},bindings:{label:"Bindings",description:"Key bindings and shortcuts"},broadcast:{label:"Broadcast",description:"Broadcast and notification settings"},audio:{label:"Audio",description:"Audio input/output settings"},session:{label:"Session",description:"Session management and persistence"},cron:{label:"Cron",description:"Scheduled tasks and automation"},web:{label:"Web",description:"Web server and API settings"},discovery:{label:"Discovery",description:"Service discovery and networking"},canvasHost:{label:"Canvas Host",description:"Canvas rendering and display"},talk:{label:"Talk",description:"Voice and speech settings"},plugins:{label:"Plugins",description:"Plugin management and extensions"}};function Pa(e){return Ra[e]??Ra.default}function Rp(e,t,n){if(!n)return!0;const s=n.toLowerCase(),i=ci[e];return e.toLowerCase().includes(s)||i&&(i.label.toLowerCase().includes(s)||i.description.toLowerCase().includes(s))?!0:mt(t,s)}function mt(e,t){if(e.title?.toLowerCase().includes(t)||e.description?.toLowerCase().includes(t)||e.enum?.some(s=>String(s).toLowerCase().includes(t)))return!0;if(e.properties){for(const[s,i]of Object.entries(e.properties))if(s.toLowerCase().includes(t)||mt(i,t))return!0}if(e.items){const s=Array.isArray(e.items)?e.items:[e.items];for(const i of s)if(i&&mt(i,t))return!0}if(e.additionalProperties&&typeof e.additionalProperties=="object"&&mt(e.additionalProperties,t))return!0;const n=e.anyOf??e.oneOf??e.allOf;if(n){for(const s of n)if(s&&mt(s,t))return!0}return!1}function Pp(e){if(!e.schema)return r`
    Schema unavailable.
    `;const t=e.schema,n=e.value??{};if(ue(t)!=="object"||!t.properties)return r`
    Unsupported schema. Use Raw.
    `;const s=new Set(e.unsupportedPaths??[]),i=t.properties,a=e.searchQuery??"",o=e.activeSection,c=e.activeSubsection??null,p=Object.entries(i).sort((u,h)=>{const v=te([u[0]],e.uiHints)?.order??50,w=te([h[0]],e.uiHints)?.order??50;return v!==w?v-w:u[0].localeCompare(h[0])}).filter(([u,h])=>!(o&&u!==o||a&&!Rp(u,h,a)));let d=null;if(o&&c&&p.length===1){const u=p[0]?.[1];u&&ue(u)==="object"&&u.properties&&u.properties[c]&&(d={sectionKey:o,subsectionKey:c,schema:u.properties[c]})}return p.length===0?r` +
    +
    ${Q.search}
    +
    + ${a?`No settings match "${a}"`:"No settings in this section"} +
    +
    + `:r` +
    + ${d?(()=>{const{sectionKey:u,subsectionKey:h,schema:v}=d,w=te([u,h],e.uiHints),$=w?.label??v.title??we(h),k=w?.help??v.description??"",T=n[u],M=T&&typeof T=="object"?T[h]:void 0,P=`config-section-${u}-${h}`;return r` +
    +
    + ${Pa(u)} +
    +

    ${$}

    + ${k?r`

    ${k}

    `:g} +
    +
    +
    + ${ye({schema:v,value:M,path:[u,h],hints:e.uiHints,unsupported:s,disabled:e.disabled??!1,showLabel:!1,onPatch:e.onPatch})} +
    +
    + `})():p.map(([u,h])=>{const v=ci[u]??{label:u.charAt(0).toUpperCase()+u.slice(1),description:h.description??""};return r` +
    +
    + ${Pa(u)} +
    +

    ${v.label}

    + ${v.description?r`

    ${v.description}

    `:g} +
    +
    +
    + ${ye({schema:h,value:n[u],path:[u],hints:e.uiHints,unsupported:s,disabled:e.disabled??!1,showLabel:!1,onPatch:e.onPatch})} +
    +
    + `})} +
    + `}const Np=new Set(["title","description","default","nullable"]);function Op(e){return Object.keys(e??{}).filter(n=>!Np.has(n)).length===0}function ur(e){const t=e.filter(i=>i!=null),n=t.length!==e.length,s=[];for(const i of t)s.some(a=>Object.is(a,i))||s.push(i);return{enumValues:s,nullable:n}}function pr(e){return!e||typeof e!="object"?{schema:null,unsupportedPaths:[""]}:wt(e,[])}function wt(e,t){const n=new Set,s={...e},i=bn(t)||"";if(e.anyOf||e.oneOf||e.allOf){const c=Dp(e,t);return c||{schema:e,unsupportedPaths:[i]}}const a=Array.isArray(e.type)&&e.type.includes("null"),o=ue(e)??(e.properties||e.additionalProperties?"object":void 0);if(s.type=o??e.type,s.nullable=a||e.nullable,s.enum){const{enumValues:c,nullable:l}=ur(s.enum);s.enum=c,l&&(s.nullable=!0),c.length===0&&n.add(i)}if(o==="object"){const c=e.properties??{},l={};for(const[p,d]of Object.entries(c)){const u=wt(d,[...t,p]);u.schema&&(l[p]=u.schema);for(const h of u.unsupportedPaths)n.add(h)}if(s.properties=l,e.additionalProperties===!0)n.add(i);else if(e.additionalProperties===!1)s.additionalProperties=!1;else if(e.additionalProperties&&typeof e.additionalProperties=="object"&&!Op(e.additionalProperties)){const p=wt(e.additionalProperties,[...t,"*"]);s.additionalProperties=p.schema??e.additionalProperties,p.unsupportedPaths.length>0&&n.add(i)}}else if(o==="array"){const c=Array.isArray(e.items)?e.items[0]:e.items;if(!c)n.add(i);else{const l=wt(c,[...t,"*"]);s.items=l.schema??c,l.unsupportedPaths.length>0&&n.add(i)}}else o!=="string"&&o!=="number"&&o!=="integer"&&o!=="boolean"&&!s.enum&&n.add(i);return{schema:s,unsupportedPaths:Array.from(n)}}function Dp(e,t){if(e.allOf)return null;const n=e.anyOf??e.oneOf;if(!n)return null;const s=[],i=[];let a=!1;for(const c of n){if(!c||typeof c!="object")return null;if(Array.isArray(c.enum)){const{enumValues:l,nullable:p}=ur(c.enum);s.push(...l),p&&(a=!0);continue}if("const"in c){if(c.const==null){a=!0;continue}s.push(c.const);continue}if(ue(c)==="null"){a=!0;continue}i.push(c)}if(s.length>0&&i.length===0){const c=[];for(const l of s)c.some(p=>Object.is(p,l))||c.push(l);return{schema:{...e,enum:c,nullable:a,anyOf:void 0,oneOf:void 0,allOf:void 0},unsupportedPaths:[]}}if(i.length===1){const c=wt(i[0],t);return c.schema&&(c.schema.nullable=a||c.schema.nullable),c}const o=["string","number","integer","boolean"];return i.length>0&&s.length===0&&i.every(c=>c.type&&o.includes(String(c.type)))?{schema:{...e,nullable:a},unsupportedPaths:[]}:null}const As={all:r``,env:r``,update:r``,agents:r``,auth:r``,channels:r``,messages:r``,commands:r``,hooks:r``,skills:r``,tools:r``,gateway:r``,wizard:r``,meta:r``,logging:r``,browser:r``,ui:r``,models:r``,bindings:r``,broadcast:r``,audio:r``,session:r``,cron:r``,web:r``,discovery:r``,canvasHost:r``,talk:r``,plugins:r``,default:r``},Na=[{key:"env",label:"Environment"},{key:"update",label:"Updates"},{key:"agents",label:"Agents"},{key:"auth",label:"Authentication"},{key:"channels",label:"Channels"},{key:"messages",label:"Messages"},{key:"commands",label:"Commands"},{key:"hooks",label:"Hooks"},{key:"skills",label:"Skills"},{key:"tools",label:"Tools"},{key:"gateway",label:"Gateway"},{key:"wizard",label:"Setup Wizard"}],Oa="__all__";function Da(e){return As[e]??As.default}function Bp(e,t){const n=ci[e];return n||{label:t?.title??we(e),description:t?.description??""}}function Fp(e){const{key:t,schema:n,uiHints:s}=e;if(!n||ue(n)!=="object"||!n.properties)return[];const i=Object.entries(n.properties).map(([a,o])=>{const c=te([t,a],s),l=c?.label??o.title??we(a),p=c?.help??o.description??"",d=c?.order??50;return{key:a,label:l,description:p,order:d}});return i.sort((a,o)=>a.order!==o.order?a.order-o.order:a.key.localeCompare(o.key)),i}function Up(e,t){if(!e||!t)return[];const n=[];function s(i,a,o){if(i===a)return;if(typeof i!=typeof a){n.push({path:o,from:i,to:a});return}if(typeof i!="object"||i===null||a===null){i!==a&&n.push({path:o,from:i,to:a});return}if(Array.isArray(i)&&Array.isArray(a)){JSON.stringify(i)!==JSON.stringify(a)&&n.push({path:o,from:i,to:a});return}const c=i,l=a,p=new Set([...Object.keys(c),...Object.keys(l)]);for(const d of p)s(c[d],l[d],o?`${o}.${d}`:d)}return s(e,t,""),n}function Ba(e,t=40){let n;try{n=JSON.stringify(e)??String(e)}catch{n=String(e)}return n.length<=t?n:n.slice(0,t-3)+"..."}function Kp(e){const t=e.valid==null?"unknown":e.valid?"valid":"invalid",n=pr(e.schema),s=n.schema?n.unsupportedPaths.length>0:!1,i=n.schema?.properties??{},a=Na.filter(E=>E.key in i),o=new Set(Na.map(E=>E.key)),c=Object.keys(i).filter(E=>!o.has(E)).map(E=>({key:E,label:E.charAt(0).toUpperCase()+E.slice(1)})),l=[...a,...c],p=e.activeSection&&n.schema&&ue(n.schema)==="object"?n.schema.properties?.[e.activeSection]:void 0,d=e.activeSection?Bp(e.activeSection,p):null,u=e.activeSection?Fp({key:e.activeSection,schema:p,uiHints:e.uiHints}):[],h=e.formMode==="form"&&!!e.activeSection&&u.length>0,v=e.activeSubsection===Oa,w=e.searchQuery||v?null:e.activeSubsection??u[0]?.key??null,$=e.formMode==="form"?Up(e.originalValue,e.formValue):[],k=e.formMode==="raw"&&e.raw!==e.originalRaw,T=e.formMode==="form"?$.length>0:k,M=!!e.formValue&&!e.loading&&!!n.schema,P=e.connected&&!e.saving&&T&&(e.formMode==="raw"?!0:M),L=e.connected&&!e.applying&&!e.updating&&T&&(e.formMode==="raw"?!0:M),C=e.connected&&!e.applying&&!e.updating;return r` +
    + + + + +
    + +
    +
    + ${T?r` + ${e.formMode==="raw"?"Unsaved changes":`${$.length} unsaved change${$.length!==1?"s":""}`} + `:r` + No changes + `} +
    +
    + + + + +
    +
    + + + ${T&&e.formMode==="form"?r` +
    + + View ${$.length} pending change${$.length!==1?"s":""} + + + + +
    + ${$.map(E=>r` +
    +
    ${E.path}
    +
    + ${Ba(E.from)} + + ${Ba(E.to)} +
    +
    + `)} +
    +
    + `:g} + + ${d&&e.formMode==="form"?r` +
    +
    ${Da(e.activeSection??"")}
    +
    +
    ${d.label}
    + ${d.description?r`
    ${d.description}
    `:g} +
    +
    + `:g} + + ${h?r` +
    + + ${u.map(E=>r` + + `)} +
    + `:g} + + +
    + ${e.formMode==="form"?r` + ${e.schemaLoading?r`
    +
    + Loading schema… +
    `:Pp({schema:n.schema,uiHints:e.uiHints,value:e.formValue,disabled:e.loading||!e.formValue,unsupportedPaths:n.unsupportedPaths,onPatch:e.onFormPatch,searchQuery:e.searchQuery,activeSection:e.activeSection,activeSubsection:w})} + ${s?r`
    + Form view can't safely edit some fields. + Use Raw to avoid losing config entries. +
    `:g} + `:r` + + `} +
    + + ${e.issues.length>0?r`
    +
    ${JSON.stringify(e.issues,null,2)}
    +
    `:g} +
    +
    + `}function Hp(e){if(!e&&e!==0)return"n/a";const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.round(t/60);return n<60?`${n}m`:`${Math.round(n/60)}h`}function zp(e,t){const n=t.snapshot,s=n?.channels;if(!n||!s)return!1;const i=s[e],a=typeof i?.configured=="boolean"&&i.configured,o=typeof i?.running=="boolean"&&i.running,c=typeof i?.connected=="boolean"&&i.connected,p=(n.channelAccounts?.[e]??[]).some(d=>d.configured||d.running||d.connected);return a||o||c||p}function jp(e,t){return t?.[e]?.length??0}function fr(e,t){const n=jp(e,t);return n<2?g:r``}function qp(e,t){let n=e;for(const s of t){if(!n)return null;const i=ue(n);if(i==="object"){const a=n.properties??{};if(typeof s=="string"&&a[s]){n=a[s];continue}const o=n.additionalProperties;if(typeof s=="string"&&o&&typeof o=="object"){n=o;continue}return null}if(i==="array"){if(typeof s!="number")return null;n=(Array.isArray(n.items)?n.items[0]:n.items)??null;continue}return null}return n}function Vp(e,t){const s=(e.channels??{})[t],i=e[t];return(s&&typeof s=="object"?s:null)??(i&&typeof i=="object"?i:null)??{}}function Wp(e){const t=pr(e.schema),n=t.schema;if(!n)return r`
    Schema unavailable. Use Raw.
    `;const s=qp(n,["channels",e.channelId]);if(!s)return r`
    Channel config schema unavailable.
    `;const i=e.configValue??{},a=Vp(i,e.channelId);return r` +
    + ${ye({schema:s,value:a,path:["channels",e.channelId],hints:e.uiHints,unsupported:new Set(t.unsupportedPaths),disabled:e.disabled,showLabel:!1,onPatch:e.onPatch})} +
    + `}function $e(e){const{channelId:t,props:n}=e,s=n.configSaving||n.configSchemaLoading;return r` +
    + ${n.configSchemaLoading?r`
    Loading config schema…
    `:Wp({channelId:t,configValue:n.configForm,schema:n.configSchema,uiHints:n.configUiHints,disabled:s,onPatch:n.onConfigPatch})} +
    + + +
    +
    + `}function Gp(e){const{props:t,discord:n,accountCountLabel:s}=e;return r` +
    +
    Discord
    +
    Bot status and channel configuration.
    + ${s} + +
    +
    + Configured + ${n?.configured?"Yes":"No"} +
    +
    + Running + ${n?.running?"Yes":"No"} +
    +
    + Last start + ${n?.lastStartAt?O(n.lastStartAt):"n/a"} +
    +
    + Last probe + ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"} +
    +
    + + ${n?.lastError?r`
    + ${n.lastError} +
    `:g} + + ${n?.probe?r`
    + Probe ${n.probe.ok?"ok":"failed"} · + ${n.probe.status??""} ${n.probe.error??""} +
    `:g} + + ${$e({channelId:"discord",props:t})} + +
    + +
    +
    + `}function Yp(e){const{props:t,googleChat:n,accountCountLabel:s}=e;return r` +
    +
    Google Chat
    +
    Chat API webhook status and channel configuration.
    + ${s} + +
    +
    + Configured + ${n?n.configured?"Yes":"No":"n/a"} +
    +
    + Running + ${n?n.running?"Yes":"No":"n/a"} +
    +
    + Credential + ${n?.credentialSource??"n/a"} +
    +
    + Audience + + ${n?.audienceType?`${n.audienceType}${n.audience?` · ${n.audience}`:""}`:"n/a"} + +
    +
    + Last start + ${n?.lastStartAt?O(n.lastStartAt):"n/a"} +
    +
    + Last probe + ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"} +
    +
    + + ${n?.lastError?r`
    + ${n.lastError} +
    `:g} + + ${n?.probe?r`
    + Probe ${n.probe.ok?"ok":"failed"} · + ${n.probe.status??""} ${n.probe.error??""} +
    `:g} + + ${$e({channelId:"googlechat",props:t})} + +
    + +
    +
    + `}function Qp(e){const{props:t,imessage:n,accountCountLabel:s}=e;return r` +
    +
    iMessage
    +
    macOS bridge status and channel configuration.
    + ${s} + +
    +
    + Configured + ${n?.configured?"Yes":"No"} +
    +
    + Running + ${n?.running?"Yes":"No"} +
    +
    + Last start + ${n?.lastStartAt?O(n.lastStartAt):"n/a"} +
    +
    + Last probe + ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"} +
    +
    + + ${n?.lastError?r`
    + ${n.lastError} +
    `:g} + + ${n?.probe?r`
    + Probe ${n.probe.ok?"ok":"failed"} · + ${n.probe.error??""} +
    `:g} + + ${$e({channelId:"imessage",props:t})} + +
    + +
    +
    + `}function Zp(e){const{values:t,original:n}=e;return t.name!==n.name||t.displayName!==n.displayName||t.about!==n.about||t.picture!==n.picture||t.banner!==n.banner||t.website!==n.website||t.nip05!==n.nip05||t.lud16!==n.lud16}function Jp(e){const{state:t,callbacks:n,accountId:s}=e,i=Zp(t),a=(c,l,p={})=>{const{type:d="text",placeholder:u,maxLength:h,help:v}=p,w=t.values[c]??"",$=t.fieldErrors[c],k=`nostr-profile-${c}`;return d==="textarea"?r` +
    + + + ${v?r`
    ${v}
    `:g} + ${$?r`
    ${$}
    `:g} +
    + `:r` +
    + + {const M=T.target;n.onFieldChange(c,M.value)}} + ?disabled=${t.saving} + /> + ${v?r`
    ${v}
    `:g} + ${$?r`
    ${$}
    `:g} +
    + `},o=()=>{const c=t.values.picture;return c?r` +
    + Profile picture preview{const p=l.target;p.style.display="none"}} + @load=${l=>{const p=l.target;p.style.display="block"}} + /> +
    + `:g};return r` +
    +
    +
    Edit Profile
    +
    Account: ${s}
    +
    + + ${t.error?r`
    ${t.error}
    `:g} + + ${t.success?r`
    ${t.success}
    `:g} + + ${o()} + + ${a("name","Username",{placeholder:"satoshi",maxLength:256,help:"Short username (e.g., satoshi)"})} + + ${a("displayName","Display Name",{placeholder:"Satoshi Nakamoto",maxLength:256,help:"Your full display name"})} + + ${a("about","Bio",{type:"textarea",placeholder:"Tell people about yourself...",maxLength:2e3,help:"A brief bio or description"})} + + ${a("picture","Avatar URL",{type:"url",placeholder:"https://example.com/avatar.jpg",help:"HTTPS URL to your profile picture"})} + + ${t.showAdvanced?r` +
    +
    Advanced
    + + ${a("banner","Banner URL",{type:"url",placeholder:"https://example.com/banner.jpg",help:"HTTPS URL to a banner image"})} + + ${a("website","Website",{type:"url",placeholder:"https://example.com",help:"Your personal website"})} + + ${a("nip05","NIP-05 Identifier",{placeholder:"you@example.com",help:"Verifiable identifier (e.g., you@domain.com)"})} + + ${a("lud16","Lightning Address",{placeholder:"you@getalby.com",help:"Lightning address for tips (LUD-16)"})} +
    + `:g} + +
    + + + + + + + +
    + + ${i?r`
    + You have unsaved changes +
    `:g} +
    + `}function Xp(e){const t={name:e?.name??"",displayName:e?.displayName??"",about:e?.about??"",picture:e?.picture??"",banner:e?.banner??"",website:e?.website??"",nip05:e?.nip05??"",lud16:e?.lud16??""};return{values:t,original:{...t},saving:!1,importing:!1,error:null,success:null,fieldErrors:{},showAdvanced:!!(e?.banner||e?.website||e?.nip05||e?.lud16)}}function Fa(e){return e?e.length<=20?e:`${e.slice(0,8)}...${e.slice(-8)}`:"n/a"}function ef(e){const{props:t,nostr:n,nostrAccounts:s,accountCountLabel:i,profileFormState:a,profileFormCallbacks:o,onEditProfile:c}=e,l=s[0],p=n?.configured??l?.configured??!1,d=n?.running??l?.running??!1,u=n?.publicKey??l?.publicKey,h=n?.lastStartAt??l?.lastStartAt??null,v=n?.lastError??l?.lastError??null,w=s.length>1,$=a!=null,k=M=>{const P=M.publicKey,L=M.profile,C=L?.displayName??L?.name??M.name??M.accountId;return r` + + `},T=()=>{if($&&o)return Jp({state:a,callbacks:o,accountId:s[0]?.accountId??"default"});const M=l?.profile??n?.profile,{name:P,displayName:L,about:C,picture:E,nip05:pe}=M??{},yn=P||L||C||E||pe;return r` +
    +
    +
    Profile
    + ${p?r` + + `:g} +
    + ${yn?r` +
    + ${E?r` +
    + Profile picture{wn.target.style.display="none"}} + /> +
    + `:g} + ${P?r`
    Name${P}
    `:g} + ${L?r`
    Display Name${L}
    `:g} + ${C?r`
    About${C}
    `:g} + ${pe?r`
    NIP-05${pe}
    `:g} +
    + `:r` +
    + No profile set. Click "Edit Profile" to add your name, bio, and avatar. +
    + `} +
    + `};return r` +
    +
    Nostr
    +
    Decentralized DMs via Nostr relays (NIP-04).
    + ${i} + + ${w?r` + + `:r` +
    +
    + Configured + ${p?"Yes":"No"} +
    +
    + Running + ${d?"Yes":"No"} +
    +
    + Public Key + ${Fa(u)} +
    +
    + Last start + ${h?O(h):"n/a"} +
    +
    + `} + + ${v?r`
    ${v}
    `:g} + + ${T()} + + ${$e({channelId:"nostr",props:t})} + +
    + +
    +
    + `}function tf(e){const{props:t,signal:n,accountCountLabel:s}=e;return r` +
    +
    Signal
    +
    signal-cli status and channel configuration.
    + ${s} + +
    +
    + Configured + ${n?.configured?"Yes":"No"} +
    +
    + Running + ${n?.running?"Yes":"No"} +
    +
    + Base URL + ${n?.baseUrl??"n/a"} +
    +
    + Last start + ${n?.lastStartAt?O(n.lastStartAt):"n/a"} +
    +
    + Last probe + ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"} +
    +
    + + ${n?.lastError?r`
    + ${n.lastError} +
    `:g} + + ${n?.probe?r`
    + Probe ${n.probe.ok?"ok":"failed"} · + ${n.probe.status??""} ${n.probe.error??""} +
    `:g} + + ${$e({channelId:"signal",props:t})} + +
    + +
    +
    + `}function nf(e){const{props:t,slack:n,accountCountLabel:s}=e;return r` +
    +
    Slack
    +
    Socket mode status and channel configuration.
    + ${s} + +
    +
    + Configured + ${n?.configured?"Yes":"No"} +
    +
    + Running + ${n?.running?"Yes":"No"} +
    +
    + Last start + ${n?.lastStartAt?O(n.lastStartAt):"n/a"} +
    +
    + Last probe + ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"} +
    +
    + + ${n?.lastError?r`
    + ${n.lastError} +
    `:g} + + ${n?.probe?r`
    + Probe ${n.probe.ok?"ok":"failed"} · + ${n.probe.status??""} ${n.probe.error??""} +
    `:g} + + ${$e({channelId:"slack",props:t})} + +
    + +
    +
    + `}function sf(e){const{props:t,telegram:n,telegramAccounts:s,accountCountLabel:i}=e,a=s.length>1,o=c=>{const p=c.probe?.bot?.username,d=c.name||c.accountId;return r` + + `};return r` +
    +
    Telegram
    +
    Bot status and channel configuration.
    + ${i} + + ${a?r` + + `:r` +
    +
    + Configured + ${n?.configured?"Yes":"No"} +
    +
    + Running + ${n?.running?"Yes":"No"} +
    +
    + Mode + ${n?.mode??"n/a"} +
    +
    + Last start + ${n?.lastStartAt?O(n.lastStartAt):"n/a"} +
    +
    + Last probe + ${n?.lastProbeAt?O(n.lastProbeAt):"n/a"} +
    +
    + `} + + ${n?.lastError?r`
    + ${n.lastError} +
    `:g} + + ${n?.probe?r`
    + Probe ${n.probe.ok?"ok":"failed"} · + ${n.probe.status??""} ${n.probe.error??""} +
    `:g} + + ${$e({channelId:"telegram",props:t})} + +
    + +
    +
    + `}function af(e){const{props:t,whatsapp:n,accountCountLabel:s}=e;return r` +
    +
    WhatsApp
    +
    Link WhatsApp Web and monitor connection health.
    + ${s} + +
    +
    + Configured + ${n?.configured?"Yes":"No"} +
    +
    + Linked + ${n?.linked?"Yes":"No"} +
    +
    + Running + ${n?.running?"Yes":"No"} +
    +
    + Connected + ${n?.connected?"Yes":"No"} +
    +
    + Last connect + + ${n?.lastConnectedAt?O(n.lastConnectedAt):"n/a"} + +
    +
    + Last message + + ${n?.lastMessageAt?O(n.lastMessageAt):"n/a"} + +
    +
    + Auth age + + ${n?.authAgeMs!=null?Hp(n.authAgeMs):"n/a"} + +
    +
    + + ${n?.lastError?r`
    + ${n.lastError} +
    `:g} + + ${t.whatsappMessage?r`
    + ${t.whatsappMessage} +
    `:g} + + ${t.whatsappQrDataUrl?r`
    + WhatsApp QR +
    `:g} + +
    + + + + + +
    + + ${$e({channelId:"whatsapp",props:t})} +
    + `}function of(e){const t=e.snapshot?.channels,n=t?.whatsapp??void 0,s=t?.telegram??void 0,i=t?.discord??null;t?.googlechat;const a=t?.slack??null,o=t?.signal??null,c=t?.imessage??null,l=t?.nostr??null,d=rf(e.snapshot).map((u,h)=>({key:u,enabled:zp(u,e),order:h})).sort((u,h)=>u.enabled!==h.enabled?u.enabled?-1:1:u.order-h.order);return r` +
    + ${d.map(u=>lf(u.key,e,{whatsapp:n,telegram:s,discord:i,slack:a,signal:o,imessage:c,nostr:l,channelAccounts:e.snapshot?.channelAccounts??null}))} +
    + +
    +
    +
    +
    Channel health
    +
    Channel status snapshots from the gateway.
    +
    +
    ${e.lastSuccessAt?O(e.lastSuccessAt):"n/a"}
    +
    + ${e.lastError?r`
    + ${e.lastError} +
    `:g} +
    +${e.snapshot?JSON.stringify(e.snapshot,null,2):"No snapshot yet."}
    +      
    +
    + `}function rf(e){return e?.channelMeta?.length?e.channelMeta.map(t=>t.id):e?.channelOrder?.length?e.channelOrder:["whatsapp","telegram","discord","googlechat","slack","signal","imessage","nostr"]}function lf(e,t,n){const s=fr(e,n.channelAccounts);switch(e){case"whatsapp":return af({props:t,whatsapp:n.whatsapp,accountCountLabel:s});case"telegram":return sf({props:t,telegram:n.telegram,telegramAccounts:n.channelAccounts?.telegram??[],accountCountLabel:s});case"discord":return Gp({props:t,discord:n.discord,accountCountLabel:s});case"googlechat":return Yp({props:t,accountCountLabel:s});case"slack":return nf({props:t,slack:n.slack,accountCountLabel:s});case"signal":return tf({props:t,signal:n.signal,accountCountLabel:s});case"imessage":return Qp({props:t,imessage:n.imessage,accountCountLabel:s});case"nostr":{const i=n.channelAccounts?.nostr??[],a=i[0],o=a?.accountId??"default",c=a?.profile??null,l=t.nostrProfileAccountId===o?t.nostrProfileFormState:null,p=l?{onFieldChange:t.onNostrProfileFieldChange,onSave:t.onNostrProfileSave,onImport:t.onNostrProfileImport,onCancel:t.onNostrProfileCancel,onToggleAdvanced:t.onNostrProfileToggleAdvanced}:null;return ef({props:t,nostr:n.nostr,nostrAccounts:i,accountCountLabel:s,profileFormState:l,profileFormCallbacks:p,onEditProfile:()=>t.onNostrProfileEdit(o,c)})}default:return cf(e,t,n.channelAccounts??{})}}function cf(e,t,n){const s=uf(t.snapshot,e),i=t.snapshot?.channels?.[e],a=typeof i?.configured=="boolean"?i.configured:void 0,o=typeof i?.running=="boolean"?i.running:void 0,c=typeof i?.connected=="boolean"?i.connected:void 0,l=typeof i?.lastError=="string"?i.lastError:void 0,p=n[e]??[],d=fr(e,n);return r` +
    +
    ${s}
    +
    Channel status and configuration.
    + ${d} + + ${p.length>0?r` + + `:r` +
    +
    + Configured + ${a==null?"n/a":a?"Yes":"No"} +
    +
    + Running + ${o==null?"n/a":o?"Yes":"No"} +
    +
    + Connected + ${c==null?"n/a":c?"Yes":"No"} +
    +
    + `} + + ${l?r`
    + ${l} +
    `:g} + + ${$e({channelId:e,props:t})} +
    + `}function df(e){return e?.channelMeta?.length?Object.fromEntries(e.channelMeta.map(t=>[t.id,t])):{}}function uf(e,t){return df(e)[t]?.label??e?.channelLabels?.[t]??t}const pf=600*1e3;function hr(e){return e.lastInboundAt?Date.now()-e.lastInboundAt
    + `:r` +
    + Auth failed. Re-copy a tokenized URL with + clawdbot dashboard --no-open, or update the token, + then click Connect. + +
    + `})(),a=(()=>{if(e.connected||!e.lastError||(typeof window<"u"?window.isSecureContext:!0)!==!1)return null;const c=e.lastError.toLowerCase();return!c.includes("secure context")&&!c.includes("device identity required")?null:r` +
    + This page is HTTP, so the browser blocks device identity. Use HTTPS (Tailscale Serve) or + open http://127.0.0.1:18789 on the gateway host. +
    + If you must stay on HTTP, set + gateway.controlUi.allowInsecureAuth: true (token-only). +
    + +
    + `})();return r` +
    +
    +
    Gateway Access
    +
    Where the dashboard connects and how it authenticates.
    +
    + + + + +
    +
    + + + Click Connect to apply connection changes. +
    +
    + +
    +
    Snapshot
    +
    Latest gateway handshake information.
    +
    +
    +
    Status
    +
    + ${e.connected?"Connected":"Disconnected"} +
    +
    +
    +
    Uptime
    +
    ${n}
    +
    +
    +
    Tick Interval
    +
    ${s}
    +
    +
    +
    Last Channels Refresh
    +
    + ${e.lastChannelsRefresh?O(e.lastChannelsRefresh):"n/a"} +
    +
    +
    + ${e.lastError?r`
    +
    ${e.lastError}
    + ${i??""} + ${a??""} +
    `:r`
    + Use Channels to link WhatsApp, Telegram, Discord, Signal, or iMessage. +
    `} +
    +
    + +
    +
    +
    Instances
    +
    ${e.presenceCount}
    +
    Presence beacons in the last 5 minutes.
    +
    +
    +
    Sessions
    +
    ${e.sessionsCount??"n/a"}
    +
    Recent session keys tracked by the gateway.
    +
    +
    +
    Cron
    +
    + ${e.cronEnabled==null?"n/a":e.cronEnabled?"Enabled":"Disabled"} +
    +
    Next wake ${gr(e.cronNext)}
    +
    +
    + +
    +
    Notes
    +
    Quick reminders for remote control setups.
    +
    +
    +
    Tailscale serve
    +
    + Prefer serve mode to keep the gateway on loopback with tailnet auth. +
    +
    +
    +
    Session hygiene
    +
    Use /new or sessions.patch to reset context.
    +
    +
    +
    Cron reminders
    +
    Use isolated sessions for recurring runs.
    +
    +
    +
    + `}const rh=["","off","minimal","low","medium","high"],lh=["","off","on"],ch=[{value:"",label:"inherit"},{value:"off",label:"off (explicit)"},{value:"on",label:"on"}],dh=["","off","on","stream"];function uh(e){if(!e)return"";const t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t}function vr(e){return uh(e)==="zai"}function ph(e){return vr(e)?lh:rh}function fh(e,t){return!t||!e||e==="off"?e:"on"}function hh(e,t){return e?t&&e==="on"?"low":e:null}function gh(e){const t=e.result?.sessions??[];return r` +
    +
    +
    +
    Sessions
    +
    Active session keys and per-session overrides.
    +
    + +
    + +
    + + + + +
    + + ${e.error?r`
    ${e.error}
    `:g} + +
    + ${e.result?`Store: ${e.result.path}`:""} +
    + +
    +
    +
    Key
    +
    Label
    +
    Kind
    +
    Updated
    +
    Tokens
    +
    Thinking
    +
    Verbose
    +
    Reasoning
    +
    Actions
    +
    + ${t.length===0?r`
    No sessions found.
    `:t.map(n=>vh(n,e.basePath,e.onPatch,e.onDelete,e.loading))} +
    +
    + `}function vh(e,t,n,s,i){const a=e.updatedAt?O(e.updatedAt):"n/a",o=e.thinkingLevel??"",c=vr(e.modelProvider),l=fh(o,c),p=ph(e.modelProvider),d=e.verboseLevel??"",u=e.reasoningLevel??"",h=e.displayName??e.key,v=e.kind!=="global",w=v?`${Rs("chat",t)}?session=${encodeURIComponent(e.key)}`:null;return r` +
    +
    ${v?r`${h}`:h}
    +
    + {const k=$.target.value.trim();n(e.key,{label:k||null})}} + /> +
    +
    ${e.kind}
    +
    ${a}
    +
    ${bf(e)}
    +
    + +
    +
    + +
    +
    + +
    +
    + +
    +
    + `}function mh(e){const t=Math.max(0,e),n=Math.floor(t/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60);return s<60?`${s}m`:`${Math.floor(s/60)}h`}function Ie(e,t){return t?r`
    ${e}${t}
    `:g}function bh(e){const t=e.execApprovalQueue[0];if(!t)return g;const n=t.request,s=t.expiresAtMs-Date.now(),i=s>0?`expires in ${mh(s)}`:"expired",a=e.execApprovalQueue.length;return r` + + `}function yh(e){const t=e.report?.skills??[],n=e.filter.trim().toLowerCase(),s=n?t.filter(i=>[i.name,i.description,i.source].join(" ").toLowerCase().includes(n)):t;return r` +
    +
    +
    +
    Skills
    +
    Bundled, managed, and workspace skills.
    +
    + +
    + +
    + +
    ${s.length} shown
    +
    + + ${e.error?r`
    ${e.error}
    `:g} + + ${s.length===0?r`
    No skills found.
    `:r` +
    + ${s.map(i=>wh(i,e))} +
    + `} +
    + `}function wh(e,t){const n=t.busyKey===e.skillKey,s=t.edits[e.skillKey]??"",i=t.messages[e.skillKey]??null,a=e.install.length>0&&e.missing.bins.length>0,o=[...e.missing.bins.map(l=>`bin:${l}`),...e.missing.env.map(l=>`env:${l}`),...e.missing.config.map(l=>`config:${l}`),...e.missing.os.map(l=>`os:${l}`)],c=[];return e.disabled&&c.push("disabled"),e.blockedByAllowlist&&c.push("blocked by allowlist"),r` +
    +
    +
    + ${e.emoji?`${e.emoji} `:""}${e.name} +
    +
    ${as(e.description,140)}
    +
    + ${e.source} + + ${e.eligible?"eligible":"blocked"} + + ${e.disabled?r`disabled`:g} +
    + ${o.length>0?r` +
    + Missing: ${o.join(", ")} +
    + `:g} + ${c.length>0?r` +
    + Reason: ${c.join(", ")} +
    + `:g} +
    +
    +
    + + ${a?r``:g} +
    + ${i?r`
    + ${i.message} +
    `:g} + ${e.primaryEnv?r` +
    + API key + t.onEdit(e.skillKey,l.target.value)} + /> +
    + + `:g} +
    +
    + `}function $h(e,t){const n=Rs(t,e.basePath);return r` + {s.defaultPrevented||s.button!==0||s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||(s.preventDefault(),e.setTab(t))}} + title=${ss(t)} + > + + ${ss(t)} + + `}function xh(e){const t=kh(e.sessionKey,e.sessionsResult),n=e.onboarding,s=e.onboarding,i=e.onboarding?!1:e.settings.chatShowThinking,a=e.onboarding?!0:e.settings.chatFocusMode,o=r``,c=r``;return r` +
    + + + | + + +
    + `}function kh(e,t){const n=new Set,s=[],i=t?.sessions?.find(a=>a.key===e);if(n.add(e),s.push({key:e,displayName:i?.displayName}),t?.sessions)for(const a of t.sessions)n.has(a.key)||(n.add(a.key),s.push({key:a.key,displayName:a.displayName}));return s}const Ah=["system","light","dark"];function Sh(e){const t=Math.max(0,Ah.indexOf(e.theme)),n=s=>i=>{const o={element:i.currentTarget};(i.clientX||i.clientY)&&(o.pointerClientX=i.clientX,o.pointerClientY=i.clientY),e.setTheme(s,o)};return r` +
    +
    + + + + +
    +
    + `}function _h(){return r` + + `}function Th(){return r` + + `}function Ch(){return r` + + `}const Eh=/^data:/i,Lh=/^https?:\/\//i;function Mh(e){const t=e.agentsList?.agents??[],s=eo(e.sessionKey)?.agentId??e.agentsList?.defaultId??"main",a=t.find(c=>c.id===s)?.identity,o=a?.avatarUrl??a?.avatar;if(o)return Eh.test(o)||Lh.test(o)?o:a?.avatarUrl}function Ih(e){const t=e.presenceEntries.length,n=e.sessionsResult?.count??null,s=e.cronStatus?.nextWakeAtMs??null,i=e.connected?null:"Disconnected from gateway.",a=e.tab==="chat",o=a&&(e.settings.chatFocusMode||e.onboarding),c=e.onboarding?!1:e.settings.chatShowThinking,l=Mh(e),p=e.chatAvatarUrl??l??null;return r` +
    +
    +
    + +
    + +
    +
    CLAWDBOT
    +
    Gateway Dashboard
    +
    +
    +
    +
    +
    + + Health + ${e.connected?"OK":"Offline"} +
    + ${Sh(e)} +
    +
    + +
    +
    +
    +
    ${ss(e.tab)}
    +
    ${ml(e.tab)}
    +
    +
    + ${e.lastError?r`
    ${e.lastError}
    `:g} + ${a?xh(e):g} +
    +
    + + ${e.tab==="overview"?oh({connected:e.connected,hello:e.hello,settings:e.settings,password:e.password,lastError:e.lastError,presenceCount:t,sessionsCount:n,cronEnabled:e.cronStatus?.enabled??null,cronNext:s,lastChannelsRefresh:e.channelsLastSuccess,onSettingsChange:d=>e.applySettings(d),onPasswordChange:d=>e.password=d,onSessionKeyChange:d=>{e.sessionKey=d,e.chatMessage="",e.resetToolStream(),e.applySettings({...e.settings,sessionKey:d,lastActiveSessionKey:d}),e.loadAssistantIdentity()},onConnect:()=>e.connect(),onRefresh:()=>e.loadOverview()}):g} + + ${e.tab==="channels"?of({connected:e.connected,loading:e.channelsLoading,snapshot:e.channelsSnapshot,lastError:e.channelsError,lastSuccessAt:e.channelsLastSuccess,whatsappMessage:e.whatsappLoginMessage,whatsappQrDataUrl:e.whatsappLoginQrDataUrl,whatsappConnected:e.whatsappLoginConnected,whatsappBusy:e.whatsappBusy,configSchema:e.configSchema,configSchemaLoading:e.configSchemaLoading,configForm:e.configForm,configUiHints:e.configUiHints,configSaving:e.configSaving,configFormDirty:e.configFormDirty,nostrProfileFormState:e.nostrProfileFormState,nostrProfileAccountId:e.nostrProfileAccountId,onRefresh:d=>oe(e,d),onWhatsAppStart:d=>e.handleWhatsAppStart(d),onWhatsAppWait:()=>e.handleWhatsAppWait(),onWhatsAppLogout:()=>e.handleWhatsAppLogout(),onConfigPatch:(d,u)=>Bt(e,d,u),onConfigSave:()=>e.handleChannelConfigSave(),onConfigReload:()=>e.handleChannelConfigReload(),onNostrProfileEdit:(d,u)=>e.handleNostrProfileEdit(d,u),onNostrProfileCancel:()=>e.handleNostrProfileCancel(),onNostrProfileFieldChange:(d,u)=>e.handleNostrProfileFieldChange(d,u),onNostrProfileSave:()=>e.handleNostrProfileSave(),onNostrProfileImport:()=>e.handleNostrProfileImport(),onNostrProfileToggleAdvanced:()=>e.handleNostrProfileToggleAdvanced()}):g} + + ${e.tab==="instances"?Lf({loading:e.presenceLoading,entries:e.presenceEntries,lastError:e.presenceError,statusMessage:e.presenceStatus,onRefresh:()=>js(e)}):g} + + ${e.tab==="sessions"?gh({loading:e.sessionsLoading,result:e.sessionsResult,error:e.sessionsError,activeMinutes:e.sessionsFilterActive,limit:e.sessionsFilterLimit,includeGlobal:e.sessionsIncludeGlobal,includeUnknown:e.sessionsIncludeUnknown,basePath:e.basePath,onFiltersChange:d=>{e.sessionsFilterActive=d.activeMinutes,e.sessionsFilterLimit=d.limit,e.sessionsIncludeGlobal=d.includeGlobal,e.sessionsIncludeUnknown=d.includeUnknown},onRefresh:()=>st(e),onPatch:(d,u)=>Ml(e,d,u),onDelete:d=>Il(e,d)}):g} + + ${e.tab==="cron"?Sf({loading:e.cronLoading,status:e.cronStatus,jobs:e.cronJobs,error:e.cronError,busy:e.cronBusy,form:e.cronForm,channels:e.channelsSnapshot?.channelMeta?.length?e.channelsSnapshot.channelMeta.map(d=>d.id):e.channelsSnapshot?.channelOrder??[],channelLabels:e.channelsSnapshot?.channelLabels??{},channelMeta:e.channelsSnapshot?.channelMeta??[],runsJobId:e.cronRunsJobId,runs:e.cronRuns,onFormChange:d=>e.cronForm={...e.cronForm,...d},onRefresh:()=>e.loadCron(),onAdd:()=>ec(e),onToggle:(d,u)=>tc(e,d,u),onRun:d=>nc(e,d),onRemove:d=>sc(e,d),onLoadRuns:d=>po(e,d)}):g} + + ${e.tab==="skills"?yh({loading:e.skillsLoading,report:e.skillsReport,error:e.skillsError,filter:e.skillsFilter,edits:e.skillEdits,messages:e.skillMessages,busyKey:e.skillsBusyKey,onFilterChange:d=>e.skillsFilter=d,onRefresh:()=>Ct(e,{clearMessages:!0}),onToggle:(d,u)=>Zc(e,d,u),onEdit:(d,u)=>Qc(e,d,u),onSaveKey:d=>Jc(e,d),onInstall:(d,u,h)=>Xc(e,d,u,h)}):g} + + ${e.tab==="nodes"?Nf({loading:e.nodesLoading,nodes:e.nodes,devicesLoading:e.devicesLoading,devicesError:e.devicesError,devicesList:e.devicesList,configForm:e.configForm??e.configSnapshot?.config,configLoading:e.configLoading,configSaving:e.configSaving,configDirty:e.configFormDirty,configFormMode:e.configFormMode,execApprovalsLoading:e.execApprovalsLoading,execApprovalsSaving:e.execApprovalsSaving,execApprovalsDirty:e.execApprovalsDirty,execApprovalsSnapshot:e.execApprovalsSnapshot,execApprovalsForm:e.execApprovalsForm,execApprovalsSelectedAgent:e.execApprovalsSelectedAgent,execApprovalsTarget:e.execApprovalsTarget,execApprovalsTargetNodeId:e.execApprovalsTargetNodeId,onRefresh:()=>pn(e),onDevicesRefresh:()=>Te(e),onDeviceApprove:d=>Uc(e,d),onDeviceReject:d=>Kc(e,d),onDeviceRotate:(d,u,h)=>Hc(e,{deviceId:d,role:u,scopes:h}),onDeviceRevoke:(d,u)=>zc(e,{deviceId:d,role:u}),onLoadConfig:()=>be(e),onLoadExecApprovals:()=>{const d=e.execApprovalsTarget==="node"&&e.execApprovalsTargetNodeId?{kind:"node",nodeId:e.execApprovalsTargetNodeId}:{kind:"gateway"};return zs(e,d)},onBindDefault:d=>{d?Bt(e,["tools","exec","node"],d):Zi(e,["tools","exec","node"])},onBindAgent:(d,u)=>{const h=["agents","list",d,"tools","exec","node"];u?Bt(e,h,u):Zi(e,h)},onSaveBindings:()=>ls(e),onExecApprovalsTargetChange:(d,u)=>{e.execApprovalsTarget=d,e.execApprovalsTargetNodeId=u,e.execApprovalsSnapshot=null,e.execApprovalsForm=null,e.execApprovalsDirty=!1,e.execApprovalsSelectedAgent=null},onExecApprovalsSelectAgent:d=>{e.execApprovalsSelectedAgent=d},onExecApprovalsPatch:(d,u)=>Gc(e,d,u),onExecApprovalsRemove:d=>Yc(e,d),onSaveExecApprovals:()=>{const d=e.execApprovalsTarget==="node"&&e.execApprovalsTargetNodeId?{kind:"node",nodeId:e.execApprovalsTargetNodeId}:{kind:"gateway"};return Wc(e,d)}}):g} + + ${e.tab==="chat"?kp({sessionKey:e.sessionKey,onSessionKeyChange:d=>{e.sessionKey=d,e.chatMessage="",e.chatStream=null,e.chatStreamStartedAt=null,e.chatRunId=null,e.chatQueue=[],e.resetToolStream(),e.resetChatScroll(),e.applySettings({...e.settings,sessionKey:d,lastActiveSessionKey:d}),e.loadAssistantIdentity(),Xe(e),fs(e)},thinkingLevel:e.chatThinkingLevel,showThinking:c,loading:e.chatLoading,sending:e.chatSending,compactionStatus:e.compactionStatus,assistantAvatarUrl:p,messages:e.chatMessages,toolMessages:e.chatToolMessages,stream:e.chatStream,streamStartedAt:e.chatStreamStartedAt,draft:e.chatMessage,queue:e.chatQueue,connected:e.connected,canSend:e.connected,disabledReason:i,error:e.lastError,sessions:e.sessionsResult,focusMode:o,onRefresh:()=>(e.resetToolStream(),Promise.all([Xe(e),fs(e)])),onToggleFocusMode:()=>{e.onboarding||e.applySettings({...e.settings,chatFocusMode:!e.settings.chatFocusMode})},onChatScroll:d=>e.handleChatScroll(d),onDraftChange:d=>e.chatMessage=d,onSend:()=>e.handleSendChat(),canAbort:!!e.chatRunId,onAbort:()=>{e.handleAbortChat()},onQueueRemove:d=>e.removeQueuedMessage(d),onNewSession:()=>e.handleSendChat("/new",{restoreDraft:!0}),sidebarOpen:e.sidebarOpen,sidebarContent:e.sidebarContent,sidebarError:e.sidebarError,splitRatio:e.splitRatio,onOpenSidebar:d=>e.handleOpenSidebar(d),onCloseSidebar:()=>e.handleCloseSidebar(),onSplitRatioChange:d=>e.handleSplitRatioChange(d),assistantName:e.assistantName,assistantAvatar:e.assistantAvatar}):g} + + ${e.tab==="config"?Kp({raw:e.configRaw,originalRaw:e.configRawOriginal,valid:e.configValid,issues:e.configIssues,loading:e.configLoading,saving:e.configSaving,applying:e.configApplying,updating:e.updateRunning,connected:e.connected,schema:e.configSchema,schemaLoading:e.configSchemaLoading,uiHints:e.configUiHints,formMode:e.configFormMode,formValue:e.configForm,originalValue:e.configFormOriginal,searchQuery:e.configSearchQuery,activeSection:e.configActiveSection,activeSubsection:e.configActiveSubsection,onRawChange:d=>{e.configRaw=d},onFormModeChange:d=>e.configFormMode=d,onFormPatch:(d,u)=>Bt(e,d,u),onSearchChange:d=>e.configSearchQuery=d,onSectionChange:d=>{e.configActiveSection=d,e.configActiveSubsection=null},onSubsectionChange:d=>e.configActiveSubsection=d,onReload:()=>be(e),onSave:()=>ls(e),onApply:()=>Ql(e),onUpdate:()=>Zl(e)}):g} + + ${e.tab==="debug"?Ef({loading:e.debugLoading,status:e.debugStatus,health:e.debugHealth,models:e.debugModels,heartbeat:e.debugHeartbeat,eventLog:e.eventLog,callMethod:e.debugCallMethod,callParams:e.debugCallParams,callResult:e.debugCallResult,callError:e.debugCallError,onCallMethodChange:d=>e.debugCallMethod=d,onCallParamsChange:d=>e.debugCallParams=d,onRefresh:()=>dn(e),onCall:()=>rc(e)}):g} + + ${e.tab==="logs"?Pf({loading:e.logsLoading,error:e.logsError,file:e.logsFile,entries:e.logsEntries,filterText:e.logsFilterText,levelFilters:e.logsLevelFilters,autoFollow:e.logsAutoFollow,truncated:e.logsTruncated,onFilterTextChange:d=>e.logsFilterText=d,onLevelToggle:(d,u)=>{e.logsLevelFilters={...e.logsLevelFilters,[d]:u}},onToggleAutoFollow:d=>e.logsAutoFollow=d,onRefresh:()=>Os(e,{reset:!0}),onExport:(d,u)=>e.exportLogs(d,u),onScroll:d=>e.handleLogsScroll(d)}):g} +
    + ${bh(e)} +
    + `}const Rh={trace:!0,debug:!0,info:!0,warn:!0,error:!0,fatal:!0},Ph={name:"",description:"",agentId:"",enabled:!0,scheduleKind:"every",scheduleAt:"",everyAmount:"30",everyUnit:"minutes",cronExpr:"0 7 * * *",cronTz:"",sessionTarget:"main",wakeMode:"next-heartbeat",payloadKind:"systemEvent",payloadText:"",deliver:!1,channel:"last",to:"",timeoutSeconds:"",postToMainPrefix:""};async function Nh(e){if(!(!e.client||!e.connected)&&!e.agentsLoading){e.agentsLoading=!0,e.agentsError=null;try{const t=await e.client.request("agents.list",{});t&&(e.agentsList=t)}catch(t){e.agentsError=String(t)}finally{e.agentsLoading=!1}}}const mr={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"clawdbot-control-ui",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"clawdbot-macos",IOS_APP:"clawdbot-ios",ANDROID_APP:"clawdbot-android",NODE_HOST:"node-host",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"clawdbot-probe"},za=mr,Ss={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",PROBE:"probe",TEST:"test"};new Set(Object.values(mr));new Set(Object.values(Ss));function Oh(e){const t=e.version??(e.nonce?"v2":"v1"),n=e.scopes.join(","),s=e.token??"",i=[t,e.deviceId,e.clientId,e.clientMode,e.role,n,String(e.signedAtMs),s];return t==="v2"&&i.push(e.nonce??""),i.join("|")}const Dh=4008;class Bh{constructor(t){this.opts=t,this.ws=null,this.pending=new Map,this.closed=!1,this.lastSeq=null,this.connectNonce=null,this.connectSent=!1,this.connectTimer=null,this.backoffMs=800}start(){this.closed=!1,this.connect()}stop(){this.closed=!0,this.ws?.close(),this.ws=null,this.flushPending(new Error("gateway client stopped"))}get connected(){return this.ws?.readyState===WebSocket.OPEN}connect(){this.closed||(this.ws=new WebSocket(this.opts.url),this.ws.onopen=()=>this.queueConnect(),this.ws.onmessage=t=>this.handleMessage(String(t.data??"")),this.ws.onclose=t=>{const n=String(t.reason??"");this.ws=null,this.flushPending(new Error(`gateway closed (${t.code}): ${n}`)),this.opts.onClose?.({code:t.code,reason:n}),this.scheduleReconnect()},this.ws.onerror=()=>{})}scheduleReconnect(){if(this.closed)return;const t=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*1.7,15e3),window.setTimeout(()=>this.connect(),t)}flushPending(t){for(const[,n]of this.pending)n.reject(t);this.pending.clear()}async sendConnect(){if(this.connectSent)return;this.connectSent=!0,this.connectTimer!==null&&(window.clearTimeout(this.connectTimer),this.connectTimer=null);const t=typeof crypto<"u"&&!!crypto.subtle,n=["operator.admin","operator.approvals","operator.pairing"],s="operator";let i=null,a=!1,o=this.opts.token;if(t){i=await Us();const d=Fc({deviceId:i.deviceId,role:s})?.token;o=d??this.opts.token,a=!!(d&&this.opts.token)}const c=o||this.opts.password?{token:o,password:this.opts.password}:void 0;let l;if(t&&i){const d=Date.now(),u=this.connectNonce??void 0,h=Oh({deviceId:i.deviceId,clientId:this.opts.clientName??za.CONTROL_UI,clientMode:this.opts.mode??Ss.WEBCHAT,role:s,scopes:n,signedAtMs:d,token:o??null,nonce:u}),v=await Dc(i.privateKey,h);l={id:i.deviceId,publicKey:i.publicKey,signature:v,signedAt:d,nonce:u}}const p={minProtocol:3,maxProtocol:3,client:{id:this.opts.clientName??za.CONTROL_UI,version:this.opts.clientVersion??"dev",platform:this.opts.platform??navigator.platform??"web",mode:this.opts.mode??Ss.WEBCHAT,instanceId:this.opts.instanceId},role:s,scopes:n,device:l,caps:[],auth:c,userAgent:navigator.userAgent,locale:navigator.language};this.request("connect",p).then(d=>{d?.auth?.deviceToken&&i&&Eo({deviceId:i.deviceId,role:d.auth.role??s,token:d.auth.deviceToken,scopes:d.auth.scopes??[]}),this.backoffMs=800,this.opts.onHello?.(d)}).catch(()=>{a&&i&&Lo({deviceId:i.deviceId,role:s}),this.ws?.close(Dh,"connect failed")})}handleMessage(t){let n;try{n=JSON.parse(t)}catch{return}const s=n;if(s.type==="event"){const i=n;if(i.event==="connect.challenge"){const o=i.payload,c=o&&typeof o.nonce=="string"?o.nonce:null;c&&(this.connectNonce=c,this.sendConnect());return}const a=typeof i.seq=="number"?i.seq:null;a!==null&&(this.lastSeq!==null&&a>this.lastSeq+1&&this.opts.onGap?.({expected:this.lastSeq+1,received:a}),this.lastSeq=a);try{this.opts.onEvent?.(i)}catch(o){console.error("[gateway] event handler error:",o)}return}if(s.type==="res"){const i=n,a=this.pending.get(i.id);if(!a)return;this.pending.delete(i.id),i.ok?a.resolve(i.payload):a.reject(new Error(i.error?.message??"request failed"));return}}request(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return Promise.reject(new Error("gateway not connected"));const s=Ps(),i={type:"req",id:s,method:t,params:n},a=new Promise((o,c)=>{this.pending.set(s,{resolve:l=>o(l),reject:c})});return this.ws.send(JSON.stringify(i)),a}queueConnect(){this.connectNonce=null,this.connectSent=!1,this.connectTimer!==null&&window.clearTimeout(this.connectTimer),this.connectTimer=window.setTimeout(()=>{this.sendConnect()},750)}}function _s(e){return typeof e=="object"&&e!==null}function Fh(e){if(!_s(e))return null;const t=typeof e.id=="string"?e.id.trim():"",n=e.request;if(!t||!_s(n))return null;const s=typeof n.command=="string"?n.command.trim():"";if(!s)return null;const i=typeof e.createdAtMs=="number"?e.createdAtMs:0,a=typeof e.expiresAtMs=="number"?e.expiresAtMs:0;return!i||!a?null:{id:t,request:{command:s,cwd:typeof n.cwd=="string"?n.cwd:null,host:typeof n.host=="string"?n.host:null,security:typeof n.security=="string"?n.security:null,ask:typeof n.ask=="string"?n.ask:null,agentId:typeof n.agentId=="string"?n.agentId:null,resolvedPath:typeof n.resolvedPath=="string"?n.resolvedPath:null,sessionKey:typeof n.sessionKey=="string"?n.sessionKey:null},createdAtMs:i,expiresAtMs:a}}function Uh(e){if(!_s(e))return null;const t=typeof e.id=="string"?e.id.trim():"";return t?{id:t,decision:typeof e.decision=="string"?e.decision:null,resolvedBy:typeof e.resolvedBy=="string"?e.resolvedBy:null,ts:typeof e.ts=="number"?e.ts:null}:null}function br(e){const t=Date.now();return e.filter(n=>n.expiresAtMs>t)}function Kh(e,t){const n=br(e).filter(s=>s.id!==t.id);return n.push(t),n}function ja(e,t){return br(e).filter(n=>n.id!==t)}async function yr(e,t){if(!e.client||!e.connected)return;const n=e.sessionKey.trim(),s=n?{sessionKey:n}:{};try{const i=await e.client.request("agent.identity.get",s);if(!i)return;const a=ns(i);e.assistantName=a.name,e.assistantAvatar=a.avatar,e.assistantAgentId=a.agentId??null}catch{}}function Xn(e,t){const n=(e??"").trim(),s=t.mainSessionKey?.trim();if(!s)return n;if(!n)return s;const i=t.mainKey?.trim()||"main",a=t.defaultAgentId?.trim();return n==="main"||n===i||a&&(n===`agent:${a}:main`||n===`agent:${a}:${i}`)?s:n}function Hh(e,t){if(!t?.mainSessionKey)return;const n=Xn(e.sessionKey,t),s=Xn(e.settings.sessionKey,t),i=Xn(e.settings.lastActiveSessionKey,t),a=n||s||e.sessionKey,o={...e.settings,sessionKey:s||a,lastActiveSessionKey:i||a},c=o.sessionKey!==e.settings.sessionKey||o.lastActiveSessionKey!==e.settings.lastActiveSessionKey;a!==e.sessionKey&&(e.sessionKey=a),c&&ke(e,o)}function wr(e){e.lastError=null,e.hello=null,e.connected=!1,e.execApprovalQueue=[],e.execApprovalError=null,e.client?.stop(),e.client=new Bh({url:e.settings.gatewayUrl,token:e.settings.token.trim()?e.settings.token:void 0,password:e.password.trim()?e.password:void 0,clientName:"clawdbot-control-ui",mode:"webchat",onHello:t=>{e.connected=!0,e.lastError=null,e.hello=t,qh(e,t),yr(e),Nh(e),pn(e,{quiet:!0}),Te(e,{quiet:!0}),Qs(e)},onClose:({code:t,reason:n})=>{e.connected=!1,t!==1012&&(e.lastError=`disconnected (${t}): ${n||"no reason"}`)},onEvent:t=>zh(e,t),onGap:({expected:t,received:n})=>{e.lastError=`event gap detected (expected seq ${t}, got ${n}); refresh recommended`}}),e.client.start()}function zh(e,t){try{jh(e,t)}catch(n){console.error("[gateway] handleGatewayEvent error:",t.event,n)}}function jh(e,t){if(e.eventLogBuffer=[{ts:Date.now(),event:t.event,payload:t.payload},...e.eventLogBuffer].slice(0,250),e.tab==="debug"&&(e.eventLog=e.eventLogBuffer),t.event==="agent"){if(e.onboarding)return;Hl(e,t.payload);return}if(t.event==="chat"){const n=t.payload;n?.sessionKey&&Mo(e,n.sessionKey);const s=Ll(e,n);(s==="final"||s==="error"||s==="aborted")&&(Ns(e),$d(e)),s==="final"&&Xe(e);return}if(t.event==="presence"){const n=t.payload;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence,e.presenceError=null,e.presenceStatus=null);return}if(t.event==="cron"&&e.tab==="cron"&&Zs(e),(t.event==="device.pair.requested"||t.event==="device.pair.resolved")&&Te(e,{quiet:!0}),t.event==="exec.approval.requested"){const n=Fh(t.payload);if(n){e.execApprovalQueue=Kh(e.execApprovalQueue,n),e.execApprovalError=null;const s=Math.max(0,n.expiresAtMs-Date.now()+500);window.setTimeout(()=>{e.execApprovalQueue=ja(e.execApprovalQueue,n.id)},s)}return}if(t.event==="exec.approval.resolved"){const n=Uh(t.payload);n&&(e.execApprovalQueue=ja(e.execApprovalQueue,n.id))}}function qh(e,t){const n=t.snapshot;n?.presence&&Array.isArray(n.presence)&&(e.presenceEntries=n.presence),n?.health&&(e.debugHealth=n.health),n?.sessionDefaults&&Hh(e,n.sessionDefaults)}function Vh(e){e.basePath=ld(),pd(e,!0),cd(e),dd(e),window.addEventListener("popstate",e.popStateHandler),ad(e),wr(e),sd(e),e.tab==="logs"&&Vs(e),e.tab==="debug"&&Gs(e)}function Wh(e){Wl(e)}function Gh(e){window.removeEventListener("popstate",e.popStateHandler),id(e),Ws(e),Ys(e),ud(e),e.topbarObserver?.disconnect(),e.topbarObserver=null}function Yh(e,t){if(e.tab==="chat"&&(t.has("chatMessages")||t.has("chatToolMessages")||t.has("chatStream")||t.has("chatLoading")||t.has("tab"))){const n=t.has("tab"),s=t.has("chatLoading")&&t.get("chatLoading")===!0&&e.chatLoading===!1;ln(e,n||s||!e.chatHasAutoScrolled)}e.tab==="logs"&&(t.has("logsEntries")||t.has("logsAutoFollow")||t.has("tab"))&&e.logsAutoFollow&&e.logsAtBottom&&ro(e,t.has("tab")||t.has("logsAutoFollow"))}async function Qh(e,t){await ic(e,t),await oe(e,!0)}async function Zh(e){await ac(e),await oe(e,!0)}async function Jh(e){await oc(e),await oe(e,!0)}async function Xh(e){await ls(e),await be(e),await oe(e,!0)}async function eg(e){await be(e),await oe(e,!0)}function tg(e){if(!Array.isArray(e))return{};const t={};for(const n of e){if(typeof n!="string")continue;const[s,...i]=n.split(":");if(!s||i.length===0)continue;const a=s.trim(),o=i.join(":").trim();a&&o&&(t[a]=o)}return t}function $r(e){return(e.channelsSnapshot?.channelAccounts?.nostr??[])[0]?.accountId??e.nostrProfileAccountId??"default"}function xr(e,t=""){return`/api/channels/nostr/${encodeURIComponent(e)}/profile${t}`}function ng(e,t,n){e.nostrProfileAccountId=t,e.nostrProfileFormState=Xp(n??void 0)}function sg(e){e.nostrProfileFormState=null,e.nostrProfileAccountId=null}function ig(e,t,n){const s=e.nostrProfileFormState;s&&(e.nostrProfileFormState={...s,values:{...s.values,[t]:n},fieldErrors:{...s.fieldErrors,[t]:""}})}function ag(e){const t=e.nostrProfileFormState;t&&(e.nostrProfileFormState={...t,showAdvanced:!t.showAdvanced})}async function og(e){const t=e.nostrProfileFormState;if(!t||t.saving)return;const n=$r(e);e.nostrProfileFormState={...t,saving:!0,error:null,success:null,fieldErrors:{}};try{const s=await fetch(xr(n),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t.values)}),i=await s.json().catch(()=>null);if(!s.ok||i?.ok===!1||!i){const a=i?.error??`Profile update failed (${s.status})`;e.nostrProfileFormState={...t,saving:!1,error:a,success:null,fieldErrors:tg(i?.details)};return}if(!i.persisted){e.nostrProfileFormState={...t,saving:!1,error:"Profile publish failed on all relays.",success:null};return}e.nostrProfileFormState={...t,saving:!1,error:null,success:"Profile published to relays.",fieldErrors:{},original:{...t.values}},await oe(e,!0)}catch(s){e.nostrProfileFormState={...t,saving:!1,error:`Profile update failed: ${String(s)}`,success:null}}}async function rg(e){const t=e.nostrProfileFormState;if(!t||t.importing)return;const n=$r(e);e.nostrProfileFormState={...t,importing:!0,error:null,success:null};try{const s=await fetch(xr(n,"/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoMerge:!0})}),i=await s.json().catch(()=>null);if(!s.ok||i?.ok===!1||!i){const l=i?.error??`Profile import failed (${s.status})`;e.nostrProfileFormState={...t,importing:!1,error:l,success:null};return}const a=i.merged??i.imported??null,o=a?{...t.values,...a}:t.values,c=!!(o.banner||o.website||o.nip05||o.lud16);e.nostrProfileFormState={...t,importing:!1,values:o,error:null,success:i.saved?"Profile imported from relays. Review and publish.":"Profile imported. Review and publish.",showAdvanced:c},i.saved&&await oe(e,!0)}catch(s){e.nostrProfileFormState={...t,importing:!1,error:`Profile import failed: ${String(s)}`,success:null}}}var lg=Object.defineProperty,cg=Object.getOwnPropertyDescriptor,b=(e,t,n,s)=>{for(var i=s>1?void 0:s?cg(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(s?o(t,n,i):o(i))||i);return s&&i&&lg(t,n,i),i};const es=ul();function dg(){if(!window.location.search)return!1;const t=new URLSearchParams(window.location.search).get("onboarding");if(!t)return!1;const n=t.trim().toLowerCase();return n==="1"||n==="true"||n==="yes"||n==="on"}let m=class extends Ze{constructor(){super(...arguments),this.settings=pl(),this.password="",this.tab="chat",this.onboarding=dg(),this.connected=!1,this.theme=this.settings.theme??"system",this.themeResolved="dark",this.hello=null,this.lastError=null,this.eventLog=[],this.eventLogBuffer=[],this.toolStreamSyncTimer=null,this.sidebarCloseTimer=null,this.assistantName=es.name,this.assistantAvatar=es.avatar,this.assistantAgentId=es.agentId??null,this.sessionKey=this.settings.sessionKey,this.chatLoading=!1,this.chatSending=!1,this.chatMessage="",this.chatMessages=[],this.chatToolMessages=[],this.chatStream=null,this.chatStreamStartedAt=null,this.chatRunId=null,this.compactionStatus=null,this.chatAvatarUrl=null,this.chatThinkingLevel=null,this.chatQueue=[],this.sidebarOpen=!1,this.sidebarContent=null,this.sidebarError=null,this.splitRatio=this.settings.splitRatio,this.nodesLoading=!1,this.nodes=[],this.devicesLoading=!1,this.devicesError=null,this.devicesList=null,this.execApprovalsLoading=!1,this.execApprovalsSaving=!1,this.execApprovalsDirty=!1,this.execApprovalsSnapshot=null,this.execApprovalsForm=null,this.execApprovalsSelectedAgent=null,this.execApprovalsTarget="gateway",this.execApprovalsTargetNodeId=null,this.execApprovalQueue=[],this.execApprovalBusy=!1,this.execApprovalError=null,this.configLoading=!1,this.configRaw=`{ +} +`,this.configRawOriginal="",this.configValid=null,this.configIssues=[],this.configSaving=!1,this.configApplying=!1,this.updateRunning=!1,this.applySessionKey=this.settings.lastActiveSessionKey,this.configSnapshot=null,this.configSchema=null,this.configSchemaVersion=null,this.configSchemaLoading=!1,this.configUiHints={},this.configForm=null,this.configFormOriginal=null,this.configFormDirty=!1,this.configFormMode="form",this.configSearchQuery="",this.configActiveSection=null,this.configActiveSubsection=null,this.channelsLoading=!1,this.channelsSnapshot=null,this.channelsError=null,this.channelsLastSuccess=null,this.whatsappLoginMessage=null,this.whatsappLoginQrDataUrl=null,this.whatsappLoginConnected=null,this.whatsappBusy=!1,this.nostrProfileFormState=null,this.nostrProfileAccountId=null,this.presenceLoading=!1,this.presenceEntries=[],this.presenceError=null,this.presenceStatus=null,this.agentsLoading=!1,this.agentsList=null,this.agentsError=null,this.sessionsLoading=!1,this.sessionsResult=null,this.sessionsError=null,this.sessionsFilterActive="",this.sessionsFilterLimit="120",this.sessionsIncludeGlobal=!0,this.sessionsIncludeUnknown=!1,this.cronLoading=!1,this.cronJobs=[],this.cronStatus=null,this.cronError=null,this.cronForm={...Ph},this.cronRunsJobId=null,this.cronRuns=[],this.cronBusy=!1,this.skillsLoading=!1,this.skillsReport=null,this.skillsError=null,this.skillsFilter="",this.skillEdits={},this.skillsBusyKey=null,this.skillMessages={},this.debugLoading=!1,this.debugStatus=null,this.debugHealth=null,this.debugModels=[],this.debugHeartbeat=null,this.debugCallMethod="",this.debugCallParams="{}",this.debugCallResult=null,this.debugCallError=null,this.logsLoading=!1,this.logsError=null,this.logsFile=null,this.logsEntries=[],this.logsFilterText="",this.logsLevelFilters={...Rh},this.logsAutoFollow=!0,this.logsTruncated=!1,this.logsCursor=null,this.logsLastFetchAt=null,this.logsLimit=500,this.logsMaxBytes=25e4,this.logsAtBottom=!0,this.client=null,this.chatScrollFrame=null,this.chatScrollTimeout=null,this.chatHasAutoScrolled=!1,this.chatUserNearBottom=!0,this.nodesPollInterval=null,this.logsPollInterval=null,this.debugPollInterval=null,this.logsScrollFrame=null,this.toolStreamById=new Map,this.toolStreamOrder=[],this.basePath="",this.popStateHandler=()=>fd(this),this.themeMedia=null,this.themeMediaHandler=null,this.topbarObserver=null}createRenderRoot(){return this}connectedCallback(){super.connectedCallback(),Vh(this)}firstUpdated(){Wh(this)}disconnectedCallback(){Gh(this),super.disconnectedCallback()}updated(e){Yh(this,e)}connect(){wr(this)}handleChatScroll(e){zl(this,e)}handleLogsScroll(e){jl(this,e)}exportLogs(e,t){Vl(e,t)}resetToolStream(){Ns(this)}resetChatScroll(){ql(this)}async loadAssistantIdentity(){await yr(this)}applySettings(e){ke(this,e)}setTab(e){od(this,e)}setTheme(e,t){rd(this,e,t)}async loadOverview(){await Po(this)}async loadCron(){await Zs(this)}async handleAbortChat(){await Oo(this)}removeQueuedMessage(e){bd(this,e)}async handleSendChat(e,t){await yd(this,e,t)}async handleWhatsAppStart(e){await Qh(this,e)}async handleWhatsAppWait(){await Zh(this)}async handleWhatsAppLogout(){await Jh(this)}async handleChannelConfigSave(){await Xh(this)}async handleChannelConfigReload(){await eg(this)}handleNostrProfileEdit(e,t){ng(this,e,t)}handleNostrProfileCancel(){sg(this)}handleNostrProfileFieldChange(e,t){ig(this,e,t)}async handleNostrProfileSave(){await og(this)}async handleNostrProfileImport(){await rg(this)}handleNostrProfileToggleAdvanced(){ag(this)}async handleExecApprovalDecision(e){const t=this.execApprovalQueue[0];if(!(!t||!this.client||this.execApprovalBusy)){this.execApprovalBusy=!0,this.execApprovalError=null;try{await this.client.request("exec.approval.resolve",{id:t.id,decision:e}),this.execApprovalQueue=this.execApprovalQueue.filter(n=>n.id!==t.id)}catch(n){this.execApprovalError=`Exec approval failed: ${String(n)}`}finally{this.execApprovalBusy=!1}}}handleOpenSidebar(e){this.sidebarCloseTimer!=null&&(window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=null),this.sidebarContent=e,this.sidebarError=null,this.sidebarOpen=!0}handleCloseSidebar(){this.sidebarOpen=!1,this.sidebarCloseTimer!=null&&window.clearTimeout(this.sidebarCloseTimer),this.sidebarCloseTimer=window.setTimeout(()=>{this.sidebarOpen||(this.sidebarContent=null,this.sidebarError=null,this.sidebarCloseTimer=null)},200)}handleSplitRatioChange(e){const t=Math.max(.4,Math.min(.7,e));this.splitRatio=t,this.applySettings({...this.settings,splitRatio:t})}render(){return Ih(this)}};b([y()],m.prototype,"settings",2);b([y()],m.prototype,"password",2);b([y()],m.prototype,"tab",2);b([y()],m.prototype,"onboarding",2);b([y()],m.prototype,"connected",2);b([y()],m.prototype,"theme",2);b([y()],m.prototype,"themeResolved",2);b([y()],m.prototype,"hello",2);b([y()],m.prototype,"lastError",2);b([y()],m.prototype,"eventLog",2);b([y()],m.prototype,"assistantName",2);b([y()],m.prototype,"assistantAvatar",2);b([y()],m.prototype,"assistantAgentId",2);b([y()],m.prototype,"sessionKey",2);b([y()],m.prototype,"chatLoading",2);b([y()],m.prototype,"chatSending",2);b([y()],m.prototype,"chatMessage",2);b([y()],m.prototype,"chatMessages",2);b([y()],m.prototype,"chatToolMessages",2);b([y()],m.prototype,"chatStream",2);b([y()],m.prototype,"chatStreamStartedAt",2);b([y()],m.prototype,"chatRunId",2);b([y()],m.prototype,"compactionStatus",2);b([y()],m.prototype,"chatAvatarUrl",2);b([y()],m.prototype,"chatThinkingLevel",2);b([y()],m.prototype,"chatQueue",2);b([y()],m.prototype,"sidebarOpen",2);b([y()],m.prototype,"sidebarContent",2);b([y()],m.prototype,"sidebarError",2);b([y()],m.prototype,"splitRatio",2);b([y()],m.prototype,"nodesLoading",2);b([y()],m.prototype,"nodes",2);b([y()],m.prototype,"devicesLoading",2);b([y()],m.prototype,"devicesError",2);b([y()],m.prototype,"devicesList",2);b([y()],m.prototype,"execApprovalsLoading",2);b([y()],m.prototype,"execApprovalsSaving",2);b([y()],m.prototype,"execApprovalsDirty",2);b([y()],m.prototype,"execApprovalsSnapshot",2);b([y()],m.prototype,"execApprovalsForm",2);b([y()],m.prototype,"execApprovalsSelectedAgent",2);b([y()],m.prototype,"execApprovalsTarget",2);b([y()],m.prototype,"execApprovalsTargetNodeId",2);b([y()],m.prototype,"execApprovalQueue",2);b([y()],m.prototype,"execApprovalBusy",2);b([y()],m.prototype,"execApprovalError",2);b([y()],m.prototype,"configLoading",2);b([y()],m.prototype,"configRaw",2);b([y()],m.prototype,"configRawOriginal",2);b([y()],m.prototype,"configValid",2);b([y()],m.prototype,"configIssues",2);b([y()],m.prototype,"configSaving",2);b([y()],m.prototype,"configApplying",2);b([y()],m.prototype,"updateRunning",2);b([y()],m.prototype,"applySessionKey",2);b([y()],m.prototype,"configSnapshot",2);b([y()],m.prototype,"configSchema",2);b([y()],m.prototype,"configSchemaVersion",2);b([y()],m.prototype,"configSchemaLoading",2);b([y()],m.prototype,"configUiHints",2);b([y()],m.prototype,"configForm",2);b([y()],m.prototype,"configFormOriginal",2);b([y()],m.prototype,"configFormDirty",2);b([y()],m.prototype,"configFormMode",2);b([y()],m.prototype,"configSearchQuery",2);b([y()],m.prototype,"configActiveSection",2);b([y()],m.prototype,"configActiveSubsection",2);b([y()],m.prototype,"channelsLoading",2);b([y()],m.prototype,"channelsSnapshot",2);b([y()],m.prototype,"channelsError",2);b([y()],m.prototype,"channelsLastSuccess",2);b([y()],m.prototype,"whatsappLoginMessage",2);b([y()],m.prototype,"whatsappLoginQrDataUrl",2);b([y()],m.prototype,"whatsappLoginConnected",2);b([y()],m.prototype,"whatsappBusy",2);b([y()],m.prototype,"nostrProfileFormState",2);b([y()],m.prototype,"nostrProfileAccountId",2);b([y()],m.prototype,"presenceLoading",2);b([y()],m.prototype,"presenceEntries",2);b([y()],m.prototype,"presenceError",2);b([y()],m.prototype,"presenceStatus",2);b([y()],m.prototype,"agentsLoading",2);b([y()],m.prototype,"agentsList",2);b([y()],m.prototype,"agentsError",2);b([y()],m.prototype,"sessionsLoading",2);b([y()],m.prototype,"sessionsResult",2);b([y()],m.prototype,"sessionsError",2);b([y()],m.prototype,"sessionsFilterActive",2);b([y()],m.prototype,"sessionsFilterLimit",2);b([y()],m.prototype,"sessionsIncludeGlobal",2);b([y()],m.prototype,"sessionsIncludeUnknown",2);b([y()],m.prototype,"cronLoading",2);b([y()],m.prototype,"cronJobs",2);b([y()],m.prototype,"cronStatus",2);b([y()],m.prototype,"cronError",2);b([y()],m.prototype,"cronForm",2);b([y()],m.prototype,"cronRunsJobId",2);b([y()],m.prototype,"cronRuns",2);b([y()],m.prototype,"cronBusy",2);b([y()],m.prototype,"skillsLoading",2);b([y()],m.prototype,"skillsReport",2);b([y()],m.prototype,"skillsError",2);b([y()],m.prototype,"skillsFilter",2);b([y()],m.prototype,"skillEdits",2);b([y()],m.prototype,"skillsBusyKey",2);b([y()],m.prototype,"skillMessages",2);b([y()],m.prototype,"debugLoading",2);b([y()],m.prototype,"debugStatus",2);b([y()],m.prototype,"debugHealth",2);b([y()],m.prototype,"debugModels",2);b([y()],m.prototype,"debugHeartbeat",2);b([y()],m.prototype,"debugCallMethod",2);b([y()],m.prototype,"debugCallParams",2);b([y()],m.prototype,"debugCallResult",2);b([y()],m.prototype,"debugCallError",2);b([y()],m.prototype,"logsLoading",2);b([y()],m.prototype,"logsError",2);b([y()],m.prototype,"logsFile",2);b([y()],m.prototype,"logsEntries",2);b([y()],m.prototype,"logsFilterText",2);b([y()],m.prototype,"logsLevelFilters",2);b([y()],m.prototype,"logsAutoFollow",2);b([y()],m.prototype,"logsTruncated",2);b([y()],m.prototype,"logsCursor",2);b([y()],m.prototype,"logsLastFetchAt",2);b([y()],m.prototype,"logsLimit",2);b([y()],m.prototype,"logsMaxBytes",2);b([y()],m.prototype,"logsAtBottom",2);m=b([Ja("clawdbot-app")],m); +//# sourceMappingURL=index-DQcOTEYz.js.map diff --git a/dist/control-ui/assets/index-DQcOTEYz.js.map b/dist/control-ui/assets/index-DQcOTEYz.js.map new file mode 100644 index 000000000..d48222472 --- /dev/null +++ b/dist/control-ui/assets/index-DQcOTEYz.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index-DQcOTEYz.js","sources":["../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/css-tag.js","../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/reactive-element.js","../../../node_modules/.pnpm/lit-html@3.3.2/node_modules/lit-html/lit-html.js","../../../node_modules/.pnpm/lit-element@4.2.2/node_modules/lit-element/lit-element.js","../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/decorators/custom-element.js","../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/decorators/property.js","../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/decorators/state.js","../../../ui/src/ui/assistant-identity.ts","../../../ui/src/ui/storage.ts","../../../src/sessions/session-key-utils.ts","../../../ui/src/ui/navigation.ts","../../../ui/src/ui/icons.ts","../../../src/shared/text/reasoning-tags.ts","../../../ui/src/ui/format.ts","../../../ui/src/ui/chat/message-extract.ts","../../../ui/src/ui/uuid.ts","../../../ui/src/ui/controllers/chat.ts","../../../ui/src/ui/controllers/sessions.ts","../../../ui/src/ui/app-tool-stream.ts","../../../ui/src/ui/app-scroll.ts","../../../ui/src/ui/controllers/config/form-utils.ts","../../../ui/src/ui/controllers/config.ts","../../../ui/src/ui/controllers/cron.ts","../../../ui/src/ui/controllers/channels.ts","../../../ui/src/ui/controllers/debug.ts","../../../ui/src/ui/controllers/logs.ts","../../../node_modules/.pnpm/@noble+ed25519@3.0.0/node_modules/@noble/ed25519/index.js","../../../ui/src/ui/device-identity.ts","../../../ui/src/ui/device-auth.ts","../../../ui/src/ui/controllers/devices.ts","../../../ui/src/ui/controllers/nodes.ts","../../../ui/src/ui/controllers/exec-approvals.ts","../../../ui/src/ui/controllers/presence.ts","../../../ui/src/ui/controllers/skills.ts","../../../ui/src/ui/theme.ts","../../../ui/src/ui/theme-transition.ts","../../../ui/src/ui/app-polling.ts","../../../ui/src/ui/app-settings.ts","../../../ui/src/ui/app-chat.ts","../../../node_modules/.pnpm/lit-html@3.3.2/node_modules/lit-html/directive.js","../../../node_modules/.pnpm/lit-html@3.3.2/node_modules/lit-html/directive-helpers.js","../../../node_modules/.pnpm/lit-html@3.3.2/node_modules/lit-html/directives/repeat.js","../../../ui/src/ui/chat/message-normalizer.ts","../../../node_modules/.pnpm/lit-html@3.3.2/node_modules/lit-html/directives/unsafe-html.js","../../../node_modules/.pnpm/dompurify@3.3.1/node_modules/dompurify/dist/purify.es.mjs","../../../node_modules/.pnpm/marked@17.0.1/node_modules/marked/lib/marked.esm.js","../../../ui/src/ui/markdown.ts","../../../ui/src/ui/chat/copy-as-markdown.ts","../../../ui/src/ui/tool-display.ts","../../../ui/src/ui/chat/constants.ts","../../../ui/src/ui/chat/tool-helpers.ts","../../../ui/src/ui/chat/tool-cards.ts","../../../ui/src/ui/chat/grouped-render.ts","../../../ui/src/ui/views/markdown-sidebar.ts","../../../ui/src/ui/components/resizable-divider.ts","../../../ui/src/ui/views/chat.ts","../../../ui/src/ui/views/config-form.shared.ts","../../../ui/src/ui/views/config-form.node.ts","../../../ui/src/ui/views/config-form.render.ts","../../../ui/src/ui/views/config-form.analyze.ts","../../../ui/src/ui/views/config.ts","../../../ui/src/ui/views/channels.shared.ts","../../../ui/src/ui/views/channels.config.ts","../../../ui/src/ui/views/channels.discord.ts","../../../ui/src/ui/views/channels.googlechat.ts","../../../ui/src/ui/views/channels.imessage.ts","../../../ui/src/ui/views/channels.nostr-profile-form.ts","../../../ui/src/ui/views/channels.nostr.ts","../../../ui/src/ui/views/channels.signal.ts","../../../ui/src/ui/views/channels.slack.ts","../../../ui/src/ui/views/channels.telegram.ts","../../../ui/src/ui/views/channels.whatsapp.ts","../../../ui/src/ui/views/channels.ts","../../../ui/src/ui/presenter.ts","../../../ui/src/ui/views/cron.ts","../../../ui/src/ui/views/debug.ts","../../../ui/src/ui/views/instances.ts","../../../ui/src/ui/views/logs.ts","../../../ui/src/ui/views/nodes.ts","../../../ui/src/ui/views/overview.ts","../../../ui/src/ui/views/sessions.ts","../../../ui/src/ui/views/exec-approval.ts","../../../ui/src/ui/views/skills.ts","../../../ui/src/ui/app-render.helpers.ts","../../../ui/src/ui/app-render.ts","../../../ui/src/ui/app-defaults.ts","../../../ui/src/ui/controllers/agents.ts","../../../src/gateway/protocol/client-info.ts","../../../src/gateway/device-auth.ts","../../../ui/src/ui/gateway.ts","../../../ui/src/ui/controllers/exec-approval.ts","../../../ui/src/ui/controllers/assistant-identity.ts","../../../ui/src/ui/app-gateway.ts","../../../ui/src/ui/app-lifecycle.ts","../../../ui/src/ui/app-channels.ts","../../../ui/src/ui/app.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=globalThis,e=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&\"adoptedStyleSheets\"in Document.prototype&&\"replace\"in CSSStyleSheet.prototype,s=Symbol(),o=new WeakMap;class n{constructor(t,e,o){if(this._$cssResult$=!0,o!==s)throw Error(\"CSSResult is not constructable. Use `unsafeCSS` or `css` instead.\");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const s=this.t;if(e&&void 0===t){const e=void 0!==s&&1===s.length;e&&(t=o.get(s)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&o.set(s,t))}return t}toString(){return this.cssText}}const r=t=>new n(\"string\"==typeof t?t:t+\"\",void 0,s),i=(t,...e)=>{const o=1===t.length?t[0]:e.reduce((e,s,o)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if(\"number\"==typeof t)return t;throw Error(\"Value passed to 'css' function must be a 'css' function result: \"+t+\". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.\")})(s)+t[o+1],t[0]);return new n(o,t,s)},S=(s,o)=>{if(e)s.adoptedStyleSheets=o.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const e of o){const o=document.createElement(\"style\"),n=t.litNonce;void 0!==n&&o.setAttribute(\"nonce\",n),o.textContent=e.cssText,s.appendChild(o)}},c=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e=\"\";for(const s of t.cssRules)e+=s.cssText;return r(e)})(t):t;export{n as CSSResult,S as adoptStyles,i as css,c as getCompatibleStyle,e as supportsAdoptingStyleSheets,r as unsafeCSS};\n//# sourceMappingURL=css-tag.js.map\n","import{getCompatibleStyle as t,adoptStyles as s}from\"./css-tag.js\";export{CSSResult,css,supportsAdoptingStyleSheets,unsafeCSS}from\"./css-tag.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const{is:i,defineProperty:e,getOwnPropertyDescriptor:h,getOwnPropertyNames:r,getOwnPropertySymbols:o,getPrototypeOf:n}=Object,a=globalThis,c=a.trustedTypes,l=c?c.emptyScript:\"\",p=a.reactiveElementPolyfillSupport,d=(t,s)=>t,u={toAttribute(t,s){switch(s){case Boolean:t=t?l:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,s){let i=t;switch(s){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},f=(t,s)=>!i(t,s),b={attribute:!0,type:String,converter:u,reflect:!1,useDefault:!1,hasChanged:f};Symbol.metadata??=Symbol(\"metadata\"),a.litPropertyMetadata??=new WeakMap;class y extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,s=b){if(s.state&&(s.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((s=Object.create(s)).wrapped=!0),this.elementProperties.set(t,s),!s.noAccessor){const i=Symbol(),h=this.getPropertyDescriptor(t,i,s);void 0!==h&&e(this.prototype,t,h)}}static getPropertyDescriptor(t,s,i){const{get:e,set:r}=h(this.prototype,t)??{get(){return this[s]},set(t){this[s]=t}};return{get:e,set(s){const h=e?.call(this);r?.call(this,s),this.requestUpdate(t,h,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??b}static _$Ei(){if(this.hasOwnProperty(d(\"elementProperties\")))return;const t=n(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(d(\"finalized\")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(d(\"properties\"))){const t=this.properties,s=[...r(t),...o(t)];for(const i of s)this.createProperty(i,t[i])}const t=this[Symbol.metadata];if(null!==t){const s=litPropertyMetadata.get(t);if(void 0!==s)for(const[t,i]of s)this.elementProperties.set(t,i)}this._$Eh=new Map;for(const[t,s]of this.elementProperties){const i=this._$Eu(t,s);void 0!==i&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(s){const i=[];if(Array.isArray(s)){const e=new Set(s.flat(1/0).reverse());for(const s of e)i.unshift(t(s))}else void 0!==s&&i.push(t(s));return i}static _$Eu(t,s){const i=s.attribute;return!1===i?void 0:\"string\"==typeof i?i:\"string\"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,s=this.constructor.elementProperties;for(const i of s.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return s(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,s,i){this._$AK(t,i)}_$ET(t,s){const i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(void 0!==e&&!0===i.reflect){const h=(void 0!==i.converter?.toAttribute?i.converter:u).toAttribute(s,i.type);this._$Em=t,null==h?this.removeAttribute(e):this.setAttribute(e,h),this._$Em=null}}_$AK(t,s){const i=this.constructor,e=i._$Eh.get(t);if(void 0!==e&&this._$Em!==e){const t=i.getPropertyOptions(e),h=\"function\"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:u;this._$Em=e;const r=h.fromAttribute(s,t.type);this[e]=r??this._$Ej?.get(e)??r,this._$Em=null}}requestUpdate(t,s,i,e=!1,h){if(void 0!==t){const r=this.constructor;if(!1===e&&(h=this[t]),i??=r.getPropertyOptions(t),!((i.hasChanged??f)(h,s)||i.useDefault&&i.reflect&&h===this._$Ej?.get(t)&&!this.hasAttribute(r._$Eu(t,i))))return;this.C(t,s,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,s,{useDefault:i,reflect:e,wrapped:h},r){i&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,r??s??this[t]),!0!==h||void 0!==r)||(this._$AL.has(t)||(this.hasUpdated||i||(s=void 0),this._$AL.set(t,s)),!0===e&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,s]of this._$Ep)this[t]=s;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[s,i]of t){const{wrapped:t}=i,e=this[s];!0!==t||this._$AL.has(s)||void 0===e||this.C(s,void 0,i,e)}}let t=!1;const s=this._$AL;try{t=this.shouldUpdate(s),t?(this.willUpdate(s),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(s)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(s)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}}y.elementStyles=[],y.shadowRootOptions={mode:\"open\"},y[d(\"elementProperties\")]=new Map,y[d(\"finalized\")]=new Map,p?.({ReactiveElement:y}),(a.reactiveElementVersions??=[]).push(\"2.1.2\");export{y as ReactiveElement,s as adoptStyles,u as defaultConverter,t as getCompatibleStyle,f as notEqual};\n//# sourceMappingURL=reactive-element.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=globalThis,i=t=>t,s=t.trustedTypes,e=s?s.createPolicy(\"lit-html\",{createHTML:t=>t}):void 0,h=\"$lit$\",o=`lit$${Math.random().toFixed(9).slice(2)}$`,n=\"?\"+o,r=`<${n}>`,l=document,c=()=>l.createComment(\"\"),a=t=>null===t||\"object\"!=typeof t&&\"function\"!=typeof t,u=Array.isArray,d=t=>u(t)||\"function\"==typeof t?.[Symbol.iterator],f=\"[ \\t\\n\\f\\r]\",v=/<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g,_=/-->/g,m=/>/g,p=RegExp(`>|${f}(?:([^\\\\s\"'>=/]+)(${f}*=${f}*(?:[^ \\t\\n\\f\\r\"'\\`<>=]|(\"|')|))|$)`,\"g\"),g=/'/g,$=/\"/g,y=/^(?:script|style|textarea|title)$/i,x=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),b=x(1),w=x(2),T=x(3),E=Symbol.for(\"lit-noChange\"),A=Symbol.for(\"lit-nothing\"),C=new WeakMap,P=l.createTreeWalker(l,129);function V(t,i){if(!u(t)||!t.hasOwnProperty(\"raw\"))throw Error(\"invalid template strings array\");return void 0!==e?e.createHTML(i):i}const N=(t,i)=>{const s=t.length-1,e=[];let n,l=2===i?\"\":3===i?\"\":\"\",c=v;for(let i=0;i\"===u[0]?(c=n??v,d=-1):void 0===u[1]?d=-2:(d=c.lastIndex-u[2].length,a=u[1],c=void 0===u[3]?p:'\"'===u[3]?$:g):c===$||c===g?c=p:c===_||c===m?c=v:(c=p,n=void 0);const x=c===p&&t[i+1].startsWith(\"/>\")?\" \":\"\";l+=c===v?s+r:d>=0?(e.push(a),s.slice(0,d)+h+s.slice(d)+o+x):s+o+(-2===d?i:x)}return[V(t,l+(t[s]||\"\")+(2===i?\"\":3===i?\"\":\"\")),e]};class S{constructor({strings:t,_$litType$:i},e){let r;this.parts=[];let l=0,a=0;const u=t.length-1,d=this.parts,[f,v]=N(t,i);if(this.el=S.createElement(f,e),P.currentNode=this.el.content,2===i||3===i){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(r=P.nextNode())&&d.length0){r.textContent=s?s.emptyScript:\"\";for(let s=0;s2||\"\"!==s[0]||\"\"!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=A}_$AI(t,i=this,s,e){const h=this.strings;let o=!1;if(void 0===h)t=M(this,t,i,0),o=!a(t)||t!==this._$AH&&t!==E,o&&(this._$AH=t);else{const e=t;let n,r;for(t=h[0],n=0;n{const e=s?.renderBefore??i;let h=e._$litPart$;if(void 0===h){const t=s?.renderBefore??null;e._$litPart$=h=new k(i.insertBefore(c(),t),t,void 0,s??{})}return h._$AI(t),h};export{j as _$LH,b as html,T as mathml,E as noChange,A as nothing,D as render,w as svg};\n//# sourceMappingURL=lit-html.js.map\n","import{ReactiveElement as t}from\"@lit/reactive-element\";export*from\"@lit/reactive-element\";import{render as e,noChange as r}from\"lit-html\";export*from\"lit-html\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const s=globalThis;class i extends t{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const r=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=e(r,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return r}}i._$litElement$=!0,i[\"finalized\"]=!0,s.litElementHydrateSupport?.({LitElement:i});const o=s.litElementPolyfillSupport;o?.({LitElement:i});const n={_$AK:(t,e,r)=>{t._$AK(e,r)},_$AL:t=>t._$AL};(s.litElementVersions??=[]).push(\"4.2.2\");export{i as LitElement,n as _$LE};\n//# sourceMappingURL=lit-element.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=t=>(e,o)=>{void 0!==o?o.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)};export{t as customElement};\n//# sourceMappingURL=custom-element.js.map\n","import{notEqual as t,defaultConverter as e}from\"../reactive-element.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const o={attribute:!0,type:String,converter:e,reflect:!1,hasChanged:t},r=(t=o,e,r)=>{const{kind:n,metadata:i}=r;let s=globalThis.litPropertyMetadata.get(i);if(void 0===s&&globalThis.litPropertyMetadata.set(i,s=new Map),\"setter\"===n&&((t=Object.create(t)).wrapped=!0),s.set(r.name,t),\"accessor\"===n){const{name:o}=r;return{set(r){const n=e.get.call(this);e.set.call(this,r),this.requestUpdate(o,n,t,!0,r)},init(e){return void 0!==e&&this.C(o,void 0,t,e),e}}}if(\"setter\"===n){const{name:o}=r;return function(r){const n=this[o];e.call(this,r),this.requestUpdate(o,n,t,!0,r)}}throw Error(\"Unsupported decorator location: \"+n)};function n(t){return(e,o)=>\"object\"==typeof o?r(t,e,o):((t,e,o)=>{const r=e.hasOwnProperty(o);return e.constructor.createProperty(o,t),r?Object.getOwnPropertyDescriptor(e,o):void 0})(t,e,o)}export{n as property,r as standardProperty};\n//# sourceMappingURL=property.js.map\n","import{property as t}from\"./property.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */function r(r){return t({...r,state:!0,attribute:!1})}export{r as state};\n//# sourceMappingURL=state.js.map\n","const MAX_ASSISTANT_NAME = 50;\nconst MAX_ASSISTANT_AVATAR = 200;\n\nexport const DEFAULT_ASSISTANT_NAME = \"Assistant\";\nexport const DEFAULT_ASSISTANT_AVATAR = \"A\";\n\nexport type AssistantIdentity = {\n agentId?: string | null;\n name: string;\n avatar: string | null;\n};\n\ndeclare global {\n interface Window {\n __CLAWDBOT_ASSISTANT_NAME__?: string;\n __CLAWDBOT_ASSISTANT_AVATAR__?: string;\n }\n}\n\nfunction coerceIdentityValue(value: string | undefined, maxLength: number): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (!trimmed) return undefined;\n if (trimmed.length <= maxLength) return trimmed;\n return trimmed.slice(0, maxLength);\n}\n\nexport function normalizeAssistantIdentity(\n input?: Partial | null,\n): AssistantIdentity {\n const name =\n coerceIdentityValue(input?.name, MAX_ASSISTANT_NAME) ?? DEFAULT_ASSISTANT_NAME;\n const avatar = coerceIdentityValue(input?.avatar ?? undefined, MAX_ASSISTANT_AVATAR) ?? null;\n const agentId =\n typeof input?.agentId === \"string\" && input.agentId.trim()\n ? input.agentId.trim()\n : null;\n return { agentId, name, avatar };\n}\n\nexport function resolveInjectedAssistantIdentity(): AssistantIdentity {\n if (typeof window === \"undefined\") {\n return normalizeAssistantIdentity({});\n }\n return normalizeAssistantIdentity({\n name: window.__CLAWDBOT_ASSISTANT_NAME__,\n avatar: window.__CLAWDBOT_ASSISTANT_AVATAR__,\n });\n}\n","const KEY = \"clawdbot.control.settings.v1\";\n\nimport type { ThemeMode } from \"./theme\";\n\nexport type UiSettings = {\n gatewayUrl: string;\n token: string;\n sessionKey: string;\n lastActiveSessionKey: string;\n theme: ThemeMode;\n chatFocusMode: boolean;\n chatShowThinking: boolean;\n splitRatio: number; // Sidebar split ratio (0.4 to 0.7, default 0.6)\n navCollapsed: boolean; // Collapsible sidebar state\n navGroupsCollapsed: Record; // Which nav groups are collapsed\n};\n\nexport function loadSettings(): UiSettings {\n const defaultUrl = (() => {\n const proto = location.protocol === \"https:\" ? \"wss\" : \"ws\";\n return `${proto}://${location.host}`;\n })();\n\n const defaults: UiSettings = {\n gatewayUrl: defaultUrl,\n token: \"\",\n sessionKey: \"main\",\n lastActiveSessionKey: \"main\",\n theme: \"system\",\n chatFocusMode: false,\n chatShowThinking: true,\n splitRatio: 0.6,\n navCollapsed: false,\n navGroupsCollapsed: {},\n };\n\n try {\n const raw = localStorage.getItem(KEY);\n if (!raw) return defaults;\n const parsed = JSON.parse(raw) as Partial;\n return {\n gatewayUrl:\n typeof parsed.gatewayUrl === \"string\" && parsed.gatewayUrl.trim()\n ? parsed.gatewayUrl.trim()\n : defaults.gatewayUrl,\n token: typeof parsed.token === \"string\" ? parsed.token : defaults.token,\n sessionKey:\n typeof parsed.sessionKey === \"string\" && parsed.sessionKey.trim()\n ? parsed.sessionKey.trim()\n : defaults.sessionKey,\n lastActiveSessionKey:\n typeof parsed.lastActiveSessionKey === \"string\" &&\n parsed.lastActiveSessionKey.trim()\n ? parsed.lastActiveSessionKey.trim()\n : (typeof parsed.sessionKey === \"string\" &&\n parsed.sessionKey.trim()) ||\n defaults.lastActiveSessionKey,\n theme:\n parsed.theme === \"light\" ||\n parsed.theme === \"dark\" ||\n parsed.theme === \"system\"\n ? parsed.theme\n : defaults.theme,\n chatFocusMode:\n typeof parsed.chatFocusMode === \"boolean\"\n ? parsed.chatFocusMode\n : defaults.chatFocusMode,\n chatShowThinking:\n typeof parsed.chatShowThinking === \"boolean\"\n ? parsed.chatShowThinking\n : defaults.chatShowThinking,\n splitRatio:\n typeof parsed.splitRatio === \"number\" &&\n parsed.splitRatio >= 0.4 &&\n parsed.splitRatio <= 0.7\n ? parsed.splitRatio\n : defaults.splitRatio,\n navCollapsed:\n typeof parsed.navCollapsed === \"boolean\"\n ? parsed.navCollapsed\n : defaults.navCollapsed,\n navGroupsCollapsed:\n typeof parsed.navGroupsCollapsed === \"object\" &&\n parsed.navGroupsCollapsed !== null\n ? parsed.navGroupsCollapsed\n : defaults.navGroupsCollapsed,\n };\n } catch {\n return defaults;\n }\n}\n\nexport function saveSettings(next: UiSettings) {\n localStorage.setItem(KEY, JSON.stringify(next));\n}\n","export type ParsedAgentSessionKey = {\n agentId: string;\n rest: string;\n};\n\nexport function parseAgentSessionKey(\n sessionKey: string | undefined | null,\n): ParsedAgentSessionKey | null {\n const raw = (sessionKey ?? \"\").trim();\n if (!raw) return null;\n const parts = raw.split(\":\").filter(Boolean);\n if (parts.length < 3) return null;\n if (parts[0] !== \"agent\") return null;\n const agentId = parts[1]?.trim();\n const rest = parts.slice(2).join(\":\");\n if (!agentId || !rest) return null;\n return { agentId, rest };\n}\n\nexport function isSubagentSessionKey(sessionKey: string | undefined | null): boolean {\n const raw = (sessionKey ?? \"\").trim();\n if (!raw) return false;\n if (raw.toLowerCase().startsWith(\"subagent:\")) return true;\n const parsed = parseAgentSessionKey(raw);\n return Boolean((parsed?.rest ?? \"\").toLowerCase().startsWith(\"subagent:\"));\n}\n\nexport function isAcpSessionKey(sessionKey: string | undefined | null): boolean {\n const raw = (sessionKey ?? \"\").trim();\n if (!raw) return false;\n const normalized = raw.toLowerCase();\n if (normalized.startsWith(\"acp:\")) return true;\n const parsed = parseAgentSessionKey(raw);\n return Boolean((parsed?.rest ?? \"\").toLowerCase().startsWith(\"acp:\"));\n}\n\nconst THREAD_SESSION_MARKERS = [\":thread:\", \":topic:\"];\n\nexport function resolveThreadParentSessionKey(\n sessionKey: string | undefined | null,\n): string | null {\n const raw = (sessionKey ?? \"\").trim();\n if (!raw) return null;\n const normalized = raw.toLowerCase();\n let idx = -1;\n for (const marker of THREAD_SESSION_MARKERS) {\n const candidate = normalized.lastIndexOf(marker);\n if (candidate > idx) idx = candidate;\n }\n if (idx <= 0) return null;\n const parent = raw.slice(0, idx).trim();\n return parent ? parent : null;\n}\n","import type { IconName } from \"./icons.js\";\n\nexport const TAB_GROUPS = [\n { label: \"Chat\", tabs: [\"chat\"] },\n {\n label: \"Control\",\n tabs: [\"overview\", \"channels\", \"instances\", \"sessions\", \"cron\"],\n },\n { label: \"Agent\", tabs: [\"skills\", \"nodes\"] },\n { label: \"Settings\", tabs: [\"config\", \"debug\", \"logs\"] },\n] as const;\n\nexport type Tab =\n | \"overview\"\n | \"channels\"\n | \"instances\"\n | \"sessions\"\n | \"cron\"\n | \"skills\"\n | \"nodes\"\n | \"chat\"\n | \"config\"\n | \"debug\"\n | \"logs\";\n\nconst TAB_PATHS: Record = {\n overview: \"/overview\",\n channels: \"/channels\",\n instances: \"/instances\",\n sessions: \"/sessions\",\n cron: \"/cron\",\n skills: \"/skills\",\n nodes: \"/nodes\",\n chat: \"/chat\",\n config: \"/config\",\n debug: \"/debug\",\n logs: \"/logs\",\n};\n\nconst PATH_TO_TAB = new Map(\n Object.entries(TAB_PATHS).map(([tab, path]) => [path, tab as Tab]),\n);\n\nexport function normalizeBasePath(basePath: string): string {\n if (!basePath) return \"\";\n let base = basePath.trim();\n if (!base.startsWith(\"/\")) base = `/${base}`;\n if (base === \"/\") return \"\";\n if (base.endsWith(\"/\")) base = base.slice(0, -1);\n return base;\n}\n\nexport function normalizePath(path: string): string {\n if (!path) return \"/\";\n let normalized = path.trim();\n if (!normalized.startsWith(\"/\")) normalized = `/${normalized}`;\n if (normalized.length > 1 && normalized.endsWith(\"/\")) {\n normalized = normalized.slice(0, -1);\n }\n return normalized;\n}\n\nexport function pathForTab(tab: Tab, basePath = \"\"): string {\n const base = normalizeBasePath(basePath);\n const path = TAB_PATHS[tab];\n return base ? `${base}${path}` : path;\n}\n\nexport function tabFromPath(pathname: string, basePath = \"\"): Tab | null {\n const base = normalizeBasePath(basePath);\n let path = pathname || \"/\";\n if (base) {\n if (path === base) {\n path = \"/\";\n } else if (path.startsWith(`${base}/`)) {\n path = path.slice(base.length);\n }\n }\n let normalized = normalizePath(path).toLowerCase();\n if (normalized.endsWith(\"/index.html\")) normalized = \"/\";\n if (normalized === \"/\") return \"chat\";\n return PATH_TO_TAB.get(normalized) ?? null;\n}\n\nexport function inferBasePathFromPathname(pathname: string): string {\n let normalized = normalizePath(pathname);\n if (normalized.endsWith(\"/index.html\")) {\n normalized = normalizePath(normalized.slice(0, -\"/index.html\".length));\n }\n if (normalized === \"/\") return \"\";\n const segments = normalized.split(\"/\").filter(Boolean);\n if (segments.length === 0) return \"\";\n for (let i = 0; i < segments.length; i++) {\n const candidate = `/${segments.slice(i).join(\"/\")}`.toLowerCase();\n if (PATH_TO_TAB.has(candidate)) {\n const prefix = segments.slice(0, i);\n return prefix.length ? `/${prefix.join(\"/\")}` : \"\";\n }\n }\n return `/${segments.join(\"/\")}`;\n}\n\nexport function iconForTab(tab: Tab): IconName {\n switch (tab) {\n case \"chat\":\n return \"messageSquare\";\n case \"overview\":\n return \"barChart\";\n case \"channels\":\n return \"link\";\n case \"instances\":\n return \"radio\";\n case \"sessions\":\n return \"fileText\";\n case \"cron\":\n return \"loader\";\n case \"skills\":\n return \"zap\";\n case \"nodes\":\n return \"monitor\";\n case \"config\":\n return \"settings\";\n case \"debug\":\n return \"bug\";\n case \"logs\":\n return \"scrollText\";\n default:\n return \"folder\";\n }\n}\n\nexport function titleForTab(tab: Tab) {\n switch (tab) {\n case \"overview\":\n return \"Overview\";\n case \"channels\":\n return \"Channels\";\n case \"instances\":\n return \"Instances\";\n case \"sessions\":\n return \"Sessions\";\n case \"cron\":\n return \"Cron Jobs\";\n case \"skills\":\n return \"Skills\";\n case \"nodes\":\n return \"Nodes\";\n case \"chat\":\n return \"Chat\";\n case \"config\":\n return \"Config\";\n case \"debug\":\n return \"Debug\";\n case \"logs\":\n return \"Logs\";\n default:\n return \"Control\";\n }\n}\n\nexport function subtitleForTab(tab: Tab) {\n switch (tab) {\n case \"overview\":\n return \"Gateway status, entry points, and a fast health read.\";\n case \"channels\":\n return \"Manage channels and settings.\";\n case \"instances\":\n return \"Presence beacons from connected clients and nodes.\";\n case \"sessions\":\n return \"Inspect active sessions and adjust per-session defaults.\";\n case \"cron\":\n return \"Schedule wakeups and recurring agent runs.\";\n case \"skills\":\n return \"Manage skill availability and API key injection.\";\n case \"nodes\":\n return \"Paired devices, capabilities, and command exposure.\";\n case \"chat\":\n return \"Direct gateway chat session for quick interventions.\";\n case \"config\":\n return \"Edit ~/.clawdbot/clawdbot.json safely.\";\n case \"debug\":\n return \"Gateway snapshots, events, and manual RPC calls.\";\n case \"logs\":\n return \"Live tail of the gateway file logs.\";\n default:\n return \"\";\n }\n}\n","import { html, type TemplateResult } from \"lit\";\n\n// Lucide-style SVG icons\n// All icons use currentColor for stroke\n\nexport const icons = {\n // Navigation icons\n messageSquare: html``,\n barChart: html``,\n link: html``,\n radio: html``,\n fileText: html``,\n zap: html``,\n monitor: html``,\n settings: html``,\n bug: html``,\n scrollText: html``,\n folder: html``,\n\n // UI icons\n menu: html``,\n x: html``,\n check: html``,\n copy: html``,\n search: html``,\n brain: html``,\n book: html``,\n loader: html``,\n\n // Tool icons\n wrench: html``,\n fileCode: html``,\n edit: html``,\n penLine: html``,\n paperclip: html``,\n globe: html``,\n image: html``,\n smartphone: html``,\n plug: html``,\n circle: html``,\n puzzle: html``,\n} as const;\n\nexport type IconName = keyof typeof icons;\n\nexport function icon(name: IconName): TemplateResult {\n return icons[name];\n}\n\nexport function renderIcon(name: IconName, className = \"nav-item__icon\"): TemplateResult {\n return html`${icons[name]}`;\n}\n\n// Legacy function for compatibility\nexport function renderEmojiIcon(iconContent: string | TemplateResult, className: string): TemplateResult {\n return html`${iconContent}`;\n}\n\nexport function setEmojiIcon(target: HTMLElement | null, icon: string): void {\n if (!target) return;\n target.textContent = icon;\n}\n","export type ReasoningTagMode = \"strict\" | \"preserve\";\nexport type ReasoningTagTrim = \"none\" | \"start\" | \"both\";\n\nconst QUICK_TAG_RE = /<\\s*\\/?\\s*(?:think(?:ing)?|thought|antthinking|final)\\b/i;\nconst FINAL_TAG_RE = /<\\s*\\/?\\s*final\\b[^>]*>/gi;\nconst THINKING_TAG_RE = /<\\s*(\\/?)\\s*(?:think(?:ing)?|thought|antthinking)\\b[^>]*>/gi;\n\nfunction applyTrim(value: string, mode: ReasoningTagTrim): string {\n if (mode === \"none\") return value;\n if (mode === \"start\") return value.trimStart();\n return value.trim();\n}\n\nexport function stripReasoningTagsFromText(\n text: string,\n options?: {\n mode?: ReasoningTagMode;\n trim?: ReasoningTagTrim;\n },\n): string {\n if (!text) return text;\n if (!QUICK_TAG_RE.test(text)) return text;\n\n const mode = options?.mode ?? \"strict\";\n const trimMode = options?.trim ?? \"both\";\n\n let cleaned = text;\n if (FINAL_TAG_RE.test(cleaned)) {\n FINAL_TAG_RE.lastIndex = 0;\n cleaned = cleaned.replace(FINAL_TAG_RE, \"\");\n } else {\n FINAL_TAG_RE.lastIndex = 0;\n }\n\n THINKING_TAG_RE.lastIndex = 0;\n let result = \"\";\n let lastIndex = 0;\n let inThinking = false;\n\n for (const match of cleaned.matchAll(THINKING_TAG_RE)) {\n const idx = match.index ?? 0;\n const isClose = match[1] === \"/\";\n\n if (!inThinking) {\n result += cleaned.slice(lastIndex, idx);\n if (!isClose) {\n inThinking = true;\n }\n } else if (isClose) {\n inThinking = false;\n }\n\n lastIndex = idx + match[0].length;\n }\n\n if (!inThinking || mode === \"preserve\") {\n result += cleaned.slice(lastIndex);\n }\n\n return applyTrim(result, trimMode);\n}\n","import { stripReasoningTagsFromText } from \"../../../src/shared/text/reasoning-tags.js\";\n\nexport function formatMs(ms?: number | null): string {\n if (!ms && ms !== 0) return \"n/a\";\n return new Date(ms).toLocaleString();\n}\n\nexport function formatAgo(ms?: number | null): string {\n if (!ms && ms !== 0) return \"n/a\";\n const diff = Date.now() - ms;\n if (diff < 0) return \"just now\";\n const sec = Math.round(diff / 1000);\n if (sec < 60) return `${sec}s ago`;\n const min = Math.round(sec / 60);\n if (min < 60) return `${min}m ago`;\n const hr = Math.round(min / 60);\n if (hr < 48) return `${hr}h ago`;\n const day = Math.round(hr / 24);\n return `${day}d ago`;\n}\n\nexport function formatDurationMs(ms?: number | null): string {\n if (!ms && ms !== 0) return \"n/a\";\n if (ms < 1000) return `${ms}ms`;\n const sec = Math.round(ms / 1000);\n if (sec < 60) return `${sec}s`;\n const min = Math.round(sec / 60);\n if (min < 60) return `${min}m`;\n const hr = Math.round(min / 60);\n if (hr < 48) return `${hr}h`;\n const day = Math.round(hr / 24);\n return `${day}d`;\n}\n\nexport function formatList(values?: Array): string {\n if (!values || values.length === 0) return \"none\";\n return values.filter((v): v is string => Boolean(v && v.trim())).join(\", \");\n}\n\nexport function clampText(value: string, max = 120): string {\n if (value.length <= max) return value;\n return `${value.slice(0, Math.max(0, max - 1))}…`;\n}\n\nexport function truncateText(value: string, max: number): {\n text: string;\n truncated: boolean;\n total: number;\n} {\n if (value.length <= max) {\n return { text: value, truncated: false, total: value.length };\n }\n return {\n text: value.slice(0, Math.max(0, max)),\n truncated: true,\n total: value.length,\n };\n}\n\nexport function toNumber(value: string, fallback: number): number {\n const n = Number(value);\n return Number.isFinite(n) ? n : fallback;\n}\n\nexport function parseList(input: string): string[] {\n return input\n .split(/[,\\n]/)\n .map((v) => v.trim())\n .filter((v) => v.length > 0);\n}\n\nexport function stripThinkingTags(value: string): string {\n return stripReasoningTagsFromText(value, { mode: \"preserve\", trim: \"start\" });\n}\n","import { stripThinkingTags } from \"../format\";\n\nconst ENVELOPE_PREFIX = /^\\[([^\\]]+)\\]\\s*/;\nconst ENVELOPE_CHANNELS = [\n \"WebChat\",\n \"WhatsApp\",\n \"Telegram\",\n \"Signal\",\n \"Slack\",\n \"Discord\",\n \"iMessage\",\n \"Teams\",\n \"Matrix\",\n \"Zalo\",\n \"Zalo Personal\",\n \"BlueBubbles\",\n];\n\nconst textCache = new WeakMap();\nconst thinkingCache = new WeakMap();\n\nfunction looksLikeEnvelopeHeader(header: string): boolean {\n if (/\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}Z\\b/.test(header)) return true;\n if (/\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}\\b/.test(header)) return true;\n return ENVELOPE_CHANNELS.some((label) => header.startsWith(`${label} `));\n}\n\nexport function stripEnvelope(text: string): string {\n const match = text.match(ENVELOPE_PREFIX);\n if (!match) return text;\n const header = match[1] ?? \"\";\n if (!looksLikeEnvelopeHeader(header)) return text;\n return text.slice(match[0].length);\n}\n\nexport function extractText(message: unknown): string | null {\n const m = message as Record;\n const role = typeof m.role === \"string\" ? m.role : \"\";\n const content = m.content;\n if (typeof content === \"string\") {\n const processed = role === \"assistant\" ? stripThinkingTags(content) : stripEnvelope(content);\n return processed;\n }\n if (Array.isArray(content)) {\n const parts = content\n .map((p) => {\n const item = p as Record;\n if (item.type === \"text\" && typeof item.text === \"string\") return item.text;\n return null;\n })\n .filter((v): v is string => typeof v === \"string\");\n if (parts.length > 0) {\n const joined = parts.join(\"\\n\");\n const processed = role === \"assistant\" ? stripThinkingTags(joined) : stripEnvelope(joined);\n return processed;\n }\n }\n if (typeof m.text === \"string\") {\n const processed = role === \"assistant\" ? stripThinkingTags(m.text) : stripEnvelope(m.text);\n return processed;\n }\n return null;\n}\n\nexport function extractTextCached(message: unknown): string | null {\n if (!message || typeof message !== \"object\") return extractText(message);\n const obj = message as object;\n if (textCache.has(obj)) return textCache.get(obj) ?? null;\n const value = extractText(message);\n textCache.set(obj, value);\n return value;\n}\n\nexport function extractThinking(message: unknown): string | null {\n const m = message as Record;\n const content = m.content;\n const parts: string[] = [];\n if (Array.isArray(content)) {\n for (const p of content) {\n const item = p as Record;\n if (item.type === \"thinking\" && typeof item.thinking === \"string\") {\n const cleaned = item.thinking.trim();\n if (cleaned) parts.push(cleaned);\n }\n }\n }\n if (parts.length > 0) return parts.join(\"\\n\");\n\n // Back-compat: older logs may still have tags inside text blocks.\n const rawText = extractRawText(message);\n if (!rawText) return null;\n const matches = [\n ...rawText.matchAll(\n /<\\s*think(?:ing)?\\s*>([\\s\\S]*?)<\\s*\\/\\s*think(?:ing)?\\s*>/gi,\n ),\n ];\n const extracted = matches\n .map((m) => (m[1] ?? \"\").trim())\n .filter(Boolean);\n return extracted.length > 0 ? extracted.join(\"\\n\") : null;\n}\n\nexport function extractThinkingCached(message: unknown): string | null {\n if (!message || typeof message !== \"object\") return extractThinking(message);\n const obj = message as object;\n if (thinkingCache.has(obj)) return thinkingCache.get(obj) ?? null;\n const value = extractThinking(message);\n thinkingCache.set(obj, value);\n return value;\n}\n\nexport function extractRawText(message: unknown): string | null {\n const m = message as Record;\n const content = m.content;\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) {\n const parts = content\n .map((p) => {\n const item = p as Record;\n if (item.type === \"text\" && typeof item.text === \"string\") return item.text;\n return null;\n })\n .filter((v): v is string => typeof v === \"string\");\n if (parts.length > 0) return parts.join(\"\\n\");\n }\n if (typeof m.text === \"string\") return m.text;\n return null;\n}\n\nexport function formatReasoningMarkdown(text: string): string {\n const trimmed = text.trim();\n if (!trimmed) return \"\";\n const lines = trimmed\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n .map((line) => `_${line}_`);\n return lines.length ? [\"_Reasoning:_\", ...lines].join(\"\\n\") : \"\";\n}\n","export type CryptoLike = {\n randomUUID?: (() => string) | undefined;\n getRandomValues?: ((array: Uint8Array) => Uint8Array) | undefined;\n};\n\nfunction uuidFromBytes(bytes: Uint8Array): string {\n bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4\n bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 1\n\n let hex = \"\";\n for (let i = 0; i < bytes.length; i++) {\n hex += bytes[i]!.toString(16).padStart(2, \"0\");\n }\n\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(\n 16,\n 20,\n )}-${hex.slice(20)}`;\n}\n\nfunction weakRandomBytes(): Uint8Array {\n const bytes = new Uint8Array(16);\n const now = Date.now();\n for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);\n bytes[0] ^= now & 0xff;\n bytes[1] ^= (now >>> 8) & 0xff;\n bytes[2] ^= (now >>> 16) & 0xff;\n bytes[3] ^= (now >>> 24) & 0xff;\n return bytes;\n}\n\nexport function generateUUID(cryptoLike: CryptoLike | null = globalThis.crypto): string {\n if (cryptoLike && typeof cryptoLike.randomUUID === \"function\") return cryptoLike.randomUUID();\n\n if (cryptoLike && typeof cryptoLike.getRandomValues === \"function\") {\n const bytes = new Uint8Array(16);\n cryptoLike.getRandomValues(bytes);\n return uuidFromBytes(bytes);\n }\n\n return uuidFromBytes(weakRandomBytes());\n}\n\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport { extractText } from \"../chat/message-extract\";\nimport { generateUUID } from \"../uuid\";\n\nexport type ChatState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n sessionKey: string;\n chatLoading: boolean;\n chatMessages: unknown[];\n chatThinkingLevel: string | null;\n chatSending: boolean;\n chatMessage: string;\n chatRunId: string | null;\n chatStream: string | null;\n chatStreamStartedAt: number | null;\n lastError: string | null;\n};\n\nexport type ChatEventPayload = {\n runId: string;\n sessionKey: string;\n state: \"delta\" | \"final\" | \"aborted\" | \"error\";\n message?: unknown;\n errorMessage?: string;\n};\n\nexport async function loadChatHistory(state: ChatState) {\n if (!state.client || !state.connected) return;\n state.chatLoading = true;\n state.lastError = null;\n try {\n const res = (await state.client.request(\"chat.history\", {\n sessionKey: state.sessionKey,\n limit: 200,\n })) as { messages?: unknown[]; thinkingLevel?: string | null };\n state.chatMessages = Array.isArray(res.messages) ? res.messages : [];\n state.chatThinkingLevel = res.thinkingLevel ?? null;\n } catch (err) {\n state.lastError = String(err);\n } finally {\n state.chatLoading = false;\n }\n}\n\nexport async function sendChatMessage(state: ChatState, message: string): Promise {\n if (!state.client || !state.connected) return false;\n const msg = message.trim();\n if (!msg) return false;\n\n const now = Date.now();\n state.chatMessages = [\n ...state.chatMessages,\n {\n role: \"user\",\n content: [{ type: \"text\", text: msg }],\n timestamp: now,\n },\n ];\n\n state.chatSending = true;\n state.lastError = null;\n const runId = generateUUID();\n state.chatRunId = runId;\n state.chatStream = \"\";\n state.chatStreamStartedAt = now;\n try {\n await state.client.request(\"chat.send\", {\n sessionKey: state.sessionKey,\n message: msg,\n deliver: false,\n idempotencyKey: runId,\n });\n return true;\n } catch (err) {\n const error = String(err);\n state.chatRunId = null;\n state.chatStream = null;\n state.chatStreamStartedAt = null;\n state.lastError = error;\n state.chatMessages = [\n ...state.chatMessages,\n {\n role: \"assistant\",\n content: [{ type: \"text\", text: \"Error: \" + error }],\n timestamp: Date.now(),\n },\n ];\n return false;\n } finally {\n state.chatSending = false;\n }\n}\n\nexport async function abortChatRun(state: ChatState): Promise {\n if (!state.client || !state.connected) return false;\n const runId = state.chatRunId;\n try {\n await state.client.request(\n \"chat.abort\",\n runId\n ? { sessionKey: state.sessionKey, runId }\n : { sessionKey: state.sessionKey },\n );\n return true;\n } catch (err) {\n state.lastError = String(err);\n return false;\n }\n}\n\nexport function handleChatEvent(\n state: ChatState,\n payload?: ChatEventPayload,\n) {\n if (!payload) return null;\n if (payload.sessionKey !== state.sessionKey) return null;\n if (payload.runId && state.chatRunId && payload.runId !== state.chatRunId)\n return null;\n\n if (payload.state === \"delta\") {\n const next = extractText(payload.message);\n if (typeof next === \"string\") {\n const current = state.chatStream ?? \"\";\n if (!current || next.length >= current.length) {\n state.chatStream = next;\n }\n }\n } else if (payload.state === \"final\") {\n state.chatStream = null;\n state.chatRunId = null;\n state.chatStreamStartedAt = null;\n } else if (payload.state === \"aborted\") {\n state.chatStream = null;\n state.chatRunId = null;\n state.chatStreamStartedAt = null;\n } else if (payload.state === \"error\") {\n state.chatStream = null;\n state.chatRunId = null;\n state.chatStreamStartedAt = null;\n state.lastError = payload.errorMessage ?? \"chat error\";\n }\n return payload.state;\n}\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport { toNumber } from \"../format\";\nimport type { SessionsListResult } from \"../types\";\n\nexport type SessionsState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n sessionsLoading: boolean;\n sessionsResult: SessionsListResult | null;\n sessionsError: string | null;\n sessionsFilterActive: string;\n sessionsFilterLimit: string;\n sessionsIncludeGlobal: boolean;\n sessionsIncludeUnknown: boolean;\n};\n\nexport async function loadSessions(state: SessionsState) {\n if (!state.client || !state.connected) return;\n if (state.sessionsLoading) return;\n state.sessionsLoading = true;\n state.sessionsError = null;\n try {\n const params: Record = {\n includeGlobal: state.sessionsIncludeGlobal,\n includeUnknown: state.sessionsIncludeUnknown,\n };\n const activeMinutes = toNumber(state.sessionsFilterActive, 0);\n const limit = toNumber(state.sessionsFilterLimit, 0);\n if (activeMinutes > 0) params.activeMinutes = activeMinutes;\n if (limit > 0) params.limit = limit;\n const res = (await state.client.request(\"sessions.list\", params)) as\n | SessionsListResult\n | undefined;\n if (res) state.sessionsResult = res;\n } catch (err) {\n state.sessionsError = String(err);\n } finally {\n state.sessionsLoading = false;\n }\n}\n\nexport async function patchSession(\n state: SessionsState,\n key: string,\n patch: {\n label?: string | null;\n thinkingLevel?: string | null;\n verboseLevel?: string | null;\n reasoningLevel?: string | null;\n },\n) {\n if (!state.client || !state.connected) return;\n const params: Record = { key };\n if (\"label\" in patch) params.label = patch.label;\n if (\"thinkingLevel\" in patch) params.thinkingLevel = patch.thinkingLevel;\n if (\"verboseLevel\" in patch) params.verboseLevel = patch.verboseLevel;\n if (\"reasoningLevel\" in patch) params.reasoningLevel = patch.reasoningLevel;\n try {\n await state.client.request(\"sessions.patch\", params);\n await loadSessions(state);\n } catch (err) {\n state.sessionsError = String(err);\n }\n}\n\nexport async function deleteSession(state: SessionsState, key: string) {\n if (!state.client || !state.connected) return;\n if (state.sessionsLoading) return;\n const confirmed = window.confirm(\n `Delete session \"${key}\"?\\n\\nDeletes the session entry and archives its transcript.`,\n );\n if (!confirmed) return;\n state.sessionsLoading = true;\n state.sessionsError = null;\n try {\n await state.client.request(\"sessions.delete\", { key, deleteTranscript: true });\n await loadSessions(state);\n } catch (err) {\n state.sessionsError = String(err);\n } finally {\n state.sessionsLoading = false;\n }\n}\n","import { truncateText } from \"./format\";\n\nconst TOOL_STREAM_LIMIT = 50;\nconst TOOL_STREAM_THROTTLE_MS = 80;\nconst TOOL_OUTPUT_CHAR_LIMIT = 120_000;\n\nexport type AgentEventPayload = {\n runId: string;\n seq: number;\n stream: string;\n ts: number;\n sessionKey?: string;\n data: Record;\n};\n\nexport type ToolStreamEntry = {\n toolCallId: string;\n runId: string;\n sessionKey?: string;\n name: string;\n args?: unknown;\n output?: string;\n startedAt: number;\n updatedAt: number;\n message: Record;\n};\n\ntype ToolStreamHost = {\n sessionKey: string;\n chatRunId: string | null;\n toolStreamById: Map;\n toolStreamOrder: string[];\n chatToolMessages: Record[];\n toolStreamSyncTimer: number | null;\n};\n\nfunction extractToolOutputText(value: unknown): string | null {\n if (!value || typeof value !== \"object\") return null;\n const record = value as Record;\n if (typeof record.text === \"string\") return record.text;\n const content = record.content;\n if (!Array.isArray(content)) return null;\n const parts = content\n .map((item) => {\n if (!item || typeof item !== \"object\") return null;\n const entry = item as Record;\n if (entry.type === \"text\" && typeof entry.text === \"string\") return entry.text;\n return null;\n })\n .filter((part): part is string => Boolean(part));\n if (parts.length === 0) return null;\n return parts.join(\"\\n\");\n}\n\nfunction formatToolOutput(value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n const contentText = extractToolOutputText(value);\n let text: string;\n if (typeof value === \"string\") {\n text = value;\n } else if (contentText) {\n text = contentText;\n } else {\n try {\n text = JSON.stringify(value, null, 2);\n } catch {\n text = String(value);\n }\n }\n const truncated = truncateText(text, TOOL_OUTPUT_CHAR_LIMIT);\n if (!truncated.truncated) return truncated.text;\n return `${truncated.text}\\n\\n… truncated (${truncated.total} chars, showing first ${truncated.text.length}).`;\n}\n\nfunction buildToolStreamMessage(entry: ToolStreamEntry): Record {\n const content: Array> = [];\n content.push({\n type: \"toolcall\",\n name: entry.name,\n arguments: entry.args ?? {},\n });\n if (entry.output) {\n content.push({\n type: \"toolresult\",\n name: entry.name,\n text: entry.output,\n });\n }\n return {\n role: \"assistant\",\n toolCallId: entry.toolCallId,\n runId: entry.runId,\n content,\n timestamp: entry.startedAt,\n };\n}\n\nfunction trimToolStream(host: ToolStreamHost) {\n if (host.toolStreamOrder.length <= TOOL_STREAM_LIMIT) return;\n const overflow = host.toolStreamOrder.length - TOOL_STREAM_LIMIT;\n const removed = host.toolStreamOrder.splice(0, overflow);\n for (const id of removed) host.toolStreamById.delete(id);\n}\n\nfunction syncToolStreamMessages(host: ToolStreamHost) {\n host.chatToolMessages = host.toolStreamOrder\n .map((id) => host.toolStreamById.get(id)?.message)\n .filter((msg): msg is Record => Boolean(msg));\n}\n\nexport function flushToolStreamSync(host: ToolStreamHost) {\n if (host.toolStreamSyncTimer != null) {\n clearTimeout(host.toolStreamSyncTimer);\n host.toolStreamSyncTimer = null;\n }\n syncToolStreamMessages(host);\n}\n\nexport function scheduleToolStreamSync(host: ToolStreamHost, force = false) {\n if (force) {\n flushToolStreamSync(host);\n return;\n }\n if (host.toolStreamSyncTimer != null) return;\n host.toolStreamSyncTimer = window.setTimeout(\n () => flushToolStreamSync(host),\n TOOL_STREAM_THROTTLE_MS,\n );\n}\n\nexport function resetToolStream(host: ToolStreamHost) {\n host.toolStreamById.clear();\n host.toolStreamOrder = [];\n host.chatToolMessages = [];\n flushToolStreamSync(host);\n}\n\nexport type CompactionStatus = {\n active: boolean;\n startedAt: number | null;\n completedAt: number | null;\n};\n\ntype CompactionHost = ToolStreamHost & {\n compactionStatus?: CompactionStatus | null;\n compactionClearTimer?: number | null;\n};\n\nconst COMPACTION_TOAST_DURATION_MS = 5000;\n\nexport function handleCompactionEvent(host: CompactionHost, payload: AgentEventPayload) {\n const data = payload.data ?? {};\n const phase = typeof data.phase === \"string\" ? data.phase : \"\";\n \n // Clear any existing timer\n if (host.compactionClearTimer != null) {\n window.clearTimeout(host.compactionClearTimer);\n host.compactionClearTimer = null;\n }\n \n if (phase === \"start\") {\n host.compactionStatus = {\n active: true,\n startedAt: Date.now(),\n completedAt: null,\n };\n } else if (phase === \"end\") {\n host.compactionStatus = {\n active: false,\n startedAt: host.compactionStatus?.startedAt ?? null,\n completedAt: Date.now(),\n };\n // Auto-clear the toast after duration\n host.compactionClearTimer = window.setTimeout(() => {\n host.compactionStatus = null;\n host.compactionClearTimer = null;\n }, COMPACTION_TOAST_DURATION_MS);\n }\n}\n\nexport function handleAgentEvent(host: ToolStreamHost, payload?: AgentEventPayload) {\n if (!payload) return;\n \n // Handle compaction events\n if (payload.stream === \"compaction\") {\n handleCompactionEvent(host as CompactionHost, payload);\n return;\n }\n \n if (payload.stream !== \"tool\") return;\n const sessionKey =\n typeof payload.sessionKey === \"string\" ? payload.sessionKey : undefined;\n if (sessionKey && sessionKey !== host.sessionKey) return;\n // Fallback: only accept session-less events for the active run.\n if (!sessionKey && host.chatRunId && payload.runId !== host.chatRunId) return;\n if (host.chatRunId && payload.runId !== host.chatRunId) return;\n if (!host.chatRunId) return;\n\n const data = payload.data ?? {};\n const toolCallId = typeof data.toolCallId === \"string\" ? data.toolCallId : \"\";\n if (!toolCallId) return;\n const name = typeof data.name === \"string\" ? data.name : \"tool\";\n const phase = typeof data.phase === \"string\" ? data.phase : \"\";\n const args = phase === \"start\" ? data.args : undefined;\n const output =\n phase === \"update\"\n ? formatToolOutput(data.partialResult)\n : phase === \"result\"\n ? formatToolOutput(data.result)\n : undefined;\n\n const now = Date.now();\n let entry = host.toolStreamById.get(toolCallId);\n if (!entry) {\n entry = {\n toolCallId,\n runId: payload.runId,\n sessionKey,\n name,\n args,\n output,\n startedAt: typeof payload.ts === \"number\" ? payload.ts : now,\n updatedAt: now,\n message: {},\n };\n host.toolStreamById.set(toolCallId, entry);\n host.toolStreamOrder.push(toolCallId);\n } else {\n entry.name = name;\n if (args !== undefined) entry.args = args;\n if (output !== undefined) entry.output = output;\n entry.updatedAt = now;\n }\n\n entry.message = buildToolStreamMessage(entry);\n trimToolStream(host);\n scheduleToolStreamSync(host, phase === \"result\");\n}\n","type ScrollHost = {\n updateComplete: Promise;\n querySelector: (selectors: string) => Element | null;\n style: CSSStyleDeclaration;\n chatScrollFrame: number | null;\n chatScrollTimeout: number | null;\n chatHasAutoScrolled: boolean;\n chatUserNearBottom: boolean;\n logsScrollFrame: number | null;\n logsAtBottom: boolean;\n topbarObserver: ResizeObserver | null;\n};\n\nexport function scheduleChatScroll(host: ScrollHost, force = false) {\n if (host.chatScrollFrame) cancelAnimationFrame(host.chatScrollFrame);\n if (host.chatScrollTimeout != null) {\n clearTimeout(host.chatScrollTimeout);\n host.chatScrollTimeout = null;\n }\n const pickScrollTarget = () => {\n const container = host.querySelector(\".chat-thread\") as HTMLElement | null;\n if (container) {\n const overflowY = getComputedStyle(container).overflowY;\n const canScroll =\n overflowY === \"auto\" ||\n overflowY === \"scroll\" ||\n container.scrollHeight - container.clientHeight > 1;\n if (canScroll) return container;\n }\n return (document.scrollingElement ?? document.documentElement) as HTMLElement | null;\n };\n // Wait for Lit render to complete, then scroll\n void host.updateComplete.then(() => {\n host.chatScrollFrame = requestAnimationFrame(() => {\n host.chatScrollFrame = null;\n const target = pickScrollTarget();\n if (!target) return;\n const distanceFromBottom =\n target.scrollHeight - target.scrollTop - target.clientHeight;\n const shouldStick = force || host.chatUserNearBottom || distanceFromBottom < 200;\n if (!shouldStick) return;\n if (force) host.chatHasAutoScrolled = true;\n target.scrollTop = target.scrollHeight;\n host.chatUserNearBottom = true;\n const retryDelay = force ? 150 : 120;\n host.chatScrollTimeout = window.setTimeout(() => {\n host.chatScrollTimeout = null;\n const latest = pickScrollTarget();\n if (!latest) return;\n const latestDistanceFromBottom =\n latest.scrollHeight - latest.scrollTop - latest.clientHeight;\n const shouldStickRetry =\n force || host.chatUserNearBottom || latestDistanceFromBottom < 200;\n if (!shouldStickRetry) return;\n latest.scrollTop = latest.scrollHeight;\n host.chatUserNearBottom = true;\n }, retryDelay);\n });\n });\n}\n\nexport function scheduleLogsScroll(host: ScrollHost, force = false) {\n if (host.logsScrollFrame) cancelAnimationFrame(host.logsScrollFrame);\n void host.updateComplete.then(() => {\n host.logsScrollFrame = requestAnimationFrame(() => {\n host.logsScrollFrame = null;\n const container = host.querySelector(\".log-stream\") as HTMLElement | null;\n if (!container) return;\n const distanceFromBottom =\n container.scrollHeight - container.scrollTop - container.clientHeight;\n const shouldStick = force || distanceFromBottom < 80;\n if (!shouldStick) return;\n container.scrollTop = container.scrollHeight;\n });\n });\n}\n\nexport function handleChatScroll(host: ScrollHost, event: Event) {\n const container = event.currentTarget as HTMLElement | null;\n if (!container) return;\n const distanceFromBottom =\n container.scrollHeight - container.scrollTop - container.clientHeight;\n host.chatUserNearBottom = distanceFromBottom < 200;\n}\n\nexport function handleLogsScroll(host: ScrollHost, event: Event) {\n const container = event.currentTarget as HTMLElement | null;\n if (!container) return;\n const distanceFromBottom =\n container.scrollHeight - container.scrollTop - container.clientHeight;\n host.logsAtBottom = distanceFromBottom < 80;\n}\n\nexport function resetChatScroll(host: ScrollHost) {\n host.chatHasAutoScrolled = false;\n host.chatUserNearBottom = true;\n}\n\nexport function exportLogs(lines: string[], label: string) {\n if (lines.length === 0) return;\n const blob = new Blob([`${lines.join(\"\\n\")}\\n`], { type: \"text/plain\" });\n const url = URL.createObjectURL(blob);\n const anchor = document.createElement(\"a\");\n const stamp = new Date().toISOString().slice(0, 19).replace(/[:T]/g, \"-\");\n anchor.href = url;\n anchor.download = `clawdbot-logs-${label}-${stamp}.log`;\n anchor.click();\n URL.revokeObjectURL(url);\n}\n\nexport function observeTopbar(host: ScrollHost) {\n if (typeof ResizeObserver === \"undefined\") return;\n const topbar = host.querySelector(\".topbar\");\n if (!topbar) return;\n const update = () => {\n const { height } = topbar.getBoundingClientRect();\n host.style.setProperty(\"--topbar-height\", `${height}px`);\n };\n update();\n host.topbarObserver = new ResizeObserver(() => update());\n host.topbarObserver.observe(topbar);\n}\n","export function cloneConfigObject(value: T): T {\n if (typeof structuredClone === \"function\") {\n return structuredClone(value);\n }\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nexport function serializeConfigForm(form: Record): string {\n return `${JSON.stringify(form, null, 2).trimEnd()}\\n`;\n}\n\nexport function setPathValue(\n obj: Record | unknown[],\n path: Array,\n value: unknown,\n) {\n if (path.length === 0) return;\n let current: Record | unknown[] = obj;\n for (let i = 0; i < path.length - 1; i += 1) {\n const key = path[i];\n const nextKey = path[i + 1];\n if (typeof key === \"number\") {\n if (!Array.isArray(current)) return;\n if (current[key] == null) {\n current[key] =\n typeof nextKey === \"number\" ? [] : ({} as Record);\n }\n current = current[key] as Record | unknown[];\n } else {\n if (typeof current !== \"object\" || current == null) return;\n const record = current as Record;\n if (record[key] == null) {\n record[key] =\n typeof nextKey === \"number\" ? [] : ({} as Record);\n }\n current = record[key] as Record | unknown[];\n }\n }\n const lastKey = path[path.length - 1];\n if (typeof lastKey === \"number\") {\n if (Array.isArray(current)) current[lastKey] = value;\n return;\n }\n if (typeof current === \"object\" && current != null) {\n (current as Record)[lastKey] = value;\n }\n}\n\nexport function removePathValue(\n obj: Record | unknown[],\n path: Array,\n) {\n if (path.length === 0) return;\n let current: Record | unknown[] = obj;\n for (let i = 0; i < path.length - 1; i += 1) {\n const key = path[i];\n if (typeof key === \"number\") {\n if (!Array.isArray(current)) return;\n current = current[key] as Record | unknown[];\n } else {\n if (typeof current !== \"object\" || current == null) return;\n current = (current as Record)[key] as\n | Record\n | unknown[];\n }\n if (current == null) return;\n }\n const lastKey = path[path.length - 1];\n if (typeof lastKey === \"number\") {\n if (Array.isArray(current)) current.splice(lastKey, 1);\n return;\n }\n if (typeof current === \"object\" && current != null) {\n delete (current as Record)[lastKey];\n }\n}\n\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport type {\n ConfigSchemaResponse,\n ConfigSnapshot,\n ConfigUiHints,\n} from \"../types\";\nimport {\n cloneConfigObject,\n removePathValue,\n serializeConfigForm,\n setPathValue,\n} from \"./config/form-utils\";\n\nexport type ConfigState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n applySessionKey: string;\n configLoading: boolean;\n configRaw: string;\n configRawOriginal: string;\n configValid: boolean | null;\n configIssues: unknown[];\n configSaving: boolean;\n configApplying: boolean;\n updateRunning: boolean;\n configSnapshot: ConfigSnapshot | null;\n configSchema: unknown | null;\n configSchemaVersion: string | null;\n configSchemaLoading: boolean;\n configUiHints: ConfigUiHints;\n configForm: Record | null;\n configFormOriginal: Record | null;\n configFormDirty: boolean;\n configFormMode: \"form\" | \"raw\";\n configSearchQuery: string;\n configActiveSection: string | null;\n configActiveSubsection: string | null;\n lastError: string | null;\n};\n\nexport async function loadConfig(state: ConfigState) {\n if (!state.client || !state.connected) return;\n state.configLoading = true;\n state.lastError = null;\n try {\n const res = (await state.client.request(\"config.get\", {})) as ConfigSnapshot;\n applyConfigSnapshot(state, res);\n } catch (err) {\n state.lastError = String(err);\n } finally {\n state.configLoading = false;\n }\n}\n\nexport async function loadConfigSchema(state: ConfigState) {\n if (!state.client || !state.connected) return;\n if (state.configSchemaLoading) return;\n state.configSchemaLoading = true;\n try {\n const res = (await state.client.request(\n \"config.schema\",\n {},\n )) as ConfigSchemaResponse;\n applyConfigSchema(state, res);\n } catch (err) {\n state.lastError = String(err);\n } finally {\n state.configSchemaLoading = false;\n }\n}\n\nexport function applyConfigSchema(\n state: ConfigState,\n res: ConfigSchemaResponse,\n) {\n state.configSchema = res.schema ?? null;\n state.configUiHints = res.uiHints ?? {};\n state.configSchemaVersion = res.version ?? null;\n}\n\nexport function applyConfigSnapshot(state: ConfigState, snapshot: ConfigSnapshot) {\n state.configSnapshot = snapshot;\n const rawFromSnapshot =\n typeof snapshot.raw === \"string\"\n ? snapshot.raw\n : snapshot.config && typeof snapshot.config === \"object\"\n ? serializeConfigForm(snapshot.config as Record)\n : state.configRaw;\n if (!state.configFormDirty || state.configFormMode === \"raw\") {\n state.configRaw = rawFromSnapshot;\n } else if (state.configForm) {\n state.configRaw = serializeConfigForm(state.configForm);\n } else {\n state.configRaw = rawFromSnapshot;\n }\n state.configValid = typeof snapshot.valid === \"boolean\" ? snapshot.valid : null;\n state.configIssues = Array.isArray(snapshot.issues) ? snapshot.issues : [];\n\n if (!state.configFormDirty) {\n state.configForm = cloneConfigObject(snapshot.config ?? {});\n state.configFormOriginal = cloneConfigObject(snapshot.config ?? {});\n state.configRawOriginal = rawFromSnapshot;\n }\n}\n\nexport async function saveConfig(state: ConfigState) {\n if (!state.client || !state.connected) return;\n state.configSaving = true;\n state.lastError = null;\n try {\n const raw =\n state.configFormMode === \"form\" && state.configForm\n ? serializeConfigForm(state.configForm)\n : state.configRaw;\n const baseHash = state.configSnapshot?.hash;\n if (!baseHash) {\n state.lastError = \"Config hash missing; reload and retry.\";\n return;\n }\n await state.client.request(\"config.set\", { raw, baseHash });\n state.configFormDirty = false;\n await loadConfig(state);\n } catch (err) {\n state.lastError = String(err);\n } finally {\n state.configSaving = false;\n }\n}\n\nexport async function applyConfig(state: ConfigState) {\n if (!state.client || !state.connected) return;\n state.configApplying = true;\n state.lastError = null;\n try {\n const raw =\n state.configFormMode === \"form\" && state.configForm\n ? serializeConfigForm(state.configForm)\n : state.configRaw;\n const baseHash = state.configSnapshot?.hash;\n if (!baseHash) {\n state.lastError = \"Config hash missing; reload and retry.\";\n return;\n }\n await state.client.request(\"config.apply\", {\n raw,\n baseHash,\n sessionKey: state.applySessionKey,\n });\n state.configFormDirty = false;\n await loadConfig(state);\n } catch (err) {\n state.lastError = String(err);\n } finally {\n state.configApplying = false;\n }\n}\n\nexport async function runUpdate(state: ConfigState) {\n if (!state.client || !state.connected) return;\n state.updateRunning = true;\n state.lastError = null;\n try {\n await state.client.request(\"update.run\", {\n sessionKey: state.applySessionKey,\n });\n } catch (err) {\n state.lastError = String(err);\n } finally {\n state.updateRunning = false;\n }\n}\n\nexport function updateConfigFormValue(\n state: ConfigState,\n path: Array,\n value: unknown,\n) {\n const base = cloneConfigObject(\n state.configForm ?? state.configSnapshot?.config ?? {},\n );\n setPathValue(base, path, value);\n state.configForm = base;\n state.configFormDirty = true;\n if (state.configFormMode === \"form\") {\n state.configRaw = serializeConfigForm(base);\n }\n}\n\nexport function removeConfigFormValue(\n state: ConfigState,\n path: Array,\n) {\n const base = cloneConfigObject(\n state.configForm ?? state.configSnapshot?.config ?? {},\n );\n removePathValue(base, path);\n state.configForm = base;\n state.configFormDirty = true;\n if (state.configFormMode === \"form\") {\n state.configRaw = serializeConfigForm(base);\n }\n}\n","import { toNumber } from \"../format\";\nimport type { GatewayBrowserClient } from \"../gateway\";\nimport type { CronJob, CronRunLogEntry, CronStatus } from \"../types\";\nimport type { CronFormState } from \"../ui-types\";\n\nexport type CronState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n cronLoading: boolean;\n cronJobs: CronJob[];\n cronStatus: CronStatus | null;\n cronError: string | null;\n cronForm: CronFormState;\n cronRunsJobId: string | null;\n cronRuns: CronRunLogEntry[];\n cronBusy: boolean;\n};\n\nexport async function loadCronStatus(state: CronState) {\n if (!state.client || !state.connected) return;\n try {\n const res = (await state.client.request(\"cron.status\", {})) as CronStatus;\n state.cronStatus = res;\n } catch (err) {\n state.cronError = String(err);\n }\n}\n\nexport async function loadCronJobs(state: CronState) {\n if (!state.client || !state.connected) return;\n if (state.cronLoading) return;\n state.cronLoading = true;\n state.cronError = null;\n try {\n const res = (await state.client.request(\"cron.list\", {\n includeDisabled: true,\n })) as { jobs?: CronJob[] };\n state.cronJobs = Array.isArray(res.jobs) ? res.jobs : [];\n } catch (err) {\n state.cronError = String(err);\n } finally {\n state.cronLoading = false;\n }\n}\n\nexport function buildCronSchedule(form: CronFormState) {\n if (form.scheduleKind === \"at\") {\n const ms = Date.parse(form.scheduleAt);\n if (!Number.isFinite(ms)) throw new Error(\"Invalid run time.\");\n return { kind: \"at\" as const, atMs: ms };\n }\n if (form.scheduleKind === \"every\") {\n const amount = toNumber(form.everyAmount, 0);\n if (amount <= 0) throw new Error(\"Invalid interval amount.\");\n const unit = form.everyUnit;\n const mult = unit === \"minutes\" ? 60_000 : unit === \"hours\" ? 3_600_000 : 86_400_000;\n return { kind: \"every\" as const, everyMs: amount * mult };\n }\n const expr = form.cronExpr.trim();\n if (!expr) throw new Error(\"Cron expression required.\");\n return { kind: \"cron\" as const, expr, tz: form.cronTz.trim() || undefined };\n}\n\nexport function buildCronPayload(form: CronFormState) {\n if (form.payloadKind === \"systemEvent\") {\n const text = form.payloadText.trim();\n if (!text) throw new Error(\"System event text required.\");\n return { kind: \"systemEvent\" as const, text };\n }\n const message = form.payloadText.trim();\n if (!message) throw new Error(\"Agent message required.\");\n const payload: {\n kind: \"agentTurn\";\n message: string;\n deliver?: boolean;\n channel?: string;\n to?: string;\n timeoutSeconds?: number;\n } = { kind: \"agentTurn\", message };\n if (form.deliver) payload.deliver = true;\n if (form.channel) payload.channel = form.channel;\n if (form.to.trim()) payload.to = form.to.trim();\n const timeoutSeconds = toNumber(form.timeoutSeconds, 0);\n if (timeoutSeconds > 0) payload.timeoutSeconds = timeoutSeconds;\n return payload;\n}\n\nexport async function addCronJob(state: CronState) {\n if (!state.client || !state.connected || state.cronBusy) return;\n state.cronBusy = true;\n state.cronError = null;\n try {\n const schedule = buildCronSchedule(state.cronForm);\n const payload = buildCronPayload(state.cronForm);\n const agentId = state.cronForm.agentId.trim();\n const job = {\n name: state.cronForm.name.trim(),\n description: state.cronForm.description.trim() || undefined,\n agentId: agentId || undefined,\n enabled: state.cronForm.enabled,\n schedule,\n sessionTarget: state.cronForm.sessionTarget,\n wakeMode: state.cronForm.wakeMode,\n payload,\n isolation:\n state.cronForm.postToMainPrefix.trim() &&\n state.cronForm.sessionTarget === \"isolated\"\n ? { postToMainPrefix: state.cronForm.postToMainPrefix.trim() }\n : undefined,\n };\n if (!job.name) throw new Error(\"Name required.\");\n await state.client.request(\"cron.add\", job);\n state.cronForm = {\n ...state.cronForm,\n name: \"\",\n description: \"\",\n payloadText: \"\",\n };\n await loadCronJobs(state);\n await loadCronStatus(state);\n } catch (err) {\n state.cronError = String(err);\n } finally {\n state.cronBusy = false;\n }\n}\n\nexport async function toggleCronJob(\n state: CronState,\n job: CronJob,\n enabled: boolean,\n) {\n if (!state.client || !state.connected || state.cronBusy) return;\n state.cronBusy = true;\n state.cronError = null;\n try {\n await state.client.request(\"cron.update\", { id: job.id, patch: { enabled } });\n await loadCronJobs(state);\n await loadCronStatus(state);\n } catch (err) {\n state.cronError = String(err);\n } finally {\n state.cronBusy = false;\n }\n}\n\nexport async function runCronJob(state: CronState, job: CronJob) {\n if (!state.client || !state.connected || state.cronBusy) return;\n state.cronBusy = true;\n state.cronError = null;\n try {\n await state.client.request(\"cron.run\", { id: job.id, mode: \"force\" });\n await loadCronRuns(state, job.id);\n } catch (err) {\n state.cronError = String(err);\n } finally {\n state.cronBusy = false;\n }\n}\n\nexport async function removeCronJob(state: CronState, job: CronJob) {\n if (!state.client || !state.connected || state.cronBusy) return;\n state.cronBusy = true;\n state.cronError = null;\n try {\n await state.client.request(\"cron.remove\", { id: job.id });\n if (state.cronRunsJobId === job.id) {\n state.cronRunsJobId = null;\n state.cronRuns = [];\n }\n await loadCronJobs(state);\n await loadCronStatus(state);\n } catch (err) {\n state.cronError = String(err);\n } finally {\n state.cronBusy = false;\n }\n}\n\nexport async function loadCronRuns(state: CronState, jobId: string) {\n if (!state.client || !state.connected) return;\n try {\n const res = (await state.client.request(\"cron.runs\", {\n id: jobId,\n limit: 50,\n })) as { entries?: CronRunLogEntry[] };\n state.cronRunsJobId = jobId;\n state.cronRuns = Array.isArray(res.entries) ? res.entries : [];\n } catch (err) {\n state.cronError = String(err);\n }\n}\n","import type { ChannelsStatusSnapshot } from \"../types\";\nimport type { ChannelsState } from \"./channels.types\";\n\nexport type { ChannelsState };\n\nexport async function loadChannels(state: ChannelsState, probe: boolean) {\n if (!state.client || !state.connected) return;\n if (state.channelsLoading) return;\n state.channelsLoading = true;\n state.channelsError = null;\n try {\n const res = (await state.client.request(\"channels.status\", {\n probe,\n timeoutMs: 8000,\n })) as ChannelsStatusSnapshot;\n state.channelsSnapshot = res;\n state.channelsLastSuccess = Date.now();\n } catch (err) {\n state.channelsError = String(err);\n } finally {\n state.channelsLoading = false;\n }\n}\n\nexport async function startWhatsAppLogin(state: ChannelsState, force: boolean) {\n if (!state.client || !state.connected || state.whatsappBusy) return;\n state.whatsappBusy = true;\n try {\n const res = (await state.client.request(\"web.login.start\", {\n force,\n timeoutMs: 30000,\n })) as { message?: string; qrDataUrl?: string };\n state.whatsappLoginMessage = res.message ?? null;\n state.whatsappLoginQrDataUrl = res.qrDataUrl ?? null;\n state.whatsappLoginConnected = null;\n } catch (err) {\n state.whatsappLoginMessage = String(err);\n state.whatsappLoginQrDataUrl = null;\n state.whatsappLoginConnected = null;\n } finally {\n state.whatsappBusy = false;\n }\n}\n\nexport async function waitWhatsAppLogin(state: ChannelsState) {\n if (!state.client || !state.connected || state.whatsappBusy) return;\n state.whatsappBusy = true;\n try {\n const res = (await state.client.request(\"web.login.wait\", {\n timeoutMs: 120000,\n })) as { connected?: boolean; message?: string };\n state.whatsappLoginMessage = res.message ?? null;\n state.whatsappLoginConnected = res.connected ?? null;\n if (res.connected) state.whatsappLoginQrDataUrl = null;\n } catch (err) {\n state.whatsappLoginMessage = String(err);\n state.whatsappLoginConnected = null;\n } finally {\n state.whatsappBusy = false;\n }\n}\n\nexport async function logoutWhatsApp(state: ChannelsState) {\n if (!state.client || !state.connected || state.whatsappBusy) return;\n state.whatsappBusy = true;\n try {\n await state.client.request(\"channels.logout\", { channel: \"whatsapp\" });\n state.whatsappLoginMessage = \"Logged out.\";\n state.whatsappLoginQrDataUrl = null;\n state.whatsappLoginConnected = null;\n } catch (err) {\n state.whatsappLoginMessage = String(err);\n } finally {\n state.whatsappBusy = false;\n }\n}\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport type { HealthSnapshot, StatusSummary } from \"../types\";\n\nexport type DebugState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n debugLoading: boolean;\n debugStatus: StatusSummary | null;\n debugHealth: HealthSnapshot | null;\n debugModels: unknown[];\n debugHeartbeat: unknown | null;\n debugCallMethod: string;\n debugCallParams: string;\n debugCallResult: string | null;\n debugCallError: string | null;\n};\n\nexport async function loadDebug(state: DebugState) {\n if (!state.client || !state.connected) return;\n if (state.debugLoading) return;\n state.debugLoading = true;\n try {\n const [status, health, models, heartbeat] = await Promise.all([\n state.client.request(\"status\", {}),\n state.client.request(\"health\", {}),\n state.client.request(\"models.list\", {}),\n state.client.request(\"last-heartbeat\", {}),\n ]);\n state.debugStatus = status as StatusSummary;\n state.debugHealth = health as HealthSnapshot;\n const modelPayload = models as { models?: unknown[] } | undefined;\n state.debugModels = Array.isArray(modelPayload?.models)\n ? modelPayload?.models\n : [];\n state.debugHeartbeat = heartbeat as unknown;\n } catch (err) {\n state.debugCallError = String(err);\n } finally {\n state.debugLoading = false;\n }\n}\n\nexport async function callDebugMethod(state: DebugState) {\n if (!state.client || !state.connected) return;\n state.debugCallError = null;\n state.debugCallResult = null;\n try {\n const params = state.debugCallParams.trim()\n ? (JSON.parse(state.debugCallParams) as unknown)\n : {};\n const res = await state.client.request(state.debugCallMethod.trim(), params);\n state.debugCallResult = JSON.stringify(res, null, 2);\n } catch (err) {\n state.debugCallError = String(err);\n }\n}\n\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport type { LogEntry, LogLevel } from \"../types\";\n\nexport type LogsState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n logsLoading: boolean;\n logsError: string | null;\n logsCursor: number | null;\n logsFile: string | null;\n logsEntries: LogEntry[];\n logsTruncated: boolean;\n logsLastFetchAt: number | null;\n logsLimit: number;\n logsMaxBytes: number;\n};\n\nconst LOG_BUFFER_LIMIT = 2000;\nconst LEVELS = new Set([\n \"trace\",\n \"debug\",\n \"info\",\n \"warn\",\n \"error\",\n \"fatal\",\n]);\n\nfunction parseMaybeJsonString(value: unknown) {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n if (!trimmed.startsWith(\"{\") || !trimmed.endsWith(\"}\")) return null;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (!parsed || typeof parsed !== \"object\") return null;\n return parsed as Record;\n } catch {\n return null;\n }\n}\n\nfunction normalizeLevel(value: unknown): LogLevel | null {\n if (typeof value !== \"string\") return null;\n const lowered = value.toLowerCase() as LogLevel;\n return LEVELS.has(lowered) ? lowered : null;\n}\n\nexport function parseLogLine(line: string): LogEntry {\n if (!line.trim()) return { raw: line, message: line };\n try {\n const obj = JSON.parse(line) as Record;\n const meta =\n obj && typeof obj._meta === \"object\" && obj._meta !== null\n ? (obj._meta as Record)\n : null;\n const time =\n typeof obj.time === \"string\"\n ? obj.time\n : typeof meta?.date === \"string\"\n ? meta?.date\n : null;\n const level = normalizeLevel(meta?.logLevelName ?? meta?.level);\n\n const contextCandidate =\n typeof obj[\"0\"] === \"string\"\n ? (obj[\"0\"] as string)\n : typeof meta?.name === \"string\"\n ? (meta?.name as string)\n : null;\n const contextObj = parseMaybeJsonString(contextCandidate);\n let subsystem: string | null = null;\n if (contextObj) {\n if (typeof contextObj.subsystem === \"string\") subsystem = contextObj.subsystem;\n else if (typeof contextObj.module === \"string\") subsystem = contextObj.module;\n }\n if (!subsystem && contextCandidate && contextCandidate.length < 120) {\n subsystem = contextCandidate;\n }\n\n let message: string | null = null;\n if (typeof obj[\"1\"] === \"string\") message = obj[\"1\"] as string;\n else if (!contextObj && typeof obj[\"0\"] === \"string\") message = obj[\"0\"] as string;\n else if (typeof obj.message === \"string\") message = obj.message as string;\n\n return {\n raw: line,\n time,\n level,\n subsystem,\n message: message ?? line,\n meta: meta ?? undefined,\n };\n } catch {\n return { raw: line, message: line };\n }\n}\n\nexport async function loadLogs(\n state: LogsState,\n opts?: { reset?: boolean; quiet?: boolean },\n) {\n if (!state.client || !state.connected) return;\n if (state.logsLoading && !opts?.quiet) return;\n if (!opts?.quiet) state.logsLoading = true;\n state.logsError = null;\n try {\n const res = await state.client.request(\"logs.tail\", {\n cursor: opts?.reset ? undefined : state.logsCursor ?? undefined,\n limit: state.logsLimit,\n maxBytes: state.logsMaxBytes,\n });\n const payload = res as {\n file?: string;\n cursor?: number;\n size?: number;\n lines?: unknown;\n truncated?: boolean;\n reset?: boolean;\n };\n const lines = Array.isArray(payload.lines)\n ? (payload.lines.filter((line) => typeof line === \"string\") as string[])\n : [];\n const entries = lines.map(parseLogLine);\n const shouldReset = Boolean(opts?.reset || payload.reset || state.logsCursor == null);\n state.logsEntries = shouldReset\n ? entries\n : [...state.logsEntries, ...entries].slice(-LOG_BUFFER_LIMIT);\n if (typeof payload.cursor === \"number\") state.logsCursor = payload.cursor;\n if (typeof payload.file === \"string\") state.logsFile = payload.file;\n state.logsTruncated = Boolean(payload.truncated);\n state.logsLastFetchAt = Date.now();\n } catch (err) {\n state.logsError = String(err);\n } finally {\n if (!opts?.quiet) state.logsLoading = false;\n }\n}\n","/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\n/**\n * 5KB JS implementation of ed25519 EdDSA signatures.\n * Compliant with RFC8032, FIPS 186-5 & ZIP215.\n * @module\n * @example\n * ```js\nimport * as ed from '@noble/ed25519';\n(async () => {\n const secretKey = ed.utils.randomSecretKey();\n const message = Uint8Array.from([0xab, 0xbc, 0xcd, 0xde]);\n const pubKey = await ed.getPublicKeyAsync(secretKey); // Sync methods are also present\n const signature = await ed.signAsync(message, secretKey);\n const isValid = await ed.verifyAsync(signature, message, pubKey);\n})();\n```\n */\n/**\n * Curve params. ed25519 is twisted edwards curve. Equation is −x² + y² = -a + dx²y².\n * * P = `2n**255n - 19n` // field over which calculations are done\n * * N = `2n**252n + 27742317777372353535851937790883648493n` // group order, amount of curve points\n * * h = 8 // cofactor\n * * a = `Fp.create(BigInt(-1))` // equation param\n * * d = -121665/121666 a.k.a. `Fp.neg(121665 * Fp.inv(121666))` // equation param\n * * Gx, Gy are coordinates of Generator / base point\n */\nconst ed25519_CURVE = {\n p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,\n n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,\n h: 8n,\n a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,\n d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,\n Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,\n Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n,\n};\nconst { p: P, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE;\nconst L = 32; // field / group byte length\nconst L2 = 64;\n// Helpers and Precomputes sections are reused between libraries\n// ## Helpers\n// ----------\nconst captureTrace = (...args) => {\n if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(...args);\n }\n};\nconst err = (message = '') => {\n const e = new Error(message);\n captureTrace(e, err);\n throw e;\n};\nconst isBig = (n) => typeof n === 'bigint'; // is big integer\nconst isStr = (s) => typeof s === 'string'; // is string\nconst isBytes = (a) => a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n/** Asserts something is Uint8Array. */\nconst abytes = (value, length, title = '') => {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n err(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);\n }\n return value;\n};\n/** create Uint8Array */\nconst u8n = (len) => new Uint8Array(len);\nconst u8fr = (buf) => Uint8Array.from(buf);\nconst padh = (n, pad) => n.toString(16).padStart(pad, '0');\nconst bytesToHex = (b) => Array.from(abytes(b))\n .map((e) => padh(e, 2))\n .join('');\nconst C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; // ASCII characters\nconst _ch = (ch) => {\n if (ch >= C._0 && ch <= C._9)\n return ch - C._0; // '2' => 50-48\n if (ch >= C.A && ch <= C.F)\n return ch - (C.A - 10); // 'B' => 66-(65-10)\n if (ch >= C.a && ch <= C.f)\n return ch - (C.a - 10); // 'b' => 98-(97-10)\n return;\n};\nconst hexToBytes = (hex) => {\n const e = 'hex invalid';\n if (!isStr(hex))\n return err(e);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n return err(e);\n const array = u8n(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n // treat each char as ASCII\n const n1 = _ch(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = _ch(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined)\n return err(e);\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n};\nconst cr = () => globalThis?.crypto; // WebCrypto is available in all modern environments\nconst subtle = () => cr()?.subtle ?? err('crypto.subtle must be defined, consider polyfill');\n// prettier-ignore\nconst concatBytes = (...arrs) => {\n const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0)); // create u8a of summed length\n let pad = 0; // walk through each array,\n arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type\n return r;\n};\n/** WebCrypto OS-level CSPRNG (random number generator). Will throw when not available. */\nconst randomBytes = (len = L) => {\n const c = cr();\n return c.getRandomValues(u8n(len));\n};\nconst big = BigInt;\nconst assertRange = (n, min, max, msg = 'bad number: out of range') => (isBig(n) && min <= n && n < max ? n : err(msg));\n/** modular division */\nconst M = (a, b = P) => {\n const r = a % b;\n return r >= 0n ? r : b + r;\n};\nconst modN = (a) => M(a, N);\n/** Modular inversion using euclidean GCD (non-CT). No negative exponent for now. */\n// prettier-ignore\nconst invert = (num, md) => {\n if (num === 0n || md <= 0n)\n err('no inverse n=' + num + ' mod=' + md);\n let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;\n while (a !== 0n) {\n const q = b / a, r = b % a;\n const m = x - u * q, n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n return b === 1n ? M(x, md) : err('no inverse'); // b is gcd at this point\n};\nconst callHash = (name) => {\n // @ts-ignore\n const fn = hashes[name];\n if (typeof fn !== 'function')\n err('hashes.' + name + ' not set');\n return fn;\n};\nconst hash = (msg) => callHash('sha512')(msg);\nconst apoint = (p) => (p instanceof Point ? p : err('Point expected'));\n// ## End of Helpers\n// -----------------\nconst B256 = 2n ** 256n;\n/** Point in XYZT extended coordinates. */\nclass Point {\n static BASE;\n static ZERO;\n X;\n Y;\n Z;\n T;\n constructor(X, Y, Z, T) {\n const max = B256;\n this.X = assertRange(X, 0n, max);\n this.Y = assertRange(Y, 0n, max);\n this.Z = assertRange(Z, 1n, max);\n this.T = assertRange(T, 0n, max);\n Object.freeze(this);\n }\n static CURVE() {\n return ed25519_CURVE;\n }\n static fromAffine(p) {\n return new Point(p.x, p.y, 1n, M(p.x * p.y));\n }\n /** RFC8032 5.1.3: Uint8Array to Point. */\n static fromBytes(hex, zip215 = false) {\n const d = _d;\n // Copy array to not mess it up.\n const normed = u8fr(abytes(hex, L));\n // adjust first LE byte = last BE byte\n const lastByte = hex[31];\n normed[31] = lastByte & ~0x80;\n const y = bytesToNumLE(normed);\n // zip215=true: 0 <= y < 2^256\n // zip215=false, RFC8032: 0 <= y < 2^255-19\n const max = zip215 ? B256 : P;\n assertRange(y, 0n, max);\n const y2 = M(y * y); // y²\n const u = M(y2 - 1n); // u=y²-1\n const v = M(d * y2 + 1n); // v=dy²+1\n let { isValid, value: x } = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (!isValid)\n err('bad point: y not sqrt'); // not square root: bad point\n const isXOdd = (x & 1n) === 1n; // adjust sign of x coordinate\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === 0n && isLastByteOdd)\n err('bad point: x==0, isLastByteOdd'); // x=0, x_0=1\n if (isLastByteOdd !== isXOdd)\n x = M(-x);\n return new Point(x, y, 1n, M(x * y)); // Z=1, T=xy\n }\n static fromHex(hex, zip215) {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /** Checks if the point is valid and on-curve. */\n assertValidity() {\n const a = _a;\n const d = _d;\n const p = this;\n if (p.is0())\n return err('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = M(X * X); // X²\n const Y2 = M(Y * Y); // Y²\n const Z2 = M(Z * Z); // Z²\n const Z4 = M(Z2 * Z2); // Z⁴\n const aX2 = M(X2 * a); // aX²\n const left = M(Z2 * M(aX2 + Y2)); // (aX² + Y²)Z²\n const right = M(Z4 + M(d * M(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n return err('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = M(X * Y);\n const ZT = M(Z * T);\n if (XY !== ZT)\n return err('bad point: equation left != right (2)');\n return this;\n }\n /** Equality check: compare points P&Q. */\n equals(other) {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = apoint(other); // checks class equality\n const X1Z2 = M(X1 * Z2);\n const X2Z1 = M(X2 * Z1);\n const Y1Z2 = M(Y1 * Z2);\n const Y2Z1 = M(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(I);\n }\n /** Flip point over y coordinate. */\n negate() {\n return new Point(M(-this.X), this.Y, this.Z, M(-this.T));\n }\n /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */\n double() {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const a = _a;\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n const A = M(X1 * X1);\n const B = M(Y1 * Y1);\n const C = M(2n * M(Z1 * Z1));\n const D = M(a * A);\n const x1y1 = X1 + Y1;\n const E = M(M(x1y1 * x1y1) - A - B);\n const G = D + B;\n const F = G - C;\n const H = D - B;\n const X3 = M(E * F);\n const Y3 = M(G * H);\n const T3 = M(E * H);\n const Z3 = M(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n /** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */\n add(other) {\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other); // doesn't check if other on-curve\n const a = _a;\n const d = _d;\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3\n const A = M(X1 * X2);\n const B = M(Y1 * Y2);\n const C = M(T1 * d * T2);\n const D = M(Z1 * Z2);\n const E = M((X1 + Y1) * (X2 + Y2) - A - B);\n const F = M(D - C);\n const G = M(D + C);\n const H = M(B - a * A);\n const X3 = M(E * F);\n const Y3 = M(G * H);\n const T3 = M(E * H);\n const Z3 = M(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(apoint(other).negate());\n }\n /**\n * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.\n * Uses {@link wNAF} for base point.\n * Uses fake point to mitigate side-channel leakage.\n * @param n scalar by which point is multiplied\n * @param safe safe mode guards against timing attacks; unsafe mode is faster\n */\n multiply(n, safe = true) {\n if (!safe && (n === 0n || this.is0()))\n return I;\n assertRange(n, 1n, N);\n if (n === 1n)\n return this;\n if (this.equals(G))\n return wNAF(n).p;\n // init result point & fake point\n let p = I;\n let f = G;\n for (let d = this; n > 0n; d = d.double(), n >>= 1n) {\n // if bit is present, add to point\n // if not present, add to fake, for timing safety\n if (n & 1n)\n p = p.add(d);\n else if (safe)\n f = f.add(d);\n }\n return p;\n }\n multiplyUnsafe(scalar) {\n return this.multiply(scalar, false);\n }\n /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */\n toAffine() {\n const { X, Y, Z } = this;\n // fast-paths for ZERO point OR Z=1\n if (this.equals(I))\n return { x: 0n, y: 1n };\n const iz = invert(Z, P);\n // (Z * Z^-1) must be 1, otherwise bad math\n if (M(Z * iz) !== 1n)\n err('invalid inverse');\n // x = X*Z^-1; y = Y*Z^-1\n const x = M(X * iz);\n const y = M(Y * iz);\n return { x, y };\n }\n toBytes() {\n const { x, y } = this.assertValidity().toAffine();\n const b = numTo32bLE(y);\n // store sign in first LE byte\n b[31] |= x & 1n ? 0x80 : 0;\n return b;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n clearCofactor() {\n return this.multiply(big(h), false);\n }\n isSmallOrder() {\n return this.clearCofactor().is0();\n }\n isTorsionFree() {\n // Multiply by big number N. We can't `mul(N)` because of checks. Instead, we `mul(N/2)*2+1`\n let p = this.multiply(N / 2n, false).double();\n if (N % 2n)\n p = p.add(this);\n return p.is0();\n }\n}\n/** Generator / base point */\nconst G = new Point(Gx, Gy, 1n, M(Gx * Gy));\n/** Identity / zero point */\nconst I = new Point(0n, 1n, 1n, 0n);\n// Static aliases\nPoint.BASE = G;\nPoint.ZERO = I;\nconst numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), L2)).reverse();\nconst bytesToNumLE = (b) => big('0x' + bytesToHex(u8fr(abytes(b)).reverse()));\nconst pow2 = (x, power) => {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n};\n// prettier-ignore\nconst pow_2_252_3 = (x) => {\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n};\nconst RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n; // √-1\n// for sqrt comp\n// prettier-ignore\nconst uvRatio = (u, v) => {\n const v3 = M(v * v * v); // v³\n const v7 = M(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7).pow_p_5_8; // (uv⁷)^(p-5)/8\n let x = M(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = M(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = M(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === M(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === M(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if ((M(x) & 1n) === 1n)\n x = M(-x); // edIsNegative\n return { isValid: useRoot1 || useRoot2, value: x };\n};\n// N == L, just weird naming\nconst modL_LE = (hash) => modN(bytesToNumLE(hash)); // modulo L; but little-endian\n/** hashes.sha512 should conform to the interface. */\n// TODO: rename\nconst sha512a = (...m) => hashes.sha512Async(concatBytes(...m)); // Async SHA512\nconst sha512s = (...m) => callHash('sha512')(concatBytes(...m));\n// RFC8032 5.1.5\nconst hash2extK = (hashed) => {\n // slice creates a copy, unlike subarray\n const head = hashed.slice(0, L);\n head[0] &= 248; // Clamp bits: 0b1111_1000\n head[31] &= 127; // 0b0111_1111\n head[31] |= 64; // 0b0100_0000\n const prefix = hashed.slice(L, L2); // secret key \"prefix\"\n const scalar = modL_LE(head); // modular division over curve order\n const point = G.multiply(scalar); // public key point\n const pointBytes = point.toBytes(); // point serialized to Uint8Array\n return { head, prefix, scalar, point, pointBytes };\n};\n// RFC8032 5.1.5; getPublicKey async, sync. Hash priv key and extract point.\nconst getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);\nconst getExtendedPublicKey = (secretKey) => hash2extK(sha512s(abytes(secretKey, L)));\n/** Creates 32-byte ed25519 public key from 32-byte secret key. Async. */\nconst getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);\n/** Creates 32-byte ed25519 public key from 32-byte secret key. To use, set `hashes.sha512` first. */\nconst getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;\nconst hashFinishA = (res) => sha512a(res.hashable).then(res.finish);\nconst hashFinishS = (res) => res.finish(sha512s(res.hashable));\n// Code, shared between sync & async sign\nconst _sign = (e, rBytes, msg) => {\n const { pointBytes: P, scalar: s } = e;\n const r = modL_LE(rBytes); // r was created outside, reduce it modulo L\n const R = G.multiply(r).toBytes(); // R = [r]B\n const hashable = concatBytes(R, P, msg); // dom2(F, C) || R || A || PH(M)\n const finish = (hashed) => {\n // k = SHA512(dom2(F, C) || R || A || PH(M))\n const S = modN(r + modL_LE(hashed) * s); // S = (r + k * s) mod L; 0 <= s < l\n return abytes(concatBytes(R, numTo32bLE(S)), L2); // 64-byte sig: 32b R.x + 32b LE(S)\n };\n return { hashable, finish };\n};\n/**\n * Signs message using secret key. Async.\n * Follows RFC8032 5.1.6.\n */\nconst signAsync = async (message, secretKey) => {\n const m = abytes(message);\n const e = await getExtendedPublicKeyAsync(secretKey);\n const rBytes = await sha512a(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))\n return hashFinishA(_sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature\n};\n/**\n * Signs message using secret key. To use, set `hashes.sha512` first.\n * Follows RFC8032 5.1.6.\n */\nconst sign = (message, secretKey) => {\n const m = abytes(message);\n const e = getExtendedPublicKey(secretKey);\n const rBytes = sha512s(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))\n return hashFinishS(_sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature\n};\nconst defaultVerifyOpts = { zip215: true };\nconst _verify = (sig, msg, pub, opts = defaultVerifyOpts) => {\n sig = abytes(sig, L2); // Signature hex str/Bytes, must be 64 bytes\n msg = abytes(msg); // Message hex str/Bytes\n pub = abytes(pub, L);\n const { zip215 } = opts; // switch between zip215 and rfc8032 verif\n let A;\n let R;\n let s;\n let SB;\n let hashable = Uint8Array.of();\n try {\n A = Point.fromBytes(pub, zip215); // public key A decoded\n R = Point.fromBytes(sig.slice(0, L), zip215); // 0 <= R < 2^256: ZIP215 R can be >= P\n s = bytesToNumLE(sig.slice(L, L2)); // Decode second half as an integer S\n SB = G.multiply(s, false); // in the range 0 <= s < L\n hashable = concatBytes(R.toBytes(), A.toBytes(), msg); // dom2(F, C) || R || A || PH(M)\n }\n catch (error) { }\n const finish = (hashed) => {\n // k = SHA512(dom2(F, C) || R || A || PH(M))\n if (SB == null)\n return false; // false if try-catch catched an error\n if (!zip215 && A.isSmallOrder())\n return false; // false for SBS: Strongly Binding Signature\n const k = modL_LE(hashed); // decode in little-endian, modulo L\n const RkA = R.add(A.multiply(k, false)); // [8]R + [8][k]A'\n return RkA.add(SB.negate()).clearCofactor().is0(); // [8][S]B = [8]R + [8][k]A'\n };\n return { hashable, finish };\n};\n/** Verifies signature on message and public key. Async. Follows RFC8032 5.1.7. */\nconst verifyAsync = async (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishA(_verify(signature, message, publicKey, opts));\n/** Verifies signature on message and public key. To use, set `hashes.sha512` first. Follows RFC8032 5.1.7. */\nconst verify = (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishS(_verify(signature, message, publicKey, opts));\n/** Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves. */\nconst etc = {\n bytesToHex: bytesToHex,\n hexToBytes: hexToBytes,\n concatBytes: concatBytes,\n mod: M,\n invert: invert,\n randomBytes: randomBytes,\n};\nconst hashes = {\n sha512Async: async (message) => {\n const s = subtle();\n const m = concatBytes(message);\n return u8n(await s.digest('SHA-512', m.buffer));\n },\n sha512: undefined,\n};\n// FIPS 186 B.4.1 compliant key generation produces private keys\n// with modulo bias being neglible. takes >N+16 bytes, returns (hash mod n-1)+1\nconst randomSecretKey = (seed = randomBytes(L)) => seed;\nconst keygen = (seed) => {\n const secretKey = randomSecretKey(seed);\n const publicKey = getPublicKey(secretKey);\n return { secretKey, publicKey };\n};\nconst keygenAsync = async (seed) => {\n const secretKey = randomSecretKey(seed);\n const publicKey = await getPublicKeyAsync(secretKey);\n return { secretKey, publicKey };\n};\n/** ed25519-specific key utilities. */\nconst utils = {\n getExtendedPublicKeyAsync: getExtendedPublicKeyAsync,\n getExtendedPublicKey: getExtendedPublicKey,\n randomSecretKey: randomSecretKey,\n};\n// ## Precomputes\n// --------------\nconst W = 8; // W is window size\nconst scalarBits = 256;\nconst pwindows = Math.ceil(scalarBits / W) + 1; // 33 for W=8, NOT 32 - see wNAF loop\nconst pwindowSize = 2 ** (W - 1); // 128 for W=8\nconst precompute = () => {\n const points = [];\n let p = G;\n let b = p;\n for (let w = 0; w < pwindows; w++) {\n b = p;\n points.push(b);\n for (let i = 1; i < pwindowSize; i++) {\n b = b.add(p);\n points.push(b);\n } // i=1, bc we skip 0\n p = b.double();\n }\n return points;\n};\nlet Gpows = undefined; // precomputes for base point G\n// const-time negate\nconst ctneg = (cnd, p) => {\n const n = p.negate();\n return cnd ? n : p;\n};\n/**\n * Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by\n * caching multiples of G (base point). Cache is stored in 32MB of RAM.\n * Any time `G.multiply` is done, precomputes are used.\n * Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.\n *\n * w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,\n * but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.\n *\n * !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().\n */\nconst wNAF = (n) => {\n const comp = Gpows || (Gpows = precompute());\n let p = I;\n let f = G; // f must be G, or could become I in the end\n const pow_2_w = 2 ** W; // 256 for W=8\n const maxNum = pow_2_w; // 256 for W=8\n const mask = big(pow_2_w - 1); // 255 for W=8 == mask 0b11111111\n const shiftBy = big(W); // 8 for W=8\n for (let w = 0; w < pwindows; w++) {\n let wbits = Number(n & mask); // extract W bits.\n n >>= shiftBy; // shift number by W bits.\n // We use negative indexes to reduce size of precomputed table by 2x.\n // Instead of needing precomputes 0..256, we only calculate them for 0..128.\n // If an index > 128 is found, we do (256-index) - where 256 is next window.\n // Naive: index +127 => 127, +224 => 224\n // Optimized: index +127 => 127, +224 => 256-32\n if (wbits > pwindowSize) {\n wbits -= maxNum;\n n += 1n;\n }\n const off = w * pwindowSize;\n const offF = off; // offsets, evaluate both\n const offP = off + Math.abs(wbits) - 1;\n const isEven = w % 2 !== 0; // conditions, evaluate both\n const isNeg = wbits < 0;\n if (wbits === 0) {\n // off == I: can't add it. Adding random offF instead.\n f = f.add(ctneg(isEven, comp[offF])); // bits are 0: add garbage to fake point\n }\n else {\n p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point\n }\n }\n if (n !== 0n)\n err('invalid wnaf');\n return { p, f }; // return both real and fake points for JIT\n};\n// !! Remove the export to easily use in REPL / browser console\nexport { etc, getPublicKey, getPublicKeyAsync, hash, hashes, keygen, keygenAsync, Point, sign, signAsync, utils, verify, verifyAsync, };\n","import { getPublicKeyAsync, signAsync, utils } from \"@noble/ed25519\";\n\ntype StoredIdentity = {\n version: 1;\n deviceId: string;\n publicKey: string;\n privateKey: string;\n createdAtMs: number;\n};\n\nexport type DeviceIdentity = {\n deviceId: string;\n publicKey: string;\n privateKey: string;\n};\n\nconst STORAGE_KEY = \"clawdbot-device-identity-v1\";\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/g, \"\");\n}\n\nfunction base64UrlDecode(input: string): Uint8Array {\n const normalized = input.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n const padded = normalized + \"=\".repeat((4 - (normalized.length % 4)) % 4);\n const binary = atob(padded);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);\n return out;\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nasync function fingerprintPublicKey(publicKey: Uint8Array): Promise {\n const hash = await crypto.subtle.digest(\"SHA-256\", publicKey);\n return bytesToHex(new Uint8Array(hash));\n}\n\nasync function generateIdentity(): Promise {\n const privateKey = utils.randomSecretKey();\n const publicKey = await getPublicKeyAsync(privateKey);\n const deviceId = await fingerprintPublicKey(publicKey);\n return {\n deviceId,\n publicKey: base64UrlEncode(publicKey),\n privateKey: base64UrlEncode(privateKey),\n };\n}\n\nexport async function loadOrCreateDeviceIdentity(): Promise {\n try {\n const raw = localStorage.getItem(STORAGE_KEY);\n if (raw) {\n const parsed = JSON.parse(raw) as StoredIdentity;\n if (\n parsed?.version === 1 &&\n typeof parsed.deviceId === \"string\" &&\n typeof parsed.publicKey === \"string\" &&\n typeof parsed.privateKey === \"string\"\n ) {\n const derivedId = await fingerprintPublicKey(base64UrlDecode(parsed.publicKey));\n if (derivedId !== parsed.deviceId) {\n const updated: StoredIdentity = {\n ...parsed,\n deviceId: derivedId,\n };\n localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));\n return {\n deviceId: derivedId,\n publicKey: parsed.publicKey,\n privateKey: parsed.privateKey,\n };\n }\n return {\n deviceId: parsed.deviceId,\n publicKey: parsed.publicKey,\n privateKey: parsed.privateKey,\n };\n }\n }\n } catch {\n // fall through to regenerate\n }\n\n const identity = await generateIdentity();\n const stored: StoredIdentity = {\n version: 1,\n deviceId: identity.deviceId,\n publicKey: identity.publicKey,\n privateKey: identity.privateKey,\n createdAtMs: Date.now(),\n };\n localStorage.setItem(STORAGE_KEY, JSON.stringify(stored));\n return identity;\n}\n\nexport async function signDevicePayload(privateKeyBase64Url: string, payload: string) {\n const key = base64UrlDecode(privateKeyBase64Url);\n const data = new TextEncoder().encode(payload);\n const sig = await signAsync(data, key);\n return base64UrlEncode(sig);\n}\n","export type DeviceAuthEntry = {\n token: string;\n role: string;\n scopes: string[];\n updatedAtMs: number;\n};\n\ntype DeviceAuthStore = {\n version: 1;\n deviceId: string;\n tokens: Record;\n};\n\nconst STORAGE_KEY = \"clawdbot.device.auth.v1\";\n\nfunction normalizeRole(role: string): string {\n return role.trim();\n}\n\nfunction normalizeScopes(scopes: string[] | undefined): string[] {\n if (!Array.isArray(scopes)) return [];\n const out = new Set();\n for (const scope of scopes) {\n const trimmed = scope.trim();\n if (trimmed) out.add(trimmed);\n }\n return [...out].sort();\n}\n\nfunction readStore(): DeviceAuthStore | null {\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as DeviceAuthStore;\n if (!parsed || parsed.version !== 1) return null;\n if (!parsed.deviceId || typeof parsed.deviceId !== \"string\") return null;\n if (!parsed.tokens || typeof parsed.tokens !== \"object\") return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\nfunction writeStore(store: DeviceAuthStore) {\n try {\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(store));\n } catch {\n // best-effort\n }\n}\n\nexport function loadDeviceAuthToken(params: {\n deviceId: string;\n role: string;\n}): DeviceAuthEntry | null {\n const store = readStore();\n if (!store || store.deviceId !== params.deviceId) return null;\n const role = normalizeRole(params.role);\n const entry = store.tokens[role];\n if (!entry || typeof entry.token !== \"string\") return null;\n return entry;\n}\n\nexport function storeDeviceAuthToken(params: {\n deviceId: string;\n role: string;\n token: string;\n scopes?: string[];\n}): DeviceAuthEntry {\n const role = normalizeRole(params.role);\n const next: DeviceAuthStore = {\n version: 1,\n deviceId: params.deviceId,\n tokens: {},\n };\n const existing = readStore();\n if (existing && existing.deviceId === params.deviceId) {\n next.tokens = { ...existing.tokens };\n }\n const entry: DeviceAuthEntry = {\n token: params.token,\n role,\n scopes: normalizeScopes(params.scopes),\n updatedAtMs: Date.now(),\n };\n next.tokens[role] = entry;\n writeStore(next);\n return entry;\n}\n\nexport function clearDeviceAuthToken(params: { deviceId: string; role: string }) {\n const store = readStore();\n if (!store || store.deviceId !== params.deviceId) return;\n const role = normalizeRole(params.role);\n if (!store.tokens[role]) return;\n const next = { ...store, tokens: { ...store.tokens } };\n delete next.tokens[role];\n writeStore(next);\n}\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport { loadOrCreateDeviceIdentity } from \"../device-identity\";\nimport { clearDeviceAuthToken, storeDeviceAuthToken } from \"../device-auth\";\n\nexport type DeviceTokenSummary = {\n role: string;\n scopes?: string[];\n createdAtMs?: number;\n rotatedAtMs?: number;\n revokedAtMs?: number;\n lastUsedAtMs?: number;\n};\n\nexport type PendingDevice = {\n requestId: string;\n deviceId: string;\n displayName?: string;\n role?: string;\n remoteIp?: string;\n isRepair?: boolean;\n ts?: number;\n};\n\nexport type PairedDevice = {\n deviceId: string;\n displayName?: string;\n roles?: string[];\n scopes?: string[];\n remoteIp?: string;\n tokens?: DeviceTokenSummary[];\n createdAtMs?: number;\n approvedAtMs?: number;\n};\n\nexport type DevicePairingList = {\n pending: PendingDevice[];\n paired: PairedDevice[];\n};\n\nexport type DevicesState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n devicesLoading: boolean;\n devicesError: string | null;\n devicesList: DevicePairingList | null;\n};\n\nexport async function loadDevices(state: DevicesState, opts?: { quiet?: boolean }) {\n if (!state.client || !state.connected) return;\n if (state.devicesLoading) return;\n state.devicesLoading = true;\n if (!opts?.quiet) state.devicesError = null;\n try {\n const res = (await state.client.request(\"device.pair.list\", {})) as DevicePairingList | null;\n state.devicesList = {\n pending: Array.isArray(res?.pending) ? res!.pending : [],\n paired: Array.isArray(res?.paired) ? res!.paired : [],\n };\n } catch (err) {\n if (!opts?.quiet) state.devicesError = String(err);\n } finally {\n state.devicesLoading = false;\n }\n}\n\nexport async function approveDevicePairing(state: DevicesState, requestId: string) {\n if (!state.client || !state.connected) return;\n try {\n await state.client.request(\"device.pair.approve\", { requestId });\n await loadDevices(state);\n } catch (err) {\n state.devicesError = String(err);\n }\n}\n\nexport async function rejectDevicePairing(state: DevicesState, requestId: string) {\n if (!state.client || !state.connected) return;\n const confirmed = window.confirm(\"Reject this device pairing request?\");\n if (!confirmed) return;\n try {\n await state.client.request(\"device.pair.reject\", { requestId });\n await loadDevices(state);\n } catch (err) {\n state.devicesError = String(err);\n }\n}\n\nexport async function rotateDeviceToken(\n state: DevicesState,\n params: { deviceId: string; role: string; scopes?: string[] },\n) {\n if (!state.client || !state.connected) return;\n try {\n const res = (await state.client.request(\"device.token.rotate\", params)) as\n | { token?: string; role?: string; deviceId?: string; scopes?: string[] }\n | undefined;\n if (res?.token) {\n const identity = await loadOrCreateDeviceIdentity();\n const role = res.role ?? params.role;\n if (res.deviceId === identity.deviceId || params.deviceId === identity.deviceId) {\n storeDeviceAuthToken({\n deviceId: identity.deviceId,\n role,\n token: res.token,\n scopes: res.scopes ?? params.scopes ?? [],\n });\n }\n window.prompt(\"New device token (copy and store securely):\", res.token);\n }\n await loadDevices(state);\n } catch (err) {\n state.devicesError = String(err);\n }\n}\n\nexport async function revokeDeviceToken(\n state: DevicesState,\n params: { deviceId: string; role: string },\n) {\n if (!state.client || !state.connected) return;\n const confirmed = window.confirm(\n `Revoke token for ${params.deviceId} (${params.role})?`,\n );\n if (!confirmed) return;\n try {\n await state.client.request(\"device.token.revoke\", params);\n const identity = await loadOrCreateDeviceIdentity();\n if (params.deviceId === identity.deviceId) {\n clearDeviceAuthToken({ deviceId: identity.deviceId, role: params.role });\n }\n await loadDevices(state);\n } catch (err) {\n state.devicesError = String(err);\n }\n}\n","import type { GatewayBrowserClient } from \"../gateway\";\n\nexport type NodesState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n nodesLoading: boolean;\n nodes: Array>;\n lastError: string | null;\n};\n\nexport async function loadNodes(\n state: NodesState,\n opts?: { quiet?: boolean },\n) {\n if (!state.client || !state.connected) return;\n if (state.nodesLoading) return;\n state.nodesLoading = true;\n if (!opts?.quiet) state.lastError = null;\n try {\n const res = (await state.client.request(\"node.list\", {})) as {\n nodes?: Array>;\n };\n state.nodes = Array.isArray(res.nodes) ? res.nodes : [];\n } catch (err) {\n if (!opts?.quiet) state.lastError = String(err);\n } finally {\n state.nodesLoading = false;\n }\n}\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport { cloneConfigObject, removePathValue, setPathValue } from \"./config/form-utils\";\n\nexport type ExecApprovalsDefaults = {\n security?: string;\n ask?: string;\n askFallback?: string;\n autoAllowSkills?: boolean;\n};\n\nexport type ExecApprovalsAllowlistEntry = {\n id?: string;\n pattern: string;\n lastUsedAt?: number;\n lastUsedCommand?: string;\n lastResolvedPath?: string;\n};\n\nexport type ExecApprovalsAgent = ExecApprovalsDefaults & {\n allowlist?: ExecApprovalsAllowlistEntry[];\n};\n\nexport type ExecApprovalsFile = {\n version?: number;\n socket?: { path?: string };\n defaults?: ExecApprovalsDefaults;\n agents?: Record;\n};\n\nexport type ExecApprovalsSnapshot = {\n path: string;\n exists: boolean;\n hash: string;\n file: ExecApprovalsFile;\n};\n\nexport type ExecApprovalsTarget =\n | { kind: \"gateway\" }\n | { kind: \"node\"; nodeId: string };\n\nexport type ExecApprovalsState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n execApprovalsLoading: boolean;\n execApprovalsSaving: boolean;\n execApprovalsDirty: boolean;\n execApprovalsSnapshot: ExecApprovalsSnapshot | null;\n execApprovalsForm: ExecApprovalsFile | null;\n execApprovalsSelectedAgent: string | null;\n lastError: string | null;\n};\n\nfunction resolveExecApprovalsRpc(target?: ExecApprovalsTarget | null): {\n method: string;\n params: Record;\n} | null {\n if (!target || target.kind === \"gateway\") {\n return { method: \"exec.approvals.get\", params: {} };\n }\n const nodeId = target.nodeId.trim();\n if (!nodeId) return null;\n return { method: \"exec.approvals.node.get\", params: { nodeId } };\n}\n\nfunction resolveExecApprovalsSaveRpc(\n target: ExecApprovalsTarget | null | undefined,\n params: { file: ExecApprovalsFile; baseHash: string },\n): { method: string; params: Record } | null {\n if (!target || target.kind === \"gateway\") {\n return { method: \"exec.approvals.set\", params };\n }\n const nodeId = target.nodeId.trim();\n if (!nodeId) return null;\n return { method: \"exec.approvals.node.set\", params: { ...params, nodeId } };\n}\n\nexport async function loadExecApprovals(\n state: ExecApprovalsState,\n target?: ExecApprovalsTarget | null,\n) {\n if (!state.client || !state.connected) return;\n if (state.execApprovalsLoading) return;\n state.execApprovalsLoading = true;\n state.lastError = null;\n try {\n const rpc = resolveExecApprovalsRpc(target);\n if (!rpc) {\n state.lastError = \"Select a node before loading exec approvals.\";\n return;\n }\n const res = (await state.client.request(rpc.method, rpc.params)) as ExecApprovalsSnapshot;\n applyExecApprovalsSnapshot(state, res);\n } catch (err) {\n state.lastError = String(err);\n } finally {\n state.execApprovalsLoading = false;\n }\n}\n\nexport function applyExecApprovalsSnapshot(\n state: ExecApprovalsState,\n snapshot: ExecApprovalsSnapshot,\n) {\n state.execApprovalsSnapshot = snapshot;\n if (!state.execApprovalsDirty) {\n state.execApprovalsForm = cloneConfigObject(snapshot.file ?? {});\n }\n}\n\nexport async function saveExecApprovals(\n state: ExecApprovalsState,\n target?: ExecApprovalsTarget | null,\n) {\n if (!state.client || !state.connected) return;\n state.execApprovalsSaving = true;\n state.lastError = null;\n try {\n const baseHash = state.execApprovalsSnapshot?.hash;\n if (!baseHash) {\n state.lastError = \"Exec approvals hash missing; reload and retry.\";\n return;\n }\n const file =\n state.execApprovalsForm ??\n state.execApprovalsSnapshot?.file ??\n {};\n const rpc = resolveExecApprovalsSaveRpc(target, { file, baseHash });\n if (!rpc) {\n state.lastError = \"Select a node before saving exec approvals.\";\n return;\n }\n await state.client.request(rpc.method, rpc.params);\n state.execApprovalsDirty = false;\n await loadExecApprovals(state, target);\n } catch (err) {\n state.lastError = String(err);\n } finally {\n state.execApprovalsSaving = false;\n }\n}\n\nexport function updateExecApprovalsFormValue(\n state: ExecApprovalsState,\n path: Array,\n value: unknown,\n) {\n const base = cloneConfigObject(\n state.execApprovalsForm ?? state.execApprovalsSnapshot?.file ?? {},\n );\n setPathValue(base, path, value);\n state.execApprovalsForm = base;\n state.execApprovalsDirty = true;\n}\n\nexport function removeExecApprovalsFormValue(\n state: ExecApprovalsState,\n path: Array,\n) {\n const base = cloneConfigObject(\n state.execApprovalsForm ?? state.execApprovalsSnapshot?.file ?? {},\n );\n removePathValue(base, path);\n state.execApprovalsForm = base;\n state.execApprovalsDirty = true;\n}\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport type { PresenceEntry } from \"../types\";\n\nexport type PresenceState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n presenceLoading: boolean;\n presenceEntries: PresenceEntry[];\n presenceError: string | null;\n presenceStatus: string | null;\n};\n\nexport async function loadPresence(state: PresenceState) {\n if (!state.client || !state.connected) return;\n if (state.presenceLoading) return;\n state.presenceLoading = true;\n state.presenceError = null;\n state.presenceStatus = null;\n try {\n const res = (await state.client.request(\"system-presence\", {})) as\n | PresenceEntry[]\n | undefined;\n if (Array.isArray(res)) {\n state.presenceEntries = res;\n state.presenceStatus = res.length === 0 ? \"No instances yet.\" : null;\n } else {\n state.presenceEntries = [];\n state.presenceStatus = \"No presence payload.\";\n }\n } catch (err) {\n state.presenceError = String(err);\n } finally {\n state.presenceLoading = false;\n }\n}\n\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport type { SkillStatusReport } from \"../types\";\n\nexport type SkillsState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n skillsLoading: boolean;\n skillsReport: SkillStatusReport | null;\n skillsError: string | null;\n skillsBusyKey: string | null;\n skillEdits: Record;\n skillMessages: SkillMessageMap;\n};\n\nexport type SkillMessage = {\n kind: \"success\" | \"error\";\n message: string;\n};\n\nexport type SkillMessageMap = Record;\n\ntype LoadSkillsOptions = {\n clearMessages?: boolean;\n};\n\nfunction setSkillMessage(state: SkillsState, key: string, message?: SkillMessage) {\n if (!key.trim()) return;\n const next = { ...state.skillMessages };\n if (message) next[key] = message;\n else delete next[key];\n state.skillMessages = next;\n}\n\nfunction getErrorMessage(err: unknown) {\n if (err instanceof Error) return err.message;\n return String(err);\n}\n\nexport async function loadSkills(state: SkillsState, options?: LoadSkillsOptions) {\n if (options?.clearMessages && Object.keys(state.skillMessages).length > 0) {\n state.skillMessages = {};\n }\n if (!state.client || !state.connected) return;\n if (state.skillsLoading) return;\n state.skillsLoading = true;\n state.skillsError = null;\n try {\n const res = (await state.client.request(\"skills.status\", {})) as\n | SkillStatusReport\n | undefined;\n if (res) state.skillsReport = res;\n } catch (err) {\n state.skillsError = getErrorMessage(err);\n } finally {\n state.skillsLoading = false;\n }\n}\n\nexport function updateSkillEdit(\n state: SkillsState,\n skillKey: string,\n value: string,\n) {\n state.skillEdits = { ...state.skillEdits, [skillKey]: value };\n}\n\nexport async function updateSkillEnabled(\n state: SkillsState,\n skillKey: string,\n enabled: boolean,\n) {\n if (!state.client || !state.connected) return;\n state.skillsBusyKey = skillKey;\n state.skillsError = null;\n try {\n await state.client.request(\"skills.update\", { skillKey, enabled });\n await loadSkills(state);\n setSkillMessage(state, skillKey, {\n kind: \"success\",\n message: enabled ? \"Skill enabled\" : \"Skill disabled\",\n });\n } catch (err) {\n const message = getErrorMessage(err);\n state.skillsError = message;\n setSkillMessage(state, skillKey, {\n kind: \"error\",\n message,\n });\n } finally {\n state.skillsBusyKey = null;\n }\n}\n\nexport async function saveSkillApiKey(state: SkillsState, skillKey: string) {\n if (!state.client || !state.connected) return;\n state.skillsBusyKey = skillKey;\n state.skillsError = null;\n try {\n const apiKey = state.skillEdits[skillKey] ?? \"\";\n await state.client.request(\"skills.update\", { skillKey, apiKey });\n await loadSkills(state);\n setSkillMessage(state, skillKey, {\n kind: \"success\",\n message: \"API key saved\",\n });\n } catch (err) {\n const message = getErrorMessage(err);\n state.skillsError = message;\n setSkillMessage(state, skillKey, {\n kind: \"error\",\n message,\n });\n } finally {\n state.skillsBusyKey = null;\n }\n}\n\nexport async function installSkill(\n state: SkillsState,\n skillKey: string,\n name: string,\n installId: string,\n) {\n if (!state.client || !state.connected) return;\n state.skillsBusyKey = skillKey;\n state.skillsError = null;\n try {\n const result = (await state.client.request(\"skills.install\", {\n name,\n installId,\n timeoutMs: 120000,\n })) as { ok?: boolean; message?: string };\n await loadSkills(state);\n setSkillMessage(state, skillKey, {\n kind: \"success\",\n message: result?.message ?? \"Installed\",\n });\n } catch (err) {\n const message = getErrorMessage(err);\n state.skillsError = message;\n setSkillMessage(state, skillKey, {\n kind: \"error\",\n message,\n });\n } finally {\n state.skillsBusyKey = null;\n }\n}\n","export type ThemeMode = \"system\" | \"light\" | \"dark\";\nexport type ResolvedTheme = \"light\" | \"dark\";\n\nexport function getSystemTheme(): ResolvedTheme {\n if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") {\n return \"dark\";\n }\n return window.matchMedia(\"(prefers-color-scheme: dark)\").matches\n ? \"dark\"\n : \"light\";\n}\n\nexport function resolveTheme(mode: ThemeMode): ResolvedTheme {\n if (mode === \"system\") return getSystemTheme();\n return mode;\n}\n","import type { ThemeMode } from \"./theme\";\n\nexport type ThemeTransitionContext = {\n element?: HTMLElement | null;\n pointerClientX?: number;\n pointerClientY?: number;\n};\n\nexport type ThemeTransitionOptions = {\n nextTheme: ThemeMode;\n applyTheme: () => void;\n context?: ThemeTransitionContext;\n currentTheme?: ThemeMode | null;\n};\n\ntype DocumentWithViewTransition = Document & {\n startViewTransition?: (callback: () => void) => { finished: Promise };\n};\n\nconst clamp01 = (value: number) => {\n if (Number.isNaN(value)) return 0.5;\n if (value <= 0) return 0;\n if (value >= 1) return 1;\n return value;\n};\n\nconst hasReducedMotionPreference = () => {\n if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") {\n return false;\n }\n return window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches ?? false;\n};\n\nconst cleanupThemeTransition = (root: HTMLElement) => {\n root.classList.remove(\"theme-transition\");\n root.style.removeProperty(\"--theme-switch-x\");\n root.style.removeProperty(\"--theme-switch-y\");\n};\n\nexport const startThemeTransition = ({\n nextTheme,\n applyTheme,\n context,\n currentTheme,\n}: ThemeTransitionOptions) => {\n if (currentTheme === nextTheme) return;\n\n const documentReference = globalThis.document ?? null;\n if (!documentReference) {\n applyTheme();\n return;\n }\n\n const root = documentReference.documentElement;\n const document_ = documentReference as DocumentWithViewTransition;\n const prefersReducedMotion = hasReducedMotionPreference();\n\n const canUseViewTransition =\n Boolean(document_.startViewTransition) && !prefersReducedMotion;\n\n if (canUseViewTransition) {\n let xPercent = 0.5;\n let yPercent = 0.5;\n\n if (\n context?.pointerClientX !== undefined &&\n context?.pointerClientY !== undefined &&\n typeof window !== \"undefined\"\n ) {\n xPercent = clamp01(context.pointerClientX / window.innerWidth);\n yPercent = clamp01(context.pointerClientY / window.innerHeight);\n } else if (context?.element) {\n const rect = context.element.getBoundingClientRect();\n if (\n rect.width > 0 &&\n rect.height > 0 &&\n typeof window !== \"undefined\"\n ) {\n xPercent = clamp01((rect.left + rect.width / 2) / window.innerWidth);\n yPercent = clamp01((rect.top + rect.height / 2) / window.innerHeight);\n }\n }\n\n root.style.setProperty(\"--theme-switch-x\", `${xPercent * 100}%`);\n root.style.setProperty(\"--theme-switch-y\", `${yPercent * 100}%`);\n root.classList.add(\"theme-transition\");\n\n try {\n const transition = document_.startViewTransition?.(() => {\n applyTheme();\n });\n if (transition?.finished) {\n void transition.finished.finally(() => cleanupThemeTransition(root));\n } else {\n cleanupThemeTransition(root);\n }\n } catch {\n cleanupThemeTransition(root);\n applyTheme();\n }\n return;\n }\n\n applyTheme();\n cleanupThemeTransition(root);\n};\n","import { loadLogs } from \"./controllers/logs\";\nimport { loadNodes } from \"./controllers/nodes\";\nimport { loadDebug } from \"./controllers/debug\";\nimport type { ClawdbotApp } from \"./app\";\n\ntype PollingHost = {\n nodesPollInterval: number | null;\n logsPollInterval: number | null;\n debugPollInterval: number | null;\n tab: string;\n};\n\nexport function startNodesPolling(host: PollingHost) {\n if (host.nodesPollInterval != null) return;\n host.nodesPollInterval = window.setInterval(\n () => void loadNodes(host as unknown as ClawdbotApp, { quiet: true }),\n 5000,\n );\n}\n\nexport function stopNodesPolling(host: PollingHost) {\n if (host.nodesPollInterval == null) return;\n clearInterval(host.nodesPollInterval);\n host.nodesPollInterval = null;\n}\n\nexport function startLogsPolling(host: PollingHost) {\n if (host.logsPollInterval != null) return;\n host.logsPollInterval = window.setInterval(() => {\n if (host.tab !== \"logs\") return;\n void loadLogs(host as unknown as ClawdbotApp, { quiet: true });\n }, 2000);\n}\n\nexport function stopLogsPolling(host: PollingHost) {\n if (host.logsPollInterval == null) return;\n clearInterval(host.logsPollInterval);\n host.logsPollInterval = null;\n}\n\nexport function startDebugPolling(host: PollingHost) {\n if (host.debugPollInterval != null) return;\n host.debugPollInterval = window.setInterval(() => {\n if (host.tab !== \"debug\") return;\n void loadDebug(host as unknown as ClawdbotApp);\n }, 3000);\n}\n\nexport function stopDebugPolling(host: PollingHost) {\n if (host.debugPollInterval == null) return;\n clearInterval(host.debugPollInterval);\n host.debugPollInterval = null;\n}\n","import { loadConfig, loadConfigSchema } from \"./controllers/config\";\nimport { loadCronJobs, loadCronStatus } from \"./controllers/cron\";\nimport { loadChannels } from \"./controllers/channels\";\nimport { loadDebug } from \"./controllers/debug\";\nimport { loadLogs } from \"./controllers/logs\";\nimport { loadDevices } from \"./controllers/devices\";\nimport { loadNodes } from \"./controllers/nodes\";\nimport { loadExecApprovals } from \"./controllers/exec-approvals\";\nimport { loadPresence } from \"./controllers/presence\";\nimport { loadSessions } from \"./controllers/sessions\";\nimport { loadSkills } from \"./controllers/skills\";\nimport { inferBasePathFromPathname, normalizeBasePath, normalizePath, pathForTab, tabFromPath, type Tab } from \"./navigation\";\nimport { saveSettings, type UiSettings } from \"./storage\";\nimport { resolveTheme, type ResolvedTheme, type ThemeMode } from \"./theme\";\nimport { startThemeTransition, type ThemeTransitionContext } from \"./theme-transition\";\nimport { scheduleChatScroll, scheduleLogsScroll } from \"./app-scroll\";\nimport { startLogsPolling, stopLogsPolling, startDebugPolling, stopDebugPolling } from \"./app-polling\";\nimport { refreshChat } from \"./app-chat\";\nimport type { ClawdbotApp } from \"./app\";\n\ntype SettingsHost = {\n settings: UiSettings;\n theme: ThemeMode;\n themeResolved: ResolvedTheme;\n applySessionKey: string;\n sessionKey: string;\n tab: Tab;\n connected: boolean;\n chatHasAutoScrolled: boolean;\n logsAtBottom: boolean;\n eventLog: unknown[];\n eventLogBuffer: unknown[];\n basePath: string;\n themeMedia: MediaQueryList | null;\n themeMediaHandler: ((event: MediaQueryListEvent) => void) | null;\n};\n\nexport function applySettings(host: SettingsHost, next: UiSettings) {\n const normalized = {\n ...next,\n lastActiveSessionKey: next.lastActiveSessionKey?.trim() || next.sessionKey.trim() || \"main\",\n };\n host.settings = normalized;\n saveSettings(normalized);\n if (next.theme !== host.theme) {\n host.theme = next.theme;\n applyResolvedTheme(host, resolveTheme(next.theme));\n }\n host.applySessionKey = host.settings.lastActiveSessionKey;\n}\n\nexport function setLastActiveSessionKey(host: SettingsHost, next: string) {\n const trimmed = next.trim();\n if (!trimmed) return;\n if (host.settings.lastActiveSessionKey === trimmed) return;\n applySettings(host, { ...host.settings, lastActiveSessionKey: trimmed });\n}\n\nexport function applySettingsFromUrl(host: SettingsHost) {\n if (!window.location.search) return;\n const params = new URLSearchParams(window.location.search);\n const tokenRaw = params.get(\"token\");\n const passwordRaw = params.get(\"password\");\n const sessionRaw = params.get(\"session\");\n const gatewayUrlRaw = params.get(\"gatewayUrl\");\n let shouldCleanUrl = false;\n\n if (tokenRaw != null) {\n const token = tokenRaw.trim();\n if (token && token !== host.settings.token) {\n applySettings(host, { ...host.settings, token });\n }\n params.delete(\"token\");\n shouldCleanUrl = true;\n }\n\n if (passwordRaw != null) {\n const password = passwordRaw.trim();\n if (password) {\n (host as { password: string }).password = password;\n }\n params.delete(\"password\");\n shouldCleanUrl = true;\n }\n\n if (sessionRaw != null) {\n const session = sessionRaw.trim();\n if (session) {\n host.sessionKey = session;\n applySettings(host, {\n ...host.settings,\n sessionKey: session,\n lastActiveSessionKey: session,\n });\n }\n }\n\n if (gatewayUrlRaw != null) {\n const gatewayUrl = gatewayUrlRaw.trim();\n if (gatewayUrl && gatewayUrl !== host.settings.gatewayUrl) {\n applySettings(host, { ...host.settings, gatewayUrl });\n }\n params.delete(\"gatewayUrl\");\n shouldCleanUrl = true;\n }\n\n if (!shouldCleanUrl) return;\n const url = new URL(window.location.href);\n url.search = params.toString();\n window.history.replaceState({}, \"\", url.toString());\n}\n\nexport function setTab(host: SettingsHost, next: Tab) {\n if (host.tab !== next) host.tab = next;\n if (next === \"chat\") host.chatHasAutoScrolled = false;\n if (next === \"logs\")\n startLogsPolling(host as unknown as Parameters[0]);\n else stopLogsPolling(host as unknown as Parameters[0]);\n if (next === \"debug\")\n startDebugPolling(host as unknown as Parameters[0]);\n else stopDebugPolling(host as unknown as Parameters[0]);\n void refreshActiveTab(host);\n syncUrlWithTab(host, next, false);\n}\n\nexport function setTheme(\n host: SettingsHost,\n next: ThemeMode,\n context?: ThemeTransitionContext,\n) {\n const applyTheme = () => {\n host.theme = next;\n applySettings(host, { ...host.settings, theme: next });\n applyResolvedTheme(host, resolveTheme(next));\n };\n startThemeTransition({\n nextTheme: next,\n applyTheme,\n context,\n currentTheme: host.theme,\n });\n}\n\nexport async function refreshActiveTab(host: SettingsHost) {\n if (host.tab === \"overview\") await loadOverview(host);\n if (host.tab === \"channels\") await loadChannelsTab(host);\n if (host.tab === \"instances\") await loadPresence(host as unknown as ClawdbotApp);\n if (host.tab === \"sessions\") await loadSessions(host as unknown as ClawdbotApp);\n if (host.tab === \"cron\") await loadCron(host);\n if (host.tab === \"skills\") await loadSkills(host as unknown as ClawdbotApp);\n if (host.tab === \"nodes\") {\n await loadNodes(host as unknown as ClawdbotApp);\n await loadDevices(host as unknown as ClawdbotApp);\n await loadConfig(host as unknown as ClawdbotApp);\n await loadExecApprovals(host as unknown as ClawdbotApp);\n }\n if (host.tab === \"chat\") {\n await refreshChat(host as unknown as Parameters[0]);\n scheduleChatScroll(\n host as unknown as Parameters[0],\n !host.chatHasAutoScrolled,\n );\n }\n if (host.tab === \"config\") {\n await loadConfigSchema(host as unknown as ClawdbotApp);\n await loadConfig(host as unknown as ClawdbotApp);\n }\n if (host.tab === \"debug\") {\n await loadDebug(host as unknown as ClawdbotApp);\n host.eventLog = host.eventLogBuffer;\n }\n if (host.tab === \"logs\") {\n host.logsAtBottom = true;\n await loadLogs(host as unknown as ClawdbotApp, { reset: true });\n scheduleLogsScroll(\n host as unknown as Parameters[0],\n true,\n );\n }\n}\n\nexport function inferBasePath() {\n if (typeof window === \"undefined\") return \"\";\n const configured = window.__CLAWDBOT_CONTROL_UI_BASE_PATH__;\n if (typeof configured === \"string\" && configured.trim()) {\n return normalizeBasePath(configured);\n }\n return inferBasePathFromPathname(window.location.pathname);\n}\n\nexport function syncThemeWithSettings(host: SettingsHost) {\n host.theme = host.settings.theme ?? \"system\";\n applyResolvedTheme(host, resolveTheme(host.theme));\n}\n\nexport function applyResolvedTheme(host: SettingsHost, resolved: ResolvedTheme) {\n host.themeResolved = resolved;\n if (typeof document === \"undefined\") return;\n const root = document.documentElement;\n root.dataset.theme = resolved;\n root.style.colorScheme = resolved;\n}\n\nexport function attachThemeListener(host: SettingsHost) {\n if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") return;\n host.themeMedia = window.matchMedia(\"(prefers-color-scheme: dark)\");\n host.themeMediaHandler = (event) => {\n if (host.theme !== \"system\") return;\n applyResolvedTheme(host, event.matches ? \"dark\" : \"light\");\n };\n if (typeof host.themeMedia.addEventListener === \"function\") {\n host.themeMedia.addEventListener(\"change\", host.themeMediaHandler);\n return;\n }\n const legacy = host.themeMedia as MediaQueryList & {\n addListener: (cb: (event: MediaQueryListEvent) => void) => void;\n };\n legacy.addListener(host.themeMediaHandler);\n}\n\nexport function detachThemeListener(host: SettingsHost) {\n if (!host.themeMedia || !host.themeMediaHandler) return;\n if (typeof host.themeMedia.removeEventListener === \"function\") {\n host.themeMedia.removeEventListener(\"change\", host.themeMediaHandler);\n return;\n }\n const legacy = host.themeMedia as MediaQueryList & {\n removeListener: (cb: (event: MediaQueryListEvent) => void) => void;\n };\n legacy.removeListener(host.themeMediaHandler);\n host.themeMedia = null;\n host.themeMediaHandler = null;\n}\n\nexport function syncTabWithLocation(host: SettingsHost, replace: boolean) {\n if (typeof window === \"undefined\") return;\n const resolved = tabFromPath(window.location.pathname, host.basePath) ?? \"chat\";\n setTabFromRoute(host, resolved);\n syncUrlWithTab(host, resolved, replace);\n}\n\nexport function onPopState(host: SettingsHost) {\n if (typeof window === \"undefined\") return;\n const resolved = tabFromPath(window.location.pathname, host.basePath);\n if (!resolved) return;\n\n const url = new URL(window.location.href);\n const session = url.searchParams.get(\"session\")?.trim();\n if (session) {\n host.sessionKey = session;\n applySettings(host, {\n ...host.settings,\n sessionKey: session,\n lastActiveSessionKey: session,\n });\n }\n\n setTabFromRoute(host, resolved);\n}\n\nexport function setTabFromRoute(host: SettingsHost, next: Tab) {\n if (host.tab !== next) host.tab = next;\n if (next === \"chat\") host.chatHasAutoScrolled = false;\n if (next === \"logs\")\n startLogsPolling(host as unknown as Parameters[0]);\n else stopLogsPolling(host as unknown as Parameters[0]);\n if (next === \"debug\")\n startDebugPolling(host as unknown as Parameters[0]);\n else stopDebugPolling(host as unknown as Parameters[0]);\n if (host.connected) void refreshActiveTab(host);\n}\n\nexport function syncUrlWithTab(host: SettingsHost, tab: Tab, replace: boolean) {\n if (typeof window === \"undefined\") return;\n const targetPath = normalizePath(pathForTab(tab, host.basePath));\n const currentPath = normalizePath(window.location.pathname);\n const url = new URL(window.location.href);\n\n if (tab === \"chat\" && host.sessionKey) {\n url.searchParams.set(\"session\", host.sessionKey);\n } else {\n url.searchParams.delete(\"session\");\n }\n\n if (currentPath !== targetPath) {\n url.pathname = targetPath;\n }\n\n if (replace) {\n window.history.replaceState({}, \"\", url.toString());\n } else {\n window.history.pushState({}, \"\", url.toString());\n }\n}\n\nexport function syncUrlWithSessionKey(\n host: SettingsHost,\n sessionKey: string,\n replace: boolean,\n) {\n if (typeof window === \"undefined\") return;\n const url = new URL(window.location.href);\n url.searchParams.set(\"session\", sessionKey);\n if (replace) window.history.replaceState({}, \"\", url.toString());\n else window.history.pushState({}, \"\", url.toString());\n}\n\nexport async function loadOverview(host: SettingsHost) {\n await Promise.all([\n loadChannels(host as unknown as ClawdbotApp, false),\n loadPresence(host as unknown as ClawdbotApp),\n loadSessions(host as unknown as ClawdbotApp),\n loadCronStatus(host as unknown as ClawdbotApp),\n loadDebug(host as unknown as ClawdbotApp),\n ]);\n}\n\nexport async function loadChannelsTab(host: SettingsHost) {\n await Promise.all([\n loadChannels(host as unknown as ClawdbotApp, true),\n loadConfigSchema(host as unknown as ClawdbotApp),\n loadConfig(host as unknown as ClawdbotApp),\n ]);\n}\n\nexport async function loadCron(host: SettingsHost) {\n await Promise.all([\n loadChannels(host as unknown as ClawdbotApp, false),\n loadCronStatus(host as unknown as ClawdbotApp),\n loadCronJobs(host as unknown as ClawdbotApp),\n ]);\n}\n","import { abortChatRun, loadChatHistory, sendChatMessage } from \"./controllers/chat\";\nimport { loadSessions } from \"./controllers/sessions\";\nimport { generateUUID } from \"./uuid\";\nimport { resetToolStream } from \"./app-tool-stream\";\nimport { scheduleChatScroll } from \"./app-scroll\";\nimport { setLastActiveSessionKey } from \"./app-settings\";\nimport { normalizeBasePath } from \"./navigation\";\nimport type { GatewayHelloOk } from \"./gateway\";\nimport { parseAgentSessionKey } from \"../../../src/sessions/session-key-utils.js\";\nimport type { ClawdbotApp } from \"./app\";\n\ntype ChatHost = {\n connected: boolean;\n chatMessage: string;\n chatQueue: Array<{ id: string; text: string; createdAt: number }>;\n chatRunId: string | null;\n chatSending: boolean;\n sessionKey: string;\n basePath: string;\n hello: GatewayHelloOk | null;\n chatAvatarUrl: string | null;\n};\n\nexport function isChatBusy(host: ChatHost) {\n return host.chatSending || Boolean(host.chatRunId);\n}\n\nexport function isChatStopCommand(text: string) {\n const trimmed = text.trim();\n if (!trimmed) return false;\n const normalized = trimmed.toLowerCase();\n if (normalized === \"/stop\") return true;\n return (\n normalized === \"stop\" ||\n normalized === \"esc\" ||\n normalized === \"abort\" ||\n normalized === \"wait\" ||\n normalized === \"exit\"\n );\n}\n\nexport async function handleAbortChat(host: ChatHost) {\n if (!host.connected) return;\n host.chatMessage = \"\";\n await abortChatRun(host as unknown as ClawdbotApp);\n}\n\nfunction enqueueChatMessage(host: ChatHost, text: string) {\n const trimmed = text.trim();\n if (!trimmed) return;\n host.chatQueue = [\n ...host.chatQueue,\n {\n id: generateUUID(),\n text: trimmed,\n createdAt: Date.now(),\n },\n ];\n}\n\nasync function sendChatMessageNow(\n host: ChatHost,\n message: string,\n opts?: { previousDraft?: string; restoreDraft?: boolean },\n) {\n resetToolStream(host as unknown as Parameters[0]);\n const ok = await sendChatMessage(host as unknown as ClawdbotApp, message);\n if (!ok && opts?.previousDraft != null) {\n host.chatMessage = opts.previousDraft;\n }\n if (ok) {\n setLastActiveSessionKey(host as unknown as Parameters[0], host.sessionKey);\n }\n if (ok && opts?.restoreDraft && opts.previousDraft?.trim()) {\n host.chatMessage = opts.previousDraft;\n }\n scheduleChatScroll(host as unknown as Parameters[0]);\n if (ok && !host.chatRunId) {\n void flushChatQueue(host);\n }\n return ok;\n}\n\nasync function flushChatQueue(host: ChatHost) {\n if (!host.connected || isChatBusy(host)) return;\n const [next, ...rest] = host.chatQueue;\n if (!next) return;\n host.chatQueue = rest;\n const ok = await sendChatMessageNow(host, next.text);\n if (!ok) {\n host.chatQueue = [next, ...host.chatQueue];\n }\n}\n\nexport function removeQueuedMessage(host: ChatHost, id: string) {\n host.chatQueue = host.chatQueue.filter((item) => item.id !== id);\n}\n\nexport async function handleSendChat(\n host: ChatHost,\n messageOverride?: string,\n opts?: { restoreDraft?: boolean },\n) {\n if (!host.connected) return;\n const previousDraft = host.chatMessage;\n const message = (messageOverride ?? host.chatMessage).trim();\n if (!message) return;\n\n if (isChatStopCommand(message)) {\n await handleAbortChat(host);\n return;\n }\n\n if (messageOverride == null) {\n host.chatMessage = \"\";\n }\n\n if (isChatBusy(host)) {\n enqueueChatMessage(host, message);\n return;\n }\n\n await sendChatMessageNow(host, message, {\n previousDraft: messageOverride == null ? previousDraft : undefined,\n restoreDraft: Boolean(messageOverride && opts?.restoreDraft),\n });\n}\n\nexport async function refreshChat(host: ChatHost) {\n await Promise.all([\n loadChatHistory(host as unknown as ClawdbotApp),\n loadSessions(host as unknown as ClawdbotApp),\n refreshChatAvatar(host),\n ]);\n scheduleChatScroll(host as unknown as Parameters[0], true);\n}\n\nexport const flushChatQueueForEvent = flushChatQueue;\n\ntype SessionDefaultsSnapshot = {\n defaultAgentId?: string;\n};\n\nfunction resolveAgentIdForSession(host: ChatHost): string | null {\n const parsed = parseAgentSessionKey(host.sessionKey);\n if (parsed?.agentId) return parsed.agentId;\n const snapshot = host.hello?.snapshot as { sessionDefaults?: SessionDefaultsSnapshot } | undefined;\n const fallback = snapshot?.sessionDefaults?.defaultAgentId?.trim();\n return fallback || \"main\";\n}\n\nfunction buildAvatarMetaUrl(basePath: string, agentId: string): string {\n const base = normalizeBasePath(basePath);\n const encoded = encodeURIComponent(agentId);\n return base ? `${base}/avatar/${encoded}?meta=1` : `/avatar/${encoded}?meta=1`;\n}\n\nexport async function refreshChatAvatar(host: ChatHost) {\n if (!host.connected) {\n host.chatAvatarUrl = null;\n return;\n }\n const agentId = resolveAgentIdForSession(host);\n if (!agentId) {\n host.chatAvatarUrl = null;\n return;\n }\n host.chatAvatarUrl = null;\n const url = buildAvatarMetaUrl(host.basePath, agentId);\n try {\n const res = await fetch(url, { method: \"GET\" });\n if (!res.ok) {\n host.chatAvatarUrl = null;\n return;\n }\n const data = (await res.json()) as { avatarUrl?: unknown };\n const avatarUrl = typeof data.avatarUrl === \"string\" ? data.avatarUrl.trim() : \"\";\n host.chatAvatarUrl = avatarUrl || null;\n } catch {\n host.chatAvatarUrl = null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},e=t=>(...e)=>({_$litDirective$:t,values:e});class i{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}export{i as Directive,t as PartType,e as directive};\n//# sourceMappingURL=directive.js.map\n","import{_$LH as o}from\"./lit-html.js\";\n/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const{I:t}=o,i=o=>o,n=o=>null===o||\"object\"!=typeof o&&\"function\"!=typeof o,e={HTML:1,SVG:2,MATHML:3},l=(o,t)=>void 0===t?void 0!==o?._$litType$:o?._$litType$===t,d=o=>null!=o?._$litType$?.h,c=o=>void 0!==o?._$litDirective$,f=o=>o?._$litDirective$,r=o=>void 0===o.strings,s=()=>document.createComment(\"\"),v=(o,n,e)=>{const l=o._$AA.parentNode,d=void 0===n?o._$AB:n._$AA;if(void 0===e){const i=l.insertBefore(s(),d),n=l.insertBefore(s(),d);e=new t(i,n,o,o.options)}else{const t=e._$AB.nextSibling,n=e._$AM,c=n!==o;if(c){let t;e._$AQ?.(o),e._$AM=o,void 0!==e._$AP&&(t=o._$AU)!==n._$AU&&e._$AP(t)}if(t!==d||c){let o=e._$AA;for(;o!==t;){const t=i(o).nextSibling;i(l).insertBefore(o,d),o=t}}}return e},u=(o,t,i=o)=>(o._$AI(t,i),o),m={},p=(o,t=m)=>o._$AH=t,M=o=>o._$AH,h=o=>{o._$AR(),o._$AA.remove()},j=o=>{o._$AR()};export{e as TemplateResultType,j as clearPart,M as getCommittedValue,f as getDirectiveClass,v as insertPart,d as isCompiledTemplateResult,c as isDirectiveResult,n as isPrimitive,r as isSingleExpression,l as isTemplateResult,h as removePart,u as setChildPartValue,p as setCommittedValue};\n//# sourceMappingURL=directive-helpers.js.map\n","import{noChange as e}from\"../lit-html.js\";import{directive as s,Directive as t,PartType as r}from\"../directive.js\";import{getCommittedValue as l,setChildPartValue as o,insertPart as i,removePart as n,setCommittedValue as f}from\"../directive-helpers.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst u=(e,s,t)=>{const r=new Map;for(let l=s;l<=t;l++)r.set(e[l],l);return r},c=s(class extends t{constructor(e){if(super(e),e.type!==r.CHILD)throw Error(\"repeat() can only be used in text expressions\")}dt(e,s,t){let r;void 0===t?t=s:void 0!==s&&(r=s);const l=[],o=[];let i=0;for(const s of e)l[i]=r?r(s,i):i,o[i]=t(s,i),i++;return{values:o,keys:l}}render(e,s,t){return this.dt(e,s,t).values}update(s,[t,r,c]){const d=l(s),{values:p,keys:a}=this.dt(t,r,c);if(!Array.isArray(d))return this.ut=a,p;const h=this.ut??=[],v=[];let m,y,x=0,j=d.length-1,k=0,w=p.length-1;for(;x<=j&&k<=w;)if(null===d[x])x++;else if(null===d[j])j--;else if(h[x]===a[k])v[k]=o(d[x],p[k]),x++,k++;else if(h[j]===a[w])v[w]=o(d[j],p[w]),j--,w--;else if(h[x]===a[w])v[w]=o(d[x],p[w]),i(s,v[w+1],d[x]),x++,w--;else if(h[j]===a[k])v[k]=o(d[j],p[k]),i(s,d[x],d[j]),j--,k++;else if(void 0===m&&(m=u(a,k,w),y=u(h,x,j)),m.has(h[x]))if(m.has(h[j])){const e=y.get(a[k]),t=void 0!==e?d[e]:null;if(null===t){const e=i(s,d[x]);o(e,p[k]),v[k]=e}else v[k]=o(t,p[k]),i(s,d[x],t),d[e]=null;k++}else n(d[j]),j--;else n(d[x]),x++;for(;k<=w;){const e=i(s,v[w+1]);o(e,p[k]),v[k++]=e}for(;x<=j;){const e=d[x++];null!==e&&n(e)}return this.ut=a,f(s,v),e}});export{c as repeat};\n//# sourceMappingURL=repeat.js.map\n","/**\n * Message normalization utilities for chat rendering.\n */\n\nimport type {\n NormalizedMessage,\n MessageContentItem,\n} from \"../types/chat-types\";\n\n/**\n * Normalize a raw message object into a consistent structure.\n */\nexport function normalizeMessage(message: unknown): NormalizedMessage {\n const m = message as Record;\n let role = typeof m.role === \"string\" ? m.role : \"unknown\";\n\n // Detect tool messages by common gateway shapes.\n // Some tool events come through as assistant role with tool_* items in the content array.\n const hasToolId =\n typeof m.toolCallId === \"string\" || typeof m.tool_call_id === \"string\";\n\n const contentRaw = m.content;\n const contentItems = Array.isArray(contentRaw) ? contentRaw : null;\n const hasToolContent =\n Array.isArray(contentItems) &&\n contentItems.some((item) => {\n const x = item as Record;\n const t = String(x.type ?? \"\").toLowerCase();\n return t === \"toolresult\" || t === \"tool_result\";\n });\n\n const hasToolName =\n typeof (m as Record).toolName === \"string\" ||\n typeof (m as Record).tool_name === \"string\";\n\n if (hasToolId || hasToolContent || hasToolName) {\n role = \"toolResult\";\n }\n\n // Extract content\n let content: MessageContentItem[] = [];\n\n if (typeof m.content === \"string\") {\n content = [{ type: \"text\", text: m.content }];\n } else if (Array.isArray(m.content)) {\n content = m.content.map((item: Record) => ({\n type: (item.type as MessageContentItem[\"type\"]) || \"text\",\n text: item.text as string | undefined,\n name: item.name as string | undefined,\n args: item.args || item.arguments,\n }));\n } else if (typeof m.text === \"string\") {\n content = [{ type: \"text\", text: m.text }];\n }\n\n const timestamp = typeof m.timestamp === \"number\" ? m.timestamp : Date.now();\n const id = typeof m.id === \"string\" ? m.id : undefined;\n\n return { role, content, timestamp, id };\n}\n\n/**\n * Normalize role for grouping purposes.\n */\nexport function normalizeRoleForGrouping(role: string): string {\n const lower = role.toLowerCase();\n // Preserve original casing when it's already a core role.\n if (role === \"user\" || role === \"User\") return role;\n if (role === \"assistant\") return \"assistant\";\n if (role === \"system\") return \"system\";\n // Keep tool-related roles distinct so the UI can style/toggle them.\n if (\n lower === \"toolresult\" ||\n lower === \"tool_result\" ||\n lower === \"tool\" ||\n lower === \"function\"\n ) {\n return \"tool\";\n }\n return role;\n}\n\n/**\n * Check if a message is a tool result message based on its role.\n */\nexport function isToolResultMessage(message: unknown): boolean {\n const m = message as Record;\n const role = typeof m.role === \"string\" ? m.role.toLowerCase() : \"\";\n return role === \"toolresult\" || role === \"tool_result\";\n}\n","import{nothing as t,noChange as i}from\"../lit-html.js\";import{directive as r,Directive as s,PartType as n}from\"../directive.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */class e extends s{constructor(i){if(super(i),this.it=t,i.type!==n.CHILD)throw Error(this.constructor.directiveName+\"() can only be used in child bindings\")}render(r){if(r===t||null==r)return this._t=void 0,this.it=r;if(r===i)return r;if(\"string\"!=typeof r)throw Error(this.constructor.directiveName+\"() called with a non-string value\");if(r===this.it)return this._t;this.it=r;const s=[r];return s.raw=s,this._t={_$litType$:this.constructor.resultType,strings:s,values:[]}}}e.directiveName=\"unsafeHTML\",e.resultType=1;const o=r(e);export{e as UnsafeHTMLDirective,o as unsafeHTML};\n//# sourceMappingURL=unsafe-html.js.map\n","/*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */\n\nconst {\n entries,\n setPrototypeOf,\n isFrozen,\n getPrototypeOf,\n getOwnPropertyDescriptor\n} = Object;\nlet {\n freeze,\n seal,\n create\n} = Object; // eslint-disable-line import/no-mutable-exports\nlet {\n apply,\n construct\n} = typeof Reflect !== 'undefined' && Reflect;\nif (!freeze) {\n freeze = function freeze(x) {\n return x;\n };\n}\nif (!seal) {\n seal = function seal(x) {\n return x;\n };\n}\nif (!apply) {\n apply = function apply(func, thisArg) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n return func.apply(thisArg, args);\n };\n}\nif (!construct) {\n construct = function construct(Func) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n return new Func(...args);\n };\n}\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySplice = unapply(Array.prototype.splice);\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst regExpTest = unapply(RegExp.prototype.test);\nconst typeErrorCreate = unconstruct(TypeError);\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply(func) {\n return function (thisArg) {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n args[_key3 - 1] = arguments[_key3];\n }\n return apply(func, thisArg, args);\n };\n}\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct(Func) {\n return function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n return construct(Func, args);\n };\n}\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(set, array) {\n let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n array[l] = lcElement;\n }\n element = lcElement;\n }\n }\n set[element] = true;\n }\n return set;\n}\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray(array) {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n return array;\n}\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone(object) {\n const newObject = create(null);\n for (const [property, value] of entries(object)) {\n const isPropertyExist = objectHasOwnProperty(object, property);\n if (isPropertyExist) {\n if (Array.isArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (value && typeof value === 'object' && value.constructor === Object) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n return newObject;\n}\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter(object, prop) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n object = getPrototypeOf(object);\n }\n function fallbackValue() {\n return null;\n }\n return fallbackValue;\n}\n\nconst html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);\nconst svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);\nconst svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nconst svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);\nconst mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nconst mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);\nconst text = freeze(['#text']);\n\nconst html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);\nconst svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);\nconst mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);\nconst xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);\n\n// eslint-disable-next-line unicorn/better-regex\nconst MUSTACHE_EXPR = seal(/\\{\\{[\\w\\W]*|[\\w\\W]*\\}\\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode\nconst ERB_EXPR = seal(/<%[\\w\\W]*|[\\w\\W]*%>/gm);\nconst TMPLIT_EXPR = seal(/\\$\\{[\\w\\W]*/gm); // eslint-disable-line unicorn/better-regex\nconst DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nconst ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nconst IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nconst IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nconst ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nconst DOCTYPE_NAME = seal(/^html$/i);\nconst CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n\nvar EXPRESSIONS = /*#__PURE__*/Object.freeze({\n __proto__: null,\n ARIA_ATTR: ARIA_ATTR,\n ATTR_WHITESPACE: ATTR_WHITESPACE,\n CUSTOM_ELEMENT: CUSTOM_ELEMENT,\n DATA_ATTR: DATA_ATTR,\n DOCTYPE_NAME: DOCTYPE_NAME,\n ERB_EXPR: ERB_EXPR,\n IS_ALLOWED_URI: IS_ALLOWED_URI,\n IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,\n MUSTACHE_EXPR: MUSTACHE_EXPR,\n TMPLIT_EXPR: TMPLIT_EXPR\n});\n\n/* eslint-disable @typescript-eslint/indent */\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5,\n // Deprecated\n entityNode: 6,\n // Deprecated\n progressingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12 // Deprecated\n};\nconst getGlobal = function getGlobal() {\n return typeof window === 'undefined' ? null : window;\n};\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {\n if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {\n return null;\n }\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n }\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn('TrustedTypes policy ' + policyName + ' could not be created.');\n return null;\n }\n};\nconst _createHooksMap = function _createHooksMap() {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: []\n };\n};\nfunction createDOMPurify() {\n let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();\n const DOMPurify = root => createDOMPurify(root);\n DOMPurify.version = '3.3.1';\n DOMPurify.removed = [];\n if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n return DOMPurify;\n }\n let {\n document\n } = window;\n const originalDocument = document;\n const currentScript = originalDocument.currentScript;\n const {\n DocumentFragment,\n HTMLTemplateElement,\n Node,\n Element,\n NodeFilter,\n NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,\n HTMLFormElement,\n DOMParser,\n trustedTypes\n } = window;\n const ElementPrototype = Element.prototype;\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n let trustedTypesPolicy;\n let emptyHTML = '';\n const {\n implementation,\n createNodeIterator,\n createDocumentFragment,\n getElementsByTagName\n } = document;\n const {\n importNode\n } = originalDocument;\n let hooks = _createHooksMap();\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;\n const {\n MUSTACHE_EXPR,\n ERB_EXPR,\n TMPLIT_EXPR,\n DATA_ATTR,\n ARIA_ATTR,\n IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE,\n CUSTOM_ELEMENT\n } = EXPRESSIONS;\n let {\n IS_ALLOWED_URI: IS_ALLOWED_URI$1\n } = EXPRESSIONS;\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false\n }\n }));\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {\n tagCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n }\n }));\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n /* Decide if document with ... should be returned */\n let WHOLE_DOCUMENT = false;\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES = {};\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);\n let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc = null;\n /* Keep a reference to config to pass to hooks */\n let CONFIG = null;\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n const formElement = document.createElement('form');\n const isRegexOrFunction = function isRegexOrFunction(testValue) {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function _parseConfig() {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;\n /* Set configuration parameters */\n ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;\n ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;\n ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;\n URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;\n DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;\n FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;\n FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});\n FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;\n NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;\n MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;\n HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;\n CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};\n if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;\n }\n if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;\n }\n if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;\n }\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, text);\n ALLOWED_ATTR = [];\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, html$1);\n addToSet(ALLOWED_ATTR, html);\n }\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, svg$1);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, svgFilters);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, mathMl$1);\n addToSet(ALLOWED_ATTR, mathMl);\n addToSet(ALLOWED_ATTR, xml);\n }\n }\n /* Merge configuration parameters */\n if (cfg.ADD_TAGS) {\n if (typeof cfg.ADD_TAGS === 'function') {\n EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n } else {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n }\n if (cfg.ADD_ATTR) {\n if (typeof cfg.ADD_ATTR === 'function') {\n EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n } else {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n }\n if (cfg.ADD_URI_SAFE_ATTR) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n if (cfg.FORBID_CONTENTS) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n if (cfg.ADD_FORBID_CONTENTS) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);\n }\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.');\n }\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.');\n }\n // Overwrite existing TrustedTypes policy.\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n // Sign local variables required by `sanitize`.\n emptyHTML = trustedTypesPolicy.createHTML('');\n } else {\n // Uninitialized policy, attempt to initialize the internal dompurify policy.\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);\n }\n // If creating the internal policy succeeded sign internal variables.\n if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {\n emptyHTML = trustedTypesPolicy.createHTML('');\n }\n }\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n CONFIG = cfg;\n };\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);\n const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function _checkValidNamespace(element) {\n let parent = getParentNode(element);\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template'\n };\n }\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n if (element.namespaceURI === SVG_NAMESPACE) {\n // The only way to switch from HTML namespace to SVG\n // is via . If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n // The only way to switch from MathML to SVG is via`\n // svg if parent is either or MathML\n // text integration points.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);\n }\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n }\n if (element.namespaceURI === MATHML_NAMESPACE) {\n // The only way to switch from HTML namespace to MathML\n // is via . If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n // The only way to switch from SVG to MathML is via\n // and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n }\n if (element.namespaceURI === HTML_NAMESPACE) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);\n }\n // For XHTML and XML documents that support custom namespaces\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {\n return true;\n }\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function _forceRemove(node) {\n arrayPush(DOMPurify.removed, {\n element: node\n });\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n remove(node);\n }\n };\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function _removeAttribute(name, element) {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element\n });\n }\n element.removeAttribute(name);\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function _initDocument(dirty) {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n if (FORCE_BODY) {\n dirty = '' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty = '' + dirty + '';\n }\n const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n const body = doc.body || doc.documentElement;\n if (dirty && leadingWhitespace) {\n body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);\n }\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];\n }\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function _createNodeIterator(root) {\n return createNodeIterator.call(root.ownerDocument || root, root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);\n };\n /**\n * _isClobbered\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function _isClobbered(element) {\n return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');\n };\n /**\n * Checks whether the given object is a DOM node.\n *\n * @param value object to check whether it's a DOM node\n * @return true is object is a DOM node\n */\n const _isNode = function _isNode(value) {\n return typeof Node === 'function' && value instanceof Node;\n };\n function _executeHooks(hooks, currentNode, data) {\n arrayForEach(hooks, hook => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n const _sanitizeElements = function _sanitizeElements(currentNode) {\n let content = null;\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(currentNode.nodeName);\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS\n });\n /* Detect mXSS attempts abusing namespace confusion */\n if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\\w!]/g, currentNode.textContent)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove any kind of possibly harmful comments */\n if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\\w]/g, currentNode.data)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove element if anything forbids its presence */\n if (!(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {\n return false;\n }\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {\n return false;\n }\n }\n /* Keep content except for bad-listed elements */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode) || currentNode.parentNode;\n const childNodes = getChildNodes(currentNode) || currentNode.childNodes;\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n for (let i = childCount - 1; i >= 0; --i) {\n const childClone = cloneNode(childNodes[i], true);\n childClone.__removalCount = (currentNode.__removalCount || 0) + 1;\n parentNode.insertBefore(childClone, getNextSibling(currentNode));\n }\n }\n }\n _forceRemove(currentNode);\n return true;\n }\n /* Check whether element has a valid namespace */\n if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\\/no(script|embed|frames)/i, currentNode.innerHTML)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n content = currentNode.textContent;\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {\n content = stringReplace(content, expr, ' ');\n });\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, {\n element: currentNode.cloneNode()\n });\n currentNode.textContent = content;\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n return false;\n };\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {\n /* Make sure attribute cannot clobber */\n if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {\n return false;\n }\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {\n return false;\n } else ;\n return true;\n };\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function _isBasicCustomElement(tagName) {\n return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);\n };\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n const {\n attributes\n } = currentNode;\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined\n };\n let l = attributes.length;\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const {\n name,\n namespaceURI,\n value: attrValue\n } = attr;\n const lcName = transformCaseFunc(name);\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n /* Work around a security issue with comments inside attributes */\n if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\\/(style|title|textarea)/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Make sure we cannot easily use animated hrefs, even if animations are allowed */\n if (lcName === 'attributename' && stringMatch(value, 'href')) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Did the hooks approve of the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\\/>/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {\n value = stringReplace(value, expr, ' ');\n });\n }\n /* Is `value` valid for this attribute? */\n const lcTag = transformCaseFunc(currentNode.nodeName);\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Handle attributes that require Trusted Types */\n if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {\n if (namespaceURI) ; else {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML':\n {\n value = trustedTypesPolicy.createHTML(value);\n break;\n }\n case 'TrustedScriptURL':\n {\n value = trustedTypesPolicy.createScriptURL(value);\n break;\n }\n }\n }\n }\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {\n _removeAttribute(name, currentNode);\n }\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n while (shadowNode = shadowIterator.nextNode()) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode);\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n /* Deep shadow DOM detected */\n if (shadowNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(shadowNode.content);\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty) {\n let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '';\n }\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n if (typeof dirty.toString === 'function') {\n dirty = dirty.toString();\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n } else {\n throw typeErrorCreate('toString is not a function');\n }\n }\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n /* Assign config vars */\n if (!SET_CONFIG) {\n _parseConfig(cfg);\n }\n /* Clean up removed elements */\n DOMPurify.removed = [];\n /* Check if dirty is correctly typed for IN_PLACE */\n if (typeof dirty === 'string') {\n IN_PLACE = false;\n }\n if (IN_PLACE) {\n /* Do some early pre-sanitization to avoid unsafe root nodes */\n if (dirty.nodeName) {\n const tagName = transformCaseFunc(dirty.nodeName);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');\n }\n }\n } else if (dirty instanceof Node) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n } else {\n /* Exit directly if we have nothing to do */\n if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;\n }\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n /* Get node iterator */\n const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);\n /* Now start iterating over the created document */\n while (currentNode = nodeIterator.nextNode()) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode);\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n /* Shadow DOM detected, sanitize it */\n if (currentNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(currentNode.content);\n }\n }\n /* If we sanitized `dirty` in-place, return it. */\n if (IN_PLACE) {\n return dirty;\n }\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n return returnNode;\n }\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n /* Serialize doctype if allowed */\n if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {\n serializedHTML = '\\n' + serializedHTML;\n }\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {\n serializedHTML = stringReplace(serializedHTML, expr, ' ');\n });\n }\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;\n };\n DOMPurify.setConfig = function () {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n _parseConfig(cfg);\n SET_CONFIG = true;\n };\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n };\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n DOMPurify.addHook = function (entryPoint, hookFunction) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n arrayPush(hooks[entryPoint], hookFunction);\n };\n DOMPurify.removeHook = function (entryPoint, hookFunction) {\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n return arrayPop(hooks[entryPoint]);\n };\n DOMPurify.removeHooks = function (entryPoint) {\n hooks[entryPoint] = [];\n };\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n return DOMPurify;\n}\nvar purify = createDOMPurify();\n\nexport { purify as default };\n//# sourceMappingURL=purify.es.mjs.map\n","/**\n * marked v17.0.1 - a markdown parser\n * Copyright (c) 2018-2025, MarkedJS. (MIT License)\n * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License)\n * https://github.com/markedjs/marked\n */\n\n/**\n * DO NOT EDIT THIS FILE\n * The code in this file is generated from files in ./src/\n */\n\nfunction L(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=L();function Z(u){T=u}var C={exec:()=>null};function k(u,e=\"\"){let t=typeof u==\"string\"?u:u.source,n={replace:(r,i)=>{let s=typeof i==\"string\"?i:i.source;return s=s.replace(m.caret,\"$1\"),t=t.replace(r,s),n},getRegex:()=>new RegExp(t,e)};return n}var me=(()=>{try{return!!new RegExp(\"(?<=1)(?/,blockquoteSetextReplace:/\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \\t]?/gm,listReplaceTabs:/^\\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\\[[ xX]\\] +\\S/,listReplaceTask:/^\\[[ xX]\\] +/,listTaskCheckbox:/\\[[ xX]\\]/,anyLine:/\\n.*\\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\\||\\| *$/g,tableRowBlankLine:/\\n[ \\t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\\s|>)/i,endPreScriptTag:/^<\\/(pre|code|kbd|script)(\\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,unicodeAlphaNumeric:/[\\p{L}\\p{N}]/u,escapeTest:/[&<>\"']/,escapeReplace:/[&<>\"']/g,escapeTestNoEncode:/[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,escapeReplaceNoEncode:/[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,unescapeTest:/&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig,caret:/(^|[^\\[])\\^/g,percentDecode:/%25/g,findPipe:/\\|/g,splitPipe:/ \\|/,slashPipe:/\\\\\\|/g,carriageReturn:/\\r\\n|\\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\\S*/,endingNewline:/\\n$/,listItemRegex:u=>new RegExp(`^( {0,3}${u})((?:[\t ][^\\\\n]*)?(?:\\\\n|$))`),nextBulletRegex:u=>new RegExp(`^ {0,${Math.min(3,u-1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \t][^\\\\n]*)?(?:\\\\n|$))`),hrRegex:u=>new RegExp(`^ {0,${Math.min(3,u-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),fencesBeginRegex:u=>new RegExp(`^ {0,${Math.min(3,u-1)}}(?:\\`\\`\\`|~~~)`),headingBeginRegex:u=>new RegExp(`^ {0,${Math.min(3,u-1)}}#`),htmlBeginRegex:u=>new RegExp(`^ {0,${Math.min(3,u-1)}}<(?:[a-z].*>|!--)`,\"i\")},xe=/^(?:[ \\t]*(?:\\n|$))+/,be=/^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/,Re=/^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/,I=/^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/,Te=/^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/,N=/(?:[*+-]|\\d{1,9}[.)])/,re=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,se=k(re).replace(/bull/g,N).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/\\|table/g,\"\").getRegex(),Oe=k(re).replace(/bull/g,N).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/table/g,/ {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/).getRegex(),Q=/^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/,we=/^[^\\n]+/,F=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/,ye=k(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/).replace(\"label\",F).replace(\"title\",/(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/).getRegex(),Pe=k(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/).replace(/bull/g,N).getRegex(),v=\"address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul\",j=/|$))/,Se=k(\"^ {0,3}(?:<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:[^\\\\n]*\\\\n+|$)|comment[^\\\\n]*(\\\\n+|$)|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)|\\\\n*|$)|\\\\n*|$)|)[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$))\",\"i\").replace(\"comment\",j).replace(\"tag\",v).replace(\"attribute\",/ +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/).getRegex(),ie=k(Q).replace(\"hr\",I).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\",\"\").replace(\"|table\",\"\").replace(\"blockquote\",\" {0,3}>\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\",\" {0,3}(?:[*+-]|1[.)]) \").replace(\"html\",\")|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",v).getRegex(),$e=k(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/).replace(\"paragraph\",ie).getRegex(),U={blockquote:$e,code:be,def:ye,fences:Re,heading:Te,hr:I,html:Se,lheading:se,list:Pe,newline:xe,paragraph:ie,table:C,text:we},te=k(\"^ *([^\\\\n ].*)\\\\n {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)\").replace(\"hr\",I).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"blockquote\",\" {0,3}>\").replace(\"code\",\"(?: {4}| {0,3}\t)[^\\\\n]\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\",\" {0,3}(?:[*+-]|1[.)]) \").replace(\"html\",\")|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",v).getRegex(),_e={...U,lheading:Oe,table:te,paragraph:k(Q).replace(\"hr\",I).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\",\"\").replace(\"table\",te).replace(\"blockquote\",\" {0,3}>\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\",\" {0,3}(?:[*+-]|1[.)]) \").replace(\"html\",\")|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",v).getRegex()},Le={...U,html:k(`^ *(?:comment *(?:\\\\n|\\\\s*$)|<(tag)[\\\\s\\\\S]+? *(?:\\\\n{2,}|\\\\s*$)|\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))`).replace(\"comment\",j).replace(/tag/g,\"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b\").getRegex(),def:/^ *\\[([^\\]]+)\\]: *]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,heading:/^(#{1,6})(.*)(?:\\n+|$)/,fences:C,lheading:/^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,paragraph:k(Q).replace(\"hr\",I).replace(\"heading\",` *#{1,6} *[^\n]`).replace(\"lheading\",se).replace(\"|table\",\"\").replace(\"blockquote\",\" {0,3}>\").replace(\"|fences\",\"\").replace(\"|list\",\"\").replace(\"|html\",\"\").replace(\"|tag\",\"\").getRegex()},Me=/^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/,ze=/^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/,oe=/^( {2,}|\\\\)\\n(?!\\s*$)/,Ae=/^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\`+)[^`]+\\k(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/).replace(\"precode-\",me?\"(?`+)[^`]+\\k(?!`)/).replace(\"html\",/<(?! )[^<>]*?>/).getRegex(),ue=/^(?:\\*+(?:((?!\\*)punct)|[^\\s*]))|^_+(?:((?!_)punct)|([^\\s_]))/,qe=k(ue,\"u\").replace(/punct/g,D).getRegex(),ve=k(ue,\"u\").replace(/punct/g,le).getRegex(),pe=\"^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)\",De=k(pe,\"gu\").replace(/notPunctSpace/g,ae).replace(/punctSpace/g,K).replace(/punct/g,D).getRegex(),He=k(pe,\"gu\").replace(/notPunctSpace/g,Ee).replace(/punctSpace/g,Ie).replace(/punct/g,le).getRegex(),Ze=k(\"^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)\",\"gu\").replace(/notPunctSpace/g,ae).replace(/punctSpace/g,K).replace(/punct/g,D).getRegex(),Ge=k(/\\\\(punct)/,\"gu\").replace(/punct/g,D).getRegex(),Ne=k(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/).replace(\"scheme\",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(\"email\",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Qe=k(j).replace(\"(?:-->|$)\",\"-->\").getRegex(),Fe=k(\"^comment|^|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>|^<\\\\?[\\\\s\\\\S]*?\\\\?>|^|^\").replace(\"comment\",Qe).replace(\"attribute\",/\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/).getRegex(),q=/(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+[^`]*?`+(?!`)|[^\\[\\]\\\\`])*?/,je=k(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]*(?:\\n[ \\t]*)?)(title))?\\s*\\)/).replace(\"label\",q).replace(\"href\",/<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/).replace(\"title\",/\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex(),ce=k(/^!?\\[(label)\\]\\[(ref)\\]/).replace(\"label\",q).replace(\"ref\",F).getRegex(),he=k(/^!?\\[(ref)\\](?:\\[\\])?/).replace(\"ref\",F).getRegex(),Ue=k(\"reflink|nolink(?!\\\\()\",\"g\").replace(\"reflink\",ce).replace(\"nolink\",he).getRegex(),ne=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,W={_backpedal:C,anyPunctuation:Ge,autolink:Ne,blockSkip:Be,br:oe,code:ze,del:C,emStrongLDelim:qe,emStrongRDelimAst:De,emStrongRDelimUnd:Ze,escape:Me,link:je,nolink:he,punctuation:Ce,reflink:ce,reflinkSearch:Ue,tag:Fe,text:Ae,url:C},Ke={...W,link:k(/^!?\\[(label)\\]\\((.*?)\\)/).replace(\"label\",q).getRegex(),reflink:k(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace(\"label\",q).getRegex()},G={...W,emStrongRDelimAst:He,emStrongLDelim:ve,url:k(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace(\"protocol\",ne).replace(\"email\",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,del:/^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,text:k(/^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\\":\">\",'\"':\""\",\"'\":\"'\"},ke=u=>Xe[u];function w(u,e){if(e){if(m.escapeTest.test(u))return u.replace(m.escapeReplace,ke)}else if(m.escapeTestNoEncode.test(u))return u.replace(m.escapeReplaceNoEncode,ke);return u}function X(u){try{u=encodeURI(u).replace(m.percentDecode,\"%\")}catch{return null}return u}function J(u,e){let t=u.replace(m.findPipe,(i,s,a)=>{let o=!1,l=s;for(;--l>=0&&a[l]===\"\\\\\";)o=!o;return o?\"|\":\" |\"}),n=t.split(m.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length0?-2:-1}function ge(u,e,t,n,r){let i=e.href,s=e.title||null,a=u[1].replace(r.other.outputLinkReplace,\"$1\");n.state.inLink=!0;let o={type:u[0].charAt(0)===\"!\"?\"image\":\"link\",raw:t,href:i,title:s,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,o}function Je(u,e,t){let n=u.match(t.other.indentCodeCompensation);if(n===null)return e;let r=n[1];return e.split(`\n`).map(i=>{let s=i.match(t.other.beginningSpace);if(s===null)return i;let[a]=s;return a.length>=r.length?i.slice(r.length):i}).join(`\n`)}var y=class{options;rules;lexer;constructor(e){this.options=e||T}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:\"space\",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,\"\");return{type:\"code\",raw:t[0],codeBlockStyle:\"indented\",text:this.options.pedantic?n:z(n,`\n`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=Je(n,t[3]||\"\",this.rules);return{type:\"code\",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,\"$1\"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=z(n,\"#\");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:\"heading\",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:\"hr\",raw:z(t[0],`\n`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=z(t[0],`\n`).split(`\n`),r=\"\",i=\"\",s=[];for(;n.length>0;){let a=!1,o=[],l;for(l=0;l1,i={type:\"list\",raw:\"\",ordered:r,start:r?+n.slice(0,-1):\"\",loose:!1,items:[]};n=r?`\\\\d{1,9}\\\\${n.slice(-1)}`:`\\\\${n}`,this.options.pedantic&&(n=r?n:\"[*+-]\");let s=this.rules.other.listItemRegex(n),a=!1;for(;e;){let l=!1,p=\"\",c=\"\";if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let g=t[2].split(`\n`,1)[0].replace(this.rules.other.listReplaceTabs,O=>\" \".repeat(3*O.length)),h=e.split(`\n`,1)[0],R=!g.trim(),f=0;if(this.options.pedantic?(f=2,c=g.trimStart()):R?f=t[1].length+1:(f=t[2].search(this.rules.other.nonSpaceChar),f=f>4?1:f,c=g.slice(f),f+=t[1].length),R&&this.rules.other.blankLine.test(h)&&(p+=h+`\n`,e=e.substring(h.length+1),l=!0),!l){let O=this.rules.other.nextBulletRegex(f),V=this.rules.other.hrRegex(f),Y=this.rules.other.fencesBeginRegex(f),ee=this.rules.other.headingBeginRegex(f),fe=this.rules.other.htmlBeginRegex(f);for(;e;){let H=e.split(`\n`,1)[0],A;if(h=H,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting,\" \"),A=h):A=h.replace(this.rules.other.tabCharGlobal,\" \"),Y.test(h)||ee.test(h)||fe.test(h)||O.test(h)||V.test(h))break;if(A.search(this.rules.other.nonSpaceChar)>=f||!h.trim())c+=`\n`+A.slice(f);else{if(R||g.replace(this.rules.other.tabCharGlobal,\" \").search(this.rules.other.nonSpaceChar)>=4||Y.test(g)||ee.test(g)||V.test(g))break;c+=`\n`+h}!R&&!h.trim()&&(R=!0),p+=H+`\n`,e=e.substring(H.length+1),g=A.slice(f)}}i.loose||(a?i.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(a=!0)),i.items.push({type:\"list_item\",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]}),i.raw+=p}let o=i.items.at(-1);if(o)o.raw=o.raw.trimEnd(),o.text=o.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.items){if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),l.task){if(l.text=l.text.replace(this.rules.other.listReplaceTask,\"\"),l.tokens[0]?.type===\"text\"||l.tokens[0]?.type===\"paragraph\"){l.tokens[0].raw=l.tokens[0].raw.replace(this.rules.other.listReplaceTask,\"\"),l.tokens[0].text=l.tokens[0].text.replace(this.rules.other.listReplaceTask,\"\");for(let c=this.lexer.inlineQueue.length-1;c>=0;c--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[c].src)){this.lexer.inlineQueue[c].src=this.lexer.inlineQueue[c].src.replace(this.rules.other.listReplaceTask,\"\");break}}let p=this.rules.other.listTaskCheckbox.exec(l.raw);if(p){let c={type:\"checkbox\",raw:p[0]+\" \",checked:p[0]!==\"[ ]\"};l.checked=c.checked,i.loose?l.tokens[0]&&[\"paragraph\",\"text\"].includes(l.tokens[0].type)&&\"tokens\"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=c.raw+l.tokens[0].raw,l.tokens[0].text=c.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(c)):l.tokens.unshift({type:\"paragraph\",raw:c.raw,text:c.raw,tokens:[c]}):l.tokens.unshift(c)}}if(!i.loose){let p=l.tokens.filter(g=>g.type===\"space\"),c=p.length>0&&p.some(g=>this.rules.other.anyLine.test(g.raw));i.loose=c}}if(i.loose)for(let l of i.items){l.loose=!0;for(let p of l.tokens)p.type===\"text\"&&(p.type=\"paragraph\")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:\"html\",block:!0,raw:t[0],pre:t[1]===\"pre\"||t[1]===\"script\"||t[1]===\"style\",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,\" \"),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,\"$1\").replace(this.rules.inline.anyPunctuation,\"$1\"):\"\",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,\"$1\"):t[3];return{type:\"def\",tag:n,raw:t[0],href:r,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=J(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,\"\").split(\"|\"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,\"\").split(`\n`):[],s={type:\"table\",raw:t[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let a of r)this.rules.other.tableAlignRight.test(a)?s.align.push(\"right\"):this.rules.other.tableAlignCenter.test(a)?s.align.push(\"center\"):this.rules.other.tableAlignLeft.test(a)?s.align.push(\"left\"):s.align.push(null);for(let a=0;a({text:o,tokens:this.lexer.inline(o),header:!1,align:s.align[l]})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:\"heading\",raw:t[0],depth:t[2].charAt(0)===\"=\"?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`\n`?t[1].slice(0,-1):t[1];return{type:\"paragraph\",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:\"text\",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:\"escape\",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:\"html\",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=z(n.slice(0,-1),\"\\\\\");if((n.length-s.length)%2===0)return}else{let s=de(t[2],\"()\");if(s===-2)return;if(s>-1){let o=(t[0].indexOf(\"!\")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,o).trim(),t[3]=\"\"}}let r=t[2],i=\"\";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],i=s[3])}else i=t[3]?t[3].slice(1,-1):\"\";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),ge(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,\"$1\"),title:i&&i.replace(this.rules.inline.anyPunctuation,\"$1\")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,\" \"),i=t[r.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:\"text\",raw:s,text:s}}return ge(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=\"\"){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(r[1]||r[2]||\"\")||!n||this.rules.inline.punctuation.exec(n)){let s=[...r[0]].length-1,a,o,l=s,p=0,c=r[0][0]===\"*\"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(r=c.exec(t))!=null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){l+=o;continue}else if((r[5]||r[6])&&s%3&&!((s+o)%3)){p+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+p);let g=[...r[0]][0].length,h=e.slice(0,s+r.index+g+o);if(Math.min(s,o)%2){let f=h.slice(1,-1);return{type:\"em\",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}let R=h.slice(2,-2);return{type:\"strong\",raw:h,text:R,tokens:this.lexer.inlineTokens(R)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal,\" \"),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:\"codespan\",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:\"br\",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:\"del\",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]===\"@\"?(n=t[1],r=\"mailto:\"+n):(n=t[1],r=n),{type:\"link\",raw:t[0],text:n,href:r,tokens:[{type:\"text\",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]===\"@\")n=t[0],r=\"mailto:\"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??\"\";while(i!==t[0]);n=t[0],t[1]===\"www.\"?r=\"http://\"+t[0]:r=t[0]}return{type:\"link\",raw:t[0],text:n,href:r,tokens:[{type:\"text\",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:\"text\",raw:t[0],text:t[0],escaped:n}}}};var x=class u{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new y,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:E.normal,inline:M.normal};this.options.pedantic?(t.block=E.pedantic,t.inline=M.pedantic):this.options.gfm&&(t.block=E.gfm,this.options.breaks?t.inline=M.breaks:t.inline=M.gfm),this.tokenizer.rules=t}static get rules(){return{block:E,inline:M}}static lex(e,t){return new u(t).lex(e)}static lexInline(e,t){return new u(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,`\n`),this.blockTokens(e,this.tokens);for(let t=0;t(r=s.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let s=t.at(-1);r.raw.length===1&&s!==void 0?s.raw+=`\n`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type===\"paragraph\"||s?.type===\"text\"?(s.raw+=(s.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,s.text+=`\n`+r.text,this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type===\"paragraph\"||s?.type===\"text\"?(s.raw+=(s.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,s.text+=`\n`+r.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let s=1/0,a=e.slice(1),o;this.options.extensions.startBlock.forEach(l=>{o=l.call({lexer:this},a),typeof o==\"number\"&&o>=0&&(s=Math.min(s,o))}),s<1/0&&s>=0&&(i=e.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let s=t.at(-1);n&&s?.type===\"paragraph\"?(s.raw+=(s.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,s.text+=`\n`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type===\"text\"?(s.raw+=(s.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,s.text+=`\n`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(e){let s=\"Infinite loop on byte: \"+e.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw new Error(s)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,r=null;if(this.tokens.links){let o=Object.keys(this.tokens.links);if(o.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)o.includes(r[0].slice(r[0].lastIndexOf(\"[\")+1,-1))&&(n=n.slice(0,r.index)+\"[\"+\"a\".repeat(r[0].length-2)+\"]\"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,r.index)+\"++\"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+\"[\"+\"a\".repeat(r[0].length-i-2)+\"]\"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let s=!1,a=\"\";for(;e;){s||(a=\"\"),s=!1;let o;if(this.options.extensions?.inline?.some(p=>(o=p.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let p=t.at(-1);o.type===\"text\"&&p?.type===\"text\"?(p.raw+=o.raw,p.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,a)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let l=e;if(this.options.extensions?.startInline){let p=1/0,c=e.slice(1),g;this.options.extensions.startInline.forEach(h=>{g=h.call({lexer:this},c),typeof g==\"number\"&&g>=0&&(p=Math.min(p,g))}),p<1/0&&p>=0&&(l=e.substring(0,p+1))}if(o=this.tokenizer.inlineText(l)){e=e.substring(o.raw.length),o.raw.slice(-1)!==\"_\"&&(a=o.raw.slice(-1)),s=!0;let p=t.at(-1);p?.type===\"text\"?(p.raw+=o.raw,p.text+=o.text):t.push(o);continue}if(e){let p=\"Infinite loop on byte: \"+e.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return t}};var P=class{options;parser;constructor(e){this.options=e||T}space(e){return\"\"}code({text:e,lang:t,escaped:n}){let r=(t||\"\").match(m.notSpaceStart)?.[0],i=e.replace(m.endingNewline,\"\")+`\n`;return r?'
    '+(n?i:w(i,!0))+`
    \n`:\"
    \"+(n?i:w(i,!0))+`
    \n`}blockquote({tokens:e}){return`
    \n${this.parser.parse(e)}
    \n`}html({text:e}){return e}def(e){return\"\"}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)}\n`}hr(e){return`
    \n`}list(e){let t=e.ordered,n=e.start,r=\"\";for(let a=0;a\n`+r+\"\n`}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • \n`}checkbox({checked:e}){return\" '}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    \n`}table(e){let t=\"\",n=\"\";for(let i=0;i${r}`),`\n\n`+t+`\n`+r+`
    \n`}tablerow({text:e}){return`\n${e}\n`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?\"th\":\"td\";return(e.align?`<${n} align=\"${e.align}\">`:`<${n}>`)+t+`\n`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${w(e,!0)}`}br(e){return\"
    \"}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=X(e);if(i===null)return r;e=i;let s='
    \"+r+\"\",s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=X(e);if(i===null)return w(n);e=i;let s=`\"${n}\"`;return\",s}text(e){return\"tokens\"in e&&e.tokens?this.parser.parseInline(e.tokens):\"escaped\"in e&&e.escaped?e.text:w(e.text)}};var $=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return\"\"+e}image({text:e}){return\"\"+e}br(){return\"\"}checkbox({raw:e}){return e}};var b=class u{options;renderer;textRenderer;constructor(e){this.options=e||T,this.options.renderer=this.options.renderer||new P,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new $}static parse(e,t){return new u(t).parse(e)}static parseInline(e,t){return new u(t).parseInline(e)}parse(e){let t=\"\";for(let n=0;n{let a=i[s].flat(1/0);n=n.concat(this.walkTokens(a,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error(\"extension name required\");if(\"renderer\"in i){let s=t.renderers[i.name];s?t.renderers[i.name]=function(...a){let o=i.renderer.apply(this,a);return o===!1&&(o=s.apply(this,a)),o}:t.renderers[i.name]=i.renderer}if(\"tokenizer\"in i){if(!i.level||i.level!==\"block\"&&i.level!==\"inline\")throw new Error(\"extension level must be 'block' or 'inline'\");let s=t[i.level];s?s.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level===\"block\"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level===\"inline\"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}\"childTokens\"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),r.extensions=t),n.renderer){let i=this.defaults.renderer||new P(this.defaults);for(let s in n.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if([\"options\",\"parser\"].includes(s))continue;let a=s,o=n.renderer[a],l=i[a];i[a]=(...p)=>{let c=o.apply(i,p);return c===!1&&(c=l.apply(i,p)),c||\"\"}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new y(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if([\"options\",\"rules\",\"lexer\"].includes(s))continue;let a=s,o=n.tokenizer[a],l=i[a];i[a]=(...p)=>{let c=o.apply(i,p);return c===!1&&(c=l.apply(i,p)),c}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new S;for(let s in n.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if([\"options\",\"block\"].includes(s))continue;let a=s,o=n.hooks[a],l=i[a];S.passThroughHooks.has(s)?i[a]=p=>{if(this.defaults.async&&S.passThroughHooksRespectAsync.has(s))return(async()=>{let g=await o.call(i,p);return l.call(i,g)})();let c=o.call(i,p);return l.call(i,c)}:i[a]=(...p)=>{if(this.defaults.async)return(async()=>{let g=await o.apply(i,p);return g===!1&&(g=await l.apply(i,p)),g})();let c=o.apply(i,p);return c===!1&&(c=l.apply(i,p)),c}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(a){let o=[];return o.push(s.call(this,a)),i&&(o=o.concat(i.call(this,a))),o}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,r)=>{let i={...r},s={...this.defaults,...i},a=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error(\"marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.\"));if(typeof n>\"u\"||n===null)return a(new Error(\"marked(): input parameter is undefined or null\"));if(typeof n!=\"string\")return a(new Error(\"marked(): input parameter is of type \"+Object.prototype.toString.call(n)+\", string expected\"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(n):n,p=await(s.hooks?await s.hooks.provideLexer():e?x.lex:x.lexInline)(o,s),c=s.hooks?await s.hooks.processAllTokens(p):p;s.walkTokens&&await Promise.all(this.walkTokens(c,s.walkTokens));let h=await(s.hooks?await s.hooks.provideParser():e?b.parse:b.parseInline)(c,s);return s.hooks?await s.hooks.postprocess(h):h})().catch(a);try{s.hooks&&(n=s.hooks.preprocess(n));let l=(s.hooks?s.hooks.provideLexer():e?x.lex:x.lexInline)(n,s);s.hooks&&(l=s.hooks.processAllTokens(l)),s.walkTokens&&this.walkTokens(l,s.walkTokens);let c=(s.hooks?s.hooks.provideParser():e?b.parse:b.parseInline)(l,s);return s.hooks&&(c=s.hooks.postprocess(c)),c}catch(o){return a(o)}}}onError(e,t){return n=>{if(n.message+=`\nPlease report this to https://github.com/markedjs/marked.`,e){let r=\"

    An error occurred:

    \"+w(n.message+\"\",!0)+\"
    \";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}};var _=new B;function d(u,e){return _.parse(u,e)}d.options=d.setOptions=function(u){return _.setOptions(u),d.defaults=_.defaults,Z(d.defaults),d};d.getDefaults=L;d.defaults=T;d.use=function(...u){return _.use(...u),d.defaults=_.defaults,Z(d.defaults),d};d.walkTokens=function(u,e){return _.walkTokens(u,e)};d.parseInline=_.parseInline;d.Parser=b;d.parser=b.parse;d.Renderer=P;d.TextRenderer=$;d.Lexer=x;d.lexer=x.lex;d.Tokenizer=y;d.Hooks=S;d.parse=d;var Dt=d.options,Ht=d.setOptions,Zt=d.use,Gt=d.walkTokens,Nt=d.parseInline,Qt=d,Ft=b.parse,jt=x.lex;export{S as Hooks,x as Lexer,B as Marked,b as Parser,P as Renderer,$ as TextRenderer,y as Tokenizer,T as defaults,L as getDefaults,jt as lexer,d as marked,Dt as options,Qt as parse,Nt as parseInline,Ft as parser,Ht as setOptions,Zt as use,Gt as walkTokens};\n//# sourceMappingURL=marked.esm.js.map\n","import DOMPurify from \"dompurify\";\nimport { marked } from \"marked\";\nimport { truncateText } from \"./format\";\n\nmarked.setOptions({\n gfm: true,\n breaks: true,\n mangle: false,\n});\n\nconst allowedTags = [\n \"a\",\n \"b\",\n \"blockquote\",\n \"br\",\n \"code\",\n \"del\",\n \"em\",\n \"h1\",\n \"h2\",\n \"h3\",\n \"h4\",\n \"hr\",\n \"i\",\n \"li\",\n \"ol\",\n \"p\",\n \"pre\",\n \"strong\",\n \"table\",\n \"tbody\",\n \"td\",\n \"th\",\n \"thead\",\n \"tr\",\n \"ul\",\n];\n\nconst allowedAttrs = [\"class\", \"href\", \"rel\", \"target\", \"title\", \"start\"];\n\nlet hooksInstalled = false;\nconst MARKDOWN_CHAR_LIMIT = 140_000;\nconst MARKDOWN_PARSE_LIMIT = 40_000;\nconst MARKDOWN_CACHE_LIMIT = 200;\nconst MARKDOWN_CACHE_MAX_CHARS = 50_000;\nconst markdownCache = new Map();\n\nfunction getCachedMarkdown(key: string): string | null {\n const cached = markdownCache.get(key);\n if (cached === undefined) return null;\n markdownCache.delete(key);\n markdownCache.set(key, cached);\n return cached;\n}\n\nfunction setCachedMarkdown(key: string, value: string) {\n markdownCache.set(key, value);\n if (markdownCache.size <= MARKDOWN_CACHE_LIMIT) return;\n const oldest = markdownCache.keys().next().value;\n if (oldest) markdownCache.delete(oldest);\n}\n\nfunction installHooks() {\n if (hooksInstalled) return;\n hooksInstalled = true;\n\n DOMPurify.addHook(\"afterSanitizeAttributes\", (node) => {\n if (!(node instanceof HTMLAnchorElement)) return;\n const href = node.getAttribute(\"href\");\n if (!href) return;\n node.setAttribute(\"rel\", \"noreferrer noopener\");\n node.setAttribute(\"target\", \"_blank\");\n });\n}\n\nexport function toSanitizedMarkdownHtml(markdown: string): string {\n const input = markdown.trim();\n if (!input) return \"\";\n installHooks();\n if (input.length <= MARKDOWN_CACHE_MAX_CHARS) {\n const cached = getCachedMarkdown(input);\n if (cached !== null) return cached;\n }\n const truncated = truncateText(input, MARKDOWN_CHAR_LIMIT);\n const suffix = truncated.truncated\n ? `\\n\\n… truncated (${truncated.total} chars, showing first ${truncated.text.length}).`\n : \"\";\n if (truncated.text.length > MARKDOWN_PARSE_LIMIT) {\n const escaped = escapeHtml(`${truncated.text}${suffix}`);\n const html = `
    ${escaped}
    `;\n const sanitized = DOMPurify.sanitize(html, {\n ALLOWED_TAGS: allowedTags,\n ALLOWED_ATTR: allowedAttrs,\n });\n if (input.length <= MARKDOWN_CACHE_MAX_CHARS) {\n setCachedMarkdown(input, sanitized);\n }\n return sanitized;\n }\n const rendered = marked.parse(`${truncated.text}${suffix}`) as string;\n const sanitized = DOMPurify.sanitize(rendered, {\n ALLOWED_TAGS: allowedTags,\n ALLOWED_ATTR: allowedAttrs,\n });\n if (input.length <= MARKDOWN_CACHE_MAX_CHARS) {\n setCachedMarkdown(input, sanitized);\n }\n return sanitized;\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(//g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n","import { html, type TemplateResult } from \"lit\";\nimport { icons } from \"../icons\";\n\nconst COPIED_FOR_MS = 1500;\nconst ERROR_FOR_MS = 2000;\nconst COPY_LABEL = \"Copy as markdown\";\nconst COPIED_LABEL = \"Copied\";\nconst ERROR_LABEL = \"Copy failed\";\n\ntype CopyButtonOptions = {\n text: () => string;\n label?: string;\n};\n\nasync function copyTextToClipboard(text: string): Promise {\n if (!text) return false;\n\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction setButtonLabel(button: HTMLButtonElement, label: string) {\n button.title = label;\n button.setAttribute(\"aria-label\", label);\n}\n\nfunction createCopyButton(options: CopyButtonOptions): TemplateResult {\n const idleLabel = options.label ?? COPY_LABEL;\n return html`\n {\n const btn = e.currentTarget as HTMLButtonElement | null;\n const iconContainer = btn?.querySelector(\n \".chat-copy-btn__icon\",\n ) as HTMLElement | null;\n\n if (!btn || btn.dataset.copying === \"1\") return;\n\n btn.dataset.copying = \"1\";\n btn.setAttribute(\"aria-busy\", \"true\");\n btn.disabled = true;\n\n const copied = await copyTextToClipboard(options.text());\n if (!btn.isConnected) return;\n\n delete btn.dataset.copying;\n btn.removeAttribute(\"aria-busy\");\n btn.disabled = false;\n\n if (!copied) {\n btn.dataset.error = \"1\";\n setButtonLabel(btn, ERROR_LABEL);\n\n window.setTimeout(() => {\n if (!btn.isConnected) return;\n delete btn.dataset.error;\n setButtonLabel(btn, idleLabel);\n }, ERROR_FOR_MS);\n return;\n }\n\n btn.dataset.copied = \"1\";\n setButtonLabel(btn, COPIED_LABEL);\n\n window.setTimeout(() => {\n if (!btn.isConnected) return;\n delete btn.dataset.copied;\n setButtonLabel(btn, idleLabel);\n }, COPIED_FOR_MS);\n }}\n >\n \n ${icons.copy}\n ${icons.check}\n \n \n `;\n}\n\nexport function renderCopyAsMarkdownButton(markdown: string): TemplateResult {\n return createCopyButton({ text: () => markdown, label: COPY_LABEL });\n}\n","import rawConfig from \"./tool-display.json\";\nimport type { IconName } from \"./icons\";\n\ntype ToolDisplayActionSpec = {\n label?: string;\n detailKeys?: string[];\n};\n\ntype ToolDisplaySpec = {\n icon?: string;\n title?: string;\n label?: string;\n detailKeys?: string[];\n actions?: Record;\n};\n\ntype ToolDisplayConfig = {\n version?: number;\n fallback?: ToolDisplaySpec;\n tools?: Record;\n};\n\nexport type ToolDisplay = {\n name: string;\n icon: IconName;\n title: string;\n label: string;\n verb?: string;\n detail?: string;\n};\n\nconst TOOL_DISPLAY_CONFIG = rawConfig as ToolDisplayConfig;\nconst FALLBACK = TOOL_DISPLAY_CONFIG.fallback ?? { icon: \"puzzle\" };\nconst TOOL_MAP = TOOL_DISPLAY_CONFIG.tools ?? {};\n\nfunction normalizeToolName(name?: string): string {\n return (name ?? \"tool\").trim();\n}\n\nfunction defaultTitle(name: string): string {\n const cleaned = name.replace(/_/g, \" \").trim();\n if (!cleaned) return \"Tool\";\n return cleaned\n .split(/\\s+/)\n .map((part) =>\n part.length <= 2 && part.toUpperCase() === part\n ? part\n : `${part.at(0)?.toUpperCase() ?? \"\"}${part.slice(1)}`,\n )\n .join(\" \");\n}\n\nfunction normalizeVerb(value?: string): string | undefined {\n const trimmed = value?.trim();\n if (!trimmed) return undefined;\n return trimmed.replace(/_/g, \" \");\n}\n\nfunction coerceDisplayValue(value: unknown): string | undefined {\n if (value === null || value === undefined) return undefined;\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n if (!trimmed) return undefined;\n const firstLine = trimmed.split(/\\r?\\n/)[0]?.trim() ?? \"\";\n if (!firstLine) return undefined;\n return firstLine.length > 160 ? `${firstLine.slice(0, 157)}…` : firstLine;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (Array.isArray(value)) {\n const values = value\n .map((item) => coerceDisplayValue(item))\n .filter((item): item is string => Boolean(item));\n if (values.length === 0) return undefined;\n const preview = values.slice(0, 3).join(\", \");\n return values.length > 3 ? `${preview}…` : preview;\n }\n return undefined;\n}\n\nfunction lookupValueByPath(args: unknown, path: string): unknown {\n if (!args || typeof args !== \"object\") return undefined;\n let current: unknown = args;\n for (const segment of path.split(\".\")) {\n if (!segment) return undefined;\n if (!current || typeof current !== \"object\") return undefined;\n const record = current as Record;\n current = record[segment];\n }\n return current;\n}\n\nfunction resolveDetailFromKeys(args: unknown, keys: string[]): string | undefined {\n for (const key of keys) {\n const value = lookupValueByPath(args, key);\n const display = coerceDisplayValue(value);\n if (display) return display;\n }\n return undefined;\n}\n\nfunction resolveReadDetail(args: unknown): string | undefined {\n if (!args || typeof args !== \"object\") return undefined;\n const record = args as Record;\n const path = typeof record.path === \"string\" ? record.path : undefined;\n if (!path) return undefined;\n const offset = typeof record.offset === \"number\" ? record.offset : undefined;\n const limit = typeof record.limit === \"number\" ? record.limit : undefined;\n if (offset !== undefined && limit !== undefined) {\n return `${path}:${offset}-${offset + limit}`;\n }\n return path;\n}\n\nfunction resolveWriteDetail(args: unknown): string | undefined {\n if (!args || typeof args !== \"object\") return undefined;\n const record = args as Record;\n const path = typeof record.path === \"string\" ? record.path : undefined;\n return path;\n}\n\nfunction resolveActionSpec(\n spec: ToolDisplaySpec | undefined,\n action: string | undefined,\n): ToolDisplayActionSpec | undefined {\n if (!spec || !action) return undefined;\n return spec.actions?.[action] ?? undefined;\n}\n\nexport function resolveToolDisplay(params: {\n name?: string;\n args?: unknown;\n meta?: string;\n}): ToolDisplay {\n const name = normalizeToolName(params.name);\n const key = name.toLowerCase();\n const spec = TOOL_MAP[key];\n const icon = (spec?.icon ?? FALLBACK.icon ?? \"puzzle\") as IconName;\n const title = spec?.title ?? defaultTitle(name);\n const label = spec?.label ?? name;\n const actionRaw =\n params.args && typeof params.args === \"object\"\n ? ((params.args as Record).action as string | undefined)\n : undefined;\n const action = typeof actionRaw === \"string\" ? actionRaw.trim() : undefined;\n const actionSpec = resolveActionSpec(spec, action);\n const verb = normalizeVerb(actionSpec?.label ?? action);\n\n let detail: string | undefined;\n if (key === \"read\") detail = resolveReadDetail(params.args);\n if (!detail && (key === \"write\" || key === \"edit\" || key === \"attach\")) {\n detail = resolveWriteDetail(params.args);\n }\n\n const detailKeys =\n actionSpec?.detailKeys ?? spec?.detailKeys ?? FALLBACK.detailKeys ?? [];\n if (!detail && detailKeys.length > 0) {\n detail = resolveDetailFromKeys(params.args, detailKeys);\n }\n\n if (!detail && params.meta) {\n detail = params.meta;\n }\n\n if (detail) {\n detail = shortenHomeInString(detail);\n }\n\n return {\n name,\n icon,\n title,\n label,\n verb,\n detail,\n };\n}\n\nexport function formatToolDetail(display: ToolDisplay): string | undefined {\n const parts: string[] = [];\n if (display.verb) parts.push(display.verb);\n if (display.detail) parts.push(display.detail);\n if (parts.length === 0) return undefined;\n return parts.join(\" · \");\n}\n\nexport function formatToolSummary(display: ToolDisplay): string {\n const detail = formatToolDetail(display);\n return detail ? `${display.label}: ${detail}` : display.label;\n}\n\nfunction shortenHomeInString(input: string): string {\n if (!input) return input;\n return input\n .replace(/\\/Users\\/[^/]+/g, \"~\")\n .replace(/\\/home\\/[^/]+/g, \"~\");\n}\n","/**\n * Chat-related constants for the UI layer.\n */\n\n/** Character threshold for showing tool output inline vs collapsed */\nexport const TOOL_INLINE_THRESHOLD = 80;\n\n/** Maximum lines to show in collapsed preview */\nexport const PREVIEW_MAX_LINES = 2;\n\n/** Maximum characters to show in collapsed preview */\nexport const PREVIEW_MAX_CHARS = 100;\n","/**\n * Helper functions for tool card rendering.\n */\n\nimport { PREVIEW_MAX_CHARS, PREVIEW_MAX_LINES } from \"./constants\";\n\n/**\n * Format tool output content for display in the sidebar.\n * Detects JSON and wraps it in a code block with formatting.\n */\nexport function formatToolOutputForSidebar(text: string): string {\n const trimmed = text.trim();\n // Try to detect and format JSON\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n const parsed = JSON.parse(trimmed);\n return \"```json\\n\" + JSON.stringify(parsed, null, 2) + \"\\n```\";\n } catch {\n // Not valid JSON, return as-is\n }\n }\n return text;\n}\n\n/**\n * Get a truncated preview of tool output text.\n * Truncates to first N lines or first N characters, whichever is shorter.\n */\nexport function getTruncatedPreview(text: string): string {\n const allLines = text.split(\"\\n\");\n const lines = allLines.slice(0, PREVIEW_MAX_LINES);\n const preview = lines.join(\"\\n\");\n if (preview.length > PREVIEW_MAX_CHARS) {\n return preview.slice(0, PREVIEW_MAX_CHARS) + \"…\";\n }\n return lines.length < allLines.length ? preview + \"…\" : preview;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatToolDetail, resolveToolDisplay } from \"../tool-display\";\nimport { icons } from \"../icons\";\nimport type { ToolCard } from \"../types/chat-types\";\nimport { TOOL_INLINE_THRESHOLD } from \"./constants\";\nimport {\n formatToolOutputForSidebar,\n getTruncatedPreview,\n} from \"./tool-helpers\";\nimport { isToolResultMessage } from \"./message-normalizer\";\nimport { extractTextCached } from \"./message-extract\";\n\nexport function extractToolCards(message: unknown): ToolCard[] {\n const m = message as Record;\n const content = normalizeContent(m.content);\n const cards: ToolCard[] = [];\n\n for (const item of content) {\n const kind = String(item.type ?? \"\").toLowerCase();\n const isToolCall =\n [\"toolcall\", \"tool_call\", \"tooluse\", \"tool_use\"].includes(kind) ||\n (typeof item.name === \"string\" && item.arguments != null);\n if (isToolCall) {\n cards.push({\n kind: \"call\",\n name: (item.name as string) ?? \"tool\",\n args: coerceArgs(item.arguments ?? item.args),\n });\n }\n }\n\n for (const item of content) {\n const kind = String(item.type ?? \"\").toLowerCase();\n if (kind !== \"toolresult\" && kind !== \"tool_result\") continue;\n const text = extractToolText(item);\n const name = typeof item.name === \"string\" ? item.name : \"tool\";\n cards.push({ kind: \"result\", name, text });\n }\n\n if (\n isToolResultMessage(message) &&\n !cards.some((card) => card.kind === \"result\")\n ) {\n const name =\n (typeof m.toolName === \"string\" && m.toolName) ||\n (typeof m.tool_name === \"string\" && m.tool_name) ||\n \"tool\";\n const text = extractTextCached(message) ?? undefined;\n cards.push({ kind: \"result\", name, text });\n }\n\n return cards;\n}\n\nexport function renderToolCardSidebar(\n card: ToolCard,\n onOpenSidebar?: (content: string) => void,\n) {\n const display = resolveToolDisplay({ name: card.name, args: card.args });\n const detail = formatToolDetail(display);\n const hasText = Boolean(card.text?.trim());\n\n const canClick = Boolean(onOpenSidebar);\n const handleClick = canClick\n ? () => {\n if (hasText) {\n onOpenSidebar!(formatToolOutputForSidebar(card.text!));\n return;\n }\n const info = `## ${display.label}\\n\\n${\n detail ? `**Command:** \\`${detail}\\`\\n\\n` : \"\"\n }*No output — tool completed successfully.*`;\n onOpenSidebar!(info);\n }\n : undefined;\n\n const isShort = hasText && (card.text?.length ?? 0) <= TOOL_INLINE_THRESHOLD;\n const showCollapsed = hasText && !isShort;\n const showInline = hasText && isShort;\n const isEmpty = !hasText;\n\n return html`\n {\n if (e.key !== \"Enter\" && e.key !== \" \") return;\n e.preventDefault();\n handleClick?.();\n }\n : nothing}\n >\n
    \n
    \n ${icons[display.icon]}\n ${display.label}\n
    \n ${canClick\n ? html`${hasText ? \"View\" : \"\"} ${icons.check}`\n : nothing}\n ${isEmpty && !canClick ? html`${icons.check}` : nothing}\n
    \n ${detail\n ? html`
    ${detail}
    `\n : nothing}\n ${isEmpty\n ? html`
    Completed
    `\n : nothing}\n ${showCollapsed\n ? html`
    ${getTruncatedPreview(card.text!)}
    `\n : nothing}\n ${showInline\n ? html`
    ${card.text}
    `\n : nothing}\n \n `;\n}\n\nfunction normalizeContent(content: unknown): Array> {\n if (!Array.isArray(content)) return [];\n return content.filter(Boolean) as Array>;\n}\n\nfunction coerceArgs(value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n if (!trimmed) return value;\n if (!trimmed.startsWith(\"{\") && !trimmed.startsWith(\"[\")) return value;\n try {\n return JSON.parse(trimmed);\n } catch {\n return value;\n }\n}\n\nfunction extractToolText(item: Record): string | undefined {\n if (typeof item.text === \"string\") return item.text;\n if (typeof item.content === \"string\") return item.content;\n return undefined;\n}\n","import { html, nothing } from \"lit\";\nimport { unsafeHTML } from \"lit/directives/unsafe-html.js\";\n\nimport type { AssistantIdentity } from \"../assistant-identity\";\nimport { toSanitizedMarkdownHtml } from \"../markdown\";\nimport type { MessageGroup } from \"../types/chat-types\";\nimport { renderCopyAsMarkdownButton } from \"./copy-as-markdown\";\nimport { isToolResultMessage, normalizeRoleForGrouping } from \"./message-normalizer\";\nimport {\n extractTextCached,\n extractThinkingCached,\n formatReasoningMarkdown,\n} from \"./message-extract\";\nimport { extractToolCards, renderToolCardSidebar } from \"./tool-cards\";\n\nexport function renderReadingIndicatorGroup(assistant?: AssistantIdentity) {\n return html`\n
    \n ${renderAvatar(\"assistant\", assistant)}\n
    \n
    \n \n \n \n
    \n
    \n
    \n `;\n}\n\nexport function renderStreamingGroup(\n text: string,\n startedAt: number,\n onOpenSidebar?: (content: string) => void,\n assistant?: AssistantIdentity,\n) {\n const timestamp = new Date(startedAt).toLocaleTimeString([], {\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n const name = assistant?.name ?? \"Assistant\";\n\n return html`\n
    \n ${renderAvatar(\"assistant\", assistant)}\n
    \n ${renderGroupedMessage(\n {\n role: \"assistant\",\n content: [{ type: \"text\", text }],\n timestamp: startedAt,\n },\n { isStreaming: true, showReasoning: false },\n onOpenSidebar,\n )}\n
    \n ${name}\n ${timestamp}\n
    \n
    \n
    \n `;\n}\n\nexport function renderMessageGroup(\n group: MessageGroup,\n opts: {\n onOpenSidebar?: (content: string) => void;\n showReasoning: boolean;\n assistantName?: string;\n assistantAvatar?: string | null;\n },\n) {\n const normalizedRole = normalizeRoleForGrouping(group.role);\n const assistantName = opts.assistantName ?? \"Assistant\";\n const who =\n normalizedRole === \"user\"\n ? \"You\"\n : normalizedRole === \"assistant\"\n ? assistantName\n : normalizedRole;\n const roleClass =\n normalizedRole === \"user\"\n ? \"user\"\n : normalizedRole === \"assistant\"\n ? \"assistant\"\n : \"other\";\n const timestamp = new Date(group.timestamp).toLocaleTimeString([], {\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n\n return html`\n
    \n ${renderAvatar(group.role, {\n name: assistantName,\n avatar: opts.assistantAvatar ?? null,\n })}\n
    \n ${group.messages.map((item, index) =>\n renderGroupedMessage(\n item.message,\n {\n isStreaming:\n group.isStreaming && index === group.messages.length - 1,\n showReasoning: opts.showReasoning,\n },\n opts.onOpenSidebar,\n ),\n )}\n
    \n ${who}\n ${timestamp}\n
    \n
    \n
    \n `;\n}\n\nfunction renderAvatar(\n role: string,\n assistant?: Pick,\n) {\n const normalized = normalizeRoleForGrouping(role);\n const assistantName = assistant?.name?.trim() || \"Assistant\";\n const assistantAvatar = assistant?.avatar?.trim() || \"\";\n const initial =\n normalized === \"user\"\n ? \"U\"\n : normalized === \"assistant\"\n ? assistantName.charAt(0).toUpperCase() || \"A\"\n : normalized === \"tool\"\n ? \"⚙\"\n : \"?\";\n const className =\n normalized === \"user\"\n ? \"user\"\n : normalized === \"assistant\"\n ? \"assistant\"\n : normalized === \"tool\"\n ? \"tool\"\n : \"other\";\n\n if (assistantAvatar && normalized === \"assistant\") {\n if (isAvatarUrl(assistantAvatar)) {\n return html``;\n }\n return html`
    ${assistantAvatar}
    `;\n }\n\n return html`
    ${initial}
    `;\n}\n\nfunction isAvatarUrl(value: string): boolean {\n return (\n /^https?:\\/\\//i.test(value) ||\n /^data:image\\//i.test(value) ||\n /^\\//.test(value) // Relative paths from avatar endpoint\n );\n}\n\nfunction renderGroupedMessage(\n message: unknown,\n opts: { isStreaming: boolean; showReasoning: boolean },\n onOpenSidebar?: (content: string) => void,\n) {\n const m = message as Record;\n const role = typeof m.role === \"string\" ? m.role : \"unknown\";\n const isToolResult =\n isToolResultMessage(message) ||\n role.toLowerCase() === \"toolresult\" ||\n role.toLowerCase() === \"tool_result\" ||\n typeof m.toolCallId === \"string\" ||\n typeof m.tool_call_id === \"string\";\n\n const toolCards = extractToolCards(message);\n const hasToolCards = toolCards.length > 0;\n\n const extractedText = extractTextCached(message);\n const extractedThinking =\n opts.showReasoning && role === \"assistant\"\n ? extractThinkingCached(message)\n : null;\n const markdownBase = extractedText?.trim() ? extractedText : null;\n const reasoningMarkdown = extractedThinking\n ? formatReasoningMarkdown(extractedThinking)\n : null;\n const markdown = markdownBase;\n const canCopyMarkdown = role === \"assistant\" && Boolean(markdown?.trim());\n\n const bubbleClasses = [\n \"chat-bubble\",\n canCopyMarkdown ? \"has-copy\" : \"\",\n opts.isStreaming ? \"streaming\" : \"\",\n \"fade-in\",\n ]\n .filter(Boolean)\n .join(\" \");\n\n if (!markdown && hasToolCards && isToolResult) {\n return html`${toolCards.map((card) =>\n renderToolCardSidebar(card, onOpenSidebar),\n )}`;\n }\n\n if (!markdown && !hasToolCards) return nothing;\n\n return html`\n
    \n ${canCopyMarkdown ? renderCopyAsMarkdownButton(markdown!) : nothing}\n ${reasoningMarkdown\n ? html`
    ${unsafeHTML(\n toSanitizedMarkdownHtml(reasoningMarkdown),\n )}
    `\n : nothing}\n ${markdown\n ? html`
    ${unsafeHTML(toSanitizedMarkdownHtml(markdown))}
    `\n : nothing}\n ${toolCards.map((card) => renderToolCardSidebar(card, onOpenSidebar))}\n
    \n `;\n}\n","import { html, nothing } from \"lit\";\nimport { unsafeHTML } from \"lit/directives/unsafe-html.js\";\n\nimport { icons } from \"../icons\";\nimport { toSanitizedMarkdownHtml } from \"../markdown\";\n\nexport type MarkdownSidebarProps = {\n content: string | null;\n error: string | null;\n onClose: () => void;\n onViewRawText: () => void;\n};\n\nexport function renderMarkdownSidebar(props: MarkdownSidebarProps) {\n return html`\n
    \n
    \n
    Tool Output
    \n \n
    \n
    \n ${props.error\n ? html`\n
    ${props.error}
    \n \n `\n : props.content\n ? html`
    ${unsafeHTML(toSanitizedMarkdownHtml(props.content))}
    `\n : html`
    No content available
    `}\n
    \n
    \n `;\n}\n","import { LitElement, html, css } from \"lit\";\nimport { customElement, property } from \"lit/decorators.js\";\n\n/**\n * A draggable divider for resizable split views.\n * Dispatches 'resize' events with { splitRatio: number } detail.\n */\n@customElement(\"resizable-divider\")\nexport class ResizableDivider extends LitElement {\n @property({ type: Number }) splitRatio = 0.6;\n @property({ type: Number }) minRatio = 0.4;\n @property({ type: Number }) maxRatio = 0.7;\n\n private isDragging = false;\n private startX = 0;\n private startRatio = 0;\n\n static styles = css`\n :host {\n width: 4px;\n cursor: col-resize;\n background: var(--border, #333);\n transition: background 150ms ease-out;\n flex-shrink: 0;\n position: relative;\n }\n\n :host::before {\n content: \"\";\n position: absolute;\n top: 0;\n left: -4px;\n right: -4px;\n bottom: 0;\n }\n\n :host(:hover) {\n background: var(--accent, #007bff);\n }\n\n :host(.dragging) {\n background: var(--accent, #007bff);\n }\n `;\n\n render() {\n return html``;\n }\n\n connectedCallback() {\n super.connectedCallback();\n this.addEventListener(\"mousedown\", this.handleMouseDown);\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this.removeEventListener(\"mousedown\", this.handleMouseDown);\n document.removeEventListener(\"mousemove\", this.handleMouseMove);\n document.removeEventListener(\"mouseup\", this.handleMouseUp);\n }\n\n private handleMouseDown = (e: MouseEvent) => {\n this.isDragging = true;\n this.startX = e.clientX;\n this.startRatio = this.splitRatio;\n this.classList.add(\"dragging\");\n\n document.addEventListener(\"mousemove\", this.handleMouseMove);\n document.addEventListener(\"mouseup\", this.handleMouseUp);\n\n e.preventDefault();\n };\n\n private handleMouseMove = (e: MouseEvent) => {\n if (!this.isDragging) return;\n\n const container = this.parentElement;\n if (!container) return;\n\n const containerWidth = container.getBoundingClientRect().width;\n const deltaX = e.clientX - this.startX;\n const deltaRatio = deltaX / containerWidth;\n\n let newRatio = this.startRatio + deltaRatio;\n newRatio = Math.max(this.minRatio, Math.min(this.maxRatio, newRatio));\n\n this.dispatchEvent(\n new CustomEvent(\"resize\", {\n detail: { splitRatio: newRatio },\n bubbles: true,\n composed: true,\n })\n );\n };\n\n private handleMouseUp = () => {\n this.isDragging = false;\n this.classList.remove(\"dragging\");\n\n document.removeEventListener(\"mousemove\", this.handleMouseMove);\n document.removeEventListener(\"mouseup\", this.handleMouseUp);\n };\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n \"resizable-divider\": ResizableDivider;\n }\n}\n","import { html, nothing } from \"lit\";\nimport { repeat } from \"lit/directives/repeat.js\";\nimport type { SessionsListResult } from \"../types\";\nimport type { ChatQueueItem } from \"../ui-types\";\nimport type { ChatItem, MessageGroup } from \"../types/chat-types\";\nimport { icons } from \"../icons\";\nimport {\n normalizeMessage,\n normalizeRoleForGrouping,\n} from \"../chat/message-normalizer\";\nimport {\n renderMessageGroup,\n renderReadingIndicatorGroup,\n renderStreamingGroup,\n} from \"../chat/grouped-render\";\nimport { renderMarkdownSidebar } from \"./markdown-sidebar\";\nimport \"../components/resizable-divider\";\n\nexport type CompactionIndicatorStatus = {\n active: boolean;\n startedAt: number | null;\n completedAt: number | null;\n};\n\nexport type ChatProps = {\n sessionKey: string;\n onSessionKeyChange: (next: string) => void;\n thinkingLevel: string | null;\n showThinking: boolean;\n loading: boolean;\n sending: boolean;\n canAbort?: boolean;\n compactionStatus?: CompactionIndicatorStatus | null;\n messages: unknown[];\n toolMessages: unknown[];\n stream: string | null;\n streamStartedAt: number | null;\n assistantAvatarUrl?: string | null;\n draft: string;\n queue: ChatQueueItem[];\n connected: boolean;\n canSend: boolean;\n disabledReason: string | null;\n error: string | null;\n sessions: SessionsListResult | null;\n // Focus mode\n focusMode: boolean;\n // Sidebar state\n sidebarOpen?: boolean;\n sidebarContent?: string | null;\n sidebarError?: string | null;\n splitRatio?: number;\n assistantName: string;\n assistantAvatar: string | null;\n // Event handlers\n onRefresh: () => void;\n onToggleFocusMode: () => void;\n onDraftChange: (next: string) => void;\n onSend: () => void;\n onAbort?: () => void;\n onQueueRemove: (id: string) => void;\n onNewSession: () => void;\n onOpenSidebar?: (content: string) => void;\n onCloseSidebar?: () => void;\n onSplitRatioChange?: (ratio: number) => void;\n onChatScroll?: (event: Event) => void;\n};\n\nconst COMPACTION_TOAST_DURATION_MS = 5000;\n\nfunction renderCompactionIndicator(status: CompactionIndicatorStatus | null | undefined) {\n if (!status) return nothing;\n \n // Show \"compacting...\" while active\n if (status.active) {\n return html`\n
    \n ${icons.loader} Compacting context...\n
    \n `;\n }\n\n // Show \"compaction complete\" briefly after completion\n if (status.completedAt) {\n const elapsed = Date.now() - status.completedAt;\n if (elapsed < COMPACTION_TOAST_DURATION_MS) {\n return html`\n
    \n ${icons.check} Context compacted\n
    \n `;\n }\n }\n \n return nothing;\n}\n\nexport function renderChat(props: ChatProps) {\n const canCompose = props.connected;\n const isBusy = props.sending || props.stream !== null;\n const canAbort = Boolean(props.canAbort && props.onAbort);\n const activeSession = props.sessions?.sessions?.find(\n (row) => row.key === props.sessionKey,\n );\n const reasoningLevel = activeSession?.reasoningLevel ?? \"off\";\n const showReasoning = props.showThinking && reasoningLevel !== \"off\";\n const assistantIdentity = {\n name: props.assistantName,\n avatar: props.assistantAvatar ?? props.assistantAvatarUrl ?? null,\n };\n\n const composePlaceholder = props.connected\n ? \"Message (↩ to send, Shift+↩ for line breaks)\"\n : \"Connect to the gateway to start chatting…\";\n\n const splitRatio = props.splitRatio ?? 0.6;\n const sidebarOpen = Boolean(props.sidebarOpen && props.onCloseSidebar);\n const thread = html`\n \n ${props.loading ? html`
    Loading chat…
    ` : nothing}\n ${repeat(buildChatItems(props), (item) => item.key, (item) => {\n if (item.kind === \"reading-indicator\") {\n return renderReadingIndicatorGroup(assistantIdentity);\n }\n\n if (item.kind === \"stream\") {\n return renderStreamingGroup(\n item.text,\n item.startedAt,\n props.onOpenSidebar,\n assistantIdentity,\n );\n }\n\n if (item.kind === \"group\") {\n return renderMessageGroup(item, {\n onOpenSidebar: props.onOpenSidebar,\n showReasoning,\n assistantName: props.assistantName,\n assistantAvatar: assistantIdentity.avatar,\n });\n }\n\n return nothing;\n })}\n \n `;\n\n return html`\n
    \n ${props.disabledReason\n ? html`
    ${props.disabledReason}
    `\n : nothing}\n\n ${props.error\n ? html`
    ${props.error}
    `\n : nothing}\n\n ${renderCompactionIndicator(props.compactionStatus)}\n\n ${props.focusMode\n ? html`\n \n ${icons.x}\n \n `\n : nothing}\n\n \n \n ${thread}\n \n\n ${sidebarOpen\n ? html`\n \n props.onSplitRatioChange?.(e.detail.splitRatio)}\n >\n
    \n ${renderMarkdownSidebar({\n content: props.sidebarContent ?? null,\n error: props.sidebarError ?? null,\n onClose: props.onCloseSidebar!,\n onViewRawText: () => {\n if (!props.sidebarContent || !props.onOpenSidebar) return;\n props.onOpenSidebar(`\\`\\`\\`\\n${props.sidebarContent}\\n\\`\\`\\``);\n },\n })}\n
    \n `\n : nothing}\n \n\n ${props.queue.length\n ? html`\n
    \n
    Queued (${props.queue.length})
    \n
    \n ${props.queue.map(\n (item) => html`\n
    \n
    ${item.text}
    \n props.onQueueRemove(item.id)}\n >\n ${icons.x}\n \n
    \n `,\n )}\n
    \n
    \n `\n : nothing}\n\n
    \n \n
    \n \n ${canAbort ? \"Stop\" : \"New session\"}\n \n \n ${isBusy ? \"Queue\" : \"Send\"}\n \n
    \n
    \n
    \n `;\n}\n\nconst CHAT_HISTORY_RENDER_LIMIT = 200;\n\nfunction groupMessages(items: ChatItem[]): Array {\n const result: Array = [];\n let currentGroup: MessageGroup | null = null;\n\n for (const item of items) {\n if (item.kind !== \"message\") {\n if (currentGroup) {\n result.push(currentGroup);\n currentGroup = null;\n }\n result.push(item);\n continue;\n }\n\n const normalized = normalizeMessage(item.message);\n const role = normalizeRoleForGrouping(normalized.role);\n const timestamp = normalized.timestamp || Date.now();\n\n if (!currentGroup || currentGroup.role !== role) {\n if (currentGroup) result.push(currentGroup);\n currentGroup = {\n kind: \"group\",\n key: `group:${role}:${item.key}`,\n role,\n messages: [{ message: item.message, key: item.key }],\n timestamp,\n isStreaming: false,\n };\n } else {\n currentGroup.messages.push({ message: item.message, key: item.key });\n }\n }\n\n if (currentGroup) result.push(currentGroup);\n return result;\n}\n\nfunction buildChatItems(props: ChatProps): Array {\n const items: ChatItem[] = [];\n const history = Array.isArray(props.messages) ? props.messages : [];\n const tools = Array.isArray(props.toolMessages) ? props.toolMessages : [];\n const historyStart = Math.max(0, history.length - CHAT_HISTORY_RENDER_LIMIT);\n if (historyStart > 0) {\n items.push({\n kind: \"message\",\n key: \"chat:history:notice\",\n message: {\n role: \"system\",\n content: `Showing last ${CHAT_HISTORY_RENDER_LIMIT} messages (${historyStart} hidden).`,\n timestamp: Date.now(),\n },\n });\n }\n for (let i = historyStart; i < history.length; i++) {\n const msg = history[i];\n const normalized = normalizeMessage(msg);\n\n if (!props.showThinking && normalized.role.toLowerCase() === \"toolresult\") {\n continue;\n }\n\n items.push({\n kind: \"message\",\n key: messageKey(msg, i),\n message: msg,\n });\n }\n if (props.showThinking) {\n for (let i = 0; i < tools.length; i++) {\n items.push({\n kind: \"message\",\n key: messageKey(tools[i], i + history.length),\n message: tools[i],\n });\n }\n }\n\n if (props.stream !== null) {\n const key = `stream:${props.sessionKey}:${props.streamStartedAt ?? \"live\"}`;\n if (props.stream.trim().length > 0) {\n items.push({\n kind: \"stream\",\n key,\n text: props.stream,\n startedAt: props.streamStartedAt ?? Date.now(),\n });\n } else {\n items.push({ kind: \"reading-indicator\", key });\n }\n }\n\n return groupMessages(items);\n}\n\nfunction messageKey(message: unknown, index: number): string {\n const m = message as Record;\n const toolCallId = typeof m.toolCallId === \"string\" ? m.toolCallId : \"\";\n if (toolCallId) return `tool:${toolCallId}`;\n const id = typeof m.id === \"string\" ? m.id : \"\";\n if (id) return `msg:${id}`;\n const messageId = typeof m.messageId === \"string\" ? m.messageId : \"\";\n if (messageId) return `msg:${messageId}`;\n const timestamp = typeof m.timestamp === \"number\" ? m.timestamp : null;\n const role = typeof m.role === \"string\" ? m.role : \"unknown\";\n if (timestamp != null) return `msg:${role}:${timestamp}:${index}`;\n return `msg:${role}:${index}`;\n}\n","import type { ConfigUiHints } from \"../types\";\n\nexport type JsonSchema = {\n type?: string | string[];\n title?: string;\n description?: string;\n properties?: Record;\n items?: JsonSchema | JsonSchema[];\n additionalProperties?: JsonSchema | boolean;\n enum?: unknown[];\n const?: unknown;\n default?: unknown;\n anyOf?: JsonSchema[];\n oneOf?: JsonSchema[];\n allOf?: JsonSchema[];\n nullable?: boolean;\n};\n\nexport function schemaType(schema: JsonSchema): string | undefined {\n if (!schema) return undefined;\n if (Array.isArray(schema.type)) {\n const filtered = schema.type.filter((t) => t !== \"null\");\n return filtered[0] ?? schema.type[0];\n }\n return schema.type;\n}\n\nexport function defaultValue(schema?: JsonSchema): unknown {\n if (!schema) return \"\";\n if (schema.default !== undefined) return schema.default;\n const type = schemaType(schema);\n switch (type) {\n case \"object\":\n return {};\n case \"array\":\n return [];\n case \"boolean\":\n return false;\n case \"number\":\n case \"integer\":\n return 0;\n case \"string\":\n return \"\";\n default:\n return \"\";\n }\n}\n\nexport function pathKey(path: Array): string {\n return path.filter((segment) => typeof segment === \"string\").join(\".\");\n}\n\nexport function hintForPath(path: Array, hints: ConfigUiHints) {\n const key = pathKey(path);\n const direct = hints[key];\n if (direct) return direct;\n const segments = key.split(\".\");\n for (const [hintKey, hint] of Object.entries(hints)) {\n if (!hintKey.includes(\"*\")) continue;\n const hintSegments = hintKey.split(\".\");\n if (hintSegments.length !== segments.length) continue;\n let match = true;\n for (let i = 0; i < segments.length; i += 1) {\n if (hintSegments[i] !== \"*\" && hintSegments[i] !== segments[i]) {\n match = false;\n break;\n }\n }\n if (match) return hint;\n }\n return undefined;\n}\n\nexport function humanize(raw: string) {\n return raw\n .replace(/_/g, \" \")\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/\\s+/g, \" \")\n .replace(/^./, (m) => m.toUpperCase());\n}\n\nexport function isSensitivePath(path: Array): boolean {\n const key = pathKey(path).toLowerCase();\n return (\n key.includes(\"token\") ||\n key.includes(\"password\") ||\n key.includes(\"secret\") ||\n key.includes(\"apikey\") ||\n key.endsWith(\"key\")\n );\n}\n\n","import { html, nothing, type TemplateResult } from \"lit\";\nimport type { ConfigUiHints } from \"../types\";\nimport {\n defaultValue,\n hintForPath,\n humanize,\n isSensitivePath,\n pathKey,\n schemaType,\n type JsonSchema,\n} from \"./config-form.shared\";\n\nconst META_KEYS = new Set([\"title\", \"description\", \"default\", \"nullable\"]);\n\nfunction isAnySchema(schema: JsonSchema): boolean {\n const keys = Object.keys(schema ?? {}).filter((key) => !META_KEYS.has(key));\n return keys.length === 0;\n}\n\nfunction jsonValue(value: unknown): string {\n if (value === undefined) return \"\";\n try {\n return JSON.stringify(value, null, 2) ?? \"\";\n } catch {\n return \"\";\n }\n}\n\n// SVG Icons as template literals\nconst icons = {\n chevronDown: html``,\n plus: html``,\n minus: html``,\n trash: html``,\n edit: html``,\n};\n\nexport function renderNode(params: {\n schema: JsonSchema;\n value: unknown;\n path: Array;\n hints: ConfigUiHints;\n unsupported: Set;\n disabled: boolean;\n showLabel?: boolean;\n onPatch: (path: Array, value: unknown) => void;\n}): TemplateResult | typeof nothing {\n const { schema, value, path, hints, unsupported, disabled, onPatch } = params;\n const showLabel = params.showLabel ?? true;\n const type = schemaType(schema);\n const hint = hintForPath(path, hints);\n const label = hint?.label ?? schema.title ?? humanize(String(path.at(-1)));\n const help = hint?.help ?? schema.description;\n const key = pathKey(path);\n\n if (unsupported.has(key)) {\n return html`
    \n
    ${label}
    \n
    Unsupported schema node. Use Raw mode.
    \n
    `;\n }\n\n // Handle anyOf/oneOf unions\n if (schema.anyOf || schema.oneOf) {\n const variants = schema.anyOf ?? schema.oneOf ?? [];\n const nonNull = variants.filter(\n (v) => !(v.type === \"null\" || (Array.isArray(v.type) && v.type.includes(\"null\")))\n );\n\n if (nonNull.length === 1) {\n return renderNode({ ...params, schema: nonNull[0] });\n }\n\n // Check if it's a set of literal values (enum-like)\n const extractLiteral = (v: JsonSchema): unknown | undefined => {\n if (v.const !== undefined) return v.const;\n if (v.enum && v.enum.length === 1) return v.enum[0];\n return undefined;\n };\n const literals = nonNull.map(extractLiteral);\n const allLiterals = literals.every((v) => v !== undefined);\n\n if (allLiterals && literals.length > 0 && literals.length <= 5) {\n // Use segmented control for small sets\n const resolvedValue = value ?? schema.default;\n return html`\n
    \n ${showLabel ? html`` : nothing}\n ${help ? html`
    ${help}
    ` : nothing}\n
    \n ${literals.map((lit, idx) => html`\n onPatch(path, lit)}\n >\n ${String(lit)}\n \n `)}\n
    \n
    \n `;\n }\n\n if (allLiterals && literals.length > 5) {\n // Use dropdown for larger sets\n return renderSelect({ ...params, options: literals, value: value ?? schema.default });\n }\n\n // Handle mixed primitive types\n const primitiveTypes = new Set(\n nonNull.map((variant) => schemaType(variant)).filter(Boolean)\n );\n const normalizedTypes = new Set(\n [...primitiveTypes].map((v) => (v === \"integer\" ? \"number\" : v))\n );\n\n if ([...normalizedTypes].every((v) => [\"string\", \"number\", \"boolean\"].includes(v as string))) {\n const hasString = normalizedTypes.has(\"string\");\n const hasNumber = normalizedTypes.has(\"number\");\n const hasBoolean = normalizedTypes.has(\"boolean\");\n \n if (hasBoolean && normalizedTypes.size === 1) {\n return renderNode({\n ...params,\n schema: { ...schema, type: \"boolean\", anyOf: undefined, oneOf: undefined },\n });\n }\n\n if (hasString || hasNumber) {\n return renderTextInput({\n ...params,\n inputType: hasNumber && !hasString ? \"number\" : \"text\",\n });\n }\n }\n }\n\n // Enum - use segmented for small, dropdown for large\n if (schema.enum) {\n const options = schema.enum;\n if (options.length <= 5) {\n const resolvedValue = value ?? schema.default;\n return html`\n
    \n ${showLabel ? html`` : nothing}\n ${help ? html`
    ${help}
    ` : nothing}\n
    \n ${options.map((opt) => html`\n onPatch(path, opt)}\n >\n ${String(opt)}\n \n `)}\n
    \n
    \n `;\n }\n return renderSelect({ ...params, options, value: value ?? schema.default });\n }\n\n // Object type - collapsible section\n if (type === \"object\") {\n return renderObject(params);\n }\n\n // Array type\n if (type === \"array\") {\n return renderArray(params);\n }\n\n // Boolean - toggle row\n if (type === \"boolean\") {\n const displayValue = typeof value === \"boolean\" ? value : typeof schema.default === \"boolean\" ? schema.default : false;\n return html`\n \n `;\n }\n\n // Number/Integer\n if (type === \"number\" || type === \"integer\") {\n return renderNumberInput(params);\n }\n\n // String\n if (type === \"string\") {\n return renderTextInput({ ...params, inputType: \"text\" });\n }\n\n // Fallback\n return html`\n
    \n
    ${label}
    \n
    Unsupported type: ${type}. Use Raw mode.
    \n
    \n `;\n}\n\nfunction renderTextInput(params: {\n schema: JsonSchema;\n value: unknown;\n path: Array;\n hints: ConfigUiHints;\n disabled: boolean;\n showLabel?: boolean;\n inputType: \"text\" | \"number\";\n onPatch: (path: Array, value: unknown) => void;\n}): TemplateResult {\n const { schema, value, path, hints, disabled, onPatch, inputType } = params;\n const showLabel = params.showLabel ?? true;\n const hint = hintForPath(path, hints);\n const label = hint?.label ?? schema.title ?? humanize(String(path.at(-1)));\n const help = hint?.help ?? schema.description;\n const isSensitive = hint?.sensitive ?? isSensitivePath(path);\n const placeholder =\n hint?.placeholder ??\n (isSensitive ? \"••••\" : schema.default !== undefined ? `Default: ${schema.default}` : \"\");\n const displayValue = value ?? \"\";\n\n return html`\n
    \n ${showLabel ? html`` : nothing}\n ${help ? html`
    ${help}
    ` : nothing}\n
    \n {\n const raw = (e.target as HTMLInputElement).value;\n if (inputType === \"number\") {\n if (raw.trim() === \"\") {\n onPatch(path, undefined);\n return;\n }\n const parsed = Number(raw);\n onPatch(path, Number.isNaN(parsed) ? raw : parsed);\n return;\n }\n onPatch(path, raw);\n }}\n />\n ${schema.default !== undefined ? html`\n onPatch(path, schema.default)}\n >↺\n ` : nothing}\n
    \n
    \n `;\n}\n\nfunction renderNumberInput(params: {\n schema: JsonSchema;\n value: unknown;\n path: Array;\n hints: ConfigUiHints;\n disabled: boolean;\n showLabel?: boolean;\n onPatch: (path: Array, value: unknown) => void;\n}): TemplateResult {\n const { schema, value, path, hints, disabled, onPatch } = params;\n const showLabel = params.showLabel ?? true;\n const hint = hintForPath(path, hints);\n const label = hint?.label ?? schema.title ?? humanize(String(path.at(-1)));\n const help = hint?.help ?? schema.description;\n const displayValue = value ?? schema.default ?? \"\";\n const numValue = typeof displayValue === \"number\" ? displayValue : 0;\n\n return html`\n
    \n ${showLabel ? html`` : nothing}\n ${help ? html`
    ${help}
    ` : nothing}\n
    \n onPatch(path, numValue - 1)}\n >−\n {\n const raw = (e.target as HTMLInputElement).value;\n const parsed = raw === \"\" ? undefined : Number(raw);\n onPatch(path, parsed);\n }}\n />\n onPatch(path, numValue + 1)}\n >+\n
    \n
    \n `;\n}\n\nfunction renderSelect(params: {\n schema: JsonSchema;\n value: unknown;\n path: Array;\n hints: ConfigUiHints;\n disabled: boolean;\n showLabel?: boolean;\n options: unknown[];\n onPatch: (path: Array, value: unknown) => void;\n}): TemplateResult {\n const { schema, value, path, hints, disabled, options, onPatch } = params;\n const showLabel = params.showLabel ?? true;\n const hint = hintForPath(path, hints);\n const label = hint?.label ?? schema.title ?? humanize(String(path.at(-1)));\n const help = hint?.help ?? schema.description;\n const resolvedValue = value ?? schema.default;\n const currentIndex = options.findIndex(\n (opt) => opt === resolvedValue || String(opt) === String(resolvedValue),\n );\n const unset = \"__unset__\";\n\n return html`\n
    \n ${showLabel ? html`` : nothing}\n ${help ? html`
    ${help}
    ` : nothing}\n = 0 ? String(currentIndex) : unset}\n @change=${(e: Event) => {\n const val = (e.target as HTMLSelectElement).value;\n onPatch(path, val === unset ? undefined : options[Number(val)]);\n }}\n >\n \n ${options.map((opt, idx) => html`\n \n `)}\n \n
    \n `;\n}\n\nfunction renderObject(params: {\n schema: JsonSchema;\n value: unknown;\n path: Array;\n hints: ConfigUiHints;\n unsupported: Set;\n disabled: boolean;\n showLabel?: boolean;\n onPatch: (path: Array, value: unknown) => void;\n}): TemplateResult {\n const { schema, value, path, hints, unsupported, disabled, onPatch } = params;\n const showLabel = params.showLabel ?? true;\n const hint = hintForPath(path, hints);\n const label = hint?.label ?? schema.title ?? humanize(String(path.at(-1)));\n const help = hint?.help ?? schema.description;\n \n const fallback = value ?? schema.default;\n const obj = fallback && typeof fallback === \"object\" && !Array.isArray(fallback)\n ? (fallback as Record)\n : {};\n const props = schema.properties ?? {};\n const entries = Object.entries(props);\n \n // Sort by hint order\n const sorted = entries.sort((a, b) => {\n const orderA = hintForPath([...path, a[0]], hints)?.order ?? 0;\n const orderB = hintForPath([...path, b[0]], hints)?.order ?? 0;\n if (orderA !== orderB) return orderA - orderB;\n return a[0].localeCompare(b[0]);\n });\n\n const reserved = new Set(Object.keys(props));\n const additional = schema.additionalProperties;\n const allowExtra = Boolean(additional) && typeof additional === \"object\";\n\n // For top-level, don't wrap in collapsible\n if (path.length === 1) {\n return html`\n
    \n ${sorted.map(([propKey, node]) =>\n renderNode({\n schema: node,\n value: obj[propKey],\n path: [...path, propKey],\n hints,\n unsupported,\n disabled,\n onPatch,\n })\n )}\n ${allowExtra ? renderMapField({\n schema: additional as JsonSchema,\n value: obj,\n path,\n hints,\n unsupported,\n disabled,\n reservedKeys: reserved,\n onPatch,\n }) : nothing}\n
    \n `;\n }\n\n // Nested objects get collapsible treatment\n return html`\n
    \n \n ${label}\n ${icons.chevronDown}\n \n ${help ? html`
    ${help}
    ` : nothing}\n
    \n ${sorted.map(([propKey, node]) =>\n renderNode({\n schema: node,\n value: obj[propKey],\n path: [...path, propKey],\n hints,\n unsupported,\n disabled,\n onPatch,\n })\n )}\n ${allowExtra ? renderMapField({\n schema: additional as JsonSchema,\n value: obj,\n path,\n hints,\n unsupported,\n disabled,\n reservedKeys: reserved,\n onPatch,\n }) : nothing}\n
    \n
    \n `;\n}\n\nfunction renderArray(params: {\n schema: JsonSchema;\n value: unknown;\n path: Array;\n hints: ConfigUiHints;\n unsupported: Set;\n disabled: boolean;\n showLabel?: boolean;\n onPatch: (path: Array, value: unknown) => void;\n}): TemplateResult {\n const { schema, value, path, hints, unsupported, disabled, onPatch } = params;\n const showLabel = params.showLabel ?? true;\n const hint = hintForPath(path, hints);\n const label = hint?.label ?? schema.title ?? humanize(String(path.at(-1)));\n const help = hint?.help ?? schema.description;\n\n const itemsSchema = Array.isArray(schema.items) ? schema.items[0] : schema.items;\n if (!itemsSchema) {\n return html`\n
    \n
    ${label}
    \n
    Unsupported array schema. Use Raw mode.
    \n
    \n `;\n }\n\n const arr = Array.isArray(value) ? value : Array.isArray(schema.default) ? schema.default : [];\n\n return html`\n
    \n
    \n ${showLabel ? html`${label}` : nothing}\n ${arr.length} item${arr.length !== 1 ? 's' : ''}\n {\n const next = [...arr, defaultValue(itemsSchema)];\n onPatch(path, next);\n }}\n >\n ${icons.plus}\n Add\n \n
    \n ${help ? html`
    ${help}
    ` : nothing}\n \n ${arr.length === 0 ? html`\n
    \n No items yet. Click \"Add\" to create one.\n
    \n ` : html`\n
    \n ${arr.map((item, idx) => html`\n
    \n
    \n #${idx + 1}\n {\n const next = [...arr];\n next.splice(idx, 1);\n onPatch(path, next);\n }}\n >\n ${icons.trash}\n \n
    \n
    \n ${renderNode({\n schema: itemsSchema,\n value: item,\n path: [...path, idx],\n hints,\n unsupported,\n disabled,\n showLabel: false,\n onPatch,\n })}\n
    \n
    \n `)}\n
    \n `}\n
    \n `;\n}\n\nfunction renderMapField(params: {\n schema: JsonSchema;\n value: Record;\n path: Array;\n hints: ConfigUiHints;\n unsupported: Set;\n disabled: boolean;\n reservedKeys: Set;\n onPatch: (path: Array, value: unknown) => void;\n}): TemplateResult {\n const { schema, value, path, hints, unsupported, disabled, reservedKeys, onPatch } = params;\n const anySchema = isAnySchema(schema);\n const entries = Object.entries(value ?? {}).filter(([key]) => !reservedKeys.has(key));\n\n return html`\n
    \n
    \n Custom entries\n {\n const next = { ...(value ?? {}) };\n let index = 1;\n let key = `custom-${index}`;\n while (key in next) {\n index += 1;\n key = `custom-${index}`;\n }\n next[key] = anySchema ? {} : defaultValue(schema);\n onPatch(path, next);\n }}\n >\n ${icons.plus}\n Add Entry\n \n
    \n \n ${entries.length === 0 ? html`\n
    No custom entries.
    \n ` : html`\n
    \n ${entries.map(([key, entryValue]) => {\n const valuePath = [...path, key];\n const fallback = jsonValue(entryValue);\n return html`\n
    \n
    \n {\n const nextKey = (e.target as HTMLInputElement).value.trim();\n if (!nextKey || nextKey === key) return;\n const next = { ...(value ?? {}) };\n if (nextKey in next) return;\n next[nextKey] = next[key];\n delete next[key];\n onPatch(path, next);\n }}\n />\n
    \n
    \n ${anySchema\n ? html`\n {\n const target = e.target as HTMLTextAreaElement;\n const raw = target.value.trim();\n if (!raw) {\n onPatch(valuePath, undefined);\n return;\n }\n try {\n onPatch(valuePath, JSON.parse(raw));\n } catch {\n target.value = fallback;\n }\n }}\n >\n `\n : renderNode({\n schema,\n value: entryValue,\n path: valuePath,\n hints,\n unsupported,\n disabled,\n showLabel: false,\n onPatch,\n })}\n
    \n {\n const next = { ...(value ?? {}) };\n delete next[key];\n onPatch(path, next);\n }}\n >\n ${icons.trash}\n \n
    \n `;\n })}\n
    \n `}\n
    \n `;\n}\n","import { html, nothing } from \"lit\";\nimport type { ConfigUiHints } from \"../types\";\nimport { icons } from \"../icons\";\nimport {\n hintForPath,\n humanize,\n schemaType,\n type JsonSchema,\n} from \"./config-form.shared\";\nimport { renderNode } from \"./config-form.node\";\n\nexport type ConfigFormProps = {\n schema: JsonSchema | null;\n uiHints: ConfigUiHints;\n value: Record | null;\n disabled?: boolean;\n unsupportedPaths?: string[];\n searchQuery?: string;\n activeSection?: string | null;\n activeSubsection?: string | null;\n onPatch: (path: Array, value: unknown) => void;\n};\n\n// SVG Icons for section cards (Lucide-style)\nconst sectionIcons = {\n env: html``,\n update: html``,\n agents: html``,\n auth: html``,\n channels: html``,\n messages: html``,\n commands: html``,\n hooks: html``,\n skills: html``,\n tools: html``,\n gateway: html``,\n wizard: html``,\n // Additional sections\n meta: html``,\n logging: html``,\n browser: html``,\n ui: html``,\n models: html``,\n bindings: html``,\n broadcast: html``,\n audio: html``,\n session: html``,\n cron: html``,\n web: html``,\n discovery: html``,\n canvasHost: html``,\n talk: html``,\n plugins: html``,\n default: html``,\n};\n\n// Section metadata\nexport const SECTION_META: Record = {\n env: { label: \"Environment Variables\", description: \"Environment variables passed to the gateway process\" },\n update: { label: \"Updates\", description: \"Auto-update settings and release channel\" },\n agents: { label: \"Agents\", description: \"Agent configurations, models, and identities\" },\n auth: { label: \"Authentication\", description: \"API keys and authentication profiles\" },\n channels: { label: \"Channels\", description: \"Messaging channels (Telegram, Discord, Slack, etc.)\" },\n messages: { label: \"Messages\", description: \"Message handling and routing settings\" },\n commands: { label: \"Commands\", description: \"Custom slash commands\" },\n hooks: { label: \"Hooks\", description: \"Webhooks and event hooks\" },\n skills: { label: \"Skills\", description: \"Skill packs and capabilities\" },\n tools: { label: \"Tools\", description: \"Tool configurations (browser, search, etc.)\" },\n gateway: { label: \"Gateway\", description: \"Gateway server settings (port, auth, binding)\" },\n wizard: { label: \"Setup Wizard\", description: \"Setup wizard state and history\" },\n // Additional sections\n meta: { label: \"Metadata\", description: \"Gateway metadata and version information\" },\n logging: { label: \"Logging\", description: \"Log levels and output configuration\" },\n browser: { label: \"Browser\", description: \"Browser automation settings\" },\n ui: { label: \"UI\", description: \"User interface preferences\" },\n models: { label: \"Models\", description: \"AI model configurations and providers\" },\n bindings: { label: \"Bindings\", description: \"Key bindings and shortcuts\" },\n broadcast: { label: \"Broadcast\", description: \"Broadcast and notification settings\" },\n audio: { label: \"Audio\", description: \"Audio input/output settings\" },\n session: { label: \"Session\", description: \"Session management and persistence\" },\n cron: { label: \"Cron\", description: \"Scheduled tasks and automation\" },\n web: { label: \"Web\", description: \"Web server and API settings\" },\n discovery: { label: \"Discovery\", description: \"Service discovery and networking\" },\n canvasHost: { label: \"Canvas Host\", description: \"Canvas rendering and display\" },\n talk: { label: \"Talk\", description: \"Voice and speech settings\" },\n plugins: { label: \"Plugins\", description: \"Plugin management and extensions\" },\n};\n\nfunction getSectionIcon(key: string) {\n return sectionIcons[key as keyof typeof sectionIcons] ?? sectionIcons.default;\n}\n\nfunction matchesSearch(key: string, schema: JsonSchema, query: string): boolean {\n if (!query) return true;\n const q = query.toLowerCase();\n const meta = SECTION_META[key];\n \n // Check key name\n if (key.toLowerCase().includes(q)) return true;\n \n // Check label and description\n if (meta) {\n if (meta.label.toLowerCase().includes(q)) return true;\n if (meta.description.toLowerCase().includes(q)) return true;\n }\n \n return schemaMatches(schema, q);\n}\n\nfunction schemaMatches(schema: JsonSchema, query: string): boolean {\n if (schema.title?.toLowerCase().includes(query)) return true;\n if (schema.description?.toLowerCase().includes(query)) return true;\n if (schema.enum?.some((value) => String(value).toLowerCase().includes(query))) return true;\n\n if (schema.properties) {\n for (const [propKey, propSchema] of Object.entries(schema.properties)) {\n if (propKey.toLowerCase().includes(query)) return true;\n if (schemaMatches(propSchema, query)) return true;\n }\n }\n\n if (schema.items) {\n const items = Array.isArray(schema.items) ? schema.items : [schema.items];\n for (const item of items) {\n if (item && schemaMatches(item, query)) return true;\n }\n }\n\n if (schema.additionalProperties && typeof schema.additionalProperties === \"object\") {\n if (schemaMatches(schema.additionalProperties, query)) return true;\n }\n\n const unions = schema.anyOf ?? schema.oneOf ?? schema.allOf;\n if (unions) {\n for (const entry of unions) {\n if (entry && schemaMatches(entry, query)) return true;\n }\n }\n\n return false;\n}\n\nexport function renderConfigForm(props: ConfigFormProps) {\n if (!props.schema) {\n return html`
    Schema unavailable.
    `;\n }\n const schema = props.schema;\n const value = props.value ?? {};\n if (schemaType(schema) !== \"object\" || !schema.properties) {\n return html`
    Unsupported schema. Use Raw.
    `;\n }\n const unsupported = new Set(props.unsupportedPaths ?? []);\n const properties = schema.properties;\n const searchQuery = props.searchQuery ?? \"\";\n const activeSection = props.activeSection;\n const activeSubsection = props.activeSubsection ?? null;\n\n const entries = Object.entries(properties).sort((a, b) => {\n const orderA = hintForPath([a[0]], props.uiHints)?.order ?? 50;\n const orderB = hintForPath([b[0]], props.uiHints)?.order ?? 50;\n if (orderA !== orderB) return orderA - orderB;\n return a[0].localeCompare(b[0]);\n });\n\n const filteredEntries = entries.filter(([key, node]) => {\n if (activeSection && key !== activeSection) return false;\n if (searchQuery && !matchesSearch(key, node, searchQuery)) return false;\n return true;\n });\n\n let subsectionContext:\n | { sectionKey: string; subsectionKey: string; schema: JsonSchema }\n | null = null;\n if (activeSection && activeSubsection && filteredEntries.length === 1) {\n const sectionSchema = filteredEntries[0]?.[1];\n if (\n sectionSchema &&\n schemaType(sectionSchema) === \"object\" &&\n sectionSchema.properties &&\n sectionSchema.properties[activeSubsection]\n ) {\n subsectionContext = {\n sectionKey: activeSection,\n subsectionKey: activeSubsection,\n schema: sectionSchema.properties[activeSubsection],\n };\n }\n }\n\n if (filteredEntries.length === 0) {\n return html`\n
    \n
    ${icons.search}
    \n
    \n ${searchQuery \n ? `No settings match \"${searchQuery}\"` \n : \"No settings in this section\"}\n
    \n
    \n `;\n }\n\n return html`\n
    \n ${subsectionContext\n ? (() => {\n const { sectionKey, subsectionKey, schema: node } = subsectionContext;\n const hint = hintForPath([sectionKey, subsectionKey], props.uiHints);\n const label = hint?.label ?? node.title ?? humanize(subsectionKey);\n const description = hint?.help ?? node.description ?? \"\";\n const sectionValue = (value as Record)[sectionKey];\n const scopedValue =\n sectionValue && typeof sectionValue === \"object\"\n ? (sectionValue as Record)[subsectionKey]\n : undefined;\n const id = `config-section-${sectionKey}-${subsectionKey}`;\n return html`\n
    \n
    \n ${getSectionIcon(sectionKey)}\n
    \n

    ${label}

    \n ${description\n ? html`

    ${description}

    `\n : nothing}\n
    \n
    \n
    \n ${renderNode({\n schema: node,\n value: scopedValue,\n path: [sectionKey, subsectionKey],\n hints: props.uiHints,\n unsupported,\n disabled: props.disabled ?? false,\n showLabel: false,\n onPatch: props.onPatch,\n })}\n
    \n
    \n `;\n })()\n : filteredEntries.map(([key, node]) => {\n const meta = SECTION_META[key] ?? {\n label: key.charAt(0).toUpperCase() + key.slice(1),\n description: node.description ?? \"\",\n };\n\n return html`\n
    \n
    \n ${getSectionIcon(key)}\n
    \n

    ${meta.label}

    \n ${meta.description\n ? html`

    ${meta.description}

    `\n : nothing}\n
    \n
    \n
    \n ${renderNode({\n schema: node,\n value: (value as Record)[key],\n path: [key],\n hints: props.uiHints,\n unsupported,\n disabled: props.disabled ?? false,\n showLabel: false,\n onPatch: props.onPatch,\n })}\n
    \n
    \n `;\n })}\n
    \n `;\n}\n","import { pathKey, schemaType, type JsonSchema } from \"./config-form.shared\";\n\nexport type ConfigSchemaAnalysis = {\n schema: JsonSchema | null;\n unsupportedPaths: string[];\n};\n\nconst META_KEYS = new Set([\"title\", \"description\", \"default\", \"nullable\"]);\n\nfunction isAnySchema(schema: JsonSchema): boolean {\n const keys = Object.keys(schema ?? {}).filter((key) => !META_KEYS.has(key));\n return keys.length === 0;\n}\n\nfunction normalizeEnum(values: unknown[]): { enumValues: unknown[]; nullable: boolean } {\n const filtered = values.filter((value) => value != null);\n const nullable = filtered.length !== values.length;\n const enumValues: unknown[] = [];\n for (const value of filtered) {\n if (!enumValues.some((existing) => Object.is(existing, value))) {\n enumValues.push(value);\n }\n }\n return { enumValues, nullable };\n}\n\nexport function analyzeConfigSchema(raw: unknown): ConfigSchemaAnalysis {\n if (!raw || typeof raw !== \"object\") {\n return { schema: null, unsupportedPaths: [\"\"] };\n }\n return normalizeSchemaNode(raw as JsonSchema, []);\n}\n\nfunction normalizeSchemaNode(\n schema: JsonSchema,\n path: Array,\n): ConfigSchemaAnalysis {\n const unsupported = new Set();\n const normalized: JsonSchema = { ...schema };\n const pathLabel = pathKey(path) || \"\";\n\n if (schema.anyOf || schema.oneOf || schema.allOf) {\n const union = normalizeUnion(schema, path);\n if (union) return union;\n return { schema, unsupportedPaths: [pathLabel] };\n }\n\n const nullable = Array.isArray(schema.type) && schema.type.includes(\"null\");\n const type =\n schemaType(schema) ??\n (schema.properties || schema.additionalProperties ? \"object\" : undefined);\n normalized.type = type ?? schema.type;\n normalized.nullable = nullable || schema.nullable;\n\n if (normalized.enum) {\n const { enumValues, nullable: enumNullable } = normalizeEnum(normalized.enum);\n normalized.enum = enumValues;\n if (enumNullable) normalized.nullable = true;\n if (enumValues.length === 0) unsupported.add(pathLabel);\n }\n\n if (type === \"object\") {\n const properties = schema.properties ?? {};\n const normalizedProps: Record = {};\n for (const [key, value] of Object.entries(properties)) {\n const res = normalizeSchemaNode(value, [...path, key]);\n if (res.schema) normalizedProps[key] = res.schema;\n for (const entry of res.unsupportedPaths) unsupported.add(entry);\n }\n normalized.properties = normalizedProps;\n\n if (schema.additionalProperties === true) {\n unsupported.add(pathLabel);\n } else if (schema.additionalProperties === false) {\n normalized.additionalProperties = false;\n } else if (\n schema.additionalProperties &&\n typeof schema.additionalProperties === \"object\"\n ) {\n if (!isAnySchema(schema.additionalProperties as JsonSchema)) {\n const res = normalizeSchemaNode(\n schema.additionalProperties as JsonSchema,\n [...path, \"*\"],\n );\n normalized.additionalProperties =\n res.schema ?? (schema.additionalProperties as JsonSchema);\n if (res.unsupportedPaths.length > 0) unsupported.add(pathLabel);\n }\n }\n } else if (type === \"array\") {\n const itemsSchema = Array.isArray(schema.items)\n ? schema.items[0]\n : schema.items;\n if (!itemsSchema) {\n unsupported.add(pathLabel);\n } else {\n const res = normalizeSchemaNode(itemsSchema, [...path, \"*\"]);\n normalized.items = res.schema ?? itemsSchema;\n if (res.unsupportedPaths.length > 0) unsupported.add(pathLabel);\n }\n } else if (\n type !== \"string\" &&\n type !== \"number\" &&\n type !== \"integer\" &&\n type !== \"boolean\" &&\n !normalized.enum\n ) {\n unsupported.add(pathLabel);\n }\n\n return {\n schema: normalized,\n unsupportedPaths: Array.from(unsupported),\n };\n}\n\nfunction normalizeUnion(\n schema: JsonSchema,\n path: Array,\n): ConfigSchemaAnalysis | null {\n if (schema.allOf) return null;\n const union = schema.anyOf ?? schema.oneOf;\n if (!union) return null;\n\n const literals: unknown[] = [];\n const remaining: JsonSchema[] = [];\n let nullable = false;\n\n for (const entry of union) {\n if (!entry || typeof entry !== \"object\") return null;\n if (Array.isArray(entry.enum)) {\n const { enumValues, nullable: enumNullable } = normalizeEnum(entry.enum);\n literals.push(...enumValues);\n if (enumNullable) nullable = true;\n continue;\n }\n if (\"const\" in entry) {\n if (entry.const == null) {\n nullable = true;\n continue;\n }\n literals.push(entry.const);\n continue;\n }\n if (schemaType(entry) === \"null\") {\n nullable = true;\n continue;\n }\n remaining.push(entry);\n }\n\n if (literals.length > 0 && remaining.length === 0) {\n const unique: unknown[] = [];\n for (const value of literals) {\n if (!unique.some((existing) => Object.is(existing, value))) {\n unique.push(value);\n }\n }\n return {\n schema: {\n ...schema,\n enum: unique,\n nullable,\n anyOf: undefined,\n oneOf: undefined,\n allOf: undefined,\n },\n unsupportedPaths: [],\n };\n }\n\n if (remaining.length === 1) {\n const res = normalizeSchemaNode(remaining[0], path);\n if (res.schema) {\n res.schema.nullable = nullable || res.schema.nullable;\n }\n return res;\n }\n\n const primitiveTypes = [\"string\", \"number\", \"integer\", \"boolean\"];\n if (\n remaining.length > 0 &&\n literals.length === 0 &&\n remaining.every((entry) => entry.type && primitiveTypes.includes(String(entry.type)))\n ) {\n return {\n schema: {\n ...schema,\n nullable,\n },\n unsupportedPaths: [],\n };\n }\n\n return null;\n}\n","import { html, nothing } from \"lit\";\nimport type { ConfigUiHints } from \"../types\";\nimport { analyzeConfigSchema, renderConfigForm, SECTION_META } from \"./config-form\";\nimport {\n hintForPath,\n humanize,\n schemaType,\n type JsonSchema,\n} from \"./config-form.shared\";\n\nexport type ConfigProps = {\n raw: string;\n originalRaw: string;\n valid: boolean | null;\n issues: unknown[];\n loading: boolean;\n saving: boolean;\n applying: boolean;\n updating: boolean;\n connected: boolean;\n schema: unknown | null;\n schemaLoading: boolean;\n uiHints: ConfigUiHints;\n formMode: \"form\" | \"raw\";\n formValue: Record | null;\n originalValue: Record | null;\n searchQuery: string;\n activeSection: string | null;\n activeSubsection: string | null;\n onRawChange: (next: string) => void;\n onFormModeChange: (mode: \"form\" | \"raw\") => void;\n onFormPatch: (path: Array, value: unknown) => void;\n onSearchChange: (query: string) => void;\n onSectionChange: (section: string | null) => void;\n onSubsectionChange: (section: string | null) => void;\n onReload: () => void;\n onSave: () => void;\n onApply: () => void;\n onUpdate: () => void;\n};\n\n// SVG Icons for sidebar (Lucide-style)\nconst sidebarIcons = {\n all: html``,\n env: html``,\n update: html``,\n agents: html``,\n auth: html``,\n channels: html``,\n messages: html``,\n commands: html``,\n hooks: html``,\n skills: html``,\n tools: html``,\n gateway: html``,\n wizard: html``,\n // Additional sections\n meta: html``,\n logging: html``,\n browser: html``,\n ui: html``,\n models: html``,\n bindings: html``,\n broadcast: html``,\n audio: html``,\n session: html``,\n cron: html``,\n web: html``,\n discovery: html``,\n canvasHost: html``,\n talk: html``,\n plugins: html``,\n default: html``,\n};\n\n// Section definitions\nconst SECTIONS: Array<{ key: string; label: string }> = [\n { key: \"env\", label: \"Environment\" },\n { key: \"update\", label: \"Updates\" },\n { key: \"agents\", label: \"Agents\" },\n { key: \"auth\", label: \"Authentication\" },\n { key: \"channels\", label: \"Channels\" },\n { key: \"messages\", label: \"Messages\" },\n { key: \"commands\", label: \"Commands\" },\n { key: \"hooks\", label: \"Hooks\" },\n { key: \"skills\", label: \"Skills\" },\n { key: \"tools\", label: \"Tools\" },\n { key: \"gateway\", label: \"Gateway\" },\n { key: \"wizard\", label: \"Setup Wizard\" },\n];\n\ntype SubsectionEntry = {\n key: string;\n label: string;\n description?: string;\n order: number;\n};\n\nconst ALL_SUBSECTION = \"__all__\";\n\nfunction getSectionIcon(key: string) {\n return sidebarIcons[key as keyof typeof sidebarIcons] ?? sidebarIcons.default;\n}\n\nfunction resolveSectionMeta(key: string, schema?: JsonSchema): {\n label: string;\n description?: string;\n} {\n const meta = SECTION_META[key];\n if (meta) return meta;\n return {\n label: schema?.title ?? humanize(key),\n description: schema?.description ?? \"\",\n };\n}\n\nfunction resolveSubsections(params: {\n key: string;\n schema: JsonSchema | undefined;\n uiHints: ConfigUiHints;\n}): SubsectionEntry[] {\n const { key, schema, uiHints } = params;\n if (!schema || schemaType(schema) !== \"object\" || !schema.properties) return [];\n const entries = Object.entries(schema.properties).map(([subKey, node]) => {\n const hint = hintForPath([key, subKey], uiHints);\n const label = hint?.label ?? node.title ?? humanize(subKey);\n const description = hint?.help ?? node.description ?? \"\";\n const order = hint?.order ?? 50;\n return { key: subKey, label, description, order };\n });\n entries.sort((a, b) => (a.order !== b.order ? a.order - b.order : a.key.localeCompare(b.key)));\n return entries;\n}\n\nfunction computeDiff(\n original: Record | null,\n current: Record | null\n): Array<{ path: string; from: unknown; to: unknown }> {\n if (!original || !current) return [];\n const changes: Array<{ path: string; from: unknown; to: unknown }> = [];\n \n function compare(orig: unknown, curr: unknown, path: string) {\n if (orig === curr) return;\n if (typeof orig !== typeof curr) {\n changes.push({ path, from: orig, to: curr });\n return;\n }\n if (typeof orig !== \"object\" || orig === null || curr === null) {\n if (orig !== curr) {\n changes.push({ path, from: orig, to: curr });\n }\n return;\n }\n if (Array.isArray(orig) && Array.isArray(curr)) {\n if (JSON.stringify(orig) !== JSON.stringify(curr)) {\n changes.push({ path, from: orig, to: curr });\n }\n return;\n }\n const origObj = orig as Record;\n const currObj = curr as Record;\n const allKeys = new Set([...Object.keys(origObj), ...Object.keys(currObj)]);\n for (const key of allKeys) {\n compare(origObj[key], currObj[key], path ? `${path}.${key}` : key);\n }\n }\n \n compare(original, current, \"\");\n return changes;\n}\n\nfunction truncateValue(value: unknown, maxLen = 40): string {\n let str: string;\n try {\n const json = JSON.stringify(value);\n str = json ?? String(value);\n } catch {\n str = String(value);\n }\n if (str.length <= maxLen) return str;\n return str.slice(0, maxLen - 3) + \"...\";\n}\n\nexport function renderConfig(props: ConfigProps) {\n const validity =\n props.valid == null ? \"unknown\" : props.valid ? \"valid\" : \"invalid\";\n const analysis = analyzeConfigSchema(props.schema);\n const formUnsafe = analysis.schema\n ? analysis.unsupportedPaths.length > 0\n : false;\n\n // Get available sections from schema\n const schemaProps = analysis.schema?.properties ?? {};\n const availableSections = SECTIONS.filter(s => s.key in schemaProps);\n\n // Add any sections in schema but not in our list\n const knownKeys = new Set(SECTIONS.map(s => s.key));\n const extraSections = Object.keys(schemaProps)\n .filter(k => !knownKeys.has(k))\n .map(k => ({ key: k, label: k.charAt(0).toUpperCase() + k.slice(1) }));\n\n const allSections = [...availableSections, ...extraSections];\n\n const activeSectionSchema =\n props.activeSection && analysis.schema && schemaType(analysis.schema) === \"object\"\n ? (analysis.schema.properties?.[props.activeSection] as JsonSchema | undefined)\n : undefined;\n const activeSectionMeta = props.activeSection\n ? resolveSectionMeta(props.activeSection, activeSectionSchema)\n : null;\n const subsections = props.activeSection\n ? resolveSubsections({\n key: props.activeSection,\n schema: activeSectionSchema,\n uiHints: props.uiHints,\n })\n : [];\n const allowSubnav =\n props.formMode === \"form\" &&\n Boolean(props.activeSection) &&\n subsections.length > 0;\n const isAllSubsection = props.activeSubsection === ALL_SUBSECTION;\n const effectiveSubsection = props.searchQuery\n ? null\n : isAllSubsection\n ? null\n : props.activeSubsection ?? (subsections[0]?.key ?? null);\n\n // Compute diff for showing changes (works for both form and raw modes)\n const diff = props.formMode === \"form\"\n ? computeDiff(props.originalValue, props.formValue)\n : [];\n const hasRawChanges = props.formMode === \"raw\" && props.raw !== props.originalRaw;\n const hasChanges = props.formMode === \"form\" ? diff.length > 0 : hasRawChanges;\n\n // Save/apply buttons require actual changes to be enabled.\n // Note: formUnsafe warns about unsupported schema paths but shouldn't block saving.\n const canSaveForm =\n Boolean(props.formValue) && !props.loading && Boolean(analysis.schema);\n const canSave =\n props.connected &&\n !props.saving &&\n hasChanges &&\n (props.formMode === \"raw\" ? true : canSaveForm);\n const canApply =\n props.connected &&\n !props.applying &&\n !props.updating &&\n hasChanges &&\n (props.formMode === \"raw\" ? true : canSaveForm);\n const canUpdate = props.connected && !props.applying && !props.updating;\n\n return html`\n
    \n \n \n \n \n
    \n \n
    \n
    \n ${hasChanges ? html`\n ${props.formMode === \"raw\" ? \"Unsaved changes\" : `${diff.length} unsaved change${diff.length !== 1 ? \"s\" : \"\"}`}\n ` : html`\n No changes\n `}\n
    \n
    \n \n \n ${props.saving ? \"Saving…\" : \"Save\"}\n \n \n ${props.applying ? \"Applying…\" : \"Apply\"}\n \n \n ${props.updating ? \"Updating…\" : \"Update\"}\n \n
    \n
    \n \n \n ${hasChanges && props.formMode === \"form\" ? html`\n
    \n \n View ${diff.length} pending change${diff.length !== 1 ? \"s\" : \"\"}\n \n \n \n \n
    \n ${diff.map(change => html`\n
    \n
    ${change.path}
    \n
    \n ${truncateValue(change.from)}\n \n ${truncateValue(change.to)}\n
    \n
    \n `)}\n
    \n
    \n ` : nothing}\n\n ${activeSectionMeta && props.formMode === \"form\"\n ? html`\n
    \n
    ${getSectionIcon(props.activeSection ?? \"\")}
    \n
    \n
    ${activeSectionMeta.label}
    \n ${activeSectionMeta.description\n ? html`
    ${activeSectionMeta.description}
    `\n : nothing}\n
    \n
    \n `\n : nothing}\n\n ${allowSubnav\n ? html`\n
    \n props.onSubsectionChange(ALL_SUBSECTION)}\n >\n All\n \n ${subsections.map(\n (entry) => html`\n props.onSubsectionChange(entry.key)}\n >\n ${entry.label}\n \n `,\n )}\n
    \n `\n : nothing}\n\n \n
    \n ${props.formMode === \"form\"\n ? html`\n ${props.schemaLoading\n ? html`
    \n
    \n Loading schema…\n
    `\n : renderConfigForm({\n schema: analysis.schema,\n uiHints: props.uiHints,\n value: props.formValue,\n disabled: props.loading || !props.formValue,\n unsupportedPaths: analysis.unsupportedPaths,\n onPatch: props.onFormPatch,\n searchQuery: props.searchQuery,\n activeSection: props.activeSection,\n activeSubsection: effectiveSubsection,\n })}\n ${formUnsafe\n ? html`
    \n Form view can't safely edit some fields.\n Use Raw to avoid losing config entries.\n
    `\n : nothing}\n `\n : html`\n \n `}\n
    \n\n ${props.issues.length > 0\n ? html`
    \n
    ${JSON.stringify(props.issues, null, 2)}
    \n
    `\n : nothing}\n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport type { ChannelAccountSnapshot } from \"../types\";\nimport type { ChannelKey, ChannelsProps } from \"./channels.types\";\n\nexport function formatDuration(ms?: number | null) {\n if (!ms && ms !== 0) return \"n/a\";\n const sec = Math.round(ms / 1000);\n if (sec < 60) return `${sec}s`;\n const min = Math.round(sec / 60);\n if (min < 60) return `${min}m`;\n const hr = Math.round(min / 60);\n return `${hr}h`;\n}\n\nexport function channelEnabled(key: ChannelKey, props: ChannelsProps) {\n const snapshot = props.snapshot;\n const channels = snapshot?.channels as Record | null;\n if (!snapshot || !channels) return false;\n const channelStatus = channels[key] as Record | undefined;\n const configured = typeof channelStatus?.configured === \"boolean\" && channelStatus.configured;\n const running = typeof channelStatus?.running === \"boolean\" && channelStatus.running;\n const connected = typeof channelStatus?.connected === \"boolean\" && channelStatus.connected;\n const accounts = snapshot.channelAccounts?.[key] ?? [];\n const accountActive = accounts.some(\n (account) => account.configured || account.running || account.connected,\n );\n return configured || running || connected || accountActive;\n}\n\nexport function getChannelAccountCount(\n key: ChannelKey,\n channelAccounts?: Record | null,\n): number {\n return channelAccounts?.[key]?.length ?? 0;\n}\n\nexport function renderChannelAccountCount(\n key: ChannelKey,\n channelAccounts?: Record | null,\n) {\n const count = getChannelAccountCount(key, channelAccounts);\n if (count < 2) return nothing;\n return html`
    Accounts (${count})
    `;\n}\n\n","import { html } from \"lit\";\n\nimport type { ConfigUiHints } from \"../types\";\nimport type { ChannelsProps } from \"./channels.types\";\nimport {\n analyzeConfigSchema,\n renderNode,\n schemaType,\n type JsonSchema,\n} from \"./config-form\";\n\ntype ChannelConfigFormProps = {\n channelId: string;\n configValue: Record | null;\n schema: unknown | null;\n uiHints: ConfigUiHints;\n disabled: boolean;\n onPatch: (path: Array, value: unknown) => void;\n};\n\nfunction resolveSchemaNode(\n schema: JsonSchema | null,\n path: Array,\n): JsonSchema | null {\n let current = schema;\n for (const key of path) {\n if (!current) return null;\n const type = schemaType(current);\n if (type === \"object\") {\n const properties = current.properties ?? {};\n if (typeof key === \"string\" && properties[key]) {\n current = properties[key];\n continue;\n }\n const additional = current.additionalProperties;\n if (typeof key === \"string\" && additional && typeof additional === \"object\") {\n current = additional as JsonSchema;\n continue;\n }\n return null;\n }\n if (type === \"array\") {\n if (typeof key !== \"number\") return null;\n const items = Array.isArray(current.items) ? current.items[0] : current.items;\n current = items ?? null;\n continue;\n }\n return null;\n }\n return current;\n}\n\nfunction resolveChannelValue(\n config: Record,\n channelId: string,\n): Record {\n const channels = (config.channels ?? {}) as Record;\n const fromChannels = channels[channelId];\n const fallback = config[channelId];\n const resolved =\n (fromChannels && typeof fromChannels === \"object\"\n ? (fromChannels as Record)\n : null) ??\n (fallback && typeof fallback === \"object\"\n ? (fallback as Record)\n : null);\n return resolved ?? {};\n}\n\nexport function renderChannelConfigForm(props: ChannelConfigFormProps) {\n const analysis = analyzeConfigSchema(props.schema);\n const normalized = analysis.schema;\n if (!normalized) {\n return html`
    Schema unavailable. Use Raw.
    `;\n }\n const node = resolveSchemaNode(normalized, [\"channels\", props.channelId]);\n if (!node) {\n return html`
    Channel config schema unavailable.
    `;\n }\n const configValue = props.configValue ?? {};\n const value = resolveChannelValue(configValue, props.channelId);\n return html`\n
    \n ${renderNode({\n schema: node,\n value,\n path: [\"channels\", props.channelId],\n hints: props.uiHints,\n unsupported: new Set(analysis.unsupportedPaths),\n disabled: props.disabled,\n showLabel: false,\n onPatch: props.onPatch,\n })}\n
    \n `;\n}\n\nexport function renderChannelConfigSection(params: {\n channelId: string;\n props: ChannelsProps;\n}) {\n const { channelId, props } = params;\n const disabled = props.configSaving || props.configSchemaLoading;\n return html`\n
    \n ${props.configSchemaLoading\n ? html`
    Loading config schema…
    `\n : renderChannelConfigForm({\n channelId,\n configValue: props.configForm,\n schema: props.configSchema,\n uiHints: props.configUiHints,\n disabled,\n onPatch: props.onConfigPatch,\n })}\n
    \n props.onConfigSave()}\n >\n ${props.configSaving ? \"Saving…\" : \"Save\"}\n \n props.onConfigReload()}\n >\n Reload\n \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatAgo } from \"../format\";\nimport type { DiscordStatus } from \"../types\";\nimport type { ChannelsProps } from \"./channels.types\";\nimport { renderChannelConfigSection } from \"./channels.config\";\n\nexport function renderDiscordCard(params: {\n props: ChannelsProps;\n discord?: DiscordStatus | null;\n accountCountLabel: unknown;\n}) {\n const { props, discord, accountCountLabel } = params;\n\n return html`\n
    \n
    Discord
    \n
    Bot status and channel configuration.
    \n ${accountCountLabel}\n\n
    \n
    \n Configured\n ${discord?.configured ? \"Yes\" : \"No\"}\n
    \n
    \n Running\n ${discord?.running ? \"Yes\" : \"No\"}\n
    \n
    \n Last start\n ${discord?.lastStartAt ? formatAgo(discord.lastStartAt) : \"n/a\"}\n
    \n
    \n Last probe\n ${discord?.lastProbeAt ? formatAgo(discord.lastProbeAt) : \"n/a\"}\n
    \n
    \n\n ${discord?.lastError\n ? html`
    \n ${discord.lastError}\n
    `\n : nothing}\n\n ${discord?.probe\n ? html`
    \n Probe ${discord.probe.ok ? \"ok\" : \"failed\"} ·\n ${discord.probe.status ?? \"\"} ${discord.probe.error ?? \"\"}\n
    `\n : nothing}\n\n ${renderChannelConfigSection({ channelId: \"discord\", props })}\n\n
    \n \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatAgo } from \"../format\";\nimport type { GoogleChatStatus } from \"../types\";\nimport { renderChannelConfigSection } from \"./channels.config\";\nimport type { ChannelsProps } from \"./channels.types\";\n\nexport function renderGoogleChatCard(params: {\n props: ChannelsProps;\n googleChat?: GoogleChatStatus | null;\n accountCountLabel: unknown;\n}) {\n const { props, googleChat, accountCountLabel } = params;\n\n return html`\n
    \n
    Google Chat
    \n
    Chat API webhook status and channel configuration.
    \n ${accountCountLabel}\n\n
    \n
    \n Configured\n ${googleChat ? (googleChat.configured ? \"Yes\" : \"No\") : \"n/a\"}\n
    \n
    \n Running\n ${googleChat ? (googleChat.running ? \"Yes\" : \"No\") : \"n/a\"}\n
    \n
    \n Credential\n ${googleChat?.credentialSource ?? \"n/a\"}\n
    \n
    \n Audience\n \n ${googleChat?.audienceType\n ? `${googleChat.audienceType}${googleChat.audience ? ` · ${googleChat.audience}` : \"\"}`\n : \"n/a\"}\n \n
    \n
    \n Last start\n ${googleChat?.lastStartAt ? formatAgo(googleChat.lastStartAt) : \"n/a\"}\n
    \n
    \n Last probe\n ${googleChat?.lastProbeAt ? formatAgo(googleChat.lastProbeAt) : \"n/a\"}\n
    \n
    \n\n ${googleChat?.lastError\n ? html`
    \n ${googleChat.lastError}\n
    `\n : nothing}\n\n ${googleChat?.probe\n ? html`
    \n Probe ${googleChat.probe.ok ? \"ok\" : \"failed\"} ·\n ${googleChat.probe.status ?? \"\"} ${googleChat.probe.error ?? \"\"}\n
    `\n : nothing}\n\n ${renderChannelConfigSection({ channelId: \"googlechat\", props })}\n\n
    \n \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatAgo } from \"../format\";\nimport type { IMessageStatus } from \"../types\";\nimport type { ChannelsProps } from \"./channels.types\";\nimport { renderChannelConfigSection } from \"./channels.config\";\n\nexport function renderIMessageCard(params: {\n props: ChannelsProps;\n imessage?: IMessageStatus | null;\n accountCountLabel: unknown;\n}) {\n const { props, imessage, accountCountLabel } = params;\n\n return html`\n
    \n
    iMessage
    \n
    macOS bridge status and channel configuration.
    \n ${accountCountLabel}\n\n
    \n
    \n Configured\n ${imessage?.configured ? \"Yes\" : \"No\"}\n
    \n
    \n Running\n ${imessage?.running ? \"Yes\" : \"No\"}\n
    \n
    \n Last start\n ${imessage?.lastStartAt ? formatAgo(imessage.lastStartAt) : \"n/a\"}\n
    \n
    \n Last probe\n ${imessage?.lastProbeAt ? formatAgo(imessage.lastProbeAt) : \"n/a\"}\n
    \n
    \n\n ${imessage?.lastError\n ? html`
    \n ${imessage.lastError}\n
    `\n : nothing}\n\n ${imessage?.probe\n ? html`
    \n Probe ${imessage.probe.ok ? \"ok\" : \"failed\"} ·\n ${imessage.probe.error ?? \"\"}\n
    `\n : nothing}\n\n ${renderChannelConfigSection({ channelId: \"imessage\", props })}\n\n
    \n \n
    \n
    \n `;\n}\n","/**\n * Nostr Profile Edit Form\n *\n * Provides UI for editing and publishing Nostr profile (kind:0).\n */\n\nimport { html, nothing, type TemplateResult } from \"lit\";\n\nimport type { NostrProfile as NostrProfileType } from \"../types\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface NostrProfileFormState {\n /** Current form values */\n values: NostrProfileType;\n /** Original values for dirty detection */\n original: NostrProfileType;\n /** Whether the form is currently submitting */\n saving: boolean;\n /** Whether import is in progress */\n importing: boolean;\n /** Last error message */\n error: string | null;\n /** Last success message */\n success: string | null;\n /** Validation errors per field */\n fieldErrors: Record;\n /** Whether to show advanced fields */\n showAdvanced: boolean;\n}\n\nexport interface NostrProfileFormCallbacks {\n /** Called when a field value changes */\n onFieldChange: (field: keyof NostrProfileType, value: string) => void;\n /** Called when save is clicked */\n onSave: () => void;\n /** Called when import is clicked */\n onImport: () => void;\n /** Called when cancel is clicked */\n onCancel: () => void;\n /** Called when toggle advanced is clicked */\n onToggleAdvanced: () => void;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction isFormDirty(state: NostrProfileFormState): boolean {\n const { values, original } = state;\n return (\n values.name !== original.name ||\n values.displayName !== original.displayName ||\n values.about !== original.about ||\n values.picture !== original.picture ||\n values.banner !== original.banner ||\n values.website !== original.website ||\n values.nip05 !== original.nip05 ||\n values.lud16 !== original.lud16\n );\n}\n\n// ============================================================================\n// Form Rendering\n// ============================================================================\n\nexport function renderNostrProfileForm(params: {\n state: NostrProfileFormState;\n callbacks: NostrProfileFormCallbacks;\n accountId: string;\n}): TemplateResult {\n const { state, callbacks, accountId } = params;\n const isDirty = isFormDirty(state);\n\n const renderField = (\n field: keyof NostrProfileType,\n label: string,\n opts: {\n type?: \"text\" | \"url\" | \"textarea\";\n placeholder?: string;\n maxLength?: number;\n help?: string;\n } = {}\n ) => {\n const { type = \"text\", placeholder, maxLength, help } = opts;\n const value = state.values[field] ?? \"\";\n const error = state.fieldErrors[field];\n\n const inputId = `nostr-profile-${field}`;\n\n if (type === \"textarea\") {\n return html`\n
    \n \n {\n const target = e.target as HTMLTextAreaElement;\n callbacks.onFieldChange(field, target.value);\n }}\n ?disabled=${state.saving}\n >\n ${help ? html`
    ${help}
    ` : nothing}\n ${error ? html`
    ${error}
    ` : nothing}\n
    \n `;\n }\n\n return html`\n
    \n \n {\n const target = e.target as HTMLInputElement;\n callbacks.onFieldChange(field, target.value);\n }}\n ?disabled=${state.saving}\n />\n ${help ? html`
    ${help}
    ` : nothing}\n ${error ? html`
    ${error}
    ` : nothing}\n
    \n `;\n };\n\n const renderPicturePreview = () => {\n const picture = state.values.picture;\n if (!picture) return nothing;\n\n return html`\n
    \n {\n const img = e.target as HTMLImageElement;\n img.style.display = \"none\";\n }}\n @load=${(e: Event) => {\n const img = e.target as HTMLImageElement;\n img.style.display = \"block\";\n }}\n />\n
    \n `;\n };\n\n return html`\n
    \n
    \n
    Edit Profile
    \n
    Account: ${accountId}
    \n
    \n\n ${state.error\n ? html`
    ${state.error}
    `\n : nothing}\n\n ${state.success\n ? html`
    ${state.success}
    `\n : nothing}\n\n ${renderPicturePreview()}\n\n ${renderField(\"name\", \"Username\", {\n placeholder: \"satoshi\",\n maxLength: 256,\n help: \"Short username (e.g., satoshi)\",\n })}\n\n ${renderField(\"displayName\", \"Display Name\", {\n placeholder: \"Satoshi Nakamoto\",\n maxLength: 256,\n help: \"Your full display name\",\n })}\n\n ${renderField(\"about\", \"Bio\", {\n type: \"textarea\",\n placeholder: \"Tell people about yourself...\",\n maxLength: 2000,\n help: \"A brief bio or description\",\n })}\n\n ${renderField(\"picture\", \"Avatar URL\", {\n type: \"url\",\n placeholder: \"https://example.com/avatar.jpg\",\n help: \"HTTPS URL to your profile picture\",\n })}\n\n ${state.showAdvanced\n ? html`\n
    \n
    Advanced
    \n\n ${renderField(\"banner\", \"Banner URL\", {\n type: \"url\",\n placeholder: \"https://example.com/banner.jpg\",\n help: \"HTTPS URL to a banner image\",\n })}\n\n ${renderField(\"website\", \"Website\", {\n type: \"url\",\n placeholder: \"https://example.com\",\n help: \"Your personal website\",\n })}\n\n ${renderField(\"nip05\", \"NIP-05 Identifier\", {\n placeholder: \"you@example.com\",\n help: \"Verifiable identifier (e.g., you@domain.com)\",\n })}\n\n ${renderField(\"lud16\", \"Lightning Address\", {\n placeholder: \"you@getalby.com\",\n help: \"Lightning address for tips (LUD-16)\",\n })}\n
    \n `\n : nothing}\n\n
    \n \n ${state.saving ? \"Saving...\" : \"Save & Publish\"}\n \n\n \n ${state.importing ? \"Importing...\" : \"Import from Relays\"}\n \n\n \n ${state.showAdvanced ? \"Hide Advanced\" : \"Show Advanced\"}\n \n\n \n Cancel\n \n
    \n\n ${isDirty\n ? html`
    \n You have unsaved changes\n
    `\n : nothing}\n
    \n `;\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\n/**\n * Create initial form state from existing profile\n */\nexport function createNostrProfileFormState(\n profile: NostrProfileType | undefined\n): NostrProfileFormState {\n const values: NostrProfileType = {\n name: profile?.name ?? \"\",\n displayName: profile?.displayName ?? \"\",\n about: profile?.about ?? \"\",\n picture: profile?.picture ?? \"\",\n banner: profile?.banner ?? \"\",\n website: profile?.website ?? \"\",\n nip05: profile?.nip05 ?? \"\",\n lud16: profile?.lud16 ?? \"\",\n };\n\n return {\n values,\n original: { ...values },\n saving: false,\n importing: false,\n error: null,\n success: null,\n fieldErrors: {},\n showAdvanced: Boolean(\n profile?.banner || profile?.website || profile?.nip05 || profile?.lud16\n ),\n };\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatAgo } from \"../format\";\nimport type { ChannelAccountSnapshot, NostrStatus } from \"../types\";\nimport type { ChannelsProps } from \"./channels.types\";\nimport { renderChannelConfigSection } from \"./channels.config\";\nimport {\n renderNostrProfileForm,\n type NostrProfileFormState,\n type NostrProfileFormCallbacks,\n} from \"./channels.nostr-profile-form\";\n\n/**\n * Truncate a pubkey for display (shows first and last 8 chars)\n */\nfunction truncatePubkey(pubkey: string | null | undefined): string {\n if (!pubkey) return \"n/a\";\n if (pubkey.length <= 20) return pubkey;\n return `${pubkey.slice(0, 8)}...${pubkey.slice(-8)}`;\n}\n\nexport function renderNostrCard(params: {\n props: ChannelsProps;\n nostr?: NostrStatus | null;\n nostrAccounts: ChannelAccountSnapshot[];\n accountCountLabel: unknown;\n /** Profile form state (optional - if provided, shows form) */\n profileFormState?: NostrProfileFormState | null;\n /** Profile form callbacks */\n profileFormCallbacks?: NostrProfileFormCallbacks | null;\n /** Called when Edit Profile is clicked */\n onEditProfile?: () => void;\n}) {\n const {\n props,\n nostr,\n nostrAccounts,\n accountCountLabel,\n profileFormState,\n profileFormCallbacks,\n onEditProfile,\n } = params;\n const primaryAccount = nostrAccounts[0];\n const summaryConfigured = nostr?.configured ?? primaryAccount?.configured ?? false;\n const summaryRunning = nostr?.running ?? primaryAccount?.running ?? false;\n const summaryPublicKey =\n nostr?.publicKey ??\n (primaryAccount as { publicKey?: string } | undefined)?.publicKey;\n const summaryLastStartAt = nostr?.lastStartAt ?? primaryAccount?.lastStartAt ?? null;\n const summaryLastError = nostr?.lastError ?? primaryAccount?.lastError ?? null;\n const hasMultipleAccounts = nostrAccounts.length > 1;\n const showingForm = profileFormState !== null && profileFormState !== undefined;\n\n const renderAccountCard = (account: ChannelAccountSnapshot) => {\n const publicKey = (account as { publicKey?: string }).publicKey;\n const profile = (account as { profile?: { name?: string; displayName?: string } }).profile;\n const displayName = profile?.displayName ?? profile?.name ?? account.name ?? account.accountId;\n\n return html`\n
    \n
    \n
    ${displayName}
    \n
    ${account.accountId}
    \n
    \n
    \n
    \n Running\n ${account.running ? \"Yes\" : \"No\"}\n
    \n
    \n Configured\n ${account.configured ? \"Yes\" : \"No\"}\n
    \n
    \n Public Key\n ${truncatePubkey(publicKey)}\n
    \n
    \n Last inbound\n ${account.lastInboundAt ? formatAgo(account.lastInboundAt) : \"n/a\"}\n
    \n ${account.lastError\n ? html`\n
    ${account.lastError}
    \n `\n : nothing}\n
    \n
    \n `;\n };\n\n const renderProfileSection = () => {\n // If showing form, render the form instead of the read-only view\n if (showingForm && profileFormCallbacks) {\n return renderNostrProfileForm({\n state: profileFormState,\n callbacks: profileFormCallbacks,\n accountId: nostrAccounts[0]?.accountId ?? \"default\",\n });\n }\n\n const profile =\n (primaryAccount as\n | {\n profile?: {\n name?: string;\n displayName?: string;\n about?: string;\n picture?: string;\n nip05?: string;\n };\n }\n | undefined)?.profile ?? nostr?.profile;\n const { name, displayName, about, picture, nip05 } = profile ?? {};\n const hasAnyProfileData = name || displayName || about || picture || nip05;\n\n return html`\n
    \n
    \n
    Profile
    \n ${summaryConfigured\n ? html`\n \n Edit Profile\n \n `\n : nothing}\n
    \n ${hasAnyProfileData\n ? html`\n
    \n ${picture\n ? html`\n
    \n {\n (e.target as HTMLImageElement).style.display = \"none\";\n }}\n />\n
    \n `\n : nothing}\n ${name ? html`
    Name${name}
    ` : nothing}\n ${displayName\n ? html`
    Display Name${displayName}
    `\n : nothing}\n ${about\n ? html`
    About${about}
    `\n : nothing}\n ${nip05 ? html`
    NIP-05${nip05}
    ` : nothing}\n
    \n `\n : html`\n
    \n No profile set. Click \"Edit Profile\" to add your name, bio, and avatar.\n
    \n `}\n
    \n `;\n };\n\n return html`\n
    \n
    Nostr
    \n
    Decentralized DMs via Nostr relays (NIP-04).
    \n ${accountCountLabel}\n\n ${hasMultipleAccounts\n ? html`\n
    \n ${nostrAccounts.map((account) => renderAccountCard(account))}\n
    \n `\n : html`\n
    \n
    \n Configured\n ${summaryConfigured ? \"Yes\" : \"No\"}\n
    \n
    \n Running\n ${summaryRunning ? \"Yes\" : \"No\"}\n
    \n
    \n Public Key\n ${truncatePubkey(summaryPublicKey)}\n
    \n
    \n Last start\n ${summaryLastStartAt ? formatAgo(summaryLastStartAt) : \"n/a\"}\n
    \n
    \n `}\n\n ${summaryLastError\n ? html`
    ${summaryLastError}
    `\n : nothing}\n\n ${renderProfileSection()}\n\n ${renderChannelConfigSection({ channelId: \"nostr\", props })}\n\n
    \n \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatAgo } from \"../format\";\nimport type { SignalStatus } from \"../types\";\nimport type { ChannelsProps } from \"./channels.types\";\nimport { renderChannelConfigSection } from \"./channels.config\";\n\nexport function renderSignalCard(params: {\n props: ChannelsProps;\n signal?: SignalStatus | null;\n accountCountLabel: unknown;\n}) {\n const { props, signal, accountCountLabel } = params;\n\n return html`\n
    \n
    Signal
    \n
    signal-cli status and channel configuration.
    \n ${accountCountLabel}\n\n
    \n
    \n Configured\n ${signal?.configured ? \"Yes\" : \"No\"}\n
    \n
    \n Running\n ${signal?.running ? \"Yes\" : \"No\"}\n
    \n
    \n Base URL\n ${signal?.baseUrl ?? \"n/a\"}\n
    \n
    \n Last start\n ${signal?.lastStartAt ? formatAgo(signal.lastStartAt) : \"n/a\"}\n
    \n
    \n Last probe\n ${signal?.lastProbeAt ? formatAgo(signal.lastProbeAt) : \"n/a\"}\n
    \n
    \n\n ${signal?.lastError\n ? html`
    \n ${signal.lastError}\n
    `\n : nothing}\n\n ${signal?.probe\n ? html`
    \n Probe ${signal.probe.ok ? \"ok\" : \"failed\"} ·\n ${signal.probe.status ?? \"\"} ${signal.probe.error ?? \"\"}\n
    `\n : nothing}\n\n ${renderChannelConfigSection({ channelId: \"signal\", props })}\n\n
    \n \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatAgo } from \"../format\";\nimport type { SlackStatus } from \"../types\";\nimport type { ChannelsProps } from \"./channels.types\";\nimport { renderChannelConfigSection } from \"./channels.config\";\n\nexport function renderSlackCard(params: {\n props: ChannelsProps;\n slack?: SlackStatus | null;\n accountCountLabel: unknown;\n}) {\n const { props, slack, accountCountLabel } = params;\n\n return html`\n
    \n
    Slack
    \n
    Socket mode status and channel configuration.
    \n ${accountCountLabel}\n\n
    \n
    \n Configured\n ${slack?.configured ? \"Yes\" : \"No\"}\n
    \n
    \n Running\n ${slack?.running ? \"Yes\" : \"No\"}\n
    \n
    \n Last start\n ${slack?.lastStartAt ? formatAgo(slack.lastStartAt) : \"n/a\"}\n
    \n
    \n Last probe\n ${slack?.lastProbeAt ? formatAgo(slack.lastProbeAt) : \"n/a\"}\n
    \n
    \n\n ${slack?.lastError\n ? html`
    \n ${slack.lastError}\n
    `\n : nothing}\n\n ${slack?.probe\n ? html`
    \n Probe ${slack.probe.ok ? \"ok\" : \"failed\"} ·\n ${slack.probe.status ?? \"\"} ${slack.probe.error ?? \"\"}\n
    `\n : nothing}\n\n ${renderChannelConfigSection({ channelId: \"slack\", props })}\n\n
    \n \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatAgo } from \"../format\";\nimport type { ChannelAccountSnapshot, TelegramStatus } from \"../types\";\nimport type { ChannelsProps } from \"./channels.types\";\nimport { renderChannelConfigSection } from \"./channels.config\";\n\nexport function renderTelegramCard(params: {\n props: ChannelsProps;\n telegram?: TelegramStatus;\n telegramAccounts: ChannelAccountSnapshot[];\n accountCountLabel: unknown;\n}) {\n const { props, telegram, telegramAccounts, accountCountLabel } = params;\n const hasMultipleAccounts = telegramAccounts.length > 1;\n\n const renderAccountCard = (account: ChannelAccountSnapshot) => {\n const probe = account.probe as { bot?: { username?: string } } | undefined;\n const botUsername = probe?.bot?.username;\n const label = account.name || account.accountId;\n return html`\n
    \n
    \n
    \n ${botUsername ? `@${botUsername}` : label}\n
    \n
    ${account.accountId}
    \n
    \n
    \n
    \n Running\n ${account.running ? \"Yes\" : \"No\"}\n
    \n
    \n Configured\n ${account.configured ? \"Yes\" : \"No\"}\n
    \n
    \n Last inbound\n ${account.lastInboundAt ? formatAgo(account.lastInboundAt) : \"n/a\"}\n
    \n ${account.lastError\n ? html`\n
    \n ${account.lastError}\n
    \n `\n : nothing}\n
    \n
    \n `;\n };\n\n return html`\n
    \n
    Telegram
    \n
    Bot status and channel configuration.
    \n ${accountCountLabel}\n\n ${hasMultipleAccounts\n ? html`\n
    \n ${telegramAccounts.map((account) => renderAccountCard(account))}\n
    \n `\n : html`\n
    \n
    \n Configured\n ${telegram?.configured ? \"Yes\" : \"No\"}\n
    \n
    \n Running\n ${telegram?.running ? \"Yes\" : \"No\"}\n
    \n
    \n Mode\n ${telegram?.mode ?? \"n/a\"}\n
    \n
    \n Last start\n ${telegram?.lastStartAt ? formatAgo(telegram.lastStartAt) : \"n/a\"}\n
    \n
    \n Last probe\n ${telegram?.lastProbeAt ? formatAgo(telegram.lastProbeAt) : \"n/a\"}\n
    \n
    \n `}\n\n ${telegram?.lastError\n ? html`
    \n ${telegram.lastError}\n
    `\n : nothing}\n\n ${telegram?.probe\n ? html`
    \n Probe ${telegram.probe.ok ? \"ok\" : \"failed\"} ·\n ${telegram.probe.status ?? \"\"} ${telegram.probe.error ?? \"\"}\n
    `\n : nothing}\n\n ${renderChannelConfigSection({ channelId: \"telegram\", props })}\n\n
    \n \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatAgo } from \"../format\";\nimport type { WhatsAppStatus } from \"../types\";\nimport type { ChannelsProps } from \"./channels.types\";\nimport { renderChannelConfigSection } from \"./channels.config\";\nimport { formatDuration } from \"./channels.shared\";\n\nexport function renderWhatsAppCard(params: {\n props: ChannelsProps;\n whatsapp?: WhatsAppStatus;\n accountCountLabel: unknown;\n}) {\n const { props, whatsapp, accountCountLabel } = params;\n\n return html`\n
    \n
    WhatsApp
    \n
    Link WhatsApp Web and monitor connection health.
    \n ${accountCountLabel}\n\n
    \n
    \n Configured\n ${whatsapp?.configured ? \"Yes\" : \"No\"}\n
    \n
    \n Linked\n ${whatsapp?.linked ? \"Yes\" : \"No\"}\n
    \n
    \n Running\n ${whatsapp?.running ? \"Yes\" : \"No\"}\n
    \n
    \n Connected\n ${whatsapp?.connected ? \"Yes\" : \"No\"}\n
    \n
    \n Last connect\n \n ${whatsapp?.lastConnectedAt\n ? formatAgo(whatsapp.lastConnectedAt)\n : \"n/a\"}\n \n
    \n
    \n Last message\n \n ${whatsapp?.lastMessageAt ? formatAgo(whatsapp.lastMessageAt) : \"n/a\"}\n \n
    \n
    \n Auth age\n \n ${whatsapp?.authAgeMs != null\n ? formatDuration(whatsapp.authAgeMs)\n : \"n/a\"}\n \n
    \n
    \n\n ${whatsapp?.lastError\n ? html`
    \n ${whatsapp.lastError}\n
    `\n : nothing}\n\n ${props.whatsappMessage\n ? html`
    \n ${props.whatsappMessage}\n
    `\n : nothing}\n\n ${props.whatsappQrDataUrl\n ? html`
    \n \"WhatsApp\n
    `\n : nothing}\n\n
    \n props.onWhatsAppStart(false)}\n >\n ${props.whatsappBusy ? \"Working…\" : \"Show QR\"}\n \n props.onWhatsAppStart(true)}\n >\n Relink\n \n props.onWhatsAppWait()}\n >\n Wait for scan\n \n props.onWhatsAppLogout()}\n >\n Logout\n \n \n
    \n\n ${renderChannelConfigSection({ channelId: \"whatsapp\", props })}\n
    \n `;\n}\n\n","import { html, nothing } from \"lit\";\n\nimport { formatAgo } from \"../format\";\nimport type {\n ChannelAccountSnapshot,\n ChannelUiMetaEntry,\n ChannelsStatusSnapshot,\n DiscordStatus,\n GoogleChatStatus,\n IMessageStatus,\n NostrProfile,\n NostrStatus,\n SignalStatus,\n SlackStatus,\n TelegramStatus,\n WhatsAppStatus,\n} from \"../types\";\nimport type {\n ChannelKey,\n ChannelsChannelData,\n ChannelsProps,\n} from \"./channels.types\";\nimport { channelEnabled, renderChannelAccountCount } from \"./channels.shared\";\nimport { renderChannelConfigSection } from \"./channels.config\";\nimport { renderDiscordCard } from \"./channels.discord\";\nimport { renderGoogleChatCard } from \"./channels.googlechat\";\nimport { renderIMessageCard } from \"./channels.imessage\";\nimport { renderNostrCard } from \"./channels.nostr\";\nimport { renderSignalCard } from \"./channels.signal\";\nimport { renderSlackCard } from \"./channels.slack\";\nimport { renderTelegramCard } from \"./channels.telegram\";\nimport { renderWhatsAppCard } from \"./channels.whatsapp\";\n\nexport function renderChannels(props: ChannelsProps) {\n const channels = props.snapshot?.channels as Record | null;\n const whatsapp = (channels?.whatsapp ?? undefined) as\n | WhatsAppStatus\n | undefined;\n const telegram = (channels?.telegram ?? undefined) as\n | TelegramStatus\n | undefined;\n const discord = (channels?.discord ?? null) as DiscordStatus | null;\n const googlechat = (channels?.googlechat ?? null) as GoogleChatStatus | null;\n const slack = (channels?.slack ?? null) as SlackStatus | null;\n const signal = (channels?.signal ?? null) as SignalStatus | null;\n const imessage = (channels?.imessage ?? null) as IMessageStatus | null;\n const nostr = (channels?.nostr ?? null) as NostrStatus | null;\n const channelOrder = resolveChannelOrder(props.snapshot);\n const orderedChannels = channelOrder\n .map((key, index) => ({\n key,\n enabled: channelEnabled(key, props),\n order: index,\n }))\n .sort((a, b) => {\n if (a.enabled !== b.enabled) return a.enabled ? -1 : 1;\n return a.order - b.order;\n });\n\n return html`\n
    \n ${orderedChannels.map((channel) =>\n renderChannel(channel.key, props, {\n whatsapp,\n telegram,\n discord,\n googlechat,\n slack,\n signal,\n imessage,\n nostr,\n channelAccounts: props.snapshot?.channelAccounts ?? null,\n }),\n )}\n
    \n\n
    \n
    \n
    \n
    Channel health
    \n
    Channel status snapshots from the gateway.
    \n
    \n
    ${props.lastSuccessAt ? formatAgo(props.lastSuccessAt) : \"n/a\"}
    \n
    \n ${props.lastError\n ? html`
    \n ${props.lastError}\n
    `\n : nothing}\n
    \n${props.snapshot ? JSON.stringify(props.snapshot, null, 2) : \"No snapshot yet.\"}\n      
    \n
    \n `;\n}\n\nfunction resolveChannelOrder(snapshot: ChannelsStatusSnapshot | null): ChannelKey[] {\n if (snapshot?.channelMeta?.length) {\n return snapshot.channelMeta.map((entry) => entry.id) as ChannelKey[];\n }\n if (snapshot?.channelOrder?.length) {\n return snapshot.channelOrder;\n }\n return [\n \"whatsapp\",\n \"telegram\",\n \"discord\",\n \"googlechat\",\n \"slack\",\n \"signal\",\n \"imessage\",\n \"nostr\",\n ];\n}\n\nfunction renderChannel(\n key: ChannelKey,\n props: ChannelsProps,\n data: ChannelsChannelData,\n) {\n const accountCountLabel = renderChannelAccountCount(\n key,\n data.channelAccounts,\n );\n switch (key) {\n case \"whatsapp\":\n return renderWhatsAppCard({\n props,\n whatsapp: data.whatsapp,\n accountCountLabel,\n });\n case \"telegram\":\n return renderTelegramCard({\n props,\n telegram: data.telegram,\n telegramAccounts: data.channelAccounts?.telegram ?? [],\n accountCountLabel,\n });\n case \"discord\":\n return renderDiscordCard({\n props,\n discord: data.discord,\n accountCountLabel,\n });\n case \"googlechat\":\n return renderGoogleChatCard({\n props,\n googlechat: data.googlechat,\n accountCountLabel,\n });\n case \"slack\":\n return renderSlackCard({\n props,\n slack: data.slack,\n accountCountLabel,\n });\n case \"signal\":\n return renderSignalCard({\n props,\n signal: data.signal,\n accountCountLabel,\n });\n case \"imessage\":\n return renderIMessageCard({\n props,\n imessage: data.imessage,\n accountCountLabel,\n });\n case \"nostr\": {\n const nostrAccounts = data.channelAccounts?.nostr ?? [];\n const primaryAccount = nostrAccounts[0];\n const accountId = primaryAccount?.accountId ?? \"default\";\n const profile =\n (primaryAccount as { profile?: NostrProfile | null } | undefined)?.profile ?? null;\n const showForm =\n props.nostrProfileAccountId === accountId ? props.nostrProfileFormState : null;\n const profileFormCallbacks = showForm\n ? {\n onFieldChange: props.onNostrProfileFieldChange,\n onSave: props.onNostrProfileSave,\n onImport: props.onNostrProfileImport,\n onCancel: props.onNostrProfileCancel,\n onToggleAdvanced: props.onNostrProfileToggleAdvanced,\n }\n : null;\n return renderNostrCard({\n props,\n nostr: data.nostr,\n nostrAccounts,\n accountCountLabel,\n profileFormState: showForm,\n profileFormCallbacks,\n onEditProfile: () => props.onNostrProfileEdit(accountId, profile),\n });\n }\n default:\n return renderGenericChannelCard(key, props, data.channelAccounts ?? {});\n }\n}\n\nfunction renderGenericChannelCard(\n key: ChannelKey,\n props: ChannelsProps,\n channelAccounts: Record,\n) {\n const label = resolveChannelLabel(props.snapshot, key);\n const status = props.snapshot?.channels?.[key] as Record | undefined;\n const configured = typeof status?.configured === \"boolean\" ? status.configured : undefined;\n const running = typeof status?.running === \"boolean\" ? status.running : undefined;\n const connected = typeof status?.connected === \"boolean\" ? status.connected : undefined;\n const lastError = typeof status?.lastError === \"string\" ? status.lastError : undefined;\n const accounts = channelAccounts[key] ?? [];\n const accountCountLabel = renderChannelAccountCount(key, channelAccounts);\n\n return html`\n
    \n
    ${label}
    \n
    Channel status and configuration.
    \n ${accountCountLabel}\n\n ${accounts.length > 0\n ? html`\n
    \n ${accounts.map((account) => renderGenericAccount(account))}\n
    \n `\n : html`\n
    \n
    \n Configured\n ${configured == null ? \"n/a\" : configured ? \"Yes\" : \"No\"}\n
    \n
    \n Running\n ${running == null ? \"n/a\" : running ? \"Yes\" : \"No\"}\n
    \n
    \n Connected\n ${connected == null ? \"n/a\" : connected ? \"Yes\" : \"No\"}\n
    \n
    \n `}\n\n ${lastError\n ? html`
    \n ${lastError}\n
    `\n : nothing}\n\n ${renderChannelConfigSection({ channelId: key, props })}\n
    \n `;\n}\n\nfunction resolveChannelMetaMap(\n snapshot: ChannelsStatusSnapshot | null,\n): Record {\n if (!snapshot?.channelMeta?.length) return {};\n return Object.fromEntries(snapshot.channelMeta.map((entry) => [entry.id, entry]));\n}\n\nfunction resolveChannelLabel(\n snapshot: ChannelsStatusSnapshot | null,\n key: string,\n): string {\n const meta = resolveChannelMetaMap(snapshot)[key];\n return meta?.label ?? snapshot?.channelLabels?.[key] ?? key;\n}\n\nconst RECENT_ACTIVITY_THRESHOLD_MS = 10 * 60 * 1000; // 10 minutes\n\nfunction hasRecentActivity(account: ChannelAccountSnapshot): boolean {\n if (!account.lastInboundAt) return false;\n return Date.now() - account.lastInboundAt < RECENT_ACTIVITY_THRESHOLD_MS;\n}\n\nfunction deriveRunningStatus(account: ChannelAccountSnapshot): \"Yes\" | \"No\" | \"Active\" {\n if (account.running) return \"Yes\";\n // If we have recent inbound activity, the channel is effectively running\n if (hasRecentActivity(account)) return \"Active\";\n return \"No\";\n}\n\nfunction deriveConnectedStatus(account: ChannelAccountSnapshot): \"Yes\" | \"No\" | \"Active\" | \"n/a\" {\n if (account.connected === true) return \"Yes\";\n if (account.connected === false) return \"No\";\n // If connected is null/undefined but we have recent activity, show as active\n if (hasRecentActivity(account)) return \"Active\";\n return \"n/a\";\n}\n\nfunction renderGenericAccount(account: ChannelAccountSnapshot) {\n const runningStatus = deriveRunningStatus(account);\n const connectedStatus = deriveConnectedStatus(account);\n\n return html`\n
    \n
    \n
    ${account.name || account.accountId}
    \n
    ${account.accountId}
    \n
    \n
    \n
    \n Running\n ${runningStatus}\n
    \n
    \n Configured\n ${account.configured ? \"Yes\" : \"No\"}\n
    \n
    \n Connected\n ${connectedStatus}\n
    \n
    \n Last inbound\n ${account.lastInboundAt ? formatAgo(account.lastInboundAt) : \"n/a\"}\n
    \n ${account.lastError\n ? html`\n
    \n ${account.lastError}\n
    \n `\n : nothing}\n
    \n
    \n `;\n}\n","import { formatAgo, formatDurationMs, formatMs } from \"./format\";\nimport type { CronJob, GatewaySessionRow, PresenceEntry } from \"./types\";\n\nexport function formatPresenceSummary(entry: PresenceEntry): string {\n const host = entry.host ?? \"unknown\";\n const ip = entry.ip ? `(${entry.ip})` : \"\";\n const mode = entry.mode ?? \"\";\n const version = entry.version ?? \"\";\n return `${host} ${ip} ${mode} ${version}`.trim();\n}\n\nexport function formatPresenceAge(entry: PresenceEntry): string {\n const ts = entry.ts ?? null;\n return ts ? formatAgo(ts) : \"n/a\";\n}\n\nexport function formatNextRun(ms?: number | null) {\n if (!ms) return \"n/a\";\n return `${formatMs(ms)} (${formatAgo(ms)})`;\n}\n\nexport function formatSessionTokens(row: GatewaySessionRow) {\n if (row.totalTokens == null) return \"n/a\";\n const total = row.totalTokens ?? 0;\n const ctx = row.contextTokens ?? 0;\n return ctx ? `${total} / ${ctx}` : String(total);\n}\n\nexport function formatEventPayload(payload: unknown): string {\n if (payload == null) return \"\";\n try {\n return JSON.stringify(payload, null, 2);\n } catch {\n return String(payload);\n }\n}\n\nexport function formatCronState(job: CronJob) {\n const state = job.state ?? {};\n const next = state.nextRunAtMs ? formatMs(state.nextRunAtMs) : \"n/a\";\n const last = state.lastRunAtMs ? formatMs(state.lastRunAtMs) : \"n/a\";\n const status = state.lastStatus ?? \"n/a\";\n return `${status} · next ${next} · last ${last}`;\n}\n\nexport function formatCronSchedule(job: CronJob) {\n const s = job.schedule;\n if (s.kind === \"at\") return `At ${formatMs(s.atMs)}`;\n if (s.kind === \"every\") return `Every ${formatDurationMs(s.everyMs)}`;\n return `Cron ${s.expr}${s.tz ? ` (${s.tz})` : \"\"}`;\n}\n\nexport function formatCronPayload(job: CronJob) {\n const p = job.payload;\n if (p.kind === \"systemEvent\") return `System: ${p.text}`;\n return `Agent: ${p.message}`;\n}\n\n","import { html, nothing } from \"lit\";\n\nimport { formatMs } from \"../format\";\nimport {\n formatCronPayload,\n formatCronSchedule,\n formatCronState,\n formatNextRun,\n} from \"../presenter\";\nimport type { ChannelUiMetaEntry, CronJob, CronRunLogEntry, CronStatus } from \"../types\";\nimport type { CronFormState } from \"../ui-types\";\n\nexport type CronProps = {\n loading: boolean;\n status: CronStatus | null;\n jobs: CronJob[];\n error: string | null;\n busy: boolean;\n form: CronFormState;\n channels: string[];\n channelLabels?: Record;\n channelMeta?: ChannelUiMetaEntry[];\n runsJobId: string | null;\n runs: CronRunLogEntry[];\n onFormChange: (patch: Partial) => void;\n onRefresh: () => void;\n onAdd: () => void;\n onToggle: (job: CronJob, enabled: boolean) => void;\n onRun: (job: CronJob) => void;\n onRemove: (job: CronJob) => void;\n onLoadRuns: (jobId: string) => void;\n};\n\nfunction buildChannelOptions(props: CronProps): string[] {\n const options = [\"last\", ...props.channels.filter(Boolean)];\n const current = props.form.channel?.trim();\n if (current && !options.includes(current)) {\n options.push(current);\n }\n const seen = new Set();\n return options.filter((value) => {\n if (seen.has(value)) return false;\n seen.add(value);\n return true;\n });\n}\n\nfunction resolveChannelLabel(props: CronProps, channel: string): string {\n if (channel === \"last\") return \"last\";\n const meta = props.channelMeta?.find((entry) => entry.id === channel);\n if (meta?.label) return meta.label;\n return props.channelLabels?.[channel] ?? channel;\n}\n\nexport function renderCron(props: CronProps) {\n const channelOptions = buildChannelOptions(props);\n return html`\n
    \n
    \n
    Scheduler
    \n
    Gateway-owned cron scheduler status.
    \n
    \n
    \n
    Enabled
    \n
    \n ${props.status\n ? props.status.enabled\n ? \"Yes\"\n : \"No\"\n : \"n/a\"}\n
    \n
    \n
    \n
    Jobs
    \n
    ${props.status?.jobs ?? \"n/a\"}
    \n
    \n
    \n
    Next wake
    \n
    ${formatNextRun(props.status?.nextWakeAtMs ?? null)}
    \n
    \n
    \n
    \n \n ${props.error ? html`${props.error}` : nothing}\n
    \n
    \n\n
    \n
    New Job
    \n
    Create a scheduled wakeup or agent run.
    \n
    \n \n \n \n \n \n
    \n ${renderScheduleFields(props)}\n
    \n \n \n \n
    \n \n\t ${props.form.payloadKind === \"agentTurn\"\n\t ? html`\n\t
    \n \n\t \n \n \n ${props.form.sessionTarget === \"isolated\"\n ? html`\n \n `\n : nothing}\n
    \n `\n : nothing}\n
    \n \n
    \n
    \n
    \n\n
    \n
    Jobs
    \n
    All scheduled jobs stored in the gateway.
    \n ${props.jobs.length === 0\n ? html`
    No jobs yet.
    `\n : html`\n
    \n ${props.jobs.map((job) => renderJob(job, props))}\n
    \n `}\n
    \n\n
    \n
    Run history
    \n
    Latest runs for ${props.runsJobId ?? \"(select a job)\"}.
    \n ${props.runsJobId == null\n ? html`\n
    \n Select a job to inspect run history.\n
    \n `\n : props.runs.length === 0\n ? html`
    No runs yet.
    `\n : html`\n
    \n ${props.runs.map((entry) => renderRun(entry))}\n
    \n `}\n
    \n `;\n}\n\nfunction renderScheduleFields(props: CronProps) {\n const form = props.form;\n if (form.scheduleKind === \"at\") {\n return html`\n \n `;\n }\n if (form.scheduleKind === \"every\") {\n return html`\n
    \n \n \n
    \n `;\n }\n return html`\n
    \n \n \n
    \n `;\n}\n\nfunction renderJob(job: CronJob, props: CronProps) {\n const isSelected = props.runsJobId === job.id;\n const itemClass = `list-item list-item-clickable${isSelected ? \" list-item-selected\" : \"\"}`;\n return html`\n
    props.onLoadRuns(job.id)}>\n
    \n
    ${job.name}
    \n
    ${formatCronSchedule(job)}
    \n
    ${formatCronPayload(job)}
    \n ${job.agentId ? html`
    Agent: ${job.agentId}
    ` : nothing}\n
    \n ${job.enabled ? \"enabled\" : \"disabled\"}\n ${job.sessionTarget}\n ${job.wakeMode}\n
    \n
    \n
    \n
    ${formatCronState(job)}
    \n
    \n {\n event.stopPropagation();\n props.onToggle(job, !job.enabled);\n }}\n >\n ${job.enabled ? \"Disable\" : \"Enable\"}\n \n {\n event.stopPropagation();\n props.onRun(job);\n }}\n >\n Run\n \n {\n event.stopPropagation();\n props.onLoadRuns(job.id);\n }}\n >\n Runs\n \n {\n event.stopPropagation();\n props.onRemove(job);\n }}\n >\n Remove\n \n
    \n
    \n
    \n `;\n}\n\nfunction renderRun(entry: CronRunLogEntry) {\n return html`\n
    \n
    \n
    ${entry.status}
    \n
    ${entry.summary ?? \"\"}
    \n
    \n
    \n
    ${formatMs(entry.ts)}
    \n
    ${entry.durationMs ?? 0}ms
    \n ${entry.error ? html`
    ${entry.error}
    ` : nothing}\n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatEventPayload } from \"../presenter\";\nimport type { EventLogEntry } from \"../app-events\";\n\nexport type DebugProps = {\n loading: boolean;\n status: Record | null;\n health: Record | null;\n models: unknown[];\n heartbeat: unknown;\n eventLog: EventLogEntry[];\n callMethod: string;\n callParams: string;\n callResult: string | null;\n callError: string | null;\n onCallMethodChange: (next: string) => void;\n onCallParamsChange: (next: string) => void;\n onRefresh: () => void;\n onCall: () => void;\n};\n\nexport function renderDebug(props: DebugProps) {\n return html`\n
    \n
    \n
    \n
    \n
    Snapshots
    \n
    Status, health, and heartbeat data.
    \n
    \n \n
    \n
    \n
    \n
    Status
    \n
    ${JSON.stringify(props.status ?? {}, null, 2)}
    \n
    \n
    \n
    Health
    \n
    ${JSON.stringify(props.health ?? {}, null, 2)}
    \n
    \n
    \n
    Last heartbeat
    \n
    ${JSON.stringify(props.heartbeat ?? {}, null, 2)}
    \n
    \n
    \n
    \n\n
    \n
    Manual RPC
    \n
    Send a raw gateway method with JSON params.
    \n
    \n \n \n
    \n
    \n \n
    \n ${props.callError\n ? html`
    \n ${props.callError}\n
    `\n : nothing}\n ${props.callResult\n ? html`
    ${props.callResult}
    `\n : nothing}\n
    \n
    \n\n
    \n
    Models
    \n
    Catalog from models.list.
    \n
    ${JSON.stringify(\n        props.models ?? [],\n        null,\n        2,\n      )}
    \n
    \n\n
    \n
    Event Log
    \n
    Latest gateway events.
    \n ${props.eventLog.length === 0\n ? html`
    No events yet.
    `\n : html`\n
    \n ${props.eventLog.map(\n (evt) => html`\n
    \n
    \n
    ${evt.event}
    \n
    ${new Date(evt.ts).toLocaleTimeString()}
    \n
    \n
    \n
    ${formatEventPayload(evt.payload)}
    \n
    \n
    \n `,\n )}\n
    \n `}\n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatPresenceAge, formatPresenceSummary } from \"../presenter\";\nimport type { PresenceEntry } from \"../types\";\n\nexport type InstancesProps = {\n loading: boolean;\n entries: PresenceEntry[];\n lastError: string | null;\n statusMessage: string | null;\n onRefresh: () => void;\n};\n\nexport function renderInstances(props: InstancesProps) {\n return html`\n
    \n
    \n
    \n
    Connected Instances
    \n
    Presence beacons from the gateway and clients.
    \n
    \n \n
    \n ${props.lastError\n ? html`
    \n ${props.lastError}\n
    `\n : nothing}\n ${props.statusMessage\n ? html`
    \n ${props.statusMessage}\n
    `\n : nothing}\n
    \n ${props.entries.length === 0\n ? html`
    No instances reported yet.
    `\n : props.entries.map((entry) => renderEntry(entry))}\n
    \n
    \n `;\n}\n\nfunction renderEntry(entry: PresenceEntry) {\n const lastInput =\n entry.lastInputSeconds != null\n ? `${entry.lastInputSeconds}s ago`\n : \"n/a\";\n const mode = entry.mode ?? \"unknown\";\n const roles = Array.isArray(entry.roles) ? entry.roles.filter(Boolean) : [];\n const scopes = Array.isArray(entry.scopes) ? entry.scopes.filter(Boolean) : [];\n const scopesLabel =\n scopes.length > 0\n ? scopes.length > 3\n ? `${scopes.length} scopes`\n : `scopes: ${scopes.join(\", \")}`\n : null;\n return html`\n
    \n
    \n
    ${entry.host ?? \"unknown host\"}
    \n
    ${formatPresenceSummary(entry)}
    \n
    \n ${mode}\n ${roles.map((role) => html`${role}`)}\n ${scopesLabel ? html`${scopesLabel}` : nothing}\n ${entry.platform ? html`${entry.platform}` : nothing}\n ${entry.deviceFamily\n ? html`${entry.deviceFamily}`\n : nothing}\n ${entry.modelIdentifier\n ? html`${entry.modelIdentifier}`\n : nothing}\n ${entry.version ? html`${entry.version}` : nothing}\n
    \n
    \n
    \n
    ${formatPresenceAge(entry)}
    \n
    Last input ${lastInput}
    \n
    Reason ${entry.reason ?? \"\"}
    \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport type { LogEntry, LogLevel } from \"../types\";\n\nconst LEVELS: LogLevel[] = [\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"];\n\nexport type LogsProps = {\n loading: boolean;\n error: string | null;\n file: string | null;\n entries: LogEntry[];\n filterText: string;\n levelFilters: Record;\n autoFollow: boolean;\n truncated: boolean;\n onFilterTextChange: (next: string) => void;\n onLevelToggle: (level: LogLevel, enabled: boolean) => void;\n onToggleAutoFollow: (next: boolean) => void;\n onRefresh: () => void;\n onExport: (lines: string[], label: string) => void;\n onScroll: (event: Event) => void;\n};\n\nfunction formatTime(value?: string | null) {\n if (!value) return \"\";\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) return value;\n return date.toLocaleTimeString();\n}\n\nfunction matchesFilter(entry: LogEntry, needle: string) {\n if (!needle) return true;\n const haystack = [entry.message, entry.subsystem, entry.raw]\n .filter(Boolean)\n .join(\" \")\n .toLowerCase();\n return haystack.includes(needle);\n}\n\nexport function renderLogs(props: LogsProps) {\n const needle = props.filterText.trim().toLowerCase();\n const levelFiltered = LEVELS.some((level) => !props.levelFilters[level]);\n const filtered = props.entries.filter((entry) => {\n if (entry.level && !props.levelFilters[entry.level]) return false;\n return matchesFilter(entry, needle);\n });\n const exportLabel = needle || levelFiltered ? \"filtered\" : \"visible\";\n\n return html`\n
    \n
    \n
    \n
    Logs
    \n
    Gateway file logs (JSONL).
    \n
    \n
    \n \n props.onExport(filtered.map((entry) => entry.raw), exportLabel)}\n >\n Export ${exportLabel}\n \n
    \n
    \n\n
    \n \n \n
    \n\n
    \n ${LEVELS.map(\n (level) => html`\n \n `,\n )}\n
    \n\n ${props.file\n ? html`
    File: ${props.file}
    `\n : nothing}\n ${props.truncated\n ? html`
    \n Log output truncated; showing latest chunk.\n
    `\n : nothing}\n ${props.error\n ? html`
    ${props.error}
    `\n : nothing}\n\n
    \n ${filtered.length === 0\n ? html`
    No log entries.
    `\n : filtered.map(\n (entry) => html`\n
    \n
    ${formatTime(entry.time)}
    \n
    ${entry.level ?? \"\"}
    \n
    ${entry.subsystem ?? \"\"}
    \n
    ${entry.message ?? entry.raw}
    \n
    \n `,\n )}\n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { clampText, formatAgo, formatList } from \"../format\";\nimport type {\n ExecApprovalsAllowlistEntry,\n ExecApprovalsFile,\n ExecApprovalsSnapshot,\n} from \"../controllers/exec-approvals\";\nimport type {\n DevicePairingList,\n DeviceTokenSummary,\n PairedDevice,\n PendingDevice,\n} from \"../controllers/devices\";\n\nexport type NodesProps = {\n loading: boolean;\n nodes: Array>;\n devicesLoading: boolean;\n devicesError: string | null;\n devicesList: DevicePairingList | null;\n configForm: Record | null;\n configLoading: boolean;\n configSaving: boolean;\n configDirty: boolean;\n configFormMode: \"form\" | \"raw\";\n execApprovalsLoading: boolean;\n execApprovalsSaving: boolean;\n execApprovalsDirty: boolean;\n execApprovalsSnapshot: ExecApprovalsSnapshot | null;\n execApprovalsForm: ExecApprovalsFile | null;\n execApprovalsSelectedAgent: string | null;\n execApprovalsTarget: \"gateway\" | \"node\";\n execApprovalsTargetNodeId: string | null;\n onRefresh: () => void;\n onDevicesRefresh: () => void;\n onDeviceApprove: (requestId: string) => void;\n onDeviceReject: (requestId: string) => void;\n onDeviceRotate: (deviceId: string, role: string, scopes?: string[]) => void;\n onDeviceRevoke: (deviceId: string, role: string) => void;\n onLoadConfig: () => void;\n onLoadExecApprovals: () => void;\n onBindDefault: (nodeId: string | null) => void;\n onBindAgent: (agentIndex: number, nodeId: string | null) => void;\n onSaveBindings: () => void;\n onExecApprovalsTargetChange: (kind: \"gateway\" | \"node\", nodeId: string | null) => void;\n onExecApprovalsSelectAgent: (agentId: string) => void;\n onExecApprovalsPatch: (path: Array, value: unknown) => void;\n onExecApprovalsRemove: (path: Array) => void;\n onSaveExecApprovals: () => void;\n};\n\nexport function renderNodes(props: NodesProps) {\n const bindingState = resolveBindingsState(props);\n const approvalsState = resolveExecApprovalsState(props);\n return html`\n ${renderExecApprovals(approvalsState)}\n ${renderBindings(bindingState)}\n ${renderDevices(props)}\n
    \n
    \n
    \n
    Nodes
    \n
    Paired devices and live links.
    \n
    \n \n
    \n
    \n ${props.nodes.length === 0\n ? html`
    No nodes found.
    `\n : props.nodes.map((n) => renderNode(n))}\n
    \n
    \n `;\n}\n\nfunction renderDevices(props: NodesProps) {\n const list = props.devicesList ?? { pending: [], paired: [] };\n const pending = Array.isArray(list.pending) ? list.pending : [];\n const paired = Array.isArray(list.paired) ? list.paired : [];\n return html`\n
    \n
    \n
    \n
    Devices
    \n
    Pairing requests + role tokens.
    \n
    \n \n
    \n ${props.devicesError\n ? html`
    ${props.devicesError}
    `\n : nothing}\n
    \n ${pending.length > 0\n ? html`\n
    Pending
    \n ${pending.map((req) => renderPendingDevice(req, props))}\n `\n : nothing}\n ${paired.length > 0\n ? html`\n
    Paired
    \n ${paired.map((device) => renderPairedDevice(device, props))}\n `\n : nothing}\n ${pending.length === 0 && paired.length === 0\n ? html`
    No paired devices.
    `\n : nothing}\n
    \n
    \n `;\n}\n\nfunction renderPendingDevice(req: PendingDevice, props: NodesProps) {\n const name = req.displayName?.trim() || req.deviceId;\n const age = typeof req.ts === \"number\" ? formatAgo(req.ts) : \"n/a\";\n const role = req.role?.trim() ? `role: ${req.role}` : \"role: -\";\n const repair = req.isRepair ? \" · repair\" : \"\";\n const ip = req.remoteIp ? ` · ${req.remoteIp}` : \"\";\n return html`\n
    \n
    \n
    ${name}
    \n
    ${req.deviceId}${ip}
    \n
    \n ${role} · requested ${age}${repair}\n
    \n
    \n
    \n
    \n \n \n
    \n
    \n
    \n `;\n}\n\nfunction renderPairedDevice(device: PairedDevice, props: NodesProps) {\n const name = device.displayName?.trim() || device.deviceId;\n const ip = device.remoteIp ? ` · ${device.remoteIp}` : \"\";\n const roles = `roles: ${formatList(device.roles)}`;\n const scopes = `scopes: ${formatList(device.scopes)}`;\n const tokens = Array.isArray(device.tokens) ? device.tokens : [];\n return html`\n
    \n
    \n
    ${name}
    \n
    ${device.deviceId}${ip}
    \n
    ${roles} · ${scopes}
    \n ${tokens.length === 0\n ? html`
    Tokens: none
    `\n : html`\n
    Tokens
    \n
    \n ${tokens.map((token) => renderTokenRow(device.deviceId, token, props))}\n
    \n `}\n
    \n
    \n `;\n}\n\nfunction renderTokenRow(deviceId: string, token: DeviceTokenSummary, props: NodesProps) {\n const status = token.revokedAtMs ? \"revoked\" : \"active\";\n const scopes = `scopes: ${formatList(token.scopes)}`;\n const when = formatAgo(token.rotatedAtMs ?? token.createdAtMs ?? token.lastUsedAtMs ?? null);\n return html`\n
    \n
    ${token.role} · ${status} · ${scopes} · ${when}
    \n
    \n props.onDeviceRotate(deviceId, token.role, token.scopes)}\n >\n Rotate\n \n ${token.revokedAtMs\n ? nothing\n : html`\n props.onDeviceRevoke(deviceId, token.role)}\n >\n Revoke\n \n `}\n
    \n
    \n `;\n}\n\ntype BindingAgent = {\n id: string;\n name?: string;\n index: number;\n isDefault: boolean;\n binding?: string | null;\n};\n\ntype BindingNode = {\n id: string;\n label: string;\n};\n\ntype BindingState = {\n ready: boolean;\n disabled: boolean;\n configDirty: boolean;\n configLoading: boolean;\n configSaving: boolean;\n defaultBinding?: string | null;\n agents: BindingAgent[];\n nodes: BindingNode[];\n onBindDefault: (nodeId: string | null) => void;\n onBindAgent: (agentIndex: number, nodeId: string | null) => void;\n onSave: () => void;\n onLoadConfig: () => void;\n formMode: \"form\" | \"raw\";\n};\n\ntype ExecSecurity = \"deny\" | \"allowlist\" | \"full\";\ntype ExecAsk = \"off\" | \"on-miss\" | \"always\";\n\ntype ExecApprovalsResolvedDefaults = {\n security: ExecSecurity;\n ask: ExecAsk;\n askFallback: ExecSecurity;\n autoAllowSkills: boolean;\n};\n\ntype ExecApprovalsAgentOption = {\n id: string;\n name?: string;\n isDefault?: boolean;\n};\n\ntype ExecApprovalsTargetNode = {\n id: string;\n label: string;\n};\n\ntype ExecApprovalsState = {\n ready: boolean;\n disabled: boolean;\n dirty: boolean;\n loading: boolean;\n saving: boolean;\n form: ExecApprovalsFile | null;\n defaults: ExecApprovalsResolvedDefaults;\n selectedScope: string;\n selectedAgent: Record | null;\n agents: ExecApprovalsAgentOption[];\n allowlist: ExecApprovalsAllowlistEntry[];\n target: \"gateway\" | \"node\";\n targetNodeId: string | null;\n targetNodes: ExecApprovalsTargetNode[];\n onSelectScope: (agentId: string) => void;\n onSelectTarget: (kind: \"gateway\" | \"node\", nodeId: string | null) => void;\n onPatch: (path: Array, value: unknown) => void;\n onRemove: (path: Array) => void;\n onLoad: () => void;\n onSave: () => void;\n};\n\nconst EXEC_APPROVALS_DEFAULT_SCOPE = \"__defaults__\";\n\nconst SECURITY_OPTIONS: Array<{ value: ExecSecurity; label: string }> = [\n { value: \"deny\", label: \"Deny\" },\n { value: \"allowlist\", label: \"Allowlist\" },\n { value: \"full\", label: \"Full\" },\n];\n\nconst ASK_OPTIONS: Array<{ value: ExecAsk; label: string }> = [\n { value: \"off\", label: \"Off\" },\n { value: \"on-miss\", label: \"On miss\" },\n { value: \"always\", label: \"Always\" },\n];\n\nfunction resolveBindingsState(props: NodesProps): BindingState {\n const config = props.configForm;\n const nodes = resolveExecNodes(props.nodes);\n const { defaultBinding, agents } = resolveAgentBindings(config);\n const ready = Boolean(config);\n const disabled = props.configSaving || props.configFormMode === \"raw\";\n return {\n ready,\n disabled,\n configDirty: props.configDirty,\n configLoading: props.configLoading,\n configSaving: props.configSaving,\n defaultBinding,\n agents,\n nodes,\n onBindDefault: props.onBindDefault,\n onBindAgent: props.onBindAgent,\n onSave: props.onSaveBindings,\n onLoadConfig: props.onLoadConfig,\n formMode: props.configFormMode,\n };\n}\n\nfunction normalizeSecurity(value?: string): ExecSecurity {\n if (value === \"allowlist\" || value === \"full\" || value === \"deny\") return value;\n return \"deny\";\n}\n\nfunction normalizeAsk(value?: string): ExecAsk {\n if (value === \"always\" || value === \"off\" || value === \"on-miss\") return value;\n return \"on-miss\";\n}\n\nfunction resolveExecApprovalsDefaults(\n form: ExecApprovalsFile | null,\n): ExecApprovalsResolvedDefaults {\n const defaults = form?.defaults ?? {};\n return {\n security: normalizeSecurity(defaults.security),\n ask: normalizeAsk(defaults.ask),\n askFallback: normalizeSecurity(defaults.askFallback ?? \"deny\"),\n autoAllowSkills: Boolean(defaults.autoAllowSkills ?? false),\n };\n}\n\nfunction resolveConfigAgents(config: Record | null): ExecApprovalsAgentOption[] {\n const agentsNode = (config?.agents ?? {}) as Record;\n const list = Array.isArray(agentsNode.list) ? agentsNode.list : [];\n const agents: ExecApprovalsAgentOption[] = [];\n list.forEach((entry) => {\n if (!entry || typeof entry !== \"object\") return;\n const record = entry as Record;\n const id = typeof record.id === \"string\" ? record.id.trim() : \"\";\n if (!id) return;\n const name = typeof record.name === \"string\" ? record.name.trim() : undefined;\n const isDefault = record.default === true;\n agents.push({ id, name: name || undefined, isDefault });\n });\n return agents;\n}\n\nfunction resolveExecApprovalsAgents(\n config: Record | null,\n form: ExecApprovalsFile | null,\n): ExecApprovalsAgentOption[] {\n const configAgents = resolveConfigAgents(config);\n const approvalsAgents = Object.keys(form?.agents ?? {});\n const merged = new Map();\n configAgents.forEach((agent) => merged.set(agent.id, agent));\n approvalsAgents.forEach((id) => {\n if (merged.has(id)) return;\n merged.set(id, { id });\n });\n const agents = Array.from(merged.values());\n if (agents.length === 0) {\n agents.push({ id: \"main\", isDefault: true });\n }\n agents.sort((a, b) => {\n if (a.isDefault && !b.isDefault) return -1;\n if (!a.isDefault && b.isDefault) return 1;\n const aLabel = a.name?.trim() ? a.name : a.id;\n const bLabel = b.name?.trim() ? b.name : b.id;\n return aLabel.localeCompare(bLabel);\n });\n return agents;\n}\n\nfunction resolveExecApprovalsScope(\n selected: string | null,\n agents: ExecApprovalsAgentOption[],\n): string {\n if (selected === EXEC_APPROVALS_DEFAULT_SCOPE) return EXEC_APPROVALS_DEFAULT_SCOPE;\n if (selected && agents.some((agent) => agent.id === selected)) return selected;\n return EXEC_APPROVALS_DEFAULT_SCOPE;\n}\n\nfunction resolveExecApprovalsState(props: NodesProps): ExecApprovalsState {\n const form = props.execApprovalsForm ?? props.execApprovalsSnapshot?.file ?? null;\n const ready = Boolean(form);\n const defaults = resolveExecApprovalsDefaults(form);\n const agents = resolveExecApprovalsAgents(props.configForm, form);\n const targetNodes = resolveExecApprovalsNodes(props.nodes);\n const target = props.execApprovalsTarget;\n let targetNodeId =\n target === \"node\" && props.execApprovalsTargetNodeId\n ? props.execApprovalsTargetNodeId\n : null;\n if (target === \"node\" && targetNodeId && !targetNodes.some((node) => node.id === targetNodeId)) {\n targetNodeId = null;\n }\n const selectedScope = resolveExecApprovalsScope(props.execApprovalsSelectedAgent, agents);\n const selectedAgent =\n selectedScope !== EXEC_APPROVALS_DEFAULT_SCOPE\n ? ((form?.agents ?? {})[selectedScope] as Record | undefined) ??\n null\n : null;\n const allowlist = Array.isArray((selectedAgent as { allowlist?: unknown })?.allowlist)\n ? ((selectedAgent as { allowlist?: ExecApprovalsAllowlistEntry[] }).allowlist ??\n [])\n : [];\n return {\n ready,\n disabled: props.execApprovalsSaving || props.execApprovalsLoading,\n dirty: props.execApprovalsDirty,\n loading: props.execApprovalsLoading,\n saving: props.execApprovalsSaving,\n form,\n defaults,\n selectedScope,\n selectedAgent,\n agents,\n allowlist,\n target,\n targetNodeId,\n targetNodes,\n onSelectScope: props.onExecApprovalsSelectAgent,\n onSelectTarget: props.onExecApprovalsTargetChange,\n onPatch: props.onExecApprovalsPatch,\n onRemove: props.onExecApprovalsRemove,\n onLoad: props.onLoadExecApprovals,\n onSave: props.onSaveExecApprovals,\n };\n}\n\nfunction renderBindings(state: BindingState) {\n const supportsBinding = state.nodes.length > 0;\n const defaultValue = state.defaultBinding ?? \"\";\n return html`\n
    \n
    \n
    \n
    Exec node binding
    \n
    \n Pin agents to a specific node when using exec host=node.\n
    \n
    \n \n ${state.configSaving ? \"Saving…\" : \"Save\"}\n \n
    \n\n ${state.formMode === \"raw\"\n ? html`
    \n Switch the Config tab to Form mode to edit bindings here.\n
    `\n : nothing}\n\n ${!state.ready\n ? html`
    \n
    Load config to edit bindings.
    \n \n
    `\n : html`\n
    \n
    \n
    \n
    Default binding
    \n
    Used when agents do not override a node binding.
    \n
    \n
    \n \n ${!supportsBinding\n ? html`
    No nodes with system.run available.
    `\n : nothing}\n
    \n
    \n\n ${state.agents.length === 0\n ? html`
    No agents found.
    `\n : state.agents.map((agent) =>\n renderAgentBinding(agent, state),\n )}\n
    \n `}\n
    \n `;\n}\n\nfunction renderExecApprovals(state: ExecApprovalsState) {\n const ready = state.ready;\n const targetReady = state.target !== \"node\" || Boolean(state.targetNodeId);\n return html`\n
    \n
    \n
    \n
    Exec approvals
    \n
    \n Allowlist and approval policy for exec host=gateway/node.\n
    \n
    \n \n ${state.saving ? \"Saving…\" : \"Save\"}\n \n
    \n\n ${renderExecApprovalsTarget(state)}\n\n ${!ready\n ? html`
    \n
    Load exec approvals to edit allowlists.
    \n \n
    `\n : html`\n ${renderExecApprovalsTabs(state)}\n ${renderExecApprovalsPolicy(state)}\n ${state.selectedScope === EXEC_APPROVALS_DEFAULT_SCOPE\n ? nothing\n : renderExecApprovalsAllowlist(state)}\n `}\n
    \n `;\n}\n\nfunction renderExecApprovalsTarget(state: ExecApprovalsState) {\n const hasNodes = state.targetNodes.length > 0;\n const nodeValue = state.targetNodeId ?? \"\";\n return html`\n
    \n
    \n
    \n
    Target
    \n
    \n Gateway edits local approvals; node edits the selected node.\n
    \n
    \n
    \n \n ${state.target === \"node\"\n ? html`\n \n `\n : nothing}\n
    \n
    \n ${state.target === \"node\" && !hasNodes\n ? html`
    No nodes advertise exec approvals yet.
    `\n : nothing}\n
    \n `;\n}\n\nfunction renderExecApprovalsTabs(state: ExecApprovalsState) {\n return html`\n
    \n Scope\n
    \n state.onSelectScope(EXEC_APPROVALS_DEFAULT_SCOPE)}\n >\n Defaults\n \n ${state.agents.map((agent) => {\n const label = agent.name?.trim() ? `${agent.name} (${agent.id})` : agent.id;\n return html`\n state.onSelectScope(agent.id)}\n >\n ${label}\n \n `;\n })}\n
    \n
    \n `;\n}\n\nfunction renderExecApprovalsPolicy(state: ExecApprovalsState) {\n const isDefaults = state.selectedScope === EXEC_APPROVALS_DEFAULT_SCOPE;\n const defaults = state.defaults;\n const agent = state.selectedAgent ?? {};\n const basePath = isDefaults ? [\"defaults\"] : [\"agents\", state.selectedScope];\n const agentSecurity = typeof agent.security === \"string\" ? agent.security : undefined;\n const agentAsk = typeof agent.ask === \"string\" ? agent.ask : undefined;\n const agentAskFallback =\n typeof agent.askFallback === \"string\" ? agent.askFallback : undefined;\n const securityValue = isDefaults ? defaults.security : agentSecurity ?? \"__default__\";\n const askValue = isDefaults ? defaults.ask : agentAsk ?? \"__default__\";\n const askFallbackValue = isDefaults\n ? defaults.askFallback\n : agentAskFallback ?? \"__default__\";\n const autoOverride =\n typeof agent.autoAllowSkills === \"boolean\" ? agent.autoAllowSkills : undefined;\n const autoEffective = autoOverride ?? defaults.autoAllowSkills;\n const autoIsDefault = autoOverride == null;\n\n return html`\n
    \n
    \n
    \n
    Security
    \n
    \n ${isDefaults\n ? \"Default security mode.\"\n : `Default: ${defaults.security}.`}\n
    \n
    \n
    \n \n
    \n
    \n\n
    \n
    \n
    Ask
    \n
    \n ${isDefaults ? \"Default prompt policy.\" : `Default: ${defaults.ask}.`}\n
    \n
    \n
    \n \n
    \n
    \n\n
    \n
    \n
    Ask fallback
    \n
    \n ${isDefaults\n ? \"Applied when the UI prompt is unavailable.\"\n : `Default: ${defaults.askFallback}.`}\n
    \n
    \n
    \n \n
    \n
    \n\n
    \n
    \n
    Auto-allow skill CLIs
    \n
    \n ${isDefaults\n ? \"Allow skill executables listed by the Gateway.\"\n : autoIsDefault\n ? `Using default (${defaults.autoAllowSkills ? \"on\" : \"off\"}).`\n : `Override (${autoEffective ? \"on\" : \"off\"}).`}\n
    \n
    \n
    \n \n ${!isDefaults && !autoIsDefault\n ? html` state.onRemove([...basePath, \"autoAllowSkills\"])}\n >\n Use default\n `\n : nothing}\n
    \n
    \n
    \n `;\n}\n\nfunction renderExecApprovalsAllowlist(state: ExecApprovalsState) {\n const allowlistPath = [\"agents\", state.selectedScope, \"allowlist\"];\n const entries = state.allowlist;\n return html`\n
    \n
    \n
    Allowlist
    \n
    Case-insensitive glob patterns.
    \n
    \n {\n const next = [...entries, { pattern: \"\" }];\n state.onPatch(allowlistPath, next);\n }}\n >\n Add pattern\n \n
    \n
    \n ${entries.length === 0\n ? html`
    No allowlist entries yet.
    `\n : entries.map((entry, index) =>\n renderAllowlistEntry(state, entry, index),\n )}\n
    \n `;\n}\n\nfunction renderAllowlistEntry(\n state: ExecApprovalsState,\n entry: ExecApprovalsAllowlistEntry,\n index: number,\n) {\n const lastUsed = entry.lastUsedAt ? formatAgo(entry.lastUsedAt) : \"never\";\n const lastCommand = entry.lastUsedCommand\n ? clampText(entry.lastUsedCommand, 120)\n : null;\n const lastPath = entry.lastResolvedPath\n ? clampText(entry.lastResolvedPath, 120)\n : null;\n return html`\n
    \n
    \n
    ${entry.pattern?.trim() ? entry.pattern : \"New pattern\"}
    \n
    Last used: ${lastUsed}
    \n ${lastCommand ? html`
    ${lastCommand}
    ` : nothing}\n ${lastPath ? html`
    ${lastPath}
    ` : nothing}\n
    \n
    \n \n {\n if (state.allowlist.length <= 1) {\n state.onRemove([\"agents\", state.selectedScope, \"allowlist\"]);\n return;\n }\n state.onRemove([\"agents\", state.selectedScope, \"allowlist\", index]);\n }}\n >\n Remove\n \n
    \n
    \n `;\n}\n\nfunction renderAgentBinding(agent: BindingAgent, state: BindingState) {\n const bindingValue = agent.binding ?? \"__default__\";\n const label = agent.name?.trim() ? `${agent.name} (${agent.id})` : agent.id;\n const supportsBinding = state.nodes.length > 0;\n return html`\n
    \n
    \n
    ${label}
    \n
    \n ${agent.isDefault ? \"default agent\" : \"agent\"} ·\n ${bindingValue === \"__default__\"\n ? `uses default (${state.defaultBinding ?? \"any\"})`\n : `override: ${agent.binding}`}\n
    \n
    \n
    \n \n
    \n
    \n `;\n}\n\nfunction resolveExecNodes(nodes: Array>): BindingNode[] {\n const list: BindingNode[] = [];\n for (const node of nodes) {\n const commands = Array.isArray(node.commands) ? node.commands : [];\n const supports = commands.some((cmd) => String(cmd) === \"system.run\");\n if (!supports) continue;\n const nodeId = typeof node.nodeId === \"string\" ? node.nodeId.trim() : \"\";\n if (!nodeId) continue;\n const displayName =\n typeof node.displayName === \"string\" && node.displayName.trim()\n ? node.displayName.trim()\n : nodeId;\n list.push({ id: nodeId, label: displayName === nodeId ? nodeId : `${displayName} · ${nodeId}` });\n }\n list.sort((a, b) => a.label.localeCompare(b.label));\n return list;\n}\n\nfunction resolveExecApprovalsNodes(nodes: Array>): ExecApprovalsTargetNode[] {\n const list: ExecApprovalsTargetNode[] = [];\n for (const node of nodes) {\n const commands = Array.isArray(node.commands) ? node.commands : [];\n const supports = commands.some(\n (cmd) => String(cmd) === \"system.execApprovals.get\" || String(cmd) === \"system.execApprovals.set\",\n );\n if (!supports) continue;\n const nodeId = typeof node.nodeId === \"string\" ? node.nodeId.trim() : \"\";\n if (!nodeId) continue;\n const displayName =\n typeof node.displayName === \"string\" && node.displayName.trim()\n ? node.displayName.trim()\n : nodeId;\n list.push({ id: nodeId, label: displayName === nodeId ? nodeId : `${displayName} · ${nodeId}` });\n }\n list.sort((a, b) => a.label.localeCompare(b.label));\n return list;\n}\n\nfunction resolveAgentBindings(config: Record | null): {\n defaultBinding?: string | null;\n agents: BindingAgent[];\n} {\n const fallbackAgent: BindingAgent = {\n id: \"main\",\n name: undefined,\n index: 0,\n isDefault: true,\n binding: null,\n };\n if (!config || typeof config !== \"object\") {\n return { defaultBinding: null, agents: [fallbackAgent] };\n }\n const tools = (config.tools ?? {}) as Record;\n const exec = (tools.exec ?? {}) as Record;\n const defaultBinding =\n typeof exec.node === \"string\" && exec.node.trim() ? exec.node.trim() : null;\n\n const agentsNode = (config.agents ?? {}) as Record;\n const list = Array.isArray(agentsNode.list) ? agentsNode.list : [];\n if (list.length === 0) {\n return { defaultBinding, agents: [fallbackAgent] };\n }\n\n const agents: BindingAgent[] = [];\n list.forEach((entry, index) => {\n if (!entry || typeof entry !== \"object\") return;\n const record = entry as Record;\n const id = typeof record.id === \"string\" ? record.id.trim() : \"\";\n if (!id) return;\n const name = typeof record.name === \"string\" ? record.name.trim() : undefined;\n const isDefault = record.default === true;\n const toolsEntry = (record.tools ?? {}) as Record;\n const execEntry = (toolsEntry.exec ?? {}) as Record;\n const binding =\n typeof execEntry.node === \"string\" && execEntry.node.trim()\n ? execEntry.node.trim()\n : null;\n agents.push({\n id,\n name: name || undefined,\n index,\n isDefault,\n binding,\n });\n });\n\n if (agents.length === 0) {\n agents.push(fallbackAgent);\n }\n\n return { defaultBinding, agents };\n}\n\nfunction renderNode(node: Record) {\n const connected = Boolean(node.connected);\n const paired = Boolean(node.paired);\n const title =\n (typeof node.displayName === \"string\" && node.displayName.trim()) ||\n (typeof node.nodeId === \"string\" ? node.nodeId : \"unknown\");\n const caps = Array.isArray(node.caps) ? (node.caps as unknown[]) : [];\n const commands = Array.isArray(node.commands) ? (node.commands as unknown[]) : [];\n return html`\n
    \n
    \n
    ${title}
    \n
    \n ${typeof node.nodeId === \"string\" ? node.nodeId : \"\"}\n ${typeof node.remoteIp === \"string\" ? ` · ${node.remoteIp}` : \"\"}\n ${typeof node.version === \"string\" ? ` · ${node.version}` : \"\"}\n
    \n
    \n ${paired ? \"paired\" : \"unpaired\"}\n \n ${connected ? \"connected\" : \"offline\"}\n \n ${caps.slice(0, 12).map((c) => html`${String(c)}`)}\n ${commands\n .slice(0, 8)\n .map((c) => html`${String(c)}`)}\n
    \n
    \n
    \n `;\n}\n","import { html } from \"lit\";\n\nimport type { GatewayHelloOk } from \"../gateway\";\nimport { formatAgo, formatDurationMs } from \"../format\";\nimport { formatNextRun } from \"../presenter\";\nimport type { UiSettings } from \"../storage\";\n\nexport type OverviewProps = {\n connected: boolean;\n hello: GatewayHelloOk | null;\n settings: UiSettings;\n password: string;\n lastError: string | null;\n presenceCount: number;\n sessionsCount: number | null;\n cronEnabled: boolean | null;\n cronNext: number | null;\n lastChannelsRefresh: number | null;\n onSettingsChange: (next: UiSettings) => void;\n onPasswordChange: (next: string) => void;\n onSessionKeyChange: (next: string) => void;\n onConnect: () => void;\n onRefresh: () => void;\n};\n\nexport function renderOverview(props: OverviewProps) {\n const snapshot = props.hello?.snapshot as\n | { uptimeMs?: number; policy?: { tickIntervalMs?: number } }\n | undefined;\n const uptime = snapshot?.uptimeMs ? formatDurationMs(snapshot.uptimeMs) : \"n/a\";\n const tick = snapshot?.policy?.tickIntervalMs\n ? `${snapshot.policy.tickIntervalMs}ms`\n : \"n/a\";\n const authHint = (() => {\n if (props.connected || !props.lastError) return null;\n const lower = props.lastError.toLowerCase();\n const authFailed = lower.includes(\"unauthorized\") || lower.includes(\"connect failed\");\n if (!authFailed) return null;\n const hasToken = Boolean(props.settings.token.trim());\n const hasPassword = Boolean(props.password.trim());\n if (!hasToken && !hasPassword) {\n return html`\n
    \n This gateway requires auth. Add a token or password, then click Connect.\n
    \n clawdbot dashboard --no-open → tokenized URL
    \n clawdbot doctor --generate-gateway-token → set token\n
    \n
    \n Docs: Control UI auth\n
    \n
    \n `;\n }\n return html`\n
    \n Auth failed. Re-copy a tokenized URL with\n clawdbot dashboard --no-open, or update the token,\n then click Connect.\n
    \n Docs: Control UI auth\n
    \n
    \n `;\n })();\n const insecureContextHint = (() => {\n if (props.connected || !props.lastError) return null;\n const isSecureContext = typeof window !== \"undefined\" ? window.isSecureContext : true;\n if (isSecureContext !== false) return null;\n const lower = props.lastError.toLowerCase();\n if (!lower.includes(\"secure context\") && !lower.includes(\"device identity required\")) {\n return null;\n }\n return html`\n
    \n This page is HTTP, so the browser blocks device identity. Use HTTPS (Tailscale Serve) or\n open http://127.0.0.1:18789 on the gateway host.\n
    \n If you must stay on HTTP, set\n gateway.controlUi.allowInsecureAuth: true (token-only).\n
    \n
    \n Docs: Tailscale Serve\n · \n Docs: Insecure HTTP\n
    \n
    \n `;\n })();\n\n return html`\n
    \n
    \n
    Gateway Access
    \n
    Where the dashboard connects and how it authenticates.
    \n
    \n \n \n \n \n
    \n
    \n \n \n Click Connect to apply connection changes.\n
    \n
    \n\n
    \n
    Snapshot
    \n
    Latest gateway handshake information.
    \n
    \n
    \n
    Status
    \n
    \n ${props.connected ? \"Connected\" : \"Disconnected\"}\n
    \n
    \n
    \n
    Uptime
    \n
    ${uptime}
    \n
    \n
    \n
    Tick Interval
    \n
    ${tick}
    \n
    \n
    \n
    Last Channels Refresh
    \n
    \n ${props.lastChannelsRefresh\n ? formatAgo(props.lastChannelsRefresh)\n : \"n/a\"}\n
    \n
    \n
    \n ${props.lastError\n ? html`
    \n
    ${props.lastError}
    \n ${authHint ?? \"\"}\n ${insecureContextHint ?? \"\"}\n
    `\n : html`
    \n Use Channels to link WhatsApp, Telegram, Discord, Signal, or iMessage.\n
    `}\n
    \n
    \n\n
    \n
    \n
    Instances
    \n
    ${props.presenceCount}
    \n
    Presence beacons in the last 5 minutes.
    \n
    \n
    \n
    Sessions
    \n
    ${props.sessionsCount ?? \"n/a\"}
    \n
    Recent session keys tracked by the gateway.
    \n
    \n
    \n
    Cron
    \n
    \n ${props.cronEnabled == null\n ? \"n/a\"\n : props.cronEnabled\n ? \"Enabled\"\n : \"Disabled\"}\n
    \n
    Next wake ${formatNextRun(props.cronNext)}
    \n
    \n
    \n\n
    \n
    Notes
    \n
    Quick reminders for remote control setups.
    \n
    \n
    \n
    Tailscale serve
    \n
    \n Prefer serve mode to keep the gateway on loopback with tailnet auth.\n
    \n
    \n
    \n
    Session hygiene
    \n
    Use /new or sessions.patch to reset context.
    \n
    \n
    \n
    Cron reminders
    \n
    Use isolated sessions for recurring runs.
    \n
    \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { formatAgo } from \"../format\";\nimport { formatSessionTokens } from \"../presenter\";\nimport { pathForTab } from \"../navigation\";\nimport type { GatewaySessionRow, SessionsListResult } from \"../types\";\n\nexport type SessionsProps = {\n loading: boolean;\n result: SessionsListResult | null;\n error: string | null;\n activeMinutes: string;\n limit: string;\n includeGlobal: boolean;\n includeUnknown: boolean;\n basePath: string;\n onFiltersChange: (next: {\n activeMinutes: string;\n limit: string;\n includeGlobal: boolean;\n includeUnknown: boolean;\n }) => void;\n onRefresh: () => void;\n onPatch: (\n key: string,\n patch: {\n label?: string | null;\n thinkingLevel?: string | null;\n verboseLevel?: string | null;\n reasoningLevel?: string | null;\n },\n ) => void;\n onDelete: (key: string) => void;\n};\n\nconst THINK_LEVELS = [\"\", \"off\", \"minimal\", \"low\", \"medium\", \"high\"] as const;\nconst BINARY_THINK_LEVELS = [\"\", \"off\", \"on\"] as const;\nconst VERBOSE_LEVELS = [\n { value: \"\", label: \"inherit\" },\n { value: \"off\", label: \"off (explicit)\" },\n { value: \"on\", label: \"on\" },\n] as const;\nconst REASONING_LEVELS = [\"\", \"off\", \"on\", \"stream\"] as const;\n\nfunction normalizeProviderId(provider?: string | null): string {\n if (!provider) return \"\";\n const normalized = provider.trim().toLowerCase();\n if (normalized === \"z.ai\" || normalized === \"z-ai\") return \"zai\";\n return normalized;\n}\n\nfunction isBinaryThinkingProvider(provider?: string | null): boolean {\n return normalizeProviderId(provider) === \"zai\";\n}\n\nfunction resolveThinkLevelOptions(provider?: string | null): readonly string[] {\n return isBinaryThinkingProvider(provider) ? BINARY_THINK_LEVELS : THINK_LEVELS;\n}\n\nfunction resolveThinkLevelDisplay(value: string, isBinary: boolean): string {\n if (!isBinary) return value;\n if (!value || value === \"off\") return value;\n return \"on\";\n}\n\nfunction resolveThinkLevelPatchValue(value: string, isBinary: boolean): string | null {\n if (!value) return null;\n if (!isBinary) return value;\n if (value === \"on\") return \"low\";\n return value;\n}\n\nexport function renderSessions(props: SessionsProps) {\n const rows = props.result?.sessions ?? [];\n return html`\n
    \n
    \n
    \n
    Sessions
    \n
    Active session keys and per-session overrides.
    \n
    \n \n
    \n\n
    \n \n \n \n \n
    \n\n ${props.error\n ? html`
    ${props.error}
    `\n : nothing}\n\n
    \n ${props.result ? `Store: ${props.result.path}` : \"\"}\n
    \n\n
    \n
    \n
    Key
    \n
    Label
    \n
    Kind
    \n
    Updated
    \n
    Tokens
    \n
    Thinking
    \n
    Verbose
    \n
    Reasoning
    \n
    Actions
    \n
    \n ${rows.length === 0\n ? html`
    No sessions found.
    `\n : rows.map((row) =>\n renderRow(row, props.basePath, props.onPatch, props.onDelete, props.loading),\n )}\n
    \n
    \n `;\n}\n\nfunction renderRow(\n row: GatewaySessionRow,\n basePath: string,\n onPatch: SessionsProps[\"onPatch\"],\n onDelete: SessionsProps[\"onDelete\"],\n disabled: boolean,\n) {\n const updated = row.updatedAt ? formatAgo(row.updatedAt) : \"n/a\";\n const rawThinking = row.thinkingLevel ?? \"\";\n const isBinaryThinking = isBinaryThinkingProvider(row.modelProvider);\n const thinking = resolveThinkLevelDisplay(rawThinking, isBinaryThinking);\n const thinkLevels = resolveThinkLevelOptions(row.modelProvider);\n const verbose = row.verboseLevel ?? \"\";\n const reasoning = row.reasoningLevel ?? \"\";\n const displayName = row.displayName ?? row.key;\n const canLink = row.kind !== \"global\";\n const chatUrl = canLink\n ? `${pathForTab(\"chat\", basePath)}?session=${encodeURIComponent(row.key)}`\n : null;\n\n return html`\n
    \n
    ${canLink\n ? html`${displayName}`\n : displayName}
    \n
    \n {\n const value = (e.target as HTMLInputElement).value.trim();\n onPatch(row.key, { label: value || null });\n }}\n />\n
    \n
    ${row.kind}
    \n
    ${updated}
    \n
    ${formatSessionTokens(row)}
    \n
    \n {\n const value = (e.target as HTMLSelectElement).value;\n onPatch(row.key, {\n thinkingLevel: resolveThinkLevelPatchValue(value, isBinaryThinking),\n });\n }}\n >\n ${thinkLevels.map((level) =>\n html``,\n )}\n \n
    \n
    \n {\n const value = (e.target as HTMLSelectElement).value;\n onPatch(row.key, { verboseLevel: value || null });\n }}\n >\n ${VERBOSE_LEVELS.map(\n (level) => html``,\n )}\n \n
    \n
    \n {\n const value = (e.target as HTMLSelectElement).value;\n onPatch(row.key, { reasoningLevel: value || null });\n }}\n >\n ${REASONING_LEVELS.map((level) =>\n html``,\n )}\n \n
    \n
    \n \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport type { AppViewState } from \"../app-view-state\";\n\nfunction formatRemaining(ms: number): string {\n const remaining = Math.max(0, ms);\n const totalSeconds = Math.floor(remaining / 1000);\n if (totalSeconds < 60) return `${totalSeconds}s`;\n const minutes = Math.floor(totalSeconds / 60);\n if (minutes < 60) return `${minutes}m`;\n const hours = Math.floor(minutes / 60);\n return `${hours}h`;\n}\n\nfunction renderMetaRow(label: string, value?: string | null) {\n if (!value) return nothing;\n return html`
    ${label}${value}
    `;\n}\n\nexport function renderExecApprovalPrompt(state: AppViewState) {\n const active = state.execApprovalQueue[0];\n if (!active) return nothing;\n const request = active.request;\n const remainingMs = active.expiresAtMs - Date.now();\n const remaining = remainingMs > 0 ? `expires in ${formatRemaining(remainingMs)}` : \"expired\";\n const queueCount = state.execApprovalQueue.length;\n return html`\n
    \n
    \n
    \n
    \n
    Exec approval needed
    \n
    ${remaining}
    \n
    \n ${queueCount > 1\n ? html`
    ${queueCount} pending
    `\n : nothing}\n
    \n
    ${request.command}
    \n
    \n ${renderMetaRow(\"Host\", request.host)}\n ${renderMetaRow(\"Agent\", request.agentId)}\n ${renderMetaRow(\"Session\", request.sessionKey)}\n ${renderMetaRow(\"CWD\", request.cwd)}\n ${renderMetaRow(\"Resolved\", request.resolvedPath)}\n ${renderMetaRow(\"Security\", request.security)}\n ${renderMetaRow(\"Ask\", request.ask)}\n
    \n ${state.execApprovalError\n ? html`
    ${state.execApprovalError}
    `\n : nothing}\n
    \n state.handleExecApprovalDecision(\"allow-once\")}\n >\n Allow once\n \n state.handleExecApprovalDecision(\"allow-always\")}\n >\n Always allow\n \n state.handleExecApprovalDecision(\"deny\")}\n >\n Deny\n \n
    \n
    \n
    \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport { clampText } from \"../format\";\nimport type { SkillStatusEntry, SkillStatusReport } from \"../types\";\nimport type { SkillMessageMap } from \"../controllers/skills\";\n\nexport type SkillsProps = {\n loading: boolean;\n report: SkillStatusReport | null;\n error: string | null;\n filter: string;\n edits: Record;\n busyKey: string | null;\n messages: SkillMessageMap;\n onFilterChange: (next: string) => void;\n onRefresh: () => void;\n onToggle: (skillKey: string, enabled: boolean) => void;\n onEdit: (skillKey: string, value: string) => void;\n onSaveKey: (skillKey: string) => void;\n onInstall: (skillKey: string, name: string, installId: string) => void;\n};\n\nexport function renderSkills(props: SkillsProps) {\n const skills = props.report?.skills ?? [];\n const filter = props.filter.trim().toLowerCase();\n const filtered = filter\n ? skills.filter((skill) =>\n [skill.name, skill.description, skill.source]\n .join(\" \")\n .toLowerCase()\n .includes(filter),\n )\n : skills;\n\n return html`\n
    \n
    \n
    \n
    Skills
    \n
    Bundled, managed, and workspace skills.
    \n
    \n \n
    \n\n
    \n \n
    ${filtered.length} shown
    \n
    \n\n ${props.error\n ? html`
    ${props.error}
    `\n : nothing}\n\n ${filtered.length === 0\n ? html`
    No skills found.
    `\n : html`\n
    \n ${filtered.map((skill) => renderSkill(skill, props))}\n
    \n `}\n
    \n `;\n}\n\nfunction renderSkill(skill: SkillStatusEntry, props: SkillsProps) {\n const busy = props.busyKey === skill.skillKey;\n const apiKey = props.edits[skill.skillKey] ?? \"\";\n const message = props.messages[skill.skillKey] ?? null;\n const canInstall =\n skill.install.length > 0 && skill.missing.bins.length > 0;\n const missing = [\n ...skill.missing.bins.map((b) => `bin:${b}`),\n ...skill.missing.env.map((e) => `env:${e}`),\n ...skill.missing.config.map((c) => `config:${c}`),\n ...skill.missing.os.map((o) => `os:${o}`),\n ];\n const reasons: string[] = [];\n if (skill.disabled) reasons.push(\"disabled\");\n if (skill.blockedByAllowlist) reasons.push(\"blocked by allowlist\");\n return html`\n
    \n
    \n
    \n ${skill.emoji ? `${skill.emoji} ` : \"\"}${skill.name}\n
    \n
    ${clampText(skill.description, 140)}
    \n
    \n ${skill.source}\n \n ${skill.eligible ? \"eligible\" : \"blocked\"}\n \n ${skill.disabled ? html`disabled` : nothing}\n
    \n ${missing.length > 0\n ? html`\n
    \n Missing: ${missing.join(\", \")}\n
    \n `\n : nothing}\n ${reasons.length > 0\n ? html`\n
    \n Reason: ${reasons.join(\", \")}\n
    \n `\n : nothing}\n
    \n
    \n
    \n props.onToggle(skill.skillKey, skill.disabled)}\n >\n ${skill.disabled ? \"Enable\" : \"Disable\"}\n \n ${canInstall\n ? html`\n props.onInstall(skill.skillKey, skill.name, skill.install[0].id)}\n >\n ${busy ? \"Installing…\" : skill.install[0].label}\n `\n : nothing}\n
    \n ${message\n ? html`\n ${message.message}\n
    `\n : nothing}\n ${skill.primaryEnv\n ? html`\n
    \n API key\n \n props.onEdit(skill.skillKey, (e.target as HTMLInputElement).value)}\n />\n
    \n props.onSaveKey(skill.skillKey)}\n >\n Save key\n \n `\n : nothing}\n
    \n \n `;\n}\n","import { html } from \"lit\";\nimport { repeat } from \"lit/directives/repeat.js\";\n\nimport type { AppViewState } from \"./app-view-state\";\nimport { iconForTab, pathForTab, titleForTab, type Tab } from \"./navigation\";\nimport { icons } from \"./icons\";\nimport { loadChatHistory } from \"./controllers/chat\";\nimport { syncUrlWithSessionKey } from \"./app-settings\";\nimport type { SessionsListResult } from \"./types\";\nimport type { ThemeMode } from \"./theme\";\nimport type { ThemeTransitionContext } from \"./theme-transition\";\n\nexport function renderTab(state: AppViewState, tab: Tab) {\n const href = pathForTab(tab, state.basePath);\n return html`\n {\n if (\n event.defaultPrevented ||\n event.button !== 0 ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey\n ) {\n return;\n }\n event.preventDefault();\n state.setTab(tab);\n }}\n title=${titleForTab(tab)}\n >\n ${icons[iconForTab(tab)]}\n ${titleForTab(tab)}\n \n `;\n}\n\nexport function renderChatControls(state: AppViewState) {\n const sessionOptions = resolveSessionOptions(state.sessionKey, state.sessionsResult);\n const disableThinkingToggle = state.onboarding;\n const disableFocusToggle = state.onboarding;\n const showThinking = state.onboarding ? false : state.settings.chatShowThinking;\n const focusActive = state.onboarding ? true : state.settings.chatFocusMode;\n // Refresh icon\n const refreshIcon = html``;\n const focusIcon = html``;\n return html`\n
    \n \n {\n state.resetToolStream();\n void loadChatHistory(state);\n }}\n title=\"Refresh chat history\"\n >\n ${refreshIcon}\n \n |\n {\n if (disableThinkingToggle) return;\n state.applySettings({\n ...state.settings,\n chatShowThinking: !state.settings.chatShowThinking,\n });\n }}\n aria-pressed=${showThinking}\n title=${disableThinkingToggle\n ? \"Disabled during onboarding\"\n : \"Toggle assistant thinking/working output\"}\n >\n ${icons.brain}\n \n {\n if (disableFocusToggle) return;\n state.applySettings({\n ...state.settings,\n chatFocusMode: !state.settings.chatFocusMode,\n });\n }}\n aria-pressed=${focusActive}\n title=${disableFocusToggle\n ? \"Disabled during onboarding\"\n : \"Toggle focus mode (hide sidebar + page header)\"}\n >\n ${focusIcon}\n \n
    \n `;\n}\n\nfunction resolveSessionOptions(sessionKey: string, sessions: SessionsListResult | null) {\n const seen = new Set();\n const options: Array<{ key: string; displayName?: string }> = [];\n\n const resolvedCurrent = sessions?.sessions?.find((s) => s.key === sessionKey);\n\n // Add current session key first\n seen.add(sessionKey);\n options.push({ key: sessionKey, displayName: resolvedCurrent?.displayName });\n\n // Add sessions from the result\n if (sessions?.sessions) {\n for (const s of sessions.sessions) {\n if (!seen.has(s.key)) {\n seen.add(s.key);\n options.push({ key: s.key, displayName: s.displayName });\n }\n }\n }\n\n return options;\n}\n\nconst THEME_ORDER: ThemeMode[] = [\"system\", \"light\", \"dark\"];\n\nexport function renderThemeToggle(state: AppViewState) {\n const index = Math.max(0, THEME_ORDER.indexOf(state.theme));\n const applyTheme = (next: ThemeMode) => (event: MouseEvent) => {\n const element = event.currentTarget as HTMLElement;\n const context: ThemeTransitionContext = { element };\n if (event.clientX || event.clientY) {\n context.pointerClientX = event.clientX;\n context.pointerClientY = event.clientY;\n }\n state.setTheme(next, context);\n };\n\n return html`\n
    \n
    \n \n \n ${renderMonitorIcon()}\n \n \n ${renderSunIcon()}\n \n \n ${renderMoonIcon()}\n \n
    \n
    \n `;\n}\n\nfunction renderSunIcon() {\n return html`\n \n \n \n \n \n \n \n \n \n \n \n `;\n}\n\nfunction renderMoonIcon() {\n return html`\n \n
    \n \n `;\n}\n\nfunction renderMonitorIcon() {\n return html`\n \n \n \n \n \n `;\n}\n","import { html, nothing } from \"lit\";\n\nimport type { GatewayBrowserClient, GatewayHelloOk } from \"./gateway\";\nimport type { AppViewState } from \"./app-view-state\";\nimport { parseAgentSessionKey } from \"../../../src/routing/session-key.js\";\nimport {\n TAB_GROUPS,\n iconForTab,\n pathForTab,\n subtitleForTab,\n titleForTab,\n type Tab,\n} from \"./navigation\";\nimport { icons } from \"./icons\";\nimport type { UiSettings } from \"./storage\";\nimport type { ThemeMode } from \"./theme\";\nimport type { ThemeTransitionContext } from \"./theme-transition\";\nimport type {\n ConfigSnapshot,\n CronJob,\n CronRunLogEntry,\n CronStatus,\n HealthSnapshot,\n LogEntry,\n LogLevel,\n PresenceEntry,\n ChannelsStatusSnapshot,\n SessionsListResult,\n SkillStatusReport,\n StatusSummary,\n} from \"./types\";\nimport type { ChatQueueItem, CronFormState } from \"./ui-types\";\nimport { refreshChatAvatar } from \"./app-chat\";\nimport { renderChat } from \"./views/chat\";\nimport { renderConfig } from \"./views/config\";\nimport { renderChannels } from \"./views/channels\";\nimport { renderCron } from \"./views/cron\";\nimport { renderDebug } from \"./views/debug\";\nimport { renderInstances } from \"./views/instances\";\nimport { renderLogs } from \"./views/logs\";\nimport { renderNodes } from \"./views/nodes\";\nimport { renderOverview } from \"./views/overview\";\nimport { renderSessions } from \"./views/sessions\";\nimport { renderExecApprovalPrompt } from \"./views/exec-approval\";\nimport {\n approveDevicePairing,\n loadDevices,\n rejectDevicePairing,\n revokeDeviceToken,\n rotateDeviceToken,\n} from \"./controllers/devices\";\nimport { renderSkills } from \"./views/skills\";\nimport { renderChatControls, renderTab, renderThemeToggle } from \"./app-render.helpers\";\nimport { loadChannels } from \"./controllers/channels\";\nimport { loadPresence } from \"./controllers/presence\";\nimport { deleteSession, loadSessions, patchSession } from \"./controllers/sessions\";\nimport {\n installSkill,\n loadSkills,\n saveSkillApiKey,\n updateSkillEdit,\n updateSkillEnabled,\n type SkillMessage,\n} from \"./controllers/skills\";\nimport { loadNodes } from \"./controllers/nodes\";\nimport { loadChatHistory } from \"./controllers/chat\";\nimport {\n applyConfig,\n loadConfig,\n runUpdate,\n saveConfig,\n updateConfigFormValue,\n removeConfigFormValue,\n} from \"./controllers/config\";\nimport {\n loadExecApprovals,\n removeExecApprovalsFormValue,\n saveExecApprovals,\n updateExecApprovalsFormValue,\n} from \"./controllers/exec-approvals\";\nimport { loadCronRuns, toggleCronJob, runCronJob, removeCronJob, addCronJob } from \"./controllers/cron\";\nimport { loadDebug, callDebugMethod } from \"./controllers/debug\";\nimport { loadLogs } from \"./controllers/logs\";\n\nconst AVATAR_DATA_RE = /^data:/i;\nconst AVATAR_HTTP_RE = /^https?:\\/\\//i;\n\nfunction resolveAssistantAvatarUrl(state: AppViewState): string | undefined {\n const list = state.agentsList?.agents ?? [];\n const parsed = parseAgentSessionKey(state.sessionKey);\n const agentId =\n parsed?.agentId ??\n state.agentsList?.defaultId ??\n \"main\";\n const agent = list.find((entry) => entry.id === agentId);\n const identity = agent?.identity;\n const candidate = identity?.avatarUrl ?? identity?.avatar;\n if (!candidate) return undefined;\n if (AVATAR_DATA_RE.test(candidate) || AVATAR_HTTP_RE.test(candidate)) return candidate;\n return identity?.avatarUrl;\n}\n\nexport function renderApp(state: AppViewState) {\n const presenceCount = state.presenceEntries.length;\n const sessionsCount = state.sessionsResult?.count ?? null;\n const cronNext = state.cronStatus?.nextWakeAtMs ?? null;\n const chatDisabledReason = state.connected ? null : \"Disconnected from gateway.\";\n const isChat = state.tab === \"chat\";\n const chatFocus = isChat && (state.settings.chatFocusMode || state.onboarding);\n const showThinking = state.onboarding ? false : state.settings.chatShowThinking;\n const assistantAvatarUrl = resolveAssistantAvatarUrl(state);\n const chatAvatarUrl = state.chatAvatarUrl ?? assistantAvatarUrl ?? null;\n\n return html`\n
    \n
    \n
    \n \n state.applySettings({\n ...state.settings,\n navCollapsed: !state.settings.navCollapsed,\n })}\n title=\"${state.settings.navCollapsed ? \"Expand sidebar\" : \"Collapse sidebar\"}\"\n aria-label=\"${state.settings.navCollapsed ? \"Expand sidebar\" : \"Collapse sidebar\"}\"\n >\n ${icons.menu}\n \n
    \n
    \n \"Clawdbot\"\n
    \n
    \n
    CLAWDBOT
    \n
    Gateway Dashboard
    \n
    \n
    \n
    \n
    \n
    \n \n Health\n ${state.connected ? \"OK\" : \"Offline\"}\n
    \n ${renderThemeToggle(state)}\n
    \n
    \n \n
    \n
    \n
    \n
    ${titleForTab(state.tab)}
    \n
    ${subtitleForTab(state.tab)}
    \n
    \n
    \n ${state.lastError\n ? html`
    ${state.lastError}
    `\n : nothing}\n ${isChat ? renderChatControls(state) : nothing}\n
    \n
    \n\n ${state.tab === \"overview\"\n ? renderOverview({\n connected: state.connected,\n hello: state.hello,\n settings: state.settings,\n password: state.password,\n lastError: state.lastError,\n presenceCount,\n sessionsCount,\n cronEnabled: state.cronStatus?.enabled ?? null,\n cronNext,\n lastChannelsRefresh: state.channelsLastSuccess,\n onSettingsChange: (next) => state.applySettings(next),\n onPasswordChange: (next) => (state.password = next),\n onSessionKeyChange: (next) => {\n state.sessionKey = next;\n state.chatMessage = \"\";\n state.resetToolStream();\n state.applySettings({\n ...state.settings,\n sessionKey: next,\n lastActiveSessionKey: next,\n });\n void state.loadAssistantIdentity();\n },\n onConnect: () => state.connect(),\n onRefresh: () => state.loadOverview(),\n })\n : nothing}\n\n ${state.tab === \"channels\"\n ? renderChannels({\n connected: state.connected,\n loading: state.channelsLoading,\n snapshot: state.channelsSnapshot,\n lastError: state.channelsError,\n lastSuccessAt: state.channelsLastSuccess,\n whatsappMessage: state.whatsappLoginMessage,\n whatsappQrDataUrl: state.whatsappLoginQrDataUrl,\n whatsappConnected: state.whatsappLoginConnected,\n whatsappBusy: state.whatsappBusy,\n configSchema: state.configSchema,\n configSchemaLoading: state.configSchemaLoading,\n configForm: state.configForm,\n configUiHints: state.configUiHints,\n configSaving: state.configSaving,\n configFormDirty: state.configFormDirty,\n nostrProfileFormState: state.nostrProfileFormState,\n nostrProfileAccountId: state.nostrProfileAccountId,\n onRefresh: (probe) => loadChannels(state, probe),\n onWhatsAppStart: (force) => state.handleWhatsAppStart(force),\n onWhatsAppWait: () => state.handleWhatsAppWait(),\n onWhatsAppLogout: () => state.handleWhatsAppLogout(),\n onConfigPatch: (path, value) => updateConfigFormValue(state, path, value),\n onConfigSave: () => state.handleChannelConfigSave(),\n onConfigReload: () => state.handleChannelConfigReload(),\n onNostrProfileEdit: (accountId, profile) =>\n state.handleNostrProfileEdit(accountId, profile),\n onNostrProfileCancel: () => state.handleNostrProfileCancel(),\n onNostrProfileFieldChange: (field, value) =>\n state.handleNostrProfileFieldChange(field, value),\n onNostrProfileSave: () => state.handleNostrProfileSave(),\n onNostrProfileImport: () => state.handleNostrProfileImport(),\n onNostrProfileToggleAdvanced: () => state.handleNostrProfileToggleAdvanced(),\n })\n : nothing}\n\n ${state.tab === \"instances\"\n ? renderInstances({\n loading: state.presenceLoading,\n entries: state.presenceEntries,\n lastError: state.presenceError,\n statusMessage: state.presenceStatus,\n onRefresh: () => loadPresence(state),\n })\n : nothing}\n\n ${state.tab === \"sessions\"\n ? renderSessions({\n loading: state.sessionsLoading,\n result: state.sessionsResult,\n error: state.sessionsError,\n activeMinutes: state.sessionsFilterActive,\n limit: state.sessionsFilterLimit,\n includeGlobal: state.sessionsIncludeGlobal,\n includeUnknown: state.sessionsIncludeUnknown,\n basePath: state.basePath,\n onFiltersChange: (next) => {\n state.sessionsFilterActive = next.activeMinutes;\n state.sessionsFilterLimit = next.limit;\n state.sessionsIncludeGlobal = next.includeGlobal;\n state.sessionsIncludeUnknown = next.includeUnknown;\n\t },\n\t onRefresh: () => loadSessions(state),\n\t onPatch: (key, patch) => patchSession(state, key, patch),\n\t onDelete: (key) => deleteSession(state, key),\n\t })\n\t : nothing}\n\n ${state.tab === \"cron\"\n ? renderCron({\n loading: state.cronLoading,\n status: state.cronStatus,\n jobs: state.cronJobs,\n error: state.cronError,\n busy: state.cronBusy,\n form: state.cronForm,\n channels: state.channelsSnapshot?.channelMeta?.length\n ? state.channelsSnapshot.channelMeta.map((entry) => entry.id)\n : state.channelsSnapshot?.channelOrder ?? [],\n channelLabels: state.channelsSnapshot?.channelLabels ?? {},\n channelMeta: state.channelsSnapshot?.channelMeta ?? [],\n runsJobId: state.cronRunsJobId,\n runs: state.cronRuns,\n onFormChange: (patch) => (state.cronForm = { ...state.cronForm, ...patch }),\n onRefresh: () => state.loadCron(),\n onAdd: () => addCronJob(state),\n onToggle: (job, enabled) => toggleCronJob(state, job, enabled),\n onRun: (job) => runCronJob(state, job),\n onRemove: (job) => removeCronJob(state, job),\n onLoadRuns: (jobId) => loadCronRuns(state, jobId),\n })\n : nothing}\n\n ${state.tab === \"skills\"\n ? renderSkills({\n loading: state.skillsLoading,\n report: state.skillsReport,\n error: state.skillsError,\n filter: state.skillsFilter,\n edits: state.skillEdits,\n messages: state.skillMessages,\n busyKey: state.skillsBusyKey,\n onFilterChange: (next) => (state.skillsFilter = next),\n onRefresh: () => loadSkills(state, { clearMessages: true }),\n onToggle: (key, enabled) => updateSkillEnabled(state, key, enabled),\n onEdit: (key, value) => updateSkillEdit(state, key, value),\n onSaveKey: (key) => saveSkillApiKey(state, key),\n onInstall: (skillKey, name, installId) =>\n installSkill(state, skillKey, name, installId),\n })\n : nothing}\n\n ${state.tab === \"nodes\"\n ? renderNodes({\n loading: state.nodesLoading,\n nodes: state.nodes,\n devicesLoading: state.devicesLoading,\n devicesError: state.devicesError,\n devicesList: state.devicesList,\n configForm: state.configForm ?? (state.configSnapshot?.config as Record | null),\n configLoading: state.configLoading,\n configSaving: state.configSaving,\n configDirty: state.configFormDirty,\n configFormMode: state.configFormMode,\n execApprovalsLoading: state.execApprovalsLoading,\n execApprovalsSaving: state.execApprovalsSaving,\n execApprovalsDirty: state.execApprovalsDirty,\n execApprovalsSnapshot: state.execApprovalsSnapshot,\n execApprovalsForm: state.execApprovalsForm,\n execApprovalsSelectedAgent: state.execApprovalsSelectedAgent,\n execApprovalsTarget: state.execApprovalsTarget,\n execApprovalsTargetNodeId: state.execApprovalsTargetNodeId,\n onRefresh: () => loadNodes(state),\n onDevicesRefresh: () => loadDevices(state),\n onDeviceApprove: (requestId) => approveDevicePairing(state, requestId),\n onDeviceReject: (requestId) => rejectDevicePairing(state, requestId),\n onDeviceRotate: (deviceId, role, scopes) =>\n rotateDeviceToken(state, { deviceId, role, scopes }),\n onDeviceRevoke: (deviceId, role) =>\n revokeDeviceToken(state, { deviceId, role }),\n onLoadConfig: () => loadConfig(state),\n onLoadExecApprovals: () => {\n const target =\n state.execApprovalsTarget === \"node\" && state.execApprovalsTargetNodeId\n ? { kind: \"node\" as const, nodeId: state.execApprovalsTargetNodeId }\n : { kind: \"gateway\" as const };\n return loadExecApprovals(state, target);\n },\n onBindDefault: (nodeId) => {\n if (nodeId) {\n updateConfigFormValue(state, [\"tools\", \"exec\", \"node\"], nodeId);\n } else {\n removeConfigFormValue(state, [\"tools\", \"exec\", \"node\"]);\n }\n },\n onBindAgent: (agentIndex, nodeId) => {\n const basePath = [\"agents\", \"list\", agentIndex, \"tools\", \"exec\", \"node\"];\n if (nodeId) {\n updateConfigFormValue(state, basePath, nodeId);\n } else {\n removeConfigFormValue(state, basePath);\n }\n },\n onSaveBindings: () => saveConfig(state),\n onExecApprovalsTargetChange: (kind, nodeId) => {\n state.execApprovalsTarget = kind;\n state.execApprovalsTargetNodeId = nodeId;\n state.execApprovalsSnapshot = null;\n state.execApprovalsForm = null;\n state.execApprovalsDirty = false;\n state.execApprovalsSelectedAgent = null;\n },\n onExecApprovalsSelectAgent: (agentId) => {\n state.execApprovalsSelectedAgent = agentId;\n },\n onExecApprovalsPatch: (path, value) =>\n updateExecApprovalsFormValue(state, path, value),\n onExecApprovalsRemove: (path) =>\n removeExecApprovalsFormValue(state, path),\n onSaveExecApprovals: () => {\n const target =\n state.execApprovalsTarget === \"node\" && state.execApprovalsTargetNodeId\n ? { kind: \"node\" as const, nodeId: state.execApprovalsTargetNodeId }\n : { kind: \"gateway\" as const };\n return saveExecApprovals(state, target);\n },\n })\n : nothing}\n\n ${state.tab === \"chat\"\n ? renderChat({\n sessionKey: state.sessionKey,\n onSessionKeyChange: (next) => {\n state.sessionKey = next;\n state.chatMessage = \"\";\n state.chatStream = null;\n state.chatStreamStartedAt = null;\n state.chatRunId = null;\n state.chatQueue = [];\n state.resetToolStream();\n state.resetChatScroll();\n state.applySettings({\n ...state.settings,\n sessionKey: next,\n lastActiveSessionKey: next,\n });\n void state.loadAssistantIdentity();\n void loadChatHistory(state);\n void refreshChatAvatar(state);\n },\n thinkingLevel: state.chatThinkingLevel,\n showThinking,\n loading: state.chatLoading,\n sending: state.chatSending,\n compactionStatus: state.compactionStatus,\n assistantAvatarUrl: chatAvatarUrl,\n messages: state.chatMessages,\n toolMessages: state.chatToolMessages,\n stream: state.chatStream,\n streamStartedAt: state.chatStreamStartedAt,\n draft: state.chatMessage,\n queue: state.chatQueue,\n connected: state.connected,\n canSend: state.connected,\n disabledReason: chatDisabledReason,\n error: state.lastError,\n sessions: state.sessionsResult,\n focusMode: chatFocus,\n onRefresh: () => {\n state.resetToolStream();\n return Promise.all([loadChatHistory(state), refreshChatAvatar(state)]);\n },\n onToggleFocusMode: () => {\n if (state.onboarding) return;\n state.applySettings({\n ...state.settings,\n chatFocusMode: !state.settings.chatFocusMode,\n });\n },\n onChatScroll: (event) => state.handleChatScroll(event),\n onDraftChange: (next) => (state.chatMessage = next),\n onSend: () => state.handleSendChat(),\n canAbort: Boolean(state.chatRunId),\n onAbort: () => void state.handleAbortChat(),\n onQueueRemove: (id) => state.removeQueuedMessage(id),\n onNewSession: () =>\n state.handleSendChat(\"/new\", { restoreDraft: true }),\n // Sidebar props for tool output viewing\n sidebarOpen: state.sidebarOpen,\n sidebarContent: state.sidebarContent,\n sidebarError: state.sidebarError,\n splitRatio: state.splitRatio,\n onOpenSidebar: (content: string) => state.handleOpenSidebar(content),\n onCloseSidebar: () => state.handleCloseSidebar(),\n onSplitRatioChange: (ratio: number) => state.handleSplitRatioChange(ratio),\n assistantName: state.assistantName,\n assistantAvatar: state.assistantAvatar,\n })\n : nothing}\n\n ${state.tab === \"config\"\n ? renderConfig({\n raw: state.configRaw,\n originalRaw: state.configRawOriginal,\n valid: state.configValid,\n issues: state.configIssues,\n loading: state.configLoading,\n saving: state.configSaving,\n applying: state.configApplying,\n updating: state.updateRunning,\n connected: state.connected,\n schema: state.configSchema,\n schemaLoading: state.configSchemaLoading,\n uiHints: state.configUiHints,\n formMode: state.configFormMode,\n formValue: state.configForm,\n originalValue: state.configFormOriginal,\n searchQuery: state.configSearchQuery,\n activeSection: state.configActiveSection,\n activeSubsection: state.configActiveSubsection,\n onRawChange: (next) => {\n state.configRaw = next;\n },\n onFormModeChange: (mode) => (state.configFormMode = mode),\n onFormPatch: (path, value) => updateConfigFormValue(state, path, value),\n onSearchChange: (query) => (state.configSearchQuery = query),\n onSectionChange: (section) => {\n state.configActiveSection = section;\n state.configActiveSubsection = null;\n },\n onSubsectionChange: (section) => (state.configActiveSubsection = section),\n onReload: () => loadConfig(state),\n onSave: () => saveConfig(state),\n onApply: () => applyConfig(state),\n onUpdate: () => runUpdate(state),\n })\n : nothing}\n\n ${state.tab === \"debug\"\n ? renderDebug({\n loading: state.debugLoading,\n status: state.debugStatus,\n health: state.debugHealth,\n models: state.debugModels,\n heartbeat: state.debugHeartbeat,\n eventLog: state.eventLog,\n callMethod: state.debugCallMethod,\n callParams: state.debugCallParams,\n callResult: state.debugCallResult,\n callError: state.debugCallError,\n onCallMethodChange: (next) => (state.debugCallMethod = next),\n onCallParamsChange: (next) => (state.debugCallParams = next),\n onRefresh: () => loadDebug(state),\n onCall: () => callDebugMethod(state),\n })\n : nothing}\n\n ${state.tab === \"logs\"\n ? renderLogs({\n loading: state.logsLoading,\n error: state.logsError,\n file: state.logsFile,\n entries: state.logsEntries,\n filterText: state.logsFilterText,\n levelFilters: state.logsLevelFilters,\n autoFollow: state.logsAutoFollow,\n truncated: state.logsTruncated,\n onFilterTextChange: (next) => (state.logsFilterText = next),\n onLevelToggle: (level, enabled) => {\n state.logsLevelFilters = { ...state.logsLevelFilters, [level]: enabled };\n },\n onToggleAutoFollow: (next) => (state.logsAutoFollow = next),\n onRefresh: () => loadLogs(state, { reset: true }),\n onExport: (lines, label) => state.exportLogs(lines, label),\n onScroll: (event) => state.handleLogsScroll(event),\n })\n : nothing}\n
    \n ${renderExecApprovalPrompt(state)}\n
    \n `;\n}\n","import type { LogLevel } from \"./types\";\nimport type { CronFormState } from \"./ui-types\";\n\nexport const DEFAULT_LOG_LEVEL_FILTERS: Record = {\n trace: true,\n debug: true,\n info: true,\n warn: true,\n error: true,\n fatal: true,\n};\n\nexport const DEFAULT_CRON_FORM: CronFormState = {\n name: \"\",\n description: \"\",\n agentId: \"\",\n enabled: true,\n scheduleKind: \"every\",\n scheduleAt: \"\",\n everyAmount: \"30\",\n everyUnit: \"minutes\",\n cronExpr: \"0 7 * * *\",\n cronTz: \"\",\n sessionTarget: \"main\",\n wakeMode: \"next-heartbeat\",\n payloadKind: \"systemEvent\",\n payloadText: \"\",\n deliver: false,\n channel: \"last\",\n to: \"\",\n timeoutSeconds: \"\",\n postToMainPrefix: \"\",\n};\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport type { AgentsListResult } from \"../types\";\n\nexport type AgentsState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n agentsLoading: boolean;\n agentsError: string | null;\n agentsList: AgentsListResult | null;\n};\n\nexport async function loadAgents(state: AgentsState) {\n if (!state.client || !state.connected) return;\n if (state.agentsLoading) return;\n state.agentsLoading = true;\n state.agentsError = null;\n try {\n const res = (await state.client.request(\"agents.list\", {})) as AgentsListResult | undefined;\n if (res) state.agentsList = res;\n } catch (err) {\n state.agentsError = String(err);\n } finally {\n state.agentsLoading = false;\n }\n}\n","export const GATEWAY_CLIENT_IDS = {\n WEBCHAT_UI: \"webchat-ui\",\n CONTROL_UI: \"clawdbot-control-ui\",\n WEBCHAT: \"webchat\",\n CLI: \"cli\",\n GATEWAY_CLIENT: \"gateway-client\",\n MACOS_APP: \"clawdbot-macos\",\n IOS_APP: \"clawdbot-ios\",\n ANDROID_APP: \"clawdbot-android\",\n NODE_HOST: \"node-host\",\n TEST: \"test\",\n FINGERPRINT: \"fingerprint\",\n PROBE: \"clawdbot-probe\",\n} as const;\n\nexport type GatewayClientId = (typeof GATEWAY_CLIENT_IDS)[keyof typeof GATEWAY_CLIENT_IDS];\n\n// Back-compat naming (internal): these values are IDs, not display names.\nexport const GATEWAY_CLIENT_NAMES = GATEWAY_CLIENT_IDS;\nexport type GatewayClientName = GatewayClientId;\n\nexport const GATEWAY_CLIENT_MODES = {\n WEBCHAT: \"webchat\",\n CLI: \"cli\",\n UI: \"ui\",\n BACKEND: \"backend\",\n NODE: \"node\",\n PROBE: \"probe\",\n TEST: \"test\",\n} as const;\n\nexport type GatewayClientMode = (typeof GATEWAY_CLIENT_MODES)[keyof typeof GATEWAY_CLIENT_MODES];\n\nexport type GatewayClientInfo = {\n id: GatewayClientId;\n displayName?: string;\n version: string;\n platform: string;\n deviceFamily?: string;\n modelIdentifier?: string;\n mode: GatewayClientMode;\n instanceId?: string;\n};\n\nconst GATEWAY_CLIENT_ID_SET = new Set(Object.values(GATEWAY_CLIENT_IDS));\nconst GATEWAY_CLIENT_MODE_SET = new Set(Object.values(GATEWAY_CLIENT_MODES));\n\nexport function normalizeGatewayClientId(raw?: string | null): GatewayClientId | undefined {\n const normalized = raw?.trim().toLowerCase();\n if (!normalized) return undefined;\n return GATEWAY_CLIENT_ID_SET.has(normalized as GatewayClientId)\n ? (normalized as GatewayClientId)\n : undefined;\n}\n\nexport function normalizeGatewayClientName(raw?: string | null): GatewayClientName | undefined {\n return normalizeGatewayClientId(raw);\n}\n\nexport function normalizeGatewayClientMode(raw?: string | null): GatewayClientMode | undefined {\n const normalized = raw?.trim().toLowerCase();\n if (!normalized) return undefined;\n return GATEWAY_CLIENT_MODE_SET.has(normalized as GatewayClientMode)\n ? (normalized as GatewayClientMode)\n : undefined;\n}\n","export type DeviceAuthPayloadParams = {\n deviceId: string;\n clientId: string;\n clientMode: string;\n role: string;\n scopes: string[];\n signedAtMs: number;\n token?: string | null;\n nonce?: string | null;\n version?: \"v1\" | \"v2\";\n};\n\nexport function buildDeviceAuthPayload(params: DeviceAuthPayloadParams): string {\n const version = params.version ?? (params.nonce ? \"v2\" : \"v1\");\n const scopes = params.scopes.join(\",\");\n const token = params.token ?? \"\";\n const base = [\n version,\n params.deviceId,\n params.clientId,\n params.clientMode,\n params.role,\n scopes,\n String(params.signedAtMs),\n token,\n ];\n if (version === \"v2\") {\n base.push(params.nonce ?? \"\");\n }\n return base.join(\"|\");\n}\n","import { generateUUID } from \"./uuid\";\nimport {\n GATEWAY_CLIENT_MODES,\n GATEWAY_CLIENT_NAMES,\n type GatewayClientMode,\n type GatewayClientName,\n} from \"../../../src/gateway/protocol/client-info.js\";\nimport { buildDeviceAuthPayload } from \"../../../src/gateway/device-auth.js\";\nimport { loadOrCreateDeviceIdentity, signDevicePayload } from \"./device-identity\";\nimport { clearDeviceAuthToken, loadDeviceAuthToken, storeDeviceAuthToken } from \"./device-auth\";\n\nexport type GatewayEventFrame = {\n type: \"event\";\n event: string;\n payload?: unknown;\n seq?: number;\n stateVersion?: { presence: number; health: number };\n};\n\nexport type GatewayResponseFrame = {\n type: \"res\";\n id: string;\n ok: boolean;\n payload?: unknown;\n error?: { code: string; message: string; details?: unknown };\n};\n\nexport type GatewayHelloOk = {\n type: \"hello-ok\";\n protocol: number;\n features?: { methods?: string[]; events?: string[] };\n snapshot?: unknown;\n auth?: {\n deviceToken?: string;\n role?: string;\n scopes?: string[];\n issuedAtMs?: number;\n };\n policy?: { tickIntervalMs?: number };\n};\n\ntype Pending = {\n resolve: (value: unknown) => void;\n reject: (err: unknown) => void;\n};\n\nexport type GatewayBrowserClientOptions = {\n url: string;\n token?: string;\n password?: string;\n clientName?: GatewayClientName;\n clientVersion?: string;\n platform?: string;\n mode?: GatewayClientMode;\n instanceId?: string;\n onHello?: (hello: GatewayHelloOk) => void;\n onEvent?: (evt: GatewayEventFrame) => void;\n onClose?: (info: { code: number; reason: string }) => void;\n onGap?: (info: { expected: number; received: number }) => void;\n};\n\n// 4008 = application-defined code (browser rejects 1008 \"Policy Violation\")\nconst CONNECT_FAILED_CLOSE_CODE = 4008;\n\nexport class GatewayBrowserClient {\n private ws: WebSocket | null = null;\n private pending = new Map();\n private closed = false;\n private lastSeq: number | null = null;\n private connectNonce: string | null = null;\n private connectSent = false;\n private connectTimer: number | null = null;\n private backoffMs = 800;\n\n constructor(private opts: GatewayBrowserClientOptions) {}\n\n start() {\n this.closed = false;\n this.connect();\n }\n\n stop() {\n this.closed = true;\n this.ws?.close();\n this.ws = null;\n this.flushPending(new Error(\"gateway client stopped\"));\n }\n\n get connected() {\n return this.ws?.readyState === WebSocket.OPEN;\n }\n\n private connect() {\n if (this.closed) return;\n this.ws = new WebSocket(this.opts.url);\n this.ws.onopen = () => this.queueConnect();\n this.ws.onmessage = (ev) => this.handleMessage(String(ev.data ?? \"\"));\n this.ws.onclose = (ev) => {\n const reason = String(ev.reason ?? \"\");\n this.ws = null;\n this.flushPending(new Error(`gateway closed (${ev.code}): ${reason}`));\n this.opts.onClose?.({ code: ev.code, reason });\n this.scheduleReconnect();\n };\n this.ws.onerror = () => {\n // ignored; close handler will fire\n };\n }\n\n private scheduleReconnect() {\n if (this.closed) return;\n const delay = this.backoffMs;\n this.backoffMs = Math.min(this.backoffMs * 1.7, 15_000);\n window.setTimeout(() => this.connect(), delay);\n }\n\n private flushPending(err: Error) {\n for (const [, p] of this.pending) p.reject(err);\n this.pending.clear();\n }\n\n private async sendConnect() {\n if (this.connectSent) return;\n this.connectSent = true;\n if (this.connectTimer !== null) {\n window.clearTimeout(this.connectTimer);\n this.connectTimer = null;\n }\n\n // crypto.subtle is only available in secure contexts (HTTPS, localhost).\n // Over plain HTTP, we skip device identity and fall back to token-only auth.\n // Gateways may reject this unless gateway.controlUi.allowInsecureAuth is enabled.\n const isSecureContext = typeof crypto !== \"undefined\" && !!crypto.subtle;\n\n const scopes = [\"operator.admin\", \"operator.approvals\", \"operator.pairing\"];\n const role = \"operator\";\n let deviceIdentity: Awaited> | null = null;\n let canFallbackToShared = false;\n let authToken = this.opts.token;\n\n if (isSecureContext) {\n deviceIdentity = await loadOrCreateDeviceIdentity();\n const storedToken = loadDeviceAuthToken({\n deviceId: deviceIdentity.deviceId,\n role,\n })?.token;\n authToken = storedToken ?? this.opts.token;\n canFallbackToShared = Boolean(storedToken && this.opts.token);\n }\n const auth =\n authToken || this.opts.password\n ? {\n token: authToken,\n password: this.opts.password,\n }\n : undefined;\n\n let device:\n | {\n id: string;\n publicKey: string;\n signature: string;\n signedAt: number;\n nonce: string | undefined;\n }\n | undefined;\n\n if (isSecureContext && deviceIdentity) {\n const signedAtMs = Date.now();\n const nonce = this.connectNonce ?? undefined;\n const payload = buildDeviceAuthPayload({\n deviceId: deviceIdentity.deviceId,\n clientId: this.opts.clientName ?? GATEWAY_CLIENT_NAMES.CONTROL_UI,\n clientMode: this.opts.mode ?? GATEWAY_CLIENT_MODES.WEBCHAT,\n role,\n scopes,\n signedAtMs,\n token: authToken ?? null,\n nonce,\n });\n const signature = await signDevicePayload(deviceIdentity.privateKey, payload);\n device = {\n id: deviceIdentity.deviceId,\n publicKey: deviceIdentity.publicKey,\n signature,\n signedAt: signedAtMs,\n nonce,\n };\n }\n const params = {\n minProtocol: 3,\n maxProtocol: 3,\n client: {\n id: this.opts.clientName ?? GATEWAY_CLIENT_NAMES.CONTROL_UI,\n version: this.opts.clientVersion ?? \"dev\",\n platform: this.opts.platform ?? navigator.platform ?? \"web\",\n mode: this.opts.mode ?? GATEWAY_CLIENT_MODES.WEBCHAT,\n instanceId: this.opts.instanceId,\n },\n role,\n scopes,\n device,\n caps: [],\n auth,\n userAgent: navigator.userAgent,\n locale: navigator.language,\n };\n\n void this.request(\"connect\", params)\n .then((hello) => {\n if (hello?.auth?.deviceToken && deviceIdentity) {\n storeDeviceAuthToken({\n deviceId: deviceIdentity.deviceId,\n role: hello.auth.role ?? role,\n token: hello.auth.deviceToken,\n scopes: hello.auth.scopes ?? [],\n });\n }\n this.backoffMs = 800;\n this.opts.onHello?.(hello);\n })\n .catch(() => {\n if (canFallbackToShared && deviceIdentity) {\n clearDeviceAuthToken({ deviceId: deviceIdentity.deviceId, role });\n }\n this.ws?.close(CONNECT_FAILED_CLOSE_CODE, \"connect failed\");\n });\n }\n\n private handleMessage(raw: string) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return;\n }\n\n const frame = parsed as { type?: unknown };\n if (frame.type === \"event\") {\n const evt = parsed as GatewayEventFrame;\n if (evt.event === \"connect.challenge\") {\n const payload = evt.payload as { nonce?: unknown } | undefined;\n const nonce = payload && typeof payload.nonce === \"string\" ? payload.nonce : null;\n if (nonce) {\n this.connectNonce = nonce;\n void this.sendConnect();\n }\n return;\n }\n const seq = typeof evt.seq === \"number\" ? evt.seq : null;\n if (seq !== null) {\n if (this.lastSeq !== null && seq > this.lastSeq + 1) {\n this.opts.onGap?.({ expected: this.lastSeq + 1, received: seq });\n }\n this.lastSeq = seq;\n }\n try {\n this.opts.onEvent?.(evt);\n } catch (err) {\n console.error(\"[gateway] event handler error:\", err);\n }\n return;\n }\n\n if (frame.type === \"res\") {\n const res = parsed as GatewayResponseFrame;\n const pending = this.pending.get(res.id);\n if (!pending) return;\n this.pending.delete(res.id);\n if (res.ok) pending.resolve(res.payload);\n else pending.reject(new Error(res.error?.message ?? \"request failed\"));\n return;\n }\n }\n\n request(method: string, params?: unknown): Promise {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {\n return Promise.reject(new Error(\"gateway not connected\"));\n }\n const id = generateUUID();\n const frame = { type: \"req\", id, method, params };\n const p = new Promise((resolve, reject) => {\n this.pending.set(id, { resolve: (v) => resolve(v as T), reject });\n });\n this.ws.send(JSON.stringify(frame));\n return p;\n }\n\n private queueConnect() {\n this.connectNonce = null;\n this.connectSent = false;\n if (this.connectTimer !== null) window.clearTimeout(this.connectTimer);\n this.connectTimer = window.setTimeout(() => {\n void this.sendConnect();\n }, 750);\n }\n}\n","export type ExecApprovalRequestPayload = {\n command: string;\n cwd?: string | null;\n host?: string | null;\n security?: string | null;\n ask?: string | null;\n agentId?: string | null;\n resolvedPath?: string | null;\n sessionKey?: string | null;\n};\n\nexport type ExecApprovalRequest = {\n id: string;\n request: ExecApprovalRequestPayload;\n createdAtMs: number;\n expiresAtMs: number;\n};\n\nexport type ExecApprovalResolved = {\n id: string;\n decision?: string | null;\n resolvedBy?: string | null;\n ts?: number | null;\n};\n\nfunction isRecord(value: unknown): value is Record {\n return typeof value === \"object\" && value !== null;\n}\n\nexport function parseExecApprovalRequested(payload: unknown): ExecApprovalRequest | null {\n if (!isRecord(payload)) return null;\n const id = typeof payload.id === \"string\" ? payload.id.trim() : \"\";\n const request = payload.request;\n if (!id || !isRecord(request)) return null;\n const command = typeof request.command === \"string\" ? request.command.trim() : \"\";\n if (!command) return null;\n const createdAtMs = typeof payload.createdAtMs === \"number\" ? payload.createdAtMs : 0;\n const expiresAtMs = typeof payload.expiresAtMs === \"number\" ? payload.expiresAtMs : 0;\n if (!createdAtMs || !expiresAtMs) return null;\n return {\n id,\n request: {\n command,\n cwd: typeof request.cwd === \"string\" ? request.cwd : null,\n host: typeof request.host === \"string\" ? request.host : null,\n security: typeof request.security === \"string\" ? request.security : null,\n ask: typeof request.ask === \"string\" ? request.ask : null,\n agentId: typeof request.agentId === \"string\" ? request.agentId : null,\n resolvedPath: typeof request.resolvedPath === \"string\" ? request.resolvedPath : null,\n sessionKey: typeof request.sessionKey === \"string\" ? request.sessionKey : null,\n },\n createdAtMs,\n expiresAtMs,\n };\n}\n\nexport function parseExecApprovalResolved(payload: unknown): ExecApprovalResolved | null {\n if (!isRecord(payload)) return null;\n const id = typeof payload.id === \"string\" ? payload.id.trim() : \"\";\n if (!id) return null;\n return {\n id,\n decision: typeof payload.decision === \"string\" ? payload.decision : null,\n resolvedBy: typeof payload.resolvedBy === \"string\" ? payload.resolvedBy : null,\n ts: typeof payload.ts === \"number\" ? payload.ts : null,\n };\n}\n\nexport function pruneExecApprovalQueue(queue: ExecApprovalRequest[]): ExecApprovalRequest[] {\n const now = Date.now();\n return queue.filter((entry) => entry.expiresAtMs > now);\n}\n\nexport function addExecApproval(\n queue: ExecApprovalRequest[],\n entry: ExecApprovalRequest,\n): ExecApprovalRequest[] {\n const next = pruneExecApprovalQueue(queue).filter((item) => item.id !== entry.id);\n next.push(entry);\n return next;\n}\n\nexport function removeExecApproval(queue: ExecApprovalRequest[], id: string): ExecApprovalRequest[] {\n return pruneExecApprovalQueue(queue).filter((entry) => entry.id !== id);\n}\n","import type { GatewayBrowserClient } from \"../gateway\";\nimport {\n normalizeAssistantIdentity,\n type AssistantIdentity,\n} from \"../assistant-identity\";\n\nexport type AssistantIdentityState = {\n client: GatewayBrowserClient | null;\n connected: boolean;\n sessionKey: string;\n assistantName: string;\n assistantAvatar: string | null;\n assistantAgentId: string | null;\n};\n\nexport async function loadAssistantIdentity(\n state: AssistantIdentityState,\n opts?: { sessionKey?: string },\n) {\n if (!state.client || !state.connected) return;\n const sessionKey = opts?.sessionKey?.trim() || state.sessionKey.trim();\n const params = sessionKey ? { sessionKey } : {};\n try {\n const res = (await state.client.request(\"agent.identity.get\", params)) as\n | Partial\n | undefined;\n if (!res) return;\n const normalized = normalizeAssistantIdentity(res);\n state.assistantName = normalized.name;\n state.assistantAvatar = normalized.avatar;\n state.assistantAgentId = normalized.agentId ?? null;\n } catch {\n // Ignore errors; keep last known identity.\n }\n}\n","import { loadChatHistory } from \"./controllers/chat\";\nimport { loadDevices } from \"./controllers/devices\";\nimport { loadNodes } from \"./controllers/nodes\";\nimport { loadAgents } from \"./controllers/agents\";\nimport type { GatewayEventFrame, GatewayHelloOk } from \"./gateway\";\nimport { GatewayBrowserClient } from \"./gateway\";\nimport type { EventLogEntry } from \"./app-events\";\nimport type { AgentsListResult, PresenceEntry, HealthSnapshot, StatusSummary } from \"./types\";\nimport type { Tab } from \"./navigation\";\nimport type { UiSettings } from \"./storage\";\nimport { handleAgentEvent, resetToolStream, type AgentEventPayload } from \"./app-tool-stream\";\nimport { flushChatQueueForEvent } from \"./app-chat\";\nimport {\n applySettings,\n loadCron,\n refreshActiveTab,\n setLastActiveSessionKey,\n} from \"./app-settings\";\nimport { handleChatEvent, type ChatEventPayload } from \"./controllers/chat\";\nimport {\n addExecApproval,\n parseExecApprovalRequested,\n parseExecApprovalResolved,\n removeExecApproval,\n} from \"./controllers/exec-approval\";\nimport type { ClawdbotApp } from \"./app\";\nimport type { ExecApprovalRequest } from \"./controllers/exec-approval\";\nimport { loadAssistantIdentity } from \"./controllers/assistant-identity\";\n\ntype GatewayHost = {\n settings: UiSettings;\n password: string;\n client: GatewayBrowserClient | null;\n connected: boolean;\n hello: GatewayHelloOk | null;\n lastError: string | null;\n onboarding?: boolean;\n eventLogBuffer: EventLogEntry[];\n eventLog: EventLogEntry[];\n tab: Tab;\n presenceEntries: PresenceEntry[];\n presenceError: string | null;\n presenceStatus: StatusSummary | null;\n agentsLoading: boolean;\n agentsList: AgentsListResult | null;\n agentsError: string | null;\n debugHealth: HealthSnapshot | null;\n assistantName: string;\n assistantAvatar: string | null;\n assistantAgentId: string | null;\n sessionKey: string;\n chatRunId: string | null;\n execApprovalQueue: ExecApprovalRequest[];\n execApprovalError: string | null;\n};\n\ntype SessionDefaultsSnapshot = {\n defaultAgentId?: string;\n mainKey?: string;\n mainSessionKey?: string;\n scope?: string;\n};\n\nfunction normalizeSessionKeyForDefaults(\n value: string | undefined,\n defaults: SessionDefaultsSnapshot,\n): string {\n const raw = (value ?? \"\").trim();\n const mainSessionKey = defaults.mainSessionKey?.trim();\n if (!mainSessionKey) return raw;\n if (!raw) return mainSessionKey;\n const mainKey = defaults.mainKey?.trim() || \"main\";\n const defaultAgentId = defaults.defaultAgentId?.trim();\n const isAlias =\n raw === \"main\" ||\n raw === mainKey ||\n (defaultAgentId &&\n (raw === `agent:${defaultAgentId}:main` ||\n raw === `agent:${defaultAgentId}:${mainKey}`));\n return isAlias ? mainSessionKey : raw;\n}\n\nfunction applySessionDefaults(host: GatewayHost, defaults?: SessionDefaultsSnapshot) {\n if (!defaults?.mainSessionKey) return;\n const resolvedSessionKey = normalizeSessionKeyForDefaults(host.sessionKey, defaults);\n const resolvedSettingsSessionKey = normalizeSessionKeyForDefaults(\n host.settings.sessionKey,\n defaults,\n );\n const resolvedLastActiveSessionKey = normalizeSessionKeyForDefaults(\n host.settings.lastActiveSessionKey,\n defaults,\n );\n const nextSessionKey = resolvedSessionKey || resolvedSettingsSessionKey || host.sessionKey;\n const nextSettings = {\n ...host.settings,\n sessionKey: resolvedSettingsSessionKey || nextSessionKey,\n lastActiveSessionKey: resolvedLastActiveSessionKey || nextSessionKey,\n };\n const shouldUpdateSettings =\n nextSettings.sessionKey !== host.settings.sessionKey ||\n nextSettings.lastActiveSessionKey !== host.settings.lastActiveSessionKey;\n if (nextSessionKey !== host.sessionKey) {\n host.sessionKey = nextSessionKey;\n }\n if (shouldUpdateSettings) {\n applySettings(host as unknown as Parameters[0], nextSettings);\n }\n}\n\nexport function connectGateway(host: GatewayHost) {\n host.lastError = null;\n host.hello = null;\n host.connected = false;\n host.execApprovalQueue = [];\n host.execApprovalError = null;\n\n host.client?.stop();\n host.client = new GatewayBrowserClient({\n url: host.settings.gatewayUrl,\n token: host.settings.token.trim() ? host.settings.token : undefined,\n password: host.password.trim() ? host.password : undefined,\n clientName: \"clawdbot-control-ui\",\n mode: \"webchat\",\n onHello: (hello) => {\n host.connected = true;\n host.lastError = null;\n host.hello = hello;\n applySnapshot(host, hello);\n void loadAssistantIdentity(host as unknown as ClawdbotApp);\n void loadAgents(host as unknown as ClawdbotApp);\n void loadNodes(host as unknown as ClawdbotApp, { quiet: true });\n void loadDevices(host as unknown as ClawdbotApp, { quiet: true });\n void refreshActiveTab(host as unknown as Parameters[0]);\n },\n onClose: ({ code, reason }) => {\n host.connected = false;\n // Code 1012 = Service Restart (expected during config saves, don't show as error)\n if (code !== 1012) {\n host.lastError = `disconnected (${code}): ${reason || \"no reason\"}`;\n }\n },\n onEvent: (evt) => handleGatewayEvent(host, evt),\n onGap: ({ expected, received }) => {\n host.lastError = `event gap detected (expected seq ${expected}, got ${received}); refresh recommended`;\n },\n });\n host.client.start();\n}\n\nexport function handleGatewayEvent(host: GatewayHost, evt: GatewayEventFrame) {\n try {\n handleGatewayEventUnsafe(host, evt);\n } catch (err) {\n console.error(\"[gateway] handleGatewayEvent error:\", evt.event, err);\n }\n}\n\nfunction handleGatewayEventUnsafe(host: GatewayHost, evt: GatewayEventFrame) {\n host.eventLogBuffer = [\n { ts: Date.now(), event: evt.event, payload: evt.payload },\n ...host.eventLogBuffer,\n ].slice(0, 250);\n if (host.tab === \"debug\") {\n host.eventLog = host.eventLogBuffer;\n }\n\n if (evt.event === \"agent\") {\n if (host.onboarding) return;\n handleAgentEvent(\n host as unknown as Parameters[0],\n evt.payload as AgentEventPayload | undefined,\n );\n return;\n }\n\n if (evt.event === \"chat\") {\n const payload = evt.payload as ChatEventPayload | undefined;\n if (payload?.sessionKey) {\n setLastActiveSessionKey(\n host as unknown as Parameters[0],\n payload.sessionKey,\n );\n }\n const state = handleChatEvent(host as unknown as ClawdbotApp, payload);\n if (state === \"final\" || state === \"error\" || state === \"aborted\") {\n resetToolStream(host as unknown as Parameters[0]);\n void flushChatQueueForEvent(\n host as unknown as Parameters[0],\n );\n }\n if (state === \"final\") void loadChatHistory(host as unknown as ClawdbotApp);\n return;\n }\n\n if (evt.event === \"presence\") {\n const payload = evt.payload as { presence?: PresenceEntry[] } | undefined;\n if (payload?.presence && Array.isArray(payload.presence)) {\n host.presenceEntries = payload.presence;\n host.presenceError = null;\n host.presenceStatus = null;\n }\n return;\n }\n\n if (evt.event === \"cron\" && host.tab === \"cron\") {\n void loadCron(host as unknown as Parameters[0]);\n }\n\n if (evt.event === \"device.pair.requested\" || evt.event === \"device.pair.resolved\") {\n void loadDevices(host as unknown as ClawdbotApp, { quiet: true });\n }\n\n if (evt.event === \"exec.approval.requested\") {\n const entry = parseExecApprovalRequested(evt.payload);\n if (entry) {\n host.execApprovalQueue = addExecApproval(host.execApprovalQueue, entry);\n host.execApprovalError = null;\n const delay = Math.max(0, entry.expiresAtMs - Date.now() + 500);\n window.setTimeout(() => {\n host.execApprovalQueue = removeExecApproval(host.execApprovalQueue, entry.id);\n }, delay);\n }\n return;\n }\n\n if (evt.event === \"exec.approval.resolved\") {\n const resolved = parseExecApprovalResolved(evt.payload);\n if (resolved) {\n host.execApprovalQueue = removeExecApproval(host.execApprovalQueue, resolved.id);\n }\n }\n}\n\nexport function applySnapshot(host: GatewayHost, hello: GatewayHelloOk) {\n const snapshot = hello.snapshot as\n | {\n presence?: PresenceEntry[];\n health?: HealthSnapshot;\n sessionDefaults?: SessionDefaultsSnapshot;\n }\n | undefined;\n if (snapshot?.presence && Array.isArray(snapshot.presence)) {\n host.presenceEntries = snapshot.presence;\n }\n if (snapshot?.health) {\n host.debugHealth = snapshot.health;\n }\n if (snapshot?.sessionDefaults) {\n applySessionDefaults(host, snapshot.sessionDefaults);\n }\n}\n","import type { Tab } from \"./navigation\";\nimport { connectGateway } from \"./app-gateway\";\nimport {\n applySettingsFromUrl,\n attachThemeListener,\n detachThemeListener,\n inferBasePath,\n syncTabWithLocation,\n syncThemeWithSettings,\n} from \"./app-settings\";\nimport { observeTopbar, scheduleChatScroll, scheduleLogsScroll } from \"./app-scroll\";\nimport {\n startLogsPolling,\n startNodesPolling,\n stopLogsPolling,\n stopNodesPolling,\n startDebugPolling,\n stopDebugPolling,\n} from \"./app-polling\";\n\ntype LifecycleHost = {\n basePath: string;\n tab: Tab;\n chatHasAutoScrolled: boolean;\n chatLoading: boolean;\n chatMessages: unknown[];\n chatToolMessages: unknown[];\n chatStream: string;\n logsAutoFollow: boolean;\n logsAtBottom: boolean;\n logsEntries: unknown[];\n popStateHandler: () => void;\n topbarObserver: ResizeObserver | null;\n};\n\nexport function handleConnected(host: LifecycleHost) {\n host.basePath = inferBasePath();\n syncTabWithLocation(\n host as unknown as Parameters[0],\n true,\n );\n syncThemeWithSettings(\n host as unknown as Parameters[0],\n );\n attachThemeListener(\n host as unknown as Parameters[0],\n );\n window.addEventListener(\"popstate\", host.popStateHandler);\n applySettingsFromUrl(\n host as unknown as Parameters[0],\n );\n connectGateway(host as unknown as Parameters[0]);\n startNodesPolling(host as unknown as Parameters[0]);\n if (host.tab === \"logs\") {\n startLogsPolling(host as unknown as Parameters[0]);\n }\n if (host.tab === \"debug\") {\n startDebugPolling(host as unknown as Parameters[0]);\n }\n}\n\nexport function handleFirstUpdated(host: LifecycleHost) {\n observeTopbar(host as unknown as Parameters[0]);\n}\n\nexport function handleDisconnected(host: LifecycleHost) {\n window.removeEventListener(\"popstate\", host.popStateHandler);\n stopNodesPolling(host as unknown as Parameters[0]);\n stopLogsPolling(host as unknown as Parameters[0]);\n stopDebugPolling(host as unknown as Parameters[0]);\n detachThemeListener(\n host as unknown as Parameters[0],\n );\n host.topbarObserver?.disconnect();\n host.topbarObserver = null;\n}\n\nexport function handleUpdated(\n host: LifecycleHost,\n changed: Map,\n) {\n if (\n host.tab === \"chat\" &&\n (changed.has(\"chatMessages\") ||\n changed.has(\"chatToolMessages\") ||\n changed.has(\"chatStream\") ||\n changed.has(\"chatLoading\") ||\n changed.has(\"tab\"))\n ) {\n const forcedByTab = changed.has(\"tab\");\n const forcedByLoad =\n changed.has(\"chatLoading\") &&\n changed.get(\"chatLoading\") === true &&\n host.chatLoading === false;\n scheduleChatScroll(\n host as unknown as Parameters[0],\n forcedByTab || forcedByLoad || !host.chatHasAutoScrolled,\n );\n }\n if (\n host.tab === \"logs\" &&\n (changed.has(\"logsEntries\") || changed.has(\"logsAutoFollow\") || changed.has(\"tab\"))\n ) {\n if (host.logsAutoFollow && host.logsAtBottom) {\n scheduleLogsScroll(\n host as unknown as Parameters[0],\n changed.has(\"tab\") || changed.has(\"logsAutoFollow\"),\n );\n }\n }\n}\n","import {\n loadChannels,\n logoutWhatsApp,\n startWhatsAppLogin,\n waitWhatsAppLogin,\n} from \"./controllers/channels\";\nimport { loadConfig, saveConfig } from \"./controllers/config\";\nimport type { ClawdbotApp } from \"./app\";\nimport type { NostrProfile } from \"./types\";\nimport { createNostrProfileFormState } from \"./views/channels.nostr-profile-form\";\n\nexport async function handleWhatsAppStart(host: ClawdbotApp, force: boolean) {\n await startWhatsAppLogin(host, force);\n await loadChannels(host, true);\n}\n\nexport async function handleWhatsAppWait(host: ClawdbotApp) {\n await waitWhatsAppLogin(host);\n await loadChannels(host, true);\n}\n\nexport async function handleWhatsAppLogout(host: ClawdbotApp) {\n await logoutWhatsApp(host);\n await loadChannels(host, true);\n}\n\nexport async function handleChannelConfigSave(host: ClawdbotApp) {\n await saveConfig(host);\n await loadConfig(host);\n await loadChannels(host, true);\n}\n\nexport async function handleChannelConfigReload(host: ClawdbotApp) {\n await loadConfig(host);\n await loadChannels(host, true);\n}\n\nfunction parseValidationErrors(details: unknown): Record {\n if (!Array.isArray(details)) return {};\n const errors: Record = {};\n for (const entry of details) {\n if (typeof entry !== \"string\") continue;\n const [rawField, ...rest] = entry.split(\":\");\n if (!rawField || rest.length === 0) continue;\n const field = rawField.trim();\n const message = rest.join(\":\").trim();\n if (field && message) errors[field] = message;\n }\n return errors;\n}\n\nfunction resolveNostrAccountId(host: ClawdbotApp): string {\n const accounts = host.channelsSnapshot?.channelAccounts?.nostr ?? [];\n return accounts[0]?.accountId ?? host.nostrProfileAccountId ?? \"default\";\n}\n\nfunction buildNostrProfileUrl(accountId: string, suffix = \"\"): string {\n return `/api/channels/nostr/${encodeURIComponent(accountId)}/profile${suffix}`;\n}\n\nexport function handleNostrProfileEdit(\n host: ClawdbotApp,\n accountId: string,\n profile: NostrProfile | null,\n) {\n host.nostrProfileAccountId = accountId;\n host.nostrProfileFormState = createNostrProfileFormState(profile ?? undefined);\n}\n\nexport function handleNostrProfileCancel(host: ClawdbotApp) {\n host.nostrProfileFormState = null;\n host.nostrProfileAccountId = null;\n}\n\nexport function handleNostrProfileFieldChange(\n host: ClawdbotApp,\n field: keyof NostrProfile,\n value: string,\n) {\n const state = host.nostrProfileFormState;\n if (!state) return;\n host.nostrProfileFormState = {\n ...state,\n values: {\n ...state.values,\n [field]: value,\n },\n fieldErrors: {\n ...state.fieldErrors,\n [field]: \"\",\n },\n };\n}\n\nexport function handleNostrProfileToggleAdvanced(host: ClawdbotApp) {\n const state = host.nostrProfileFormState;\n if (!state) return;\n host.nostrProfileFormState = {\n ...state,\n showAdvanced: !state.showAdvanced,\n };\n}\n\nexport async function handleNostrProfileSave(host: ClawdbotApp) {\n const state = host.nostrProfileFormState;\n if (!state || state.saving) return;\n const accountId = resolveNostrAccountId(host);\n\n host.nostrProfileFormState = {\n ...state,\n saving: true,\n error: null,\n success: null,\n fieldErrors: {},\n };\n\n try {\n const response = await fetch(buildNostrProfileUrl(accountId), {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(state.values),\n });\n const data = (await response.json().catch(() => null)) as\n | { ok?: boolean; error?: string; details?: unknown; persisted?: boolean }\n | null;\n\n if (!response.ok || data?.ok === false || !data) {\n const errorMessage = data?.error ?? `Profile update failed (${response.status})`;\n host.nostrProfileFormState = {\n ...state,\n saving: false,\n error: errorMessage,\n success: null,\n fieldErrors: parseValidationErrors(data?.details),\n };\n return;\n }\n\n if (!data.persisted) {\n host.nostrProfileFormState = {\n ...state,\n saving: false,\n error: \"Profile publish failed on all relays.\",\n success: null,\n };\n return;\n }\n\n host.nostrProfileFormState = {\n ...state,\n saving: false,\n error: null,\n success: \"Profile published to relays.\",\n fieldErrors: {},\n original: { ...state.values },\n };\n await loadChannels(host, true);\n } catch (err) {\n host.nostrProfileFormState = {\n ...state,\n saving: false,\n error: `Profile update failed: ${String(err)}`,\n success: null,\n };\n }\n}\n\nexport async function handleNostrProfileImport(host: ClawdbotApp) {\n const state = host.nostrProfileFormState;\n if (!state || state.importing) return;\n const accountId = resolveNostrAccountId(host);\n\n host.nostrProfileFormState = {\n ...state,\n importing: true,\n error: null,\n success: null,\n };\n\n try {\n const response = await fetch(buildNostrProfileUrl(accountId, \"/import\"), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ autoMerge: true }),\n });\n const data = (await response.json().catch(() => null)) as\n | { ok?: boolean; error?: string; imported?: NostrProfile; merged?: NostrProfile; saved?: boolean }\n | null;\n\n if (!response.ok || data?.ok === false || !data) {\n const errorMessage = data?.error ?? `Profile import failed (${response.status})`;\n host.nostrProfileFormState = {\n ...state,\n importing: false,\n error: errorMessage,\n success: null,\n };\n return;\n }\n\n const merged = data.merged ?? data.imported ?? null;\n const nextValues = merged ? { ...state.values, ...merged } : state.values;\n const showAdvanced = Boolean(\n nextValues.banner || nextValues.website || nextValues.nip05 || nextValues.lud16,\n );\n\n host.nostrProfileFormState = {\n ...state,\n importing: false,\n values: nextValues,\n error: null,\n success: data.saved\n ? \"Profile imported from relays. Review and publish.\"\n : \"Profile imported. Review and publish.\",\n showAdvanced,\n };\n\n if (data.saved) {\n await loadChannels(host, true);\n }\n } catch (err) {\n host.nostrProfileFormState = {\n ...state,\n importing: false,\n error: `Profile import failed: ${String(err)}`,\n success: null,\n };\n }\n}\n","import { LitElement, html, nothing } from \"lit\";\nimport { customElement, state } from \"lit/decorators.js\";\n\nimport type { GatewayBrowserClient, GatewayHelloOk } from \"./gateway\";\nimport { resolveInjectedAssistantIdentity } from \"./assistant-identity\";\nimport { loadSettings, type UiSettings } from \"./storage\";\nimport { renderApp } from \"./app-render\";\nimport type { Tab } from \"./navigation\";\nimport type { ResolvedTheme, ThemeMode } from \"./theme\";\nimport type {\n AgentsListResult,\n ConfigSnapshot,\n ConfigUiHints,\n CronJob,\n CronRunLogEntry,\n CronStatus,\n HealthSnapshot,\n LogEntry,\n LogLevel,\n PresenceEntry,\n ChannelsStatusSnapshot,\n SessionsListResult,\n SkillStatusReport,\n StatusSummary,\n NostrProfile,\n} from \"./types\";\nimport { type ChatQueueItem, type CronFormState } from \"./ui-types\";\nimport type { EventLogEntry } from \"./app-events\";\nimport { DEFAULT_CRON_FORM, DEFAULT_LOG_LEVEL_FILTERS } from \"./app-defaults\";\nimport type {\n ExecApprovalsFile,\n ExecApprovalsSnapshot,\n} from \"./controllers/exec-approvals\";\nimport type { DevicePairingList } from \"./controllers/devices\";\nimport type { ExecApprovalRequest } from \"./controllers/exec-approval\";\nimport {\n resetToolStream as resetToolStreamInternal,\n type ToolStreamEntry,\n} from \"./app-tool-stream\";\nimport {\n exportLogs as exportLogsInternal,\n handleChatScroll as handleChatScrollInternal,\n handleLogsScroll as handleLogsScrollInternal,\n resetChatScroll as resetChatScrollInternal,\n} from \"./app-scroll\";\nimport { connectGateway as connectGatewayInternal } from \"./app-gateway\";\nimport {\n handleConnected,\n handleDisconnected,\n handleFirstUpdated,\n handleUpdated,\n} from \"./app-lifecycle\";\nimport {\n applySettings as applySettingsInternal,\n loadCron as loadCronInternal,\n loadOverview as loadOverviewInternal,\n setTab as setTabInternal,\n setTheme as setThemeInternal,\n onPopState as onPopStateInternal,\n} from \"./app-settings\";\nimport {\n handleAbortChat as handleAbortChatInternal,\n handleSendChat as handleSendChatInternal,\n removeQueuedMessage as removeQueuedMessageInternal,\n} from \"./app-chat\";\nimport {\n handleChannelConfigReload as handleChannelConfigReloadInternal,\n handleChannelConfigSave as handleChannelConfigSaveInternal,\n handleNostrProfileCancel as handleNostrProfileCancelInternal,\n handleNostrProfileEdit as handleNostrProfileEditInternal,\n handleNostrProfileFieldChange as handleNostrProfileFieldChangeInternal,\n handleNostrProfileImport as handleNostrProfileImportInternal,\n handleNostrProfileSave as handleNostrProfileSaveInternal,\n handleNostrProfileToggleAdvanced as handleNostrProfileToggleAdvancedInternal,\n handleWhatsAppLogout as handleWhatsAppLogoutInternal,\n handleWhatsAppStart as handleWhatsAppStartInternal,\n handleWhatsAppWait as handleWhatsAppWaitInternal,\n} from \"./app-channels\";\nimport type { NostrProfileFormState } from \"./views/channels.nostr-profile-form\";\nimport { loadAssistantIdentity as loadAssistantIdentityInternal } from \"./controllers/assistant-identity\";\n\ndeclare global {\n interface Window {\n __CLAWDBOT_CONTROL_UI_BASE_PATH__?: string;\n }\n}\n\nconst injectedAssistantIdentity = resolveInjectedAssistantIdentity();\n\nfunction resolveOnboardingMode(): boolean {\n if (!window.location.search) return false;\n const params = new URLSearchParams(window.location.search);\n const raw = params.get(\"onboarding\");\n if (!raw) return false;\n const normalized = raw.trim().toLowerCase();\n return normalized === \"1\" || normalized === \"true\" || normalized === \"yes\" || normalized === \"on\";\n}\n\n@customElement(\"clawdbot-app\")\nexport class ClawdbotApp extends LitElement {\n @state() settings: UiSettings = loadSettings();\n @state() password = \"\";\n @state() tab: Tab = \"chat\";\n @state() onboarding = resolveOnboardingMode();\n @state() connected = false;\n @state() theme: ThemeMode = this.settings.theme ?? \"system\";\n @state() themeResolved: ResolvedTheme = \"dark\";\n @state() hello: GatewayHelloOk | null = null;\n @state() lastError: string | null = null;\n @state() eventLog: EventLogEntry[] = [];\n private eventLogBuffer: EventLogEntry[] = [];\n private toolStreamSyncTimer: number | null = null;\n private sidebarCloseTimer: number | null = null;\n\n @state() assistantName = injectedAssistantIdentity.name;\n @state() assistantAvatar = injectedAssistantIdentity.avatar;\n @state() assistantAgentId = injectedAssistantIdentity.agentId ?? null;\n\n @state() sessionKey = this.settings.sessionKey;\n @state() chatLoading = false;\n @state() chatSending = false;\n @state() chatMessage = \"\";\n @state() chatMessages: unknown[] = [];\n @state() chatToolMessages: unknown[] = [];\n @state() chatStream: string | null = null;\n @state() chatStreamStartedAt: number | null = null;\n @state() chatRunId: string | null = null;\n @state() compactionStatus: import(\"./app-tool-stream\").CompactionStatus | null = null;\n @state() chatAvatarUrl: string | null = null;\n @state() chatThinkingLevel: string | null = null;\n @state() chatQueue: ChatQueueItem[] = [];\n // Sidebar state for tool output viewing\n @state() sidebarOpen = false;\n @state() sidebarContent: string | null = null;\n @state() sidebarError: string | null = null;\n @state() splitRatio = this.settings.splitRatio;\n\n @state() nodesLoading = false;\n @state() nodes: Array> = [];\n @state() devicesLoading = false;\n @state() devicesError: string | null = null;\n @state() devicesList: DevicePairingList | null = null;\n @state() execApprovalsLoading = false;\n @state() execApprovalsSaving = false;\n @state() execApprovalsDirty = false;\n @state() execApprovalsSnapshot: ExecApprovalsSnapshot | null = null;\n @state() execApprovalsForm: ExecApprovalsFile | null = null;\n @state() execApprovalsSelectedAgent: string | null = null;\n @state() execApprovalsTarget: \"gateway\" | \"node\" = \"gateway\";\n @state() execApprovalsTargetNodeId: string | null = null;\n @state() execApprovalQueue: ExecApprovalRequest[] = [];\n @state() execApprovalBusy = false;\n @state() execApprovalError: string | null = null;\n\n @state() configLoading = false;\n @state() configRaw = \"{\\n}\\n\";\n @state() configRawOriginal = \"\";\n @state() configValid: boolean | null = null;\n @state() configIssues: unknown[] = [];\n @state() configSaving = false;\n @state() configApplying = false;\n @state() updateRunning = false;\n @state() applySessionKey = this.settings.lastActiveSessionKey;\n @state() configSnapshot: ConfigSnapshot | null = null;\n @state() configSchema: unknown | null = null;\n @state() configSchemaVersion: string | null = null;\n @state() configSchemaLoading = false;\n @state() configUiHints: ConfigUiHints = {};\n @state() configForm: Record | null = null;\n @state() configFormOriginal: Record | null = null;\n @state() configFormDirty = false;\n @state() configFormMode: \"form\" | \"raw\" = \"form\";\n @state() configSearchQuery = \"\";\n @state() configActiveSection: string | null = null;\n @state() configActiveSubsection: string | null = null;\n\n @state() channelsLoading = false;\n @state() channelsSnapshot: ChannelsStatusSnapshot | null = null;\n @state() channelsError: string | null = null;\n @state() channelsLastSuccess: number | null = null;\n @state() whatsappLoginMessage: string | null = null;\n @state() whatsappLoginQrDataUrl: string | null = null;\n @state() whatsappLoginConnected: boolean | null = null;\n @state() whatsappBusy = false;\n @state() nostrProfileFormState: NostrProfileFormState | null = null;\n @state() nostrProfileAccountId: string | null = null;\n\n @state() presenceLoading = false;\n @state() presenceEntries: PresenceEntry[] = [];\n @state() presenceError: string | null = null;\n @state() presenceStatus: string | null = null;\n\n @state() agentsLoading = false;\n @state() agentsList: AgentsListResult | null = null;\n @state() agentsError: string | null = null;\n\n @state() sessionsLoading = false;\n @state() sessionsResult: SessionsListResult | null = null;\n @state() sessionsError: string | null = null;\n @state() sessionsFilterActive = \"\";\n @state() sessionsFilterLimit = \"120\";\n @state() sessionsIncludeGlobal = true;\n @state() sessionsIncludeUnknown = false;\n\n @state() cronLoading = false;\n @state() cronJobs: CronJob[] = [];\n @state() cronStatus: CronStatus | null = null;\n @state() cronError: string | null = null;\n @state() cronForm: CronFormState = { ...DEFAULT_CRON_FORM };\n @state() cronRunsJobId: string | null = null;\n @state() cronRuns: CronRunLogEntry[] = [];\n @state() cronBusy = false;\n\n @state() skillsLoading = false;\n @state() skillsReport: SkillStatusReport | null = null;\n @state() skillsError: string | null = null;\n @state() skillsFilter = \"\";\n @state() skillEdits: Record = {};\n @state() skillsBusyKey: string | null = null;\n @state() skillMessages: Record = {};\n\n @state() debugLoading = false;\n @state() debugStatus: StatusSummary | null = null;\n @state() debugHealth: HealthSnapshot | null = null;\n @state() debugModels: unknown[] = [];\n @state() debugHeartbeat: unknown | null = null;\n @state() debugCallMethod = \"\";\n @state() debugCallParams = \"{}\";\n @state() debugCallResult: string | null = null;\n @state() debugCallError: string | null = null;\n\n @state() logsLoading = false;\n @state() logsError: string | null = null;\n @state() logsFile: string | null = null;\n @state() logsEntries: LogEntry[] = [];\n @state() logsFilterText = \"\";\n @state() logsLevelFilters: Record = {\n ...DEFAULT_LOG_LEVEL_FILTERS,\n };\n @state() logsAutoFollow = true;\n @state() logsTruncated = false;\n @state() logsCursor: number | null = null;\n @state() logsLastFetchAt: number | null = null;\n @state() logsLimit = 500;\n @state() logsMaxBytes = 250_000;\n @state() logsAtBottom = true;\n\n client: GatewayBrowserClient | null = null;\n private chatScrollFrame: number | null = null;\n private chatScrollTimeout: number | null = null;\n private chatHasAutoScrolled = false;\n private chatUserNearBottom = true;\n private nodesPollInterval: number | null = null;\n private logsPollInterval: number | null = null;\n private debugPollInterval: number | null = null;\n private logsScrollFrame: number | null = null;\n private toolStreamById = new Map();\n private toolStreamOrder: string[] = [];\n basePath = \"\";\n private popStateHandler = () =>\n onPopStateInternal(\n this as unknown as Parameters[0],\n );\n private themeMedia: MediaQueryList | null = null;\n private themeMediaHandler: ((event: MediaQueryListEvent) => void) | null = null;\n private topbarObserver: ResizeObserver | null = null;\n\n createRenderRoot() {\n return this;\n }\n\n connectedCallback() {\n super.connectedCallback();\n handleConnected(this as unknown as Parameters[0]);\n }\n\n protected firstUpdated() {\n handleFirstUpdated(this as unknown as Parameters[0]);\n }\n\n disconnectedCallback() {\n handleDisconnected(this as unknown as Parameters[0]);\n super.disconnectedCallback();\n }\n\n protected updated(changed: Map) {\n handleUpdated(\n this as unknown as Parameters[0],\n changed,\n );\n }\n\n connect() {\n connectGatewayInternal(\n this as unknown as Parameters[0],\n );\n }\n\n handleChatScroll(event: Event) {\n handleChatScrollInternal(\n this as unknown as Parameters[0],\n event,\n );\n }\n\n handleLogsScroll(event: Event) {\n handleLogsScrollInternal(\n this as unknown as Parameters[0],\n event,\n );\n }\n\n exportLogs(lines: string[], label: string) {\n exportLogsInternal(lines, label);\n }\n\n resetToolStream() {\n resetToolStreamInternal(\n this as unknown as Parameters[0],\n );\n }\n\n resetChatScroll() {\n resetChatScrollInternal(\n this as unknown as Parameters[0],\n );\n }\n\n async loadAssistantIdentity() {\n await loadAssistantIdentityInternal(this);\n }\n\n applySettings(next: UiSettings) {\n applySettingsInternal(\n this as unknown as Parameters[0],\n next,\n );\n }\n\n setTab(next: Tab) {\n setTabInternal(this as unknown as Parameters[0], next);\n }\n\n setTheme(next: ThemeMode, context?: Parameters[2]) {\n setThemeInternal(\n this as unknown as Parameters[0],\n next,\n context,\n );\n }\n\n async loadOverview() {\n await loadOverviewInternal(\n this as unknown as Parameters[0],\n );\n }\n\n async loadCron() {\n await loadCronInternal(\n this as unknown as Parameters[0],\n );\n }\n\n async handleAbortChat() {\n await handleAbortChatInternal(\n this as unknown as Parameters[0],\n );\n }\n\n removeQueuedMessage(id: string) {\n removeQueuedMessageInternal(\n this as unknown as Parameters[0],\n id,\n );\n }\n\n async handleSendChat(\n messageOverride?: string,\n opts?: Parameters[2],\n ) {\n await handleSendChatInternal(\n this as unknown as Parameters[0],\n messageOverride,\n opts,\n );\n }\n\n async handleWhatsAppStart(force: boolean) {\n await handleWhatsAppStartInternal(this, force);\n }\n\n async handleWhatsAppWait() {\n await handleWhatsAppWaitInternal(this);\n }\n\n async handleWhatsAppLogout() {\n await handleWhatsAppLogoutInternal(this);\n }\n\n async handleChannelConfigSave() {\n await handleChannelConfigSaveInternal(this);\n }\n\n async handleChannelConfigReload() {\n await handleChannelConfigReloadInternal(this);\n }\n\n handleNostrProfileEdit(accountId: string, profile: NostrProfile | null) {\n handleNostrProfileEditInternal(this, accountId, profile);\n }\n\n handleNostrProfileCancel() {\n handleNostrProfileCancelInternal(this);\n }\n\n handleNostrProfileFieldChange(field: keyof NostrProfile, value: string) {\n handleNostrProfileFieldChangeInternal(this, field, value);\n }\n\n async handleNostrProfileSave() {\n await handleNostrProfileSaveInternal(this);\n }\n\n async handleNostrProfileImport() {\n await handleNostrProfileImportInternal(this);\n }\n\n handleNostrProfileToggleAdvanced() {\n handleNostrProfileToggleAdvancedInternal(this);\n }\n\n async handleExecApprovalDecision(decision: \"allow-once\" | \"allow-always\" | \"deny\") {\n const active = this.execApprovalQueue[0];\n if (!active || !this.client || this.execApprovalBusy) return;\n this.execApprovalBusy = true;\n this.execApprovalError = null;\n try {\n await this.client.request(\"exec.approval.resolve\", {\n id: active.id,\n decision,\n });\n this.execApprovalQueue = this.execApprovalQueue.filter((entry) => entry.id !== active.id);\n } catch (err) {\n this.execApprovalError = `Exec approval failed: ${String(err)}`;\n } finally {\n this.execApprovalBusy = false;\n }\n }\n\n // Sidebar handlers for tool output viewing\n handleOpenSidebar(content: string) {\n if (this.sidebarCloseTimer != null) {\n window.clearTimeout(this.sidebarCloseTimer);\n this.sidebarCloseTimer = null;\n }\n this.sidebarContent = content;\n this.sidebarError = null;\n this.sidebarOpen = true;\n }\n\n handleCloseSidebar() {\n this.sidebarOpen = false;\n // Clear content after transition\n if (this.sidebarCloseTimer != null) {\n window.clearTimeout(this.sidebarCloseTimer);\n }\n this.sidebarCloseTimer = window.setTimeout(() => {\n if (this.sidebarOpen) return;\n this.sidebarContent = null;\n this.sidebarError = null;\n this.sidebarCloseTimer = null;\n }, 200);\n }\n\n handleSplitRatioChange(ratio: number) {\n const newRatio = Math.max(0.4, Math.min(0.7, ratio));\n this.splitRatio = newRatio;\n this.applySettings({ ...this.settings, splitRatio: newRatio });\n }\n\n render() {\n return renderApp(this);\n }\n}\n"],"names":["t","e","s","o","n$3","r","n","i","S","c","h","a","l","p","d","u","f","b","y$2","y","v","_","m","g","$","x","E","A","C","P","V","N","S$1","I","L","z","H","M","R","k","Z","I$2","Z$1","j","B","D","MAX_ASSISTANT_NAME","MAX_ASSISTANT_AVATAR","DEFAULT_ASSISTANT_NAME","coerceIdentityValue","value","maxLength","trimmed","normalizeAssistantIdentity","input","name","avatar","resolveInjectedAssistantIdentity","KEY","loadSettings","defaults","raw","parsed","saveSettings","next","parseAgentSessionKey","sessionKey","parts","agentId","rest","TAB_GROUPS","TAB_PATHS","PATH_TO_TAB","tab","path","normalizeBasePath","basePath","base","normalizePath","normalized","pathForTab","tabFromPath","pathname","inferBasePathFromPathname","segments","candidate","prefix","iconForTab","titleForTab","subtitleForTab","icons","html","QUICK_TAG_RE","FINAL_TAG_RE","THINKING_TAG_RE","applyTrim","mode","stripReasoningTagsFromText","text","options","cleaned","result","lastIndex","inThinking","match","idx","isClose","formatMs","ms","formatAgo","diff","sec","min","hr","formatDurationMs","formatList","values","clampText","max","truncateText","toNumber","fallback","stripThinkingTags","ENVELOPE_PREFIX","ENVELOPE_CHANNELS","textCache","thinkingCache","looksLikeEnvelopeHeader","header","label","stripEnvelope","extractText","message","role","content","item","joined","extractTextCached","obj","extractThinking","rawText","extractRawText","extracted","extractThinkingCached","formatReasoningMarkdown","lines","line","uuidFromBytes","bytes","hex","weakRandomBytes","now","generateUUID","cryptoLike","loadChatHistory","state","res","err","sendChatMessage","msg","runId","error","abortChatRun","handleChatEvent","payload","current","loadSessions","params","activeMinutes","limit","patchSession","key","patch","deleteSession","TOOL_STREAM_LIMIT","TOOL_STREAM_THROTTLE_MS","TOOL_OUTPUT_CHAR_LIMIT","extractToolOutputText","record","entry","part","formatToolOutput","contentText","truncated","buildToolStreamMessage","trimToolStream","host","overflow","removed","id","syncToolStreamMessages","flushToolStreamSync","scheduleToolStreamSync","force","resetToolStream","COMPACTION_TOAST_DURATION_MS","handleCompactionEvent","data","phase","handleAgentEvent","toolCallId","args","output","scheduleChatScroll","pickScrollTarget","container","overflowY","target","distanceFromBottom","retryDelay","latest","latestDistanceFromBottom","scheduleLogsScroll","handleChatScroll","event","handleLogsScroll","resetChatScroll","exportLogs","blob","url","anchor","stamp","observeTopbar","topbar","update","height","cloneConfigObject","serializeConfigForm","form","setPathValue","nextKey","lastKey","removePathValue","loadConfig","applyConfigSnapshot","loadConfigSchema","applyConfigSchema","snapshot","rawFromSnapshot","saveConfig","baseHash","applyConfig","runUpdate","updateConfigFormValue","removeConfigFormValue","loadCronStatus","loadCronJobs","buildCronSchedule","amount","unit","expr","buildCronPayload","timeoutSeconds","addCronJob","schedule","job","toggleCronJob","enabled","runCronJob","loadCronRuns","removeCronJob","jobId","loadChannels","probe","startWhatsAppLogin","waitWhatsAppLogin","logoutWhatsApp","loadDebug","status","health","models","heartbeat","modelPayload","callDebugMethod","LOG_BUFFER_LIMIT","LEVELS","parseMaybeJsonString","normalizeLevel","lowered","parseLogLine","meta","time","level","contextCandidate","contextObj","subsystem","loadLogs","opts","entries","shouldReset","ed25519_CURVE","Gx","Gy","_a","_d","L2","captureTrace","isBig","isStr","isBytes","abytes","length","title","len","needsLen","ofLen","got","u8n","u8fr","buf","padh","pad","bytesToHex","_ch","ch","hexToBytes","hl","al","array","ai","hi","n1","n2","cr","subtle","concatBytes","arrs","sum","randomBytes","big","assertRange","modN","invert","num","md","q","callHash","fn","hashes","apoint","Point","B256","X","Y","T","zip215","normed","lastByte","bytesToNumLE","y2","isValid","uvRatio","isXOdd","isLastByteOdd","X2","Y2","Z2","Z4","aX2","left","right","XY","ZT","other","X1","Y1","Z1","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","G","F","X3","Y3","T3","Z3","T1","T2","safe","wNAF","scalar","iz","numTo32bLE","pow2","power","pow_2_252_3","b2","b4","b5","b10","b20","b40","b80","b160","b240","b250","RM1","v3","v7","pow","vx2","root1","root2","useRoot1","useRoot2","noRoot","modL_LE","hash","sha512a","sha512s","hash2extK","hashed","head","point","pointBytes","getExtendedPublicKeyAsync","secretKey","getExtendedPublicKey","getPublicKeyAsync","hashFinishA","_sign","rBytes","signAsync","randomSecretKey","seed","utils","W","scalarBits","pwindows","pwindowSize","precompute","points","w","Gpows","ctneg","cnd","comp","pow_2_w","maxNum","mask","shiftBy","wbits","off","offF","offP","isEven","isNeg","STORAGE_KEY","base64UrlEncode","binary","byte","base64UrlDecode","padded","out","fingerprintPublicKey","publicKey","generateIdentity","privateKey","loadOrCreateDeviceIdentity","derivedId","updated","identity","stored","signDevicePayload","privateKeyBase64Url","sig","normalizeRole","normalizeScopes","scopes","scope","readStore","writeStore","store","loadDeviceAuthToken","storeDeviceAuthToken","existing","clearDeviceAuthToken","loadDevices","approveDevicePairing","requestId","rejectDevicePairing","rotateDeviceToken","revokeDeviceToken","loadNodes","resolveExecApprovalsRpc","nodeId","resolveExecApprovalsSaveRpc","loadExecApprovals","rpc","applyExecApprovalsSnapshot","saveExecApprovals","file","updateExecApprovalsFormValue","removeExecApprovalsFormValue","loadPresence","setSkillMessage","getErrorMessage","loadSkills","updateSkillEdit","skillKey","updateSkillEnabled","saveSkillApiKey","apiKey","installSkill","installId","getSystemTheme","resolveTheme","clamp01","hasReducedMotionPreference","cleanupThemeTransition","root","startThemeTransition","nextTheme","applyTheme","context","currentTheme","documentReference","document_","prefersReducedMotion","xPercent","yPercent","rect","transition","startNodesPolling","stopNodesPolling","startLogsPolling","stopLogsPolling","startDebugPolling","stopDebugPolling","applySettings","applyResolvedTheme","setLastActiveSessionKey","applySettingsFromUrl","tokenRaw","passwordRaw","sessionRaw","gatewayUrlRaw","shouldCleanUrl","token","password","session","gatewayUrl","setTab","refreshActiveTab","syncUrlWithTab","setTheme","loadOverview","loadChannelsTab","loadCron","refreshChat","inferBasePath","configured","syncThemeWithSettings","resolved","attachThemeListener","detachThemeListener","syncTabWithLocation","replace","setTabFromRoute","onPopState","targetPath","currentPath","syncUrlWithSessionKey","isChatBusy","isChatStopCommand","handleAbortChat","enqueueChatMessage","sendChatMessageNow","ok","flushChatQueue","removeQueuedMessage","handleSendChat","messageOverride","previousDraft","refreshChatAvatar","flushChatQueueForEvent","resolveAgentIdForSession","buildAvatarMetaUrl","encoded","avatarUrl","i$1","normalizeMessage","hasToolId","contentRaw","contentItems","hasToolContent","hasToolName","timestamp","normalizeRoleForGrouping","lower","isToolResultMessage","setPrototypeOf","isFrozen","getPrototypeOf","getOwnPropertyDescriptor","freeze","seal","create","apply","construct","func","thisArg","_len","_key","Func","_len2","_key2","arrayForEach","unapply","arrayLastIndexOf","arrayPop","arrayPush","arraySplice","stringToLowerCase","stringToString","stringMatch","stringReplace","stringIndexOf","stringTrim","objectHasOwnProperty","regExpTest","typeErrorCreate","unconstruct","_len3","_key3","_len4","_key4","addToSet","set","transformCaseFunc","element","lcElement","cleanArray","index","clone","object","newObject","property","lookupGetter","prop","desc","fallbackValue","html$1","svg$1","svgFilters","svgDisallowed","mathMl$1","mathMlDisallowed","svg","mathMl","xml","MUSTACHE_EXPR","ERB_EXPR","TMPLIT_EXPR","DATA_ATTR","ARIA_ATTR","IS_ALLOWED_URI","IS_SCRIPT_OR_DATA","ATTR_WHITESPACE","DOCTYPE_NAME","CUSTOM_ELEMENT","EXPRESSIONS","NODE_TYPE","getGlobal","_createTrustedTypesPolicy","trustedTypes","purifyHostElement","suffix","ATTR_NAME","policyName","scriptUrl","_createHooksMap","createDOMPurify","window","DOMPurify","document","originalDocument","currentScript","DocumentFragment","HTMLTemplateElement","Node","Element","NodeFilter","NamedNodeMap","HTMLFormElement","DOMParser","ElementPrototype","cloneNode","remove","getNextSibling","getChildNodes","getParentNode","template","trustedTypesPolicy","emptyHTML","implementation","createNodeIterator","createDocumentFragment","getElementsByTagName","importNode","hooks","IS_ALLOWED_URI$1","ALLOWED_TAGS","DEFAULT_ALLOWED_TAGS","ALLOWED_ATTR","DEFAULT_ALLOWED_ATTR","CUSTOM_ELEMENT_HANDLING","FORBID_TAGS","FORBID_ATTR","EXTRA_ELEMENT_HANDLING","ALLOW_ARIA_ATTR","ALLOW_DATA_ATTR","ALLOW_UNKNOWN_PROTOCOLS","ALLOW_SELF_CLOSE_IN_ATTR","SAFE_FOR_TEMPLATES","SAFE_FOR_XML","WHOLE_DOCUMENT","SET_CONFIG","FORCE_BODY","RETURN_DOM","RETURN_DOM_FRAGMENT","RETURN_TRUSTED_TYPE","SANITIZE_DOM","SANITIZE_NAMED_PROPS","SANITIZE_NAMED_PROPS_PREFIX","KEEP_CONTENT","IN_PLACE","USE_PROFILES","FORBID_CONTENTS","DEFAULT_FORBID_CONTENTS","DATA_URI_TAGS","DEFAULT_DATA_URI_TAGS","URI_SAFE_ATTRIBUTES","DEFAULT_URI_SAFE_ATTRIBUTES","MATHML_NAMESPACE","SVG_NAMESPACE","HTML_NAMESPACE","NAMESPACE","IS_EMPTY_INPUT","ALLOWED_NAMESPACES","DEFAULT_ALLOWED_NAMESPACES","MATHML_TEXT_INTEGRATION_POINTS","HTML_INTEGRATION_POINTS","COMMON_SVG_AND_HTML_ELEMENTS","PARSER_MEDIA_TYPE","SUPPORTED_PARSER_MEDIA_TYPES","DEFAULT_PARSER_MEDIA_TYPE","CONFIG","formElement","isRegexOrFunction","testValue","_parseConfig","cfg","ALL_SVG_TAGS","ALL_MATHML_TAGS","_checkValidNamespace","parent","tagName","parentTagName","_forceRemove","node","_removeAttribute","_initDocument","dirty","doc","leadingWhitespace","matches","dirtyPayload","body","_createNodeIterator","_isClobbered","_isNode","_executeHooks","currentNode","hook","_sanitizeElements","_isBasicCustomElement","parentNode","childNodes","childCount","childClone","_isValidAttribute","lcTag","lcName","_sanitizeAttributes","attributes","hookEvent","attr","namespaceURI","attrValue","initValue","_sanitizeShadowDOM","fragment","shadowNode","shadowIterator","importedNode","returnNode","nodeIterator","serializedHTML","tag","entryPoint","hookFunction","purify","me","xe","be","Re","Te","re","se","Oe","Q","we","ye","Pe","Se","ie","$e","U","te","_e","Le","Me","ze","oe","Ae","K","ae","Ce","le","Ie","Ee","Be","ue","qe","ve","pe","De","He","Ze","Ge","Ne","Qe","Fe","je","ce","he","Ue","ne","Ke","We","Xe","ke","J","de","ge","Je","O","ee","fe","marked","allowedTags","allowedAttrs","hooksInstalled","MARKDOWN_CHAR_LIMIT","MARKDOWN_PARSE_LIMIT","MARKDOWN_CACHE_LIMIT","MARKDOWN_CACHE_MAX_CHARS","markdownCache","getCachedMarkdown","cached","setCachedMarkdown","oldest","installHooks","toSanitizedMarkdownHtml","markdown","escapeHtml","sanitized","rendered","COPIED_FOR_MS","ERROR_FOR_MS","COPY_LABEL","COPIED_LABEL","ERROR_LABEL","copyTextToClipboard","setButtonLabel","button","createCopyButton","idleLabel","btn","copied","renderCopyAsMarkdownButton","TOOL_DISPLAY_CONFIG","rawConfig","FALLBACK","TOOL_MAP","normalizeToolName","defaultTitle","normalizeVerb","coerceDisplayValue","firstLine","preview","lookupValueByPath","segment","resolveDetailFromKeys","keys","display","resolveReadDetail","offset","resolveWriteDetail","resolveActionSpec","spec","action","resolveToolDisplay","icon","actionRaw","actionSpec","verb","detail","detailKeys","shortenHomeInString","formatToolDetail","TOOL_INLINE_THRESHOLD","PREVIEW_MAX_LINES","PREVIEW_MAX_CHARS","formatToolOutputForSidebar","getTruncatedPreview","allLines","extractToolCards","normalizeContent","cards","kind","coerceArgs","extractToolText","card","renderToolCardSidebar","onOpenSidebar","hasText","canClick","handleClick","info","isShort","showCollapsed","showInline","isEmpty","nothing","renderReadingIndicatorGroup","assistant","renderAvatar","renderStreamingGroup","startedAt","renderGroupedMessage","renderMessageGroup","group","normalizedRole","assistantName","who","roleClass","assistantAvatar","initial","className","isAvatarUrl","isToolResult","toolCards","hasToolCards","extractedText","extractedThinking","markdownBase","reasoningMarkdown","canCopyMarkdown","bubbleClasses","unsafeHTML","renderMarkdownSidebar","props","ResizableDivider","LitElement","containerWidth","deltaRatio","newRatio","css","__decorateClass","customElement","renderCompactionIndicator","renderChat","canCompose","isBusy","canAbort","reasoningLevel","row","showReasoning","assistantIdentity","composePlaceholder","splitRatio","sidebarOpen","thread","repeat","buildChatItems","CHAT_HISTORY_RENDER_LIMIT","groupMessages","items","currentGroup","history","tools","historyStart","messageKey","messageId","schemaType","schema","defaultValue","pathKey","hintForPath","hints","direct","hintKey","hint","hintSegments","humanize","isSensitivePath","META_KEYS","isAnySchema","jsonValue","renderNode","unsupported","disabled","onPatch","showLabel","type","help","nonNull","extractLiteral","literals","allLiterals","resolvedValue","lit","renderSelect","primitiveTypes","variant","normalizedTypes","hasString","hasNumber","renderTextInput","opt","renderObject","renderArray","displayValue","renderNumberInput","inputType","isSensitive","placeholder","numValue","currentIndex","unset","val","sorted","orderA","orderB","reserved","additional","allowExtra","propKey","renderMapField","itemsSchema","arr","reservedKeys","anySchema","entryValue","valuePath","sectionIcons","SECTION_META","getSectionIcon","matchesSearch","query","schemaMatches","propSchema","unions","renderConfigForm","properties","searchQuery","activeSection","activeSubsection","filteredEntries","subsectionContext","sectionSchema","sectionKey","subsectionKey","description","sectionValue","scopedValue","normalizeEnum","filtered","nullable","enumValues","analyzeConfigSchema","normalizeSchemaNode","pathLabel","union","normalizeUnion","enumNullable","normalizedProps","remaining","unique","sidebarIcons","SECTIONS","ALL_SUBSECTION","resolveSectionMeta","resolveSubsections","uiHints","subKey","order","computeDiff","original","changes","compare","orig","curr","origObj","currObj","allKeys","truncateValue","maxLen","str","renderConfig","validity","analysis","formUnsafe","schemaProps","availableSections","knownKeys","extraSections","allSections","activeSectionSchema","activeSectionMeta","subsections","allowSubnav","isAllSubsection","effectiveSubsection","hasRawChanges","hasChanges","canSaveForm","canSave","canApply","canUpdate","section","change","formatDuration","channelEnabled","channels","channelStatus","running","connected","accountActive","account","getChannelAccountCount","channelAccounts","renderChannelAccountCount","count","resolveSchemaNode","resolveChannelValue","config","channelId","fromChannels","renderChannelConfigForm","configValue","renderChannelConfigSection","renderDiscordCard","discord","accountCountLabel","renderGoogleChatCard","googleChat","renderIMessageCard","imessage","isFormDirty","renderNostrProfileForm","callbacks","accountId","isDirty","renderField","field","inputId","renderPicturePreview","picture","img","createNostrProfileFormState","profile","truncatePubkey","pubkey","renderNostrCard","nostr","nostrAccounts","profileFormState","profileFormCallbacks","onEditProfile","primaryAccount","summaryConfigured","summaryRunning","summaryPublicKey","summaryLastStartAt","summaryLastError","hasMultipleAccounts","showingForm","renderAccountCard","displayName","renderProfileSection","about","nip05","hasAnyProfileData","renderSignalCard","signal","renderSlackCard","slack","renderTelegramCard","telegram","telegramAccounts","botUsername","renderWhatsAppCard","whatsapp","renderChannels","orderedChannels","resolveChannelOrder","channel","renderChannel","showForm","renderGenericChannelCard","resolveChannelLabel","lastError","accounts","renderGenericAccount","resolveChannelMetaMap","RECENT_ACTIVITY_THRESHOLD_MS","hasRecentActivity","deriveRunningStatus","deriveConnectedStatus","runningStatus","connectedStatus","formatPresenceSummary","ip","version","formatPresenceAge","ts","formatNextRun","formatSessionTokens","total","ctx","formatEventPayload","formatCronState","last","formatCronSchedule","formatCronPayload","buildChannelOptions","seen","renderCron","channelOptions","renderScheduleFields","renderJob","renderRun","itemClass","renderDebug","evt","renderInstances","renderEntry","lastInput","roles","scopesLabel","formatTime","date","matchesFilter","needle","renderLogs","levelFiltered","exportLabel","renderNodes","bindingState","resolveBindingsState","approvalsState","resolveExecApprovalsState","renderExecApprovals","renderBindings","renderDevices","list","pending","paired","req","renderPendingDevice","device","renderPairedDevice","age","repair","tokens","renderTokenRow","deviceId","when","EXEC_APPROVALS_DEFAULT_SCOPE","SECURITY_OPTIONS","ASK_OPTIONS","nodes","resolveExecNodes","defaultBinding","agents","resolveAgentBindings","ready","normalizeSecurity","normalizeAsk","resolveExecApprovalsDefaults","resolveConfigAgents","agentsNode","isDefault","resolveExecApprovalsAgents","configAgents","approvalsAgents","merged","agent","aLabel","bLabel","resolveExecApprovalsScope","selected","targetNodes","resolveExecApprovalsNodes","targetNodeId","selectedScope","selectedAgent","allowlist","supportsBinding","renderAgentBinding","targetReady","renderExecApprovalsTarget","renderExecApprovalsTabs","renderExecApprovalsPolicy","renderExecApprovalsAllowlist","hasNodes","nodeValue","first","isDefaults","agentSecurity","agentAsk","agentAskFallback","securityValue","askValue","askFallbackValue","autoOverride","autoEffective","autoIsDefault","option","allowlistPath","renderAllowlistEntry","lastUsed","lastCommand","lastPath","bindingValue","cmd","fallbackAgent","exec","execEntry","binding","caps","commands","renderOverview","uptime","tick","authHint","hasToken","hasPassword","insecureContextHint","THINK_LEVELS","BINARY_THINK_LEVELS","VERBOSE_LEVELS","REASONING_LEVELS","normalizeProviderId","provider","isBinaryThinkingProvider","resolveThinkLevelOptions","resolveThinkLevelDisplay","isBinary","resolveThinkLevelPatchValue","renderSessions","rows","renderRow","onDelete","rawThinking","isBinaryThinking","thinking","thinkLevels","verbose","reasoning","canLink","chatUrl","formatRemaining","totalSeconds","minutes","renderMetaRow","renderExecApprovalPrompt","active","request","remainingMs","queueCount","renderSkills","skills","filter","skill","renderSkill","busy","canInstall","missing","reasons","renderTab","href","renderChatControls","sessionOptions","resolveSessionOptions","disableThinkingToggle","disableFocusToggle","showThinking","focusActive","refreshIcon","focusIcon","sessions","resolvedCurrent","THEME_ORDER","renderThemeToggle","renderMonitorIcon","renderSunIcon","renderMoonIcon","AVATAR_DATA_RE","AVATAR_HTTP_RE","resolveAssistantAvatarUrl","renderApp","presenceCount","sessionsCount","cronNext","chatDisabledReason","isChat","chatFocus","assistantAvatarUrl","chatAvatarUrl","isGroupCollapsed","hasActiveTab","agentIndex","ratio","DEFAULT_LOG_LEVEL_FILTERS","DEFAULT_CRON_FORM","loadAgents","GATEWAY_CLIENT_IDS","GATEWAY_CLIENT_NAMES","GATEWAY_CLIENT_MODES","buildDeviceAuthPayload","CONNECT_FAILED_CLOSE_CODE","GatewayBrowserClient","ev","reason","delay","isSecureContext","deviceIdentity","canFallbackToShared","authToken","storedToken","auth","signedAtMs","nonce","signature","hello","frame","seq","method","resolve","reject","isRecord","parseExecApprovalRequested","command","createdAtMs","expiresAtMs","parseExecApprovalResolved","pruneExecApprovalQueue","queue","addExecApproval","removeExecApproval","loadAssistantIdentity","normalizeSessionKeyForDefaults","mainSessionKey","mainKey","defaultAgentId","applySessionDefaults","resolvedSessionKey","resolvedSettingsSessionKey","resolvedLastActiveSessionKey","nextSessionKey","nextSettings","shouldUpdateSettings","connectGateway","applySnapshot","code","handleGatewayEvent","expected","received","handleGatewayEventUnsafe","handleConnected","handleFirstUpdated","handleDisconnected","handleUpdated","changed","forcedByTab","forcedByLoad","handleWhatsAppStart","handleWhatsAppWait","handleWhatsAppLogout","handleChannelConfigSave","handleChannelConfigReload","parseValidationErrors","details","errors","rawField","resolveNostrAccountId","buildNostrProfileUrl","handleNostrProfileEdit","handleNostrProfileCancel","handleNostrProfileFieldChange","handleNostrProfileToggleAdvanced","handleNostrProfileSave","response","errorMessage","handleNostrProfileImport","nextValues","showAdvanced","injectedAssistantIdentity","resolveOnboardingMode","ClawdbotApp","onPopStateInternal","connectGatewayInternal","handleChatScrollInternal","handleLogsScrollInternal","exportLogsInternal","resetToolStreamInternal","resetChatScrollInternal","loadAssistantIdentityInternal","applySettingsInternal","setTabInternal","setThemeInternal","loadOverviewInternal","loadCronInternal","handleAbortChatInternal","removeQueuedMessageInternal","handleSendChatInternal","handleWhatsAppStartInternal","handleWhatsAppWaitInternal","handleWhatsAppLogoutInternal","handleChannelConfigSaveInternal","handleChannelConfigReloadInternal","handleNostrProfileEditInternal","handleNostrProfileCancelInternal","handleNostrProfileFieldChangeInternal","handleNostrProfileSaveInternal","handleNostrProfileImportInternal","handleNostrProfileToggleAdvancedInternal","decision"],"mappings":"ssBAKA,MAAMA,GAAE,WAAWC,GAAED,GAAE,aAAsBA,GAAE,WAAX,QAAqBA,GAAE,SAAS,eAAe,uBAAuB,SAAS,WAAW,YAAY,cAAc,UAAUE,GAAE,OAAM,EAAGC,GAAE,IAAI,QAAO,IAAAC,GAAC,KAAO,CAAC,YAAY,EAAEH,EAAEE,EAAE,CAAC,GAAG,KAAK,aAAa,GAAGA,IAAID,GAAE,MAAM,MAAM,mEAAmE,EAAE,KAAK,QAAQ,EAAE,KAAK,EAAED,CAAC,CAAC,IAAI,YAAY,CAAC,IAAI,EAAE,KAAK,EAAE,MAAMC,EAAE,KAAK,EAAE,GAAGD,IAAY,IAAT,OAAW,CAAC,MAAMA,EAAWC,IAAT,QAAgBA,EAAE,SAAN,EAAaD,IAAI,EAAEE,GAAE,IAAID,CAAC,GAAY,IAAT,UAAc,KAAK,EAAE,EAAE,IAAI,eAAe,YAAY,KAAK,OAAO,EAAED,GAAGE,GAAE,IAAID,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,UAAU,CAAC,OAAO,KAAK,OAAO,CAAC,EAAC,MAAMG,GAAEL,GAAG,IAAIM,GAAY,OAAON,GAAjB,SAAmBA,EAAEA,EAAE,GAAG,OAAOE,EAAC,EAAEK,GAAE,CAACP,KAAKC,IAAI,CAAC,MAAME,EAAMH,EAAE,SAAN,EAAaA,EAAE,CAAC,EAAEC,EAAE,OAAO,CAACA,EAAEC,EAAEC,IAAIF,GAAGD,GAAG,CAAC,GAAQA,EAAE,eAAP,GAAoB,OAAOA,EAAE,QAAQ,GAAa,OAAOA,GAAjB,SAAmB,OAAOA,EAAE,MAA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AAA,CAAR3zB,EAAA,CAAM,EApII01C,EAoIF,UAAA,cAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EArII01C,EAqIF,UAAA,YAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EAtII01C,EAsIF,UAAA,WAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EAvII01C,EAuIF,UAAA,cAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EAxII01C,EAwIF,UAAA,iBAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EAzII01C,EAyIF,UAAA,mBAAA,CAAA,EAGA/hB,EAAA,CAAR3zB,EAAA,CAAM,EA5II01C,EA4IF,UAAA,iBAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EA7II01C,EA6IF,UAAA,gBAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EA9II01C,EA8IF,UAAA,aAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EA/II01C,EA+IF,UAAA,kBAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EAhJI01C,EAgJF,UAAA,YAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EAjJI01C,EAiJF,UAAA,eAAA,CAAA,EACA/hB,EAAA,CAAR3zB,EAAA,CAAM,EAlJI01C,EAkJF,UAAA,eAAA,CAAA,EAlJEA,EAAN/hB,EAAA,CADNC,GAAc,cAAc,CAAA,EAChB8hB,CAAA","x_google_ignoreList":[0,1,2,3,4,5,6,26,39,40,41,43,44,45]} \ No newline at end of file diff --git a/dist/control-ui/index.html b/dist/control-ui/index.html new file mode 100644 index 000000000..9407eea99 --- /dev/null +++ b/dist/control-ui/index.html @@ -0,0 +1,15 @@ + + + + + + Clawdbot Control + + + + + + + + + diff --git a/docker-compose.yml b/docker-compose.yml index 7970084fc..8b9859f05 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -20,7 +20,7 @@ services: [ "node", "dist/index.js", - "gateway-daemon", + "gateway", "--bind", "${CLAWDBOT_GATEWAY_BIND:-lan}", "--port", diff --git a/docs.acp.md b/docs.acp.md new file mode 100644 index 000000000..ca664134e --- /dev/null +++ b/docs.acp.md @@ -0,0 +1,194 @@ +# Clawdbot ACP Bridge + +This document describes how the Clawdbot ACP (Agent Client Protocol) bridge works, +how it maps ACP sessions to Gateway sessions, and how IDEs should invoke it. + +## Overview + +`clawdbot acp` exposes an ACP agent over stdio and forwards prompts to a running +Clawdbot Gateway over WebSocket. It keeps ACP session ids mapped to Gateway +session keys so IDEs can reconnect to the same agent transcript or reset it on +request. + +Key goals: + +- Minimal ACP surface area (stdio, NDJSON). +- Stable session mapping across reconnects. +- Works with existing Gateway session store (list/resolve/reset). +- Safe defaults (isolated ACP session keys by default). + +## How can I use this + +Use ACP when an IDE or tooling speaks Agent Client Protocol and you want it to +drive a Clawdbot Gateway session. + +Quick steps: + +1. Run a Gateway (local or remote). +2. Configure the Gateway target (`gateway.remote.url` + auth) or pass flags. +3. Point the IDE to run `clawdbot acp` over stdio. + +Example config: + +```bash +clawdbot config set gateway.remote.url wss://gateway-host:18789 +clawdbot config set gateway.remote.token +``` + +Example run: + +```bash +clawdbot acp --url wss://gateway-host:18789 --token +``` + +## Selecting agents + +ACP does not pick agents directly. It routes by the Gateway session key. + +Use agent-scoped session keys to target a specific agent: + +```bash +clawdbot acp --session agent:main:main +clawdbot acp --session agent:design:main +clawdbot acp --session agent:qa:bug-123 +``` + +Each ACP session maps to a single Gateway session key. One agent can have many +sessions; ACP defaults to an isolated `acp:` session unless you override +the key or label. + +## Zed editor setup + +Add a custom ACP agent in `~/.config/zed/settings.json`: + +```json +{ + "agent_servers": { + "Clawdbot ACP": { + "type": "custom", + "command": "clawdbot", + "args": ["acp"], + "env": {} + } + } +} +``` + +To target a specific Gateway or agent: + +```json +{ + "agent_servers": { + "Clawdbot ACP": { + "type": "custom", + "command": "clawdbot", + "args": [ + "acp", + "--url", "wss://gateway-host:18789", + "--token", "", + "--session", "agent:design:main" + ], + "env": {} + } + } +} +``` + +In Zed, open the Agent panel and select “Clawdbot ACP” to start a thread. + +## Execution Model + +- ACP client spawns `clawdbot acp` and speaks ACP messages over stdio. +- The bridge connects to the Gateway using existing auth config (or CLI flags). +- ACP `prompt` translates to Gateway `chat.send`. +- Gateway streaming events are translated back into ACP streaming events. +- ACP `cancel` maps to Gateway `chat.abort` for the active run. + +## Session Mapping + +By default each ACP session is mapped to a dedicated Gateway session key: + +- `acp:` unless overridden. + +You can override or reuse sessions in two ways: + +1) CLI defaults + +```bash +clawdbot acp --session agent:main:main +clawdbot acp --session-label "support inbox" +clawdbot acp --reset-session +``` + +2) ACP metadata per session + +```json +{ + "_meta": { + "sessionKey": "agent:main:main", + "sessionLabel": "support inbox", + "resetSession": true, + "requireExisting": false + } +} +``` + +Rules: + +- `sessionKey`: direct Gateway session key. +- `sessionLabel`: resolve an existing session by label. +- `resetSession`: mint a new transcript for the key before first use. +- `requireExisting`: fail if the key/label does not exist. + +### Session Listing + +ACP `listSessions` maps to Gateway `sessions.list` and returns a filtered +summary suitable for IDE session pickers. `_meta.limit` can cap the number of +sessions returned. + +## Prompt Translation + +ACP prompt inputs are converted into a Gateway `chat.send`: + +- `text` and `resource` blocks become prompt text. +- `resource_link` with image mime types become attachments. +- The working directory can be prefixed into the prompt (default on, can be + disabled with `--no-prefix-cwd`). + +Gateway streaming events are translated into ACP `message` and `tool_call` +updates. Terminal Gateway states map to ACP `done` with stop reasons: + +- `complete` -> `stop` +- `aborted` -> `cancel` +- `error` -> `error` + +## Auth + Gateway Discovery + +`clawdbot acp` resolves the Gateway URL and auth from CLI flags or config: + +- `--url` / `--token` / `--password` take precedence. +- Otherwise use configured `gateway.remote.*` settings. + +## Operational Notes + +- ACP sessions are stored in memory for the bridge process lifetime. +- Gateway session state is persisted by the Gateway itself. +- `--verbose` logs ACP/Gateway bridge events to stderr (never stdout). +- ACP runs can be canceled and the active run id is tracked per session. + +## Compatibility + +- ACP bridge uses `@agentclientprotocol/sdk` (currently 0.13.x). +- Works with ACP clients that implement `initialize`, `newSession`, + `loadSession`, `prompt`, `cancel`, and `listSessions`. + +## Testing + +- Unit: `src/acp/session.test.ts` covers run id lifecycle. +- Full gate: `pnpm lint && pnpm build && pnpm test && pnpm docs:build`. + +## Related Docs + +- CLI usage: `docs/cli/acp.md` +- Session model: `docs/concepts/session.md` +- Session management internals: `docs/reference/session-management-compaction.md` diff --git a/docs/automation/cron-jobs.md b/docs/automation/cron-jobs.md index a7c006c7d..b75fd352e 100644 --- a/docs/automation/cron-jobs.md +++ b/docs/automation/cron-jobs.md @@ -3,9 +3,12 @@ summary: "Cron jobs + wakeups for the Gateway scheduler" read_when: - Scheduling background jobs or wakeups - Wiring automation that should run with or alongside heartbeats + - Deciding between heartbeat and cron for scheduled tasks --- # Cron jobs (Gateway scheduler) +> **Cron vs Heartbeat?** See [Cron vs Heartbeat](/automation/cron-vs-heartbeat) for guidance on when to use each. + Cron is the Gateway’s built-in scheduler. It persists jobs, wakes the agent at the right time, and can optionally deliver output back to a chat. @@ -78,6 +81,7 @@ Isolated jobs run a dedicated agent turn in session `cron:`. Key behaviors: - Prompt is prefixed with `[cron: ]` for traceability. +- Each run starts a **fresh session id** (no prior conversation carry-over). - A summary is posted to the main session (prefix `Cron`, configurable). - `wakeMode: "now"` triggers an immediate heartbeat after posting the summary. - If `payload.deliver: true`, output is delivered to a channel; otherwise it stays internal. @@ -100,7 +104,9 @@ Common `agentTurn` fields: - `bestEffortDeliver`: avoid failing the job if delivery fails. Isolation options (only for `session=isolated`): -- `postToMainPrefix` (CLI: `--post-prefix`): prefix for the summary system event in main. +- `postToMainPrefix` (CLI: `--post-prefix`): prefix for the system event in main. +- `postToMainMode`: `summary` (default) or `full`. +- `postToMainMaxChars`: max chars when `postToMainMode=full` (default 8000). ### Model and thinking overrides Isolated jobs (`agentTurn`) can override the model and thinking level: @@ -118,14 +124,19 @@ Resolution priority: ### Delivery (channel + target) Isolated jobs can deliver output to a channel. The job payload can specify: -- `channel`: `whatsapp` / `telegram` / `discord` / `slack` / `signal` / `imessage` / `last` +- `channel`: `whatsapp` / `telegram` / `discord` / `slack` / `mattermost` (plugin) / `signal` / `imessage` / `last` - `to`: channel-specific recipient target If `channel` or `to` is omitted, cron can fall back to the main session’s “last route” (the last place the agent replied). +Delivery notes: +- If `to` is set, cron auto-delivers the agent’s final output even if `deliver` is omitted. +- Use `deliver: true` when you want last-route delivery without an explicit `to`. +- Use `deliver: false` to keep output internal even if a `to` is present. + Target format reminders: -- Slack/Discord targets should use explicit prefixes (e.g. `channel:`, `user:`) to avoid ambiguity. +- Slack/Discord/Mattermost (plugin) targets should use explicit prefixes (e.g. `channel:`, `user:`) to avoid ambiguity. - Telegram topics should use the `:topic:` form (see below). #### Telegram delivery targets (topics / forum threads) @@ -252,15 +263,15 @@ Run history: clawdbot cron runs --id --limit 50 ``` -Immediate wake without creating a job: +Immediate system event without creating a job: ```bash -clawdbot wake --mode now --text "Next heartbeat: check battery." +clawdbot system event --mode now --text "Next heartbeat: check battery." ``` ## Gateway API surface - `cron.list`, `cron.status`, `cron.add`, `cron.update`, `cron.remove` - `cron.run` (force or due), `cron.runs` -- `wake` (enqueue system event + optional heartbeat) +For immediate system events without a job, use [`clawdbot system event`](/cli/system). ## Troubleshooting diff --git a/docs/automation/cron-vs-heartbeat.md b/docs/automation/cron-vs-heartbeat.md new file mode 100644 index 000000000..333a45d0b --- /dev/null +++ b/docs/automation/cron-vs-heartbeat.md @@ -0,0 +1,274 @@ +--- +summary: "Guidance for choosing between heartbeat and cron jobs for automation" +read_when: + - Deciding how to schedule recurring tasks + - Setting up background monitoring or notifications + - Optimizing token usage for periodic checks +--- +# Cron vs Heartbeat: When to Use Each + +Both heartbeats and cron jobs let you run tasks on a schedule. This guide helps you choose the right mechanism for your use case. + +## Quick Decision Guide + +| Use Case | Recommended | Why | +|----------|-------------|-----| +| Check inbox every 30 min | Heartbeat | Batches with other checks, context-aware | +| Send daily report at 9am sharp | Cron (isolated) | Exact timing needed | +| Monitor calendar for upcoming events | Heartbeat | Natural fit for periodic awareness | +| Run weekly deep analysis | Cron (isolated) | Standalone task, can use different model | +| Remind me in 20 minutes | Cron (main, `--at`) | One-shot with precise timing | +| Background project health check | Heartbeat | Piggybacks on existing cycle | + +## Heartbeat: Periodic Awareness + +Heartbeats run in the **main session** at a regular interval (default: 30 min). They're designed for the agent to check on things and surface anything important. + +### When to use heartbeat + +- **Multiple periodic checks**: Instead of 5 separate cron jobs checking inbox, calendar, weather, notifications, and project status, a single heartbeat can batch all of these. +- **Context-aware decisions**: The agent has full main-session context, so it can make smart decisions about what's urgent vs. what can wait. +- **Conversational continuity**: Heartbeat runs share the same session, so the agent remembers recent conversations and can follow up naturally. +- **Low-overhead monitoring**: One heartbeat replaces many small polling tasks. + +### Heartbeat advantages + +- **Batches multiple checks**: One agent turn can review inbox, calendar, and notifications together. +- **Reduces API calls**: A single heartbeat is cheaper than 5 isolated cron jobs. +- **Context-aware**: The agent knows what you've been working on and can prioritize accordingly. +- **Smart suppression**: If nothing needs attention, the agent replies `HEARTBEAT_OK` and no message is delivered. +- **Natural timing**: Drifts slightly based on queue load, which is fine for most monitoring. + +### Heartbeat example: HEARTBEAT.md checklist + +```md +# Heartbeat checklist + +- Check email for urgent messages +- Review calendar for events in next 2 hours +- If a background task finished, summarize results +- If idle for 8+ hours, send a brief check-in +``` + +The agent reads this on each heartbeat and handles all items in one turn. + +### Configuring heartbeat + +```json5 +{ + agents: { + defaults: { + heartbeat: { + every: "30m", // interval + target: "last", // where to deliver alerts + activeHours: { start: "08:00", end: "22:00" } // optional + } + } + } +} +``` + +See [Heartbeat](/gateway/heartbeat) for full configuration. + +## Cron: Precise Scheduling + +Cron jobs run at **exact times** and can run in isolated sessions without affecting main context. + +### When to use cron + +- **Exact timing required**: "Send this at 9:00 AM every Monday" (not "sometime around 9"). +- **Standalone tasks**: Tasks that don't need conversational context. +- **Different model/thinking**: Heavy analysis that warrants a more powerful model. +- **One-shot reminders**: "Remind me in 20 minutes" with `--at`. +- **Noisy/frequent tasks**: Tasks that would clutter main session history. +- **External triggers**: Tasks that should run independently of whether the agent is otherwise active. + +### Cron advantages + +- **Exact timing**: 5-field cron expressions with timezone support. +- **Session isolation**: Runs in `cron:` without polluting main history. +- **Model overrides**: Use a cheaper or more powerful model per job. +- **Delivery control**: Can deliver directly to a channel; still posts a summary to main by default (configurable). +- **No agent context needed**: Runs even if main session is idle or compacted. +- **One-shot support**: `--at` for precise future timestamps. + +### Cron example: Daily morning briefing + +```bash +clawdbot cron add \ + --name "Morning briefing" \ + --cron "0 7 * * *" \ + --tz "America/New_York" \ + --session isolated \ + --message "Generate today's briefing: weather, calendar, top emails, news summary." \ + --model opus \ + --deliver \ + --channel whatsapp \ + --to "+15551234567" +``` + +This runs at exactly 7:00 AM New York time, uses Opus for quality, and delivers directly to WhatsApp. + +### Cron example: One-shot reminder + +```bash +clawdbot cron add \ + --name "Meeting reminder" \ + --at "20m" \ + --session main \ + --system-event "Reminder: standup meeting starts in 10 minutes." \ + --wake now \ + --delete-after-run +``` + +See [Cron jobs](/automation/cron-jobs) for full CLI reference. + +## Decision Flowchart + +``` +Does the task need to run at an EXACT time? + YES -> Use cron + NO -> Continue... + +Does the task need isolation from main session? + YES -> Use cron (isolated) + NO -> Continue... + +Can this task be batched with other periodic checks? + YES -> Use heartbeat (add to HEARTBEAT.md) + NO -> Use cron + +Is this a one-shot reminder? + YES -> Use cron with --at + NO -> Continue... + +Does it need a different model or thinking level? + YES -> Use cron (isolated) with --model/--thinking + NO -> Use heartbeat +``` + +## Combining Both + +The most efficient setup uses **both**: + +1. **Heartbeat** handles routine monitoring (inbox, calendar, notifications) in one batched turn every 30 minutes. +2. **Cron** handles precise schedules (daily reports, weekly reviews) and one-shot reminders. + +### Example: Efficient automation setup + +**HEARTBEAT.md** (checked every 30 min): +```md +# Heartbeat checklist +- Scan inbox for urgent emails +- Check calendar for events in next 2h +- Review any pending tasks +- Light check-in if quiet for 8+ hours +``` + +**Cron jobs** (precise timing): +```bash +# Daily morning briefing at 7am +clawdbot cron add --name "Morning brief" --cron "0 7 * * *" --session isolated --message "..." --deliver + +# Weekly project review on Mondays at 9am +clawdbot cron add --name "Weekly review" --cron "0 9 * * 1" --session isolated --message "..." --model opus + +# One-shot reminder +clawdbot cron add --name "Call back" --at "2h" --session main --system-event "Call back the client" --wake now +``` + + +## Lobster: Deterministic workflows with approvals + +Lobster is the workflow runtime for **multi-step tool pipelines** that need deterministic execution and explicit approvals. +Use it when the task is more than a single agent turn, and you want a resumable workflow with human checkpoints. + +### When Lobster fits + +- **Multi-step automation**: You need a fixed pipeline of tool calls, not a one-off prompt. +- **Approval gates**: Side effects should pause until you approve, then resume. +- **Resumable runs**: Continue a paused workflow without re-running earlier steps. + +### How it pairs with heartbeat and cron + +- **Heartbeat/cron** decide *when* a run happens. +- **Lobster** defines *what steps* happen once the run starts. + +For scheduled workflows, use cron or heartbeat to trigger an agent turn that calls Lobster. +For ad-hoc workflows, call Lobster directly. + +### Operational notes (from the code) + +- Lobster runs as a **local subprocess** (`lobster` CLI) in tool mode and returns a **JSON envelope**. +- If the tool returns `needs_approval`, you resume with a `resumeToken` and `approve` flag. +- The tool is an **optional plugin**; you must allowlist `lobster` in `tools.allow`. +- If you pass `lobsterPath`, it must be an **absolute path**. + +See [Lobster](/tools/lobster) for full usage and examples. + +## Main Session vs Isolated Session + +Both heartbeat and cron can interact with the main session, but differently: + +| | Heartbeat | Cron (main) | Cron (isolated) | +|---|---|---|---| +| Session | Main | Main (via system event) | `cron:` | +| History | Shared | Shared | Fresh each run | +| Context | Full | Full | None (starts clean) | +| Model | Main session model | Main session model | Can override | +| Output | Delivered if not `HEARTBEAT_OK` | Heartbeat prompt + event | Summary posted to main | + +### When to use main session cron + +Use `--session main` with `--system-event` when you want: +- The reminder/event to appear in main session context +- The agent to handle it during the next heartbeat with full context +- No separate isolated run + +```bash +clawdbot cron add \ + --name "Check project" \ + --every "4h" \ + --session main \ + --system-event "Time for a project health check" \ + --wake now +``` + +### When to use isolated cron + +Use `--session isolated` when you want: +- A clean slate without prior context +- Different model or thinking settings +- Output delivered directly to a channel (summary still posts to main by default) +- History that doesn't clutter main session + +```bash +clawdbot cron add \ + --name "Deep analysis" \ + --cron "0 6 * * 0" \ + --session isolated \ + --message "Weekly codebase analysis..." \ + --model opus \ + --thinking high \ + --deliver +``` + +## Cost Considerations + +| Mechanism | Cost Profile | +|-----------|--------------| +| Heartbeat | One turn every N minutes; scales with HEARTBEAT.md size | +| Cron (main) | Adds event to next heartbeat (no isolated turn) | +| Cron (isolated) | Full agent turn per job; can use cheaper model | + +**Tips**: +- Keep `HEARTBEAT.md` small to minimize token overhead. +- Batch similar checks into heartbeat instead of multiple cron jobs. +- Use `target: "none"` on heartbeat if you only want internal processing. +- Use isolated cron with a cheaper model for routine tasks. + +## Related + +- [Heartbeat](/gateway/heartbeat) - full heartbeat configuration +- [Cron jobs](/automation/cron-jobs) - full cron CLI and API reference +- [System](/cli/system) - system events + heartbeat controls diff --git a/docs/automation/gmail-pubsub.md b/docs/automation/gmail-pubsub.md index 3c74672d4..94feba3d7 100644 --- a/docs/automation/gmail-pubsub.md +++ b/docs/automation/gmail-pubsub.md @@ -92,13 +92,13 @@ under `hooks.transformsDir` (see [Webhooks](/automation/webhook)). Use the Clawdbot helper to wire everything together (installs deps on macOS via brew): ```bash -clawdbot hooks gmail setup \ +clawdbot webhooks gmail setup \ --account clawdbot@gmail.com ``` Defaults: - Uses Tailscale Funnel for the public push endpoint. -- Writes `hooks.gmail` config for `clawdbot hooks gmail run`. +- Writes `hooks.gmail` config for `clawdbot webhooks gmail run`. - Enables the Gmail hook preset (`hooks.presets: ["gmail"]`). Path note: when `tailscale.mode` is enabled, Clawdbot automatically sets @@ -124,7 +124,7 @@ Gateway auto-start (recommended): Manual daemon (starts `gog gmail watch serve` + auto-renew): ```bash -clawdbot hooks gmail run +clawdbot webhooks gmail run ``` ## One-time setup @@ -191,7 +191,7 @@ Notes: - `--hook-url` points to Clawdbot `/hooks/gmail` (mapped; isolated run + summary to main). - `--include-body` and `--max-bytes` control the body snippet sent to Clawdbot. -Recommended: `clawdbot hooks gmail run` wraps the same flow and auto-renews the watch. +Recommended: `clawdbot webhooks gmail run` wraps the same flow and auto-renews the watch. ## Expose the handler (advanced, unsupported) diff --git a/docs/automation/poll.md b/docs/automation/poll.md index d22de2eec..628bdff85 100644 --- a/docs/automation/poll.md +++ b/docs/automation/poll.md @@ -16,19 +16,19 @@ read_when: ```bash # WhatsApp -clawdbot message poll --to +15555550123 \ +clawdbot message poll --target +15555550123 \ --poll-question "Lunch today?" --poll-option "Yes" --poll-option "No" --poll-option "Maybe" -clawdbot message poll --to 123456789@g.us \ +clawdbot message poll --target 123456789@g.us \ --poll-question "Meeting time?" --poll-option "10am" --poll-option "2pm" --poll-option "4pm" --poll-multi # Discord -clawdbot message poll --channel discord --to channel:123456789 \ +clawdbot message poll --channel discord --target channel:123456789 \ --poll-question "Snack?" --poll-option "Pizza" --poll-option "Sushi" -clawdbot message poll --channel discord --to channel:123456789 \ +clawdbot message poll --channel discord --target channel:123456789 \ --poll-question "Plan?" --poll-option "A" --poll-option "B" --poll-duration-hours 48 # MS Teams -clawdbot message poll --channel msteams --to conversation:19:abc@thread.tacv2 \ +clawdbot message poll --channel msteams --target conversation:19:abc@thread.tacv2 \ --poll-question "Lunch?" --poll-option "Pizza" --poll-option "Sushi" ``` diff --git a/docs/automation/webhook.md b/docs/automation/webhook.md index 00734f0d0..0828483d2 100644 --- a/docs/automation/webhook.md +++ b/docs/automation/webhook.md @@ -71,8 +71,8 @@ Payload: - `sessionKey` optional (string): The key used to identify the agent's session. Defaults to a random `hook:`. Using a consistent key allows for a multi-turn conversation within the hook context. - `wakeMode` optional (`now` | `next-heartbeat`): Whether to trigger an immediate heartbeat (default `now`) or wait for the next periodic check. - `deliver` optional (boolean): If `true`, the agent's response will be sent to the messaging channel. Defaults to `true`. Responses that are only heartbeat acknowledgments are automatically skipped. -- `channel` optional (string): The messaging channel for delivery. One of: `last`, `whatsapp`, `telegram`, `discord`, `slack`, `signal`, `imessage`, `msteams`. Defaults to `last`. -- `to` optional (string): The recipient identifier for the channel (e.g., phone number for WhatsApp/Signal, chat ID for Telegram, channel ID for Discord/Slack, conversation ID for MS Teams). Defaults to the last recipient in the main session. +- `channel` optional (string): The messaging channel for delivery. One of: `last`, `whatsapp`, `telegram`, `discord`, `slack`, `mattermost` (plugin), `signal`, `imessage`, `msteams`. Defaults to `last`. +- `to` optional (string): The recipient identifier for the channel (e.g., phone number for WhatsApp/Signal, chat ID for Telegram, channel ID for Discord/Slack/Mattermost (plugin), conversation ID for MS Teams). Defaults to the last recipient in the main session. - `model` optional (string): Model override (e.g., `anthropic/claude-3-5-sonnet` or an alias). Must be in the allowed model list if restricted. - `thinking` optional (string): Thinking level override (e.g., `low`, `medium`, `high`). - `timeoutSeconds` optional (number): Maximum duration for the agent run in seconds. @@ -96,7 +96,7 @@ Mapping options (summary): - TS transforms require a TS loader (e.g. `bun` or `tsx`) or precompiled `.js` at runtime. - Set `deliver: true` + `channel`/`to` on mappings to route replies to a chat surface (`channel` defaults to `last` and falls back to WhatsApp). -- `clawdbot hooks gmail setup` writes `hooks.gmail` config for `clawdbot hooks gmail run`. +- `clawdbot webhooks gmail setup` writes `hooks.gmail` config for `clawdbot webhooks gmail run`. See [Gmail Pub/Sub](/automation/gmail-pubsub) for the full Gmail watch flow. ## Responses diff --git a/docs/bedrock.md b/docs/bedrock.md index abdd3e1ab..690508e4b 100644 --- a/docs/bedrock.md +++ b/docs/bedrock.md @@ -17,6 +17,37 @@ not an API key. - Auth: AWS credentials (env vars, shared config, or instance role) - Region: `AWS_REGION` or `AWS_DEFAULT_REGION` (default: `us-east-1`) +## Automatic model discovery + +If AWS credentials are detected, Clawdbot can automatically discover Bedrock +models that support **streaming** and **text output**. Discovery uses +`bedrock:ListFoundationModels` and is cached (default: 1 hour). + +Config options live under `models.bedrockDiscovery`: + +```json5 +{ + models: { + bedrockDiscovery: { + enabled: true, + region: "us-east-1", + providerFilter: ["anthropic", "amazon"], + refreshInterval: 3600, + defaultContextWindow: 32000, + defaultMaxTokens: 4096 + } + } +} +``` + +Notes: +- `enabled` defaults to `true` when AWS credentials are present. +- `region` defaults to `AWS_REGION` or `AWS_DEFAULT_REGION`, then `us-east-1`. +- `providerFilter` matches Bedrock provider names (for example `anthropic`). +- `refreshInterval` is seconds; set to `0` to disable caching. +- `defaultContextWindow` (default: `32000`) and `defaultMaxTokens` (default: `4096`) + are used for discovered models (override if you know your model limits). + ## Setup (manual) 1) Ensure AWS credentials are available on the **gateway host**: @@ -28,9 +59,11 @@ export AWS_REGION="us-east-1" # Optional: export AWS_SESSION_TOKEN="..." export AWS_PROFILE="your-profile" +# Optional (Bedrock API key/bearer token): +export AWS_BEARER_TOKEN_BEDROCK="..." ``` -2) Add a Bedrock provider and model to your config: +2) Add a Bedrock provider and model to your config (no `apiKey` required): ```json5 { @@ -39,12 +72,13 @@ export AWS_PROFILE="your-profile" "amazon-bedrock": { baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", api: "bedrock-converse-stream", + auth: "aws-sdk", models: [ { - id: "anthropic.claude-3-7-sonnet-20250219-v1:0", - name: "Claude 3.7 Sonnet (Bedrock)", + id: "anthropic.claude-opus-4-5-20251101-v1:0", + name: "Claude Opus 4.5 (Bedrock)", reasoning: true, - input: ["text"], + input: ["text", "image"], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 200000, maxTokens: 8192 @@ -55,16 +89,83 @@ export AWS_PROFILE="your-profile" }, agents: { defaults: { - model: { primary: "amazon-bedrock/anthropic.claude-3-7-sonnet-20250219-v1:0" } + model: { primary: "amazon-bedrock/anthropic.claude-opus-4-5-20251101-v1:0" } } } } ``` +## EC2 Instance Roles + +When running Clawdbot on an EC2 instance with an IAM role attached, the AWS SDK +will automatically use the instance metadata service (IMDS) for authentication. +However, Clawdbot's credential detection currently only checks for environment +variables, not IMDS credentials. + +**Workaround:** Set `AWS_PROFILE=default` to signal that AWS credentials are +available. The actual authentication still uses the instance role via IMDS. + +```bash +# Add to ~/.bashrc or your shell profile +export AWS_PROFILE=default +export AWS_REGION=us-east-1 +``` + +**Required IAM permissions** for the EC2 instance role: +- `bedrock:InvokeModel` +- `bedrock:InvokeModelWithResponseStream` +- `bedrock:ListFoundationModels` (for automatic discovery) + +Or attach the managed policy `AmazonBedrockFullAccess`. + +**Quick setup:** + +```bash +# 1. Create IAM role and instance profile +aws iam create-role --role-name EC2-Bedrock-Access \ + --assume-role-policy-document '{ + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Principal": {"Service": "ec2.amazonaws.com"}, + "Action": "sts:AssumeRole" + }] + }' + +aws iam attach-role-policy --role-name EC2-Bedrock-Access \ + --policy-arn arn:aws:iam::aws:policy/AmazonBedrockFullAccess + +aws iam create-instance-profile --instance-profile-name EC2-Bedrock-Access +aws iam add-role-to-instance-profile \ + --instance-profile-name EC2-Bedrock-Access \ + --role-name EC2-Bedrock-Access + +# 2. Attach to your EC2 instance +aws ec2 associate-iam-instance-profile \ + --instance-id i-xxxxx \ + --iam-instance-profile Name=EC2-Bedrock-Access + +# 3. On the EC2 instance, enable discovery +clawdbot config set models.bedrockDiscovery.enabled true +clawdbot config set models.bedrockDiscovery.region us-east-1 + +# 4. Set the workaround env vars +echo 'export AWS_PROFILE=default' >> ~/.bashrc +echo 'export AWS_REGION=us-east-1' >> ~/.bashrc +source ~/.bashrc + +# 5. Verify models are discovered +clawdbot models list +``` + ## Notes - Bedrock requires **model access** enabled in your AWS account/region. +- Automatic discovery needs the `bedrock:ListFoundationModels` permission. - If you use profiles, set `AWS_PROFILE` on the gateway host. +- Clawdbot surfaces the credential source in this order: `AWS_BEARER_TOKEN_BEDROCK`, + then `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY`, then `AWS_PROFILE`, then the + default AWS SDK chain. - Reasoning support depends on the model; check the Bedrock model card for current capabilities. - If you prefer a managed key flow, you can also place an OpenAI‑compatible diff --git a/docs/brave-search.md b/docs/brave-search.md new file mode 100644 index 000000000..a29143fb4 --- /dev/null +++ b/docs/brave-search.md @@ -0,0 +1,40 @@ +--- +summary: "Brave Search API setup for web_search" +read_when: + - You want to use Brave Search for web_search + - You need a BRAVE_API_KEY or plan details +--- + +# Brave Search API + +Clawdbot uses Brave Search as the default provider for `web_search`. + +## Get an API key + +1) Create a Brave Search API account at https://brave.com/search/api/ +2) In the dashboard, choose the **Data for Search** plan and generate an API key. +3) Store the key in config (recommended) or set `BRAVE_API_KEY` in the Gateway environment. + +## Config example + +```json5 +{ + tools: { + web: { + search: { + provider: "brave", + apiKey: "BRAVE_API_KEY_HERE", + maxResults: 5, + timeoutSeconds: 30 + } + } + } +} +``` + +## Notes + +- The Data for AI plan is **not** compatible with `web_search`. +- Brave provides a free tier plus paid plans; check the Brave API portal for current limits. + +See [Web tools](/tools/web) for the full web_search configuration. diff --git a/docs/channels/bluebubbles.md b/docs/channels/bluebubbles.md new file mode 100644 index 000000000..a1f4a0892 --- /dev/null +++ b/docs/channels/bluebubbles.md @@ -0,0 +1,232 @@ +--- +summary: "iMessage via BlueBubbles macOS server (REST send/receive, typing, reactions, pairing, advanced actions)." +read_when: + - Setting up BlueBubbles channel + - Troubleshooting webhook pairing + - Configuring iMessage on macOS +--- +# BlueBubbles (macOS REST) + +Status: bundled plugin that talks to the BlueBubbles macOS server over HTTP. **Recommended for iMessage integration** due to its richer API and easier setup compared to the legacy imsg channel. + +## Overview +- Runs on macOS via the BlueBubbles helper app ([bluebubbles.app](https://bluebubbles.app)). +- Recommended/tested: macOS Sequoia (15). macOS Tahoe (26) works; edit is currently broken on Tahoe, and group icon updates may report success but not sync. +- Clawdbot talks to it through its REST API (`GET /api/v1/ping`, `POST /message/text`, `POST /chat/:id/*`). +- Incoming messages arrive via webhooks; outgoing replies, typing indicators, read receipts, and tapbacks are REST calls. +- Attachments and stickers are ingested as inbound media (and surfaced to the agent when possible). +- Pairing/allowlist works the same way as other channels (`/start/pairing` etc) with `channels.bluebubbles.allowFrom` + pairing codes. +- Reactions are surfaced as system events just like Slack/Telegram so agents can "mention" them before replying. +- Advanced features: edit, unsend, reply threading, message effects, group management. + +## Quick start +1. Install the BlueBubbles server on your Mac (follow the instructions at [bluebubbles.app/install](https://bluebubbles.app/install)). +2. In the BlueBubbles config, enable the web API and set a password. +3. Run `clawdbot onboard` and select BlueBubbles, or configure manually: + ```json5 + { + channels: { + bluebubbles: { + enabled: true, + serverUrl: "http://192.168.1.100:1234", + password: "example-password", + webhookPath: "/bluebubbles-webhook" + } + } + } + ``` +4. Point BlueBubbles webhooks to your gateway (example: `https://your-gateway-host:3000/bluebubbles-webhook?password=`). +5. Start the gateway; it will register the webhook handler and start pairing. + +## Onboarding +BlueBubbles is available in the interactive setup wizard: +``` +clawdbot onboard +``` + +The wizard prompts for: +- **Server URL** (required): BlueBubbles server address (e.g., `http://192.168.1.100:1234`) +- **Password** (required): API password from BlueBubbles Server settings +- **Webhook path** (optional): Defaults to `/bluebubbles-webhook` +- **DM policy**: pairing, allowlist, open, or disabled +- **Allow list**: Phone numbers, emails, or chat targets + +You can also add BlueBubbles via CLI: +``` +clawdbot channels add bluebubbles --http-url http://192.168.1.100:1234 --password +``` + +## Access control (DMs + groups) +DMs: +- Default: `channels.bluebubbles.dmPolicy = "pairing"`. +- Unknown senders receive a pairing code; messages are ignored until approved (codes expire after 1 hour). +- Approve via: + - `clawdbot pairing list bluebubbles` + - `clawdbot pairing approve bluebubbles ` +- Pairing is the default token exchange. Details: [Pairing](/start/pairing) + +Groups: +- `channels.bluebubbles.groupPolicy = open | allowlist | disabled` (default: `allowlist`). +- `channels.bluebubbles.groupAllowFrom` controls who can trigger in groups when `allowlist` is set. + +### Mention gating (groups) +BlueBubbles supports mention gating for group chats, matching iMessage/WhatsApp behavior: +- Uses `agents.list[].groupChat.mentionPatterns` (or `messages.groupChat.mentionPatterns`) to detect mentions. +- When `requireMention` is enabled for a group, the agent only responds when mentioned. +- Control commands from authorized senders bypass mention gating. + +Per-group configuration: +```json5 +{ + channels: { + bluebubbles: { + groupPolicy: "allowlist", + groupAllowFrom: ["+15555550123"], + groups: { + "*": { requireMention: true }, // default for all groups + "iMessage;-;chat123": { requireMention: false } // override for specific group + } + } + } +} +``` + +### Command gating +- Control commands (e.g., `/config`, `/model`) require authorization. +- Uses `allowFrom` and `groupAllowFrom` to determine command authorization. +- Authorized senders can run control commands even without mentioning in groups. + +## Typing + read receipts +- **Typing indicators**: Sent automatically before and during response generation. +- **Read receipts**: Controlled by `channels.bluebubbles.sendReadReceipts` (default: `true`). +- **Typing indicators**: Clawdbot sends typing start events; BlueBubbles clears typing automatically on send or timeout (manual stop via DELETE is unreliable). + +```json5 +{ + channels: { + bluebubbles: { + sendReadReceipts: false // disable read receipts + } + } +} +``` + +## Advanced actions +BlueBubbles supports advanced message actions when enabled in config: + +```json5 +{ + channels: { + bluebubbles: { + actions: { + reactions: true, // tapbacks (default: true) + edit: true, // edit sent messages (macOS 13+, broken on macOS 26 Tahoe) + unsend: true, // unsend messages (macOS 13+) + reply: true, // reply threading by message GUID + sendWithEffect: true, // message effects (slam, loud, etc.) + renameGroup: true, // rename group chats + setGroupIcon: true, // set group chat icon/photo (flaky on macOS 26 Tahoe) + addParticipant: true, // add participants to groups + removeParticipant: true, // remove participants from groups + leaveGroup: true, // leave group chats + sendAttachment: true // send attachments/media + } + } + } +} +``` + +Available actions: +- **react**: Add/remove tapback reactions (`messageId`, `emoji`, `remove`) +- **edit**: Edit a sent message (`messageId`, `text`) +- **unsend**: Unsend a message (`messageId`) +- **reply**: Reply to a specific message (`messageId`, `text`, `to`) +- **sendWithEffect**: Send with iMessage effect (`text`, `to`, `effectId`) +- **renameGroup**: Rename a group chat (`chatGuid`, `displayName`) +- **setGroupIcon**: Set a group chat's icon/photo (`chatGuid`, `media`) — flaky on macOS 26 Tahoe (API may return success but the icon does not sync). +- **addParticipant**: Add someone to a group (`chatGuid`, `address`) +- **removeParticipant**: Remove someone from a group (`chatGuid`, `address`) +- **leaveGroup**: Leave a group chat (`chatGuid`) +- **sendAttachment**: Send media/files (`to`, `buffer`, `filename`, `asVoice`) + - Voice memos: set `asVoice: true` with **MP3** or **CAF** audio to send as an iMessage voice message. BlueBubbles converts MP3 → CAF when sending voice memos. + +### Message IDs (short vs full) +Clawdbot may surface *short* message IDs (e.g., `1`, `2`) to save tokens. +- `MessageSid` / `ReplyToId` can be short IDs. +- `MessageSidFull` / `ReplyToIdFull` contain the provider full IDs. +- Short IDs are in-memory; they can expire on restart or cache eviction. +- Actions accept short or full `messageId`, but short IDs will error if no longer available. + +Use full IDs for durable automations and storage: +- Templates: `{{MessageSidFull}}`, `{{ReplyToIdFull}}` +- Context: `MessageSidFull` / `ReplyToIdFull` in inbound payloads + +See [Configuration](/gateway/configuration) for template variables. + +## Block streaming +Control whether responses are sent as a single message or streamed in blocks: +```json5 +{ + channels: { + bluebubbles: { + blockStreaming: true // enable block streaming (default behavior) + } + } +} +``` + +## Media + limits +- Inbound attachments are downloaded and stored in the media cache. +- Media cap via `channels.bluebubbles.mediaMaxMb` (default: 8 MB). +- Outbound text is chunked to `channels.bluebubbles.textChunkLimit` (default: 4000 chars). + +## Configuration reference +Full configuration: [Configuration](/gateway/configuration) + +Provider options: +- `channels.bluebubbles.enabled`: Enable/disable the channel. +- `channels.bluebubbles.serverUrl`: BlueBubbles REST API base URL. +- `channels.bluebubbles.password`: API password. +- `channels.bluebubbles.webhookPath`: Webhook endpoint path (default: `/bluebubbles-webhook`). +- `channels.bluebubbles.dmPolicy`: `pairing | allowlist | open | disabled` (default: `pairing`). +- `channels.bluebubbles.allowFrom`: DM allowlist (handles, emails, E.164 numbers, `chat_id:*`, `chat_guid:*`). +- `channels.bluebubbles.groupPolicy`: `open | allowlist | disabled` (default: `allowlist`). +- `channels.bluebubbles.groupAllowFrom`: Group sender allowlist. +- `channels.bluebubbles.groups`: Per-group config (`requireMention`, etc.). +- `channels.bluebubbles.sendReadReceipts`: Send read receipts (default: `true`). +- `channels.bluebubbles.blockStreaming`: Enable block streaming (default: `true`). +- `channels.bluebubbles.textChunkLimit`: Outbound chunk size in chars (default: 4000). +- `channels.bluebubbles.chunkMode`: `length` (default) splits only when exceeding `textChunkLimit`; `newline` splits on blank lines (paragraph boundaries) before length chunking. +- `channels.bluebubbles.mediaMaxMb`: Inbound media cap in MB (default: 8). +- `channels.bluebubbles.historyLimit`: Max group messages for context (0 disables). +- `channels.bluebubbles.dmHistoryLimit`: DM history limit. +- `channels.bluebubbles.actions`: Enable/disable specific actions. +- `channels.bluebubbles.accounts`: Multi-account configuration. + +Related global options: +- `agents.list[].groupChat.mentionPatterns` (or `messages.groupChat.mentionPatterns`). +- `messages.responsePrefix`. + +## Addressing / delivery targets +Prefer `chat_guid` for stable routing: +- `chat_guid:iMessage;-;+15555550123` (preferred for groups) +- `chat_id:123` +- `chat_identifier:...` +- Direct handles: `+15555550123`, `user@example.com` + - If a direct handle does not have an existing DM chat, Clawdbot will create one via `POST /api/v1/chat/new`. This requires the BlueBubbles Private API to be enabled. + +## Security +- Webhook requests are authenticated by comparing `guid`/`password` query params or headers against `channels.bluebubbles.password`. Requests from `localhost` are also accepted. +- Keep the API password and webhook endpoint secret (treat them like credentials). +- Enable HTTPS + firewall rules on the BlueBubbles server if exposing it outside your LAN. + +## Troubleshooting +- If typing/read events stop working, check the BlueBubbles webhook logs and verify the gateway path matches `channels.bluebubbles.webhookPath`. +- Pairing codes expire after one hour; use `clawdbot pairing list bluebubbles` and `clawdbot pairing approve bluebubbles `. +- Reactions require the BlueBubbles private API (`POST /api/v1/message/react`); ensure the server version exposes it. +- Edit/unsend require macOS 13+ and a compatible BlueBubbles server version. On macOS 26 (Tahoe), edit is currently broken due to private API changes. +- Group icon updates can be flaky on macOS 26 (Tahoe): the API may return success but the new icon does not sync. +- Clawdbot auto-hides known-broken actions based on the BlueBubbles server's macOS version. If edit still appears on macOS 26 (Tahoe), disable it manually with `channels.bluebubbles.actions.edit=false`. +- For status/health info: `clawdbot status --all` or `clawdbot status --deep`. + +For general channel workflow reference, see [Channels](/channels) and the [Plugins](/plugins) guide. diff --git a/docs/channels/discord.md b/docs/channels/discord.md index 3ded9f374..12dd28084 100644 --- a/docs/channels/discord.md +++ b/docs/channels/discord.md @@ -13,6 +13,7 @@ Status: ready for DM and guild text channels via the official Discord bot gatewa 2) Set the token for Clawdbot: - Env: `DISCORD_BOT_TOKEN=...` - Or config: `channels.discord.token: "..."`. + - If both are set, config takes precedence (env fallback is default-account only). 3) Invite the bot to your server with message permissions. 4) Start the gateway. 5) DM access is pairing by default; approve the pairing code on first contact. @@ -38,8 +39,8 @@ Minimal config: ## How it works 1. Create a Discord application → Bot, enable the intents you need (DMs + guild messages + message content), and grab the bot token. 2. Invite the bot to your server with the permissions required to read/send messages where you want to use it. -3. Configure Clawdbot with `DISCORD_BOT_TOKEN` (or `channels.discord.token` in `~/.clawdbot/clawdbot.json`). -4. Run the gateway; it auto-starts the Discord channel when a token is available (env or config) and `channels.discord.enabled` is not `false`. +3. Configure Clawdbot with `channels.discord.token` (or `DISCORD_BOT_TOKEN` as a fallback). +4. Run the gateway; it auto-starts the Discord channel when a token is available (config first, env fallback) and `channels.discord.enabled` is not `false`. - If you prefer env vars, set `DISCORD_BOT_TOKEN` (a config block is optional). 5. Direct chats: use `user:` (or a `<@id>` mention) when delivering; all turns land in the shared `main` session. Bare numeric IDs are ambiguous and rejected. 6. Guild channels: use `channel:` for delivery. Mentions are required by default and can be set per guild or per channel. @@ -57,7 +58,7 @@ Minimal config: - The `discord` tool is only exposed when the current channel is Discord. 13. Native commands use isolated session keys (`agent::discord:slash:`) rather than the shared `main` session. -Note: Discord does not provide a simple username → id lookup without extra guild context, so prefer ids or `<@id>` mentions for DM delivery targets. +Note: Name → id resolution uses guild member search and requires Server Members Intent; if the bot can’t search members, use ids or `<@id>` mentions. Note: Slugs are lowercase with spaces replaced by `-`. Channel names are slugged without the leading `#`. Note: Guild context `[from:]` lines include `author.tag` + `id` to make ping-ready replies easy. @@ -174,6 +175,8 @@ Notes: - `agents.list[].groupChat.mentionPatterns` (or `messages.groupChat.mentionPatterns`) also count as mentions for guild messages. - Multi-agent override: set per-agent patterns on `agents.list[].groupChat.mentionPatterns`. - If `channels` is present, any channel not listed is denied by default. +- Use a `"*"` channel entry to apply defaults across all channels; explicit channel entries override the wildcard. +- Threads inherit parent channel config (allowlist, `requireMention`, skills, prompts, etc.) unless you add the thread channel id explicitly. - Bot-authored messages are ignored by default; set `channels.discord.allowBots=true` to allow them (own messages remain filtered). - Warning: If you allow replies to other bots (`channels.discord.allowBots=true`), prevent bot-to-bot reply loops with `requireMention`, `channels.discord.guilds.*.channels..users` allowlists, and/or clear guardrails in `AGENTS.md` and `SOUL.md`. @@ -191,14 +194,18 @@ Notes: - Your config requires mentions and you didn’t mention it, or - Your guild/channel allowlist denies the channel/user. - **`requireMention: false` but still no replies**: - - `channels.discord.groupPolicy` defaults to **allowlist**; set it to `"open"` or add a guild entry under `channels.discord.guilds` (optionally list channels under `channels.discord.guilds..channels` to restrict). - - `requireMention` must live under `channels.discord.guilds` (or a specific channel). `channels.discord.requireMention` at the top level is ignored. +- `channels.discord.groupPolicy` defaults to **allowlist**; set it to `"open"` or add a guild entry under `channels.discord.guilds` (optionally list channels under `channels.discord.guilds..channels` to restrict). + - If you only set `DISCORD_BOT_TOKEN` and never create a `channels.discord` section, the runtime + defaults `groupPolicy` to `open`. Add `channels.discord.groupPolicy`, + `channels.defaults.groupPolicy`, or a guild/channel allowlist to lock it down. +- `requireMention` must live under `channels.discord.guilds` (or a specific channel). `channels.discord.requireMention` at the top level is ignored. - **Permission audits** (`channels status --probe`) only check numeric channel IDs. If you use slugs/names as `channels.discord.guilds.*.channels` keys, the audit can’t verify permissions. - **DMs don’t work**: `channels.discord.dm.enabled=false`, `channels.discord.dm.policy="disabled"`, or you haven’t been approved yet (`channels.discord.dm.policy="pairing"`). ## Capabilities & limits - DMs and guild text channels (threads are treated as separate channels; voice not supported). - Typing indicators sent best-effort; message chunking uses `channels.discord.textChunkLimit` (default 2000) and splits tall replies by line count (`channels.discord.maxLinesPerMessage`, default 17). +- Optional newline chunking: set `channels.discord.chunkMode="newline"` to split on blank lines (paragraph boundaries) before length chunking. - File uploads supported up to the configured `channels.discord.mediaMaxMb` (default 8 MB). - Mention-gated guild replies by default to avoid noisy bots. - Reply context is injected when a message references another message (quoted content + ids). @@ -282,7 +289,7 @@ ack reaction after the bot replies. - `dm.enabled`: set `false` to ignore all DMs (default `true`). - `dm.policy`: DM access control (`pairing` recommended). `"open"` requires `dm.allowFrom=["*"]`. -- `dm.allowFrom`: DM allowlist (user ids or names). Used by `dm.policy="allowlist"` and for `dm.policy="open"` validation. +- `dm.allowFrom`: DM allowlist (user ids or names). Used by `dm.policy="allowlist"` and for `dm.policy="open"` validation. The wizard accepts usernames and resolves them to ids when the bot can search members. - `dm.groupEnabled`: enable group DMs (default `false`). - `dm.groupChannels`: optional allowlist for group DM channel ids or slugs. - `groupPolicy`: controls guild channel handling (`open|disabled|allowlist`); `allowlist` requires channel allowlists. @@ -300,6 +307,7 @@ ack reaction after the bot replies. - `guilds..requireMention`: per-guild mention requirement (overridable per channel). - `guilds..reactionNotifications`: reaction system event mode (`off`, `own`, `all`, `allowlist`). - `textChunkLimit`: outbound text chunk size (chars). Default: 2000. +- `chunkMode`: `length` (default) splits only when exceeding `textChunkLimit`; `newline` splits on blank lines (paragraph boundaries) before length chunking. - `maxLinesPerMessage`: soft max line count per message. Default: 17. - `mediaMaxMb`: clamp inbound media saved to disk. - `historyLimit`: number of recent guild messages to include as context when replying to a mention (default 20; falls back to `messages.groupChat.historyLimit`; `0` disables). @@ -360,10 +368,15 @@ Allowlist matching notes: - Use `*` to allow any sender/channel. - When `guilds..channels` is present, channels not listed are denied by default. - When `guilds..channels` is omitted, all channels in the allowlisted guild are allowed. +- To allow **no channels**, set `channels.discord.groupPolicy: "disabled"` (or keep an empty allowlist). +- The configure wizard accepts `Guild/Channel` names (public + private) and resolves them to IDs when possible. +- On startup, Clawdbot resolves channel/user names in allowlists to IDs (when the bot can search members) + and logs the mapping; unresolved entries are kept as typed. Native command notes: - The registered commands mirror Clawdbot’s chat commands. - Native commands honor the same allowlists as DMs/guild messages (`channels.discord.dm.allowFrom`, `channels.discord.guilds`, per-channel rules). +- Slash commands may still be visible in Discord UI to users who aren’t allowlisted; Clawdbot enforces allowlists on execution and replies “not authorized”. ## Tool actions The agent can call `discord` with actions like: diff --git a/docs/channels/googlechat.md b/docs/channels/googlechat.md new file mode 100644 index 000000000..00cfa7c72 --- /dev/null +++ b/docs/channels/googlechat.md @@ -0,0 +1,220 @@ +--- +summary: "Google Chat app support status, capabilities, and configuration" +read_when: + - Working on Google Chat channel features +--- +# Google Chat (Chat API) + +Status: ready for DMs + spaces via Google Chat API webhooks (HTTP only). + +## Quick setup (beginner) +1) Create a Google Cloud project and enable the **Google Chat API**. + - Go to: [Google Chat API Credentials](https://console.cloud.google.com/apis/api/chat.googleapis.com/credentials) + - Enable the API if it is not already enabled. +2) Create a **Service Account**: + - Press **Create Credentials** > **Service Account**. + - Name it whatever you want (e.g., `clawdbot-chat`). + - Leave permissions blank (press **Continue**). + - Leave principals with access blank (press **Done**). +3) Create and download the **JSON Key**: + - In the list of service accounts, click on the one you just created. + - Go to the **Keys** tab. + - Click **Add Key** > **Create new key**. + - Select **JSON** and press **Create**. +4) Store the downloaded JSON file on your gateway host (e.g., `~/.clawdbot/googlechat-service-account.json`). +5) Create a Google Chat app in the [Google Cloud Console Chat Configuration](https://console.cloud.google.com/apis/api/chat.googleapis.com/hangouts-chat): + - Fill in the **Application info**: + - **App name**: (e.g. `Clawdbot`) + - **Avatar URL**: (e.g. `https://clawd.bot/logo.png`) + - **Description**: (e.g. `Personal AI Assistant`) + - Enable **Interactive features**. + - Under **Functionality**, check **Join spaces and group conversations**. + - Under **Connection settings**, select **HTTP endpoint URL**. + - Under **Triggers**, select **Use a common HTTP endpoint URL for all triggers** and set it to your gateway's public URL followed by `/googlechat`. + - *Tip: Run `clawdbot status` to find your gateway's public URL.* + - Under **Visibility**, check **Make this Chat app available to specific people and groups in <Your Domain>**. + - Enter your email address (e.g. `user@example.com`) in the text box. + - Click **Save** at the bottom. +6) **Enable the app status**: + - After saving, **refresh the page**. + - Look for the **App status** section (usually near the top or bottom after saving). + - Change the status to **Live - available to users**. + - Click **Save** again. +7) Configure Clawdbot with the service account path + webhook audience: + - Env: `GOOGLE_CHAT_SERVICE_ACCOUNT_FILE=/path/to/service-account.json` + - Or config: `channels.googlechat.serviceAccountFile: "/path/to/service-account.json"`. +8) Set the webhook audience type + value (matches your Chat app config). +9) Start the gateway. Google Chat will POST to your webhook path. + +## Add to Google Chat +Once the gateway is running and your email is added to the visibility list: +1) Go to [Google Chat](https://chat.google.com/). +2) Click the **+** (plus) icon next to **Direct Messages**. +3) In the search bar (where you usually add people), type the **App name** you configured in the Google Cloud Console. + - **Note**: The bot will *not* appear in the "Marketplace" browse list because it is a private app. You must search for it by name. +4) Select your bot from the results. +5) Click **Add** or **Chat** to start a 1:1 conversation. +6) Send "Hello" to trigger the assistant! + +## Public URL (Webhook-only) +Google Chat webhooks require a public HTTPS endpoint. For security, **only expose the `/googlechat` path** to the internet. Keep the Clawdbot dashboard and other sensitive endpoints on your private network. + +### Option A: Tailscale Funnel (Recommended) +Use Tailscale Serve for the private dashboard and Funnel for the public webhook path. This keeps `/` private while exposing only `/googlechat`. + +1. **Check what address your gateway is bound to:** + ```bash + ss -tlnp | grep 18789 + ``` + Note the IP address (e.g., `127.0.0.1`, `0.0.0.0`, or your Tailscale IP like `100.x.x.x`). + +2. **Expose the dashboard to the tailnet only (port 8443):** + ```bash + # If bound to localhost (127.0.0.1 or 0.0.0.0): + tailscale serve --bg --https 8443 http://127.0.0.1:18789 + + # If bound to Tailscale IP only (e.g., 100.106.161.80): + tailscale serve --bg --https 8443 http://100.106.161.80:18789 + ``` + +3. **Expose only the webhook path publicly:** + ```bash + # If bound to localhost (127.0.0.1 or 0.0.0.0): + tailscale funnel --bg --set-path /googlechat http://127.0.0.1:18789/googlechat + + # If bound to Tailscale IP only (e.g., 100.106.161.80): + tailscale funnel --bg --set-path /googlechat http://100.106.161.80:18789/googlechat + ``` + +4. **Authorize the node for Funnel access:** + If prompted, visit the authorization URL shown in the output to enable Funnel for this node in your tailnet policy. + +5. **Verify the configuration:** + ```bash + tailscale serve status + tailscale funnel status + ``` + +Your public webhook URL will be: +`https://..ts.net/googlechat` + +Your private dashboard stays tailnet-only: +`https://..ts.net:8443/` + +Use the public URL (without `:8443`) in the Google Chat app config. + +> Note: This configuration persists across reboots. To remove it later, run `tailscale funnel reset` and `tailscale serve reset`. + +### Option B: Reverse Proxy (Caddy) +If you use a reverse proxy like Caddy, only proxy the specific path: +```caddy +your-domain.com { + reverse_proxy /googlechat* localhost:18789 +} +``` +With this config, any request to `your-domain.com/` will be ignored or returned as 404, while `your-domain.com/googlechat` is safely routed to Clawdbot. + +### Option C: Cloudflare Tunnel +Configure your tunnel's ingress rules to only route the webhook path: +- **Path**: `/googlechat` -> `http://localhost:18789/googlechat` +- **Default Rule**: HTTP 404 (Not Found) + +## How it works + +1. Google Chat sends webhook POSTs to the gateway. Each request includes an `Authorization: Bearer ` header. +2. Clawdbot verifies the token against the configured `audienceType` + `audience`: + - `audienceType: "app-url"` → audience is your HTTPS webhook URL. + - `audienceType: "project-number"` → audience is the Cloud project number. +3. Messages are routed by space: + - DMs use session key `agent::googlechat:dm:`. + - Spaces use session key `agent::googlechat:group:`. +4. DM access is pairing by default. Unknown senders receive a pairing code; approve with: + - `clawdbot pairing approve googlechat ` +5. Group spaces require @-mention by default. Use `botUser` if mention detection needs the app’s user name. + +## Targets +Use these identifiers for delivery and allowlists: +- Direct messages: `users/` or `users/` (email addresses are accepted). +- Spaces: `spaces/`. + +## Config highlights +```json5 +{ + channels: { + "googlechat": { + enabled: true, + serviceAccountFile: "/path/to/service-account.json", + audienceType: "app-url", + audience: "https://gateway.example.com/googlechat", + webhookPath: "/googlechat", + botUser: "users/1234567890", // optional; helps mention detection + dm: { + policy: "pairing", + allowFrom: ["users/1234567890", "name@example.com"] + }, + groupPolicy: "allowlist", + groups: { + "spaces/AAAA": { + allow: true, + requireMention: true, + users: ["users/1234567890"], + systemPrompt: "Short answers only." + } + }, + actions: { reactions: true }, + typingIndicator: "message", + mediaMaxMb: 20 + } + } +} +``` + +Notes: +- Service account credentials can also be passed inline with `serviceAccount` (JSON string). +- Default webhook path is `/googlechat` if `webhookPath` isn’t set. +- Reactions are available via the `reactions` tool and `channels action` when `actions.reactions` is enabled. +- `typingIndicator` supports `none`, `message` (default), and `reaction` (reaction requires user OAuth). +- Attachments are downloaded through the Chat API and stored in the media pipeline (size capped by `mediaMaxMb`). + +## Troubleshooting + +### 405 Method Not Allowed +If Google Cloud Logs Explorer shows errors like: +``` +status code: 405, reason phrase: HTTP error response: HTTP/1.1 405 Method Not Allowed +``` + +This means the webhook handler isn't registered. Common causes: +1. **Channel not configured**: The `channels.googlechat` section is missing from your config. Verify with: + ```bash + clawdbot config get channels.googlechat + ``` + If it returns "Config path not found", add the configuration (see [Config highlights](#config-highlights)). + +2. **Plugin not enabled**: Check plugin status: + ```bash + clawdbot plugins list | grep googlechat + ``` + If it shows "disabled", add `plugins.entries.googlechat.enabled: true` to your config. + +3. **Gateway not restarted**: After adding config, restart the gateway: + ```bash + clawdbot gateway restart + ``` + +Verify the channel is running: +```bash +clawdbot channels status +# Should show: Google Chat default: enabled, configured, ... +``` + +### Other issues +- Check `clawdbot channels status --probe` for auth errors or missing audience config. +- If no messages arrive, confirm the Chat app's webhook URL + event subscriptions. +- If mention gating blocks replies, set `botUser` to the app's user resource name and verify `requireMention`. +- Use `clawdbot logs --follow` while sending a test message to see if requests reach the gateway. + +Related docs: +- [Gateway configuration](/gateway/configuration) +- [Security](/gateway/security) +- [Reactions](/tools/reactions) diff --git a/docs/channels/grammy.md b/docs/channels/grammy.md index ff0c92c7a..89e5beed2 100644 --- a/docs/channels/grammy.md +++ b/docs/channels/grammy.md @@ -17,7 +17,7 @@ read_when: - **Proxy:** optional `channels.telegram.proxy` uses `undici.ProxyAgent` through grammY’s `client.baseFetch`. - **Webhook support:** `webhook-set.ts` wraps `setWebhook/deleteWebhook`; `webhook.ts` hosts the callback with health + graceful shutdown. Gateway enables webhook mode when `channels.telegram.webhookUrl` is set (otherwise it long-polls). - **Sessions:** direct chats collapse into the agent main session (`agent::`); groups use `agent::telegram:group:`; replies route back to the same channel. -- **Config knobs:** `channels.telegram.botToken`, `channels.telegram.dmPolicy`, `channels.telegram.groups` (allowlist + mention defaults), `channels.telegram.allowFrom`, `channels.telegram.groupAllowFrom`, `channels.telegram.groupPolicy`, `channels.telegram.mediaMaxMb`, `channels.telegram.proxy`, `channels.telegram.webhookSecret`, `channels.telegram.webhookUrl`. +- **Config knobs:** `channels.telegram.botToken`, `channels.telegram.dmPolicy`, `channels.telegram.groups` (allowlist + mention defaults), `channels.telegram.allowFrom`, `channels.telegram.groupAllowFrom`, `channels.telegram.groupPolicy`, `channels.telegram.mediaMaxMb`, `channels.telegram.linkPreview`, `channels.telegram.proxy`, `channels.telegram.webhookSecret`, `channels.telegram.webhookUrl`. - **Draft streaming:** optional `channels.telegram.streamMode` uses `sendMessageDraft` in private topic chats (Bot API 9.3+). This is separate from channel block streaming. - **Tests:** grammy mocks cover DM + group mention gating and outbound send; more media/webhook fixtures still welcome. diff --git a/docs/channels/imessage.md b/docs/channels/imessage.md index 6d98b9f73..bae945e8c 100644 --- a/docs/channels/imessage.md +++ b/docs/channels/imessage.md @@ -108,10 +108,68 @@ If you want iMessage on another Mac, set `channels.imessage.cliPath` to a wrappe Example wrapper: ```bash #!/usr/bin/env bash -exec ssh -T mac-mini imsg "$@" +exec ssh -T gateway-host imsg "$@" ``` -Multi-account support: use `channels.imessage.accounts` with per-account config and optional `name`. See [`gateway/configuration`](/gateway/configuration#telegramaccounts--discordaccounts--slackaccounts--signalaccounts--imessageaccounts) for the shared pattern. Don’t commit `~/.clawdbot/clawdbot.json` (it often contains tokens). +**Remote attachments:** When `cliPath` points to a remote host via SSH, attachment paths in the Messages database reference files on the remote machine. Clawdbot can automatically fetch these over SCP by setting `channels.imessage.remoteHost`: + +```json5 +{ + channels: { + imessage: { + cliPath: "~/imsg-ssh", // SSH wrapper to remote Mac + remoteHost: "user@gateway-host", // for SCP file transfer + includeAttachments: true + } + } +} +``` + +If `remoteHost` is not set, Clawdbot attempts to auto-detect it by parsing the SSH command in your wrapper script. Explicit configuration is recommended for reliability. + +#### Remote Mac via Tailscale (example) +If the Gateway runs on a Linux host/VM but iMessage must run on a Mac, Tailscale is the simplest bridge: the Gateway talks to the Mac over the tailnet, runs `imsg` via SSH, and SCPs attachments back. + +Architecture: +``` +┌──────────────────────────────┐ SSH (imsg rpc) ┌──────────────────────────┐ +│ Gateway host (Linux/VM) │──────────────────────────────────▶│ Mac with Messages + imsg │ +│ - clawdbot gateway │ SCP (attachments) │ - Messages signed in │ +│ - channels.imessage.cliPath │◀──────────────────────────────────│ - Remote Login enabled │ +└──────────────────────────────┘ └──────────────────────────┘ + ▲ + │ Tailscale tailnet (hostname or 100.x.y.z) + ▼ + user@gateway-host +``` + +Concrete config example (Tailscale hostname): +```json5 +{ + channels: { + imessage: { + enabled: true, + cliPath: "~/.clawdbot/scripts/imsg-ssh", + remoteHost: "bot@mac-mini.tailnet-1234.ts.net", + includeAttachments: true, + dbPath: "/Users/bot/Library/Messages/chat.db" + } + } +} +``` + +Example wrapper (`~/.clawdbot/scripts/imsg-ssh`): +```bash +#!/usr/bin/env bash +exec ssh -T bot@mac-mini.tailnet-1234.ts.net imsg "$@" +``` + +Notes: +- Ensure the Mac is signed in to Messages, and Remote Login is enabled. +- Use SSH keys so `ssh bot@mac-mini.tailnet-1234.ts.net` works without prompts. +- `remoteHost` should match the SSH target so SCP can fetch attachments. + +Multi-account support: use `channels.imessage.accounts` with per-account config and optional `name`. See [`gateway/configuration`](/gateway/configuration#telegramaccounts--discordaccounts--slackaccounts--signalaccounts--imessageaccounts) for the shared pattern. Don't commit `~/.clawdbot/clawdbot.json` (it often contains tokens). ## Access control (DMs + groups) DMs: @@ -161,6 +219,7 @@ This is useful when you want an isolated personality/model for a specific thread ## Limits - Outbound text is chunked to `channels.imessage.textChunkLimit` (default 4000). +- Optional newline chunking: set `channels.imessage.chunkMode="newline"` to split on blank lines (paragraph boundaries) before length chunking. - Media uploads are capped by `channels.imessage.mediaMaxMb` (default 16). ## Addressing / delivery targets @@ -182,10 +241,11 @@ Provider options: - `channels.imessage.enabled`: enable/disable channel startup. - `channels.imessage.cliPath`: path to `imsg`. - `channels.imessage.dbPath`: Messages DB path. +- `channels.imessage.remoteHost`: SSH host for SCP attachment transfer when `cliPath` points to a remote Mac (e.g., `user@gateway-host`). Auto-detected from SSH wrapper if not set. - `channels.imessage.service`: `imessage | sms | auto`. - `channels.imessage.region`: SMS region. - `channels.imessage.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing). -- `channels.imessage.allowFrom`: DM allowlist (handles or `chat_id:*`). `open` requires `"*"`. +- `channels.imessage.allowFrom`: DM allowlist (handles, emails, E.164 numbers, or `chat_id:*`). `open` requires `"*"`. iMessage has no usernames; use handles or chat targets. - `channels.imessage.groupPolicy`: `open | allowlist | disabled` (default: allowlist). - `channels.imessage.groupAllowFrom`: group sender allowlist. - `channels.imessage.historyLimit` / `channels.imessage.accounts.*.historyLimit`: max group messages to include as context (0 disables). @@ -194,6 +254,7 @@ Provider options: - `channels.imessage.includeAttachments`: ingest attachments into context. - `channels.imessage.mediaMaxMb`: inbound/outbound media cap (MB). - `channels.imessage.textChunkLimit`: outbound chunk size (chars). +- `channels.imessage.chunkMode`: `length` (default) or `newline` to split on blank lines (paragraph boundaries) before length chunking. Related global options: - `agents.list[].groupChat.mentionPatterns` (or `messages.groupChat.mentionPatterns`). diff --git a/docs/channels/index.md b/docs/channels/index.md index b6b9559da..52e963b87 100644 --- a/docs/channels/index.md +++ b/docs/channels/index.md @@ -15,16 +15,25 @@ Text is supported everywhere; media and reactions vary by channel. - [Telegram](/channels/telegram) — Bot API via grammY; supports groups. - [Discord](/channels/discord) — Discord Bot API + Gateway; supports servers, channels, and DMs. - [Slack](/channels/slack) — Bolt SDK; workspace apps. +- [Google Chat](/channels/googlechat) — Google Chat API app via HTTP webhook. +- [Mattermost](/channels/mattermost) — Bot API + WebSocket; channels, groups, DMs (plugin, installed separately). - [Signal](/channels/signal) — signal-cli; privacy-focused. -- [iMessage](/channels/imessage) — macOS only; native integration. +- [BlueBubbles](/channels/bluebubbles) — **Recommended for iMessage**; uses the BlueBubbles macOS server REST API with full feature support (edit, unsend, effects, reactions, group management — edit currently broken on macOS 26 Tahoe). +- [iMessage](/channels/imessage) — macOS only; native integration via imsg (legacy, consider BlueBubbles for new setups). - [Microsoft Teams](/channels/msteams) — Bot Framework; enterprise support (plugin, installed separately). +- [Nextcloud Talk](/channels/nextcloud-talk) — Self-hosted chat via Nextcloud Talk (plugin, installed separately). - [Matrix](/channels/matrix) — Matrix protocol (plugin, installed separately). +- [Nostr](/channels/nostr) — Decentralized DMs via NIP-04 (plugin, installed separately). +- [Tlon](/channels/tlon) — Urbit-based messenger (plugin, installed separately). - [Zalo](/channels/zalo) — Zalo Bot API; Vietnam's popular messenger (plugin, installed separately). +- [Zalo Personal](/channels/zalouser) — Zalo personal account via QR login (plugin, installed separately). - [WebChat](/web/webchat) — Gateway WebChat UI over WebSocket. ## Notes - Channels can run simultaneously; configure multiple and Clawdbot will route per chat. +- Fastest setup is usually **Telegram** (simple bot token). WhatsApp requires QR pairing and + stores more state on disk. - Group behavior varies by channel; see [Groups](/concepts/groups). - DM pairing and allowlists are enforced for safety; see [Security](/gateway/security). - Telegram internals: [grammY notes](/channels/grammy). diff --git a/docs/channels/location.md b/docs/channels/location.md index f38031fb6..c3742c63a 100644 --- a/docs/channels/location.md +++ b/docs/channels/location.md @@ -14,6 +14,7 @@ Clawdbot normalizes shared locations from chat channels into: Currently supported: - **Telegram** (location pins + venues + live locations) - **WhatsApp** (locationMessage + liveLocationMessage) +- **Matrix** (`m.location` with `geo_uri`) ## Text formatting Locations are rendered as friendly lines without brackets: @@ -44,3 +45,4 @@ When a location is present, these fields are added to `ctx`: ## Channel notes - **Telegram**: venues map to `LocationName/LocationAddress`; live locations use `live_period`. - **WhatsApp**: `locationMessage.comment` and `liveLocationMessage.caption` are appended as the caption line. +- **Matrix**: `geo_uri` is parsed as a pin location; altitude is ignored and `LocationIsLive` is always false. diff --git a/docs/channels/matrix.md b/docs/channels/matrix.md index add7d4930..2d9025f51 100644 --- a/docs/channels/matrix.md +++ b/docs/channels/matrix.md @@ -5,17 +5,26 @@ read_when: --- # Matrix (plugin) -Status: supported via plugin (matrix-js-sdk). Direct messages, rooms, threads, media, reactions, and polls. +Matrix is an open, decentralized messaging protocol. Clawdbot connects as a Matrix **user** +on any homeserver, so you need a Matrix account for the bot. Once it is logged in, you can DM +the bot directly or invite it to rooms (Matrix "groups"). Beeper is a valid client option too, +but it requires E2EE to be enabled. + +Status: supported via plugin (matrix-bot-sdk). Direct messages, rooms, threads, media, reactions, +polls (send + poll-start as text), location, and E2EE (with crypto support). ## Plugin required + Matrix ships as a plugin and is not bundled with the core install. Install via CLI (npm registry): + ```bash clawdbot plugins install @clawdbot/matrix ``` Local checkout (when running from a git repo): + ```bash clawdbot plugins install ./extensions/matrix ``` @@ -25,26 +34,54 @@ Clawdbot will offer the local install path automatically. Details: [Plugins](/plugin) -## Quick setup (beginner) +## Setup + 1) Install the Matrix plugin: - From npm: `clawdbot plugins install @clawdbot/matrix` - From a local checkout: `clawdbot plugins install ./extensions/matrix` -2) Configure credentials: - - Env: `MATRIX_HOMESERVER`, `MATRIX_USER_ID`, `MATRIX_ACCESS_TOKEN` (or `MATRIX_PASSWORD`) +2) Create a Matrix account on a homeserver: + - Browse hosting options at [https://matrix.org/ecosystem/hosting/](https://matrix.org/ecosystem/hosting/) + - Or host it yourself. +3) Get an access token for the bot account: + - Use the Matrix login API with `curl` at your home server: + + ```bash + curl --request POST \ + --url https://matrix.example.org/_matrix/client/v3/login \ + --header 'Content-Type: application/json' \ + --data '{ + "type": "m.login.password", + "identifier": { + "type": "m.id.user", + "user": "your-user-name" + }, + "password": "your-password" + }' + ``` + + - Replace `matrix.example.org` with your homeserver URL. + - Or set `channels.matrix.userId` + `channels.matrix.password`: Clawdbot calls the same + login endpoint, stores the access token in `~/.clawdbot/credentials/matrix/credentials.json`, + and reuses it on next start. +4) Configure credentials: + - Env: `MATRIX_HOMESERVER`, `MATRIX_ACCESS_TOKEN` (or `MATRIX_USER_ID` + `MATRIX_PASSWORD`) - Or config: `channels.matrix.*` -3) Restart the gateway (or finish onboarding). -4) DM access defaults to pairing; approve the pairing code on first contact. + - If both are set, config takes precedence. + - With access token: user ID is fetched automatically via `/whoami`. + - When set, `channels.matrix.userId` should be the full Matrix ID (example: `@bot:example.org`). +5) Restart the gateway (or finish onboarding). +6) Start a DM with the bot or invite it to a room from any Matrix client + (Element, Beeper, etc.; see https://matrix.org/ecosystem/clients/). Beeper requires E2EE, + so set `channels.matrix.encryption: true` and verify the device. -Runtime note: Matrix requires Node.js (Bun is not supported). +Minimal config (access token, user ID auto-fetched): -Minimal config: ```json5 { channels: { matrix: { enabled: true, homeserver: "https://matrix.example.org", - userId: "@clawdbot:example.org", accessToken: "syt_***", dm: { policy: "pairing" } } @@ -52,74 +89,140 @@ Minimal config: } ``` -## Encryption (E2EE) -End-to-end encrypted rooms are **not** supported. -- Use unencrypted rooms or disable encryption when creating the room. -- If a room is E2EE, the bot will receive encrypted events and won’t reply. +E2EE config (end to end encryption enabled): -## What it is -Matrix is an open messaging protocol. Clawdbot connects as a Matrix user and listens to DMs and rooms. -- A Matrix user account owned by the Gateway. -- Deterministic routing: replies go back to Matrix. +```json5 +{ + channels: { + matrix: { + enabled: true, + homeserver: "https://matrix.example.org", + accessToken: "syt_***", + encryption: true, + dm: { policy: "pairing" } + } + } +} +``` + +## Encryption (E2EE) + +End-to-end encryption is **supported** via the Rust crypto SDK. + +Enable with `channels.matrix.encryption: true`: + +- If the crypto module loads, encrypted rooms are decrypted automatically. +- Outbound media is encrypted when sending to encrypted rooms. +- On first connection, Clawdbot requests device verification from your other sessions. +- Verify the device in another Matrix client (Element, etc.) to enable key sharing. +- If the crypto module cannot be loaded, E2EE is disabled and encrypted rooms will not decrypt; + Clawdbot logs a warning. +- If you see missing crypto module errors (for example, `@matrix-org/matrix-sdk-crypto-nodejs-*`), + allow build scripts for `@matrix-org/matrix-sdk-crypto-nodejs` and run + `pnpm rebuild @matrix-org/matrix-sdk-crypto-nodejs` or fetch the binary with + `node node_modules/@matrix-org/matrix-sdk-crypto-nodejs/download-lib.js`. + +Crypto state is stored per account + access token in +`~/.clawdbot/matrix/accounts//__//crypto/` +(SQLite database). Sync state lives alongside it in `bot-storage.json`. +If the access token (device) changes, a new store is created and the bot must be +re-verified for encrypted rooms. + +**Device verification:** +When E2EE is enabled, the bot will request verification from your other sessions on startup. +Open Element (or another client) and approve the verification request to establish trust. +Once verified, the bot can decrypt messages in encrypted rooms. + +## Routing model + +- Replies always go back to Matrix. - DMs share the agent's main session; rooms map to group sessions. ## Access control (DMs) + - Default: `channels.matrix.dm.policy = "pairing"`. Unknown senders get a pairing code. - Approve via: - `clawdbot pairing list matrix` - `clawdbot pairing approve matrix ` - Public DMs: `channels.matrix.dm.policy="open"` plus `channels.matrix.dm.allowFrom=["*"]`. +- `channels.matrix.dm.allowFrom` accepts user IDs or display names. The wizard resolves display names to user IDs when directory search is available. ## Rooms (groups) -- Default: `channels.matrix.groupPolicy = "allowlist"` (mention-gated). -- Allowlist rooms with `channels.matrix.rooms`: + +- Default: `channels.matrix.groupPolicy = "allowlist"` (mention-gated). Use `channels.defaults.groupPolicy` to override the default when unset. +- Allowlist rooms with `channels.matrix.groups` (room IDs, aliases, or names): + ```json5 { channels: { matrix: { - rooms: { - "!roomId:example.org": { requireMention: true } - } + groupPolicy: "allowlist", + groups: { + "!roomId:example.org": { allow: true }, + "#alias:example.org": { allow: true } + }, + groupAllowFrom: ["@owner:example.org"] } } } ``` + - `requireMention: false` enables auto-reply in that room. +- `groups."*"` can set defaults for mention gating across rooms. +- `groupAllowFrom` restricts which senders can trigger the bot in rooms (optional). +- Per-room `users` allowlists can further restrict senders inside a specific room. +- The configure wizard prompts for room allowlists (room IDs, aliases, or names) and resolves names when possible. +- On startup, Clawdbot resolves room/user names in allowlists to IDs and logs the mapping; unresolved entries are kept as typed. +- Invites are auto-joined by default; control with `channels.matrix.autoJoin` and `channels.matrix.autoJoinAllowlist`. +- To allow **no rooms**, set `channels.matrix.groupPolicy: "disabled"` (or keep an empty allowlist). +- Legacy key: `channels.matrix.rooms` (same shape as `groups`). ## Threads + - Reply threading is supported. -- `channels.matrix.replyToMode` controls replies when tagged: +- `channels.matrix.threadReplies` controls whether replies stay in threads: + - `off`, `inbound` (default), `always` +- `channels.matrix.replyToMode` controls reply-to metadata when not replying in a thread: - `off` (default), `first`, `all` ## Capabilities + | Feature | Status | |---------|--------| | Direct messages | ✅ Supported | | Rooms | ✅ Supported | | Threads | ✅ Supported | | Media | ✅ Supported | -| Reactions | ✅ Supported | -| Polls | ✅ Supported | +| E2EE | ✅ Supported (crypto module required) | +| Reactions | ✅ Supported (send/read via tools) | +| Polls | ✅ Send supported; inbound poll starts are converted to text (responses/ends ignored) | +| Location | ✅ Supported (geo URI; altitude ignored) | | Native commands | ✅ Supported | ## Configuration reference (Matrix) + Full configuration: [Configuration](/gateway/configuration) Provider options: + - `channels.matrix.enabled`: enable/disable channel startup. - `channels.matrix.homeserver`: homeserver URL. -- `channels.matrix.userId`: Matrix user ID. +- `channels.matrix.userId`: Matrix user ID (optional with access token). - `channels.matrix.accessToken`: access token. - `channels.matrix.password`: password for login (token stored). - `channels.matrix.deviceName`: device display name. +- `channels.matrix.encryption`: enable E2EE (default: false). - `channels.matrix.initialSyncLimit`: initial sync limit. - `channels.matrix.threadReplies`: `off | inbound | always` (default: inbound). - `channels.matrix.textChunkLimit`: outbound text chunk size (chars). +- `channels.matrix.chunkMode`: `length` (default) or `newline` to split on blank lines (paragraph boundaries) before length chunking. - `channels.matrix.dm.policy`: `pairing | allowlist | open | disabled` (default: pairing). -- `channels.matrix.dm.allowFrom`: DM allowlist. `open` requires `"*"`. +- `channels.matrix.dm.allowFrom`: DM allowlist (user IDs or display names). `open` requires `"*"`. The wizard resolves names to IDs when possible. - `channels.matrix.groupPolicy`: `allowlist | open | disabled` (default: allowlist). +- `channels.matrix.groupAllowFrom`: allowlisted senders for group messages. - `channels.matrix.allowlistOnly`: force allowlist rules for DMs + rooms. -- `channels.matrix.rooms`: per-room settings and allowlist. +- `channels.matrix.groups`: group allowlist + per-room settings map. +- `channels.matrix.rooms`: legacy group allowlist/config. - `channels.matrix.replyToMode`: reply-to mode for threads/tags. - `channels.matrix.mediaMaxMb`: inbound/outbound media cap (MB). - `channels.matrix.autoJoin`: invite handling (`always | allowlist | off`, default: always). diff --git a/docs/channels/mattermost.md b/docs/channels/mattermost.md new file mode 100644 index 000000000..de4771745 --- /dev/null +++ b/docs/channels/mattermost.md @@ -0,0 +1,123 @@ +--- +summary: "Mattermost bot setup and Clawdbot config" +read_when: + - Setting up Mattermost + - Debugging Mattermost routing +--- + +# Mattermost (plugin) + +Status: supported via plugin (bot token + WebSocket events). Channels, groups, and DMs are supported. +Mattermost is a self-hostable team messaging platform; see the official site at +[mattermost.com](https://mattermost.com) for product details and downloads. + +## Plugin required +Mattermost ships as a plugin and is not bundled with the core install. + +Install via CLI (npm registry): +```bash +clawdbot plugins install @clawdbot/mattermost +``` + +Local checkout (when running from a git repo): +```bash +clawdbot plugins install ./extensions/mattermost +``` + +If you choose Mattermost during configure/onboarding and a git checkout is detected, +Clawdbot will offer the local install path automatically. + +Details: [Plugins](/plugin) + +## Quick setup +1) Install the Mattermost plugin. +2) Create a Mattermost bot account and copy the **bot token**. +3) Copy the Mattermost **base URL** (e.g., `https://chat.example.com`). +4) Configure Clawdbot and start the gateway. + +Minimal config: +```json5 +{ + channels: { + mattermost: { + enabled: true, + botToken: "mm-token", + baseUrl: "https://chat.example.com", + dmPolicy: "pairing" + } + } +} +``` + +## Environment variables (default account) +Set these on the gateway host if you prefer env vars: + +- `MATTERMOST_BOT_TOKEN=...` +- `MATTERMOST_URL=https://chat.example.com` + +Env vars apply only to the **default** account (`default`). Other accounts must use config values. + +## Chat modes +Mattermost responds to DMs automatically. Channel behavior is controlled by `chatmode`: + +- `oncall` (default): respond only when @mentioned in channels. +- `onmessage`: respond to every channel message. +- `onchar`: respond when a message starts with a trigger prefix. + +Config example: +```json5 +{ + channels: { + mattermost: { + chatmode: "onchar", + oncharPrefixes: [">", "!"] + } + } +} +``` + +Notes: +- `onchar` still responds to explicit @mentions. +- `channels.mattermost.requireMention` is honored for legacy configs but `chatmode` is preferred. + +## Access control (DMs) +- Default: `channels.mattermost.dmPolicy = "pairing"` (unknown senders get a pairing code). +- Approve via: + - `clawdbot pairing list mattermost` + - `clawdbot pairing approve mattermost ` +- Public DMs: `channels.mattermost.dmPolicy="open"` plus `channels.mattermost.allowFrom=["*"]`. + +## Channels (groups) +- Default: `channels.mattermost.groupPolicy = "allowlist"` (mention-gated). +- Allowlist senders with `channels.mattermost.groupAllowFrom` (user IDs or `@username`). +- Open channels: `channels.mattermost.groupPolicy="open"` (mention-gated). + +## Targets for outbound delivery +Use these target formats with `clawdbot message send` or cron/webhooks: + +- `channel:` for a channel +- `user:` for a DM +- `@username` for a DM (resolved via the Mattermost API) + +Bare IDs are treated as channels. + +## Multi-account +Mattermost supports multiple accounts under `channels.mattermost.accounts`: + +```json5 +{ + channels: { + mattermost: { + accounts: { + default: { name: "Primary", botToken: "mm-token", baseUrl: "https://chat.example.com" }, + alerts: { name: "Alerts", botToken: "mm-token-2", baseUrl: "https://alerts.example.com" } + } + } + } +} +``` + +## Troubleshooting +- No replies in channels: ensure the bot is in the channel and mention it (oncall), use a trigger prefix (onchar), or set `chatmode: "onmessage"`. +- Auth errors: check the bot token, base URL, and whether the account is enabled. +- Multi-account issues: env vars only apply to the `default` account. diff --git a/docs/channels/msteams.md b/docs/channels/msteams.md index 7c4cfb54d..2f6ed5f83 100644 --- a/docs/channels/msteams.md +++ b/docs/channels/msteams.md @@ -8,9 +8,9 @@ read_when: > "Abandon all hope, ye who enter here." -Updated: 2026-01-16 +Updated: 2026-01-21 -Status: text + DM attachments are supported; channel/group attachments require Microsoft Graph permissions. Polls are sent via Adaptive Cards. +Status: text + DM attachments are supported; channel/group file sending requires `sharePointSiteId` + Graph permissions (see [Sending files in group chats](#sending-files-in-group-chats)). Polls are sent via Adaptive Cards. ## Plugin required Microsoft Teams ships as a plugin and is not bundled with the core install. @@ -76,12 +76,13 @@ Disable with: **DM access** - Default: `channels.msteams.dmPolicy = "pairing"`. Unknown senders are ignored until approved. -- `channels.msteams.allowFrom` accepts AAD object IDs or UPNs. +- `channels.msteams.allowFrom` accepts AAD object IDs, UPNs, or display names. The wizard resolves names to IDs via Microsoft Graph when credentials allow. **Group access** -- Default: `channels.msteams.groupPolicy = "allowlist"` (blocked unless you add `groupAllowFrom`). +- Default: `channels.msteams.groupPolicy = "allowlist"` (blocked unless you add `groupAllowFrom`). Use `channels.defaults.groupPolicy` to override the default when unset. - `channels.msteams.groupAllowFrom` controls which senders can trigger in group chats/channels (falls back to `channels.msteams.allowFrom`). - Set `groupPolicy: "open"` to allow any member (still mention‑gated by default). +- To allow **no channels**, set `channels.msteams.groupPolicy: "disabled"`. Example: ```json5 @@ -95,6 +96,32 @@ Example: } ``` +**Teams + channel allowlist** +- Scope group/channel replies by listing teams and channels under `channels.msteams.teams`. +- Keys can be team IDs or names; channel keys can be conversation IDs or names. +- When `groupPolicy="allowlist"` and a teams allowlist is present, only listed teams/channels are accepted (mention‑gated). +- The configure wizard accepts `Team/Channel` entries and stores them for you. +- On startup, Clawdbot resolves team/channel and user allowlist names to IDs (when Graph permissions allow) + and logs the mapping; unresolved entries are kept as typed. + +Example: +```json5 +{ + channels: { + msteams: { + groupPolicy: "allowlist", + teams: { + "My Team": { + channels: { + "General": { requireMention: true } + } + } + } + } + } +} +``` + ## How it works 1. Install the Microsoft Teams plugin. 2. Create an **Azure Bot** (App ID + secret + tenant ID). @@ -376,7 +403,7 @@ Clawdbot handles this by returning quickly and sending replies proactively, but Teams markdown is more limited than Slack or Discord: - Basic formatting works: **bold**, *italic*, `code`, links - Complex markdown (tables, nested lists) may not render correctly -- Adaptive Cards are used for polls; other card types are not yet supported +- Adaptive Cards are supported for polls and arbitrary card sends (see below) ## Configuration Key settings (see `/gateway/configuration` for shared channel patterns): @@ -386,8 +413,9 @@ Key settings (see `/gateway/configuration` for shared channel patterns): - `channels.msteams.webhook.port` (default `3978`) - `channels.msteams.webhook.path` (default `/api/messages`) - `channels.msteams.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing) -- `channels.msteams.allowFrom`: allowlist for DMs (AAD object IDs or UPNs). +- `channels.msteams.allowFrom`: allowlist for DMs (AAD object IDs, UPNs, or display names). The wizard resolves names to IDs during setup when Graph access is available. - `channels.msteams.textChunkLimit`: outbound text chunk size. +- `channels.msteams.chunkMode`: `length` (default) or `newline` to split on blank lines (paragraph boundaries) before length chunking. - `channels.msteams.mediaAllowHosts`: allowlist for inbound attachment hosts (defaults to Microsoft/Teams domains). - `channels.msteams.requireMention`: require @mention in channels/groups (default true). - `channels.msteams.replyStyle`: `thread | top-level` (see [Reply Style](#reply-style-threads-vs-posts)). @@ -395,6 +423,7 @@ Key settings (see `/gateway/configuration` for shared channel patterns): - `channels.msteams.teams..requireMention`: per-team override. - `channels.msteams.teams..channels..replyStyle`: per-channel override. - `channels.msteams.teams..channels..requireMention`: per-channel override. +- `channels.msteams.sharePointSiteId`: SharePoint site ID for file uploads in group chats/channels (see [Sending files in group chats](#sending-files-in-group-chats)). ## Routing & Sessions - Session keys follow the standard agent format (see [/concepts/session](/concepts/session)): @@ -444,14 +473,159 @@ Teams recently introduced two channel UI styles over the same underlying data mo Without Graph permissions, channel messages with images will be received as text-only (the image content is not accessible to the bot). By default, Clawdbot only downloads media from Microsoft/Teams hostnames. Override with `channels.msteams.mediaAllowHosts` (use `["*"]` to allow any host). +## Sending files in group chats + +Bots can send files in DMs using the FileConsentCard flow (built-in). However, **sending files in group chats/channels** requires additional setup: + +| Context | How files are sent | Setup needed | +|---------|-------------------|--------------| +| **DMs** | FileConsentCard → user accepts → bot uploads | Works out of the box | +| **Group chats/channels** | Upload to SharePoint → share link | Requires `sharePointSiteId` + Graph permissions | +| **Images (any context)** | Base64-encoded inline | Works out of the box | + +### Why group chats need SharePoint + +Bots don't have a personal OneDrive drive (the `/me/drive` Graph API endpoint doesn't work for application identities). To send files in group chats/channels, the bot uploads to a **SharePoint site** and creates a sharing link. + +### Setup + +1. **Add Graph API permissions** in Entra ID (Azure AD) → App Registration: + - `Sites.ReadWrite.All` (Application) - upload files to SharePoint + - `Chat.Read.All` (Application) - optional, enables per-user sharing links + +2. **Grant admin consent** for the tenant. + +3. **Get your SharePoint site ID:** + ```bash + # Via Graph Explorer or curl with a valid token: + curl -H "Authorization: Bearer $TOKEN" \ + "https://graph.microsoft.com/v1.0/sites/{hostname}:/{site-path}" + + # Example: for a site at "contoso.sharepoint.com/sites/BotFiles" + curl -H "Authorization: Bearer $TOKEN" \ + "https://graph.microsoft.com/v1.0/sites/contoso.sharepoint.com:/sites/BotFiles" + + # Response includes: "id": "contoso.sharepoint.com,guid1,guid2" + ``` + +4. **Configure Clawdbot:** + ```json5 + { + channels: { + msteams: { + // ... other config ... + sharePointSiteId: "contoso.sharepoint.com,guid1,guid2" + } + } + } + ``` + +### Sharing behavior + +| Permission | Sharing behavior | +|------------|------------------| +| `Sites.ReadWrite.All` only | Organization-wide sharing link (anyone in org can access) | +| `Sites.ReadWrite.All` + `Chat.Read.All` | Per-user sharing link (only chat members can access) | + +Per-user sharing is more secure as only the chat participants can access the file. If `Chat.Read.All` permission is missing, the bot falls back to organization-wide sharing. + +### Fallback behavior + +| Scenario | Result | +|----------|--------| +| Group chat + file + `sharePointSiteId` configured | Upload to SharePoint, send sharing link | +| Group chat + file + no `sharePointSiteId` | Attempt OneDrive upload (may fail), send text only | +| Personal chat + file | FileConsentCard flow (works without SharePoint) | +| Any context + image | Base64-encoded inline (works without SharePoint) | + +### Files stored location + +Uploaded files are stored in a `/ClawdbotShared/` folder in the configured SharePoint site's default document library. + ## Polls (Adaptive Cards) Clawdbot sends Teams polls as Adaptive Cards (there is no native Teams poll API). -- CLI: `clawdbot message poll --channel msteams --to conversation: ...` +- CLI: `clawdbot message poll --channel msteams --target conversation: ...` - Votes are recorded by the gateway in `~/.clawdbot/msteams-polls.json`. - The gateway must stay online to record votes. - Polls do not auto-post result summaries yet (inspect the store file if needed). +## Adaptive Cards (arbitrary) +Send any Adaptive Card JSON to Teams users or conversations using the `message` tool or CLI. + +The `card` parameter accepts an Adaptive Card JSON object. When `card` is provided, the message text is optional. + +**Agent tool:** +```json +{ + "action": "send", + "channel": "msteams", + "target": "user:", + "card": { + "type": "AdaptiveCard", + "version": "1.5", + "body": [{"type": "TextBlock", "text": "Hello!"}] + } +} +``` + +**CLI:** +```bash +clawdbot message send --channel msteams \ + --target "conversation:19:abc...@thread.tacv2" \ + --card '{"type":"AdaptiveCard","version":"1.5","body":[{"type":"TextBlock","text":"Hello!"}]}' +``` + +See [Adaptive Cards documentation](https://adaptivecards.io/) for card schema and examples. For target format details, see [Target formats](#target-formats) below. + +## Target formats + +MSTeams targets use prefixes to distinguish between users and conversations: + +| Target type | Format | Example | +|-------------|--------|---------| +| User (by ID) | `user:` | `user:40a1a0ed-4ff2-4164-a219-55518990c197` | +| User (by name) | `user:` | `user:John Smith` (requires Graph API) | +| Group/channel | `conversation:` | `conversation:19:abc123...@thread.tacv2` | +| Group/channel (raw) | `` | `19:abc123...@thread.tacv2` (if contains `@thread`) | + +**CLI examples:** +```bash +# Send to a user by ID +clawdbot message send --channel msteams --target "user:40a1a0ed-..." --message "Hello" + +# Send to a user by display name (triggers Graph API lookup) +clawdbot message send --channel msteams --target "user:John Smith" --message "Hello" + +# Send to a group chat or channel +clawdbot message send --channel msteams --target "conversation:19:abc...@thread.tacv2" --message "Hello" + +# Send an Adaptive Card to a conversation +clawdbot message send --channel msteams --target "conversation:19:abc...@thread.tacv2" \ + --card '{"type":"AdaptiveCard","version":"1.5","body":[{"type":"TextBlock","text":"Hello"}]}' +``` + +**Agent tool examples:** +```json +{ + "action": "send", + "channel": "msteams", + "target": "user:John Smith", + "message": "Hello!" +} +``` + +```json +{ + "action": "send", + "channel": "msteams", + "target": "conversation:19:abc...@thread.tacv2", + "card": {"type": "AdaptiveCard", "version": "1.5", "body": [{"type": "TextBlock", "text": "Hello"}]} +} +``` + +Note: Without the `user:` prefix, names default to group/team resolution. Always use `user:` when targeting people by display name. + ## Proactive messaging - Proactive messages are only possible **after** a user has interacted, because we store conversation references at that point. - See `/gateway/configuration` for `dmPolicy` and allowlist gating. diff --git a/docs/channels/nextcloud-talk.md b/docs/channels/nextcloud-talk.md new file mode 100644 index 000000000..abc696444 --- /dev/null +++ b/docs/channels/nextcloud-talk.md @@ -0,0 +1,120 @@ +--- +summary: "Nextcloud Talk support status, capabilities, and configuration" +read_when: + - Working on Nextcloud Talk channel features +--- +# Nextcloud Talk (plugin) + +Status: supported via plugin (webhook bot). Direct messages, rooms, reactions, and markdown messages are supported. + +## Plugin required +Nextcloud Talk ships as a plugin and is not bundled with the core install. + +Install via CLI (npm registry): +```bash +clawdbot plugins install @clawdbot/nextcloud-talk +``` + +Local checkout (when running from a git repo): +```bash +clawdbot plugins install ./extensions/nextcloud-talk +``` + +If you choose Nextcloud Talk during configure/onboarding and a git checkout is detected, +Clawdbot will offer the local install path automatically. + +Details: [Plugins](/plugin) + +## Quick setup (beginner) +1) Install the Nextcloud Talk plugin. +2) On your Nextcloud server, create a bot: + ```bash + ./occ talk:bot:install "Clawdbot" "" "" --feature reaction + ``` +3) Enable the bot in the target room settings. +4) Configure Clawdbot: + - Config: `channels.nextcloud-talk.baseUrl` + `channels.nextcloud-talk.botSecret` + - Or env: `NEXTCLOUD_TALK_BOT_SECRET` (default account only) +5) Restart the gateway (or finish onboarding). + +Minimal config: +```json5 +{ + channels: { + "nextcloud-talk": { + enabled: true, + baseUrl: "https://cloud.example.com", + botSecret: "shared-secret", + dmPolicy: "pairing" + } + } +} +``` + +## Notes +- Bots cannot initiate DMs. The user must message the bot first. +- Webhook URL must be reachable by the Gateway; set `webhookPublicUrl` if behind a proxy. +- Media uploads are not supported by the bot API; media is sent as URLs. +- The webhook payload does not distinguish DMs vs rooms; set `apiUser` + `apiPassword` to enable room-type lookups (otherwise DMs are treated as rooms). + +## Access control (DMs) +- Default: `channels.nextcloud-talk.dmPolicy = "pairing"`. Unknown senders get a pairing code. +- Approve via: + - `clawdbot pairing list nextcloud-talk` + - `clawdbot pairing approve nextcloud-talk ` +- Public DMs: `channels.nextcloud-talk.dmPolicy="open"` plus `channels.nextcloud-talk.allowFrom=["*"]`. + +## Rooms (groups) +- Default: `channels.nextcloud-talk.groupPolicy = "allowlist"` (mention-gated). +- Allowlist rooms with `channels.nextcloud-talk.rooms`: +```json5 +{ + channels: { + "nextcloud-talk": { + rooms: { + "room-token": { requireMention: true } + } + } + } +} +``` +- To allow no rooms, keep the allowlist empty or set `channels.nextcloud-talk.groupPolicy="disabled"`. + +## Capabilities +| Feature | Status | +|---------|--------| +| Direct messages | Supported | +| Rooms | Supported | +| Threads | Not supported | +| Media | URL-only | +| Reactions | Supported | +| Native commands | Not supported | + +## Configuration reference (Nextcloud Talk) +Full configuration: [Configuration](/gateway/configuration) + +Provider options: +- `channels.nextcloud-talk.enabled`: enable/disable channel startup. +- `channels.nextcloud-talk.baseUrl`: Nextcloud instance URL. +- `channels.nextcloud-talk.botSecret`: bot shared secret. +- `channels.nextcloud-talk.botSecretFile`: secret file path. +- `channels.nextcloud-talk.apiUser`: API user for room lookups (DM detection). +- `channels.nextcloud-talk.apiPassword`: API/app password for room lookups. +- `channels.nextcloud-talk.apiPasswordFile`: API password file path. +- `channels.nextcloud-talk.webhookPort`: webhook listener port (default: 8788). +- `channels.nextcloud-talk.webhookHost`: webhook host (default: 0.0.0.0). +- `channels.nextcloud-talk.webhookPath`: webhook path (default: /nextcloud-talk-webhook). +- `channels.nextcloud-talk.webhookPublicUrl`: externally reachable webhook URL. +- `channels.nextcloud-talk.dmPolicy`: `pairing | allowlist | open | disabled`. +- `channels.nextcloud-talk.allowFrom`: DM allowlist (user IDs). `open` requires `"*"`. +- `channels.nextcloud-talk.groupPolicy`: `allowlist | open | disabled`. +- `channels.nextcloud-talk.groupAllowFrom`: group allowlist (user IDs). +- `channels.nextcloud-talk.rooms`: per-room settings and allowlist. +- `channels.nextcloud-talk.historyLimit`: group history limit (0 disables). +- `channels.nextcloud-talk.dmHistoryLimit`: DM history limit (0 disables). +- `channels.nextcloud-talk.dms`: per-DM overrides (historyLimit). +- `channels.nextcloud-talk.textChunkLimit`: outbound text chunk size (chars). +- `channels.nextcloud-talk.chunkMode`: `length` (default) or `newline` to split on blank lines (paragraph boundaries) before length chunking. +- `channels.nextcloud-talk.blockStreaming`: disable block streaming for this channel. +- `channels.nextcloud-talk.blockStreamingCoalesce`: block streaming coalesce tuning. +- `channels.nextcloud-talk.mediaMaxMb`: inbound media cap (MB). diff --git a/docs/channels/nostr.md b/docs/channels/nostr.md new file mode 100644 index 000000000..d1dc284bb --- /dev/null +++ b/docs/channels/nostr.md @@ -0,0 +1,235 @@ +--- +summary: "Nostr DM channel via NIP-04 encrypted messages" +read_when: + - You want Clawdbot to receive DMs via Nostr + - You're setting up decentralized messaging +--- +# Nostr + +**Status:** Optional plugin (disabled by default). + +Nostr is a decentralized protocol for social networking. This channel enables Clawdbot to receive and respond to encrypted direct messages (DMs) via NIP-04. + +## Install (on demand) + +### Onboarding (recommended) + +- The onboarding wizard (`clawdbot onboard`) and `clawdbot channels add` list optional channel plugins. +- Selecting Nostr prompts you to install the plugin on demand. + +Install defaults: + +- **Dev channel + git checkout available:** uses the local plugin path. +- **Stable/Beta:** downloads from npm. + +You can always override the choice in the prompt. + +### Manual install + +```bash +clawdbot plugins install @clawdbot/nostr +``` + +Use a local checkout (dev workflows): + +```bash +clawdbot plugins install --link /extensions/nostr +``` + +Restart the Gateway after installing or enabling plugins. + +## Quick setup + +1) Generate a Nostr keypair (if needed): + +```bash +# Using nak +nak key generate +``` + +2) Add to config: + +```json +{ + "channels": { + "nostr": { + "privateKey": "${NOSTR_PRIVATE_KEY}" + } + } +} +``` + +3) Export the key: + +```bash +export NOSTR_PRIVATE_KEY="nsec1..." +``` + +4) Restart the Gateway. + +## Configuration reference + +| Key | Type | Default | Description | +| --- | --- | --- | --- | +| `privateKey` | string | required | Private key in `nsec` or hex format | +| `relays` | string[] | `['wss://relay.damus.io', 'wss://nos.lol']` | Relay URLs (WebSocket) | +| `dmPolicy` | string | `pairing` | DM access policy | +| `allowFrom` | string[] | `[]` | Allowed sender pubkeys | +| `enabled` | boolean | `true` | Enable/disable channel | +| `name` | string | - | Display name | +| `profile` | object | - | NIP-01 profile metadata | + +## Profile metadata + +Profile data is published as a NIP-01 `kind:0` event. You can manage it from the Control UI (Channels -> Nostr -> Profile) or set it directly in config. + +Example: + +```json +{ + "channels": { + "nostr": { + "privateKey": "${NOSTR_PRIVATE_KEY}", + "profile": { + "name": "clawdbot", + "displayName": "Clawdbot", + "about": "Personal assistant DM bot", + "picture": "https://example.com/avatar.png", + "banner": "https://example.com/banner.png", + "website": "https://example.com", + "nip05": "clawdbot@example.com", + "lud16": "clawdbot@example.com" + } + } + } +} +``` + +Notes: + +- Profile URLs must use `https://`. +- Importing from relays merges fields and preserves local overrides. + +## Access control + +### DM policies + +- **pairing** (default): unknown senders get a pairing code. +- **allowlist**: only pubkeys in `allowFrom` can DM. +- **open**: public inbound DMs (requires `allowFrom: ["*"]`). +- **disabled**: ignore inbound DMs. + +### Allowlist example + +```json +{ + "channels": { + "nostr": { + "privateKey": "${NOSTR_PRIVATE_KEY}", + "dmPolicy": "allowlist", + "allowFrom": ["npub1abc...", "npub1xyz..."] + } + } +} +``` + +## Key formats + +Accepted formats: + +- **Private key:** `nsec...` or 64-char hex +- **Pubkeys (`allowFrom`):** `npub...` or hex + +## Relays + +Defaults: `relay.damus.io` and `nos.lol`. + +```json +{ + "channels": { + "nostr": { + "privateKey": "${NOSTR_PRIVATE_KEY}", + "relays": [ + "wss://relay.damus.io", + "wss://relay.primal.net", + "wss://nostr.wine" + ] + } + } +} +``` + +Tips: + +- Use 2-3 relays for redundancy. +- Avoid too many relays (latency, duplication). +- Paid relays can improve reliability. +- Local relays are fine for testing (`ws://localhost:7777`). + +## Protocol support + +| NIP | Status | Description | +| --- | --- | --- | +| NIP-01 | Supported | Basic event format + profile metadata | +| NIP-04 | Supported | Encrypted DMs (`kind:4`) | +| NIP-17 | Planned | Gift-wrapped DMs | +| NIP-44 | Planned | Versioned encryption | + +## Testing + +### Local relay + +```bash +# Start strfry +docker run -p 7777:7777 ghcr.io/hoytech/strfry +``` + +```json +{ + "channels": { + "nostr": { + "privateKey": "${NOSTR_PRIVATE_KEY}", + "relays": ["ws://localhost:7777"] + } + } +} +``` + +### Manual test + +1) Note the bot pubkey (npub) from logs. +2) Open a Nostr client (Damus, Amethyst, etc.). +3) DM the bot pubkey. +4) Verify the response. + +## Troubleshooting + +### Not receiving messages + +- Verify the private key is valid. +- Ensure relay URLs are reachable and use `wss://` (or `ws://` for local). +- Confirm `enabled` is not `false`. +- Check Gateway logs for relay connection errors. + +### Not sending responses + +- Check relay accepts writes. +- Verify outbound connectivity. +- Watch for relay rate limits. + +### Duplicate responses + +- Expected when using multiple relays. +- Messages are deduplicated by event ID; only the first delivery triggers a response. + +## Security + +- Never commit private keys. +- Use environment variables for keys. +- Consider `allowlist` for production bots. + +## Limitations (MVP) + +- Direct messages only (no group chats). +- No media attachments. +- NIP-04 only (NIP-17 gift-wrap planned). diff --git a/docs/channels/signal.md b/docs/channels/signal.md index e19c6579b..c154b0591 100644 --- a/docs/channels/signal.md +++ b/docs/channels/signal.md @@ -74,6 +74,22 @@ Example: Multi-account support: use `channels.signal.accounts` with per-account config and optional `name`. See [`gateway/configuration`](/gateway/configuration#telegramaccounts--discordaccounts--slackaccounts--signalaccounts--imessageaccounts) for the shared pattern. +## External daemon mode (httpUrl) +If you want to manage `signal-cli` yourself (slow JVM cold starts, container init, or shared CPUs), run the daemon separately and point Clawdbot at it: + +```json5 +{ + channels: { + signal: { + httpUrl: "http://127.0.0.1:8080", + autoStart: false + } + } +} +``` + +This skips auto-spawn and the startup wait inside Clawdbot. For slow starts when auto-spawning, set `channels.signal.startupTimeoutMs`. + ## Access control (DMs + groups) DMs: - Default: `channels.signal.dmPolicy = "pairing"`. @@ -95,13 +111,40 @@ Groups: ## Media + limits - Outbound text is chunked to `channels.signal.textChunkLimit` (default 4000). +- Optional newline chunking: set `channels.signal.chunkMode="newline"` to split on blank lines (paragraph boundaries) before length chunking. - Attachments supported (base64 fetched from `signal-cli`). - Default media cap: `channels.signal.mediaMaxMb` (default 8). - Use `channels.signal.ignoreAttachments` to skip downloading media. - Group history context uses `channels.signal.historyLimit` (or `channels.signal.accounts.*.historyLimit`), falling back to `messages.groupChat.historyLimit`. Set `0` to disable (default 50). +## Typing + read receipts +- **Typing indicators**: Clawdbot sends typing signals via `signal-cli sendTyping` and refreshes them while a reply is running. +- **Read receipts**: when `channels.signal.sendReadReceipts` is true, Clawdbot forwards read receipts for allowed DMs. +- Signal-cli does not expose read receipts for groups. + +## Reactions (message tool) +- Use `message action=react` with `channel=signal`. +- Targets: sender E.164 or UUID (use `uuid:` from pairing output; bare UUID works too). +- `messageId` is the Signal timestamp for the message you’re reacting to. +- Group reactions require `targetAuthor` or `targetAuthorUuid`. + +Examples: +``` +message action=react channel=signal target=uuid:123e4567-e89b-12d3-a456-426614174000 messageId=1737630212345 emoji=🔥 +message action=react channel=signal target=+15551234567 messageId=1737630212345 emoji=🔥 remove=true +message action=react channel=signal target=signal:group: targetAuthor=uuid: messageId=1737630212345 emoji=✅ +``` + +Config: +- `channels.signal.actions.reactions`: enable/disable reaction actions (default true). +- `channels.signal.reactionLevel`: `off | ack | minimal | extensive`. + - `off`/`ack` disables agent reactions (message tool `react` will error). + - `minimal`/`extensive` enables agent reactions and sets the guidance level. +- Per-account overrides: `channels.signal.accounts..actions.reactions`, `channels.signal.accounts..reactionLevel`. + ## Delivery targets (CLI/cron) - DMs: `signal:+15551234567` (or plain E.164). +- UUID DMs: `uuid:` (or bare UUID). - Groups: `signal:group:`. - Usernames: `username:` (if supported by your Signal account). @@ -115,17 +158,19 @@ Provider options: - `channels.signal.httpUrl`: full daemon URL (overrides host/port). - `channels.signal.httpHost`, `channels.signal.httpPort`: daemon bind (default 127.0.0.1:8080). - `channels.signal.autoStart`: auto-spawn daemon (default true if `httpUrl` unset). +- `channels.signal.startupTimeoutMs`: startup wait timeout in ms (cap 120000). - `channels.signal.receiveMode`: `on-start | manual`. - `channels.signal.ignoreAttachments`: skip attachment downloads. - `channels.signal.ignoreStories`: ignore stories from the daemon. - `channels.signal.sendReadReceipts`: forward read receipts. - `channels.signal.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing). -- `channels.signal.allowFrom`: DM allowlist (E.164 or `uuid:`). `open` requires `"*"`. +- `channels.signal.allowFrom`: DM allowlist (E.164 or `uuid:`). `open` requires `"*"`. Signal has no usernames; use phone/UUID ids. - `channels.signal.groupPolicy`: `open | allowlist | disabled` (default: allowlist). - `channels.signal.groupAllowFrom`: group sender allowlist. - `channels.signal.historyLimit`: max group messages to include as context (0 disables). - `channels.signal.dmHistoryLimit`: DM history limit in user turns. Per-user overrides: `channels.signal.dms[""].historyLimit`. - `channels.signal.textChunkLimit`: outbound chunk size (chars). +- `channels.signal.chunkMode`: `length` (default) or `newline` to split on blank lines (paragraph boundaries) before length chunking. - `channels.signal.mediaMaxMb`: inbound/outbound media cap (MB). Related global options: diff --git a/docs/channels/slack.md b/docs/channels/slack.md index aabe7ac6b..5f768db0e 100644 --- a/docs/channels/slack.md +++ b/docs/channels/slack.md @@ -1,11 +1,13 @@ --- -summary: "Slack socket mode setup and Clawdbot config" -read_when: "Setting up Slack or debugging Slack socket mode" +summary: "Slack setup for socket or HTTP webhook mode" +read_when: "Setting up Slack or debugging Slack socket/HTTP mode" --- -# Slack (socket mode) +# Slack -## Quick setup (beginner) +## Socket mode (default) + +### Quick setup (beginner) 1) Create a Slack app and enable **Socket Mode**. 2) Create an **App Token** (`xapp-...`) and **Bot Token** (`xoxb-...`). 3) Set tokens for Clawdbot and start the gateway. @@ -23,8 +25,8 @@ Minimal config: } ``` -## Setup -1) Create a Slack app (From scratch) in https://api.channels.slack.com/apps. +### Setup +1) Create a Slack app (From scratch) in https://api.slack.com/apps. 2) **Socket Mode** → toggle on. Then go to **Basic Information** → **App-Level Tokens** → **Generate Token and Scopes** with scope `connections:write`. Copy the **App Token** (`xapp-...`). 3) **OAuth & Permissions** → add bot token scopes (use the manifest below). Click **Install to Workspace**. Copy the **Bot User OAuth Token** (`xoxb-...`). 4) Optional: **OAuth & Permissions** → add **User Token Scopes** (see the read-only list below). Reinstall the app and copy the **User OAuth Token** (`xoxp-...`). @@ -43,7 +45,7 @@ Use the manifest below so scopes and events stay in sync. Multi-account support: use `channels.slack.accounts` with per-account tokens and optional `name`. See [`gateway/configuration`](/gateway/configuration#telegramaccounts--discordaccounts--slackaccounts--signalaccounts--imessageaccounts) for the shared pattern. -## Clawdbot config (minimal) +### Clawdbot config (minimal) Set tokens via env vars (recommended): - `SLACK_APP_TOKEN=xapp-...` @@ -63,7 +65,7 @@ Or via config: } ``` -## User token (optional) +### User token (optional) Clawdbot can use a Slack user token (`xoxp-...`) for read operations (history, pins, reactions, emoji, member info). By default this stays read-only: reads prefer the user token when present, and writes still use the bot token unless @@ -102,18 +104,51 @@ Example with userTokenReadOnly explicitly set (allow user token writes): } ``` -### Token usage +#### Token usage - Read operations (history, reactions list, pins list, emoji list, member info, search) prefer the user token when configured, otherwise the bot token. - Write operations (send/edit/delete messages, add/remove reactions, pin/unpin, file uploads) use the bot token by default. If `userTokenReadOnly: false` and no bot token is available, Clawdbot falls back to the user token. -## History context +### History context - `channels.slack.historyLimit` (or `channels.slack.accounts.*.historyLimit`) controls how many recent channel/group messages are wrapped into the prompt. - Falls back to `messages.groupChat.historyLimit`. Set `0` to disable (default 50). -## Manifest (optional) +## HTTP mode (Events API) +Use HTTP webhook mode when your Gateway is reachable by Slack over HTTPS (typical for server deployments). +HTTP mode uses the Events API + Interactivity + Slash Commands with a shared request URL. + +### Setup +1) Create a Slack app and **disable Socket Mode** (optional if you only use HTTP). +2) **Basic Information** → copy the **Signing Secret**. +3) **OAuth & Permissions** → install the app and copy the **Bot User OAuth Token** (`xoxb-...`). +4) **Event Subscriptions** → enable events and set the **Request URL** to your gateway webhook path (default `/slack/events`). +5) **Interactivity & Shortcuts** → enable and set the same **Request URL**. +6) **Slash Commands** → set the same **Request URL** for your command(s). + +Example request URL: +`https://gateway-host/slack/events` + +### Clawdbot config (minimal) +```json5 +{ + channels: { + slack: { + enabled: true, + mode: "http", + botToken: "xoxb-...", + signingSecret: "your-signing-secret", + webhookPath: "/slack/events" + } + } +} +``` + +Multi-account HTTP mode: set `channels.slack.accounts..mode = "http"` and provide a unique +`webhookPath` per account so each Slack app can point to its own URL. + +### Manifest (optional) Use this Slack app manifest to create the app quickly (adjust the name/command if you want). Include the user scopes if you plan to configure a user token. @@ -210,29 +245,29 @@ If you enable native commands, add one `slash_commands` entry per command you wa ## Scopes (current vs optional) Slack's Conversations API is type-scoped: you only need the scopes for the conversation types you actually touch (channels, groups, im, mpim). See -https://api.channels.slack.com/docs/conversations-api for the overview. +https://docs.slack.dev/apis/web-api/using-the-conversations-api/ for the overview. ### Bot token scopes (required) - `chat:write` (send/update/delete messages via `chat.postMessage`) - https://api.channels.slack.com/methods/chat.postMessage + https://docs.slack.dev/reference/methods/chat.postMessage - `im:write` (open DMs via `conversations.open` for user DMs) - https://api.channels.slack.com/methods/conversations.open + https://docs.slack.dev/reference/methods/conversations.open - `channels:history`, `groups:history`, `im:history`, `mpim:history` - https://api.channels.slack.com/methods/conversations.history + https://docs.slack.dev/reference/methods/conversations.history - `channels:read`, `groups:read`, `im:read`, `mpim:read` - https://api.channels.slack.com/methods/conversations.info + https://docs.slack.dev/reference/methods/conversations.info - `users:read` (user lookup) - https://api.channels.slack.com/methods/users.info + https://docs.slack.dev/reference/methods/users.info - `reactions:read`, `reactions:write` (`reactions.get` / `reactions.add`) - https://api.channels.slack.com/methods/reactions.get - https://api.channels.slack.com/methods/reactions.add + https://docs.slack.dev/reference/methods/reactions.get + https://docs.slack.dev/reference/methods/reactions.add - `pins:read`, `pins:write` (`pins.list` / `pins.add` / `pins.remove`) - https://api.channels.slack.com/scopes/pins:read - https://api.channels.slack.com/scopes/pins:write + https://docs.slack.dev/reference/scopes/pins.read + https://docs.slack.dev/reference/scopes/pins.write - `emoji:read` (`emoji.list`) - https://api.channels.slack.com/scopes/emoji:read + https://docs.slack.dev/reference/scopes/emoji.read - `files:write` (uploads via `files.uploadV2`) - https://api.channels.slack.com/messaging/files/uploading + https://docs.slack.dev/messaging/working-with-files/#upload ### User token scopes (optional, read-only by default) Add these under **User Token Scopes** if you configure `channels.slack.userToken`. @@ -249,9 +284,9 @@ Add these under **User Token Scopes** if you configure `channels.slack.userToken - `mpim:write` (only if we add group-DM open/DM start via `conversations.open`) - `groups:write` (only if we add private-channel management: create/rename/invite/archive) - `chat:write.public` (only if we want to post to channels the bot isn't in) - https://api.channels.slack.com/scopes/chat:write.public + https://docs.slack.dev/reference/scopes/chat.write.public - `users:read.email` (only if we need email fields from `users.info`) - https://api.channels.slack.com/changelog/2017-04-narrowing-email-access + https://docs.slack.dev/changelog/2017-04-narrowing-email-access - `files:read` (only if we start listing/reading file metadata) ## Config @@ -269,7 +304,8 @@ Slack uses Socket Mode only (no HTTP webhook server). Provide both tokens: "policy": "pairing", "allowFrom": ["U123", "U456", "*"], "groupEnabled": false, - "groupChannels": ["G123"] + "groupChannels": ["G123"], + "replyToMode": "all" }, "channels": { "C123": { "allow": true, "requireMention": true }, @@ -313,6 +349,7 @@ ack reaction after the bot replies. ## Limits - Outbound text is chunked to `channels.slack.textChunkLimit` (default 4000). +- Optional newline chunking: set `channels.slack.chunkMode="newline"` to split on blank lines (paragraph boundaries) before length chunking. - Media uploads are capped by `channels.slack.mediaMaxMb` (default 20). ## Reply threading @@ -326,6 +363,73 @@ By default, Clawdbot replies in the main channel. Use `channels.slack.replyToMod The mode applies to both auto-replies and agent tool calls (`slack sendMessage`). +### Per-chat-type threading +You can configure different threading behavior per chat type by setting `channels.slack.replyToModeByChatType`: + +```json5 +{ + channels: { + slack: { + replyToMode: "off", // default for channels + replyToModeByChatType: { + direct: "all", // DMs always thread + group: "first" // group DMs/MPIM thread first reply + }, + } + } +} +``` + +Supported chat types: +- `direct`: 1:1 DMs (Slack `im`) +- `group`: group DMs / MPIMs (Slack `mpim`) +- `channel`: standard channels (public/private) + +Precedence: +1) `replyToModeByChatType.` +2) `replyToMode` +3) Provider default (`off`) + +Legacy `channels.slack.dm.replyToMode` is still accepted as a fallback for `direct` when no chat-type override is set. + +Examples: + +Thread DMs only: +```json5 +{ + channels: { + slack: { + replyToMode: "off", + replyToModeByChatType: { direct: "all" } + } + } +} +``` + +Thread group DMs but keep channels in the root: +```json5 +{ + channels: { + slack: { + replyToMode: "off", + replyToModeByChatType: { group: "first" } + } + } +} +``` + +Make channels thread, keep DMs in the root: +```json5 +{ + channels: { + slack: { + replyToMode: "first", + replyToModeByChatType: { direct: "off", group: "off" } + } + } +} +``` + ### Manual threading tags For fine-grained control, use these tags in agent responses: - `[[reply_to_current]]` — reply to the triggering message (start/continue thread). @@ -335,6 +439,7 @@ For fine-grained control, use these tags in agent responses: - DMs share the `main` session (like WhatsApp/Telegram). - Channels map to `agent::slack:channel:` sessions. - Slash commands use `agent::slack:slash:` sessions (prefix configurable via `channels.slack.slashCommand.sessionPrefix`). +- If Slack doesn’t provide `channel_type`, Clawdbot infers it from the channel ID prefix (`D`, `C`, `G`) and defaults to `channel` to keep session keys stable. - Native command registration uses `commands.native` (global default `"auto"` → Slack off) and can be overridden per-workspace with `channels.slack.commands.native`. Text commands require standalone `/...` messages and can be disabled with `commands.text: false`. Slack slash commands are managed in the Slack app and are not removed automatically. Use `commands.useAccessGroups: false` to bypass access-group checks for commands. - Full command list + config: [Slash commands](/tools/slash-commands) @@ -342,10 +447,19 @@ For fine-grained control, use these tags in agent responses: - Default: `channels.slack.dm.policy="pairing"` — unknown DM senders get a pairing code (expires after 1 hour). - Approve via: `clawdbot pairing approve slack `. - To allow anyone: set `channels.slack.dm.policy="open"` and `channels.slack.dm.allowFrom=["*"]`. +- `channels.slack.dm.allowFrom` accepts user IDs, @handles, or emails (resolved at startup when tokens allow). The wizard accepts usernames and resolves them to ids during setup when tokens allow. ## Group policy - `channels.slack.groupPolicy` controls channel handling (`open|disabled|allowlist`). - `allowlist` requires channels to be listed in `channels.slack.channels`. + - If you only set `SLACK_BOT_TOKEN`/`SLACK_APP_TOKEN` and never create a `channels.slack` section, + the runtime defaults `groupPolicy` to `open`. Add `channels.slack.groupPolicy`, + `channels.defaults.groupPolicy`, or a channel allowlist to lock it down. + - The configure wizard accepts `#channel` names and resolves them to IDs when possible + (public + private); if multiple matches exist, it prefers the active channel. + - On startup, Clawdbot resolves channel/user names in allowlists to IDs (when tokens allow) + and logs the mapping; unresolved entries are kept as typed. + - To allow **no channels**, set `channels.slack.groupPolicy: "disabled"` (or keep an empty allowlist). Channel options (`channels.slack.channels.` or `channels.slack.channels.`): - `allow`: allow/deny the channel when `groupPolicy="allowlist"`. diff --git a/docs/channels/telegram.md b/docs/channels/telegram.md index a437d933a..e708e2e64 100644 --- a/docs/channels/telegram.md +++ b/docs/channels/telegram.md @@ -13,6 +13,7 @@ Status: production-ready for bot DMs + groups via grammY. Long-polling by defaul 2) Set the token: - Env: `TELEGRAM_BOT_TOKEN=...` - Or config: `channels.telegram.botToken: "..."`. + - If both are set, config takes precedence (env fallback is default-account only). 3) Start the gateway. 4) DM access is pairing by default; approve the pairing code on first contact. @@ -61,10 +62,11 @@ Example: ``` Env option: `TELEGRAM_BOT_TOKEN=...` (works for the default account). +If both env and config are set, config takes precedence. Multi-account support: use `channels.telegram.accounts` with per-account tokens and optional `name`. See [`gateway/configuration`](/gateway/configuration#telegramaccounts--discordaccounts--slackaccounts--signalaccounts--imessageaccounts) for the shared pattern. -3) Start the gateway. Telegram starts when a token is resolved (env or config). +3) Start the gateway. Telegram starts when a token is resolved (config first, env fallback). 4) DM access defaults to pairing. Approve the code when the bot is first contacted. 5) For groups: add the bot, decide privacy/admin behavior (below), then set `channels.telegram.groups` to control mention gating + allowlists. @@ -118,6 +120,13 @@ You can add custom commands to the menu via config: } ``` +## Troubleshooting + +- `setMyCommands failed` in logs usually means outbound HTTPS/DNS is blocked to `api.telegram.org`. +- If you see `sendMessage` or `sendChatAction` failures, check IPv6 routing and DNS. + +More help: [Channel troubleshooting](/channels/troubleshooting). + Notes: - Custom commands are **menu entries only**; Clawdbot does not implement them unless you handle them elsewhere. - Command names are normalized (leading `/` stripped, lowercased) and must match `a-z`, `0-9`, `_` (1–32 chars). @@ -126,6 +135,7 @@ Notes: ## Limits - Outbound text is chunked to `channels.telegram.textChunkLimit` (default 4000). +- Optional newline chunking: set `channels.telegram.chunkMode="newline"` to split on blank lines (paragraph boundaries) before length chunking. - Media downloads/uploads are capped by `channels.telegram.mediaMaxMb` (default 5). - Telegram Bot API requests time out after `channels.telegram.timeoutSeconds` (default 500 via grammY). Set lower to avoid long hangs. - Group history context uses `channels.telegram.historyLimit` (or `channels.telegram.accounts.*.historyLimit`), falling back to `messages.groupChat.historyLimit`. Set `0` to disable (default 50). @@ -150,6 +160,7 @@ By default, the bot only responds to mentions in groups (`@botname` or patterns ``` **Important:** Setting `channels.telegram.groups` creates an **allowlist** - only listed groups (or `"*"`) will be accepted. +Forum topics inherit their parent group config (allowFrom, requireMention, skills, prompts) unless you add per-topic overrides under `channels.telegram.groups..topics.`. To allow all groups with always-respond: ```json5 @@ -214,18 +225,21 @@ Telegram forum topics include a `message_thread_id` per message. Clawdbot: - General topic (thread id `1`) is special: message sends omit `message_thread_id` (Telegram rejects it), but typing indicators still include it. - Exposes `MessageThreadId` + `IsForum` in template context for routing/templating. - Topic-specific configuration is available under `channels.telegram.groups..topics.` (skills, allowlists, auto-reply, system prompts, disable). +- Topic configs inherit group settings (requireMention, allowlists, skills, prompts, enabled) unless overridden per topic. Private chats can include `message_thread_id` in some edge cases. Clawdbot keeps the DM session key unchanged, but still uses the thread id for replies/draft streaming when it is present. ## Inline Buttons -Telegram supports inline keyboards with callback buttons. Enable this feature via capabilities: +Telegram supports inline keyboards with callback buttons. ```json5 { "channels": { "telegram": { - "capabilities": ["inlineButtons"] + "capabilities": { + "inlineButtons": "allowlist" + } } } } @@ -238,7 +252,9 @@ For per-account configuration: "telegram": { "accounts": { "main": { - "capabilities": ["inlineButtons"] + "capabilities": { + "inlineButtons": "allowlist" + } } } } @@ -246,6 +262,16 @@ For per-account configuration: } ``` +Scopes: +- `off` — inline buttons disabled +- `dm` — only DMs (group targets blocked) +- `group` — only groups (DM targets blocked) +- `all` — DMs + groups +- `allowlist` — DMs + groups, but only senders allowed by `allowFrom`/`groupAllowFrom` (same rules as control commands) + +Default: `allowlist`. +Legacy: `capabilities: ["inlineButtons"]` = `inlineButtons: "all"`. + ### Sending buttons Use the message tool with the `buttons` parameter: @@ -273,12 +299,12 @@ When a user clicks a button, the callback data is sent back to the agent as a me ### Configuration options -Telegram capabilities can be configured at two levels: +Telegram capabilities can be configured at two levels (object form shown above; legacy string arrays still supported): -- `channels.telegram.capabilities`: Global default capability list applied to all Telegram accounts unless overridden. -- `channels.telegram.accounts..capabilities`: Per-account capabilities that override or extend the global defaults for that specific account. +- `channels.telegram.capabilities`: Global default capability config applied to all Telegram accounts unless overridden. +- `channels.telegram.accounts..capabilities`: Per-account capabilities that override the global defaults for that specific account. -Use the global setting when all Telegram bots/accounts should behave the same. Use per-account configuration when different bots need different behaviors (for example, one account only handles DMs while another is allowed in groups or has extra capabilities). +Use the global setting when all Telegram bots/accounts should behave the same. Use per-account configuration when different bots need different behaviors (for example, one account only handles DMs while another is allowed in groups). ## Access control (DMs + groups) ### DM access @@ -287,7 +313,7 @@ Use the global setting when all Telegram bots/accounts should behave the same. U - `clawdbot pairing list telegram` - `clawdbot pairing approve telegram ` - Pairing is the default token exchange used for Telegram DMs. Details: [Pairing](/start/pairing) -- `channels.telegram.allowFrom` accepts numeric user IDs (recommended) or `@username` entries. It is **not** the bot username; use the human sender’s ID. +- `channels.telegram.allowFrom` accepts numeric user IDs (recommended) or `@username` entries. It is **not** the bot username; use the human sender’s ID. The wizard accepts `@username` and resolves it to the numeric ID when possible. #### Finding your Telegram user ID Safer (no third-party bot): @@ -344,6 +370,19 @@ To force a voice note bubble in agent replies, include this tag anywhere in the The tag is stripped from the delivered text. Other channels ignore this tag. +For message tool sends, set `asVoice: true` with a voice-compatible audio `media` URL +(`message` is optional when media is present): + +```json5 +{ + "action": "send", + "channel": "telegram", + "to": "123456789", + "media": "https://example.com/voice.ogg", + "asVoice": true +} +``` + ## Streaming (drafts) Telegram can stream **draft bubbles** while the agent is generating a response. Clawdbot uses Bot API `sendMessageDraft` (not real messages) and then sends the @@ -397,8 +436,8 @@ The agent sees reactions as **system notifications** in the conversation history **Configuration:** - `channels.telegram.reactionNotifications`: Controls which reactions trigger notifications - - `"off"` — ignore all reactions (default when not set) - - `"own"` — notify when users react to bot messages (best-effort; in-memory) + - `"off"` — ignore all reactions + - `"own"` — notify when users react to bot messages (best-effort; in-memory) (default) - `"all"` — notify for all reactions - `channels.telegram.reactionLevel`: Controls agent's reaction capability @@ -428,7 +467,7 @@ The agent sees reactions as **system notifications** in the conversation history ## Delivery targets (CLI/cron) - Use a chat id (`123456789`) or a username (`@name`) as the target. -- Example: `clawdbot message send --channel telegram --to 123456789 --message "hi"`. +- Example: `clawdbot message send --channel telegram --target 123456789 --message "hi"`. ## Troubleshooting @@ -453,6 +492,10 @@ The agent sees reactions as **system notifications** in the conversation history - Make sure your Telegram user ID is authorized (via pairing or `channels.telegram.allowFrom`) - Commands require authorization even in groups with `groupPolicy: "open"` +**Long-polling aborts immediately on Node 22+ (often with proxies/custom fetch):** +- Node 22+ is stricter about `AbortSignal` instances; foreign signals can abort `fetch` calls right away. +- Upgrade to a Clawdbot build that normalizes abort signals, or run the gateway on Node 20 until you can upgrade. + **Bot starts, then silently stops responding (or logs `HttpError: Network request ... failed`):** - Some hosts resolve `api.telegram.org` to IPv6 first. If your server does not have working IPv6 egress, grammY can get stuck on IPv6-only requests. - Fix by enabling IPv6 egress **or** forcing IPv4 resolution for `api.telegram.org` (for example, add an `/etc/hosts` entry using the IPv4 A record, or prefer IPv4 in your OS DNS stack), then restart the gateway. @@ -477,10 +520,12 @@ Provider options: - `channels.telegram.groups..enabled`: disable the group when `false`. - `channels.telegram.groups..topics..*`: per-topic overrides (same fields as group). - `channels.telegram.groups..topics..requireMention`: per-topic mention gating override. -- `channels.telegram.capabilities`: Enable channel features (e.g., "inlineButtons"). -- `channels.telegram.accounts..capabilities`: Per-account capabilities. +- `channels.telegram.capabilities.inlineButtons`: `off | dm | group | all | allowlist` (default: allowlist). +- `channels.telegram.accounts..capabilities.inlineButtons`: per-account override. - `channels.telegram.replyToMode`: `off | first | all` (default: `first`). - `channels.telegram.textChunkLimit`: outbound chunk size (chars). +- `channels.telegram.chunkMode`: `length` (default) or `newline` to split on blank lines (paragraph boundaries) before length chunking. +- `channels.telegram.linkPreview`: toggle link previews for outbound messages (default: true). - `channels.telegram.streamMode`: `off | partial | block` (draft streaming). - `channels.telegram.mediaMaxMb`: inbound/outbound media cap (MB). - `channels.telegram.retry`: retry policy for outbound Telegram API calls (attempts, minDelayMs, maxDelayMs, jitter). @@ -491,8 +536,8 @@ Provider options: - `channels.telegram.actions.reactions`: gate Telegram tool reactions. - `channels.telegram.actions.sendMessage`: gate Telegram tool message sends. - `channels.telegram.actions.deleteMessage`: gate Telegram tool message deletes. -- `channels.telegram.reactionNotifications`: `off | own | all` — control which reactions trigger system events (default: `off` when not set). -- `channels.telegram.reactionLevel`: `off | ack | minimal | extensive` — control agent's reaction capability (default: `ack` when not set). +- `channels.telegram.reactionNotifications`: `off | own | all` — control which reactions trigger system events (default: `own` when not set). +- `channels.telegram.reactionLevel`: `off | ack | minimal | extensive` — control agent's reaction capability (default: `minimal` when not set). Related global options: - `agents.list[].groupChat.mentionPatterns` (mention gating patterns). diff --git a/docs/channels/tlon.md b/docs/channels/tlon.md new file mode 100644 index 000000000..a2436d5e7 --- /dev/null +++ b/docs/channels/tlon.md @@ -0,0 +1,133 @@ +--- +summary: "Tlon/Urbit support status, capabilities, and configuration" +read_when: + - Working on Tlon/Urbit channel features +--- +# Tlon (plugin) + +Tlon is a decentralized messenger built on Urbit. Clawdbot connects to your Urbit ship and can +respond to DMs and group chat messages. Group replies require an @ mention by default and can +be further restricted via allowlists. + +Status: supported via plugin. DMs, group mentions, thread replies, and text-only media fallback +(URL appended to caption). Reactions, polls, and native media uploads are not supported. + +## Plugin required + +Tlon ships as a plugin and is not bundled with the core install. + +Install via CLI (npm registry): + +```bash +clawdbot plugins install @clawdbot/tlon +``` + +Local checkout (when running from a git repo): + +```bash +clawdbot plugins install ./extensions/tlon +``` + +Details: [Plugins](/plugin) + +## Setup + +1) Install the Tlon plugin. +2) Gather your ship URL and login code. +3) Configure `channels.tlon`. +4) Restart the gateway. +5) DM the bot or mention it in a group channel. + +Minimal config (single account): + +```json5 +{ + channels: { + tlon: { + enabled: true, + ship: "~sampel-palnet", + url: "https://your-ship-host", + code: "lidlut-tabwed-pillex-ridrup" + } + } +} +``` + +## Group channels + +Auto-discovery is enabled by default. You can also pin channels manually: + +```json5 +{ + channels: { + tlon: { + groupChannels: [ + "chat/~host-ship/general", + "chat/~host-ship/support" + ] + } + } +} +``` + +Disable auto-discovery: + +```json5 +{ + channels: { + tlon: { + autoDiscoverChannels: false + } + } +} +``` + +## Access control + +DM allowlist (empty = allow all): + +```json5 +{ + channels: { + tlon: { + dmAllowlist: ["~zod", "~nec"] + } + } +} +``` + +Group authorization (restricted by default): + +```json5 +{ + channels: { + tlon: { + defaultAuthorizedShips: ["~zod"], + authorization: { + channelRules: { + "chat/~host-ship/general": { + mode: "restricted", + allowedShips: ["~zod", "~nec"] + }, + "chat/~host-ship/announcements": { + mode: "open" + } + } + } + } + } +} +``` + +## Delivery targets (CLI/cron) + +Use these with `clawdbot message send` or cron delivery: + +- DM: `~sampel-palnet` or `dm/~sampel-palnet` +- Group: `chat/~host-ship/channel` or `group:~host-ship/channel` + +## Notes + +- Group replies require a mention (e.g. `~your-bot-ship`) to respond. +- Thread replies: if the inbound message is in a thread, Clawdbot replies in-thread. +- Media: `sendMedia` falls back to text + URL (no native upload). diff --git a/docs/channels/troubleshooting.md b/docs/channels/troubleshooting.md index 6eed5265d..a62f9e27e 100644 --- a/docs/channels/troubleshooting.md +++ b/docs/channels/troubleshooting.md @@ -22,3 +22,4 @@ clawdbot channels status --probe ## Telegram quick fixes - Logs show `HttpError: Network request for 'sendMessage' failed` or `sendChatAction` → check IPv6 DNS. If `api.telegram.org` resolves to IPv6 first and the host lacks IPv6 egress, force IPv4 or enable IPv6. See [/channels/telegram#troubleshooting](/channels/telegram#troubleshooting). +- Logs show `setMyCommands failed` → check outbound HTTPS and DNS reachability to `api.telegram.org` (common on locked-down VPS or proxies). diff --git a/docs/channels/whatsapp.md b/docs/channels/whatsapp.md index 97b089981..4759cf4c9 100644 --- a/docs/channels/whatsapp.md +++ b/docs/channels/whatsapp.md @@ -82,15 +82,13 @@ When the wizard asks for your personal WhatsApp number, enter the phone you will "selfChatMode": true, "dmPolicy": "allowlist", "allowFrom": ["+15551234567"] - }, - "messages": { - "responsePrefix": "[clawdbot]" } } ``` -Tip: set `messages.responsePrefix` explicitly if you want a consistent bot prefix -on outbound replies. +Self-chat replies default to `[{identity.name}]` when set (otherwise `[clawdbot]`) +if `messages.responsePrefix` is unset. Set it explicitly to customize or disable +the prefix (use `""` to remove it). ### Number sourcing tips - **Local eSIM** from your country's mobile carrier (most reliable) @@ -204,9 +202,9 @@ The wizard uses it to set your **allowlist/owner** so your own DMs are permitted - `always`: always triggers. - `/activation mention|always` is owner-only and must be sent as a standalone message. - Owner = `channels.whatsapp.allowFrom` (or self E.164 if unset). -- **History injection**: - - Recent messages (default 50) inserted under: - `[Chat messages since your last reply - for context]` +- **History injection** (pending-only): + - Recent *unprocessed* messages (default 50) inserted under: + `[Chat messages since your last reply - for context]` (messages already in the session are not re-injected) - Current message under: `[Current message - respond to this]` - Sender suffix appended: `[from: Name (+E164)]` @@ -273,12 +271,13 @@ WhatsApp can automatically send emoji reactions to incoming messages immediately ## Limits - Outbound text is chunked to `channels.whatsapp.textChunkLimit` (default 4000). +- Optional newline chunking: set `channels.whatsapp.chunkMode="newline"` to split on blank lines (paragraph boundaries) before length chunking. - Inbound media saves are capped by `channels.whatsapp.mediaMaxMb` (default 50 MB). - Outbound media items are capped by `agents.defaults.mediaMaxMb` (default 5 MB). ## Outbound send (text + media) - Uses active web listener; error if gateway not running. -- Text chunking: 4k max per message (configurable via `channels.whatsapp.textChunkLimit`). +- Text chunking: 4k max per message (configurable via `channels.whatsapp.textChunkLimit`, optional `channels.whatsapp.chunkMode`). - Media: - Image/video/audio/document supported. - Audio sent as PTT; `audio/ogg` => `audio/ogg; codecs=opus`. @@ -288,6 +287,11 @@ WhatsApp can automatically send emoji reactions to incoming messages immediately - CLI: `clawdbot message send --media --gif-playback` - Gateway: `send` params include `gifPlayback: true` +## Voice notes (PTT audio) +WhatsApp sends audio as **voice notes** (PTT bubble). +- Best results: OGG/Opus. Clawdbot rewrites `audio/ogg` to `audio/ogg; codecs=opus`. +- `[[audio_as_voice]]` is ignored for WhatsApp (audio already ships as voice note). + ## Media limits + optimization - Default outbound cap: 5 MB (per media item). - Override: `agents.defaults.mediaMaxMb`. @@ -310,7 +314,7 @@ WhatsApp can automatically send emoji reactions to incoming messages immediately ## Config quick map - `channels.whatsapp.dmPolicy` (DM policy: pairing/allowlist/open/disabled). - `channels.whatsapp.selfChatMode` (same-phone setup; bot uses your personal WhatsApp number). -- `channels.whatsapp.allowFrom` (DM allowlist). +- `channels.whatsapp.allowFrom` (DM allowlist). WhatsApp uses E.164 phone numbers (no usernames). - `channels.whatsapp.mediaMaxMb` (inbound media save cap). - `channels.whatsapp.ackReaction` (auto-reaction on message receipt: `{emoji, direct, group}`). - `channels.whatsapp.accounts..*` (per-account settings + optional `authDir`). @@ -331,6 +335,7 @@ WhatsApp can automatically send emoji reactions to incoming messages immediately - `agents.defaults.heartbeat.model` (optional override) - `agents.defaults.heartbeat.target` - `agents.defaults.heartbeat.to` +- `agents.defaults.heartbeat.session` - `agents.list[].heartbeat.*` (per-agent overrides) - `session.*` (scope, idle, store, mainKey) - `web.enabled` (disable channel startup when false) diff --git a/docs/channels/zalo.md b/docs/channels/zalo.md index b4d23bcf1..55f2d5104 100644 --- a/docs/channels/zalo.md +++ b/docs/channels/zalo.md @@ -92,7 +92,7 @@ Multi-account support: use `channels.zalo.accounts` with per-account tokens and - `clawdbot pairing list zalo` - `clawdbot pairing approve zalo ` - Pairing is the default token exchange. Details: [Pairing](/start/pairing) -- `channels.zalo.allowFrom` accepts numeric user IDs. +- `channels.zalo.allowFrom` accepts numeric user IDs (no username lookup available). ## Long-polling vs webhook - Default: long-polling (no public URL required). @@ -124,7 +124,7 @@ Multi-account support: use `channels.zalo.accounts` with per-account tokens and ## Delivery targets (CLI/cron) - Use a chat id as the target. -- Example: `clawdbot message send --channel zalo --to 123456789 --message "hi"`. +- Example: `clawdbot message send --channel zalo --target 123456789 --message "hi"`. ## Troubleshooting @@ -147,7 +147,7 @@ Provider options: - `channels.zalo.botToken`: bot token from Zalo Bot Platform. - `channels.zalo.tokenFile`: read token from file path. - `channels.zalo.dmPolicy`: `pairing | allowlist | open | disabled` (default: pairing). -- `channels.zalo.allowFrom`: DM allowlist (user IDs). `open` requires `"*"`. +- `channels.zalo.allowFrom`: DM allowlist (user IDs). `open` requires `"*"`. The wizard will ask for numeric IDs. - `channels.zalo.mediaMaxMb`: inbound/outbound media cap (MB, default 5). - `channels.zalo.webhookUrl`: enable webhook mode (HTTPS required). - `channels.zalo.webhookSecret`: webhook secret (8-256 chars). diff --git a/docs/channels/zalouser.md b/docs/channels/zalouser.md new file mode 100644 index 000000000..004a9d223 --- /dev/null +++ b/docs/channels/zalouser.md @@ -0,0 +1,123 @@ +--- +summary: "Zalo personal account support via zca-cli (QR login), capabilities, and configuration" +read_when: + - Setting up Zalo Personal for Clawdbot + - Debugging Zalo Personal login or message flow +--- +# Zalo Personal (unofficial) + +Status: experimental. This integration automates a **personal Zalo account** via `zca-cli`. + +> **Warning:** This is an unofficial integration and may result in account suspension/ban. Use at your own risk. + +## Plugin required +Zalo Personal ships as a plugin and is not bundled with the core install. +- Install via CLI: `clawdbot plugins install @clawdbot/zalouser` +- Or from a source checkout: `clawdbot plugins install ./extensions/zalouser` +- Details: [Plugins](/plugin) + +## Prerequisite: zca-cli +The Gateway machine must have the `zca` binary available in `PATH`. + +- Verify: `zca --version` +- If missing, install zca-cli (see `extensions/zalouser/README.md` or the upstream zca-cli docs). + +## Quick setup (beginner) +1) Install the plugin (see above). +2) Login (QR, on the Gateway machine): + - `clawdbot channels login --channel zalouser` + - Scan the QR code in the terminal with the Zalo mobile app. +3) Enable the channel: + +```json5 +{ + channels: { + zalouser: { + enabled: true, + dmPolicy: "pairing" + } + } +} +``` + +4) Restart the Gateway (or finish onboarding). +5) DM access defaults to pairing; approve the pairing code on first contact. + +## What it is +- Uses `zca listen` to receive inbound messages. +- Uses `zca msg ...` to send replies (text/media/link). +- Designed for “personal account” use cases where Zalo Bot API is not available. + +## Naming +Channel id is `zalouser` to make it explicit this automates a **personal Zalo user account** (unofficial). We keep `zalo` reserved for a potential future official Zalo API integration. + +## Finding IDs (directory) +Use the directory CLI to discover peers/groups and their IDs: + +```bash +clawdbot directory self --channel zalouser +clawdbot directory peers list --channel zalouser --query "name" +clawdbot directory groups list --channel zalouser --query "work" +``` + +## Limits +- Outbound text is chunked to ~2000 characters (Zalo client limits). +- Streaming is blocked by default. + +## Access control (DMs) +`channels.zalouser.dmPolicy` supports: `pairing | allowlist | open | disabled` (default: `pairing`). +`channels.zalouser.allowFrom` accepts user IDs or names. The wizard resolves names to IDs via `zca friend find` when available. + +Approve via: +- `clawdbot pairing list zalouser` +- `clawdbot pairing approve zalouser ` + +## Group access (optional) +- Default: `channels.zalouser.groupPolicy = "open"` (groups allowed). Use `channels.defaults.groupPolicy` to override the default when unset. +- Restrict to an allowlist with: + - `channels.zalouser.groupPolicy = "allowlist"` + - `channels.zalouser.groups` (keys are group IDs or names) +- Block all groups: `channels.zalouser.groupPolicy = "disabled"`. +- The configure wizard can prompt for group allowlists. +- On startup, Clawdbot resolves group/user names in allowlists to IDs and logs the mapping; unresolved entries are kept as typed. + +Example: +```json5 +{ + channels: { + zalouser: { + groupPolicy: "allowlist", + groups: { + "123456789": { allow: true }, + "Work Chat": { allow: true } + } + } + } +} +``` + +## Multi-account +Accounts map to zca profiles. Example: + +```json5 +{ + channels: { + zalouser: { + enabled: true, + defaultAccount: "default", + accounts: { + work: { enabled: true, profile: "work" } + } + } + } +} +``` + +## Troubleshooting + +**`zca` not found:** +- Install zca-cli and ensure it’s on `PATH` for the Gateway process. + +**Login doesn’t stick:** +- `clawdbot channels status --probe` +- Re-login: `clawdbot channels logout --channel zalouser && clawdbot channels login --channel zalouser` diff --git a/docs/cli/acp.md b/docs/cli/acp.md new file mode 100644 index 000000000..6e27416b3 --- /dev/null +++ b/docs/cli/acp.md @@ -0,0 +1,166 @@ +--- +summary: "Run the ACP bridge for IDE integrations" +read_when: + - Setting up ACP-based IDE integrations + - Debugging ACP session routing to the Gateway +--- + +# acp + +Run the ACP (Agent Client Protocol) bridge that talks to a Clawdbot Gateway. + +This command speaks ACP over stdio for IDEs and forwards prompts to the Gateway +over WebSocket. It keeps ACP sessions mapped to Gateway session keys. + +## Usage + +```bash +clawdbot acp + +# Remote Gateway +clawdbot acp --url wss://gateway-host:18789 --token + +# Attach to an existing session key +clawdbot acp --session agent:main:main + +# Attach by label (must already exist) +clawdbot acp --session-label "support inbox" + +# Reset the session key before the first prompt +clawdbot acp --session agent:main:main --reset-session +``` + +## ACP client (debug) + +Use the built-in ACP client to sanity-check the bridge without an IDE. +It spawns the ACP bridge and lets you type prompts interactively. + +```bash +clawdbot acp client + +# Point the spawned bridge at a remote Gateway +clawdbot acp client --server-args --url wss://gateway-host:18789 --token + +# Override the server command (default: clawdbot) +clawdbot acp client --server "node" --server-args dist/entry.js acp --url ws://127.0.0.1:19001 +``` + +## How to use this + +Use ACP when an IDE (or other client) speaks Agent Client Protocol and you want +it to drive a Clawdbot Gateway session. + +1. Ensure the Gateway is running (local or remote). +2. Configure the Gateway target (config or flags). +3. Point your IDE to run `clawdbot acp` over stdio. + +Example config (persisted): + +```bash +clawdbot config set gateway.remote.url wss://gateway-host:18789 +clawdbot config set gateway.remote.token +``` + +Example direct run (no config write): + +```bash +clawdbot acp --url wss://gateway-host:18789 --token +``` + +## Selecting agents + +ACP does not pick agents directly. It routes by the Gateway session key. + +Use agent-scoped session keys to target a specific agent: + +```bash +clawdbot acp --session agent:main:main +clawdbot acp --session agent:design:main +clawdbot acp --session agent:qa:bug-123 +``` + +Each ACP session maps to a single Gateway session key. One agent can have many +sessions; ACP defaults to an isolated `acp:` session unless you override +the key or label. + +## Zed editor setup + +Add a custom ACP agent in `~/.config/zed/settings.json` (or use Zed’s Settings UI): + +```json +{ + "agent_servers": { + "Clawdbot ACP": { + "type": "custom", + "command": "clawdbot", + "args": ["acp"], + "env": {} + } + } +} +``` + +To target a specific Gateway or agent: + +```json +{ + "agent_servers": { + "Clawdbot ACP": { + "type": "custom", + "command": "clawdbot", + "args": [ + "acp", + "--url", "wss://gateway-host:18789", + "--token", "", + "--session", "agent:design:main" + ], + "env": {} + } + } +} +``` + +In Zed, open the Agent panel and select “Clawdbot ACP” to start a thread. + +## Session mapping + +By default, ACP sessions get an isolated Gateway session key with an `acp:` prefix. +To reuse a known session, pass a session key or label: + +- `--session `: use a specific Gateway session key. +- `--session-label