@directive-run/ai 1.19.0 → 1.19.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.
Files changed (60) hide show
  1. package/dist/anthropic.d.cts +1 -1
  2. package/dist/anthropic.d.ts +1 -1
  3. package/dist/chunk-2C3R77ZW.cjs +16 -0
  4. package/dist/chunk-2C3R77ZW.cjs.map +1 -0
  5. package/dist/chunk-ARYO7BLK.js +16 -0
  6. package/dist/chunk-ARYO7BLK.js.map +1 -0
  7. package/dist/chunk-MPAX6C5V.cjs +4 -0
  8. package/dist/chunk-MPAX6C5V.cjs.map +1 -0
  9. package/dist/chunk-WERHNNUD.js +4 -0
  10. package/dist/chunk-WERHNNUD.js.map +1 -0
  11. package/dist/{debug-timeline-Dn1lC_gK.d.cts → debug-timeline-DpnRMnLU.d.cts} +1 -1
  12. package/dist/{debug-timeline-BGcPa0JO.d.ts → debug-timeline-L13P-U2I.d.ts} +1 -1
  13. package/dist/devtools.d.cts +5 -5
  14. package/dist/devtools.d.ts +5 -5
  15. package/dist/evals.d.cts +2 -2
  16. package/dist/evals.d.ts +2 -2
  17. package/dist/gemini.d.cts +1 -1
  18. package/dist/gemini.d.ts +1 -1
  19. package/dist/guardrails.cjs +1 -1
  20. package/dist/guardrails.cjs.map +1 -1
  21. package/dist/guardrails.d.cts +616 -4
  22. package/dist/guardrails.d.ts +616 -4
  23. package/dist/guardrails.js +1 -1
  24. package/dist/guardrails.js.map +1 -1
  25. package/dist/{health-monitor-Cq5sDvid.d.cts → health-monitor-C6xoXrQz.d.cts} +1 -1
  26. package/dist/{health-monitor-DtwmIJkb.d.ts → health-monitor-qL9RNMH3.d.ts} +1 -1
  27. package/dist/index.cjs +11 -11
  28. package/dist/index.d.cts +10 -10
  29. package/dist/index.d.ts +10 -10
  30. package/dist/index.js +11 -11
  31. package/dist/index.js.map +1 -1
  32. package/dist/multi-agent.d.cts +6 -6
  33. package/dist/multi-agent.d.ts +6 -6
  34. package/dist/ollama.d.cts +1 -1
  35. package/dist/ollama.d.ts +1 -1
  36. package/dist/openai.d.cts +2 -2
  37. package/dist/openai.d.ts +2 -2
  38. package/dist/{orchestrator-types-s0766dDB.d.cts → orchestrator-types-C-sgbBQX.d.cts} +20 -3
  39. package/dist/{orchestrator-types-C5D5JZUj.d.ts → orchestrator-types-CX1PqpKR.d.ts} +20 -3
  40. package/dist/predicate.d.cts +1 -1
  41. package/dist/predicate.d.ts +1 -1
  42. package/dist/{semantic-cache-Ba0-jEwb.d.cts → semantic-cache-DM7ev7NQ.d.cts} +1 -1
  43. package/dist/{semantic-cache-Ba0-jEwb.d.ts → semantic-cache-DM7ev7NQ.d.ts} +1 -1
  44. package/dist/testing.cjs +1 -1
  45. package/dist/testing.d.cts +4 -4
  46. package/dist/testing.d.ts +4 -4
  47. package/dist/testing.js +1 -1
  48. package/dist/{types-CUp1N0uU.d.cts → types-DJ09LjZX.d.cts} +1 -1
  49. package/dist/{types-CUp1N0uU.d.ts → types-DJ09LjZX.d.ts} +1 -1
  50. package/package.json +2 -2
  51. package/dist/ann-index-27QV9tPC.d.ts +0 -616
  52. package/dist/ann-index-HoZFIUA-.d.cts +0 -616
  53. package/dist/chunk-2PG26JZU.cjs +0 -16
  54. package/dist/chunk-2PG26JZU.cjs.map +0 -1
  55. package/dist/chunk-BFSRYCOS.js +0 -4
  56. package/dist/chunk-BFSRYCOS.js.map +0 -1
  57. package/dist/chunk-CAA6Q4YY.cjs +0 -4
  58. package/dist/chunk-CAA6Q4YY.cjs.map +0 -1
  59. package/dist/chunk-MIHH5GPT.js +0 -16
  60. package/dist/chunk-MIHH5GPT.js.map +0 -1
