web-agent-bridge 3.0.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/LICENSE +72 -21
  2. package/README.ar.md +1286 -1073
  3. package/README.md +1764 -1535
  4. package/bin/agent-runner.js +474 -474
  5. package/bin/cli.js +237 -138
  6. package/bin/wab.js +80 -80
  7. package/examples/bidi-agent.js +119 -119
  8. package/examples/cross-site-agent.js +91 -91
  9. package/examples/mcp-agent.js +94 -94
  10. package/examples/next-app-router/README.md +44 -44
  11. package/examples/puppeteer-agent.js +108 -108
  12. package/examples/saas-dashboard/README.md +55 -55
  13. package/examples/shopify-hydrogen/README.md +74 -74
  14. package/examples/vision-agent.js +171 -171
  15. package/examples/wordpress-elementor/README.md +77 -77
  16. package/package.json +17 -3
  17. package/public/.well-known/agent-tools.json +180 -180
  18. package/public/.well-known/ai-assets.json +59 -59
  19. package/public/.well-known/ai-plugin.json +28 -0
  20. package/public/.well-known/security.txt +8 -0
  21. package/public/agent-workspace.html +349 -347
  22. package/public/ai.html +198 -196
  23. package/public/api.html +413 -0
  24. package/public/browser.html +486 -484
  25. package/public/commander-dashboard.html +243 -243
  26. package/public/cookies.html +210 -208
  27. package/public/css/agent-workspace.css +1713 -1713
  28. package/public/css/premium.css +317 -317
  29. package/public/css/styles.css +1235 -1235
  30. package/public/dashboard.html +706 -704
  31. package/public/demo.html +1770 -1
  32. package/public/dns.html +507 -0
  33. package/public/docs.html +587 -585
  34. package/public/feed.xml +89 -89
  35. package/public/growth.html +463 -0
  36. package/public/index.html +341 -9
  37. package/public/integrations.html +556 -0
  38. package/public/js/agent-workspace.js +1740 -1740
  39. package/public/js/auth-nav.js +31 -31
  40. package/public/js/auth-redirect.js +12 -12
  41. package/public/js/cookie-consent.js +56 -56
  42. package/public/js/wab-demo-page.js +721 -721
  43. package/public/js/ws-client.js +74 -74
  44. package/public/llms-full.txt +360 -309
  45. package/public/llms.txt +125 -86
  46. package/public/login.html +85 -83
  47. package/public/mesh-dashboard.html +328 -328
  48. package/public/openapi.json +580 -580
  49. package/public/phone-shield.html +281 -0
  50. package/public/premium-dashboard.html +2489 -2487
  51. package/public/premium.html +793 -791
  52. package/public/privacy.html +297 -295
  53. package/public/register.html +105 -103
  54. package/public/robots.txt +87 -87
  55. package/public/script/wab-consent.d.ts +36 -36
  56. package/public/script/wab-consent.js +104 -104
  57. package/public/script/wab-schema.js +131 -131
  58. package/public/script/wab.d.ts +108 -108
  59. package/public/script/wab.min.js +580 -580
  60. package/public/security.txt +8 -0
  61. package/public/terms.html +256 -254
  62. package/script/ai-agent-bridge.js +1754 -1754
  63. package/sdk/README.md +99 -99
  64. package/sdk/agent-mesh.js +449 -449
  65. package/sdk/commander.js +262 -262
  66. package/sdk/index.d.ts +464 -464
  67. package/sdk/index.js +18 -1
  68. package/sdk/multi-agent.js +318 -318
  69. package/sdk/package.json +12 -1
  70. package/sdk/safety-shield.js +219 -0
  71. package/sdk/schema-discovery.js +83 -83
  72. package/server/adapters/index.js +520 -520
  73. package/server/config/plans.js +367 -367
  74. package/server/config/secrets.js +102 -102
  75. package/server/control-plane/index.js +301 -301
  76. package/server/data-plane/index.js +354 -354
  77. package/server/index.js +175 -19
  78. package/server/llm/index.js +404 -404
  79. package/server/middleware/adminAuth.js +35 -35
  80. package/server/middleware/auth.js +50 -50
  81. package/server/middleware/featureGate.js +88 -88
  82. package/server/middleware/rateLimits.js +100 -100
  83. package/server/middleware/sensitiveAction.js +157 -0
  84. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  85. package/server/migrations/002_premium_features.sql +418 -418
  86. package/server/migrations/003_ads_integer_cents.sql +33 -33
  87. package/server/migrations/004_agent_os.sql +158 -158
  88. package/server/migrations/005_marketplace_metering.sql +126 -126
  89. package/server/models/adapters/index.js +33 -33
  90. package/server/models/adapters/mysql.js +183 -183
  91. package/server/models/adapters/postgresql.js +172 -172
  92. package/server/models/adapters/sqlite.js +7 -7
  93. package/server/models/db.js +681 -681
  94. package/server/observability/failure-analysis.js +337 -337
  95. package/server/observability/index.js +394 -394
  96. package/server/protocol/capabilities.js +223 -223
  97. package/server/protocol/index.js +243 -243
  98. package/server/protocol/schema.js +584 -584
  99. package/server/registry/certification.js +271 -271
  100. package/server/registry/index.js +326 -326
  101. package/server/routes/admin-premium.js +671 -671
  102. package/server/routes/admin.js +261 -261
  103. package/server/routes/ads.js +130 -130
  104. package/server/routes/agent-workspace.js +540 -378
  105. package/server/routes/api.js +150 -150
  106. package/server/routes/auth.js +71 -71
  107. package/server/routes/billing.js +45 -45
  108. package/server/routes/commander.js +316 -316
  109. package/server/routes/demo-showcase.js +332 -0
  110. package/server/routes/demo-store.js +154 -0
  111. package/server/routes/discovery.js +417 -406
  112. package/server/routes/gateway.js +173 -0
  113. package/server/routes/license.js +251 -240
  114. package/server/routes/mesh.js +469 -469
  115. package/server/routes/noscript.js +543 -543
  116. package/server/routes/premium-v2.js +686 -686
  117. package/server/routes/premium.js +724 -724
  118. package/server/routes/runtime.js +2148 -2147
  119. package/server/routes/sovereign.js +465 -385
  120. package/server/routes/universal.js +200 -177
  121. package/server/routes/wab-api.js +850 -491
  122. package/server/runtime/container-worker.js +111 -111
  123. package/server/runtime/container.js +448 -448
  124. package/server/runtime/distributed-worker.js +362 -362
  125. package/server/runtime/event-bus.js +210 -210
  126. package/server/runtime/index.js +253 -253
  127. package/server/runtime/queue.js +599 -599
  128. package/server/runtime/replay.js +666 -666
  129. package/server/runtime/sandbox.js +266 -266
  130. package/server/runtime/scheduler.js +534 -534
  131. package/server/runtime/session-engine.js +293 -293
  132. package/server/runtime/state-manager.js +188 -188
  133. package/server/security/cross-site-redactor.js +196 -0
  134. package/server/security/dry-run.js +180 -0
  135. package/server/security/human-gate-rate-limit.js +147 -0
  136. package/server/security/human-gate-transports.js +178 -0
  137. package/server/security/human-gate.js +281 -0
  138. package/server/security/index.js +368 -368
  139. package/server/security/intent-engine.js +245 -0
  140. package/server/security/reward-guard.js +171 -0
  141. package/server/security/rollback-store.js +239 -0
  142. package/server/security/token-scope.js +404 -0
  143. package/server/security/url-policy.js +139 -0
  144. package/server/services/agent-chat.js +506 -506
  145. package/server/services/agent-learning.js +601 -575
  146. package/server/services/agent-memory.js +625 -625
  147. package/server/services/agent-mesh.js +555 -539
  148. package/server/services/agent-symphony.js +717 -717
  149. package/server/services/agent-tasks.js +1807 -1807
  150. package/server/services/api-key-engine.js +292 -0
  151. package/server/services/cluster.js +894 -894
  152. package/server/services/commander.js +738 -738
  153. package/server/services/edge-compute.js +440 -440
  154. package/server/services/email.js +204 -204
  155. package/server/services/hosted-runtime.js +205 -205
  156. package/server/services/lfd.js +635 -616
  157. package/server/services/local-ai.js +389 -389
  158. package/server/services/marketplace.js +270 -270
  159. package/server/services/metering.js +182 -182
  160. package/server/services/modules/affiliate-intelligence.js +93 -0
  161. package/server/services/modules/agent-firewall.js +90 -0
  162. package/server/services/modules/bounty.js +89 -0
  163. package/server/services/modules/collective-bargaining.js +92 -0
  164. package/server/services/modules/dark-pattern.js +66 -0
  165. package/server/services/modules/gov-intelligence.js +45 -0
  166. package/server/services/modules/neural.js +55 -0
  167. package/server/services/modules/notary.js +49 -0
  168. package/server/services/modules/price-time-machine.js +86 -0
  169. package/server/services/modules/protocol.js +104 -0
  170. package/server/services/negotiation.js +439 -439
  171. package/server/services/plugins.js +771 -771
  172. package/server/services/premium.js +1 -1
  173. package/server/services/price-intelligence.js +566 -565
  174. package/server/services/price-shield.js +1137 -1137
  175. package/server/services/reputation.js +465 -465
  176. package/server/services/search-engine.js +357 -357
  177. package/server/services/security.js +513 -513
  178. package/server/services/self-healing.js +843 -843
  179. package/server/services/sovereign-shield.js +542 -0
  180. package/server/services/stripe.js +192 -192
  181. package/server/services/swarm.js +788 -788
  182. package/server/services/universal-scraper.js +662 -661
  183. package/server/services/verification.js +481 -481
  184. package/server/services/vision.js +1163 -1163
  185. package/server/utils/cache.js +125 -125
  186. package/server/utils/migrate.js +81 -81
  187. package/server/utils/safe-fetch.js +228 -0
  188. package/server/utils/secureFields.js +50 -50
  189. package/server/ws.js +161 -161
  190. package/templates/artisan-marketplace.yaml +104 -104
  191. package/templates/book-price-scout.yaml +98 -98
  192. package/templates/electronics-price-tracker.yaml +108 -108
  193. package/templates/flight-deal-hunter.yaml +113 -113
  194. package/templates/freelancer-direct.yaml +116 -116
  195. package/templates/grocery-price-compare.yaml +93 -93
  196. package/templates/hotel-direct-booking.yaml +113 -113
  197. package/templates/local-services.yaml +98 -98
  198. package/templates/olive-oil-tunisia.yaml +88 -88
  199. package/templates/organic-farm-fresh.yaml +101 -101
  200. package/templates/restaurant-direct.yaml +97 -97
  201. package/server/services/fairness-engine.js +0 -409
  202. package/server/services/fairness.js +0 -420
