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,367 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * WAB Business Model Configuration
5
+ *
6
+ * Defines what is OPEN (free core for adoption) and what is CLOSED (paid for revenue).
7
+ *
8
+ * Principle: "Open what creates network effects. Close what creates operational value."
9
+ *
10
+ * OPEN (Core — free forever):
11
+ * - WAP Protocol (schema, discovery, permissions)
12
+ * - SDK + Client Runtime (JS, integrations)
13
+ * - Browser Execution Layer (basic)
14
+ * - Adapters (MCP, REST, Browser)
15
+ * - Registry (read-only — search commands, sites, templates)
16
+ * - Basic agent registration & authentication
17
+ *
18
+ * CLOSED (Paid — revenue layer):
19
+ * - Workspace / Control Plane (dashboard, monitoring, agent management)
20
+ * - Advanced Orchestration (scheduling, retries, pipelines, distributed exec)
21
+ * - Observability (tracing, analytics, performance insights)
22
+ * - Enterprise Security (signing, audit logs, compliance, IP allowlists)
23
+ * - Hosted Runtime (cloud execution, auto-scaling)
24
+ * - Marketplace commissions (10-20%)
25
+ */
26
+
27
+ // ─── Plans ──────────────────────────────────────────────────────────────
28
+
29
+ const PLANS = {
30
+ free: {
31
+ id: 'free',
32
+ name: 'Free',
33
+ price: 0,
34
+ interval: 'month',
35
+ description: 'Core WAP protocol + SDK for developers & site integration',
36
+ limits: {
37
+ agents: 3,
38
+ tasksPerDay: 50,
39
+ executionsPerDay: 100,
40
+ sessions: 5,
41
+ maxConcurrency: 2,
42
+ replayRecordings: 10,
43
+ computeMinutesPerDay: 10,
44
+ storageMB: 50,
45
+ webhooks: 1,
46
+ customAgents: 1,
47
+ apiCallsPerMinute: 20,
48
+ },
49
+ features: {
50
+ // OPEN — always available
51
+ protocol: true,
52
+ sdk: true,
53
+ browserExecution: true,
54
+ adapters: true, // MCP, REST, Browser adapters
55
+ registryRead: true, // Browse commands, sites, templates
56
+ agentRegistration: true,
57
+ basicAuth: true,
58
+ discovery: true, // /.well-known/agent-tools.json
59
+ capabilityNegotiation: true,
60
+ semanticActions: true, // Basic semantic actions
61
+ communityTemplates: true,
62
+
63
+ // CLOSED — not available on free
64
+ workspace: false,
65
+ advancedOrchestration: false,
66
+ observability: false,
67
+ enterpriseSecurity: false,
68
+ hostedRuntime: false,
69
+ marketplace: false,
70
+ failureAnalysis: false,
71
+ replayEngine: false,
72
+ certification: false,
73
+ llmInference: false,
74
+ prioritySupport: false,
75
+ customDomain: false,
76
+ sla: false,
77
+ auditLog: false,
78
+ advancedAnalytics: false,
79
+ dataExtraction: false,
80
+ trafficIntelligence: false,
81
+ exploitShield: false,
82
+ visionAnalysis: false,
83
+ swarmExecution: false,
84
+ agentMemory: false,
85
+ },
86
+ },
87
+
88
+ starter: {
89
+ id: 'starter',
90
+ name: 'Starter',
91
+ price: 29,
92
+ interval: 'month',
93
+ stripePrice: process.env.STRIPE_PRICE_STARTER,
94
+ description: 'For developers building production agents',
95
+ limits: {
96
+ agents: 10,
97
+ tasksPerDay: 500,
98
+ executionsPerDay: 1000,
99
+ sessions: 25,
100
+ maxConcurrency: 5,
101
+ replayRecordings: 100,
102
+ computeMinutesPerDay: 60,
103
+ storageMB: 500,
104
+ webhooks: 5,
105
+ customAgents: 5,
106
+ apiCallsPerMinute: 60,
107
+ },
108
+ features: {
109
+ // OPEN
110
+ protocol: true,
111
+ sdk: true,
112
+ browserExecution: true,
113
+ adapters: true,
114
+ registryRead: true,
115
+ agentRegistration: true,
116
+ basicAuth: true,
117
+ discovery: true,
118
+ capabilityNegotiation: true,
119
+ semanticActions: true,
120
+ communityTemplates: true,
121
+
122
+ // PAID — now available
123
+ workspace: true,
124
+ advancedOrchestration: true,
125
+ observability: true, // Basic observability (metrics, logs)
126
+ failureAnalysis: true,
127
+ replayEngine: true,
128
+ llmInference: true,
129
+ advancedAnalytics: true,
130
+ dataExtraction: true,
131
+ agentMemory: true,
132
+
133
+ // Still closed
134
+ enterpriseSecurity: false,
135
+ hostedRuntime: false,
136
+ marketplace: false,
137
+ certification: false,
138
+ prioritySupport: false,
139
+ customDomain: false,
140
+ sla: false,
141
+ auditLog: false,
142
+ trafficIntelligence: false,
143
+ exploitShield: false,
144
+ visionAnalysis: false,
145
+ swarmExecution: false,
146
+ },
147
+ },
148
+
149
+ pro: {
150
+ id: 'pro',
151
+ name: 'Pro',
152
+ price: 99,
153
+ interval: 'month',
154
+ stripePrice: process.env.STRIPE_PRICE_PRO,
155
+ description: 'For teams & companies running agents at scale',
156
+ limits: {
157
+ agents: 50,
158
+ tasksPerDay: 5000,
159
+ executionsPerDay: 10000,
160
+ sessions: 100,
161
+ maxConcurrency: 20,
162
+ replayRecordings: 1000,
163
+ computeMinutesPerDay: 300,
164
+ storageMB: 5000,
165
+ webhooks: 25,
166
+ customAgents: 25,
167
+ apiCallsPerMinute: 200,
168
+ },
169
+ features: {
170
+ // All OPEN
171
+ protocol: true, sdk: true, browserExecution: true, adapters: true,
172
+ registryRead: true, agentRegistration: true, basicAuth: true,
173
+ discovery: true, capabilityNegotiation: true, semanticActions: true,
174
+ communityTemplates: true,
175
+
176
+ // All Starter features
177
+ workspace: true, advancedOrchestration: true, observability: true,
178
+ failureAnalysis: true, replayEngine: true, llmInference: true,
179
+ advancedAnalytics: true, dataExtraction: true, agentMemory: true,
180
+
181
+ // New in Pro
182
+ hostedRuntime: true,
183
+ marketplace: true, // Publish & sell on marketplace
184
+ certification: true,
185
+ trafficIntelligence: true,
186
+ exploitShield: true,
187
+ visionAnalysis: true,
188
+ swarmExecution: true,
189
+ auditLog: true,
190
+ customDomain: true,
191
+
192
+ // Enterprise only
193
+ enterpriseSecurity: false,
194
+ prioritySupport: false,
195
+ sla: false,
196
+ },
197
+ },
198
+
199
+ enterprise: {
200
+ id: 'enterprise',
201
+ name: 'Enterprise',
202
+ price: null, // Custom pricing
203
+ interval: 'month',
204
+ stripePrice: process.env.STRIPE_PRICE_ENTERPRISE,
205
+ description: 'For organizations needing security, compliance & dedicated support',
206
+ limits: {
207
+ agents: -1, // Unlimited
208
+ tasksPerDay: -1,
209
+ executionsPerDay: -1,
210
+ sessions: -1,
211
+ maxConcurrency: 100,
212
+ replayRecordings: -1,
213
+ computeMinutesPerDay: -1,
214
+ storageMB: -1,
215
+ webhooks: -1,
216
+ customAgents: -1,
217
+ apiCallsPerMinute: 1000,
218
+ },
219
+ features: {
220
+ // Everything
221
+ protocol: true, sdk: true, browserExecution: true, adapters: true,
222
+ registryRead: true, agentRegistration: true, basicAuth: true,
223
+ discovery: true, capabilityNegotiation: true, semanticActions: true,
224
+ communityTemplates: true,
225
+ workspace: true, advancedOrchestration: true, observability: true,
226
+ failureAnalysis: true, replayEngine: true, llmInference: true,
227
+ advancedAnalytics: true, dataExtraction: true, agentMemory: true,
228
+ hostedRuntime: true, marketplace: true, certification: true,
229
+ trafficIntelligence: true, exploitShield: true, visionAnalysis: true,
230
+ swarmExecution: true, auditLog: true, customDomain: true,
231
+
232
+ // Enterprise exclusive
233
+ enterpriseSecurity: true,
234
+ prioritySupport: true,
235
+ sla: true,
236
+ },
237
+ },
238
+ };
239
+
240
+ // ─── Usage-Based Pricing (Pay-as-you-go overages) ───────────────────
241
+
242
+ const USAGE_PRICING = {
243
+ execution: { unit: 'execution', price: 0.001, description: '$0.001 per execution beyond plan limit' },
244
+ computeMinute: { unit: 'minute', price: 0.01, description: '$0.01 per compute minute beyond plan limit' },
245
+ storage: { unit: 'MB', price: 0.05, description: '$0.05 per MB/month beyond plan limit' },
246
+ llmToken: { unit: '1K tokens', price: 0.002, description: '$0.002 per 1K tokens (pass-through + margin)' },
247
+ agent: { unit: 'agent', price: 2.00, description: '$2/month per additional agent beyond plan limit' },
248
+ };
249
+
250
+ // ─── Marketplace Commissions ────────────────────────────────────────
251
+
252
+ const MARKETPLACE = {
253
+ commission: 0.15, // 15% platform fee
254
+ minPrice: 0.99,
255
+ maxPrice: 999.99,
256
+ payoutThreshold: 25.00, // Minimum balance for payout
257
+ categories: [
258
+ 'automation', 'scraping', 'commerce', 'analytics',
259
+ 'security', 'integration', 'ai-agent', 'template',
260
+ 'adapter', 'plugin',
261
+ ],
262
+ };
263
+
264
+ // ─── Feature Gate Mapping ───────────────────────────────────────────
265
+ // Maps API path patterns to required features
266
+
267
+ const FEATURE_GATES = {
268
+ // Advanced orchestration
269
+ '/tasks': { feature: 'advancedOrchestration', methods: ['POST'] },
270
+ '/tasks/*/pause': { feature: 'advancedOrchestration', methods: ['POST'] },
271
+ '/tasks/*/resume': { feature: 'advancedOrchestration', methods: ['POST'] },
272
+ '/execute/pipeline': { feature: 'advancedOrchestration', methods: ['POST'] },
273
+
274
+ // Observability (write/analysis — reads are free for basic health)
275
+ '/observability/metrics': { feature: 'observability', methods: ['GET'] },
276
+ '/observability/traces': { feature: 'observability', methods: ['GET'] },
277
+ '/observability/logs': { feature: 'observability', methods: ['GET'] },
278
+
279
+ // Replay engine
280
+ '/replay': { feature: 'replayEngine', methods: ['GET', 'POST'] },
281
+
282
+ // Failure analysis
283
+ '/failures': { feature: 'failureAnalysis', methods: ['GET', 'POST'] },
284
+
285
+ // Sessions (beyond free limit)
286
+ '/sessions': { feature: 'workspace', methods: ['POST'] },
287
+
288
+ // Certification
289
+ '/certification/verify': { feature: 'certification', methods: ['POST'] },
290
+
291
+ // LLM
292
+ '/llm/complete': { feature: 'llmInference', methods: ['POST'] },
293
+ '/llm/embed': { feature: 'llmInference', methods: ['POST'] },
294
+
295
+ // Control plane
296
+ '/deployments': { feature: 'workspace', methods: ['POST'] },
297
+ '/policies': { feature: 'workspace', methods: ['POST'] },
298
+
299
+ // Signing (enterprise)
300
+ '/sign': { feature: 'enterpriseSecurity', methods: ['POST'] },
301
+ '/verify': { feature: 'enterpriseSecurity', methods: ['POST'] },
302
+
303
+ // Swarm
304
+ '/premium/v2/swarm': { feature: 'swarmExecution', methods: ['POST'] },
305
+
306
+ // Vision
307
+ '/premium/v2/vision': { feature: 'visionAnalysis', methods: ['POST'] },
308
+
309
+ // Marketplace
310
+ '/marketplace/publish': { feature: 'marketplace', methods: ['POST'] },
311
+ };
312
+
313
+ // ─── Helpers ────────────────────────────────────────────────────────
314
+
315
+ function getPlan(tier) {
316
+ return PLANS[tier] || PLANS.free;
317
+ }
318
+
319
+ function getLimit(tier, limitName) {
320
+ const plan = getPlan(tier);
321
+ return plan.limits[limitName] ?? 0;
322
+ }
323
+
324
+ function hasFeature(tier, featureName) {
325
+ const plan = getPlan(tier);
326
+ return plan.features[featureName] === true;
327
+ }
328
+
329
+ function isUnlimited(tier, limitName) {
330
+ return getLimit(tier, limitName) === -1;
331
+ }
332
+
333
+ function listPlans(includeEnterprise = true) {
334
+ const plans = Object.values(PLANS);
335
+ return includeEnterprise ? plans : plans.filter(p => p.id !== 'enterprise');
336
+ }
337
+
338
+ function getUpgradePath(currentTier) {
339
+ const order = ['free', 'starter', 'pro', 'enterprise'];
340
+ const idx = order.indexOf(currentTier);
341
+ if (idx === -1 || idx >= order.length - 1) return null;
342
+ return PLANS[order[idx + 1]];
343
+ }
344
+
345
+ function checkFeatureGate(path, method) {
346
+ for (const [pattern, gate] of Object.entries(FEATURE_GATES)) {
347
+ const regex = new RegExp('^' + pattern.replace(/\*/g, '[^/]+') + '(/|$)');
348
+ if (regex.test(path) && gate.methods.includes(method)) {
349
+ return gate.feature;
350
+ }
351
+ }
352
+ return null; // No gate — free access
353
+ }
354
+
355
+ module.exports = {
356
+ PLANS,
357
+ USAGE_PRICING,
358
+ MARKETPLACE,
359
+ FEATURE_GATES,
360
+ getPlan,
361
+ getLimit,
362
+ hasFeature,
363
+ isUnlimited,
364
+ listPlans,
365
+ getUpgradePath,
366
+ checkFeatureGate,
367
+ };
package/server/index.js CHANGED
@@ -34,6 +34,7 @@ const workspaceRoutes = require('./routes/agent-workspace');
34
34
  const universalRoutes = require('./routes/universal');
