@applitools/mcp 0.8.4 → 0.8.6

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
@@ -50,10 +50,9 @@ const TOOL_NAMES = {
50
50
  EYES_SETUP_PROJECT: 'eyes_setup_project',
51
51
  EYES_SETUP_UFG: 'eyes_setup_ufg',
52
52
  EYES_ADD_CHECKPOINTS: 'eyes_add_checkpoints_to_test',
53
- EYES_GET_BATCH_URL: 'eyes_get_batch_url',
54
- EYES_FETCH_VISUAL_RESULTS: 'eyes_fetch_visual_results',
55
- EYES_ANALYZE_BATCH: 'eyes_analyze_batch',
56
53
  };
54
+ /** Opt-in for the experimental tool set (`1`/`true`). Off by default; see `EXPERIMENTAL_TOOLS`. */
55
+ const EXPERIMENTAL_ENV = 'APPLITOOLS_MCP_EXPERIMENTAL';
57
56
  const DEFAULT_SERVER_URL = 'https://eyes.applitools.com';
58
57
  const TRANSPORT_MODE = 'stdio';
59
58
  const RESOURCE_URIS = {
@@ -216,7 +215,6 @@ function findApiKey(workingDirectory = process.cwd()) {
216
215
  let currentClientInfo = undefined;
217
216
  let currentCredentials = undefined;
218
217
  let ide = undefined;
219
- let experimental = false;
220
218
  function setClientInfo(clientInfo) {
221
219
  currentClientInfo = clientInfo;
222
220
  }
@@ -239,20 +237,10 @@ function parseIDE(env, argv) {
239
237
  var _a;
240
238
  return env['ide'] || ((_a = argv.find(arg => arg.startsWith('--ide='))) === null || _a === void 0 ? void 0 : _a.split('=')[1]) || 'unknown';
241
239
  }
242
- function setExperimental(enabled) {
243
- experimental = enabled;
244
- }
245
- function isExperimental() {
246
- return experimental;
247
- }
248
- /**
249
- * The swap is unconditional: the server always registers the eyes-inspect/eyes-resolve/eyes-review
250
- * families in place of the legacy results tools — see `registerAllTools`. No env, argv or config
251
- * turns it off; the retired `--experimental` argv and `APPLITOOLS_MCP_EXPERIMENTAL` stay ignored.
252
- * Kept as a seam so the mode plumbing can be unwound in one pass rather than threaded through here.
253
- */
254
- function parseExperimental() {
255
- return true;
240
+ /** Evaluated once at process start; off unless `EXPERIMENTAL_ENV` is `1`/`true` (any case). */
241
+ function parseExperimental(env) {
242
+ var _a;
243
+ return ['1', 'true'].includes(((_a = env[EXPERIMENTAL_ENV]) !== null && _a !== void 0 ? _a : '').toLowerCase());
256
244
  }
257
245
 
258
246
  /** Load credentials from server context, config files, or environment variables */
@@ -552,6 +540,17 @@ function recordScopeMode(scopeId, mode, deps = defaultPhaseTrackerDeps) {
552
540
  function getScopeMode(scopeId, deps = defaultPhaseTrackerDeps) {
553
541
  return readJson(deps, recordPath(deps, 'modes', scopeId));
554
542
  }
543
+ /**
544
+ * Persists `rootScope` as the root of the review that last touched `scopeId`, overwriting any earlier one.
545
+ * A hint for the caller's guidance only: concurrent reviews of one scope overwrite each other.
546
+ */
547
+ function recordScopeRoot(scopeId, rootScope, deps = defaultPhaseTrackerDeps) {
548
+ writeJson(deps, recordPath(deps, 'roots', scopeId), rootScope);
549
+ }
550
+ /** The root last recorded for `scopeId` via `recordScopeRoot`, or `undefined` if never recorded. */
551
+ function getScopeRoot(scopeId, deps = defaultPhaseTrackerDeps) {
552
+ return readJson(deps, recordPath(deps, 'roots', scopeId));
553
+ }
555
554
  /** Discards `id`'s completion, as if `recordCompletion` had never been called for it. */
556
555
  function clearCompletion(id, deps = defaultPhaseTrackerDeps) {
557
556
  withRetry(() => deps.deleteFile(recordPath(deps, 'completions', id)), deps);
@@ -564,6 +563,10 @@ function clearChildFindings(parentId, deps = defaultPhaseTrackerDeps) {
564
563
  function clearScopeMode(scopeId, deps = defaultPhaseTrackerDeps) {
565
564
  withRetry(() => deps.deleteFile(recordPath(deps, 'modes', scopeId)), deps);
566
565
  }
566
+ /** Discards `scopeId`'s recorded root, as if `recordScopeRoot` had never been called for it. */
567
+ function clearScopeRoot(scopeId, deps = defaultPhaseTrackerDeps) {
568
+ withRetry(() => deps.deleteFile(recordPath(deps, 'roots', scopeId)), deps);
569
+ }
567
570
  /** Persists the keys of `scopeId`'s children still unready to be finalized, as of its own latest live check — overwriting whatever was recorded before, so a child that has since become ready (or a newly-discovered unready one) is reflected exactly, never accumulated across checks. */
568
571
  function recordUnreadyChildren(scopeId, childKeys, deps = defaultPhaseTrackerDeps) {
569
572
  writeJson(deps, recordPath(deps, 'unready-children', scopeId), childKeys);
@@ -3827,7 +3830,7 @@ async function getCompatibleSelectors(options, image1, image2, selectors, fetchI
3827
3830
  * differs from what the test actually ran with (see `eyes-inspect`'s `fetchDiffRects`, this
3828
3831
  * function's only caller, for when the more expensive `compareStep` path is needed instead).
3829
3832
  */
3830
- async function fetchStepDiff$1(options, fetchImpl = reqTransport) {
3833
+ async function fetchStepDiff(options, fetchImpl = reqTransport) {
3831
3834
  const { baseUrl, batchId, sessionId, stepIndex, accountId, keys } = options;
3832
3835
  const url = `${baseUrl}/api/sessions/batches/${batchId}/${sessionId}/${stepIndex}/diff?accountId=${accountId}&apiKey=${encodeURIComponent(keys.getReadKey())}`;
3833
3836
  const data = await getJson(url, fetchImpl);
@@ -4060,7 +4063,7 @@ async function mapAnchoredRegionsBySelector(rawSession, stepIndex, anchored, dep
4060
4063
  }
4061
4064
 
4062
4065
  const defaultFetchRawDiffsDeps = {
4063
- fetchStepDiff: fetchStepDiff$1,
4066
+ fetchStepDiff,
4064
4067
  compareStep,
4065
4068
  readFile: defaultFsCacheDeps.readFile,
4066
4069
  writeFile: defaultFsCacheDeps.writeFile,
@@ -4496,7 +4499,7 @@ function gateRejectionCount() {
4496
4499
 
4497
4500
  var name = "@applitools/mcp";
4498
4501
  var mcpName = "io.github.applitools/applitools";
4499
- var version = "0.8.4";
4502
+ var version = "0.8.6";
4500
4503
  var description = "Applitools MCP server for AI coding assistants";
4501
4504
  var main = "./dist/index.js";
4502
4505
  var bin = "./dist/index.js";
@@ -4537,13 +4540,6 @@ var author = {
4537
4540
  name: "Applitools Team",
4538
4541
  email: "team@applitools.com"
4539
4542
  };
4540
- var repository = {
4541
- type: "git",
4542
- url: "https://github.com/applitools/mcp"
4543
- };
4544
- var bugs = {
4545
- url: "https://github.com/applitools/mcp/issues"
4546
- };
4547
4543
  var homepage = "https://applitools.com";
4548
4544
  var files = [
4549
4545
  "dist",
@@ -4613,8 +4609,6 @@ var packageJson = {
4613
4609
  icon: icon,
4614
4610
  license: license,
4615
4611
  author: author,
4616
- repository: repository,
4617
- bugs: bugs,
4618
4612
  homepage: homepage,
4619
4613
  files: files,
4620
4614
  engines: engines,
@@ -4764,7 +4758,7 @@ const createToolHandler = (toolDef, logic) => {
4764
4758
  const { batchId, sessionId } = extractScopeIds(safeParams);
4765
4759
  const telemetry = {};
4766
4760
  const callInputs = reportedInputs(safeParams);
4767
- const outcomeJsonParams = () => jsonParams({ experimental_mode: isExperimental(), ...telemetry, gate_rejections: gateRejectionCount() }, callInputs);
4761
+ const outcomeJsonParams = () => jsonParams({ ...telemetry, gate_rejections: gateRejectionCount() }, callInputs);
4768
4762
  externalLog('mcp_tool_invoked', {
4769
4763
  ide: getIDE() || 'unknown',
4770
4764
  mcp_version: packageJson.version,
@@ -4775,7 +4769,7 @@ const createToolHandler = (toolDef, logic) => {
4775
4769
  batch_id: batchId,
4776
4770
  session_id: sessionId,
4777
4771
  params: JSON.stringify(params, null, 2).slice(0, 1024),
4778
- json_params: jsonParams({ experimental_mode: isExperimental() }, callInputs),
4772
+ json_params: jsonParams({}, callInputs),
4779
4773
  automation_framework: automationFramework,
4780
4774
  automation_framework_version: automationFrameworkVersion,
4781
4775
  sdk_language: sdkLanguage,
@@ -4800,7 +4794,10 @@ const createToolHandler = (toolDef, logic) => {
4800
4794
  transport_mode: TRANSPORT_MODE,
4801
4795
  batch_id: batchId,
4802
4796
  session_id: sessionId,
4803
- params: JSON.stringify(truncateForTelemetry(structuredContentWithoutMessage), null, 2).slice(0, 1024),
4797
+ // Only tools with structured output report it; an empty `{}` carries nothing worth a field.
4798
+ ...(Object.keys(structuredContentWithoutMessage).length
4799
+ ? { params: JSON.stringify(truncateForTelemetry(structuredContentWithoutMessage), null, 2).slice(0, 1024) }
4800
+ : {}),
4804
4801
  json_params: outcomeJsonParams(),
4805
4802
  }).catch(() => { });
4806
4803
  const handlerResult = result;
@@ -5066,8 +5063,8 @@ async function verifyApiKeyWithServer(params) {
5066
5063
  }
5067
5064
 
5068
5065
  /** Authentication Tools - Verify API Key */
5069
- const TOOL_NAME$6 = TOOL_NAMES.EYES_VERIFY_API_KEY;
5070
- const TOOL_DESCRIPTION$6 = 'Validate your Applitools API key and optional server URL. Searches for API key in .env, applitools.config.js/ts/cjs/mjs, and playwright.config.js/ts/cjs/mjs files.';
5066
+ const TOOL_NAME$3 = TOOL_NAMES.EYES_VERIFY_API_KEY;
5067
+ const TOOL_DESCRIPTION$3 = 'Validate your Applitools API key and optional server URL. Searches for API key in .env, applitools.config.js/ts/cjs/mjs, and playwright.config.js/ts/cjs/mjs files.';
5071
5068
  const VerifyApiKeyInputSchema = zod.z.object({
5072
5069
  apiKey: zod.z.string().optional().describe('Optional API key to validate (will search config files if not provided)'),
5073
5070
  serverUrl: zod.z.string().optional().describe('Optional Applitools server URL (defaults to https://eyes.applitools.com)'),
@@ -5143,11 +5140,11 @@ async function verifyApiKey(input = {}) {
5143
5140
  /** Verify API Key Tool - MCP Tool Object Export */
5144
5141
  /** MCP Tool Object for verify_api_key */
5145
5142
  const verifyApiKeyTool = {
5146
- name: TOOL_NAME$6,
5147
- description: TOOL_DESCRIPTION$6,
5143
+ name: TOOL_NAME$3,
5144
+ description: TOOL_DESCRIPTION$3,
5148
5145
  inputSchema: VerifyApiKeyInputSchema,
5149
5146
  handler: createToolHandler({
5150
- name: TOOL_NAME$6,
5147
+ name: TOOL_NAME$3,
5151
5148
  input: VerifyApiKeyInputSchema,
5152
5149
  }, async (params) => {
5153
5150
  const result = await verifyApiKey(params);
@@ -5243,61 +5240,28 @@ function validateCommonInput(input) {
5243
5240
  };
5244
5241
  }
5245
5242
 
5246
- // The setup prompts' results-flow guidance, switched on the server's experimental mode: the
5247
- // default text teaches the legacy results tools; experimental hides those tools (see
5248
- // `registerAllTools`), so the same sections teach the eyes-review/eyes-inspect flow instead.
5249
- // The new-family tool names are spelled literally, matching how the family descriptions
5250
- // reference each other, to keep this module free of the families' import graph.
5251
- /** Why `--reporter` overrides are forbidden — the justification names whichever results surface the mode has. */
5243
+ // Tool names are spelled literally, matching how the family descriptions reference each other,
5244
+ // to keep this module free of the families' import graph.
5245
+ /** Why `--reporter` overrides are forbidden — the justification names what the run loses. */
5252
5246
  function reporterOverrideWarning() {
5253
- const consequence = isExperimental()
5254
- ? 'which means the HTML report will not contain Eyes results and the batch URL printed at the end of the run is lost.'
5255
- : `which means the HTML report will not contain Eyes results. The "${TOOL_NAMES.EYES_FETCH_VISUAL_RESULTS}" tool will then read a stale report from a previous run and return outdated results.`;
5256
- return `**IMPORTANT: When running Playwright tests (including this example), NEVER add \`--reporter=list\`, \`--reporter=dot\`, \`--reporter=line\`, or any other \`--reporter\` flag. Doing so overrides the configured reporters and suppresses the Eyes reporter, ${consequence}**`;
5247
+ return '**IMPORTANT: When running Playwright tests (including this example), NEVER add `--reporter=list`, `--reporter=dot`, `--reporter=line`, or any other `--reporter` flag. Doing so overrides the configured reporters and suppresses the Eyes reporter, which means the HTML report will not contain Eyes results and the batch URL printed at the end of the run is lost.**';
5257
5248
  }
5258
5249
  const REVIEW_FLOW = `After the run, take the Eyes batch URL printed at the end of the test output and call the MCP tool "eyes_review_progress" with scope "batch" to review the results — it drives the whole investigation and tells you exactly what to inspect next; use mode "resolve" to also accept/reject checkpoints. For raw data instead of a driven review, "eyes_inspect_sessions" lists the batch's sessions and "eyes_inspect_steps" their steps.`;
5259
5250
  function viewingResultsSection(flavor) {
5260
- if (isExperimental()) {
5261
- return flavor === 'project'
5262
- ? `**Viewing Test Results:**
5263
-
5264
- ${REVIEW_FLOW}`
5265
- : `**Viewing UFG Test Results:**
5266
-
5267
- ${REVIEW_FLOW} Every browser/device configured in "browsersInfo" appears as its own session in the batch.`;
5268
- }
5269
5251
  return flavor === 'project'
5270
5252
  ? `**Viewing Test Results:**
5271
5253
 
5272
- You have multiple options for viewing and analyzing Eyes test results:
5273
-
5274
- 1. **Get structured test status data** (RECOMMENDED):
5275
- Use the MCP tool "${TOOL_NAMES.EYES_FETCH_VISUAL_RESULTS}" to fetch complete test results including:
5276
- - Batch name and URL
5277
- - Test name and status (passed/failed/unresolved/new/aborted)
5278
- - Retry attempt number
5279
- - Individual session details
5280
- This tool requires the playwright-report/index.html file to be generated.
5281
-
5282
- 2. **Extract URLs from console output**:
5283
- If the playwright-report/index.html file is not available, Use the MCP tool "${TOOL_NAMES.EYES_GET_BATCH_URL}" to extract batch and session URLs from the Playwright test output.`
5254
+ ${REVIEW_FLOW}`
5284
5255
  : `**Viewing UFG Test Results:**
5285
5256
 
5286
- After running tests with the UFG enabled, you can view results using:
5287
-
5288
- 1. **Get structured test status data** (RECOMMENDED):
5289
- Use the MCP tool "${TOOL_NAMES.EYES_FETCH_VISUAL_RESULTS}" to fetch complete test results for all browsers/devices configured in UFG.
5290
-
5291
- 2. **Extract URLs from console output**:
5292
-
5293
- When the playwright-report/index.html is not available use the MCP tool "${TOOL_NAMES.EYES_GET_BATCH_URL}" to extract batch and session URLs from the test output.`;
5257
+ ${REVIEW_FLOW} Every browser/device configured in "browsersInfo" appears as its own session in the batch.`;
5294
5258
  }
5295
5259
 
5296
- const TILDA_WARNING_MESSAGE$2 = `[CORE REQUIREMENT: URL INTEGRITY] Playwright visual results return URLs ending in ~~. These are not typos. You are strictly forbidden from stripping trailing tildes from these links. Use markdown [Visual Test results](URL with tildes) for links. Output the raw, verbatim URL string exactly as captured from the test output.`;
5297
- const TOOL_NAME$5 = TOOL_NAMES.EYES_SETUP_PROJECT;
5298
- const TOOL_DESCRIPTION$5 = `Get step-by-step instructions to set up a Playwright JS project with Applitools Eyes (Fixtures variant)
5260
+ const TILDA_WARNING_MESSAGE$1 = `[CORE REQUIREMENT: URL INTEGRITY] Playwright visual results return URLs ending in ~~. These are not typos. You are strictly forbidden from stripping trailing tildes from these links. Use markdown [Visual Test results](URL with tildes) for links. Output the raw, verbatim URL string exactly as captured from the test output.`;
5261
+ const TOOL_NAME$2 = TOOL_NAMES.EYES_SETUP_PROJECT;
5262
+ const TOOL_DESCRIPTION$2 = `Get step-by-step instructions to set up a Playwright JS project with Applitools Eyes (Fixtures variant)
5299
5263
 
5300
- ${TILDA_WARNING_MESSAGE$2}`;
5264
+ ${TILDA_WARNING_MESSAGE$1}`;
5301
5265
  const PlaywrightJsSetupProjectInputSchema = commonInputSchema.extend({
5302
5266
  projectName: zod.z.string().optional().describe('Optional project name'),
5303
5267
  apiKey: zod.z.string().optional().describe('Optional API key (will use validated key from session if not provided)'),
@@ -5537,11 +5501,11 @@ You can use the mcp tool "${TOOL_NAMES.EYES_SETUP_UFG}" to accomplish that.`;
5537
5501
  }
5538
5502
 
5539
5503
  const eyesSetupProjectTool = {
5540
- name: TOOL_NAME$5,
5541
- description: TOOL_DESCRIPTION$5,
5504
+ name: TOOL_NAME$2,
5505
+ description: TOOL_DESCRIPTION$2,
5542
5506
  inputSchema: PlaywrightJsSetupProjectClientInputSchema,
5543
5507
  handler: createToolHandler({
5544
- name: TOOL_NAME$5,
5508
+ name: TOOL_NAME$2,
5545
5509
  input: PlaywrightJsSetupProjectInputSchema,
5546
5510
  }, async (params) => {
5547
5511
  const result = await eyesSetupProject(params);
@@ -5556,11 +5520,11 @@ const eyesSetupProjectTool = {
5556
5520
  }),
5557
5521
  };
5558
5522
 
5559
- const TILDA_WARNING_MESSAGE$1 = `[CORE REQUIREMENT: URL INTEGRITY] Playwright visual results return URLs ending in ~~. These are not typos. You are strictly forbidden from stripping trailing tildes from these links. Use markdown [Visual Test results](URL with tildes) for links. Output the raw, verbatim URL string exactly as captured from the test output.`;
5560
- const TOOL_NAME$4 = TOOL_NAMES.EYES_SETUP_UFG;
5561
- const TOOL_DESCRIPTION$4 = `Configure Ultrafast Grid (UFG) for cross-browser and cross-device testing
5523
+ const TILDA_WARNING_MESSAGE = `[CORE REQUIREMENT: URL INTEGRITY] Playwright visual results return URLs ending in ~~. These are not typos. You are strictly forbidden from stripping trailing tildes from these links. Use markdown [Visual Test results](URL with tildes) for links. Output the raw, verbatim URL string exactly as captured from the test output.`;
5524
+ const TOOL_NAME$1 = TOOL_NAMES.EYES_SETUP_UFG;
5525
+ const TOOL_DESCRIPTION$1 = `Configure Ultrafast Grid (UFG) for cross-browser and cross-device testing
5562
5526
 
5563
- ${TILDA_WARNING_MESSAGE$1}`;
5527
+ ${TILDA_WARNING_MESSAGE}`;
5564
5528
  const PlaywrightJsSetupUfgInputSchema = commonInputSchema.extend({
5565
5529
  playwrightConfigPath: zod.z
5566
5530
  .string()
@@ -5632,11 +5596,11 @@ ${viewingResultsSection('ufg')}`;
5632
5596
  }
5633
5597
 
5634
5598
  const eyesSetupUfgTool = {
5635
- name: TOOL_NAME$4,
5636
- description: TOOL_DESCRIPTION$4,
5599
+ name: TOOL_NAME$1,
5600
+ description: TOOL_DESCRIPTION$1,
5637
5601
  inputSchema: PlaywrightJsSetupUfgClientInputSchema,
5638
5602
  handler: createToolHandler({
5639
- name: TOOL_NAME$4,
5603
+ name: TOOL_NAME$1,
5640
5604
  input: PlaywrightJsSetupUfgInputSchema,
5641
5605
  }, async (params) => {
5642
5606
  const result = await eyesSetupUfg(params);
@@ -5651,8 +5615,8 @@ const eyesSetupUfgTool = {
5651
5615
  }),
5652
5616
  };
5653
5617
 
5654
- const TOOL_NAME$3 = TOOL_NAMES.EYES_ADD_CHECKPOINTS;
5655
- const TOOL_DESCRIPTION$3 = 'Setup step: add eyes.check() visual checkpoints to an existing Playwright test file. Edits source, not results.';
5618
+ const TOOL_NAME = TOOL_NAMES.EYES_ADD_CHECKPOINTS;
5619
+ const TOOL_DESCRIPTION = 'Setup step: add eyes.check() visual checkpoints to an existing Playwright test file. Edits source, not results.';
5656
5620
  const PlaywrightJsAddCheckpointsInputSchema = commonInputSchema.extend({
5657
5621
  filePath: zod.z
5658
5622
  .string()
@@ -5850,11 +5814,11 @@ You can use the MCP tool "${TOOL_NAMES.EYES_SETUP_UFG}" to setup the UFG for the
5850
5814
  }
5851
5815
 
5852
5816
  const eyesAddCheckpointsToTestTool = {
5853
- name: TOOL_NAME$3,
5854
- description: TOOL_DESCRIPTION$3,
5817
+ name: TOOL_NAME,
5818
+ description: TOOL_DESCRIPTION,
5855
5819
  inputSchema: PlaywrightJsAddCheckpointsClientInputSchema,
5856
5820
  handler: createToolHandler({
5857
- name: TOOL_NAME$3,
5821
+ name: TOOL_NAME,
5858
5822
  input: PlaywrightJsAddCheckpointsInputSchema,
5859
5823
  }, async (params) => {
5860
5824
  const result = await eyesAddCheckpointsToTest(params);
@@ -5869,1019 +5833,24 @@ const eyesAddCheckpointsToTestTool = {
5869
5833
  }),
5870
5834
  };
5871
5835
 
5872
- /** Get Batch URL from Output Tool */
5873
- const TOOL_NAME$2 = TOOL_NAMES.EYES_GET_BATCH_URL;
5874
- const TOOL_DESCRIPTION$2 = `═══════════════════════════════════════
5875
- 📋 SHOW THIS MESSAGE TO USER AS-IS
5876
- ═══════════════════════════════════════
5877
-
5878
- Extract and convert Eyes test result URLs from console output. Parses the test execution output to find session URLs and converts them to batch URLs for viewing all test results together in the Eyes dashboard. This tool extracts URLs only - use ${TOOL_NAMES.EYES_FETCH_VISUAL_RESULTS} to get detailed test status and results data.`;
5879
- const GetBatchUrlFromOutputInputSchema = zod.z.object({
5880
- testOutput: zod.z.string().describe('The console output from running the Playwright test'),
5881
- workspaceRoot: zod.z.string().optional().describe('Workspace root directory (optional, defaults to current directory)'),
5882
- });
5883
- const BatchUrlToolResultSchema = zod.z.object({
5884
- message: zod.z.string().describe('Human-readable summary of URL extraction results'),
5885
- batchUrls: zod.z
5886
- .array(zod.z.url())
5887
- .nullable()
5888
- .optional()
5889
- .describe('Array of batch URLs for viewing all test results together in the Eyes dashboard. Null if no URLs found.'),
5890
- sessionUrls: zod.z
5891
- .array(zod.z.string({ message: 'CRITICAL: The Session URL with contains ~~ in the end that must be kept in the output' }))
5892
- .nullable()
5893
- .optional()
5894
- .describe('Array of individual session URLs from test output (may end with ~~). Null if no URLs found.'),
5895
- testResults: zod.z.any().optional().describe('Additional test result metadata if available'),
5896
- });
5897
- /**
5898
- * Helper function to get batch URL for a given session
5899
- * This would ideally use the Eyes API, but for now we provide a fallback
5900
- */
5901
- async function getBatchUrlForSession(_sessionId, _accountId) {
5902
- // For now, we'll construct a likely batch URL based on the session URL pattern
5903
- // In a full implementation, you would query the Eyes API to get the actual batch ID
5904
- // The batch URL typically follows this pattern:
5905
- // https://eyes.applitools.com/app/batches/{batchId}?accountId={accountId}~~
5906
- // However, we need the actual batch ID which requires an API call
5907
- throw new Error('Batch URL extraction requires API access. Please use the Playwright HTML report or click the session URL and find the batch link in the dashboard.');
5908
- }
5909
- /**
5910
- * Get batch URL from test console output
5911
- * Extracts Eyes result URLs from test output and converts them to batch URLs
5912
- */
5913
- async function getBatchUrlFromOutput(input) {
5914
- const { testOutput } = input;
5915
- // Extract all Eyes result URLs from the output
5916
- // Pattern: https://eyes.applitools.com/app/test-results/{sessionId}?accountId={accountId}~~
5917
- const urlPattern = /https:\/\/eyes\.applitools\.com\/app\/test-results\/(\d+)\?accountId=([^~\s]+)(~~)?/g;
5918
- const matches = [...testOutput.matchAll(urlPattern)];
5919
- if (matches.length === 0) {
5920
- const result = {
5921
- message: wrapText('No Eyes test result URLs found in the output. Make sure the test has completed and the Eyes reporter is configured correctly.', 'prefix'),
5922
- batchUrls: null,
5923
- sessionUrls: null,
5924
- };
5925
- return BatchUrlToolResultSchema.parse(result);
5926
- }
5927
- const sessionUrls = [];
5928
- const sessionIds = [];
5929
- const accountIds = [];
5930
- matches.forEach(match => {
5931
- const fullUrl = match[0];
5932
- const sessionId = match[1];
5933
- const accountId = match[2];
5934
- sessionUrls.push(fullUrl);
5935
- sessionIds.push(sessionId);
5936
- accountIds.push(accountId);
5937
- });
5938
- // Get batch information from the first session
5939
- // All sessions from the same test run should be in the same batch
5940
- const firstSessionId = sessionIds[0];
5941
- const firstAccountId = accountIds[0];
5942
- try {
5943
- // Try to get batch information from the Eyes API
5944
- // This is a simplified approach - in production, you'd want to use the actual Eyes API
5945
- const batchUrl = await getBatchUrlForSession(firstSessionId, firstAccountId);
5946
- const message = wrapText(`Found ${sessionUrls.length} Eyes test result(s).\n\n` +
5947
- `**Batch URL** (view all results together):\n[View Batch Results](${batchUrl})\n\n` +
5948
- `**Individual Session URLs**:\n${sessionUrls
5949
- .map((url, i) => `${i + 1}. [Session ${i + 1}](${url})`)
5950
- .join('\n')}\n\n` +
5951
- `🚨 **IMPORTANT**: Always use the Batch URL to view all test results together. ` +
5952
- `The batch URL shows all visual checkpoints and tests in a single dashboard view.`, 'prefix');
5953
- const result = {
5954
- message,
5955
- batchUrls: [batchUrl],
5956
- sessionUrls,
5957
- };
5958
- return BatchUrlToolResultSchema.parse(result);
5959
- }
5960
- catch (error) {
5961
- // If we can't get batch info, provide instructions on how to find it
5962
- const message = wrapText(`Found ${sessionUrls.length} Eyes test result(s):\n\n` +
5963
- `${sessionUrls.map((url, i) => `${i + 1}. [Session ${i + 1}](${url})`).join('\n')}\n\n` +
5964
- `**Note**: These are individual session URLs. To view all results together:\n` +
5965
- `1. Click any of the URLs above\n` +
5966
- `2. Look for the "View Batch" or "Batch Results" link in the dashboard\n` +
5967
- `3. Or use the Playwright HTML report by running: \`npx playwright show-report\`\n\n` +
5968
- `Error getting batch URL: ${error instanceof Error ? error.message : String(error)}`, 'prefix');
5969
- const result = {
5970
- message,
5971
- batchUrls: null,
5972
- sessionUrls,
5973
- };
5974
- return BatchUrlToolResultSchema.parse(result);
5975
- }
5976
- }
5977
-
5978
- /** Get Batch URL from Output Tool - MCP Tool Object Export */
5979
- /** MCP Tool Object for get_batch_url */
5980
- const getBatchUrlFromOutputTool = {
5981
- name: TOOL_NAME$2,
5982
- description: TOOL_DESCRIPTION$2,
5983
- inputSchema: GetBatchUrlFromOutputInputSchema,
5984
- outputSchema: BatchUrlToolResultSchema,
5985
- handler: createToolHandler({
5986
- name: TOOL_NAME$2,
5987
- input: GetBatchUrlFromOutputInputSchema,
5988
- output: BatchUrlToolResultSchema,
5989
- }, async (params) => {
5990
- const result = await getBatchUrlFromOutput(params);
5991
- return {
5992
- content: [
5993
- {
5994
- type: 'text',
5995
- text: result.message,
5996
- },
5997
- ],
5998
- structuredContent: result,
5999
- };
6000
- }),
5836
+ const ALL_TOOLS = {
5837
+ verifyApiKey: verifyApiKeyTool,
5838
+ eyesSetupProject: eyesSetupProjectTool,
5839
+ eyesSetupUfg: eyesSetupUfgTool,
5840
+ eyesAddCheckpointsToTest: eyesAddCheckpointsToTestTool,
6001
5841
  };
6002
5842
 
6003
- async function parseReportFile(reportPath) {
6004
- const reportHtml = await promises.readFile(reportPath, 'utf-8');
6005
- const assignmentPattern = /window\.__testResultsMap\s*=\s*/;
6006
- const assignmentMatch = reportHtml.match(assignmentPattern);
6007
- if (!assignmentMatch) {
6008
- throw new Error('No Eyes test results found in the Playwright report');
6009
- }
6010
- const startIndex = assignmentMatch.index + assignmentMatch[0].length;
6011
- // Walk from startIndex to find the closing brace of the root JSON object,
6012
- // correctly skipping braces that appear inside JSON string values.
6013
- // Note: do NOT bound by </script> — that tag can appear verbatim inside a
6014
- // JSON string value (e.g. a test named "close</script>tag"), which would
6015
- // truncate the slice mid-JSON and cause a spurious parse error.
6016
- // The brace walker terminates as soon as depth returns to 0.
6017
- const bounded = reportHtml.slice(startIndex);
6018
- let depth = 0;
6019
- let inStr = false;
6020
- let esc = false;
6021
- let endIdx = -1;
6022
- for (let i = 0; i < bounded.length; i++) {
6023
- const c = bounded[i];
6024
- if (esc) {
6025
- esc = false;
6026
- continue;
6027
- }
6028
- if (c === '\\' && inStr) {
6029
- esc = true;
6030
- continue;
6031
- }
6032
- if (c === '"') {
6033
- inStr = !inStr;
6034
- continue;
6035
- }
6036
- if (!inStr) {
6037
- if (c === '{')
6038
- depth++;
6039
- else if (c === '}' && --depth === 0) {
6040
- endIdx = i;
6041
- break;
6042
- }
6043
- }
6044
- }
6045
- if (endIdx === -1) {
6046
- throw new Error('Malformed JSON: unmatched braces');
6047
- }
6048
- try {
6049
- return JSON.parse(bounded.slice(0, endIdx + 1));
6050
- }
6051
- catch {
6052
- throw new Error('Malformed JSON: invalid structure in test results map');
6053
- }
6054
- }
6055
-
6056
- function fixEyesUrl(url) {
6057
- return url.replace(/eyesapi\./gi, 'eyes.');
6058
- }
6059
- function ensureTrailingSlash(url) {
6060
- return url.endsWith('/') ? url : `${url}/`;
6061
- }
6062
- /**
6063
- * The reusable tool-description fragment that warns the LLM not to strip the
6064
- * trailing `~~` from server-emitted session/batch URLs. The tildes are base64
6065
- * padding inside the accountId value itself (`=` encoded as `~`), so stripping
6066
- * them corrupts the account ID and the server rejects the request.
6067
- */
6068
- const TILDA_URL_WARNING = '[CORE REQUIREMENT: URL INTEGRITY] Visual-results URLs returned by Eyes end with `~~`. ' +
6069
- 'These tildes are part of the account ID token, not typos. You are strictly forbidden from stripping ' +
6070
- 'trailing tildes from these links. Render them with markdown ' +
6071
- '`[Visual Test results](URL with tildes)` and output the raw, verbatim URL.';
6072
- /**
6073
- * Build the canonical Eyes dashboard URL for a single test session.
6074
- *
6075
- * Output shape: `{serverUrl}/app/test-results/{batchId}/{sessionId}[?accountId={accountId}]`
6076
- *
6077
- * Nothing is appended after the accountId: any `~~` in the final URL is base64
6078
- * padding inside the accountId value, which arrives complete from the server.
6079
- *
6080
- * `accountId` is optional because not every caller has one to hand (the
6081
- * batch-results-API flow authenticates by API key alone); pass it whenever
6082
- * the URL was itself derived from a parsed accountId, so review round-trips
6083
- * stay tied to the account they came from.
6084
- */
6085
- function buildSessionUrl$1(serverUrl, batchId, sessionId, accountId) {
6086
- const accountIdQuery = accountId ? `?accountId=${accountId}` : '';
6087
- return `${serverUrl}/app/test-results/${batchId}/${sessionId}${accountIdQuery}`;
6088
- }
6089
- /**
6090
- * Build the canonical Eyes dashboard URL for a whole batch.
6091
- *
6092
- * Output shape: `{serverUrl}/app/test-results/{batchId}[/?accountId={accountId}]`
6093
- */
6094
- function buildBatchUrl$1(serverUrl, batchId, accountId) {
6095
- return accountId
6096
- ? `${serverUrl}/app/test-results/${batchId}/?accountId=${accountId}`
6097
- : `${serverUrl}/app/test-results/${batchId}`;
6098
- }
6099
-
6100
- /**
6101
- * Canonical visual-test status set, shared by every part of the MCP package
6102
- * that produces or consumes a per-test status string.
6103
- *
6104
- * Single source of truth for:
6105
- * - the Zod enum on `VisualTestResultSchema.status`
6106
- * ([[../dtos/visual-results-result.ts]])
6107
- * - the runtime `normalizeStatus()` helper used by `eyes_analyze_batch`
6108
- * ([[../tools/eyes-analyze-batch/tool.ts]]) to coerce arbitrary BE
6109
- * strings into the canonical set
6110
- * - the `STATUS_PRIORITY` ordering used by `eyes_fetch_visual_results`
6111
- * ([[../tools/eyes-fetch-visual-results/batch-processor.ts]]) when it
6112
- * reconciles per-step results into a single test status
6113
- * - the per-status counters in `buildVisualResultsResult`
6114
- * ([[../utils/build-visual-results-result.ts]])
6115
- *
6116
- * Adding a new status: append it to {@link CANONICAL_STATUSES} and the rest
6117
- * of the package picks it up automatically.
6118
- */
6119
- /**
6120
- * Tuple of every status the MCP tools may return on a per-test basis. Keep
6121
- * this as a `readonly` tuple (not a plain array) so we can derive both the
6122
- * Zod enum and the TypeScript union without re-declaring the values.
6123
- */
6124
- const CANONICAL_STATUSES = ['passed', 'failed', 'unresolved', 'new', 'aborted', 'running', 'empty'];
6125
- /** Set form of {@link CANONICAL_STATUSES} for O(1) membership checks. */
6126
- const CANONICAL_STATUS_SET = new Set(CANONICAL_STATUSES);
6127
- /**
6128
- * Reconciliation order for `determineStatus()` in
6129
- * [[../tools/eyes-fetch-visual-results/batch-processor.ts]] — the lowest
6130
- * index wins when multiple statuses are observed for the same test across
6131
- * retries / chunks.
6132
- *
6133
- * Aborted / empty / new are decided by boolean flags before this list is
6134
- * consulted, so they don't appear here.
6135
- */
6136
- const STATUS_PRIORITY = [
6137
- 'running',
6138
- 'passed',
6139
- 'failed',
6140
- 'unresolved',
6141
- ];
6142
- /** Default fallback when an unrecognised status string arrives from the BE. */
6143
- const DEFAULT_UNKNOWN_STATUS = 'unresolved';
6144
- /**
6145
- * Coerce an arbitrary status string from the Eyes BE into the canonical set
6146
- * the MCP tools expose on the wire. Case-insensitive; unknown values fall
6147
- * back to {@link DEFAULT_UNKNOWN_STATUS} so the schema parse never throws on
6148
- * unexpected BE input (forward-compatible with new server-side states).
6149
- */
6150
- function normalizeStatus(status) {
6151
- const lower = status.toLowerCase();
6152
- return CANONICAL_STATUS_SET.has(lower) ? lower : DEFAULT_UNKNOWN_STATUS;
6153
- }
6154
-
6155
- function filterToLastRetry(eyesResults) {
6156
- if (eyesResults.length === 0) {
6157
- return [];
6158
- }
6159
- const maxRetry = Math.max(...eyesResults.map(r => { var _a; return (_a = r.playwrightRetry) !== null && _a !== void 0 ? _a : 0; }));
6160
- return eyesResults.filter(r => { var _a; return ((_a = r.playwrightRetry) !== null && _a !== void 0 ? _a : 0) === maxRetry; });
6161
- }
6162
- function determineStatus(result) {
6163
- if (result.isAborted)
6164
- return 'aborted';
6165
- if (result.steps === 0)
6166
- return 'empty';
6167
- const status = result.status.toLowerCase();
6168
- if (result.isNew && status !== 'running')
6169
- return 'new';
6170
- if (STATUS_PRIORITY.includes(status))
6171
- return status;
6172
- return 'unresolved';
6173
- }
6174
- async function fetchBatchStatus(batchId, batchData) {
6175
- const chunkSize = 300;
6176
- const chunks = [];
6177
- for (let i = 0; i < batchData.sessions.length; i += chunkSize) {
6178
- chunks.push(batchData.sessions.slice(i, i + chunkSize));
6179
- }
6180
- const baseUrl = ensureTrailingSlash(fixEyesUrl(batchData.eyesServerUrl));
6181
- const apiClient = new ApiClient({
6182
- baseUrl: baseUrl.replace(/\/$/, ''),
6183
- apiKey: batchData.apiKey,
6184
- timeout: 30000,
6185
- });
6186
- try {
6187
- const results = await Promise.all(chunks.map(async (chunk) => {
6188
- try {
6189
- const response = await apiClient.post(`api/sessions/batches/${batchId}/sessions/sdkquery`, { sessions: chunk });
6190
- return response;
6191
- }
6192
- catch {
6193
- return { sessions: [], errors: [] };
6194
- }
6195
- }));
6196
- return {
6197
- sessions: results.map(result => result.sessions).flat(),
6198
- errors: results.map(result => result.errors).flat(),
6199
- };
6200
- }
6201
- catch {
6202
- return { sessions: [], errors: [] };
6203
- }
6204
- }
6205
- async function processBatches(testResultsData, fallbackApiKey) {
6206
- const sessionsByBatchId = new Map();
6207
- const eyesResultsByBatch = new Map();
6208
- Object.values(testResultsData).forEach(results => {
6209
- if (Array.isArray(results)) {
6210
- const lastRetryResults = filterToLastRetry(results);
6211
- lastRetryResults.forEach(result => {
6212
- const batchId = result.batchId;
6213
- if (!eyesResultsByBatch.has(batchId)) {
6214
- eyesResultsByBatch.set(batchId, []);
6215
- }
6216
- eyesResultsByBatch.get(batchId).push(result);
6217
- if (!sessionsByBatchId.has(batchId)) {
6218
- sessionsByBatchId.set(batchId, {
6219
- batchName: result.batchName,
6220
- batchUrl: result.appUrls.batch,
6221
- sessions: [],
6222
- apiKey: result.eyesServer.apiKey,
6223
- eyesServerUrl: result.eyesServer.eyesServerUrl,
6224
- });
6225
- }
6226
- const batchData = sessionsByBatchId.get(batchId);
6227
- batchData.sessions.push({
6228
- id: result.id,
6229
- accessToken: result.secretToken,
6230
- });
6231
- });
6232
- }
6233
- });
6234
- if (sessionsByBatchId.size === 0) {
6235
- return [];
6236
- }
6237
- const batchStatusPromises = Array.from(sessionsByBatchId.entries()).map(async ([batchId, batchData]) => {
6238
- const effectiveApiKey = batchData.apiKey || fallbackApiKey;
6239
- const effectiveBatchData = effectiveApiKey ? { ...batchData, apiKey: effectiveApiKey } : batchData;
6240
- const serverResponse = await fetchBatchStatus(batchId, effectiveBatchData);
6241
- return { batchId, serverResponse };
6242
- });
6243
- const batchStatuses = await Promise.all(batchStatusPromises);
6244
- const statusBySessionId = new Map();
6245
- batchStatuses.forEach(({ serverResponse }) => {
6246
- serverResponse.sessions.forEach(session => {
6247
- statusBySessionId.set(session.id, session);
6248
- });
6249
- });
6250
- const processedBatches = [];
6251
- eyesResultsByBatch.forEach((eyesResults, batchId) => {
6252
- const batchData = sessionsByBatchId.get(batchId);
6253
- const tests = [];
6254
- eyesResults.forEach(result => {
6255
- var _a;
6256
- const serverStatus = statusBySessionId.get(result.id);
6257
- if (serverStatus) {
6258
- result.status = serverStatus.status;
6259
- result.isDifferent = serverStatus.isDifferent;
6260
- result.isNew = serverStatus.isNew;
6261
- result.isAborted = serverStatus.isAborted;
6262
- }
6263
- const finalStatus = determineStatus(result);
6264
- // Extract diff descriptions from actualAppOutput
6265
- const stepDiffs = [];
6266
- if (serverStatus === null || serverStatus === void 0 ? void 0 : serverStatus.actualAppOutput) {
6267
- serverStatus.actualAppOutput.forEach((output, index) => {
6268
- if (output.diffDescriptions && output.diffDescriptions.length > 0) {
6269
- stepDiffs.push({
6270
- stepIndex: index,
6271
- stepName: output.tag || `Step ${index + 1}`,
6272
- diffDescriptions: output.diffDescriptions,
6273
- });
6274
- }
6275
- });
6276
- }
6277
- tests.push({
6278
- testName: result.name,
6279
- batchName: result.batchName,
6280
- status: finalStatus,
6281
- sessionUrl: result.appUrls.session,
6282
- steps: result.steps,
6283
- retryAttempt: (_a = result.playwrightRetry) !== null && _a !== void 0 ? _a : 0,
6284
- browser: result.hostApp,
6285
- ...(stepDiffs.length > 0 ? { stepDiffs } : {}),
6286
- });
6287
- });
6288
- processedBatches.push({
6289
- batchId,
6290
- batchName: batchData.batchName,
6291
- batchUrl: batchData.batchUrl,
6292
- tests,
6293
- });
6294
- });
6295
- return processedBatches;
6296
- }
6297
-
6298
- /**
6299
- * Tool-agnostic builder that turns an array of `ProcessedBatch` into the
6300
- * `VisualResultsToolResult` shape (message + structured results + summary).
6301
- *
6302
- * Used by both `eyes_fetch_visual_results` and `eyes_analyze_batch` so they
6303
- * produce identical output structures from different upstream sources.
6304
- */
6305
- function calculateSummary(batches) {
6306
- let totalTests = 0;
6307
- let passed = 0;
6308
- let failed = 0;
6309
- let unresolved = 0;
6310
- let newTests = 0;
6311
- let aborted = 0;
6312
- batches.forEach(batch => {
6313
- batch.tests.forEach(test => {
6314
- totalTests++;
6315
- if (test.status === 'passed')
6316
- passed++;
6317
- else if (test.status === 'failed')
6318
- failed++;
6319
- else if (test.status === 'unresolved')
6320
- unresolved++;
6321
- else if (test.status === 'new')
6322
- newTests++;
6323
- else if (test.status === 'aborted')
6324
- aborted++;
6325
- });
6326
- });
6327
- return {
6328
- totalBatches: batches.length,
6329
- totalTests,
6330
- passed,
6331
- failed,
6332
- unresolved,
6333
- new: newTests,
6334
- aborted,
6335
- };
6336
- }
6337
- // Textual diff descriptions are temporarily disabled because they interfere
6338
- // with the eyes-inspect skill. Re-enable by restoring the original body of
6339
- // this function and the stepDiffs propagation in buildVisualResultsResult.
6340
- function formatDiffDescriptions(_test) {
6341
- return '';
6342
- }
6343
- function formatMessage(batches, summary) {
6344
- return wrapText(`✅ Fetched visual test results from ${batches.length} batch(es):\n\n` +
6345
- `**Summary:**\n` +
6346
- `- Total Tests: ${summary.totalTests}\n` +
6347
- `- Passed: ${summary.passed}\n` +
6348
- `- Failed: ${summary.failed}\n` +
6349
- `- Unresolved: ${summary.unresolved}\n` +
6350
- `- New: ${summary.new}\n` +
6351
- `- Aborted: ${summary.aborted}\n\n` +
6352
- batches
6353
- .map((batch, i) => {
6354
- const testsWithDiffs = batch.tests.filter(t => t.stepDiffs && t.stepDiffs.length > 0);
6355
- const testLines = testsWithDiffs
6356
- .map(t => ` - **${t.testName}** (${t.browser}) — ${t.status}${formatDiffDescriptions()}`)
6357
- .join('\n');
6358
- return (`**Batch ${i + 1}: ${batch.batchName}**\n` +
6359
- `- [View Batch](${batch.batchUrl})\n` +
6360
- `- Tests: ${batch.tests.length}\n` +
6361
- (testLines ? `- Tests with visual differences:\n${testLines}\n` : ''));
6362
- })
6363
- .join('\n'), 'prefix');
6364
- }
6365
- function buildVisualResultsResult(batches) {
6366
- const summary = calculateSummary(batches);
6367
- const results = batches.map(batch => ({
6368
- batchId: batch.batchId,
6369
- batchName: batch.batchName,
6370
- batchUrl: batch.batchUrl,
6371
- tests: batch.tests.map(test => ({
6372
- testName: test.testName,
6373
- batchName: test.batchName,
6374
- status: test.status,
6375
- sessionUrl: test.sessionUrl,
6376
- steps: test.steps,
6377
- retryAttempt: test.retryAttempt,
6378
- browser: test.browser,
6379
- // stepDiffs intentionally omitted while textual diff descriptions are disabled
6380
- })),
6381
- }));
6382
- const message = formatMessage(results, summary);
6383
- return {
6384
- message,
6385
- results,
6386
- summary: {
6387
- totalBatches: summary.totalBatches,
6388
- totalTests: summary.totalTests,
6389
- passed: summary.passed,
6390
- failed: summary.failed,
6391
- unresolved: summary.unresolved,
6392
- new: summary.new,
6393
- aborted: summary.aborted,
6394
- },
5843
+ const workspaceRootSchema = zod.z
5844
+ .string()
5845
+ .optional()
5846
+ .describe("Root directory of the caller's project (optional; used to locate its .env credentials)");
5847
+ function instrumentedRegistrar(server) {
5848
+ const registerTool = (name, config, handler) => {
5849
+ const inputSchema = { workspaceRoot: workspaceRootSchema, ...config.inputSchema };
5850
+ const wrapped = createToolHandler({ name, input: zod.z.object(inputSchema) }, async (params) => handler(params).then(result => result));
5851
+ return server.registerTool(name, { ...config, inputSchema }, wrapped);
6395
5852
  };
6396
- }
6397
-
6398
- /**
6399
- * Shared Zod schemas describing the "visual results" tool output shape.
6400
- *
6401
- * Both `eyes_fetch_visual_results` (Playwright report flow) and
6402
- * `eyes_analyze_batch` (paste-batch-URL flow) return data in this shape, so
6403
- * the schemas live here rather than inside either tool. Each tool re-exports
6404
- * them under tool-specific aliases for stable public names.
6405
- */
6406
- const DiffDescriptionSchema = zod.z.object({
6407
- baselineValue: zod.z.string().describe('Original value from the baseline snapshot'),
6408
- checkpointValue: zod.z.string().describe('New value from the checkpoint snapshot'),
6409
- category: zod.z
6410
- .string()
6411
- .describe('Diff category code emitted by the Eyes BE. Canonical set: ' +
6412
- '"ContentTextShort" (text changed ≤10 words), ' +
6413
- '"ContentTextLong" (text changed >10 words), ' +
6414
- '"FontColor" (font foreground color), ' +
6415
- '"FontSize" (font size), ' +
6416
- '"FontFamily" (font family), ' +
6417
- '"FontStyle" (bold / italic / underline), ' +
6418
- '"BackgroundColor" (element background color), ' +
6419
- '"BorderStyle" (border style / color / width), ' +
6420
- '"GraphicChanged" (image / icon / SVG content). ' +
6421
- 'New BE-side categories are passed through verbatim.'),
6422
- });
6423
- const StepDiffSchema = zod.z.object({
6424
- stepIndex: zod.z.number().describe('Zero-based index of the step within the test'),
6425
- stepName: zod.z.string().describe('Name/label of the visual checkpoint'),
6426
- diffDescriptions: zod.z
6427
- .array(DiffDescriptionSchema)
6428
- .describe('List of textual descriptions of visual differences detected in this step'),
6429
- });
6430
- const VisualTestResultSchema = zod.z.object({
6431
- testName: zod.z.string().describe('Name of the visual test'),
6432
- batchName: zod.z.string().describe('Name of the batch this test belongs to'),
6433
- status: zod.z
6434
- .enum(CANONICAL_STATUSES)
6435
- .describe('Visual test status: "passed" - all checkpoints match baseline, ' +
6436
- '"failed" - visual differences detected, ' +
6437
- '"unresolved" - differences need review, ' +
6438
- '"new" - first-time checkpoint with no baseline, ' +
6439
- '"aborted" - test terminated prematurely, ' +
6440
- '"running" - test still executing, ' +
6441
- '"empty" - test completed with zero checkpoints.'),
6442
- sessionUrl: zod.z
6443
- .string()
6444
- .describe('URL to the visual test results in the Eyes dashboard. Any trailing `~~` is base64 ' +
6445
- 'padding inside the accountId value — part of the account ID token, not typos. ' +
6446
- 'Do not strip it.'),
6447
- steps: zod.z.number().describe('Number of visual checkpoints in this test'),
6448
- retryAttempt: zod.z.number().describe('Retry attempt number (0 for first attempt)'),
6449
- browser: zod.z.string().describe('Browser/device configuration this test ran on'),
6450
- stepDiffs: zod.z
6451
- .array(StepDiffSchema)
6452
- .optional()
6453
- .describe('Textual descriptions of visual differences for steps with diffs. Only present for tests where DOM-based diff analysis detected categorized differences.'),
6454
- });
6455
- const BatchResultSchema = zod.z.object({
6456
- // batchId/batchUrl are intentionally part of the public response shape:
6457
- // - `batchId` is the stable identifier the LLM/agent uses to correlate
6458
- // this result with prior tool calls (e.g. the stale-report check in
6459
- // `eyes_fetch_visual_results` reads `batchId` to verify expected vs
6460
- // observed batches) and to disambiguate multiple batches in one run.
6461
- // - `batchUrl` is rendered as a `[View Batch]` link in the human message
6462
- // and is what the user clicks to open the dashboard.
6463
- // Removing either would force every consumer to reconstruct the URL from
6464
- // the server URL + ID, so they stay.
6465
- batchId: zod.z
6466
- .string()
6467
- .describe('Stable batch identifier; used by clients to correlate, deduplicate, and detect stale reports.'),
6468
- batchName: zod.z.string().describe('Human-readable batch label as shown in the Eyes dashboard.'),
6469
- batchUrl: zod.z.string().describe('Full Eyes dashboard URL for this batch; rendered as a `[View Batch]` link.'),
6470
- tests: zod.z.array(VisualTestResultSchema).describe('All visual tests within this batch'),
6471
- });
6472
- const VisualResultsToolResultSchema = zod.z.object({
6473
- message: zod.z.string().describe('Human-readable summary of the visual test results'),
6474
- results: zod.z.array(BatchResultSchema).optional().describe('Detailed results grouped by batch'),
6475
- summary: zod.z
6476
- .object({
6477
- totalBatches: zod.z.number().describe('Total number of batches'),
6478
- totalTests: zod.z.number().describe('Total number of visual tests across all batches'),
6479
- passed: zod.z
6480
- .number()
6481
- .describe('Number of tests where all visual checkpoints matched the baseline (no differences detected)'),
6482
- failed: zod.z.number().describe('Number of tests with visual differences that were marked as failures after review'),
6483
- unresolved: zod.z
6484
- .number()
6485
- .describe('Number of tests with visual differences that require human review and acceptance/rejection'),
6486
- new: zod.z
6487
- .number()
6488
- .describe('Number of tests running for the first time with no existing baseline to compare against'),
6489
- aborted: zod.z.number().describe('Number of tests that were terminated prematurely before completion'),
6490
- })
6491
- .optional()
6492
- .describe('Aggregated statistics summarizing test results across all batches. Counts tests by their visual comparison status.'),
6493
- });
6494
-
6495
- // Shared with `eyes_analyze_batch` so the wording (and the underlying URL
6496
- // convention) stays in lock-step. See TILDA_URL_WARNING in url-utils.
6497
- const TILDA_WARNING_MESSAGE = TILDA_URL_WARNING;
6498
- const TOOL_NAME$1 = TOOL_NAMES.EYES_FETCH_VISUAL_RESULTS;
6499
- const TOOL_DESCRIPTION$1 = `Fetch current up-to-date visual test results from the Playwright HTML report and the Eyes server.
6500
-
6501
- IMPORTANT:
6502
- - This tool reads the Playwright HTML report directly from disk.
6503
- - **Do NOT copy or move the report file.** Instead, always point this tool to the actual report location using the \`reportPath\` argument when it's not in the default location.
6504
- - For standard Playwright runs, the default report is at \`playwright-report/index.html\` in the workspace root.
6505
- - For the Eyes example (\`npx eyes-setup run-example\`), the report is generated at:
6506
- \`<workspaceRoot>/eyes-examples/eyes-playwright-report/index.html\`
6507
- In that case, call the tool with:
6508
- - \`reportPath: "<workspaceRoot>/eyes-examples/eyes-playwright-report/index.html"\`
6509
- - \`workspaceRoot: "<workspaceRoot>"\`
6510
-
6511
- **CRITICAL: Do NOT run Playwright with \`--reporter=list\`, \`--reporter=dot\`, \`--reporter=line\`, or any other \`--reporter\` flag that overrides the configured reporters. Doing so suppresses the Eyes reporter, preventing it from writing results to the HTML report. This tool will then read a stale report from a previous run and return outdated results.**
6512
-
6513
- Always run Playwright without reporter overrides, for example:
6514
- - ✅ CORRECT: \`npx playwright test\`
6515
- - ❌ INCORRECT: \`npx playwright test --reporter=list\`
6516
-
6517
- **Stale report detection (optional):** If you know the batch IDs from the current Playwright run output, pass them via the \`expectedBatchIds\` parameter. This tool will warn you if those batch IDs are not found in the report, indicating the report may be from a previous run.
6518
-
6519
- The tool returns structured test results that can be displayed in a table, including:
6520
- - Test name
6521
- - Visual test status (passed/failed/unresolved/new/aborted)
6522
- - Retry attempt number
6523
- - Browser/device configuration
6524
-
6525
- ${TILDA_WARNING_MESSAGE}`;
6526
- const PlaywrightFetchVisualResultsInputSchema = commonInputSchema.extend({
6527
- reportPath: zod.z
6528
- .string()
6529
- .optional()
6530
- .describe('Path to the Playwright HTML report (optional, defaults to playwright-report/index.html)'),
6531
- serverUrl: zod.z.string().optional().describe('Optional Applitools server URL (defaults to https://eyes.applitools.com)'),
6532
- expectedBatchIds: zod.z
6533
- .array(zod.z.string())
6534
- .optional()
6535
- .describe('Optional list of batch IDs extracted from the Playwright run output. When provided, the tool verifies these IDs appear in the report to confirm it is current and not stale from a previous run.'),
6536
- });
6537
- const PlaywrightFetchVisualResultsClientInputSchema = createClientInputSchema(PlaywrightFetchVisualResultsInputSchema);
6538
- function buildStaleReportWarning(expectedBatchIds, processedBatches) {
6539
- const reportBatchIds = new Set(processedBatches.map(b => b.batchId));
6540
- const missingBatchIds = expectedBatchIds.filter(id => !reportBatchIds.has(id));
6541
- if (missingBatchIds.length === 0)
6542
- return '';
6543
- return (`⚠️ STALE REPORT WARNING: The following batch IDs from the Playwright run were NOT found in the report: [${missingBatchIds.join(', ')}]. ` +
6544
- `The report likely reflects a previous run, not the current one.\n` +
6545
- `To fix this: re-run Playwright WITHOUT any --reporter flag overrides (e.g. npx playwright test), then call this tool again.\n\n`);
6546
- }
6547
- /**
6548
- * Main tool function to fetch visual test results
6549
- */
6550
- async function playwrightFetchVisualResults(input) {
6551
- const { workspaceRoot, warning } = validateCommonInput(input);
6552
- const reportPath = input.reportPath || path.join(workspaceRoot, 'playwright-report', 'index.html');
6553
- try {
6554
- // Step 1: Parse report file to extract test results
6555
- let testResultsData;
6556
- try {
6557
- testResultsData = await parseReportFile(reportPath);
6558
- }
6559
- catch (parseError) {
6560
- if (parseError instanceof Error && parseError.message.includes('No Eyes test results found')) {
6561
- const result = {
6562
- message: wrapText(`${warning}No Eyes test results found in the Playwright report.\n\n` +
6563
- `Make sure:\n` +
6564
- `1. The Eyes Playwright reporter is configured: ['@applitools/eyes-playwright/reporter']\n` +
6565
- `2. Tests are using the Eyes fixture: import { test } from '@applitools/eyes-playwright/fixture'\n` +
6566
- `3. Visual checkpoints are added: await eyes.check('label')`, 'prefix'),
6567
- };
6568
- return VisualResultsToolResultSchema.parse(result);
6569
- }
6570
- throw parseError;
6571
- }
6572
- // Step 2: Get API key from session or config
6573
- const apiKey = getLastValidatedApiKey() || loadCredentials(workspaceRoot).apiKey;
6574
- // Step 3: Process batches (filter, group, fetch status, resolve)
6575
- const processedBatches = await processBatches(testResultsData, apiKey);
6576
- // Check if we have any results to process
6577
- if (processedBatches.length === 0) {
6578
- const result = {
6579
- message: wrapText(`${warning}Found Eyes test results but no sessions to query.\n\n` +
6580
- `This can happen if tests haven't completed yet.`, 'prefix'),
6581
- };
6582
- return VisualResultsToolResultSchema.parse(result);
6583
- }
6584
- // Step 4: Build final response
6585
- const result = buildVisualResultsResult(processedBatches);
6586
- if (warning)
6587
- result.message = warning + result.message;
6588
- // Step 5: Optionally verify expected batch IDs to detect stale reports
6589
- if (input.expectedBatchIds && input.expectedBatchIds.length > 0) {
6590
- const staleWarning = buildStaleReportWarning(input.expectedBatchIds, processedBatches);
6591
- if (staleWarning)
6592
- result.message = staleWarning + result.message;
6593
- }
6594
- return VisualResultsToolResultSchema.parse(result);
6595
- }
6596
- catch (error) {
6597
- // Handle file read errors
6598
- if (error instanceof Error && error.message.includes('ENOENT')) {
6599
- const result = {
6600
- message: wrapText(`${warning}Error reading Playwright report: ${error.message}\n\n` +
6601
- `Make sure the report exists at: ${reportPath}`, 'prefix'),
6602
- };
6603
- return VisualResultsToolResultSchema.parse(result);
6604
- }
6605
- // Handle parsing errors
6606
- if (error instanceof Error && error.message.includes('Malformed JSON')) {
6607
- const result = {
6608
- message: wrapText(`${warning}Error parsing Eyes test results from report: ${error.message}`, 'prefix'),
6609
- };
6610
- return VisualResultsToolResultSchema.parse(result);
6611
- }
6612
- // Generic error handling
6613
- const result = {
6614
- message: wrapText(`${warning}Error processing visual test results: ${error instanceof Error ? error.message : String(error)}`, 'prefix'),
6615
- };
6616
- return VisualResultsToolResultSchema.parse(result);
6617
- }
6618
- }
6619
-
6620
- const playwrightFetchVisualResultsTool = {
6621
- name: TOOL_NAME$1,
6622
- description: TOOL_DESCRIPTION$1,
6623
- inputSchema: PlaywrightFetchVisualResultsClientInputSchema,
6624
- outputSchema: VisualResultsToolResultSchema,
6625
- handler: createToolHandler({
6626
- name: TOOL_NAME$1,
6627
- input: PlaywrightFetchVisualResultsInputSchema,
6628
- output: VisualResultsToolResultSchema,
6629
- }, async (params) => {
6630
- const result = await playwrightFetchVisualResults(params);
6631
- return {
6632
- content: [
6633
- {
6634
- type: 'text',
6635
- text: result.message,
6636
- },
6637
- ],
6638
- structuredContent: result,
6639
- };
6640
- }),
6641
- };
6642
-
6643
- /**
6644
- * API client for the "Paste Batch URL" flow (AD-13206 Part 2).
6645
- *
6646
- * Uses two public v1 API endpoints:
6647
- * 1. GET /api/v1/batches/{batchId}?steps=true — batch results with step-level diffs count
6648
- * 2. GET /api/v1/batches/{batchId}/{sessionId}/{stepIndex}/diff — per-step diff descriptions
6649
- *
6650
- * Both authenticate with `X-Eyes-Api-Key` header only (no session tokens required).
6651
- * Delegates HTTP concerns (retry, auth headers, timeouts) to the shared `ApiClient`.
6652
- *
6653
- * ## Concurrency cap (vs. pagination / throttling)
6654
- *
6655
- * The fan-out helper {@link fetchStepDiffsWithCap} caps the number of
6656
- * **simultaneous in-flight** per-step `/diff` requests at
6657
- * {@link DEFAULT_STEP_DIFF_CONCURRENCY} (10 by default). It is **not**:
6658
- *
6659
- * - **Pagination.** The Eyes BE returns the full diff for one
6660
- * `(batchId, sessionId, stepIndex)` in one response — there is no page
6661
- * cursor, no `nextPage`, no partial result; `stepIndex` is an identity
6662
- * coordinate, not an offset. We always issue exactly one request per
6663
- * step that has diffs and the BE never asks us to ask again.
6664
- * - **Server-side throttling.** The Eyes BE does not advertise a per-key
6665
- * concurrency budget for these endpoints; the cap is purely client-side
6666
- * courtesy so that batches with hundreds of failing steps don't open
6667
- * hundreds of sockets at once. Real throttling (HTTP 429) is handled
6668
- * transparently by the shared `ApiClient` retry policy.
6669
- *
6670
- * In other words: we always request "all the data in one go", but we drip
6671
- * the requests through a fixed-size worker pool.
6672
- */
6673
- // ─── URL helpers ─────────────────────────────────────────────────────────────
6674
- // Unlike eyes-results' own BATCH_PATH: single capture, and `\s` excluded so the id can be
6675
- // plucked out of surrounding console text, not only out of a well-formed URL.
6676
- const BATCH_ID_PATTERN = new RegExp(`${BATCH_ROUTE_PREFIX_SOURCE}([^/?#\\s]+)`);
6677
- /**
6678
- * Extract a batch ID from a full Applitools dashboard URL or return the value
6679
- * as-is if it already looks like a plain batch ID.
6680
- *
6681
- * The regex anchors on either dashboard path prefix — `/app/test-results/` and the
6682
- * `/app/batches/` form the Eyes server returns as a run's own session URL — and captures
6683
- * everything up to the next `/`, `?`, `#`, or whitespace, so deep links into a specific
6684
- * session/step inside the batch resolve to the **batch ID** — not the
6685
- * session ID — which is what every downstream API call expects.
6686
- *
6687
- * Examples:
6688
- * https://eyes.applitools.com/app/test-results/00000251626130890241 → 00000251626130890241
6689
- * https://eyes.applitools.com/app/test-results/00000251626130890241?some=param → 00000251626130890241
6690
- * https://eyes.applitools.com/app/test-results/00000251626130890241#anchor → 00000251626130890241
6691
- * https://eyes.applitools.com/app/test-results/00000251626130890241/00000251626130890242 → 00000251626130890241
6692
- * https://eyes.applitools.com/app/test-results/00000251626130890241/00000251626130890242/other → 00000251626130890241
6693
- * https://eyes.applitools.com/app/batches/00000251626130890241/00000251626130890242 → 00000251626130890241
6694
- * 00000251626130890241 → 00000251626130890241 (passthrough)
6695
- */
6696
- function extractBatchId(urlOrId) {
6697
- const match = urlOrId.match(BATCH_ID_PATTERN);
6698
- if (match)
6699
- return match[1];
6700
- return urlOrId.trim();
6701
- }
6702
- /**
6703
- * Extract the Eyes server base URL from an Applitools batch URL.
6704
- * Falls back to the defaultUrl if the input is not a valid URL.
6705
- *
6706
- * Example: https://eyes.applitools.com/app/test-results/... → https://eyes.applitools.com
6707
- */
6708
- function extractServerUrl(urlOrId, defaultUrl = 'https://eyes.applitools.com') {
6709
- try {
6710
- const parsed = new URL(urlOrId);
6711
- return `${parsed.protocol}//${parsed.host}`;
6712
- }
6713
- catch {
6714
- return defaultUrl;
6715
- }
6716
- }
6717
- // ─── Batch Results API ────────────────────────────────────────────────────────
6718
- /** Sentinel for a 404 from the Batch Results API — the batch ID does not exist. */
6719
- class BatchNotFoundError extends Error {
6720
- constructor(batchId) {
6721
- super(`Batch not found: ${batchId}`);
6722
- this.batchId = batchId;
6723
- this.name = 'BatchNotFoundError';
6724
- }
6725
- }
6726
- /**
6727
- * Fetch batch results from the public Batch Results API.
6728
- *
6729
- * Returns step-level data including `diffDescriptionsCount` per step. Throws
6730
- * `InvalidApiKeyError` on 401 (via the shared client) and `BatchNotFoundError`
6731
- * on 404 so the calling tool can render actionable messages.
6732
- */
6733
- async function fetchBatchResults(batchId, apiKey, serverUrl) {
6734
- const client = new ApiClient({ baseUrl: serverUrl, apiKey });
6735
- const res = await client.getRaw(`api/v1/batches/${batchId}?steps=true`);
6736
- if (res.status === 404)
6737
- throw new BatchNotFoundError(batchId);
6738
- if (!res.ok)
6739
- throw new Error(`HTTP ${res.status}: ${res.statusText}`);
6740
- return (await res.json());
6741
- }
6742
- // ─── Per-step diff API ────────────────────────────────────────────────────────
6743
- /**
6744
- * Fetch and deduplicate diff descriptions for a single step.
6745
- *
6746
- * Returns an empty array when:
6747
- * - The step has no diffs (204 No Content)
6748
- * - The request fails for any reason (graceful degradation)
6749
- *
6750
- * Deduplicates diff descriptions across pixel regions, since the same logical
6751
- * difference can appear in multiple diff regions in the response.
6752
- */
6753
- async function fetchStepDiff(client, batchId,
6754
- /** In the Eyes API, testId and sessionId refer to the same entity. The Batch Results API calls it testId; this endpoint calls it sessionId. */
6755
- sessionId, stepIndex) {
6756
- var _a;
6757
- try {
6758
- const res = await client.getRaw(`api/v1/batches/${batchId}/${sessionId}/${stepIndex}/diff`);
6759
- // 204 = matching step (no diffs)
6760
- if (res.status === 204)
6761
- return [];
6762
- if (!res.ok)
6763
- return [];
6764
- const data = (await res.json());
6765
- return deduplicateDiffDescriptions((_a = data.image1) !== null && _a !== void 0 ? _a : []);
6766
- }
6767
- catch (err) {
6768
- // Surface auth errors loudly so the user sees "invalid API key" instead of
6769
- // an empty diff list for every step. Everything else degrades gracefully
6770
- // — one flaky per-step request must not fail the whole tool.
6771
- if (err instanceof InvalidApiKeyError || err instanceof MissingApiKeyError) {
6772
- throw err;
6773
- }
6774
- return [];
6775
- }
6776
- }
6777
- /**
6778
- * Default ceiling on concurrent in-flight `/diff` requests. See the
6779
- * "Concurrency cap" section at the top of the file for the rationale and
6780
- * for why this is a client-side fan-out limit, not server pagination.
6781
- */
6782
- const DEFAULT_STEP_DIFF_CONCURRENCY = 10;
6783
- /**
6784
- * Fetch per-step diffs for every step in `tasks`, in one go, but with a
6785
- * client-side concurrency cap so we don't open one socket per step on big
6786
- * failing batches. Results are returned in the same order as `tasks`.
6787
- *
6788
- * Important non-features (so reviewers don't have to ask):
6789
- * - `stepIndex` is an **identity** coordinate, not a pagination cursor;
6790
- * each `(batchId, sessionId, stepIndex)` returns a complete diff in
6791
- * one shot.
6792
- * - The cap is purely client-side. Real throttling (HTTP 429) is handled
6793
- * by `ApiClient`'s retry policy; this function only limits how many
6794
- * requests are awaited concurrently.
6795
- * - A single `ApiClient` is shared across all fan-out calls so retry
6796
- * config, auth headers, and connection state are reused.
6797
- */
6798
- async function fetchStepDiffsWithCap(tasks, apiKey, serverUrl, concurrencyLimit = DEFAULT_STEP_DIFF_CONCURRENCY) {
6799
- const client = new ApiClient({ baseUrl: serverUrl, apiKey });
6800
- const results = new Array(tasks.length);
6801
- let cursor = 0;
6802
- async function processNext() {
6803
- while (cursor < tasks.length) {
6804
- const index = cursor++;
6805
- const t = tasks[index];
6806
- results[index] = await fetchStepDiff(client, t.batchId, t.sessionId, t.stepIndex);
6807
- }
6808
- }
6809
- const workers = Array.from({ length: Math.min(concurrencyLimit, tasks.length) }, processNext);
6810
- await Promise.all(workers);
6811
- return results;
6812
- }
6813
- // ─── Helpers ──────────────────────────────────────────────────────────────────
6814
- /**
6815
- * Deduplicate diff descriptions across pixel diff regions.
6816
- *
6817
- * The per-step diff API can return the same logical difference (e.g. "text
6818
- * changed") in multiple pixel regions of the image. This function collapses
6819
- * them to unique `(baselineValue, checkpointValue, category)` tuples.
6820
- */
6821
- function deduplicateDiffDescriptions(regions) {
6822
- var _a;
6823
- const seen = new Set();
6824
- const result = [];
6825
- for (const region of regions) {
6826
- for (const desc of (_a = region.diffDescriptions) !== null && _a !== void 0 ? _a : []) {
6827
- const key = `${desc.baselineValue}|||${desc.checkpointValue}|||${desc.category}`;
6828
- if (!seen.has(key)) {
6829
- seen.add(key);
6830
- result.push({
6831
- baselineValue: desc.baselineValue,
6832
- checkpointValue: desc.checkpointValue,
6833
- category: desc.category,
6834
- });
6835
- }
6836
- }
6837
- }
6838
- return result;
6839
- }
6840
-
6841
- /**
6842
- * Translate auth/transport errors thrown by `ApiClient` into actionable,
6843
- * user-facing wording shared between every MCP tool that talks to the Eyes
6844
- * server.
6845
- *
6846
- * Keeping this in one place means a wording change (or a new error class
6847
- * like {@link InvalidApiKeyError}) is reflected everywhere automatically;
6848
- * tools only have to add their own specialised cases (e.g. `BatchNotFoundError`
6849
- * in `eyes_analyze_batch`) before falling through to {@link formatApiFetchError}.
6850
- */
6851
- /**
6852
- * Default, generic prefix used when the error has no recognised type. Tools
6853
- * may override it via the `genericPrefix` option to add tool-specific
6854
- * context (e.g. "Failed to fetch batch results: ...").
6855
- */
6856
- const DEFAULT_GENERIC_PREFIX = 'Eyes server request failed: ';
6857
- /**
6858
- * Map an unknown error thrown by an `ApiClient` call to a single-string
6859
- * message suitable for `wrapText()`-rendered tool output.
6860
- *
6861
- * Recognised cases:
6862
- * - {@link InvalidApiKeyError}: tells the user to call the `eyes_verify_api_key`
6863
- * MCP tool again, or set `APPLITOOLS_API_KEY`.
6864
- * - {@link MissingApiKeyError}: same remediation, different opening.
6865
- * - Anything else: prefix + `err.message` (or `String(err)` if not an Error).
6866
- *
6867
- * Tools with extra error classes should special-case those FIRST and only
6868
- * fall through to this helper for the shared cases.
6869
- */
6870
- function formatApiFetchError(err, options = {}) {
6871
- var _a;
6872
- if (err instanceof InvalidApiKeyError) {
6873
- return (`Authentication failed: invalid API key. ` +
6874
- `Please call the \`${TOOL_NAMES.EYES_VERIFY_API_KEY}\` MCP tool to refresh your credentials, ` +
6875
- `or set a valid APPLITOOLS_API_KEY environment variable.`);
6876
- }
6877
- if (err instanceof MissingApiKeyError) {
6878
- return (`No Applitools API key found. ` +
6879
- `Please call the \`${TOOL_NAMES.EYES_VERIFY_API_KEY}\` MCP tool first, ` +
6880
- `or set the APPLITOOLS_API_KEY environment variable.`);
6881
- }
6882
- const prefix = (_a = options.genericPrefix) !== null && _a !== void 0 ? _a : DEFAULT_GENERIC_PREFIX;
6883
- const msg = err instanceof Error ? err.message : String(err);
6884
- return `${prefix}${msg}`;
5853
+ return { registerTool };
6885
5854
  }
6886
5855
 
6887
5856
  const defaultResolverDeps = {
@@ -6926,236 +5895,6 @@ async function getFullAccountId(accountId, apiKey, serverUrl = DEFAULT_SERVER_UR
6926
5895
  }
6927
5896
  }
6928
5897
 
6929
- /**
6930
- * eyes_analyze_batch MCP tool — "Paste Batch URL" flow (AD-13206 Part 2).
6931
- *
6932
- * Accepts an Applitools batch URL or bare batch ID and returns visual test
6933
- * results with textual diff descriptions. Unlike `eyes_fetch_visual_results`,
6934
- * this tool does NOT require a Playwright HTML report on disk — it queries
6935
- * the public Batch Results API directly.
6936
- *
6937
- * Data flow:
6938
- * 1. Extract batch ID + server URL from the input URL
6939
- * 2. Load API key (session cache → config files → env vars)
6940
- * 3. GET /api/v1/batches/{batchId}?steps=true (via shared ApiClient)
6941
- * 4. For every step with diffDescriptionsCount > 0:
6942
- * GET /api/v1/batches/{batchId}/{sessionId}/{stepIndex}/diff
6943
- * (≤10 concurrent; deduplicate across pixel regions)
6944
- * 5. Build structured response in the same shape as eyes_fetch_visual_results
6945
- */
6946
- // ─── Tool metadata ────────────────────────────────────────────────────────────
6947
- const TOOL_NAME = TOOL_NAMES.EYES_ANALYZE_BATCH;
6948
- const TOOL_DESCRIPTION = `Fetch visual test results and textual diff descriptions from an Applitools Eyes batch URL.
6949
-
6950
- Use this tool when the user provides a batch URL from the Applitools dashboard (e.g. https://eyes.applitools.com/app/test-results/{batchId}) or a bare batch ID, and you need to analyze its visual test results without a Playwright HTML report on disk.
6951
-
6952
- This is the counterpart to \`eyes_fetch_visual_results\` for cases where:
6953
- - The user is looking at results from a CI run or a previous run
6954
- - There is no Playwright report available locally
6955
- - The user pastes a batch URL from the Eyes dashboard
6956
-
6957
- The tool returns the same structured output as \`eyes_fetch_visual_results\`, including:
6958
- - Per-test status (passed / failed / unresolved / new / aborted)
6959
- - Textual diff descriptions for steps with visual differences
6960
- - Aggregate summary statistics
6961
-
6962
- Note: Textual diff descriptions require DOM-based diff analysis on the server side. Steps without DOM capture (e.g. Figma, mobile native) may not have diff descriptions even when diffs are present.`;
6963
- // ─── Input / output schemas ───────────────────────────────────────────────────
6964
- const AnalyzeBatchInputSchema = commonInputSchema.extend({
6965
- batchUrl: zod.z
6966
- .string()
6967
- .describe('The Applitools Eyes batch URL (e.g. https://eyes.applitools.com/app/test-results/{batchId}) or a bare batch ID.'),
6968
- serverUrl: zod.z
6969
- .string()
6970
- .optional()
6971
- .describe('Eyes server base URL (optional, auto-detected from batchUrl or defaults to https://eyes.applitools.com). Set this for on-premises Eyes deployments.'),
6972
- });
6973
- const AnalyzeBatchClientInputSchema = createClientInputSchema(AnalyzeBatchInputSchema);
6974
- // ─── Tool implementation ──────────────────────────────────────────────────────
6975
- async function analyzeEyesBatch(input) {
6976
- var _a, _b;
6977
- const { workspaceRoot } = validateCommonInput(input);
6978
- // Step 1 — Extract batch ID and server URL
6979
- const batchId = extractBatchId(input.batchUrl);
6980
- if (!batchId) {
6981
- return VisualResultsToolResultSchema.parse({
6982
- message: wrapText(`Could not extract a batch ID from: ${input.batchUrl}\n\n` +
6983
- `Please provide a full Eyes batch URL (e.g. https://eyes.applitools.com/app/test-results/{batchId}) ` +
6984
- `or a bare batch ID.`, 'prefix'),
6985
- });
6986
- }
6987
- const serverUrl = (_a = input.serverUrl) !== null && _a !== void 0 ? _a : extractServerUrl(input.batchUrl, DEFAULT_SERVER_URL);
6988
- // Step 2 — Load API key. Defer wording to the shared `formatApiFetchError`
6989
- // helper so that any future copy change in one place propagates here too.
6990
- const apiKey = getLastValidatedApiKey() || loadCredentials(workspaceRoot).apiKey;
6991
- if (!apiKey) {
6992
- return VisualResultsToolResultSchema.parse({
6993
- message: wrapText(formatApiFetchError(new MissingApiKeyError()), 'prefix'),
6994
- });
6995
- }
6996
- // Resolve the key's true accountId so emitted dashboard URLs carry it; on
6997
- // verification failure the URLs simply omit the accountId query param.
6998
- const accountId = await getFullAccountId(undefined, apiKey, serverUrl);
6999
- // Step 3 — Fetch batch results
7000
- let batchData;
7001
- try {
7002
- batchData = await fetchBatchResults(batchId, apiKey, serverUrl);
7003
- }
7004
- catch (err) {
7005
- return VisualResultsToolResultSchema.parse({
7006
- message: wrapText(formatFetchError(err, batchId), 'prefix'),
7007
- });
7008
- }
7009
- if (!batchData.tests || batchData.tests.length === 0) {
7010
- return VisualResultsToolResultSchema.parse({
7011
- message: wrapText(`Batch ${batchId} contains no tests.`, 'prefix'),
7012
- });
7013
- }
7014
- // Step 4 — Fetch per-step diff descriptions for steps that have diffs
7015
- const stepDiffsByTest = new Map();
7016
- const diffTasks = buildDiffTasks(batchData.tests);
7017
- if (diffTasks.length > 0) {
7018
- // Fetch all step diffs with concurrency cap. Auth errors propagate; other
7019
- // per-step failures are absorbed inside fetchStepDiff and surface as [].
7020
- let diffResults;
7021
- try {
7022
- diffResults = await fetchStepDiffsWithCap(diffTasks.map(t => ({ batchId, sessionId: t.testId, stepIndex: t.stepIndex })), apiKey, serverUrl);
7023
- }
7024
- catch (err) {
7025
- return VisualResultsToolResultSchema.parse({
7026
- message: wrapText(formatFetchError(err, batchId), 'prefix'),
7027
- });
7028
- }
7029
- // Group results by testId
7030
- for (let i = 0; i < diffTasks.length; i++) {
7031
- const task = diffTasks[i];
7032
- const descriptions = diffResults[i];
7033
- if (descriptions.length > 0) {
7034
- if (!stepDiffsByTest.has(task.testId)) {
7035
- stepDiffsByTest.set(task.testId, []);
7036
- }
7037
- stepDiffsByTest.get(task.testId).push({
7038
- stepIndex: task.stepIndex,
7039
- stepName: task.stepName,
7040
- diffDescriptions: descriptions,
7041
- });
7042
- }
7043
- }
7044
- }
7045
- // Step 5 — Build ProcessedBatch compatible with the shared response builder
7046
- //
7047
- // Any `~~` in these URLs is base64 padding inside the accountId value itself
7048
- // (`=` encoded as `~`), never a separate suffix. Both visual-results tools
7049
- // build URLs through the shared helpers in utils/url-utils.ts.
7050
- const batchUrl = buildBatchUrl$1(serverUrl, batchId, accountId);
7051
- const batchName = ((_b = batchData.statistics) === null || _b === void 0 ? void 0 : _b.name) || batchId;
7052
- const processedTests = batchData.tests.map(test => {
7053
- var _a, _b, _c;
7054
- const stepDiffs = (_a = stepDiffsByTest.get(test.testId)) !== null && _a !== void 0 ? _a : [];
7055
- const browser = ((_b = test.env) === null || _b === void 0 ? void 0 : _b.app) || ((_c = test.env) === null || _c === void 0 ? void 0 : _c.device) || 'Unknown';
7056
- return {
7057
- testName: test.testName,
7058
- batchName,
7059
- status: normalizeStatus(test.status),
7060
- sessionUrl: buildSessionUrl$1(serverUrl, batchId, test.testId, accountId),
7061
- steps: test.steps.length,
7062
- retryAttempt: 0,
7063
- browser,
7064
- ...(stepDiffs.length > 0 ? { stepDiffs } : {}),
7065
- };
7066
- });
7067
- const processedBatches = [
7068
- {
7069
- batchId,
7070
- batchName,
7071
- batchUrl,
7072
- tests: processedTests,
7073
- },
7074
- ];
7075
- // Reuse the shared response builder for consistent output formatting
7076
- const result = buildVisualResultsResult(processedBatches);
7077
- return VisualResultsToolResultSchema.parse(result);
7078
- }
7079
- // Fall back to `Step N` for unnamed steps: the API omits `name`, and the
7080
- // downstream StepDiffSchema requires a string `stepName`.
7081
- function buildDiffTasks(tests) {
7082
- const diffTasks = [];
7083
- for (const test of tests) {
7084
- for (let i = 0; i < test.steps.length; i++) {
7085
- const step = test.steps[i];
7086
- if (step.diffDescriptionsCount > 0) {
7087
- diffTasks.push({
7088
- testId: test.testId,
7089
- stepIndex: i,
7090
- stepName: step.name || `Step ${i + 1}`,
7091
- });
7092
- }
7093
- }
7094
- }
7095
- return diffTasks;
7096
- }
7097
- /**
7098
- * Translate a fetch error into actionable, user-facing wording.
7099
- *
7100
- * Specialises for {@link BatchNotFoundError} (this tool's own 404 sentinel),
7101
- * then defers to the shared {@link formatApiFetchError} util so that
7102
- * `InvalidApiKeyError` / `MissingApiKeyError` wording stays consistent with
7103
- * `eyes_fetch_visual_results` (and any future MCP tool that talks to the
7104
- * Eyes server).
7105
- */
7106
- function formatFetchError(err, batchId) {
7107
- if (err instanceof BatchNotFoundError) {
7108
- return `Batch not found: ${batchId}. Verify the URL/batch ID and that the key has access to this batch.`;
7109
- }
7110
- return formatApiFetchError(err, { genericPrefix: 'Failed to fetch batch results: ' });
7111
- }
7112
-
7113
- const analyzeEyesBatchTool = {
7114
- name: TOOL_NAME,
7115
- description: TOOL_DESCRIPTION,
7116
- inputSchema: AnalyzeBatchClientInputSchema,
7117
- outputSchema: VisualResultsToolResultSchema,
7118
- handler: createToolHandler({
7119
- name: TOOL_NAME,
7120
- input: AnalyzeBatchInputSchema,
7121
- output: VisualResultsToolResultSchema,
7122
- }, async (params) => {
7123
- const result = await analyzeEyesBatch(params);
7124
- return {
7125
- content: [
7126
- {
7127
- type: 'text',
7128
- text: result.message,
7129
- },
7130
- ],
7131
- structuredContent: result,
7132
- };
7133
- }),
7134
- };
7135
-
7136
- const ALL_TOOLS = {
7137
- verifyApiKey: verifyApiKeyTool,
7138
- eyesSetupProject: eyesSetupProjectTool,
7139
- eyesSetupUfg: eyesSetupUfgTool,
7140
- eyesAddCheckpointsToTest: eyesAddCheckpointsToTestTool,
7141
- getBatchUrlFromOutput: getBatchUrlFromOutputTool,
7142
- playwrightFetchVisualResults: playwrightFetchVisualResultsTool,
7143
- analyzeEyesBatch: analyzeEyesBatchTool,
7144
- };
7145
-
7146
- const workspaceRootSchema = zod.z
7147
- .string()
7148
- .optional()
7149
- .describe("Root directory of the caller's project (optional; used to locate its .env credentials)");
7150
- function instrumentedRegistrar(server) {
7151
- const registerTool = (name, config, handler) => {
7152
- const inputSchema = { workspaceRoot: workspaceRootSchema, ...config.inputSchema };
7153
- const wrapped = createToolHandler({ name, input: zod.z.object(inputSchema) }, async (params) => handler(params).then(result => result));
7154
- return server.registerTool(name, { ...config, inputSchema }, wrapped);
7155
- };
7156
- return { registerTool };
7157
- }
7158
-
7159
5898
  const defaultDeps = { getFullAccountId };
7160
5899
  // One resolution per parse: everything downstream — API-call fetchers and URL
7161
5900
  // builders alike — receives the healed accountId. The raw eyes-results parse
@@ -7222,7 +5961,7 @@ const defaultCommandsDeps$1 = {
7222
5961
  fetchRawSession,
7223
5962
  fetchPrunedDom,
7224
5963
  getCompatibleSelectors,
7225
- fetchStepDiff: fetchStepDiff$1,
5964
+ fetchStepDiff,
7226
5965
  fetchCheckpointImage,
7227
5966
  fetchImageById,
7228
5967
  compareStep,
@@ -7556,7 +6295,7 @@ const defaultFetchVisibleDomDiffDeps = {
7556
6295
  fetchRawSession,
7557
6296
  awaitDomDiff,
7558
6297
  awaitDomDiffTask,
7559
- fetchStepDiff: fetchStepDiff$1,
6298
+ fetchStepDiff,
7560
6299
  compareStep,
7561
6300
  readFile: defaultFsCacheDeps.readFile,
7562
6301
  writeFile: defaultFsCacheDeps.writeFile,
@@ -9232,9 +7971,19 @@ function parentLevelOf(level) {
9232
7971
  function childLevelLabel(level) {
9233
7972
  return LEVEL_LABELS[childLevelOf(level)];
9234
7973
  }
9235
- /** `rootScope`, defaulted to `level` itself when the caller omits it — see the plan's "Bounding an investigation" section. */
7974
+ /**
7975
+ * `rootScope`, defaulted to `level` itself when the caller omits it — except a diff, which always
7976
+ * belongs to at least a step review, so a diff-rooted `next` would strand the model after the last area.
7977
+ */
9236
7978
  function resolveRootScope(level, rootScope) {
9237
- return rootScope !== null && rootScope !== void 0 ? rootScope : level;
7979
+ return rootScope !== null && rootScope !== void 0 ? rootScope : (level === 'diff' ? 'step' : level);
7980
+ }
7981
+ function isScopeType(value) {
7982
+ return SCOPE_TYPES.includes(value);
7983
+ }
7984
+ /** Whether `outer` is `inner` itself or one of its ancestors. */
7985
+ function isAtOrAbove(outer, inner) {
7986
+ return levelDepth(outer) <= levelDepth(inner);
9238
7987
  }
9239
7988
  /** Whether escalating beyond `level` (to a sibling, or to the parent) would go past the entity the investigation was scoped to. */
9240
7989
  function hasReachedRootScope(level, rootScope) {
@@ -9320,7 +8069,10 @@ function computeCompleted(scopeId, liveChildScopeIds, deps) {
9320
8069
  * them, never mutates or re-scopes one.
9321
8070
  */
9322
8071
  function buildProgressNext(params) {
9323
- const { level, rootScope, completed, descentCall, endCall, parentProgressCall } = params;
8072
+ return withRootReminder(progressNext(params), params.rootScope);
8073
+ }
8074
+ function progressNext(params) {
8075
+ const { level, rootScope, completed, descentCall, endCall, hasChildFindings, parentProgressCall } = params;
9324
8076
  const label = LEVEL_LABELS[level];
9325
8077
  const childLabel = LEVEL_LABELS[childLevelOf(level)];
9326
8078
  if (completed === null) {
@@ -9330,6 +8082,12 @@ function buildProgressNext(params) {
9330
8082
  calls: [descentCall],
9331
8083
  };
9332
8084
  }
8085
+ if (!hasChildFindings) {
8086
+ return {
8087
+ instruction: emptyCloseInstruction(`Every ${childLabel} of this ${label} was reviewed and none of them recorded a finding`, endCall.tool, level),
8088
+ calls: [withEmptyFindings(endCall)],
8089
+ };
8090
+ }
9333
8091
  return {
9334
8092
  instruction: `Every ${childLabel} of this ${label} was reviewed. Call ${endCall.tool} with scope "${level}" and a summary built from findings.`,
9335
8093
  calls: [endCall],
@@ -9344,6 +8102,20 @@ function buildProgressNext(params) {
9344
8102
  calls: [parentProgressCall],
9345
8103
  };
9346
8104
  }
8105
+ /** Clients that rebuild arguments instead of copying `next.calls` drop `rootScope`; restating it in prose keeps it in view. */
8106
+ function rootReminder(rootScope) {
8107
+ return `This review is rooted at scope "${rootScope}" — pass rootScope: "${rootScope}" on every eyes_review_* call until it reports complete.`;
8108
+ }
8109
+ /** Root responses carry no calls and keep their done message verbatim. */
8110
+ function withRootReminder(next, rootScope) {
8111
+ return next.calls ? { ...next, instruction: `${next.instruction} ${rootReminder(rootScope)}` } : next;
8112
+ }
8113
+ function emptyCloseInstruction(reviewedNothingFound, endTool, scope) {
8114
+ return `${reviewedNothingFound}, so there is nothing to summarize — call ${endTool} with scope "${scope}" and \`findings: []\` (an empty list is the only valid submission here).`;
8115
+ }
8116
+ function withEmptyFindings(call) {
8117
+ return { ...call, args: { ...call.args, findings: [] } };
8118
+ }
9347
8119
  /**
9348
8120
  * `eyes_review_end`'s `next` for one level, once its checks have passed (soft-incomplete redirects
9349
8121
  * are built by the caller directly — see `tools.ts`): while `level` hasn't reached `rootScope`, a call
@@ -9353,6 +8125,9 @@ function buildProgressNext(params) {
9353
8125
  * `parentProgressCall` are expected to already carry `rootScope` from their `nextCall()` call site.
9354
8126
  */
9355
8127
  function buildEndNext(params) {
8128
+ return withRootReminder(endNext(params), params.rootScope);
8129
+ }
8130
+ function endNext(params) {
9356
8131
  const { level, rootScope, siblingCall, parentClose, parentProgressCall, doneMessage } = params;
9357
8132
  const label = LEVEL_LABELS[level];
9358
8133
  if (hasReachedRootScope(level, rootScope)) {
@@ -9369,6 +8144,13 @@ function buildEndNext(params) {
9369
8144
  }
9370
8145
  if (parentClose) {
9371
8146
  const closeLabel = LEVEL_LABELS[parentClose.level];
8147
+ if (!parentClose.hasChildFindings) {
8148
+ return {
8149
+ instruction: emptyCloseInstruction(`This ${label} was reviewed, and so was every other ${label}, so the ${closeLabel} is now fully reviewed too — and none of its ${childLevelLabel(parentClose.level)}s recorded a finding`, parentClose.endCall.tool, parentClose.level),
8150
+ calls: [withEmptyFindings(parentClose.endCall)],
8151
+ nextLevel: parentClose.nextLevel,
8152
+ };
8153
+ }
9372
8154
  return {
9373
8155
  instruction: `This ${label} was reviewed, and so was every other ${label}, so the ${closeLabel} is now fully reviewed too. Call ${parentClose.endCall.tool} for the ${closeLabel} next, citing the indexed findings in next.nextLevel as its sources — do not re-check its progress first, this response already is that answer.`,
9374
8156
  calls: [parentClose.endCall],
@@ -9650,10 +8432,12 @@ function verifySourcedFindings(findings, childFindings) {
9650
8432
  claimedBy.set(source, findingIndex);
9651
8433
  }
9652
8434
  });
8435
+ if (outOfRange.length > 0 && childFindings.length === 0) {
8436
+ throw new Error("This level has no child findings to cite, so `sources` cannot name anything. Call again with `findings: []` — the only valid submission when the list this level's own _progress call reported is empty.");
8437
+ }
9653
8438
  if (outOfRange.length > 0) {
9654
- const range = childFindings.length > 0 ? `0-${childFindings.length - 1}` : '(there are no child findings to source from)';
9655
8439
  throw new Error(`Sources name an index that is not a valid child finding index for this call: ${outOfRange.join('; ')}. ` +
9656
- `Valid indices are ${range}. Call again with sources that only reference indices from the findings this level's own _progress call reported.`);
8440
+ `Valid indices are 0-${childFindings.length - 1}. Call again with sources that only reference indices from the findings this level's own _progress call reported.`);
9657
8441
  }
9658
8442
  if (overlapping.length > 0) {
9659
8443
  throw new Error(`${overlapping.join('; ')} — each child finding must be consolidated into exactly one submitted finding. ` +
@@ -9752,9 +8536,9 @@ const REVIEW_SCOPE_ID_SHAPES = {
9752
8536
  .describe(`${STEP_INDEX_DESC}. Required for scope "step"; omit it otherwise.`),
9753
8537
  };
9754
8538
  const RootScopeShape = zod.z
9755
- .enum(LEVELS)
8539
+ .enum(SCOPE_TYPES)
9756
8540
  .optional()
9757
- .describe("Determines the shape of this call's `next` output. Only specify it when a prior call's `next` output already indicated one — and then pass that value through as given, never omitted or modified.");
8541
+ .describe("The scope this review was started at; bounds how far `next` escalates. Omit it only on a review's first call — it then defaults to that call's own scope (for eyes_review_diff_report, to its step). On every later call pass through the value the previous call's `next` gave, unchanged: a call that omits it while a wider review is still in progress is sent back unexecuted with the call to repeat (findings always roll up to the parent level regardless).");
9758
8542
  const ModeShape = zod.z
9759
8543
  .enum(MODES)
9760
8544
  .optional()
@@ -9960,7 +8744,7 @@ const SOURCES_DESC = "Indexes into the flat, combined list of every child findin
9960
8744
  'entry (no gaps, no overlap between entries), counting `sourceClusters` too; between the two fields, at least ' +
9961
8745
  "one citation is required here. This entry's isBug/isExpected must then be consistent with the child findings " +
9962
8746
  'it names: isBug non-null iff any of them has isBug non-null; isExpected non-null iff every one of them has ' +
9963
- 'isExpected non-null.';
8747
+ 'isExpected non-null. When _progress reported no child findings, submit `findings: []`.';
9964
8748
  const SourcesShape = zod.z.array(zod.z.number().int().nonnegative()).describe(SOURCES_DESC);
9965
8749
  const SOURCE_CLUSTERS_DESC = 'Ids from the `clusters` block that same _progress call reported — a shorthand for every index the named cluster ' +
9966
8750
  'holds, so a large list can be claimed without transcribing it. Clusters were grouped by a mechanical key alone ' +
@@ -10035,6 +8819,34 @@ const JsonFileArgShape = zod.z
10035
8819
  'one repetitive cause such as one locale/theme change touching every changed area alike) — writing to a file has ' +
10036
8820
  'no such limit. The tool reads and validates the file exactly as if its contents had been sent inline.');
10037
8821
 
8822
+ /**
8823
+ * Build the canonical Eyes dashboard URL for a single test session.
8824
+ *
8825
+ * Output shape: `{serverUrl}/app/test-results/{batchId}/{sessionId}[?accountId={accountId}]`
8826
+ *
8827
+ * Nothing is appended after the accountId: any `~~` in the final URL is base64
8828
+ * padding inside the accountId value, which arrives complete from the server.
8829
+ *
8830
+ * `accountId` is optional because not every caller has one to hand (the
8831
+ * batch-results-API flow authenticates by API key alone); pass it whenever
8832
+ * the URL was itself derived from a parsed accountId, so review round-trips
8833
+ * stay tied to the account they came from.
8834
+ */
8835
+ function buildSessionUrl$1(serverUrl, batchId, sessionId, accountId) {
8836
+ const accountIdQuery = accountId ? `?accountId=${accountId}` : '';
8837
+ return `${serverUrl}/app/test-results/${batchId}/${sessionId}${accountIdQuery}`;
8838
+ }
8839
+ /**
8840
+ * Build the canonical Eyes dashboard URL for a whole batch.
8841
+ *
8842
+ * Output shape: `{serverUrl}/app/test-results/{batchId}[/?accountId={accountId}]`
8843
+ */
8844
+ function buildBatchUrl$1(serverUrl, batchId, accountId) {
8845
+ return accountId
8846
+ ? `${serverUrl}/app/test-results/${batchId}/?accountId=${accountId}`
8847
+ : `${serverUrl}/app/test-results/${batchId}`;
8848
+ }
8849
+
10038
8850
  /**
10039
8851
  * Builds a batch or session URL from parsed components — the inverse of `api`'s
10040
8852
  * `parseBatchUrl`/`parseSessionUrl`. The review tools need these to construct ready-made
@@ -10746,16 +9558,13 @@ async function decideOrCreditStepAction(params) {
10746
9558
  * model-authored summary prose from whenever `_end` first recorded them, never regenerated —
10747
9559
  * this only re-consolidates its rollup now that its children are promoted.
10748
9560
  *
10749
- * `pushesUp` mirrors the same rule the live `_end` calls use (see `commands.ts`'s conditional
10750
- * `pushUpTo`): only the walk's own root conditions its push-up on the calling command's `rootScope`;
10751
- * every node below the root always pushes up to its immediate in-subtree parent, since that's how
10752
- * the root's own consolidation gets the data to consolidate from.
9561
+ * Every node, the walk's root included, pushes up to its parent exactly as the live `_end` calls
9562
+ * do — `rootScope` bounds `next`, never where findings are recorded.
10753
9563
  */
10754
- function promoteSubtreeToResolve(rootLevel, rootScope, ctx, keys, deps) {
9564
+ function promoteSubtreeToResolve(rootLevel, ctx, keys, deps) {
10755
9565
  return walkSubtree(rootLevel, ctx, async (level, nodeCtx, scopeId) => {
10756
9566
  if (getScopeMode(scopeId, deps) !== 'inspect')
10757
9567
  return;
10758
- const pushesUp = level !== rootLevel || !hasReachedRootScope(level, rootScope);
10759
9568
  if (level === 'diff') {
10760
9569
  const findings = getCompletion(scopeId, deps).payload;
10761
9570
  const promoted = await applyRegionMasking({
@@ -10766,11 +9575,9 @@ function promoteSubtreeToResolve(rootLevel, rootScope, ctx, keys, deps) {
10766
9575
  deps,
10767
9576
  });
10768
9577
  recordCompletion(scopeId, promoted, deps);
10769
- if (pushesUp) {
10770
- const parentScopeId = stepScopeId(nodeCtx.sessionUrl, nodeCtx.stepIndex);
10771
- appendChildFinding(parentScopeId, diffChildKey(nodeCtx.areaRect), promoted, deps);
10772
- reportRollup(parentScopeId, diffChildKey(nodeCtx.areaRect), { resolution: { accepted: 0, rejected: 0, unresolved: 0 }, regions: mergeFindingRegions(promoted) }, deps);
10773
- }
9578
+ const parentScopeId = stepScopeId(nodeCtx.sessionUrl, nodeCtx.stepIndex);
9579
+ appendChildFinding(parentScopeId, diffChildKey(nodeCtx.areaRect), promoted, deps);
9580
+ reportRollup(parentScopeId, diffChildKey(nodeCtx.areaRect), { resolution: { accepted: 0, rejected: 0, unresolved: 0 }, regions: mergeFindingRegions(promoted) }, deps);
10774
9581
  }
10775
9582
  else if (level === 'step') {
10776
9583
  const session = await fetchSteps(nodeCtx.sessionUrl, keys);
@@ -10786,21 +9593,19 @@ function promoteSubtreeToResolve(rootLevel, rootScope, ctx, keys, deps) {
10786
9593
  deps,
10787
9594
  });
10788
9595
  recordCompletion(scopeId, findings, deps);
10789
- if (pushesUp) {
10790
- const parentScopeId = sessionScopeId(nodeCtx.sessionUrl);
10791
- appendChildFinding(parentScopeId, stepChildKey(nodeCtx.stepIndex), findings, deps);
10792
- reportRollup(parentScopeId, stepChildKey(nodeCtx.stepIndex), { resolution, regions: rollup.regions }, deps);
10793
- }
9596
+ const parentScopeId = sessionScopeId(nodeCtx.sessionUrl);
9597
+ appendChildFinding(parentScopeId, stepChildKey(nodeCtx.stepIndex), findings, deps);
9598
+ reportRollup(parentScopeId, stepChildKey(nodeCtx.stepIndex), { resolution, regions: rollup.regions }, deps);
10794
9599
  }
10795
9600
  else {
10796
9601
  const findings = getCompletion(scopeId, deps).payload;
10797
9602
  const { rollup } = consolidateRollup(scopeId, findings, 'resolve', deps);
10798
9603
  recordCompletion(scopeId, findings, deps);
10799
- if (pushesUp && level === 'scenario') {
9604
+ if (level === 'scenario') {
10800
9605
  appendChildFinding(batchScopeId(nodeCtx.batchUrl), scenarioChildKey(nodeCtx.scenarioName), findings, deps);
10801
9606
  reportRollup(batchScopeId(nodeCtx.batchUrl), scenarioChildKey(nodeCtx.scenarioName), rollup, deps);
10802
9607
  }
10803
- else if (pushesUp && level === 'session') {
9608
+ else if (level === 'session') {
10804
9609
  const session = await fetchSteps(nodeCtx.sessionUrl, keys);
10805
9610
  const parentScopeId = scenarioScopeIdForSession(nodeCtx.sessionUrl, session.sessionName);
10806
9611
  appendChildFinding(parentScopeId, sessionChildKey(nodeCtx.sessionUrl), findings, deps);
@@ -11066,6 +9871,7 @@ function chainDown(child, rootScope, mode, deps) {
11066
9871
  if (incomplete.length !== 1)
11067
9872
  return node;
11068
9873
  recordScopeMode(node.scopeId, mode, deps);
9874
+ recordScopeRoot(node.scopeId, rootScope, deps);
11069
9875
  node = incomplete[0];
11070
9876
  }
11071
9877
  }
@@ -11099,7 +9905,7 @@ function originContribution(level, childKey) {
11099
9905
  }
11100
9906
  }
11101
9907
  /** Every write is keyed by child key and overwriting, so two siblings racing into the same ancestor is safe. */
11102
- async function deriveClose(level, mode, deps) {
9908
+ async function deriveClose(level, rootScope, mode, deps) {
11103
9909
  const [childKey, childFindings] = orderedChildFindingEntries(level.scopeId, deps)[0];
11104
9910
  const { findings: forwarded, rollup } = consolidateRollup(level.scopeId, forwardFindings(childFindings, originContribution(level, childKey)), mode, deps);
11105
9911
  const parent = await level.up.parent();
@@ -11107,6 +9913,7 @@ async function deriveClose(level, mode, deps) {
11107
9913
  appendChildFinding(parent.scopeId, level.up.key, forwarded, deps);
11108
9914
  reportRollup(parent.scopeId, level.up.key, rollup, deps);
11109
9915
  recordScopeMode(level.scopeId, mode, deps);
9916
+ recordScopeRoot(level.scopeId, rootScope, deps);
11110
9917
  log(level.scopeId, 'derived-close', { input: { scopeId: level.scopeId } }, deps);
11111
9918
  return parent;
11112
9919
  }
@@ -11116,7 +9923,7 @@ async function chainUp(parent, rootScope, mode, deps) {
11116
9923
  for (;;) {
11117
9924
  if (!level.up || !compressibleOnAscent(level.level, level.scopeId, deps))
11118
9925
  return { kind: 'end', level };
11119
- const grandParent = await deriveClose(level, mode, deps);
9926
+ const grandParent = await deriveClose(level, rootScope, mode, deps);
11120
9927
  const unreviewed = queuedChildNodes(grandParent, rootScope, mode, deps).find(child => child.scopeId !== level.scopeId && !isCompleted(child.scopeId, deps));
11121
9928
  if (unreviewed) {
11122
9929
  const target = chainDown(unreviewed, rootScope, mode, deps);
@@ -11130,7 +9937,16 @@ async function runProgress(params) {
11130
9937
  const completed = computeCompleted(scopeId, children.map(c => c.scopeId), deps);
11131
9938
  const nextChild = completed === null ? children.find(c => !isCompleted(c.scopeId, deps)) : undefined;
11132
9939
  const descentCall = nextChild && descend(nextChild);
11133
- const next = buildProgressNext({ level, rootScope, completed, descentCall, endCall, parentProgressCall });
9940
+ const hasChildFindings = completed === null && !descentCall && flattenChildFindings(scopeId, deps).length > 0;
9941
+ const next = buildProgressNext({
9942
+ level,
9943
+ rootScope,
9944
+ completed,
9945
+ descentCall,
9946
+ endCall,
9947
+ hasChildFindings,
9948
+ parentProgressCall,
9949
+ });
11134
9950
  const stillInvestigating = completed === null && descentCall !== undefined;
11135
9951
  // Each branch below builds its own complete literal, keys already in the order they must
11136
9952
  // serialize in — `next` last, however many of findings/resolution/regions precede it — rather
@@ -11145,14 +9961,38 @@ async function runProgress(params) {
11145
9961
  recordToolTelemetry({ resolve_decisions: rollup.resolution });
11146
9962
  return { completed, findings, clusters, resolution: rollup.resolution, regions: rollup.regions, next };
11147
9963
  }
9964
+ /** Below batch only; `undefined` when nothing recorded on the parent suggests an enclosing walk. */
9965
+ function inferEnclosingReview(parent, parentScopeId, deps) {
9966
+ // A stored root narrower than the parent, or not a scope at all, would make `widen` a call
9967
+ // the schema or the walk rejects.
9968
+ const stored = getScopeRoot(parentScopeId, deps);
9969
+ const root = isScopeType(stored) && isAtOrAbove(stored, parent) ? stored : undefined;
9970
+ if (!root && !getScopeMode(parentScopeId, deps))
9971
+ return undefined;
9972
+ return {
9973
+ scope: parent,
9974
+ rootScope: root !== null && root !== void 0 ? root : parent,
9975
+ state: getCompletion(parentScopeId, deps) ? 'closed-earlier' : 'in-progress',
9976
+ };
9977
+ }
9978
+ function enclosingWarning(level, enclosing) {
9979
+ return enclosing.state === 'in-progress'
9980
+ ? `This call omitted rootScope, so the review closed here at scope "${level}" — but the enclosing ${enclosing.scope} is mid-review, rooted at "${enclosing.rootScope}". If you are continuing that review, call the tool named in review.widen.tool with review.widen.args unchanged; this ${level}'s findings are already recorded for it.`
9981
+ : `The enclosing ${enclosing.scope}'s summary predates this ${level}'s new findings; to refresh it, call the tool named in review.widen.tool with review.widen.args unchanged.`;
9982
+ }
11148
9983
  async function runEnd(params) {
11149
- const { level, toolName, rootScope, scopeId, ownChildren, progressCall, pushUpTo, finalize, getSiblings, descend, parentProgressCall, ascent, mode, doneMessage, deps, } = params;
9984
+ var _a;
9985
+ const { level, toolName, rootScope, rootScopeOmitted, scopeId, ownChildren, progressCall, pushUpTo, finalize, getSiblings, descend, parentProgressCall, ascent, mode, doneMessage, deps, } = params;
11150
9986
  const stillIncomplete = ownChildren.some(c => !isCompleted(c.scopeId, deps));
11151
9987
  if (stillIncomplete) {
11152
9988
  const instruction = `Not every ${childLevelLabel(level)} of this ${level} was reviewed yet. This submission was discarded — call ${progressCall.tool} for this ${level} again to see what remains, then call this again once it reports being fully reviewed.`;
11153
9989
  countGateRejection();
11154
9990
  log(scopeId, toolName, { input: { scopeId }, error: instruction }, deps);
11155
- return { persisted: false, next: { instruction, calls: [progressCall] } };
9991
+ return {
9992
+ persisted: false,
9993
+ next: { instruction: `${instruction} ${rootReminder(rootScope)}`, calls: [progressCall] },
9994
+ reachedRoot: false,
9995
+ };
11156
9996
  }
11157
9997
  const { findings, rollup } = await finalize();
11158
9998
  const count = Array.isArray(findings) ? findings.length : undefined;
@@ -11165,6 +10005,7 @@ async function runEnd(params) {
11165
10005
  appendChildFinding(pushUpTo.parentScopeId, pushUpTo.childKey, findings, deps);
11166
10006
  reportRollup(pushUpTo.parentScopeId, pushUpTo.childKey, rollup, deps);
11167
10007
  }
10008
+ const reachedRoot = hasReachedRootScope(level, rootScope);
11168
10009
  const siblings = await getSiblings();
11169
10010
  const incompleteSibling = siblings.find(s => !isCompleted(s.scopeId, deps));
11170
10011
  // No incomplete sibling means the parent's `_progress` could only answer "call `_end`", which is already known here.
@@ -11173,7 +10014,7 @@ async function runEnd(params) {
11173
10014
  if (descend)
11174
10015
  target = { kind: 'call', ...descend(incompleteSibling) };
11175
10016
  }
11176
- else if (ascent && !hasReachedRootScope(level, rootScope)) {
10017
+ else if (ascent && !reachedRoot) {
11177
10018
  target = await chainUp(ascent(), rootScope, mode, deps);
11178
10019
  }
11179
10020
  const next = buildEndNext({
@@ -11189,26 +10030,23 @@ async function runEnd(params) {
11189
10030
  findings: target.level.findings(),
11190
10031
  clusters: target.level.clusters(),
11191
10032
  },
10033
+ hasChildFindings: flattenChildFindings(target.level.scopeId, deps).length > 0,
11192
10034
  }
11193
10035
  : undefined,
11194
10036
  parentProgressCall,
11195
10037
  doneMessage,
11196
10038
  });
11197
- return { persisted: true, next, findings, rollup };
10039
+ if (!reachedRoot || !parentProgressCall || !pushUpTo)
10040
+ return { persisted: true, next, findings, rollup, reachedRoot };
10041
+ const parent = parentProgressCall.args.scope;
10042
+ const enclosing = rootScopeOmitted ? inferEnclosingReview(parent, pushUpTo.parentScopeId, deps) : undefined;
10043
+ const widen = { ...parentProgressCall, args: { ...parentProgressCall.args, rootScope: (_a = enclosing === null || enclosing === void 0 ? void 0 : enclosing.rootScope) !== null && _a !== void 0 ? _a : parent } };
10044
+ const instruction = enclosing ? `${next.instruction} ${enclosingWarning(level, enclosing)}` : next.instruction;
10045
+ return { persisted: true, next: { ...next, instruction }, findings, rollup, reachedRoot, widen, enclosing };
11198
10046
  }
11199
10047
  /**
11200
- * Once a review reaches its rootScope — the point where `next.instruction` becomes the
11201
- * `finalDoneMessage` that hands off to a user-facing report, rather than pointing at a sibling or
11202
- * parent call — folds each finding's `example` link into its `summary` text as a markdown link
11203
- * and drops the standalone `example` key. This is what makes the link survive into the report
11204
- * structurally: past this point the model is only ever copying/paraphrasing `summary` prose, so a
11205
- * link embedded in that same string travels with it, instead of sitting in a separate field a
11206
- * "compose a readable report" pass can quietly leave behind.
11207
- *
11208
- * Below the root, both fields are left separate and untouched — the next level up still needs its
11209
- * own `example` input when consolidating (see `SummaryExampleShape`), and folding early would
11210
- * bake this level's link into a `summary` that gets restated, not carried forward verbatim, at
11211
- * the next hop.
10048
+ * At `reachedRoot` the model only paraphrases `summary` into the user's report, so the link must live inside it;
10049
+ * below the root the next level still consolidates from a separate `example`.
11212
10050
  */
11213
10051
  function foldExampleIntoSummary(findings) {
11214
10052
  if (!Array.isArray(findings))
@@ -11220,20 +10058,20 @@ function foldExampleIntoSummary(findings) {
11220
10058
  return { ...rest, summary: `${summary} ([view](${example}))` };
11221
10059
  });
11222
10060
  }
11223
- /**
11224
- * The `_end` response body: `findings` and, in `mode: 'resolve'`, the `resolution` and `regions`
11225
- * tallies beside it — the same merged totals `runEnd`'s own `rollup` carries. `regions` is also
11226
- * attached to each finding individually (see `consolidateRollup`), where the change it describes
11227
- * actually happened; the top-level copy here is just that same total, for a reader who only wants
11228
- * the global count without walking every finding. `isRootScope` gates `foldExampleIntoSummary` —
11229
- * see its own doc comment for why the fold only happens there.
11230
- */
11231
- function endResponse(result, mode, isRootScope) {
10061
+ /** `review` is internal: it carries the root-only data to `tools.ts`, whose `withReviewField` merges it into the leading `review` field. */
10062
+ function endResponse(result, mode) {
11232
10063
  // `next` is assigned last so it always serializes as this response's final key, however many
11233
10064
  // of findings/resolution/regions precede it.
11234
10065
  const response = {};
10066
+ if (result.reachedRoot) {
10067
+ response.review = {
10068
+ reachedRoot: true,
10069
+ ...(result.widen && { widen: result.widen }),
10070
+ ...(result.enclosing && { enclosing: result.enclosing }),
10071
+ };
10072
+ }
11235
10073
  if (result.persisted)
11236
- response.findings = isRootScope ? foldExampleIntoSummary(result.findings) : result.findings;
10074
+ response.findings = result.reachedRoot ? foldExampleIntoSummary(result.findings) : result.findings;
11237
10075
  if (result.persisted && mode === 'resolve' && result.rollup) {
11238
10076
  response.resolution = result.rollup.resolution;
11239
10077
  response.regions = result.rollup.regions;
@@ -11280,7 +10118,8 @@ function checkModeAgreesWithParent(params) {
11280
10118
  if (!parentMode || parentMode === mode)
11281
10119
  return null;
11282
10120
  const instruction = `This call passed mode "${mode}", but its parent scope is already being reviewed in mode "${parentMode}". ` +
11283
- `Call ${retryCall.tool} again with mode: "${parentMode}" — every level of one investigation must share the same mode.`;
10121
+ `Call ${retryCall.tool} again with mode: "${parentMode}" — every level of one investigation must share the same mode. ` +
10122
+ rootReminder(retryCall.args.rootScope);
11284
10123
  countGateRejection();
11285
10124
  log(parentScopeId, retryCall.tool, { input: { parentScopeId, mode }, error: instruction }, deps);
11286
10125
  return { instruction, calls: [{ ...retryCall, args: { ...retryCall.args, mode: parentMode } }] };
@@ -11295,6 +10134,39 @@ function checkParentModeMismatch(level, rootScope, parentScopeId, mode, retryCal
11295
10134
  ? null
11296
10135
  : checkModeAgreesWithParent({ parentScopeId, mode, retryCall, deps });
11297
10136
  }
10137
+ /** Nearest first: the call's own scope, its session (step level only), its batch. */
10138
+ function midWalkCandidates(own, scopeId, sessionUrl) {
10139
+ const session = own === 'step' ? [{ scope: 'session', scopeId: sessionScopeId(sessionUrl) }] : [];
10140
+ return [{ scope: own, scopeId }, ...session, { scope: 'batch', scopeId: rootScopeId(scopeId) }];
10141
+ }
10142
+ /** Reads `roots` only; a mid-walk rootless call is redirected before anything is discarded or written. */
10143
+ function checkRootlessMidWalk(params) {
10144
+ const { level, scopeId, sessionUrl, rootScopeOmitted, retryCall, restart, deps } = params;
10145
+ if (!rootScopeOmitted)
10146
+ return null;
10147
+ const own = resolveRootScope(level, undefined);
10148
+ const root = midWalkCandidates(own, scopeId, sessionUrl)
10149
+ .map(candidate => {
10150
+ const stored = getScopeRoot(candidate.scopeId, deps);
10151
+ const open = isScopeType(stored) &&
10152
+ isAtOrAbove(stored, candidate.scope) &&
10153
+ !isAtOrAbove(own, stored) &&
10154
+ getCompletion(candidate.scopeId, deps) === undefined;
10155
+ return open ? stored : undefined;
10156
+ })
10157
+ .find(stored => stored !== undefined);
10158
+ if (!root)
10159
+ return null;
10160
+ const instruction = `This call omitted rootScope, but this ${own} belongs to a review that is still in progress and rooted at "${root}"; without rootScope it would be narrowed to this ${own} alone. Nothing was recorded. ` +
10161
+ `Call ${retryCall.tool} again with rootScope: "${root}" and every other argument unchanged — next.calls holds exactly that call. ` +
10162
+ `To review this ${own} on its own instead, pass rootScope: "${own}" explicitly. ${rootReminder(root)}`;
10163
+ countGateRejection();
10164
+ log(scopeId, retryCall.tool, { input: { scopeId, rootScopeOmitted: true }, error: instruction }, deps);
10165
+ return {
10166
+ instruction,
10167
+ calls: [{ ...retryCall, args: { ...retryCall.args, rootScope: root, ...(restart ? { restart: true } : {}) } }],
10168
+ };
10169
+ }
11298
10170
  // ---------------------------------------------------------------------------
11299
10171
  // `restart` — discards every cached record for a scope and everything beneath it, so a caller
11300
10172
  // that wants to independently re-review something already reviewed (by this investigation or a
@@ -11308,6 +10180,7 @@ function discardSubtree(level, ctx, deps) {
11308
10180
  clearChildFindings(scopeId, deps);
11309
10181
  clearChildFindings(rollupScopeId(scopeId), deps);
11310
10182
  clearScopeMode(scopeId, deps);
10183
+ clearScopeRoot(scopeId, deps);
11311
10184
  clearQueuedChildKeys(scopeId, deps);
11312
10185
  clearUnreadyChildren(scopeId, deps);
11313
10186
  clearDiscoveredChildren(scopeId, deps);
@@ -11326,15 +10199,16 @@ async function maybeDiscard(restart, level, ctx, deps) {
11326
10199
  // to promote.
11327
10200
  // ---------------------------------------------------------------------------
11328
10201
  async function promoteIfNeeded(params) {
11329
- const { level, scopeId, ctx, rootScope, mode, restart, keys, deps } = params;
10202
+ const { level, scopeId, ctx, mode, restart, keys, deps } = params;
11330
10203
  if (restart || mode !== 'resolve' || !isCompleted(scopeId, deps) || getScopeMode(scopeId, deps) !== 'inspect')
11331
10204
  return;
11332
- await promoteSubtreeToResolve(level, rootScope, ctx, keys, deps);
10205
+ await promoteSubtreeToResolve(level, ctx, keys, deps);
11333
10206
  }
11334
- /** `promoteIfNeeded` followed by `recordScopeMode` — every level's own pair, in this same order. */
10207
+ /** `promoteIfNeeded` followed by `recordScopeMode`/`recordScopeRoot` — every level's own sequence, in this same order. */
11335
10208
  async function promoteAndRecordMode(params) {
11336
10209
  await promoteIfNeeded(params);
11337
10210
  recordScopeMode(params.scopeId, params.mode, params.deps);
10211
+ recordScopeRoot(params.scopeId, params.rootScope, params.deps);
11338
10212
  }
11339
10213
  // ---------------------------------------------------------------------------
11340
10214
  // diff_report's hard gates — verifies eyes_inspect_image_diff and both baseline/checkpoint
@@ -11473,14 +10347,19 @@ async function withGateLog(toolName, scopeId, input, deps, fn) {
11473
10347
  // ---------------------------------------------------------------------------
11474
10348
  const ASK_TO_RESOLVE = ' Unless you are already resolving this investigation, ask the user whether to proceed to resolve the differences found.';
11475
10349
  function finalDoneMessage(params) {
11476
- const { level, findingsCount, hasExampleLink, mentionEnvironment, runningSessionCount = 0, debugLogPath } = params;
10350
+ const { rootScope, where, findingsCount, hasExampleLink, mentionEnvironment, runningSessionCount = 0, debugLogPath, } = params;
10351
+ const opener = `The review the user started at scope "${rootScope}" (${where}) is complete`;
10352
+ const parent = parentLevelOf(rootScope);
10353
+ const widenClause = parent
10354
+ ? ` Nothing further is needed unless the user wants a wider review; to widen it, call the tool named in review.widen.tool with review.widen.args unchanged (${EYES_REVIEW_TOOLS.progress} at scope "${parent}").`
10355
+ : ' This is the widest scope; nothing further is needed.';
11477
10356
  const runningClause = runningSessionCount > 0
11478
10357
  ? ` ${runningSessionCount} session(s) are still running and could not be reviewed. Mention this to the user and suggest re-running this review once those sessions complete, or are aborted manually, to review them too.`
11479
10358
  : '';
11480
10359
  const debugLogClause = ` This investigation's debug log is at ${debugLogPath}, for troubleshooting only — never mention it in ` +
11481
10360
  `the report above; reveal it only if the user explicitly asks where the log is.`;
11482
10361
  if (findingsCount === 0) {
11483
- return `${level} was fully reviewed — no differences were found. Report this to the user.${runningClause}${debugLogClause}`;
10362
+ return `${opener} — no differences were found. Report this to the user.${widenClause}${runningClause}${debugLogClause}`;
11484
10363
  }
11485
10364
  const exampleClause = hasExampleLink
11486
10365
  ? ', each with its example link already folded into the summary text — reproduce it exactly, never strip it out,'
@@ -11488,9 +10367,9 @@ function finalDoneMessage(params) {
11488
10367
  const environmentClause = mentionEnvironment
11489
10368
  ? ' Call out any finding that occurs in one environment (browser/OS/viewport) but not others.'
11490
10369
  : '';
11491
- return (`${level} was fully reviewed. Produce a report for the user, ordered: known bugs first (most severe first), then unexpected changes, then ` +
10370
+ return (`${opener}: ${findingsCount} finding${findingsCount === 1 ? '' : 's'}. Produce a report for the user, ordered: known bugs first (most severe first), then unexpected changes, then ` +
11492
10371
  `expected changes last — a finding that's both a known bug and an expected change is still a bug, so order it with the bugs. One entry per ` +
11493
- `distinct diff (skip duplicates)${exampleClause} noting whether it's expected or a bug.${environmentClause}${ASK_TO_RESOLVE}${runningClause}${debugLogClause}`);
10372
+ `distinct diff (skip duplicates)${exampleClause} noting whether it's expected or a bug.${environmentClause}${ASK_TO_RESOLVE}${widenClause}${runningClause}${debugLogClause}`);
11494
10373
  }
11495
10374
  // ---------------------------------------------------------------------------
11496
10375
  // One exported command function per (tool, scope) pair — `tools.ts` dispatches on `scope`
@@ -11592,13 +10471,14 @@ async function batchProgress(params) {
11592
10471
  });
11593
10472
  }
11594
10473
  async function batchEnd(params) {
11595
- const { batchUrl, findings, keys, rootScope, mode, restart, deps } = params;
10474
+ const { batchUrl, findings, keys, rootScope, rootScopeOmitted, mode, restart, deps } = params;
11596
10475
  const scopeId = batchScopeId(batchUrl);
11597
10476
  await maybeDiscard(restart, 'batch', { batchUrl }, deps);
11598
10477
  await promoteAndRecordMode({ level: 'batch', scopeId, ctx: { batchUrl }, rootScope, mode, restart, keys, deps });
11599
10478
  const children = await batchChildren(batchUrl, keys, rootScope, mode, deps);
11600
10479
  const doneMessage = finalDoneMessage({
11601
- level: 'The whole batch',
10480
+ rootScope: 'batch',
10481
+ where: `batch ${batchUrl}`,
11602
10482
  findingsCount: findings.length,
11603
10483
  hasExampleLink: true,
11604
10484
  mentionEnvironment: true,
@@ -11610,6 +10490,7 @@ async function batchEnd(params) {
11610
10490
  toolName: EYES_REVIEW_TOOLS.end,
11611
10491
  scopeId,
11612
10492
  rootScope,
10493
+ rootScopeOmitted,
11613
10494
  ownChildren: children,
11614
10495
  finalize: verifyAndConsolidate(scopeId, batchScopeId(batchUrl), { batchUrl, findings }, findings, mode, deps),
11615
10496
  progressCall: reviewProgressCall('batch', { batchUrl }, rootScope, mode),
@@ -11618,13 +10499,17 @@ async function batchEnd(params) {
11618
10499
  doneMessage,
11619
10500
  deps,
11620
10501
  });
11621
- return endResponse(result, mode, result.next.instruction === doneMessage);
10502
+ return endResponse(result, mode);
11622
10503
  }
11623
10504
  async function scenarioProgress(params) {
11624
- const { batchUrl, scenarioName, keys, rootScope, mode, restart, deps } = params;
10505
+ const { batchUrl, scenarioName, keys, rootScope, rootScopeOmitted, mode, restart, deps } = params;
11625
10506
  const scopeId = scenarioScopeId(batchUrl, scenarioName);
10507
+ const retryCall = reviewProgressCall('scenario', { batchUrl, scenarioName }, rootScope, mode);
10508
+ const midWalk = checkRootlessMidWalk({ level: 'scenario', scopeId, rootScopeOmitted, retryCall, restart, deps });
10509
+ if (midWalk)
10510
+ return { completed: null, next: midWalk };
11626
10511
  await maybeDiscard(restart, 'scenario', { batchUrl, scenarioName }, deps);
11627
- const mismatch = checkParentModeMismatch('scenario', rootScope, batchScopeId(batchUrl), mode, reviewProgressCall('scenario', { batchUrl, scenarioName }, rootScope, mode), deps);
10512
+ const mismatch = checkParentModeMismatch('scenario', rootScope, batchScopeId(batchUrl), mode, retryCall, deps);
11628
10513
  if (mismatch)
11629
10514
  return { completed: null, next: mismatch };
11630
10515
  await promoteAndRecordMode({
@@ -11651,10 +10536,14 @@ async function scenarioProgress(params) {
11651
10536
  });
11652
10537
  }
11653
10538
  async function scenarioEnd(params) {
11654
- const { batchUrl, scenarioName, findings, keys, rootScope, mode, restart, deps } = params;
10539
+ const { batchUrl, scenarioName, findings, keys, rootScope, rootScopeOmitted, mode, restart, deps } = params;
11655
10540
  const scopeId = scenarioScopeId(batchUrl, scenarioName);
10541
+ const retryCall = reviewEndCall('scenario', { batchUrl, scenarioName, findings }, rootScope, mode);
10542
+ const midWalk = checkRootlessMidWalk({ level: 'scenario', scopeId, rootScopeOmitted, retryCall, restart, deps });
10543
+ if (midWalk)
10544
+ return { next: midWalk };
11656
10545
  await maybeDiscard(restart, 'scenario', { batchUrl, scenarioName }, deps);
11657
- const mismatch = checkParentModeMismatch('scenario', rootScope, batchScopeId(batchUrl), mode, reviewEndCall('scenario', { batchUrl, scenarioName, findings }, rootScope, mode), deps);
10546
+ const mismatch = checkParentModeMismatch('scenario', rootScope, batchScopeId(batchUrl), mode, retryCall, deps);
11658
10547
  if (mismatch)
11659
10548
  return { next: mismatch };
11660
10549
  await promoteAndRecordMode({
@@ -11669,7 +10558,8 @@ async function scenarioEnd(params) {
11669
10558
  });
11670
10559
  const children = await scenarioChildren(batchUrl, scenarioName, keys, rootScope, mode, deps);
11671
10560
  const doneMessage = finalDoneMessage({
11672
- level: 'This scenario',
10561
+ rootScope: 'scenario',
10562
+ where: `scenario "${scenarioName}"`,
11673
10563
  findingsCount: findings.length,
11674
10564
  hasExampleLink: true,
11675
10565
  mentionEnvironment: true,
@@ -11681,12 +10571,11 @@ async function scenarioEnd(params) {
11681
10571
  toolName: EYES_REVIEW_TOOLS.end,
11682
10572
  scopeId,
11683
10573
  rootScope,
10574
+ rootScopeOmitted,
11684
10575
  ownChildren: children,
11685
10576
  finalize: verifyAndConsolidate(scopeId, batchScopeId(batchUrl), { batchUrl, scenarioName, findings }, findings, mode, deps),
11686
10577
  progressCall: reviewProgressCall('scenario', { batchUrl, scenarioName }, rootScope, mode),
11687
- pushUpTo: hasReachedRootScope('scenario', rootScope)
11688
- ? undefined
11689
- : { parentScopeId: batchScopeId(batchUrl), childKey: scenarioChildKey(scenarioName) },
10578
+ pushUpTo: { parentScopeId: batchScopeId(batchUrl), childKey: scenarioChildKey(scenarioName) },
11690
10579
  getSiblings: async () => (await batchChildren(batchUrl, keys, rootScope, mode, deps)).filter(s => s.scopeId !== scopeId),
11691
10580
  descend: sibling => descentTarget('batch', { batchUrl }, sibling.key, rootScope, mode, deps),
11692
10581
  parentProgressCall: reviewProgressCall('batch', { batchUrl }, rootScope, mode),
@@ -11695,7 +10584,7 @@ async function scenarioEnd(params) {
11695
10584
  doneMessage,
11696
10585
  deps,
11697
10586
  });
11698
- return endResponse(result, mode, result.next.instruction === doneMessage);
10587
+ return endResponse(result, mode);
11699
10588
  }
11700
10589
  // ---------------------------------------------------------------------------
11701
10590
  // A queued session whose entity has genuinely stopped existing (deleted, merged, otherwise
@@ -11722,8 +10611,12 @@ function missingSessionFinding(sessionUrl) {
11722
10611
  };
11723
10612
  }
11724
10613
  async function sessionProgress(params) {
11725
- const { sessionUrl, keys, rootScope, mode, restart, deps } = params;
10614
+ const { sessionUrl, keys, rootScope, rootScopeOmitted, mode, restart, deps } = params;
11726
10615
  const scopeId = sessionScopeId(sessionUrl);
10616
+ const retryCall = reviewProgressCall('session', { sessionUrl }, rootScope, mode);
10617
+ const midWalk = checkRootlessMidWalk({ level: 'session', scopeId, rootScopeOmitted, retryCall, restart, deps });
10618
+ if (midWalk)
10619
+ return { completed: null, next: midWalk };
11727
10620
  await maybeDiscard(restart, 'session', { sessionUrl }, deps);
11728
10621
  // Fetched before computing children (rather than going through the sessionChildren wrapper,
11729
10622
  // which would fetch it again) so the mode gate below can run — and, on a mismatch, exit —
@@ -11745,7 +10638,7 @@ async function sessionProgress(params) {
11745
10638
  },
11746
10639
  };
11747
10640
  }
11748
- const mismatch = checkParentModeMismatch('session', rootScope, scenarioScopeIdForSession(sessionUrl, session.sessionName), mode, reviewProgressCall('session', { sessionUrl }, rootScope, mode), deps);
10641
+ const mismatch = checkParentModeMismatch('session', rootScope, scenarioScopeIdForSession(sessionUrl, session.sessionName), mode, retryCall, deps);
11749
10642
  if (mismatch)
11750
10643
  return { completed: null, next: mismatch };
11751
10644
  await promoteAndRecordMode({ level: 'session', scopeId, ctx: { sessionUrl }, rootScope, mode, restart, keys, deps });
@@ -11763,8 +10656,12 @@ async function sessionProgress(params) {
11763
10656
  });
11764
10657
  }
11765
10658
  async function sessionEnd(params) {
11766
- const { sessionUrl, findings, keys, rootScope, mode, restart, deps } = params;
10659
+ const { sessionUrl, findings, keys, rootScope, rootScopeOmitted, mode, restart, deps } = params;
11767
10660
  const scopeId = sessionScopeId(sessionUrl);
10661
+ const retryCall = reviewEndCall('session', { sessionUrl, findings }, rootScope, mode);
10662
+ const midWalk = checkRootlessMidWalk({ level: 'session', scopeId, rootScopeOmitted, retryCall, restart, deps });
10663
+ if (midWalk)
10664
+ return { next: midWalk };
11768
10665
  await maybeDiscard(restart, 'session', { sessionUrl }, deps);
11769
10666
  let session;
11770
10667
  try {
@@ -11784,13 +10681,14 @@ async function sessionEnd(params) {
11784
10681
  }
11785
10682
  const { baseUrl, batchId, accountId } = await parseSessionUrlVerified(sessionUrl, keys);
11786
10683
  const batchUrl = buildBatchUrl({ baseUrl, batchId, accountId });
11787
- const mismatch = checkParentModeMismatch('session', rootScope, scenarioScopeIdForSession(sessionUrl, session.sessionName), mode, reviewEndCall('session', { sessionUrl, findings }, rootScope, mode), deps);
10684
+ const mismatch = checkParentModeMismatch('session', rootScope, scenarioScopeIdForSession(sessionUrl, session.sessionName), mode, retryCall, deps);
11788
10685
  if (mismatch)
11789
10686
  return { next: mismatch };
11790
10687
  await promoteAndRecordMode({ level: 'session', scopeId, ctx: { sessionUrl }, rootScope, mode, restart, keys, deps });
11791
10688
  const children = await sessionStepChildren({ sessionUrl, session, mode, keys, deps });
11792
10689
  const doneMessage = finalDoneMessage({
11793
- level: 'This session',
10690
+ rootScope: 'session',
10691
+ where: `session ${sessionUrl}`,
11794
10692
  findingsCount: findings.length,
11795
10693
  hasExampleLink: true,
11796
10694
  mentionEnvironment: false,
@@ -11801,15 +10699,14 @@ async function sessionEnd(params) {
11801
10699
  toolName: EYES_REVIEW_TOOLS.end,
11802
10700
  scopeId,
11803
10701
  rootScope,
10702
+ rootScopeOmitted,
11804
10703
  ownChildren: children,
11805
10704
  finalize: verifyAndConsolidate(scopeId, sessionScopeId(sessionUrl), { sessionUrl, findings }, findings, mode, deps),
11806
10705
  progressCall: reviewProgressCall('session', { sessionUrl }, rootScope, mode),
11807
- pushUpTo: hasReachedRootScope('session', rootScope)
11808
- ? undefined
11809
- : {
11810
- parentScopeId: scenarioScopeIdForSession(sessionUrl, session.sessionName),
11811
- childKey: sessionChildKey(sessionUrl),
11812
- },
10706
+ pushUpTo: {
10707
+ parentScopeId: scenarioScopeIdForSession(sessionUrl, session.sessionName),
10708
+ childKey: sessionChildKey(sessionUrl),
10709
+ },
11813
10710
  getSiblings: async () => (await scenarioChildren(batchUrl, session.sessionName, keys, rootScope, mode, deps)).filter(s => s.scopeId !== scopeId),
11814
10711
  descend: sibling => descentTarget('scenario', { batchUrl, scenarioName: session.sessionName }, sibling.key, rootScope, mode, deps),
11815
10712
  parentProgressCall: reviewProgressCall('scenario', { batchUrl, scenarioName: session.sessionName }, rootScope, mode),
@@ -11818,7 +10715,7 @@ async function sessionEnd(params) {
11818
10715
  doneMessage,
11819
10716
  deps,
11820
10717
  });
11821
- return endResponse(result, mode, result.next.instruction === doneMessage);
10718
+ return endResponse(result, mode);
11822
10719
  }
11823
10720
  const DOM_DIFF_OBTAINABLE_RECORD = 'stepProgress:domDiffObtainable';
11824
10721
  /** Why this step can never yield a DOM diff, decided from session data ahead of any call; `fetchVisibleDomDiff`'s third case, `no-dom-data`, is only knowable from the server. */
@@ -11833,10 +10730,14 @@ function domDiffUnobtainableReason(step) {
11833
10730
  }
11834
10731
  async function stepProgress(params) {
11835
10732
  var _a, _b;
11836
- const { sessionUrl, stepIndex, keys, rootScope, mode, restart, deps } = params;
10733
+ const { sessionUrl, stepIndex, keys, rootScope, rootScopeOmitted, mode, restart, deps } = params;
11837
10734
  const scopeId = stepScopeId(sessionUrl, stepIndex);
10735
+ const retryCall = reviewProgressCall('step', { sessionUrl, stepIndex }, rootScope, mode);
10736
+ const midWalk = checkRootlessMidWalk({ level: 'step', scopeId, sessionUrl, rootScopeOmitted, retryCall, restart, deps });
10737
+ if (midWalk)
10738
+ return { completed: null, next: midWalk };
11838
10739
  await maybeDiscard(restart, 'step', { sessionUrl, stepIndex }, deps);
11839
- const mismatch = checkParentModeMismatch('step', rootScope, sessionScopeId(sessionUrl), mode, reviewProgressCall('step', { sessionUrl, stepIndex }, rootScope, mode), deps);
10740
+ const mismatch = checkParentModeMismatch('step', rootScope, sessionScopeId(sessionUrl), mode, retryCall, deps);
11840
10741
  if (mismatch)
11841
10742
  return { completed: null, next: mismatch };
11842
10743
  await promoteAndRecordMode({
@@ -11933,10 +10834,14 @@ function prependEvidenceRound(next, params) {
11933
10834
  next.instruction += ` ${unseen.length} of the ${remaining.length} areas left have no evidence yet: call ${EYES_INSPECT_TOOLS.evidence} ONCE with exactly the areaRects the first call in next.calls already carries — the other areas left already have theirs on record — then report all ${remaining.length} in the one ${EYES_REVIEW_TOOLS.diffReport} call.`;
11934
10835
  }
11935
10836
  async function stepEnd(params) {
11936
- const { sessionUrl, stepIndex, findings, keys, rootScope, mode, restart, deps } = params;
10837
+ const { sessionUrl, stepIndex, findings, keys, rootScope, rootScopeOmitted, mode, restart, deps } = params;
11937
10838
  const scopeId = stepScopeId(sessionUrl, stepIndex);
10839
+ const retryCall = reviewEndCall('step', { sessionUrl, stepIndex, findings }, rootScope, mode);
10840
+ const midWalk = checkRootlessMidWalk({ level: 'step', scopeId, sessionUrl, rootScopeOmitted, retryCall, restart, deps });
10841
+ if (midWalk)
10842
+ return { next: midWalk };
11938
10843
  await maybeDiscard(restart, 'step', { sessionUrl, stepIndex }, deps);
11939
- const mismatch = checkParentModeMismatch('step', rootScope, sessionScopeId(sessionUrl), mode, reviewEndCall('step', { sessionUrl, stepIndex, findings }, rootScope, mode), deps);
10844
+ const mismatch = checkParentModeMismatch('step', rootScope, sessionScopeId(sessionUrl), mode, retryCall, deps);
11940
10845
  if (mismatch)
11941
10846
  return { next: mismatch };
11942
10847
  await promoteAndRecordMode({
@@ -11961,7 +10866,8 @@ async function stepEnd(params) {
11961
10866
  let action = null;
11962
10867
  let resolution = emptyRollup().resolution;
11963
10868
  const doneMessage = finalDoneMessage({
11964
- level: 'This step',
10869
+ rootScope: 'step',
10870
+ where: `stepIndex ${stepIndex} of session ${sessionUrl}`,
11965
10871
  findingsCount: findings.length,
11966
10872
  hasExampleLink: true,
11967
10873
  mentionEnvironment: false,
@@ -11972,6 +10878,7 @@ async function stepEnd(params) {
11972
10878
  toolName: EYES_REVIEW_TOOLS.end,
11973
10879
  scopeId,
11974
10880
  rootScope,
10881
+ rootScopeOmitted,
11975
10882
  ownChildren: children,
11976
10883
  finalize: async () => {
11977
10884
  const childFindings = flattenChildFindings(scopeId, deps);
@@ -12009,9 +10916,7 @@ async function stepEnd(params) {
12009
10916
  return { findings: findingsWithExamples, rollup: { resolution, regions: rollup.regions } };
12010
10917
  },
12011
10918
  progressCall: reviewProgressCall('step', { sessionUrl, stepIndex }, rootScope, mode),
12012
- pushUpTo: hasReachedRootScope('step', rootScope)
12013
- ? undefined
12014
- : { parentScopeId: sessionScopeId(sessionUrl), childKey: stepChildKey(stepIndex) },
10919
+ pushUpTo: { parentScopeId: sessionScopeId(sessionUrl), childKey: stepChildKey(stepIndex) },
12015
10920
  getSiblings: async () => (await sessionChildren({ sessionUrl, keys, mode, deps })).filter(s => s.scopeId !== scopeId),
12016
10921
  descend: sibling => descentTarget('session', { sessionUrl }, sibling.key, rootScope, mode, deps),
12017
10922
  parentProgressCall: reviewProgressCall('session', { sessionUrl }, rootScope, mode),
@@ -12030,13 +10935,10 @@ async function stepEnd(params) {
12030
10935
  doneMessage,
12031
10936
  deps,
12032
10937
  });
12033
- // Captured before describeStepOutcome appends its own sentence below — otherwise the
12034
- // instruction would no longer match `doneMessage` verbatim even at the true rootScope.
12035
- const isRootScope = result.next.instruction === doneMessage;
12036
10938
  if (result.persisted && mode === 'resolve') {
12037
10939
  result.next.instruction += ` ${describeStepOutcome(action, resolution)}`;
12038
10940
  }
12039
- return endResponse(result, mode, isRootScope);
10941
+ return endResponse(result, mode);
12040
10942
  }
12041
10943
  async function diffReport(params) {
12042
10944
  const { sessionUrl, stepIndex, areaRect, findings, sameAs, keys, rootScope, mode, restart, groupIndex, deps } = params;
@@ -12049,7 +10951,6 @@ async function diffReport(params) {
12049
10951
  level: 'diff',
12050
10952
  scopeId,
12051
10953
  ctx: { sessionUrl, stepIndex, areaRect },
12052
- rootScope,
12053
10954
  mode,
12054
10955
  restart,
12055
10956
  keys,
@@ -12092,9 +10993,7 @@ async function diffReport(params) {
12092
10993
  };
12093
10994
  },
12094
10995
  progressCall: reviewProgressCall('step', { sessionUrl, stepIndex }, rootScope, mode),
12095
- pushUpTo: hasReachedRootScope('diff', rootScope)
12096
- ? undefined
12097
- : { parentScopeId: stepScopeId(sessionUrl, stepIndex), childKey: diffChildKey(areaRect) },
10996
+ pushUpTo: { parentScopeId: stepScopeId(sessionUrl, stepIndex), childKey: diffChildKey(areaRect) },
12098
10997
  getSiblings: async () => (await stepChildren(sessionUrl, stepIndex, keys, deps)).filter(s => s.scopeId !== scopeId),
12099
10998
  descend: sibling => descentTarget('step', { sessionUrl, stepIndex }, sibling.key, rootScope, mode, deps),
12100
10999
  parentProgressCall: reviewProgressCall('step', { sessionUrl, stepIndex }, rootScope, mode),
@@ -12108,7 +11007,19 @@ async function diffReport(params) {
12108
11007
  // Sequential, not verify-all-then-apply-all: an entry may `sameAs` an area an earlier entry of this same call recorded, and in resolve mode its mask gate re-reads the regions earlier entries applied.
12109
11008
  async function diffReportBatch(params) {
12110
11009
  var _a, _b;
12111
- const { sessionUrl, stepIndex, reports, keys, rootScope, mode, restart, deps } = params;
11010
+ const { sessionUrl, stepIndex, reports, keys, rootScope, rootScopeOmitted, mode, restart, deps } = params;
11011
+ const scopeId = stepScopeId(sessionUrl, stepIndex);
11012
+ const midWalk = checkRootlessMidWalk({
11013
+ level: 'diff',
11014
+ scopeId,
11015
+ sessionUrl,
11016
+ rootScopeOmitted,
11017
+ retryCall: nextCall(EYES_REVIEW_TOOLS.diffReport, { sessionUrl, stepIndex, reports }, rootScope, mode),
11018
+ restart,
11019
+ deps,
11020
+ });
11021
+ if (midWalk)
11022
+ return { groups: [], next: midWalk };
12112
11023
  const groups = [];
12113
11024
  let last;
12114
11025
  for (const [groupIndex, report] of reports.entries()) {
@@ -12193,8 +11104,8 @@ async function batchStopMessage(params) {
12193
11104
  // completeness live on every call; `eyes_review_end` persists findings once complete, pushing them
12194
11105
  // up into its parent's own accumulated record so they survive a child later dropping out of its
12195
11106
  // parent's live-children set; `rootScope` bounds how far `next` ever escalates, so a request scoped to
12196
- // one entity never spills into its siblings or ancestors; `mode` decides whether the traversal also
12197
- // resolves what it reports.
11107
+ // one entity never leads the model into its siblings or ancestors — it never decides whether findings
11108
+ // are pushed up; `mode` decides whether the traversal also resolves what it reports.
12198
11109
  //
12199
11110
  // This is a thin registration layer over `commands.ts`, in the same shape as
12200
11111
  // `eyes-inspect/tools.ts`/`eyes-resolve/tools.ts`: Zod schemas, descriptions, and handlers that
@@ -12287,9 +11198,15 @@ async function resolveJsonArg(raw, argName) {
12287
11198
  function recordReviewCall(scopeType, mode) {
12288
11199
  recordToolTelemetry({ chain_source: 'review', scope_type: scopeType, mode });
12289
11200
  }
12290
- /** The 5 args every scope's own arm passes identically, once its own id(s) are resolved. */
12291
- function commonArgs(url, rootScope, mode, restart, deps) {
12292
- return { keys: reviewApiKeyProvider(url, mode), rootScope, mode, restart, deps };
11201
+ /** The args every scope's own arm passes identically, once its own id(s) are resolved. */
11202
+ function commonArgs(url, rootScope, rootScopeOmitted, mode, restart, deps) {
11203
+ return { keys: reviewApiKeyProvider(url, mode), rootScope, rootScopeOmitted, mode, restart, deps };
11204
+ }
11205
+ /** `review` leads every review-family response so `next` stays the last key; an `_end` at its root supplies `reachedRoot`/`widen`/`enclosing`. */
11206
+ function withReviewField(result, scope, rootScope, mode) {
11207
+ const { review: atRoot, ...rest } = result;
11208
+ const review = { rootScope, mode, scope, reachedRoot: false, ...atRoot };
11209
+ return { review, ...rest };
12293
11210
  }
12294
11211
  function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
12295
11212
  server.registerTool(EYES_REVIEW_TOOLS.progress, {
@@ -12303,13 +11220,14 @@ function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
12303
11220
  },
12304
11221
  }, async ({ scope, batchUrl, scenarioName, sessionUrl, stepIndex, rootScope: rawRootScope, mode: rawMode, restart }) => {
12305
11222
  const rootScope = resolveRootScope(scope, rawRootScope);
11223
+ const rootScopeOmitted = rawRootScope === undefined;
12306
11224
  const mode = resolveMode(rawMode);
12307
11225
  recordReviewCall(scope, mode);
12308
11226
  const result = await (async () => {
12309
11227
  switch (scope) {
12310
11228
  case 'batch': {
12311
11229
  const url = requireId(batchUrl, 'batchUrl', scope);
12312
- return batchProgress({ batchUrl: url, ...commonArgs(url, rootScope, mode, restart, deps) });
11230
+ return batchProgress({ batchUrl: url, ...commonArgs(url, rootScope, rootScopeOmitted, mode, restart, deps) });
12313
11231
  }
12314
11232
  case 'scenario': {
12315
11233
  const url = requireId(batchUrl, 'batchUrl', scope);
@@ -12317,12 +11235,15 @@ function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
12317
11235
  return scenarioProgress({
12318
11236
  batchUrl: url,
12319
11237
  scenarioName: name,
12320
- ...commonArgs(url, rootScope, mode, restart, deps),
11238
+ ...commonArgs(url, rootScope, rootScopeOmitted, mode, restart, deps),
12321
11239
  });
12322
11240
  }
12323
11241
  case 'session': {
12324
11242
  const url = requireId(sessionUrl, 'sessionUrl', scope);
12325
- return sessionProgress({ sessionUrl: url, ...commonArgs(url, rootScope, mode, restart, deps) });
11243
+ return sessionProgress({
11244
+ sessionUrl: url,
11245
+ ...commonArgs(url, rootScope, rootScopeOmitted, mode, restart, deps),
11246
+ });
12326
11247
  }
12327
11248
  case 'step': {
12328
11249
  const url = requireId(sessionUrl, 'sessionUrl', scope);
@@ -12330,12 +11251,12 @@ function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
12330
11251
  return stepProgress({
12331
11252
  sessionUrl: url,
12332
11253
  stepIndex: index,
12333
- ...commonArgs(url, rootScope, mode, restart, deps),
11254
+ ...commonArgs(url, rootScope, rootScopeOmitted, mode, restart, deps),
12334
11255
  });
12335
11256
  }
12336
11257
  }
12337
11258
  })();
12338
- return textResult(JSON.stringify(result, null, 2));
11259
+ return textResult(JSON.stringify(withReviewField(result, scope, rootScope, mode), null, 2));
12339
11260
  });
12340
11261
  server.registerTool(EYES_REVIEW_TOOLS.end, {
12341
11262
  description: END_DESC,
@@ -12349,6 +11270,7 @@ function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
12349
11270
  },
12350
11271
  }, async ({ scope, batchUrl, scenarioName, sessionUrl, stepIndex, findings: rawFindingsArg, rootScope: rawRootScope, mode: rawMode, restart, }) => {
12351
11272
  const rootScope = resolveRootScope(scope, rawRootScope);
11273
+ const rootScopeOmitted = rawRootScope === undefined;
12352
11274
  const mode = resolveMode(rawMode);
12353
11275
  recordReviewCall(scope, mode);
12354
11276
  const rawFindings = await resolveJsonArg(rawFindingsArg, 'findings');
@@ -12360,7 +11282,7 @@ function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
12360
11282
  return batchEnd({
12361
11283
  batchUrl: url,
12362
11284
  findings: summaryFindings(),
12363
- ...commonArgs(url, rootScope, mode, restart, deps),
11285
+ ...commonArgs(url, rootScope, rootScopeOmitted, mode, restart, deps),
12364
11286
  });
12365
11287
  }
12366
11288
  case 'scenario': {
@@ -12370,7 +11292,7 @@ function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
12370
11292
  batchUrl: url,
12371
11293
  scenarioName: name,
12372
11294
  findings: summaryFindings(),
12373
- ...commonArgs(url, rootScope, mode, restart, deps),
11295
+ ...commonArgs(url, rootScope, rootScopeOmitted, mode, restart, deps),
12374
11296
  });
12375
11297
  }
12376
11298
  case 'session': {
@@ -12378,7 +11300,7 @@ function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
12378
11300
  return sessionEnd({
12379
11301
  sessionUrl: url,
12380
11302
  findings: summaryFindings(),
12381
- ...commonArgs(url, rootScope, mode, restart, deps),
11303
+ ...commonArgs(url, rootScope, rootScopeOmitted, mode, restart, deps),
12382
11304
  });
12383
11305
  }
12384
11306
  case 'step': {
@@ -12389,12 +11311,12 @@ function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
12389
11311
  sessionUrl: url,
12390
11312
  stepIndex: index,
12391
11313
  findings: stepFindings,
12392
- ...commonArgs(url, rootScope, mode, restart, deps),
11314
+ ...commonArgs(url, rootScope, rootScopeOmitted, mode, restart, deps),
12393
11315
  });
12394
11316
  }
12395
11317
  }
12396
11318
  })();
12397
- return textResult(JSON.stringify(result, null, 2));
11319
+ return textResult(JSON.stringify(withReviewField(result, scope, rootScope, mode), null, 2));
12398
11320
  });
12399
11321
  // --- Diff (leaf) -------------------------------------------------------------
12400
11322
  server.registerTool(EYES_REVIEW_TOOLS.diffReport, {
@@ -12409,32 +11331,33 @@ function registerReviewTools(server, deps = defaultPhaseTrackerDeps) {
12409
11331
  },
12410
11332
  }, async ({ sessionUrl, stepIndex, reports: rawReportsArg, rootScope: rawRootScope, mode: rawMode, restart }) => {
12411
11333
  const rootScope = resolveRootScope('diff', rawRootScope);
11334
+ const rootScopeOmitted = rawRootScope === undefined;
12412
11335
  const mode = resolveMode(rawMode);
12413
11336
  recordReviewCall('diff', mode);
12414
11337
  const keys = reviewApiKeyProvider(sessionUrl, mode);
12415
11338
  const rawReports = await resolveJsonArg(rawReportsArg, 'reports');
12416
11339
  const reports = parseResolvedArg(DiffReportsShape, rawReports, 'reports');
12417
- const result = await diffReportBatch({ sessionUrl, stepIndex, reports, keys, rootScope, mode, restart, deps });
12418
- return textResult(JSON.stringify(result, null, 2));
11340
+ const result = await diffReportBatch({
11341
+ sessionUrl,
11342
+ stepIndex,
11343
+ reports,
11344
+ keys,
11345
+ rootScope,
11346
+ rootScopeOmitted,
11347
+ mode,
11348
+ restart,
11349
+ deps,
11350
+ });
11351
+ return textResult(JSON.stringify(withReviewField(result, 'diff', rootScope, mode), null, 2));
12419
11352
  });
12420
11353
  }
12421
11354
 
12422
- /** The tool swap the guard env controls — the single authority on what registers in each mode. */
12423
- const EXPERIMENTAL_TOOL_SWAP = {
12424
- // Registered ONLY in experimental mode (skipped otherwise). Derived from the family name maps
12425
- // — not hand-copied — so a newly added family tool can't silently bypass the gate.
12426
- experimentalOnly: [EYES_INSPECT_TOOLS, EYES_RESOLVE_TOOLS, EYES_REVIEW_TOOLS].flatMap(family => Object.values(family)),
12427
- // Hidden IN experimental mode: the legacy results tools the families replace. Runtime-hidden
12428
- // rather than deleted (see `.team-lead/plan-remove-legacy-results-tools.md` for the eventual
12429
- // removal) so the default server keeps its published tool set untouched.
12430
- replacedByExperimental: [
12431
- TOOL_NAMES.EYES_GET_BATCH_URL,
12432
- TOOL_NAMES.EYES_FETCH_VISUAL_RESULTS,
12433
- TOOL_NAMES.EYES_ANALYZE_BATCH,
12434
- ],
12435
- };
11355
+ /** Derived from the family name maps — not hand-copied — so a newly added family tool can't be missed. */
11356
+ const FAMILY_TOOL_NAMES = [EYES_INSPECT_TOOLS, EYES_RESOLVE_TOOLS, EYES_REVIEW_TOOLS].flatMap(family => Object.values(family));
11357
+ /** Tools registered only in experimental mode (`EXPERIMENTAL_ENV`). Add a name here to ship a tool behind the flag. */
11358
+ const EXPERIMENTAL_TOOLS = [];
12436
11359
  function skippedToolNames(experimental) {
12437
- return new Set(EXPERIMENTAL_TOOL_SWAP.replacedByExperimental );
11360
+ return new Set(experimental ? [] : EXPERIMENTAL_TOOLS);
12438
11361
  }
12439
11362
  function filteredRegistrar(inner, skipped) {
12440
11363
  const registerTool = (name, config, handler) => {
@@ -12445,20 +11368,15 @@ function filteredRegistrar(inner, skipped) {
12445
11368
  return { registerTool };
12446
11369
  }
12447
11370
  /**
12448
- * Registers the server's tool set for the mode chosen at process start. Everything registers
12449
- * through one name filter fed by `skippedToolNames`, so `EXPERIMENTAL_TOOL_SWAP` is the only
12450
- * place that decides which tools each mode exposes.
11371
+ * Registers the server's tool set for the mode chosen at process start: the native tools plus the
11372
+ * three tool families, minus whatever `skippedToolNames` hides in this mode.
12451
11373
  */
12452
11374
  function registerAllTools(server, experimental) {
12453
- const skipped = skippedToolNames();
11375
+ const skipped = skippedToolNames(experimental);
12454
11376
  Object.values(ALL_TOOLS).forEach(tool => {
12455
11377
  if (skipped.has(tool.name))
12456
11378
  return;
12457
- server.registerTool(tool.name, {
12458
- description: tool.description,
12459
- inputSchema: tool.inputSchema,
12460
- ...('outputSchema' in tool && tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),
12461
- }, tool.handler);
11379
+ server.registerTool(tool.name, { description: tool.description, inputSchema: tool.inputSchema }, tool.handler);
12462
11380
  });
12463
11381
  // The families register themselves; the instrumented registrar gives their handlers the same
12464
11382
  // createToolHandler wrapping as the tools above, and the filter drops the skipped names.
@@ -12466,19 +11384,17 @@ function registerAllTools(server, experimental) {
12466
11384
  registerEyesInspectDataTools(registrar);
12467
11385
  registerEyesResolveTools(registrar);
12468
11386
  registerReviewTools(registrar);
12469
- // A resource, not a tool — outside the name-based swap, so it stays gated by the mode directly.
12470
11387
  registerEyesInspectResources(server);
12471
11388
  }
12472
- /** Derived from the same swap structure as registration, so the startup log can't drift. */
11389
+ /** Derived from the same name sources as registration, so the startup log can't drift. */
12473
11390
  function registeredToolNames(experimental) {
12474
- const skipped = skippedToolNames();
12475
- return [...Object.values(TOOL_NAMES), ...EXPERIMENTAL_TOOL_SWAP.experimentalOnly].filter(name => !skipped.has(name));
11391
+ const skipped = skippedToolNames(experimental);
11392
+ return [...Object.values(TOOL_NAMES), ...FAMILY_TOOL_NAMES].filter(name => !skipped.has(name));
12476
11393
  }
12477
11394
 
12478
11395
  async function startServer() {
12479
11396
  loadEnvOnce(process.cwd(), 'server startup');
12480
- const experimental = parseExperimental();
12481
- setExperimental(experimental);
11397
+ const experimental = parseExperimental(process.env);
12482
11398
  const server = new mcp_js.McpServer({
12483
11399
  name: 'applitools-mcp',
12484
11400
  version: packageJson.version,
@@ -12540,7 +11456,7 @@ async function startServer() {
12540
11456
  .catch(error => log$2('debug', '[MCP Server] roots/list failed:', error));
12541
11457
  }
12542
11458
  };
12543
- registerAllTools(server);
11459
+ registerAllTools(server, experimental);
12544
11460
  server.registerResource('documentation', RESOURCE_URIS.DOCUMENTATION_README, {
12545
11461
  title: RESOURCE_METADATA.DOCUMENTATION_README.title,
12546
11462
  description: RESOURCE_METADATA.DOCUMENTATION_README.description,
@@ -12563,8 +11479,8 @@ async function startServer() {
12563
11479
  const transport = new stdio_js.StdioServerTransport();
12564
11480
  await server.connect(transport);
12565
11481
  log$2('info', '[MCP Server] Applitools MCP Server started successfully (Stdio Mode)');
12566
- log$2('info', `[MCP Server] Experimental tools ${'enabled' }`);
12567
- log$2('info', `[MCP Server] Available tools: ${registeredToolNames().join(', ')}`);
11482
+ log$2('info', `[MCP Server] Experimental tools ${experimental ? 'enabled' : 'disabled'}`);
11483
+ log$2('info', `[MCP Server] Available tools: ${registeredToolNames(experimental).join(', ')}`);
12568
11484
  log$2('info', `[MCP Server] Available resources: documentation (${RESOURCE_URIS.DOCUMENTATION_README})`);
12569
11485
  }
12570
11486
  process.on('SIGINT', () => {