@hunt-labs/bytekit-mcp 0.2.1 → 0.2.3

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
@@ -107,6 +107,27 @@ function abortReason(signal) {
107
107
  return reason instanceof Error ? reason : new Error(String(reason));
108
108
  }
109
109
  // ============================================================
110
+ // 429 species (issue #2681)
111
+ // ============================================================
112
+ /**
113
+ * The envelope `code` the gateway sends when the account's concurrency cap — not its
114
+ * request rate — is what rejected the call. HTTP 429 carries both conditions
115
+ * (docs/api/openapi.yaml: "Rate limit (`rate_limited`) or concurrency limit
116
+ * (`concurrency_limit`) exceeded"), and they need opposite advice.
117
+ */
118
+ const CONCURRENCY_LIMIT_CODE = 'concurrency_limit';
119
+ /**
120
+ * Advice for a `concurrency_limit` 429.
121
+ *
122
+ * It names the real wait scale deliberately. The spec describes the `Retry-After` on this
123
+ * variant as "a fixed small back-off", but the condition only clears when the account's
124
+ * in-flight jobs finish (or their slots expire, 5 min), so "try again in a moment" — the
125
+ * rate-limit copy every 429 used to get — is false here.
126
+ */
127
+ const CONCURRENCY_LIMIT_MESSAGE = 'Concurrency limit reached — every concurrent slot on your plan is already in use. ' +
128
+ 'Wait for your in-flight jobs to finish before retrying; this can take minutes, not ' +
129
+ 'seconds. Check your plan limit with get_account.';
130
+ // ============================================================
110
131
  // Client
111
132
  // ============================================================
