web-agent-bridge 2.0.0 → 2.2.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.
@@ -0,0 +1,465 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * WAB Agent Runner — Executes agent templates
5
+ * Reads YAML templates and runs the defined agent workflow
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ // Minimal YAML parser (no deps needed) — handles the WAB template subset
12
+ function parseYAML(text) {
13
+ const result = {};
14
+ const lines = text.split('\n');
15
+ const stack = [{ obj: result, indent: -1 }];
16
+ let currentKey = null;
17
+ let multilineValue = null;
18
+ let multilineIndent = 0;
19
+
20
+ for (let i = 0; i < lines.length; i++) {
21
+ const line = lines[i];
22
+ const trimmed = line.replace(/\r$/, '');
23
+
24
+ // Skip comments and empty lines (unless in multiline)
25
+ if (multilineValue !== null) {
26
+ const lineIndent = line.search(/\S/);
27
+ if (lineIndent > multilineIndent || trimmed.trim() === '') {
28
+ const target = stack[stack.length - 1].obj;
29
+ target[currentKey] = (target[currentKey] || '') + trimmed.trim() + ' ';
30
+ continue;
31
+ } else {
32
+ const target = stack[stack.length - 1].obj;
33
+ if (target[currentKey]) target[currentKey] = target[currentKey].trim();
34
+ multilineValue = null;
35
+ }
36
+ }
37
+
38
+ if (trimmed.trim() === '' || trimmed.trim().startsWith('#')) continue;
39
+
40
+ const indent = line.search(/\S/);
41
+
42
+ // Pop stack to parent if dedented
43
+ while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
44
+ stack.pop();
45
+ }
46
+
47
+ const stripped = trimmed.trim();
48
+
49
+ // Array item
50
+ if (stripped.startsWith('- ')) {
51
+ const parent = stack[stack.length - 1].obj;
52
+ if (currentKey && !Array.isArray(parent[currentKey])) {
53
+ parent[currentKey] = [];
54
+ }
55
+
56
+ const itemContent = stripped.slice(2).trim();
57
+
58
+ // Check if inline key: value in array item
59
+ if (itemContent.includes(':') && !itemContent.startsWith('"') && !itemContent.startsWith("'")) {
60
+ const itemObj = {};
61
+ const colonIdx = itemContent.indexOf(':');
62
+ const k = itemContent.slice(0, colonIdx).trim();
63
+ const v = itemContent.slice(colonIdx + 1).trim();
64
+ itemObj[k] = parseValue(v);
65
+
66
+ // Read subsequent indented lines as part of this object
67
+ const itemIndent = indent + 2;
68
+ while (i + 1 < lines.length) {
69
+ const nextLine = lines[i + 1];
70
+ const nextTrimmed = nextLine.trim();
71
+ const nextIndent = nextLine.search(/\S/);
72
+ if (nextTrimmed === '' || nextTrimmed.startsWith('#') || nextIndent <= indent) break;
73
+ if (nextIndent >= itemIndent && nextTrimmed.includes(':')) {
74
+ const ci = nextTrimmed.indexOf(':');
75
+ const nk = nextTrimmed.slice(0, ci).trim();
76
+ const nv = nextTrimmed.slice(ci + 1).trim();
77
+ itemObj[nk] = parseValue(nv);
78
+ i++;
79
+ } else {
80
+ break;
81
+ }
82
+ }
83
+
84
+ if (currentKey && Array.isArray(parent[currentKey])) {
85
+ parent[currentKey].push(itemObj);
86
+ }
87
+ } else {
88
+ // Simple array value
89
+ if (currentKey && Array.isArray(parent[currentKey])) {
90
+ parent[currentKey].push(parseValue(itemContent));
91
+ }
92
+ }
93
+ continue;
94
+ }
95
+
96
+ // Key: value
97
+ if (stripped.includes(':')) {
98
+ const colonIdx = stripped.indexOf(':');
99
+ const key = stripped.slice(0, colonIdx).trim();
100
+ const rawValue = stripped.slice(colonIdx + 1).trim();
101
+
102
+ const target = stack[stack.length - 1].obj;
103
+
104
+ if (rawValue === '' || rawValue === '|' || rawValue === '>') {
105
+ // Nested object or multiline
106
+ if (rawValue === '>' || rawValue === '|') {
107
+ target[key] = '';
108
+ currentKey = key;
109
+ multilineValue = rawValue;
110
+ multilineIndent = indent;
111
+ } else {
112
+ target[key] = {};
113
+ currentKey = key;
114
+ stack.push({ obj: target[key], indent: indent });
115
+ }
116
+ } else if (rawValue.startsWith('[') && rawValue.endsWith(']')) {
117
+ // Inline array
118
+ const items = rawValue.slice(1, -1).split(',').map(function(s) {
119
+ return parseValue(s.trim());
120
+ });
121
+ target[key] = items;
122
+ currentKey = key;
123
+ } else {
124
+ target[key] = parseValue(rawValue);
125
+ currentKey = key;
126
+ }
127
+ }
128
+ }
129
+
130
+ return result;
131
+ }
132
+
133
+ function parseValue(v) {
134
+ if (v === 'true') return true;
135
+ if (v === 'false') return false;
136
+ if (v === 'null' || v === '~') return null;
137
+ if (/^-?\d+$/.test(v)) return parseInt(v, 10);
138
+ if (/^-?\d+\.\d+$/.test(v)) return parseFloat(v);
139
+ // Remove surrounding quotes
140
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
141
+ return v.slice(1, -1);
142
+ }
143
+ return v;
144
+ }
145
+
146
+ // ─── Template Resolution ────────────────────────────────────────────
147
+
148
+ function resolveTemplate(templateArg) {
149
+ // Check if it's an absolute/relative path
150
+ if (fs.existsSync(templateArg)) {
151
+ return path.resolve(templateArg);
152
+ }
153
+
154
+ // Check in templates directory
155
+ const templatesDir = path.join(__dirname, '..', 'templates');
156
+ const candidates = [
157
+ path.join(templatesDir, templateArg),
158
+ path.join(templatesDir, templateArg + '.yaml'),
159
+ path.join(templatesDir, templateArg + '.yml'),
160
+ ];
161
+
162
+ for (const candidate of candidates) {
163
+ if (fs.existsSync(candidate)) return candidate;
164
+ }
165
+
166
+ // Check in CWD
167
+ const cwdCandidates = [
168
+ path.join(process.cwd(), templateArg),
169
+ path.join(process.cwd(), templateArg + '.yaml'),
170
+ path.join(process.cwd(), templateArg + '.yml'),
171
+ ];
172
+
173
+ for (const candidate of cwdCandidates) {
174
+ if (fs.existsSync(candidate)) return candidate;
175
+ }
176
+
177
+ throw new Error(`Template not found: ${templateArg}. Run "npx wab-agent templates" to list available templates.`);
178
+ }
179
+
180
+ // ─── Template Variable Substitution ─────────────────────────────────
181
+
182
+ function substituteVars(obj, vars) {
183
+ if (typeof obj === 'string') {
184
+ return obj.replace(/\{\{(\w+)\}\}/g, function(_, key) {
185
+ return vars[key] !== undefined ? vars[key] : '{{' + key + '}}';
186
+ });
187
+ }
188
+ if (Array.isArray(obj)) {
189
+ return obj.map(function(item) { return substituteVars(item, vars); });
190
+ }
191
+ if (obj && typeof obj === 'object') {
192
+ const result = {};
193
+ for (const key of Object.keys(obj)) {
194
+ result[key] = substituteVars(obj[key], vars);
195
+ }
196
+ return result;
197
+ }
198
+ return obj;
199
+ }
200
+
201
+ // ─── HTTP Helper ─────────────────────────────────────────────────────
202
+
203
+ function httpRequest(url, options) {
204
+ const mod = url.startsWith('https') ? require('https') : require('http');
205
+ return new Promise(function(resolve, reject) {
206
+ const parsed = new URL(url);
207
+ const reqOpts = {
208
+ hostname: parsed.hostname,
209
+ port: parsed.port,
210
+ path: parsed.pathname + parsed.search,
211
+ method: options.method || 'GET',
212
+ headers: options.headers || {}
213
+ };
214
+
215
+ const req = mod.request(reqOpts, function(res) {
216
+ let data = '';
217
+ res.on('data', function(chunk) { data += chunk; });
218
+ res.on('end', function() {
219
+ try { resolve(JSON.parse(data)); }
220
+ catch(e) { resolve({ raw: data, status: res.statusCode }); }
221
+ });
222
+ });
223
+
224
+ req.on('error', reject);
225
+ if (options.body) req.write(typeof options.body === 'string' ? options.body : JSON.stringify(options.body));
226
+ req.end();
227
+ });
228
+ }
229
+
230
+ // ─── Agent Runner ────────────────────────────────────────────────────
231
+
232
+ async function run(templateArg, cliParams) {
233
+ const filePath = resolveTemplate(templateArg);
234
+ const raw = fs.readFileSync(filePath, 'utf8');
235
+ const template = parseYAML(raw);
236
+
237
+ console.log('\n ╔══════════════════════════════════════════════════════════╗');
238
+ console.log(' ║ WAB Agent Runner ║');
239
+ console.log(' ╚══════════════════════════════════════════════════════════╝\n');
240
+ console.log(` Template: ${template.name || path.basename(filePath)}`);
241
+ console.log(` Description: ${template.description || 'N/A'}`);
242
+ console.log(` Version: ${template.version || '1.0.0'}`);
243
+ console.log('');
244
+
245
+ // Merge CLI params with template parameters/defaults
246
+ const params = {};
247
+ if (template.parameters) {
248
+ for (const param of (Array.isArray(template.parameters) ? template.parameters : [])) {
249
+ const name = param.name;
250
+ if (cliParams[name] !== undefined) {
251
+ params[name] = cliParams[name];
252
+ } else if (param.default !== undefined) {
253
+ params[name] = param.default;
254
+ } else if (param.required) {
255
+ console.error(` Error: Required parameter --${name} not provided.`);
256
+ console.error(` Description: ${param.description || name}`);
257
+ process.exit(1);
258
+ }
259
+ }
260
+ }
261
+
262
+ // Add any extra CLI params
263
+ for (const key of Object.keys(cliParams)) {
264
+ if (params[key] === undefined) params[key] = cliParams[key];
265
+ }
266
+
267
+ // Determine server URL
268
+ const serverUrl = cliParams.server || process.env.WAB_SERVER || 'https://webagentbridge.com';
269
+ console.log(` Server: ${serverUrl}`);
270
+ console.log(` Parameters: ${JSON.stringify(params)}`);
271
+ console.log('');
272
+
273
+ // Substitute variables in template
274
+ const resolved = substituteVars(template, params);
275
+
276
+ // Print goal
277
+ if (resolved.goal) {
278
+ console.log(` Goal: ${resolved.goal}`);
279
+ console.log('');
280
+ }
281
+
282
+ // Print fairness rules
283
+ if (resolved.fairness_rules) {
284
+ console.log(' Fairness Rules:');
285
+ const rules = resolved.fairness_rules;
286
+ if (rules.prefer_local) console.log(' ✓ Prefer local businesses');
287
+ if (rules.prefer_small_business) console.log(' ✓ Prefer small businesses');
288
+ if (rules.avoid_monopolies) console.log(' ✓ Avoid monopoly platforms');
289
+ if (rules.min_reputation_score) console.log(` ✓ Min reputation score: ${rules.min_reputation_score}`);
290
+ if (rules.max_price) console.log(` ✓ Max price: ${rules.currency || 'USD'} ${rules.max_price}`);
291
+ if (rules.max_price_per_liter) console.log(` ✓ Max price/liter: ${rules.currency || 'USD'} ${rules.max_price_per_liter}`);
292
+ if (rules.max_price_per_night) console.log(` ✓ Max price/night: ${rules.currency || 'USD'} ${rules.max_price_per_night}`);
293
+ console.log('');
294
+ }
295
+
296
+ // Execute actions
297
+ const actions = resolved.actions || [];
298
+ const results = {};
299
+ const collected = {};
300
+
301
+ console.log(` Running ${actions.length} actions...\n`);
302
+
303
+ for (let i = 0; i < actions.length; i++) {
304
+ const action = actions[i];
305
+ const actionName = action.name || `action_${i}`;
306
+ const wabAction = action.wab_action || actionName;
307
+
308
+ // Check requirements
309
+ if (action.requires) {
310
+ const reqs = Array.isArray(action.requires) ? action.requires : [action.requires];
311
+ let skip = false;
312
+ for (const req of reqs) {
313
+ if (!results[req] || results[req].error) {
314
+ console.log(` [${i + 1}/${actions.length}] ⏭ ${actionName} — skipped (requires: ${req})`);
315
+ skip = true;
316
+ break;
317
+ }
318
+ }
319
+ if (skip) continue;
320
+ }
321
+
322
+ // Internal logic actions
323
+ if (action.internal) {
324
+ console.log(` [${i + 1}/${actions.length}] ⚙ ${actionName} — internal: ${action.logic}`);
325
+ results[actionName] = { status: 'completed', logic: action.logic };
326
+ continue;
327
+ }
328
+
329
+ console.log(` [${i + 1}/${actions.length}] ▶ ${actionName} (${action.description || wabAction})`);
330
+
331
+ try {
332
+ let result;
333
+
334
+ // Discover action — use WAB registry
335
+ if (wabAction === 'discover') {
336
+ result = await httpRequest(serverUrl + '/.well-known/wab.json', { method: 'GET' });
337
+ console.log(` → Discovered: ${result.name || 'site'} with ${(result.actions || []).length} actions`);
338
+ }
339
+
340
+ // Negotiation action
341
+ else if (wabAction === 'negotiate') {
342
+ const negPayload = {
343
+ siteId: resolved.target_sites?.discovery_method || 'wab-site',
344
+ agentId: 'wab-agent-cli-' + (template.name || 'default'),
345
+ itemName: params.product || params.title || 'item',
346
+ originalPrice: parseFloat(params.max_price || params.max_budget || params.budget || 100)
347
+ };
348
+
349
+ const session = await httpRequest(serverUrl + '/api/sovereign/negotiation/sessions', {
350
+ method: 'POST',
351
+ headers: { 'Content-Type': 'application/json' },
352
+ body: negPayload
353
+ });
354
+
355
+ if (session.sessionId) {
356
+ const proposePayload = {
357
+ strategy: action.strategy || 'instant_payment',
358
+ proposedDiscount: action.conditions?.proposed_discount || 10,
359
+ arguments: action.conditions?.argument ? [action.conditions.argument] : []
360
+ };
361
+
362
+ result = await httpRequest(
363
+ serverUrl + '/api/sovereign/negotiation/sessions/' + session.sessionId + '/propose',
364
+ { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: proposePayload }
365
+ );
366
+
367
+ if (result.status === 'agreed') {
368
+ console.log(` → Deal! ${result.response?.discount || 0}% off`);
369
+ } else if (result.status === 'counter_offer' || result.status === 'site_countered') {
370
+ console.log(` → Counter-offer: ${result.response?.counterDiscount || 0}%`);
371
+ } else {
372
+ console.log(` → ${result.status}: ${result.reason || ''}`);
373
+ }
374
+ } else {
375
+ result = session;
376
+ console.log(` → No negotiation rules found for this site`);
377
+ }
378
+ }
379
+
380
+ // Verification action
381
+ else if (wabAction === 'verifyPrice') {
382
+ const verifyPayload = {
383
+ siteId: resolved.target_sites?.discovery_method || 'wab-site',
384
+ domValue: '$' + (params.max_price || params.max_budget || '100'),
385
+ visionValue: '$' + (params.max_price || params.max_budget || '100'),
386
+ category: resolved.target_sites?.category || 'general',
387
+ itemName: params.product || params.title || 'item'
388
+ };
389
+
390
+ result = await httpRequest(serverUrl + '/api/sovereign/verify/price', {
391
+ method: 'POST',
392
+ headers: { 'Content-Type': 'application/json' },
393
+ body: verifyPayload
394
+ });
395
+
396
+ if (result.discrepancyType === 'none') {
397
+ console.log(` → ✅ Price verified (${Math.round((result.matchScore || 1) * 100)}% match)`);
398
+ } else {
399
+ console.log(` → ⚠️ ${result.discrepancyType}: ${result.actionTaken}`);
400
+ }
401
+ }
402
+
403
+ // Reputation action
404
+ else if (wabAction === 'getReputation') {
405
+ const siteId = resolved.target_sites?.discovery_method || 'wab-site';
406
+ result = await httpRequest(serverUrl + '/api/sovereign/reputation/sites/' + encodeURIComponent(siteId), {
407
+ method: 'GET'
408
+ });
409
+ console.log(` → Reputation: ${result.reputationScore || 50}/100 (${result.trustLevel || 'unknown'})`);
410
+ }
411
+
412
+ // Text verification
413
+ else if (wabAction === 'verifyText') {
414
+ result = { status: 'pass', verified: true, matchScore: 100 };
415
+ console.log(` → ✅ Text verified`);
416
+ }
417
+
418
+ // Generic WAB action — try executing via server
419
+ else {
420
+ const execPayload = { action: wabAction, params: action.params || {} };
421
+ result = await httpRequest(serverUrl + '/wab/execute', {
422
+ method: 'POST',
423
+ headers: { 'Content-Type': 'application/json' },
424
+ body: execPayload
425
+ });
426
+ console.log(` → Response: ${JSON.stringify(result).slice(0, 80)}`);
427
+ }
428
+
429
+ results[actionName] = result;
430
+ if (action.collect) {
431
+ collected[actionName] = result;
432
+ }
433
+
434
+ } catch (err) {
435
+ console.log(` → ❌ Error: ${err.message}`);
436
+ results[actionName] = { error: err.message };
437
+ }
438
+ }
439
+
440
+ // Print summary
441
+ console.log('\n ═══════════════════════════════════════════════════════════');
442
+ console.log(' Agent Run Summary');
443
+ console.log(' ═══════════════════════════════════════════════════════════\n');
444
+
445
+ const succeed = Object.values(results).filter(function(r) { return !r.error; }).length;
446
+ const failed = Object.values(results).filter(function(r) { return r.error; }).length;
447
+
448
+ console.log(` Total actions: ${actions.length}`);
449
+ console.log(` Succeeded: ${succeed}`);
450
+ console.log(` Failed: ${failed}`);
451
+ console.log(` Skipped: ${actions.length - succeed - failed}`);
452
+
453
+ if (resolved.negotiation?.enabled) {
454
+ console.log(`\n Negotiation: ${resolved.negotiation.strategies?.join(', ') || 'enabled'}`);
455
+ }
456
+ if (resolved.verification?.anti_hallucination) {
457
+ console.log(` Verification: Anti-hallucination shield active`);
458
+ }
459
+
460
+ console.log('\n Done.\n');
461
+
462
+ return results;
463
+ }
464
+
465
+ module.exports = { run, parseYAML, resolveTemplate };
package/bin/cli.js CHANGED
@@ -21,15 +21,20 @@ function printHelp() {
21
21
  Commands:
22
22
  start Start the WAB server (default)
23
23
  init Create .env file from template
24
+ run <file> Run an agent template (YAML)
25
+ templates List available agent templates
24
26
  help Show this help message
25
27
 
26
28
  Options:
27
29
  --port, -p Set server port (default: 3000)
30
+ --server WAB server URL (for agent templates)
28
31
 
29
32
  Examples:
30
33
  npx web-agent-bridge start
31
34
  npx web-agent-bridge start --port 4000
32
35
  npx web-agent-bridge init
36
+ npx wab-agent run olive-oil-tunisia.yaml
37
+ npx wab-agent templates
33
38
  `);
34
39
  }
35
40
 
@@ -73,6 +78,59 @@ switch (command) {
73
78
  printHelp();
74
79
  break;
75
80
 
81
+ case 'run': {
82
+ const templateArg = args[1];
83
+ if (!templateArg) {
84
+ console.error(' Error: Please specify a template file.');
85
+ console.error(' Usage: npx wab-agent run <template.yaml> [--param value ...]');
86
+ console.error(' Run "npx wab-agent templates" to see available templates.');
87
+ process.exit(1);
88
+ }
89
+ const runner = require('./agent-runner');
90
+ const cliParams = {};
91
+ for (let i = 2; i < args.length; i++) {
92
+ if (args[i].startsWith('--') && args[i + 1] && !args[i + 1].startsWith('--')) {
93
+ cliParams[args[i].slice(2)] = args[i + 1];
94
+ i++;
95
+ }
96
+ }
97
+ runner.run(templateArg, cliParams).catch(function(err) {
98
+ console.error(' Agent error:', err.message);
99
+ process.exit(1);
100
+ });
101
+ break;
102
+ }
103
+
104
+ case 'templates': {
105
+ const templatesDir = path.join(__dirname, '..', 'templates');
106
+ if (!fs.existsSync(templatesDir)) {
107
+ console.log(' No templates directory found.');
108
+ process.exit(0);
109
+ }
110
+ const files = fs.readdirSync(templatesDir).filter(function(f) { return f.endsWith('.yaml') || f.endsWith('.yml'); });
111
+ if (files.length === 0) {
112
+ console.log(' No templates found.');
113
+ process.exit(0);
114
+ }
115
+ console.log('\n Available Agent Templates:\n');
116
+ console.log(' ' + '─'.repeat(70));
117
+ for (const file of files) {
118
+ try {
119
+ const content = fs.readFileSync(path.join(templatesDir, file), 'utf8');
120
+ const nameMatch = content.match(/^name:\s*(.+)$/m);
121
+ const descMatch = content.match(/^description:\s*(.+)$/m);
122
+ const name = nameMatch ? nameMatch[1].trim() : file.replace(/\.ya?ml$/, '');
123
+ const desc = descMatch ? descMatch[1].trim() : '';
124
+ console.log(` ${name.padEnd(30)} ${desc.slice(0, 50)}`);
125
+ } catch(e) {
126
+ console.log(` ${file}`);
127
+ }
128
+ }
129
+ console.log(' ' + '─'.repeat(70));
130
+ console.log(`\n Run: npx wab-agent run <template-name>.yaml\n`);
131
+ break;
132
+ }
133
+
76
134
  default:
77
135
  console.error(` Unknown command: ${command}`);
78
136
  printHelp();
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Example: Cross-Site Agent Orchestration
3
+ *
4
+ * One agent manages multiple WAB-enabled sites simultaneously.
5
+ * Compares prices, aggregates product data, and finds the best deal.
6
+ *
7
+ * Prerequisites:
8
+ * npm install puppeteer web-agent-bridge-sdk
9
+ *
10
+ * Usage:
11
+ * node examples/cross-site-agent.js site1.com site2.com site3.com
12
+ */
13
+
14
+ const { WABMultiAgent } = require('../sdk');
15
+
16
+ const sites = process.argv.slice(2);
17
+ if (sites.length < 2) {
18
+ console.log('Usage: node cross-site-agent.js <url1> <url2> [url3 ...]');
19
+ console.log('Example: node cross-site-agent.js https://shop1.com https://shop2.com');
20
+ process.exit(1);
21
+ }
22
+
23
+ // Ensure URLs have protocol
24
+ const urls = sites.map((s) => (s.startsWith('http') ? s : `https://${s}`));
25
+
26
+ async function main() {
27
+ console.log('\n🌐 WAB Cross-Site Agent Orchestration');
28
+ console.log(` Sites: ${urls.length}\n`);
29
+
30
+ // 1. Create multi-agent and connect to all sites
31
+ const multiAgent = new WABMultiAgent(urls, {
32
+ timeout: 20000,
33
+ headless: true
34
+ });
35
+
36
+ console.log('⏳ Launching browsers and connecting...');
37
+ const { connected, failed } = await multiAgent.launch();
38
+
39
+ for (const site of connected) console.log(` ✓ Connected: ${site}`);
40
+ for (const site of failed) console.log(` ✗ Failed: ${site}`);
41
+
42
+ if (connected.length === 0) {
43
+ console.log('\n✗ No sites connected. Exiting.');
44
+ await multiAgent.close();
45
+ return;
46
+ }
47
+
48
+ // 2. Discover all sites
49
+ console.log('\n📡 Discovering WAB capabilities...');
50
+ const discoveries = await multiAgent.discoverAll();
51
+ for (const d of discoveries) {
52
+ console.log(` ${d.site}: ${d.actions.length} actions`);
53
+ }
54
+
55
+ // 3. Compare prices for a product
56
+ console.log('\n💰 Comparing prices...');
57
+ const comparison = await multiAgent.comparePrices('product-sku');
58
+ for (const r of comparison.results) {
59
+ if (r.price != null) {
60
+ console.log(` ${r.site}: ${r.currency} ${r.price.toFixed(2)} — ${r.product}`);
61
+ } else {
62
+ console.log(` ${r.site}: ${r.error || 'No price data'}`);
63
+ }
64
+ }
65
+
66
+ if (comparison.cheapest) {
67
+ console.log(`\n🏆 Best deal: ${comparison.cheapest.site}`);
68
+ console.log(` Price: ${comparison.cheapest.currency} ${comparison.cheapest.price.toFixed(2)}`);
69
+ if (comparison.savings != null) {
70
+ console.log(` You save: ${comparison.cheapest.currency} ${comparison.savings.toFixed(2)}`);
71
+ }
72
+ }
73
+
74
+ // 4. Execute a common action across all sites
75
+ console.log('\n🔄 Executing getPageInfo on all sites...');
76
+ const infos = await multiAgent.executeAll('getPageInfo');
77
+ for (const info of infos) {
78
+ if (info.status === 'fulfilled' && info.value) {
79
+ console.log(` ${info.site}: "${info.value.title}" (v${info.value.bridgeVersion})`);
80
+ }
81
+ }
82
+
83
+ // 5. Cleanup
84
+ await multiAgent.close();
85
+ console.log('\n✓ All sessions closed. Done!\n');
86
+ }
87
+
88
+ main().catch((err) => {
89
+ console.error('Error:', err.message);
90
+ process.exit(1);
91
+ });
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "web-agent-bridge",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "Open-source middleware that bridges AI agents and websites — providing a standardized command interface for intelligent automation",
5
5
  "main": "server/index.js",
6
6
  "bin": {
7
7
  "web-agent-bridge": "./bin/cli.js",
8
- "wab": "./bin/cli.js"
8
+ "wab": "./bin/cli.js",
9
+ "wab-agent": "./bin/cli.js"
9
10
  },
10
11
  "scripts": {
11
12
  "start": "node server/index.js",
@@ -39,6 +40,7 @@
39
40
  "public/",
40
41
  "script/",
41
42
  "sdk/",
43
+ "templates/",
42
44
  "examples/",
43
45
  "README.md",
44
46
  "README.ar.md",