@hunt-labs/bytekit-mcp 0.2.0 → 0.2.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.
package/dist/client.js CHANGED
@@ -53,6 +53,60 @@ export function parseRetryAfterMs(headerValue) {
53
53
  return DEFAULT_RETRY_AFTER_MS;
54
54
  }
55
55
  // ============================================================
56
+ // Per-request timeout budget (#2568)
57
+ // ============================================================
58
+ /** Default per-request budget (ms) covering fetch + retry sleep + retry fetch + body read. */
59
+ const DEFAULT_TIMEOUT_MS = 120_000;
60
+ /**
61
+ * Upper bound accepted by `AbortSignal.timeout` without `ERR_OUT_OF_RANGE`. A caller
62
+ * value above this is clamped rather than allowed to crash the constructor.
63
+ */
64
+ const MAX_TIMEOUT_MS = 2_147_483_647;
65
+ /**
66
+ * Settle with `promise`, or reject with the signal's abort reason the moment it aborts --
67
+ * whichever happens first.
68
+ *
69
+ * Adds an abort listener and NO timers, so it is invisible to vitest fake timers and
70
+ * cannot perturb the exact-equality `Retry-After` assertions in `client.test.ts`.
71
+ *
72
+ * The race (rather than relying on `init.signal` passthrough alone) is what makes a
73
+ * custom `fetch` that ignores the signal and never resolves still reject within budget --
74
+ * and it is the only way a `response.json()` on a hand-built `Response`, which is
75
+ * attached to no signal at all, can be interrupted.
76
+ */
77
+ function withAbort(promise, signal) {
78
+ if (signal === undefined)
79
+ return promise;
80
+ if (signal.aborted) {
81
+ // The abandoned promise may still reject later; absorb it so it cannot surface as
82
+ // an unhandled rejection.
83
+ promise.catch(() => { });
84
+ return Promise.reject(abortReason(signal));
85
+ }
86
+ return new Promise((resolve, reject) => {
87
+ const onAbort = () => {
88
+ reject(abortReason(signal));
89
+ };
90
+ signal.addEventListener('abort', onAbort, { once: true });
91
+ // Forwarding BOTH settlements up front means a late rejection from the raced-away
92
+ // promise is still handled after the abort already won -- otherwise a slow fetch
93
+ // that eventually fails would surface as an unhandled rejection. The `finally`
94
+ // drops the listener on every path, so a long-lived signal accrues none.
95
+ void promise.then(resolve, reject).finally(() => {
96
+ signal.removeEventListener('abort', onAbort);
97
+ });
98
+ });
99
+ }
100
+ /**
101
+ * Narrow `AbortSignal.reason` -- typed `any` by lib.dom -- to a real `Error`. A timeout
102
+ * signal's reason is a `DOMException` named `TimeoutError`, which already extends `Error`;
103
+ * the fallback only covers a signal carrying some other reason.
104
+ */
105
+ function abortReason(signal) {
106
+ const reason = signal.reason;
107
+ return reason instanceof Error ? reason : new Error(String(reason));
108
+ }
109
+ // ============================================================
56
110
  // Client
57
111
  // ============================================================