112
133
  export class BytekitClient {
@@ -238,8 +259,19 @@ export class BytekitClient {
238
259
  const elapsed = Date.now() - start;
239
260
  process.stderr.write(`[mcp] ${method} ${path} -> ${response.status} (${elapsed}ms)\n`);
240
261
  }
241
- // 429: retry once with Retry-After
262
+ // 429: two conditions share this status, and only one of them is retryable here.
242
263
  if (response.status === 429) {
264
+ // Read the envelope code BEFORE deciding to retry: a `concurrency_limit` 429 does
265
+ // not clear on the header's back-off, so retrying it burns the one attempt and then
266
+ // reports the wrong thing twice over (issue #2681). Absent/unparseable code -> the
267
+ // pre-existing retry, unchanged.
268
+ const code = await this.read429Code(response, signal);
269
+ if (code === CONCURRENCY_LIMIT_CODE) {
270
+ if (this.verbose) {
271
+ process.stderr.write('[mcp] Concurrency limit reached, not retrying\n');
272
+ }
273
+ throw new BytekitApiError(CONCURRENCY_LIMIT_MESSAGE, 429, CONCURRENCY_LIMIT_CODE);
274
+ }
243
275
  const retryAfter = response.headers.get('Retry-After');
244
276
  const waitMs = parseRetryAfterMs(retryAfter);
245
277
  if (this.verbose) {
@@ -279,6 +311,13 @@ export class BytekitClient {
279
311
  throw new BytekitApiError('Could not reach ByteKit API. Check your connection and base URL.', 0, 'network_error');
280
312
  }
281
313
  if (retryResponse.status === 429) {
314
+ // The species can differ between the two attempts -- a rate-limit 429 whose retry,
315
+ // a second later, finds every slot held. This throw hardcoded `rate_limited`, so
316
+ // that case was mislabeled here too (issue #2681).
317
+ const retryCode = await this.read429Code(retryResponse, signal);
318
+ if (retryCode === CONCURRENCY_LIMIT_CODE) {
319
+ throw new BytekitApiError(CONCURRENCY_LIMIT_MESSAGE, 429, CONCURRENCY_LIMIT_CODE);
320
+ }
282
321
  throw new BytekitApiError('Rate limited. Try again in a moment.', 429, 'rate_limited');
283
322
  }
284
323
  response = retryResponse;
@@ -305,6 +344,31 @@ export class BytekitClient {
305
344
  async get(path) {
306
345
  return this.request('GET', path);
307
346
  }
347
+ /**
348
+ * Read the error `code` off a 429 body, tolerating anything that is not one.
349
+ *
350
+ * The 429 branch reached this ticket having never read the body at all, so the read is
351
+ * additive and must stay incapable of changing the outcome for a body it cannot parse
352
+ * (issue #2681, E3): an empty body, an edge proxy's HTML error page, or a response
353
+ * object with no usable `json()` all resolve to `undefined` here, and the caller then
354
+ * behaves exactly as it did before. Only an aborted read is escalated — as a timeout,
355
+ * matching {@link handleErrorResponse} — because a body read that ran out of budget is
356
+ * a timeout, not an absent code.
357
+ *
358
+ * Both wire shapes are covered by {@link parseErrorEnvelope}'s `code`: the unified
359
+ * `{ error: { code } }` envelope and the flat vendor-masked `{ error: '<code>' }`.
360
+ */
361
+ async read429Code(response, signal) {
362
+ try {
363
+ return (await parseErrorEnvelope(response, signal)).code;
364
+ }
365
+ catch {
366
+ // `parseErrorEnvelope` swallows every parse failure and rejects only on abort.
367
+ if (signal?.aborted)
368
+ throw this.timeoutError();
369
+ return undefined;
370
+ }
371
+ }
308
372
  /**
309
373
  * Map a non-2xx `response` to a {@link BytekitApiError}.
310
374
  *
@@ -346,12 +410,54 @@ export class BytekitClient {
346
410
  if (path.startsWith('/v1/search')) {
347
411
  throw new BytekitApiError('Search credit quota exhausted. Add credits or upgrade your plan to run more searches.', 402, 'quota_exceeded');
348
412
  }
413
+ // Screenshot quotas are credit/count-based, not bandwidth (issue #2591 item 3) --
414
+ // the bandwidth wording below is factually wrong for this endpoint. The
415
+ // get_account pointer is also dropped here: recommending an immediate follow-up
416
+ // call right after a quota failure is rate-limit-fragile on a 1-rps plan.
417
+ // Exact-match (not startsWith) so `/v1/screenshots/{id}` GET is unaffected.
418
+ if (path === '/v1/screenshots') {
419
+ throw new BytekitApiError('Screenshot quota exhausted. Add credits or upgrade your plan to capture more screenshots.', 402, 'quota_exceeded');
420
+ }
349
421
  throw new BytekitApiError('Bandwidth quota exhausted. Check usage with get_account.', 402, 'quota_exceeded');
350
422
  }
351
423
  if (status === 422) {
352
- const base = envelope.message ?? 'Validation error.';
424
+ // ── The RESOURCE-body 422 (issue #2679) ──
425
+ // POST /v1/screenshots answers a capture that FAILED inside its sync hold with 422
426
+ // whose body is the flat `ScreenshotResponse` resource — `serializeScreenshot`
427
+ // (gateway routes/screenshots.ts:175 + :194) — carrying `error_code`/`error_message`
428
+ // at the top level rather than the unified `Error` envelope. That is now the
429
+ // documented shape (docs/api/openapi.yaml, POST /v1/screenshots 422: `oneOf` Error |
430
+ // ScreenshotResponse); the gateway was deliberately left untouched, because its flat
431
+ // body is what carries the `ss_` handle and the rest of the resource, and reshaping
432
+ // it would move a wire contract the SDK, CLI and dashboard already read.
433
+ //
434
+ // Rendered as `code: message`, the same spelling the generic-envelope branch below
435
+ // uses, so one 422 does not read differently from every other server-coded error.
436
+ // The code alone when `error_message` is null: the code is the half the agent acts
437
+ // on, and a bare `null` would be worse than terse.
438
+ //
439
+ // Precedence: this wins over `envelope.message` because a resource body cannot
440
+ // populate it (its `message` key does not exist), so the two are never both present
441
+ // — a genuine validation 422 still carries the unified envelope and renders exactly
442
+ // as before.
443
+ const resource = envelope.resource;
444
+ const base = resource
445
+ ? resource.message !== undefined
446
+ ? `${resource.code}: ${resource.message}`
447
+ : resource.code
448
+ : (envelope.message ?? 'Validation error.');
353
449
  const detail = envelope.details !== undefined ? `${base} (${formatErrorDetails(envelope.details)})` : base;
354
- throw new BytekitApiError(detail, 422, envelope.code ?? 'validation_error');
450
+ // A sync-failed screenshot (POST /v1/screenshots -> 422) carries no `ss_` handle in
451
+ // the generic error body this branch parses (only message/details/code) -- the
452
+ // handle is only GUARANTEED to travel in the `X-Screenshot-ID` response header
453
+ // (openapi.yaml: "matches `id` in the JSON envelope"). Reading it here lets the
454
+ // agent redeem the failed screenshot later via get_result (issue #2591 item 2).
455
+ // Scoped to the exact create-endpoint path (not `startsWith`, which would also
456
+ // match `/v1/screenshots/{id}` GET) so no other 422 path is affected. Header
457
+ // absent -> degrade gracefully, omit the handle line entirely (E1).
458
+ const screenshotId = path === '/v1/screenshots' ? response.headers.get('X-Screenshot-ID') : null;
459
+ const message = screenshotId ? `${detail} (Screenshot ID: ${screenshotId})` : detail;
460
+ throw new BytekitApiError(message, 422, resource?.code ?? envelope.code ?? 'validation_error');
355
461
  }
356
462
  // ── Flat vendor-masked shape: `{ "error": "<code>" }` (e.g. /v1/search 502,
357
463
  // docs/api/openapi.yaml §/v1/search 502). The string IS the error code, so
@@ -427,6 +533,16 @@ async function parseErrorEnvelope(response, signal) {
427
533
  parsed.message = b.message;
428
534
  else if (typeof b.error === 'string' && b.error.length > 0)
429
535
  parsed.code = b.error;
536
+ // Resource-body failure fields (issue #2679), carried alongside — never merged into
537
+ // `code`/`message`, so only the 422 branch can act on them. `error_message` is a
538
+ // nullable DB column, so a null is treated as absent and the code stands alone.
539
+ const r = body;
540
+ if (typeof r.error_code === 'string' && r.error_code.length > 0) {
541
+ parsed.resource =
542
+ typeof r.error_message === 'string' && r.error_message.length > 0
543
+ ? { code: r.error_code, message: r.error_message }
544
+ : { code: r.error_code };
545
+ }
430
546
  return parsed;
431
547
  }
432
548
  /** Render an error `details` value as a compact human-readable string. */