@directive-run/ai 1.19.0 → 1.19.2

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-4TZDDT63.cjs +4 -0
  6. package/dist/chunk-4TZDDT63.cjs.map +1 -0
  7. package/dist/chunk-ARYO7BLK.js +16 -0
  8. package/dist/chunk-ARYO7BLK.js.map +1 -0
  9. package/dist/chunk-MAWPOW4D.js +4 -0
  10. package/dist/chunk-MAWPOW4D.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 +645 -21
  22. package/dist/guardrails.d.ts +645 -21
  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,7 +1,219 @@
1
- export { A as ANNIndex, a as ANNSearchResult, D as DEFAULT_INJECTION_PATTERNS, b as DetectedPII, E as EnhancedPIIGuardrailOptions, I as InjectionDetectionResult, P as PIIDetectionResult, c as PIIDetector, d as PIIType, e as PromptInjectionGuardrailOptions, R as RateLimitGuardrail, f as RedactionStyle, S as STRICT_INJECTION_PATTERNS, V as VPTreeIndexConfig, g as createBruteForceIndex, h as createContentFilterGuardrail, i as createEnhancedPIIGuardrail, j as createLengthGuardrail, k as createModerationGuardrail, l as createOutputPIIGuardrail, m as createOutputSchemaGuardrail, n as createOutputTypeGuardrail, o as createPIIGuardrail, p as createPromptInjectionGuardrail, q as createRateLimitGuardrail, r as createToolGuardrail, s as createUntrustedContentGuardrail, t as createVPTreeIndex, u as detectAndRedactPII, v as detectPII, w as detectPromptInjection, x as markUntrustedContent, y as redactPII, z as sanitizeInjection } from './ann-index-27QV9tPC.js';
1
+ import { m as GuardrailFn, I as InputGuardrailData, O as OutputGuardrailData, aW as SchemaValidator, T as ToolCallGuardrailData } from './types-DJ09LjZX.js';
2
+ import { a as Embedding } from './semantic-cache-DM7ev7NQ.js';
3
+ export { B as BatchedEmbedder, C as CacheEntry, b as CacheLookupResult, c as CacheStats, E as EmbedderFn, S as SemanticCache, d as SemanticCacheConfig, e as SemanticCacheStorage, f as createBatchedEmbedder, g as createInMemoryStorage, h as createSemanticCache, i as createSemanticCacheGuardrail, j as createTestEmbedder } from './semantic-cache-DM7ev7NQ.js';
2
4
  import { Plugin } from '@directive-run/core';
