@mcpjam/cli 5.10.3 → 5.11.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
@@ -9,7 +9,7 @@ import { mkdir, writeFile, readFile, chmod, rename, rm, open, unlink, stat } fro
9
9
  import { spawn } from 'child_process';
10
10
  import { createRequire } from 'module';
11
11
  import os, { homedir, tmpdir } from 'os';
12
- import { RUN_LAUNCH_HEADERS, getRegistryDirectoryServerOperation, listOrganizationsOperation, listProjectsOperation, createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, cancelProjectServerConnectionOperation, listChatSessionsOperation, resolveProject, sendChatMessageOperation, createTunnelOperation, listEvalSuiteRunsOperation, listEvalSuiteRevisionsOperation, runEvalSuiteOperation, getEvalRunOperation, getEvalRunRouteFactsOperation, getEvalRunServerFactsOperation, proposeEvalDescriptionRewriteOperation, startEvalDescriptionExperimentOperation, getEvalDescriptionExperimentOperation, cancelEvalRunOperation, backtestEvalRunJudgeOperation, backtestEvalRunOperation, requestEvalRunJudgeOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, createClientOperation, updateClientOperation, setClientServersOperation, duplicateClientOperation, createEnvironmentOperation, ensureAdhocEnvironmentOperation, nameEnvironmentOperation, updateEnvironmentOperation, createSecretOperation, updateSecretOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, listTraceDestinationsOperation, getTraceDestinationOperation, createTraceDestinationOperation, updateTraceDestinationOperation, deleteTraceDestinationOperation, testTraceDestinationOperation, pauseTraceDestinationOperation, resumeTraceDestinationOperation, backfillTraceDestinationOperation, listTraceDestinationBackfillsOperation, runOperationWithPermalinks, withPermalinkEnvelope, PlatformApiError, installRegistryServerOperation, installRegistryDirectoryServerOperation, getProjectServerOperation, DEFAULT_PLATFORM_API_BASE_URL, projectResolutionError, listProjectServersOperation, createProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, driveChatSessionBrowserOperation, observeChatSessionBrowserOperation, isPlatformApiError, describePlatformRefusal, platformRefusalHint, createEvalSuiteOperation, listEvalSuitesOperation, buildAppPermalink, listEvalSuiteStageAnalyticsOperation, getEvalRunStageAnalyticsOperation, listEvalGithubReposOperation, connectEvalGithubRepoOperation, resolveEnvironmentOperation, listClientsOperation, getClientOperation, deleteClientOperation, listEnvironmentsOperation, getEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listSecretsOperation, getSecretOperation, deleteSecretOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, listProjectSkillsOperation, getProjectSkillOperation, listJourneysOperation, listJourneyRunsOperation, getJourneyRunOperation, launchJourneyRunOperation, cancelJourneyRunOperation, listJourneyRunSessionsOperation, listScenariosOperation, getScenarioOperation, publishScenarioOperation, unpublishScenarioOperation, PlatformApiClient, platformBrowserToolPolicySchema, listServerToolsOperation, runEvalCaseOperation, getCapabilitiesOperation, searchSessionsOperation, getChatSessionOperation, getChatSessionTraceOperation, listPersonasOperation, getPersonaOperation, createPersonaOperation, updatePersonaOperation, deletePersonaOperation, generatePersonasOperation, getJourneyOperation, createJourneyOperation, updateJourneyOperation, archiveJourneyOperation, generateJourneysOperation, getSwarmOverviewOperation, getJourneyRunScorecardOperation, listSwarmFindingsOperation, dismissSwarmFindingOperation, undismissSwarmFindingOperation, getWaveInsightsOperation, requestWaveInsightsOperation, cancelWaveInsightsOperation, listSwarmsOperation, getSwarmOperation, createSwarmOperation, updateSwarmOperation, archiveSwarmOperation, getUserTestingScenarioOperation, listUserTestingSessionsOperation, getUserTestingSessionOperation, getUserTestingMetricsOperation, getUserTestingUsageOperation, listUserTestingFindingsOperation, getUserTestingSignalsOperation, getUserTestingInsightsOperation, requestUserTestingInsightsOperation, cancelUserTestingInsightsOperation, dismissUserTestingFindingOperation, undismissUserTestingFindingOperation, updateUserTestingScenarioOperation, setUserTestingGuestExecutionOperation, rotateUserTestingLinkOperation, upsertUserTestingMemberOperation, removeUserTestingMemberOperation, rebindUserTestingScenarioOperation, startClaudeReadinessRunOperation, startOpenAIReadinessRunOperation, getReadinessRunOperation, listReadinessRunsOperation, cancelReadinessRunOperation, getReadinessReportOperation, listRegistryDirectorySourcesOperation, searchRegistryDirectoryOperation, listRegistryServersOperation, listRegistryConnectionsOperation, uninstallRegistryServerOperation } from '@mcpjam/sdk/platform';
12
+ import { RUN_LAUNCH_HEADERS, getRegistryDirectoryServerOperation, listOrganizationsOperation, listProjectsOperation, createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, cancelProjectServerConnectionOperation, listChatSessionsOperation, resolveProject, sendChatMessageOperation, createTunnelOperation, listEvalSuiteRunsOperation, listEvalSuiteRevisionsOperation, runEvalSuiteOperation, getEvalRunOperation, getEvalRunRouteFactsOperation, getEvalRunServerFactsOperation, proposeEvalDescriptionRewriteOperation, startEvalDescriptionExperimentOperation, getEvalDescriptionExperimentOperation, cancelEvalRunOperation, backtestEvalRunJudgeOperation, backtestEvalRunOperation, requestEvalRunJudgeOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, createClientOperation, updateClientOperation, setClientServersOperation, duplicateClientOperation, createEnvironmentOperation, ensureAdhocEnvironmentOperation, nameEnvironmentOperation, updateEnvironmentOperation, createSecretOperation, updateSecretOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, listTraceDestinationsOperation, getTraceDestinationOperation, createTraceDestinationOperation, updateTraceDestinationOperation, deleteTraceDestinationOperation, testTraceDestinationOperation, pauseTraceDestinationOperation, resumeTraceDestinationOperation, backfillTraceDestinationOperation, listTraceDestinationBackfillsOperation, runOperationWithPermalinks, withPermalinkEnvelope, PlatformApiError, installRegistryServerOperation, installRegistryDirectoryServerOperation, getProjectServerOperation, DEFAULT_PLATFORM_API_BASE_URL, projectResolutionError, listProjectServersOperation, createProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, driveChatSessionBrowserOperation, observeChatSessionBrowserOperation, isPlatformApiError, describePlatformRefusal, platformRefusalHint, createEvalSuiteOperation, listEvalSuitesOperation, buildAppPermalink, listEvalSuiteStageAnalyticsOperation, getEvalRunStageAnalyticsOperation, listEvalGithubReposOperation, connectEvalGithubRepoOperation, resolveEnvironmentOperation, listClientsOperation, getClientOperation, deleteClientOperation, listEnvironmentsOperation, getEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listSecretsOperation, getSecretOperation, deleteSecretOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, listProjectSkillsOperation, getProjectSkillOperation, listGoalsOperation, listGoalRunsOperation, getGoalRunOperation, launchGoalRunOperation, cancelGoalRunOperation, listGoalRunSessionsOperation, PlatformApiClient, platformBrowserToolPolicySchema, listServerToolsOperation, runEvalCaseOperation, getCapabilitiesOperation, getStudyOperation, listStudySessionsOperation, getStudySessionOperation, getStudyMetricsOperation, getStudyUsageOperation, listStudyFindingsOperation, getStudySignalsOperation, getStudyInsightsOperation, requestStudyInsightsOperation, cancelStudyInsightsOperation, dismissStudyFindingOperation, undismissStudyFindingOperation, updateStudyOperation, setStudyGuestExecutionOperation, rotateStudyLinkOperation, upsertStudyMemberOperation, removeStudyMemberOperation, rebindStudyOperation, listStudiesOperation, publishStudyOperation, unpublishStudyOperation, searchSessionsOperation, getChatSessionOperation, getChatSessionTraceOperation, listPersonasOperation, getPersonaOperation, createPersonaOperation, updatePersonaOperation, deletePersonaOperation, generatePersonasOperation, getGoalOperation, createGoalOperation, updateGoalOperation, archiveGoalOperation, generateGoalsOperation, getSwarmOverviewOperation, getGoalRunScorecardOperation, listSwarmFindingsOperation, dismissSwarmFindingOperation, undismissSwarmFindingOperation, getSwarmRunInsightsOperation, requestSwarmRunInsightsOperation, cancelSwarmRunInsightsOperation, listSwarmsOperation, getSwarmOperation, createSwarmOperation, updateSwarmOperation, archiveSwarmOperation, startClaudeReadinessRunOperation, startOpenAIReadinessRunOperation, getReadinessRunOperation, listReadinessRunsOperation, cancelReadinessRunOperation, getReadinessReportOperation, listRegistryDirectorySourcesOperation, searchRegistryDirectoryOperation, listRegistryServersOperation, listRegistryConnectionsOperation, uninstallRegistryServerOperation } from '@mcpjam/sdk/platform';
13
13
  import { isDeepStrictEqual } from 'util';
14
14
  import { swarmVerdictLabel, composeSuiteGateWithBaseReport, EVAL_SUITE_SCHEMA_VERSION, EVAL_SUITE_SCHEMA_VERSIONS, MAX_BATCH_CREATE_CASES, filterSuppressedSuiteAssertions, evalSuiteFileSchema, MAX_IMPORT_NOTE_CHARS, isOpaqueId } from '@mcpjam/sdk/contract';
15
15
  import { HOST_TEMPLATES, HOST_TEMPLATE_IDS, seedHostTemplate } from '@mcpjam/sdk/host-config/templates';
@@ -28,7 +28,7 @@ import { PostHog } from 'posthog-node';
28
28
 
29
29
  // package.json
