@silmaril-security/sdk 0.9.0 → 0.10.0

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