@tangle-network/agent-bench 5.0.0 → 7.0.0
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.
- package/CHANGELOG.md +17 -0
- package/HARNESS.md +6 -0
- package/README.md +10 -0
- package/dist/index.d.ts +23 -1
- package/dist/index.js +91 -5
- package/dist/index.js.map +1 -1
- package/package.json +8 -6
- package/pier_agents/candidate_contract.py +42 -14
- package/pier_agents/graph_driver.mjs +244 -0
- package/pier_agents/graph_process.py +344 -0
- package/pier_agents/tangle_candidate.py +120 -16
- package/scripts/verify-packed-consumer.mjs +6 -0
- package/src/pier-agent.test.mts +6 -0
- package/src/pier-agent.ts +60 -2
- package/src/pier-trial-controller.ts +95 -2
- package/src/swe-self-improve.mts +23 -1
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""Evaluator-side graph coordination with candidate-UID command execution."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import base64
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import secrets
|
|
9
|
+
import shlex
|
|
10
|
+
import tempfile
|
|
11
|
+
import time
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from pier.models.agent.context import AgentContext
|
|
16
|
+
from pier.environments.base import BaseEnvironment
|
|
17
|
+
|
|
18
|
+
from .candidate_contract import CandidateContractError, _safe_relative, sha256_bytes
|
|
19
|
+
from .workspace_boundary import candidate_git_env
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
async def _output_file_state(
|
|
23
|
+
agent: Any, environment: BaseEnvironment, path: str
|
|
24
|
+
) -> tuple[int, str] | str:
|
|
25
|
+
quoted = shlex.quote(path)
|
|
26
|
+
try:
|
|
27
|
+
result = await agent._exec(
|
|
28
|
+
environment,
|
|
29
|
+
f"""set -eu
|
|
30
|
+
file={quoted}
|
|
31
|
+
if ! test -e "$file" && ! test -L "$file"; then exit 3; fi
|
|
32
|
+
if ! test -f "$file" || test -L "$file" ||
|
|
33
|
+
test "$(realpath -e -- "$file")" != "$file" ||
|
|
34
|
+
test "$(stat -c %h -- "$file")" != 1; then exit 4; fi
|
|
35
|
+
stat -c '%s %d:%i %y %z' -- "$file"
|
|
36
|
+
""",
|
|
37
|
+
user="root",
|
|
38
|
+
check=False,
|
|
39
|
+
timeout_sec=5,
|
|
40
|
+
)
|
|
41
|
+
except TimeoutError:
|
|
42
|
+
return "timeout"
|
|
43
|
+
except Exception:
|
|
44
|
+
return "capture-failed"
|
|
45
|
+
if result.return_code == 3:
|
|
46
|
+
return "missing"
|
|
47
|
+
if result.return_code == 4:
|
|
48
|
+
return "unsafe-path"
|
|
49
|
+
size, _, identity = (result.stdout or "").strip().partition(" ")
|
|
50
|
+
if result.return_code != 0 or not size.isdigit() or not identity:
|
|
51
|
+
return "capture-failed"
|
|
52
|
+
return int(size), identity
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
async def _snapshot_outputs(
|
|
56
|
+
agent: Any,
|
|
57
|
+
environment: BaseEnvironment,
|
|
58
|
+
directory: Path,
|
|
59
|
+
prior: dict[str, tuple[int, str] | str],
|
|
60
|
+
max_file_bytes: int,
|
|
61
|
+
max_total_bytes: int,
|
|
62
|
+
timeout_ms: int,
|
|
63
|
+
) -> dict[str, Any]:
|
|
64
|
+
directory.mkdir(mode=0o700, parents=True)
|
|
65
|
+
failures: dict[str, str] = {}
|
|
66
|
+
pending = set(prior)
|
|
67
|
+
try:
|
|
68
|
+
async with asyncio.timeout(timeout_ms / 1000):
|
|
69
|
+
for path, before in prior.items():
|
|
70
|
+
source = f"{agent._contract.task_root}/{path}"
|
|
71
|
+
after = await _output_file_state(agent, environment, source)
|
|
72
|
+
destination = directory / path
|
|
73
|
+
if isinstance(after, str):
|
|
74
|
+
failures[path] = after
|
|
75
|
+
elif before == after:
|
|
76
|
+
failures[path] = "capture-failed"
|
|
77
|
+
elif after[0] > min(max_file_bytes, max_total_bytes):
|
|
78
|
+
failures[path] = "size-limit"
|
|
79
|
+
else:
|
|
80
|
+
destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
81
|
+
boundary = agent._process_boundary
|
|
82
|
+
staging = f"{boundary.config.control_root}/check-output-{secrets.token_hex(16)}"
|
|
83
|
+
copied = False
|
|
84
|
+
try:
|
|
85
|
+
# Pier changes ownership when it downloads files. Keep the command's workspace intact.
|
|
86
|
+
await agent._exec(
|
|
87
|
+
environment,
|
|
88
|
+
f"umask 077; {shlex.join(['cp', '--', source, staging])}",
|
|
89
|
+
user="root",
|
|
90
|
+
)
|
|
91
|
+
await environment.download_file(staging, destination)
|
|
92
|
+
copied = destination.stat().st_size == after[0]
|
|
93
|
+
if copied:
|
|
94
|
+
max_total_bytes -= after[0]
|
|
95
|
+
except Exception:
|
|
96
|
+
pass
|
|
97
|
+
finally:
|
|
98
|
+
if not copied:
|
|
99
|
+
failures[path] = "capture-failed"
|
|
100
|
+
destination.unlink(missing_ok=True)
|
|
101
|
+
await asyncio.shield(
|
|
102
|
+
boundary.remove_control_files(environment, None, staging)
|
|
103
|
+
)
|
|
104
|
+
pending.remove(path)
|
|
105
|
+
except TimeoutError:
|
|
106
|
+
failures.update((path, "timeout") for path in pending)
|
|
107
|
+
return {"directory": str(directory), "failures": failures}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
async def _run_check(
|
|
111
|
+
agent: Any,
|
|
112
|
+
environment: BaseEnvironment,
|
|
113
|
+
request: dict[str, Any],
|
|
114
|
+
run_dir: Path,
|
|
115
|
+
public_env: dict[str, str],
|
|
116
|
+
output_root: Path,
|
|
117
|
+
) -> dict[str, Any]:
|
|
118
|
+
boundary = agent._process_boundary
|
|
119
|
+
contract = agent._contract
|
|
120
|
+
identifier = request["id"]
|
|
121
|
+
command = request["command"]
|
|
122
|
+
arguments = request["args"]
|
|
123
|
+
milliseconds = request["timeoutMs"]
|
|
124
|
+
check_env = dict(request["env"])
|
|
125
|
+
if (
|
|
126
|
+
type(identifier) is not int
|
|
127
|
+
or identifier < 0
|
|
128
|
+
or command != "/bin/sh"
|
|
129
|
+
or not isinstance(arguments, list)
|
|
130
|
+
or len(arguments) != 2
|
|
131
|
+
or arguments[0] != "-c"
|
|
132
|
+
or not isinstance(arguments[1], str)
|
|
133
|
+
or type(milliseconds) is not int
|
|
134
|
+
or milliseconds <= 0
|
|
135
|
+
):
|
|
136
|
+
raise CandidateContractError("invalid evaluator graph command")
|
|
137
|
+
source = Path(check_env.pop("GRAPH_EVIDENCE"))
|
|
138
|
+
task_file = Path(check_env.pop("GRAPH_INPUT"))
|
|
139
|
+
if (
|
|
140
|
+
source.resolve() != source
|
|
141
|
+
or not source.is_relative_to(run_dir / "graph-evidence")
|
|
142
|
+
or task_file != source / "_input" / "task.json"
|
|
143
|
+
or any(public_env.get(name) != value for name, value in check_env.items())
|
|
144
|
+
):
|
|
145
|
+
raise CandidateContractError("graph check evidence or public environment changed")
|
|
146
|
+
target = f"{boundary.config.evaluator_root}/graph-evidence/{identifier}"
|
|
147
|
+
for file in source.rglob("*"):
|
|
148
|
+
if file.is_symlink():
|
|
149
|
+
raise CandidateContractError("graph evidence contains a symlink")
|
|
150
|
+
if not file.is_file():
|
|
151
|
+
continue
|
|
152
|
+
content = file.read_bytes()
|
|
153
|
+
await agent._write_verified_file(
|
|
154
|
+
environment,
|
|
155
|
+
file,
|
|
156
|
+
f"{target}/{file.relative_to(source).as_posix()}",
|
|
157
|
+
anchor=boundary.config.evaluator_root,
|
|
158
|
+
mode=0o444,
|
|
159
|
+
digest=sha256_bytes(content),
|
|
160
|
+
byte_length=len(content),
|
|
161
|
+
)
|
|
162
|
+
check_env.update(GRAPH_EVIDENCE=target, GRAPH_INPUT=f"{target}/_input/task.json")
|
|
163
|
+
outputs = request.get("outputs")
|
|
164
|
+
prior = {}
|
|
165
|
+
if outputs:
|
|
166
|
+
for item in outputs["paths"]:
|
|
167
|
+
path = _safe_relative(item, "graph check output")
|
|
168
|
+
prior[path] = await _output_file_state(
|
|
169
|
+
agent, environment, f"{contract.task_root}/{path}"
|
|
170
|
+
)
|
|
171
|
+
wrapper, marker = await boundary.stage_wrapper(environment)
|
|
172
|
+
try:
|
|
173
|
+
seconds = min(milliseconds, contract.timeout_ms) / 1000
|
|
174
|
+
call = shlex.join([
|
|
175
|
+
wrapper, marker, str(boundary.config.uid), str(boundary.config.gid),
|
|
176
|
+
f"{seconds:.3f}", "2", "-",
|
|
177
|
+
*(f"{name}={value}" for name, value in check_env.items()),
|
|
178
|
+
command, *arguments,
|
|
179
|
+
])
|
|
180
|
+
result = await agent._exec(
|
|
181
|
+
environment,
|
|
182
|
+
call,
|
|
183
|
+
cwd=contract.task_root,
|
|
184
|
+
env={
|
|
185
|
+
**candidate_git_env(contract.task_root),
|
|
186
|
+
"HOME": boundary.config.home,
|
|
187
|
+
"TMPDIR": boundary.config.temporary,
|
|
188
|
+
"PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
|
|
189
|
+
},
|
|
190
|
+
user="root",
|
|
191
|
+
timeout_sec=math.ceil(seconds) + 12,
|
|
192
|
+
check=False,
|
|
193
|
+
)
|
|
194
|
+
timed_out = await boundary.timeout_marker_exists(environment, marker)
|
|
195
|
+
receipt: dict[str, Any] = {
|
|
196
|
+
"id": identifier,
|
|
197
|
+
"exitCode": result.return_code,
|
|
198
|
+
"stdout": (result.stdout or "")[-131072:],
|
|
199
|
+
"stderr": (result.stderr or "")[-131072:],
|
|
200
|
+
"killedBySignal": None,
|
|
201
|
+
"timedOut": timed_out,
|
|
202
|
+
}
|
|
203
|
+
if outputs:
|
|
204
|
+
receipt["outputSnapshot"] = await _snapshot_outputs(
|
|
205
|
+
agent,
|
|
206
|
+
environment,
|
|
207
|
+
output_root / str(identifier),
|
|
208
|
+
prior,
|
|
209
|
+
outputs["maxFileBytes"],
|
|
210
|
+
outputs["maxTotalBytes"],
|
|
211
|
+
outputs.get("timeoutMs", 30_000),
|
|
212
|
+
)
|
|
213
|
+
return receipt
|
|
214
|
+
finally:
|
|
215
|
+
await asyncio.shield(boundary.remove_control_files(environment, wrapper, marker))
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
async def _run_leaf(
|
|
219
|
+
agent: Any, environment: BaseEnvironment, request: dict[str, Any], instruction: str
|
|
220
|
+
) -> dict[str, Any]:
|
|
221
|
+
contract = agent._contract
|
|
222
|
+
if (
|
|
223
|
+
not agent._graph_leaf_dispatch or request.get("id") != 0 or
|
|
224
|
+
request.get("node") != contract.plan["launch"]["graph"]["nodeId"] or
|
|
225
|
+
type(request.get("timeoutMs")) is not int or request["timeoutMs"] <= 0
|
|
226
|
+
):
|
|
227
|
+
raise CandidateContractError("Pier only admits the signed leaf as the graph's first process")
|
|
228
|
+
process = await agent._prepare_signed_process(environment, instruction, request["timeoutMs"])
|
|
229
|
+
started = time.monotonic()
|
|
230
|
+
boundary = agent._process_boundary
|
|
231
|
+
try:
|
|
232
|
+
result = await agent._execute_signed_process(environment, process)
|
|
233
|
+
timed_out = await boundary.timeout_marker_exists(environment, process.timeout_marker)
|
|
234
|
+
stdout = (result.stdout or "").encode("utf-8")
|
|
235
|
+
stdout_truncated = len(stdout) > 131072
|
|
236
|
+
return {
|
|
237
|
+
"id": request["id"],
|
|
238
|
+
"exitCode": result.return_code,
|
|
239
|
+
"timedOut": timed_out,
|
|
240
|
+
"elapsedMs": int((time.monotonic() - started) * 1000),
|
|
241
|
+
"stdout": None if stdout_truncated else stdout.decode("utf-8"),
|
|
242
|
+
"stdoutDigest": sha256_bytes(stdout),
|
|
243
|
+
"stdoutTruncated": stdout_truncated,
|
|
244
|
+
"stderrDigest": sha256_bytes((result.stderr or "").encode("utf-8")),
|
|
245
|
+
}
|
|
246
|
+
finally:
|
|
247
|
+
try:
|
|
248
|
+
await asyncio.shield(boundary.kill_and_wait(environment))
|
|
249
|
+
finally:
|
|
250
|
+
try:
|
|
251
|
+
await asyncio.shield(agent._remove_instruction_file(environment, process.instruction_path))
|
|
252
|
+
finally:
|
|
253
|
+
await asyncio.shield(boundary.remove_control_files(
|
|
254
|
+
environment, process.wrapper, process.timeout_marker,
|
|
255
|
+
))
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
async def run_graph_in_pier(
|
|
259
|
+
agent: Any,
|
|
260
|
+
environment: BaseEnvironment,
|
|
261
|
+
context: AgentContext,
|
|
262
|
+
*,
|
|
263
|
+
driver: tuple[str, str],
|
|
264
|
+
invocation: bytes,
|
|
265
|
+
trace_run_id: str,
|
|
266
|
+
instruction: str,
|
|
267
|
+
) -> None:
|
|
268
|
+
contract = agent._contract
|
|
269
|
+
root = agent.logs_dir.resolve() / "graph-runtime"
|
|
270
|
+
root.mkdir(mode=0o700)
|
|
271
|
+
workspace = root / "workspace-evidence"
|
|
272
|
+
workspace.mkdir(mode=0o700)
|
|
273
|
+
run_dir = root / "run"
|
|
274
|
+
public_env = dict(contract.env)
|
|
275
|
+
# Authored graph checks only receive explicitly admitted public environment values.
|
|
276
|
+
public_env.pop("PATH", None)
|
|
277
|
+
context.metadata = {**agent._identity_metadata(), "termination": {"kind": "running"}}
|
|
278
|
+
started = time.monotonic()
|
|
279
|
+
async with asyncio.timeout(contract.timeout_ms / 1000):
|
|
280
|
+
with (root / "coordinator.stderr").open("wb") as stderr, tempfile.TemporaryDirectory(
|
|
281
|
+
prefix="pier-graph-outputs-"
|
|
282
|
+
) as output_root:
|
|
283
|
+
process = await asyncio.create_subprocess_exec(
|
|
284
|
+
*driver,
|
|
285
|
+
stdin=asyncio.subprocess.PIPE,
|
|
286
|
+
stdout=asyncio.subprocess.PIPE,
|
|
287
|
+
stderr=stderr,
|
|
288
|
+
env={"PATH": os.defpath},
|
|
289
|
+
cwd=root,
|
|
290
|
+
limit=4 * 1024 * 1024,
|
|
291
|
+
)
|
|
292
|
+
assert process.stdin is not None and process.stdout is not None
|
|
293
|
+
|
|
294
|
+
async def send(value: dict[str, Any]) -> None:
|
|
295
|
+
process.stdin.write((json.dumps(value) + "\n").encode())
|
|
296
|
+
await process.stdin.drain()
|
|
297
|
+
|
|
298
|
+
try:
|
|
299
|
+
await send({
|
|
300
|
+
"plan": contract.plan,
|
|
301
|
+
"taskDigest": contract.receipt["benchmark"]["task"]["digest"],
|
|
302
|
+
"invocation": base64.b64encode(invocation).decode("ascii"),
|
|
303
|
+
"traceRunId": trace_run_id,
|
|
304
|
+
"runDir": str(run_dir),
|
|
305
|
+
"workspace": str(workspace),
|
|
306
|
+
"publicEnv": public_env,
|
|
307
|
+
"leaf": {
|
|
308
|
+
"instructionDigest": contract.instruction.sha256,
|
|
309
|
+
"instructionByteLength": contract.instruction.byte_length,
|
|
310
|
+
} if agent._graph_leaf_dispatch else None,
|
|
311
|
+
"protectedValues": agent._graph_redaction_values(environment),
|
|
312
|
+
})
|
|
313
|
+
record = None
|
|
314
|
+
while line := await process.stdout.readline():
|
|
315
|
+
message = json.loads(line)
|
|
316
|
+
if message.get("kind") == "check":
|
|
317
|
+
# The process wrapper stops every process of this trial's candidate UID.
|
|
318
|
+
result = await _run_check(
|
|
319
|
+
agent, environment, message, run_dir, public_env, Path(output_root)
|
|
320
|
+
)
|
|
321
|
+
await send(result)
|
|
322
|
+
elif message.get("kind") == "leaf":
|
|
323
|
+
result = await _run_leaf(agent, environment, message, instruction)
|
|
324
|
+
await send(result)
|
|
325
|
+
elif message.get("kind") == "complete":
|
|
326
|
+
record = message["graphExecution"]
|
|
327
|
+
break
|
|
328
|
+
else:
|
|
329
|
+
raise CandidateContractError("invalid graph coordinator response")
|
|
330
|
+
process.stdin.close()
|
|
331
|
+
if await process.wait() != 0 or record is None:
|
|
332
|
+
raise CandidateContractError("graph coordinator produced no terminal record")
|
|
333
|
+
finally:
|
|
334
|
+
if process.returncode is None:
|
|
335
|
+
process.kill()
|
|
336
|
+
await asyncio.shield(process.wait())
|
|
337
|
+
await asyncio.shield(agent._process_boundary.kill_and_wait(environment))
|
|
338
|
+
await asyncio.shield(agent._restore_profile_and_capture_solution(environment))
|
|
339
|
+
context.metadata = {
|
|
340
|
+
**agent._identity_metadata(),
|
|
341
|
+
"termination": {"kind": "exit", "exitCode": 0 if record["delivered"] else 1},
|
|
342
|
+
"observedElapsedMs": int((time.monotonic() - started) * 1000),
|
|
343
|
+
"graphExecution": record,
|
|
344
|
+
}
|
|
@@ -22,6 +22,7 @@ from dataclasses import dataclass, replace
|
|
|
22
22
|
from importlib.metadata import PackageNotFoundError, version as package_version
|
|
23
23
|
from pathlib import Path, PurePosixPath
|
|
24
24
|
from typing import Any
|
|
25
|
+
from urllib.parse import urlsplit
|
|
25
26
|
|
|
26
27
|
from pier.agents.base import BaseAgent
|
|
27
28
|
from pier.agents.installed.base import NonZeroAgentExitCodeError
|
|
@@ -36,6 +37,7 @@ from .candidate_contract import (
|
|
|
36
37
|
load_prepared_candidate_contract,
|
|
37
38
|
sha256_bytes,
|
|
38
39
|
)
|
|
40
|
+
from .graph_process import run_graph_in_pier
|
|
39
41
|
from .process_boundary import CandidateProcessBoundary, ProcessBoundaryConfig
|
|
40
42
|
from .workspace_boundary import (
|
|
41
43
|
CandidateWorkspaceBoundary,
|
|
@@ -88,6 +90,18 @@ class OriginalProfileFile:
|
|
|
88
90
|
content: bytes | None
|
|
89
91
|
|
|
90
92
|
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class PreparedProcess:
|
|
95
|
+
argv: list[str]
|
|
96
|
+
command: str
|
|
97
|
+
cwd: str
|
|
98
|
+
env: dict[str, str]
|
|
99
|
+
instruction_path: str | None
|
|
100
|
+
wrapper: str
|
|
101
|
+
timeout_marker: str
|
|
102
|
+
timeout_seconds: float
|
|
103
|
+
|
|
104
|
+
|
|
91
105
|
class PierCandidateError(CandidateContractError):
|
|
92
106
|
"""The prepared candidate cannot be replayed safely by Pier."""
|
|
93
107
|
|
|
@@ -174,6 +188,10 @@ class TangleCandidateAgent(BaseAgent):
|
|
|
174
188
|
knowledge_bundle_path: str | None = None,
|
|
175
189
|
pier_version: str | None = None,
|
|
176
190
|
extra_env: dict[str, str] | None = None,
|
|
191
|
+
graph_invocation_path: str | None = None,
|
|
192
|
+
graph_node_path: str | None = None,
|
|
193
|
+
graph_driver_path: str | None = None,
|
|
194
|
+
graph_leaf_dispatch: bool = False,
|
|
177
195
|
*args: Any,
|
|
178
196
|
**kwargs: Any,
|
|
179
197
|
) -> None:
|
|
@@ -191,6 +209,19 @@ class TangleCandidateAgent(BaseAgent):
|
|
|
191
209
|
raise PierCandidateError("task_dir, profile_dir, and pier_version are required")
|
|
192
210
|
|
|
193
211
|
self._expected_pier_version = pier_version
|
|
212
|
+
self._graph_invocation = (
|
|
213
|
+
Path(graph_invocation_path).read_bytes() if graph_invocation_path else None
|
|
214
|
+
)
|
|
215
|
+
self._graph_driver: tuple[str, str] | None = None
|
|
216
|
+
if self._graph_invocation is not None:
|
|
217
|
+
if not graph_node_path or not graph_driver_path:
|
|
218
|
+
raise PierCandidateError("sealed graph requires an evaluator coordinator")
|
|
219
|
+
self._graph_driver = (
|
|
220
|
+
str(Path(graph_node_path).resolve(strict=True)),
|
|
221
|
+
str(Path(graph_driver_path).resolve(strict=True)),
|
|
222
|
+
)
|
|
223
|
+
self._trace_run_id = trace_run_id
|
|
224
|
+
self._graph_leaf_dispatch = graph_leaf_dispatch is True
|
|
194
225
|
self._contract = load_prepared_candidate_contract(
|
|
195
226
|
Path(plan_path).expanduser().resolve(),
|
|
196
227
|
Path(receipt_path).expanduser().resolve(),
|
|
@@ -198,7 +229,15 @@ class TangleCandidateAgent(BaseAgent):
|
|
|
198
229
|
Path(knowledge_bundle_path).expanduser().absolute()
|
|
199
230
|
if knowledge_bundle_path
|
|
200
231
|
else None,
|
|
232
|
+
self._graph_invocation,
|
|
201
233
|
)
|
|
234
|
+
if self._graph_driver is not None:
|
|
235
|
+
limits = self._contract.plan["limits"]
|
|
236
|
+
if limits["maxModelCalls"] and (
|
|
237
|
+
not self._graph_leaf_dispatch or limits["maxCostUsd"] != 0 or
|
|
238
|
+
len(self._contract.model_network_domains) != 1
|
|
239
|
+
):
|
|
240
|
+
raise PierCandidateError("a model-backed Pier graph requires an admitted profile leaf and a zero-cost gateway grant")
|
|
202
241
|
if model_name != self._contract.requested_model:
|
|
203
242
|
raise PierCandidateError(
|
|
204
243
|
"Pier model does not match the runtime-resolved request: "
|
|
@@ -656,6 +695,8 @@ fi""",
|
|
|
656
695
|
f"installed={observed_pier}"
|
|
657
696
|
)
|
|
658
697
|
await self._verify_pier_execution_identity(environment)
|
|
698
|
+
if self._graph_leaf_dispatch:
|
|
699
|
+
self._verify_graph_leaf_network(environment)
|
|
659
700
|
await self._workspace_boundary.materialize_task_workspace(environment)
|
|
660
701
|
await self._workspace_boundary.verify_repository(environment)
|
|
661
702
|
await self._workspace_boundary.verify_container_workspace(
|
|
@@ -729,6 +770,44 @@ fi""",
|
|
|
729
770
|
"usageSource": "protected-agent-eval-trace",
|
|
730
771
|
}
|
|
731
772
|
|
|
773
|
+
def _verify_graph_leaf_network(self, environment: BaseEnvironment) -> None:
|
|
774
|
+
if environment.task_env_config.allow_internet is not False:
|
|
775
|
+
raise PierCandidateError("protected Pier graph leaves refuse unrestricted Internet")
|
|
776
|
+
domains = self._contract.model_network_domains
|
|
777
|
+
if not domains:
|
|
778
|
+
return
|
|
779
|
+
if tuple(environment.network_allowlist.domains) != domains or not environment.capabilities.filtered_egress:
|
|
780
|
+
raise PierCandidateError("Pier did not bind the frozen gateway-only network policy")
|
|
781
|
+
if not (environment.agent_process_env({}) or {}).get("HTTPS_PROXY"):
|
|
782
|
+
raise PierCandidateError("Pier did not install the protected gateway proxy")
|
|
783
|
+
token = self._extra_env.get("MODEL_GATEWAY_TOKEN")
|
|
784
|
+
if not token:
|
|
785
|
+
raise PierCandidateError("a model-backed graph leaf requires an activated gateway grant")
|
|
786
|
+
if any(name.lower() in {"http_proxy", "https_proxy", "all_proxy", "no_proxy"}
|
|
787
|
+
for name in self._contract.env.keys() | self._extra_env.keys()):
|
|
788
|
+
raise PierCandidateError("a protected graph leaf cannot replace Pier's gateway proxy")
|
|
789
|
+
if any(self._extra_env.get(name, token) != token
|
|
790
|
+
for name in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN")):
|
|
791
|
+
raise PierCandidateError("a protected graph leaf must use its activated gateway grant")
|
|
792
|
+
gateway_url = self._extra_env.get("MODEL_GATEWAY_BASE_URL", "")
|
|
793
|
+
for value in (gateway_url, self._extra_env.get("OPENAI_BASE_URL", gateway_url),
|
|
794
|
+
self._extra_env.get("ANTHROPIC_BASE_URL", gateway_url)):
|
|
795
|
+
gateway = urlsplit(value)
|
|
796
|
+
if (
|
|
797
|
+
gateway.scheme != "https" or gateway.hostname != domains[0] or
|
|
798
|
+
gateway.port not in {None, 443} or gateway.username or gateway.password
|
|
799
|
+
):
|
|
800
|
+
raise PierCandidateError("the activated gateway differs from the frozen model domain")
|
|
801
|
+
|
|
802
|
+
def _graph_redaction_values(self, environment: BaseEnvironment) -> list[str]:
|
|
803
|
+
values = [value for name, value in self._extra_env.items() if name not in _TRACE_ENV_NAMES]
|
|
804
|
+
for name, value in (environment.agent_process_env({}) or {}).items():
|
|
805
|
+
if name.lower() in {"http_proxy", "https_proxy"}:
|
|
806
|
+
values.append(value)
|
|
807
|
+
if password := urlsplit(value).password:
|
|
808
|
+
values.append(password)
|
|
809
|
+
return values
|
|
810
|
+
|
|
732
811
|
async def _upload_instruction(
|
|
733
812
|
self, environment: BaseEnvironment, instruction: str
|
|
734
813
|
) -> tuple[list[str], str | None, str | None]:
|
|
@@ -892,12 +971,9 @@ fi""",
|
|
|
892
971
|
user="root",
|
|
893
972
|
)
|
|
894
973
|
|
|
895
|
-
async def
|
|
896
|
-
self,
|
|
897
|
-
|
|
898
|
-
environment: BaseEnvironment,
|
|
899
|
-
context: AgentContext,
|
|
900
|
-
) -> None:
|
|
974
|
+
async def _prepare_signed_process(
|
|
975
|
+
self, environment: BaseEnvironment, instruction: str, timeout_ms: int
|
|
976
|
+
) -> PreparedProcess:
|
|
901
977
|
argv, stdin_path, instruction_path = await self._upload_instruction(
|
|
902
978
|
environment, instruction
|
|
903
979
|
)
|
|
@@ -914,7 +990,7 @@ fi""",
|
|
|
914
990
|
wrapper, timeout_marker = await self._process_boundary.stage_wrapper(
|
|
915
991
|
environment
|
|
916
992
|
)
|
|
917
|
-
timeout_seconds = self._contract.timeout_ms / 1000
|
|
993
|
+
timeout_seconds = min(timeout_ms, self._contract.timeout_ms) / 1000
|
|
918
994
|
command = shlex.join(
|
|
919
995
|
[
|
|
920
996
|
wrapper,
|
|
@@ -928,6 +1004,40 @@ fi""",
|
|
|
928
1004
|
*argv,
|
|
929
1005
|
]
|
|
930
1006
|
)
|
|
1007
|
+
return PreparedProcess(
|
|
1008
|
+
argv, command, cwd, process_env, instruction_path, wrapper, timeout_marker,
|
|
1009
|
+
timeout_seconds,
|
|
1010
|
+
)
|
|
1011
|
+
|
|
1012
|
+
async def _execute_signed_process(self, environment: BaseEnvironment, process: PreparedProcess):
|
|
1013
|
+
return await environment.exec(
|
|
1014
|
+
command=process.command,
|
|
1015
|
+
cwd=process.cwd,
|
|
1016
|
+
env=environment.agent_process_env(process.env),
|
|
1017
|
+
user="root",
|
|
1018
|
+
timeout_sec=math.ceil(process.timeout_seconds) + 12,
|
|
1019
|
+
)
|
|
1020
|
+
|
|
1021
|
+
async def run(
|
|
1022
|
+
self,
|
|
1023
|
+
instruction: str,
|
|
1024
|
+
environment: BaseEnvironment,
|
|
1025
|
+
context: AgentContext,
|
|
1026
|
+
) -> None:
|
|
1027
|
+
if self._graph_driver is not None and self._graph_invocation is not None:
|
|
1028
|
+
await run_graph_in_pier(
|
|
1029
|
+
self,
|
|
1030
|
+
environment,
|
|
1031
|
+
context,
|
|
1032
|
+
driver=self._graph_driver,
|
|
1033
|
+
invocation=self._graph_invocation,
|
|
1034
|
+
trace_run_id=self._trace_run_id,
|
|
1035
|
+
instruction=instruction,
|
|
1036
|
+
)
|
|
1037
|
+
return
|
|
1038
|
+
|
|
1039
|
+
process = await self._prepare_signed_process(environment, instruction, self._contract.timeout_ms)
|
|
1040
|
+
wrapper, timeout_marker, instruction_path = process.wrapper, process.timeout_marker, process.instruction_path
|
|
931
1041
|
context.metadata = {
|
|
932
1042
|
**self._identity_metadata(),
|
|
933
1043
|
"termination": {"kind": "running"},
|
|
@@ -935,13 +1045,7 @@ fi""",
|
|
|
935
1045
|
|
|
936
1046
|
started = time.monotonic()
|
|
937
1047
|
try:
|
|
938
|
-
result = await
|
|
939
|
-
command=command,
|
|
940
|
-
cwd=cwd,
|
|
941
|
-
env=environment.agent_process_env(process_env),
|
|
942
|
-
user="root",
|
|
943
|
-
timeout_sec=math.ceil(timeout_seconds) + 12,
|
|
944
|
-
)
|
|
1048
|
+
result = await self._execute_signed_process(environment, process)
|
|
945
1049
|
except (asyncio.CancelledError, asyncio.TimeoutError):
|
|
946
1050
|
elapsed = int((time.monotonic() - started) * 1000)
|
|
947
1051
|
cleanup_errors: list[str] = []
|
|
@@ -1017,8 +1121,8 @@ fi""",
|
|
|
1017
1121
|
"executionId": self._contract.execution_id,
|
|
1018
1122
|
"exitCode": result.return_code,
|
|
1019
1123
|
"elapsedMs": elapsed,
|
|
1020
|
-
"cwd": cwd,
|
|
1021
|
-
"argv": argv,
|
|
1124
|
+
"cwd": process.cwd,
|
|
1125
|
+
"argv": process.argv,
|
|
1022
1126
|
"instructionDelivery": self._contract.instruction.delivery_kind,
|
|
1023
1127
|
},
|
|
1024
1128
|
indent=2,
|
|
@@ -252,6 +252,7 @@ root = Path(pier_agents.__file__).parent
|
|
|
252
252
|
expected = {
|
|
253
253
|
"__init__.py",
|
|
254
254
|
"candidate_contract.py",
|
|
255
|
+
"graph_process.py",
|
|
255
256
|
"process_boundary.py",
|
|
256
257
|
"tangle_candidate.py",
|
|
257
258
|
"workspace_boundary.py",
|
|
@@ -307,6 +308,11 @@ for name in sorted(expected):
|
|
|
307
308
|
await run('npm', ['exec', '--', 'tsx', 'managed-execution.ts'], consumerDir)
|
|
308
309
|
const installedPackage = path.join(consumerDir, 'node_modules', '@tangle-network', 'agent-bench')
|
|
309
310
|
await access(path.join(installedPackage, 'dist', 'pier-trial-supervisor.mjs'))
|
|
311
|
+
await run(
|
|
312
|
+
'node',
|
|
313
|
+
['--check', path.join(installedPackage, 'pier_agents', 'graph_driver.mjs')],
|
|
314
|
+
consumerDir,
|
|
315
|
+
)
|
|
310
316
|
const prepared = await run(
|
|
311
317
|
'npm',
|
|
312
318
|
[
|
package/src/pier-agent.test.mts
CHANGED
|
@@ -39,6 +39,12 @@ function prepared(root: string): PreparedAgentCandidateExecution {
|
|
|
39
39
|
kind: 'agent-candidate-execution-plan-material',
|
|
40
40
|
runCell: { bundleDigest },
|
|
41
41
|
executionId,
|
|
42
|
+
launch: {
|
|
43
|
+
executable: 'python3',
|
|
44
|
+
args: [{ kind: 'public', value: '/opt/tangle-candidate/runner.py' }],
|
|
45
|
+
env: { PUBLIC_MODE: { kind: 'public', value: 'fixture' } },
|
|
46
|
+
cwd: { workspace: 'task', path: '.' },
|
|
47
|
+
},
|
|
42
48
|
limits: {
|
|
43
49
|
timeoutMs: 60_000,
|
|
44
50
|
maxSteps: 8,
|