opencode-swarm-plugin 0.44.0 → 0.44.1

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.
Files changed (205) hide show
  1. package/bin/swarm.serve.test.ts +6 -4
  2. package/bin/swarm.ts +16 -10
  3. package/dist/compaction-prompt-scoring.js +139 -0
  4. package/dist/eval-capture.js +12811 -0
  5. package/dist/hive.d.ts.map +1 -1
  6. package/dist/index.js +7644 -62599
  7. package/dist/plugin.js +23766 -78721
  8. package/dist/swarm-orchestrate.d.ts.map +1 -1
  9. package/dist/swarm-prompts.d.ts.map +1 -1
  10. package/dist/swarm-review.d.ts.map +1 -1
  11. package/package.json +17 -5
  12. package/.changeset/swarm-insights-data-layer.md +0 -63
  13. package/.hive/analysis/eval-failure-analysis-2025-12-25.md +0 -331
  14. package/.hive/analysis/session-data-quality-audit.md +0 -320
  15. package/.hive/eval-results.json +0 -483
  16. package/.hive/issues.jsonl +0 -138
  17. package/.hive/memories.jsonl +0 -729
  18. package/.opencode/eval-history.jsonl +0 -327
  19. package/.turbo/turbo-build.log +0 -9
  20. package/CHANGELOG.md +0 -2286
  21. package/SCORER-ANALYSIS.md +0 -598
  22. package/docs/analysis/subagent-coordination-patterns.md +0 -902
  23. package/docs/analysis-socratic-planner-pattern.md +0 -504
  24. package/docs/planning/ADR-001-monorepo-structure.md +0 -171
  25. package/docs/planning/ADR-002-package-extraction.md +0 -393
  26. package/docs/planning/ADR-003-performance-improvements.md +0 -451
  27. package/docs/planning/ADR-004-message-queue-features.md +0 -187
  28. package/docs/planning/ADR-005-devtools-observability.md +0 -202
  29. package/docs/planning/ADR-007-swarm-enhancements-worktree-review.md +0 -168
  30. package/docs/planning/ADR-008-worker-handoff-protocol.md +0 -293
  31. package/docs/planning/ADR-009-oh-my-opencode-patterns.md +0 -353
  32. package/docs/planning/ADR-010-cass-inhousing.md +0 -1215
  33. package/docs/planning/ROADMAP.md +0 -368
  34. package/docs/semantic-memory-cli-syntax.md +0 -123
  35. package/docs/swarm-mail-architecture.md +0 -1147
  36. package/docs/testing/context-recovery-test.md +0 -470
  37. package/evals/ARCHITECTURE.md +0 -1189
  38. package/evals/README.md +0 -768
  39. package/evals/compaction-prompt.eval.ts +0 -149
  40. package/evals/compaction-resumption.eval.ts +0 -289
  41. package/evals/coordinator-behavior.eval.ts +0 -307
  42. package/evals/coordinator-session.eval.ts +0 -154
  43. package/evals/evalite.config.ts.bak +0 -15
  44. package/evals/example.eval.ts +0 -31
  45. package/evals/fixtures/cass-baseline.ts +0 -217
  46. package/evals/fixtures/compaction-cases.ts +0 -350
  47. package/evals/fixtures/compaction-prompt-cases.ts +0 -311
  48. package/evals/fixtures/coordinator-sessions.ts +0 -328
  49. package/evals/fixtures/decomposition-cases.ts +0 -105
  50. package/evals/lib/compaction-loader.test.ts +0 -248
  51. package/evals/lib/compaction-loader.ts +0 -320
  52. package/evals/lib/data-loader.evalite-test.ts +0 -289
  53. package/evals/lib/data-loader.test.ts +0 -345
  54. package/evals/lib/data-loader.ts +0 -281
  55. package/evals/lib/llm.ts +0 -115
  56. package/evals/scorers/compaction-prompt-scorers.ts +0 -145
  57. package/evals/scorers/compaction-scorers.ts +0 -305
  58. package/evals/scorers/coordinator-discipline.evalite-test.ts +0 -539
  59. package/evals/scorers/coordinator-discipline.ts +0 -325
  60. package/evals/scorers/index.test.ts +0 -146
  61. package/evals/scorers/index.ts +0 -328
  62. package/evals/scorers/outcome-scorers.evalite-test.ts +0 -27
  63. package/evals/scorers/outcome-scorers.ts +0 -349
  64. package/evals/swarm-decomposition.eval.ts +0 -121
  65. package/examples/commands/swarm.md +0 -745
  66. package/examples/plugin-wrapper-template.ts +0 -2515
  67. package/examples/skills/hive-workflow/SKILL.md +0 -212
  68. package/examples/skills/skill-creator/SKILL.md +0 -223
  69. package/examples/skills/swarm-coordination/SKILL.md +0 -292
  70. package/global-skills/cli-builder/SKILL.md +0 -344
  71. package/global-skills/cli-builder/references/advanced-patterns.md +0 -244
  72. package/global-skills/learning-systems/SKILL.md +0 -644
  73. package/global-skills/skill-creator/LICENSE.txt +0 -202
  74. package/global-skills/skill-creator/SKILL.md +0 -352
  75. package/global-skills/skill-creator/references/output-patterns.md +0 -82
  76. package/global-skills/skill-creator/references/workflows.md +0 -28
  77. package/global-skills/swarm-coordination/SKILL.md +0 -995
  78. package/global-skills/swarm-coordination/references/coordinator-patterns.md +0 -235
  79. package/global-skills/swarm-coordination/references/strategies.md +0 -138
  80. package/global-skills/system-design/SKILL.md +0 -213
  81. package/global-skills/testing-patterns/SKILL.md +0 -430
  82. package/global-skills/testing-patterns/references/dependency-breaking-catalog.md +0 -586
  83. package/opencode-swarm-plugin-0.30.7.tgz +0 -0
  84. package/opencode-swarm-plugin-0.31.0.tgz +0 -0
  85. package/scripts/cleanup-test-memories.ts +0 -346
  86. package/scripts/init-skill.ts +0 -222
  87. package/scripts/migrate-unknown-sessions.ts +0 -349
  88. package/scripts/validate-skill.ts +0 -204
  89. package/src/agent-mail.ts +0 -1724
  90. package/src/anti-patterns.test.ts +0 -1167
  91. package/src/anti-patterns.ts +0 -448
  92. package/src/compaction-capture.integration.test.ts +0 -257
  93. package/src/compaction-hook.test.ts +0 -838
  94. package/src/compaction-hook.ts +0 -1204
  95. package/src/compaction-observability.integration.test.ts +0 -139
  96. package/src/compaction-observability.test.ts +0 -187
  97. package/src/compaction-observability.ts +0 -324
  98. package/src/compaction-prompt-scorers.test.ts +0 -475
  99. package/src/compaction-prompt-scoring.ts +0 -300
  100. package/src/contributor-tools.test.ts +0 -133
  101. package/src/contributor-tools.ts +0 -201
  102. package/src/dashboard.test.ts +0 -611
  103. package/src/dashboard.ts +0 -462
  104. package/src/error-enrichment.test.ts +0 -403
  105. package/src/error-enrichment.ts +0 -219
  106. package/src/eval-capture.test.ts +0 -1015
  107. package/src/eval-capture.ts +0 -929
  108. package/src/eval-gates.test.ts +0 -306
  109. package/src/eval-gates.ts +0 -218
  110. package/src/eval-history.test.ts +0 -508
  111. package/src/eval-history.ts +0 -214
  112. package/src/eval-learning.test.ts +0 -378
  113. package/src/eval-learning.ts +0 -360
  114. package/src/eval-runner.test.ts +0 -223
  115. package/src/eval-runner.ts +0 -402
  116. package/src/export-tools.test.ts +0 -476
  117. package/src/export-tools.ts +0 -257
  118. package/src/hive.integration.test.ts +0 -2241
  119. package/src/hive.ts +0 -1628
  120. package/src/index.ts +0 -940
  121. package/src/learning.integration.test.ts +0 -1815
  122. package/src/learning.ts +0 -1079
  123. package/src/logger.test.ts +0 -189
  124. package/src/logger.ts +0 -135
  125. package/src/mandate-promotion.test.ts +0 -473
  126. package/src/mandate-promotion.ts +0 -239
  127. package/src/mandate-storage.integration.test.ts +0 -601
  128. package/src/mandate-storage.test.ts +0 -578
  129. package/src/mandate-storage.ts +0 -794
  130. package/src/mandates.ts +0 -540
  131. package/src/memory-tools.test.ts +0 -195
  132. package/src/memory-tools.ts +0 -344
  133. package/src/memory.integration.test.ts +0 -334
  134. package/src/memory.test.ts +0 -158
  135. package/src/memory.ts +0 -527
  136. package/src/model-selection.test.ts +0 -188
  137. package/src/model-selection.ts +0 -68
  138. package/src/observability-tools.test.ts +0 -359
  139. package/src/observability-tools.ts +0 -871
  140. package/src/output-guardrails.test.ts +0 -438
  141. package/src/output-guardrails.ts +0 -381
  142. package/src/pattern-maturity.test.ts +0 -1160
  143. package/src/pattern-maturity.ts +0 -525
  144. package/src/planning-guardrails.test.ts +0 -491
  145. package/src/planning-guardrails.ts +0 -438
  146. package/src/plugin.ts +0 -23
  147. package/src/post-compaction-tracker.test.ts +0 -251
  148. package/src/post-compaction-tracker.ts +0 -237
  149. package/src/query-tools.test.ts +0 -636
  150. package/src/query-tools.ts +0 -324
  151. package/src/rate-limiter.integration.test.ts +0 -466
  152. package/src/rate-limiter.ts +0 -774
  153. package/src/replay-tools.test.ts +0 -496
  154. package/src/replay-tools.ts +0 -240
  155. package/src/repo-crawl.integration.test.ts +0 -441
  156. package/src/repo-crawl.ts +0 -610
  157. package/src/schemas/cell-events.test.ts +0 -347
  158. package/src/schemas/cell-events.ts +0 -807
  159. package/src/schemas/cell.ts +0 -257
  160. package/src/schemas/evaluation.ts +0 -166
  161. package/src/schemas/index.test.ts +0 -199
  162. package/src/schemas/index.ts +0 -286
  163. package/src/schemas/mandate.ts +0 -232
  164. package/src/schemas/swarm-context.ts +0 -115
  165. package/src/schemas/task.ts +0 -161
  166. package/src/schemas/worker-handoff.test.ts +0 -302
  167. package/src/schemas/worker-handoff.ts +0 -131
  168. package/src/sessions/agent-discovery.test.ts +0 -137
  169. package/src/sessions/agent-discovery.ts +0 -112
  170. package/src/sessions/index.ts +0 -15
  171. package/src/skills.integration.test.ts +0 -1192
  172. package/src/skills.test.ts +0 -643
  173. package/src/skills.ts +0 -1549
  174. package/src/storage.integration.test.ts +0 -341
  175. package/src/storage.ts +0 -884
  176. package/src/structured.integration.test.ts +0 -817
  177. package/src/structured.test.ts +0 -1046
  178. package/src/structured.ts +0 -762
  179. package/src/swarm-decompose.test.ts +0 -188
  180. package/src/swarm-decompose.ts +0 -1302
  181. package/src/swarm-deferred.integration.test.ts +0 -157
  182. package/src/swarm-deferred.test.ts +0 -38
  183. package/src/swarm-insights.test.ts +0 -214
  184. package/src/swarm-insights.ts +0 -459
  185. package/src/swarm-mail.integration.test.ts +0 -970
  186. package/src/swarm-mail.ts +0 -739
  187. package/src/swarm-orchestrate.integration.test.ts +0 -282
  188. package/src/swarm-orchestrate.test.ts +0 -548
  189. package/src/swarm-orchestrate.ts +0 -3084
  190. package/src/swarm-prompts.test.ts +0 -1270
  191. package/src/swarm-prompts.ts +0 -2077
  192. package/src/swarm-research.integration.test.ts +0 -701
  193. package/src/swarm-research.test.ts +0 -698
  194. package/src/swarm-research.ts +0 -472
  195. package/src/swarm-review.integration.test.ts +0 -285
  196. package/src/swarm-review.test.ts +0 -879
  197. package/src/swarm-review.ts +0 -709
  198. package/src/swarm-strategies.ts +0 -407
  199. package/src/swarm-worktree.test.ts +0 -501
  200. package/src/swarm-worktree.ts +0 -575
  201. package/src/swarm.integration.test.ts +0 -2377
  202. package/src/swarm.ts +0 -38
  203. package/src/tool-adapter.integration.test.ts +0 -1221
  204. package/src/tool-availability.ts +0 -461
  205. package/tsconfig.json +0 -28
