web-agent-bridge 3.4.0 → 3.8.1

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 (310) hide show
  1. package/LICENSE +84 -84
  2. package/README.ar.md +1563 -1304
  3. package/README.md +137 -298
  4. package/bin/agent-runner.js +474 -474
  5. package/bin/cli.js +237 -237
  6. package/bin/wab-init.js +244 -223
  7. package/bin/wab.js +80 -80
  8. package/examples/azure-dns-wab.js +83 -83
  9. package/examples/bidi-agent.js +119 -119
  10. package/examples/cloudflare-wab-dns.js +121 -121
  11. package/examples/cpanel-wab-dns.js +114 -114
  12. package/examples/cross-site-agent.js +91 -91
  13. package/examples/dns-discovery-agent.js +166 -166
  14. package/examples/gcp-dns-wab.js +76 -76
  15. package/examples/governance-agent.js +169 -169
  16. package/examples/mcp-agent.js +94 -94
  17. package/examples/next-app-router/README.md +44 -44
  18. package/examples/plesk-wab-dns.js +103 -103
  19. package/examples/puppeteer-agent.js +108 -108
  20. package/examples/route53-wab-dns.js +144 -144
  21. package/examples/saas-dashboard/README.md +55 -55
  22. package/examples/safe-mode-agent.js +96 -96
  23. package/examples/self-discovery.js +106 -0
  24. package/examples/shopify-hydrogen/README.md +74 -74
  25. package/examples/vision-agent.js +171 -171
  26. package/examples/wab-sign.js +74 -74
  27. package/examples/wab-verify.js +60 -60
  28. package/examples/wordpress-elementor/README.md +77 -77
  29. package/package.json +93 -93
  30. package/public/.well-known/agent-tools.json +180 -180
  31. package/public/.well-known/ai-assets.json +59 -59
  32. package/public/.well-known/security.txt +8 -8
  33. package/public/.well-known/wab.json +28 -28
  34. package/public/activate.html +448 -368
  35. package/public/adopt.html +236 -0
  36. package/public/adoption-metrics.html +188 -188
  37. package/public/agent-workspace.html +359 -349
  38. package/public/ai.html +198 -198
  39. package/public/api.html +397 -413
  40. package/public/azure-dns-integration.html +289 -289
  41. package/public/browser.html +486 -486
  42. package/public/cloudflare-integration.html +380 -380
  43. package/public/commander-dashboard.html +243 -243
  44. package/public/cookies.html +210 -210
  45. package/public/cpanel-integration.html +398 -398
  46. package/public/css/agent-workspace.css +1713 -1713
  47. package/public/css/premium.css +317 -317
  48. package/public/css/styles.css +1401 -1263
  49. package/public/dashboard-shieldlink.html +295 -0
  50. package/public/dashboard.html +711 -707
  51. package/public/dns.html +436 -436
  52. package/public/docs.html +588 -588
  53. package/public/enterprise-mesh.ar.html +80 -0
  54. package/public/enterprise-mesh.html +81 -0
  55. package/public/feed.xml +89 -89
  56. package/public/gcp-dns-integration.html +318 -318
  57. package/public/governance.ar.html +70 -0
  58. package/public/governance.html +69 -0
  59. package/public/growth.html +465 -465
  60. package/public/index.html +1372 -1266
  61. package/public/integrations.html +556 -556
  62. package/public/js/activate.js +449 -145
  63. package/public/js/agent-workspace.js +1740 -1740
  64. package/public/js/auth-nav.js +117 -65
  65. package/public/js/auth-redirect.js +12 -12
  66. package/public/js/cookie-consent.js +56 -56
  67. package/public/js/dns.js +438 -438
  68. package/public/js/wab-demo-page.js +721 -721
  69. package/public/js/ws-client.js +74 -74
  70. package/public/l-preview.html +242 -0
  71. package/public/llms-full.txt +360 -360
  72. package/public/llms.txt +125 -125
  73. package/public/login.html +85 -85
  74. package/public/mesh-dashboard.html +328 -328
  75. package/public/milestones.html +346 -0
  76. package/public/one-click.html +779 -0
  77. package/public/openapi.json +669 -669
  78. package/public/partners.ar.html +145 -0
  79. package/public/partners.html +143 -0
  80. package/public/phone-shield.html +281 -281
  81. package/public/plesk-integration.html +375 -375
  82. package/public/premium-dashboard.html +2489 -2489
  83. package/public/premium.html +793 -793
  84. package/public/privacy.html +297 -297
  85. package/public/provider-onboarding.html +172 -172
  86. package/public/provider-sandbox.html +134 -134
  87. package/public/providers.html +359 -359
  88. package/public/refusals.html +172 -0
  89. package/public/register.html +105 -105
  90. package/public/registrar-integrations.html +141 -141
  91. package/public/ring4.html +292 -0
  92. package/public/robots.txt +99 -99
  93. package/public/route53-integration.html +531 -531
  94. package/public/score.html +263 -0
  95. package/public/script/wab-consent.d.ts +36 -36
  96. package/public/script/wab-consent.js +104 -104
  97. package/public/script/wab-schema.js +131 -131
  98. package/public/script/wab.d.ts +108 -108
  99. package/public/script/wab.min.js +580 -580
  100. package/public/security.txt +8 -8
  101. package/public/shieldlink.html +244 -0
  102. package/public/shieldqr.html +231 -231
  103. package/public/sitemap.xml +13 -1
  104. package/public/terms.html +256 -256
  105. package/public/trust-graph-api.ar.html +92 -0
  106. package/public/trust-graph-api.html +91 -0
  107. package/public/wab-features.html +560 -0
  108. package/public/wab-trust.html +200 -200
  109. package/public/wab-truth.html +375 -0
  110. package/public/wab-vs-protocols.html +210 -210
  111. package/public/whitepaper.html +449 -449
  112. package/script/ai-agent-bridge.js +1754 -1754
  113. package/sdk/README.md +99 -99
  114. package/sdk/agent-mesh.js +449 -449
  115. package/sdk/auto-discovery.js +301 -288
  116. package/sdk/commander.js +262 -262
  117. package/sdk/governance.js +262 -262
  118. package/sdk/index.d.ts +464 -464
  119. package/sdk/index.js +649 -649
  120. package/sdk/multi-agent.js +318 -318
  121. package/sdk/safe-mode.js +221 -221
  122. package/sdk/safety-shield.js +219 -219
  123. package/sdk/schema-discovery.js +83 -83
  124. package/server/adapters/index.js +520 -520
  125. package/server/config/plans.js +412 -367
  126. package/server/config/secrets.js +102 -102
  127. package/server/control-plane/index.js +301 -301
  128. package/server/data-plane/index.js +354 -354
  129. package/server/index.js +790 -670
  130. package/server/llm/index.js +404 -404
  131. package/server/middleware/adminAuth.js +35 -35
  132. package/server/middleware/api-tier.js +170 -0
  133. package/server/middleware/auth.js +50 -50
  134. package/server/middleware/featureGate.js +88 -88
  135. package/server/middleware/rateLimits.js +100 -100
  136. package/server/middleware/sensitiveAction.js +157 -157
  137. package/server/middleware/wab-trust.js +141 -0
  138. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  139. package/server/migrations/002_premium_features.sql +418 -418
  140. package/server/migrations/003_ads_integer_cents.sql +33 -33
  141. package/server/migrations/004_agent_os.sql +158 -158
  142. package/server/migrations/005_marketplace_metering.sql +126 -126
  143. package/server/migrations/006_growth_suite.sql +138 -0
  144. package/server/migrations/007_governance.sql +106 -106
  145. package/server/migrations/008_plans.sql +144 -144
  146. package/server/migrations/009_shieldqr.sql +30 -30
  147. package/server/migrations/010_extended_trust.sql +33 -33
  148. package/server/migrations/011_outreach.sql +47 -0
  149. package/server/migrations/012_shieldlink.sql +116 -0
  150. package/server/migrations/013_ct_monitor.sql +13 -0
  151. package/server/migrations/014_wab_advanced_features.sql +128 -0
  152. package/server/migrations/015_wab_truth_layer.sql +101 -0
  153. package/server/migrations/016_ring4_external_trust.sql +84 -0
  154. package/server/migrations/017_ring4_extensions.sql +69 -0
  155. package/server/migrations/018_commercial_foundations.sql +167 -0
  156. package/server/migrations/019_unify_tier_constraints.sql +133 -0
  157. package/server/models/adapters/index.js +33 -33
  158. package/server/models/adapters/mysql.js +183 -183
  159. package/server/models/adapters/postgresql.js +172 -172
  160. package/server/models/adapters/sqlite.js +7 -7
  161. package/server/models/db.js +740 -740
  162. package/server/observability/failure-analysis.js +337 -337
  163. package/server/observability/index.js +394 -394
  164. package/server/protocol/capabilities.js +223 -223
  165. package/server/protocol/index.js +243 -243
  166. package/server/protocol/schema.js +584 -584
  167. package/server/registry/certification.js +271 -271
  168. package/server/registry/index.js +326 -326
  169. package/server/routes/activate.js +478 -0
  170. package/server/routes/admin-outreach.js +239 -0
  171. package/server/routes/admin-plans.js +76 -76
  172. package/server/routes/admin-premium.js +674 -673
  173. package/server/routes/admin-shieldlink.js +137 -0
  174. package/server/routes/admin-shieldqr.js +90 -90
  175. package/server/routes/admin-trust-monitor.js +139 -83
  176. package/server/routes/admin.js +550 -549
  177. package/server/routes/adopt.js +61 -0
  178. package/server/routes/ads.js +130 -130
  179. package/server/routes/agent-workspace.js +540 -540
  180. package/server/routes/api-keys.js +127 -0
  181. package/server/routes/api.js +150 -150
  182. package/server/routes/auth.js +71 -71
  183. package/server/routes/billing.js +57 -57
  184. package/server/routes/commander.js +316 -316
  185. package/server/routes/customer-shieldlink.js +133 -0
  186. package/server/routes/demo-showcase.js +332 -332
  187. package/server/routes/demo-store.js +154 -154
  188. package/server/routes/diagnose.js +373 -0
  189. package/server/routes/discovery.js +2348 -2348
  190. package/server/routes/enterprise-mesh.js +170 -0
  191. package/server/routes/gateway.js +173 -173
  192. package/server/routes/governance-saas.js +203 -0
  193. package/server/routes/governance.js +208 -208
  194. package/server/routes/growth.js +1048 -0
  195. package/server/routes/intent.js +328 -0
  196. package/server/routes/license.js +251 -251
  197. package/server/routes/mesh.js +469 -469
  198. package/server/routes/noscript.js +543 -543
  199. package/server/routes/partners.js +201 -0
  200. package/server/routes/plans.js +33 -33
  201. package/server/routes/premium-v2.js +686 -686
  202. package/server/routes/premium.js +724 -724
  203. package/server/routes/providers.js +650 -650
  204. package/server/routes/reputation.js +411 -0
  205. package/server/routes/ring4.js +885 -0
  206. package/server/routes/runtime.js +2148 -2148
  207. package/server/routes/shieldlink.js +70 -0
  208. package/server/routes/shieldqr.js +88 -88
  209. package/server/routes/sovereign.js +465 -465
  210. package/server/routes/truth-layer.js +670 -0
  211. package/server/routes/universal.js +200 -200
  212. package/server/routes/unsubscribe.js +51 -0
  213. package/server/routes/wab-api.js +850 -850
  214. package/server/routes/wab-cache.js +282 -0
  215. package/server/runtime/container-worker.js +111 -111
  216. package/server/runtime/container.js +448 -448
  217. package/server/runtime/distributed-worker.js +362 -362
  218. package/server/runtime/event-bus.js +210 -210
  219. package/server/runtime/index.js +253 -253
  220. package/server/runtime/queue.js +599 -599
  221. package/server/runtime/replay.js +666 -666
  222. package/server/runtime/sandbox.js +266 -266
  223. package/server/runtime/scheduler.js +534 -534
  224. package/server/runtime/session-engine.js +293 -293
  225. package/server/runtime/state-manager.js +188 -188
  226. package/server/secrets/wab-signing-key.pem +3 -0
  227. package/server/secrets/wab-signing-pub.pem +3 -0
  228. package/server/security/cross-site-redactor.js +196 -196
  229. package/server/security/dry-run.js +180 -180
  230. package/server/security/human-gate-rate-limit.js +147 -147
  231. package/server/security/human-gate-transports.js +178 -178
  232. package/server/security/human-gate.js +281 -281
  233. package/server/security/index.js +368 -368
  234. package/server/security/intent-engine.js +245 -245
  235. package/server/security/reward-guard.js +171 -171
  236. package/server/security/rollback-store.js +239 -239
  237. package/server/security/token-scope.js +404 -404
  238. package/server/security/url-policy.js +139 -139
  239. package/server/services/adoption-agent.js +182 -0
  240. package/server/services/agent-chat.js +506 -506
  241. package/server/services/agent-learning.js +601 -601
  242. package/server/services/agent-memory.js +625 -625
  243. package/server/services/agent-mesh.js +555 -555
  244. package/server/services/agent-symphony.js +717 -717
  245. package/server/services/agent-tasks.js +1807 -1807
  246. package/server/services/api-key-engine.js +292 -292
  247. package/server/services/cluster.js +894 -894
  248. package/server/services/commander.js +738 -738
  249. package/server/services/edge-compute.js +440 -440
  250. package/server/services/email.js +233 -233
  251. package/server/services/fairness-engine.js +409 -0
  252. package/server/services/fairness.js +420 -0
  253. package/server/services/governance.js +466 -466
  254. package/server/services/hosted-runtime.js +205 -205
  255. package/server/services/lfd.js +635 -635
  256. package/server/services/local-ai.js +389 -389
  257. package/server/services/marketplace.js +270 -270
  258. package/server/services/metering.js +182 -182
  259. package/server/services/modules/affiliate-intelligence.js +93 -93
  260. package/server/services/modules/agent-firewall.js +90 -90
  261. package/server/services/modules/bounty.js +89 -89
  262. package/server/services/modules/collective-bargaining.js +92 -92
  263. package/server/services/modules/dark-pattern.js +66 -66
  264. package/server/services/modules/gov-intelligence.js +45 -45
  265. package/server/services/modules/neural.js +55 -55
  266. package/server/services/modules/notary.js +49 -49
  267. package/server/services/modules/price-time-machine.js +86 -86
  268. package/server/services/modules/protocol.js +104 -104
  269. package/server/services/negotiation.js +439 -439
  270. package/server/services/outreach-agent.js +312 -0
  271. package/server/services/plans.js +214 -214
  272. package/server/services/plugins.js +771 -771
  273. package/server/services/price-intelligence.js +566 -566
  274. package/server/services/price-shield.js +1137 -1137
  275. package/server/services/provider-clients.js +740 -740
  276. package/server/services/reputation.js +465 -465
  277. package/server/services/search-engine.js +357 -357
  278. package/server/services/security.js +513 -513
  279. package/server/services/self-healing.js +843 -843
  280. package/server/services/shieldlink.js +492 -0
  281. package/server/services/shieldqr.js +322 -322
  282. package/server/services/sovereign-shield.js +542 -542
  283. package/server/services/ssl-ct-monitor.js +224 -0
  284. package/server/services/ssl-inspector.js +42 -42
  285. package/server/services/ssl-monitor.js +167 -167
  286. package/server/services/stripe.js +206 -205
  287. package/server/services/swarm.js +788 -788
  288. package/server/services/universal-scraper.js +662 -662
  289. package/server/services/verification.js +481 -481
  290. package/server/services/vision.js +1163 -1163
  291. package/server/services/wab-crypto.js +178 -178
  292. package/server/utils/cache.js +125 -125
  293. package/server/utils/migrate.js +81 -81
  294. package/server/utils/safe-fetch.js +228 -228
  295. package/server/utils/secureFields.js +50 -50
  296. package/server/ws.js +161 -161
  297. package/templates/artisan-marketplace.yaml +104 -104
  298. package/templates/book-price-scout.yaml +98 -98
  299. package/templates/electronics-price-tracker.yaml +108 -108
  300. package/templates/flight-deal-hunter.yaml +113 -113
  301. package/templates/freelancer-direct.yaml +116 -116
  302. package/templates/grocery-price-compare.yaml +93 -93
  303. package/templates/hotel-direct-booking.yaml +113 -113
  304. package/templates/local-services.yaml +98 -98
  305. package/templates/olive-oil-tunisia.yaml +88 -88
  306. package/templates/organic-farm-fresh.yaml +101 -101
  307. package/templates/restaurant-direct.yaml +97 -97
  308. package/templates/ring4/banking-sovereign.yaml +55 -0
  309. package/templates/ring4/ecommerce-sovereign.yaml +58 -0
  310. package/templates/ring4/healthcare-sovereign.yaml +60 -0
