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,721 +1,721 @@
1
- /**
2
- * WAB /demo page — tries live Railway store, falls back to in-browser protocol simulator.
3
- * No placeholders: full cart/checkout/order parity with TechStore API shape.
4
- */
5
- (function () {
6
- 'use strict';
7
-
8
- var STORE = 'https://web-agent-bridge-production.up.railway.app';
9
- var CONNECT_MS = 4500;
10
-
11
- var OFFLINE_CATALOG = [
12
- { id: 1, name: 'Wireless Headphones', price: 4900, currency: 'USD', category: 'electronics', image: '🎧', rating: 4.7 },
13
- { id: 2, name: 'Mechanical Keyboard', price: 8900, currency: 'USD', category: 'electronics', image: '⌨️', rating: 4.9 },
14
- { id: 3, name: 'Smart Watch', price: 19900, currency: 'USD', category: 'electronics', image: '⌚', rating: 4.5 },
15
- { id: 4, name: 'USB-C Hub', price: 3400, currency: 'USD', category: 'accessories', image: '🔌', rating: 4.3 }
16
- ];
17
-
18
- var useRemote = false;
19
- var offlineStock = {};
20
- var offlineCart = [];
21
- var offlineOrders = [];
22
- var offlineAudit = [];
23
-
24
- function resetOfflineState() {
25
- offlineCart = [];
26
- offlineOrders = [];
27
- offlineAudit = [];
28
- OFFLINE_CATALOG.forEach(function (p) { offlineStock[p.id] = p.id === 1 ? 12 : p.id === 2 ? 7 : p.id === 3 ? 3 : 25; });
29
- }
30
-
31
- function fmtCents(c) {
32
- return '$' + (c / 100).toFixed(2);
33
- }
34
-
35
- function cloneProducts() {
36
- return OFFLINE_CATALOG.map(function (p) {
37
- return {
38
- id: p.id,
39
- name: p.name,
40
- price: p.price,
41
- currency: p.currency,
42
- stock: offlineStock[p.id],
43
- category: p.category,
44
- image: p.image,
45
- rating: p.rating,
46
- priceFormatted: fmtCents(p.price)
47
- };
48
- });
49
- }
50
-
51
- function localDiscovery() {
52
- return {
53
- wab_version: '1.2.0',
54
- protocol: '1.0',
55
- generated_at: new Date().toISOString(),
56
- site: {
57
- name: 'TechStore (Offline Demo)',
58
- domain: 'browser-local',
59
- description: 'In-browser WAB simulator — same JSON shape as live store; no network required.',
60
- category: 'e-commerce',
61
- platform: 'demo'
62
- },
63
- actions: [
64
- { name: 'listProducts', description: 'List all products' },
65
- { name: 'getProduct', description: 'Get product by id' },
66
- { name: 'searchProducts', description: 'Search products' },
67
- { name: 'addToCart', description: 'Add to cart' },
68
- { name: 'viewCart', description: 'View cart' },
69
- { name: 'removeFromCart', description: 'Remove from cart' },
70
- { name: 'checkout', description: 'Checkout' },
71
- { name: 'getOrderStatus', description: 'Order status' }
72
- ],
73
- endpoints: { execute: 'local://wab/execute', discover: 'local://.well-known/wab.json' }
74
- };
75
- }
76
-
77
- function localExec(action, params) {
78
- params = params || {};
79
- var result;
80
- switch (action) {
81
- case 'listProducts': {
82
- var list = cloneProducts();
83
- if (params.category) list = list.filter(function (p) { return p.category === params.category; });
84
- result = { products: list, total: list.length };
85
- break;
86
- }
87
- case 'getProduct': {
88
- var gp = cloneProducts().find(function (x) { return x.id === params.productId; });
89
- result = gp || { error: 'Product ' + params.productId + ' not found' };
90
- break;
91
- }
92
- case 'searchProducts': {
93
- var q = (params.query || '').toLowerCase();
94
- var matches = cloneProducts().filter(function (p) {
95
- return p.name.toLowerCase().indexOf(q) !== -1 || p.category.indexOf(q) !== -1;
96
- });
97
- result = { query: params.query, results: matches, total: matches.length };
98
- break;
99
- }
100
- case 'addToCart': {
101
- var id = params.productId;
102
- var qty = params.quantity || 1;
103
- var prod = OFFLINE_CATALOG.find(function (x) { return x.id === id; });
104
- if (!prod) { result = { error: 'Product ' + id + ' not found' }; break; }
105
- if (offlineStock[id] < qty) { result = { error: 'Insufficient stock. Available: ' + offlineStock[id] }; break; }
106
- offlineStock[id] -= qty;
107
- var existing = offlineCart.find(function (c) { return c.productId === id; });
108
- if (existing) existing.quantity += qty;
109
- else offlineCart.push({ productId: id, name: prod.name, price: prod.price, quantity: qty });
110
- var tAdd = offlineCart.reduce(function (s, c) { return s + c.price * c.quantity; }, 0);
111
- result = { added: prod.name, quantity: qty, cartItems: offlineCart.length, cartTotal: fmtCents(tAdd) };
112
- break;
113
- }
114
- case 'viewCart': {
115
- var tView = offlineCart.reduce(function (s, c) { return s + c.price * c.quantity; }, 0);
116
- result = {
117
- items: offlineCart.map(function (c) {
118
- return {
119
- productId: c.productId,
120
- name: c.name,
121
- price: c.price,
122
- quantity: c.quantity,
123
- priceFormatted: fmtCents(c.price),
124
- subtotal: fmtCents(c.price * c.quantity)
125
- };
126
- }),
127
- itemCount: offlineCart.reduce(function (s, c) { return s + c.quantity; }, 0),
128
- total: fmtCents(tView)
129
- };
130
- break;
131
- }
132
- case 'removeFromCart': {
133
- var rid = params.productId;
134
- var idx = offlineCart.findIndex(function (c) { return c.productId === rid; });
135
- if (idx === -1) { result = { error: 'Product not in cart' }; break; }
136
- var rem = offlineCart.splice(idx, 1)[0];
137
- var pRem = OFFLINE_CATALOG.find(function (x) { return x.id === rem.productId; });
138
- if (pRem) offlineStock[rid] += rem.quantity;
139
- var tRem = offlineCart.reduce(function (s, c) { return s + c.price * c.quantity; }, 0);
140
- result = { removed: rem.name, cartItems: offlineCart.length, cartTotal: fmtCents(tRem) };
141
- break;
142
- }
143
- case 'checkout': {
144
- if (!offlineCart.length) { result = { error: 'Cart is empty' }; break; }
145
- if (!params.email) { result = { error: 'Email is required' }; break; }
146
- var tCo = offlineCart.reduce(function (s, c) { return s + c.price * c.quantity; }, 0);
147
- var itemCount = offlineCart.reduce(function (s, c) { return s + c.quantity; }, 0);
148
- var oid = 'ORD-OFF-' + Math.random().toString(36).slice(2, 10).toUpperCase();
149
- offlineOrders.push({
150
- orderId: oid,
151
- email: params.email,
152
- items: offlineCart.map(function (c) { return Object.assign({}, c); }),
153
- total: fmtCents(tCo),
154
- status: 'confirmed',
155
- createdAt: new Date().toISOString()
156
- });
157
- offlineCart = [];
158
- result = { orderId: oid, status: 'confirmed', total: fmtCents(tCo), itemCount: itemCount, email: params.email };
159
- break;
160
- }
161
- case 'getOrderStatus': {
162
- var ord = offlineOrders.find(function (o) { return o.orderId === params.orderId; });
163
- if (!ord) { result = { error: 'Order ' + params.orderId + ' not found' }; break; }
164
- var ic = ord.items.reduce(function (s, i) { return s + i.quantity; }, 0);
165
- result = { orderId: ord.orderId, status: ord.status, total: ord.total, itemCount: ic, createdAt: ord.createdAt };
166
- break;
167
- }
168
- default:
169
- result = { error: 'Unknown action: ' + action };
170
- }
171
- var success = !result.error;
172
- offlineAudit.push({ action: action, params: params, success: success, timestamp: new Date().toISOString() });
173
- if (offlineAudit.length > 200) offlineAudit.shift();
174
- return { success: success, action: action, result: result, wab_version: '1.2.0', duration_ms: 0, mode: 'offline' };
175
- }
176
-
177
- function localGet(path) {
178
- if (path === '/.well-known/wab.json' || path === '/agent-bridge.json' || path === '/wab/discover') {
179
- return localDiscovery();
180
- }
181
- if (path === '/wab/ping') {
182
- return { status: 'ok', wab_version: '1.2.0', protocol: '1.0', mode: 'offline-demo', timestamp: new Date().toISOString() };
183
- }
184
- if (path === '/wab/audit') {
185
- return { entries: offlineAudit.slice(-50), total: offlineAudit.length, mode: 'offline-demo' };
186
- }
187
- return { error: 'Not found', path: path };
188
- }
189
-
190
- /* ── DOM refs ─────────────────────────────────── */
191
- var netLog = document.getElementById('net-log');
192
- var agentLog = document.getElementById('agent-log');
193
- var reqCount = 0;
194
- var busy = false;
195
- var cartData = { items: [], total: '$0.00', itemCount: 0 };
196
- var productsCache = [];
197
-
198
- var bannerEl = document.getElementById('demo-mode-banner');
199
- var storeFrame = document.getElementById('store-frame');
200
- var storeLiveWrap = document.getElementById('store-live-wrap');
201
- var storeOfflineBox = document.getElementById('store-offline-placeholder');
202
-
203
- function setBanner(html, kind) {
204
- if (!bannerEl) return;
205
- bannerEl.style.display = 'block';
206
- bannerEl.className = 'demo-banner demo-banner--' + (kind || 'info');
207
- bannerEl.innerHTML = html;
208
- }
209
-
210
- function syntaxHL(json) {
211
- if (typeof json !== 'string') json = JSON.stringify(json, null, 2);
212
- return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (m) {
213
- var c = 'num';
214
- if (/^"/.test(m)) c = /:$/.test(m) ? 'key' : 'str';
215
- else if (/true|false/.test(m)) c = 'bool';
216
- return '<span class="' + c + '">' + m + '</span>';
217
- });
218
- }
219
-
220
- function addNetEntry(method, url, reqBody, resBody, status, duration, label) {
221
- var id = ++reqCount;
222
- document.getElementById('req-count').textContent = reqCount + ' request' + (reqCount > 1 ? 's' : '');
223
- var g = document.createElement('div');
224
- g.className = 'log-group';
225
- var sc = status >= 200 && status < 300 ? 's2' : 's4';
226
- var short = url.replace(STORE, '');
227
- if (label) short = '<span class="net-local">' + label + '</span> ' + short;
228
- g.innerHTML =
229
- '<div class="log-group-header">' +
230
- '<span class="arrow" id="arr-' + id + '">▶</span>' +
231
- '<span class="method ' + method + '">' + method + '</span>' +
232
- '<span class="url">' + short + '</span>' +
233
- '<span class="status ' + sc + '">' + status + '</span>' +
234
- '<span class="timing">' + duration + 'ms</span>' +
235
- '</div>' +
236
- '<div class="log-group-body" id="nb-' + id + '">' +
237
- (reqBody ? '<div class="log-sec"><div class="log-sec-title">Request</div><div class="log-json">' + syntaxHL(reqBody) + '</div></div>' : '') +
238
- '<div class="log-sec"><div class="log-sec-title">Response · ' + status + '</div><div class="log-json">' + syntaxHL(resBody) + '</div></div>' +
239
- '</div>';
240
- g.querySelector('.log-group-header').addEventListener('click', function () {
241
- document.getElementById('nb-' + id).classList.toggle('open');
242
- document.getElementById('arr-' + id).classList.toggle('open');
243
- });
244
- netLog.appendChild(g);
245
- netLog.scrollTop = netLog.scrollHeight;
246
- }
247
-
248
- function wabGet(path) {
249
- var s = performance.now();
250
- if (!useRemote) {
251
- var d = localGet(path);
252
- addNetEntry('GET', 'local://wab' + path, null, d, 200, Math.round(performance.now() - s), 'OFFLINE');
253
- return Promise.resolve(d);
254
- }
255
- var url = STORE + path;
256
- return fetch(url)
257
- .then(function (r) { return r.json().then(function (j) { addNetEntry('GET', url, null, j, r.status, Math.round(performance.now() - s)); return j; }); })
258
- .catch(function (err) {
259
- addNetEntry('GET', url, null, { error: String(err.message || err) }, 0, Math.round(performance.now() - s));
260
- throw err;
261
- });
262
- }
263
-
264
- function wabExec(action, params) {
265
- var s = performance.now();
266
- if (!useRemote) {
267
- var body = { action: action, params: params || {} };
268
- var out = localExec(action, params);
269
- addNetEntry('POST', 'local://wab/execute', body, out, 200, Math.round(performance.now() - s), 'OFFLINE');
270
- return Promise.resolve(out);
271
- }
272
- var url = STORE + '/wab/execute';
273
- var bodyR = { action: action, params: params || {} };
274
- return fetch(url, {
275
- method: 'POST',
276
- headers: { 'Content-Type': 'application/json' },
277
- body: JSON.stringify(bodyR)
278
- })
279
- .then(function (r) { return r.json().then(function (j) { addNetEntry('POST', url, bodyR, j, r.status, Math.round(performance.now() - s)); return j; }); })
280
- .catch(function (err) {
281
- addNetEntry('POST', url, bodyR, { error: String(err.message || err) }, 0, Math.round(performance.now() - s));
282
- throw err;
283
- });
284
- }
285
-
286
- function sleep(ms) {
287
- return new Promise(function (r) { setTimeout(r, ms); });
288
- }
289
-
290
- function refreshStore() {
291
- if (!useRemote) return;
292
- try { storeFrame.contentWindow.postMessage({ source: 'wab-agent', type: 'refresh' }, '*'); } catch (e) {}
293
- setTimeout(function () { storeFrame.src = STORE + '?t=' + Date.now(); }, 300);
294
- }
295
-
296
- function applyStorePanel() {
297
- if (useRemote) {
298
- if (storeLiveWrap) storeLiveWrap.style.display = '';
299
- if (storeOfflineBox) storeOfflineBox.style.display = 'none';
300
- } else {
301
- if (storeLiveWrap) storeLiveWrap.style.display = 'none';
302
- if (storeOfflineBox) storeOfflineBox.style.display = 'flex';
303
- }
304
- }
305
-
306
- function agentMsg(text, type) {
307
- var div = document.createElement('div');
308
- div.className = 'agent-msg ' + (type || 'system');
309
- div.textContent = text;
310
- agentLog.appendChild(div);
311
- agentLog.scrollTop = agentLog.scrollHeight;
312
- }
313
-
314
- function setPhase(n, s) {
315
- var d = document.getElementById('ph-' + n);
316
- var l = document.getElementById('pl-' + n);
317
- if (d) d.className = 'ph-dot' + (s ? ' ' + s : '');
318
- if (l) l.className = 'ph-lbl' + (s ? ' ' + s : '');
319
- }
320
-
321
- function resetPhases() {
322
- ['discover', 'plan', 'execute', 'confirm'].forEach(function (p) { setPhase(p, ''); });
323
- }
324
-
325
- /* ── Shop UI ──────────────────────────────────── */
326
- function loadProducts() {
327
- var grid = document.getElementById('products-grid');
328
- grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:24px;color:var(--muted)">Loading products via WAB Protocol…</div>';
329
- return wabExec('listProducts')
330
- .then(function (d) {
331
- if (!d.success) {
332
- grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:24px;color:var(--red)">Could not load products. <button type="button" class="retry-btn" id="demo-retry">Retry</button></div>';
333
- var rb = document.getElementById('demo-retry');
334
- if (rb) rb.addEventListener('click', function () { loadProducts(); });
335
- return;
336
- }
337
- productsCache = d.result.products;
338
- renderProducts();
339
- })
340
- .catch(function () {
341
- grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:24px;color:var(--red)">Network error. <button type="button" class="retry-btn" id="demo-retry">Retry</button></div>';
342
- var rb = document.getElementById('demo-retry');
343
- if (rb) rb.addEventListener('click', function () { loadProducts(); });
344
- });
345
- }
346
-
347
- function renderProducts() {
348
- var grid = document.getElementById('products-grid');
349
- grid.innerHTML = productsCache.map(function (p) {
350
- var stars = '';
351
- for (var i = 0; i < 5; i++) stars += i < Math.round(p.rating) ? '★' : '☆';
352
- var sc = p.stock <= 5 ? 'stock low' : 'stock';
353
- var st = p.stock <= 0 ? 'Out of stock' : (p.stock <= 5 ? p.stock + ' left' : p.stock + ' in stock');
354
- return '<div class="p-card">' +
355
- '<span class="emoji">' + p.image + '</span>' +
356
- '<h4>' + p.name + '</h4>' +
357
- '<div class="rating">' + stars + '</div>' +
358
- '<div class="price">' + p.priceFormatted + '</div>' +
359
- '<div class="' + sc + '">' + st + '</div>' +
360
- '<button class="add" data-id="' + p.id + '" data-name="' + p.name.replace(/"/g, '&quot;') + '"' + (p.stock <= 0 ? ' disabled' : '') + '>+ Add to Cart</button>' +
361
- '</div>';
362
- }).join('');
363
- grid.querySelectorAll('.add').forEach(function (btn) {
364
- btn.addEventListener('click', function () {
365
- shopAddToCart(parseInt(btn.dataset.id, 10), btn.dataset.name);
366
- });
367
- });
368
- }
369
-
370
- function shopAddToCart(id, name) {
371
- wabExec('addToCart', { productId: id, quantity: 1 }).then(function (d) {
372
- if (d.success) {
373
- shopRefreshCart();
374
- loadProducts();
375
- refreshStore();
376
- }
377
- });
378
- }
379
-
380
- function shopRemoveFromCart(id) {
381
- wabExec('removeFromCart', { productId: id }).then(function (d) {
382
- if (d.success) {
383
- shopRefreshCart();
384
- loadProducts();
385
- refreshStore();
386
- }
387
- });
388
- }
389
-
390
- function shopRefreshCart() {
391
- return wabExec('viewCart').then(function (d) {
392
- if (!d.success) return;
393
- cartData = d.result;
394
- renderCart();
395
- });
396
- }
397
-
398
- function renderCart() {
399
- var area = document.getElementById('cart-area');
400
- var items = document.getElementById('cart-items');
401
- var totalEl = document.getElementById('cart-total-val');
402
- if (cartData.itemCount === 0) {
403
- area.style.display = 'none';
404
- return;
405
- }
406
- area.style.display = 'block';
407
- items.innerHTML = cartData.items.map(function (c) {
408
- var prod = productsCache.find(function (p) { return p.id === c.productId; }) || {};
409
- return '<div class="cart-item">' +
410
- '<span class="ci-emoji">' + (prod.image || '📦') + '</span>' +
411
- '<div class="ci-info"><div class="ci-name">' + c.name + '</div><div class="ci-meta">Qty: ' + c.quantity + ' × ' + c.priceFormatted + '</div></div>' +
412
- '<div class="ci-price">' + c.subtotal + '</div>' +
413
- '<button class="ci-remove" data-id="' + c.productId + '">✕</button>' +
414
- '</div>';
415
- }).join('');
416
- totalEl.textContent = cartData.total;
417
- items.querySelectorAll('.ci-remove').forEach(function (btn) {
418
- btn.addEventListener('click', function () {
419
- shopRemoveFromCart(parseInt(btn.dataset.id, 10));
420
- });
421
- });
422
- }
423
-
424
- function checkoutSuccessCopy() {
425
- return useRemote
426
- ? 'Every step used HTTP to the live Railway TechStore (WAB Protocol). See Network Log →'
427
- : 'This session used the <strong>offline WAB simulator</strong> in your browser — same JSON request/response shape as a real store; no external server required.';
428
- }
429
-
430
- /* ── AI Agent flows ───────────────────────────── */
431
- function doDiscover() {
432
- setPhase('discover', 'active');
433
- agentMsg('Fetching discovery document…', 'think');
434
- return wabGet('/.well-known/wab.json').then(function (doc) {
435
- var n = doc.actions && doc.actions.length ? doc.actions.length : 0;
436
- agentMsg('Discovered ' + n + ' actions on "' + (doc.site && doc.site.name) + '"', 'result');
437
- setPhase('discover', 'done');
438
- return doc;
439
- });
440
- }
441
-
442
- function runFullAgent() {
443
- if (busy) return;
444
- busy = true;
445
- document.getElementById('btn-full').disabled = true;
446
- resetPhases();
447
- agentLog.innerHTML = '';
448
- agentMsg('Agent session started (' + (useRemote ? 'live store' : 'offline simulator') + ')', 'system');
449
- agentMsg('Target: ' + (useRemote ? STORE : 'local://wab'), 'system');
450
-
451
- doDiscover()
452
- .then(function (doc) { return sleep(300).then(function () { return doc; }); })
453
- .then(function (doc) {
454
- setPhase('plan', 'active');
455
- agentMsg('Planning: find cheapest in-stock product → cart → checkout → verify', 'think');
456
- setPhase('plan', 'done');
457
- return sleep(200).then(function () { return doc; });
458
- })
459
- .then(function () {
460
- setPhase('execute', 'active');
461
- return wabExec('listProducts');
462
- })
463
- .then(function (list) {
464
- if (!list || !list.success || !list.result || !list.result.products) {
465
- throw new Error((list && list.result && list.result.error) || 'listProducts failed');
466
- }
467
- var prods = list.result.products;
468
- agentMsg('Found ' + prods.length + ' products', 'result');
469
- var cheap = prods.reduce(function (a, b) { return a.price < b.price ? a : b; });
470
- agentMsg('Cheapest: "' + cheap.name + '" at ' + cheap.priceFormatted, 'think');
471
- return wabExec('addToCart', { productId: cheap.id, quantity: 1 });
472
- })
473
- .then(function (addD) {
474
- agentMsg(addD.success ? 'Added. Cart: ' + addD.result.cartTotal : 'Failed: ' + addD.result.error, addD.success ? 'result' : 'error');
475
- return wabExec('viewCart');
476
- })
477
- .then(function (cartD) {
478
- agentMsg('Cart: ' + cartD.result.itemCount + ' item(s), ' + cartD.result.total, 'result');
479
- return wabExec('checkout', { email: 'agent@webagentbridge.com' });
480
- })
481
- .then(function (orderD) {
482
- if (!orderD || !orderD.result) {
483
- agentMsg('Checkout returned no result', 'error');
484
- setPhase('execute', 'done');
485
- return Promise.resolve();
486
- }
487
- agentMsg(orderD.success ? 'Order: ' + orderD.result.orderId + ' — ' + orderD.result.total : 'Failed: ' + (orderD.result.error || orderD.result), orderD.success ? 'result' : 'error');
488
- setPhase('execute', 'done');
489
- if (!orderD.success) {
490
- setPhase('confirm', 'active');
491
- return wabGet('/wab/audit');
492
- }
493
- setPhase('confirm', 'active');
494
- return wabExec('getOrderStatus', { orderId: orderD.result.orderId }).then(function (st) {
495
- agentMsg('Status: ' + (st.result && st.result.status ? st.result.status : 'unknown'), 'result');
496
- return wabGet('/wab/audit');
497
- });
498
- })
499
- .then(function () {
500
- agentMsg('Audit log checked', 'result');
501
- setPhase('confirm', 'done');
502
- agentMsg('Complete — see Network Log for all protocol calls', 'system');
503
- refreshStore();
504
- return loadProducts();
505
- })
506
- .catch(function (e) {
507
- agentMsg('Agent error: ' + (e && e.message ? e.message : e), 'error');
508
- })
509
- .finally(function () {
510
- busy = false;
511
- document.getElementById('btn-full').disabled = false;
512
- });
513
- }
514
-
515
- function handleInput(text) {
516
- if (busy) return;
517
- text = text.trim();
518
- if (!text) return;
519
- busy = true;
520
- if (text.charAt(0) === '{') {
521
- try {
522
- var p = JSON.parse(text);
523
- if (p.action) {
524
- agentMsg('Execute: ' + p.action, 'user');
525
- wabExec(p.action, p.params).then(function () {
526
- if (['addToCart', 'removeFromCart', 'checkout'].indexOf(p.action) !== -1) {
527
- refreshStore();
528
- loadProducts();
529
- }
530
- busy = false;
531
- });
532
- return;
533
- }
534
- } catch (e) {}
535
- }
536
- agentMsg('User: ' + text, 'user');
537
- var l = text.toLowerCase();
538
- if (l.indexOf('discover') !== -1) {
539
- doDiscover().finally(function () { busy = false; });
540
- return;
541
- }
542
- if (l.indexOf('list') !== -1 || l.indexOf('product') !== -1) {
543
- wabExec('listProducts').then(function (d) {
544
- if (d.success) agentMsg(d.result.total + ' products', 'result');
545
- busy = false;
546
- });
547
- return;
548
- }
549
- if (l.indexOf('search') !== -1 || l.indexOf('find') !== -1) {
550
- var q = text.replace(/^.*?(search|find)\s*(for)?\s*/i, '').trim() || 'keyboard';
551
- wabExec('searchProducts', { query: q }).then(function (d) {
552
- if (d.success) agentMsg(d.result.total + ' results', 'result');
553
- busy = false;
554
- });
555
- return;
556
- }
557
- if (l.indexOf('cart') !== -1) {
558
- wabExec('viewCart').then(function (d) {
559
- agentMsg(d.result.itemCount + ' items, ' + d.result.total, 'result');
560
- busy = false;
561
- });
562
- return;
563
- }
564
- if (l.indexOf('buy') !== -1 || l.indexOf('purchase') !== -1 || l.indexOf('cheapest') !== -1) {
565
- runFullAgent();
566
- busy = false;
567
- return;
568
- }
569
- if (l.indexOf('ping') !== -1) {
570
- wabGet('/wab/ping').finally(function () { busy = false; });
571
- return;
572
- }
573
- if (l.indexOf('audit') !== -1) {
574
- wabGet('/wab/audit').finally(function () { busy = false; });
575
- return;
576
- }
577
- agentMsg('Try: discover, list products, search keyboard, view cart, buy cheapest, or raw JSON', 'think');
578
- busy = false;
579
- }
580
-
581
- /* ── Init: probe remote ───────────────────────── */
582
- resetOfflineState();
583
-
584
- function tryRemote() {
585
- var ctrl = new AbortController();
586
- var t = setTimeout(function () { ctrl.abort(); }, CONNECT_MS);
587
- return fetch(STORE + '/wab/ping', { signal: ctrl.signal })
588
- .then(function (r) {
589
- clearTimeout(t);
590
- if (!r.ok) throw new Error('ping ' + r.status);
591
- return r.json();
592
- })
593
- .then(function () {
594
- useRemote = true;
595
- setBanner(
596
- '<strong>Live demo store connected.</strong> Requests go to Railway; if it goes offline, this page switches to the offline simulator automatically on reload.',
597
- 'ok'
598
- );
599
- applyStorePanel();
600
- })
601
- .catch(function () {
602
- useRemote = false;
603
- setBanner(
604
- '<strong>Offline mode.</strong> The live TechStore on Railway did not respond in time. ' +
605
- 'You are using the <strong>in-browser WAB simulator</strong> — same <code>POST /wab/execute</code> JSON shape, logged as <code>OFFLINE</code> in the network panel. ' +
606
- '<a href="' + STORE + '" target="_blank" rel="noopener">Open live store</a> in a new tab when it is available.',
607
- 'warn'
608
- );
609
- applyStorePanel();
610
- });
611
- }
612
-
613
- document.querySelectorAll('.tab').forEach(function (t) {
614
- t.addEventListener('click', function () {
615
- document.querySelectorAll('.tab').forEach(function (x) { x.classList.remove('active'); });
616
- document.querySelectorAll('.tab-body').forEach(function (x) { x.classList.remove('active'); });
617
- this.classList.add('active');
618
- document.getElementById('tab-' + this.dataset.tab).classList.add('active');
619
- });
620
- });
621
-
622
- document.getElementById('btn-checkout').addEventListener('click', function () {
623
- var email = document.getElementById('checkout-email').value;
624
- if (!email) return;
625
- var btn = this;
626
- btn.disabled = true;
627
- btn.textContent = 'Processing…';
628
- wabExec('checkout', { email: email }).then(function (d) {
629
- if (d.success) {
630
- return wabExec('getOrderStatus', { orderId: d.result.orderId }).then(function (statusD) {
631
- document.getElementById('shop-view').style.display = 'none';
632
- document.getElementById('order-view').style.display = 'block';
633
- document.getElementById('order-view').innerHTML =
634
- '<div class="order-done">' +
635
- '<div class="check">✅</div>' +
636
- '<h3>Order Confirmed!</h3>' +
637
- '<div class="oid">' + d.result.orderId + '</div>' +
638
- '<p>Total: <strong>' + d.result.total + '</strong><br>' + d.result.itemCount + ' item(s)<br>' + d.result.email + '</p>' +
639
- '<p style="margin-top:12px;font-size:0.75rem;color:var(--muted)">Status: ' + (statusD.success ? statusD.result.status : 'confirmed') + '</p>' +
640
- '<p style="margin-top:14px;font-size:0.72rem;color:var(--dim);line-height:1.5">' + checkoutSuccessCopy() + '</p>' +
641
- '<button class="reset-btn" id="btn-reset-shop">Shop Again</button>' +
642
- '</div>';
643
- document.getElementById('btn-reset-shop').addEventListener('click', function () {
644
- document.getElementById('shop-view').style.display = 'block';
645
- document.getElementById('order-view').style.display = 'none';
646
- cartData = { items: [], total: '$0.00', itemCount: 0 };
647
- renderCart();
648
- if (!useRemote) resetOfflineState();
649
- loadProducts();
650
- refreshStore();
651
- btn.disabled = false;
652
- btn.textContent = 'Complete Purchase via WAB Protocol';
653
- });
654
- refreshStore();
655
- });
656
- } else {
657
- btn.disabled = false;
658
- btn.textContent = 'Complete Purchase via WAB Protocol';
659
- alert(d.result.error || 'Checkout failed');
660
- }
661
- });
662
- });
663
-
664
- document.getElementById('btn-full').addEventListener('click', runFullAgent);
665
- document.getElementById('btn-discover').addEventListener('click', function () {
666
- if (!busy) {
667
- busy = true;
668
- doDiscover().finally(function () { busy = false; });
669
- }
670
- });
671
- document.getElementById('btn-list').addEventListener('click', function () {
672
- if (!busy) {
673
- busy = true;
674
- agentMsg('Listing…', 'think');
675
- wabExec('listProducts').finally(function () { busy = false; });
676
- }
677
- });
678
- document.getElementById('btn-search').addEventListener('click', function () {
679
- var q = prompt('Search:');
680
- if (q && !busy) {
681
- busy = true;
682
- wabExec('searchProducts', { query: q }).finally(function () { busy = false; });
683
- }
684
- });
685
- document.getElementById('btn-viewcart').addEventListener('click', function () {
686
- if (!busy) {
687
- busy = true;
688
- wabExec('viewCart').finally(function () { busy = false; });
689
- }
690
- });
691
- document.getElementById('btn-clear').addEventListener('click', function () {
692
- netLog.innerHTML = '';
693
- reqCount = 0;
694
- document.getElementById('req-count').textContent = '0 requests';
695
- });
696
- document.getElementById('btn-send').addEventListener('click', function () {
697
- var i = document.getElementById('cmd-input');
698
- handleInput(i.value);
699
- i.value = '';
700
- });
701
- document.getElementById('cmd-input').addEventListener('keydown', function (e) {
702
- if (e.key === 'Enter') {
703
- handleInput(this.value);
704
- this.value = '';
705
- }
706
- });
707
-
708
- window.addEventListener('message', function (e) {
709
- if (!e.data || e.data.source !== 'wab-store') return;
710
- if (e.data.type === 'action-executed' || e.data.type === 'cart-update') {
711
- loadProducts();
712
- shopRefreshCart();
713
- }
714
- });
715
-
716
- tryRemote().then(function () {
717
- return loadProducts();
718
- }).then(function () {
719
- return shopRefreshCart();
720
- });
721
- })();
1
+ /**
2
+ * WAB /demo page — tries live Railway store, falls back to in-browser protocol simulator.
3
+ * No placeholders: full cart/checkout/order parity with TechStore API shape.
4
+ */
5
+ (function () {
6
+ 'use strict';
7
+
8
+ var STORE = 'https://web-agent-bridge-production.up.railway.app';
9
+ var CONNECT_MS = 4500;
10
+
11
+ var OFFLINE_CATALOG = [
12
+ { id: 1, name: 'Wireless Headphones', price: 4900, currency: 'USD', category: 'electronics', image: '🎧', rating: 4.7 },
13
+ { id: 2, name: 'Mechanical Keyboard', price: 8900, currency: 'USD', category: 'electronics', image: '⌨️', rating: 4.9 },
14
+ { id: 3, name: 'Smart Watch', price: 19900, currency: 'USD', category: 'electronics', image: '⌚', rating: 4.5 },
15
+ { id: 4, name: 'USB-C Hub', price: 3400, currency: 'USD', category: 'accessories', image: '🔌', rating: 4.3 }
16
+ ];
17
+
18
+ var useRemote = false;
19
+ var offlineStock = {};
20
+ var offlineCart = [];
21
+ var offlineOrders = [];
22
+ var offlineAudit = [];
23
+
24
+ function resetOfflineState() {
25
+ offlineCart = [];
26
+ offlineOrders = [];
27
+ offlineAudit = [];
28
+ OFFLINE_CATALOG.forEach(function (p) { offlineStock[p.id] = p.id === 1 ? 12 : p.id === 2 ? 7 : p.id === 3 ? 3 : 25; });
29
+ }
30
+
31
+ function fmtCents(c) {
32
+ return '$' + (c / 100).toFixed(2);
33
+ }
34
+
35
+ function cloneProducts() {
36
+ return OFFLINE_CATALOG.map(function (p) {
37
+ return {
38
+ id: p.id,
39
+ name: p.name,
40
+ price: p.price,
41
+ currency: p.currency,
42
+ stock: offlineStock[p.id],
43
+ category: p.category,
44
+ image: p.image,
45
+ rating: p.rating,
46
+ priceFormatted: fmtCents(p.price)
47
+ };
48
+ });
49
+ }
50
+
51
+ function localDiscovery() {
52
+ return {
53
+ wab_version: '1.2.0',
54
+ protocol: '1.0',
55
+ generated_at: new Date().toISOString(),
56
+ site: {
57
+ name: 'TechStore (Offline Demo)',
58
+ domain: 'browser-local',
59
+ description: 'In-browser WAB simulator — same JSON shape as live store; no network required.',
60
+ category: 'e-commerce',
61
+ platform: 'demo'
62
+ },
63
+ actions: [
64
+ { name: 'listProducts', description: 'List all products' },
65
+ { name: 'getProduct', description: 'Get product by id' },
66
+ { name: 'searchProducts', description: 'Search products' },
67
+ { name: 'addToCart', description: 'Add to cart' },
68
+ { name: 'viewCart', description: 'View cart' },
69
+ { name: 'removeFromCart', description: 'Remove from cart' },
70
+ { name: 'checkout', description: 'Checkout' },
71
+ { name: 'getOrderStatus', description: 'Order status' }
72
+ ],
73
+ endpoints: { execute: 'local://wab/execute', discover: 'local://.well-known/wab.json' }
74
+ };
75
+ }
76
+
77
+ function localExec(action, params) {
78
+ params = params || {};
79
+ var result;
80
+ switch (action) {
81
+ case 'listProducts': {
82
+ var list = cloneProducts();
83
+ if (params.category) list = list.filter(function (p) { return p.category === params.category; });
84
+ result = { products: list, total: list.length };
85
+ break;
86
+ }
87
+ case 'getProduct': {
88
+ var gp = cloneProducts().find(function (x) { return x.id === params.productId; });
89
+ result = gp || { error: 'Product ' + params.productId + ' not found' };
90
+ break;
91
+ }
92
+ case 'searchProducts': {
93
+ var q = (params.query || '').toLowerCase();
94
+ var matches = cloneProducts().filter(function (p) {
95
+ return p.name.toLowerCase().indexOf(q) !== -1 || p.category.indexOf(q) !== -1;
96
+ });
97
+ result = { query: params.query, results: matches, total: matches.length };
98
+ break;
99
+ }
100
+ case 'addToCart': {
101
+ var id = params.productId;
102
+ var qty = params.quantity || 1;
103
+ var prod = OFFLINE_CATALOG.find(function (x) { return x.id === id; });
104
+ if (!prod) { result = { error: 'Product ' + id + ' not found' }; break; }
105
+ if (offlineStock[id] < qty) { result = { error: 'Insufficient stock. Available: ' + offlineStock[id] }; break; }
106
+ offlineStock[id] -= qty;
107
+ var existing = offlineCart.find(function (c) { return c.productId === id; });
108
+ if (existing) existing.quantity += qty;
109
+ else offlineCart.push({ productId: id, name: prod.name, price: prod.price, quantity: qty });
110
+ var tAdd = offlineCart.reduce(function (s, c) { return s + c.price * c.quantity; }, 0);
111
+ result = { added: prod.name, quantity: qty, cartItems: offlineCart.length, cartTotal: fmtCents(tAdd) };
112
+ break;
113
+ }
114
+ case 'viewCart': {
115
+ var tView = offlineCart.reduce(function (s, c) { return s + c.price * c.quantity; }, 0);
116
+ result = {
117
+ items: offlineCart.map(function (c) {
118
+ return {
119
+ productId: c.productId,
120
+ name: c.name,
121
+ price: c.price,
122
+ quantity: c.quantity,
123
+ priceFormatted: fmtCents(c.price),
124
+ subtotal: fmtCents(c.price * c.quantity)
125
+ };
126
+ }),
127
+ itemCount: offlineCart.reduce(function (s, c) { return s + c.quantity; }, 0),
128
+ total: fmtCents(tView)
129
+ };
130
+ break;
131
+ }
132
+ case 'removeFromCart': {
133
+ var rid = params.productId;
134
+ var idx = offlineCart.findIndex(function (c) { return c.productId === rid; });
135
+ if (idx === -1) { result = { error: 'Product not in cart' }; break; }
136
+ var rem = offlineCart.splice(idx, 1)[0];
137
+ var pRem = OFFLINE_CATALOG.find(function (x) { return x.id === rem.productId; });
138
+ if (pRem) offlineStock[rid] += rem.quantity;
139
+ var tRem = offlineCart.reduce(function (s, c) { return s + c.price * c.quantity; }, 0);
140
+ result = { removed: rem.name, cartItems: offlineCart.length, cartTotal: fmtCents(tRem) };
141
+ break;
142
+ }
143
+ case 'checkout': {
144
+ if (!offlineCart.length) { result = { error: 'Cart is empty' }; break; }
145
+ if (!params.email) { result = { error: 'Email is required' }; break; }
146
+ var tCo = offlineCart.reduce(function (s, c) { return s + c.price * c.quantity; }, 0);
147
+ var itemCount = offlineCart.reduce(function (s, c) { return s + c.quantity; }, 0);
148
+ var oid = 'ORD-OFF-' + Math.random().toString(36).slice(2, 10).toUpperCase();
149
+ offlineOrders.push({
150
+ orderId: oid,
151
+ email: params.email,
152
+ items: offlineCart.map(function (c) { return Object.assign({}, c); }),
153
+ total: fmtCents(tCo),
154
+ status: 'confirmed',
155
+ createdAt: new Date().toISOString()
156
+ });
157
+ offlineCart = [];
158
+ result = { orderId: oid, status: 'confirmed', total: fmtCents(tCo), itemCount: itemCount, email: params.email };
159
+ break;
160
+ }
161
+ case 'getOrderStatus': {
162
+ var ord = offlineOrders.find(function (o) { return o.orderId === params.orderId; });
163
+ if (!ord) { result = { error: 'Order ' + params.orderId + ' not found' }; break; }
164
+ var ic = ord.items.reduce(function (s, i) { return s + i.quantity; }, 0);
165
+ result = { orderId: ord.orderId, status: ord.status, total: ord.total, itemCount: ic, createdAt: ord.createdAt };
166
+ break;
167
+ }
168
+ default:
169
+ result = { error: 'Unknown action: ' + action };
170
+ }
171
+ var success = !result.error;
172
+ offlineAudit.push({ action: action, params: params, success: success, timestamp: new Date().toISOString() });
173
+ if (offlineAudit.length > 200) offlineAudit.shift();
174
+ return { success: success, action: action, result: result, wab_version: '1.2.0', duration_ms: 0, mode: 'offline' };
175
+ }
176
+
177
+ function localGet(path) {
178
+ if (path === '/.well-known/wab.json' || path === '/agent-bridge.json' || path === '/wab/discover') {
179
+ return localDiscovery();
180
+ }
181
+ if (path === '/wab/ping') {
182
+ return { status: 'ok', wab_version: '1.2.0', protocol: '1.0', mode: 'offline-demo', timestamp: new Date().toISOString() };
183
+ }
184
+ if (path === '/wab/audit') {
185
+ return { entries: offlineAudit.slice(-50), total: offlineAudit.length, mode: 'offline-demo' };
186
+ }
187
+ return { error: 'Not found', path: path };
188
+ }
189
+
190
+ /* ── DOM refs ─────────────────────────────────── */
191
+ var netLog = document.getElementById('net-log');
192
+ var agentLog = document.getElementById('agent-log');
193
+ var reqCount = 0;
194
+ var busy = false;
195
+ var cartData = { items: [], total: '$0.00', itemCount: 0 };
196
+ var productsCache = [];
197
+
198
+ var bannerEl = document.getElementById('demo-mode-banner');
199
+ var storeFrame = document.getElementById('store-frame');
200
+ var storeLiveWrap = document.getElementById('store-live-wrap');
201
+ var storeOfflineBox = document.getElementById('store-offline-placeholder');
202
+
203
+ function setBanner(html, kind) {
204
+ if (!bannerEl) return;
205
+ bannerEl.style.display = 'block';
206
+ bannerEl.className = 'demo-banner demo-banner--' + (kind || 'info');
207
+ bannerEl.innerHTML = html;
208
+ }
209
+
210
+ function syntaxHL(json) {
211
+ if (typeof json !== 'string') json = JSON.stringify(json, null, 2);
212
+ return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (m) {
213
+ var c = 'num';
214
+ if (/^"/.test(m)) c = /:$/.test(m) ? 'key' : 'str';
215
+ else if (/true|false/.test(m)) c = 'bool';
216
+ return '<span class="' + c + '">' + m + '</span>';
217
+ });
218
+ }
219
+
220
+ function addNetEntry(method, url, reqBody, resBody, status, duration, label) {
221
+ var id = ++reqCount;
222
+ document.getElementById('req-count').textContent = reqCount + ' request' + (reqCount > 1 ? 's' : '');
223
+ var g = document.createElement('div');
224
+ g.className = 'log-group';
225
+ var sc = status >= 200 && status < 300 ? 's2' : 's4';
226
+ var short = url.replace(STORE, '');
227
+ if (label) short = '<span class="net-local">' + label + '</span> ' + short;
228
+ g.innerHTML =
229
+ '<div class="log-group-header">' +
230
+ '<span class="arrow" id="arr-' + id + '">▶</span>' +
231
+ '<span class="method ' + method + '">' + method + '</span>' +
232
+ '<span class="url">' + short + '</span>' +
233
+ '<span class="status ' + sc + '">' + status + '</span>' +
234
+ '<span class="timing">' + duration + 'ms</span>' +
235
+ '</div>' +
236
+ '<div class="log-group-body" id="nb-' + id + '">' +
237
+ (reqBody ? '<div class="log-sec"><div class="log-sec-title">Request</div><div class="log-json">' + syntaxHL(reqBody) + '</div></div>' : '') +
238
+ '<div class="log-sec"><div class="log-sec-title">Response · ' + status + '</div><div class="log-json">' + syntaxHL(resBody) + '</div></div>' +
239
+ '</div>';
240
+ g.querySelector('.log-group-header').addEventListener('click', function () {
241
+ document.getElementById('nb-' + id).classList.toggle('open');
242
+ document.getElementById('arr-' + id).classList.toggle('open');
243
+ });
244
+ netLog.appendChild(g);
245
+ netLog.scrollTop = netLog.scrollHeight;
246
+ }
247
+
248
+ function wabGet(path) {
249
+ var s = performance.now();
250
+ if (!useRemote) {
251
+ var d = localGet(path);
252
+ addNetEntry('GET', 'local://wab' + path, null, d, 200, Math.round(performance.now() - s), 'OFFLINE');
253
+ return Promise.resolve(d);
254
+ }
255
+ var url = STORE + path;
256
+ return fetch(url)
257
+ .then(function (r) { return r.json().then(function (j) { addNetEntry('GET', url, null, j, r.status, Math.round(performance.now() - s)); return j; }); })
258
+ .catch(function (err) {
259
+ addNetEntry('GET', url, null, { error: String(err.message || err) }, 0, Math.round(performance.now() - s));
260
+ throw err;
261
+ });
262
+ }
263
+
264
+ function wabExec(action, params) {
265
+ var s = performance.now();
266
+ if (!useRemote) {
267
+ var body = { action: action, params: params || {} };
268
+ var out = localExec(action, params);
269
+ addNetEntry('POST', 'local://wab/execute', body, out, 200, Math.round(performance.now() - s), 'OFFLINE');
270
+ return Promise.resolve(out);
271
+ }
272
+ var url = STORE + '/wab/execute';
273
+ var bodyR = { action: action, params: params || {} };
274
+ return fetch(url, {
275
+ method: 'POST',
276
+ headers: { 'Content-Type': 'application/json' },
277
+ body: JSON.stringify(bodyR)
278
+ })
279
+ .then(function (r) { return r.json().then(function (j) { addNetEntry('POST', url, bodyR, j, r.status, Math.round(performance.now() - s)); return j; }); })
280
+ .catch(function (err) {
281
+ addNetEntry('POST', url, bodyR, { error: String(err.message || err) }, 0, Math.round(performance.now() - s));
282
+ throw err;
283
+ });
284
+ }
285
+
286
+ function sleep(ms) {
287
+ return new Promise(function (r) { setTimeout(r, ms); });
288
+ }
289
+
290
+ function refreshStore() {
291
+ if (!useRemote) return;
292
+ try { storeFrame.contentWindow.postMessage({ source: 'wab-agent', type: 'refresh' }, '*'); } catch (e) {}
293
+ setTimeout(function () { storeFrame.src = STORE + '?t=' + Date.now(); }, 300);
294
+ }
295
+
296
+ function applyStorePanel() {
297
+ if (useRemote) {
298
+ if (storeLiveWrap) storeLiveWrap.style.display = '';
299
+ if (storeOfflineBox) storeOfflineBox.style.display = 'none';
300
+ } else {
301
+ if (storeLiveWrap) storeLiveWrap.style.display = 'none';
302
+ if (storeOfflineBox) storeOfflineBox.style.display = 'flex';
303
+ }
304
+ }
305
+
306
+ function agentMsg(text, type) {
307
+ var div = document.createElement('div');
308
+ div.className = 'agent-msg ' + (type || 'system');
309
+ div.textContent = text;
310
+ agentLog.appendChild(div);
311
+ agentLog.scrollTop = agentLog.scrollHeight;
312
+ }
313
+
314
+ function setPhase(n, s) {
315
+ var d = document.getElementById('ph-' + n);
316
+ var l = document.getElementById('pl-' + n);
317
+ if (d) d.className = 'ph-dot' + (s ? ' ' + s : '');
318
+ if (l) l.className = 'ph-lbl' + (s ? ' ' + s : '');
319
+ }
320
+
321
+ function resetPhases() {
322
+ ['discover', 'plan', 'execute', 'confirm'].forEach(function (p) { setPhase(p, ''); });
323
+ }
324
+
325
+ /* ── Shop UI ──────────────────────────────────── */
326
+ function loadProducts() {
327
+ var grid = document.getElementById('products-grid');
328
+ grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:24px;color:var(--muted)">Loading products via WAB Protocol…</div>';
329
+ return wabExec('listProducts')
330
+ .then(function (d) {
331
+ if (!d.success) {
332
+ grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:24px;color:var(--red)">Could not load products. <button type="button" class="retry-btn" id="demo-retry">Retry</button></div>';
333
+ var rb = document.getElementById('demo-retry');
334
+ if (rb) rb.addEventListener('click', function () { loadProducts(); });
335
+ return;
336
+ }
337
+ productsCache = d.result.products;
338
+ renderProducts();
339
+ })
340
+ .catch(function () {
341
+ grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:24px;color:var(--red)">Network error. <button type="button" class="retry-btn" id="demo-retry">Retry</button></div>';
342
+ var rb = document.getElementById('demo-retry');
343
+ if (rb) rb.addEventListener('click', function () { loadProducts(); });
344
+ });
345
+ }
346
+
347
+ function renderProducts() {
348
+ var grid = document.getElementById('products-grid');
349
+ grid.innerHTML = productsCache.map(function (p) {
350
+ var stars = '';
351
+ for (var i = 0; i < 5; i++) stars += i < Math.round(p.rating) ? '★' : '☆';
352
+ var sc = p.stock <= 5 ? 'stock low' : 'stock';
353
+ var st = p.stock <= 0 ? 'Out of stock' : (p.stock <= 5 ? p.stock + ' left' : p.stock + ' in stock');
354
+ return '<div class="p-card">' +
355
+ '<span class="emoji">' + p.image + '</span>' +
356
+ '<h4>' + p.name + '</h4>' +
357
+ '<div class="rating">' + stars + '</div>' +
358
+ '<div class="price">' + p.priceFormatted + '</div>' +
359
+ '<div class="' + sc + '">' + st + '</div>' +
360
+ '<button class="add" data-id="' + p.id + '" data-name="' + p.name.replace(/"/g, '&quot;') + '"' + (p.stock <= 0 ? ' disabled' : '') + '>+ Add to Cart</button>' +
361
+ '</div>';
362
+ }).join('');
363
+ grid.querySelectorAll('.add').forEach(function (btn) {
364
+ btn.addEventListener('click', function () {
365
+ shopAddToCart(parseInt(btn.dataset.id, 10), btn.dataset.name);
366
+ });
367
+ });
368
+ }
369
+
370
+ function shopAddToCart(id, name) {
371
+ wabExec('addToCart', { productId: id, quantity: 1 }).then(function (d) {
372
+ if (d.success) {
373
+ shopRefreshCart();
374
+ loadProducts();
375
+ refreshStore();
376
+ }
377
+ });
378
+ }
379
+
380
+ function shopRemoveFromCart(id) {
381
+ wabExec('removeFromCart', { productId: id }).then(function (d) {
382
+ if (d.success) {
383
+ shopRefreshCart();
384
+ loadProducts();
385
+ refreshStore();
386
+ }
387
+ });
388
+ }
389
+
390
+ function shopRefreshCart() {
391
+ return wabExec('viewCart').then(function (d) {
392
+ if (!d.success) return;
393
+ cartData = d.result;
394
+ renderCart();
395
+ });
396
+ }
397
+
398
+ function renderCart() {
399
+ var area = document.getElementById('cart-area');
400
+ var items = document.getElementById('cart-items');
401
+ var totalEl = document.getElementById('cart-total-val');
402
+ if (cartData.itemCount === 0) {
403
+ area.style.display = 'none';
404
+ return;
405
+ }
406
+ area.style.display = 'block';
407
+ items.innerHTML = cartData.items.map(function (c) {
408
+ var prod = productsCache.find(function (p) { return p.id === c.productId; }) || {};
409
+ return '<div class="cart-item">' +
410
+ '<span class="ci-emoji">' + (prod.image || '📦') + '</span>' +
411
+ '<div class="ci-info"><div class="ci-name">' + c.name + '</div><div class="ci-meta">Qty: ' + c.quantity + ' × ' + c.priceFormatted + '</div></div>' +
412
+ '<div class="ci-price">' + c.subtotal + '</div>' +
413
+ '<button class="ci-remove" data-id="' + c.productId + '">✕</button>' +
414
+ '</div>';
415
+ }).join('');
416
+ totalEl.textContent = cartData.total;
417
+ items.querySelectorAll('.ci-remove').forEach(function (btn) {
418
+ btn.addEventListener('click', function () {
419
+ shopRemoveFromCart(parseInt(btn.dataset.id, 10));
420
+ });
421
+ });
422
+ }
423
+
424
+ function checkoutSuccessCopy() {
425
+ return useRemote
426
+ ? 'Every step used HTTP to the live Railway TechStore (WAB Protocol). See Network Log →'
427
+ : 'This session used the <strong>offline WAB simulator</strong> in your browser — same JSON request/response shape as a real store; no external server required.';
428
+ }
429
+
430
+ /* ── AI Agent flows ───────────────────────────── */
431
+ function doDiscover() {
432
+ setPhase('discover', 'active');
433
+ agentMsg('Fetching discovery document…', 'think');
434
+ return wabGet('/.well-known/wab.json').then(function (doc) {
435
+ var n = doc.actions && doc.actions.length ? doc.actions.length : 0;
436
+ agentMsg('Discovered ' + n + ' actions on "' + (doc.site && doc.site.name) + '"', 'result');
437
+ setPhase('discover', 'done');
438
+ return doc;
439
+ });
440
+ }
441
+
442
+ function runFullAgent() {
443
+ if (busy) return;
444
+ busy = true;
445
+ document.getElementById('btn-full').disabled = true;
446
+ resetPhases();
447
+ agentLog.innerHTML = '';
448
+ agentMsg('Agent session started (' + (useRemote ? 'live store' : 'offline simulator') + ')', 'system');
449
+ agentMsg('Target: ' + (useRemote ? STORE : 'local://wab'), 'system');
450
+
451
+ doDiscover()
452
+ .then(function (doc) { return sleep(300).then(function () { return doc; }); })
453
+ .then(function (doc) {
454
+ setPhase('plan', 'active');
455
+ agentMsg('Planning: find cheapest in-stock product → cart → checkout → verify', 'think');
456
+ setPhase('plan', 'done');
457
+ return sleep(200).then(function () { return doc; });
458
+ })
459
+ .then(function () {
460
+ setPhase('execute', 'active');
461
+ return wabExec('listProducts');
462
+ })
463
+ .then(function (list) {
464
+ if (!list || !list.success || !list.result || !list.result.products) {
465
+ throw new Error((list && list.result && list.result.error) || 'listProducts failed');
466
+ }
467
+ var prods = list.result.products;
468
+ agentMsg('Found ' + prods.length + ' products', 'result');
469
+ var cheap = prods.reduce(function (a, b) { return a.price < b.price ? a : b; });
470
+ agentMsg('Cheapest: "' + cheap.name + '" at ' + cheap.priceFormatted, 'think');
471
+ return wabExec('addToCart', { productId: cheap.id, quantity: 1 });
472
+ })
473
+ .then(function (addD) {
474
+ agentMsg(addD.success ? 'Added. Cart: ' + addD.result.cartTotal : 'Failed: ' + addD.result.error, addD.success ? 'result' : 'error');
475
+ return wabExec('viewCart');
476
+ })
477
+ .then(function (cartD) {
478
+ agentMsg('Cart: ' + cartD.result.itemCount + ' item(s), ' + cartD.result.total, 'result');
479
+ return wabExec('checkout', { email: 'agent@webagentbridge.com' });
480
+ })
481
+ .then(function (orderD) {
482
+ if (!orderD || !orderD.result) {
483
+ agentMsg('Checkout returned no result', 'error');
484
+ setPhase('execute', 'done');
485
+ return Promise.resolve();
486
+ }
487
+ agentMsg(orderD.success ? 'Order: ' + orderD.result.orderId + ' — ' + orderD.result.total : 'Failed: ' + (orderD.result.error || orderD.result), orderD.success ? 'result' : 'error');
488
+ setPhase('execute', 'done');
489
+ if (!orderD.success) {
490
+ setPhase('confirm', 'active');
491
+ return wabGet('/wab/audit');
492
+ }
493
+ setPhase('confirm', 'active');
494
+ return wabExec('getOrderStatus', { orderId: orderD.result.orderId }).then(function (st) {
495
+ agentMsg('Status: ' + (st.result && st.result.status ? st.result.status : 'unknown'), 'result');
496
+ return wabGet('/wab/audit');
497
+ });
498
+ })
499
+ .then(function () {
500
+ agentMsg('Audit log checked', 'result');
501
+ setPhase('confirm', 'done');
502
+ agentMsg('Complete — see Network Log for all protocol calls', 'system');
503
+ refreshStore();
504
+ return loadProducts();
505
+ })
506
+ .catch(function (e) {
507
+ agentMsg('Agent error: ' + (e && e.message ? e.message : e), 'error');
508
+ })
509
+ .finally(function () {
510
+ busy = false;
511
+ document.getElementById('btn-full').disabled = false;
512
+ });
513
+ }
514
+
515
+ function handleInput(text) {
516
+ if (busy) return;
517
+ text = text.trim();
518
+ if (!text) return;
519
+ busy = true;
520
+ if (text.charAt(0) === '{') {
521
+ try {
522
+ var p = JSON.parse(text);
523
+ if (p.action) {
524
+ agentMsg('Execute: ' + p.action, 'user');
525
+ wabExec(p.action, p.params).then(function () {
526
+ if (['addToCart', 'removeFromCart', 'checkout'].indexOf(p.action) !== -1) {
527
+ refreshStore();
528
+ loadProducts();
529
+ }
530
+ busy = false;
531
+ });
532
+ return;
533
+ }
534
+ } catch (e) {}
535
+ }
536
+ agentMsg('User: ' + text, 'user');
537
+ var l = text.toLowerCase();
538
+ if (l.indexOf('discover') !== -1) {
539
+ doDiscover().finally(function () { busy = false; });
540
+ return;
541
+ }
542
+ if (l.indexOf('list') !== -1 || l.indexOf('product') !== -1) {
543
+ wabExec('listProducts').then(function (d) {
544
+ if (d.success) agentMsg(d.result.total + ' products', 'result');
545
+ busy = false;
546
+ });
547
+ return;
548
+ }
549
+ if (l.indexOf('search') !== -1 || l.indexOf('find') !== -1) {
550
+ var q = text.replace(/^.*?(search|find)\s*(for)?\s*/i, '').trim() || 'keyboard';
551
+ wabExec('searchProducts', { query: q }).then(function (d) {
552
+ if (d.success) agentMsg(d.result.total + ' results', 'result');
553
+ busy = false;
554
+ });
555
+ return;
556
+ }
557
+ if (l.indexOf('cart') !== -1) {
558
+ wabExec('viewCart').then(function (d) {
559
+ agentMsg(d.result.itemCount + ' items, ' + d.result.total, 'result');
560
+ busy = false;
561
+ });
562
+ return;
563
+ }
564
+ if (l.indexOf('buy') !== -1 || l.indexOf('purchase') !== -1 || l.indexOf('cheapest') !== -1) {
565
+ runFullAgent();
566
+ busy = false;
567
+ return;
568
+ }
569
+ if (l.indexOf('ping') !== -1) {
570
+ wabGet('/wab/ping').finally(function () { busy = false; });
571
+ return;
572
+ }
573
+ if (l.indexOf('audit') !== -1) {
574
+ wabGet('/wab/audit').finally(function () { busy = false; });
575
+ return;
576
+ }
577
+ agentMsg('Try: discover, list products, search keyboard, view cart, buy cheapest, or raw JSON', 'think');
578
+ busy = false;
579
+ }
580
+
581
+ /* ── Init: probe remote ───────────────────────── */
582
+ resetOfflineState();
583
+
584
+ function tryRemote() {
585
+ var ctrl = new AbortController();
586
+ var t = setTimeout(function () { ctrl.abort(); }, CONNECT_MS);
587
+ return fetch(STORE + '/wab/ping', { signal: ctrl.signal })
588
+ .then(function (r) {
589
+ clearTimeout(t);
590
+ if (!r.ok) throw new Error('ping ' + r.status);
591
+ return r.json();
592
+ })
593
+ .then(function () {
594
+ useRemote = true;
595
+ setBanner(
596
+ '<strong>Live demo store connected.</strong> Requests go to Railway; if it goes offline, this page switches to the offline simulator automatically on reload.',
597
+ 'ok'
598
+ );
599
+ applyStorePanel();
600
+ })
601
+ .catch(function () {
602
+ useRemote = false;
603
+ setBanner(
604
+ '<strong>Offline mode.</strong> The live TechStore on Railway did not respond in time. ' +
605
+ 'You are using the <strong>in-browser WAB simulator</strong> — same <code>POST /wab/execute</code> JSON shape, logged as <code>OFFLINE</code> in the network panel. ' +
606
+ '<a href="' + STORE + '" target="_blank" rel="noopener">Open live store</a> in a new tab when it is available.',
607
+ 'warn'
608
+ );
609
+ applyStorePanel();
610
+ });
611
+ }
612
+
613
+ document.querySelectorAll('.tab').forEach(function (t) {
614
+ t.addEventListener('click', function () {
615
+ document.querySelectorAll('.tab').forEach(function (x) { x.classList.remove('active'); });
616
+ document.querySelectorAll('.tab-body').forEach(function (x) { x.classList.remove('active'); });
617
+ this.classList.add('active');
618
+ document.getElementById('tab-' + this.dataset.tab).classList.add('active');
619
+ });
620
+ });
621
+
622
+ document.getElementById('btn-checkout').addEventListener('click', function () {
623
+ var email = document.getElementById('checkout-email').value;
624
+ if (!email) return;
625
+ var btn = this;
626
+ btn.disabled = true;
627
+ btn.textContent = 'Processing…';
628
+ wabExec('checkout', { email: email }).then(function (d) {
629
+ if (d.success) {
630
+ return wabExec('getOrderStatus', { orderId: d.result.orderId }).then(function (statusD) {
631
+ document.getElementById('shop-view').style.display = 'none';
632
+ document.getElementById('order-view').style.display = 'block';
633
+ document.getElementById('order-view').innerHTML =
634
+ '<div class="order-done">' +
635
+ '<div class="check">✅</div>' +
636
+ '<h3>Order Confirmed!</h3>' +
637
+ '<div class="oid">' + d.result.orderId + '</div>' +
638
+ '<p>Total: <strong>' + d.result.total + '</strong><br>' + d.result.itemCount + ' item(s)<br>' + d.result.email + '</p>' +
639
+ '<p style="margin-top:12px;font-size:0.75rem;color:var(--muted)">Status: ' + (statusD.success ? statusD.result.status : 'confirmed') + '</p>' +
640
+ '<p style="margin-top:14px;font-size:0.72rem;color:var(--dim);line-height:1.5">' + checkoutSuccessCopy() + '</p>' +
641
+ '<button class="reset-btn" id="btn-reset-shop">Shop Again</button>' +
642
+ '</div>';
643
+ document.getElementById('btn-reset-shop').addEventListener('click', function () {
644
+ document.getElementById('shop-view').style.display = 'block';
645
+ document.getElementById('order-view').style.display = 'none';
646
+ cartData = { items: [], total: '$0.00', itemCount: 0 };
647
+ renderCart();
648
+ if (!useRemote) resetOfflineState();
649
+ loadProducts();
650
+ refreshStore();
651
+ btn.disabled = false;
652
+ btn.textContent = 'Complete Purchase via WAB Protocol';
653
+ });
654
+ refreshStore();
655
+ });
656
+ } else {
657
+ btn.disabled = false;
658
+ btn.textContent = 'Complete Purchase via WAB Protocol';
659
+ alert(d.result.error || 'Checkout failed');
660
+ }
661
+ });
662
+ });
663
+
664
+ document.getElementById('btn-full').addEventListener('click', runFullAgent);
665
+ document.getElementById('btn-discover').addEventListener('click', function () {
666
+ if (!busy) {
667
+ busy = true;
668
+ doDiscover().finally(function () { busy = false; });
669
+ }
670
+ });
671
+ document.getElementById('btn-list').addEventListener('click', function () {
672
+ if (!busy) {
673
+ busy = true;
674
+ agentMsg('Listing…', 'think');
675
+ wabExec('listProducts').finally(function () { busy = false; });
676
+ }
677
+ });
678
+ document.getElementById('btn-search').addEventListener('click', function () {
679
+ var q = prompt('Search:');
680
+ if (q && !busy) {
681
+ busy = true;
682
+ wabExec('searchProducts', { query: q }).finally(function () { busy = false; });
683
+ }
684
+ });
685
+ document.getElementById('btn-viewcart').addEventListener('click', function () {
686
+ if (!busy) {
687
+ busy = true;
688
+ wabExec('viewCart').finally(function () { busy = false; });
689
+ }
690
+ });
691
+ document.getElementById('btn-clear').addEventListener('click', function () {
692
+ netLog.innerHTML = '';
693
+ reqCount = 0;
694
+ document.getElementById('req-count').textContent = '0 requests';
695
+ });
696
+ document.getElementById('btn-send').addEventListener('click', function () {
697
+ var i = document.getElementById('cmd-input');
698
+ handleInput(i.value);
699
+ i.value = '';
700
+ });
701
+ document.getElementById('cmd-input').addEventListener('keydown', function (e) {
702
+ if (e.key === 'Enter') {
703
+ handleInput(this.value);
704
+ this.value = '';
705
+ }
706
+ });
707
+
708
+ window.addEventListener('message', function (e) {
709
+ if (!e.data || e.data.source !== 'wab-store') return;
710
+ if (e.data.type === 'action-executed' || e.data.type === 'cart-update') {
711
+ loadProducts();
712
+ shopRefreshCart();
713
+ }
714
+ });
715
+
716
+ tryRemote().then(function () {
717
+ return loadProducts();
718
+ }).then(function () {
719
+ return shopRefreshCart();
720
+ });
721
+ })();