@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.
@@ -61,6 +61,22 @@ export declare function slugToUrlPath(slug: string[]): string;
61
61
  * (the docs index, which keeps its HTML URL and has an empty slug), are ignored.
62
62
  */
63
63
  export declare function parseLlmsTxt(text: string): Array<string[]>;
64
+ /**
65
+ * Returns a new bundle object whose keys are sorted lexicographically.
66
+ *
67
+ * Page-slug discovery order comes from `/docs/llms.txt`, which reflects
68
+ * fumadocs-mdx's file-discovery order in the generated `.source/index.ts` manifest.
69
+ * That order is NOT guaranteed stable across independent `next build` invocations —
70
+ * two regenerations from byte-identical docs content can (and empirically do, issue
71
+ * #2590 DoD-2) produce a differently-ORDERED but content-identical bundle, because
72
+ * nothing in the assembly step normalizes insertion order before `JSON.stringify`
73
+ * freezes it into the artifact.
74
+ *
75
+ * Sorting is a pure function of the key SET, independent of discovery order, so this
76
+ * fixes the actual root cause (the generator's un-normalized assembly step) rather than
77
+ * papering over one observed reordering.
78
+ */
79
+ export declare function sortBundleKeys<T>(bundle: Record<string, T>): Record<string, T>;
64
80
  /**
65
81
  * Extracts the page title from the rendered markdown.
66
82
  *
@@ -113,6 +113,28 @@ export function parseLlmsTxt(text) {
113
113
  }
114
114
  return slugs;
115
115
  }
116
+ /**
117
+ * Returns a new bundle object whose keys are sorted lexicographically.
118
+ *
119
+ * Page-slug discovery order comes from `/docs/llms.txt`, which reflects
120
+ * fumadocs-mdx's file-discovery order in the generated `.source/index.ts` manifest.
121
+ * That order is NOT guaranteed stable across independent `next build` invocations —
122
+ * two regenerations from byte-identical docs content can (and empirically do, issue
123
+ * #2590 DoD-2) produce a differently-ORDERED but content-identical bundle, because
124
+ * nothing in the assembly step normalizes insertion order before `JSON.stringify`
125
+ * freezes it into the artifact.
126
+ *
127
+ * Sorting is a pure function of the key SET, independent of discovery order, so this
128
+ * fixes the actual root cause (the generator's un-normalized assembly step) rather than
129
+ * papering over one observed reordering.
130
+ */
131
+ export function sortBundleKeys(bundle) {
132
+ const sorted = {};
133
+ for (const key of Object.keys(bundle).sort()) {
134
+ sorted[key] = bundle[key];
135
+ }
136
+ return sorted;
137
+ }
116
138
  /**
117
139
  * Extracts the page title from the rendered markdown.
118
140
  *
@@ -14,9 +14,18 @@ import type { ScrapeResult } from '../client.js';
14
14
  * handle, and also what GET returns while the job is pending/processing (gateway
15
15
  * routes/scrape.ts `handleGetScrapeById`). Non-error: the agent should poll, not fail.
16
16
  * - failed: `{ status:'failed', id, error:{ code, message, ... } }` — flagged as a tool
17
- * error, rendering the public error code + message only.
18
- * - success: full envelope; primary content prefers markdown → html → raw_html, with
19
- * optional links/images blocks appended.
17
+ * error, rendering the public error code + message (plus any `warnings` the envelope
18
+ * carries, issue #2679).
19
+ * - success: full envelope; every textual format present (markdown, html, raw_html) is
20
+ * rendered, in that fixed canonical order — the first present format is the
21
+ * unlabeled primary, each remaining one follows under its own
22
+ * `--- format: <name> ---` delimiter — plus an optional `warnings` block (issue #2679)
23
+ * and optional links/images blocks, all inside
24
+ * ONE truncation budget (issue #2589; previously only one format was shown, and
25
+ * links/images were appended AFTER truncation). The links/images block is passed to
26
+ * the truncator as a RESERVED trailing block (capped at half the budget) so it
27
+ * always gets its own slice of the budget instead of being the first thing
28
+ * discarded when the textual formats alone already fill it (cr-1/cr-4 hardening).
20
29
  *
21
30
  * Every optional line is omitted when absent, so no `undefined`/`null` literal is ever
22
31
  * emitted (issue #2419).
@@ -1,14 +1,50 @@
1
1
  import { truncateContent } from './truncate.js';
2
+ // One rendered line PER ENTRY, deliberately not joined here (issue #2687 item 6): the
3
+ // truncator needs the entry boundaries to cut between whole URLs instead of slicing the
4
+ // joined block to a raw byte count, which severed the tail entry mid-URL.
2
5
  function renderLinks(links) {
3
- return links
4
- .map((link) => typeof link === 'string' ? link : `${link.url}${link.text ? ` — ${link.text}` : ''}`)
5
- .join('\n');
6
+ return links.map((link) => typeof link === 'string' ? link : `${link.url}${link.text ? ` — ${link.text}` : ''}`);
6
7
  }
7
8
  function renderImages(images) {
8
- return images
9
- .map((image) => typeof image === 'string' ? image : `${image.url}${image.alt ? ` — ${image.alt}` : ''}`)
10
- .join('\n');
9
+ return images.map((image) => typeof image === 'string' ? image : `${image.url}${image.alt ? ` — ${image.alt}` : ''}`);
10
+ }
11
+ /**
12
+ * One line per warning: `<code>: <message>` plus ` (<element>)` when the warning names a
13
+ * DOM element or format (issue #2679).
14
+ *
15
+ * The `code` is deliberately part of the LINE, not just of the section header: it is the
16
+ * machine-readable half of the signal, and it is what tells `artifact_unavailable` (a
17
+ * billed format is missing) apart from `lossy_table` (cosmetic). `element` is `null` for
18
+ * every whole-extraction warning (`low_quality_extraction`, `llm_clean_*`, …) and must
19
+ * then render nothing at all rather than a literal `(null)`.
20
+ *
21
+ * The input is the real `ScrapeWarning` union from scrape-contract.generated.ts — all 12
22
+ * codes — so no hand-written subset can drift from the contract.
23
+ */
24
+ function renderWarnings(warnings) {
25
+ return warnings.map((w) => `${w.code}: ${w.message}${w.element ? ` (${w.element})` : ''}`);
26
+ }
27
+ /**
28
+ * `warnings` when the envelope carries a non-empty array, `[]` otherwise (issue #2679 E3).
29
+ *
30
+ * The parameter is structurally typed rather than taking a `ScrapeEnvelope`, because the
31
+ * field is strict-optional on the success envelope and is not declared at all on the
32
+ * failed one — this keeps ONE presence guard for both branches, so an absent field can
33
+ * never reach the render as `undefined`. `status` is in the signature only to keep the
34
+ * parameter off TypeScript's weak-type check (an all-optional parameter type rejects the
35
+ * failed envelope outright with TS2559); every envelope shape carries it.
36
+ */
37
+ function presentWarnings(envelope) {
38
+ return Array.isArray(envelope.warnings) ? envelope.warnings : [];
11
39
  }
