@claude-flow/cli 3.10.5 → 3.10.7

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 (145) hide show
  1. package/README.md +2 -2
  2. package/dist/src/benchmarks/capability-tasks.d.ts +126 -0
  3. package/dist/src/benchmarks/capability-tasks.d.ts.map +1 -0
  4. package/dist/src/benchmarks/capability-tasks.js +147 -0
  5. package/dist/src/benchmarks/capability-tasks.js.map +1 -0
  6. package/dist/src/benchmarks/gaia-agent-contrastive.d.ts +53 -0
  7. package/dist/src/benchmarks/gaia-agent-contrastive.d.ts.map +1 -0
  8. package/dist/src/benchmarks/gaia-agent-contrastive.js +177 -0
  9. package/dist/src/benchmarks/gaia-agent-contrastive.js.map +1 -0
  10. package/dist/src/benchmarks/gaia-agent-gemini.d.ts +51 -0
  11. package/dist/src/benchmarks/gaia-agent-gemini.d.ts.map +1 -0
  12. package/dist/src/benchmarks/gaia-agent-gemini.js +352 -0
  13. package/dist/src/benchmarks/gaia-agent-gemini.js.map +1 -0
  14. package/dist/src/benchmarks/gaia-claude-p.d.ts +105 -0
  15. package/dist/src/benchmarks/gaia-claude-p.d.ts.map +1 -0
  16. package/dist/src/benchmarks/gaia-claude-p.js +269 -0
  17. package/dist/src/benchmarks/gaia-claude-p.js.map +1 -0
  18. package/dist/src/benchmarks/gaia-claude-p.smoke.d.ts +20 -0
  19. package/dist/src/benchmarks/gaia-claude-p.smoke.d.ts.map +1 -0
  20. package/dist/src/benchmarks/gaia-claude-p.smoke.js +168 -0
  21. package/dist/src/benchmarks/gaia-claude-p.smoke.js.map +1 -0
  22. package/dist/src/benchmarks/gaia-codeagent-runner.py +556 -0
  23. package/dist/src/benchmarks/gaia-codeagent.d.ts +129 -0
  24. package/dist/src/benchmarks/gaia-codeagent.d.ts.map +1 -0
  25. package/dist/src/benchmarks/gaia-codeagent.js +590 -0
  26. package/dist/src/benchmarks/gaia-codeagent.js.map +1 -0
  27. package/dist/src/benchmarks/gaia-codeagent.smoke.d.ts +33 -0
  28. package/dist/src/benchmarks/gaia-codeagent.smoke.d.ts.map +1 -0
  29. package/dist/src/benchmarks/gaia-codeagent.smoke.js +241 -0
  30. package/dist/src/benchmarks/gaia-codeagent.smoke.js.map +1 -0
  31. package/dist/src/benchmarks/gaia-dag-pilot.d.ts +22 -0
  32. package/dist/src/benchmarks/gaia-dag-pilot.d.ts.map +1 -0
  33. package/dist/src/benchmarks/gaia-dag-pilot.js +158 -0
  34. package/dist/src/benchmarks/gaia-dag-pilot.js.map +1 -0
  35. package/dist/src/benchmarks/gaia-dag.d.ts +110 -0
  36. package/dist/src/benchmarks/gaia-dag.d.ts.map +1 -0
  37. package/dist/src/benchmarks/gaia-dag.js +658 -0
  38. package/dist/src/benchmarks/gaia-dag.js.map +1 -0
  39. package/dist/src/benchmarks/gaia-dag.smoke.d.ts +21 -0
  40. package/dist/src/benchmarks/gaia-dag.smoke.d.ts.map +1 -0
  41. package/dist/src/benchmarks/gaia-dag.smoke.js +290 -0
  42. package/dist/src/benchmarks/gaia-dag.smoke.js.map +1 -0
  43. package/dist/src/benchmarks/gaia-ensemble-pilot.d.ts +17 -0
  44. package/dist/src/benchmarks/gaia-ensemble-pilot.d.ts.map +1 -0
  45. package/dist/src/benchmarks/gaia-ensemble-pilot.js +106 -0
  46. package/dist/src/benchmarks/gaia-ensemble-pilot.js.map +1 -0
  47. package/dist/src/benchmarks/gaia-ensemble.d.ts +103 -0
  48. package/dist/src/benchmarks/gaia-ensemble.d.ts.map +1 -0
  49. package/dist/src/benchmarks/gaia-ensemble.js +462 -0
  50. package/dist/src/benchmarks/gaia-ensemble.js.map +1 -0
  51. package/dist/src/benchmarks/gaia-gemini-pilot.d.ts +17 -0
  52. package/dist/src/benchmarks/gaia-gemini-pilot.d.ts.map +1 -0
  53. package/dist/src/benchmarks/gaia-gemini-pilot.js +168 -0
  54. package/dist/src/benchmarks/gaia-gemini-pilot.js.map +1 -0
  55. package/dist/src/benchmarks/gaia-mode-router.d.ts +67 -0
  56. package/dist/src/benchmarks/gaia-mode-router.d.ts.map +1 -0
  57. package/dist/src/benchmarks/gaia-mode-router.js +126 -0
  58. package/dist/src/benchmarks/gaia-mode-router.js.map +1 -0
  59. package/dist/src/benchmarks/gaia-mode-router.smoke.d.ts +15 -0
  60. package/dist/src/benchmarks/gaia-mode-router.smoke.d.ts.map +1 -0
  61. package/dist/src/benchmarks/gaia-mode-router.smoke.js +131 -0
  62. package/dist/src/benchmarks/gaia-mode-router.smoke.js.map +1 -0
  63. package/dist/src/benchmarks/gaia-tools/grounded_query.smoke.d.ts +24 -0
  64. package/dist/src/benchmarks/gaia-tools/grounded_query.smoke.d.ts.map +1 -0
  65. package/dist/src/benchmarks/gaia-tools/grounded_query.smoke.js +276 -0
  66. package/dist/src/benchmarks/gaia-tools/grounded_query.smoke.js.map +1 -0
  67. package/dist/src/benchmarks/gaia-tools/image_describe.d.ts +45 -0
  68. package/dist/src/benchmarks/gaia-tools/image_describe.d.ts.map +1 -0
  69. package/dist/src/benchmarks/gaia-tools/image_describe.js +222 -0
  70. package/dist/src/benchmarks/gaia-tools/image_describe.js.map +1 -0
  71. package/dist/src/benchmarks/gaia-tools/image_describe.smoke.d.ts +24 -0
  72. package/dist/src/benchmarks/gaia-tools/image_describe.smoke.d.ts.map +1 -0
  73. package/dist/src/benchmarks/gaia-tools/image_describe.smoke.js +169 -0
  74. package/dist/src/benchmarks/gaia-tools/image_describe.smoke.js.map +1 -0
  75. package/dist/src/benchmarks/gaia-tools/pdf_read.d.ts +27 -0
  76. package/dist/src/benchmarks/gaia-tools/pdf_read.d.ts.map +1 -0
  77. package/dist/src/benchmarks/gaia-tools/pdf_read.js +226 -0
  78. package/dist/src/benchmarks/gaia-tools/pdf_read.js.map +1 -0
  79. package/dist/src/benchmarks/gaia-tools/python_exec.d.ts +31 -0
  80. package/dist/src/benchmarks/gaia-tools/python_exec.d.ts.map +1 -0
  81. package/dist/src/benchmarks/gaia-tools/python_exec.js +94 -0
  82. package/dist/src/benchmarks/gaia-tools/python_exec.js.map +1 -0
  83. package/dist/src/benchmarks/gaia-tools/python_exec.smoke.d.ts +13 -0
  84. package/dist/src/benchmarks/gaia-tools/python_exec.smoke.d.ts.map +1 -0
  85. package/dist/src/benchmarks/gaia-tools/python_exec.smoke.js +98 -0
  86. package/dist/src/benchmarks/gaia-tools/python_exec.smoke.js.map +1 -0
  87. package/dist/src/benchmarks/gaia-tools/visit_webpage.d.ts +52 -0
  88. package/dist/src/benchmarks/gaia-tools/visit_webpage.d.ts.map +1 -0
  89. package/dist/src/benchmarks/gaia-tools/visit_webpage.js +304 -0
  90. package/dist/src/benchmarks/gaia-tools/visit_webpage.js.map +1 -0
  91. package/dist/src/benchmarks/gaia-tools/web_browse.d.ts +61 -0
  92. package/dist/src/benchmarks/gaia-tools/web_browse.d.ts.map +1 -0
  93. package/dist/src/benchmarks/gaia-tools/web_browse.js +217 -0
  94. package/dist/src/benchmarks/gaia-tools/web_browse.js.map +1 -0
  95. package/dist/src/benchmarks/gaia-tools/web_browse.smoke.d.ts +26 -0
  96. package/dist/src/benchmarks/gaia-tools/web_browse.smoke.d.ts.map +1 -0
  97. package/dist/src/benchmarks/gaia-tools/web_browse.smoke.js +152 -0
  98. package/dist/src/benchmarks/gaia-tools/web_browse.smoke.js.map +1 -0
  99. package/dist/src/benchmarks/gaia-tools/web_search.smoke.d.ts +24 -0
  100. package/dist/src/benchmarks/gaia-tools/web_search.smoke.d.ts.map +1 -0
  101. package/dist/src/benchmarks/gaia-tools/web_search.smoke.js +311 -0
  102. package/dist/src/benchmarks/gaia-tools/web_search.smoke.js.map +1 -0
  103. package/dist/src/benchmarks/gaia-visit-webpage.smoke.d.ts +25 -0
  104. package/dist/src/benchmarks/gaia-visit-webpage.smoke.d.ts.map +1 -0
  105. package/dist/src/benchmarks/gaia-visit-webpage.smoke.js +304 -0
  106. package/dist/src/benchmarks/gaia-visit-webpage.smoke.js.map +1 -0
  107. package/dist/src/commands/performance-capability.d.ts +30 -0
  108. package/dist/src/commands/performance-capability.d.ts.map +1 -0
  109. package/dist/src/commands/performance-capability.js +349 -0
  110. package/dist/src/commands/performance-capability.js.map +1 -0
  111. package/dist/src/commands/route.d.ts.map +1 -1
  112. package/dist/src/commands/route.js +9 -0
  113. package/dist/src/commands/route.js.map +1 -1
  114. package/dist/src/init/statusline-generator.d.ts.map +1 -1
  115. package/dist/src/init/statusline-generator.js +25 -2
  116. package/dist/src/init/statusline-generator.js.map +1 -1
  117. package/dist/src/mcp-tools/agentdb-tools.d.ts.map +1 -1
  118. package/dist/src/mcp-tools/agentdb-tools.js +20 -3
  119. package/dist/src/mcp-tools/agentdb-tools.js.map +1 -1
  120. package/dist/src/mcp-tools/hooks-tools.d.ts.map +1 -1
  121. package/dist/src/mcp-tools/hooks-tools.js +60 -14
  122. package/dist/src/mcp-tools/hooks-tools.js.map +1 -1
  123. package/dist/src/mcp-tools/memory-tools.d.ts.map +1 -1
  124. package/dist/src/mcp-tools/memory-tools.js +36 -3
  125. package/dist/src/mcp-tools/memory-tools.js.map +1 -1
  126. package/dist/src/mcp-tools/system-tools.d.ts.map +1 -1
  127. package/dist/src/mcp-tools/system-tools.js +12 -1
  128. package/dist/src/mcp-tools/system-tools.js.map +1 -1
  129. package/dist/src/memory/memory-bridge.d.ts +1 -0
  130. package/dist/src/memory/memory-bridge.d.ts.map +1 -1
  131. package/dist/src/memory/memory-bridge.js +39 -0
  132. package/dist/src/memory/memory-bridge.js.map +1 -1
  133. package/dist/src/memory/memory-initializer.d.ts +10 -0
  134. package/dist/src/memory/memory-initializer.d.ts.map +1 -1
  135. package/dist/src/memory/memory-initializer.js +22 -5
  136. package/dist/src/memory/memory-initializer.js.map +1 -1
  137. package/dist/src/parser.d.ts +16 -0
  138. package/dist/src/parser.d.ts.map +1 -1
  139. package/dist/src/parser.js +23 -2
  140. package/dist/src/parser.js.map +1 -1
  141. package/dist/src/ruvector/vector-db.d.ts.map +1 -1
  142. package/dist/src/ruvector/vector-db.js +31 -3
  143. package/dist/src/ruvector/vector-db.js.map +1 -1
  144. package/dist/tsconfig.tsbuildinfo +1 -1
  145. package/package.json +1 -1
