@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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.0.0
4
+
5
+ Bench's public candidate-execution types move to Runtime 11. Consumers that
6
+ import Runtime types alongside Bench should use the same major.
7
+
8
+ Pier can run an exact candidate from a standalone train or selection admission. The transport verifies the signed search, cell, and workspace identities before staging and retains the same protected results used by paired experiments.
9
+
3
10
  ## 3.0.0
4
11
 
5
12
  Breaking: every adapter is now agent-eval's `BenchmarkAdapter` (agent-eval `^2.0.11`), the one benchmark contract, and agent-bench's own `BenchmarkAdapter`, `BenchScore` and the old `BenchTask` shape are gone.
package/README.md CHANGED
@@ -113,9 +113,17 @@ The judge is a model call, so its score records the exact judge turn usage on `B
113
113
  ## Pier custom candidates
114
114
 
115
115
  The package executes a branded `PreparedAgentCandidateExecution` from `@tangle-network/agent-runtime` through one atomic API and ships `pier_agents.tangle_candidate:TangleCandidateAgent` as its thin Pier transport.
116
+ Use `createPierCandidateExecutionOptions` in Runtime's `placeCell` execution callback to run sealed experiment cells through this transport.
117
+ For a standalone train or selection cell, pass the same factory to
118
+ `executeAgentCandidateSearchCell` as its `execution` callback and use a
119
+ `FilePierCandidateTrialController<'search'>`. The transport preserves the
120
+ admitted search identity through the verifier. Final assessment uses paired
121
+ experiment evidence.
116
122
  The executor recreates every input from runtime-verified file bytes and reveals model credentials only inside the claimed execution callback.
123
+ An experiment can execute a code workspace, a materialized profile, and a measured Knowledge snapshot together. Pier checks the Knowledge files and optional retrieval configuration against the sealed bundle and excludes its own injected paths from the task patch.
117
124
  Pier owns the task container and verifier; protected model usage and traces stay in `@tangle-network/agent-eval` and are finalized by the shared runtime.
118
125
  `FilePierCandidateTrialController` atomically reserves a unique Pier job, then persists the supervisor PID, process-session identity, and that job's exact Docker projects so a fresh evaluator process can stop and remove an abandoned trial.
126
+ Use `createPierTaskTrialController` when each approved task digest already maps to an evaluator-owned Pier task directory. Give it the pinned Pier command and jobs directory. It launches exactly that task and reads the official result and patch through the same controller on completion or recovery. The evaluator still owns task staging and authorization.
119
127
  Run `PIER_REPO=/path/to/pier pnpm verify:pier` for the zero-model failure/pass and fresh-process recovery proof, and see `HARNESS.md` for the exact invocation and failure contract.
120
128
  From an installed npm package, expose the shipped Python module with `export PYTHONPATH="$(npm root)/@tangle-network/agent-bench${PYTHONPATH:+:$PYTHONPATH}"` before invoking Pier.
121
129
 
package/dist/index.d.ts CHANGED
@@ -11,7 +11,7 @@ import { BenchEvaluation, BenchPayload, BenchRuntime, BenchTask, JudgeArtifactFi
11
11
  import { AgentProfile, SandboxClient, SandboxRun, TurnResult, sumSandboxUsage } from "@tangle-network/agent-runtime/kernel";
12
12
  import { RunTerminalOutcome, TraceStore } from "@tangle-network/agent-eval";
13
13
  import { SandboxEvent } from "@tangle-network/sandbox";
14
- import { AgentCandidateBenchmarkGraderPort, AgentCandidateExecutionClaimStore, AgentCandidateExecutorPort, AgentCandidateExecutorRequest, AgentCandidateExecutorStopRequest, AgentCandidateOutputArtifactPort, AgentCandidateRunFinalization, PreparedAgentCandidateExecution } from "@tangle-network/agent-runtime/candidate-execution";
14
+ import { AgentCandidateBenchmarkGraderPort, AgentCandidateExecutionClaimStore, AgentCandidateExecutionFormat, AgentCandidateExecutorPort, AgentCandidateExecutorRequest, AgentCandidateExecutorStopRequest, AgentCandidateOutputArtifactPort, AgentCandidateRunFinalization, ExecutePreparedAgentCandidateOptions, PreparedAgentCandidateExecution } from "@tangle-network/agent-runtime/candidate-execution";
15
15
  interface ResolveBenchClientOptions {
16
16
  /** The selector (the `BACKEND` env value): `router` = off-box; anything else = in-box Sandbox. */
17
17
  backend: string;
@@ -197,8 +197,8 @@ interface RunBenchmarksReport {
197
197
  export declare function runBenchmarks(opts: RunBenchmarksOptions): Promise<RunBenchmarksReport>;
198
198
  /** Render the leaderboard as a fixed-width table for a CLI/log. */
199
199
  export declare function printBenchmarksReport(report: RunBenchmarksReport): string;
200
- interface StagePreparedPierCandidateOptions {
201
- readonly prepared: PreparedAgentCandidateExecution;
200
+ interface StagePreparedPierCandidateOptions<Format extends AgentCandidateExecutionFormat = 'experiment'> {
201
+ readonly prepared: PreparedAgentCandidateExecution<Format>;
202
202
  /** Evaluator-owned directory persisted with the Pier trial. */
203
203
  readonly directory: string;
204
204
  /** Exact Pier package version pinned by the experiment contract. */
@@ -237,9 +237,9 @@ type PierCandidateTrialIdentity = Readonly<AgentCandidateExecutorStopRequest>;
237
237
  * Evaluator-owned lifecycle whose stop path works without the process-local
238
238
  * handle returned by `start`.
239
239
  */
240
- interface PierCandidateTrialController {
240
+ interface PierCandidateTrialController<Format extends AgentCandidateExecutionFormat = 'experiment'> {
241
241
  start(staged: StagedPierCandidateExecution, context: {
242
- readonly request: AgentCandidateExecutorRequest;
242
+ readonly request: AgentCandidateExecutorRequest<Format>;
243
243
  readonly traceStore: TraceStore;
244
244
  readonly signal: AbortSignal;
245
245
  readonly deadlineAtMs: number;
@@ -272,7 +272,7 @@ interface PierCandidateGraderPort {
272
272
  readonly officialResult: PierCandidateOfficialResult;
273
273
  }): Promise<RuntimeGraderResult>;
274
274
  }
275
- interface ExecutePreparedPierCandidateOptions extends StagePreparedPierCandidateOptions {
275
+ interface ExecutePreparedPierCandidateOptions<Format extends AgentCandidateExecutionFormat = 'experiment'> extends StagePreparedPierCandidateOptions<Format> {
276
276
  readonly traceStore: TraceStore;
277
277
  /** Durable one-shot store shared by every process capable of running this benchmark. */
278
278
  readonly claimStore: AgentCandidateExecutionClaimStore;
@@ -282,12 +282,14 @@ interface ExecutePreparedPierCandidateOptions extends StagePreparedPierCandidate
282
282
  * Starts exactly one Pier trial synchronously and persists its non-secret
283
283
  * process/container identity before returning.
284
284
  */
285
- readonly controller: PierCandidateTrialController;
285
+ readonly controller: PierCandidateTrialController<Format>;
286
286
  }
287
287
  /** Recovery-only runtime executor for an expired attempt owned by another process. */
288
- export declare function createPierCandidateRecoveryExecutor(controller: PierCandidateTrialController): AgentCandidateExecutorPort;
288
+ export declare function createPierCandidateRecoveryExecutor<Format extends AgentCandidateExecutionFormat>(controller: PierCandidateTrialController<Format>): AgentCandidateExecutorPort<Format>;
289
+ /** Bind Pier and its separate verifier to Runtime's prepared experiment cell. */
290
+ export declare function createPierCandidateExecutionOptions<Format extends AgentCandidateExecutionFormat>(options: ExecutePreparedPierCandidateOptions<Format>): ExecutePreparedAgentCandidateOptions<Format>;
289
291
  /** Execute and finalize through the runtime's only gradable candidate path. */
290
- export declare function executePreparedPierCandidate(options: ExecutePreparedPierCandidateOptions): Promise<AgentCandidateRunFinalization>;
292
+ export declare function executePreparedPierCandidate<Format extends AgentCandidateExecutionFormat>(options: ExecutePreparedPierCandidateOptions<Format>): Promise<AgentCandidateRunFinalization>;
291
293
  interface PierCandidateProcessSpec {
292
294
  /** Returns launch data only. The controller, not this callback, starts the process. */
293
295
  readonly command: string;
@@ -308,11 +310,11 @@ interface PierDockerConnection {
308
310
  /** Exact variables needed by both Pier and Docker cleanup; values are never persisted. */
309
311
  readonly env: Readonly<Record<string, string | undefined>>;
310
312
  }
311
- interface FilePierCandidateTrialControllerOptions {
313
+ interface FilePierCandidateTrialControllerOptions<Format extends AgentCandidateExecutionFormat = 'experiment'> {
312
314
  /** Shared evaluator-owned control root, available to crash-recovery workers. */
313
315
  readonly directory: string;
314
316
  readonly launch?: (staged: StagedPierCandidateExecution, context: {
315
- readonly request: AgentCandidateExecutorRequest;
317
+ readonly request: AgentCandidateExecutorRequest<Format>;
316
318
  readonly traceStore: TraceStore;
317
319
  readonly signal: AbortSignal;
318
320
  readonly deadlineAtMs: number;
@@ -327,16 +329,34 @@ interface FilePierCandidateTrialControllerOptions {
327
329
  readonly supervisorPath?: string;
328
330
  readonly pollIntervalMs?: number;
329
331
  }
330
- export declare class FilePierCandidateTrialController implements PierCandidateTrialController {
332
+ interface CreatePierTaskTrialControllerOptions {
333
+ readonly directory: string;
334
+ readonly jobsDirectory: string;
335
+ /** Maximum bytes for each retained official result and patch file. */
336
+ readonly maxEvidenceBytes: number;
337
+ /** Evaluator-owned task directories, keyed by the already approved Runtime task digest. */
338
+ readonly tasks: readonly {
339
+ readonly taskDigest: `sha256:${string}`;
340
+ readonly directory: string;
341
+ }[];
342
+ /** The pinned Pier executable, or its interpreter and prefix arguments ending at `pier`. */
343
+ readonly command: Pick<PierCandidateProcessSpec, 'command' | 'cwd' | 'env' | 'dockerCommand'> & {
344
+ readonly prefix?: readonly string[];
345
+ };
346
+ readonly dockerConnection?: PierDockerConnection;
347
+ }
348
+ /** Run one approved Pier task and reopen its official result through the durable controller. */
349
+ export declare function createPierTaskTrialController<Format extends AgentCandidateExecutionFormat = 'experiment'>(options: CreatePierTaskTrialControllerOptions): FilePierCandidateTrialController<Format>;
350
+ export declare class FilePierCandidateTrialController<Format extends AgentCandidateExecutionFormat = 'experiment'> implements PierCandidateTrialController<Format> {
331
351
  private readonly directory;
332
352
  private readonly launch?;
333
353
  private readonly readResult?;
334
354
  private readonly dockerConnection;
335
355
  private readonly supervisorPath;
336
356
  private readonly pollIntervalMs;
337
- constructor(options: FilePierCandidateTrialControllerOptions);
357
+ constructor(options: FilePierCandidateTrialControllerOptions<Format>);
338
358
  start(staged: StagedPierCandidateExecution, context: {
339
- readonly request: AgentCandidateExecutorRequest;
359
+ readonly request: AgentCandidateExecutorRequest<Format>;
340
360
  readonly traceStore: TraceStore;
341
361
  readonly signal: AbortSignal;
342
362
  readonly deadlineAtMs: number;
@@ -350,5 +370,5 @@ export declare class FilePierCandidateTrialController implements PierCandidateTr
350
370
  private forceRecovery;
351
371
  }
352
372
  export declare function createPierResultGrader(descriptor: Pick<PierCandidateGraderPort, 'name' | 'version' | 'artifact'>): PierCandidateGraderPort;
353
- export { ADAPTERS, type BenchCell, type BenchCellTaskResult, type BenchEvaluation, type BenchExecution, type BenchExecutionContext, type BenchLeaderboardRow, type BenchPayload, type BenchPromptResult, type BenchRuntime, type BenchShot, type BenchShotResult, type BenchTask, type ExecutePreparedPierCandidateOptions, FINAL_ANSWER_SENTINEL, type FilePierCandidateTrialControllerOptions, type JudgeArtifactFileReceipt, type JudgeArtifactReceipt, type LoadOptions, type PierCandidateGraderPort, type PierCandidateOfficialResult, type PierCandidateProcessSpec, type PierCandidateTerminationAcknowledgement, type PierCandidateTrialController, type PierCandidateTrialHandle, type PierCandidateTrialIdentity, type PierCandidateTrialResult, type PierDockerConnection, type RagAnswerScore, type RagContext, type ResearchAnswer, type RunBenchmarksOptions, type RunBenchmarksReport, type RuntimeBenchmark, type RuntimeBenchmarkSpec, StagedJudgeError, type StagedPierCandidateExecution, type StagedRunCaptureSpec, type StagedRunSpec, type SweBenchAdapterOptions, type SweBenchArtifactCaptureContext, type SweBenchCacheLevel, answerScoreToEvaluation, contextBlock, contextsFrom, createCragAdapter, createNoMiraclAdapter, createOpenRagBenchAdapter, createRagBenchAdapter, createSweBenchAdapter, createT2RagBenchAdapter, normalizeAnswer, parseCitations, parseFinalAnswer, ragAnswerOutput, resolveAdapter, runStagedJudge, runtimeBenchmark, scoreAnswerArtifact, scoreSweReport, sweEvaluationArgv, swePatchOutput, tokenF1 };
373
+ export { ADAPTERS, type BenchCell, type BenchCellTaskResult, type BenchEvaluation, type BenchExecution, type BenchExecutionContext, type BenchLeaderboardRow, type BenchPayload, type BenchPromptResult, type BenchRuntime, type BenchShot, type BenchShotResult, type BenchTask, type CreatePierTaskTrialControllerOptions, type ExecutePreparedPierCandidateOptions, FINAL_ANSWER_SENTINEL, type FilePierCandidateTrialControllerOptions, type JudgeArtifactFileReceipt, type JudgeArtifactReceipt, type LoadOptions, type PierCandidateGraderPort, type PierCandidateOfficialResult, type PierCandidateProcessSpec, type PierCandidateTerminationAcknowledgement, type PierCandidateTrialController, type PierCandidateTrialHandle, type PierCandidateTrialIdentity, type PierCandidateTrialResult, type PierDockerConnection, type RagAnswerScore, type RagContext, type ResearchAnswer, type RunBenchmarksOptions, type RunBenchmarksReport, type RuntimeBenchmark, type RuntimeBenchmarkSpec, StagedJudgeError, type StagedPierCandidateExecution, type StagedRunCaptureSpec, type StagedRunSpec, type SweBenchAdapterOptions, type SweBenchArtifactCaptureContext, type SweBenchCacheLevel, answerScoreToEvaluation, contextBlock, contextsFrom, createCragAdapter, createNoMiraclAdapter, createOpenRagBenchAdapter, createRagBenchAdapter, createSweBenchAdapter, createT2RagBenchAdapter, normalizeAnswer, parseCitations, parseFinalAnswer, ragAnswerOutput, resolveAdapter, runStagedJudge, runtimeBenchmark, scoreAnswerArtifact, scoreSweReport, sweEvaluationArgv, swePatchOutput, tokenF1 };
354
374
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ import { chmod, lstat, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/p
12
12
  import { dirname, isAbsolute, join, resolve } from "node:path";
13
13
  import { execFileSync, spawn } from "node:child_process";
14
14
  import { createHash } from "node:crypto";
15
- import { accessSync, closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
15
+ import { accessSync, closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
16
16
  import { tmpdir } from "node:os";
17
17
  import { fileURLToPath } from "node:url";
18
18
  import { SandboxRunAbortError, createExecutor, inlineSandboxClient, openSandboxRun, resolveSandboxClient, sumSandboxUsage } from "@tangle-network/agent-runtime/kernel";
@@ -1165,6 +1165,53 @@ function protectedEnvironment(prepared, request) {
1165
1165
  for (const name of Object.keys(prepared.launch.env)) if (!(name in request.launch.env)) throw new Error(`executor request omitted signed public environment ${name}`);
1166
1166
  return Object.freeze(Object.fromEntries(protectedEntries));
1167
1167
  }
1168
+ async function stageKnowledge(directory, prepared, request) {
1169
+ const knowledge = request.knowledge;
1170
+ const declared = prepared.bundle.knowledge;
1171
+ if (!knowledge && !declared) return [];
1172
+ if (!knowledge || !declared || knowledge.snapshot.digest !== declared.snapshot.digest) throw new Error("Pier knowledge input differs from the prepared bundle");
1173
+ const { digest: bundleDigest, ...material } = prepared.bundle;
1174
+ const bundleBytes = Buffer.from(canonicalJson(material), "utf8");
1175
+ if (sha256$1(bundleBytes) !== bundleDigest) throw new Error("Pier bundle bytes do not match their sealed digest");
1176
+ const bundlePath = join(directory, "knowledge-bundle.json");
1177
+ const knowledgeDir = join(directory, "knowledge");
1178
+ const files = knowledge.files.map((file) => ({
1179
+ ...file,
1180
+ path: `files/${file.path}`
1181
+ }));
1182
+ const expected = declared.snapshot.material.files.map((file) => ({
1183
+ ...file,
1184
+ path: `files/${file.path}`
1185
+ }));
1186
+ if (declared.retrievalConfig && knowledge.retrievalConfig) {
1187
+ files.push({
1188
+ path: "retrieval.json",
1189
+ mode: 420,
1190
+ bytes: knowledge.retrievalConfig
1191
+ });
1192
+ expected.push({
1193
+ path: "retrieval.json",
1194
+ mode: 420,
1195
+ sha256: declared.retrievalConfig.sha256,
1196
+ byteLength: declared.retrievalConfig.byteLength
1197
+ });
1198
+ } else if (declared.retrievalConfig || knowledge.retrievalConfig) throw new Error("Pier retrieval configuration differs from the prepared bundle");
1199
+ await materializeExecutorFiles(knowledgeDir, files, expected, "knowledge executor input");
1200
+ await writeFile(bundlePath, bundleBytes, {
1201
+ mode: 384,
1202
+ flag: "wx"
1203
+ });
1204
+ await mkdir(join(knowledgeDir, "files"), {
1205
+ mode: 448,
1206
+ recursive: true
1207
+ });
1208
+ return [
1209
+ "--agent-kwarg",
1210
+ `knowledge_bundle_path=${bundlePath}`,
1211
+ "--agent-kwarg",
1212
+ `knowledge_dir=${knowledgeDir}`
1213
+ ];
1214
+ }
1168
1215
  /**
1169
1216
  * Persist the runtime's exact canonical bytes and return only Pier transport
1170
1217
  * arguments. No benchmark-specific plan or candidate-authored telemetry exists.
@@ -1228,6 +1275,7 @@ async function stagePreparedPierCandidateExecution(options, request) {
1228
1275
  `pier_version=${options.pierVersion}`
1229
1276
  ];
1230
1277
  if (candidateDirectory !== void 0) agentArgs.push("--agent-kwarg", `candidate_dir=${candidateDirectory}`);
1278
+ agentArgs.push(...await stageKnowledge(directory, prepared, request));
1231
1279
  return {
1232
1280
  executionId: request.executionId,
1233
1281
  directory,
@@ -1261,7 +1309,7 @@ function protectedCaptureFromPierResult(request, value) {
1261
1309
  const metadata = record(record(result.agent_result, "Pier agent_result").metadata, "Pier agent_result.metadata");
1262
1310
  const expected = {
1263
1311
  executionId: request.executionId,
1264
- bundleDigest: request.executionPlan.value.material.runCell.bundleDigest,
1312
+ bundleDigest: request.materializationReceipt.value.bundleDigest,
1265
1313
  executionPlanDigest: request.executionPlan.value.digest,
1266
1314
  materializationReceiptDigest: request.materializationReceipt.digest
1267
1315
  };
@@ -1346,99 +1394,101 @@ async function awaitAbortableTrial(trial, signal) {
1346
1394
  });
1347
1395
  });
1348
1396
  }
1349
- /** Execute and finalize through the runtime's only gradable candidate path. */
1350
- async function executePreparedPierCandidate(options) {
1397
+ /** Bind Pier and its separate verifier to Runtime's prepared experiment cell. */
1398
+ function createPierCandidateExecutionOptions(options) {
1351
1399
  const trials = /* @__PURE__ */ new Map();
1352
1400
  const officialResults = /* @__PURE__ */ new Map();
1353
1401
  const trialIdentity = (executionId, executionPlanDigest) => JSON.stringify([executionId, executionPlanDigest]);
1354
- const executor = {
1355
- execute: async (request, context) => {
1356
- context.signal.throwIfAborted();
1357
- const staged = await stagePreparedPierCandidateExecution(options, request);
1358
- context.signal.throwIfAborted();
1359
- const identity = trialIdentity(request.executionId, request.executionPlan.value.digest);
1360
- if (trials.has(identity)) throw new Error("Pier trial identity is already active");
1361
- const trial = options.controller.start(staged, {
1362
- request,
1363
- traceStore: context.traceStore,
1364
- signal: context.signal,
1365
- deadlineAtMs: context.deadlineAtMs
1366
- });
1367
- if (trial.identity.executionId !== request.executionId || trial.identity.executionPlanDigest !== request.executionPlan.value.digest) {
1368
- assertTerminationAcknowledged(await trial.terminateAndWait());
1369
- throw new Error("Pier controller returned a different durable trial identity");
1402
+ return {
1403
+ executor: {
1404
+ execute: async (request, context) => {
1405
+ context.signal.throwIfAborted();
1406
+ if (request.executionId !== options.prepared.executionId || request.materializationReceipt.digest !== options.prepared.materializationReceipt.digest) throw new Error("Pier executor received a different prepared candidate");
1407
+ const staged = await stagePreparedPierCandidateExecution(options, request);
1408
+ context.signal.throwIfAborted();
1409
+ const identity = trialIdentity(request.executionId, request.executionPlan.value.digest);
1410
+ if (trials.has(identity)) throw new Error("Pier trial identity is already active");
1411
+ const trial = options.controller.start(staged, {
1412
+ request,
1413
+ traceStore: context.traceStore,
1414
+ signal: context.signal,
1415
+ deadlineAtMs: context.deadlineAtMs
1416
+ });
1417
+ if (trial.identity.executionId !== request.executionId || trial.identity.executionPlanDigest !== request.executionPlan.value.digest) {
1418
+ assertTerminationAcknowledged(await trial.terminateAndWait());
1419
+ throw new Error("Pier controller returned a different durable trial identity");
1420
+ }
1421
+ const active = { handle: trial };
1422
+ trials.set(identity, active);
1423
+ const result = sealPierTrialResult(await awaitAbortableTrial(trial, context.signal));
1424
+ active.result = result;
1425
+ officialResults.set(request.executionId, result);
1426
+ return protectedCaptureFromPierResult(request, result.value);
1427
+ },
1428
+ stop: async (request) => {
1429
+ assertTerminationAcknowledged(await options.controller.terminateAndWait({
1430
+ executionId: request.executionId,
1431
+ executionPlanDigest: request.executionPlanDigest
1432
+ }));
1433
+ return { stopped: true };
1434
+ },
1435
+ capture: async (request) => {
1436
+ const identity = trialIdentity(request.executionId, request.executionPlanDigest);
1437
+ const active = trials.get(identity);
1438
+ let result = active?.result;
1439
+ if (!result && active) try {
1440
+ result = sealPierTrialResult(await active.handle.result);
1441
+ } catch {
1442
+ result = void 0;
1443
+ }
1444
+ if (!result) {
1445
+ const recovered = await options.controller.captureResult(request);
1446
+ result = recovered ? sealPierTrialResult(recovered) : void 0;
1447
+ }
1448
+ if (!result) return {};
1449
+ officialResults.set(request.executionId, result);
1450
+ const task = options.prepared.benchmark.task;
1451
+ if (task.outcome.kind !== "workspace") throw new Error("Pier candidate execution requires a workspace task outcome");
1452
+ const repository = task.repository;
1453
+ if (!repository) throw new Error("Pier workspace task is missing repository identity");
1454
+ const taskOutcome = await capturePierTaskOutcome({
1455
+ repositoryRoot: options.prepared.roots.staging.taskRoot,
1456
+ baseCommit: repository.baseCommit,
1457
+ baseTree: repository.baseTree,
1458
+ patch: result.taskPatch
1459
+ });
1460
+ trials.delete(identity);
1461
+ return { taskOutcome };
1370
1462
  }
1371
- const active = { handle: trial };
1372
- trials.set(identity, active);
1373
- const result = sealPierTrialResult(await awaitAbortableTrial(trial, context.signal));
1374
- active.result = result;
1375
- officialResults.set(request.executionId, result);
1376
- return protectedCaptureFromPierResult(request, result.value);
1377
- },
1378
- stop: async (request) => {
1379
- assertTerminationAcknowledged(await options.controller.terminateAndWait({
1380
- executionId: request.executionId,
1381
- executionPlanDigest: request.executionPlanDigest
1382
- }));
1383
- return { stopped: true };
1384
1463
  },
1385
- capture: async (request) => {
1386
- const identity = trialIdentity(request.executionId, request.executionPlanDigest);
1387
- const active = trials.get(identity);
1388
- let result = active?.result;
1389
- if (!result && active) try {
1390
- result = sealPierTrialResult(await active.handle.result);
1391
- } catch {
1392
- result = void 0;
1393
- }
1394
- if (!result) {
1395
- const recovered = await options.controller.captureResult(request);
1396
- result = recovered ? sealPierTrialResult(recovered) : void 0;
1397
- }
1398
- if (!result) return {};
1399
- officialResults.set(request.executionId, result);
1400
- const task = options.prepared.benchmark.task;
1401
- if (task.outcome.kind !== "workspace") throw new Error("Pier candidate execution requires a workspace task outcome");
1402
- const repository = task.repository;
1403
- if (!repository) throw new Error("Pier workspace task is missing repository identity");
1404
- const taskOutcome = await capturePierTaskOutcome({
1405
- repositoryRoot: options.prepared.roots.staging.taskRoot,
1406
- baseCommit: repository.baseCommit,
1407
- baseTree: repository.baseTree,
1408
- patch: result.taskPatch
1409
- });
1410
- trials.delete(identity);
1411
- return { taskOutcome };
1412
- }
1413
- };
1414
- const grader = {
1415
- name: options.grader.name,
1416
- version: options.grader.version,
1417
- artifact: options.grader.artifact,
1418
- run: async (input) => {
1419
- const official = officialResults.get(input.executionId);
1420
- if (!official) throw new Error("Pier official result is missing for executable grading");
1421
- return await options.grader.run({
1422
- ...input,
1423
- officialResult: {
1424
- value: parseExactJson(official.resultBytes, "Pier result.json"),
1425
- bytes: Uint8Array.from(official.resultBytes)
1464
+ grader: {
1465
+ name: options.grader.name,
1466
+ version: options.grader.version,
1467
+ artifact: options.grader.artifact,
1468
+ run: async (input) => {
1469
+ const official = officialResults.get(input.executionId);
1470
+ if (!official) throw new Error("Pier official result is missing for executable grading");
1471
+ try {
1472
+ return await options.grader.run({
1473
+ ...input,
1474
+ officialResult: {
1475
+ value: parseExactJson(official.resultBytes, "Pier result.json"),
1476
+ bytes: Uint8Array.from(official.resultBytes)
1477
+ }
1478
+ });
1479
+ } finally {
1480
+ officialResults.delete(input.executionId);
1426
1481
  }
1427
- });
1428
- }
1482
+ }
1483
+ },
1484
+ outputArtifacts: options.outputArtifacts,
1485
+ traceStore: options.traceStore,
1486
+ claimStore: options.claimStore
1429
1487
  };
1430
- try {
1431
- return await executePreparedAgentCandidate(options.prepared, {
1432
- executor,
1433
- grader,
1434
- outputArtifacts: options.outputArtifacts,
1435
- traceStore: options.traceStore,
1436
- claimStore: options.claimStore
1437
- });
1438
- } finally {
1439
- officialResults.clear();
1440
- trials.clear();
1441
- }
1488
+ }
1489
+ /** Execute and finalize through the runtime's only gradable candidate path. */
1490
+ async function executePreparedPierCandidate(options) {
1491
+ return await executePreparedAgentCandidate(options.prepared, createPierCandidateExecutionOptions(options));
1442
1492
  }
1443
1493
  // src/pier-trial-controller.ts
1444
1494
  /** Restart-safe evaluator ownership for one Pier process and its Docker projects. */
@@ -1447,6 +1497,104 @@ const terminalFile = "terminal.json";
1447
1497
  const stopFile = "stop-requested";
1448
1498
  const sha256Pattern = /^sha256:[a-f0-9]{64}$/;
1449
1499
  const defaultDockerConnectionId = "local-default";
1500
+ /** Run one approved Pier task and reopen its official result through the durable controller. */
1501
+ function createPierTaskTrialController(options) {
1502
+ const jobsDirectory = absolutePath(options.jobsDirectory, "Pier jobs directory");
1503
+ const { maxEvidenceBytes } = options;
1504
+ if (!Number.isSafeInteger(maxEvidenceBytes) || maxEvidenceBytes < 1) throw new Error("Pier evidence limit must be a positive safe integer");
1505
+ const tasks = /* @__PURE__ */ new Map();
1506
+ for (const { taskDigest, directory } of options.tasks) {
1507
+ if (!sha256Pattern.test(taskDigest) || tasks.has(taskDigest)) throw new Error("Pier task directories require distinct approved SHA-256 task digests");
1508
+ tasks.set(taskDigest, absolutePath(directory, "Pier task directory"));
1509
+ }
1510
+ const { prefix = [], env, ...command } = options.command;
1511
+ const argumentsPrefix = [...prefix];
1512
+ const environment = { ...env };
1513
+ const readResult = async ({ jobsDirectory, jobName }) => readOfficialTrial(join(jobsDirectory, jobName), maxEvidenceBytes);
1514
+ return new FilePierCandidateTrialController({
1515
+ directory: options.directory,
1516
+ dockerConnection: options.dockerConnection,
1517
+ readResult,
1518
+ launch(staged, { request }) {
1519
+ const task = tasks.get(request.benchmark.task.digest);
1520
+ if (!task) throw new Error("Pier has no directory for this approved task");
1521
+ assertRealDirectory(task, "Pier task directory");
1522
+ const jobName = `candidate-${trialKey({
1523
+ executionId: request.executionId,
1524
+ executionPlanDigest: request.executionPlan.value.digest
1525
+ })}`;
1526
+ return {
1527
+ ...command,
1528
+ args: [
1529
+ ...argumentsPrefix,
1530
+ "run",
1531
+ "--path",
1532
+ task,
1533
+ ...staged.agentArgs,
1534
+ ...staged.attemptArgs,
1535
+ ...Object.keys(staged.evaluatorEnv).flatMap((name) => ["--agent-env", `${name}=\${${name}}`]),
1536
+ "--env",
1537
+ "docker",
1538
+ "--job-name",
1539
+ jobName,
1540
+ "--jobs-dir",
1541
+ jobsDirectory,
1542
+ "--n-concurrent",
1543
+ "1",
1544
+ "--quiet"
1545
+ ],
1546
+ env: {
1547
+ ...environment,
1548
+ ...staged.evaluatorEnv
1549
+ },
1550
+ jobsDirectory,
1551
+ jobName,
1552
+ readResult: async () => {
1553
+ const result = await readResult({
1554
+ jobsDirectory,
1555
+ jobName
1556
+ });
1557
+ if (!result) throw new Error("Pier emitted no official trial result");
1558
+ return result;
1559
+ }
1560
+ };
1561
+ }
1562
+ });
1563
+ }
1564
+ function readOfficialTrial(directory, maxEvidenceBytes) {
1565
+ if (!existsSync(directory)) return void 0;
1566
+ assertRealDirectory(directory, "Pier job directory");
1567
+ let result;
1568
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
1569
+ if (!entry.isDirectory()) continue;
1570
+ const trial = join(directory, entry.name);
1571
+ const resultPath = join(trial, "result.json");
1572
+ if (!existsSync(resultPath)) continue;
1573
+ const resultBytes = readOfficialTrialFile(resultPath, maxEvidenceBytes);
1574
+ const value = JSON.parse(resultBytes.toString("utf8"));
1575
+ if (value === null || typeof value !== "object" || !("trial_name" in value) || typeof value.trial_name !== "string") throw new Error("Pier emitted a malformed official trial result");
1576
+ if (result) throw new Error("Expected one official result for the approved Pier task");
1577
+ const artifacts = join(trial, "artifacts");
1578
+ assertRealDirectory(artifacts, "Pier trial artifacts directory");
1579
+ result = {
1580
+ value,
1581
+ resultBytes,
1582
+ taskPatch: readOfficialTrialFile(join(artifacts, "model.patch"), maxEvidenceBytes)
1583
+ };
1584
+ }
1585
+ return result;
1586
+ }
1587
+ function readOfficialTrialFile(path, maxEvidenceBytes) {
1588
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1589
+ try {
1590
+ const evidence = fstatSync(fd);
1591
+ if (!evidence.isFile()) throw new Error("Pier trial evidence must be a regular file");
1592
+ if (evidence.size > maxEvidenceBytes) throw new Error("Pier trial evidence exceeds its configured limit");
1593
+ return readFileSync(fd);
1594
+ } finally {
1595
+ closeSync(fd);
1596
+ }
1597
+ }
1450
1598
  function nonEmpty(value, label) {
1451
1599
  if (!value || value.includes("\0")) throw new Error(`${label} must be non-empty without NUL`);
1452
1600
  return value;
@@ -2048,6 +2196,6 @@ async function runNode(script, input, signal) {
2048
2196
  child.stdin.end(input);
2049
2197
  });
2050
2198
  }
2051
- export { ADAPTERS, FINAL_ANSWER_SENTINEL, FilePierCandidateTrialController, StagedJudgeError, answerScoreToEvaluation, contextBlock, contextsFrom, createCragAdapter, createNoMiraclAdapter, createOpenRagBenchAdapter, createPierCandidateRecoveryExecutor, createPierResultGrader, createRagBenchAdapter, createSweBenchAdapter, createT2RagBenchAdapter, executePreparedPierCandidate, normalizeAnswer, parseCitations, parseFinalAnswer, printBenchmarksReport, ragAnswerOutput, resolveAdapter, runBenchmarks, runStagedJudge, runtimeBenchmark, scoreAnswerArtifact, scoreSweReport, sweEvaluationArgv, swePatchOutput, tokenF1 };
2199
+ export { ADAPTERS, FINAL_ANSWER_SENTINEL, FilePierCandidateTrialController, StagedJudgeError, answerScoreToEvaluation, contextBlock, contextsFrom, createCragAdapter, createNoMiraclAdapter, createOpenRagBenchAdapter, createPierCandidateExecutionOptions, createPierCandidateRecoveryExecutor, createPierResultGrader, createPierTaskTrialController, createRagBenchAdapter, createSweBenchAdapter, createT2RagBenchAdapter, executePreparedPierCandidate, normalizeAnswer, parseCitations, parseFinalAnswer, printBenchmarksReport, ragAnswerOutput, resolveAdapter, runBenchmarks, runStagedJudge, runtimeBenchmark, scoreAnswerArtifact, scoreSweReport, sweEvaluationArgv, swePatchOutput, tokenF1 };
2052
2200
 
2053
2201
  //# sourceMappingURL=index.js.map