40
+ // Textual formats in canonical render order. The first one present in the envelope is
41
+ // the unlabeled primary (today's position); every other one present follows under its
42
+ // own delimiter. Module-local: nothing outside this file needs it (issue #2589).
43
+ const TEXTUAL_FORMATS = ['markdown', 'html', 'raw_html'];
44
+ // Full delimiter templates for every possible secondary textual format, used only to
45
+ // detect and strip a DANGLING partial delimiter left by a byte-boundary truncation
46
+ // cut (issue #2589 cr-8) — never to detect a complete, legitimately-rendered one.
47
+ const FORMAT_DELIMITER_MARKERS = TEXTUAL_FORMATS.map((f) => `\n\n--- format: ${f} ---\n\n`);
12
48
  /**
13
49
  * Renders a scrape envelope (from POST /v1/scrape or GET /v1/scrape/{id}) into
14
50
  * human-readable lines for MCP tool output.
@@ -24,9 +60,18 @@ function renderImages(images) {
24
60
  * handle, and also what GET returns while the job is pending/processing (gateway
25
61
  * routes/scrape.ts `handleGetScrapeById`). Non-error: the agent should poll, not fail.
26
62
  * - failed: `{ status:'failed', id, error:{ code, message, ... } }` — flagged as a tool
27
- * error, rendering the public error code + message only.
28
- * - success: full envelope; primary content prefers markdown → html → raw_html, with
29
- * optional links/images blocks appended.
63
+ * error, rendering the public error code + message (plus any `warnings` the envelope
64
+ * carries, issue #2679).
65
+ * - success: full envelope; every textual format present (markdown, html, raw_html) is
66
+ * rendered, in that fixed canonical order — the first present format is the
67
+ * unlabeled primary, each remaining one follows under its own
68
+ * `--- format: <name> ---` delimiter — plus an optional `warnings` block (issue #2679)
69
+ * and optional links/images blocks, all inside
70
+ * ONE truncation budget (issue #2589; previously only one format was shown, and
71
+ * links/images were appended AFTER truncation). The links/images block is passed to
72
+ * the truncator as a RESERVED trailing block (capped at half the budget) so it
73
+ * always gets its own slice of the budget instead of being the first thing
74
+ * discarded when the textual formats alone already fill it (cr-1/cr-4 hardening).
30
75
  *
31
76
  * Every optional line is omitted when absent, so no `undefined`/`null` literal is ever
32
77
  * emitted (issue #2419).
@@ -39,45 +84,117 @@ export function renderScrapeResult(result) {
39
84
  'Status: queued',
40
85
  `URL: ${result.url}`,
41
86
  `Status URL: ${result.status_url}`,
87
+ // `events` is spec-required on the queued envelope (ScrapeQueuedEnvelope.events)
88
+ // and was dropped entirely (issue #2687 item 5) — an agent that registered a
89
+ // webhook had no way to see which events the job is actually subscribed to. An
90
+ // empty array renders `none`, because "subscribed to nothing" is a different
91
+ // answer from "not rendered".
92
+ `Events: ${Array.isArray(result.events) && result.events.length > 0 ? result.events.join(', ') : 'none'}`,
93
+ // Mirrors render-screenshot.ts's pending-branch sentence verbatim (issue #2687
94
+ // item 10): 0.2.2 gave a still-pending SCREENSHOT this guidance (#2591 item 4)
95
+ // but left the queued SCRAPE render without it, so an agent holding an `sc_`
96
+ // handle was told the job was queued and left to invent the next step.
97
+ 'Use get_result with this ID to check when it completes.',
42
98
  ].join('\n'),
43
99
  isError: false,
44
100
  };
45
101
  }
46
102
  if (result.status === 'failed') {
103
+ // Warnings on the terminal-failure envelope too (issue #2679). `ScrapeErrorEnvelope`
104
+ // does not DECLARE the field today, and `buildErrorEnvelope` never sets it — this is
105
+ // the renderer's half of the invariant "no warning the API emits is invisible through
106
+ // MCP": whichever terminal envelope a warning arrives on, the renderer is not the
107
+ // reason it is lost. No truncation budget applies here — the failed render has no
108
+ // payload to compete with.
109
+ const failedWarnings = renderWarnings(presentWarnings(result));
110
+ // `id` is nullable (issue #2591 item 7; openapi.yaml ScrapeErrorEnvelope.id:
111
+ // `type: ["string", "null"]`) — null when the job was never queued (e.g. a
112
+ // validation failure before a row existed). Render an em-dash rather than the
113
+ // literal "ID: null".
47
114
  return {
48
115
  text: [
49
- `ID: ${result.id}`,
116
+ `ID: ${result.id ?? '—'}`,
50
117
  'Status: failed',
51
118
  `Error: ${result.error.code}`,
52
119
  result.error.message,
120
+ // Same `Warnings (N):` header the success render uses, so one output contract
121
+ // covers both terminal shapes. Absent/empty appends nothing at all (E3).
122
+ ...(failedWarnings.length > 0
123
+ ? ['', `Warnings (${failedWarnings.length}):`, ...failedWarnings]
124
+ : []),
53
125
  ].join('\n'),
54
126
  isError: true,
55
127
  };
56
128
  }
57
- // Primary content for display: prefer markdown → html → rawHtml
58
- const content = result.formats.markdown ?? result.formats.html ?? result.formats.raw_html ?? '';
59
- const { text, truncated } = truncateContent(content);
129
+ // Every textual format present, in canonical order. Presence is `typeof === 'string'`
130
+ // (not truthiness) so an empty-string format still counts as present — this
131
+ // reproduces the old `??` chain's behavior for the primary slot exactly (`'' ?? …`
132
+ // is not nullish either) while also surfacing a present-but-empty SECONDARY format
133
+ // to the caller instead of silently dropping it.
134
+ const present = TEXTUAL_FORMATS.filter((f) => typeof result.formats[f] === 'string');
135
+ let payload = present.length > 0 ? result.formats[present[0]] : '';
136
+ for (const f of present.slice(1)) {
137
+ payload += `\n\n--- format: ${f} ---\n\n${result.formats[f]}`;
138
+ }
139
+ // Links/images are built as a separate trailing block (not folded into `payload`
140
+ // directly) so they can be passed to truncateContent as a RESERVED block rather
141
+ // than ordinary tail content — see cr-1/cr-4 in the function doc above.
142
+ //
143
+ // Presence of the key — not a non-empty length — is what gates the section (issue
144
+ // #2687 item 1). The API echoes every REQUESTED format back as an array, empty or
145
+ // not, and omits the key entirely for a format that was not requested. So an empty
146
+ // array means "you asked, and the page had none" and gets a `Links (0):` header,
147
+ // while an absent key means "you did not ask" and renders nothing at all (E4) —
148
+ // without this distinction the agent cannot tell an empty page from an unrequested
149
+ // format, and a zero-line on every scrape would be pure noise.
150
+ const trailingSections = [];
151
+ // Warnings go FIRST among the reserved sections (issue #2679). `renderReserveSections`
152
+ // fills sequentially, so section order IS budget priority: a failure signal —
153
+ // `artifact_unavailable` says a format the caller was BILLED for is missing — must not
154
+ // be the thing an oversized links list crowds out. Riding the reserve is also what
155
+ // keeps the block inside #2687's truncation budget accounting (E2) rather than
156
+ // appended outside it.
157
+ //
158
+ // Gated on a NON-EMPTY array, unlike the links/images sections just below. Their
159
+ // presence-of-key rule (#2687 item 1) exists because the API echoes every REQUESTED
160
+ // format back, so `[]` means "you asked, and there were none". Nobody requests
161
+ // warnings, so `warnings: []` carries no such answer and a `Warnings (0):` header would
162
+ // be pure noise on every clean scrape — both `[]` and absent render nothing.
163
+ const warnings = presentWarnings(result);
164
+ if (warnings.length > 0) {
165
+ trailingSections.push({ label: 'Warnings', entries: renderWarnings(warnings) });
166
+ }
167
+ if (Array.isArray(result.formats.links)) {
168
+ trailingSections.push({ label: 'Links', entries: renderLinks(result.formats.links) });
169
+ }
170
+ if (Array.isArray(result.formats.images)) {
171
+ trailingSections.push({ label: 'Images', entries: renderImages(result.formats.images) });
172
+ }
173
+ // Single truncation site: the WHOLE assembled payload (formats + links + images) is
174
+ // truncated once, then meta lines are prepended (issue #2589 audit L1 — links/images
175
+ // used to be appended AFTER truncation, so the combined output could blow past the
176
+ // budget). `trailingSections` is passed as a reserved suffix, not concatenated ahead of
177
+ // time, so it survives the cut even when `payload` alone already fills the budget — and
178
+ // it travels as STRUCTURED sections rather than a joined string so the truncator cuts
179
+ // between whole entries and announces each cut per section (issue #2687 item 6).
180
+ const { text, truncated } = truncateContent(payload, undefined, undefined, trailingSections, FORMAT_DELIMITER_MARKERS);
60
181
  const metaLines = [
61
182
  `ID: ${result.id}`,
62
183
  `URL: ${result.url}`,
63
184
  result.final_url !== result.url ? `Final URL: ${result.final_url}` : null,
64
185
  result.status_code !== null ? `Status Code: ${result.status_code}` : null,
65
186
  result.content_type ? `Content-Type: ${result.content_type}` : null,
187
+ // The billing basis — compressed upstream wire bytes (issue #2687 item 5). Nothing
188
+ // else in the render surfaced what the call cost, so an agent budgeting bandwidth
189
+ // was flying blind. Spelled distinctly from the `Content-Type` line above so the two
190
+ // are not confusable at a glance.
191
+ typeof result.content_length === 'number'
192
+ ? `Content Length: ${result.content_length} bytes`
193
+ : null,
66
194
  result.metadata.title ? `Title: ${result.metadata.title}` : null,
67
195
  truncated ? 'Note: Content was truncated to 100KB' : null,
68
196
  ]
69
197
  .filter(Boolean)
70
198
  .join('\n');
71
- let body = `${metaLines}\n\n---\n\n${text}`;
72
- // Append links block when present
73
- if (Array.isArray(result.formats.links) && result.formats.links.length > 0) {
74
- const linkList = renderLinks(result.formats.links);
75
- body += `\n\nLinks (${result.formats.links.length}):\n${linkList}`;
76
- }
77
- // Append images block when present
78
- if (Array.isArray(result.formats.images) && result.formats.images.length > 0) {
79
- const imgList = renderImages(result.formats.images);
80
- body += `\n\nImages (${result.formats.images.length}):\n${imgList}`;
81
- }
82
- return { text: body, isError: false };
199
+ return { text: `${metaLines}\n\n---\n\n${text}`, isError: false };
83
200
  }
@@ -24,8 +24,24 @@ export function renderScreenshotResult(result) {
24
24
  const lines = [
25
25
  result.id ? `ID: ${result.id}` : null,
26
26
  result.url ? `URL: ${result.url}` : null,
27
+ // Spec field (openapi.yaml ScreenshotResponse.page_title) that the tool description
28
+ // already promises as "metadata" but the renderer dropped (issue #2687 item 4). It
29
+ // is the only in-band signal of WHAT was captured — for an agent chasing a redirect
30
+ // or an interstitial, the rendered title is how it learns it got the wrong page.
31
+ // Omitted (never `Page title: null`) when the API returns no title.
32
+ result.page_title ? `Page title: ${result.page_title}` : null,
27
33
  `Status: ${result.status}`,
28
34
  result.image_url ? `Image: ${result.image_url}` : null,
35
+ // The image URL is a short-lived SIGNED link (issue #2687 item 4). Nothing in the
36
+ // render said so, and an agent that stashed the URL and fetched it later got an
37
+ // opaque 403. Emitted only alongside an actual image URL — a pending screenshot has
38
+ // nothing to expire. `expires_at` (openapi.yaml ScreenshotResponse) is preferred
39
+ // when present, because a concrete instant is actionable where a rule of thumb is not.
40
+ result.image_url
41
+ ? result.expires_at
42
+ ? `Note: the image URL is a signed link that expires at ${result.expires_at} — download it before then.`
43
+ : 'Note: the image URL is a signed link that expires roughly 600s after it is issued — download it before then.'
44
+ : null,
29
45
  result.image_width && result.image_height
30
46
  ? `Size: ${result.image_width}x${result.image_height}`
31
47
  : null,
@@ -33,6 +49,12 @@ export function renderScreenshotResult(result) {
33
49
  result.credits_charged !== undefined && result.credits_charged !== null
34
50
  ? `Credits: ${result.credits_charged}`
35
51
  : null,
52
+ // Mirrors screenshot_url's queued-branch hint text exactly (issue #2591 item 4) --
53
+ // an agent that redeems the handle through get_result while it's still pending
54
+ // needs the same "call again later" guidance screenshot_url gives at submit time.
55
+ result.status === 'pending' || result.status === 'processing'
56
+ ? 'Use get_result with this ID to check when it completes.'
57
+ : null,
36
58
  ].filter((line) => line !== null);
37
59
  return { text: lines.join('\n'), isError: false };
38
60
  }
@@ -2,7 +2,44 @@
2
2
  * Truncate text content to a maximum byte size while preserving valid UTF-8.
3
3
  * Returns the truncated text with a suffix indicating truncation + content URL.
4
4
  */
