@vybestack/llxprt-code-tools 0.11.0 → 0.12.0-nightly.260910.2aac6841e

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.
Files changed (65) hide show
  1. package/dist/src/acquisition/bounded-http-response.d.ts +14 -17
  2. package/dist/src/acquisition/bounded-http-response.js +124 -99
  3. package/dist/src/acquisition/bounded-http-response.js.map +1 -1
  4. package/dist/src/formatters/ToolFormatter.js +7 -8
  5. package/dist/src/formatters/ToolFormatter.js.map +1 -1
  6. package/dist/src/index.d.ts +1 -1
  7. package/dist/src/index.js +1 -1
  8. package/dist/src/index.js.map +1 -1
  9. package/dist/src/interfaces/ISkillService.d.ts +0 -6
  10. package/dist/src/interfaces/IToolHost.d.ts +0 -11
  11. package/dist/src/test-utils/loopback-test-helpers.d.ts +20 -0
  12. package/dist/src/test-utils/loopback-test-helpers.js +158 -0
  13. package/dist/src/test-utils/loopback-test-helpers.js.map +1 -0
  14. package/dist/src/tools/activate-skill.js +7 -18
  15. package/dist/src/tools/activate-skill.js.map +1 -1
  16. package/dist/src/tools/codesearch.js +0 -1
  17. package/dist/src/tools/codesearch.js.map +1 -1
  18. package/dist/src/tools/direct-web-fetch.js +25 -14
  19. package/dist/src/tools/direct-web-fetch.js.map +1 -1
  20. package/dist/src/tools/exa-web-search.js +0 -1
  21. package/dist/src/tools/exa-web-search.js.map +1 -1
  22. package/dist/src/tools/github-ops.d.ts +1 -1
  23. package/dist/src/tools/github-ops.js +16 -1
  24. package/dist/src/tools/github-ops.js.map +1 -1
  25. package/dist/src/tools/github.js +3 -2
  26. package/dist/src/tools/github.js.map +1 -1
  27. package/dist/src/tools/read-file.d.ts +0 -4
  28. package/dist/src/tools/read-file.js +1 -5
  29. package/dist/src/tools/read-file.js.map +1 -1
  30. package/dist/src/tools/tool-registry.js +0 -11
  31. package/dist/src/tools/tool-registry.js.map +1 -1
  32. package/dist/src/types/wire-types.d.ts +11 -0
  33. package/dist/src/utils/fileUtils.js +4 -1
  34. package/dist/src/utils/fileUtils.js.map +1 -1
  35. package/dist/src/utils/flatOrNestedSetting.d.ts +19 -0
  36. package/dist/src/utils/flatOrNestedSetting.js +55 -0
  37. package/dist/src/utils/flatOrNestedSetting.js.map +1 -0
  38. package/dist/src/utils/imageResize.d.ts +11 -1
  39. package/dist/src/utils/imageResize.js +27 -9
  40. package/dist/src/utils/imageResize.js.map +1 -1
  41. package/dist/src/utils/imageTokenEstimation.d.ts +25 -1
  42. package/dist/src/utils/imageTokenEstimation.js +93 -7
  43. package/dist/src/utils/imageTokenEstimation.js.map +1 -1
  44. package/dist/src/utils/mediaUtils.d.ts +2 -2
  45. package/package.json +7 -4
  46. package/src/acquisition/bounded-http-response.ts +132 -112
  47. package/src/formatters/ToolFormatter.ts +8 -8
  48. package/src/index.ts +1 -0
  49. package/src/interfaces/ISkillService.ts +0 -7
  50. package/src/interfaces/IToolHost.ts +0 -13
  51. package/src/test-utils/loopback-test-helpers.ts +214 -0
  52. package/src/tools/activate-skill.ts +9 -23
  53. package/src/tools/codesearch.ts +2 -4
  54. package/src/tools/direct-web-fetch.ts +32 -20
  55. package/src/tools/exa-web-search.ts +1 -3
  56. package/src/tools/github-ops.ts +18 -1
  57. package/src/tools/github.ts +4 -2
  58. package/src/tools/read-file.ts +1 -14
  59. package/src/tools/tool-registry.ts +0 -15
  60. package/src/types/wire-types.ts +8 -0
  61. package/src/utils/fileUtils.ts +9 -0
  62. package/src/utils/flatOrNestedSetting.ts +63 -0
  63. package/src/utils/imageResize.ts +41 -9
  64. package/src/utils/imageTokenEstimation.ts +109 -5
  65. package/src/utils/mediaUtils.ts +2 -2