@@ -0,0 +1,556 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ GAIA CodeAgent Python Step Runner — ADR-138 iter 54
4
+
5
+ This script is invoked by gaia-codeagent.ts for each agent step.
6
+ It pre-defines tool functions as Python callables, then exec()s the agent's
7
+ code in that context.
8
+
9
+ Protocol (via environment variables):
10
+ GAIA_CODE_FILE : path to a temp file containing the agent's Python code
11
+ GAIA_RESULT_FILE : path where this runner writes final_answer JSON sentinel
12
+ ANTHROPIC_API_KEY : passed through to claude -p tool backends
13
+ GAIA_ATTACHMENT_PATH: optional attachment file path for this question
14
+
15
+ Tool dispatch strategy:
16
+ web_search(query) -> claude -p with WebSearch (best web coverage)
17
+ visit_webpage(url) -> requests + bs4 HTML extraction (no claude -p overhead)
18
+ grounded_query(query) -> ruflo TS grounded_query via node subprocess
19
+ read_file(path) -> direct Python (text/csv/json/xlsx/pptx) or requests+bs4 for PDF
20
+ describe_image(path) -> claude -p with --allowedTools Read (Claude vision)
21
+ final_answer(answer) -> writes GAIA_RESULT_FILE JSON and sys.exit(0)
22
+
23
+ Authorized imports (pre-loaded):
24
+ math, re, json, datetime, collections, itertools, statistics,
25
+ fractions, decimal, string, unicodedata, operator, sys, os, pathlib,
26
+ urllib.parse, pandas (optional), numpy (optional), sympy (optional),
27
+ requests (optional), bs4 (optional), openpyxl (optional)
28
+
29
+ Refs: ADR-138, HAL-DEEP-STUDY.md, #2156, iter 54
30
+ """
31
+
32
+ import sys
33
+ import os
34
+ import json
35
+ import subprocess
36
+ import tempfile
37
+ import math
38
+ import re
39
+ import datetime
40
+ from datetime import date, timedelta
41
+ from collections import Counter, defaultdict, OrderedDict
42
+ import itertools
43
+ import statistics
44
+ import fractions
45
+ import decimal
46
+ import operator
47
+ import string
48
+ import unicodedata
49
+ from urllib.parse import urlparse, quote, unquote
50
+ from pathlib import Path
51
+
52
+ # Optional heavy imports — graceful fallback
53
+ try:
54
+ import pandas as pd
55
+ import numpy as np
56
+ except ImportError:
57
+ pd = None
58
+ np = None
59
+
60
+ try:
61
+ import sympy
62
+ except ImportError:
63
+ sympy = None
64
+
65
+ try:
66
+ import requests
67
+ from bs4 import BeautifulSoup
68
+ HAS_REQUESTS = True
69
+ except ImportError:
70
+ requests = None
71
+ BeautifulSoup = None
72
+ HAS_REQUESTS = False
73
+
74
+ try:
75
+ import openpyxl
76
+ HAS_OPENPYXL = True
77
+ except ImportError:
78
+ HAS_OPENPYXL = False
79
+
80
+ try:
81
+ from pptx import Presentation as PptxPresentation
82
+ HAS_PPTX = True
83
+ except ImportError:
84
+ HAS_PPTX = False
85
+
86
+
87
+ # ---------------------------------------------------------------------------
88
+ # Configuration
89
+ # ---------------------------------------------------------------------------
90
+
91
+ ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
92
+ GAIA_RESULT_FILE = os.environ.get("GAIA_RESULT_FILE", "")
93
+ GAIA_CODE_FILE = os.environ.get("GAIA_CODE_FILE", "")
94
+ GAIA_ATTACHMENT_PATH = os.environ.get("GAIA_ATTACHMENT_PATH", "")
95
+
96
+ CLAUDE_CMD = "claude"
97
+ TOOL_TIMEOUT = 30 # seconds per tool call
98
+
99
+
100
+ # ---------------------------------------------------------------------------
101
+ # Tool: web_search
102
+ # Dispatches to claude -p with WebSearch for best web coverage
103
+ # ---------------------------------------------------------------------------
104
+
105
+ def web_search(query: str) -> str:
106
+ """Search the web and return relevant snippets."""
107
+ if not query or not query.strip():
108
+ return "[web_search: empty query]"
109
+ try:
110
+ result = subprocess.run(
111
+ [
112
+ CLAUDE_CMD, "-p",
113
+ "--allowedTools", "WebSearch",
114
+ "--output-format", "text",
115
+ f"Search the web for: {query}\n\nReturn the top results with titles, URLs, and key snippets. Be concise.",
116
+ ],
117
+ capture_output=True,
118
+ text=True,
119
+ timeout=TOOL_TIMEOUT,
120
+ env={**os.environ, "ANTHROPIC_API_KEY": ANTHROPIC_API_KEY},
121
+ )
122
+ output = result.stdout.strip()
123
+ if output:
124
+ return output[:4000]
125
+ if result.stderr:
126
+ return f"[web_search: {result.stderr.strip()[:200]}]"
127
+ return "[web_search: no results]"
128
+ except subprocess.TimeoutExpired:
129
+ return f"[web_search: timed out after {TOOL_TIMEOUT}s]"
130
+ except FileNotFoundError:
131
+ # claude CLI not available — fall back to DuckDuckGo scraping
132
+ return _ddg_fallback(query)
133
+ except Exception as e:
134
+ return f"[web_search error: {e}]"
135
+
136
+
137
+ def _ddg_fallback(query: str) -> str:
138
+ """Fallback web search via DuckDuckGo HTML scraping."""
139
+ if not HAS_REQUESTS:
140
+ return "[web_search: requests not available]"
141
+ try:
142
+ headers = {"User-Agent": "Mozilla/5.0 (compatible; ruflo-gaia/1.0)"}
143
+ resp = requests.post(
144
+ "https://html.duckduckgo.com/html/",
145
+ data={"q": query},
146
+ headers=headers,
147
+ timeout=15,
148
+ )
149
+ soup = BeautifulSoup(resp.text, "html.parser")
150
+ results = []
151
+ for r in soup.select(".result")[:5]:
152
+ title_el = r.select_one(".result__title")
153
+ snip_el = r.select_one(".result__snippet")
154
+ title = title_el.get_text(strip=True) if title_el else ""
155
+ snip = snip_el.get_text(strip=True) if snip_el else ""
156
+ if title:
157
+ results.append(f"{title}: {snip}")
158
+ return "\n".join(results) if results else "[web_search: no results]"
159
+ except Exception as e:
160
+ return f"[web_search: {e}]"
161
+
162
+
163
+ # ---------------------------------------------------------------------------
164
+ # Tool: visit_webpage
165
+ # Fetches full page content via requests + bs4
166
+ # ---------------------------------------------------------------------------
167
+
168
+ def visit_webpage(url: str) -> str:
169
+ """Fetch the full text content of a webpage."""
170
+ if not url or not url.strip():
171
+ return "[visit_webpage: empty URL]"
172
+ url = url.strip()
173
+ if not url.startswith("http"):
174
+ url = "https://" + url
175
+ if HAS_REQUESTS:
176
+ return _visit_with_requests(url)
177
+ else:
178
+ return _visit_with_claude(url)
179
+
180
+
181
+ def _visit_with_requests(url: str) -> str:
182
+ """Fetch page via requests + bs4 text extraction."""
183
+ try:
184
+ headers = {"User-Agent": "Mozilla/5.0 (compatible; ruflo-gaia/1.0)"}
185
+ resp = requests.get(url, headers=headers, timeout=20, allow_redirects=True)
186
+ if resp.status_code != 200:
187
+ return f"[visit_webpage: HTTP {resp.status_code} for {url}]"
188
+
189
+ soup = BeautifulSoup(resp.text, "html.parser")
190
+ # Remove noise
191
+ for tag in soup(["script", "style", "nav", "footer", "header", "aside", "noscript"]):
192
+ tag.decompose()
193
+
194
+ # Extract main content
195
+ text = soup.get_text(separator="\n", strip=True)
196
+ # Collapse blank lines
197
+ lines = [l.strip() for l in text.splitlines() if l.strip()]
198
+ content = "\n".join(lines)
199
+
200
+ if len(content) > 8000:
201
+ content = content[:8000] + "\n[... truncated ...]"
202
+ return content if content else "[visit_webpage: no text content extracted]"
203
+ except requests.exceptions.Timeout:
204
+ return f"[visit_webpage: timed out fetching {url}]"
205
+ except Exception as e:
206
+ return f"[visit_webpage error: {e}]"
207
+
208
+
209
+ def _visit_with_claude(url: str) -> str:
210
+ """Fallback: fetch webpage via claude -p with WebFetch."""
211
+ try:
212
+ result = subprocess.run(
213
+ [
214
+ CLAUDE_CMD, "-p",
215
+ "--allowedTools", "WebFetch",
216
+ "--output-format", "text",
217
+ f"Fetch the content of this URL and return the full text: {url}",
218
+ ],
219
+ capture_output=True,
220
+ text=True,
221
+ timeout=TOOL_TIMEOUT,
222
+ env={**os.environ, "ANTHROPIC_API_KEY": ANTHROPIC_API_KEY},
223
+ )
224
+ output = result.stdout.strip()
225
+ return output[:8000] if output else f"[visit_webpage: no content from {url}]"
226
+ except Exception as e:
227
+ return f"[visit_webpage: {e}]"
228
+
229
+
230
+ # ---------------------------------------------------------------------------
231
+ # Tool: grounded_query
232
+ # Calls Gemini with Google Search grounding (ruflo's unique advantage)
233
+ # ---------------------------------------------------------------------------
234
+
235
+ def grounded_query(query: str) -> str:
236
+ """Ask Gemini with Google Search grounding — returns synthesized answer with citations."""
237
+ if not query or not query.strip():
238
+ return "[grounded_query: empty query]"
239
+
240
+ google_key = os.environ.get("GOOGLE_AI_API_KEY", "")
241
+ if not google_key:
242
+ # Fall back to web_search if no Google key
243
+ return web_search(query)
244
+
245
+ try:
246
+ import urllib.request
247
+ import urllib.error
248
+
249
+ url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"
250
+ payload = {
251
+ "contents": [{"parts": [{"text": query}]}],
252
+ "tools": [{"google_search": {}}],
253
+ "generationConfig": {"maxOutputTokens": 1024},
254
+ }
255
+ data = json.dumps(payload).encode("utf-8")
256
+ req = urllib.request.Request(
257
+ f"{url}?key={google_key}",
258
+ data=data,
259
+ headers={"Content-Type": "application/json"},
260
+ )
261
+ with urllib.request.urlopen(req, timeout=20) as resp:
262
+ body = json.loads(resp.read().decode("utf-8"))
263
+
264
+ # Extract text
265
+ candidates = body.get("candidates", [])
266
+ if not candidates:
267
+ return "[grounded_query: no candidates]"
268
+ parts = candidates[0].get("content", {}).get("parts", [])
269
+ text = " ".join(p.get("text", "") for p in parts).strip()
270
+
271
+ # Extract sources
272
+ sources = []
273
+ grounding = candidates[0].get("groundingMetadata", {})
274
+ for chunk in grounding.get("groundingChunks", [])[:4]:
275
+ web = chunk.get("web", {})
276
+ title = web.get("title", "")
277
+ src_uri = web.get("uri", "")
278
+ if title and src_uri:
279
+ sources.append(f"- {title}: {src_uri}")
280
+
281
+ result = text
282
+ if sources:
283
+ result += "\n\nSources:\n" + "\n".join(sources)
284
+ return result[:4000] if result else "[grounded_query: empty response]"
285
+
286
+ except Exception as e:
287
+ # Fall back to web_search
288
+ return web_search(query)
289
+
290
+
291
+ # ---------------------------------------------------------------------------
292
+ # Tool: read_file
293
+ # Supports: txt, csv, json, xlsx, pptx, pdf (via pdfminer.six if available)
294
+ # ---------------------------------------------------------------------------
295
+
296
+ def read_file(path: str) -> str:
297
+ """Read a file and return its text content."""
298
+ if not path or not path.strip():
299
+ return "[read_file: empty path]"
300
+ path = path.strip()
301
+ if not os.path.exists(path):
302
+ return f"[read_file: file not found: {path}]"
303
+
304
+ ext = Path(path).suffix.lower()
305
+
306
+ # Text-based formats — direct read
307
+ if ext in (".txt", ".md", ".log", ".xml", ".html", ".htm"):
308
+ try:
309
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
310
+ content = f.read(50_000)
311
+ return content if content else "[read_file: empty file]"
312
+ except Exception as e:
313
+ return f"[read_file: {e}]"
314
+
315
+ # JSON
316
+ if ext == ".json":
317
+ try:
318
+ with open(path, "r", encoding="utf-8") as f:
319
+ data = json.load(f)
320
+ return json.dumps(data, indent=2)[:8000]
321
+ except Exception as e:
322
+ return f"[read_file json: {e}]"
323
+
324
+ # CSV
325
+ if ext == ".csv":
326
+ if pd is not None:
327
+ try:
328
+ df = pd.read_csv(path)
329
+ return f"Shape: {df.shape}\nColumns: {list(df.columns)}\n\nFirst rows:\n{df.head(10).to_string()}"
330
+ except Exception as e:
331
+ return f"[read_file csv: {e}]"
332
+ else:
333
+ try:
334
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
335
+ return f.read(8000)
336
+ except Exception as e:
337
+ return f"[read_file csv: {e}]"
338
+
339
+ # Excel
340
+ if ext in (".xlsx", ".xls"):
341
+ if pd is not None:
342
+ try:
343
+ df = pd.read_excel(path, sheet_name=None)
344
+ parts = []
345
+ for sheet_name, sheet_df in df.items():
346
+ parts.append(f"Sheet: {sheet_name}")
347
+ parts.append(sheet_df.head(20).to_string())
348
+ return "\n\n".join(parts)[:8000]
349
+ except Exception as e:
350
+ return f"[read_file excel: {e}]"
351
+ elif HAS_OPENPYXL:
352
+ try:
353
+ wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
354
+ parts = []
355
+ for ws in wb.worksheets:
356
+ rows = []
357
+ for row in ws.iter_rows(max_row=20, values_only=True):
358
+ rows.append("\t".join(str(c) if c is not None else "" for c in row))
359
+ parts.append(f"Sheet: {ws.title}\n" + "\n".join(rows))
360
+ return "\n\n".join(parts)[:8000]
361
+ except Exception as e:
362
+ return f"[read_file excel: {e}]"
363
+ return "[read_file: pandas/openpyxl not available for Excel]"
364
+
365
+ # PPTX
366
+ if ext == ".pptx":
367
+ if HAS_PPTX:
368
+ try:
369
+ prs = PptxPresentation(path)
370
+ parts = []
371
+ for i, slide in enumerate(prs.slides):
372
+ texts = [shape.text for shape in slide.shapes if shape.has_text_frame]
373
+ parts.append(f"Slide {i+1}: " + " | ".join(texts))
374
+ return "\n".join(parts)[:8000]
375
+ except Exception as e:
376
+ return f"[read_file pptx: {e}]"
377
+ return "[read_file: python-pptx not available]"
378
+
379
+ # PDF — try pdfminer.six, then fallback to pdftotext subprocess
380
+ if ext == ".pdf":
381
+ return _read_pdf(path)
382
+
383
+ # Images — use describe_image
384
+ if ext in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff"):
385
+ return describe_image(path)
386
+
387
+ # Unknown — try as text
388
+ try:
389
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
390
+ return f.read(8000)
391
+ except Exception as e:
392
+ return f"[read_file: unsupported format {ext}: {e}]"
393
+
394
+
395
+ def _read_pdf(path: str) -> str:
396
+ """Extract text from a PDF file."""
397
+ # Try pdfminer.six
398
+ try:
399
+ from pdfminer.high_level import extract_text as pdfminer_extract
400
+ text = pdfminer_extract(path)
401
+ if text and text.strip():
402
+ return text.strip()[:8000]
403
+ except ImportError:
404
+ pass
405
+ except Exception:
406
+ pass
407
+
408
+ # Try pdftotext subprocess
409
+ try:
410
+ result = subprocess.run(
411
+ ["pdftotext", path, "-"],
412
+ capture_output=True, text=True, timeout=15
413
+ )
414
+ if result.stdout.strip():
415
+ return result.stdout.strip()[:8000]
416
+ except (FileNotFoundError, subprocess.TimeoutExpired, Exception):
417
+ pass
418
+
419
+ # Last resort: claude -p with Read (vision for scanned PDFs)
420
+ if ANTHROPIC_API_KEY:
421
+ try:
422
+ result = subprocess.run(
423
+ [
424
+ CLAUDE_CMD, "-p",
425
+ "--allowedTools", "Read",
426
+ "--output-format", "text",
427
+ f"Read and extract all text from this file: {path}",
428
+ ],
429
+ capture_output=True, text=True, timeout=30,
430
+ env={**os.environ, "ANTHROPIC_API_KEY": ANTHROPIC_API_KEY},
431
+ )
432
+ if result.stdout.strip():
433
+ return result.stdout.strip()[:8000]
434
+ except Exception:
435
+ pass
436
+
437
+ return f"[read_file: could not extract text from PDF at {path}]"
438
+
439
+
440
+ # ---------------------------------------------------------------------------
441
+ # Tool: describe_image
442
+ # Uses claude -p with vision capability
443
+ # ---------------------------------------------------------------------------
444
+
445
+ def describe_image(path: str) -> str:
446
+ """Describe the contents of an image using Claude vision."""
447
+ if not path or not os.path.exists(path):
448
+ return f"[describe_image: file not found: {path}]"
449
+ if not ANTHROPIC_API_KEY:
450
+ return "[describe_image: ANTHROPIC_API_KEY not set]"
451
+ try:
452
+ result = subprocess.run(
453
+ [
454
+ CLAUDE_CMD, "-p",
455
+ "--allowedTools", "Read",
456
+ "--output-format", "text",
457
+ f"Describe this image in detail, including any text, numbers, charts, or data visible: {path}",
458
+ ],
459
+ capture_output=True, text=True, timeout=30,
460
+ env={**os.environ, "ANTHROPIC_API_KEY": ANTHROPIC_API_KEY},
461
+ )
462
+ output = result.stdout.strip()
463
+ return output[:4000] if output else "[describe_image: no description generated]"
464
+ except Exception as e:
465
+ return f"[describe_image: {e}]"
466
+
467
+
468
+ # ---------------------------------------------------------------------------
469
+ # Tool: final_answer
470
+ # Writes sentinel JSON and exits
471
+ # ---------------------------------------------------------------------------
472
+
473
+ def final_answer(answer) -> None:
474
+ """Submit the final answer. This ends the agent loop."""
475
+ answer_str = str(answer).strip()
476
+
477
+ # Write sentinel JSON
478
+ if GAIA_RESULT_FILE:
479
+ try:
480
+ with open(GAIA_RESULT_FILE, "w", encoding="utf-8") as f:
481
+ json.dump({"answer": answer_str}, f)
482
+ except Exception as e:
483
+ print(f"[final_answer: could not write result file: {e}]", file=sys.stderr)
484
+
485
+ print(f"[GAIA_FINAL_ANSWER]: {answer_str}")
486
+ sys.exit(0)
487
+
488
+
489
+ # ---------------------------------------------------------------------------
490
+ # Main execution
491
+ # ---------------------------------------------------------------------------
492
+
493
+ def main():
494
+ # Read agent code
495
+ if not GAIA_CODE_FILE or not os.path.exists(GAIA_CODE_FILE):
496
+ print("[CodeAgent runner: GAIA_CODE_FILE not set or not found]", file=sys.stderr)
497
+ sys.exit(1)
498
+
499
+ with open(GAIA_CODE_FILE, "r", encoding="utf-8") as f:
500
+ agent_code = f.read()
501
+
502
+ # Build execution globals with all tool functions pre-defined
503
+ exec_globals = {
504
+ "__builtins__": __builtins__,
505
+ # Math / standard lib
506
+ "math": math,
507
+ "re": re,
508
+ "json": json,
509
+ "datetime": datetime,
510
+ "date": date,
511
+ "timedelta": timedelta,
512
+ "Counter": Counter,
513
+ "defaultdict": defaultdict,
514
+ "OrderedDict": OrderedDict,
515
+ "itertools": itertools,
516
+ "statistics": statistics,
517
+ "fractions": fractions,
518
+ "decimal": decimal,
519
+ "operator": operator,
520
+ "string": string,
521
+ "unicodedata": unicodedata,
522
+ "urlparse": urlparse,
523
+ "quote": quote,
524
+ "unquote": unquote,
525
+ "Path": Path,
526
+ "os": os,
527
+ "sys": sys,
528
+ "pd": pd,
529
+ "np": np,
530
+ "sympy": sympy,
531
+ "requests": requests,
532
+ # Tool functions
533
+ "web_search": web_search,
534
+ "visit_webpage": visit_webpage,
535
+ "grounded_query": grounded_query,
536
+ "read_file": read_file,
537
+ "describe_image": describe_image,
538
+ "final_answer": final_answer,
539
+ # Attachment path hint
540
+ "ATTACHMENT_PATH": GAIA_ATTACHMENT_PATH,
541
+ }
542
+
543
+ # Execute
544
+ try:
545
+ exec(agent_code, exec_globals)
546
+ except SystemExit:
547
+ # final_answer() calls sys.exit(0) — expected
548
+ raise
549
+ except Exception as e:
550
+ import traceback
551
+ print(f"[CodeAgent execution error]\n{traceback.format_exc()}", file=sys.stderr)
552
+ sys.exit(2)
553
+
554
+
555
+ if __name__ == "__main__":
556
+ main()
@@ -0,0 +1,129 @@
1
+ /**
2
+ * GAIA CodeAgent — ADR-138 iter 54 (FINAL design)
3
+ *
4
+ * smolagents-style CodeAgent harness for the GAIA L1 benchmark.
5
+ * NOT the smolagents library — this is the PATTERN implemented natively in ruflo TS.
6
+ *
7
+ * Architecture (HAL replication):
8
+ * Instead of Anthropic native tool_use blocks (JSON → execute → repeat),
9
+ * the agent writes Python code that calls tools as functions. The code is
10
+ * parsed from markdown code blocks, executed in gaia-codeagent-runner.py,
11
+ * and the stdout is fed back as the next user turn. The agent commits its
12
+ * answer by calling final_answer("value") in Python.
13
+ *
14
+ * Why this beats ToolCallingAgent on GAIA (from HAL-DEEP-STUDY.md):
15
+ * - 30% fewer steps for the same task (Python is more expressive than JSON)
16
+ * - Variables persist across steps in the agent's mental model
17
+ * - Complex control flow (loops, try/except) is native
18
+ * - final_answer() is deterministic — no regex extraction fragility
19
+ *
20
+ * Loop algorithm:
21
+ * 1. Build system prompt with tool signatures and GAIA instruction template.
22
+ * 2. Call Anthropic Messages API (text-in / text-out — NO tools array).
23
+ * 3. Parse the response for a ```python ... ``` code block.
24
+ * 4. If code block found: run gaia-codeagent-runner.py subprocess.
25
+ * - Runner pre-defines tool functions (web_search, visit_webpage, etc.)
26
+ * - If final_answer("X") is called in the code: extract X, return result.
27
+ * - Otherwise: feed stdout back as user turn, continue.
28
+ * 5. If no code block: prompt agent to produce one (max 3 retries).
29
+ * 6. If maxTurns exceeded: return timedOut=true.
30
+ * 7. Every planningInterval turns: inject a planning checkpoint.
31
+ *
32
+ * Tool routing (via gaia-codeagent-runner.py):
33
+ * web_search(query) → claude -p with WebSearch (best web coverage)
34
+ * visit_webpage(url) → requests + bs4 HTML extraction
35
+ * grounded_query(query) → Gemini with Google Search grounding (ruflo unique)
36
+ * read_file(path) → Python direct (text/csv/json/xlsx) or subprocess
37
+ * describe_image(path) → claude -p with vision
38
+ * final_answer(x) → writes sentinel JSON and exits runner
39
+ *
40
+ * Key parameters:
41
+ * model: claude-sonnet-4-6 (default; ADR-138 targets Sonnet 4.5+)
42
+ * maxTurns: 20 (HAL uses 200; 20 is cost-controlled for L1)
43
+ * planningInterval: 4 (match HAL's planning_interval=4)
44
+ * maxTokensPerTurn: 4096 (code generation needs more space than ToolCalling)
45
+ *
46
+ * Refs: ADR-138, HAL-DEEP-STUDY.md, smolagents CodeAgent, #2156, iter 54
47
+ */
48
+ import { GaiaQuestion } from './gaia-loader.js';
49
+ import { isAnswerCorrect } from './gaia-agent.js';
50
+ export { isAnswerCorrect };
51
+ export interface CodeAgentResult {
52
+ questionId: string;
53
+ finalAnswer: string | null;
54
+ turns: number;
55
+ toolCallsByName: Record<string, number>;
56
+ totalInputTokens: number;
57
+ totalOutputTokens: number;
58
+ wallMs: number;
59
+ replanCount: number;
60
+ timedOut?: boolean;
61
+ error?: string;
62
+ /** Steps log for debugging — each entry is one turn's code + output. */
63
+ steps?: Array<{
64
+ code: string;
65
+ output: string;
66
+ }>;
67
+ }
68
+ export interface CodeAgentOptions {
69
+ model?: string;
70
+ maxTurns?: number;
71
+ maxTokensPerTurn?: number;
72
+ perTurnTimeoutMs?: number;
73
+ /** Timeout for each Python step execution (default: 30s). */
74
+ perStepTimeoutMs?: number;
75
+ planningInterval?: number;
76
+ apiKey?: string;
77
+ /** If true, include step-by-step code/output log in the result. */
78
+ verbose?: boolean;
79
+ /**
80
+ * Optional tool catalogue override — used by unit tests to inject mock tools.
81
+ * In production (Python runner mode) this is ignored; the runner defines its own tools.
82
+ */
83
+ catalogue?: unknown[];
84
+ }
85
+ /**
86
+ * Extract the first ```python ... ``` code block from assistant output.
87
+ * Returns null if no code block is found.
88
+ *
89
+ * Exported for use in unit tests (gaia-codeagent.smoke.ts T1).
90
+ */
91
+ export declare function extractCodeBlock(text: string): string | null;
92
+ /**
93
+ * Execute a single Python code step via the gaia-codeagent-runner.py subprocess.
94
+ *
95
+ * This is a thin public wrapper around `executeAgentCodeStep` that:
96
+ * - Exposes a clean typed signature for unit tests (gaia-codeagent.smoke.ts T2-T4)
97
+ * - Renames `output` → `observation` to match the smolagents naming convention
98
+ *
99
+ * @param code Python code to execute
100
+ * @param attachmentPath Path to attached file, or null
101
+ * @param timeoutMs Subprocess timeout in ms (default: 30s)
102
+ * @param apiKey Anthropic API key (passed to runner for claude -p tool calls)
103
+ */
104
+ export declare function runCodeAgentStep(code: string, attachmentPath: string | null, timeoutMs?: number, apiKey?: string): {
105
+ observation: string;
106
+ finalAnswer: string | null;
107
+ };
108
+ /**
109
+ * Run a GAIA question through the smolagents-style CodeAgent harness.
110
+ *
111
+ * The agent writes Python code, we execute it with tool stubs, and feed
112
+ * the output back. The loop continues until final_answer() is called
113
+ * or maxTurns is exhausted.
114
+ */
115
+ export declare function runGaiaCodeAgent(question: GaiaQuestion, options?: CodeAgentOptions): Promise<CodeAgentResult>;
116
+ /**
117
+ * Run all 5 SMOKE_FIXTURE questions through the CodeAgent harness.
118
+ * Pass criteria: ≥3/5 correct (60%).
119
+ */
120
+ export declare function runCodeAgentSmokeTest(opts?: {
121
+ verbose?: boolean;
122
+ apiKey?: string;
123
+ model?: string;
124
+ }): Promise<{
125
+ passRate: number;
126
+ passed: number;
127
+ total: number;
128
+ }>;
129
+ //# sourceMappingURL=gaia-codeagent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gaia-codeagent.d.ts","sourceRoot":"","sources":["../../../src/benchmarks/gaia-codeagent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAOH,OAAO,EACL,YAAY,EAEb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAA0B,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAM1E,OAAO,EAAE,eAAe,EAAE,CAAC;AAwD3B,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,gBAAgB,EAAE,MAAM,CAAC;IACzB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wEAAwE;IACxE,KAAK,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACjD;AAED,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,6DAA6D;IAC7D,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mEAAmE;IACnE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,EAAE,CAAC;CACvB;AA0GD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAU5D;AAkHD;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,MAAM,EACZ,cAAc,EAAE,MAAM,GAAG,IAAI,EAC7B,SAAS,SAA8B,EACvC,MAAM,SAAK,GACV;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAIrD;AAkDD;;;;;;GAMG;AACH,wBAAsB,gBAAgB,CACpC,QAAQ,EAAE,YAAY,EACtB,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,eAAe,CAAC,CAsL1B;AA8CD;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,IAAI,GAAE;IAChD,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;CACX,GAAG,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAuDpE"}