@tangle-network/agent-bench 6.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 +8 -0
- package/README.md +4 -0
- package/dist/index.d.ts +10 -1
- package/dist/index.js +27 -5
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/pier_agents/graph_driver.mjs +187 -27
- package/pier_agents/graph_process.py +59 -4
- package/pier_agents/tangle_candidate.py +103 -31
- package/src/pier-agent.ts +8 -1
- package/src/pier-trial-controller.ts +34 -4
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-bench",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "7.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Benchmark adapters and execution for agent-runtime across coding, tool-use, RAG, memory, browser, and terminal tasks.",
|
|
6
6
|
"repository": {
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"@tangle-network/agent-eval": "^2.0.29 || ^3.0.1",
|
|
32
32
|
"@tangle-network/agent-interface": "^5.10.41",
|
|
33
33
|
"@tangle-network/agent-knowledge": "^23.0.9",
|
|
34
|
-
"@tangle-network/agent-runtime": "^
|
|
34
|
+
"@tangle-network/agent-runtime": "^15.0.0",
|
|
35
35
|
"@tangle-network/sandbox": "^1.0.813"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
@@ -1,40 +1,205 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { createInterface } from 'node:readline'
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { canonicalAgentProfileDigest } from '@tangle-network/agent-interface'
|
|
5
|
+
import { redactProtectedValue, runProtectedCandidateGraph } from '@tangle-network/agent-runtime/candidate-execution'
|
|
6
|
+
import { contentAddress, createPrivateCasArtifactPort, FileSpawnJournal } from '@tangle-network/agent-runtime/kernel'
|
|
6
7
|
|
|
7
8
|
// The evaluator starts this process. Its stdout is the control channel to Pier, not a worker log.
|
|
8
9
|
const send = (value) => process.stdout.write(`${JSON.stringify(value)}\n`)
|
|
10
|
+
const digest = (value) => `sha256:${createHash('sha256').update(value).digest('hex')}`
|
|
9
11
|
console.log = console.error
|
|
10
12
|
const input = createInterface({ input: process.stdin })
|
|
11
13
|
const pending = new Map()
|
|
12
14
|
let next = 0
|
|
13
|
-
let
|
|
15
|
+
let execution
|
|
16
|
+
let protectedValues = []
|
|
14
17
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const run = (command, outputs) => new Promise((resolve, reject) => {
|
|
18
|
+
function request(message, signal) {
|
|
19
|
+
return new Promise((resolve, reject) => {
|
|
18
20
|
const id = next++
|
|
19
21
|
const abort = () => {
|
|
20
22
|
pending.delete(id)
|
|
21
|
-
reject(
|
|
23
|
+
reject(signal.reason)
|
|
22
24
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
+
signal?.throwIfAborted()
|
|
26
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
25
27
|
pending.set(id, (result) => {
|
|
26
|
-
|
|
28
|
+
signal?.removeEventListener('abort', abort)
|
|
27
29
|
resolve(result)
|
|
28
30
|
})
|
|
29
|
-
send({
|
|
30
|
-
kind: 'check', id, command: command.command, args: command.args,
|
|
31
|
-
timeoutMs: command.timeoutMs, env: command.env, outputs,
|
|
32
|
-
})
|
|
31
|
+
send({ ...message, id })
|
|
33
32
|
})
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function redact(value) {
|
|
36
|
+
return protectedValues.length ? redactProtectedValue(value, protectedValues).value : value
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function runCheck(command, outputs) {
|
|
40
|
+
command.signal?.throwIfAborted()
|
|
41
|
+
const result = await request({
|
|
42
|
+
kind: 'check', command: command.command, args: command.args,
|
|
43
|
+
timeoutMs: command.timeoutMs, env: command.env, outputs,
|
|
44
|
+
}, command.signal)
|
|
45
|
+
return {
|
|
46
|
+
...result,
|
|
47
|
+
stdout: redact(result.stdout),
|
|
48
|
+
stderr: redact(result.stderr),
|
|
49
|
+
...(result.outputSnapshot ? { outputSnapshot: { ...result.outputSnapshot, redact } } : {}),
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function protectedLeaf({ plan, leaf, graph, record }) {
|
|
54
|
+
const node = plan.launch.graph.nodeId
|
|
55
|
+
const selected = graph.nodes.find(({ id }) => id === node)
|
|
56
|
+
const profileDigest = selected && canonicalAgentProfileDigest(selected.profile)
|
|
57
|
+
const maxModelCalls = plan.limits.maxModelCalls
|
|
58
|
+
const tokenLimit = plan.limits.maxInputTokens + plan.limits.maxOutputTokens
|
|
59
|
+
let launched = false
|
|
60
|
+
return (profile, spawn) => {
|
|
61
|
+
if (!leaf || spawn?.route?.node !== node || spawn.continuity === 'resume' ||
|
|
62
|
+
!profileDigest || canonicalAgentProfileDigest(profile) !== profileDigest) {
|
|
63
|
+
throw new Error('Pier requires the single profile admitted in the protected graph plan')
|
|
64
|
+
}
|
|
65
|
+
const budget = spawn.budget
|
|
66
|
+
if (maxModelCalls && (
|
|
67
|
+
(budget.maxTokens !== undefined && budget.maxTokens < tokenLimit) ||
|
|
68
|
+
(budget.maxIterations !== undefined && budget.maxIterations < maxModelCalls)
|
|
69
|
+
)) {
|
|
70
|
+
throw new Error('The graph leaf reservation cannot cover the frozen trial grant')
|
|
71
|
+
}
|
|
72
|
+
let running
|
|
73
|
+
let result
|
|
74
|
+
let reported
|
|
75
|
+
let executionNode
|
|
76
|
+
const executor = {
|
|
77
|
+
runtime: 'cli',
|
|
78
|
+
async execute(task, signal) {
|
|
79
|
+
signal.throwIfAborted()
|
|
80
|
+
if (launched || next !== 0 || typeof task !== 'string' ||
|
|
81
|
+
Buffer.byteLength(task) !== leaf.instructionByteLength || digest(task) !== leaf.instructionDigest) {
|
|
82
|
+
throw new Error('Pier requires one signed leaf launch with the exact task as the first process')
|
|
83
|
+
}
|
|
84
|
+
launched = true
|
|
85
|
+
reported = {
|
|
86
|
+
iterations: 1,
|
|
87
|
+
tokens: { input: 0, output: 0 },
|
|
88
|
+
usd: 0,
|
|
89
|
+
ms: 0,
|
|
90
|
+
...(maxModelCalls ? { tokensKnown: false, usdKnown: false, iterationsKnown: false } : {}),
|
|
91
|
+
}
|
|
92
|
+
running = request({ kind: 'leaf', node, timeoutMs: budget.deadlineMs ?? plan.limits.timeoutMs })
|
|
93
|
+
const observed = await running
|
|
94
|
+
reported = { ...reported, ms: observed.elapsedMs }
|
|
95
|
+
let out = null
|
|
96
|
+
if (observed.exitCode === 0 && !observed.timedOut && !observed.stdoutTruncated) {
|
|
97
|
+
try {
|
|
98
|
+
const value = JSON.parse(observed.stdout)
|
|
99
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) out = redact(value)
|
|
100
|
+
} catch {
|
|
101
|
+
// The application output must be a complete JSON object to drive the graph.
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const capture = {
|
|
105
|
+
node,
|
|
106
|
+
execution: executionNode,
|
|
107
|
+
profileDigest,
|
|
108
|
+
profilePlanDigest: plan.profile.planDigest,
|
|
109
|
+
instructionDigest: leaf.instructionDigest,
|
|
110
|
+
exitCode: observed.exitCode,
|
|
111
|
+
timedOut: observed.timedOut,
|
|
112
|
+
elapsedMs: observed.elapsedMs,
|
|
113
|
+
stdoutDigest: observed.stdoutDigest,
|
|
114
|
+
stdoutTruncated: observed.stdoutTruncated,
|
|
115
|
+
stderrDigest: observed.stderrDigest,
|
|
116
|
+
output: out,
|
|
117
|
+
}
|
|
118
|
+
record(capture)
|
|
119
|
+
result = {
|
|
120
|
+
out,
|
|
121
|
+
outRef: contentAddress(out),
|
|
122
|
+
outputFormat: 'json',
|
|
123
|
+
outcome: out === null
|
|
124
|
+
? { success: false, error: 'The signed Pier leaf did not return a successful JSON result' }
|
|
125
|
+
: { success: true },
|
|
126
|
+
spent: reported,
|
|
127
|
+
}
|
|
128
|
+
return result
|
|
129
|
+
},
|
|
130
|
+
async teardown() {
|
|
131
|
+
// A reply is emitted only after Pier has closed the candidate UID processes.
|
|
132
|
+
await running
|
|
133
|
+
return { destroyed: true }
|
|
134
|
+
},
|
|
135
|
+
accounting() {
|
|
136
|
+
if (!reported) return undefined
|
|
137
|
+
return {
|
|
138
|
+
kind: 'leaf',
|
|
139
|
+
reported,
|
|
140
|
+
// Hold the graph allocation against the entire permitted grant. The actual model
|
|
141
|
+
// usage is unknown here and is settled once, independently, by the trial owner.
|
|
142
|
+
reservation: maxModelCalls ? {
|
|
143
|
+
iterations: maxModelCalls,
|
|
144
|
+
tokens: { input: plan.limits.maxInputTokens, output: plan.limits.maxOutputTokens },
|
|
145
|
+
usd: 0,
|
|
146
|
+
ms: reported.ms,
|
|
147
|
+
} : reported,
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
resultArtifact() {
|
|
151
|
+
if (!result) throw new Error('The signed Pier leaf has no terminal result')
|
|
152
|
+
return result
|
|
153
|
+
},
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
name: node,
|
|
157
|
+
act: async () => { throw new Error('The signed Pier process owns this graph leaf') },
|
|
158
|
+
executorSpec: {
|
|
159
|
+
profile,
|
|
160
|
+
harness: null,
|
|
161
|
+
executorFactory(_spec, { node: worker }) {
|
|
162
|
+
if (!worker || worker.parentId !== spawn.parentNodeId ||
|
|
163
|
+
worker.identity?.profileDigest !== profileDigest) {
|
|
164
|
+
throw new Error('Pier requires a Runtime assignment for the admitted graph profile')
|
|
165
|
+
}
|
|
166
|
+
const { rootId, parentId, nodeId, attemptId } = worker
|
|
167
|
+
executionNode = { rootId, parentId, nodeId, attemptId }
|
|
168
|
+
return executor
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function bindLeafEvidence(runDir, capture) {
|
|
176
|
+
const { rootId, nodeId, parentId, attemptId } = capture.execution
|
|
177
|
+
const journal = new FileSpawnJournal(join(runDir, 'spawn-journal.jsonl'))
|
|
178
|
+
const events = await journal.loadTree(rootId)
|
|
179
|
+
const started = events?.find((event) => event.kind === 'spawned' && event.id === nodeId &&
|
|
180
|
+
event.attemptId === attemptId)
|
|
181
|
+
const routed = events?.find((event) => event.kind === 'edge' && event.id === nodeId &&
|
|
182
|
+
event.edge.kind === 'routes' && event.edge.to === capture.node)
|
|
183
|
+
if (!started?.assignmentId || started.parent !== parentId ||
|
|
184
|
+
started.identity?.profileDigest !== capture.profileDigest || !routed) {
|
|
185
|
+
throw new Error('The signed Pier leaf has no matching Runtime route and execution record')
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
...capture,
|
|
189
|
+
execution: { ...capture.execution, assignmentId: started.assignmentId },
|
|
190
|
+
route: { ...routed.edge, traversal: routed.traversal },
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async function launch({ plan, taskDigest, invocation, traceRunId, runDir, workspace, publicEnv, leaf }) {
|
|
195
|
+
const invocationBytes = Buffer.from(invocation, 'base64')
|
|
196
|
+
const { graph } = JSON.parse(invocationBytes)
|
|
197
|
+
const artifactNamespace = createHash('sha256').update(traceRunId).digest('hex')
|
|
198
|
+
let nativeEvidence
|
|
34
199
|
const execution = await runProtectedCandidateGraph(
|
|
35
200
|
{
|
|
36
201
|
executionPlan: { value: { material: plan } },
|
|
37
|
-
graphInvocation:
|
|
202
|
+
graphInvocation: invocationBytes,
|
|
38
203
|
benchmark: { task: { digest: taskDigest } },
|
|
39
204
|
resolvedModel: plan.model.resolved,
|
|
40
205
|
trace: { runId: traceRunId },
|
|
@@ -43,15 +208,8 @@ async function launch({ plan, taskDigest, invocation, traceRunId, runDir, worksp
|
|
|
43
208
|
{
|
|
44
209
|
runDir,
|
|
45
210
|
checkArtifacts: createPrivateCasArtifactPort(join(runDir, 'artifacts'), artifactNamespace),
|
|
46
|
-
checkProcess: {
|
|
47
|
-
|
|
48
|
-
env: publicEnv,
|
|
49
|
-
run,
|
|
50
|
-
runWithOutputs: run,
|
|
51
|
-
},
|
|
52
|
-
makeLeafAgent() {
|
|
53
|
-
throw new Error('This protected Pier trial does not admit native model calls')
|
|
54
|
-
},
|
|
211
|
+
checkProcess: { cwd: workspace, env: publicEnv, run: runCheck, runWithOutputs: runCheck },
|
|
212
|
+
makeLeafAgent: protectedLeaf({ plan, leaf, graph, record: (value) => { nativeEvidence = value } }),
|
|
55
213
|
},
|
|
56
214
|
)
|
|
57
215
|
const { result, record, ...identity } = execution
|
|
@@ -61,15 +219,17 @@ async function launch({ plan, taskDigest, invocation, traceRunId, runDir, worksp
|
|
|
61
219
|
...identity,
|
|
62
220
|
record: Buffer.from(record).toString('base64'),
|
|
63
221
|
delivered: result.result.kind !== 'no-winner',
|
|
222
|
+
...(nativeEvidence ? { nativeEvidence: await bindLeafEvidence(runDir, nativeEvidence) } : {}),
|
|
64
223
|
},
|
|
65
224
|
})
|
|
66
225
|
}
|
|
67
226
|
|
|
68
227
|
input.on('line', (line) => {
|
|
69
228
|
const value = JSON.parse(line)
|
|
70
|
-
if (
|
|
71
|
-
|
|
72
|
-
|
|
229
|
+
if (execution === undefined) {
|
|
230
|
+
protectedValues = value.protectedValues
|
|
231
|
+
execution = launch(value).catch((error) => {
|
|
232
|
+
console.error(redact(error instanceof Error ? error.message : String(error)))
|
|
73
233
|
process.exitCode = 1
|
|
74
234
|
input.close()
|
|
75
235
|
process.stdin.destroy()
|
|
@@ -7,6 +7,7 @@ import math
|
|
|
7
7
|
import os
|
|
8
8
|
import secrets
|
|
9
9
|
import shlex
|
|
10
|
+
import tempfile
|
|
10
11
|
import time
|
|
11
12
|
from pathlib import Path
|
|
12
13
|
from typing import Any
|
|
@@ -112,6 +113,7 @@ async def _run_check(
|
|
|
112
113
|
request: dict[str, Any],
|
|
113
114
|
run_dir: Path,
|
|
114
115
|
public_env: dict[str, str],
|
|
116
|
+
output_root: Path,
|
|
115
117
|
) -> dict[str, Any]:
|
|
116
118
|
boundary = agent._process_boundary
|
|
117
119
|
contract = agent._contract
|
|
@@ -202,7 +204,7 @@ async def _run_check(
|
|
|
202
204
|
receipt["outputSnapshot"] = await _snapshot_outputs(
|
|
203
205
|
agent,
|
|
204
206
|
environment,
|
|
205
|
-
|
|
207
|
+
output_root / str(identifier),
|
|
206
208
|
prior,
|
|
207
209
|
outputs["maxFileBytes"],
|
|
208
210
|
outputs["maxTotalBytes"],
|
|
@@ -213,6 +215,46 @@ async def _run_check(
|
|
|
213
215
|
await asyncio.shield(boundary.remove_control_files(environment, wrapper, marker))
|
|
214
216
|
|
|
215
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
|
+
|
|
216
258
|
async def run_graph_in_pier(
|
|
217
259
|
agent: Any,
|
|
218
260
|
environment: BaseEnvironment,
|
|
@@ -221,6 +263,7 @@ async def run_graph_in_pier(
|
|
|
221
263
|
driver: tuple[str, str],
|
|
222
264
|
invocation: bytes,
|
|
223
265
|
trace_run_id: str,
|
|
266
|
+
instruction: str,
|
|
224
267
|
) -> None:
|
|
225
268
|
contract = agent._contract
|
|
226
269
|
root = agent.logs_dir.resolve() / "graph-runtime"
|
|
@@ -229,12 +272,14 @@ async def run_graph_in_pier(
|
|
|
229
272
|
workspace.mkdir(mode=0o700)
|
|
230
273
|
run_dir = root / "run"
|
|
231
274
|
public_env = dict(contract.env)
|
|
232
|
-
#
|
|
275
|
+
# Authored graph checks only receive explicitly admitted public environment values.
|
|
233
276
|
public_env.pop("PATH", None)
|
|
234
277
|
context.metadata = {**agent._identity_metadata(), "termination": {"kind": "running"}}
|
|
235
278
|
started = time.monotonic()
|
|
236
279
|
async with asyncio.timeout(contract.timeout_ms / 1000):
|
|
237
|
-
with (root / "coordinator.stderr").open("wb") as stderr
|
|
280
|
+
with (root / "coordinator.stderr").open("wb") as stderr, tempfile.TemporaryDirectory(
|
|
281
|
+
prefix="pier-graph-outputs-"
|
|
282
|
+
) as output_root:
|
|
238
283
|
process = await asyncio.create_subprocess_exec(
|
|
239
284
|
*driver,
|
|
240
285
|
stdin=asyncio.subprocess.PIPE,
|
|
@@ -259,13 +304,23 @@ async def run_graph_in_pier(
|
|
|
259
304
|
"runDir": str(run_dir),
|
|
260
305
|
"workspace": str(workspace),
|
|
261
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),
|
|
262
312
|
})
|
|
263
313
|
record = None
|
|
264
314
|
while line := await process.stdout.readline():
|
|
265
315
|
message = json.loads(line)
|
|
266
316
|
if message.get("kind") == "check":
|
|
267
317
|
# The process wrapper stops every process of this trial's candidate UID.
|
|
268
|
-
result = await _run_check(
|
|
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)
|
|
269
324
|
await send(result)
|
|
270
325
|
elif message.get("kind") == "complete":
|
|
271
326
|
record = message["graphExecution"]
|
|
@@ -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
|
|
@@ -89,6 +90,18 @@ class OriginalProfileFile:
|
|
|
89
90
|
content: bytes | None
|
|
90
91
|
|
|
91
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
|
+
|
|
92
105
|
class PierCandidateError(CandidateContractError):
|
|
93
106
|
"""The prepared candidate cannot be replayed safely by Pier."""
|
|
94
107
|
|
|
@@ -178,6 +191,7 @@ class TangleCandidateAgent(BaseAgent):
|
|
|
178
191
|
graph_invocation_path: str | None = None,
|
|
179
192
|
graph_node_path: str | None = None,
|
|
180
193
|
graph_driver_path: str | None = None,
|
|
194
|
+
graph_leaf_dispatch: bool = False,
|
|
181
195
|
*args: Any,
|
|
182
196
|
**kwargs: Any,
|
|
183
197
|
) -> None:
|
|
@@ -207,6 +221,7 @@ class TangleCandidateAgent(BaseAgent):
|
|
|
207
221
|
str(Path(graph_driver_path).resolve(strict=True)),
|
|
208
222
|
)
|
|
209
223
|
self._trace_run_id = trace_run_id
|
|
224
|
+
self._graph_leaf_dispatch = graph_leaf_dispatch is True
|
|
210
225
|
self._contract = load_prepared_candidate_contract(
|
|
211
226
|
Path(plan_path).expanduser().resolve(),
|
|
212
227
|
Path(receipt_path).expanduser().resolve(),
|
|
@@ -216,11 +231,13 @@ class TangleCandidateAgent(BaseAgent):
|
|
|
216
231
|
else None,
|
|
217
232
|
self._graph_invocation,
|
|
218
233
|
)
|
|
219
|
-
if
|
|
220
|
-
self.
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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")
|
|
224
241
|
if model_name != self._contract.requested_model:
|
|
225
242
|
raise PierCandidateError(
|
|
226
243
|
"Pier model does not match the runtime-resolved request: "
|
|
@@ -678,6 +695,8 @@ fi""",
|
|
|
678
695
|
f"installed={observed_pier}"
|
|
679
696
|
)
|
|
680
697
|
await self._verify_pier_execution_identity(environment)
|
|
698
|
+
if self._graph_leaf_dispatch:
|
|
699
|
+
self._verify_graph_leaf_network(environment)
|
|
681
700
|
await self._workspace_boundary.materialize_task_workspace(environment)
|
|
682
701
|
await self._workspace_boundary.verify_repository(environment)
|
|
683
702
|
await self._workspace_boundary.verify_container_workspace(
|
|
@@ -751,6 +770,44 @@ fi""",
|
|
|
751
770
|
"usageSource": "protected-agent-eval-trace",
|
|
752
771
|
}
|
|
753
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
|
+
|
|
754
811
|
async def _upload_instruction(
|
|
755
812
|
self, environment: BaseEnvironment, instruction: str
|
|
756
813
|
) -> tuple[list[str], str | None, str | None]:
|
|
@@ -914,22 +971,9 @@ fi""",
|
|
|
914
971
|
user="root",
|
|
915
972
|
)
|
|
916
973
|
|
|
917
|
-
async def
|
|
918
|
-
self,
|
|
919
|
-
|
|
920
|
-
environment: BaseEnvironment,
|
|
921
|
-
context: AgentContext,
|
|
922
|
-
) -> None:
|
|
923
|
-
if self._graph_driver is not None and self._graph_invocation is not None:
|
|
924
|
-
await run_graph_in_pier(
|
|
925
|
-
self,
|
|
926
|
-
environment,
|
|
927
|
-
context,
|
|
928
|
-
driver=self._graph_driver,
|
|
929
|
-
invocation=self._graph_invocation,
|
|
930
|
-
trace_run_id=self._trace_run_id,
|
|
931
|
-
)
|
|
932
|
-
return
|
|
974
|
+
async def _prepare_signed_process(
|
|
975
|
+
self, environment: BaseEnvironment, instruction: str, timeout_ms: int
|
|
976
|
+
) -> PreparedProcess:
|
|
933
977
|
argv, stdin_path, instruction_path = await self._upload_instruction(
|
|
934
978
|
environment, instruction
|
|
935
979
|
)
|
|
@@ -946,7 +990,7 @@ fi""",
|
|
|
946
990
|
wrapper, timeout_marker = await self._process_boundary.stage_wrapper(
|
|
947
991
|
environment
|
|
948
992
|
)
|
|
949
|
-
timeout_seconds = self._contract.timeout_ms / 1000
|
|
993
|
+
timeout_seconds = min(timeout_ms, self._contract.timeout_ms) / 1000
|
|
950
994
|
command = shlex.join(
|
|
951
995
|
[
|
|
952
996
|
wrapper,
|
|
@@ -960,6 +1004,40 @@ fi""",
|
|
|
960
1004
|
*argv,
|
|
961
1005
|
]
|
|
962
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
|
|
963
1041
|
context.metadata = {
|
|
964
1042
|
**self._identity_metadata(),
|
|
965
1043
|
"termination": {"kind": "running"},
|
|
@@ -967,13 +1045,7 @@ fi""",
|
|
|
967
1045
|
|
|
968
1046
|
started = time.monotonic()
|
|
969
1047
|
try:
|
|
970
|
-
result = await
|
|
971
|
-
command=command,
|
|
972
|
-
cwd=cwd,
|
|
973
|
-
env=environment.agent_process_env(process_env),
|
|
974
|
-
user="root",
|
|
975
|
-
timeout_sec=math.ceil(timeout_seconds) + 12,
|
|
976
|
-
)
|
|
1048
|
+
result = await self._execute_signed_process(environment, process)
|
|
977
1049
|
except (asyncio.CancelledError, asyncio.TimeoutError):
|
|
978
1050
|
elapsed = int((time.monotonic() - started) * 1000)
|
|
979
1051
|
cleanup_errors: list[str] = []
|
|
@@ -1049,8 +1121,8 @@ fi""",
|
|
|
1049
1121
|
"executionId": self._contract.execution_id,
|
|
1050
1122
|
"exitCode": result.return_code,
|
|
1051
1123
|
"elapsedMs": elapsed,
|
|
1052
|
-
"cwd": cwd,
|
|
1053
|
-
"argv": argv,
|
|
1124
|
+
"cwd": process.cwd,
|
|
1125
|
+
"argv": process.argv,
|
|
1054
1126
|
"instructionDelivery": self._contract.instruction.delivery_kind,
|
|
1055
1127
|
},
|
|
1056
1128
|
indent=2,
|
package/src/pier-agent.ts
CHANGED
|
@@ -81,6 +81,8 @@ export interface PierCandidateTrialController<
|
|
|
81
81
|
> {
|
|
82
82
|
/** This controller runs the sealed graph through the protected Pier trial. */
|
|
83
83
|
readonly graphDispatch?: true
|
|
84
|
+
/** This controller can launch the signed profile as a leaf of the sealed graph. */
|
|
85
|
+
readonly graphLeafDispatch?: true
|
|
84
86
|
start(
|
|
85
87
|
staged: StagedPierCandidateExecution,
|
|
86
88
|
context: {
|
|
@@ -109,6 +111,8 @@ export interface PierCandidateTrialResult {
|
|
|
109
111
|
readonly graphExecution?: AgentCandidateExecutorFinalCapture['graphExecution']
|
|
110
112
|
/** The trusted coordinator reached a graph deliverable that may be independently graded. */
|
|
111
113
|
readonly graphDelivered?: boolean
|
|
114
|
+
/** Evaluator-side observation of the signed native graph leaf. */
|
|
115
|
+
readonly nativeEvidence?: Uint8Array
|
|
112
116
|
}
|
|
113
117
|
|
|
114
118
|
export interface PierCandidateOfficialResult {
|
|
@@ -568,6 +572,7 @@ function sealPierTrialResult(value: PierCandidateTrialResult): PierCandidateTria
|
|
|
568
572
|
throw new Error('Pier graph execution requires raw evaluator record bytes')
|
|
569
573
|
}
|
|
570
574
|
const graphExecution = graph && Object.freeze({ ...graph, record: Uint8Array.from(graph.record) })
|
|
575
|
+
const nativeEvidence = value.nativeEvidence && Uint8Array.from(value.nativeEvidence)
|
|
571
576
|
return Object.freeze({
|
|
572
577
|
value: parsed,
|
|
573
578
|
get resultBytes(): Uint8Array {
|
|
@@ -578,6 +583,7 @@ function sealPierTrialResult(value: PierCandidateTrialResult): PierCandidateTria
|
|
|
578
583
|
},
|
|
579
584
|
...(graphExecution ? { graphExecution } : {}),
|
|
580
585
|
...(value.graphDelivered === undefined ? {} : { graphDelivered: value.graphDelivered }),
|
|
586
|
+
...(nativeEvidence ? { nativeEvidence } : {}),
|
|
581
587
|
})
|
|
582
588
|
}
|
|
583
589
|
|
|
@@ -738,7 +744,7 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
|
|
|
738
744
|
if (result.graphExecution && result.graphDelivered === false) {
|
|
739
745
|
trials.delete(identity)
|
|
740
746
|
officialResults.delete(request.executionId)
|
|
741
|
-
return { graphExecution: result.graphExecution }
|
|
747
|
+
return { graphExecution: result.graphExecution, ...(result.nativeEvidence ? { evidence: result.nativeEvidence } : {}) }
|
|
742
748
|
}
|
|
743
749
|
officialResults.set(request.executionId, result)
|
|
744
750
|
const task = options.prepared.benchmark.task
|
|
@@ -758,6 +764,7 @@ export function createPierCandidateExecutionOptions<Format extends AgentCandidat
|
|
|
758
764
|
return {
|
|
759
765
|
taskOutcome,
|
|
760
766
|
...(result.graphExecution ? { graphExecution: result.graphExecution } : {}),
|
|
767
|
+
...(result.nativeEvidence ? { evidence: result.nativeEvidence } : {}),
|
|
761
768
|
}
|
|
762
769
|
},
|
|
763
770
|
}
|