polyctl 0.7.0__py3-none-any.whl

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 (99) hide show
  1. polyctl/__init__.py +7 -0
  2. polyctl/__main__.py +5 -0
  3. polyctl/a2a.py +226 -0
  4. polyctl/a2a_mcp.py +546 -0
  5. polyctl/acp.py +417 -0
  6. polyctl/adapters/README.md +101 -0
  7. polyctl/adapters/aider.json +32 -0
  8. polyctl/adapters/amazon-q.json +15 -0
  9. polyctl/adapters/amp.json +16 -0
  10. polyctl/adapters/antigravity.json +120 -0
  11. polyctl/adapters/claude-code.json +229 -0
  12. polyctl/adapters/cloud-generic.json +57 -0
  13. polyctl/adapters/codex.json +47 -0
  14. polyctl/adapters/command-code.json +45 -0
  15. polyctl/adapters/copilot.json +17 -0
  16. polyctl/adapters/cursor-agent.json +29 -0
  17. polyctl/adapters/deepseek.json +13 -0
  18. polyctl/adapters/droid.json +34 -0
  19. polyctl/adapters/gemini.json +30 -0
  20. polyctl/adapters/grok.json +22 -0
  21. polyctl/adapters/hermes.json +34 -0
  22. polyctl/adapters/kilocode.json +30 -0
  23. polyctl/adapters/kimi.json +23 -0
  24. polyctl/adapters/kiro.json +332 -0
  25. polyctl/adapters/ollama.json +29 -0
  26. polyctl/adapters/omp.json +34 -0
  27. polyctl/adapters/openai-api.json +68 -0
  28. polyctl/adapters/opencode.json +162 -0
  29. polyctl/adapters/pi.json +24 -0
  30. polyctl/adapters/pr-agent.json +54 -0
  31. polyctl/adapters/profiles.json +9 -0
  32. polyctl/adapters/qoder.json +163 -0
  33. polyctl/adapters/qwen.json +27 -0
  34. polyctl/adapters/reasonix.json +25 -0
  35. polyctl/adapters/rewriters/rtk.json +24 -0
  36. polyctl/adapters/trae.json +31 -0
  37. polyctl/adapters/vendors.json +42 -0
  38. polyctl/adapters/warp.json +88 -0
  39. polyctl/allowlist.py +1756 -0
  40. polyctl/api_review.py +920 -0
  41. polyctl/cli.py +835 -0
  42. polyctl/conformance_harness.py +9 -0
  43. polyctl/demo.py +503 -0
  44. polyctl/drivers.py +146 -0
  45. polyctl/email.py +160 -0
  46. polyctl/features.py +98 -0
  47. polyctl/journal.py +144 -0
  48. polyctl/language.py +945 -0
  49. polyctl/lib.py +1296 -0
  50. polyctl/matrix.py +660 -0
  51. polyctl/mcp.py +1362 -0
  52. polyctl/ntfy.py +169 -0
  53. polyctl/outbound.py +39 -0
  54. polyctl/parts/__init__.py +5 -0
  55. polyctl/parts/cli_authority.py +2615 -0
  56. polyctl/parts/cli_channels.py +1325 -0
  57. polyctl/parts/cli_checks.py +2293 -0
  58. polyctl/parts/cli_completion.py +686 -0
  59. polyctl/parts/cli_evidence.py +141 -0
  60. polyctl/parts/cli_gain.py +375 -0
  61. polyctl/parts/cli_harness.py +392 -0
  62. polyctl/parts/cli_hooks.py +1816 -0
  63. polyctl/parts/cli_install.py +638 -0
  64. polyctl/parts/cli_lanes.py +106 -0
  65. polyctl/parts/cli_maintenance.py +2536 -0
  66. polyctl/parts/cli_next.py +248 -0
  67. polyctl/parts/cli_pr.py +53 -0
  68. polyctl/parts/cli_project.py +2857 -0
  69. polyctl/parts/cli_review.py +5158 -0
  70. polyctl/parts/cli_status.py +898 -0
  71. polyctl/parts/lib_adapters.py +2933 -0
  72. polyctl/parts/lib_alarms.py +2106 -0
  73. polyctl/parts/lib_events.py +224 -0
  74. polyctl/parts/lib_evidence.py +412 -0
  75. polyctl/parts/lib_gates.py +2099 -0
  76. polyctl/parts/lib_lanes.py +829 -0
  77. polyctl/parts/lib_mail.py +1541 -0
  78. polyctl/parts/lib_next.py +652 -0
  79. polyctl/parts/lib_pr.py +331 -0
  80. polyctl/parts/lib_slices.py +3337 -0
  81. polyctl/parts/lib_state.py +2415 -0
  82. polyctl/parts/lib_transcript.py +4118 -0
  83. polyctl/pressure.py +325 -0
  84. polyctl/prices.json +47 -0
  85. polyctl/procs.py +1194 -0
  86. polyctl/settings.py +505 -0
  87. polyctl/skill/SKILL.md +365 -0
  88. polyctl/skillkit.py +503 -0
  89. polyctl/storage.py +2055 -0
  90. polyctl/telegram.py +327 -0
  91. polyctl/tiers.py +123 -0
  92. polyctl/verdicts.py +41 -0
  93. polyctl/watchdog.py +3887 -0
  94. polyctl/web.py +337 -0
  95. polyctl-0.7.0.dist-info/METADATA +235 -0
  96. polyctl-0.7.0.dist-info/RECORD +99 -0
  97. polyctl-0.7.0.dist-info/WHEEL +4 -0
  98. polyctl-0.7.0.dist-info/entry_points.txt +5 -0
  99. polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
