@browserstack/mcp-server 2.2.3 → 2.3.0-beta.2

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.
@@ -1,14 +1,4 @@
1
1
  import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
2
- /**
3
- * Returns the most specific human-readable text for an error raised by an
4
- * API call, capped at 500 characters. For an AxiosError with a response body
5
- * it prefers the body's `message`, `error` or `errors` field, serialising
6
- * objects, and uses the whole body when none of those fields exist. An empty,
7
- * whitespace-only or HTML-document body falls back to the error's own message.
8
- * @param err - The error object to describe
9
- * @param defaultText - The fallback error message
10
- */
11
- export declare function errorText(err: unknown, defaultText: string): string;
12
2
  /**
13
3
  * Formats an AxiosError into a CallToolResult with an appropriate message.
14
4
  * @param err - The error object to format
package/dist/lib/error.js CHANGED
@@ -1,75 +1,23 @@
1
1
  import { AxiosError } from "axios";
2
- const MAX_ERROR_TEXT = 500;
3
- const BODY_FIELDS = ["message", "error", "errors"];
4
- function clip(text) {
5
- return text.length > MAX_ERROR_TEXT ? text.slice(0, MAX_ERROR_TEXT) : text;
6
- }
7
- const HTML_DOCUMENT = /^\s*<(!doctype|html)\b/i;
8
- function stringify(value) {
9
- if (typeof value === "string") {
10
- return HTML_DOCUMENT.test(value) ? "" : value.trim();
11
- }
12
- if (value === undefined || value === null)
13
- return "";
14
- try {
15
- const json = JSON.stringify(value);
16
- return json === "{}" || json === "[]" ? "" : (json ?? "");
17
- }
18
- catch {
19
- return "";
20
- }
21
- }
22
- /**
23
- * Text taken from an API error body: the first non-empty `message`, `error`
24
- * or `errors` field when any of them is present, otherwise the whole body.
25
- * Returns undefined when the body carries no usable text.
26
- */
27
- function bodyText(data) {
28
- if (typeof data !== "object" || data === null) {
29
- const text = stringify(data);
30
- return text ? clip(text) : undefined;
31
- }
32
- const record = data;
33
- const named = BODY_FIELDS.filter((key) => key in record);
34
- if (named.length > 0) {
35
- for (const key of named) {
36
- const text = stringify(record[key]);
37
- if (text)
38
- return clip(text);
39
- }
40
- return undefined;
41
- }
42
- const text = stringify(record);
43
- return text ? clip(text) : undefined;
44
- }
45
- /**
46
- * Returns the most specific human-readable text for an error raised by an
47
- * API call, capped at 500 characters. For an AxiosError with a response body
48
- * it prefers the body's `message`, `error` or `errors` field, serialising
49
- * objects, and uses the whole body when none of those fields exist. An empty,
50
- * whitespace-only or HTML-document body falls back to the error's own message.
51
- * @param err - The error object to describe
52
- * @param defaultText - The fallback error message
53
- */
54
- export function errorText(err, defaultText) {
55
- if (err instanceof AxiosError) {
56
- const text = bodyText(err.response?.data);
57
- if (text)
58
- return text;
59
- return clip(err.message || defaultText);
60
- }
61
- if (err instanceof Error)
62
- return clip(err.message || defaultText);
63
- return defaultText;
64
- }
65
2
  /**
66
3
  * Formats an AxiosError into a CallToolResult with an appropriate message.
67
4
  * @param err - The error object to format
68
5
  * @param defaultText - The fallback error message
69
6
  */
70
7
  export function formatAxiosError(err, defaultText) {
8
+ let text = defaultText;
9
+ if (err instanceof AxiosError && err.response?.data) {
10
+ const message = err.response.data.message ||
11
+ err.response.data.error ||
12
+ err.message ||
13
+ defaultText;
14
+ text = message;
15
+ }
16
+ else if (err instanceof Error) {
17
+ text = err.message;
18
+ }
71
19
  return {
72
- content: [{ type: "text", text: errorText(err, defaultText) }],
20
+ content: [{ type: "text", text }],
73
21
  isError: true,
74
22
  };
75
23
  }
