web-agent-bridge 3.2.0 → 3.3.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.
- package/LICENSE +72 -72
- package/README.ar.md +1286 -1152
- package/README.md +1764 -1635
- package/bin/agent-runner.js +474 -474
- package/bin/cli.js +237 -138
- package/bin/wab.js +80 -80
- package/examples/bidi-agent.js +119 -119
- package/examples/cross-site-agent.js +91 -91
- package/examples/mcp-agent.js +94 -94
- package/examples/next-app-router/README.md +44 -44
- package/examples/puppeteer-agent.js +108 -108
- package/examples/saas-dashboard/README.md +55 -55
- package/examples/shopify-hydrogen/README.md +74 -74
- package/examples/vision-agent.js +171 -171
- package/examples/wordpress-elementor/README.md +77 -77
- package/package.json +16 -3
- package/public/.well-known/agent-tools.json +180 -180
- package/public/.well-known/ai-assets.json +59 -59
- package/public/.well-known/security.txt +8 -0
- package/public/agent-workspace.html +349 -349
- package/public/ai.html +198 -198
- package/public/api.html +413 -412
- package/public/browser.html +486 -486
- package/public/commander-dashboard.html +243 -243
- package/public/cookies.html +210 -210
- package/public/css/agent-workspace.css +1713 -1713
- package/public/css/premium.css +317 -317
- package/public/css/styles.css +1235 -1235
- package/public/dashboard.html +706 -706
- package/public/dns.html +507 -0
- package/public/docs.html +587 -587
- package/public/feed.xml +89 -89
- package/public/growth.html +463 -463
- package/public/index.html +1070 -982
- package/public/integrations.html +556 -0
- package/public/js/agent-workspace.js +1740 -1740
- package/public/js/auth-nav.js +31 -31
- package/public/js/auth-redirect.js +12 -12
- package/public/js/cookie-consent.js +56 -56
- package/public/js/wab-demo-page.js +721 -721
- package/public/js/ws-client.js +74 -74
- package/public/llms-full.txt +360 -360
- package/public/llms.txt +125 -125
- package/public/login.html +85 -85
- package/public/mesh-dashboard.html +328 -328
- package/public/openapi.json +580 -580
- package/public/phone-shield.html +281 -0
- package/public/premium-dashboard.html +2489 -2489
- package/public/premium.html +793 -793
- package/public/privacy.html +297 -297
- package/public/register.html +105 -105
- package/public/robots.txt +87 -87
- package/public/script/wab-consent.d.ts +36 -36
- package/public/script/wab-consent.js +104 -104
- package/public/script/wab-schema.js +131 -131
- package/public/script/wab.d.ts +108 -108
- package/public/script/wab.min.js +580 -580
- package/public/security.txt +8 -0
- package/public/terms.html +256 -256
- package/script/ai-agent-bridge.js +1754 -1754
- package/sdk/README.md +99 -99
- package/sdk/agent-mesh.js +449 -449
- package/sdk/commander.js +262 -262
- package/sdk/index.d.ts +464 -464
- package/sdk/index.js +12 -1
- package/sdk/multi-agent.js +318 -318
- package/sdk/package.json +1 -1
- package/sdk/safety-shield.js +219 -0
- package/sdk/schema-discovery.js +83 -83
- package/server/adapters/index.js +520 -520
- package/server/config/plans.js +367 -367
- package/server/config/secrets.js +102 -102
- package/server/control-plane/index.js +301 -301
- package/server/data-plane/index.js +354 -354
- package/server/index.js +531 -427
- package/server/llm/index.js +404 -404
- package/server/middleware/adminAuth.js +35 -35
- package/server/middleware/auth.js +50 -50
- package/server/middleware/featureGate.js +88 -88
- package/server/middleware/rateLimits.js +100 -100
- package/server/middleware/sensitiveAction.js +157 -0
- package/server/migrations/001_add_analytics_indexes.sql +7 -7
- package/server/migrations/002_premium_features.sql +418 -418
- package/server/migrations/003_ads_integer_cents.sql +33 -33
- package/server/migrations/004_agent_os.sql +158 -158
- package/server/migrations/005_marketplace_metering.sql +126 -126
- package/server/models/adapters/index.js +33 -33
- package/server/models/adapters/mysql.js +183 -183
- package/server/models/adapters/postgresql.js +172 -172
- package/server/models/adapters/sqlite.js +7 -7
- package/server/models/db.js +681 -681
- package/server/observability/failure-analysis.js +337 -337
- package/server/observability/index.js +394 -394
- package/server/protocol/capabilities.js +223 -223
- package/server/protocol/index.js +243 -243
- package/server/protocol/schema.js +584 -584
- package/server/registry/certification.js +271 -271
- package/server/registry/index.js +326 -326
- package/server/routes/admin-premium.js +671 -671
- package/server/routes/admin.js +261 -261
- package/server/routes/ads.js +130 -130
- package/server/routes/agent-workspace.js +540 -540
- package/server/routes/api.js +150 -150
- package/server/routes/auth.js +71 -71
- package/server/routes/billing.js +45 -45
- package/server/routes/commander.js +316 -316
- package/server/routes/demo-showcase.js +332 -332
- package/server/routes/demo-store.js +154 -0
- package/server/routes/discovery.js +417 -417
- package/server/routes/gateway.js +173 -157
- package/server/routes/license.js +251 -240
- package/server/routes/mesh.js +469 -469
- package/server/routes/noscript.js +543 -543
- package/server/routes/premium-v2.js +686 -686
- package/server/routes/premium.js +724 -724
- package/server/routes/runtime.js +2148 -2147
- package/server/routes/sovereign.js +465 -385
- package/server/routes/universal.js +200 -185
- package/server/routes/wab-api.js +850 -501
- package/server/runtime/container-worker.js +111 -111
- package/server/runtime/container.js +448 -448
- package/server/runtime/distributed-worker.js +362 -362
- package/server/runtime/event-bus.js +210 -210
- package/server/runtime/index.js +253 -253
- package/server/runtime/queue.js +599 -599
- package/server/runtime/replay.js +666 -666
- package/server/runtime/sandbox.js +266 -266
- package/server/runtime/scheduler.js +534 -534
- package/server/runtime/session-engine.js +293 -293
- package/server/runtime/state-manager.js +188 -188
- package/server/security/cross-site-redactor.js +196 -0
- package/server/security/dry-run.js +180 -0
- package/server/security/human-gate-rate-limit.js +147 -0
- package/server/security/human-gate-transports.js +178 -0
- package/server/security/human-gate.js +281 -0
- package/server/security/index.js +368 -368
- package/server/security/intent-engine.js +245 -0
- package/server/security/reward-guard.js +171 -0
- package/server/security/rollback-store.js +239 -0
- package/server/security/token-scope.js +404 -0
- package/server/security/url-policy.js +139 -0
- package/server/services/agent-chat.js +506 -506
- package/server/services/agent-learning.js +601 -575
- package/server/services/agent-memory.js +625 -625
- package/server/services/agent-mesh.js +555 -539
- package/server/services/agent-symphony.js +717 -717
- package/server/services/agent-tasks.js +1807 -1807
- package/server/services/api-key-engine.js +292 -261
- package/server/services/cluster.js +894 -894
- package/server/services/commander.js +738 -738
- package/server/services/edge-compute.js +440 -440
- package/server/services/email.js +204 -204
- package/server/services/hosted-runtime.js +205 -205
- package/server/services/lfd.js +635 -635
- package/server/services/local-ai.js +389 -389
- package/server/services/marketplace.js +270 -270
- package/server/services/metering.js +182 -182
- package/server/services/modules/affiliate-intelligence.js +93 -93
- package/server/services/modules/agent-firewall.js +90 -90
- package/server/services/modules/bounty.js +89 -89
- package/server/services/modules/collective-bargaining.js +92 -92
- package/server/services/modules/dark-pattern.js +66 -66
- package/server/services/modules/gov-intelligence.js +45 -45
- package/server/services/modules/neural.js +55 -55
- package/server/services/modules/notary.js +49 -49
- package/server/services/modules/price-time-machine.js +86 -86
- package/server/services/modules/protocol.js +104 -104
- package/server/services/negotiation.js +439 -439
- package/server/services/plugins.js +771 -771
- package/server/services/price-intelligence.js +566 -566
- package/server/services/price-shield.js +1137 -1137
- package/server/services/reputation.js +465 -465
- package/server/services/search-engine.js +357 -357
- package/server/services/security.js +513 -513
- package/server/services/self-healing.js +843 -843
- package/server/services/sovereign-shield.js +542 -0
- package/server/services/stripe.js +192 -192
- package/server/services/swarm.js +788 -788
- package/server/services/universal-scraper.js +662 -661
- package/server/services/verification.js +481 -481
- package/server/services/vision.js +1163 -1163
- package/server/utils/cache.js +125 -125
- package/server/utils/migrate.js +81 -81
- package/server/utils/safe-fetch.js +228 -0
- package/server/utils/secureFields.js +50 -50
- package/server/ws.js +161 -161
- package/templates/artisan-marketplace.yaml +104 -104
- package/templates/book-price-scout.yaml +98 -98
- package/templates/electronics-price-tracker.yaml +108 -108
- package/templates/flight-deal-hunter.yaml +113 -113
- package/templates/freelancer-direct.yaml +116 -116
- package/templates/grocery-price-compare.yaml +93 -93
- package/templates/hotel-direct-booking.yaml +113 -113
- package/templates/local-services.yaml +98 -98
- package/templates/olive-oil-tunisia.yaml +88 -88
- package/templates/organic-farm-fresh.yaml +101 -101
- package/templates/restaurant-direct.yaml +97 -97
- package/public/score.html +0 -263
- package/server/migrations/006_growth_suite.sql +0 -138
- package/server/routes/growth.js +0 -962
- package/server/services/fairness-engine.js +0 -409
- package/server/services/fairness.js +0 -420
|
@@ -1,671 +1,671 @@
|
|
|
1
|
-
const express = require('express');
|
|
2
|
-
const router = express.Router();
|
|
3
|
-
const { authenticateAdmin } = require('../middleware/adminAuth');
|
|
4
|
-
const { db } = require('../models/db');
|
|
5
|
-
|
|
6
|
-
router.use(authenticateAdmin);
|
|
7
|
-
|
|
8
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
9
|
-
// Platform Overview
|
|
10
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
11
|
-
|
|
12
|
-
router.get('/overview/stats', (req, res) => {
|
|
13
|
-
try {
|
|
14
|
-
const totalUsers = db.prepare('SELECT COUNT(*) as c FROM users').get().c;
|
|
15
|
-
const totalSites = db.prepare('SELECT COUNT(*) as c FROM sites').get().c;
|
|
16
|
-
const activeSites = db.prepare('SELECT COUNT(*) as c FROM sites WHERE active = 1').get().c;
|
|
17
|
-
|
|
18
|
-
const revenue = db.prepare(
|
|
19
|
-
"SELECT COALESCE(SUM(amount), 0) as total FROM payments WHERE status = 'succeeded'"
|
|
20
|
-
).get().total;
|
|
21
|
-
|
|
22
|
-
const totalMemories = db.prepare('SELECT COUNT(*) as c FROM agent_memories').get().c;
|
|
23
|
-
const totalHealingEvents = db.prepare('SELECT COUNT(*) as c FROM healing_log').get().c;
|
|
24
|
-
const totalVisionAnalyses = db.prepare('SELECT COUNT(*) as c FROM vision_cache').get().c;
|
|
25
|
-
const totalSwarmTasks = db.prepare('SELECT COUNT(*) as c FROM swarm_tasks').get().c;
|
|
26
|
-
const pluginsInstalled = db.prepare('SELECT COUNT(*) as c FROM plugin_installations').get().c;
|
|
27
|
-
|
|
28
|
-
const newUsersLast7Days = db.prepare(
|
|
29
|
-
"SELECT COUNT(*) as c FROM users WHERE created_at >= datetime('now', '-7 days')"
|
|
30
|
-
).get().c;
|
|
31
|
-
const newSitesLast7Days = db.prepare(
|
|
32
|
-
"SELECT COUNT(*) as c FROM sites WHERE created_at >= datetime('now', '-7 days')"
|
|
33
|
-
).get().c;
|
|
34
|
-
|
|
35
|
-
const pageInfo = db.prepare('PRAGMA page_count').get();
|
|
36
|
-
const pageSizeInfo = db.prepare('PRAGMA page_size').get();
|
|
37
|
-
const dbSizeBytes = (pageInfo.page_count || 0) * (pageSizeInfo.page_size || 0);
|
|
38
|
-
|
|
39
|
-
res.json({
|
|
40
|
-
users: { total: totalUsers },
|
|
41
|
-
sites: { total: totalSites, active: activeSites },
|
|
42
|
-
revenue: { total: revenue },
|
|
43
|
-
premiumFeatures: {
|
|
44
|
-
totalMemories,
|
|
45
|
-
totalHealingEvents,
|
|
46
|
-
totalVisionAnalyses,
|
|
47
|
-
totalSwarmTasks,
|
|
48
|
-
pluginsInstalled,
|
|
49
|
-
},
|
|
50
|
-
growth: {
|
|
51
|
-
newUsersLast7Days,
|
|
52
|
-
newSitesLast7Days,
|
|
53
|
-
},
|
|
54
|
-
system: {
|
|
55
|
-
dbSizeBytes,
|
|
56
|
-
dbSizeMB: Math.round((dbSizeBytes / 1048576) * 100) / 100,
|
|
57
|
-
uptimeSeconds: Math.floor(process.uptime()),
|
|
58
|
-
},
|
|
59
|
-
});
|
|
60
|
-
} catch (err) {
|
|
61
|
-
res.status(500).json({ error: err.message });
|
|
62
|
-
}
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
66
|
-
// Memory Management
|
|
67
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
68
|
-
|
|
69
|
-
router.get('/memory/global-stats', (req, res) => {
|
|
70
|
-
try {
|
|
71
|
-
const total = db.prepare('SELECT COUNT(*) as c FROM agent_memories').get().c;
|
|
72
|
-
const active = db.prepare(
|
|
73
|
-
"SELECT COUNT(*) as c FROM agent_memories WHERE expires_at IS NULL OR expires_at > datetime('now')"
|
|
74
|
-
).get().c;
|
|
75
|
-
const expired = db.prepare(
|
|
76
|
-
"SELECT COUNT(*) as c FROM agent_memories WHERE expires_at IS NOT NULL AND expires_at <= datetime('now')"
|
|
77
|
-
).get().c;
|
|
78
|
-
|
|
79
|
-
const byType = db.prepare(
|
|
80
|
-
'SELECT memory_type, COUNT(*) as count FROM agent_memories GROUP BY memory_type'
|
|
81
|
-
).all();
|
|
82
|
-
const byCategory = db.prepare(
|
|
83
|
-
'SELECT category, COUNT(*) as count FROM agent_memories GROUP BY category'
|
|
84
|
-
).all();
|
|
85
|
-
|
|
86
|
-
const avgImportance = db.prepare(
|
|
87
|
-
'SELECT AVG(importance) as avg FROM agent_memories'
|
|
88
|
-
).get().avg || 0;
|
|
89
|
-
|
|
90
|
-
const storageBytes = db.prepare(
|
|
91
|
-
'SELECT SUM(LENGTH(key) + LENGTH(value) + COALESCE(LENGTH(embedding), 0)) as bytes FROM agent_memories'
|
|
92
|
-
).get().bytes || 0;
|
|
93
|
-
|
|
94
|
-
const totalSessions = db.prepare('SELECT COUNT(*) as c FROM memory_sessions').get().c;
|
|
95
|
-
const totalAssociations = db.prepare('SELECT COUNT(*) as c FROM memory_associations').get().c;
|
|
96
|
-
|
|
97
|
-
res.json({
|
|
98
|
-
total,
|
|
99
|
-
active,
|
|
100
|
-
expired,
|
|
101
|
-
byType,
|
|
102
|
-
byCategory,
|
|
103
|
-
avgImportance: Math.round(avgImportance * 1000) / 1000,
|
|
104
|
-
storageBytes,
|
|
105
|
-
totalSessions,
|
|
106
|
-
totalAssociations,
|
|
107
|
-
});
|
|
108
|
-
} catch (err) {
|
|
109
|
-
res.status(500).json({ error: err.message });
|
|
110
|
-
}
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
router.get('/memory/top-users', (req, res) => {
|
|
114
|
-
try {
|
|
115
|
-
const rows = db.prepare(`
|
|
116
|
-
SELECT am.site_id, s.name as site_name, s.domain, u.email as user_email,
|
|
117
|
-
COUNT(*) as memory_count,
|
|
118
|
-
SUM(LENGTH(am.key) + LENGTH(am.value)) as storage_bytes,
|
|
119
|
-
AVG(am.importance) as avg_importance
|
|
120
|
-
FROM agent_memories am
|
|
121
|
-
LEFT JOIN sites s ON am.site_id = s.id
|
|
122
|
-
LEFT JOIN users u ON s.user_id = u.id
|
|
123
|
-
GROUP BY am.site_id
|
|
124
|
-
ORDER BY memory_count DESC
|
|
125
|
-
LIMIT 20
|
|
126
|
-
`).all();
|
|
127
|
-
|
|
128
|
-
res.json({ topUsers: rows });
|
|
129
|
-
} catch (err) {
|
|
130
|
-
res.status(500).json({ error: err.message });
|
|
131
|
-
}
|
|
132
|
-
});
|
|
133
|
-
|
|
134
|
-
router.delete('/memory/cleanup', (req, res) => {
|
|
135
|
-
try {
|
|
136
|
-
const result = db.prepare(
|
|
137
|
-
"DELETE FROM agent_memories WHERE expires_at IS NOT NULL AND expires_at <= datetime('now')"
|
|
138
|
-
).run();
|
|
139
|
-
|
|
140
|
-
res.json({ purged: result.changes });
|
|
141
|
-
} catch (err) {
|
|
142
|
-
res.status(500).json({ error: err.message });
|
|
143
|
-
}
|
|
144
|
-
});
|
|
145
|
-
|
|
146
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
147
|
-
// Healing Management
|
|
148
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
149
|
-
|
|
150
|
-
router.get('/healing/global-stats', (req, res) => {
|
|
151
|
-
try {
|
|
152
|
-
const total = db.prepare('SELECT COUNT(*) as c FROM healing_log').get().c;
|
|
153
|
-
const successes = db.prepare('SELECT COUNT(*) as c FROM healing_log WHERE success = 1').get().c;
|
|
154
|
-
const successRate = total > 0 ? Math.round((successes / total) * 10000) / 100 : 0;
|
|
155
|
-
|
|
156
|
-
const topStrategies = db.prepare(`
|
|
157
|
-
SELECT strategy, COUNT(*) as count,
|
|
158
|
-
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successes,
|
|
159
|
-
AVG(confidence) as avg_confidence
|
|
160
|
-
FROM healing_log
|
|
161
|
-
GROUP BY strategy
|
|
162
|
-
ORDER BY count DESC
|
|
163
|
-
`).all();
|
|
164
|
-
|
|
165
|
-
const totalRegistered = db.prepare('SELECT COUNT(*) as c FROM selector_registry').get().c;
|
|
166
|
-
const totalCorrections = db.prepare('SELECT COUNT(*) as c FROM selector_corrections').get().c;
|
|
167
|
-
|
|
168
|
-
res.json({
|
|
169
|
-
total,
|
|
170
|
-
successes,
|
|
171
|
-
successRate,
|
|
172
|
-
topStrategies,
|
|
173
|
-
totalRegistered,
|
|
174
|
-
totalCorrections,
|
|
175
|
-
});
|
|
176
|
-
} catch (err) {
|
|
177
|
-
res.status(500).json({ error: err.message });
|
|
178
|
-
}
|
|
179
|
-
});
|
|
180
|
-
|
|
181
|
-
router.get('/healing/community-corrections', (req, res) => {
|
|
182
|
-
try {
|
|
183
|
-
const corrections = db.prepare(`
|
|
184
|
-
SELECT sc.*, s.name as site_name, s.domain
|
|
185
|
-
FROM selector_corrections sc
|
|
186
|
-
LEFT JOIN sites s ON sc.site_id = s.id
|
|
187
|
-
WHERE sc.shared = 1
|
|
188
|
-
ORDER BY sc.applied_count DESC, sc.created_at DESC
|
|
189
|
-
`).all();
|
|
190
|
-
|
|
191
|
-
res.json({ corrections });
|
|
192
|
-
} catch (err) {
|
|
193
|
-
res.status(500).json({ error: err.message });
|
|
194
|
-
}
|
|
195
|
-
});
|
|
196
|
-
|
|
197
|
-
router.get('/healing/broken-selectors', (req, res) => {
|
|
198
|
-
try {
|
|
199
|
-
const broken = db.prepare(`
|
|
200
|
-
SELECT sr.*, s.name as site_name, s.domain
|
|
201
|
-
FROM selector_registry sr
|
|
202
|
-
LEFT JOIN sites s ON sr.site_id = s.id
|
|
203
|
-
WHERE sr.confidence < 0.5
|
|
204
|
-
ORDER BY sr.confidence ASC
|
|
205
|
-
`).all();
|
|
206
|
-
|
|
207
|
-
res.json({ broken });
|
|
208
|
-
} catch (err) {
|
|
209
|
-
res.status(500).json({ error: err.message });
|
|
210
|
-
}
|
|
211
|
-
});
|
|
212
|
-
|
|
213
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
214
|
-
// Vision Management
|
|
215
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
216
|
-
|
|
217
|
-
router.get('/vision/global-stats', (req, res) => {
|
|
218
|
-
try {
|
|
219
|
-
const total = db.prepare('SELECT COUNT(*) as c FROM vision_cache').get().c;
|
|
220
|
-
const activeCached = db.prepare(
|
|
221
|
-
"SELECT COUNT(*) as c FROM vision_cache WHERE expires_at > datetime('now')"
|
|
222
|
-
).get().c;
|
|
223
|
-
const expiredCached = db.prepare(
|
|
224
|
-
"SELECT COUNT(*) as c FROM vision_cache WHERE expires_at <= datetime('now')"
|
|
225
|
-
).get().c;
|
|
226
|
-
const cacheHitRate = total > 0
|
|
227
|
-
? Math.round((activeCached / total) * 10000) / 100
|
|
228
|
-
: 0;
|
|
229
|
-
|
|
230
|
-
const providerUsage = db.prepare(`
|
|
231
|
-
SELECT provider, COUNT(*) as count,
|
|
232
|
-
SUM(tokens_used) as total_tokens,
|
|
233
|
-
AVG(latency_ms) as avg_latency
|
|
234
|
-
FROM vision_cache
|
|
235
|
-
GROUP BY provider
|
|
236
|
-
ORDER BY count DESC
|
|
237
|
-
`).all();
|
|
238
|
-
|
|
239
|
-
const totalTokens = db.prepare(
|
|
240
|
-
'SELECT COALESCE(SUM(tokens_used), 0) as t FROM vision_cache'
|
|
241
|
-
).get().t;
|
|
242
|
-
const avgLatency = db.prepare(
|
|
243
|
-
'SELECT COALESCE(AVG(latency_ms), 0) as avg FROM vision_cache'
|
|
244
|
-
).get().avg;
|
|
245
|
-
const totalElements = db.prepare('SELECT COUNT(*) as c FROM vision_elements').get().c;
|
|
246
|
-
|
|
247
|
-
res.json({
|
|
248
|
-
totalAnalyses: total,
|
|
249
|
-
activeCached,
|
|
250
|
-
expiredCached,
|
|
251
|
-
cacheHitRate,
|
|
252
|
-
providerUsage,
|
|
253
|
-
totalTokens,
|
|
254
|
-
avgLatencyMs: Math.round(avgLatency),
|
|
255
|
-
totalElements,
|
|
256
|
-
});
|
|
257
|
-
} catch (err) {
|
|
258
|
-
res.status(500).json({ error: err.message });
|
|
259
|
-
}
|
|
260
|
-
});
|
|
261
|
-
|
|
262
|
-
router.get('/vision/usage-by-site', (req, res) => {
|
|
263
|
-
try {
|
|
264
|
-
const rows = db.prepare(`
|
|
265
|
-
SELECT vc.site_id, s.name as site_name, s.domain,
|
|
266
|
-
COUNT(*) as analyses_count,
|
|
267
|
-
SUM(vc.tokens_used) as total_tokens,
|
|
268
|
-
AVG(vc.latency_ms) as avg_latency
|
|
269
|
-
FROM vision_cache vc
|
|
270
|
-
LEFT JOIN sites s ON vc.site_id = s.id
|
|
271
|
-
GROUP BY vc.site_id
|
|
272
|
-
ORDER BY analyses_count DESC
|
|
273
|
-
`).all();
|
|
274
|
-
|
|
275
|
-
res.json({ usageBySite: rows });
|
|
276
|
-
} catch (err) {
|
|
277
|
-
res.status(500).json({ error: err.message });
|
|
278
|
-
}
|
|
279
|
-
});
|
|
280
|
-
|
|
281
|
-
router.delete('/vision/purge-cache', (req, res) => {
|
|
282
|
-
try {
|
|
283
|
-
const cacheResult = db.prepare(
|
|
284
|
-
"DELETE FROM vision_cache WHERE expires_at <= datetime('now')"
|
|
285
|
-
).run();
|
|
286
|
-
const elemResult = db.prepare(
|
|
287
|
-
'DELETE FROM vision_elements WHERE cache_id NOT IN (SELECT id FROM vision_cache)'
|
|
288
|
-
).run();
|
|
289
|
-
|
|
290
|
-
res.json({
|
|
291
|
-
purgedCacheEntries: cacheResult.changes,
|
|
292
|
-
orphanedElementsCleaned: elemResult.changes,
|
|
293
|
-
});
|
|
294
|
-
} catch (err) {
|
|
295
|
-
res.status(500).json({ error: err.message });
|
|
296
|
-
}
|
|
297
|
-
});
|
|
298
|
-
|
|
299
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
300
|
-
// Swarm Management
|
|
301
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
302
|
-
|
|
303
|
-
router.get('/swarm/global-stats', (req, res) => {
|
|
304
|
-
try {
|
|
305
|
-
const total = db.prepare('SELECT COUNT(*) as c FROM swarm_tasks').get().c;
|
|
306
|
-
const completed = db.prepare(
|
|
307
|
-
"SELECT COUNT(*) as c FROM swarm_tasks WHERE status = 'completed'"
|
|
308
|
-
).get().c;
|
|
309
|
-
const failed = db.prepare(
|
|
310
|
-
"SELECT COUNT(*) as c FROM swarm_tasks WHERE status = 'failed'"
|
|
311
|
-
).get().c;
|
|
312
|
-
const running = db.prepare(
|
|
313
|
-
"SELECT COUNT(*) as c FROM swarm_tasks WHERE status = 'running'"
|
|
314
|
-
).get().c;
|
|
315
|
-
const successRate = total > 0 ? Math.round((completed / total) * 10000) / 100 : 0;
|
|
316
|
-
|
|
317
|
-
const avgAgentsRow = db.prepare(`
|
|
318
|
-
SELECT AVG(agent_count) as avg_agents FROM (
|
|
319
|
-
SELECT COUNT(*) as agent_count FROM swarm_agents
|
|
320
|
-
GROUP BY task_id
|
|
321
|
-
)
|
|
322
|
-
`).get();
|
|
323
|
-
const avgAgents = avgAgentsRow ? Math.round((avgAgentsRow.avg_agents || 0) * 100) / 100 : 0;
|
|
324
|
-
|
|
325
|
-
const taskTypeBreakdown = db.prepare(`
|
|
326
|
-
SELECT task_type, COUNT(*) as count,
|
|
327
|
-
SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed
|
|
328
|
-
FROM swarm_tasks
|
|
329
|
-
GROUP BY task_type
|
|
330
|
-
`).all();
|
|
331
|
-
|
|
332
|
-
res.json({
|
|
333
|
-
total,
|
|
334
|
-
completed,
|
|
335
|
-
failed,
|
|
336
|
-
running,
|
|
337
|
-
successRate,
|
|
338
|
-
avgAgentsPerTask: avgAgents,
|
|
339
|
-
taskTypeBreakdown,
|
|
340
|
-
});
|
|
341
|
-
} catch (err) {
|
|
342
|
-
res.status(500).json({ error: err.message });
|
|
343
|
-
}
|
|
344
|
-
});
|
|
345
|
-
|
|
346
|
-
router.get('/swarm/active-tasks', (req, res) => {
|
|
347
|
-
try {
|
|
348
|
-
const tasks = db.prepare(`
|
|
349
|
-
SELECT st.*, s.name as site_name, s.domain
|
|
350
|
-
FROM swarm_tasks st
|
|
351
|
-
LEFT JOIN sites s ON st.site_id = s.id
|
|
352
|
-
WHERE st.status IN ('pending', 'running')
|
|
353
|
-
ORDER BY st.created_at DESC
|
|
354
|
-
`).all();
|
|
355
|
-
|
|
356
|
-
const enriched = tasks.map(t => {
|
|
357
|
-
const agents = db.prepare(
|
|
358
|
-
'SELECT id, agent_role, agent_type, target, status, score FROM swarm_agents WHERE task_id = ?'
|
|
359
|
-
).all(t.id);
|
|
360
|
-
return { ...t, agents };
|
|
361
|
-
});
|
|
362
|
-
|
|
363
|
-
res.json({ activeTasks: enriched });
|
|
364
|
-
} catch (err) {
|
|
365
|
-
res.status(500).json({ error: err.message });
|
|
366
|
-
}
|
|
367
|
-
});
|
|
368
|
-
|
|
369
|
-
router.post('/swarm/cancel-all', (req, res) => {
|
|
370
|
-
try {
|
|
371
|
-
const now = new Date().toISOString();
|
|
372
|
-
|
|
373
|
-
const runningTasks = db.prepare(
|
|
374
|
-
"SELECT id FROM swarm_tasks WHERE status IN ('pending', 'running')"
|
|
375
|
-
).all();
|
|
376
|
-
|
|
377
|
-
const cancelTx = db.transaction(() => {
|
|
378
|
-
for (const task of runningTasks) {
|
|
379
|
-
db.prepare(
|
|
380
|
-
"UPDATE swarm_tasks SET status = 'cancelled', completed_at = ? WHERE id = ?"
|
|
381
|
-
).run(now, task.id);
|
|
382
|
-
db.prepare(
|
|
383
|
-
"UPDATE swarm_agents SET status = 'cancelled' WHERE task_id = ? AND status IN ('idle', 'running')"
|
|
384
|
-
).run(task.id);
|
|
385
|
-
}
|
|
386
|
-
});
|
|
387
|
-
cancelTx();
|
|
388
|
-
|
|
389
|
-
res.json({ cancelledTasks: runningTasks.length });
|
|
390
|
-
} catch (err) {
|
|
391
|
-
res.status(500).json({ error: err.message });
|
|
392
|
-
}
|
|
393
|
-
});
|
|
394
|
-
|
|
395
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
396
|
-
// Plugin Management
|
|
397
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
398
|
-
|
|
399
|
-
router.get('/plugins/all', (req, res) => {
|
|
400
|
-
try {
|
|
401
|
-
const plugins = db.prepare(`
|
|
402
|
-
SELECT pr.*,
|
|
403
|
-
(SELECT COUNT(*) FROM plugin_installations pi WHERE pi.plugin_id = pr.id) as installation_count
|
|
404
|
-
FROM plugin_registry pr
|
|
405
|
-
ORDER BY pr.created_at DESC
|
|
406
|
-
`).all();
|
|
407
|
-
|
|
408
|
-
res.json({ plugins });
|
|
409
|
-
} catch (err) {
|
|
410
|
-
res.status(500).json({ error: err.message });
|
|
411
|
-
}
|
|
412
|
-
});
|
|
413
|
-
|
|
414
|
-
router.put('/plugins/:pluginId/toggle', (req, res) => {
|
|
415
|
-
try {
|
|
416
|
-
const { pluginId } = req.params;
|
|
417
|
-
const plugin = db.prepare('SELECT * FROM plugin_registry WHERE id = ?').get(pluginId);
|
|
418
|
-
if (!plugin) return res.status(404).json({ error: 'Plugin not found' });
|
|
419
|
-
|
|
420
|
-
const newEnabled = plugin.enabled ? 0 : 1;
|
|
421
|
-
db.prepare(
|
|
422
|
-
"UPDATE plugin_registry SET enabled = ?, updated_at = datetime('now') WHERE id = ?"
|
|
423
|
-
).run(newEnabled, pluginId);
|
|
424
|
-
|
|
425
|
-
res.json({ pluginId, enabled: !!newEnabled });
|
|
426
|
-
} catch (err) {
|
|
427
|
-
res.status(500).json({ error: err.message });
|
|
428
|
-
}
|
|
429
|
-
});
|
|
430
|
-
|
|
431
|
-
router.get('/plugins/hook-stats', (req, res) => {
|
|
432
|
-
try {
|
|
433
|
-
const stats = db.prepare(`
|
|
434
|
-
SELECT hook_name,
|
|
435
|
-
COUNT(*) as total_executions,
|
|
436
|
-
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successes,
|
|
437
|
-
ROUND(CAST(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) AS REAL) / COUNT(*) * 100, 2) as success_rate,
|
|
438
|
-
AVG(duration_ms) as avg_duration_ms
|
|
439
|
-
FROM hook_executions
|
|
440
|
-
GROUP BY hook_name
|
|
441
|
-
ORDER BY total_executions DESC
|
|
442
|
-
`).all();
|
|
443
|
-
|
|
444
|
-
res.json({ hookStats: stats });
|
|
445
|
-
} catch (err) {
|
|
446
|
-
res.status(500).json({ error: err.message });
|
|
447
|
-
}
|
|
448
|
-
});
|
|
449
|
-
|
|
450
|
-
router.delete('/plugins/:pluginId', (req, res) => {
|
|
451
|
-
try {
|
|
452
|
-
const { pluginId } = req.params;
|
|
453
|
-
const plugin = db.prepare('SELECT * FROM plugin_registry WHERE id = ?').get(pluginId);
|
|
454
|
-
if (!plugin) return res.status(404).json({ error: 'Plugin not found' });
|
|
455
|
-
|
|
456
|
-
const removeTx = db.transaction(() => {
|
|
457
|
-
db.prepare('DELETE FROM plugin_installations WHERE plugin_id = ?').run(pluginId);
|
|
458
|
-
db.prepare('DELETE FROM plugin_hooks WHERE plugin_id = ?').run(pluginId);
|
|
459
|
-
db.prepare('DELETE FROM hook_executions WHERE plugin_id = ?').run(pluginId);
|
|
460
|
-
db.prepare('DELETE FROM plugin_registry WHERE id = ?').run(pluginId);
|
|
461
|
-
});
|
|
462
|
-
removeTx();
|
|
463
|
-
|
|
464
|
-
res.json({ removed: true, pluginId, name: plugin.name });
|
|
465
|
-
} catch (err) {
|
|
466
|
-
res.status(500).json({ error: err.message });
|
|
467
|
-
}
|
|
468
|
-
});
|
|
469
|
-
|
|
470
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
471
|
-
// Revenue
|
|
472
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
473
|
-
|
|
474
|
-
function getTierPrices() {
|
|
475
|
-
const plans = db.prepare('SELECT tier, price FROM plans').all();
|
|
476
|
-
const prices = { free: 0, starter: 900, pro: 2900, enterprise: 9900 };
|
|
477
|
-
for (const p of plans) prices[p.tier] = p.price;
|
|
478
|
-
return prices;
|
|
479
|
-
}
|
|
480
|
-
const TIER_PRICES = new Proxy({}, { get: function(_, tier) { return getTierPrices()[tier] || 0; } });
|
|
481
|
-
|
|
482
|
-
router.get('/revenue/summary', (req, res) => {
|
|
483
|
-
try {
|
|
484
|
-
const tierCounts = db.prepare(`
|
|
485
|
-
SELECT tier, COUNT(*) as count
|
|
486
|
-
FROM subscriptions
|
|
487
|
-
WHERE status = 'active'
|
|
488
|
-
GROUP BY tier
|
|
489
|
-
`).all();
|
|
490
|
-
|
|
491
|
-
let mrr = 0;
|
|
492
|
-
for (const row of tierCounts) {
|
|
493
|
-
mrr += (TIER_PRICES[row.tier] || 0) * row.count;
|
|
494
|
-
}
|
|
495
|
-
const arr = mrr * 12;
|
|
496
|
-
|
|
497
|
-
const totalActive = db.prepare(
|
|
498
|
-
"SELECT COUNT(*) as c FROM subscriptions WHERE status = 'active'"
|
|
499
|
-
).get().c;
|
|
500
|
-
const cancelledLast30 = db.prepare(
|
|
501
|
-
"SELECT COUNT(*) as c FROM subscriptions WHERE status = 'cancelled' AND started_at >= datetime('now', '-30 days')"
|
|
502
|
-
).get().c;
|
|
503
|
-
const churnRate = totalActive > 0
|
|
504
|
-
? Math.round((cancelledLast30 / (totalActive + cancelledLast30)) * 10000) / 100
|
|
505
|
-
: 0;
|
|
506
|
-
|
|
507
|
-
const arpu = totalActive > 0 ? Math.round(mrr / totalActive) : 0;
|
|
508
|
-
|
|
509
|
-
res.json({
|
|
510
|
-
mrr,
|
|
511
|
-
mrrFormatted: `$${(mrr / 100).toFixed(2)}`,
|
|
512
|
-
arr,
|
|
513
|
-
arrFormatted: `$${(arr / 100).toFixed(2)}`,
|
|
514
|
-
churnRate,
|
|
515
|
-
arpu,
|
|
516
|
-
arpuFormatted: `$${(arpu / 100).toFixed(2)}`,
|
|
517
|
-
activeSubscriptions: totalActive,
|
|
518
|
-
cancelledLast30Days: cancelledLast30,
|
|
519
|
-
tierCounts,
|
|
520
|
-
});
|
|
521
|
-
} catch (err) {
|
|
522
|
-
res.status(500).json({ error: err.message });
|
|
523
|
-
}
|
|
524
|
-
});
|
|
525
|
-
|
|
526
|
-
router.get('/revenue/timeline', (req, res) => {
|
|
527
|
-
try {
|
|
528
|
-
const rows = db.prepare(`
|
|
529
|
-
SELECT strftime('%Y-%m', created_at) as month,
|
|
530
|
-
SUM(amount) as total_amount,
|
|
531
|
-
COUNT(*) as payment_count
|
|
532
|
-
FROM payments
|
|
533
|
-
WHERE status = 'succeeded'
|
|
534
|
-
AND created_at >= datetime('now', '-12 months')
|
|
535
|
-
GROUP BY month
|
|
536
|
-
ORDER BY month ASC
|
|
537
|
-
`).all();
|
|
538
|
-
|
|
539
|
-
res.json({ timeline: rows });
|
|
540
|
-
} catch (err) {
|
|
541
|
-
res.status(500).json({ error: err.message });
|
|
542
|
-
}
|
|
543
|
-
});
|
|
544
|
-
|
|
545
|
-
router.get('/revenue/tier-breakdown', (req, res) => {
|
|
546
|
-
try {
|
|
547
|
-
const totalSites = db.prepare('SELECT COUNT(*) as c FROM sites WHERE active = 1').get().c;
|
|
548
|
-
const tiers = db.prepare(`
|
|
549
|
-
SELECT tier, COUNT(*) as count
|
|
550
|
-
FROM sites
|
|
551
|
-
WHERE active = 1
|
|
552
|
-
GROUP BY tier
|
|
553
|
-
ORDER BY CASE tier
|
|
554
|
-
WHEN 'free' THEN 1
|
|
555
|
-
WHEN 'starter' THEN 2
|
|
556
|
-
WHEN 'pro' THEN 3
|
|
557
|
-
WHEN 'enterprise' THEN 4
|
|
558
|
-
END
|
|
559
|
-
`).all();
|
|
560
|
-
|
|
561
|
-
const breakdown = tiers.map(t => ({
|
|
562
|
-
tier: t.tier,
|
|
563
|
-
count: t.count,
|
|
564
|
-
percentage: totalSites > 0
|
|
565
|
-
? Math.round((t.count / totalSites) * 10000) / 100
|
|
566
|
-
: 0,
|
|
567
|
-
pricePerMonth: `$${((TIER_PRICES[t.tier] || 0) / 100).toFixed(2)}`,
|
|
568
|
-
}));
|
|
569
|
-
|
|
570
|
-
res.json({ totalActiveSites: totalSites, breakdown });
|
|
571
|
-
} catch (err) {
|
|
572
|
-
res.status(500).json({ error: err.message });
|
|
573
|
-
}
|
|
574
|
-
});
|
|
575
|
-
|
|
576
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
577
|
-
// System
|
|
578
|
-
// ═══════════════════════════════════════════════════════════════════════
|
|
579
|
-
|
|
580
|
-
router.get('/system/health', (req, res) => {
|
|
581
|
-
try {
|
|
582
|
-
const pageInfo = db.prepare('PRAGMA page_count').get();
|
|
583
|
-
const pageSizeInfo = db.prepare('PRAGMA page_size').get();
|
|
584
|
-
const dbSizeBytes = (pageInfo.page_count || 0) * (pageSizeInfo.page_size || 0);
|
|
585
|
-
|
|
586
|
-
const tables = db.prepare(
|
|
587
|
-
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
588
|
-
).all();
|
|
589
|
-
|
|
590
|
-
const tableStats = tables.map(t => {
|
|
591
|
-
const count = db.prepare(`SELECT COUNT(*) as c FROM "${t.name}"`).get().c;
|
|
592
|
-
return { table: t.name, rows: count };
|
|
593
|
-
});
|
|
594
|
-
|
|
595
|
-
res.json({
|
|
596
|
-
dbSizeBytes,
|
|
597
|
-
dbSizeMB: Math.round((dbSizeBytes / 1048576) * 100) / 100,
|
|
598
|
-
tableCount: tables.length,
|
|
599
|
-
tables: tableStats,
|
|
600
|
-
uptimeSeconds: Math.floor(process.uptime()),
|
|
601
|
-
nodeVersion: process.version,
|
|
602
|
-
memoryUsage: process.memoryUsage(),
|
|
603
|
-
});
|
|
604
|
-
} catch (err) {
|
|
605
|
-
res.status(500).json({ error: err.message });
|
|
606
|
-
}
|
|
607
|
-
});
|
|
608
|
-
|
|
609
|
-
router.post('/system/maintenance', (req, res) => {
|
|
610
|
-
try {
|
|
611
|
-
db.exec('ANALYZE');
|
|
612
|
-
|
|
613
|
-
const oldLogs = db.prepare(
|
|
614
|
-
"DELETE FROM analytics WHERE created_at < datetime('now', '-90 days')"
|
|
615
|
-
).run();
|
|
616
|
-
const oldHookExec = db.prepare(
|
|
617
|
-
"DELETE FROM hook_executions WHERE executed_at < datetime('now', '-90 days')"
|
|
618
|
-
).run();
|
|
619
|
-
const oldNotifications = db.prepare(
|
|
620
|
-
"DELETE FROM notifications_log WHERE created_at < datetime('now', '-90 days')"
|
|
621
|
-
).run();
|
|
622
|
-
|
|
623
|
-
db.exec('VACUUM');
|
|
624
|
-
|
|
625
|
-
res.json({
|
|
626
|
-
success: true,
|
|
627
|
-
vacuumed: true,
|
|
628
|
-
analyzed: true,
|
|
629
|
-
deletedOldAnalytics: oldLogs.changes,
|
|
630
|
-
deletedOldHookExecutions: oldHookExec.changes,
|
|
631
|
-
deletedOldNotifications: oldNotifications.changes,
|
|
632
|
-
});
|
|
633
|
-
} catch (err) {
|
|
634
|
-
res.status(500).json({ error: err.message });
|
|
635
|
-
}
|
|
636
|
-
});
|
|
637
|
-
|
|
638
|
-
router.get('/system/audit-log', (req, res) => {
|
|
639
|
-
try {
|
|
640
|
-
const limit = parseInt(req.query.limit) || 100;
|
|
641
|
-
|
|
642
|
-
const hasAuditLogs = db.prepare(
|
|
643
|
-
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'audit_logs'"
|
|
644
|
-
).get();
|
|
645
|
-
|
|
646
|
-
if (hasAuditLogs) {
|
|
647
|
-
const logs = db.prepare(`
|
|
648
|
-
SELECT al.*, s.name as site_name, s.domain
|
|
649
|
-
FROM audit_logs al
|
|
650
|
-
LEFT JOIN sites s ON al.site_id = s.id
|
|
651
|
-
ORDER BY al.created_at DESC
|
|
652
|
-
LIMIT ?
|
|
653
|
-
`).all(limit);
|
|
654
|
-
return res.json({ source: 'audit_logs', logs });
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
const logs = db.prepare(`
|
|
658
|
-
SELECT a.*, s.name as site_name, s.domain
|
|
659
|
-
FROM analytics a
|
|
660
|
-
LEFT JOIN sites s ON a.site_id = s.id
|
|
661
|
-
ORDER BY a.created_at DESC
|
|
662
|
-
LIMIT ?
|
|
663
|
-
`).all(limit);
|
|
664
|
-
|
|
665
|
-
res.json({ source: 'analytics', logs });
|
|
666
|
-
} catch (err) {
|
|
667
|
-
res.status(500).json({ error: err.message });
|
|
668
|
-
}
|
|
669
|
-
});
|
|
670
|
-
|
|
671
|
-
module.exports = router;
|
|
1
|
+
const express = require('express');
|
|
2
|
+
const router = express.Router();
|
|
3
|
+
const { authenticateAdmin } = require('../middleware/adminAuth');
|
|
4
|
+
const { db } = require('../models/db');
|
|
5
|
+
|
|
6
|
+
router.use(authenticateAdmin);
|
|
7
|
+
|
|
8
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
9
|
+
// Platform Overview
|
|
10
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
11
|
+
|
|
12
|
+
router.get('/overview/stats', (req, res) => {
|
|
13
|
+
try {
|
|
14
|
+
const totalUsers = db.prepare('SELECT COUNT(*) as c FROM users').get().c;
|
|
15
|
+
const totalSites = db.prepare('SELECT COUNT(*) as c FROM sites').get().c;
|
|
16
|
+
const activeSites = db.prepare('SELECT COUNT(*) as c FROM sites WHERE active = 1').get().c;
|
|
17
|
+
|
|
18
|
+
const revenue = db.prepare(
|
|
19
|
+
"SELECT COALESCE(SUM(amount), 0) as total FROM payments WHERE status = 'succeeded'"
|
|
20
|
+
).get().total;
|
|
21
|
+
|
|
22
|
+
const totalMemories = db.prepare('SELECT COUNT(*) as c FROM agent_memories').get().c;
|
|
23
|
+
const totalHealingEvents = db.prepare('SELECT COUNT(*) as c FROM healing_log').get().c;
|
|
24
|
+
const totalVisionAnalyses = db.prepare('SELECT COUNT(*) as c FROM vision_cache').get().c;
|
|
25
|
+
const totalSwarmTasks = db.prepare('SELECT COUNT(*) as c FROM swarm_tasks').get().c;
|
|
26
|
+
const pluginsInstalled = db.prepare('SELECT COUNT(*) as c FROM plugin_installations').get().c;
|
|
27
|
+
|
|
28
|
+
const newUsersLast7Days = db.prepare(
|
|
29
|
+
"SELECT COUNT(*) as c FROM users WHERE created_at >= datetime('now', '-7 days')"
|
|
30
|
+
).get().c;
|
|
31
|
+
const newSitesLast7Days = db.prepare(
|
|
32
|
+
"SELECT COUNT(*) as c FROM sites WHERE created_at >= datetime('now', '-7 days')"
|
|
33
|
+
).get().c;
|
|
34
|
+
|
|
35
|
+
const pageInfo = db.prepare('PRAGMA page_count').get();
|
|
36
|
+
const pageSizeInfo = db.prepare('PRAGMA page_size').get();
|
|
37
|
+
const dbSizeBytes = (pageInfo.page_count || 0) * (pageSizeInfo.page_size || 0);
|
|
38
|
+
|
|
39
|
+
res.json({
|
|
40
|
+
users: { total: totalUsers },
|
|
41
|
+
sites: { total: totalSites, active: activeSites },
|
|
42
|
+
revenue: { total: revenue },
|
|
43
|
+
premiumFeatures: {
|
|
44
|
+
totalMemories,
|
|
45
|
+
totalHealingEvents,
|
|
46
|
+
totalVisionAnalyses,
|
|
47
|
+
totalSwarmTasks,
|
|
48
|
+
pluginsInstalled,
|
|
49
|
+
},
|
|
50
|
+
growth: {
|
|
51
|
+
newUsersLast7Days,
|
|
52
|
+
newSitesLast7Days,
|
|
53
|
+
},
|
|
54
|
+
system: {
|
|
55
|
+
dbSizeBytes,
|
|
56
|
+
dbSizeMB: Math.round((dbSizeBytes / 1048576) * 100) / 100,
|
|
57
|
+
uptimeSeconds: Math.floor(process.uptime()),
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
} catch (err) {
|
|
61
|
+
res.status(500).json({ error: err.message });
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
66
|
+
// Memory Management
|
|
67
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
68
|
+
|
|
69
|
+
router.get('/memory/global-stats', (req, res) => {
|
|
70
|
+
try {
|
|
71
|
+
const total = db.prepare('SELECT COUNT(*) as c FROM agent_memories').get().c;
|
|
72
|
+
const active = db.prepare(
|
|
73
|
+
"SELECT COUNT(*) as c FROM agent_memories WHERE expires_at IS NULL OR expires_at > datetime('now')"
|
|
74
|
+
).get().c;
|
|
75
|
+
const expired = db.prepare(
|
|
76
|
+
"SELECT COUNT(*) as c FROM agent_memories WHERE expires_at IS NOT NULL AND expires_at <= datetime('now')"
|
|
77
|
+
).get().c;
|
|
78
|
+
|
|
79
|
+
const byType = db.prepare(
|
|
80
|
+
'SELECT memory_type, COUNT(*) as count FROM agent_memories GROUP BY memory_type'
|
|
81
|
+
).all();
|
|
82
|
+
const byCategory = db.prepare(
|
|
83
|
+
'SELECT category, COUNT(*) as count FROM agent_memories GROUP BY category'
|
|
84
|
+
).all();
|
|
85
|
+
|
|
86
|
+
const avgImportance = db.prepare(
|
|
87
|
+
'SELECT AVG(importance) as avg FROM agent_memories'
|
|
88
|
+
).get().avg || 0;
|
|
89
|
+
|
|
90
|
+
const storageBytes = db.prepare(
|
|
91
|
+
'SELECT SUM(LENGTH(key) + LENGTH(value) + COALESCE(LENGTH(embedding), 0)) as bytes FROM agent_memories'
|
|
92
|
+
).get().bytes || 0;
|
|
93
|
+
|
|
94
|
+
const totalSessions = db.prepare('SELECT COUNT(*) as c FROM memory_sessions').get().c;
|
|
95
|
+
const totalAssociations = db.prepare('SELECT COUNT(*) as c FROM memory_associations').get().c;
|
|
96
|
+
|
|
97
|
+
res.json({
|
|
98
|
+
total,
|
|
99
|
+
active,
|
|
100
|
+
expired,
|
|
101
|
+
byType,
|
|
102
|
+
byCategory,
|
|
103
|
+
avgImportance: Math.round(avgImportance * 1000) / 1000,
|
|
104
|
+
storageBytes,
|
|
105
|
+
totalSessions,
|
|
106
|
+
totalAssociations,
|
|
107
|
+
});
|
|
108
|
+
} catch (err) {
|
|
109
|
+
res.status(500).json({ error: err.message });
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
router.get('/memory/top-users', (req, res) => {
|
|
114
|
+
try {
|
|
115
|
+
const rows = db.prepare(`
|
|
116
|
+
SELECT am.site_id, s.name as site_name, s.domain, u.email as user_email,
|
|
117
|
+
COUNT(*) as memory_count,
|
|
118
|
+
SUM(LENGTH(am.key) + LENGTH(am.value)) as storage_bytes,
|
|
119
|
+
AVG(am.importance) as avg_importance
|
|
120
|
+
FROM agent_memories am
|
|
121
|
+
LEFT JOIN sites s ON am.site_id = s.id
|
|
122
|
+
LEFT JOIN users u ON s.user_id = u.id
|
|
123
|
+
GROUP BY am.site_id
|
|
124
|
+
ORDER BY memory_count DESC
|
|
125
|
+
LIMIT 20
|
|
126
|
+
`).all();
|
|
127
|
+
|
|
128
|
+
res.json({ topUsers: rows });
|
|
129
|
+
} catch (err) {
|
|
130
|
+
res.status(500).json({ error: err.message });
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
router.delete('/memory/cleanup', (req, res) => {
|
|
135
|
+
try {
|
|
136
|
+
const result = db.prepare(
|
|
137
|
+
"DELETE FROM agent_memories WHERE expires_at IS NOT NULL AND expires_at <= datetime('now')"
|
|
138
|
+
).run();
|
|
139
|
+
|
|
140
|
+
res.json({ purged: result.changes });
|
|
141
|
+
} catch (err) {
|
|
142
|
+
res.status(500).json({ error: err.message });
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
147
|
+
// Healing Management
|
|
148
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
149
|
+
|
|
150
|
+
router.get('/healing/global-stats', (req, res) => {
|
|
151
|
+
try {
|
|
152
|
+
const total = db.prepare('SELECT COUNT(*) as c FROM healing_log').get().c;
|
|
153
|
+
const successes = db.prepare('SELECT COUNT(*) as c FROM healing_log WHERE success = 1').get().c;
|
|
154
|
+
const successRate = total > 0 ? Math.round((successes / total) * 10000) / 100 : 0;
|
|
155
|
+
|
|
156
|
+
const topStrategies = db.prepare(`
|
|
157
|
+
SELECT strategy, COUNT(*) as count,
|
|
158
|
+
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successes,
|
|
159
|
+
AVG(confidence) as avg_confidence
|
|
160
|
+
FROM healing_log
|
|
161
|
+
GROUP BY strategy
|
|
162
|
+
ORDER BY count DESC
|
|
163
|
+
`).all();
|
|
164
|
+
|
|
165
|
+
const totalRegistered = db.prepare('SELECT COUNT(*) as c FROM selector_registry').get().c;
|
|
166
|
+
const totalCorrections = db.prepare('SELECT COUNT(*) as c FROM selector_corrections').get().c;
|
|
167
|
+
|
|
168
|
+
res.json({
|
|
169
|
+
total,
|
|
170
|
+
successes,
|
|
171
|
+
successRate,
|
|
172
|
+
topStrategies,
|
|
173
|
+
totalRegistered,
|
|
174
|
+
totalCorrections,
|
|
175
|
+
});
|
|
176
|
+
} catch (err) {
|
|
177
|
+
res.status(500).json({ error: err.message });
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
router.get('/healing/community-corrections', (req, res) => {
|
|
182
|
+
try {
|
|
183
|
+
const corrections = db.prepare(`
|
|
184
|
+
SELECT sc.*, s.name as site_name, s.domain
|
|
185
|
+
FROM selector_corrections sc
|
|
186
|
+
LEFT JOIN sites s ON sc.site_id = s.id
|
|
187
|
+
WHERE sc.shared = 1
|
|
188
|
+
ORDER BY sc.applied_count DESC, sc.created_at DESC
|
|
189
|
+
`).all();
|
|
190
|
+
|
|
191
|
+
res.json({ corrections });
|
|
192
|
+
} catch (err) {
|
|
193
|
+
res.status(500).json({ error: err.message });
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
router.get('/healing/broken-selectors', (req, res) => {
|
|
198
|
+
try {
|
|
199
|
+
const broken = db.prepare(`
|
|
200
|
+
SELECT sr.*, s.name as site_name, s.domain
|
|
201
|
+
FROM selector_registry sr
|
|
202
|
+
LEFT JOIN sites s ON sr.site_id = s.id
|
|
203
|
+
WHERE sr.confidence < 0.5
|
|
204
|
+
ORDER BY sr.confidence ASC
|
|
205
|
+
`).all();
|
|
206
|
+
|
|
207
|
+
res.json({ broken });
|
|
208
|
+
} catch (err) {
|
|
209
|
+
res.status(500).json({ error: err.message });
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
214
|
+
// Vision Management
|
|
215
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
216
|
+
|
|
217
|
+
router.get('/vision/global-stats', (req, res) => {
|
|
218
|
+
try {
|
|
219
|
+
const total = db.prepare('SELECT COUNT(*) as c FROM vision_cache').get().c;
|
|
220
|
+
const activeCached = db.prepare(
|
|
221
|
+
"SELECT COUNT(*) as c FROM vision_cache WHERE expires_at > datetime('now')"
|
|
222
|
+
).get().c;
|
|
223
|
+
const expiredCached = db.prepare(
|
|
224
|
+
"SELECT COUNT(*) as c FROM vision_cache WHERE expires_at <= datetime('now')"
|
|
225
|
+
).get().c;
|
|
226
|
+
const cacheHitRate = total > 0
|
|
227
|
+
? Math.round((activeCached / total) * 10000) / 100
|
|
228
|
+
: 0;
|
|
229
|
+
|
|
230
|
+
const providerUsage = db.prepare(`
|
|
231
|
+
SELECT provider, COUNT(*) as count,
|
|
232
|
+
SUM(tokens_used) as total_tokens,
|
|
233
|
+
AVG(latency_ms) as avg_latency
|
|
234
|
+
FROM vision_cache
|
|
235
|
+
GROUP BY provider
|
|
236
|
+
ORDER BY count DESC
|
|
237
|
+
`).all();
|
|
238
|
+
|
|
239
|
+
const totalTokens = db.prepare(
|
|
240
|
+
'SELECT COALESCE(SUM(tokens_used), 0) as t FROM vision_cache'
|
|
241
|
+
).get().t;
|
|
242
|
+
const avgLatency = db.prepare(
|
|
243
|
+
'SELECT COALESCE(AVG(latency_ms), 0) as avg FROM vision_cache'
|
|
244
|
+
).get().avg;
|
|
245
|
+
const totalElements = db.prepare('SELECT COUNT(*) as c FROM vision_elements').get().c;
|
|
246
|
+
|
|
247
|
+
res.json({
|
|
248
|
+
totalAnalyses: total,
|
|
249
|
+
activeCached,
|
|
250
|
+
expiredCached,
|
|
251
|
+
cacheHitRate,
|
|
252
|
+
providerUsage,
|
|
253
|
+
totalTokens,
|
|
254
|
+
avgLatencyMs: Math.round(avgLatency),
|
|
255
|
+
totalElements,
|
|
256
|
+
});
|
|
257
|
+
} catch (err) {
|
|
258
|
+
res.status(500).json({ error: err.message });
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
router.get('/vision/usage-by-site', (req, res) => {
|
|
263
|
+
try {
|
|
264
|
+
const rows = db.prepare(`
|
|
265
|
+
SELECT vc.site_id, s.name as site_name, s.domain,
|
|
266
|
+
COUNT(*) as analyses_count,
|
|
267
|
+
SUM(vc.tokens_used) as total_tokens,
|
|
268
|
+
AVG(vc.latency_ms) as avg_latency
|
|
269
|
+
FROM vision_cache vc
|
|
270
|
+
LEFT JOIN sites s ON vc.site_id = s.id
|
|
271
|
+
GROUP BY vc.site_id
|
|
272
|
+
ORDER BY analyses_count DESC
|
|
273
|
+
`).all();
|
|
274
|
+
|
|
275
|
+
res.json({ usageBySite: rows });
|
|
276
|
+
} catch (err) {
|
|
277
|
+
res.status(500).json({ error: err.message });
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
router.delete('/vision/purge-cache', (req, res) => {
|
|
282
|
+
try {
|
|
283
|
+
const cacheResult = db.prepare(
|
|
284
|
+
"DELETE FROM vision_cache WHERE expires_at <= datetime('now')"
|
|
285
|
+
).run();
|
|
286
|
+
const elemResult = db.prepare(
|
|
287
|
+
'DELETE FROM vision_elements WHERE cache_id NOT IN (SELECT id FROM vision_cache)'
|
|
288
|
+
).run();
|
|
289
|
+
|
|
290
|
+
res.json({
|
|
291
|
+
purgedCacheEntries: cacheResult.changes,
|
|
292
|
+
orphanedElementsCleaned: elemResult.changes,
|
|
293
|
+
});
|
|
294
|
+
} catch (err) {
|
|
295
|
+
res.status(500).json({ error: err.message });
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
300
|
+
// Swarm Management
|
|
301
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
302
|
+
|
|
303
|
+
router.get('/swarm/global-stats', (req, res) => {
|
|
304
|
+
try {
|
|
305
|
+
const total = db.prepare('SELECT COUNT(*) as c FROM swarm_tasks').get().c;
|
|
306
|
+
const completed = db.prepare(
|
|
307
|
+
"SELECT COUNT(*) as c FROM swarm_tasks WHERE status = 'completed'"
|
|
308
|
+
).get().c;
|
|
309
|
+
const failed = db.prepare(
|
|
310
|
+
"SELECT COUNT(*) as c FROM swarm_tasks WHERE status = 'failed'"
|
|
311
|
+
).get().c;
|
|
312
|
+
const running = db.prepare(
|
|
313
|
+
"SELECT COUNT(*) as c FROM swarm_tasks WHERE status = 'running'"
|
|
314
|
+
).get().c;
|
|
315
|
+
const successRate = total > 0 ? Math.round((completed / total) * 10000) / 100 : 0;
|
|
316
|
+
|
|
317
|
+
const avgAgentsRow = db.prepare(`
|
|
318
|
+
SELECT AVG(agent_count) as avg_agents FROM (
|
|
319
|
+
SELECT COUNT(*) as agent_count FROM swarm_agents
|
|
320
|
+
GROUP BY task_id
|
|
321
|
+
)
|
|
322
|
+
`).get();
|
|
323
|
+
const avgAgents = avgAgentsRow ? Math.round((avgAgentsRow.avg_agents || 0) * 100) / 100 : 0;
|
|
324
|
+
|
|
325
|
+
const taskTypeBreakdown = db.prepare(`
|
|
326
|
+
SELECT task_type, COUNT(*) as count,
|
|
327
|
+
SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed
|
|
328
|
+
FROM swarm_tasks
|
|
329
|
+
GROUP BY task_type
|
|
330
|
+
`).all();
|
|
331
|
+
|
|
332
|
+
res.json({
|
|
333
|
+
total,
|
|
334
|
+
completed,
|
|
335
|
+
failed,
|
|
336
|
+
running,
|
|
337
|
+
successRate,
|
|
338
|
+
avgAgentsPerTask: avgAgents,
|
|
339
|
+
taskTypeBreakdown,
|
|
340
|
+
});
|
|
341
|
+
} catch (err) {
|
|
342
|
+
res.status(500).json({ error: err.message });
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
router.get('/swarm/active-tasks', (req, res) => {
|
|
347
|
+
try {
|
|
348
|
+
const tasks = db.prepare(`
|
|
349
|
+
SELECT st.*, s.name as site_name, s.domain
|
|
350
|
+
FROM swarm_tasks st
|
|
351
|
+
LEFT JOIN sites s ON st.site_id = s.id
|
|
352
|
+
WHERE st.status IN ('pending', 'running')
|
|
353
|
+
ORDER BY st.created_at DESC
|
|
354
|
+
`).all();
|
|
355
|
+
|
|
356
|
+
const enriched = tasks.map(t => {
|
|
357
|
+
const agents = db.prepare(
|
|
358
|
+
'SELECT id, agent_role, agent_type, target, status, score FROM swarm_agents WHERE task_id = ?'
|
|
359
|
+
).all(t.id);
|
|
360
|
+
return { ...t, agents };
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
res.json({ activeTasks: enriched });
|
|
364
|
+
} catch (err) {
|
|
365
|
+
res.status(500).json({ error: err.message });
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
router.post('/swarm/cancel-all', (req, res) => {
|
|
370
|
+
try {
|
|
371
|
+
const now = new Date().toISOString();
|
|
372
|
+
|
|
373
|
+
const runningTasks = db.prepare(
|
|
374
|
+
"SELECT id FROM swarm_tasks WHERE status IN ('pending', 'running')"
|
|
375
|
+
).all();
|
|
376
|
+
|
|
377
|
+
const cancelTx = db.transaction(() => {
|
|
378
|
+
for (const task of runningTasks) {
|
|
379
|
+
db.prepare(
|
|
380
|
+
"UPDATE swarm_tasks SET status = 'cancelled', completed_at = ? WHERE id = ?"
|
|
381
|
+
).run(now, task.id);
|
|
382
|
+
db.prepare(
|
|
383
|
+
"UPDATE swarm_agents SET status = 'cancelled' WHERE task_id = ? AND status IN ('idle', 'running')"
|
|
384
|
+
).run(task.id);
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
cancelTx();
|
|
388
|
+
|
|
389
|
+
res.json({ cancelledTasks: runningTasks.length });
|
|
390
|
+
} catch (err) {
|
|
391
|
+
res.status(500).json({ error: err.message });
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
396
|
+
// Plugin Management
|
|
397
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
398
|
+
|
|
399
|
+
router.get('/plugins/all', (req, res) => {
|
|
400
|
+
try {
|
|
401
|
+
const plugins = db.prepare(`
|
|
402
|
+
SELECT pr.*,
|
|
403
|
+
(SELECT COUNT(*) FROM plugin_installations pi WHERE pi.plugin_id = pr.id) as installation_count
|
|
404
|
+
FROM plugin_registry pr
|
|
405
|
+
ORDER BY pr.created_at DESC
|
|
406
|
+
`).all();
|
|
407
|
+
|
|
408
|
+
res.json({ plugins });
|
|
409
|
+
} catch (err) {
|
|
410
|
+
res.status(500).json({ error: err.message });
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
router.put('/plugins/:pluginId/toggle', (req, res) => {
|
|
415
|
+
try {
|
|
416
|
+
const { pluginId } = req.params;
|
|
417
|
+
const plugin = db.prepare('SELECT * FROM plugin_registry WHERE id = ?').get(pluginId);
|
|
418
|
+
if (!plugin) return res.status(404).json({ error: 'Plugin not found' });
|
|
419
|
+
|
|
420
|
+
const newEnabled = plugin.enabled ? 0 : 1;
|
|
421
|
+
db.prepare(
|
|
422
|
+
"UPDATE plugin_registry SET enabled = ?, updated_at = datetime('now') WHERE id = ?"
|
|
423
|
+
).run(newEnabled, pluginId);
|
|
424
|
+
|
|
425
|
+
res.json({ pluginId, enabled: !!newEnabled });
|
|
426
|
+
} catch (err) {
|
|
427
|
+
res.status(500).json({ error: err.message });
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
router.get('/plugins/hook-stats', (req, res) => {
|
|
432
|
+
try {
|
|
433
|
+
const stats = db.prepare(`
|
|
434
|
+
SELECT hook_name,
|
|
435
|
+
COUNT(*) as total_executions,
|
|
436
|
+
SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successes,
|
|
437
|
+
ROUND(CAST(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) AS REAL) / COUNT(*) * 100, 2) as success_rate,
|
|
438
|
+
AVG(duration_ms) as avg_duration_ms
|
|
439
|
+
FROM hook_executions
|
|
440
|
+
GROUP BY hook_name
|
|
441
|
+
ORDER BY total_executions DESC
|
|
442
|
+
`).all();
|
|
443
|
+
|
|
444
|
+
res.json({ hookStats: stats });
|
|
445
|
+
} catch (err) {
|
|
446
|
+
res.status(500).json({ error: err.message });
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
router.delete('/plugins/:pluginId', (req, res) => {
|
|
451
|
+
try {
|
|
452
|
+
const { pluginId } = req.params;
|
|
453
|
+
const plugin = db.prepare('SELECT * FROM plugin_registry WHERE id = ?').get(pluginId);
|
|
454
|
+
if (!plugin) return res.status(404).json({ error: 'Plugin not found' });
|
|
455
|
+
|
|
456
|
+
const removeTx = db.transaction(() => {
|
|
457
|
+
db.prepare('DELETE FROM plugin_installations WHERE plugin_id = ?').run(pluginId);
|
|
458
|
+
db.prepare('DELETE FROM plugin_hooks WHERE plugin_id = ?').run(pluginId);
|
|
459
|
+
db.prepare('DELETE FROM hook_executions WHERE plugin_id = ?').run(pluginId);
|
|
460
|
+
db.prepare('DELETE FROM plugin_registry WHERE id = ?').run(pluginId);
|
|
461
|
+
});
|
|
462
|
+
removeTx();
|
|
463
|
+
|
|
464
|
+
res.json({ removed: true, pluginId, name: plugin.name });
|
|
465
|
+
} catch (err) {
|
|
466
|
+
res.status(500).json({ error: err.message });
|
|
467
|
+
}
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
471
|
+
// Revenue
|
|
472
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
473
|
+
|
|
474
|
+
function getTierPrices() {
|
|
475
|
+
const plans = db.prepare('SELECT tier, price FROM plans').all();
|
|
476
|
+
const prices = { free: 0, starter: 900, pro: 2900, enterprise: 9900 };
|
|
477
|
+
for (const p of plans) prices[p.tier] = p.price;
|
|
478
|
+
return prices;
|
|
479
|
+
}
|
|
480
|
+
const TIER_PRICES = new Proxy({}, { get: function(_, tier) { return getTierPrices()[tier] || 0; } });
|
|
481
|
+
|
|
482
|
+
router.get('/revenue/summary', (req, res) => {
|
|
483
|
+
try {
|
|
484
|
+
const tierCounts = db.prepare(`
|
|
485
|
+
SELECT tier, COUNT(*) as count
|
|
486
|
+
FROM subscriptions
|
|
487
|
+
WHERE status = 'active'
|
|
488
|
+
GROUP BY tier
|
|
489
|
+
`).all();
|
|
490
|
+
|
|
491
|
+
let mrr = 0;
|
|
492
|
+
for (const row of tierCounts) {
|
|
493
|
+
mrr += (TIER_PRICES[row.tier] || 0) * row.count;
|
|
494
|
+
}
|
|
495
|
+
const arr = mrr * 12;
|
|
496
|
+
|
|
497
|
+
const totalActive = db.prepare(
|
|
498
|
+
"SELECT COUNT(*) as c FROM subscriptions WHERE status = 'active'"
|
|
499
|
+
).get().c;
|
|
500
|
+
const cancelledLast30 = db.prepare(
|
|
501
|
+
"SELECT COUNT(*) as c FROM subscriptions WHERE status = 'cancelled' AND started_at >= datetime('now', '-30 days')"
|
|
502
|
+
).get().c;
|
|
503
|
+
const churnRate = totalActive > 0
|
|
504
|
+
? Math.round((cancelledLast30 / (totalActive + cancelledLast30)) * 10000) / 100
|
|
505
|
+
: 0;
|
|
506
|
+
|
|
507
|
+
const arpu = totalActive > 0 ? Math.round(mrr / totalActive) : 0;
|
|
508
|
+
|
|
509
|
+
res.json({
|
|
510
|
+
mrr,
|
|
511
|
+
mrrFormatted: `$${(mrr / 100).toFixed(2)}`,
|
|
512
|
+
arr,
|
|
513
|
+
arrFormatted: `$${(arr / 100).toFixed(2)}`,
|
|
514
|
+
churnRate,
|
|
515
|
+
arpu,
|
|
516
|
+
arpuFormatted: `$${(arpu / 100).toFixed(2)}`,
|
|
517
|
+
activeSubscriptions: totalActive,
|
|
518
|
+
cancelledLast30Days: cancelledLast30,
|
|
519
|
+
tierCounts,
|
|
520
|
+
});
|
|
521
|
+
} catch (err) {
|
|
522
|
+
res.status(500).json({ error: err.message });
|
|
523
|
+
}
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
router.get('/revenue/timeline', (req, res) => {
|
|
527
|
+
try {
|
|
528
|
+
const rows = db.prepare(`
|
|
529
|
+
SELECT strftime('%Y-%m', created_at) as month,
|
|
530
|
+
SUM(amount) as total_amount,
|
|
531
|
+
COUNT(*) as payment_count
|
|
532
|
+
FROM payments
|
|
533
|
+
WHERE status = 'succeeded'
|
|
534
|
+
AND created_at >= datetime('now', '-12 months')
|
|
535
|
+
GROUP BY month
|
|
536
|
+
ORDER BY month ASC
|
|
537
|
+
`).all();
|
|
538
|
+
|
|
539
|
+
res.json({ timeline: rows });
|
|
540
|
+
} catch (err) {
|
|
541
|
+
res.status(500).json({ error: err.message });
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
router.get('/revenue/tier-breakdown', (req, res) => {
|
|
546
|
+
try {
|
|
547
|
+
const totalSites = db.prepare('SELECT COUNT(*) as c FROM sites WHERE active = 1').get().c;
|
|
548
|
+
const tiers = db.prepare(`
|
|
549
|
+
SELECT tier, COUNT(*) as count
|
|
550
|
+
FROM sites
|
|
551
|
+
WHERE active = 1
|
|
552
|
+
GROUP BY tier
|
|
553
|
+
ORDER BY CASE tier
|
|
554
|
+
WHEN 'free' THEN 1
|
|
555
|
+
WHEN 'starter' THEN 2
|
|
556
|
+
WHEN 'pro' THEN 3
|
|
557
|
+
WHEN 'enterprise' THEN 4
|
|
558
|
+
END
|
|
559
|
+
`).all();
|
|
560
|
+
|
|
561
|
+
const breakdown = tiers.map(t => ({
|
|
562
|
+
tier: t.tier,
|
|
563
|
+
count: t.count,
|
|
564
|
+
percentage: totalSites > 0
|
|
565
|
+
? Math.round((t.count / totalSites) * 10000) / 100
|
|
566
|
+
: 0,
|
|
567
|
+
pricePerMonth: `$${((TIER_PRICES[t.tier] || 0) / 100).toFixed(2)}`,
|
|
568
|
+
}));
|
|
569
|
+
|
|
570
|
+
res.json({ totalActiveSites: totalSites, breakdown });
|
|
571
|
+
} catch (err) {
|
|
572
|
+
res.status(500).json({ error: err.message });
|
|
573
|
+
}
|
|
574
|
+
});
|
|
575
|
+
|
|
576
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
577
|
+
// System
|
|
578
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
579
|
+
|
|
580
|
+
router.get('/system/health', (req, res) => {
|
|
581
|
+
try {
|
|
582
|
+
const pageInfo = db.prepare('PRAGMA page_count').get();
|
|
583
|
+
const pageSizeInfo = db.prepare('PRAGMA page_size').get();
|
|
584
|
+
const dbSizeBytes = (pageInfo.page_count || 0) * (pageSizeInfo.page_size || 0);
|
|
585
|
+
|
|
586
|
+
const tables = db.prepare(
|
|
587
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
588
|
+
).all();
|
|
589
|
+
|
|
590
|
+
const tableStats = tables.map(t => {
|
|
591
|
+
const count = db.prepare(`SELECT COUNT(*) as c FROM "${t.name}"`).get().c;
|
|
592
|
+
return { table: t.name, rows: count };
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
res.json({
|
|
596
|
+
dbSizeBytes,
|
|
597
|
+
dbSizeMB: Math.round((dbSizeBytes / 1048576) * 100) / 100,
|
|
598
|
+
tableCount: tables.length,
|
|
599
|
+
tables: tableStats,
|
|
600
|
+
uptimeSeconds: Math.floor(process.uptime()),
|
|
601
|
+
nodeVersion: process.version,
|
|
602
|
+
memoryUsage: process.memoryUsage(),
|
|
603
|
+
});
|
|
604
|
+
} catch (err) {
|
|
605
|
+
res.status(500).json({ error: err.message });
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
router.post('/system/maintenance', (req, res) => {
|
|
610
|
+
try {
|
|
611
|
+
db.exec('ANALYZE');
|
|
612
|
+
|
|
613
|
+
const oldLogs = db.prepare(
|
|
614
|
+
"DELETE FROM analytics WHERE created_at < datetime('now', '-90 days')"
|
|
615
|
+
).run();
|
|
616
|
+
const oldHookExec = db.prepare(
|
|
617
|
+
"DELETE FROM hook_executions WHERE executed_at < datetime('now', '-90 days')"
|
|
618
|
+
).run();
|
|
619
|
+
const oldNotifications = db.prepare(
|
|
620
|
+
"DELETE FROM notifications_log WHERE created_at < datetime('now', '-90 days')"
|
|
621
|
+
).run();
|
|
622
|
+
|
|
623
|
+
db.exec('VACUUM');
|
|
624
|
+
|
|
625
|
+
res.json({
|
|
626
|
+
success: true,
|
|
627
|
+
vacuumed: true,
|
|
628
|
+
analyzed: true,
|
|
629
|
+
deletedOldAnalytics: oldLogs.changes,
|
|
630
|
+
deletedOldHookExecutions: oldHookExec.changes,
|
|
631
|
+
deletedOldNotifications: oldNotifications.changes,
|
|
632
|
+
});
|
|
633
|
+
} catch (err) {
|
|
634
|
+
res.status(500).json({ error: err.message });
|
|
635
|
+
}
|
|
636
|
+
});
|
|
637
|
+
|
|
638
|
+
router.get('/system/audit-log', (req, res) => {
|
|
639
|
+
try {
|
|
640
|
+
const limit = parseInt(req.query.limit) || 100;
|
|
641
|
+
|
|
642
|
+
const hasAuditLogs = db.prepare(
|
|
643
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'audit_logs'"
|
|
644
|
+
).get();
|
|
645
|
+
|
|
646
|
+
if (hasAuditLogs) {
|
|
647
|
+
const logs = db.prepare(`
|
|
648
|
+
SELECT al.*, s.name as site_name, s.domain
|
|
649
|
+
FROM audit_logs al
|
|
650
|
+
LEFT JOIN sites s ON al.site_id = s.id
|
|
651
|
+
ORDER BY al.created_at DESC
|
|
652
|
+
LIMIT ?
|
|
653
|
+
`).all(limit);
|
|
654
|
+
return res.json({ source: 'audit_logs', logs });
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
const logs = db.prepare(`
|
|
658
|
+
SELECT a.*, s.name as site_name, s.domain
|
|
659
|
+
FROM analytics a
|
|
660
|
+
LEFT JOIN sites s ON a.site_id = s.id
|
|
661
|
+
ORDER BY a.created_at DESC
|
|
662
|
+
LIMIT ?
|
|
663
|
+
`).all(limit);
|
|
664
|
+
|
|
665
|
+
res.json({ source: 'analytics', logs });
|
|
666
|
+
} catch (err) {
|
|
667
|
+
res.status(500).json({ error: err.message });
|
|
668
|
+
}
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
module.exports = router;
|