3
- export { B as BatchedEmbedder, C as CacheEntry, a as CacheLookupResult, b as CacheStats, E as EmbedderFn, c as Embedding, S as SemanticCache, d as SemanticCacheConfig, e as SemanticCacheStorage, f as createBatchedEmbedder, g as createInMemoryStorage, h as createSemanticCache, i as createSemanticCacheGuardrail, j as createTestEmbedder } from './semantic-cache-Ba0-jEwb.js';
4
- import './types-CUp1N0uU.js';
5
+
6
+ /**
7
+ * Built-in guardrails for AI adapter — PII, moderation, rate limiting, tool allowlists, schema validation.
8
+ */
9
+
10
+ /**
11
+ * Create a PII detection guardrail that scans input text for personally identifiable
12
+ * information. Blocks input when PII is detected, or optionally redacts matches and
13
+ * passes the sanitized text through.
14
+ *
15
+ * @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]"`).
16
+ * @returns An input guardrail that blocks or redacts PII in user input.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * const piiGuardrail = createPIIGuardrail({
21
+ * patterns: [
22
+ * /\b\d{3}-\d{2}-\d{4}\b/, // SSN
23
+ * /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i, // Email
24
+ * ],
25
+ * redact: true,
26
+ * });
27
+ * ```
28
+ *
29
+ * @public
30
+ */
31
+ declare function createPIIGuardrail(options: {
32
+ patterns?: RegExp[];
33
+ redact?: boolean;
34
+ redactReplacement?: string;
35
+ }): GuardrailFn<InputGuardrailData>;
36
+ /**
37
+ * Create a content moderation guardrail that delegates to a user-supplied check function.
38
+ * Works on both input and output data — the guardrail extracts the text content
39
+ * automatically and passes it to {@link options.checkFn}.
40
+ *
41
+ * @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"`).
42
+ * @returns A guardrail that blocks content flagged by the check function.
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * const moderationGuardrail = createModerationGuardrail({
47
+ * checkFn: async (text) => {
48
+ * const result = await openai.moderations.create({ input: text });
49
+ * return result.results[0].flagged;
50
+ * },
51
+ * });
52
+ * ```
53
+ *
54
+ * @public
55
+ */
56
+ declare function createModerationGuardrail(options: {
57
+ checkFn: (text: string) => boolean | Promise<boolean>;
58
+ message?: string;
59
+ }): GuardrailFn<InputGuardrailData | OutputGuardrailData>;
60
+ /** Rate limiter with reset capability for testing */
61
+ interface RateLimitGuardrail extends GuardrailFn<InputGuardrailData> {
62
+ reset(): void;
63
+ }
64
+ /**
65
+ * Create a rate limit guardrail that tracks token and request counts over a sliding
66
+ * one-minute window. Returns a {@link RateLimitGuardrail} — a guardrail function with
67
+ * an additional `reset()` method for testing.
68
+ *
69
+ * @param options - Configuration for rate limiting: `maxTokensPerMinute` caps tokens in the sliding window (defaults to `100000`), `maxRequestsPerMinute` caps requests (defaults to `60`).
70
+ * @returns A rate limit guardrail with an attached `reset()` method.
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * const rateLimiter = createRateLimitGuardrail({
75
+ * maxTokensPerMinute: 50000,
76
+ * maxRequestsPerMinute: 30,
77
+ * });
78
+ * ```
79
+ *
80
+ * @public
81
+ */
82
+ declare function createRateLimitGuardrail(options: {
83
+ maxTokensPerMinute?: number;
84
+ maxRequestsPerMinute?: number;
85
+ }): RateLimitGuardrail;
86
+ /**
87
+ * Create a tool-call guardrail that restricts which tools an agent may invoke.
88
+ * Supports allowlist mode, denylist mode, or both — when both are provided, a tool
89
+ * must appear in the allowlist and not appear in the denylist.
90
+ *
91
+ * @param options - Configuration for tool filtering: `allowlist` sets permitted tool names, `denylist` sets blocked tool names, `caseSensitive` controls case matching (defaults to `false`).
92
+ * @returns A tool-call guardrail that enforces the allowlist/denylist rules.
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * const toolGuardrail = createToolGuardrail({
97
+ * allowlist: ["search", "calculate"],
98
+ * denylist: ["delete_account"],
99
+ * });
100
+ * ```
101
+ *
102
+ * @public
103
+ */
104
+ declare function createToolGuardrail(options: {
105
+ allowlist?: string[];
106
+ denylist?: string[];
107
+ /** @default false */
108
+ caseSensitive?: boolean;
109
+ }): GuardrailFn<ToolCallGuardrailData>;
110
+ /**
111
+ * Create an output guardrail that validates agent output against a schema using
112
+ * a user-supplied {@link SchemaValidator}. Compatible with any validation library
113
+ * (Zod, Valibot, ArkType, etc.) via the adapter pattern.
114
+ *
115
+ * @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"`).
116
+ * @returns An output guardrail that rejects output failing schema validation.
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * import { z } from "zod";
121
+ *
122
+ * const schemaGuardrail = createOutputSchemaGuardrail({
123
+ * validate: (value) => {
124
+ * const result = z.object({ answer: z.string() }).safeParse(value);
125
+ * return { valid: result.success, errors: result.error?.issues.map(i => i.message) };
126
+ * },
127
+ * });
128
+ * ```
129
+ *
130
+ * @public
131
+ */
132
+ declare function createOutputSchemaGuardrail<T = unknown>(options: {
133
+ validate: SchemaValidator<T>;
134
+ errorPrefix?: string;
135
+ }): GuardrailFn<OutputGuardrailData>;
136
+ /**
137
+ * Create an output guardrail that performs lightweight runtime type checks without
138
+ * requiring a schema library. Supports `"string"`, `"number"`, `"boolean"`, `"object"`,
139
+ * and `"array"` with optional size and field constraints.
140
+ *
141
+ * @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.
142
+ * @returns An output guardrail that rejects output not matching the expected type or constraints.
143
+ *
144
+ * @example
145
+ * ```typescript
146
+ * const typeGuardrail = createOutputTypeGuardrail({
147
+ * type: "object",
148
+ * requiredFields: ["id", "name"],
149
+ * });
150
+ * ```
151
+ *
152
+ * @public
153
+ */
154
+ declare function createOutputTypeGuardrail(options: {
155
+ type: "string" | "number" | "boolean" | "object" | "array";
156
+ requiredFields?: string[];
157
+ minLength?: number;
158
+ maxLength?: number;
159
+ minStringLength?: number;
160
+ maxStringLength?: number;
161
+ }): GuardrailFn<OutputGuardrailData>;
162
+ /**
163
+ * Create an output guardrail that enforces maximum length constraints on agent output,
164
+ * measured in characters or estimated tokens.
165
+ *
166
+ * @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)`).
167
+ * @returns An output guardrail that rejects output exceeding the configured length limits.
168
+ *
169
+ * @example
170
+ * ```typescript
171
+ * const lengthGuardrail = createLengthGuardrail({
172
+ * maxCharacters: 5000,
173
+ * maxTokens: 1200,
174
+ * });
175
+ * ```
176
+ *
177
+ * @public
178
+ */
179
+ declare function createLengthGuardrail(options: {
180
+ /** Maximum characters in output */
181
+ maxCharacters?: number;
182
+ /** Maximum estimated tokens in output */
183
+ maxTokens?: number;
184
+ /** Custom token estimator (default: chars / 4) */
185
+ estimateTokens?: (text: string) => number;
186
+ }): GuardrailFn<OutputGuardrailData>;
187
+ /**
188
+ * Create an output guardrail that blocks content matching any of the provided patterns.
189
+ * String patterns are escaped and compiled to RegExp; RegExp patterns are used as-is.
190
+ *
191
+ * @remarks
192
+ * A warning is logged when `blockedPatterns` is empty, since an empty list means no
193
+ * content will ever be filtered.
194
+ *
195
+ * @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`).
196
+ * @returns An output guardrail that rejects output containing any blocked pattern.
197
+ *
198
+ * @example
199
+ * ```typescript
200
+ * const contentFilter = createContentFilterGuardrail({
201
+ * blockedPatterns: [
202
+ * /\bpassword\b/i,
203
+ * /\bsecret\b/i,
204
+ * 'internal-only',
205
+ * ],
206
+ * });
207
+ * ```
208
+ *
209
+ * @public
210
+ */
211
+ declare function createContentFilterGuardrail(options: {
212
+ /** Patterns to block — strings or RegExp */
213
+ blockedPatterns: Array<string | RegExp>;
214
+ /** Case-sensitive matching for string patterns (default: false) */
215
+ caseSensitive?: boolean;
216
+ }): GuardrailFn<OutputGuardrailData>;
5
217
 
