@stylusnexus/agentarmor-ml 0.1.2 → 0.1.6
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.
- package/README.md +20 -8
- package/dist/cli.js +30 -18
- package/dist/index.d.mts +29 -1
- package/dist/index.d.ts +29 -1
- package/dist/index.js +144 -115
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +144 -115
- package/dist/index.mjs.map +1 -1
- package/package.json +28 -6
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ ML classifier add-on for [Agent Armor](https://github.com/stylusnexus/agent-armo
|
|
|
9
9
|
|
|
10
10
|
Regex-based detection handles the obvious attacks: hidden HTML instructions, known jailbreak patterns, blatant exfiltration triggers. But sophisticated attacks use natural language to manipulate agent behavior through biased framing, subtle persona shifts, or contextual learning traps. These don't have a regex signature.
|
|
11
11
|
|
|
12
|
-
The ML classifier catches what patterns can't. It's trained on the full [AI Agent Traps](https://
|
|
12
|
+
The ML classifier catches what patterns can't. It's trained on the full [AI Agent Traps](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=6372438) taxonomy, runs locally (no API calls, no data leaves your machine), and adds meaningful detection coverage on the semantic manipulation categories where regex falls short.
|
|
13
13
|
|
|
14
14
|
## Install
|
|
15
15
|
|
|
@@ -29,15 +29,15 @@ const armor = await AgentArmor.create({
|
|
|
29
29
|
const result = await armor.scan(content);
|
|
30
30
|
|
|
31
31
|
// ML-detected threats have source: 'ml'
|
|
32
|
-
result.threats.filter(t => t.source === 'ml');
|
|
32
|
+
result.threats.filter((t) => t.source === 'ml');
|
|
33
33
|
```
|
|
34
34
|
|
|
35
35
|
## How It Works
|
|
36
36
|
|
|
37
|
-
On first use, the model (~
|
|
37
|
+
On first use, the model (~165MB quantized ONNX) is downloaded from HuggingFace and cached locally:
|
|
38
38
|
|
|
39
|
-
- **macOS:** `~/Library/Caches/agentarmor/
|
|
40
|
-
- **Linux:** `~/.cache/agentarmor/
|
|
39
|
+
- **macOS:** `~/Library/Caches/agentarmor/v2/`
|
|
40
|
+
- **Linux:** `~/.cache/agentarmor/v2/`
|
|
41
41
|
- **Custom:** Set `AGENTARMOR_CACHE_DIR` or pass `ml.modelDir` in config
|
|
42
42
|
|
|
43
43
|
Subsequent runs load from cache with no network calls.
|
|
@@ -57,7 +57,7 @@ const armor = await AgentArmor.create({
|
|
|
57
57
|
timeoutMs: 120_000,
|
|
58
58
|
retries: 2,
|
|
59
59
|
onProgress: (received, total) => {
|
|
60
|
-
console.log(`${Math.round(received / total * 100)}%`);
|
|
60
|
+
console.log(`${Math.round((received / total) * 100)}%`);
|
|
61
61
|
},
|
|
62
62
|
},
|
|
63
63
|
},
|
|
@@ -82,14 +82,26 @@ agentarmor-ml clear-cache
|
|
|
82
82
|
|
|
83
83
|
## Inference Details
|
|
84
84
|
|
|
85
|
-
- Tokenizes input to 512 tokens (
|
|
85
|
+
- Tokenizes input to 512 tokens with the Hugging Face [`tokenizers`](https://www.npmjs.com/package/tokenizers) package, reading the model's own `tokenizer.json` (SentencePiece Unigram). A retrained model needs no code change; a test fails if the ids drift from the Python training tokenizer.
|
|
86
|
+
- If most of an input's tokens are unknown to the tokenizer, the ML result is dropped and the pattern detectors carry the scan. The scan result lists it in `stats.detectorsSkipped`, and `on.warn` fires once
|
|
86
87
|
- Runs ONNX inference with INT8 quantization via `onnxruntime-node`
|
|
87
88
|
- Applies sigmoid on logits with strictness-based thresholds: `strict=0.3`, `balanced=0.5`, `permissive=0.7`
|
|
88
89
|
- `scan()` (sync) returns empty — ML inference is async-only via `scanAsync()`
|
|
89
90
|
|
|
91
|
+
## Limits
|
|
92
|
+
|
|
93
|
+
Treat the classifier as a second opinion for triage, not a gate. The regex result stays the thing that blocks content. Measured on 2026-10-08 on the shipped INT8 model (see the [main README](https://github.com/stylusnexus/agent-armor#how-well-it-works) for the full table):
|
|
94
|
+
|
|
95
|
+
- **False flags.** It flags 21 of 105 honest eval samples (about 20%) and 38 of 339 short NotInject prompts; together with the regex detectors, 29 of 105 honest eval samples. Most flags are ordinary operations documents (credential rotation, incident summaries, CI output, setup steps with URLs) and markdown image links.
|
|
96
|
+
- **Languages.** English and Chinese only. In probes, "ignore all previous instructions" in Spanish, German and Russian was not flagged.
|
|
97
|
+
- **Long text.** The model reads at most 512 tokens, and an attack after about 700 characters of honest text drops below the threshold ([#274](https://github.com/stylusnexus/agent-armor/issues/274)).
|
|
98
|
+
- **Obfuscation.** Leetspeak and word-joiner characters were missed in probes.
|
|
99
|
+
- **Small evaluation sets.** Differences of 10 to 20 samples between model versions are noise.
|
|
100
|
+
|
|
90
101
|
## Deployment Notes
|
|
91
102
|
|
|
92
|
-
- **AWS Lambda:**
|
|
103
|
+
- **AWS Lambda:** 165MB model + ~40MB onnxruntime = ~205MB, fits the 250MB limit but is tight. Use `modelDir` to bundle the model in your deployment package.
|
|
104
|
+
- **Native tokenizer:** `tokenizers` is a native add-on that ships prebuilt binaries for macOS, Linux (glibc and musl, x64 and arm64) and Windows, about 64 MB in `node_modules` in total and about 5 MB for one platform. For Lambda, delete the other platforms' `.node` files in `node_modules/tokenizers/` (as you already do for `onnxruntime-node`). Run so far: macOS arm64 (local) and Linux x64 (CI); Windows, linux-arm64, musl and Lambda have not been run.
|
|
93
105
|
- **Vercel Edge:** Not supported (ONNX runtime requires Node.js native bindings).
|
|
94
106
|
|
|
95
107
|
## Requirements
|
package/dist/cli.js
CHANGED
|
@@ -9,19 +9,17 @@ var import_fs2 = require("fs");
|
|
|
9
9
|
// src/constants.ts
|
|
10
10
|
var import_os = require("os");
|
|
11
11
|
var import_path = require("path");
|
|
12
|
-
var MODEL_VERSION = "
|
|
12
|
+
var MODEL_VERSION = "v2";
|
|
13
13
|
var HF_REPO_ID = "stylusnexus/agent-armor-classifier";
|
|
14
|
+
var HF_REVISION = "v2";
|
|
14
15
|
var MODEL_FILENAME = "model_quantized.onnx";
|
|
15
16
|
var REQUIRED_MODEL_FILES = [
|
|
16
17
|
"model_quantized.onnx",
|
|
17
18
|
"tokenizer.json",
|
|
18
19
|
"label_map.json"
|
|
19
20
|
];
|
|
20
|
-
var OPTIONAL_MODEL_FILES = [
|
|
21
|
-
|
|
22
|
-
"special_tokens_map.json"
|
|
23
|
-
];
|
|
24
|
-
var MODEL_CHECKSUM = "PLACEHOLDER_UPDATE_AFTER_FIRST_PUBLISH";
|
|
21
|
+
var OPTIONAL_MODEL_FILES = ["tokenizer_config.json", "special_tokens_map.json"];
|
|
22
|
+
var MODEL_CHECKSUM = "4f3e912ab7f6ef7fba679590738b7f00b6d3bfe0cafa09982463211f20b0d42f";
|
|
25
23
|
var LABELS = [
|
|
26
24
|
"hidden-html",
|
|
27
25
|
"metadata-injection",
|
|
@@ -38,9 +36,7 @@ var LABELS = [
|
|
|
38
36
|
"persona-hyperstition",
|
|
39
37
|
"benign"
|
|
40
38
|
];
|
|
41
|
-
var LABEL_TO_INDEX = Object.fromEntries(
|
|
42
|
-
LABELS.map((label, i) => [label, i])
|
|
43
|
-
);
|
|
39
|
+
var LABEL_TO_INDEX = Object.fromEntries(LABELS.map((label, i) => [label, i]));
|
|
44
40
|
function getDefaultCacheDir() {
|
|
45
41
|
const envOverride = process.env.AGENTARMOR_CACHE_DIR;
|
|
46
42
|
if (envOverride) return envOverride;
|
|
@@ -64,7 +60,9 @@ var import_promises2 = require("stream/promises");
|
|
|
64
60
|
|
|
65
61
|
// src/errors.ts
|
|
66
62
|
var AgentArmorModelError = class extends Error {
|
|
63
|
+
/** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */
|
|
67
64
|
code;
|
|
65
|
+
/** The underlying error, when this wraps one (e.g. a failed fetch). */
|
|
68
66
|
cause;
|
|
69
67
|
constructor(code, message, cause) {
|
|
70
68
|
super(message);
|
|
@@ -166,7 +164,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
166
164
|
if (config.modelUrl) {
|
|
167
165
|
baseUrl = config.modelUrl.replace(/\/$/, "");
|
|
168
166
|
} else {
|
|
169
|
-
baseUrl = `https://huggingface.co/${HF_REPO_ID}/resolve
|
|
167
|
+
baseUrl = `https://huggingface.co/${HF_REPO_ID}/resolve/${HF_REVISION}`;
|
|
170
168
|
}
|
|
171
169
|
const url = `${baseUrl}/${filename}`;
|
|
172
170
|
const destPath = (0, import_path2.join)(destDir, filename);
|
|
@@ -185,7 +183,9 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
185
183
|
const makeRequest = (requestUrl, redirectCount = 0) => {
|
|
186
184
|
if (redirectCount > 5) {
|
|
187
185
|
clearTimeout(timer);
|
|
188
|
-
reject(
|
|
186
|
+
reject(
|
|
187
|
+
new AgentArmorModelError("DOWNLOAD_FAILED", `Too many redirects for ${filename}`)
|
|
188
|
+
);
|
|
189
189
|
return;
|
|
190
190
|
}
|
|
191
191
|
const protocol = requestUrl.startsWith("https") ? import_https.get : import_https.get;
|
|
@@ -226,14 +226,22 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
226
226
|
}).catch((pipeErr) => {
|
|
227
227
|
clearTimeout(timer);
|
|
228
228
|
reject(
|
|
229
|
-
new AgentArmorModelError(
|
|
229
|
+
new AgentArmorModelError(
|
|
230
|
+
"DOWNLOAD_FAILED",
|
|
231
|
+
`Failed to write ${filename}`,
|
|
232
|
+
pipeErr
|
|
233
|
+
)
|
|
230
234
|
);
|
|
231
235
|
});
|
|
232
236
|
});
|
|
233
237
|
req.on("error", (reqErr) => {
|
|
234
238
|
clearTimeout(timer);
|
|
235
239
|
reject(
|
|
236
|
-
new AgentArmorModelError(
|
|
240
|
+
new AgentArmorModelError(
|
|
241
|
+
"DOWNLOAD_FAILED",
|
|
242
|
+
`Network error downloading ${filename}`,
|
|
243
|
+
reqErr
|
|
244
|
+
)
|
|
237
245
|
);
|
|
238
246
|
});
|
|
239
247
|
};
|
|
@@ -259,8 +267,8 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
259
267
|
}
|
|
260
268
|
}
|
|
261
269
|
}
|
|
262
|
-
async function verifyChecksum(filePath) {
|
|
263
|
-
if (
|
|
270
|
+
async function verifyChecksum(filePath, expected = MODEL_CHECKSUM) {
|
|
271
|
+
if (expected.startsWith("PLACEHOLDER")) {
|
|
264
272
|
return true;
|
|
265
273
|
}
|
|
266
274
|
const hash = (0, import_crypto.createHash)("sha256");
|
|
@@ -269,7 +277,7 @@ async function verifyChecksum(filePath) {
|
|
|
269
277
|
hash.update(chunk);
|
|
270
278
|
}
|
|
271
279
|
const digest = hash.digest("hex");
|
|
272
|
-
return digest ===
|
|
280
|
+
return digest === expected;
|
|
273
281
|
}
|
|
274
282
|
async function waitForLock(lockPath, config) {
|
|
275
283
|
const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
@@ -348,7 +356,9 @@ async function cmdDownload(args) {
|
|
|
348
356
|
const onProgress = quiet ? void 0 : (received, total) => {
|
|
349
357
|
if (total > 0) {
|
|
350
358
|
const pct = (received / total * 100).toFixed(1);
|
|
351
|
-
process.stdout.write(
|
|
359
|
+
process.stdout.write(
|
|
360
|
+
`\rDownloading... ${pct}% (${(received / 1e6).toFixed(1)}/${(total / 1e6).toFixed(1)} MB)`
|
|
361
|
+
);
|
|
352
362
|
}
|
|
353
363
|
};
|
|
354
364
|
try {
|
|
@@ -364,7 +374,9 @@ async function cmdDownload(args) {
|
|
|
364
374
|
(0, import_fs2.copyFileSync)(src, dest);
|
|
365
375
|
}
|
|
366
376
|
if (!quiet) console.log("");
|
|
367
|
-
console.log(
|
|
377
|
+
console.log(
|
|
378
|
+
quiet ? (0, import_path3.join)(resolvedDir, "model_quantized.onnx") : `Model downloaded to: ${resolvedDir}`
|
|
379
|
+
);
|
|
368
380
|
} catch (err) {
|
|
369
381
|
console.error(`
|
|
370
382
|
Download failed: ${err instanceof Error ? err.message : String(err)}`);
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
|
+
/** Resolved on-disk paths to the ONNX model and its supporting files. */
|
|
1
2
|
interface ModelArtifacts {
|
|
3
|
+
/** Path to `model_quantized.onnx`. */
|
|
2
4
|
modelPath: string;
|
|
5
|
+
/** Path to `tokenizer.json`. */
|
|
3
6
|
tokenizerPath: string;
|
|
7
|
+
/** Path to `label_map.json`. */
|
|
4
8
|
labelMapPath: string;
|
|
9
|
+
/** Directory containing all resolved model files. */
|
|
5
10
|
modelDir: string;
|
|
6
11
|
}
|
|
7
12
|
|
|
@@ -10,6 +15,9 @@ interface DetectorOptions {
|
|
|
10
15
|
}
|
|
11
16
|
interface DetectorResult {
|
|
12
17
|
threats: Threat[];
|
|
18
|
+
skipped?: {
|
|
19
|
+
reason: string;
|
|
20
|
+
};
|
|
13
21
|
}
|
|
14
22
|
interface Threat {
|
|
15
23
|
category: string;
|
|
@@ -33,23 +41,43 @@ interface Detector {
|
|
|
33
41
|
scanAsync?(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
34
42
|
sanitize(content: string, threats: Threat[]): string;
|
|
35
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* ONNX-based detector running the DeBERTa-v3-small multi-label classifier.
|
|
46
|
+
* Implements Agent Armor's `Detector` interface via structural typing —
|
|
47
|
+
* {@link MLDetector.create} loads the model; {@link MLDetector.scanAsync}
|
|
48
|
+
* runs inference. {@link MLDetector.scan} (sync) always returns no threats,
|
|
49
|
+
* since ONNX inference is async-only.
|
|
50
|
+
*/
|
|
36
51
|
declare class MLDetector implements Detector {
|
|
52
|
+
/** Unique identifier for this detector. */
|
|
37
53
|
readonly id = "ml-classifier";
|
|
54
|
+
/** Human-readable name. */
|
|
38
55
|
readonly name = "ML Classifier (DeBERTa-v3-small)";
|
|
56
|
+
/** Trap category this detector's labels currently map into. */
|
|
39
57
|
readonly category = "content-injection";
|
|
58
|
+
/** Model version — surfaced on AuditRecord.mlModelVersion when this detector ran (#75). */
|
|
59
|
+
readonly version = "v2";
|
|
40
60
|
private session;
|
|
41
61
|
private tokenizer;
|
|
42
62
|
private ort;
|
|
43
63
|
private constructor();
|
|
64
|
+
/** Loads the ONNX session and tokenizer from resolved {@link ModelArtifacts}. */
|
|
44
65
|
static create(artifacts: ModelArtifacts): Promise<MLDetector>;
|
|
66
|
+
/** Always returns no threats — ML inference is async-only, use {@link scanAsync}. */
|
|
45
67
|
scan(_content: string, _options?: DetectorOptions): DetectorResult;
|
|
68
|
+
/** Tokenizes `content`, runs ONNX inference, and returns threats above the strictness threshold. */
|
|
46
69
|
scanAsync(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
70
|
+
/** Passthrough — the ML detector doesn't modify content; pattern detectors sanitize. */
|
|
47
71
|
sanitize(content: string, _threats: Threat[]): string;
|
|
48
72
|
}
|
|
49
73
|
|
|
50
|
-
|
|
74
|
+
/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */
|
|
75
|
+
type ModelErrorCode = 'MODEL_NOT_FOUND' | 'CHECKSUM_MISMATCH' | 'DOWNLOAD_FAILED' | 'DOWNLOAD_TIMEOUT' | 'DISK_FULL' | 'LOCK_TIMEOUT' | 'UNSUPPORTED_TOKENIZER' | 'TOKENIZER_LOAD_FAILED';
|
|
76
|
+
/** Thrown when the ML model can't be resolved (missing, corrupt, or unreachable). */
|
|
51
77
|
declare class AgentArmorModelError extends Error {
|
|
78
|
+
/** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */
|
|
52
79
|
readonly code: ModelErrorCode;
|
|
80
|
+
/** The underlying error, when this wraps one (e.g. a failed fetch). */
|
|
53
81
|
readonly cause?: Error;
|
|
54
82
|
constructor(code: ModelErrorCode, message: string, cause?: Error);
|
|
55
83
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
|
+
/** Resolved on-disk paths to the ONNX model and its supporting files. */
|
|
1
2
|
interface ModelArtifacts {
|
|
3
|
+
/** Path to `model_quantized.onnx`. */
|
|
2
4
|
modelPath: string;
|
|
5
|
+
/** Path to `tokenizer.json`. */
|
|
3
6
|
tokenizerPath: string;
|
|
7
|
+
/** Path to `label_map.json`. */
|
|
4
8
|
labelMapPath: string;
|
|
9
|
+
/** Directory containing all resolved model files. */
|
|
5
10
|
modelDir: string;
|
|
6
11
|
}
|
|
7
12
|
|
|
@@ -10,6 +15,9 @@ interface DetectorOptions {
|
|
|
10
15
|
}
|
|
11
16
|
interface DetectorResult {
|
|
12
17
|
threats: Threat[];
|
|
18
|
+
skipped?: {
|
|
19
|
+
reason: string;
|
|
20
|
+
};
|
|
13
21
|
}
|
|
14
22
|
interface Threat {
|
|
15
23
|
category: string;
|
|
@@ -33,23 +41,43 @@ interface Detector {
|
|
|
33
41
|
scanAsync?(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
34
42
|
sanitize(content: string, threats: Threat[]): string;
|
|
35
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* ONNX-based detector running the DeBERTa-v3-small multi-label classifier.
|
|
46
|
+
* Implements Agent Armor's `Detector` interface via structural typing —
|
|
47
|
+
* {@link MLDetector.create} loads the model; {@link MLDetector.scanAsync}
|
|
48
|
+
* runs inference. {@link MLDetector.scan} (sync) always returns no threats,
|
|
49
|
+
* since ONNX inference is async-only.
|
|
50
|
+
*/
|
|
36
51
|
declare class MLDetector implements Detector {
|
|
52
|
+
/** Unique identifier for this detector. */
|
|
37
53
|
readonly id = "ml-classifier";
|
|
54
|
+
/** Human-readable name. */
|
|
38
55
|
readonly name = "ML Classifier (DeBERTa-v3-small)";
|
|
56
|
+
/** Trap category this detector's labels currently map into. */
|
|
39
57
|
readonly category = "content-injection";
|
|
58
|
+
/** Model version — surfaced on AuditRecord.mlModelVersion when this detector ran (#75). */
|
|
59
|
+
readonly version = "v2";
|
|
40
60
|
private session;
|
|
41
61
|
private tokenizer;
|
|
42
62
|
private ort;
|
|
43
63
|
private constructor();
|
|
64
|
+
/** Loads the ONNX session and tokenizer from resolved {@link ModelArtifacts}. */
|
|
44
65
|
static create(artifacts: ModelArtifacts): Promise<MLDetector>;
|
|
66
|
+
/** Always returns no threats — ML inference is async-only, use {@link scanAsync}. */
|
|
45
67
|
scan(_content: string, _options?: DetectorOptions): DetectorResult;
|
|
68
|
+
/** Tokenizes `content`, runs ONNX inference, and returns threats above the strictness threshold. */
|
|
46
69
|
scanAsync(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
70
|
+
/** Passthrough — the ML detector doesn't modify content; pattern detectors sanitize. */
|
|
47
71
|
sanitize(content: string, _threats: Threat[]): string;
|
|
48
72
|
}
|
|
49
73
|
|
|
50
|
-
|
|
74
|
+
/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */
|
|
75
|
+
type ModelErrorCode = 'MODEL_NOT_FOUND' | 'CHECKSUM_MISMATCH' | 'DOWNLOAD_FAILED' | 'DOWNLOAD_TIMEOUT' | 'DISK_FULL' | 'LOCK_TIMEOUT' | 'UNSUPPORTED_TOKENIZER' | 'TOKENIZER_LOAD_FAILED';
|
|
76
|
+
/** Thrown when the ML model can't be resolved (missing, corrupt, or unreachable). */
|
|
51
77
|
declare class AgentArmorModelError extends Error {
|
|
78
|
+
/** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */
|
|
52
79
|
readonly code: ModelErrorCode;
|
|
80
|
+
/** The underlying error, when this wraps one (e.g. a failed fetch). */
|
|
53
81
|
readonly cause?: Error;
|
|
54
82
|
constructor(code: ModelErrorCode, message: string, cause?: Error);
|
|
55
83
|
}
|