package/dist/lib/utils.js CHANGED
@@ -7,9 +7,6 @@ export function sanitizeUrlParam(param) {
7
7
  return param.replace(/[;&|`$(){}[\]<>]/g, "");
8
8
  }
9
9
  const ONE_MB = 1048576;
10
- // sharp's default (~268M px) lets one image decode to ~1 GB of RGBA; 25M px caps it near 100 MB.
11
- const MAX_INPUT_PIXELS = 25_000_000;
12
- const MAX_IMAGE_DIMENSION = 1920;
13
10
  let sharpConfigured = false;
14
11
  //Compresses a base64 image intelligently to keep it under 1 MB if needed.
15
12
  export async function maybeCompressBase64(base64) {
@@ -28,19 +25,11 @@ export async function maybeCompressBase64(base64) {
28
25
  sharp.concurrency(1);
29
26
  sharpConfigured = true;
30
27
  }
31
- const image = globalConfig.REMOTE_MCP
32
- ? sharp(buffer, { limitInputPixels: MAX_INPUT_PIXELS }).resize({
33
- width: MAX_IMAGE_DIMENSION,
34
- height: MAX_IMAGE_DIMENSION,
35
- fit: "inside",
36
- withoutEnlargement: true,
37
- })
38
- : sharp(buffer);
39
- const compressedBuffer = await image.png({ quality }).toBuffer();
28
+ const compressedBuffer = await sharp(buffer).png({ quality }).toBuffer();
40
29
  return compressedBuffer.toString("base64");
41
30
  }
42
31
  catch (err) {
43
- logger.warn("Image compression failed; returning the uncompressed image. %s", err instanceof Error ? err.message : String(err));
32
+ logger.warn("Image compression unavailable (sharp failed to load); returning the uncompressed image. %s", err instanceof Error ? err.message : String(err));
44
33
  return base64;
45
34
  }
46
35
  }
@@ -1,10 +1,6 @@
1
1
  import { SessionType } from "../../lib/constants.js";
2
2
  import { BrowserStackConfig } from "../../lib/types.js";
3
- export declare const MAX_SCREENSHOT_BYTES: number | undefined;
4
- export declare function parseScreenshotUrls(text: string): string[];
5
- export type Screenshot = {
3
+ export declare function fetchAutomationScreenshots(sessionId: string, sessionType: SessionType | undefined, config: BrowserStackConfig): Promise<{
6
4
  url: string;
7
5
  base64: string;
8
- mimeType: string;
9
- };
10
- export declare function fetchAutomationScreenshots(sessionId: string, sessionType: SessionType | undefined, config: BrowserStackConfig): Promise<Screenshot[]>;
6
+ }[]>;
@@ -3,10 +3,6 @@ import { SessionType } from "../../lib/constants.js";
3
3
  import { getBrowserStackAuth } from "../../lib/get-auth.js";
4
4
  import { apiClient } from "../../lib/apiClient.js";
5
5
  import globalConfig from "../../config.js";
6
- import { MAX_LOG_BYTES } from "../failurelogs-utils/utils.js";
7
- export const MAX_SCREENSHOT_BYTES = globalConfig.REMOTE_MCP
8
- ? 10 * 1024 * 1024
9
- : undefined;
10
6
  async function extractScreenshotUrls(sessionId, sessionType, config) {
11
7
  const authString = getBrowserStackAuth(config);
12
8
  const auth = Buffer.from(authString).toString("base64");
@@ -18,112 +14,47 @@ async function extractScreenshotUrls(sessionId, sessionType, config) {
18
14
  "Content-Type": "application/json",
19
15
  Authorization: `Basic ${auth}`,
20
16
  },
21
- maxContentLength: MAX_LOG_BYTES,
22
17
  raise_error: false,
23
18
  });
24
- if (response.status === 413) {
25
- throw new Error("The logs for this session are too large (over 5 MB) to find screenshots here. Open the session in the BrowserStack dashboard to view them.");
26
- }
27
19
  await assertOkResponse(response, "Session");
28
20
  const text = typeof response.data === "string"
29
21
  ? response.data
30
22
  : JSON.stringify(response.data);
31
- return parseScreenshotUrls(text);
32
- }
33
- const LOG_PREFIX = String.raw `^\d{4}-\d{2}-\d{2} \d{1,2}:\d{1,2}:\d{1,2}:\d{1,3} `;
34
- const LINE_TYPE_PATTERN = new RegExp(`${LOG_PREFIX}([A-Z_]+) `);
35
- const SCREENSHOT_REQUEST_PATTERN = new RegExp(String.raw `${LOG_PREFIX}REQUEST \[[^\]]+\] GET /session/[^/\s]+/screenshot(\s|$)`);
36
- const RESPONSE_VALUE_PATTERN = new RegExp(String.raw `${LOG_PREFIX}RESPONSE \{"value"\s*:\s*"(https://[^"]+)"`);
37
- const DEBUG_SCREENSHOT_PATTERN = new RegExp(String.raw `${LOG_PREFIX}DEBUG (https://\S+)$`);
38
- const TRUSTED_HOST_PATTERN = /(^|\.)browserstack\.com$|\.s3([.-][a-z0-9-]+)*\.amazonaws\.com$|\.backblazeb2\.com$/;
39
- function isTrustedScreenshotUrl(value) {
40
- try {
41
- const url = new URL(value);
42
- return url.protocol === "https:" && TRUSTED_HOST_PATTERN.test(url.hostname);
43
- }
44
- catch {
45
- return false;
46
- }
47
- }
48
- export function parseScreenshotUrls(text) {
49
23
  const urls = [];
50
- const lines = text.split("\n").map((line) => line.trimEnd());
51
- for (let i = 0; i < lines.length; i++) {
52
- const line = lines[i];
53
- const debugMatch = line.match(DEBUG_SCREENSHOT_PATTERN);
54
- if (debugMatch) {
55
- urls.push(debugMatch[1]);
56
- continue;
57
- }
58
- if (!SCREENSHOT_REQUEST_PATTERN.test(line)) {
59
- continue;
60
- }
61
- for (let j = i + 1; j < lines.length; j++) {
62
- const lineType = lines[j].match(LINE_TYPE_PATTERN)?.[1];
63
- if (lineType === "REQUEST") {
64
- break;
65
- }
66
- if (lineType === "RESPONSE") {
67
- const valueMatch = lines[j].match(RESPONSE_VALUE_PATTERN);
68
- if (valueMatch) {
69
- urls.push(valueMatch[1]);
70
- }
71
- break;
24
+ const SCREENSHOT_PATTERN = /REQUEST.*GET.*\/screenshot/;
25
+ const RESPONSE_VALUE_PATTERN = /"value"\s*:\s*"([^"]+)"/;
26
+ // Split logs into lines and process them
27
+ const lines = text.split("\n");
28
+ for (let i = 0; i < lines.length - 1; i++) {
29
+ const currentLine = lines[i];
30
+ const nextLine = lines[i + 1];
31
+ if (SCREENSHOT_PATTERN.test(currentLine)) {
32
+ const match = nextLine.match(RESPONSE_VALUE_PATTERN);
33
+ if (match && match[1]) {
34
+ urls.push(match[1]);
72
35
  }
73
36
  }
74
37
  }
75
- return [...new Set(urls)].filter(isTrustedScreenshotUrl);
76
- }
77
- function detectImageMimeType(buffer) {
78
- if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
79
- return "image/jpeg";
80
- }
81
- return "image/png";
38
+ return urls;
82
39
  }
83
- // Returns null for a screenshot over MAX_SCREENSHOT_BYTES so the rest still load.
84
40
  async function fetchAndCompress(url) {
85
- const response = await apiClient.get({
86
- url,
87
- responseType: "arraybuffer",
88
- maxContentLength: MAX_SCREENSHOT_BYTES,
89
- raise_error: false,
90
- });
91
- if (response.status === 413) {
92
- return null;
93
- }
94
- if (!response.ok) {
95
- throw new Error(`Failed to download screenshot: ${response.status} ${response.statusText}`);
96
- }
41
+ const response = await apiClient.get({ url, responseType: "arraybuffer" });
97
42
  // Axios returns response.data as a Buffer for binary data
98
- const buffer = Buffer.from(response.data);
99
- const base64 = await maybeCompressBase64(buffer.toString("base64"));
100
- // Detect AFTER compression: sharp re-encodes anything over 1 MB to PNG, so
101
- // reading the original bytes would label a large JPEG with the wrong type.
102
- return {
103
- url,
104
- base64,
105
- mimeType: detectImageMimeType(Buffer.from(base64, "base64")),
106
- };
43
+ const base64 = Buffer.from(response.data).toString("base64");
44
+ return { url, base64: await maybeCompressBase64(base64) };
107
45
  }
108
46
  //Converts screenshot URLs to base64 encoded images
109
47
  async function convertUrlsToBase64(urls) {
110
- let results;
111
48
  // Hosted pods are memory-constrained: process one image at a time. Local runs
112
49
  // keep the concurrent path.
113
50
  if (globalConfig.REMOTE_MCP) {
114
- results = [];
51
+ const screenshots = [];
115
52
  for (const url of urls) {
116
- results.push(await fetchAndCompress(url));
53
+ screenshots.push(await fetchAndCompress(url));
117
54
  }
55
+ return screenshots;
118
56
  }
119
- else {
120
- results = await Promise.all(urls.map(fetchAndCompress));
121
- }
122
- const screenshots = results.filter((s) => s !== null);
123
- if (urls.length > 0 && screenshots.length === 0) {
124
- throw new Error("The screenshots in this session are too large (over 10 MB each) to fetch here. Open the session in the BrowserStack dashboard to view them.");
125
- }
126
- return screenshots;
57
+ return Promise.all(urls.map(fetchAndCompress));
127
58
  }
128
59
  //Fetches and converts screenshot URLs to base64 encoded images
129
60
  export async function fetchAutomationScreenshots(sessionId, sessionType = SessionType.Automate, config) {
@@ -14,7 +14,7 @@ export async function fetchAutomationScreenshotsTool(args, config) {
14
14
  content: [
15
15
  {
16
16
  type: "text",
17
- text: "No screenshots found in the session logs. Run with browserstack.debug: true to capture visual-log screenshots.",
17
+ text: "No screenshots found in the session or some unexpected error occurred",
18
18
  },
19
19
  ],
20
20
  isError: true,
@@ -23,7 +23,7 @@ export async function fetchAutomationScreenshotsTool(args, config) {
23
23
  const results = screenshots.map((screenshot, index) => ({
24
24
  type: "image",
25
25
  data: screenshot.base64,
26
- mimeType: screenshot.mimeType,
26
+ mimeType: "image/png",
27
27
  _meta: { url: screenshot.url, index: index + 1 },
28
28
  }));
29
29
  return {
@@ -7,6 +7,8 @@
7
7
  * one is meant, which is exactly why the Python side used to rename body fields `body_*`.
8
8
  * Grouping removes the collision AND the rename, so a caller sends the spec's own names.
9
9
  */
10
+ import appConfig from "../../config.js";
11
+ import { APP_BINARY_EXTENSIONS, MAX_APP_UPLOAD_BYTES, validateUploadPath, } from "../../lib/upload-validator.js";
10
12
  import { InvocationError } from "./index-loader.js";
11
13
  /**
12
14
  * String formats worth ENFORCING, as opposed to merely publishing.
@@ -202,6 +204,34 @@ export function coerce(value, param) {
202
204
  }
203
205
  function coerceType(value, param, label = param.name) {
204
206
  const expected = param.type;
207
+ if (expected === "any") {
208
+ // PASSES THROUGH UNTOUCHED, which is the whole point of declaring it. A polymorphic
209
+ // parameter reached the string branch and arrived as text: WebDriver's frame id takes a
210
+ // number, an element reference or null, and `null` sent as "null" is refused as an
211
+ // invalid argument — a failure that reads like the caller chose the wrong frame.
212
+ return value;
213
+ }
214
+ if (expected === "file") {
215
+ // CHECKED HERE, not at egress: `bind` runs dry before the write-consent gate, so a path
216
+ // that does not exist — or a base directory nobody configured — is refused before the
217
+ // user is asked to approve an upload that was never going to happen.
218
+ //
219
+ // The rules are the ones the server already applies to every other upload, so the
220
+ // answer does not depend on which surface asked.
221
+ const given = String(value ?? "").trim();
222
+ if (!given)
223
+ throw new InvocationError(`'${label}' must be a path to a file`);
224
+ try {
225
+ return validateUploadPath(given, {
226
+ allowedExtensions: APP_BINARY_EXTENSIONS,
227
+ maxSizeBytes: MAX_APP_UPLOAD_BYTES,
228
+ allowedBaseDir: appConfig.UPLOAD_BASE_DIR,
229
+ });
230
+ }
231
+ catch (error) {
232
+ throw new InvocationError(error instanceof Error ? error.message : String(error));
233
+ }
234
+ }
205
235
  if (expected === "object" || expected === "array") {
206
236
  // An opaque body object is passed through as given: the spec does not describe its
207
237
  // fields, so validating or reshaping it would mean inventing a contract.
@@ -267,6 +297,32 @@ function coerceType(value, param, label = param.name) {
267
297
  if (untyped && (typeof value === "object" || typeof value === "boolean")) {
268
298
  return value;
269
299
  }
300
+ // A DECLARED STRING IS NOT A LICENCE TO STRINGIFY ANYTHING.
301
+ //
302
+ // The untyped case above was fixed because `String(value)` destroyed objects the spec had
303
+ // declined to describe. A DECLARED string was left stringifying whatever arrived, and it
304
+ // is the worse of the two: an object sent for `create_test_case_comment`'s `comment` was
305
+ // serialised to the literal text "[object Object]", the API accepted it, the write
306
+ // returned 200, and the agent reported success in good faith. tm exposes no comment
307
+ // delete, so that text is now permanently on the case.
308
+ //
309
+ // A 400 teaches the caller what it got wrong. A 200 that stores "[object Object]" teaches
310
+ // it nothing and cannot be undone, so refuse here rather than let it reach the wire.
311
+ //
312
+ // `null` passes through instead of becoming the five characters "null", which no API has
313
+ // ever wanted: several string parameters document null as the way to CLEAR a field —
314
+ // `test_plan_id` says "send null or '' to unlink" — and stringifying it silently sent a
315
+ // value where the caller meant to send an absence.
316
+ if (expected === "string") {
317
+ if (value === null || value === undefined)
318
+ return value;
319
+ if (typeof value === "object") {
320
+ throw new InvocationError(`'${label}' must be a string, and was ${Array.isArray(value) ? "a list" : "an object"}. ` +
321
+ `Serialising it would send the text ` +
322
+ `${JSON.stringify(Array.isArray(value) ? "[object Array]" : "[object Object]")} ` +
323
+ `rather than its contents, and the call would succeed with that stored.`);
324
+ }
325
+ }
270
326
  const text = String(value);
271
327
  if (param.values && param.values.length > 0) {
272
328
  const allowed = param.values.map((v) => String(v));
@@ -21,31 +21,7 @@ import { Transport } from "./egress.js";
21
21
  export declare function selectedEnvironment(): string;
22
22
  /** True when this product's host is account-specific and must be discovered per call. */
23
23
  export declare function isRegionSharded(product: string, source?: HostSource): boolean;
24
- /**
25
- * Resolve a product's host.
26
- *
27
- * Atlas resolves: an explicit per-session override, then the host for the session's
28
- * environment (`harness.extra_environments[env][product]`), then the profile's own
29
- * `base_url`. The same rungs, in the same order, with one addition:
30
- *
31
- * 1. CAPABILITY_REGISTRY_BASE_URL_<PRODUCT> explicit, environment-agnostic
32
- * 2. CAPABILITY_REGISTRY_BASE_URL_<PRODUCT>_<ENV> this environment's host
33
- * 3. CAPABILITY_REGISTRY_BASE_URLS {product:{env:url}} the same, as one map
34
- * 4. account discovery — the index's `base_urls`, probed
35
- * 5. the single host declared in the index, `base_url`
36
- * 6. refuse, by name
37
- *
38
- * DISCOVERY OUTRANKS THE DECLARED HOST, which is where this departs from Atlas. A declared
39
- * host is one fixed origin, so for a region-sharded product it would send every account
40
- * outside the default region to the wrong host — a failure that only shows up on those
41
- * accounts, and so passes any test run from inside the default one. Discovery answers with
42
- * the region the account is actually on; `base_url` is the fallback for when the probe
43
- * cannot answer at all.
44
- *
45
- * Refusing rather than guessing is deliberate: a guessed host fails as a DNS error or a 404
46
- * that reads like the caller's problem, when it is our missing configuration.
47
- */
48
- export declare function resolveBaseUrl(product: string, config: BrowserStackConfig, source?: HostSource, transport?: Transport): Promise<string>;
24
+ export declare function resolveBaseUrl(product: string, config: BrowserStackConfig, source?: HostSource, transport?: Transport, host?: string): Promise<string>;
49
25
  /**
50
26
  * Locate the artifact(s).
51
27
  *
@@ -86,10 +86,49 @@ function credentialsFrom(config) {
86
86
  * Refusing rather than guessing is deliberate: a guessed host fails as a DNS error or a 404
87
87
  * that reads like the caller's problem, when it is our missing configuration.
88
88
  */
89
- export async function resolveBaseUrl(product, config, source, transport) {
89
+ /**
90
+ * The host a capability named, as opposed to the product's own.
91
+ *
92
+ * `_HOST_` is in the override variable deliberately. The environment-suffixed form is
93
+ * `CAPABILITY_REGISTRY_BASE_URL_<PRODUCT>_<ENV>`, so a bare
94
+ * `CAPABILITY_REGISTRY_BASE_URL_APPAUTOMATE_HUB` would mean the hub host or the "hub"
95
+ * environment depending on which the reader had in mind — and whichever the code chose,
96
+ * the other reading sends a call to the wrong origin silently.
97
+ *
98
+ * A named environment refuses rather than falling back to the declared host, for the same
99
+ * reason the product-level resolver does: a preprod session must not reach production
100
+ * because nobody defined preprod's hub.
101
+ */
102
+ function resolveNamedHost(product, key, host, source, environment) {
103
+ const trim = (url) => url.replace(/\/$/, "");
104
+ const suffix = `${key}_HOST_${host.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}`;
105
+ const override = process.env[`CAPABILITY_REGISTRY_BASE_URL_${suffix}`];
106
+ if (override)
107
+ return trim(override);
108
+ if (environment) {
109
+ throw new InvocationError(`environment '${environment}' has no '${host}' host for product '${product}'. Set ` +
110
+ `CAPABILITY_REGISTRY_BASE_URL_${suffix}.`);
111
+ }
112
+ const declared = source?.hosts?.[host];
113
+ if (declared)
114
+ return trim(declared);
115
+ const known = Object.keys(source?.hosts ?? {});
116
+ throw new InvocationError(`that capability is served from the '${host}' host, which product '${product}' does ` +
117
+ `not declare. ` +
118
+ (known.length
119
+ ? `Its index defines: ${known.join(", ")}.`
120
+ : `Its index defines no named hosts.`) +
121
+ ` Set CAPABILITY_REGISTRY_BASE_URL_${suffix} to override.`);
122
+ }
123
+ export async function resolveBaseUrl(product, config, source, transport, host) {
90
124
  const key = product.toUpperCase();
91
125
  const environment = selectedEnvironment();
92
126
  const trim = (url) => url.replace(/\/$/, "");
127
+ // A capability that names a host is asking for one fixed origin, so none of the rungs
128
+ // below apply: discovery answers with the product's own host, and the declared
129
+ // `base_url` cannot serve this capability's paths at all.
130
+ if (host)
131
+ return resolveNamedHost(product, key, host, source, environment);
93
132
  const explicit = process.env[`CAPABILITY_REGISTRY_BASE_URL_${key}`];
94
133
  if (explicit)
95
134
  return trim(explicit);
@@ -14,7 +14,7 @@
14
14
  import { Credentials, Transport } from "./egress.js";
15
15
  import { Capability, ProductIndex } from "./types.js";
16
16
  /** What the resolver needs from a product's index to find its host. */
17
- export type HostSource = Pick<ProductIndex, "base_url" | "base_urls" | "probe_path" | "auth"> & {
17
+ export type HostSource = Pick<ProductIndex, "base_url" | "base_urls" | "hosts" | "probe_path" | "auth"> & {
18
18
  capabilities?: Capability[];
19
19
  };
20
20
  /** Exposed for tests; a long-lived process must not pin a stale region forever. */
@@ -135,7 +135,19 @@ async function readBody(response) {
135
135
  const size = response.headers.get("content-length");
136
136
  return `<non-text response: ${contentType}${size ? `, ${size} bytes` : ""}>`;
137
137
  }
138
- const raw = await response.text().catch(() => "");
138
+ // A FAILED READ IS NOT AN EMPTY BODY. `fetch` resolves as soon as the headers arrive, so
139
+ // the abort timer can fire while the body is still streaming. Swallowing that here
140
+ // returned the status line with no payload — a slow session create came back as a 200
141
+ // carrying null, which reads as a successful start that forgot to mention the session id.
142
+ // The device was really allocated, so the caller then had a session it could not name and
143
+ // could not release. Re-throwing lets the transport report the call as failed.
144
+ let raw;
145
+ try {
146
+ raw = await response.text();
147
+ }
148
+ catch (error) {
149
+ throw new Error(`the response body could not be read: ${error instanceof Error ? error.message : String(error)}`);
150
+ }
139
151
  if (!raw.trim())
140
152
  return null;
141
153
  if (contentType.includes("json")) {
@@ -169,8 +181,14 @@ export function fetchTransport(timeoutMs = 45_000) {
169
181
  method,
170
182
  headers,
171
183
  // Only send a body when there IS one: a literal `null` payload with a JSON
172
- // content-type is rejected by several endpoints.
173
- body: body === undefined ? undefined : JSON.stringify(body),
184
+ // content-type is rejected by several endpoints. A FormData goes through as it is —
185
+ // stringifying it yields "[object FormData]", which uploads nothing and reads as a
186
+ // product error rather than ours.
187
+ body: body === undefined
188
+ ? undefined
189
+ : body instanceof FormData
190
+ ? body
191
+ : JSON.stringify(body),
174
192
  // A redirect from an authenticated API is usually a login bounce, and following it
175
193
  // turns a clear 401/302 into a 200 carrying an HTML sign-in page — which the
176
194
  // resolver would then read as an empty result set rather than a failure.
@@ -10,6 +10,16 @@ export declare class IndexError extends Error {
10
10
  }
11
11
  /** Thrown to the caller as a tool error, so the wording is caller-facing. */
12
12
  export declare class InvocationError extends Error {
13
+ /**
14
+ * Set when the handle exists in the artifact but this surface withholds it.
15
+ *
16
+ * The MESSAGE deliberately does not say so — a caller is told the capability does not
17
+ * exist, because "withheld" invites a retry, a search for synonyms, or a question to the
18
+ * user about enabling it, none of which can succeed here. The flag keeps the distinction
19
+ * for telemetry, where knowing how often a withheld handle is reached for is how we learn
20
+ * whether withholding it was the right call.
21
+ */
22
+ withheld?: boolean;
13
23
  }
14
24
  /** The file inside a product subdirectory, for the earlier nested layout. */
15
25
  export declare const INDEX_FILE = "index.json";
@@ -32,8 +42,22 @@ export declare function endpointKey(method: string, path: string): string;
32
42
  * FAILS CLOSED: any truthy `disabled` hides it, not just `=== true`. The flag exists to
33
43
  * suppress something that cannot work, so an unexpected shape must hide it rather than be
34
44
  * ignored — the opposite default would turn a typo into a silently re-enabled capability.
45
+ *
46
+ * `local_only` withholds on a remote server only, for a capability that reads the caller's
47
+ * own machine: there, the path it would take resolves against the operator's disk instead.
48
+ * Read at call time rather than captured, because the remote server builds its config per
49
+ * session and a value captured at module load would outlive the deployment it described.
35
50
  */
36
51
  export declare function isDisabled(capability: Capability): boolean;
52
+ /**
53
+ * Is this capability published for reference only on this surface?
54
+ *
55
+ * `local_only` on a remote server. The capability is real and the caller may well be asking
56
+ * for exactly it, so hiding it leaves the agent concluding no such route exists. Publishing
57
+ * it without the means to call it, and with a note saying what to do instead, answers the
58
+ * question it was asked.
59
+ */
60
+ export declare function isReferenceOnly(capability: Capability): boolean;
37
61
  export interface LoadedProduct {
38
62
  name: string;
39
63
  product: ProductIndex;
@@ -66,16 +90,18 @@ export declare class CapabilityRegistry {
66
90
  private readonly withheld;
67
91
  constructor(index: RegistryIndex, provenance?: Record<string, Provenance>);
68
92
  /**
69
- * The `capability_disabled` message for a handle this build withholds, if it is one.
93
+ * Does this build withhold the handle?
70
94
  *
71
- * Says THAT it is disabled and nothing about why. The reason is documentation and lives
72
- * with the decision; repeating it here would put four copies of a paragraph in the
73
- * shipped artifact to serve a path the flag itself makes rare.
95
+ * WHAT THE CALLER IS TOLD IS THAT IT DOES NOT EXIST, which is why this returns a boolean
96
+ * rather than a message. Saying "withheld" describes the artifact rather than the
97
+ * surface, and every action it invites — retry, hunt for a synonym, ask the user to turn
98
+ * it on — fails here. A capability absent from search, describe and every listing should
99
+ * read the same way at invocation as it does everywhere else.
74
100
  *
75
- * Returns undefined for anything else, so the caller falls through to its own
76
- * not-found wording.
101
+ * The caller raises its own not-found error and marks it `withheld`, so the distinction
102
+ * survives in telemetry without reaching the agent.
77
103
  */
78
- private withheldMatch;
104
+ private isWithheld;
79
105
  /** How many capabilities each product withholds. Startup logging only. */
80
106
  disabledCounts(): Record<string, number>;
81
107
  static fromFile(file: string): CapabilityRegistry;