@tangle-network/agent-bench 3.0.0 → 4.0.2
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 +21 -0
- package/README.md +8 -0
- package/dist/cli.js +44 -6
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +35 -15
- package/dist/index.js +248 -89
- package/dist/index.js.map +1 -1
- package/dist/pier-trial-supervisor.mjs +352 -0
- package/package.json +5 -5
- package/pier_agents/candidate_contract.py +226 -74
- package/pier_agents/tangle_candidate.py +79 -1
- package/pier_agents/workspace_boundary.py +29 -1
- package/scripts/verify-packed-consumer.mjs +1 -0
- package/scripts/verify-pier-agent.mts +174 -123
- package/src/index.ts +3 -0
- package/src/pier-agent.ts +127 -39
- package/src/pier-trial-controller.test.mts +48 -1
- package/src/pier-trial-controller.ts +121 -8
- package/src/published.test.mts +29 -6
- package/src/published.ts +53 -8
package/src/pier-agent.ts
CHANGED
|
@@ -7,12 +7,14 @@ import { dirname, isAbsolute, join, resolve } from 'node:path'
|
|
|
7
7
|
import type {
|
|
8
8
|
AgentCandidateBenchmarkGraderPort,
|
|
9
9
|
AgentCandidateExecutionClaimStore,
|
|
10
|
+
AgentCandidateExecutionFormat,
|
|
10
11
|
AgentCandidateExecutorRequest,
|
|
11
12
|
AgentCandidateExecutorStopRequest,
|
|
12
13
|
AgentCandidateExecutorPort,
|
|
13
14
|
AgentCandidateOutputArtifactPort,
|
|
14
15
|
AgentCandidateProtectedRunCapture,
|
|
15
16
|
AgentCandidateRunFinalization,
|
|
17
|
+
ExecutePreparedAgentCandidateOptions,
|
|
16
18
|
PreparedAgentCandidateExecution,
|
|
17
19
|
} from '@tangle-network/agent-runtime/candidate-execution'
|
|
18
20
|
|
|
@@ -24,8 +26,10 @@ import { capturePierTaskOutcome } from './pier-task-outcome'
|
|
|
24
26
|
const adapterImportPath = 'pier_agents.tangle_candidate:TangleCandidateAgent'
|
|
25
27
|
const sha256Pattern = /^sha256:[a-f0-9]{64}$/
|
|
26
28
|
|
|
27
|
-
interface StagePreparedPierCandidateOptions
|
|
28
|
-
|
|
29
|
+
interface StagePreparedPierCandidateOptions<
|
|
30
|
+
Format extends AgentCandidateExecutionFormat = 'experiment',
|
|
31
|
+
> {
|
|
32
|
+
readonly prepared: PreparedAgentCandidateExecution<Format>
|
|
29
33
|
/** Evaluator-owned directory persisted with the Pier trial. */
|
|
30
34
|
readonly directory: string
|
|
31
35
|
/** Exact Pier package version pinned by the experiment contract. */
|
|
@@ -69,11 +73,13 @@ export type PierCandidateTrialIdentity = Readonly<AgentCandidateExecutorStopRequ
|
|
|
69
73
|
* Evaluator-owned lifecycle whose stop path works without the process-local
|
|
70
74
|
* handle returned by `start`.
|
|
71
75
|
*/
|
|
72
|
-
export interface PierCandidateTrialController
|
|
76
|
+
export interface PierCandidateTrialController<
|
|
77
|
+
Format extends AgentCandidateExecutionFormat = 'experiment',
|
|
78
|
+
> {
|
|
73
79
|
start(
|
|
74
80
|
staged: StagedPierCandidateExecution,
|
|
75
81
|
context: {
|
|
76
|
-
readonly request: AgentCandidateExecutorRequest
|
|
82
|
+
readonly request: AgentCandidateExecutorRequest<Format>
|
|
77
83
|
readonly traceStore: TraceStore
|
|
78
84
|
readonly signal: AbortSignal
|
|
79
85
|
readonly deadlineAtMs: number
|
|
@@ -114,7 +120,9 @@ export interface PierCandidateGraderPort {
|
|
|
114
120
|
}): Promise<RuntimeGraderResult>
|
|
115
121
|
}
|
|
116
122
|
|
|
117
|
-
export interface ExecutePreparedPierCandidateOptions
|
|
123
|
+
export interface ExecutePreparedPierCandidateOptions<
|
|
124
|
+
Format extends AgentCandidateExecutionFormat = 'experiment',
|
|
125
|
+
> extends StagePreparedPierCandidateOptions<Format> {
|
|
118
126
|
readonly traceStore: TraceStore
|
|
119
127
|
/** Durable one-shot store shared by every process capable of running this benchmark. */
|
|
120
128
|
readonly claimStore: AgentCandidateExecutionClaimStore
|
|
@@ -124,13 +132,13 @@ export interface ExecutePreparedPierCandidateOptions extends StagePreparedPierCa
|
|
|
124
132
|
* Starts exactly one Pier trial synchronously and persists its non-secret
|
|
125
133
|
* process/container identity before returning.
|
|
126
134
|
*/
|
|
127
|
-
readonly controller: PierCandidateTrialController
|
|
135
|
+
readonly controller: PierCandidateTrialController<Format>
|
|
128
136
|
}
|
|
129
137
|
|
|
130
138
|
/** Recovery-only runtime executor for an expired attempt owned by another process. */
|
|
131
|
-
export function createPierCandidateRecoveryExecutor(
|
|
132
|
-
controller: PierCandidateTrialController
|
|
133
|
-
): AgentCandidateExecutorPort {
|
|
139
|
+
export function createPierCandidateRecoveryExecutor<Format extends AgentCandidateExecutionFormat>(
|
|
140
|
+
controller: PierCandidateTrialController<Format>,
|
|
141
|
+
): AgentCandidateExecutorPort<Format> {
|
|
134
142
|
return {
|
|
135
143
|
execute: async () => {
|
|
136
144
|
throw new Error('recovery-only Pier executor cannot start a candidate')
|
|
@@ -279,8 +287,8 @@ async function materializeExecutorFiles(
|
|
|
279
287
|
}
|
|
280
288
|
|
|
281
289
|
function protectedEnvironment(
|
|
282
|
-
prepared: PreparedAgentCandidateExecution
|
|
283
|
-
request: AgentCandidateExecutorRequest
|
|
290
|
+
prepared: PreparedAgentCandidateExecution<AgentCandidateExecutionFormat>,
|
|
291
|
+
request: AgentCandidateExecutorRequest<AgentCandidateExecutionFormat>,
|
|
284
292
|
): Readonly<Record<string, string>> {
|
|
285
293
|
const protectedEntries: Array<readonly [string, string]> = []
|
|
286
294
|
for (const [name, value] of Object.entries(request.launch.env)) {
|
|
@@ -299,14 +307,60 @@ function protectedEnvironment(
|
|
|
299
307
|
return Object.freeze(Object.fromEntries(protectedEntries))
|
|
300
308
|
}
|
|
301
309
|
|
|
310
|
+
async function stageKnowledge(
|
|
311
|
+
directory: string,
|
|
312
|
+
prepared: PreparedAgentCandidateExecution<AgentCandidateExecutionFormat>,
|
|
313
|
+
request: AgentCandidateExecutorRequest<AgentCandidateExecutionFormat>,
|
|
314
|
+
): Promise<string[]> {
|
|
315
|
+
const knowledge = request.knowledge
|
|
316
|
+
const declared = prepared.bundle.knowledge
|
|
317
|
+
if (!knowledge && !declared) return []
|
|
318
|
+
if (!knowledge || !declared || knowledge.snapshot.digest !== declared.snapshot.digest)
|
|
319
|
+
throw new Error('Pier knowledge input differs from the prepared bundle')
|
|
320
|
+
|
|
321
|
+
const { digest: bundleDigest, ...material } = prepared.bundle
|
|
322
|
+
const bundleBytes = Buffer.from(canonicalJson(material), 'utf8')
|
|
323
|
+
if (sha256(bundleBytes) !== bundleDigest)
|
|
324
|
+
throw new Error('Pier bundle bytes do not match their sealed digest')
|
|
325
|
+
const bundlePath = join(directory, 'knowledge-bundle.json')
|
|
326
|
+
const knowledgeDir = join(directory, 'knowledge')
|
|
327
|
+
const files = knowledge.files.map((file) => ({ ...file, path: `files/${file.path}` }))
|
|
328
|
+
const expected = declared.snapshot.material.files.map((file) => ({
|
|
329
|
+
...file,
|
|
330
|
+
path: `files/${file.path}`,
|
|
331
|
+
}))
|
|
332
|
+
if (declared.retrievalConfig && knowledge.retrievalConfig) {
|
|
333
|
+
files.push({ path: 'retrieval.json', mode: 0o644, bytes: knowledge.retrievalConfig })
|
|
334
|
+
expected.push({
|
|
335
|
+
path: 'retrieval.json',
|
|
336
|
+
mode: 0o644,
|
|
337
|
+
sha256: declared.retrievalConfig.sha256,
|
|
338
|
+
byteLength: declared.retrievalConfig.byteLength,
|
|
339
|
+
})
|
|
340
|
+
} else if (declared.retrievalConfig || knowledge.retrievalConfig) {
|
|
341
|
+
throw new Error('Pier retrieval configuration differs from the prepared bundle')
|
|
342
|
+
}
|
|
343
|
+
await materializeExecutorFiles(knowledgeDir, files, expected, 'knowledge executor input')
|
|
344
|
+
// The evaluator-side adapter reads this to verify the snapshot and optional retrieval
|
|
345
|
+
// configuration against the already signed bundle digest. It never enters the container.
|
|
346
|
+
await writeFile(bundlePath, bundleBytes, { mode: 0o600, flag: 'wx' })
|
|
347
|
+
await mkdir(join(knowledgeDir, 'files'), { mode: 0o700, recursive: true })
|
|
348
|
+
return [
|
|
349
|
+
'--agent-kwarg',
|
|
350
|
+
`knowledge_bundle_path=${bundlePath}`,
|
|
351
|
+
'--agent-kwarg',
|
|
352
|
+
`knowledge_dir=${knowledgeDir}`,
|
|
353
|
+
]
|
|
354
|
+
}
|
|
355
|
+
|
|
302
356
|
/**
|
|
303
357
|
* Persist the runtime's exact canonical bytes and return only Pier transport
|
|
304
358
|
* arguments. No benchmark-specific plan or candidate-authored telemetry exists.
|
|
305
359
|
*/
|
|
306
360
|
/** @internal Package-private transport seam exercised by adapter tests. */
|
|
307
361
|
export async function stagePreparedPierCandidateExecution(
|
|
308
|
-
options: StagePreparedPierCandidateOptions
|
|
309
|
-
request: AgentCandidateExecutorRequest
|
|
362
|
+
options: StagePreparedPierCandidateOptions<AgentCandidateExecutionFormat>,
|
|
363
|
+
request: AgentCandidateExecutorRequest<AgentCandidateExecutionFormat>,
|
|
310
364
|
): Promise<StagedPierCandidateExecution> {
|
|
311
365
|
const { prepared } = options
|
|
312
366
|
nonEmpty(options.pierVersion, 'pierVersion')
|
|
@@ -402,6 +456,7 @@ export async function stagePreparedPierCandidateExecution(
|
|
|
402
456
|
if (candidateDirectory !== undefined) {
|
|
403
457
|
agentArgs.push('--agent-kwarg', `candidate_dir=${candidateDirectory}`)
|
|
404
458
|
}
|
|
459
|
+
agentArgs.push(...(await stageKnowledge(directory, prepared, request)))
|
|
405
460
|
|
|
406
461
|
return {
|
|
407
462
|
executionId: request.executionId,
|
|
@@ -428,7 +483,7 @@ function exceptionType(value: unknown): string | undefined {
|
|
|
428
483
|
/** Read only identity and termination from Pier; usage always comes from agent-eval. */
|
|
429
484
|
/** @internal Package-private result parser exercised by adapter tests. */
|
|
430
485
|
export function protectedCaptureFromPierResult(
|
|
431
|
-
request: AgentCandidateExecutorRequest
|
|
486
|
+
request: AgentCandidateExecutorRequest<AgentCandidateExecutionFormat>,
|
|
432
487
|
value: unknown,
|
|
433
488
|
): AgentCandidateProtectedRunCapture {
|
|
434
489
|
const result = record(value, 'Pier trial result') as PierResultLike
|
|
@@ -436,7 +491,7 @@ export function protectedCaptureFromPierResult(
|
|
|
436
491
|
const metadata = record(agentResult.metadata, 'Pier agent_result.metadata')
|
|
437
492
|
const expected = {
|
|
438
493
|
executionId: request.executionId,
|
|
439
|
-
bundleDigest: request.
|
|
494
|
+
bundleDigest: request.materializationReceipt.value.bundleDigest,
|
|
440
495
|
executionPlanDigest: request.executionPlan.value.digest,
|
|
441
496
|
materializationReceiptDigest: request.materializationReceipt.digest,
|
|
442
497
|
}
|
|
@@ -547,10 +602,10 @@ export async function awaitAbortableTrial<T>(
|
|
|
547
602
|
})
|
|
548
603
|
}
|
|
549
604
|
|
|
550
|
-
/**
|
|
551
|
-
export
|
|
552
|
-
options: ExecutePreparedPierCandidateOptions
|
|
553
|
-
):
|
|
605
|
+
/** Bind Pier and its separate verifier to Runtime's prepared experiment cell. */
|
|
606
|
+
export function createPierCandidateExecutionOptions<Format extends AgentCandidateExecutionFormat>(
|
|
607
|
+
options: ExecutePreparedPierCandidateOptions<Format>,
|
|
608
|
+
): ExecutePreparedAgentCandidateOptions<Format> {
|
|
554
609
|
const trials = new Map<
|
|
555
610
|
string,
|
|
556
611
|
{ readonly handle: PierCandidateTrialHandle; result?: PierCandidateTrialResult }
|
|
@@ -558,13 +613,20 @@ export async function executePreparedPierCandidate(
|
|
|
558
613
|
const officialResults = new Map<string, PierCandidateTrialResult>()
|
|
559
614
|
const trialIdentity = (executionId: string, executionPlanDigest: string): string =>
|
|
560
615
|
JSON.stringify([executionId, executionPlanDigest])
|
|
561
|
-
const executor: AgentCandidateExecutorPort = {
|
|
616
|
+
const executor: AgentCandidateExecutorPort<Format> = {
|
|
562
617
|
execute: async (request, context) => {
|
|
563
618
|
context.signal.throwIfAborted()
|
|
619
|
+
if (
|
|
620
|
+
request.executionId !== options.prepared.executionId ||
|
|
621
|
+
request.materializationReceipt.digest !== options.prepared.materializationReceipt.digest
|
|
622
|
+
) {
|
|
623
|
+
throw new Error('Pier executor received a different prepared candidate')
|
|
624
|
+
}
|
|
564
625
|
const staged = await stagePreparedPierCandidateExecution(options, request)
|
|
565
626
|
context.signal.throwIfAborted()
|
|
566
627
|
const identity = trialIdentity(request.executionId, request.executionPlan.value.digest)
|
|
567
628
|
if (trials.has(identity)) throw new Error('Pier trial identity is already active')
|
|
629
|
+
const startedAt = Date.now()
|
|
568
630
|
const trial = options.controller.start(staged, {
|
|
569
631
|
request,
|
|
570
632
|
traceStore: context.traceStore,
|
|
@@ -584,9 +646,26 @@ export async function executePreparedPierCandidate(
|
|
|
584
646
|
}
|
|
585
647
|
trials.set(identity, active)
|
|
586
648
|
const result = sealPierTrialResult(await awaitAbortableTrial(trial, context.signal))
|
|
649
|
+
const endedAt = Math.max(startedAt, Date.now())
|
|
587
650
|
active.result = result
|
|
588
651
|
officialResults.set(request.executionId, result)
|
|
589
|
-
|
|
652
|
+
const capture = protectedCaptureFromPierResult(request, result.value)
|
|
653
|
+
// Custom controllers may already retain a terminal trace. The standard task controller
|
|
654
|
+
// supplies official results; the execution boundary records its observed trial interval.
|
|
655
|
+
if (!(await context.traceStore.getRun(request.trace.runId))) {
|
|
656
|
+
await context.traceStore.appendRun({
|
|
657
|
+
runId: request.trace.runId,
|
|
658
|
+
scenarioId: request.benchmark.task.scenario.id,
|
|
659
|
+
startedAt,
|
|
660
|
+
endedAt,
|
|
661
|
+
status:
|
|
662
|
+
capture.termination.kind === 'exit' && capture.termination.exitCode === 0
|
|
663
|
+
? 'completed'
|
|
664
|
+
: 'failed',
|
|
665
|
+
tags: request.trace.tags,
|
|
666
|
+
})
|
|
667
|
+
}
|
|
668
|
+
return capture
|
|
590
669
|
},
|
|
591
670
|
stop: async (request) => {
|
|
592
671
|
assertTerminationAcknowledged(
|
|
@@ -638,25 +717,34 @@ export async function executePreparedPierCandidate(
|
|
|
638
717
|
run: async (input) => {
|
|
639
718
|
const official = officialResults.get(input.executionId)
|
|
640
719
|
if (!official) throw new Error('Pier official result is missing for executable grading')
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
720
|
+
try {
|
|
721
|
+
return await options.grader.run({
|
|
722
|
+
...input,
|
|
723
|
+
officialResult: {
|
|
724
|
+
value: parseExactJson(official.resultBytes, 'Pier result.json'),
|
|
725
|
+
bytes: Uint8Array.from(official.resultBytes),
|
|
726
|
+
},
|
|
727
|
+
})
|
|
728
|
+
} finally {
|
|
729
|
+
officialResults.delete(input.executionId)
|
|
730
|
+
}
|
|
648
731
|
},
|
|
649
732
|
}
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
claimStore: options.claimStore,
|
|
657
|
-
})
|
|
658
|
-
} finally {
|
|
659
|
-
officialResults.clear()
|
|
660
|
-
trials.clear()
|
|
733
|
+
return {
|
|
734
|
+
executor,
|
|
735
|
+
grader,
|
|
736
|
+
outputArtifacts: options.outputArtifacts,
|
|
737
|
+
traceStore: options.traceStore,
|
|
738
|
+
claimStore: options.claimStore,
|
|
661
739
|
}
|
|
662
740
|
}
|
|
741
|
+
|
|
742
|
+
/** Execute and finalize through the runtime's only gradable candidate path. */
|
|
743
|
+
export async function executePreparedPierCandidate<Format extends AgentCandidateExecutionFormat>(
|
|
744
|
+
options: ExecutePreparedPierCandidateOptions<Format>,
|
|
745
|
+
): Promise<AgentCandidateRunFinalization> {
|
|
746
|
+
return await executePreparedAgentCandidate(
|
|
747
|
+
options.prepared,
|
|
748
|
+
createPierCandidateExecutionOptions(options),
|
|
749
|
+
)
|
|
750
|
+
}
|
|
@@ -11,7 +11,7 @@ import type { AgentCandidateExecutorRequest } from '@tangle-network/agent-runtim
|
|
|
11
11
|
import { InMemoryTraceStore } from '@tangle-network/agent-eval'
|
|
12
12
|
|
|
13
13
|
import { createStagedPierCandidateExecutionFixture } from './pier-agent.test-fixtures.mts'
|
|
14
|
-
import { FilePierCandidateTrialController } from './pier-trial-controller'
|
|
14
|
+
import { createPierTaskTrialController, FilePierCandidateTrialController } from './pier-trial-controller'
|
|
15
15
|
|
|
16
16
|
// Process identity and restart recovery require Linux /proc start-time receipts.
|
|
17
17
|
const execFileAsync = promisify(execFile)
|
|
@@ -31,6 +31,53 @@ function testRequest(executionId: string, executionPlanDigest: `sha256:${string}
|
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
test('launches a configured task and reopens its exact Pier files after restart', { skip: process.platform !== 'linux' }, async () => {
|
|
35
|
+
const root = await mkdtemp(path.join(tmpdir(), 'pier-task-trial-'))
|
|
36
|
+
const task = path.join(root, 'approved-task')
|
|
37
|
+
const jobsDirectory = path.join(root, 'jobs')
|
|
38
|
+
const command = path.join(root, 'pier.mjs')
|
|
39
|
+
const fakeDocker = path.join(root, 'docker')
|
|
40
|
+
const taskDigest = `sha256:${'a'.repeat(64)}` as const
|
|
41
|
+
const { staged, context } = testRequest('approved-task', `sha256:${'b'.repeat(64)}`)
|
|
42
|
+
Object.assign(context.request, { benchmark: { task: { digest: taskDigest } } })
|
|
43
|
+
let handle: ReturnType<FilePierCandidateTrialController['start']> | undefined
|
|
44
|
+
try {
|
|
45
|
+
await mkdir(task)
|
|
46
|
+
await writeFile(fakeDocker, '#!/bin/sh\nexit 0\n', { mode: 0o700 })
|
|
47
|
+
await writeFile(command, `import assert from 'node:assert/strict';
|
|
48
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
49
|
+
import { join } from 'node:path';
|
|
50
|
+
const args = process.argv.slice(2);
|
|
51
|
+
const option = (name) => args[args.indexOf(name) + 1];
|
|
52
|
+
assert.equal(args[0], 'run');
|
|
53
|
+
assert.equal(option('--path'), ${JSON.stringify(task)});
|
|
54
|
+
assert.equal(option('--env'), 'docker');
|
|
55
|
+
assert.equal(option('--n-attempts'), '1');
|
|
56
|
+
assert.equal(option('--max-retries'), '0');
|
|
57
|
+
const dir = join(option('--jobs-dir'), option('--job-name'), 'approved-task__trial');
|
|
58
|
+
mkdirSync(join(dir, 'artifacts'), { recursive: true });
|
|
59
|
+
writeFileSync(join(dir, 'result.json'), '{"trial_name":"approved-task__trial"}\\n');
|
|
60
|
+
writeFileSync(join(dir, 'artifacts', 'model.patch'), 'retained patch\\n');
|
|
61
|
+
`)
|
|
62
|
+
const options = {
|
|
63
|
+
directory: path.join(root, 'controller'),
|
|
64
|
+
jobsDirectory,
|
|
65
|
+
maxEvidenceBytes: 1024,
|
|
66
|
+
tasks: [{ taskDigest, directory: task }],
|
|
67
|
+
command: { command: process.execPath, cwd: root, env: {}, prefix: [command], dockerCommand: fakeDocker },
|
|
68
|
+
}
|
|
69
|
+
const controller = createPierTaskTrialController(options)
|
|
70
|
+
handle = controller.start(staged, context)
|
|
71
|
+
const result = await handle.result
|
|
72
|
+
assert.equal(Buffer.from(result.resultBytes).toString(), '{"trial_name":"approved-task__trial"}\n')
|
|
73
|
+
assert.equal(Buffer.from(result.taskPatch).toString(), 'retained patch\n')
|
|
74
|
+
assert.deepEqual(await createPierTaskTrialController(options).captureResult(handle.identity), result)
|
|
75
|
+
} finally {
|
|
76
|
+
if (handle) await handle.terminateAndWait()
|
|
77
|
+
await rm(root, { recursive: true, force: true })
|
|
78
|
+
}
|
|
79
|
+
})
|
|
80
|
+
|
|
34
81
|
test('an existing Pier job is rejected without deleting or starting it', async () => {
|
|
35
82
|
const root = await mkdtemp(path.join(tmpdir(), 'pier-controller-scope-'))
|
|
36
83
|
const controlRoot = path.join(root, 'control')
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
closeSync,
|
|
7
7
|
constants,
|
|
8
8
|
existsSync,
|
|
9
|
+
fstatSync,
|
|
9
10
|
fsyncSync,
|
|
10
11
|
lstatSync,
|
|
11
12
|
mkdirSync,
|
|
@@ -21,7 +22,10 @@ import { isAbsolute, join, resolve } from 'node:path'
|
|
|
21
22
|
import { fileURLToPath } from 'node:url'
|
|
22
23
|
import type { Writable } from 'node:stream'
|
|
23
24
|
|
|
24
|
-
import type {
|
|
25
|
+
import type {
|
|
26
|
+
AgentCandidateExecutionFormat,
|
|
27
|
+
AgentCandidateExecutorRequest,
|
|
28
|
+
} from '@tangle-network/agent-runtime/candidate-execution'
|
|
25
29
|
|
|
26
30
|
import type { TraceStore } from '@tangle-network/agent-eval'
|
|
27
31
|
|
|
@@ -96,13 +100,15 @@ export interface PierDockerConnection {
|
|
|
96
100
|
readonly env: Readonly<Record<string, string | undefined>>
|
|
97
101
|
}
|
|
98
102
|
|
|
99
|
-
export interface FilePierCandidateTrialControllerOptions
|
|
103
|
+
export interface FilePierCandidateTrialControllerOptions<
|
|
104
|
+
Format extends AgentCandidateExecutionFormat = 'experiment',
|
|
105
|
+
> {
|
|
100
106
|
/** Shared evaluator-owned control root, available to crash-recovery workers. */
|
|
101
107
|
readonly directory: string
|
|
102
108
|
readonly launch?: (
|
|
103
109
|
staged: StagedPierCandidateExecution,
|
|
104
110
|
context: {
|
|
105
|
-
readonly request: AgentCandidateExecutorRequest
|
|
111
|
+
readonly request: AgentCandidateExecutorRequest<Format>
|
|
106
112
|
readonly traceStore: TraceStore
|
|
107
113
|
readonly signal: AbortSignal
|
|
108
114
|
readonly deadlineAtMs: number
|
|
@@ -119,6 +125,111 @@ export interface FilePierCandidateTrialControllerOptions {
|
|
|
119
125
|
readonly pollIntervalMs?: number
|
|
120
126
|
}
|
|
121
127
|
|
|
128
|
+
export interface CreatePierTaskTrialControllerOptions {
|
|
129
|
+
readonly directory: string
|
|
130
|
+
readonly jobsDirectory: string
|
|
131
|
+
/** Maximum bytes for each retained official result and patch file. */
|
|
132
|
+
readonly maxEvidenceBytes: number
|
|
133
|
+
/** Evaluator-owned task directories, keyed by the already approved Runtime task digest. */
|
|
134
|
+
readonly tasks: readonly { readonly taskDigest: `sha256:${string}`; readonly directory: string }[]
|
|
135
|
+
/** The pinned Pier executable, or its interpreter and prefix arguments ending at `pier`. */
|
|
136
|
+
readonly command: Pick<PierCandidateProcessSpec, 'command' | 'cwd' | 'env' | 'dockerCommand'> & {
|
|
137
|
+
readonly prefix?: readonly string[]
|
|
138
|
+
}
|
|
139
|
+
readonly dockerConnection?: PierDockerConnection
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Run one approved Pier task and reopen its official result through the durable controller. */
|
|
143
|
+
export function createPierTaskTrialController<
|
|
144
|
+
Format extends AgentCandidateExecutionFormat = 'experiment',
|
|
145
|
+
>(options: CreatePierTaskTrialControllerOptions): FilePierCandidateTrialController<Format> {
|
|
146
|
+
const jobsDirectory = absolutePath(options.jobsDirectory, 'Pier jobs directory')
|
|
147
|
+
const { maxEvidenceBytes } = options
|
|
148
|
+
if (!Number.isSafeInteger(maxEvidenceBytes) || maxEvidenceBytes < 1) {
|
|
149
|
+
throw new Error('Pier evidence limit must be a positive safe integer')
|
|
150
|
+
}
|
|
151
|
+
const tasks = new Map<string, string>()
|
|
152
|
+
for (const { taskDigest, directory } of options.tasks) {
|
|
153
|
+
if (!sha256Pattern.test(taskDigest) || tasks.has(taskDigest)) {
|
|
154
|
+
throw new Error('Pier task directories require distinct approved SHA-256 task digests')
|
|
155
|
+
}
|
|
156
|
+
tasks.set(taskDigest, absolutePath(directory, 'Pier task directory'))
|
|
157
|
+
}
|
|
158
|
+
const { prefix = [], env, ...command } = options.command
|
|
159
|
+
const argumentsPrefix = [...prefix]
|
|
160
|
+
const environment = { ...env }
|
|
161
|
+
const readResult = async ({ jobsDirectory, jobName }: { jobsDirectory: string; jobName: string }) =>
|
|
162
|
+
readOfficialTrial(join(jobsDirectory, jobName), maxEvidenceBytes)
|
|
163
|
+
return new FilePierCandidateTrialController<Format>({
|
|
164
|
+
directory: options.directory,
|
|
165
|
+
dockerConnection: options.dockerConnection,
|
|
166
|
+
readResult,
|
|
167
|
+
launch(staged, { request }) {
|
|
168
|
+
const task = tasks.get(request.benchmark.task.digest)
|
|
169
|
+
if (!task) throw new Error('Pier has no directory for this approved task')
|
|
170
|
+
assertRealDirectory(task, 'Pier task directory')
|
|
171
|
+
const jobName = `candidate-${trialKey({
|
|
172
|
+
executionId: request.executionId,
|
|
173
|
+
executionPlanDigest: request.executionPlan.value.digest,
|
|
174
|
+
})}`
|
|
175
|
+
return {
|
|
176
|
+
...command,
|
|
177
|
+
args: [
|
|
178
|
+
...argumentsPrefix,
|
|
179
|
+
'run', '--path', task,
|
|
180
|
+
...staged.agentArgs,
|
|
181
|
+
...staged.attemptArgs,
|
|
182
|
+
...Object.keys(staged.evaluatorEnv).flatMap((name) => ['--agent-env', `${name}=\${${name}}`]),
|
|
183
|
+
'--env', 'docker', '--job-name', jobName, '--jobs-dir', jobsDirectory,
|
|
184
|
+
'--n-concurrent', '1', '--quiet',
|
|
185
|
+
],
|
|
186
|
+
env: { ...environment, ...staged.evaluatorEnv },
|
|
187
|
+
jobsDirectory,
|
|
188
|
+
jobName,
|
|
189
|
+
readResult: async () => {
|
|
190
|
+
const result = await readResult({ jobsDirectory, jobName })
|
|
191
|
+
if (!result) throw new Error('Pier emitted no official trial result')
|
|
192
|
+
return result
|
|
193
|
+
},
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
})
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function readOfficialTrial(directory: string, maxEvidenceBytes: number): PierCandidateTrialResult | undefined {
|
|
200
|
+
if (!existsSync(directory)) return undefined
|
|
201
|
+
assertRealDirectory(directory, 'Pier job directory')
|
|
202
|
+
let result: PierCandidateTrialResult | undefined
|
|
203
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
204
|
+
if (!entry.isDirectory()) continue
|
|
205
|
+
const trial = join(directory, entry.name)
|
|
206
|
+
const resultPath = join(trial, 'result.json')
|
|
207
|
+
if (!existsSync(resultPath)) continue
|
|
208
|
+
const resultBytes = readOfficialTrialFile(resultPath, maxEvidenceBytes)
|
|
209
|
+
const value: unknown = JSON.parse(resultBytes.toString('utf8'))
|
|
210
|
+
if (value === null || typeof value !== 'object' || !('trial_name' in value) || typeof value.trial_name !== 'string') {
|
|
211
|
+
throw new Error('Pier emitted a malformed official trial result')
|
|
212
|
+
}
|
|
213
|
+
if (result) throw new Error('Expected one official result for the approved Pier task')
|
|
214
|
+
const artifacts = join(trial, 'artifacts')
|
|
215
|
+
assertRealDirectory(artifacts, 'Pier trial artifacts directory')
|
|
216
|
+
result = { value, resultBytes, taskPatch: readOfficialTrialFile(join(artifacts, 'model.patch'), maxEvidenceBytes) }
|
|
217
|
+
}
|
|
218
|
+
return result
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function readOfficialTrialFile(path: string, maxEvidenceBytes: number): Buffer {
|
|
222
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
|
|
223
|
+
try {
|
|
224
|
+
const evidence = fstatSync(fd)
|
|
225
|
+
if (!evidence.isFile()) throw new Error('Pier trial evidence must be a regular file')
|
|
226
|
+
if (evidence.size > maxEvidenceBytes) throw new Error('Pier trial evidence exceeds its configured limit')
|
|
227
|
+
return readFileSync(fd)
|
|
228
|
+
} finally {
|
|
229
|
+
closeSync(fd)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
122
233
|
function nonEmpty(value: string, label: string): string {
|
|
123
234
|
if (!value || value.includes('\0')) throw new Error(`${label} must be non-empty without NUL`)
|
|
124
235
|
return value
|
|
@@ -506,15 +617,17 @@ function assertRealDirectory(path: string, label: string): void {
|
|
|
506
617
|
}
|
|
507
618
|
}
|
|
508
619
|
|
|
509
|
-
export class FilePierCandidateTrialController
|
|
620
|
+
export class FilePierCandidateTrialController<
|
|
621
|
+
Format extends AgentCandidateExecutionFormat = 'experiment',
|
|
622
|
+
> implements PierCandidateTrialController<Format> {
|
|
510
623
|
private readonly directory: string
|
|
511
|
-
private readonly launch?: NonNullable<FilePierCandidateTrialControllerOptions['launch']>
|
|
512
|
-
private readonly readResult?: NonNullable<FilePierCandidateTrialControllerOptions['readResult']>
|
|
624
|
+
private readonly launch?: NonNullable<FilePierCandidateTrialControllerOptions<Format>['launch']>
|
|
625
|
+
private readonly readResult?: NonNullable<FilePierCandidateTrialControllerOptions<Format>['readResult']>
|
|
513
626
|
private readonly dockerConnection: PierDockerConnection
|
|
514
627
|
private readonly supervisorPath: string
|
|
515
628
|
private readonly pollIntervalMs: number
|
|
516
629
|
|
|
517
|
-
constructor(options: FilePierCandidateTrialControllerOptions) {
|
|
630
|
+
constructor(options: FilePierCandidateTrialControllerOptions<Format>) {
|
|
518
631
|
this.directory = absolutePath(options.directory, 'Pier controller directory')
|
|
519
632
|
this.launch = options.launch
|
|
520
633
|
this.readResult = options.readResult
|
|
@@ -548,7 +661,7 @@ export class FilePierCandidateTrialController implements PierCandidateTrialContr
|
|
|
548
661
|
start(
|
|
549
662
|
staged: StagedPierCandidateExecution,
|
|
550
663
|
context: {
|
|
551
|
-
readonly request: AgentCandidateExecutorRequest
|
|
664
|
+
readonly request: AgentCandidateExecutorRequest<Format>
|
|
552
665
|
readonly traceStore: TraceStore
|
|
553
666
|
readonly signal: AbortSignal
|
|
554
667
|
readonly deadlineAtMs: number
|
package/src/published.test.mts
CHANGED
|
@@ -14,12 +14,16 @@ import { tmpdir } from 'node:os'
|
|
|
14
14
|
import path from 'node:path'
|
|
15
15
|
import test from 'node:test'
|
|
16
16
|
import { validateRunRecord } from '@tangle-network/agent-eval'
|
|
17
|
-
import { runPublished, PUBLISHED_BENCHMARKS } from './published'
|
|
17
|
+
import { runPublished, PUBLISHED_BENCHMARKS, type PublishedRun } from './published'
|
|
18
18
|
|
|
19
19
|
const TASK = 'simple.email_sf_contact_phone_update'
|
|
20
20
|
let uv = true
|
|
21
21
|
try { execFileSync('uv', ['--version'], { stdio: 'ignore' }) } catch { uv = false }
|
|
22
22
|
|
|
23
|
+
function assertGoldTask({ taskScores }: PublishedRun) {
|
|
24
|
+
assert.deepEqual(taskScores.map(({ id, passed, score }) => ({ id, passed, score })), [{ id: TASK, passed: true, score: 1 }])
|
|
25
|
+
}
|
|
26
|
+
|
|
23
27
|
/** One chat-completions answer: the gold tool call first, then a closing message; or a closing message alone. */
|
|
24
28
|
function standIn(gold: boolean) {
|
|
25
29
|
const requests: Array<{ tools: number; messages: number }> = []
|
|
@@ -62,7 +66,8 @@ async function run(gold: boolean, cacheDir: string) {
|
|
|
62
66
|
env: { AGENT_BENCH_ROUTER_URL: `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`, TANGLE_API_KEY: 'local-stand-in' },
|
|
63
67
|
})
|
|
64
68
|
const runRecords = (await readFile(result.runRecords, 'utf8')).trim().split('\n').map((line) => JSON.parse(line) as Record<string, unknown>)
|
|
65
|
-
|
|
69
|
+
const publisher = JSON.parse(await readFile(result.resultPath, 'utf8'))
|
|
70
|
+
return { result, requests, record: JSON.parse(await readFile(path.join(out, 'automationbench-run.json'), 'utf8')), runRecords, publisher }
|
|
66
71
|
} finally {
|
|
67
72
|
server.close()
|
|
68
73
|
await rm(out, { recursive: true, force: true })
|
|
@@ -74,7 +79,7 @@ test('AutomationBench: the publisher\'s grader passes the gold tool call and fai
|
|
|
74
79
|
try {
|
|
75
80
|
const gold = await run(true, cacheDir)
|
|
76
81
|
assert.equal(gold.result.tasks, 1)
|
|
77
|
-
|
|
82
|
+
assertGoldTask(gold.result)
|
|
78
83
|
assert.equal(gold.result.measured, 'model-shaped')
|
|
79
84
|
assert.equal(gold.result.official, true)
|
|
80
85
|
assert.equal(gold.result.ref, PUBLISHED_BENCHMARKS.automationbench!.ref)
|
|
@@ -89,6 +94,12 @@ test('AutomationBench: the publisher\'s grader passes the gold tool call and fai
|
|
|
89
94
|
assert.equal(row.outcome.raw.passed, 1)
|
|
90
95
|
assert.equal(row.candidateId, 'model:stand-in-model')
|
|
91
96
|
assert.deepEqual([row.model, row.terminalOutcome, row.costUsd], ['unknown', 'unknown', null])
|
|
97
|
+
const publisher = gold.publisher.tasks[0]
|
|
98
|
+
assert.ok(publisher.input_tokens > 0 && publisher.output_tokens > 0)
|
|
99
|
+
assert.equal(row.outcome.raw.publisherInputTokens, publisher.input_tokens)
|
|
100
|
+
assert.equal(row.outcome.raw.publisherOutputTokens, publisher.output_tokens)
|
|
101
|
+
assert.equal(row.outcome.raw.publisherEstimatedCostUsd, publisher.cost)
|
|
102
|
+
assert.equal(row.tokenUsage.tokensKnown, false)
|
|
92
103
|
|
|
93
104
|
const none = await run(false, cacheDir)
|
|
94
105
|
assert.equal(none.result.tasks, 1)
|
|
@@ -188,12 +199,15 @@ test('AutomationBench on profile and app targets: its runner drives a harness lo
|
|
|
188
199
|
}
|
|
189
200
|
const result = await runPublished('automationbench', 'profile:claude-code/own-loop-peer', { ...options, out: path.join(out, 'profile') })
|
|
190
201
|
assert.equal(result.measured, 'own-loop')
|
|
191
|
-
|
|
202
|
+
assertGoldTask(result)
|
|
203
|
+
const [publisherTask] = JSON.parse(await readFile(result.resultPath, 'utf8')).tasks
|
|
204
|
+
assert.equal(result.taskScores[0]?.raw?.publisherInputTokens, publisherTask.input_tokens)
|
|
205
|
+
assert.equal(result.taskScores[0]?.raw?.publisherOutputTokens, publisherTask.output_tokens)
|
|
192
206
|
|
|
193
207
|
const apps = JSON.stringify({ 'bench-app': `http://127.0.0.1:${(appServer.address() as AddressInfo).port}/api/tools/profile?definition` })
|
|
194
208
|
const app = await runPublished('automationbench', 'app:bench-app@claude-code/app-peer', { ...options, env: { ...options.env, AGENT_BENCH_APPS: apps }, out: path.join(out, 'app') })
|
|
195
209
|
assert.equal(app.measured, 'own-loop')
|
|
196
|
-
|
|
210
|
+
assertGoldTask(app)
|
|
197
211
|
assert.equal(app.model, 'claude-code/app-peer')
|
|
198
212
|
assert.equal(app.app?.app, 'bench-app')
|
|
199
213
|
assert.equal(app.app?.profileVersion, '1.0.0')
|
|
@@ -205,7 +219,7 @@ test('AutomationBench on profile and app targets: its runner drives a harness lo
|
|
|
205
219
|
const file = path.join(root, 'bench-app-profile.json')
|
|
206
220
|
await writeFile(file, JSON.stringify(served))
|
|
207
221
|
const fromFile = await runPublished('automationbench', 'app:bench-app@claude-code/app-peer', { ...options, env: { ...options.env, AGENT_BENCH_APPS: JSON.stringify({ 'bench-app': file }) }, out: path.join(out, 'app-file') })
|
|
208
|
-
|
|
222
|
+
assertGoldTask(fromFile)
|
|
209
223
|
assert.equal(fromFile.app?.profileDigest, app.app?.profileDigest)
|
|
210
224
|
assert.equal(fromFile.app?.profileUrl, file)
|
|
211
225
|
} finally {
|
|
@@ -339,6 +353,15 @@ test('Harvey LAB: the publisher\'s harness and rubric grader, with a substituted
|
|
|
339
353
|
assert.equal(result.taskScores[0]!.raw?.['crit.C-001'], gold ? 1 : 0)
|
|
340
354
|
const row = validateRunRecord(JSON.parse((await readFile(result.runRecords, 'utf8')).trim()))
|
|
341
355
|
assert.equal(row.outcome.raw['crit.C-001'], gold ? 1 : 0)
|
|
356
|
+
const [runId] = (await readFile(path.join(result.resultPath, 'tasks.tsv'), 'utf8')).split('\t')
|
|
357
|
+
assert.ok(runId)
|
|
358
|
+
const metrics = JSON.parse(await readFile(path.join(result.resultPath, runId, 'metrics.json'), 'utf8'))
|
|
359
|
+
assert.ok(metrics.input_tokens > 0 && metrics.output_tokens > 0)
|
|
360
|
+
assert.deepEqual(row.tokenUsage, {
|
|
361
|
+
input: metrics.input_tokens, output: metrics.output_tokens, tokensKnown: false,
|
|
362
|
+
})
|
|
363
|
+
assert.equal(row.outcome.raw.publisherAgentWallMs, metrics.wall_clock_seconds * 1_000)
|
|
364
|
+
assert.equal(row.costUsd, null)
|
|
342
365
|
} finally {
|
|
343
366
|
server.closeAllConnections()
|
|
344
367
|
server.close()
|