5
- export declare function truncateContent(text: string, maxBytes?: number, contentUrl?: string): {
5
+ /**
6
+ * A labeled, entry-addressable block of the reserve (issue #2687 item 6).
7
+ *
8
+ * Passing the reserve as SECTIONS rather than one pre-joined string is what lets the
9
+ * truncator cut at an entry boundary and account for the cut per section. A raw string
10
+ * reserve can only be sliced to a byte count, which routinely severed the tail entry
11
+ * mid-URL and left the section header advertising its pre-cut count.
12
+ */
13
+ export interface ReserveSection {
14
+ /** Section label as rendered in the header, e.g. `Links`. */
15
+ label: string;
16
+ /** One rendered line per entry; never joined by the caller. */
17
+ entries: string[];
18
+ }
19
+ /**
20
+ * Renders `sections` into the reserve block, emitting only WHOLE entries and announcing
21
+ * any cut per section (issue #2687 item 6).
22
+ *
23
+ * Budget policy, in order:
24
+ * 1. Every section header is emitted if it fits — a section the agent asked for must be
25
+ * named even when the budget leaves no room for its entries, otherwise the render is
26
+ * indistinguishable from "you did not request it" (the same signal item 1 restores).
27
+ * 2. Entries are then filled in section order. An entry is taken only if it fits WHOLE,
28
+ * and — unless it is the section's last — only if room for that section's marker
29
+ * survives it. That reservation is what guarantees a cut is always announceable.
30
+ * 3. A section that lost entries gets its marker with the count actually emitted.
31
+ *
32
+ * Filling sequentially (rather than pro-rating across sections) means a later section can
33
+ * end up with a `0 of N` marker. That is deliberate: it reports honestly which entries the
34
+ * caller is not seeing, instead of silently rebalancing which content gets dropped.
35
+ *
36
+ * Degenerate budgets (smaller than the headers plus one marker) degrade to headers alone,
37
+ * or to the empty string. No signal is lost there either: the header still carries the
38
+ * real total, and `truncateContent` only reaches this path when it is about to append its
39
+ * own global truncation suffix.
40
+ */
41
+ export declare function renderReserveSections(sections: readonly ReserveSection[], maxBytes: number): string;
42
+ export declare function truncateContent(text: string, maxBytes?: number, contentUrl?: string, reserve?: string | readonly ReserveSection[], dangleMarkers?: readonly string[]): {
6
43
  text: string;
7
44
  truncated: boolean;
8
45
  };
@@ -3,24 +3,192 @@
3
3
  * Returns the truncated text with a suffix indicating truncation + content URL.
4
4
  */
5
5
  const MAX_BYTES = 100 * 1024; // 100KB
6
- export function truncateContent(text, maxBytes = MAX_BYTES, contentUrl) {
7
- const byteLength = Buffer.byteLength(text, 'utf8');
8
- if (byteLength <= maxBytes) {
9
- return { text, truncated: false };
10
- }
11
- // Binary search for the character index that fits within maxBytes
12
- // This handles multi-byte UTF-8 characters correctly
6
+ // The MINIMUM share of `maxBytes` guaranteed to the primary `text` whenever it wants
7
+ // it (issue #2589 cr-1). Without this floor, an oversized reserve block (e.g. a huge
8
+ // links list) could crowd the primary `text` out entirely, just trading which side
9
+ // silently loses everything. It is NOT an unconditional ceiling on `reserve`: when
10
+ // `text` is small and doesn't need its half, the reserve is allowed to claim the
11
+ // leftover instead of that budget going unused (cr2-2) - see the `reserveBudget`
12
+ // computation below.
13
+ const MAX_RESERVE_FRACTION = 0.5;
14
+ /** Slices `text` to at most `maxBytes` UTF-8 bytes, trimming any incomplete trailing
15
+ * multi-byte sequence so the result is always valid UTF-8. */
16
+ function sliceToBytes(text, maxBytes) {
17
+ if (maxBytes <= 0)
18
+ return '';
13
19
  const buf = Buffer.from(text, 'utf8');
14
20
  const sliced = buf.subarray(0, maxBytes);
15
21
  // Decode back to string -- Buffer.toString will handle incomplete multi-byte
16
22
  // sequences at the boundary by replacing them, but we trim to last complete char
17
- let truncated = sliced.toString('utf8');
18
- // Remove any replacement character at the end (from incomplete multi-byte sequence)
19
- while (truncated.endsWith('\uFFFD')) {
20
- truncated = truncated.slice(0, -1);
23
+ let out = sliced.toString('utf8');
24
+ while (out.endsWith('\uFFFD')) {
25
+ out = out.slice(0, -1);
26
+ }
27
+ return out;
28
+ }
29
+ /**
30
+ * Strips a trailing occurrence of any of `markers` from `text` — either a PARTIAL
31
+ * occurrence (issue #2589 cr-8) or, when the cut landed exactly at the end of a
32
+ * COMPLETE delimiter (cr2-6), the whole delimiter.
33
+ *
34
+ * ONLY called when the caller has already confirmed `text` was itself cut (i.e. some
35
+ * of the original content beyond this point was discarded) — see the `textBytes >
36
+ * textBudget` guard at the call site. Under that guard, ANY marker match at the tail
37
+ * — partial or complete — means the section it announces lost 100% of its content to
38
+ * the cut: a partial marker (`\n\n---`) with no closing `format: <name> ---` is an
39
+ * obvious dangling fragment; a COMPLETE marker (`\n\n--- format: html ---\n\n`) with
40
+ * nothing after it is just as misleading, since it announces a section that turns out
41
+ * to be entirely empty, and produces the same forbidden `---\n\n---` collision once
42
+ * the truncation suffix's own leading `\n\n---` is appended right after it. Stripping
43
+ * both cases is safe specifically because of the cut guard: a complete marker that is
44
+ * NOT immediately followed by a cut (i.e. genuinely legitimate, real content or a
45
+ * deliberately-empty format) never reaches this function at all, since
46
+ * `truncateContent` only calls it when `text` was truncated.
47
+ *
48
+ * When multiple markers/lengths match, the longest matching suffix wins.
49
+ */
50
+ function stripDanglingMarker(text, markers) {
51
+ let bestLen = 0;
52
+ for (const marker of markers) {
53
+ for (let len = marker.length; len > 0; len--) {
54
+ if (len > bestLen && text.endsWith(marker.slice(0, len))) {
55
+ bestLen = len;
56
+ }
57
+ }
58
+ }
59
+ return bestLen > 0 ? text.slice(0, text.length - bestLen) : text;
60
+ }
61
+ const byteLen = (value) => Buffer.byteLength(value, 'utf8');
62
+ /** `\n\nLinks (42):` — the section header, identical in shape to the pre-#2687 render. */
63
+ function sectionHeader(section) {
64
+ return `\n\n${section.label} (${section.entries.length}):`;
65
+ }
66
+ /** The per-section cut announcement, carrying the REAL kept count (issue #2687 item 6). */
67
+ function sectionMarker(label, shown, total) {
68
+ return `\n[${label} truncated: ${shown} of ${total} entries shown]`;
69
+ }
70
+ /**
71
+ * Renders `sections` into the reserve block, emitting only WHOLE entries and announcing
72
+ * any cut per section (issue #2687 item 6).
73
+ *
74
+ * Budget policy, in order:
75
+ * 1. Every section header is emitted if it fits — a section the agent asked for must be
76
+ * named even when the budget leaves no room for its entries, otherwise the render is
77
+ * indistinguishable from "you did not request it" (the same signal item 1 restores).
78
+ * 2. Entries are then filled in section order. An entry is taken only if it fits WHOLE,
79
+ * and — unless it is the section's last — only if room for that section's marker
80
+ * survives it. That reservation is what guarantees a cut is always announceable.
81
+ * 3. A section that lost entries gets its marker with the count actually emitted.
82
+ *
83
+ * Filling sequentially (rather than pro-rating across sections) means a later section can
84
+ * end up with a `0 of N` marker. That is deliberate: it reports honestly which entries the
85
+ * caller is not seeing, instead of silently rebalancing which content gets dropped.
86
+ *
87
+ * Degenerate budgets (smaller than the headers plus one marker) degrade to headers alone,
88
+ * or to the empty string. No signal is lost there either: the header still carries the
89
+ * real total, and `truncateContent` only reaches this path when it is about to append its
90
+ * own global truncation suffix.
91
+ */
92
+ export function renderReserveSections(sections, maxBytes) {
93
+ const full = sections
94
+ .map((s) => s.entries.length > 0 ? `${sectionHeader(s)}\n${s.entries.join('\n')}` : sectionHeader(s))
95
+ .join('');
96
+ if (byteLen(full) <= maxBytes)
97
+ return full;
98
+ let remaining = maxBytes;
99
+ const headerEmitted = sections.map((s) => {
100
+ const cost = byteLen(sectionHeader(s));
101
+ if (cost > remaining)
102
+ return false;
103
+ remaining -= cost;
104
+ return true;
105
+ });
106
+ const kept = sections.map(() => []);
107
+ const cut = sections.map(() => false);
108
+ for (let i = 0; i < sections.length; i++) {
109
+ const section = sections[i];
110
+ if (!headerEmitted[i])
111
+ continue;
112
+ // Upper bound on this section's marker: `shown` can never have more digits than
113
+ // `total`, so the all-shown spelling is the longest the marker can ever be.
114
+ const markerReserve = byteLen(sectionMarker(section.label, section.entries.length, section.entries.length));
115
+ for (let j = 0; j < section.entries.length; j++) {
116
+ const cost = byteLen(`\n${section.entries[j]}`);
117
+ const isLast = j === section.entries.length - 1;
118
+ if (cost + (isLast ? 0 : markerReserve) > remaining)
119
+ break;
120
+ kept[i].push(section.entries[j]);
121
+ remaining -= cost;
122
+ }
123
+ if (kept[i].length < section.entries.length) {
124
+ const marker = sectionMarker(section.label, kept[i].length, section.entries.length);
125
+ if (byteLen(marker) <= remaining) {
126
+ remaining -= byteLen(marker);
127
+ cut[i] = true;
128
+ }
129
+ }
130
+ }
131
+ let out = '';
132
+ for (let i = 0; i < sections.length; i++) {
133
+ const section = sections[i];
134
+ if (!headerEmitted[i])
135
+ continue;
136
+ out += sectionHeader(section);
137
+ for (const entry of kept[i])
138
+ out += `\n${entry}`;
139
+ if (cut[i])
140
+ out += sectionMarker(section.label, kept[i].length, section.entries.length);
141
+ }
142
+ return out;
143
+ }
144
+ export function truncateContent(text, maxBytes = MAX_BYTES, contentUrl,
145
+ // `reserve`: content appended immediately after `text`, budgeted SEPARATELY from
146
+ // `text` (capped at MAX_RESERVE_FRACTION of maxBytes) so it survives even when
147
+ // `text` alone already fills the whole budget - e.g. render-scrape.ts's
148
+ // links/images blocks, which used to be appended into the same tail-truncated
149
+ // string and were the first thing discarded (issue #2589 cr-1/cr-4).
150
+ //
151
+ // A {@link ReserveSection} array additionally gets entry-boundary cuts and per-section
152
+ // markers (issue #2687 item 6); a plain string keeps the byte-slice behavior verbatim,
153
+ // for callers with no entry structure to preserve.
154
+ reserve = '',
155
+ // Full delimiter templates (not just markers) whose trailing partial occurrence in
156
+ // the truncated `text` should be stripped rather than left dangling (cr-8).
157
+ dangleMarkers = []) {
158
+ const sections = typeof reserve === 'string' ? null : reserve;
159
+ const reserveText = typeof reserve === 'string' ? reserve : renderReserveSections(reserve, Infinity);
160
+ const textBytes = Buffer.byteLength(text, 'utf8');
161
+ const reserveBytes = Buffer.byteLength(reserveText, 'utf8');
162
+ if (textBytes + reserveBytes <= maxBytes) {
163
+ return { text: text + reserveText, truncated: false };
164
+ }
165
+ // Give the reserve block first claim on its own (capped) share of the budget, then
166
+ // whatever remains to the primary text - the inverse of "reserve competes in the
167
+ // same tail-truncated string" (which is what silently dropped it in full).
168
+ //
169
+ // The cap is a FLOOR guarantee for `text` (text never loses more than half the
170
+ // budget to reserve), not a ceiling on `reserve`: `maxBytes - textBytes` is the
171
+ // budget `text` genuinely has no use for, so when text is small the reserve is
172
+ // allowed to claim that leftover instead of being shaved to 50% unconditionally
173
+ // (issue #2589 cr2-2 - the unconditional cap wasted up to ~50KB of the 100KB
174
+ // budget while still dropping billed links/images content). `maxBytes - textBytes`
175
+ // goes negative whenever text alone already exceeds the budget, in which case
176
+ // `Math.max` falls back to the fixed half-budget floor unchanged from cr-1.
177
+ const reserveBudget = Math.min(reserveBytes, Math.max(Math.floor(maxBytes * MAX_RESERVE_FRACTION), maxBytes - textBytes));
178
+ const textBudget = maxBytes - reserveBudget;
179
+ let slicedText = sliceToBytes(text, textBudget);
180
+ if (textBytes > textBudget) {
181
+ slicedText = stripDanglingMarker(slicedText, dangleMarkers);
21
182
  }
183
+ // A structured reserve re-renders under the budget (whole entries + per-section
184
+ // markers, issue #2687 item 6); a string reserve falls back to the raw byte slice.
185
+ const slicedReserve = reserveBytes > reserveBudget
186
+ ? sections === null
187
+ ? sliceToBytes(reserveText, reserveBudget)
188
+ : renderReserveSections(sections, reserveBudget)
189
+ : reserveText;
22
190
  const suffix = contentUrl
23
191
  ? `\n\n---\n[Content truncated. Full content available at: ${contentUrl}]`
24
192
  : '\n\n---\n[Content truncated at 100KB]';
25
- return { text: truncated + suffix, truncated: true };
193
+ return { text: slicedText + slicedReserve + suffix, truncated: true };
26
194
  }
@@ -1,6 +1,12 @@
1
1
  export function accountResource(server, client) {
2
2
  server.resource('account', 'bytekit://account', { description: 'Current ByteKit account details and usage' }, async () => {
3
- const [account, usage] = await Promise.all([client.getAccount(), client.getUsage()]);
3
+ // Serialized rather than issued concurrently: firing both requests at once is
4
+ // unkind to 1-rps plans (issue #2687 item 8). `get_account` was serialized for
5
+ // exactly this reason in #2591 item 3; this resource calls the same two endpoints
6
+ // and kept awaiting them together, so reading `bytekit://account` could still burn
7
+ // two requests inside the same second and rate-limit itself.
8
+ const account = await client.getAccount();
9
+ const usage = await client.getUsage();
4
10
  const text = JSON.stringify({ account, usage }, null, 2);
5
11
  return {
6
12
  contents: [
@@ -135,8 +135,13 @@ export interface ScrapeSuccessEnvelope {
135
135
  export interface ScrapeErrorEnvelope {
136
136
  schema_version: ScrapeEnvelopeSchemaVersion;
137
137
  status: 'failed';
138
- /** Stable job identifier (sc_… prefixed). Canonical field (#1232; queued/error migrated #1971). */
139
- id: string;
138
+ /**
139
+ * Stable job identifier (sc_… prefixed). Canonical field (#1232; queued/error migrated
140
+ * #1971). Nullable (issue #2591 item 7, matches docs/api/openapi.yaml
141
+ * ScrapeErrorEnvelope.id: `type: ["string", "null"]`) — null when the job was never
142
+ * queued (e.g. a validation failure before a row existed).
143
+ */
144
+ id: string | null;
140
145
  error: {
141
146
  code: ScrapeEnvelopeErrorCode;
142
147
  message: string;
@@ -1,11 +1,19 @@
1
1
  export function getAccountTool(server, client) {
2
2
  server.tool('get_account', 'Get your ByteKit account details, plan info, and current usage/quota.', {}, async () => {
3
3
  try {
4
- const [account, usage] = await Promise.all([client.getAccount(), client.getUsage()]);
4
+ // Serialized, not Promise.all: firing both requests concurrently is unkind to
5
+ // 1-rps plans (issue #2591 item 3 / DoD bullet 2) — this also keeps `get_account`
6
+ // itself safe to recommend as a quota-check follow-up without risking a second
7
+ // rate-limit hit from its own two sub-requests.
8
+ const account = await client.getAccount();
9
+ const usage = await client.getUsage();
5
10
  // The API may return a null account name (issue #2477) — fall back to the email
6
- // rather than rendering the literal `Account: null`.
11
+ // rather than rendering the literal `Account: null`. When there's no name, show
12
+ // the email once instead of duplicating it in both slots (issue #2591 item 5).
7
13
  const lines = [
8
- `Account: ${account.name ?? account.email} (${account.email})`,
14
+ account.name
15
+ ? `Account: ${account.name} (${account.email})`
16
+ : `Account: ${account.email}`,
9
17
  `Account ID: ${account.id}`,
10
18
  '',
11
19
  `Plan: ${account.plan.name} (${account.plan.slug})`,