@silmaril-security/sdk 0.8.2 → 0.9.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.
@@ -0,0 +1,647 @@
1
+ // src/exceptions.ts
2
+ var MAX_PROMPT_DISPLAY_LEN = 100;
3
+ var FirewallBlockedException = class _FirewallBlockedException extends Error {
4
+ score;
5
+ threshold;
6
+ promptText;
7
+ runId;
8
+ hook;
9
+ toolName;
10
+ toolCallId;
11
+ result;
12
+ constructor(params) {
13
+ super(_FirewallBlockedException.formatMessage(params));
14
+ this.name = "FirewallBlockedException";
15
+ this.score = params.score;
16
+ this.threshold = params.threshold;
17
+ this.promptText = params.promptText;
18
+ this.runId = params.runId;
19
+ this.hook = params.hook;
20
+ this.toolName = params.toolName;
21
+ this.toolCallId = params.toolCallId;
22
+ this.result = params.result;
23
+ Object.setPrototypeOf(this, _FirewallBlockedException.prototype);
24
+ }
25
+ static formatMessage(params) {
26
+ const truncated = params.promptText.length > MAX_PROMPT_DISPLAY_LEN ? `${params.promptText.slice(0, MAX_PROMPT_DISPLAY_LEN)}...` : params.promptText;
27
+ if (params.result?.prediction !== "MALICIOUS" && params.result?.governance?.action === "block") {
28
+ return `Request blocked by Silmaril Firewall governance policy: '${truncated}'`;
29
+ }
30
+ return `Request blocked by Silmaril Firewall (score=${params.score.toFixed(4)}, threshold=${params.threshold.toFixed(4)}): '${truncated}'`;
31
+ }
32
+ };
33
+
34
+ // src/hooks.ts
35
+ var HookLabel = {
36
+ USER_INPUT: "user_input",
37
+ SYSTEM_PROMPT: "system_prompt",
38
+ TOOL_CALL: "tool_call",
39
+ TOOL_RESPONSE: "tool_response",
40
+ LLM_OUTPUT: "llm_output",
41
+ UNKNOWN: "unknown"
42
+ };
43
+ var FirewallHook = {
44
+ LLM_START: "on_llm_start",
45
+ CHAT_MODEL_START: "on_chat_model_start",
46
+ TOOL_START: "on_tool_start",
47
+ RETRIEVER_START: "on_retriever_start",
48
+ LLM_END: "on_llm_end",
49
+ TOOL_END: "on_tool_end",
50
+ RETRIEVER_END: "on_retriever_end"
51
+ };
52
+ var DEFAULT_HOOKS = /* @__PURE__ */ new Set([
53
+ FirewallHook.LLM_START,
54
+ FirewallHook.CHAT_MODEL_START,
55
+ FirewallHook.TOOL_START,
56
+ FirewallHook.TOOL_END
57
+ ]);
58
+ var INPUT_HOOKS = /* @__PURE__ */ new Set([
59
+ FirewallHook.LLM_START,
60
+ FirewallHook.CHAT_MODEL_START,
61
+ FirewallHook.TOOL_START,
62
+ FirewallHook.RETRIEVER_START
63
+ ]);
64
+ var OUTPUT_HOOKS = /* @__PURE__ */ new Set([
65
+ FirewallHook.LLM_END,
66
+ FirewallHook.TOOL_END,
67
+ FirewallHook.RETRIEVER_END
68
+ ]);
69
+ var ALL_HOOKS = /* @__PURE__ */ new Set([
70
+ ...INPUT_HOOKS,
71
+ ...OUTPUT_HOOKS
72
+ ]);
73
+ var FIREWALL_HOOK_TO_LABEL = {
74
+ [FirewallHook.CHAT_MODEL_START]: HookLabel.USER_INPUT,
75
+ [FirewallHook.LLM_START]: HookLabel.USER_INPUT,
76
+ [FirewallHook.TOOL_START]: HookLabel.TOOL_CALL,
77
+ [FirewallHook.TOOL_END]: HookLabel.TOOL_RESPONSE,
78
+ [FirewallHook.RETRIEVER_START]: HookLabel.TOOL_CALL,
79
+ [FirewallHook.RETRIEVER_END]: HookLabel.TOOL_RESPONSE,
80
+ [FirewallHook.LLM_END]: HookLabel.LLM_OUTPUT
81
+ };
82
+ var FIREWALL_HOOK_VALUES = new Set(Object.values(FirewallHook));
83
+
84
+ // src/modes.ts
85
+ function validateMode(value) {
86
+ if (value === void 0 || value === "shadow" || value === "warn" || value === "block") {
87
+ return value;
88
+ }
89
+ throw new Error("Firewall: mode must be shadow, warn, or block");
90
+ }
91
+
92
+ // src/adapters/vercel-v4.ts
93
+ var DEFAULT_V4_MAX_BUFFERED_BYTES = 1048576;
94
+ var DEFAULT_V4_MAX_BUFFERED_PARTS = 1e4;
95
+ var VercelV4BufferLimitError = class extends Error {
96
+ constructor(limitName, limit) {
97
+ super(`Silmaril Vercel v4 middleware exceeded its ${limitName} buffer limit (${limit})`);
98
+ this.name = "VercelV4BufferLimitError";
99
+ }
100
+ };
101
+ function isRecord(value) {
102
+ return typeof value === "object" && value !== null && !Array.isArray(value);
103
+ }
104
+ function stringifyValue(value) {
105
+ if (value === null || value === void 0) return "";
106
+ if (typeof value === "string") return value;
107
+ try {
108
+ return JSON.stringify(value);
109
+ } catch {
110
+ return String(value);
111
+ }
112
+ }
113
+ function stringifyToolResult(output) {
114
+ if (!isRecord(output) || typeof output.type !== "string") {
115
+ return stringifyValue(output);
116
+ }
117
+ if ((output.type === "text" || output.type === "error-text") && typeof output.value === "string") {
118
+ return output.value;
119
+ }
120
+ if ((output.type === "json" || output.type === "error-json") && output.value !== void 0) {
121
+ return stringifyValue(output.value);
122
+ }
123
+ if (output.type === "content" && Array.isArray(output.value)) {
124
+ return output.value.map(
125
+ (part) => isRecord(part) && part.type === "text" && typeof part.text === "string" ? part.text : ""
126
+ ).filter(Boolean).join(" ");
127
+ }
128
+ if (output.type === "execution-denied" && typeof output.reason === "string") {
129
+ return output.reason;
130
+ }
131
+ return "";
132
+ }
133
+ function promptText(message) {
134
+ if (typeof message.content === "string") return message.content;
135
+ return message.content.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("");
136
+ }
137
+ function promptToolResults(message) {
138
+ if (typeof message.content === "string") return [];
139
+ const results = [];
140
+ for (const part of message.content) {
141
+ if (part.type !== "tool-result" || typeof part.toolName !== "string" || typeof part.toolCallId !== "string") {
142
+ continue;
143
+ }
144
+ const text = stringifyToolResult(part.output);
145
+ if (text.trim()) {
146
+ results.push({
147
+ text,
148
+ toolName: part.toolName,
149
+ toolCallId: part.toolCallId
150
+ });
151
+ }
152
+ }
153
+ return results;
154
+ }
155
+ function validatePositiveLimit(value, fallback, name) {
156
+ const resolved = value ?? fallback;
157
+ if (!Number.isSafeInteger(resolved) || resolved < 1) {
158
+ throw new Error(`${name} must be a positive safe integer`);
159
+ }
160
+ return resolved;
161
+ }
162
+ function encodedLength(value) {
163
+ return new TextEncoder().encode(value).byteLength;
164
+ }
165
+ async function inputFingerprint(value) {
166
+ const digest = await globalThis.crypto.subtle.digest(
167
+ "SHA-256",
168
+ new TextEncoder().encode(value)
169
+ );
170
+ return Array.from(
171
+ new Uint8Array(digest),
172
+ (byte) => byte.toString(16).padStart(2, "0")
173
+ ).join("");
174
+ }
175
+ function finalInputBytes(segment) {
176
+ const input = segment.deltas.join("");
177
+ return segment.inputEncoding === "text" ? JSON.stringify(input) : input;
178
+ }
179
+ function estimatedPartSize(part, maximum) {
180
+ try {
181
+ const serialized = JSON.stringify(part);
182
+ if (serialized === void 0) return 64;
183
+ return Math.min(encodedLength(serialized), maximum + 1);
184
+ } catch {
185
+ return maximum + 1;
186
+ }
187
+ }
188
+ function createMiddlewareV4(firewall, options = {}) {
189
+ const scanInput = options.scanInput ?? true;
190
+ const scanOutput = options.scanOutput ?? false;
191
+ const scanToolCalls = options.scanToolCalls ?? false;
192
+ const requestedMode = validateMode(options.mode) ?? (options.shadowMode === void 0 ? firewall.mode : options.shadowMode ? "shadow" : "block");
193
+ const possibleBlock = requestedMode === void 0 || requestedMode === "block";
194
+ const maxBufferedBytes = validatePositiveLimit(
195
+ options.maxBufferedBytes,
196
+ DEFAULT_V4_MAX_BUFFERED_BYTES,
197
+ "maxBufferedBytes"
198
+ );
199
+ const maxBufferedParts = validatePositiveLimit(
200
+ options.maxBufferedParts,
201
+ DEFAULT_V4_MAX_BUFFERED_PARTS,
202
+ "maxBufferedParts"
203
+ );
204
+ const classifyOrBlock = async (text, hook, context = {}, signal) => {
205
+ if (!text.trim()) return;
206
+ const result = await firewall.classify(text, {
207
+ hook,
208
+ ...context.toolName === void 0 ? {} : { toolName: context.toolName },
209
+ ...requestedMode === void 0 ? {} : { mode: requestedMode },
210
+ ...signal === void 0 ? {} : { signal }
211
+ });
212
+ const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
213
+ const effectiveMode = requestedMode ?? result.mode ?? "block";
214
+ const event = {
215
+ hook,
216
+ ...context.toolName === void 0 ? {} : { toolName: context.toolName },
217
+ ...context.toolCallId === void 0 ? {} : { toolCallId: context.toolCallId },
218
+ text,
219
+ result,
220
+ blocked,
221
+ mode: effectiveMode,
222
+ shadowMode: effectiveMode === "shadow"
223
+ };
224
+ options.onClassify?.(event);
225
+ if (!blocked || effectiveMode !== "block") return;
226
+ const error = new FirewallBlockedException({
227
+ score: result.score,
228
+ threshold: result.threshold,
229
+ promptText: text,
230
+ hook,
231
+ ...context.toolName === void 0 ? {} : { toolName: context.toolName },
232
+ ...context.toolCallId === void 0 ? {} : { toolCallId: context.toolCallId },
233
+ result
234
+ });
235
+ options.onBlocked?.(error);
236
+ throw error;
237
+ };
238
+ const scanPrompt = async (prompt, signal) => {
239
+ const toolTurnResults = [];
240
+ for (let index = prompt.length - 1; index >= 0; index--) {
241
+ const message = prompt[index];
242
+ const results = promptToolResults(message);
243
+ toolTurnResults.unshift(...results);
244
+ if (message.role.toLowerCase() !== "tool") break;
245
+ }
246
+ if (toolTurnResults.length > 0) {
247
+ for (const result of toolTurnResults) {
248
+ await classifyOrBlock(result.text, HookLabel.TOOL_RESPONSE, result, signal);
249
+ }
250
+ return;
251
+ }
252
+ for (let index = prompt.length - 1; index >= 0; index--) {
253
+ const message = prompt[index];
254
+ if (message.role.toLowerCase() !== "user") continue;
255
+ const text = promptText(message);
256
+ if (text.trim()) {
257
+ await classifyOrBlock(text, HookLabel.USER_INPUT, {}, signal);
258
+ }
259
+ return;
260
+ }
261
+ };
262
+ const scanGenerateResult = async (result, signal) => {
263
+ let text = "";
264
+ const flushText = async () => {
265
+ if (scanOutput && text) {
266
+ await classifyOrBlock(text, HookLabel.LLM_OUTPUT, {}, signal);
267
+ }
268
+ text = "";
269
+ };
270
+ for (const part of result.content) {
271
+ if (part.type === "text" && typeof part.text === "string") {
272
+ text += part.text;
273
+ continue;
274
+ }
275
+ if (scanToolCalls && part.type === "tool-call" && typeof part.toolName === "string" && typeof part.toolCallId === "string") {
276
+ await flushText();
277
+ const input = typeof part.input === "string" ? part.input : stringifyValue(part.input);
278
+ await classifyOrBlock(input, HookLabel.TOOL_CALL, {
279
+ toolName: part.toolName,
280
+ toolCallId: part.toolCallId
281
+ }, signal);
282
+ }
283
+ }
284
+ await flushText();
285
+ };
286
+ return {
287
+ specificationVersion: "v4",
288
+ async wrapGenerate({
289
+ params,
290
+ doGenerate
291
+ }) {
292
+ if (scanInput) await scanPrompt(params.prompt, params.abortSignal);
293
+ const result = await doGenerate();
294
+ await scanGenerateResult(result, params.abortSignal);
295
+ return result;
296
+ },
297
+ async wrapStream({
298
+ params,
299
+ doStream
300
+ }) {
301
+ if (scanInput) await scanPrompt(params.prompt, params.abortSignal);
302
+ const result = await doStream();
303
+ if (!scanOutput && !scanToolCalls) return result;
304
+ const textStreams = /* @__PURE__ */ new Map();
305
+ const toolStreams = /* @__PURE__ */ new Map();
306
+ const completedTextIds = /* @__PURE__ */ new Set();
307
+ const completedToolIds = /* @__PURE__ */ new Map();
308
+ const queue = [];
309
+ let queueHead = 0;
310
+ let queuedBytes = 0;
311
+ let activeBytes = 0;
312
+ let distinctIds = 0;
313
+ let nextSegmentOrder = 0;
314
+ const registerId = () => {
315
+ distinctIds++;
316
+ if (distinctIds > maxBufferedParts) {
317
+ throw new VercelV4BufferLimitError("parts", maxBufferedParts);
318
+ }
319
+ };
320
+ const checkActiveBytes = (additional) => {
321
+ activeBytes += additional;
322
+ if (activeBytes > maxBufferedBytes) {
323
+ throw new VercelV4BufferLimitError("bytes", maxBufferedBytes);
324
+ }
325
+ };
326
+ const hold = (part, status) => {
327
+ const size = estimatedPartSize(part, maxBufferedBytes);
328
+ if (queue.length - queueHead + 1 > maxBufferedParts) {
329
+ throw new VercelV4BufferLimitError("parts", maxBufferedParts);
330
+ }
331
+ if (queuedBytes + size > maxBufferedBytes) {
332
+ throw new VercelV4BufferLimitError("bytes", maxBufferedBytes);
333
+ }
334
+ const entry = { part, size, status };
335
+ queue.push(entry);
336
+ queuedBytes += size;
337
+ return entry;
338
+ };
339
+ const emitOrHold = (part, pending, controller) => {
340
+ if (!possibleBlock) {
341
+ controller.enqueue(part);
342
+ return void 0;
343
+ }
344
+ return hold(part, pending ? "pending" : "approved");
345
+ };
346
+ const drain = (controller) => {
347
+ try {
348
+ while (queueHead < queue.length) {
349
+ const entry = queue[queueHead];
350
+ if (entry.status === "pending") break;
351
+ queueHead++;
352
+ queuedBytes -= entry.size;
353
+ if (entry.replacement !== void 0) {
354
+ controller.enqueue(entry.replacement);
355
+ } else if (entry.status === "approved") {
356
+ controller.enqueue(entry.part);
357
+ }
358
+ }
359
+ } finally {
360
+ if (queueHead > 0) queue.splice(0, queueHead);
361
+ queueHead = 0;
362
+ }
363
+ };
364
+ const resolveSegment = (segment, error) => {
365
+ activeBytes -= segment.byteLength;
366
+ if (!possibleBlock) return;
367
+ for (const entry of segment.entries) {
368
+ entry.status = error === void 0 ? "approved" : "dropped";
369
+ }
370
+ if (error !== void 0 && segment.entries.length > 0) {
371
+ segment.entries[0].replacement = { type: "error", error };
372
+ }
373
+ };
374
+ const classifyTextSegment = async (segment) => {
375
+ try {
376
+ await classifyOrBlock(
377
+ segment.deltas.join(""),
378
+ HookLabel.LLM_OUTPUT,
379
+ {},
380
+ params.abortSignal
381
+ );
382
+ resolveSegment(segment, void 0);
383
+ return false;
384
+ } catch (error) {
385
+ if (!(error instanceof FirewallBlockedException)) throw error;
386
+ resolveSegment(segment, error);
387
+ return true;
388
+ }
389
+ };
390
+ const classifyToolSegment = async (segment) => {
391
+ const input = segment.deltas.join("");
392
+ const fingerprint = await inputFingerprint(finalInputBytes(segment));
393
+ try {
394
+ await classifyOrBlock(
395
+ input,
396
+ HookLabel.TOOL_CALL,
397
+ { toolName: segment.toolName, toolCallId: segment.id },
398
+ params.abortSignal
399
+ );
400
+ resolveSegment(segment, void 0);
401
+ return { blocked: false, fingerprint };
402
+ } catch (error) {
403
+ if (!(error instanceof FirewallBlockedException)) throw error;
404
+ resolveSegment(segment, error);
405
+ return { blocked: true, fingerprint };
406
+ }
407
+ };
408
+ const finalizeActive = async () => {
409
+ const active = [
410
+ ...Array.from(textStreams, ([id, segment]) => ({
411
+ kind: "text",
412
+ id,
413
+ segment
414
+ })),
415
+ ...Array.from(toolStreams, ([id, segment]) => ({
416
+ kind: "tool",
417
+ id,
418
+ segment
419
+ }))
420
+ ].sort((left, right) => left.segment.order - right.segment.order);
421
+ for (const item of active) {
422
+ if (item.kind === "text") {
423
+ await classifyTextSegment(item.segment);
424
+ textStreams.delete(item.id);
425
+ completedTextIds.add(item.id);
426
+ } else {
427
+ const verdict = await classifyToolSegment(item.segment);
428
+ toolStreams.delete(item.id);
429
+ completedToolIds.set(item.id, {
430
+ blocked: verdict.blocked,
431
+ toolName: item.segment.toolName,
432
+ inputEncoding: item.segment.inputEncoding,
433
+ inputFingerprint: verdict.fingerprint,
434
+ finalSeen: false
435
+ });
436
+ }
437
+ }
438
+ };
439
+ const transformed = result.stream.pipeThrough(
440
+ new TransformStream({
441
+ async transform(part, controller) {
442
+ params.abortSignal?.throwIfAborted();
443
+ if (part.type === "finish") {
444
+ await finalizeActive();
445
+ emitOrHold(part, false, controller);
446
+ drain(controller);
447
+ return;
448
+ }
449
+ if (scanOutput && part.type === "text-start") {
450
+ if (typeof part.id !== "string" || textStreams.has(part.id) || completedTextIds.has(part.id)) {
451
+ throw new Error("Invalid AI SDK v4 text-start stream identity");
452
+ }
453
+ registerId();
454
+ const entry = emitOrHold(part, true, controller);
455
+ textStreams.set(part.id, {
456
+ id: part.id,
457
+ order: nextSegmentOrder++,
458
+ entries: entry === void 0 ? [] : [entry],
459
+ deltas: [],
460
+ byteLength: 0
461
+ });
462
+ drain(controller);
463
+ return;
464
+ }
465
+ if (scanOutput && part.type === "text-delta") {
466
+ if (typeof part.id !== "string" || typeof part.delta !== "string") {
467
+ throw new Error("Invalid AI SDK v4 text-delta stream part");
468
+ }
469
+ const segment = textStreams.get(part.id);
470
+ if (segment === void 0) {
471
+ throw new Error("AI SDK v4 text-delta has no matching text-start");
472
+ }
473
+ const bytes = encodedLength(part.delta);
474
+ checkActiveBytes(bytes);
475
+ segment.byteLength += bytes;
476
+ segment.deltas.push(part.delta);
477
+ const entry = emitOrHold(part, true, controller);
478
+ if (entry !== void 0) segment.entries.push(entry);
479
+ drain(controller);
480
+ return;
481
+ }
482
+ if (scanOutput && part.type === "text-end") {
483
+ if (typeof part.id !== "string") {
484
+ throw new Error("Invalid AI SDK v4 text-end stream identity");
485
+ }
486
+ const segment = textStreams.get(part.id);
487
+ if (segment === void 0) {
488
+ throw new Error("AI SDK v4 text-end has no matching text-start");
489
+ }
490
+ const entry = emitOrHold(part, true, controller);
491
+ if (entry !== void 0) segment.entries.push(entry);
492
+ textStreams.delete(part.id);
493
+ const blocked = await classifyTextSegment(segment);
494
+ completedTextIds.add(part.id);
495
+ void blocked;
496
+ drain(controller);
497
+ return;
498
+ }
499
+ if (scanToolCalls && part.type === "tool-input-start") {
500
+ if (typeof part.id !== "string" || typeof part.toolName !== "string" || toolStreams.has(part.id) || completedToolIds.has(part.id)) {
501
+ throw new Error("Invalid AI SDK v4 tool-input-start stream identity");
502
+ }
503
+ registerId();
504
+ const entry = emitOrHold(part, true, controller);
505
+ toolStreams.set(part.id, {
506
+ id: part.id,
507
+ order: nextSegmentOrder++,
508
+ toolName: part.toolName,
509
+ inputEncoding: part.inputEncoding ?? "json",
510
+ entries: entry === void 0 ? [] : [entry],
511
+ deltas: [],
512
+ byteLength: 0
513
+ });
514
+ drain(controller);
515
+ return;
516
+ }
517
+ if (scanToolCalls && part.type === "tool-input-delta") {
518
+ if (typeof part.id !== "string" || typeof part.delta !== "string") {
519
+ throw new Error("Invalid AI SDK v4 tool-input-delta stream part");
520
+ }
521
+ const segment = toolStreams.get(part.id);
522
+ if (segment === void 0) {
523
+ throw new Error("AI SDK v4 tool-input-delta has no matching tool-input-start");
524
+ }
525
+ const bytes = encodedLength(part.delta);
526
+ checkActiveBytes(bytes);
527
+ segment.byteLength += bytes;
528
+ segment.deltas.push(part.delta);
529
+ const entry = emitOrHold(part, true, controller);
530
+ if (entry !== void 0) segment.entries.push(entry);
531
+ drain(controller);
532
+ return;
533
+ }
534
+ if (scanToolCalls && part.type === "tool-input-end") {
535
+ if (typeof part.id !== "string") {
536
+ throw new Error("Invalid AI SDK v4 tool-input-end stream identity");
537
+ }
538
+ const segment = toolStreams.get(part.id);
539
+ if (segment === void 0) {
540
+ throw new Error("AI SDK v4 tool-input-end has no matching tool-input-start");
541
+ }
542
+ const entry = emitOrHold(part, true, controller);
543
+ if (entry !== void 0) segment.entries.push(entry);
544
+ toolStreams.delete(part.id);
545
+ const verdict = await classifyToolSegment(segment);
546
+ completedToolIds.set(part.id, {
547
+ blocked: verdict.blocked,
548
+ toolName: segment.toolName,
549
+ inputEncoding: segment.inputEncoding,
550
+ inputFingerprint: verdict.fingerprint,
551
+ finalSeen: false
552
+ });
553
+ drain(controller);
554
+ return;
555
+ }
556
+ if (scanToolCalls && part.type === "tool-call") {
557
+ if (typeof part.toolCallId !== "string" || typeof part.toolName !== "string" || typeof part.input !== "string") {
558
+ throw new Error("Invalid AI SDK v4 tool-call stream part");
559
+ }
560
+ if (toolStreams.has(part.toolCallId)) {
561
+ throw new Error("AI SDK v4 tool-call arrived before tool-input-end");
562
+ }
563
+ const completed = completedToolIds.get(part.toolCallId);
564
+ if (completed !== void 0) {
565
+ if (completed.toolName !== part.toolName) {
566
+ throw new Error("AI SDK v4 tool-call name does not match its streamed input ID");
567
+ }
568
+ if (completed.finalSeen) {
569
+ throw new Error("AI SDK v4 tool-call repeated a completed streamed input ID");
570
+ }
571
+ completed.finalSeen = true;
572
+ if (completed.blocked) {
573
+ drain(controller);
574
+ return;
575
+ }
576
+ const actualFingerprint = await inputFingerprint(part.input);
577
+ if (actualFingerprint === completed.inputFingerprint) {
578
+ emitOrHold(part, false, controller);
579
+ drain(controller);
580
+ return;
581
+ }
582
+ const bytes2 = encodedLength(part.input);
583
+ checkActiveBytes(bytes2);
584
+ const entry2 = emitOrHold(part, true, controller);
585
+ const changedSegment = {
586
+ id: part.toolCallId,
587
+ order: nextSegmentOrder++,
588
+ toolName: part.toolName,
589
+ inputEncoding: "json",
590
+ entries: entry2 === void 0 ? [] : [entry2],
591
+ deltas: [part.input],
592
+ byteLength: bytes2
593
+ };
594
+ const changedVerdict = await classifyToolSegment(changedSegment);
595
+ completed.blocked = changedVerdict.blocked;
596
+ completed.inputFingerprint = changedVerdict.fingerprint;
597
+ drain(controller);
598
+ return;
599
+ }
600
+ registerId();
601
+ const bytes = encodedLength(part.input);
602
+ checkActiveBytes(bytes);
603
+ const entry = emitOrHold(part, true, controller);
604
+ const segment = {
605
+ id: part.toolCallId,
606
+ order: nextSegmentOrder++,
607
+ toolName: part.toolName,
608
+ inputEncoding: "json",
609
+ entries: entry === void 0 ? [] : [entry],
610
+ deltas: [part.input],
611
+ byteLength: bytes
612
+ };
613
+ const verdict = await classifyToolSegment(segment);
614
+ completedToolIds.set(part.toolCallId, {
615
+ blocked: verdict.blocked,
616
+ toolName: part.toolName,
617
+ inputEncoding: segment.inputEncoding,
618
+ inputFingerprint: verdict.fingerprint,
619
+ finalSeen: true
620
+ });
621
+ drain(controller);
622
+ return;
623
+ }
624
+ emitOrHold(part, false, controller);
625
+ drain(controller);
626
+ },
627
+ async flush(controller) {
628
+ params.abortSignal?.throwIfAborted();
629
+ await finalizeActive();
630
+ drain(controller);
631
+ if (queueHead !== queue.length) {
632
+ throw new Error("Silmaril Vercel v4 middleware retained unresolved stream parts");
633
+ }
634
+ }
635
+ })
636
+ );
637
+ return Object.assign({}, result, { stream: transformed });
638
+ }
639
+ };
640
+ }
641
+ export {
642
+ DEFAULT_V4_MAX_BUFFERED_BYTES,
643
+ DEFAULT_V4_MAX_BUFFERED_PARTS,
644
+ VercelV4BufferLimitError,
645
+ createMiddlewareV4
646
+ };
647
+ //# sourceMappingURL=vercel-v4.js.map