@framers/agentos-ext-ml-classifiers 0.1.0 → 0.2.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 (51) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/MLClassifierGuardrail.d.ts +88 -117
  3. package/dist/MLClassifierGuardrail.d.ts.map +1 -1
  4. package/dist/MLClassifierGuardrail.js +255 -264
  5. package/dist/MLClassifierGuardrail.js.map +1 -1
  6. package/dist/classifiers/InjectionClassifier.d.ts +1 -1
  7. package/dist/classifiers/InjectionClassifier.d.ts.map +1 -1
  8. package/dist/classifiers/JailbreakClassifier.d.ts +1 -1
  9. package/dist/classifiers/JailbreakClassifier.d.ts.map +1 -1
  10. package/dist/classifiers/ToxicityClassifier.d.ts +1 -1
  11. package/dist/classifiers/ToxicityClassifier.d.ts.map +1 -1
  12. package/dist/classifiers/WorkerClassifierProxy.d.ts +1 -1
  13. package/dist/classifiers/WorkerClassifierProxy.d.ts.map +1 -1
  14. package/dist/index.d.ts +16 -90
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +33 -306
  17. package/dist/index.js.map +1 -1
  18. package/dist/keyword-classifier.d.ts +26 -0
  19. package/dist/keyword-classifier.d.ts.map +1 -0
  20. package/dist/keyword-classifier.js +113 -0
  21. package/dist/keyword-classifier.js.map +1 -0
  22. package/dist/llm-classifier.d.ts +27 -0
  23. package/dist/llm-classifier.d.ts.map +1 -0
  24. package/dist/llm-classifier.js +129 -0
  25. package/dist/llm-classifier.js.map +1 -0
  26. package/dist/tools/ClassifyContentTool.d.ts +53 -80
  27. package/dist/tools/ClassifyContentTool.d.ts.map +1 -1
  28. package/dist/tools/ClassifyContentTool.js +52 -103
  29. package/dist/tools/ClassifyContentTool.js.map +1 -1
  30. package/dist/types.d.ts +77 -277
  31. package/dist/types.d.ts.map +1 -1
  32. package/dist/types.js +9 -55
  33. package/dist/types.js.map +1 -1
  34. package/package.json +10 -16
  35. package/src/MLClassifierGuardrail.ts +279 -316
  36. package/src/index.ts +35 -339
  37. package/src/keyword-classifier.ts +130 -0
  38. package/src/llm-classifier.ts +163 -0
  39. package/src/tools/ClassifyContentTool.ts +75 -132
  40. package/src/types.ts +78 -325
  41. package/test/ClassifierOrchestrator.spec.ts +365 -0
  42. package/test/ClassifyContentTool.spec.ts +226 -0
  43. package/test/InjectionClassifier.spec.ts +263 -0
  44. package/test/JailbreakClassifier.spec.ts +295 -0
  45. package/test/MLClassifierGuardrail.spec.ts +486 -0
  46. package/test/SlidingWindowBuffer.spec.ts +391 -0
  47. package/test/ToxicityClassifier.spec.ts +268 -0
  48. package/test/WorkerClassifierProxy.spec.ts +303 -0
  49. package/test/index.spec.ts +431 -0
  50. package/tsconfig.json +20 -0
  51. package/vitest.config.ts +24 -0
