@applitools/mcp 0.10.4 → 0.10.5

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
@@ -8,8 +8,8 @@ var promises = require('node:fs/promises');
8
8
  var path = require('node:path');
9
9
  var logger$1 = require('@applitools/logger');
10
10
  var coreBase = require('@applitools/core-base');
11
- var fs = require('node:fs');
12
11
  var dotenv = require('dotenv');
12
+ var fs = require('node:fs');
13
13
  var os = require('node:os');
14
14
  var crypto = require('node:crypto');
15
15
  var req = require('@applitools/req');
@@ -38,8 +38,8 @@ function _interopNamespaceDefault(e) {
38
38
  }
39
39
 
40
40
  var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
41
- var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
42
41
  var dotenv__namespace = /*#__PURE__*/_interopNamespaceDefault(dotenv);
42
+ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
43
43
  var os__namespace = /*#__PURE__*/_interopNamespaceDefault(os);
44
44
  var crypto__namespace = /*#__PURE__*/_interopNamespaceDefault(crypto);
45
45
  var zlib__namespace = /*#__PURE__*/_interopNamespaceDefault(zlib);
@@ -66,555 +66,252 @@ const RESOURCE_METADATA = {
66
66
  },
67
67
  };
68
68
 
69
- function loadEnvFile(workingDirectory) {
70
- const envPath = path__namespace.join(workingDirectory, '.env');
71
- if (!fs__namespace.existsSync(envPath)) {
72
- return {};
73
- }
74
- try {
75
- const content = fs__namespace.readFileSync(envPath, 'utf-8');
76
- const lines = content.split('\n');
77
- let apiKey;
78
- let serverUrl;
79
- for (const line of lines) {
80
- const trimmed = line.trim();
81
- // Skip empty lines and comments
82
- if (!trimmed || trimmed.startsWith('#')) {
83
- continue;
84
- }
85
- // Parse KEY=VALUE
86
- const match = trimmed.match(/^([^=]+)=(.*)$/);
87
- if (!match)
88
- continue;
89
- const key = match[1].trim();
90
- let value = match[2].trim();
91
- // Remove quotes if present
92
- if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
93
- value = value.slice(1, -1);
94
- }
95
- if (key === 'APPLITOOLS_API_KEY' && value) {
96
- apiKey = value;
97
- }
98
- else if (key === 'APPLITOOLS_SERVER_URL' && value) {
99
- serverUrl = value;
100
- }
101
- }
102
- if (apiKey) {
103
- return { apiKey, serverUrl, foundIn: '.env' };
104
- }
105
- }
106
- catch {
107
- // Silently ignore errors reading .env
108
- }
109
- return {};
110
- }
111
69
  /**
112
- * Helper to resolve environment variable references in config files
113
- * Checks if the content references an env var, then resolves from process.env or .env file
70
+ * Wraps already-resolved key strings. A getter throws a clear error if its key wasn't supplied —
71
+ * e.g. a write key deliberately withheld when building a provider for a read-only call — rather
72
+ * than returning `undefined` and letting a missing credential fail confusingly further down.
114
73
  */
