claude-flow 3.10.4 → 3.10.5

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 (58) hide show
  1. package/package.json +1 -1
  2. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent-planning.smoke.d.ts +18 -0
  3. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent-planning.smoke.js +253 -0
  4. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent.d.ts +198 -0
  5. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent.js +651 -0
  6. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.d.ts +133 -0
  7. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.js +281 -0
  8. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.smoke.d.ts +22 -0
  9. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.smoke.js +300 -0
  10. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.d.ts +138 -0
  11. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.js +260 -0
  12. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.smoke.d.ts +19 -0
  13. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.smoke.js +246 -0
  14. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.d.ts +123 -0
  15. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.js +312 -0
  16. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.smoke.d.ts +21 -0
  17. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.smoke.js +327 -0
  18. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.d.ts +125 -0
  19. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.js +350 -0
  20. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.smoke.d.ts +21 -0
  21. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.smoke.js +228 -0
  22. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-e2e-smoke.d.ts +27 -0
  23. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-e2e-smoke.js +136 -0
  24. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-extract.smoke.d.ts +45 -0
  25. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-extract.smoke.js +242 -0
  26. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/features.d.ts +46 -0
  27. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/features.js +170 -0
  28. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.d.ts +105 -0
  29. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.js +260 -0
  30. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.smoke.d.ts +20 -0
  31. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.smoke.js +235 -0
  32. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/train-data-loader.d.ts +51 -0
  33. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/train-data-loader.js +179 -0
  34. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-judge.d.ts +88 -0
  35. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-judge.js +437 -0
  36. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-loader.d.ts +87 -0
  37. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-loader.js +326 -0
  38. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/file_read.d.ts +35 -0
  39. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/file_read.js +403 -0
  40. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/grounded_query.d.ts +126 -0
  41. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/grounded_query.js +225 -0
  42. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/index.d.ts +32 -0
  43. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/index.js +36 -0
  44. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/types.d.ts +62 -0
  45. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/types.js +12 -0
  46. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/web_search.d.ts +30 -0
  47. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/web_search.js +210 -0
  48. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.d.ts +88 -0
  49. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.js +297 -0
  50. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.smoke.d.ts +20 -0
  51. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.smoke.js +332 -0
  52. package/v3/@claude-flow/cli/dist/src/commands/gaia-bench.d.ts +40 -0
  53. package/v3/@claude-flow/cli/dist/src/commands/gaia-bench.js +597 -0
  54. package/v3/@claude-flow/cli/dist/src/commands/index.js +2 -0
  55. package/v3/@claude-flow/cli/dist/src/commands/init.js +41 -4
  56. package/v3/@claude-flow/cli/dist/src/init/executor.js +25 -6
  57. package/v3/@claude-flow/cli/dist/src/init/mcp-generator.js +9 -4
  58. package/v3/@claude-flow/cli/package.json +1 -1
