@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/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,112 @@ 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 startedAt = Date.now();
1412
+ const trial = options.controller.start(staged, {
1413
+ request,
1414
+ traceStore: context.traceStore,
1415
+ signal: context.signal,
1416
+ deadlineAtMs: context.deadlineAtMs
1417
+ });
1418
+ if (trial.identity.executionId !== request.executionId || trial.identity.executionPlanDigest !== request.executionPlan.value.digest) {
1419
+ assertTerminationAcknowledged(await trial.terminateAndWait());
1420
+ throw new Error("Pier controller returned a different durable trial identity");
1421
+ }
1422
+ const active = { handle: trial };
1423
+ trials.set(identity, active);
1424
+ const result = sealPierTrialResult(await awaitAbortableTrial(trial, context.signal));
1425
+ const endedAt = Math.max(startedAt, Date.now());
1426
+ active.result = result;
1427
+ officialResults.set(request.executionId, result);
1428
+ const capture = protectedCaptureFromPierResult(request, result.value);
1429
+ if (!await context.traceStore.getRun(request.trace.runId)) await context.traceStore.appendRun({
1430
+ runId: request.trace.runId,
1431
+ scenarioId: request.benchmark.task.scenario.id,
1432
+ startedAt,
1433
+ endedAt,
1434
+ status: capture.termination.kind === "exit" && capture.termination.exitCode === 0 ? "completed" : "failed",
1435
+ tags: request.trace.tags
1436
+ });
1437
+ return capture;
1438
+ },
1439
+ stop: async (request) => {
1440
+ assertTerminationAcknowledged(await options.controller.terminateAndWait({
1441
+ executionId: request.executionId,
1442
+ executionPlanDigest: request.executionPlanDigest
1443
+ }));
1444
+ return { stopped: true };
1445
+ },
1446
+ capture: async (request) => {
1447
+ const identity = trialIdentity(request.executionId, request.executionPlanDigest);
1448
+ const active = trials.get(identity);
1449
+ let result = active?.result;
1450
+ if (!result && active) try {
1451
+ result = sealPierTrialResult(await active.handle.result);
1452
+ } catch {
1453
+ result = void 0;
1454
+ }
1455
+ if (!result) {
1456
+ const recovered = await options.controller.captureResult(request);
1457
+ result = recovered ? sealPierTrialResult(recovered) : void 0;
1458
+ }
1459
+ if (!result) return {};
1460
+ officialResults.set(request.executionId, result);
1461
+ const task = options.prepared.benchmark.task;
1462
+ if (task.outcome.kind !== "workspace") throw new Error("Pier candidate execution requires a workspace task outcome");
1463
+ const repository = task.repository;
1464
+ if (!repository) throw new Error("Pier workspace task is missing repository identity");
1465
+ const taskOutcome = await capturePierTaskOutcome({
1466
+ repositoryRoot: options.prepared.roots.staging.taskRoot,
1467
+ baseCommit: repository.baseCommit,
1468
+ baseTree: repository.baseTree,
1469
+ patch: result.taskPatch
1470
+ });
1471
+ trials.delete(identity);
1472
+ return { taskOutcome };
1370
1473
  }
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
1474
  },
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)
1475
+ grader: {
1476
+ name: options.grader.name,
1477
+ version: options.grader.version,
1478
+ artifact: options.grader.artifact,
1479
+ run: async (input) => {
1480
+ const official = officialResults.get(input.executionId);
1481
+ if (!official) throw new Error("Pier official result is missing for executable grading");
1482
+ try {
1483
+ return await options.grader.run({
1484
+ ...input,
1485
+ officialResult: {
1486
+ value: parseExactJson(official.resultBytes, "Pier result.json"),
1487
+ bytes: Uint8Array.from(official.resultBytes)
1488
+ }
1489
+ });
1490
+ } finally {
1491
+ officialResults.delete(input.executionId);
1426
1492
  }
1427
- });
1428
- }
1493
+ }
1494
+ },
1495
+ outputArtifacts: options.outputArtifacts,
1496
+ traceStore: options.traceStore,
1497
+ claimStore: options.claimStore
1429
1498
  };
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
- }
1499
+ }
1500
+ /** Execute and finalize through the runtime's only gradable candidate path. */
1501
+ async function executePreparedPierCandidate(options) {
1502
+ return await executePreparedAgentCandidate(options.prepared, createPierCandidateExecutionOptions(options));
1442
1503
  }
1443
1504
  // src/pier-trial-controller.ts
1444
1505
  /** Restart-safe evaluator ownership for one Pier process and its Docker projects. */
@@ -1447,6 +1508,104 @@ const terminalFile = "terminal.json";
1447
1508
  const stopFile = "stop-requested";
1448
1509
  const sha256Pattern = /^sha256:[a-f0-9]{64}$/;
1449
1510
  const defaultDockerConnectionId = "local-default";
