@hunt-labs/bytekit-mcp 0.2.0 → 0.2.1
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/CHANGELOG.md +29 -0
- package/README.md +10 -10
- package/dist/client.d.ts +45 -0
- package/dist/client.js +206 -21
- package/dist/docs-bundle/docs-bundle.json +133 -123
- package/dist/docs-bundle/helpers.d.ts +17 -1
- package/dist/docs-bundle/helpers.js +25 -0
- package/dist/lib/render-scrape.d.ts +27 -0
- package/dist/lib/render-scrape.js +83 -0
- package/dist/tools/get-result.js +15 -3
- package/dist/tools/list-docs.d.ts +6 -0
- package/dist/tools/list-docs.js +8 -4
- package/dist/tools/scrape-url.js +5 -69
- package/dist/tools/web-search.js +6 -2
- package/package.json +1 -1
- package/dist/docs-bundle/load-bundle.test.d.ts +0 -9
- package/dist/docs-bundle/load-bundle.test.js +0 -50
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
8
8
|
This file records only the delta between versions. For how to use the package
|
|
9
9
|
today, see [README.md](./README.md), which remains the authoritative usage guide.
|
|
10
10
|
|
|
11
|
+
## [0.2.1] - 2026-07-24
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- The spec'd flat `/v1/search` 502 error body (`{"error":"search_provider_error"}`)
|
|
16
|
+
now surfaces its code in the tool error text instead of collapsing to a generic
|
|
17
|
+
"ByteKit API error (HTTP 502)". Flat `{error: "<string>"}` bodies on any status
|
|
18
|
+
parse the same way; envelope-shaped bodies keep winning when both shapes are
|
|
19
|
+
present. (#2541)
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- `BytekitClient` accepts a `timeoutMs` constructor option — a per-request budget in
|
|
24
|
+
milliseconds, defaulting to `120000`. Set `0` to disable it entirely. Values that are
|
|
25
|
+
negative or non-finite normalize to disabled rather than throwing. Previously a hung
|
|
26
|
+
upstream hung a stdio MCP tool call forever. (#2568)
|
|
27
|
+
- The budget covers an **entire** `request()` call rather than each await separately:
|
|
28
|
+
the initial fetch, the 429 `Retry-After` sleep, the retry fetch, **and both** the
|
|
29
|
+
success and error body reads (`response.json()` in `request()` and in
|
|
30
|
+
`parseErrorEnvelope`). Two of those previously swallowed an abort outright — the
|
|
31
|
+
`Retry-After` sleep observed no signal, and a failed error-body read was downgraded to
|
|
32
|
+
"no envelope", surfacing a misleading status-line message instead of the timeout.
|
|
33
|
+
Exhausting the budget now produces a `BytekitApiError` with
|
|
34
|
+
`errorCode: 'timeout'`, distinct from `'network_error'`. (#2568)
|
|
35
|
+
- Note the semantics are **client-side only**: aborting does not cancel or refund
|
|
36
|
+
server-side work already in progress, so an account may still be billed for a result
|
|
37
|
+
the caller never reads. The `120000` default is deliberately well above the server-side
|
|
38
|
+
screenshot ceiling so it never truncates a legitimate billable operation. (#2568)
|
|
39
|
+
|
|
11
40
|
## [0.2.0] - 2026-07-21
|
|
12
41
|
|
|
13
42
|
### Removed (**BREAKING**)
|
package/README.md
CHANGED
|
@@ -91,16 +91,16 @@ The local server resolves the key in this order:
|
|
|
91
91
|
|
|
92
92
|
## Tool inventory
|
|
93
93
|
|
|
94
|
-
| Tool | What it does
|
|
95
|
-
| ---------------- |
|
|
96
|
-
| `scrape_url` | Fetch a URL and return HTML, clean markdown, links, or images.
|
|
97
|
-
| `
|
|
98
|
-
| `screenshot_url` | Capture a screenshot of a page (desktop/mobile, PNG/JPEG).
|
|
99
|
-
| `get_result` | Fetch a previously created screenshot by id.
|
|
100
|
-
| `get_account` | Return account details, plan, and current usage/quota.
|
|
101
|
-
| `list_docs` | List every page in the bundled ByteKit documentation.
|
|
102
|
-
| `search_docs` | Search the bundled documentation.
|
|
103
|
-
| `get_doc` | Fetch the full markdown of one documentation page.
|
|
94
|
+
| Tool | What it does |
|
|
95
|
+
| ---------------- | ---------------------------------------------------------------------- |
|
|
96
|
+
| `scrape_url` | Fetch a URL and return HTML, clean markdown, links, or images. |
|
|
97
|
+
| `web_search` | Run a web search and return ranked organic results. |
|
|
98
|
+
| `screenshot_url` | Capture a screenshot of a page (desktop/mobile, PNG/JPEG). |
|
|
99
|
+
| `get_result` | Fetch a previously created screenshot (`ss_`) or scrape (`sc_`) by id. |
|
|
100
|
+
| `get_account` | Return account details, plan, and current usage/quota. |
|
|
101
|
+
| `list_docs` | List every page in the bundled ByteKit documentation. |
|
|
102
|
+
| `search_docs` | Search the bundled documentation. |
|
|
103
|
+
| `get_doc` | Fetch the full markdown of one documentation page. |
|
|
104
104
|
|
|
105
105
|
The server also exposes **resources** (`bytekit://account`,
|
|
106
106
|
`bytekit://screenshot/{id}`) and **prompts** (`summarize_webpage`,
|
package/dist/client.d.ts
CHANGED
|
@@ -140,13 +140,47 @@ export declare class BytekitClient {
|
|
|
140
140
|
* call time so tests can stub `globalThis.fetch` without constructing a new client.
|
|
141
141
|
*/
|
|
142
142
|
private readonly fetchFn;
|
|
143
|
+
/**
|
|
144
|
+
* Normalized per-request budget in milliseconds; `0` means disabled. Resolved once
|
|
145
|
+
* here so every `request()` reads a value already known to be safe to hand to
|
|
146
|
+
* `AbortSignal.timeout`.
|
|
147
|
+
*/
|
|
148
|
+
private readonly timeoutMs;
|
|
143
149
|
constructor(options: {
|
|
144
150
|
apiKey: string;
|
|
145
151
|
baseUrl?: string;
|
|
146
152
|
verbose?: boolean;
|
|
153
|
+
/**
|
|
154
|
+
* Budget (ms) for an ENTIRE `request()` call -- the initial fetch, the 429
|
|
155
|
+
* `Retry-After` sleep, the retry fetch, and both the success and error body reads.
|
|
156
|
+
* Not per-await. Defaults to {@link DEFAULT_TIMEOUT_MS}; `0` disables it entirely.
|
|
157
|
+
* Values `<= 0` or non-finite normalize to disabled; oversized values are clamped
|
|
158
|
+
* to {@link MAX_TIMEOUT_MS}.
|
|
159
|
+
*/
|
|
160
|
+
timeoutMs?: number;
|
|
147
161
|
fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
148
162
|
});
|
|
163
|
+
/**
|
|
164
|
+
* The distinct error a budget exhaustion produces. `statusCode: 0` mirrors the
|
|
165
|
+
* existing `network_error` convention for failures that never produced an HTTP
|
|
166
|
+
* status, and `timeout` keeps the two classes distinguishable to callers.
|
|
167
|
+
*
|
|
168
|
+
* The message interpolates only the numeric budget -- no URL, header, body, or API
|
|
169
|
+
* key -- because every tool's catch block renders this text straight to the agent.
|
|
170
|
+
*/
|
|
171
|
+
private timeoutError;
|
|
149
172
|
scrape(params: ScrapeParams): Promise<ScrapeResult>;
|
|
173
|
+
/**
|
|
174
|
+
* Retrieve a previously created scrape by its `sc_` id
|
|
175
|
+
* (openapi.yaml `GET /v1/scrape/{id}`, operationId `getScrape`).
|
|
176
|
+
*
|
|
177
|
+
* Always answers HTTP 200 on an existing job — the `status` discriminator carries the
|
|
178
|
+
* state, so a still-running scrape arrives as a {@link ScrapeQueuedEnvelope} rather than
|
|
179
|
+
* a non-2xx. This is the redemption half of the async `scrape` handle: POST /v1/scrape
|
|
180
|
+
* may answer 202 with a queued envelope, and without this method that `sc_` id had no
|
|
181
|
+
* MCP-side retrieval path at all (issue #2538).
|
|
182
|
+
*/
|
|
183
|
+
getScrape(id: string): Promise<ScrapeResult>;
|
|
150
184
|
search(params: SearchParams): Promise<SearchResponse>;
|
|
151
185
|
screenshot(params: ScreenshotParams): Promise<ScreenshotResult>;
|
|
152
186
|
getScreenshot(id: string): Promise<ScreenshotResult>;
|
|
@@ -155,5 +189,16 @@ export declare class BytekitClient {
|
|
|
155
189
|
private request;
|
|
156
190
|
private post;
|
|
157
191
|
private get;
|
|
192
|
+
/**
|
|
193
|
+
* Map a non-2xx `response` to a {@link BytekitApiError}.
|
|
194
|
+
*
|
|
195
|
+
* `path` is the request path (the caller's second `request` argument). It is threaded in
|
|
196
|
+
* so status mappings can be endpoint-aware: the 402 message differs between the
|
|
197
|
+
* bandwidth-billed capture endpoints and the credit-billed `/v1/search` (issue #2571).
|
|
198
|
+
*
|
|
199
|
+
* `signal` is the per-request timeout signal (#2568); it is forwarded into
|
|
200
|
+
* `parseErrorEnvelope` so an aborted error-body read surfaces as a timeout rather than a
|
|
201
|
+
* misleading status-line message.
|
|
202
|
+
*/
|
|
158
203
|
private handleErrorResponse;
|
|
159
204
|
}
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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,6 +338,14 @@ 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
|
+
}
|
|
187
349
|
throw new BytekitApiError('Bandwidth quota exhausted. Check usage with get_account.', 402, 'quota_exceeded');
|
|
188
350
|
}
|
|
189
351
|
if (status === 422) {
|
|
@@ -191,6 +353,17 @@ export class BytekitClient {
|
|
|
191
353
|
const detail = envelope.details !== undefined ? `${base} (${formatErrorDetails(envelope.details)})` : base;
|
|
192
354
|
throw new BytekitApiError(detail, 422, envelope.code ?? 'validation_error');
|
|
193
355
|
}
|
|
356
|
+
// ── Flat vendor-masked shape: `{ "error": "<code>" }` (e.g. /v1/search 502,
|
|
357
|
+
// docs/api/openapi.yaml §/v1/search 502). The string IS the error code, so
|
|
358
|
+
// surface it — but keep the status line in the text, because a bare code is
|
|
359
|
+
// not a sentence and callers key off the HTTP status (issue #2541).
|
|
360
|
+
// Position is load-bearing: strictly BELOW the 401/402/422 mappings, whose
|
|
361
|
+
// actionable guidance must keep winning (#2478), and strictly ABOVE the
|
|
362
|
+
// generic envelope branch, which is unreachable for flat bodies anyway
|
|
363
|
+
// because the flat parse never populates both `code` and `message`. ──
|
|
364
|
+
if (envelope.shape === 'flat' && envelope.code !== undefined) {
|
|
365
|
+
throw new BytekitApiError(`ByteKit API error (HTTP ${status}): ${envelope.code}`, status, envelope.code);
|
|
366
|
+
}
|
|
194
367
|
// ── Generic envelope rendering: any other non-2xx that carried a parseable
|
|
195
368
|
// API envelope surfaces the server's own code + message so the agent can act
|
|
196
369
|
// on it (e.g. 503 `blocked`, 400 `invalid_url`, 404 `not_found`). ──
|
|
@@ -207,27 +380,38 @@ export class BytekitClient {
|
|
|
207
380
|
}
|
|
208
381
|
/**
|
|
209
382
|
* Read an error response body into a normalized `{ code, message, details }`
|
|
210
|
-
* envelope
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
*
|
|
214
|
-
* message
|
|
383
|
+
* envelope, tagged with the wire `shape` it came from.
|
|
384
|
+
*
|
|
385
|
+
* - `'envelope'` — the canonical unified shape `{ error: { code, message, details } }`.
|
|
386
|
+
* It always wins: it is matched first and returns before any flat parse runs.
|
|
387
|
+
* - `'flat'` — either a top-level `{ message: '<string>' }`, or the flat
|
|
388
|
+
* vendor-masked `{ error: '<string>' }` form. In the latter the string is the
|
|
389
|
+
* error **CODE**, not a message: `/v1/search` answers a provider outage with
|
|
390
|
+
* `502 {"error":"search_provider_error"}` (docs/api/openapi.yaml §/v1/search
|
|
391
|
+
* 502), a body deliberately outside the unified envelope. An empty string is
|
|
392
|
+
* treated as absent (issue #2541, E8).
|
|
393
|
+
* - `'none'` — non-JSON or non-object body; the caller falls back to a
|
|
394
|
+
* status-line message instead of crashing (issue #2478, E1).
|
|
215
395
|
*/
|
|
216
|
-
async function parseErrorEnvelope(response) {
|
|
396
|
+
async function parseErrorEnvelope(response, signal) {
|
|
217
397
|
let body;
|
|
218
398
|
try {
|
|
219
|
-
body = await response.json();
|
|
399
|
+
body = await withAbort(response.json(), signal);
|
|
220
400
|
}
|
|
221
401
|
catch {
|
|
222
|
-
|
|
402
|
+
// An aborted/timed-out body read is NOT a "no envelope" outcome. Surfacing it lets
|
|
403
|
+
// the caller report a timeout instead of a misleading status-line message (#2568).
|
|
404
|
+
if (signal?.aborted)
|
|
405
|
+
throw signal.reason;
|
|
406
|
+
return { shape: 'none' };
|
|
223
407
|
}
|
|
224
408
|
if (typeof body !== 'object' || body === null)
|
|
225
|
-
return {};
|
|
409
|
+
return { shape: 'none' };
|
|
226
410
|
const b = body;
|
|
227
411
|
// Canonical unified envelope: `error` is an object with code/message/details.
|
|
228
412
|
if (typeof b.error === 'object' && b.error !== null) {
|
|
229
413
|
const err = b.error;
|
|
230
|
-
const parsed = {};
|
|
414
|
+
const parsed = { shape: 'envelope' };
|
|
231
415
|
if (typeof err.code === 'string')
|
|
232
416
|
parsed.code = err.code;
|
|
233
417
|
if (typeof err.message === 'string')
|
|
@@ -236,12 +420,13 @@ async function parseErrorEnvelope(response) {
|
|
|
236
420
|
parsed.details = err.details;
|
|
237
421
|
return parsed;
|
|
238
422
|
}
|
|
239
|
-
//
|
|
240
|
-
|
|
423
|
+
// Flat shapes: a top-level `message` (a human sentence), or an `error` string
|
|
424
|
+
// (a machine-readable code). Ordering is preserved from #2478.
|
|
425
|
+
const parsed = { shape: 'flat' };
|
|
241
426
|
if (typeof b.message === 'string')
|
|
242
427
|
parsed.message = b.message;
|
|
243
|
-
else if (typeof b.error === 'string')
|
|
244
|
-
parsed.
|
|
428
|
+
else if (typeof b.error === 'string' && b.error.length > 0)
|
|
429
|
+
parsed.code = b.error;
|
|
245
430
|
return parsed;
|
|
246
431
|
}
|
|
247
432
|
/** Render an error `details` value as a compact human-readable string. */
|