35
35
  const runtimeRoutes = require('./routes/runtime');
36
36
  const { handleWebhookRequest } = require('./services/stripe');
37
+ const { runtime } = require('./runtime');
37
38
 
38
39
  const app = express();
39
40
  const PORT = process.env.PORT || 3000;
@@ -355,6 +356,9 @@ if (process.env.NODE_ENV !== 'test') {
355
356
  const server = http.createServer(app);
356
357
  setupWebSocket(server);
357
358
 
359
+ // Start Agent OS runtime
360
+ runtime.start();
361
+
358
362
  server.listen(PORT, () => {
359
363
  console.log(`\n ╔══════════════════════════════════════════╗`);
360
364
  console.log(` ║ Web Agent Bridge v${pkg.version} ║`);
@@ -0,0 +1,88 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Feature Gate Middleware for Agent OS
5
+ *
6
+ * Enforces plan-based access control on /api/os/* endpoints.
7
+ * Checks tier features and usage limits before allowing access.
8
+ *
9
+ * OPEN endpoints (always free): protocol, registry read, discovery, adapters read,
10
+ * agent registration, basic health, SDK downloads
11
+ *
12
+ * GATED endpoints: orchestration, observability details, replay, failure analysis,
13
+ * sessions beyond limit, LLM inference, certification, signing, hosted runtime,
14
+ * marketplace publish, swarm, vision
15
+ */
16
+
17
+ const { checkFeatureGate, hasFeature, getPlan } = require('../config/plans');
18
+ const metering = require('../services/metering');
19
+ const { metrics } = require('../observability');
20
+
21
+ /**
22
+ * Feature Gate Middleware
23
+ * Checks if the requesting agent/user has the required feature in their plan.
24
+ *
25
+ * Requires req.agentTier to be set (by auth middleware or license verification).
26
+ * Falls back to 'free' if not set.
27
+ */
28
+ function featureGate(req, res, next) {
29
+ const tier = req.agentTier || req.session?.tier || 'free';
30
+ const requiredFeature = checkFeatureGate(req.path, req.method);
31
+
32
+ // No gate on this endpoint — free access
33
+ if (!requiredFeature) return next();
34
+
35
+ // Check feature
36
+ if (!hasFeature(tier, requiredFeature)) {
37
+ metrics.increment('feature_gate.denied', 1, { feature: requiredFeature, tier });
38
+ const plan = getPlan(tier);
39
+ return res.status(403).json({
40
+ error: 'Feature not available on your plan',
41
+ feature: requiredFeature,
42
+ currentPlan: tier,
43
+ upgrade: `This feature requires a higher plan. Visit /api/os/plans for available plans.`,
44
+ upgradeUrl: '/api/os/plans',
45
+ });
46
+ }
47
+
48
+ metrics.increment('feature_gate.allowed', 1, { feature: requiredFeature, tier });
49
+ next();
50
+ }
51
+
52
+ /**
53
+ * Usage Limit Middleware
54
+ * Enforces per-metric limits (executions/day, tasks/day, etc.) based on plan.
55
+ */
56
+ function usageLimit(metric) {
57
+ return function (req, res, next) {
58
+ const tier = req.agentTier || req.session?.tier || 'free';
59
+ const entityId = req.agentId || req.session?.agentId || req.ip;
60
+
61
+ const result = metering.record(entityId, metric, tier);
62
+
63
+ if (!result.allowed) {
64
+ metrics.increment('usage_limit.exceeded', 1, { metric, tier });
65
+ return res.status(429).json({
66
+ error: 'Usage limit exceeded',
67
+ metric,
68
+ current: result.current,
69
+ limit: result.limit,
70
+ overage: result.overageAmount,
71
+ overageCost: result.overageCost,
72
+ upgrade: 'Upgrade your plan for higher limits or enable pay-as-you-go overages.',
73
+ upgradeUrl: '/api/os/plans',
74
+ });
75
+ }
76
+
77
+ // Attach usage info to response headers
78
+ if (result.limit > 0) {
79
+ res.set('X-WAB-Usage-Current', String(result.current));
80
+ res.set('X-WAB-Usage-Limit', String(result.limit));
81
+ res.set('X-WAB-Usage-Remaining', String(Math.max(0, result.limit - result.current)));
82
+ }
83
+
84
+ next();
85
+ };
86
+ }
87
+
88
+ module.exports = { featureGate, usageLimit };
@@ -0,0 +1,158 @@
1
+ -- Agent OS persistence layer
2
+ -- Stores agents, tasks, deployments, registry data, and audit logs
3
+
4
+ -- Agent identities
5
+ CREATE TABLE IF NOT EXISTS os_agents (
6
+ id TEXT PRIMARY KEY,
7
+ name TEXT NOT NULL,
8
+ type TEXT NOT NULL DEFAULT 'autonomous',
9
+ status TEXT NOT NULL DEFAULT 'active',
10
+ capabilities TEXT DEFAULT '[]',
11
+ api_key_hash TEXT,
12
+ public_key TEXT,
13
+ metadata TEXT DEFAULT '{}',
14
+ ip_allowlist TEXT DEFAULT '[]',
15
+ command_count INTEGER DEFAULT 0,
16
+ created_at INTEGER NOT NULL,
17
+ last_seen INTEGER
18
+ );
19
+
20
+ -- Agent sessions
21
+ CREATE TABLE IF NOT EXISTS os_sessions (
22
+ token TEXT PRIMARY KEY,
23
+ agent_id TEXT NOT NULL,
24
+ ip TEXT,
25
+ expires_at INTEGER NOT NULL,
26
+ created_at INTEGER NOT NULL,
27
+ FOREIGN KEY (agent_id) REFERENCES os_agents(id) ON DELETE CASCADE
28
+ );
29
+
30
+ -- Tasks
31
+ CREATE TABLE IF NOT EXISTS os_tasks (
32
+ id TEXT PRIMARY KEY,
33
+ type TEXT NOT NULL,
34
+ state TEXT NOT NULL DEFAULT 'queued',
35
+ priority INTEGER DEFAULT 5,
36
+ agent_id TEXT,
37
+ params TEXT DEFAULT '{}',
38
+ result TEXT,
39
+ error TEXT,
40
+ retry_count INTEGER DEFAULT 0,
41
+ max_retries INTEGER DEFAULT 3,
42
+ depends_on TEXT DEFAULT '[]',
43
+ created_at INTEGER NOT NULL,
44
+ started_at INTEGER,
45
+ completed_at INTEGER,
46
+ timeout INTEGER DEFAULT 30000
47
+ );
48
+
49
+ CREATE INDEX IF NOT EXISTS idx_os_tasks_state ON os_tasks(state);
50
+ CREATE INDEX IF NOT EXISTS idx_os_tasks_agent ON os_tasks(agent_id);
51
+
52
+ -- Deployments
53
+ CREATE TABLE IF NOT EXISTS os_deployments (
54
+ id TEXT PRIMARY KEY,
55
+ agent_id TEXT NOT NULL,
56
+ status TEXT NOT NULL DEFAULT 'active',
57
+ config TEXT DEFAULT '{}',
58
+ sites TEXT DEFAULT '[]',
59
+ health_status TEXT DEFAULT 'unknown',
60
+ last_health_check INTEGER,
61
+ created_at INTEGER NOT NULL,
62
+ FOREIGN KEY (agent_id) REFERENCES os_agents(id) ON DELETE CASCADE
63
+ );
64
+
65
+ -- Registry: commands
66
+ CREATE TABLE IF NOT EXISTS os_registry_commands (
67
+ id TEXT PRIMARY KEY,
68
+ site_id TEXT NOT NULL,
69
+ name TEXT NOT NULL,
70
+ description TEXT DEFAULT '',
71
+ category TEXT DEFAULT 'general',
72
+ version TEXT DEFAULT '1.0.0',
73
+ input_schema TEXT DEFAULT '{}',
74
+ output_schema TEXT DEFAULT '{}',
75
+ capabilities TEXT DEFAULT '[]',
76
+ tags TEXT DEFAULT '[]',
77
+ usage_count INTEGER DEFAULT 0,
78
+ last_used INTEGER,
79
+ created_at INTEGER NOT NULL
80
+ );
81
+
82
+ CREATE INDEX IF NOT EXISTS idx_os_reg_cmd_site ON os_registry_commands(site_id);
83
+ CREATE INDEX IF NOT EXISTS idx_os_reg_cmd_cat ON os_registry_commands(category);
84
+
85
+ -- Registry: sites
86
+ CREATE TABLE IF NOT EXISTS os_registry_sites (
87
+ domain TEXT PRIMARY KEY,
88
+ name TEXT,
89
+ description TEXT DEFAULT '',
90
+ tier TEXT DEFAULT 'free',
91
+ protocol_version TEXT DEFAULT '1.0.0',
92
+ capabilities TEXT DEFAULT '[]',
93
+ endpoints TEXT DEFAULT '{}',
94
+ verified INTEGER DEFAULT 0,
95
+ agent_visits INTEGER DEFAULT 0,
96
+ last_seen INTEGER,
97
+ created_at INTEGER NOT NULL
98
+ );
99
+
100
+ -- Registry: templates
101
+ CREATE TABLE IF NOT EXISTS os_registry_templates (
102
+ id TEXT PRIMARY KEY,
103
+ name TEXT NOT NULL,
104
+ description TEXT DEFAULT '',
105
+ category TEXT DEFAULT 'general',
106
+ author TEXT DEFAULT 'system',
107
+ version TEXT DEFAULT '1.0.0',
108
+ steps TEXT DEFAULT '[]',
109
+ variables TEXT DEFAULT '{}',
110
+ required_capabilities TEXT DEFAULT '[]',
111
+ tags TEXT DEFAULT '[]',
112
+ downloads INTEGER DEFAULT 0,
113
+ created_at INTEGER NOT NULL
114
+ );
115
+
116
+ -- Audit log (immutable append-only)
117
+ CREATE TABLE IF NOT EXISTS os_audit_log (
118
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
119
+ timestamp INTEGER NOT NULL,
120
+ agent_id TEXT,
121
+ action TEXT NOT NULL,
122
+ resource TEXT,
123
+ resource_id TEXT,
124
+ details TEXT DEFAULT '{}',
125
+ ip TEXT,
126
+ outcome TEXT DEFAULT 'success'
127
+ );
128
+
129
+ CREATE INDEX IF NOT EXISTS idx_os_audit_ts ON os_audit_log(timestamp);
130
+ CREATE INDEX IF NOT EXISTS idx_os_audit_agent ON os_audit_log(agent_id);
131
+
132
+ -- Capability grants
133
+ CREATE TABLE IF NOT EXISTS os_capability_grants (
134
+ id TEXT PRIMARY KEY,
135
+ agent_id TEXT NOT NULL,
136
+ capability TEXT NOT NULL,
137
+ site_id TEXT DEFAULT '*',
138
+ max_calls INTEGER,
139
+ used_calls INTEGER DEFAULT 0,
140
+ rate_limit TEXT,
141
+ expires_at INTEGER,
142
+ status TEXT DEFAULT 'active',
143
+ created_at INTEGER NOT NULL,
144
+ FOREIGN KEY (agent_id) REFERENCES os_agents(id) ON DELETE CASCADE
145
+ );
146
+
147
+ CREATE INDEX IF NOT EXISTS idx_os_cap_agent ON os_capability_grants(agent_id);
148
+
149
+ -- Policies
150
+ CREATE TABLE IF NOT EXISTS os_policies (
151
+ id TEXT PRIMARY KEY,
152
+ name TEXT NOT NULL,
153
+ description TEXT DEFAULT '',
154
+ priority INTEGER DEFAULT 0,
155
+ rules TEXT DEFAULT '[]',
156
+ entity_bindings TEXT DEFAULT '[]',
157
+ created_at INTEGER NOT NULL
158
+ );