@mcpjam/cli 4.1.0 → 4.2.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/dist/index.js CHANGED
@@ -2,16 +2,16 @@
2
2
  import { Command, CommanderError, Option } from 'commander';
3
3
  import { realpathSync, readFileSync, existsSync, mkdirSync, writeFileSync, unlinkSync, statSync, closeSync, renameSync, openSync } from 'fs';
4
4
  import { pathToFileURL } from 'url';
5
- import { probeMcpServer, redactForTelemetry, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, classifyMcpHeader, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, SubscriptionCoordinator, listTools, listPrompts, getPrompt, MCPAppsConformanceTest, scoreFromAppsResult, MCPAppsConformanceSuite, MCPTasksConformanceTest, scoreFromTasksResult, runOAuthLogin, OAuthConformanceTest, scoreFromOAuthResult, OAuthConformanceSuite, runXaaFlow, MCPConformanceTest, scoreFromProtocolResult, MCPConformanceSuite, runConformance, isConformanceReportingConfigured, reportConformanceRun, reportConformanceRunSafely, OPENAI_SUBMISSION_MODES, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunJson, DEFAULT_SUBSCRIPTION_RECONNECT_POLICY, isKnownProtocolVersion, describeConformanceScore, toConformanceReport, buildConformanceRunReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, normalizeRegistrationStrategy, normalizeXaaClientAuth, normalizeIdentityAssertionFormat, IDENTITY_ASSERTION_FORMATS, XAA_CONFIDENTIAL_CIMD_ORIGIN, getLocalConfidentialCimdProvider, MCP_PROTOCOL_VERSIONS, gatherClaudeReadinessEvidence, gradeClaudeReadiness, gatherOpenAIReadinessEvidence, xmldomParseXml, gradeOpenAIReadiness, openUrlInBrowser, buildEvalRunReport, buildEvalDecisionSummaryFromIterations, MCPClientManager, decodeMcpHeaderValue, canDeclareTasksExtension, createStrictElicitationContentValidator, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, MCP_TASKS_CHECK_CATEGORIES, MCP_TASKS_CHECK_IDS, OAuthProxyError, isLoopbackHost, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS, OPENAI_SUBMISSION_MODE_SHAPES, createDirectoryPluginFileSource, collectZipArchiveObservations, createZipPluginFileSource, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, formatEvalDecisionSummary, formatGateReport, detectFlakyCases, evaluateCompareGates, buildRunCompareReport, loadEvalSuiteFile, formatSuiteFileFindings, serializeEvalSuiteFile, MAX_SUITE_FILE_BYTES, buildCorpus, HostedOnlyCaseError, verifyCorpusLock, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, evaluateGates, gateInputFromPlatformRun, calculateLatencyStats, CORPUS_LOCK_VERSION, canonicalDigest, passRateFractionFromPercent, suiteFilePointer, isUnknownTaskError, isMCPTasksWireError, LEGACY_TASK_STATUSES } from '@mcpjam/sdk';
5
+ import { probeMcpServer, redactForTelemetry, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, classifyMcpHeader, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, SubscriptionCoordinator, listTools, listPrompts, getPrompt, MCPAppsConformanceTest, scoreFromAppsResult, MCPAppsConformanceSuite, MCPTasksConformanceTest, scoreFromTasksResult, runOAuthLogin, OAuthConformanceTest, scoreFromOAuthResult, OAuthConformanceSuite, runXaaFlow, MCPConformanceTest, scoreFromProtocolResult, MCPConformanceSuite, runConformance, isConformanceReportingConfigured, reportConformanceRun, reportConformanceRunSafely, OPENAI_SUBMISSION_MODES, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunHtml, renderStructuredRunJson, DEFAULT_SUBSCRIPTION_RECONNECT_POLICY, isKnownProtocolVersion, describeConformanceScore, toConformanceReport, buildConformanceRunReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, normalizeRegistrationStrategy, normalizeXaaClientAuth, normalizeIdentityAssertionFormat, IDENTITY_ASSERTION_FORMATS, XAA_CONFIDENTIAL_CIMD_ORIGIN, getLocalConfidentialCimdProvider, MCP_PROTOCOL_VERSIONS, gatherClaudeReadinessEvidence, gradeClaudeReadiness, gatherOpenAIReadinessEvidence, xmldomParseXml, gradeOpenAIReadiness, openUrlInBrowser, buildEvalRunReport, buildEvalDecisionSummaryFromIterations, MCPClientManager, decodeMcpHeaderValue, canDeclareTasksExtension, createStrictElicitationContentValidator, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, MCP_TASKS_CHECK_CATEGORIES, MCP_TASKS_CHECK_IDS, OAuthProxyError, isLoopbackHost, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS, OPENAI_SUBMISSION_MODE_SHAPES, createDirectoryPluginFileSource, collectZipArchiveObservations, createZipPluginFileSource, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, loadEvalSuiteFile, formatEvalDecisionSummary, gateOutcomeVerdict, formatGateReport, detectFlakyCases, evaluateCompareGates, buildRunCompareReport, formatSuiteFileFindings, serializeEvalSuiteFile, MAX_SUITE_FILE_BYTES, buildCorpus, HostedOnlyCaseError, verifyCorpusLock, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, canonicalDigest, evaluateGates, gateInputFromPlatformRun, calculateLatencyStats, CORPUS_LOCK_VERSION, passRateFractionFromPercent, DEFAULT_MIN_EFFECT_SIZE, DEFAULT_MIN_SAMPLE_SIZE, suiteFilePointer, isUnknownTaskError, isMCPTasksWireError, LEGACY_TASK_STATUSES } from '@mcpjam/sdk';
6
6
  import path7, { join, dirname, basename } from 'path';
7
7
  import { randomUUID, randomBytes, createHash } from 'crypto';
8
8
  import { mkdir, writeFile, readFile, chmod, rename, rm, open, unlink, stat } from 'fs/promises';
9
9
  import { spawn } from 'child_process';
10
10
  import { createRequire } from 'module';
11
11
  import os, { homedir } from 'os';