30
30
  var package_default = {
31
- version: "5.10.3"};
31
+ version: "5.11.0"};
32
32
  function conformanceExitCode(result) {
33
33
  if (result.outcome === "incomplete") return 3;
34
34
  if (result.outcome === "failed") return 1;
@@ -12178,37 +12178,59 @@ function pageArgs(options) {
12178
12178
  function addPageOptions(command) {
12179
12179
  return command.option("--cursor <cursor>", "Page cursor from a previous response").option("--limit <n>", "Items per page (1-200)");
12180
12180
  }
12181
- function registerJourneysCommands(program) {
12182
- const journeys = program.command("journeys").description(
12183
- "List journeys and inspect their runs (the Swarms product) in your hosted MCPJam projects"
12181
+ function goalIdOf(options) {
12182
+ if (options.goalId !== void 0 && options.journey !== void 0) {
12183
+ throw usageError(
12184
+ "Use either --goal-id or its deprecated --journey alias, not both."
12185
+ );
12186
+ }
12187
+ const selected = options.goalId ?? options.journey;
12188
+ if (selected === void 0) {
12189
+ throw usageError("Missing required option: --goal-id");
12190
+ }
12191
+ return selected;
12192
+ }
12193
+ function foldSwarmRunId(options) {
12194
+ if (options.swarmRun !== void 0 && options.wave !== void 0) {
12195
+ throw usageError(
12196
+ "Use either --swarm-run or its deprecated --wave alias, not both."
12197
+ );
12198
+ }
12199
+ return options.swarmRun ?? options.wave;
12200
+ }
12201
+ function registerGoalsCommands(program) {
12202
+ const goals = program.command("goals").alias("journeys").description(
12203
+ "List goals and inspect their runs (the Swarms product) in your hosted MCPJam projects"
12184
12204
  );
12185
- journeys.command("list").description("List the journeys in a project").option(
12205
+ goals.command("list").description("List the goals in a project").option(
12186
12206
  "--project <id-or-name>",
12187
12207
  "Project name or ID (defaults to the most recently updated project)"
12188
- ).action(async (options, command) => {
12189
- const globalOptions = getGlobalOptions(command);
12190
- const result = await runPlatformOperation(
12191
- platformOptionsOf(command),
12192
- globalOptions.timeout,
12193
- ({ client, signal }) => listJourneysOperation.execute(
12194
- { project: resolveCloudProjectArgs(options).project },
12195
- { client, signal }
12196
- )
12197
- );
12198
- writeResult(result, globalOptions.format);
12199
- });
12208
+ ).action(
12209
+ async (options, command) => {
12210
+ const globalOptions = getGlobalOptions(command);
12211
+ const result = await runPlatformOperation(
12212
+ platformOptionsOf(command),
12213
+ globalOptions.timeout,
12214
+ ({ client, signal }) => listGoalsOperation.execute(
12215
+ { project: resolveCloudProjectArgs(options).project },
12216
+ { client, signal }
12217
+ )
12218
+ );
12219
+ writeResult(result, globalOptions.format);
12220
+ }
12221
+ );
12200
12222
  addPageOptions(
12201
- journeys.command("runs").description("List a journey's runs, newest first").requiredOption("--journey <id>", "Journey ID (from `journeys list`)").option("--project <id-or-name>", "Project name or ID")
12223
+ goals.command("runs").description("List a goal's runs, newest first").option("--goal-id <id>", "Goal ID (from `goals list`)").option("--journey <id>", "Deprecated alias for --goal-id").option("--project <id-or-name>", "Project name or ID")
12202
12224
  ).action(
12203
12225
  async (options, command) => {
12204
12226
  const globalOptions = getGlobalOptions(command);
12205
12227
  const result = await runPlatformOperation(
12206
12228
  platformOptionsOf(command),
12207
12229
  globalOptions.timeout,
12208
- ({ client, signal }) => listJourneyRunsOperation.execute(
12230
+ ({ client, signal }) => listGoalRunsOperation.execute(
12209
12231
  {
12210
12232
  project: resolveCloudProjectArgs(options).project,
12211
- journey: options.journey,
12233
+ goalId: goalIdOf(options),
12212
12234
  ...pageArgs(options)
12213
12235
  },
12214
12236
  { client, signal }
@@ -12217,33 +12239,36 @@ function registerJourneysCommands(program) {
12217
12239
  writeResult(result, globalOptions.format);
12218
12240
  }
12219
12241
  );
12220
- journeys.command("status").description(
12242
+ goals.command("status").description(
12221
12243
  "Show one run's status, target rollups, and per-session attempts. Poll this after launching; `status` leaves 'running' once every attempt has settled. A run someone stopped reports 'failed' with canceled: true."
12222
- ).requiredOption("--run <id>", "Journey run ID").option("--project <id-or-name>", "Project name or ID").action(
12244
+ ).requiredOption("--run <id>", "Goal run ID").option("--project <id-or-name>", "Project name or ID").action(
12223
12245
  async (options, command) => {
12224
12246
  const globalOptions = getGlobalOptions(command);
12225
12247
  const result = await runPlatformOperation(
12226
12248
  platformOptionsOf(command),
12227
12249
  globalOptions.timeout,
12228
- ({ client, signal }) => getJourneyRunOperation.execute(
12229
- { project: resolveCloudProjectArgs(options).project, run: options.run },
12250
+ ({ client, signal }) => getGoalRunOperation.execute(
12251
+ {
12252
+ project: resolveCloudProjectArgs(options).project,
12253
+ run: options.run
12254
+ },
12230
12255
  { client, signal }
12231
12256
  )
12232
12257
  );
12233
12258
  writeResult(result, globalOptions.format);
12234
12259
  }
12235
12260
  );
12236
- journeys.command("run").description(
12237
- "Launch a journey. Returns as soon as the run exists \u2014 poll `journeys status` for progress."
12238
- ).requiredOption("--journey <id>", "Journey ID to launch").option("--project <id-or-name>", "Project name or ID").option(
12261
+ goals.command("run").description(
12262
+ "Launch a goal. Returns as soon as the run exists \u2014 poll `goals status` for progress."
12263
+ ).option("--goal-id <id>", "Goal ID to launch").option("--journey <id>", "Deprecated alias for --goal-id").option("--project <id-or-name>", "Project name or ID").option(
12239
12264
  "--idempotency-key <key>",
12240
- "Retry key. Pass one: a launch spends model credits, so a retry after a dropped response must not run the journey twice. Replaying a key returns the original run."
12265
+ "Retry key. Pass one: a launch spends model credits, so a retry after a dropped response must not run the goal twice. Replaying a key returns the original run."
12241
12266
  ).option(
12242
- "--wave <id>",
12267
+ "--swarm-run <id>",
12243
12268
  "Opaque id linking the sibling runs of one co-launched batch"
12244
- ).option(
12269
+ ).option("--wave <id>", "Deprecated alias for --swarm-run").option(
12245
12270
  "--environment <id>",
12246
- "Fan out across this project environment instead of the journey's authored targets (repeatable)",
12271
+ "Fan out across this project environment instead of the goal's authored targets (repeatable)",
12247
12272
  collectRepeatable2,
12248
12273
  []
12249
12274
  ).action(
@@ -12252,12 +12277,15 @@ function registerJourneysCommands(program) {
12252
12277
  const result = await runPlatformOperation(
12253
12278
  platformOptionsOf(command),
12254
12279
  globalOptions.timeout,
12255
- ({ client, signal }) => launchJourneyRunOperation.execute(
12280
+ ({ client, signal }) => launchGoalRunOperation.execute(
12256
12281
  {
12257
12282
  project: resolveCloudProjectArgs(options).project,
12258
- journey: options.journey,
12283
+ goalId: goalIdOf(options),
12259
12284
  ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
12260
- ...options.wave ? { waveId: options.wave } : {},
12285
+ // `swarmRunId`, not `waveId`: the operation renamed its input
12286
+ // with the rest of the noun, and the conditional spread means
12287
+ // a stale key would be dropped in silence rather than refused.
12288
+ ...foldSwarmRunId(options) ? { swarmRunId: foldSwarmRunId(options) } : {},
12261
12289
  ...options.environment?.length ? { environmentIds: options.environment } : {}
12262
12290
  },
12263
12291
  { client, signal }
@@ -12266,16 +12294,19 @@ function registerJourneysCommands(program) {
12266
12294
  writeResult(result, globalOptions.format);
12267
12295
  }
12268
12296
  );
12269
- journeys.command("cancel").description(
12270
- "Stop a running journey run. Idempotent \u2014 cancelling an already-cancelled run succeeds; a run that finished on its own conflicts instead."
12271
- ).requiredOption("--run <id>", "Journey run ID").option("--project <id-or-name>", "Project name or ID").action(
12297
+ goals.command("cancel").description(
12298
+ "Stop a running goal run. Idempotent \u2014 cancelling an already-cancelled run succeeds; a run that finished on its own conflicts instead."
12299
+ ).requiredOption("--run <id>", "Goal run ID").option("--project <id-or-name>", "Project name or ID").action(
12272
12300
  async (options, command) => {
12273
12301
  const globalOptions = getGlobalOptions(command);
12274
12302
  const result = await runPlatformOperation(
12275
12303
  platformOptionsOf(command),
12276
12304
  globalOptions.timeout,
12277
- ({ client, signal }) => cancelJourneyRunOperation.execute(
12278
- { project: resolveCloudProjectArgs(options).project, run: options.run },
12305
+ ({ client, signal }) => cancelGoalRunOperation.execute(
12306
+ {
12307
+ project: resolveCloudProjectArgs(options).project,
12308
+ run: options.run
12309
+ },
12279
12310
  { client, signal }
12280
12311
  )
12281
12312
  );
@@ -12283,16 +12314,16 @@ function registerJourneysCommands(program) {
12283
12314
  }
12284
12315
  );
12285
12316
  addPageOptions(
12286
- journeys.command("sessions").description(
12317
+ goals.command("sessions").description(
12287
12318
  "List the chat sessions a run produced, with readiness and goal scores"
12288
- ).requiredOption("--run <id>", "Journey run ID").option("--project <id-or-name>", "Project name or ID")
12319
+ ).requiredOption("--run <id>", "Goal run ID").option("--project <id-or-name>", "Project name or ID")
12289
12320
  ).action(
12290
12321
  async (options, command) => {
12291
12322
  const globalOptions = getGlobalOptions(command);
12292
12323
  const result = await runPlatformOperation(
12293
12324
  platformOptionsOf(command),
12294
12325
  globalOptions.timeout,
12295
- ({ client, signal }) => listJourneyRunSessionsOperation.execute(
12326
+ ({ client, signal }) => listGoalRunSessionsOperation.execute(
12296
12327
  {
12297
12328
  project: resolveCloudProjectArgs(options).project,
12298
12329
  run: options.run,
@@ -12302,12 +12333,18 @@ function registerJourneysCommands(program) {
12302
12333
  )
12303
12334
  );
12304
12335
  writeResult(
12305
- globalOptions.format === "human" ? { ...result, items: result.items.map((row) => ({ ...row, goalResult: swarmVerdictLabel(row.verdict) })) } : result,
12336
+ globalOptions.format === "human" ? {
12337
+ ...result,
12338
+ items: result.items.map((row) => ({
12339
+ ...row,
12340
+ goalResult: swarmVerdictLabel(row.verdict)
12341
+ }))
12342
+ } : result,
12306
12343
  globalOptions.format
12307
12344
  );
12308
12345
  }
12309
12346
  );
12310
- return journeys;
12347
+ return goals;
12311
12348
  }
12312
12349
 
12313
12350
  // src/lib/projects-render.ts
@@ -12878,1527 +12915,1859 @@ async function pollConnection(options, timeoutMs, connectionRequestId, expiresAt
12878
12915
  process.removeListener("SIGINT", onInterrupt);
12879
12916
  }
12880
12917
  }
12881
- function registerScenariosCommands(program) {
12882
- const scenarios = program.command("scenarios").description(
12883
- "Publish project environments for user testing, and take them down again"
12884
- );
12885
- const SCENARIO_MODES = [
12886
- "project_members",
12887
- "invited_only",
12888
- "anyone_with_link"
12889
- ];
12890
- scenarios.command("list").description("List the scenarios published from a project").option(
12891
- "--project <id-or-name>",
12892
- "Project name or ID (defaults to the most recently updated project)"
12893
- ).action(async (options, command) => {
12894
- const globalOptions = getGlobalOptions(command);
12895
- const result = await runPlatformOperation(
12896
- platformOptionsOf(command),
12897
- globalOptions.timeout,
12898
- ({ client, signal }) => listScenariosOperation.execute(
12899
- {
12900
- project: resolveCloudProjectArgs(options).project
12901
- },
12902
- { client, signal }
12903
- )
12904
- );
12905
- writeResult(result, globalOptions.format);
12906
- });
12907
- scenarios.command("get").description(
12908
- "Show one scenario: access mode, attached servers, share link"
12909
- ).requiredOption("--scenario <id-or-name>", "Scenario name or ID").option(
12910
- "--project <id-or-name>",
12911
- "Project name or ID (defaults to the most recently updated project)"
12912
- ).action(
12913
- async (options, command) => {
12914
- const globalOptions = getGlobalOptions(command);
12915
- const result = await runPlatformOperation(
12916
- platformOptionsOf(command),
12917
- globalOptions.timeout,
12918
- ({ client, signal }) => getScenarioOperation.execute(
12919
- {
12920
- scenario: options.scenario,
12921
- project: resolveCloudProjectArgs(options).project
12922
- },
12923
- { client, signal }
12924
- )
12925
- );
12926
- writeResult(result, globalOptions.format);
12927
- }
12928
- );
12929
- scenarios.command("publish").description(
12930
- "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 cloud user-testing update` to change an existing scenario)."
12931
- ).requiredOption("--environment <id>", "Project environment ID").option(
12932
- "--project <id-or-name>",
12933
- "Project name or ID (defaults to the most recently updated project)"
12934
- ).option("--name <name>", "Scenario name (create time only)").option("--description <text>", "Scenario description (create time only)").option(
12935
- "--mode <mode>",
12936
- "Who may open the share link (create time only): project_members | invited_only | anyone_with_link"
12937
- ).action(
12938
- async (options, command) => {
12939
- const globalOptions = getGlobalOptions(command);
12940
- const mode = options.mode;
12941
- if (mode !== void 0 && !SCENARIO_MODES.includes(mode)) {
12942
- command.error(
12943
- `error: option '--mode <mode>' must be one of ${SCENARIO_MODES.join(
12944
- ", "
12945
- )}`
12946
- );
12947
- }
12948
- const result = await runPlatformOperation(
12949
- platformOptionsOf(command),
12950
- globalOptions.timeout,
12951
- ({ client, signal }) => publishScenarioOperation.execute(
12952
- {
12953
- project: resolveCloudProjectArgs(options).project,
12954
- environment: options.environment,
12955
- ...options.name !== void 0 ? { name: options.name } : {},
12956
- ...options.description !== void 0 ? { description: options.description } : {},
12957
- ...mode !== void 0 ? { mode } : {}
12958
- },
12959
- { client, signal }
12960
- )
12961
- );
12962
- writeResult(result, globalOptions.format);
12963
- }
12964
- );
12965
- scenarios.command("unpublish").description(
12966
- "Take an environment's scenario down, invalidating its share link and any live guest sessions. Idempotent."
12967
- ).requiredOption("--environment <id>", "Project environment ID").option("--project <id-or-name>", "Project name or ID").action(
12968
- async (options, command) => {
12969
- const globalOptions = getGlobalOptions(command);
12970
- const result = await runPlatformOperation(
12971
- platformOptionsOf(command),
12972
- globalOptions.timeout,
12973
- ({ client, signal }) => unpublishScenarioOperation.execute(
12974
- { project: resolveCloudProjectArgs(options).project, environment: options.environment },
12975
- { client, signal }
12976
- )
12977
- );
12978
- writeResult(result, globalOptions.format);
12979
- }
12918
+ function studyCommand(group, name, description) {
12919
+ return addProjectOption(
12920
+ group.command(name).description(description).option("--study <id>", "Study ID").option("--scenario <id>", "Deprecated alias for --study")
12980
12921
  );
12981
12922
  }
12982
- function resolveSecretValue(options, { required }) {
12983
- const supplied = [
12984
- options.value !== void 0 ? "--value" : null,
12985
- options.valueFile !== void 0 ? "--value-file" : null,
12986
- options.valueEnv !== void 0 ? "--value-env" : null
12987
- ].filter((flag) => flag !== null);
12988
- if (supplied.length > 1) {
12989
- throw usageError(
12990
- `Provide exactly one of --value, --value-file, or --value-env (got ${supplied.join(
12991
- ", "
12992
- )}).`
12993
- );
12994
- }
12995
- if (supplied.length === 0) {
12996
- if (!required) return void 0;
12923
+ function studyOf(options) {
12924
+ if (options.study !== void 0 && options.scenario !== void 0) {
12997
12925
  throw usageError(
12998
- "A value is required. Prefer --value-file <path>, --value-env <VAR>, or `--value -` to read stdin; --value <literal> works but is written to your shell history."
12926
+ "Use either --study or its deprecated --scenario alias, not both."
12999
12927
  );
13000
12928
  }
13001
- if (options.valueEnv !== void 0) {
13002
- const value = process.env[options.valueEnv];
13003
- if (value === void 0 || value === "") {
13004
- throw usageError(
13005
- `Environment variable "${options.valueEnv}" is not set (or is empty).`
13006
- );
13007
- }
13008
- return value;
13009
- }
13010
- const readStdinOrFile = (path9) => {
13011
- try {
13012
- return path9 === "-" ? readFileSync(0, "utf8") : readFileSync(path9, "utf8");
13013
- } catch (error) {
13014
- throw usageError(
13015
- path9 === "-" ? "Failed to read the secret value from stdin." : `Failed to read the secret value from "${path9}".`,
13016
- { source: error instanceof Error ? error.message : String(error) }
13017
- );
13018
- }
13019
- };
13020
- const stripOneTrailingNewline = (text) => text.replace(/\r?\n$/, "");
13021
- if (options.valueFile !== void 0) {
13022
- const raw = readStdinOrFile(options.valueFile);
13023
- const text = options.valueFile === "-" ? stripOneTrailingNewline(raw) : raw;
13024
- if (text === "") throw usageError("The secret value is empty.");
13025
- return text;
13026
- }
13027
- if (options.value === "-") {
13028
- const text = stripOneTrailingNewline(readStdinOrFile("-"));
13029
- if (text === "") throw usageError("The secret value is empty.");
13030
- return text;
12929
+ const selected = options.study ?? options.scenario;
12930
+ if (selected === void 0) {
12931
+ throw usageError("Missing required option: --study");
13031
12932
  }
13032
- if (options.value === "") throw usageError("The secret value is empty.");
13033
- return options.value;
12933
+ return selected;
13034
12934
  }
13035
- function brokerFields(options) {
12935
+ function addPageOptions2(command) {
12936
+ return command.option("--cursor <cursor>", "Page cursor from a previous response").option("--limit <n>", "Page size");
12937
+ }
12938
+ function pageArgs2(options) {
12939
+ const limit = parseIntegerOption(options.limit, "--limit");
13036
12940
  return {
13037
- ...options.host !== void 0 && options.host.length > 0 ? { brokerHosts: options.host } : {},
13038
- ...options.header !== void 0 ? { brokerHeader: options.header } : {},
13039
- ...options.template !== void 0 ? { brokerTemplate: options.template } : {}
12941
+ ...options.cursor ? { cursor: options.cursor } : {},
12942
+ ...limit !== void 0 ? { limit } : {}
13040
12943
  };
13041
12944
  }
13042
- function collectHost(value, previous = []) {
13043
- return [...previous, value];
13044
- }
13045
- function registerSecretsCommands(program) {
13046
- const secrets = program.command("secrets").description(
13047
- "Store and manage the project credentials a workflow needs (stripe, gh, psql). Write-only: no command prints a value."
12945
+ function registerStudiesCommands(program) {
12946
+ const group = program.command("studies").aliases(["scenarios", "user-testing"]).description(
12947
+ "Publish project environments as studies, read what testers did, and control who can reach them"
13048
12948
  );
13049
- secrets.command("list").description(
13050
- "List the project's secrets \u2014 metadata only. Shows the project-shared ones plus your own personal ones."
13051
- ).option(
13052
- "--project <id-or-name>",
13053
- "Project name or ID (defaults to the most recently updated project)"
13054
- ).action(
13055
- async (options, command) => {
13056
- const globalOptions = getGlobalOptions(command);
13057
- const result = await runPlatformOperation(
13058
- platformOptionsOf(command),
13059
- globalOptions.timeout,
13060
- ({ client, signal }) => listSecretsOperation.execute(
13061
- { project: resolveCloudProjectArgs(options).project },
13062
- { client, signal }
13063
- )
13064
- );
13065
- writeResult(result, globalOptions.format);
13066
- }
12949
+ bindOperation(
12950
+ studyCommand(
12951
+ group,
12952
+ "get",
12953
+ "One study's full read \u2014 model, system prompt, tool-approval policy, resolved servers, the environment it publishes \u2014 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."
12954
+ ),
12955
+ getStudyOperation,
12956
+ (options) => ({
12957
+ project: options.project,
12958
+ study: studyOf(options)
12959
+ })
13067
12960
  );
13068
- secrets.command("show").description(
13069
- "Show one secret's metadata: delivery mode, host binding, sharing, last delivery. Never its value."
13070
- ).requiredOption("--secret <id>", "Secret ID, from `cloud secrets list`").option("--project <id-or-name>", "Project name or ID").action(
13071
- async (options, command) => {
13072
- const globalOptions = getGlobalOptions(command);
13073
- const result = await runPlatformOperation(
13074
- platformOptionsOf(command),
13075
- globalOptions.timeout,
13076
- ({ client, signal }) => getSecretOperation.execute(
13077
- {
13078
- project: resolveCloudProjectArgs(options).project,
13079
- secret: options.secret
13080
- },
13081
- { client, signal }
13082
- )
13083
- );
13084
- writeResult(result, globalOptions.format);
13085
- }
12961
+ bindOperation(
12962
+ addPageOptions2(
12963
+ studyCommand(
12964
+ group,
12965
+ "sessions",
12966
+ "List the sessions real visitors had with a study: counts, feedback, device and segment, with a first-message preview. Summaries only \u2014 use `session` for a transcript."
12967
+ )
12968
+ ),
12969
+ listStudySessionsOperation,
12970
+ (options) => ({
12971
+ project: options.project,
12972
+ study: studyOf(options),
12973
+ ...pageArgs2(options)
12974
+ })
13086
12975
  );
13087
- secrets.command("set").description(
13088
- "Create a secret. The value comes from --value-file, --value-env, or stdin \u2014 never a positional argument."
13089
- ).requiredOption(
13090
- "--name <NAME>",
13091
- "Environment-variable name (STRIPE_API_KEY). Uppercase, digits, underscores; not starting with a digit. Immutable."
13092
- ).requiredOption(
13093
- "--delivery <mode>",
13094
- "brokered (the proxy injects it outside the sandbox \u2014 extraction-proof, not use-proof, HTTPS only) or materialized (a real env var inside the box, which is what a CLI can read, and which `env` prints)"
13095
- ).option(
13096
- "--value-file <path>",
13097
- "Read the value from a file, VERBATIM \u2014 a trailing newline is kept, because in a PEM block it is part of the credential. `-` reads stdin instead, which drops one trailing newline. Preferred."
13098
- ).option("--value-env <VAR>", "Read the value from an environment variable.").option(
13099
- "--value <literal>",
13100
- "The value inline, or `-` to read stdin. SCRIPTING ONLY: an inline literal is written to your shell history and is visible in `ps` while the command runs."
13101
- ).option("--description <text>", "What this credential is for.").option(
13102
- "--host <hostname>",
13103
- "Brokered only, repeatable: an exact hostname the header is injected on (api.stripe.com). No scheme, no port, no wildcard.",
13104
- collectHost
13105
- ).option(
13106
- "--header <name>",
13107
- "Brokered only: the header name, e.g. Authorization."
13108
- ).option(
13109
- "--template <value>",
13110
- 'Brokered only: the header value with {} where the secret goes, e.g. "Bearer {}".'
13111
- ).option(
13112
- "--sharing <scope>",
13113
- "project (default; delivered to every member's sessions, admin-only) or user (personal; delivered only in sessions you start)"
13114
- ).option(
13115
- "--idempotency-key <key>",
13116
- "Retry key. Pass one: a retried create without it fails as a name conflict with the row the first attempt already made."
13117
- ).action(
13118
- async (options, command) => {
13119
- const globalOptions = getGlobalOptions(command);
13120
- const value = resolveSecretValue(options, { required: true });
13121
- const input = createSecretOperation.inputSchema.safeParse({
13122
- project: resolveCloudProjectArgs(options).project,
13123
- name: options.name,
13124
- value,
13125
- ...options.description !== void 0 ? { description: options.description } : {},
13126
- delivery: options.delivery,
13127
- ...brokerFields(options),
13128
- ...options.sharing !== void 0 ? { sharing: options.sharing } : {},
13129
- ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
13130
- });
13131
- if (!input.success) {
13132
- throw usageError(
13133
- `Invalid input: ${input.error.issues.map(
13134
- (issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`
13135
- ).join("; ")}`
13136
- );
13137
- }
13138
- const result = await runPlatformOperation(
13139
- platformOptionsOf(command),
13140
- globalOptions.timeout,
13141
- ({ client, signal }) => createSecretOperation.execute(input.data, { client, signal })
13142
- );
13143
- writeResult(result, globalOptions.format);
13144
- }
13145
- );
13146
- secrets.command("update").description(
13147
- "Rotate a secret's value and/or change how it is delivered. A rotation reaches NEW RUNS ONLY \u2014 a session already running keeps the value it was given."
13148
- ).requiredOption("--secret <id>", "Secret ID, from `cloud secrets list`").option("--project <id-or-name>", "Project name or ID").option(
13149
- "--value-file <path>",
13150
- "Read the new value from a file, VERBATIM \u2014 a trailing newline is kept. `-` reads stdin instead, which drops one trailing newline. Preferred."
13151
- ).option(
13152
- "--value-env <VAR>",
13153
- "Read the new value from an environment variable."
13154
- ).option(
13155
- "--value <literal>",
13156
- "The new value inline, or `-` to read stdin. SCRIPTING ONLY \u2014 see `secrets set`."
13157
- ).option("--description <text>", "Replacement description.").option(
13158
- "--clear-description",
13159
- "Remove the description entirely, leaving the secret with none."
13160
- ).option(
13161
- "--delivery <mode>",
13162
- "brokered or materialized. Switching to brokered needs --host/--header/--template in the same call; switching to materialized clears them."
13163
- ).option("--host <hostname>", "Brokered only, repeatable.", collectHost).option("--header <name>", "Brokered only: the header name.").option("--template <value>", 'Brokered only: e.g. "Bearer {}".').action(
13164
- async (options, command) => {
13165
- const globalOptions = getGlobalOptions(command);
13166
- if (options.description !== void 0 && options.clearDescription) {
13167
- throw usageError(
13168
- "Provide either --description or --clear-description, not both."
13169
- );
13170
- }
13171
- const value = resolveSecretValue(options, { required: false });
13172
- const input = updateSecretOperation.inputSchema.safeParse({
13173
- project: resolveCloudProjectArgs(options).project,
13174
- secret: options.secret,
13175
- ...value !== void 0 ? { value } : {},
13176
- // `--clear-description` is the flag spelling of the `null` the REST
13177
- // route and the SDK client already accept. Distinct from
13178
- // `--description ""`, which SETS an empty description.
13179
- ...options.clearDescription ? { description: null } : {},
13180
- ...options.description !== void 0 ? { description: options.description } : {},
13181
- ...options.delivery !== void 0 ? { delivery: options.delivery } : {},
13182
- ...brokerFields(options)
13183
- });
13184
- if (!input.success) {
13185
- throw usageError(
13186
- `Invalid input: ${input.error.issues.map(
13187
- (issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`
13188
- ).join("; ")}`
13189
- );
13190
- }
13191
- const result = await runPlatformOperation(
13192
- platformOptionsOf(command),
13193
- globalOptions.timeout,
13194
- ({ client, signal }) => updateSecretOperation.execute(input.data, { client, signal })
13195
- );
13196
- writeResult(result, globalOptions.format);
13197
- }
13198
- );
13199
- secrets.command("rm").description(
13200
- "Delete a secret. HARD: the row and the encrypted value both go, and MCPJam stops delivering it. Not blocked when an environment still selects it \u2014 deletion never waits on cleanup. This does NOT revoke the credential at the provider that issued it, and runs already in flight keep the value they were handed."
13201
- ).requiredOption("--secret <id>", "Secret ID, from `cloud secrets list`").option("--project <id-or-name>", "Project name or ID").action(
13202
- async (options, command) => {
13203
- const globalOptions = getGlobalOptions(command);
13204
- const result = await runPlatformOperation(
13205
- platformOptionsOf(command),
13206
- globalOptions.timeout,
13207
- ({ client, signal }) => deleteSecretOperation.execute(
13208
- {
13209
- project: resolveCloudProjectArgs(options).project,
13210
- secret: options.secret
13211
- },
13212
- { client, signal }
13213
- )
13214
- );
13215
- writeResult(result, globalOptions.format);
13216
- }
13217
- );
13218
- }
13219
- async function waitForSessionTurn(run, signal, wait = async (ms, signal2) => {
13220
- await setTimeout$1(ms, void 0, { signal: signal2 });
13221
- }) {
13222
- for (; ; ) {
13223
- signal?.throwIfAborted();
13224
- try {
13225
- return await run();
13226
- } catch (error) {
13227
- if (!isPlatformApiError(error) || error.status !== 409 || error.details?.reason !== "TURN_IN_PROGRESS")
13228
- throw error;
13229
- const retryAfterMs = error.details.retryAfterMs;
13230
- if (typeof retryAfterMs !== "number" || !Number.isFinite(retryAfterMs) || retryAfterMs <= 0)
13231
- throw error;
13232
- await wait(retryAfterMs, signal);
13233
- }
13234
- }
13235
- }
13236
- function browserInput(options) {
13237
- const requested = options.browser || options.browserMode || options.browserOrigins || options.browserTools || options.browserProfile;
13238
- if (!requested) return void 0;
13239
- if ((options.browserOrigins || options.browserTools) && !options.browserMode)
13240
- throw usageError(
13241
- "--browser-origins and --browser-tools require --browser-mode"
13242
- );
13243
- if (options.browserMode && !["allow_all", "read_only", "allowlist"].includes(options.browserMode))
13244
- throw usageError(
13245
- "--browser-mode must be allow_all, read_only, or allowlist"
13246
- );
13247
- const policy = options.browserMode ? platformBrowserToolPolicySchema.safeParse({
13248
- mode: options.browserMode,
13249
- ...options.browserOrigins ? { originAllowlist: options.browserOrigins } : {},
13250
- ...options.browserTools ? { toolAllowlist: options.browserTools } : {}
13251
- }) : void 0;
13252
- if (policy && !policy.success) throw usageError(policy.error.message);
13253
- return {
13254
- ...policy?.success ? { policy: policy.data } : {},
13255
- ...options.browserProfile ? { profileId: options.browserProfile } : {}
13256
- };
13257
- }
13258
- function addBrowserFlags(command) {
13259
- return command.option("--browser", "Attach the session browser for this turn").option(
13260
- "--browser-mode <mode>",
13261
- "Initial browser grant: allow_all, read_only, or allowlist"
13262
- ).option("--browser-origins <origins...>", "Allowed HTTP(S) origins").option(
13263
- "--browser-tools <tools...>",
13264
- "Allowed browser_* or webmcp:<name> tools"
13265
- ).option("--browser-profile <profileId>", "Initial saved browser profile");
13266
- }
13267
- function json(text) {
13268
- if (text === void 0) return void 0;
13269
- try {
13270
- return JSON.parse(text);
13271
- } catch {
13272
- throw usageError("Expected valid JSON");
13273
- }
13274
- }
13275
- function registerSessionsBrowserCommands(sessions) {
13276
- const browser = sessions.command("browser").description(
13277
- "Drive the same hosted browser as an API Playground session. Uses metered desktop time."
13278
- );
13279
- const common = (command, required = true) => (required ? command.requiredOption("--session <id>", "Public chat session ID") : command.option("--session <id>", "Existing public chat session ID")).option("--command-id <id>", "Stable command ID for retries");
13280
12976
  bindOperation(
13281
- addBrowserFlags(
13282
- addProjectOption(common(browser.command("open"), false))
13283
- ).option(
13284
- "--idempotency-key <key>",
13285
- "Stable key when creating a new session"
12977
+ addPageOptions2(
12978
+ studyCommand(
12979
+ group,
12980
+ "session",
12981
+ "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."
12982
+ ).requiredOption("--session <id>", "Session ID")
13286
12983
  ),
13287
- driveChatSessionBrowserOperation,
13288
- (o) => {
13289
- if (!o.session && !o.idempotencyKey)
13290
- throw usageError(
13291
- "--idempotency-key is required when creating a session; reuse it after a timeout"
13292
- );
13293
- if (!o.session && !o.browserMode)
13294
- throw usageError("--browser-mode is required when creating a session");
13295
- return {
13296
- op: "open",
13297
- sessionId: o.session,
13298
- project: o.project,
13299
- ...browserInput({ ...o, browser: true }),
13300
- idempotencyKey: o.idempotencyKey
13301
- };
13302
- },
13303
- { defaultTimeoutMs: 36e4 }
12984
+ getStudySessionOperation,
12985
+ (options) => ({
12986
+ project: options.project,
12987
+ study: studyOf(options),
12988
+ session: options.session,
12989
+ ...pageArgs2(options)
12990
+ })
13304
12991
  );
13305
12992
  bindOperation(
13306
- common(browser.command("navigate <url>")),
13307
- driveChatSessionBrowserOperation,
13308
- (o, url) => ({
13309
- op: "navigate",
13310
- sessionId: o.session,
13311
- url,
13312
- commandId: o.commandId ?? randomUUID()
13313
- }),
13314
- { defaultTimeoutMs: 36e4 }
12993
+ studyCommand(
12994
+ group,
12995
+ "metrics",
12996
+ "Aggregate metrics across a study's sessions."
12997
+ ).option("--population <name>", "Restrict to a session population"),
12998
+ getStudyMetricsOperation,
12999
+ (options) => ({
13000
+ project: options.project,
13001
+ study: studyOf(options),
13002
+ ...options.population ? { population: options.population } : {}
13003
+ })
13315
13004
  );
13316
13005
  bindOperation(
13317
- common(browser.command("act")).requiredOption(
13318
- "--verb <verb>",
13319
- "click, type, press, scroll, hover, drag, select, or dialog/tab action"
13320
- ).option("--target <json>", "Target ref, selector, or coordinates").option("--value <text>", "Action value").option("--expected-state <token>", "Observation state token"),
13321
- driveChatSessionBrowserOperation,
13322
- (o) => ({
13323
- op: "act",
13324
- sessionId: o.session,
13325
- commandId: o.commandId ?? randomUUID(),
13326
- command: {
13327
- verb: o.verb,
13328
- target: json(o.target),
13329
- value: o.value,
13330
- expectedState: o.expectedState
13331
- }
13332
- }),
13333
- { defaultTimeoutMs: 36e4 }
13006
+ studyCommand(
13007
+ group,
13008
+ "usage",
13009
+ "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."
13010
+ ),
13011
+ getStudyUsageOperation,
13012
+ (options) => ({
13013
+ project: options.project,
13014
+ study: studyOf(options)
13015
+ })
13334
13016
  );
13335
13017
  bindOperation(
13336
- common(browser.command("invoke <toolKey>")).requiredOption(
13337
- "--input <json>",
13338
- "Page tool input"
13018
+ studyCommand(
13019
+ group,
13020
+ "findings",
13021
+ "Problems detected across a study's sessions, tracked over time."
13339
13022
  ),
13340
- driveChatSessionBrowserOperation,
13341
- (o, toolKey) => ({
13342
- op: "invoke",
13343
- sessionId: o.session,
13344
- toolKey,
13345
- input: json(o.input),
13346
- commandId: o.commandId ?? randomUUID()
13347
- }),
13348
- { defaultTimeoutMs: 36e4 }
13023
+ listStudyFindingsOperation,
13024
+ (options) => ({
13025
+ project: options.project,
13026
+ study: studyOf(options)
13027
+ })
13349
13028
  );
13350
13029
  bindOperation(
13351
- common(browser.command("note <text>")),
13352
- driveChatSessionBrowserOperation,
13353
- (o, text) => ({
13354
- op: "note",
13355
- sessionId: o.session,
13356
- text,
13357
- commandId: o.commandId ?? randomUUID()
13030
+ studyCommand(
13031
+ group,
13032
+ "signals",
13033
+ "The study's live analysis window, and the windowId its insights are keyed by."
13034
+ ),
13035
+ getStudySignalsOperation,
13036
+ (options) => ({
13037
+ project: options.project,
13038
+ study: studyOf(options)
13358
13039
  })
13359
13040
  );
13360
13041
  bindOperation(
13361
- common(browser.command("close")),
13362
- driveChatSessionBrowserOperation,
13363
- (o) => ({
13364
- op: "close",
13365
- sessionId: o.session
13042
+ studyCommand(
13043
+ group,
13044
+ "insights",
13045
+ "The model's analysis of one window, if one has been requested. Not-found means nobody asked, which is different from asked-and-working."
13046
+ ).requiredOption("--window <id>", "Window ID (from `signals`)"),
13047
+ getStudyInsightsOperation,
13048
+ (options) => ({
13049
+ project: options.project,
13050
+ study: studyOf(options),
13051
+ window: options.window
13366
13052
  })
13367
13053
  );
13368
- for (const op of ["observe", "trace", "artifact"]) {
13369
- const command = common(browser.command(op)).option("--mode <mode>", "Observation mode (default screenshot)").option("--download <dir>", "Download screenshot to this directory");
13370
- bindOperation(
13371
- command,
13372
- {
13373
- ...observeChatSessionBrowserOperation,
13374
- execute: async (input, context) => {
13375
- const { download, ...wire } = input;
13376
- if (op === "trace" && download)
13377
- throw usageError("Use observe or artifact with --download");
13378
- const result = await observeChatSessionBrowserOperation.execute(
13379
- wire,
13380
- context
13381
- );
13382
- if (!download) return result;
13383
- let artifact = result;
13384
- if (op !== "artifact") {
13385
- const commandId = wire.commandId;
13386
- if (!commandId)
13387
- throw usageError("--download requires a command ID");
13388
- artifact = await context.client.chatSessionBrowser(
13389
- wire.sessionId,
13390
- "artifact",
13391
- { commandId },
13392
- { signal: context.signal }
13393
- );
13394
- }
13395
- if (!("url" in artifact) || typeof artifact.url !== "string")
13396
- throw usageError("No screenshot is available for this command");
13397
- const bytes = await fetchArtifactBytes(artifact.url, 3e4);
13398
- const extension = bytes[0] === 255 && bytes[1] === 216 ? "jpg" : "png";
13399
- const dir = resolve(download);
13400
- await mkdir(dir, { recursive: true });
13401
- const path9 = resolve(
13402
- dir,
13403
- `${(wire.commandId ?? "screenshot").replace(
13404
- /[^A-Za-z0-9_.-]/g,
13405
- "_"
13406
- )}.${extension}`
13407
- );
13408
- await writeFile(path9, bytes);
13409
- return { ...result, savedTo: path9 };
13410
- }
13411
- },
13412
- (o) => {
13413
- if (op === "artifact" && !o.commandId)
13414
- throw usageError("artifact requires --command-id");
13415
- return {
13416
- op,
13417
- sessionId: o.session,
13418
- commandId: o.commandId ?? (op === "observe" ? randomUUID() : void 0),
13419
- mode: o.mode,
13420
- download: o.download
13421
- };
13422
- },
13423
- { defaultTimeoutMs: 36e4 }
13424
- );
13425
- }
13426
- }
13427
- function requireQuery(value) {
13428
- const trimmed2 = value?.trim() ?? "";
13429
- if (trimmed2.length === 0) {
13430
- throw usageError("--query needs search terms.");
13431
- }
13432
- return trimmed2;
13433
- }
13434
- function parseSources(value) {
13435
- if (value === void 0) return void 0;
13436
- const parsed = value.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
13437
- if (parsed.length === 0) {
13438
- throw usageError(
13439
- "--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."
13440
- );
13441
- }
13442
- return parsed;
13443
- }
13444
- function validateOpInput2(op, raw) {
13445
- const parsed = op.inputSchema.safeParse(raw);
13446
- if (!parsed.success) {
13447
- const detail = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ");
13448
- const error = new Error(`Invalid input: ${detail}`);
13449
- error.exitCode = 2;
13450
- throw error;
13451
- }
13452
- return parsed.data;
13453
- }
13454
- function registerSessionsCommands(program) {
13455
- const sessions = program.command("sessions").description(
13456
- "List Playground chat sessions, or search conversations across Playground, user testing, evals and swarms."
13054
+ bindOperation(
13055
+ studyCommand(
13056
+ group,
13057
+ "request-insights",
13058
+ "Ask a model to analyze the current window. Returns pending; poll `insights`. Included with MCPJam \u2014 no credits are consumed; it counts against a daily insight quota shared with swarm insights. A 409 means the window has not been mined yet \u2014 wait rather than retrying in a loop."
13059
+ ).option("--force", "Regenerate over a window that already has insights."),
13060
+ requestStudyInsightsOperation,
13061
+ (options) => ({
13062
+ project: options.project,
13063
+ study: studyOf(options),
13064
+ ...options.force ? { force: true } : {}
13065
+ })
13457
13066
  );
13458
- addProjectOption(
13459
- sessions.command("list").description(
13460
- "List Playground chat sessions, newest first (one project; pass --all-projects to include every accessible project)"
13461
- )
13462
- ).addOption(
13463
- new Option(
13464
- "--all-projects",
13465
- "List sessions across every accessible project, ignoring the project link and MCPJAM_PROJECT"
13466
- ).conflicts("project")
13467
- ).option("--status <status>", "Filter by session status").option(
13468
- "--limit <n>",
13469
- "Maximum sessions to return (1-200)",
13470
- (value) => Number.parseInt(value, 10)
13471
- ).action(
13472
- async (options, command) => {
13473
- const globalOptions = getGlobalOptions(command);
13474
- if (options.allProjects) {
13475
- const input = validateOpInput2(listChatSessionsOperation, {
13476
- ...options.status === void 0 ? {} : { status: options.status },
13477
- ...options.limit === void 0 ? {} : { limit: options.limit }
13478
- });
13479
- const result2 = await runPlatformOperation(
13480
- platformOptionsOf(command),
13481
- globalOptions.timeout,
13482
- ({ client, signal }) => listChatSessionsOperation.execute(input, { client, signal }),
13483
- {
13484
- quiet: globalOptions.quiet,
13485
- cloudScope: { kind: "all-projects" }
13486
- }
13487
- );
13488
- writeResult(result2, globalOptions.format);
13489
- return;
13490
- }
13491
- const resolved = resolveCloudProjectArgs(options);
13492
- const result = await runPlatformOperation(
13493
- platformOptionsOf(command),
13494
- globalOptions.timeout,
13495
- async ({ client, signal }) => {
13496
- let project = resolved.project;
13497
- if (project === void 0) {
13498
- const page = await client.listProjects({}, { signal });
13499
- const resolution = resolveProject(page.items, void 0);
13500
- if (!resolution.ok) {
13501
- throw usageError(
13502
- appendProjectLinkHint(
13503
- resolution.message,
13504
- resolved.projectScope
13505
- )
13506
- );
13507
- }
13508
- project = resolution.project.id;
13509
- }
13510
- const input = validateOpInput2(listChatSessionsOperation, {
13511
- project,
13512
- ...options.status === void 0 ? {} : { status: options.status },
13513
- ...options.limit === void 0 ? {} : { limit: options.limit }
13514
- });
13515
- return listChatSessionsOperation.execute(input, {
13516
- client,
13517
- signal
13518
- });
13519
- },
13520
- {
13521
- quiet: globalOptions.quiet,
13522
- projectScope: resolved.projectScope,
13523
- cloudScope: resolved.projectScope
13524
- }
13525
- );
13526
- writeResult(result, globalOptions.format);
13527
- }
13067
+ bindOperation(
13068
+ studyCommand(
13069
+ group,
13070
+ "cancel-insights",
13071
+ "Stop an in-flight generation. The recovery path for a window stuck pending \u2014 without it the only way forward is --force, which takes another slice of the daily insight quota."
13072
+ ).requiredOption("--window <id>", "Window ID"),
13073
+ cancelStudyInsightsOperation,
13074
+ (options) => ({
13075
+ project: options.project,
13076
+ study: studyOf(options),
13077
+ window: options.window
13078
+ })
13528
13079
  );
13529
13080
  bindOperation(
13530
- addProjectOption(
13531
- sessions.command("search").description(
13532
- "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."
13533
- ).requiredOption("--query <text>", "Search terms").option(
13534
- "--scope <scope>",
13535
- "titles (default) or transcripts. Transcript search excludes sessions created before 2026-08-14."
13536
- ).option(
13537
- "--source <types>",
13538
- "Comma-separated surfaces: direct, scenario, eval, swarm. Defaults to all."
13539
- ).option("--status <status>", "active (default) or archived").option("--limit <n>", "Results per page (1-200)").option(
13540
- "--cursor <cursor>",
13541
- "Opaque cursor from a previous page's nextCursor. Page with the same --query and --scope you started with."
13542
- )
13081
+ studyCommand(
13082
+ group,
13083
+ "dismiss-finding",
13084
+ "Mark a finding as not worth acting on. Its lifecycle keeps updating underneath."
13085
+ ).requiredOption("--finding <id>", "Finding ID"),
13086
+ dismissStudyFindingOperation,
13087
+ (options) => ({
13088
+ project: options.project,
13089
+ study: studyOf(options),
13090
+ finding: options.finding
13091
+ })
13092
+ );
13093
+ bindOperation(
13094
+ studyCommand(
13095
+ group,
13096
+ "undismiss-finding",
13097
+ "Bring a dismissed finding back into the active list."
13098
+ ).requiredOption("--finding <id>", "Finding ID"),
13099
+ undismissStudyFindingOperation,
13100
+ (options) => ({
13101
+ project: options.project,
13102
+ study: studyOf(options),
13103
+ finding: options.finding
13104
+ })
13105
+ );
13106
+ bindOperation(
13107
+ studyCommand(
13108
+ group,
13109
+ "update",
13110
+ "Rename a study, 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 study live in a mode you did not ask for."
13111
+ ).option("--name <name>").option("--description <text>").option(
13112
+ "--mode <mode>",
13113
+ "project_members | invited_only | anyone_with_link"
13543
13114
  ),
13544
- searchSessionsOperation,
13115
+ updateStudyOperation,
13545
13116
  (options) => ({
13546
- query: requireQuery(options.query),
13547
13117
  project: options.project,
13548
- scope: options.scope,
13549
- sourceTypes: parseSources(options.source),
13550
- status: options.status,
13551
- limit: parseIntegerOption(options.limit, "--limit", {
13552
- min: 1,
13553
- max: 200
13554
- }),
13555
- cursor: options.cursor
13118
+ study: studyOf(options),
13119
+ ...options.name !== void 0 ? { name: options.name } : {},
13120
+ ...options.description !== void 0 ? { description: options.description } : {},
13121
+ ...options.mode !== void 0 ? { mode: options.mode } : {}
13556
13122
  })
13557
13123
  );
13558
- registerSessionsBrowserCommands(sessions);
13559
13124
  bindOperation(
13560
- addBrowserFlags(
13561
- addProjectOption(
13562
- sessions.command("send").description(
13563
- "Send one message to a project's MCP servers and print the reply plus the raw tool calls, latency and token usage. SPENDS model credits. Omit --session to start a conversation; pass the sessionId it returns to continue one."
13564
- ).requiredOption(
13565
- "--message <text>",
13566
- "The message to send, as the user"
13567
- ).requiredOption(
13568
- "--idempotency-key <key>",
13569
- "Stable key for THIS turn's intent. Reuse it when retrying: a retry with the same key replays the completed turn instead of running and billing it again. Do NOT generate a fresh key per attempt."
13570
- ).option(
13571
- "--session <sessionId>",
13572
- "Continue this session instead of starting one. Configuration is fixed at the first turn, so the config flags below are refused with a session. The per-turn flags are not: --client, --max-steps and --max-tool-calls apply to whichever turn sends them, and --client in particular must be RE-SENT on every turn of a host-bound conversation \u2014 a session started with --client alone refuses a continuation that omits it."
13573
- ).option(
13574
- "--model <modelId>",
13575
- 'Provider-prefixed model id, e.g. "anthropic/claude-sonnet-5". Required to start a session; a bare id is rejected rather than guessed.'
13576
- ).option(
13577
- "--client <hostId>",
13578
- "Client ID (from `mcpjam cloud clients list`) to run the turn AS. A client that declares an agent harness (Claude Code, Codex, Cursor CLI) runs the REAL runtime; without one the turn runs MCPJam's emulated engine. Per-turn, NOT pinned to the session \u2014 pass it on every turn, and check the printed `engine` to see what ran. Continuing a session you started with --client alone REQUIRES it: without it the turn is refused rather than answered by the emulated engine. Alongside --environment it only asserts which host you expect (a mismatch is refused). It cannot be combined with --server: --client cannot be pinned beside a pinned server set, so a later turn that omitted it would run the emulated engine on a session established on the harness. Use --environment, or --client alone (which connects the client's own servers). A harness turn needs --tool-mode auto with no --max-tool-calls."
13579
- ).option(
13580
- "--environment <environmentId>",
13581
- "Run against this environment's servers (mutually exclusive with --server). An environment pins its own host, so a harness environment runs its harness on every turn, continuations included."
13582
- ).option(
13583
- "--server <serverId...>",
13584
- "Run against these project servers (mutually exclusive with --environment)"
13585
- ).option("--system-prompt <text>", "System prompt for the session").option(
13586
- "--tool-mode <mode>",
13587
- "read_only (default) advertises only tools annotated readOnlyHint:true. auto advertises everything and MAY CAUSE REAL SIDE EFFECTS."
13588
- ).option("--max-steps <n>", "Maximum engine steps this turn (1-16)").option(
13589
- "--max-tool-calls <n>",
13590
- "Cap the tool calls this turn may make. 0 answers without tools."
13591
- ).option("--temperature <n>", "Sampling temperature (0-2)")
13592
- )
13593
- ),
13594
- {
13595
- ...sendChatMessageOperation,
13596
- execute: (input, context) => waitForSessionTurn(
13597
- () => sendChatMessageOperation.execute(input, context),
13598
- context.signal
13599
- )
13600
- },
13601
- (options) => ({
13602
- idempotencyKey: options.idempotencyKey ?? "",
13603
- message: options.message ?? "",
13604
- browser: browserInput(options),
13605
- project: options.project,
13606
- sessionId: options.session,
13607
- modelId: options.model,
13608
- hostId: options.client,
13609
- environmentId: options.environment,
13610
- serverIds: options.server,
13611
- systemPrompt: options.systemPrompt,
13612
- toolMode: options.toolMode,
13613
- maxSteps: parseIntegerOption(options.maxSteps, "--max-steps", {
13614
- min: 1,
13615
- max: 16
13616
- }),
13617
- maxToolCalls: parseIntegerOption(
13618
- options.maxToolCalls,
13619
- "--max-tool-calls",
13620
- { min: 0, max: 16 }
13621
- ),
13622
- temperature: parseFloatOption(options.temperature)
13623
- }),
13624
- // A Playground turn runs a model, and often tools with it. The 30s program
13625
- // default expired mid-turn while the turn kept running and spending, which
13626
- // reads to the caller as "it failed" when it had not.
13627
- { defaultTimeoutMs: 36e4 }
13125
+ studyCommand(
13126
+ group,
13127
+ "guest-execution",
13128
+ "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."
13129
+ ).requiredOption("--enabled <bool>", "true | false").requiredOption("--computer-enabled <bool>", "true | false").requiredOption("--shared-skills-enabled <bool>", "true | false").requiredOption(
13130
+ "--daily-credit-cap <n>",
13131
+ "Hard ceiling on visitor spend per day, in credits"
13132
+ ).requiredOption("--daily-computer-start-cap <n>").requiredOption("--max-concurrent-computers <n>").option(
13133
+ "--harness-enabled <bool>",
13134
+ "true | false. Omitting this REPLACES any existing harness setting with 'disabled'."
13135
+ ).option("--daily-harness-spend-cap-micros <n>").option("--daily-harness-call-cap <n>").option("--max-concurrent-harness-runs <n>"),
13136
+ setStudyGuestExecutionOperation,
13137
+ (options) => {
13138
+ if (options.harnessEnabled === void 0 && (options.dailyHarnessSpendCapMicros !== void 0 || options.dailyHarnessCallCap !== void 0 || options.maxConcurrentHarnessRuns !== void 0)) {
13139
+ throw usageError(
13140
+ "--harness-enabled is required when any harness cap is given: omitting it disables the harness, so the caps would land on nothing."
13141
+ );
13142
+ }
13143
+ return {
13144
+ project: options.project,
13145
+ study: studyOf(options),
13146
+ enabled: parseBooleanFlag(options.enabled, "--enabled"),
13147
+ computerEnabled: parseBooleanFlag(
13148
+ options.computerEnabled,
13149
+ "--computer-enabled"
13150
+ ),
13151
+ sharedSkillsEnabled: parseBooleanFlag(
13152
+ options.sharedSkillsEnabled,
13153
+ "--shared-skills-enabled"
13154
+ ),
13155
+ dailyCreditCap: parseNumberFlag(
13156
+ options.dailyCreditCap,
13157
+ "--daily-credit-cap"
13158
+ ),
13159
+ dailyComputerStartCap: parseRequiredIntegerOption(
13160
+ options.dailyComputerStartCap,
13161
+ "--daily-computer-start-cap"
13162
+ ),
13163
+ maxConcurrentComputers: parseRequiredIntegerOption(
13164
+ options.maxConcurrentComputers,
13165
+ "--max-concurrent-computers"
13166
+ ),
13167
+ ...options.harnessEnabled !== void 0 ? {
13168
+ harnessEnabled: parseBooleanFlag(
13169
+ options.harnessEnabled,
13170
+ "--harness-enabled"
13171
+ )
13172
+ } : {},
13173
+ ...options.dailyHarnessSpendCapMicros !== void 0 ? {
13174
+ dailyHarnessSpendCapMicros: parseIntegerOption(
13175
+ options.dailyHarnessSpendCapMicros,
13176
+ "--daily-harness-spend-cap-micros"
13177
+ )
13178
+ } : {},
13179
+ ...options.dailyHarnessCallCap !== void 0 ? {
13180
+ dailyHarnessCallCap: parseIntegerOption(
13181
+ options.dailyHarnessCallCap,
13182
+ "--daily-harness-call-cap"
13183
+ )
13184
+ } : {},
13185
+ ...options.maxConcurrentHarnessRuns !== void 0 ? {
13186
+ maxConcurrentHarnessRuns: parseIntegerOption(
13187
+ options.maxConcurrentHarnessRuns,
13188
+ "--max-concurrent-harness-runs"
13189
+ )
13190
+ } : {}
13191
+ };
13192
+ }
13628
13193
  );
13629
13194
  bindOperation(
13630
- addProjectOption(
13631
- sessions.command("show").description(
13632
- "Print a session's metadata and a window of its raw messages. Message indices are ABSOLUTE transcript positions \u2014 the same ones `sessions trace` spans reference."
13633
- ).requiredOption("--session <sessionId>", "The session to read").option(
13634
- "--after-message <index>",
13635
- "Start the window at this absolute transcript index"
13636
- ).option("--limit <n>", "Messages to return (1-200)")
13195
+ studyCommand(
13196
+ group,
13197
+ "rotate-link",
13198
+ "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."
13637
13199
  ),
13638
- getChatSessionOperation,
13200
+ rotateStudyLinkOperation,
13639
13201
  (options) => ({
13640
- sessionId: options.session ?? "",
13641
13202
  project: options.project,
13642
- afterMessageIndex: parseIntegerOption(
13643
- options.afterMessage,
13644
- "--after-message",
13645
- { min: 0 }
13646
- ),
13647
- limit: parseIntegerOption(options.limit, "--limit", { min: 1, max: 200 })
13203
+ study: studyOf(options)
13648
13204
  })
13649
13205
  );
13650
13206
  bindOperation(
13651
- addProjectOption(
13652
- sessions.command("trace").description(
13653
- "Print a session's per-turn execution spans: per-tool-call latency, token usage, and indices into the transcript. Returns the LATEST turn by default \u2014 page older turns with --after-turn, or use --no-spans for cheap summaries."
13654
- ).requiredOption("--session <sessionId>", "The session to trace").option("--turn <turnId>", "Return exactly this turn").option(
13655
- "--after-turn <promptIndex>",
13656
- "Page forward from this turn index (mutually exclusive with --turn)"
13657
- ).option("--limit <n>", "Turns to return (1-20). Defaults to 1.").option("--no-spans", "Return per-turn summaries without span payloads")
13658
- ),
13659
- getChatSessionTraceOperation,
13207
+ studyCommand(
13208
+ group,
13209
+ "invite",
13210
+ "Grant one person access by email. Upsert, so re-inviting an existing member is not an error."
13211
+ ).requiredOption("--email <email>").option("--send-invite-email", "Also email them. Off by default."),
13212
+ upsertStudyMemberOperation,
13660
13213
  (options) => ({
13661
- sessionId: options.session ?? "",
13662
13214
  project: options.project,
13663
- turnId: options.turn,
13664
- afterPromptIndex: parseIntegerOption(options.afterTurn, "--after-turn", {
13665
- min: 0
13666
- }),
13667
- limit: parseIntegerOption(options.limit, "--limit", { min: 1, max: 20 }),
13668
- // Commander's `--no-spans` sets `spans: false` and leaves it `true` when
13669
- // absent, so only an explicit opt-out is forwarded — the route's own
13670
- // default stays the source of truth for everyone else.
13671
- includeSpans: options.spans === false ? false : void 0
13215
+ study: studyOf(options),
13216
+ email: options.email,
13217
+ ...options.sendInviteEmail ? { sendInviteEmail: true } : {}
13672
13218
  })
13673
13219
  );
13674
- }
13675
- function parseFloatOption(value) {
13676
- if (value === void 0) return void 0;
13677
- if (value.trim() === "") {
13678
- throw usageError("--temperature needs a number.");
13679
- }
13680
- const parsed = Number(value);
13681
- if (!Number.isFinite(parsed)) {
13682
- throw usageError("--temperature must be a number.");
13683
- }
13684
- return parsed;
13685
- }
13686
- var SESSIONS_BOUNDS = { min: 1, max: 100 };
13687
- var TURNS_BOUNDS = { min: 1, max: 200 };
13688
- var JOURNEY_COUNT_BOUNDS = { min: 1, max: 5 };
13689
- var PERSONA_COUNT_BOUNDS = { min: 1, max: 12 };
13690
- function groundingArgs(options) {
13691
- requireExactlyOne({
13692
- "--environment": options.environment,
13693
- "--server-attachment": options.serverAttachment
13694
- });
13695
- const journeyCount = parseIntegerOption(
13696
- options.journeyCount,
13697
- "--journey-count",
13698
- JOURNEY_COUNT_BOUNDS
13699
- );
13700
- return {
13701
- ...options.environment ? { environmentId: options.environment } : {},
13702
- ...options.serverAttachment ? { serverAttachmentId: options.serverAttachment } : {},
13703
- ...options.description ? { description: options.description } : {},
13704
- ...journeyCount !== void 0 ? { journeyCount } : {}
13705
- };
13706
- }
13707
- function addConfigOptions(command, required) {
13708
- const sessions = "--sessions-per-target <n>";
13709
- const turns = "--max-turns <n>";
13710
- const sessionsHelp = "Sessions run against EACH target. Total sessions = targets x this, and the total is what spends.";
13711
- const turnsHelp = "Cap on assistant turns per session.";
13712
- return required ? command.requiredOption(sessions, sessionsHelp).requiredOption(turns, turnsHelp) : command.option(sessions, sessionsHelp).option(turns, turnsHelp);
13713
- }
13714
- function addGroundingOptions(command) {
13715
- return command.option(
13716
- "--environment <id>",
13717
- "Ground the drafts in this project environment. Use this one normally."
13718
- ).option(
13719
- "--server-attachment <id>",
13720
- "Legacy grounding source. Prefer --environment."
13721
- ).option("--description <text>", "Who the audience is, in your own words.").option("--journey-count <n>", "How many journeys to draft per persona.");
13722
- }
13723
- function registerSwarmAuthoringCommands(program, journeys) {
13724
- const personas = program.command("personas").description(
13725
- "The reusable synthetic characters Swarms journeys run as. A persona carries a name, a role and behavioural notes; the goal lives on each journey."
13726
- );
13727
13220
  bindOperation(
13728
- addProjectOption(
13729
- personas.command("list").description("List the project's personas.")
13730
- ),
13731
- listPersonasOperation,
13732
- (options) => ({ project: options.project })
13221
+ studyCommand(
13222
+ group,
13223
+ "remove-member",
13224
+ "Revoke one person's access."
13225
+ ).requiredOption("--member <id-or-email>"),
13226
+ removeStudyMemberOperation,
13227
+ (options) => ({
13228
+ project: options.project,
13229
+ study: studyOf(options),
13230
+ member: options.member
13231
+ })
13733
13232
  );
13734
13233
  bindOperation(
13735
- addProjectOption(
13736
- personas.command("get").description("Show one persona in full, including its notes.").requiredOption("--persona <id>", "Persona ID")
13737
- ),
13738
- getPersonaOperation,
13234
+ studyCommand(
13235
+ group,
13236
+ "rebind",
13237
+ "Point a study 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."
13238
+ ).requiredOption("--environment <id>", "Project environment ID"),
13239
+ rebindStudyOperation,
13739
13240
  (options) => ({
13740
13241
  project: options.project,
13741
- persona: options.persona
13242
+ study: studyOf(options),
13243
+ environmentId: options.environment
13742
13244
  })
13743
13245
  );
13744
13246
  bindOperation(
13745
13247
  addProjectOption(
13746
- personas.command("create").description(
13747
- "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."
13748
- ).requiredOption("--name <name>", "Display name").requiredOption(
13749
- "--role <role>",
13750
- "Who they are, in a few words \u2014 'enterprise procurement lead'"
13751
- ).option(
13752
- "--notes <text>",
13753
- "How they behave: what they know, what they will not tolerate, how they phrase things"
13754
- ).option("--idempotency-key <key>", "Retry key")
13248
+ group.command("list").description("List the studies published from a project")
13755
13249
  ),
13756
- createPersonaOperation,
13250
+ listStudiesOperation,
13757
13251
  (options) => ({
13758
- project: options.project,
13759
- name: options.name,
13760
- role: options.role,
13761
- ...options.notes !== void 0 ? { notes: options.notes } : {},
13762
- ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
13252
+ project: options.project
13763
13253
  })
13764
13254
  );
13765
13255
  bindOperation(
13766
13256
  addProjectOption(
13767
- personas.command("update").description(
13768
- "Edit a persona. Finished runs keep the persona they ran as \u2014 editing does not rewrite history."
13769
- ).requiredOption("--persona <id>", "Persona ID").option("--name <name>").option("--role <role>").option("--notes <text>")
13770
- ),
13771
- updatePersonaOperation,
13772
- (options) => ({
13773
- project: options.project,
13774
- persona: options.persona,
13775
- ...options.name !== void 0 ? { name: options.name } : {},
13776
- ...options.role !== void 0 ? { role: options.role } : {},
13777
- ...options.notes !== void 0 ? { notes: options.notes } : {}
13778
- })
13779
- );
13780
- bindOperation(
13781
- addProjectOption(
13782
- personas.command("delete").description(
13783
- "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."
13784
- ).requiredOption("--persona <id>", "Persona ID")
13785
- ),
13786
- deletePersonaOperation,
13787
- (options) => ({
13788
- project: options.project,
13789
- persona: options.persona
13790
- })
13791
- );
13792
- bindOperation(
13793
- addGroundingOptions(
13794
- addProjectOption(
13795
- personas.command("generate").description(
13796
- "Draft candidate personas with a model, grounded in what the project's servers do. SAVES NOTHING \u2014 pipe what you want into `personas create`. Included with MCPJam; no customer credits consumed; counts against the organization's daily generation quota."
13797
- ).option("--persona-count <n>", "Draft a slate of N personas.")
13257
+ group.command("publish").description(
13258
+ "Publish an environment as a study and print its share link. Idempotent \u2014 re-publishing returns the existing study, 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 `studies update` to change an existing study)."
13259
+ ).requiredOption("--environment <id>", "Project environment ID").option("--name <name>", "Study name (create time only)").option("--description <text>", "Study description (create time only)").option(
13260
+ "--mode <mode>",
13261
+ "Who may open the share link (create time only): project_members | invited_only | anyone_with_link"
13798
13262
  )
13799
13263
  ),
13800
- generatePersonasOperation,
13801
- (options) => {
13802
- const personaCount = parseIntegerOption(
13803
- options.personaCount,
13804
- "--persona-count",
13805
- PERSONA_COUNT_BOUNDS
13806
- );
13807
- return {
13808
- project: options.project,
13809
- ...groundingArgs(options),
13810
- ...personaCount !== void 0 ? { personaCount } : {}
13811
- };
13812
- }
13813
- );
13814
- bindOperation(
13815
- addProjectOption(
13816
- journeys.command("get").description(
13817
- "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."
13818
- ).requiredOption("--journey <id>", "Journey ID")
13819
- ),
13820
- getJourneyOperation,
13821
- (options) => ({
13822
- project: options.project,
13823
- journey: options.journey
13824
- })
13825
- );
13826
- bindOperation(
13827
- addConfigOptions(
13828
- addProjectOption(
13829
- journeys.command("create").description(
13830
- "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."
13831
- ).requiredOption(
13832
- "--goal <text>",
13833
- "What the persona is trying to accomplish"
13834
- ).requiredOption("--persona <id>", "Persona ID to run as").option("--name <name>").option("--swarm <id>", "Swarm container ID (authoring provenance)").option(
13835
- "--environment <id>",
13836
- "Environment to fan out across. Repeatable.",
13837
- (value, previous = []) => [...previous, value]
13838
- ).option("--idempotency-key <key>", "Retry key")
13839
- ),
13840
- true
13841
- ),
13842
- createJourneyOperation,
13843
- (options) => ({
13844
- project: options.project,
13845
- goal: options.goal,
13846
- persona: options.persona,
13847
- sessionsPerTarget: parseRequiredIntegerOption(
13848
- options.sessionsPerTarget,
13849
- "--sessions-per-target",
13850
- SESSIONS_BOUNDS
13851
- ),
13852
- maxTurns: parseRequiredIntegerOption(
13853
- options.maxTurns,
13854
- "--max-turns",
13855
- TURNS_BOUNDS
13856
- ),
13857
- ...options.name !== void 0 ? { name: options.name } : {},
13858
- ...options.swarm !== void 0 ? { swarm: options.swarm } : {},
13859
- ...options.environment?.length ? { environmentIds: options.environment } : {},
13860
- ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
13861
- })
13862
- );
13863
- bindOperation(
13864
- addConfigOptions(
13865
- addProjectOption(
13866
- journeys.command("update").description(
13867
- "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."
13868
- ).requiredOption("--journey <id>", "Journey ID").option("--name <name>").option("--goal <text>").option(
13869
- "--environment <id>",
13870
- "Replace the fan-out with these. Repeatable.",
13871
- (value, previous = []) => [...previous, value]
13872
- ).option(
13873
- "--clear-environments",
13874
- "Drop the fan-out and return the journey to its host targets."
13875
- )
13876
- ),
13877
- false
13878
- ),
13879
- updateJourneyOperation,
13264
+ publishStudyOperation,
13880
13265
  (options) => {
13881
- if (options.clearEnvironments && options.environment?.length) {
13882
- throw new Error(
13883
- "--clear-environments and --environment cannot be used together"
13266
+ const mode = options.mode;
13267
+ if (mode !== void 0 && !STUDY_MODES.includes(mode)) {
13268
+ throw usageError(
13269
+ `option '--mode <mode>' must be one of ${STUDY_MODES.join(", ")}`
13884
13270
  );
13885
13271
  }
13886
- requireTogether(
13887
- { flag: "--sessions-per-target", value: options.sessionsPerTarget },
13888
- { flag: "--max-turns", value: options.maxTurns }
13889
- );
13890
13272
  return {
13891
13273
  project: options.project,
13892
- journey: options.journey,
13274
+ environment: options.environment,
13893
13275
  ...options.name !== void 0 ? { name: options.name } : {},
13894
- ...options.goal !== void 0 ? { goal: options.goal } : {},
13895
- ...options.clearEnvironments ? { environmentIds: null } : options.environment?.length ? { environmentIds: options.environment } : {},
13896
- ...options.sessionsPerTarget !== void 0 ? {
13897
- sessionsPerTarget: parseIntegerOption(
13898
- options.sessionsPerTarget,
13899
- "--sessions-per-target",
13900
- SESSIONS_BOUNDS
13901
- )
13902
- } : {},
13903
- ...options.maxTurns !== void 0 ? {
13904
- maxTurns: parseIntegerOption(
13905
- options.maxTurns,
13906
- "--max-turns",
13907
- TURNS_BOUNDS
13908
- )
13909
- } : {}
13276
+ ...options.description !== void 0 ? { description: options.description } : {},
13277
+ ...mode !== void 0 ? { mode } : {}
13910
13278
  };
13911
13279
  }
13912
13280
  );
13913
13281
  bindOperation(
13914
13282
  addProjectOption(
13915
- journeys.command("archive").description(
13916
- "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."
13917
- ).requiredOption("--journey <id>", "Journey ID")
13283
+ group.command("unpublish").description(
13284
+ "Take an environment's study down, invalidating its share link and any live guest sessions. Idempotent."
13285
+ ).requiredOption("--environment <id>", "Project environment ID")
13918
13286
  ),
13919
- archiveJourneyOperation,
13287
+ unpublishStudyOperation,
13920
13288
  (options) => ({
13921
13289
  project: options.project,
13922
- journey: options.journey
13290
+ environment: options.environment
13923
13291
  })
13924
13292
  );
13925
- bindOperation(
13926
- addGroundingOptions(
13927
- addProjectOption(
13928
- journeys.command("generate").description(
13929
- "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; included with MCPJam (no customer credits consumed) and counts against the organization's daily generation quota."
13930
- ).requiredOption("--persona-name <name>").requiredOption("--persona-role <role>").option("--persona-notes <text>")
13931
- )
13932
- ),
13933
- generateJourneysOperation,
13934
- (options) => ({
13935
- project: options.project,
13936
- persona: {
13937
- name: options.personaName,
13938
- role: options.personaRole,
13939
- ...options.personaNotes !== void 0 ? { notes: options.personaNotes } : {}
13940
- },
13941
- ...groundingArgs(options)
13942
- })
13293
+ }
13294
+ var STUDY_MODES = [
13295
+ "project_members",
13296
+ "invited_only",
13297
+ "anyone_with_link"
13298
+ ];
13299
+ function parseBooleanFlag(value, flag) {
13300
+ const normalized = value.trim().toLowerCase();
13301
+ if (normalized === "true") return true;
13302
+ if (normalized === "false") return false;
13303
+ throw new Error(`${flag} must be true or false`);
13304
+ }
13305
+ function parseNumberFlag(value, flag) {
13306
+ const parsed = Number(value);
13307
+ if (!Number.isFinite(parsed) || parsed < 0) {
13308
+ throw new Error(`${flag} must be a non-negative number`);
13309
+ }
13310
+ return parsed;
13311
+ }
13312
+ function resolveSecretValue(options, { required }) {
13313
+ const supplied = [
13314
+ options.value !== void 0 ? "--value" : null,
13315
+ options.valueFile !== void 0 ? "--value-file" : null,
13316
+ options.valueEnv !== void 0 ? "--value-env" : null
13317
+ ].filter((flag) => flag !== null);
13318
+ if (supplied.length > 1) {
13319
+ throw usageError(
13320
+ `Provide exactly one of --value, --value-file, or --value-env (got ${supplied.join(
13321
+ ", "
13322
+ )}).`
13323
+ );
13324
+ }
13325
+ if (supplied.length === 0) {
13326
+ if (!required) return void 0;
13327
+ throw usageError(
13328
+ "A value is required. Prefer --value-file <path>, --value-env <VAR>, or `--value -` to read stdin; --value <literal> works but is written to your shell history."
13329
+ );
13330
+ }
13331
+ if (options.valueEnv !== void 0) {
13332
+ const value = process.env[options.valueEnv];
13333
+ if (value === void 0 || value === "") {
13334
+ throw usageError(
13335
+ `Environment variable "${options.valueEnv}" is not set (or is empty).`
13336
+ );
13337
+ }
13338
+ return value;
13339
+ }
13340
+ const readStdinOrFile = (path9) => {
13341
+ try {
13342
+ return path9 === "-" ? readFileSync(0, "utf8") : readFileSync(path9, "utf8");
13343
+ } catch (error) {
13344
+ throw usageError(
13345
+ path9 === "-" ? "Failed to read the secret value from stdin." : `Failed to read the secret value from "${path9}".`,
13346
+ { source: error instanceof Error ? error.message : String(error) }
13347
+ );
13348
+ }
13349
+ };
13350
+ const stripOneTrailingNewline = (text) => text.replace(/\r?\n$/, "");
13351
+ if (options.valueFile !== void 0) {
13352
+ const raw = readStdinOrFile(options.valueFile);
13353
+ const text = options.valueFile === "-" ? stripOneTrailingNewline(raw) : raw;
13354
+ if (text === "") throw usageError("The secret value is empty.");
13355
+ return text;
13356
+ }
13357
+ if (options.value === "-") {
13358
+ const text = stripOneTrailingNewline(readStdinOrFile("-"));
13359
+ if (text === "") throw usageError("The secret value is empty.");
13360
+ return text;
13361
+ }
13362
+ if (options.value === "") throw usageError("The secret value is empty.");
13363
+ return options.value;
13364
+ }
13365
+ function brokerFields(options) {
13366
+ return {
13367
+ ...options.host !== void 0 && options.host.length > 0 ? { brokerHosts: options.host } : {},
13368
+ ...options.header !== void 0 ? { brokerHeader: options.header } : {},
13369
+ ...options.template !== void 0 ? { brokerTemplate: options.template } : {}
13370
+ };
13371
+ }
13372
+ function collectHost(value, previous = []) {
13373
+ return [...previous, value];
13374
+ }
13375
+ function registerSecretsCommands(program) {
13376
+ const secrets = program.command("secrets").description(
13377
+ "Store and manage the project credentials a workflow needs (stripe, gh, psql). Write-only: no command prints a value."
13943
13378
  );
13944
- bindOperation(
13945
- addProjectOption(
13946
- journeys.command("overview").description(
13947
- "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."
13948
- )
13949
- ),
13950
- getSwarmOverviewOperation,
13951
- (options) => ({ project: options.project })
13379
+ secrets.command("list").description(
13380
+ "List the project's secrets \u2014 metadata only. Shows the project-shared ones plus your own personal ones."
13381
+ ).option(
13382
+ "--project <id-or-name>",
13383
+ "Project name or ID (defaults to the most recently updated project)"
13384
+ ).action(
13385
+ async (options, command) => {
13386
+ const globalOptions = getGlobalOptions(command);
13387
+ const result = await runPlatformOperation(
13388
+ platformOptionsOf(command),
13389
+ globalOptions.timeout,
13390
+ ({ client, signal }) => listSecretsOperation.execute(
13391
+ { project: resolveCloudProjectArgs(options).project },
13392
+ { client, signal }
13393
+ )
13394
+ );
13395
+ writeResult(result, globalOptions.format);
13396
+ }
13952
13397
  );
13953
- bindOperation(
13954
- addProjectOption(
13955
- journeys.command("scorecard").description(
13956
- "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."
13957
- ).requiredOption("--run <id>", "Journey run ID")
13958
- ),
13959
- getJourneyRunScorecardOperation,
13960
- (options) => ({
13961
- project: options.project,
13962
- run: options.run
13963
- })
13398
+ secrets.command("show").description(
13399
+ "Show one secret's metadata: delivery mode, host binding, sharing, last delivery. Never its value."
13400
+ ).requiredOption("--secret <id>", "Secret ID, from `cloud secrets list`").option("--project <id-or-name>", "Project name or ID").action(
13401
+ async (options, command) => {
13402
+ const globalOptions = getGlobalOptions(command);
13403
+ const result = await runPlatformOperation(
13404
+ platformOptionsOf(command),
13405
+ globalOptions.timeout,
13406
+ ({ client, signal }) => getSecretOperation.execute(
13407
+ {
13408
+ project: resolveCloudProjectArgs(options).project,
13409
+ secret: options.secret
13410
+ },
13411
+ { client, signal }
13412
+ )
13413
+ );
13414
+ writeResult(result, globalOptions.format);
13415
+ }
13964
13416
  );
13965
- bindOperation(
13966
- addProjectOption(
13967
- journeys.command("findings").description(
13968
- "Criteria that keep failing across waves, with how long each has been failing."
13969
- )
13970
- ),
13971
- listSwarmFindingsOperation,
13972
- (options) => ({ project: options.project })
13417
+ secrets.command("set").description(
13418
+ "Create a secret. The value comes from --value-file, --value-env, or stdin \u2014 never a positional argument."
13419
+ ).requiredOption(
13420
+ "--name <NAME>",
13421
+ "Environment-variable name (STRIPE_API_KEY). Uppercase, digits, underscores; not starting with a digit. Immutable."
13422
+ ).requiredOption(
13423
+ "--delivery <mode>",
13424
+ "brokered (the proxy injects it outside the sandbox \u2014 extraction-proof, not use-proof, HTTPS only) or materialized (a real env var inside the box, which is what a CLI can read, and which `env` prints)"
13425
+ ).option(
13426
+ "--value-file <path>",
13427
+ "Read the value from a file, VERBATIM \u2014 a trailing newline is kept, because in a PEM block it is part of the credential. `-` reads stdin instead, which drops one trailing newline. Preferred."
13428
+ ).option("--value-env <VAR>", "Read the value from an environment variable.").option(
13429
+ "--value <literal>",
13430
+ "The value inline, or `-` to read stdin. SCRIPTING ONLY: an inline literal is written to your shell history and is visible in `ps` while the command runs."
13431
+ ).option("--description <text>", "What this credential is for.").option(
13432
+ "--host <hostname>",
13433
+ "Brokered only, repeatable: an exact hostname the header is injected on (api.stripe.com). No scheme, no port, no wildcard.",
13434
+ collectHost
13435
+ ).option(
13436
+ "--header <name>",
13437
+ "Brokered only: the header name, e.g. Authorization."
13438
+ ).option(
13439
+ "--template <value>",
13440
+ 'Brokered only: the header value with {} where the secret goes, e.g. "Bearer {}".'
13441
+ ).option(
13442
+ "--sharing <scope>",
13443
+ "project (default; delivered to every member's sessions, admin-only) or user (personal; delivered only in sessions you start)"
13444
+ ).option(
13445
+ "--idempotency-key <key>",
13446
+ "Retry key. Pass one: a retried create without it fails as a name conflict with the row the first attempt already made."
13447
+ ).action(
13448
+ async (options, command) => {
13449
+ const globalOptions = getGlobalOptions(command);
13450
+ const value = resolveSecretValue(options, { required: true });
13451
+ const input = createSecretOperation.inputSchema.safeParse({
13452
+ project: resolveCloudProjectArgs(options).project,
13453
+ name: options.name,
13454
+ value,
13455
+ ...options.description !== void 0 ? { description: options.description } : {},
13456
+ delivery: options.delivery,
13457
+ ...brokerFields(options),
13458
+ ...options.sharing !== void 0 ? { sharing: options.sharing } : {},
13459
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
13460
+ });
13461
+ if (!input.success) {
13462
+ throw usageError(
13463
+ `Invalid input: ${input.error.issues.map(
13464
+ (issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`
13465
+ ).join("; ")}`
13466
+ );
13467
+ }
13468
+ const result = await runPlatformOperation(
13469
+ platformOptionsOf(command),
13470
+ globalOptions.timeout,
13471
+ ({ client, signal }) => createSecretOperation.execute(input.data, { client, signal })
13472
+ );
13473
+ writeResult(result, globalOptions.format);
13474
+ }
13973
13475
  );
13974
- bindOperation(
13975
- addProjectOption(
13976
- journeys.command("dismiss-finding").description(
13977
- "Mark a finding as not worth acting on. Its lifecycle keeps updating underneath, so undismissing later shows honest current state."
13978
- ).requiredOption("--finding <id>", "Finding ID")
13979
- ),
13980
- dismissSwarmFindingOperation,
13981
- (options) => ({
13982
- project: options.project,
13983
- finding: options.finding
13984
- })
13476
+ secrets.command("update").description(
13477
+ "Rotate a secret's value and/or change how it is delivered. A rotation reaches NEW RUNS ONLY \u2014 a session already running keeps the value it was given."
13478
+ ).requiredOption("--secret <id>", "Secret ID, from `cloud secrets list`").option("--project <id-or-name>", "Project name or ID").option(
13479
+ "--value-file <path>",
13480
+ "Read the new value from a file, VERBATIM \u2014 a trailing newline is kept. `-` reads stdin instead, which drops one trailing newline. Preferred."
13481
+ ).option(
13482
+ "--value-env <VAR>",
13483
+ "Read the new value from an environment variable."
13484
+ ).option(
13485
+ "--value <literal>",
13486
+ "The new value inline, or `-` to read stdin. SCRIPTING ONLY \u2014 see `secrets set`."
13487
+ ).option("--description <text>", "Replacement description.").option(
13488
+ "--clear-description",
13489
+ "Remove the description entirely, leaving the secret with none."
13490
+ ).option(
13491
+ "--delivery <mode>",
13492
+ "brokered or materialized. Switching to brokered needs --host/--header/--template in the same call; switching to materialized clears them."
13493
+ ).option("--host <hostname>", "Brokered only, repeatable.", collectHost).option("--header <name>", "Brokered only: the header name.").option("--template <value>", 'Brokered only: e.g. "Bearer {}".').action(
13494
+ async (options, command) => {
13495
+ const globalOptions = getGlobalOptions(command);
13496
+ if (options.description !== void 0 && options.clearDescription) {
13497
+ throw usageError(
13498
+ "Provide either --description or --clear-description, not both."
13499
+ );
13500
+ }
13501
+ const value = resolveSecretValue(options, { required: false });
13502
+ const input = updateSecretOperation.inputSchema.safeParse({
13503
+ project: resolveCloudProjectArgs(options).project,
13504
+ secret: options.secret,
13505
+ ...value !== void 0 ? { value } : {},
13506
+ // `--clear-description` is the flag spelling of the `null` the REST
13507
+ // route and the SDK client already accept. Distinct from
13508
+ // `--description ""`, which SETS an empty description.
13509
+ ...options.clearDescription ? { description: null } : {},
13510
+ ...options.description !== void 0 ? { description: options.description } : {},
13511
+ ...options.delivery !== void 0 ? { delivery: options.delivery } : {},
13512
+ ...brokerFields(options)
13513
+ });
13514
+ if (!input.success) {
13515
+ throw usageError(
13516
+ `Invalid input: ${input.error.issues.map(
13517
+ (issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`
13518
+ ).join("; ")}`
13519
+ );
13520
+ }
13521
+ const result = await runPlatformOperation(
13522
+ platformOptionsOf(command),
13523
+ globalOptions.timeout,
13524
+ ({ client, signal }) => updateSecretOperation.execute(input.data, { client, signal })
13525
+ );
13526
+ writeResult(result, globalOptions.format);
13527
+ }
13985
13528
  );
13986
- bindOperation(
13987
- addProjectOption(
13988
- journeys.command("undismiss-finding").description("Bring a dismissed finding back into the active list.").requiredOption("--finding <id>", "Finding ID")
13989
- ),
13990
- undismissSwarmFindingOperation,
13991
- (options) => ({
13992
- project: options.project,
13993
- finding: options.finding
13994
- })
13529
+ secrets.command("rm").description(
13530
+ "Delete a secret. HARD: the row and the encrypted value both go, and MCPJam stops delivering it. Not blocked when an environment still selects it \u2014 deletion never waits on cleanup. This does NOT revoke the credential at the provider that issued it, and runs already in flight keep the value they were handed."
13531
+ ).requiredOption("--secret <id>", "Secret ID, from `cloud secrets list`").option("--project <id-or-name>", "Project name or ID").action(
13532
+ async (options, command) => {
13533
+ const globalOptions = getGlobalOptions(command);
13534
+ const result = await runPlatformOperation(
13535
+ platformOptionsOf(command),
13536
+ globalOptions.timeout,
13537
+ ({ client, signal }) => deleteSecretOperation.execute(
13538
+ {
13539
+ project: resolveCloudProjectArgs(options).project,
13540
+ secret: options.secret
13541
+ },
13542
+ { client, signal }
13543
+ )
13544
+ );
13545
+ writeResult(result, globalOptions.format);
13546
+ }
13995
13547
  );
13996
- bindOperation(
13997
- addProjectOption(
13998
- journeys.command("insights").description(
13999
- "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."
14000
- ).requiredOption("--wave <id>", "Wave ID (the waveId on a run)")
14001
- ),
14002
- getWaveInsightsOperation,
14003
- (options) => ({
14004
- project: options.project,
14005
- wave: options.wave
14006
- })
13548
+ }
13549
+ async function waitForSessionTurn(run, signal, wait = async (ms, signal2) => {
13550
+ await setTimeout$1(ms, void 0, { signal: signal2 });
13551
+ }) {
13552
+ for (; ; ) {
13553
+ signal?.throwIfAborted();
13554
+ try {
13555
+ return await run();
13556
+ } catch (error) {
13557
+ if (!isPlatformApiError(error) || error.status !== 409 || error.details?.reason !== "TURN_IN_PROGRESS")
13558
+ throw error;
13559
+ const retryAfterMs = error.details.retryAfterMs;
13560
+ if (typeof retryAfterMs !== "number" || !Number.isFinite(retryAfterMs) || retryAfterMs <= 0)
13561
+ throw error;
13562
+ await wait(retryAfterMs, signal);
13563
+ }
13564
+ }
13565
+ }
13566
+ function browserInput(options) {
13567
+ const requested = options.browser || options.browserMode || options.browserOrigins || options.browserTools || options.browserProfile;
13568
+ if (!requested) return void 0;
13569
+ if ((options.browserOrigins || options.browserTools) && !options.browserMode)
13570
+ throw usageError(
13571
+ "--browser-origins and --browser-tools require --browser-mode"
13572
+ );
13573
+ if (options.browserMode && !["allow_all", "read_only", "allowlist"].includes(options.browserMode))
13574
+ throw usageError(
13575
+ "--browser-mode must be allow_all, read_only, or allowlist"
13576
+ );
13577
+ const policy = options.browserMode ? platformBrowserToolPolicySchema.safeParse({
13578
+ mode: options.browserMode,
13579
+ ...options.browserOrigins ? { originAllowlist: options.browserOrigins } : {},
13580
+ ...options.browserTools ? { toolAllowlist: options.browserTools } : {}
13581
+ }) : void 0;
13582
+ if (policy && !policy.success) throw usageError(policy.error.message);
13583
+ return {
13584
+ ...policy?.success ? { policy: policy.data } : {},
13585
+ ...options.browserProfile ? { profileId: options.browserProfile } : {}
13586
+ };
13587
+ }
13588
+ function addBrowserFlags(command) {
13589
+ return command.option("--browser", "Attach the session browser for this turn").option(
13590
+ "--browser-mode <mode>",
13591
+ "Initial browser grant: allow_all, read_only, or allowlist"
13592
+ ).option("--browser-origins <origins...>", "Allowed HTTP(S) origins").option(
13593
+ "--browser-tools <tools...>",
13594
+ "Allowed browser_* or webmcp:<name> tools"
13595
+ ).option("--browser-profile <profileId>", "Initial saved browser profile");
13596
+ }
13597
+ function json(text) {
13598
+ if (text === void 0) return void 0;
13599
+ try {
13600
+ return JSON.parse(text);
13601
+ } catch {
13602
+ throw usageError("Expected valid JSON");
13603
+ }
13604
+ }
13605
+ function registerSessionsBrowserCommands(sessions) {
13606
+ const browser = sessions.command("browser").description(
13607
+ "Drive the same hosted browser as an API Playground session. Uses metered desktop time."
14007
13608
  );
13609
+ const common = (command, required = true) => (required ? command.requiredOption("--session <id>", "Public chat session ID") : command.option("--session <id>", "Existing public chat session ID")).option("--command-id <id>", "Stable command ID for retries");
14008
13610
  bindOperation(
14009
- addProjectOption(
14010
- journeys.command("request-insights").description(
14011
- "Ask a model to analyze a whole wave. Returns immediately as pending; poll `journeys insights`. Included with MCPJam \u2014 no credits are consumed; it counts against a daily insight quota shared with user-testing insights. Read the scorecards first \u2014 they cost no quota and usually explain the failure."
14012
- ).requiredOption("--wave <id>", "Wave ID").option(
14013
- "--force",
14014
- "Regenerate over a wave that already has insights. Takes another slice of the daily insight quota."
14015
- )
13611
+ addBrowserFlags(
13612
+ addProjectOption(common(browser.command("open"), false))
13613
+ ).option(
13614
+ "--idempotency-key <key>",
13615
+ "Stable key when creating a new session"
14016
13616
  ),
14017
- requestWaveInsightsOperation,
14018
- (options) => ({
14019
- project: options.project,
14020
- wave: options.wave,
14021
- ...options.force ? { force: true } : {}
14022
- })
13617
+ driveChatSessionBrowserOperation,
13618
+ (o) => {
13619
+ if (!o.session && !o.idempotencyKey)
13620
+ throw usageError(
13621
+ "--idempotency-key is required when creating a session; reuse it after a timeout"
13622
+ );
13623
+ if (!o.session && !o.browserMode)
13624
+ throw usageError("--browser-mode is required when creating a session");
13625
+ return {
13626
+ op: "open",
13627
+ sessionId: o.session,
13628
+ project: o.project,
13629
+ ...browserInput({ ...o, browser: true }),
13630
+ idempotencyKey: o.idempotencyKey
13631
+ };
13632
+ },
13633
+ { defaultTimeoutMs: 36e4 }
14023
13634
  );
14024
13635
  bindOperation(
14025
- addProjectOption(
14026
- journeys.command("cancel-insights").description(
14027
- "Stop an in-flight insights generation. The recovery path for a wave stuck pending \u2014 without it the only way forward is --force, which takes another slice of the daily insight quota."
14028
- ).requiredOption("--wave <id>", "Wave ID")
14029
- ),
14030
- cancelWaveInsightsOperation,
14031
- (options) => ({
14032
- project: options.project,
14033
- wave: options.wave
14034
- })
14035
- );
14036
- const swarms = program.command("swarms").description(
14037
- "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."
14038
- );
14039
- bindOperation(
14040
- addProjectOption(
14041
- swarms.command("list").description("List the project's swarm containers.")
14042
- ),
14043
- listSwarmsOperation,
14044
- (options) => ({ project: options.project })
13636
+ common(browser.command("navigate <url>")),
13637
+ driveChatSessionBrowserOperation,
13638
+ (o, url) => ({
13639
+ op: "navigate",
13640
+ sessionId: o.session,
13641
+ url,
13642
+ commandId: o.commandId ?? randomUUID()
13643
+ }),
13644
+ { defaultTimeoutMs: 36e4 }
14045
13645
  );
14046
13646
  bindOperation(
14047
- addProjectOption(
14048
- swarms.command("get").description("Show one swarm container.").requiredOption("--swarm <id>", "Swarm container ID")
14049
- ),
14050
- getSwarmOperation,
14051
- (options) => ({
14052
- project: options.project,
14053
- swarm: options.swarm
14054
- })
13647
+ common(browser.command("act")).requiredOption(
13648
+ "--verb <verb>",
13649
+ "click, type, press, scroll, hover, drag, select, or dialog/tab action"
13650
+ ).option("--target <json>", "Target ref, selector, or coordinates").option("--value <text>", "Action value").option("--expected-state <token>", "Observation state token"),
13651
+ driveChatSessionBrowserOperation,
13652
+ (o) => ({
13653
+ op: "act",
13654
+ sessionId: o.session,
13655
+ commandId: o.commandId ?? randomUUID(),
13656
+ command: {
13657
+ verb: o.verb,
13658
+ target: json(o.target),
13659
+ value: o.value,
13660
+ expectedState: o.expectedState
13661
+ }
13662
+ }),
13663
+ { defaultTimeoutMs: 36e4 }
14055
13664
  );
14056
13665
  bindOperation(
14057
- addConfigOptions(
14058
- addProjectOption(
14059
- swarms.command("create").description(
14060
- "Create a container to author journeys under. Runs nothing."
14061
- ).requiredOption("--name <name>").option("--description <text>").option(
14062
- "--environment <id>",
14063
- "Default fan-out for journeys authored here. Repeatable.",
14064
- (value, previous = []) => [...previous, value]
14065
- ).option("--idempotency-key <key>", "Retry key")
14066
- ),
14067
- true
13666
+ common(browser.command("invoke <toolKey>")).requiredOption(
13667
+ "--input <json>",
13668
+ "Page tool input"
14068
13669
  ),
14069
- createSwarmOperation,
14070
- (options) => ({
14071
- project: options.project,
14072
- name: options.name,
14073
- sessionsPerTarget: parseRequiredIntegerOption(
14074
- options.sessionsPerTarget,
14075
- "--sessions-per-target",
14076
- SESSIONS_BOUNDS
14077
- ),
14078
- maxTurns: parseRequiredIntegerOption(
14079
- options.maxTurns,
14080
- "--max-turns",
14081
- TURNS_BOUNDS
14082
- ),
14083
- ...options.description !== void 0 ? { description: options.description } : {},
14084
- ...options.environment?.length ? { environmentIds: options.environment } : {},
14085
- ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
14086
- })
13670
+ driveChatSessionBrowserOperation,
13671
+ (o, toolKey) => ({
13672
+ op: "invoke",
13673
+ sessionId: o.session,
13674
+ toolKey,
13675
+ input: json(o.input),
13676
+ commandId: o.commandId ?? randomUUID()
13677
+ }),
13678
+ { defaultTimeoutMs: 36e4 }
14087
13679
  );
14088
13680
  bindOperation(
14089
- addConfigOptions(
14090
- addProjectOption(
14091
- swarms.command("update").description(
14092
- "Edit a swarm container. --sessions-per-target and --max-turns must be given together."
14093
- ).requiredOption("--swarm <id>", "Swarm container ID").option("--name <name>").option("--description <text>").option(
14094
- "--environment <id>",
14095
- "Replace the default fan-out. Repeatable.",
14096
- (value, previous = []) => [...previous, value]
14097
- )
14098
- ),
14099
- false
14100
- ),
14101
- updateSwarmOperation,
14102
- (options) => ({
14103
- project: options.project,
14104
- swarm: options.swarm,
14105
- ...options.name !== void 0 ? { name: options.name } : {},
14106
- ...options.description !== void 0 ? { description: options.description } : {},
14107
- ...options.environment?.length ? { environmentIds: options.environment } : {},
14108
- ...options.sessionsPerTarget !== void 0 ? {
14109
- sessionsPerTarget: parseIntegerOption(
14110
- options.sessionsPerTarget,
14111
- "--sessions-per-target"
14112
- )
14113
- } : {},
14114
- ...options.maxTurns !== void 0 ? { maxTurns: parseIntegerOption(options.maxTurns, "--max-turns") } : {}
13681
+ common(browser.command("note <text>")),
13682
+ driveChatSessionBrowserOperation,
13683
+ (o, text) => ({
13684
+ op: "note",
13685
+ sessionId: o.session,
13686
+ text,
13687
+ commandId: o.commandId ?? randomUUID()
14115
13688
  })
14116
13689
  );
14117
13690
  bindOperation(
14118
- addProjectOption(
14119
- swarms.command("archive").description(
14120
- "Take a container off the roster. Journeys authored under it keep working \u2014 the reference is authoring provenance, not ownership."
14121
- ).requiredOption("--swarm <id>", "Swarm container ID")
14122
- ),
14123
- archiveSwarmOperation,
14124
- (options) => ({
14125
- project: options.project,
14126
- swarm: options.swarm
13691
+ common(browser.command("close")),
13692
+ driveChatSessionBrowserOperation,
13693
+ (o) => ({
13694
+ op: "close",
13695
+ sessionId: o.session
14127
13696
  })
14128
13697
  );
13698
+ for (const op of ["observe", "trace", "artifact"]) {
13699
+ const command = common(browser.command(op)).option("--mode <mode>", "Observation mode (default screenshot)").option("--download <dir>", "Download screenshot to this directory");
13700
+ bindOperation(
13701
+ command,
13702
+ {
13703
+ ...observeChatSessionBrowserOperation,
13704
+ execute: async (input, context) => {
13705
+ const { download, ...wire } = input;
13706
+ if (op === "trace" && download)
13707
+ throw usageError("Use observe or artifact with --download");
13708
+ const result = await observeChatSessionBrowserOperation.execute(
13709
+ wire,
13710
+ context
13711
+ );
13712
+ if (!download) return result;
13713
+ let artifact = result;
13714
+ if (op !== "artifact") {
13715
+ const commandId = wire.commandId;
13716
+ if (!commandId)
13717
+ throw usageError("--download requires a command ID");
13718
+ artifact = await context.client.chatSessionBrowser(
13719
+ wire.sessionId,
13720
+ "artifact",
13721
+ { commandId },
13722
+ { signal: context.signal }
13723
+ );
13724
+ }
13725
+ if (!("url" in artifact) || typeof artifact.url !== "string")
13726
+ throw usageError("No screenshot is available for this command");
13727
+ const bytes = await fetchArtifactBytes(artifact.url, 3e4);
13728
+ const extension = bytes[0] === 255 && bytes[1] === 216 ? "jpg" : "png";
13729
+ const dir = resolve(download);
13730
+ await mkdir(dir, { recursive: true });
13731
+ const path9 = resolve(
13732
+ dir,
13733
+ `${(wire.commandId ?? "screenshot").replace(
13734
+ /[^A-Za-z0-9_.-]/g,
13735
+ "_"
13736
+ )}.${extension}`
13737
+ );
13738
+ await writeFile(path9, bytes);
13739
+ return { ...result, savedTo: path9 };
13740
+ }
13741
+ },
13742
+ (o) => {
13743
+ if (op === "artifact" && !o.commandId)
13744
+ throw usageError("artifact requires --command-id");
13745
+ return {
13746
+ op,
13747
+ sessionId: o.session,
13748
+ commandId: o.commandId ?? (op === "observe" ? randomUUID() : void 0),
13749
+ mode: o.mode,
13750
+ download: o.download
13751
+ };
13752
+ },
13753
+ { defaultTimeoutMs: 36e4 }
13754
+ );
13755
+ }
14129
13756
  }
14130
- function collect(value, previous = []) {
14131
- return [...previous, value];
13757
+ function requireQuery(value) {
13758
+ const trimmed2 = value?.trim() ?? "";
13759
+ if (trimmed2.length === 0) {
13760
+ throw usageError("--query needs search terms.");
13761
+ }
13762
+ return trimmed2;
14132
13763
  }
14133
- var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
14134
- function splitOnFirst(raw, separator, flag) {
14135
- const index = raw.indexOf(separator);
14136
- if (index < 0) {
13764
+ function parseSources(value) {
13765
+ if (value === void 0) return void 0;
13766
+ const parsed = value.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
13767
+ if (parsed.length === 0) {
14137
13768
  throw usageError(
14138
- `${flag} expects "Name${separator}value"; the argument had no "${separator}".`
13769
+ "--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."
14139
13770
  );
14140
13771
  }
14141
- const name = raw.slice(0, index).trim();
14142
- if (!name) {
14143
- throw usageError(`${flag} has an empty name before the "${separator}".`);
14144
- }
14145
- return [name, raw.slice(index + separator.length)];
13772
+ return parsed;
14146
13773
  }
14147
- function resolveHeaders(options) {
14148
- const headers = /* @__PURE__ */ Object.create(null);
14149
- const seen = /* @__PURE__ */ new Map();
14150
- const named = (options.header?.length ?? 0) + (options.headerEnv?.length ?? 0) + (options.headerFile?.length ?? 0);
14151
- if (options.clearHeaders) {
14152
- if (named > 0) {
14153
- throw usageError(
14154
- "--clear-headers removes every header, so it cannot be combined with a header flag. Pass one or the other."
14155
- );
14156
- }
14157
- return {};
14158
- }
14159
- const put = (name, value, flag) => {
14160
- if (!HEADER_NAME_PATTERN.test(name)) {
14161
- throw usageError(
14162
- `That ${flag} name is not an HTTP token. Use letters, digits and !#$%&'*+.^_\`|~- only.`
14163
- );
14164
- }
14165
- const key = name.toLowerCase();
14166
- const previous = seen.get(key);
14167
- if (previous !== void 0) {
14168
- throw usageError(
14169
- `Header "${name}" was given twice (already set by ${previous}). HTTP header names are case-insensitive.`
14170
- );
14171
- }
14172
- if (/[\r\n\0]/.test(value)) {
14173
- throw usageError(
14174
- `Header "${name}" contains a newline or a null byte. A header value cannot span lines.`
14175
- );
14176
- }
14177
- if (value === "") {
14178
- throw usageError(`The value for header "${name}" is empty.`);
14179
- }
14180
- seen.set(key, flag);
14181
- headers[name] = value;
14182
- };
14183
- for (const raw of options.header ?? []) {
14184
- const [name, value] = splitOnFirst(raw, ":", "--header");
14185
- put(name, value.trim(), "--header");
14186
- }
14187
- for (const raw of options.headerEnv ?? []) {
14188
- const [name, variable] = splitOnFirst(raw, "=", "--header-env");
14189
- const value = process.env[variable.trim()];
14190
- if (value === void 0 || value === "") {
14191
- throw usageError(
14192
- `Environment variable "${variable.trim()}" is not set (or is empty).`
14193
- );
14194
- }
14195
- put(name, value, "--header-env");
13774
+ function validateOpInput2(op, raw) {
13775
+ const parsed = op.inputSchema.safeParse(raw);
13776
+ if (!parsed.success) {
13777
+ const detail = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ");
13778
+ const error = new Error(`Invalid input: ${detail}`);
13779
+ error.exitCode = 2;
13780
+ throw error;
14196
13781
  }
14197
- for (const raw of options.headerFile ?? []) {
14198
- const [name, path9] = splitOnFirst(raw, "=", "--header-file");
14199
- const target = path9.trim();
14200
- let contents;
14201
- try {
14202
- contents = target === "-" ? readFileSync(0, "utf8") : readFileSync(target, "utf8");
14203
- } catch (error) {
14204
- throw usageError(
14205
- target === "-" ? `Failed to read the value for header "${name}" from stdin.` : `Failed to read the value for header "${name}" from "${target}".`,
14206
- { source: error instanceof Error ? error.message : String(error) }
14207
- );
14208
- }
14209
- put(name, contents.replace(/\r?\n$/, ""), "--header-file");
14210
- }
14211
- return Object.keys(headers).length > 0 ? { ...headers } : void 0;
14212
- }
14213
- function resolveAttributes(pairs) {
14214
- if (!pairs || pairs.length === 0) return void 0;
14215
- const out = /* @__PURE__ */ Object.create(null);
14216
- for (const raw of pairs) {
14217
- const [key, value] = splitOnFirst(raw, "=", "--attr");
14218
- if (Object.prototype.hasOwnProperty.call(out, key)) {
14219
- throw usageError(`Resource attribute "${key}" was given twice.`);
14220
- }
14221
- out[key] = value;
14222
- }
14223
- return { ...out };
14224
- }
14225
- var SOURCE_TYPES = ["eval", "scenario", "swarm", "direct"];
14226
- function resolveSourceTypes(values) {
14227
- if (!values || values.length === 0) return void 0;
14228
- const out = [];
14229
- for (const raw of values) {
14230
- const value = raw.trim();
14231
- if (!SOURCE_TYPES.includes(value)) {
14232
- throw usageError(
14233
- `--source expects one of ${SOURCE_TYPES.join(
14234
- ", "
14235
- )} (got ${JSON.stringify(raw)}).`
14236
- );
14237
- }
14238
- if (!out.includes(value)) out.push(value);
14239
- }
14240
- return out;
13782
+ return parsed.data;
14241
13783
  }
14242
- var ORG_FLAG_DESCRIPTION = "Organization ID, from `cloud organizations list`";
14243
- function registerTraceDestinationsCommands(program) {
14244
- const destinations = program.command("trace-destinations").alias("traces").description(
14245
- "Stream an organization's traces to an OTLP/HTTP endpoint (Coralogix, Honeycomb, Grafana, a collector). Header values are write-only: no command prints one."
13784
+ function registerSessionsCommands(program) {
13785
+ const sessions = program.command("sessions").description(
13786
+ "List Playground chat sessions, or search conversations across Playground, user testing, evals and swarms."
14246
13787
  );
14247
- destinations.command("list").description(
14248
- "List the organization's destinations \u2014 endpoint, sources, redaction setting and delivery health. Header names only, never their values."
14249
- ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).action(async (options, command) => {
14250
- const globalOptions = getGlobalOptions(command);
14251
- const result = await runPlatformOperation(
14252
- platformOptionsOf(command),
14253
- globalOptions.timeout,
14254
- ({ client, signal }) => listTraceDestinationsOperation.execute(
14255
- { organization: options.org },
14256
- { client, signal }
14257
- ),
14258
- { cloudScope: { kind: "organization", organization: options.org } }
14259
- );
14260
- writeResult(result, globalOptions.format);
14261
- });
14262
- destinations.command("show").description(
14263
- "Show one destination in full, including delivery health: the last HTTP status the vendor answered with, sessions and spans delivered, and how many are still queued."
14264
- ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption(
14265
- "--destination <id>",
14266
- "Destination ID, from `cloud trace-destinations list`"
14267
- ).action(async (options, command) => {
14268
- const globalOptions = getGlobalOptions(command);
14269
- const result = await runPlatformOperation(
14270
- platformOptionsOf(command),
14271
- globalOptions.timeout,
14272
- ({ client, signal }) => getTraceDestinationOperation.execute(
14273
- { organization: options.org, destination: options.destination },
14274
- { client, signal }
14275
- ),
14276
- { cloudScope: { kind: "organization", organization: options.org } }
14277
- );
14278
- writeResult(result, globalOptions.format);
14279
- });
14280
- destinations.command("create").description(
14281
- "Create a destination and start streaming. Header values come from --header-env or --header-file; --header takes one inline for scripting."
14282
- ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--name <name>", "Human label for this destination.").requiredOption(
14283
- "--endpoint <url>",
14284
- "The vendor's OTLP/HTTP intake, HTTPS only. `/v1/traces` is appended if the path does not already end there."
14285
- ).option(
14286
- "--header-env <Name=VAR>",
14287
- "Repeatable: read a header's value from an environment variable. Preferred.",
14288
- collect
14289
- ).option(
14290
- "--header-file <Name=path>",
14291
- "Repeatable: read a header's value from a file (`-` reads stdin). One trailing newline is dropped \u2014 a header cannot span lines.",
14292
- collect
14293
- ).option(
14294
- "--header <Name: value>",
14295
- "Repeatable, SCRIPTING ONLY: an inline header value is written to your shell history and is visible in `ps` while the command runs.",
14296
- collect
14297
- ).option(
14298
- "--attr <key=value>",
14299
- "Repeatable: an extra OTel resource attribute (cx.application.name=mcpjam). `mcpjam.*` names are reserved by the exporter.",
14300
- collect
14301
- ).option(
14302
- "--source <type>",
14303
- "Repeatable: eval, scenario, swarm or direct. `direct` is Playground, and only sessions SHARED to the workspace are ever sent. Defaults to the server's default set.",
14304
- collect
14305
- ).option(
14306
- "--include-content",
14307
- "Send prompts, outputs, tool arguments and screenshots. OFF by default, and off is the safe reading \u2014 this decides whether customer content leaves the platform."
14308
- ).option(
14309
- "--project <id>",
14310
- "Repeatable: restrict to these projects. Omit for every project in the organization, present and future.",
14311
- collect
14312
- ).option(
14313
- "--compression <mode>",
14314
- "gzip or none. gzip is optional in OTLP/HTTP and some intakes reject it."
14315
- ).option(
14316
- "--preset <id>",
14317
- "Vendor preset id this was created from (coralogix, honeycomb, \u2026). Labelling only."
14318
- ).option("--disabled", "Create it without starting the stream.").action(
13788
+ addProjectOption(
13789
+ sessions.command("list").description(
13790
+ "List Playground chat sessions, newest first (one project; pass --all-projects to include every accessible project)"
13791
+ )
13792
+ ).addOption(
13793
+ new Option(
13794
+ "--all-projects",
13795
+ "List sessions across every accessible project, ignoring the project link and MCPJAM_PROJECT"
13796
+ ).conflicts("project")
13797
+ ).option("--status <status>", "Filter by session status").option(
13798
+ "--limit <n>",
13799
+ "Maximum sessions to return (1-200)",
13800
+ (value) => Number.parseInt(value, 10)
13801
+ ).action(
14319
13802
  async (options, command) => {
14320
13803
  const globalOptions = getGlobalOptions(command);
14321
- const headers = resolveHeaders(options);
14322
- const resourceAttributes = resolveAttributes(options.attr);
14323
- const sourceTypes = resolveSourceTypes(options.source);
14324
- if (options.compression !== void 0 && options.compression !== "gzip" && options.compression !== "none") {
14325
- throw usageError("--compression expects gzip or none.");
13804
+ if (options.allProjects) {
13805
+ const input = validateOpInput2(listChatSessionsOperation, {
13806
+ ...options.status === void 0 ? {} : { status: options.status },
13807
+ ...options.limit === void 0 ? {} : { limit: options.limit }
13808
+ });
13809
+ const result2 = await runPlatformOperation(
13810
+ platformOptionsOf(command),
13811
+ globalOptions.timeout,
13812
+ ({ client, signal }) => listChatSessionsOperation.execute(input, { client, signal }),
13813
+ {
13814
+ quiet: globalOptions.quiet,
13815
+ cloudScope: { kind: "all-projects" }
13816
+ }
13817
+ );
13818
+ writeResult(result2, globalOptions.format);
13819
+ return;
14326
13820
  }
13821
+ const resolved = resolveCloudProjectArgs(options);
14327
13822
  const result = await runPlatformOperation(
14328
13823
  platformOptionsOf(command),
14329
13824
  globalOptions.timeout,
14330
- ({ client, signal }) => createTraceDestinationOperation.execute(
14331
- {
14332
- organization: options.org,
14333
- name: options.name,
14334
- endpointUrl: options.endpoint,
14335
- ...headers ? { headers } : {},
14336
- ...resourceAttributes ? { resourceAttributes } : {},
14337
- ...sourceTypes ? { sourceTypes } : {},
14338
- ...options.includeContent ? { includeContent: true } : {},
14339
- ...options.project ? { projectIds: options.project } : {},
14340
- ...options.compression ? { compression: options.compression } : {},
14341
- ...options.preset ? { preset: options.preset } : {},
14342
- ...options.disabled ? { enabled: false } : {}
14343
- },
14344
- { client, signal }
14345
- ),
14346
- { cloudScope: { kind: "organization", organization: options.org } }
13825
+ async ({ client, signal }) => {
13826
+ let project = resolved.project;
13827
+ if (project === void 0) {
13828
+ const page = await client.listProjects({}, { signal });
13829
+ const resolution = resolveProject(page.items, void 0);
13830
+ if (!resolution.ok) {
13831
+ throw usageError(
13832
+ appendProjectLinkHint(
13833
+ resolution.message,
13834
+ resolved.projectScope
13835
+ )
13836
+ );
13837
+ }
13838
+ project = resolution.project.id;
13839
+ }
13840
+ const input = validateOpInput2(listChatSessionsOperation, {
13841
+ project,
13842
+ ...options.status === void 0 ? {} : { status: options.status },
13843
+ ...options.limit === void 0 ? {} : { limit: options.limit }
13844
+ });
13845
+ return listChatSessionsOperation.execute(input, {
13846
+ client,
13847
+ signal
13848
+ });
13849
+ },
13850
+ {
13851
+ quiet: globalOptions.quiet,
13852
+ projectScope: resolved.projectScope,
13853
+ cloudScope: resolved.projectScope
13854
+ }
14347
13855
  );
14348
13856
  writeResult(result, globalOptions.format);
14349
13857
  }
14350
13858
  );
14351
- destinations.command("update").description(
14352
- "Edit a destination. Any header flag REPLACES the whole header set; passing none leaves the stored headers alone."
14353
- ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--destination <id>", "Destination ID").option("--name <name>", "New label.").option("--endpoint <url>", "New OTLP/HTTP intake, HTTPS only.").option(
14354
- "--header-env <Name=VAR>",
14355
- "Repeatable: read a header's value from an environment variable. Preferred.",
14356
- collect
14357
- ).option(
14358
- "--header-file <Name=path>",
14359
- "Repeatable: read a header's value from a file (`-` reads stdin).",
14360
- collect
14361
- ).option(
14362
- "--header <Name: value>",
14363
- "Repeatable, SCRIPTING ONLY: written to your shell history and visible in `ps`.",
14364
- collect
14365
- ).option(
14366
- "--clear-headers",
14367
- "Remove every stored header. Reach for this before pointing a destination at a new endpoint that must not receive the old vendor's credentials \u2014 omitting the header flags LEAVES them, which is not the same thing."
14368
- ).option(
14369
- "--attr <key=value>",
14370
- "Repeatable: REPLACES the resource attributes.",
14371
- collect
14372
- ).option("--source <type>", "Repeatable: REPLACES the source list.", collect).option("--include-content", "Start sending content. Audited.").option("--no-include-content", "Stop sending content; redact again.").option(
14373
- "--project <id>",
14374
- "Repeatable: REPLACES the project allowlist.",
14375
- collect
14376
- ).option(
14377
- "--all-projects",
14378
- "Stream every project in the organization. The explicit way back \u2014 an empty --project list would mean a destination that matches nothing."
14379
- ).option("--compression <mode>", "gzip or none.").option("--enable", "Start streaming.").option("--disable", "Stop streaming, keeping the configuration.").action(
14380
- async (options, command) => {
14381
- const globalOptions = getGlobalOptions(command);
14382
- if (options.enable && options.disable) {
14383
- throw usageError("Pass --enable or --disable, not both.");
14384
- }
14385
- if (options.allProjects && options.project) {
14386
- throw usageError(
14387
- "Pass --all-projects or --project, not both \u2014 they are two answers to the same question."
14388
- );
14389
- }
14390
- if (options.compression !== void 0 && options.compression !== "gzip" && options.compression !== "none") {
14391
- throw usageError("--compression expects gzip or none.");
14392
- }
14393
- const headers = resolveHeaders(options);
14394
- const resourceAttributes = resolveAttributes(options.attr);
14395
- const sourceTypes = resolveSourceTypes(options.source);
14396
- const enabled = options.enable ? true : options.disable ? false : void 0;
14397
- const patch = {
14398
- ...options.name !== void 0 ? { name: options.name } : {},
14399
- ...options.endpoint !== void 0 ? { endpointUrl: options.endpoint } : {},
14400
- ...headers ? { headers } : {},
14401
- ...resourceAttributes ? { resourceAttributes } : {},
13859
+ bindOperation(
13860
+ addProjectOption(
13861
+ sessions.command("search").description(
13862
+ "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."
13863
+ ).requiredOption("--query <text>", "Search terms").option(
13864
+ "--scope <scope>",
13865
+ "titles (default) or transcripts. Transcript search excludes sessions created before 2026-08-14."
13866
+ ).option(
13867
+ "--source <types>",
13868
+ "Comma-separated surfaces: direct, scenario, eval, swarm. Defaults to all."
13869
+ ).option("--status <status>", "active (default) or archived").option("--limit <n>", "Results per page (1-200)").option(
13870
+ "--cursor <cursor>",
13871
+ "Opaque cursor from a previous page's nextCursor. Page with the same --query and --scope you started with."
13872
+ )
13873
+ ),
13874
+ searchSessionsOperation,
13875
+ (options) => ({
13876
+ query: requireQuery(options.query),
13877
+ project: options.project,
13878
+ scope: options.scope,
13879
+ sourceTypes: parseSources(options.source),
13880
+ status: options.status,
13881
+ limit: parseIntegerOption(options.limit, "--limit", {
13882
+ min: 1,
13883
+ max: 200
13884
+ }),
13885
+ cursor: options.cursor
13886
+ })
13887
+ );
13888
+ registerSessionsBrowserCommands(sessions);
13889
+ bindOperation(
13890
+ addBrowserFlags(
13891
+ addProjectOption(
13892
+ sessions.command("send").description(
13893
+ "Send one message to a project's MCP servers and print the reply plus the raw tool calls, latency and token usage. SPENDS model credits. Omit --session to start a conversation; pass the sessionId it returns to continue one."
13894
+ ).requiredOption(
13895
+ "--message <text>",
13896
+ "The message to send, as the user"
13897
+ ).requiredOption(
13898
+ "--idempotency-key <key>",
13899
+ "Stable key for THIS turn's intent. Reuse it when retrying: a retry with the same key replays the completed turn instead of running and billing it again. Do NOT generate a fresh key per attempt."
13900
+ ).option(
13901
+ "--session <sessionId>",
13902
+ "Continue this session instead of starting one. Configuration is fixed at the first turn, so the config flags below are refused with a session. The per-turn flags are not: --client, --max-steps and --max-tool-calls apply to whichever turn sends them, and --client in particular must be RE-SENT on every turn of a host-bound conversation \u2014 a session started with --client alone refuses a continuation that omits it."
13903
+ ).option(
13904
+ "--model <modelId>",
13905
+ 'Provider-prefixed model id, e.g. "anthropic/claude-sonnet-5". Required to start a session; a bare id is rejected rather than guessed.'
13906
+ ).option(
13907
+ "--client <hostId>",
13908
+ "Client ID (from `mcpjam cloud clients list`) to run the turn AS. A client that declares an agent harness (Claude Code, Codex, Cursor CLI) runs the REAL runtime; without one the turn runs MCPJam's emulated engine. Per-turn, NOT pinned to the session \u2014 pass it on every turn, and check the printed `engine` to see what ran. Continuing a session you started with --client alone REQUIRES it: without it the turn is refused rather than answered by the emulated engine. Alongside --environment it only asserts which host you expect (a mismatch is refused). It cannot be combined with --server: --client cannot be pinned beside a pinned server set, so a later turn that omitted it would run the emulated engine on a session established on the harness. Use --environment, or --client alone (which connects the client's own servers). A harness turn needs --tool-mode auto with no --max-tool-calls."
13909
+ ).option(
13910
+ "--environment <environmentId>",
13911
+ "Run against this environment's servers (mutually exclusive with --server). An environment pins its own host, so a harness environment runs its harness on every turn, continuations included."
13912
+ ).option(
13913
+ "--server <serverId...>",
13914
+ "Run against these project servers (mutually exclusive with --environment)"
13915
+ ).option("--system-prompt <text>", "System prompt for the session").option(
13916
+ "--tool-mode <mode>",
13917
+ "read_only (default) advertises only tools annotated readOnlyHint:true. auto advertises everything and MAY CAUSE REAL SIDE EFFECTS."
13918
+ ).option("--max-steps <n>", "Maximum engine steps this turn (1-16)").option(
13919
+ "--max-tool-calls <n>",
13920
+ "Cap the tool calls this turn may make. 0 answers without tools."
13921
+ ).option("--temperature <n>", "Sampling temperature (0-2)")
13922
+ )
13923
+ ),
13924
+ {
13925
+ ...sendChatMessageOperation,
13926
+ execute: (input, context) => waitForSessionTurn(
13927
+ () => sendChatMessageOperation.execute(input, context),
13928
+ context.signal
13929
+ )
13930
+ },
13931
+ (options) => ({
13932
+ idempotencyKey: options.idempotencyKey ?? "",
13933
+ message: options.message ?? "",
13934
+ browser: browserInput(options),
13935
+ project: options.project,
13936
+ sessionId: options.session,
13937
+ modelId: options.model,
13938
+ hostId: options.client,
13939
+ environmentId: options.environment,
13940
+ serverIds: options.server,
13941
+ systemPrompt: options.systemPrompt,
13942
+ toolMode: options.toolMode,
13943
+ maxSteps: parseIntegerOption(options.maxSteps, "--max-steps", {
13944
+ min: 1,
13945
+ max: 16
13946
+ }),
13947
+ maxToolCalls: parseIntegerOption(
13948
+ options.maxToolCalls,
13949
+ "--max-tool-calls",
13950
+ { min: 0, max: 16 }
13951
+ ),
13952
+ temperature: parseFloatOption(options.temperature)
13953
+ }),
13954
+ // A Playground turn runs a model, and often tools with it. The 30s program
13955
+ // default expired mid-turn while the turn kept running and spending, which
13956
+ // reads to the caller as "it failed" when it had not.
13957
+ { defaultTimeoutMs: 36e4 }
13958
+ );
13959
+ bindOperation(
13960
+ addProjectOption(
13961
+ sessions.command("show").description(
13962
+ "Print a session's metadata and a window of its raw messages. Message indices are ABSOLUTE transcript positions \u2014 the same ones `sessions trace` spans reference."
13963
+ ).requiredOption("--session <sessionId>", "The session to read").option(
13964
+ "--after-message <index>",
13965
+ "Start the window at this absolute transcript index"
13966
+ ).option("--limit <n>", "Messages to return (1-200)")
13967
+ ),
13968
+ getChatSessionOperation,
13969
+ (options) => ({
13970
+ sessionId: options.session ?? "",
13971
+ project: options.project,
13972
+ afterMessageIndex: parseIntegerOption(
13973
+ options.afterMessage,
13974
+ "--after-message",
13975
+ { min: 0 }
13976
+ ),
13977
+ limit: parseIntegerOption(options.limit, "--limit", { min: 1, max: 200 })
13978
+ })
13979
+ );
13980
+ bindOperation(
13981
+ addProjectOption(
13982
+ sessions.command("trace").description(
13983
+ "Print a session's per-turn execution spans: per-tool-call latency, token usage, and indices into the transcript. Returns the LATEST turn by default \u2014 page older turns with --after-turn, or use --no-spans for cheap summaries."
13984
+ ).requiredOption("--session <sessionId>", "The session to trace").option("--turn <turnId>", "Return exactly this turn").option(
13985
+ "--after-turn <promptIndex>",
13986
+ "Page forward from this turn index (mutually exclusive with --turn)"
13987
+ ).option("--limit <n>", "Turns to return (1-20). Defaults to 1.").option("--no-spans", "Return per-turn summaries without span payloads")
13988
+ ),
13989
+ getChatSessionTraceOperation,
13990
+ (options) => ({
13991
+ sessionId: options.session ?? "",
13992
+ project: options.project,
13993
+ turnId: options.turn,
13994
+ afterPromptIndex: parseIntegerOption(options.afterTurn, "--after-turn", {
13995
+ min: 0
13996
+ }),
13997
+ limit: parseIntegerOption(options.limit, "--limit", { min: 1, max: 20 }),
13998
+ // Commander's `--no-spans` sets `spans: false` and leaves it `true` when
13999
+ // absent, so only an explicit opt-out is forwarded — the route's own
14000
+ // default stays the source of truth for everyone else.
14001
+ includeSpans: options.spans === false ? false : void 0
14002
+ })
14003
+ );
14004
+ }
14005
+ function parseFloatOption(value) {
14006
+ if (value === void 0) return void 0;
14007
+ if (value.trim() === "") {
14008
+ throw usageError("--temperature needs a number.");
14009
+ }
14010
+ const parsed = Number(value);
14011
+ if (!Number.isFinite(parsed)) {
14012
+ throw usageError("--temperature must be a number.");
14013
+ }
14014
+ return parsed;
14015
+ }
14016
+ var SESSIONS_BOUNDS = { min: 1, max: 100 };
14017
+ var TURNS_BOUNDS = { min: 1, max: 200 };
14018
+ var JOURNEY_COUNT_BOUNDS = { min: 1, max: 5 };
14019
+ var PERSONA_COUNT_BOUNDS = { min: 1, max: 12 };
14020
+ function baseGroundingArgs(options) {
14021
+ requireExactlyOne({
14022
+ "--environment": options.environment,
14023
+ "--server-attachment": options.serverAttachment
14024
+ });
14025
+ return {
14026
+ ...options.environment ? { environmentId: options.environment } : {},
14027
+ ...options.serverAttachment ? { serverAttachmentId: options.serverAttachment } : {},
14028
+ ...options.description ? { description: options.description } : {}
14029
+ };
14030
+ }
14031
+ function groundingArgs(options) {
14032
+ const journeyCount = parseIntegerOption(
14033
+ options.journeyCount,
14034
+ "--journey-count",
14035
+ JOURNEY_COUNT_BOUNDS
14036
+ );
14037
+ return {
14038
+ ...baseGroundingArgs(options),
14039
+ ...journeyCount !== void 0 ? { journeyCount } : {}
14040
+ };
14041
+ }
14042
+ function goalGroundingArgs(options) {
14043
+ if (options.goalCount !== void 0 && options.journeyCount !== void 0) {
14044
+ throw usageError(
14045
+ "Use either --goal-count or its deprecated --journey-count alias, not both."
14046
+ );
14047
+ }
14048
+ const goalCount = parseIntegerOption(
14049
+ options.goalCount ?? options.journeyCount,
14050
+ "--goal-count",
14051
+ JOURNEY_COUNT_BOUNDS
14052
+ );
14053
+ return {
14054
+ ...baseGroundingArgs(options),
14055
+ ...goalCount !== void 0 ? { goalCount } : {}
14056
+ };
14057
+ }
14058
+ function addConfigOptions(command, required) {
14059
+ const iterations = "--iterations <n>";
14060
+ const legacyIterations = "--sessions-per-target <n>";
14061
+ const turns = "--max-turns <n>";
14062
+ const iterationsHelp = "Sessions run against EACH target. Total sessions = targets x this, and the total is what spends.";
14063
+ const legacyHelp = "Deprecated alias for --iterations.";
14064
+ const turnsHelp = "Cap on assistant turns per session.";
14065
+ const withIterations = command.option(iterations, iterationsHelp).option(legacyIterations, legacyHelp);
14066
+ return required ? withIterations.requiredOption(turns, turnsHelp) : withIterations.option(turns, turnsHelp);
14067
+ }
14068
+ function iterationsOf(options) {
14069
+ if (options.iterations !== void 0 && options.sessionsPerTarget !== void 0) {
14070
+ throw usageError(
14071
+ "Use either --iterations or its deprecated --sessions-per-target alias, not both."
14072
+ );
14073
+ }
14074
+ const raw = options.iterations ?? options.sessionsPerTarget;
14075
+ return raw === void 0 ? void 0 : parseIntegerOption(raw, "--iterations", SESSIONS_BOUNDS);
14076
+ }
14077
+ function swarmRunIdOf(options) {
14078
+ const selected = foldSwarmRunId(options);
14079
+ if (selected === void 0) {
14080
+ throw usageError("Missing required option: --swarm-run");
14081
+ }
14082
+ return selected;
14083
+ }
14084
+ function requiredIterationsOf(options) {
14085
+ const value = iterationsOf(options);
14086
+ if (value === void 0) {
14087
+ throw usageError("Missing required option: --iterations");
14088
+ }
14089
+ return value;
14090
+ }
14091
+ function addGroundingOptions(command) {
14092
+ return command.option(
14093
+ "--environment <id>",
14094
+ "Ground the drafts in this project environment. Use this one normally."
14095
+ ).option(
14096
+ "--server-attachment <id>",
14097
+ "Legacy grounding source. Prefer --environment."
14098
+ ).option("--description <text>", "Who the audience is, in your own words.").option("--journey-count <n>", "How many goals to draft per persona.");
14099
+ }
14100
+ function addGoalCountOption(command) {
14101
+ return command.option("--goal-count <n>", "How many goals to draft.");
14102
+ }
14103
+ function registerSwarmAuthoringCommands(program, goals) {
14104
+ const personas = program.command("personas").description(
14105
+ "The reusable synthetic characters Swarms goals run as. A persona carries a name, a role and behavioural notes; the task lives on each goal."
14106
+ );
14107
+ bindOperation(
14108
+ addProjectOption(
14109
+ personas.command("list").description("List the project's personas.")
14110
+ ),
14111
+ listPersonasOperation,
14112
+ (options) => ({ project: options.project })
14113
+ );
14114
+ bindOperation(
14115
+ addProjectOption(
14116
+ personas.command("get").description("Show one persona in full, including its notes.").requiredOption("--persona <id>", "Persona ID")
14117
+ ),
14118
+ getPersonaOperation,
14119
+ (options) => ({
14120
+ project: options.project,
14121
+ persona: options.persona
14122
+ })
14123
+ );
14124
+ bindOperation(
14125
+ addProjectOption(
14126
+ personas.command("create").description(
14127
+ "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."
14128
+ ).requiredOption("--name <name>", "Display name").requiredOption(
14129
+ "--role <role>",
14130
+ "Who they are, in a few words \u2014 'enterprise procurement lead'"
14131
+ ).option(
14132
+ "--notes <text>",
14133
+ "How they behave: what they know, what they will not tolerate, how they phrase things"
14134
+ ).option("--idempotency-key <key>", "Retry key")
14135
+ ),
14136
+ createPersonaOperation,
14137
+ (options) => ({
14138
+ project: options.project,
14139
+ name: options.name,
14140
+ role: options.role,
14141
+ ...options.notes !== void 0 ? { notes: options.notes } : {},
14142
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
14143
+ })
14144
+ );
14145
+ bindOperation(
14146
+ addProjectOption(
14147
+ personas.command("update").description(
14148
+ "Edit a persona. Finished runs keep the persona they ran as \u2014 editing does not rewrite history."
14149
+ ).requiredOption("--persona <id>", "Persona ID").option("--name <name>").option("--role <role>").option("--notes <text>")
14150
+ ),
14151
+ updatePersonaOperation,
14152
+ (options) => ({
14153
+ project: options.project,
14154
+ persona: options.persona,
14155
+ ...options.name !== void 0 ? { name: options.name } : {},
14156
+ ...options.role !== void 0 ? { role: options.role } : {},
14157
+ ...options.notes !== void 0 ? { notes: options.notes } : {}
14158
+ })
14159
+ );
14160
+ bindOperation(
14161
+ addProjectOption(
14162
+ personas.command("delete").description(
14163
+ "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 goals and a second delete answers not-found."
14164
+ ).requiredOption("--persona <id>", "Persona ID")
14165
+ ),
14166
+ deletePersonaOperation,
14167
+ (options) => ({
14168
+ project: options.project,
14169
+ persona: options.persona
14170
+ })
14171
+ );
14172
+ bindOperation(
14173
+ addGroundingOptions(
14174
+ addProjectOption(
14175
+ personas.command("generate").description(
14176
+ "Draft candidate personas with a model, grounded in what the project's servers do. SAVES NOTHING \u2014 pipe what you want into `personas create`. Included with MCPJam; no customer credits consumed; counts against the organization's daily generation quota."
14177
+ ).option("--persona-count <n>", "Draft a slate of N personas.")
14178
+ )
14179
+ ),
14180
+ generatePersonasOperation,
14181
+ (options) => {
14182
+ const personaCount = parseIntegerOption(
14183
+ options.personaCount,
14184
+ "--persona-count",
14185
+ PERSONA_COUNT_BOUNDS
14186
+ );
14187
+ return {
14188
+ project: options.project,
14189
+ ...groundingArgs(options),
14190
+ ...personaCount !== void 0 ? { personaCount } : {}
14191
+ };
14192
+ }
14193
+ );
14194
+ bindOperation(
14195
+ addProjectOption(
14196
+ goals.command("get").description(
14197
+ "Show one goal in full. Read this before launching if you want to know what a run will cost: it produces targets x iterations conversations."
14198
+ ).option("--goal-id <id>", "Goal ID").option("--journey <id>", "Deprecated alias for --goal-id")
14199
+ ),
14200
+ getGoalOperation,
14201
+ (options) => ({
14202
+ project: options.project,
14203
+ goalId: goalIdOf(options)
14204
+ })
14205
+ );
14206
+ bindOperation(
14207
+ addConfigOptions(
14208
+ addProjectOption(
14209
+ goals.command("create").description(
14210
+ "Author a goal: a persona, a task, and the environments to pursue it against. Creating does NOT run it \u2014 `goals run` does, and that is the call that spends."
14211
+ ).requiredOption(
14212
+ "--goal <text>",
14213
+ "What the persona is trying to accomplish"
14214
+ ).requiredOption("--persona <id>", "Persona ID to run as").option("--name <name>").option("--swarm <id>", "Swarm container ID (authoring provenance)").option(
14215
+ "--environment <id>",
14216
+ "Environment to fan out across. Repeatable.",
14217
+ (value, previous = []) => [...previous, value]
14218
+ ).option("--idempotency-key <key>", "Retry key")
14219
+ ),
14220
+ true
14221
+ ),
14222
+ createGoalOperation,
14223
+ (options) => ({
14224
+ project: options.project,
14225
+ goal: options.goal,
14226
+ persona: options.persona,
14227
+ iterations: requiredIterationsOf(options),
14228
+ maxTurns: parseRequiredIntegerOption(
14229
+ options.maxTurns,
14230
+ "--max-turns",
14231
+ TURNS_BOUNDS
14232
+ ),
14233
+ ...options.name !== void 0 ? { name: options.name } : {},
14234
+ ...options.swarm !== void 0 ? { swarm: options.swarm } : {},
14235
+ ...options.environment?.length ? { environmentIds: options.environment } : {},
14236
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
14237
+ })
14238
+ );
14239
+ bindOperation(
14240
+ addConfigOptions(
14241
+ addProjectOption(
14242
+ goals.command("update").description(
14243
+ "Edit a goal. --iterations and --max-turns must be given together (they are one config upstream). A run already in flight keeps the config it launched with."
14244
+ ).option("--goal-id <id>", "Goal ID").option("--journey <id>", "Deprecated alias for --goal-id").option("--name <name>").option("--goal <text>").option(
14245
+ "--environment <id>",
14246
+ "Replace the fan-out with these. Repeatable.",
14247
+ (value, previous = []) => [...previous, value]
14248
+ ).option(
14249
+ "--clear-environments",
14250
+ "Drop the fan-out and return the goal to its host targets."
14251
+ )
14252
+ ),
14253
+ false
14254
+ ),
14255
+ updateGoalOperation,
14256
+ (options) => {
14257
+ if (options.clearEnvironments && options.environment?.length) {
14258
+ throw new Error(
14259
+ "--clear-environments and --environment cannot be used together"
14260
+ );
14261
+ }
14262
+ requireTogether(
14263
+ {
14264
+ flag: "--iterations",
14265
+ value: options.iterations ?? options.sessionsPerTarget
14266
+ },
14267
+ { flag: "--max-turns", value: options.maxTurns }
14268
+ );
14269
+ return {
14270
+ project: options.project,
14271
+ goalId: goalIdOf(options),
14272
+ ...options.name !== void 0 ? { name: options.name } : {},
14273
+ ...options.goal !== void 0 ? { goal: options.goal } : {},
14274
+ ...options.clearEnvironments ? { environmentIds: null } : options.environment?.length ? { environmentIds: options.environment } : {},
14275
+ ...iterationsOf(options) !== void 0 ? { iterations: iterationsOf(options) } : {},
14276
+ ...options.maxTurns !== void 0 ? {
14277
+ maxTurns: parseIntegerOption(
14278
+ options.maxTurns,
14279
+ "--max-turns",
14280
+ TURNS_BOUNDS
14281
+ )
14282
+ } : {}
14283
+ };
14284
+ }
14285
+ );
14286
+ bindOperation(
14287
+ addProjectOption(
14288
+ goals.command("archive").description(
14289
+ "Take a goal off the roster. Its runs, sessions and scorecards stay readable \u2014 the evidence for past decisions is not deleted with the goal that produced it."
14290
+ ).option("--goal-id <id>", "Goal ID").option("--journey <id>", "Deprecated alias for --goal-id")
14291
+ ),
14292
+ archiveGoalOperation,
14293
+ (options) => ({
14294
+ project: options.project,
14295
+ goalId: goalIdOf(options)
14296
+ })
14297
+ );
14298
+ bindOperation(
14299
+ addGoalCountOption(
14300
+ addGroundingOptions(
14301
+ addProjectOption(
14302
+ goals.command("generate").description(
14303
+ "Draft candidate goals 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; included with MCPJam (no customer credits consumed) and counts against the organization's daily generation quota."
14304
+ ).requiredOption("--persona-name <name>").requiredOption("--persona-role <role>").option("--persona-notes <text>")
14305
+ )
14306
+ )
14307
+ ),
14308
+ generateGoalsOperation,
14309
+ (options) => ({
14310
+ project: options.project,
14311
+ persona: {
14312
+ name: options.personaName,
14313
+ role: options.personaRole,
14314
+ ...options.personaNotes !== void 0 ? { notes: options.personaNotes } : {}
14315
+ },
14316
+ ...goalGroundingArgs(options)
14317
+ })
14318
+ );
14319
+ bindOperation(
14320
+ addProjectOption(
14321
+ goals.command("overview").description(
14322
+ "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."
14323
+ )
14324
+ ),
14325
+ getSwarmOverviewOperation,
14326
+ (options) => ({ project: options.project })
14327
+ );
14328
+ bindOperation(
14329
+ addProjectOption(
14330
+ goals.command("scorecard").description(
14331
+ "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."
14332
+ ).requiredOption("--run <id>", "Goal run ID")
14333
+ ),
14334
+ getGoalRunScorecardOperation,
14335
+ (options) => ({
14336
+ project: options.project,
14337
+ run: options.run
14338
+ })
14339
+ );
14340
+ bindOperation(
14341
+ addProjectOption(
14342
+ goals.command("findings").description(
14343
+ "Criteria that keep failing across swarm runs, with how long each has been failing."
14344
+ )
14345
+ ),
14346
+ listSwarmFindingsOperation,
14347
+ (options) => ({ project: options.project })
14348
+ );
14349
+ bindOperation(
14350
+ addProjectOption(
14351
+ goals.command("dismiss-finding").description(
14352
+ "Mark a finding as not worth acting on. Its lifecycle keeps updating underneath, so undismissing later shows honest current state."
14353
+ ).requiredOption("--finding <id>", "Finding ID")
14354
+ ),
14355
+ dismissSwarmFindingOperation,
14356
+ (options) => ({
14357
+ project: options.project,
14358
+ finding: options.finding
14359
+ })
14360
+ );
14361
+ bindOperation(
14362
+ addProjectOption(
14363
+ goals.command("undismiss-finding").description("Bring a dismissed finding back into the active list.").requiredOption("--finding <id>", "Finding ID")
14364
+ ),
14365
+ undismissSwarmFindingOperation,
14366
+ (options) => ({
14367
+ project: options.project,
14368
+ finding: options.finding
14369
+ })
14370
+ );
14371
+ bindOperation(
14372
+ addProjectOption(
14373
+ goals.command("insights").description(
14374
+ "The model's analysis of a whole swarm run, if one has been requested. Not-found means nobody asked for it, which is different from asked-and-still-working."
14375
+ ).option("--swarm-run <id>", "Swarm run ID (the swarmRunId on a run)").option("--wave <id>", "Deprecated alias for --swarm-run")
14376
+ ),
14377
+ getSwarmRunInsightsOperation,
14378
+ (options) => ({
14379
+ project: options.project,
14380
+ swarmRun: swarmRunIdOf(options)
14381
+ })
14382
+ );
14383
+ bindOperation(
14384
+ addProjectOption(
14385
+ goals.command("request-insights").description(
14386
+ "Ask a model to analyze a whole swarm run. Returns immediately as pending; poll `goals insights`. Included with MCPJam \u2014 no credits are consumed; it counts against a daily insight quota shared with user-testing insights. Read the scorecards first \u2014 they cost no quota and usually explain the failure."
14387
+ ).option("--swarm-run <id>", "Swarm run ID").option("--wave <id>", "Deprecated alias for --swarm-run").option(
14388
+ "--force",
14389
+ "Regenerate over a swarm run that already has insights. Takes another slice of the daily insight quota."
14390
+ )
14391
+ ),
14392
+ requestSwarmRunInsightsOperation,
14393
+ (options) => ({
14394
+ project: options.project,
14395
+ swarmRun: swarmRunIdOf(options),
14396
+ ...options.force ? { force: true } : {}
14397
+ })
14398
+ );
14399
+ bindOperation(
14400
+ addProjectOption(
14401
+ goals.command("cancel-insights").description(
14402
+ "Stop an in-flight insights generation. The recovery path for a swarm run stuck pending \u2014 without it the only way forward is --force, which takes another slice of the daily insight quota."
14403
+ ).option("--swarm-run <id>", "Swarm run ID").option("--wave <id>", "Deprecated alias for --swarm-run")
14404
+ ),
14405
+ cancelSwarmRunInsightsOperation,
14406
+ (options) => ({
14407
+ project: options.project,
14408
+ swarmRun: swarmRunIdOf(options)
14409
+ })
14410
+ );
14411
+ const swarms = program.command("swarms").description(
14412
+ "Swarm containers group goals authored together and hold their shared execution config. A goal does not need one, but a project authored through the app will have them."
14413
+ );
14414
+ bindOperation(
14415
+ addProjectOption(
14416
+ swarms.command("list").description("List the project's swarm containers.")
14417
+ ),
14418
+ listSwarmsOperation,
14419
+ (options) => ({ project: options.project })
14420
+ );
14421
+ bindOperation(
14422
+ addProjectOption(
14423
+ swarms.command("get").description("Show one swarm container.").requiredOption("--swarm <id>", "Swarm container ID")
14424
+ ),
14425
+ getSwarmOperation,
14426
+ (options) => ({
14427
+ project: options.project,
14428
+ swarm: options.swarm
14429
+ })
14430
+ );
14431
+ bindOperation(
14432
+ addConfigOptions(
14433
+ addProjectOption(
14434
+ swarms.command("create").description(
14435
+ "Create a container to author goals under. Runs nothing."
14436
+ ).requiredOption("--name <name>").option("--description <text>").option(
14437
+ "--environment <id>",
14438
+ "Default fan-out for goals authored here. Repeatable.",
14439
+ (value, previous = []) => [...previous, value]
14440
+ ).option("--idempotency-key <key>", "Retry key")
14441
+ ),
14442
+ true
14443
+ ),
14444
+ createSwarmOperation,
14445
+ (options) => ({
14446
+ project: options.project,
14447
+ name: options.name,
14448
+ iterations: requiredIterationsOf(options),
14449
+ maxTurns: parseRequiredIntegerOption(
14450
+ options.maxTurns,
14451
+ "--max-turns",
14452
+ TURNS_BOUNDS
14453
+ ),
14454
+ ...options.description !== void 0 ? { description: options.description } : {},
14455
+ ...options.environment?.length ? { environmentIds: options.environment } : {},
14456
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
14457
+ })
14458
+ );
14459
+ bindOperation(
14460
+ addConfigOptions(
14461
+ addProjectOption(
14462
+ swarms.command("update").description(
14463
+ "Edit a swarm container. --iterations and --max-turns must be given together."
14464
+ ).requiredOption("--swarm <id>", "Swarm container ID").option("--name <name>").option("--description <text>").option(
14465
+ "--environment <id>",
14466
+ "Replace the default fan-out. Repeatable.",
14467
+ (value, previous = []) => [...previous, value]
14468
+ )
14469
+ ),
14470
+ false
14471
+ ),
14472
+ updateSwarmOperation,
14473
+ (options) => ({
14474
+ project: options.project,
14475
+ swarm: options.swarm,
14476
+ ...options.name !== void 0 ? { name: options.name } : {},
14477
+ ...options.description !== void 0 ? { description: options.description } : {},
14478
+ ...options.environment?.length ? { environmentIds: options.environment } : {},
14479
+ // Through the shared fold, like `goals update`: `addConfigOptions`
14480
+ // registers BOTH flags on this command, so reading only the deprecated
14481
+ // one would accept `--iterations` and silently change nothing.
14482
+ ...iterationsOf(options) !== void 0 ? { iterations: iterationsOf(options) } : {},
14483
+ ...options.maxTurns !== void 0 ? { maxTurns: parseIntegerOption(options.maxTurns, "--max-turns") } : {}
14484
+ })
14485
+ );
14486
+ bindOperation(
14487
+ addProjectOption(
14488
+ swarms.command("archive").description(
14489
+ "Take a container off the roster. Goals authored under it keep working \u2014 the reference is authoring provenance, not ownership."
14490
+ ).requiredOption("--swarm <id>", "Swarm container ID")
14491
+ ),
14492
+ archiveSwarmOperation,
14493
+ (options) => ({
14494
+ project: options.project,
14495
+ swarm: options.swarm
14496
+ })
14497
+ );
14498
+ }
14499
+ function collect(value, previous = []) {
14500
+ return [...previous, value];
14501
+ }
14502
+ var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
14503
+ function splitOnFirst(raw, separator, flag) {
14504
+ const index = raw.indexOf(separator);
14505
+ if (index < 0) {
14506
+ throw usageError(
14507
+ `${flag} expects "Name${separator}value"; the argument had no "${separator}".`
14508
+ );
14509
+ }
14510
+ const name = raw.slice(0, index).trim();
14511
+ if (!name) {
14512
+ throw usageError(`${flag} has an empty name before the "${separator}".`);
14513
+ }
14514
+ return [name, raw.slice(index + separator.length)];
14515
+ }
14516
+ function resolveHeaders(options) {
14517
+ const headers = /* @__PURE__ */ Object.create(null);
14518
+ const seen = /* @__PURE__ */ new Map();
14519
+ const named = (options.header?.length ?? 0) + (options.headerEnv?.length ?? 0) + (options.headerFile?.length ?? 0);
14520
+ if (options.clearHeaders) {
14521
+ if (named > 0) {
14522
+ throw usageError(
14523
+ "--clear-headers removes every header, so it cannot be combined with a header flag. Pass one or the other."
14524
+ );
14525
+ }
14526
+ return {};
14527
+ }
14528
+ const put = (name, value, flag) => {
14529
+ if (!HEADER_NAME_PATTERN.test(name)) {
14530
+ throw usageError(
14531
+ `That ${flag} name is not an HTTP token. Use letters, digits and !#$%&'*+.^_\`|~- only.`
14532
+ );
14533
+ }
14534
+ const key = name.toLowerCase();
14535
+ const previous = seen.get(key);
14536
+ if (previous !== void 0) {
14537
+ throw usageError(
14538
+ `Header "${name}" was given twice (already set by ${previous}). HTTP header names are case-insensitive.`
14539
+ );
14540
+ }
14541
+ if (/[\r\n\0]/.test(value)) {
14542
+ throw usageError(
14543
+ `Header "${name}" contains a newline or a null byte. A header value cannot span lines.`
14544
+ );
14545
+ }
14546
+ if (value === "") {
14547
+ throw usageError(`The value for header "${name}" is empty.`);
14548
+ }
14549
+ seen.set(key, flag);
14550
+ headers[name] = value;
14551
+ };
14552
+ for (const raw of options.header ?? []) {
14553
+ const [name, value] = splitOnFirst(raw, ":", "--header");
14554
+ put(name, value.trim(), "--header");
14555
+ }
14556
+ for (const raw of options.headerEnv ?? []) {
14557
+ const [name, variable] = splitOnFirst(raw, "=", "--header-env");
14558
+ const value = process.env[variable.trim()];
14559
+ if (value === void 0 || value === "") {
14560
+ throw usageError(
14561
+ `Environment variable "${variable.trim()}" is not set (or is empty).`
14562
+ );
14563
+ }
14564
+ put(name, value, "--header-env");
14565
+ }
14566
+ for (const raw of options.headerFile ?? []) {
14567
+ const [name, path9] = splitOnFirst(raw, "=", "--header-file");
14568
+ const target = path9.trim();
14569
+ let contents;
14570
+ try {
14571
+ contents = target === "-" ? readFileSync(0, "utf8") : readFileSync(target, "utf8");
14572
+ } catch (error) {
14573
+ throw usageError(
14574
+ target === "-" ? `Failed to read the value for header "${name}" from stdin.` : `Failed to read the value for header "${name}" from "${target}".`,
14575
+ { source: error instanceof Error ? error.message : String(error) }
14576
+ );
14577
+ }
14578
+ put(name, contents.replace(/\r?\n$/, ""), "--header-file");
14579
+ }
14580
+ return Object.keys(headers).length > 0 ? { ...headers } : void 0;
14581
+ }
14582
+ function resolveAttributes(pairs) {
14583
+ if (!pairs || pairs.length === 0) return void 0;
14584
+ const out = /* @__PURE__ */ Object.create(null);
14585
+ for (const raw of pairs) {
14586
+ const [key, value] = splitOnFirst(raw, "=", "--attr");
14587
+ if (Object.prototype.hasOwnProperty.call(out, key)) {
14588
+ throw usageError(`Resource attribute "${key}" was given twice.`);
14589
+ }
14590
+ out[key] = value;
14591
+ }
14592
+ return { ...out };
14593
+ }
14594
+ var SOURCE_TYPES = ["eval", "scenario", "swarm", "direct"];
14595
+ function resolveSourceTypes(values) {
14596
+ if (!values || values.length === 0) return void 0;
14597
+ const out = [];
14598
+ for (const raw of values) {
14599
+ const value = raw.trim();
14600
+ if (!SOURCE_TYPES.includes(value)) {
14601
+ throw usageError(
14602
+ `--source expects one of ${SOURCE_TYPES.join(
14603
+ ", "
14604
+ )} (got ${JSON.stringify(raw)}).`
14605
+ );
14606
+ }
14607
+ if (!out.includes(value)) out.push(value);
14608
+ }
14609
+ return out;
14610
+ }
14611
+ var ORG_FLAG_DESCRIPTION = "Organization ID, from `cloud organizations list`";
14612
+ function registerTraceDestinationsCommands(program) {
14613
+ const destinations = program.command("trace-destinations").alias("traces").description(
14614
+ "Stream an organization's traces to an OTLP/HTTP endpoint (Coralogix, Honeycomb, Grafana, a collector). Header values are write-only: no command prints one."
14615
+ );
14616
+ destinations.command("list").description(
14617
+ "List the organization's destinations \u2014 endpoint, sources, redaction setting and delivery health. Header names only, never their values."
14618
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).action(async (options, command) => {
14619
+ const globalOptions = getGlobalOptions(command);
14620
+ const result = await runPlatformOperation(
14621
+ platformOptionsOf(command),
14622
+ globalOptions.timeout,
14623
+ ({ client, signal }) => listTraceDestinationsOperation.execute(
14624
+ { organization: options.org },
14625
+ { client, signal }
14626
+ ),
14627
+ { cloudScope: { kind: "organization", organization: options.org } }
14628
+ );
14629
+ writeResult(result, globalOptions.format);
14630
+ });
14631
+ destinations.command("show").description(
14632
+ "Show one destination in full, including delivery health: the last HTTP status the vendor answered with, sessions and spans delivered, and how many are still queued."
14633
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption(
14634
+ "--destination <id>",
14635
+ "Destination ID, from `cloud trace-destinations list`"
14636
+ ).action(async (options, command) => {
14637
+ const globalOptions = getGlobalOptions(command);
14638
+ const result = await runPlatformOperation(
14639
+ platformOptionsOf(command),
14640
+ globalOptions.timeout,
14641
+ ({ client, signal }) => getTraceDestinationOperation.execute(
14642
+ { organization: options.org, destination: options.destination },
14643
+ { client, signal }
14644
+ ),
14645
+ { cloudScope: { kind: "organization", organization: options.org } }
14646
+ );
14647
+ writeResult(result, globalOptions.format);
14648
+ });
14649
+ destinations.command("create").description(
14650
+ "Create a destination and start streaming. Header values come from --header-env or --header-file; --header takes one inline for scripting."
14651
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--name <name>", "Human label for this destination.").requiredOption(
14652
+ "--endpoint <url>",
14653
+ "The vendor's OTLP/HTTP intake, HTTPS only. `/v1/traces` is appended if the path does not already end there."
14654
+ ).option(
14655
+ "--header-env <Name=VAR>",
14656
+ "Repeatable: read a header's value from an environment variable. Preferred.",
14657
+ collect
14658
+ ).option(
14659
+ "--header-file <Name=path>",
14660
+ "Repeatable: read a header's value from a file (`-` reads stdin). One trailing newline is dropped \u2014 a header cannot span lines.",
14661
+ collect
14662
+ ).option(
14663
+ "--header <Name: value>",
14664
+ "Repeatable, SCRIPTING ONLY: an inline header value is written to your shell history and is visible in `ps` while the command runs.",
14665
+ collect
14666
+ ).option(
14667
+ "--attr <key=value>",
14668
+ "Repeatable: an extra OTel resource attribute (cx.application.name=mcpjam). `mcpjam.*` names are reserved by the exporter.",
14669
+ collect
14670
+ ).option(
14671
+ "--source <type>",
14672
+ "Repeatable: eval, scenario, swarm or direct. `direct` is Playground, and only sessions SHARED to the workspace are ever sent. Defaults to the server's default set.",
14673
+ collect
14674
+ ).option(
14675
+ "--include-content",
14676
+ "Send prompts, outputs, tool arguments and screenshots. OFF by default, and off is the safe reading \u2014 this decides whether customer content leaves the platform."
14677
+ ).option(
14678
+ "--project <id>",
14679
+ "Repeatable: restrict to these projects. Omit for every project in the organization, present and future.",
14680
+ collect
14681
+ ).option(
14682
+ "--compression <mode>",
14683
+ "gzip or none. gzip is optional in OTLP/HTTP and some intakes reject it."
14684
+ ).option(
14685
+ "--preset <id>",
14686
+ "Vendor preset id this was created from (coralogix, honeycomb, \u2026). Labelling only."
14687
+ ).option("--disabled", "Create it without starting the stream.").action(
14688
+ async (options, command) => {
14689
+ const globalOptions = getGlobalOptions(command);
14690
+ const headers = resolveHeaders(options);
14691
+ const resourceAttributes = resolveAttributes(options.attr);
14692
+ const sourceTypes = resolveSourceTypes(options.source);
14693
+ if (options.compression !== void 0 && options.compression !== "gzip" && options.compression !== "none") {
14694
+ throw usageError("--compression expects gzip or none.");
14695
+ }
14696
+ const result = await runPlatformOperation(
14697
+ platformOptionsOf(command),
14698
+ globalOptions.timeout,
14699
+ ({ client, signal }) => createTraceDestinationOperation.execute(
14700
+ {
14701
+ organization: options.org,
14702
+ name: options.name,
14703
+ endpointUrl: options.endpoint,
14704
+ ...headers ? { headers } : {},
14705
+ ...resourceAttributes ? { resourceAttributes } : {},
14706
+ ...sourceTypes ? { sourceTypes } : {},
14707
+ ...options.includeContent ? { includeContent: true } : {},
14708
+ ...options.project ? { projectIds: options.project } : {},
14709
+ ...options.compression ? { compression: options.compression } : {},
14710
+ ...options.preset ? { preset: options.preset } : {},
14711
+ ...options.disabled ? { enabled: false } : {}
14712
+ },
14713
+ { client, signal }
14714
+ ),
14715
+ { cloudScope: { kind: "organization", organization: options.org } }
14716
+ );
14717
+ writeResult(result, globalOptions.format);
14718
+ }
14719
+ );
14720
+ destinations.command("update").description(
14721
+ "Edit a destination. Any header flag REPLACES the whole header set; passing none leaves the stored headers alone."
14722
+ ).requiredOption("--org <id>", ORG_FLAG_DESCRIPTION).requiredOption("--destination <id>", "Destination ID").option("--name <name>", "New label.").option("--endpoint <url>", "New OTLP/HTTP intake, HTTPS only.").option(
14723
+ "--header-env <Name=VAR>",
14724
+ "Repeatable: read a header's value from an environment variable. Preferred.",
14725
+ collect
14726
+ ).option(
14727
+ "--header-file <Name=path>",
14728
+ "Repeatable: read a header's value from a file (`-` reads stdin).",
14729
+ collect
14730
+ ).option(
14731
+ "--header <Name: value>",
14732
+ "Repeatable, SCRIPTING ONLY: written to your shell history and visible in `ps`.",
14733
+ collect
14734
+ ).option(
14735
+ "--clear-headers",
14736
+ "Remove every stored header. Reach for this before pointing a destination at a new endpoint that must not receive the old vendor's credentials \u2014 omitting the header flags LEAVES them, which is not the same thing."
14737
+ ).option(
14738
+ "--attr <key=value>",
14739
+ "Repeatable: REPLACES the resource attributes.",
14740
+ collect
14741
+ ).option("--source <type>", "Repeatable: REPLACES the source list.", collect).option("--include-content", "Start sending content. Audited.").option("--no-include-content", "Stop sending content; redact again.").option(
14742
+ "--project <id>",
14743
+ "Repeatable: REPLACES the project allowlist.",
14744
+ collect
14745
+ ).option(
14746
+ "--all-projects",
14747
+ "Stream every project in the organization. The explicit way back \u2014 an empty --project list would mean a destination that matches nothing."
14748
+ ).option("--compression <mode>", "gzip or none.").option("--enable", "Start streaming.").option("--disable", "Stop streaming, keeping the configuration.").action(
14749
+ async (options, command) => {
14750
+ const globalOptions = getGlobalOptions(command);
14751
+ if (options.enable && options.disable) {
14752
+ throw usageError("Pass --enable or --disable, not both.");
14753
+ }
14754
+ if (options.allProjects && options.project) {
14755
+ throw usageError(
14756
+ "Pass --all-projects or --project, not both \u2014 they are two answers to the same question."
14757
+ );
14758
+ }
14759
+ if (options.compression !== void 0 && options.compression !== "gzip" && options.compression !== "none") {
14760
+ throw usageError("--compression expects gzip or none.");
14761
+ }
14762
+ const headers = resolveHeaders(options);
14763
+ const resourceAttributes = resolveAttributes(options.attr);
14764
+ const sourceTypes = resolveSourceTypes(options.source);
14765
+ const enabled = options.enable ? true : options.disable ? false : void 0;
14766
+ const patch = {
14767
+ ...options.name !== void 0 ? { name: options.name } : {},
14768
+ ...options.endpoint !== void 0 ? { endpointUrl: options.endpoint } : {},
14769
+ ...headers ? { headers } : {},
14770
+ ...resourceAttributes ? { resourceAttributes } : {},
14402
14771
  ...sourceTypes ? { sourceTypes } : {},
14403
14772
  // Commander's `--no-include-content` sets this to false, so the
14404
14773
  // tri-state survives: absent leaves it, true starts sending content,
@@ -15230,682 +15599,352 @@ var TunnelSession = class {
15230
15599
  this.deps.closeGrantTimeoutMs ?? CLOSE_GRANT_TIMEOUT_MS
15231
15600
  );
15232
15601
  } catch {
15233
- aborter.abort();
15234
- }
15235
- }
15236
- waitUntilClosed() {
15237
- return this.closed;
15238
- }
15239
- /** Ctrl-C path: close everything, best-effort revoke, exit 0. */
15240
- async stop() {
15241
- if (this.stopped) return;
15242
- this.stopped = true;
15243
- this.mintAborter?.abort();
15244
- await this.cleanup();
15245
- if (this.grantResult) {
15246
- const aborter = new AbortController();
15247
- try {
15248
- await withTimeout(
15249
- this.deps.closeGrant(this.grantResult, aborter.signal),
15250
- this.deps.closeGrantTimeoutMs ?? CLOSE_GRANT_TIMEOUT_MS
15251
- );
15252
- this.deps.log("Tunnel grant revoked.");
15253
- } catch (error) {
15254
- aborter.abort();
15255
- this.deps.log(
15256
- `Could not revoke the tunnel grant (${error instanceof Error ? error.message : String(error)}); it dies with the next create or its own expiry.`
15257
- );
15258
- }
15259
- }
15260
- this.settle({ exitCode: 0 });
15261
- }
15262
- async dial(result) {
15263
- this.dialing = true;
15264
- this.pendingPermanent = null;
15265
- try {
15266
- const connection = this.deps.connectRelay({
15267
- grant: result.grant,
15268
- localAddr: this.bridge.localAddr,
15269
- onPermanentFailure: (reason, closeCode) => this.handlePermanentFailure(reason, closeCode)
15270
- });
15271
- this.connection = connection;
15272
- await connection.connect();
15273
- const pending = this.pendingPermanent;
15274
- if (connection.permanentFailure || pending) {
15275
- this.pendingPermanent = null;
15276
- connection.close();
15277
- throw new Error(connection.permanentFailure ?? pending.reason);
15278
- }
15279
- } finally {
15280
- this.dialing = false;
15281
- }
15282
- }
15283
- handlePermanentFailure(reason, closeCode) {
15284
- if (this.stopped || this.settled) return;
15285
- if (this.dialing || !this.started) {
15286
- this.pendingPermanent = { reason, closeCode };
15287
- return;
15288
- }
15289
- this.dispatchPermanentFailure(reason, closeCode);
15290
- }
15291
- flushPendingPermanent() {
15292
- const pending = this.pendingPermanent;
15293
- if (!pending || this.stopped || this.settled) return;
15294
- this.pendingPermanent = null;
15295
- this.dispatchPermanentFailure(pending.reason, pending.closeCode);
15296
- }
15297
- dispatchPermanentFailure(reason, closeCode) {
15298
- if (closeCode === CLOSE_BAD_TOKEN) {
15299
- if (!this.reminting) {
15300
- void this.remint();
15301
- }
15302
- return;
15303
- }
15304
- void this.fail(permanentCloseMessage(reason, closeCode));
15305
- }
15306
- async remint() {
15307
- if (this.reminting) return;
15308
- this.reminting = true;
15309
- try {
15310
- const now = this.deps.now?.() ?? Date.now();
15311
- if (this.lastRemintAt !== null && now - this.lastRemintAt > REMINT_RESET_WINDOW_MS) {
15312
- this.remintAttempts = 0;
15313
- }
15314
- this.lastRemintAt = now;
15315
- this.remintAttempts += 1;
15316
- if (this.remintAttempts > MAX_REMINT_ATTEMPTS) {
15317
- await this.fail(
15318
- `Tunnel session expired and could not be renewed after ${MAX_REMINT_ATTEMPTS} rapid attempts.`
15319
- );
15320
- return;
15321
- }
15322
- this.deps.log(
15323
- `Tunnel session expired; renewing the grant (attempt ${this.remintAttempts}/${MAX_REMINT_ATTEMPTS})...`
15324
- );
15325
- try {
15326
- this.connection?.close();
15327
- const result = await this.mintGrant();
15328
- this.grantResult = result;
15329
- if (this.stopped || this.settled) {
15330
- await this.revokeGrantBestEffort();
15331
- return;
15332
- }
15333
- await this.dial(result);
15334
- this.deps.onGrant?.(result, true);
15335
- } catch (error) {
15336
- await this.revokeGrantBestEffort();
15337
- if (this.stopped || this.settled) return;
15338
- await this.fail(
15339
- `Failed to renew the tunnel: ${error instanceof Error ? error.message : String(error)}`
15340
- );
15341
- }
15342
- } finally {
15343
- this.reminting = false;
15344
- this.flushPendingPermanent();
15345
- }
15346
- }
15347
- async fail(reason) {
15348
- await this.cleanup();
15349
- this.settle({ exitCode: 1, reason });
15350
- }
15351
- async cleanup() {
15352
- this.connection?.close();
15353
- this.connection = null;
15354
- if (this.bridge) {
15355
- const bridge = this.bridge;
15356
- this.bridge = null;
15357
- await bridge.close().catch(() => {
15358
- });
15359
- }
15360
- }
15361
- };
15362
-
15363
- // src/commands/tunnel.ts
15364
- function parseTunnelTarget(tokens) {
15365
- const isUrl = (token) => /^https?:\/\//i.test(token);
15366
- if (tokens.length === 0) {
15367
- throw usageError(
15368
- "Specify a target: a local server URL (mcpjam cloud tunnel http://localhost:9090/mcp --server my-server) or a stdio command (mcpjam cloud tunnel --server my-server -- npx -y @modelcontextprotocol/server-everything)."
15369
- );
15370
- }
15371
- if (isUrl(tokens[0])) {
15372
- if (tokens.length > 1) {
15373
- throw usageError(
15374
- "Pass either a URL or a stdio command (after --), not both."
15375
- );
15376
- }
15377
- try {
15378
- new URL(tokens[0]);
15379
- } catch {
15380
- throw usageError(`Invalid URL: ${tokens[0]}`);
15602
+ aborter.abort();
15381
15603
  }
15382
- return { kind: "http", url: tokens[0] };
15383
- }
15384
- return { kind: "stdio", command: tokens[0], args: tokens.slice(1) };
15385
- }
15386
- function overwriteWarning(result) {
15387
- const grant = result.grant;
15388
- if (!grant.existed) return void 0;
15389
- if (grant.previousTransportType === "stdio") {
15390
- return `WARNING: server "${grant.name ?? grant.serverId}" already existed as a stdio server \u2014 its config was converted to an HTTP server pointing at this tunnel.`;
15391
- }
15392
- if (grant.previousUrl) {
15393
- return `WARNING: server "${grant.name ?? grant.serverId}" already existed \u2014 its URL was overwritten (was: ${grant.previousUrl}).`;
15394
15604
  }
15395
- return void 0;
15396
- }
15397
- function publicHost(url) {
15398
- try {
15399
- return new URL(url).host || url;
15400
- } catch {
15401
- return url;
15605
+ waitUntilClosed() {
15606
+ return this.closed;
15402
15607
  }
15403
- }
15404
- function registerTunnelCommands(program) {
15405
- const tunnel = program.command("tunnel").description(
15406
- "Expose a local MCP server through an MCPJam tunnel and register it as a server in your project"
15407
- ).argument(
15408
- "[target...]",
15409
- "Local http(s) MCP server URL, or a stdio command after `--`"
15410
- );
15411
- addRequiredOptionWithHiddenAlias(
15412
- tunnel,
15413
- "--server <name>",
15414
- "--id",
15415
- "Server name to register in the project (an existing server with this name is pointed at the tunnel)"
15416
- );
15417
- tunnel.option(
15418
- "--project <id-or-name>",
15419
- "Project name or ID (defaults to the most recently updated project)"
15420
- ).option(
15421
- "-e, --env <env...>",
15422
- 'Stdio environment assignment in "KEY=VALUE" format. Pass multiple values or repeat the flag.'
15423
- ).option("--cwd <path>", "Working directory for the stdio MCP server process").action(
15424
- async (target, options, command) => {
15425
- const globalOptions = getGlobalOptions(command);
15426
- const parsedTarget = parseTunnelTarget(target);
15427
- if (parsedTarget.kind === "http" && ((options.env?.length ?? 0) > 0 || options.cwd)) {
15428
- throw usageError(
15429
- "--env and --cwd can only be used with a stdio command target."
15430
- );
15431
- }
15432
- const status = (message) => {
15433
- process.stderr.write(`${message}
15434
- `);
15435
- };
15436
- const bridgeTarget = parsedTarget.kind === "http" ? { kind: "http", url: parsedTarget.url } : {
15437
- kind: "stdio",
15438
- config: parseServerConfig({
15439
- transport: "stdio",
15440
- command: parsedTarget.command,
15441
- args: parsedTarget.args,
15442
- env: options.env,
15443
- cwd: options.cwd,
15444
- timeout: globalOptions.timeout
15445
- })
15446
- };
15447
- const platform = platformOptionsOf(command);
15448
- preflightCloudCredentials(platform);
15449
- const resolved = resolveCloudProjectArgs(options);
15450
- announceCloudContext({
15451
- scope: resolved.projectScope,
15452
- options: platform,
15453
- quiet: globalOptions.quiet
15454
- });
15455
- let client;
15608
+ /** Ctrl-C path: close everything, best-effort revoke, exit 0. */
15609
+ async stop() {
15610
+ if (this.stopped) return;
15611
+ this.stopped = true;
15612
+ this.mintAborter?.abort();
15613
+ await this.cleanup();
15614
+ if (this.grantResult) {
15615
+ const aborter = new AbortController();
15456
15616
  try {
15457
- ({ client } = buildCloudClientContext(
15458
- platform,
15459
- globalOptions.timeout
15460
- ));
15617
+ await withTimeout(
15618
+ this.deps.closeGrant(this.grantResult, aborter.signal),
15619
+ this.deps.closeGrantTimeoutMs ?? CLOSE_GRANT_TIMEOUT_MS
15620
+ );
15621
+ this.deps.log("Tunnel grant revoked.");
15461
15622
  } catch (error) {
15462
- throw toCliError(error);
15623
+ aborter.abort();
15624
+ this.deps.log(
15625
+ `Could not revoke the tunnel grant (${error instanceof Error ? error.message : String(error)}); it dies with the next create or its own expiry.`
15626
+ );
15463
15627
  }
15464
- const printStartup = (result) => {
15465
- const warning = overwriteWarning(result);
15466
- if (warning) status(warning);
15467
- if (globalOptions.format === "human") {
15468
- process.stdout.write(
15469
- `Tunnel live: ${result.grant.url}
15470
- Registered server "${result.grant.name ?? options.server}" in project "${result.project.name}" (${result.grant.serverId})
15471
- `
15472
- );
15473
- status("Press Ctrl-C to stop the tunnel.");
15474
- } else {
15475
- writeResult(
15476
- {
15477
- url: result.grant.url,
15478
- serverId: result.grant.serverId,
15479
- name: result.grant.name ?? options.server,
15480
- slug: result.grant.slug,
15481
- project: result.project,
15482
- existed: result.grant.existed ?? false,
15483
- ...result.grant.previousUrl ? { previousUrl: result.grant.previousUrl } : {},
15484
- ...result.grant.previousTransportType ? { previousTransportType: result.grant.previousTransportType } : {},
15485
- ...result.grant.secretVersion !== void 0 ? { secretVersion: result.grant.secretVersion } : {},
15486
- target: parsedTarget.kind === "http" ? { kind: "http", url: parsedTarget.url } : {
15487
- kind: "stdio",
15488
- command: parsedTarget.command,
15489
- args: parsedTarget.args
15490
- }
15491
- },
15492
- globalOptions.format
15493
- );
15494
- }
15495
- };
15496
- const session = new TunnelSession({
15497
- createGrant: (signal) => createTunnelOperation.execute(
15498
- { project: resolved.project, name: options.server },
15499
- { client, signal }
15500
- ),
15501
- closeGrant: async (result, signal) => {
15502
- await client.closeTunnel(
15503
- {
15504
- projectId: result.project.id,
15505
- serverId: result.grant.serverId
15506
- },
15507
- { signal }
15508
- );
15509
- },
15510
- startBridge: (serverId) => startLocalBridge({
15511
- serverId,
15512
- target: bridgeTarget,
15513
- timeoutMs: globalOptions.timeout,
15514
- log: status
15515
- }),
15516
- connectRelay: ({ grant, localAddr, onPermanentFailure }) => new RelayConnection({
15517
- serverId: grant.serverId,
15518
- slug: grant.slug,
15519
- relayWsUrl: grant.relayWsUrl,
15520
- connectToken: grant.connectToken,
15521
- localAddr,
15522
- publicHost: publicHost(grant.url),
15523
- logger: { info: status, warn: status },
15524
- onPermanentFailure
15525
- }),
15526
- log: status,
15527
- onGrant: (result, rotated) => {
15528
- if (rotated) {
15529
- status(`Tunnel secret rotated; new URL: ${result.grant.url}`);
15530
- return;
15531
- }
15532
- printStartup(result);
15533
- }
15628
+ }
15629
+ this.settle({ exitCode: 0 });
15630
+ }
15631
+ async dial(result) {
15632
+ this.dialing = true;
15633
+ this.pendingPermanent = null;
15634
+ try {
15635
+ const connection = this.deps.connectRelay({
15636
+ grant: result.grant,
15637
+ localAddr: this.bridge.localAddr,
15638
+ onPermanentFailure: (reason, closeCode) => this.handlePermanentFailure(reason, closeCode)
15534
15639
  });
15535
- if (parsedTarget.kind === "stdio") {
15536
- status(
15537
- `Starting stdio server: ${parsedTarget.command}${parsedTarget.args.length ? ` ${parsedTarget.args.join(" ")}` : ""}`
15538
- );
15640
+ this.connection = connection;
15641
+ await connection.connect();
15642
+ const pending = this.pendingPermanent;
15643
+ if (connection.permanentFailure || pending) {
15644
+ this.pendingPermanent = null;
15645
+ connection.close();
15646
+ throw new Error(connection.permanentFailure ?? pending.reason);
15539
15647
  }
15540
- let sigints = 0;
15541
- const onSignal = () => {
15542
- sigints += 1;
15543
- if (sigints === 1) {
15544
- status("Shutting down tunnel... (Ctrl-C again to force quit)");
15545
- void session.stop();
15546
- return;
15547
- }
15548
- process.exit(130);
15549
- };
15550
- process.on("SIGINT", onSignal);
15551
- process.on("SIGTERM", onSignal);
15552
- try {
15553
- const startPromise = session.start();
15554
- try {
15555
- await Promise.race([startPromise, session.waitUntilClosed()]);
15556
- } catch (error) {
15557
- if (sigints === 0) {
15558
- throw toCliError(error);
15559
- }
15560
- }
15561
- if (sigints > 0) {
15562
- startPromise.catch(() => {
15563
- });
15564
- }
15565
- const result = await session.waitUntilClosed();
15566
- if (result.exitCode !== 0) {
15567
- throw cliError(
15568
- "TUNNEL_CLOSED",
15569
- result.reason ?? "Tunnel closed",
15570
- result.exitCode
15571
- );
15648
+ } finally {
15649
+ this.dialing = false;
15650
+ }
15651
+ }
15652
+ handlePermanentFailure(reason, closeCode) {
15653
+ if (this.stopped || this.settled) return;
15654
+ if (this.dialing || !this.started) {
15655
+ this.pendingPermanent = { reason, closeCode };
15656
+ return;
15657
+ }
15658
+ this.dispatchPermanentFailure(reason, closeCode);
15659
+ }
15660
+ flushPendingPermanent() {
15661
+ const pending = this.pendingPermanent;
15662
+ if (!pending || this.stopped || this.settled) return;
15663
+ this.pendingPermanent = null;
15664
+ this.dispatchPermanentFailure(pending.reason, pending.closeCode);
15665
+ }
15666
+ dispatchPermanentFailure(reason, closeCode) {
15667
+ if (closeCode === CLOSE_BAD_TOKEN) {
15668
+ if (!this.reminting) {
15669
+ void this.remint();
15670
+ }
15671
+ return;
15672
+ }
15673
+ void this.fail(permanentCloseMessage(reason, closeCode));
15674
+ }
15675
+ async remint() {
15676
+ if (this.reminting) return;
15677
+ this.reminting = true;
15678
+ try {
15679
+ const now = this.deps.now?.() ?? Date.now();
15680
+ if (this.lastRemintAt !== null && now - this.lastRemintAt > REMINT_RESET_WINDOW_MS) {
15681
+ this.remintAttempts = 0;
15682
+ }
15683
+ this.lastRemintAt = now;
15684
+ this.remintAttempts += 1;
15685
+ if (this.remintAttempts > MAX_REMINT_ATTEMPTS) {
15686
+ await this.fail(
15687
+ `Tunnel session expired and could not be renewed after ${MAX_REMINT_ATTEMPTS} rapid attempts.`
15688
+ );
15689
+ return;
15690
+ }
15691
+ this.deps.log(
15692
+ `Tunnel session expired; renewing the grant (attempt ${this.remintAttempts}/${MAX_REMINT_ATTEMPTS})...`
15693
+ );
15694
+ try {
15695
+ this.connection?.close();
15696
+ const result = await this.mintGrant();
15697
+ this.grantResult = result;
15698
+ if (this.stopped || this.settled) {
15699
+ await this.revokeGrantBestEffort();
15700
+ return;
15572
15701
  }
15573
- } finally {
15574
- process.removeListener("SIGINT", onSignal);
15575
- process.removeListener("SIGTERM", onSignal);
15702
+ await this.dial(result);
15703
+ this.deps.onGrant?.(result, true);
15704
+ } catch (error) {
15705
+ await this.revokeGrantBestEffort();
15706
+ if (this.stopped || this.settled) return;
15707
+ await this.fail(
15708
+ `Failed to renew the tunnel: ${error instanceof Error ? error.message : String(error)}`
15709
+ );
15576
15710
  }
15711
+ } finally {
15712
+ this.reminting = false;
15713
+ this.flushPendingPermanent();
15577
15714
  }
15578
- );
15579
- }
15580
- function scenarioCommand(group, name, description) {
15581
- return addProjectOption(
15582
- group.command(name).description(description).requiredOption("--scenario <id>", "Scenario ID")
15583
- );
15715
+ }
15716
+ async fail(reason) {
15717
+ await this.cleanup();
15718
+ this.settle({ exitCode: 1, reason });
15719
+ }
15720
+ async cleanup() {
15721
+ this.connection?.close();
15722
+ this.connection = null;
15723
+ if (this.bridge) {
15724
+ const bridge = this.bridge;
15725
+ this.bridge = null;
15726
+ await bridge.close().catch(() => {
15727
+ });
15728
+ }
15729
+ }
15730
+ };
15731
+
15732
+ // src/commands/tunnel.ts
15733
+ function parseTunnelTarget(tokens) {
15734
+ const isUrl = (token) => /^https?:\/\//i.test(token);
15735
+ if (tokens.length === 0) {
15736
+ throw usageError(
15737
+ "Specify a target: a local server URL (mcpjam cloud tunnel http://localhost:9090/mcp --server my-server) or a stdio command (mcpjam cloud tunnel --server my-server -- npx -y @modelcontextprotocol/server-everything)."
15738
+ );
15739
+ }
15740
+ if (isUrl(tokens[0])) {
15741
+ if (tokens.length > 1) {
15742
+ throw usageError(
15743
+ "Pass either a URL or a stdio command (after --), not both."
15744
+ );
15745
+ }
15746
+ try {
15747
+ new URL(tokens[0]);
15748
+ } catch {
15749
+ throw usageError(`Invalid URL: ${tokens[0]}`);
15750
+ }
15751
+ return { kind: "http", url: tokens[0] };
15752
+ }
15753
+ return { kind: "stdio", command: tokens[0], args: tokens.slice(1) };
15584
15754
  }
15585
- function addPageOptions2(command) {
15586
- return command.option("--cursor <cursor>", "Page cursor from a previous response").option("--limit <n>", "Page size");
15755
+ function overwriteWarning(result) {
15756
+ const grant = result.grant;
15757
+ if (!grant.existed) return void 0;
15758
+ if (grant.previousTransportType === "stdio") {
15759
+ return `WARNING: server "${grant.name ?? grant.serverId}" already existed as a stdio server \u2014 its config was converted to an HTTP server pointing at this tunnel.`;
15760
+ }
15761
+ if (grant.previousUrl) {
15762
+ return `WARNING: server "${grant.name ?? grant.serverId}" already existed \u2014 its URL was overwritten (was: ${grant.previousUrl}).`;
15763
+ }
15764
+ return void 0;
15587
15765
  }
15588
- function pageArgs2(options) {
15589
- const limit = parseIntegerOption(options.limit, "--limit");
15590
- return {
15591
- ...options.cursor ? { cursor: options.cursor } : {},
15592
- ...limit !== void 0 ? { limit } : {}
15593
- };
15766
+ function publicHost(url) {
15767
+ try {
15768
+ return new URL(url).host || url;
15769
+ } catch {
15770
+ return url;
15771
+ }
15594
15772
  }
15595
- function registerUserTestingCommands(program) {
15596
- const group = program.command("user-testing").description(
15597
- "Read what a published scenario produced, and control who can reach it"
15598
- );
15599
- bindOperation(
15600
- scenarioCommand(
15601
- group,
15602
- "get",
15603
- "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."
15604
- ),
15605
- getUserTestingScenarioOperation,
15606
- (options) => ({
15607
- project: options.project,
15608
- scenario: options.scenario
15609
- })
15610
- );
15611
- bindOperation(
15612
- addPageOptions2(
15613
- scenarioCommand(
15614
- group,
15615
- "sessions",
15616
- "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."
15617
- )
15618
- ),
15619
- listUserTestingSessionsOperation,
15620
- (options) => ({
15621
- project: options.project,
15622
- scenario: options.scenario,
15623
- ...pageArgs2(options)
15624
- })
15625
- );
15626
- bindOperation(
15627
- addPageOptions2(
15628
- scenarioCommand(
15629
- group,
15630
- "session",
15631
- "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."
15632
- ).requiredOption("--session <id>", "Session ID")
15633
- ),
15634
- getUserTestingSessionOperation,
15635
- (options) => ({
15636
- project: options.project,
15637
- scenario: options.scenario,
15638
- session: options.session,
15639
- ...pageArgs2(options)
15640
- })
15641
- );
15642
- bindOperation(
15643
- scenarioCommand(
15644
- group,
15645
- "metrics",
15646
- "Aggregate metrics across a scenario's sessions."
15647
- ).option("--population <name>", "Restrict to a session population"),
15648
- getUserTestingMetricsOperation,
15649
- (options) => ({
15650
- project: options.project,
15651
- scenario: options.scenario,
15652
- ...options.population ? { population: options.population } : {}
15653
- })
15654
- );
15655
- bindOperation(
15656
- scenarioCommand(
15657
- group,
15658
- "usage",
15659
- "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."
15660
- ),
15661
- getUserTestingUsageOperation,
15662
- (options) => ({
15663
- project: options.project,
15664
- scenario: options.scenario
15665
- })
15666
- );
15667
- bindOperation(
15668
- scenarioCommand(
15669
- group,
15670
- "findings",
15671
- "Problems detected across a scenario's sessions, tracked over time."
15672
- ),
15673
- listUserTestingFindingsOperation,
15674
- (options) => ({
15675
- project: options.project,
15676
- scenario: options.scenario
15677
- })
15678
- );
15679
- bindOperation(
15680
- scenarioCommand(
15681
- group,
15682
- "signals",
15683
- "The scenario's live analysis window, and the windowId its insights are keyed by."
15684
- ),
15685
- getUserTestingSignalsOperation,
15686
- (options) => ({
15687
- project: options.project,
15688
- scenario: options.scenario
15689
- })
15690
- );
15691
- bindOperation(
15692
- scenarioCommand(
15693
- group,
15694
- "insights",
15695
- "The model's analysis of one window, if one has been requested. Not-found means nobody asked, which is different from asked-and-working."
15696
- ).requiredOption("--window <id>", "Window ID (from `signals`)"),
15697
- getUserTestingInsightsOperation,
15698
- (options) => ({
15699
- project: options.project,
15700
- scenario: options.scenario,
15701
- window: options.window
15702
- })
15703
- );
15704
- bindOperation(
15705
- scenarioCommand(
15706
- group,
15707
- "request-insights",
15708
- "Ask a model to analyze the current window. Returns pending; poll `insights`. Included with MCPJam \u2014 no credits are consumed; it counts against a daily insight quota shared with swarm insights. A 409 means the window has not been mined yet \u2014 wait rather than retrying in a loop."
15709
- ).option("--force", "Regenerate over a window that already has insights."),
15710
- requestUserTestingInsightsOperation,
15711
- (options) => ({
15712
- project: options.project,
15713
- scenario: options.scenario,
15714
- ...options.force ? { force: true } : {}
15715
- })
15716
- );
15717
- bindOperation(
15718
- scenarioCommand(
15719
- group,
15720
- "cancel-insights",
15721
- "Stop an in-flight generation. The recovery path for a window stuck pending \u2014 without it the only way forward is --force, which takes another slice of the daily insight quota."
15722
- ).requiredOption("--window <id>", "Window ID"),
15723
- cancelUserTestingInsightsOperation,
15724
- (options) => ({
15725
- project: options.project,
15726
- scenario: options.scenario,
15727
- window: options.window
15728
- })
15729
- );
15730
- bindOperation(
15731
- scenarioCommand(
15732
- group,
15733
- "dismiss-finding",
15734
- "Mark a finding as not worth acting on. Its lifecycle keeps updating underneath."
15735
- ).requiredOption("--finding <id>", "Finding ID"),
15736
- dismissUserTestingFindingOperation,
15737
- (options) => ({
15738
- project: options.project,
15739
- scenario: options.scenario,
15740
- finding: options.finding
15741
- })
15742
- );
15743
- bindOperation(
15744
- scenarioCommand(
15745
- group,
15746
- "undismiss-finding",
15747
- "Bring a dismissed finding back into the active list."
15748
- ).requiredOption("--finding <id>", "Finding ID"),
15749
- undismissUserTestingFindingOperation,
15750
- (options) => ({
15751
- project: options.project,
15752
- scenario: options.scenario,
15753
- finding: options.finding
15754
- })
15755
- );
15756
- bindOperation(
15757
- scenarioCommand(
15758
- group,
15759
- "update",
15760
- "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."
15761
- ).option("--name <name>").option("--description <text>").option(
15762
- "--mode <mode>",
15763
- "project_members | invited_only | anyone_with_link"
15764
- ),
15765
- updateUserTestingScenarioOperation,
15766
- (options) => ({
15767
- project: options.project,
15768
- scenario: options.scenario,
15769
- ...options.name !== void 0 ? { name: options.name } : {},
15770
- ...options.description !== void 0 ? { description: options.description } : {},
15771
- ...options.mode !== void 0 ? { mode: options.mode } : {}
15772
- })
15773
+ function registerTunnelCommands(program) {
15774
+ const tunnel = program.command("tunnel").description(
15775
+ "Expose a local MCP server through an MCPJam tunnel and register it as a server in your project"
15776
+ ).argument(
15777
+ "[target...]",
15778
+ "Local http(s) MCP server URL, or a stdio command after `--`"
15773
15779
  );
15774
- bindOperation(
15775
- scenarioCommand(
15776
- group,
15777
- "guest-execution",
15778
- "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."
15779
- ).requiredOption("--enabled <bool>", "true | false").requiredOption("--computer-enabled <bool>", "true | false").requiredOption("--shared-skills-enabled <bool>", "true | false").requiredOption(
15780
- "--daily-credit-cap <n>",
15781
- "Hard ceiling on visitor spend per day, in credits"
15782
- ).requiredOption("--daily-computer-start-cap <n>").requiredOption("--max-concurrent-computers <n>").option(
15783
- "--harness-enabled <bool>",
15784
- "true | false. Omitting this REPLACES any existing harness setting with 'disabled'."
15785
- ).option("--daily-harness-spend-cap-micros <n>").option("--daily-harness-call-cap <n>").option("--max-concurrent-harness-runs <n>"),
15786
- setUserTestingGuestExecutionOperation,
15787
- (options) => {
15788
- if (options.harnessEnabled === void 0 && (options.dailyHarnessSpendCapMicros !== void 0 || options.dailyHarnessCallCap !== void 0 || options.maxConcurrentHarnessRuns !== void 0)) {
15780
+ addRequiredOptionWithHiddenAlias(
15781
+ tunnel,
15782
+ "--server <name>",
15783
+ "--id",
15784
+ "Server name to register in the project (an existing server with this name is pointed at the tunnel)"
15785
+ );
15786
+ tunnel.option(
15787
+ "--project <id-or-name>",
15788
+ "Project name or ID (defaults to the most recently updated project)"
15789
+ ).option(
15790
+ "-e, --env <env...>",
15791
+ 'Stdio environment assignment in "KEY=VALUE" format. Pass multiple values or repeat the flag.'
15792
+ ).option("--cwd <path>", "Working directory for the stdio MCP server process").action(
15793
+ async (target, options, command) => {
15794
+ const globalOptions = getGlobalOptions(command);
15795
+ const parsedTarget = parseTunnelTarget(target);
15796
+ if (parsedTarget.kind === "http" && ((options.env?.length ?? 0) > 0 || options.cwd)) {
15789
15797
  throw usageError(
15790
- "--harness-enabled is required when any harness cap is given: omitting it disables the harness, so the caps would land on nothing."
15798
+ "--env and --cwd can only be used with a stdio command target."
15791
15799
  );
15792
15800
  }
15793
- return {
15794
- project: options.project,
15795
- scenario: options.scenario,
15796
- enabled: parseBooleanFlag(options.enabled, "--enabled"),
15797
- computerEnabled: parseBooleanFlag(
15798
- options.computerEnabled,
15799
- "--computer-enabled"
15800
- ),
15801
- sharedSkillsEnabled: parseBooleanFlag(
15802
- options.sharedSkillsEnabled,
15803
- "--shared-skills-enabled"
15804
- ),
15805
- dailyCreditCap: parseNumberFlag(
15806
- options.dailyCreditCap,
15807
- "--daily-credit-cap"
15808
- ),
15809
- dailyComputerStartCap: parseRequiredIntegerOption(
15810
- options.dailyComputerStartCap,
15811
- "--daily-computer-start-cap"
15812
- ),
15813
- maxConcurrentComputers: parseRequiredIntegerOption(
15814
- options.maxConcurrentComputers,
15815
- "--max-concurrent-computers"
15801
+ const status = (message) => {
15802
+ process.stderr.write(`${message}
15803
+ `);
15804
+ };
15805
+ const bridgeTarget = parsedTarget.kind === "http" ? { kind: "http", url: parsedTarget.url } : {
15806
+ kind: "stdio",
15807
+ config: parseServerConfig({
15808
+ transport: "stdio",
15809
+ command: parsedTarget.command,
15810
+ args: parsedTarget.args,
15811
+ env: options.env,
15812
+ cwd: options.cwd,
15813
+ timeout: globalOptions.timeout
15814
+ })
15815
+ };
15816
+ const platform = platformOptionsOf(command);
15817
+ preflightCloudCredentials(platform);
15818
+ const resolved = resolveCloudProjectArgs(options);
15819
+ announceCloudContext({
15820
+ scope: resolved.projectScope,
15821
+ options: platform,
15822
+ quiet: globalOptions.quiet
15823
+ });
15824
+ let client;
15825
+ try {
15826
+ ({ client } = buildCloudClientContext(
15827
+ platform,
15828
+ globalOptions.timeout
15829
+ ));
15830
+ } catch (error) {
15831
+ throw toCliError(error);
15832
+ }
15833
+ const printStartup = (result) => {
15834
+ const warning = overwriteWarning(result);
15835
+ if (warning) status(warning);
15836
+ if (globalOptions.format === "human") {
15837
+ process.stdout.write(
15838
+ `Tunnel live: ${result.grant.url}
15839
+ Registered server "${result.grant.name ?? options.server}" in project "${result.project.name}" (${result.grant.serverId})
15840
+ `
15841
+ );
15842
+ status("Press Ctrl-C to stop the tunnel.");
15843
+ } else {
15844
+ writeResult(
15845
+ {
15846
+ url: result.grant.url,
15847
+ serverId: result.grant.serverId,
15848
+ name: result.grant.name ?? options.server,
15849
+ slug: result.grant.slug,
15850
+ project: result.project,
15851
+ existed: result.grant.existed ?? false,
15852
+ ...result.grant.previousUrl ? { previousUrl: result.grant.previousUrl } : {},
15853
+ ...result.grant.previousTransportType ? { previousTransportType: result.grant.previousTransportType } : {},
15854
+ ...result.grant.secretVersion !== void 0 ? { secretVersion: result.grant.secretVersion } : {},
15855
+ target: parsedTarget.kind === "http" ? { kind: "http", url: parsedTarget.url } : {
15856
+ kind: "stdio",
15857
+ command: parsedTarget.command,
15858
+ args: parsedTarget.args
15859
+ }
15860
+ },
15861
+ globalOptions.format
15862
+ );
15863
+ }
15864
+ };
15865
+ const session = new TunnelSession({
15866
+ createGrant: (signal) => createTunnelOperation.execute(
15867
+ { project: resolved.project, name: options.server },
15868
+ { client, signal }
15816
15869
  ),
15817
- ...options.harnessEnabled !== void 0 ? {
15818
- harnessEnabled: parseBooleanFlag(
15819
- options.harnessEnabled,
15820
- "--harness-enabled"
15821
- )
15822
- } : {},
15823
- ...options.dailyHarnessSpendCapMicros !== void 0 ? {
15824
- dailyHarnessSpendCapMicros: parseIntegerOption(
15825
- options.dailyHarnessSpendCapMicros,
15826
- "--daily-harness-spend-cap-micros"
15827
- )
15828
- } : {},
15829
- ...options.dailyHarnessCallCap !== void 0 ? {
15830
- dailyHarnessCallCap: parseIntegerOption(
15831
- options.dailyHarnessCallCap,
15832
- "--daily-harness-call-cap"
15833
- )
15834
- } : {},
15835
- ...options.maxConcurrentHarnessRuns !== void 0 ? {
15836
- maxConcurrentHarnessRuns: parseIntegerOption(
15837
- options.maxConcurrentHarnessRuns,
15838
- "--max-concurrent-harness-runs"
15839
- )
15840
- } : {}
15870
+ closeGrant: async (result, signal) => {
15871
+ await client.closeTunnel(
15872
+ {
15873
+ projectId: result.project.id,
15874
+ serverId: result.grant.serverId
15875
+ },
15876
+ { signal }
15877
+ );
15878
+ },
15879
+ startBridge: (serverId) => startLocalBridge({
15880
+ serverId,
15881
+ target: bridgeTarget,
15882
+ timeoutMs: globalOptions.timeout,
15883
+ log: status
15884
+ }),
15885
+ connectRelay: ({ grant, localAddr, onPermanentFailure }) => new RelayConnection({
15886
+ serverId: grant.serverId,
15887
+ slug: grant.slug,
15888
+ relayWsUrl: grant.relayWsUrl,
15889
+ connectToken: grant.connectToken,
15890
+ localAddr,
15891
+ publicHost: publicHost(grant.url),
15892
+ logger: { info: status, warn: status },
15893
+ onPermanentFailure
15894
+ }),
15895
+ log: status,
15896
+ onGrant: (result, rotated) => {
15897
+ if (rotated) {
15898
+ status(`Tunnel secret rotated; new URL: ${result.grant.url}`);
15899
+ return;
15900
+ }
15901
+ printStartup(result);
15902
+ }
15903
+ });
15904
+ if (parsedTarget.kind === "stdio") {
15905
+ status(
15906
+ `Starting stdio server: ${parsedTarget.command}${parsedTarget.args.length ? ` ${parsedTarget.args.join(" ")}` : ""}`
15907
+ );
15908
+ }
15909
+ let sigints = 0;
15910
+ const onSignal = () => {
15911
+ sigints += 1;
15912
+ if (sigints === 1) {
15913
+ status("Shutting down tunnel... (Ctrl-C again to force quit)");
15914
+ void session.stop();
15915
+ return;
15916
+ }
15917
+ process.exit(130);
15841
15918
  };
15919
+ process.on("SIGINT", onSignal);
15920
+ process.on("SIGTERM", onSignal);
15921
+ try {
15922
+ const startPromise = session.start();
15923
+ try {
15924
+ await Promise.race([startPromise, session.waitUntilClosed()]);
15925
+ } catch (error) {
15926
+ if (sigints === 0) {
15927
+ throw toCliError(error);
15928
+ }
15929
+ }
15930
+ if (sigints > 0) {
15931
+ startPromise.catch(() => {
15932
+ });
15933
+ }
15934
+ const result = await session.waitUntilClosed();
15935
+ if (result.exitCode !== 0) {
15936
+ throw cliError(
15937
+ "TUNNEL_CLOSED",
15938
+ result.reason ?? "Tunnel closed",
15939
+ result.exitCode
15940
+ );
15941
+ }
15942
+ } finally {
15943
+ process.removeListener("SIGINT", onSignal);
15944
+ process.removeListener("SIGTERM", onSignal);
15945
+ }
15842
15946
  }
15843
15947
  );
15844
- bindOperation(
15845
- scenarioCommand(
15846
- group,
15847
- "rotate-link",
15848
- "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."
15849
- ),
15850
- rotateUserTestingLinkOperation,
15851
- (options) => ({
15852
- project: options.project,
15853
- scenario: options.scenario
15854
- })
15855
- );
15856
- bindOperation(
15857
- scenarioCommand(
15858
- group,
15859
- "invite",
15860
- "Grant one person access by email. Upsert, so re-inviting an existing member is not an error."
15861
- ).requiredOption("--email <email>").option("--send-invite-email", "Also email them. Off by default."),
15862
- upsertUserTestingMemberOperation,
15863
- (options) => ({
15864
- project: options.project,
15865
- scenario: options.scenario,
15866
- email: options.email,
15867
- ...options.sendInviteEmail ? { sendInviteEmail: true } : {}
15868
- })
15869
- );
15870
- bindOperation(
15871
- scenarioCommand(
15872
- group,
15873
- "remove-member",
15874
- "Revoke one person's access."
15875
- ).requiredOption("--member <id-or-email>"),
15876
- removeUserTestingMemberOperation,
15877
- (options) => ({
15878
- project: options.project,
15879
- scenario: options.scenario,
15880
- member: options.member
15881
- })
15882
- );
15883
- bindOperation(
15884
- scenarioCommand(
15885
- group,
15886
- "rebind",
15887
- "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."
15888
- ).requiredOption("--environment <id>", "Project environment ID"),
15889
- rebindUserTestingScenarioOperation,
15890
- (options) => ({
15891
- project: options.project,
15892
- scenario: options.scenario,
15893
- environmentId: options.environment
15894
- })
15895
- );
15896
- }
15897
- function parseBooleanFlag(value, flag) {
15898
- const normalized = value.trim().toLowerCase();
15899
- if (normalized === "true") return true;
15900
- if (normalized === "false") return false;
15901
- throw new Error(`${flag} must be true or false`);
15902
- }
15903
- function parseNumberFlag(value, flag) {
15904
- const parsed = Number(value);
15905
- if (!Number.isFinite(parsed) || parsed < 0) {
15906
- throw new Error(`${flag} must be a non-negative number`);
15907
- }
15908
- return parsed;
15909
15948
  }
15910
15949
 
15911
15950
  // src/commands/cloud.ts
@@ -15932,10 +15971,9 @@ function registerCloudCommands(program) {
15932
15971
  cloud.commandsGroup("Observability:");
15933
15972
  registerTraceDestinationsCommands(cloud);
15934
15973
  cloud.commandsGroup("Swarms and user testing:");
15935
- const journeys = registerJourneysCommands(cloud);
15936
- registerScenariosCommands(cloud);
15937
- registerSwarmAuthoringCommands(cloud, journeys);
15938
- registerUserTestingCommands(cloud);
15974
+ const goals = registerGoalsCommands(cloud);
15975
+ registerSwarmAuthoringCommands(cloud, goals);
15976
+ registerStudiesCommands(cloud);
15939
15977
  return cloud;
15940
15978
  }
15941
15979
  function resolveHostConnection(hostId) {