web-agent-bridge 3.2.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/LICENSE +84 -72
  2. package/README.ar.md +1304 -1152
  3. package/README.md +298 -1635
  4. package/bin/agent-runner.js +474 -474
  5. package/bin/cli.js +237 -138
  6. package/bin/wab-init.js +223 -0
  7. package/bin/wab.js +80 -80
  8. package/examples/azure-dns-wab.js +83 -0
  9. package/examples/bidi-agent.js +119 -119
  10. package/examples/cloudflare-wab-dns.js +121 -0
  11. package/examples/cpanel-wab-dns.js +114 -0
  12. package/examples/cross-site-agent.js +91 -91
  13. package/examples/dns-discovery-agent.js +166 -0
  14. package/examples/gcp-dns-wab.js +76 -0
  15. package/examples/governance-agent.js +169 -0
  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 -0
  19. package/examples/puppeteer-agent.js +108 -108
  20. package/examples/route53-wab-dns.js +144 -0
  21. package/examples/saas-dashboard/README.md +55 -55
  22. package/examples/safe-mode-agent.js +96 -0
  23. package/examples/shopify-hydrogen/README.md +74 -74
  24. package/examples/vision-agent.js +171 -171
  25. package/examples/wab-sign.js +74 -0
  26. package/examples/wab-verify.js +60 -0
  27. package/examples/wordpress-elementor/README.md +77 -77
  28. package/package.json +19 -6
  29. package/public/.well-known/agent-tools.json +180 -180
  30. package/public/.well-known/ai-assets.json +59 -59
  31. package/public/.well-known/security.txt +8 -0
  32. package/public/.well-known/wab.json +28 -0
  33. package/public/activate.html +368 -0
  34. package/public/adoption-metrics.html +188 -0
  35. package/public/agent-workspace.html +349 -349
  36. package/public/ai.html +198 -198
  37. package/public/api.html +413 -412
  38. package/public/azure-dns-integration.html +289 -0
  39. package/public/browser.html +486 -486
  40. package/public/cloudflare-integration.html +380 -0
  41. package/public/commander-dashboard.html +243 -243
  42. package/public/cookies.html +210 -210
  43. package/public/cpanel-integration.html +398 -0
  44. package/public/css/agent-workspace.css +1713 -1713
  45. package/public/css/premium.css +317 -317
  46. package/public/css/styles.css +1263 -1235
  47. package/public/dashboard.html +707 -706
  48. package/public/dns.html +436 -0
  49. package/public/docs.html +588 -587
  50. package/public/feed.xml +89 -89
  51. package/public/gcp-dns-integration.html +318 -0
  52. package/public/growth.html +465 -463
  53. package/public/index.html +1266 -982
  54. package/public/integrations.html +556 -0
  55. package/public/js/activate.js +145 -0
  56. package/public/js/agent-workspace.js +1740 -1740
  57. package/public/js/auth-nav.js +65 -31
  58. package/public/js/auth-redirect.js +12 -12
  59. package/public/js/cookie-consent.js +56 -56
  60. package/public/js/dns.js +438 -0
  61. package/public/js/wab-demo-page.js +721 -721
  62. package/public/js/ws-client.js +74 -74
  63. package/public/llms-full.txt +360 -360
  64. package/public/llms.txt +125 -125
  65. package/public/login.html +85 -85
  66. package/public/mesh-dashboard.html +328 -328
  67. package/public/openapi.json +669 -580
  68. package/public/phone-shield.html +281 -0
  69. package/public/plesk-integration.html +375 -0
  70. package/public/premium-dashboard.html +2489 -2489
  71. package/public/premium.html +793 -793
  72. package/public/privacy.html +297 -297
  73. package/public/provider-onboarding.html +172 -0
  74. package/public/provider-sandbox.html +134 -0
  75. package/public/providers.html +359 -0
  76. package/public/register.html +105 -105
  77. package/public/registrar-integrations.html +141 -0
  78. package/public/robots.txt +99 -87
  79. package/public/route53-integration.html +531 -0
  80. package/public/script/wab-consent.d.ts +36 -36
  81. package/public/script/wab-consent.js +104 -104
  82. package/public/script/wab-schema.js +131 -131
  83. package/public/script/wab.d.ts +108 -108
  84. package/public/script/wab.min.js +580 -580
  85. package/public/security.txt +8 -0
  86. package/public/shieldqr.html +231 -0
  87. package/public/sitemap.xml +6 -0
  88. package/public/terms.html +256 -256
  89. package/public/wab-trust.html +200 -0
  90. package/public/wab-vs-protocols.html +210 -0
  91. package/public/whitepaper.html +449 -0
  92. package/script/ai-agent-bridge.js +1754 -1754
  93. package/sdk/README.md +99 -99
  94. package/sdk/agent-mesh.js +449 -449
  95. package/sdk/auto-discovery.js +288 -0
  96. package/sdk/commander.js +262 -262
  97. package/sdk/governance.js +262 -0
  98. package/sdk/index.d.ts +464 -464
  99. package/sdk/index.js +25 -1
  100. package/sdk/multi-agent.js +318 -318
  101. package/sdk/package.json +2 -2
  102. package/sdk/safe-mode.js +221 -0
  103. package/sdk/safety-shield.js +219 -0
  104. package/sdk/schema-discovery.js +83 -83
  105. package/server/adapters/index.js +520 -520
  106. package/server/config/plans.js +367 -367
  107. package/server/config/secrets.js +102 -102
  108. package/server/control-plane/index.js +301 -301
  109. package/server/data-plane/index.js +354 -354
  110. package/server/index.js +670 -427
  111. package/server/llm/index.js +404 -404
  112. package/server/middleware/adminAuth.js +35 -35
  113. package/server/middleware/auth.js +50 -50
  114. package/server/middleware/featureGate.js +88 -88
  115. package/server/middleware/rateLimits.js +100 -100
  116. package/server/middleware/sensitiveAction.js +157 -0
  117. package/server/migrations/001_add_analytics_indexes.sql +7 -7
  118. package/server/migrations/002_premium_features.sql +418 -418
  119. package/server/migrations/003_ads_integer_cents.sql +33 -33
  120. package/server/migrations/004_agent_os.sql +158 -158
  121. package/server/migrations/005_marketplace_metering.sql +126 -126
  122. package/server/migrations/007_governance.sql +106 -0
  123. package/server/migrations/008_plans.sql +144 -0
  124. package/server/migrations/009_shieldqr.sql +30 -0
  125. package/server/migrations/010_extended_trust.sql +33 -0
  126. package/server/models/adapters/index.js +33 -33
  127. package/server/models/adapters/mysql.js +183 -183
  128. package/server/models/adapters/postgresql.js +172 -172
  129. package/server/models/adapters/sqlite.js +7 -7
  130. package/server/models/db.js +740 -681
  131. package/server/observability/failure-analysis.js +337 -337
  132. package/server/observability/index.js +394 -394
  133. package/server/protocol/capabilities.js +223 -223
  134. package/server/protocol/index.js +243 -243
  135. package/server/protocol/schema.js +584 -584
  136. package/server/registry/certification.js +271 -271
  137. package/server/registry/index.js +326 -326
  138. package/server/routes/admin-plans.js +76 -0
  139. package/server/routes/admin-premium.js +673 -671
  140. package/server/routes/admin-shieldqr.js +90 -0
  141. package/server/routes/admin-trust-monitor.js +83 -0
  142. package/server/routes/admin.js +549 -261
  143. package/server/routes/ads.js +130 -130
  144. package/server/routes/agent-workspace.js +540 -540
  145. package/server/routes/api.js +150 -150
  146. package/server/routes/auth.js +71 -71
  147. package/server/routes/billing.js +57 -45
  148. package/server/routes/commander.js +316 -316
  149. package/server/routes/demo-showcase.js +332 -332
  150. package/server/routes/demo-store.js +154 -0
  151. package/server/routes/discovery.js +2348 -417
  152. package/server/routes/gateway.js +173 -157
  153. package/server/routes/governance.js +208 -0
  154. package/server/routes/license.js +251 -240
  155. package/server/routes/mesh.js +469 -469
  156. package/server/routes/noscript.js +543 -543
  157. package/server/routes/plans.js +33 -0
  158. package/server/routes/premium-v2.js +686 -686
  159. package/server/routes/premium.js +724 -724
  160. package/server/routes/providers.js +650 -0
  161. package/server/routes/runtime.js +2148 -2147
  162. package/server/routes/shieldqr.js +88 -0
  163. package/server/routes/sovereign.js +465 -385
  164. package/server/routes/universal.js +200 -185
  165. package/server/routes/wab-api.js +850 -501
  166. package/server/runtime/container-worker.js +111 -111
  167. package/server/runtime/container.js +448 -448
  168. package/server/runtime/distributed-worker.js +362 -362
  169. package/server/runtime/event-bus.js +210 -210
  170. package/server/runtime/index.js +253 -253
  171. package/server/runtime/queue.js +599 -599
  172. package/server/runtime/replay.js +666 -666
  173. package/server/runtime/sandbox.js +266 -266
  174. package/server/runtime/scheduler.js +534 -534
  175. package/server/runtime/session-engine.js +293 -293
  176. package/server/runtime/state-manager.js +188 -188
  177. package/server/security/cross-site-redactor.js +196 -0
  178. package/server/security/dry-run.js +180 -0
  179. package/server/security/human-gate-rate-limit.js +147 -0
  180. package/server/security/human-gate-transports.js +178 -0
  181. package/server/security/human-gate.js +281 -0
  182. package/server/security/index.js +368 -368
  183. package/server/security/intent-engine.js +245 -0
  184. package/server/security/reward-guard.js +171 -0
  185. package/server/security/rollback-store.js +239 -0
  186. package/server/security/token-scope.js +404 -0
  187. package/server/security/url-policy.js +139 -0
  188. package/server/services/agent-chat.js +506 -506
  189. package/server/services/agent-learning.js +601 -575
  190. package/server/services/agent-memory.js +625 -625
  191. package/server/services/agent-mesh.js +555 -539
  192. package/server/services/agent-symphony.js +717 -717
  193. package/server/services/agent-tasks.js +1807 -1807
  194. package/server/services/api-key-engine.js +292 -261
  195. package/server/services/cluster.js +894 -894
  196. package/server/services/commander.js +738 -738
  197. package/server/services/edge-compute.js +440 -440
  198. package/server/services/email.js +233 -204
  199. package/server/services/governance.js +466 -0
  200. package/server/services/hosted-runtime.js +205 -205
  201. package/server/services/lfd.js +635 -635
  202. package/server/services/local-ai.js +389 -389
  203. package/server/services/marketplace.js +270 -270
  204. package/server/services/metering.js +182 -182
  205. package/server/services/modules/affiliate-intelligence.js +93 -93
  206. package/server/services/modules/agent-firewall.js +90 -90
  207. package/server/services/modules/bounty.js +89 -89
  208. package/server/services/modules/collective-bargaining.js +92 -92
  209. package/server/services/modules/dark-pattern.js +66 -66
  210. package/server/services/modules/gov-intelligence.js +45 -45
  211. package/server/services/modules/neural.js +55 -55
  212. package/server/services/modules/notary.js +49 -49
  213. package/server/services/modules/price-time-machine.js +86 -86
  214. package/server/services/modules/protocol.js +104 -104
  215. package/server/services/negotiation.js +439 -439
  216. package/server/services/plans.js +214 -0
  217. package/server/services/plugins.js +771 -771
  218. package/server/services/premium.js +1 -1
  219. package/server/services/price-intelligence.js +566 -566
  220. package/server/services/price-shield.js +1137 -1137
  221. package/server/services/provider-clients.js +740 -0
  222. package/server/services/reputation.js +465 -465
  223. package/server/services/search-engine.js +357 -357
  224. package/server/services/security.js +513 -513
  225. package/server/services/self-healing.js +843 -843
  226. package/server/services/shieldqr.js +322 -0
  227. package/server/services/sovereign-shield.js +542 -0
  228. package/server/services/ssl-inspector.js +42 -0
  229. package/server/services/ssl-monitor.js +167 -0
  230. package/server/services/stripe.js +205 -192
  231. package/server/services/swarm.js +788 -788
  232. package/server/services/universal-scraper.js +662 -661
  233. package/server/services/verification.js +481 -481
  234. package/server/services/vision.js +1163 -1163
  235. package/server/services/wab-crypto.js +178 -0
  236. package/server/utils/cache.js +125 -125
  237. package/server/utils/migrate.js +81 -81
  238. package/server/utils/safe-fetch.js +228 -0
  239. package/server/utils/secureFields.js +50 -50
  240. package/server/ws.js +161 -161
  241. package/templates/artisan-marketplace.yaml +104 -104
  242. package/templates/book-price-scout.yaml +98 -98
  243. package/templates/electronics-price-tracker.yaml +108 -108
  244. package/templates/flight-deal-hunter.yaml +113 -113
  245. package/templates/freelancer-direct.yaml +116 -116
  246. package/templates/grocery-price-compare.yaml +93 -93
  247. package/templates/hotel-direct-booking.yaml +113 -113
  248. package/templates/local-services.yaml +98 -98
  249. package/templates/olive-oil-tunisia.yaml +88 -88
  250. package/templates/organic-farm-fresh.yaml +101 -101
  251. package/templates/restaurant-direct.yaml +97 -97
  252. package/public/score.html +0 -263
  253. package/server/migrations/006_growth_suite.sql +0 -138
  254. package/server/routes/growth.js +0 -962
  255. package/server/services/fairness-engine.js +0 -409
  256. package/server/services/fairness.js +0 -420
@@ -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
+ })();