opencode-swarm-plugin 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,656 @@
1
+ /**
2
+ * Rate Limiter Module - Distributed rate limiting for Agent Mail
3
+ *
4
+ * Provides sliding window rate limiting with dual backends:
5
+ * - Redis (primary) - Distributed, uses sorted sets for sliding window
6
+ * - SQLite (fallback) - Local, file-based persistence
7
+ *
8
+ * Features:
9
+ * - Dual window enforcement: per-minute AND per-hour limits
10
+ * - Automatic backend fallback (Redis → SQLite)
11
+ * - Configurable limits per endpoint via env vars
12
+ * - Auto-cleanup of expired entries
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * // Create rate limiter (auto-selects backend)
17
+ * const limiter = await createRateLimiter();
18
+ *
19
+ * // Check if request is allowed
20
+ * const result = await limiter.checkLimit("BlueLake", "send");
21
+ * if (!result.allowed) {
22
+ * console.log(`Rate limited. Reset at ${result.resetAt}`);
23
+ * }
24
+ *
25
+ * // Record a request after it completes
26
+ * await limiter.recordRequest("BlueLake", "send");
27
+ * ```
28
+ */
29
+
30
+ import Redis from "ioredis";
31
+ import { Database } from "bun:sqlite";
32
+ import { mkdirSync, existsSync } from "node:fs";
33
+ import { dirname, join } from "node:path";
34
+ import { homedir } from "node:os";
35
+
36
+ // ============================================================================
37
+ // Types
38
+ // ============================================================================
39
+
40
+ /**
41
+ * Result of checking a rate limit
42
+ */
43
+ export interface RateLimitResult {
44
+ /** Whether the request is allowed */
45
+ allowed: boolean;
46
+ /** Remaining requests in the most restrictive window */
47
+ remaining: number;
48
+ /** Unix timestamp (ms) when the limit resets */
49
+ resetAt: number;
50
+ }
51
+
52
+ /**
53
+ * Rate limiter interface
54
+ */
55
+ export interface RateLimiter {
56
+ /**
57
+ * Check if a request is allowed under rate limits
58
+ * Checks BOTH minute and hour windows - both must pass
59
+ *
60
+ * @param agentName - The agent making the request
61
+ * @param endpoint - The endpoint being accessed
62
+ * @returns Rate limit check result
63
+ */
64
+ checkLimit(agentName: string, endpoint: string): Promise<RateLimitResult>;
65
+
66
+ /**
67
+ * Record a request against the rate limit
68
+ * Should be called AFTER the request succeeds
69
+ *
70
+ * @param agentName - The agent making the request
71
+ * @param endpoint - The endpoint being accessed
72
+ */
73
+ recordRequest(agentName: string, endpoint: string): Promise<void>;
74
+
75
+ /**
76
+ * Close the rate limiter and release resources
77
+ */
78
+ close(): Promise<void>;
79
+ }
80
+
81
+ /**
82
+ * Rate limit configuration for an endpoint
83
+ */
84
+ export interface EndpointLimits {
85
+ /** Requests allowed per minute */
86
+ perMinute: number;
87
+ /** Requests allowed per hour */
88
+ perHour: number;
89
+ }
90
+
91
+ // ============================================================================
92
+ // Default Limits
93
+ // ============================================================================
94
+
95
+ /**
96
+ * Default rate limits per endpoint
97
+ * Can be overridden via OPENCODE_RATE_LIMIT_{ENDPOINT}_PER_MIN and _PER_HOUR
98
+ */
99
+ export const DEFAULT_LIMITS: Record<string, EndpointLimits> = {
100
+ send: { perMinute: 20, perHour: 200 },
101
+ reserve: { perMinute: 10, perHour: 100 },
102
+ release: { perMinute: 10, perHour: 100 },
103
+ ack: { perMinute: 20, perHour: 200 },
104
+ inbox: { perMinute: 60, perHour: 600 },
105
+ read_message: { perMinute: 60, perHour: 600 },
106
+ summarize_thread: { perMinute: 30, perHour: 300 },
107
+ search: { perMinute: 30, perHour: 300 },
108
+ };
109
+
110
+ /**
111
+ * Get rate limits for an endpoint, with env var overrides
112
+ *
113
+ * @param endpoint - The endpoint name
114
+ * @returns Rate limits for the endpoint
115
+ */
116
+ export function getLimitsForEndpoint(endpoint: string): EndpointLimits {
117
+ const defaults = DEFAULT_LIMITS[endpoint] || { perMinute: 60, perHour: 600 };
118
+ const upperEndpoint = endpoint.toUpperCase();
119
+
120
+ const perMinuteEnv =
121
+ process.env[`OPENCODE_RATE_LIMIT_${upperEndpoint}_PER_MIN`];
122
+ const perHourEnv =
123
+ process.env[`OPENCODE_RATE_LIMIT_${upperEndpoint}_PER_HOUR`];
124
+
125
+ return {
126
+ perMinute: perMinuteEnv ? parseInt(perMinuteEnv, 10) : defaults.perMinute,
127
+ perHour: perHourEnv ? parseInt(perHourEnv, 10) : defaults.perHour,
128
+ };
129
+ }
130
+
131
+ // ============================================================================
132
+ // Redis Rate Limiter
133
+ // ============================================================================
134
+
135
+ /**
136
+ * Redis-backed rate limiter using sorted sets
137
+ *
138
+ * Uses sliding window algorithm:
139
+ * 1. Store each request as a member with timestamp as score
140
+ * 2. Remove expired entries (outside window)
141
+ * 3. Count remaining entries
142
+ *
143
+ * Key format: ratelimit:{agent}:{endpoint}:{window}
144
+ * Window values: "minute" or "hour"
145
+ */
146
+ export class RedisRateLimiter implements RateLimiter {
147
+ private redis: Redis;
148
+ private connected: boolean = false;
149
+
150
+ constructor(redis: Redis) {
151
+ this.redis = redis;
152
+ this.connected = true;
153
+ }
154
+
155
+ /**
156
+ * Build Redis key for rate limiting
157
+ */
158
+ private buildKey(
159
+ agentName: string,
160
+ endpoint: string,
161
+ window: "minute" | "hour",
162
+ ): string {
163
+ return `ratelimit:${agentName}:${endpoint}:${window}`;
164
+ }
165
+
166
+ /**
167
+ * Get window duration in milliseconds
168
+ */
169
+ private getWindowDuration(window: "minute" | "hour"): number {
170
+ return window === "minute" ? 60_000 : 3_600_000;
171
+ }
172
+
173
+ async checkLimit(
174
+ agentName: string,
175
+ endpoint: string,
176
+ ): Promise<RateLimitResult> {
177
+ const limits = getLimitsForEndpoint(endpoint);
178
+ const now = Date.now();
179
+
180
+ // Check both windows
181
+ const [minuteResult, hourResult] = await Promise.all([
182
+ this.checkWindow(agentName, endpoint, "minute", limits.perMinute, now),
183
+ this.checkWindow(agentName, endpoint, "hour", limits.perHour, now),
184
+ ]);
185
+
186
+ // Return the most restrictive result (both windows must allow)
187
+ if (!minuteResult.allowed) {
188
+ return minuteResult;
189
+ }
190
+ if (!hourResult.allowed) {
191
+ return hourResult;
192
+ }
193
+
194
+ // Both allowed - return the one with fewer remaining
195
+ return minuteResult.remaining <= hourResult.remaining
196
+ ? minuteResult
197
+ : hourResult;
198
+ }
199
+
200
+ /**
201
+ * Check a single window's rate limit
202
+ */
203
+ private async checkWindow(
204
+ agentName: string,
205
+ endpoint: string,
206
+ window: "minute" | "hour",
207
+ limit: number,
208
+ now: number,
209
+ ): Promise<RateLimitResult> {
210
+ const key = this.buildKey(agentName, endpoint, window);
211
+ const windowDuration = this.getWindowDuration(window);
212
+ const windowStart = now - windowDuration;
213
+
214
+ // Remove expired entries and count current ones in a pipeline
215
+ const pipeline = this.redis.pipeline();
216
+ pipeline.zremrangebyscore(key, 0, windowStart);
217
+ pipeline.zcard(key);
218
+
219
+ const results = await pipeline.exec();
220
+ if (!results) {
221
+ return { allowed: true, remaining: limit, resetAt: now + windowDuration };
222
+ }
223
+
224
+ const count = (results[1]?.[1] as number) || 0;
225
+ const remaining = Math.max(0, limit - count);
226
+ const allowed = count < limit;
227
+
228
+ // Calculate reset time based on oldest entry in window
229
+ let resetAt = now + windowDuration;
230
+ if (!allowed) {
231
+ // Get the oldest entry's timestamp to calculate precise reset
232
+ const oldest = await this.redis.zrange(key, 0, 0, "WITHSCORES");
233
+ if (oldest.length >= 2) {
234
+ const oldestTimestamp = parseInt(oldest[1], 10);
235
+ resetAt = oldestTimestamp + windowDuration;
236
+ }
237
+ }
238
+
239
+ return { allowed, remaining, resetAt };
240
+ }
241
+
242
+ async recordRequest(agentName: string, endpoint: string): Promise<void> {
243
+ const now = Date.now();
244
+ const memberId = crypto.randomUUID();
245
+
246
+ // Record in both windows
247
+ const minuteKey = this.buildKey(agentName, endpoint, "minute");
248
+ const hourKey = this.buildKey(agentName, endpoint, "hour");
249
+
250
+ const pipeline = this.redis.pipeline();
251
+
252
+ // Add to minute window with TTL
253
+ pipeline.zadd(minuteKey, now, `${memberId}:minute`);
254
+ pipeline.expire(minuteKey, 120); // 2 minutes TTL for safety
255
+
256
+ // Add to hour window with TTL
257
+ pipeline.zadd(hourKey, now, `${memberId}:hour`);
258
+ pipeline.expire(hourKey, 7200); // 2 hours TTL for safety
259
+
260
+ await pipeline.exec();
261
+ }
262
+
263
+ async close(): Promise<void> {
264
+ if (this.connected) {
265
+ await this.redis.quit();
266
+ this.connected = false;
267
+ }
268
+ }
269
+ }
270
+
271
+ // ============================================================================
272
+ // SQLite Rate Limiter
273
+ // ============================================================================
274
+
275
+ /**
276
+ * SQLite-backed rate limiter for local/fallback use
277
+ *
278
+ * Table schema:
279
+ * - agent_name: TEXT
280
+ * - endpoint: TEXT
281
+ * - window: TEXT ('minute' or 'hour')
282
+ * - timestamp: INTEGER (Unix ms)
283
+ *
284
+ * Uses sliding window via COUNT query with timestamp filter.
285
+ */
286
+ export class SqliteRateLimiter implements RateLimiter {
287
+ private db: Database;
288
+
289
+ constructor(dbPath: string) {
290
+ // Ensure directory exists
291
+ const dir = dirname(dbPath);
292
+ if (!existsSync(dir)) {
293
+ mkdirSync(dir, { recursive: true });
294
+ }
295
+
296
+ this.db = new Database(dbPath);
297
+ this.initialize();
298
+ }
299
+
300
+ /**
301
+ * Initialize the database schema and cleanup old entries
302
+ */
303
+ private initialize(): void {
304
+ // Create table if not exists
305
+ this.db.run(`
306
+ CREATE TABLE IF NOT EXISTS rate_limits (
307
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
308
+ agent_name TEXT NOT NULL,
309
+ endpoint TEXT NOT NULL,
310
+ window TEXT NOT NULL,
311
+ timestamp INTEGER NOT NULL
312
+ )
313
+ `);
314
+
315
+ // Create indexes for fast queries
316
+ this.db.run(`
317
+ CREATE INDEX IF NOT EXISTS idx_rate_limits_lookup
318
+ ON rate_limits (agent_name, endpoint, window, timestamp)
319
+ `);
320
+
321
+ // Cleanup old entries (older than 2 hours)
322
+ const cutoff = Date.now() - 7_200_000;
323
+ this.db.run(`DELETE FROM rate_limits WHERE timestamp < ?`, [cutoff]);
324
+ }
325
+
326
+ async checkLimit(
327
+ agentName: string,
328
+ endpoint: string,
329
+ ): Promise<RateLimitResult> {
330
+ const limits = getLimitsForEndpoint(endpoint);
331
+ const now = Date.now();
332
+
333
+ // Check both windows
334
+ const minuteResult = this.checkWindow(
335
+ agentName,
336
+ endpoint,
337
+ "minute",
338
+ limits.perMinute,
339
+ now,
340
+ );
341
+ const hourResult = this.checkWindow(
342
+ agentName,
343
+ endpoint,
344
+ "hour",
345
+ limits.perHour,
346
+ now,
347
+ );
348
+
349
+ // Return the most restrictive result (both windows must allow)
350
+ if (!minuteResult.allowed) {
351
+ return minuteResult;
352
+ }
353
+ if (!hourResult.allowed) {
354
+ return hourResult;
355
+ }
356
+
357
+ // Both allowed - return the one with fewer remaining
358
+ return minuteResult.remaining <= hourResult.remaining
359
+ ? minuteResult
360
+ : hourResult;
361
+ }
362
+
363
+ /**
364
+ * Check a single window's rate limit
365
+ */
366
+ private checkWindow(
367
+ agentName: string,
368
+ endpoint: string,
369
+ window: "minute" | "hour",
370
+ limit: number,
371
+ now: number,
372
+ ): RateLimitResult {
373
+ const windowDuration = window === "minute" ? 60_000 : 3_600_000;
374
+ const windowStart = now - windowDuration;
375
+
376
+ // Count requests in window
377
+ const result = this.db
378
+ .query<{ count: number }, [string, string, string, number]>(
379
+ `SELECT COUNT(*) as count FROM rate_limits
380
+ WHERE agent_name = ? AND endpoint = ? AND window = ? AND timestamp > ?`,
381
+ )
382
+ .get(agentName, endpoint, window, windowStart);
383
+
384
+ const count = result?.count || 0;
385
+ const remaining = Math.max(0, limit - count);
386
+ const allowed = count < limit;
387
+
388
+ // Calculate reset time based on oldest entry in window
389
+ let resetAt = now + windowDuration;
390
+ if (!allowed) {
391
+ const oldest = this.db
392
+ .query<{ timestamp: number }, [string, string, string, number]>(
393
+ `SELECT MIN(timestamp) as timestamp FROM rate_limits
394
+ WHERE agent_name = ? AND endpoint = ? AND window = ? AND timestamp > ?`,
395
+ )
396
+ .get(agentName, endpoint, window, windowStart);
397
+
398
+ if (oldest?.timestamp) {
399
+ resetAt = oldest.timestamp + windowDuration;
400
+ }
401
+ }
402
+
403
+ return { allowed, remaining, resetAt };
404
+ }
405
+
406
+ async recordRequest(agentName: string, endpoint: string): Promise<void> {
407
+ const now = Date.now();
408
+
409
+ // Record in both windows
410
+ const stmt = this.db.prepare(
411
+ `INSERT INTO rate_limits (agent_name, endpoint, window, timestamp) VALUES (?, ?, ?, ?)`,
412
+ );
413
+
414
+ stmt.run(agentName, endpoint, "minute", now);
415
+ stmt.run(agentName, endpoint, "hour", now);
416
+
417
+ // Opportunistic cleanup of old entries (1% chance to avoid overhead)
418
+ if (Math.random() < 0.01) {
419
+ const cutoff = Date.now() - 7_200_000;
420
+ this.db.run(`DELETE FROM rate_limits WHERE timestamp < ?`, [cutoff]);
421
+ }
422
+ }
423
+
424
+ async close(): Promise<void> {
425
+ this.db.close();
426
+ }
427
+ }
428
+
429
+ // ============================================================================
430
+ // In-Memory Rate Limiter (for testing)
431
+ // ============================================================================
432
+
433
+ /**
434
+ * In-memory rate limiter for testing
435
+ *
436
+ * Uses Map storage with timestamp arrays per key.
437
+ * No persistence - resets on process restart.
438
+ */
439
+ export class InMemoryRateLimiter implements RateLimiter {
440
+ private storage: Map<string, number[]> = new Map();
441
+
442
+ private buildKey(
443
+ agentName: string,
444
+ endpoint: string,
445
+ window: "minute" | "hour",
446
+ ): string {
447
+ return `${agentName}:${endpoint}:${window}`;
448
+ }
449
+
450
+ async checkLimit(
451
+ agentName: string,
452
+ endpoint: string,
453
+ ): Promise<RateLimitResult> {
454
+ const limits = getLimitsForEndpoint(endpoint);
455
+ const now = Date.now();
456
+
457
+ const minuteResult = this.checkWindow(
458
+ agentName,
459
+ endpoint,
460
+ "minute",
461
+ limits.perMinute,
462
+ now,
463
+ );
464
+ const hourResult = this.checkWindow(
465
+ agentName,
466
+ endpoint,
467
+ "hour",
468
+ limits.perHour,
469
+ now,
470
+ );
471
+
472
+ // Return the most restrictive result (both windows must allow)
473
+ if (!minuteResult.allowed) return minuteResult;
474
+ if (!hourResult.allowed) return hourResult;
475
+
476
+ return minuteResult.remaining <= hourResult.remaining
477
+ ? minuteResult
478
+ : hourResult;
479
+ }
480
+
481
+ private checkWindow(
482
+ agentName: string,
483
+ endpoint: string,
484
+ window: "minute" | "hour",
485
+ limit: number,
486
+ now: number,
487
+ ): RateLimitResult {
488
+ const key = this.buildKey(agentName, endpoint, window);
489
+ const windowDuration = window === "minute" ? 60_000 : 3_600_000;
490
+ const windowStart = now - windowDuration;
491
+
492
+ // Get and filter timestamps
493
+ let timestamps = this.storage.get(key) || [];
494
+ timestamps = timestamps.filter((t) => t > windowStart);
495
+ this.storage.set(key, timestamps);
496
+
497
+ const count = timestamps.length;
498
+ const remaining = Math.max(0, limit - count);
499
+ const allowed = count < limit;
500
+
501
+ let resetAt = now + windowDuration;
502
+ if (!allowed && timestamps.length > 0) {
503
+ resetAt = timestamps[0] + windowDuration;
504
+ }
505
+
506
+ return { allowed, remaining, resetAt };
507
+ }
508
+
509
+ async recordRequest(agentName: string, endpoint: string): Promise<void> {
510
+ const now = Date.now();
511
+
512
+ // Record in both windows
513
+ for (const window of ["minute", "hour"] as const) {
514
+ const key = this.buildKey(agentName, endpoint, window);
515
+ const timestamps = this.storage.get(key) || [];
516
+ timestamps.push(now);
517
+ this.storage.set(key, timestamps);
518
+ }
519
+ }
520
+
521
+ async close(): Promise<void> {
522
+ this.storage.clear();
523
+ }
524
+
525
+ /**
526
+ * Reset all rate limits (for testing)
527
+ */
528
+ reset(): void {
529
+ this.storage.clear();
530
+ }
531
+ }
532
+
533
+ // ============================================================================
534
+ // Factory
535
+ // ============================================================================
536
+
537
+ /** Track if we've warned about fallback (warn only once) */
538
+ let hasWarnedAboutFallback = false;
539
+
540
+ /**
541
+ * Create a rate limiter with automatic backend selection
542
+ *
543
+ * Tries Redis first, falls back to SQLite on connection failure.
544
+ * Warns once when falling back to SQLite.
545
+ *
546
+ * @returns Configured rate limiter instance
547
+ *
548
+ * @example
549
+ * ```typescript
550
+ * // Auto-select backend
551
+ * const limiter = await createRateLimiter();
552
+ *
553
+ * // Force SQLite
554
+ * const limiter = await createRateLimiter({ backend: "sqlite" });
555
+ *
556
+ * // Force in-memory (testing)
557
+ * const limiter = await createRateLimiter({ backend: "memory" });
558
+ * ```
559
+ */
560
+ export async function createRateLimiter(options?: {
561
+ backend?: "redis" | "sqlite" | "memory";
562
+ redisUrl?: string;
563
+ sqlitePath?: string;
564
+ }): Promise<RateLimiter> {
565
+ const {
566
+ backend,
567
+ redisUrl = process.env.OPENCODE_RATE_LIMIT_REDIS_URL ||
568
+ "redis://localhost:6379",
569
+ sqlitePath = process.env.OPENCODE_RATE_LIMIT_SQLITE_PATH ||
570
+ join(homedir(), ".config", "opencode", "rate-limits.db"),
571
+ } = options || {};
572
+
573
+ // Explicit backend selection
574
+ if (backend === "memory") {
575
+ return new InMemoryRateLimiter();
576
+ }
577
+
578
+ if (backend === "sqlite") {
579
+ return new SqliteRateLimiter(sqlitePath);
580
+ }
581
+
582
+ if (backend === "redis") {
583
+ const redis = new Redis(redisUrl);
584
+ return new RedisRateLimiter(redis);
585
+ }
586
+
587
+ // Auto-select: try Redis first, fall back to SQLite
588
+ try {
589
+ const redis = new Redis(redisUrl, {
590
+ connectTimeout: 2000,
591
+ maxRetriesPerRequest: 1,
592
+ retryStrategy: () => null, // Don't retry on failure
593
+ lazyConnect: true,
594
+ });
595
+
596
+ // Test connection
597
+ await redis.connect();
598
+ await redis.ping();
599
+
600
+ return new RedisRateLimiter(redis);
601
+ } catch (error) {
602
+ // Redis connection failed, fall back to SQLite
603
+ if (!hasWarnedAboutFallback) {
604
+ console.warn(
605
+ `[rate-limiter] Redis connection failed (${redisUrl}), falling back to SQLite at ${sqlitePath}`,
606
+ );
607
+ hasWarnedAboutFallback = true;
608
+ }
609
+
610
+ return new SqliteRateLimiter(sqlitePath);
611
+ }
612
+ }
613
+
614
+ /**
615
+ * Reset the fallback warning flag (for testing)
616
+ */
617
+ export function resetFallbackWarning(): void {
618
+ hasWarnedAboutFallback = false;
619
+ }
620
+
621
+ // ============================================================================
622
+ // Global Instance
623
+ // ============================================================================
624
+
625
+ let globalRateLimiter: RateLimiter | null = null;
626
+
627
+ /**
628
+ * Get or create the global rate limiter instance
629
+ *
630
+ * Uses auto-selection (Redis → SQLite) by default.
631
+ */
632
+ export async function getRateLimiter(): Promise<RateLimiter> {
633
+ if (!globalRateLimiter) {
634
+ globalRateLimiter = await createRateLimiter();
635
+ }
636
+ return globalRateLimiter;
637
+ }
638
+
639
+ /**
640
+ * Set the global rate limiter instance
641
+ *
642
+ * Useful for testing or custom configurations.
643
+ */
644
+ export function setRateLimiter(limiter: RateLimiter): void {
645
+ globalRateLimiter = limiter;
646
+ }
647
+
648
+ /**
649
+ * Reset the global rate limiter instance
650
+ */
651
+ export async function resetRateLimiter(): Promise<void> {
652
+ if (globalRateLimiter) {
653
+ await globalRateLimiter.close();
654
+ globalRateLimiter = null;
655
+ }
656
+ }