@@ -1,771 +1,771 @@
1
- 'use strict';
2
-
3
- const crypto = require('crypto');
4
- const { db } = require('../models/db');
5
-
6
- // ─── Schema Creation ──────────────────────────────────────────────────
7
-
8
- db.exec(`
9
- CREATE TABLE IF NOT EXISTS plugin_registry (
10
- id TEXT PRIMARY KEY,
11
- name TEXT UNIQUE NOT NULL,
12
- version TEXT,
13
- author TEXT,
14
- description TEXT,
15
- category TEXT,
16
- entry_point TEXT,
17
- hooks TEXT DEFAULT '[]',
18
- config_schema TEXT DEFAULT '{}',
19
- icon TEXT,
20
- downloads INTEGER DEFAULT 0,
21
- rating REAL DEFAULT 0,
22
- rating_count INTEGER DEFAULT 0,
23
- enabled INTEGER DEFAULT 1,
24
- is_official INTEGER DEFAULT 0,
25
- created_at TEXT DEFAULT (datetime('now')),
26
- updated_at TEXT DEFAULT (datetime('now'))
27
- );
28
-
29
- CREATE TABLE IF NOT EXISTS plugin_installations (
30
- id TEXT PRIMARY KEY,
31
- plugin_id TEXT NOT NULL,
32
- site_id TEXT NOT NULL,
33
- user_id TEXT,
34
- config TEXT DEFAULT '{}',
35
- enabled INTEGER DEFAULT 1,
36
- installed_at TEXT DEFAULT (datetime('now')),
37
- updated_at TEXT DEFAULT (datetime('now')),
38
- UNIQUE(plugin_id, site_id)
39
- );
40
-
41
- CREATE TABLE IF NOT EXISTS plugin_hooks (
42
- id TEXT PRIMARY KEY,
43
- plugin_id TEXT NOT NULL,
44
- hook_name TEXT NOT NULL,
45
- handler TEXT NOT NULL,
46
- priority INTEGER DEFAULT 10,
47
- created_at TEXT DEFAULT (datetime('now'))
48
- );
49
-
50
- CREATE TABLE IF NOT EXISTS hook_executions (
51
- id TEXT PRIMARY KEY,
52
- hook_name TEXT NOT NULL,
53
- plugin_id TEXT,
54
- site_id TEXT,
55
- input TEXT DEFAULT '{}',
56
- output TEXT DEFAULT '{}',
57
- duration_ms INTEGER,
58
- success INTEGER,
59
- error TEXT,
60
- executed_at TEXT DEFAULT (datetime('now'))
61
- );
62
-
63
- CREATE INDEX IF NOT EXISTS idx_plugin_registry_category ON plugin_registry(category);
64
- CREATE INDEX IF NOT EXISTS idx_plugin_registry_name ON plugin_registry(name);
65
- CREATE INDEX IF NOT EXISTS idx_plugin_installations_site ON plugin_installations(site_id);
66
- CREATE INDEX IF NOT EXISTS idx_plugin_installations_plugin ON plugin_installations(plugin_id);
67
- CREATE INDEX IF NOT EXISTS idx_plugin_hooks_plugin ON plugin_hooks(plugin_id);
68
- CREATE INDEX IF NOT EXISTS idx_plugin_hooks_hook_name ON plugin_hooks(hook_name);
69
- CREATE INDEX IF NOT EXISTS idx_hook_executions_site ON hook_executions(site_id);
70
- CREATE INDEX IF NOT EXISTS idx_hook_executions_hook ON hook_executions(hook_name);
71
- CREATE INDEX IF NOT EXISTS idx_hook_executions_executed ON hook_executions(executed_at);
72
- `);
73
-
74
- // ─── Prepared Statements ──────────────────────────────────────────────
75
-
76
- const stmts = {
77
- insertPlugin: db.prepare(`
78
- INSERT INTO plugin_registry (id, name, version, author, description, category, entry_point, hooks, config_schema, icon, is_official, created_at, updated_at)
79
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
80
- `),
81
- getPlugin: db.prepare(`SELECT * FROM plugin_registry WHERE id = ?`),
82
- getPluginByName: db.prepare(`SELECT * FROM plugin_registry WHERE name = ?`),
83
- insertInstallation: db.prepare(`
84
- INSERT INTO plugin_installations (id, plugin_id, site_id, user_id, config, enabled, installed_at, updated_at)
85
- VALUES (?, ?, ?, ?, ?, 1, datetime('now'), datetime('now'))
86
- ON CONFLICT(plugin_id, site_id) DO UPDATE SET
87
- user_id = excluded.user_id,
88
- config = excluded.config,
89
- enabled = 1,
90
- updated_at = datetime('now')
91
- `),
92
- deleteInstallation: db.prepare(`DELETE FROM plugin_installations WHERE plugin_id = ? AND site_id = ?`),
93
- getInstallation: db.prepare(`SELECT * FROM plugin_installations WHERE id = ?`),
94
- updateInstallationConfig: db.prepare(`UPDATE plugin_installations SET config = ?, updated_at = datetime('now') WHERE id = ?`),
95
- getInstalledPlugins: db.prepare(`
96
- SELECT pi.*, pr.name, pr.version, pr.author, pr.description, pr.category, pr.icon, pr.hooks as plugin_hooks, pr.config_schema, pr.rating, pr.rating_count, pr.downloads, pr.is_official
97
- FROM plugin_installations pi
98
- JOIN plugin_registry pr ON pi.plugin_id = pr.id
99
- WHERE pi.site_id = ? AND pi.enabled = 1 AND pr.enabled = 1
100
- ORDER BY pr.name
101
- `),
102
- insertHook: db.prepare(`
103
- INSERT INTO plugin_hooks (id, plugin_id, hook_name, handler, priority, created_at)
104
- VALUES (?, ?, ?, ?, ?, datetime('now'))
105
- `),
106
- getHooksForName: db.prepare(`
107
- SELECT ph.*, pr.name as plugin_name
108
- FROM plugin_hooks ph
109
- JOIN plugin_registry pr ON ph.plugin_id = pr.id
110
- WHERE ph.hook_name = ?
111
- ORDER BY ph.priority ASC
112
- `),
113
- getHooksForPlugin: db.prepare(`SELECT * FROM plugin_hooks WHERE plugin_id = ?`),
114
- deleteHooksForPlugin: db.prepare(`DELETE FROM plugin_hooks WHERE plugin_id = ?`),
115
- insertExecution: db.prepare(`
116
- INSERT INTO hook_executions (id, hook_name, plugin_id, site_id, input, output, duration_ms, success, error, executed_at)
117
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
118
- `),
119
- incrementDownloads: db.prepare(`UPDATE plugin_registry SET downloads = downloads + 1, updated_at = datetime('now') WHERE id = ?`),
120
- updateRating: db.prepare(`UPDATE plugin_registry SET rating = ?, rating_count = rating_count + 1, updated_at = datetime('now') WHERE id = ?`),
121
- installationCount: db.prepare(`SELECT COUNT(*) as count FROM plugin_installations WHERE plugin_id = ?`),
122
- executionStats: db.prepare(`
123
- SELECT COUNT(*) as total,
124
- SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successes
125
- FROM hook_executions WHERE plugin_id = ?
126
- `),
127
- };
128
-
129
- // ─── Helpers ──────────────────────────────────────────────────────────
130
-
131
- function parseJSON(str, fallback) {
132
- if (!str) return fallback;
133
- try { return JSON.parse(str); } catch { return fallback; }
134
- }
135
-
136
- function enrichPlugin(row) {
137
- if (!row) return null;
138
- return {
139
- ...row,
140
- hooks: parseJSON(row.hooks, []),
141
- config_schema: parseJSON(row.config_schema, {}),
142
- enabled: !!row.enabled,
143
- is_official: !!row.is_official,
144
- };
145
- }
146
-
147
- // ─── validateConfig ───────────────────────────────────────────────────
148
-
149
- function validateConfig(config, schema) {
150
- if (!schema || typeof schema !== 'object') return { valid: true, errors: [] };
151
- const errors = [];
152
-
153
- if (schema.required && Array.isArray(schema.required)) {
154
- for (const field of schema.required) {
155
- if (config[field] === undefined || config[field] === null) {
156
- errors.push(`Missing required field: ${field}`);
157
- }
158
- }
159
- }
160
-
161
- if (schema.properties && typeof schema.properties === 'object') {
162
- for (const [key, rule] of Object.entries(schema.properties)) {
163
- const val = config[key];
164
- if (val === undefined || val === null) continue;
165
-
166
- if (rule.type) {
167
- const typeMap = {
168
- string: 'string',
169
- number: 'number',
170
- boolean: 'boolean',
171
- array: 'array',
172
- object: 'object',
173
- };
174
- const expected = typeMap[rule.type];
175
- if (expected) {
176
- const actual = Array.isArray(val) ? 'array' : typeof val;
177
- if (actual !== expected) {
178
- errors.push(`Field "${key}" must be of type ${rule.type}, got ${actual}`);
179
- }
180
- }
181
- }
182
-
183
- if (rule.enum && Array.isArray(rule.enum)) {
184
- if (!rule.enum.includes(val)) {
185
- errors.push(`Field "${key}" must be one of: ${rule.enum.join(', ')}`);
186
- }
187
- }
188
-
189
- if (rule.type === 'number' && typeof val === 'number') {
190
- if (rule.min !== undefined && val < rule.min) {
191
- errors.push(`Field "${key}" must be >= ${rule.min}`);
192
- }
193
- if (rule.max !== undefined && val > rule.max) {
194
- errors.push(`Field "${key}" must be <= ${rule.max}`);
195
- }
196
- }
197
-
198
- if (rule.type === 'string' && typeof val === 'string') {
199
- if (rule.minLength !== undefined && val.length < rule.minLength) {
200
- errors.push(`Field "${key}" must have length >= ${rule.minLength}`);
201
- }
202
- if (rule.maxLength !== undefined && val.length > rule.maxLength) {
203
- errors.push(`Field "${key}" must have length <= ${rule.maxLength}`);
204
- }
205
- }
206
- }
207
- }
208
-
209
- return { valid: errors.length === 0, errors };
210
- }
211
-
212
- // ─── Core Functions ───────────────────────────────────────────────────
213
-
214
- function registerPlugin({ name, version, author, description, category, entryPoint, hooks, configSchema, icon, isOfficial }) {
215
- const id = crypto.randomUUID();
216
- const hooksJSON = JSON.stringify(hooks || []);
217
- const schemaJSON = JSON.stringify(configSchema || {});
218
-
219
- stmts.insertPlugin.run(
220
- id, name, version || '1.0.0', author || 'Unknown', description || '',
221
- category || 'general', entryPoint || '', hooksJSON, schemaJSON,
222
- icon || '', isOfficial ? 1 : 0
223
- );
224
-
225
- if (Array.isArray(hooks)) {
226
- for (const hook of hooks) {
227
- if (hook.name && hook.handler) {
228
- registerHook(id, hook.name, hook.handler, hook.priority || 10);
229
- }
230
- }
231
- }
232
-
233
- return enrichPlugin(stmts.getPlugin.get(id));
234
- }
235
-
236
- function getPlugin(pluginId) {
237
- return enrichPlugin(stmts.getPlugin.get(pluginId));
238
- }
239
-
240
- function getPluginByName(name) {
241
- return enrichPlugin(stmts.getPluginByName.get(name));
242
- }
243
-
244
- function listPlugins({ category, search, sort, limit, offset } = {}) {
245
- let sql = 'SELECT * FROM plugin_registry WHERE enabled = 1';
246
- const params = [];
247
-
248
- if (category) {
249
- sql += ' AND category = ?';
250
- params.push(category);
251
- }
252
-
253
- if (search) {
254
- sql += ' AND (name LIKE ? OR description LIKE ?)';
255
- const term = `%${search}%`;
256
- params.push(term, term);
257
- }
258
-
259
- const sortMap = {
260
- downloads: 'downloads DESC',
261
- rating: 'rating DESC',
262
- created_at: 'created_at DESC',
263
- name: 'name ASC',
264
- };
265
- sql += ` ORDER BY ${sortMap[sort] || 'created_at DESC'}`;
266
-
267
- sql += ' LIMIT ? OFFSET ?';
268
- params.push(limit || 50, offset || 0);
269
-
270
- const rows = db.prepare(sql).all(...params);
271
- return rows.map(enrichPlugin);
272
- }
273
-
274
- function installPlugin(pluginId, siteId, userId, config) {
275
- const plugin = stmts.getPlugin.get(pluginId);
276
- if (!plugin) throw new Error(`Plugin not found: ${pluginId}`);
277
-
278
- const schema = parseJSON(plugin.config_schema, {});
279
- const finalConfig = config || {};
280
-
281
- if (schema && schema.properties) {
282
- const validation = validateConfig(finalConfig, schema);
283
- if (!validation.valid) {
284
- throw new Error(`Invalid config: ${validation.errors.join('; ')}`);
285
- }
286
- }
287
-
288
- const id = crypto.randomUUID();
289
- stmts.insertInstallation.run(id, pluginId, siteId, userId || null, JSON.stringify(finalConfig));
290
- stmts.incrementDownloads.run(pluginId);
291
-
292
- return {
293
- id,
294
- plugin_id: pluginId,
295
- site_id: siteId,
296
- user_id: userId,
297
- config: finalConfig,
298
- enabled: true,
299
- };
300
- }
301
-
302
- function uninstallPlugin(pluginId, siteId) {
303
- const changes = stmts.deleteInstallation.run(pluginId, siteId).changes;
304
- return changes > 0;
305
- }
306
-
307
- function configurePlugin(installationId, config) {
308
- const installation = stmts.getInstallation.get(installationId);
309
- if (!installation) throw new Error(`Installation not found: ${installationId}`);
310
-
311
- const plugin = stmts.getPlugin.get(installation.plugin_id);
312
- if (!plugin) throw new Error(`Plugin not found: ${installation.plugin_id}`);
313
-
314
- const schema = parseJSON(plugin.config_schema, {});
315
- if (schema && schema.properties) {
316
- const validation = validateConfig(config, schema);
317
- if (!validation.valid) {
318
- throw new Error(`Invalid config: ${validation.errors.join('; ')}`);
319
- }
320
- }
321
-
322
- stmts.updateInstallationConfig.run(JSON.stringify(config), installationId);
323
- return { id: installationId, config };
324
- }
325
-
326
- function getInstalledPlugins(siteId) {
327
- const rows = stmts.getInstalledPlugins.all(siteId);
328
- return rows.map(row => ({
329
- ...row,
330
- config: parseJSON(row.config, {}),
331
- plugin_hooks: parseJSON(row.plugin_hooks, []),
332
- config_schema: parseJSON(row.config_schema, {}),
333
- enabled: !!row.enabled,
334
- is_official: !!row.is_official,
335
- }));
336
- }
337
-
338
- // ─── Hook Management ──────────────────────────────────────────────────
339
-
340
- function registerHook(pluginId, hookName, handlerCode, priority) {
341
- const id = crypto.randomUUID();
342
- stmts.insertHook.run(id, pluginId, hookName, handlerCode, priority || 10);
343
- return { id, plugin_id: pluginId, hook_name: hookName, priority: priority || 10 };
344
- }
345
-
346
- function executeHook(hookName, siteId, input) {
347
- const installed = stmts.getInstalledPlugins.all(siteId);
348
- const installedPluginIds = new Set(installed.map(i => i.plugin_id));
349
-
350
- const allHooks = stmts.getHooksForName.all(hookName);
351
- const relevantHooks = allHooks.filter(h => installedPluginIds.has(h.plugin_id));
352
-
353
- const results = [];
354
-
355
- for (const hook of relevantHooks) {
356
- const execId = crypto.randomUUID();
357
- const start = Date.now();
358
- let output = null;
359
- let success = true;
360
- let error = null;
361
-
362
- try {
363
- const vm = require('vm');
364
- const sandbox = {
365
- input: JSON.parse(JSON.stringify(input || {})),
366
- config: {},
367
- result: null,
368
- JSON,
369
- Math,
370
- Date,
371
- Array,
372
- Object,
373
- String,
374
- Number,
375
- Boolean,
376
- parseInt,
377
- parseFloat,
378
- isNaN,
379
- isFinite,
380
- encodeURIComponent,
381
- decodeURIComponent,
382
- };
383
- const inst = installed.find(i => i.plugin_id === hook.plugin_id);
384
- sandbox.config = inst ? JSON.parse(JSON.stringify(parseJSON(inst.config, {}))) : {};
385
-
386
- const wrappedCode = `'use strict'; result = (function(input, config) { ${hook.handler} })(input, config);`;
387
- const script = new vm.Script(wrappedCode, { timeout: 1000, filename: `plugin-${hook.plugin_id}.vm` });
388
- const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
389
- script.runInContext(context, { timeout: 1000 });
390
- output = sandbox.result;
391
- } catch (err) {
392
- success = false;
393
- error = err.message || String(err);
394
- }
395
-
396
- const duration = Date.now() - start;
397
-
398
- stmts.insertExecution.run(
399
- execId, hookName, hook.plugin_id, siteId,
400
- JSON.stringify(input || {}), JSON.stringify(output || {}),
401
- duration, success ? 1 : 0, error
402
- );
403
-
404
- results.push({
405
- plugin_id: hook.plugin_id,
406
- plugin_name: hook.plugin_name,
407
- hook_name: hookName,
408
- output,
409
- success,
410
- error,
411
- duration_ms: duration,
412
- });
413
- }
414
-
415
- return results;
416
- }
417
-
418
- function getAvailableHooks() {
419
- return [
420
- { name: 'before_action', description: 'Triggered before any agent action is executed' },
421
- { name: 'after_action', description: 'Triggered after an agent action completes' },
422
- { name: 'on_discover', description: 'Triggered when agent discovers new page elements' },
423
- { name: 'on_authenticate', description: 'Triggered during authentication flow' },
424
- { name: 'on_error', description: 'Triggered when an error occurs during agent execution' },
425
- { name: 'on_memory_store', description: 'Triggered when data is stored in agent memory' },
426
- { name: 'on_memory_recall', description: 'Triggered when data is recalled from agent memory' },
427
- { name: 'on_heal_selector', description: 'Triggered when a CSS selector self-heals' },
428
- { name: 'on_vision_analyze', description: 'Triggered when vision analysis is performed on a page' },
429
- { name: 'on_swarm_start', description: 'Triggered when a swarm task begins' },
430
- { name: 'on_swarm_complete', description: 'Triggered when a swarm task completes' },
431
- { name: 'on_fairness_search', description: 'Triggered during fairness-aware search ranking' },
432
- { name: 'on_page_load', description: 'Triggered when a monitored page is loaded' },
433
- { name: 'on_agent_connect', description: 'Triggered when an agent connects to a site' },
434
- { name: 'on_agent_disconnect', description: 'Triggered when an agent disconnects from a site' },
435
- { name: 'custom', description: 'Generic hook for user-defined plugin events' },
436
- ];
437
- }
438
-
439
- // ─── Stats & Rating ───────────────────────────────────────────────────
440
-
441
- function getPluginStats(pluginId) {
442
- const plugin = stmts.getPlugin.get(pluginId);
443
- if (!plugin) return null;
444
-
445
- const instCount = stmts.installationCount.get(pluginId).count;
446
- const execStats = stmts.executionStats.get(pluginId);
447
- const total = execStats.total || 0;
448
- const successes = execStats.successes || 0;
449
-
450
- return {
451
- plugin_id: pluginId,
452
- name: plugin.name,
453
- installations: instCount,
454
- downloads: plugin.downloads,
455
- avg_rating: plugin.rating,
456
- rating_count: plugin.rating_count,
457
- total_executions: total,
458
- successful_executions: successes,
459
- success_rate: total > 0 ? Math.round((successes / total) * 10000) / 100 : 0,
460
- };
461
- }
462
-
463
- function ratePlugin(pluginId, userId, rating) {
464
- if (rating < 1 || rating > 5) throw new Error('Rating must be between 1 and 5');
465
-
466
- const plugin = stmts.getPlugin.get(pluginId);
467
- if (!plugin) throw new Error(`Plugin not found: ${pluginId}`);
468
-
469
- const oldAvg = plugin.rating || 0;
470
- const oldCount = plugin.rating_count || 0;
471
- const newAvg = ((oldAvg * oldCount) + rating) / (oldCount + 1);
472
- const rounded = Math.round(newAvg * 100) / 100;
473
-
474
- stmts.updateRating.run(rounded, pluginId);
475
-
476
- return { plugin_id: pluginId, new_rating: rounded, rating_count: oldCount + 1 };
477
- }
478
-
479
- // ─── Execution Log ────────────────────────────────────────────────────
480
-
481
- function getHookExecutionLog(siteId, { hookName, pluginId, limit } = {}) {
482
- let sql = 'SELECT he.*, pr.name as plugin_name FROM hook_executions he LEFT JOIN plugin_registry pr ON he.plugin_id = pr.id WHERE he.site_id = ?';
483
- const params = [siteId];
484
-
485
- if (hookName) {
486
- sql += ' AND he.hook_name = ?';
487
- params.push(hookName);
488
- }
489
- if (pluginId) {
490
- sql += ' AND he.plugin_id = ?';
491
- params.push(pluginId);
492
- }
493
-
494
- sql += ' ORDER BY he.executed_at DESC LIMIT ?';
495
- params.push(limit || 100);
496
-
497
- const rows = db.prepare(sql).all(...params);
498
- return rows.map(row => ({
499
- ...row,
500
- input: parseJSON(row.input, {}),
501
- output: parseJSON(row.output, {}),
502
- success: !!row.success,
503
- }));
504
- }
505
-
506
- // ─── Seed Official Plugins ────────────────────────────────────────────
507
-
508
- function seedOfficialPlugins() {
509
- const existing = stmts.getPluginByName.get('fairness-boost');
510
- if (existing) return;
511
-
512
- const plugins = [
513
- {
514
- name: 'fairness-boost',
515
- version: '1.0.0',
516
- author: 'WAB Team',
517
- description: 'Boosts indie and small-business sites in search results by 15% to promote a fairer web ecosystem.',
518
- category: 'fairness',
519
- entryPoint: 'fairness-boost/index.js',
520
- icon: '⚖️',
521
- isOfficial: true,
522
- configSchema: {
523
- properties: {
524
- boost_percentage: { type: 'number', min: 1, max: 50 },
525
- target_categories: { type: 'array' },
526
- },
527
- required: [],
528
- },
529
- hooks: [
530
- {
531
- name: 'on_fairness_search',
532
- priority: 5,
533
- handler: [
534
- 'var results = input.results || [];',
535
- 'var boost = (config && config.boost_percentage) || 15;',
536
- 'var boosted = results.map(function(r) {',
537
- ' if (r.is_indie || r.is_small_business) {',
538
- ' return Object.assign({}, r, { score: (r.score || 0) * (1 + boost / 100), boosted: true });',
539
- ' }',
540
- ' return r;',
541
- '});',
542
- 'return { results: boosted, boost_applied: boost };',
543
- ].join('\n'),
544
- },
545
- ],
546
- },
547
- {
548
- name: 'security-monitor',
549
- version: '1.0.0',
550
- author: 'WAB Team',
551
- description: 'Monitors agent actions for suspicious patterns like credential harvesting, XSS payloads, and unauthorized data access.',
552
- category: 'security',
553
- entryPoint: 'security-monitor/index.js',
554
- icon: '🛡️',
555
- isOfficial: true,
556
- configSchema: {
557
- properties: {
558
- alert_threshold: { type: 'number', min: 1, max: 10 },
559
- blocked_patterns: { type: 'array' },
560
- },
561
- required: [],
562
- },
563
- hooks: [
564
- {
565
- name: 'after_action',
566
- priority: 1,
567
- handler: [
568
- 'var action = input.action || "";',
569
- 'var data = input.data || "";',
570
- 'var dataStr = typeof data === "string" ? data : JSON.stringify(data);',
571
- 'var suspicious = [];',
572
- 'var patterns = [',
573
- ' { re: /password|passwd|secret|token/i, label: "credential_access" },',
574
- ' { re: /<script|javascript:|on\\w+\\s*=/i, label: "xss_attempt" },',
575
- ' { re: /eval\\(|Function\\(|setTimeout\\(.*,/i, label: "code_injection" },',
576
- ' { re: /\\.env|credentials|private_key/i, label: "sensitive_file_access" }',
577
- '];',
578
- 'for (var i = 0; i < patterns.length; i++) {',
579
- ' if (patterns[i].re.test(action) || patterns[i].re.test(dataStr)) {',
580
- ' suspicious.push(patterns[i].label);',
581
- ' }',
582
- '}',
583
- 'return { flagged: suspicious.length > 0, threats: suspicious, action: action, timestamp: new Date().toISOString() };',
584
- ].join('\n'),
585
- },
586
- ],
587
- },
588
- {
589
- name: 'analytics-enhanced',
590
- version: '1.0.0',
591
- author: 'WAB Team',
592
- description: 'Provides detailed page-load analytics including timing metrics, resource counts, and performance scoring.',
593
- category: 'analytics',
594
- entryPoint: 'analytics-enhanced/index.js',
595
- icon: '📊',
596
- isOfficial: true,
597
- configSchema: {
598
- properties: {
599
- track_resources: { type: 'boolean' },
600
- track_timing: { type: 'boolean' },
601
- sampling_rate: { type: 'number', min: 0, max: 100 },
602
- },
603
- required: [],
604
- },
605
- hooks: [
606
- {
607
- name: 'on_page_load',
608
- priority: 10,
609
- handler: [
610
- 'var url = input.url || "unknown";',
611
- 'var timing = input.timing || {};',
612
- 'var loadTime = timing.loadComplete || 0;',
613
- 'var domReady = timing.domReady || 0;',
614
- 'var resources = input.resources || [];',
615
- 'var scripts = resources.filter(function(r) { return r.type === "script"; }).length;',
616
- 'var styles = resources.filter(function(r) { return r.type === "stylesheet"; }).length;',
617
- 'var images = resources.filter(function(r) { return r.type === "image"; }).length;',
618
- 'var perfScore = 100;',
619
- 'if (loadTime > 3000) perfScore -= 20;',
620
- 'if (loadTime > 5000) perfScore -= 20;',
621
- 'if (scripts > 20) perfScore -= 15;',
622
- 'if (images > 50) perfScore -= 10;',
623
- 'if (perfScore < 0) perfScore = 0;',
624
- 'return {',
625
- ' url: url,',
626
- ' load_time_ms: loadTime,',
627
- ' dom_ready_ms: domReady,',
628
- ' resource_counts: { scripts: scripts, styles: styles, images: images, total: resources.length },',
629
- ' performance_score: perfScore,',
630
- ' tracked_at: new Date().toISOString()',
631
- '};',
632
- ].join('\n'),
633
- },
634
- ],
635
- },
636
- {
637
- name: 'auto-healer',
638
- version: '1.0.0',
639
- author: 'WAB Team',
640
- description: 'Automatically logs errors and suggests self-healing strategies such as selector updates, retry logic, and fallback actions.',
641
- category: 'reliability',
642
- entryPoint: 'auto-healer/index.js',
643
- icon: '🩹',
644
- isOfficial: true,
645
- configSchema: {
646
- properties: {
647
- max_retries: { type: 'number', min: 0, max: 10 },
648
- auto_retry: { type: 'boolean' },
649
- },
650
- required: [],
651
- },
652
- hooks: [
653
- {
654
- name: 'on_error',
655
- priority: 3,
656
- handler: [
657
- 'var errorMsg = input.error || input.message || "Unknown error";',
658
- 'var selector = input.selector || null;',
659
- 'var action = input.action || "unknown";',
660
- 'var strategies = [];',
661
- 'if (selector) {',
662
- ' strategies.push({ type: "selector_update", suggestion: "Try broader selector or data-testid attribute" });',
663
- ' strategies.push({ type: "wait_and_retry", suggestion: "Element may not be loaded yet, add wait before action" });',
664
- '}',
665
- 'if (/timeout|ETIMEDOUT/i.test(errorMsg)) {',
666
- ' strategies.push({ type: "increase_timeout", suggestion: "Network may be slow, increase timeout threshold" });',
667
- ' strategies.push({ type: "retry", suggestion: "Transient failure, retry with exponential backoff" });',
668
- '}',
669
- 'if (/not found|404/i.test(errorMsg)) {',
670
- ' strategies.push({ type: "fallback_url", suggestion: "Page may have moved, check for redirects" });',
671
- '}',
672
- 'if (/permission|forbidden|403/i.test(errorMsg)) {',
673
- ' strategies.push({ type: "re_authenticate", suggestion: "Session may have expired, re-authenticate" });',
674
- '}',
675
- 'if (strategies.length === 0) {',
676
- ' strategies.push({ type: "log_and_skip", suggestion: "Unknown error pattern, log and continue" });',
677
- '}',
678
- 'return { error: errorMsg, action: action, selector: selector, strategies: strategies, analyzed_at: new Date().toISOString() };',
679
- ].join('\n'),
680
- },
681
- ],
682
- },
683
- {
684
- name: 'memory-optimizer',
685
- version: '1.0.0',
686
- author: 'WAB Team',
687
- description: 'Checks for duplicate entries before storing new data in agent memory, reducing storage waste and improving recall accuracy.',
688
- category: 'performance',
689
- entryPoint: 'memory-optimizer/index.js',
690
- icon: '🧠',
691
- isOfficial: true,
692
- configSchema: {
693
- properties: {
694
- similarity_threshold: { type: 'number', min: 0, max: 1 },
695
- max_memory_entries: { type: 'number', min: 10, max: 100000 },
696
- },
697
- required: [],
698
- },
699
- hooks: [
700
- {
701
- name: 'on_memory_store',
702
- priority: 5,
703
- handler: [
704
- 'var key = input.key || "";',
705
- 'var value = input.value || "";',
706
- 'var existingKeys = input.existing_keys || [];',
707
- 'var valueStr = typeof value === "string" ? value : JSON.stringify(value);',
708
- 'var dominated = false;',
709
- 'var duplicateOf = null;',
710
- 'for (var i = 0; i < existingKeys.length; i++) {',
711
- ' if (existingKeys[i] === key) {',
712
- ' dominated = true;',
713
- ' duplicateOf = key;',
714
- ' break;',
715
- ' }',
716
- ' var normalizedExisting = existingKeys[i].toLowerCase().replace(/[^a-z0-9]/g, "");',
717
- ' var normalizedNew = key.toLowerCase().replace(/[^a-z0-9]/g, "");',
718
- ' if (normalizedExisting === normalizedNew) {',
719
- ' dominated = true;',
720
- ' duplicateOf = existingKeys[i];',
721
- ' break;',
722
- ' }',
723
- '}',
724
- 'return {',
725
- ' allow_store: !dominated,',
726
- ' is_duplicate: dominated,',
727
- ' duplicate_of: duplicateOf,',
728
- ' key: key,',
729
- ' value_length: valueStr.length,',
730
- ' checked_at: new Date().toISOString()',
731
- '};',
732
- ].join('\n'),
733
- },
734
- ],
735
- },
736
- ];
737
-
738
- const doSeed = db.transaction(() => {
739
- for (const p of plugins) {
740
- try {
741
- registerPlugin(p);
742
- } catch (_) {
743
- // already exists
744
- }
745
- }
746
- });
747
- doSeed();
748
- }
749
-
750
- seedOfficialPlugins();
751
-
752
- // ─── Exports ──────────────────────────────────────────────────────────
753
-
754
- module.exports = {
755
- registerPlugin,
756
- getPlugin,
757
- getPluginByName,
758
- listPlugins,
759
- installPlugin,
760
- uninstallPlugin,
761
- configurePlugin,
762
- getInstalledPlugins,
763
- registerHook,
764
- executeHook,
765
- getAvailableHooks,
766
- validateConfig,
767
- getPluginStats,
768
- ratePlugin,
769
- getHookExecutionLog,
770
- seedOfficialPlugins,
771
- };
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { db } = require('../models/db');
5
+
6
+ // ─── Schema Creation ──────────────────────────────────────────────────
7
+
8
+ db.exec(`
9
+ CREATE TABLE IF NOT EXISTS plugin_registry (
10
+ id TEXT PRIMARY KEY,
11
+ name TEXT UNIQUE NOT NULL,
12
+ version TEXT,
13
+ author TEXT,
14
+ description TEXT,
15
+ category TEXT,
16
+ entry_point TEXT,
17
+ hooks TEXT DEFAULT '[]',
18
+ config_schema TEXT DEFAULT '{}',
19
+ icon TEXT,
20
+ downloads INTEGER DEFAULT 0,
21
+ rating REAL DEFAULT 0,
22
+ rating_count INTEGER DEFAULT 0,
23
+ enabled INTEGER DEFAULT 1,
24
+ is_official INTEGER DEFAULT 0,
25
+ created_at TEXT DEFAULT (datetime('now')),
26
+ updated_at TEXT DEFAULT (datetime('now'))
27
+ );
28
+
29
+ CREATE TABLE IF NOT EXISTS plugin_installations (
30
+ id TEXT PRIMARY KEY,
31
+ plugin_id TEXT NOT NULL,
32
+ site_id TEXT NOT NULL,
33
+ user_id TEXT,
34
+ config TEXT DEFAULT '{}',
35
+ enabled INTEGER DEFAULT 1,
36
+ installed_at TEXT DEFAULT (datetime('now')),
37
+ updated_at TEXT DEFAULT (datetime('now')),
38
+ UNIQUE(plugin_id, site_id)
39
+ );
40
+
41
+ CREATE TABLE IF NOT EXISTS plugin_hooks (
42
+ id TEXT PRIMARY KEY,
43
+ plugin_id TEXT NOT NULL,
44
+ hook_name TEXT NOT NULL,
45
+ handler TEXT NOT NULL,
46
+ priority INTEGER DEFAULT 10,
47
+ created_at TEXT DEFAULT (datetime('now'))
48
+ );
49
+
50
+ CREATE TABLE IF NOT EXISTS hook_executions (
51
+ id TEXT PRIMARY KEY,
52
+ hook_name TEXT NOT NULL,
53
+ plugin_id TEXT,
54
+ site_id TEXT,
55
+ input TEXT DEFAULT '{}',
56
+ output TEXT DEFAULT '{}',
57
+ duration_ms INTEGER,
58
+ success INTEGER,
59
+ error TEXT,
60
+ executed_at TEXT DEFAULT (datetime('now'))
61
+ );
62
+
63
+ CREATE INDEX IF NOT EXISTS idx_plugin_registry_category ON plugin_registry(category);
64
+ CREATE INDEX IF NOT EXISTS idx_plugin_registry_name ON plugin_registry(name);
65
+ CREATE INDEX IF NOT EXISTS idx_plugin_installations_site ON plugin_installations(site_id);
66
+ CREATE INDEX IF NOT EXISTS idx_plugin_installations_plugin ON plugin_installations(plugin_id);
67
+ CREATE INDEX IF NOT EXISTS idx_plugin_hooks_plugin ON plugin_hooks(plugin_id);
68
+ CREATE INDEX IF NOT EXISTS idx_plugin_hooks_hook_name ON plugin_hooks(hook_name);
69
+ CREATE INDEX IF NOT EXISTS idx_hook_executions_site ON hook_executions(site_id);
70
+ CREATE INDEX IF NOT EXISTS idx_hook_executions_hook ON hook_executions(hook_name);
71
+ CREATE INDEX IF NOT EXISTS idx_hook_executions_executed ON hook_executions(executed_at);
72
+ `);
73
+
74
+ // ─── Prepared Statements ──────────────────────────────────────────────
75
+
76
+ const stmts = {
77
+ insertPlugin: db.prepare(`
78
+ INSERT INTO plugin_registry (id, name, version, author, description, category, entry_point, hooks, config_schema, icon, is_official, created_at, updated_at)
79
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
80
+ `),
81
+ getPlugin: db.prepare(`SELECT * FROM plugin_registry WHERE id = ?`),
82
+ getPluginByName: db.prepare(`SELECT * FROM plugin_registry WHERE name = ?`),
83
+ insertInstallation: db.prepare(`
84
+ INSERT INTO plugin_installations (id, plugin_id, site_id, user_id, config, enabled, installed_at, updated_at)
85
+ VALUES (?, ?, ?, ?, ?, 1, datetime('now'), datetime('now'))
86
+ ON CONFLICT(plugin_id, site_id) DO UPDATE SET
87
+ user_id = excluded.user_id,
88
+ config = excluded.config,
89
+ enabled = 1,
90
+ updated_at = datetime('now')
91
+ `),
92
+ deleteInstallation: db.prepare(`DELETE FROM plugin_installations WHERE plugin_id = ? AND site_id = ?`),
93
+ getInstallation: db.prepare(`SELECT * FROM plugin_installations WHERE id = ?`),
94
+ updateInstallationConfig: db.prepare(`UPDATE plugin_installations SET config = ?, updated_at = datetime('now') WHERE id = ?`),
95
+ getInstalledPlugins: db.prepare(`
96
+ SELECT pi.*, pr.name, pr.version, pr.author, pr.description, pr.category, pr.icon, pr.hooks as plugin_hooks, pr.config_schema, pr.rating, pr.rating_count, pr.downloads, pr.is_official
97
+ FROM plugin_installations pi
98
+ JOIN plugin_registry pr ON pi.plugin_id = pr.id
99
+ WHERE pi.site_id = ? AND pi.enabled = 1 AND pr.enabled = 1
100
+ ORDER BY pr.name
101
+ `),
102
+ insertHook: db.prepare(`
103
+ INSERT INTO plugin_hooks (id, plugin_id, hook_name, handler, priority, created_at)
104
+ VALUES (?, ?, ?, ?, ?, datetime('now'))
105
+ `),
106
+ getHooksForName: db.prepare(`
107
+ SELECT ph.*, pr.name as plugin_name
108
+ FROM plugin_hooks ph
109
+ JOIN plugin_registry pr ON ph.plugin_id = pr.id
110
+ WHERE ph.hook_name = ?
111
+ ORDER BY ph.priority ASC
112
+ `),
113
+ getHooksForPlugin: db.prepare(`SELECT * FROM plugin_hooks WHERE plugin_id = ?`),
114
+ deleteHooksForPlugin: db.prepare(`DELETE FROM plugin_hooks WHERE plugin_id = ?`),
115
+ insertExecution: db.prepare(`
116
+ INSERT INTO hook_executions (id, hook_name, plugin_id, site_id, input, output, duration_ms, success, error, executed_at)
117
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
118
+ `),
119
+ incrementDownloads: db.prepare(`UPDATE plugin_registry SET downloads = downloads + 1, updated_at = datetime('now') WHERE id = ?`),
120
+ updateRating: db.prepare(`UPDATE plugin_registry SET rating = ?, rating_count = rating_count + 1, updated_at = datetime('now') WHERE id = ?`),
121
+ installationCount: db.prepare(`SELECT COUNT(*) as count FROM plugin_installations WHERE plugin_id = ?`),
122
+ executionStats: db.prepare(`
123
+ SELECT COUNT(*) as total,
124
+ SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successes
125
+ FROM hook_executions WHERE plugin_id = ?
126
+ `),
127
+ };
128
+
129
+ // ─── Helpers ──────────────────────────────────────────────────────────
130
+
131
+ function parseJSON(str, fallback) {
132
+ if (!str) return fallback;
133
+ try { return JSON.parse(str); } catch { return fallback; }
134
+ }
135
+
136
+ function enrichPlugin(row) {
137
+ if (!row) return null;
138
+ return {
139
+ ...row,
140
+ hooks: parseJSON(row.hooks, []),
141
+ config_schema: parseJSON(row.config_schema, {}),
142
+ enabled: !!row.enabled,
143
+ is_official: !!row.is_official,
144
+ };
145
+ }
146
+
147
+ // ─── validateConfig ───────────────────────────────────────────────────
148
+
149
+ function validateConfig(config, schema) {
150
+ if (!schema || typeof schema !== 'object') return { valid: true, errors: [] };
151
+ const errors = [];
152
+
153
+ if (schema.required && Array.isArray(schema.required)) {
154
+ for (const field of schema.required) {
155
+ if (config[field] === undefined || config[field] === null) {
156
+ errors.push(`Missing required field: ${field}`);
157
+ }
158
+ }
159
+ }
160
+
161
+ if (schema.properties && typeof schema.properties === 'object') {
162
+ for (const [key, rule] of Object.entries(schema.properties)) {
163
+ const val = config[key];
164
+ if (val === undefined || val === null) continue;
165
+
166
+ if (rule.type) {
167
+ const typeMap = {
168
+ string: 'string',
169
+ number: 'number',
170
+ boolean: 'boolean',
171
+ array: 'array',
172
+ object: 'object',
173
+ };
174
+ const expected = typeMap[rule.type];
175
+ if (expected) {
176
+ const actual = Array.isArray(val) ? 'array' : typeof val;
177
+ if (actual !== expected) {
178
+ errors.push(`Field "${key}" must be of type ${rule.type}, got ${actual}`);
179
+ }
180
+ }
181
+ }
182
+
183
+ if (rule.enum && Array.isArray(rule.enum)) {
184
+ if (!rule.enum.includes(val)) {
185
+ errors.push(`Field "${key}" must be one of: ${rule.enum.join(', ')}`);
186
+ }
187
+ }
188
+
189
+ if (rule.type === 'number' && typeof val === 'number') {
190
+ if (rule.min !== undefined && val < rule.min) {
191
+ errors.push(`Field "${key}" must be >= ${rule.min}`);
192
+ }
193
+ if (rule.max !== undefined && val > rule.max) {
194
+ errors.push(`Field "${key}" must be <= ${rule.max}`);
195
+ }
196
+ }
197
+
198
+ if (rule.type === 'string' && typeof val === 'string') {
199
+ if (rule.minLength !== undefined && val.length < rule.minLength) {
200
+ errors.push(`Field "${key}" must have length >= ${rule.minLength}`);
201
+ }
202
+ if (rule.maxLength !== undefined && val.length > rule.maxLength) {
203
+ errors.push(`Field "${key}" must have length <= ${rule.maxLength}`);
204
+ }
205
+ }
206
+ }
207
+ }
208
+
209
+ return { valid: errors.length === 0, errors };
210
+ }
211
+
212
+ // ─── Core Functions ───────────────────────────────────────────────────
213
+
214
+ function registerPlugin({ name, version, author, description, category, entryPoint, hooks, configSchema, icon, isOfficial }) {
215
+ const id = crypto.randomUUID();
216
+ const hooksJSON = JSON.stringify(hooks || []);
217
+ const schemaJSON = JSON.stringify(configSchema || {});
218
+
219
+ stmts.insertPlugin.run(
220
+ id, name, version || '1.0.0', author || 'Unknown', description || '',
221
+ category || 'general', entryPoint || '', hooksJSON, schemaJSON,
222
+ icon || '', isOfficial ? 1 : 0
223
+ );
224
+
225
+ if (Array.isArray(hooks)) {
226
+ for (const hook of hooks) {
227
+ if (hook.name && hook.handler) {
228
+ registerHook(id, hook.name, hook.handler, hook.priority || 10);
229
+ }
230
+ }
231
+ }
232
+
233
+ return enrichPlugin(stmts.getPlugin.get(id));
234
+ }
235
+
236
+ function getPlugin(pluginId) {
237
+ return enrichPlugin(stmts.getPlugin.get(pluginId));
238
+ }
239
+
240
+ function getPluginByName(name) {
241
+ return enrichPlugin(stmts.getPluginByName.get(name));
242
+ }
243
+
244
+ function listPlugins({ category, search, sort, limit, offset } = {}) {
245
+ let sql = 'SELECT * FROM plugin_registry WHERE enabled = 1';
246
+ const params = [];
247
+
248
+ if (category) {
249
+ sql += ' AND category = ?';
250
+ params.push(category);
251
+ }
252
+
253
+ if (search) {
254
+ sql += ' AND (name LIKE ? OR description LIKE ?)';
255
+ const term = `%${search}%`;
256
+ params.push(term, term);
257
+ }
258
+
259
+ const sortMap = {
260
+ downloads: 'downloads DESC',
261
+ rating: 'rating DESC',
262
+ created_at: 'created_at DESC',
263
+ name: 'name ASC',
264
+ };
265
+ sql += ` ORDER BY ${sortMap[sort] || 'created_at DESC'}`;
266
+
267
+ sql += ' LIMIT ? OFFSET ?';
268
+ params.push(limit || 50, offset || 0);
269
+
270
+ const rows = db.prepare(sql).all(...params);
271
+ return rows.map(enrichPlugin);
272
+ }
273
+
274
+ function installPlugin(pluginId, siteId, userId, config) {
275
+ const plugin = stmts.getPlugin.get(pluginId);
276
+ if (!plugin) throw new Error(`Plugin not found: ${pluginId}`);
277
+
278
+ const schema = parseJSON(plugin.config_schema, {});
279
+ const finalConfig = config || {};
280
+
281
+ if (schema && schema.properties) {
282
+ const validation = validateConfig(finalConfig, schema);
283
+ if (!validation.valid) {
284
+ throw new Error(`Invalid config: ${validation.errors.join('; ')}`);
285
+ }
286
+ }
287
+
288
+ const id = crypto.randomUUID();
289
+ stmts.insertInstallation.run(id, pluginId, siteId, userId || null, JSON.stringify(finalConfig));
290
+ stmts.incrementDownloads.run(pluginId);
291
+
292
+ return {
293
+ id,
294
+ plugin_id: pluginId,
295
+ site_id: siteId,
296
+ user_id: userId,
297
+ config: finalConfig,
298
+ enabled: true,
299
+ };
300
+ }
301
+
302
+ function uninstallPlugin(pluginId, siteId) {
303
+ const changes = stmts.deleteInstallation.run(pluginId, siteId).changes;
304
+ return changes > 0;
305
+ }
306
+
307
+ function configurePlugin(installationId, config) {
308
+ const installation = stmts.getInstallation.get(installationId);
309
+ if (!installation) throw new Error(`Installation not found: ${installationId}`);
310
+
311
+ const plugin = stmts.getPlugin.get(installation.plugin_id);
312
+ if (!plugin) throw new Error(`Plugin not found: ${installation.plugin_id}`);
313
+
314
+ const schema = parseJSON(plugin.config_schema, {});
315
+ if (schema && schema.properties) {
316
+ const validation = validateConfig(config, schema);
317
+ if (!validation.valid) {
318
+ throw new Error(`Invalid config: ${validation.errors.join('; ')}`);
319
+ }
320
+ }
321
+
322
+ stmts.updateInstallationConfig.run(JSON.stringify(config), installationId);
323
+ return { id: installationId, config };
324
+ }
325
+
326
+ function getInstalledPlugins(siteId) {
327
+ const rows = stmts.getInstalledPlugins.all(siteId);
328
+ return rows.map(row => ({
329
+ ...row,
330
+ config: parseJSON(row.config, {}),
331
+ plugin_hooks: parseJSON(row.plugin_hooks, []),
332
+ config_schema: parseJSON(row.config_schema, {}),
333
+ enabled: !!row.enabled,
334
+ is_official: !!row.is_official,
335
+ }));
336
+ }
337
+
338
+ // ─── Hook Management ──────────────────────────────────────────────────
339
+
340
+ function registerHook(pluginId, hookName, handlerCode, priority) {
341
+ const id = crypto.randomUUID();
342
+ stmts.insertHook.run(id, pluginId, hookName, handlerCode, priority || 10);
343
+ return { id, plugin_id: pluginId, hook_name: hookName, priority: priority || 10 };
344
+ }
345
+
346
+ function executeHook(hookName, siteId, input) {
347
+ const installed = stmts.getInstalledPlugins.all(siteId);
348
+ const installedPluginIds = new Set(installed.map(i => i.plugin_id));
349
+
350
+ const allHooks = stmts.getHooksForName.all(hookName);
351
+ const relevantHooks = allHooks.filter(h => installedPluginIds.has(h.plugin_id));
352
+
353
+ const results = [];
354
+
355
+ for (const hook of relevantHooks) {
356
+ const execId = crypto.randomUUID();
357
+ const start = Date.now();
358
+ let output = null;
359
+ let success = true;
360
+ let error = null;
361
+
362
+ try {
363
+ const vm = require('vm');
364
+ const sandbox = {
365
+ input: JSON.parse(JSON.stringify(input || {})),
366
+ config: {},
367
+ result: null,
368
+ JSON,
369
+ Math,
370
+ Date,
371
+ Array,
372
+ Object,
373
+ String,
374
+ Number,
375
+ Boolean,
376
+ parseInt,
377
+ parseFloat,
378
+ isNaN,
379
+ isFinite,
380
+ encodeURIComponent,
381
+ decodeURIComponent,
382
+ };
383
+ const inst = installed.find(i => i.plugin_id === hook.plugin_id);
384
+ sandbox.config = inst ? JSON.parse(JSON.stringify(parseJSON(inst.config, {}))) : {};
385
+
386
+ const wrappedCode = `'use strict'; result = (function(input, config) { ${hook.handler} })(input, config);`;
387
+ const script = new vm.Script(wrappedCode, { timeout: 1000, filename: `plugin-${hook.plugin_id}.vm` });
388
+ const context = vm.createContext(sandbox, { codeGeneration: { strings: false, wasm: false } });
389
+ script.runInContext(context, { timeout: 1000 });
390
+ output = sandbox.result;
391
+ } catch (err) {
392
+ success = false;
393
+ error = err.message || String(err);
394
+ }
395
+
396
+ const duration = Date.now() - start;
397
+
398
+ stmts.insertExecution.run(
399
+ execId, hookName, hook.plugin_id, siteId,
400
+ JSON.stringify(input || {}), JSON.stringify(output || {}),
401
+ duration, success ? 1 : 0, error
402
+ );
403
+
404
+ results.push({
405
+ plugin_id: hook.plugin_id,
406
+ plugin_name: hook.plugin_name,
407
+ hook_name: hookName,
408
+ output,
409
+ success,
410
+ error,
411
+ duration_ms: duration,
412
+ });
413
+ }
414
+
415
+ return results;
416
+ }
417
+
418
+ function getAvailableHooks() {
419
+ return [
420
+ { name: 'before_action', description: 'Triggered before any agent action is executed' },
421
+ { name: 'after_action', description: 'Triggered after an agent action completes' },
422
+ { name: 'on_discover', description: 'Triggered when agent discovers new page elements' },
423
+ { name: 'on_authenticate', description: 'Triggered during authentication flow' },
424
+ { name: 'on_error', description: 'Triggered when an error occurs during agent execution' },
425
+ { name: 'on_memory_store', description: 'Triggered when data is stored in agent memory' },
426
+ { name: 'on_memory_recall', description: 'Triggered when data is recalled from agent memory' },
427
+ { name: 'on_heal_selector', description: 'Triggered when a CSS selector self-heals' },
428
+ { name: 'on_vision_analyze', description: 'Triggered when vision analysis is performed on a page' },
429
+ { name: 'on_swarm_start', description: 'Triggered when a swarm task begins' },
430
+ { name: 'on_swarm_complete', description: 'Triggered when a swarm task completes' },
431
+ { name: 'on_fairness_search', description: 'Triggered during fairness-aware search ranking' },
432
+ { name: 'on_page_load', description: 'Triggered when a monitored page is loaded' },
433
+ { name: 'on_agent_connect', description: 'Triggered when an agent connects to a site' },
434
+ { name: 'on_agent_disconnect', description: 'Triggered when an agent disconnects from a site' },
435
+ { name: 'custom', description: 'Generic hook for user-defined plugin events' },
436
+ ];
437
+ }
438
+
439
+ // ─── Stats & Rating ───────────────────────────────────────────────────
440
+
441
+ function getPluginStats(pluginId) {
442
+ const plugin = stmts.getPlugin.get(pluginId);
443
+ if (!plugin) return null;
444
+
445
+ const instCount = stmts.installationCount.get(pluginId).count;
446
+ const execStats = stmts.executionStats.get(pluginId);
447
+ const total = execStats.total || 0;
448
+ const successes = execStats.successes || 0;
449
+
450
+ return {
451
+ plugin_id: pluginId,
452
+ name: plugin.name,
453
+ installations: instCount,
454
+ downloads: plugin.downloads,
455
+ avg_rating: plugin.rating,
456
+ rating_count: plugin.rating_count,
457
+ total_executions: total,
458
+ successful_executions: successes,
459
+ success_rate: total > 0 ? Math.round((successes / total) * 10000) / 100 : 0,
460
+ };
461
+ }
462
+
463
+ function ratePlugin(pluginId, userId, rating) {
464
+ if (rating < 1 || rating > 5) throw new Error('Rating must be between 1 and 5');
465
+
466
+ const plugin = stmts.getPlugin.get(pluginId);
467
+ if (!plugin) throw new Error(`Plugin not found: ${pluginId}`);
468
+
469
+ const oldAvg = plugin.rating || 0;
470
+ const oldCount = plugin.rating_count || 0;
471
+ const newAvg = ((oldAvg * oldCount) + rating) / (oldCount + 1);
472
+ const rounded = Math.round(newAvg * 100) / 100;
473
+
474
+ stmts.updateRating.run(rounded, pluginId);
475
+
476
+ return { plugin_id: pluginId, new_rating: rounded, rating_count: oldCount + 1 };
477
+ }
478
+
479
+ // ─── Execution Log ────────────────────────────────────────────────────
480
+
481
+ function getHookExecutionLog(siteId, { hookName, pluginId, limit } = {}) {
482
+ let sql = 'SELECT he.*, pr.name as plugin_name FROM hook_executions he LEFT JOIN plugin_registry pr ON he.plugin_id = pr.id WHERE he.site_id = ?';
483
+ const params = [siteId];
484
+
485
+ if (hookName) {
486
+ sql += ' AND he.hook_name = ?';
487
+ params.push(hookName);
488
+ }
489
+ if (pluginId) {
490
+ sql += ' AND he.plugin_id = ?';
491
+ params.push(pluginId);
492
+ }
493
+
494
+ sql += ' ORDER BY he.executed_at DESC LIMIT ?';
495
+ params.push(limit || 100);
496
+
497
+ const rows = db.prepare(sql).all(...params);
498
+ return rows.map(row => ({
499
+ ...row,
500
+ input: parseJSON(row.input, {}),
501
+ output: parseJSON(row.output, {}),
502
+ success: !!row.success,
503
+ }));
504
+ }
505
+
506
+ // ─── Seed Official Plugins ────────────────────────────────────────────
507
+
508
+ function seedOfficialPlugins() {
509
+ const existing = stmts.getPluginByName.get('fairness-boost');
510
+ if (existing) return;
511
+
512
+ const plugins = [
513
+ {
514
+ name: 'fairness-boost',
515
+ version: '1.0.0',
516
+ author: 'WAB Team',
517
+ description: 'Boosts indie and small-business sites in search results by 15% to promote a fairer web ecosystem.',
518
+ category: 'fairness',
519
+ entryPoint: 'fairness-boost/index.js',
520
+ icon: '⚖️',
521
+ isOfficial: true,
522
+ configSchema: {
523
+ properties: {
524
+ boost_percentage: { type: 'number', min: 1, max: 50 },
525
+ target_categories: { type: 'array' },
526
+ },
527
+ required: [],
528
+ },
529
+ hooks: [
530
+ {
531
+ name: 'on_fairness_search',
532
+ priority: 5,
533
+ handler: [
534
+ 'var results = input.results || [];',
535
+ 'var boost = (config && config.boost_percentage) || 15;',
536
+ 'var boosted = results.map(function(r) {',
537
+ ' if (r.is_indie || r.is_small_business) {',
538
+ ' return Object.assign({}, r, { score: (r.score || 0) * (1 + boost / 100), boosted: true });',
539
+ ' }',
540
+ ' return r;',
541
+ '});',
542
+ 'return { results: boosted, boost_applied: boost };',
543
+ ].join('\n'),
544
+ },
545
+ ],
546
+ },
547
+ {
548
+ name: 'security-monitor',
549
+ version: '1.0.0',
550
+ author: 'WAB Team',
551
+ description: 'Monitors agent actions for suspicious patterns like credential harvesting, XSS payloads, and unauthorized data access.',
552
+ category: 'security',
553
+ entryPoint: 'security-monitor/index.js',
554
+ icon: '🛡️',
555
+ isOfficial: true,
556
+ configSchema: {
557
+ properties: {
558
+ alert_threshold: { type: 'number', min: 1, max: 10 },
559
+ blocked_patterns: { type: 'array' },
560
+ },
561
+ required: [],
562
+ },
563
+ hooks: [
564
+ {
565
+ name: 'after_action',
566
+ priority: 1,
567
+ handler: [
568
+ 'var action = input.action || "";',
569
+ 'var data = input.data || "";',
570
+ 'var dataStr = typeof data === "string" ? data : JSON.stringify(data);',
571
+ 'var suspicious = [];',
572
+ 'var patterns = [',
573
+ ' { re: /password|passwd|secret|token/i, label: "credential_access" },',
574
+ ' { re: /<script|javascript:|on\\w+\\s*=/i, label: "xss_attempt" },',
575
+ ' { re: /eval\\(|Function\\(|setTimeout\\(.*,/i, label: "code_injection" },',
576
+ ' { re: /\\.env|credentials|private_key/i, label: "sensitive_file_access" }',
577
+ '];',
578
+ 'for (var i = 0; i < patterns.length; i++) {',
579
+ ' if (patterns[i].re.test(action) || patterns[i].re.test(dataStr)) {',
580
+ ' suspicious.push(patterns[i].label);',
581
+ ' }',
582
+ '}',
583
+ 'return { flagged: suspicious.length > 0, threats: suspicious, action: action, timestamp: new Date().toISOString() };',
584
+ ].join('\n'),
585
+ },
586
+ ],
587
+ },
588
+ {
589
+ name: 'analytics-enhanced',
590
+ version: '1.0.0',
591
+ author: 'WAB Team',
592
+ description: 'Provides detailed page-load analytics including timing metrics, resource counts, and performance scoring.',
593
+ category: 'analytics',
594
+ entryPoint: 'analytics-enhanced/index.js',
595
+ icon: '📊',
596
+ isOfficial: true,
597
+ configSchema: {
598
+ properties: {
599
+ track_resources: { type: 'boolean' },
600
+ track_timing: { type: 'boolean' },
601
+ sampling_rate: { type: 'number', min: 0, max: 100 },
602
+ },
603
+ required: [],
604
+ },
605
+ hooks: [
606
+ {
607
+ name: 'on_page_load',
608
+ priority: 10,
609
+ handler: [
610
+ 'var url = input.url || "unknown";',
611
+ 'var timing = input.timing || {};',
612
+ 'var loadTime = timing.loadComplete || 0;',
613
+ 'var domReady = timing.domReady || 0;',
614
+ 'var resources = input.resources || [];',
615
+ 'var scripts = resources.filter(function(r) { return r.type === "script"; }).length;',
616
+ 'var styles = resources.filter(function(r) { return r.type === "stylesheet"; }).length;',
617
+ 'var images = resources.filter(function(r) { return r.type === "image"; }).length;',
618
+ 'var perfScore = 100;',
619
+ 'if (loadTime > 3000) perfScore -= 20;',
620
+ 'if (loadTime > 5000) perfScore -= 20;',
621
+ 'if (scripts > 20) perfScore -= 15;',
622
+ 'if (images > 50) perfScore -= 10;',
623
+ 'if (perfScore < 0) perfScore = 0;',
624
+ 'return {',
625
+ ' url: url,',
626
+ ' load_time_ms: loadTime,',
627
+ ' dom_ready_ms: domReady,',
628
+ ' resource_counts: { scripts: scripts, styles: styles, images: images, total: resources.length },',
629
+ ' performance_score: perfScore,',
630
+ ' tracked_at: new Date().toISOString()',
631
+ '};',
632
+ ].join('\n'),
633
+ },
634
+ ],
635
+ },
636
+ {
637
+ name: 'auto-healer',
638
+ version: '1.0.0',
639
+ author: 'WAB Team',
640
+ description: 'Automatically logs errors and suggests self-healing strategies such as selector updates, retry logic, and fallback actions.',
641
+ category: 'reliability',
642
+ entryPoint: 'auto-healer/index.js',
643
+ icon: '🩹',
644
+ isOfficial: true,
645
+ configSchema: {
646
+ properties: {
647
+ max_retries: { type: 'number', min: 0, max: 10 },
648
+ auto_retry: { type: 'boolean' },
649
+ },
650
+ required: [],
651
+ },
652
+ hooks: [
653
+ {
654
+ name: 'on_error',
655
+ priority: 3,
656
+ handler: [
657
+ 'var errorMsg = input.error || input.message || "Unknown error";',
658
+ 'var selector = input.selector || null;',
659
+ 'var action = input.action || "unknown";',
660
+ 'var strategies = [];',
661
+ 'if (selector) {',
662
+ ' strategies.push({ type: "selector_update", suggestion: "Try broader selector or data-testid attribute" });',
663
+ ' strategies.push({ type: "wait_and_retry", suggestion: "Element may not be loaded yet, add wait before action" });',
664
+ '}',
665
+ 'if (/timeout|ETIMEDOUT/i.test(errorMsg)) {',
666
+ ' strategies.push({ type: "increase_timeout", suggestion: "Network may be slow, increase timeout threshold" });',
667
+ ' strategies.push({ type: "retry", suggestion: "Transient failure, retry with exponential backoff" });',
668
+ '}',
669
+ 'if (/not found|404/i.test(errorMsg)) {',
670
+ ' strategies.push({ type: "fallback_url", suggestion: "Page may have moved, check for redirects" });',
671
+ '}',
672
+ 'if (/permission|forbidden|403/i.test(errorMsg)) {',
673
+ ' strategies.push({ type: "re_authenticate", suggestion: "Session may have expired, re-authenticate" });',
674
+ '}',
675
+ 'if (strategies.length === 0) {',
676
+ ' strategies.push({ type: "log_and_skip", suggestion: "Unknown error pattern, log and continue" });',
677
+ '}',
678
+ 'return { error: errorMsg, action: action, selector: selector, strategies: strategies, analyzed_at: new Date().toISOString() };',
679
+ ].join('\n'),
680
+ },
681
+ ],
682
+ },
683
+ {
684
+ name: 'memory-optimizer',
685
+ version: '1.0.0',
686
+ author: 'WAB Team',
687
+ description: 'Checks for duplicate entries before storing new data in agent memory, reducing storage waste and improving recall accuracy.',
688
+ category: 'performance',
689
+ entryPoint: 'memory-optimizer/index.js',
690
+ icon: '🧠',
691
+ isOfficial: true,
692
+ configSchema: {
693
+ properties: {
694
+ similarity_threshold: { type: 'number', min: 0, max: 1 },
695
+ max_memory_entries: { type: 'number', min: 10, max: 100000 },
696
+ },
697
+ required: [],
698
+ },
699
+ hooks: [
700
+ {
701
+ name: 'on_memory_store',
702
+ priority: 5,
703
+ handler: [
704
+ 'var key = input.key || "";',
705
+ 'var value = input.value || "";',
706
+ 'var existingKeys = input.existing_keys || [];',
707
+ 'var valueStr = typeof value === "string" ? value : JSON.stringify(value);',
708
+ 'var dominated = false;',
709
+ 'var duplicateOf = null;',
710
+ 'for (var i = 0; i < existingKeys.length; i++) {',
711
+ ' if (existingKeys[i] === key) {',
712
+ ' dominated = true;',
713
+ ' duplicateOf = key;',
714
+ ' break;',
715
+ ' }',
716
+ ' var normalizedExisting = existingKeys[i].toLowerCase().replace(/[^a-z0-9]/g, "");',
717
+ ' var normalizedNew = key.toLowerCase().replace(/[^a-z0-9]/g, "");',
718
+ ' if (normalizedExisting === normalizedNew) {',
719
+ ' dominated = true;',
720
+ ' duplicateOf = existingKeys[i];',
721
+ ' break;',
722
+ ' }',
723
+ '}',
724
+ 'return {',
725
+ ' allow_store: !dominated,',
726
+ ' is_duplicate: dominated,',
727
+ ' duplicate_of: duplicateOf,',
728
+ ' key: key,',
729
+ ' value_length: valueStr.length,',
730
+ ' checked_at: new Date().toISOString()',
731
+ '};',
732
+ ].join('\n'),
733
+ },
734
+ ],
735
+ },
736
+ ];
737
+
738
+ const doSeed = db.transaction(() => {
739
+ for (const p of plugins) {
740
+ try {
741
+ registerPlugin(p);
742
+ } catch (_) {
743
+ // already exists
744
+ }
745
+ }
746
+ });
747
+ doSeed();
748
+ }
749
+
750
+ seedOfficialPlugins();
751
+
752
+ // ─── Exports ──────────────────────────────────────────────────────────
753
+
754
+ module.exports = {
755
+ registerPlugin,
756
+ getPlugin,
757
+ getPluginByName,
758
+ listPlugins,
759
+ installPlugin,
760
+ uninstallPlugin,
761
+ configurePlugin,
762
+ getInstalledPlugins,
763
+ registerHook,
764
+ executeHook,
765
+ getAvailableHooks,
766
+ validateConfig,
767
+ getPluginStats,
768
+ ratePlugin,
769
+ getHookExecutionLog,
770
+ seedOfficialPlugins,
771
+ };