12
- import { getRegistryDirectoryServerOperation, listOrganizationsOperation, listProjectsOperation, createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, listChatSessionsOperation, resolveProject, createTunnelOperation, listEvalSuiteRunsOperation, getEvalRunOperation, cancelEvalRunOperation, requestEvalRunJudgeOperation, listEvalCheckReposOperation, connectEvalCheckRepoOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, runEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, createHostOperation, updateHostOperation, setHostServersOperation, duplicateHostOperation, createEnvironmentOperation, ensureAdhocEnvironmentOperation, nameEnvironmentOperation, updateEnvironmentOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, PlatformApiError, installRegistryServerOperation, installRegistryDirectoryServerOperation, getProjectServerOperation, DEFAULT_PLATFORM_API_BASE_URL, projectResolutionError, listProjectServersOperation, createProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, isPlatformApiError, createEvalSuiteOperation, listEvalSuitesOperation, runEvalSuiteOperation, resolveEnvironmentOperation, listHostsOperation, getHostOperation, deleteHostOperation, listEnvironmentsOperation, getEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, listJourneysOperation, listJourneyRunsOperation, getJourneyRunOperation, launchJourneyRunOperation, cancelJourneyRunOperation, listJourneyRunSessionsOperation, listScenariosOperation, getScenarioOperation, publishScenarioOperation, unpublishScenarioOperation, PlatformApiClient, getCapabilitiesOperation, searchSessionsOperation, sendChatMessageOperation, getChatSessionOperation, getChatSessionTraceOperation, listPersonasOperation, getPersonaOperation, createPersonaOperation, updatePersonaOperation, deletePersonaOperation, generatePersonasOperation, getJourneyOperation, createJourneyOperation, updateJourneyOperation, archiveJourneyOperation, generateJourneysOperation, getSwarmOverviewOperation, getJourneyRunScorecardOperation, listSwarmFindingsOperation, dismissSwarmFindingOperation, undismissSwarmFindingOperation, getWaveInsightsOperation, requestWaveInsightsOperation, cancelWaveInsightsOperation, listSwarmsOperation, getSwarmOperation, createSwarmOperation, updateSwarmOperation, archiveSwarmOperation, getUserTestingScenarioOperation, listUserTestingSessionsOperation, getUserTestingSessionOperation, getUserTestingMetricsOperation, getUserTestingUsageOperation, listUserTestingFindingsOperation, getUserTestingSignalsOperation, getUserTestingInsightsOperation, requestUserTestingInsightsOperation, cancelUserTestingInsightsOperation, dismissUserTestingFindingOperation, undismissUserTestingFindingOperation, updateUserTestingScenarioOperation, setUserTestingGuestExecutionOperation, rotateUserTestingLinkOperation, upsertUserTestingMemberOperation, removeUserTestingMemberOperation, rebindUserTestingScenarioOperation, startClaudeReadinessRunOperation, startOpenAIReadinessRunOperation, getReadinessRunOperation, listReadinessRunsOperation, cancelReadinessRunOperation, getReadinessReportOperation, listRegistryDirectorySourcesOperation, searchRegistryDirectoryOperation, listRegistryServersOperation, listRegistryConnectionsOperation, uninstallRegistryServerOperation } from '@mcpjam/sdk/platform';
12
+ import { getRegistryDirectoryServerOperation, listOrganizationsOperation, listProjectsOperation, createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, listChatSessionsOperation, resolveProject, createTunnelOperation, listEvalSuiteRunsOperation, runEvalSuiteOperation, getEvalRunOperation, cancelEvalRunOperation, requestEvalRunJudgeOperation, listEvalCheckReposOperation, connectEvalCheckRepoOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, runEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, createHostOperation, updateHostOperation, setHostServersOperation, duplicateHostOperation, createEnvironmentOperation, ensureAdhocEnvironmentOperation, nameEnvironmentOperation, updateEnvironmentOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, PlatformApiError, installRegistryServerOperation, installRegistryDirectoryServerOperation, getProjectServerOperation, DEFAULT_PLATFORM_API_BASE_URL, projectResolutionError, listProjectServersOperation, createProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, isPlatformApiError, createEvalSuiteOperation, listEvalSuitesOperation, resolveEnvironmentOperation, listHostsOperation, getHostOperation, deleteHostOperation, listEnvironmentsOperation, getEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, listJourneysOperation, listJourneyRunsOperation, getJourneyRunOperation, launchJourneyRunOperation, cancelJourneyRunOperation, listJourneyRunSessionsOperation, listScenariosOperation, getScenarioOperation, publishScenarioOperation, unpublishScenarioOperation, PlatformApiClient, getCapabilitiesOperation, searchSessionsOperation, sendChatMessageOperation, getChatSessionOperation, getChatSessionTraceOperation, listPersonasOperation, getPersonaOperation, createPersonaOperation, updatePersonaOperation, deletePersonaOperation, generatePersonasOperation, getJourneyOperation, createJourneyOperation, updateJourneyOperation, archiveJourneyOperation, generateJourneysOperation, getSwarmOverviewOperation, getJourneyRunScorecardOperation, listSwarmFindingsOperation, dismissSwarmFindingOperation, undismissSwarmFindingOperation, getWaveInsightsOperation, requestWaveInsightsOperation, cancelWaveInsightsOperation, listSwarmsOperation, getSwarmOperation, createSwarmOperation, updateSwarmOperation, archiveSwarmOperation, getUserTestingScenarioOperation, listUserTestingSessionsOperation, getUserTestingSessionOperation, getUserTestingMetricsOperation, getUserTestingUsageOperation, listUserTestingFindingsOperation, getUserTestingSignalsOperation, getUserTestingInsightsOperation, requestUserTestingInsightsOperation, cancelUserTestingInsightsOperation, dismissUserTestingFindingOperation, undismissUserTestingFindingOperation, updateUserTestingScenarioOperation, setUserTestingGuestExecutionOperation, rotateUserTestingLinkOperation, upsertUserTestingMemberOperation, removeUserTestingMemberOperation, rebindUserTestingScenarioOperation, startClaudeReadinessRunOperation, startOpenAIReadinessRunOperation, getReadinessRunOperation, listReadinessRunsOperation, cancelReadinessRunOperation, getReadinessReportOperation, listRegistryDirectorySourcesOperation, searchRegistryDirectoryOperation, listRegistryServersOperation, listRegistryConnectionsOperation, uninstallRegistryServerOperation } from '@mcpjam/sdk/platform';
13
13
  import { isDeepStrictEqual } from 'util';
14
- import { evalSuiteFileSchema, MAX_BATCH_CREATE_CASES, isOpaqueId } from '@mcpjam/sdk/contract';
14
+ import { MAX_BATCH_CREATE_CASES, evalSuiteFileSchema, isOpaqueId } from '@mcpjam/sdk/contract';
15
15
  import { HOST_TEMPLATES as HOST_TEMPLATES$1, HOST_TEMPLATE_IDS, seedHostTemplate } from '@mcpjam/sdk/host-config/templates';
16
16
  import http from 'http';
17
17
  import https from 'https';
@@ -27,7 +27,7 @@ import { PostHog } from 'posthog-node';
27
27
 
28
28
  // package.json
29
29
  var package_default = {
30
- version: "4.1.0"};
30
+ version: "4.2.0"};
31
31
  function conformanceExitCode(result) {
32
32
  if (result.outcome === "incomplete") return 3;
33
33
  if (result.outcome === "failed") return 1;
@@ -496,6 +496,10 @@ function renderConformanceReporterResult(result, reporter) {
496
496
  return JSON.stringify(renderConformanceReportJson(report));
497
497
  case "junit-xml":
498
498
  return renderConformanceReportJUnitXml(report);
499
+ case "html":
500
+ throw usageError(
501
+ 'The "html" reporter is not available for this command yet. Use "json-summary" or "junit-xml".'
502
+ );
499
503
  }
500
504
  }