@@ -1,419 +1,382 @@
1
1
  /**
2
- * @fileoverview IGuardrailService implementation backed by ML classifiers.
2
+ * @file MLClassifierGuardrail.ts
3
+ * @description IGuardrailService implementation that classifies text for toxicity,
4
+ * prompt injection, NSFW content, and threats using a three-tier strategy:
3
5
  *
4
- * `MLClassifierGuardrail` bridges the AgentOS guardrail pipeline to the ML
5
- * classifier subsystem. It implements both `evaluateInput` (full-text
6
- * classification of user messages) and `evaluateOutput` (sliding-window
7
- * classification of streamed agent responses).
6
+ * 1. **ONNX inference** attempts to load `@huggingface/transformers` at runtime
7
+ * and run a lightweight ONNX classification model.
8
+ * 2. **LLM-as-judge** falls back to an LLM invoker callback that prompts a
9
+ * language model for structured JSON safety classification.
10
+ * 3. **Keyword matching** — last-resort regex/keyword-based detection when neither
11
+ * ONNX nor LLM are available.
8
12
  *
9
- * Three streaming evaluation modes are supported:
13
+ * The guardrail is configured as Phase 2 (parallel, non-sanitizing) so it runs
14
+ * alongside other read-only guardrails without blocking the streaming pipeline.
10
15
  *
11
- * | Mode | Behaviour |
12
- * |---------------|----------------------------------------------------------------|
13
- * | `blocking` | Every chunk that fills the sliding window is classified |
14
- * | | **synchronously** — the stream waits for the result. |
15
- * | `non-blocking`| Classification fires in the background; violations are surfaced |
16
- * | | on the **next** `evaluateOutput` call for the same stream. |
17
- * | `hybrid` | The first chunk for each stream is blocking; subsequent chunks |
18
- * | | switch to non-blocking for lower latency. |
16
+ * ### Action thresholds
19
17
  *
20
- * The default mode is `blocking` when `streamingMode` is enabled.
18
+ * - **FLAG** when any category confidence exceeds `flagThreshold` (default 0.5).
19
+ * - **BLOCK** when any category confidence exceeds `blockThreshold` (default 0.8).
21
20
  *
22
- * @module agentos/extensions/packs/ml-classifiers/MLClassifierGuardrail
21
+ * @module ml-classifiers/MLClassifierGuardrail
23
22
  */
24
23
 
25
24
  import type {
25
+ IGuardrailService,
26
26
  GuardrailConfig,
27
- GuardrailEvaluationResult,
28
27
  GuardrailInputPayload,
29
28
  GuardrailOutputPayload,
30
- IGuardrailService,
29
+ GuardrailEvaluationResult,
31
30
  } from '@framers/agentos';
32
31
  import { GuardrailAction } from '@framers/agentos';
33
32
  import { AgentOSResponseChunkType } from '@framers/agentos';
34
- import type { ISharedServiceRegistry } from '@framers/agentos';
35
- import type { MLClassifierPackOptions, ChunkEvaluation } from './types';
36
- import { DEFAULT_THRESHOLDS } from './types';
37
- import { SlidingWindowBuffer } from './SlidingWindowBuffer';
38
- import { ClassifierOrchestrator } from './ClassifierOrchestrator';
39
- import type { IContentClassifier } from './IContentClassifier';
40
-
41
- // ---------------------------------------------------------------------------
42
- // Streaming mode union
43
- // ---------------------------------------------------------------------------
44
-
45
- /**
46
- * The evaluation strategy used for output (streaming) chunks.
47
- *
48
- * - `blocking` — await classification on every filled window.
49
- * - `non-blocking` — fire classification in the background; surface result later.
50
- * - `hybrid` — first chunk per stream is blocking, rest non-blocking.
51
- */
52
- type StreamingMode = 'blocking' | 'non-blocking' | 'hybrid';
33
+ import type {
34
+ MLClassifierOptions,
35
+ ClassifierCategory,
36
+ ClassifierResult,
37
+ CategoryScore,
38
+ } from './types';
39
+ import { ALL_CATEGORIES } from './types';
40
+ import { classifyByKeywords } from './keyword-classifier';
41
+ import { classifyByLlm } from './llm-classifier';
53
42
 
54
43
  // ---------------------------------------------------------------------------
55
44
  // MLClassifierGuardrail
56
45
  // ---------------------------------------------------------------------------
57
46
 
58
47
  /**
59
- * Guardrail implementation that runs ML classifiers against both user input
60
- * and streamed agent output.
48
+ * AgentOS guardrail that classifies text for safety using ML models, LLM
49
+ * inference, or keyword fallback.
61
50
  *
62
51
  * @implements {IGuardrailService}
63
- *
64
- * @example
65
- * ```typescript
66
- * const guardrail = new MLClassifierGuardrail(serviceRegistry, {
67
- * classifiers: ['toxicity'],
68
- * streamingMode: true,
69
- * chunkSize: 150,
70
- * guardrailScope: 'both',
71
- * });
72
- *
73
- * // Input evaluation — runs classifier on the full user message.
74
- * const inputResult = await guardrail.evaluateInput({ context, input });
75
- *
76
- * // Output evaluation — accumulates tokens, classifies at window boundary.
77
- * const outputResult = await guardrail.evaluateOutput({ context, chunk });
78
- * ```
79
52
  */
