-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_tools.py
More file actions
374 lines (342 loc) · 15.6 KB
/
Copy pathread_tools.py
File metadata and controls
374 lines (342 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
"""GitHub READ tools over `gh` — always registered (read-only is the safe default).
Six are ported from protoAgent's tools/github_tools.py (PRs, issues, diffs, CI). Two
new ones (`github_read_file`, `github_repo_contents`) are STUBBED — the team builds
them out (see the TODOs). Each tool takes an `owner/name` repo — or falls back to the
configured default when it's omitted — and degrades to a readable `Error: ...` string
when `gh`/auth is unavailable.
"""
from __future__ import annotations
import json
import re
from langchain_core.tools import tool
from .gh_cli import bad_repo, check_gh_error, run_gh
from .gh_issue import resolve_repo
# Error-relevant lines to surface from a failed CI log (github_run_failure).
_CI_ERR_RE = re.compile(
r"(error|fail|✕|✗|×|not ok|exit code|command not found|exception|traceback|"
r"assertion|timeout|expected .* to|cannot |refused|unauthorized|forbidden|panic|fatal)",
re.IGNORECASE,
)
def get_read_tools(default_repo: str = "") -> list:
"""Build the read tools. ``default_repo`` (``owner/name``) is used whenever a tool's
``repo`` arg is omitted, so an agent with one configured repo needn't repeat it."""
@tool
async def github_get_pr(number: int, repo: str = "") -> str:
"""Fetch a GitHub pull request: title, state, author, body, branch, and changed files.
Args:
repo: Repository as ``owner/name``. Omit to use the agent's configured default repo.
number: PR number.
"""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
rc, out, serr = await run_gh(
[
"pr",
"view",
str(number),
"--repo",
repo,
"--json",
"number,title,state,author,body,additions,deletions,files,url,headRefName,baseRefName",
]
)
if gh_err := check_gh_error(rc, serr):
return gh_err
try:
d = json.loads(out)
except json.JSONDecodeError:
return f"Error: could not parse gh output: {out[:200]}"
files = ", ".join(f.get("path", "?") for f in (d.get("files") or [])[:20])
return (
f"PR #{d.get('number')} [{d.get('state')}] {d.get('title')}\n"
f"branch: {d.get('headRefName', '?')} -> {d.get('baseRefName', '?')}\n"
f"by {(d.get('author') or {}).get('login', '?')} | "
f"+{d.get('additions', 0)}/-{d.get('deletions', 0)} | {d.get('url')}\n"
f"files: {files or '(none)'}\n\n{(d.get('body') or '').strip()[:2000]}"
)
@tool
async def github_get_issue(number: int, repo: str = "") -> str:
"""Fetch a GitHub issue: title, state, author, labels, and body.
Args:
repo: Repository as ``owner/name``. Omit to use the agent's configured default repo.
number: Issue number.
"""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
rc, out, serr = await run_gh(
["issue", "view", str(number), "--repo", repo, "--json", "number,title,state,author,labels,body,url"]
)
if gh_err := check_gh_error(rc, serr):
return gh_err
try:
d = json.loads(out)
except json.JSONDecodeError:
return f"Error: could not parse gh output: {out[:200]}"
labels = ", ".join(lbl.get("name", "") for lbl in (d.get("labels") or []))
return (
f"Issue #{d.get('number')} [{d.get('state')}] {d.get('title')}\n"
f"by {(d.get('author') or {}).get('login', '?')} | labels: {labels or '(none)'} | "
f"{d.get('url')}\n\n{(d.get('body') or '').strip()[:2000]}"
)
@tool
async def github_list_issues(repo: str = "", state: str = "open", limit: int = 20) -> str:
"""List GitHub issues for a repo.
Args:
repo: Repository as ``owner/name``. Omit to use the agent's configured default repo.
state: ``open`` | ``closed`` | ``all`` (default ``open``).
limit: Max issues to return (1-50, default 20).
"""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
if state not in ("open", "closed", "all"):
return f"Error: state must be open|closed|all (got {state!r})."
limit = max(1, min(int(limit), 50))
rc, out, serr = await run_gh(
[
"issue",
"list",
"--repo",
repo,
"--state",
state,
"--limit",
str(limit),
"--json",
"number,title,state,labels",
]
)
if gh_err := check_gh_error(rc, serr):
return gh_err
try:
items = json.loads(out)
except json.JSONDecodeError:
return f"Error: could not parse gh output: {out[:200]}"
if not items:
return f"No {state} issues in {repo}."
lines = [f"{len(items)} {state} issue(s) in {repo}:"]
for it in items:
labels = ",".join(lbl.get("name", "") for lbl in (it.get("labels") or []))
lines.append(
f" #{it.get('number')} [{it.get('state')}] {it.get('title')}" + (f" ({labels})" if labels else "")
)
return "\n".join(lines)
@tool
async def github_get_commit_diff(ref: str, repo: str = "", max_chars: int = 8000) -> str:
"""Fetch a commit's metadata + unified diff.
Args:
repo: Repository as ``owner/name``. Omit to use the agent's configured default repo.
ref: Commit SHA (or ref) to inspect.
max_chars: Truncate the diff at this many characters (default 8000).
"""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
rc, out, serr = await run_gh(
["api", f"repos/{repo}/commits/{ref}", "-H", "Accept: application/vnd.github.diff"]
)
if gh_err := check_gh_error(rc, serr):
return gh_err
diff = out.strip()
if not diff:
return f"No diff for {repo}@{ref} (empty or merge commit)."
if len(diff) > max_chars:
diff = diff[:max_chars] + f"\n… (truncated at {max_chars} chars)"
return f"Commit {repo}@{ref}:\n\n{diff}"
@tool
async def github_pr_diff(number: int, repo: str = "", max_chars: int = 12000) -> str:
"""Fetch a pull request's full unified diff — for reviewing the change itself.
Args:
repo: Repository as ``owner/name``. Omit to use the agent's configured default repo.
number: PR number.
max_chars: Truncate the diff at this many characters (default 12000).
"""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
rc, out, serr = await run_gh(["pr", "diff", str(number), "--repo", repo])
if gh_err := check_gh_error(rc, serr):
return gh_err
diff = out.strip()
if not diff:
return f"No diff for {repo}#{number} (empty PR or diff unavailable)."
if len(diff) > max_chars:
diff = diff[:max_chars] + f"\n… (truncated at {max_chars} chars)"
return f"PR {repo}#{number} diff:\n\n{diff}"
@tool
async def github_ci_runs(repo: str = "", branch: str = "", limit: int = 15) -> str:
"""List recent GitHub Actions runs for a repo — for CI triage.
Args:
repo: Repository as ``owner/name``. Omit to use the agent's configured default repo.
branch: Optional branch filter (e.g. ``main``).
limit: Max runs to return (capped at 50).
Feed a failing run's id to ``github_run_failure`` to see why it failed.
"""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
args = [
"run",
"list",
"--repo",
repo,
"--limit",
str(max(1, min(int(limit), 50))),
"--json",
"databaseId,name,status,conclusion,headBranch,event,createdAt,url",
]
if branch.strip():
args += ["--branch", branch.strip()]
rc, out, serr = await run_gh(args)
if gh_err := check_gh_error(rc, serr):
return gh_err
try:
runs = json.loads(out)
except json.JSONDecodeError:
return f"Error: could not parse gh output: {out[:200]}"
if not runs:
return f"No recent runs for {repo}" + (f" on {branch}" if branch.strip() else "")
lines = [
f"#{r.get('databaseId')} [{r.get('conclusion') or r.get('status')}] "
f"{r.get('name')} ({r.get('headBranch')} · {r.get('event')}) — {r.get('url')}"
for r in runs
]
return f"{repo} — {len(runs)} recent run(s):\n" + "\n".join(lines)
@tool
async def github_run_failure(run_id: int, repo: str = "", max_lines: int = 40) -> str:
"""Explain why a GitHub Actions run failed — the error lines from its failed steps.
Args:
repo: Repository as ``owner/name``. Omit to use the agent's configured default repo.
run_id: The run id (``databaseId`` from ``github_ci_runs``).
max_lines: Cap on error lines returned (capped at 80).
"""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
cap = max(5, min(int(max_lines), 80))
rc, out, serr = await run_gh(["run", "view", str(run_id), "--repo", repo, "--log-failed"], timeout=60)
if gh_err := check_gh_error(rc, serr):
return gh_err
raw = [ln.rstrip() for ln in out.splitlines() if ln.strip()]
seen: set = set()
uniq: list[str] = []
for ln in raw:
msg = ln.split("\t")[-1]
if _CI_ERR_RE.search(msg):
key = msg[:120]
if key not in seen:
seen.add(key)
uniq.append(msg[:200])
picked = uniq[-cap:] if uniq else [ln.split("\t")[-1][:200] for ln in raw[-cap:]]
if not picked:
return f"Run {run_id} in {repo}: no failed-step log lines (run may not have failed, or its logs expired)."
return f"{repo} run {run_id} — failure log ({len(picked)} line(s)):\n" + "\n".join(picked)
# ── NEW read tools — STUBBED. Build these out (this is what lets an agent research
# any repo over `gh` without registering an fs project per repo). ────────────────
@tool
async def github_read_file(path: str, repo: str = "", ref: str = "") -> str:
"""Read a single file's contents from a GitHub repo.
Args:
repo: Repository as ``owner/name``. Omit to use the agent's configured default repo.
path: Path to the file within the repo (e.g. ``docs/guide.md``).
ref: Optional branch / tag / SHA (default: the repo's default branch).
TODO(team): implement via `gh api repos/{repo}/contents/{path}?ref={ref}` with
`Accept: application/vnd.github.raw` (returns the raw file body), or
`gh api .../contents/... --jq .content | base64 -d`. Validate repo with
bad_repo(); cap the returned size; return a readable Error on failure.
"""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
args = ["api", f"repos/{repo}/contents/{path}", "-H", "Accept: application/vnd.github.raw+json"]
if ref.strip():
args += ["-f", f"ref={ref}"]
rc, out, serr = await run_gh(args)
if gh_err := check_gh_error(rc, serr):
return gh_err
if len(out) > 20000:
out = out[:20000] + "\n… (truncated at 20000 chars)"
return out
@tool
async def github_path_exists(path: str, repo: str = "", ref: str = "") -> str:
"""Check whether a path exists in a GitHub repo — the grounding probe for
review claims about external references.
A diff is often only correct if something OUTSIDE it exists (a cross-repo
`COPY --from` path, a workspace package, an action ref). The answer is
authoritative: EXISTS means the assumption holds (don't invent a problem
around it); MISSING means the dependency is really absent (that's the
finding). A tool error means UNVERIFIED — report a Gap, never a severity.
Args:
repo: Repository as ``owner/name`` — may be a DIFFERENT repo than the
PR under review (that is the point). Omit for the default repo.
path: Repo-relative path to check (file or directory).
ref: Optional branch / tag / SHA (default: the repo's default branch).
"""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
if not path.strip():
return "Error: `path` is empty."
clean = path.strip().strip("/")
args = ["api", f"repos/{repo}/contents/{clean}"]
if ref.strip():
args += ["-f", f"ref={ref.strip()}"]
rc, out, serr = await run_gh(args)
if rc == 0:
return f"EXISTS: {repo}/{clean}" + (f" @ {ref.strip()}" if ref.strip() else "")
blob = (serr or out or "").lower()
if "404" in blob or "not found" in blob:
return (
f"MISSING: {repo}/{clean}"
+ (f" @ {ref.strip()}" if ref.strip() else "")
+ " — the path does not exist."
)
return (
check_gh_error(rc, serr)
or f"Error (gh exit {rc}): could not verify {repo}/{clean} — treat as UNVERIFIED (a Gap, not a finding)."
)
@tool
async def github_repo_contents(repo: str = "", path: str = "", ref: str = "") -> str:
"""List the contents (files + dirs) of a path in a GitHub repo.
Args:
repo: Repository as ``owner/name``. Omit to use the agent's configured default repo.
path: Directory path within the repo (default: repo root).
ref: Optional branch / tag / SHA (default: the repo's default branch).
"""
repo = resolve_repo(repo, default_repo) or ""
if err := bad_repo(repo):
return err
args = ["api", f"repos/{repo}/contents/{path}" if path else f"repos/{repo}/contents"]
if ref.strip():
args += ["-f", f"ref={ref}"]
rc, out, serr = await run_gh(args)
if gh_err := check_gh_error(rc, serr):
return gh_err
try:
items = json.loads(out)
except json.JSONDecodeError:
return f"Error: could not parse gh output: {out[:200]}"
if not items:
return f"No contents in {repo}/{path or '.'}."
type_map = {"file": "FILE", "dir": "DIR ", "symlink": "LINK", "submodule": "SUB "}
lines = [f"{repo}/{path or '.'} — {len(items)} item(s):"]
for entry in items:
etype = entry.get("type", "")
t = type_map.get(etype, (etype or "?").upper())[:4]
size = "0" if etype == "dir" else str(entry.get("size", 0))
lines.append(f"{t:4s} {size:>8s} {entry.get('name', '?')} ({entry.get('path', '')})")
return "\n".join(lines)
return [
github_get_pr,
github_get_issue,
github_list_issues,
github_get_commit_diff,
github_pr_diff,
github_path_exists,
github_ci_runs,
github_run_failure,
github_read_file,
github_repo_contents,
]