115
- function resolveEnvVarFromContent(content, envVarName, workingDirectory) {
116
- // Check if content references the environment variable (with or without process.env prefix)
117
- const patterns = [
118
- new RegExp(`process\\.env\\.${envVarName}`, 'i'),
119
- new RegExp(`${envVarName}(?!['"])`, 'i'), // Bare reference (not in quotes)
120
- ];
121
- const hasReference = patterns.some(pattern => pattern.test(content));
122
- if (!hasReference) {
123
- return undefined;
74
+ class StaticApiKeyProvider {
75
+ keys;
76
+ constructor(keys) {
77
+ this.keys = keys;
124
78
  }
125
- // Try to resolve the value: first from process.env, then from .env file
126
- const envValue = process.env[envVarName];
127
- if (envValue) {
128
- return envValue;
79
+ getReadKey() {
80
+ return this.require('readKey', 'read');
129
81
  }
130
- // Fallback to .env file
131
- const envResult = loadEnvFile(workingDirectory);
132
- if (envVarName === 'APPLITOOLS_API_KEY') {
133
- return envResult.apiKey;
82
+ getWriteKey() {
83
+ return this.require('writeKey', 'write');
134
84
  }
135
- else if (envVarName === 'APPLITOOLS_SERVER_URL') {
136
- return envResult.serverUrl;
85
+ getRunKey() {
86
+ return this.require('runKey', 'run');
137
87
  }
138
- return undefined;
139
- }
140
- function loadConfigFile(configPath, fileName, workingDirectory) {
141
- if (!fs__namespace.existsSync(configPath)) {
142
- return {};
88
+ require(field, label) {
89
+ const key = this.keys[field];
90
+ if (key === undefined)
91
+ throw new Error(`No ${label} API key is available for this call.`);
92
+ return key;
143
93
  }
144
- try {
145
- const content = fs__namespace.readFileSync(configPath, 'utf-8');
146
- // Search for apiKey and serverUrl in the file content
147
- let apiKey;
148
- let serverUrl;
149
- // Pattern 1: apiKey: 'value' or apiKey: "value" (hardcoded values)
150
- const apiKeyMatch = content.match(/apiKey\s*:\s*['"]([^'"]+)['"]/i);
151
- if (apiKeyMatch) {
152
- apiKey = apiKeyMatch[1];
153
- }
154
- // Pattern 2: serverUrl: 'value' or serverUrl: "value" (hardcoded values)
155
- const serverUrlMatch = content.match(/serverUrl\s*:\s*['"]([^'"]+)['"]/i);
156
- if (serverUrlMatch) {
157
- serverUrl = serverUrlMatch[1];
158
- }
159
- // Pattern 3: Resolve environment variable references in config file
160
- if (!apiKey) {
161
- apiKey = resolveEnvVarFromContent(content, 'APPLITOOLS_API_KEY', workingDirectory);
94
+ }
95
+
96
+ const defaultLoadEnvDeps = {
97
+ existsSync: fs__namespace.existsSync,
98
+ configDotenv: ({ path }) => {
99
+ try {
100
+ return { parsed: dotenv__namespace.parse(fs__namespace.readFileSync(path)) };
162
101
  }
163
- if (!serverUrl) {
164
- serverUrl = resolveEnvVarFromContent(content, 'APPLITOOLS_SERVER_URL', workingDirectory);
102
+ catch {
103
+ return {};
165
104
  }
166
- if (apiKey) {
167
- return { apiKey, serverUrl, foundIn: fileName };
105
+ },
106
+ };
107
+ /** The variables `loadEnvFromCwd` reads from a `.env`: the keys and the server URL the Eyes tools use. */
108
+ const WORKSPACE_ENV_NAMES = [
109
+ 'APPLITOOLS_API_KEY',
110
+ 'APPLITOOLS_READ_KEY',
111
+ 'APPLITOOLS_WRITE_KEY',
112
+ 'APPLITOOLS_SERVER_URL',
113
+ ];
114
+ /** The nearest `.env` up from `startDir` that defines any of `WORKSPACE_ENV_NAMES`; never writes `process.env`. */
115
+ function loadEnvFromCwd(startDir = process.cwd(), deps = defaultLoadEnvDeps) {
116
+ let dir = startDir;
117
+ while (true) {
118
+ const envPath = path__namespace.join(dir, '.env');
119
+ if (deps.existsSync(envPath)) {
120
+ const result = deps.configDotenv({ path: envPath });
121
+ const parsed = Object.fromEntries(WORKSPACE_ENV_NAMES.flatMap(name => (result?.parsed?.[name] ? [[name, result.parsed[name]]] : [])));
122
+ if (Object.keys(parsed).length)
123
+ return { path: envPath, parsed };
168
124
  }
125
+ const parent = path__namespace.dirname(dir);
126
+ if (parent === dir)
127
+ return undefined;
128
+ dir = parent;
169
129
  }
170
- catch {
171
- // Silently ignore errors reading config file
172
- }
173
- return {};
174
130
  }
175
- function findApiKey(workingDirectory = process.cwd()) {
176
- // Define config file patterns to check (in priority order)
177
- const configFiles = [
178
- // Applitools config files
179
- { name: 'applitools.config.js', path: path__namespace.join(workingDirectory, 'applitools.config.js') },
180
- { name: 'applitools.config.cjs', path: path__namespace.join(workingDirectory, 'applitools.config.cjs') },
181
- { name: 'applitools.config.mjs', path: path__namespace.join(workingDirectory, 'applitools.config.mjs') },
182
- { name: 'applitools.config.ts', path: path__namespace.join(workingDirectory, 'applitools.config.ts') },
183
- // Playwright config files
184
- { name: 'playwright.config.js', path: path__namespace.join(workingDirectory, 'playwright.config.js') },
185
- { name: 'playwright.config.cjs', path: path__namespace.join(workingDirectory, 'playwright.config.cjs') },
186
- { name: 'playwright.config.mjs', path: path__namespace.join(workingDirectory, 'playwright.config.mjs') },
187
- { name: 'playwright.config.ts', path: path__namespace.join(workingDirectory, 'playwright.config.ts') },
188
- ];
189
- // 1. Check each config file in order (config files have priority over .env)
190
- for (const config of configFiles) {
191
- const result = loadConfigFile(config.path, config.name, workingDirectory);
192
- if (result.apiKey) {
193
- return result;
131
+
132
+ const RETRYABLE_CODES = new Set(['EBUSY', 'EPERM', 'EACCES', 'EAGAIN']);
133
+ const RETRY_ATTEMPTS = 5;
134
+ const RETRY_BASE_DELAY_MS = 20;
135
+ /**
136
+ * A synchronous blocking sleep (`Atomics.wait` against a throwaway shared buffer) — matches
137
+ * the rest of this codebase's synchronous fs style (`fs.readFileSync`/`writeFileSync`
138
+ * throughout `commands.ts`), rather than forcing every phase-tracker call to be async merely
139
+ * to await a short backoff delay.
140
+ */
141
+ function busyWaitSleep(ms) {
142
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
143
+ }
144
+ const defaultPhaseTrackerDeps = {
145
+ readFile: p => (fs__namespace.existsSync(p) ? fs__namespace.readFileSync(p, 'utf8') : null),
146
+ writeFile: (p, contents) => fs__namespace.writeFileSync(p, contents),
147
+ appendFile: (p, contents) => fs__namespace.appendFileSync(p, contents),
148
+ deleteFile: p => fs__namespace.rmSync(p, { force: true }),
149
+ mkdir: dir => fs__namespace.mkdirSync(dir, { recursive: true }),
150
+ sleep: busyWaitSleep,
151
+ stateDir: path__namespace.join(os__namespace.tmpdir(), 'eyes-resolve'),
152
+ };
153
+ /**
154
+ * Retries `fn` on a transient file-lock error (a momentarily-locked file must never crash a
155
+ * workflow call — see `lib.md`), with a short exponential backoff between attempts. Any other
156
+ * error (including a non-`Error` throw with no `.code`) propagates immediately, unretried.
157
+ */
158
+ function withRetry(fn, deps) {
159
+ for (let attempt = 0;; attempt++) {
160
+ try {
161
+ return fn();
162
+ }
163
+ catch (error) {
164
+ const code = error?.code;
165
+ if (attempt >= RETRY_ATTEMPTS - 1 || !code || !RETRYABLE_CODES.has(code))
166
+ throw error;
167
+ deps.sleep(RETRY_BASE_DELAY_MS * 2 ** attempt);
194
168
  }
195
169
  }
196
- // 2. Check .env file as fallback
197
- const envResult = loadEnvFile(workingDirectory);
198
- if (envResult.apiKey) {
199
- return envResult;
200
- }
201
- // 3. Check environment variables as final fallback
202
- const envApiKey = process.env.APPLITOOLS_API_KEY;
203
- const envServerUrl = process.env.APPLITOOLS_SERVER_URL;
204
- if (envApiKey) {
205
- return {
206
- apiKey: envApiKey,
207
- serverUrl: envServerUrl,
208
- foundIn: 'environment variable',
209
- };
210
- }
211
- // Not found
212
- return {};
213
170
  }
214
-
215
- let currentClientInfo = undefined;
216
- let currentCredentials = undefined;
217
- let ide = undefined;
218
- function setClientInfo(clientInfo) {
219
- currentClientInfo = clientInfo;
171
+ function hashId(id) {
172
+ return crypto__namespace.createHash('sha256').update(id).digest('hex');
220
173
  }
221
- function getClientInfo() {
222
- return currentClientInfo;
174
+ // path.posix.join/dirname (not path.join/dirname) so the result is deterministic across
175
+ // platforms — Node's fs APIs accept forward slashes on Windows too (same convention as
176
+ // `api/fs-cache.ts`'s `cacheFilePath`).
177
+ function recordPath(deps, kind, id) {
178
+ return path__namespace.posix.join(deps.stateDir, kind, `${hashId(id)}.json`);
223
179
  }
224
- function setCredentials(credentials) {
225
- currentCredentials = credentials;
180
+ function readJson(deps, filePath) {
181
+ const contents = withRetry(() => deps.readFile(filePath), deps);
182
+ return contents === null ? undefined : JSON.parse(contents);
226
183
  }
227
- function getCredentials() {
228
- return currentCredentials;
184
+ function writeJson(deps, filePath, value) {
185
+ withRetry(() => deps.mkdir(path__namespace.posix.dirname(filePath)), deps);
186
+ withRetry(() => deps.writeFile(filePath, JSON.stringify(value)), deps);
229
187
  }
230
- function setIDE(ideName) {
231
- ide = ideName;
188
+ /** The recorded completion for `id`, or `undefined` if `<level>_end` was never (successfully) called for it. */
189
+ function getCompletion(id, deps = defaultPhaseTrackerDeps) {
190
+ return readJson(deps, recordPath(deps, 'completions', id));
232
191
  }
233
- function getIDE() {
234
- return ide;
192
+ function isCompleted(id, deps = defaultPhaseTrackerDeps) {
193
+ return getCompletion(id, deps) !== undefined;
235
194
  }
236
- function parseIDE(env, argv) {
237
- var _a;
238
- return env['ide'] || ((_a = argv.find(arg => arg.startsWith('--ide='))) === null || _a === void 0 ? void 0 : _a.split('=')[1]) || 'unknown';
195
+ /**
196
+ * Persists `payload` as `id`'s completion, stamped with the current time — overwriting
197
+ * whatever was recorded for `id` before, so revising a summary (or refreshing a stale
198
+ * completion) is just calling this again.
199
+ */
200
+ function recordCompletion(id, payload, deps = defaultPhaseTrackerDeps) {
201
+ const completion = { payload, completedAt: new Date().toISOString() };
202
+ writeJson(deps, recordPath(deps, 'completions', id), completion);
203
+ return completion;
239
204
  }
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());
205
+ /** `parentId`'s full accumulated child-findings record, read as-is with no live-data filtering. `{}` if no child has ever reported into it. */
206
+ function getChildFindings(parentId, deps = defaultPhaseTrackerDeps) {
207
+ return readJson(deps, recordPath(deps, 'child-findings', parentId)) ?? {};
244
208
  }
245
-
246
- /** Load credentials from server context, config files, or environment variables */
247
- function loadCredentials(workingDirectory) {
248
- const storedCredentials = getCredentials();
249
- if ((storedCredentials === null || storedCredentials === void 0 ? void 0 : storedCredentials.apiKey) && (storedCredentials === null || storedCredentials === void 0 ? void 0 : storedCredentials.serverUrl)) {
250
- return {
251
- apiKey: storedCredentials.apiKey,
252
- serverUrl: storedCredentials.serverUrl,
253
- source: 'server-context',
254
- };
255
- }
256
- const workingDir = workingDirectory || process.cwd();
257
- const configResult = findApiKey(workingDir);
258
- const apiKey = configResult.apiKey;
259
- const serverUrl = configResult.serverUrl || DEFAULT_SERVER_URL;
260
- const source = configResult.foundIn;
261
- return { apiKey, serverUrl, source };
209
+ /**
210
+ * Writes (or overwrites) `childId`'s entry in `parentId`'s accumulated findings record,
211
+ * creating that record the first time any child reports into it. Called once a child's own
212
+ * `_end` succeeds — independent of whether `childId` is still among `parentId`'s currently-live
213
+ * children, so a child that later drops out of the live set never loses its findings.
214
+ */
215
+ function appendChildFinding(parentId, childId, payload, deps = defaultPhaseTrackerDeps) {
216
+ const record = getChildFindings(parentId, deps);
217
+ record[childId] = payload;
218
+ writeJson(deps, recordPath(deps, 'child-findings', parentId), record);
262
219
  }
263
- /** Load and store credentials in server context */
264
- function loadAndStoreCredentials(workingDirectory) {
265
- const result = loadCredentials(workingDirectory);
266
- if (result.apiKey && result.serverUrl) {
267
- setCredentials({
268
- apiKey: result.apiKey,
269
- serverUrl: result.serverUrl,
270
- });
271
- return true;
272
- }
273
- return false;
220
+ /** Appends one entry to `scopeId`'s invocation log — called as a side effect of every eyes-inspect data tool. */
221
+ function logInvocation(scopeId, toolName, args, deps = defaultPhaseTrackerDeps) {
222
+ const filePath = recordPath(deps, 'invocations', scopeId);
223
+ const log = readJson(deps, filePath) ?? [];
224
+ log.push({ toolName, args, at: new Date().toISOString() });
225
+ writeJson(deps, filePath, log);
274
226
  }
275
- /** Get credentials for external logging */
276
- function getCredentialsForLogging() {
277
- const result = loadCredentials();
278
- return {
279
- apiKey: result.apiKey,
280
- serverUrl: result.serverUrl || DEFAULT_SERVER_URL,
281
- };
227
+ /** Whether `scopeId`'s invocation log contains a call to `toolName` whose `args` satisfy `matcher` — the per-item invocation-verification check backing `step_end`/`diff_end`'s hard gates. */
228
+ function verifyInvocation(scopeId, toolName, matcher, deps = defaultPhaseTrackerDeps) {
229
+ const log = readJson(deps, recordPath(deps, 'invocations', scopeId)) ?? [];
230
+ return log.some(entry => entry.toolName === toolName && matcher(entry.args));
282
231
  }
283
-
284
- const handler = (() => {
285
- if (process.env.APPLITOOLS_LOG_FILE) {
286
- return logger$1.makeFileHandler({ filename: process.env.APPLITOOLS_LOG_FILE });
287
- }
288
- else if (process.env.APPLITOOLS_LOG_DIR) {
289
- return logger$1.makeRollingFileHandler({ dirname: process.env.APPLITOOLS_LOG_DIR });
290
- }
291
- // Default to stderr to avoid interfering with MCP stdio protocol
292
- return {
293
- // eslint-disable-next-line no-console
294
- log: (message) => console.error(message),
295
- // eslint-disable-next-line no-console
296
- warn: (message) => console.warn(message),
297
- // eslint-disable-next-line no-console
298
- error: (message) => console.error(message),
299
- };
300
- })();
301
- // Only perform expensive serialisation when a log sink is explicitly configured.
302
- const isVerboseLogging = !!(process.env.APPLITOOLS_LOG_FILE ||
303
- process.env.APPLITOOLS_LOG_DIR ||
304
- process.env.APPLITOOLS_SHOW_LOGS);
305
- const logger = logger$1.makeLogger({ level: 'all', handler });
306
- const externalLogger = coreBase.makeCore({
307
- agentId: 'mcp-tool-handler',
308
- maskLog: false,
309
- logger,
310
- offlineLocationPath: undefined,
311
- });
312
- function log$2(level, ...args) {
313
- logger[level](level, ...args);
232
+ /** Persists `mode` as the mode `scopeId` is currently being reviewed in — overwriting whatever was recorded before, so re-entering with the same mode simply re-states it. */
233
+ function recordScopeMode(scopeId, mode, deps = defaultPhaseTrackerDeps) {
234
+ writeJson(deps, recordPath(deps, 'modes', scopeId), mode);
314
235
  }
315
- async function externalLog(eventName, data, level = 'Notice') {
316
- // Get credentials using centralized loader
317
- const { apiKey, serverUrl: eyesServerUrl } = getCredentialsForLogging();
318
- if (!apiKey || apiKey === '') {
319
- logger.warn(`Cannot log external event ${eventName} - no API key configured`);
320
- return;
321
- }
322
- try {
323
- await externalLogger.logEvent({
324
- settings: {
325
- apiKey,
326
- eyesServerUrl,
327
- level,
328
- event: {
329
- type: eventName,
330
- data: data || {},
331
- },
332
- },
333
- logger,
334
- });
335
- }
336
- catch (error) {
337
- logger.error(`Failed to log external event ${eventName}:`, error);
338
- }
236
+ /** The mode last recorded for `scopeId` via `recordScopeMode`, or `undefined` if never recorded. */
237
+ function getScopeMode(scopeId, deps = defaultPhaseTrackerDeps) {
238
+ return readJson(deps, recordPath(deps, 'modes', scopeId));
339
239
  }
340
-
341
240
  /**
342
- * Documentation Resource
343
- *
344
- * Exposes the comprehensive README documentation for the Applitools MCP server
241
+ * Persists `rootScope` as the root of the review that last touched `scopeId`, overwriting any earlier one.
242
+ * A hint for the caller's guidance only: concurrent reviews of one scope overwrite each other.
345
243
  */
244
+ function recordScopeRoot(scopeId, rootScope, deps = defaultPhaseTrackerDeps) {
245
+ writeJson(deps, recordPath(deps, 'roots', scopeId), rootScope);
246
+ }
247
+ /** The root last recorded for `scopeId` via `recordScopeRoot`, or `undefined` if never recorded. */
248
+ function getScopeRoot(scopeId, deps = defaultPhaseTrackerDeps) {
249
+ return readJson(deps, recordPath(deps, 'roots', scopeId));
250
+ }
251
+ /** Discards `id`'s completion, as if `recordCompletion` had never been called for it. */
252
+ function clearCompletion(id, deps = defaultPhaseTrackerDeps) {
253
+ withRetry(() => deps.deleteFile(recordPath(deps, 'completions', id)), deps);
254
+ }
255
+ /** Discards `parentId`'s entire accumulated child-findings record — every child's entry, not just one. */
256
+ function clearChildFindings(parentId, deps = defaultPhaseTrackerDeps) {
257
+ withRetry(() => deps.deleteFile(recordPath(deps, 'child-findings', parentId)), deps);
258
+ }
259
+ /** Discards `scopeId`'s recorded mode, as if `recordScopeMode` had never been called for it. */
260
+ function clearScopeMode(scopeId, deps = defaultPhaseTrackerDeps) {
261
+ withRetry(() => deps.deleteFile(recordPath(deps, 'modes', scopeId)), deps);
262
+ }
263
+ /** Discards `scopeId`'s recorded root, as if `recordScopeRoot` had never been called for it. */
264
+ function clearScopeRoot(scopeId, deps = defaultPhaseTrackerDeps) {
265
+ withRetry(() => deps.deleteFile(recordPath(deps, 'roots', scopeId)), deps);
266
+ }
267
+ /** 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. */
268
+ function recordUnreadyChildren(scopeId, childKeys, deps = defaultPhaseTrackerDeps) {
269
+ writeJson(deps, recordPath(deps, 'unready-children', scopeId), childKeys);
270
+ }
271
+ /** The child keys `recordUnreadyChildren` last recorded as unready for `scopeId`, or `[]` if never recorded. */
272
+ function getUnreadyChildren(scopeId, deps = defaultPhaseTrackerDeps) {
273
+ return readJson(deps, recordPath(deps, 'unready-children', scopeId)) ?? [];
274
+ }
275
+ /** Discards `scopeId`'s recorded unready-children snapshot, as if `recordUnreadyChildren` had never been called for it. */
276
+ function clearUnreadyChildren(scopeId, deps = defaultPhaseTrackerDeps) {
277
+ withRetry(() => deps.deleteFile(recordPath(deps, 'unready-children', scopeId)), deps);
278
+ }
279
+ /** `scopeId`'s queued child keys — the stable, append-only set of children discovered live so far, investigated from regardless of what a later live fetch would show. `[]` if none have ever been queued. */
280
+ function getQueuedChildKeys(scopeId, deps = defaultPhaseTrackerDeps) {
281
+ return readJson(deps, recordPath(deps, 'children', scopeId)) ?? [];
282
+ }
346
283
  /**
347
- * Read documentation resource content
284
+ * Appends any of `liveKeys` not already queued, preserving the existing queue's order with
285
+ * newcomers appended in their given order — never removes a key, so a child that later drops out
286
+ * of a live fetch (resolved via propagation, or otherwise) stays queued and gets visited. Returns
287
+ * the full merged queue; writes only when something actually changed.
348
288
  */
349
- async function readDocumentationResource(uri) {
350
- // Validate URI first (don't log validation errors)
351
- if (uri !== RESOURCE_URIS.DOCUMENTATION_README) {
352
- throw new Error(`Unknown resource URI: ${uri}`);
353
- }
354
- try {
355
- // Determine the correct path based on whether we're running from source or dist
356
- // In production: dist/resources/documentation/index.js -> dist/docs/README.md
357
- // In tests: src/resources/documentation/index.ts -> docs/README.md
358
- let docsPath;
359
- if (/[\\/]dist(?:[\\/]|$)/.test(__dirname)) {
360
- // Running from compiled dist (standalone or VS Code extension)
361
- // Expect docs folder to be sibling of the script
362
- docsPath = path.join(__dirname, 'docs/README.md');
363
- }
364
- else {
365
- // Running from source (tests)
366
- docsPath = path.join(__dirname, '../../../docs/README.md');
367
- }
368
- const content = await promises.readFile(docsPath, 'utf-8');
369
- return {
370
- contents: [
371
- {
372
- uri,
373
- text: content,
374
- mimeType: 'text/markdown',
375
- },
376
- ],
377
- };
378
- }
379
- catch (error) {
380
- // Only log unexpected errors (file system errors, not validation errors)
381
- log$2('error', '[Resources] Failed to read documentation:', error);
382
- throw new Error(`Failed to read documentation: ${error instanceof Error ? error.message : String(error)}`);
383
- }
289
+ function queueChildKeys(scopeId, liveKeys, deps = defaultPhaseTrackerDeps) {
290
+ const existing = getQueuedChildKeys(scopeId, deps);
291
+ const existingSet = new Set(existing);
292
+ const fresh = liveKeys.filter(k => !existingSet.has(k));
293
+ if (fresh.length === 0)
294
+ return existing;
295
+ const merged = [...existing, ...fresh];
296
+ writeJson(deps, recordPath(deps, 'children', scopeId), merged);
297
+ return merged;
298
+ }
299
+ /** Discards `scopeId`'s entire queued-children record, as if nothing had ever been queued for it. */
300
+ function clearQueuedChildKeys(scopeId, deps = defaultPhaseTrackerDeps) {
301
+ withRetry(() => deps.deleteFile(recordPath(deps, 'children', scopeId)), deps);
384
302
  }
385
-
386
303
  /**
387
- * Wraps already-resolved key strings. A getter throws a clear error if its key wasn't supplied —
388
- * e.g. a write key deliberately withheld when building a provider for a read-only call — rather
389
- * than returning `undefined` and letting a missing credential fail confusingly further down.
304
+ * Persists `payload` as everything `scopeId`'s own live fetch most recently discovered — e.g. a
305
+ * batch's full session list, expensive to fetch and shared by everything nested under it —
306
+ * overwriting whatever was recorded before, so a caller that decides to refresh simply calls this
307
+ * again. Unlike `queueChildKeys`/`getQueuedChildKeys` (a stable, append-only set of keys a caller
308
+ * has committed to investigating), this is the raw discovery result itself — including entries
309
+ * (e.g. still-`Running` sessions) that may not be ready to investigate at all — so a lower-level
310
+ * scope nested underneath `scopeId` can re-derive its own children from it without repeating the
311
+ * fetch.
390
312
  */
391
- class StaticApiKeyProvider {
392
- keys;
393
- constructor(keys) {
394
- this.keys = keys;
395
- }
396
- getReadKey() {
397
- return this.require('readKey', 'read');
398
- }
399
- getWriteKey() {
400
- return this.require('writeKey', 'write');
401
- }
402
- getRunKey() {
403
- return this.require('runKey', 'run');
404
- }
405
- require(field, label) {
406
- const key = this.keys[field];
407
- if (key === undefined)
408
- throw new Error(`No ${label} API key is available for this call.`);
409
- return key;
410
- }
411
- }
412
-
413
- const defaultLoadEnvDeps = {
414
- existsSync: fs__namespace.existsSync,
415
- configDotenv: dotenv__namespace.config,
416
- };
417
- function loadEnvFromCwd(startDir = process.cwd(), deps = defaultLoadEnvDeps) {
418
- let dir = startDir;
419
- while (true) {
420
- const envPath = path__namespace.join(dir, '.env');
421
- if (deps.existsSync(envPath)) {
422
- const preset = new Set(Object.keys(process.env));
423
- const result = deps.configDotenv({ path: envPath });
424
- const parsed = result?.parsed ?? {};
425
- const applied = Object.keys(parsed).filter(name => !preset.has(name));
426
- return { path: envPath, applied, parsed };
427
- }
428
- const parent = path__namespace.dirname(dir);
429
- if (parent === dir)
430
- return undefined;
431
- dir = parent;
432
- }
433
- }
434
-
435
- const RETRYABLE_CODES = new Set(['EBUSY', 'EPERM', 'EACCES', 'EAGAIN']);
436
- const RETRY_ATTEMPTS = 5;
437
- const RETRY_BASE_DELAY_MS = 20;
438
- /**
439
- * A synchronous blocking sleep (`Atomics.wait` against a throwaway shared buffer) — matches
440
- * the rest of this codebase's synchronous fs style (`fs.readFileSync`/`writeFileSync`
441
- * throughout `commands.ts`), rather than forcing every phase-tracker call to be async merely
442
- * to await a short backoff delay.
443
- */
444
- function busyWaitSleep(ms) {
445
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
446
- }
447
- const defaultPhaseTrackerDeps = {
448
- readFile: p => (fs__namespace.existsSync(p) ? fs__namespace.readFileSync(p, 'utf8') : null),
449
- writeFile: (p, contents) => fs__namespace.writeFileSync(p, contents),
450
- appendFile: (p, contents) => fs__namespace.appendFileSync(p, contents),
451
- deleteFile: p => fs__namespace.rmSync(p, { force: true }),
452
- mkdir: dir => fs__namespace.mkdirSync(dir, { recursive: true }),
453
- sleep: busyWaitSleep,
454
- stateDir: path__namespace.join(os__namespace.tmpdir(), 'eyes-resolve'),
455
- };
456
- /**
457
- * Retries `fn` on a transient file-lock error (a momentarily-locked file must never crash a
458
- * workflow call — see `lib.md`), with a short exponential backoff between attempts. Any other
459
- * error (including a non-`Error` throw with no `.code`) propagates immediately, unretried.
460
- */
461
- function withRetry(fn, deps) {
462
- for (let attempt = 0;; attempt++) {
463
- try {
464
- return fn();
465
- }
466
- catch (error) {
467
- const code = error?.code;
468
- if (attempt >= RETRY_ATTEMPTS - 1 || !code || !RETRYABLE_CODES.has(code))
469
- throw error;
470
- deps.sleep(RETRY_BASE_DELAY_MS * 2 ** attempt);
471
- }
472
- }
473
- }
474
- function hashId(id) {
475
- return crypto__namespace.createHash('sha256').update(id).digest('hex');
476
- }
477
- // path.posix.join/dirname (not path.join/dirname) so the result is deterministic across
478
- // platforms — Node's fs APIs accept forward slashes on Windows too (same convention as
479
- // `api/fs-cache.ts`'s `cacheFilePath`).
480
- function recordPath(deps, kind, id) {
481
- return path__namespace.posix.join(deps.stateDir, kind, `${hashId(id)}.json`);
482
- }
483
- function readJson(deps, filePath) {
484
- const contents = withRetry(() => deps.readFile(filePath), deps);
485
- return contents === null ? undefined : JSON.parse(contents);
486
- }
487
- function writeJson(deps, filePath, value) {
488
- withRetry(() => deps.mkdir(path__namespace.posix.dirname(filePath)), deps);
489
- withRetry(() => deps.writeFile(filePath, JSON.stringify(value)), deps);
490
- }
491
- /** The recorded completion for `id`, or `undefined` if `<level>_end` was never (successfully) called for it. */
492
- function getCompletion(id, deps = defaultPhaseTrackerDeps) {
493
- return readJson(deps, recordPath(deps, 'completions', id));
494
- }
495
- function isCompleted(id, deps = defaultPhaseTrackerDeps) {
496
- return getCompletion(id, deps) !== undefined;
497
- }
498
- /**
499
- * Persists `payload` as `id`'s completion, stamped with the current time — overwriting
500
- * whatever was recorded for `id` before, so revising a summary (or refreshing a stale
501
- * completion) is just calling this again.
502
- */
503
- function recordCompletion(id, payload, deps = defaultPhaseTrackerDeps) {
504
- const completion = { payload, completedAt: new Date().toISOString() };
505
- writeJson(deps, recordPath(deps, 'completions', id), completion);
506
- return completion;
507
- }
508
- /** `parentId`'s full accumulated child-findings record, read as-is with no live-data filtering. `{}` if no child has ever reported into it. */
509
- function getChildFindings(parentId, deps = defaultPhaseTrackerDeps) {
510
- return readJson(deps, recordPath(deps, 'child-findings', parentId)) ?? {};
511
- }
512
- /**
513
- * Writes (or overwrites) `childId`'s entry in `parentId`'s accumulated findings record,
514
- * creating that record the first time any child reports into it. Called once a child's own
515
- * `_end` succeeds — independent of whether `childId` is still among `parentId`'s currently-live
516
- * children, so a child that later drops out of the live set never loses its findings.
517
- */
518
- function appendChildFinding(parentId, childId, payload, deps = defaultPhaseTrackerDeps) {
519
- const record = getChildFindings(parentId, deps);
520
- record[childId] = payload;
521
- writeJson(deps, recordPath(deps, 'child-findings', parentId), record);
522
- }
523
- /** Appends one entry to `scopeId`'s invocation log — called as a side effect of every eyes-inspect data tool. */
524
- function logInvocation(scopeId, toolName, args, deps = defaultPhaseTrackerDeps) {
525
- const filePath = recordPath(deps, 'invocations', scopeId);
526
- const log = readJson(deps, filePath) ?? [];
527
- log.push({ toolName, args, at: new Date().toISOString() });
528
- writeJson(deps, filePath, log);
529
- }
530
- /** Whether `scopeId`'s invocation log contains a call to `toolName` whose `args` satisfy `matcher` — the per-item invocation-verification check backing `step_end`/`diff_end`'s hard gates. */
531
- function verifyInvocation(scopeId, toolName, matcher, deps = defaultPhaseTrackerDeps) {
532
- const log = readJson(deps, recordPath(deps, 'invocations', scopeId)) ?? [];
533
- return log.some(entry => entry.toolName === toolName && matcher(entry.args));
534
- }
535
- /** Persists `mode` as the mode `scopeId` is currently being reviewed in — overwriting whatever was recorded before, so re-entering with the same mode simply re-states it. */
536
- function recordScopeMode(scopeId, mode, deps = defaultPhaseTrackerDeps) {
537
- writeJson(deps, recordPath(deps, 'modes', scopeId), mode);
538
- }
539
- /** The mode last recorded for `scopeId` via `recordScopeMode`, or `undefined` if never recorded. */
540
- function getScopeMode(scopeId, deps = defaultPhaseTrackerDeps) {
541
- return readJson(deps, recordPath(deps, 'modes', scopeId));
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
- }
554
- /** Discards `id`'s completion, as if `recordCompletion` had never been called for it. */
555
- function clearCompletion(id, deps = defaultPhaseTrackerDeps) {
556
- withRetry(() => deps.deleteFile(recordPath(deps, 'completions', id)), deps);
557
- }
558
- /** Discards `parentId`'s entire accumulated child-findings record — every child's entry, not just one. */
559
- function clearChildFindings(parentId, deps = defaultPhaseTrackerDeps) {
560
- withRetry(() => deps.deleteFile(recordPath(deps, 'child-findings', parentId)), deps);
561
- }
562
- /** Discards `scopeId`'s recorded mode, as if `recordScopeMode` had never been called for it. */
563
- function clearScopeMode(scopeId, deps = defaultPhaseTrackerDeps) {
564
- withRetry(() => deps.deleteFile(recordPath(deps, 'modes', scopeId)), deps);
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
- }
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. */
571
- function recordUnreadyChildren(scopeId, childKeys, deps = defaultPhaseTrackerDeps) {
572
- writeJson(deps, recordPath(deps, 'unready-children', scopeId), childKeys);
573
- }
574
- /** The child keys `recordUnreadyChildren` last recorded as unready for `scopeId`, or `[]` if never recorded. */
575
- function getUnreadyChildren(scopeId, deps = defaultPhaseTrackerDeps) {
576
- return readJson(deps, recordPath(deps, 'unready-children', scopeId)) ?? [];
577
- }
578
- /** Discards `scopeId`'s recorded unready-children snapshot, as if `recordUnreadyChildren` had never been called for it. */
579
- function clearUnreadyChildren(scopeId, deps = defaultPhaseTrackerDeps) {
580
- withRetry(() => deps.deleteFile(recordPath(deps, 'unready-children', scopeId)), deps);
581
- }
582
- /** `scopeId`'s queued child keys — the stable, append-only set of children discovered live so far, investigated from regardless of what a later live fetch would show. `[]` if none have ever been queued. */
583
- function getQueuedChildKeys(scopeId, deps = defaultPhaseTrackerDeps) {
584
- return readJson(deps, recordPath(deps, 'children', scopeId)) ?? [];
585
- }
586
- /**
587
- * Appends any of `liveKeys` not already queued, preserving the existing queue's order with
588
- * newcomers appended in their given order — never removes a key, so a child that later drops out
589
- * of a live fetch (resolved via propagation, or otherwise) stays queued and gets visited. Returns
590
- * the full merged queue; writes only when something actually changed.
591
- */
592
- function queueChildKeys(scopeId, liveKeys, deps = defaultPhaseTrackerDeps) {
593
- const existing = getQueuedChildKeys(scopeId, deps);
594
- const existingSet = new Set(existing);
595
- const fresh = liveKeys.filter(k => !existingSet.has(k));
596
- if (fresh.length === 0)
597
- return existing;
598
- const merged = [...existing, ...fresh];
599
- writeJson(deps, recordPath(deps, 'children', scopeId), merged);
600
- return merged;
601
- }
602
- /** Discards `scopeId`'s entire queued-children record, as if nothing had ever been queued for it. */
603
- function clearQueuedChildKeys(scopeId, deps = defaultPhaseTrackerDeps) {
604
- withRetry(() => deps.deleteFile(recordPath(deps, 'children', scopeId)), deps);
605
- }
606
- /**
607
- * Persists `payload` as everything `scopeId`'s own live fetch most recently discovered — e.g. a
608
- * batch's full session list, expensive to fetch and shared by everything nested under it —
609
- * overwriting whatever was recorded before, so a caller that decides to refresh simply calls this
610
- * again. Unlike `queueChildKeys`/`getQueuedChildKeys` (a stable, append-only set of keys a caller
611
- * has committed to investigating), this is the raw discovery result itself — including entries
612
- * (e.g. still-`Running` sessions) that may not be ready to investigate at all — so a lower-level
613
- * scope nested underneath `scopeId` can re-derive its own children from it without repeating the
614
- * fetch.
615
- */
616
- function recordDiscoveredChildren(scopeId, payload, deps = defaultPhaseTrackerDeps) {
617
- writeJson(deps, recordPath(deps, 'discovered-children', scopeId), payload);
313
+ function recordDiscoveredChildren(scopeId, payload, deps = defaultPhaseTrackerDeps) {
314
+ writeJson(deps, recordPath(deps, 'discovered-children', scopeId), payload);
618
315
  }
619
316
  /** What `recordDiscoveredChildren` last recorded for `scopeId`, or `undefined` if never recorded. */
620
317
  function getDiscoveredChildren(scopeId, deps = defaultPhaseTrackerDeps) {
@@ -661,7 +358,7 @@ function getLogFilePath(scopeId, deps = defaultPhaseTrackerDeps) {
661
358
  * lock-retry backoff (`withRetry`) as every other record this module writes, so a caller never
662
359
  * has to poll for the file to become available itself; a momentarily-busy append just retries.
663
360
  */
664
- function log$1(scopeId, label, fields = {}, deps = defaultPhaseTrackerDeps) {
361
+ function log$2(scopeId, label, fields = {}, deps = defaultPhaseTrackerDeps) {
665
362
  const entry = { at: new Date().toISOString(), label, ...fields };
666
363
  withRetry(() => deps.mkdir(debugLogDir(deps)), deps);
667
364
  withRetry(() => deps.appendFile(getLogFilePath(scopeId, deps), `${JSON.stringify(entry)}\n`), deps);
@@ -3299,6 +2996,36 @@ function parseBatchUrl(url) {
3299
2996
  return { ...parsed, sessionId: null };
3300
2997
  }
3301
2998
 
2999
+ /** The only domains an API key is ever sent to: a request host must be one of them or a subdomain of one. */
3000
+ const SAFE_DOMAINS = ['applitools.com'];
3001
+ // The first rule `url` breaks, worded for the user and naming at most the hostname; undefined when it may receive a key.
3002
+ function refusalReason(url) {
3003
+ let parsed;
3004
+ try {
3005
+ parsed = new URL(url);
3006
+ }
3007
+ catch {
3008
+ return 'the URL could not be parsed';
3009
+ }
3010
+ const { hostname, protocol, username, password } = parsed;
3011
+ if (!SAFE_DOMAINS.some(domain => hostname === domain || hostname.endsWith(`.${domain}`))) {
3012
+ return `${hostname || 'the URL'} is not an Applitools host`;
3013
+ }
3014
+ if (protocol !== 'https:')
3015
+ return `${hostname} is addressed over ${protocol.slice(0, -1)}, and keys are sent over https only`;
3016
+ if (username || password)
3017
+ return `the URL for ${hostname} contains a user name or password, which keys are never sent with`;
3018
+ return undefined;
3019
+ }
3020
+ function isTrustedEyesUrl(url) {
3021
+ return refusalReason(url) === undefined;
3022
+ }
3023
+ function assertTrustedEyesUrl(url) {
3024
+ const reason = refusalReason(url);
3025
+ if (reason)
3026
+ throw new Error(`${reason}, so the request was not sent`);
3027
+ }
3028
+
3302
3029
  // Same convention as core-base's reqEyes: `expected` is enforced by an afterResponse hook, so
3303
3030
  // call sites branch only on the statuses that carry meaning for them.
3304
3031
  function handleUnexpectedResponse() {
@@ -3338,9 +3065,38 @@ function isolateRetryPerRequest() {
3338
3065
  },
3339
3066
  };
3340
3067
  }
3068
+ // Kept last on every request: req appends per-call hooks after the instance's, and any earlier
3069
+ // beforeRequest may still return a request with a different URL.
3070
+ function guardDestination() {
3071
+ const guard = {
3072
+ afterOptionsMerged({ options }) {
3073
+ const hooks = [].concat(options.hooks ?? []);
3074
+ return { ...options, hooks: [...hooks.filter(hook => hook !== guard), guard] };
3075
+ },
3076
+ beforeRequest({ request }) {
3077
+ assertTrustedEyesUrl(request.url);
3078
+ // node-fetch forwards custom headers, the key's included, across a cross-origin redirect.
3079
+ return { request, redirect: 'error' };
3080
+ },
3081
+ };
3082
+ return guard;
3083
+ }
3084
+ /** Paths whose endpoint accepts the key only as the `apiKey` query parameter; every other request carries it as a header only. */
3085
+ const QUERY_AUTH_PATHS = [];
3086
+ /** The task-status endpoint answers without a key, so a request to it carries none. */
3087
+ const KEYLESS_PATH = /^\/api\/tasks\/[^/]+\/status$/;
3088
+ // Older api modules bake `apiKey=` into the URLs they pass in, so the parameter is settled here per path.
3089
+ function withQueryAuth(input, serverUrl, apiKey) {
3090
+ const url = new URL(String(input), serverUrl.endsWith('/') ? serverUrl : `${serverUrl}/`);
3091
+ if (QUERY_AUTH_PATHS.some(path => path.test(url.pathname)))
3092
+ url.searchParams.set('apiKey', apiKey);
3093
+ else
3094
+ url.searchParams.delete('apiKey');
3095
+ return url;
3096
+ }
3341
3097
  /**
3342
3098
  * Builds a configured `req` — core-base's `makeReqEyes` concept adapted to this package: the
3343
- * instance owns the server URL, the `apiKey` query parameter, the transient-retry policy, and the
3099
+ * instance owns the server URL, the API key, the transient-retry policy, and the
3344
3100
  * `expected`-status convention above, so api functions take the configured req plus business
3345
3101
  * parameters and never thread baseUrl/apiKey/transport themselves. Flat options on purpose: an api
3346
3102
  * function's own deps spread straight in — `makeReqResults({serverUrl, apiKey, ...deps})`.
@@ -3355,9 +3111,11 @@ function isolateRetryPerRequest() {
3355
3111
  * calls through a single instance and pins both properties.
3356
3112
  */
3357
3113
  function makeReqResults({ serverUrl, apiKey, fetch, logger }) {
3358
- return req.makeReq({
3114
+ const req$1 = req.makeReq({
3359
3115
  baseUrl: serverUrl,
3360
- query: { apiKey },
3116
+ headers: { 'X-Eyes-Api-Key': apiKey },
3117
+ // req's HTTP/2 path rebuilds the request without its `redirect` mode.
3118
+ httpVersion: 1,
3361
3119
  retry: {
3362
3120
  limit: 5,
3363
3121
  timeout: [200, 400, 800, 1600, 3200],
@@ -3370,10 +3128,19 @@ function makeReqResults({ serverUrl, apiKey, fetch, logger }) {
3370
3128
  // needs its own timeout to not hang forever.
3371
3129
  requestTimeout: 30000,
3372
3130
  connectionTimeout: 300000,
3373
- hooks: [isolateRetryPerRequest(), handleUnexpectedResponse()],
3131
+ hooks: [isolateRetryPerRequest(), handleUnexpectedResponse(), guardDestination()],
3374
3132
  fetch,
3375
3133
  logger,
3376
3134
  });
3135
+ return (input, options) => {
3136
+ if (typeof input !== 'string' && !(input instanceof URL))
3137
+ return req$1(input, options);
3138
+ const url = withQueryAuth(input, serverUrl, apiKey);
3139
+ if (!KEYLESS_PATH.test(url.pathname))
3140
+ return req$1(url, options);
3141
+ // An empty value overrides the instance's key header, and req drops empty-valued headers.
3142
+ return req$1(url, { ...options, headers: { ...options?.headers, 'X-Eyes-Api-Key': '' } });
3143
+ };
3377
3144
  }
3378
3145
 
3379
3146
  /**
@@ -3987,140 +3754,461 @@ async function compareStep(body, options, fetchImpl = reqTransport) {
3987
3754
  const response = await postJson(url, body, fetchImpl);
3988
3755
  return getJsonResult(response, apiKey, fetchImpl, undefined, url);
3989
3756
  }
3990
-
3991
- /**
3992
- * Given a reference step and a candidate list of other steps, returns which of `steps` actually
3993
- * have the same diff as `reference` — the real target steps an accept/reject decision should
3994
- * propagate to, as opposed to every step a scenario-name match happened to include. `image1`/
3995
- * `image2` here are plain baseline/checkpoint image id strings, not full `ImageRecord` objects
3996
- * (unlike `compareStep`'s own request shape) — each entry (including `reference`) carries its
3997
- * own step's `matchSettings`, never another step's.
3998
- *
3999
- * Confirmed live: an async job (202 + Location), same as every other endpoint in this file.
4000
- * **The result is `number[]` — zero-based indices into the request's own `steps` array, e.g.
4001
- * `[0, 1]` meaning `steps[0]` and `steps[1]` both matched — never step objects, and never
4002
- * `{sessionId, stepIndex}` identifiers.** A caller must resolve each index back against its own
4003
- * original `steps`/candidate array; the response carries nothing else to identify a match by.
4004
- * When nothing in `steps` matches `reference`, the job's own result is `204 No Content` — an
4005
- * empty body, which `getJsonResult` parses as `undefined` — normalized here to `[]` so callers
4006
- * can always assume an array.
4007
- */
4008
- async function findSameDiffSteps(body, options, fetchImpl = reqTransport) {
4009
- const { baseUrl, accountId, keys } = options;
4010
- const apiKey = keys.getReadKey();
4011
- const url = `${baseUrl}/api/sessions/steps/samediffas?accountId=${accountId}&apiKey=${encodeURIComponent(apiKey)}`;
4012
- const response = await postJson(url, body, fetchImpl);
4013
- return (await getJsonResult(response, apiKey, fetchImpl, undefined, url)) ?? [];
3757
+
3758
+ /**
3759
+ * Given a reference step and a candidate list of other steps, returns which of `steps` actually
3760
+ * have the same diff as `reference` — the real target steps an accept/reject decision should
3761
+ * propagate to, as opposed to every step a scenario-name match happened to include. `image1`/
3762
+ * `image2` here are plain baseline/checkpoint image id strings, not full `ImageRecord` objects
3763
+ * (unlike `compareStep`'s own request shape) — each entry (including `reference`) carries its
3764
+ * own step's `matchSettings`, never another step's.
3765
+ *
3766
+ * Confirmed live: an async job (202 + Location), same as every other endpoint in this file.
3767
+ * **The result is `number[]` — zero-based indices into the request's own `steps` array, e.g.
3768
+ * `[0, 1]` meaning `steps[0]` and `steps[1]` both matched — never step objects, and never
3769
+ * `{sessionId, stepIndex}` identifiers.** A caller must resolve each index back against its own
3770
+ * original `steps`/candidate array; the response carries nothing else to identify a match by.
3771
+ * When nothing in `steps` matches `reference`, the job's own result is `204 No Content` — an
3772
+ * empty body, which `getJsonResult` parses as `undefined` — normalized here to `[]` so callers
3773
+ * can always assume an array.
3774
+ */
3775
+ async function findSameDiffSteps(body, options, fetchImpl = reqTransport) {
3776
+ const { baseUrl, accountId, keys } = options;
3777
+ const apiKey = keys.getReadKey();
3778
+ const url = `${baseUrl}/api/sessions/steps/samediffas?accountId=${accountId}&apiKey=${encodeURIComponent(apiKey)}`;
3779
+ const response = await postJson(url, body, fetchImpl);
3780
+ return (await getJsonResult(response, apiKey, fetchImpl, undefined, url)) ?? [];
3781
+ }
3782
+
3783
+ // findNodeBySelector/findNodeByRect return a nested {domSelector, rect} shape (DomNode);
3784
+ // the Region shape needed elsewhere is flat (domSelector alongside left/top/width/height).
3785
+ function toRegion$1(resolved) {
3786
+ return { domSelector: resolved.domSelector, ...resolved.rect };
3787
+ }
3788
+ /**
3789
+ * Maps every `anchored` pair's `domSelector` to the other side via one batched
3790
+ * get-compatible-selectors call, resolving each mapped selector's accurate rect locally
3791
+ * against that side's DOM (the API only returns the mapped selector, never a rect). Falls
3792
+ * back to treating every selector as unmapped if the batch call itself fails for some reason
3793
+ * other than a bad input selector (`sessions`'s own `checkRegions` already filters those out).
3794
+ * Mutates each pair's missing side in place. Returns whether anything was attempted (i.e.
3795
+ * `anchored` was non-empty and both sides have an image to map between).
3796
+ *
3797
+ * Lives here, not in `atoms/sessions` (where the rest of the region-healing pipeline this composes
3798
+ * into — `checkRegions`/`clearStaleSelectors`/`healNonAnchoredRegionsBySourceRect` — lives):
3799
+ * this is the one step of that pipeline that actually calls the network (`getCompatibleSelectors`),
3800
+ * and `atoms` must never depend on `api`/`common` (so it can't reference `ApiKeyProvider` or make
3801
+ * network calls) — the orchestration belongs in `common`, which depends on both instead.
3802
+ */
3803
+ async function mapAnchoredRegionsBySelector(rawSession, stepIndex, anchored, deps) {
3804
+ if (anchored.length === 0)
3805
+ return false;
3806
+ const sourceSide = resolveDomIdSide('unchanged', rawSession, stepIndex);
3807
+ const missingSide = sourceSide === 'baseline' ? 'checkpoint' : 'baseline';
3808
+ const imageSource = imageForSide(rawSession, stepIndex, sourceSide);
3809
+ const imageMissing = imageForSide(rawSession, stepIndex, missingSide);
3810
+ if (!imageSource || !imageMissing)
3811
+ return false;
3812
+ const domMissing = await deps.fetchDomForSide(rawSession, stepIndex, missingSide, deps.baseUrl).catch(() => null);
3813
+ // `anchored` pairs are guaranteed a truthy domSelector by checkRegions's own definition of "anchored".
3814
+ const selectors = anchored.map(p => (p.baseline ?? p.checkpoint).domSelector);
3815
+ let mapped;
3816
+ try {
3817
+ mapped = await deps.getCompatibleSelectors({ baseUrl: deps.baseUrl, accountId: deps.accountId, keys: deps.keys }, imageSource, imageMissing, selectors);
3818
+ }
3819
+ catch {
3820
+ mapped = selectors.map(() => null); // the batch itself failed — treat every one as unmapped rather than throwing
3821
+ }
3822
+ anchored.forEach((pair, i) => {
3823
+ const newSelector = mapped[i];
3824
+ const resolved = newSelector && domMissing ? findNodeBySelector(domMissing, newSelector) : null;
3825
+ pair[missingSide] = resolved
3826
+ ? toRegion$1(resolved)
3827
+ : { ...(pair.baseline ?? pair.checkpoint), domSelector: newSelector ?? '' };
3828
+ });
3829
+ return true;
3830
+ }
3831
+
3832
+ const defaultFetchRawDiffsDeps = {
3833
+ fetchStepDiff,
3834
+ compareStep,
3835
+ readFile: defaultFsCacheDeps.readFile,
3836
+ writeFile: defaultFsCacheDeps.writeFile,
3837
+ };
3838
+ /**
3839
+ * The two-way visual diff for one step — `image1` in the baseline image's own coordinate
3840
+ * space, `image2` in the checkpoint's, exactly mirroring both the plain `GET .../diff`
3841
+ * endpoint's and `compareStep`'s own response shape. When the step's resolution state is
3842
+ * unchanged from the original test run (`appOutputResolution[stepIndex].isChanged` is not
3843
+ * `true`), the cheap `GET .../diff` endpoint is used as-is — nothing about the step's
3844
+ * effective match settings differs from what the test already ran with. Otherwise, the step's
3845
+ * current effective regions are folded into a fresh `compareStep` request so the returned diff
3846
+ * reflects any region added since the test ran — that (more expensive) result is cached on
3847
+ * disk, keyed by a hash of the full request body, so repeated calls against the same resolved
3848
+ * state don't repeatedly hit the endpoint.
3849
+ *
3850
+ * Takes an already-fetched `rawSession` rather than fetching its own — `batchId`/`sessionId`
3851
+ * are read straight off it (`rawSession.batchId`/`rawSession.id`), so a caller that already has
3852
+ * the raw session in hand (e.g. for its own domId lookups) never pays for a second fetch just
3853
+ * to hand this function a `url` it would otherwise re-resolve into the same session itself.
3854
+ *
3855
+ * `matchSettings` comes straight from `getEffectiveMatchSettings` — the raw session's own
3856
+ * scalars/regions, shaped directly into the request format, with no baseline/checkpoint
3857
+ * pairing and no healing: that shaping only exists for diagnostic region output (which needs
3858
+ * both sides shown, healing in whichever one the raw session doesn't encode), never for a
3859
+ * compare request. Re-deriving "accepted ⇒ checkpoint, else baseline" here would duplicate
3860
+ * logic the raw session's own `annotations` field already resolves — and healing in the other
3861
+ * side would cost an extra network round trip per region for nothing a compare request needs.
3862
+ */
3863
+ async function fetchRawDiffs(rawSession, stepIndex, baseUrl, accountId, keys, deps = defaultFetchRawDiffsDeps) {
3864
+ const batchId = rawSession?.batchId;
3865
+ const sessionId = rawSession?.id;
3866
+ if (rawSession?.appOutputResolution?.[stepIndex]?.isChanged !== true) {
3867
+ return deps.fetchStepDiff({ baseUrl, batchId, sessionId, stepIndex, accountId, keys });
3868
+ }
3869
+ const requestBody = {
3870
+ matchSettings: getEffectiveMatchSettings(rawSession, stepIndex),
3871
+ image1: imageForSide(rawSession, stepIndex, 'baseline'),
3872
+ image2: imageForSide(rawSession, stepIndex, 'checkpoint'),
3873
+ sessionId: rawSession.id,
3874
+ batchId: rawSession.batchId,
3875
+ runningSessionId: rawSession.runningSessionId,
3876
+ stepIndex,
3877
+ };
3878
+ // SHA-256 (not SHA-1): this is only a content-addressed cache key, but the hashed body carries
3879
+ // session identifiers, so a collision-prone digest is neither needed nor acceptable here.
3880
+ const requestHash = crypto__namespace.createHash('sha256').update(JSON.stringify(requestBody)).digest('hex').slice(0, 16);
3881
+ const cachePath = cacheFilePath(defaultFsCacheDeps, 'eyes-compare', requestHash);
3882
+ const cached = deps.readFile(cachePath);
3883
+ if (cached !== null) {
3884
+ const parsed = JSON.parse(cached);
3885
+ return { image1: parsed.image1 ?? [], image2: parsed.image2 ?? [] };
3886
+ }
3887
+ const result = await deps.compareStep(requestBody, { baseUrl, accountId, keys });
3888
+ const rects = { image1: result.image1 ?? [], image2: result.image2 ?? [] };
3889
+ deps.writeFile(cachePath, JSON.stringify(rects));
3890
+ return rects;
3891
+ }
3892
+
3893
+ function loadEnvFile(workingDirectory) {
3894
+ const envPath = path__namespace.join(workingDirectory, '.env');
3895
+ if (!fs__namespace.existsSync(envPath)) {
3896
+ return {};
3897
+ }
3898
+ try {
3899
+ const content = fs__namespace.readFileSync(envPath, 'utf-8');
3900
+ const lines = content.split('\n');
3901
+ let apiKey;
3902
+ let serverUrl;
3903
+ for (const line of lines) {
3904
+ const trimmed = line.trim();
3905
+ // Skip empty lines and comments
3906
+ if (!trimmed || trimmed.startsWith('#')) {
3907
+ continue;
3908
+ }
3909
+ // Parse KEY=VALUE
3910
+ const match = trimmed.match(/^([^=]+)=(.*)$/);
3911
+ if (!match)
3912
+ continue;
3913
+ const key = match[1].trim();
3914
+ let value = match[2].trim();
3915
+ // Remove quotes if present
3916
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
3917
+ value = value.slice(1, -1);
3918
+ }
3919
+ if (key === 'APPLITOOLS_API_KEY' && value) {
3920
+ apiKey = value;
3921
+ }
3922
+ else if (key === 'APPLITOOLS_SERVER_URL' && value) {
3923
+ serverUrl = value;
3924
+ }
3925
+ }
3926
+ if (apiKey) {
3927
+ return { apiKey, serverUrl, foundIn: '.env' };
3928
+ }
3929
+ }
3930
+ catch {
3931
+ // Silently ignore errors reading .env
3932
+ }
3933
+ return {};
3934
+ }
3935
+ /**
3936
+ * Helper to resolve environment variable references in config files
3937
+ * Checks if the content references an env var, then resolves from process.env or .env file
3938
+ */
3939
+ function resolveEnvVarFromContent(content, envVarName, workingDirectory) {
3940
+ // Check if content references the environment variable (with or without process.env prefix)
3941
+ const patterns = [
3942
+ new RegExp(`process\\.env\\.${envVarName}`, 'i'),
3943
+ new RegExp(`${envVarName}(?!['"])`, 'i'), // Bare reference (not in quotes)
3944
+ ];
3945
+ const hasReference = patterns.some(pattern => pattern.test(content));
3946
+ if (!hasReference) {
3947
+ return undefined;
3948
+ }
3949
+ // Try to resolve the value: first from process.env, then from .env file
3950
+ const envValue = process.env[envVarName];
3951
+ if (envValue) {
3952
+ return envValue;
3953
+ }
3954
+ // Fallback to .env file
3955
+ const envResult = loadEnvFile(workingDirectory);
3956
+ if (envVarName === 'APPLITOOLS_API_KEY') {
3957
+ return envResult.apiKey;
3958
+ }
3959
+ else if (envVarName === 'APPLITOOLS_SERVER_URL') {
3960
+ return envResult.serverUrl;
3961
+ }
3962
+ return undefined;
3963
+ }
3964
+ function loadConfigFile(configPath, fileName, workingDirectory) {
3965
+ if (!fs__namespace.existsSync(configPath)) {
3966
+ return {};
3967
+ }
3968
+ try {
3969
+ const content = fs__namespace.readFileSync(configPath, 'utf-8');
3970
+ // Search for apiKey and serverUrl in the file content
3971
+ let apiKey;
3972
+ let serverUrl;
3973
+ // Pattern 1: apiKey: 'value' or apiKey: "value" (hardcoded values)
3974
+ const apiKeyMatch = content.match(/apiKey\s*:\s*['"]([^'"]+)['"]/i);
3975
+ if (apiKeyMatch) {
3976
+ apiKey = apiKeyMatch[1];
3977
+ }
3978
+ // Pattern 2: serverUrl: 'value' or serverUrl: "value" (hardcoded values)
3979
+ const serverUrlMatch = content.match(/serverUrl\s*:\s*['"]([^'"]+)['"]/i);
3980
+ if (serverUrlMatch) {
3981
+ serverUrl = serverUrlMatch[1];
3982
+ }
3983
+ // Pattern 3: Resolve environment variable references in config file
3984
+ if (!apiKey) {
3985
+ apiKey = resolveEnvVarFromContent(content, 'APPLITOOLS_API_KEY', workingDirectory);
3986
+ }
3987
+ if (!serverUrl) {
3988
+ serverUrl = resolveEnvVarFromContent(content, 'APPLITOOLS_SERVER_URL', workingDirectory);
3989
+ }
3990
+ if (apiKey) {
3991
+ return { apiKey, serverUrl, foundIn: fileName };
3992
+ }
3993
+ }
3994
+ catch {
3995
+ // Silently ignore errors reading config file
3996
+ }
3997
+ return {};
3998
+ }
3999
+ function findApiKey(workingDirectory = process.cwd()) {
4000
+ // Define config file patterns to check (in priority order)
4001
+ const configFiles = [
4002
+ // Applitools config files
4003
+ { name: 'applitools.config.js', path: path__namespace.join(workingDirectory, 'applitools.config.js') },
4004
+ { name: 'applitools.config.cjs', path: path__namespace.join(workingDirectory, 'applitools.config.cjs') },
4005
+ { name: 'applitools.config.mjs', path: path__namespace.join(workingDirectory, 'applitools.config.mjs') },
4006
+ { name: 'applitools.config.ts', path: path__namespace.join(workingDirectory, 'applitools.config.ts') },
4007
+ // Playwright config files
4008
+ { name: 'playwright.config.js', path: path__namespace.join(workingDirectory, 'playwright.config.js') },
4009
+ { name: 'playwright.config.cjs', path: path__namespace.join(workingDirectory, 'playwright.config.cjs') },
4010
+ { name: 'playwright.config.mjs', path: path__namespace.join(workingDirectory, 'playwright.config.mjs') },
4011
+ { name: 'playwright.config.ts', path: path__namespace.join(workingDirectory, 'playwright.config.ts') },
4012
+ ];
4013
+ // 1. Check each config file in order (config files have priority over .env)
4014
+ for (const config of configFiles) {
4015
+ const result = loadConfigFile(config.path, config.name, workingDirectory);
4016
+ if (result.apiKey) {
4017
+ return result;
4018
+ }
4019
+ }
4020
+ // 2. Check .env file as fallback
4021
+ const envResult = loadEnvFile(workingDirectory);
4022
+ if (envResult.apiKey) {
4023
+ return envResult;
4024
+ }
4025
+ // 3. Check environment variables as final fallback
4026
+ const envApiKey = process.env.APPLITOOLS_API_KEY;
4027
+ const envServerUrl = process.env.APPLITOOLS_SERVER_URL;
4028
+ if (envApiKey) {
4029
+ return {
4030
+ apiKey: envApiKey,
4031
+ serverUrl: envServerUrl,
4032
+ foundIn: 'environment variable',
4033
+ };
4034
+ }
4035
+ // Not found
4036
+ return {};
4037
+ }
4038
+
4039
+ let currentClientInfo = undefined;
4040
+ let currentCredentials = undefined;
4041
+ let ide = undefined;
4042
+ function setClientInfo(clientInfo) {
4043
+ currentClientInfo = clientInfo;
4044
+ }
4045
+ function getClientInfo() {
4046
+ return currentClientInfo;
4047
+ }
4048
+ function setCredentials(credentials) {
4049
+ currentCredentials = credentials;
4050
+ }
4051
+ function getCredentials() {
4052
+ return currentCredentials;
4053
+ }
4054
+ function setIDE(ideName) {
4055
+ ide = ideName;
4056
+ }
4057
+ function getIDE() {
4058
+ return ide;
4059
+ }
4060
+ function parseIDE(env, argv) {
4061
+ var _a;
4062
+ return env['ide'] || ((_a = argv.find(arg => arg.startsWith('--ide='))) === null || _a === void 0 ? void 0 : _a.split('=')[1]) || 'unknown';
4063
+ }
4064
+ /** Evaluated once at process start; off unless `EXPERIMENTAL_ENV` is `1`/`true` (any case). */
4065
+ function parseExperimental(env) {
4066
+ var _a;
4067
+ return ['1', 'true'].includes(((_a = env[EXPERIMENTAL_ENV]) !== null && _a !== void 0 ? _a : '').toLowerCase());
4068
+ }
4069
+
4070
+ /** Load credentials from server context, config files, or environment variables */
4071
+ function loadCredentials(workingDirectory) {
4072
+ const storedCredentials = getCredentials();
4073
+ if ((storedCredentials === null || storedCredentials === void 0 ? void 0 : storedCredentials.apiKey) && (storedCredentials === null || storedCredentials === void 0 ? void 0 : storedCredentials.serverUrl)) {
4074
+ return {
4075
+ apiKey: storedCredentials.apiKey,
4076
+ serverUrl: storedCredentials.serverUrl,
4077
+ source: 'server-context',
4078
+ };
4079
+ }
4080
+ const workingDir = workingDirectory || process.cwd();
4081
+ const configResult = findApiKey(workingDir);
4082
+ const apiKey = configResult.apiKey;
4083
+ const serverUrl = configResult.serverUrl || process.env.APPLITOOLS_SERVER_URL || DEFAULT_SERVER_URL;
4084
+ const source = configResult.foundIn;
4085
+ return { apiKey, serverUrl, source };
4086
+ }
4087
+ /** Load and store credentials in server context */
4088
+ function loadAndStoreCredentials(workingDirectory) {
4089
+ const result = loadCredentials(workingDirectory);
4090
+ if (result.apiKey && result.serverUrl) {
4091
+ setCredentials({
4092
+ apiKey: result.apiKey,
4093
+ serverUrl: result.serverUrl,
4094
+ });
4095
+ return true;
4096
+ }
4097
+ return false;
4098
+ }
4099
+ /** Get credentials for external logging */
4100
+ function getCredentialsForLogging() {
4101
+ const result = loadCredentials();
4102
+ return {
4103
+ apiKey: result.apiKey,
4104
+ serverUrl: result.serverUrl || DEFAULT_SERVER_URL,
4105
+ };
4014
4106
  }
4015
4107
 
4016
- // findNodeBySelector/findNodeByRect return a nested {domSelector, rect} shape (DomNode);
4017
- // the Region shape needed elsewhere is flat (domSelector alongside left/top/width/height).
4018
- function toRegion$1(resolved) {
4019
- return { domSelector: resolved.domSelector, ...resolved.rect };
4108
+ const handler = (() => {
4109
+ if (process.env.APPLITOOLS_LOG_FILE) {
4110
+ return logger$1.makeFileHandler({ filename: process.env.APPLITOOLS_LOG_FILE });
4111
+ }
4112
+ else if (process.env.APPLITOOLS_LOG_DIR) {
4113
+ return logger$1.makeRollingFileHandler({ dirname: process.env.APPLITOOLS_LOG_DIR });
4114
+ }
4115
+ // Default to stderr to avoid interfering with MCP stdio protocol
4116
+ return {
4117
+ // eslint-disable-next-line no-console
4118
+ log: (message) => console.error(message),
4119
+ // eslint-disable-next-line no-console
4120
+ warn: (message) => console.warn(message),
4121
+ // eslint-disable-next-line no-console
4122
+ error: (message) => console.error(message),
4123
+ };
4124
+ })();
4125
+ // Only perform expensive serialisation when a log sink is explicitly configured.
4126
+ const isVerboseLogging = !!(process.env.APPLITOOLS_LOG_FILE ||
4127
+ process.env.APPLITOOLS_LOG_DIR ||
4128
+ process.env.APPLITOOLS_SHOW_LOGS);
4129
+ const logger = logger$1.makeLogger({ level: 'all', handler });
4130
+ const externalLogger = coreBase.makeCore({
4131
+ agentId: 'mcp-tool-handler',
4132
+ maskLog: false,
4133
+ logger,
4134
+ offlineLocationPath: undefined,
4135
+ });
4136
+ function log$1(level, ...args) {
4137
+ logger[level](level, ...args);
4020
4138
  }
4021
- /**
4022
- * Maps every `anchored` pair's `domSelector` to the other side via one batched
4023
- * get-compatible-selectors call, resolving each mapped selector's accurate rect locally
4024
- * against that side's DOM (the API only returns the mapped selector, never a rect). Falls
4025
- * back to treating every selector as unmapped if the batch call itself fails for some reason
4026
- * other than a bad input selector (`sessions`'s own `checkRegions` already filters those out).
4027
- * Mutates each pair's missing side in place. Returns whether anything was attempted (i.e.
4028
- * `anchored` was non-empty and both sides have an image to map between).
4029
- *
4030
- * Lives here, not in `atoms/sessions` (where the rest of the region-healing pipeline this composes
4031
- * into — `checkRegions`/`clearStaleSelectors`/`healNonAnchoredRegionsBySourceRect` — lives):
4032
- * this is the one step of that pipeline that actually calls the network (`getCompatibleSelectors`),
4033
- * and `atoms` must never depend on `api`/`common` (so it can't reference `ApiKeyProvider` or make
4034
- * network calls) — the orchestration belongs in `common`, which depends on both instead.
4035
- */
4036
- async function mapAnchoredRegionsBySelector(rawSession, stepIndex, anchored, deps) {
4037
- if (anchored.length === 0)
4038
- return false;
4039
- const sourceSide = resolveDomIdSide('unchanged', rawSession, stepIndex);
4040
- const missingSide = sourceSide === 'baseline' ? 'checkpoint' : 'baseline';
4041
- const imageSource = imageForSide(rawSession, stepIndex, sourceSide);
4042
- const imageMissing = imageForSide(rawSession, stepIndex, missingSide);
4043
- if (!imageSource || !imageMissing)
4044
- return false;
4045
- const domMissing = await deps.fetchDomForSide(rawSession, stepIndex, missingSide, deps.baseUrl).catch(() => null);
4046
- // `anchored` pairs are guaranteed a truthy domSelector by checkRegions's own definition of "anchored".
4047
- const selectors = anchored.map(p => (p.baseline ?? p.checkpoint).domSelector);
4048
- let mapped;
4139
+ async function externalLog(eventName, data, level = 'Notice') {
4140
+ // Get credentials using centralized loader
4141
+ const { apiKey, serverUrl: eyesServerUrl } = getCredentialsForLogging();
4142
+ if (!apiKey || apiKey === '') {
4143
+ logger.warn(`Cannot log external event ${eventName} - no API key configured`);
4144
+ return;
4145
+ }
4146
+ if (!isTrustedEyesUrl(eyesServerUrl)) {
4147
+ logger.warn(`Cannot log external event ${eventName} - the configured server is not an Applitools host`);
4148
+ return;
4149
+ }
4049
4150
  try {
4050
- mapped = await deps.getCompatibleSelectors({ baseUrl: deps.baseUrl, accountId: deps.accountId, keys: deps.keys }, imageSource, imageMissing, selectors);
4151
+ await externalLogger.logEvent({
4152
+ settings: {
4153
+ apiKey,
4154
+ eyesServerUrl,
4155
+ level,
4156
+ event: {
4157
+ type: eventName,
4158
+ data: data || {},
4159
+ },
4160
+ },
4161
+ logger,
4162
+ });
4051
4163
  }
4052
- catch {
4053
- mapped = selectors.map(() => null); // the batch itself failed — treat every one as unmapped rather than throwing
4164
+ catch (error) {
4165
+ logger.error(`Failed to log external event ${eventName}:`, error);
4054
4166
  }
4055
- anchored.forEach((pair, i) => {
4056
- const newSelector = mapped[i];
4057
- const resolved = newSelector && domMissing ? findNodeBySelector(domMissing, newSelector) : null;
4058
- pair[missingSide] = resolved
4059
- ? toRegion$1(resolved)
4060
- : { ...(pair.baseline ?? pair.checkpoint), domSelector: newSelector ?? '' };
4061
- });
4062
- return true;
4063
4167
  }
4064
4168
 
4065
- const defaultFetchRawDiffsDeps = {
4066
- fetchStepDiff,
4067
- compareStep,
4068
- readFile: defaultFsCacheDeps.readFile,
4069
- writeFile: defaultFsCacheDeps.writeFile,
4070
- };
4071
4169
  /**
4072
- * The two-way visual diff for one step — `image1` in the baseline image's own coordinate
4073
- * space, `image2` in the checkpoint's, exactly mirroring both the plain `GET .../diff`
4074
- * endpoint's and `compareStep`'s own response shape. When the step's resolution state is
4075
- * unchanged from the original test run (`appOutputResolution[stepIndex].isChanged` is not
4076
- * `true`), the cheap `GET .../diff` endpoint is used as-is — nothing about the step's
4077
- * effective match settings differs from what the test already ran with. Otherwise, the step's
4078
- * current effective regions are folded into a fresh `compareStep` request so the returned diff
4079
- * reflects any region added since the test ran — that (more expensive) result is cached on
4080
- * disk, keyed by a hash of the full request body, so repeated calls against the same resolved
4081
- * state don't repeatedly hit the endpoint.
4082
- *
4083
- * Takes an already-fetched `rawSession` rather than fetching its own — `batchId`/`sessionId`
4084
- * are read straight off it (`rawSession.batchId`/`rawSession.id`), so a caller that already has
4085
- * the raw session in hand (e.g. for its own domId lookups) never pays for a second fetch just
4086
- * to hand this function a `url` it would otherwise re-resolve into the same session itself.
4170
+ * Documentation Resource
4087
4171
  *
4088
- * `matchSettings` comes straight from `getEffectiveMatchSettings` — the raw session's own
4089
- * scalars/regions, shaped directly into the request format, with no baseline/checkpoint
4090
- * pairing and no healing: that shaping only exists for diagnostic region output (which needs
4091
- * both sides shown, healing in whichever one the raw session doesn't encode), never for a
4092
- * compare request. Re-deriving "accepted ⇒ checkpoint, else baseline" here would duplicate
4093
- * logic the raw session's own `annotations` field already resolves — and healing in the other
4094
- * side would cost an extra network round trip per region for nothing a compare request needs.
4172
+ * Exposes the comprehensive README documentation for the Applitools MCP server
4095
4173
  */
4096
- async function fetchRawDiffs(rawSession, stepIndex, baseUrl, accountId, keys, deps = defaultFetchRawDiffsDeps) {
4097
- const batchId = rawSession?.batchId;
4098
- const sessionId = rawSession?.id;
4099
- if (rawSession?.appOutputResolution?.[stepIndex]?.isChanged !== true) {
4100
- return deps.fetchStepDiff({ baseUrl, batchId, sessionId, stepIndex, accountId, keys });
4174
+ /**
4175
+ * Read documentation resource content
4176
+ */
4177
+ async function readDocumentationResource(uri) {
4178
+ // Validate URI first (don't log validation errors)
4179
+ if (uri !== RESOURCE_URIS.DOCUMENTATION_README) {
4180
+ throw new Error(`Unknown resource URI: ${uri}`);
4101
4181
  }
4102
- const requestBody = {
4103
- matchSettings: getEffectiveMatchSettings(rawSession, stepIndex),
4104
- image1: imageForSide(rawSession, stepIndex, 'baseline'),
4105
- image2: imageForSide(rawSession, stepIndex, 'checkpoint'),
4106
- sessionId: rawSession.id,
4107
- batchId: rawSession.batchId,
4108
- runningSessionId: rawSession.runningSessionId,
4109
- stepIndex,
4110
- };
4111
- // SHA-256 (not SHA-1): this is only a content-addressed cache key, but the hashed body carries
4112
- // session identifiers, so a collision-prone digest is neither needed nor acceptable here.
4113
- const requestHash = crypto__namespace.createHash('sha256').update(JSON.stringify(requestBody)).digest('hex').slice(0, 16);
4114
- const cachePath = cacheFilePath(defaultFsCacheDeps, 'eyes-compare', requestHash);
4115
- const cached = deps.readFile(cachePath);
4116
- if (cached !== null) {
4117
- const parsed = JSON.parse(cached);
4118
- return { image1: parsed.image1 ?? [], image2: parsed.image2 ?? [] };
4182
+ try {
4183
+ // Determine the correct path based on whether we're running from source or dist
4184
+ // In production: dist/resources/documentation/index.js -> dist/docs/README.md
4185
+ // In tests: src/resources/documentation/index.ts -> docs/README.md
4186
+ let docsPath;
4187
+ if (/[\\/]dist(?:[\\/]|$)/.test(__dirname)) {
4188
+ // Running from compiled dist (standalone or VS Code extension)
4189
+ // Expect docs folder to be sibling of the script
4190
+ docsPath = path.join(__dirname, 'docs/README.md');
4191
+ }
4192
+ else {
4193
+ // Running from source (tests)
4194
+ docsPath = path.join(__dirname, '../../../docs/README.md');
4195
+ }
4196
+ const content = await promises.readFile(docsPath, 'utf-8');
4197
+ return {
4198
+ contents: [
4199
+ {
4200
+ uri,
4201
+ text: content,
4202
+ mimeType: 'text/markdown',
4203
+ },
4204
+ ],
4205
+ };
4206
+ }
4207
+ catch (error) {
4208
+ // Only log unexpected errors (file system errors, not validation errors)
4209
+ log$1('error', '[Resources] Failed to read documentation:', error);
4210
+ throw new Error(`Failed to read documentation: ${error instanceof Error ? error.message : String(error)}`);
4119
4211
  }
4120
- const result = await deps.compareStep(requestBody, { baseUrl, accountId, keys });
4121
- const rects = { image1: result.image1 ?? [], image2: result.image2 ?? [] };
4122
- deps.writeFile(cachePath, JSON.stringify(rects));
4123
- return rects;
4124
4212
  }
4125
4213
 
4126
4214
  const sessionMetadata = {
@@ -4144,33 +4232,38 @@ function getLastValidatedServerUrl() {
4144
4232
  return sessionMetadata.lastValidatedServerUrl;
4145
4233
  }
4146
4234
 
4147
- const API_KEY_VARS = ['APPLITOOLS_READ_KEY', 'APPLITOOLS_WRITE_KEY'];
4148
4235
  const loadEnvOnce = utils__namespace.general.cachify((startDir, source) => {
4149
4236
  const loaded = loadEnvFromCwd(startDir);
4150
4237
  if (loaded) {
4151
- const applied = loaded.applied.length ? `set ${loaded.applied.join(', ')}` : 'no new variables applied';
4152
- log$2('info', `[MCP Server] .env loaded from ${loaded.path} (${applied}; walked up from ${startDir}, triggered by ${source})`);
4238
+ log$1('info', `[MCP Server] .env loaded from ${loaded.path} (defines ${Object.keys(loaded.parsed).join(', ')}; walked up from ${startDir}, triggered by ${source})`);
4153
4239
  }
4154
4240
  else {
4155
- log$2('debug', `[MCP Server] no .env found walking up from ${startDir} (triggered by ${source})`);
4241
+ log$1('debug', `[MCP Server] no .env found walking up from ${startDir} (triggered by ${source})`);
4156
4242
  }
4157
4243
  return loaded;
4158
4244
  }, ([startDir]) => startDir, 30000);
4245
+ // Saved the first time a .env overrides a name, so the launch value comes back once no chosen .env defines it.
4246
+ const launchValues = new Map();
4159
4247
  function syncWorkspaceKeys(workspaceRoot, source) {
4160
4248
  const loaded = loadEnvOnce(workspaceRoot, source);
4161
- if (!loaded)
4162
- return;
4163
- for (const name of API_KEY_VARS) {
4164
- const value = loaded.parsed[name];
4165
- if (process.env[name] === value)
4166
- continue;
4167
- if (value) {
4249
+ for (const name of WORKSPACE_ENV_NAMES) {
4250
+ const value = loaded === null || loaded === void 0 ? void 0 : loaded.parsed[name];
4251
+ if (loaded && value) {
4252
+ if (!launchValues.has(name))
4253
+ launchValues.set(name, process.env[name]);
4254
+ if (process.env[name] === value)
4255
+ continue;
4168
4256
  process.env[name] = value;
4169
- log$2('info', `[MCP Server] ${name} set from ${loaded.path} (triggered by ${source})`);
4257
+ log$1('info', `[MCP Server] ${name} set from ${loaded.path} (triggered by ${source})`);
4170
4258
  }
4171
- else if (name in process.env) {
4172
- delete process.env[name];
4173
- log$2('info', `[MCP Server] ${name} removed — not in ${loaded.path} (triggered by ${source})`);
4259
+ else if (launchValues.has(name)) {
4260
+ const launchValue = launchValues.get(name);
4261
+ launchValues.delete(name);
4262
+ if (launchValue === undefined)
4263
+ delete process.env[name];
4264
+ else
4265
+ process.env[name] = launchValue;
4266
+ log$1('info', `[MCP Server] ${name} restored to its launch value (triggered by ${source})`);
4174
4267
  }
4175
4268
  }
4176
4269
  }
@@ -4499,8 +4592,8 @@ function gateRejectionCount() {
4499
4592
 
4500
4593
  var name = "@applitools/mcp";
4501
4594
  var mcpName = "io.github.applitools/applitools";
4502
- var mcpRegistryVersion = "1.0.16";
4503
- var version = "0.10.4";
4595
+ var mcpRegistryVersion = "1.0.17";
4596
+ var version = "0.10.5";
4504
4597
  var description = "Applitools MCP server for AI coding assistants";
4505
4598
  var main = "./dist/index.js";
4506
4599
  var bin = "./dist/index.js";
@@ -4732,7 +4825,7 @@ function jsonParams(essential, inputs) {
4732
4825
  if (biggest === undefined)
4733
4826
  return json;
4734
4827
  fields.delete(biggest);
4735
- log$2('warn', `[MCP] json_params over ${JSON_PARAMS_BUDGET} chars — dropped input "${biggest}"`);
4828
+ log$1('warn', `[MCP] json_params over ${JSON_PARAMS_BUDGET} chars — dropped input "${biggest}"`);
4736
4829
  json = serialize();
4737
4830
  }
4738
4831
  return json;
@@ -4740,10 +4833,12 @@ function jsonParams(essential, inputs) {
4740
4833
  const createToolHandler = (toolDef, logic) => {
4741
4834
  return async (params) => {
4742
4835
  const clientInfo = getClientInfo();
4743
- log$2('info', `[MCP] 🟢 Tool Accessed: ${toolDef.name}`);
4744
- log$2('info', `[MCP] 📥 Client: ${(clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.name) || 'unknown'} v${(clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.version) || 'unknown'}`);
4836
+ log$1('info', `[MCP] 🟢 Tool Accessed: ${toolDef.name}`);
4837
+ log$1('info', `[MCP] 📥 Client: ${(clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.name) || 'unknown'} v${(clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.version) || 'unknown'}`);
4838
+ if (typeof (params === null || params === void 0 ? void 0 : params.apiKey) === 'string')
4839
+ logger.mask(params.apiKey);
4745
4840
  if (isVerboseLogging)
4746
- log$2('info', `[MCP] 📥 Params:`, JSON.stringify(params, null, 2));
4841
+ log$1('info', `[MCP] 📥 Params:`, JSON.stringify(params, null, 2));
4747
4842
  const safeParams = params !== null && params !== void 0 ? params : {};
4748
4843
  const workspaceRoot = safeParams.workspaceRoot || getWorkspaceRoot() || process.cwd();
4749
4844
  syncWorkspaceKeys(workspaceRoot, toolDef.name);
@@ -4770,7 +4865,8 @@ const createToolHandler = (toolDef, logic) => {
4770
4865
  transport_mode: TRANSPORT_MODE,
4771
4866
  batch_id: batchId,
4772
4867
  session_id: sessionId,
4773
- params: JSON.stringify(params, null, 2).slice(0, 1024),
4868
+ // The backend attributes every event to the authenticating key's account, so no key goes out here.
4869
+ params: JSON.stringify({ ...params, apiKey: undefined }, null, 2).slice(0, 1024),
4774
4870
  json_params: jsonParams({}, callInputs),
4775
4871
  automation_framework: automationFramework,
4776
4872
  automation_framework_version: automationFrameworkVersion,
@@ -4782,7 +4878,7 @@ const createToolHandler = (toolDef, logic) => {
4782
4878
  const validatedParams = toolDef.input.parse(enrichedParams || {});
4783
4879
  const result = await withToolTelemetry(telemetry, () => logic(validatedParams));
4784
4880
  if (isVerboseLogging)
4785
- log$2('info', `[MCP] 📤 Result:`, serializeResultForLog(result));
4881
+ log$1('info', `[MCP] 📤 Result:`, serializeResultForLog(result));
4786
4882
  const structuredContentWithoutMessage = { ...result.structuredContent };
4787
4883
  if (structuredContentWithoutMessage && 'message' in structuredContentWithoutMessage) {
4788
4884
  delete structuredContentWithoutMessage.message;
@@ -4893,6 +4989,12 @@ const DEFAULT_RETRY_CONFIG = [
4893
4989
  timeout: [2000, 4000, 8000, 16000, 32000],
4894
4990
  },
4895
4991
  ];
4992
+ // node-fetch forwards the key header across a cross-origin redirect, and req's HTTP/2 path
4993
+ // rebuilds the request without its `redirect` mode.
4994
+ const NO_REDIRECTS = {
4995
+ hooks: { beforeRequest: ({ request }) => ({ request, redirect: 'error' }) },
4996
+ httpVersion: 1,
4997
+ };
4896
4998
  /**
4897
4999
  * API Client for Eyes server using @applitools/req for automatic retry handling
4898
5000
  */
@@ -4927,6 +5029,7 @@ class ApiClient {
4927
5029
  },
4928
5030
  requestTimeout: this.timeout,
4929
5031
  retry: this.retryConfig,
5032
+ ...NO_REDIRECTS,
4930
5033
  });
4931
5034
  if (response.status === 401) {
4932
5035
  throw new InvalidApiKeyError(this.apiKey);
@@ -4949,9 +5052,10 @@ class ApiClient {
4949
5052
  },
4950
5053
  requestTimeout: this.timeout,
4951
5054
  retry: this.retryConfig,
5055
+ ...NO_REDIRECTS,
4952
5056
  });
4953
- // Handle authentication errors
4954
- if (response.status === 401) {
5057
+ // Handle authentication errors; a 403 refuses the key too, which account-id-resolver remembers
5058
+ if (response.status === 401 || response.status === 403) {
4955
5059
  throw new InvalidApiKeyError(this.apiKey);
4956
5060
  }
4957
5061
  if (!response.ok) {
@@ -4978,16 +5082,16 @@ class ApiClient {
4978
5082
  const reqOptions = {
4979
5083
  method: 'POST',
4980
5084
  headers: {
5085
+ 'X-Eyes-Api-Key': this.apiKey,
4981
5086
  'Content-Type': 'application/json',
4982
5087
  Accept: 'application/json',
4983
5088
  },
4984
5089
  body,
4985
5090
  requestTimeout: this.timeout,
4986
5091
  retry: this.retryConfig,
5092
+ ...NO_REDIRECTS,
4987
5093
  };
4988
- // Add API key to query for POST requests (Eyes API pattern)
4989
- const url = `${this.baseUrl}/${endpoint}${endpoint.includes('?') ? '&' : '?'}apiKey=${this.apiKey}`;
4990
- const response = await req.req(url, reqOptions);
5094
+ const response = await req.req(`${this.baseUrl}/${endpoint}`, reqOptions);
4991
5095
  // Handle authentication errors
4992
5096
  if (response.status === 401) {
4993
5097
  throw new InvalidApiKeyError(this.apiKey);
@@ -5050,14 +5154,15 @@ const VERIFY_RETRY_CONFIG = [
5050
5154
  */
5051
5155
  async function verifyApiKeyWithServer(params) {
5052
5156
  const { apiKey, serverUrl } = params;
5157
+ assertTrustedEyesUrl(serverUrl);
5053
5158
  const client = new ApiClient({
5054
5159
  baseUrl: serverUrl,
5055
5160
  apiKey: apiKey,
5056
5161
  timeout: 2000,
5057
5162
  retryConfig: VERIFY_RETRY_CONFIG,
5058
5163
  });
5059
- const response = await client.get(`api/auth/access?accessKey=${apiKey}`);
5060
- log$2('debug', `API key verification response: ${JSON.stringify(response)}`);
5164
+ const response = await client.get('api/auth/access');
5165
+ log$1('debug', `API key verification response: ${JSON.stringify(response)}`);
5061
5166
  if (response.accountId === '') {
5062
5167
  throw new Error('Invalid API key');
5063
5168
  }
@@ -5083,12 +5188,17 @@ const VerifyApiKeyInputSchema = zod.z.object({
5083
5188
  .optional()
5084
5189
  .describe('If true, save the validated API key and server URL as the default configuration in cache'),
5085
5190
  });
5191
+ // A key that fails validation is the one telemetry case where a key is reported, masked so that
5192
+ // a short value is never shown.
5193
+ function reportUnvalidatedKey(apiKey) {
5194
+ recordToolTelemetry({ api_key_masked: apiKey.length <= 7 ? '***' : `${apiKey.slice(0, 3)}***${apiKey.slice(-3)}` });
5195
+ }
5086
5196
  /** Verify API key handler function */
5087
5197
  async function verifyApiKey(input = {}) {
5088
5198
  // Determine working directory
5089
5199
  const workingDirectory = input.workingDirectory || input.workspaceRoot || process.cwd();
5090
- log$2('debug', `Verifying Eyes API key in working directory: ${workingDirectory}`);
5091
- log$2('debug', `Input parameters: ${JSON.stringify(input)}`);
5200
+ log$1('debug', `Verifying Eyes API key in working directory: ${workingDirectory}`);
5201
+ log$1('debug', `Input parameters: ${JSON.stringify(input)}`);
5092
5202
  // Get API key - priority: input parameter > credential loader (server-context > config files > env vars)
5093
5203
  let apiKey = input.apiKey;
5094
5204
  let serverUrl = input.serverUrl;
@@ -5113,10 +5223,21 @@ async function verifyApiKey(input = {}) {
5113
5223
  new URL(finalServerUrl);
5114
5224
  }
5115
5225
  catch {
5226
+ reportUnvalidatedKey(apiKey);
5116
5227
  return {
5117
5228
  message: wrapText('Eyes authentication failed. Invalid server URL format. Please verify that your server URL is correct.', 'suffix'),
5118
5229
  };
5119
5230
  }
5231
+ try {
5232
+ assertTrustedEyesUrl(finalServerUrl);
5233
+ }
5234
+ catch (error) {
5235
+ reportUnvalidatedKey(apiKey);
5236
+ return {
5237
+ message: wrapText(`Eyes authentication failed: ${error.message}. ` +
5238
+ 'Correct the server URL where it is set: the serverUrl argument, APPLITOOLS_SERVER_URL or the project config file.', 'suffix'),
5239
+ };
5240
+ }
5120
5241
  // Call Eyes API to verify the key
5121
5242
  try {
5122
5243
  await verifyApiKeyWithServer({ apiKey, serverUrl: finalServerUrl });
@@ -5133,6 +5254,7 @@ async function verifyApiKey(input = {}) {
5133
5254
  }
5134
5255
  catch {
5135
5256
  // Return invalid for any error (401, network, etc.)
5257
+ reportUnvalidatedKey(apiKey);
5136
5258
  return {
5137
5259
  message: wrapText('Eyes authentication failed. Please verify that your API Key or server URL is correct. Visit our documentation to learn how to retrieve these values: https://applitools.com/docs/eyes/playwright#set-your-applitools-api-key', 'suffix'),
5138
5260
  };
@@ -5272,7 +5394,8 @@ const PlaywrightJsSetupProjectClientInputSchema = createClientInputSchema(Playwr
5272
5394
  async function eyesSetupProject(input = {}) {
5273
5395
  const { workspaceRoot, warning } = validateCommonInput(input);
5274
5396
  let apiKey = getLastValidatedApiKey() || findApiKey(workspaceRoot).apiKey;
5275
- let eyesServerUrl = getLastValidatedServerUrl() || findApiKey(workspaceRoot).serverUrl;
5397
+ const foundServerUrl = getLastValidatedServerUrl() || findApiKey(workspaceRoot).serverUrl;
5398
+ let eyesServerUrl = foundServerUrl && isTrustedEyesUrl(foundServerUrl) ? foundServerUrl : undefined;
5276
5399
  const requiredApiKeyMessage = !apiKey
5277
5400
  ? 'IMPORTANT: An Applitools API key is required to run visual tests. Please provide your API key using the --apiKey argument when running npx eyes-setup, or set it in your environment variables or Playwright config file.'
5278
5401
  : '';
@@ -5858,20 +5981,30 @@ function instrumentedRegistrar(server) {
5858
5981
  const defaultResolverDeps = {
5859
5982
  verify: verifyApiKeyWithServer,
5860
5983
  };
5861
- // No expiry: an accountId is a fixed property of the account behind the key, so a resolved entry
5862
- // can never go stale. Holds the in-flight promise so a burst of URL builds shares one verification.
5984
+ // A resolved entry never expires: an accountId is a fixed property of the account behind the key.
5985
+ // Holds the in-flight promise so a burst of URL builds shares one verification.
5863
5986
  const accountIds = new Map();
5987
+ // A refusal can be temporary (a proxy's 403, permissions granted later), so it is retried after this long.
5988
+ const REFUSAL_TTL_MS = 5 * 60 * 1000;
5989
+ const refusalExpiry = new Map();
5864
5990
  function realAccountId(apiKey, serverUrl, deps) {
5991
+ var _a, _b;
5865
5992
  // serverUrl joins the key because one API key against two servers is two accounts.
5866
5993
  const key = `${serverUrl}::${apiKey}`;
5994
+ const now = (_a = deps.now) !== null && _a !== void 0 ? _a : (() => performance.now());
5867
5995
  const known = accountIds.get(key);
5868
- if (known)
5996
+ if (known && ((_b = refusalExpiry.get(key)) !== null && _b !== void 0 ? _b : Infinity) > now())
5869
5997
  return known;
5870
5998
  const promise = deps.verify({ apiKey, serverUrl }).then(result => result.accountId);
5871
5999
  accountIds.set(key, promise);
5872
- // Failures are not remembered — a transient error must not poison the id for the whole process.
5873
- promise.catch(() => {
5874
- if (accountIds.get(key) === promise)
6000
+ refusalExpiry.delete(key);
6001
+ // A refused key is not sent again until the refusal expires; any other failure is retried next call.
6002
+ promise.catch(error => {
6003
+ if (accountIds.get(key) !== promise)
6004
+ return;
6005
+ if (error instanceof InvalidApiKeyError)
6006
+ refusalExpiry.set(key, now() + REFUSAL_TTL_MS);
6007
+ else
5875
6008
  accountIds.delete(key);
5876
6009
  });
5877
6010
  return promise;
@@ -5884,6 +6017,10 @@ function realAccountId(apiKey, serverUrl, deps) {
5884
6017
  * failure also returns the input unchanged.
5885
6018
  */
5886
6019
  async function getFullAccountId(accountId, apiKey, serverUrl = DEFAULT_SERVER_URL, deps = defaultResolverDeps) {
6020
+ // Padded base64 always has a length divisible by 4 and stripped padding never leaves one, so an id
6021
+ // of such a length is already complete and a lookup could not change it.
6022
+ if (accountId && accountId.length % 4 === 0)
6023
+ return accountId;
5887
6024
  try {
5888
6025
  const real = await realAccountId(apiKey, serverUrl, deps);
5889
6026
  if (accountId === undefined)
@@ -6743,6 +6880,7 @@ function textResult(text) {
6743
6880
  * variable name and the wording of the note that follows.
6744
6881
  */
6745
6882
  function resolveApiKey(spec, urlForAccountHint) {
6883
+ assertTrustedEyesUrl(urlForAccountHint);
6746
6884
  const apiKey = process.env[spec.envVar];
6747
6885
  if (apiKey)
6748
6886
  return apiKey;
@@ -7921,7 +8059,7 @@ function registerEyesResolveTools(server, deps = defaultCommandsDeps) {
7921
8059
  * consolidates into that investigation's own single debug log rather than scattering per level.
7922
8060
  */
7923
8061
  function log(scopeId, label, fields = {}, deps) {
7924
- log$1(rootScopeId(scopeId), label, fields, deps);
8062
+ log$2(rootScopeId(scopeId), label, fields, deps);
7925
8063
  }
7926
8064
  /** The exact path `log` above appends `scopeId`'s investigation's entries to — see `log`'s own doc comment for the root-normalization it applies first. */
7927
8065
  function debugLogPath(scopeId, deps) {
@@ -11410,7 +11548,7 @@ function registeredToolNames(experimental) {
11410
11548
  }
11411
11549
 
11412
11550
  async function startServer() {
11413
- loadEnvOnce(process.cwd(), 'server startup');
11551
+ syncWorkspaceKeys(process.cwd(), 'server startup');
11414
11552
  const experimental = parseExperimental(process.env);
11415
11553
  const server = new mcp_js.McpServer({
11416
11554
  name: 'applitools-mcp',
@@ -11447,7 +11585,7 @@ async function startServer() {
11447
11585
  const clientInfo = server.server.getClientVersion();
11448
11586
  setClientInfo(clientInfo);
11449
11587
  setIDE(parseIDE(process.env, process.argv));
11450
- log$2('info', '[MCP Server] Client connected:', {
11588
+ log$1('info', '[MCP Server] Client connected:', {
11451
11589
  name: (clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.name) || 'unknown',
11452
11590
  version: (clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.version) || 'unknown',
11453
11591
  description: clientInfo === null || clientInfo === void 0 ? void 0 : clientInfo.description,
@@ -11468,9 +11606,9 @@ async function startServer() {
11468
11606
  .then(({ roots }) => {
11469
11607
  const root = roots.find(r => r.uri.startsWith('file://'));
11470
11608
  if (root)
11471
- loadEnvOnce(node_url.fileURLToPath(root.uri), 'client roots');
11609
+ syncWorkspaceKeys(node_url.fileURLToPath(root.uri), 'client roots');
11472
11610
  })
11473
- .catch(error => log$2('debug', '[MCP Server] roots/list failed:', error));
11611
+ .catch(error => log$1('debug', '[MCP Server] roots/list failed:', error));
11474
11612
  }
11475
11613
  };
11476
11614
  registerAllTools(server, experimental);
@@ -11484,28 +11622,28 @@ async function startServer() {
11484
11622
  return result;
11485
11623
  }
11486
11624
  catch (error) {
11487
- log$2('error', '[MCP Server] Resource documentation read failed:', error);
11625
+ log$1('error', '[MCP Server] Resource documentation read failed:', error);
11488
11626
  throw error;
11489
11627
  }
11490
11628
  });
11491
- log$2('info', '[MCP Server] Registered resources: documentation');
11629
+ log$1('info', '[MCP Server] Registered resources: documentation');
11492
11630
  const credentialsLoaded = loadAndStoreCredentials();
11493
11631
  if (credentialsLoaded) {
11494
- log$2('info', '[MCP Server] Credentials loaded from config/environment for stdio mode');
11632
+ log$1('info', '[MCP Server] Credentials loaded from config/environment for stdio mode');
11495
11633
  }
11496
11634
  const transport = new stdio_js.StdioServerTransport();
11497
11635
  await server.connect(transport);
11498
- log$2('info', '[MCP Server] Applitools MCP Server started successfully (Stdio Mode)');
11499
- log$2('info', `[MCP Server] Experimental tools ${experimental ? 'enabled' : 'disabled'}`);
11500
- log$2('info', `[MCP Server] Available tools: ${registeredToolNames(experimental).join(', ')}`);
11501
- log$2('info', `[MCP Server] Available resources: documentation (${RESOURCE_URIS.DOCUMENTATION_README})`);
11636
+ log$1('info', '[MCP Server] Applitools MCP Server started successfully (Stdio Mode)');
11637
+ log$1('info', `[MCP Server] Experimental tools ${experimental ? 'enabled' : 'disabled'}`);
11638
+ log$1('info', `[MCP Server] Available tools: ${registeredToolNames(experimental).join(', ')}`);
11639
+ log$1('info', `[MCP Server] Available resources: documentation (${RESOURCE_URIS.DOCUMENTATION_README})`);
11502
11640
  }
11503
11641
  process.on('SIGINT', () => {
11504
- log$2('info', '[MCP Server] Received SIGINT, shutting down gracefully...');
11642
+ log$1('info', '[MCP Server] Received SIGINT, shutting down gracefully...');
11505
11643
  process.exit(0);
11506
11644
  });
11507
11645
  process.on('SIGTERM', () => {
11508
- log$2('info', '[MCP Server] Received SIGTERM, shutting down gracefully...');
11646
+ log$1('info', '[MCP Server] Received SIGTERM, shutting down gracefully...');
11509
11647
  process.exit(0);
11510
11648
  });
11511
11649
  const REJECTION_LOG_THROTTLE_MS = 1000;
@@ -11528,17 +11666,17 @@ function makeThrottledRejectionHandler(logFn, throttleMs = REJECTION_LOG_THROTTL
11528
11666
  }
11529
11667
  };
11530
11668
  }
11531
- process.on('unhandledRejection', makeThrottledRejectionHandler((...args) => log$2('error', ...args)));
11669
+ process.on('unhandledRejection', makeThrottledRejectionHandler((...args) => log$1('error', ...args)));
11532
11670
  process.on('uncaughtException', error => {
11533
11671
  if (error.code === 'EPIPE') {
11534
11672
  process.stderr.write('[MCP Server] Client disconnected (EPIPE), shutting down gracefully...\n');
11535
11673
  process.exit(0);
11536
11674
  }
11537
- log$2('error', '[MCP Server] Uncaught Exception:', error);
11675
+ log$1('error', '[MCP Server] Uncaught Exception:', error);
11538
11676
  });
11539
11677
 
11540
11678
  startServer().catch(error => {
11541
- log$2('error', '[MCP Server] Failed to start Applitools Eyes MCP server:', error);
11679
+ log$1('error', '[MCP Server] Failed to start Applitools Eyes MCP server:', error);
11542
11680
  process.exit(1);
11543
11681
  });
11544
11682
  //# sourceMappingURL=index.js.map