@mcpjam/cli 5.5.2 → 5.7.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, listServerSkillCatalog, getVerifiedServerSkill, isServerSkillRefusalError, readVerifiedServerSkillFile, 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, GATE_WAIVER_MAX_REASON_LENGTH, GATE_WAIVER_REASON_NOTICE, MCPClientManager, withSkillsExtensionCapability, MCP_SKILLS_EXTENSION_ID, 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, declareEvalSuiteFileValidity, formatEvalRunDecisionSummary, gateOutcomeVerdict, applyGateWaiver, formatGateReport, formatGateWaiverLine, detectFlakyCases, evaluateCompareGates, buildRunCompareReport, formatSuiteFileFindings, serializeEvalSuiteFile, MAX_SUITE_FILE_BYTES, buildCorpus, HostedOnlyCaseError, verifyCorpusLock, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, canonicalDigest, readEvalRunDecisionSummary as readEvalRunDecisionSummary$1, buildEvalRunDecisionSummary, evaluateGates, gateInputFromPlatformRun, isGateWaiverInForce, calculateLatencyStats, CORPUS_LOCK_VERSION, suiteFilePointer, passRateFractionFromPercent, DEFAULT_MIN_EFFECT_SIZE, DEFAULT_MIN_SAMPLE_SIZE, isUnknownTaskError, isMCPTasksWireError, LEGACY_TASK_STATUSES } from '@mcpjam/sdk';
5
+ import { probeMcpServer, redactForTelemetry, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, classifyMcpHeader, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, listServerSkillCatalog, getVerifiedServerSkill, isServerSkillRefusalError, readVerifiedServerSkillFile, 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, GATE_WAIVER_MAX_REASON_LENGTH, GATE_WAIVER_REASON_NOTICE, MCPClientManager, withSkillsExtensionCapability, MCP_SKILLS_EXTENSION_ID, 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, declareEvalSuiteFileValidity, formatEvalRunDecisionSummary, gateOutcomeVerdict, applyGateWaiver, formatGateReport, formatGateWaiverLine, detectFlakyCases, evaluateCompareGates, buildRunCompareReport, formatSuiteFileFindings, serializeEvalSuiteFile, MAX_SUITE_FILE_BYTES, buildCorpus, HostedOnlyCaseError, verifyCorpusLock, detectCiMetadata, detectLauncherKind, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, canonicalDigest, readEvalRunDecisionSummary as readEvalRunDecisionSummary$1, buildEvalRunDecisionSummary, evaluateGates, gateInputFromPlatformRun, isGateWaiverInForce, calculateLatencyStats, CORPUS_LOCK_VERSION, suiteFilePointer, passRateFractionFromPercent, DEFAULT_MIN_EFFECT_SIZE, DEFAULT_MIN_SAMPLE_SIZE, 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
- import os, { homedir } from 'os';
12
- import { getRegistryDirectoryServerOperation, listOrganizationsOperation, listProjectsOperation, createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, cancelProjectServerConnectionOperation, 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, createClientOperation, updateClientOperation, setClientServersOperation, duplicateClientOperation, createEnvironmentOperation, ensureAdhocEnvironmentOperation, nameEnvironmentOperation, updateEnvironmentOperation, createSecretOperation, updateSecretOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, runOperationWithPermalinks, withPermalinkEnvelope, PlatformApiError, installRegistryServerOperation, installRegistryDirectoryServerOperation, getProjectServerOperation, DEFAULT_PLATFORM_API_BASE_URL, projectResolutionError, listProjectServersOperation, createProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, isPlatformApiError, createEvalSuiteOperation, listEvalSuitesOperation, buildAppPermalink, listEvalSuiteStageAnalyticsOperation, getEvalRunStageAnalyticsOperation, resolveEnvironmentOperation, listClientsOperation, getClientOperation, deleteClientOperation, listEnvironmentsOperation, getEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listSecretsOperation, getSecretOperation, deleteSecretOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, listProjectSkillsOperation, getProjectSkillOperation, listJourneysOperation, listJourneyRunsOperation, getJourneyRunOperation, launchJourneyRunOperation, cancelJourneyRunOperation, listJourneyRunSessionsOperation, listScenariosOperation, getScenarioOperation, publishScenarioOperation, unpublishScenarioOperation, PlatformApiClient, listServerToolsOperation, 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';
11
+ import os, { homedir, tmpdir } from 'os';
12
+ import { RUN_LAUNCH_HEADERS, getRegistryDirectoryServerOperation, listOrganizationsOperation, listProjectsOperation, createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, cancelProjectServerConnectionOperation, listChatSessionsOperation, resolveProject, createTunnelOperation, listEvalSuiteRunsOperation, listEvalSuiteRevisionsOperation, runEvalSuiteOperation, getEvalRunOperation, getEvalRunRouteFactsOperation, getEvalRunServerFactsOperation, proposeEvalDescriptionRewriteOperation, startEvalDescriptionExperimentOperation, getEvalDescriptionExperimentOperation, cancelEvalRunOperation, requestEvalRunJudgeOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, createClientOperation, updateClientOperation, setClientServersOperation, duplicateClientOperation, createEnvironmentOperation, ensureAdhocEnvironmentOperation, nameEnvironmentOperation, updateEnvironmentOperation, createSecretOperation, updateSecretOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, listTraceDestinationsOperation, getTraceDestinationOperation, createTraceDestinationOperation, updateTraceDestinationOperation, deleteTraceDestinationOperation, testTraceDestinationOperation, pauseTraceDestinationOperation, resumeTraceDestinationOperation, backfillTraceDestinationOperation, listTraceDestinationBackfillsOperation, runOperationWithPermalinks, withPermalinkEnvelope, PlatformApiError, installRegistryServerOperation, installRegistryDirectoryServerOperation, getProjectServerOperation, DEFAULT_PLATFORM_API_BASE_URL, projectResolutionError, listProjectServersOperation, createProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, isPlatformApiError, createEvalSuiteOperation, listEvalSuitesOperation, buildAppPermalink, listEvalSuiteStageAnalyticsOperation, getEvalRunStageAnalyticsOperation, listEvalGithubReposOperation, connectEvalGithubRepoOperation, resolveEnvironmentOperation, listClientsOperation, getClientOperation, deleteClientOperation, listEnvironmentsOperation, getEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listSecretsOperation, getSecretOperation, deleteSecretOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, listProjectSkillsOperation, getProjectSkillOperation, listJourneysOperation, listJourneyRunsOperation, getJourneyRunOperation, launchJourneyRunOperation, cancelJourneyRunOperation, listJourneyRunSessionsOperation, listScenariosOperation, getScenarioOperation, publishScenarioOperation, unpublishScenarioOperation, PlatformApiClient, listServerToolsOperation, runEvalCaseOperation, 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 { MAX_BATCH_CREATE_CASES, evalSuiteFileSchema, MAX_IMPORT_NOTE_CHARS, isOpaqueId } from '@mcpjam/sdk/contract';
14
+ import { composeSuiteGateWithBaseReport, MAX_BATCH_CREATE_CASES, evalSuiteFileSchema, MAX_IMPORT_NOTE_CHARS, isOpaqueId } from '@mcpjam/sdk/contract';
15
15
  import { HOST_TEMPLATES, 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: "5.5.2"};
30
+ version: "5.7.0"};
31
31
  function conformanceExitCode(result) {
32
32
  if (result.outcome === "incomplete") return 3;
33
33
  if (result.outcome === "failed") return 1;
@@ -1561,18 +1561,18 @@ async function ensureInspector(options = {}) {
1561
1561
  const explicitFrontendUrl = options.frontendUrl !== void 0 ? normalizeExplicitInspectorFrontendUrl(options.frontendUrl) : void 0;
1562
1562
  const health = await getInspectorHealth(baseUrl);
1563
1563
  if (health.healthy) {
1564
- const browserBaseUrl2 = explicitFrontendUrl ?? await resolveInspectorBrowserBaseUrlForHealth(baseUrl, health.frontendUrl, {
1564
+ const browserBaseUrl3 = explicitFrontendUrl ?? await resolveInspectorBrowserBaseUrlForHealth(baseUrl, health.frontendUrl, {
1565
1565
  hasActiveClient: health.hasActiveClient,
1566
1566
  openBrowser: options.openBrowser === true,
1567
1567
  skipDiscovery: options.skipDiscovery
1568
1568
  });
1569
- const url2 = buildInspectorUrl(browserBaseUrl2, options.tab);
1569
+ const url2 = buildInspectorUrl(browserBaseUrl3, options.tab);
1570
1570
  if (options.openBrowser && !health.hasActiveClient) {
1571
1571
  openUrl(url2);
1572
1572
  }
1573
1573
  return {
1574
1574
  baseUrl,
1575
- ...browserBaseUrl2 !== baseUrl ? { frontendUrl: browserBaseUrl2 } : {},
1575
+ ...browserBaseUrl3 !== baseUrl ? { frontendUrl: browserBaseUrl3 } : {},
1576
1576
  hasActiveClient: health.hasActiveClient,
1577
1577
  url: url2,
1578
1578
  started: false
@@ -1586,7 +1586,7 @@ async function ensureInspector(options = {}) {
1586
1586
  await startInspector(baseUrl, options.timeoutMs ?? DEFAULT_START_TIMEOUT_MS);
1587
1587
  clearInspectorSessionTokenCache(baseUrl);
1588
1588
  const startedHealth = await getInspectorHealth(baseUrl);
1589
- const browserBaseUrl = explicitFrontendUrl ?? await resolveInspectorBrowserBaseUrlForHealth(
1589
+ const browserBaseUrl2 = explicitFrontendUrl ?? await resolveInspectorBrowserBaseUrlForHealth(
1590
1590
  baseUrl,
1591
1591
  startedHealth.frontendUrl,
1592
1592
  {
@@ -1595,13 +1595,13 @@ async function ensureInspector(options = {}) {
1595
1595
  skipDiscovery: options.skipDiscovery
1596
1596
  }
1597
1597
  );
1598
- const url = buildInspectorUrl(browserBaseUrl, options.tab);
1598
+ const url = buildInspectorUrl(browserBaseUrl2, options.tab);
1599
1599
  if (options.openBrowser) {
1600
1600
  openUrl(url);
1601
1601
  }
1602
1602
  return {
1603
1603
  baseUrl,
1604
- ...browserBaseUrl !== baseUrl ? { frontendUrl: browserBaseUrl } : {},
1604
+ ...browserBaseUrl2 !== baseUrl ? { frontendUrl: browserBaseUrl2 } : {},
1605
1605
  hasActiveClient: startedHealth.hasActiveClient,
1606
1606
  url,
1607
1607
  started: true
@@ -1783,7 +1783,7 @@ var InspectorApiClient = class {
1783
1783
  );
1784
1784
  }
1785
1785
  const payload = await readResponsePayload(response);
1786
- if (!response.ok) {
1786
+ if (!response.ok && !init.treatAsSuccess?.(response.status, payload)) {
1787
1787
  throw operationalError(
1788
1788
  getErrorMessage(payload) ?? `Inspector request ${path9} failed with ${response.status}.`,
1789
1789
  payload
@@ -4062,7 +4062,13 @@ function resolveExplicitApiUrl(options, env) {
4062
4062
  var RESERVED_HEADER_NAMES = /* @__PURE__ */ new Set([
4063
4063
  "authorization",
4064
4064
  "idempotency-key",
4065
- "content-type"
4065
+ "content-type",
4066
+ // The run's DECLARED origin, which this client sets from the environment. A
4067
+ // `--header` that could overwrite it would let a badge be forged from a flag
4068
+ // — which is exactly why the platform's own `source` is stamped server-side
4069
+ // and why `user-agent`-derived attribution was removed as forgeable.
4070
+ RUN_LAUNCH_HEADERS.launcher,
4071
+ RUN_LAUNCH_HEADERS.ci
4066
4072
  ]);
4067
4073
  var HEADER_NAME_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
4068
4074
  function parseHeader2(raw, source) {
@@ -4086,7 +4092,7 @@ function parseHeader2(raw, source) {
4086
4092
  const lower = name.toLowerCase();
4087
4093
  if (RESERVED_HEADER_NAMES.has(lower)) {
4088
4094
  throw usageError(
4089
- `${source} cannot set ${JSON.stringify(name)} \u2014 it is derived from the credential and request`
4095
+ `${source} cannot set ${JSON.stringify(name)} \u2014 the CLI derives it from the credential, the request, or the environment`
4090
4096
  );
4091
4097
  }
4092
4098
  return [lower, value];
@@ -4126,6 +4132,26 @@ function buildPlatformClient(options, deps = {}) {
4126
4132
  ...deps.fetchFn ? { fetch: deps.fetchFn } : {},
4127
4133
  ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
4128
4134
  userAgent: `mcpjam-cli/${package_default.version}`,
4135
+ // WHAT THIS PROCESS IS, declared on every eval-run launch.
4136
+ //
4137
+ // The platform stamps `source` itself and everything over the public API
4138
+ // is `api`, so a CLI run and a GitHub Actions job were the same badge.
4139
+ // `detectLauncherKind` reads `GITHUB_ACTIONS` — the same test
4140
+ // `report-conformance-run`'s `detectSource` uses, so a composite run and
4141
+ // an eval run from one job never disagree about where they came from.
4142
+ //
4143
+ // Declared, not proven, and the platform treats it that way: it is a
4144
+ // display label beside the stamp, never an authorization input. A secret
4145
+ // that could prove it cannot live in a public npm package.
4146
+ launcher: {
4147
+ kind: detectLauncherKind(env, "cli"),
4148
+ client: "mcpjam-cli",
4149
+ version: package_default.version
4150
+ },
4151
+ ...(() => {
4152
+ const ci = detectCiMetadata(env);
4153
+ return ci ? { ci } : {};
4154
+ })(),
4129
4155
  ...extraHeaders ? { extraHeaders } : {}
4130
4156
  });
4131
4157
  return { client, credentialKind: credential.kind, baseUrl: resolvedBaseUrl };
@@ -4137,11 +4163,22 @@ function webOriginForApiBaseUrl(baseUrl) {
4137
4163
  return DEFAULT_PLATFORM_ORIGIN;
4138
4164
  }
4139
4165
  }
4166
+ function ciOwnedSuiteReason(details) {
4167
+ return typeof details === "object" && details !== null && details.reason === "CI_OWNED_SUITE_READ_ONLY";
4168
+ }
4140
4169
  function toCliError(error) {
4141
4170
  if (error instanceof CliError) {
4142
4171
  return error;
4143
4172
  }
4144
4173
  if (isPlatformApiError(error)) {
4174
+ if (ciOwnedSuiteReason(error.details)) {
4175
+ return cliError(
4176
+ "CI_OWNED_SUITE_READ_ONLY",
4177
+ `${error.message} If this run is syncing a suite file, make sure the file's \`suite.id\` still matches the suite it created \u2014 a renamed id no longer owns it.`,
4178
+ 1,
4179
+ error.details
4180
+ );
4181
+ }
4145
4182
  const message = error.code === "UNAUTHORIZED" ? `${error.message} Run \`mcpjam cloud login\` or pass a valid sk_ API key.` : error.message;
4146
4183
  return cliError(error.code, message, 1, error.details);
4147
4184
  }
@@ -5601,6 +5638,38 @@ function extractIterationVideoUrl(result) {
5601
5638
  const trace = asRecord(root.trace) ?? root;
5602
5639
  return asString(trace.videoUrl);
5603
5640
  }
5641
+ function extractIterationVideoMeta(result) {
5642
+ const root = asRecord(result);
5643
+ if (!root) return void 0;
5644
+ const trace = asRecord(root.trace) ?? root;
5645
+ const meta = asRecord(trace.videoMeta);
5646
+ if (!meta) return void 0;
5647
+ const out = {};
5648
+ if (typeof meta.source === "string") out.source = meta.source;
5649
+ if (typeof meta.fps === "number") out.fps = meta.fps;
5650
+ if (typeof meta.durationMs === "number") out.durationMs = meta.durationMs;
5651
+ if (typeof meta.distinctFrames === "number") {
5652
+ out.distinctFrames = meta.distinctFrames;
5653
+ }
5654
+ if (typeof meta.truncated === "boolean") out.truncated = meta.truncated;
5655
+ return Object.keys(out).length > 0 ? out : void 0;
5656
+ }
5657
+ function iterationVideoExtension(meta) {
5658
+ return meta?.source === "hosted" ? "mp4" : "webm";
5659
+ }
5660
+ function describeIterationVideo(meta) {
5661
+ if (!meta) return "";
5662
+ const parts = [];
5663
+ if (typeof meta.durationMs === "number" && meta.durationMs > 0) {
5664
+ parts.push(`${Math.round(meta.durationMs / 1e3)}s`);
5665
+ }
5666
+ if (typeof meta.fps === "number" && meta.fps > 0) parts.push(`${meta.fps}fps`);
5667
+ if (typeof meta.distinctFrames === "number") {
5668
+ parts.push(`${meta.distinctFrames} distinct frames`);
5669
+ }
5670
+ if (meta.truncated) parts.push("STOPPED AT THE SIZE LIMIT");
5671
+ return parts.join(" \xB7 ");
5672
+ }
5604
5673
  function screenshotFilename(shot, index) {
5605
5674
  const tool = (shot.toolName ?? "widget").replace(/[^a-zA-Z0-9_-]+/g, "-");
5606
5675
  const suffix = shot.toolCallId ? shot.toolCallId.replace(/[^a-zA-Z0-9_-]+/g, "-") : String(index + 1);
@@ -5621,6 +5690,14 @@ function suiteFileTooLarge(bytes, limit) {
5621
5690
  `the suite serializes to ${bytes} bytes, over the ${limit}-byte limit a suite file may be. Nothing was written. Split the suite into smaller ones and export each \u2014 this never truncates.`
5622
5691
  );
5623
5692
  }
5693
+ function suiteVerdictPolicyThreshold(settings) {
5694
+ if (!isVerdictPolicyV2Suite(settings)) return null;
5695
+ const threshold = settings.verdictPolicyDefaults?.passThreshold;
5696
+ return typeof threshold === "number" && threshold >= 0 && threshold <= 1 ? threshold : null;
5697
+ }
5698
+ function isVerdictPolicyV2Suite(settings) {
5699
+ return settings.policy === "v2" || settings.verdictPolicyVersion === 2;
5700
+ }
5624
5701
  function percentToFraction(percent) {
5625
5702
  if (!Number.isFinite(percent)) return null;
5626
5703
  const text = plainDecimal(percent);
@@ -5735,7 +5812,16 @@ function suiteLevelFindings(detail, cases, environment) {
5735
5812
  )
5736
5813
  );
5737
5814
  }
5738
- if (settings.minimumAccuracy === null || settings.minimumAccuracy === void 0) {
5815
+ if (isVerdictPolicyV2Suite(settings)) {
5816
+ if (suiteVerdictPolicyThreshold(settings) === null) {
5817
+ findings.push(
5818
+ unsupported(
5819
+ ["settings", "verdictPolicyDefaults", "passThreshold"],
5820
+ "suite is on verdict policy 2 but its stored `verdictPolicyDefaults.passThreshold` is missing or not a fraction in [0,1], so there is no threshold to write. Its legacy `minimumAccuracy` is NOT a stand-in \u2014 the platform stopped reading that at upgrade, and exporting it would claim a threshold no run uses. Set the suite's passThreshold and export again."
5821
+ )
5822
+ );
5823
+ }
5824
+ } else if (settings.minimumAccuracy === null || settings.minimumAccuracy === void 0) {
5739
5825
  findings.push(
5740
5826
  unsupported(
5741
5827
  ["settings", "minimumAccuracy"],
@@ -5985,7 +6071,11 @@ function buildSuiteFileFromPlatform(input) {
5985
6071
  ...executionConfig.systemPrompt === void 0 ? {} : { systemPrompt: executionConfig.systemPrompt },
5986
6072
  ...executionConfig.temperature === void 0 ? {} : { temperature: executionConfig.temperature },
5987
6073
  repetitions,
5988
- passThreshold: percentToFraction(
6074
+ // A v2 suite uses its own fraction; a legacy one converts its percent.
6075
+ // Never the other way round for a v2 suite: `suiteLevelFindings` has
6076
+ // already refused the export when a v2 threshold is unreadable, so this
6077
+ // `??` can only reach the legacy branch for a legacy suite.
6078
+ passThreshold: isVerdictPolicyV2Suite(detail.settings) ? suiteVerdictPolicyThreshold(detail.settings) : percentToFraction(
5989
6079
  detail.settings.minimumAccuracy
5990
6080
  ),
5991
6081
  // `{}`, not the resolved defaults: the contract documents them and the
@@ -6080,6 +6170,7 @@ function fileCaseToCreateBody(testCase) {
6080
6170
  id: testCase.id,
6081
6171
  title: testCase.title,
6082
6172
  ...testCase.intent !== void 0 ? { intent: testCase.intent } : {},
6173
+ ...testCase.kind !== void 0 ? { kind: testCase.kind } : {},
6083
6174
  steps: testCase.steps,
6084
6175
  iterations: testCase.repetitions,
6085
6176
  repetitions: testCase.repetitions,
@@ -6102,6 +6193,7 @@ function fileCaseToUpdateBody(testCase) {
6102
6193
  // A file re-sync is authoritative: unlike an ordinary PATCH, a missing
6103
6194
  // label must clear the old one rather than preserve stale attribution.
6104
6195
  intent: testCase.intent ?? null,
6196
+ kind: testCase.kind ?? null,
6105
6197
  steps: testCase.steps,
6106
6198
  iterations: testCase.repetitions,
6107
6199
  repetitions: testCase.repetitions,
@@ -6286,7 +6378,10 @@ async function syncFileOwnedCases(client, params) {
6286
6378
  {
6287
6379
  projectId: params.projectId,
6288
6380
  suiteId: params.suiteId,
6289
- body: { cases: chunk.map(fileCaseToCreateBody) }
6381
+ body: {
6382
+ cases: chunk.map(fileCaseToCreateBody),
6383
+ declaredSuiteId: params.declaredSuiteId
6384
+ }
6290
6385
  },
6291
6386
  { signal: params.signal }
6292
6387
  );
@@ -6324,7 +6419,10 @@ async function syncFileOwnedCases(client, params) {
6324
6419
  projectId: params.projectId,
6325
6420
  suiteId: params.suiteId,
6326
6421
  caseId: row.id,
6327
- body: fileCaseToUpdateBody(file)
6422
+ body: {
6423
+ ...fileCaseToUpdateBody(file),
6424
+ declaredSuiteId: params.declaredSuiteId
6425
+ }
6328
6426
  },
6329
6427
  { signal: params.signal }
6330
6428
  );
@@ -6358,7 +6456,9 @@ async function syncFileOwnedCases(client, params) {
6358
6456
  {
6359
6457
  projectId: params.projectId,
6360
6458
  suiteId: params.suiteId,
6361
- caseId: row.id
6459
+ caseId: row.id,
6460
+ // A query param on this one — the route reads no body.
6461
+ declaredSuiteId: params.declaredSuiteId
6362
6462
  },
6363
6463
  { signal: params.signal }
6364
6464
  );
@@ -6646,6 +6746,9 @@ async function executeEvalRunFromFile(context, params) {
6646
6746
  suiteId: synced.suite.id,
6647
6747
  cases: outgoingCases,
6648
6748
  declaredCaseIds: new Set(outgoingCases.map((testCase) => testCase.id)),
6749
+ // The suite is CI-owned by virtue of this very id, so every write below
6750
+ // has to name it. See `syncFileOwnedCases`.
6751
+ declaredSuiteId: authored.suite.id,
6649
6752
  signal: context.signal
6650
6753
  });
6651
6754
  const hasExplicitTarget = Boolean(
@@ -6658,6 +6761,7 @@ async function executeEvalRunFromFile(context, params) {
6658
6761
  {
6659
6762
  project: project.id,
6660
6763
  suite: synced.suite.id,
6764
+ declaredSuiteId: authored.suite.id,
6661
6765
  hosts: authored.target.hosts.map((host) => ({
6662
6766
  host: host.id ?? host.name,
6663
6767
  ...host.servers ? {
@@ -6673,6 +6777,7 @@ async function executeEvalRunFromFile(context, params) {
6673
6777
  {
6674
6778
  project: project.id,
6675
6779
  suite: synced.suite.id,
6780
+ declaredSuiteId: authored.suite.id,
6676
6781
  environments: [fileEnvironment]
6677
6782
  },
6678
6783
  { client: context.client, signal: context.signal }
@@ -6943,9 +7048,14 @@ var EVAL_GATE_USAGE_EXIT_CODE = 2;
6943
7048
  function parseNonNegativeInteger2(raw, flag) {
6944
7049
  const value = raw.trim() === "" ? NaN : Number(raw);
6945
7050
  if (!Number.isInteger(value) || value < 0) {
6946
- throw usageError(
6947
- `${flag} must be a non-negative integer, got "${raw}".`
6948
- );
7051
+ throw usageError(`${flag} must be a non-negative integer, got "${raw}".`);
7052
+ }
7053
+ return value;
7054
+ }
7055
+ function parseNonNegativeDecimal(raw, flag) {
7056
+ const value = raw.trim() === "" ? NaN : Number(raw);
7057
+ if (!Number.isFinite(value) || value < 0) {
7058
+ throw usageError(`${flag} must be a non-negative number, got "${raw}".`);
6949
7059
  }
6950
7060
  return value;
6951
7061
  }
@@ -6988,6 +7098,12 @@ function comparePolicyFromOptions(options) {
6988
7098
  "--max-p95-latency-increase-ms"
6989
7099
  );
6990
7100
  }
7101
+ if (options.maxCostIncreasePercent !== void 0) {
7102
+ policy.maximumCostIncreasePercent = parseNonNegativeDecimal(
7103
+ options.maxCostIncreasePercent,
7104
+ "--max-cost-increase-percent"
7105
+ );
7106
+ }
6991
7107
  return policy;
6992
7108
  }
6993
7109
  var CASE_SET_CHANGED_STATUSES = /* @__PURE__ */ new Set(["new_case", "removed_case"]);
@@ -7015,28 +7131,46 @@ function iterationWeightingEqualFrom(cases) {
7015
7131
  }
7016
7132
  return true;
7017
7133
  }
7018
- function sideFromRun(summary, integrity, e2eP95Ms) {
7134
+ function sideFromRun(summary, integrity, e2eP95Ms, cost = {}) {
7135
+ const totals = {
7136
+ ...e2eP95Ms !== void 0 ? { e2eP95Ms } : {},
7137
+ ...cost.costUsd !== void 0 ? { costUsd: cost.costUsd } : {},
7138
+ ...cost.costCoverage !== void 0 ? { costCoverage: cost.costCoverage } : {}
7139
+ };
7019
7140
  return {
7020
7141
  iterations: {
7021
7142
  total: summary?.total ?? 0,
7022
7143
  passed: summary?.passed ?? 0
7023
7144
  },
7024
7145
  ...integrity ? { scoreIntegrity: integrity } : {},
7025
- ...e2eP95Ms !== void 0 ? { totals: { e2eP95Ms } } : {}
7146
+ ...Object.keys(totals).length > 0 ? { totals } : {}
7026
7147
  };
7027
7148
  }
7028
7149
  function compareGateInputFrom(compare, latency = {}) {
7029
7150
  const cases = compare.cases;
7030
7151
  return {
7152
+ // Cost comes STRAIGHT OFF the wire, unlike p95: the compare DTO already
7153
+ // carries whole-run cost with its coverage, so no iteration fetch is
7154
+ // needed to decide a cost-increase gate. Coverage travels with it because
7155
+ // the gate refuses on a partial sum — a run we priced less of would
7156
+ // otherwise read as the cheaper run.
7031
7157
  base: sideFromRun(
7032
7158
  compare.baseRun.summary,
7033
7159
  compare.scoreContract.base.scoreIntegrity,
7034
- latency.baseP95Ms
7160
+ latency.baseP95Ms,
7161
+ {
7162
+ ...typeof compare.metrics.estimatedCostUsd.base === "number" ? { costUsd: compare.metrics.estimatedCostUsd.base } : {},
7163
+ ...compare.metrics.costCoverage ? { costCoverage: compare.metrics.costCoverage.base } : {}
7164
+ }
7035
7165
  ),
7036
7166
  compare: sideFromRun(
7037
7167
  compare.compareRun.summary,
7038
7168
  compare.scoreContract.compare.scoreIntegrity,
7039
- latency.compareP95Ms
7169
+ latency.compareP95Ms,
7170
+ {
7171
+ ...typeof compare.metrics.estimatedCostUsd.compare === "number" ? { costUsd: compare.metrics.estimatedCostUsd.compare } : {},
7172
+ ...compare.metrics.costCoverage ? { costCoverage: compare.metrics.costCoverage.compare } : {}
7173
+ }
7040
7174
  ),
7041
7175
  deterministicScoreRegressions: deterministicRegressionsFrom(cases),
7042
7176
  scoreDeltasAvailable: cases.some((row) => row.scoreDeltas.length > 0),
@@ -7116,6 +7250,13 @@ function parseScorerMap(entries, flag, parseValue) {
7116
7250
  }
7117
7251
  return out;
7118
7252
  }
7253
+ function parseNonNegativeDecimal2(raw, flag) {
7254
+ const value = raw.trim() === "" ? NaN : Number(raw);
7255
+ if (!Number.isFinite(value) || value < 0) {
7256
+ throw usageError(`${flag} must be a non-negative number, got "${raw}".`);
7257
+ }
7258
+ return value;
7259
+ }
7119
7260
  function parseUnit(raw, flag) {
7120
7261
  const value = raw.trim() === "" ? NaN : Number(raw);
7121
7262
  if (!Number.isFinite(value) || value < 0 || value > 1) {
@@ -7146,6 +7287,12 @@ function policyFromOptions(options) {
7146
7287
  parseUnit
7147
7288
  );
7148
7289
  }
7290
+ if (options.maxCostUsd !== void 0) {
7291
+ policy.maximumCostUsd = parseNonNegativeDecimal2(
7292
+ options.maxCostUsd,
7293
+ "--max-cost-usd"
7294
+ );
7295
+ }
7149
7296
  return policy;
7150
7297
  }
7151
7298
  function policyNeedsIterations(policy) {
@@ -7153,7 +7300,9 @@ function policyNeedsIterations(policy) {
7153
7300
  policy.noGatingScoreErrors || policy.minimumScorerPassRate || policy.minimumMeanScore || policy.maximumTotalTokens !== void 0 || // p95 comes from iteration durations, exactly like tokens come from
7154
7301
  // iteration counts. Omitting it here would leave the latency gate
7155
7302
  // permanently non-gateable — the fetch that could decide it never runs.
7156
- policy.maximumP95LatencyMs !== void 0
7303
+ policy.maximumP95LatencyMs !== void 0 || // Same for cost: it is summed from per-iteration `usage`, so without
7304
+ // the iterations the gate can only ever answer non-gateable.
7305
+ policy.maximumCostUsd !== void 0
7157
7306
  );
7158
7307
  }
7159
7308
  function importEvidenceBlocksGate(run) {
@@ -7262,11 +7411,11 @@ function baselineCompareParams(baseline) {
7262
7411
  return baseline.kind === "run" ? { baseRunId: baseline.runId } : { baseCommitSha: baseline.commitSha };
7263
7412
  }
7264
7413
  function comparePolicyFromGateOptions(options) {
7265
- const hasComparativeFlag = options.minSampleSize !== void 0 || options.minEffectSizePercent !== void 0 || options.gateDeterministicRegressions === true || options.maxP95LatencyIncreaseMs !== void 0;
7414
+ const hasComparativeFlag = options.minSampleSize !== void 0 || options.minEffectSizePercent !== void 0 || options.gateDeterministicRegressions === true || options.maxP95LatencyIncreaseMs !== void 0 || options.maxCostIncreasePercent !== void 0;
7266
7415
  const hasBaseline = Boolean(options.baseline) || Boolean(options.baselineSha);
7267
7416
  if (hasComparativeFlag && !hasBaseline) {
7268
7417
  throw usageError(
7269
- "--min-sample-size, --min-effect-size-percent, --gate-deterministic-regressions, and --max-p95-latency-increase-ms tune the baseline regression gate; pass --baseline or --baseline-sha to enable it."
7418
+ "--min-sample-size, --min-effect-size-percent, --gate-deterministic-regressions, --max-p95-latency-increase-ms and --max-cost-increase-percent tune the baseline regression gate; pass --baseline or --baseline-sha to enable it."
7270
7419
  );
7271
7420
  }
7272
7421
  return comparePolicyFromOptions({
@@ -7274,7 +7423,8 @@ function comparePolicyFromGateOptions(options) {
7274
7423
  minSampleSize: options.minSampleSize,
7275
7424
  minEffectSizePercent: options.minEffectSizePercent,
7276
7425
  gateDeterministicRegressions: options.gateDeterministicRegressions,
7277
- maxP95LatencyIncreaseMs: options.maxP95LatencyIncreaseMs
7426
+ maxP95LatencyIncreaseMs: options.maxP95LatencyIncreaseMs,
7427
+ maxCostIncreasePercent: options.maxCostIncreasePercent
7278
7428
  });
7279
7429
  }
7280
7430
  function baselineNotFoundReason(error) {
@@ -7359,7 +7509,8 @@ function buildBaselineProvenance(requestedBaseline, compare, input, policy) {
7359
7509
  minEffectSize: policy.passRateRegression.minEffectSize ?? DEFAULT_MIN_EFFECT_SIZE
7360
7510
  } : null,
7361
7511
  noDeterministicRegressions: policy.noDeterministicRegressions === true,
7362
- maximumP95LatencyIncreaseMs: policy.maximumP95LatencyIncreaseMs ?? null
7512
+ maximumP95LatencyIncreaseMs: policy.maximumP95LatencyIncreaseMs ?? null,
7513
+ maximumCostIncreasePercent: policy.maximumCostIncreasePercent ?? null
7363
7514
  },
7364
7515
  compatibility: {
7365
7516
  caseSetChanged: input.caseSetChanged,
@@ -7677,17 +7828,63 @@ function encodeInlineImage(data, protocol) {
7677
7828
  }
7678
7829
 
7679
7830
  // src/commands/eval.ts
7831
+ function clientSelectorOf(options) {
7832
+ if (options.client !== void 0 && options.host !== void 0) {
7833
+ throw usageError(
7834
+ "Use either --client or its deprecated --host alias, not both."
7835
+ );
7836
+ }
7837
+ return options.client ?? options.host;
7838
+ }
7839
+ function annotateCatalogHostConfusion(error, selectors) {
7840
+ const isNotFound = (isPlatformApiError(error) || error instanceof CliError) && error.code === "NOT_FOUND";
7841
+ if (!isNotFound) return error;
7842
+ const catalogIds = (selectors ?? []).filter(
7843
+ (selector) => HOST_TEMPLATE_IDS.includes(selector.trim()) && // The CLIENT lookup is the only one this advice is about. A run resolves
7844
+ // the project, the suite and the cases first, and any of those can miss
7845
+ // with its own NOT_FOUND — telling someone their mistyped SUITE name is
7846
+ // a host-compat catalog id would be a confident non-sequitur. The SDK's
7847
+ // resolver names what it was looking for, so match on that plus the
7848
+ // selector rather than on the code alone.
7849
+ error.message.includes(`Suite host "${selector.trim()}"`)
7850
+ );
7851
+ if (catalogIds.length === 0) return error;
7852
+ const named = catalogIds.map((id) => `"${id}"`).join(", ");
7853
+ const message = `${error.message} ${named} names a host-compat catalog id \u2014 what \`mcpjam tools --host\` takes to emulate an AI host \u2014 not a client saved in this project. Under \`cloud eval\`, \`--client\` (and its deprecated \`--host\` alias) selects a saved client; list them with \`mcpjam cloud clients list\`.`;
7854
+ if (error instanceof CliError) {
7855
+ return new CliError(error.code, message, error.exitCode, error.details);
7856
+ }
7857
+ return new PlatformApiError(message, error.code, {
7858
+ status: error.status,
7859
+ ...error.details !== void 0 ? { details: error.details } : {},
7860
+ ...error.endpoint !== void 0 ? { endpoint: error.endpoint } : {}
7861
+ });
7862
+ }
7863
+ async function withCatalogHostHint(selectors, body) {
7864
+ try {
7865
+ return await body();
7866
+ } catch (error) {
7867
+ throw annotateCatalogHostConfusion(error, selectors);
7868
+ }
7869
+ }
7680
7870
  function selectorField(singular, plural, values) {
7681
7871
  if (!values?.length) return {};
7682
7872
  return values.length === 1 ? { [singular]: values[0] } : { [plural]: values };
7683
7873
  }
7684
7874
  function composeField(options) {
7875
+ if (options.composeClient !== void 0 && options.composeHost !== void 0) {
7876
+ throw usageError(
7877
+ "Use either --compose-client or its deprecated --compose-host alias, not both."
7878
+ );
7879
+ }
7880
+ const composeClient = options.composeClient ?? options.composeHost;
7881
+ const clientFlag = options.composeHost !== void 0 ? "--compose-host" : "--compose-client";
7685
7882
  const models = Array.isArray(options.composeModel) ? options.composeModel : options.composeModel ? [options.composeModel] : void 0;
7686
7883
  const refinements = options.composeComputer !== void 0 || models !== void 0 || (options.composeServer?.length ?? 0) > 0 || options.composeServerGroup !== void 0 || options.composeHostServers === true || (options.composeSkill?.length ?? 0) > 0 || (options.composeSecret?.length ?? 0) > 0 || options.withClientDefault === true || options.saveTargets === true;
7687
- if (!options.composeHost) {
7884
+ if (!composeClient) {
7688
7885
  if (refinements) {
7689
7886
  throw usageError(
7690
- "--compose-* flags need --compose-host: the host is what the composed stack runs as, and the others only refine it."
7887
+ "--compose-* flags need --compose-client: the client is what the composed stack runs as, and the others only refine it."
7691
7888
  );
7692
7889
  }
7693
7890
  return {};
@@ -7700,17 +7897,17 @@ function composeField(options) {
7700
7897
  const pinsServers = options.composeServerGroup !== void 0 || (options.composeServer?.length ?? 0) > 0;
7701
7898
  if (options.composeHostServers === true && pinsServers) {
7702
7899
  throw usageError(
7703
- "--compose-host-servers runs against the host's current list, so it cannot be combined with --compose-server / --compose-server-group, which pin one."
7900
+ "--compose-host-servers runs against the client's current list, so it cannot be combined with --compose-server / --compose-server-group, which pin one."
7704
7901
  );
7705
7902
  }
7706
7903
  if (!pinsServers && options.composeHostServers !== true) {
7707
7904
  throw usageError(
7708
- "--compose-host needs to know which servers to test: add --compose-server <name>. To deliberately use whatever servers the host points at right now \u2014 which changes when the host is edited \u2014 pass --compose-host-servers."
7905
+ `${clientFlag} needs to know which servers to test: add --compose-server <name>. To deliberately use whatever servers the client points at right now \u2014 which changes when the client is edited \u2014 pass --compose-host-servers.`
7709
7906
  );
7710
7907
  }
7711
7908
  return {
7712
7909
  compose: {
7713
- host: options.composeHost,
7910
+ host: composeClient,
7714
7911
  ...options.composeServerGroup !== void 0 ? { serverGroup: options.composeServerGroup } : {},
7715
7912
  ...options.composeHostServers === true ? { hostServers: true } : {},
7716
7913
  ...selectorField("server", "servers", options.composeServer),
@@ -7815,7 +8012,9 @@ function writeRunDisclosure(format, disclosure, stream = process.stdout) {
7815
8012
  lines.push(` Model: ${model.modelId} \u2014 ${destination}`);
7816
8013
  }
7817
8014
  } else if (execution.modelsUnresolved) {
7818
- lines.push(` Models: not derivable \u2014 ${execution.modelsUnresolved.reason}`);
8015
+ lines.push(
8016
+ ` Models: not derivable \u2014 ${execution.modelsUnresolved.reason}`
8017
+ );
7819
8018
  }
7820
8019
  if (execution.sandbox.engaged) {
7821
8020
  lines.push(` Sandbox: engaged (${execution.sandbox.vendor ?? "?"})`);
@@ -7842,11 +8041,15 @@ function writeRunDisclosure(format, disclosure, stream = process.stdout) {
7842
8041
  for (const touchpoint of firingAnalysis) {
7843
8042
  const firesLabel = touchpoint.fires === "auto-on-completion" ? "fires automatically on completion" : "fires only if explicitly requested";
7844
8043
  lines.push(
7845
- ` Analysis: ${touchpoint.label} ${firesLabel}, may send evidence to ${touchpoint.destinations.join(", ")}`
8044
+ ` Analysis: ${touchpoint.label} ${firesLabel}, may send evidence to ${touchpoint.destinations.join(
8045
+ ", "
8046
+ )}`
7846
8047
  );
7847
8048
  }
7848
8049
  } else {
7849
- lines.push(" Analysis: no analyzer/judge touchpoint can fire for this run");
8050
+ lines.push(
8051
+ " Analysis: no analyzer/judge touchpoint can fire for this run"
8052
+ );
7850
8053
  }
7851
8054
  lines.push(
7852
8055
  disclosure.retention.effectiveToday === "kept-indefinitely" ? " Retention: kept indefinitely" : ` Retention: swept after ${disclosure.retention.policyDays ?? "?"} day(s)`
@@ -7963,13 +8166,17 @@ function loadSuiteDefinition(options) {
7963
8166
  "That looks like a versioned suite file. Use `eval run --file` to upload and run it."
7964
8167
  );
7965
8168
  }
8169
+ const clientAttachments = clientSelectorOf(options);
7966
8170
  const merged = {
7967
8171
  ...base,
7968
8172
  ...options.project !== void 0 ? { project: options.project } : {},
7969
8173
  ...options.name !== void 0 ? { name: options.name } : {},
7970
8174
  ...options.model !== void 0 ? { model: options.model } : {},
7971
8175
  ...options.provider !== void 0 ? { provider: options.provider } : {},
7972
- ...options.server !== void 0 ? { servers: options.server } : {}
8176
+ ...options.server !== void 0 ? { servers: options.server } : {},
8177
+ // `create_eval_suite` still names the field `hosts`; the FLAG is the
8178
+ // product noun either way.
8179
+ ...clientAttachments !== void 0 ? { hosts: clientAttachments } : {}
7973
8180
  };
7974
8181
  const parsed = createEvalSuiteOperation.inputSchema.safeParse(merged);
7975
8182
  if (!parsed.success) {
@@ -8058,8 +8265,11 @@ function buildSuiteUpdateInput(options) {
8058
8265
  computerEnvironment: options.computerImage === "off" ? null : options.computerImage
8059
8266
  };
8060
8267
  }
8061
- if (options.host !== void 0)
8062
- input.hosts = options.host.map((host) => ({ host }));
8268
+ const clientAttachments = clientSelectorOf(options);
8269
+ if (clientAttachments !== void 0) {
8270
+ delete input.hosts;
8271
+ input.clients = clientAttachments.map((client) => ({ client }));
8272
+ }
8063
8273
  const exec = { ...input.executionConfig ?? {} };
8064
8274
  if (options.model !== void 0) exec.model = options.model;
8065
8275
  if (options.systemPrompt !== void 0)
@@ -8168,14 +8378,40 @@ function resolveScreenshotPath(out, shot, index, total) {
8168
8378
  }
8169
8379
  return out;
8170
8380
  }
8381
+ function resolveIterationVideoPath(out, iterationId, meta) {
8382
+ const safeId = iterationId.replace(/[^a-zA-Z0-9_-]+/g, "-") || "iteration";
8383
+ return join(out, `${safeId}.${iterationVideoExtension(meta)}`);
8384
+ }
8385
+ function requireVideoOutDirectory(out) {
8386
+ if (existsSync(out) && !statSync(out).isDirectory()) {
8387
+ throw usageError(
8388
+ `--out must be a directory when --video is set (${out} is a file), so the recording can be saved beside the screenshots.`
8389
+ );
8390
+ }
8391
+ mkdirSync(out, { recursive: true });
8392
+ }
8171
8393
  function collectRepeatable(value, previous) {
8172
8394
  return [...previous, value];
8173
8395
  }
8174
8396
  var DEFAULT_RUN_WAIT_TIMEOUT_MS = 6e5;
8175
8397
  var RUN_POLL_INTERVAL_MS = 3e3;
8176
- async function waitForEvalRun(client, signal, projectId, runId, deadline) {
8398
+ var GRADING_WAIT_EXTENSION_MS = 31 * 6e4;
8399
+ function isSuiteGateRouteUnsupported(error) {
8400
+ if (!isPlatformApiError(error)) return false;
8401
+ return error.code === "FEATURE_NOT_SUPPORTED" || error.code === "NOT_IMPLEMENTED" || error.status === 501 || error.status === 405 || error.status === 404 && error.codeSource === "status";
8402
+ }
8403
+ function isSuiteGateReportAbsent(error) {
8404
+ if (!isPlatformApiError(error)) return false;
8405
+ return error.status === 404;
8406
+ }
8407
+ async function waitForEvalRun(client, signal, projectId, runId, deadline, gradingExtensionMs = 0) {
8408
+ let extended = false;
8177
8409
  let run = await client.getEvalRun({ projectId, runId }, { signal });
8178
8410
  while (!TERMINAL_RUN_STATUSES.has(run.status)) {
8411
+ if (run.status === "grading" && !extended && gradingExtensionMs > 0) {
8412
+ extended = true;
8413
+ deadline = Math.max(deadline, Date.now() + gradingExtensionMs);
8414
+ }
8179
8415
  if (Date.now() >= deadline) {
8180
8416
  throw operationalError(
8181
8417
  `Eval run "${runId}" is still ${run.status} after waiting for completion.`
@@ -8221,7 +8457,12 @@ function gateReportCase(report, baselineProvenance) {
8221
8457
  // way), but reporting them as `breaking` — the same class a genuine
8222
8458
  // failure gets — would claim a defect the run never observed. Mirrors
8223
8459
  // `gateCase` in sdk/src/run-compare.ts.
8224
- classification: report.outcome === "failed" ? "breaking" : waived ? "informational" : passed ? "non_breaking" : "informational",
8460
+ classification: report.outcome === "failed" ? "breaking" : (
8461
+ // A waived gate is `informational`, NOT `non_breaking`. It really did
8462
+ // fail; `non_breaking` would claim the run observed no breaking change,
8463
+ // which is the opposite of what happened.
8464
+ waived ? "informational" : passed ? "non_breaking" : "informational"
8465
+ ),
8225
8466
  // The failing verdicts are carried on a WAIVED case too. The waiver
8226
8467
  // explains why the build was not blocked; it is not a reason to stop
8227
8468
  // saying what failed.
@@ -8268,13 +8509,21 @@ async function runEvalGate(options, command) {
8268
8509
  });
8269
8510
  const comparePolicy = comparePolicyFromGateOptions(options);
8270
8511
  const waitTimeoutMs = options.waitTimeout !== void 0 ? parsePositiveInteger(options.waitTimeout, "--wait-timeout") : DEFAULT_GATE_WAIT_TIMEOUT_MS;
8512
+ const gradingExtensionMs = options.waitTimeout !== void 0 ? 0 : GRADING_WAIT_EXTENSION_MS;
8271
8513
  const resolved = resolveCloudProjectArgs(options);
8272
8514
  let decisionSummary;
8515
+ let resolvedProjectId;
8273
8516
  let outcome;
8274
8517
  try {
8275
8518
  outcome = await runPlatformOperation(
8276
8519
  platformOptionsOf(command),
8277
- Math.max(globalOptions.timeout, options.wait ? waitTimeoutMs : 0),
8520
+ // The extension rides in the OUTER budget too: that budget aborts the
8521
+ // whole command, so an inner deadline pushed past it would never be
8522
+ // reached.
8523
+ Math.max(
8524
+ globalOptions.timeout,
8525
+ options.wait ? waitTimeoutMs + gradingExtensionMs : 0
8526
+ ),
8278
8527
  async ({ client, signal }) => {
8279
8528
  const projects = await client.listProjects({}, { signal });
8280
8529
  const resolution = resolveProject(projects.items, resolved.project);
@@ -8284,12 +8533,18 @@ async function runEvalGate(options, command) {
8284
8533
  );
8285
8534
  }
8286
8535
  const project = resolution.project;
8287
- const deadline = Date.now() + waitTimeoutMs;
8536
+ resolvedProjectId = project.id;
8537
+ let deadline = Date.now() + waitTimeoutMs;
8538
+ let gradingExtended = false;
8288
8539
  let run = await client.getEvalRun(
8289
8540
  { projectId: project.id, runId },
8290
8541
  { signal }
8291
8542
  );
8292
8543
  while (!TERMINAL_RUN_STATUSES.has(run.status)) {
8544
+ if (run.status === "grading" && !gradingExtended && gradingExtensionMs > 0) {
8545
+ gradingExtended = true;
8546
+ deadline = Math.max(deadline, Date.now() + gradingExtensionMs);
8547
+ }
8293
8548
  if (!options.wait) {
8294
8549
  decisionSummary = await readEvalRunDecisionSummary(
8295
8550
  client,
@@ -8502,7 +8757,76 @@ async function runEvalGate(options, command) {
8502
8757
  outcome.report,
8503
8758
  activeWaiverForRun(outcome.run)
8504
8759
  );
8505
- const exitCode = evalGateExitCode(report);
8760
+ let suiteGate;
8761
+ let suiteGateSkip;
8762
+ let composedOutcome = report.outcome;
8763
+ if (options.suitePolicy !== false && resolvedProjectId) {
8764
+ const fetched = await runPlatformOperation(
8765
+ platformOptionsOf(command),
8766
+ globalOptions.timeout,
8767
+ async ({ client, signal }) => {
8768
+ try {
8769
+ return {
8770
+ kind: "report",
8771
+ report: await client.getEvalRunGate(
8772
+ { projectId: resolvedProjectId, runId },
8773
+ { signal }
8774
+ )
8775
+ };
8776
+ } catch (error) {
8777
+ if (isSuiteGateRouteUnsupported(error)) {
8778
+ return {
8779
+ kind: "skip",
8780
+ message: "This MCPJam deployment does not serve stored suite quality-gate evaluation."
8781
+ };
8782
+ }
8783
+ if (isSuiteGateReportAbsent(error)) {
8784
+ return {
8785
+ kind: "skip",
8786
+ message: "No stored suite quality-gate report for this run. The gate section was not evaluated."
8787
+ };
8788
+ }
8789
+ return {
8790
+ kind: "error",
8791
+ message: error instanceof Error ? error.message : String(error)
8792
+ };
8793
+ }
8794
+ }
8795
+ );
8796
+ if (fetched.kind === "report") {
8797
+ suiteGate = fetched.report;
8798
+ composedOutcome = composeSuiteGateWithBaseReport({
8799
+ base: { outcome: report.outcome },
8800
+ suite: fetched.report
8801
+ }).outcome;
8802
+ } else if (fetched.kind === "skip") {
8803
+ suiteGateSkip = fetched.message;
8804
+ } else {
8805
+ suiteGateSkip = fetched.message;
8806
+ if (report.outcome === "passed" || report.outcome === "waived") {
8807
+ composedOutcome = "incomplete";
8808
+ }
8809
+ }
8810
+ }
8811
+ const composedReport = {
8812
+ ...report,
8813
+ outcome: composedOutcome === "unavailable" ? "incomplete" : composedOutcome,
8814
+ // The suite gate's own conditions ride into the report's verdict list, so
8815
+ // every renderer — human, JUnit, HTML — names the condition that turned
8816
+ // CI red. Without them a suite-gate failure prints "Gate: FAILED" over
8817
+ // nothing but PASS rows, and the JUnit failure message is empty.
8818
+ verdicts: suiteGate ? [
8819
+ ...report.verdicts,
8820
+ ...suiteGate.conditions.filter((condition) => condition.status !== "passed").map((condition) => ({
8821
+ gate: `suiteGate:${condition.condition}`,
8822
+ status: condition.status === "failed" ? "failed" : "non_gateable",
8823
+ message: condition.message,
8824
+ ...typeof condition.observed === "number" ? { observed: condition.observed } : {},
8825
+ ...typeof condition.threshold === "number" ? { threshold: condition.threshold } : {}
8826
+ }))
8827
+ ] : report.verdicts
8828
+ };
8829
+ const exitCode = evalGateExitCode(composedReport);
8506
8830
  const structured = needsReport ? buildEvalRunReport(
8507
8831
  outcome.run ? [
8508
8832
  {
@@ -8513,8 +8837,8 @@ async function runEvalGate(options, command) {
8513
8837
  }
8514
8838
  ] : [],
8515
8839
  {
8516
- cases: [gateReportCase(report, outcome.baselineProvenance)],
8517
- verdict: gateOutcomeVerdict(report.outcome),
8840
+ cases: [gateReportCase(composedReport, outcome.baselineProvenance)],
8841
+ verdict: gateOutcomeVerdict(composedReport.outcome),
8518
8842
  ...decisionSummary ? { decisionSummary } : {},
8519
8843
  ...outcome.baselineProvenance ? { metadata: { baselineComparison: outcome.baselineProvenance } } : {}
8520
8844
  }
@@ -8531,16 +8855,22 @@ async function runEvalGate(options, command) {
8531
8855
  } else {
8532
8856
  writeResult(
8533
8857
  globalOptions.format === "json" ? {
8534
- gate: report,
8858
+ gate: composedReport,
8535
8859
  exitCode,
8860
+ ...suiteGate ? { suiteGate } : {},
8861
+ ...suiteGateSkip ? { suiteGateSkip } : {},
8536
8862
  ...decisionSummary ? { decisionSummary } : {}
8537
- } : { gate: report, exitCode },
8863
+ } : { gate: composedReport, exitCode },
8538
8864
  globalOptions.format
8539
8865
  );
8540
8866
  }
8541
8867
  if (globalOptions.format === "human" && !reporter) {
8542
- process.stderr.write(`${formatGateReport(report)}
8868
+ process.stderr.write(`${formatGateReport(composedReport)}
8543
8869
  `);
8870
+ if (suiteGateSkip) {
8871
+ process.stderr.write(`${suiteGateSkip}
8872
+ `);
8873
+ }
8544
8874
  writeEvalDecisionSummary(
8545
8875
  globalOptions.format,
8546
8876
  decisionSummary,
@@ -8951,7 +9281,11 @@ var EMPTY_DIFF = {
8951
9281
  };
8952
9282
  async function writeCompareResult(args, structured) {
8953
9283
  if (args.out && structured) {
8954
- await writeReporterArtifact(args.out, args.reporter ?? "json-summary", structured);
9284
+ await writeReporterArtifact(
9285
+ args.out,
9286
+ args.reporter ?? "json-summary",
9287
+ structured
9288
+ );
8955
9289
  }
8956
9290
  if (args.reporter && structured) {
8957
9291
  writeReporterResult(args.reporter, structured);
@@ -9230,16 +9564,16 @@ function registerEvalCommands(program) {
9230
9564
  ).option(
9231
9565
  "--json <json>",
9232
9566
  "Inline suite definition JSON (or @file, or - for stdin)"
9233
- ).option("--name <name>", "Suite name (overrides the file)").option(
9234
- "--model <model>",
9235
- "Suite-level default model (overrides the file)"
9236
- ).option(
9567
+ ).option("--name <name>", "Suite name (overrides the file)").option("--model <model>", "Suite-level default model (overrides the file)").option(
9237
9568
  "--provider <provider>",
9238
9569
  "Suite-level default provider (overrides the file; needed for bare/custom model ids)"
9239
9570
  ).option(
9240
9571
  "--server <id-or-name...>",
9241
9572
  "Project HTTP server names or IDs (overrides the file)"
9242
- ).action(async (options, command) => {
9573
+ ).option(
9574
+ "--client <id-or-name...>",
9575
+ "Clients to attach the suite to, by name or ID (overrides the file). Without one the suite lists no client and `eval run --client` has nothing to select"
9576
+ ).option("--host <id-or-name...>", "Deprecated alias for --client").action(async (options, command) => {
9243
9577
  const globalOptions = getGlobalOptions(command);
9244
9578
  const input = loadSuiteDefinition(options);
9245
9579
  const resolved = resolveCloudProjectArgs(options, {
@@ -9259,15 +9593,17 @@ function registerEvalCommands(program) {
9259
9593
  evals.command("list").description("List the eval suites saved in a project").option(
9260
9594
  "--project <id-or-name>",
9261
9595
  "Project name or ID (defaults to the most recently updated project)"
9262
- ).action(async (options, command) => {
9263
- const globalOptions = getGlobalOptions(command);
9264
- const result = await runCloudOp(
9265
- command,
9266
- options,
9267
- ({ client, signal }, project) => listEvalSuitesOperation.execute(project, { client, signal })
9268
- );
9269
- writeResult(result, globalOptions.format);
9270
- });
9596
+ ).action(
9597
+ async (options, command) => {
9598
+ const globalOptions = getGlobalOptions(command);
9599
+ const result = await runCloudOp(
9600
+ command,
9601
+ options,
9602
+ ({ client, signal }, project) => listEvalSuitesOperation.execute(project, { client, signal })
9603
+ );
9604
+ writeResult(result, globalOptions.format);
9605
+ }
9606
+ );
9271
9607
  evals.command("runs").description("List a suite's run history, newest first").requiredOption("--suite <id-or-name>", "Eval suite name or ID").option(
9272
9608
  "--project <id-or-name>",
9273
9609
  "Project name or ID (defaults to the most recently updated project)"
@@ -9285,6 +9621,29 @@ function registerEvalCommands(program) {
9285
9621
  await executeOp(listEvalSuiteRunsOperation, input, options, command);
9286
9622
  }
9287
9623
  );
9624
+ evals.command("revisions").description("List a suite's settings history, newest first").requiredOption("--suite <id-or-name>", "Eval suite name or ID").option(
9625
+ "--project <id-or-name>",
9626
+ "Project name or ID (defaults to the most recently updated project)"
9627
+ ).option(
9628
+ "--limit <n>",
9629
+ "Maximum number of revisions to return (1-100)",
9630
+ (value) => Number.parseInt(value, 10)
9631
+ ).option("--cursor <cursor>", "Pagination cursor from a previous page").action(
9632
+ async (options, command) => {
9633
+ const input = validateOpInput(listEvalSuiteRevisionsOperation, {
9634
+ suite: options.suite,
9635
+ ...options.project === void 0 ? {} : { project: options.project },
9636
+ ...options.limit === void 0 ? {} : { limit: options.limit },
9637
+ ...options.cursor === void 0 ? {} : { cursor: options.cursor }
9638
+ });
9639
+ await executeOp(
9640
+ listEvalSuiteRevisionsOperation,
9641
+ input,
9642
+ options,
9643
+ command
9644
+ );
9645
+ }
9646
+ );
9288
9647
  evals.command("run").description(
9289
9648
  "Start an eval run of an existing suite, or upload a versioned suite file and run it"
9290
9649
  ).option("--suite <id-or-name>", "Eval suite name or ID").option(
@@ -9299,9 +9658,12 @@ function registerEvalCommands(program) {
9299
9658
  ).option(
9300
9659
  "--environment <id-or-name...>",
9301
9660
  "Attached project environment(s) to run. Several values start one PAID RUN each."
9661
+ ).option(
9662
+ "--client <id-or-name...>",
9663
+ "Attached client(s) to run, so the run is stamped with that client's config. Several values start one PAID RUN each."
9302
9664
  ).option(
9303
9665
  "--host <id-or-name...>",
9304
- "Attached host(s) to run, so the run is stamped with that host's config. Several values start one PAID RUN each."
9666
+ "Deprecated alias for --client. NOT the host-compat catalog id `mcpjam tools --host` takes."
9305
9667
  ).option(
9306
9668
  "--all-targets",
9307
9669
  "Run EVERY attached environment (or, if none, every attached host) \u2014 one PAID RUN per target"
@@ -9334,16 +9696,19 @@ function registerEvalCommands(program) {
9334
9696
  "Retry-safety key: repeating the call returns the run it already started"
9335
9697
  ).option("--wait", "Wait for every started run to reach a terminal status").option(
9336
9698
  "--wait-timeout <ms>",
9337
- "Maximum time to wait for completion (default: 600000)"
9699
+ "Maximum time to wait for completion (default 600000; a run held for its judge gets up to 31 more minutes unless this flag is set)"
9338
9700
  ).option(
9339
9701
  "--reporter <json-summary|junit-xml|html>",
9340
9702
  "Render the completed run report to stdout"
9341
9703
  ).option(
9342
9704
  "--out <path>",
9343
9705
  "Atomically write the completed report selected by --reporter (default: json-summary)"
9706
+ ).option(
9707
+ "--compose-client <id-or-name>",
9708
+ "Compose a stack to run instead of naming a saved environment: the client it runs as. Default is EPHEMERAL (does not attach to the suite)."
9344
9709
  ).option(
9345
9710
  "--compose-host <id-or-name>",
9346
- "Compose a stack to run instead of naming a saved environment: the host it runs as. Default is EPHEMERAL (does not attach to the suite)."
9711
+ "Deprecated alias for --compose-client"
9347
9712
  ).option(
9348
9713
  "--compose-computer <id-or-name>",
9349
9714
  "Sandbox image to pin on the composed stack"
@@ -9390,6 +9755,7 @@ function registerEvalCommands(program) {
9390
9755
  "Use either --repetitions or its deprecated --iterations alias, not both."
9391
9756
  );
9392
9757
  }
9758
+ const clientSelectors = clientSelectorOf(options);
9393
9759
  if ((options.reporter !== void 0 || options.out !== void 0) && !options.wait) {
9394
9760
  throw usageError("--reporter and --out require --wait.");
9395
9761
  }
@@ -9400,6 +9766,7 @@ function registerEvalCommands(program) {
9400
9766
  const globalOptions = getGlobalOptions(command);
9401
9767
  const reporter = parseReporterFormat(options.reporter);
9402
9768
  const waitTimeoutMs = options.waitTimeout !== void 0 ? parsePositiveInteger(options.waitTimeout, "--wait-timeout") : DEFAULT_RUN_WAIT_TIMEOUT_MS;
9769
+ const gradingExtensionMs = options.waitTimeout !== void 0 ? 0 : GRADING_WAIT_EXTENSION_MS;
9403
9770
  let webOrigin = DEFAULT_PLATFORM_ORIGIN;
9404
9771
  const resolved = resolveCloudProjectArgs(options);
9405
9772
  if (options.wait) {
@@ -9449,9 +9816,11 @@ function registerEvalCommands(program) {
9449
9816
  knobs: {
9450
9817
  ...options.server ? { server: options.server } : {},
9451
9818
  ...options.environment ? { environment: options.environment } : {},
9452
- ...options.host ? { host: options.host } : {},
9819
+ ...clientSelectors ? { host: clientSelectors } : {},
9453
9820
  ...options.allTargets ? { allTargets: true } : {},
9454
- ...options.repetitions !== void 0 || options.iterations !== void 0 ? { repetitions: options.repetitions ?? options.iterations } : {},
9821
+ ...options.repetitions !== void 0 || options.iterations !== void 0 ? {
9822
+ repetitions: options.repetitions ?? options.iterations
9823
+ } : {},
9455
9824
  ...options.case?.length ? { case: options.case } : {},
9456
9825
  ...options.excludeSkills ? { excludeSkills: true } : {},
9457
9826
  ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
@@ -9469,33 +9838,44 @@ function registerEvalCommands(program) {
9469
9838
  }
9470
9839
  );
9471
9840
  }
9472
- return runEvalSuiteOperation.execute(
9473
- {
9474
- project: resolved.project ?? options.project,
9475
- suite: options.suite,
9476
- ...options.server ? { servers: options.server } : {},
9477
- // ONE value maps to the singular field, several to the plural:
9478
- // the op rejects sending both, and the singular carries the
9479
- // long-standing description a caller may already rely on.
9480
- ...selectorField("environment", "environments", options.environment),
9481
- ...selectorField("host", "hosts", options.host),
9482
- ...options.allTargets ? { allAttached: true } : {},
9483
- ...options.repetitions !== void 0 ? { repetitions: options.repetitions } : options.iterations !== void 0 ? { iterations: options.iterations } : {},
9484
- ...options.case?.length ? { cases: options.case } : {},
9485
- ...options.excludeSkills ? { excludeSkills: true } : {},
9486
- ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
9487
- ...options.notes !== void 0 ? { notes: options.notes } : {},
9488
- ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
9489
- ...options.matchOptions ? { matchOptions: parseMatchOptionsOption(options.matchOptions) } : {},
9490
- ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
9491
- ...composeField(options)
9492
- },
9493
- {
9494
- client: context.client,
9495
- signal: context.signal,
9496
- onDisclosure,
9497
- onDisclosureUnavailable
9498
- }
9841
+ return withCatalogHostHint(
9842
+ clientSelectors,
9843
+ () => runEvalSuiteOperation.execute(
9844
+ {
9845
+ project: resolved.project ?? options.project,
9846
+ suite: options.suite,
9847
+ ...options.server ? { servers: options.server } : {},
9848
+ // ONE value maps to the singular field, several to the plural:
9849
+ // the op rejects sending both, and the singular carries the
9850
+ // long-standing description a caller may already rely on.
9851
+ ...selectorField(
9852
+ "environment",
9853
+ "environments",
9854
+ options.environment
9855
+ ),
9856
+ ...selectorField("client", "clients", clientSelectors),
9857
+ ...options.allTargets ? { allAttached: true } : {},
9858
+ ...options.repetitions !== void 0 ? { repetitions: options.repetitions } : options.iterations !== void 0 ? { iterations: options.iterations } : {},
9859
+ ...options.case?.length ? { cases: options.case } : {},
9860
+ ...options.excludeSkills ? { excludeSkills: true } : {},
9861
+ ...options.refreshSnapshot ? { refreshSnapshot: true } : {},
9862
+ ...options.notes !== void 0 ? { notes: options.notes } : {},
9863
+ ...options.minPassRate !== void 0 ? { minPassRate: options.minPassRate } : {},
9864
+ ...options.matchOptions ? {
9865
+ matchOptions: parseMatchOptionsOption(
9866
+ options.matchOptions
9867
+ )
9868
+ } : {},
9869
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
9870
+ ...composeField(options)
9871
+ },
9872
+ {
9873
+ client: context.client,
9874
+ signal: context.signal,
9875
+ onDisclosure,
9876
+ onDisclosureUnavailable
9877
+ }
9878
+ )
9499
9879
  );
9500
9880
  },
9501
9881
  { projectScope: resolved.projectScope }
@@ -9533,7 +9913,11 @@ function registerEvalCommands(program) {
9533
9913
  }
9534
9914
  const completion = await runPlatformOperation(
9535
9915
  platformOptionsOf(command),
9536
- Math.max(globalOptions.timeout, waitTimeoutMs),
9916
+ // The extension has to be in the OUTER budget too. That budget aborts
9917
+ // the whole command, so an inner deadline pushed past it would be
9918
+ // killed before it could be reached — the extension would exist and
9919
+ // never apply.
9920
+ Math.max(globalOptions.timeout, waitTimeoutMs + gradingExtensionMs),
9537
9921
  async ({ client, signal }) => {
9538
9922
  const deadline = Date.now() + waitTimeoutMs;
9539
9923
  const waited = await Promise.all(
@@ -9546,7 +9930,8 @@ function registerEvalCommands(program) {
9546
9930
  signal,
9547
9931
  result.project.id,
9548
9932
  target.runId,
9549
- deadline
9933
+ deadline,
9934
+ gradingExtensionMs
9550
9935
  )
9551
9936
  };
9552
9937
  } catch (error) {
@@ -9559,7 +9944,9 @@ function registerEvalCommands(program) {
9559
9944
  }
9560
9945
  })
9561
9946
  );
9562
- const runs = waited.flatMap((entry) => entry.ok ? [entry.run] : []);
9947
+ const runs = waited.flatMap(
9948
+ (entry) => entry.ok ? [entry.run] : []
9949
+ );
9563
9950
  const waitErrors = waited.flatMap(
9564
9951
  (entry) => !entry.ok ? [
9565
9952
  {
@@ -9663,7 +10050,9 @@ function registerEvalCommands(program) {
9663
10050
  status: run.status,
9664
10051
  result: run.result,
9665
10052
  reportingFailed: reportingFailedRunIds.has(run.id),
9666
- reportingFailedErrorCode: completion.iterationErrorCodes.get(run.id)
10053
+ reportingFailedErrorCode: completion.iterationErrorCodes.get(
10054
+ run.id
10055
+ )
9667
10056
  })
9668
10057
  );
9669
10058
  const code = evalRunWaitExitCode({
@@ -9848,6 +10237,134 @@ function registerEvalCommands(program) {
9848
10237
  );
9849
10238
  }
9850
10239
  );
10240
+ addProjectOption(
10241
+ evals.command("route-facts").description(
10242
+ "Read the tool routes a run's trials took \u2014 which paths were used, and which expected tools were missing or substituted"
10243
+ ).requiredOption("--run <id>", "Eval run ID (from `eval run`)")
10244
+ ).action(
10245
+ async (options, command) => {
10246
+ const input = validateOpInput(
10247
+ getEvalRunRouteFactsOperation,
10248
+ {
10249
+ runId: options.run,
10250
+ ...options.project === void 0 ? {} : { project: options.project }
10251
+ },
10252
+ { projectOptional: true }
10253
+ );
10254
+ await executeOp(
10255
+ getEvalRunRouteFactsOperation,
10256
+ input,
10257
+ options,
10258
+ command
10259
+ );
10260
+ }
10261
+ );
10262
+ addProjectOption(
10263
+ evals.command("server-facts").description(
10264
+ "Read the server a run was taken against \u2014 tool surface, catalog size, annotation coverage, tool-metadata signals, and what connect and discovery observed"
10265
+ ).requiredOption("--run <id>", "Eval run ID (from `eval run`)")
10266
+ ).action(
10267
+ async (options, command) => {
10268
+ const input = validateOpInput(
10269
+ getEvalRunServerFactsOperation,
10270
+ {
10271
+ runId: options.run,
10272
+ ...options.project === void 0 ? {} : { project: options.project }
10273
+ },
10274
+ { projectOptional: true }
10275
+ );
10276
+ await executeOp(
10277
+ getEvalRunServerFactsOperation,
10278
+ input,
10279
+ options,
10280
+ command
10281
+ );
10282
+ }
10283
+ );
10284
+ const descriptionExperiment = evals.command("description-experiment").description(
10285
+ "Propose, start, or read a two-arm tool-description rewrite experiment"
10286
+ );
10287
+ addProjectOption(
10288
+ descriptionExperiment.command("propose").description(
10289
+ "Draft a rewritten tool description from a finished run's failed trials. Spends a small model budget; poll `description-experiment get` rather than re-proposing."
10290
+ ).requiredOption("--run <id>", "Source eval run ID").requiredOption("--tool <name>", "Catalog tool name to rewrite").option("--case <id...>", "Limit evidence to these case ids")
10291
+ ).action(
10292
+ async (options, command) => {
10293
+ const input = validateOpInput(
10294
+ proposeEvalDescriptionRewriteOperation,
10295
+ {
10296
+ runId: options.run,
10297
+ toolName: options.tool,
10298
+ ...options.case && options.case.length > 0 ? { caseIds: options.case } : {},
10299
+ ...options.project === void 0 ? {} : { project: options.project }
10300
+ },
10301
+ { projectOptional: true }
10302
+ );
10303
+ await executeOp(
10304
+ proposeEvalDescriptionRewriteOperation,
10305
+ input,
10306
+ options,
10307
+ command
10308
+ );
10309
+ }
10310
+ );
10311
+ addProjectOption(
10312
+ descriptionExperiment.command("start").description(
10313
+ "Launch the two-arm experiment (original + rewrite). Spends eval-iteration credits; poll `description-experiment get`."
10314
+ ).requiredOption("--experiment <id>", "Description-experiment ID").option("--case-scope <scope>", "Which cases to replay: all or affected").option("--repetitions <n>", "Repetitions per case per arm (1\u201310)").option("--iterations <n>", "Deprecated alias for --repetitions (1\u201310)").option(
10315
+ "--max-trials <n>",
10316
+ "Refuse if plannedTrials exceeds this (max 400)"
10317
+ )
10318
+ ).action(
10319
+ async (options, command) => {
10320
+ if (options.repetitions !== void 0 && options.iterations !== void 0) {
10321
+ throw usageError(
10322
+ "Use either --repetitions or its deprecated --iterations alias, not both."
10323
+ );
10324
+ }
10325
+ const repetitions = options.repetitions ?? options.iterations;
10326
+ const input = validateOpInput(startEvalDescriptionExperimentOperation, {
10327
+ experiment: options.experiment,
10328
+ ...options.caseScope !== void 0 ? { caseScope: options.caseScope } : {},
10329
+ ...repetitions !== void 0 ? {
10330
+ iterationOverride: parsePositiveInteger(
10331
+ repetitions,
10332
+ options.repetitions !== void 0 ? "--repetitions" : "--iterations"
10333
+ )
10334
+ } : {},
10335
+ ...options.maxTrials !== void 0 ? {
10336
+ maxTrials: parsePositiveInteger(
10337
+ options.maxTrials,
10338
+ "--max-trials"
10339
+ )
10340
+ } : {},
10341
+ ...options.project === void 0 ? {} : { project: options.project }
10342
+ });
10343
+ await executeOp(
10344
+ startEvalDescriptionExperimentOperation,
10345
+ input,
10346
+ options,
10347
+ command
10348
+ );
10349
+ }
10350
+ );
10351
+ addProjectOption(
10352
+ descriptionExperiment.command("get").description(
10353
+ "Read one description-experiment document, including its report when materialised"
10354
+ ).requiredOption("--experiment <id>", "Description-experiment ID")
10355
+ ).action(
10356
+ async (options, command) => {
10357
+ await executeOp(
10358
+ getEvalDescriptionExperimentOperation,
10359
+ {
10360
+ experiment: options.experiment,
10361
+ ...options.project === void 0 ? {} : { project: options.project }
10362
+ },
10363
+ options,
10364
+ command
10365
+ );
10366
+ }
10367
+ );
9851
10368
  addProjectOption(
9852
10369
  evals.command("cancel").description(
9853
10370
  "Cancel an in-flight eval run (no-op if already cancelled; errors if it already finished)"
@@ -9887,47 +10404,63 @@ function registerEvalCommands(program) {
9887
10404
  },
9888
10405
  { projectOptional: true }
9889
10406
  );
9890
- await executeOp(
9891
- requestEvalRunJudgeOperation,
9892
- input,
9893
- options,
9894
- command
9895
- );
10407
+ await executeOp(requestEvalRunJudgeOperation, input, options, command);
9896
10408
  }
9897
10409
  );
9898
10410
  const PROJECT_OPT = "Project name or ID (defaults to most recently updated)";
9899
- const checks = evals.command("checks").description("Run an eval suite on a repository's pull requests");
9900
- checks.command("list").description(
9901
- "List the repositories running an eval suite on their pull requests"
9902
- ).option("--project <id-or-name>", PROJECT_OPT).action(async (options, command) => {
9903
- await executeOp(
9904
- listEvalCheckReposOperation,
9905
- { project: options.project },
9906
- options,
9907
- command
10411
+ function registerGithubSubcommands(group, deprecated) {
10412
+ const suffix = deprecated ? " [deprecated: use `mcpjam cloud eval github`]" : "";
10413
+ group.command("list").description(
10414
+ `List the repositories running an eval suite on their pull requests${suffix}`
10415
+ ).option("--project <id-or-name>", PROJECT_OPT).action(
10416
+ async (options, command) => {
10417
+ await executeOp(
10418
+ listEvalGithubReposOperation,
10419
+ { project: options.project },
10420
+ options,
10421
+ command
10422
+ );
10423
+ }
9908
10424
  );
9909
- });
9910
- checks.command("connect").description(
9911
- "Run this suite on every pull request to a repository (affects everyone who opens one)"
9912
- ).requiredOption("--suite <id-or-name>", "Eval suite name or ID").requiredOption("--repo <owner/repo>", "Repository to connect").requiredOption(
9913
- "--outage-policy <fail-open|fail-closed>",
9914
- "What the check reports when MCPJam cannot conclude"
9915
- ).option("--project <id-or-name>", PROJECT_OPT).action(
9916
- async (options, command) => {
9917
- const policy = OUTAGE_POLICY_BY_FLAG.get(options.outagePolicy);
9918
- if (!policy) {
9919
- throw usageError(
9920
- '--outage-policy must be "fail-open" or "fail-closed". fail-closed blocks merges while MCPJam cannot conclude; fail-open lets an unverified change through.'
10425
+ group.command("connect").description(
10426
+ `Run this suite on every pull request to a repository (affects everyone who opens one)${suffix}`
10427
+ ).requiredOption("--suite <id-or-name>", "Eval suite name or ID").requiredOption("--repo <owner/repo>", "Repository to connect").requiredOption(
10428
+ "--outage-policy <fail-open|fail-closed>",
10429
+ "What the check reports when MCPJam cannot conclude"
10430
+ ).option("--project <id-or-name>", PROJECT_OPT).action(
10431
+ async (options, command) => {
10432
+ const policy = OUTAGE_POLICY_BY_FLAG.get(options.outagePolicy);
10433
+ if (!policy) {
10434
+ throw usageError(
10435
+ '--outage-policy must be "fail-open" or "fail-closed". fail-closed blocks merges while MCPJam cannot conclude; fail-open lets an unverified change through.'
10436
+ );
10437
+ }
10438
+ const input = validateOpInput(connectEvalGithubRepoOperation, {
10439
+ project: options.project,
10440
+ suite: options.suite,
10441
+ repo: options.repo,
10442
+ outagePolicy: policy
10443
+ });
10444
+ await executeOp(
10445
+ connectEvalGithubRepoOperation,
10446
+ input,
10447
+ options,
10448
+ command
9921
10449
  );
9922
10450
  }
9923
- const input = validateOpInput(connectEvalCheckRepoOperation, {
9924
- project: options.project,
9925
- suite: options.suite,
9926
- repo: options.repo,
9927
- outagePolicy: policy
9928
- });
9929
- await executeOp(connectEvalCheckRepoOperation, input, options, command);
9930
- }
10451
+ );
10452
+ }
10453
+ registerGithubSubcommands(
10454
+ evals.command("github").description(
10455
+ "Run an eval suite on a GitHub repository's pull requests (GitHub checks)"
10456
+ ),
10457
+ false
10458
+ );
10459
+ registerGithubSubcommands(
10460
+ evals.command("checks").description(
10461
+ "Deprecated alias for `cloud eval github` \u2014 a repository's GitHub checks, not a case's grading checks"
10462
+ ),
10463
+ true
9931
10464
  );
9932
10465
  addProjectOption(
9933
10466
  evals.command("iterations").description(
@@ -9991,15 +10524,24 @@ function registerEvalCommands(program) {
9991
10524
  ).option(
9992
10525
  "--max-p95-latency-increase-ms <ms>",
9993
10526
  "Fail if p95 end-to-end latency rose by more than this many milliseconds vs the baseline; requires --baseline or --baseline-sha"
10527
+ ).option(
10528
+ "--max-cost-usd <usd>",
10529
+ "Fail if the run's MCPJam-billed cost exceeded this many dollars; non-gateable when the run's cost is unknown or only partly measured"
10530
+ ).option(
10531
+ "--max-cost-increase-percent <percent>",
10532
+ "Fail if cost rose by more than this percentage of the baseline's; requires --baseline or --baseline-sha"
9994
10533
  ).option("--wait", "Poll until the run reaches a terminal status").option(
9995
10534
  "--wait-timeout <ms>",
9996
- "Give up waiting after this many milliseconds (default 600000)"
10535
+ "Give up waiting after this many milliseconds (default 600000; a run held for its judge gets up to 31 more minutes unless this flag is set)"
9997
10536
  ).option(
9998
10537
  "--reporter <json-summary|junit-xml|html>",
9999
10538
  "Write a structured report to stdout instead of the default output"
10000
10539
  ).option(
10001
10540
  "--out <path>",
10002
10541
  "Atomically write the structured report selected by --reporter (default: json-summary)"
10542
+ ).option(
10543
+ "--no-suite-policy",
10544
+ "Skip the stored suite quality-gate; evaluate only the flag/base report"
10003
10545
  ).action(
10004
10546
  async (options, command) => {
10005
10547
  await runEvalGate(options, command);
@@ -10049,6 +10591,9 @@ function registerEvalCommands(program) {
10049
10591
  ).option(
10050
10592
  "--max-p95-latency-increase-ms <ms>",
10051
10593
  "Fail if p95 end-to-end latency rose by more than this many milliseconds"
10594
+ ).option(
10595
+ "--max-cost-increase-percent <percent>",
10596
+ "Fail if cost rose by more than this percentage of the baseline's; non-gateable when either run's cost is unknown or only partly measured"
10052
10597
  ).option(
10053
10598
  "--reporter <json-summary|junit-xml|html>",
10054
10599
  "Write a structured report to stdout instead of the default output"
@@ -10075,10 +10620,7 @@ function registerEvalCommands(program) {
10075
10620
  );
10076
10621
  evals.command("export").description(
10077
10622
  "Write a hosted eval suite to a local suite file, refusing anything it cannot represent losslessly"
10078
- ).requiredOption(
10079
- "--suite <id-or-name>",
10080
- "Eval suite to export (name or ID)"
10081
- ).option(
10623
+ ).requiredOption("--suite <id-or-name>", "Eval suite to export (name or ID)").option(
10082
10624
  "--project <id-or-name>",
10083
10625
  "Project the suite belongs to (defaults to the most recently updated project)"
10084
10626
  ).option(
@@ -10160,7 +10702,10 @@ function registerEvalCommands(program) {
10160
10702
  ).option(
10161
10703
  "--out <path>",
10162
10704
  "Save the PNG(s) to a file or directory instead of rendering inline"
10163
- ).option("--index <n>", "Show only the Nth screenshot (1-based)").action(
10705
+ ).option("--index <n>", "Show only the Nth screenshot (1-based)").option(
10706
+ "--video",
10707
+ "With --out, also download the iteration's replay recording next to the screenshots"
10708
+ ).action(
10164
10709
  async (options, command) => {
10165
10710
  const globalOptions = getGlobalOptions(command);
10166
10711
  const index = options.index !== void 0 ? parsePositiveInteger(options.index, "--index") : void 0;
@@ -10181,6 +10726,14 @@ function registerEvalCommands(program) {
10181
10726
  quiet: globalOptions.quiet
10182
10727
  }
10183
10728
  );
10729
+ if (options.video) {
10730
+ if (options.out === void 0) {
10731
+ throw usageError(
10732
+ "--video needs --out: the recording is a file to save, not something to print. Use `eval video --run \u2026 --iteration \u2026` for the URL."
10733
+ );
10734
+ }
10735
+ requireVideoOutDirectory(options.out);
10736
+ }
10184
10737
  let shots = extractRenderedScreenshots(result);
10185
10738
  if (index !== void 0) {
10186
10739
  if (index > shots.length) {
@@ -10214,11 +10767,39 @@ function registerEvalCommands(program) {
10214
10767
  writeFileSync(path9, bytes);
10215
10768
  saved.push({ ...shot, savedTo: path9 });
10216
10769
  }
10770
+ let video;
10771
+ if (options.video) {
10772
+ const videoUrl = extractIterationVideoUrl(result);
10773
+ if (videoUrl) {
10774
+ const meta = extractIterationVideoMeta(result);
10775
+ const videoPath = resolveIterationVideoPath(
10776
+ options.out,
10777
+ options.iteration,
10778
+ meta
10779
+ );
10780
+ const videoBytes = await fetchArtifactBytes(
10781
+ videoUrl,
10782
+ globalOptions.timeout,
10783
+ "video"
10784
+ );
10785
+ mkdirSync(dirname(videoPath), { recursive: true });
10786
+ writeFileSync(videoPath, videoBytes);
10787
+ video = {
10788
+ videoUrl,
10789
+ savedTo: videoPath,
10790
+ ...meta ? { videoMeta: meta } : {}
10791
+ };
10792
+ }
10793
+ }
10217
10794
  if (isJson) {
10218
- writeResult({ ...base, items: saved });
10795
+ writeResult({
10796
+ ...base,
10797
+ items: saved,
10798
+ ...options.video ? { video: video ?? null } : {}
10799
+ });
10219
10800
  return;
10220
10801
  }
10221
- if (saved.length === 0) {
10802
+ if (saved.length === 0 && !video) {
10222
10803
  process.stdout.write(
10223
10804
  "No rendered widget screenshots for this iteration.\n"
10224
10805
  );
@@ -10230,6 +10811,17 @@ function registerEvalCommands(program) {
10230
10811
  `
10231
10812
  );
10232
10813
  }
10814
+ if (options.video) {
10815
+ if (video) {
10816
+ const summary = describeIterationVideo(video.videoMeta);
10817
+ process.stdout.write(
10818
+ `Saved replay recording \u2192 ${video.savedTo}${summary ? ` (${summary})` : ""}
10819
+ `
10820
+ );
10821
+ } else {
10822
+ process.stdout.write("No replay recording for this iteration.\n");
10823
+ }
10824
+ }
10233
10825
  return;
10234
10826
  }
10235
10827
  if (isJson) {
@@ -10262,14 +10854,14 @@ function registerEvalCommands(program) {
10262
10854
  );
10263
10855
  addProjectOption(
10264
10856
  evals.command("video").description(
10265
- "Get the Playwright replay video (.webm) an eval iteration recorded \u2014 prints the URL, or downloads it with --out"
10857
+ "Get the replay recording an eval iteration made \u2014 prints the URL, or downloads it with --out. A local widget run records a .webm; an unattended run on a hosted browser records an .mp4"
10266
10858
  ).requiredOption("--run <id>", "Eval run ID (from `eval run`)").requiredOption(
10267
10859
  "--iteration <id>",
10268
10860
  "Iteration ID (from `eval iterations`)"
10269
10861
  )
10270
10862
  ).option(
10271
10863
  "--out <path>",
10272
- "Download the .webm to this file instead of printing the URL"
10864
+ "Download the recording to this file instead of printing the URL"
10273
10865
  ).action(
10274
10866
  async (options, command) => {
10275
10867
  const globalOptions = getGlobalOptions(command);
@@ -10291,20 +10883,23 @@ function registerEvalCommands(program) {
10291
10883
  }
10292
10884
  );
10293
10885
  const videoUrl = extractIterationVideoUrl(result);
10886
+ const videoMeta = videoUrl ? extractIterationVideoMeta(result) : void 0;
10294
10887
  const base = {
10295
10888
  project: result.project,
10296
10889
  runId: result.runId,
10297
10890
  iterationId: result.iterationId
10298
10891
  };
10892
+ const metaFields = videoMeta ? { videoMeta } : {};
10299
10893
  const isJson = globalOptions.format === "json";
10300
10894
  if (!videoUrl) {
10301
10895
  if (isJson) {
10302
10896
  writeResult({ ...base, videoUrl: null });
10303
10897
  return;
10304
10898
  }
10305
- process.stdout.write("No replay video for this iteration.\n");
10899
+ process.stdout.write("No replay recording for this iteration.\n");
10306
10900
  return;
10307
10901
  }
10902
+ const summary = describeIterationVideo(videoMeta);
10308
10903
  if (options.out !== void 0) {
10309
10904
  const bytes = await fetchArtifactBytes(
10310
10905
  videoUrl,
@@ -10314,19 +10909,29 @@ function registerEvalCommands(program) {
10314
10909
  mkdirSync(dirname(options.out), { recursive: true });
10315
10910
  writeFileSync(options.out, bytes);
10316
10911
  if (isJson) {
10317
- writeResult({ ...base, videoUrl, savedTo: options.out });
10912
+ writeResult({
10913
+ ...base,
10914
+ videoUrl,
10915
+ ...metaFields,
10916
+ savedTo: options.out
10917
+ });
10318
10918
  return;
10319
10919
  }
10320
- process.stdout.write(`Saved replay video \u2192 ${options.out}
10321
- `);
10920
+ process.stdout.write(
10921
+ `Saved replay recording \u2192 ${options.out}${summary ? ` (${summary})` : ""}
10922
+ `
10923
+ );
10322
10924
  return;
10323
10925
  }
10324
10926
  if (isJson) {
10325
- writeResult({ ...base, videoUrl });
10927
+ writeResult({ ...base, videoUrl, ...metaFields });
10326
10928
  return;
10327
10929
  }
10328
- process.stdout.write(`${videoUrl}
10329
- `);
10930
+ process.stdout.write(
10931
+ `${videoUrl}${summary ? `
10932
+ ${summary}
10933
+ ` : "\n"}`
10934
+ );
10330
10935
  }
10331
10936
  );
10332
10937
  evals.command("get").description("Show an eval suite's full settings").requiredOption("--suite <id-or-name>", "Eval suite name or ID").option("--project <id-or-name>", PROJECT_OPT).action(
@@ -10347,7 +10952,10 @@ function registerEvalCommands(program) {
10347
10952
  ).option(
10348
10953
  "--computer-image <id-or-name|off>",
10349
10954
  "Sandbox image eval runs boot from (see `mcpjam cloud images list`); off uses the default base image"
10350
- ).option("--host <id-or-name...>", "Replace host attachments (by name or ID)").option("--model <id>", "Execution model id").option("--system-prompt <text>", "Execution system prompt").option("--temperature <n>", "Execution temperature").option("--min-accuracy <pct>", "Minimum accuracy, 0\u2013100").option(
10955
+ ).option(
10956
+ "--client <id-or-name...>",
10957
+ "Replace client attachments (by name or ID)"
10958
+ ).option("--host <id-or-name...>", "Deprecated alias for --client").option("--model <id>", "Execution model id").option("--system-prompt <text>", "Execution system prompt").option("--temperature <n>", "Execution temperature").option("--min-accuracy <pct>", "Minimum accuracy, 0\u2013100").option(
10351
10959
  "--min-iterations <1-10|off>",
10352
10960
  "Floor on per-case iterations; off removes the floor"
10353
10961
  ).option("--tool-call-order <any|in-order|exact>", "Tool call order").option("--arguments <ignore|partial|exact>", "Argument matching").option("--extra-tool-calls <unlimited|N>", "Allowed extra tool calls").option(
@@ -10444,7 +11052,11 @@ function registerEvalCommands(program) {
10444
11052
  async (options, command) => {
10445
11053
  await executeOp(
10446
11054
  getEvalCaseOperation,
10447
- { project: options.project, suite: options.suite, case: options.case },
11055
+ {
11056
+ project: options.project,
11057
+ suite: options.suite,
11058
+ case: options.case
11059
+ },
10448
11060
  options,
10449
11061
  command
10450
11062
  );
@@ -10458,9 +11070,12 @@ function registerEvalCommands(program) {
10458
11070
  ).option(
10459
11071
  "--environment <id-or-name>",
10460
11072
  "Project environment to run against (must be attached to the suite)"
11073
+ ).option(
11074
+ "--client <id-or-name>",
11075
+ "Attached client to run against, so the run is stamped with that client's config"
10461
11076
  ).option(
10462
11077
  "--host <id-or-name>",
10463
- "Attached host to run against, so the run is stamped with that host's config"
11078
+ "Deprecated alias for --client. NOT the host-compat catalog id `mcpjam tools --host` takes."
10464
11079
  ).option(
10465
11080
  "--repetitions <n>",
10466
11081
  "Run the case this many times under verdict policy 2 (1-10)",
@@ -10472,9 +11087,12 @@ function registerEvalCommands(program) {
10472
11087
  ).option(
10473
11088
  "--idempotency-key <key>",
10474
11089
  "Retry-safety key: repeating the call returns the run it already started"
11090
+ ).option(
11091
+ "--compose-client <id-or-name>",
11092
+ "Compose a stack to run this case instead of naming a saved environment: the client it runs as. Default is EPHEMERAL."
10475
11093
  ).option(
10476
11094
  "--compose-host <id-or-name>",
10477
- "Compose a stack to run this case instead of naming a saved environment. Default is EPHEMERAL."
11095
+ "Deprecated alias for --compose-client"
10478
11096
  ).option(
10479
11097
  "--compose-computer <id-or-name>",
10480
11098
  "Sandbox image to pin on the composed stack"
@@ -10503,21 +11121,25 @@ function registerEvalCommands(program) {
10503
11121
  "Use either --repetitions or its deprecated --iterations alias, not both."
10504
11122
  );
10505
11123
  }
10506
- await executeOp(
10507
- runEvalCaseOperation,
10508
- {
10509
- project: options.project,
10510
- suite: options.suite,
10511
- case: options.case,
10512
- ...options.server?.length ? { servers: options.server } : {},
10513
- ...options.environment ? { environment: options.environment } : {},
10514
- ...options.host ? { host: options.host } : {},
10515
- ...options.repetitions !== void 0 ? { repetitions: options.repetitions } : options.iterations !== void 0 ? { iterations: options.iterations } : {},
10516
- ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
10517
- ...composeField(options)
10518
- },
10519
- options,
10520
- command
11124
+ const clientSelector = clientSelectorOf(options);
11125
+ await withCatalogHostHint(
11126
+ clientSelector === void 0 ? void 0 : [clientSelector],
11127
+ () => executeOp(
11128
+ runEvalCaseOperation,
11129
+ {
11130
+ project: options.project,
11131
+ suite: options.suite,
11132
+ case: options.case,
11133
+ ...options.server?.length ? { servers: options.server } : {},
11134
+ ...options.environment ? { environment: options.environment } : {},
11135
+ ...clientSelector ? { client: clientSelector } : {},
11136
+ ...options.repetitions !== void 0 ? { repetitions: options.repetitions } : options.iterations !== void 0 ? { iterations: options.iterations } : {},
11137
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
11138
+ ...composeField(options)
11139
+ },
11140
+ options,
11141
+ command
11142
+ )
10521
11143
  );
10522
11144
  }
10523
11145
  );
@@ -10539,7 +11161,11 @@ function registerEvalCommands(program) {
10539
11161
  async (options, command) => {
10540
11162
  await executeOp(
10541
11163
  deleteEvalCaseOperation,
10542
- { project: options.project, suite: options.suite, case: options.case },
11164
+ {
11165
+ project: options.project,
11166
+ suite: options.suite,
11167
+ case: options.case
11168
+ },
10543
11169
  options,
10544
11170
  command
10545
11171
  );
@@ -12940,6 +13566,412 @@ function registerSwarmAuthoringCommands(program, journeys) {
12940
13566
  })
12941
13567
  );
12942
13568
  }
13569
+ function collect(value, previous = []) {
13570
+ return [...previous, value];
13571
+ }
13572
+ var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
13573
+ function splitOnFirst(raw, separator, flag) {
13574
+ const index = raw.indexOf(separator);
13575
+ if (index < 0) {
13576
+ throw usageError(
13577
+ `${flag} expects "Name${separator}value"; the argument had no "${separator}".`
13578
+ );
13579
+ }
13580
+ const name = raw.slice(0, index).trim();
13581
+ if (!name) {
13582
+ throw usageError(`${flag} has an empty name before the "${separator}".`);
13583
+ }
13584
+ return [name, raw.slice(index + separator.length)];
13585
+ }
13586
+ function resolveHeaders(options) {
13587
+ const headers = /* @__PURE__ */ Object.create(null);
13588
+ const seen = /* @__PURE__ */ new Map();
13589
+ const named = (options.header?.length ?? 0) + (options.headerEnv?.length ?? 0) + (options.headerFile?.length ?? 0);
13590
+ if (options.clearHeaders) {
13591
+ if (named > 0) {
13592
+ throw usageError(
13593
+ "--clear-headers removes every header, so it cannot be combined with a header flag. Pass one or the other."
13594
+ );
13595
+ }
13596
+ return {};
13597
+ }
13598
+ const put = (name, value, flag) => {
13599
+ if (!HEADER_NAME_PATTERN.test(name)) {
13600
+ throw usageError(
13601
+ `That ${flag} name is not an HTTP token. Use letters, digits and !#$%&'*+.^_\`|~- only.`
13602
+ );
13603
+ }
13604
+ const key = name.toLowerCase();
13605
+ const previous = seen.get(key);
13606
+ if (previous !== void 0) {
13607
+ throw usageError(
13608
+ `Header "${name}" was given twice (already set by ${previous}). HTTP header names are case-insensitive.`
13609
+ );
13610
+ }
13611
+ if (/[\r\n\0]/.test(value)) {
13612
+ throw usageError(
13613
+ `Header "${name}" contains a newline or a null byte. A header value cannot span lines.`
13614
+ );
13615
+ }
13616
+ if (value === "") {
13617
+ throw usageError(`The value for header "${name}" is empty.`);
13618
+ }
13619
+ seen.set(key, flag);
13620
+ headers[name] = value;
13621
+ };
13622
+ for (const raw of options.header ?? []) {
13623
+ const [name, value] = splitOnFirst(raw, ":", "--header");
13624
+ put(name, value.trim(), "--header");
13625
+ }
13626
+ for (const raw of options.headerEnv ?? []) {
13627
+ const [name, variable] = splitOnFirst(raw, "=", "--header-env");
13628
+ const value = process.env[variable.trim()];
13629
+ if (value === void 0 || value === "") {
13630
+ throw usageError(
13631
+ `Environment variable "${variable.trim()}" is not set (or is empty).`
13632
+ );
13633
+ }
13634
+ put(name, value, "--header-env");
13635
+ }
13636
+ for (const raw of options.headerFile ?? []) {
13637
+ const [name, path9] = splitOnFirst(raw, "=", "--header-file");
13638
+ const target = path9.trim();
13639
+ let contents;
13640
+ try {
13641
+ contents = target === "-" ? readFileSync(0, "utf8") : readFileSync(target, "utf8");
13642
+ } catch (error) {
13643
+ throw usageError(
13644
+ target === "-" ? `Failed to read the value for header "${name}" from stdin.` : `Failed to read the value for header "${name}" from "${target}".`,
13645
+ { source: error instanceof Error ? error.message : String(error) }
13646
+ );
13647
+ }
13648
+ put(name, contents.replace(/\r?\n$/, ""), "--header-file");
13649
+ }
13650
+ return Object.keys(headers).length > 0 ? { ...headers } : void 0;
13651
+ }
13652
+ function resolveAttributes(pairs) {
13653
+ if (!pairs || pairs.length === 0) return void 0;
13654
+ const out = /* @__PURE__ */ Object.create(null);
13655
+ for (const raw of pairs) {
13656
+ const [key, value] = splitOnFirst(raw, "=", "--attr");
13657
+ if (Object.prototype.hasOwnProperty.call(out, key)) {
13658
+ throw usageError(`Resource attribute "${key}" was given twice.`);
13659
+ }
13660
+ out[key] = value;
13661
+ }
13662
+ return { ...out };
13663
+ }
13664
+ var SOURCE_TYPES = ["eval", "scenario", "swarm", "direct"];
13665
+ function resolveSourceTypes(values) {
13666
+ if (!values || values.length === 0) return void 0;
13667
+ const out = [];
13668
+ for (const raw of values) {
13669
+ const value = raw.trim();
13670
+ if (!SOURCE_TYPES.includes(value)) {
13671
+ throw usageError(
13672
+ `--source expects one of ${SOURCE_TYPES.join(
13673
+ ", "
13674
+ )} (got ${JSON.stringify(raw)}).`
13675
+ );
13676
+ }
13677
+ if (!out.includes(value)) out.push(value);
13678
+ }
13679
+ return out;
13680
+ }
13681
+ var ORG_FLAG_DESCRIPTION = "Organization ID, from `cloud organizations list`";
13682
+ function registerTraceDestinationsCommands(program) {
13683
+ const destinations = program.command("trace-destinations").alias("traces").description(
13684
+ "Stream an organization's traces to an OTLP/HTTP endpoint (Coralogix, Honeycomb, Grafana, a collector). Header values are write-only: no command prints one."
13685
+ );
13686
+ destinations.command("list").description(
13687
+ "List the organization's destinations \u2014 endpoint, sources, redaction setting and delivery health. Header names only, never their values."
13688
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).action(async (options, command) => {
13689
+ const globalOptions = getGlobalOptions(command);
13690
+ const result = await runPlatformOperation(
13691
+ platformOptionsOf(command),
13692
+ globalOptions.timeout,
13693
+ ({ client, signal }) => listTraceDestinationsOperation.execute(
13694
+ { organization: options.org },
13695
+ { client, signal }
13696
+ ),
13697
+ { cloudScope: { kind: "organization", organization: options.org } }
13698
+ );
13699
+ writeResult(result, globalOptions.format);
13700
+ });
13701
+ destinations.command("show").description(
13702
+ "Show one destination in full, including delivery health: the last HTTP status the vendor answered with, sessions and spans delivered, and how many are still queued."
13703
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption(
13704
+ "--destination <id>",
13705
+ "Destination ID, from `cloud trace-destinations list`"
13706
+ ).action(async (options, command) => {
13707
+ const globalOptions = getGlobalOptions(command);
13708
+ const result = await runPlatformOperation(
13709
+ platformOptionsOf(command),
13710
+ globalOptions.timeout,
13711
+ ({ client, signal }) => getTraceDestinationOperation.execute(
13712
+ { organization: options.org, destination: options.destination },
13713
+ { client, signal }
13714
+ ),
13715
+ { cloudScope: { kind: "organization", organization: options.org } }
13716
+ );
13717
+ writeResult(result, globalOptions.format);
13718
+ });
13719
+ destinations.command("create").description(
13720
+ "Create a destination and start streaming. Header values come from --header-env or --header-file; --header takes one inline for scripting."
13721
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--name <name>", "Human label for this destination.").requiredOption(
13722
+ "--endpoint <url>",
13723
+ "The vendor's OTLP/HTTP intake, HTTPS only. `/v1/traces` is appended if the path does not already end there."
13724
+ ).option(
13725
+ "--header-env <Name=VAR>",
13726
+ "Repeatable: read a header's value from an environment variable. Preferred.",
13727
+ collect
13728
+ ).option(
13729
+ "--header-file <Name=path>",
13730
+ "Repeatable: read a header's value from a file (`-` reads stdin). One trailing newline is dropped \u2014 a header cannot span lines.",
13731
+ collect
13732
+ ).option(
13733
+ "--header <Name: value>",
13734
+ "Repeatable, SCRIPTING ONLY: an inline header value is written to your shell history and is visible in `ps` while the command runs.",
13735
+ collect
13736
+ ).option(
13737
+ "--attr <key=value>",
13738
+ "Repeatable: an extra OTel resource attribute (cx.application.name=mcpjam). `mcpjam.*` names are reserved by the exporter.",
13739
+ collect
13740
+ ).option(
13741
+ "--source <type>",
13742
+ "Repeatable: eval, scenario, swarm or direct. `direct` is Playground, and only sessions SHARED to the workspace are ever sent. Defaults to the server's default set.",
13743
+ collect
13744
+ ).option(
13745
+ "--include-content",
13746
+ "Send prompts, outputs, tool arguments and screenshots. OFF by default, and off is the safe reading \u2014 this decides whether customer content leaves the platform."
13747
+ ).option(
13748
+ "--project <id>",
13749
+ "Repeatable: restrict to these projects. Omit for every project in the organization, present and future.",
13750
+ collect
13751
+ ).option(
13752
+ "--compression <mode>",
13753
+ "gzip or none. gzip is optional in OTLP/HTTP and some intakes reject it."
13754
+ ).option(
13755
+ "--preset <id>",
13756
+ "Vendor preset id this was created from (coralogix, honeycomb, \u2026). Labelling only."
13757
+ ).option("--disabled", "Create it without starting the stream.").action(
13758
+ async (options, command) => {
13759
+ const globalOptions = getGlobalOptions(command);
13760
+ const headers = resolveHeaders(options);
13761
+ const resourceAttributes = resolveAttributes(options.attr);
13762
+ const sourceTypes = resolveSourceTypes(options.source);
13763
+ if (options.compression !== void 0 && options.compression !== "gzip" && options.compression !== "none") {
13764
+ throw usageError("--compression expects gzip or none.");
13765
+ }
13766
+ const result = await runPlatformOperation(
13767
+ platformOptionsOf(command),
13768
+ globalOptions.timeout,
13769
+ ({ client, signal }) => createTraceDestinationOperation.execute(
13770
+ {
13771
+ organization: options.org,
13772
+ name: options.name,
13773
+ endpointUrl: options.endpoint,
13774
+ ...headers ? { headers } : {},
13775
+ ...resourceAttributes ? { resourceAttributes } : {},
13776
+ ...sourceTypes ? { sourceTypes } : {},
13777
+ ...options.includeContent ? { includeContent: true } : {},
13778
+ ...options.project ? { projectIds: options.project } : {},
13779
+ ...options.compression ? { compression: options.compression } : {},
13780
+ ...options.preset ? { preset: options.preset } : {},
13781
+ ...options.disabled ? { enabled: false } : {}
13782
+ },
13783
+ { client, signal }
13784
+ ),
13785
+ { cloudScope: { kind: "organization", organization: options.org } }
13786
+ );
13787
+ writeResult(result, globalOptions.format);
13788
+ }
13789
+ );
13790
+ destinations.command("update").description(
13791
+ "Edit a destination. Any header flag REPLACES the whole header set; passing none leaves the stored headers alone."
13792
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--destination <id>", "Destination ID").option("--name <name>", "New label.").option("--endpoint <url>", "New OTLP/HTTP intake, HTTPS only.").option(
13793
+ "--header-env <Name=VAR>",
13794
+ "Repeatable: read a header's value from an environment variable. Preferred.",
13795
+ collect
13796
+ ).option(
13797
+ "--header-file <Name=path>",
13798
+ "Repeatable: read a header's value from a file (`-` reads stdin).",
13799
+ collect
13800
+ ).option(
13801
+ "--header <Name: value>",
13802
+ "Repeatable, SCRIPTING ONLY: written to your shell history and visible in `ps`.",
13803
+ collect
13804
+ ).option(
13805
+ "--clear-headers",
13806
+ "Remove every stored header. Reach for this before pointing a destination at a new endpoint that must not receive the old vendor's credentials \u2014 omitting the header flags LEAVES them, which is not the same thing."
13807
+ ).option(
13808
+ "--attr <key=value>",
13809
+ "Repeatable: REPLACES the resource attributes.",
13810
+ collect
13811
+ ).option("--source <type>", "Repeatable: REPLACES the source list.", collect).option("--include-content", "Start sending content. Audited.").option("--no-include-content", "Stop sending content; redact again.").option(
13812
+ "--project <id>",
13813
+ "Repeatable: REPLACES the project allowlist.",
13814
+ collect
13815
+ ).option(
13816
+ "--all-projects",
13817
+ "Stream every project in the organization. The explicit way back \u2014 an empty --project list would mean a destination that matches nothing."
13818
+ ).option("--compression <mode>", "gzip or none.").option("--enable", "Start streaming.").option("--disable", "Stop streaming, keeping the configuration.").action(
13819
+ async (options, command) => {
13820
+ const globalOptions = getGlobalOptions(command);
13821
+ if (options.enable && options.disable) {
13822
+ throw usageError("Pass --enable or --disable, not both.");
13823
+ }
13824
+ if (options.allProjects && options.project) {
13825
+ throw usageError(
13826
+ "Pass --all-projects or --project, not both \u2014 they are two answers to the same question."
13827
+ );
13828
+ }
13829
+ if (options.compression !== void 0 && options.compression !== "gzip" && options.compression !== "none") {
13830
+ throw usageError("--compression expects gzip or none.");
13831
+ }
13832
+ const headers = resolveHeaders(options);
13833
+ const resourceAttributes = resolveAttributes(options.attr);
13834
+ const sourceTypes = resolveSourceTypes(options.source);
13835
+ const enabled = options.enable ? true : options.disable ? false : void 0;
13836
+ const patch = {
13837
+ ...options.name !== void 0 ? { name: options.name } : {},
13838
+ ...options.endpoint !== void 0 ? { endpointUrl: options.endpoint } : {},
13839
+ ...headers ? { headers } : {},
13840
+ ...resourceAttributes ? { resourceAttributes } : {},
13841
+ ...sourceTypes ? { sourceTypes } : {},
13842
+ // Commander's `--no-include-content` sets this to false, so the
13843
+ // tri-state survives: absent leaves it, true starts sending content,
13844
+ // false redacts again.
13845
+ ...options.includeContent !== void 0 ? { includeContent: options.includeContent } : {},
13846
+ ...options.project ? { projectIds: options.project } : {},
13847
+ ...options.allProjects ? { allProjects: true } : {},
13848
+ ...options.compression ? { compression: options.compression } : {},
13849
+ ...enabled !== void 0 ? { enabled } : {}
13850
+ };
13851
+ if (Object.keys(patch).length === 0) {
13852
+ throw usageError("Nothing to update \u2014 pass at least one field.");
13853
+ }
13854
+ const result = await runPlatformOperation(
13855
+ platformOptionsOf(command),
13856
+ globalOptions.timeout,
13857
+ ({ client, signal }) => updateTraceDestinationOperation.execute(
13858
+ {
13859
+ organization: options.org,
13860
+ destination: options.destination,
13861
+ ...patch
13862
+ },
13863
+ { client, signal }
13864
+ ),
13865
+ { cloudScope: { kind: "organization", organization: options.org } }
13866
+ );
13867
+ writeResult(result, globalOptions.format);
13868
+ }
13869
+ );
13870
+ destinations.command("rm").description(
13871
+ "Delete a destination. Streaming stops and anything queued is discarded \u2014 but traces ALREADY DELIVERED stay in the vendor's system, and nothing here can retract them."
13872
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--destination <id>", "Destination ID").action(async (options, command) => {
13873
+ const globalOptions = getGlobalOptions(command);
13874
+ const result = await runPlatformOperation(
13875
+ platformOptionsOf(command),
13876
+ globalOptions.timeout,
13877
+ ({ client, signal }) => deleteTraceDestinationOperation.execute(
13878
+ { organization: options.org, destination: options.destination },
13879
+ { client, signal }
13880
+ ),
13881
+ { cloudScope: { kind: "organization", organization: options.org } }
13882
+ );
13883
+ writeResult(result, globalOptions.format);
13884
+ });
13885
+ destinations.command("test").description(
13886
+ "Send one synthetic span, to prove the endpoint and credentials work. Returns as soon as the send is SCHEDULED \u2014 read the outcome from `show` a moment later."
13887
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--destination <id>", "Destination ID").action(async (options, command) => {
13888
+ const globalOptions = getGlobalOptions(command);
13889
+ const result = await runPlatformOperation(
13890
+ platformOptionsOf(command),
13891
+ globalOptions.timeout,
13892
+ ({ client, signal }) => testTraceDestinationOperation.execute(
13893
+ { organization: options.org, destination: options.destination },
13894
+ { client, signal }
13895
+ ),
13896
+ { cloudScope: { kind: "organization", organization: options.org } }
13897
+ );
13898
+ writeResult(result, globalOptions.format);
13899
+ });
13900
+ destinations.command("pause").description(
13901
+ "Stop delivering without deleting. NOTHING IS QUEUED while paused: the window becomes a gap, not a backlog, and only `backfill` can fill it."
13902
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--destination <id>", "Destination ID").action(async (options, command) => {
13903
+ const globalOptions = getGlobalOptions(command);
13904
+ const result = await runPlatformOperation(
13905
+ platformOptionsOf(command),
13906
+ globalOptions.timeout,
13907
+ ({ client, signal }) => pauseTraceDestinationOperation.execute(
13908
+ { organization: options.org, destination: options.destination },
13909
+ { client, signal }
13910
+ ),
13911
+ { cloudScope: { kind: "organization", organization: options.org } }
13912
+ );
13913
+ writeResult(result, globalOptions.format);
13914
+ });
13915
+ destinations.command("resume").description(
13916
+ "Start delivering again. Fix what caused an automatic pause first \u2014 `show` reports the reason \u2014 or it will pause again. Reports `pausedSince` so the gap can be sized."
13917
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--destination <id>", "Destination ID").action(async (options, command) => {
13918
+ const globalOptions = getGlobalOptions(command);
13919
+ const result = await runPlatformOperation(
13920
+ platformOptionsOf(command),
13921
+ globalOptions.timeout,
13922
+ ({ client, signal }) => resumeTraceDestinationOperation.execute(
13923
+ { organization: options.org, destination: options.destination },
13924
+ { client, signal }
13925
+ ),
13926
+ { cloudScope: { kind: "organization", organization: options.org } }
13927
+ );
13928
+ writeResult(result, globalOptions.format);
13929
+ });
13930
+ destinations.command("backfill").description(
13931
+ "Replay a window of history \u2014 for the gap a pause left, or to seed a new destination. Queues every eligible session in the window, so a wide window is a lot of vendor ingest."
13932
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--destination <id>", "Destination ID").requiredOption(
13933
+ "--days <n>",
13934
+ "How far back to replay. 1 to 30.",
13935
+ (value) => {
13936
+ const days = Number(value.trim());
13937
+ if (!Number.isInteger(days) || days < 1 || days > 30) {
13938
+ throw usageError("--days expects a whole number between 1 and 30.");
13939
+ }
13940
+ return days;
13941
+ }
13942
+ ).action(async (options, command) => {
13943
+ const globalOptions = getGlobalOptions(command);
13944
+ const result = await runPlatformOperation(
13945
+ platformOptionsOf(command),
13946
+ globalOptions.timeout,
13947
+ ({ client, signal }) => backfillTraceDestinationOperation.execute(
13948
+ {
13949
+ organization: options.org,
13950
+ destination: options.destination,
13951
+ days: options.days
13952
+ },
13953
+ { client, signal }
13954
+ ),
13955
+ { cloudScope: { kind: "organization", organization: options.org } }
13956
+ );
13957
+ writeResult(result, globalOptions.format);
13958
+ });
13959
+ destinations.command("backfills").description(
13960
+ "The 20 most recent backfills for a destination, newest first, with how many sessions each scanned and queued."
13961
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--destination <id>", "Destination ID").action(async (options, command) => {
13962
+ const globalOptions = getGlobalOptions(command);
13963
+ const result = await runPlatformOperation(
13964
+ platformOptionsOf(command),
13965
+ globalOptions.timeout,
13966
+ ({ client, signal }) => listTraceDestinationBackfillsOperation.execute(
13967
+ { organization: options.org, destination: options.destination },
13968
+ { client, signal }
13969
+ ),
13970
+ { cloudScope: { kind: "organization", organization: options.org } }
13971
+ );
13972
+ writeResult(result, globalOptions.format);
13973
+ });
13974
+ }
12943
13975
  function addRequiredOptionWithHiddenAlias(command, visibleFlags, hiddenLongFlag, description) {
12944
13976
  const option = new Option(
12945
13977
  `${hiddenLongFlag}, ${visibleFlags}`,
@@ -14336,6 +15368,8 @@ function registerCloudCommands(program) {
14336
15368
  registerSecretsCommands(cloud);
14337
15369
  registerImagesCommands(cloud);
14338
15370
  registerSkillsCommands(cloud);
15371
+ cloud.commandsGroup("Observability:");
15372
+ registerTraceDestinationsCommands(cloud);
14339
15373
  cloud.commandsGroup("Swarms and user testing:");
14340
15374
  const journeys = registerJourneysCommands(cloud);
14341
15375
  registerScenariosCommands(cloud);
@@ -14367,7 +15401,7 @@ function resolveHostFromOptions(options) {
14367
15401
  return resolveHostConnection(options.host);
14368
15402
  }
14369
15403
  function applyHostToConfig(config, host) {
14370
- const identity = {
15404
+ const identity2 = {
14371
15405
  ...host.clientInfo ? { clientInfo: host.clientInfo } : {},
14372
15406
  ...host.clientCapabilities ? { clientCapabilities: host.clientCapabilities } : {},
14373
15407
  ...host.supportedProtocolVersions ? { supportedProtocolVersions: host.supportedProtocolVersions } : {}
@@ -14382,7 +15416,7 @@ function applyHostToConfig(config, host) {
14382
15416
  };
14383
15417
  return {
14384
15418
  ...config,
14385
- ...identity,
15419
+ ...identity2,
14386
15420
  ...httpOnly,
14387
15421
  ...conformance
14388
15422
  };
@@ -16034,6 +17068,8 @@ function createMcpJamMcpServer(options) {
16034
17068
  url,
16035
17069
  accessToken,
16036
17070
  headers,
17071
+ // See the `server probe` command: this runs on the user's machine.
17072
+ allowPrivateNetwork: true,
16037
17073
  timeoutMs: timeoutMs ?? defaultTimeoutMs
16038
17074
  });
16039
17075
  return redactForTelemetry(result);
@@ -17123,12 +18159,18 @@ function registerOAuthCommands(program) {
17123
18159
  setProcessExitCode(3);
17124
18160
  }
17125
18161
  });
17126
- oauth.command("metadata").description("Fetch OAuth metadata from a URL").requiredOption("--url <url>", "OAuth metadata URL").action(async (options, command) => {
18162
+ oauth.command("metadata").description("Fetch OAuth metadata from a URL").requiredOption("--url <url>", "OAuth metadata URL").option(
18163
+ "--https-only",
18164
+ "Apply the hosted policy: reject non-HTTPS and private targets"
18165
+ ).action(async (options, command) => {
17127
18166
  const format = getOAuthFormat(command);
17128
- const result = await runOAuthMetadata(options.url);
18167
+ const result = await runOAuthMetadata(
18168
+ options.url,
18169
+ options.httpsOnly === true
18170
+ );
17129
18171
  writeResult(result, format);
17130
18172
  });
17131
- oauth.command("proxy").description("Proxy an OAuth request with hosted-mode safety checks").requiredOption("--url <url>", "OAuth request URL").option("--method <method>", "HTTP method", "GET").option(
18173
+ oauth.command("proxy").description("Proxy an OAuth request through the SSRF-hardened transport").requiredOption("--url <url>", "OAuth request URL").option("--method <method>", "HTTP method", "GET").option(
17132
18174
  "--header <header>",
17133
18175
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
17134
18176
  (value, previous = []) => [...previous, value],
@@ -17136,12 +18178,17 @@ function registerOAuthCommands(program) {
17136
18178
  ).option(
17137
18179
  "--body <value>",
17138
18180
  "Request body as JSON, raw string, @path, or - for stdin"
18181
+ ).option(
18182
+ "--https-only",
18183
+ "Apply the hosted policy: reject non-HTTPS and private targets"
17139
18184
  ).action(async (options, command) => {
17140
18185
  const format = getOAuthFormat(command);
17141
18186
  const result = await runOAuthProxy(options);
17142
18187
  writeResult(result, format);
17143
18188
  });
17144
- oauth.command("debug-proxy").description("Proxy an OAuth debug request with hosted-mode safety checks").requiredOption("--url <url>", "OAuth request URL").option("--method <method>", "HTTP method", "GET").option(
18189
+ oauth.command("debug-proxy").description(
18190
+ "Proxy an OAuth debug request through the SSRF-hardened transport"
18191
+ ).requiredOption("--url <url>", "OAuth request URL").option("--method <method>", "HTTP method", "GET").option(
17145
18192
  "--header <header>",
17146
18193
  'HTTP header in "Key: Value" format. Repeat to send multiple headers.',
17147
18194
  (value, previous = []) => [...previous, value],
@@ -17149,6 +18196,9 @@ function registerOAuthCommands(program) {
17149
18196
  ).option(
17150
18197
  "--body <value>",
17151
18198
  "Request body as JSON, raw string, @path, or - for stdin"
18199
+ ).option(
18200
+ "--https-only",
18201
+ "Apply the hosted policy: reject non-HTTPS and private targets"
17152
18202
  ).action(async (options, command) => {
17153
18203
  const format = getOAuthFormat(command);
17154
18204
  const result = await runOAuthDebugProxy(
@@ -17228,6 +18278,9 @@ function buildOAuthConformanceConfig(options, defaults) {
17228
18278
  serverUrl,
17229
18279
  protocolVersion,
17230
18280
  registrationStrategy,
18281
+ // The CLI runs on the user's machine, where the server under test is
18282
+ // routinely on loopback or a LAN address.
18283
+ allowPrivateNetwork: true,
17231
18284
  auth,
17232
18285
  client,
17233
18286
  scopes: options.scopes?.trim() || void 0,
@@ -17318,6 +18371,8 @@ function buildOAuthLoginConfig(options, defaults) {
17318
18371
  ...registrationStrategy ? { registrationStrategy } : {},
17319
18372
  protocolMode: protocolVersion ?? "auto",
17320
18373
  registrationMode: registrationStrategy ?? "auto",
18374
+ // See buildOAuthConformanceConfig: a local server under test is the norm.
18375
+ allowPrivateNetwork: true,
17321
18376
  auth,
17322
18377
  client,
17323
18378
  scopes: options.scopes?.trim() || void 0,
@@ -17439,9 +18494,12 @@ function parseAuthMode(value) {
17439
18494
  `Invalid auth mode "${value}". Use ${[...VALID_AUTH_MODES].join(", ")}.`
17440
18495
  );
17441
18496
  }
17442
- async function runOAuthMetadata(url) {
18497
+ async function runOAuthMetadata(url, httpsOnly = false) {
17443
18498
  try {
17444
- const result = await fetchOAuthMetadata(url, true);
18499
+ const result = await fetchOAuthMetadata(url, {
18500
+ httpsOnly,
18501
+ allowPrivateNetwork: !httpsOnly
18502
+ });
17445
18503
  if ("status" in result && result.status !== void 0) {
17446
18504
  throw cliError(
17447
18505
  statusToErrorCode(result.status),
@@ -17460,7 +18518,8 @@ async function runOAuthProxy(options) {
17460
18518
  method: options.method,
17461
18519
  headers: parseHeadersOption(options.header),
17462
18520
  body: parseProxyBody(options.body),
17463
- httpsOnly: true
18521
+ httpsOnly: options.httpsOnly === true,
18522
+ allowPrivateNetwork: options.httpsOnly !== true
17464
18523
  });
17465
18524
  } catch (error) {
17466
18525
  throw mapOAuthProxyError(error);
@@ -17473,7 +18532,8 @@ async function runOAuthDebugProxy(options) {
17473
18532
  method: options.method,
17474
18533
  headers: parseHeadersOption(options.header),
17475
18534
  body: parseProxyBody(options.body),
17476
- httpsOnly: true
18535
+ httpsOnly: options.httpsOnly === true,
18536
+ allowPrivateNetwork: options.httpsOnly !== true
17477
18537
  });
17478
18538
  } catch (error) {
17479
18539
  throw mapOAuthProxyError(error);
@@ -17737,7 +18797,10 @@ function buildXaaConfig(options, timeoutMs) {
17737
18797
  } : {},
17738
18798
  ...options.scopes?.trim() ? { scope: options.scopes.trim() } : {},
17739
18799
  ...timeoutMs !== void 0 ? { timeoutMs } : {},
17740
- httpsOnly: options.httpsOnly ?? false
18800
+ httpsOnly: options.httpsOnly ?? false,
18801
+ // The inverse of the hosted switch: without --https-only this is a local
18802
+ // dev run, and the mock IdP plus the RS it talks to are on loopback.
18803
+ allowPrivateNetwork: options.httpsOnly !== true
17741
18804
  };
17742
18805
  }
17743
18806
  function parseRegistration(value) {
@@ -18239,6 +19302,9 @@ function registerServerCommands(program) {
18239
19302
  result = await probeMcpServer({
18240
19303
  url: probeUrl,
18241
19304
  protocolVersion,
19305
+ // Local tool, local servers: probing http://127.0.0.1:3000/mcp is
19306
+ // the ordinary case, not the exception.
19307
+ allowPrivateNetwork: true,
18242
19308
  headers: parseHeadersOption(options.header),
18243
19309
  accessToken,
18244
19310
  clientCapabilities: "clientCapabilities" in config ? config.clientCapabilities : void 0,
@@ -19072,7 +20138,7 @@ function registerSubscriptionsCommands(program) {
19072
20138
  ...options,
19073
20139
  timeout: globalOptions.timeout
19074
20140
  });
19075
- const emit = (event) => {
20141
+ const emit2 = (event) => {
19076
20142
  process.stdout.write(`${JSON.stringify(event)}
19077
20143
  `);
19078
20144
  };
@@ -19103,7 +20169,7 @@ function registerSubscriptionsCommands(program) {
19103
20169
  reconnect,
19104
20170
  ...handlers
19105
20171
  }),
19106
- emit,
20172
+ emit: emit2,
19107
20173
  status
19108
20174
  }
19109
20175
  );
@@ -19887,7 +20953,7 @@ async function driveTaskWatch(args) {
19887
20953
  1
19888
20954
  );
19889
20955
  }
19890
- const identity = {
20956
+ const identity2 = {
19891
20957
  serverId,
19892
20958
  wire: support.wire,
19893
20959
  taskId
@@ -19898,7 +20964,7 @@ async function driveTaskWatch(args) {
19898
20964
  }
19899
20965
  const extension = support.wire === "extension";
19900
20966
  const result = await driveTaskToTerminal({
19901
- identity,
20967
+ identity: identity2,
19902
20968
  engine,
19903
20969
  getTask: async () => extension ? extensionTaskToObservation(await manager.getTaskExt(serverId, taskId)) : legacyTaskToObservation(
19904
20970
  await manager.getTask(serverId, taskId)
@@ -21512,6 +22578,692 @@ function registerInspectorCommands(program) {
21512
22578
  );
21513
22579
  });
21514
22580
  }
22581
+ var STORE_VERSION = 1;
22582
+ function getBrowserStateFilePath(options = {}) {
22583
+ const env = options.env ?? process.env;
22584
+ const platform = options.platform ?? process.platform;
22585
+ const homeDirectory = options.homeDirectory ?? homedir();
22586
+ if (env.MCPJAM_BROWSER_STATE_FILE) return env.MCPJAM_BROWSER_STATE_FILE;
22587
+ if (platform === "win32") {
22588
+ return join(
22589
+ env.APPDATA || join(homeDirectory, "AppData", "Roaming"),
22590
+ "mcpjam",
22591
+ "browser.json"
22592
+ );
22593
+ }
22594
+ return join(
22595
+ env.XDG_CONFIG_HOME || join(homeDirectory, ".config"),
22596
+ "mcpjam",
22597
+ "browser.json"
22598
+ );
22599
+ }
22600
+ function readBrowserState(filePath) {
22601
+ let raw;
22602
+ try {
22603
+ raw = readFileSync(filePath, "utf8");
22604
+ } catch {
22605
+ return { version: STORE_VERSION };
22606
+ }
22607
+ try {
22608
+ const parsed = JSON.parse(raw);
22609
+ return {
22610
+ version: STORE_VERSION,
22611
+ ...typeof parsed.consent === "string" ? { consent: parsed.consent } : {},
22612
+ ...isSessionMap(parsed.sessions) ? { sessions: parsed.sessions } : {}
22613
+ };
22614
+ } catch {
22615
+ return { version: STORE_VERSION };
22616
+ }
22617
+ }
22618
+ async function writeBrowserState(filePath, state) {
22619
+ await mkdir(dirname(filePath), { recursive: true, mode: 448 });
22620
+ await writeFileAtomic(filePath, JSON.stringify(state, null, 2), {
22621
+ mode: 384
22622
+ });
22623
+ }
22624
+ async function rememberSession(filePath, projectId, sessionId) {
22625
+ const state = readBrowserState(filePath);
22626
+ await writeBrowserState(filePath, {
22627
+ ...state,
22628
+ sessions: { ...state.sessions ?? {}, [projectId]: sessionId }
22629
+ });
22630
+ }
22631
+ async function forgetSessionIf(filePath, projectId, sessionId) {
22632
+ const state = readBrowserState(filePath);
22633
+ if (state.sessions?.[projectId] !== sessionId) return false;
22634
+ const sessions = { ...state.sessions };
22635
+ delete sessions[projectId];
22636
+ await writeBrowserState(filePath, { ...state, sessions });
22637
+ return true;
22638
+ }
22639
+ function isSessionMap(value) {
22640
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.values(value).every(
22641
+ (entry) => typeof entry === "string"
22642
+ );
22643
+ }
22644
+
22645
+ // src/commands/browser.ts
22646
+ var LOCAL_CONSENT_HEADER = "x-mcpjam-local-consent";
22647
+ var BROWSER_ROUTE = "/api/mcp/computers/local-browser";
22648
+ var CLIENT_KIND = "cli";
22649
+ function addCommonOptions(command) {
22650
+ return command.option("--cloud", "Drive an isolated MCPJam cloud browser").option(
22651
+ "--api-url <url>",
22652
+ "Cloud API URL (for example https://staging.mcpjam.com/api/v1)"
22653
+ ).option(
22654
+ "--api-key <key>",
22655
+ "Cloud API key (or use MCPJAM_API_KEY / cloud login)"
22656
+ ).option("--inspector-url <url>", "Local Inspector base URL").option("--project <id>", "Project whose browser to drive", "default").option(
22657
+ "--session <id>",
22658
+ "Browser session id (defaults to the last opened)"
22659
+ ).option(
22660
+ "--consent <token>",
22661
+ "Local computer consent capability (defaults to the stored one)"
22662
+ ).option(
22663
+ "--client-id <id>",
22664
+ "How this client appears in the session trace",
22665
+ "mcpjam-cli"
22666
+ );
22667
+ }
22668
+ function projectOf(options) {
22669
+ return typeof options.project === "string" && options.project.trim() ? options.project.trim() : "default";
22670
+ }
22671
+ function consentOf(options) {
22672
+ if (typeof options.consent === "string" && options.consent.trim()) {
22673
+ return options.consent.trim();
22674
+ }
22675
+ const fromEnv = process.env.MCPJAM_LOCAL_CONSENT;
22676
+ if (fromEnv && fromEnv.trim()) return fromEnv.trim();
22677
+ const stored = readBrowserState(getBrowserStateFilePath()).consent;
22678
+ if (stored) return stored;
22679
+ throw operationalError(
22680
+ "This machine's browser has not been authorized for the CLI.",
22681
+ "Open the Inspector, allow the local computer, then run `mcpjam browser consent --token <capability>` (or set MCPJAM_LOCAL_CONSENT). The CLI never grants this itself \u2014 the consent screen is where a person authorizes the agent browser."
22682
+ );
22683
+ }
22684
+ function sessionStoreKey(options, projectId) {
22685
+ if (!options.cloud) return projectId;
22686
+ const { baseUrl } = buildPlatformClient(options);
22687
+ return `cloud:${baseUrl.replace(/\/$/, "")}:${projectId}`;
22688
+ }
22689
+ function sessionOf(options, projectId) {
22690
+ const storeKey = sessionStoreKey(options, projectId);
22691
+ if (typeof options.session === "string" && options.session.trim()) {
22692
+ return options.session.trim();
22693
+ }
22694
+ const sessions = readBrowserState(getBrowserStateFilePath()).sessions;
22695
+ const stored = sessions && Object.hasOwn(sessions, storeKey) ? sessions[storeKey] : void 0;
22696
+ if (typeof stored === "string" && stored) return stored;
22697
+ throw usageError(
22698
+ `No open browser session for project \`${projectId}\`.`,
22699
+ "Run `mcpjam browser open` first, or pass --session <id>."
22700
+ );
22701
+ }
22702
+ function browserBaseUrl(options) {
22703
+ const baseUrl = normalizeInspectorBaseUrl(
22704
+ typeof options.inspectorUrl === "string" ? options.inspectorUrl : void 0
22705
+ );
22706
+ let parsed;
22707
+ try {
22708
+ parsed = new URL(baseUrl);
22709
+ } catch {
22710
+ throw usageError(`\`${baseUrl}\` is not a valid Inspector URL.`);
22711
+ }
22712
+ const loopback = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1" || parsed.hostname === "[::1]" || parsed.hostname === "::1";
22713
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && loopback)) {
22714
+ throw usageError(
22715
+ `Refusing to send the local computer consent capability to ${baseUrl} in cleartext.`,
22716
+ "Use https:// for a remote Inspector; http:// is allowed for localhost only."
22717
+ );
22718
+ }
22719
+ return baseUrl;
22720
+ }
22721
+ async function post(options, path9, body, timeoutMs) {
22722
+ if (options.cloud) {
22723
+ if (options.inspectorUrl || options.consent)
22724
+ throw usageError(
22725
+ "--cloud uses cloud credentials, not --inspector-url or --consent"
22726
+ );
22727
+ if (body.projectId === "default")
22728
+ throw usageError("Pass --project <cloud-project-id>");
22729
+ const { client: client2 } = buildPlatformClient({
22730
+ ...options,
22731
+ timeoutMs: timeoutMs ?? 12e4
22732
+ });
22733
+ return client2.browserSession(
22734
+ path9.slice(1),
22735
+ body
22736
+ );
22737
+ }
22738
+ const client = new InspectorApiClient({ baseUrl: browserBaseUrl(options) });
22739
+ const result = await client.request(`${BROWSER_ROUTE}${path9}`, {
22740
+ method: "POST",
22741
+ body,
22742
+ headers: { [LOCAL_CONSENT_HEADER]: consentOf(options) },
22743
+ ...timeoutMs ? { timeoutMs } : {},
22744
+ // The door answers a REFUSAL with 403 and an UNKNOWN outcome with 502, and
22745
+ // those bodies carry the distinction the whole contract turns on: `refused`
22746
+ // means nothing ran and a retry is safe; `unknown` means it may have run
22747
+ // and a retry could submit it twice. Letting the transport throw them away
22748
+ // collapses both into one generic error, and a script that retries on
22749
+ // failure re-submits a command that already happened.
22750
+ //
22751
+ // Only a body that IS a contract result is claimed. A consent failure or a
22752
+ // bad artifactId still throws, so it stays loud.
22753
+ treatAsSuccess: (_status, payload) => isContractResult(payload)
22754
+ });
22755
+ return result ?? {};
22756
+ }
22757
+ function isContractResult(payload) {
22758
+ if (typeof payload !== "object" || payload === null) return false;
22759
+ const status = payload.status;
22760
+ return status === "executed" || status === "refused" || status === "unknown";
22761
+ }
22762
+ function identity(options) {
22763
+ return {
22764
+ client: CLIENT_KIND,
22765
+ clientId: typeof options.clientId === "string" ? options.clientId : "mcpjam-cli"
22766
+ };
22767
+ }
22768
+ async function fetchScreenshot(options, projectId, sessionId, page, outDir, inline = false, timeoutMs) {
22769
+ const artifact = page?.artifacts?.screenshot;
22770
+ if (!artifact?.id) return { kind: "none" };
22771
+ if (artifact.evicted) {
22772
+ return {
22773
+ kind: "failed",
22774
+ detail: "the screenshot was captured but its payload is no longer kept"
22775
+ };
22776
+ }
22777
+ if (options.cloud) {
22778
+ const body = await post(
22779
+ options,
22780
+ "/artifact",
22781
+ { projectId, sessionId, artifactId: artifact.id },
22782
+ timeoutMs
22783
+ );
22784
+ if (typeof body.screenshot !== "string")
22785
+ return { kind: "failed", detail: "Screenshot is no longer available" };
22786
+ if (inline)
22787
+ return {
22788
+ kind: "inline",
22789
+ base64: body.screenshot,
22790
+ mediaType: "image/jpeg"
22791
+ };
22792
+ const file2 = join(outDir ?? tmpdir(), `mcpjam-browser-${artifact.id}.jpg`);
22793
+ await writeFile(file2, Buffer.from(body.screenshot, "base64"));
22794
+ return { kind: "file", path: file2 };
22795
+ }
22796
+ const baseUrl = browserBaseUrl(options);
22797
+ const token = await fetchInspectorSessionToken(baseUrl);
22798
+ const response = await fetch(`${baseUrl}${BROWSER_ROUTE}/artifact`, {
22799
+ method: "POST",
22800
+ headers: {
22801
+ "Content-Type": "application/json",
22802
+ "X-MCP-Session-Auth": `Bearer ${token}`,
22803
+ [LOCAL_CONSENT_HEADER]: consentOf(options)
22804
+ },
22805
+ body: JSON.stringify({ projectId, sessionId, artifactId: artifact.id }),
22806
+ // The SAME budget the command itself got. Without a signal a route that
22807
+ // keeps its response body open never settles `arrayBuffer()`, and the CLI
22808
+ // sits there having already run the command it will never print.
22809
+ signal: AbortSignal.timeout(timeoutMs ?? 3e4)
22810
+ });
22811
+ if (!response.ok) {
22812
+ return {
22813
+ kind: "failed",
22814
+ detail: `the screenshot could not be fetched (HTTP ${response.status})`
22815
+ };
22816
+ }
22817
+ const buffer = Buffer.from(await response.arrayBuffer());
22818
+ if (inline) {
22819
+ return {
22820
+ kind: "inline",
22821
+ base64: buffer.toString("base64"),
22822
+ mediaType: artifact.mediaType ?? "image/jpeg"
22823
+ };
22824
+ }
22825
+ const file = join(
22826
+ outDir ?? tmpdir(),
22827
+ `mcpjam-browser-${artifact.id}${extensionFor(artifact.mediaType)}`
22828
+ );
22829
+ await writeFile(file, buffer);
22830
+ return { kind: "file", path: file };
22831
+ }
22832
+ function extensionFor(mediaType) {
22833
+ return mediaType && !mediaType.startsWith("image/") ? ".txt" : ".jpg";
22834
+ }
22835
+ function registerBrowserCommands(program) {
22836
+ const browser = program.command("browser").description("Drive a local or cloud browser and read its session trace");
22837
+ browser.command("consent").description("Store the local computer capability granted in the Inspector").requiredOption(
22838
+ "--token <token>",
22839
+ "The capability the Inspector showed once"
22840
+ ).action(async (options, command) => {
22841
+ const globalOptions = getGlobalOptions(
22842
+ command,
22843
+ options.cloud ? 12e4 : 3e4
22844
+ );
22845
+ const file = getBrowserStateFilePath();
22846
+ const state = readBrowserState(file);
22847
+ await writeBrowserState(file, {
22848
+ ...state,
22849
+ consent: String(options.token)
22850
+ });
22851
+ writeResult({ success: true, stored: file }, globalOptions.format);
22852
+ });
22853
+ addCommonOptions(
22854
+ browser.command("open").description("Open (or attach to) this project's browser session")
22855
+ ).option(
22856
+ "--mode <mode>",
22857
+ "Session policy: allow_all | read_only | allowlist",
22858
+ "allow_all"
22859
+ ).option("--origin <origin...>", "Origins this session may visit").option("--tool <op...>", "Operations this session may use").option("--profile <profile>", "persistent | ephemeral", "persistent").option("--attach <mode>", "prefer | never | require", "prefer").option("--observe <mode>", "Initial observation: a11y | screenshot | none").option("--out-dir <dir>", "Where to write an initial screenshot").option(
22860
+ "--run-key <key>",
22861
+ "Names an ephemeral run, so two never share a profile"
22862
+ ).option(
22863
+ "--no-screenshots",
22864
+ "Keep a ledger without pictures for this session"
22865
+ ).action(async (options, command) => {
22866
+ const globalOptions = getGlobalOptions(
22867
+ command,
22868
+ options.cloud ? 12e4 : 3e4
22869
+ );
22870
+ const projectId = projectOf(options);
22871
+ if (options.profile !== "persistent" && options.profile !== "ephemeral") {
22872
+ throw usageError(
22873
+ `Unknown --profile \`${String(options.profile)}\`.`,
22874
+ "Use --profile persistent or --profile ephemeral."
22875
+ );
22876
+ }
22877
+ const body = await post(
22878
+ options,
22879
+ "/session",
22880
+ {
22881
+ projectId,
22882
+ attach: options.attach,
22883
+ profile: options.profile,
22884
+ policy: {
22885
+ mode: options.mode,
22886
+ ...Array.isArray(options.origin) && options.origin.length ? { originAllowlist: options.origin } : {},
22887
+ ...Array.isArray(options.tool) && options.tool.length ? { toolAllowlist: options.tool } : {}
22888
+ },
22889
+ ...options.screenshots === false ? { captureScreenshots: false } : {},
22890
+ ...options.observe ? { observe: options.observe } : {},
22891
+ ...typeof options.runKey === "string" ? { runKey: options.runKey } : {},
22892
+ ...identity(options)
22893
+ },
22894
+ globalOptions.timeout
22895
+ );
22896
+ const session = body.session;
22897
+ if (session?.sessionId) {
22898
+ await rememberSession(
22899
+ getBrowserStateFilePath(),
22900
+ sessionStoreKey(options, projectId),
22901
+ session.sessionId
22902
+ );
22903
+ }
22904
+ let extra = {};
22905
+ if (options.observe === "screenshot" && session?.sessionId) {
22906
+ const shot = await fetchScreenshot(
22907
+ options,
22908
+ projectId,
22909
+ session.sessionId,
22910
+ body.page,
22911
+ typeof options.outDir === "string" ? options.outDir : void 0,
22912
+ false,
22913
+ globalOptions.timeout
22914
+ ).catch((error) => ({
22915
+ kind: "failed",
22916
+ detail: error instanceof Error ? error.message : String(error)
22917
+ }));
22918
+ if (shot.kind === "file") extra = { screenshotPath: shot.path };
22919
+ else if (shot.kind === "failed")
22920
+ extra = { screenshotError: shot.detail };
22921
+ }
22922
+ writeResult({ success: true, ...body, ...extra }, globalOptions.format);
22923
+ });
22924
+ addCommonOptions(
22925
+ browser.command("sessions").description("List browser sessions")
22926
+ ).action(async (options, command) => {
22927
+ const body = await post(
22928
+ options,
22929
+ "/sessions",
22930
+ { projectId: projectOf(options) },
22931
+ getGlobalOptions(command).timeout
22932
+ );
22933
+ writeResult(body, getGlobalOptions(command).format);
22934
+ });
22935
+ addCommonOptions(browser.command("observe").description("Look at the page")).option(
22936
+ "--mode <mode>",
22937
+ "a11y | screenshot | text | dom | console | network | dialog | url | page_tools",
22938
+ "a11y"
22939
+ ).option(
22940
+ "--request <id>",
22941
+ "With --mode network: read one exchange instead of the tail"
22942
+ ).option("--root-ref <ref>", "Scope an a11y tree to a ref").option("--root-selector <selector>", "Scope an a11y tree to a selector").option("--filter <filter>", "interactive | all").option("--tab <tabId>", "Which tab to observe").option("--out-dir <dir>", "Where to write a screenshot").option("--inline", "Return screenshot bytes instead of a file path").action(async (options, command) => {
22943
+ const globalOptions = getGlobalOptions(
22944
+ command,
22945
+ options.cloud ? 12e4 : 3e4
22946
+ );
22947
+ const projectId = projectOf(options);
22948
+ const sessionId = sessionOf(options, projectId);
22949
+ const result = await post(
22950
+ options,
22951
+ "/command",
22952
+ {
22953
+ projectId,
22954
+ sessionId,
22955
+ ...options.tab ? { tabId: options.tab } : {},
22956
+ command: {
22957
+ op: "observe",
22958
+ mode: options.mode,
22959
+ ...options.request ? { requestId: options.request } : {},
22960
+ ...options.rootRef ? { rootRef: options.rootRef } : {},
22961
+ ...options.rootSelector ? { rootSelector: options.rootSelector } : {},
22962
+ ...options.filter ? { filter: options.filter } : {}
22963
+ },
22964
+ ...identity(options)
22965
+ },
22966
+ globalOptions.timeout
22967
+ );
22968
+ await emit(result, {
22969
+ options,
22970
+ projectId,
22971
+ sessionId,
22972
+ format: globalOptions.format,
22973
+ timeoutMs: globalOptions.timeout,
22974
+ saveScreenshots: options.mode === "screenshot" && !options.inline,
22975
+ inline: options.mode === "screenshot" && options.inline === true,
22976
+ outDir: typeof options.outDir === "string" ? options.outDir : void 0
22977
+ });
22978
+ });
22979
+ addCommonOptions(
22980
+ browser.command("navigate <url>").description("Go to a URL, returning the page it landed on")
22981
+ ).option("--new-tab", "Open in a new tab").option("--tab <tabId>", "Which tab to navigate").option(
22982
+ "--command-id <id>",
22983
+ "Idempotency key: reuse it to retry safely after a transport failure"
22984
+ ).option("--observe-after <mode>", "a11y | screenshot | none", "a11y").action(async (url, options, command) => {
22985
+ const globalOptions = getGlobalOptions(
22986
+ command,
22987
+ options.cloud ? 12e4 : 3e4
22988
+ );
22989
+ const projectId = projectOf(options);
22990
+ const sessionId = sessionOf(options, projectId);
22991
+ const result = await post(
22992
+ options,
22993
+ "/command",
22994
+ {
22995
+ projectId,
22996
+ sessionId,
22997
+ ...options.tab ? { tabId: options.tab } : {},
22998
+ ...options.commandId ? { commandId: options.commandId } : {},
22999
+ command: {
23000
+ op: "navigate",
23001
+ url,
23002
+ ...options.newTab ? { newTab: true } : {},
23003
+ observeAfter: options.observeAfter
23004
+ },
23005
+ ...identity(options)
23006
+ },
23007
+ globalOptions.timeout
23008
+ );
23009
+ await emit(result, {
23010
+ options,
23011
+ projectId,
23012
+ sessionId,
23013
+ format: globalOptions.format,
23014
+ timeoutMs: globalOptions.timeout,
23015
+ saveScreenshots: options.observeAfter === "screenshot",
23016
+ outDir: typeof options.outDir === "string" ? options.outDir : void 0
23017
+ });
23018
+ });
23019
+ addCommonOptions(
23020
+ browser.command("act").description(
23021
+ "Click, type, press, scroll, hover, drag, select, or move tabs"
23022
+ )
23023
+ ).requiredOption(
23024
+ "--verb <verb>",
23025
+ "click | type | press | scroll | hover | drag | select | close_tab | activate_tab | accept_dialog | dismiss_dialog"
23026
+ ).option("--ref <ref>", "Target a ref from the last a11y observation").option("--selector <selector>", "Target a CSS selector").option("--x <x>", "Target x, in the 1024x768 observation viewport").option("--y <y>", "Target y, in the 1024x768 observation viewport").option("--value <value>", "Text to type, key to press, option to select").option("--expected-state <token>", "Refuse if the page has moved since").option("--tab <tabId>", "Which tab to act on").option(
23027
+ "--command-id <id>",
23028
+ "Idempotency key: reuse it to retry safely after a transport failure"
23029
+ ).option("--observe-after <mode>", "a11y | screenshot | none", "a11y").option("--out-dir <dir>", "Where to write a screenshot").action(async (options, command) => {
23030
+ const globalOptions = getGlobalOptions(
23031
+ command,
23032
+ options.cloud ? 12e4 : 3e4
23033
+ );
23034
+ const projectId = projectOf(options);
23035
+ const sessionId = sessionOf(options, projectId);
23036
+ const result = await post(
23037
+ options,
23038
+ "/command",
23039
+ {
23040
+ projectId,
23041
+ sessionId,
23042
+ ...options.tab ? { tabId: options.tab } : {},
23043
+ ...options.commandId ? { commandId: options.commandId } : {},
23044
+ command: {
23045
+ op: "act",
23046
+ verb: options.verb,
23047
+ ...targetFrom(options) ? { target: targetFrom(options) } : {},
23048
+ ...options.value === void 0 ? {} : { value: options.value },
23049
+ ...options.expectedState ? { expectedState: options.expectedState } : {},
23050
+ observeAfter: options.observeAfter
23051
+ },
23052
+ ...identity(options)
23053
+ },
23054
+ globalOptions.timeout
23055
+ );
23056
+ await emit(result, {
23057
+ options,
23058
+ projectId,
23059
+ sessionId,
23060
+ format: globalOptions.format,
23061
+ timeoutMs: globalOptions.timeout,
23062
+ saveScreenshots: options.observeAfter === "screenshot",
23063
+ outDir: typeof options.outDir === "string" ? options.outDir : void 0
23064
+ });
23065
+ });
23066
+ for (const op of ["back", "forward", "reload"]) {
23067
+ addCommonOptions(
23068
+ browser.command(op).description(`${op} the current browser tab`)
23069
+ ).option("--tab <id>", "Tab to drive").option("--command-id <id>", "Idempotency key for this command").action(async (options, command) => {
23070
+ const global = getGlobalOptions(
23071
+ command,
23072
+ options.cloud ? 12e4 : 3e4
23073
+ );
23074
+ const projectId = projectOf(options);
23075
+ const sessionId = sessionOf(options, projectId);
23076
+ const result = await post(
23077
+ options,
23078
+ "/command",
23079
+ {
23080
+ projectId,
23081
+ sessionId,
23082
+ command: { op, observeAfter: "a11y" },
23083
+ ...identity(options),
23084
+ ...options.tab ? { tabId: options.tab } : {},
23085
+ ...options.commandId ? { commandId: options.commandId } : {}
23086
+ },
23087
+ global.timeout
23088
+ );
23089
+ await emit(result, {
23090
+ options,
23091
+ projectId,
23092
+ sessionId,
23093
+ format: global.format,
23094
+ saveScreenshots: false
23095
+ });
23096
+ });
23097
+ }
23098
+ addCommonOptions(
23099
+ browser.command("invoke <toolKey>").description("Invoke a WebMCP tool listed by observe --mode page_tools")
23100
+ ).option("--input <json>", "Tool arguments as JSON", "{}").option("--frame <id>", "Frame declaring the tool").option("--tab <id>", "Tab declaring the tool").option("--command-id <id>", "Idempotency key for this invocation").action(async (toolKey, options, command) => {
23101
+ let input;
23102
+ try {
23103
+ input = JSON.parse(options.input);
23104
+ } catch {
23105
+ throw usageError("--input must be valid JSON");
23106
+ }
23107
+ const global = getGlobalOptions(
23108
+ command,
23109
+ options.cloud ? 12e4 : 3e4
23110
+ );
23111
+ const projectId = projectOf(options);
23112
+ const sessionId = sessionOf(options, projectId);
23113
+ const result = await post(
23114
+ options,
23115
+ "/command",
23116
+ {
23117
+ projectId,
23118
+ sessionId,
23119
+ command: {
23120
+ op: "invoke_page_tool",
23121
+ toolKey,
23122
+ input,
23123
+ ...options.frame ? { frameId: options.frame } : {}
23124
+ },
23125
+ ...identity(options),
23126
+ ...options.tab ? { tabId: options.tab } : {},
23127
+ ...options.commandId ? { commandId: options.commandId } : {}
23128
+ },
23129
+ global.timeout
23130
+ );
23131
+ await emit(result, {
23132
+ options,
23133
+ projectId,
23134
+ sessionId,
23135
+ format: global.format,
23136
+ saveScreenshots: false
23137
+ });
23138
+ });
23139
+ addCommonOptions(
23140
+ browser.command("note <text>").description("Write a marker into the session trace")
23141
+ ).action(async (text, options, command) => {
23142
+ const globalOptions = getGlobalOptions(
23143
+ command,
23144
+ options.cloud ? 12e4 : 3e4
23145
+ );
23146
+ const projectId = projectOf(options);
23147
+ const sessionId = sessionOf(options, projectId);
23148
+ const body = await post(
23149
+ options,
23150
+ "/note",
23151
+ { projectId, sessionId, text, ...identity(options) },
23152
+ globalOptions.timeout
23153
+ );
23154
+ writeResult({ success: true, ...body }, globalOptions.format);
23155
+ });
23156
+ addCommonOptions(
23157
+ browser.command("trace").description("Read this session's command history")
23158
+ ).option("--after-seq <seq>", "Only rows after this seq").option("--command-id <id>", "Find one command's row").option("--limit <n>", "How many rows", "100").action(async (options, command) => {
23159
+ const globalOptions = getGlobalOptions(
23160
+ command,
23161
+ options.cloud ? 12e4 : 3e4
23162
+ );
23163
+ const projectId = projectOf(options);
23164
+ const sessionId = sessionOf(options, projectId);
23165
+ const body = await post(
23166
+ options,
23167
+ "/trace",
23168
+ {
23169
+ projectId,
23170
+ sessionId,
23171
+ ...options.afterSeq === void 0 ? {} : { afterSeq: Number(options.afterSeq) },
23172
+ ...options.commandId ? { commandId: options.commandId } : {},
23173
+ limit: Number(options.limit)
23174
+ },
23175
+ globalOptions.timeout
23176
+ );
23177
+ writeResult({ success: true, ...body }, globalOptions.format);
23178
+ });
23179
+ addCommonOptions(
23180
+ browser.command("close").description("Leave the session; --terminate closes the browser too")
23181
+ ).option(
23182
+ "--terminate",
23183
+ "Close the browser itself, not just this participant"
23184
+ ).action(async (options, command) => {
23185
+ const globalOptions = getGlobalOptions(
23186
+ command,
23187
+ options.cloud ? 12e4 : 3e4
23188
+ );
23189
+ const projectId = projectOf(options);
23190
+ const sessionId = sessionOf(options, projectId);
23191
+ const body = await post(
23192
+ options,
23193
+ "/close",
23194
+ {
23195
+ projectId,
23196
+ sessionId,
23197
+ ...options.terminate ? { terminate: true } : {},
23198
+ ...identity(options)
23199
+ },
23200
+ globalOptions.timeout
23201
+ );
23202
+ await forgetSessionIf(
23203
+ getBrowserStateFilePath(),
23204
+ sessionStoreKey(options, projectId),
23205
+ sessionId
23206
+ );
23207
+ writeResult({ success: true, ...body }, globalOptions.format);
23208
+ });
23209
+ }
23210
+ function targetFrom(options) {
23211
+ const named = [
23212
+ typeof options.ref === "string" && options.ref ? "ref" : null,
23213
+ typeof options.selector === "string" && options.selector ? "selector" : null,
23214
+ options.x !== void 0 || options.y !== void 0 ? "coordinates" : null
23215
+ ].filter(Boolean);
23216
+ if (named.length === 0) return void 0;
23217
+ if (named.length > 1) {
23218
+ throw usageError(
23219
+ `Give one target, not ${named.length}: ${named.join(", ")}.`
23220
+ );
23221
+ }
23222
+ if (typeof options.ref === "string" && options.ref)
23223
+ return { ref: options.ref };
23224
+ if (typeof options.selector === "string" && options.selector) {
23225
+ return { selector: options.selector };
23226
+ }
23227
+ const x = Number(options.x);
23228
+ const y = Number(options.y);
23229
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
23230
+ throw usageError("--x and --y must both be numbers.");
23231
+ }
23232
+ return { coordinates: [x, y] };
23233
+ }
23234
+ async function emit(result, context) {
23235
+ let extra = {};
23236
+ if (context.saveScreenshots || context.inline) {
23237
+ const page = result.page ?? result.refusal?.page;
23238
+ const shot = await fetchScreenshot(
23239
+ context.options,
23240
+ context.projectId,
23241
+ context.sessionId,
23242
+ page,
23243
+ context.outDir,
23244
+ context.inline === true,
23245
+ context.timeoutMs
23246
+ ).catch((error) => ({
23247
+ kind: "failed",
23248
+ detail: error instanceof Error ? error.message : String(error)
23249
+ }));
23250
+ if (shot.kind === "file") extra = { screenshotPath: shot.path };
23251
+ else if (shot.kind === "inline") {
23252
+ extra = { screenshot: shot.base64, screenshotMediaType: shot.mediaType };
23253
+ } else if (shot.kind === "failed") {
23254
+ extra = { screenshotError: shot.detail };
23255
+ }
23256
+ }
23257
+ const envelope = envelopeFor(result);
23258
+ writeResult({ ...envelope, ...extra }, context.format);
23259
+ if (envelope.success !== true) setProcessExitCode(1);
23260
+ }
23261
+ function envelopeFor(result) {
23262
+ return {
23263
+ ...result,
23264
+ success: result.status === "executed" && result.ok !== false
23265
+ };
23266
+ }
21515
23267
 
21516
23268
  // src/lib/registry-render.ts
21517
23269
  function line(label, value) {
@@ -21794,6 +23546,7 @@ async function main(argv = process.argv, dependencies = {}) {
21794
23546
  registerRegistryCommands(program);
21795
23547
  program.commandsGroup("CLI:");
21796
23548
  registerInspectorCommands(program);
23549
+ registerBrowserCommands(program);
21797
23550
  registerMcpCommands(program);
21798
23551
  registerTelemetryCommands(program, dependencies.telemetry);
21799
23552
  if (argv.length <= 2) {