@mcpjam/cli 3.22.0 → 3.24.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,14 +2,14 @@
2
2
  import { Command, CommanderError } from 'commander';
3
3
  import { realpathSync, mkdirSync, writeFileSync, readFileSync, existsSync, statSync, closeSync, renameSync, openSync } from 'fs';
4
4
  import { pathToFileURL } from 'url';
5
- import { probeMcpServer, redactForTelemetry, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, classifyMcpHeader, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, SubscriptionCoordinator, listTools, listPrompts, getPrompt, MCPAppsConformanceTest, scoreFromAppsResult, MCPAppsConformanceSuite, MCPTasksConformanceTest, scoreFromTasksResult, runOAuthLogin, OAuthConformanceTest, scoreFromOAuthResult, OAuthConformanceSuite, runXaaFlow, MCPConformanceTest, scoreFromProtocolResult, MCPConformanceSuite, openUrlInBrowser, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunJson, DEFAULT_SUBSCRIPTION_RECONNECT_POLICY, isKnownProtocolVersion, describeConformanceScore, toConformanceReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, normalizeRegistrationStrategy, normalizeXaaClientAuth, normalizeIdentityAssertionFormat, IDENTITY_ASSERTION_FORMATS, XAA_CONFIDENTIAL_CIMD_ORIGIN, getLocalConfidentialCimdProvider, MCP_PROTOCOL_VERSIONS, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, MCPClientManager, decodeMcpHeaderValue, canDeclareTasksExtension, createStrictElicitationContentValidator, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, MCP_TASKS_CHECK_CATEGORIES, MCP_TASKS_CHECK_IDS, OAuthProxyError, isLoopbackHost, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, isUnknownTaskError, isMCPTasksWireError, LEGACY_TASK_STATUSES } from '@mcpjam/sdk';
6
- import { mkdir, writeFile, readFile, chmod, rename, rm } from 'fs/promises';
5
+ import { probeMcpServer, redactForTelemetry, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, classifyMcpHeader, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, SubscriptionCoordinator, listTools, listPrompts, getPrompt, MCPAppsConformanceTest, scoreFromAppsResult, MCPAppsConformanceSuite, MCPTasksConformanceTest, scoreFromTasksResult, runOAuthLogin, OAuthConformanceTest, scoreFromOAuthResult, OAuthConformanceSuite, runXaaFlow, MCPConformanceTest, scoreFromProtocolResult, MCPConformanceSuite, openUrlInBrowser, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunJson, DEFAULT_SUBSCRIPTION_RECONNECT_POLICY, isKnownProtocolVersion, describeConformanceScore, toConformanceReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, normalizeRegistrationStrategy, normalizeXaaClientAuth, normalizeIdentityAssertionFormat, IDENTITY_ASSERTION_FORMATS, XAA_CONFIDENTIAL_CIMD_ORIGIN, getLocalConfidentialCimdProvider, MCP_PROTOCOL_VERSIONS, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, formatGateReport, detectFlakyCases, evaluateCompareGates, buildRunCompareReport, buildCorpus, HostedOnlyCaseError, verifyCorpusLock, MCPClientManager, decodeMcpHeaderValue, canDeclareTasksExtension, createStrictElicitationContentValidator, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, MCP_TASKS_CHECK_CATEGORIES, MCP_TASKS_CHECK_IDS, OAuthProxyError, isLoopbackHost, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS, evaluateGates, gateInputFromPlatformRun, calculateLatencyStats, CORPUS_LOCK_VERSION, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, passRateFractionFromPercent, isUnknownTaskError, isMCPTasksWireError, LEGACY_TASK_STATUSES } from '@mcpjam/sdk';
6
+ import { mkdir, writeFile, readFile, chmod, rename, rm, open, unlink } from 'fs/promises';
7
7
  import path2, { dirname, join, basename } from 'path';
8
- import { randomUUID } from 'crypto';
8
+ import { randomUUID, randomBytes } from 'crypto';
9
9
  import { spawn } from 'child_process';
10
10
  import { createRequire } from 'module';
11
11
  import os, { homedir } from 'os';
12
- import { createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, listEvalSuiteRunsOperation, cancelEvalRunOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, runEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, listChatboxesOperation, getChatboxOperation, listChatSessionsOperation, createHostOperation, updateHostOperation, setHostServersOperation, duplicateHostOperation, createEnvironmentOperation, updateEnvironmentOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, createTunnelOperation, DEFAULT_PLATFORM_API_BASE_URL, PlatformApiClient, isPlatformApiError, PlatformApiError, listOrganizationsOperation, listProjectsOperation, listProjectServersOperation, createProjectServerOperation, getProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, createEvalSuiteOperation, listEvalSuitesOperation, runEvalSuiteOperation, getEvalRunOperation, listHostsOperation, getHostOperation, deleteHostOperation, listEnvironmentsOperation, getEnvironmentOperation, resolveEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listJourneysOperation, listJourneyRunsOperation, getJourneyRunOperation, launchJourneyRunOperation, cancelJourneyRunOperation, listJourneyRunSessionsOperation, publishScenarioOperation, unpublishScenarioOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation } from '@mcpjam/sdk/platform';
12
+ import { createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, listEvalSuiteRunsOperation, cancelEvalRunOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, runEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, listChatSessionsOperation, createHostOperation, updateHostOperation, setHostServersOperation, duplicateHostOperation, createEnvironmentOperation, updateEnvironmentOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, createTunnelOperation, DEFAULT_PLATFORM_API_BASE_URL, PlatformApiClient, isPlatformApiError, PlatformApiError, listOrganizationsOperation, listProjectsOperation, listProjectServersOperation, createProjectServerOperation, getProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, createEvalSuiteOperation, listEvalSuitesOperation, runEvalSuiteOperation, getEvalRunOperation, resolveProject, listHostsOperation, getHostOperation, deleteHostOperation, listEnvironmentsOperation, getEnvironmentOperation, resolveEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listJourneysOperation, listJourneyRunsOperation, getJourneyRunOperation, launchJourneyRunOperation, cancelJourneyRunOperation, listJourneyRunSessionsOperation, listScenariosOperation, getScenarioOperation, publishScenarioOperation, unpublishScenarioOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, getCapabilitiesOperation, 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, searchSessionsOperation } from '@mcpjam/sdk/platform';
13
13
  import { buildHostProfilesFromCatalog, buildMarketHostProfiles, scanWidgetUsage, evaluateMarketHosts, fetchHostCompatCatalog } from '@mcpjam/sdk/host-compat';
14
14
  import { HOST_TEMPLATES as HOST_TEMPLATES$1, HOST_TEMPLATE_IDS, seedHostTemplate } from '@mcpjam/sdk/host-config/templates';
15
15
  import { applyVisibilityPolicyAndCountSignals, isAppOnlyTool, extractHostExecutionPolicy, hostConnectionProfile } from '@mcpjam/sdk/host-config/internal';
@@ -25,7 +25,7 @@ import { WebSocket } from 'ws';
25
25
 
26
26
  // package.json