@@ -1,616 +0,0 @@
1
- import { m as GuardrailFn, I as InputGuardrailData, O as OutputGuardrailData, q as SchemaValidator, T as ToolCallGuardrailData } from './types-CUp1N0uU.js';
2
- import { c as Embedding } from './semantic-cache-Ba0-jEwb.js';
3
-
4
- /**
5
- * Built-in guardrails for AI adapter — PII, moderation, rate limiting, tool allowlists, schema validation.
6
- */
7
-
8
- /**
9
- * Create a PII detection guardrail that scans input text for personally identifiable
10
- * information. Blocks input when PII is detected, or optionally redacts matches and
11
- * passes the sanitized text through.
12
- *
13
- * @param options - Configuration for PII detection: `patterns` sets the RegExp list (defaults to SSN, credit card, email), `redact` replaces matches instead of blocking, `redactReplacement` sets the replacement string (defaults to `"[REDACTED]"`).
14
- * @returns An input guardrail that blocks or redacts PII in user input.
15
- *
16
- * @example
17
- * ```typescript
18
- * const piiGuardrail = createPIIGuardrail({
19
- * patterns: [
20
- * /\b\d{3}-\d{2}-\d{4}\b/, // SSN
21
- * /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i, // Email
22
- * ],
23
- * redact: true,
24
- * });
25
- * ```
26
- *
27
- * @public
28
- */
29
- declare function createPIIGuardrail(options: {
30
- patterns?: RegExp[];
31
- redact?: boolean;
32
- redactReplacement?: string;
33
- }): GuardrailFn<InputGuardrailData>;
34
- /**
35
- * Create a content moderation guardrail that delegates to a user-supplied check function.
36
- * Works on both input and output data — the guardrail extracts the text content
37
- * automatically and passes it to {@link options.checkFn}.
38
- *
39
- * @param options - Configuration for content moderation: `checkFn` returns `true` when content should be flagged (supports async), `message` sets the rejection reason (defaults to `"Content flagged by moderation"`).
40
- * @returns A guardrail that blocks content flagged by the check function.
41
- *
42
- * @example
43
- * ```typescript
44
- * const moderationGuardrail = createModerationGuardrail({
45
- * checkFn: async (text) => {
46
- * const result = await openai.moderations.create({ input: text });
47
- * return result.results[0].flagged;
48
- * },
49
- * });
50
- * ```
51
- *
52
- * @public
53
- */
54
- declare function createModerationGuardrail(options: {
55
- checkFn: (text: string) => boolean | Promise<boolean>;
56
- message?: string;
57
- }): GuardrailFn<InputGuardrailData | OutputGuardrailData>;
58
- /** Rate limiter with reset capability for testing */
59
- interface RateLimitGuardrail extends GuardrailFn<InputGuardrailData> {
60
- reset(): void;
61
- }
62
- /**
63
- * Create a rate limit guardrail that tracks token and request counts over a sliding
64
- * one-minute window. Returns a {@link RateLimitGuardrail} — a guardrail function with
65
- * an additional `reset()` method for testing.
66
- *
67
- * @param options - Configuration for rate limiting: `maxTokensPerMinute` caps tokens in the sliding window (defaults to `100000`), `maxRequestsPerMinute` caps requests (defaults to `60`).
68
- * @returns A rate limit guardrail with an attached `reset()` method.
69
- *
70
- * @example
71
- * ```typescript
72
- * const rateLimiter = createRateLimitGuardrail({
73
- * maxTokensPerMinute: 50000,
74
- * maxRequestsPerMinute: 30,
75
- * });
76
- * ```
77
- *
78
- * @public
79
- */
80
- declare function createRateLimitGuardrail(options: {
81
- maxTokensPerMinute?: number;
82
- maxRequestsPerMinute?: number;
83
- }): RateLimitGuardrail;
84
- /**
85
- * Create a tool-call guardrail that restricts which tools an agent may invoke.
86
- * Supports allowlist mode, denylist mode, or both — when both are provided, a tool
87
- * must appear in the allowlist and not appear in the denylist.
88
- *
89
- * @param options - Configuration for tool filtering: `allowlist` sets permitted tool names, `denylist` sets blocked tool names, `caseSensitive` controls case matching (defaults to `false`).
90
- * @returns A tool-call guardrail that enforces the allowlist/denylist rules.
91
- *
92
- * @example
93
- * ```typescript
94
- * const toolGuardrail = createToolGuardrail({
95
- * allowlist: ["search", "calculate"],
96
- * denylist: ["delete_account"],
97
- * });
98
- * ```
99
- *
100
- * @public
101
- */
102
- declare function createToolGuardrail(options: {
103
- allowlist?: string[];
104
- denylist?: string[];
105
- /** @default false */
106
- caseSensitive?: boolean;
107
- }): GuardrailFn<ToolCallGuardrailData>;
108
- /**
109
- * Create an output guardrail that validates agent output against a schema using
110
- * a user-supplied {@link SchemaValidator}. Compatible with any validation library
111
- * (Zod, Valibot, ArkType, etc.) via the adapter pattern.
112
- *
113
- * @param options - Configuration for schema validation: `validate` checks the output against the expected schema, `errorPrefix` is prepended to error messages (defaults to `"Output schema validation failed"`).
114
- * @returns An output guardrail that rejects output failing schema validation.
115
- *
116
- * @example
117
- * ```typescript
118
- * import { z } from "zod";
119
- *
120
- * const schemaGuardrail = createOutputSchemaGuardrail({
121
- * validate: (value) => {
122
- * const result = z.object({ answer: z.string() }).safeParse(value);
123
- * return { valid: result.success, errors: result.error?.issues.map(i => i.message) };
124
- * },
125
- * });
126
- * ```
127
- *
128
- * @public
129
- */
130
- declare function createOutputSchemaGuardrail<T = unknown>(options: {
131
- validate: SchemaValidator<T>;
132
- errorPrefix?: string;
133
- }): GuardrailFn<OutputGuardrailData>;
134
- /**
135
- * Create an output guardrail that performs lightweight runtime type checks without
136
- * requiring a schema library. Supports `"string"`, `"number"`, `"boolean"`, `"object"`,
137
- * and `"array"` with optional size and field constraints.
138
- *
139
- * @param options - Configuration for type checking: `type` sets the expected JS type, `requiredFields` lists object keys that must exist, `minLength`/`maxLength` constrain array size, `minStringLength`/`maxStringLength` constrain string length.
140
- * @returns An output guardrail that rejects output not matching the expected type or constraints.
141
- *
142
- * @example
143
- * ```typescript
144
- * const typeGuardrail = createOutputTypeGuardrail({
145
- * type: "object",
146
- * requiredFields: ["id", "name"],
147
- * });
148
- * ```
149
- *
150
- * @public
151
- */
152
- declare function createOutputTypeGuardrail(options: {
153
- type: "string" | "number" | "boolean" | "object" | "array";
154
- requiredFields?: string[];
155
- minLength?: number;
156
- maxLength?: number;
157
- minStringLength?: number;
158
- maxStringLength?: number;
159
- }): GuardrailFn<OutputGuardrailData>;
160
- /**
161
- * Create an output guardrail that enforces maximum length constraints on agent output,
162
- * measured in characters or estimated tokens.
163
- *
164
- * @param options - Configuration for length limits: `maxCharacters` caps character count, `maxTokens` caps estimated token count, `estimateTokens` provides a custom token estimator (defaults to `Math.ceil(text.length / 4)`).
165
- * @returns An output guardrail that rejects output exceeding the configured length limits.
166
- *
167
- * @example
168
- * ```typescript
169
- * const lengthGuardrail = createLengthGuardrail({
170
- * maxCharacters: 5000,
171
- * maxTokens: 1200,
172
- * });
173
- * ```
174
- *
175
- * @public
176
- */
177
- declare function createLengthGuardrail(options: {
178
- /** Maximum characters in output */
179
- maxCharacters?: number;
180
- /** Maximum estimated tokens in output */
181
- maxTokens?: number;
182
- /** Custom token estimator (default: chars / 4) */
183
- estimateTokens?: (text: string) => number;
184
- }): GuardrailFn<OutputGuardrailData>;
185
- /**
186
- * Create an output guardrail that blocks content matching any of the provided patterns.
187
- * String patterns are escaped and compiled to RegExp; RegExp patterns are used as-is.
188
- *
189
- * @remarks
190
- * A warning is logged when `blockedPatterns` is empty, since an empty list means no
191
- * content will ever be filtered.
192
- *
193
- * @param options - Configuration for content filtering: `blockedPatterns` lists strings or RegExps to match against output, `caseSensitive` controls case matching for string patterns (defaults to `false`).
194
- * @returns An output guardrail that rejects output containing any blocked pattern.
195
- *
196
- * @example
197
- * ```typescript
198
- * const contentFilter = createContentFilterGuardrail({
199
- * blockedPatterns: [
200
- * /\bpassword\b/i,
201
- * /\bsecret\b/i,
202
- * 'internal-only',
203
- * ],
204
- * });
205
- * ```
206
- *
207
- * @public
208
- */
209
- declare function createContentFilterGuardrail(options: {
210
- /** Patterns to block — strings or RegExp */
211
- blockedPatterns: Array<string | RegExp>;
212
- /** Case-sensitive matching for string patterns (default: false) */
213
- caseSensitive?: boolean;
214
- }): GuardrailFn<OutputGuardrailData>;
215
-
216
- /**
217
- * Enhanced PII Detection Guardrail
218
- *
219
- * Provides comprehensive PII detection beyond basic regex patterns:
220
- * - Multiple PII types (SSN, credit cards, emails, phones, addresses, names)
221
- * - Pluggable detection backends (regex, custom, or external services)
222
- * - Context-aware detection (reduces false positives)
223
- * - Redaction with reversible or irreversible options
224
- *
225
- * @example
226
- * ```typescript
227
- * import { createEnhancedPIIGuardrail } from '@directive-run/ai';
228
- *
229
- * const guardrail = createEnhancedPIIGuardrail({
230
- * types: ['ssn', 'credit_card', 'email'],
231
- * redact: true,
232
- * detector: 'regex', // or 'custom' with custom detector
233
- * });
234
- * ```
235
- */
236
-
237
- /** Supported PII types */
238
- type PIIType = "ssn" | "credit_card" | "email" | "phone" | "address" | "name" | "date_of_birth" | "passport" | "driver_license" | "ip_address" | "bank_account" | "medical_id" | "national_id";
239
- /** Detected PII instance */
240
- interface DetectedPII {
241
- type: PIIType;
242
- value: string;
243
- position: {
244
- start: number;
245
- end: number;
246
- };
247
- confidence: number;
248
- context?: string;
249
- }
250
- /** PII detection result */
251
- interface PIIDetectionResult {
252
- detected: boolean;
253
- items: DetectedPII[];
254
- typeCounts: Partial<Record<PIIType, number>>;
255
- /** Text with PII redacted (if requested) */
256
- redactedText?: string;
257
- }
258
- /** Custom PII detector interface */
259
- interface PIIDetector {
260
- detect(text: string, types: PIIType[]): Promise<DetectedPII[]>;
261
- name: string;
262
- }
263
- /** Redaction style */
264
- type RedactionStyle =
265
- /** Replace with [REDACTED] */
266
- "placeholder"
267
- /** Replace with type-specific placeholder like [EMAIL] */
268
- | "typed"
269
- /**
270
- * Replace with a fixed-width `****` mask plus the last 4 characters
271
- * (e.g. `****6789`). Does not preserve or reveal the original length.
272
- */
273
- | "masked"
274
- /**
275
- * Replace with a deterministic FNV-1a hash.
276
- *
277
- * **WARNING — this is PSEUDONYMIZATION, not anonymization.** FNV-1a is a
278
- * fast, non-cryptographic 32-bit hash. For low-entropy structured PII (SSNs,
279
- * card numbers, phone numbers) the output is trivially RE-IDENTIFIABLE via
280
- * brute force or a precomputed rainbow table. It MUST NOT be relied on for
281
- * GDPR / HIPAA de-identification. Use it only for referential integrity
282
- * (correlating the same value across audit logs).
283
- */
284
- | "hashed";
285
- /** Redact detected PII from text */
286
- declare function redactPII(text: string, items: DetectedPII[], style?: RedactionStyle): string;
287
- /** Options for enhanced PII guardrail */
288
- interface EnhancedPIIGuardrailOptions {
289
- /** PII types to detect (default: all) */
290
- types?: PIIType[];
291
- /** Detection backend (default: 'regex') */
292
- detector?: "regex" | PIIDetector;
293
- /** Redact instead of blocking */
294
- redact?: boolean;
295
- /** Redaction style (default: 'typed') */
296
- redactionStyle?: RedactionStyle;
297
- /** Minimum confidence to flag (0-1, default: 0.7) */
298
- minConfidence?: number;
299
- /** Callback when PII is detected */
300
- onDetected?: (items: DetectedPII[]) => void;
301
- /** Allow specific values (whitelist) */
302
- allowlist?: string[];
303
- /** Block only if count exceeds threshold */
304
- minItemsToBlock?: number;
305
- /** Timeout for custom detector in milliseconds (default: 5000) */
306
- detectorTimeout?: number;
307
- }
308
- /**
309
- * Create an enhanced PII detection guardrail.
310
- *
311
- * @example
312
- * ```typescript
313
- * // Basic usage
314
- * const guardrail = createEnhancedPIIGuardrail();
315
- *
316
- * // Redact instead of blocking
317
- * const redactGuardrail = createEnhancedPIIGuardrail({
318
- * redact: true,
319
- * redactionStyle: 'masked',
320
- * });
321
- *
322
- * // Custom detection with external service
323
- * const customGuardrail = createEnhancedPIIGuardrail({
324
- * detector: myPresidioDetector,
325
- * types: ['ssn', 'credit_card', 'medical_id'],
326
- * });
327
- * ```
328
- */
329
- declare function createEnhancedPIIGuardrail(options?: EnhancedPIIGuardrailOptions): GuardrailFn<InputGuardrailData>;
330
- /**
331
- * Create an output PII guardrail (for checking agent responses).
332
- *
333
- * @example
334
- * ```typescript
335
- * const outputGuardrail = createOutputPIIGuardrail({
336
- * types: ['ssn', 'credit_card'],
337
- * redact: true,
338
- * });
339
- * ```
340
- */
341
- declare function createOutputPIIGuardrail(options?: EnhancedPIIGuardrailOptions): GuardrailFn<OutputGuardrailData>;
342
- /**
343
- * Detect PII in text without using as a guardrail.
344
- * Useful for analysis and logging.
345
- *
346
- * @example
347
- * ```typescript
348
- * const result = await detectPII('My SSN is 123-45-6789');
349
- * console.log(result.items); // [{ type: 'ssn', value: '123-45-6789', ... }]
350
- *
351
- * // With custom detector and timeout
352
- * const result = await detectPII(text, {
353
- * detector: myPresidioDetector,
354
- * timeout: 10000, // 10 seconds
355
- * });
356
- * ```
357
- */
358
- declare function detectPII(text: string, options?: {
359
- types?: PIIType[];
360
- detector?: "regex" | PIIDetector;
361
- minConfidence?: number;
362
- /** Timeout for custom detectors in milliseconds (default: 5000) */
363
- timeout?: number;
364
- }): Promise<PIIDetectionResult>;
365
- /**
366
- * Detect PII in text and return a result whose `redactedText` is populated.
367
- *
368
- * This composes {@link detectPII} and {@link redactPII} so callers do not have
369
- * to manually wire the two together (and do not have to mutate the detection
370
- * result). When no PII is detected, `redactedText` is left `undefined` — it is
371
- * deliberately NOT defaulted to the raw input.
372
- *
373
- * @example
374
- * ```typescript
375
- * const result = await detectAndRedactPII('My SSN is 123-45-6789', {
376
- * types: ['ssn'],
377
- * style: 'typed',
378
- * });
379
- * console.log(result.detected); // true
380
- * // ssn is a sensitive-category type, so `typed` emits a generic [REDACTED]
381
- * console.log(result.redactedText); // 'My SSN is [REDACTED]'
382
- *
383
- * const clean = await detectAndRedactPII('nothing here', { types: ['ssn'] });
384
- * console.log(clean.detected); // false
385
- * console.log(clean.redactedText); // undefined
386
- * ```
387
- */
388
- declare function detectAndRedactPII(text: string, options?: {
389
- types?: PIIType[];
390
- detector?: "regex" | PIIDetector;
391
- minConfidence?: number;
392
- /** Timeout for custom detectors in milliseconds (default: 5000) */
393
- timeout?: number;
394
- /** Redaction style applied when PII is detected (default: 'typed') */
395
- style?: RedactionStyle;
396
- }): Promise<PIIDetectionResult>;
397
-
398
- /**
399
- * Prompt Injection Detection Guardrail
400
- *
401
- * Detects and blocks prompt injection attacks including:
402
- * - Direct injection attempts ("ignore previous instructions")
403
- * - Jailbreak patterns ("DAN mode", "pretend you can")
404
- * - Indirect injection via external content
405
- * - Encoding-based evasion attempts
406
- *
407
- * @example
408
- * ```typescript
409
- * import { createPromptInjectionGuardrail } from '@directive-run/ai';
410
- *
411
- * const guardrail = createPromptInjectionGuardrail({
412
- * strictMode: true,
413
- * onBlocked: (input, patterns) => logSecurityEvent(input, patterns),
414
- * });
415
- * ```
416
- */
417
-
418
- /** Pattern with metadata for better debugging */
419
- interface InjectionPattern {
420
- pattern: RegExp;
421
- name: string;
422
- severity: "low" | "medium" | "high" | "critical";
423
- category: InjectionCategory;
424
- }
425
- /** Categories of injection attacks */
426
- type InjectionCategory = "instruction_override" | "jailbreak" | "role_manipulation" | "encoding_evasion" | "delimiter_injection" | "context_manipulation" | "indirect_injection";
427
- /** Default injection patterns - well-tested and low false-positive rate */
428
- declare const DEFAULT_INJECTION_PATTERNS: InjectionPattern[];
429
- /** Strict patterns - more aggressive, may have higher false positives */
430
- declare const STRICT_INJECTION_PATTERNS: InjectionPattern[];
431
- /** Detailed detection result */
432
- interface InjectionDetectionResult {
433
- detected: boolean;
434
- patterns: Array<{
435
- name: string;
436
- category: InjectionCategory;
437
- severity: InjectionPattern["severity"];
438
- match: string;
439
- position: number;
440
- }>;
441
- riskScore: number;
442
- sanitizedInput?: string;
443
- }
444
- /**
445
- * Detect prompt injection patterns in text.
446
- * Returns detailed results about what was detected.
447
- *
448
- * @throws Error if input exceeds MAX_INJECTION_INPUT_LENGTH (100KB)
449
- */
450
- declare function detectPromptInjection(text: string, patterns?: InjectionPattern[]): InjectionDetectionResult;
451
- /**
452
- * Sanitize text by removing detected injection patterns.
453
- * Warning: This is a best-effort sanitization, not a security guarantee.
454
- *
455
- * Uses a single-pass approach to prevent infinite loops where a replacement
456
- * could create a new pattern match.
457
- */
458
- declare function sanitizeInjection(text: string, patterns?: InjectionPattern[]): string;
459
- /** Options for prompt injection guardrail */
460
- interface PromptInjectionGuardrailOptions {
461
- /** Additional patterns to check (added to defaults) */
462
- additionalPatterns?: InjectionPattern[];
463
- /** Replace default patterns entirely */
464
- replacePatterns?: InjectionPattern[];
465
- /** Use strict mode with more aggressive detection */
466
- strictMode?: boolean;
467
- /** Minimum risk score to block (0-100, default: 50) */
468
- blockThreshold?: number;
469
- /** Attempt to sanitize instead of blocking */
470
- sanitize?: boolean;
471
- /** Callback when injection is detected */
472
- onBlocked?: (input: string, result: InjectionDetectionResult) => void;
473
- /** Categories to ignore (e.g., allow 'role_manipulation' for roleplay apps) */
474
- ignoreCategories?: InjectionCategory[];
475
- }
476
- /**
477
- * Create a prompt injection detection guardrail.
478
- *
479
- * @example
480
- * ```typescript
481
- * // Basic usage
482
- * const guardrail = createPromptInjectionGuardrail();
483
- *
484
- * // Strict mode for high-security applications
485
- * const strictGuardrail = createPromptInjectionGuardrail({
486
- * strictMode: true,
487
- * blockThreshold: 25,
488
- * });
489
- *
490
- * // Allow role manipulation for roleplay apps
491
- * const roleplayGuardrail = createPromptInjectionGuardrail({
492
- * ignoreCategories: ['role_manipulation'],
493
- * });
494
- * ```
495
- */
496
- declare function createPromptInjectionGuardrail(options?: PromptInjectionGuardrailOptions): GuardrailFn<InputGuardrailData>;
497
- /**
498
- * Mark content as potentially untrusted (from external sources).
499
- * This wraps the content with markers that injection detection will scrutinize more closely.
500
- *
501
- * @example
502
- * ```typescript
503
- * const userUpload = await readFile(path);
504
- * const markedContent = markUntrustedContent(userUpload, 'user-upload');
505
- * const prompt = `Summarize this document: ${markedContent}`;
506
- * ```
507
- */
508
- declare function markUntrustedContent(content: string, source: string): string;
509
- /**
510
- * Create a guardrail that applies stricter checks to marked untrusted content.
511
- *
512
- * @example
513
- * ```typescript
514
- * const guardrail = createUntrustedContentGuardrail({
515
- * baseGuardrail: createPromptInjectionGuardrail({ strictMode: true }),
516
- * });
517
- * ```
518
- */
519
- declare function createUntrustedContentGuardrail(options: {
520
- /** Guardrail to apply to untrusted sections */
521
- baseGuardrail?: GuardrailFn<InputGuardrailData>;
522
- /** Block if untrusted content contains these patterns */
523
- additionalPatterns?: InjectionPattern[];
524
- }): GuardrailFn<InputGuardrailData>;
525
-
526
- /**
527
- * Approximate Nearest Neighbor (ANN) Index for Semantic Cache
528
- *
529
- * Provides pluggable vector search backends for efficient similarity lookups.
530
- * Includes a brute-force exact search and a VP-tree (Vantage Point Tree) for
531
- * fast approximate nearest neighbor queries.
532
- *
533
- * @example
534
- * ```typescript
535
- * import { createSemanticCache } from '@directive-run/ai';
536
- * import { createVPTreeIndex } from '@directive-run/ai';
537
- *
538
- * const index = createVPTreeIndex();
539
- *
540
- * const cache = createSemanticCache({
541
- * embedder: myEmbedder,
542
- * annIndex: index,
543
- * });
544
- * ```
545
- */
546
-
547
- /** Search result from an ANN index */
548
- interface ANNSearchResult {
549
- /** ID of the matched item */
550
- id: number;
551
- /** Similarity score (0-1, higher is more similar) */
552
- similarity: number;
553
- }
554
- /** ANN Index interface - pluggable vector search backend */
555
- interface ANNIndex {
556
- /** Add a vector to the index */
557
- add(id: number, embedding: Embedding): void;
558
- /** Remove a vector from the index */
559
- remove(id: number): void;
560
- /** Search for the k nearest neighbors */
561
- search(query: Embedding, k: number, threshold?: number): ANNSearchResult[];
562
- /** Rebuild the index (call after batch additions) */
563
- rebuild(): void;
564
- /** Get the number of indexed vectors */
565
- size(): number;
566
- /** Clear the index */
567
- clear(): void;
568
- /** Check if the index needs to be rebuilt (e.g., after additions/removals) */
569
- needsRebuild(): boolean;
570
- }
571
- /**
572
- * Create a brute-force exact search index.
573
- *
574
- * O(n) search, O(1) add/remove. Best for small collections (< 10,000 vectors).
575
- *
576
- * @example
577
- * ```typescript
578
- * const index = createBruteForceIndex();
579
- * index.add(0, [0.1, 0.2, 0.3]);
580
- * index.add(1, [0.4, 0.5, 0.6]);
581
- *
582
- * const results = index.search([0.1, 0.2, 0.3], 1);
583
- * // [{ id: 0, similarity: 1.0 }]
584
- * ```
585
- */
586
- declare function createBruteForceIndex(): ANNIndex;
587
- /** VP-Tree index configuration */
588
- interface VPTreeIndexConfig {
589
- /** Optional random number generator for deterministic builds. Returns a number in [0, 1). */
590
- random?: () => number;
591
- }
592
- /**
593
- * Create a VP-Tree (Vantage Point Tree) index for efficient approximate nearest neighbor search.
594
- *
595
- * O(log n) search on average, requires rebuild after batch additions.
596
- * Best for medium collections (1,000 - 100,000 vectors).
597
- *
598
- * @example
599
- * ```typescript
600
- * const index = createVPTreeIndex();
601
- *
602
- * // Add vectors
603
- * for (let i = 0; i < embeddings.length; i++) {
604
- * index.add(i, embeddings[i]);
605
- * }
606
- *
607
- * // Build the tree
608
- * index.rebuild();
609
- *
610
- * // Search
611
- * const results = index.search(queryEmbedding, 5, 0.9);
612
- * ```
613
- */
614
- declare function createVPTreeIndex(vpConfig?: VPTreeIndexConfig): ANNIndex;
615
-
616
- export { type ANNIndex as A, DEFAULT_INJECTION_PATTERNS as D, type EnhancedPIIGuardrailOptions as E, type InjectionDetectionResult as I, type PIIDetectionResult as P, type RateLimitGuardrail as R, STRICT_INJECTION_PATTERNS as S, type VPTreeIndexConfig as V, type ANNSearchResult as a, type DetectedPII as b, type PIIDetector as c, type PIIType as d, type PromptInjectionGuardrailOptions as e, type RedactionStyle as f, createBruteForceIndex as g, createContentFilterGuardrail as h, createEnhancedPIIGuardrail as i, createLengthGuardrail as j, createModerationGuardrail as k, createOutputPIIGuardrail as l, createOutputSchemaGuardrail as m, createOutputTypeGuardrail as n, createPIIGuardrail as o, createPromptInjectionGuardrail as p, createRateLimitGuardrail as q, createToolGuardrail as r, createUntrustedContentGuardrail as s, createVPTreeIndex as t, detectAndRedactPII as u, detectPII as v, detectPromptInjection as w, markUntrustedContent as x, redactPII as y, sanitizeInjection as z };