web-agent-bridge 2.5.0 → 2.7.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,205 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Hosted Runtime Service
5
+ *
6
+ * Cloud execution abstraction for running agents without local infrastructure.
7
+ * Pay-as-you-go model with auto-scaling, resource tracking, and multi-region support.
8
+ */
9
+
10
+ const crypto = require('crypto');
11
+ const { bus } = require('../runtime/event-bus');
12
+ const metering = require('./metering');
13
+
14
+ class HostedRuntime {
15
+ constructor() {
16
+ this._instances = new Map(); // instanceId → RuntimeInstance
17
+ this._executions = new Map(); // executionId → Execution
18
+ this._maxInstances = 1000;
19
+ }
20
+
21
+ /**
22
+ * Launch a hosted runtime instance for an agent
23
+ */
24
+ launch(config) {
25
+ if (!config.agentId) throw new Error('agentId required');
26
+
27
+ const instanceId = `hrt_${crypto.randomBytes(8).toString('hex')}`;
28
+ const instance = {
29
+ id: instanceId,
30
+ agentId: config.agentId,
31
+ tier: config.tier || 'starter',
32
+ region: config.region || 'auto',
33
+ resources: {
34
+ cpu: config.cpu || '0.5', // vCPU
35
+ memory: config.memory || '512', // MB
36
+ timeout: config.timeout || 300000, // 5 min default
37
+ },
38
+ status: 'starting',
39
+ startedAt: Date.now(),
40
+ lastActivity: Date.now(),
41
+ executionCount: 0,
42
+ computeMinutes: 0,
43
+ errors: 0,
44
+ };
45
+
46
+ this._instances.set(instanceId, instance);
47
+
48
+ // Simulate startup (in real deployment, this would provision container/lambda)
49
+ instance.status = 'running';
50
+ bus.emit('hosted.launched', { instanceId, agentId: config.agentId, region: instance.region });
51
+
52
+ return instance;
53
+ }
54
+
55
+ /**
56
+ * Execute a task on a hosted instance
57
+ */
58
+ async execute(instanceId, task) {
59
+ const instance = this._instances.get(instanceId);
60
+ if (!instance) throw new Error('Instance not found');
61
+ if (instance.status !== 'running') throw new Error(`Instance not running (status: ${instance.status})`);
62
+
63
+ const executionId = `hexe_${crypto.randomBytes(8).toString('hex')}`;
64
+ const execution = {
65
+ id: executionId,
66
+ instanceId,
67
+ agentId: instance.agentId,
68
+ task: {
69
+ type: task.type,
70
+ action: task.action,
71
+ params: task.params || {},
72
+ },
73
+ status: 'running',
74
+ startedAt: Date.now(),
75
+ completedAt: null,
76
+ result: null,
77
+ error: null,
78
+ computeMs: 0,
79
+ resources: {
80
+ cpuUsage: 0,
81
+ memoryUsage: 0,
82
+ networkCalls: 0,
83
+ },
84
+ };
85
+
86
+ this._executions.set(executionId, execution);
87
+ instance.executionCount++;
88
+ instance.lastActivity = Date.now();
89
+
90
+ // Record metering
91
+ metering.record(instance.agentId, 'executionsPerDay', instance.tier, 1);
92
+
93
+ bus.emit('hosted.execution.started', { executionId, instanceId, type: task.type });
94
+
95
+ // Return execution handle (actual execution is async in real deployment)
96
+ return execution;
97
+ }
98
+
99
+ /**
100
+ * Complete an execution (called by worker after task finishes)
101
+ */
102
+ completeExecution(executionId, result, error = null) {
103
+ const execution = this._executions.get(executionId);
104
+ if (!execution) return null;
105
+
106
+ execution.status = error ? 'failed' : 'completed';
107
+ execution.completedAt = Date.now();
108
+ execution.result = result;
109
+ execution.error = error ? { message: error.message || String(error) } : null;
110
+ execution.computeMs = execution.completedAt - execution.startedAt;
111
+
112
+ // Update instance stats
113
+ const instance = this._instances.get(execution.instanceId);
114
+ if (instance) {
115
+ const minutes = execution.computeMs / 60000;
116
+ instance.computeMinutes += minutes;
117
+ metering.record(instance.agentId, 'computeMinutesPerDay', instance.tier, minutes);
118
+ if (error) instance.errors++;
119
+ }
120
+
121
+ bus.emit('hosted.execution.completed', {
122
+ executionId, instanceId: execution.instanceId,
123
+ status: execution.status, computeMs: execution.computeMs,
124
+ });
125
+
126
+ return execution;
127
+ }
128
+
129
+ /**
130
+ * Stop a hosted instance
131
+ */
132
+ stop(instanceId) {
133
+ const instance = this._instances.get(instanceId);
134
+ if (!instance) return false;
135
+ instance.status = 'stopped';
136
+ instance.stoppedAt = Date.now();
137
+ bus.emit('hosted.stopped', { instanceId, agentId: instance.agentId });
138
+ return true;
139
+ }
140
+
141
+ /**
142
+ * Get instance
143
+ */
144
+ getInstance(instanceId) {
145
+ return this._instances.get(instanceId) || null;
146
+ }
147
+
148
+ /**
149
+ * List instances
150
+ */
151
+ listInstances(filters = {}, limit = 50) {
152
+ let instances = Array.from(this._instances.values());
153
+ if (filters.agentId) instances = instances.filter(i => i.agentId === filters.agentId);
154
+ if (filters.status) instances = instances.filter(i => i.status === filters.status);
155
+ if (filters.region) instances = instances.filter(i => i.region === filters.region);
156
+ return instances.slice(0, limit);
157
+ }
158
+
159
+ /**
160
+ * Get execution
161
+ */
162
+ getExecution(executionId) {
163
+ return this._executions.get(executionId) || null;
164
+ }
165
+
166
+ /**
167
+ * List executions for an instance
168
+ */
169
+ listExecutions(instanceId, limit = 50) {
170
+ return Array.from(this._executions.values())
171
+ .filter(e => e.instanceId === instanceId)
172
+ .sort((a, b) => b.startedAt - a.startedAt)
173
+ .slice(0, limit);
174
+ }
175
+
176
+ /**
177
+ * Get compute usage for an agent
178
+ */
179
+ getComputeUsage(agentId) {
180
+ const instances = Array.from(this._instances.values())
181
+ .filter(i => i.agentId === agentId);
182
+
183
+ return {
184
+ activeInstances: instances.filter(i => i.status === 'running').length,
185
+ totalExecutions: instances.reduce((sum, i) => sum + i.executionCount, 0),
186
+ totalComputeMinutes: Math.round(instances.reduce((sum, i) => sum + i.computeMinutes, 0) * 100) / 100,
187
+ totalErrors: instances.reduce((sum, i) => sum + i.errors, 0),
188
+ };
189
+ }
190
+
191
+ getStats() {
192
+ const instances = Array.from(this._instances.values());
193
+ return {
194
+ totalInstances: instances.length,
195
+ running: instances.filter(i => i.status === 'running').length,
196
+ stopped: instances.filter(i => i.status === 'stopped').length,
197
+ totalExecutions: this._executions.size,
198
+ totalComputeMinutes: Math.round(instances.reduce((sum, i) => sum + i.computeMinutes, 0) * 100) / 100,
199
+ };
200
+ }
201
+ }
202
+
203
+ const hostedRuntime = new HostedRuntime();
204
+
205
+ module.exports = { HostedRuntime, hostedRuntime };
@@ -0,0 +1,270 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Marketplace Engine
5
+ *
6
+ * Tools & integrations marketplace with publishing, discovery, purchasing,
7
+ * and revenue sharing (15% platform commission).
8
+ */
9
+
10
+ const crypto = require('crypto');
11
+ const { bus } = require('../runtime/event-bus');
12
+ const { MARKETPLACE } = require('../config/plans');
13
+
14
+ class MarketplaceEngine {
15
+ constructor() {
16
+ this._listings = new Map(); // listingId → Listing
17
+ this._purchases = new Map(); // purchaseId → Purchase
18
+ this._reviews = new Map(); // listingId → Review[]
19
+ this._earnings = new Map(); // sellerId → EarningsRecord
20
+ }
21
+
22
+ /**
23
+ * Publish a listing to the marketplace
24
+ */
25
+ publish(listing) {
26
+ if (!listing.name || !listing.type || !listing.sellerId) {
27
+ throw new Error('name, type, and sellerId are required');
28
+ }
29
+ if (!MARKETPLACE.categories.includes(listing.category || 'automation')) {
30
+ throw new Error(`Invalid category. Must be one of: ${MARKETPLACE.categories.join(', ')}`);
31
+ }
32
+ if (listing.price !== undefined && listing.price !== 0) {
33
+ if (listing.price < MARKETPLACE.minPrice || listing.price > MARKETPLACE.maxPrice) {
34
+ throw new Error(`Price must be between $${MARKETPLACE.minPrice} and $${MARKETPLACE.maxPrice}`);
35
+ }
36
+ }
37
+
38
+ const id = `mkt_${crypto.randomBytes(8).toString('hex')}`;
39
+ const entry = {
40
+ id,
41
+ name: listing.name,
42
+ description: listing.description || '',
43
+ type: listing.type, // 'tool', 'template', 'adapter', 'plugin', 'integration'
44
+ category: listing.category || 'automation',
45
+ sellerId: listing.sellerId,
46
+ sellerName: listing.sellerName || 'Anonymous',
47
+ price: listing.price || 0, // 0 = free
48
+ currency: 'usd',
49
+ version: listing.version || '1.0.0',
50
+ tags: listing.tags || [],
51
+ icon: listing.icon || null,
52
+ readme: listing.readme || '',
53
+ installCommand: listing.installCommand || null,
54
+ configSchema: listing.configSchema || null,
55
+ entryPoint: listing.entryPoint || null,
56
+
57
+ // Stats
58
+ installs: 0,
59
+ revenue: 0,
60
+ rating: 0,
61
+ reviewCount: 0,
62
+
63
+ // Status
64
+ status: 'pending_review', // pending_review → approved → published | rejected
65
+ publishedAt: null,
66
+ createdAt: Date.now(),
67
+ updatedAt: Date.now(),
68
+ };
69
+
70
+ this._listings.set(id, entry);
71
+ this._reviews.set(id, []);
72
+ bus.emit('marketplace.listed', { id, name: entry.name, type: entry.type, price: entry.price });
73
+ return entry;
74
+ }
75
+
76
+ /**
77
+ * Approve a listing (admin action)
78
+ */
79
+ approve(listingId) {
80
+ const listing = this._listings.get(listingId);
81
+ if (!listing) throw new Error('Listing not found');
82
+ listing.status = 'published';
83
+ listing.publishedAt = Date.now();
84
+ listing.updatedAt = Date.now();
85
+ bus.emit('marketplace.approved', { id: listingId, name: listing.name });
86
+ return listing;
87
+ }
88
+
89
+ /**
90
+ * Reject a listing (admin action)
91
+ */
92
+ reject(listingId, reason) {
93
+ const listing = this._listings.get(listingId);
94
+ if (!listing) throw new Error('Listing not found');
95
+ listing.status = 'rejected';
96
+ listing.rejectionReason = reason;
97
+ listing.updatedAt = Date.now();
98
+ return listing;
99
+ }
100
+
101
+ /**
102
+ * Purchase/install a listing
103
+ */
104
+ purchase(listingId, buyerId) {
105
+ const listing = this._listings.get(listingId);
106
+ if (!listing) throw new Error('Listing not found');
107
+ if (listing.status !== 'published') throw new Error('Listing not available');
108
+
109
+ const purchaseId = `pur_${crypto.randomBytes(8).toString('hex')}`;
110
+ const commission = listing.price * MARKETPLACE.commission;
111
+ const sellerEarning = listing.price - commission;
112
+
113
+ const purchase = {
114
+ id: purchaseId,
115
+ listingId,
116
+ listingName: listing.name,
117
+ buyerId,
118
+ sellerId: listing.sellerId,
119
+ price: listing.price,
120
+ commission,
121
+ sellerEarning,
122
+ currency: 'usd',
123
+ status: listing.price === 0 ? 'completed' : 'pending_payment',
124
+ createdAt: Date.now(),
125
+ };
126
+
127
+ this._purchases.set(purchaseId, purchase);
128
+ listing.installs++;
129
+
130
+ // Track earnings
131
+ if (sellerEarning > 0) {
132
+ const earnings = this._earnings.get(listing.sellerId) || { total: 0, pending: 0, paid: 0 };
133
+ earnings.total += sellerEarning;
134
+ earnings.pending += sellerEarning;
135
+ this._earnings.set(listing.sellerId, earnings);
136
+ }
137
+
138
+ listing.revenue += listing.price;
139
+ bus.emit('marketplace.purchased', { purchaseId, listingId, buyerId, price: listing.price });
140
+ return purchase;
141
+ }
142
+
143
+ /**
144
+ * Complete payment for a purchase
145
+ */
146
+ completePayment(purchaseId) {
147
+ const purchase = this._purchases.get(purchaseId);
148
+ if (!purchase) throw new Error('Purchase not found');
149
+ purchase.status = 'completed';
150
+ purchase.completedAt = Date.now();
151
+ return purchase;
152
+ }
153
+
154
+ /**
155
+ * Add a review
156
+ */
157
+ addReview(listingId, review) {
158
+ const listing = this._listings.get(listingId);
159
+ if (!listing) throw new Error('Listing not found');
160
+
161
+ const reviews = this._reviews.get(listingId) || [];
162
+ const entry = {
163
+ id: `rev_${crypto.randomBytes(6).toString('hex')}`,
164
+ userId: review.userId,
165
+ rating: Math.max(1, Math.min(5, review.rating)),
166
+ comment: review.comment || '',
167
+ createdAt: Date.now(),
168
+ };
169
+ reviews.push(entry);
170
+ this._reviews.set(listingId, reviews);
171
+
172
+ // Update average rating
173
+ listing.reviewCount = reviews.length;
174
+ listing.rating = reviews.reduce((sum, r) => sum + r.rating, 0) / reviews.length;
175
+ listing.rating = Math.round(listing.rating * 10) / 10;
176
+
177
+ return entry;
178
+ }
179
+
180
+ /**
181
+ * Search listings
182
+ */
183
+ search(filters = {}, limit = 50) {
184
+ let results = Array.from(this._listings.values())
185
+ .filter(l => l.status === 'published');
186
+
187
+ if (filters.type) results = results.filter(l => l.type === filters.type);
188
+ if (filters.category) results = results.filter(l => l.category === filters.category);
189
+ if (filters.sellerId) results = results.filter(l => l.sellerId === filters.sellerId);
190
+ if (filters.free) results = results.filter(l => l.price === 0);
191
+ if (filters.paid) results = results.filter(l => l.price > 0);
192
+ if (filters.minRating) results = results.filter(l => l.rating >= filters.minRating);
193
+ if (filters.tag) results = results.filter(l => l.tags.includes(filters.tag));
194
+ if (filters.query) {
195
+ const q = filters.query.toLowerCase();
196
+ results = results.filter(l =>
197
+ l.name.toLowerCase().includes(q) ||
198
+ l.description.toLowerCase().includes(q) ||
199
+ l.tags.some(t => t.toLowerCase().includes(q))
200
+ );
201
+ }
202
+
203
+ // Sort
204
+ const sortBy = filters.sortBy || 'installs';
205
+ results.sort((a, b) => {
206
+ if (sortBy === 'rating') return b.rating - a.rating;
207
+ if (sortBy === 'newest') return b.createdAt - a.createdAt;
208
+ if (sortBy === 'price') return a.price - b.price;
209
+ return b.installs - a.installs; // default: popular
210
+ });
211
+
212
+ return results.slice(0, limit);
213
+ }
214
+
215
+ /**
216
+ * Get listing by ID
217
+ */
218
+ getListing(id) {
219
+ return this._listings.get(id) || null;
220
+ }
221
+
222
+ /**
223
+ * Get reviews for a listing
224
+ */
225
+ getReviews(listingId) {
226
+ return this._reviews.get(listingId) || [];
227
+ }
228
+
229
+ /**
230
+ * Get seller earnings
231
+ */
232
+ getEarnings(sellerId) {
233
+ return this._earnings.get(sellerId) || { total: 0, pending: 0, paid: 0 };
234
+ }
235
+
236
+ /**
237
+ * Get purchases for a buyer
238
+ */
239
+ getPurchases(buyerId) {
240
+ return Array.from(this._purchases.values())
241
+ .filter(p => p.buyerId === buyerId)
242
+ .sort((a, b) => b.createdAt - a.createdAt);
243
+ }
244
+
245
+ /**
246
+ * Admin: list pending listings
247
+ */
248
+ getPendingListings() {
249
+ return Array.from(this._listings.values())
250
+ .filter(l => l.status === 'pending_review')
251
+ .sort((a, b) => a.createdAt - b.createdAt);
252
+ }
253
+
254
+ getStats() {
255
+ const listings = Array.from(this._listings.values());
256
+ return {
257
+ totalListings: listings.length,
258
+ published: listings.filter(l => l.status === 'published').length,
259
+ pending: listings.filter(l => l.status === 'pending_review').length,
260
+ totalPurchases: this._purchases.size,
261
+ totalRevenue: listings.reduce((sum, l) => sum + l.revenue, 0),
262
+ categories: MARKETPLACE.categories,
263
+ commission: MARKETPLACE.commission,
264
+ };
265
+ }
266
+ }
267
+
268
+ const marketplace = new MarketplaceEngine();
269
+
270
+ module.exports = { MarketplaceEngine, marketplace };
@@ -0,0 +1,182 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Usage Metering Service
5
+ *
6
+ * Tracks executions, agents, compute time, API calls, and storage per agent/site.
7
+ * Enforces plan limits and records overages for billing.
8
+ */
9
+
10
+ const db = require('../models/db').db || require('../models/db');
11
+ const { getLimit, isUnlimited, USAGE_PRICING } = require('../config/plans');
12
+ const { bus } = require('../runtime/event-bus');
13
+
14
+ // ─── Storage ────────────────────────────────────────────────────────
15
+
16
+ // In-memory counters with periodic flush to DB
17
+ const _counters = new Map(); // key → { count, lastReset }
18
+
19
+ function _key(entityId, metric) {
20
+ return `${entityId}:${metric}`;
21
+ }
22
+
23
+ function _today() {
24
+ return new Date().toISOString().slice(0, 10); // YYYY-MM-DD
25
+ }
26
+
27
+ function _getCounter(entityId, metric) {
28
+ const key = _key(entityId, metric);
29
+ const entry = _counters.get(key);
30
+ const today = _today();
31
+
32
+ // Reset daily counters
33
+ if (!entry || entry.lastReset !== today) {
34
+ _counters.set(key, { count: 0, lastReset: today, overage: 0 });
35
+ return _counters.get(key);
36
+ }
37
+ return entry;
38
+ }
39
+
40
+ // ─── Public API ─────────────────────────────────────────────────────
41
+
42
+ /**
43
+ * Record a usage event and check limits
44
+ * @returns {{ allowed: boolean, current: number, limit: number, overage: boolean }}
45
+ */
46
+ function record(entityId, metric, tier, amount = 1) {
47
+ const counter = _getCounter(entityId, metric);
48
+ const limit = getLimit(tier, metric);
49
+
50
+ counter.count += amount;
51
+
52
+ // Unlimited
53
+ if (isUnlimited(tier, metric)) {
54
+ bus.emit('metering.recorded', { entityId, metric, amount, current: counter.count });
55
+ return { allowed: true, current: counter.count, limit: -1, overage: false };
56
+ }
57
+
58
+ const isOver = counter.count > limit;
59
+ if (isOver) {
60
+ counter.overage += amount;
61
+ bus.emit('metering.overage', { entityId, metric, current: counter.count, limit, overage: counter.overage });
62
+ } else {
63
+ bus.emit('metering.recorded', { entityId, metric, amount, current: counter.count });
64
+ }
65
+
66
+ return {
67
+ allowed: !isOver,
68
+ current: counter.count,
69
+ limit,
70
+ overage: isOver,
71
+ overageAmount: isOver ? counter.overage : 0,
72
+ overageCost: isOver ? counter.overage * (USAGE_PRICING[metric]?.price || 0) : 0,
73
+ };
74
+ }
75
+
76
+ /**
77
+ * Check if a usage would exceed the limit (without recording)
78
+ */
79
+ function check(entityId, metric, tier, amount = 1) {
80
+ const counter = _getCounter(entityId, metric);
81
+ const limit = getLimit(tier, metric);
82
+
83
+ if (isUnlimited(tier, metric)) {
84
+ return { allowed: true, current: counter.count, limit: -1, remaining: Infinity };
85
+ }
86
+
87
+ const remaining = Math.max(0, limit - counter.count);
88
+ return {
89
+ allowed: counter.count + amount <= limit,
90
+ current: counter.count,
91
+ limit,
92
+ remaining,
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Get current usage for an entity
98
+ */
99
+ function getUsage(entityId, tier) {
100
+ const metrics = [
101
+ 'agents', 'tasksPerDay', 'executionsPerDay', 'sessions',
102
+ 'computeMinutesPerDay', 'apiCallsPerMinute',
103
+ ];
104
+
105
+ const usage = {};
106
+ for (const metric of metrics) {
107
+ const counter = _getCounter(entityId, metric);
108
+ const limit = getLimit(tier, metric);
109
+ usage[metric] = {
110
+ current: counter.count,
111
+ limit: isUnlimited(tier, metric) ? -1 : limit,
112
+ percentage: isUnlimited(tier, metric) ? 0 : (limit > 0 ? Math.round((counter.count / limit) * 100) : 0),
113
+ overage: counter.overage || 0,
114
+ };
115
+ }
116
+
117
+ return usage;
118
+ }
119
+
120
+ /**
121
+ * Get usage summary for billing
122
+ */
123
+ function getBillingSummary(entityId) {
124
+ const overages = {};
125
+ let totalCost = 0;
126
+
127
+ for (const [key, counter] of _counters) {
128
+ if (!key.startsWith(entityId + ':')) continue;
129
+ if (counter.overage > 0) {
130
+ const metric = key.split(':')[1];
131
+ const pricing = USAGE_PRICING[metric];
132
+ const cost = pricing ? counter.overage * pricing.price : 0;
133
+ overages[metric] = {
134
+ overage: counter.overage,
135
+ unitPrice: pricing?.price || 0,
136
+ cost,
137
+ };
138
+ totalCost += cost;
139
+ }
140
+ }
141
+
142
+ return { entityId, overages, totalCost, period: _today() };
143
+ }
144
+
145
+ /**
146
+ * Reset counters (for testing or admin)
147
+ */
148
+ function reset(entityId, metric = null) {
149
+ if (metric) {
150
+ _counters.delete(_key(entityId, metric));
151
+ } else {
152
+ for (const key of _counters.keys()) {
153
+ if (key.startsWith(entityId + ':')) _counters.delete(key);
154
+ }
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Get global stats
160
+ */
161
+ function getStats() {
162
+ let totalEntities = new Set();
163
+ let totalEvents = 0;
164
+ for (const [key, counter] of _counters) {
165
+ totalEntities.add(key.split(':')[0]);
166
+ totalEvents += counter.count;
167
+ }
168
+ return {
169
+ trackedEntities: totalEntities.size,
170
+ totalEvents,
171
+ counterEntries: _counters.size,
172
+ };
173
+ }
174
+
175
+ module.exports = {
176
+ record,
177
+ check,
178
+ getUsage,
179
+ getBillingSummary,
180
+ reset,
181
+ getStats,
182
+ };