6
218
  /**
7
219
  * Fact-PII Guardrail — input guardrail at the fact-store boundary
@@ -148,26 +360,38 @@ interface FactPIIGuardrailOptions {
148
360
  customDetector?: (text: string) => readonly FactPIIMatch[];
149
361
  /**
150
362
  * Maximum nesting depth to walk when scanning a structured fact
151
- * value. Default `1` — the scanner inspects top-level strings, then
152
- * descends one level into the object/array. Arrays and plain objects
153
- * count as one depth level each. Maps and Sets are still NOT walked
154
- * by the built-in scanner; PII inside those structures must go
155
- * through a `customDetector`.
363
+ * value. Default `1` — the scanner inspects top-level strings AND
364
+ * recurses one level into nested objects / arrays. Each array level
365
+ * burns one depth slot (so `[[email]]` at `walkDepth: 1` walks the
366
+ * outer array but its inner array is NOT scanned). Maps and Sets
367
+ * are still NOT walked by the built-in scanner; PII inside those
368
+ * structures must go through a `customDetector`.
156
369
  *
157
- * Per R13-C6 the walker recurses into arrays (Supabase realtime
158
- * payloads ship as `payload.new = [{...}]`, MCP resource lists ship
159
- * as arrays those shapes silently bypassed the Tier 0 guard before).
370
+ * Real-world common shapes and the `walkDepth` they need:
371
+ * - **Flat object** (`{ email, ssn }`) works at default `1`.
372
+ * - **Nested object** (`{ profile: { email } }`) needs `walkDepth: 2`.
373
+ * - **Supabase realtime row payload** (`payload.new = [{ email }]`,
374
+ * passed as the fact value) — the fact's value is the object
375
+ * `{ new: [...] }`, so the chain is object → array → object →
376
+ * string and needs `walkDepth: 4`.
377
+ * - **MCP resource notification list** (`{ resources: [{...}] }`) —
378
+ * same shape, needs `walkDepth: 4`.
160
379
  *
161
- * Consumers with deeply-nested PII shapes have two options:
162
- * 1. Pass `walkDepth: 2` (or higher) the scanner walks plain
163
- * objects and arrays to that depth. Maps and Sets are still
164
- * skipped.
165
- * 2. Pass a `customDetector` that walks the consumer-specific shape
166
- * and returns concrete matches — the right answer for
167
- * domain-specific structures (Maps, Sets, getters, Symbol keys).
380
+ * For deeper or non-object structures (Maps, Sets, class instances
381
+ * with getters, Symbol-keyed properties), pass a `customDetector`
382
+ * that walks the consumer-specific shape and returns concrete
383
+ * matches.
168
384
  *
169
- * Maximum is `5` to prevent pathological recursion on cyclic
170
- * structures. Passing anything higher clamps to `5`.
385
+ * **Hard caps for safety:**
386
+ * - `walkDepth` clamps to `[1, 5]` to prevent pathological recursion
387
+ * on cyclic structures. Non-finite values (`NaN`, `Infinity`,
388
+ * non-number casts) clamp to `1`.
389
+ * - The walker caps any single array's element count at 10,000
390
+ * (warns + truncates). Pass a `customDetector` for larger
391
+ * payloads.
392
+ * - Cycles via shared object references are detected and the
393
+ * walker treats re-encountered ancestors as "no match" rather
394
+ * than recursing.
171
395
  *
172
396
  * Property iteration uses `Object.entries`, which skips
173
397
  * Symbol-keyed properties and non-enumerable string keys. If you
@@ -187,4 +411,404 @@ interface FactPIIGuardrailOptions {
187
411
  */
