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