opencode-swarm-plugin 0.12.4 → 0.12.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/beads.ts CHANGED
@@ -55,6 +55,10 @@ export class BeadValidationError extends Error {
55
55
 
56
56
  /**
57
57
  * Build a bd create command from args
58
+ *
59
+ * Note: Bun's `$` template literal properly escapes arguments when passed as array.
60
+ * Each array element is treated as a separate argument, preventing shell injection.
61
+ * Example: ["bd", "create", "; rm -rf /"] becomes: bd create "; rm -rf /"
58
62
  */
59
63
  function buildCreateCommand(args: BeadCreateArgs): string[] {
60
64
  const parts = ["bd", "create", args.title];
@@ -250,25 +254,40 @@ export const beads_create_epic = tool({
250
254
 
251
255
  return JSON.stringify(result, null, 2);
252
256
  } catch (error) {
253
- // Partial failure - return what was created with rollback hint
254
- const rollbackHint = created
255
- .map((b) => `bd close ${b.id} --reason "Rollback partial epic"`)
256
- .join("\n");
257
+ // Partial failure - execute rollback automatically
258
+ const rollbackCommands: string[] = [];
259
+
260
+ for (const bead of created) {
261
+ try {
262
+ const closeCmd = [
263
+ "bd",
264
+ "close",
265
+ bead.id,
266
+ "--reason",
267
+ "Rollback partial epic",
268
+ "--json",
269
+ ];
270
+ await Bun.$`${closeCmd}`.quiet().nothrow();
271
+ rollbackCommands.push(
272
+ `bd close ${bead.id} --reason "Rollback partial epic"`,
273
+ );
274
+ } catch (rollbackError) {
275
+ // Log rollback failure but continue
276
+ console.error(`Failed to rollback bead ${bead.id}:`, rollbackError);
277
+ }
278
+ }
257
279
 
258
- const result: EpicCreateResult = {
259
- success: false,
260
- epic: created[0] || ({} as Bead),
261
- subtasks: created.slice(1),
262
- rollback_hint: rollbackHint,
263
- };
280
+ // Throw error with rollback info
281
+ const errorMsg = error instanceof Error ? error.message : String(error);
282
+ const rollbackInfo =
283
+ rollbackCommands.length > 0
284
+ ? `\n\nRolled back ${rollbackCommands.length} bead(s):\n${rollbackCommands.join("\n")}`
285
+ : "\n\nNo beads to rollback.";
264
286
 
265
- return JSON.stringify(
266
- {
267
- ...result,
268
- error: error instanceof Error ? error.message : String(error),
269
- },
270
- null,
271
- 2,
287
+ throw new BeadError(
288
+ `Epic creation failed: ${errorMsg}${rollbackInfo}`,
289
+ "beads_create_epic",
290
+ 1,
272
291
  );
273
292
  }
274
293
  },
@@ -487,10 +506,38 @@ export const beads_sync = tool({
487
506
  },
488
507
  async execute(args, ctx) {
489
508
  const autoPull = args.auto_pull ?? true;
509
+ const TIMEOUT_MS = 30000; // 30 seconds
510
+
511
+ /**
512
+ * Helper to run a command with timeout
513
+ */
514
+ const withTimeout = async <T>(
515
+ promise: Promise<T>,
516
+ timeoutMs: number,
517
+ operation: string,
518
+ ): Promise<T> => {
519
+ const timeoutPromise = new Promise<never>((_, reject) =>
520
+ setTimeout(
521
+ () =>
522
+ reject(
523
+ new BeadError(
524
+ `Operation timed out after ${timeoutMs}ms`,
525
+ operation,
526
+ ),
527
+ ),
528
+ timeoutMs,
529
+ ),
530
+ );
531
+ return Promise.race([promise, timeoutPromise]);
532
+ };
490
533
 
491
534
  // 1. Pull if requested
492
535
  if (autoPull) {
493
- const pullResult = await Bun.$`git pull --rebase`.quiet().nothrow();
536
+ const pullResult = await withTimeout(
537
+ Bun.$`git pull --rebase`.quiet().nothrow(),
538
+ TIMEOUT_MS,
539
+ "git pull --rebase",
540
+ );
494
541
  if (pullResult.exitCode !== 0) {
495
542
  throw new BeadError(
496
543
  `Failed to pull: ${pullResult.stderr.toString()}`,
@@ -501,7 +548,11 @@ export const beads_sync = tool({
501
548
  }
502
549
 
503
550
  // 2. Sync beads
504
- const syncResult = await Bun.$`bd sync`.quiet().nothrow();
551
+ const syncResult = await withTimeout(
552
+ Bun.$`bd sync`.quiet().nothrow(),
553
+ TIMEOUT_MS,
554
+ "bd sync",
555
+ );
505
556
  if (syncResult.exitCode !== 0) {
506
557
  throw new BeadError(
507
558
  `Failed to sync beads: ${syncResult.stderr.toString()}`,
@@ -511,7 +562,11 @@ export const beads_sync = tool({
511
562
  }
512
563
 
513
564
  // 3. Push
514
- const pushResult = await Bun.$`git push`.quiet().nothrow();
565
+ const pushResult = await withTimeout(
566
+ Bun.$`git push`.quiet().nothrow(),
567
+ TIMEOUT_MS,
568
+ "git push",
569
+ );
515
570
  if (pushResult.exitCode !== 0) {
516
571
  throw new BeadError(
517
572
  `Failed to push: ${pushResult.stderr.toString()}`,
@@ -122,9 +122,15 @@ export function getLimitsForEndpoint(endpoint: string): EndpointLimits {
122
122
  const perHourEnv =
123
123
  process.env[`OPENCODE_RATE_LIMIT_${upperEndpoint}_PER_HOUR`];
124
124
 
125
+ // Parse and validate env vars, fall back to defaults on NaN
126
+ const parsedPerMinute = perMinuteEnv ? parseInt(perMinuteEnv, 10) : NaN;
127
+ const parsedPerHour = perHourEnv ? parseInt(perHourEnv, 10) : NaN;
128
+
125
129
  return {
126
- perMinute: perMinuteEnv ? parseInt(perMinuteEnv, 10) : defaults.perMinute,
127
- perHour: perHourEnv ? parseInt(perHourEnv, 10) : defaults.perHour,
130
+ perMinute: Number.isNaN(parsedPerMinute)
131
+ ? defaults.perMinute
132
+ : parsedPerMinute,
133
+ perHour: Number.isNaN(parsedPerHour) ? defaults.perHour : parsedPerHour,
128
134
  };
129
135
  }
130
136
 
@@ -211,10 +217,11 @@ export class RedisRateLimiter implements RateLimiter {
211
217
  const windowDuration = this.getWindowDuration(window);
212
218
  const windowStart = now - windowDuration;
213
219
 
214
- // Remove expired entries and count current ones in a pipeline
220
+ // Remove expired entries, count current ones, and fetch oldest in a single pipeline
215
221
  const pipeline = this.redis.pipeline();
216
222
  pipeline.zremrangebyscore(key, 0, windowStart);
217
223
  pipeline.zcard(key);
224
+ pipeline.zrange(key, 0, 0, "WITHSCORES"); // Fetch oldest entry atomically
218
225
 
219
226
  const results = await pipeline.exec();
220
227
  if (!results) {
@@ -225,11 +232,10 @@ export class RedisRateLimiter implements RateLimiter {
225
232
  const remaining = Math.max(0, limit - count);
226
233
  const allowed = count < limit;
227
234
 
228
- // Calculate reset time based on oldest entry in window
235
+ // Calculate reset time based on oldest entry in window (fetched atomically)
229
236
  let resetAt = now + windowDuration;
230
237
  if (!allowed) {
231
- // Get the oldest entry's timestamp to calculate precise reset
232
- const oldest = await this.redis.zrange(key, 0, 0, "WITHSCORES");
238
+ const oldest = (results[2]?.[1] as string[]) || [];
233
239
  if (oldest.length >= 2) {
234
240
  const oldestTimestamp = parseInt(oldest[1], 10);
235
241
  resetAt = oldestTimestamp + windowDuration;
@@ -42,15 +42,15 @@ export type BeadDependency = z.infer<typeof BeadDependencySchema>;
42
42
  export const BeadSchema = z.object({
43
43
  id: z
44
44
  .string()
45
- .regex(/^[a-z0-9-]+-[a-z0-9]+(\.\d+)?$/, "Invalid bead ID format"),
45
+ .regex(/^[a-z0-9]+(-[a-z0-9]+)+(\.\d+)?$/, "Invalid bead ID format"),
46
46
  title: z.string().min(1, "Title required"),
47
47
  description: z.string().optional().default(""),
48
48
  status: BeadStatusSchema.default("open"),
49
49
  priority: z.number().int().min(0).max(3).default(2),
50
50
  issue_type: BeadTypeSchema.default("task"),
51
- created_at: z.string(), // ISO-8601
52
- updated_at: z.string().optional(),
53
- closed_at: z.string().optional(),
51
+ created_at: z.string().datetime({ offset: true }), // ISO-8601 with timezone offset
52
+ updated_at: z.string().datetime({ offset: true }).optional(),
53
+ closed_at: z.string().datetime({ offset: true }).optional(),
54
54
  parent_id: z.string().optional(),
55
55
  dependencies: z.array(BeadDependencySchema).optional().default([]),
56
56
  metadata: z.record(z.string(), z.unknown()).optional(),
@@ -53,7 +53,7 @@ export const EvaluationSchema = z.object({
53
53
  criteria: z.record(z.string(), CriterionEvaluationSchema),
54
54
  overall_feedback: z.string(),
55
55
  retry_suggestion: z.string().nullable(),
56
- timestamp: z.string().optional(), // ISO-8601
56
+ timestamp: z.string().datetime({ offset: true }).optional(), // ISO-8601 with timezone
57
57
  });
58
58
  export type Evaluation = z.infer<typeof EvaluationSchema>;
59
59
 
@@ -91,7 +91,7 @@ export const WeightedEvaluationSchema = z.object({
91
91
  criteria: z.record(z.string(), WeightedCriterionEvaluationSchema),
92
92
  overall_feedback: z.string(),
93
93
  retry_suggestion: z.string().nullable(),
94
- timestamp: z.string().optional(), // ISO-8601
94
+ timestamp: z.string().datetime({ offset: true }).optional(), // ISO-8601 with timezone
95
95
  /** Average weight across all criteria (indicates overall confidence) */
96
96
  average_weight: z.number().min(0).max(1).optional(),
97
97
  /** Raw score before weighting */
@@ -94,7 +94,7 @@ export const SwarmSpawnResultSchema = z.object({
94
94
  coordinator_name: z.string(), // Agent Mail name of coordinator
95
95
  thread_id: z.string(), // Agent Mail thread for this swarm
96
96
  agents: z.array(SpawnedAgentSchema),
97
- started_at: z.string(), // ISO-8601
97
+ started_at: z.string().datetime({ offset: true }), // ISO-8601 with timezone
98
98
  });
99
99
  export type SwarmSpawnResult = z.infer<typeof SwarmSpawnResultSchema>;
100
100
 
@@ -109,7 +109,7 @@ export const AgentProgressSchema = z.object({
109
109
  message: z.string().optional(),
110
110
  files_touched: z.array(z.string()).optional(),
111
111
  blockers: z.array(z.string()).optional(),
112
- timestamp: z.string(), // ISO-8601
112
+ timestamp: z.string().datetime({ offset: true }), // ISO-8601 with timezone
113
113
  });
114
114
  export type AgentProgress = z.infer<typeof AgentProgressSchema>;
115
115
 
@@ -124,6 +124,6 @@ export const SwarmStatusSchema = z.object({
124
124
  failed: z.number().int().min(0),
125
125
  blocked: z.number().int().min(0),
126
126
  agents: z.array(SpawnedAgentSchema),
127
- last_update: z.string(), // ISO-8601
127
+ last_update: z.string().datetime({ offset: true }), // ISO-8601 with timezone
128
128
  });
129
129
  export type SwarmStatus = z.infer<typeof SwarmStatusSchema>;
package/src/storage.ts CHANGED
@@ -73,20 +73,35 @@ async function resolveSemanticMemoryCommand(): Promise<string[]> {
73
73
  async function execSemanticMemory(
74
74
  args: string[],
75
75
  ): Promise<{ exitCode: number; stdout: Buffer; stderr: Buffer }> {
76
- const cmd = await resolveSemanticMemoryCommand();
77
- const fullCmd = [...cmd, ...args];
78
-
79
- // Use Bun.spawn for dynamic command arrays
80
- const proc = Bun.spawn(fullCmd, {
81
- stdout: "pipe",
82
- stderr: "pipe",
83
- });
76
+ try {
77
+ const cmd = await resolveSemanticMemoryCommand();
78
+ const fullCmd = [...cmd, ...args];
84
79
 
85
- const stdout = Buffer.from(await new Response(proc.stdout).arrayBuffer());
86
- const stderr = Buffer.from(await new Response(proc.stderr).arrayBuffer());
87
- const exitCode = await proc.exited;
80
+ // Use Bun.spawn for dynamic command arrays
81
+ const proc = Bun.spawn(fullCmd, {
82
+ stdout: "pipe",
83
+ stderr: "pipe",
84
+ });
88
85
 
89
- return { exitCode, stdout, stderr };
86
+ try {
87
+ const stdout = Buffer.from(await new Response(proc.stdout).arrayBuffer());
88
+ const stderr = Buffer.from(await new Response(proc.stderr).arrayBuffer());
89
+ const exitCode = await proc.exited;
90
+
91
+ return { exitCode, stdout, stderr };
92
+ } finally {
93
+ // Ensure process cleanup
94
+ proc.kill();
95
+ }
96
+ } catch (error) {
97
+ // Return structured error result on exceptions
98
+ const errorMessage = error instanceof Error ? error.message : String(error);
99
+ return {
100
+ exitCode: 1,
101
+ stdout: Buffer.from(""),
102
+ stderr: Buffer.from(`Error executing semantic-memory: ${errorMessage}`),
103
+ };
104
+ }
90
105
  }
91
106
 
92
107
  /**
@@ -646,17 +661,22 @@ export async function createStorageWithFallback(
646
661
  // ============================================================================
647
662
 
648
663
  let globalStorage: LearningStorage | null = null;
664
+ let globalStoragePromise: Promise<LearningStorage> | null = null;
649
665
 
650
666
  /**
651
667
  * Get or create the global storage instance
652
668
  *
653
669
  * Uses semantic-memory by default, with automatic fallback to in-memory.
670
+ * Prevents race conditions by storing the initialization promise.
654
671
  */
655
672
  export async function getStorage(): Promise<LearningStorage> {
656
- if (!globalStorage) {
657
- globalStorage = await createStorageWithFallback();
673
+ if (!globalStoragePromise) {
674
+ globalStoragePromise = createStorageWithFallback().then((storage) => {
675
+ globalStorage = storage;
676
+ return storage;
677
+ });
658
678
  }
659
- return globalStorage;
679
+ return globalStoragePromise;
660
680
  }
661
681
 
662
682
  /**
@@ -666,6 +686,7 @@ export async function getStorage(): Promise<LearningStorage> {
666
686
  */
667
687
  export function setStorage(storage: LearningStorage): void {
668
688
  globalStorage = storage;
689
+ globalStoragePromise = Promise.resolve(storage);
669
690
  }
670
691
 
671
692
  /**
@@ -676,4 +697,5 @@ export async function resetStorage(): Promise<void> {
676
697
  await globalStorage.close();
677
698
  globalStorage = null;
678
699
  }
700
+ globalStoragePromise = null;
679
701
  }
package/src/swarm.ts CHANGED
@@ -1343,6 +1343,19 @@ export const swarm_validate_decomposition = tool({
1343
1343
  for (let i = 0; i < validated.subtasks.length; i++) {
1344
1344
  const deps = validated.subtasks[i].dependencies;
1345
1345
  for (const dep of deps) {
1346
+ // Check bounds first
1347
+ if (dep < 0 || dep >= validated.subtasks.length) {
1348
+ return JSON.stringify(
1349
+ {
1350
+ valid: false,
1351
+ error: `Invalid dependency: subtask ${i} depends on ${dep}, but only ${validated.subtasks.length} subtasks exist (indices 0-${validated.subtasks.length - 1})`,
1352
+ hint: "Dependency index is out of bounds",
1353
+ },
1354
+ null,
1355
+ 2,
1356
+ );
1357
+ }
1358
+ // Check forward references
1346
1359
  if (dep >= i) {
1347
1360
  return JSON.stringify(
1348
1361
  {
@@ -1,138 +0,0 @@
1
- ---
2
- name: swarm-planner
3
- description: Strategic task decomposition for swarm coordination
4
- model: claude-sonnet-4-5
5
- ---
6
-
7
- You are a swarm planner. Your job is to decompose complex tasks into optimal parallel subtasks.
8
-
9
- ## Your Role
10
-
11
- You analyze tasks and create decomposition plans that:
12
-
13
- - Maximize parallelization (agents work independently)
14
- - Minimize conflicts (no file overlap between subtasks)
15
- - Follow the best strategy for the task type
16
-
17
- ## Workflow
18
-
19
- 1. **Analyze** - Call `swarm_select_strategy` to understand the task
20
- 2. **Plan** - Call `swarm_plan_prompt` to get strategy-specific guidance
21
- 3. **Decompose** - Create a BeadTree following the guidelines
22
- 4. **Validate** - Ensure no file conflicts or circular dependencies
23
-
24
- ## Strategy Selection
25
-
26
- The plugin auto-selects strategies based on task keywords:
27
-
28
- | Strategy | Best For | Keywords |
29
- | ----------------- | -------------------------------------------- | -------------------------------------- |
30
- | **file-based** | Refactoring, migrations, pattern changes | refactor, migrate, rename, update all |
31
- | **feature-based** | New features, adding functionality | add, implement, build, create, feature |
32
- | **risk-based** | Bug fixes, security issues, critical changes | fix, bug, security, critical, urgent |
33
-
34
- You can override with explicit strategy if the auto-detection is wrong.
35
-
36
- ## Output Format
37
-
38
- Return ONLY valid JSON matching the BeadTree schema:
39
-
40
- ```json
41
- {
42
- "epic": {
43
- "title": "Epic title for beads tracker",
44
- "description": "Brief description of the overall goal"
45
- },
46
- "subtasks": [
47
- {
48
- "title": "What this subtask accomplishes",
49
- "description": "Detailed instructions for the agent",
50
- "files": ["src/path/to/file.ts", "src/path/to/file.test.ts"],
51
- "dependencies": [],
52
- "estimated_complexity": 2
53
- }
54
- ]
55
- }
56
- ```
57
-
58
- **CRITICAL**: Return ONLY the JSON. No markdown, no explanation, no code blocks.
59
-
60
- ## Decomposition Rules
61
-
62
- 1. **2-7 subtasks** - Too few = not parallel, too many = coordination overhead
63
- 2. **No file overlap** - Each file appears in exactly one subtask
64
- 3. **Include tests** - Put test files with the code they test
65
- 4. **Order by dependency** - If B needs A's output, A comes first (lower index)
66
- 5. **Estimate complexity** - 1 (trivial) to 5 (complex)
67
-
68
- ## Anti-Patterns to Avoid
69
-
70
- - Don't split tightly coupled files across subtasks
71
- - Don't create subtasks that can't be tested independently
72
- - Don't forget shared types/utilities that multiple files depend on
73
- - Don't make one subtask do everything while others are trivial
74
-
75
- ## Example Decomposition
76
-
77
- **Task**: "Add user authentication with OAuth"
78
-
79
- **Strategy**: feature-based (detected from "add" keyword)
80
-
81
- **Result**:
82
-
83
- ```json
84
- {
85
- "epic": {
86
- "title": "Add user authentication with OAuth",
87
- "description": "Implement OAuth-based authentication flow with session management"
88
- },
89
- "subtasks": [
90
- {
91
- "title": "Set up OAuth provider configuration",
92
- "description": "Configure OAuth provider (Google/GitHub), add environment variables, create auth config",
93
- "files": ["src/auth/config.ts", "src/auth/providers.ts", ".env.example"],
94
- "dependencies": [],
95
- "estimated_complexity": 2
96
- },
97
- {
98
- "title": "Implement session management",
99
- "description": "Create session store, JWT handling, cookie management",
100
- "files": [
101
- "src/auth/session.ts",
102
- "src/auth/jwt.ts",
103
- "src/middleware/auth.ts"
104
- ],
105
- "dependencies": [0],
106
- "estimated_complexity": 3
107
- },
108
- {
109
- "title": "Add protected route wrapper",
110
- "description": "Create HOC/middleware for protecting routes, redirect logic",
111
- "files": ["src/components/ProtectedRoute.tsx", "src/hooks/useAuth.ts"],
112
- "dependencies": [1],
113
- "estimated_complexity": 2
114
- },
115
- {
116
- "title": "Create login/logout UI",
117
- "description": "Login page, logout button, auth state display",
118
- "files": ["src/app/login/page.tsx", "src/components/AuthButton.tsx"],
119
- "dependencies": [0],
120
- "estimated_complexity": 2
121
- }
122
- ]
123
- }
124
- ```
125
-
126
- ## Usage
127
-
128
- The coordinator invokes you like this:
129
-
130
- ```
131
- @swarm-planner "Add user authentication with OAuth"
132
- ```
133
-
134
- You respond with the BeadTree JSON. The coordinator then:
135
-
136
- 1. Validates with `swarm_validate_decomposition`
137
- 2. Creates beads with `beads_create_epic`
138
- 3. Spawns worker agents for each subtask