188
412
  declare function createFactPIIGuardrail(options?: FactPIIGuardrailOptions): Plugin;
189
413
 
190
- export { type FactPIICategory, type FactPIIGuardrailMode, type FactPIIGuardrailOptions, type FactPIIMatch, createFactPIIGuardrail };
414
+ /**
415
+ * Enhanced PII Detection Guardrail
416
+ *
417
+ * Provides comprehensive PII detection beyond basic regex patterns:
418
+ * - Multiple PII types (SSN, credit cards, emails, phones, addresses, names)
419
+ * - Pluggable detection backends (regex, custom, or external services)
420
+ * - Context-aware detection (reduces false positives)
421
+ * - Redaction with reversible or irreversible options
422
+ *
423
+ * @example
424
+ * ```typescript
425
+ * import { createEnhancedPIIGuardrail } from '@directive-run/ai';
426
+ *
427
+ * const guardrail = createEnhancedPIIGuardrail({
428
+ * types: ['ssn', 'credit_card', 'email'],
429
+ * redact: true,
430
+ * detector: 'regex', // or 'custom' with custom detector
431
+ * });
432
+ * ```
433
+ */
434
+
435
+ /** Supported PII types */
436
+ type PIIType = "ssn" | "credit_card" | "email" | "phone" | "address" | "name" | "date_of_birth" | "passport" | "driver_license" | "ip_address" | "bank_account" | "medical_id" | "national_id";
437
+ /** Detected PII instance */
438
+ interface DetectedPII {
439
+ type: PIIType;
440
+ value: string;
441
+ position: {
442
+ start: number;
443
+ end: number;
444
+ };
445
+ confidence: number;
446
+ context?: string;
447
+ }
448
+ /** PII detection result */
449
+ interface PIIDetectionResult {
450
+ detected: boolean;
451
+ items: DetectedPII[];
452
+ typeCounts: Partial<Record<PIIType, number>>;
453
+ /** Text with PII redacted (if requested) */
454
+ redactedText?: string;
455
+ }
456
+ /** Custom PII detector interface */
457
+ interface PIIDetector {
458
+ detect(text: string, types: PIIType[]): Promise<DetectedPII[]>;
459
+ name: string;
460
+ }
461
+ /** Redaction style */
462
+ type RedactionStyle =
463
+ /** Replace with [REDACTED] */
464
+ "placeholder"
465
+ /** Replace with type-specific placeholder like [EMAIL] */
466
+ | "typed"
467
+ /**
468
+ * Replace with a fixed-width `****` mask plus the last 4 characters
469
+ * (e.g. `****6789`). Does not preserve or reveal the original length.
470
+ */
471
+ | "masked"
472
+ /**
473
+ * Replace with a deterministic FNV-1a hash.
474
+ *
475
+ * **WARNING — this is PSEUDONYMIZATION, not anonymization.** FNV-1a is a
476
+ * fast, non-cryptographic 32-bit hash. For low-entropy structured PII (SSNs,
477
+ * card numbers, phone numbers) the output is trivially RE-IDENTIFIABLE via
478
+ * brute force or a precomputed rainbow table. It MUST NOT be relied on for
479
+ * GDPR / HIPAA de-identification. Use it only for referential integrity
480
+ * (correlating the same value across audit logs).
481
+ */
482
+ | "hashed";
483
+ /** Redact detected PII from text */
484
+ declare function redactPII(text: string, items: DetectedPII[], style?: RedactionStyle): string;
485
+ /** Options for enhanced PII guardrail */
486
+ interface EnhancedPIIGuardrailOptions {
487
+ /** PII types to detect (default: all) */
488
+ types?: PIIType[];
489
+ /** Detection backend (default: 'regex') */
490
+ detector?: "regex" | PIIDetector;
491
+ /** Redact instead of blocking */
492
+ redact?: boolean;
493
+ /** Redaction style (default: 'typed') */
494
+ redactionStyle?: RedactionStyle;
495
+ /** Minimum confidence to flag (0-1, default: 0.7) */
496
+ minConfidence?: number;
497
+ /** Callback when PII is detected */
498
+ onDetected?: (items: DetectedPII[]) => void;
499
+ /** Allow specific values (whitelist) */
500
+ allowlist?: string[];
501
+ /** Block only if count exceeds threshold */
502
+ minItemsToBlock?: number;
503
+ /** Timeout for custom detector in milliseconds (default: 5000) */
504
+ detectorTimeout?: number;
505
+ }
506
+ /**
507
+ * Create an enhanced PII detection guardrail.
508
+ *
509
+ * @example
510
+ * ```typescript
511
+ * // Basic usage
512
+ * const guardrail = createEnhancedPIIGuardrail();
513
+ *
514
+ * // Redact instead of blocking
515
+ * const redactGuardrail = createEnhancedPIIGuardrail({
516
+ * redact: true,
517
+ * redactionStyle: 'masked',
518
+ * });
519
+ *
520
+ * // Custom detection with external service
521
+ * const customGuardrail = createEnhancedPIIGuardrail({
522
+ * detector: myPresidioDetector,
523
+ * types: ['ssn', 'credit_card', 'medical_id'],
524
+ * });
525
+ * ```
526
+ */
527
+ declare function createEnhancedPIIGuardrail(options?: EnhancedPIIGuardrailOptions): GuardrailFn<InputGuardrailData>;
528
+ /**
529
+ * Create an output PII guardrail (for checking agent responses).
530
+ *
531
+ * @example
532
+ * ```typescript
533
+ * const outputGuardrail = createOutputPIIGuardrail({
534
+ * types: ['ssn', 'credit_card'],
535
+ * redact: true,
536
+ * });
537
+ * ```
538
+ */
539
+ declare function createOutputPIIGuardrail(options?: EnhancedPIIGuardrailOptions): GuardrailFn<OutputGuardrailData>;
540
+ /**
541
+ * Detect PII in text without using as a guardrail.
542
+ * Useful for analysis and logging.
543
+ *
544
+ * @example
545
+ * ```typescript
546
+ * const result = await detectPII('My SSN is 123-45-6789');
547
+ * console.log(result.items); // [{ type: 'ssn', value: '123-45-6789', ... }]
548
+ *
549
+ * // With custom detector and timeout
550
+ * const result = await detectPII(text, {
551
+ * detector: myPresidioDetector,
552
+ * timeout: 10000, // 10 seconds
553
+ * });
554
+ * ```
555
+ */
556
+ declare function detectPII(text: string, options?: {
557
+ types?: PIIType[];
558
+ detector?: "regex" | PIIDetector;
559
+ minConfidence?: number;
560
+ /** Timeout for custom detectors in milliseconds (default: 5000) */
561
+ timeout?: number;
562
+ }): Promise<PIIDetectionResult>;
563
+ /**
564
+ * Detect PII in text and return a result whose `redactedText` is populated.
565
+ *
566
+ * This composes {@link detectPII} and {@link redactPII} so callers do not have
567
+ * to manually wire the two together (and do not have to mutate the detection
568
+ * result). When no PII is detected, `redactedText` is left `undefined` — it is
569
+ * deliberately NOT defaulted to the raw input.
570
+ *
571
+ * @example
572
+ * ```typescript
573
+ * const result = await detectAndRedactPII('My SSN is 123-45-6789', {
574
+ * types: ['ssn'],
575
+ * style: 'typed',
576
+ * });
577
+ * console.log(result.detected); // true
578
+ * // ssn is a sensitive-category type, so `typed` emits a generic [REDACTED]
579
+ * console.log(result.redactedText); // 'My SSN is [REDACTED]'
580
+ *
581
+ * const clean = await detectAndRedactPII('nothing here', { types: ['ssn'] });
582
+ * console.log(clean.detected); // false
583
+ * console.log(clean.redactedText); // undefined
584
+ * ```
585
+ */
586
+ declare function detectAndRedactPII(text: string, options?: {
587
+ types?: PIIType[];
588
+ detector?: "regex" | PIIDetector;
589
+ minConfidence?: number;
590
+ /** Timeout for custom detectors in milliseconds (default: 5000) */
591
+ timeout?: number;
592
+ /** Redaction style applied when PII is detected (default: 'typed') */
593
+ style?: RedactionStyle;
594
+ }): Promise<PIIDetectionResult>;
595
+
596
+ /**
597
+ * Prompt Injection Detection Guardrail
598
+ *
599
+ * Detects and blocks prompt injection attacks including:
600
+ * - Direct injection attempts ("ignore previous instructions")
601
+ * - Jailbreak patterns ("DAN mode", "pretend you can")
602
+ * - Indirect injection via external content
603
+ * - Encoding-based evasion attempts
604
+ *
605
+ * @example
606
+ * ```typescript
607
+ * import { createPromptInjectionGuardrail } from '@directive-run/ai';
608
+ *
609
+ * const guardrail = createPromptInjectionGuardrail({
610
+ * strictMode: true,
611
+ * onBlocked: (input, patterns) => logSecurityEvent(input, patterns),
612
+ * });
613
+ * ```
614
+ */
615
+
616
+ /** Pattern with metadata for better debugging */
617
+ interface InjectionPattern {
618
+ pattern: RegExp;
619
+ name: string;
620
+ severity: "low" | "medium" | "high" | "critical";
621
+ category: InjectionCategory;
622
+ }
623
+ /** Categories of injection attacks */
624
+ type InjectionCategory = "instruction_override" | "jailbreak" | "role_manipulation" | "encoding_evasion" | "delimiter_injection" | "context_manipulation" | "indirect_injection";
625
+ /** Default injection patterns - well-tested and low false-positive rate */
626
+ declare const DEFAULT_INJECTION_PATTERNS: InjectionPattern[];
627
+ /** Strict patterns - more aggressive, may have higher false positives */
628
+ declare const STRICT_INJECTION_PATTERNS: InjectionPattern[];
629
+ /** Detailed detection result */
630
+ interface InjectionDetectionResult {
631
+ detected: boolean;
632
+ patterns: Array<{
633
+ name: string;
634
+ category: InjectionCategory;
635
+ severity: InjectionPattern["severity"];
636
+ match: string;
637
+ position: number;
638
+ }>;
639
+ riskScore: number;
640
+ sanitizedInput?: string;
641
+ }
642
+ /**
643
+ * Detect prompt injection patterns in text.
644
+ * Returns detailed results about what was detected.
645
+ *
646
+ * @throws Error if input exceeds MAX_INJECTION_INPUT_LENGTH (100KB)
647
+ */
648
+ declare function detectPromptInjection(text: string, patterns?: InjectionPattern[]): InjectionDetectionResult;
649
+ /**
650
+ * Sanitize text by removing detected injection patterns.
651
+ * Warning: This is a best-effort sanitization, not a security guarantee.
652
+ *
653
+ * Uses a single-pass approach to prevent infinite loops where a replacement
654
+ * could create a new pattern match.
655
+ */
656
+ declare function sanitizeInjection(text: string, patterns?: InjectionPattern[]): string;
657
+ /** Options for prompt injection guardrail */
658
+ interface PromptInjectionGuardrailOptions {
659
+ /** Additional patterns to check (added to defaults) */
660
+ additionalPatterns?: InjectionPattern[];
661
+ /** Replace default patterns entirely */
662
+ replacePatterns?: InjectionPattern[];
663
+ /** Use strict mode with more aggressive detection */
664
+ strictMode?: boolean;
665
+ /** Minimum risk score to block (0-100, default: 50) */
666
+ blockThreshold?: number;
667
+ /** Attempt to sanitize instead of blocking */
668
+ sanitize?: boolean;
669
+ /** Callback when injection is detected */
670
+ onBlocked?: (input: string, result: InjectionDetectionResult) => void;
671
+ /** Categories to ignore (e.g., allow 'role_manipulation' for roleplay apps) */
672
+ ignoreCategories?: InjectionCategory[];
673
+ }
674
+ /**
675
+ * Create a prompt injection detection guardrail.
676
+ *
677
+ * @example
678
+ * ```typescript
679
+ * // Basic usage
680
+ * const guardrail = createPromptInjectionGuardrail();
681
+ *
682
+ * // Strict mode for high-security applications
683
+ * const strictGuardrail = createPromptInjectionGuardrail({
684
+ * strictMode: true,
685
+ * blockThreshold: 25,
686
+ * });
687
+ *
688
+ * // Allow role manipulation for roleplay apps
689
+ * const roleplayGuardrail = createPromptInjectionGuardrail({
690
+ * ignoreCategories: ['role_manipulation'],
691
+ * });
692
+ * ```
693
+ */
694
+ declare function createPromptInjectionGuardrail(options?: PromptInjectionGuardrailOptions): GuardrailFn<InputGuardrailData>;
695
+ /**
696
+ * Mark content as potentially untrusted (from external sources).
697
+ * This wraps the content with markers that injection detection will scrutinize more closely.
698
+ *
699
+ * @example
700
+ * ```typescript
701
+ * const userUpload = await readFile(path);
702
+ * const markedContent = markUntrustedContent(userUpload, 'user-upload');
703
+ * const prompt = `Summarize this document: ${markedContent}`;
704
+ * ```
705
+ */
706
+ declare function markUntrustedContent(content: string, source: string): string;
707
+ /**
708
+ * Create a guardrail that applies stricter checks to marked untrusted content.
709
+ *
710
+ * @example
711
+ * ```typescript
712
+ * const guardrail = createUntrustedContentGuardrail({
713
+ * baseGuardrail: createPromptInjectionGuardrail({ strictMode: true }),
714
+ * });
715
+ * ```
716
+ */
717
+ declare function createUntrustedContentGuardrail(options: {
718
+ /** Guardrail to apply to untrusted sections */
719
+ baseGuardrail?: GuardrailFn<InputGuardrailData>;
720
+ /** Block if untrusted content contains these patterns */
721
+ additionalPatterns?: InjectionPattern[];
722
+ }): GuardrailFn<InputGuardrailData>;
723
+
724
+ /**
725
+ * Approximate Nearest Neighbor (ANN) Index for Semantic Cache
726
+ *
727
+ * Provides pluggable vector search backends for efficient similarity lookups.
728
+ * Includes a brute-force exact search and a VP-tree (Vantage Point Tree) for
729
+ * fast approximate nearest neighbor queries.
730
+ *
731
+ * @example
732
+ * ```typescript
733
+ * import { createSemanticCache } from '@directive-run/ai';
734
+ * import { createVPTreeIndex } from '@directive-run/ai';
735
+ *
736
+ * const index = createVPTreeIndex();
737
+ *
738
+ * const cache = createSemanticCache({
739
+ * embedder: myEmbedder,
740
+ * annIndex: index,
741
+ * });
742
+ * ```
743
+ */
744
+
745
+ /** Search result from an ANN index */
746
+ interface ANNSearchResult {
747
+ /** ID of the matched item */
748
+ id: number;
749
+ /** Similarity score (0-1, higher is more similar) */
750
+ similarity: number;
751
+ }
752
+ /** ANN Index interface - pluggable vector search backend */
753
+ interface ANNIndex {
754
+ /** Add a vector to the index */
755
+ add(id: number, embedding: Embedding): void;
756
+ /** Remove a vector from the index */
757
+ remove(id: number): void;
758
+ /** Search for the k nearest neighbors */
759
+ search(query: Embedding, k: number, threshold?: number): ANNSearchResult[];
760
+ /** Rebuild the index (call after batch additions) */
761
+ rebuild(): void;
762
+ /** Get the number of indexed vectors */
763
+ size(): number;
764
+ /** Clear the index */
765
+ clear(): void;
766
+ /** Check if the index needs to be rebuilt (e.g., after additions/removals) */
767
+ needsRebuild(): boolean;
768
+ }
769
+ /**
770
+ * Create a brute-force exact search index.
771
+ *
772
+ * O(n) search, O(1) add/remove. Best for small collections (< 10,000 vectors).
773
+ *
774
+ * @example
775
+ * ```typescript
776
+ * const index = createBruteForceIndex();
777
+ * index.add(0, [0.1, 0.2, 0.3]);
778
+ * index.add(1, [0.4, 0.5, 0.6]);
779
+ *
780
+ * const results = index.search([0.1, 0.2, 0.3], 1);
781
+ * // [{ id: 0, similarity: 1.0 }]
782
+ * ```
783
+ */
784
+ declare function createBruteForceIndex(): ANNIndex;
785
+ /** VP-Tree index configuration */
786
+ interface VPTreeIndexConfig {
787
+ /** Optional random number generator for deterministic builds. Returns a number in [0, 1). */
788
+ random?: () => number;
789
+ }
790
+ /**
791
+ * Create a VP-Tree (Vantage Point Tree) index for efficient approximate nearest neighbor search.
792
+ *
793
+ * O(log n) search on average, requires rebuild after batch additions.
794
+ * Best for medium collections (1,000 - 100,000 vectors).
795
+ *
796
+ * @example
797
+ * ```typescript
798
+ * const index = createVPTreeIndex();
799
+ *
800
+ * // Add vectors
801
+ * for (let i = 0; i < embeddings.length; i++) {
802
+ * index.add(i, embeddings[i]);
803
+ * }
804
+ *
805
+ * // Build the tree
806
+ * index.rebuild();
807
+ *
808
+ * // Search
809
+ * const results = index.search(queryEmbedding, 5, 0.9);
810
+ * ```
811
+ */
812
+ declare function createVPTreeIndex(vpConfig?: VPTreeIndexConfig): ANNIndex;
813
+
814
+ export { type ANNIndex, type ANNSearchResult, DEFAULT_INJECTION_PATTERNS, type DetectedPII, Embedding, type EnhancedPIIGuardrailOptions, type FactPIICategory, type FactPIIGuardrailMode, type FactPIIGuardrailOptions, type FactPIIMatch, type InjectionDetectionResult, type PIIDetectionResult, type PIIDetector, type PIIType, type PromptInjectionGuardrailOptions, type RateLimitGuardrail, type RedactionStyle, STRICT_INJECTION_PATTERNS, type VPTreeIndexConfig, createBruteForceIndex, createContentFilterGuardrail, createEnhancedPIIGuardrail, createFactPIIGuardrail, createLengthGuardrail, createModerationGuardrail, createOutputPIIGuardrail, createOutputSchemaGuardrail, createOutputTypeGuardrail, createPIIGuardrail, createPromptInjectionGuardrail, createRateLimitGuardrail, createToolGuardrail, createUntrustedContentGuardrail, createVPTreeIndex, detectAndRedactPII, detectPII, detectPromptInjection, markUntrustedContent, redactPII, sanitizeInjection };