501
505
  function renderConformanceForCli(result, reporter, format) {
@@ -579,11 +583,11 @@ function parseReporterFormat(value) {
579
583
  if (value === void 0) {
580
584
  return void 0;
581
585
  }
582
- if (value === "json-summary" || value === "junit-xml") {
586
+ if (value === "json-summary" || value === "junit-xml" || value === "html") {
583
587
  return value;
584
588
  }
585
589
  throw usageError(
586
- `Invalid reporter "${value}". Use "json-summary" or "junit-xml".`
590
+ `Invalid reporter "${value}". Use "json-summary", "junit-xml", or "html".`
587
591
  );
588
592
  }
589
593
  function writeReporterResult(reporter, report) {
@@ -591,6 +595,10 @@ function writeReporterResult(reporter, report) {
591
595
  process.stdout.write(renderStructuredRunJUnitXml(report));
592
596
  return;
593
597
  }
598
+ if (reporter === "html") {
599
+ process.stdout.write(renderStructuredRunHtml(report));
600
+ return;
601
+ }
594
602
  writeResult(renderStructuredRunJson(report), "json");
595
603
  }
596
604
  function writeEvalDecisionSummary(format, summary, destination = process.stdout) {
@@ -618,7 +626,7 @@ async function writeJsonArtifact(outputPath, payload) {
618
626
  }
619
627
  async function writeReporterArtifact(outputPath, reporter, report) {
620
628
  const resolvedPath = path7.resolve(process.cwd(), outputPath);
621
- const body = reporter === "junit-xml" ? renderStructuredRunJUnitXml(report) : `${JSON.stringify(renderStructuredRunJson(report), null, 2)}
629
+ const body = reporter === "junit-xml" ? renderStructuredRunJUnitXml(report) : reporter === "html" ? renderStructuredRunHtml(report) : `${JSON.stringify(renderStructuredRunJson(report), null, 2)}
622
630
  `;
623
631
  try {
624
632
  return await writeFileAtomic(resolvedPath, body, { createParents: true });
@@ -6197,92 +6205,6 @@ function isNonVerdictRunResult(result) {
6197
6205
  }
6198
6206
  var EVAL_GATE_INCOMPLETE_EXIT_CODE = 3;
6199
6207
  var EVAL_GATE_USAGE_EXIT_CODE = 2;
6200
- function parsePercent(raw, flag) {
6201
- const value = raw.trim() === "" ? NaN : Number(raw);
6202
- if (!Number.isFinite(value) || value < 0 || value > 100) {
6203
- throw usageError(`${flag} must be a number between 0 and 100, got "${raw}".`);
6204
- }
6205
- return passRateFractionFromPercent(value);
6206
- }
6207
- function parseScorerMap(entries, flag, parseValue) {
6208
- const out = /* @__PURE__ */ Object.create(null);
6209
- for (const entry of entries) {
6210
- const index = entry.indexOf("=");
6211
- if (index <= 0) {
6212
- throw usageError(`${flag} must be <scorerId>=<value>, got "${entry}".`);
6213
- }
6214
- const scorerId = entry.slice(0, index).trim();
6215
- if (!scorerId) {
6216
- throw usageError(`${flag} is missing a scorer id in "${entry}".`);
6217
- }
6218
- if (Object.prototype.hasOwnProperty.call(out, scorerId)) {
6219
- throw usageError(
6220
- `${flag} names "${scorerId}" more than once; pass one threshold per scorer.`
6221
- );
6222
- }
6223
- out[scorerId] = parseValue(entry.slice(index + 1).trim(), flag);
6224
- }
6225
- return out;
6226
- }
6227
- function parseUnit(raw, flag) {
6228
- const value = raw.trim() === "" ? NaN : Number(raw);
6229
- if (!Number.isFinite(value) || value < 0 || value > 1) {
6230
- throw usageError(`${flag} must be a number between 0 and 1, got "${raw}".`);
6231
- }
6232
- return value;
6233
- }
6234
- function policyFromOptions(options) {
6235
- const policy = {};
6236
- if (options.minPassRatePercent !== void 0) {
6237
- policy.minimumPassRate = parsePercent(
6238
- options.minPassRatePercent,
6239
- "--min-pass-rate-percent"
6240
- );
6241
- }
6242
- if (options.noGatingScoreErrors) policy.noGatingScoreErrors = true;
6243
- if (options.minScorerPassRate?.length) {
6244
- policy.minimumScorerPassRate = parseScorerMap(
6245
- options.minScorerPassRate,
6246
- "--min-scorer-pass-rate",
6247
- parsePercent
6248
- );
6249
- }
6250
- if (options.minMeanScore?.length) {
6251
- policy.minimumMeanScore = parseScorerMap(
6252
- options.minMeanScore,
6253
- "--min-mean-score",
6254
- parseUnit
6255
- );
6256
- }
6257
- return policy;
6258
- }
6259
- function policyNeedsIterations(policy) {
6260
- return Boolean(
6261
- policy.noGatingScoreErrors || policy.minimumScorerPassRate || policy.minimumMeanScore || policy.maximumTotalTokens !== void 0 || // p95 comes from iteration durations, exactly like tokens come from
6262
- // iteration counts. Omitting it here would leave the latency gate
6263
- // permanently non-gateable — the fetch that could decide it never runs.
6264
- policy.maximumP95LatencyMs !== void 0
6265
- );
6266
- }
6267
- function reportForRun(run, iterations, policy) {
6268
- return evaluateGates(gateInputFromPlatformRun(run, iterations), policy);
6269
- }
6270
-
6271
- // src/lib/eval-iterations.ts
6272
- async function fetchAllIterations(client, signal, projectId, runId) {
6273
- const items = [];
6274
- let cursor;
6275
- for (let page = 0; page < 100; page += 1) {
6276
- const result = await client.listEvalRunIterations(
6277
- { projectId, runId, ...cursor ? { cursor } : {}, limit: 200 },
6278
- { signal }
6279
- );
6280
- items.push(...result.items);
6281
- if (!result.nextCursor) return { items, complete: true };
6282
- cursor = result.nextCursor;
6283
- }
6284
- return { items, complete: false };
6285
- }
6286
6208
 
6287
6209
  // src/lib/eval-compare.ts
6288
6210
  function parseNonNegativeInteger2(raw, flag) {
@@ -6408,6 +6330,374 @@ function flakyInputFrom(iterations) {
6408
6330
  passed: iteration.result === "passed"
6409
6331
  }));
6410
6332
  }
6333
+ async function fetchAllIterations(client, signal, projectId, runId) {
6334
+ const items = [];
6335
+ let cursor;
6336
+ for (let page = 0; page < 100; page += 1) {
6337
+ const result = await client.listEvalRunIterations(
6338
+ { projectId, runId, ...cursor ? { cursor } : {}, limit: 200 },
6339
+ { signal }
6340
+ );
6341
+ items.push(...result.items);
6342
+ if (!result.nextCursor) return { items, complete: true };
6343
+ cursor = result.nextCursor;
6344
+ }
6345
+ return { items, complete: false };
6346
+ }
6347
+ function p95Of(iterations) {
6348
+ if (!iterations?.complete) return void 0;
6349
+ const durations = iterations.items.map((iteration) => iteration.durationMs).filter((ms) => typeof ms === "number");
6350
+ if (durations.length === 0 || durations.length !== iterations.items.length) {
6351
+ return void 0;
6352
+ }
6353
+ return calculateLatencyStats(durations).p95;
6354
+ }
6355
+
6356
+ // src/lib/eval-gate.ts
6357
+ function parsePercent(raw, flag) {
6358
+ const value = raw.trim() === "" ? NaN : Number(raw);
6359
+ if (!Number.isFinite(value) || value < 0 || value > 100) {
6360
+ throw usageError(`${flag} must be a number between 0 and 100, got "${raw}".`);
6361
+ }
6362
+ return passRateFractionFromPercent(value);
6363
+ }
6364
+ function parseScorerMap(entries, flag, parseValue) {
6365
+ const out = /* @__PURE__ */ Object.create(null);
6366
+ for (const entry of entries) {
6367
+ const index = entry.indexOf("=");
6368
+ if (index <= 0) {
6369
+ throw usageError(`${flag} must be <scorerId>=<value>, got "${entry}".`);
6370
+ }
6371
+ const scorerId = entry.slice(0, index).trim();
6372
+ if (!scorerId) {
6373
+ throw usageError(`${flag} is missing a scorer id in "${entry}".`);
6374
+ }
6375
+ if (Object.prototype.hasOwnProperty.call(out, scorerId)) {
6376
+ throw usageError(
6377
+ `${flag} names "${scorerId}" more than once; pass one threshold per scorer.`
6378
+ );
6379
+ }
6380
+ out[scorerId] = parseValue(entry.slice(index + 1).trim(), flag);
6381
+ }
6382
+ return out;
6383
+ }
6384
+ function parseUnit(raw, flag) {
6385
+ const value = raw.trim() === "" ? NaN : Number(raw);
6386
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
6387
+ throw usageError(`${flag} must be a number between 0 and 1, got "${raw}".`);
6388
+ }
6389
+ return value;
6390
+ }
6391
+ function policyFromOptions(options) {
6392
+ const policy = {};
6393
+ if (options.minPassRatePercent !== void 0) {
6394
+ policy.minimumPassRate = parsePercent(
6395
+ options.minPassRatePercent,
6396
+ "--min-pass-rate-percent"
6397
+ );
6398
+ }
6399
+ if (options.noGatingScoreErrors) policy.noGatingScoreErrors = true;
6400
+ if (options.minScorerPassRate?.length) {
6401
+ policy.minimumScorerPassRate = parseScorerMap(
6402
+ options.minScorerPassRate,
6403
+ "--min-scorer-pass-rate",
6404
+ parsePercent
6405
+ );
6406
+ }
6407
+ if (options.minMeanScore?.length) {
6408
+ policy.minimumMeanScore = parseScorerMap(
6409
+ options.minMeanScore,
6410
+ "--min-mean-score",
6411
+ parseUnit
6412
+ );
6413
+ }
6414
+ return policy;
6415
+ }
6416
+ function policyNeedsIterations(policy) {
6417
+ return Boolean(
6418
+ policy.noGatingScoreErrors || policy.minimumScorerPassRate || policy.minimumMeanScore || policy.maximumTotalTokens !== void 0 || // p95 comes from iteration durations, exactly like tokens come from
6419
+ // iteration counts. Omitting it here would leave the latency gate
6420
+ // permanently non-gateable — the fetch that could decide it never runs.
6421
+ policy.maximumP95LatencyMs !== void 0
6422
+ );
6423
+ }
6424
+ function reportForRun(run, iterations, policy) {
6425
+ return evaluateGates(gateInputFromPlatformRun(run, iterations), policy);
6426
+ }
6427
+ var SHA_LIKE_BASELINE = /^[0-9a-f]{40}$/i;
6428
+ function assertRunIdBaseline(baseline, runId) {
6429
+ const normalized = baseline.trim();
6430
+ if (normalized === "") {
6431
+ throw usageError(
6432
+ `--baseline must not be blank. Pass a run id, or omit the flag entirely to gate on absolute thresholds only.`
6433
+ );
6434
+ }
6435
+ if (normalized === runId) {
6436
+ throw usageError(
6437
+ `--baseline "${baseline}" is the same as --run "${runId}". A run cannot be its own baseline \u2014 pass a different, earlier run id.`
6438
+ );
6439
+ }
6440
+ if (SHA_LIKE_BASELINE.test(normalized)) {
6441
+ throw usageError(
6442
+ `--baseline "${baseline}" looks like a git SHA. SHA baselines are not supported yet; pass a run id. (Source-SHA baseline resolution is a follow-up step, gated on a backend index that does not exist yet.)`
6443
+ );
6444
+ }
6445
+ return normalized;
6446
+ }
6447
+ function comparePolicyFromGateOptions(options) {
6448
+ const hasComparativeFlag = options.minSampleSize !== void 0 || options.minEffectSizePercent !== void 0 || options.gateDeterministicRegressions === true || options.maxP95LatencyIncreaseMs !== void 0;
6449
+ if (hasComparativeFlag && !options.baseline) {
6450
+ throw usageError(
6451
+ "--min-sample-size, --min-effect-size-percent, --gate-deterministic-regressions, and --max-p95-latency-increase-ms tune the baseline regression gate; pass --baseline to enable it."
6452
+ );
6453
+ }
6454
+ return comparePolicyFromOptions({
6455
+ gateRegressions: Boolean(options.baseline),
6456
+ minSampleSize: options.minSampleSize,
6457
+ minEffectSizePercent: options.minEffectSizePercent,
6458
+ gateDeterministicRegressions: options.gateDeterministicRegressions,
6459
+ maxP95LatencyIncreaseMs: options.maxP95LatencyIncreaseMs
6460
+ });
6461
+ }
6462
+ function baselineNotFoundReason(error) {
6463
+ const details = error?.details;
6464
+ return typeof details === "object" && details !== null && details.reason === "BASELINE_NOT_FOUND";
6465
+ }
6466
+ var OUTCOME_RANK = {
6467
+ passed: 0,
6468
+ incomplete: 1,
6469
+ failed: 2,
6470
+ usage_error: 3
6471
+ };
6472
+ function mergeGateReports(threshold, comparative) {
6473
+ return {
6474
+ outcome: OUTCOME_RANK[comparative.outcome] > OUTCOME_RANK[threshold.outcome] ? comparative.outcome : threshold.outcome,
6475
+ verdicts: [...threshold.verdicts, ...comparative.verdicts],
6476
+ // The run being gated IS the compare side of the baseline comparison, so
6477
+ // its own score integrity — already computed by `evaluateGates` above —
6478
+ // is the one meaning that survives the merge. The comparison's own
6479
+ // (base+compare) combined integrity is recorded separately in the
6480
+ // baseline provenance, not lost.
6481
+ scoreIntegrity: threshold.scoreIntegrity
6482
+ };
6483
+ }
6484
+ function incompatibilityReasonsFor(row, runEvaluationConfigChanged) {
6485
+ const reasons = [];
6486
+ if (row.status === "new_case") reasons.push("case_added");
6487
+ if (row.status === "removed_case") reasons.push("case_removed");
6488
+ if (row.configChanged) reasons.push("scenario_config_changed");
6489
+ if (row.evaluationConfigChanged || runEvaluationConfigChanged) {
6490
+ reasons.push("evaluation_config_changed");
6491
+ }
6492
+ if (row.base.outcome !== "absent" && row.compare.outcome !== "absent" && row.base.iterationIds.length !== row.compare.iterationIds.length) {
6493
+ reasons.push("iteration_weighting_unequal");
6494
+ }
6495
+ return reasons;
6496
+ }
6497
+ function buildBaselineProvenance(requestedBaseline, compare, input, policy) {
6498
+ const classified = compare.cases.map((row) => ({
6499
+ row,
6500
+ reasons: incompatibilityReasonsFor(
6501
+ row,
6502
+ compare.scoreContract.evaluationConfigChanged
6503
+ )
6504
+ }));
6505
+ return {
6506
+ requestedBaseline,
6507
+ baseline: compare.baseline,
6508
+ baseRunId: compare.baseRun.id,
6509
+ compareRunId: compare.compareRun.id,
6510
+ // The RESOLVED policy that produced this verdict, defaults filled in —
6511
+ // an archived report must be self-describing without cross-referencing
6512
+ // the CLI invocation that produced it. `null` means the gate was not
6513
+ // asked for, not "asked for with a threshold of nothing".
6514
+ policy: {
6515
+ passRateRegression: policy.passRateRegression ? {
6516
+ minSampleSize: policy.passRateRegression.minSampleSize ?? DEFAULT_MIN_SAMPLE_SIZE,
6517
+ minEffectSize: policy.passRateRegression.minEffectSize ?? DEFAULT_MIN_EFFECT_SIZE
6518
+ } : null,
6519
+ noDeterministicRegressions: policy.noDeterministicRegressions === true,
6520
+ maximumP95LatencyIncreaseMs: policy.maximumP95LatencyIncreaseMs ?? null
6521
+ },
6522
+ compatibility: {
6523
+ caseSetChanged: input.caseSetChanged,
6524
+ scenarioConfigChanged: input.scenarioConfigChanged,
6525
+ evaluationConfigChanged: input.evaluationConfigChanged,
6526
+ iterationWeightingEqual: input.iterationWeightingEqual,
6527
+ baseScoreIntegrity: compare.scoreContract.base.scoreIntegrity,
6528
+ compareScoreIntegrity: compare.scoreContract.compare.scoreIntegrity,
6529
+ // The pin names "comparable case ids" explicitly: which cases an
6530
+ // archived report's verdict actually covers, and which ones a
6531
+ // `caseSetChanged: true` flag alone does not name.
6532
+ comparableCaseIds: classified.filter(({ reasons }) => reasons.length === 0).map(({ row }) => row.caseKey),
6533
+ incompatibleCases: classified.filter(({ reasons }) => reasons.length > 0).map(({ row, reasons }) => ({
6534
+ caseKey: row.caseKey,
6535
+ status: row.status,
6536
+ reasons
6537
+ }))
6538
+ },
6539
+ // Dimensions the pinned contract requires but the `/compare` wire does
6540
+ // not carry today (E4b / backend follow-up work). Never invented, never
6541
+ // silently dropped.
6542
+ notRecorded: {
6543
+ modelProvider: "notRecorded",
6544
+ hostHarness: "notRecorded",
6545
+ serverEnvironmentIdentity: "notRecorded",
6546
+ configHashesBeyondEvaluationConfigHash: "notRecorded"
6547
+ }
6548
+ };
6549
+ }
6550
+ async function evaluateBaselineComparison(input) {
6551
+ let compare;
6552
+ try {
6553
+ compare = await input.client.compareEvalRun(
6554
+ {
6555
+ projectId: input.projectId,
6556
+ runId: input.runId,
6557
+ baseRunId: input.baseline
6558
+ },
6559
+ { signal: input.signal }
6560
+ );
6561
+ } catch (error) {
6562
+ const reason = baselineNotFoundReason(error);
6563
+ const detail = error instanceof Error ? error.message : String(error);
6564
+ return {
6565
+ report: {
6566
+ outcome: "incomplete",
6567
+ scoreIntegrity: "unknown",
6568
+ verdicts: [
6569
+ {
6570
+ gate: "baseline",
6571
+ status: "non_gateable",
6572
+ message: reason ? `no baseline to compare against: ${detail}` : `could not compare against the baseline: ${detail}`
6573
+ }
6574
+ ]
6575
+ }
6576
+ };
6577
+ }
6578
+ if (compare.baseRun.completedAt === null || compare.compareRun.completedAt === null) {
6579
+ return {
6580
+ report: {
6581
+ outcome: "incomplete",
6582
+ scoreIntegrity: "unknown",
6583
+ verdicts: [
6584
+ {
6585
+ gate: "baseline",
6586
+ status: "non_gateable",
6587
+ message: "both runs must be completed before they can be compared"
6588
+ }
6589
+ ]
6590
+ }
6591
+ };
6592
+ }
6593
+ const needsLatency = input.policy.maximumP95LatencyIncreaseMs !== void 0;
6594
+ let baseIterations;
6595
+ let compareIterationsForLatency = input.compareIterations;
6596
+ if (needsLatency) {
6597
+ try {
6598
+ [baseIterations, compareIterationsForLatency] = await Promise.all([
6599
+ fetchAllIterations(
6600
+ input.client,
6601
+ input.signal,
6602
+ input.projectId,
6603
+ compare.baseRun.id
6604
+ ),
6605
+ input.compareIterations ?? fetchAllIterations(
6606
+ input.client,
6607
+ input.signal,
6608
+ input.projectId,
6609
+ compare.compareRun.id
6610
+ )
6611
+ ]);
6612
+ } catch {
6613
+ baseIterations = void 0;
6614
+ compareIterationsForLatency = void 0;
6615
+ }
6616
+ }
6617
+ const compareInput = compareGateInputFrom(compare, {
6618
+ baseP95Ms: p95Of(baseIterations),
6619
+ compareP95Ms: p95Of(compareIterationsForLatency)
6620
+ });
6621
+ return {
6622
+ report: evaluateCompareGates(compareInput, input.policy),
6623
+ provenance: buildBaselineProvenance(
6624
+ input.baseline,
6625
+ compare,
6626
+ compareInput,
6627
+ input.policy
6628
+ )
6629
+ };
6630
+ }
6631
+
6632
+ // src/lib/eval-run-exit-code.ts
6633
+ var SEVERITY_ORDER = [1, 3, 4, 5, 0];
6634
+ function worstOf(codes) {
6635
+ for (const code of SEVERITY_ORDER) {
6636
+ if (codes.includes(code)) return code;
6637
+ }
6638
+ return 0;
6639
+ }
6640
+ function runExitCode(run) {
6641
+ const codes = [];
6642
+ if (isNonVerdictRunStatus(run.status)) {
6643
+ codes.push(5);
6644
+ } else if (isNonVerdictRunResult(run.result)) {
6645
+ codes.push(5);
6646
+ } else if (run.result === "failed") {
6647
+ codes.push(1);
6648
+ } else if (run.result === "passed") {
6649
+ codes.push(0);
6650
+ } else {
6651
+ codes.push(5);
6652
+ }
6653
+ if (run.reportingFailed) {
6654
+ codes.push(classifyWaitErrorExitCode(run.reportingFailedErrorCode));
6655
+ }
6656
+ return worstOf(codes);
6657
+ }
6658
+ function evalRunWaitExitCode(input) {
6659
+ const codes = [];
6660
+ if (input.launchOutcome !== "started") {
6661
+ codes.push(4);
6662
+ }
6663
+ for (const run of input.runs) {
6664
+ codes.push(runExitCode(run));
6665
+ }
6666
+ for (const waitError of input.waitErrors) {
6667
+ codes.push(classifyWaitErrorExitCode(waitError.errorCode));
6668
+ }
6669
+ return worstOf(codes);
6670
+ }
6671
+ var AUTH_SHAPED_CODES = /* @__PURE__ */ new Set([
6672
+ "UNAUTHORIZED",
6673
+ "FORBIDDEN",
6674
+ "OAUTH_REQUIRED"
6675
+ ]);
6676
+ var INVALID_SHAPED_CODES = /* @__PURE__ */ new Set([
6677
+ "VALIDATION_ERROR",
6678
+ "NOT_FOUND",
6679
+ "CONFLICT",
6680
+ "UNSUPPORTED"
6681
+ ]);
6682
+ var BILLING_SHAPED_DETAIL_CODES = /* @__PURE__ */ new Set([
6683
+ "billing_limit_reached",
6684
+ "billing_feature_not_included"
6685
+ ]);
6686
+ function isBillingShapedDetail(details) {
6687
+ if (!details || typeof details !== "object") return false;
6688
+ const inner = details.code;
6689
+ return typeof inner === "string" && BILLING_SHAPED_DETAIL_CODES.has(inner);
6690
+ }
6691
+ function classifyLaunchErrorExitCode(code, details) {
6692
+ if (isBillingShapedDetail(details)) return 4;
6693
+ if (code !== void 0 && AUTH_SHAPED_CODES.has(code)) return 3;
6694
+ if (code !== void 0 && INVALID_SHAPED_CODES.has(code)) return 2;
6695
+ return 4;
6696
+ }
6697
+ function classifyWaitErrorExitCode(code) {
6698
+ if (code !== void 0 && AUTH_SHAPED_CODES.has(code)) return 3;
6699
+ return 5;
6700
+ }
6411
6701
 
6412
6702
  // src/lib/terminal-image.ts
6413
6703
  var ESC = "\x1B";
@@ -6951,17 +7241,27 @@ function launchFailureCases(result) {
6951
7241
  ];
6952
7242
  });
6953
7243
  }
6954
- function gateReportCase(report) {
7244
+ function gateReportCase(report, baselineProvenance) {
6955
7245
  const passed = report.outcome === "passed";
6956
7246
  return {
6957
7247
  id: "gate",
6958
7248
  title: "Eval gate",
6959
7249
  category: "gate",
6960
7250
  passed,
7251
+ // Only a real FAILED gate is a confirmed regression. `incomplete` and
7252
+ // `usage_error` still fail this row (nothing was established either
7253
+ // way), but reporting them as `breaking` — the same class a genuine
7254
+ // failure gets — would claim a defect the run never observed. Mirrors
7255
+ // `gateCase` in sdk/src/run-compare.ts.
7256
+ classification: report.outcome === "failed" ? "breaking" : passed ? "non_breaking" : "informational",
6961
7257
  ...passed ? {} : {
6962
7258
  error: report.verdicts.filter((verdict) => verdict.status !== "passed").map((verdict) => verdict.message).join("; ")
6963
7259
  },
6964
- details: report
7260
+ // The baseline provenance rides along on the case row too, not only in
7261
+ // the report's top-level metadata: `--reporter junit-xml` has no other
7262
+ // place to carry it, and a regression visible in the exit code but
7263
+ // absent from the artifact is a reporting bug.
7264
+ details: baselineProvenance ? { ...report, baseline: baselineProvenance } : report
6965
7265
  };
6966
7266
  }
6967
7267
  var DEFAULT_GATE_WAIT_TIMEOUT_MS = 6e5;
@@ -6973,6 +7273,8 @@ async function runEvalGate(options, command) {
6973
7273
  ...options,
6974
7274
  noGatingScoreErrors: options.gatingScoreErrors === false
6975
7275
  });
7276
+ const baseline = options.baseline !== void 0 ? assertRunIdBaseline(options.baseline, options.run) : void 0;
7277
+ const comparePolicy = comparePolicyFromGateOptions(options);
6976
7278
  const waitTimeoutMs = options.waitTimeout !== void 0 ? parsePositiveInteger(options.waitTimeout, "--wait-timeout") : DEFAULT_GATE_WAIT_TIMEOUT_MS;
6977
7279
  const resolved = resolveCloudProjectArgs(options);
6978
7280
  let decisionSummary;
@@ -7076,34 +7378,47 @@ async function runEvalGate(options, command) {
7076
7378
  }
7077
7379
  );
7078
7380
  }
7079
- if (iterationError) {
7381
+ const thresholdReport = iterationError ? {
7382
+ outcome: "incomplete",
7383
+ scoreIntegrity: "unknown",
7384
+ verdicts: [
7385
+ {
7386
+ gate: "fetch",
7387
+ status: "non_gateable",
7388
+ message: `could not read the run: ${iterationError}`
7389
+ }
7390
+ ]
7391
+ } : reportForRun(
7392
+ run,
7393
+ policyNeedsIterations(policy) ? iterations : void 0,
7394
+ policy
7395
+ );
7396
+ const iterationsComplete = iterationError ? false : iterations?.complete ?? !needsReport;
7397
+ if (!baseline) {
7080
7398
  return {
7081
- report: {
7082
- outcome: "incomplete",
7083
- scoreIntegrity: "unknown",
7084
- verdicts: [
7085
- {
7086
- gate: "fetch",
7087
- status: "non_gateable",
7088
- message: `could not read the run: ${iterationError}`
7089
- }
7090
- ]
7091
- },
7399
+ report: thresholdReport,
7092
7400
  run,
7093
- iterations: [],
7094
- iterationsComplete: false,
7095
- iterationError
7401
+ iterations: iterations?.items ?? [],
7402
+ iterationsComplete,
7403
+ ...iterationError ? { iterationError } : {}
7096
7404
  };
7097
7405
  }
7406
+ const baselineResult = await evaluateBaselineComparison({
7407
+ client,
7408
+ signal,
7409
+ projectId: project.id,
7410
+ runId: options.run,
7411
+ baseline,
7412
+ policy: comparePolicy,
7413
+ compareIterations: iterations
7414
+ });
7098
7415
  return {
7099
- report: reportForRun(
7100
- run,
7101
- policyNeedsIterations(policy) ? iterations : void 0,
7102
- policy
7103
- ),
7416
+ report: mergeGateReports(thresholdReport, baselineResult.report),
7104
7417
  run,
7105
7418
  iterations: iterations?.items ?? [],
7106
- iterationsComplete: iterations?.complete ?? !needsReport
7419
+ iterationsComplete,
7420
+ ...iterationError ? { iterationError } : {},
7421
+ ...baselineResult.provenance ? { baselineProvenance: baselineResult.provenance } : {}
7107
7422
  };
7108
7423
  }
7109
7424
  );
@@ -7112,23 +7427,36 @@ async function runEvalGate(options, command) {
7112
7427
  throw error;
7113
7428
  }
7114
7429
  const detail = error instanceof Error ? error.message : String(error);
7115
- writeResult(
7116
- {
7117
- gate: {
7118
- outcome: "incomplete",
7119
- scoreIntegrity: "unknown",
7120
- verdicts: [
7121
- {
7122
- gate: "fetch",
7123
- status: "non_gateable",
7124
- message: `could not read the run: ${detail}`
7125
- }
7126
- ]
7127
- },
7128
- exitCode: EVAL_GATE_INCOMPLETE_EXIT_CODE
7129
- },
7130
- globalOptions.format
7131
- );
7430
+ const report = {
7431
+ outcome: "incomplete",
7432
+ scoreIntegrity: "unknown",
7433
+ verdicts: [
7434
+ {
7435
+ gate: "fetch",
7436
+ status: "non_gateable",
7437
+ message: `could not read the run: ${detail}`
7438
+ }
7439
+ ]
7440
+ };
7441
+ const structured2 = needsReport ? buildEvalRunReport([], {
7442
+ cases: [gateReportCase(report)],
7443
+ verdict: gateOutcomeVerdict(report.outcome)
7444
+ }) : void 0;
7445
+ if (options.out && structured2) {
7446
+ await writeReporterArtifact(
7447
+ options.out,
7448
+ reporter ?? "json-summary",
7449
+ structured2
7450
+ );
7451
+ }
7452
+ if (reporter && structured2) {
7453
+ writeReporterResult(reporter, structured2);
7454
+ } else {
7455
+ writeResult(
7456
+ { gate: report, exitCode: EVAL_GATE_INCOMPLETE_EXIT_CODE },
7457
+ globalOptions.format
7458
+ );
7459
+ }
7132
7460
  setProcessExitCode(EVAL_GATE_INCOMPLETE_EXIT_CODE);
7133
7461
  return;
7134
7462
  }
@@ -7143,8 +7471,10 @@ async function runEvalGate(options, command) {
7143
7471
  }
7144
7472
  ] : [],
7145
7473
  {
7146
- cases: [gateReportCase(outcome.report)],
7147
- ...decisionSummary ? { decisionSummary } : {}
7474
+ cases: [gateReportCase(outcome.report, outcome.baselineProvenance)],
7475
+ verdict: gateOutcomeVerdict(outcome.report.outcome),
7476
+ ...decisionSummary ? { decisionSummary } : {},
7477
+ ...outcome.baselineProvenance ? { metadata: { baselineComparison: outcome.baselineProvenance } } : {}
7148
7478
  }
7149
7479
  ) : void 0;
7150
7480
  if (options.out && structured) {
@@ -7461,21 +7791,9 @@ var EMPTY_DIFF = {
7461
7791
  delta: null,
7462
7792
  percentDelta: null
7463
7793
  };
7464
- function p95Of(iterations) {
7465
- if (!iterations?.complete) return void 0;
7466
- const durations = iterations.items.map((iteration) => iteration.durationMs).filter((ms) => typeof ms === "number");
7467
- if (durations.length === 0 || durations.length !== iterations.items.length) {
7468
- return void 0;
7469
- }
7470
- return calculateLatencyStats(durations).p95;
7471
- }
7472
- function baselineNotFoundReason(error) {
7473
- const details = error?.details;
7474
- return typeof details === "object" && details !== null && details.reason === "BASELINE_NOT_FOUND";
7475
- }
7476
7794
  async function writeCompareResult(args, structured) {
7477
7795
  if (args.out && structured) {
7478
- await writeJsonArtifact(args.out, structured);
7796
+ await writeReporterArtifact(args.out, args.reporter ?? "json-summary", structured);
7479
7797
  }
7480
7798
  if (args.reporter && structured) {
7481
7799
  writeReporterResult(args.reporter, structured);
@@ -7770,7 +8088,7 @@ function registerEvalCommands(program) {
7770
8088
  "--wait-timeout <ms>",
7771
8089
  "Maximum time to wait for completion (default: 600000)"
7772
8090
  ).option(
7773
- "--reporter <json-summary|junit-xml>",
8091
+ "--reporter <json-summary|junit-xml|html>",
7774
8092
  "Render the completed run report to stdout"
7775
8093
  ).option(
7776
8094
  "--out <path>",
@@ -7820,90 +8138,114 @@ function registerEvalCommands(program) {
7820
8138
  const waitTimeoutMs = options.waitTimeout !== void 0 ? parsePositiveInteger(options.waitTimeout, "--wait-timeout") : DEFAULT_RUN_WAIT_TIMEOUT_MS;
7821
8139
  let webOrigin = DEFAULT_PLATFORM_ORIGIN;
7822
8140
  const resolved = resolveCloudProjectArgs(options);
7823
- const result = await runPlatformOperation(
7824
- platformOptionsOf(command),
7825
- globalOptions.timeout,
7826
- (context) => {
7827
- webOrigin = context.webOrigin;
7828
- const onDisclosure = (disclosure) => {
7829
- writeRunDisclosure(
7830
- globalOptions.format,
7831
- disclosure,
7832
- reporter === void 0 ? process.stdout : process.stderr
7833
- );
7834
- };
7835
- const onDisclosureUnavailable = (reason) => {
7836
- if (globalOptions.format !== "human") return;
7837
- const stream = reporter === void 0 ? process.stdout : process.stderr;
7838
- stream.write(`Pre-run disclosure unavailable: ${reason}
8141
+ if (options.wait) {
8142
+ try {
8143
+ preflightCloudCredentials(platformOptionsOf(command));
8144
+ } catch (error) {
8145
+ if (error instanceof CliError && error.exitCode === 2) throw error;
8146
+ if (error instanceof CliError) {
8147
+ throw new CliError(error.code, error.message, 3, error.details);
8148
+ }
8149
+ throw error;
8150
+ }
8151
+ }
8152
+ let result;
8153
+ try {
8154
+ result = await runPlatformOperation(
8155
+ platformOptionsOf(command),
8156
+ globalOptions.timeout,
8157
+ (context) => {
8158
+ webOrigin = context.webOrigin;
8159
+ const onDisclosure = (disclosure) => {
8160
+ writeRunDisclosure(
8161
+ globalOptions.format,
8162
+ disclosure,
8163
+ reporter === void 0 ? process.stdout : process.stderr
8164
+ );
8165
+ };
8166
+ const onDisclosureUnavailable = (reason) => {
8167
+ if (globalOptions.format !== "human") return;
8168
+ const stream = reporter === void 0 ? process.stdout : process.stderr;
8169
+ stream.write(`Pre-run disclosure unavailable: ${reason}
7839
8170
  `);
7840
- };
7841
- if (options.file) {
7842
- const source = readSuiteFileInput(options.file);
7843
- return executeEvalRunFromFile(
8171
+ };
8172
+ if (options.file) {
8173
+ const source = readSuiteFileInput(options.file);
8174
+ return executeEvalRunFromFile(
8175
+ {
8176
+ client: context.client,
8177
+ signal: context.signal,
8178
+ onDisclosure,
8179
+ onDisclosureUnavailable
8180
+ },
8181
+ {
8182
+ source,
8183
+ label: options.file === "-" ? "<stdin>" : options.file,
8184
+ projectSelector: resolved.project ?? options.project,
8185
+ knobs: {
8186
+ ...options.server ? { server: options.server } : {},
8187
+ ...options.environment ? { environment: options.environment } : {},
8188
+ ...options.host ? { host: options.host } : {},
8189
+ ...options.allTargets ? { allTargets: true } : {},
8190
+ ...options.repetitions !== void 0 || options.iterations !== void 0 ? { repetitions: options.repetitions ?? options.iterations } : {},
8191
+ ...options.case?.length ? { case: options.case } : {},
8192
+ ...options.excludeSkills ? { excludeSkills: true } : {},
8193
+ ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
8194
+ ...options.notes !== void 0 ? { notes: options.notes } : {},
8195
+ ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
8196
+ ...options.matchOptions ? {
8197
+ matchOptions: parseMatchOptionsOption(
8198
+ options.matchOptions
8199
+ )
8200
+ } : {},
8201
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
8202
+ ...composeField(options)
8203
+ }
8204
+ }
8205
+ );
8206
+ }
8207
+ return runEvalSuiteOperation.execute(
8208
+ {
8209
+ project: resolved.project ?? options.project,
8210
+ suite: options.suite,
8211
+ ...options.server ? { servers: options.server } : {},
8212
+ // ONE value maps to the singular field, several to the plural:
8213
+ // the op rejects sending both, and the singular carries the
8214
+ // long-standing description a caller may already rely on.
8215
+ ...selectorField("environment", "environments", options.environment),
8216
+ ...selectorField("host", "hosts", options.host),
8217
+ ...options.allTargets ? { allAttached: true } : {},
8218
+ ...options.repetitions !== void 0 ? { repetitions: options.repetitions } : options.iterations !== void 0 ? { iterations: options.iterations } : {},
8219
+ ...options.case?.length ? { cases: options.case } : {},
8220
+ ...options.excludeSkills ? { excludeSkills: true } : {},
8221
+ ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
8222
+ ...options.notes !== void 0 ? { notes: options.notes } : {},
8223
+ ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
8224
+ ...options.matchOptions ? { matchOptions: parseMatchOptionsOption(options.matchOptions) } : {},
8225
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
8226
+ ...composeField(options)
8227
+ },
7844
8228
  {
7845
8229
  client: context.client,
7846
8230
  signal: context.signal,
7847
8231
  onDisclosure,
7848
8232
  onDisclosureUnavailable
7849
- },
7850
- {
7851
- source,
7852
- label: options.file === "-" ? "<stdin>" : options.file,
7853
- projectSelector: resolved.project ?? options.project,
7854
- knobs: {
7855
- ...options.server ? { server: options.server } : {},
7856
- ...options.environment ? { environment: options.environment } : {},
7857
- ...options.host ? { host: options.host } : {},
7858
- ...options.allTargets ? { allTargets: true } : {},
7859
- ...options.repetitions !== void 0 || options.iterations !== void 0 ? { repetitions: options.repetitions ?? options.iterations } : {},
7860
- ...options.case?.length ? { case: options.case } : {},
7861
- ...options.excludeSkills ? { excludeSkills: true } : {},
7862
- ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
7863
- ...options.notes !== void 0 ? { notes: options.notes } : {},
7864
- ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
7865
- ...options.matchOptions ? {
7866
- matchOptions: parseMatchOptionsOption(
7867
- options.matchOptions
7868
- )
7869
- } : {},
7870
- ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
7871
- ...composeField(options)
7872
- }
7873
8233
  }
7874
8234
  );
7875
- }
7876
- return runEvalSuiteOperation.execute(
7877
- {
7878
- project: resolved.project ?? options.project,
7879
- suite: options.suite,
7880
- ...options.server ? { servers: options.server } : {},
7881
- // ONE value maps to the singular field, several to the plural:
7882
- // the op rejects sending both, and the singular carries the
7883
- // long-standing description a caller may already rely on.
7884
- ...selectorField("environment", "environments", options.environment),
7885
- ...selectorField("host", "hosts", options.host),
7886
- ...options.allTargets ? { allAttached: true } : {},
7887
- ...options.repetitions !== void 0 ? { repetitions: options.repetitions } : options.iterations !== void 0 ? { iterations: options.iterations } : {},
7888
- ...options.case?.length ? { cases: options.case } : {},
7889
- ...options.excludeSkills ? { excludeSkills: true } : {},
7890
- ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
7891
- ...options.notes !== void 0 ? { notes: options.notes } : {},
7892
- ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
7893
- ...options.matchOptions ? { matchOptions: parseMatchOptionsOption(options.matchOptions) } : {},
7894
- ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
7895
- ...composeField(options)
7896
- },
7897
- {
7898
- client: context.client,
7899
- signal: context.signal,
7900
- onDisclosure,
7901
- onDisclosureUnavailable
7902
- }
8235
+ },
8236
+ { projectScope: resolved.projectScope }
8237
+ );
8238
+ } catch (error) {
8239
+ if (options.wait && error instanceof CliError && error.exitCode !== 2) {
8240
+ throw new CliError(
8241
+ error.code,
8242
+ error.message,
8243
+ classifyLaunchErrorExitCode(error.code, error.details),
8244
+ error.details
7903
8245
  );
7904
- },
7905
- { projectScope: resolved.projectScope }
7906
- );
8246
+ }
8247
+ throw error;
8248
+ }
7907
8249
  if (!options.wait) {
7908
8250
  writeResult(result, globalOptions.format);
7909
8251
  writeRunGroupSummary(globalOptions.format, webOrigin, result);
@@ -7913,6 +8255,17 @@ function registerEvalCommands(program) {
7913
8255
  return;
7914
8256
  }
7915
8257
  const needsReport = reporter !== void 0 || options.out !== void 0;
8258
+ try {
8259
+ preflightCloudCredentials(platformOptionsOf(command));
8260
+ } catch (error) {
8261
+ writeResult({ launch: result, runs: [] }, globalOptions.format);
8262
+ writeRunGroupSummary(globalOptions.format, webOrigin, result);
8263
+ if (error instanceof CliError && error.exitCode === 2) throw error;
8264
+ if (error instanceof CliError) {
8265
+ throw new CliError(error.code, error.message, 3, error.details);
8266
+ }
8267
+ throw error;
8268
+ }
7916
8269
  const completion = await runPlatformOperation(
7917
8270
  platformOptionsOf(command),
7918
8271
  Math.max(globalOptions.timeout, waitTimeoutMs),
@@ -7935,22 +8288,31 @@ function registerEvalCommands(program) {
7935
8288
  return {
7936
8289
  ok: false,
7937
8290
  runId: target.runId,
7938
- error: error instanceof Error ? error.message : String(error)
8291
+ error: error instanceof Error ? error.message : String(error),
8292
+ ...isPlatformApiError(error) ? { errorCode: error.code } : {}
7939
8293
  };
7940
8294
  }
7941
8295
  })
7942
8296
  );
7943
8297
  const runs = waited.flatMap((entry) => entry.ok ? [entry.run] : []);
7944
8298
  const waitErrors = waited.flatMap(
7945
- (entry) => !entry.ok ? [{ runId: entry.runId, error: entry.error }] : []
8299
+ (entry) => !entry.ok ? [
8300
+ {
8301
+ runId: entry.runId,
8302
+ error: entry.error,
8303
+ ...entry.errorCode ? { errorCode: entry.errorCode } : {}
8304
+ }
8305
+ ] : []
7946
8306
  );
7947
8307
  if (!needsReport) {
7948
8308
  return {
7949
8309
  runs,
7950
8310
  waitErrors,
7951
- reportInputs: []
8311
+ reportInputs: [],
8312
+ iterationErrorCodes: /* @__PURE__ */ new Map()
7952
8313
  };
7953
8314
  }
8315
+ const iterationErrorCodes = /* @__PURE__ */ new Map();
7954
8316
  const reportInputs = await Promise.all(
7955
8317
  runs.map(async (run) => {
7956
8318
  try {
@@ -7966,6 +8328,9 @@ function registerEvalCommands(program) {
7966
8328
  iterationsComplete: iterations.complete
7967
8329
  };
7968
8330
  } catch (error) {
8331
+ if (isPlatformApiError(error)) {
8332
+ iterationErrorCodes.set(run.id, error.code);
8333
+ }
7969
8334
  return {
7970
8335
  run,
7971
8336
  iterations: [],
@@ -7975,7 +8340,7 @@ function registerEvalCommands(program) {
7975
8340
  }
7976
8341
  })
7977
8342
  );
7978
- return { runs, waitErrors, reportInputs };
8343
+ return { runs, waitErrors, reportInputs, iterationErrorCodes };
7979
8344
  },
7980
8345
  {
7981
8346
  projectScope: resolved.projectScope,
@@ -7999,12 +8364,36 @@ function registerEvalCommands(program) {
7999
8364
  ...result.runGroupId ? { runGroupId: result.runGroupId } : {}
8000
8365
  }
8001
8366
  }) : void 0;
8367
+ const reportingErrors = completion.reportInputs.filter(
8368
+ (input) => !input.iterationsComplete || input.iterationError
8369
+ );
8370
+ const reportingFailedRunIds = new Set(
8371
+ reportingErrors.map((input) => input.run.id)
8372
+ );
8373
+ const runOutcomes = completion.runs.map(
8374
+ (run) => ({
8375
+ status: run.status,
8376
+ result: run.result,
8377
+ reportingFailed: reportingFailedRunIds.has(run.id),
8378
+ reportingFailedErrorCode: completion.iterationErrorCodes.get(run.id)
8379
+ })
8380
+ );
8381
+ const code = evalRunWaitExitCode({
8382
+ launchOutcome: result.outcome,
8383
+ runs: runOutcomes,
8384
+ waitErrors: completion.waitErrors
8385
+ });
8386
+ let outWriteError;
8002
8387
  if (options.out && report) {
8003
- await writeReporterArtifact(
8004
- options.out,
8005
- reporter ?? "json-summary",
8006
- report
8007
- );
8388
+ try {
8389
+ await writeReporterArtifact(
8390
+ options.out,
8391
+ reporter ?? "json-summary",
8392
+ report
8393
+ );
8394
+ } catch (error) {
8395
+ outWriteError = error instanceof Error ? error.message : String(error);
8396
+ }
8008
8397
  }
8009
8398
  if (reporter && report) {
8010
8399
  writeReporterResult(reporter, report);
@@ -8015,18 +8404,20 @@ function registerEvalCommands(program) {
8015
8404
  );
8016
8405
  writeRunGroupSummary(globalOptions.format, webOrigin, result);
8017
8406
  }
8018
- const reportingErrors = completion.reportInputs.filter(
8019
- (input) => !input.iterationsComplete || input.iterationError
8020
- );
8407
+ if (outWriteError !== void 0) {
8408
+ throw cliError("OUT_WRITE_FAILED", outWriteError, worstOf([code, 4]));
8409
+ }
8021
8410
  if (reportingErrors.length > 0 || completion.waitErrors.length > 0) {
8022
8411
  const affectedRunIds = [
8023
8412
  ...reportingErrors.map((input) => input.run.id),
8024
8413
  ...completion.waitErrors.map((entry) => entry.runId)
8025
8414
  ];
8026
- throw operationalError(
8415
+ throw cliError(
8416
+ "OPERATIONAL_ERROR",
8027
8417
  needsReport ? `Completed eval run report is incomplete for: ${affectedRunIds.join(
8028
8418
  ", "
8029
8419
  )}.` : `Did not observe completion for: ${affectedRunIds.join(", ")}.`,
8420
+ code,
8030
8421
  {
8031
8422
  // Machine-readable, because the message is not: a pipeline that
8032
8423
  // needs to resume or cancel these runs should not have to parse
@@ -8036,9 +8427,7 @@ function registerEvalCommands(program) {
8036
8427
  }
8037
8428
  );
8038
8429
  }
8039
- if (result.outcome !== "started") {
8040
- setProcessExitCode(1);
8041
- }
8430
+ setProcessExitCode(code);
8042
8431
  }
8043
8432
  );
8044
8433
  addProjectOption(
@@ -8227,11 +8616,26 @@ function registerEvalCommands(program) {
8227
8616
  "Minimum mean score for one scorer (repeatable)",
8228
8617
  collectRepeatable,
8229
8618
  []
8619
+ ).option(
8620
+ "--baseline <runId>",
8621
+ "Baseline run ID to gate a regression delta against (SHA baselines are not supported yet)"
8622
+ ).option(
8623
+ "--min-sample-size <n>",
8624
+ "Iterations required on EACH side before a pass-rate regression is decidable (default 5); requires --baseline"
8625
+ ).option(
8626
+ "--min-effect-size-percent <0-100>",
8627
+ "Smallest pass-rate drop worth failing on, as a percentage (default 1); requires --baseline"
8628
+ ).option(
8629
+ "--gate-deterministic-regressions",
8630
+ "Fail if a deterministic gating scorer flipped from passed to failed; requires --baseline"
8631
+ ).option(
8632
+ "--max-p95-latency-increase-ms <ms>",
8633
+ "Fail if p95 end-to-end latency rose by more than this many milliseconds vs the baseline; requires --baseline"
8230
8634
  ).option("--wait", "Poll until the run reaches a terminal status").option(
8231
8635
  "--wait-timeout <ms>",
8232
8636
  "Give up waiting after this many milliseconds (default 600000)"
8233
8637
  ).option(
8234
- "--reporter <json-summary|junit-xml>",
8638
+ "--reporter <json-summary|junit-xml|html>",
8235
8639
  "Write a structured report to stdout instead of the default output"
8236
8640
  ).option(
8237
8641
  "--out <path>",
@@ -8264,9 +8668,12 @@ function registerEvalCommands(program) {
8264
8668
  "--max-p95-latency-increase-ms <ms>",
8265
8669
  "Fail if p95 end-to-end latency rose by more than this many milliseconds"
8266
8670
  ).option(
8267
- "--reporter <json-summary|junit-xml>",
8671
+ "--reporter <json-summary|junit-xml|html>",
8268
8672
  "Write a structured report to stdout instead of the default output"
8269
- ).option("--out <path>", "Write the structured report to a JSON file").action(
8673
+ ).option(
8674
+ "--out <path>",
8675
+ "Atomically write the structured report selected by --reporter (default: json-summary)"
8676
+ ).action(
8270
8677
  async (options, command) => {
8271
8678
  await runEvalCompare(options, command);
8272
8679
  }
@@ -13695,6 +14102,11 @@ function registerConformanceRunCommand(program) {
13695
14102
  const reporter = parseReporterFormat(
13696
14103
  options.reporter
13697
14104
  );
14105
+ if (reporter === "html") {
14106
+ throw usageError(
14107
+ 'The "html" reporter is not available for this command yet. Use "json-summary" or "junit-xml".'
14108
+ );
14109
+ }
13698
14110
  const format = resolveConformanceOutputFormatForCli(
13699
14111
  globalOptions.format,
13700
14112
  process.stdout.isTTY,
@@ -15759,7 +16171,7 @@ function registerServerCommands(program) {
15759
16171
  "Diff failure policy: breaking, any, or none"
15760
16172
  ).option(
15761
16173
  "--reporter <reporter>",
15762
- "Structured reporter output: json-summary or junit-xml"
16174
+ "Structured reporter output: json-summary, junit-xml, or html"
15763
16175
  ).option("--out <path>", "Write the raw diff JSON artifact to a file")
15764
16176
  )
15765
16177
  ).action(async (options, command) => {
@@ -18007,7 +18419,7 @@ function registerToolsCommands(program) {
18007
18419
  "Evaluate the tool-call outcome policy against isError"
18008
18420
  ).option(
18009
18421
  "--reporter <reporter>",
18010
- "Structured reporter output: json-summary or junit-xml"
18422
+ "Structured reporter output: json-summary, junit-xml, or html"
18011
18423
  ).option(
18012
18424
  "--debug-out <path>",
18013
18425
  "Write a structured debug artifact to a file"