@directive-run/ai 1.20.1 → 1.21.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.
@@ -1,817 +1,4 @@
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';
4
- import { Plugin } from '@directive-run/core';
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>;
217
-
218
- /**
219
- * Fact-PII Guardrail — input guardrail at the fact-store boundary
220
- *
221
- * Closes the source → fact → agent prompt PII bypass surfaced by R5's
222
- * red-team / privacy / AI-integration reviewers: `createPIIGuardrail`
223
- * only inspects the `data.input` string at runStream entry, so PII that
224
- * a source publishes into a fact (a Supabase realtime row carrying a
225
- * customer email, a webhook payload with a SSN, an MCP server's
226
- * resource notification with a card number) reaches the agent's
227
- * prompt — via fact injection — without ever hitting the input
228
- * guardrail chain.
229
- *
230
- * This plugin runs as a Directive plugin (`onFactSet` / `onFactsBatch`),
231
- * scans every write to a pii-tagged fact against a sync regex matcher
232
- * for the three highest-volume PII categories (SSN, credit card, email),
233
- * and either **redacts** the value (the default — safe shipping posture)
234
- * or **rejects** the write (throws so the source's publish handler can
235
- * surface the violation). Operators wire it once at `createSystem`; no
236
- * per-source / per-fact changes are required.
237
- *
238
- * The async PII detector from `pii-enhanced.ts` is unsuitable here:
239
- * `onFactSet` is synchronous and a deferred detection would let the
240
- * raw PII reach observers + breakpoints + audit-ledger before the
241
- * redaction completed. Built-in matching is therefore inlined as
242
- * synchronous regex. Consumers who need richer detection pass a
243
- * synchronous `customDetector`.
244
- *
245
- * @example Defensive (redact PII writes into pii-tagged facts)
246
- * ```ts
247
- * import { createSystem, t } from '@directive-run/core';
248
- * import { createFactPIIGuardrail } from '@directive-run/ai/guardrails';
249
- *
250
- * const customer = createModule('customer', {
251
- * schema: {
252
- * facts: {
253
- * email: t.string().meta({ tags: ['pii'] }),
254
- * ssn: t.string().meta({ tags: ['pii'] }),
255
- * },
256
- * },
257
- * sources: {
258
- * supabase: { attach: (publish) => subscribe(publish) },
259
- * },
260
- * });
261
- *
262
- * const system = createSystem({
263
- * module: customer,
264
- * plugins: [
265
- * createFactPIIGuardrail({
266
- * mode: 'redact',
267
- * onBlocked: (key, detected) => {
268
- * console.warn(`[fact-pii] redacted ${detected.length} match(es) in ${key}`);
269
- * },
270
- * }),
271
- * ],
272
- * });
273
- * ```
274
- *
275
- * @example Monitor-only (alert on every PII match; don't mutate the fact)
276
- * ```ts
277
- * createFactPIIGuardrail({
278
- * mode: 'alert',
279
- * onBlocked: (key) => Sentry.captureException(new Error(`pii match: ${key}`)),
280
- * });
281
- * ```
282
- *
283
- * @example Allow specific keys (not just by tag)
284
- * ```ts
285
- * createFactPIIGuardrail({
286
- * includeKeys: ['customer.email', 'customer.phone'],
287
- * });
288
- * ```
289
- */
290
-
291
- /**
292
- * Public match record for a single PII finding. Mirrors `DetectedPII` from
293
- * `pii-enhanced.ts` so a downstream guardrail can normalize against either
294
- * detection path.
295
- */
296
- interface FactPIIMatch {
297
- type: FactPIICategory;
298
- value: string;
299
- start: number;
300
- end: number;
301
- }
302
- /** PII categories the built-in synchronous detector covers. */
303
- type FactPIICategory = "ssn" | "credit_card" | "email";
304
- /**
305
- * Behavior when a pii-tagged fact's incoming value contains detected PII.
306
- *
307
- * - `"redact"` (default): the fact is rewritten with redacted text (e.g.
308
- * `"[SSN]"`) via a follow-up store write. The system briefly observes
309
- * the raw value during the same microtask the publish landed in, then
310
- * the redacted value overwrites it before any reconcile / agent runs.
311
- * Safe shipping posture for production: the LLM call always sees the
312
- * redacted value.
313
- * - `"alert"`: fire `onBlocked` but DO NOT mutate the fact. The raw value
314
- * stays in the store. Use this for monitoring-only deployments where
315
- * the source's transport is already trusted but a regression detector
316
- * is needed (paging ops on every match).
317
- *
318
- * Note: Directive plugin hooks (`onFactSet`, `onFactsBatch`) are
319
- * wrapped by the plugin manager's `safeCall` so a throw from inside the
320
- * hook is swallowed. The guardrail therefore cannot reject the write
321
- * itself — it can only observe + redact-via-followup-write or alert.
322
- * For hard rejection at the publish boundary, a future RFC will add a
323
- * pre-commit transform hook on the source primitive.
324
- */
325
- type FactPIIGuardrailMode = "redact" | "alert";
326
- interface FactPIIGuardrailOptions {
327
- /** Default: `"redact"` */
328
- mode?: FactPIIGuardrailMode;
329
- /**
330
- * Built-in categories to scan for. Default: all three (`ssn`,
331
- * `credit_card`, `email`). Pass `[]` to opt out of the built-ins and
332
- * rely entirely on `customDetector`.
333
- */
334
- types?: readonly FactPIICategory[];
335
- /**
336
- * Specific fact keys to scan in addition to the auto-detected
337
- * `pii`-tagged set. Useful when a consumer can't change the schema's
338
- * meta but knows the key should be screened.
339
- */
340
- includeKeys?: readonly string[];
341
- /**
342
- * Exclude these fact keys even if they're pii-tagged. Escape hatch for
343
- * a key that's already pre-sanitized upstream of the manager.
344
- */
345
- excludeKeys?: readonly string[];
346
- /**
347
- * Called whenever the guardrail detects PII and acts on it. Receives the
348
- * fact key, the detected matches, and the action that was taken. Fires
349
- * AFTER redact + before any throw in `reject` mode. Use this to alert
350
- * SREs without coupling the guardrail to a specific logging backend.
351
- */
352
- onBlocked?: (key: string, detected: readonly FactPIIMatch[], action: FactPIIGuardrailMode) => void;
353
- /**
354
- * Custom synchronous detector that runs alongside the built-in regex
355
- * scanner. The union of detections is acted on. Useful when the
356
- * consumer ships a domain-specific PII detector (e.g. internal
357
- * account-number format). MUST be synchronous — `onFactSet` cannot
358
- * await deferred work.
359
- */
360
- customDetector?: (text: string) => readonly FactPIIMatch[];
361
- /**
362
- * Maximum nesting depth to walk when scanning a structured fact
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`.
369
- *
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`.
379
- *
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.
384
- *
385
- * **Hard caps for safety:**
386
- * - `walkDepth` clamps to `[1, 5]`. Non-finite values (`NaN`,
387
- * `Infinity`, non-number casts) clamp to `1`.
388
- * - The walker caps any single array's element count at 10,000
389
- * (warns + truncates). Pass a `customDetector` for larger
390
- * payloads.
391
- * - Before walking, the value is passed through `structuredClone`
392
- * to strip any Proxies, exotic getters, Symbol-iterator
393
- * overrides, and functions the consumer might have attached.
394
- * Cyclic inputs throw `DataCloneError` from `structuredClone`
395
- * and the walker treats them as "no match" with a warning.
396
- * Non-cloneable values (functions, DOM nodes, WeakMaps, etc.)
397
- * throw the same way — wire a `customDetector` for those shapes.
398
- *
399
- * Property iteration uses `Object.entries`, which skips
400
- * Symbol-keyed properties and non-enumerable string keys. If you
401
- * store PII under a Symbol key (unusual), a `customDetector` is the
402
- * right escape hatch.
403
- */
404
- walkDepth?: number;
405
- }
406
- /**
407
- * Create a Directive plugin that scans pii-tagged fact writes for PII and
408
- * redacts or rejects them at the manager boundary.
409
- *
410
- * Wire it once at `createSystem({ plugins: [...] })`. The plugin caches
411
- * the pii-tagged key set on `onInit` so per-write hooks are O(1) lookups.
412
- *
413
- * @returns a `Plugin` instance ready to add to `SystemConfig.plugins`.
414
- */
415
- declare function createFactPIIGuardrail(options?: FactPIIGuardrailOptions): Plugin;
416
-
417
- /**
418
- * Enhanced PII Detection Guardrail
419
- *
420
- * Provides comprehensive PII detection beyond basic regex patterns:
421
- * - Multiple PII types (SSN, credit cards, emails, phones, addresses, names)
422
- * - Pluggable detection backends (regex, custom, or external services)
423
- * - Context-aware detection (reduces false positives)
424
- * - Redaction with reversible or irreversible options
425
- *
426
- * @example
427
- * ```typescript
428
- * import { createEnhancedPIIGuardrail } from '@directive-run/ai';
429
- *
430
- * const guardrail = createEnhancedPIIGuardrail({
431
- * types: ['ssn', 'credit_card', 'email'],
432
- * redact: true,
433
- * detector: 'regex', // or 'custom' with custom detector
434
- * });
435
- * ```
436
- */
437
-
438
- /** Supported PII types */
439
- type PIIType = "ssn" | "credit_card" | "email" | "phone" | "address" | "name" | "date_of_birth" | "passport" | "driver_license" | "ip_address" | "bank_account" | "medical_id" | "national_id";
440
- /** Detected PII instance */
441
- interface DetectedPII {
442
- type: PIIType;
443
- value: string;
444
- position: {
445
- start: number;
446
- end: number;
447
- };
448
- confidence: number;
449
- context?: string;
450
- }
451
- /** PII detection result */
452
- interface PIIDetectionResult {
453
- detected: boolean;
454
- items: DetectedPII[];
455
- typeCounts: Partial<Record<PIIType, number>>;
456
- /** Text with PII redacted (if requested) */
457
- redactedText?: string;
458
- }
459
- /** Custom PII detector interface */
460
- interface PIIDetector {
461
- detect(text: string, types: PIIType[]): Promise<DetectedPII[]>;
462
- name: string;
463
- }
464
- /** Redaction style */
465
- type RedactionStyle =
466
- /** Replace with [REDACTED] */
467
- "placeholder"
468
- /** Replace with type-specific placeholder like [EMAIL] */
469
- | "typed"
470
- /**
471
- * Replace with a fixed-width `****` mask plus the last 4 characters
472
- * (e.g. `****6789`). Does not preserve or reveal the original length.
473
- */
474
- | "masked"
475
- /**
476
- * Replace with a deterministic FNV-1a hash.
477
- *
478
- * **WARNING — this is PSEUDONYMIZATION, not anonymization.** FNV-1a is a
479
- * fast, non-cryptographic 32-bit hash. For low-entropy structured PII (SSNs,
480
- * card numbers, phone numbers) the output is trivially RE-IDENTIFIABLE via
481
- * brute force or a precomputed rainbow table. It MUST NOT be relied on for
482
- * GDPR / HIPAA de-identification. Use it only for referential integrity
483
- * (correlating the same value across audit logs).
484
- */
485
- | "hashed";
486
- /** Redact detected PII from text */
487
- declare function redactPII(text: string, items: DetectedPII[], style?: RedactionStyle): string;
488
- /** Options for enhanced PII guardrail */
489
- interface EnhancedPIIGuardrailOptions {
490
- /** PII types to detect (default: all) */
491
- types?: PIIType[];
492
- /** Detection backend (default: 'regex') */
493
- detector?: "regex" | PIIDetector;
494
- /** Redact instead of blocking */
495
- redact?: boolean;
496
- /** Redaction style (default: 'typed') */
497
- redactionStyle?: RedactionStyle;
498
- /** Minimum confidence to flag (0-1, default: 0.7) */
499
- minConfidence?: number;
500
- /** Callback when PII is detected */
501
- onDetected?: (items: DetectedPII[]) => void;
502
- /** Allow specific values (whitelist) */
503
- allowlist?: string[];
504
- /** Block only if count exceeds threshold */
505
- minItemsToBlock?: number;
506
- /** Timeout for custom detector in milliseconds (default: 5000) */
507
- detectorTimeout?: number;
508
- }
509
- /**
510
- * Create an enhanced PII detection guardrail.
511
- *
512
- * @example
513
- * ```typescript
514
- * // Basic usage
515
- * const guardrail = createEnhancedPIIGuardrail();
516
- *
517
- * // Redact instead of blocking
518
- * const redactGuardrail = createEnhancedPIIGuardrail({
519
- * redact: true,
520
- * redactionStyle: 'masked',
521
- * });
522
- *
523
- * // Custom detection with external service
524
- * const customGuardrail = createEnhancedPIIGuardrail({
525
- * detector: myPresidioDetector,
526
- * types: ['ssn', 'credit_card', 'medical_id'],
527
- * });
528
- * ```
529
- */
530
- declare function createEnhancedPIIGuardrail(options?: EnhancedPIIGuardrailOptions): GuardrailFn<InputGuardrailData>;
531
- /**
532
- * Create an output PII guardrail (for checking agent responses).
533
- *
534
- * @example
535
- * ```typescript
536
- * const outputGuardrail = createOutputPIIGuardrail({
537
- * types: ['ssn', 'credit_card'],
538
- * redact: true,
539
- * });
540
- * ```
541
- */
542
- declare function createOutputPIIGuardrail(options?: EnhancedPIIGuardrailOptions): GuardrailFn<OutputGuardrailData>;
543
- /**
544
- * Detect PII in text without using as a guardrail.
545
- * Useful for analysis and logging.
546
- *
547
- * @example
548
- * ```typescript
549
- * const result = await detectPII('My SSN is 123-45-6789');
550
- * console.log(result.items); // [{ type: 'ssn', value: '123-45-6789', ... }]
551
- *
552
- * // With custom detector and timeout
553
- * const result = await detectPII(text, {
554
- * detector: myPresidioDetector,
555
- * timeout: 10000, // 10 seconds
556
- * });
557
- * ```
558
- */
559
- declare function detectPII(text: string, options?: {
560
- types?: PIIType[];
561
- detector?: "regex" | PIIDetector;
562
- minConfidence?: number;
563
- /** Timeout for custom detectors in milliseconds (default: 5000) */
564
- timeout?: number;
565
- }): Promise<PIIDetectionResult>;
566
- /**
567
- * Detect PII in text and return a result whose `redactedText` is populated.
568
- *
569
- * This composes {@link detectPII} and {@link redactPII} so callers do not have
570
- * to manually wire the two together (and do not have to mutate the detection
571
- * result). When no PII is detected, `redactedText` is left `undefined` — it is
572
- * deliberately NOT defaulted to the raw input.
573
- *
574
- * @example
575
- * ```typescript
576
- * const result = await detectAndRedactPII('My SSN is 123-45-6789', {
577
- * types: ['ssn'],
578
- * style: 'typed',
579
- * });
580
- * console.log(result.detected); // true
581
- * // ssn is a sensitive-category type, so `typed` emits a generic [REDACTED]
582
- * console.log(result.redactedText); // 'My SSN is [REDACTED]'
583
- *
584
- * const clean = await detectAndRedactPII('nothing here', { types: ['ssn'] });
585
- * console.log(clean.detected); // false
586
- * console.log(clean.redactedText); // undefined
587
- * ```
588
- */
589
- declare function detectAndRedactPII(text: string, options?: {
590
- types?: PIIType[];
591
- detector?: "regex" | PIIDetector;
592
- minConfidence?: number;
593
- /** Timeout for custom detectors in milliseconds (default: 5000) */
594
- timeout?: number;
595
- /** Redaction style applied when PII is detected (default: 'typed') */
596
- style?: RedactionStyle;
597
- }): Promise<PIIDetectionResult>;
598
-
599
- /**
600
- * Prompt Injection Detection Guardrail
601
- *
602
- * Detects and blocks prompt injection attacks including:
603
- * - Direct injection attempts ("ignore previous instructions")
604
- * - Jailbreak patterns ("DAN mode", "pretend you can")
605
- * - Indirect injection via external content
606
- * - Encoding-based evasion attempts
607
- *
608
- * @example
609
- * ```typescript
610
- * import { createPromptInjectionGuardrail } from '@directive-run/ai';
611
- *
612
- * const guardrail = createPromptInjectionGuardrail({
613
- * strictMode: true,
614
- * onBlocked: (input, patterns) => logSecurityEvent(input, patterns),
615
- * });
616
- * ```
617
- */
618
-
619
- /** Pattern with metadata for better debugging */
620
- interface InjectionPattern {
621
- pattern: RegExp;
622
- name: string;
623
- severity: "low" | "medium" | "high" | "critical";
624
- category: InjectionCategory;
625
- }
626
- /** Categories of injection attacks */
627
- type InjectionCategory = "instruction_override" | "jailbreak" | "role_manipulation" | "encoding_evasion" | "delimiter_injection" | "context_manipulation" | "indirect_injection";
628
- /** Default injection patterns - well-tested and low false-positive rate */
629
- declare const DEFAULT_INJECTION_PATTERNS: InjectionPattern[];
630
- /** Strict patterns - more aggressive, may have higher false positives */
631
- declare const STRICT_INJECTION_PATTERNS: InjectionPattern[];
632
- /** Detailed detection result */
633
- interface InjectionDetectionResult {
634
- detected: boolean;
635
- patterns: Array<{
636
- name: string;
637
- category: InjectionCategory;
638
- severity: InjectionPattern["severity"];
639
- match: string;
640
- position: number;
641
- }>;
642
- riskScore: number;
643
- sanitizedInput?: string;
644
- }
645
- /**
646
- * Detect prompt injection patterns in text.
647
- * Returns detailed results about what was detected.
648
- *
649
- * @throws Error if input exceeds MAX_INJECTION_INPUT_LENGTH (100KB)
650
- */
651
- declare function detectPromptInjection(text: string, patterns?: InjectionPattern[]): InjectionDetectionResult;
652
- /**
653
- * Sanitize text by removing detected injection patterns.
654
- * Warning: This is a best-effort sanitization, not a security guarantee.
655
- *
656
- * Uses a single-pass approach to prevent infinite loops where a replacement
657
- * could create a new pattern match.
658
- */
659
- declare function sanitizeInjection(text: string, patterns?: InjectionPattern[]): string;
660
- /** Options for prompt injection guardrail */
661
- interface PromptInjectionGuardrailOptions {
662
- /** Additional patterns to check (added to defaults) */
663
- additionalPatterns?: InjectionPattern[];
664
- /** Replace default patterns entirely */
665
- replacePatterns?: InjectionPattern[];
666
- /** Use strict mode with more aggressive detection */
667
- strictMode?: boolean;
668
- /** Minimum risk score to block (0-100, default: 50) */
669
- blockThreshold?: number;
670
- /** Attempt to sanitize instead of blocking */
671
- sanitize?: boolean;
672
- /** Callback when injection is detected */
673
- onBlocked?: (input: string, result: InjectionDetectionResult) => void;
674
- /** Categories to ignore (e.g., allow 'role_manipulation' for roleplay apps) */
675
- ignoreCategories?: InjectionCategory[];
676
- }
677
- /**
678
- * Create a prompt injection detection guardrail.
679
- *
680
- * @example
681
- * ```typescript
682
- * // Basic usage
683
- * const guardrail = createPromptInjectionGuardrail();
684
- *
685
- * // Strict mode for high-security applications
686
- * const strictGuardrail = createPromptInjectionGuardrail({
687
- * strictMode: true,
688
- * blockThreshold: 25,
689
- * });
690
- *
691
- * // Allow role manipulation for roleplay apps
692
- * const roleplayGuardrail = createPromptInjectionGuardrail({
693
- * ignoreCategories: ['role_manipulation'],
694
- * });
695
- * ```
696
- */
697
- declare function createPromptInjectionGuardrail(options?: PromptInjectionGuardrailOptions): GuardrailFn<InputGuardrailData>;
698
- /**
699
- * Mark content as potentially untrusted (from external sources).
700
- * This wraps the content with markers that injection detection will scrutinize more closely.
701
- *
702
- * @example
703
- * ```typescript
704
- * const userUpload = await readFile(path);
705
- * const markedContent = markUntrustedContent(userUpload, 'user-upload');
706
- * const prompt = `Summarize this document: ${markedContent}`;
707
- * ```
708
- */
709
- declare function markUntrustedContent(content: string, source: string): string;
710
- /**
711
- * Create a guardrail that applies stricter checks to marked untrusted content.
712
- *
713
- * @example
714
- * ```typescript
715
- * const guardrail = createUntrustedContentGuardrail({
716
- * baseGuardrail: createPromptInjectionGuardrail({ strictMode: true }),
717
- * });
718
- * ```
719
- */
720
- declare function createUntrustedContentGuardrail(options: {
721
- /** Guardrail to apply to untrusted sections */
722
- baseGuardrail?: GuardrailFn<InputGuardrailData>;
723
- /** Block if untrusted content contains these patterns */
724
- additionalPatterns?: InjectionPattern[];
725
- }): GuardrailFn<InputGuardrailData>;
726
-
727
- /**
728
- * Approximate Nearest Neighbor (ANN) Index for Semantic Cache
729
- *
730
- * Provides pluggable vector search backends for efficient similarity lookups.
731
- * Includes a brute-force exact search and a VP-tree (Vantage Point Tree) for
732
- * fast approximate nearest neighbor queries.
733
- *
734
- * @example
735
- * ```typescript
736
- * import { createSemanticCache } from '@directive-run/ai';
737
- * import { createVPTreeIndex } from '@directive-run/ai';
738
- *
739
- * const index = createVPTreeIndex();
740
- *
741
- * const cache = createSemanticCache({
742
- * embedder: myEmbedder,
743
- * annIndex: index,
744
- * });
745
- * ```
746
- */
747
-
748
- /** Search result from an ANN index */
749
- interface ANNSearchResult {
750
- /** ID of the matched item */
751
- id: number;
752
- /** Similarity score (0-1, higher is more similar) */
753
- similarity: number;
754
- }
755
- /** ANN Index interface - pluggable vector search backend */
756
- interface ANNIndex {
757
- /** Add a vector to the index */
758
- add(id: number, embedding: Embedding): void;
759
- /** Remove a vector from the index */
760
- remove(id: number): void;
761
- /** Search for the k nearest neighbors */
762
- search(query: Embedding, k: number, threshold?: number): ANNSearchResult[];
763
- /** Rebuild the index (call after batch additions) */
764
- rebuild(): void;
765
- /** Get the number of indexed vectors */
766
- size(): number;
767
- /** Clear the index */
768
- clear(): void;
769
- /** Check if the index needs to be rebuilt (e.g., after additions/removals) */
770
- needsRebuild(): boolean;
771
- }
772
- /**
773
- * Create a brute-force exact search index.
774
- *
775
- * O(n) search, O(1) add/remove. Best for small collections (< 10,000 vectors).
776
- *
777
- * @example
778
- * ```typescript
779
- * const index = createBruteForceIndex();
780
- * index.add(0, [0.1, 0.2, 0.3]);
781
- * index.add(1, [0.4, 0.5, 0.6]);
782
- *
783
- * const results = index.search([0.1, 0.2, 0.3], 1);
784
- * // [{ id: 0, similarity: 1.0 }]
785
- * ```
786
- */
787
- declare function createBruteForceIndex(): ANNIndex;
788
- /** VP-Tree index configuration */
789
- interface VPTreeIndexConfig {
790
- /** Optional random number generator for deterministic builds. Returns a number in [0, 1). */
791
- random?: () => number;
792
- }
793
- /**
794
- * Create a VP-Tree (Vantage Point Tree) index for efficient approximate nearest neighbor search.
795
- *
796
- * O(log n) search on average, requires rebuild after batch additions.
797
- * Best for medium collections (1,000 - 100,000 vectors).
798
- *
799
- * @example
800
- * ```typescript
801
- * const index = createVPTreeIndex();
802
- *
803
- * // Add vectors
804
- * for (let i = 0; i < embeddings.length; i++) {
805
- * index.add(i, embeddings[i]);
806
- * }
807
- *
808
- * // Build the tree
809
- * index.rebuild();
810
- *
811
- * // Search
812
- * const results = index.search(queryEmbedding, 5, 0.9);
813
- * ```
814
- */
815
- declare function createVPTreeIndex(vpConfig?: VPTreeIndexConfig): ANNIndex;
816
-
817
- 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 };
1
+ export { A as ANNIndex, a as ANNSearchResult, D as DEFAULT_INJECTION_PATTERNS, b as DetectedPII, E as EnhancedPIIGuardrailOptions, F as FactPIICategory, d as FactPIIGuardrailMode, e as FactPIIGuardrailOptions, f as FactPIIMatch, I as InjectionDetectionResult, g as PIIDetectionResult, h as PIIDetector, P as PIIType, i as PromptInjectionGuardrailOptions, j as RateLimitGuardrail, R as RedactionStyle, S as STRICT_INJECTION_PATTERNS, V as VPTreeIndexConfig, k as createBruteForceIndex, l as createContentFilterGuardrail, m as createEnhancedPIIGuardrail, n as createFactPIIGuardrail, o as createLengthGuardrail, p as createModerationGuardrail, q as createOutputPIIGuardrail, r as createOutputSchemaGuardrail, s as createOutputTypeGuardrail, t as createPIIGuardrail, u as createPromptInjectionGuardrail, v as createRateLimitGuardrail, w as createToolGuardrail, x as createUntrustedContentGuardrail, y as createVPTreeIndex, z as detectAndRedactPII, B as detectPII, C as detectPromptInjection, G as markUntrustedContent, H as redactPII, J as sanitizeInjection } from './guardrails-export-CxCOi3sd.js';
2
+ export { B as BatchedEmbedder, C as CacheEntry, b as CacheLookupResult, c as CacheStats, E as EmbedderFn, a 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-DM7ev7NQ.js';
3
+ import './types-DJ09LjZX.js';
4
+ import '@directive-run/core';