@tangle-network/agent-bench 3.0.0 → 4.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.
@@ -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 { AgentCandidateExecutorRequest } from '@tangle-network/agent-runtime/candidate-execution'
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 implements PierCandidateTrialController {
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