constare 0.1.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.
- constare/__init__.py +32 -0
- constare/__main__.py +5 -0
- constare/agents/__init__.py +157 -0
- constare/agents/antigravity/__init__.py +25 -0
- constare/agents/antigravity/selfcheck/core.toml +77 -0
- constare/agents/claude_code/__init__.py +456 -0
- constare/agents/claude_code/_config.py +536 -0
- constare/agents/claude_code/_process.py +454 -0
- constare/agents/claude_code/_signals.py +499 -0
- constare/agents/claude_code/gate.sh +28 -0
- constare/agents/claude_code/selfcheck/accept-edits.toml +80 -0
- constare/agents/claude_code/selfcheck/bypass.toml +79 -0
- constare/agents/claude_code/selfcheck/core.toml +97 -0
- constare/agents/claude_code/selfcheck/effects.toml +24 -0
- constare/agents/claude_code/selfcheck/fetch.toml +33 -0
- constare/agents/claude_code/selfcheck/hooks-json.toml +63 -0
- constare/agents/claude_code/selfcheck/layers.toml +90 -0
- constare/agents/claude_code/selfcheck/mcp.toml +31 -0
- constare/agents/claude_code/selfcheck/plan.toml +53 -0
- constare/agents/claude_code/selfcheck/sandbox.toml +41 -0
- constare/agents/codex/__init__.py +28 -0
- constare/agents/codex/selfcheck/core.toml +77 -0
- constare/agents/grok/__init__.py +27 -0
- constare/agents/grok/selfcheck/core.toml +77 -0
- constare/casefile.py +557 -0
- constare/cli.py +145 -0
- constare/containment.py +351 -0
- constare/judge.py +76 -0
- constare/model.py +442 -0
- constare/policy.py +659 -0
- constare/process.py +56 -0
- constare/replay.py +660 -0
- constare/report.py +334 -0
- constare/standins/__init__.py +5 -0
- constare/standins/mcp_server.py +97 -0
- constare/standins/network.py +77 -0
- constare/version.py +3 -0
- constare/workspace.py +217 -0
- constare-0.1.0.dist-info/METADATA +429 -0
- constare-0.1.0.dist-info/RECORD +43 -0
- constare-0.1.0.dist-info/WHEEL +4 -0
- constare-0.1.0.dist-info/entry_points.txt +2 -0
- constare-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
"""Claude Code.
|
|
2
|
+
|
|
3
|
+
Each replay is one `claude -p` process in stream-json mode, in a constructed
|
|
4
|
+
environment, talking to a scripted Messages API on loopback that asks for
|
|
5
|
+
exactly one tool call. The decision is read from `tool_result_meta`, checked
|
|
6
|
+
against the agent's other signals, and audited against what the shell gate
|
|
7
|
+
recorded.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import secrets
|
|
17
|
+
import shlex
|
|
18
|
+
import shutil
|
|
19
|
+
import sys
|
|
20
|
+
from collections.abc import Mapping, Sequence
|
|
21
|
+
from contextlib import ExitStack
|
|
22
|
+
from dataclasses import dataclass, replace
|
|
23
|
+
from importlib.resources import files
|
|
24
|
+
from importlib.resources.abc import Traversable
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any, ClassVar, assert_never
|
|
27
|
+
|
|
28
|
+
from ...model import (
|
|
29
|
+
JSON,
|
|
30
|
+
Action,
|
|
31
|
+
AgentInfo,
|
|
32
|
+
Case,
|
|
33
|
+
Decision,
|
|
34
|
+
Edit,
|
|
35
|
+
Fetch,
|
|
36
|
+
Host,
|
|
37
|
+
Layer,
|
|
38
|
+
McpCall,
|
|
39
|
+
Mechanism,
|
|
40
|
+
Note,
|
|
41
|
+
Problem,
|
|
42
|
+
Read,
|
|
43
|
+
Reading,
|
|
44
|
+
ReplaySettings,
|
|
45
|
+
Seen,
|
|
46
|
+
Shell,
|
|
47
|
+
Unseen,
|
|
48
|
+
UnseenReason,
|
|
49
|
+
Write,
|
|
50
|
+
)
|
|
51
|
+
from ...standins import mcp_server
|
|
52
|
+
from ...standins.network import Blackhole
|
|
53
|
+
from ...version import __version__
|
|
54
|
+
from ...workspace import Workspace
|
|
55
|
+
from . import _config, _process, _signals
|
|
56
|
+
|
|
57
|
+
BINARY = "claude"
|
|
58
|
+
PROBE_TIMEOUT = 30.0
|
|
59
|
+
VERSION = re.compile(r"\d+(?:\.\d+)+[\w.+-]*")
|
|
60
|
+
|
|
61
|
+
MODES = _config.MODES
|
|
62
|
+
|
|
63
|
+
DESCRIPTION = "constare replay"
|
|
64
|
+
"""The description the scripted model gives for a shell command."""
|
|
65
|
+
EDIT_SUFFIX = " edited"
|
|
66
|
+
MCP_NAME = re.compile(r"[A-Za-z0-9_-]+")
|
|
67
|
+
"""Server and tool names known to appear unchanged in the agent's own name for an MCP tool, `mcp__server__tool`."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ClaudeCode:
|
|
71
|
+
id: ClassVar[str] = "claude-code"
|
|
72
|
+
selfcheck: ClassVar[Traversable] = files(__package__) / "selfcheck"
|
|
73
|
+
|
|
74
|
+
def __init__(self, host: Host) -> None:
|
|
75
|
+
self._host = host
|
|
76
|
+
self._binary: Path | None = None
|
|
77
|
+
|
|
78
|
+
def host_files(self) -> tuple[Path, ...]:
|
|
79
|
+
found = shutil.which(BINARY, path=self._host.path)
|
|
80
|
+
user = _config.user_config_dir(self._host)
|
|
81
|
+
binary = (Path(os.path.abspath(found)),) if found is not None else ()
|
|
82
|
+
return (*binary, user / _config.USER_SETTINGS, user / _config.USER_HOOKS_DIR)
|
|
83
|
+
|
|
84
|
+
def probe(self, ws: Workspace) -> AgentInfo | Problem:
|
|
85
|
+
"""`claude --version` in an isolated environment, without starting a scripted model."""
|
|
86
|
+
found = shutil.which(BINARY, path=self._host.path)
|
|
87
|
+
if found is None:
|
|
88
|
+
return Problem(self.id, f"the {BINARY} binary was not found on PATH")
|
|
89
|
+
binary = Path(os.path.realpath(found))
|
|
90
|
+
env = _process.build_env(ws, self._host.path, 1, None)
|
|
91
|
+
result = _process.launch(binary, env, ws, ["--version"], PROBE_TIMEOUT, bare=True)
|
|
92
|
+
version = VERSION.match(result.stdout[0]) if result.stdout else None
|
|
93
|
+
if not isinstance(result, _process.Exited) or result.code != 0 or version is None:
|
|
94
|
+
return Problem(self.id, f"{binary} did not report its version")
|
|
95
|
+
self._binary = binary
|
|
96
|
+
return AgentInfo(self.id, version.group(), binary)
|
|
97
|
+
|
|
98
|
+
def cache_key(self, info: AgentInfo, probes: Sequence[Case]) -> str | None:
|
|
99
|
+
"""Fingerprint of the agent binary, signal tables, gate script, and probes; None if monkeypatched."""
|
|
100
|
+
if mcp_standin is not _ORIG_MCP_STANDIN:
|
|
101
|
+
return None
|
|
102
|
+
try:
|
|
103
|
+
binary = Path(os.path.realpath(info.binary))
|
|
104
|
+
stat = binary.stat()
|
|
105
|
+
except OSError:
|
|
106
|
+
return None
|
|
107
|
+
gate_bytes = files(__package__).joinpath("gate.sh").read_bytes()
|
|
108
|
+
def encode_table(
|
|
109
|
+
table: Mapping[_signals.MetaKey, tuple[Decision, Mechanism | None]],
|
|
110
|
+
) -> list[Any]:
|
|
111
|
+
return sorted(
|
|
112
|
+
([list(k), [v[0].value, v[1].value if v[1] else None]] for k, v in table.items()),
|
|
113
|
+
key=lambda row: [(part is not None, str(part or "")) for part in row[0]],
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
payload = {
|
|
117
|
+
"constare": __version__,
|
|
118
|
+
"agent": [info.id, info.version, str(binary), stat.st_size, stat.st_mtime_ns],
|
|
119
|
+
"gate": hashlib.sha256(gate_bytes).hexdigest(),
|
|
120
|
+
"table": encode_table(_signals.TABLE),
|
|
121
|
+
"sandboxed": encode_table(_signals.SANDBOXED),
|
|
122
|
+
"asked_by": sorted([k is not None, k or "", v.value if v else None] for k, v in _signals.ASKED_BY.items()),
|
|
123
|
+
"built_in": sorted(_signals.BUILT_IN),
|
|
124
|
+
"removed": [_signals.REMOVED[0].value, _signals.REMOVED[1].value],
|
|
125
|
+
"probes": [
|
|
126
|
+
{
|
|
127
|
+
"id": p.id,
|
|
128
|
+
"action": repr(p.action),
|
|
129
|
+
"expect": repr(p.expect),
|
|
130
|
+
"layers": sorted(p.replay.layers),
|
|
131
|
+
"mode": p.replay.mode,
|
|
132
|
+
"mode_from_config": p.replay.mode_from_config,
|
|
133
|
+
"include": [repr(i) for i in p.replay.include],
|
|
134
|
+
"fixtures": sorted((str(k), v) for k, v in p.replay.fixtures.items()),
|
|
135
|
+
}
|
|
136
|
+
for p in probes
|
|
137
|
+
],
|
|
138
|
+
}
|
|
139
|
+
return hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
|
|
140
|
+
|
|
141
|
+
def inspect(self, replay: ReplaySettings, cases: Sequence[Case]) -> tuple[list[Problem], list[Note]]:
|
|
142
|
+
return _config.inspect(self._host, replay, cases)
|
|
143
|
+
|
|
144
|
+
def configured_mode(self, replay: ReplaySettings) -> str:
|
|
145
|
+
return _config.configured_mode(self._host, replay)
|
|
146
|
+
|
|
147
|
+
def install(self, ws: Workspace, layers: frozenset[Layer]) -> None:
|
|
148
|
+
_config.install(ws, self._host, layers)
|
|
149
|
+
|
|
150
|
+
def replay(self, case: Case, ws: Workspace, info: AgentInfo, timeout: float) -> Reading:
|
|
151
|
+
action = case.action
|
|
152
|
+
if isinstance(action, McpCall) and not (MCP_NAME.fullmatch(action.server) and MCP_NAME.fullmatch(action.tool)):
|
|
153
|
+
# A stand-in tool the agent lists under another name would read as a tool a rule removed.
|
|
154
|
+
unmatched = f'"{action.server}.{action.tool}" has characters other than letters, digits, "_" and "-"'
|
|
155
|
+
return Unseen(UnseenReason.STANDIN_DOWN, f"{unmatched}, so a stand-in tool cannot be matched to the call")
|
|
156
|
+
unreadable = _config.neutralise(ws)
|
|
157
|
+
if unreadable is not None:
|
|
158
|
+
return Unseen(UnseenReason.CONFIG_IGNORED, unreadable)
|
|
159
|
+
|
|
160
|
+
call = tool_call(action, ws)
|
|
161
|
+
config = _config.read_replay_config(ws)
|
|
162
|
+
# A shell case that checks effects has to run its command, so nothing stands in front of the shell.
|
|
163
|
+
runs_command = isinstance(action, Shell) and case.checks_effects
|
|
164
|
+
server = mcp_standin(action, ws) if isinstance(action, McpCall) else None
|
|
165
|
+
standin_commands = [server.command] if server is not None else []
|
|
166
|
+
gate = None if runs_command else _process.install_gate(ws, [*config.hook_commands, *standin_commands])
|
|
167
|
+
with ExitStack() as stack:
|
|
168
|
+
model = stack.enter_context(_process.ScriptedModel(call))
|
|
169
|
+
# An allowed fetch goes to a proxy that refuses it, and an allowed MCP call to a server that does nothing.
|
|
170
|
+
proxy = stack.enter_context(Blackhole()) if isinstance(action, Fetch) else None
|
|
171
|
+
env = _process.build_env(ws, self._host.path, model.port, gate, proxy.port if proxy is not None else None)
|
|
172
|
+
args = [*mode_args(case.replay), "--strict-mcp-config"]
|
|
173
|
+
args += ["--mcp-config", server.config] if server is not None else []
|
|
174
|
+
process = _process.launch(info.binary, env, ws, args, timeout)
|
|
175
|
+
# The gate also records the start of the stand-in server, which is neither a hook nor a held command.
|
|
176
|
+
facts = _signals.RunFacts(
|
|
177
|
+
process=process,
|
|
178
|
+
requests=tuple(model.requests),
|
|
179
|
+
gate=(
|
|
180
|
+
tuple(record for record in _process.read_gate(gate) if record.command not in standin_commands)
|
|
181
|
+
if gate is not None
|
|
182
|
+
else ()
|
|
183
|
+
),
|
|
184
|
+
held_marker=_process.HELD_MARKER + gate.nonce if gate is not None else None,
|
|
185
|
+
sandbox_auto_allow=config.sandbox_auto_allow,
|
|
186
|
+
mcp=server.facts() if server is not None else None,
|
|
187
|
+
fetch=_signals.FetchFacts(action.url, tuple(proxy.hosts)) if isinstance(action, Fetch) and proxy else None,
|
|
188
|
+
)
|
|
189
|
+
_record(ws, case, call, facts)
|
|
190
|
+
reading = _signals.read(call, facts, case)
|
|
191
|
+
return reading if isinstance(reading, Unseen) else in_expected_mode(reading, process.stdout, case.replay)
|
|
192
|
+
|
|
193
|
+
def replay_batch(
|
|
194
|
+
self,
|
|
195
|
+
ws: Workspace,
|
|
196
|
+
cases: Sequence[Case],
|
|
197
|
+
layers: tuple[Layer, ...],
|
|
198
|
+
mode: str,
|
|
199
|
+
*,
|
|
200
|
+
info: AgentInfo | None = None,
|
|
201
|
+
timeout: float | None = None,
|
|
202
|
+
) -> list[Reading]:
|
|
203
|
+
"""Run compatible non-effect cases in one `claude -p` session, returning aligned Readings."""
|
|
204
|
+
if not cases:
|
|
205
|
+
return []
|
|
206
|
+
effective_timeout = PROBE_TIMEOUT if timeout is None else timeout
|
|
207
|
+
binary = info.binary if info is not None else self._binary
|
|
208
|
+
if binary is None:
|
|
209
|
+
found = shutil.which(BINARY, path=self._host.path)
|
|
210
|
+
if found is None:
|
|
211
|
+
return [Unseen(UnseenReason.NO_REQUESTS, f"the {BINARY} binary was not found on PATH")] * len(cases)
|
|
212
|
+
binary = Path(os.path.realpath(found))
|
|
213
|
+
agent_info = info or AgentInfo(self.id, "", binary)
|
|
214
|
+
|
|
215
|
+
unreadable = _config.neutralise(ws)
|
|
216
|
+
if unreadable is not None:
|
|
217
|
+
return [Unseen(UnseenReason.CONFIG_IGNORED, unreadable)] * len(cases)
|
|
218
|
+
|
|
219
|
+
results: list[Reading | None] = [None] * len(cases)
|
|
220
|
+
batch_indices: list[int] = []
|
|
221
|
+
batch_cases: list[Case] = []
|
|
222
|
+
for idx, case in enumerate(cases):
|
|
223
|
+
if case.checks_effects or isinstance(case.action, Fetch | McpCall):
|
|
224
|
+
sub_private = ws.private / f"single-{idx}"
|
|
225
|
+
sub_private.mkdir(parents=True, exist_ok=True)
|
|
226
|
+
single_ws = Workspace(ws.root, ws.project, ws.home, ws.outside, sub_private)
|
|
227
|
+
results[idx] = self.replay(
|
|
228
|
+
replace(case, replay=replace(case.replay, mode=mode)), single_ws, agent_info, effective_timeout
|
|
229
|
+
)
|
|
230
|
+
else:
|
|
231
|
+
batch_indices.append(idx)
|
|
232
|
+
batch_cases.append(case)
|
|
233
|
+
|
|
234
|
+
if not batch_cases:
|
|
235
|
+
return [r for r in results if r is not None]
|
|
236
|
+
|
|
237
|
+
config = _config.read_replay_config(ws)
|
|
238
|
+
calls = [tool_call(case.action, ws) for case in batch_cases]
|
|
239
|
+
gate = _process.install_gate(ws, config.hook_commands)
|
|
240
|
+
turn_size = 1 if config.hook_commands else 7
|
|
241
|
+
with _process.ScriptedModel(calls, turn_size=turn_size, gate=gate) as model:
|
|
242
|
+
env = _process.build_env(ws, self._host.path, model.port, gate)
|
|
243
|
+
batch_replay = replace(batch_cases[0].replay, mode=mode)
|
|
244
|
+
args = [*mode_args(batch_replay), "--strict-mcp-config"]
|
|
245
|
+
process = _process.launch(binary, env, ws, args, effective_timeout)
|
|
246
|
+
trailing_gate = model.finish_gates()
|
|
247
|
+
|
|
248
|
+
all_gate = _process.read_gate(gate)
|
|
249
|
+
if turn_size == 1:
|
|
250
|
+
held_trailing = tuple(record for record in trailing_gate if not record.ran)
|
|
251
|
+
gate_per_call = [model.turn_gates.get(i, ()) + held_trailing for i in range(len(batch_cases))]
|
|
252
|
+
else:
|
|
253
|
+
buckets: list[list[_process.GateRecord]] = [[] for _ in calls]
|
|
254
|
+
unmatched: list[_process.GateRecord] = []
|
|
255
|
+
for record in all_gate:
|
|
256
|
+
if not record.ran:
|
|
257
|
+
matches = [
|
|
258
|
+
i
|
|
259
|
+
for i, call in enumerate(calls)
|
|
260
|
+
if isinstance(batch_cases[i].action, Shell) and _signals._wraps(record.command, call)
|
|
261
|
+
]
|
|
262
|
+
if matches:
|
|
263
|
+
target = next((i for i in matches if not buckets[i]), matches[0])
|
|
264
|
+
buckets[target].append(record)
|
|
265
|
+
continue
|
|
266
|
+
unmatched.append(record)
|
|
267
|
+
gate_per_call = [tuple(buckets[i] + unmatched) for i in range(len(calls))]
|
|
268
|
+
|
|
269
|
+
marker = _process.HELD_MARKER + gate.nonce
|
|
270
|
+
reqs = tuple(model.requests)
|
|
271
|
+
facts_list = [
|
|
272
|
+
_signals.RunFacts(
|
|
273
|
+
process=process,
|
|
274
|
+
requests=reqs,
|
|
275
|
+
gate=gate_i,
|
|
276
|
+
held_marker=marker,
|
|
277
|
+
sandbox_auto_allow=config.sandbox_auto_allow,
|
|
278
|
+
)
|
|
279
|
+
for gate_i in gate_per_call
|
|
280
|
+
]
|
|
281
|
+
_write_replay(
|
|
282
|
+
ws,
|
|
283
|
+
process,
|
|
284
|
+
reqs,
|
|
285
|
+
all_gate,
|
|
286
|
+
marker,
|
|
287
|
+
cases=[case.id for case in batch_cases],
|
|
288
|
+
calls=[{"id": c.id, "name": c.name, "input": dict(c.input)} for c in calls],
|
|
289
|
+
)
|
|
290
|
+
readings, started = _signals.read_many(calls, facts_list, batch_cases)
|
|
291
|
+
expected = MODES.get(mode, mode)
|
|
292
|
+
for idx, case, reading in zip(batch_indices, batch_cases, readings, strict=True):
|
|
293
|
+
if isinstance(reading, Unseen) or started == expected:
|
|
294
|
+
results[idx] = reading
|
|
295
|
+
else:
|
|
296
|
+
results[idx] = _mode_mismatch(started, expected, replace(case.replay, mode=mode))
|
|
297
|
+
return [r for r in results if r is not None]
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def mode_args(replay: ReplaySettings) -> list[str]:
|
|
301
|
+
"""The arguments that put the agent in the mode a case file names.
|
|
302
|
+
|
|
303
|
+
There are none when it names no mode: `--permission-mode` wins over
|
|
304
|
+
`permissions.defaultMode`, so passing it would replace the mode the
|
|
305
|
+
developer's own sessions start in.
|
|
306
|
+
"""
|
|
307
|
+
return [] if replay.mode_from_config else ["--permission-mode", MODES[replay.mode]]
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _mode_mismatch(started: str | None, expected: str, replay: ReplaySettings) -> Unseen:
|
|
311
|
+
asked = "its configuration asks for" if replay.mode_from_config else "the case file names"
|
|
312
|
+
said = f'started in "{started}" mode' if started is not None else "did not say which mode it started in"
|
|
313
|
+
return Unseen(UnseenReason.CONFIG_IGNORED, f'the agent {said}, not in the "{expected}" mode {asked}')
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def in_expected_mode(reading: Seen, stdout: Sequence[str], replay: ReplaySettings) -> Reading:
|
|
317
|
+
"""The reading, when the agent says it started in the mode the plan checked the self-check for.
|
|
318
|
+
|
|
319
|
+
The agent does not take every mode from every settings file, and a
|
|
320
|
+
decision made in another mode is not the one the case asked about.
|
|
321
|
+
"""
|
|
322
|
+
expected = MODES.get(replay.mode, replay.mode)
|
|
323
|
+
started = _started_mode(stdout)
|
|
324
|
+
return reading if started == expected else _mode_mismatch(started, expected, replay)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _started_mode(stdout: Sequence[str]) -> str | None:
|
|
328
|
+
"""`permissionMode` of the agent's `init` event, or None when it is not there as text."""
|
|
329
|
+
for line in stdout:
|
|
330
|
+
try:
|
|
331
|
+
event = json.loads(line)
|
|
332
|
+
except ValueError:
|
|
333
|
+
continue
|
|
334
|
+
if isinstance(event, dict) and event.get("type") == "system" and event.get("subtype") == "init":
|
|
335
|
+
mode = event.get("permissionMode")
|
|
336
|
+
return mode if isinstance(mode, str) else None
|
|
337
|
+
return None
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _thaw(value: object) -> JSON:
|
|
341
|
+
if isinstance(value, Mapping):
|
|
342
|
+
return {str(k): _thaw(v) for k, v in value.items()}
|
|
343
|
+
if isinstance(value, list | tuple):
|
|
344
|
+
return [_thaw(item) for item in value]
|
|
345
|
+
if value is None or isinstance(value, str | int | float | bool):
|
|
346
|
+
return value
|
|
347
|
+
return str(value)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def tool_call(action: Action, ws: Workspace) -> _process.ToolCall:
|
|
351
|
+
"""The one tool call the scripted model asks for.
|
|
352
|
+
|
|
353
|
+
The id carries a nonce drawn per replay, so a reading can only match a
|
|
354
|
+
call this replay's scripted model served.
|
|
355
|
+
"""
|
|
356
|
+
call_id = f"toolu_constare_{secrets.token_hex(8)}"
|
|
357
|
+
match action:
|
|
358
|
+
case Shell(command):
|
|
359
|
+
return _process.ToolCall(call_id, "Bash", {"command": ws.render(command), "description": DESCRIPTION})
|
|
360
|
+
case Read(path):
|
|
361
|
+
return _process.ToolCall(call_id, "Read", {"file_path": str(ws.resolve(path))})
|
|
362
|
+
case Write(path, content):
|
|
363
|
+
return _process.ToolCall(call_id, "Write", {"file_path": str(ws.resolve(path)), "content": content})
|
|
364
|
+
case Edit(path):
|
|
365
|
+
target = ws.resolve(path)
|
|
366
|
+
line = _first_line(target)
|
|
367
|
+
edit = {"file_path": str(target), "old_string": line, "new_string": line + EDIT_SUFFIX}
|
|
368
|
+
return _process.ToolCall(call_id, "Edit", edit)
|
|
369
|
+
case Fetch(url):
|
|
370
|
+
return _process.ToolCall(call_id, "WebFetch", {"url": url, "prompt": DESCRIPTION})
|
|
371
|
+
case McpCall(server, tool, arguments):
|
|
372
|
+
thawed = _thaw(arguments)
|
|
373
|
+
return _process.ToolCall(
|
|
374
|
+
call_id, f"mcp__{server}__{tool}", thawed if isinstance(thawed, dict) else {}
|
|
375
|
+
)
|
|
376
|
+
case _:
|
|
377
|
+
assert_never(action)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
@dataclass(frozen=True)
|
|
381
|
+
class McpStandin:
|
|
382
|
+
"""The server the agent starts under the name of the developer's own, which never starts."""
|
|
383
|
+
|
|
384
|
+
call: McpCall
|
|
385
|
+
command: str
|
|
386
|
+
"""What the agent hands its shell prefix to start the server. The gate passes this and nothing like it."""
|
|
387
|
+
config: str
|
|
388
|
+
"""The `--mcp-config` value that names the server."""
|
|
389
|
+
log: Path
|
|
390
|
+
|
|
391
|
+
def facts(self) -> _signals.McpFacts:
|
|
392
|
+
"""What the server saw, read once the agent has exited."""
|
|
393
|
+
return _signals.McpFacts(self.call.server, self.call.tool, mcp_server.read_log(self.log))
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def mcp_standin(action: McpCall, ws: Workspace) -> McpStandin:
|
|
397
|
+
"""Put the stand-in server in the replay, offering the one tool the case calls.
|
|
398
|
+
|
|
399
|
+
It runs on the interpreter that runs constare, named by absolute path,
|
|
400
|
+
so it needs nothing from the replay's PATH.
|
|
401
|
+
"""
|
|
402
|
+
directory = ws.private / "mcp"
|
|
403
|
+
directory.mkdir()
|
|
404
|
+
script, manifest, log = directory / "server.py", directory / "manifest.json", directory / "log.jsonl"
|
|
405
|
+
script.write_bytes(files(mcp_server.__package__ or "").joinpath("mcp_server.py").read_bytes())
|
|
406
|
+
mcp_server.write_manifest(manifest, action.server, (action.tool,))
|
|
407
|
+
arguments = ["-I", str(script), str(manifest), str(log)]
|
|
408
|
+
config = {"mcpServers": {action.server: {"command": sys.executable, "args": arguments}}}
|
|
409
|
+
return McpStandin(action, shlex.join([sys.executable, *arguments]), json.dumps(config), log)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
_ORIG_MCP_STANDIN = mcp_standin
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _first_line(path: Path) -> str:
|
|
416
|
+
"""The first non-empty line of a file, which an edit replaces; empty when there is none."""
|
|
417
|
+
try:
|
|
418
|
+
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
419
|
+
except OSError:
|
|
420
|
+
return ""
|
|
421
|
+
return next((line for line in lines if line.strip()), "")
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _write_replay(
|
|
425
|
+
ws: Workspace,
|
|
426
|
+
process: _process.Exited | _process.TimedOut,
|
|
427
|
+
requests: Sequence[_process.RequestLog],
|
|
428
|
+
gate: Sequence[_process.GateRecord],
|
|
429
|
+
held_marker: str | None,
|
|
430
|
+
**extra: Any,
|
|
431
|
+
) -> None:
|
|
432
|
+
replay = {
|
|
433
|
+
**extra,
|
|
434
|
+
"exit": process.code if isinstance(process, _process.Exited) else None,
|
|
435
|
+
"requests": [{"path": r.path, "had_tools": r.had_tools, "step": r.step} for r in requests],
|
|
436
|
+
"gate": [{"command": r.command, "ran": r.ran, "exit_code": r.exit_code} for r in gate],
|
|
437
|
+
"held_marker": held_marker,
|
|
438
|
+
}
|
|
439
|
+
(ws.private / "stdout.jsonl").write_text("".join(f"{line}\n" for line in process.stdout), encoding="utf-8")
|
|
440
|
+
(ws.private / "stderr.txt").write_text(process.stderr, encoding="utf-8")
|
|
441
|
+
(ws.private / "replay.json").write_text(json.dumps(replay, indent=2) + "\n", encoding="utf-8")
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _record(ws: Workspace, case: Case, call: _process.ToolCall, facts: _signals.RunFacts) -> None:
|
|
445
|
+
"""Leave what the replay produced in its private directory, for a kept replay to be inspected."""
|
|
446
|
+
_write_replay(
|
|
447
|
+
ws,
|
|
448
|
+
facts.process,
|
|
449
|
+
facts.requests,
|
|
450
|
+
facts.gate,
|
|
451
|
+
facts.held_marker,
|
|
452
|
+
case=case.id,
|
|
453
|
+
call={"id": call.id, "name": call.name, "input": dict(call.input)},
|
|
454
|
+
mcp=None if facts.mcp is None else {"offered": sorted(facts.mcp.log.offered), "calls": facts.mcp.log.calls},
|
|
455
|
+
fetch=None if facts.fetch is None else {"proxied": facts.fetch.proxied},
|
|
456
|
+
)
|