@@ -11,9 +11,33 @@ import { type ImageDimensions } from './imageDimensions.js';
11
11
  export type ImageTokenProviderFamily = 'anthropic' | 'openai' | 'gemini' | 'default';
12
12
  /** Flat fallback when no provider is known (better than 85, safer than 3000). */
13
13
  export declare const DEFAULT_IMAGE_TOKEN_ESTIMATE = 1000;
14
+ /** Classification of an OpenAI-family model for image token estimation. */
15
+ export type OpenaiImageTokenGeneration = 'patch' | 'legacy' | 'unknown';
16
+ /**
17
+ * Classify a model name for OpenAI image token estimation.
18
+ *
19
+ * - 'patch': GPT-5.2 and newer, including any later minor (gpt-5.6,
20
+ * gpt-5.10), named variants like gpt-5.6-sol/terra/luna, and every
21
+ * GPT-6+ model (gpt-6, gpt-10). The major/minor version is parsed
22
+ * numerically so multi-digit versions classify correctly.
23
+ * - 'legacy': gpt-4o, gpt-4.1, gpt-5.0, gpt-5.1, and o-series models
24
+ * (o1, o3, o4-mini).
25
+ * - 'unknown': model is provided but does not match either category.
26
+ * Callers in the OpenAI family should use the patch formula (conservative-high).
27
+ * - Returns 'unknown' for undefined/empty model so callers can decide.
28
+ */
29
+ export declare function classifyOpenaiModel(model: string | undefined): OpenaiImageTokenGeneration;
30
+ /**
31
+ * Determine whether a model name belongs to the GPT-5.2-or-newer generation
32
+ * that uses the patch-based image token formula. For unknown models in the
33
+ * OpenAI family, returns true (conservative-high, per issue #3477).
34
+ * Returns false for undefined/empty model (no basis to choose).
35
+ */
36
+ export declare function isGpt52OrNewer(model: string | undefined): boolean;
14
37
  export interface ImageTokenEstimateInput {
15
38
  readonly provider?: string;
16
39
  readonly dimensions?: ImageDimensions;
40
+ readonly model?: string;
17
41
  }
18
42
  export declare function resolveImageTokenProviderFamily(provider: string | undefined): ImageTokenProviderFamily;
19
43
  /**
@@ -26,4 +50,4 @@ export declare function estimateImageTokens(input: ImageTokenEstimateInput): num
26
50
  * optional base64 payload. Images are measured from their parsed header
27
51
  * dimensions; every other binary payload uses the flat default estimate.
28
52
  */