1511
+ /** Run one approved Pier task and reopen its official result through the durable controller. */
1512
+ function createPierTaskTrialController(options) {
1513
+ const jobsDirectory = absolutePath(options.jobsDirectory, "Pier jobs directory");
1514
+ const { maxEvidenceBytes } = options;
1515
+ if (!Number.isSafeInteger(maxEvidenceBytes) || maxEvidenceBytes < 1) throw new Error("Pier evidence limit must be a positive safe integer");
1516
+ const tasks = /* @__PURE__ */ new Map();
1517
+ for (const { taskDigest, directory } of options.tasks) {
1518
+ if (!sha256Pattern.test(taskDigest) || tasks.has(taskDigest)) throw new Error("Pier task directories require distinct approved SHA-256 task digests");
1519
+ tasks.set(taskDigest, absolutePath(directory, "Pier task directory"));
1520
+ }
1521
+ const { prefix = [], env, ...command } = options.command;
1522
+ const argumentsPrefix = [...prefix];
1523
+ const environment = { ...env };
1524
+ const readResult = async ({ jobsDirectory, jobName }) => readOfficialTrial(join(jobsDirectory, jobName), maxEvidenceBytes);
1525
+ return new FilePierCandidateTrialController({
1526
+ directory: options.directory,
1527
+ dockerConnection: options.dockerConnection,
1528
+ readResult,
1529
+ launch(staged, { request }) {
1530
+ const task = tasks.get(request.benchmark.task.digest);
1531
+ if (!task) throw new Error("Pier has no directory for this approved task");
1532
+ assertRealDirectory(task, "Pier task directory");
1533
+ const jobName = `candidate-${trialKey({
1534
+ executionId: request.executionId,
1535
+ executionPlanDigest: request.executionPlan.value.digest
1536
+ })}`;
1537
+ return {
1538
+ ...command,
1539
+ args: [
1540
+ ...argumentsPrefix,
1541
+ "run",
1542
+ "--path",
1543
+ task,
1544
+ ...staged.agentArgs,
1545
+ ...staged.attemptArgs,
1546
+ ...Object.keys(staged.evaluatorEnv).flatMap((name) => ["--agent-env", `${name}=\${${name}}`]),
1547
+ "--env",
1548
+ "docker",
1549
+ "--job-name",
1550
+ jobName,
1551
+ "--jobs-dir",
1552
+ jobsDirectory,
1553
+ "--n-concurrent",
1554
+ "1",
1555
+ "--quiet"
1556
+ ],
1557
+ env: {
1558
+ ...environment,
1559
+ ...staged.evaluatorEnv
1560
+ },
1561
+ jobsDirectory,
1562
+ jobName,
1563
+ readResult: async () => {
1564
+ const result = await readResult({
1565
+ jobsDirectory,
1566
+ jobName
1567
+ });
1568
+ if (!result) throw new Error("Pier emitted no official trial result");
1569
+ return result;
1570
+ }
1571
+ };
1572
+ }
1573
+ });
1574
+ }
1575
+ function readOfficialTrial(directory, maxEvidenceBytes) {
1576
+ if (!existsSync(directory)) return void 0;
1577
+ assertRealDirectory(directory, "Pier job directory");
1578
+ let result;
1579
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
1580
+ if (!entry.isDirectory()) continue;
1581
+ const trial = join(directory, entry.name);
1582
+ const resultPath = join(trial, "result.json");
1583
+ if (!existsSync(resultPath)) continue;
1584
+ const resultBytes = readOfficialTrialFile(resultPath, maxEvidenceBytes);
1585
+ const value = JSON.parse(resultBytes.toString("utf8"));
1586
+ 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");
1587
+ if (result) throw new Error("Expected one official result for the approved Pier task");
1588
+ const artifacts = join(trial, "artifacts");
1589
+ assertRealDirectory(artifacts, "Pier trial artifacts directory");
1590
+ result = {
1591
+ value,
1592
+ resultBytes,
1593
+ taskPatch: readOfficialTrialFile(join(artifacts, "model.patch"), maxEvidenceBytes)
1594
+ };
1595
+ }
1596
+ return result;
1597
+ }
1598
+ function readOfficialTrialFile(path, maxEvidenceBytes) {
1599
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1600
+ try {
1601
+ const evidence = fstatSync(fd);
1602
+ if (!evidence.isFile()) throw new Error("Pier trial evidence must be a regular file");
1603
+ if (evidence.size > maxEvidenceBytes) throw new Error("Pier trial evidence exceeds its configured limit");
1604
+ return readFileSync(fd);
1605
+ } finally {
1606
+ closeSync(fd);
1607
+ }
1608
+ }
1450
1609
  function nonEmpty(value, label) {
1451
1610
  if (!value || value.includes("\0")) throw new Error(`${label} must be non-empty without NUL`);
1452
1611
  return value;
@@ -2048,6 +2207,6 @@ async function runNode(script, input, signal) {
2048
2207
  child.stdin.end(input);
2049
2208
  });
2050
2209
  }
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 };
2210
+ 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
2211
 
2053
2212
  //# sourceMappingURL=index.js.map