opencode-swarm-plugin 0.19.0 → 0.21.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,381 @@
1
+ /**
2
+ * Output Guardrails for MCP Tool Response Truncation
3
+ *
4
+ * Prevents MCP tools from blowing out context with massive responses.
5
+ * Provides smart truncation that preserves JSON, code blocks, and markdown structure.
6
+ *
7
+ * @module output-guardrails
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { guardrailOutput, DEFAULT_GUARDRAIL_CONFIG } from "./output-guardrails"
12
+ *
13
+ * const result = guardrailOutput("context7_get-library-docs", hugeOutput)
14
+ * if (result.truncated) {
15
+ * console.log(`Truncated ${result.originalLength - result.truncatedLength} chars`)
16
+ * }
17
+ * ```
18
+ */
19
+
20
+ /**
21
+ * Guardrail configuration for tool output limits
22
+ *
23
+ * Controls per-tool character limits and skip rules.
24
+ */
25
+ export interface GuardrailConfig {
26
+ /**
27
+ * Default max characters for tool output
28
+ * Default: 32000 chars (~8000 tokens at 4 chars/token)
29
+ */
30
+ defaultMaxChars: number;
31
+
32
+ /**
33
+ * Per-tool character limit overrides
34
+ *
35
+ * Higher limits for code/doc tools that commonly return large outputs.
36
+ */
37
+ toolLimits: Record<string, number>;
38
+
39
+ /**
40
+ * Tools that should never be truncated
41
+ *
42
+ * Internal coordination tools (beads_*, swarmmail_*, structured_*)
43
+ * should always return complete output.
44
+ */
45
+ skipTools: string[];
46
+ }
47
+
48
+ /**
49
+ * Result of guardrail output processing
50
+ */
51
+ export interface GuardrailResult {
52
+ /** Processed output (truncated if needed) */
53
+ output: string;
54
+
55
+ /** Whether truncation occurred */
56
+ truncated: boolean;
57
+
58
+ /** Original output length in characters */
59
+ originalLength: number;
60
+
61
+ /** Final output length in characters */
62
+ truncatedLength: number;
63
+ }
64
+
65
+ /**
66
+ * Metrics for guardrail analytics
67
+ *
68
+ * Used to track truncation patterns and adjust limits.
69
+ */
70
+ export interface GuardrailMetrics {
71
+ /** Tool that produced the output */
72
+ toolName: string;
73
+
74
+ /** Original output length */
75
+ originalLength: number;
76
+
77
+ /** Truncated output length */
78
+ truncatedLength: number;
79
+
80
+ /** Timestamp of truncation */
81
+ timestamp: number;
82
+ }
83
+
84
+ /**
85
+ * Default guardrail configuration
86
+ *
87
+ * - defaultMaxChars: 32000 (~8000 tokens)
88
+ * - Higher limits for code/doc tools (64000)
89
+ * - Skip internal coordination tools
90
+ */
91
+ export const DEFAULT_GUARDRAIL_CONFIG: GuardrailConfig = {
92
+ defaultMaxChars: 32000,
93
+
94
+ toolLimits: {
95
+ // Higher limits for code/doc tools that commonly return large outputs
96
+ "repo-autopsy_file": 64000,
97
+ "repo-autopsy_search": 64000,
98
+ "repo-autopsy_exports_map": 64000,
99
+ "context7_get-library-docs": 64000,
100
+ cass_view: 64000,
101
+ cass_search: 48000,
102
+ skills_read: 48000,
103
+
104
+ // Lower limits for list/stats tools
105
+ "repo-autopsy_structure": 24000,
106
+ "repo-autopsy_stats": 16000,
107
+ cass_stats: 8000,
108
+ },
109
+
110
+ skipTools: [
111
+ // Beads tools - always return full output
112
+ "beads_create",
113
+ "beads_create_epic",
114
+ "beads_query",
115
+ "beads_update",
116
+ "beads_close",
117
+ "beads_start",
118
+ "beads_ready",
119
+ "beads_sync",
120
+
121
+ // Agent Mail tools - always return full output
122
+ "agentmail_init",
123
+ "agentmail_send",
124
+ "agentmail_inbox",
125
+ "agentmail_read_message",
126
+ "agentmail_summarize_thread",
127
+ "agentmail_reserve",
128
+ "agentmail_release",
129
+ "agentmail_ack",
130
+
131
+ // Swarm Mail tools - always return full output
132
+ "swarmmail_init",
133
+ "swarmmail_send",
134
+ "swarmmail_inbox",
135
+ "swarmmail_read_message",
136
+ "swarmmail_reserve",
137
+ "swarmmail_release",
138
+ "swarmmail_ack",
139
+
140
+ // Structured output tools - always return full output
141
+ "structured_extract_json",
142
+ "structured_validate",
143
+ "structured_parse_evaluation",
144
+ "structured_parse_decomposition",
145
+ "structured_parse_bead_tree",
146
+
147
+ // Swarm orchestration tools - always return full output
148
+ "swarm_select_strategy",
149
+ "swarm_plan_prompt",
150
+ "swarm_decompose",
151
+ "swarm_validate_decomposition",
152
+ "swarm_status",
153
+ "swarm_progress",
154
+ "swarm_complete",
155
+ "swarm_record_outcome",
156
+ "swarm_subtask_prompt",
157
+ "swarm_spawn_subtask",
158
+ "swarm_complete_subtask",
159
+ "swarm_evaluation_prompt",
160
+
161
+ // Mandate tools - always return full output
162
+ "mandate_file",
163
+ "mandate_vote",
164
+ "mandate_query",
165
+ "mandate_list",
166
+ "mandate_stats",
167
+ ],
168
+ };
169
+
170
+ /**
171
+ * Find matching closing brace for JSON truncation
172
+ *
173
+ * Walks forward from startIdx to find the matching closing brace,
174
+ * respecting nested braces and brackets.
175
+ *
176
+ * @param text - Text to search
177
+ * @param startIdx - Index of opening brace
178
+ * @returns Index of matching closing brace, or -1 if not found
179
+ */
180
+ function findMatchingBrace(text: string, startIdx: number): number {
181
+ const openChar = text[startIdx];
182
+ const closeChar = openChar === "{" ? "}" : "]";
183
+ let depth = 1;
184
+
185
+ for (let i = startIdx + 1; i < text.length; i++) {
186
+ if (text[i] === openChar) {
187
+ depth++;
188
+ } else if (text[i] === closeChar) {
189
+ depth--;
190
+ if (depth === 0) {
191
+ return i;
192
+ }
193
+ }
194
+ }
195
+
196
+ return -1;
197
+ }
198
+
199
+ /**
200
+ * Smart truncation preserving structure boundaries
201
+ *
202
+ * Truncates text while preserving:
203
+ * - JSON structure (finds matching braces, doesn't cut mid-object)
204
+ * - Code blocks (preserves ``` boundaries)
205
+ * - Markdown headers (cuts at ## boundaries when possible)
206
+ *
207
+ * @param text - Text to truncate
208
+ * @param maxChars - Maximum character count
209
+ * @returns Truncated text with "[TRUNCATED - X chars removed]" suffix
210
+ */
211
+ export function truncateWithBoundaries(text: string, maxChars: number): string {
212
+ if (text.length <= maxChars) {
213
+ return text;
214
+ }
215
+
216
+ // Try to find a good truncation point
217
+ let truncateAt = maxChars;
218
+
219
+ // Check if we're in the middle of a JSON structure
220
+ const beforeTruncate = text.slice(0, maxChars);
221
+ const lastOpenBrace = Math.max(
222
+ beforeTruncate.lastIndexOf("{"),
223
+ beforeTruncate.lastIndexOf("["),
224
+ );
225
+ const lastCloseBrace = Math.max(
226
+ beforeTruncate.lastIndexOf("}"),
227
+ beforeTruncate.lastIndexOf("]"),
228
+ );
229
+
230
+ // If we have an unclosed brace/bracket, try to find the matching close
231
+ if (lastOpenBrace > lastCloseBrace) {
232
+ const matchingClose = findMatchingBrace(text, lastOpenBrace);
233
+ if (matchingClose !== -1 && matchingClose < maxChars * 1.2) {
234
+ // If the matching close is within 20% of maxChars, include it
235
+ truncateAt = matchingClose + 1;
236
+ } else {
237
+ // Otherwise, truncate before the unclosed brace
238
+ truncateAt = lastOpenBrace;
239
+ }
240
+ }
241
+
242
+ // Check for code block boundaries (```)
243
+ const codeBlockMarker = "```";
244
+ const beforeTruncateForCode = text.slice(0, truncateAt);
245
+ const codeBlockCount = (beforeTruncateForCode.match(/```/g) || []).length;
246
+
247
+ // If we have an odd number of ``` markers, we're inside a code block
248
+ if (codeBlockCount % 2 === 1) {
249
+ // Try to find the closing ```
250
+ const closeMarkerIdx = text.indexOf(codeBlockMarker, truncateAt);
251
+ if (closeMarkerIdx !== -1 && closeMarkerIdx < maxChars * 1.2) {
252
+ // If close marker is within 20% of maxChars, include it
253
+ truncateAt = closeMarkerIdx + codeBlockMarker.length;
254
+ } else {
255
+ // Otherwise, truncate before the opening ```
256
+ const lastOpenMarker = beforeTruncateForCode.lastIndexOf(codeBlockMarker);
257
+ if (lastOpenMarker !== -1) {
258
+ truncateAt = lastOpenMarker;
259
+ }
260
+ }
261
+ }
262
+
263
+ // Try to find a markdown header boundary (## or ###)
264
+ const headerMatch = text.slice(0, truncateAt).match(/\n#{1,6}\s/g);
265
+ if (headerMatch && headerMatch.length > 0) {
266
+ const lastHeaderIdx = beforeTruncateForCode.lastIndexOf("\n##");
267
+ if (lastHeaderIdx !== -1 && lastHeaderIdx > maxChars * 0.8) {
268
+ // If we have a header within 80% of maxChars, truncate there
269
+ truncateAt = lastHeaderIdx;
270
+ }
271
+ }
272
+
273
+ // Ensure we don't truncate in the middle of a word
274
+ // Walk back to the last whitespace
275
+ while (truncateAt > 0 && !/\s/.test(text[truncateAt])) {
276
+ truncateAt--;
277
+ }
278
+
279
+ const truncated = text.slice(0, truncateAt).trimEnd();
280
+ const charsRemoved = text.length - truncated.length;
281
+
282
+ return `${truncated}\n\n[TRUNCATED - ${charsRemoved.toLocaleString()} chars removed]`;
283
+ }
284
+
285
+ /**
286
+ * Get the character limit for a specific tool
287
+ *
288
+ * @param toolName - Name of the tool
289
+ * @param config - Guardrail configuration
290
+ * @returns Character limit for the tool
291
+ */
292
+ function getToolLimit(
293
+ toolName: string,
294
+ config: GuardrailConfig = DEFAULT_GUARDRAIL_CONFIG,
295
+ ): number {
296
+ return config.toolLimits[toolName] ?? config.defaultMaxChars;
297
+ }
298
+
299
+ /**
300
+ * Apply guardrails to tool output
301
+ *
302
+ * Main entry point for guardrail processing:
303
+ * 1. Check if tool is in skipTools → return unchanged
304
+ * 2. Check if output.length > getToolLimit(toolName) → truncate
305
+ * 3. Return { output, truncated, originalLength, truncatedLength }
306
+ *
307
+ * @param toolName - Name of the tool that produced the output
308
+ * @param output - Tool output to process
309
+ * @param config - Optional guardrail configuration (defaults to DEFAULT_GUARDRAIL_CONFIG)
310
+ * @returns Guardrail result with truncated output and metadata
311
+ *
312
+ * @example
313
+ * ```typescript
314
+ * const result = guardrailOutput("context7_get-library-docs", hugeOutput)
315
+ * console.log(result.output) // Truncated or original
316
+ * console.log(result.truncated) // true if truncated
317
+ * console.log(`${result.originalLength} → ${result.truncatedLength} chars`)
318
+ * ```
319
+ */
320
+ export function guardrailOutput(
321
+ toolName: string,
322
+ output: string,
323
+ config: GuardrailConfig = DEFAULT_GUARDRAIL_CONFIG,
324
+ ): GuardrailResult {
325
+ const originalLength = output.length;
326
+
327
+ // Check if tool should be skipped
328
+ if (config.skipTools.includes(toolName)) {
329
+ return {
330
+ output,
331
+ truncated: false,
332
+ originalLength,
333
+ truncatedLength: originalLength,
334
+ };
335
+ }
336
+
337
+ // Get the limit for this tool
338
+ const limit = getToolLimit(toolName, config);
339
+
340
+ // Check if truncation is needed
341
+ if (originalLength <= limit) {
342
+ return {
343
+ output,
344
+ truncated: false,
345
+ originalLength,
346
+ truncatedLength: originalLength,
347
+ };
348
+ }
349
+
350
+ // Truncate with smart boundaries
351
+ const truncatedOutput = truncateWithBoundaries(output, limit);
352
+ const truncatedLength = truncatedOutput.length;
353
+
354
+ return {
355
+ output: truncatedOutput,
356
+ truncated: true,
357
+ originalLength,
358
+ truncatedLength,
359
+ };
360
+ }
361
+
362
+ /**
363
+ * Create a guardrail metrics entry
364
+ *
365
+ * Used for analytics and learning about truncation patterns.
366
+ *
367
+ * @param result - Guardrail result from guardrailOutput
368
+ * @param toolName - Name of the tool
369
+ * @returns Metrics entry
370
+ */
371
+ export function createMetrics(
372
+ result: GuardrailResult,
373
+ toolName: string,
374
+ ): GuardrailMetrics {
375
+ return {
376
+ toolName,
377
+ originalLength: result.originalLength,
378
+ truncatedLength: result.truncatedLength,
379
+ timestamp: Date.now(),
380
+ };
381
+ }