polyctl/api_review.py ADDED
@@ -0,0 +1,920 @@
1
+ """polyctl-api-review: an answer from an OpenAI-compatible chat API, run by polyctl as a tool reviewer (API-REVIEWER).
2
+
3
+ polyctl hands a tool reviewer the review prompt, which carries the candidate's diff, and a file to answer
4
+ in (docs/adapters.md, "A reviewer can be a tool polyctl runs"). Without `--tree`, this client asks a
5
+ provider's `/chat/completions` once, with the prompt as the only message and no tools, and writes the
6
+ answer it gets. With `--tree DIR`, it offers four read-only function tools (`read`, `grep`, `glob`,
7
+ `list`) confined to the unpacked candidate tree at `DIR`, answers tool calls within per-answer and
8
+ per-turn bounds (keeping `tools` on every request of the turn and sending `tool_choice: "none"` once
9
+ a bound is reached), and writes the final verdict and the tool usage (`rounds`, `read_bytes`) beside
10
+ it (API-REVIEWER-TOOLS, API-REVIEWER-TOOLS-3).
11
+
12
+ The provider is the machine's. `review.api_providers` names each by a word, with its base URL and
13
+ the environment variable that holds its key; the model is `<provider>/<model>`. The key is read
14
+ from that variable at the moment it is sent, sent to that URL alone - over HTTPS, or to this
15
+ machine with no proxy between - and never carried through a redirect. It is never written anywhere.
16
+ """
17
+ import argparse
18
+ import json
19
+ import ntpath
20
+ import os
21
+ import re
22
+ import stat
23
+ import sys
24
+ import time
25
+ import urllib.error
26
+ import urllib.parse
27
+ import urllib.request
28
+
29
+ from . import __version__, lib as A, outbound
30
+
31
+ UTF8 = "utf-8"
32
+ USAGE, FAILED = 2, 1
33
+ LOOPBACK = ("127.0.0.1", "localhost", "::1")
34
+
35
+ TOOL_MAX_BYTES = 32_768
36
+ TOOL_MAX_LINES = 2_000
37
+ READ_MAX_BYTES = 131_072
38
+ READ_MAX_LINES = 2_000
39
+ TOOL_MAX_MATCHES = 100
40
+ GREP_MAX_FILE_BYTES = 524_288
41
+ TURN_MAX_ROUNDS = 24
42
+ TURN_MAX_READ_BYTES = 2_097_152
43
+ TURN_MAX_SECONDS = 900.0
44
+
45
+ TOOLS = [
46
+ {
47
+ "type": "function",
48
+ "function": {
49
+ "name": "read",
50
+ "description": ("Read one file in the candidate's unpacked tree (at most 2,000 lines or 128 KiB per call; "
51
+ "pass first_line and line_count to page, and each partial read says how much is left). "
52
+ "Every path is relative to the tree root (do not prefix with candidate/)."),
53
+ "parameters": {
54
+ "type": "object",
55
+ "properties": {
56
+ "path": {"type": "string", "description": "Relative path of the file inside the tree."},
57
+ "first_line": {"type": "integer", "description": "1-based first line to read (default 1)."},
58
+ "line_count": {"type": "integer", "description": "Maximum number of lines to read (up to 2,000)."},
59
+ },
60
+ "required": ["path"],
61
+ "additionalProperties": False,
62
+ },
63
+ },
64
+ },
65
+ {
66
+ "type": "function",
67
+ "function": {
68
+ "name": "grep",
69
+ "description": ("Search files in the candidate's unpacked tree for a regular expression "
70
+ "(at most 100 matches and 32 KiB per call; scans up to 512 KiB per file and charges "
71
+ "only returned matches to the turn read budget)."),
72
+ "parameters": {
73
+ "type": "object",
74
+ "properties": {
75
+ "pattern": {"type": "string", "description": "Regular expression to match against each line."},
76
+ "path": {"type": "string", "description": "Optional relative file or directory path to search."},
77
+ "glob": {"type": "string", "description": "Optional glob pattern filtering file paths."},
78
+ },
79
+ "required": ["pattern"],
80
+ "additionalProperties": False,
81
+ },
82
+ },
83
+ },
84
+ {
85
+ "type": "function",
86
+ "function": {
87
+ "name": "glob",
88
+ "description": ("Find files in the candidate's unpacked tree matching a glob pattern "
89
+ "(at most 100 matches and 32 KiB per call)."),
90
+ "parameters": {
91
+ "type": "object",
92
+ "properties": {
93
+ "pattern": {"type": "string", "description": "Relative glob pattern inside the tree."},
94
+ },
95
+ "required": ["pattern"],
96
+ "additionalProperties": False,
97
+ },
98
+ },
99
+ },
100
+ {
101
+ "type": "function",
102
+ "function": {
103
+ "name": "list",
104
+ "description": ("List one directory in the candidate's unpacked tree "
105
+ "(at most 100 entries and 32 KiB per call)."),
106
+ "parameters": {
107
+ "type": "object",
108
+ "properties": {
109
+ "path": {"type": "string", "description": "Relative directory path inside the tree ('.' for root)."},
110
+ },
111
+ "additionalProperties": False,
112
+ },
113
+ },
114
+ },
115
+ ]
116
+
117
+
118
+ def providers(entries):
119
+ """{word: (base URL, key variable)} from `review.api_providers`, or ValueError naming the entry that is not one.
120
+
121
+ `/chat/completions` is put after the base URL. Behind a `?` or a `#` it landed in the query or the fragment, and
122
+ the key went to the base URL's own path; and a user or a password in the URL is a credential written in a setting,
123
+ which urllib read as a port and printed in the error that refused it (HUNT-LEADS-SEC). Neither is taken, and
124
+ neither refusal repeats the URL, whose query may hold a key too.
125
+ """
126
+ table = {}
127
+ for entry in entries or []:
128
+ words = str(entry).split()
129
+ if len(words) != 3:
130
+ raise ValueError(f"{entry!r} in review.api_providers is not a word, a base URL and the environment "
131
+ "variable that holds its key")
132
+ name, url, variable = words
133
+ parsed = urllib.parse.urlparse(url)
134
+ if "@" in parsed.netloc:
135
+ raise ValueError(f"{name}'s base URL names a user or a password: write it without them, since the key is "
136
+ "read from its environment variable alone")
137
+ if "?" in url or "#" in url:
138
+ raise ValueError(f"{name}'s base URL holds a query or a fragment, where /chat/completions would land: "
139
+ "write the URL the API's paths start from, with neither")
140
+ if not (parsed.scheme == "https" or parsed.scheme == "http" and parsed.hostname in LOOPBACK) \
141
+ or not parsed.hostname:
142
+ raise ValueError(f"{name}'s base URL {url} is not https: its key would leave this machine unprotected")
143
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", variable):
144
+ raise ValueError(f"{name}'s key is named {variable!r}, which is no environment variable")
145
+ table[name] = (url.rstrip("/"), variable)
146
+ return table
147
+
148
+
149
+ def _scrub(text, key):
150
+ """`text` with the key taken out, as written and as Python escapes it in a repr (API-REVIEWER-3).
151
+
152
+ It is put in place by a mark that does not hold the key: a key spelled `<key>` was replaced by itself
153
+ (API-REVIEWER-4).
154
+ """
155
+ forms = {key, repr(key)[1:-1], key.encode("unicode_escape").decode("ascii")} - {""}
156
+ mark = next(mark for mark in ("<key>", "<redacted>", "***", "#") if not any(form in mark for form in forms))
157
+ for form in sorted(forms, key=len, reverse=True):
158
+ text = text.replace(form, mark)
159
+ return text
160
+
161
+
162
+ def _content(answer):
163
+ """The text of the first choice's message: a string, or the text parts of a list of them."""
164
+ try:
165
+ content = answer["choices"][0]["message"]["content"]
166
+ except (KeyError, IndexError, TypeError):
167
+ return ""
168
+ if isinstance(content, list):
169
+ content = "".join(part.get("text", "") for part in content if isinstance(part, dict))
170
+ return content if isinstance(content, str) else ""
171
+
172
+
173
+ def _no_answer(provider, model, answer):
174
+ """Why an answer holds no text (API-REVIEWER-5).
175
+
176
+ A reasoning model that spends the whole answer its provider allows on reasoning stops before it writes a verdict:
177
+ EVREN allows 16,384 tokens, and on a review prompt of about 28 KB GLM-5.3, DeepSeek V4.1 Flash, Qwen3.8 Flash and
178
+ MiMo V2.6 Pro each spent all of them so on 2026-10-06. "Gave no answer" sent a person looking for a fault at the
179
+ provider. Only polyctl's own words and a whole number from the answer are said: the provider's text is not printed. They
180
+ say thinking, since a string in polyctl's core never names a field of a harness's transcript (API-REVIEWER-6).
181
+ """
182
+ try:
183
+ choice = answer["choices"][0]
184
+ finish = choice.get("finish_reason")
185
+ details = (answer.get("usage") or {}).get("completion_tokens_details")
186
+ except (KeyError, IndexError, TypeError, AttributeError):
187
+ return f"{provider} gave no answer for {model}"
188
+ if finish != "length":
189
+ return f"{provider} gave no answer for {model}"
190
+ spent = details.get("reasoning_tokens") if isinstance(details, dict) else None
191
+ spent = f" ({spent} tokens of thinking)" if isinstance(spent, int) and not isinstance(spent, bool) else ""
192
+ return (f"{model} on {provider} spent the whole answer it may give{spent} before it wrote one; a smaller "
193
+ "candidate, or a model that reasons less, gives a verdict")
194
+
195
+
196
+ def _check_relative_syntax(raw_path):
197
+ """Refusal reason when `raw_path` is absolute or climbs above the root with `..`, else None."""
198
+ if not isinstance(raw_path, str) or "\x00" in raw_path:
199
+ return "refused: invalid path"
200
+ cleaned = raw_path.strip() or "."
201
+ if os.path.isabs(cleaned) or cleaned.startswith(("/", "\\", "~")) or ntpath.splitdrive(cleaned)[0]:
202
+ return "refused: absolute path is outside the candidate tree"
203
+ depth = 0
204
+ for part in cleaned.replace("\\", "/").split("/"):
205
+ if part in ("", "."):
206
+ continue
207
+ if part == "..":
208
+ if depth == 0:
209
+ return "refused: '..' leaves the candidate tree"
210
+ depth -= 1
211
+ else:
212
+ depth += 1
213
+ return None
214
+
215
+
216
+ def _link_stays_in_tree(link_path, real_root, config_names):
217
+ """(resolved_path, None) when `link_path` resolves inside `real_root` and outside harness config, else (None, why)."""
218
+ try:
219
+ target = os.readlink(link_path)
220
+ except OSError:
221
+ return None, "refused: symbolic link cannot be read"
222
+ if os.path.isabs(target) or target.startswith(("/", "\\", "~")) or ntpath.splitdrive(target)[0]:
223
+ return None, "refused: symbolic link leads outside the candidate tree"
224
+ step_target = os.path.normpath(os.path.join(os.path.dirname(link_path), target))
225
+ real_target = os.path.realpath(link_path)
226
+ if not (A._within(step_target, real_root) and A._within(real_target, real_root)):
227
+ return None, "refused: symbolic link leads outside the candidate tree"
228
+ rel_target = os.path.relpath(real_target, real_root).replace(os.sep, "/")
229
+ if rel_target != "." and A.project_config_member(rel_target, config_names) is not None:
230
+ return None, "refused: harness configuration is withheld from reviewers"
231
+ return real_target, None
232
+
233
+
234
+ def _resolve_in_tree(tree_root, raw_path, config_names):
235
+ """Resolve `raw_path` inside `tree_root`: (real_path, rel_path, None), or (None, None, refusal)."""
236
+ if not tree_root or os.path.islink(os.path.abspath(tree_root)) or not os.path.isdir(tree_root):
237
+ return None, None, "refused: candidate tree is not available"
238
+ real_root = os.path.realpath(tree_root)
239
+ refused = _check_relative_syntax(raw_path)
240
+ if refused:
241
+ return None, None, refused
242
+ cleaned = (raw_path or "").strip() or "."
243
+ if cleaned != "." and not A._lands_inside(real_root, cleaned):
244
+ return None, None, "refused: '..' leaves the candidate tree"
245
+ cur = real_root
246
+ for part in cleaned.replace("\\", "/").split("/"):
247
+ if part in ("", "."):
248
+ continue
249
+ if part == "..":
250
+ cur = os.path.dirname(cur)
251
+ if not A._within(cur, real_root):
252
+ return None, None, "refused: '..' leaves the candidate tree"
253
+ continue
254
+ cur = os.path.join(cur, part)
255
+ rel_cur = os.path.relpath(cur, real_root).replace(os.sep, "/")
256
+ if rel_cur != "." and A.project_config_member(rel_cur, config_names) is not None:
257
+ return None, None, "refused: harness configuration is withheld from reviewers"
258
+ if os.path.islink(cur):
259
+ cur, link_refused = _link_stays_in_tree(cur, real_root, config_names)
260
+ if link_refused:
261
+ return None, None, link_refused
262
+ final_real = os.path.realpath(cur)
263
+ if not A._within(final_real, real_root):
264
+ return None, None, "refused: path resolves outside the candidate tree"
265
+ final_rel = os.path.relpath(final_real, real_root).replace(os.sep, "/")
266
+ if final_rel != "." and A.project_config_member(final_rel, config_names) is not None:
267
+ return None, None, "refused: harness configuration is withheld from reviewers"
268
+ return final_real, ("" if final_rel == "." else final_rel), None
269
+
270
+
271
+ def _glob_regex(pattern):
272
+ parts, i, n = ["^"], 0, len(pattern)
273
+ while i < n:
274
+ if pattern[i:i + 3] == "**/":
275
+ parts.append("(?:.+/)?")
276
+ i += 3
277
+ elif pattern[i:i + 2] == "**":
278
+ parts.append(".*")
279
+ i += 2
280
+ elif pattern[i] == "*":
281
+ parts.append("[^/]*")
282
+ i += 1
283
+ elif pattern[i] == "?":
284
+ parts.append("[^/]")
285
+ i += 1
286
+ elif pattern[i] == "[":
287
+ j = pattern.find("]", i + 1)
288
+ if j < 0:
289
+ parts.append(re.escape("["))
290
+ i += 1
291
+ else:
292
+ inner = pattern[i + 1:j].replace("\\", "\\\\")
293
+ if inner.startswith("!"):
294
+ inner = "^" + inner[1:]
295
+ parts.append(f"[{inner}]")
296
+ i = j + 1
297
+ else:
298
+ parts.append(re.escape(pattern[i]))
299
+ i += 1
300
+ parts.append("$")
301
+ return re.compile("".join(parts))
302
+
303
+
304
+ def _iter_tree_files(real_root, start_real, start_rel, config_names, refused_links=None):
305
+ """Yield `(real_path, rel_path)` for regular files under `start_real`, confined to `real_root`."""
306
+ visited = set()
307
+ try:
308
+ st0 = os.stat(start_real)
309
+ visited.add((st0.st_dev, st0.st_ino))
310
+ except OSError:
311
+ return
312
+
313
+ def walk(cur_real, cur_rel):
314
+ try:
315
+ names = sorted(os.listdir(cur_real))
316
+ except OSError:
317
+ return
318
+ for name in names:
319
+ child_lex = os.path.join(cur_real, name)
320
+ child_rel = f"{cur_rel}/{name}" if cur_rel else name
321
+ if A.project_config_member(child_rel, config_names) is not None:
322
+ continue
323
+ if os.path.islink(child_lex):
324
+ child_real, link_refused = _link_stays_in_tree(child_lex, real_root, config_names)
325
+ if link_refused:
326
+ if refused_links is not None and "outside" in link_refused:
327
+ refused_links.append((child_rel, link_refused))
328
+ continue
329
+ else:
330
+ child_real = os.path.realpath(child_lex)
331
+ if not A._within(child_real, real_root):
332
+ continue
333
+ try:
334
+ st = os.stat(child_real)
335
+ except OSError:
336
+ continue
337
+ if stat.S_ISDIR(st.st_mode):
338
+ key = (st.st_dev, st.st_ino)
339
+ if key in visited:
340
+ continue
341
+ visited.add(key)
342
+ yield from walk(child_real, child_rel)
343
+ elif stat.S_ISREG(st.st_mode):
344
+ yield child_real, child_rel
345
+
346
+ yield from walk(start_real, start_rel)
347
+
348
+
349
+ def _read_regular_bytes(real_path, max_bytes):
350
+ """Read up to `max_bytes + 1` bytes from a regular file without blocking on special files."""
351
+ flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
352
+ try:
353
+ fd = os.open(real_path, flags)
354
+ except FileNotFoundError:
355
+ return None, "error: file not found"
356
+ except IsADirectoryError:
357
+ return None, "error: path is a directory"
358
+ except OSError as exc:
359
+ return None, f"error: could not open file ({type(exc).__name__})"
360
+ try:
361
+ mode = os.fstat(fd).st_mode
362
+ if stat.S_ISDIR(mode):
363
+ return None, "error: path is a directory"
364
+ if not stat.S_ISREG(mode):
365
+ return None, "refused: path is not a regular file"
366
+ chunks, total = [], 0
367
+ with os.fdopen(fd, "rb") as fh:
368
+ fd = None
369
+ while total <= max_bytes:
370
+ chunk = fh.read(min(65536, max_bytes + 1 - total))
371
+ if not chunk:
372
+ break
373
+ chunks.append(chunk)
374
+ total += len(chunk)
375
+ return b"".join(chunks), None
376
+ except OSError as exc:
377
+ return None, f"error: could not read file ({type(exc).__name__})"
378
+ finally:
379
+ if fd is not None:
380
+ try:
381
+ os.close(fd)
382
+ except OSError:
383
+ pass
384
+
385
+
386
+ def _read_regular_window(real_path, first_line, capped_lines):
387
+ """Read `selected` lines (`first_line`..`first_line + capped_lines - 1`), `total_lines`, `total_bytes` and
388
+ `prefix_bytes` from a regular file without blocking on special files or cutting large files short at 2 MiB
389
+ (API-REVIEWER-TOOLS-3)."""
390
+ flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
391
+ try:
392
+ fd = os.open(real_path, flags)
393
+ except FileNotFoundError:
394
+ return None, "error: file not found"
395
+ except IsADirectoryError:
396
+ return None, "error: path is a directory"
397
+ except OSError as exc:
398
+ return None, f"error: could not open file ({type(exc).__name__})"
399
+ try:
400
+ mode = os.fstat(fd).st_mode
401
+ if stat.S_ISDIR(mode):
402
+ return None, "error: path is a directory"
403
+ if not stat.S_ISREG(mode):
404
+ return None, "refused: path is not a regular file"
405
+ selected = []
406
+ total_lines = 0
407
+ total_bytes = 0
408
+ prefix_bytes = 0
409
+ end_line = first_line + capped_lines - 1
410
+ with os.fdopen(fd, "rb") as fh:
411
+ fd = None
412
+ for raw_line in fh:
413
+ line_text = raw_line.decode(UTF8, "replace")
414
+ parts = line_text.splitlines(keepends=True) or [line_text]
415
+ for part in parts:
416
+ total_lines += 1
417
+ part_bytes = len(part.encode(UTF8, "replace"))
418
+ total_bytes += part_bytes
419
+ if total_lines < first_line:
420
+ prefix_bytes += part_bytes
421
+ elif total_lines <= end_line:
422
+ selected.append(part)
423
+ return (selected, total_lines, total_bytes, prefix_bytes), None
424
+ except OSError as exc:
425
+ return None, f"error: could not read file ({type(exc).__name__})"
426
+ finally:
427
+ if fd is not None:
428
+ try:
429
+ os.close(fd)
430
+ except OSError:
431
+ pass
432
+
433
+
434
+ def _cap_answer_bytes(text, limit=TOOL_MAX_BYTES):
435
+ encoded = text.encode(UTF8, "replace")
436
+ if len(encoded) <= limit:
437
+ return text
438
+ suffix = f"\n... (truncated at {limit} bytes)"
439
+ keep = max(0, limit - len(suffix.encode(UTF8)))
440
+ return encoded[:keep].decode(UTF8, "ignore") + suffix
441
+
442
+
443
+ def _tool_note(turn_seconds=None):
444
+ """The prompt note that tells the model about the review tools and their per-answer and per-turn bounds
445
+ (API-REVIEWER-TOOLS-3)."""
446
+ seconds = TURN_MAX_SECONDS if turn_seconds is None else turn_seconds
447
+ return (f"--- REVIEW TOOLS: you have four read-only function tools (`read`, `grep`, `glob`, `list`) over the "
448
+ f"unpacked candidate tree. Every path is relative to the tree root (do not prefix with `candidate/`). "
449
+ f"Bounds: `read` returns at most a window of {READ_MAX_LINES} lines or {READ_MAX_BYTES} bytes "
450
+ f"({READ_MAX_BYTES // 1024} KiB) per call, with the `first_line` and `line_count` to page with and how much "
451
+ f"of the file is left; `grep`, `glob` and `list` return at most {TOOL_MAX_MATCHES} matches/entries and "
452
+ f"{TOOL_MAX_BYTES} bytes ({TOOL_MAX_BYTES // 1024} KiB) per call (`grep` scans up to "
453
+ f"{GREP_MAX_FILE_BYTES} bytes per file and charges only its returned matches to the turn read budget); "
454
+ f"the turn allows at most {TURN_MAX_ROUNDS} tool rounds, {TURN_MAX_READ_BYTES} bytes "
455
+ f"({TURN_MAX_READ_BYTES // (1024 * 1024)} MiB) total read, and {seconds:g}s "
456
+ f"wall time, after which `tool_choice` is `\"none\"` and you must write your final review verdict. ---")
457
+
458
+
459
+ def _tool_read(state, args):
460
+ real_path, _, refused = _resolve_in_tree(state["tree"], args.get("path"), state["config_names"])
461
+ if refused:
462
+ return refused
463
+ max_lines = READ_MAX_LINES
464
+ max_bytes = READ_MAX_BYTES
465
+ first_line = args.get("first_line", args.get("start_line", 1))
466
+ line_count = args.get("line_count", args.get("limit", max_lines))
467
+ if not isinstance(first_line, int) or isinstance(first_line, bool) or first_line < 1:
468
+ return "error: first_line must be a positive integer"
469
+ if not isinstance(line_count, int) or isinstance(line_count, bool) or line_count < 1:
470
+ return "error: line_count must be a positive integer"
471
+ capped_lines = min(line_count, max_lines)
472
+ line_bound_hit = line_count > max_lines
473
+ remaining = TURN_MAX_READ_BYTES - state["read_bytes"]
474
+ if remaining <= 0:
475
+ state["bound"] = f"total bytes read limit ({TURN_MAX_READ_BYTES} bytes) reached"
476
+ return f"turn bound reached: {state['bound']}; write your review verdict now"
477
+ window, err = _read_regular_window(real_path, first_line, capped_lines)
478
+ if err:
479
+ return err
480
+ selected, total_lines, total_bytes, prefix_bytes = window
481
+ start_idx = first_line - 1
482
+ raw_all = "".join(selected).encode(UTF8, "replace")
483
+ byte_bound_hit = False
484
+ if len(raw_all) > remaining and remaining <= max_bytes:
485
+ raw_selected = raw_all[:remaining]
486
+ state["read_bytes"] += remaining
487
+ state["bound"] = f"total bytes read limit ({TURN_MAX_READ_BYTES} bytes) reached"
488
+ shown_lines = raw_selected.decode(UTF8, "ignore").splitlines()
489
+ else:
490
+ reserve = 180 if max_bytes >= 256 else 0
491
+ body_limit = max(1, max_bytes - reserve)
492
+ kept_raw, shown_lines, raw_total, fmt_total = [], [], 0, 0
493
+ for idx, line in enumerate(selected):
494
+ raw_line = line.encode(UTF8, "replace")
495
+ clean_line = line.rstrip("\r\n")
496
+ fmt_line = f"{first_line + idx}: {clean_line}".encode(UTF8, "replace")
497
+ add_fmt = len(fmt_line) + (1 if shown_lines else 0)
498
+ if raw_total + len(raw_line) > max_bytes or fmt_total + add_fmt > body_limit:
499
+ byte_bound_hit = True
500
+ if not shown_lines:
501
+ prefix = f"{first_line}: ".encode(UTF8)
502
+ take = max(1, min(max_bytes, body_limit - len(prefix)))
503
+ clipped = raw_line[:take]
504
+ kept_raw.append(clipped)
505
+ shown_lines.append(clipped.decode(UTF8, "ignore").rstrip("\r\n"))
506
+ break
507
+ kept_raw.append(raw_line)
508
+ shown_lines.append(clean_line)
509
+ raw_total += len(raw_line)
510
+ fmt_total += add_fmt
511
+ raw_selected = b"".join(kept_raw)
512
+ if len(raw_selected) > remaining:
513
+ raw_selected = raw_selected[:remaining]
514
+ state["read_bytes"] += remaining
515
+ state["bound"] = f"total bytes read limit ({TURN_MAX_READ_BYTES} bytes) reached"
516
+ shown_lines = raw_selected.decode(UTF8, "ignore").splitlines()
517
+ else:
518
+ state["read_bytes"] += len(raw_selected)
519
+ if state["read_bytes"] >= TURN_MAX_READ_BYTES:
520
+ state["bound"] = f"total bytes read limit ({TURN_MAX_READ_BYTES} bytes) reached"
521
+ last_line = first_line + len(shown_lines) - 1 if shown_lines else start_idx
522
+ lines_left = max(0, total_lines - last_line)
523
+ bytes_left = max(0, total_bytes - prefix_bytes - len(raw_selected))
524
+ next_line = last_line + 1
525
+ next_count = min(max_lines, max(1, lines_left))
526
+ if not byte_bound_hit and lines_left > 0 and capped_lines == max_lines:
527
+ line_bound_hit = True
528
+ numbered = "\n".join(f"{first_line + idx}: {line}" for idx, line in enumerate(shown_lines))
529
+ notes = []
530
+ if byte_bound_hit:
531
+ notes.append(f"... (truncated at {max_bytes} bytes; {lines_left} lines / {bytes_left} bytes left; "
532
+ f"page with first_line={next_line}, line_count={next_count})")
533
+ elif line_bound_hit:
534
+ if lines_left > 0:
535
+ notes.append(f"... (truncated at {max_lines} lines; {lines_left} lines / {bytes_left} bytes left; "
536
+ f"page with first_line={next_line}, line_count={next_count})")
537
+ else:
538
+ notes.append(f"... (truncated at {max_lines} lines; 0 lines / 0 bytes left)")
539
+ elif lines_left > 0:
540
+ notes.append(f"... ({lines_left} lines / {bytes_left} bytes left; "
541
+ f"page with first_line={next_line}, line_count={next_count})")
542
+ if state["bound"]:
543
+ notes.append(f"... (turn bound reached: {state['bound']})")
544
+ out = numbered + ("\n" + "\n".join(notes) if notes else "")
545
+ return _cap_answer_bytes(out, max_bytes)
546
+
547
+
548
+ def _tool_list(state, args):
549
+ raw_path = args.get("path", ".")
550
+ if raw_path is None:
551
+ raw_path = "."
552
+ real_path, rel_path, refused = _resolve_in_tree(state["tree"], raw_path, state["config_names"])
553
+ if refused:
554
+ return refused
555
+ if not os.path.isdir(real_path):
556
+ return "error: path is not a directory"
557
+ real_root = os.path.realpath(state["tree"])
558
+ try:
559
+ names = sorted(os.listdir(real_path))
560
+ except OSError as exc:
561
+ return f"error: could not list directory ({type(exc).__name__})"
562
+ entries = []
563
+ for name in names:
564
+ child_rel = f"{rel_path}/{name}" if rel_path else name
565
+ if A.project_config_member(child_rel, state["config_names"]) is not None:
566
+ continue
567
+ child_lex = os.path.join(real_path, name)
568
+ if os.path.islink(child_lex):
569
+ child_real, link_refused = _link_stays_in_tree(child_lex, real_root, state["config_names"])
570
+ if link_refused:
571
+ continue
572
+ else:
573
+ child_real = os.path.realpath(child_lex)
574
+ if not A._within(child_real, real_root):
575
+ continue
576
+ entries.append(f"{name}/" if os.path.isdir(child_real) else name)
577
+ truncated = len(entries) > TOOL_MAX_MATCHES
578
+ shown = entries[:TOOL_MAX_MATCHES]
579
+ out = "\n".join(shown) if shown else "(empty directory)"
580
+ if truncated:
581
+ out += f"\n... (truncated at {TOOL_MAX_MATCHES} entries)"
582
+ return _cap_answer_bytes(out, TOOL_MAX_BYTES)
583
+
584
+
585
+ def _tool_glob(state, args):
586
+ pattern = args.get("pattern")
587
+ if not isinstance(pattern, str) or not pattern.strip():
588
+ return "error: pattern must be a non-empty string"
589
+ refused = _check_relative_syntax(pattern)
590
+ if refused:
591
+ return refused
592
+ if not state["tree"] or os.path.islink(os.path.abspath(state["tree"])) or not os.path.isdir(state["tree"]):
593
+ return "refused: candidate tree is not available"
594
+ real_root = os.path.realpath(state["tree"])
595
+ if not A._lands_inside(real_root, pattern.strip()):
596
+ return "refused: '..' leaves the candidate tree"
597
+ norm_parts = []
598
+ for part in pattern.strip().replace("\\", "/").split("/"):
599
+ if part in ("", "."):
600
+ continue
601
+ if part == "..":
602
+ if not norm_parts:
603
+ return "refused: '..' leaves the candidate tree"
604
+ norm_parts.pop()
605
+ else:
606
+ norm_parts.append(part)
607
+ norm_pattern = "/".join(norm_parts) or "*"
608
+ prefix_parts = []
609
+ for part in norm_parts:
610
+ if any(ch in part for ch in "*?["):
611
+ break
612
+ prefix_parts.append(part)
613
+ if prefix_parts:
614
+ _, _, prefix_refused = _resolve_in_tree(state["tree"], "/".join(prefix_parts), state["config_names"])
615
+ if prefix_refused:
616
+ return prefix_refused
617
+ matcher = _glob_regex(norm_pattern)
618
+ refused_links = []
619
+ matches = []
620
+ truncated = False
621
+ for _, rel_path in _iter_tree_files(real_root, real_root, "", state["config_names"], refused_links=refused_links):
622
+ if matcher.match(rel_path):
623
+ if len(matches) >= TOOL_MAX_MATCHES:
624
+ truncated = True
625
+ break
626
+ matches.append(rel_path)
627
+ if not matches and refused_links:
628
+ for link_rel, link_why in refused_links:
629
+ if matcher.match(link_rel):
630
+ return link_why
631
+ out = "\n".join(matches) if matches else "(no matches)"
632
+ if truncated:
633
+ out += f"\n... (truncated at {TOOL_MAX_MATCHES} matches)"
634
+ return _cap_answer_bytes(out, TOOL_MAX_BYTES)
635
+
636
+
637
+ def _tool_grep(state, args):
638
+ pattern = args.get("pattern")
639
+ if not isinstance(pattern, str) or not pattern:
640
+ return "error: pattern must be a non-empty string"
641
+ try:
642
+ regex = re.compile(pattern)
643
+ except re.error as exc:
644
+ return f"error: invalid regular expression ({exc})"
645
+ raw_path = args.get("path", ".")
646
+ if raw_path is None:
647
+ raw_path = "."
648
+ real_path, rel_path, refused = _resolve_in_tree(state["tree"], raw_path, state["config_names"])
649
+ if refused:
650
+ return refused
651
+ file_glob = args.get("glob")
652
+ glob_matcher = None
653
+ glob_basename = False
654
+ if file_glob is not None:
655
+ if not isinstance(file_glob, str) or not file_glob.strip():
656
+ return "error: glob must be a non-empty string"
657
+ glob_refused = _check_relative_syntax(file_glob)
658
+ if glob_refused:
659
+ return glob_refused
660
+ norm_glob = "/".join(part for part in file_glob.strip().replace("\\", "/").split("/") if part not in ("", "."))
661
+ glob_basename = "/" not in norm_glob
662
+ glob_matcher = _glob_regex(norm_glob)
663
+ real_root = os.path.realpath(state["tree"])
664
+ if os.path.isfile(real_path):
665
+ files = [(real_path, rel_path)]
666
+ elif os.path.isdir(real_path):
667
+ files = _iter_tree_files(real_root, real_path, rel_path, state["config_names"])
668
+ else:
669
+ return "error: path not found"
670
+ remaining = TURN_MAX_READ_BYTES - state["read_bytes"]
671
+ if remaining <= 0:
672
+ state["bound"] = f"total bytes read limit ({TURN_MAX_READ_BYTES} bytes) reached"
673
+ return f"turn bound reached: {state['bound']}; write your review verdict now"
674
+ matches = []
675
+ truncated = False
676
+ for file_real, file_rel in files:
677
+ if glob_matcher is not None:
678
+ target_name = os.path.basename(file_rel) if glob_basename else file_rel
679
+ if not glob_matcher.match(target_name) and not glob_matcher.match(file_rel):
680
+ continue
681
+ data, err = _read_regular_bytes(file_real, GREP_MAX_FILE_BYTES)
682
+ if err or data is None or b"\x00" in data[:4096]:
683
+ continue
684
+ for lineno, line in enumerate(data.decode(UTF8, "replace").splitlines(), 1):
685
+ if regex.search(line):
686
+ if len(matches) >= TOOL_MAX_MATCHES:
687
+ truncated = True
688
+ break
689
+ matches.append(f"{file_rel}:{lineno}: {line[:300]}")
690
+ if truncated:
691
+ break
692
+ if matches:
693
+ body = "\n".join(matches)
694
+ raw_matches = body.encode(UTF8, "replace")[:TOOL_MAX_BYTES]
695
+ if len(raw_matches) > remaining:
696
+ body = raw_matches[:remaining].decode(UTF8, "ignore")
697
+ state["read_bytes"] += remaining
698
+ state["bound"] = f"total bytes read limit ({TURN_MAX_READ_BYTES} bytes) reached"
699
+ else:
700
+ state["read_bytes"] += len(raw_matches)
701
+ if state["read_bytes"] >= TURN_MAX_READ_BYTES:
702
+ state["bound"] = f"total bytes read limit ({TURN_MAX_READ_BYTES} bytes) reached"
703
+ out = body
704
+ else:
705
+ out = "(no matches)"
706
+ if truncated:
707
+ out += f"\n... (truncated at {TOOL_MAX_MATCHES} matches)"
708
+ if state["bound"]:
709
+ out += f"\n... (turn bound reached: {state['bound']})"
710
+ return _cap_answer_bytes(out, TOOL_MAX_BYTES)
711
+
712
+
713
+ def _dispatch_tool(state, name, raw_args):
714
+ if state["bound"]:
715
+ return f"turn bound reached: {state['bound']}; write your review verdict now"
716
+ try:
717
+ parsed = json.loads(raw_args) if isinstance(raw_args, str) else (raw_args or {})
718
+ except ValueError:
719
+ return "error: tool arguments must be a JSON object"
720
+ if not isinstance(parsed, dict):
721
+ return "error: tool arguments must be a JSON object"
722
+ if name == "read":
723
+ return _tool_read(state, parsed)
724
+ if name == "grep":
725
+ return _tool_grep(state, parsed)
726
+ if name == "glob":
727
+ return _tool_glob(state, parsed)
728
+ if name == "list":
729
+ return _tool_list(state, parsed)
730
+ return f"error: unknown tool {name!r}"
731
+
732
+
733
+ def _ask_provider(opener, url, key, payload, timeout):
734
+ body = json.dumps(payload).encode(UTF8)
735
+ request = urllib.request.Request(url + "/chat/completions", data=body, method="POST", headers={
736
+ "Content-Type": "application/json", "Authorization": f"Bearer {key}",
737
+ "User-Agent": f"polyctl/{__version__}"})
738
+ with opener.open(request, timeout=timeout) as response:
739
+ return json.loads(response.read().decode(UTF8, "replace"))
740
+
741
+
742
+ def _write_answer(output_path, text, rounds=0, read_bytes=0):
743
+ with open(output_path, "w", encoding=UTF8, newline="\n") as fh:
744
+ fh.write(text)
745
+ try:
746
+ with open(output_path + ".tool.json", "w", encoding=UTF8, newline="\n") as fh:
747
+ json.dump({"rounds": int(rounds), "read_bytes": int(read_bytes)}, fh)
748
+ except OSError:
749
+ pass
750
+
751
+
752
+ def main(argv=None):
753
+ A.utf8_streams()
754
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
755
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
756
+ parser.add_argument("--model", required=True, help="<provider>/<model>, the provider named in review.api_providers")
757
+ parser.add_argument("--diff-file", required=True, help="the candidate polyctl wrote; the prompt carries the same diff")
758
+ parser.add_argument("--output", required=True, help="where the answer is written")
759
+ parser.add_argument("--tree", default=None, help="the unpacked candidate tree for read-only review tools")
760
+ parser.add_argument("--timeout", type=float, default=TURN_MAX_SECONDS, help="seconds to wait for the answer")
761
+ parser.add_argument("prompt", help="the review prompt, or - to read it from standard input")
762
+ args = parser.parse_args(argv)
763
+
764
+ def refuse(text, code=USAGE):
765
+ print(f"{parser.prog}: {text}", file=sys.stderr)
766
+ return code
767
+
768
+ provider, _, model = args.model.partition("/")
769
+ if not provider or not model:
770
+ return refuse(f"--model is {args.model!r}; it names <provider>/<model>")
771
+ from . import settings
772
+ try:
773
+ table = providers(settings.get({}, "review.api_providers"))
774
+ except ValueError as exc:
775
+ return refuse(str(exc))
776
+ if provider not in table:
777
+ return refuse(f"review.api_providers names no {provider}; the machine's providers are "
778
+ f"{', '.join(sorted(table)) or 'none'}")
779
+ url, variable = table[provider]
780
+ key = os.environ.get(variable)
781
+ if not key:
782
+ return refuse(f"{variable} is not set, and it holds {provider}'s key")
783
+ # A header carries printable ASCII alone, and the error that refuses one names its value: a key holding a line
784
+ # break was printed with it (API-REVIEWER-2). What the key holds is not said.
785
+ if not re.fullmatch(r"[\x20-\x7e]+", key):
786
+ return refuse(f"{variable} holds a character outside printable ASCII, which no header carries")
787
+ if not os.path.isfile(args.diff_file):
788
+ return refuse(f"the candidate {args.diff_file} is not there")
789
+ prompt = sys.stdin.read() if args.prompt == "-" else args.prompt
790
+ # A provider on this machine is asked directly. A proxy the environment named took a request for 127.0.0.1, its
791
+ # key in plain text, to wherever the proxy was (API-REVIEWER-2); one over HTTPS passes a proxy as a tunnel, which
792
+ # carries the key encrypted. No redirect is followed: it is an answer, not a place to send the key.
793
+ handlers = []
794
+ if urllib.parse.urlparse(url).hostname in LOOPBACK:
795
+ handlers.append(urllib.request.ProxyHandler({}))
796
+ opener = outbound.opener(*handlers)
797
+
798
+ use_tools = args.tree is not None
799
+ state = {
800
+ "tree": args.tree,
801
+ "config_names": A.project_config_names() if use_tools else {},
802
+ "rounds": 0,
803
+ "read_bytes": 0,
804
+ "bound": None,
805
+ "none_ignored": 0,
806
+ "started": time.monotonic(),
807
+ "turn_seconds": min(float(args.timeout), TURN_MAX_SECONDS),
808
+ }
809
+ user_prompt = f"{prompt}\n\n{_tool_note(state['turn_seconds'])}" if use_tools else prompt
810
+ messages = [{"role": "user", "content": user_prompt}]
811
+
812
+ while True:
813
+ # Once tools were offered, every later request of the turn offers the same tools; past a turn bound the
814
+ # request carries `tool_choice: "none"` (not an absent `tools`), since a gateway whose conversion sees no
815
+ # `tools` on a follow-up drops `tool_call_id` from the tool results and fails upstream with 400
816
+ # (API-REVIEWER-TOOLS-3).
817
+ payload = {"model": model, "messages": messages}
818
+ if use_tools:
819
+ payload["tools"] = TOOLS
820
+ if state["bound"] is not None:
821
+ payload["tool_choice"] = "none"
822
+ req_timeout = max(1.0, float(args.timeout) - (time.monotonic() - state["started"])) if use_tools else args.timeout
823
+ try:
824
+ answer = _ask_provider(opener, url, key, payload, req_timeout)
825
+ except urllib.error.HTTPError as exc:
826
+ if outbound.is_redirect(exc.code):
827
+ # The status, and what to do: the key goes to the URL review.api_providers names and nowhere else
828
+ # (HUNT-LEADS-SEC).
829
+ return refuse(f"{provider} answered HTTP {exc.code}, a redirect, which polyctl does not follow with the key: "
830
+ "write the URL its endpoint moved to in review.api_providers", FAILED)
831
+ try:
832
+ said = _scrub(exc.read(300).decode(UTF8, "replace"), key) if exc.fp else ""
833
+ except Exception: # a body cut short is no reason to say less than the status
834
+ said = ""
835
+ detail = f": {' '.join(said.split())}" if said else ""
836
+ if use_tools and exc.code in (400, 404, 422, 501):
837
+ return refuse(f"{provider} refused the review tools for {model} (HTTP {exc.code}){detail}", FAILED)
838
+ return refuse(f"{provider} answered HTTP {exc.code}{detail}", FAILED)
839
+ except Exception as exc:
840
+ # Every failure of the exchange is said with the key taken out: http.client's protocol errors are none of
841
+ # URLError, OSError or ValueError, and a provider that put the key in a malformed status line had it printed
842
+ # in the traceback (API-REVIEWER-3).
843
+ return refuse(f"{provider} could not be asked ({type(exc).__name__}: {_scrub(str(exc), key)})", FAILED)
844
+
845
+ if not isinstance(answer, dict) or ("error" in answer and "choices" not in answer):
846
+ if use_tools:
847
+ return refuse(f"{provider} refused the review tools for {model}", FAILED)
848
+ return refuse(_no_answer(provider, model, answer if isinstance(answer, dict) else {}), FAILED)
849
+
850
+ if not use_tools:
851
+ break
852
+
853
+ try:
854
+ message = answer["choices"][0]["message"]
855
+ tool_calls = message.get("tool_calls") if isinstance(message, dict) else None
856
+ except (KeyError, IndexError, TypeError):
857
+ tool_calls = None
858
+
859
+ if not tool_calls:
860
+ break
861
+ if not isinstance(tool_calls, list):
862
+ return refuse(f"{provider} returned a malformed tool call for {model}", FAILED)
863
+
864
+ under_none = payload.get("tool_choice") == "none"
865
+ if under_none and state["none_ignored"] >= 1:
866
+ return refuse(f"{model} on {provider} still called tools under tool_choice=\"none\" after "
867
+ f"{state['bound']} (no more tools: give the verdict)", FAILED)
868
+ if not under_none:
869
+ state["rounds"] += 1
870
+ round_tag = f"none_{state['none_ignored'] + 1}" if under_none else str(state["rounds"])
871
+ seen_ids = state.setdefault("call_ids", set())
872
+ normalized_calls = []
873
+ for index, call in enumerate(tool_calls, 1):
874
+ if not isinstance(call, dict) or not isinstance(call.get("function"), dict):
875
+ return refuse(f"{provider} returned a malformed tool call for {model}", FAILED)
876
+ raw_id = call.get("id")
877
+ call_id = raw_id.strip() if isinstance(raw_id, str) else ""
878
+ if not call_id or call_id in seen_ids:
879
+ call_id = f"call_{round_tag}_{index}"
880
+ suffix = 1
881
+ while call_id in seen_ids:
882
+ suffix += 1
883
+ call_id = f"call_{round_tag}_{index}_{suffix}"
884
+ seen_ids.add(call_id)
885
+ normalized_calls.append(dict(call, id=call_id))
886
+ messages.append({"role": "assistant", "content": message.get("content"), "tool_calls": normalized_calls})
887
+ if under_none:
888
+ state["none_ignored"] += 1
889
+ for call in normalized_calls:
890
+ messages.append({"role": "tool", "tool_call_id": call["id"], "content": "no more tools: give the verdict"})
891
+ continue
892
+
893
+ for call in normalized_calls:
894
+ if state["bound"] is None and (time.monotonic() - state["started"]) >= state["turn_seconds"]:
895
+ state["bound"] = f"wall-time limit ({state['turn_seconds']:g}s) reached"
896
+ if state["bound"] is None and state["read_bytes"] >= TURN_MAX_READ_BYTES:
897
+ state["bound"] = f"total bytes read limit ({TURN_MAX_READ_BYTES} bytes) reached"
898
+ fn = call["function"]
899
+ out = _dispatch_tool(state, str(fn.get("name") or ""), fn.get("arguments") or "{}")
900
+ messages.append({"role": "tool", "tool_call_id": call["id"], "content": out})
901
+
902
+ if state["bound"] is None and (time.monotonic() - state["started"]) >= state["turn_seconds"]:
903
+ state["bound"] = f"wall-time limit ({state['turn_seconds']:g}s) reached"
904
+ if state["bound"] is None and state["read_bytes"] >= TURN_MAX_READ_BYTES:
905
+ state["bound"] = f"total bytes read limit ({TURN_MAX_READ_BYTES} bytes) reached"
906
+ if state["bound"] is None and state["rounds"] >= TURN_MAX_ROUNDS:
907
+ state["bound"] = f"tool round limit ({TURN_MAX_ROUNDS} rounds) reached"
908
+ if state["bound"] is not None:
909
+ messages[-1]["content"] += (f"\n\n[turn bound reached: {state['bound']}; tool_choice is \"none\" on the "
910
+ "next request — provide your final review verdict now]")
911
+
912
+ text = _content(answer)
913
+ if not text.strip():
914
+ return refuse(_no_answer(provider, model, answer), FAILED)
915
+ _write_answer(args.output, text, rounds=state["rounds"], read_bytes=state["read_bytes"])
916
+ return 0
917
+
918
+
919
+ if __name__ == "__main__":
920
+ sys.exit(main())