package/README.md CHANGED
@@ -1,1535 +1,1764 @@
1
- # Web Agent Bridge (WAB)
2
-
3
- [![npm](https://img.shields.io/npm/v/web-agent-bridge)](https://www.npmjs.com/package/web-agent-bridge)
4
- [![CI](https://github.com/abokenan444/web-agent-bridge/actions/workflows/ci.yml/badge.svg)](https://github.com/abokenan444/web-agent-bridge/actions/workflows/ci.yml)
5
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
- [![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen.svg)](https://nodejs.org/)
7
- [![Docker](https://img.shields.io/badge/docker-ready-blue.svg)](https://hub.docker.com/)
8
- [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
9
-
10
- > **robots.txt told bots what NOT to do. WAB tells AI agents what they CAN do.**
11
-
12
- 🌐 **Live Website:** [https://webagentbridge.com](https://webagentbridge.com) — Try the Agent Workspace, dashboards, and many more features live.
13
-
14
- **English** | **[العربية](README.ar.md)**
15
-
16
- WAB is an open-source middleware layer that bridges AI agents and websites — like **OpenAPI for human-facing pages**. Website owners embed a script that exposes a standardized `window.AICommands` interface. AI agents discover available actions, execute commands, and interact with sites accurately — no DOM parsing, no scraping, no guesswork.
17
-
18
- ### Three Paths to WAB
19
-
20
- | Path | For | How |
21
- |---|---|---|
22
- | **🏢 Website Owner** | Control how AI interacts with your site | Embed the script, configure permissions |
23
- | **🤖 Agent Developer** | Build reliable agents that work on any WAB-enabled site | Use `window.AICommands` or the Agent SDK |
24
- | **🔧 Self-Hosting** | Run the full WAB platform for your organization | Clone, deploy, manage licenses & analytics |
25
- | **WordPress** | Sites powered by WP | Use the **[Web Agent Bridge WordPress plugin](web-agent-bridge-wordpress/README.md)** (settings, shortcode, per-page disable, hooks) |
26
-
27
- ---
28
-
29
- ## Features
30
-
31
- - **Auto-Discovery** — Automatically detects buttons, forms, and navigation on the page
32
- - **Structured Auto-Discovery** — Detects schema.org JSON-LD + microdata products/offers and exposes read actions
33
- - **Commerce + Booking Intents** — Detects common actions like add-to-cart, checkout, and booking/reservation flows
34
- - **Permission System** — Granular control over what AI agents can do (click, fill forms, API access, etc.)
35
- - **Standardized Interface** — Unified `window.AICommands` object any agent can consume
36
- - **Secure License Exchange** — Embed uses public `siteId` + `/api/license/token`; long-lived license keys stay in the owner dashboard, not in HTML
37
- - **Rate Limiting** — Multi-dimensional abuse protection (IP + license key + site)
38
- - **Analytics Dashboard** — Track how AI agents interact with your site
39
- - **Real-Time Analytics** — WebSocket-based live event streaming with auto-reconnection
40
- - **In-Memory Caching** — TTL-based cache layer reduces DB reads on hot paths
41
- - **Analytics Queue** — Batched writes with transaction support for high-throughput tracking
42
- - **WebDriver BiDi Compatible** — Standard protocol support via `window.__wab_bidi`
43
- - **CDN Versioning** — Serve scripts via versioned URLs (`/v1/ai-agent-bridge.js`, `/latest/ai-agent-bridge.js`)
44
- - **Docker Ready** — One-command deployment with Docker Compose
45
- - **DB Migrations** — Numbered SQL migration runner with tracking table
46
- - **Custom Actions** — Register your own actions with custom handlers
47
- - **Subscription Tiers** — Free core + paid premium features (API access, analytics, automated login)
48
- - **Event System** — Subscribe to bridge events for monitoring
49
- - **Security Sandbox** — Origin validation, session tokens, command signing, audit logging, auto-lockdown
50
- - **Self-Healing Selectors** — Resilient element resolution with fuzzy matching for dynamic SPAs
51
- - **Stealth Mode** — Human-like interaction patterns (requires explicit consent)
52
- - **Multi-Database** — SQLite (default), PostgreSQL, MySQL via pluggable adapters
53
- - **Agent SDK** — Built-in SDK for building AI agents with Puppeteer/Playwright
54
- - **React Package** — `@web-agent-bridge/react` with `WABProvider`, `useWAB`, `useWABAction`, and `useWABActions`
55
- - **Vue Package** — `@web-agent-bridge/vue` composables (`useWAB`, `useWABAction`, `useWABActions`) for Vue 3+
56
- - **Svelte Package** — `@web-agent-bridge/svelte` stores (`createWAB`, `createWABAction`) for Svelte 3+
57
- - **LangChain Adapter** — `@web-agent-bridge/langchain` wraps WAB actions as LangChain tools for LLM agents
58
- - **GDPR/CCPA Consent** — Optional `wab-consent.js` banner with `WABConsent.showBanner()` and `hasConsent()` gate
59
- - **Admin Dashboard** — User management, tier grants, system analytics
60
- - **Stripe Integration** — Payment processing with customer portal
61
- - **Plugin Architecture** — Dynamic plugin system with hook-based execution, per-site installation, priority ordering, ratings, and audit logging
62
- - **Vision Analysis Service** — Multi-provider screenshot analysis (local Moondream, OpenAI, Anthropic, Ollama) with interactive element detection, bounding box extraction, and AES-256-GCM encrypted API keys
63
- - **Fairness Engine** — Neutrality layer ensuring AI agents give equal opportunity to small and large sites with fairness-weighted search, commission transparency tracking, and trust signature validation
64
- - **Agent Memory System** — Persistent behavioral memory with 4 memory types, 5 categories, semantic associations, importance scoring, and TTL-based expiration
65
- - **Premium Traffic Intelligence** — Advanced bot detection (30+ agent types), behavioral profiling, anomaly/spike detection, security exploit detection (SQLi, XSS), and webhook alerting
66
- - **E-Mail Service** — SMTP-based transactional emails (welcome, registration, password reset, contact) with branded HTML templates
67
- - **NoScript Fallback** — 1×1 tracking pixel endpoint for analytics collection when JavaScript is unavailable
68
- - **WAB-MCP Adapter** — Expose WAB site capabilities as MCP tools for Claude, GPT, Gemini, and other MCP-compatible AI agents
69
- - **WordPress Plugin** — Native WordPress plugin with settings page, per-page action meta boxes, discovery document generation, and dashboard widget
70
- - **WAB Browser (Desktop)** — Standalone Electron desktop browser with built-in ad blocker (80+ domains), scam shield, fairness ranking, agent chat, bookmarks, history, and WAB protocol support. *Desktop source is maintained in a separate private build pipeline (`wab-browser/`); the PWA source below is fully open.*
71
- - **PWA Browser (Mobile)** — Progressive Web App browser for Android/iOS with ad blocking (80+ domains), WAB Search engine, scam detection, fairness ranking, real AI agent chat, and offline-first service worker. Full source at `public/pwa/`.
72
- - **Schema Discovery SDK** — Server-side extraction of schema.org JSON-LD Product nodes from HTML with automatic WAB action hint generation
73
-
74
- ### v2.0Digital Fortress Features
75
-
76
- - **Real-time Negotiation Engine** — AI agents negotiate prices directly with WAB-enabled sites using multi-round sessions. 8 condition types (bulk, loyalty, time-based, first-purchase, cart-value, seasonal, membership, referral) and 4 discount types (percentage, fixed, free-shipping, bonus-item). Includes daily usage limits, minimum order values, and full audit trail of all offers
77
- - **Anti-Hallucination Shield** Cross-verification engine comparing DOM vs vision screenshots, market benchmark validation, temporal consistency checks, and Levenshtein text similarity scoring. 4 severity levels (minor → fraud) and 5 response actions (warn, halt, confirm-human, auto-correct, block)
78
- - **Decentralized Reputation System** — HMAC-signed trust attestations from the agent network covering 6 attestation types (purchase, booking, query, form, navigation, verification). 7 trust levels (unknown → blacklisted), temporal decay, Sybil resistance, global leaderboard, and challenge/dispute system
79
- - **Sovereign Dashboard** — Real-time command center with fairness radar, privacy shield, negotiation logs, verification checks, and AI model switcher. Exposes `/api/sovereign/dashboard/sovereign` aggregate endpoint
80
- - **Community Agent Hub** — 11 pre-built YAML agent templates (hotel booking, grocery comparison, artisan marketplace, flight deals, etc.) with CLI runner: `npx wab-agent run template.yaml`
81
- - **AI Brain Swapping** — Local AI runtime that auto-discovers Ollama and llama.cpp endpoints plus custom OpenAI-compatible APIs. Model capability tracking for text/vision, context window management, latency-based routing, and inference logging with token metrics
82
- - **Cross-Site Agent Orchestration** — One agent manages multiple WAB-enabled sites simultaneously via `WABMultiAgent`. Compare prices across stores, aggregate data, run parallel actions, and find the best deal automatically
83
-
84
- ### v2.3Private Agent Mesh (Distributed Mind)
85
-
86
- - **Inter-Agent Protocol** — Agents communicate through a private mesh with 5 built-in channels (alerts, discoveries, tactics, negotiations, votes). 6 message types with confidence scoring, auto-expiring stale agents via heartbeat, peer verification of shared knowledge. All communication stays local — no external transmission
87
- - **Local Reinforcement Learning** Agents learn from every user decision using UCB1 multi-armed bandit action selection, gradient-descent policy updates with sigmoid activation, temporal discounting, and sequential pattern mining. Zero external API calls — all learning is local
88
- - **Symphony Orchestrator** — Four specialized agents (Researcher, Analyst, Negotiator, Guardian) collaborate autonomously through rule-based engines. 5 templates, 6-phase pipeline (analyze → research → negotiate → guard → synthesize → decide), Guardian veto for safety, weighted consensus. Full phase logging with duration tracking. No external LLM dependency
89
- - **Agent Mesh Dashboard** — Real-time visualization of your agent mesh: active agents, communication channels, shared knowledge base, symphony compositions, and learning performance metrics
90
-
91
- ### v2.4Commander & Edge Intelligence
92
-
93
- - **Commander Agent System** — Local-first mission orchestration engine that decomposes high-level goals into task DAGs. Agent registry with capabilities tracking, parallel execution engine, learning integration for outcome feedback, and edge coordination for distributed work
94
- - **Edge Compute System** Transforms every user device into a sovereign AI node. Hardware profiling (CPU, RAM, GPU), AES-256-GCM encrypted inter-node communication, weighted load balancing, heartbeat-based health monitoring with auto-failover, and swarm formation with capability-based clustering
95
- - **Swarm Execution Engine** — Launch multiple agents in parallel to solve a single task. Configurable strategies (parallel, sequential, hybrid), result merging with best-score selection, role specialization, fairness-weighted aggregation, and per-agent confidence scoring
96
-
97
- ### v2.5Agent Workspace & Multilingual AI
98
-
99
- - **Agent Workspace** — Premium 4-panel workspace for non-technical users: embedded browser, smart agent chat, real-time negotiation monitor, and results panel. Subscription tiers (Free/Starter/Pro/Enterprise), deal tracking, and admin management. Live at [webagentbridge.com/workspace](https://webagentbridge.com/workspace)
100
- - **Bilingual UI (AR/EN)** Full Arabic/English interface with auto-detection from browser language. Toggle instantly between languages. RTL/LTR layout support
101
- - **Multilingual Agent** — The smart agent understands and responds in any language the user writes in — Arabic, English, French, Spanish, Turkish, and more. No restrictions on input style, dialect, or format
102
- - **Dynamic Pricing Shield** — Detects price manipulation by websites that change prices based on device type, geolocation, cookies, browsing history, referral source, or repeat visits. The agent probes the same page with 12 distinct identity personas (clean desktop, mobile, Mac premium, EU/MENA/SEA geo, repeat visitor, Google/social/comparison referral, privacy-focused, bot-like) and uses statistical analysis (coefficient of variation, z-score outliers) to expose hidden pricing. Includes manipulation scoring (0–100), actionable tips, historical trend detection, and a strategy builder that recommends the best identity for the lowest price. Full API at `/api/sovereign/price-shield/`
103
-
104
- ### v3.0Agent OS (Execution Layer for the Web)
105
-
106
- WAB v3.0 transforms the project from an advanced automation tool into a **real Agent Operating System** — a complete execution layer for AI agents on the web, comparable to MCP but purpose-built for browser interaction.
107
-
108
- - **WAB Protocol (WABP) v1.0.0** — Formal protocol with JSON Schema command registry, typed messages, input/output validation, and versioned command definitions. 10 built-in commands (discover, execute, semantic.execute, agent.register, task.submit, task.status, commerce.compare, commerce.negotiate, mesh.send, ai.infer). Every command has declared capabilities, risk levels, and permission requirements
109
- - **Capability Negotiation** Dynamic capability grants between agents and sites. Risk-based auto-approval (low-risk auto-granted, high-risk requires policy), rate limiting per capability, expirable grants with usage tracking, and full revocation support
110
- - **Agent Runtime Engine** — Production-grade task runtime with priority queue scheduler, dependency resolution, retry with exponential backoff, pause/resume/cancel, concurrency limits, and state machine transitions. EventBus with async middleware, namespace wildcards, replay buffer (10K events), and dead letter queue
111
- - **Execution Sandbox** — Per-task isolation with resource limits (timeout, maxMemory, maxNetworkCalls, maxDomOperations), domain allowlists, blocked selector enforcement, capability checks at execution time, and full audit trail of every operation
112
- - **State Manager** — Agent state persistence with labeled checkpoints, rollback to any checkpoint, state transitions with validation, merge operations, and TTL-based cleanup
113
- - **Observability Stack** — Structured JSON logger with child loggers and pluggable sinks, distributed tracer with parent-child spans (OpenTelemetry-compatible), and metrics collector with counters, gauges, histograms (p50/p90/p95/p99 percentiles), and time series for dashboards
114
- - **Security Model** — AgentIdentity (registration, hashed API key authentication, session management with TTL, IP allowlists, revocation), CommandSigner (HMAC-SHA256 signing/verification with nonce + timestamp, timing-safe comparison), and SiteIsolation (per-site access control, allowed/blocked agents, max concurrency, selector blocking, data classification)
115
- - **Control Plane** — AgentManager for deployment lifecycle (deploy, assign to sites, health checks, undeploy) and PolicyEngine with typed rules, condition evaluation (equals, contains, pattern, min, max, in), priority-ordered policy binding, and entity-level policy enforcement
116
- - **Data Plane** — SemanticActionResolver maps `domain.action` notation (e.g., `checkout.addItem`) to concrete implementations per site. Executor routes tasks through tracing + metrics, supports semantic/pipeline/parallel execution modes, with 8 built-in semantic actions for checkout, search, auth, navigation, and content
117
- - **Multi-Model LLM Abstraction** — Unified interface for OpenAI (chat completions + embeddings), Anthropic (messages API), and Ollama (local models with auto-discovery). LLMManager provides automatic fallback chain through all providers, response caching (5min TTL), cost tracking via token counts, and model listing
118
- - **Registry & Ecosystem** — CommandRegistry (like npm for WAB commands — register, discover, search by category/tag/capability, usage tracking), SiteRegistry (WAB-enabled sites directory with verification, capability listing, visit tracking), and TemplateRegistry (reusable workflow templates with download counts and ratings)
119
- - **Unified Runtime API** — All Agent OS layers exposed via RESTful endpoints at `/api/os/*`: protocol discovery, agent identity/auth, task CRUD, semantic execution, deployments, policies, isolation, observability (metrics/traces/logs), registry (commands/sites/templates), LLM operations, command signing, and Server-Sent Events for real-time streaming
120
- - **WABAgentOS SDK Client** — New `WABAgentOS` class in the SDK provides full TypeScript-typed API for all Agent OS operations: register authenticate negotiate capabilities submit tasks execute semantically query observability subscribe to events
121
-
122
- ### v3.1WAP Deep Architecture (Protocol Hardening)
123
-
124
- v3.1 hardens the Agent OS into a production-grade system that *surpasses* MCP — making WAP (Web Agent Protocol) the top-level protocol with MCP as just one adapter.
125
-
126
- - **WAP Discovery Spec** — Formal `/.well-known/agent-tools.json` discovery document. AI agents can find all WAP capabilities, commands, permissions, runtime config, security model, and SDKs from a single standardized URL
127
- - **Adapter Layer** — WAP sits at the top; MCP, REST/GraphQL, and Browser automation are transport adapters beneath it. MCP Adapter exposes all WAB commands as MCP tools (list_tools / call_tool). REST Adapter registers external APIs as first-class WAP endpoints with auth, mapping, and rate limiting. Browser Adapter translates semantic actions (checkout.addItem, search.query, auth.login) into concrete browser step plans with selector fallbacks and verification
128
- - **Auth Middleware** — All `/api/os/*` mutation endpoints require authentication (Bearer token, API key, or agent header). Public read endpoints remain open for discovery. GET requests pass through for read-only access
129
- - **Deterministic Replay Engine** — Records all task inputs, outputs, and side-effects. Supports replay with verification mode (re-execute and compare), dry-run mode (inspect recorded steps), and diff between two recordings. Enables debugging, regression testing, and workflow certification
130
- - **Failure Analysis & Classification** — Automatic classification of failures into 9 categories (network, timeout, permission, validation, execution, rate_limit, resource, dependency, unknown). Root cause analysis, severity scoring, retryability assessment, suggested fixes, and pattern detection for recurring failures
131
- - **Session Engine** — Browser execution sessions with cookie jar (set/get/domain-scoped), localStorage/sessionStorage emulation, navigation history, variable store, session export/import for transfer, and TTL-based expiration
132
- - **Certification System** — Site compatibility verification with 13 weighted checks across 7 categories (integration, protocol, data, security, fairness, compliance, sovereignty). Issues certificates at 5 levels (none basic standard premium sovereign) with 90-day validity, HMAC-signed badges, and revocation
133
- - **DB Persistence Layer** — SQLite tables for all Agent OS entities: agents, sessions, tasks, deployments, registry commands/sites/templates, audit log (immutable append-only), capability grants, and policies. Auto-migrates on boot
134
- - **65+ API Endpoints** — Adapters (MCP tools, REST endpoints, browser mappings), replay (recordings, replay, diff, stats), sessions (CRUD, cookies, storage, export/import), failure analysis (query, patterns, summary, classify), certification (verify, certificates, revoke), plus all existing v3.0 endpoints
135
-
136
- > **Many more features** are available on the live website that aren't listed here dashboards, analytics, admin tools, and more. Visit [webagentbridge.com](https://webagentbridge.com) to explore.
137
-
138
- ---
139
-
140
- ## Quick Start
141
-
142
- ### 1. Install & Run the Server
143
-
144
- ```bash
145
- # Option A: Clone and run
146
- git clone https://github.com/abokenan444/web-agent-bridge.git
147
- cd web-agent-bridge
148
- npm install
149
- cp .env.example .env
150
- npm start
151
-
152
- # Option B: npx (one command)
153
- npx web-agent-bridge start
154
-
155
- # Option C: Docker
156
- docker compose up -d
157
- ```
158
-
159
- ### 2. Create an Account
160
-
161
- Visit `http://localhost:3000/register` and create an account, then add your site from the dashboard.
162
-
163
- ### 3. Add the Script to Your Website
164
-
165
- ```html
166
- <!-- Recommended: copy the snippet from your dashboard (uses siteId only) -->
167
- <script>
168
- window.AIBridgeConfig = {
169
- siteId: "your-site-uuid-from-dashboard",
170
- configEndpoint: "https://yourserver.com/api/license/token",
171
- agentPermissions: {
172
- readContent: true,
173
- click: true,
174
- fillForms: true,
175
- scroll: true
176
- }
177
- };
178
- </script>
179
- <script src="https://yourserver.com/script/ai-agent-bridge.js"></script>
180
- ```
181
-
182
- The server matches **Origin** to your registered site domain, then returns a short-lived **session token**. Analytics (`/api/license/track`) require that session — not the long-lived license key. Keep the license key in the dashboard only.
183
-
184
- ### 4. AI Agents Can Now Interact
185
-
186
- ```javascript
187
- // From the AI agent's side
188
- const bridge = window.AICommands;
189
- const actions = bridge.getActions(); // discover actions
190
- await bridge.execute("signup"); // execute an action
191
- const info = bridge.getPageInfo(); // get page metadata
192
- ```
193
-
194
- ---
195
-
196
- ## Project Structure
197
-
198
- ```
199
- web-agent-bridge/
200
- ├── server/ # Express.js backend
201
- │ ├── index.js # Server entry point
202
- │ ├── ws.js # WebSocket server (live analytics)
203
- │ ├── routes/
204
- │ │ ├── auth.js # Authentication (register/login)
205
- │ │ ├── api.js # Sites, config, analytics API
206
- │ │ ├── license.js # License verification, token exchange & tracking
207
- │ │ ├── admin.js # Admin dashboard API
208
- │ │ ├── admin-premium.js # Admin premium analytics (memory, vision, swarm, plugins)
209
- │ │ ├── billing.js # Stripe billing integration
210
- │ │ ├── sovereign.js # v2.0: negotiation, reputation, verification, dashboard
211
- │ │ ├── mesh.js # v2.3: agent mesh protocol routes
212
- │ │ ├── commander.js # v2.4: mission orchestration routes
213
- │ │ ├── premium.js # Premium features
214
- │ │ ├── premium-v2.js # v2 premium (memory, vision, healing, swarm, plugins)
215
- │ │ ├── discovery.js # WAB discovery + fairness-weighted search
216
- │ │ ├── wab-api.js # WAB HTTP transport (alternative to JS/WS)
217
- │ │ └── noscript.js # NoScript tracking pixel fallback
218
- │ ├── services/
219
- │ │ ├── negotiation.js # Real-time negotiation engine
220
- │ │ ├── verification.js # Anti-hallucination shield
221
- │ │ ├── reputation.js # Decentralized reputation system
222
- │ │ ├── agent-mesh.js # Inter-agent protocol (mesh)
223
- │ │ ├── agent-learning.js # Local reinforcement learning (UCB1)
224
- │ │ ├── agent-symphony.js # Symphony orchestrator (4 roles, 6 phases)
225
- │ │ ├── agent-memory.js # Persistent agent memory with associations
226
- │ │ ├── commander.js # Mission orchestration & task DAGs
227
- │ │ ├── edge-compute.js # Edge computing / sovereign AI nodes
228
- │ │ ├── swarm.js # Swarm execution engine
229
- │ │ ├── fairness.js # Fairness & neutrality engine
230
- │ │ ├── vision.js # Vision analysis (multi-provider)
231
- │ │ ├── self-healing.js # Self-healing selector corrections
232
- │ │ ├── local-ai.js # Local AI model runtime
233
- │ │ ├── plugins.js # Plugin architecture (hooks, registry)
234
- │ │ ├── premium.js # Premium traffic intelligence & bot detection
235
- │ │ ├── email.js # SMTP email service
236
- │ │ └── stripe.js # Stripe payment integration
237
- │ ├── middleware/
238
- │ │ ├── auth.js # JWT authentication middleware
239
- │ │ ├── adminAuth.js # Admin authentication
240
- │ │ └── rateLimits.js # Multi-layer rate limiting
241
- │ ├── models/
242
- │ │ ├── db.js # Database operations
243
- │ │ └── adapters/ # SQLite, PostgreSQL, MySQL adapters
244
- │ ├── migrations/ # Numbered SQL migrations
245
- │ └── utils/
246
- │ ├── cache.js # In-memory TTL cache + analytics queue
247
- │ ├── migrate.js # Migration runner
248
- │ └── secureFields.js # Field-level encryption utilities
249
- ├── public/ # Frontend
250
- │ ├── index.html # Landing page
251
- │ ├── dashboard.html # Management dashboard
252
- │ ├── premium-dashboard.html # Premium analytics dashboard
253
- │ ├── docs.html # Documentation
254
- │ ├── login.html / register.html # Auth pages
255
- │ ├── admin/ # Admin panel
256
- │ ├── pwa/ # Progressive Web App (mobile browser)
257
- │ │ ├── manifest.json # PWA manifest
258
- │ │ ├── sw.js # Service worker (offline-first)
259
- │ │ ├── index.html # Mobile browser UI
260
- │ │ ├── app.js # Ad blocker, scam shield, fairness
261
- │ │ ├── app.css # Mobile-optimized dark theme
262
- │ │ └── icons/ # PWA icons (192x192, 512x512)
263
- │ ├── script/
264
- │ │ ├── wab.min.js # Minified WAB client library
265
- │ │ ├── wab-consent.js # GDPR/CCPA consent banner
266
- │ │ ├── wab-schema.js # Schema.org discovery
267
- │ │ ├── wab.d.ts # TypeScript definitions
268
- │ │ └── wab-consent.d.ts # Consent TypeScript definitions
269
- │ ├── js/ # Dashboard frontend JS
270
- │ └── css/ # Stylesheets
271
- ├── script/
272
- │ └── ai-agent-bridge.js # The bridge script (embed in websites)
273
- ├── examples/ # Agent examples
274
- │ ├── puppeteer-agent.js # Puppeteer + window.AICommands
275
- │ ├── bidi-agent.js # WebDriver BiDi protocol
276
- │ ├── vision-agent.js # Vision/NLP intent resolution
277
- │ ├── mcp-agent.js # MCP adapter usage for Claude/GPT
278
- │ ├── cross-site-agent.js # Multi-domain orchestration
279
- │ ├── next-app-router/ # Next.js App Router integration
280
- │ ├── shopify-hydrogen/ # Shopify Hydrogen storefront
281
- │ ├── wordpress-elementor/ # WordPress + Elementor setup
282
- │ └── saas-dashboard/ # SaaS dashboard actions
283
- ├── packages/ # Framework wrappers
284
- │ ├── react/ # @web-agent-bridge/react
285
- │ ├── vue/ # @web-agent-bridge/vue
286
- │ ├── svelte/ # @web-agent-bridge/svelte
287
- │ └── langchain/ # @web-agent-bridge/langchain
288
- ├── sdk/ # Agent SDK
289
- │ ├── index.js # WABAgent for Puppeteer/Playwright
290
- │ └── schema-discovery.js # Server-side schema.org extraction
291
- ├── wab-mcp-adapter/ # MCP adapter for Claude/GPT/Gemini
292
- │ ├── index.js # MCP tool definitions
293
- │ └── package.json
294
- ├── wab-browser/ # Electron desktop browser
295
- │ ├── main.js # Electron main process
296
- │ ├── preload.js # Bridge preload
297
- │ └── package.json
298
- ├── web-agent-bridge-wordpress/ # WordPress plugin
299
- │ ├── web-agent-bridge.php # Plugin entry point
300
- │ ├── includes/ # PHP classes (API, Actions, Dashboard)
301
- │ └── assets/ # Plugin CSS/JS
302
- ├── bin/
303
- │ ├── cli.js # CLI entry point (wab-agent)
304
- └── wab.js # Agent runner
305
- ├── templates/ # 11 Community Agent Hub YAML templates
306
- ├── docs/
307
- │ ├── SPEC.md # WAB Protocol Specification
308
- └── DEPLOY.md # Deployment guide
309
- ├── demo-store/ # Demo store for testing
310
- ├── deploy/ # Nginx configs
311
- ├── tests/ # Jest + Supertest test suite
312
- ├── .env # Environment variables
313
- └── package.json
314
- ```
315
-
316
- ---
317
-
318
- ## API Endpoints
319
-
320
- ### Authentication
321
- | Endpoint | Method | Description |
322
- |---|---|---|
323
- | `/api/auth/register` | POST | Create account |
324
- | `/api/auth/login` | POST | Sign in, receive JWT |
325
- | `/api/auth/me` | GET | Get current user |
326
-
327
- ### Sites
328
- | Endpoint | Method | Description |
329
- |---|---|---|
330
- | `/api/sites` | GET | List your sites |
331
- | `/api/sites` | POST | Add a new site |
332
- | `/api/sites/:id` | GET | Get site details |
333
- | `/api/sites/:id/config` | PUT | Update configuration |
334
- | `/api/sites/:id/tier` | PUT | Change subscription tier |
335
- | `/api/sites/:id` | DELETE | Delete a site |
336
- | `/api/sites/:id/snippet` | GET | Get install code snippet |
337
- | `/api/sites/:id/analytics` | GET | Get analytics data |
338
-
339
- ### License (Public)
340
- | Endpoint | Method | Description |
341
- |---|---|---|
342
- | `/api/license/verify` | POST | Verify license key for domain (cached) |
343
- | `/api/license/token` | POST | Exchange `siteId` (Origin must match domain) or `licenseKey` for session token |
344
- | `/api/license/session` | POST | Validate session token (domain-locked) |
345
- | `/api/license/track` | POST | Record analytics (`sessionToken` + Origin) |
346
-
347
- ### Sovereign (v2.0)
348
- | Endpoint | Method | Description |
349
- |---|---|---|
350
- | `/api/sovereign/reputation/agents` | POST | Register a new agent |
351
- | `/api/sovereign/reputation/attestations` | POST | Submit a trust attestation |
352
- | `/api/sovereign/reputation/sites/:siteId` | GET | Get site reputation |
353
- | `/api/sovereign/reputation/leaderboard` | GET | Get reputation leaderboard |
354
- | `/api/sovereign/negotiation/rules` | POST | Create negotiation rule |
355
- | `/api/sovereign/negotiation/rules/:siteId` | GET | Get rules for a site |
356
- | `/api/sovereign/negotiation/sessions` | POST | Open negotiation session |
357
- | `/api/sovereign/negotiation/sessions/:id/propose` | POST | Submit counter-offer |
358
- | `/api/sovereign/negotiation/sessions/:id/confirm` | POST | Confirm a deal |
359
- | `/api/sovereign/verify/price` | POST | Verify price (DOM vs vision) |
360
- | `/api/sovereign/verify/text` | POST | Verify text accuracy |
361
- | `/api/sovereign/verify/page` | POST | Full page verification |
362
- | `/api/sovereign/dashboard/sovereign` | GET | Dashboard aggregate data |
363
-
364
- ### Agent Mesh (v2.3)
365
- | Endpoint | Method | Description |
366
- |---|---|---|
367
- | `/api/mesh/agents` | POST | Register agent in mesh |
368
- | `/api/mesh/agents` | GET | List mesh agents |
369
- | `/api/mesh/channels` | GET | List communication channels |
370
- | `/api/mesh/messages` | POST | Publish message to channel |
371
- | `/api/mesh/messages/:channel` | GET | Get messages from channel |
372
- | `/api/mesh/knowledge` | POST | Share knowledge to mesh |
373
- | `/api/mesh/knowledge` | GET | Query knowledge base |
374
- | `/api/mesh/votes` | POST | Start a vote |
375
- | `/api/mesh/votes/:id/cast` | POST | Cast a vote |
376
- | `/api/mesh/votes/:id/tally` | GET | Get vote results |
377
-
378
- ### Commander (v2.4)
379
- | Endpoint | Method | Description |
380
- |---|---|---|
381
- | `/api/commander/missions` | POST | Create a new mission |
382
- | `/api/commander/missions/:id/launch` | POST | Launch mission execution |
383
- | `/api/commander/missions/:id` | GET | Get mission status |
384
- | `/api/commander/missions` | GET | List all missions |
385
- | `/api/commander/agents` | POST | Register an agent |
386
- | `/api/commander/agents` | GET | List registered agents |
387
- | `/api/commander/edge/nodes` | POST | Register edge node |
388
- | `/api/commander/edge/nodes` | GET | List edge nodes |
389
- | `/api/commander/ai/models` | GET | Discover local AI models |
390
- | `/api/commander/ai/infer` | POST | Run local AI inference |
391
- | `/api/commander/stats` | GET | Unified platform statistics |
392
-
393
- ### Premium v2
394
- | Endpoint | Method | Description |
395
- |---|---|---|
396
- | `/api/premium/v2/memory` | POST | Store agent memory |
397
- | `/api/premium/v2/memory/:agentId` | GET | Recall agent memories |
398
- | `/api/premium/v2/memory/associate` | POST | Create memory association |
399
- | `/api/premium/v2/memory/:id` | DELETE | Forget a memory |
400
- | `/api/premium/v2/memory/consolidate` | POST | Consolidate old memories |
401
- | `/api/premium/v2/vision/analyze` | POST | Analyze screenshot |
402
- | `/api/premium/v2/vision/elements` | POST | Extract interactive elements |
403
- | `/api/premium/v2/healing/corrections` | POST | Register selector correction |
404
- | `/api/premium/v2/healing/resolve` | POST | Resolve broken selector |
405
- | `/api/premium/v2/swarm/execute` | POST | Launch swarm task |
406
- | `/api/premium/v2/swarm/:id` | GET | Get swarm results |
407
- | `/api/premium/v2/plugins` | GET | List available plugins |
408
- | `/api/premium/v2/plugins/:id/install` | POST | Install plugin for site |
409
- | `/api/premium/v2/plugins/:id/hooks` | POST | Execute plugin hook |
410
-
411
- ### Discovery & Fairness
412
- | Endpoint | Method | Description |
413
- |---|---|---|
414
- | `/api/discovery` | GET | WAB discovery document |
415
- | `/api/discovery/search` | GET | Fairness-weighted site search |
416
- | `/api/discovery/register` | POST | Register site in WAB directory |
417
-
418
- ### WAB Protocol (HTTP Transport)
419
- | Endpoint | Method | Description |
420
- |---|---|---|
421
- | `/api/wab/session` | POST | Exchange session token |
422
- | `/api/wab/actions` | GET | Get available actions |
423
- | `/api/wab/execute` | POST | Execute action via HTTP |
424
-
425
- ### NoScript Fallback
426
- | Endpoint | Method | Description |
427
- |---|---|---|
428
- | `/noscript/pixel.gif` | GET | 1×1 tracking pixel for non-JS environments |
429
-
430
- ---
431
-
432
- ## Bridge Script API
433
-
434
- Once loaded, `window.AICommands` exposes:
435
-
436
- | Method | Description |
437
- |---|---|
438
- | `getActions(category?)` | List available actions |
439
- | `getAction(name)` | Get a specific action |
440
- | `execute(name, params?)` | Execute an action |
441
- | `readContent(selector)` | Read element content |
442
- | `getPageInfo()` | Get page and bridge metadata |
443
- | `waitForElement(selector, timeout?)` | Wait for DOM element |
444
- | `waitForNavigation(timeout?)` | Wait for URL change |
445
- | `registerAction(def)` | Register a custom action |
446
- | `authenticate(key, meta?)` | Authenticate an agent |
447
- | `refresh()` | Re-scan the page |
448
- | `onReady(callback)` | Callback when bridge is ready |
449
- | `events.on(event, cb)` | Subscribe to events |
450
-
451
- ---
452
-
453
- ## Configuration
454
-
455
- ```javascript
456
- window.AIBridgeConfig = {
457
- // Recommended copy siteId from dashboard snippet (no license key in HTML)
458
- siteId: "uuid-from-dashboard",
459
- configEndpoint: "/api/license/token",
460
-
461
- // Legacy: token exchange via license key (avoid embedding in public pages)
462
- // licenseKey: "WAB-...",
463
-
464
- agentPermissions: {
465
- readContent: true, // Read page text
466
- click: true, // Click elements
467
- fillForms: false, // Fill/submit forms
468
- scroll: true, // Scroll page
469
- navigate: false, // Navigate pages
470
- apiAccess: false, // Internal API calls (Pro+)
471
- automatedLogin: false, // Auto login (Starter+)
472
- extractData: false // Data extraction (Pro+)
473
- },
474
- restrictions: {
475
- allowedSelectors: [],
476
- blockedSelectors: [".private", "[data-private]"],
477
- requireLoginForActions: ["apiAccess"],
478
- rateLimit: { maxCallsPerMinute: 60 }
479
- },
480
- logging: { enabled: false, level: "basic" }
481
- };
482
- ```
483
-
484
- ---
485
-
486
- ## Subscription Tiers
487
-
488
- | Feature | Free | Starter | Pro | Enterprise |
489
- |---|:---:|:---:|:---:|:---:|
490
- | Auto-discovery | | | | ✓ |
491
- | Click/Scroll | ✓ | ✓ | ✓ | ✓ |
492
- | Form filling | ✓ | ✓ | ✓ | ✓ |
493
- | Basic logging | | | ✓ | ✓ |
494
- | Automated login | ✗ | ✓ | ✓ | ✓ |
495
- | Analytics dashboard | | | | |
496
- | API access | | | | ✓ |
497
- | Data extraction | | | | ✓ |
498
- | Custom rate limits | | | | ✓ |
499
- | Webhooks | | | | ✓ |
500
-
501
- ---
502
-
503
- ## Tech Stack
504
-
505
- - **Backend**: Node.js + Express + WebSocket (ws)
506
- - **Database**: SQLite (via better-sqlite3) with migration runner
507
- - **Auth**: JWT + bcrypt + session tokens (domain-locked)
508
- - **Caching**: In-memory TTL cache + batched analytics queue
509
- - **Payments**: Stripe integration with billing portal
510
- - **Frontend**: Vanilla HTML/CSS/JS (no framework dependencies)
511
- - **Framework Wrappers**: React, Vue 3, Svelte (optional)
512
- - **LLM Integration**: LangChain adapter, MCP adapter
513
- - **Security**: Helmet, CORS, CSP, multi-layer rate limiting
514
- - **Containers**: Docker + Docker Compose
515
- - **CI/CD**: GitHub Actions (test + auto-publish to npm)
516
- - **Testing**: Jest + Supertest
517
-
518
- ---
519
-
520
- ## WebDriver BiDi Compatibility
521
-
522
- WAB exposes a `window.__wab_bidi` interface for agents using standardized WebDriver BiDi protocol:
523
-
524
- ```javascript
525
- // Get BiDi context
526
- const context = window.__wab_bidi.getContext();
527
-
528
- // Send BiDi command
529
- const result = await window.__wab_bidi.send({
530
- id: 1,
531
- method: 'wab.executeAction',
532
- params: { name: 'signup', data: {} }
533
- });
534
-
535
- // Supported methods:
536
- // wab.getContext, wab.getActions, wab.executeAction, wab.readContent, wab.getPageInfo
537
- ```
538
-
539
- ---
540
-
541
- ## Real-Time Analytics (WebSocket)
542
-
543
- Connect to `ws://localhost:3000/ws/analytics` for live analytics. Use the built-in `WABWebSocket` client for automatic reconnection with exponential backoff:
544
-
545
- ```javascript
546
- // Recommended: use the auto-reconnecting client
547
- import { WABWebSocket } from './js/ws-client.js';
548
-
549
- const ws = new WABWebSocket('jwt-token', 'site-id');
550
- ws.on('analytic', (data) => console.log(data));
551
- ws.on('reconnecting', ({ attempt, delay }) => console.log(`Reconnecting #${attempt}...`));
552
- ws.connect();
553
- ```
554
-
555
- ```javascript
556
- // Or connect manually
557
- const ws = new WebSocket('ws://localhost:3000/ws/analytics');
558
- ws.onopen = () => ws.send(JSON.stringify({ type: 'auth', token: 'jwt-token', siteId: 'site-id' }));
559
- ws.onmessage = (e) => console.log(JSON.parse(e.data));
560
- ```
561
-
562
- ### WebSocket Message Protocol
563
-
564
- **Client → Server Messages:**
565
-
566
- | Message | Fields | Description |
567
- |---|---|---|
568
- | `auth` | `type`, `token`, `siteId` | Authenticate and subscribe to a site's events |
569
-
570
- ```json
571
- { "type": "auth", "token": "eyJhbGciOi...", "siteId": "uuid-of-site" }
572
- ```
573
-
574
- **Server → Client Messages:**
575
-
576
- | Message Type | Fields | Description |
577
- |---|---|---|
578
- | `auth:success` | `type`, `siteId` | Authentication succeeded |
579
- | `analytic` | `type`, `timestamp`, `actionName`, `agentId`, `success` | Real-time analytics event |
580
- | `error` | `type`, `message` | Error (invalid auth, malformed message) |
581
-
582
- ```json
583
- // Success response
584
- { "type": "auth:success", "siteId": "uuid-of-site" }
585
-
586
- // Analytics event
587
- {
588
- "type": "analytic",
589
- "timestamp": "2024-01-15T10:30:00.000Z",
590
- "actionName": "click-signup",
591
- "agentId": "agent-123",
592
- "triggerType": "click",
593
- "success": true
594
- }
595
-
596
- // Error
597
- { "type": "error", "message": "Invalid message or auth failed" }
598
- ```
599
-
600
- **Connection Lifecycle:**
601
- 1. Connect to `ws://host:port/ws/analytics`
602
- 2. Send `auth` message with valid JWT and site ID
603
- 3. Receive `auth:success` confirmation
604
- 4. Receive `analytic` events as they occur
605
- 5. Server sends heartbeat pings every 30 seconds dead connections are cleaned up automatically
606
-
607
- ---
608
-
609
- ## CDN & Versioning
610
-
611
- Scripts are served at versioned URLs for cache-safe deployments:
612
-
613
- | URL | Description |
614
- |---|---|
615
- | `/script/ai-agent-bridge.js` | Default path |
616
- | `/v1/ai-agent-bridge.js` | Version-pinned (recommended) |
617
- | `/latest/ai-agent-bridge.js` | Always latest (use with caution) |
618
-
619
- ---
620
-
621
- ## Docker
622
-
623
- ```bash
624
- # Quick start
625
- docker compose up -d
626
-
627
- # Or build manually
628
- docker build -t web-agent-bridge .
629
- docker run -p 3000:3000 -e JWT_SECRET=your-secret -e JWT_SECRET_ADMIN=your-admin-secret web-agent-bridge
630
- ```
631
-
632
- ---
633
-
634
- ## Testing
635
-
636
- ```bash
637
- npm test
638
- ```
639
-
640
- Tests cover: authentication, site CRUD, config management, license verification, analytics tracking, and static pages.
641
-
642
- ---
643
-
644
- ## Agent SDK
645
-
646
- WAB includes a built-in SDK for building AI agents. See [`sdk/README.md`](sdk/README.md) for full documentation.
647
-
648
- ```javascript
649
- const puppeteer = require('puppeteer');
650
- const { WABAgent } = require('web-agent-bridge/sdk');
651
-
652
- const browser = await puppeteer.launch();
653
- const page = await browser.newPage();
654
- const agent = new WABAgent(page);
655
-
656
- await agent.navigateAndWait('https://example.com');
657
- const actions = await agent.getActions();
658
- await agent.execute('signup', { email: 'user@test.com' });
659
- await browser.close();
660
- ```
661
-
662
- ### SDK Extras
663
-
664
- The SDK now includes additional helpers for advanced agent workflows:
665
-
666
- ```javascript
667
- // Wait for GDPR consent before proceeding
668
- await agent.waitForConsent();
669
-
670
- // Discover all actions + page meta
671
- const disc = await agent.discover();
672
- console.log(disc.actions, disc.meta);
673
-
674
- // Run a sequence of actions (stops on first failure by default)
675
- const results = await agent.runPipeline([
676
- { name: 'login', params: { email: 'a@b.com', pass: 'secret' } },
677
- { name: 'addToCart', params: { sku: 'ABC123' } },
678
- { name: 'checkout' }
679
- ]);
680
-
681
- // Run actions in parallel
682
- const parallel = await agent.executeParallel([
683
- { name: 'getCartCount' },
684
- { name: 'getWishlistCount' }
685
- ]);
686
-
687
- // Capture screenshot (base64) for vision agents
688
- const b64 = await agent.screenshot({ fullPage: true });
689
- ```
690
-
691
- ---
692
-
693
- ## Framework Packages
694
-
695
- ### Vue 3
696
-
697
- ```bash
698
- npm install @web-agent-bridge/vue
699
- ```
700
-
701
- ```javascript
702
- import { useWAB, useWABAction } from '@web-agent-bridge/vue';
703
-
704
- // In setup()
705
- const { ready, execute } = useWAB({ siteUrl: 'https://example.com' });
706
- const cart = useWABAction('addToCart');
707
-
708
- // In template handler
709
- await cart.run({ sku: 'ABC123' });
710
- console.log(cart.result.value);
711
- ```
712
-
713
- ### Svelte
714
-
715
- ```bash
716
- npm install @web-agent-bridge/svelte
717
- ```
718
-
719
- ```svelte
720
- <script>
721
- import { createWAB, createWABAction } from '@web-agent-bridge/svelte';
722
-
723
- const wab = createWAB();
724
- const cart = createWABAction('addToCart');
725
-
726
- async function add() {
727
- await cart.run({ sku: 'ABC123' });
728
- }
729
- </script>
730
-
731
- {#if $cart.loading}Adding...{/if}
732
- {#if $cart.result}Added!{/if}
733
- <button on:click={add}>Add to Cart</button>
734
- ```
735
-
736
- ### LangChain / LangGraph
737
-
738
- ```bash
739
- npm install @web-agent-bridge/langchain
740
- ```
741
-
742
- ```javascript
743
- const { WABToolkit } = require('@web-agent-bridge/langchain');
744
- const { ChatOpenAI } = require('@langchain/openai');
745
- const { AgentExecutor, createOpenAIToolsAgent } = require('langchain/agents');
746
-
747
- // HTTP mode discover + execute via the WAB server
748
- const toolkit = new WABToolkit({ siteUrl: 'https://shop.example.com' });
749
- const tools = await toolkit.getTools();
750
-
751
- // Browser mode — use with Puppeteer/Playwright
752
- const { WABAgent } = require('web-agent-bridge/sdk');
753
- const toolkit2 = new WABToolkit({ agent: new WABAgent(page) });
754
- const tools2 = await toolkit2.getTools();
755
-
756
- // Pass tools to any LangChain agent
757
- const llm = new ChatOpenAI({ model: 'gpt-4o' });
758
- const agent = await createOpenAIToolsAgent({ llm, tools, prompt });
759
- const executor = new AgentExecutor({ agent, tools });
760
- await executor.invoke({ input: 'Add the first product to my cart' });
761
- ```
762
-
763
- ---
764
-
765
- ## GDPR / CCPA Consent
766
-
767
- Load the consent script after `wab.min.js` to gate agent actions behind user consent:
768
-
769
- ```html
770
- <script src="/script/wab.min.js"></script>
771
- <script src="/script/wab-consent.js"></script>
772
- <script>
773
- WABConsent.showBanner({
774
- policyUrl: '/privacy',
775
- message: 'Allow AI agents to interact with this page?',
776
- onAccept: () => WAB.init({ siteUrl: location.origin }),
777
- onDecline: () => console.log('Agent access declined')
778
- });
779
- </script>
780
- ```
781
-
782
- SDK agents can check consent programmatically:
783
-
784
- ```javascript
785
- const agent = new WABAgent(page);
786
- const ok = await agent.hasConsent(); // true | false
787
- await agent.waitForConsent(); // blocks until Allow is clicked
788
- ```
789
-
790
- ---
791
-
792
- ## Agent Examples
793
-
794
- Ready-to-run agent examples in the [`examples/`](examples/) directory:
795
-
796
- | File | Description |
797
- |---|---|
798
- | `puppeteer-agent.js` | Basic agent using Puppeteer + `window.AICommands` |
799
- | `bidi-agent.js` | Agent using WebDriver BiDi protocol via `window.__wab_bidi` |
800
- | `vision-agent.js` | Vision/NLP agent — resolves natural language intents to actions using a local keyword-based resolver (no external API) |
801
- | `mcp-agent.js` | MCP adapter usage for Claude and GPT with tool discovery and execution |
802
- | `cross-site-agent.js` | Multi-domain orchestration — compare prices across stores, aggregate data, find best deals |
803
-
804
- ## Framework + CMS Examples
805
-
806
- Additional integration examples are available in:
807
-
808
- | Path | Description |
809
- |---|---|
810
- | `examples/next-app-router/` | Next.js App Router integration with `@web-agent-bridge/react` |
811
- | `examples/shopify-hydrogen/` | Hydrogen storefront integration with practical cart actions |
812
- | `examples/wordpress-elementor/` | WordPress + Elementor setup with schema-assisted actions |
813
- | `examples/saas-dashboard/` | Notion-style SaaS dashboard actions for KPI read + workflow triggers |
814
-
815
- ```bash
816
- node examples/puppeteer-agent.js http://localhost:3000
817
- node examples/bidi-agent.js http://localhost:3000
818
- node examples/vision-agent.js http://localhost:3000
819
- ```
820
-
821
- ---
822
-
823
- ## Multi-Database Support
824
-
825
- WAB defaults to SQLite but supports PostgreSQL and MySQL via database adapters.
826
-
827
- ```bash
828
- # SQLite (default no setup needed)
829
- npm start
830
-
831
- # PostgreSQL
832
- npm install pg
833
- DB_ADAPTER=postgresql DATABASE_URL=postgres://user:pass@localhost:5432/wab npm start
834
-
835
- # MySQL
836
- npm install mysql2
837
- DB_ADAPTER=mysql DATABASE_URL=mysql://user:pass@localhost:3306/wab npm start
838
- ```
839
-
840
- ### When to Choose Which Database
841
-
842
- | Scenario | Recommended DB | Why |
843
- |---|---|---|
844
- | Local dev / prototyping | SQLite | Zero setup, single file, instant |
845
- | Small production (< 100 sites) | SQLite | Fast, no external dependencies |
846
- | Medium production (100-10K sites) | PostgreSQL | Better concurrency, JSONB support |
847
- | Large / enterprise production | PostgreSQL | Replication, backups, scalability |
848
- | Existing MySQL infrastructure | MySQL | Integrate with what you already use |
849
-
850
- See [`server/models/adapters/`](server/models/adapters/) for adapter implementations.
851
-
852
- ---
853
-
854
- ## Security Architecture
855
-
856
- WAB implements defense-in-depth to protect the bridge from misuse:
857
-
858
- ### Secure License Exchange
859
-
860
- 1. **Dashboard snippet (recommended):** `siteId` + `configEndpoint`. The browser sends `POST /api/license/token` with `{ siteId }`; the server checks **Origin** against the site’s registered domain and issues a session token.
861
- 2. **Legacy:** `licenseKey` + `configEndpoint` (or deprecated `_licenseKey`) still works for token exchange but should not be embedded in public HTML.
862
- 3. **Session** is domain-locked (1h TTL); **analytics** use `sessionToken` on `POST /api/license/track` (not the license key).
863
- 4. **WebSocket** `/ws/analytics`: user JWT must **own** the `siteId`; admin JWT may observe any site.
864
-
865
- ```
866
- Client Server
867
- │── POST /api/license/token ──→│ { siteId } + Origin header
868
- │ │ domain match sessionToken
869
- │←── { sessionToken, tier } ──│
870
- │── POST /api/license/track ─→│ { sessionToken, actionName } + Origin
871
- ```
872
-
873
- **Production:** set `JWT_SECRET`, `JWT_SECRET_ADMIN`, `STRIPE_WEBHOOK_SECRET`, `ALLOWED_ORIGINS`, and create the first admin via `BOOTSTRAP_ADMIN_*` or `node scripts/create-admin.js`.
874
-
875
- ### Security Sandbox
876
-
877
- Every bridge instance runs inside a `SecuritySandbox` that provides:
878
-
879
- - **Session tokens** — Unique cryptographic token per session prevents replay attacks
880
- - **Origin validation** — Only whitelisted origins can interact with the bridge
881
- - **Command validation** — All commands are validated for format, length, and blocklist
882
- - **Audit logging** — Every action is logged with timestamp, agent fingerprint, and status
883
- - **Escalation protection** — Attempts to access higher-tier features trigger automatic lockdown after 5 violations
884
- - **Auto-lockdown** — Bridge becomes read-only when security violations are detected
885
-
886
- ```javascript
887
- // Get security status
888
- const info = bridge.getPageInfo();
889
- console.log(info.security);
890
- // { sandboxActive: true, locked: false, sessionToken: "a3f2..." }
891
-
892
- // View audit log
893
- const audit = bridge.security.getAuditLog(20);
894
- ```
895
-
896
- ### Selector Restrictions
897
-
898
- Block sensitive page sections from agent access:
899
-
900
- ```javascript
901
- window.AIBridgeConfig = {
902
- restrictions: {
903
- blockedSelectors: [".private", "[data-private]", "#payment-form"],
904
- allowedSelectors: [".public-content"]
905
- }
906
- };
907
- ```
908
-
909
- ---
910
-
911
- ## Self-Healing Selectors
912
-
913
- Modern SPAs frequently change their DOM structure. WAB's self-healing system ensures selectors keep working even when the page changes:
914
-
915
- ### How It Works
916
-
917
- 1. **Fingerprinting** — When actions are discovered, WAB stores a rich fingerprint of each element (tag, id, classes, text, ARIA attributes, position)
918
- 2. **7-Strategy Resolution** — When a selector breaks, WAB tries these strategies in order:
919
- - `data-wab-id` attribute (most stable — add to your HTML)
920
- - `data-testid` attribute
921
- - Element ID
922
- - `aria-label` (semantic, usually survives redesigns)
923
- - `name` attribute
924
- - Fuzzy text matching (bigram similarity > 70%)
925
- - Role + position heuristic
926
- 3. **SPA Observer** — A `MutationObserver` watches for DOM changes and automatically re-discovers actions with a 500ms debounce
927
-
928
- ```javascript
929
- // Check healing stats
930
- const info = bridge.getPageInfo();
931
- console.log(info.selfHealing);
932
- // { tracked: 12, healed: 3, failed: 0 }
933
-
934
- // Listen for healing events
935
- bridge.events.on('selector:healed', (data) => {
936
- console.log(`Healed: ${data.action} via ${data.strategy}`);
937
- });
938
- ```
939
-
940
- ### Best Practices for Site Owners
941
-
942
- Add `data-wab-id` attributes to critical elements for maximum stability:
943
-
944
- ```html
945
- <button data-wab-id="signup-btn">Sign Up</button>
946
- <form data-wab-id="login-form">...</form>
947
- ```
948
-
949
- ---
950
-
951
- ## Stealth Mode
952
-
953
- For sites with anti-bot protection, WAB can simulate human-like interaction patterns. **Stealth mode requires explicit consent** to ensure ethical use.
954
-
955
- ```javascript
956
- window.AIBridgeConfig = {
957
- stealth: {
958
- enabled: true,
959
- consent: true // Required confirms site owner authorizes human-like patterns
960
- }
961
- };
962
- ```
963
-
964
- > **⚠️ Ethical Use Policy:** Stealth mode is designed for accessibility and testing on your own websites. Using it to bypass security controls on sites you do not own may violate terms of service and applicable laws.
965
-
966
- When enabled, all interactions use:
967
-
968
- | Feature | Description |
969
- |---|---|
970
- | **Mouse event chain** | `mouseover → mouseenter → mousemove → mousedown → mouseup → click` with natural coordinates |
971
- | **Typing simulation** | Character-by-character input with 30-120ms delays per keystroke |
972
- | **Scroll easing** | Multi-step scrolling with variable speed |
973
- | **Random delays** | 50-400ms natural pauses between actions |
974
-
975
- ```javascript
976
- // Enable/disable at runtime (consent required)
977
- bridge.stealth.enable(true); // true = consent granted
978
- bridge.stealth.disable();
979
- ```
980
-
981
- ---
982
-
983
- ## CLI
984
-
985
- Install globally or use via npx:
986
-
987
- ```bash
988
- # Run the server
989
- npx web-agent-bridge start
990
- npx web-agent-bridge start --port 8080
991
-
992
- # Initialize a new project
993
- npx web-agent-bridge init
994
- ```
995
-
996
- ---
997
-
998
- ## Environment Variables
999
-
1000
- See `.env.example`. Important:
1001
-
1002
- ```
1003
- PORT=3000
1004
- NODE_ENV=development
1005
- JWT_SECRET=long-random-user-signing-secret
1006
- JWT_SECRET_ADMIN=long-random-admin-signing-secret # required in production
1007
- ALLOWED_ORIGINS=http://localhost:3000,https://your-app.com
1008
- STRIPE_WEBHOOK_SECRET=whsec_... # Stripe webhook verify
1009
- CREDENTIALS_ENCRYPTION_KEY=... # optional SMTP password encryption
1010
- DB_ADAPTER=sqlite
1011
- DATABASE_URL=
1012
- ```
1013
-
1014
- First admin: set `BOOTSTRAP_ADMIN_EMAIL` / `BOOTSTRAP_ADMIN_PASSWORD` when the `admins` table is empty, or run `node scripts/create-admin.js <email> <password>`.
1015
-
1016
- ---
1017
-
1018
- ## Real-time Negotiation Engine
1019
-
1020
- Site owners define negotiation rules. AI agents negotiate prices in multi-round sessions:
1021
-
1022
- ```javascript
1023
- // Agent opens a negotiation session
1024
- const session = await fetch('/api/sovereign/negotiation/sessions', {
1025
- method: 'POST',
1026
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1027
- body: JSON.stringify({
1028
- siteId: 'site-uuid',
1029
- agentId: 'agent-id',
1030
- originalPrice: 49.99,
1031
- itemId: 'product-123',
1032
- itemName: 'Olive Oil 1L'
1033
- })
1034
- }).then(r => r.json());
1035
-
1036
- // Agent makes a counter-offer
1037
- const counter = await fetch(`/api/sovereign/negotiation/sessions/${session.sessionId}/propose`, {
1038
- method: 'POST',
1039
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1040
- body: JSON.stringify({
1041
- agentId: 'agent-id',
1042
- proposedPrice: 39.99
1043
- })
1044
- }).then(r => r.json());
1045
- // { status: 'accepted', finalPrice: 42.49, message: 'Deal! ...' }
1046
- ```
1047
-
1048
- ### Condition Types
1049
- | Condition | Description |
1050
- |---|---|
1051
- | `bulk_quantity` | Discounts based on order quantity |
1052
- | `loyalty` | Rewards for repeat customers |
1053
- | `time_based` | Happy hour / flash sale windows |
1054
- | `first_purchase` | Welcome discount for new buyers |
1055
- | `cart_value` | Minimum cart value threshold |
1056
- | `seasonal` | Date-range seasonal promotions |
1057
- | `membership` | Member-only pricing |
1058
- | `referral` | Referral-based discounts |
1059
-
1060
- ---
1061
-
1062
- ## Anti-Hallucination Shield
1063
-
1064
- Cross-verification engine that catches AI hallucinations before they reach users:
1065
-
1066
- ```javascript
1067
- // Verify a price
1068
- const result = await fetch('/api/sovereign/verify/price', {
1069
- method: 'POST',
1070
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1071
- body: JSON.stringify({
1072
- siteId: 'site-uuid',
1073
- domValue: 29.99,
1074
- visionValue: 29.99,
1075
- category: 'electronics',
1076
- itemName: 'USB Cable'
1077
- })
1078
- }).then(r => r.json());
1079
- // { verified: true, confidence: 0.98, severity: 'none', layers: { dom_vision: { match: true }, ... } }
1080
-
1081
- // Verify text content
1082
- const textResult = await fetch('/api/sovereign/verify/text', {
1083
- method: 'POST',
1084
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1085
- body: JSON.stringify({
1086
- siteId: 'site-uuid',
1087
- source: 'dom',
1088
- value: 'Free shipping on orders over $50',
1089
- expected: 'Free shipping on orders over $50'
1090
- })
1091
- }).then(r => r.json());
1092
- // { verified: true, similarity: 1.0 }
1093
- ```
1094
-
1095
- ### Verification Layers
1096
- 1. **DOM vs Vision** — Compares DOM-extracted price with screenshot OCR value
1097
- 2. **Market Benchmark** — Validates against historical price benchmarks for the category
1098
- 3. **Temporal Consistency** — Checks if price changed suspiciously since last verification
1099
- 4. **Composite Score** — Weighted combination of all layers with severity classification
1100
-
1101
- ---
1102
-
1103
- ## Community Agent Hub
1104
-
1105
- Pre-built YAML agent templates for common use cases. Run any template from the CLI:
1106
-
1107
- ```bash
1108
- # List available templates
1109
- npx wab-agent templates
1110
-
1111
- # Run a template
1112
- npx wab-agent run olive-oil-tunisia --budget 50 --region tunis
1113
-
1114
- # Run with custom server
1115
- npx wab-agent run hotel-direct-booking --server https://yourserver.com --checkin 2025-01-15
1116
- ```
1117
-
1118
- ### Available Templates
1119
- | Template | Description |
1120
- |---|---|
1121
- | `olive-oil-tunisia` | Find olive oil from small Tunisian farms |
1122
- | `hotel-direct-booking` | Book hotels directly, bypass aggregators |
1123
- | `artisan-marketplace` | Handmade products from independent artisans |
1124
- | `grocery-price-compare` | Compare grocery prices across local stores |
1125
- | `freelancer-direct` | Find freelancers without platform fees |
1126
- | `restaurant-direct` | Order from restaurants without delivery apps |
1127
- | `book-price-scout` | Find books from indie bookstores |
1128
- | `flight-deal-hunter` | Find flights direct from airlines |
1129
- | `electronics-price-tracker` | Track electronics prices with history |
1130
- | `local-services` | Find local service providers |
1131
- | `organic-farm-fresh` | Organic produce direct from farms |
1132
-
1133
- ### Create Your Own Template
1134
-
1135
- ```yaml
1136
- name: my-custom-agent
1137
- description: My custom agent template
1138
- goal: Find the best deals on custom products
1139
- version: "1.0"
1140
- target_sites:
1141
- - https://example.com
1142
- parameters:
1143
- budget:
1144
- type: number
1145
- default: 100
1146
- description: Maximum budget
1147
- actions:
1148
- - name: discover
1149
- wab_action: discover
1150
- - name: search
1151
- wab_action: execute
1152
- action_name: search
1153
- params:
1154
- query: "{{keyword}}"
1155
- - name: negotiate
1156
- wab_action: negotiate
1157
- params:
1158
- item_id: "{{item_id}}"
1159
- max_price: "{{budget}}"
1160
- negotiation:
1161
- enabled: true
1162
- max_rounds: 3
1163
- accept_threshold: 0.85
1164
- fairness_rules:
1165
- - Prefer independent sellers over large platforms
1166
- - Verify all prices before purchase
1167
- ```
1168
-
1169
- ---
1170
-
1171
- ## Commander Agent System
1172
-
1173
- The Commander is a local-first mission orchestration engine that decomposes high-level goals into task DAGs and distributes work across specialized agents:
1174
-
1175
- ```javascript
1176
- // Create a mission
1177
- const mission = await fetch('/api/commander/missions', {
1178
- method: 'POST',
1179
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1180
- body: JSON.stringify({
1181
- goal: 'Find the cheapest olive oil across 5 stores',
1182
- strategy: 'parallel',
1183
- agents: ['researcher-1', 'analyst-1', 'negotiator-1']
1184
- })
1185
- }).then(r => r.json());
1186
-
1187
- // Launch mission
1188
- await fetch(`/api/commander/missions/${mission.id}/launch`, { method: 'POST', headers: { 'Authorization': 'Bearer ' + token } });
1189
-
1190
- // Check status
1191
- const status = await fetch(`/api/commander/missions/${mission.id}`, { headers: { 'Authorization': 'Bearer ' + token } }).then(r => r.json());
1192
- // → { status: 'completed', tasks: [...], result: { bestPrice: 12.99, store: 'farm-direct' } }
1193
- ```
1194
-
1195
- ### Commander Capabilities
1196
- | Feature | Description |
1197
- |---|---|
1198
- | **Mission Decomposition** | Breaks high-level goals into task DAGs with dependency tracking |
1199
- | **Agent Registry** | Tracks agent capabilities, availability, and performance history |
1200
- | **Parallel Execution** | Runs independent tasks concurrently across multiple agents |
1201
- | **Learning Integration** | Records outcomes for reinforcement learning feedback |
1202
- | **Edge Coordination** | Distributes compute-heavy tasks to edge nodes |
1203
-
1204
- ---
1205
-
1206
- ## Edge Compute System
1207
-
1208
- Transform every user device into a sovereign AI node — no central cloud required:
1209
-
1210
- ```javascript
1211
- // Register a device as an edge node
1212
- const node = await fetch('/api/commander/edge/nodes', {
1213
- method: 'POST',
1214
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1215
- body: JSON.stringify({
1216
- name: 'my-laptop',
1217
- capabilities: { cpu: 8, ram: 16384, gpu: true },
1218
- supportedTasks: ['text-inference', 'vision-analysis', 'price-comparison']
1219
- })
1220
- }).then(r => r.json());
1221
-
1222
- // List available edge nodes
1223
- const nodes = await fetch('/api/commander/edge/nodes', { headers: { 'Authorization': 'Bearer ' + token } }).then(r => r.json());
1224
- ```
1225
-
1226
- | Feature | Description |
1227
- |---|---|
1228
- | **Hardware Profiling** | Detects CPU, RAM, GPU capabilities per node |
1229
- | **AES-256-GCM Encryption** | All inter-node data is encrypted end-to-end |
1230
- | **Weighted Load Balancing** | Routes tasks based on hardware + availability scores |
1231
- | **Heartbeat Health Monitoring** | Auto-failover when nodes become unresponsive |
1232
- | **Swarm Formation** | Capability-based clustering of nodes for distributed tasks |
1233
-
1234
- ---
1235
-
1236
- ## Swarm Execution Engine
1237
-
1238
- Launch multiple agents in parallel to solve a single task, then intelligently merge their outputs:
1239
-
1240
- ```javascript
1241
- // Launch a swarm task
1242
- const swarm = await fetch('/api/premium/v2/swarm/execute', {
1243
- method: 'POST',
1244
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1245
- body: JSON.stringify({
1246
- task: 'Find best laptop deals under $1000',
1247
- strategy: 'parallel', // parallel | sequential | hybrid
1248
- agentCount: 4,
1249
- roles: ['researcher', 'analyst', 'price-checker', 'reviewer'],
1250
- mergeStrategy: 'best-score' // best-score | fairness-weighted | consensus
1251
- })
1252
- }).then(r => r.json());
1253
- // → { swarmId: '...', agents: 4, status: 'running' }
1254
-
1255
- // Get merged results
1256
- const results = await fetch(`/api/premium/v2/swarm/${swarm.swarmId}`, {
1257
- headers: { 'Authorization': 'Bearer ' + token }
1258
- }).then(r => r.json());
1259
- // { status: 'completed', merged: { bestDeal: {...}, confidence: 0.94 } }
1260
- ```
1261
-
1262
- ---
1263
-
1264
- ## Fairness Engine
1265
-
1266
- A neutrality layer ensuring AI agents give equal opportunity to small and large sites, preventing monopolistic concentration of agent traffic:
1267
-
1268
- ```javascript
1269
- // Fairness-weighted search (instead of pure relevance)
1270
- const results = await fetch('/api/discovery/search?q=olive+oil&fairness=true', {
1271
- headers: { 'Authorization': 'Bearer ' + token }
1272
- }).then(r => r.json());
1273
- // Small farms ranked alongside Amazon weighted by neutrality score, not just SEO
1274
-
1275
- // Register site in WAB directory
1276
- await fetch('/api/discovery/register', {
1277
- method: 'POST',
1278
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1279
- body: JSON.stringify({
1280
- domain: 'small-farm.example.com',
1281
- category: 'food',
1282
- commissionRate: 0, // Direct — no middleman
1283
- independentSeller: true
1284
- })
1285
- }).then(r => r.json());
1286
- ```
1287
-
1288
- ### How Neutrality Scoring Works
1289
- | Factor | Weight | Description |
1290
- |---|---|---|
1291
- | **Configuration completeness** | 25% | How well the site has configured WAB |
1292
- | **Trust score** | 25% | Reputation attestations from the agent network |
1293
- | **Transparency** | 25% | Commission disclosure, pricing clarity |
1294
- | **Responsiveness** | 25% | API response time, uptime, action success rate |
1295
-
1296
- Small independent sites with good WAB configuration can outrank large platforms on fairness-weighted searches.
1297
-
1298
- ---
1299
-
1300
- ## Agent Memory System
1301
-
1302
- Persistent behavioral memory allowing agents to remember user preferences, learn patterns, and build associations:
1303
-
1304
- ```javascript
1305
- // Store a memory
1306
- await fetch('/api/premium/v2/memory', {
1307
- method: 'POST',
1308
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1309
- body: JSON.stringify({
1310
- agentId: 'agent-1',
1311
- type: 'preference', // preference | interaction | correction | pattern
1312
- category: 'purchase', // navigation | purchase | search | form | custom
1313
- key: 'preferred-brand',
1314
- value: 'organic-only',
1315
- importance: 0.9
1316
- })
1317
- }).then(r => r.json());
1318
-
1319
- // Recall memories
1320
- const memories = await fetch('/api/premium/v2/memory/agent-1?category=purchase&limit=10', {
1321
- headers: { 'Authorization': 'Bearer ' + token }
1322
- }).then(r => r.json());
1323
-
1324
- // Create associations
1325
- await fetch('/api/premium/v2/memory/associate', {
1326
- method: 'POST',
1327
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1328
- body: JSON.stringify({
1329
- sourceId: 'memory-1',
1330
- targetId: 'memory-2',
1331
- relationship: 'leads_to' // leads_to | similar_to | replaces | depends_on
1332
- })
1333
- }).then(r => r.json());
1334
- ```
1335
-
1336
- ---
1337
-
1338
- ## Vision Analysis Service
1339
-
1340
- Multi-provider screenshot analysis for interactive element detection and data extraction:
1341
-
1342
- ```javascript
1343
- // Analyze a screenshot
1344
- const analysis = await fetch('/api/premium/v2/vision/analyze', {
1345
- method: 'POST',
1346
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1347
- body: JSON.stringify({
1348
- screenshot: 'base64-encoded-image...',
1349
- provider: 'auto', // auto | local | openai | anthropic | ollama
1350
- extractElements: true
1351
- })
1352
- }).then(r => r.json());
1353
- // { elements: [{ type: 'button', text: 'Add to Cart', selector: '#add-btn', confidence: 0.95, bbox: [120, 340, 200, 40] }] }
1354
-
1355
- // Extract interactive elements only
1356
- const elements = await fetch('/api/premium/v2/vision/elements', {
1357
- method: 'POST',
1358
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1359
- body: JSON.stringify({ screenshot: 'base64...', types: ['button', 'input', 'link'] })
1360
- }).then(r => r.json());
1361
- ```
1362
-
1363
- ### Supported Vision Providers
1364
- | Provider | Local? | Description |
1365
- |---|---|---|
1366
- | **Moondream** | ✅ | Lightweight local vision model |
1367
- | **Ollama** | ✅ | Local models via Ollama (llava, bakllava) |
1368
- | **OpenAI** | ❌ | GPT-4 Vision |
1369
- | **Anthropic** | | Claude Vision |
1370
-
1371
- ---
1372
-
1373
- ## Plugin Architecture
1374
-
1375
- Dynamic plugin system allowing third-party extensions:
1376
-
1377
- ```javascript
1378
- // List available plugins
1379
- const plugins = await fetch('/api/premium/v2/plugins', {
1380
- headers: { 'Authorization': 'Bearer ' + token }
1381
- }).then(r => r.json());
1382
-
1383
- // Install a plugin for your site
1384
- await fetch('/api/premium/v2/plugins/price-alert/install', {
1385
- method: 'POST',
1386
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1387
- body: JSON.stringify({ siteId: 'site-uuid', config: { threshold: 10 } })
1388
- }).then(r => r.json());
1389
-
1390
- // Execute a plugin hook
1391
- await fetch('/api/premium/v2/plugins/price-alert/hooks', {
1392
- method: 'POST',
1393
- headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1394
- body: JSON.stringify({ hook: 'onPriceChange', data: { oldPrice: 49.99, newPrice: 39.99 } })
1395
- }).then(r => r.json());
1396
- ```
1397
-
1398
- ---
1399
-
1400
- ## Premium Traffic Intelligence
1401
-
1402
- Advanced bot detection and traffic profiling for premium sites:
1403
-
1404
- | Capability | Description |
1405
- |---|---|
1406
- | **30+ Bot Types** | Detects Google, Bing, ChatGPT, Claude, Perplexity, and more |
1407
- | **Behavioral Profiling** | Classifies agent behavior by signature, platform, and type |
1408
- | **Anomaly Detection** | Spike detection and pattern analysis for unusual traffic |
1409
- | **Security Exploit Detection** | Flags SQL injection, XSS patterns, and rate anomalies |
1410
- | **Webhook Alerting** | Triggers webhooks on suspicious activity |
1411
- | **Compliance Audit Logging** | Full audit trail for regulatory compliance |
1412
-
1413
- ---
1414
-
1415
- ## WAB-MCP Adapter
1416
-
1417
- Expose WAB site capabilities as [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) tools for Claude, GPT, Gemini, and other MCP-compatible AI agents:
1418
-
1419
- ```javascript
1420
- const { WABMCPAdapter } = require('wab-mcp-adapter');
1421
-
1422
- // Create adapter for a WAB-enabled site
1423
- const adapter = new WABMCPAdapter({
1424
- siteUrl: 'https://shop.example.com',
1425
- transport: 'http' // http | websocket | direct
1426
- });
1427
-
1428
- // Get MCP tool definitions
1429
- const tools = await adapter.getTools();
1430
- // → [{ name: 'discover', description: '...', inputSchema: {...} }, ...]
1431
-
1432
- // Execute via MCP
1433
- const result = await adapter.executeTool('execute_action', {
1434
- name: 'addToCart',
1435
- params: { sku: 'ABC123' }
1436
- });
1437
- ```
1438
-
1439
- ### Built-in MCP Tools
1440
- | Tool | Description |
1441
- |---|---|
1442
- | `discover` | Auto-discover available actions on a WAB site |
1443
- | `get_actions` | Get list of all actions with parameters |
1444
- | `execute_action` | Execute a specific action |
1445
- | `read_content` | Read content from the page |
1446
- | `get_page_info` | Get page metadata |
1447
- | `fairness_search` | Search the WAB directory with fairness weighting |
1448
- | `authenticate` | Authenticate an agent with the site |
1449
-
1450
- ---
1451
-
1452
- ## WAB Browser (Desktop)
1453
-
1454
- Standalone Electron desktop browser with built-in privacy and fairness features:
1455
-
1456
- - **Ad Blocker** — 80+ blocked ad domains + URL pattern matching + cosmetic CSS rules
1457
- - **Scam Shield** — Detects suspicious TLDs and brand-name spoofing in URLs
1458
- - **Fairness Ranking** Prioritizes independent sites, flags big-tech concentration
1459
- - **Agent Chat** Built-in AI assistant panel for browsing help
1460
- - **Notifications** — Page analysis with safety and fairness alerts
1461
- - **Ghost Mode** — Privacy-first browsing with no tracking
1462
- - **Smart Search** — WAB Search integration for independent search
1463
- - **Desktop/Mobile Toggle** — Switch user-agent for responsive testing
1464
-
1465
- ```bash
1466
- # Run the WAB Browser
1467
- cd wab-browser
1468
- npm install
1469
- npx electron .
1470
-
1471
- # Build installer (Windows NSIS)
1472
- npm run build:win
1473
- ```
1474
-
1475
- ---
1476
-
1477
- ## PWA Browser (Mobile)
1478
-
1479
- Progressive Web App browser for Android and iOS — installable from any mobile browser:
1480
-
1481
- - **Ad Blocker** — 80+ ad domain blacklist + URL pattern matching
1482
- - **Scam Detection** — Suspicious TLD alerts and brand-name spoofing checks
1483
- - **Fairness Mode** — Filters big-tech sites to promote independent alternatives
1484
- - **Offline-First** — Service worker caches shell assets for offline launch
1485
- - **WAB Search** — Independent search engine with multi-source aggregation, autocomplete, and trending
1486
- - **AI Agent Chat** — Real AI agent (OpenAI / local Ollama / smart fallback) with conversation memory, web search, and security analysis
1487
-
1488
- Install at: `https://yourserver.com/pwa/`
1489
-
1490
- ---
1491
-
1492
- ## WordPress Plugin
1493
-
1494
- Native WordPress plugin for adding WAB support to any WordPress site:
1495
-
1496
- ```bash
1497
- # Install
1498
- cp -r web-agent-bridge-wordpress/ /wp-content/plugins/web-agent-bridge/
1499
- ```
1500
-
1501
- | Feature | Description |
1502
- |---|---|
1503
- | **Settings Page** | Configure API base URL, site ID, permissions |
1504
- | **Per-Page Actions** | Meta box for adding custom WAB actions per page/post |
1505
- | **Discovery Document** | Auto-generates WAB discovery endpoint |
1506
- | **Dashboard Widget** | Shows WAB status and agent interaction stats |
1507
- | **Shortcode** | `[wab_bridge]` shortcode for embedding WAB on specific pages |
1508
- | **Hooks API** | `wab_before_action` / `wab_after_action` for custom logic |
1509
-
1510
- See [`web-agent-bridge-wordpress/README.md`](web-agent-bridge-wordpress/README.md) for full documentation.
1511
-
1512
- ---
1513
-
1514
- ## WAB Protocol Specification
1515
-
1516
- The full normative specification is available at [`docs/SPEC.md`](docs/SPEC.md):
1517
-
1518
- | Layer | Description |
1519
- |---|---|
1520
- | **Protocol Layer** | Discovery document format, command protocol, fairness protocol |
1521
- | **Runtime Layer** | `window.AICommands` interface, auto-discovery engine, security sandbox |
1522
- | **Transport Layer** | JavaScript global, WebSocket, HTTP, WebDriver BiDi, MCP |
1523
-
1524
- ### 5-Phase Lifecycle
1525
- 1. **Discover** Agent finds WAB discovery document (`.well-known/wab.json` or script tag)
1526
- 2. **Authenticate** Agent exchanges `siteId` for session token
1527
- 3. **Plan** Agent reads available actions and page metadata
1528
- 4. **Execute** — Agent runs actions through the bridge
1529
- 5. **Confirm** — Results are verified via Anti-Hallucination Shield
1530
-
1531
- ---
1532
-
1533
- ## License
1534
-
1535
- MIT Free to use, modify, and distribute.
1
+ # Web Agent Bridge (WAB)
2
+
3
+ [![npm](https://img.shields.io/npm/v/web-agent-bridge)](https://www.npmjs.com/package/web-agent-bridge)
4
+ [![npm downloads](https://img.shields.io/npm/dm/web-agent-bridge?label=npm%20downloads&color=red)](https://www.npmjs.com/package/web-agent-bridge)
5
+ [![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-)
6
+ [![CI](https://github.com/abokenan444/web-agent-bridge/actions/workflows/ci.yml/badge.svg)](https://github.com/abokenan444/web-agent-bridge/actions/workflows/ci.yml)
7
+ [![License: Open Core](https://img.shields.io/badge/License-Open_Core-blue.svg)](LICENSE)
8
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen.svg)](https://nodejs.org/)
9
+ [![Docker](https://img.shields.io/badge/docker-ready-blue.svg)](https://hub.docker.com/)
10
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
11
+ [![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?logo=discord&logoColor=white)](https://discord.gg/NnbpJYEF)
12
+
13
+ > **robots.txt told bots what NOT to do. WAB tells AI agents what they CAN do.**
14
+
15
+ 🌐 **Live Website:** [https://webagentbridge.com](https://webagentbridge.com) — Try the Agent Workspace, dashboards, and many more features live.
16
+
17
+ **English** | **[العربية](README.ar.md)**
18
+
19
+ WAB is **the open AI↔Web protocol and agent platform**. What started as a small middleware script has grown into a full stack: a standardized `window.AICommands` interface (like **OpenAPI for human-facing pages**), a sovereign desktop browser, a phone-shield communication layer, DNS-level discovery, an agent mesh, a multi-module API gateway, and SDKs for React/Vue/Svelte/LangChain. Website owners control what AI can do; agents discover capabilities, execute commands, and interact with sites accurately — no DOM parsing, no scraping, no guesswork.
20
+
21
+ ### Three Paths to WAB
22
+
23
+ | Path | For | How |
24
+ |---|---|---|
25
+ | **🏢 Website Owner** | Control how AI interacts with your site | Embed the script, configure permissions |
26
+ | **🤖 Agent Developer** | Build reliable agents that work on any WAB-enabled site | Use `window.AICommands` or the Agent SDK |
27
+ | **🔧 Self-Hosting** | Run the full WAB platform for your organization | Clone, deploy, manage licenses & analytics |
28
+ | **WordPress** | Sites powered by WP | Use the **[Web Agent Bridge WordPress plugin](web-agent-bridge-wordpress/README.md)** (settings, shortcode, per-page disable, hooks) |
29
+
30
+ ---
31
+
32
+ ## Features
33
+
34
+ - **Auto-Discovery** — Automatically detects buttons, forms, and navigation on the page
35
+ - **Structured Auto-Discovery** — Detects schema.org JSON-LD + microdata products/offers and exposes read actions
36
+ - **Commerce + Booking Intents** — Detects common actions like add-to-cart, checkout, and booking/reservation flows
37
+ - **Permission System** — Granular control over what AI agents can do (click, fill forms, API access, etc.)
38
+ - **Standardized Interface** — Unified `window.AICommands` object any agent can consume
39
+ - **Secure License Exchange** — Embed uses public `siteId` + `/api/license/token`; long-lived license keys stay in the owner dashboard, not in HTML
40
+ - **Rate Limiting** — Multi-dimensional abuse protection (IP + license key + site)
41
+ - **Analytics Dashboard** — Track how AI agents interact with your site
42
+ - **Real-Time Analytics** — WebSocket-based live event streaming with auto-reconnection
43
+ - **In-Memory Caching** — TTL-based cache layer reduces DB reads on hot paths
44
+ - **Analytics Queue** — Batched writes with transaction support for high-throughput tracking
45
+ - **WebDriver BiDi Compatible** — Standard protocol support via `window.__wab_bidi`
46
+ - **CDN Versioning** — Serve scripts via versioned URLs (`/v1/ai-agent-bridge.js`, `/latest/ai-agent-bridge.js`)
47
+ - **Docker Ready** — One-command deployment with Docker Compose
48
+ - **DB Migrations** — Numbered SQL migration runner with tracking table
49
+ - **Custom Actions** — Register your own actions with custom handlers
50
+ - **Subscription Tiers** — Free core + paid premium features (API access, analytics, automated login)
51
+ - **Event System** — Subscribe to bridge events for monitoring
52
+ - **Security Sandbox** — Origin validation, session tokens, command signing, audit logging, auto-lockdown
53
+ - **Self-Healing Selectors** — Resilient element resolution with fuzzy matching for dynamic SPAs
54
+ - **Stealth Mode** — Human-like interaction patterns (requires explicit consent)
55
+ - **Multi-Database** — SQLite (default), PostgreSQL, MySQL via pluggable adapters
56
+ - **Agent SDK** — Built-in SDK for building AI agents with Puppeteer/Playwright
57
+ - **React Package** — `@web-agent-bridge/react` with `WABProvider`, `useWAB`, `useWABAction`, and `useWABActions`
58
+ - **Vue Package** — `@web-agent-bridge/vue` composables (`useWAB`, `useWABAction`, `useWABActions`) for Vue 3+
59
+ - **Svelte Package** — `@web-agent-bridge/svelte` stores (`createWAB`, `createWABAction`) for Svelte 3+
60
+ - **LangChain Adapter** — `@web-agent-bridge/langchain` wraps WAB actions as LangChain tools for LLM agents
61
+ - **GDPR/CCPA Consent** — Optional `wab-consent.js` banner with `WABConsent.showBanner()` and `hasConsent()` gate
62
+ - **Admin Dashboard** — User management, tier grants, system analytics
63
+ - **Stripe Integration** — Payment processing with customer portal
64
+ - **Plugin Architecture** — Dynamic plugin system with hook-based execution, per-site installation, priority ordering, ratings, and audit logging
65
+ - **Vision Analysis Service** — Multi-provider screenshot analysis (local Moondream, OpenAI, Anthropic, Ollama) with interactive element detection, bounding box extraction, and AES-256-GCM encrypted API keys
66
+ - **Fairness Engine** — Neutrality layer ensuring AI agents give equal opportunity to small and large sites with fairness-weighted search, commission transparency tracking, and trust signature validation
67
+ - **Agent Memory System** — Persistent behavioral memory with 4 memory types, 5 categories, semantic associations, importance scoring, and TTL-based expiration
68
+ - **Premium Traffic Intelligence** — Advanced bot detection (30+ agent types), behavioral profiling, anomaly/spike detection, security exploit detection (SQLi, XSS), and webhook alerting
69
+ - **E-Mail Service** — SMTP-based transactional emails (welcome, registration, password reset, contact) with branded HTML templates
70
+ - **NoScript Fallback** — 1×1 tracking pixel endpoint for analytics collection when JavaScript is unavailable
71
+ - **WAB-MCP Adapter** — Expose WAB site capabilities as MCP tools for Claude, GPT, Gemini, and other MCP-compatible AI agents
72
+ - **WordPress Plugin** — Native WordPress plugin with settings page, per-page action meta boxes, discovery document generation, and dashboard widget
73
+ - **WAB Browser (Desktop)** — Standalone Electron desktop browser with built-in ad blocker (80+ domains), scam shield, fairness ranking, agent chat, bookmarks, history, and WAB protocol support. *Desktop source is maintained in a separate private build pipeline (`wab-browser/`); the PWA source below is fully open.*
74
+ - **PWA Browser (Mobile)** Progressive Web App browser for Android/iOS with ad blocking (80+ domains), WAB Search engine, scam detection, fairness ranking, real AI agent chat, and offline-first service worker. Full source at `public/pwa/`.
75
+ - **Schema Discovery SDK** — Server-side extraction of schema.org JSON-LD Product nodes from HTML with automatic WAB action hint generation
76
+
77
+ ### v2.0Digital Fortress Features
78
+
79
+ - **Real-time Negotiation Engine** — AI agents negotiate prices directly with WAB-enabled sites using multi-round sessions. 8 condition types (bulk, loyalty, time-based, first-purchase, cart-value, seasonal, membership, referral) and 4 discount types (percentage, fixed, free-shipping, bonus-item). Includes daily usage limits, minimum order values, and full audit trail of all offers
80
+ - **Anti-Hallucination Shield** — Cross-verification engine comparing DOM vs vision screenshots, market benchmark validation, temporal consistency checks, and Levenshtein text similarity scoring. 4 severity levels (minor → fraud) and 5 response actions (warn, halt, confirm-human, auto-correct, block)
81
+ - **Decentralized Reputation System** — HMAC-signed trust attestations from the agent network covering 6 attestation types (purchase, booking, query, form, navigation, verification). 7 trust levels (unknown → blacklisted), temporal decay, Sybil resistance, global leaderboard, and challenge/dispute system
82
+ - **Sovereign Dashboard** — Real-time command center with fairness radar, privacy shield, negotiation logs, verification checks, and AI model switcher. Exposes `/api/sovereign/dashboard/sovereign` aggregate endpoint
83
+ - **Community Agent Hub** — 11 pre-built YAML agent templates (hotel booking, grocery comparison, artisan marketplace, flight deals, etc.) with CLI runner: `npx wab-agent run template.yaml`
84
+ - **AI Brain Swapping** Local AI runtime that auto-discovers Ollama and llama.cpp endpoints plus custom OpenAI-compatible APIs. Model capability tracking for text/vision, context window management, latency-based routing, and inference logging with token metrics
85
+ - **Cross-Site Agent Orchestration** — One agent manages multiple WAB-enabled sites simultaneously via `WABMultiAgent`. Compare prices across stores, aggregate data, run parallel actions, and find the best deal automatically
86
+
87
+ ### v2.3Private Agent Mesh (Distributed Mind)
88
+
89
+ - **Inter-Agent Protocol** — Agents communicate through a private mesh with 5 built-in channels (alerts, discoveries, tactics, negotiations, votes). 6 message types with confidence scoring, auto-expiring stale agents via heartbeat, peer verification of shared knowledge. All communication stays local — no external transmission
90
+ - **Local Reinforcement Learning** — Agents learn from every user decision using UCB1 multi-armed bandit action selection, gradient-descent policy updates with sigmoid activation, temporal discounting, and sequential pattern mining. Zero external API calls — all learning is local
91
+ - **Symphony Orchestrator** Four specialized agents (Researcher, Analyst, Negotiator, Guardian) collaborate autonomously through rule-based engines. 5 templates, 6-phase pipeline (analyze → research → negotiate → guard → synthesize → decide), Guardian veto for safety, weighted consensus. Full phase logging with duration tracking. No external LLM dependency
92
+ - **Agent Mesh Dashboard** — Real-time visualization of your agent mesh: active agents, communication channels, shared knowledge base, symphony compositions, and learning performance metrics
93
+
94
+ ### v2.4Commander & Edge Intelligence
95
+
96
+ - **Commander Agent System** — Local-first mission orchestration engine that decomposes high-level goals into task DAGs. Agent registry with capabilities tracking, parallel execution engine, learning integration for outcome feedback, and edge coordination for distributed work
97
+ - **Edge Compute System** Transforms every user device into a sovereign AI node. Hardware profiling (CPU, RAM, GPU), AES-256-GCM encrypted inter-node communication, weighted load balancing, heartbeat-based health monitoring with auto-failover, and swarm formation with capability-based clustering
98
+ - **Swarm Execution Engine** — Launch multiple agents in parallel to solve a single task. Configurable strategies (parallel, sequential, hybrid), result merging with best-score selection, role specialization, fairness-weighted aggregation, and per-agent confidence scoring
99
+
100
+ ### v2.5Agent Workspace & Multilingual AI
101
+
102
+ - **Agent Workspace** — Premium 4-panel workspace for non-technical users: embedded browser, smart agent chat, real-time negotiation monitor, and results panel. Subscription tiers (Free/Starter/Pro/Enterprise), deal tracking, and admin management. Live at [webagentbridge.com/workspace](https://webagentbridge.com/workspace)
103
+ - **Bilingual UI (AR/EN)** — Full Arabic/English interface with auto-detection from browser language. Toggle instantly between languages. RTL/LTR layout support
104
+ - **Multilingual Agent** The smart agent understands and responds in any language the user writes in — Arabic, English, French, Spanish, Turkish, and more. No restrictions on input style, dialect, or format
105
+ - **Dynamic Pricing Shield** — Detects price manipulation by websites that change prices based on device type, geolocation, cookies, browsing history, referral source, or repeat visits. The agent probes the same page with 12 distinct identity personas (clean desktop, mobile, Mac premium, EU/MENA/SEA geo, repeat visitor, Google/social/comparison referral, privacy-focused, bot-like) and uses statistical analysis (coefficient of variation, z-score outliers) to expose hidden pricing. Includes manipulation scoring (0–100), actionable tips, historical trend detection, and a strategy builder that recommends the best identity for the lowest price. Full API at `/api/sovereign/price-shield/`
106
+
107
+ ### v3.0 — Agent OS (Execution Layer for the Web)
108
+
109
+ WAB v3.0 transforms the project from an advanced automation tool into a **real Agent Operating System** a complete execution layer for AI agents on the web, comparable to MCP but purpose-built for browser interaction.
110
+
111
+ - **WAB Protocol (WABP) v1.0.0** — Formal protocol with JSON Schema command registry, typed messages, input/output validation, and versioned command definitions. 10 built-in commands (discover, execute, semantic.execute, agent.register, task.submit, task.status, commerce.compare, commerce.negotiate, mesh.send, ai.infer). Every command has declared capabilities, risk levels, and permission requirements
112
+ - **Capability Negotiation** — Dynamic capability grants between agents and sites. Risk-based auto-approval (low-risk auto-granted, high-risk requires policy), rate limiting per capability, expirable grants with usage tracking, and full revocation support
113
+ - **Agent Runtime Engine** — Production-grade task runtime with priority queue scheduler, dependency resolution, retry with exponential backoff, pause/resume/cancel, concurrency limits, and state machine transitions. EventBus with async middleware, namespace wildcards, replay buffer (10K events), and dead letter queue
114
+ - **Execution Sandbox** — Per-task isolation with resource limits (timeout, maxMemory, maxNetworkCalls, maxDomOperations), domain allowlists, blocked selector enforcement, capability checks at execution time, and full audit trail of every operation
115
+ - **State Manager** — Agent state persistence with labeled checkpoints, rollback to any checkpoint, state transitions with validation, merge operations, and TTL-based cleanup
116
+ - **Observability Stack** — Structured JSON logger with child loggers and pluggable sinks, distributed tracer with parent-child spans (OpenTelemetry-compatible), and metrics collector with counters, gauges, histograms (p50/p90/p95/p99 percentiles), and time series for dashboards
117
+ - **Security Model** — AgentIdentity (registration, hashed API key authentication, session management with TTL, IP allowlists, revocation), CommandSigner (HMAC-SHA256 signing/verification with nonce + timestamp, timing-safe comparison), and SiteIsolation (per-site access control, allowed/blocked agents, max concurrency, selector blocking, data classification)
118
+ - **Control Plane** — AgentManager for deployment lifecycle (deploy, assign to sites, health checks, undeploy) and PolicyEngine with typed rules, condition evaluation (equals, contains, pattern, min, max, in), priority-ordered policy binding, and entity-level policy enforcement
119
+ - **Data Plane** — SemanticActionResolver maps `domain.action` notation (e.g., `checkout.addItem`) to concrete implementations per site. Executor routes tasks through tracing + metrics, supports semantic/pipeline/parallel execution modes, with 8 built-in semantic actions for checkout, search, auth, navigation, and content
120
+ - **Multi-Model LLM Abstraction** — Unified interface for OpenAI (chat completions + embeddings), Anthropic (messages API), and Ollama (local models with auto-discovery). LLMManager provides automatic fallback chain through all providers, response caching (5min TTL), cost tracking via token counts, and model listing
121
+ - **Registry & Ecosystem** — CommandRegistry (like npm for WAB commands — register, discover, search by category/tag/capability, usage tracking), SiteRegistry (WAB-enabled sites directory with verification, capability listing, visit tracking), and TemplateRegistry (reusable workflow templates with download counts and ratings)
122
+ - **Unified Runtime API** All Agent OS layers exposed via RESTful endpoints at `/api/os/*`: protocol discovery, agent identity/auth, task CRUD, semantic execution, deployments, policies, isolation, observability (metrics/traces/logs), registry (commands/sites/templates), LLM operations, command signing, and Server-Sent Events for real-time streaming
123
+ - **WABAgentOS SDK Client** — New `WABAgentOS` class in the SDK provides full TypeScript-typed API for all Agent OS operations: register → authenticate → negotiate capabilities → submit tasks → execute semantically → query observability → subscribe to events
124
+
125
+ ### v3.1 — WAP Deep Architecture (Protocol Hardening)
126
+
127
+ v3.1 hardens the Agent OS into a production-grade system that *surpasses* MCP making WAP (Web Agent Protocol) the top-level protocol with MCP as just one adapter.
128
+
129
+ - **WAP Discovery Spec** — Formal `/.well-known/agent-tools.json` discovery document. AI agents can find all WAP capabilities, commands, permissions, runtime config, security model, and SDKs from a single standardized URL
130
+ - **Adapter Layer** — WAP sits at the top; MCP, REST/GraphQL, and Browser automation are transport adapters beneath it. MCP Adapter exposes all WAB commands as MCP tools (list_tools / call_tool). REST Adapter registers external APIs as first-class WAP endpoints with auth, mapping, and rate limiting. Browser Adapter translates semantic actions (checkout.addItem, search.query, auth.login) into concrete browser step plans with selector fallbacks and verification
131
+ - **Auth Middleware** — All `/api/os/*` mutation endpoints require authentication (Bearer token, API key, or agent header). Public read endpoints remain open for discovery. GET requests pass through for read-only access
132
+ - **Deterministic Replay Engine** — Records all task inputs, outputs, and side-effects. Supports replay with verification mode (re-execute and compare), dry-run mode (inspect recorded steps), and diff between two recordings. Enables debugging, regression testing, and workflow certification
133
+ - **Failure Analysis & Classification** — Automatic classification of failures into 9 categories (network, timeout, permission, validation, execution, rate_limit, resource, dependency, unknown). Root cause analysis, severity scoring, retryability assessment, suggested fixes, and pattern detection for recurring failures
134
+ - **Session Engine** — Browser execution sessions with cookie jar (set/get/domain-scoped), localStorage/sessionStorage emulation, navigation history, variable store, session export/import for transfer, and TTL-based expiration
135
+ - **Certification System** — Site compatibility verification with 13 weighted checks across 7 categories (integration, protocol, data, security, fairness, compliance, sovereignty). Issues certificates at 5 levels (none → basic → standard → premium → sovereign) with 90-day validity, HMAC-signed badges, and revocation
136
+ - **DB Persistence Layer** SQLite tables for all Agent OS entities: agents, sessions, tasks, deployments, registry commands/sites/templates, audit log (immutable append-only), capability grants, and policies. Auto-migrates on boot
137
+ - **65+ API Endpoints** — Adapters (MCP tools, REST endpoints, browser mappings), replay (recordings, replay, diff, stats), sessions (CRUD, cookies, storage, export/import), failure analysis (query, patterns, summary, classify), certification (verify, certificates, revoke), plus all existing v3.0 endpoints
138
+
139
+ > **Many more features** are available on the live website that aren't listed here — dashboards, analytics, admin tools, and more. Visit [webagentbridge.com](https://webagentbridge.com) to explore.
140
+
141
+ ### v3.2 — API Gateway & Advanced Modules
142
+
143
+ v3.2 introduces a **unified API gateway** at `/api/v1` with 10 advanced modules for AI agent protection, consumer rights, price intelligence, and regulatory compliance. All modules use centralized API key authentication with plan-based access control.
144
+
145
+ 🌐 **Live API Docs:** [webagentbridge.com/api](https://webagentbridge.com/api) (English / العربية)
146
+
147
+ #### API Plans & Pricing
148
+
149
+ | Plan | Price | Requests/Day | Requests/Min | Modules |
150
+ |------|-------|-------------|-------------|----------|
151
+ | **Free** | $0/mo | 100 | 10 | Protocol, Price Time Machine, Dark Pattern, Bounty |
152
+ | **Pro** | $29/mo | 10,000 | 100 | All Free + Firewall, Neural, Bargaining, Affiliate |
153
+ | **Business** | $149/mo | 100,000 | 500 | All 10 modules (incl. Notary, Gov Intelligence) |
154
+ | **Enterprise** | Custom | Unlimited | Custom | All 10 + SLA + on-premise option |
155
+
156
+ **Get your API key:** `POST /api/v1/keys/generate` with `{"plan": "FREE", "owner": "name", "email": "you@example.com"}`
157
+
158
+ #### The 10 Modules
159
+
160
+ | # | Module | Route | Type | Min Plan | Description |
161
+ |---|--------|-------|------|----------|-------------|
162
+ | 01 | **Agent Firewall** | `/api/v1/firewall` | 🟡 API Open · Engine Closed | PRO | Scans URLs/content for prompt injection, phishing, malicious domains |
163
+ | 02 | **Cryptographic Notary** | `/api/v1/notary` | 🔴 Fully Closed | BUSINESS | Issues legally admissible cryptographic certificates for price discrimination proof |
164
+ | 03 | **Dark Pattern Detector** | `/api/v1/dark-pattern` | 🔴 Fully Closed | FREE | Detects all 17 OECD-classified dark patterns with EU DSA/DMA audit reports |
165
+ | 04 | **Collective Bargaining** | `/api/v1/bargaining` | 🟡 Join Open · Engine Closed | PRO | Anonymous buyer grouping for bulk discount negotiation |
166
+ | 05 | **Gov Intelligence** | `/api/v1/gov` | 🔴 Fully Closed | BUSINESS | Regulatory compliance database and domain compliance checking |
167
+ | 06 | **Price Time Machine** | `/api/v1/price` | 🟡 API Open · DB Closed | FREE | Historical price tracking and fake discount detection |
168
+ | 07 | **WAB Neural Engine** | `/api/v1/neural` | 🔴 Fully Closed | PRO | Local AI inference for URL analysis, content classification, embeddings |
169
+ | 08 | **WAB Protocol** | `/api/v1/protocol` | 🟢 Fully Open Source | FREE | Open wab.json trust protocol validator and schema endpoint |
170
+ | 09 | **Bounty Network** | `/api/v1/bounty` | 🟡 Report Open · Rules Closed | FREE | Community-powered threat reporting and bug bounty with leaderboard |
171
+ | 10 | **Affiliate Intelligence** | `/api/v1/affiliate` | 🟡 API Open · DB Closed | PRO | Detects affiliate link manipulation, cookie stuffing, tracking pixel abuse |
172
+
173
+ **Type Legend:** 🟢 Fully open source · 🟡 Public API interface, proprietary engine · 🔴 Fully closed (returns 503 without engine)
174
+
175
+ #### Authentication
176
+
177
+ All module endpoints require an API key via one of three methods:
178
+
179
+ ```bash
180
+ # Option 1: Authorization header (recommended)
181
+ curl -X POST https://www.webagentbridge.com/api/v1/firewall/scan \
182
+ -H "Authorization: Bearer wab_live_pro_YOUR_KEY" \
183
+ -H "Content-Type: application/json" \
184
+ -d '{"url": "https://example.com", "content": "page content..."}'
185
+
186
+ # Option 2: X-WAB-Key header
187
+ curl -H "X-WAB-Key: wab_live_pro_YOUR_KEY" \
188
+ https://www.webagentbridge.com/api/v1/protocol/check/example.com
189
+
190
+ # Option 3: Query parameter
191
+ curl https://www.webagentbridge.com/api/v1/bounty/stats?api_key=wab_live_fre_YOUR_KEY
192
+ ```
193
+
194
+ #### Key Management
195
+
196
+ | Endpoint | Method | Description |
197
+ |----------|--------|-------------|
198
+ | `/api/v1/keys/generate` | POST | Create a new API key |
199
+ | `/api/v1/keys/validate` | POST | Validate an existing key |
200
+ | `/api/v1/keys/usage` | GET | Check usage and quotas |
201
+ | `/api/v1/keys/revoke` | POST | Revoke a key |
202
+ | `/api/v1/keys/rotate` | POST | Rotate a key (revoke old, issue new) |
203
+
204
+ #### Gateway Endpoints
205
+
206
+ | Endpoint | Method | Description |
207
+ |----------|--------|-------------|
208
+ | `/api/v1/health` | GET | Gateway health check (public) |
209
+ | `/api/v1/plans` | GET | List available plans and pricing (public) |
210
+ | `/api/v1/modules` | GET | List all available modules (public) |
211
+
212
+ #### How to Subscribe
213
+
214
+ 1. Visit [webagentbridge.com/api](https://webagentbridge.com/api) to explore available modules
215
+ 2. Generate a **Free** API key: `POST /api/v1/keys/generate` with your name and email
216
+ 3. Start making requests to any Free-tier module immediately
217
+ 4. Upgrade to **Pro** ($29/mo) or **Business** ($149/mo) for access to advanced modules
218
+ 5. Manage your keys via the `/api/v1/keys/*` endpoints
219
+
220
+ ---
221
+
222
+ ## Quick Start
223
+
224
+ > **Looking for a 5-minute install?** See **[INSTALL.md](INSTALL.md)** a dedicated bilingual (English / العربية) quick-install guide that gets you a sovereign WAB-enabled site with DNS Discovery in one command.
225
+
226
+ ### Deploy in One Click
227
+
228
+ | Platform | Button | Storage | Free Tier |
229
+ |---|---|---|---|
230
+ | **Railway** | [![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/template/web-agent-bridge?referralCode=wab) | Persistent SQLite | $5 credit/mo |
231
+ | **Vercel** | [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fabokenan444%2Fweb-agent-bridge&env=JWT_SECRET,JWT_SECRET_ADMIN&project-name=web-agent-bridge) | Ephemeral | Generous free tier |
232
+ | **Netlify** | [![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/abokenan444/web-agent-bridge) | Ephemeral | 100GB bandwidth/mo |
233
+ | **Cloudflare** | [![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/abokenan444/web-agent-bridge) | Edge KV | 100K req/day |
234
+
235
+ > **Recommended for production:** Railway (persistent storage) or self-hosted with Docker.
236
+
237
+ ### 1. Install & Run the Server
238
+
239
+ ```bash
240
+ # Option A: One-line install on any Linux server (Ubuntu/Debian/CentOS/Alpine)
241
+ curl -fsSL https://raw.githubusercontent.com/abokenan444/web-agent-bridge/master/integrations/install/install.sh | sudo bash
242
+
243
+ # Option B: Clone and run
244
+ git clone https://github.com/abokenan444/web-agent-bridge.git
245
+ cd web-agent-bridge
246
+ npm install
247
+ cp .env.example .env
248
+ npm start
249
+
250
+ # Option C: npx (one command)
251
+ npx web-agent-bridge start
252
+
253
+ # Option D: Docker (standard)
254
+ docker compose up -d
255
+
256
+ # Option E: Docker with Nginx + SSL (production)
257
+ WAB_DOMAIN=yourdomain.com docker compose -f docker-compose.nginx.yml up -d
258
+ ```
259
+
260
+ ### 2. Create an Account
261
+
262
+ Visit `http://localhost:3000/register` and create an account, then add your site from the dashboard.
263
+
264
+ ### 3. Add the Script to Your Website
265
+
266
+ ```html
267
+ <!-- Recommended: copy the snippet from your dashboard (uses siteId only) -->
268
+ <script>
269
+ window.AIBridgeConfig = {
270
+ siteId: "your-site-uuid-from-dashboard",
271
+ configEndpoint: "https://yourserver.com/api/license/token",
272
+ agentPermissions: {
273
+ readContent: true,
274
+ click: true,
275
+ fillForms: true,
276
+ scroll: true
277
+ }
278
+ };
279
+ </script>
280
+ <script src="https://yourserver.com/script/ai-agent-bridge.js"></script>
281
+ ```
282
+
283
+ The server matches **Origin** to your registered site domain, then returns a short-lived **session token**. Analytics (`/api/license/track`) require that session — not the long-lived license key. Keep the license key in the dashboard only.
284
+
285
+ ### 4. AI Agents Can Now Interact
286
+
287
+ ```javascript
288
+ // From the AI agent's side
289
+ const bridge = window.AICommands;
290
+ const actions = bridge.getActions(); // discover actions
291
+ await bridge.execute("signup"); // execute an action
292
+ const info = bridge.getPageInfo(); // get page metadata
293
+ ```
294
+
295
+ ---
296
+
297
+ ## Project Structure
298
+
299
+ ```
300
+ web-agent-bridge/
301
+ ├── server/ # Express.js backend
302
+ ├── index.js # Server entry point
303
+ │ ├── ws.js # WebSocket server (live analytics)
304
+ ├── routes/
305
+ │ │ ├── auth.js # Authentication (register/login)
306
+ │ │ ├── api.js # Sites, config, analytics API
307
+ ├── license.js # License verification, token exchange & tracking
308
+ │ ├── admin.js # Admin dashboard API
309
+ │ │ ├── admin-premium.js # Admin premium analytics (memory, vision, swarm, plugins)
310
+ │ │ ├── billing.js # Stripe billing integration
311
+ │ │ ├── sovereign.js # v2.0: negotiation, reputation, verification, dashboard
312
+ │ │ ├── mesh.js # v2.3: agent mesh protocol routes
313
+ │ │ ├── commander.js # v2.4: mission orchestration routes
314
+ │ │ ├── premium.js # Premium features
315
+ │ │ ├── premium-v2.js # v2 premium (memory, vision, healing, swarm, plugins)
316
+ │ │ ├── discovery.js # WAB discovery + fairness-weighted search
317
+ │ │ ├── wab-api.js # WAB HTTP transport (alternative to JS/WS)
318
+ │ │ ├── noscript.js # NoScript tracking pixel fallback
319
+ │ │ └── gateway.js # v3.2: Unified API Gateway (/api/v1)
320
+ │ ├── services/
321
+ │ │ ├── negotiation.js # Real-time negotiation engine
322
+ │ │ ├── verification.js # Anti-hallucination shield
323
+ │ │ ├── reputation.js # Decentralized reputation system
324
+ │ │ ├── agent-mesh.js # Inter-agent protocol (mesh)
325
+ │ │ ├── agent-learning.js # Local reinforcement learning (UCB1)
326
+ │ │ ├── agent-symphony.js # Symphony orchestrator (4 roles, 6 phases)
327
+ │ │ ├── agent-memory.js # Persistent agent memory with associations
328
+ │ │ ├── commander.js # Mission orchestration & task DAGs
329
+ │ │ ├── edge-compute.js # Edge computing / sovereign AI nodes
330
+ │ │ ├── swarm.js # Swarm execution engine
331
+ │ │ ├── fairness.js # Fairness & neutrality engine
332
+ │ │ ├── vision.js # Vision analysis (multi-provider)
333
+ │ │ ├── self-healing.js # Self-healing selector corrections
334
+ │ │ ├── local-ai.js # Local AI model runtime
335
+ │ │ ├── plugins.js # Plugin architecture (hooks, registry)
336
+ │ │ ├── premium.js # Premium traffic intelligence & bot detection
337
+ │ │ ├── email.js # SMTP email service
338
+ │ │ ├── stripe.js # Stripe payment integration
339
+ │ │ ├── api-key-engine.js # v3.2: API key auth, rate limiting, plans
340
+ │ │ └── modules/ # v3.2: API Gateway modules
341
+ │ │ ├── protocol.js # WAB Protocol validator (open)
342
+ │ │ ├── agent-firewall.js # Agent Firewall (partial)
343
+ │ │ ├── price-time-machine.js # Price Time Machine (partial)
344
+ │ │ ├── bounty.js # Bounty Network (partial)
345
+ │ │ ├── collective-bargaining.js # Collective Bargaining (partial)
346
+ │ │ ├── affiliate-intelligence.js # Affiliate Intelligence (partial)
347
+ │ │ ├── neural.js # Neural Engine (closed)
348
+ │ │ ├── dark-pattern.js # Dark Pattern Detector (closed)
349
+ │ │ ├── gov-intelligence.js # Gov Intelligence (closed)
350
+ │ │ └── notary.js # Cryptographic Notary (closed)
351
+ │ ├── middleware/
352
+ │ │ ├── auth.js # JWT authentication middleware
353
+ │ │ ├── adminAuth.js # Admin authentication
354
+ │ │ └── rateLimits.js # Multi-layer rate limiting
355
+ │ ├── models/
356
+ │ │ ├── db.js # Database operations
357
+ │ │ └── adapters/ # SQLite, PostgreSQL, MySQL adapters
358
+ │ ├── migrations/ # Numbered SQL migrations
359
+ │ └── utils/
360
+ │ ├── cache.js # In-memory TTL cache + analytics queue
361
+ │ ├── migrate.js # Migration runner
362
+ │ └── secureFields.js # Field-level encryption utilities
363
+ ├── public/ # Frontend
364
+ │ ├── index.html # Landing page
365
+ │ ├── dashboard.html # Management dashboard
366
+ │ ├── premium-dashboard.html # Premium analytics dashboard
367
+ │ ├── docs.html # Documentation
368
+ │ ├── login.html / register.html # Auth pages
369
+ │ ├── admin/ # Admin panel
370
+ │ ├── pwa/ # Progressive Web App (mobile browser)
371
+ │ │ ├── manifest.json # PWA manifest
372
+ │ │ ├── sw.js # Service worker (offline-first)
373
+ │ │ ├── index.html # Mobile browser UI
374
+ │ │ ├── app.js # Ad blocker, scam shield, fairness
375
+ │ │ ├── app.css # Mobile-optimized dark theme
376
+ │ │ └── icons/ # PWA icons (192x192, 512x512)
377
+ │ ├── script/
378
+ │ │ ├── wab.min.js # Minified WAB client library
379
+ │ │ ├── wab-consent.js # GDPR/CCPA consent banner
380
+ │ │ ├── wab-schema.js # Schema.org discovery
381
+ │ │ ├── wab.d.ts # TypeScript definitions
382
+ │ │ └── wab-consent.d.ts # Consent TypeScript definitions
383
+ │ ├── js/ # Dashboard frontend JS
384
+ │ └── css/ # Stylesheets
385
+ ├── script/
386
+ │ └── ai-agent-bridge.js # The bridge script (embed in websites)
387
+ ├── examples/ # Agent examples
388
+ │ ├── puppeteer-agent.js # Puppeteer + window.AICommands
389
+ │ ├── bidi-agent.js # WebDriver BiDi protocol
390
+ │ ├── vision-agent.js # Vision/NLP intent resolution
391
+ │ ├── mcp-agent.js # MCP adapter usage for Claude/GPT
392
+ │ ├── cross-site-agent.js # Multi-domain orchestration
393
+ │ ├── next-app-router/ # Next.js App Router integration
394
+ │ ├── shopify-hydrogen/ # Shopify Hydrogen storefront
395
+ │ ├── wordpress-elementor/ # WordPress + Elementor setup
396
+ │ └── saas-dashboard/ # SaaS dashboard actions
397
+ ├── packages/ # Framework wrappers
398
+ │ ├── react/ # @web-agent-bridge/react
399
+ │ ├── vue/ # @web-agent-bridge/vue
400
+ │ ├── svelte/ # @web-agent-bridge/svelte
401
+ │ └── langchain/ # @web-agent-bridge/langchain
402
+ ├── sdk/ # Agent SDK
403
+ │ ├── index.js # WABAgent for Puppeteer/Playwright
404
+ │ └── schema-discovery.js # Server-side schema.org extraction
405
+ ├── wab-mcp-adapter/ # MCP adapter for Claude/GPT/Gemini
406
+ │ ├── index.js # MCP tool definitions
407
+ │ └── package.json
408
+ ├── wab-browser/ # Electron desktop browser
409
+ │ ├── main.js # Electron main process
410
+ │ ├── preload.js # Bridge preload
411
+ │ └── package.json
412
+ ├── web-agent-bridge-wordpress/ # WordPress plugin
413
+ │ ├── web-agent-bridge.php # Plugin entry point
414
+ │ ├── includes/ # PHP classes (API, Actions, Dashboard)
415
+ │ └── assets/ # Plugin CSS/JS
416
+ ├── bin/
417
+ │ ├── cli.js # CLI entry point (wab-agent)
418
+ │ └── wab.js # Agent runner
419
+ ├── templates/ # 11 Community Agent Hub YAML templates
420
+ ├── docs/
421
+ │ ├── SPEC.md # WAB Protocol Specification
422
+ │ └── DEPLOY.md # Deployment guide
423
+ ├── demo-store/ # Demo store for testing
424
+ ├── deploy/ # Nginx configs
425
+ ├── tests/ # Jest + Supertest test suite
426
+ ├── .env # Environment variables
427
+ └── package.json
428
+ ```
429
+
430
+ ---
431
+
432
+ ## API Endpoints
433
+
434
+ ### Authentication
435
+ | Endpoint | Method | Description |
436
+ |---|---|---|
437
+ | `/api/auth/register` | POST | Create account |
438
+ | `/api/auth/login` | POST | Sign in, receive JWT |
439
+ | `/api/auth/me` | GET | Get current user |
440
+
441
+ ### Sites
442
+ | Endpoint | Method | Description |
443
+ |---|---|---|
444
+ | `/api/sites` | GET | List your sites |
445
+ | `/api/sites` | POST | Add a new site |
446
+ | `/api/sites/:id` | GET | Get site details |
447
+ | `/api/sites/:id/config` | PUT | Update configuration |
448
+ | `/api/sites/:id/tier` | PUT | Change subscription tier |
449
+ | `/api/sites/:id` | DELETE | Delete a site |
450
+ | `/api/sites/:id/snippet` | GET | Get install code snippet |
451
+ | `/api/sites/:id/analytics` | GET | Get analytics data |
452
+
453
+ ### License (Public)
454
+ | Endpoint | Method | Description |
455
+ |---|---|---|
456
+ | `/api/license/verify` | POST | Verify license key for domain (cached) |
457
+ | `/api/license/token` | POST | Exchange `siteId` (Origin must match domain) or `licenseKey` for session token |
458
+ | `/api/license/session` | POST | Validate session token (domain-locked) |
459
+ | `/api/license/track` | POST | Record analytics (`sessionToken` + Origin) |
460
+
461
+ ### Sovereign (v2.0)
462
+ | Endpoint | Method | Description |
463
+ |---|---|---|
464
+ | `/api/sovereign/reputation/agents` | POST | Register a new agent |
465
+ | `/api/sovereign/reputation/attestations` | POST | Submit a trust attestation |
466
+ | `/api/sovereign/reputation/sites/:siteId` | GET | Get site reputation |
467
+ | `/api/sovereign/reputation/leaderboard` | GET | Get reputation leaderboard |
468
+ | `/api/sovereign/negotiation/rules` | POST | Create negotiation rule |
469
+ | `/api/sovereign/negotiation/rules/:siteId` | GET | Get rules for a site |
470
+ | `/api/sovereign/negotiation/sessions` | POST | Open negotiation session |
471
+ | `/api/sovereign/negotiation/sessions/:id/propose` | POST | Submit counter-offer |
472
+ | `/api/sovereign/negotiation/sessions/:id/confirm` | POST | Confirm a deal |
473
+ | `/api/sovereign/verify/price` | POST | Verify price (DOM vs vision) |
474
+ | `/api/sovereign/verify/text` | POST | Verify text accuracy |
475
+ | `/api/sovereign/verify/page` | POST | Full page verification |
476
+ | `/api/sovereign/dashboard/sovereign` | GET | Dashboard aggregate data |
477
+
478
+ ### Agent Mesh (v2.3)
479
+ | Endpoint | Method | Description |
480
+ |---|---|---|
481
+ | `/api/mesh/agents` | POST | Register agent in mesh |
482
+ | `/api/mesh/agents` | GET | List mesh agents |
483
+ | `/api/mesh/channels` | GET | List communication channels |
484
+ | `/api/mesh/messages` | POST | Publish message to channel |
485
+ | `/api/mesh/messages/:channel` | GET | Get messages from channel |
486
+ | `/api/mesh/knowledge` | POST | Share knowledge to mesh |
487
+ | `/api/mesh/knowledge` | GET | Query knowledge base |
488
+ | `/api/mesh/votes` | POST | Start a vote |
489
+ | `/api/mesh/votes/:id/cast` | POST | Cast a vote |
490
+ | `/api/mesh/votes/:id/tally` | GET | Get vote results |
491
+
492
+ ### Commander (v2.4)
493
+ | Endpoint | Method | Description |
494
+ |---|---|---|
495
+ | `/api/commander/missions` | POST | Create a new mission |
496
+ | `/api/commander/missions/:id/launch` | POST | Launch mission execution |
497
+ | `/api/commander/missions/:id` | GET | Get mission status |
498
+ | `/api/commander/missions` | GET | List all missions |
499
+ | `/api/commander/agents` | POST | Register an agent |
500
+ | `/api/commander/agents` | GET | List registered agents |
501
+ | `/api/commander/edge/nodes` | POST | Register edge node |
502
+ | `/api/commander/edge/nodes` | GET | List edge nodes |
503
+ | `/api/commander/ai/models` | GET | Discover local AI models |
504
+ | `/api/commander/ai/infer` | POST | Run local AI inference |
505
+ | `/api/commander/stats` | GET | Unified platform statistics |
506
+
507
+ ### Premium v2
508
+ | Endpoint | Method | Description |
509
+ |---|---|---|
510
+ | `/api/premium/v2/memory` | POST | Store agent memory |
511
+ | `/api/premium/v2/memory/:agentId` | GET | Recall agent memories |
512
+ | `/api/premium/v2/memory/associate` | POST | Create memory association |
513
+ | `/api/premium/v2/memory/:id` | DELETE | Forget a memory |
514
+ | `/api/premium/v2/memory/consolidate` | POST | Consolidate old memories |
515
+ | `/api/premium/v2/vision/analyze` | POST | Analyze screenshot |
516
+ | `/api/premium/v2/vision/elements` | POST | Extract interactive elements |
517
+ | `/api/premium/v2/healing/corrections` | POST | Register selector correction |
518
+ | `/api/premium/v2/healing/resolve` | POST | Resolve broken selector |
519
+ | `/api/premium/v2/swarm/execute` | POST | Launch swarm task |
520
+ | `/api/premium/v2/swarm/:id` | GET | Get swarm results |
521
+ | `/api/premium/v2/plugins` | GET | List available plugins |
522
+ | `/api/premium/v2/plugins/:id/install` | POST | Install plugin for site |
523
+ | `/api/premium/v2/plugins/:id/hooks` | POST | Execute plugin hook |
524
+
525
+ ### Discovery & Fairness
526
+ | Endpoint | Method | Description |
527
+ |---|---|---|
528
+ | `/api/discovery` | GET | WAB discovery document |
529
+ | `/api/discovery/search` | GET | Fairness-weighted site search |
530
+ | `/api/discovery/register` | POST | Register site in WAB directory |
531
+
532
+ ### WAB Protocol (HTTP Transport)
533
+ | Endpoint | Method | Description |
534
+ |---|---|---|
535
+ | `/api/wab/session` | POST | Exchange session token |
536
+ | `/api/wab/actions` | GET | Get available actions |
537
+ | `/api/wab/execute` | POST | Execute action via HTTP |
538
+
539
+ ### NoScript Fallback
540
+ | Endpoint | Method | Description |
541
+ |---|---|---|
542
+ | `/noscript/pixel.gif` | GET | 1×1 tracking pixel for non-JS environments |
543
+
544
+ ---
545
+
546
+ ## Bridge Script API
547
+
548
+ Once loaded, `window.AICommands` exposes:
549
+
550
+ | Method | Description |
551
+ |---|---|
552
+ | `getActions(category?)` | List available actions |
553
+ | `getAction(name)` | Get a specific action |
554
+ | `execute(name, params?)` | Execute an action |
555
+ | `readContent(selector)` | Read element content |
556
+ | `getPageInfo()` | Get page and bridge metadata |
557
+ | `waitForElement(selector, timeout?)` | Wait for DOM element |
558
+ | `waitForNavigation(timeout?)` | Wait for URL change |
559
+ | `registerAction(def)` | Register a custom action |
560
+ | `authenticate(key, meta?)` | Authenticate an agent |
561
+ | `refresh()` | Re-scan the page |
562
+ | `onReady(callback)` | Callback when bridge is ready |
563
+ | `events.on(event, cb)` | Subscribe to events |
564
+
565
+ ---
566
+
567
+ ## Configuration
568
+
569
+ ```javascript
570
+ window.AIBridgeConfig = {
571
+ // Recommended copy siteId from dashboard snippet (no license key in HTML)
572
+ siteId: "uuid-from-dashboard",
573
+ configEndpoint: "/api/license/token",
574
+
575
+ // Legacy: token exchange via license key (avoid embedding in public pages)
576
+ // licenseKey: "WAB-...",
577
+
578
+ agentPermissions: {
579
+ readContent: true, // Read page text
580
+ click: true, // Click elements
581
+ fillForms: false, // Fill/submit forms
582
+ scroll: true, // Scroll page
583
+ navigate: false, // Navigate pages
584
+ apiAccess: false, // Internal API calls (Pro+)
585
+ automatedLogin: false, // Auto login (Starter+)
586
+ extractData: false // Data extraction (Pro+)
587
+ },
588
+ restrictions: {
589
+ allowedSelectors: [],
590
+ blockedSelectors: [".private", "[data-private]"],
591
+ requireLoginForActions: ["apiAccess"],
592
+ rateLimit: { maxCallsPerMinute: 60 }
593
+ },
594
+ logging: { enabled: false, level: "basic" }
595
+ };
596
+ ```
597
+
598
+ ---
599
+
600
+ ## Subscription Tiers
601
+
602
+ | Feature | Free | Starter | Pro | Enterprise |
603
+ |---|:---:|:---:|:---:|:---:|
604
+ | Auto-discovery | | | ✓ | ✓ |
605
+ | Click/Scroll | | | | |
606
+ | Form filling | ✓ | ✓ | ✓ | ✓ |
607
+ | Basic logging | ✓ | ✓ | ✓ | ✓ |
608
+ | Automated login | ✗ | ✓ | ✓ | ✓ |
609
+ | Analytics dashboard | ✗ | ✓ | ✓ | ✓ |
610
+ | API access | ✗ | ✗ | ✓ | ✓ |
611
+ | Data extraction | | | ✓ | ✓ |
612
+ | Custom rate limits | ✗ | ✗ | ✗ | ✓ |
613
+ | Webhooks | | ✗ | ✗ | ✓ |
614
+
615
+ ---
616
+
617
+ ## Tech Stack
618
+
619
+ - **Backend**: Node.js + Express + WebSocket (ws)
620
+ - **Database**: SQLite (via better-sqlite3) with migration runner
621
+ - **Auth**: JWT + bcrypt + session tokens (domain-locked)
622
+ - **Caching**: In-memory TTL cache + batched analytics queue
623
+ - **Payments**: Stripe integration with billing portal
624
+ - **Frontend**: Vanilla HTML/CSS/JS (no framework dependencies)
625
+ - **Framework Wrappers**: React, Vue 3, Svelte (optional)
626
+ - **LLM Integration**: LangChain adapter, MCP adapter
627
+ - **Security**: Helmet, CORS, CSP, multi-layer rate limiting
628
+ - **Containers**: Docker + Docker Compose
629
+ - **CI/CD**: GitHub Actions (test + auto-publish to npm)
630
+ - **Testing**: Jest + Supertest
631
+
632
+ ---
633
+
634
+ ## WebDriver BiDi Compatibility
635
+
636
+ WAB exposes a `window.__wab_bidi` interface for agents using standardized WebDriver BiDi protocol:
637
+
638
+ ```javascript
639
+ // Get BiDi context
640
+ const context = window.__wab_bidi.getContext();
641
+
642
+ // Send BiDi command
643
+ const result = await window.__wab_bidi.send({
644
+ id: 1,
645
+ method: 'wab.executeAction',
646
+ params: { name: 'signup', data: {} }
647
+ });
648
+
649
+ // Supported methods:
650
+ // wab.getContext, wab.getActions, wab.executeAction, wab.readContent, wab.getPageInfo
651
+ ```
652
+
653
+ ---
654
+
655
+ ## Real-Time Analytics (WebSocket)
656
+
657
+ Connect to `ws://localhost:3000/ws/analytics` for live analytics. Use the built-in `WABWebSocket` client for automatic reconnection with exponential backoff:
658
+
659
+ ```javascript
660
+ // Recommended: use the auto-reconnecting client
661
+ import { WABWebSocket } from './js/ws-client.js';
662
+
663
+ const ws = new WABWebSocket('jwt-token', 'site-id');
664
+ ws.on('analytic', (data) => console.log(data));
665
+ ws.on('reconnecting', ({ attempt, delay }) => console.log(`Reconnecting #${attempt}...`));
666
+ ws.connect();
667
+ ```
668
+
669
+ ```javascript
670
+ // Or connect manually
671
+ const ws = new WebSocket('ws://localhost:3000/ws/analytics');
672
+ ws.onopen = () => ws.send(JSON.stringify({ type: 'auth', token: 'jwt-token', siteId: 'site-id' }));
673
+ ws.onmessage = (e) => console.log(JSON.parse(e.data));
674
+ ```
675
+
676
+ ### WebSocket Message Protocol
677
+
678
+ **Client Server Messages:**
679
+
680
+ | Message | Fields | Description |
681
+ |---|---|---|
682
+ | `auth` | `type`, `token`, `siteId` | Authenticate and subscribe to a site's events |
683
+
684
+ ```json
685
+ { "type": "auth", "token": "eyJhbGciOi...", "siteId": "uuid-of-site" }
686
+ ```
687
+
688
+ **Server Client Messages:**
689
+
690
+ | Message Type | Fields | Description |
691
+ |---|---|---|
692
+ | `auth:success` | `type`, `siteId` | Authentication succeeded |
693
+ | `analytic` | `type`, `timestamp`, `actionName`, `agentId`, `success` | Real-time analytics event |
694
+ | `error` | `type`, `message` | Error (invalid auth, malformed message) |
695
+
696
+ ```json
697
+ // Success response
698
+ { "type": "auth:success", "siteId": "uuid-of-site" }
699
+
700
+ // Analytics event
701
+ {
702
+ "type": "analytic",
703
+ "timestamp": "2024-01-15T10:30:00.000Z",
704
+ "actionName": "click-signup",
705
+ "agentId": "agent-123",
706
+ "triggerType": "click",
707
+ "success": true
708
+ }
709
+
710
+ // Error
711
+ { "type": "error", "message": "Invalid message or auth failed" }
712
+ ```
713
+
714
+ **Connection Lifecycle:**
715
+ 1. Connect to `ws://host:port/ws/analytics`
716
+ 2. Send `auth` message with valid JWT and site ID
717
+ 3. Receive `auth:success` confirmation
718
+ 4. Receive `analytic` events as they occur
719
+ 5. Server sends heartbeat pings every 30 seconds — dead connections are cleaned up automatically
720
+
721
+ ---
722
+
723
+ ## CDN & Versioning
724
+
725
+ Scripts are served at versioned URLs for cache-safe deployments:
726
+
727
+ | URL | Description |
728
+ |---|---|
729
+ | `/script/ai-agent-bridge.js` | Default path |
730
+ | `/v1/ai-agent-bridge.js` | Version-pinned (recommended) |
731
+ | `/latest/ai-agent-bridge.js` | Always latest (use with caution) |
732
+
733
+ ---
734
+
735
+ ## Docker
736
+
737
+ ```bash
738
+ # Standard quick start
739
+ docker compose up -d
740
+
741
+ # Production with Nginx + automatic SSL (Let's Encrypt)
742
+ WAB_DOMAIN=yourdomain.com docker compose -f docker-compose.nginx.yml up -d
743
+
744
+ # Build manually
745
+ docker build -t web-agent-bridge .
746
+ docker run -p 3000:3000 \
747
+ -e JWT_SECRET=$(openssl rand -base64 48) \
748
+ -e JWT_SECRET_ADMIN=$(openssl rand -base64 48) \
749
+ -v wab-data:/app/data \
750
+ web-agent-bridge
751
+ ```
752
+
753
+ ### Docker Compose Files
754
+
755
+ | File | Description | Use Case |
756
+ |---|---|---|
757
+ | `docker-compose.yml` | WAB server only | Development, simple deployments |
758
+ | `docker-compose.nginx.yml` | WAB + Nginx + SSL | Production with custom domain |
759
+
760
+ ### Cloudflare Worker (Edge Deployment)
761
+
762
+ Deploy WAB at the edge — no server required:
763
+
764
+ ```bash
765
+ # Install Wrangler
766
+ npm install -g wrangler
767
+ wrangler login
768
+
769
+ # Deploy from integrations/cloudflare-worker/
770
+ cd integrations/cloudflare-worker
771
+ wrangler secret put WAB_SERVER_URL
772
+ wrangler secret put WAB_SITE_ID
773
+ wrangler secret put WAB_API_KEY
774
+ wrangler deploy
775
+ ```
776
+
777
+ See [`integrations/cloudflare-worker/README.md`](integrations/cloudflare-worker/README.md) for full guide.
778
+
779
+ ---
780
+
781
+ ## Testing
782
+
783
+ ```bash
784
+ npm test
785
+ ```
786
+
787
+ Tests cover: authentication, site CRUD, config management, license verification, analytics tracking, and static pages.
788
+
789
+ ---
790
+
791
+ ## Agent SDK
792
+
793
+ WAB includes a built-in SDK for building AI agents. See [`sdk/README.md`](sdk/README.md) for full documentation.
794
+
795
+ ```javascript
796
+ const puppeteer = require('puppeteer');
797
+ const { WABAgent } = require('web-agent-bridge/sdk');
798
+
799
+ const browser = await puppeteer.launch();
800
+ const page = await browser.newPage();
801
+ const agent = new WABAgent(page);
802
+
803
+ await agent.navigateAndWait('https://example.com');
804
+ const actions = await agent.getActions();
805
+ await agent.execute('signup', { email: 'user@test.com' });
806
+ await browser.close();
807
+ ```
808
+
809
+ ### SDK Extras
810
+
811
+ The SDK now includes additional helpers for advanced agent workflows:
812
+
813
+ ```javascript
814
+ // Wait for GDPR consent before proceeding
815
+ await agent.waitForConsent();
816
+
817
+ // Discover all actions + page meta
818
+ const disc = await agent.discover();
819
+ console.log(disc.actions, disc.meta);
820
+
821
+ // Run a sequence of actions (stops on first failure by default)
822
+ const results = await agent.runPipeline([
823
+ { name: 'login', params: { email: 'a@b.com', pass: 'secret' } },
824
+ { name: 'addToCart', params: { sku: 'ABC123' } },
825
+ { name: 'checkout' }
826
+ ]);
827
+
828
+ // Run actions in parallel
829
+ const parallel = await agent.executeParallel([
830
+ { name: 'getCartCount' },
831
+ { name: 'getWishlistCount' }
832
+ ]);
833
+
834
+ // Capture screenshot (base64) for vision agents
835
+ const b64 = await agent.screenshot({ fullPage: true });
836
+ ```
837
+
838
+ ---
839
+
840
+ ## Framework Packages
841
+
842
+ ### Vue 3
843
+
844
+ ```bash
845
+ npm install @web-agent-bridge/vue
846
+ ```
847
+
848
+ ```javascript
849
+ import { useWAB, useWABAction } from '@web-agent-bridge/vue';
850
+
851
+ // In setup()
852
+ const { ready, execute } = useWAB({ siteUrl: 'https://example.com' });
853
+ const cart = useWABAction('addToCart');
854
+
855
+ // In template handler
856
+ await cart.run({ sku: 'ABC123' });
857
+ console.log(cart.result.value);
858
+ ```
859
+
860
+ ### Svelte
861
+
862
+ ```bash
863
+ npm install @web-agent-bridge/svelte
864
+ ```
865
+
866
+ ```svelte
867
+ <script>
868
+ import { createWAB, createWABAction } from '@web-agent-bridge/svelte';
869
+
870
+ const wab = createWAB();
871
+ const cart = createWABAction('addToCart');
872
+
873
+ async function add() {
874
+ await cart.run({ sku: 'ABC123' });
875
+ }
876
+ </script>
877
+
878
+ {#if $cart.loading}Adding...{/if}
879
+ {#if $cart.result}Added!{/if}
880
+ <button on:click={add}>Add to Cart</button>
881
+ ```
882
+
883
+ ### LangChain / LangGraph
884
+
885
+ ```bash
886
+ npm install @web-agent-bridge/langchain
887
+ ```
888
+
889
+ ```javascript
890
+ const { WABToolkit } = require('@web-agent-bridge/langchain');
891
+ const { ChatOpenAI } = require('@langchain/openai');
892
+ const { AgentExecutor, createOpenAIToolsAgent } = require('langchain/agents');
893
+
894
+ // HTTP mode — discover + execute via the WAB server
895
+ const toolkit = new WABToolkit({ siteUrl: 'https://shop.example.com' });
896
+ const tools = await toolkit.getTools();
897
+
898
+ // Browser mode use with Puppeteer/Playwright
899
+ const { WABAgent } = require('web-agent-bridge/sdk');
900
+ const toolkit2 = new WABToolkit({ agent: new WABAgent(page) });
901
+ const tools2 = await toolkit2.getTools();
902
+
903
+ // Pass tools to any LangChain agent
904
+ const llm = new ChatOpenAI({ model: 'gpt-4o' });
905
+ const agent = await createOpenAIToolsAgent({ llm, tools, prompt });
906
+ const executor = new AgentExecutor({ agent, tools });
907
+ await executor.invoke({ input: 'Add the first product to my cart' });
908
+ ```
909
+
910
+ ---
911
+
912
+ ## GDPR / CCPA Consent
913
+
914
+ Load the consent script after `wab.min.js` to gate agent actions behind user consent:
915
+
916
+ ```html
917
+ <script src="/script/wab.min.js"></script>
918
+ <script src="/script/wab-consent.js"></script>
919
+ <script>
920
+ WABConsent.showBanner({
921
+ policyUrl: '/privacy',
922
+ message: 'Allow AI agents to interact with this page?',
923
+ onAccept: () => WAB.init({ siteUrl: location.origin }),
924
+ onDecline: () => console.log('Agent access declined')
925
+ });
926
+ </script>
927
+ ```
928
+
929
+ SDK agents can check consent programmatically:
930
+
931
+ ```javascript
932
+ const agent = new WABAgent(page);
933
+ const ok = await agent.hasConsent(); // true | false
934
+ await agent.waitForConsent(); // blocks until Allow is clicked
935
+ ```
936
+
937
+ ---
938
+
939
+ ## Agent Examples
940
+
941
+ Ready-to-run agent examples in the [`examples/`](examples/) directory:
942
+
943
+ | File | Description |
944
+ |---|---|
945
+ | `puppeteer-agent.js` | Basic agent using Puppeteer + `window.AICommands` |
946
+ | `bidi-agent.js` | Agent using WebDriver BiDi protocol via `window.__wab_bidi` |
947
+ | `vision-agent.js` | Vision/NLP agent — resolves natural language intents to actions using a local keyword-based resolver (no external API) |
948
+ | `mcp-agent.js` | MCP adapter usage for Claude and GPT with tool discovery and execution |
949
+ | `cross-site-agent.js` | Multi-domain orchestration — compare prices across stores, aggregate data, find best deals |
950
+
951
+ ## Framework + CMS Examples
952
+
953
+ Additional integration examples are available in:
954
+
955
+ | Path | Description |
956
+ |---|---|
957
+ | `examples/next-app-router/` | Next.js App Router integration with `@web-agent-bridge/react` |
958
+ | `examples/shopify-hydrogen/` | Hydrogen storefront integration with practical cart actions |
959
+ | `examples/wordpress-elementor/` | WordPress + Elementor setup with schema-assisted actions |
960
+ | `examples/saas-dashboard/` | Notion-style SaaS dashboard actions for KPI read + workflow triggers |
961
+
962
+ ```bash
963
+ node examples/puppeteer-agent.js http://localhost:3000
964
+ node examples/bidi-agent.js http://localhost:3000
965
+ node examples/vision-agent.js http://localhost:3000
966
+ ```
967
+
968
+ ---
969
+
970
+ ## Multi-Database Support
971
+
972
+ WAB defaults to SQLite but supports PostgreSQL and MySQL via database adapters.
973
+
974
+ ```bash
975
+ # SQLite (default — no setup needed)
976
+ npm start
977
+
978
+ # PostgreSQL
979
+ npm install pg
980
+ DB_ADAPTER=postgresql DATABASE_URL=postgres://user:pass@localhost:5432/wab npm start
981
+
982
+ # MySQL
983
+ npm install mysql2
984
+ DB_ADAPTER=mysql DATABASE_URL=mysql://user:pass@localhost:3306/wab npm start
985
+ ```
986
+
987
+ ### When to Choose Which Database
988
+
989
+ | Scenario | Recommended DB | Why |
990
+ |---|---|---|
991
+ | Local dev / prototyping | SQLite | Zero setup, single file, instant |
992
+ | Small production (< 100 sites) | SQLite | Fast, no external dependencies |
993
+ | Medium production (100-10K sites) | PostgreSQL | Better concurrency, JSONB support |
994
+ | Large / enterprise production | PostgreSQL | Replication, backups, scalability |
995
+ | Existing MySQL infrastructure | MySQL | Integrate with what you already use |
996
+
997
+ See [`server/models/adapters/`](server/models/adapters/) for adapter implementations.
998
+
999
+ ---
1000
+
1001
+ ## Security Architecture
1002
+
1003
+ WAB implements defense-in-depth to protect the bridge from misuse:
1004
+
1005
+ ### Secure License Exchange
1006
+
1007
+ 1. **Dashboard snippet (recommended):** `siteId` + `configEndpoint`. The browser sends `POST /api/license/token` with `{ siteId }`; the server checks **Origin** against the site’s registered domain and issues a session token.
1008
+ 2. **Legacy:** `licenseKey` + `configEndpoint` (or deprecated `_licenseKey`) still works for token exchange but should not be embedded in public HTML.
1009
+ 3. **Session** is domain-locked (1h TTL); **analytics** use `sessionToken` on `POST /api/license/track` (not the license key).
1010
+ 4. **WebSocket** `/ws/analytics`: user JWT must **own** the `siteId`; admin JWT may observe any site.
1011
+
1012
+ ```
1013
+ Client Server
1014
+ │── POST /api/license/token ──→│ { siteId } + Origin header
1015
+ │ │ domain match → sessionToken
1016
+ │←── { sessionToken, tier } ──│
1017
+ │── POST /api/license/track ─→│ { sessionToken, actionName } + Origin
1018
+ ```
1019
+
1020
+ **Production:** set `JWT_SECRET`, `JWT_SECRET_ADMIN`, `STRIPE_WEBHOOK_SECRET`, `ALLOWED_ORIGINS`, and create the first admin via `BOOTSTRAP_ADMIN_*` or `node scripts/create-admin.js`.
1021
+
1022
+ ### Security Sandbox
1023
+
1024
+ Every bridge instance runs inside a `SecuritySandbox` that provides:
1025
+
1026
+ - **Session tokens** Unique cryptographic token per session prevents replay attacks
1027
+ - **Origin validation** — Only whitelisted origins can interact with the bridge
1028
+ - **Command validation** — All commands are validated for format, length, and blocklist
1029
+ - **Audit logging** — Every action is logged with timestamp, agent fingerprint, and status
1030
+ - **Escalation protection** — Attempts to access higher-tier features trigger automatic lockdown after 5 violations
1031
+ - **Auto-lockdown** — Bridge becomes read-only when security violations are detected
1032
+
1033
+ ```javascript
1034
+ // Get security status
1035
+ const info = bridge.getPageInfo();
1036
+ console.log(info.security);
1037
+ // { sandboxActive: true, locked: false, sessionToken: "a3f2..." }
1038
+
1039
+ // View audit log
1040
+ const audit = bridge.security.getAuditLog(20);
1041
+ ```
1042
+
1043
+ ### Selector Restrictions
1044
+
1045
+ Block sensitive page sections from agent access:
1046
+
1047
+ ```javascript
1048
+ window.AIBridgeConfig = {
1049
+ restrictions: {
1050
+ blockedSelectors: [".private", "[data-private]", "#payment-form"],
1051
+ allowedSelectors: [".public-content"]
1052
+ }
1053
+ };
1054
+ ```
1055
+
1056
+ ---
1057
+
1058
+ ## Self-Healing Selectors
1059
+
1060
+ Modern SPAs frequently change their DOM structure. WAB's self-healing system ensures selectors keep working even when the page changes:
1061
+
1062
+ ### How It Works
1063
+
1064
+ 1. **Fingerprinting** When actions are discovered, WAB stores a rich fingerprint of each element (tag, id, classes, text, ARIA attributes, position)
1065
+ 2. **7-Strategy Resolution** — When a selector breaks, WAB tries these strategies in order:
1066
+ - `data-wab-id` attribute (most stable — add to your HTML)
1067
+ - `data-testid` attribute
1068
+ - Element ID
1069
+ - `aria-label` (semantic, usually survives redesigns)
1070
+ - `name` attribute
1071
+ - Fuzzy text matching (bigram similarity > 70%)
1072
+ - Role + position heuristic
1073
+ 3. **SPA Observer** — A `MutationObserver` watches for DOM changes and automatically re-discovers actions with a 500ms debounce
1074
+
1075
+ ```javascript
1076
+ // Check healing stats
1077
+ const info = bridge.getPageInfo();
1078
+ console.log(info.selfHealing);
1079
+ // { tracked: 12, healed: 3, failed: 0 }
1080
+
1081
+ // Listen for healing events
1082
+ bridge.events.on('selector:healed', (data) => {
1083
+ console.log(`Healed: ${data.action} via ${data.strategy}`);
1084
+ });
1085
+ ```
1086
+
1087
+ ### Best Practices for Site Owners
1088
+
1089
+ Add `data-wab-id` attributes to critical elements for maximum stability:
1090
+
1091
+ ```html
1092
+ <button data-wab-id="signup-btn">Sign Up</button>
1093
+ <form data-wab-id="login-form">...</form>
1094
+ ```
1095
+
1096
+ ---
1097
+
1098
+ ## Stealth Mode
1099
+
1100
+ For sites with anti-bot protection, WAB can simulate human-like interaction patterns. **Stealth mode requires explicit consent** to ensure ethical use.
1101
+
1102
+ ```javascript
1103
+ window.AIBridgeConfig = {
1104
+ stealth: {
1105
+ enabled: true,
1106
+ consent: true // Required — confirms site owner authorizes human-like patterns
1107
+ }
1108
+ };
1109
+ ```
1110
+
1111
+ > **⚠️ Ethical Use Policy:** Stealth mode is designed for accessibility and testing on your own websites. Using it to bypass security controls on sites you do not own may violate terms of service and applicable laws.
1112
+
1113
+ When enabled, all interactions use:
1114
+
1115
+ | Feature | Description |
1116
+ |---|---|
1117
+ | **Mouse event chain** | `mouseover → mouseenter → mousemove → mousedown → mouseup → click` with natural coordinates |
1118
+ | **Typing simulation** | Character-by-character input with 30-120ms delays per keystroke |
1119
+ | **Scroll easing** | Multi-step scrolling with variable speed |
1120
+ | **Random delays** | 50-400ms natural pauses between actions |
1121
+
1122
+ ```javascript
1123
+ // Enable/disable at runtime (consent required)
1124
+ bridge.stealth.enable(true); // true = consent granted
1125
+ bridge.stealth.disable();
1126
+ ```
1127
+
1128
+ ---
1129
+
1130
+ ## CLI
1131
+
1132
+ Install globally or use via npx:
1133
+
1134
+ ```bash
1135
+ # Run the server
1136
+ npx web-agent-bridge start
1137
+ npx web-agent-bridge start --port 8080
1138
+
1139
+ # Initialize a new project
1140
+ npx web-agent-bridge init
1141
+ ```
1142
+
1143
+ ---
1144
+
1145
+ ## Environment Variables
1146
+
1147
+ See `.env.example`. Important:
1148
+
1149
+ ```
1150
+ PORT=3000
1151
+ NODE_ENV=development
1152
+ JWT_SECRET=long-random-user-signing-secret
1153
+ JWT_SECRET_ADMIN=long-random-admin-signing-secret # required in production
1154
+ ALLOWED_ORIGINS=http://localhost:3000,https://your-app.com
1155
+ STRIPE_WEBHOOK_SECRET=whsec_... # Stripe webhook verify
1156
+ CREDENTIALS_ENCRYPTION_KEY=... # optional SMTP password encryption
1157
+ DB_ADAPTER=sqlite
1158
+ DATABASE_URL=
1159
+ ```
1160
+
1161
+ First admin: set `BOOTSTRAP_ADMIN_EMAIL` / `BOOTSTRAP_ADMIN_PASSWORD` when the `admins` table is empty, or run `node scripts/create-admin.js <email> <password>`.
1162
+
1163
+ ---
1164
+
1165
+ ## Real-time Negotiation Engine
1166
+
1167
+ Site owners define negotiation rules. AI agents negotiate prices in multi-round sessions:
1168
+
1169
+ ```javascript
1170
+ // Agent opens a negotiation session
1171
+ const session = await fetch('/api/sovereign/negotiation/sessions', {
1172
+ method: 'POST',
1173
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1174
+ body: JSON.stringify({
1175
+ siteId: 'site-uuid',
1176
+ agentId: 'agent-id',
1177
+ originalPrice: 49.99,
1178
+ itemId: 'product-123',
1179
+ itemName: 'Olive Oil 1L'
1180
+ })
1181
+ }).then(r => r.json());
1182
+
1183
+ // Agent makes a counter-offer
1184
+ const counter = await fetch(`/api/sovereign/negotiation/sessions/${session.sessionId}/propose`, {
1185
+ method: 'POST',
1186
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1187
+ body: JSON.stringify({
1188
+ agentId: 'agent-id',
1189
+ proposedPrice: 39.99
1190
+ })
1191
+ }).then(r => r.json());
1192
+ // → { status: 'accepted', finalPrice: 42.49, message: 'Deal! ...' }
1193
+ ```
1194
+
1195
+ ### Condition Types
1196
+ | Condition | Description |
1197
+ |---|---|
1198
+ | `bulk_quantity` | Discounts based on order quantity |
1199
+ | `loyalty` | Rewards for repeat customers |
1200
+ | `time_based` | Happy hour / flash sale windows |
1201
+ | `first_purchase` | Welcome discount for new buyers |
1202
+ | `cart_value` | Minimum cart value threshold |
1203
+ | `seasonal` | Date-range seasonal promotions |
1204
+ | `membership` | Member-only pricing |
1205
+ | `referral` | Referral-based discounts |
1206
+
1207
+ ---
1208
+
1209
+ ## Anti-Hallucination Shield
1210
+
1211
+ Cross-verification engine that catches AI hallucinations before they reach users:
1212
+
1213
+ ```javascript
1214
+ // Verify a price
1215
+ const result = await fetch('/api/sovereign/verify/price', {
1216
+ method: 'POST',
1217
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1218
+ body: JSON.stringify({
1219
+ siteId: 'site-uuid',
1220
+ domValue: 29.99,
1221
+ visionValue: 29.99,
1222
+ category: 'electronics',
1223
+ itemName: 'USB Cable'
1224
+ })
1225
+ }).then(r => r.json());
1226
+ // { verified: true, confidence: 0.98, severity: 'none', layers: { dom_vision: { match: true }, ... } }
1227
+
1228
+ // Verify text content
1229
+ const textResult = await fetch('/api/sovereign/verify/text', {
1230
+ method: 'POST',
1231
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1232
+ body: JSON.stringify({
1233
+ siteId: 'site-uuid',
1234
+ source: 'dom',
1235
+ value: 'Free shipping on orders over $50',
1236
+ expected: 'Free shipping on orders over $50'
1237
+ })
1238
+ }).then(r => r.json());
1239
+ // → { verified: true, similarity: 1.0 }
1240
+ ```
1241
+
1242
+ ### Verification Layers
1243
+ 1. **DOM vs Vision** — Compares DOM-extracted price with screenshot OCR value
1244
+ 2. **Market Benchmark** Validates against historical price benchmarks for the category
1245
+ 3. **Temporal Consistency** — Checks if price changed suspiciously since last verification
1246
+ 4. **Composite Score** Weighted combination of all layers with severity classification
1247
+
1248
+ ---
1249
+
1250
+ ## Community Agent Hub
1251
+
1252
+ Pre-built YAML agent templates for common use cases. Run any template from the CLI:
1253
+
1254
+ ```bash
1255
+ # List available templates
1256
+ npx wab-agent templates
1257
+
1258
+ # Run a template
1259
+ npx wab-agent run olive-oil-tunisia --budget 50 --region tunis
1260
+
1261
+ # Run with custom server
1262
+ npx wab-agent run hotel-direct-booking --server https://yourserver.com --checkin 2025-01-15
1263
+ ```
1264
+
1265
+ ### Available Templates
1266
+ | Template | Description |
1267
+ |---|---|
1268
+ | `olive-oil-tunisia` | Find olive oil from small Tunisian farms |
1269
+ | `hotel-direct-booking` | Book hotels directly, bypass aggregators |
1270
+ | `artisan-marketplace` | Handmade products from independent artisans |
1271
+ | `grocery-price-compare` | Compare grocery prices across local stores |
1272
+ | `freelancer-direct` | Find freelancers without platform fees |
1273
+ | `restaurant-direct` | Order from restaurants without delivery apps |
1274
+ | `book-price-scout` | Find books from indie bookstores |
1275
+ | `flight-deal-hunter` | Find flights direct from airlines |
1276
+ | `electronics-price-tracker` | Track electronics prices with history |
1277
+ | `local-services` | Find local service providers |
1278
+ | `organic-farm-fresh` | Organic produce direct from farms |
1279
+
1280
+ ### Create Your Own Template
1281
+
1282
+ ```yaml
1283
+ name: my-custom-agent
1284
+ description: My custom agent template
1285
+ goal: Find the best deals on custom products
1286
+ version: "1.0"
1287
+ target_sites:
1288
+ - https://example.com
1289
+ parameters:
1290
+ budget:
1291
+ type: number
1292
+ default: 100
1293
+ description: Maximum budget
1294
+ actions:
1295
+ - name: discover
1296
+ wab_action: discover
1297
+ - name: search
1298
+ wab_action: execute
1299
+ action_name: search
1300
+ params:
1301
+ query: "{{keyword}}"
1302
+ - name: negotiate
1303
+ wab_action: negotiate
1304
+ params:
1305
+ item_id: "{{item_id}}"
1306
+ max_price: "{{budget}}"
1307
+ negotiation:
1308
+ enabled: true
1309
+ max_rounds: 3
1310
+ accept_threshold: 0.85
1311
+ fairness_rules:
1312
+ - Prefer independent sellers over large platforms
1313
+ - Verify all prices before purchase
1314
+ ```
1315
+
1316
+ ---
1317
+
1318
+ ## Commander Agent System
1319
+
1320
+ The Commander is a local-first mission orchestration engine that decomposes high-level goals into task DAGs and distributes work across specialized agents:
1321
+
1322
+ ```javascript
1323
+ // Create a mission
1324
+ const mission = await fetch('/api/commander/missions', {
1325
+ method: 'POST',
1326
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1327
+ body: JSON.stringify({
1328
+ goal: 'Find the cheapest olive oil across 5 stores',
1329
+ strategy: 'parallel',
1330
+ agents: ['researcher-1', 'analyst-1', 'negotiator-1']
1331
+ })
1332
+ }).then(r => r.json());
1333
+
1334
+ // Launch mission
1335
+ await fetch(`/api/commander/missions/${mission.id}/launch`, { method: 'POST', headers: { 'Authorization': 'Bearer ' + token } });
1336
+
1337
+ // Check status
1338
+ const status = await fetch(`/api/commander/missions/${mission.id}`, { headers: { 'Authorization': 'Bearer ' + token } }).then(r => r.json());
1339
+ // → { status: 'completed', tasks: [...], result: { bestPrice: 12.99, store: 'farm-direct' } }
1340
+ ```
1341
+
1342
+ ### Commander Capabilities
1343
+ | Feature | Description |
1344
+ |---|---|
1345
+ | **Mission Decomposition** | Breaks high-level goals into task DAGs with dependency tracking |
1346
+ | **Agent Registry** | Tracks agent capabilities, availability, and performance history |
1347
+ | **Parallel Execution** | Runs independent tasks concurrently across multiple agents |
1348
+ | **Learning Integration** | Records outcomes for reinforcement learning feedback |
1349
+ | **Edge Coordination** | Distributes compute-heavy tasks to edge nodes |
1350
+
1351
+ ---
1352
+
1353
+ ## Edge Compute System
1354
+
1355
+ Transform every user device into a sovereign AI node — no central cloud required:
1356
+
1357
+ ```javascript
1358
+ // Register a device as an edge node
1359
+ const node = await fetch('/api/commander/edge/nodes', {
1360
+ method: 'POST',
1361
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1362
+ body: JSON.stringify({
1363
+ name: 'my-laptop',
1364
+ capabilities: { cpu: 8, ram: 16384, gpu: true },
1365
+ supportedTasks: ['text-inference', 'vision-analysis', 'price-comparison']
1366
+ })
1367
+ }).then(r => r.json());
1368
+
1369
+ // List available edge nodes
1370
+ const nodes = await fetch('/api/commander/edge/nodes', { headers: { 'Authorization': 'Bearer ' + token } }).then(r => r.json());
1371
+ ```
1372
+
1373
+ | Feature | Description |
1374
+ |---|---|
1375
+ | **Hardware Profiling** | Detects CPU, RAM, GPU capabilities per node |
1376
+ | **AES-256-GCM Encryption** | All inter-node data is encrypted end-to-end |
1377
+ | **Weighted Load Balancing** | Routes tasks based on hardware + availability scores |
1378
+ | **Heartbeat Health Monitoring** | Auto-failover when nodes become unresponsive |
1379
+ | **Swarm Formation** | Capability-based clustering of nodes for distributed tasks |
1380
+
1381
+ ---
1382
+
1383
+ ## Swarm Execution Engine
1384
+
1385
+ Launch multiple agents in parallel to solve a single task, then intelligently merge their outputs:
1386
+
1387
+ ```javascript
1388
+ // Launch a swarm task
1389
+ const swarm = await fetch('/api/premium/v2/swarm/execute', {
1390
+ method: 'POST',
1391
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1392
+ body: JSON.stringify({
1393
+ task: 'Find best laptop deals under $1000',
1394
+ strategy: 'parallel', // parallel | sequential | hybrid
1395
+ agentCount: 4,
1396
+ roles: ['researcher', 'analyst', 'price-checker', 'reviewer'],
1397
+ mergeStrategy: 'best-score' // best-score | fairness-weighted | consensus
1398
+ })
1399
+ }).then(r => r.json());
1400
+ // { swarmId: '...', agents: 4, status: 'running' }
1401
+
1402
+ // Get merged results
1403
+ const results = await fetch(`/api/premium/v2/swarm/${swarm.swarmId}`, {
1404
+ headers: { 'Authorization': 'Bearer ' + token }
1405
+ }).then(r => r.json());
1406
+ // { status: 'completed', merged: { bestDeal: {...}, confidence: 0.94 } }
1407
+ ```
1408
+
1409
+ ---
1410
+
1411
+ ## Fairness Engine
1412
+
1413
+ A neutrality layer ensuring AI agents give equal opportunity to small and large sites, preventing monopolistic concentration of agent traffic:
1414
+
1415
+ ```javascript
1416
+ // Fairness-weighted search (instead of pure relevance)
1417
+ const results = await fetch('/api/discovery/search?q=olive+oil&fairness=true', {
1418
+ headers: { 'Authorization': 'Bearer ' + token }
1419
+ }).then(r => r.json());
1420
+ // Small farms ranked alongside Amazon — weighted by neutrality score, not just SEO
1421
+
1422
+ // Register site in WAB directory
1423
+ await fetch('/api/discovery/register', {
1424
+ method: 'POST',
1425
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1426
+ body: JSON.stringify({
1427
+ domain: 'small-farm.example.com',
1428
+ category: 'food',
1429
+ commissionRate: 0, // Direct no middleman
1430
+ independentSeller: true
1431
+ })
1432
+ }).then(r => r.json());
1433
+ ```
1434
+
1435
+ ### How Neutrality Scoring Works
1436
+ | Factor | Weight | Description |
1437
+ |---|---|---|
1438
+ | **Configuration completeness** | 25% | How well the site has configured WAB |
1439
+ | **Trust score** | 25% | Reputation attestations from the agent network |
1440
+ | **Transparency** | 25% | Commission disclosure, pricing clarity |
1441
+ | **Responsiveness** | 25% | API response time, uptime, action success rate |
1442
+
1443
+ Small independent sites with good WAB configuration can outrank large platforms on fairness-weighted searches.
1444
+
1445
+ ---
1446
+
1447
+ ## Agent Memory System
1448
+
1449
+ Persistent behavioral memory allowing agents to remember user preferences, learn patterns, and build associations:
1450
+
1451
+ ```javascript
1452
+ // Store a memory
1453
+ await fetch('/api/premium/v2/memory', {
1454
+ method: 'POST',
1455
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1456
+ body: JSON.stringify({
1457
+ agentId: 'agent-1',
1458
+ type: 'preference', // preference | interaction | correction | pattern
1459
+ category: 'purchase', // navigation | purchase | search | form | custom
1460
+ key: 'preferred-brand',
1461
+ value: 'organic-only',
1462
+ importance: 0.9
1463
+ })
1464
+ }).then(r => r.json());
1465
+
1466
+ // Recall memories
1467
+ const memories = await fetch('/api/premium/v2/memory/agent-1?category=purchase&limit=10', {
1468
+ headers: { 'Authorization': 'Bearer ' + token }
1469
+ }).then(r => r.json());
1470
+
1471
+ // Create associations
1472
+ await fetch('/api/premium/v2/memory/associate', {
1473
+ method: 'POST',
1474
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1475
+ body: JSON.stringify({
1476
+ sourceId: 'memory-1',
1477
+ targetId: 'memory-2',
1478
+ relationship: 'leads_to' // leads_to | similar_to | replaces | depends_on
1479
+ })
1480
+ }).then(r => r.json());
1481
+ ```
1482
+
1483
+ ---
1484
+
1485
+ ## Vision Analysis Service
1486
+
1487
+ Multi-provider screenshot analysis for interactive element detection and data extraction:
1488
+
1489
+ ```javascript
1490
+ // Analyze a screenshot
1491
+ const analysis = await fetch('/api/premium/v2/vision/analyze', {
1492
+ method: 'POST',
1493
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1494
+ body: JSON.stringify({
1495
+ screenshot: 'base64-encoded-image...',
1496
+ provider: 'auto', // auto | local | openai | anthropic | ollama
1497
+ extractElements: true
1498
+ })
1499
+ }).then(r => r.json());
1500
+ // → { elements: [{ type: 'button', text: 'Add to Cart', selector: '#add-btn', confidence: 0.95, bbox: [120, 340, 200, 40] }] }
1501
+
1502
+ // Extract interactive elements only
1503
+ const elements = await fetch('/api/premium/v2/vision/elements', {
1504
+ method: 'POST',
1505
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1506
+ body: JSON.stringify({ screenshot: 'base64...', types: ['button', 'input', 'link'] })
1507
+ }).then(r => r.json());
1508
+ ```
1509
+
1510
+ ### Supported Vision Providers
1511
+ | Provider | Local? | Description |
1512
+ |---|---|---|
1513
+ | **Moondream** | ✅ | Lightweight local vision model |
1514
+ | **Ollama** | ✅ | Local models via Ollama (llava, bakllava) |
1515
+ | **OpenAI** | ❌ | GPT-4 Vision |
1516
+ | **Anthropic** | | Claude Vision |
1517
+
1518
+ ---
1519
+
1520
+ ## Plugin Architecture
1521
+
1522
+ Dynamic plugin system allowing third-party extensions:
1523
+
1524
+ ```javascript
1525
+ // List available plugins
1526
+ const plugins = await fetch('/api/premium/v2/plugins', {
1527
+ headers: { 'Authorization': 'Bearer ' + token }
1528
+ }).then(r => r.json());
1529
+
1530
+ // Install a plugin for your site
1531
+ await fetch('/api/premium/v2/plugins/price-alert/install', {
1532
+ method: 'POST',
1533
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1534
+ body: JSON.stringify({ siteId: 'site-uuid', config: { threshold: 10 } })
1535
+ }).then(r => r.json());
1536
+
1537
+ // Execute a plugin hook
1538
+ await fetch('/api/premium/v2/plugins/price-alert/hooks', {
1539
+ method: 'POST',
1540
+ headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
1541
+ body: JSON.stringify({ hook: 'onPriceChange', data: { oldPrice: 49.99, newPrice: 39.99 } })
1542
+ }).then(r => r.json());
1543
+ ```
1544
+
1545
+ ---
1546
+
1547
+ ## Premium Traffic Intelligence
1548
+
1549
+ Advanced bot detection and traffic profiling for premium sites:
1550
+
1551
+ | Capability | Description |
1552
+ |---|---|
1553
+ | **30+ Bot Types** | Detects Google, Bing, ChatGPT, Claude, Perplexity, and more |
1554
+ | **Behavioral Profiling** | Classifies agent behavior by signature, platform, and type |
1555
+ | **Anomaly Detection** | Spike detection and pattern analysis for unusual traffic |
1556
+ | **Security Exploit Detection** | Flags SQL injection, XSS patterns, and rate anomalies |
1557
+ | **Webhook Alerting** | Triggers webhooks on suspicious activity |
1558
+ | **Compliance Audit Logging** | Full audit trail for regulatory compliance |
1559
+
1560
+ ---
1561
+
1562
+ ## WAB-MCP Adapter
1563
+
1564
+ Expose WAB site capabilities as [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) tools for Claude, GPT, Gemini, and other MCP-compatible AI agents:
1565
+
1566
+ ```javascript
1567
+ const { WABMCPAdapter } = require('wab-mcp-adapter');
1568
+
1569
+ // Create adapter for a WAB-enabled site
1570
+ const adapter = new WABMCPAdapter({
1571
+ siteUrl: 'https://shop.example.com',
1572
+ transport: 'http' // http | websocket | direct
1573
+ });
1574
+
1575
+ // Get MCP tool definitions
1576
+ const tools = await adapter.getTools();
1577
+ // → [{ name: 'discover', description: '...', inputSchema: {...} }, ...]
1578
+
1579
+ // Execute via MCP
1580
+ const result = await adapter.executeTool('execute_action', {
1581
+ name: 'addToCart',
1582
+ params: { sku: 'ABC123' }
1583
+ });
1584
+ ```
1585
+
1586
+ ### Built-in MCP Tools
1587
+ | Tool | Description |
1588
+ |---|---|
1589
+ | `discover` | Auto-discover available actions on a WAB site |
1590
+ | `get_actions` | Get list of all actions with parameters |
1591
+ | `execute_action` | Execute a specific action |
1592
+ | `read_content` | Read content from the page |
1593
+ | `get_page_info` | Get page metadata |
1594
+ | `fairness_search` | Search the WAB directory with fairness weighting |
1595
+ | `authenticate` | Authenticate an agent with the site |
1596
+
1597
+ ---
1598
+
1599
+ ## WAB Browser (Desktop)
1600
+
1601
+ Standalone Electron desktop browser with built-in privacy and fairness features:
1602
+
1603
+ - **Ad Blocker** — 80+ blocked ad domains + URL pattern matching + cosmetic CSS rules
1604
+ - **Scam Shield** — Detects suspicious TLDs and brand-name spoofing in URLs
1605
+ - **Fairness Ranking** — Prioritizes independent sites, flags big-tech concentration
1606
+ - **Agent Chat** — Built-in AI assistant panel for browsing help
1607
+ - **Notifications** — Page analysis with safety and fairness alerts
1608
+ - **Ghost Mode** — Privacy-first browsing with no tracking
1609
+ - **Smart Search** — WAB Search integration for independent search
1610
+ - **Desktop/Mobile Toggle** — Switch user-agent for responsive testing
1611
+
1612
+ ```bash
1613
+ # Run the WAB Browser
1614
+ cd wab-browser
1615
+ npm install
1616
+ npx electron .
1617
+
1618
+ # Build installer (Windows NSIS)
1619
+ npm run build:win
1620
+ ```
1621
+
1622
+ ---
1623
+
1624
+ ## PWA Browser (Mobile)
1625
+
1626
+ Progressive Web App browser for Android and iOS — installable from any mobile browser:
1627
+
1628
+ - **Ad Blocker** — 80+ ad domain blacklist + URL pattern matching
1629
+ - **Scam Detection** — Suspicious TLD alerts and brand-name spoofing checks
1630
+ - **Fairness Mode** — Filters big-tech sites to promote independent alternatives
1631
+ - **Offline-First** — Service worker caches shell assets for offline launch
1632
+ - **WAB Search** — Independent search engine with multi-source aggregation, autocomplete, and trending
1633
+ - **AI Agent Chat** — Real AI agent (OpenAI / local Ollama / smart fallback) with conversation memory, web search, and security analysis
1634
+
1635
+ Install at: `https://yourserver.com/pwa/`
1636
+
1637
+ ---
1638
+
1639
+ ## WordPress Plugin
1640
+
1641
+ Native WordPress plugin for adding WAB support to any WordPress site.
1642
+
1643
+ ### Standard Plugin (Deactivatable)
1644
+
1645
+ ```bash
1646
+ # Install manually
1647
+ cp -r web-agent-bridge-wordpress/ /wp-content/plugins/web-agent-bridge/
1648
+
1649
+ # Or install via WP-CLI from WordPress.org
1650
+ wp plugin install web-agent-bridge --activate
1651
+ ```
1652
+
1653
+ | Feature | Description |
1654
+ |---|---|
1655
+ | **Settings Page** | Configure API base URL, site ID, permissions |
1656
+ | **Per-Page Actions** | Meta box for adding custom WAB actions per page/post |
1657
+ | **Discovery Document** | Auto-generates WAB discovery endpoint |
1658
+ | **Dashboard Widget** | Shows WAB status and agent interaction stats |
1659
+ | **Shortcode** | `[wab_bridge]` shortcode for embedding WAB on specific pages |
1660
+ | **Hooks API** | `wab_before_action` / `wab_after_action` for custom logic |
1661
+
1662
+ ### Must-Use Plugin (Always Active, Cannot Be Deactivated)
1663
+
1664
+ For hosting providers and managed WordPress environments:
1665
+
1666
+ ```bash
1667
+ # One-command install (requires WP-CLI)
1668
+ bash web-agent-bridge-wordpress/mu-plugin/install-wab-mu.sh --wp-path /var/www/html
1669
+
1670
+ # Or manually copy to mu-plugins/
1671
+ cp web-agent-bridge-wordpress/mu-plugin/web-agent-bridge-mu.php /wp-content/mu-plugins/
1672
+ wp rewrite flush
1673
+ ```
1674
+
1675
+ The MU plugin is **always loaded by WordPress core** before any regular plugin — it cannot be deactivated from the admin panel. When the full plugin is absent, it runs a minimal fallback that serves `/.well-known/wab.json` and injects the WAB script.
1676
+
1677
+ **wp-config.php overrides:**
1678
+ ```php
1679
+ define( 'WAB_MU_API_BASE', 'https://wab.yourdomain.com' ); // Custom WAB server
1680
+ define( 'WAB_MU_DISCOVERY_CACHE_TTL', 600 ); // Cache TTL in seconds
1681
+ ```
1682
+
1683
+ See [`web-agent-bridge-wordpress/README.md`](web-agent-bridge-wordpress/README.md) and [`web-agent-bridge-wordpress/mu-plugin/README.md`](web-agent-bridge-wordpress/mu-plugin/README.md) for full documentation.
1684
+
1685
+ ---
1686
+
1687
+ ## WAB Protocol Specification
1688
+
1689
+ The full normative specification is available at [`docs/SPEC.md`](docs/SPEC.md):
1690
+
1691
+ | Layer | Description |
1692
+ |---|---|
1693
+ | **Protocol Layer** | Discovery document format, command protocol, fairness protocol |
1694
+ | **Runtime Layer** | `window.AICommands` interface, auto-discovery engine, security sandbox |
1695
+ | **Transport Layer** | JavaScript global, WebSocket, HTTP, WebDriver BiDi, MCP |
1696
+
1697
+ ### DNS Discovery
1698
+
1699
+ WAB supports DNS-level discovery, allowing AI agents to find your capabilities document without any HTTP request. Add a single TXT record to your domain:
1700
+
1701
+ ```
1702
+ _wab.yourdomain.com TXT "v=wab1; endpoint=https://yourdomain.com/.well-known/wab.json"
1703
+ ```
1704
+
1705
+ Full setup guides for Cloudflare, cPanel, GoDaddy, and Namecheap are available in:
1706
+ - [DNS-DISCOVERY.md](DNS-DISCOVERY.md) — English
1707
+ - [DNS-DISCOVERY.ar.md](DNS-DISCOVERY.ar.md) — العربية
1708
+
1709
+ ### 5-Phase Lifecycle
1710
+ 1. **Discover** — Agent finds WAB discovery document (`.well-known/wab.json` or script tag)
1711
+ 2. **Authenticate** — Agent exchanges `siteId` for session token
1712
+ 3. **Plan** — Agent reads available actions and page metadata
1713
+ 4. **Execute** — Agent runs actions through the bridge
1714
+ 5. **Confirm** — Results are verified via Anti-Hallucination Shield
1715
+
1716
+ ---
1717
+
1718
+ ## License
1719
+
1720
+ WAB uses an **Open Core** dual-license model:
1721
+
1722
+ | Layer | License | Components |
1723
+ |-------|---------|------------|
1724
+ | **Open Source** | MIT | SDK, Widget, MCP Server, Trust Protocol Spec, Browser Extension, Protocol module, Public module APIs, install.sh, Cloudflare Worker, Netlify Functions, Vercel config, Railway config |
1725
+ | **Open Source** | GPL-2.0 | WordPress Plugin (standard + Must-Use), WP-CLI installer |
1726
+ | **Proprietary (Free)** | Closed / Free | Detection Engine, Threat DB, WAB Score Model, Fairness Algorithm, Neural Engine, Dark Pattern Engine, Gov Engine, Notary Engine, Firewall Engine, Price Engine, Bargaining Engine, Bounty Verification, Affiliate DB |
1727
+ | **Commercial** | Paid API | API Gateway modules (Free/Pro/Business/Enterprise tiers), Data Marketplace, AI Safety Layer, Enterprise SDK |
1728
+
1729
+ ### Integration Components License Summary
1730
+
1731
+ | Integration | File | License | Notes |
1732
+ |---|---|---|---|
1733
+ | Linux Installer | `integrations/install/install.sh` | MIT | Fully open source |
1734
+ | Docker | `Dockerfile`, `docker-compose*.yml` | MIT | Fully open source |
1735
+ | Cloudflare Worker | `integrations/cloudflare-worker/worker.js` | MIT | Fully open source |
1736
+ | Netlify Functions | `integrations/netlify/functions/` | MIT | Fully open source |
1737
+ | Vercel Config | `integrations/vercel/vercel.json` | MIT | Fully open source |
1738
+ | Railway Config | `integrations/railway/railway.json` | MIT | Fully open source |
1739
+ | WordPress Plugin | `web-agent-bridge-wordpress/` | GPL-2.0 | Fully open source |
1740
+ | WordPress MU Plugin | `web-agent-bridge-wordpress/mu-plugin/` | GPL-2.0 | Fully open source |
1741
+ | WAB Server Core | `server/` | Open Core | Free tier + paid features |
1742
+ | WAB Browser | `wab-browser/` | Proprietary (Free) | Free to use, source private |
1743
+ | DNS Discovery Docs | `DNS-DISCOVERY.md` | MIT | Fully open source |
1744
+
1745
+ See [LICENSE](LICENSE) for full details.
1746
+
1747
+ ## Contributors ✨
1748
+
1749
+ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
1750
+ <!-- prettier-ignore-start -->
1751
+ <!-- markdownlint-disable -->
1752
+ <table>
1753
+ <tbody>
1754
+ <tr>
1755
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/abokenan444"><img src="https://avatars.githubusercontent.com/u/abokenan444?s=100" width="100px;" alt="WAB Founder"/><br /><sub><b>WAB Founder</b></sub></a><br /><a href="https://github.com/abokenan444/web-agent-bridge/commits?author=abokenan444" title="Code">💻</a> <a href="#ideas-abokenan444" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/abokenan444/web-agent-bridge/commits?author=abokenan444" title="Documentation">📖</a> <a href="#design-abokenan444" title="Design">🎨</a> <a href="#maintenance-abokenan444" title="Maintenance">🚧</a> <a href="#projectManagement-abokenan444" title="Project Management">📆</a></td>
1756
+ </tr>
1757
+ </tbody>
1758
+ </table>
1759
+
1760
+ <!-- markdownlint-restore -->
1761
+ <!-- prettier-ignore-end -->
1762
+
1763
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
1764
+