carpool-agents 0.2.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.
carpool/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """carpool — many agent tasks, one ride.
2
+
3
+ Lower the cost of agent work at a fixed quality target:
4
+ 1. exact operations run as code (zero model calls)
5
+ 2. independent reasoning tasks share ONE request, bound to stable IDs
6
+ 3. compact evidence only when a preflight says it is safe
7
+ 4. every answer is validated; failures fall back individually
8
+ """
9
+ from .backends import AnthropicBackend, CommandBackend, MockBackend, make_backend
10
+ from .batch import build_batch_prompt, build_single_prompt, parse_batch, parse_single
11
+ from .compact import normalize, preflight, verify
12
+ from .exact import ContractError, Index
13
+ from .ledger import Ledger, regressions, score
14
+ from .router import Result, run_carpool, run_compact_individual, run_individual
15
+ from .types import Answer, Completion, Source, Task
16
+
17
+ __version__ = "0.2.0"
18
+ __all__ = [
19
+ "AnthropicBackend", "CommandBackend", "MockBackend", "make_backend",
20
+ "build_batch_prompt", "build_single_prompt", "parse_batch", "parse_single",
21
+ "normalize", "preflight", "verify", "ContractError", "Index",
22
+ "Ledger", "regressions", "score", "Result", "run_carpool", "run_compact_individual", "run_individual",
23
+ "Answer", "Completion", "Source", "Task",
24
+ ]
carpool/agents.py ADDED
@@ -0,0 +1,249 @@
1
+ """Backends that report REAL provider usage.
2
+
3
+ Agent CLIs (each call pays the full agent harness — the cost carpool removes):
4
+ * ClaudeCodeBackend `claude -p --output-format json` (tested)
5
+ * CodexBackend `codex exec --json -` (parser from documented event format)
6
+ * GeminiCLIBackend `gemini -p ... --output-format json` (parser from documented format)
7
+
8
+ Raw model APIs over HTTP, stdlib only:
9
+ * OpenAICompatBackend /v1/chat/completions — OpenAI, Groq, Together, vLLM, LM Studio, OpenRouter...
10
+ * GeminiAPIBackend generateContent
11
+ * OllamaBackend /api/generate (local)
12
+
13
+ Spec strings for `make_backend` / the CLI:
14
+ claude-code[:model] claude-lean[:model] codex[:model] gemini-cli[:model]
15
+ openai:<model> gemini:<model> ollama:<model>
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import shlex
22
+ import subprocess
23
+ import tempfile
24
+ import time
25
+ import urllib.request
26
+ from typing import Optional
27
+
28
+ from .types import Completion
29
+
30
+
31
+ # ---------------------------------------------------------------- parsers
32
+ # Pure functions so they can be unit-tested against recorded payloads.
33
+
34
+ def parse_claude_code(stdout: str) -> Completion:
35
+ d = json.loads(stdout)
36
+ u = d.get("usage", {})
37
+ read = u.get("cache_read_input_tokens", 0) or 0
38
+ write = u.get("cache_creation_input_tokens", 0) or 0
39
+ return Completion(
40
+ text=d.get("result", "") or "",
41
+ input_tokens=(u.get("input_tokens", 0) or 0) + read + write,
42
+ cached_input_tokens=read,
43
+ output_tokens=u.get("output_tokens", 0) or 0,
44
+ cost_usd=float(d.get("total_cost_usd", 0) or 0),
45
+ )
46
+
47
+
48
+ def parse_codex_events(stdout: str) -> Completion:
49
+ text, inp, cached, out = "", 0, 0, 0
50
+ for line in stdout.splitlines():
51
+ line = line.strip()
52
+ if not line.startswith("{"):
53
+ continue
54
+ try:
55
+ ev = json.loads(line)
56
+ except json.JSONDecodeError:
57
+ continue
58
+ if ev.get("type") == "item.completed":
59
+ item = ev.get("item", {})
60
+ if item.get("type") in ("agent_message", "assistant_message"):
61
+ text = item.get("text", text)
62
+ elif ev.get("type") == "turn.completed":
63
+ u = ev.get("usage", {})
64
+ inp += u.get("input_tokens", 0) or 0
65
+ cached += u.get("cached_input_tokens", 0) or 0
66
+ out += u.get("output_tokens", 0) or 0
67
+ return Completion(text=text, input_tokens=inp, cached_input_tokens=cached, output_tokens=out)
68
+
69
+
70
+ def parse_gemini_cli(stdout: str) -> Completion:
71
+ d = json.loads(stdout[stdout.find("{"):])
72
+ inp = cached = out = 0
73
+ for m in d.get("stats", {}).get("models", {}).values():
74
+ t = m.get("tokens", {})
75
+ inp += t.get("prompt", 0) or 0
76
+ cached += t.get("cached", 0) or 0
77
+ out += (t.get("candidates", 0) or 0) + (t.get("thoughts", 0) or 0)
78
+ return Completion(text=d.get("response", "") or "", input_tokens=inp, cached_input_tokens=cached, output_tokens=out)
79
+
80
+
81
+ def parse_openai(d: dict) -> Completion:
82
+ u = d.get("usage") or {}
83
+ details = u.get("prompt_tokens_details") or {}
84
+ return Completion(
85
+ text=d["choices"][0]["message"].get("content") or "",
86
+ input_tokens=u.get("prompt_tokens", 0) or 0,
87
+ cached_input_tokens=details.get("cached_tokens", 0) or 0,
88
+ output_tokens=u.get("completion_tokens", 0) or 0,
89
+ )
90
+
91
+
92
+ def parse_gemini_api(d: dict) -> Completion:
93
+ u = d.get("usageMetadata") or {}
94
+ parts = (d.get("candidates") or [{}])[0].get("content", {}).get("parts", [])
95
+ return Completion(
96
+ text="".join(p.get("text", "") for p in parts if not p.get("thought")),
97
+ input_tokens=u.get("promptTokenCount", 0) or 0,
98
+ cached_input_tokens=u.get("cachedContentTokenCount", 0) or 0,
99
+ output_tokens=(u.get("candidatesTokenCount", 0) or 0) + (u.get("thoughtsTokenCount", 0) or 0),
100
+ )
101
+
102
+
103
+ def parse_ollama(d: dict) -> Completion:
104
+ return Completion(
105
+ text=d.get("response", "") or "",
106
+ input_tokens=d.get("prompt_eval_count", 0) or 0,
107
+ output_tokens=d.get("eval_count", 0) or 0,
108
+ )
109
+
110
+
111
+ # ---------------------------------------------------------------- CLI agents
112
+
113
+ class _CLI:
114
+ parse = staticmethod(lambda s: Completion(s))
115
+ timeout = 900
116
+
117
+ def argv(self) -> list[str]:
118
+ raise NotImplementedError
119
+
120
+ def __call__(self, prompt: str) -> Completion:
121
+ # empty working dir so the agent has nothing to go and read
122
+ with tempfile.TemporaryDirectory(prefix="carpool-") as cwd:
123
+ t0 = time.perf_counter()
124
+ p = subprocess.run(self.argv(), input=prompt, capture_output=True, text=True,
125
+ timeout=self.timeout, cwd=cwd)
126
+ dt = time.perf_counter() - t0
127
+ if p.returncode != 0:
128
+ raise RuntimeError(f"{self.argv()[0]} exited {p.returncode}: {(p.stderr or p.stdout)[-800:]}")
129
+ c = self.parse(p.stdout)
130
+ c.seconds = dt
131
+ return c
132
+
133
+
134
+ class ClaudeCodeBackend(_CLI):
135
+ parse = staticmethod(parse_claude_code)
136
+
137
+ def __init__(self, model: Optional[str] = None, extra: str = ""):
138
+ self.model, self.extra = model, extra
139
+
140
+ def argv(self):
141
+ a = ["claude", "-p", "--output-format", "json", "--no-session-persistence", "--strict-mcp-config"]
142
+ if self.model:
143
+ a += ["--model", self.model]
144
+ return a + shlex.split(self.extra)
145
+
146
+
147
+ class CodexBackend(_CLI):
148
+ parse = staticmethod(parse_codex_events)
149
+
150
+ def __init__(self, model: Optional[str] = None):
151
+ self.model = model
152
+
153
+ def argv(self):
154
+ a = ["codex", "exec", "--json", "--skip-git-repo-check"]
155
+ if self.model:
156
+ a += ["-m", self.model]
157
+ return a + ["-"]
158
+
159
+
160
+ class GeminiCLIBackend(_CLI):
161
+ parse = staticmethod(parse_gemini_cli)
162
+
163
+ def __init__(self, model: Optional[str] = None):
164
+ self.model = model
165
+
166
+ def argv(self):
167
+ a = ["gemini", "--output-format", "json"]
168
+ if self.model:
169
+ a += ["-m", self.model]
170
+ return a + ["-p", " "] # prompt arrives on stdin; -p enables headless mode
171
+
172
+
173
+ # ---------------------------------------------------------------- HTTP APIs
174
+
175
+ def _post(url: str, body: dict, headers: dict, timeout: float = 600) -> dict:
176
+ req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST",
177
+ headers={"content-type": "application/json", **headers})
178
+ with urllib.request.urlopen(req, timeout=timeout) as r:
179
+ return json.loads(r.read())
180
+
181
+
182
+ class _HTTP:
183
+ def __call__(self, prompt: str) -> Completion:
184
+ t0 = time.perf_counter()
185
+ c = self.call(prompt)
186
+ c.seconds = time.perf_counter() - t0
187
+ return c
188
+
189
+
190
+ class OpenAICompatBackend(_HTTP):
191
+ def __init__(self, model: str, base_url: Optional[str] = None, api_key_env: str = "OPENAI_API_KEY"):
192
+ self.model = model
193
+ self.base = (base_url or os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1").rstrip("/")
194
+ self.key = os.environ.get(api_key_env, "")
195
+
196
+ def call(self, prompt):
197
+ d = _post(f"{self.base}/chat/completions",
198
+ {"model": self.model, "messages": [{"role": "user", "content": prompt}]},
199
+ {"authorization": f"Bearer {self.key}"} if self.key else {})
200
+ return parse_openai(d)
201
+
202
+
203
+ class GeminiAPIBackend(_HTTP):
204
+ def __init__(self, model: str):
205
+ self.model, self.key = model, os.environ.get("GEMINI_API_KEY", "")
206
+
207
+ def call(self, prompt):
208
+ d = _post(f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent",
209
+ {"contents": [{"role": "user", "parts": [{"text": prompt}]}]},
210
+ {"x-goog-api-key": self.key})
211
+ return parse_gemini_api(d)
212
+
213
+
214
+ class OllamaBackend(_HTTP):
215
+ """Local models. `num_ctx` sets the context window: Ollama's default is small
216
+ and silently truncates long prompts, which would break grouped requests."""
217
+
218
+ def __init__(self, model: str, host: Optional[str] = None, num_ctx: int = 32768):
219
+ self.model, self.num_ctx = model, num_ctx
220
+ self.host = (host or os.environ.get("OLLAMA_HOST") or "http://localhost:11434").rstrip("/")
221
+ if not self.host.startswith("http"):
222
+ self.host = "http://" + self.host
223
+
224
+ def call(self, prompt):
225
+ return parse_ollama(_post(f"{self.host}/api/generate",
226
+ {"model": self.model, "prompt": prompt, "stream": False,
227
+ "options": {"num_ctx": self.num_ctx, "temperature": 0}}, {}, timeout=1800))
228
+
229
+
230
+ def make_agent_backend(spec: str):
231
+ name, _, arg = spec.partition(":")
232
+ arg = arg or None
233
+ if name == "claude-code":
234
+ return ClaudeCodeBackend(arg)
235
+ if name == "claude-lean":
236
+ # Same model through Claude Code, but no tools and a one-line system prompt:
237
+ # a strong baseline with a small fixed part per call (~1k tokens instead of ~26k).
238
+ return ClaudeCodeBackend(arg, extra='--tools "" --system-prompt "Answer the user\'s tasks exactly as instructed."')
239
+ if name == "codex":
240
+ return CodexBackend(arg)
241
+ if name == "gemini-cli":
242
+ return GeminiCLIBackend(arg)
243
+ if name == "openai" and arg:
244
+ return OpenAICompatBackend(arg)
245
+ if name == "gemini" and arg:
246
+ return GeminiAPIBackend(arg)
247
+ if name == "ollama" and arg:
248
+ return OllamaBackend(arg)
249
+ return None
carpool/backends.py ADDED
@@ -0,0 +1,197 @@
1
+ """Model backends. A backend is any callable: prompt -> Completion.
2
+
3
+ * AnthropicBackend - official `anthropic` SDK (pip install carpool[anthropic])
4
+ * CommandBackend - any CLI that reads a prompt on stdin: `claude -p`,
5
+ `codex exec -`, `gemini`, `ollama run <model>` ...
6
+ * MockBackend - offline, deterministic; for tests and demos only
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import shlex
12
+ import subprocess
13
+ import time
14
+ from typing import Callable, Optional
15
+
16
+ from .types import Completion
17
+
18
+ Backend = Callable[[str], Completion]
19
+
20
+
21
+ def estimate_tokens(text: str) -> int:
22
+ return max(1, len(text) // 4)
23
+
24
+
25
+ class AnthropicBackend:
26
+ def __init__(self, model: str = "claude-opus-5-5", effort: Optional[str] = None, max_tokens: int = 16000):
27
+ import anthropic # optional dependency
28
+
29
+ self.client = anthropic.Anthropic()
30
+ self.model, self.effort, self.max_tokens = model, effort, max_tokens
31
+
32
+ def __call__(self, prompt: str) -> Completion:
33
+ kwargs = dict(
34
+ model=self.model,
35
+ max_tokens=self.max_tokens,
36
+ messages=[{"role": "user", "content": prompt}],
37
+ # server-side refusal fallback; see Anthropic docs
38
+ betas=["server-side-fallback-2026-07-01"],
39
+ fallbacks="default",
40
+ )
41
+ if self.effort:
42
+ kwargs["output_config"] = {"effort": self.effort}
43
+ t0 = time.perf_counter()
44
+ r = self.client.beta.messages.create(**kwargs)
45
+ dt = time.perf_counter() - t0
46
+ if r.stop_reason == "refusal":
47
+ text = ""
48
+ else:
49
+ text = "".join(b.text for b in r.content if getattr(b, "type", "") == "text")
50
+ u = r.usage
51
+ cache_read = getattr(u, "cache_read_input_tokens", 0) or 0
52
+ cache_write = getattr(u, "cache_creation_input_tokens", 0) or 0
53
+ return Completion(
54
+ text=text,
55
+ input_tokens=u.input_tokens + cache_read + cache_write,
56
+ cached_input_tokens=cache_read,
57
+ output_tokens=u.output_tokens,
58
+ seconds=dt,
59
+ )
60
+
61
+
62
+ class AnthropicBatchBackend:
63
+ """Message Batches API: requests are processed asynchronously (usually
64
+ within an hour, at most 24 h) at 50% of standard prices. Use it for
65
+ work that is not time-sensitive. `map` submits every prompt of a run as
66
+ one batch; calling it with a single prompt submits a one-request batch."""
67
+
68
+ def __init__(self, model: str = "claude-opus-5-5", effort: Optional[str] = None,
69
+ max_tokens: int = 16000, poll_seconds: float = 30, client=None):
70
+ if client is None:
71
+ import anthropic # optional dependency
72
+
73
+ client = anthropic.Anthropic()
74
+ self.client = client
75
+ self.model, self.effort, self.max_tokens, self.poll = model, effort, max_tokens, poll_seconds
76
+
77
+ def _params(self, prompt: str) -> dict:
78
+ p = {"model": self.model, "max_tokens": self.max_tokens,
79
+ "messages": [{"role": "user", "content": prompt}]}
80
+ if self.effort:
81
+ p["output_config"] = {"effort": self.effort}
82
+ return p
83
+
84
+ def map(self, prompts: list[str]) -> list[Completion]:
85
+ t0 = time.perf_counter()
86
+ batch = self.client.messages.batches.create(
87
+ requests=[{"custom_id": f"r{i}", "params": self._params(p)} for i, p in enumerate(prompts)]
88
+ )
89
+ while True:
90
+ batch = self.client.messages.batches.retrieve(batch.id)
91
+ if batch.processing_status == "ended":
92
+ break
93
+ time.sleep(self.poll)
94
+ dt = time.perf_counter() - t0
95
+ out: dict[str, Completion] = {}
96
+ for r in self.client.messages.batches.results(batch.id): # any order: key by custom_id
97
+ if r.result.type != "succeeded":
98
+ out[r.custom_id] = Completion(text="", seconds=dt / len(prompts))
99
+ continue
100
+ m = r.result.message
101
+ text = "" if m.stop_reason == "refusal" else "".join(
102
+ b.text for b in m.content if getattr(b, "type", "") == "text")
103
+ u = m.usage
104
+ read = getattr(u, "cache_read_input_tokens", 0) or 0
105
+ write = getattr(u, "cache_creation_input_tokens", 0) or 0
106
+ out[r.custom_id] = Completion(text=text, input_tokens=u.input_tokens + read + write,
107
+ cached_input_tokens=read, output_tokens=u.output_tokens,
108
+ seconds=dt / len(prompts))
109
+ return [out.get(f"r{i}", Completion(text="")) for i in range(len(prompts))]
110
+
111
+ def __call__(self, prompt: str) -> Completion:
112
+ return self.map([prompt])[0]
113
+
114
+
115
+ class CommandBackend:
116
+ """Pipe the prompt into a CLI. Usage is estimated (chars/4) because most
117
+ CLIs do not print token counts; results are flagged `estimated`."""
118
+
119
+ def __init__(self, command: str, overhead_tokens: int = 0, timeout: float = 600):
120
+ self.argv = shlex.split(command)
121
+ self.overhead = overhead_tokens
122
+ self.timeout = timeout
123
+
124
+ def __call__(self, prompt: str) -> Completion:
125
+ t0 = time.perf_counter()
126
+ p = subprocess.run(self.argv, input=prompt, capture_output=True, text=True, timeout=self.timeout)
127
+ dt = time.perf_counter() - t0
128
+ if p.returncode != 0:
129
+ raise RuntimeError(f"{self.argv[0]} exited {p.returncode}: {p.stderr[-500:]}")
130
+ return Completion(
131
+ text=p.stdout,
132
+ input_tokens=estimate_tokens(prompt) + self.overhead,
133
+ output_tokens=estimate_tokens(p.stdout),
134
+ seconds=dt,
135
+ estimated=True,
136
+ )
137
+
138
+
139
+ _TASK_RE = re.compile(r"### TASK (\S+)\nQuestion: (.*?)\nSources:\n(.*?)(?=\n\n### TASK |\n*\Z)", re.S)
140
+ _SRC_RE = re.compile(r"^\[([^\]]+)\] (.*)$", re.M)
141
+
142
+
143
+ class MockBackend:
144
+ """A pretend model that answers correctly iff the gold answer is present in
145
+ the evidence it was given. Each call pays a fixed `overhead` (the agent
146
+ harness's system prompt + tool schemas, ~16k tokens in the paper's Codex
147
+ runs) — which is exactly what batching amortises."""
148
+
149
+ def __init__(self, gold: dict[str, str], overhead: int = 16_000):
150
+ self.gold, self.overhead = gold, overhead
151
+
152
+ def _answer(self, tid: str, block: str) -> tuple[str, str]:
153
+ srcs = _SRC_RE.findall(block)
154
+ g = self.gold.get(tid, "")
155
+ for sid, text in srcs:
156
+ if g and g.casefold() in text.casefold():
157
+ return g, sid
158
+ sid, text = srcs[0] if srcs else ("?", "")
159
+ words = re.findall(r"[A-Z][a-z]+", text)
160
+ return (words[-1] if words else "unknown"), sid
161
+
162
+ def __call__(self, prompt: str) -> Completion:
163
+ import json
164
+
165
+ blocks = _TASK_RE.findall(prompt)
166
+ rows = [dict(zip(("answer", "source"), self._answer(tid, srcs)), id=tid) for tid, _q, srcs in blocks]
167
+ if "Return ONLY a JSON array" in prompt:
168
+ out = json.dumps(rows)
169
+ else:
170
+ r = rows[0] if rows else {"answer": "", "source": ""}
171
+ out = json.dumps({"answer": r["answer"], "source": r["source"]})
172
+ return Completion(
173
+ text=out,
174
+ input_tokens=estimate_tokens(prompt) + self.overhead,
175
+ output_tokens=estimate_tokens(out),
176
+ seconds=0.0,
177
+ estimated=True,
178
+ )
179
+
180
+
181
+ def make_backend(spec: str, **kw) -> Backend:
182
+ """anthropic[:model] | anthropic-batch[:model] | claude-code[:model] | codex[:model] | gemini-cli[:model]
183
+ | openai:<model> | gemini:<model> | ollama:<model> | cmd:<shell command>"""
184
+ from .agents import make_agent_backend
185
+
186
+ b = make_agent_backend(spec)
187
+ if b is not None:
188
+ return b
189
+ if spec == "anthropic-batch" or spec.startswith("anthropic-batch:"):
190
+ model = spec.split(":", 1)[1] if ":" in spec else "claude-opus-5-5"
191
+ return AnthropicBatchBackend(model=model, **kw)
192
+ if spec == "anthropic" or spec.startswith("anthropic:"):
193
+ model = spec.split(":", 1)[1] if ":" in spec else "claude-opus-5-5"
194
+ return AnthropicBackend(model=model, **kw)
195
+ if spec.startswith("cmd:"):
196
+ return CommandBackend(spec[4:], **kw)
197
+ raise ValueError(f"unknown backend '{spec}'. See `carpool --help` or carpool/agents.py for specs")
carpool/batch.py ADDED
@@ -0,0 +1,116 @@
1
+ """Grouped requests: many independent tasks, one native call.
2
+
3
+ Every task and every source carries a stable ID. The model must return one
4
+ structured answer per task with the ID of the source it used. Missing,
5
+ duplicate, invalid-source and rejected answers fall back individually.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from typing import Optional
12
+
13
+ from .types import Source, Task
14
+
15
+ BATCH_INSTRUCTIONS = """You will answer {n} independent tasks.
16
+ Rules:
17
+ - Answer each task ONLY from the sources listed under that task. Never use another task's sources.
18
+ - Give the shortest exact answer (a name, number, date or short phrase), copied verbatim from the source. No explanations, no parentheses.
19
+ - Cite the ID of the one source that supports the answer.
20
+ - If sources disagree, prefer approved/current sources over drafts or superseded ones.
21
+ Return ONLY a JSON array, one object per task, no prose:
22
+ [{{"id": "<task id>", "answer": "<answer>", "source": "<source id>"}}]
23
+ """
24
+
25
+ SINGLE_INSTRUCTIONS = """Answer the task ONLY from the sources below.
26
+ Give the shortest exact answer, copied verbatim from the source (no explanations, no parentheses), and cite the ID of the one source that supports it.
27
+ If sources disagree, prefer approved/current sources over drafts or superseded ones.
28
+ Return ONLY a JSON object, no prose: {"answer": "<answer>", "source": "<source id>"}
29
+ """
30
+
31
+
32
+ def _render_task(task: Task, sources: list[Source]) -> str:
33
+ lines = [f"### TASK {task.id}", f"Question: {task.question}", "Sources:"]
34
+ for s in sources:
35
+ lines.append(f"[{s.id}] {s.text}")
36
+ return "\n".join(lines)
37
+
38
+
39
+ def build_batch_prompt(items: list[tuple[Task, list[Source]]]) -> str:
40
+ body = "\n\n".join(_render_task(t, srcs) for t, srcs in items)
41
+ return BATCH_INSTRUCTIONS.format(n=len(items)) + "\n" + body + "\n"
42
+
43
+
44
+ def build_single_prompt(task: Task) -> str:
45
+ return SINGLE_INSTRUCTIONS + "\n" + _render_task(task, task.sources) + "\n"
46
+
47
+
48
+ _PAREN_TAIL = re.compile(r"\s*[\(\[][^\)\]]*[\)\]]\s*$")
49
+
50
+
51
+ def clean_answer(ans: str) -> str:
52
+ """Drop a trailing parenthetical the model added as explanation."""
53
+ prev = None
54
+ while prev != ans:
55
+ prev, ans = ans, _PAREN_TAIL.sub("", ans).strip()
56
+ return ans
57
+
58
+
59
+ def _extract_json(text: str, open_ch: str, close_ch: str):
60
+ text = re.sub(r"```(?:json)?", "", text)
61
+ start, end = text.find(open_ch), text.rfind(close_ch)
62
+ if start == -1 or end <= start:
63
+ raise ValueError("no JSON found")
64
+ return json.loads(text[start: end + 1])
65
+
66
+
67
+ def parse_batch(text: str, items: list[tuple[Task, list[Source]]]):
68
+ """Return ({task_id: (answer, source_id)}, {task_id: failure_reason})."""
69
+ allowed = {t.id: {s.id for s in srcs} for t, srcs in items}
70
+ ok: dict[str, tuple[str, str]] = {}
71
+ bad: dict[str, str] = {}
72
+ try:
73
+ rows = _extract_json(text, "[", "]")
74
+ if not isinstance(rows, list):
75
+ raise ValueError("not a list")
76
+ except (ValueError, json.JSONDecodeError):
77
+ return {}, {tid: "unparseable batch response" for tid in allowed}
78
+
79
+ seen: dict[str, int] = {}
80
+ for row in rows:
81
+ if isinstance(row, dict) and "id" in row:
82
+ seen[str(row["id"])] = seen.get(str(row["id"]), 0) + 1
83
+ for row in rows:
84
+ if not isinstance(row, dict):
85
+ continue
86
+ tid = str(row.get("id", ""))
87
+ if tid not in allowed or tid in bad or tid in ok:
88
+ continue
89
+ if seen.get(tid, 0) > 1:
90
+ bad[tid] = "duplicate answer"
91
+ continue
92
+ ans, src = clean_answer(str(row.get("answer", "")).strip()), str(row.get("source", "")).strip()
93
+ if not ans:
94
+ bad[tid] = "empty answer"
95
+ elif src not in allowed[tid]:
96
+ # covers hallucinated IDs and cross-task evidence leakage
97
+ bad[tid] = f"invalid source '{src}'"
98
+ else:
99
+ ok[tid] = (ans, src)
100
+ for tid in allowed:
101
+ if tid not in ok and tid not in bad:
102
+ bad[tid] = "missing answer"
103
+ return ok, bad
104
+
105
+
106
+ def parse_single(text: str, task: Task) -> tuple[Optional[tuple[str, str]], Optional[str]]:
107
+ try:
108
+ obj = _extract_json(text, "{", "}")
109
+ except (ValueError, json.JSONDecodeError):
110
+ return None, "unparseable response"
111
+ ans, src = clean_answer(str(obj.get("answer", "")).strip()), str(obj.get("source", "")).strip()
112
+ if not ans:
113
+ return None, "empty answer"
114
+ if task.source(src) is None:
115
+ return None, f"invalid source '{src}'"
116
+ return (ans, src), None