opencode-swarm-plugin 0.1.0 → 0.2.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,389 @@
1
+ /**
2
+ * Tool Availability Module
3
+ *
4
+ * Checks for external tool availability and provides graceful degradation.
5
+ * Tools are checked once and cached for the session.
6
+ *
7
+ * Supported tools:
8
+ * - semantic-memory: Learning persistence with semantic search
9
+ * - cass: Cross-agent session search for historical context
10
+ * - ubs: Universal bug scanner for pre-commit checks
11
+ * - beads (bd): Git-backed issue tracking
12
+ * - agent-mail: Multi-agent coordination server
13
+ */
14
+
15
+ export type ToolName =
16
+ | "semantic-memory"
17
+ | "cass"
18
+ | "ubs"
19
+ | "beads"
20
+ | "agent-mail";
21
+
22
+ export interface ToolStatus {
23
+ available: boolean;
24
+ checkedAt: string;
25
+ error?: string;
26
+ version?: string;
27
+ }
28
+
29
+ export interface ToolAvailability {
30
+ tool: ToolName;
31
+ status: ToolStatus;
32
+ fallbackBehavior: string;
33
+ }
34
+
35
+ // Cached tool status
36
+ const toolCache = new Map<ToolName, ToolStatus>();
37
+
38
+ // Warnings already logged (to avoid spam)
39
+ const warningsLogged = new Set<ToolName>();
40
+
41
+ /**
42
+ * Check if a command exists and is executable
43
+ */
44
+ async function commandExists(cmd: string): Promise<boolean> {
45
+ try {
46
+ const result = await Bun.$`which ${cmd}`.quiet().nothrow();
47
+ return result.exitCode === 0;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Check if a URL is reachable
55
+ */
56
+ async function urlReachable(
57
+ url: string,
58
+ timeoutMs: number = 1000,
59
+ ): Promise<boolean> {
60
+ try {
61
+ const controller = new AbortController();
62
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
63
+
64
+ const response = await fetch(url, {
65
+ method: "HEAD",
66
+ signal: controller.signal,
67
+ });
68
+
69
+ clearTimeout(timeout);
70
+ return response.ok;
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Tool-specific availability checks
78
+ */
79
+ const toolCheckers: Record<ToolName, () => Promise<ToolStatus>> = {
80
+ "semantic-memory": async () => {
81
+ // Check native first, then bunx
82
+ const nativeExists = await commandExists("semantic-memory");
83
+ if (nativeExists) {
84
+ try {
85
+ const result = await Bun.$`semantic-memory stats`.quiet().nothrow();
86
+ return {
87
+ available: result.exitCode === 0,
88
+ checkedAt: new Date().toISOString(),
89
+ version: "native",
90
+ };
91
+ } catch (e) {
92
+ return {
93
+ available: false,
94
+ checkedAt: new Date().toISOString(),
95
+ error: String(e),
96
+ };
97
+ }
98
+ }
99
+
100
+ // Try bunx with manual timeout
101
+ try {
102
+ const proc = Bun.spawn(["bunx", "semantic-memory", "stats"], {
103
+ stdout: "pipe",
104
+ stderr: "pipe",
105
+ });
106
+
107
+ const timeout = setTimeout(() => proc.kill(), 10000);
108
+ const exitCode = await proc.exited;
109
+ clearTimeout(timeout);
110
+
111
+ return {
112
+ available: exitCode === 0,
113
+ checkedAt: new Date().toISOString(),
114
+ version: "bunx",
115
+ };
116
+ } catch (e) {
117
+ return {
118
+ available: false,
119
+ checkedAt: new Date().toISOString(),
120
+ error: String(e),
121
+ };
122
+ }
123
+ },
124
+
125
+ cass: async () => {
126
+ const exists = await commandExists("cass");
127
+ if (!exists) {
128
+ return {
129
+ available: false,
130
+ checkedAt: new Date().toISOString(),
131
+ error: "cass command not found",
132
+ };
133
+ }
134
+
135
+ try {
136
+ const result = await Bun.$`cass health`.quiet().nothrow();
137
+ return {
138
+ available: result.exitCode === 0,
139
+ checkedAt: new Date().toISOString(),
140
+ };
141
+ } catch (e) {
142
+ return {
143
+ available: false,
144
+ checkedAt: new Date().toISOString(),
145
+ error: String(e),
146
+ };
147
+ }
148
+ },
149
+
150
+ ubs: async () => {
151
+ const exists = await commandExists("ubs");
152
+ if (!exists) {
153
+ return {
154
+ available: false,
155
+ checkedAt: new Date().toISOString(),
156
+ error: "ubs command not found",
157
+ };
158
+ }
159
+
160
+ try {
161
+ const result = await Bun.$`ubs doctor`.quiet().nothrow();
162
+ return {
163
+ available: result.exitCode === 0,
164
+ checkedAt: new Date().toISOString(),
165
+ };
166
+ } catch (e) {
167
+ return {
168
+ available: false,
169
+ checkedAt: new Date().toISOString(),
170
+ error: String(e),
171
+ };
172
+ }
173
+ },
174
+
175
+ beads: async () => {
176
+ const exists = await commandExists("bd");
177
+ if (!exists) {
178
+ return {
179
+ available: false,
180
+ checkedAt: new Date().toISOString(),
181
+ error: "bd command not found",
182
+ };
183
+ }
184
+
185
+ try {
186
+ // Just check if bd can run - don't require a repo
187
+ const result = await Bun.$`bd --version`.quiet().nothrow();
188
+ return {
189
+ available: result.exitCode === 0,
190
+ checkedAt: new Date().toISOString(),
191
+ };
192
+ } catch (e) {
193
+ return {
194
+ available: false,
195
+ checkedAt: new Date().toISOString(),
196
+ error: String(e),
197
+ };
198
+ }
199
+ },
200
+
201
+ "agent-mail": async () => {
202
+ const reachable = await urlReachable(
203
+ "http://127.0.0.1:8765/health/liveness",
204
+ );
205
+ return {
206
+ available: reachable,
207
+ checkedAt: new Date().toISOString(),
208
+ error: reachable ? undefined : "Agent Mail server not reachable at :8765",
209
+ };
210
+ },
211
+ };
212
+
213
+ /**
214
+ * Fallback behavior descriptions for each tool
215
+ */
216
+ const fallbackBehaviors: Record<ToolName, string> = {
217
+ "semantic-memory":
218
+ "Learning data stored in-memory only (lost on session end)",
219
+ cass: "Decomposition proceeds without historical context from past sessions",
220
+ ubs: "Subtask completion skips bug scanning - manual review recommended",
221
+ beads: "Swarm cannot track issues - task coordination will be less reliable",
222
+ "agent-mail":
223
+ "Multi-agent coordination disabled - file conflicts possible if multiple agents active",
224
+ };
225
+
226
+ /**
227
+ * Check if a tool is available (cached)
228
+ *
229
+ * @param tool - Tool name to check
230
+ * @returns Tool status
231
+ */
232
+ export async function checkTool(tool: ToolName): Promise<ToolStatus> {
233
+ const cached = toolCache.get(tool);
234
+ if (cached) {
235
+ return cached;
236
+ }
237
+
238
+ const checker = toolCheckers[tool];
239
+ const status = await checker();
240
+ toolCache.set(tool, status);
241
+
242
+ return status;
243
+ }
244
+
245
+ /**
246
+ * Check if a tool is available (simple boolean, cached)
247
+ */
248
+ export async function isToolAvailable(tool: ToolName): Promise<boolean> {
249
+ const status = await checkTool(tool);
250
+ return status.available;
251
+ }
252
+
253
+ /**
254
+ * Get full availability info including fallback behavior
255
+ */
256
+ export async function getToolAvailability(
257
+ tool: ToolName,
258
+ ): Promise<ToolAvailability> {
259
+ const status = await checkTool(tool);
260
+ return {
261
+ tool,
262
+ status,
263
+ fallbackBehavior: fallbackBehaviors[tool],
264
+ };
265
+ }
266
+
267
+ /**
268
+ * Check all tools and return availability map
269
+ */
270
+ export async function checkAllTools(): Promise<
271
+ Map<ToolName, ToolAvailability>
272
+ > {
273
+ const tools: ToolName[] = [
274
+ "semantic-memory",
275
+ "cass",
276
+ "ubs",
277
+ "beads",
278
+ "agent-mail",
279
+ ];
280
+
281
+ const results = new Map<ToolName, ToolAvailability>();
282
+
283
+ // Check all in parallel
284
+ const checks = await Promise.all(
285
+ tools.map(async (tool) => ({
286
+ tool,
287
+ availability: await getToolAvailability(tool),
288
+ })),
289
+ );
290
+
291
+ for (const { tool, availability } of checks) {
292
+ results.set(tool, availability);
293
+ }
294
+
295
+ return results;
296
+ }
297
+
298
+ /**
299
+ * Log a warning about a missing tool (once per tool per session)
300
+ */
301
+ export function warnMissingTool(tool: ToolName): void {
302
+ if (warningsLogged.has(tool)) {
303
+ return;
304
+ }
305
+
306
+ warningsLogged.add(tool);
307
+ const fallback = fallbackBehaviors[tool];
308
+ console.warn(`[swarm] ${tool} not available: ${fallback}`);
309
+ }
310
+
311
+ /**
312
+ * Require a tool - throws if not available
313
+ *
314
+ * Use this for tools that are mandatory for a feature.
315
+ */
316
+ export async function requireTool(tool: ToolName): Promise<void> {
317
+ const status = await checkTool(tool);
318
+ if (!status.available) {
319
+ throw new Error(
320
+ `Required tool '${tool}' is not available: ${status.error || "unknown error"}`,
321
+ );
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Execute with fallback - runs the action if tool available, otherwise runs fallback
327
+ *
328
+ * @param tool - Tool to check
329
+ * @param action - Action to run if tool available
330
+ * @param fallback - Fallback to run if tool not available
331
+ * @returns Result from action or fallback
332
+ */
333
+ export async function withToolFallback<T>(
334
+ tool: ToolName,
335
+ action: () => Promise<T>,
336
+ fallback: () => T | Promise<T>,
337
+ ): Promise<T> {
338
+ const available = await isToolAvailable(tool);
339
+
340
+ if (available) {
341
+ return action();
342
+ }
343
+
344
+ warnMissingTool(tool);
345
+ return fallback();
346
+ }
347
+
348
+ /**
349
+ * Execute if tool available, otherwise return undefined
350
+ */
351
+ export async function ifToolAvailable<T>(
352
+ tool: ToolName,
353
+ action: () => Promise<T>,
354
+ ): Promise<T | undefined> {
355
+ const available = await isToolAvailable(tool);
356
+
357
+ if (available) {
358
+ return action();
359
+ }
360
+
361
+ warnMissingTool(tool);
362
+ return undefined;
363
+ }
364
+
365
+ /**
366
+ * Reset tool cache (for testing)
367
+ */
368
+ export function resetToolCache(): void {
369
+ toolCache.clear();
370
+ warningsLogged.clear();
371
+ }
372
+
373
+ /**
374
+ * Format tool availability for display
375
+ */
376
+ export function formatToolAvailability(
377
+ availability: Map<ToolName, ToolAvailability>,
378
+ ): string {
379
+ const lines: string[] = ["Tool Availability:"];
380
+
381
+ for (const [tool, info] of availability) {
382
+ const status = info.status.available ? "✓" : "✗";
383
+ const version = info.status.version ? ` (${info.status.version})` : "";
384
+ const fallback = info.status.available ? "" : ` → ${info.fallbackBehavior}`;
385
+ lines.push(` ${status} ${tool}${version}${fallback}`);
386
+ }
387
+
388
+ return lines.join("\n");
389
+ }