29
- export declare function estimateNonTextPartTokens(mimeType: string | undefined, base64Data: string | undefined, provider?: string): number;
53
+ export declare function estimateNonTextPartTokens(mimeType: string | undefined, base64Data: string | undefined, provider?: string, model?: string): number;
@@ -32,7 +32,12 @@ const ANTHROPIC_UNKNOWN_DIMENSIONS_TOKENS = Math.ceil(ANTHROPIC_MAX_PIXELS / ANT
32
32
  * preferred over an arbitrarily large constant that would make context
33
33
  * compression fire spuriously for every URL-referenced image.
34
34
  */
35
- const OPENAI_UNKNOWN_DIMENSIONS_TOKENS = 1105;
35
+ const OPENAI_LEGACY_UNKNOWN_DIMENSIONS_TOKENS = 1105;
36
+ /**
37
+ * GPT-5.2+ patch formula caps at 1536 patches, so the worst case at standard
38
+ * detail is ceil(1.2 x 1536) = 1844 tokens.
39
+ */
40
+ const OPENAI_PATCH_UNKNOWN_DIMENSIONS_TOKENS = 1844;
36
41
  /** OpenAI first fits the image inside a square of this many pixels per edge. */
37
42
  const OPENAI_MAX_EDGE = 2048;
38
43
  /** OpenAI then normalises the shortest side to this many pixels. */
@@ -43,6 +48,83 @@ const OPENAI_TILE_SIZE = 512;
43
48
  const OPENAI_TOKENS_PER_TILE = 170;
44
49
  /** OpenAI charges this base cost for every high-detail image. */
45
50
  const OPENAI_BASE_TOKENS = 85;
51
+ /** GPT-5.2+ patch formula: max patches at standard detail. */
52
+ const OPENAI_PATCH_MAX_PATCHES = 1536;
53
+ /** GPT-5.2+ patch formula: multiplier applied to patch count. */
54
+ const OPENAI_PATCH_MULTIPLIER = 1.2;
55
+ /**
56
+ * GPT-5.2+ patch formula: ceil(1.2 x min(ceil(w/32) x ceil(h/32), 1536)).
57
+ * Maximum 1844 tokens at standard detail.
58
+ */
59
+ function estimateOpenaiPatchTokens(dimensions) {
60
+ const patchesW = Math.ceil(dimensions.width / 32);
61
+ const patchesH = Math.ceil(dimensions.height / 32);
62
+ const patches = Math.min(patchesW * patchesH, OPENAI_PATCH_MAX_PATCHES);
63
+ return Math.ceil(OPENAI_PATCH_MULTIPLIER * patches);
64
+ }
65
+ /**
66
+ * Classify a model name for OpenAI image token estimation.
67
+ *
68
+ * - 'patch': GPT-5.2 and newer, including any later minor (gpt-5.6,
69
+ * gpt-5.10), named variants like gpt-5.6-sol/terra/luna, and every
70
+ * GPT-6+ model (gpt-6, gpt-10). The major/minor version is parsed
71
+ * numerically so multi-digit versions classify correctly.
72
+ * - 'legacy': gpt-4o, gpt-4.1, gpt-5.0, gpt-5.1, and o-series models
73
+ * (o1, o3, o4-mini).
74
+ * - 'unknown': model is provided but does not match either category.
75
+ * Callers in the OpenAI family should use the patch formula (conservative-high).
76
+ * - Returns 'unknown' for undefined/empty model so callers can decide.
77
+ */
78
+ export function classifyOpenaiModel(model) {
79
+ if (model === undefined || model.length === 0)
80
+ return 'unknown';
81
+ const normalized = model.trim().toLowerCase();
82
+ const generation = classifyNormalizedOpenaiModel(normalized);
83
+ return generation;
84
+ }
85
+ function classifyNormalizedOpenaiModel(normalized) {
86
+ // Patch when major > 5 (gpt-6, gpt-10, ...) or major == 5 with a minor
87
+ // of at least 2 (gpt-5.2, gpt-5.10). Parsed numerically because regex
88
+ // digit ranges cannot express ">= 2" or ">= 6" for multi-digit versions.
89
+ const version = /^gpt-(\d+)(?:\.(\d+))?/.exec(normalized);
90
+ if (version !== null) {
91
+ const major = parseInt(version[1], 10);
92
+ // The optional minor group is either absent (undefined, falsy) or a
93
+ // digit run (never empty), so a truthiness check separates the cases.
94
+ const minor = version[2] ? parseInt(version[2], 10) : 0;
95
+ if (major > 5 || (major === 5 && minor >= 2))
96
+ return 'patch';
97
+ }
98
+ // Known legacy models
99
+ if (isLegacyOpenaiModel(normalized))
100
+ return 'legacy';
101
+ return 'unknown';
102
+ }
103
+ const LEGACY_OPENAI_MODEL_PATTERNS = [
104
+ /^gpt-4o/,
105
+ /^gpt-4\.1/,
106
+ /^gpt-5\.0/,
107
+ /^gpt-5\.1/,
108
+ /^o[1-9]/,
109
+ ];
110
+ function isLegacyOpenaiModel(normalized) {
111
+ return LEGACY_OPENAI_MODEL_PATTERNS.some((pattern) => pattern.test(normalized));
112
+ }
113
+ /**
114
+ * Determine whether a model name belongs to the GPT-5.2-or-newer generation
115
+ * that uses the patch-based image token formula. For unknown models in the
116
+ * OpenAI family, returns true (conservative-high, per issue #3477).
117
+ * Returns false for undefined/empty model (no basis to choose).
118
+ */
119
+ export function isGpt52OrNewer(model) {
120
+ const generation = classifyOpenaiModel(model);
121
+ if (generation === 'unknown') {
122
+ // Unknown but non-empty model in the openai family: use patch formula
123
+ // (conservative-high). Undefined/empty model: no basis, use legacy.
124
+ return model !== undefined && model.trim().length > 0;
125
+ }
126
+ return generation === 'patch';
127
+ }
46
128
  /**
47
129
  * Provider-name fragments per family. Substring matching mirrors the tokenizer
48
130
  * selection in the providers runtime so alias providers that wrap a backing
@@ -109,13 +191,15 @@ function estimateOpenaiTokens(dimensions) {
109
191
  countTiles(boundedHeight * shortSideScale);
110
192
  return OPENAI_TOKENS_PER_TILE * tiles + OPENAI_BASE_TOKENS;
111
193
  }
112
- function estimateForFamily(family, dimensions) {
194
+ function estimateForFamily(family, dimensions, model) {
113
195
  if (!hasValidDimensions(dimensions)) {
114
196
  switch (family) {
115
197
  case 'anthropic':
116
198
  return ANTHROPIC_UNKNOWN_DIMENSIONS_TOKENS;
117
199
  case 'openai':
118
- return OPENAI_UNKNOWN_DIMENSIONS_TOKENS;
200
+ return isGpt52OrNewer(model)
201
+ ? OPENAI_PATCH_UNKNOWN_DIMENSIONS_TOKENS
202
+ : OPENAI_LEGACY_UNKNOWN_DIMENSIONS_TOKENS;
119
203
  case 'gemini':
120
204
  return FLAT_IMAGE_TOKEN_ESTIMATE;
121
205
  default:
@@ -126,7 +210,9 @@ function estimateForFamily(family, dimensions) {
126
210
  case 'anthropic':
127
211
  return estimateAnthropicTokens(dimensions);
128
212
  case 'openai':
129
- return estimateOpenaiTokens(dimensions);
213
+ return isGpt52OrNewer(model)
214
+ ? estimateOpenaiPatchTokens(dimensions)
215
+ : estimateOpenaiTokens(dimensions);
130
216
  case 'gemini':
131
217
  return FLAT_IMAGE_TOKEN_ESTIMATE;
132
218
  default:
@@ -139,14 +225,14 @@ function estimateForFamily(family, dimensions) {
139
225
  */
140
226
  export function estimateImageTokens(input) {
141
227
  const family = resolveImageTokenProviderFamily(input.provider);
142
- return estimateForFamily(family, input.dimensions);
228
+ return estimateForFamily(family, input.dimensions, input.model);
143
229
  }
144
230
  /**
145
231
  * Estimate tokens for a non-text (binary) part described by its MIME type and
146
232
  * optional base64 payload. Images are measured from their parsed header
147
233
  * dimensions; every other binary payload uses the flat default estimate.
148
234
  */
149
- export function estimateNonTextPartTokens(mimeType, base64Data, provider) {
235
+ export function estimateNonTextPartTokens(mimeType, base64Data, provider, model) {
150
236
  const isImage = mimeType?.toLowerCase().startsWith('image/') ?? false;
151
237
  if (!isImage) {
152
238
  return DEFAULT_IMAGE_TOKEN_ESTIMATE;
@@ -154,6 +240,6 @@ export function estimateNonTextPartTokens(mimeType, base64Data, provider) {
154
240
  const dimensions = base64Data === undefined
155
241
  ? undefined
156
242
  : parseImageDimensionsFromBase64(base64Data);
157
- return estimateImageTokens({ provider, dimensions });
243
+ return estimateImageTokens({ provider, dimensions, model });
158
244
  }
159
245
  //# sourceMappingURL=imageTokenEstimation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"imageTokenEstimation.js","sourceRoot":"","sources":["../../../src/utils/imageTokenEstimation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,8BAA8B,GAE/B,MAAM,sBAAsB,CAAC;AAa9B,iFAAiF;AACjF,MAAM,CAAC,MAAM,4BAA4B,GAAG,IAAI,CAAC;AAEjD;;;GAGG;AACH,MAAM,yBAAyB,GAAG,IAAI,CAAC;AAEvC,6EAA6E;AAC7E,MAAM,uBAAuB,GAAG,IAAI,CAAC;AAErC;;;GAGG;AACH,MAAM,oBAAoB,GAAG,IAAI,GAAG,IAAI,CAAC;AAEzC,wDAAwD;AACxD,MAAM,0BAA0B,GAAG,GAAG,CAAC;AAEvC;;;GAGG;AACH,MAAM,mCAAmC,GAAG,IAAI,CAAC,IAAI,CACnD,oBAAoB,GAAG,0BAA0B,CAClD,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,gCAAgC,GAAG,IAAI,CAAC;AAE9C,gFAAgF;AAChF,MAAM,eAAe,GAAG,IAAI,CAAC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 +21,8 @@ export interface MediaBlock {
21
21
  mimeType: string;
22
22
  /** Base64-encoded data or URL. */
23
23
  data?: string;
24
- /** Whether data is a URL or base64. */
25
- encoding?: 'url' | 'base64';
24
+ /** Whether media is inline, a URL, or a local content reference. */
25
+ encoding?: 'url' | 'base64' | 'reference';
26
26
  /** Optional caption or alt text. */
27
27
  caption?: string;
28
28
  /** Original filename if applicable. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vybestack/llxprt-code-tools",
3
- "version": "0.11.0",
3
+ "version": "0.12.0-nightly.260910.2aac6841e",
4
4
  "description": "LLxprt Code Tools — built-in tool implementations, contracts, formatters, and registry",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -46,6 +46,11 @@
46
46
  "bun": "./src/formatters/toolNameUtils.ts",
47
47
  "import": "./dist/src/formatters/toolNameUtils.js"
48
48
  },
49
+ "./utils/errors.js": {
50
+ "types": "./dist/src/utils/errors.d.ts",
51
+ "bun": "./src/utils/errors.ts",
52
+ "import": "./dist/src/utils/errors.js"
53
+ },
49
54
  "./utils/fetch.js": {
50
55
  "types": "./dist/src/utils/fetch.d.ts",
51
56
  "bun": "./src/utils/fetch.ts",
@@ -254,7 +259,7 @@
254
259
  "test": "bun ../../scripts/run_bun_tests.ts --workspace tools --junit junit.xml",
255
260
  "test:bun": "bun ../../scripts/run_bun_tests.ts --workspace tools",
256
261
  "test:ci": "bun ../../scripts/run_bun_tests.ts --workspace tools --junit junit.xml",
257
- "typecheck": "tsc --noEmit"
262
+ "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test-bun.json"
258
263
  },
259
264
  "files": [
260
265
  "index.ts",
@@ -270,12 +275,10 @@
270
275
  "dependencies": {
271
276
  "@ast-grep/napi": "^0.40.5",
272
277
  "ajv": "^8.17.1",
273
- "cheerio": "^1.1.2",
274
278
  "diff": "^8.0.3",
275
279
  "fast-glob": "^3.3.3",
276
280
  "glob": "^12.0.0",
277
281
  "html-to-text": "^9.0.5",
278
- "node-fetch": "^3.3.2",
279
282
  "shell-quote": "^1.10.0",
280
283
  "turndown": "^7.2.2",
281
284
  "zod": "^3.25.76",
@@ -7,9 +7,9 @@
7
7
  import type { ByteBudget, TruncationMetadata } from './types.js';
8
8
  import { BoundedStreamCollector } from './boundedStreamCollector.js';
9
9
 
10
- /** Minimal structural interface satisfied by a node-fetch Response. */
10
+ /** Structural surface of a native fetch Response used by bounded acquisition. */
11
11
  export interface BoundedFetchResponse {
12
- readonly body: NodeJS.ReadableStream | null;
12
+ readonly body: ReadableStream<Uint8Array> | null;
13
13
  readonly headers: { get(name: string): string | null };
14
14
  }
15
15
 
@@ -34,28 +34,17 @@ export interface BoundedHttpBody {
34
34
  readonly metadata: TruncationMetadata;
35
35
  }
36
36
 
37
- type ManagedStream = NodeJS.ReadableStream & {
38
- destroyed?: boolean;
39
- destroy?(error?: Error): unknown;
40
- };
41
-
42
37
  function createAbortError(): Error {
43
38
  const error = new Error('The operation was aborted');
44
39
  error.name = 'AbortError';
45
40
  return error;
46
41
  }
47
42
 
48
- function destroyStream(stream: ManagedStream | null | undefined): void {
49
- if (stream === null || stream === undefined) return;
50
- if (stream.destroyed === true) return;
51
- stream.destroy?.();
52
- }
53
-
54
43
  /**
55
44
  * Parse a Content-Length header strictly. Only when the entire trimmed value
56
- * consists solely of decimal digits and is safely representable as a
57
- * nonnegative integer is it accepted. Malformed or unsafe values are treated
58
- * as absent, forcing observed-byte streaming enforcement.
45
+ * consists solely of decimal digits and is safely representable as a nonnegative
46
+ * integer is it accepted. Malformed or unsafe values are treated as absent,
47
+ * forcing observed-byte streaming enforcement.
59
48
  */
60
49
  function parseContentLength(header: string | null): number | undefined {
61
50
  if (header === null) return undefined;
@@ -66,142 +55,173 @@ function parseContentLength(header: string | null): number | undefined {
66
55
  return value;
67
56
  }
68
57
 
69
- function toBuffer(chunk: unknown): Buffer {
70
- if (Buffer.isBuffer(chunk)) return chunk;
71
- if (chunk instanceof Uint8Array) return Buffer.from(chunk);
72
- // Node.js streams may emit strings; encode via UTF-8.
73
- return Buffer.from(String(chunk));
74
- }
75
-
76
58
  /**
77
- * Close/destroy a response body without reading it. Used by callers that
78
- * reject a response before body acquisition (e.g. non-2xx status).
59
+ * Close/cancel a native fetch response body without reading it. Used by callers
60
+ * that reject a response before body acquisition (e.g. non-2xx status).
79
61
  *
80
- * Both cancels the concrete HTTP request (via the caller-owned callback) and
81
- * destroys the response body wrapper so the underlying socket is released.
62
+ * The body is canceled directly, then the caller-owned callback aborts the
63
+ * concrete fetch request. Cleanup failures are ignored so the caller's primary
64
+ * HTTP status error remains authoritative and the helper stays synchronous.
82
65
  */
83
66
  export function disposeHttpResponseBody(
84
67
  response: BoundedFetchResponse,
85
68
  cancelRequest: () => void,
86
69
  ): void {
87
- cancelRequest();
88
- destroyStream(response.body as ManagedStream | null | undefined);
70
+ try {
71
+ void response.body?.cancel().catch(() => undefined);
72
+ } catch {
73
+ // Cleanup must not replace the caller's primary HTTP status error.
74
+ }
75
+ attemptRequestCancellation(cancelRequest);
76
+ }
77
+
78
+ function createReaderRelease(
79
+ reader: ReadableStreamDefaultReader<Uint8Array>,
80
+ ): () => void {
81
+ let released = false;
82
+ return (): void => {
83
+ if (released) return;
84
+ released = true;
85
+ reader.releaseLock();
86
+ };
87
+ }
88
+
89
+ function attemptRequestCancellation(cancelRequest: () => void): void {
90
+ try {
91
+ cancelRequest();
92
+ } catch {
93
+ return;
94
+ }
95
+ }
96
+
97
+ function attemptReaderRelease(releaseReader: () => void): void {
98
+ try {
99
+ releaseReader();
100
+ } catch {
101
+ // Cleanup must not replace the authoritative acquisition error.
102
+ }
89
103
  }
90
104
 
91
105
  /**
92
- * Read a managed stream through a {@link BoundedStreamCollector} configured to
93
- * retain the complete bounded response.
106
+ * Read a native {@link ReadableStream} through a {@link BoundedStreamCollector}
107
+ * configured to retain the complete bounded response.
94
108
  *
95
- * On overflow, abort, or read error the caller-owned {@link cancelRequest}
96
- * callback is invoked (cancelling the concrete HTTP request), the stream
97
- * wrapper is destroyed, and all listeners are removed. Normal completion does
109
+ * The body is consumed chunk-by-chunk via a Web Stream reader. Bytes are counted
110
+ * in one pass and decoded only when the complete body fits the budget. Overflow
111
+ * and abort cancel the locked reader and concrete request. A read error
112
+ * cancels the request directly because the stream is already errored. Every path
113
+ * releases the reader lock and removes the abort listener. Normal completion does
98
114
  * not cancel the request.
99
115
  */
100
116
  function streamBoundedBody(
101
- body: ManagedStream,
117
+ body: ReadableStream<Uint8Array>,
102
118
  budget: ByteBudget,
103
119
  signal: AbortSignal,
104
120
  cancelRequest: () => void,
105
121
  ): Promise<BoundedHttpBody> {
122
+ const reader = body.getReader();
123
+ const releaseReader = createReaderRelease(reader);
124
+ const collector = new BoundedStreamCollector({ budget, headFraction: 1 });
125
+ let settled = false;
126
+ let cancellationStarted = false;
127
+
128
+ const cancelAcquisition = (): void => {
129
+ if (cancellationStarted) return;
130
+ cancellationStarted = true;
131
+ attemptRequestCancellation(cancelRequest);
132
+ try {
133
+ void reader.cancel().catch(() => undefined);
134
+ } catch {
135
+ // Cleanup must not replace the authoritative acquisition error.
136
+ }
137
+ attemptReaderRelease(releaseReader);
138
+ };
139
+
106
140
  return new Promise<BoundedHttpBody>((resolve, reject) => {
107
- const collector = new BoundedStreamCollector({ budget, headFraction: 1 });
108
- let settled = false;
109
-
110
- const cleanup = (): void => {
111
- body.removeListener('data', onData);
112
- body.removeListener('end', onEnd);
113
- body.removeListener('error', onError);
114
- body.removeListener('close', onClose);
115
- signal.removeEventListener('abort', onAbort);
141
+ const rejectAfterCancellation = (error: unknown): void => {
142
+ reject(error);
143
+ cancelAcquisition();
116
144
  };
117
145
 
118
146
  const settle = (action: () => void): void => {
119
147
  if (settled) return;
120
148
  settled = true;
121
- cleanup();
149
+ signal.removeEventListener('abort', onAbort);
122
150
  action();
123
151
  };
124
152
 
125
- const onData = (chunk: unknown): void => {
126
- collector.append(toBuffer(chunk));
127
- if (collector.observedByteCount > budget.bytes) {
128
- const overflowBytes = collector.observedByteCount;
129
- settle(() => {
130
- cancelRequest();
131
- destroyStream(body);
132
- reject(new HttpBodyTooLargeError(overflowBytes, budget.bytes));
133
- });
134
- }
135
- };
136
-
137
- const onEnd = (): void => {
138
- settle(() => {
139
- const result = collector.getResult();
140
- resolve({ text: result.text, metadata: result.metadata });
141
- });
142
- };
143
-
144
- const onError = (err: Error): void => {
145
- settle(() => {
146
- cancelRequest();
147
- destroyStream(body);
148
- reject(err);
149
- });
150
- };
151
-
152
- /**
153
- * 'close' without a prior 'end' means the body terminated prematurely —
154
- * the complete bounded body cannot be known, so acquisition settles by
155
- * rejecting. When 'end', 'error', or 'abort' settled first, this is a
156
- * guarded no-op (single authoritative settlement).
157
- */
158
- const onClose = (): void => {
159
- settle(() => {
160
- cancelRequest();
161
- destroyStream(body);
162
- reject(new Error('Response body closed before end (incomplete body)'));
163
- });
164
- };
165
-
166
153
  const onAbort = (): void => {
167
154
  settle(() => {
168
- cancelRequest();
169
- destroyStream(body);
170
- reject(createAbortError());
155
+ rejectAfterCancellation(createAbortError());
171
156
  });
172
157
  };
173
158
 
174
- body.on('error', onError);
175
- body.on('end', onEnd);
176
- body.on('close', onClose);
177
- body.on('data', onData);
178
159
  signal.addEventListener('abort', onAbort, { once: true });
179
-
180
- // Check for abort after listener registration to avoid the race where
181
- // the signal fires between a pre-registration check and addEventListener.
182
160
  if (signal.aborted) {
183
161
  onAbort();
162
+ return;
184
163
  }
164
+
165
+ void (async () => {
166
+ try {
167
+ while (!settled) {
168
+ const { done, value } = await reader.read();
169
+ if (signal.aborted) return;
170
+ if (done) {
171
+ settle(() => {
172
+ const result = collector.getResult();
173
+ resolve({ text: result.text, metadata: result.metadata });
174
+ });
175
+ return;
176
+ }
177
+ collector.append(Buffer.from(value));
178
+ if (collector.observedByteCount > budget.bytes) {
179
+ const observedBytes = collector.observedByteCount;
180
+ settle(() => {
181
+ rejectAfterCancellation(
182
+ new HttpBodyTooLargeError(observedBytes, budget.bytes),
183
+ );
184
+ });
185
+ return;
186
+ }
187
+ }
188
+ } catch (readError) {
189
+ settle(() => {
190
+ attemptRequestCancellation(cancelRequest);
191
+ reject(readError);
192
+ });
193
+ } finally {
194
+ releaseReader();
195
+ }
196
+ })();
185
197
  });
186
198
  }
187
199
 
200
+ function attemptUnlockedBodyCancellation(
201
+ body: ReadableStream<Uint8Array> | null,
202
+ cancelRequest: () => void,
203
+ ): void {
204
+ attemptRequestCancellation(cancelRequest);
205
+ try {
206
+ void body?.cancel().catch(() => undefined);
207
+ } catch {
208
+ // Cleanup must not replace the authoritative acquisition error.
209
+ }
210
+ }
211
+
188
212
  /**
189
213
  * Stream an HTTP response body through a bounded byte budget.
190
214
  *
191
- * The body is consumed chunk-by-chunk via stream events and retained by a
192
- * {@link BoundedStreamCollector} configured to retain the complete bounded
215
+ * The body is consumed chunk-by-chunk via a native Web Stream reader and retained
216
+ * by a {@link BoundedStreamCollector} configured to retain the complete bounded
193
217
  * response (headFraction 1). Content-Length is used only as an early-reject
194
- * optimization — the actual streamed bytes are authoritative.
218
+ * optimization; the actual streamed bytes are authoritative.
195
219
  *
196
- * On overflow, abort, or read error the caller-owned {@link cancelRequest}
197
- * callback is invoked (cancelling the concrete HTTP request), the underlying
198
- * stream wrapper is destroyed, all listeners are removed, and the function
199
- * rejects. No partial body text is returned in the failure paths. Normal
220
+ * Overflow and abort cancel the body through the locked reader and invoke the
221
+ * caller-owned {@link cancelRequest} callback. Read errors invoke the callback
222
+ * directly because the stream is already errored. All failure paths release the
223
+ * reader lock, remove the abort listener, and return no partial body text. Normal
200
224
  * completion does not cancel the request.
201
- *
202
- * @param cancelRequest Caller-owned cancellation of the concrete fetch request
203
- * (e.g. aborting a per-fetch AbortController). Required so forgetting
204
- * transport ownership is a compile error.
205
225
  */
206
226
  export async function acquireBoundedHttpBody(
207
227
  response: BoundedFetchResponse,
@@ -211,13 +231,13 @@ export async function acquireBoundedHttpBody(
211
231
  ): Promise<BoundedHttpBody> {
212
232
  const advertised = parseContentLength(response.headers.get('content-length'));
213
233
  if (advertised !== undefined && advertised > budget.bytes) {
214
- cancelRequest();
215
- destroyStream(response.body as ManagedStream | null | undefined);
216
- throw new HttpBodyTooLargeError(advertised, budget.bytes);
234
+ const overflowError = new HttpBodyTooLargeError(advertised, budget.bytes);
235
+ attemptUnlockedBodyCancellation(response.body, cancelRequest);
236
+ throw overflowError;
217
237
  }
218
238
 
219
- const body = response.body as ManagedStream | null | undefined;
220
- if (body === null || body === undefined) {
239
+ const body = response.body;
240
+ if (body === null) {
221
241
  return Promise.resolve({
222
242
  text: '',
223
243
  metadata: {
@@ -57,6 +57,9 @@ function isRequiredMissing(requiredValue: unknown): boolean {
57
57
  return MISSING_SCHEMA_VALUES.has(requiredValue);
58
58
  }
59
59
 
60
+ /** Streaming argument buffers, keyed on the block so they survive across ToolFormatter instances. */
61
+ const streamingArgumentBuffers = new WeakMap<ToolCallBlock, string>();
62
+
60
63
  /**
61
64
  * Converts tool declarations to various provider formats.
62
65
  *
@@ -530,22 +533,19 @@ export class ToolFormatter implements IToolFormatter {
530
533
  index: number,
531
534
  format: ToolFormat,
532
535
  ): void {
533
- if (!('_argumentsString' in tc)) {
534
- (tc as unknown as { _argumentsString: string })._argumentsString = '';
535
- }
536
+ const previous = streamingArgumentBuffers.get(tc) ?? '';
536
537
 
537
538
  if (format === 'qwen') {
538
539
  logDoubleEscapingInChunk(chunk || '', tc.name || 'unknown', format);
539
540
  }
540
541
 
541
- (tc as unknown as { _argumentsString: string })._argumentsString += chunk;
542
+ const accumulated = previous + chunk;
543
+ streamingArgumentBuffers.set(tc, accumulated);
542
544
 
543
545
  try {
544
- const argsStr = (tc as unknown as { _argumentsString: string })
545
- ._argumentsString;
546
- if (argsStr.trim()) {
546
+ if (accumulated.trim()) {
547
547
  tc.parameters = doubleEscapeProcessToolParameters(
548
- argsStr,
548
+ accumulated,
549
549
  tc.name || 'unknown',
550
550
  format,
551
551
  );
package/src/index.ts CHANGED
@@ -179,6 +179,7 @@ export {
179
179
  type ImageTokenEstimateInput,
180
180
  estimateImageTokens,
181
181
  estimateNonTextPartTokens,
182
+ isGpt52OrNewer,
182
183
  } from './utils/imageTokenEstimation.js';
183
184
  export {
184
185
  DEFAULT_DIFF_OPTIONS,
@@ -19,8 +19,6 @@ export interface SkillActivationResult {
19
19
  description?: string;
20
20
  /** Skill source location. */
21
21
  location?: string;
22
- /** Folder structure for skill resources. */
23
- folderStructure?: string;
24
22
  /** Directory added to workspace context for skill resources. */
25
23
  resourceDirectory?: string;
26
24
  /** Error message if activation failed. */
@@ -70,9 +68,4 @@ export interface ISkillService {
70
68
  * Get one skill by name.
71
69
  */
72
70
  getSkill(name: string): SkillInfo | null;
73
-
74
- /**
75
- * Get the folder structure for a skill's resource directory.
76
- */
77
- getFolderStructure(skillName: string): Promise<string>;
78
71
  }