@@ -1,774 +0,0 @@
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 { mkdirSync, existsSync } from "node:fs";
32
- import { dirname, join } from "node:path";
33
- import { homedir } from "node:os";
34
-
35
- // SQLite is optional - only available in Bun runtime
36
- // We use dynamic import to avoid breaking Node.js environments
37
- interface BunDatabase {
38
- run(
39
- sql: string,
40
- params?: unknown[],
41
- ): { changes: number; lastInsertRowid: number };
42
- query<T>(sql: string): {
43
- get(...params: unknown[]): T | null;
44
- };
45
- prepare(sql: string): {
46
- run(...params: unknown[]): { changes: number; lastInsertRowid: number };
47
- };
48
- close(): void;
49
- }
50
-
51
- let sqliteAvailable = false;
52
- let createDatabase: ((path: string) => BunDatabase) | null = null;
53
-
54
- // Try to load bun:sqlite at module load time
55
- try {
56
- if (typeof globalThis.Bun !== "undefined") {
57
- // We're in Bun runtime - dynamic import will work
58
- const bunSqlite = await import("bun:sqlite");
59
- createDatabase = (path: string) =>
60
- new bunSqlite.Database(path) as unknown as BunDatabase;
61
- sqliteAvailable = true;
62
- }
63
- } catch {
64
- // Not in Bun runtime, SQLite fallback unavailable
65
- sqliteAvailable = false;
66
- }
67
-
68
- // ============================================================================
69
- // Types
70
- // ============================================================================
71
-
72
- /**
73
- * Result of checking a rate limit
74
- */
75
- export interface RateLimitResult {
76
- /** Whether the request is allowed */
77
- allowed: boolean;
78
- /** Remaining requests in the most restrictive window */
79
- remaining: number;
80
- /** Unix timestamp (ms) when the limit resets */
81
- resetAt: number;
82
- }
83
-
84
- /**
85
- * Rate limiter interface
86
- */
87
- export interface RateLimiter {
88
- /**
89
- * Check if a request is allowed under rate limits
90
- * Checks BOTH minute and hour windows - both must pass
91
- *
92
- * @param agentName - The agent making the request
93
- * @param endpoint - The endpoint being accessed
94
- * @returns Rate limit check result
95
- */
96
- checkLimit(agentName: string, endpoint: string): Promise<RateLimitResult>;
97
-
98
- /**
99
- * Record a request against the rate limit
100
- * Should be called AFTER the request succeeds
101
- *
102
- * @param agentName - The agent making the request
103
- * @param endpoint - The endpoint being accessed
104
- */
105
- recordRequest(agentName: string, endpoint: string): Promise<void>;
106
-
107
- /**
108
- * Close the rate limiter and release resources
109
- */
110
- close(): Promise<void>;
111
- }
112
-
113
- /**
114
- * Rate limit configuration for an endpoint
115
- */
116
- export interface EndpointLimits {
117
- /** Requests allowed per minute */
118
- perMinute: number;
119
- /** Requests allowed per hour */
120
- perHour: number;
121
- }
122
-
123
- // ============================================================================
124
- // Default Limits
125
- // ============================================================================
126
-
127
- /**
128
- * Default rate limits per endpoint
129
- * Can be overridden via OPENCODE_RATE_LIMIT_{ENDPOINT}_PER_MIN and _PER_HOUR
130
- */
131
- export const DEFAULT_LIMITS: Record<string, EndpointLimits> = {
132
- send: { perMinute: 20, perHour: 200 },
133
- reserve: { perMinute: 10, perHour: 100 },
134
- release: { perMinute: 10, perHour: 100 },
135
- ack: { perMinute: 20, perHour: 200 },
136
- inbox: { perMinute: 60, perHour: 600 },
137
- read_message: { perMinute: 60, perHour: 600 },
138
- summarize_thread: { perMinute: 30, perHour: 300 },
139
- search: { perMinute: 30, perHour: 300 },
140
- };
141
-
142
- /**
143
- * Get rate limits for an endpoint, with env var overrides
144
- *
145
- * @param endpoint - The endpoint name
146
- * @returns Rate limits for the endpoint
147
- */
148
- export function getLimitsForEndpoint(endpoint: string): EndpointLimits {
149
- const defaults = DEFAULT_LIMITS[endpoint] || { perMinute: 60, perHour: 600 };
150
- const upperEndpoint = endpoint.toUpperCase();
151
-
152
- const perMinuteEnv =
153
- process.env[`OPENCODE_RATE_LIMIT_${upperEndpoint}_PER_MIN`];
154
- const perHourEnv =
155
- process.env[`OPENCODE_RATE_LIMIT_${upperEndpoint}_PER_HOUR`];
156
-
157
- // Parse and validate env vars, fall back to defaults on NaN
158
- const parsedPerMinute = perMinuteEnv ? parseInt(perMinuteEnv, 10) : NaN;
159
- const parsedPerHour = perHourEnv ? parseInt(perHourEnv, 10) : NaN;
160
-
161
- return {
162
- perMinute: Number.isNaN(parsedPerMinute)
163
- ? defaults.perMinute
164
- : parsedPerMinute,
165
- perHour: Number.isNaN(parsedPerHour) ? defaults.perHour : parsedPerHour,
166
- };
167
- }
168
-
169
- // ============================================================================
170
- // Redis Rate Limiter
171
- // ============================================================================
172
-
173
- /**
174
- * Redis-backed rate limiter using sorted sets
175
- *
176
- * Uses sliding window algorithm:
177
- * 1. Store each request as a member with timestamp as score
178
- * 2. Remove expired entries (outside window)
179
- * 3. Count remaining entries
180
- *
181
- * Key format: ratelimit:{agent}:{endpoint}:{window}
182
- * Window values: "minute" or "hour"
183
- */
184
- export class RedisRateLimiter implements RateLimiter {
185
- private redis: Redis;
186
- private connected: boolean = false;
187
-
188
- constructor(redis: Redis) {
189
- this.redis = redis;
190
- this.connected = true;
191
- }
192
-
193
- /**
194
- * Build Redis key for rate limiting
195
- */
196
- private buildKey(
197
- agentName: string,
198
- endpoint: string,
199
- window: "minute" | "hour",
200
- ): string {
201
- return `ratelimit:${agentName}:${endpoint}:${window}`;
202
- }
203
-
204
- /**
205
- * Get window duration in milliseconds
206
- */
207
- private getWindowDuration(window: "minute" | "hour"): number {
208
- return window === "minute" ? 60_000 : 3_600_000;
209
- }
210
-
211
- async checkLimit(
212
- agentName: string,
213
- endpoint: string,
214
- ): Promise<RateLimitResult> {
215
- const limits = getLimitsForEndpoint(endpoint);
216
- const now = Date.now();
217
-
218
- // Check both windows
219
- const [minuteResult, hourResult] = await Promise.all([
220
- this.checkWindow(agentName, endpoint, "minute", limits.perMinute, now),
221
- this.checkWindow(agentName, endpoint, "hour", limits.perHour, now),
222
- ]);
223
-
224
- // Return the most restrictive result (both windows must allow)
225
- if (!minuteResult.allowed) {
226
- return minuteResult;
227
- }
228
- if (!hourResult.allowed) {
229
- return hourResult;
230
- }
231
-
232
- // Both allowed - return the one with fewer remaining
233
- return minuteResult.remaining <= hourResult.remaining
234
- ? minuteResult
235
- : hourResult;
236
- }
237
-
238
- /**
239
- * Check a single window's rate limit
240
- */
241
- private async checkWindow(
242
- agentName: string,
243
- endpoint: string,
244
- window: "minute" | "hour",
245
- limit: number,
246
- now: number,
247
- ): Promise<RateLimitResult> {
248
- const key = this.buildKey(agentName, endpoint, window);
249
- const windowDuration = this.getWindowDuration(window);
250
- const windowStart = now - windowDuration;
251
-
252
- // Remove expired entries, count current ones, and fetch oldest in a single pipeline
253
- const pipeline = this.redis.pipeline();
254
- pipeline.zremrangebyscore(key, 0, windowStart);
255
- pipeline.zcard(key);
256
- pipeline.zrange(key, 0, 0, "WITHSCORES"); // Fetch oldest entry atomically
257
-
258
- const results = await pipeline.exec();
259
- if (!results) {
260
- return { allowed: true, remaining: limit, resetAt: now + windowDuration };
261
- }
262
-
263
- const count = (results[1]?.[1] as number) || 0;
264
- const remaining = Math.max(0, limit - count);
265
- const allowed = count < limit;
266
-
267
- // Calculate reset time based on oldest entry in window (fetched atomically)
268
- let resetAt = now + windowDuration;
269
- if (!allowed) {
270
- const oldest = (results[2]?.[1] as string[]) || [];
271
- if (oldest.length >= 2) {
272
- const oldestTimestamp = parseInt(oldest[1], 10);
273
- resetAt = oldestTimestamp + windowDuration;
274
- }
275
- }
276
-
277
- return { allowed, remaining, resetAt };
278
- }
279
-
280
- async recordRequest(agentName: string, endpoint: string): Promise<void> {
281
- const now = Date.now();
282
- const memberId = crypto.randomUUID();
283
-
284
- // Record in both windows
285
- const minuteKey = this.buildKey(agentName, endpoint, "minute");
286
- const hourKey = this.buildKey(agentName, endpoint, "hour");
287
-
288
- const pipeline = this.redis.pipeline();
289
-
290
- // Add to minute window with TTL
291
- pipeline.zadd(minuteKey, now, `${memberId}:minute`);
292
- pipeline.expire(minuteKey, 120); // 2 minutes TTL for safety
293
-
294
- // Add to hour window with TTL
295
- pipeline.zadd(hourKey, now, `${memberId}:hour`);
296
- pipeline.expire(hourKey, 7200); // 2 hours TTL for safety
297
-
298
- await pipeline.exec();
299
- }
300
-
301
- async close(): Promise<void> {
302
- if (this.connected) {
303
- await this.redis.quit();
304
- this.connected = false;
305
- }
306
- }
307
- }
308
-
309
- // ============================================================================
310
- // SQLite Rate Limiter
311
- // ============================================================================
312
-
313
- /**
314
- * SQLite-backed rate limiter for local/fallback use
315
- *
316
- * Table schema:
317
- * - agent_name: TEXT
318
- * - endpoint: TEXT
319
- * - window: TEXT ('minute' or 'hour')
320
- * - timestamp: INTEGER (Unix ms)
321
- *
322
- * Uses sliding window via COUNT query with timestamp filter.
323
- */
324
- export class SqliteRateLimiter implements RateLimiter {
325
- private db: BunDatabase;
326
-
327
- constructor(dbPath: string) {
328
- if (!sqliteAvailable || !createDatabase) {
329
- throw new Error("SQLite is not available in this runtime (requires Bun)");
330
- }
331
-
332
- // Ensure directory exists
333
- const dir = dirname(dbPath);
334
- if (!existsSync(dir)) {
335
- mkdirSync(dir, { recursive: true });
336
- }
337
-
338
- this.db = createDatabase(dbPath);
339
- this.initialize();
340
- }
341
-
342
- /**
343
- * Initialize the database schema and cleanup old entries
344
- */
345
- private initialize(): void {
346
- // Create table if not exists
347
- this.db.run(`
348
- CREATE TABLE IF NOT EXISTS rate_limits (
349
- id INTEGER PRIMARY KEY AUTOINCREMENT,
350
- agent_name TEXT NOT NULL,
351
- endpoint TEXT NOT NULL,
352
- window TEXT NOT NULL,
353
- timestamp INTEGER NOT NULL
354
- )
355
- `);
356
-
357
- // Create indexes for fast queries
358
- this.db.run(`
359
- CREATE INDEX IF NOT EXISTS idx_rate_limits_lookup
360
- ON rate_limits (agent_name, endpoint, window, timestamp)
361
- `);
362
-
363
- // Cleanup old entries (older than 2 hours)
364
- const cutoff = Date.now() - 7_200_000;
365
- this.db.run(`DELETE FROM rate_limits WHERE timestamp < ?`, [cutoff]);
366
- }
367
-
368
- async checkLimit(
369
- agentName: string,
370
- endpoint: string,
371
- ): Promise<RateLimitResult> {
372
- const limits = getLimitsForEndpoint(endpoint);
373
- const now = Date.now();
374
-
375
- // Check both windows
376
- const minuteResult = this.checkWindow(
377
- agentName,
378
- endpoint,
379
- "minute",
380
- limits.perMinute,
381
- now,
382
- );
383
- const hourResult = this.checkWindow(
384
- agentName,
385
- endpoint,
386
- "hour",
387
- limits.perHour,
388
- now,
389
- );
390
-
391
- // Return the most restrictive result (both windows must allow)
392
- if (!minuteResult.allowed) {
393
- return minuteResult;
394
- }
395
- if (!hourResult.allowed) {
396
- return hourResult;
397
- }
398
-
399
- // Both allowed - return the one with fewer remaining
400
- return minuteResult.remaining <= hourResult.remaining
401
- ? minuteResult
402
- : hourResult;
403
- }
404
-
405
- /**
406
- * Check a single window's rate limit
407
- */
408
- private checkWindow(
409
- agentName: string,
410
- endpoint: string,
411
- window: "minute" | "hour",
412
- limit: number,
413
- now: number,
414
- ): RateLimitResult {
415
- const windowDuration = window === "minute" ? 60_000 : 3_600_000;
416
- const windowStart = now - windowDuration;
417
-
418
- // Count requests in window
419
- const result = this.db
420
- .query<{ count: number }>(
421
- `SELECT COUNT(*) as count FROM rate_limits
422
- WHERE agent_name = ? AND endpoint = ? AND window = ? AND timestamp > ?`,
423
- )
424
- .get(agentName, endpoint, window, windowStart);
425
-
426
- // Validate result before accessing properties
427
- if (!result || typeof result.count !== "number") {
428
- // Query failed or returned invalid data, assume no usage
429
- return {
430
- allowed: true,
431
- remaining: limit,
432
- resetAt: now + windowDuration,
433
- };
434
- }
435
-
436
- const count = result.count;
437
- const remaining = Math.max(0, limit - count);
438
- const allowed = count < limit;
439
-
440
- // Calculate reset time based on oldest entry in window
441
- let resetAt = now + windowDuration;
442
- if (!allowed) {
443
- const oldest = this.db
444
- .query<{ timestamp: number }>(
445
- `SELECT MIN(timestamp) as timestamp FROM rate_limits
446
- WHERE agent_name = ? AND endpoint = ? AND window = ? AND timestamp > ?`,
447
- )
448
- .get(agentName, endpoint, window, windowStart);
449
-
450
- // Validate oldest result before accessing properties
451
- if (oldest && typeof oldest.timestamp === "number") {
452
- resetAt = oldest.timestamp + windowDuration;
453
- }
454
- }
455
-
456
- return { allowed, remaining, resetAt };
457
- }
458
-
459
- /**
460
- * Clean up old rate limit entries in bounded batches
461
- *
462
- * Limits cleanup to prevent blocking recordRequest on large datasets:
463
- * - BATCH_SIZE: 1000 rows per iteration
464
- * - MAX_BATCHES: 10 (max 10k rows per cleanup invocation)
465
- *
466
- * Stops early if fewer than BATCH_SIZE rows deleted (no more to clean).
467
- */
468
- private cleanup(): void {
469
- const BATCH_SIZE = 1000;
470
- const MAX_BATCHES = 10;
471
- const cutoff = Date.now() - 7_200_000; // 2 hours
472
-
473
- let totalDeleted = 0;
474
-
475
- // Run bounded batches
476
- for (let i = 0; i < MAX_BATCHES; i++) {
477
- const result = this.db.run(
478
- `DELETE FROM rate_limits
479
- WHERE rowid IN (
480
- SELECT rowid FROM rate_limits
481
- WHERE timestamp < ?
482
- LIMIT ?
483
- )`,
484
- [cutoff, BATCH_SIZE],
485
- );
486
-
487
- totalDeleted += result.changes;
488
-
489
- // Stop if we deleted less than batch size (no more to delete)
490
- if (result.changes < BATCH_SIZE) break;
491
- }
492
-
493
- }
494
-
495
- async recordRequest(agentName: string, endpoint: string): Promise<void> {
496
- const now = Date.now();
497
-
498
- // Record in both windows
499
- const stmt = this.db.prepare(
500
- `INSERT INTO rate_limits (agent_name, endpoint, window, timestamp) VALUES (?, ?, ?, ?)`,
501
- );
502
-
503
- stmt.run(agentName, endpoint, "minute", now);
504
- stmt.run(agentName, endpoint, "hour", now);
505
-
506
- // Opportunistic cleanup of old entries (1% chance to avoid overhead)
507
- // Now bounded to prevent blocking on large datasets
508
- if (Math.random() < 0.01) {
509
- this.cleanup();
510
- }
511
- }
512
-
513
- async close(): Promise<void> {
514
- this.db.close();
515
- }
516
- }
517
-
518
- // ============================================================================
519
- // In-Memory Rate Limiter (for testing)
520
- // ============================================================================
521
-
522
- /**
523
- * In-memory rate limiter for testing
524
- *
525
- * Uses Map storage with timestamp arrays per key.
526
- * No persistence - resets on process restart.
527
- */
528
- export class InMemoryRateLimiter implements RateLimiter {
529
- private storage: Map<string, number[]> = new Map();
530
-
531
- private buildKey(
532
- agentName: string,
533
- endpoint: string,
534
- window: "minute" | "hour",
535
- ): string {
536
- return `${agentName}:${endpoint}:${window}`;
537
- }
538
-
539
- async checkLimit(
540
- agentName: string,
541
- endpoint: string,
542
- ): Promise<RateLimitResult> {
543
- const limits = getLimitsForEndpoint(endpoint);
544
- const now = Date.now();
545
-
546
- const minuteResult = this.checkWindow(
547
- agentName,
548
- endpoint,
549
- "minute",
550
- limits.perMinute,
551
- now,
552
- );
553
- const hourResult = this.checkWindow(
554
- agentName,
555
- endpoint,
556
- "hour",
557
- limits.perHour,
558
- now,
559
- );
560
-
561
- // Return the most restrictive result (both windows must allow)
562
- if (!minuteResult.allowed) return minuteResult;
563
- if (!hourResult.allowed) return hourResult;
564
-
565
- return minuteResult.remaining <= hourResult.remaining
566
- ? minuteResult
567
- : hourResult;
568
- }
569
-
570
- private checkWindow(
571
- agentName: string,
572
- endpoint: string,
573
- window: "minute" | "hour",
574
- limit: number,
575
- now: number,
576
- ): RateLimitResult {
577
- const key = this.buildKey(agentName, endpoint, window);
578
- const windowDuration = window === "minute" ? 60_000 : 3_600_000;
579
- const windowStart = now - windowDuration;
580
-
581
- // Get and filter timestamps
582
- let timestamps = this.storage.get(key) || [];
583
- timestamps = timestamps.filter((t) => t > windowStart);
584
- this.storage.set(key, timestamps);
585
-
586
- const count = timestamps.length;
587
- const remaining = Math.max(0, limit - count);
588
- const allowed = count < limit;
589
-
590
- let resetAt = now + windowDuration;
591
- if (!allowed && timestamps.length > 0) {
592
- resetAt = timestamps[0] + windowDuration;
593
- }
594
-
595
- return { allowed, remaining, resetAt };
596
- }
597
-
598
- async recordRequest(agentName: string, endpoint: string): Promise<void> {
599
- const now = Date.now();
600
-
601
- // Record in both windows
602
- for (const window of ["minute", "hour"] as const) {
603
- const key = this.buildKey(agentName, endpoint, window);
604
- const timestamps = this.storage.get(key) || [];
605
- timestamps.push(now);
606
- this.storage.set(key, timestamps);
607
- }
608
- }
609
-
610
- async close(): Promise<void> {
611
- this.storage.clear();
612
- }
613
-
614
- /**
615
- * Reset all rate limits (for testing)
616
- */
617
- reset(): void {
618
- this.storage.clear();
619
- }
620
- }
621
-
622
- // ============================================================================
623
- // Factory
624
- // ============================================================================
625
-
626
- /** Track if we've warned about fallback (warn only once) */
627
- let hasWarnedAboutFallback = false;
628
-
629
- /**
630
- * Create a rate limiter with automatic backend selection
631
- *
632
- * Tries Redis first, falls back to SQLite on connection failure.
633
- * Warns once when falling back to SQLite.
634
- *
635
- * @returns Configured rate limiter instance
636
- *
637
- * @example
638
- * ```typescript
639
- * // Auto-select backend
640
- * const limiter = await createRateLimiter();
641
- *
642
- * // Force SQLite
643
- * const limiter = await createRateLimiter({ backend: "sqlite" });
644
- *
645
- * // Force in-memory (testing)
646
- * const limiter = await createRateLimiter({ backend: "memory" });
647
- * ```
648
- */
649
- export async function createRateLimiter(options?: {
650
- backend?: "redis" | "sqlite" | "memory";
651
- redisUrl?: string;
652
- sqlitePath?: string;
653
- }): Promise<RateLimiter> {
654
- const {
655
- backend,
656
- redisUrl = process.env.OPENCODE_RATE_LIMIT_REDIS_URL ||
657
- "redis://localhost:6379",
658
- sqlitePath = process.env.OPENCODE_RATE_LIMIT_SQLITE_PATH ||
659
- join(homedir(), ".config", "opencode", "rate-limits.db"),
660
- } = options || {};
661
-
662
- // Explicit backend selection
663
- if (backend === "memory") {
664
- return new InMemoryRateLimiter();
665
- }
666
-
667
- if (backend === "sqlite") {
668
- if (!sqliteAvailable) {
669
- throw new Error(
670
- "SQLite backend requested but not available (requires Bun runtime)",
671
- );
672
- }
673
- return new SqliteRateLimiter(sqlitePath);
674
- }
675
-
676
- if (backend === "redis") {
677
- const redis = new Redis(redisUrl);
678
- return new RedisRateLimiter(redis);
679
- }
680
-
681
- // Auto-select: try Redis first with retry, fall back to SQLite
682
- const maxRetries = 3;
683
- const retryDelays = [100, 500, 1000]; // exponential backoff
684
-
685
- for (let attempt = 0; attempt < maxRetries; attempt++) {
686
- try {
687
- const redis = new Redis(redisUrl, {
688
- connectTimeout: 2000,
689
- maxRetriesPerRequest: 1,
690
- retryStrategy: () => null, // Don't retry on failure
691
- lazyConnect: true,
692
- });
693
-
694
- // Test connection
695
- await redis.connect();
696
- await redis.ping();
697
-
698
- return new RedisRateLimiter(redis);
699
- } catch (error) {
700
- const isLastAttempt = attempt === maxRetries - 1;
701
-
702
- if (isLastAttempt) {
703
- // All retries exhausted, fall back to SQLite or in-memory
704
- if (!hasWarnedAboutFallback) {
705
- const fallbackType = sqliteAvailable ? "SQLite" : "in-memory";
706
- const fallbackLocation = sqliteAvailable ? ` at ${sqlitePath}` : "";
707
- console.warn(
708
- `[rate-limiter] Redis connection failed after ${maxRetries} attempts (${redisUrl}), falling back to ${fallbackType}${fallbackLocation}`,
709
- );
710
- hasWarnedAboutFallback = true;
711
- }
712
-
713
- // Use SQLite if available, otherwise fall back to in-memory
714
- if (sqliteAvailable) {
715
- return new SqliteRateLimiter(sqlitePath);
716
- }
717
- return new InMemoryRateLimiter();
718
- }
719
-
720
- // Wait before retrying (exponential backoff)
721
- await new Promise((resolve) => setTimeout(resolve, retryDelays[attempt]));
722
- }
723
- }
724
-
725
- // Fallback (should never reach here due to return in last attempt)
726
- if (sqliteAvailable) {
727
- return new SqliteRateLimiter(sqlitePath);
728
- }
729
- return new InMemoryRateLimiter();
730
- }
731
-
732
- /**
733
- * Reset the fallback warning flag (for testing)
734
- */
735
- export function resetFallbackWarning(): void {
736
- hasWarnedAboutFallback = false;
737
- }
738
-
739
- // ============================================================================
740
- // Global Instance
741
- // ============================================================================
742
-
743
- let globalRateLimiter: RateLimiter | null = null;
744
-
745
- /**
746
- * Get or create the global rate limiter instance
747
- *
748
- * Uses auto-selection (Redis → SQLite) by default.
749
- */
750
- export async function getRateLimiter(): Promise<RateLimiter> {
751
- if (!globalRateLimiter) {
752
- globalRateLimiter = await createRateLimiter();
753
- }
754
- return globalRateLimiter;
755
- }
756
-
757
- /**
758
- * Set the global rate limiter instance
759
- *
760
- * Useful for testing or custom configurations.
761
- */
762
- export function setRateLimiter(limiter: RateLimiter): void {
763
- globalRateLimiter = limiter;
764
- }
765
-
766
- /**
767
- * Reset the global rate limiter instance
768
- */
769
- export async function resetRateLimiter(): Promise<void> {
770
- if (globalRateLimiter) {
771
- await globalRateLimiter.close();
772
- globalRateLimiter = null;
773
- }
774
- }