opencode-swarm-plugin 0.44.0 → 0.44.2

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 (215) hide show
  1. package/bin/swarm.serve.test.ts +6 -4
  2. package/bin/swarm.ts +18 -12
  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/hive.js +14834 -0
  7. package/dist/index.d.ts +18 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +7743 -62593
  10. package/dist/plugin.js +24052 -78907
  11. package/dist/swarm-orchestrate.d.ts.map +1 -1
  12. package/dist/swarm-prompts.d.ts.map +1 -1
  13. package/dist/swarm-prompts.js +39407 -0
  14. package/dist/swarm-review.d.ts.map +1 -1
  15. package/dist/swarm-validation.d.ts +127 -0
  16. package/dist/swarm-validation.d.ts.map +1 -0
  17. package/dist/validators/index.d.ts +7 -0
  18. package/dist/validators/index.d.ts.map +1 -0
  19. package/dist/validators/schema-validator.d.ts +58 -0
  20. package/dist/validators/schema-validator.d.ts.map +1 -0
  21. package/package.json +17 -5
  22. package/.changeset/swarm-insights-data-layer.md +0 -63
  23. package/.hive/analysis/eval-failure-analysis-2025-12-25.md +0 -331
  24. package/.hive/analysis/session-data-quality-audit.md +0 -320
  25. package/.hive/eval-results.json +0 -483
  26. package/.hive/issues.jsonl +0 -138
  27. package/.hive/memories.jsonl +0 -729
  28. package/.opencode/eval-history.jsonl +0 -327
  29. package/.turbo/turbo-build.log +0 -9
  30. package/CHANGELOG.md +0 -2286
  31. package/SCORER-ANALYSIS.md +0 -598
  32. package/docs/analysis/subagent-coordination-patterns.md +0 -902
  33. package/docs/analysis-socratic-planner-pattern.md +0 -504
  34. package/docs/planning/ADR-001-monorepo-structure.md +0 -171
  35. package/docs/planning/ADR-002-package-extraction.md +0 -393
  36. package/docs/planning/ADR-003-performance-improvements.md +0 -451
  37. package/docs/planning/ADR-004-message-queue-features.md +0 -187
  38. package/docs/planning/ADR-005-devtools-observability.md +0 -202
  39. package/docs/planning/ADR-007-swarm-enhancements-worktree-review.md +0 -168
  40. package/docs/planning/ADR-008-worker-handoff-protocol.md +0 -293
  41. package/docs/planning/ADR-009-oh-my-opencode-patterns.md +0 -353
  42. package/docs/planning/ADR-010-cass-inhousing.md +0 -1215
  43. package/docs/planning/ROADMAP.md +0 -368
  44. package/docs/semantic-memory-cli-syntax.md +0 -123
  45. package/docs/swarm-mail-architecture.md +0 -1147
  46. package/docs/testing/context-recovery-test.md +0 -470
  47. package/evals/ARCHITECTURE.md +0 -1189
  48. package/evals/README.md +0 -768
  49. package/evals/compaction-prompt.eval.ts +0 -149
  50. package/evals/compaction-resumption.eval.ts +0 -289
  51. package/evals/coordinator-behavior.eval.ts +0 -307
  52. package/evals/coordinator-session.eval.ts +0 -154
  53. package/evals/evalite.config.ts.bak +0 -15
  54. package/evals/example.eval.ts +0 -31
  55. package/evals/fixtures/cass-baseline.ts +0 -217
  56. package/evals/fixtures/compaction-cases.ts +0 -350
  57. package/evals/fixtures/compaction-prompt-cases.ts +0 -311
  58. package/evals/fixtures/coordinator-sessions.ts +0 -328
  59. package/evals/fixtures/decomposition-cases.ts +0 -105
  60. package/evals/lib/compaction-loader.test.ts +0 -248
  61. package/evals/lib/compaction-loader.ts +0 -320
  62. package/evals/lib/data-loader.evalite-test.ts +0 -289
  63. package/evals/lib/data-loader.test.ts +0 -345
  64. package/evals/lib/data-loader.ts +0 -281
  65. package/evals/lib/llm.ts +0 -115
  66. package/evals/scorers/compaction-prompt-scorers.ts +0 -145
  67. package/evals/scorers/compaction-scorers.ts +0 -305
  68. package/evals/scorers/coordinator-discipline.evalite-test.ts +0 -539
  69. package/evals/scorers/coordinator-discipline.ts +0 -325
  70. package/evals/scorers/index.test.ts +0 -146
  71. package/evals/scorers/index.ts +0 -328
  72. package/evals/scorers/outcome-scorers.evalite-test.ts +0 -27
  73. package/evals/scorers/outcome-scorers.ts +0 -349
  74. package/evals/swarm-decomposition.eval.ts +0 -121
  75. package/examples/commands/swarm.md +0 -745
  76. package/examples/plugin-wrapper-template.ts +0 -2515
  77. package/examples/skills/hive-workflow/SKILL.md +0 -212
  78. package/examples/skills/skill-creator/SKILL.md +0 -223
  79. package/examples/skills/swarm-coordination/SKILL.md +0 -292
  80. package/global-skills/cli-builder/SKILL.md +0 -344
  81. package/global-skills/cli-builder/references/advanced-patterns.md +0 -244
  82. package/global-skills/learning-systems/SKILL.md +0 -644
  83. package/global-skills/skill-creator/LICENSE.txt +0 -202
  84. package/global-skills/skill-creator/SKILL.md +0 -352
  85. package/global-skills/skill-creator/references/output-patterns.md +0 -82
  86. package/global-skills/skill-creator/references/workflows.md +0 -28
  87. package/global-skills/swarm-coordination/SKILL.md +0 -995
  88. package/global-skills/swarm-coordination/references/coordinator-patterns.md +0 -235
  89. package/global-skills/swarm-coordination/references/strategies.md +0 -138
  90. package/global-skills/system-design/SKILL.md +0 -213
  91. package/global-skills/testing-patterns/SKILL.md +0 -430
  92. package/global-skills/testing-patterns/references/dependency-breaking-catalog.md +0 -586
  93. package/opencode-swarm-plugin-0.30.7.tgz +0 -0
  94. package/opencode-swarm-plugin-0.31.0.tgz +0 -0
  95. package/scripts/cleanup-test-memories.ts +0 -346
  96. package/scripts/init-skill.ts +0 -222
  97. package/scripts/migrate-unknown-sessions.ts +0 -349
  98. package/scripts/validate-skill.ts +0 -204
  99. package/src/agent-mail.ts +0 -1724
  100. package/src/anti-patterns.test.ts +0 -1167
  101. package/src/anti-patterns.ts +0 -448
  102. package/src/compaction-capture.integration.test.ts +0 -257
  103. package/src/compaction-hook.test.ts +0 -838
  104. package/src/compaction-hook.ts +0 -1204
  105. package/src/compaction-observability.integration.test.ts +0 -139
  106. package/src/compaction-observability.test.ts +0 -187
  107. package/src/compaction-observability.ts +0 -324
  108. package/src/compaction-prompt-scorers.test.ts +0 -475
  109. package/src/compaction-prompt-scoring.ts +0 -300
  110. package/src/contributor-tools.test.ts +0 -133
  111. package/src/contributor-tools.ts +0 -201
  112. package/src/dashboard.test.ts +0 -611
  113. package/src/dashboard.ts +0 -462
  114. package/src/error-enrichment.test.ts +0 -403
  115. package/src/error-enrichment.ts +0 -219
  116. package/src/eval-capture.test.ts +0 -1015
  117. package/src/eval-capture.ts +0 -929
  118. package/src/eval-gates.test.ts +0 -306
  119. package/src/eval-gates.ts +0 -218
  120. package/src/eval-history.test.ts +0 -508
  121. package/src/eval-history.ts +0 -214
  122. package/src/eval-learning.test.ts +0 -378
  123. package/src/eval-learning.ts +0 -360
  124. package/src/eval-runner.test.ts +0 -223
  125. package/src/eval-runner.ts +0 -402
  126. package/src/export-tools.test.ts +0 -476
  127. package/src/export-tools.ts +0 -257
  128. package/src/hive.integration.test.ts +0 -2241
  129. package/src/hive.ts +0 -1628
  130. package/src/index.ts +0 -940
  131. package/src/learning.integration.test.ts +0 -1815
  132. package/src/learning.ts +0 -1079
  133. package/src/logger.test.ts +0 -189
  134. package/src/logger.ts +0 -135
  135. package/src/mandate-promotion.test.ts +0 -473
  136. package/src/mandate-promotion.ts +0 -239
  137. package/src/mandate-storage.integration.test.ts +0 -601
  138. package/src/mandate-storage.test.ts +0 -578
  139. package/src/mandate-storage.ts +0 -794
  140. package/src/mandates.ts +0 -540
  141. package/src/memory-tools.test.ts +0 -195
  142. package/src/memory-tools.ts +0 -344
  143. package/src/memory.integration.test.ts +0 -334
  144. package/src/memory.test.ts +0 -158
  145. package/src/memory.ts +0 -527
  146. package/src/model-selection.test.ts +0 -188
  147. package/src/model-selection.ts +0 -68
  148. package/src/observability-tools.test.ts +0 -359
  149. package/src/observability-tools.ts +0 -871
  150. package/src/output-guardrails.test.ts +0 -438
  151. package/src/output-guardrails.ts +0 -381
  152. package/src/pattern-maturity.test.ts +0 -1160
  153. package/src/pattern-maturity.ts +0 -525
  154. package/src/planning-guardrails.test.ts +0 -491
  155. package/src/planning-guardrails.ts +0 -438
  156. package/src/plugin.ts +0 -23
  157. package/src/post-compaction-tracker.test.ts +0 -251
  158. package/src/post-compaction-tracker.ts +0 -237
  159. package/src/query-tools.test.ts +0 -636
  160. package/src/query-tools.ts +0 -324
  161. package/src/rate-limiter.integration.test.ts +0 -466
  162. package/src/rate-limiter.ts +0 -774
  163. package/src/replay-tools.test.ts +0 -496
  164. package/src/replay-tools.ts +0 -240
  165. package/src/repo-crawl.integration.test.ts +0 -441
  166. package/src/repo-crawl.ts +0 -610
  167. package/src/schemas/cell-events.test.ts +0 -347
  168. package/src/schemas/cell-events.ts +0 -807
  169. package/src/schemas/cell.ts +0 -257
  170. package/src/schemas/evaluation.ts +0 -166
  171. package/src/schemas/index.test.ts +0 -199
  172. package/src/schemas/index.ts +0 -286
  173. package/src/schemas/mandate.ts +0 -232
  174. package/src/schemas/swarm-context.ts +0 -115
  175. package/src/schemas/task.ts +0 -161
  176. package/src/schemas/worker-handoff.test.ts +0 -302
  177. package/src/schemas/worker-handoff.ts +0 -131
  178. package/src/sessions/agent-discovery.test.ts +0 -137
  179. package/src/sessions/agent-discovery.ts +0 -112
  180. package/src/sessions/index.ts +0 -15
  181. package/src/skills.integration.test.ts +0 -1192
  182. package/src/skills.test.ts +0 -643
  183. package/src/skills.ts +0 -1549
  184. package/src/storage.integration.test.ts +0 -341
  185. package/src/storage.ts +0 -884
  186. package/src/structured.integration.test.ts +0 -817
  187. package/src/structured.test.ts +0 -1046
  188. package/src/structured.ts +0 -762
  189. package/src/swarm-decompose.test.ts +0 -188
  190. package/src/swarm-decompose.ts +0 -1302
  191. package/src/swarm-deferred.integration.test.ts +0 -157
  192. package/src/swarm-deferred.test.ts +0 -38
  193. package/src/swarm-insights.test.ts +0 -214
  194. package/src/swarm-insights.ts +0 -459
  195. package/src/swarm-mail.integration.test.ts +0 -970
  196. package/src/swarm-mail.ts +0 -739
  197. package/src/swarm-orchestrate.integration.test.ts +0 -282
  198. package/src/swarm-orchestrate.test.ts +0 -548
  199. package/src/swarm-orchestrate.ts +0 -3084
  200. package/src/swarm-prompts.test.ts +0 -1270
  201. package/src/swarm-prompts.ts +0 -2077
  202. package/src/swarm-research.integration.test.ts +0 -701
  203. package/src/swarm-research.test.ts +0 -698
  204. package/src/swarm-research.ts +0 -472
  205. package/src/swarm-review.integration.test.ts +0 -285
  206. package/src/swarm-review.test.ts +0 -879
  207. package/src/swarm-review.ts +0 -709
  208. package/src/swarm-strategies.ts +0 -407
  209. package/src/swarm-worktree.test.ts +0 -501
  210. package/src/swarm-worktree.ts +0 -575
  211. package/src/swarm.integration.test.ts +0 -2377
  212. package/src/swarm.ts +0 -38
  213. package/src/tool-adapter.integration.test.ts +0 -1221
  214. package/src/tool-availability.ts +0 -461
  215. 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
- }