80
53
  export class MLClassifierGuardrail implements IGuardrailService {
81
- // -------------------------------------------------------------------------
82
- // IGuardrailService config
83
- // -------------------------------------------------------------------------
54
+ // -----------------------------------------------------------------------
55
+ // IGuardrailService.config
56
+ // -----------------------------------------------------------------------
84
57
 
85
58
  /**
86
- * Guardrail configuration exposed to the AgentOS pipeline.
59
+ * Guardrail configuration.
87
60
  *
88
- * `evaluateStreamingChunks` is always `true` because this guardrail uses
89
- * the sliding window to evaluate output tokens incrementally.
61
+ * - `canSanitize: false` this guardrail does not modify content; it only
62
+ * BLOCKs or FLAGs. This places it in Phase 2 (parallel) of the guardrail
63
+ * dispatcher for better performance.
64
+ * - `evaluateStreamingChunks: false` — only evaluates complete messages, not
65
+ * individual streaming deltas. ML classification on partial text produces
66
+ * unreliable results.
90
67
  */
91
- readonly config: GuardrailConfig;
92
-
93
- // -------------------------------------------------------------------------
94
- // Internal state
95
- // -------------------------------------------------------------------------
68
+ readonly config: GuardrailConfig = {
69
+ canSanitize: false,
70
+ evaluateStreamingChunks: false,
71
+ };
96
72
 
97
- /** The classifier orchestrator that runs all classifiers in parallel. */
98
- private readonly orchestrator: ClassifierOrchestrator;
73
+ // -----------------------------------------------------------------------
74
+ // Private state
75
+ // -----------------------------------------------------------------------
99
76
 
100
- /** Sliding window buffer for accumulating streaming tokens. */
101
- private readonly buffer: SlidingWindowBuffer;
77
+ /** Categories to evaluate. */
78
+ private readonly categories: ClassifierCategory[];
102
79
 
103
- /** Guardrail scope — which direction(s) this guardrail evaluates. */
104
- private readonly scope: 'input' | 'output' | 'both';
80
+ /** Per-category flag thresholds. */
81
+ private readonly flagThresholds: Record<ClassifierCategory, number>;
105
82
 
106
- /** Streaming evaluation strategy for output chunks. */
107
- private readonly streamingMode: StreamingMode;
83
+ /** Per-category block thresholds. */
84
+ private readonly blockThresholds: Record<ClassifierCategory, number>;
108
85
 
109
- /**
110
- * Map of stream IDs to pending (background) classification promises.
111
- * Used in `non-blocking` and `hybrid` modes to defer result checking
112
- * to the next `evaluateOutput` call.
113
- */
114
- private readonly pendingResults: Map<string, Promise<ChunkEvaluation>> = new Map();
86
+ /** Optional LLM invoker callback for tier-2 classification. */
87
+ private readonly llmInvoker: MLClassifierOptions['llmInvoker'];
115
88
 
116
89
  /**
117
- * Tracks whether the first chunk for a given stream has been processed.
118
- * Used by `hybrid` mode to apply blocking evaluation on the first chunk
119
- * and non-blocking for subsequent chunks.
90
+ * Cached reference to the `@huggingface/transformers` pipeline function.
91
+ * `null` means we already tried and failed to load the module.
92
+ * `undefined` means we have not tried yet.
120
93
  */
121
- private readonly isFirstChunk: Map<string, boolean> = new Map();
94
+ private onnxPipeline: any | null | undefined = undefined;
122
95
 
123
- // -------------------------------------------------------------------------
96
+ // -----------------------------------------------------------------------
124
97
  // Constructor
125
- // -------------------------------------------------------------------------
98
+ // -----------------------------------------------------------------------
126
99
 
127
100
  /**
128
- * Create a new ML classifier guardrail.
101
+ * Create a new MLClassifierGuardrail.
129
102
  *
130
- * @param _services - Shared service registry (reserved for future use by
131
- * classifier factories that need lazy model loading).
132
- * @param options - Pack-level options controlling classifier selection,
133
- * thresholds, sliding window size, and streaming mode.
134
- * @param classifiers - Pre-built classifier instances. When provided,
135
- * these are used directly instead of constructing
136
- * classifiers from `options.classifiers`.
103
+ * @param options - Pack-level configuration. All properties have sensible
104
+ * defaults for zero-config operation.
137
105
  */
138
- constructor(
139
- _services: ISharedServiceRegistry,
140
- options: MLClassifierPackOptions,
141
- classifiers: IContentClassifier[] = [],
142
- ) {
143
- // Resolve thresholds: merge caller overrides on top of defaults.
144
- const thresholds = {
145
- ...DEFAULT_THRESHOLDS,
146
- ...options.thresholds,
147
- };
106
+ constructor(options?: MLClassifierOptions) {
107
+ const opts = options ?? {};
148
108
 
149
- // Build the orchestrator from the supplied classifiers.
150
- this.orchestrator = new ClassifierOrchestrator(classifiers, thresholds);
151
-
152
- // Initialise the sliding window buffer for streaming evaluation.
153
- this.buffer = new SlidingWindowBuffer({
154
- chunkSize: options.chunkSize,
155
- contextSize: options.contextSize,
156
- maxEvaluations: options.maxEvaluations,
157
- });
158
-
159
- // Store the guardrail scope (defaults to 'both').
160
- this.scope = options.guardrailScope ?? 'both';
161
-
162
- // Determine streaming mode. When `streamingMode` is enabled the default
163
- // is 'blocking'; callers can override via the `streamingMode` option
164
- // (which we reinterpret as a boolean gate here — advanced callers pass
165
- // a StreamingMode string via `options` when they need finer control).
166
- this.streamingMode = options.streamingMode ? 'blocking' : 'blocking';
167
-
168
- // Expose guardrail config to the pipeline.
169
- this.config = {
170
- evaluateStreamingChunks: true,
171
- maxStreamingEvaluations: options.maxEvaluations ?? 100,
172
- };
109
+ this.categories = opts.categories ?? [...ALL_CATEGORIES];
110
+ this.llmInvoker = opts.llmInvoker;
111
+
112
+ // Resolve per-category thresholds.
113
+ const globalFlag = opts.flagThreshold ?? 0.5;
114
+ const globalBlock = opts.blockThreshold ?? 0.8;
115
+
116
+ this.flagThresholds = {} as Record<ClassifierCategory, number>;
117
+ this.blockThresholds = {} as Record<ClassifierCategory, number>;
118
+
119
+ for (const cat of ALL_CATEGORIES) {
120
+ this.flagThresholds[cat] = opts.thresholds?.[cat]?.flag ?? globalFlag;
121
+ this.blockThresholds[cat] = opts.thresholds?.[cat]?.block ?? globalBlock;
122
+ }
173
123
  }
174
124
 
175
- // -------------------------------------------------------------------------
176
- // evaluateInput
177
- // -------------------------------------------------------------------------
125
+ // -----------------------------------------------------------------------
126
+ // IGuardrailService — evaluateInput
127
+ // -----------------------------------------------------------------------
178
128
 
179
129
  /**
180
- * Evaluate a user's input message before it enters the orchestration pipeline.
181
- *
182
- * Runs the full text through all registered classifiers and returns a
183
- * {@link GuardrailEvaluationResult} when a violation is detected, or
184
- * `null` when the content is clean.
185
- *
186
- * Skipped entirely when `scope === 'output'`.
130
+ * Evaluate user input for safety before orchestration begins.
187
131
  *
188
- * @param payload - The input payload containing user text and context.
189
- * @returns Evaluation result or `null` if no action is needed.
132
+ * @param payload - Input evaluation payload containing the user's message.
133
+ * @returns Guardrail result or `null` if no action is required.
190
134
  */
191
135
  async evaluateInput(payload: GuardrailInputPayload): Promise<GuardrailEvaluationResult | null> {
192
- // Skip input evaluation when scope is output-only.
193
- if (this.scope === 'output') {
194
- return null;
195
- }
196
-
197
- // Extract the text from the input. If there is no text, nothing to classify.
198
136
  const text = payload.input.textInput;
199
- if (!text) {
200
- return null;
201
- }
137
+ if (!text || text.length === 0) return null;
202
138
 
203
- // Run all classifiers against the full user message.
204
- const evaluation = await this.orchestrator.classifyAll(text);
205
-
206
- // Map the evaluation to a guardrail result (null for ALLOW).
207
- return this.evaluationToResult(evaluation);
139
+ const result = await this.classify(text);
140
+ return this.buildResult(result);
208
141
  }
209
142
 
210
- // -------------------------------------------------------------------------
211
- // evaluateOutput
212
- // -------------------------------------------------------------------------
143
+ // -----------------------------------------------------------------------
144
+ // IGuardrailService — evaluateOutput
145
+ // -----------------------------------------------------------------------
213
146
 
214
147
  /**
215
- * Evaluate a streamed output chunk from the agent before it is delivered
216
- * to the client.
217
- *
218
- * The method accumulates text tokens in the sliding window buffer and
219
- * triggers classifier evaluation when a full window is available. The
220
- * evaluation strategy depends on the configured streaming mode.
221
- *
222
- * Skipped entirely when `scope === 'input'`.
148
+ * Evaluate agent output for safety. Only processes FINAL_RESPONSE chunks
149
+ * since `evaluateStreamingChunks` is disabled.
223
150
  *
224
- * @param payload - The output payload containing the response chunk and context.
225
- * @returns Evaluation result or `null` if no action is needed yet.
151
+ * @param payload - Output evaluation payload from the AgentOS dispatcher.
152
+ * @returns Guardrail result or `null` if no action is required.
226
153
  */
227
154
  async evaluateOutput(payload: GuardrailOutputPayload): Promise<GuardrailEvaluationResult | null> {
228
- // Skip output evaluation when scope is input-only.
229
- if (this.scope === 'input') {
230
- return null;
231
- }
155
+ const { chunk } = payload;
232
156
 
233
- const chunk = payload.chunk;
234
-
235
- // Handle final chunks: flush remaining buffer and classify.
236
- if (chunk.isFinal) {
237
- const streamId = chunk.streamId;
238
- const flushed = this.buffer.flush(streamId);
239
-
240
- // Clean up tracking state for this stream.
241
- this.isFirstChunk.delete(streamId);
242
- this.pendingResults.delete(streamId);
243
-
244
- if (!flushed) {
245
- return null;
246
- }
247
-
248
- // Classify the remaining buffered text.
249
- const evaluation = await this.orchestrator.classifyAll(flushed.text);
250
- return this.evaluationToResult(evaluation);
251
- }
252
-
253
- // Only process TEXT_DELTA chunks — ignore tool calls, progress, etc.
254
- if (chunk.type !== AgentOSResponseChunkType.TEXT_DELTA) {
255
- return null;
256
- }
257
-
258
- // Extract the text delta from the chunk.
259
- const textDelta = (chunk as any).textDelta as string | undefined;
260
- if (!textDelta) {
157
+ // Only evaluate final text responses.
158
+ if (chunk.type !== AgentOSResponseChunkType.FINAL_RESPONSE) {
261
159
  return null;
262
160
  }
263
161
 
264
- // Resolve the stream identifier for the sliding window.
265
- const streamId = chunk.streamId;
162
+ const text = (chunk as any).text ?? (chunk as any).content ?? '';
163
+ if (typeof text !== 'string' || text.length === 0) return null;
266
164
 
267
- // Dispatch to the appropriate streaming mode handler.
268
- switch (this.streamingMode) {
269
- case 'non-blocking':
270
- return this.handleNonBlocking(streamId, textDelta);
165
+ const result = await this.classify(text);
166
+ return this.buildResult(result);
167
+ }
271
168
 
272
- case 'hybrid':
273
- return this.handleHybrid(streamId, textDelta);
169
+ // -----------------------------------------------------------------------
170
+ // Public classification method (also used by ClassifyContentTool)
171
+ // -----------------------------------------------------------------------
274
172
 
275
- case 'blocking':
276
- default:
277
- return this.handleBlocking(streamId, textDelta);
173
+ /**
174
+ * Classify a text string using the three-tier strategy: ONNX -> LLM -> keyword.
175
+ *
176
+ * @param text - The text to classify.
177
+ * @returns Classification result with per-category scores.
178
+ */
179
+ async classify(text: string): Promise<ClassifierResult> {
180
+ // Tier 1: try ONNX inference.
181
+ const onnxResult = await this.tryOnnxClassification(text);
182
+ if (onnxResult) return onnxResult;
183
+
184
+ // Tier 2: try LLM-as-judge.
185
+ if (this.llmInvoker) {
186
+ const llmResult = await this.tryLlmClassification(text);
187
+ if (llmResult) return llmResult;
278
188
  }
189
+
190
+ // Tier 3: keyword fallback.
191
+ const scores = classifyByKeywords(text, this.categories);
192
+ return {
193
+ categories: scores,
194
+ flagged: scores.some((s) => s.confidence > this.flagThresholds[s.name]),
195
+ source: 'keyword',
196
+ };
279
197
  }
280
198
 
281
- // -------------------------------------------------------------------------
282
- // Streaming mode handlers
283
- // -------------------------------------------------------------------------
199
+ // -----------------------------------------------------------------------
200
+ // Private ONNX classification (Tier 1)
201
+ // -----------------------------------------------------------------------
284
202
 
285
203
  /**
286
- * **Blocking mode**: push text into the buffer and, when a full window is
287
- * ready, await the classifier result before returning.
204
+ * Attempt to load `@huggingface/transformers` and run ONNX-based text
205
+ * classification. Returns `null` if the module is unavailable or inference
206
+ * fails.
207
+ *
208
+ * The module load is attempted only once; subsequent calls use the cached
209
+ * result (either a working pipeline or `null`).
210
+ *
211
+ * @param text - Text to classify.
212
+ * @returns Classification result or `null`.
288
213
  *
289
- * @param streamId - Identifier of the active stream.
290
- * @param textDelta - New text fragment from the current chunk.
291
- * @returns Evaluation result (possibly BLOCK/FLAG) or `null`.
214
+ * @internal
292
215
  */
293
- private async handleBlocking(
294
- streamId: string,
295
- textDelta: string,
296
- ): Promise<GuardrailEvaluationResult | null> {
297
- const ready = this.buffer.push(streamId, textDelta);
298
- if (!ready) {
299
- return null;
216
+ private async tryOnnxClassification(text: string): Promise<ClassifierResult | null> {
217
+ // If we already know ONNX is unavailable, skip.
218
+ if (this.onnxPipeline === null) return null;
219
+
220
+ // First-time load attempt.
221
+ if (this.onnxPipeline === undefined) {
222
+ try {
223
+ // Dynamic import so the optional dependency does not fail at boot.
224
+ const transformers = await import('@huggingface/transformers');
225
+ this.onnxPipeline = await transformers.pipeline(
226
+ 'text-classification',
227
+ 'Xenova/toxic-bert',
228
+ { device: 'cpu' }
229
+ );
230
+ } catch {
231
+ // Module not installed or model load failed — mark as unavailable.
232
+ this.onnxPipeline = null;
233
+ return null;
234
+ }
300
235
  }
301
236
 
302
- // Classify the filled window synchronously.
303
- const evaluation = await this.orchestrator.classifyAll(ready.text);
304
- return this.evaluationToResult(evaluation);
237
+ try {
238
+ const raw = await this.onnxPipeline(text, { topk: null });
239
+
240
+ // Map ONNX labels to our categories.
241
+ const scores = this.mapOnnxScores(raw);
242
+ return {
243
+ categories: scores,
244
+ flagged: scores.some((s) => s.confidence > this.flagThresholds[s.name]),
245
+ source: 'onnx',
246
+ };
247
+ } catch {
248
+ // Inference failed — fall through to next tier.
249
+ return null;
250
+ }
305
251
  }
306
252
 
307
253
  /**
308
- * **Non-blocking mode**: push text into the buffer. When a window is
309
- * ready, fire classification in the background and store the promise.
310
- * On the **next** `evaluateOutput` call for the same stream, check the
311
- * pending promise — if it resolved with a violation, return that result.
254
+ * Map raw ONNX text-classification output labels to our standard categories.
312
255
  *
313
- * @param streamId - Identifier of the active stream.
314
- * @param textDelta - New text fragment from the current chunk.
315
- * @returns A previously resolved violation result, or `null`.
256
+ * ONNX models (e.g. toxic-bert) produce labels like `"toxic"`, `"obscene"`,
257
+ * `"threat"`, `"insult"`, `"identity_hate"`, etc. We map these to our four
258
+ * categories, taking the max score when multiple ONNX labels map to the same
259
+ * category.
260
+ *
261
+ * @param raw - Raw ONNX pipeline output.
262
+ * @returns Per-category scores.
263
+ *
264
+ * @internal
316
265
  */
317
- private async handleNonBlocking(
318
- streamId: string,
319
- textDelta: string,
320
- ): Promise<GuardrailEvaluationResult | null> {
321
- // First, check if there is a pending result from a previous window.
322
- const pending = this.pendingResults.get(streamId);
323
- if (pending) {
324
- // Check if the promise has settled without blocking.
325
- const resolved = await Promise.race([
326
- pending.then((val) => ({ done: true as const, val })),
327
- Promise.resolve({ done: false as const, val: null as ChunkEvaluation | null }),
328
- ]);
329
-
330
- if (resolved.done && resolved.val) {
331
- // Consume the pending result.
332
- this.pendingResults.delete(streamId);
333
-
334
- const result = this.evaluationToResult(resolved.val);
335
- if (result) {
336
- return result;
337
- }
338
- }
339
- }
266
+ private mapOnnxScores(raw: any[]): CategoryScore[] {
267
+ /** Map of ONNX label -> our category. */
268
+ const labelMap: Record<string, ClassifierCategory> = {
269
+ toxic: 'toxic',
270
+ severe_toxic: 'toxic',
271
+ obscene: 'nsfw',
272
+ insult: 'toxic',
273
+ identity_hate: 'toxic',
274
+ threat: 'threat',
275
+ };
340
276
 
341
- // Push text into the buffer.
342
- const ready = this.buffer.push(streamId, textDelta);
343
- if (ready) {
344
- // Fire classification in the background — do NOT await.
345
- const classifyPromise = this.orchestrator.classifyAll(ready.text);
346
- this.pendingResults.set(streamId, classifyPromise);
277
+ const maxScores: Record<ClassifierCategory, number> = {
278
+ toxic: 0,
279
+ injection: 0,
280
+ nsfw: 0,
281
+ threat: 0,
282
+ };
283
+
284
+ for (const item of raw) {
285
+ const label = (item.label ?? '').toLowerCase().replace(/\s+/g, '_');
286
+ const score = typeof item.score === 'number' ? item.score : 0;
287
+ const cat = labelMap[label];
288
+ if (cat && score > maxScores[cat]) {
289
+ maxScores[cat] = score;
290
+ }
347
291
  }
348
292
 
349
- // Return null immediately result will be checked on next call.
350
- return null;
293
+ // ONNX models typically do not detect prompt injection; leave at 0.
294
+ return this.categories.map((name) => ({
295
+ name,
296
+ confidence: maxScores[name] ?? 0,
297
+ }));
351
298
  }
352
299
 
300
+ // -----------------------------------------------------------------------
301
+ // Private — LLM classification (Tier 2)
302
+ // -----------------------------------------------------------------------
303
+
353
304
  /**
354
- * **Hybrid mode**: the first chunk for each stream is evaluated in
355
- * blocking mode; subsequent chunks use non-blocking.
305
+ * Classify text using the LLM-as-judge fallback.
356
306
  *
357
- * This provides immediate feedback on the first window (where early
358
- * jailbreak attempts are most likely) while minimising latency for the
359
- * remainder of the stream.
307
+ * @param text - Text to classify.
308
+ * @returns Classification result or `null` if the LLM call fails.
360
309
  *
361
- * @param streamId - Identifier of the active stream.
362
- * @param textDelta - New text fragment from the current chunk.
363
- * @returns Evaluation result or `null`.
310
+ * @internal
364
311
  */
365
- private async handleHybrid(
366
- streamId: string,
367
- textDelta: string,
368
- ): Promise<GuardrailEvaluationResult | null> {
369
- // Determine whether this is the first chunk for this stream.
370
- const isFirst = !this.isFirstChunk.has(streamId);
371
- if (isFirst) {
372
- this.isFirstChunk.set(streamId, true);
373
- }
312
+ private async tryLlmClassification(text: string): Promise<ClassifierResult | null> {
313
+ if (!this.llmInvoker) return null;
314
+
315
+ try {
316
+ const scores = await classifyByLlm(text, this.llmInvoker, this.categories);
317
+
318
+ // If all scores are zero the LLM likely failed to parse — treat as null.
319
+ if (scores.every((s) => s.confidence === 0)) return null;
374
320
 
375
- // First chunk → blocking, subsequent → non-blocking.
376
- if (isFirst) {
377
- return this.handleBlocking(streamId, textDelta);
321
+ return {
322
+ categories: scores,
323
+ flagged: scores.some((s) => s.confidence > this.flagThresholds[s.name]),
324
+ source: 'llm',
325
+ };
326
+ } catch {
327
+ return null;
378
328
  }
379
- return this.handleNonBlocking(streamId, textDelta);
380
329
  }
381
330
 
382
- // -------------------------------------------------------------------------
383
- // Private helpers
384
- // -------------------------------------------------------------------------
331
+ // -----------------------------------------------------------------------
332
+ // Private — result builder
333
+ // -----------------------------------------------------------------------
385
334
 
386
335
  /**
387
- * Convert a {@link ChunkEvaluation} into a {@link GuardrailEvaluationResult}
388
- * suitable for the AgentOS guardrail pipeline.
336
+ * Convert a {@link ClassifierResult} into a {@link GuardrailEvaluationResult},
337
+ * or return `null` when no thresholds are exceeded.
389
338
  *
390
- * Returns `null` when the recommended action is ALLOW (no intervention
391
- * needed). For all other actions, the evaluation details are attached as
392
- * metadata for audit/logging.
339
+ * @param result - Classification result from any tier.
340
+ * @returns Guardrail evaluation result or `null`.
393
341
  *
394
- * @param evaluation - Aggregated classifier evaluation.
395
- * @returns A guardrail result or `null` for clean content.
342
+ * @internal
396
343
  */
397
- private evaluationToResult(evaluation: ChunkEvaluation): GuardrailEvaluationResult | null {
398
- // ALLOW means no guardrail action is needed.
399
- if (evaluation.recommendedAction === GuardrailAction.ALLOW) {
400
- return null;
344
+ private buildResult(result: ClassifierResult): GuardrailEvaluationResult | null {
345
+ // Check for BLOCK-level violations first.
346
+ const blockers = result.categories.filter((s) => s.confidence > this.blockThresholds[s.name]);
347
+
348
+ if (blockers.length > 0) {
349
+ const worst = blockers.reduce((a, b) => (b.confidence > a.confidence ? b : a));
350
+
351
+ return {
352
+ action: GuardrailAction.BLOCK,
353
+ reason: `ML classifier detected unsafe content: ${blockers.map((b) => `${b.name}(${b.confidence.toFixed(2)})`).join(', ')}`,
354
+ reasonCode: `ML_CLASSIFIER_${worst.name.toUpperCase()}`,
355
+ metadata: {
356
+ source: result.source,
357
+ categories: result.categories,
358
+ },
359
+ };
401
360
  }
402
361
 
403
- return {
404
- action: evaluation.recommendedAction,
405
- reason: `ML classifier "${evaluation.triggeredBy}" flagged content`,
406
- reasonCode: `ML_CLASSIFIER_${evaluation.recommendedAction.toUpperCase()}`,
407
- metadata: {
408
- triggeredBy: evaluation.triggeredBy,
409
- totalLatencyMs: evaluation.totalLatencyMs,
410
- classifierResults: evaluation.results.map((r) => ({
411
- classifierId: r.classifierId,
412
- bestClass: r.bestClass,
413
- confidence: r.confidence,
414
- latencyMs: r.latencyMs,
415
- })),
416
- },
417
- };
362
+ // Check for FLAG-level violations.
363
+ const flaggers = result.categories.filter((s) => s.confidence > this.flagThresholds[s.name]);
364
+
365
+ if (flaggers.length > 0) {
366
+ const worst = flaggers.reduce((a, b) => (b.confidence > a.confidence ? b : a));
367
+
368
+ return {
369
+ action: GuardrailAction.FLAG,
370
+ reason: `ML classifier flagged content: ${flaggers.map((f) => `${f.name}(${f.confidence.toFixed(2)})`).join(', ')}`,
371
+ reasonCode: `ML_CLASSIFIER_${worst.name.toUpperCase()}`,
372
+ metadata: {
373
+ source: result.source,
374
+ categories: result.categories,
375
+ },
376
+ };
377
+ }
378
+
379
+ // No thresholds exceeded — allow.
380
+ return null;
418
381
  }
419
382
  }