58
112
  export class BytekitClient {
@@ -66,19 +120,54 @@ export class BytekitClient {
66
120
  * call time so tests can stub `globalThis.fetch` without constructing a new client.
67
121
  */
68
122
  fetchFn;
123
+ /**
124
+ * Normalized per-request budget in milliseconds; `0` means disabled. Resolved once
125
+ * here so every `request()` reads a value already known to be safe to hand to
126
+ * `AbortSignal.timeout`.
127
+ */
128
+ timeoutMs;
69
129
  constructor(options) {
70
130
  this.apiKey = options.apiKey;
71
131
  this.baseUrl = (options.baseUrl ?? 'https://api.bytekit.com').replace(/\/+$/, '');
72
132
  this.verbose = options.verbose === true;
133
+ const rawTimeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
134
+ this.timeoutMs =
135
+ Number.isFinite(rawTimeoutMs) && rawTimeoutMs > 0
136
+ ? Math.min(Math.floor(rawTimeoutMs), MAX_TIMEOUT_MS)
137
+ : 0;
73
138
  // Store only when explicitly provided; otherwise resolve globalThis.fetch at
74
139
  // call time so test stubs on globalThis.fetch take effect without rebuilding
75
140
  // the client.
76
141
  this.fetchFn = options.fetch;
77
142
  }
143
+ /**
144
+ * The distinct error a budget exhaustion produces. `statusCode: 0` mirrors the
145
+ * existing `network_error` convention for failures that never produced an HTTP
146
+ * status, and `timeout` keeps the two classes distinguishable to callers.
147
+ *
148
+ * The message interpolates only the numeric budget -- no URL, header, body, or API
149
+ * key -- because every tool's catch block renders this text straight to the agent.
150
+ */
151
+ timeoutError() {
152
+ return new BytekitApiError(`ByteKit API request timed out after ${this.timeoutMs}ms.`, 0, 'timeout');
153
+ }
78
154
  // ── Public API ──
79
155
  async scrape(params) {
80
156
  return this.post('/v1/scrape', params);
81
157
  }
158
+ /**
159
+ * Retrieve a previously created scrape by its `sc_` id
160
+ * (openapi.yaml `GET /v1/scrape/{id}`, operationId `getScrape`).
161
+ *
162
+ * Always answers HTTP 200 on an existing job — the `status` discriminator carries the
163
+ * state, so a still-running scrape arrives as a {@link ScrapeQueuedEnvelope} rather than
164
+ * a non-2xx. This is the redemption half of the async `scrape` handle: POST /v1/scrape
165
+ * may answer 202 with a queued envelope, and without this method that `sc_` id had no
166
+ * MCP-side retrieval path at all (issue #2538).
167
+ */
168
+ async getScrape(id) {
169
+ return this.get(`/v1/scrape/${encodeURIComponent(id)}`);
170
+ }
82
171
  async search(params) {
83
172
  // Build the request body with only the fields the caller supplied, so the
84
173
  // wire payload stays minimal and matches the API's optional-field contract.
@@ -121,15 +210,28 @@ export class BytekitClient {
121
210
  }
122
211
  const start = Date.now();
123
212
  const doFetch = this.fetchFn ?? fetch;
213
+ // ONE signal for the whole call, created before any await, so the budget covers the
214
+ // fetch + retry sleep + retry fetch + body read taken together rather than resetting
215
+ // per await. `AbortSignal.timeout` is deliberate over a manual controller plus a
216
+ // `setTimeout`: the latter leaves a pending fake-timer-visible timer that breaks the
217
+ // exact-equality `Retry-After` assertions in client.test.ts (#2568).
218
+ const signal = this.timeoutMs > 0 ? AbortSignal.timeout(this.timeoutMs) : undefined;
124
219
  let response;
125
220
  try {
126
221
  const init = { method, headers };
127
222
  if (body !== undefined) {
128
223
  init.body = JSON.stringify(body);
129
224
  }
130
- response = await doFetch(url, init);
225
+ // Assigned conditionally: `exactOptionalPropertyTypes` forbids writing `undefined`
226
+ // into an optional property.
227
+ if (signal !== undefined) {
228
+ init.signal = signal;
229
+ }
230
+ response = await withAbort(doFetch(url, init), signal);
131
231
  }
132
232
  catch {
233
+ if (signal?.aborted)
234
+ throw this.timeoutError();
133
235
  throw new BytekitApiError('Could not reach ByteKit API. Check your connection and base URL.', 0, 'network_error');
134
236
  }
135
237
  if (this.verbose) {
@@ -143,16 +245,37 @@ export class BytekitClient {
143
245
  if (this.verbose) {
144
246
  process.stderr.write(`[mcp] Rate limited, retrying after ${waitMs}ms\n`);
145
247
  }
146
- await new Promise((resolve) => setTimeout(resolve, waitMs));
248
+ try {
249
+ await withAbort(new Promise((resolve) => {
250
+ // Exactly one timer, with the delay `parseRetryAfterMs` computed and nothing
251
+ // else -- the fake-timer HTTP-date test asserts the clock advances by exactly
252
+ // that amount, so a second or rescaled timer here would break it.
253
+ const timer = setTimeout(resolve, waitMs);
254
+ // Release the pending sleep as soon as the budget expires; a raced-away timer
255
+ // would otherwise hold the event loop open for the whole `Retry-After`.
256
+ signal?.addEventListener('abort', () => clearTimeout(timer), { once: true });
257
+ }), signal);
258
+ }
259
+ catch (err) {
260
+ // The sleep promise itself never rejects, so only the abort race can land here.
261
+ if (signal?.aborted)
262
+ throw this.timeoutError();
263
+ throw err;
264
+ }
147
265
  let retryResponse;
148
266
  try {
149
267
  const retryInit = { method, headers };
150
268
  if (body !== undefined) {
151
269
  retryInit.body = JSON.stringify(body);
152
270
  }
153
- retryResponse = await doFetch(url, retryInit);
271
+ if (signal !== undefined) {
272
+ retryInit.signal = signal;
273
+ }
274
+ retryResponse = await withAbort(doFetch(url, retryInit), signal);
154
275
  }
155
276
  catch {
277
+ if (signal?.aborted)
278
+ throw this.timeoutError();
156
279
  throw new BytekitApiError('Could not reach ByteKit API. Check your connection and base URL.', 0, 'network_error');
157
280
  }
158
281
  if (retryResponse.status === 429) {
@@ -161,9 +284,20 @@ export class BytekitClient {
161
284
  response = retryResponse;
162
285
  }
163
286
  if (!response.ok) {
164
- await this.handleErrorResponse(response);
287
+ await this.handleErrorResponse(response, path, signal);
288
+ }
289
+ try {
290
+ return (await withAbort(response.json(), signal));
291
+ }
292
+ catch (err) {
293
+ if (signal?.aborted)
294
+ throw this.timeoutError();
295
+ // Deliberate (#2568, E4 option b): a malformed 2xx body re-throws its original
296
+ // SyntaxError unchanged. This ticket's surface is the timeout it is named for, and
297
+ // inventing a new error code here would change a pre-existing, user-visible failure
298
+ // mode that nothing in the ticket asks to change.
299
+ throw err;
165
300
  }
166
- return (await response.json());
167
301
  }
168
302
  async post(path, body) {
169
303
  return this.request('POST', path, body);
@@ -171,12 +305,32 @@ export class BytekitClient {
171
305
  async get(path) {
172
306
  return this.request('GET', path);
173
307
  }
174
- async handleErrorResponse(response) {
308
+ /**
309
+ * Map a non-2xx `response` to a {@link BytekitApiError}.
310
+ *
311
+ * `path` is the request path (the caller's second `request` argument). It is threaded in
312
+ * so status mappings can be endpoint-aware: the 402 message differs between the
313
+ * bandwidth-billed capture endpoints and the credit-billed `/v1/search` (issue #2571).
314
+ *
315
+ * `signal` is the per-request timeout signal (#2568); it is forwarded into
316
+ * `parseErrorEnvelope` so an aborted error-body read surfaces as a timeout rather than a
317
+ * misleading status-line message.
318
+ */
319
+ async handleErrorResponse(response, path, signal) {
175
320
  const status = response.status;
176
321
  // Parse the body once, tolerating a non-JSON payload (e.g. a load-balancer
177
322
  // HTML error page) without crashing. Prefer the canonical unified envelope
178
323
  // ({ error: { code, message, details } }, gateway issue #699).
179
- const envelope = await parseErrorEnvelope(response);
324
+ let envelope;
325
+ try {
326
+ envelope = await parseErrorEnvelope(response, signal);
327
+ }
328
+ catch {
329
+ // Only an abort can reject here -- a genuinely non-JSON body still resolves to
330
+ // { shape: 'none' }. Without this, an error-body read that ran out of budget fell
331
+ // through to a misleading status-line message instead of a timeout (#2568 E3).
332
+ throw this.timeoutError();
333
+ }
180
334
  // ── Specific status mappings win over the generic envelope (precedence) ──
181
335
  // These carry deliberate, actionable guidance and must beat the raw
182
336
  // server-supplied code/message even when an envelope is present (issue #2478).
@@ -184,12 +338,49 @@ export class BytekitClient {
184
338
  throw new BytekitApiError('Invalid API key. Check your BYTEKIT_API_KEY.', 401, 'invalid_api_key');
185
339
  }
186
340
  if (status === 402) {
341
+ // `/v1/search` is billed per credit (1 credit per upstream page), not on bandwidth,
342
+ // so the bandwidth wording is factually wrong for a search 402 — and `get_account`'s
343
+ // usage view does not answer a search-credit question, so that pointer is dropped
344
+ // here (issue #2571). Literal path-prefix match: no other client path starts with
345
+ // `/v1/search`. Every other 402 keeps the original bandwidth message verbatim.
346
+ if (path.startsWith('/v1/search')) {
347
+ throw new BytekitApiError('Search credit quota exhausted. Add credits or upgrade your plan to run more searches.', 402, 'quota_exceeded');
348
+ }
349
+ // Screenshot quotas are credit/count-based, not bandwidth (issue #2591 item 3) --
350
+ // the bandwidth wording below is factually wrong for this endpoint. The
351
+ // get_account pointer is also dropped here: recommending an immediate follow-up
352
+ // call right after a quota failure is rate-limit-fragile on a 1-rps plan.
353
+ // Exact-match (not startsWith) so `/v1/screenshots/{id}` GET is unaffected.
354
+ if (path === '/v1/screenshots') {
355
+ throw new BytekitApiError('Screenshot quota exhausted. Add credits or upgrade your plan to capture more screenshots.', 402, 'quota_exceeded');
356
+ }
187
357
  throw new BytekitApiError('Bandwidth quota exhausted. Check usage with get_account.', 402, 'quota_exceeded');
188
358
  }
189
359
  if (status === 422) {
190
360
  const base = envelope.message ?? 'Validation error.';
191
361
  const detail = envelope.details !== undefined ? `${base} (${formatErrorDetails(envelope.details)})` : base;
192
- throw new BytekitApiError(detail, 422, envelope.code ?? 'validation_error');
362
+ // A sync-failed screenshot (POST /v1/screenshots -> 422) carries no `ss_` handle in
363
+ // the generic error body this branch parses (only message/details/code) -- the
364
+ // handle is only GUARANTEED to travel in the `X-Screenshot-ID` response header
365
+ // (openapi.yaml: "matches `id` in the JSON envelope"). Reading it here lets the
366
+ // agent redeem the failed screenshot later via get_result (issue #2591 item 2).
367
+ // Scoped to the exact create-endpoint path (not `startsWith`, which would also
368
+ // match `/v1/screenshots/{id}` GET) so no other 422 path is affected. Header
369
+ // absent -> degrade gracefully, omit the handle line entirely (E1).
370
+ const screenshotId = path === '/v1/screenshots' ? response.headers.get('X-Screenshot-ID') : null;
371
+ const message = screenshotId ? `${detail} (Screenshot ID: ${screenshotId})` : detail;
372
+ throw new BytekitApiError(message, 422, envelope.code ?? 'validation_error');
373
+ }
374
+ // ── Flat vendor-masked shape: `{ "error": "<code>" }` (e.g. /v1/search 502,
375
+ // docs/api/openapi.yaml §/v1/search 502). The string IS the error code, so
376
+ // surface it — but keep the status line in the text, because a bare code is
377
+ // not a sentence and callers key off the HTTP status (issue #2541).
378
+ // Position is load-bearing: strictly BELOW the 401/402/422 mappings, whose
379
+ // actionable guidance must keep winning (#2478), and strictly ABOVE the
380
+ // generic envelope branch, which is unreachable for flat bodies anyway
381
+ // because the flat parse never populates both `code` and `message`. ──
382
+ if (envelope.shape === 'flat' && envelope.code !== undefined) {
383
+ throw new BytekitApiError(`ByteKit API error (HTTP ${status}): ${envelope.code}`, status, envelope.code);
193
384
  }
194
385
  // ── Generic envelope rendering: any other non-2xx that carried a parseable
195
386
  // API envelope surfaces the server's own code + message so the agent can act
@@ -207,27 +398,38 @@ export class BytekitClient {
207
398
  }
208
399
  /**
209
400
  * Read an error response body into a normalized `{ code, message, details }`
210
- * envelope. Recognizes the canonical unified shape
211
- * (`{ error: { code, message, details } }`) and legacy flat shapes
212
- * (`{ message }`, `{ error: '<string>' }`). Returns an empty object for a
213
- * non-JSON or non-object body — the caller then falls back to a status-line
214
- * message instead of crashing (issue #2478, E1).
401
+ * envelope, tagged with the wire `shape` it came from.
402
+ *
403
+ * - `'envelope'` — the canonical unified shape `{ error: { code, message, details } }`.
404
+ * It always wins: it is matched first and returns before any flat parse runs.
405
+ * - `'flat'` — either a top-level `{ message: '<string>' }`, or the flat
406
+ * vendor-masked `{ error: '<string>' }` form. In the latter the string is the
407
+ * error **CODE**, not a message: `/v1/search` answers a provider outage with
408
+ * `502 {"error":"search_provider_error"}` (docs/api/openapi.yaml §/v1/search
409
+ * 502), a body deliberately outside the unified envelope. An empty string is
410
+ * treated as absent (issue #2541, E8).
411
+ * - `'none'` — non-JSON or non-object body; the caller falls back to a
412
+ * status-line message instead of crashing (issue #2478, E1).
215
413
  */
216
- async function parseErrorEnvelope(response) {
414
+ async function parseErrorEnvelope(response, signal) {
217
415
  let body;
218
416
  try {
219
- body = await response.json();
417
+ body = await withAbort(response.json(), signal);
220
418
  }
221
419
  catch {
222
- return {};
420
+ // An aborted/timed-out body read is NOT a "no envelope" outcome. Surfacing it lets
421
+ // the caller report a timeout instead of a misleading status-line message (#2568).
422
+ if (signal?.aborted)
423
+ throw signal.reason;
424
+ return { shape: 'none' };
223
425
  }
224
426
  if (typeof body !== 'object' || body === null)
225
- return {};
427
+ return { shape: 'none' };
226
428
  const b = body;
227
429
  // Canonical unified envelope: `error` is an object with code/message/details.
228
430
  if (typeof b.error === 'object' && b.error !== null) {
229
431
  const err = b.error;
230
- const parsed = {};
432
+ const parsed = { shape: 'envelope' };
231
433
  if (typeof err.code === 'string')
232
434
  parsed.code = err.code;
233
435
  if (typeof err.message === 'string')
@@ -236,12 +438,13 @@ async function parseErrorEnvelope(response) {
236
438
  parsed.details = err.details;
237
439
  return parsed;
238
440
  }
239
- // Legacy flat shapes: a top-level `message`, or an `error` string.
240
- const parsed = {};
441
+ // Flat shapes: a top-level `message` (a human sentence), or an `error` string
442
+ // (a machine-readable code). Ordering is preserved from #2478.
443
+ const parsed = { shape: 'flat' };
241
444
  if (typeof b.message === 'string')
242
445
  parsed.message = b.message;
243
- else if (typeof b.error === 'string')
244
- parsed.message = b.error;
446
+ else if (typeof b.error === 'string' && b.error.length > 0)
447
+ parsed.code = b.error;
245
448
  return parsed;
246
449
  }
247
450
  /** Render an error `details` value as a compact human-readable string. */