27
27
  var package_default = {
28
- version: "3.22.0"};
28
+ version: "3.24.0"};
29
29
  function conformanceExitCode(result) {
30
30
  if (result.outcome === "incomplete") return 3;
31
31
  if (result.outcome === "failed") return 1;
@@ -453,6 +453,8 @@ function renderConformanceReporterResult(result, reporter) {
453
453
  function renderConformanceForCli(result, reporter, format) {
454
454
  return reporter ? renderConformanceReporterResult(result, reporter) : renderConformanceResult(result, format);
455
455
  }
456
+
457
+ // src/lib/reporting.ts
456
458
  function parseReporterFormat(value) {
457
459
  if (value === void 0) {
458
460
  return void 0;
@@ -477,7 +479,7 @@ async function writeJsonArtifact(outputPath, payload) {
477
479
  await mkdir(path2.dirname(resolvedPath), { recursive: true });
478
480
  await writeFile(
479
481
  resolvedPath,
480
- `${JSON.stringify(payload, null, 2)}
482
+ `${JSON.stringify(redactForTelemetry(payload), null, 2)}
481
483
  `,
482
484
  "utf8"
483
485
  );
@@ -760,7 +762,7 @@ function isAccessTokenUsable(contents, now) {
760
762
  }
761
763
  return Date.parse(contents.expiresAt) - now.getTime() > ACCESS_TOKEN_EXPIRY_SKEW_MS;
762
764
  }
763
- var readTextFile = (path6, encoding) => readFileSync(path6, encoding);
765
+ var readTextFile = (path7, encoding) => readFileSync(path7, encoding);
764
766
  var JsonInputContext = class {
765
767
  constructor(readFile2 = readTextFile) {
766
768
  this.readFile = readFile2;
@@ -1578,7 +1580,7 @@ var InspectorApiClient = class {
1578
1580
  }
1579
1581
  throw operationalError("Inspector command response was invalid.", payload);
1580
1582
  }
1581
- async request(path6, init = {}) {
1583
+ async request(path7, init = {}) {
1582
1584
  const fetchRequest = async () => {
1583
1585
  const token = await fetchInspectorSessionToken(this.baseUrl);
1584
1586
  const { body: initBody, timeoutMs, ...fetchInit } = init;
@@ -1589,7 +1591,7 @@ var InspectorApiClient = class {
1589
1591
  headers.set("Content-Type", "application/json");
1590
1592
  body = JSON.stringify(initBody);
1591
1593
  }
1592
- return await fetch(`${this.baseUrl}${path6}`, {
1594
+ return await fetch(`${this.baseUrl}${path7}`, {
1593
1595
  ...fetchInit,
1594
1596
  signal: fetchInit.signal ?? AbortSignal.timeout(timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS),
1595
1597
  headers,
@@ -1612,7 +1614,7 @@ var InspectorApiClient = class {
1612
1614
  const payload = await readResponsePayload(response);
1613
1615
  if (!response.ok) {
1614
1616
  throw operationalError(
1615
- getErrorMessage(payload) ?? `Inspector request ${path6} failed with ${response.status}.`,
1617
+ getErrorMessage(payload) ?? `Inspector request ${path7} failed with ${response.status}.`,
1616
1618
  payload
1617
1619
  );
1618
1620
  }
@@ -4553,34 +4555,6 @@ async function executeOp(op, input, options, command) {
4553
4555
  writeResult(result, globalOptions.format);
4554
4556
  }
4555
4557
  function registerChatCommands(program) {
4556
- const chatboxes = program.command("chatboxes").description("Inspect the chatboxes published from a hosted project");
4557
- addPlatformOptions2(
4558
- chatboxes.command("list").description("List the chatboxes published from a project").option(
4559
- "--project <id-or-name>",
4560
- "Project name or ID (defaults to the most recently updated project)"
4561
- )
4562
- ).action(async (options, command) => {
4563
- const input = validateOpInput(listChatboxesOperation, {
4564
- ...options.project === void 0 ? {} : { project: options.project }
4565
- });
4566
- await executeOp(listChatboxesOperation, input, options, command);
4567
- });
4568
- addPlatformOptions2(
4569
- chatboxes.command("get").description(
4570
- "Show one chatbox: access mode, attached servers, share link"
4571
- ).requiredOption("--chatbox <id-or-name>", "Chatbox name or ID").option(
4572
- "--project <id-or-name>",
4573
- "Project name or ID (defaults to the most recently updated project)"
4574
- )
4575
- ).action(
4576
- async (options, command) => {
4577
- const input = validateOpInput(getChatboxOperation, {
4578
- chatbox: options.chatbox,
4579
- ...options.project === void 0 ? {} : { project: options.project }
4580
- });
4581
- await executeOp(getChatboxOperation, input, options, command);
4582
- }
4583
- );
4584
4558
  const sessions = program.command("chat-sessions").description("Inspect saved chat sessions");
4585
4559
  addPlatformOptions2(
4586
4560
  sessions.command("list").description(
@@ -5105,6 +5079,7 @@ function registerJourneysCommands(program) {
5105
5079
  writeResult(result, globalOptions.format);
5106
5080
  }
5107
5081
  );
5082
+ return journeys;
5108
5083
  }
5109
5084
  function addPlatformOptions5(command) {
5110
5085
  return command.option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
@@ -5142,21 +5117,86 @@ function registerScenariosCommands(program) {
5142
5117
  const scenarios = program.command("scenarios").description(
5143
5118
  "Publish project environments for user testing, and take them down again"
5144
5119
  );
5120
+ const SCENARIO_MODES = [
5121
+ "project_members",
5122
+ "invited_only",
5123
+ "anyone_with_link"
5124
+ ];
5125
+ addPlatformOptions5(
5126
+ scenarios.command("list").description("List the scenarios published from a project").option(
5127
+ "--project <id-or-name>",
5128
+ "Project name or ID (defaults to the most recently updated project)"
5129
+ )
5130
+ ).action(async (options, command) => {
5131
+ const globalOptions = getGlobalOptions(command);
5132
+ const result = await runPlatformCommand5(
5133
+ options,
5134
+ globalOptions.timeout,
5135
+ ({ client, signal }) => listScenariosOperation.execute(
5136
+ {
5137
+ ...options.project === void 0 ? {} : { project: options.project }
5138
+ },
5139
+ { client, signal }
5140
+ )
5141
+ );
5142
+ writeResult(result, globalOptions.format);
5143
+ });
5144
+ addPlatformOptions5(
5145
+ scenarios.command("get").description(
5146
+ "Show one scenario: access mode, attached servers, share link"
5147
+ ).requiredOption("--scenario <id-or-name>", "Scenario name or ID").option(
5148
+ "--project <id-or-name>",
5149
+ "Project name or ID (defaults to the most recently updated project)"
5150
+ )
5151
+ ).action(
5152
+ async (options, command) => {
5153
+ const globalOptions = getGlobalOptions(command);
5154
+ const result = await runPlatformCommand5(
5155
+ options,
5156
+ globalOptions.timeout,
5157
+ ({ client, signal }) => getScenarioOperation.execute(
5158
+ {
5159
+ scenario: options.scenario,
5160
+ ...options.project === void 0 ? {} : { project: options.project }
5161
+ },
5162
+ { client, signal }
5163
+ )
5164
+ );
5165
+ writeResult(result, globalOptions.format);
5166
+ }
5167
+ );
5145
5168
  addPlatformOptions5(
5146
5169
  scenarios.command("publish").description(
5147
- "Publish an environment as a scenario and print its share link. Idempotent \u2014 re-publishing returns the existing scenario, with created: false."
5170
+ "Publish an environment as a scenario and print its share link. Idempotent \u2014 re-publishing returns the existing scenario, with created: false. --name, --description and --mode apply at CREATE TIME, in the same call; on a re-publish they are ignored and the result says overridesIgnored: true (use `mcpjam user-testing update` to change an existing scenario)."
5148
5171
  ).requiredOption("--environment <id>", "Project environment ID").option(
5149
5172
  "--project <id-or-name>",
5150
5173
  "Project name or ID (defaults to the most recently updated project)"
5174
+ ).option("--name <name>", "Scenario name (create time only)").option("--description <text>", "Scenario description (create time only)").option(
5175
+ "--mode <mode>",
5176
+ "Who may open the share link (create time only): project_members | invited_only | anyone_with_link"
5151
5177
  )
5152
5178
  ).action(
5153
5179
  async (options, command) => {
5154
5180
  const globalOptions = getGlobalOptions(command);
5181
+ const mode = options.mode;
5182
+ if (mode !== void 0 && !SCENARIO_MODES.includes(mode)) {
5183
+ command.error(
5184
+ `error: option '--mode <mode>' must be one of ${SCENARIO_MODES.join(
5185
+ ", "
5186
+ )}`
5187
+ );
5188
+ }
5155
5189
  const result = await runPlatformCommand5(
5156
5190
  options,
5157
5191
  globalOptions.timeout,
5158
5192
  ({ client, signal }) => publishScenarioOperation.execute(
5159
- { project: options.project, environment: options.environment },
5193
+ {
5194
+ project: options.project,
5195
+ environment: options.environment,
5196
+ ...options.name !== void 0 ? { name: options.name } : {},
5197
+ ...options.description !== void 0 ? { description: options.description } : {},
5198
+ ...mode !== void 0 ? { mode } : {}
5199
+ },
5160
5200
  { client, signal }
5161
5201
  )
5162
5202
  );
@@ -5182,136 +5222,12 @@ function registerScenariosCommands(program) {
5182
5222
  }
5183
5223
  );
5184
5224
  }
5185
-
5186
- // src/lib/eval-screenshots.ts
5187
- function asRecord(value) {
5188
- return typeof value === "object" && value !== null ? value : null;
5189
- }
5190
- function asString(value) {
5191
- return typeof value === "string" ? value : void 0;
5192
- }
5193
- function extractRenderedScreenshots(result) {
5194
- const root = asRecord(result);
5195
- if (!root) return [];
5196
- const trace = asRecord(root.trace) ?? root;
5197
- const screenshots = [];
5198
- const observations = trace.widgetRenderObservations;
5199
- if (Array.isArray(observations)) {
5200
- for (const entry of observations) {
5201
- const obs = asRecord(entry);
5202
- if (!obs) continue;
5203
- const status = asString(obs.status);
5204
- const screenshotUrl = asString(obs.screenshotUrl);
5205
- if (status !== "rendered" || !screenshotUrl) continue;
5206
- screenshots.push({
5207
- status,
5208
- screenshotUrl,
5209
- toolName: asString(obs.toolName),
5210
- toolCallId: asString(obs.toolCallId),
5211
- promptIndex: typeof obs.promptIndex === "number" ? obs.promptIndex : void 0
5212
- });
5213
- }
5214
- }
5215
- const interactions = trace.browserInteractionSteps;
5216
- if (Array.isArray(interactions)) {
5217
- for (const entry of interactions) {
5218
- const step = asRecord(entry);
5219
- if (!step) continue;
5220
- const screenshotUrl = asString(step.screenshotUrl);
5221
- if (!screenshotUrl) continue;
5222
- const assertion = asRecord(step.assertion);
5223
- const status = assertion ? assertion.passed === true ? "assert:passed" : "assert:failed" : asString(step.action) ?? "interaction";
5224
- const label = asString(step.locatorLabel) ?? asString(step.action) ?? "interaction";
5225
- screenshots.push({
5226
- status,
5227
- screenshotUrl,
5228
- toolName: label,
5229
- toolCallId: asString(step.toolCallId),
5230
- promptIndex: typeof step.promptIndex === "number" ? step.promptIndex : void 0
5231
- });
5232
- }
5233
- }
5234
- return screenshots;
5235
- }
5236
- function extractIterationVideoUrl(result) {
5237
- const root = asRecord(result);
5238
- if (!root) return void 0;
5239
- const trace = asRecord(root.trace) ?? root;
5240
- return asString(trace.videoUrl);
5241
- }
5242
- function screenshotFilename(shot, index) {
5243
- const tool = (shot.toolName ?? "widget").replace(/[^a-zA-Z0-9_-]+/g, "-");
5244
- const suffix = shot.toolCallId ? shot.toolCallId.replace(/[^a-zA-Z0-9_-]+/g, "-") : String(index + 1);
5245
- return `${tool}-${suffix}.png`;
5246
- }
5247
-
5248
- // src/lib/terminal-image.ts
5249
- var ESC = "\x1B";
5250
- var BEL = "\x07";
5251
- function detectInlineImageProtocol(env = process.env, isTTY = process.stdout.isTTY) {
5252
- if (!isTTY) return null;
5253
- const termProgram = env.TERM_PROGRAM ?? "";
5254
- const term = env.TERM ?? "";
5255
- if (term === "xterm-kitty" || env.KITTY_WINDOW_ID !== void 0 || termProgram === "ghostty" || env.GHOSTTY_RESOURCES_DIR !== void 0) {
5256
- return "kitty";
5257
- }
5258
- if (termProgram === "iTerm.app" || termProgram === "WezTerm" || termProgram === "WarpTerminal" || env.LC_TERMINAL === "iTerm2") {
5259
- return "iterm";
5260
- }
5261
- return null;
5262
- }
5263
- function toBase64(data) {
5264
- return Buffer.from(data).toString("base64");
5265
- }
5266
- function encodeIterm(data) {
5267
- const payload = toBase64(data);
5268
- const args = ["inline=1", `size=${data.byteLength}`, "preserveAspectRatio=1"].join(
5269
- ";"
5270
- );
5271
- return `${ESC}]1337;File=${args}:${payload}${BEL}
5272
- `;
5273
- }
5274
- function encodeKitty(data) {
5275
- const payload = toBase64(data);
5276
- const CHUNK = 4096;
5277
- const chunks = [];
5278
- for (let offset = 0; offset < payload.length; offset += CHUNK) {
5279
- chunks.push(payload.slice(offset, offset + CHUNK));
5280
- }
5281
- if (chunks.length === 0) chunks.push("");
5282
- let out = "";
5283
- chunks.forEach((chunk, index) => {
5284
- const more = index < chunks.length - 1 ? 1 : 0;
5285
- const control = index === 0 ? `a=T,f=100,m=${more}` : `m=${more}`;
5286
- out += `${ESC}_G${control};${chunk}${ESC}\\`;
5287
- });
5288
- return `${out}
5289
- `;
5290
- }
5291
- function encodeInlineImage(data, protocol) {
5292
- return protocol === "kitty" ? encodeKitty(data) : encodeIterm(data);
5293
- }
5294
-
5295
- // src/commands/eval.ts
5296
5225
  function addPlatformOptions6(command) {
5297
5226
  return command.option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
5298
5227
  "--api-url <url>",
5299
5228
  "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
5300
5229
  );
5301
5230
  }
5302
- function writeRunLink(format, webOrigin, run) {
5303
- if (format !== "human") return;
5304
- const suiteId = run.suiteId?.trim();
5305
- const runId = run.runId?.trim();
5306
- if (!suiteId || !runId) return;
5307
- const query = run.projectId?.trim() ? `?project=${encodeURIComponent(run.projectId.trim())}` : "";
5308
- process.stdout.write(
5309
- `View: ${webOrigin}/evals/suite/${encodeURIComponent(
5310
- suiteId
5311
- )}/runs/${encodeURIComponent(runId)}${query}
5312
- `
5313
- );
5314
- }
5315
5231
  async function runPlatformCommand6(options, timeoutMs, execute) {
5316
5232
  const controller = new AbortController();
5317
5233
  const timeoutHandle = setTimeout(() => {
@@ -5327,12 +5243,8 @@ async function runPlatformCommand6(options, timeoutMs, execute) {
5327
5243
  }, timeoutMs);
5328
5244
  timeoutHandle.unref?.();
5329
5245
  try {
5330
- const { client, baseUrl } = buildPlatformClient({ ...options, timeoutMs });
5331
- return await execute({
5332
- client,
5333
- signal: controller.signal,
5334
- webOrigin: webOriginForApiBaseUrl(baseUrl)
5335
- });
5246
+ const { client } = buildPlatformClient({ ...options, timeoutMs });
5247
+ return await execute({ client, signal: controller.signal });
5336
5248
  } catch (error) {
5337
5249
  if (controller.signal.aborted && controller.signal.reason instanceof PlatformApiError) {
5338
5250
  throw toCliError(controller.signal.reason);
@@ -5342,62 +5254,1488 @@ async function runPlatformCommand6(options, timeoutMs, execute) {
5342
5254
  clearTimeout(timeoutHandle);
5343
5255
  }
5344
5256
  }
5345
- function readFileOrStdin(value, label) {
5346
- try {
5347
- return value === "-" ? readFileSync(0, "utf8") : readFileSync(value, "utf8");
5348
- } catch (error) {
5349
- throw usageError(`Failed to read ${label} "${value}".`, {
5350
- source: error instanceof Error ? error.message : String(error)
5351
- });
5352
- }
5353
- }
5354
- function loadSuiteDefinition(options) {
5355
- if (options.file !== void 0 && options.json !== void 0) {
5356
- throw usageError("Provide either --file or --json, not both.");
5357
- }
5358
- let base = {};
5359
- if (options.file !== void 0) {
5360
- const text = readFileOrStdin(options.file, "--file");
5361
- if (text.trim() === "") {
5362
- throw usageError("--file input is empty.");
5363
- }
5364
- try {
5365
- base = JSON.parse(text);
5366
- } catch (error) {
5367
- throw usageError("--file must contain valid JSON.", {
5368
- source: error instanceof Error ? error.message : String(error)
5369
- });
5257
+ function bindOperation(command, operation, buildInput) {
5258
+ addPlatformOptions6(command).action(
5259
+ async (options, invoked) => {
5260
+ const globalOptions = getGlobalOptions(invoked);
5261
+ const result = await runPlatformCommand6(
5262
+ options,
5263
+ globalOptions.timeout,
5264
+ ({ client, signal }) => operation.execute(buildInput(options), { client, signal })
5265
+ );
5266
+ writeResult(result, globalOptions.format);
5370
5267
  }
5371
- } else if (options.json !== void 0) {
5372
- base = new JsonInputContext().parseJsonInputRecord(options.json, "--json");
5373
- }
5374
- if (base === void 0 || base === null) {
5375
- base = {};
5268
+ );
5269
+ }
5270
+ function addProjectOption(command) {
5271
+ return command.option(
5272
+ "--project <id-or-name>",
5273
+ "Project name or ID (defaults to the most recently updated project)"
5274
+ );
5275
+ }
5276
+ function parseIntegerOption(value, flag, bounds) {
5277
+ if (value === void 0) return void 0;
5278
+ const trimmed = value.trim();
5279
+ const parsed = trimmed === "" ? Number.NaN : Number(trimmed);
5280
+ if (!Number.isInteger(parsed)) {
5281
+ throw usageError(`${flag} must be a whole number`);
5376
5282
  }
5377
- if (typeof base !== "object" || Array.isArray(base)) {
5378
- throw usageError("Suite definition must be a JSON object.");
5283
+ if (bounds?.min !== void 0 && parsed < bounds.min) {
5284
+ throw usageError(`${flag} must be at least ${bounds.min}`);
5379
5285
  }
5380
- const merged = {
5381
- ...base,
5382
- ...options.project !== void 0 ? { project: options.project } : {},
5383
- ...options.name !== void 0 ? { name: options.name } : {},
5384
- ...options.model !== void 0 ? { model: options.model } : {},
5385
- ...options.provider !== void 0 ? { provider: options.provider } : {},
5386
- ...options.server !== void 0 ? { servers: options.server } : {}
5387
- };
5388
- const parsed = createEvalSuiteOperation.inputSchema.safeParse(merged);
5389
- if (!parsed.success) {
5390
- const detail = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ");
5391
- throw usageError(`Invalid suite definition: ${detail}`);
5286
+ if (bounds?.max !== void 0 && parsed > bounds.max) {
5287
+ throw usageError(`${flag} must be at most ${bounds.max}`);
5392
5288
  }
5393
- return parsed.data;
5289
+ return parsed;
5394
5290
  }
5395
- function loadBodyObject(options) {
5396
- if (options.file !== void 0 && options.json !== void 0) {
5397
- throw usageError("Provide either --file or --json, not both.");
5398
- }
5399
- let base = {};
5400
- if (options.file !== void 0) {
5291
+ function parseRequiredIntegerOption(value, flag, bounds) {
5292
+ return parseIntegerOption(value, flag, bounds);
5293
+ }
5294
+ function requireExactlyOne(flags) {
5295
+ const supplied = Object.entries(flags).filter(
5296
+ ([, value]) => value !== void 0 && value !== ""
5297
+ );
5298
+ if (supplied.length === 1) return;
5299
+ const names = Object.keys(flags).join(" or ");
5300
+ throw usageError(
5301
+ supplied.length === 0 ? `Provide ${names}.` : `Provide only one of ${names}.`
5302
+ );
5303
+ }
5304
+ function requireTogether(first, second) {
5305
+ if (first.value === void 0 === (second.value === void 0)) return;
5306
+ throw usageError(
5307
+ `${first.flag} and ${second.flag} must be given together \u2014 they are one execution config upstream.`
5308
+ );
5309
+ }
5310
+
5311
+ // src/commands/swarms.ts
5312
+ var SESSIONS_BOUNDS = { min: 1, max: 100 };
5313
+ var TURNS_BOUNDS = { min: 1, max: 200 };
5314
+ var JOURNEY_COUNT_BOUNDS = { min: 1, max: 5 };
5315
+ var PERSONA_COUNT_BOUNDS = { min: 1, max: 12 };
5316
+ function groundingArgs(options) {
5317
+ requireExactlyOne({
5318
+ "--environment": options.environment,
5319
+ "--server-attachment": options.serverAttachment
5320
+ });
5321
+ const journeyCount = parseIntegerOption(
5322
+ options.journeyCount,
5323
+ "--journey-count",
5324
+ JOURNEY_COUNT_BOUNDS
5325
+ );
5326
+ return {
5327
+ ...options.environment ? { environmentId: options.environment } : {},
5328
+ ...options.serverAttachment ? { serverAttachmentId: options.serverAttachment } : {},
5329
+ ...options.description ? { description: options.description } : {},
5330
+ ...journeyCount !== void 0 ? { journeyCount } : {}
5331
+ };
5332
+ }
5333
+ function addConfigOptions(command, required) {
5334
+ const sessions = "--sessions-per-target <n>";
5335
+ const turns = "--max-turns <n>";
5336
+ const sessionsHelp = "Sessions run against EACH target. Total sessions = targets x this, and the total is what spends.";
5337
+ const turnsHelp = "Cap on assistant turns per session.";
5338
+ return required ? command.requiredOption(sessions, sessionsHelp).requiredOption(turns, turnsHelp) : command.option(sessions, sessionsHelp).option(turns, turnsHelp);
5339
+ }
5340
+ function addGroundingOptions(command) {
5341
+ return command.option(
5342
+ "--environment <id>",
5343
+ "Ground the drafts in this project environment. Use this one normally."
5344
+ ).option(
5345
+ "--server-attachment <id>",
5346
+ "Legacy grounding source. Prefer --environment."
5347
+ ).option("--description <text>", "Who the audience is, in your own words.").option("--journey-count <n>", "How many journeys to draft per persona.");
5348
+ }
5349
+ function registerSwarmAuthoringCommands(program, journeys) {
5350
+ bindOperation(
5351
+ addProjectOption(
5352
+ program.command("capabilities").description(
5353
+ "Show what you may do in a project: your role, which betas the organization has, your plan's limits, and a can-block of booleans. Ask this before scripting anything that authors, launches or publishes."
5354
+ )
5355
+ ),
5356
+ getCapabilitiesOperation,
5357
+ (options) => ({ project: options.project })
5358
+ );
5359
+ const personas = program.command("personas").description(
5360
+ "The reusable synthetic characters Swarms journeys run as. A persona carries a name, a role and behavioural notes; the goal lives on each journey."
5361
+ );
5362
+ bindOperation(
5363
+ addProjectOption(
5364
+ personas.command("list").description("List the project's personas.")
5365
+ ),
5366
+ listPersonasOperation,
5367
+ (options) => ({ project: options.project })
5368
+ );
5369
+ bindOperation(
5370
+ addProjectOption(
5371
+ personas.command("get").description("Show one persona in full, including its notes.").requiredOption("--persona <id>", "Persona ID")
5372
+ ),
5373
+ getPersonaOperation,
5374
+ (options) => ({
5375
+ project: options.project,
5376
+ persona: options.persona
5377
+ })
5378
+ );
5379
+ bindOperation(
5380
+ addProjectOption(
5381
+ personas.command("create").description(
5382
+ "Create a persona. Pass --idempotency-key when scripting: the server replays it BEFORE uniquifying the slug, so a retry without one leaves a second near-identical persona rather than the one you already made."
5383
+ ).requiredOption("--name <name>", "Display name").requiredOption(
5384
+ "--role <role>",
5385
+ "Who they are, in a few words \u2014 'enterprise procurement lead'"
5386
+ ).option(
5387
+ "--notes <text>",
5388
+ "How they behave: what they know, what they will not tolerate, how they phrase things"
5389
+ ).option("--idempotency-key <key>", "Retry key")
5390
+ ),
5391
+ createPersonaOperation,
5392
+ (options) => ({
5393
+ project: options.project,
5394
+ name: options.name,
5395
+ role: options.role,
5396
+ ...options.notes !== void 0 ? { notes: options.notes } : {},
5397
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
5398
+ })
5399
+ );
5400
+ bindOperation(
5401
+ addProjectOption(
5402
+ personas.command("update").description(
5403
+ "Edit a persona. Finished runs keep the persona they ran as \u2014 editing does not rewrite history."
5404
+ ).requiredOption("--persona <id>", "Persona ID").option("--name <name>").option("--role <role>").option("--notes <text>")
5405
+ ),
5406
+ updatePersonaOperation,
5407
+ (options) => ({
5408
+ project: options.project,
5409
+ persona: options.persona,
5410
+ ...options.name !== void 0 ? { name: options.name } : {},
5411
+ ...options.role !== void 0 ? { role: options.role } : {},
5412
+ ...options.notes !== void 0 ? { notes: options.notes } : {}
5413
+ })
5414
+ );
5415
+ bindOperation(
5416
+ addProjectOption(
5417
+ personas.command("delete").description(
5418
+ "Take a persona off the roster. SOFT: finished runs and sessions keep resolving it, so history stays readable, but it cannot be used for new journeys and a second delete answers not-found."
5419
+ ).requiredOption("--persona <id>", "Persona ID")
5420
+ ),
5421
+ deletePersonaOperation,
5422
+ (options) => ({
5423
+ project: options.project,
5424
+ persona: options.persona
5425
+ })
5426
+ );
5427
+ bindOperation(
5428
+ addGroundingOptions(
5429
+ addProjectOption(
5430
+ personas.command("generate").description(
5431
+ "Draft candidate personas with a model, grounded in what the project's servers do. SAVES NOTHING \u2014 pipe what you want into `personas create`. Spends."
5432
+ ).option("--persona-count <n>", "Draft a slate of N personas.")
5433
+ )
5434
+ ),
5435
+ generatePersonasOperation,
5436
+ (options) => {
5437
+ const personaCount = parseIntegerOption(
5438
+ options.personaCount,
5439
+ "--persona-count",
5440
+ PERSONA_COUNT_BOUNDS
5441
+ );
5442
+ return {
5443
+ project: options.project,
5444
+ ...groundingArgs(options),
5445
+ ...personaCount !== void 0 ? { personaCount } : {}
5446
+ };
5447
+ }
5448
+ );
5449
+ bindOperation(
5450
+ addProjectOption(
5451
+ journeys.command("get").description(
5452
+ "Show one journey in full. Read this before launching if you want to know what a run will cost: it produces targets x sessionsPerTarget conversations."
5453
+ ).requiredOption("--journey <id>", "Journey ID")
5454
+ ),
5455
+ getJourneyOperation,
5456
+ (options) => ({
5457
+ project: options.project,
5458
+ journey: options.journey
5459
+ })
5460
+ );
5461
+ bindOperation(
5462
+ addConfigOptions(
5463
+ addProjectOption(
5464
+ journeys.command("create").description(
5465
+ "Author a journey: a persona, a goal, and the environments to pursue it against. Creating does NOT run it \u2014 `journeys run` does, and that is the call that spends."
5466
+ ).requiredOption(
5467
+ "--goal <text>",
5468
+ "What the persona is trying to accomplish"
5469
+ ).requiredOption("--persona <id>", "Persona ID to run as").option("--name <name>").option("--swarm <id>", "Swarm container ID (authoring provenance)").option(
5470
+ "--environment <id>",
5471
+ "Environment to fan out across. Repeatable.",
5472
+ (value, previous = []) => [...previous, value]
5473
+ ).option("--idempotency-key <key>", "Retry key")
5474
+ ),
5475
+ true
5476
+ ),
5477
+ createJourneyOperation,
5478
+ (options) => ({
5479
+ project: options.project,
5480
+ goal: options.goal,
5481
+ persona: options.persona,
5482
+ sessionsPerTarget: parseRequiredIntegerOption(
5483
+ options.sessionsPerTarget,
5484
+ "--sessions-per-target",
5485
+ SESSIONS_BOUNDS
5486
+ ),
5487
+ maxTurns: parseRequiredIntegerOption(
5488
+ options.maxTurns,
5489
+ "--max-turns",
5490
+ TURNS_BOUNDS
5491
+ ),
5492
+ ...options.name !== void 0 ? { name: options.name } : {},
5493
+ ...options.swarm !== void 0 ? { swarm: options.swarm } : {},
5494
+ ...options.environment?.length ? { environmentIds: options.environment } : {},
5495
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
5496
+ })
5497
+ );
5498
+ bindOperation(
5499
+ addConfigOptions(
5500
+ addProjectOption(
5501
+ journeys.command("update").description(
5502
+ "Edit a journey. --sessions-per-target and --max-turns must be given together (they are one config upstream). A run already in flight keeps the config it launched with."
5503
+ ).requiredOption("--journey <id>", "Journey ID").option("--name <name>").option("--goal <text>").option(
5504
+ "--environment <id>",
5505
+ "Replace the fan-out with these. Repeatable.",
5506
+ (value, previous = []) => [...previous, value]
5507
+ ).option(
5508
+ "--clear-environments",
5509
+ "Drop the fan-out and return the journey to its host targets."
5510
+ )
5511
+ ),
5512
+ false
5513
+ ),
5514
+ updateJourneyOperation,
5515
+ (options) => {
5516
+ if (options.clearEnvironments && options.environment?.length) {
5517
+ throw new Error(
5518
+ "--clear-environments and --environment cannot be used together"
5519
+ );
5520
+ }
5521
+ requireTogether(
5522
+ { flag: "--sessions-per-target", value: options.sessionsPerTarget },
5523
+ { flag: "--max-turns", value: options.maxTurns }
5524
+ );
5525
+ return {
5526
+ project: options.project,
5527
+ journey: options.journey,
5528
+ ...options.name !== void 0 ? { name: options.name } : {},
5529
+ ...options.goal !== void 0 ? { goal: options.goal } : {},
5530
+ ...options.clearEnvironments ? { environmentIds: null } : options.environment?.length ? { environmentIds: options.environment } : {},
5531
+ ...options.sessionsPerTarget !== void 0 ? {
5532
+ sessionsPerTarget: parseIntegerOption(
5533
+ options.sessionsPerTarget,
5534
+ "--sessions-per-target",
5535
+ SESSIONS_BOUNDS
5536
+ )
5537
+ } : {},
5538
+ ...options.maxTurns !== void 0 ? {
5539
+ maxTurns: parseIntegerOption(
5540
+ options.maxTurns,
5541
+ "--max-turns",
5542
+ TURNS_BOUNDS
5543
+ )
5544
+ } : {}
5545
+ };
5546
+ }
5547
+ );
5548
+ bindOperation(
5549
+ addProjectOption(
5550
+ journeys.command("archive").description(
5551
+ "Take a journey off the roster. Its runs, sessions and scorecards stay readable \u2014 the evidence for past decisions is not deleted with the journey that produced it."
5552
+ ).requiredOption("--journey <id>", "Journey ID")
5553
+ ),
5554
+ archiveJourneyOperation,
5555
+ (options) => ({
5556
+ project: options.project,
5557
+ journey: options.journey
5558
+ })
5559
+ );
5560
+ bindOperation(
5561
+ addGroundingOptions(
5562
+ addProjectOption(
5563
+ journeys.command("generate").description(
5564
+ "Draft candidate journeys for a persona with a model. The persona is passed BY VALUE and does not have to exist yet, because the create flow drafts both before saving either. SAVES NOTHING; spends."
5565
+ ).requiredOption("--persona-name <name>").requiredOption("--persona-role <role>").option("--persona-notes <text>")
5566
+ )
5567
+ ),
5568
+ generateJourneysOperation,
5569
+ (options) => ({
5570
+ project: options.project,
5571
+ persona: {
5572
+ name: options.personaName,
5573
+ role: options.personaRole,
5574
+ ...options.personaNotes !== void 0 ? { notes: options.personaNotes } : {}
5575
+ },
5576
+ ...groundingArgs(options)
5577
+ })
5578
+ );
5579
+ bindOperation(
5580
+ addProjectOption(
5581
+ journeys.command("overview").description(
5582
+ "The project's recent runs with their rubric findings and goal-completion trend \u2014 the roll-up the Swarms page shows. Rates are over GRADED sessions; passRate null means nothing has been graded, not that everything failed."
5583
+ )
5584
+ ),
5585
+ getSwarmOverviewOperation,
5586
+ (options) => ({ project: options.project })
5587
+ );
5588
+ bindOperation(
5589
+ addProjectOption(
5590
+ journeys.command("scorecard").description(
5591
+ "Per-criterion pass/fail counts for one run. Deterministic \u2014 no model involved \u2014 so this is the first thing to read when explaining a failure. failedGradingCount is grading that BROKE; do not add it to failCount."
5592
+ ).requiredOption("--run <id>", "Journey run ID")
5593
+ ),
5594
+ getJourneyRunScorecardOperation,
5595
+ (options) => ({
5596
+ project: options.project,
5597
+ run: options.run
5598
+ })
5599
+ );
5600
+ bindOperation(
5601
+ addProjectOption(
5602
+ journeys.command("findings").description(
5603
+ "Criteria that keep failing across waves, with how long each has been failing."
5604
+ )
5605
+ ),
5606
+ listSwarmFindingsOperation,
5607
+ (options) => ({ project: options.project })
5608
+ );
5609
+ bindOperation(
5610
+ addProjectOption(
5611
+ journeys.command("dismiss-finding").description(
5612
+ "Mark a finding as not worth acting on. Its lifecycle keeps updating underneath, so undismissing later shows honest current state."
5613
+ ).requiredOption("--finding <id>", "Finding ID")
5614
+ ),
5615
+ dismissSwarmFindingOperation,
5616
+ (options) => ({
5617
+ project: options.project,
5618
+ finding: options.finding
5619
+ })
5620
+ );
5621
+ bindOperation(
5622
+ addProjectOption(
5623
+ journeys.command("undismiss-finding").description("Bring a dismissed finding back into the active list.").requiredOption("--finding <id>", "Finding ID")
5624
+ ),
5625
+ undismissSwarmFindingOperation,
5626
+ (options) => ({
5627
+ project: options.project,
5628
+ finding: options.finding
5629
+ })
5630
+ );
5631
+ bindOperation(
5632
+ addProjectOption(
5633
+ journeys.command("insights").description(
5634
+ "The model's analysis of a whole wave, if one has been requested. Not-found means nobody asked for it, which is different from asked-and-still-working."
5635
+ ).requiredOption("--wave <id>", "Wave ID (the waveId on a run)")
5636
+ ),
5637
+ getWaveInsightsOperation,
5638
+ (options) => ({
5639
+ project: options.project,
5640
+ wave: options.wave
5641
+ })
5642
+ );
5643
+ bindOperation(
5644
+ addProjectOption(
5645
+ journeys.command("request-insights").description(
5646
+ "Ask a model to analyze a whole wave. Returns immediately as pending; poll `journeys insights`. SPENDS against a daily budget shared with user-testing insights. Read the scorecards first \u2014 they are free and usually explain the failure."
5647
+ ).requiredOption("--wave <id>", "Wave ID").option(
5648
+ "--force",
5649
+ "Regenerate over a wave that already has insights. Spends again."
5650
+ )
5651
+ ),
5652
+ requestWaveInsightsOperation,
5653
+ (options) => ({
5654
+ project: options.project,
5655
+ wave: options.wave,
5656
+ ...options.force ? { force: true } : {}
5657
+ })
5658
+ );
5659
+ bindOperation(
5660
+ addProjectOption(
5661
+ journeys.command("cancel-insights").description(
5662
+ "Stop an in-flight insights generation. The recovery path for a wave stuck pending \u2014 without it the only way forward is --force, which spends again."
5663
+ ).requiredOption("--wave <id>", "Wave ID")
5664
+ ),
5665
+ cancelWaveInsightsOperation,
5666
+ (options) => ({
5667
+ project: options.project,
5668
+ wave: options.wave
5669
+ })
5670
+ );
5671
+ const swarms = program.command("swarms").description(
5672
+ "Swarm containers group journeys authored together and hold their shared execution config. A journey does not need one, but a project authored through the app will have them."
5673
+ );
5674
+ bindOperation(
5675
+ addProjectOption(
5676
+ swarms.command("list").description("List the project's swarm containers.")
5677
+ ),
5678
+ listSwarmsOperation,
5679
+ (options) => ({ project: options.project })
5680
+ );
5681
+ bindOperation(
5682
+ addProjectOption(
5683
+ swarms.command("get").description("Show one swarm container.").requiredOption("--swarm <id>", "Swarm container ID")
5684
+ ),
5685
+ getSwarmOperation,
5686
+ (options) => ({
5687
+ project: options.project,
5688
+ swarm: options.swarm
5689
+ })
5690
+ );
5691
+ bindOperation(
5692
+ addConfigOptions(
5693
+ addProjectOption(
5694
+ swarms.command("create").description(
5695
+ "Create a container to author journeys under. Runs nothing."
5696
+ ).requiredOption("--name <name>").option("--description <text>").option(
5697
+ "--environment <id>",
5698
+ "Default fan-out for journeys authored here. Repeatable.",
5699
+ (value, previous = []) => [...previous, value]
5700
+ ).option("--idempotency-key <key>", "Retry key")
5701
+ ),
5702
+ true
5703
+ ),
5704
+ createSwarmOperation,
5705
+ (options) => ({
5706
+ project: options.project,
5707
+ name: options.name,
5708
+ sessionsPerTarget: parseRequiredIntegerOption(
5709
+ options.sessionsPerTarget,
5710
+ "--sessions-per-target",
5711
+ SESSIONS_BOUNDS
5712
+ ),
5713
+ maxTurns: parseRequiredIntegerOption(
5714
+ options.maxTurns,
5715
+ "--max-turns",
5716
+ TURNS_BOUNDS
5717
+ ),
5718
+ ...options.description !== void 0 ? { description: options.description } : {},
5719
+ ...options.environment?.length ? { environmentIds: options.environment } : {},
5720
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
5721
+ })
5722
+ );
5723
+ bindOperation(
5724
+ addConfigOptions(
5725
+ addProjectOption(
5726
+ swarms.command("update").description(
5727
+ "Edit a swarm container. --sessions-per-target and --max-turns must be given together."
5728
+ ).requiredOption("--swarm <id>", "Swarm container ID").option("--name <name>").option("--description <text>").option(
5729
+ "--environment <id>",
5730
+ "Replace the default fan-out. Repeatable.",
5731
+ (value, previous = []) => [...previous, value]
5732
+ )
5733
+ ),
5734
+ false
5735
+ ),
5736
+ updateSwarmOperation,
5737
+ (options) => ({
5738
+ project: options.project,
5739
+ swarm: options.swarm,
5740
+ ...options.name !== void 0 ? { name: options.name } : {},
5741
+ ...options.description !== void 0 ? { description: options.description } : {},
5742
+ ...options.environment?.length ? { environmentIds: options.environment } : {},
5743
+ ...options.sessionsPerTarget !== void 0 ? {
5744
+ sessionsPerTarget: parseIntegerOption(
5745
+ options.sessionsPerTarget,
5746
+ "--sessions-per-target"
5747
+ )
5748
+ } : {},
5749
+ ...options.maxTurns !== void 0 ? { maxTurns: parseIntegerOption(options.maxTurns, "--max-turns") } : {}
5750
+ })
5751
+ );
5752
+ bindOperation(
5753
+ addProjectOption(
5754
+ swarms.command("archive").description(
5755
+ "Take a container off the roster. Journeys authored under it keep working \u2014 the reference is authoring provenance, not ownership."
5756
+ ).requiredOption("--swarm <id>", "Swarm container ID")
5757
+ ),
5758
+ archiveSwarmOperation,
5759
+ (options) => ({
5760
+ project: options.project,
5761
+ swarm: options.swarm
5762
+ })
5763
+ );
5764
+ }
5765
+ function scenarioCommand(group, name, description) {
5766
+ return addProjectOption(
5767
+ group.command(name).description(description).requiredOption("--scenario <id>", "Scenario ID")
5768
+ );
5769
+ }
5770
+ function addPageOptions2(command) {
5771
+ return command.option("--cursor <cursor>", "Page cursor from a previous response").option("--limit <n>", "Page size");
5772
+ }
5773
+ function pageArgs2(options) {
5774
+ const limit = parseIntegerOption(options.limit, "--limit");
5775
+ return {
5776
+ ...options.cursor ? { cursor: options.cursor } : {},
5777
+ ...limit !== void 0 ? { limit } : {}
5778
+ };
5779
+ }
5780
+ function registerUserTestingCommands(program) {
5781
+ const group = program.command("user-testing").description(
5782
+ "Read what a published scenario produced, and control who can reach it"
5783
+ );
5784
+ bindOperation(
5785
+ scenarioCommand(
5786
+ group,
5787
+ "get",
5788
+ "Scenario detail plus its actionable-insights envelope: findings aggregated over the latest analyzed window, with exemplar evidence. Only actionTarget mcp_server with actionability ready authorizes proposing a server change."
5789
+ ),
5790
+ getUserTestingScenarioOperation,
5791
+ (options) => ({
5792
+ project: options.project,
5793
+ scenario: options.scenario
5794
+ })
5795
+ );
5796
+ bindOperation(
5797
+ addPageOptions2(
5798
+ scenarioCommand(
5799
+ group,
5800
+ "sessions",
5801
+ "List the sessions real visitors had with a scenario: counts, feedback, device and segment, with a first-message preview. Summaries only \u2014 use `session` for a transcript."
5802
+ )
5803
+ ),
5804
+ listUserTestingSessionsOperation,
5805
+ (options) => ({
5806
+ project: options.project,
5807
+ scenario: options.scenario,
5808
+ ...pageArgs2(options)
5809
+ })
5810
+ );
5811
+ bindOperation(
5812
+ addPageOptions2(
5813
+ scenarioCommand(
5814
+ group,
5815
+ "session",
5816
+ "Read one session's conversation, paged. These are real people talking to your product; prefer `metrics` or `findings` when you want the pattern rather than the words."
5817
+ ).requiredOption("--session <id>", "Session ID")
5818
+ ),
5819
+ getUserTestingSessionOperation,
5820
+ (options) => ({
5821
+ project: options.project,
5822
+ scenario: options.scenario,
5823
+ session: options.session,
5824
+ ...pageArgs2(options)
5825
+ })
5826
+ );
5827
+ bindOperation(
5828
+ scenarioCommand(
5829
+ group,
5830
+ "metrics",
5831
+ "Aggregate metrics across a scenario's sessions."
5832
+ ).option("--population <name>", "Restrict to a session population"),
5833
+ getUserTestingMetricsOperation,
5834
+ (options) => ({
5835
+ project: options.project,
5836
+ scenario: options.scenario,
5837
+ ...options.population ? { population: options.population } : {}
5838
+ })
5839
+ );
5840
+ bindOperation(
5841
+ scenarioCommand(
5842
+ group,
5843
+ "usage",
5844
+ "Usage rates by visitor and device. Check `scan.truncated` before quoting any rate: true means it was computed over the most recent sessions, not all of them."
5845
+ ),
5846
+ getUserTestingUsageOperation,
5847
+ (options) => ({
5848
+ project: options.project,
5849
+ scenario: options.scenario
5850
+ })
5851
+ );
5852
+ bindOperation(
5853
+ scenarioCommand(
5854
+ group,
5855
+ "findings",
5856
+ "Problems detected across a scenario's sessions, tracked over time."
5857
+ ),
5858
+ listUserTestingFindingsOperation,
5859
+ (options) => ({
5860
+ project: options.project,
5861
+ scenario: options.scenario
5862
+ })
5863
+ );
5864
+ bindOperation(
5865
+ scenarioCommand(
5866
+ group,
5867
+ "signals",
5868
+ "The scenario's live analysis window, and the windowId its insights are keyed by."
5869
+ ),
5870
+ getUserTestingSignalsOperation,
5871
+ (options) => ({
5872
+ project: options.project,
5873
+ scenario: options.scenario
5874
+ })
5875
+ );
5876
+ bindOperation(
5877
+ scenarioCommand(
5878
+ group,
5879
+ "insights",
5880
+ "The model's analysis of one window, if one has been requested. Not-found means nobody asked, which is different from asked-and-working."
5881
+ ).requiredOption("--window <id>", "Window ID (from `signals`)"),
5882
+ getUserTestingInsightsOperation,
5883
+ (options) => ({
5884
+ project: options.project,
5885
+ scenario: options.scenario,
5886
+ window: options.window
5887
+ })
5888
+ );
5889
+ bindOperation(
5890
+ scenarioCommand(
5891
+ group,
5892
+ "request-insights",
5893
+ "Ask a model to analyze the current window. Returns pending; poll `insights`. SPENDS against a daily budget shared with swarm insights. A 409 means the window has not been mined yet \u2014 wait rather than retrying in a loop."
5894
+ ).option("--force", "Regenerate over a window that already has insights."),
5895
+ requestUserTestingInsightsOperation,
5896
+ (options) => ({
5897
+ project: options.project,
5898
+ scenario: options.scenario,
5899
+ ...options.force ? { force: true } : {}
5900
+ })
5901
+ );
5902
+ bindOperation(
5903
+ scenarioCommand(
5904
+ group,
5905
+ "cancel-insights",
5906
+ "Stop an in-flight generation. The recovery path for a window stuck pending \u2014 without it the only way forward is --force, which spends again."
5907
+ ).requiredOption("--window <id>", "Window ID"),
5908
+ cancelUserTestingInsightsOperation,
5909
+ (options) => ({
5910
+ project: options.project,
5911
+ scenario: options.scenario,
5912
+ window: options.window
5913
+ })
5914
+ );
5915
+ bindOperation(
5916
+ scenarioCommand(
5917
+ group,
5918
+ "dismiss-finding",
5919
+ "Mark a finding as not worth acting on. Its lifecycle keeps updating underneath."
5920
+ ).requiredOption("--finding <id>", "Finding ID"),
5921
+ dismissUserTestingFindingOperation,
5922
+ (options) => ({
5923
+ project: options.project,
5924
+ scenario: options.scenario,
5925
+ finding: options.finding
5926
+ })
5927
+ );
5928
+ bindOperation(
5929
+ scenarioCommand(
5930
+ group,
5931
+ "undismiss-finding",
5932
+ "Bring a dismissed finding back into the active list."
5933
+ ).requiredOption("--finding <id>", "Finding ID"),
5934
+ undismissUserTestingFindingOperation,
5935
+ (options) => ({
5936
+ project: options.project,
5937
+ scenario: options.scenario,
5938
+ finding: options.finding
5939
+ })
5940
+ );
5941
+ bindOperation(
5942
+ scenarioCommand(
5943
+ group,
5944
+ "update",
5945
+ "Rename a scenario, or change who may open its share link. --mode must be used ON ITS OWN: identity and exposure are separate operations upstream, and mixing them could leave the scenario live in a mode you did not ask for."
5946
+ ).option("--name <name>").option("--description <text>").option(
5947
+ "--mode <mode>",
5948
+ "project_members | invited_only | anyone_with_link"
5949
+ ),
5950
+ updateUserTestingScenarioOperation,
5951
+ (options) => ({
5952
+ project: options.project,
5953
+ scenario: options.scenario,
5954
+ ...options.name !== void 0 ? { name: options.name } : {},
5955
+ ...options.description !== void 0 ? { description: options.description } : {},
5956
+ ...options.mode !== void 0 ? { mode: options.mode } : {}
5957
+ })
5958
+ );
5959
+ bindOperation(
5960
+ scenarioCommand(
5961
+ group,
5962
+ "guest-execution",
5963
+ "Set what anonymous visitors may run on your account, and how much. A FULL REPLACEMENT: every flag is required, because these caps only mean something as a set and raising one while leaving a stale sibling produces a combination nobody chose."
5964
+ ).requiredOption("--enabled <bool>", "true | false").requiredOption("--computer-enabled <bool>", "true | false").requiredOption("--shared-skills-enabled <bool>", "true | false").requiredOption(
5965
+ "--daily-credit-cap <n>",
5966
+ "Hard ceiling on visitor spend per day, in credits"
5967
+ ).requiredOption("--daily-computer-start-cap <n>").requiredOption("--max-concurrent-computers <n>").option(
5968
+ "--harness-enabled <bool>",
5969
+ "true | false. Omitting this REPLACES any existing harness setting with 'disabled'."
5970
+ ).option("--daily-harness-spend-cap-micros <n>").option("--daily-harness-call-cap <n>").option("--max-concurrent-harness-runs <n>"),
5971
+ setUserTestingGuestExecutionOperation,
5972
+ (options) => {
5973
+ if (options.harnessEnabled === void 0 && (options.dailyHarnessSpendCapMicros !== void 0 || options.dailyHarnessCallCap !== void 0 || options.maxConcurrentHarnessRuns !== void 0)) {
5974
+ throw usageError(
5975
+ "--harness-enabled is required when any harness cap is given: omitting it disables the harness, so the caps would land on nothing."
5976
+ );
5977
+ }
5978
+ return {
5979
+ project: options.project,
5980
+ scenario: options.scenario,
5981
+ enabled: parseBooleanFlag(options.enabled, "--enabled"),
5982
+ computerEnabled: parseBooleanFlag(
5983
+ options.computerEnabled,
5984
+ "--computer-enabled"
5985
+ ),
5986
+ sharedSkillsEnabled: parseBooleanFlag(
5987
+ options.sharedSkillsEnabled,
5988
+ "--shared-skills-enabled"
5989
+ ),
5990
+ dailyCreditCap: parseNumberFlag(
5991
+ options.dailyCreditCap,
5992
+ "--daily-credit-cap"
5993
+ ),
5994
+ dailyComputerStartCap: parseRequiredIntegerOption(
5995
+ options.dailyComputerStartCap,
5996
+ "--daily-computer-start-cap"
5997
+ ),
5998
+ maxConcurrentComputers: parseRequiredIntegerOption(
5999
+ options.maxConcurrentComputers,
6000
+ "--max-concurrent-computers"
6001
+ ),
6002
+ ...options.harnessEnabled !== void 0 ? {
6003
+ harnessEnabled: parseBooleanFlag(
6004
+ options.harnessEnabled,
6005
+ "--harness-enabled"
6006
+ )
6007
+ } : {},
6008
+ ...options.dailyHarnessSpendCapMicros !== void 0 ? {
6009
+ dailyHarnessSpendCapMicros: parseIntegerOption(
6010
+ options.dailyHarnessSpendCapMicros,
6011
+ "--daily-harness-spend-cap-micros"
6012
+ )
6013
+ } : {},
6014
+ ...options.dailyHarnessCallCap !== void 0 ? {
6015
+ dailyHarnessCallCap: parseIntegerOption(
6016
+ options.dailyHarnessCallCap,
6017
+ "--daily-harness-call-cap"
6018
+ )
6019
+ } : {},
6020
+ ...options.maxConcurrentHarnessRuns !== void 0 ? {
6021
+ maxConcurrentHarnessRuns: parseIntegerOption(
6022
+ options.maxConcurrentHarnessRuns,
6023
+ "--max-concurrent-harness-runs"
6024
+ )
6025
+ } : {}
6026
+ };
6027
+ }
6028
+ );
6029
+ bindOperation(
6030
+ scenarioCommand(
6031
+ group,
6032
+ "rotate-link",
6033
+ "Mint a new share link and invalidate the old one. IMMEDIATE AND IRREVERSIBLE: everyone holding the old URL loses access and every live session on it dies. This is what you do when a link has leaked."
6034
+ ),
6035
+ rotateUserTestingLinkOperation,
6036
+ (options) => ({
6037
+ project: options.project,
6038
+ scenario: options.scenario
6039
+ })
6040
+ );
6041
+ bindOperation(
6042
+ scenarioCommand(
6043
+ group,
6044
+ "invite",
6045
+ "Grant one person access by email. Upsert, so re-inviting an existing member is not an error."
6046
+ ).requiredOption("--email <email>").option("--send-invite-email", "Also email them. Off by default."),
6047
+ upsertUserTestingMemberOperation,
6048
+ (options) => ({
6049
+ project: options.project,
6050
+ scenario: options.scenario,
6051
+ email: options.email,
6052
+ ...options.sendInviteEmail ? { sendInviteEmail: true } : {}
6053
+ })
6054
+ );
6055
+ bindOperation(
6056
+ scenarioCommand(
6057
+ group,
6058
+ "remove-member",
6059
+ "Revoke one person's access."
6060
+ ).requiredOption("--member <id-or-email>"),
6061
+ removeUserTestingMemberOperation,
6062
+ (options) => ({
6063
+ project: options.project,
6064
+ scenario: options.scenario,
6065
+ member: options.member
6066
+ })
6067
+ );
6068
+ bindOperation(
6069
+ scenarioCommand(
6070
+ group,
6071
+ "rebind",
6072
+ "Point a scenario at a different environment, KEEPING its link, members and session history. The alternative \u2014 unpublish and republish \u2014 mints a new link, which means re-sharing it with everyone."
6073
+ ).requiredOption("--environment <id>", "Project environment ID"),
6074
+ rebindUserTestingScenarioOperation,
6075
+ (options) => ({
6076
+ project: options.project,
6077
+ scenario: options.scenario,
6078
+ environmentId: options.environment
6079
+ })
6080
+ );
6081
+ }
6082
+ function parseBooleanFlag(value, flag) {
6083
+ const normalized = value.trim().toLowerCase();
6084
+ if (normalized === "true") return true;
6085
+ if (normalized === "false") return false;
6086
+ throw new Error(`${flag} must be true or false`);
6087
+ }
6088
+ function parseNumberFlag(value, flag) {
6089
+ const parsed = Number(value);
6090
+ if (!Number.isFinite(parsed) || parsed < 0) {
6091
+ throw new Error(`${flag} must be a non-negative number`);
6092
+ }
6093
+ return parsed;
6094
+ }
6095
+
6096
+ // src/lib/eval-screenshots.ts
6097
+ function asRecord(value) {
6098
+ return typeof value === "object" && value !== null ? value : null;
6099
+ }
6100
+ function asString(value) {
6101
+ return typeof value === "string" ? value : void 0;
6102
+ }
6103
+ function extractRenderedScreenshots(result) {
6104
+ const root = asRecord(result);
6105
+ if (!root) return [];
6106
+ const trace = asRecord(root.trace) ?? root;
6107
+ const screenshots = [];
6108
+ const observations = trace.widgetRenderObservations;
6109
+ if (Array.isArray(observations)) {
6110
+ for (const entry of observations) {
6111
+ const obs = asRecord(entry);
6112
+ if (!obs) continue;
6113
+ const status = asString(obs.status);
6114
+ const screenshotUrl = asString(obs.screenshotUrl);
6115
+ if (status !== "rendered" || !screenshotUrl) continue;
6116
+ screenshots.push({
6117
+ status,
6118
+ screenshotUrl,
6119
+ toolName: asString(obs.toolName),
6120
+ toolCallId: asString(obs.toolCallId),
6121
+ promptIndex: typeof obs.promptIndex === "number" ? obs.promptIndex : void 0
6122
+ });
6123
+ }
6124
+ }
6125
+ const interactions = trace.browserInteractionSteps;
6126
+ if (Array.isArray(interactions)) {
6127
+ for (const entry of interactions) {
6128
+ const step = asRecord(entry);
6129
+ if (!step) continue;
6130
+ const screenshotUrl = asString(step.screenshotUrl);
6131
+ if (!screenshotUrl) continue;
6132
+ const assertion = asRecord(step.assertion);
6133
+ const status = assertion ? assertion.passed === true ? "assert:passed" : "assert:failed" : asString(step.action) ?? "interaction";
6134
+ const label = asString(step.locatorLabel) ?? asString(step.action) ?? "interaction";
6135
+ screenshots.push({
6136
+ status,
6137
+ screenshotUrl,
6138
+ toolName: label,
6139
+ toolCallId: asString(step.toolCallId),
6140
+ promptIndex: typeof step.promptIndex === "number" ? step.promptIndex : void 0
6141
+ });
6142
+ }
6143
+ }
6144
+ return screenshots;
6145
+ }
6146
+ function extractIterationVideoUrl(result) {
6147
+ const root = asRecord(result);
6148
+ if (!root) return void 0;
6149
+ const trace = asRecord(root.trace) ?? root;
6150
+ return asString(trace.videoUrl);
6151
+ }
6152
+ function screenshotFilename(shot, index) {
6153
+ const tool = (shot.toolName ?? "widget").replace(/[^a-zA-Z0-9_-]+/g, "-");
6154
+ const suffix = shot.toolCallId ? shot.toolCallId.replace(/[^a-zA-Z0-9_-]+/g, "-") : String(index + 1);
6155
+ return `${tool}-${suffix}.png`;
6156
+ }
6157
+ var DEFAULT_CORPUS_LOCK_PATH = "mcpjam-evals.lock.json";
6158
+ var CORPUS_DRIFT_EXIT_CODE = 1;
6159
+ var CORPUS_INCOMPLETE_EXIT_CODE = 3;
6160
+ var CORPUS_USAGE_EXIT_CODE = 2;
6161
+ function incomplete(code, message, details) {
6162
+ return cliError(code, message, CORPUS_INCOMPLETE_EXIT_CODE, details);
6163
+ }
6164
+ function corpusFetchFailure(error) {
6165
+ const normalized = error instanceof CliError ? error : normalizeCliError(error);
6166
+ if (normalized.exitCode === CORPUS_USAGE_EXIT_CODE) {
6167
+ return normalized;
6168
+ }
6169
+ return cliError(
6170
+ normalized.code,
6171
+ normalized.message,
6172
+ CORPUS_INCOMPLETE_EXIT_CODE,
6173
+ normalized.details
6174
+ );
6175
+ }
6176
+ function resolveCorpusLockPath(value) {
6177
+ return path2.resolve(process.cwd(), value ?? DEFAULT_CORPUS_LOCK_PATH);
6178
+ }
6179
+ function isMissingFileError(error) {
6180
+ return typeof error === "object" && error !== null && error.code === "ENOENT";
6181
+ }
6182
+ function isRecord3(value) {
6183
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6184
+ }
6185
+ function describeLockDefect(lock) {
6186
+ if (!isRecord3(lock.suite) || typeof lock.suite.id !== "string") {
6187
+ return `"suite.id" is missing or not a string`;
6188
+ }
6189
+ if (typeof lock.evaluationConfigHash !== "string") {
6190
+ return `"evaluationConfigHash" is missing or not a string`;
6191
+ }
6192
+ if (typeof lock.fetchedAt !== "string") {
6193
+ return `"fetchedAt" is missing or not a string`;
6194
+ }
6195
+ const REQUIRED_STRINGS = [
6196
+ "scenarioKey",
6197
+ "caseId",
6198
+ "title",
6199
+ "scenarioContentHash",
6200
+ "evaluationConfigHash"
6201
+ ];
6202
+ for (const [index, row] of lock.cases.entries()) {
6203
+ if (!isRecord3(row)) {
6204
+ return `case ${index} is not an object`;
6205
+ }
6206
+ for (const field of REQUIRED_STRINGS) {
6207
+ if (typeof row[field] !== "string") {
6208
+ return `case ${index} is missing "${field}"`;
6209
+ }
6210
+ }
6211
+ if (row.scenarioKey !== `external:${row.caseId}`) {
6212
+ return `case ${index} ("${String(row.scenarioKey)}") has a scenarioKey that does not match its caseId`;
6213
+ }
6214
+ if (!Number.isInteger(row.iterations) || row.iterations < 1) {
6215
+ return `case ${index} ("${String(row.scenarioKey)}") has an invalid "iterations" (${String(row.iterations)})`;
6216
+ }
6217
+ if (!isRecord3(row.normalizedContent)) {
6218
+ return `case ${index} ("${String(
6219
+ row.scenarioKey
6220
+ )}") is missing "normalizedContent"`;
6221
+ }
6222
+ }
6223
+ const keys = /* @__PURE__ */ new Set();
6224
+ for (const row of lock.cases) {
6225
+ const key = row.scenarioKey;
6226
+ if (keys.has(key)) {
6227
+ return `"${key}" appears twice`;
6228
+ }
6229
+ keys.add(key);
6230
+ }
6231
+ return void 0;
6232
+ }
6233
+ async function readCorpusLock(lockPath) {
6234
+ let raw;
6235
+ try {
6236
+ const handle = await open(lockPath, "r");
6237
+ try {
6238
+ raw = await handle.readFile("utf8");
6239
+ } finally {
6240
+ await handle.close();
6241
+ }
6242
+ } catch (error) {
6243
+ if (isMissingFileError(error)) {
6244
+ throw incomplete(
6245
+ "CORPUS_LOCK_MISSING",
6246
+ `No corpus lock at "${lockPath}". Run \`mcpjam eval pull\` to create one before checking it with --frozen.`
6247
+ );
6248
+ }
6249
+ throw incomplete(
6250
+ "CORPUS_LOCK_UNREADABLE",
6251
+ `Could not read the corpus lock at "${lockPath}".`,
6252
+ { source: error instanceof Error ? error.message : String(error) }
6253
+ );
6254
+ }
6255
+ let parsed;
6256
+ try {
6257
+ parsed = JSON.parse(raw);
6258
+ } catch (error) {
6259
+ throw incomplete(
6260
+ "CORPUS_LOCK_MALFORMED",
6261
+ `The corpus lock at "${lockPath}" is not valid JSON. Re-create it with \`mcpjam eval pull\`.`,
6262
+ { source: error instanceof Error ? error.message : String(error) }
6263
+ );
6264
+ }
6265
+ if (typeof parsed !== "object" || parsed === null) {
6266
+ throw incomplete(
6267
+ "CORPUS_LOCK_MALFORMED",
6268
+ `The corpus lock at "${lockPath}" is not a lock object.`
6269
+ );
6270
+ }
6271
+ const lock = parsed;
6272
+ if (typeof lock.lockVersion !== "number" || !Array.isArray(lock.cases)) {
6273
+ throw incomplete(
6274
+ "CORPUS_LOCK_MALFORMED",
6275
+ `The corpus lock at "${lockPath}" is missing "lockVersion" or "cases". Re-create it with \`mcpjam eval pull\`.`
6276
+ );
6277
+ }
6278
+ const structural = describeLockDefect(lock);
6279
+ if (structural) {
6280
+ throw incomplete(
6281
+ "CORPUS_LOCK_MALFORMED",
6282
+ `The corpus lock at "${lockPath}" is malformed: ${structural}. Re-create it with \`mcpjam eval pull\`.`
6283
+ );
6284
+ }
6285
+ if (lock.lockVersion !== CORPUS_LOCK_VERSION) {
6286
+ throw incomplete(
6287
+ "CORPUS_LOCK_VERSION_MISMATCH",
6288
+ `The corpus lock at "${lockPath}" is version ${lock.lockVersion}, but this CLI writes version ${CORPUS_LOCK_VERSION}. Hashes are not comparable across lock versions. Re-create it with \`mcpjam eval pull\`.`
6289
+ );
6290
+ }
6291
+ return lock;
6292
+ }
6293
+ async function writeCorpusLockAtomic(lockPath, lock) {
6294
+ const resolved = path2.resolve(process.cwd(), lockPath);
6295
+ const temporary = `${resolved}.${process.pid}-${randomBytes(6).toString(
6296
+ "hex"
6297
+ )}.tmp`;
6298
+ try {
6299
+ const body = `${JSON.stringify(lock, null, 2)}
6300
+ `;
6301
+ await writeFile(temporary, body, { encoding: "utf8", mode: 420 });
6302
+ const handle = await open(temporary, "r+");
6303
+ try {
6304
+ await handle.sync();
6305
+ } finally {
6306
+ await handle.close();
6307
+ }
6308
+ await rename(temporary, resolved);
6309
+ } catch (error) {
6310
+ await unlink(temporary).catch(() => {
6311
+ });
6312
+ throw incomplete(
6313
+ "CORPUS_LOCK_WRITE_FAILED",
6314
+ `Failed to write the corpus lock to "${resolved}". The previous lock, if any, is unchanged.`,
6315
+ { source: error instanceof Error ? error.message : String(error) }
6316
+ );
6317
+ }
6318
+ return resolved;
6319
+ }
6320
+ var DRIFT_LABELS = {
6321
+ caseAdded: "added ",
6322
+ caseRemoved: "removed ",
6323
+ contentChanged: "content ",
6324
+ evaluationConfigChanged: "grading "
6325
+ };
6326
+ var DRIFT_MARKS = {
6327
+ caseAdded: "+",
6328
+ caseRemoved: "-",
6329
+ contentChanged: "~",
6330
+ evaluationConfigChanged: "~"
6331
+ };
6332
+ function renderCorpusDrift(drift) {
6333
+ if (drift.length === 0) {
6334
+ return "Corpus matches the lock.";
6335
+ }
6336
+ const lines = drift.map(
6337
+ (entry) => ` ${DRIFT_MARKS[entry.kind]} ${DRIFT_LABELS[entry.kind]} ${entry.scenarioKey} ${JSON.stringify(entry.title)}`
6338
+ );
6339
+ return [
6340
+ `Corpus drifted from the lock (${drift.length} ${drift.length === 1 ? "change" : "changes"}):`,
6341
+ ...lines,
6342
+ "",
6343
+ "Run `mcpjam eval pull` to accept these changes, or restore the cases in the dashboard."
6344
+ ].join("\n");
6345
+ }
6346
+
6347
+ // src/lib/eval-gate-exit-code.ts
6348
+ function evalGateExitCode(report) {
6349
+ switch (report.outcome) {
6350
+ case "passed":
6351
+ return 0;
6352
+ case "failed":
6353
+ return 1;
6354
+ case "usage_error":
6355
+ return 2;
6356
+ case "incomplete":
6357
+ return 3;
6358
+ default:
6359
+ return 3;
6360
+ }
6361
+ }
6362
+ var TERMINAL_RUN_STATUSES = /* @__PURE__ */ new Set([
6363
+ "completed",
6364
+ "failed",
6365
+ "cancelled",
6366
+ "timed_out"
6367
+ ]);
6368
+ var NON_VERDICT_STATUSES = /* @__PURE__ */ new Set(["cancelled", "timed_out", "failed"]);
6369
+ function isNonVerdictRunStatus(status) {
6370
+ return status !== void 0 && NON_VERDICT_STATUSES.has(status);
6371
+ }
6372
+ var EVAL_GATE_INCOMPLETE_EXIT_CODE = 3;
6373
+ var EVAL_GATE_USAGE_EXIT_CODE = 2;
6374
+ function parsePercent(raw, flag) {
6375
+ const value = raw.trim() === "" ? NaN : Number(raw);
6376
+ if (!Number.isFinite(value) || value < 0 || value > 100) {
6377
+ throw usageError(`${flag} must be a number between 0 and 100, got "${raw}".`);
6378
+ }
6379
+ return passRateFractionFromPercent(value);
6380
+ }
6381
+ function parseScorerMap(entries, flag, parseValue) {
6382
+ const out = /* @__PURE__ */ Object.create(null);
6383
+ for (const entry of entries) {
6384
+ const index = entry.indexOf("=");
6385
+ if (index <= 0) {
6386
+ throw usageError(`${flag} must be <scorerId>=<value>, got "${entry}".`);
6387
+ }
6388
+ const scorerId = entry.slice(0, index).trim();
6389
+ if (!scorerId) {
6390
+ throw usageError(`${flag} is missing a scorer id in "${entry}".`);
6391
+ }
6392
+ if (Object.prototype.hasOwnProperty.call(out, scorerId)) {
6393
+ throw usageError(
6394
+ `${flag} names "${scorerId}" more than once; pass one threshold per scorer.`
6395
+ );
6396
+ }
6397
+ out[scorerId] = parseValue(entry.slice(index + 1).trim(), flag);
6398
+ }
6399
+ return out;
6400
+ }
6401
+ function parseUnit(raw, flag) {
6402
+ const value = raw.trim() === "" ? NaN : Number(raw);
6403
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
6404
+ throw usageError(`${flag} must be a number between 0 and 1, got "${raw}".`);
6405
+ }
6406
+ return value;
6407
+ }
6408
+ function policyFromOptions(options) {
6409
+ const policy = {};
6410
+ if (options.minPassRatePercent !== void 0) {
6411
+ policy.minimumPassRate = parsePercent(
6412
+ options.minPassRatePercent,
6413
+ "--min-pass-rate-percent"
6414
+ );
6415
+ }
6416
+ if (options.noGatingScoreErrors) policy.noGatingScoreErrors = true;
6417
+ if (options.minScorerPassRate?.length) {
6418
+ policy.minimumScorerPassRate = parseScorerMap(
6419
+ options.minScorerPassRate,
6420
+ "--min-scorer-pass-rate",
6421
+ parsePercent
6422
+ );
6423
+ }
6424
+ if (options.minMeanScore?.length) {
6425
+ policy.minimumMeanScore = parseScorerMap(
6426
+ options.minMeanScore,
6427
+ "--min-mean-score",
6428
+ parseUnit
6429
+ );
6430
+ }
6431
+ return policy;
6432
+ }
6433
+ function policyNeedsIterations(policy) {
6434
+ return Boolean(
6435
+ policy.noGatingScoreErrors || policy.minimumScorerPassRate || policy.minimumMeanScore || policy.maximumTotalTokens !== void 0 || // p95 comes from iteration durations, exactly like tokens come from
6436
+ // iteration counts. Omitting it here would leave the latency gate
6437
+ // permanently non-gateable — the fetch that could decide it never runs.
6438
+ policy.maximumP95LatencyMs !== void 0
6439
+ );
6440
+ }
6441
+ function reportForRun(run, iterations, policy) {
6442
+ return evaluateGates(gateInputFromPlatformRun(run, iterations), policy);
6443
+ }
6444
+
6445
+ // src/lib/eval-iterations.ts
6446
+ async function fetchAllIterations(client, signal, projectId, runId) {
6447
+ const items = [];
6448
+ let cursor;
6449
+ for (let page = 0; page < 100; page += 1) {
6450
+ const result = await client.listEvalRunIterations(
6451
+ { projectId, runId, ...cursor ? { cursor } : {}, limit: 200 },
6452
+ { signal }
6453
+ );
6454
+ items.push(...result.items);
6455
+ if (!result.nextCursor) return { items, complete: true };
6456
+ cursor = result.nextCursor;
6457
+ }
6458
+ return { items, complete: false };
6459
+ }
6460
+
6461
+ // src/lib/eval-compare.ts
6462
+ function parseNonNegativeInteger2(raw, flag) {
6463
+ const value = raw.trim() === "" ? NaN : Number(raw);
6464
+ if (!Number.isInteger(value) || value < 0) {
6465
+ throw usageError(
6466
+ `${flag} must be a non-negative integer, got "${raw}".`
6467
+ );
6468
+ }
6469
+ return value;
6470
+ }
6471
+ function parsePercentAsFraction(raw, flag) {
6472
+ const value = raw.trim() === "" ? NaN : Number(raw);
6473
+ if (!Number.isFinite(value) || value < 0 || value > 100) {
6474
+ throw usageError(
6475
+ `${flag} must be a number between 0 and 100, got "${raw}".`
6476
+ );
6477
+ }
6478
+ return value / 100;
6479
+ }
6480
+ function comparePolicyFromOptions(options) {
6481
+ const policy = {};
6482
+ const tuning = {};
6483
+ if (options.minSampleSize !== void 0) {
6484
+ tuning.minSampleSize = parseNonNegativeInteger2(
6485
+ options.minSampleSize,
6486
+ "--min-sample-size"
6487
+ );
6488
+ }
6489
+ if (options.minEffectSizePercent !== void 0) {
6490
+ tuning.minEffectSize = parsePercentAsFraction(
6491
+ options.minEffectSizePercent,
6492
+ "--min-effect-size-percent"
6493
+ );
6494
+ }
6495
+ if (Object.keys(tuning).length > 0 && !options.gateRegressions) {
6496
+ throw usageError(
6497
+ "--min-sample-size and --min-effect-size-percent tune the pass-rate regression gate; pass --gate-regressions to enable it."
6498
+ );
6499
+ }
6500
+ if (options.gateRegressions) policy.passRateRegression = tuning;
6501
+ if (options.gateDeterministicRegressions) {
6502
+ policy.noDeterministicRegressions = true;
6503
+ }
6504
+ if (options.maxP95LatencyIncreaseMs !== void 0) {
6505
+ policy.maximumP95LatencyIncreaseMs = parseNonNegativeInteger2(
6506
+ options.maxP95LatencyIncreaseMs,
6507
+ "--max-p95-latency-increase-ms"
6508
+ );
6509
+ }
6510
+ return policy;
6511
+ }
6512
+ var CASE_SET_CHANGED_STATUSES = /* @__PURE__ */ new Set(["new_case", "removed_case"]);
6513
+ function deterministicRegressionsFrom(cases) {
6514
+ const regressions = [];
6515
+ for (const row of cases) {
6516
+ for (const delta of row.scoreDeltas) {
6517
+ if (!delta.gating || !delta.deterministic) continue;
6518
+ if (delta.definitionChanged) continue;
6519
+ if (delta.base?.passed === true && delta.compare?.passed === false) {
6520
+ regressions.push({ caseKey: row.caseKey, scorerId: delta.scorerId });
6521
+ }
6522
+ }
6523
+ }
6524
+ return regressions;
6525
+ }
6526
+ function iterationWeightingEqualFrom(cases) {
6527
+ for (const row of cases) {
6528
+ if (row.base.outcome === "absent" || row.compare.outcome === "absent") {
6529
+ continue;
6530
+ }
6531
+ if (row.base.iterationIds.length !== row.compare.iterationIds.length) {
6532
+ return false;
6533
+ }
6534
+ }
6535
+ return true;
6536
+ }
6537
+ function sideFromRun(summary, integrity, e2eP95Ms) {
6538
+ return {
6539
+ iterations: {
6540
+ total: summary?.total ?? 0,
6541
+ passed: summary?.passed ?? 0
6542
+ },
6543
+ ...integrity ? { scoreIntegrity: integrity } : {},
6544
+ ...e2eP95Ms !== void 0 ? { totals: { e2eP95Ms } } : {}
6545
+ };
6546
+ }
6547
+ function compareGateInputFrom(compare, latency = {}) {
6548
+ const cases = compare.cases;
6549
+ return {
6550
+ base: sideFromRun(
6551
+ compare.baseRun.summary,
6552
+ compare.scoreContract.base.scoreIntegrity,
6553
+ latency.baseP95Ms
6554
+ ),
6555
+ compare: sideFromRun(
6556
+ compare.compareRun.summary,
6557
+ compare.scoreContract.compare.scoreIntegrity,
6558
+ latency.compareP95Ms
6559
+ ),
6560
+ deterministicScoreRegressions: deterministicRegressionsFrom(cases),
6561
+ scoreDeltasAvailable: cases.some((row) => row.scoreDeltas.length > 0),
6562
+ caseSetChanged: cases.some(
6563
+ (row) => CASE_SET_CHANGED_STATUSES.has(row.status)
6564
+ ),
6565
+ scenarioConfigChanged: cases.some((row) => row.configChanged),
6566
+ // Run-level OR any single case's own. A suite that re-grades ONE case has
6567
+ // changed what that case measures, and the whole-run rate now mixes two
6568
+ // measurements — the run-level hash alone would miss it.
6569
+ evaluationConfigChanged: compare.scoreContract.evaluationConfigChanged || cases.some((row) => row.evaluationConfigChanged),
6570
+ iterationWeightingEqual: iterationWeightingEqualFrom(cases)
6571
+ };
6572
+ }
6573
+ function flakyInputFrom(iterations) {
6574
+ return iterations.filter(
6575
+ (iteration) => iteration.result === "passed" || iteration.result === "failed"
6576
+ ).map((iteration) => ({
6577
+ // Falls back to the iteration's own id, never a shared literal: a
6578
+ // single "unknown" bucket would pool unrelated iterations, and one pass
6579
+ // plus one fail from two DIFFERENT cases would be reported as a flake
6580
+ // that never existed.
6581
+ caseKey: iteration.testCaseId ?? iteration.title ?? iteration.id,
6582
+ passed: iteration.result === "passed"
6583
+ }));
6584
+ }
6585
+
6586
+ // src/lib/terminal-image.ts
6587
+ var ESC = "\x1B";
6588
+ var BEL = "\x07";
6589
+ function detectInlineImageProtocol(env = process.env, isTTY = process.stdout.isTTY) {
6590
+ if (!isTTY) return null;
6591
+ const termProgram = env.TERM_PROGRAM ?? "";
6592
+ const term = env.TERM ?? "";
6593
+ if (term === "xterm-kitty" || env.KITTY_WINDOW_ID !== void 0 || termProgram === "ghostty" || env.GHOSTTY_RESOURCES_DIR !== void 0) {
6594
+ return "kitty";
6595
+ }
6596
+ if (termProgram === "iTerm.app" || termProgram === "WezTerm" || termProgram === "WarpTerminal" || env.LC_TERMINAL === "iTerm2") {
6597
+ return "iterm";
6598
+ }
6599
+ return null;
6600
+ }
6601
+ function toBase64(data) {
6602
+ return Buffer.from(data).toString("base64");
6603
+ }
6604
+ function encodeIterm(data) {
6605
+ const payload = toBase64(data);
6606
+ const args = ["inline=1", `size=${data.byteLength}`, "preserveAspectRatio=1"].join(
6607
+ ";"
6608
+ );
6609
+ return `${ESC}]1337;File=${args}:${payload}${BEL}
6610
+ `;
6611
+ }
6612
+ function encodeKitty(data) {
6613
+ const payload = toBase64(data);
6614
+ const CHUNK = 4096;
6615
+ const chunks = [];
6616
+ for (let offset = 0; offset < payload.length; offset += CHUNK) {
6617
+ chunks.push(payload.slice(offset, offset + CHUNK));
6618
+ }
6619
+ if (chunks.length === 0) chunks.push("");
6620
+ let out = "";
6621
+ chunks.forEach((chunk, index) => {
6622
+ const more = index < chunks.length - 1 ? 1 : 0;
6623
+ const control = index === 0 ? `a=T,f=100,m=${more}` : `m=${more}`;
6624
+ out += `${ESC}_G${control};${chunk}${ESC}\\`;
6625
+ });
6626
+ return `${out}
6627
+ `;
6628
+ }
6629
+ function encodeInlineImage(data, protocol) {
6630
+ return protocol === "kitty" ? encodeKitty(data) : encodeIterm(data);
6631
+ }
6632
+
6633
+ // src/commands/eval.ts
6634
+ function addPlatformOptions7(command) {
6635
+ return command.option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
6636
+ "--api-url <url>",
6637
+ "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
6638
+ );
6639
+ }
6640
+ function writeRunLink(format, webOrigin, run) {
6641
+ if (format !== "human") return;
6642
+ const suiteId = run.suiteId?.trim();
6643
+ const runId = run.runId?.trim();
6644
+ if (!suiteId || !runId) return;
6645
+ const query = run.projectId?.trim() ? `?project=${encodeURIComponent(run.projectId.trim())}` : "";
6646
+ process.stdout.write(
6647
+ `View: ${webOrigin}/evals/suite/${encodeURIComponent(
6648
+ suiteId
6649
+ )}/runs/${encodeURIComponent(runId)}${query}
6650
+ `
6651
+ );
6652
+ }
6653
+ async function runPlatformCommand7(options, timeoutMs, execute) {
6654
+ const controller = new AbortController();
6655
+ const timeoutHandle = setTimeout(() => {
6656
+ controller.abort(
6657
+ new PlatformApiError(
6658
+ `Request timed out after ${timeoutMs}ms`,
6659
+ "TIMEOUT",
6660
+ {
6661
+ status: 0
6662
+ }
6663
+ )
6664
+ );
6665
+ }, timeoutMs);
6666
+ timeoutHandle.unref?.();
6667
+ try {
6668
+ const { client, baseUrl } = buildPlatformClient({ ...options, timeoutMs });
6669
+ return await execute({
6670
+ client,
6671
+ signal: controller.signal,
6672
+ webOrigin: webOriginForApiBaseUrl(baseUrl)
6673
+ });
6674
+ } catch (error) {
6675
+ if (controller.signal.aborted && controller.signal.reason instanceof PlatformApiError) {
6676
+ throw toCliError(controller.signal.reason);
6677
+ }
6678
+ throw toCliError(error);
6679
+ } finally {
6680
+ clearTimeout(timeoutHandle);
6681
+ }
6682
+ }
6683
+ function readFileOrStdin(value, label) {
6684
+ try {
6685
+ return value === "-" ? readFileSync(0, "utf8") : readFileSync(value, "utf8");
6686
+ } catch (error) {
6687
+ throw usageError(`Failed to read ${label} "${value}".`, {
6688
+ source: error instanceof Error ? error.message : String(error)
6689
+ });
6690
+ }
6691
+ }
6692
+ function loadSuiteDefinition(options) {
6693
+ if (options.file !== void 0 && options.json !== void 0) {
6694
+ throw usageError("Provide either --file or --json, not both.");
6695
+ }
6696
+ let base = {};
6697
+ if (options.file !== void 0) {
6698
+ const text = readFileOrStdin(options.file, "--file");
6699
+ if (text.trim() === "") {
6700
+ throw usageError("--file input is empty.");
6701
+ }
6702
+ try {
6703
+ base = JSON.parse(text);
6704
+ } catch (error) {
6705
+ throw usageError("--file must contain valid JSON.", {
6706
+ source: error instanceof Error ? error.message : String(error)
6707
+ });
6708
+ }
6709
+ } else if (options.json !== void 0) {
6710
+ base = new JsonInputContext().parseJsonInputRecord(options.json, "--json");
6711
+ }
6712
+ if (base === void 0 || base === null) {
6713
+ base = {};
6714
+ }
6715
+ if (typeof base !== "object" || Array.isArray(base)) {
6716
+ throw usageError("Suite definition must be a JSON object.");
6717
+ }
6718
+ const merged = {
6719
+ ...base,
6720
+ ...options.project !== void 0 ? { project: options.project } : {},
6721
+ ...options.name !== void 0 ? { name: options.name } : {},
6722
+ ...options.model !== void 0 ? { model: options.model } : {},
6723
+ ...options.provider !== void 0 ? { provider: options.provider } : {},
6724
+ ...options.server !== void 0 ? { servers: options.server } : {}
6725
+ };
6726
+ const parsed = createEvalSuiteOperation.inputSchema.safeParse(merged);
6727
+ if (!parsed.success) {
6728
+ const detail = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ");
6729
+ throw usageError(`Invalid suite definition: ${detail}`);
6730
+ }
6731
+ return parsed.data;
6732
+ }
6733
+ function loadBodyObject(options) {
6734
+ if (options.file !== void 0 && options.json !== void 0) {
6735
+ throw usageError("Provide either --file or --json, not both.");
6736
+ }
6737
+ let base = {};
6738
+ if (options.file !== void 0) {
5401
6739
  const text = readFileOrStdin(options.file, "--file");
5402
6740
  if (text.trim() === "") throw usageError("--file input is empty.");
5403
6741
  try {
@@ -5426,7 +6764,7 @@ function validateOpInput2(op, raw) {
5426
6764
  }
5427
6765
  async function executeOp2(op, input, options, command) {
5428
6766
  const globalOptions = getGlobalOptions(command);
5429
- const result = await runPlatformCommand6(
6767
+ const result = await runPlatformCommand7(
5430
6768
  options,
5431
6769
  globalOptions.timeout,
5432
6770
  ({ client, signal }) => op.execute(input, { client, signal })
@@ -5469,64 +6807,476 @@ function buildSuiteUpdateInput(options) {
5469
6807
  if (options.judge !== "on" && options.judge !== "off") {
5470
6808
  throw usageError('--judge must be "on" or "off".');
5471
6809
  }
5472
- judge.enabled = options.judge === "on";
6810
+ judge.enabled = options.judge === "on";
6811
+ }
6812
+ if (options.judgeModel !== void 0) judge.model = options.judgeModel;
6813
+ if (Object.keys(judge).length > 0) settings.judge = judge;
6814
+ if (Object.keys(settings).length > 0) input.settings = settings;
6815
+ return input;
6816
+ }
6817
+ function buildCaseInput(options, opts) {
6818
+ const input = { ...loadBodyObject(options) };
6819
+ if (options.project !== void 0) input.project = options.project;
6820
+ input.suite = options.suite;
6821
+ if (opts.requireCase) input.case = options.case;
6822
+ if (options.title !== void 0) input.title = options.title;
6823
+ return input;
6824
+ }
6825
+ async function fetchArtifactBytes(url, timeoutMs, kind = "screenshot") {
6826
+ const controller = new AbortController();
6827
+ const handle = setTimeout(() => controller.abort(), timeoutMs);
6828
+ handle.unref?.();
6829
+ try {
6830
+ const response = await fetch(url, { signal: controller.signal });
6831
+ if (!response.ok) {
6832
+ throw operationalError(
6833
+ `Failed to download ${kind} (HTTP ${response.status}).`,
6834
+ { url }
6835
+ );
6836
+ }
6837
+ return new Uint8Array(await response.arrayBuffer());
6838
+ } catch (error) {
6839
+ if (error instanceof Error && error.name === "AbortError") {
6840
+ throw operationalError(
6841
+ `Timed out downloading ${kind} after ${timeoutMs}ms.`,
6842
+ { url }
6843
+ );
6844
+ }
6845
+ throw error;
6846
+ } finally {
6847
+ clearTimeout(handle);
6848
+ }
6849
+ }
6850
+ function fetchScreenshotBytes(url, timeoutMs) {
6851
+ return fetchArtifactBytes(url, timeoutMs, "screenshot");
6852
+ }
6853
+ function resolveScreenshotPath(out, shot, index, total) {
6854
+ const looksLikeDir = out.endsWith("/") || existsSync(out) && statSync(out).isDirectory();
6855
+ if (looksLikeDir) {
6856
+ return join(out, screenshotFilename(shot, index));
6857
+ }
6858
+ if (total > 1) {
6859
+ throw usageError(
6860
+ "--out must be a directory when the iteration rendered multiple screenshots."
6861
+ );
6862
+ }
6863
+ return out;
6864
+ }
6865
+ function collectRepeatable2(value, previous) {
6866
+ return [...previous, value];
6867
+ }
6868
+ var DEFAULT_GATE_WAIT_TIMEOUT_MS = 6e5;
6869
+ async function runEvalGate(options, command) {
6870
+ const globalOptions = getGlobalOptions(command);
6871
+ const policy = policyFromOptions({
6872
+ ...options,
6873
+ noGatingScoreErrors: options.gatingScoreErrors === false
6874
+ });
6875
+ const waitTimeoutMs = options.waitTimeout !== void 0 ? parsePositiveInteger(options.waitTimeout, "--wait-timeout") : DEFAULT_GATE_WAIT_TIMEOUT_MS;
6876
+ let report;
6877
+ try {
6878
+ report = await runPlatformCommand7(
6879
+ options,
6880
+ Math.max(globalOptions.timeout, options.wait ? waitTimeoutMs : 0),
6881
+ async ({ client, signal }) => {
6882
+ const projects = await client.listProjects({}, { signal });
6883
+ const resolution = resolveProject(projects.items, options.project);
6884
+ if (!resolution.ok) {
6885
+ throw usageError(resolution.message);
6886
+ }
6887
+ const project = resolution.project;
6888
+ const deadline = Date.now() + waitTimeoutMs;
6889
+ let run = await client.getEvalRun(
6890
+ { projectId: project.id, runId: options.run },
6891
+ { signal }
6892
+ );
6893
+ while (!TERMINAL_RUN_STATUSES.has(run.status)) {
6894
+ if (!options.wait) {
6895
+ return {
6896
+ outcome: "incomplete",
6897
+ scoreIntegrity: "unknown",
6898
+ verdicts: [
6899
+ {
6900
+ gate: "run",
6901
+ status: "non_gateable",
6902
+ message: `run is ${run.status}; pass --wait, or gate it once it finishes`
6903
+ }
6904
+ ]
6905
+ };
6906
+ }
6907
+ if (Date.now() >= deadline) {
6908
+ return {
6909
+ outcome: "incomplete",
6910
+ scoreIntegrity: "unknown",
6911
+ verdicts: [
6912
+ {
6913
+ gate: "wait",
6914
+ status: "non_gateable",
6915
+ message: `run still ${run.status} after ${waitTimeoutMs}ms`
6916
+ }
6917
+ ]
6918
+ };
6919
+ }
6920
+ await new Promise((resolve) => setTimeout(resolve, 3e3));
6921
+ run = await client.getEvalRun(
6922
+ { projectId: project.id, runId: options.run },
6923
+ { signal }
6924
+ );
6925
+ }
6926
+ if (isNonVerdictRunStatus(run.status)) {
6927
+ return {
6928
+ outcome: "incomplete",
6929
+ scoreIntegrity: "unknown",
6930
+ verdicts: [
6931
+ {
6932
+ gate: "run",
6933
+ status: "non_gateable",
6934
+ message: `run is ${run.status}; no verdict was established`
6935
+ }
6936
+ ]
6937
+ };
6938
+ }
6939
+ const iterations = policyNeedsIterations(policy) ? await fetchAllIterations(client, signal, project.id, options.run) : void 0;
6940
+ return reportForRun(run, iterations, policy);
6941
+ }
6942
+ );
6943
+ } catch (error) {
6944
+ if (error instanceof Error && error.exitCode === EVAL_GATE_USAGE_EXIT_CODE) {
6945
+ throw error;
6946
+ }
6947
+ const detail = error instanceof Error ? error.message : String(error);
6948
+ writeResult(
6949
+ {
6950
+ gate: {
6951
+ outcome: "incomplete",
6952
+ scoreIntegrity: "unknown",
6953
+ verdicts: [
6954
+ {
6955
+ gate: "fetch",
6956
+ status: "non_gateable",
6957
+ message: `could not read the run: ${detail}`
6958
+ }
6959
+ ]
6960
+ },
6961
+ exitCode: EVAL_GATE_INCOMPLETE_EXIT_CODE
6962
+ },
6963
+ globalOptions.format
6964
+ );
6965
+ setProcessExitCode(EVAL_GATE_INCOMPLETE_EXIT_CODE);
6966
+ return;
6967
+ }
6968
+ const exitCode = evalGateExitCode(report);
6969
+ writeResult({ gate: report, exitCode }, globalOptions.format);
6970
+ if (globalOptions.format === "human") {
6971
+ process.stderr.write(`${formatGateReport(report)}
6972
+ `);
6973
+ }
6974
+ if (exitCode !== 0) {
6975
+ setProcessExitCode(exitCode);
6976
+ }
6977
+ }
6978
+ async function runEvalCompare(options, command) {
6979
+ const globalOptions = getGlobalOptions(command);
6980
+ const policy = comparePolicyFromOptions(options);
6981
+ const reporter = parseReporterFormat(options.reporter);
6982
+ let outcome;
6983
+ try {
6984
+ outcome = await runPlatformCommand7(
6985
+ options,
6986
+ globalOptions.timeout,
6987
+ async ({ client, signal }) => {
6988
+ const projects = await client.listProjects({}, { signal });
6989
+ const resolution = resolveProject(projects.items, options.project);
6990
+ if (!resolution.ok) {
6991
+ throw usageError(resolution.message);
6992
+ }
6993
+ const project = resolution.project;
6994
+ const compare = await client.compareEvalRun(
6995
+ {
6996
+ projectId: project.id,
6997
+ runId: options.run,
6998
+ ...options.baseRun ? { baseRunId: options.baseRun } : {}
6999
+ },
7000
+ { signal }
7001
+ );
7002
+ const needsIterations = policy.maximumP95LatencyIncreaseMs !== void 0;
7003
+ const [baseIterations, compareIterations] = needsIterations ? await Promise.all([
7004
+ fetchAllIterations(
7005
+ client,
7006
+ signal,
7007
+ project.id,
7008
+ compare.baseRun.id
7009
+ ),
7010
+ fetchAllIterations(
7011
+ client,
7012
+ signal,
7013
+ project.id,
7014
+ compare.compareRun.id
7015
+ )
7016
+ ]) : [
7017
+ void 0,
7018
+ await fetchAllIterations(
7019
+ client,
7020
+ signal,
7021
+ project.id,
7022
+ compare.compareRun.id
7023
+ )
7024
+ ];
7025
+ if (compare.baseRun.completedAt === null || compare.compareRun.completedAt === null) {
7026
+ return {
7027
+ report: {
7028
+ outcome: "incomplete",
7029
+ scoreIntegrity: "unknown",
7030
+ verdicts: [
7031
+ {
7032
+ gate: "run",
7033
+ status: "non_gateable",
7034
+ message: "both runs must be completed before they can be compared"
7035
+ }
7036
+ ]
7037
+ },
7038
+ compare,
7039
+ flakyCases: []
7040
+ };
7041
+ }
7042
+ const input = compareGateInputFrom(compare, {
7043
+ baseP95Ms: p95Of(baseIterations),
7044
+ compareP95Ms: p95Of(compareIterations)
7045
+ });
7046
+ return {
7047
+ report: evaluateCompareGates(input, policy),
7048
+ compare,
7049
+ // Reported, NEVER gated. See `detectFlakyCases`.
7050
+ flakyCases: compareIterations?.complete ? detectFlakyCases(flakyInputFrom(compareIterations.items)) : []
7051
+ };
7052
+ }
7053
+ );
7054
+ } catch (error) {
7055
+ if (error instanceof Error && error.exitCode === EVAL_GATE_USAGE_EXIT_CODE) {
7056
+ throw error;
7057
+ }
7058
+ const reason = baselineNotFoundReason(error);
7059
+ const detail = error instanceof Error ? error.message : String(error);
7060
+ const report = {
7061
+ outcome: "incomplete",
7062
+ scoreIntegrity: "unknown",
7063
+ verdicts: [
7064
+ {
7065
+ gate: reason ? "baseline" : "fetch",
7066
+ status: "non_gateable",
7067
+ message: reason ? `no baseline to compare against: ${detail}` : `could not compare the runs: ${detail}`
7068
+ }
7069
+ ]
7070
+ };
7071
+ await writeCompareResult(
7072
+ { report, reporter, out: options.out, format: globalOptions.format },
7073
+ // Built whenever EITHER output channel was requested. `--reporter` needs
7074
+ // it to emit JUnit rather than JSON; `--out` needs it so a CI step
7075
+ // reading the artifact finds the verdict instead of a missing file.
7076
+ reporter || options.out ? emptyCompareReport(report) : void 0
7077
+ );
7078
+ setProcessExitCode(EVAL_GATE_INCOMPLETE_EXIT_CODE);
7079
+ return;
7080
+ }
7081
+ const exitCode = evalGateExitCode(outcome.report);
7082
+ await writeCompareResult(
7083
+ {
7084
+ report: outcome.report,
7085
+ reporter,
7086
+ out: options.out,
7087
+ format: globalOptions.format
7088
+ },
7089
+ outcome.compare ? buildRunCompareReport(outcome.compare, outcome.report, {
7090
+ flakyCases: outcome.flakyCases
7091
+ }) : void 0
7092
+ );
7093
+ if (globalOptions.format === "human" && !reporter) {
7094
+ process.stderr.write(`${formatGateReport(outcome.report)}
7095
+ `);
7096
+ }
7097
+ if (exitCode !== 0) {
7098
+ setProcessExitCode(exitCode);
5473
7099
  }
5474
- if (options.judgeModel !== void 0) judge.model = options.judgeModel;
5475
- if (Object.keys(judge).length > 0) settings.judge = judge;
5476
- if (Object.keys(settings).length > 0) input.settings = settings;
5477
- return input;
5478
- }
5479
- function buildCaseInput(options, opts) {
5480
- const input = { ...loadBodyObject(options) };
5481
- if (options.project !== void 0) input.project = options.project;
5482
- input.suite = options.suite;
5483
- if (opts.requireCase) input.case = options.case;
5484
- if (options.title !== void 0) input.title = options.title;
5485
- return input;
5486
7100
  }
5487
- async function fetchArtifactBytes(url, timeoutMs, kind = "screenshot") {
5488
- const controller = new AbortController();
5489
- const handle = setTimeout(() => controller.abort(), timeoutMs);
5490
- handle.unref?.();
7101
+ async function runEvalPull(options, command) {
7102
+ const globalOptions = getGlobalOptions(command);
7103
+ const lockPath = resolveCorpusLockPath(options.lock);
7104
+ const locked = options.frozen ? await readCorpusLock(lockPath) : void 0;
7105
+ let fetched;
5491
7106
  try {
5492
- const response = await fetch(url, { signal: controller.signal });
5493
- if (!response.ok) {
5494
- throw operationalError(
5495
- `Failed to download ${kind} (HTTP ${response.status}).`,
5496
- { url }
5497
- );
5498
- }
5499
- return new Uint8Array(await response.arrayBuffer());
7107
+ fetched = await runPlatformCommand7(
7108
+ options,
7109
+ globalOptions.timeout,
7110
+ async ({ client, signal }) => {
7111
+ const selector = {
7112
+ ...options.project ? { project: options.project } : {},
7113
+ suite: options.suite
7114
+ };
7115
+ const [detail, page] = await Promise.all([
7116
+ getEvalSuiteOperation.execute(selector, { client, signal }),
7117
+ listEvalCasesOperation.execute(selector, { client, signal })
7118
+ ]);
7119
+ if (page.nextCursor) {
7120
+ throw cliError(
7121
+ "CORPUS_TRUNCATED",
7122
+ `Suite "${options.suite}" returned more cases than one page and this CLI cannot follow the cursor. Upgrade @mcpjam/cli.`,
7123
+ CORPUS_INCOMPLETE_EXIT_CODE
7124
+ );
7125
+ }
7126
+ return {
7127
+ suite: {
7128
+ id: detail.id,
7129
+ ...detail.name ? { name: detail.name } : {}
7130
+ },
7131
+ cases: page.items,
7132
+ suiteChecks: detail.settings.checks ?? [],
7133
+ ...detail.settings.matchOptions ? { suiteMatchOptions: detail.settings.matchOptions } : {}
7134
+ };
7135
+ }
7136
+ );
5500
7137
  } catch (error) {
5501
- if (error instanceof Error && error.name === "AbortError") {
5502
- throw operationalError(
5503
- `Timed out downloading ${kind} after ${timeoutMs}ms.`,
5504
- { url }
7138
+ throw corpusFetchFailure(error);
7139
+ }
7140
+ let corpus;
7141
+ try {
7142
+ corpus = buildCorpus({
7143
+ ...options.project ? { project: options.project } : {},
7144
+ suite: fetched.suite,
7145
+ cases: fetched.cases,
7146
+ suiteChecks: fetched.suiteChecks,
7147
+ ...fetched.suiteMatchOptions ? { suiteMatchOptions: fetched.suiteMatchOptions } : {},
7148
+ unsupported: options.skipUnsupported ? "skip" : "error",
7149
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
7150
+ });
7151
+ } catch (error) {
7152
+ if (error instanceof HostedOnlyCaseError) {
7153
+ throw cliError(
7154
+ "CORPUS_HOSTED_ONLY_CASE",
7155
+ `${error.message} Pass --skip-unsupported to omit cases like this from the corpus and the lock.`,
7156
+ CORPUS_USAGE_EXIT_CODE,
7157
+ { caseId: error.caseId, caseTitle: error.caseTitle }
5505
7158
  );
5506
7159
  }
5507
- throw error;
5508
- } finally {
5509
- clearTimeout(handle);
7160
+ throw cliError(
7161
+ "CORPUS_INVALID_CASE",
7162
+ error instanceof Error ? error.message : String(error),
7163
+ CORPUS_USAGE_EXIT_CODE
7164
+ );
7165
+ }
7166
+ const summary = {
7167
+ suite: corpus.suite,
7168
+ cases: corpus.cases.length,
7169
+ skipped: corpus.skipped,
7170
+ evaluationConfigHash: corpus.lock.evaluationConfigHash
7171
+ };
7172
+ if (locked) {
7173
+ const drift = verifyCorpusLock(locked, corpus.lock);
7174
+ writeResult(
7175
+ { ...summary, lockPath, frozen: true, drift },
7176
+ globalOptions.format
7177
+ );
7178
+ if (globalOptions.format === "human") {
7179
+ process.stderr.write(`${renderCorpusDrift(drift)}
7180
+ `);
7181
+ }
7182
+ if (drift.length > 0) {
7183
+ setProcessExitCode(CORPUS_DRIFT_EXIT_CODE);
7184
+ }
7185
+ return;
5510
7186
  }
7187
+ const written = await writeCorpusLockAtomic(lockPath, corpus.lock);
7188
+ writeResult(
7189
+ { ...summary, lockPath: written, written: true },
7190
+ globalOptions.format
7191
+ );
5511
7192
  }
5512
- function fetchScreenshotBytes(url, timeoutMs) {
5513
- return fetchArtifactBytes(url, timeoutMs, "screenshot");
7193
+ function emptyCompareReport(report) {
7194
+ return buildRunCompareReport(
7195
+ {
7196
+ suite: { id: "", name: "" },
7197
+ baseline: { policy: "previous_completed", baseRunId: "" },
7198
+ baseRun: {
7199
+ id: "",
7200
+ runNumber: 0,
7201
+ result: "",
7202
+ createdAt: 0,
7203
+ completedAt: null,
7204
+ summary: null
7205
+ },
7206
+ compareRun: {
7207
+ id: "",
7208
+ runNumber: 0,
7209
+ result: "",
7210
+ createdAt: 0,
7211
+ completedAt: null,
7212
+ summary: null
7213
+ },
7214
+ passSummary: {
7215
+ passRatePercent: EMPTY_DIFF,
7216
+ total: EMPTY_DIFF,
7217
+ passed: EMPTY_DIFF,
7218
+ failed: EMPTY_DIFF
7219
+ },
7220
+ metrics: {
7221
+ wallDurationMs: EMPTY_DIFF,
7222
+ totalTokens: EMPTY_DIFF,
7223
+ estimatedCostUsd: EMPTY_DIFF
7224
+ },
7225
+ scoreContract: {
7226
+ base: {
7227
+ evaluationConfigHash: null,
7228
+ scoreIntegrity: null,
7229
+ scoredIterations: 0,
7230
+ quarantinedIterations: 0
7231
+ },
7232
+ compare: {
7233
+ evaluationConfigHash: null,
7234
+ scoreIntegrity: null,
7235
+ scoredIterations: 0,
7236
+ quarantinedIterations: 0
7237
+ },
7238
+ evaluationConfigChanged: false,
7239
+ scorers: []
7240
+ },
7241
+ cases: []
7242
+ },
7243
+ report
7244
+ );
5514
7245
  }
5515
- function resolveScreenshotPath(out, shot, index, total) {
5516
- const looksLikeDir = out.endsWith("/") || existsSync(out) && statSync(out).isDirectory();
5517
- if (looksLikeDir) {
5518
- return join(out, screenshotFilename(shot, index));
7246
+ var EMPTY_DIFF = {
7247
+ base: null,
7248
+ compare: null,
7249
+ delta: null,
7250
+ percentDelta: null
7251
+ };
7252
+ function p95Of(iterations) {
7253
+ if (!iterations?.complete) return void 0;
7254
+ const durations = iterations.items.map((iteration) => iteration.durationMs).filter((ms) => typeof ms === "number");
7255
+ if (durations.length === 0 || durations.length !== iterations.items.length) {
7256
+ return void 0;
5519
7257
  }
5520
- if (total > 1) {
5521
- throw usageError(
5522
- "--out must be a directory when the iteration rendered multiple screenshots."
5523
- );
7258
+ return calculateLatencyStats(durations).p95;
7259
+ }
7260
+ function baselineNotFoundReason(error) {
7261
+ const details = error?.details;
7262
+ return typeof details === "object" && details !== null && details.reason === "BASELINE_NOT_FOUND";
7263
+ }
7264
+ async function writeCompareResult(args, structured) {
7265
+ if (args.out && structured) {
7266
+ await writeJsonArtifact(args.out, structured);
5524
7267
  }
5525
- return out;
7268
+ if (args.reporter && structured) {
7269
+ writeReporterResult(args.reporter, structured);
7270
+ return;
7271
+ }
7272
+ writeResult(
7273
+ { compare: args.report, exitCode: evalGateExitCode(args.report) },
7274
+ args.format
7275
+ );
5526
7276
  }
5527
7277
  function registerEvalCommands(program) {
5528
7278
  const evals = program.command("eval").description("Author and run eval suites in your hosted MCPJam projects");
5529
- addPlatformOptions6(
7279
+ addPlatformOptions7(
5530
7280
  evals.command("create").description(
5531
7281
  "Create a runnable eval suite from authored test cases (does not run it)"
5532
7282
  ).option(
@@ -5551,21 +7301,21 @@ function registerEvalCommands(program) {
5551
7301
  ).action(async (options, command) => {
5552
7302
  const globalOptions = getGlobalOptions(command);
5553
7303
  const input = loadSuiteDefinition(options);
5554
- const result = await runPlatformCommand6(
7304
+ const result = await runPlatformCommand7(
5555
7305
  options,
5556
7306
  globalOptions.timeout,
5557
7307
  ({ client, signal }) => createEvalSuiteOperation.execute(input, { client, signal })
5558
7308
  );
5559
7309
  writeResult(result, globalOptions.format);
5560
7310
  });
5561
- addPlatformOptions6(
7311
+ addPlatformOptions7(
5562
7312
  evals.command("list").description("List the eval suites saved in a project").option(
5563
7313
  "--project <id-or-name>",
5564
7314
  "Project name or ID (defaults to the most recently updated project)"
5565
7315
  )
5566
7316
  ).action(async (options, command) => {
5567
7317
  const globalOptions = getGlobalOptions(command);
5568
- const result = await runPlatformCommand6(
7318
+ const result = await runPlatformCommand7(
5569
7319
  options,
5570
7320
  globalOptions.timeout,
5571
7321
  ({ client, signal }) => listEvalSuitesOperation.execute(
@@ -5575,7 +7325,7 @@ function registerEvalCommands(program) {
5575
7325
  );
5576
7326
  writeResult(result, globalOptions.format);
5577
7327
  });
5578
- addPlatformOptions6(
7328
+ addPlatformOptions7(
5579
7329
  evals.command("runs").description("List a suite's run history, newest first").requiredOption("--suite <id-or-name>", "Eval suite name or ID").option(
5580
7330
  "--project <id-or-name>",
5581
7331
  "Project name or ID (defaults to the most recently updated project)"
@@ -5594,7 +7344,7 @@ function registerEvalCommands(program) {
5594
7344
  await executeOp2(listEvalSuiteRunsOperation, input, options, command);
5595
7345
  }
5596
7346
  );
5597
- addPlatformOptions6(
7347
+ addPlatformOptions7(
5598
7348
  evals.command("run").description("Start an eval run of an existing suite (asynchronous)").requiredOption("--suite <id-or-name>", "Eval suite name or ID").option(
5599
7349
  "--project <id-or-name>",
5600
7350
  "Project name or ID (defaults to the most recently updated project)"
@@ -5609,7 +7359,7 @@ function registerEvalCommands(program) {
5609
7359
  async (options, command) => {
5610
7360
  const globalOptions = getGlobalOptions(command);
5611
7361
  let webOrigin = DEFAULT_PLATFORM_ORIGIN;
5612
- const result = await runPlatformCommand6(
7362
+ const result = await runPlatformCommand7(
5613
7363
  options,
5614
7364
  globalOptions.timeout,
5615
7365
  (context) => {
@@ -5633,13 +7383,13 @@ function registerEvalCommands(program) {
5633
7383
  });
5634
7384
  }
5635
7385
  );
5636
- addPlatformOptions6(
7386
+ addPlatformOptions7(
5637
7387
  evals.command("status").description("Get the status and summary of an eval run").requiredOption("--run <id>", "Eval run ID (from `eval run`)").requiredOption("--project <id-or-name>", "Project name or ID")
5638
7388
  ).action(
5639
7389
  async (options, command) => {
5640
7390
  const globalOptions = getGlobalOptions(command);
5641
7391
  let webOrigin = DEFAULT_PLATFORM_ORIGIN;
5642
- const result = await runPlatformCommand6(
7392
+ const result = await runPlatformCommand7(
5643
7393
  options,
5644
7394
  globalOptions.timeout,
5645
7395
  (context) => {
@@ -5658,7 +7408,7 @@ function registerEvalCommands(program) {
5658
7408
  });
5659
7409
  }
5660
7410
  );
5661
- addPlatformOptions6(
7411
+ addPlatformOptions7(
5662
7412
  evals.command("cancel").description(
5663
7413
  "Cancel an in-flight eval run (no-op if already cancelled; errors if it already finished)"
5664
7414
  ).requiredOption("--run <id>", "Eval run ID (from `eval run`)").requiredOption("--project <id-or-name>", "Project name or ID")
@@ -5673,7 +7423,7 @@ function registerEvalCommands(program) {
5673
7423
  }
5674
7424
  );
5675
7425
  const PROJECT_OPT = "Project name or ID (defaults to most recently updated)";
5676
- addPlatformOptions6(
7426
+ addPlatformOptions7(
5677
7427
  evals.command("iterations").description(
5678
7428
  "List per-iteration results for an eval run (pass/fail, tool calls, tokens, latency)"
5679
7429
  ).requiredOption("--run <id>", "Eval run ID (from `eval run`)").requiredOption(
@@ -5691,7 +7441,92 @@ function registerEvalCommands(program) {
5691
7441
  await executeOp2(listEvalRunIterationsOperation, input, options, command);
5692
7442
  }
5693
7443
  );
5694
- addPlatformOptions6(
7444
+ addPlatformOptions7(
7445
+ evals.command("gate").description(
7446
+ "Apply a pass/fail policy to a finished eval run and set an exit code (0 pass, 1 eval failure, 2 usage, 3 incomplete)"
7447
+ ).requiredOption("--run <id>", "Eval run ID (from `eval run`)").requiredOption(
7448
+ "--project <id-or-name>",
7449
+ "Project the run belongs to (name or ID)"
7450
+ ).option(
7451
+ "--min-pass-rate-percent <0-100>",
7452
+ "Minimum share of iterations that must pass, as a percentage"
7453
+ ).option(
7454
+ "--no-gating-score-errors",
7455
+ "Fail if any gating scorer errored during the run"
7456
+ ).option(
7457
+ "--min-scorer-pass-rate <scorerId=percent>",
7458
+ "Minimum pass rate for one scorer (repeatable)",
7459
+ collectRepeatable2,
7460
+ []
7461
+ ).option(
7462
+ "--min-mean-score <scorerId=0..1>",
7463
+ "Minimum mean score for one scorer (repeatable)",
7464
+ collectRepeatable2,
7465
+ []
7466
+ ).option("--wait", "Poll until the run reaches a terminal status").option(
7467
+ "--wait-timeout <ms>",
7468
+ "Give up waiting after this many milliseconds (default 600000)"
7469
+ )
7470
+ ).action(
7471
+ async (options, command) => {
7472
+ await runEvalGate(options, command);
7473
+ }
7474
+ );
7475
+ addPlatformOptions7(
7476
+ evals.command("compare").description(
7477
+ "Compare a finished eval run against a baseline and set an exit code (0 pass, 1 regression, 2 usage, 3 incomplete)"
7478
+ ).requiredOption("--run <id>", "Eval run ID to compare").requiredOption(
7479
+ "--project <id-or-name>",
7480
+ "Project the run belongs to (name or ID)"
7481
+ ).option(
7482
+ "--base-run <id>",
7483
+ "Baseline run ID (defaults to the nearest earlier completed run in the same suite)"
7484
+ ).option(
7485
+ "--gate-regressions",
7486
+ "Fail on a statistically significant pass-rate regression"
7487
+ ).option(
7488
+ "--min-sample-size <n>",
7489
+ "Iterations required on EACH side before a pass-rate regression is decidable (default 5)"
7490
+ ).option(
7491
+ "--min-effect-size-percent <0-100>",
7492
+ "Smallest pass-rate drop worth failing on, as a percentage (default 1)"
7493
+ ).option(
7494
+ "--gate-deterministic-regressions",
7495
+ "Fail if a deterministic gating scorer flipped from passed to failed"
7496
+ ).option(
7497
+ "--max-p95-latency-increase-ms <ms>",
7498
+ "Fail if p95 end-to-end latency rose by more than this many milliseconds"
7499
+ ).option(
7500
+ "--reporter <json-summary|junit-xml>",
7501
+ "Write a structured report to stdout instead of the default output"
7502
+ ).option("--out <path>", "Write the structured report to a JSON file")
7503
+ ).action(
7504
+ async (options, command) => {
7505
+ await runEvalCompare(options, command);
7506
+ }
7507
+ );
7508
+ addPlatformOptions7(
7509
+ evals.command("pull").description(
7510
+ "Materialize a hosted eval suite into a local corpus lock (0 clean, 1 drift under --frozen, 2 usage, 3 incomplete)"
7511
+ ).requiredOption("--suite <id-or-name>", "Eval suite to pull (name or ID)").option(
7512
+ "--project <id-or-name>",
7513
+ "Project the suite belongs to (defaults to the most recently updated project)"
7514
+ ).option(
7515
+ "--lock <path>",
7516
+ `Lock file path (default ${DEFAULT_CORPUS_LOCK_PATH})`
7517
+ ).option(
7518
+ "--frozen",
7519
+ "Verify the lock matches the hosted suite without writing; exit 1 on drift"
7520
+ ).option(
7521
+ "--skip-unsupported",
7522
+ "Omit cases a local run cannot execute instead of failing"
7523
+ )
7524
+ ).action(
7525
+ async (options, command) => {
7526
+ await runEvalPull(options, command);
7527
+ }
7528
+ );
7529
+ addPlatformOptions7(
5695
7530
  evals.command("trace").description(
5696
7531
  "Fetch the full trace for one eval iteration (large: full message history + spans)"
5697
7532
  ).requiredOption("--run <id>", "Eval run ID (from `eval run`)").requiredOption(
@@ -5715,7 +7550,7 @@ function registerEvalCommands(program) {
5715
7550
  );
5716
7551
  }
5717
7552
  );
5718
- addPlatformOptions6(
7553
+ addPlatformOptions7(
5719
7554
  evals.command("steps").description(
5720
7555
  "Per-authored-step results for one eval iteration: status (ok/fail/skipped/pending), reason, and evidence (screenshot/video URLs). The fastest way to see WHICH step failed and why."
5721
7556
  ).requiredOption("--run <id>", "Eval run ID (from `eval run`)").requiredOption(
@@ -5739,7 +7574,7 @@ function registerEvalCommands(program) {
5739
7574
  );
5740
7575
  }
5741
7576
  );
5742
- addPlatformOptions6(
7577
+ addPlatformOptions7(
5743
7578
  evals.command("screenshot").description(
5744
7579
  "Show the widget screenshot(s) an eval iteration rendered \u2014 inline when the terminal supports it, otherwise the image URL"
5745
7580
  ).requiredOption("--run <id>", "Eval run ID (from `eval run`)").requiredOption(
@@ -5756,7 +7591,7 @@ function registerEvalCommands(program) {
5756
7591
  async (options, command) => {
5757
7592
  const globalOptions = getGlobalOptions(command);
5758
7593
  const index = options.index !== void 0 ? parsePositiveInteger(options.index, "--index") : void 0;
5759
- const result = await runPlatformCommand6(
7594
+ const result = await runPlatformCommand7(
5760
7595
  options,
5761
7596
  globalOptions.timeout,
5762
7597
  ({ client, signal }) => getEvalIterationTraceOperation.execute(
@@ -5791,15 +7626,15 @@ function registerEvalCommands(program) {
5791
7626
  shot.screenshotUrl,
5792
7627
  globalOptions.timeout
5793
7628
  );
5794
- const path6 = resolveScreenshotPath(
7629
+ const path7 = resolveScreenshotPath(
5795
7630
  options.out,
5796
7631
  shot,
5797
7632
  i,
5798
7633
  shots.length
5799
7634
  );
5800
- mkdirSync(dirname(path6), { recursive: true });
5801
- writeFileSync(path6, bytes);
5802
- saved.push({ ...shot, savedTo: path6 });
7635
+ mkdirSync(dirname(path7), { recursive: true });
7636
+ writeFileSync(path7, bytes);
7637
+ saved.push({ ...shot, savedTo: path7 });
5803
7638
  }
5804
7639
  if (isJson) {
5805
7640
  writeResult({ ...base, items: saved });
@@ -5847,7 +7682,7 @@ function registerEvalCommands(program) {
5847
7682
  }
5848
7683
  }
5849
7684
  );
5850
- addPlatformOptions6(
7685
+ addPlatformOptions7(
5851
7686
  evals.command("video").description(
5852
7687
  "Get the Playwright replay video (.webm) an eval iteration recorded \u2014 prints the URL, or downloads it with --out"
5853
7688
  ).requiredOption("--run <id>", "Eval run ID (from `eval run`)").requiredOption(
@@ -5860,7 +7695,7 @@ function registerEvalCommands(program) {
5860
7695
  ).action(
5861
7696
  async (options, command) => {
5862
7697
  const globalOptions = getGlobalOptions(command);
5863
- const result = await runPlatformCommand6(
7698
+ const result = await runPlatformCommand7(
5864
7699
  options,
5865
7700
  globalOptions.timeout,
5866
7701
  ({ client, signal }) => getEvalIterationTraceOperation.execute(
@@ -5911,7 +7746,7 @@ function registerEvalCommands(program) {
5911
7746
  `);
5912
7747
  }
5913
7748
  );
5914
- addPlatformOptions6(
7749
+ addPlatformOptions7(
5915
7750
  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)
5916
7751
  ).action(
5917
7752
  async (options, command) => {
@@ -5923,7 +7758,7 @@ function registerEvalCommands(program) {
5923
7758
  );
5924
7759
  }
5925
7760
  );
5926
- addPlatformOptions6(
7761
+ addPlatformOptions7(
5927
7762
  evals.command("update").description(
5928
7763
  "Edit an eval suite's settings (only the flags you pass change)"
5929
7764
  ).requiredOption("--suite <id-or-name>", "Eval suite name or ID").option("--project <id-or-name>", PROJECT_OPT).option("--file <path>", "Suite-update JSON body (or - for stdin)").option("--json <json>", "Inline suite-update JSON (or @file, or -)").option("--name <name>", "Rename the suite").option("--description <text>", "Suite description").option(
@@ -5937,7 +7772,7 @@ function registerEvalCommands(program) {
5937
7772
  );
5938
7773
  await executeOp2(updateEvalSuiteOperation, input, options, command);
5939
7774
  });
5940
- addPlatformOptions6(
7775
+ addPlatformOptions7(
5941
7776
  evals.command("delete").description("Permanently delete an eval suite (and its cases and runs)").requiredOption("--suite <id-or-name>", "Eval suite name or ID").option("--project <id-or-name>", PROJECT_OPT)
5942
7777
  ).action(
5943
7778
  async (options, command) => {
@@ -5949,7 +7784,7 @@ function registerEvalCommands(program) {
5949
7784
  );
5950
7785
  }
5951
7786
  );
5952
- addPlatformOptions6(
7787
+ addPlatformOptions7(
5953
7788
  evals.command("schedule").description("Enable or disable scheduled runs for a suite").requiredOption("--suite <id-or-name>", "Eval suite name or ID").option("--project <id-or-name>", PROJECT_OPT).option("--enable", "Enable scheduled runs").option("--disable", "Disable scheduled runs").option("--interval <minutes>", "Run interval in minutes (5\u201310080)").option(
5954
7789
  "--environment <id-or-name>",
5955
7790
  "Project environment the scheduled runs launch (only with --enable)"
@@ -5975,7 +7810,7 @@ function registerEvalCommands(program) {
5975
7810
  const environments = evals.command("environments").description(
5976
7811
  "Attach or detach the project environments an eval suite runs against"
5977
7812
  );
5978
- addPlatformOptions6(
7813
+ addPlatformOptions7(
5979
7814
  environments.command("set").description(
5980
7815
  "Replace the suite's attached environments (this sets the whole list)"
5981
7816
  ).requiredOption("--suite <id-or-name>", "Eval suite name or ID").requiredOption(
@@ -5996,7 +7831,7 @@ function registerEvalCommands(program) {
5996
7831
  );
5997
7832
  }
5998
7833
  );
5999
- addPlatformOptions6(
7834
+ addPlatformOptions7(
6000
7835
  environments.command("clear").description(
6001
7836
  "Detach every environment, reverting the suite to its saved server selection"
6002
7837
  ).requiredOption("--suite <id-or-name>", "Eval suite name or ID").option("--project <id-or-name>", PROJECT_OPT)
@@ -6015,7 +7850,7 @@ function registerEvalCommands(program) {
6015
7850
  }
6016
7851
  );
6017
7852
  const cases = evals.command("cases").description("List, author, and edit an eval suite's test cases");
6018
- addPlatformOptions6(
7853
+ addPlatformOptions7(
6019
7854
  cases.command("list").description("List a suite's test cases").requiredOption("--suite <id-or-name>", "Eval suite name or ID").option("--project <id-or-name>", PROJECT_OPT)
6020
7855
  ).action(
6021
7856
  async (options, command) => {
@@ -6027,7 +7862,7 @@ function registerEvalCommands(program) {
6027
7862
  );
6028
7863
  }
6029
7864
  );
6030
- addPlatformOptions6(
7865
+ addPlatformOptions7(
6031
7866
  cases.command("get").description("Show one test case").requiredOption("--suite <id-or-name>", "Eval suite name or ID").requiredOption("--case <id-or-title>", "Eval case title or ID").option("--project <id-or-name>", PROJECT_OPT)
6032
7867
  ).action(
6033
7868
  async (options, command) => {
@@ -6039,7 +7874,7 @@ function registerEvalCommands(program) {
6039
7874
  );
6040
7875
  }
6041
7876
  );
6042
- addPlatformOptions6(
7877
+ addPlatformOptions7(
6043
7878
  cases.command("run").description(
6044
7879
  "Run a single case as a persisted, fully-queryable run (inspect it with `eval iterations` / `eval steps` like any run)"
6045
7880
  ).requiredOption("--suite <id-or-name>", "Eval suite name or ID").requiredOption("--case <id-or-title>", "Eval case title or ID").option("--project <id-or-name>", PROJECT_OPT).option(
@@ -6065,7 +7900,7 @@ function registerEvalCommands(program) {
6065
7900
  );
6066
7901
  }
6067
7902
  );
6068
- addPlatformOptions6(
7903
+ addPlatformOptions7(
6069
7904
  cases.command("create").description("Add a test case to a suite (definition via --file/--json)").requiredOption("--suite <id-or-name>", "Eval suite name or ID").option("--project <id-or-name>", PROJECT_OPT).option("--file <path>", "Case JSON body (or - for stdin)").option("--json <json>", "Inline case JSON (or @file, or -)").option("--title <title>", "Case title (overrides the body)")
6070
7905
  ).action(async (options, command) => {
6071
7906
  const input = validateOpInput2(
@@ -6074,7 +7909,7 @@ function registerEvalCommands(program) {
6074
7909
  );
6075
7910
  await executeOp2(createEvalCaseOperation, input, options, command);
6076
7911
  });
6077
- addPlatformOptions6(
7912
+ addPlatformOptions7(
6078
7913
  cases.command("update").description("Edit a test case (definition via --file/--json)").requiredOption("--suite <id-or-name>", "Eval suite name or ID").requiredOption("--case <id-or-title>", "Eval case title or ID").option("--project <id-or-name>", PROJECT_OPT).option("--file <path>", "Case JSON body (or - for stdin)").option("--json <json>", "Inline case JSON (or @file, or -)").option("--title <title>", "Rename the case")
6079
7914
  ).action(async (options, command) => {
6080
7915
  const input = validateOpInput2(
@@ -6083,7 +7918,7 @@ function registerEvalCommands(program) {
6083
7918
  );
6084
7919
  await executeOp2(updateEvalCaseOperation, input, options, command);
6085
7920
  });
6086
- addPlatformOptions6(
7921
+ addPlatformOptions7(
6087
7922
  cases.command("delete").description("Permanently delete a test case").requiredOption("--suite <id-or-name>", "Eval suite name or ID").requiredOption("--case <id-or-title>", "Eval case title or ID").option("--project <id-or-name>", PROJECT_OPT)
6088
7923
  ).action(
6089
7924
  async (options, command) => {
@@ -6095,7 +7930,7 @@ function registerEvalCommands(program) {
6095
7930
  );
6096
7931
  }
6097
7932
  );
6098
- addPlatformOptions6(
7933
+ addPlatformOptions7(
6099
7934
  cases.command("generate").description(
6100
7935
  "AI-generate test cases from the suite's tools (spends credits)"
6101
7936
  ).requiredOption("--suite <id-or-name>", "Eval suite name or ID").option("--project <id-or-name>", PROJECT_OPT).option("--mode <normal|negative>", "Generation mode (default normal)").option(
@@ -6148,13 +7983,13 @@ function registerEvalCommands(program) {
6148
7983
  );
6149
7984
  }
6150
7985
  var HOST_TEMPLATES = HOST_TEMPLATES$1.map(({ id, label }) => ({ id, label }));
6151
- function addPlatformOptions7(command) {
7986
+ function addPlatformOptions8(command) {
6152
7987
  return command.option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
6153
7988
  "--api-url <url>",
6154
7989
  "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
6155
7990
  );
6156
7991
  }
6157
- async function runPlatformCommand7(options, timeoutMs, execute) {
7992
+ async function runPlatformCommand8(options, timeoutMs, execute) {
6158
7993
  const controller = new AbortController();
6159
7994
  const timeoutHandle = setTimeout(() => {
6160
7995
  controller.abort(
@@ -6222,14 +8057,14 @@ function registerHostsCommands(program) {
6222
8057
  const globalOptions = getGlobalOptions(command);
6223
8058
  writeResult({ items: HOST_TEMPLATES }, globalOptions.format);
6224
8059
  });
6225
- addPlatformOptions7(
8060
+ addPlatformOptions8(
6226
8061
  hosts.command("list").description("List the hosts saved in a project").option(
6227
8062
  "--project <id-or-name>",
6228
8063
  "Project name or ID (defaults to the most recently updated project)"
6229
8064
  )
6230
8065
  ).action(async (options, command) => {
6231
8066
  const globalOptions = getGlobalOptions(command);
6232
- const result = await runPlatformCommand7(
8067
+ const result = await runPlatformCommand8(
6233
8068
  options,
6234
8069
  globalOptions.timeout,
6235
8070
  ({ client, signal }) => listHostsOperation.execute(
@@ -6239,12 +8074,12 @@ function registerHostsCommands(program) {
6239
8074
  );
6240
8075
  writeResult(result, globalOptions.format);
6241
8076
  });
6242
- addPlatformOptions7(
8077
+ addPlatformOptions8(
6243
8078
  hosts.command("get").description("Show one host's full settings, including its host config").requiredOption("--host <id-or-name>", "Host name or ID").option("--project <id-or-name>", "Project name or ID")
6244
8079
  ).action(
6245
8080
  async (options, command) => {
6246
8081
  const globalOptions = getGlobalOptions(command);
6247
- const result = await runPlatformCommand7(
8082
+ const result = await runPlatformCommand8(
6248
8083
  options,
6249
8084
  globalOptions.timeout,
6250
8085
  ({ client, signal }) => getHostOperation.execute(
@@ -6255,7 +8090,7 @@ function registerHostsCommands(program) {
6255
8090
  writeResult(result, globalOptions.format);
6256
8091
  }
6257
8092
  );
6258
- addPlatformOptions7(
8093
+ addPlatformOptions8(
6259
8094
  hosts.command("create").description(
6260
8095
  "Create a host from a built-in template (--template) or a full host config (--file/--json)"
6261
8096
  ).requiredOption("--name <name>", "Display name for the new host").option("--project <id-or-name>", "Project name or ID").option(
@@ -6276,7 +8111,7 @@ function registerHostsCommands(program) {
6276
8111
  ...options.theme !== void 0 ? { theme: options.theme } : {},
6277
8112
  ...config !== void 0 ? { config } : {}
6278
8113
  });
6279
- const result = await runPlatformCommand7(
8114
+ const result = await runPlatformCommand8(
6280
8115
  options,
6281
8116
  globalOptions.timeout,
6282
8117
  ({ client, signal }) => createHostOperation.execute(input, { client, signal })
@@ -6284,7 +8119,7 @@ function registerHostsCommands(program) {
6284
8119
  writeResult(result, globalOptions.format);
6285
8120
  }
6286
8121
  );
6287
- addPlatformOptions7(
8122
+ addPlatformOptions8(
6288
8123
  hosts.command("update").description("Edit a host's name and/or its host config").requiredOption("--host <id-or-name>", "Host name or ID").option("--project <id-or-name>", "Project name or ID").option("--name <name>", "New display name").option(
6289
8124
  "--file <path>",
6290
8125
  "Replacement host config v2 JSON (or - for stdin)"
@@ -6302,7 +8137,7 @@ function registerHostsCommands(program) {
6302
8137
  ...options.name !== void 0 ? { name: options.name } : {},
6303
8138
  ...config !== void 0 ? { config } : {}
6304
8139
  });
6305
- const result = await runPlatformCommand7(
8140
+ const result = await runPlatformCommand8(
6306
8141
  options,
6307
8142
  globalOptions.timeout,
6308
8143
  ({ client, signal }) => updateHostOperation.execute(input, { client, signal })
@@ -6310,12 +8145,12 @@ function registerHostsCommands(program) {
6310
8145
  writeResult(result, globalOptions.format);
6311
8146
  }
6312
8147
  );
6313
- addPlatformOptions7(
8148
+ addPlatformOptions8(
6314
8149
  hosts.command("delete").description("Permanently delete a host from a project").requiredOption("--host <id-or-name>", "Host name or ID").option("--project <id-or-name>", "Project name or ID")
6315
8150
  ).action(
6316
8151
  async (options, command) => {
6317
8152
  const globalOptions = getGlobalOptions(command);
6318
- const result = await runPlatformCommand7(
8153
+ const result = await runPlatformCommand8(
6319
8154
  options,
6320
8155
  globalOptions.timeout,
6321
8156
  ({ client, signal }) => deleteHostOperation.execute(
@@ -6329,7 +8164,7 @@ function registerHostsCommands(program) {
6329
8164
  writeResult(result, globalOptions.format);
6330
8165
  }
6331
8166
  );
6332
- addPlatformOptions7(
8167
+ addPlatformOptions8(
6333
8168
  hosts.command("servers").description("Replace a host's required and optional server attachments").requiredOption("--host <id-or-name>", "Host name or ID").requiredOption(
6334
8169
  "--server-ids <ids>",
6335
8170
  "Comma-separated required server IDs"
@@ -6347,7 +8182,7 @@ function registerHostsCommands(program) {
6347
8182
  serverIds: splitIds(options.serverIds),
6348
8183
  ...options.optionalServerIds ? { optionalServerIds: splitIds(options.optionalServerIds) } : {}
6349
8184
  });
6350
- const result = await runPlatformCommand7(
8185
+ const result = await runPlatformCommand8(
6351
8186
  options,
6352
8187
  globalOptions.timeout,
6353
8188
  ({ client, signal }) => setHostServersOperation.execute(input, { client, signal })
@@ -6355,7 +8190,7 @@ function registerHostsCommands(program) {
6355
8190
  writeResult(result, globalOptions.format);
6356
8191
  }
6357
8192
  );
6358
- addPlatformOptions7(
8193
+ addPlatformOptions8(
6359
8194
  hosts.command("duplicate").description("Duplicate a host's current config").requiredOption("--host <id-or-name>", "Host name or ID").option("--name <name>", "Name for the new host").option("--project <id-or-name>", "Project name or ID")
6360
8195
  ).action(
6361
8196
  async (options, command) => {
@@ -6365,7 +8200,7 @@ function registerHostsCommands(program) {
6365
8200
  host: options.host,
6366
8201
  ...options.name === void 0 ? {} : { name: options.name }
6367
8202
  });
6368
- const result = await runPlatformCommand7(
8203
+ const result = await runPlatformCommand8(
6369
8204
  options,
6370
8205
  globalOptions.timeout,
6371
8206
  ({ client, signal }) => duplicateHostOperation.execute(input, { client, signal })
@@ -7149,13 +8984,13 @@ function statusGlyph(status) {
7149
8984
  }
7150
8985
 
7151
8986
  // src/commands/organizations.ts
7152
- function addPlatformOptions8(command) {
8987
+ function addPlatformOptions9(command) {
7153
8988
  return command.option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
7154
8989
  "--api-url <url>",
7155
8990
  "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
7156
8991
  );
7157
8992
  }
7158
- async function runPlatformCommand8(options, timeoutMs, execute) {
8993
+ async function runPlatformCommand9(options, timeoutMs, execute) {
7159
8994
  const controller = new AbortController();
7160
8995
  const timeoutHandle = setTimeout(() => {
7161
8996
  controller.abort(
@@ -7179,7 +9014,7 @@ async function runPlatformCommand8(options, timeoutMs, execute) {
7179
9014
  }
7180
9015
  function registerOrganizationsCommands(program) {
7181
9016
  const organizations = program.command("organizations").alias("orgs").description("Inspect the MCPJam organizations you belong to");
7182
- addPlatformOptions8(
9017
+ addPlatformOptions9(
7183
9018
  organizations.command("list").description(
7184
9019
  "List your organizations and their ids (an sk_ key sees only its own)"
7185
9020
  )
@@ -7188,7 +9023,7 @@ function registerOrganizationsCommands(program) {
7188
9023
  // merge dance like `projects`, whose `servers` group duplicates them.
7189
9024
  ).action(async (options, command) => {
7190
9025
  const globalOptions = getGlobalOptions(command);
7191
- const result = await runPlatformCommand8(
9026
+ const result = await runPlatformCommand9(
7192
9027
  options,
7193
9028
  globalOptions.timeout,
7194
9029
  ({ client, signal }) => listOrganizationsOperation.execute({}, { client, signal })
@@ -7201,7 +9036,65 @@ function registerOrganizationsCommands(program) {
7201
9036
  }
7202
9037
  });
7203
9038
  }
7204
- function addPlatformOptions9(command) {
9039
+ function requireQuery(value) {
9040
+ const trimmed = value?.trim() ?? "";
9041
+ if (trimmed.length === 0) {
9042
+ throw usageError("--query needs search terms.");
9043
+ }
9044
+ return trimmed;
9045
+ }
9046
+ function parseSources(value) {
9047
+ if (value === void 0) return void 0;
9048
+ const parsed = value.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
9049
+ if (parsed.length === 0) {
9050
+ throw usageError(
9051
+ "--source was given but names no surfaces. Pass a comma-separated list (direct, scenario, eval, swarm), or omit the flag to search all of them."
9052
+ );
9053
+ }
9054
+ return parsed;
9055
+ }
9056
+ function registerSessionsCommands(program) {
9057
+ const sessions = program.command("sessions").description(
9058
+ "Search the conversations recorded in a project \u2014 Playground, user testing, evals and swarms in one place."
9059
+ );
9060
+ bindOperation(
9061
+ addProjectOption(
9062
+ sessions.command("search").description(
9063
+ "Search a project's sessions by relevance. Searches titles and opening messages by default; pass --scope transcripts to search what was actually said inside the conversations. Every result carries a link you can open."
9064
+ ).requiredOption("--query <text>", "Search terms").option(
9065
+ "--scope <scope>",
9066
+ "titles (default) or transcripts. Transcript search excludes sessions created before 2026-08-14."
9067
+ ).option(
9068
+ "--source <types>",
9069
+ "Comma-separated surfaces: direct, scenario, eval, swarm. Defaults to all."
9070
+ ).option("--status <status>", "active (default) or archived").option("--limit <n>", "Results per page (1-200)").option(
9071
+ "--cursor <cursor>",
9072
+ "Opaque cursor from a previous page's nextCursor. Page with the same --query and --scope you started with."
9073
+ )
9074
+ ),
9075
+ searchSessionsOperation,
9076
+ (options) => ({
9077
+ // `.requiredOption` guarantees the flag is PRESENT, not that it says
9078
+ // anything — `--query ""` satisfies Commander. The operation rejects a
9079
+ // blank query too (it is search-only), but failing here names the flag
9080
+ // the user typed instead of reporting a validation error about `q`.
9081
+ query: requireQuery(options.query),
9082
+ project: options.project,
9083
+ // Passed through unvalidated: the operation's schema owns the vocabulary
9084
+ // for these, and re-listing the allowed values here would be a second
9085
+ // place to update when one is added.
9086
+ scope: options.scope,
9087
+ sourceTypes: parseSources(options.source),
9088
+ status: options.status,
9089
+ limit: parseIntegerOption(options.limit, "--limit", {
9090
+ min: 1,
9091
+ max: 200
9092
+ }),
9093
+ cursor: options.cursor
9094
+ })
9095
+ );
9096
+ }
9097
+ function addPlatformOptions10(command) {
7205
9098
  return command.option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
7206
9099
  "--api-url <url>",
7207
9100
  "MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
@@ -7227,7 +9120,7 @@ function requireProject(command, options) {
7227
9120
  }
7228
9121
  return project;
7229
9122
  }
7230
- async function runPlatformCommand9(options, timeoutMs, execute, externalSignal) {
9123
+ async function runPlatformCommand10(options, timeoutMs, execute, externalSignal) {
7231
9124
  const controller = new AbortController();
7232
9125
  const timeoutHandle = setTimeout(() => {
7233
9126
  controller.abort(
@@ -7261,7 +9154,7 @@ function registerProjectsCommands(program) {
7261
9154
  const projects = program.command("projects").description(
7262
9155
  "Operate the MCP servers saved in your hosted MCPJam projects"
7263
9156
  );
7264
- addPlatformOptions9(
9157
+ addPlatformOptions10(
7265
9158
  projects.command("list").description("List the projects you can access").option(
7266
9159
  "--organization-id <id>",
7267
9160
  "Restrict the listing to one organization (see `mcpjam organizations list`)"
@@ -7275,7 +9168,7 @@ function registerProjectsCommands(program) {
7275
9168
  );
7276
9169
  }
7277
9170
  const organizationId = rawOrganization?.trim();
7278
- const result = await runPlatformCommand9(
9171
+ const result = await runPlatformCommand10(
7279
9172
  platformOptionsOf(command),
7280
9173
  globalOptions.timeout,
7281
9174
  ({ client, signal }) => listProjectsOperation.execute(
@@ -7290,7 +9183,7 @@ function registerProjectsCommands(program) {
7290
9183
  writeResult(result, globalOptions.format);
7291
9184
  }
7292
9185
  });
7293
- addPlatformOptions9(
9186
+ addPlatformOptions10(
7294
9187
  projects.command("create").description("Create a hosted MCPJam project").requiredOption("--name <name>", "Project name").option("--description <text>", "Project description").option("--organization-id <id>", "Organization ID").option("--visibility <visibility>", "public or private")
7295
9188
  ).action(
7296
9189
  async (options, command) => {
@@ -7301,7 +9194,7 @@ function registerProjectsCommands(program) {
7301
9194
  ...options.organizationId === void 0 ? {} : { organizationId: options.organizationId },
7302
9195
  ...options.visibility === void 0 ? {} : { visibility: options.visibility }
7303
9196
  });
7304
- const result = await runPlatformCommand9(
9197
+ const result = await runPlatformCommand10(
7305
9198
  platformOptionsOf(command),
7306
9199
  globalOptions.timeout,
7307
9200
  ({ client, signal }) => createProjectOperation.execute(input, { client, signal })
@@ -7309,7 +9202,7 @@ function registerProjectsCommands(program) {
7309
9202
  writeResult(result, globalOptions.format);
7310
9203
  }
7311
9204
  );
7312
- addPlatformOptions9(
9205
+ addPlatformOptions10(
7313
9206
  projects.command("update").description("Update project metadata").requiredOption("--project <id-or-name>", "Project name or ID").option("--name <name>", "New project name").option("--description <text>", "New project description").option("--visibility <visibility>", "public or private")
7314
9207
  ).action(
7315
9208
  async (options, command) => {
@@ -7321,7 +9214,7 @@ function registerProjectsCommands(program) {
7321
9214
  ...options.description === void 0 ? {} : { description: options.description },
7322
9215
  ...options.visibility === void 0 ? {} : { visibility: options.visibility }
7323
9216
  });
7324
- const result = await runPlatformCommand9(
9217
+ const result = await runPlatformCommand10(
7325
9218
  platformOptions,
7326
9219
  globalOptions.timeout,
7327
9220
  ({ client, signal }) => updateProjectOperation.execute(input, { client, signal })
@@ -7329,7 +9222,7 @@ function registerProjectsCommands(program) {
7329
9222
  writeResult(result, globalOptions.format);
7330
9223
  }
7331
9224
  );
7332
- addPlatformOptions9(
9225
+ addPlatformOptions10(
7333
9226
  projects.command("delete").description("Delete a project and its project-owned resources").requiredOption("--project <id-or-name>", "Project name or ID")
7334
9227
  ).action(async (_options, command) => {
7335
9228
  const globalOptions = getGlobalOptions(command);
@@ -7337,14 +9230,14 @@ function registerProjectsCommands(program) {
7337
9230
  const input = deleteProjectOperation.inputSchema.parse({
7338
9231
  project: requireProject(command, platformOptions)
7339
9232
  });
7340
- const result = await runPlatformCommand9(
9233
+ const result = await runPlatformCommand10(
7341
9234
  platformOptions,
7342
9235
  globalOptions.timeout,
7343
9236
  ({ client, signal }) => deleteProjectOperation.execute(input, { client, signal })
7344
9237
  );
7345
9238
  writeResult(result, globalOptions.format);
7346
9239
  });
7347
- const servers = addPlatformOptions9(
9240
+ const servers = addPlatformOptions10(
7348
9241
  projects.command("servers").alias("server").description("List and manage the servers saved in a project")
7349
9242
  ).option(
7350
9243
  "--project <id-or-name>",
@@ -7353,7 +9246,7 @@ function registerProjectsCommands(program) {
7353
9246
  servers.action(async (_options, command) => {
7354
9247
  const globalOptions = getGlobalOptions(command);
7355
9248
  const platformOptions = platformOptionsOf(command);
7356
- const result = await runPlatformCommand9(
9249
+ const result = await runPlatformCommand10(
7357
9250
  platformOptions,
7358
9251
  globalOptions.timeout,
7359
9252
  ({ client, signal }) => listProjectServersOperation.execute(
@@ -7375,13 +9268,13 @@ function registerProjectsCommands(program) {
7375
9268
  }
7376
9269
  return parsed;
7377
9270
  };
7378
- addPlatformOptions9(
9271
+ addPlatformOptions10(
7379
9272
  servers.command("create").alias("add").description("Create a saved MCP server").option("--project <id-or-name>", "Project name or ID").requiredOption("--body <json>", "Server JSON body")
7380
9273
  ).action(async (options, command) => {
7381
9274
  const globalOptions = getGlobalOptions(command);
7382
9275
  const platformOptions = platformOptionsOf(command);
7383
9276
  const project = requireProject(command, platformOptions);
7384
- const result = await runPlatformCommand9(
9277
+ const result = await runPlatformCommand10(
7385
9278
  platformOptions,
7386
9279
  globalOptions.timeout,
7387
9280
  ({ client, signal }) => createProjectServerOperation.execute(
@@ -7391,13 +9284,13 @@ function registerProjectsCommands(program) {
7391
9284
  );
7392
9285
  writeResult(result, globalOptions.format);
7393
9286
  });
7394
- addPlatformOptions9(
9287
+ addPlatformOptions10(
7395
9288
  servers.command("get").description("Get one saved MCP server").option("--project <id-or-name>", "Project name or ID").requiredOption("--server <id>", "Server ID")
7396
9289
  ).action(async (options, command) => {
7397
9290
  const globalOptions = getGlobalOptions(command);
7398
9291
  const platformOptions = platformOptionsOf(command);
7399
9292
  const project = requireProject(command, platformOptions);
7400
- const result = await runPlatformCommand9(
9293
+ const result = await runPlatformCommand10(
7401
9294
  platformOptions,
7402
9295
  globalOptions.timeout,
7403
9296
  ({ client, signal }) => getProjectServerOperation.execute(
@@ -7407,14 +9300,14 @@ function registerProjectsCommands(program) {
7407
9300
  );
7408
9301
  writeResult(result, globalOptions.format);
7409
9302
  });
7410
- addPlatformOptions9(
9303
+ addPlatformOptions10(
7411
9304
  servers.command("update").description("Update one saved MCP server").option("--project <id-or-name>", "Project name or ID").requiredOption("--server <id>", "Server ID").requiredOption("--body <json>", "Patch JSON body")
7412
9305
  ).action(
7413
9306
  async (options, command) => {
7414
9307
  const globalOptions = getGlobalOptions(command);
7415
9308
  const platformOptions = platformOptionsOf(command);
7416
9309
  const project = requireProject(command, platformOptions);
7417
- const result = await runPlatformCommand9(
9310
+ const result = await runPlatformCommand10(
7418
9311
  platformOptions,
7419
9312
  globalOptions.timeout,
7420
9313
  ({ client, signal }) => updateProjectServerOperation.execute(
@@ -7429,13 +9322,13 @@ function registerProjectsCommands(program) {
7429
9322
  writeResult(result, globalOptions.format);
7430
9323
  }
7431
9324
  );
7432
- addPlatformOptions9(
9325
+ addPlatformOptions10(
7433
9326
  servers.command("delete").alias("remove").description("Delete one saved MCP server").option("--project <id-or-name>", "Project name or ID").requiredOption("--server <id>", "Server ID")
7434
9327
  ).action(async (options, command) => {
7435
9328
  const globalOptions = getGlobalOptions(command);
7436
9329
  const platformOptions = platformOptionsOf(command);
7437
9330
  const project = requireProject(command, platformOptions);
7438
- const result = await runPlatformCommand9(
9331
+ const result = await runPlatformCommand10(
7439
9332
  platformOptions,
7440
9333
  globalOptions.timeout,
7441
9334
  ({ client, signal }) => deleteProjectServerOperation.execute(
@@ -7445,7 +9338,7 @@ function registerProjectsCommands(program) {
7445
9338
  );
7446
9339
  writeResult(result, globalOptions.format);
7447
9340
  });
7448
- addPlatformOptions9(
9341
+ addPlatformOptions10(
7449
9342
  servers.command("connect").description(
7450
9343
  "Connect an MCP server URL to a project, authorizing in a browser if needed"
7451
9344
  ).requiredOption("--url <url>", "MCP server URL to connect").option("--project <id-or-name>", "Project name or ID").option(
@@ -7467,7 +9360,7 @@ function registerProjectsCommands(program) {
7467
9360
  name: options.name,
7468
9361
  reauthorize: options.reauthorize
7469
9362
  });
7470
- const created = await runPlatformCommand9(
9363
+ const created = await runPlatformCommand10(
7471
9364
  platformOptions,
7472
9365
  globalOptions.timeout,
7473
9366
  ({ client, signal }) => connectProjectServerOperation.execute(input, { client, signal })
@@ -7515,7 +9408,7 @@ function registerProjectsCommands(program) {
7515
9408
  }
7516
9409
  }
7517
9410
  );
7518
- addPlatformOptions9(
9411
+ addPlatformOptions10(
7519
9412
  servers.command("connect-status").description("Check a connection request started by `server connect`").requiredOption("--request <id>", "Connection request id (scr_\u2026)")
7520
9413
  ).action(
7521
9414
  async (options, command) => {
@@ -7523,7 +9416,7 @@ function registerProjectsCommands(program) {
7523
9416
  const input = getProjectServerConnectionStatusOperation.inputSchema.parse({
7524
9417
  connectionRequestId: options.request
7525
9418
  });
7526
- const payload = await runPlatformCommand9(
9419
+ const payload = await runPlatformCommand10(
7527
9420
  platformOptionsOf(command),
7528
9421
  globalOptions.timeout,
7529
9422
  ({ client, signal }) => getProjectServerConnectionStatusOperation.execute(input, {
@@ -7534,7 +9427,7 @@ function registerProjectsCommands(program) {
7534
9427
  writeResult(payload, globalOptions.format);
7535
9428
  }
7536
9429
  );
7537
- addPlatformOptions9(
9430
+ addPlatformOptions10(
7538
9431
  projects.command("status").description(
7539
9432
  "Health-check every server in a project (hosted doctor per server)"
7540
9433
  ).option(
@@ -7544,7 +9437,7 @@ function registerProjectsCommands(program) {
7544
9437
  ).action(async (_options, command) => {
7545
9438
  const globalOptions = getGlobalOptions(command);
7546
9439
  const platformOptions = platformOptionsOf(command);
7547
- const payload = await runPlatformCommand9(
9440
+ const payload = await runPlatformCommand10(
7548
9441
  platformOptions,
7549
9442
  globalOptions.timeout,
7550
9443
  ({ client, signal }) => showServersOperation.execute(
@@ -7591,7 +9484,7 @@ async function pollConnection(options, timeoutMs, connectionRequestId, expiresAt
7591
9484
  for (; ; ) {
7592
9485
  let current;
7593
9486
  try {
7594
- current = await runPlatformCommand9(
9487
+ current = await runPlatformCommand10(
7595
9488
  options,
7596
9489
  timeoutMs,
7597
9490
  ({ client, signal }) => getProjectServerConnectionStatusOperation.execute(
@@ -12196,7 +14089,7 @@ function buildCompactInspectorRender(uiResult, options = {}) {
12196
14089
  hasCommandError = true;
12197
14090
  }
12198
14091
  }
12199
- const topLevelError = options.skipped ? options.issue ? { warning: options.issue } : uiResult.status === "error" && isRecord3(uiResult.error) ? { warning: uiResult.error } : {} : options.issue ? { error: options.issue } : uiResult.status === "error" && isRecord3(uiResult.error) ? { error: uiResult.error } : {};
14092
+ const topLevelError = options.skipped ? options.issue ? { warning: options.issue } : uiResult.status === "error" && isRecord4(uiResult.error) ? { warning: uiResult.error } : {} : options.issue ? { error: options.issue } : uiResult.status === "error" && isRecord4(uiResult.error) ? { error: uiResult.error } : {};
12200
14093
  return {
12201
14094
  status: options.skipped ? "skipped" : hasCommandError || uiResult.status === "error" ? "error" : "rendered",
12202
14095
  remediation: options.remediation ?? "none",
@@ -12225,18 +14118,18 @@ function parseInspectorFrontendUrl(value) {
12225
14118
  return frontendUrl;
12226
14119
  }
12227
14120
  function compactInspectorCommandResponse(value) {
12228
- if (!isRecord3(value) || !isCompactInspectorCommandStatus(value.status)) {
14121
+ if (!isRecord4(value) || !isCompactInspectorCommandStatus(value.status)) {
12229
14122
  return void 0;
12230
14123
  }
12231
14124
  return {
12232
14125
  status: value.status,
12233
- ...value.status === "error" && isRecord3(value.error) ? { error: value.error } : {}
14126
+ ...value.status === "error" && isRecord4(value.error) ? { error: value.error } : {}
12234
14127
  };
12235
14128
  }
12236
14129
  function isCompactInspectorCommandStatus(value) {
12237
14130
  return value === "success" || value === "error";
12238
14131
  }
12239
- function isRecord3(value) {
14132
+ function isRecord4(value) {
12240
14133
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
12241
14134
  }
12242
14135
  function tunnelPathPrefix(serverId) {
@@ -13372,10 +15265,13 @@ async function main(argv = process.argv, dependencies = {}) {
13372
15265
  registerProjectsCommands(program);
13373
15266
  registerEvalCommands(program);
13374
15267
  registerChatCommands(program);
15268
+ registerSessionsCommands(program);
13375
15269
  registerHostsCommands(program);
13376
15270
  registerEnvironmentsCommands(program);
13377
- registerJourneysCommands(program);
15271
+ const journeys = registerJourneysCommands(program);
13378
15272
  registerScenariosCommands(program);
15273
+ registerSwarmAuthoringCommands(program, journeys);
15274
+ registerUserTestingCommands(program);
13379
15275
  registerImagesCommands(program);
13380
15276
  registerTunnelCommands(program);
13381
15277
  registerInspectorCommands(program);