@@ -0,0 +1,403 @@
1
+ /**
2
+ * GAIA Tool: file_read — ADR-133-PR2 / iter-53b attachment-tools
3
+ *
4
+ * Reads a file from the local filesystem and returns its contents as a
5
+ * UTF-8 string. Performs content-type dispatch based on extension +
6
+ * magic bytes:
7
+ *
8
+ * Supported extraction formats (iter-53b):
9
+ * - Plain text, JSON, CSV, XML, HTML, Markdown, JS/TS, Python, shell, YAML
10
+ * - XLSX — openpyxl subprocess (cell values + fill colours)
11
+ * - PPTX — python-pptx subprocess (per-slide text)
12
+ * - PNG / JPEG / GIF / WebP — returns IMAGE_BASE64 marker for vision API
13
+ * - MP3 / WAV — OpenAI Whisper (tiny model) subprocess transcript
14
+ * - .py source file — returned as UTF-8 text (no execution)
15
+ *
16
+ * For PDF / DOCX / other binary: descriptive stub (PR-4 deferred).
17
+ *
18
+ * IMAGE_BASE64 marker format:
19
+ * [IMAGE_BASE64:{"mediaType":"image/png","base64":"...","path":"/abs/path"}]
20
+ *
21
+ * The agent loop in gaia-agent.ts must parse this marker when it appears
22
+ * in a tool_result and convert it to an Anthropic vision content block.
23
+ *
24
+ * Maximum file size: 5 MB. Paths must be absolute.
25
+ *
26
+ * Refs: ADR-133, #2156, iter-53b
27
+ */
28
+ import * as fs from 'node:fs';
29
+ import * as path from 'node:path';
30
+ import { execFileSync } from 'node:child_process';
31
+ // ---------------------------------------------------------------------------
32
+ // Constants
33
+ // ---------------------------------------------------------------------------
34
+ const MAX_FILE_BYTES = 5 * 1024 * 1024; // 5 MB
35
+ // ---------------------------------------------------------------------------
36
+ // Content-type detection
37
+ // ---------------------------------------------------------------------------
38
+ const EXT_TO_TYPE = {
39
+ '.txt': 'text/plain',
40
+ '.md': 'text/markdown',
41
+ '.json': 'application/json',
42
+ '.csv': 'text/csv',
43
+ '.xml': 'application/xml',
44
+ '.html': 'text/html',
45
+ '.htm': 'text/html',
46
+ '.yaml': 'application/yaml',
47
+ '.yml': 'application/yaml',
48
+ '.js': 'application/javascript',
49
+ '.ts': 'application/typescript',
50
+ '.py': 'text/x-python',
51
+ '.sh': 'application/x-sh',
52
+ '.bash': 'application/x-sh',
53
+ '.zsh': 'application/x-sh',
54
+ // Handled binary (extraction implemented)
55
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
56
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
57
+ '.png': 'image/png',
58
+ '.jpg': 'image/jpeg',
59
+ '.jpeg': 'image/jpeg',
60
+ '.gif': 'image/gif',
61
+ '.webp': 'image/webp',
62
+ '.mp3': 'audio/mpeg',
63
+ '.wav': 'audio/wav',
64
+ // Stub binary (deferred)
65
+ '.pdf': 'application/pdf',
66
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
67
+ '.mp4': 'video/mp4',
68
+ };
69
+ /** Binary types for which we have extraction logic in iter-53b. */
70
+ const HANDLED_BINARY_TYPES = new Set([
71
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
72
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
73
+ 'image/png',
74
+ 'image/jpeg',
75
+ 'image/gif',
76
+ 'image/webp',
77
+ 'audio/mpeg',
78
+ 'audio/wav',
79
+ ]);
80
+ /** Binary types for which we return a stub (no extraction yet). */
81
+ const STUB_BINARY_TYPES = new Set([
82
+ 'application/pdf',
83
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
84
+ 'video/mp4',
85
+ ]);
86
+ function detectContentType(filePath) {
87
+ const ext = path.extname(filePath).toLowerCase();
88
+ return EXT_TO_TYPE[ext] ?? 'application/octet-stream';
89
+ }
90
+ /** Quick magic-byte check for common binary signatures. */
91
+ function hasBinaryMagic(buf) {
92
+ if (buf.length < 4)
93
+ return false;
94
+ // PDF: %PDF
95
+ if (buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46)
96
+ return true;
97
+ // PNG: \x89PNG
98
+ if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47)
99
+ return true;
100
+ // JPEG: \xff\xd8
101
+ if (buf[0] === 0xff && buf[1] === 0xd8)
102
+ return true;
103
+ // GIF: GIF8
104
+ if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38)
105
+ return true;
106
+ // ZIP (DOCX/XLSX/PPTX): PK\x03\x04
107
+ if (buf[0] === 0x50 && buf[1] === 0x4b && buf[2] === 0x03 && buf[3] === 0x04)
108
+ return true;
109
+ return false;
110
+ }
111
+ // ---------------------------------------------------------------------------
112
+ // Path validation
113
+ // ---------------------------------------------------------------------------
114
+ function validatePath(filePath) {
115
+ if (!filePath || typeof filePath !== 'string') {
116
+ throw new Error('file_read: `path` must be a non-empty string.');
117
+ }
118
+ if (!path.isAbsolute(filePath)) {
119
+ throw new Error(`file_read: path must be absolute. Got: "${filePath}". ` +
120
+ 'Resolve relative GAIA attachment paths against the cache directory before calling file_read.');
121
+ }
122
+ if (filePath.includes('\0')) {
123
+ throw new Error('file_read: path contains null byte — rejected.');
124
+ }
125
+ }
126
+ // ---------------------------------------------------------------------------
127
+ // Python subprocess helper
128
+ // ---------------------------------------------------------------------------
129
+ /**
130
+ * Run a Python script passed via stdin, with optional positional args.
131
+ * Uses execFileSync with stdin input to avoid shell-escaping issues.
132
+ */
133
+ function runPython(script, args, timeoutMs) {
134
+ return execFileSync('python3', ['-', ...args], {
135
+ input: script,
136
+ encoding: 'utf-8',
137
+ timeout: timeoutMs,
138
+ }).trim();
139
+ }
140
+ // ---------------------------------------------------------------------------
141
+ // Extraction helpers
142
+ // ---------------------------------------------------------------------------
143
+ /** Map an ARGB/RGB integer or tuple to a human-readable colour name. */
144
+ function colorName(r, g, b) {
145
+ if (r < 40 && g < 40 && b < 40)
146
+ return 'black';
147
+ if (r > 215 && g > 215 && b > 215)
148
+ return 'white';
149
+ if (r > 200 && g < 80 && b < 80)
150
+ return 'red';
151
+ if (r < 80 && g > 150 && b < 80)
152
+ return 'green';
153
+ if (r < 80 && g < 80 && b > 200)
154
+ return 'blue';
155
+ if (r > 200 && g > 200 && b < 80)
156
+ return 'yellow';
157
+ if (r > 200 && g > 100 && b < 80)
158
+ return 'orange';
159
+ if (r > 130 && g < 80 && b > 130)
160
+ return 'purple';
161
+ if (r < 80 && g > 150 && b > 150)
162
+ return 'teal';
163
+ if (r > 150 && g < 100 && b < 100)
164
+ return 'dark-red';
165
+ if (r > 150 && g > 150 && b > 150)
166
+ return 'light-gray';
167
+ if (r < 100 && g < 100 && b < 100)
168
+ return 'dark-gray';
169
+ return `rgb(${r},${g},${b})`;
170
+ }
171
+ /**
172
+ * Extract XLSX content via openpyxl Python subprocess.
173
+ * Returns cell values + fill colours as structured text.
174
+ */
175
+ function extractXlsx(filePath) {
176
+ const script = [
177
+ 'import sys, json',
178
+ 'from openpyxl import load_workbook',
179
+ 'wb = load_workbook(sys.argv[1])',
180
+ 'out = []',
181
+ 'for ws in wb.worksheets:',
182
+ " sheet = {'sheet': ws.title, 'cells': []}",
183
+ ' for row in ws.iter_rows():',
184
+ ' for cell in row:',
185
+ ' fill = cell.fill',
186
+ ' color = None',
187
+ " if fill and fill.fill_type == 'solid':",
188
+ ' fg = fill.fgColor',
189
+ " if fg.type == 'rgb' and fg.rgb not in ('00000000', 'FFFFFFFF', '00FFFFFF', 'FF000000', 'FFFFFFFF'):",
190
+ ' color = fg.rgb',
191
+ ' # Include cell if it has a value OR a color',
192
+ ' if cell.value is None and color is None:',
193
+ ' continue',
194
+ " entry = {'coord': cell.coordinate, 'value': str(cell.value) if cell.value is not None else ''}",
195
+ ' if color:',
196
+ " entry['color'] = color",
197
+ " sheet['cells'].append(entry)",
198
+ ' out.append(sheet)',
199
+ 'print(json.dumps(out))',
200
+ ].join('\n');
201
+ let raw;
202
+ try {
203
+ raw = runPython(script, [filePath], 30_000);
204
+ }
205
+ catch (err) {
206
+ throw new Error(`XLSX extraction failed: ${err instanceof Error ? err.message : String(err)}`);
207
+ }
208
+ let parsed;
209
+ try {
210
+ parsed = JSON.parse(raw);
211
+ }
212
+ catch {
213
+ return `[XLSX parse error]\nRaw output:\n${raw.slice(0, 2000)}`;
214
+ }
215
+ const lines = [`[XLSX: ${path.basename(filePath)} — ${parsed.length} sheet(s)]`];
216
+ for (const ws of parsed) {
217
+ lines.push(`\n--- Sheet: ${ws.sheet} ---`);
218
+ for (const cell of ws.cells) {
219
+ const colorPart = cell.color
220
+ ? (() => {
221
+ const hex = cell.color.slice(-6);
222
+ const r = parseInt(hex.slice(0, 2), 16);
223
+ const g = parseInt(hex.slice(2, 4), 16);
224
+ const b = parseInt(hex.slice(4, 6), 16);
225
+ return ` [fill:${colorName(r, g, b)}]`;
226
+ })()
227
+ : '';
228
+ lines.push(` ${cell.coord}: ${cell.value}${colorPart}`);
229
+ }
230
+ }
231
+ return lines.join('\n');
232
+ }
233
+ /**
234
+ * Extract PPTX content via python-pptx Python subprocess.
235
+ * Returns per-slide text.
236
+ */
237
+ function extractPptx(filePath) {
238
+ const script = [
239
+ 'import sys, json',
240
+ 'from pptx import Presentation',
241
+ 'prs = Presentation(sys.argv[1])',
242
+ 'out = []',
243
+ 'for i, slide in enumerate(prs.slides):',
244
+ ' texts = []',
245
+ ' for shape in slide.shapes:',
246
+ ' if not shape.has_text_frame:',
247
+ ' continue',
248
+ ' for para in shape.text_frame.paragraphs:',
249
+ " t = ''.join(run.text for run in para.runs).strip()",
250
+ ' if t:',
251
+ ' texts.append(t)',
252
+ " out.append({'slide': i + 1, 'texts': texts})",
253
+ 'print(json.dumps(out))',
254
+ ].join('\n');
255
+ let raw;
256
+ try {
257
+ raw = runPython(script, [filePath], 30_000);
258
+ }
259
+ catch (err) {
260
+ throw new Error(`PPTX extraction failed: ${err instanceof Error ? err.message : String(err)}`);
261
+ }
262
+ let parsed;
263
+ try {
264
+ parsed = JSON.parse(raw);
265
+ }
266
+ catch {
267
+ return `[PPTX parse error]\nRaw output:\n${raw.slice(0, 2000)}`;
268
+ }
269
+ const lines = [`[PPTX: ${path.basename(filePath)} — ${parsed.length} slide(s)]`];
270
+ for (const s of parsed) {
271
+ lines.push(`\n--- Slide ${s.slide} ---`);
272
+ for (const t of s.texts)
273
+ lines.push(` ${t}`);
274
+ }
275
+ return lines.join('\n');
276
+ }
277
+ /**
278
+ * Encode image as base64 and return the IMAGE_BASE64 marker.
279
+ * The agent loop will convert this to an Anthropic vision content block.
280
+ */
281
+ function extractImage(filePath, contentType) {
282
+ const buf = fs.readFileSync(filePath);
283
+ const b64 = buf.toString('base64');
284
+ const marker = JSON.stringify({ mediaType: contentType, base64: b64, path: filePath });
285
+ return `[IMAGE_BASE64:${marker}]`;
286
+ }
287
+ /**
288
+ * Transcribe audio via OpenAI Whisper (tiny model) Python subprocess.
289
+ */
290
+ function extractAudio(filePath) {
291
+ const script = [
292
+ 'import sys',
293
+ 'import whisper',
294
+ 'model = whisper.load_model("tiny")',
295
+ 'result = model.transcribe(sys.argv[1])',
296
+ "print(result['text'].strip())",
297
+ ].join('\n');
298
+ let transcript;
299
+ try {
300
+ transcript = runPython(script, [filePath], 120_000);
301
+ }
302
+ catch (err) {
303
+ throw new Error(`Audio transcription failed: ${err instanceof Error ? err.message : String(err)}`);
304
+ }
305
+ return `[Audio transcript: ${path.basename(filePath)}]\n\n${transcript}`;
306
+ }
307
+ // ---------------------------------------------------------------------------
308
+ // GaiaTool implementation
309
+ // ---------------------------------------------------------------------------
310
+ export class FileReadTool {
311
+ name = 'file_read';
312
+ definition = {
313
+ name: 'file_read',
314
+ description: 'Read the contents of a local file and return them as text. ' +
315
+ 'The path must be absolute. ' +
316
+ 'For XLSX files: returns cell values and fill colours. ' +
317
+ 'For PPTX files: returns per-slide text. ' +
318
+ 'For image files (PNG/JPEG/GIF/WebP): returns an IMAGE_BASE64 marker for vision API use. ' +
319
+ 'For audio files (MP3/WAV): returns a Whisper transcript. ' +
320
+ 'For Python source files (.py): returns the source code as text. ' +
321
+ `Maximum file size: ${MAX_FILE_BYTES / 1024 / 1024} MB.`,
322
+ input_schema: {
323
+ type: 'object',
324
+ properties: {
325
+ path: {
326
+ type: 'string',
327
+ description: 'Absolute path to the file to read.',
328
+ },
329
+ },
330
+ required: ['path'],
331
+ },
332
+ };
333
+ async execute(input) {
334
+ const filePath = String(input['path'] ?? '').trim();
335
+ validatePath(filePath);
336
+ let stat;
337
+ try {
338
+ stat = fs.statSync(filePath);
339
+ }
340
+ catch (e) {
341
+ const err = e;
342
+ if (err.code === 'ENOENT') {
343
+ throw new Error(`file_read: file not found: ${filePath}`);
344
+ }
345
+ throw new Error(`file_read: cannot stat "${filePath}": ${String(e)}`);
346
+ }
347
+ if (!stat.isFile()) {
348
+ throw new Error(`file_read: "${filePath}" is not a regular file.`);
349
+ }
350
+ if (stat.size > MAX_FILE_BYTES) {
351
+ throw new Error(`file_read: file too large (${stat.size} bytes > ${MAX_FILE_BYTES} byte limit): ${filePath}`);
352
+ }
353
+ const contentType = detectContentType(filePath);
354
+ // --- HANDLED binary types: extraction implemented ---
355
+ if (HANDLED_BINARY_TYPES.has(contentType)) {
356
+ if (contentType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
357
+ return extractXlsx(filePath);
358
+ }
359
+ if (contentType === 'application/vnd.openxmlformats-officedocument.presentationml.presentation') {
360
+ return extractPptx(filePath);
361
+ }
362
+ if (contentType.startsWith('image/')) {
363
+ return extractImage(filePath, contentType);
364
+ }
365
+ if (contentType.startsWith('audio/')) {
366
+ return extractAudio(filePath);
367
+ }
368
+ }
369
+ // --- STUB binary types: no extraction yet ---
370
+ if (STUB_BINARY_TYPES.has(contentType)) {
371
+ return (`[Binary file: ${contentType}]\n` +
372
+ `Path: ${filePath}\n` +
373
+ `Size: ${stat.size} bytes\n` +
374
+ `Note: Text extraction for this format is not yet implemented. ` +
375
+ `Describe what you expect the file to contain based on context.`);
376
+ }
377
+ // --- Read full file for magic-byte check ---
378
+ const buf = fs.readFileSync(filePath);
379
+ if (hasBinaryMagic(buf)) {
380
+ return (`[Binary file — magic bytes detected]\n` +
381
+ `Path: ${filePath}\n` +
382
+ `Size: ${stat.size} bytes\n` +
383
+ `Detected content-type: ${contentType}`);
384
+ }
385
+ // --- Plain text ---
386
+ let text;
387
+ try {
388
+ text = buf.toString('utf-8');
389
+ }
390
+ catch {
391
+ text = buf.toString('latin1');
392
+ }
393
+ const header = `[File: ${path.basename(filePath)} | type: ${contentType} | size: ${stat.size} bytes]\n\n`;
394
+ return header + text;
395
+ }
396
+ }
397
+ // ---------------------------------------------------------------------------
398
+ // Convenience factory
399
+ // ---------------------------------------------------------------------------
400
+ export function createFileReadTool() {
401
+ return new FileReadTool();
402
+ }
403
+ //# sourceMappingURL=file_read.js.map
@@ -0,0 +1,126 @@
1
+ /**
2
+ * GAIA Tool: grounded_query — ADR-135 / iter-33
3
+ *
4
+ * Calls Gemini 2.5 Flash with the google_search grounding tool and returns
5
+ * a synthesised factual answer plus source citations in a single API call.
6
+ *
7
+ * Architectural advantage over web_search (Google Custom Search):
8
+ * - web_search: raw snippets → agent reads + parses → 2-3 extra turns
9
+ * - grounded_query: Gemini synthesises an answer + cites sources in 1 call
10
+ *
11
+ * This is Ruflo's cross-provider stack in action:
12
+ * Gemini grounds (google_search tool) → Sonnet/Haiku reasons → answer
13
+ *
14
+ * Credential resolution (mirrors performance-capability.ts / web_search.ts):
15
+ * 1. process.env.GOOGLE_AI_API_KEY
16
+ * 2. gcloud secrets versions access latest --secret=GOOGLE_AI_API_KEY --project=ruv-dev
17
+ * 3. Throws with clear instructions if neither is available
18
+ *
19
+ * Free tier: 1500 grounded queries/day on Gemini 2.5 Flash.
20
+ * Pricing: ~$0.075/M input tokens, ~$0.30/M output tokens, grounding free <1500/day.
21
+ *
22
+ * Regression note (iter-47): this file was absent from feat/adr-135-integrate-tracks
23
+ * because the grounded-query-gemini branch was not cherry-picked during Track integration.
24
+ * The omission caused a 36-question empty-answer failure in iter-42 (13.2% vs 49.1% baseline).
25
+ *
26
+ * Refs: ADR-133, ADR-135, iter-30 research, iter-33, iter-47, #2156
27
+ * Live-tested 2026-05-27: Mercedes Sosa GAIA L1 question → HTTP 200, 4 sources.
28
+ */
29
+ import { GaiaTool, ToolDefinition } from './types.js';
30
+ export interface GroundedQueryInput {
31
+ query: string;
32
+ max_tokens?: number;
33
+ }
34
+ export interface GroundedQuerySource {
35
+ title: string;
36
+ uri: string;
37
+ snippet?: string;
38
+ }
39
+ export interface GroundedQueryResult {
40
+ /** Synthesised factual answer from Gemini. */
41
+ answer: string;
42
+ /** Web pages Gemini cited when composing its answer. */
43
+ sources: GroundedQuerySource[];
44
+ /** Auto-formulated search queries issued by Gemini. */
45
+ search_queries_used: string[];
46
+ /** True when grounding metadata was returned (sources or search_queries present). */
47
+ grounded: boolean;
48
+ /** Always 'gemini-2.5-flash' for this tool. */
49
+ model: string;
50
+ /** Estimated cost in USD. */
51
+ cost_usd: number;
52
+ }
53
+ interface GeminiPart {
54
+ text?: string;
55
+ }
56
+ interface GeminiGroundingChunk {
57
+ web?: {
58
+ title?: string;
59
+ uri?: string;
60
+ };
61
+ }
62
+ interface GeminiGroundingSupport {
63
+ groundingChunkIndices?: number[];
64
+ segment?: {
65
+ text?: string;
66
+ };
67
+ }
68
+ interface GeminiGroundingMetadata {
69
+ groundingChunks?: GeminiGroundingChunk[];
70
+ webSearchQueries?: string[];
71
+ groundingSupports?: GeminiGroundingSupport[];
72
+ }
73
+ interface GeminiCandidate {
74
+ content?: {
75
+ parts?: GeminiPart[];
76
+ };
77
+ groundingMetadata?: GeminiGroundingMetadata;
78
+ }
79
+ interface GeminiUsageMetadata {
80
+ promptTokenCount?: number;
81
+ candidatesTokenCount?: number;
82
+ }
83
+ interface GeminiGenerateContentResponse {
84
+ candidates?: GeminiCandidate[];
85
+ usageMetadata?: GeminiUsageMetadata;
86
+ }
87
+ export interface GroundedQueryTestHooks {
88
+ /** Override the API key resolver. */
89
+ resolveKey?: () => Promise<string>;
90
+ /** Override the actual HTTP fetch so tests never make live calls. */
91
+ fetchResponse?: (query: string, maxTokens: number, apiKey: string) => Promise<GeminiGenerateContentResponse>;
92
+ }
93
+ export declare const groundedQueryTestHooks: GroundedQueryTestHooks;
94
+ /**
95
+ * Resolve a Google AI API key.
96
+ *
97
+ * Order: env var → gcloud secret → throw.
98
+ * Never returns null — throws with actionable guidance if no key is found.
99
+ */
100
+ export declare function resolveGoogleAIApiKey(): Promise<string>;
101
+ /**
102
+ * Call Gemini 2.5 Flash with google_search grounding and parse the response.
103
+ *
104
+ * Exported so smoke tests can exercise the parser without live HTTP (via
105
+ * groundedQueryTestHooks.fetchResponse).
106
+ */
107
+ export declare function callGeminiGrounded(query: string, maxTokens: number, apiKey: string): Promise<GroundedQueryResult>;
108
+ /**
109
+ * Parse a raw Gemini generateContent response into GroundedQueryResult.
110
+ * Exported for unit testing the parser independently.
111
+ */
112
+ export declare function parseGeminiResponse(body: GeminiGenerateContentResponse): GroundedQueryResult;
113
+ export declare class GroundedQueryTool implements GaiaTool {
114
+ readonly name = "grounded_query";
115
+ readonly definition: ToolDefinition;
116
+ private readonly apiKey?;
117
+ constructor(opts?: {
118
+ apiKey?: string;
119
+ });
120
+ execute(input: Record<string, unknown>): Promise<string>;
121
+ }
122
+ export declare function createGroundedQueryTool(opts?: {
123
+ apiKey?: string;
124
+ }): GroundedQueryTool;
125
+ export {};
126
+ //# sourceMappingURL=grounded_query.d.ts.map