@stylusnexus/agentarmor-ml 0.1.1 → 0.1.5
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 +9 -3
- package/dist/cli.js +6 -4
- package/dist/index.d.mts +25 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +46 -23
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +46 -23
- package/dist/index.mjs.map +1 -1
- package/package.json +26 -5
package/README.md
CHANGED
|
@@ -3,7 +3,13 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/@stylusnexus/agentarmor-ml)
|
|
4
4
|
[](https://opensource.org/licenses/MIT)
|
|
5
5
|
|
|
6
|
-
ML classifier add-on for [Agent Armor](https://github.com/stylusnexus/agent-armor). Runs a DeBERTa-v3-small ONNX model locally for deeper agent trap detection that catches threats regex patterns
|
|
6
|
+
ML classifier add-on for [Agent Armor](https://github.com/stylusnexus/agent-armor). Runs a DeBERTa-v3-small ONNX model locally for deeper agent trap detection that catches threats regex patterns miss.
|
|
7
|
+
|
|
8
|
+
## Why Use the ML Classifier?
|
|
9
|
+
|
|
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
|
+
|
|
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.
|
|
7
13
|
|
|
8
14
|
## Install
|
|
9
15
|
|
|
@@ -28,7 +34,7 @@ result.threats.filter(t => t.source === 'ml');
|
|
|
28
34
|
|
|
29
35
|
## How It Works
|
|
30
36
|
|
|
31
|
-
On first use, the model (~
|
|
37
|
+
On first use, the model (~165MB quantized ONNX) is downloaded from HuggingFace and cached locally:
|
|
32
38
|
|
|
33
39
|
- **macOS:** `~/Library/Caches/agentarmor/v1/`
|
|
34
40
|
- **Linux:** `~/.cache/agentarmor/v1/`
|
|
@@ -83,7 +89,7 @@ agentarmor-ml clear-cache
|
|
|
83
89
|
|
|
84
90
|
## Deployment Notes
|
|
85
91
|
|
|
86
|
-
- **AWS Lambda:**
|
|
92
|
+
- **AWS Lambda:** 165MB model + ~40MB onnxruntime = ~205MB, fits the 250MB limit but is tight. Use `modelDir` to bundle the model in your deployment package.
|
|
87
93
|
- **Vercel Edge:** Not supported (ONNX runtime requires Node.js native bindings).
|
|
88
94
|
|
|
89
95
|
## Requirements
|
package/dist/cli.js
CHANGED
|
@@ -21,7 +21,7 @@ var OPTIONAL_MODEL_FILES = [
|
|
|
21
21
|
"tokenizer_config.json",
|
|
22
22
|
"special_tokens_map.json"
|
|
23
23
|
];
|
|
24
|
-
var MODEL_CHECKSUM = "
|
|
24
|
+
var MODEL_CHECKSUM = "5d4c8551c958f398181c60239aebedbaa4ed5b641d1645904d2de9c2d02bd41f";
|
|
25
25
|
var LABELS = [
|
|
26
26
|
"hidden-html",
|
|
27
27
|
"metadata-injection",
|
|
@@ -64,7 +64,9 @@ var import_promises2 = require("stream/promises");
|
|
|
64
64
|
|
|
65
65
|
// src/errors.ts
|
|
66
66
|
var AgentArmorModelError = class extends Error {
|
|
67
|
+
/** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */
|
|
67
68
|
code;
|
|
69
|
+
/** The underlying error, when this wraps one (e.g. a failed fetch). */
|
|
68
70
|
cause;
|
|
69
71
|
constructor(code, message, cause) {
|
|
70
72
|
super(message);
|
|
@@ -259,8 +261,8 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
259
261
|
}
|
|
260
262
|
}
|
|
261
263
|
}
|
|
262
|
-
async function verifyChecksum(filePath) {
|
|
263
|
-
if (
|
|
264
|
+
async function verifyChecksum(filePath, expected = MODEL_CHECKSUM) {
|
|
265
|
+
if (expected.startsWith("PLACEHOLDER")) {
|
|
264
266
|
return true;
|
|
265
267
|
}
|
|
266
268
|
const hash = (0, import_crypto.createHash)("sha256");
|
|
@@ -269,7 +271,7 @@ async function verifyChecksum(filePath) {
|
|
|
269
271
|
hash.update(chunk);
|
|
270
272
|
}
|
|
271
273
|
const digest = hash.digest("hex");
|
|
272
|
-
return digest ===
|
|
274
|
+
return digest === expected;
|
|
273
275
|
}
|
|
274
276
|
async function waitForLock(lockPath, config) {
|
|
275
277
|
const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
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
|
|
|
@@ -33,23 +38,43 @@ interface Detector {
|
|
|
33
38
|
scanAsync?(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
34
39
|
sanitize(content: string, threats: Threat[]): string;
|
|
35
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* ONNX-based detector running the DeBERTa-v3-small multi-label classifier.
|
|
43
|
+
* Implements Agent Armor's `Detector` interface via structural typing —
|
|
44
|
+
* {@link MLDetector.create} loads the model; {@link MLDetector.scanAsync}
|
|
45
|
+
* runs inference. {@link MLDetector.scan} (sync) always returns no threats,
|
|
46
|
+
* since ONNX inference is async-only.
|
|
47
|
+
*/
|
|
36
48
|
declare class MLDetector implements Detector {
|
|
49
|
+
/** Unique identifier for this detector. */
|
|
37
50
|
readonly id = "ml-classifier";
|
|
51
|
+
/** Human-readable name. */
|
|
38
52
|
readonly name = "ML Classifier (DeBERTa-v3-small)";
|
|
53
|
+
/** Trap category this detector's labels currently map into. */
|
|
39
54
|
readonly category = "content-injection";
|
|
55
|
+
/** Model version — surfaced on AuditRecord.mlModelVersion when this detector ran (#75). */
|
|
56
|
+
readonly version = "v1";
|
|
40
57
|
private session;
|
|
41
58
|
private tokenizer;
|
|
42
59
|
private ort;
|
|
43
60
|
private constructor();
|
|
61
|
+
/** Loads the ONNX session and tokenizer from resolved {@link ModelArtifacts}. */
|
|
44
62
|
static create(artifacts: ModelArtifacts): Promise<MLDetector>;
|
|
63
|
+
/** Always returns no threats — ML inference is async-only, use {@link scanAsync}. */
|
|
45
64
|
scan(_content: string, _options?: DetectorOptions): DetectorResult;
|
|
65
|
+
/** Tokenizes `content`, runs ONNX inference, and returns threats above the strictness threshold. */
|
|
46
66
|
scanAsync(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
67
|
+
/** Passthrough — the ML detector doesn't modify content; pattern detectors sanitize. */
|
|
47
68
|
sanitize(content: string, _threats: Threat[]): string;
|
|
48
69
|
}
|
|
49
70
|
|
|
71
|
+
/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */
|
|
50
72
|
type ModelErrorCode = 'MODEL_NOT_FOUND' | 'CHECKSUM_MISMATCH' | 'DOWNLOAD_FAILED' | 'DOWNLOAD_TIMEOUT' | 'DISK_FULL' | 'LOCK_TIMEOUT';
|
|
73
|
+
/** Thrown when the ML model can't be resolved (missing, corrupt, or unreachable). */
|
|
51
74
|
declare class AgentArmorModelError extends Error {
|
|
75
|
+
/** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */
|
|
52
76
|
readonly code: ModelErrorCode;
|
|
77
|
+
/** The underlying error, when this wraps one (e.g. a failed fetch). */
|
|
53
78
|
readonly cause?: Error;
|
|
54
79
|
constructor(code: ModelErrorCode, message: string, cause?: Error);
|
|
55
80
|
}
|
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
|
|
|
@@ -33,23 +38,43 @@ interface Detector {
|
|
|
33
38
|
scanAsync?(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
34
39
|
sanitize(content: string, threats: Threat[]): string;
|
|
35
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* ONNX-based detector running the DeBERTa-v3-small multi-label classifier.
|
|
43
|
+
* Implements Agent Armor's `Detector` interface via structural typing —
|
|
44
|
+
* {@link MLDetector.create} loads the model; {@link MLDetector.scanAsync}
|
|
45
|
+
* runs inference. {@link MLDetector.scan} (sync) always returns no threats,
|
|
46
|
+
* since ONNX inference is async-only.
|
|
47
|
+
*/
|
|
36
48
|
declare class MLDetector implements Detector {
|
|
49
|
+
/** Unique identifier for this detector. */
|
|
37
50
|
readonly id = "ml-classifier";
|
|
51
|
+
/** Human-readable name. */
|
|
38
52
|
readonly name = "ML Classifier (DeBERTa-v3-small)";
|
|
53
|
+
/** Trap category this detector's labels currently map into. */
|
|
39
54
|
readonly category = "content-injection";
|
|
55
|
+
/** Model version — surfaced on AuditRecord.mlModelVersion when this detector ran (#75). */
|
|
56
|
+
readonly version = "v1";
|
|
40
57
|
private session;
|
|
41
58
|
private tokenizer;
|
|
42
59
|
private ort;
|
|
43
60
|
private constructor();
|
|
61
|
+
/** Loads the ONNX session and tokenizer from resolved {@link ModelArtifacts}. */
|
|
44
62
|
static create(artifacts: ModelArtifacts): Promise<MLDetector>;
|
|
63
|
+
/** Always returns no threats — ML inference is async-only, use {@link scanAsync}. */
|
|
45
64
|
scan(_content: string, _options?: DetectorOptions): DetectorResult;
|
|
65
|
+
/** Tokenizes `content`, runs ONNX inference, and returns threats above the strictness threshold. */
|
|
46
66
|
scanAsync(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
67
|
+
/** Passthrough — the ML detector doesn't modify content; pattern detectors sanitize. */
|
|
47
68
|
sanitize(content: string, _threats: Threat[]): string;
|
|
48
69
|
}
|
|
49
70
|
|
|
71
|
+
/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */
|
|
50
72
|
type ModelErrorCode = 'MODEL_NOT_FOUND' | 'CHECKSUM_MISMATCH' | 'DOWNLOAD_FAILED' | 'DOWNLOAD_TIMEOUT' | 'DISK_FULL' | 'LOCK_TIMEOUT';
|
|
73
|
+
/** Thrown when the ML model can't be resolved (missing, corrupt, or unreachable). */
|
|
51
74
|
declare class AgentArmorModelError extends Error {
|
|
75
|
+
/** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */
|
|
52
76
|
readonly code: ModelErrorCode;
|
|
77
|
+
/** The underlying error, when this wraps one (e.g. a failed fetch). */
|
|
53
78
|
readonly cause?: Error;
|
|
54
79
|
constructor(code: ModelErrorCode, message: string, cause?: Error);
|
|
55
80
|
}
|
package/dist/index.js
CHANGED
|
@@ -51,7 +51,7 @@ var OPTIONAL_MODEL_FILES = [
|
|
|
51
51
|
"tokenizer_config.json",
|
|
52
52
|
"special_tokens_map.json"
|
|
53
53
|
];
|
|
54
|
-
var MODEL_CHECKSUM = "
|
|
54
|
+
var MODEL_CHECKSUM = "5d4c8551c958f398181c60239aebedbaa4ed5b641d1645904d2de9c2d02bd41f";
|
|
55
55
|
var LABELS = [
|
|
56
56
|
"hidden-html",
|
|
57
57
|
"metadata-injection",
|
|
@@ -86,6 +86,22 @@ var DEFAULT_RETRIES = 2;
|
|
|
86
86
|
|
|
87
87
|
// src/tokenizer.ts
|
|
88
88
|
var import_promises = require("fs/promises");
|
|
89
|
+
|
|
90
|
+
// src/errors.ts
|
|
91
|
+
var AgentArmorModelError = class extends Error {
|
|
92
|
+
/** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */
|
|
93
|
+
code;
|
|
94
|
+
/** The underlying error, when this wraps one (e.g. a failed fetch). */
|
|
95
|
+
cause;
|
|
96
|
+
constructor(code, message, cause) {
|
|
97
|
+
super(message);
|
|
98
|
+
this.name = "AgentArmorModelError";
|
|
99
|
+
this.code = code;
|
|
100
|
+
this.cause = cause;
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// src/tokenizer.ts
|
|
89
105
|
var DEFAULT_SPECIAL = {
|
|
90
106
|
"[UNK]": 0,
|
|
91
107
|
"[CLS]": 1,
|
|
@@ -110,10 +126,25 @@ var Tokenizer = class _Tokenizer {
|
|
|
110
126
|
*/
|
|
111
127
|
static async fromFile(path) {
|
|
112
128
|
const raw = await (0, import_promises.readFile)(path, "utf-8");
|
|
113
|
-
|
|
129
|
+
let json;
|
|
130
|
+
try {
|
|
131
|
+
json = JSON.parse(raw);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
throw new AgentArmorModelError(
|
|
134
|
+
"MODEL_NOT_FOUND",
|
|
135
|
+
`Tokenizer file at ${path} is not valid JSON. The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`,
|
|
136
|
+
err instanceof Error ? err : void 0
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
if (!json.model?.vocab) {
|
|
140
|
+
throw new AgentArmorModelError(
|
|
141
|
+
"MODEL_NOT_FOUND",
|
|
142
|
+
`Tokenizer file at ${path} is missing "model.vocab". The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`
|
|
143
|
+
);
|
|
144
|
+
}
|
|
114
145
|
const vocab = new Map(Object.entries(json.model.vocab));
|
|
115
146
|
const specialTokens = { ...DEFAULT_SPECIAL };
|
|
116
|
-
for (const token of json.added_tokens) {
|
|
147
|
+
for (const token of json.added_tokens ?? []) {
|
|
117
148
|
vocab.set(token.content, token.id);
|
|
118
149
|
if (token.content in DEFAULT_SPECIAL) {
|
|
119
150
|
specialTokens[token.content] = token.id;
|
|
@@ -208,9 +239,14 @@ var LABEL_TO_CATEGORY = {
|
|
|
208
239
|
"benign": "content-injection"
|
|
209
240
|
};
|
|
210
241
|
var MLDetector = class _MLDetector {
|
|
242
|
+
/** Unique identifier for this detector. */
|
|
211
243
|
id = "ml-classifier";
|
|
244
|
+
/** Human-readable name. */
|
|
212
245
|
name = "ML Classifier (DeBERTa-v3-small)";
|
|
246
|
+
/** Trap category this detector's labels currently map into. */
|
|
213
247
|
category = "content-injection";
|
|
248
|
+
/** Model version — surfaced on AuditRecord.mlModelVersion when this detector ran (#75). */
|
|
249
|
+
version = MODEL_VERSION;
|
|
214
250
|
session;
|
|
215
251
|
tokenizer;
|
|
216
252
|
ort;
|
|
@@ -219,17 +255,18 @@ var MLDetector = class _MLDetector {
|
|
|
219
255
|
this.tokenizer = tokenizer;
|
|
220
256
|
this.ort = ort;
|
|
221
257
|
}
|
|
258
|
+
/** Loads the ONNX session and tokenizer from resolved {@link ModelArtifacts}. */
|
|
222
259
|
static async create(artifacts) {
|
|
223
260
|
const ort = await import("onnxruntime-node");
|
|
224
261
|
const session = await ort.InferenceSession.create(artifacts.modelPath);
|
|
225
262
|
const tokenizer = await Tokenizer.fromFile(artifacts.tokenizerPath);
|
|
226
263
|
return new _MLDetector(session, tokenizer, ort);
|
|
227
264
|
}
|
|
228
|
-
|
|
265
|
+
/** Always returns no threats — ML inference is async-only, use {@link scanAsync}. */
|
|
229
266
|
scan(_content, _options) {
|
|
230
267
|
return { threats: [] };
|
|
231
268
|
}
|
|
232
|
-
|
|
269
|
+
/** Tokenizes `content`, runs ONNX inference, and returns threats above the strictness threshold. */
|
|
233
270
|
async scanAsync(content, options) {
|
|
234
271
|
const strictness = options?.strictness ?? "balanced";
|
|
235
272
|
const threshold = THRESHOLDS[strictness] ?? THRESHOLDS.balanced;
|
|
@@ -261,7 +298,7 @@ var MLDetector = class _MLDetector {
|
|
|
261
298
|
}
|
|
262
299
|
return { threats };
|
|
263
300
|
}
|
|
264
|
-
|
|
301
|
+
/** Passthrough — the ML detector doesn't modify content; pattern detectors sanitize. */
|
|
265
302
|
sanitize(content, _threats) {
|
|
266
303
|
return content;
|
|
267
304
|
}
|
|
@@ -274,20 +311,6 @@ var import_promises2 = require("fs/promises");
|
|
|
274
311
|
var import_https = require("https");
|
|
275
312
|
var import_path2 = require("path");
|
|
276
313
|
var import_promises3 = require("stream/promises");
|
|
277
|
-
|
|
278
|
-
// src/errors.ts
|
|
279
|
-
var AgentArmorModelError = class extends Error {
|
|
280
|
-
code;
|
|
281
|
-
cause;
|
|
282
|
-
constructor(code, message, cause) {
|
|
283
|
-
super(message);
|
|
284
|
-
this.name = "AgentArmorModelError";
|
|
285
|
-
this.code = code;
|
|
286
|
-
this.cause = cause;
|
|
287
|
-
}
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
// src/model-manager.ts
|
|
291
314
|
function artifactsFrom(dir) {
|
|
292
315
|
return {
|
|
293
316
|
modelPath: (0, import_path2.join)(dir, MODEL_FILENAME),
|
|
@@ -472,8 +495,8 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
472
495
|
}
|
|
473
496
|
}
|
|
474
497
|
}
|
|
475
|
-
async function verifyChecksum(filePath) {
|
|
476
|
-
if (
|
|
498
|
+
async function verifyChecksum(filePath, expected = MODEL_CHECKSUM) {
|
|
499
|
+
if (expected.startsWith("PLACEHOLDER")) {
|
|
477
500
|
return true;
|
|
478
501
|
}
|
|
479
502
|
const hash = (0, import_crypto.createHash)("sha256");
|
|
@@ -482,7 +505,7 @@ async function verifyChecksum(filePath) {
|
|
|
482
505
|
hash.update(chunk);
|
|
483
506
|
}
|
|
484
507
|
const digest = hash.digest("hex");
|
|
485
|
-
return digest ===
|
|
508
|
+
return digest === expected;
|
|
486
509
|
}
|
|
487
510
|
async function waitForLock(lockPath, config) {
|
|
488
511
|
const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/constants.ts","../src/tokenizer.ts","../src/ml-detector.ts","../src/model-manager.ts","../src/errors.ts"],"sourcesContent":["import { MLDetector } from './ml-detector';\nimport { resolveModel } from './model-manager';\n\nexport { AgentArmorModelError } from './errors';\nexport { MLDetector } from './ml-detector';\nexport type { ModelArtifacts } from './model-manager';\n\n/**\n * Create an ML detector from config.\n * Called by AgentArmor.create() when ml config is provided.\n */\nexport async function createMLDetector(mlConfig: {\n modelDir?: string;\n enabled?: boolean;\n modelUrl?: string;\n download?: {\n timeoutMs?: number;\n retries?: number;\n onProgress?: (bytesReceived: number, totalBytes: number) => void;\n };\n}): Promise<MLDetector> {\n const artifacts = await resolveModel(mlConfig);\n return MLDetector.create(artifacts);\n}\n","import { homedir, platform } from 'os';\nimport { join } from 'path';\n\nexport const MODEL_VERSION = 'v1';\nexport const HF_REPO_ID = 'stylusnexus/agent-armor-classifier';\nexport const MODEL_FILENAME = 'model_quantized.onnx';\n\nexport const REQUIRED_MODEL_FILES = [\n 'model_quantized.onnx',\n 'tokenizer.json',\n 'label_map.json',\n] as const;\n\nexport const OPTIONAL_MODEL_FILES = [\n 'tokenizer_config.json',\n 'special_tokens_map.json',\n] as const;\n\nexport const MODEL_CHECKSUM = 'PLACEHOLDER_UPDATE_AFTER_FIRST_PUBLISH';\n\nexport const LABELS = [\n 'hidden-html',\n 'metadata-injection',\n 'dynamic-cloaking',\n 'syntactic-masking',\n 'embedded-jailbreak',\n 'data-exfiltration',\n 'sub-agent-spawning',\n 'rag-knowledge-poisoning',\n 'latent-memory-poisoning',\n 'contextual-learning-trap',\n 'biased-framing',\n 'oversight-evasion',\n 'persona-hyperstition',\n 'benign',\n] as const;\n\nexport const LABEL_TO_INDEX = Object.fromEntries(\n LABELS.map((label, i) => [label, i])\n) as Record<(typeof LABELS)[number], number>;\n\nexport function getDefaultCacheDir(): string {\n const envOverride = process.env.AGENTARMOR_CACHE_DIR;\n if (envOverride) return envOverride;\n\n const xdg = process.env.XDG_CACHE_HOME;\n if (xdg) return join(xdg, 'agentarmor', MODEL_VERSION);\n\n if (platform() === 'darwin') {\n return join(homedir(), 'Library', 'Caches', 'agentarmor', MODEL_VERSION);\n }\n\n return join(homedir(), '.cache', 'agentarmor', MODEL_VERSION);\n}\n\nexport const DEFAULT_TIMEOUT_MS = 120_000;\nexport const DEFAULT_RETRIES = 2;\n","import { readFile } from 'fs/promises';\n\n/**\n * Shape of the HuggingFace tokenizer.json we care about.\n * Full spec is much larger; we only read vocab + added_tokens.\n */\ninterface TokenizerJson {\n model: {\n vocab: Record<string, number>;\n };\n added_tokens: Array<{\n id: number;\n content: string;\n }>;\n}\n\nconst DEFAULT_SPECIAL: Record<string, number> = {\n '[UNK]': 0,\n '[CLS]': 1,\n '[SEP]': 2,\n '[PAD]': 0,\n};\n\n/**\n * Minimal WordPiece tokenizer for ONNX classification inference.\n *\n * Loads a HuggingFace `tokenizer.json` and produces `input_ids` +\n * `attention_mask` as BigInt64Arrays (ONNX Runtime requires int64 tensors).\n *\n * This intentionally covers the 90% case — full HuggingFace tokenizers\n * handle BPE, normalization, pre-tokenization, etc.\n */\nexport class Tokenizer {\n private readonly vocab: Map<string, number>;\n private readonly unkId: number;\n private readonly clsId: number;\n private readonly sepId: number;\n private readonly padId: number;\n\n private constructor(vocab: Map<string, number>, specialTokens: Record<string, number>) {\n this.vocab = vocab;\n this.unkId = specialTokens['[UNK]'] ?? DEFAULT_SPECIAL['[UNK]'];\n this.clsId = specialTokens['[CLS]'] ?? DEFAULT_SPECIAL['[CLS]'];\n this.sepId = specialTokens['[SEP]'] ?? DEFAULT_SPECIAL['[SEP]'];\n this.padId = specialTokens['[PAD]'] ?? DEFAULT_SPECIAL['[PAD]'];\n }\n\n /**\n * Load a tokenizer from a HuggingFace `tokenizer.json` file.\n */\n static async fromFile(path: string): Promise<Tokenizer> {\n const raw = await readFile(path, 'utf-8');\n const json: TokenizerJson = JSON.parse(raw);\n\n const vocab = new Map<string, number>(Object.entries(json.model.vocab));\n\n // Merge added_tokens into vocab so special tokens are resolvable\n const specialTokens: Record<string, number> = { ...DEFAULT_SPECIAL };\n for (const token of json.added_tokens) {\n vocab.set(token.content, token.id);\n if (token.content in DEFAULT_SPECIAL) {\n specialTokens[token.content] = token.id;\n }\n }\n\n return new Tokenizer(vocab, specialTokens);\n }\n\n /**\n * Encode text into `input_ids` and `attention_mask` BigInt64Arrays.\n *\n * Tokenization:\n * 1. Lowercase and split on whitespace\n * 2. WordPiece subword splitting for OOV words\n * 3. Wrap with [CLS] ... [SEP]\n * 4. Pad or truncate to `maxLength`\n */\n encode(\n text: string,\n maxLength: number = 512,\n ): { inputIds: BigInt64Array; attentionMask: BigInt64Array } {\n const tokens: number[] = [this.clsId];\n\n const words = text.toLowerCase().split(/\\s+/).filter(Boolean);\n\n for (const word of words) {\n const wordTokens = this.wordPieceTokenize(word);\n tokens.push(...wordTokens);\n }\n\n tokens.push(this.sepId);\n\n // Truncate content tokens if over maxLength (keep CLS at start, SEP at end)\n if (tokens.length > maxLength) {\n tokens.length = maxLength;\n tokens[maxLength - 1] = this.sepId;\n }\n\n const inputIds = new BigInt64Array(maxLength);\n const attentionMask = new BigInt64Array(maxLength);\n\n for (let i = 0; i < tokens.length; i++) {\n inputIds[i] = BigInt(tokens[i]);\n attentionMask[i] = 1n;\n }\n\n // Remaining positions stay 0n (pad token = 0, mask = 0)\n for (let i = tokens.length; i < maxLength; i++) {\n inputIds[i] = BigInt(this.padId);\n // attentionMask[i] is already 0n\n }\n\n return { inputIds, attentionMask };\n }\n\n /**\n * WordPiece tokenization for a single word.\n * Tries to greedily match the longest prefix in vocab, then continues\n * with `##` prefixed subwords. Falls back to [UNK] if no match at all.\n */\n private wordPieceTokenize(word: string): number[] {\n // Fast path: whole word exists in vocab\n if (this.vocab.has(word)) {\n return [this.vocab.get(word)!];\n }\n\n const tokens: number[] = [];\n let start = 0;\n\n while (start < word.length) {\n let end = word.length;\n let matched = false;\n\n while (start < end) {\n const substr = start === 0 ? word.slice(0, end) : `##${word.slice(start, end)}`;\n\n if (this.vocab.has(substr)) {\n tokens.push(this.vocab.get(substr)!);\n matched = true;\n break;\n }\n\n end--;\n }\n\n if (!matched) {\n // Entire word is unresolvable — return single [UNK]\n return [this.unkId];\n }\n\n start = end;\n }\n\n return tokens;\n }\n}\n","import { LABELS } from './constants';\nimport { Tokenizer } from './tokenizer';\nimport type { ModelArtifacts } from './model-manager';\n\n// Inline types matching @stylusnexus/agentarmor's Detector interface\n// These will be compatible at runtime via structural typing\ninterface DetectorOptions {\n strictness?: 'permissive' | 'balanced' | 'strict';\n}\n\ninterface DetectorResult {\n threats: Threat[];\n}\n\ninterface Threat {\n category: string;\n type: string;\n severity: 'low' | 'medium' | 'high' | 'critical';\n confidence: number;\n description: string;\n evidence: string;\n location?: { offset: number; length: number };\n detectorId: string;\n source: 'pattern' | 'ml' | 'custom';\n}\n\ninterface Detector {\n id: string;\n name: string;\n category: string;\n scan(content: string, options?: DetectorOptions): DetectorResult;\n scanAsync?(content: string, options?: DetectorOptions): Promise<DetectorResult>;\n sanitize(content: string, threats: Threat[]): string;\n}\n\n// ONNX Runtime types\ninterface OrtSession {\n run(feeds: Record<string, any>): Promise<Record<string, any>>;\n}\n\ninterface OrtModule {\n InferenceSession: { create(path: string): Promise<OrtSession> };\n Tensor: new (type: string, data: any, dims: number[]) => any;\n}\n\nconst THRESHOLDS: Record<string, number> = {\n strict: 0.3,\n balanced: 0.5,\n permissive: 0.7,\n};\n\nconst LABEL_TO_CATEGORY: Record<string, string> = {\n 'hidden-html': 'content-injection',\n 'metadata-injection': 'content-injection',\n 'dynamic-cloaking': 'content-injection',\n 'syntactic-masking': 'content-injection',\n 'embedded-jailbreak': 'behavioural-control',\n 'data-exfiltration': 'behavioural-control',\n 'sub-agent-spawning': 'behavioural-control',\n 'rag-knowledge-poisoning': 'cognitive-state',\n 'latent-memory-poisoning': 'cognitive-state',\n 'contextual-learning-trap': 'cognitive-state',\n 'biased-framing': 'semantic-manipulation',\n 'oversight-evasion': 'semantic-manipulation',\n 'persona-hyperstition': 'semantic-manipulation',\n 'benign': 'content-injection',\n};\n\nexport class MLDetector implements Detector {\n readonly id = 'ml-classifier';\n readonly name = 'ML Classifier (DeBERTa-v3-small)';\n readonly category = 'content-injection';\n\n private session: OrtSession;\n private tokenizer: Tokenizer;\n private ort: OrtModule;\n\n private constructor(session: OrtSession, tokenizer: Tokenizer, ort: OrtModule) {\n this.session = session;\n this.tokenizer = tokenizer;\n this.ort = ort;\n }\n\n static async create(artifacts: ModelArtifacts): Promise<MLDetector> {\n const ort = await import('onnxruntime-node') as unknown as OrtModule;\n const session = await ort.InferenceSession.create(artifacts.modelPath);\n const tokenizer = await Tokenizer.fromFile(artifacts.tokenizerPath);\n return new MLDetector(session, tokenizer, ort);\n }\n\n // Sync scan returns empty — ML inference is async only\n scan(_content: string, _options?: DetectorOptions): DetectorResult {\n return { threats: [] };\n }\n\n // Async scan runs ONNX inference\n async scanAsync(content: string, options?: DetectorOptions): Promise<DetectorResult> {\n const strictness = options?.strictness ?? 'balanced';\n const threshold = THRESHOLDS[strictness] ?? THRESHOLDS.balanced;\n\n const { inputIds, attentionMask } = this.tokenizer.encode(content, 512);\n\n const feeds: Record<string, any> = {\n input_ids: new this.ort.Tensor('int64', inputIds, [1, 512]),\n attention_mask: new this.ort.Tensor('int64', attentionMask, [1, 512]),\n };\n\n const results = await this.session.run(feeds);\n const logits = results.logits?.data as Float32Array;\n if (!logits) return { threats: [] };\n\n const threats: Threat[] = [];\n for (let i = 0; i < LABELS.length; i++) {\n const label = LABELS[i];\n if (label === 'benign') continue;\n\n const prob = 1 / (1 + Math.exp(-logits[i]));\n if (prob >= threshold) {\n threats.push({\n category: LABEL_TO_CATEGORY[label] ?? 'content-injection',\n type: label,\n severity: prob >= 0.9 ? 'critical' : prob >= 0.7 ? 'high' : prob >= 0.5 ? 'medium' : 'low',\n confidence: prob,\n description: `ML classifier detected ${label} (confidence: ${(prob * 100).toFixed(1)}%)`,\n evidence: content.slice(0, 200),\n detectorId: 'ml-classifier',\n source: 'ml',\n });\n }\n }\n\n return { threats };\n }\n\n // ML detector doesn't modify content — pattern detectors handle sanitization\n sanitize(content: string, _threats: Threat[]): string {\n return content;\n }\n}\n","import { createHash } from 'crypto';\nimport { createReadStream, createWriteStream } from 'fs';\nimport { access, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';\nimport { get as httpsGet } from 'https';\nimport { join } from 'path';\nimport { pipeline } from 'stream/promises';\n\nimport {\n DEFAULT_RETRIES,\n DEFAULT_TIMEOUT_MS,\n HF_REPO_ID,\n MODEL_CHECKSUM,\n MODEL_FILENAME,\n OPTIONAL_MODEL_FILES,\n REQUIRED_MODEL_FILES,\n getDefaultCacheDir,\n} from './constants';\nimport { AgentArmorModelError } from './errors';\n\nexport interface ModelArtifacts {\n modelPath: string;\n tokenizerPath: string;\n labelMapPath: string;\n modelDir: string;\n}\n\ninterface MLConfigLike {\n modelDir?: string;\n enabled?: boolean;\n modelUrl?: string;\n download?: {\n timeoutMs?: number;\n retries?: number;\n onProgress?: (bytesReceived: number, totalBytes: number) => void;\n };\n}\n\nfunction artifactsFrom(dir: string): ModelArtifacts {\n return {\n modelPath: join(dir, MODEL_FILENAME),\n tokenizerPath: join(dir, 'tokenizer.json'),\n labelMapPath: join(dir, 'label_map.json'),\n modelDir: dir,\n };\n}\n\n/**\n * Validate that all required model files exist in a directory.\n * Throws AgentArmorModelError('MODEL_NOT_FOUND') with a helpful message if any are missing.\n */\nexport async function validateModelDir(dir: string): Promise<void> {\n const missing: string[] = [];\n for (const file of REQUIRED_MODEL_FILES) {\n try {\n await access(join(dir, file));\n } catch {\n missing.push(file);\n }\n }\n if (missing.length > 0) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Missing required model files in ${dir}: ${missing.join(', ')}. ` +\n `Required files: ${REQUIRED_MODEL_FILES.join(', ')}`,\n );\n }\n}\n\n/**\n * Resolve model artifacts — either from a user-provided modelDir or from the cache.\n * Downloads from HuggingFace if not cached.\n */\nexport async function resolveModel(config: MLConfigLike = {}): Promise<ModelArtifacts> {\n const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;\n\n if (modelDir) {\n await validateModelDir(modelDir);\n return artifactsFrom(modelDir);\n }\n\n const cacheDir = getDefaultCacheDir();\n await mkdir(cacheDir, { recursive: true });\n\n // Check if a valid cached model exists\n try {\n await validateModelDir(cacheDir);\n return artifactsFrom(cacheDir);\n } catch {\n // Not cached — download\n }\n\n await downloadWithLock(cacheDir, config);\n return artifactsFrom(cacheDir);\n}\n\n/**\n * Acquire a lock file, download all model files, verify checksum, then release the lock.\n * If another process holds the lock, wait for it.\n */\nexport async function downloadWithLock(\n cacheDir: string,\n config: MLConfigLike,\n): Promise<void> {\n const lockPath = join(cacheDir, 'model.onnx.lock');\n\n let lockFd;\n try {\n lockFd = await open(lockPath, 'wx');\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n await waitForLock(lockPath, config);\n // After lock is released, check if model is now valid\n try {\n await validateModelDir(cacheDir);\n return;\n } catch {\n // Still missing — acquire lock and download ourselves\n lockFd = await open(lockPath, 'wx');\n }\n } else {\n throw err;\n }\n }\n\n try {\n // Download required files\n for (const file of REQUIRED_MODEL_FILES) {\n await downloadFile(file, cacheDir, config, false);\n }\n\n // Download optional files (silently skip on 404)\n for (const file of OPTIONAL_MODEL_FILES) {\n await downloadFile(file, cacheDir, config, true);\n }\n\n // Verify checksum of the main model file\n const modelPath = join(cacheDir, MODEL_FILENAME);\n const checksumOk = await verifyChecksum(modelPath);\n if (!checksumOk) {\n // Clean up the bad download\n for (const file of REQUIRED_MODEL_FILES) {\n await unlink(join(cacheDir, file)).catch(() => {});\n }\n throw new AgentArmorModelError(\n 'CHECKSUM_MISMATCH',\n `Model file checksum verification failed for ${modelPath}`,\n );\n }\n } finally {\n await lockFd.close();\n await unlink(lockPath).catch(() => {});\n }\n}\n\n/**\n * Download a single file from HuggingFace (or custom modelUrl) to destDir.\n * Downloads to a .tmp file, then atomically renames on success.\n * Retries with exponential backoff. Optional files return silently on 404.\n */\nexport async function downloadFile(\n filename: string,\n destDir: string,\n config: MLConfigLike,\n optional: boolean,\n): Promise<void> {\n const retries = config.download?.retries ?? DEFAULT_RETRIES;\n const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const onProgress = config.download?.onProgress;\n\n let baseUrl: string;\n if (config.modelUrl) {\n baseUrl = config.modelUrl.replace(/\\/$/, '');\n } else {\n baseUrl = `https://huggingface.co/${HF_REPO_ID}/resolve/main`;\n }\n\n const url = `${baseUrl}/${filename}`;\n const destPath = join(destDir, filename);\n const tmpPath = `${destPath}.tmp`;\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_TIMEOUT',\n `Download of ${filename} timed out after ${timeoutMs}ms`,\n ),\n );\n }, timeoutMs);\n\n const makeRequest = (requestUrl: string, redirectCount = 0): void => {\n if (redirectCount > 5) {\n clearTimeout(timer);\n reject(new AgentArmorModelError('DOWNLOAD_FAILED', `Too many redirects for ${filename}`));\n return;\n }\n\n const protocol = requestUrl.startsWith('https') ? httpsGet : httpsGet;\n const req = protocol(requestUrl, (res) => {\n if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {\n makeRequest(res.headers.location, redirectCount + 1);\n return;\n }\n\n if (res.statusCode === 404 && optional) {\n clearTimeout(timer);\n res.resume();\n resolve();\n return;\n }\n\n if (res.statusCode !== 200) {\n clearTimeout(timer);\n res.resume();\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Failed to download ${filename}: HTTP ${res.statusCode}`,\n ),\n );\n return;\n }\n\n const totalBytes = parseInt(res.headers['content-length'] || '0', 10);\n let receivedBytes = 0;\n\n if (onProgress) {\n res.on('data', (chunk: Buffer) => {\n receivedBytes += chunk.length;\n onProgress(receivedBytes, totalBytes);\n });\n }\n\n const ws = createWriteStream(tmpPath);\n pipeline(res, ws)\n .then(() => {\n clearTimeout(timer);\n resolve();\n })\n .catch((pipeErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Failed to write ${filename}`, pipeErr),\n );\n });\n });\n\n req.on('error', (reqErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Network error downloading ${filename}`, reqErr),\n );\n });\n };\n\n makeRequest(url);\n });\n\n // Atomic rename\n await rename(tmpPath, destPath);\n return;\n } catch (err) {\n // Clean up tmp file on failure\n await unlink(tmpPath).catch(() => {});\n\n if (err instanceof AgentArmorModelError && err.code === 'DOWNLOAD_TIMEOUT') {\n throw err;\n }\n\n // If optional and this was a 404-like error, just return\n if (optional && err instanceof AgentArmorModelError && err.code === 'DOWNLOAD_FAILED') {\n return;\n }\n\n if (attempt < retries) {\n // Exponential backoff: 1s, 2s, 4s...\n const delay = 1000 * Math.pow(2, attempt);\n await new Promise((r) => setTimeout(r, delay));\n continue;\n }\n\n throw err;\n }\n }\n}\n\n/**\n * Verify SHA-256 checksum of a file against MODEL_CHECKSUM.\n * Returns true if checksum matches. Skips (returns true) if checksum is a placeholder.\n */\nexport async function verifyChecksum(filePath: string): Promise<boolean> {\n if (MODEL_CHECKSUM.startsWith('PLACEHOLDER')) {\n return true;\n }\n\n const hash = createHash('sha256');\n const stream = createReadStream(filePath);\n for await (const chunk of stream) {\n hash.update(chunk);\n }\n const digest = hash.digest('hex');\n return digest === MODEL_CHECKSUM;\n}\n\n/**\n * Wait for a lock file to be released by another process.\n * Polls every 2 seconds. Breaks stale lock after timeout.\n */\nexport async function waitForLock(lockPath: string, config: MLConfigLike): Promise<void> {\n const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const pollInterval = 2000;\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeoutMs) {\n try {\n await access(lockPath);\n } catch {\n // Lock file gone — we can proceed\n return;\n }\n\n // Check for stale lock (older than timeout)\n try {\n const lockStat = await stat(lockPath);\n const lockAge = Date.now() - lockStat.mtimeMs;\n if (lockAge > timeoutMs) {\n // Stale lock — break it\n await unlink(lockPath).catch(() => {});\n return;\n }\n } catch {\n // Lock disappeared while checking — that's fine\n return;\n }\n\n await new Promise((r) => setTimeout(r, pollInterval));\n }\n\n // Timed out waiting — break the stale lock\n await unlink(lockPath).catch(() => {});\n throw new AgentArmorModelError(\n 'LOCK_TIMEOUT',\n `Timed out waiting for lock file ${lockPath} after ${timeoutMs}ms`,\n );\n}\n","export type ModelErrorCode =\n | 'MODEL_NOT_FOUND'\n | 'CHECKSUM_MISMATCH'\n | 'DOWNLOAD_FAILED'\n | 'DOWNLOAD_TIMEOUT'\n | 'DISK_FULL'\n | 'LOCK_TIMEOUT';\n\nexport class AgentArmorModelError extends Error {\n readonly code: ModelErrorCode;\n readonly cause?: Error;\n\n constructor(code: ModelErrorCode, message: string, cause?: Error) {\n super(message);\n this.name = 'AgentArmorModelError';\n this.code = code;\n this.cause = cause;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,gBAAkC;AAClC,kBAAqB;AAEd,IAAM,gBAAgB;AACtB,IAAM,aAAa;AACnB,IAAM,iBAAiB;AAEvB,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AACF;AAEO,IAAM,iBAAiB;AAEvB,IAAM,SAAS;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAC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,EACT;AAEA,QAAM,WAAO,0BAAW,QAAQ;AAChC,QAAM,aAAS,4BAAiB,QAAQ;AACxC,mBAAiB,SAAS,QAAQ;AAChC,SAAK,OAAO,KAAK;AAAA,EACnB;AACA,QAAM,SAAS,KAAK,OAAO,KAAK;AAChC,SAAO,WAAW;AACpB;AAMA,eAAsB,YAAY,UAAkB,QAAqC;AACvF,QAAM,YAAY,OAAO,UAAU,aAAa;AAChD,QAAM,eAAe;AACrB,QAAM,YAAY,KAAK,IAAI;AAE3B,SAAO,KAAK,IAAI,IAAI,YAAY,WAAW;AACzC,QAAI;AACF,gBAAM,yBAAO,QAAQ;AAAA,IACvB,QAAQ;AAEN;AAAA,IACF;AAGA,QAAI;AACF,YAAM,WAAW,UAAM,uBAAK,QAAQ;AACpC,YAAM,UAAU,KAAK,IAAI,IAAI,SAAS;AACtC,UAAI,UAAU,WAAW;AAEvB,kBAAM,yBAAO,QAAQ,EAAE,MAAM,MAAM;AAAA,QAAC,CAAC;AACrC;AAAA,MACF;AAAA,IACF,QAAQ;AAEN;AAAA,IACF;AAEA,UAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,YAAY,CAAC;AAAA,EACtD;AAGA,YAAM,yBAAO,QAAQ,EAAE,MAAM,MAAM;AAAA,EAAC,CAAC;AACrC,QAAM,IAAI;AAAA,IACR;AAAA,IACA,mCAAmC,QAAQ,UAAU,SAAS;AAAA,EAChE;AACF;;;AJ/UA,eAAsB,iBAAiB,UASf;AACtB,QAAM,YAAY,MAAM,aAAa,QAAQ;AAC7C,SAAO,WAAW,OAAO,SAAS;AACpC;","names":["import_promises","import_path","httpsGet"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/constants.ts","../src/tokenizer.ts","../src/errors.ts","../src/ml-detector.ts","../src/model-manager.ts"],"sourcesContent":["import { MLDetector } from './ml-detector';\nimport { resolveModel } from './model-manager';\n\nexport { AgentArmorModelError } from './errors';\nexport { MLDetector } from './ml-detector';\nexport type { ModelArtifacts } from './model-manager';\n\n/**\n * Create an ML detector from config.\n * Called by AgentArmor.create() when ml config is provided.\n */\nexport async function createMLDetector(mlConfig: {\n modelDir?: string;\n enabled?: boolean;\n modelUrl?: string;\n download?: {\n timeoutMs?: number;\n retries?: number;\n onProgress?: (bytesReceived: number, totalBytes: number) => void;\n };\n}): Promise<MLDetector> {\n const artifacts = await resolveModel(mlConfig);\n return MLDetector.create(artifacts);\n}\n","import { homedir, platform } from 'os';\nimport { join } from 'path';\n\nexport const MODEL_VERSION = 'v1';\nexport const HF_REPO_ID = 'stylusnexus/agent-armor-classifier';\nexport const MODEL_FILENAME = 'model_quantized.onnx';\n\nexport const REQUIRED_MODEL_FILES = [\n 'model_quantized.onnx',\n 'tokenizer.json',\n 'label_map.json',\n] as const;\n\nexport const OPTIONAL_MODEL_FILES = [\n 'tokenizer_config.json',\n 'special_tokens_map.json',\n] as const;\n\nexport const MODEL_CHECKSUM = '5d4c8551c958f398181c60239aebedbaa4ed5b641d1645904d2de9c2d02bd41f';\n\nexport const LABELS = [\n 'hidden-html',\n 'metadata-injection',\n 'dynamic-cloaking',\n 'syntactic-masking',\n 'embedded-jailbreak',\n 'data-exfiltration',\n 'sub-agent-spawning',\n 'rag-knowledge-poisoning',\n 'latent-memory-poisoning',\n 'contextual-learning-trap',\n 'biased-framing',\n 'oversight-evasion',\n 'persona-hyperstition',\n 'benign',\n] as const;\n\nexport const LABEL_TO_INDEX = Object.fromEntries(\n LABELS.map((label, i) => [label, i])\n) as Record<(typeof LABELS)[number], number>;\n\nexport function getDefaultCacheDir(): string {\n const envOverride = process.env.AGENTARMOR_CACHE_DIR;\n if (envOverride) return envOverride;\n\n const xdg = process.env.XDG_CACHE_HOME;\n if (xdg) return join(xdg, 'agentarmor', MODEL_VERSION);\n\n if (platform() === 'darwin') {\n return join(homedir(), 'Library', 'Caches', 'agentarmor', MODEL_VERSION);\n }\n\n return join(homedir(), '.cache', 'agentarmor', MODEL_VERSION);\n}\n\nexport const DEFAULT_TIMEOUT_MS = 120_000;\nexport const DEFAULT_RETRIES = 2;\n","import { readFile } from 'fs/promises';\nimport { AgentArmorModelError } from './errors';\n\n/**\n * Shape of the HuggingFace tokenizer.json we care about.\n * Full spec is much larger; we only read vocab + added_tokens.\n *\n * Both fields are optional here on purpose: this describes a file we did not\n * write and cannot assume is well-formed (users may point `modelDir` at their\n * own directory). `fromFile` validates rather than trusting the annotation.\n */\ninterface TokenizerJson {\n model?: {\n vocab?: Record<string, number>;\n };\n added_tokens?: Array<{\n id: number;\n content: string;\n }>;\n}\n\nconst DEFAULT_SPECIAL: Record<string, number> = {\n '[UNK]': 0,\n '[CLS]': 1,\n '[SEP]': 2,\n '[PAD]': 0,\n};\n\n/**\n * Minimal WordPiece tokenizer for ONNX classification inference.\n *\n * Loads a HuggingFace `tokenizer.json` and produces `input_ids` +\n * `attention_mask` as BigInt64Arrays (ONNX Runtime requires int64 tensors).\n *\n * This intentionally covers the 90% case — full HuggingFace tokenizers\n * handle BPE, normalization, pre-tokenization, etc.\n */\nexport class Tokenizer {\n private readonly vocab: Map<string, number>;\n private readonly unkId: number;\n private readonly clsId: number;\n private readonly sepId: number;\n private readonly padId: number;\n\n private constructor(vocab: Map<string, number>, specialTokens: Record<string, number>) {\n this.vocab = vocab;\n this.unkId = specialTokens['[UNK]'] ?? DEFAULT_SPECIAL['[UNK]'];\n this.clsId = specialTokens['[CLS]'] ?? DEFAULT_SPECIAL['[CLS]'];\n this.sepId = specialTokens['[SEP]'] ?? DEFAULT_SPECIAL['[SEP]'];\n this.padId = specialTokens['[PAD]'] ?? DEFAULT_SPECIAL['[PAD]'];\n }\n\n /**\n * Load a tokenizer from a HuggingFace `tokenizer.json` file.\n */\n static async fromFile(path: string): Promise<Tokenizer> {\n const raw = await readFile(path, 'utf-8');\n\n let json: TokenizerJson;\n try {\n json = JSON.parse(raw) as TokenizerJson;\n } catch (err) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} is not valid JSON. The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`,\n err instanceof Error ? err : undefined\n );\n }\n\n // A truncated or hand-assembled tokenizer.json used to fail here with a bare\n // TypeError from deep inside this function, escaping the typed-error contract\n // every other load path in this package honours. MODEL_NOT_FOUND is the right\n // code even though the file exists: the correct recovery is the same one — go\n // get the artifacts again.\n if (!json.model?.vocab) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} is missing \"model.vocab\". The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`\n );\n }\n\n const vocab = new Map<string, number>(Object.entries(json.model.vocab));\n\n // `added_tokens` absent is tolerated rather than fatal — the special tokens\n // it usually supplies fall back to DEFAULT_SPECIAL, so the tokenizer is still\n // usable. Only a missing vocab makes it unusable.\n const specialTokens: Record<string, number> = { ...DEFAULT_SPECIAL };\n for (const token of json.added_tokens ?? []) {\n vocab.set(token.content, token.id);\n if (token.content in DEFAULT_SPECIAL) {\n specialTokens[token.content] = token.id;\n }\n }\n\n return new Tokenizer(vocab, specialTokens);\n }\n\n /**\n * Encode text into `input_ids` and `attention_mask` BigInt64Arrays.\n *\n * Tokenization:\n * 1. Lowercase and split on whitespace\n * 2. WordPiece subword splitting for OOV words\n * 3. Wrap with [CLS] ... [SEP]\n * 4. Pad or truncate to `maxLength`\n */\n encode(\n text: string,\n maxLength: number = 512,\n ): { inputIds: BigInt64Array; attentionMask: BigInt64Array } {\n const tokens: number[] = [this.clsId];\n\n const words = text.toLowerCase().split(/\\s+/).filter(Boolean);\n\n for (const word of words) {\n const wordTokens = this.wordPieceTokenize(word);\n tokens.push(...wordTokens);\n }\n\n tokens.push(this.sepId);\n\n // Truncate content tokens if over maxLength (keep CLS at start, SEP at end)\n if (tokens.length > maxLength) {\n tokens.length = maxLength;\n tokens[maxLength - 1] = this.sepId;\n }\n\n const inputIds = new BigInt64Array(maxLength);\n const attentionMask = new BigInt64Array(maxLength);\n\n for (let i = 0; i < tokens.length; i++) {\n inputIds[i] = BigInt(tokens[i]);\n attentionMask[i] = 1n;\n }\n\n // Remaining positions stay 0n (pad token = 0, mask = 0)\n for (let i = tokens.length; i < maxLength; i++) {\n inputIds[i] = BigInt(this.padId);\n // attentionMask[i] is already 0n\n }\n\n return { inputIds, attentionMask };\n }\n\n /**\n * WordPiece tokenization for a single word.\n * Tries to greedily match the longest prefix in vocab, then continues\n * with `##` prefixed subwords. Falls back to [UNK] if no match at all.\n */\n private wordPieceTokenize(word: string): number[] {\n // Fast path: whole word exists in vocab\n if (this.vocab.has(word)) {\n return [this.vocab.get(word)!];\n }\n\n const tokens: number[] = [];\n let start = 0;\n\n while (start < word.length) {\n let end = word.length;\n let matched = false;\n\n while (start < end) {\n const substr = start === 0 ? word.slice(0, end) : `##${word.slice(start, end)}`;\n\n if (this.vocab.has(substr)) {\n tokens.push(this.vocab.get(substr)!);\n matched = true;\n break;\n }\n\n end--;\n }\n\n if (!matched) {\n // Entire word is unresolvable — return single [UNK]\n return [this.unkId];\n }\n\n start = end;\n }\n\n return tokens;\n }\n}\n","/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */\nexport type ModelErrorCode =\n | 'MODEL_NOT_FOUND'\n | 'CHECKSUM_MISMATCH'\n | 'DOWNLOAD_FAILED'\n | 'DOWNLOAD_TIMEOUT'\n | 'DISK_FULL'\n | 'LOCK_TIMEOUT';\n\n/** Thrown when the ML model can't be resolved (missing, corrupt, or unreachable). */\nexport class AgentArmorModelError extends Error {\n /** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */\n readonly code: ModelErrorCode;\n /** The underlying error, when this wraps one (e.g. a failed fetch). */\n readonly cause?: Error;\n\n constructor(code: ModelErrorCode, message: string, cause?: Error) {\n super(message);\n this.name = 'AgentArmorModelError';\n this.code = code;\n this.cause = cause;\n }\n}\n","import { LABELS, MODEL_VERSION } from './constants';\nimport { Tokenizer } from './tokenizer';\nimport type { ModelArtifacts } from './model-manager';\n\n// Inline types matching @stylusnexus/agentarmor's Detector interface\n// These will be compatible at runtime via structural typing\ninterface DetectorOptions {\n strictness?: 'permissive' | 'balanced' | 'strict';\n}\n\ninterface DetectorResult {\n threats: Threat[];\n}\n\ninterface Threat {\n category: string;\n type: string;\n severity: 'low' | 'medium' | 'high' | 'critical';\n confidence: number;\n description: string;\n evidence: string;\n location?: { offset: number; length: number };\n detectorId: string;\n source: 'pattern' | 'ml' | 'custom';\n}\n\ninterface Detector {\n id: string;\n name: string;\n category: string;\n scan(content: string, options?: DetectorOptions): DetectorResult;\n scanAsync?(content: string, options?: DetectorOptions): Promise<DetectorResult>;\n sanitize(content: string, threats: Threat[]): string;\n}\n\n// ONNX Runtime types\ninterface OrtSession {\n run(feeds: Record<string, any>): Promise<Record<string, any>>;\n}\n\ninterface OrtModule {\n InferenceSession: { create(path: string): Promise<OrtSession> };\n Tensor: new (type: string, data: any, dims: number[]) => any;\n}\n\nconst THRESHOLDS: Record<string, number> = {\n strict: 0.3,\n balanced: 0.5,\n permissive: 0.7,\n};\n\nconst LABEL_TO_CATEGORY: Record<string, string> = {\n 'hidden-html': 'content-injection',\n 'metadata-injection': 'content-injection',\n 'dynamic-cloaking': 'content-injection',\n 'syntactic-masking': 'content-injection',\n 'embedded-jailbreak': 'behavioural-control',\n 'data-exfiltration': 'behavioural-control',\n 'sub-agent-spawning': 'behavioural-control',\n 'rag-knowledge-poisoning': 'cognitive-state',\n 'latent-memory-poisoning': 'cognitive-state',\n 'contextual-learning-trap': 'cognitive-state',\n 'biased-framing': 'semantic-manipulation',\n 'oversight-evasion': 'semantic-manipulation',\n 'persona-hyperstition': 'semantic-manipulation',\n 'benign': 'content-injection',\n};\n\n/**\n * ONNX-based detector running the DeBERTa-v3-small multi-label classifier.\n * Implements Agent Armor's `Detector` interface via structural typing —\n * {@link MLDetector.create} loads the model; {@link MLDetector.scanAsync}\n * runs inference. {@link MLDetector.scan} (sync) always returns no threats,\n * since ONNX inference is async-only.\n */\nexport class MLDetector implements Detector {\n /** Unique identifier for this detector. */\n readonly id = 'ml-classifier';\n /** Human-readable name. */\n readonly name = 'ML Classifier (DeBERTa-v3-small)';\n /** Trap category this detector's labels currently map into. */\n readonly category = 'content-injection';\n /** Model version — surfaced on AuditRecord.mlModelVersion when this detector ran (#75). */\n readonly version = MODEL_VERSION;\n\n private session: OrtSession;\n private tokenizer: Tokenizer;\n private ort: OrtModule;\n\n private constructor(session: OrtSession, tokenizer: Tokenizer, ort: OrtModule) {\n this.session = session;\n this.tokenizer = tokenizer;\n this.ort = ort;\n }\n\n /** Loads the ONNX session and tokenizer from resolved {@link ModelArtifacts}. */\n static async create(artifacts: ModelArtifacts): Promise<MLDetector> {\n const ort = await import('onnxruntime-node') as unknown as OrtModule;\n const session = await ort.InferenceSession.create(artifacts.modelPath);\n const tokenizer = await Tokenizer.fromFile(artifacts.tokenizerPath);\n return new MLDetector(session, tokenizer, ort);\n }\n\n /** Always returns no threats — ML inference is async-only, use {@link scanAsync}. */\n scan(_content: string, _options?: DetectorOptions): DetectorResult {\n return { threats: [] };\n }\n\n /** Tokenizes `content`, runs ONNX inference, and returns threats above the strictness threshold. */\n async scanAsync(content: string, options?: DetectorOptions): Promise<DetectorResult> {\n const strictness = options?.strictness ?? 'balanced';\n const threshold = THRESHOLDS[strictness] ?? THRESHOLDS.balanced;\n\n const { inputIds, attentionMask } = this.tokenizer.encode(content, 512);\n\n const feeds: Record<string, any> = {\n input_ids: new this.ort.Tensor('int64', inputIds, [1, 512]),\n attention_mask: new this.ort.Tensor('int64', attentionMask, [1, 512]),\n };\n\n const results = await this.session.run(feeds);\n const logits = results.logits?.data as Float32Array;\n if (!logits) return { threats: [] };\n\n const threats: Threat[] = [];\n for (let i = 0; i < LABELS.length; i++) {\n const label = LABELS[i];\n if (label === 'benign') continue;\n\n const prob = 1 / (1 + Math.exp(-logits[i]));\n if (prob >= threshold) {\n threats.push({\n category: LABEL_TO_CATEGORY[label] ?? 'content-injection',\n type: label,\n severity: prob >= 0.9 ? 'critical' : prob >= 0.7 ? 'high' : prob >= 0.5 ? 'medium' : 'low',\n confidence: prob,\n description: `ML classifier detected ${label} (confidence: ${(prob * 100).toFixed(1)}%)`,\n evidence: content.slice(0, 200),\n detectorId: 'ml-classifier',\n source: 'ml',\n });\n }\n }\n\n return { threats };\n }\n\n /** Passthrough — the ML detector doesn't modify content; pattern detectors sanitize. */\n sanitize(content: string, _threats: Threat[]): string {\n return content;\n }\n}\n","import { createHash } from 'crypto';\nimport { createReadStream, createWriteStream } from 'fs';\nimport { access, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';\nimport { get as httpsGet } from 'https';\nimport { join } from 'path';\nimport { pipeline } from 'stream/promises';\n\nimport {\n DEFAULT_RETRIES,\n DEFAULT_TIMEOUT_MS,\n HF_REPO_ID,\n MODEL_CHECKSUM,\n MODEL_FILENAME,\n OPTIONAL_MODEL_FILES,\n REQUIRED_MODEL_FILES,\n getDefaultCacheDir,\n} from './constants';\nimport { AgentArmorModelError } from './errors';\n\n/** Resolved on-disk paths to the ONNX model and its supporting files. */\nexport interface ModelArtifacts {\n /** Path to `model_quantized.onnx`. */\n modelPath: string;\n /** Path to `tokenizer.json`. */\n tokenizerPath: string;\n /** Path to `label_map.json`. */\n labelMapPath: string;\n /** Directory containing all resolved model files. */\n modelDir: string;\n}\n\ninterface MLConfigLike {\n modelDir?: string;\n enabled?: boolean;\n modelUrl?: string;\n download?: {\n timeoutMs?: number;\n retries?: number;\n onProgress?: (bytesReceived: number, totalBytes: number) => void;\n };\n}\n\nfunction artifactsFrom(dir: string): ModelArtifacts {\n return {\n modelPath: join(dir, MODEL_FILENAME),\n tokenizerPath: join(dir, 'tokenizer.json'),\n labelMapPath: join(dir, 'label_map.json'),\n modelDir: dir,\n };\n}\n\n/**\n * Validate that all required model files exist in a directory.\n * Throws AgentArmorModelError('MODEL_NOT_FOUND') with a helpful message if any are missing.\n */\nexport async function validateModelDir(dir: string): Promise<void> {\n const missing: string[] = [];\n for (const file of REQUIRED_MODEL_FILES) {\n try {\n await access(join(dir, file));\n } catch {\n missing.push(file);\n }\n }\n if (missing.length > 0) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Missing required model files in ${dir}: ${missing.join(', ')}. ` +\n `Required files: ${REQUIRED_MODEL_FILES.join(', ')}`,\n );\n }\n}\n\n/**\n * Resolve model artifacts — either from a user-provided modelDir or from the cache.\n * Downloads from HuggingFace if not cached.\n */\nexport async function resolveModel(config: MLConfigLike = {}): Promise<ModelArtifacts> {\n const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;\n\n if (modelDir) {\n await validateModelDir(modelDir);\n return artifactsFrom(modelDir);\n }\n\n const cacheDir = getDefaultCacheDir();\n await mkdir(cacheDir, { recursive: true });\n\n // Check if a valid cached model exists\n try {\n await validateModelDir(cacheDir);\n return artifactsFrom(cacheDir);\n } catch {\n // Not cached — download\n }\n\n await downloadWithLock(cacheDir, config);\n return artifactsFrom(cacheDir);\n}\n\n/**\n * Acquire a lock file, download all model files, verify checksum, then release the lock.\n * If another process holds the lock, wait for it.\n */\nexport async function downloadWithLock(\n cacheDir: string,\n config: MLConfigLike,\n): Promise<void> {\n const lockPath = join(cacheDir, 'model.onnx.lock');\n\n let lockFd;\n try {\n lockFd = await open(lockPath, 'wx');\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n await waitForLock(lockPath, config);\n // After lock is released, check if model is now valid\n try {\n await validateModelDir(cacheDir);\n return;\n } catch {\n // Still missing — acquire lock and download ourselves\n lockFd = await open(lockPath, 'wx');\n }\n } else {\n throw err;\n }\n }\n\n try {\n // Download required files\n for (const file of REQUIRED_MODEL_FILES) {\n await downloadFile(file, cacheDir, config, false);\n }\n\n // Download optional files (silently skip on 404)\n for (const file of OPTIONAL_MODEL_FILES) {\n await downloadFile(file, cacheDir, config, true);\n }\n\n // Verify checksum of the main model file\n const modelPath = join(cacheDir, MODEL_FILENAME);\n const checksumOk = await verifyChecksum(modelPath);\n if (!checksumOk) {\n // Clean up the bad download\n for (const file of REQUIRED_MODEL_FILES) {\n await unlink(join(cacheDir, file)).catch(() => {});\n }\n throw new AgentArmorModelError(\n 'CHECKSUM_MISMATCH',\n `Model file checksum verification failed for ${modelPath}`,\n );\n }\n } finally {\n await lockFd.close();\n await unlink(lockPath).catch(() => {});\n }\n}\n\n/**\n * Download a single file from HuggingFace (or custom modelUrl) to destDir.\n * Downloads to a .tmp file, then atomically renames on success.\n * Retries with exponential backoff. Optional files return silently on 404.\n */\nexport async function downloadFile(\n filename: string,\n destDir: string,\n config: MLConfigLike,\n optional: boolean,\n): Promise<void> {\n const retries = config.download?.retries ?? DEFAULT_RETRIES;\n const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const onProgress = config.download?.onProgress;\n\n let baseUrl: string;\n if (config.modelUrl) {\n baseUrl = config.modelUrl.replace(/\\/$/, '');\n } else {\n baseUrl = `https://huggingface.co/${HF_REPO_ID}/resolve/main`;\n }\n\n const url = `${baseUrl}/${filename}`;\n const destPath = join(destDir, filename);\n const tmpPath = `${destPath}.tmp`;\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_TIMEOUT',\n `Download of ${filename} timed out after ${timeoutMs}ms`,\n ),\n );\n }, timeoutMs);\n\n const makeRequest = (requestUrl: string, redirectCount = 0): void => {\n if (redirectCount > 5) {\n clearTimeout(timer);\n reject(new AgentArmorModelError('DOWNLOAD_FAILED', `Too many redirects for ${filename}`));\n return;\n }\n\n const protocol = requestUrl.startsWith('https') ? httpsGet : httpsGet;\n const req = protocol(requestUrl, (res) => {\n if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {\n makeRequest(res.headers.location, redirectCount + 1);\n return;\n }\n\n if (res.statusCode === 404 && optional) {\n clearTimeout(timer);\n res.resume();\n resolve();\n return;\n }\n\n if (res.statusCode !== 200) {\n clearTimeout(timer);\n res.resume();\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Failed to download ${filename}: HTTP ${res.statusCode}`,\n ),\n );\n return;\n }\n\n const totalBytes = parseInt(res.headers['content-length'] || '0', 10);\n let receivedBytes = 0;\n\n if (onProgress) {\n res.on('data', (chunk: Buffer) => {\n receivedBytes += chunk.length;\n onProgress(receivedBytes, totalBytes);\n });\n }\n\n const ws = createWriteStream(tmpPath);\n pipeline(res, ws)\n .then(() => {\n clearTimeout(timer);\n resolve();\n })\n .catch((pipeErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Failed to write ${filename}`, pipeErr),\n );\n });\n });\n\n req.on('error', (reqErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Network error downloading ${filename}`, reqErr),\n );\n });\n };\n\n makeRequest(url);\n });\n\n // Atomic rename\n await rename(tmpPath, destPath);\n return;\n } catch (err) {\n // Clean up tmp file on failure\n await unlink(tmpPath).catch(() => {});\n\n if (err instanceof AgentArmorModelError && err.code === 'DOWNLOAD_TIMEOUT') {\n throw err;\n }\n\n // If optional and this was a 404-like error, just return\n if (optional && err instanceof AgentArmorModelError && err.code === 'DOWNLOAD_FAILED') {\n return;\n }\n\n if (attempt < retries) {\n // Exponential backoff: 1s, 2s, 4s...\n const delay = 1000 * Math.pow(2, attempt);\n await new Promise((r) => setTimeout(r, delay));\n continue;\n }\n\n throw err;\n }\n }\n}\n\n/**\n * Verify the SHA-256 checksum of a file against an expected value (defaults to\n * the shipped MODEL_CHECKSUM). Returns true if the digest matches. Skips\n * verification (returns true) when the expected checksum is a placeholder.\n *\n * `expected` is parameterized so the behavior can be exercised independently of\n * whichever real checksum the package currently ships.\n */\nexport async function verifyChecksum(\n filePath: string,\n expected: string = MODEL_CHECKSUM,\n): Promise<boolean> {\n if (expected.startsWith('PLACEHOLDER')) {\n return true;\n }\n\n const hash = createHash('sha256');\n const stream = createReadStream(filePath);\n for await (const chunk of stream) {\n hash.update(chunk);\n }\n const digest = hash.digest('hex');\n return digest === expected;\n}\n\n/**\n * Wait for a lock file to be released by another process.\n * Polls every 2 seconds. Breaks stale lock after timeout.\n */\nexport async function waitForLock(lockPath: string, config: MLConfigLike): Promise<void> {\n const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const pollInterval = 2000;\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeoutMs) {\n try {\n await access(lockPath);\n } catch {\n // Lock file gone — we can proceed\n return;\n }\n\n // Check for stale lock (older than timeout)\n try {\n const lockStat = await stat(lockPath);\n const lockAge = Date.now() - lockStat.mtimeMs;\n if (lockAge > timeoutMs) {\n // Stale lock — break it\n await unlink(lockPath).catch(() => {});\n return;\n }\n } catch {\n // Lock disappeared while checking — that's fine\n return;\n }\n\n await new Promise((r) => setTimeout(r, pollInterval));\n }\n\n // Timed out waiting — break the stale lock\n await unlink(lockPath).catch(() => {});\n throw new AgentArmorModelError(\n 'LOCK_TIMEOUT',\n `Timed out waiting for lock file ${lockPath} after ${timeoutMs}ms`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,gBAAkC;AAClC,kBAAqB;AAEd,IAAM,gBAAgB;AACtB,IAAM,aAAa;AACnB,IAAM,iBAAiB;AAEvB,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AACF;AAEO,IAAM,iBAAiB;AAEvB,IAAM,SAAS;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,iBAAiB,OAAO;AAAA,EACnC,OAAO,IAAI,CAAC,OAAO,MA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AAC7C,SAAO,WAAW,OAAO,SAAS;AACpC;","names":["import_promises","import_path","httpsGet"]}
|
package/dist/index.mjs
CHANGED
|
@@ -13,7 +13,7 @@ var OPTIONAL_MODEL_FILES = [
|
|
|
13
13
|
"tokenizer_config.json",
|
|
14
14
|
"special_tokens_map.json"
|
|
15
15
|
];
|
|
16
|
-
var MODEL_CHECKSUM = "
|
|
16
|
+
var MODEL_CHECKSUM = "5d4c8551c958f398181c60239aebedbaa4ed5b641d1645904d2de9c2d02bd41f";
|
|
17
17
|
var LABELS = [
|
|
18
18
|
"hidden-html",
|
|
19
19
|
"metadata-injection",
|
|
@@ -48,6 +48,22 @@ var DEFAULT_RETRIES = 2;
|
|
|
48
48
|
|
|
49
49
|
// src/tokenizer.ts
|
|
50
50
|
import { readFile } from "fs/promises";
|
|
51
|
+
|
|
52
|
+
// src/errors.ts
|
|
53
|
+
var AgentArmorModelError = class extends Error {
|
|
54
|
+
/** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */
|
|
55
|
+
code;
|
|
56
|
+
/** The underlying error, when this wraps one (e.g. a failed fetch). */
|
|
57
|
+
cause;
|
|
58
|
+
constructor(code, message, cause) {
|
|
59
|
+
super(message);
|
|
60
|
+
this.name = "AgentArmorModelError";
|
|
61
|
+
this.code = code;
|
|
62
|
+
this.cause = cause;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// src/tokenizer.ts
|
|
51
67
|
var DEFAULT_SPECIAL = {
|
|
52
68
|
"[UNK]": 0,
|
|
53
69
|
"[CLS]": 1,
|
|
@@ -72,10 +88,25 @@ var Tokenizer = class _Tokenizer {
|
|
|
72
88
|
*/
|
|
73
89
|
static async fromFile(path) {
|
|
74
90
|
const raw = await readFile(path, "utf-8");
|
|
75
|
-
|
|
91
|
+
let json;
|
|
92
|
+
try {
|
|
93
|
+
json = JSON.parse(raw);
|
|
94
|
+
} catch (err) {
|
|
95
|
+
throw new AgentArmorModelError(
|
|
96
|
+
"MODEL_NOT_FOUND",
|
|
97
|
+
`Tokenizer file at ${path} is not valid JSON. The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`,
|
|
98
|
+
err instanceof Error ? err : void 0
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
if (!json.model?.vocab) {
|
|
102
|
+
throw new AgentArmorModelError(
|
|
103
|
+
"MODEL_NOT_FOUND",
|
|
104
|
+
`Tokenizer file at ${path} is missing "model.vocab". The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`
|
|
105
|
+
);
|
|
106
|
+
}
|
|
76
107
|
const vocab = new Map(Object.entries(json.model.vocab));
|
|
77
108
|
const specialTokens = { ...DEFAULT_SPECIAL };
|
|
78
|
-
for (const token of json.added_tokens) {
|
|
109
|
+
for (const token of json.added_tokens ?? []) {
|
|
79
110
|
vocab.set(token.content, token.id);
|
|
80
111
|
if (token.content in DEFAULT_SPECIAL) {
|
|
81
112
|
specialTokens[token.content] = token.id;
|
|
@@ -170,9 +201,14 @@ var LABEL_TO_CATEGORY = {
|
|
|
170
201
|
"benign": "content-injection"
|
|
171
202
|
};
|
|
172
203
|
var MLDetector = class _MLDetector {
|
|
204
|
+
/** Unique identifier for this detector. */
|
|
173
205
|
id = "ml-classifier";
|
|
206
|
+
/** Human-readable name. */
|
|
174
207
|
name = "ML Classifier (DeBERTa-v3-small)";
|
|
208
|
+
/** Trap category this detector's labels currently map into. */
|
|
175
209
|
category = "content-injection";
|
|
210
|
+
/** Model version — surfaced on AuditRecord.mlModelVersion when this detector ran (#75). */
|
|
211
|
+
version = MODEL_VERSION;
|
|
176
212
|
session;
|
|
177
213
|
tokenizer;
|
|
178
214
|
ort;
|
|
@@ -181,17 +217,18 @@ var MLDetector = class _MLDetector {
|
|
|
181
217
|
this.tokenizer = tokenizer;
|
|
182
218
|
this.ort = ort;
|
|
183
219
|
}
|
|
220
|
+
/** Loads the ONNX session and tokenizer from resolved {@link ModelArtifacts}. */
|
|
184
221
|
static async create(artifacts) {
|
|
185
222
|
const ort = await import("onnxruntime-node");
|
|
186
223
|
const session = await ort.InferenceSession.create(artifacts.modelPath);
|
|
187
224
|
const tokenizer = await Tokenizer.fromFile(artifacts.tokenizerPath);
|
|
188
225
|
return new _MLDetector(session, tokenizer, ort);
|
|
189
226
|
}
|
|
190
|
-
|
|
227
|
+
/** Always returns no threats — ML inference is async-only, use {@link scanAsync}. */
|
|
191
228
|
scan(_content, _options) {
|
|
192
229
|
return { threats: [] };
|
|
193
230
|
}
|
|
194
|
-
|
|
231
|
+
/** Tokenizes `content`, runs ONNX inference, and returns threats above the strictness threshold. */
|
|
195
232
|
async scanAsync(content, options) {
|
|
196
233
|
const strictness = options?.strictness ?? "balanced";
|
|
197
234
|
const threshold = THRESHOLDS[strictness] ?? THRESHOLDS.balanced;
|
|
@@ -223,7 +260,7 @@ var MLDetector = class _MLDetector {
|
|
|
223
260
|
}
|
|
224
261
|
return { threats };
|
|
225
262
|
}
|
|
226
|
-
|
|
263
|
+
/** Passthrough — the ML detector doesn't modify content; pattern detectors sanitize. */
|
|
227
264
|
sanitize(content, _threats) {
|
|
228
265
|
return content;
|
|
229
266
|
}
|
|
@@ -236,20 +273,6 @@ import { access, mkdir, open, rename, stat, unlink } from "fs/promises";
|
|
|
236
273
|
import { get as httpsGet } from "https";
|
|
237
274
|
import { join as join2 } from "path";
|
|
238
275
|
import { pipeline } from "stream/promises";
|
|
239
|
-
|
|
240
|
-
// src/errors.ts
|
|
241
|
-
var AgentArmorModelError = class extends Error {
|
|
242
|
-
code;
|
|
243
|
-
cause;
|
|
244
|
-
constructor(code, message, cause) {
|
|
245
|
-
super(message);
|
|
246
|
-
this.name = "AgentArmorModelError";
|
|
247
|
-
this.code = code;
|
|
248
|
-
this.cause = cause;
|
|
249
|
-
}
|
|
250
|
-
};
|
|
251
|
-
|
|
252
|
-
// src/model-manager.ts
|
|
253
276
|
function artifactsFrom(dir) {
|
|
254
277
|
return {
|
|
255
278
|
modelPath: join2(dir, MODEL_FILENAME),
|
|
@@ -434,8 +457,8 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
434
457
|
}
|
|
435
458
|
}
|
|
436
459
|
}
|
|
437
|
-
async function verifyChecksum(filePath) {
|
|
438
|
-
if (
|
|
460
|
+
async function verifyChecksum(filePath, expected = MODEL_CHECKSUM) {
|
|
461
|
+
if (expected.startsWith("PLACEHOLDER")) {
|
|
439
462
|
return true;
|
|
440
463
|
}
|
|
441
464
|
const hash = createHash("sha256");
|
|
@@ -444,7 +467,7 @@ async function verifyChecksum(filePath) {
|
|
|
444
467
|
hash.update(chunk);
|
|
445
468
|
}
|
|
446
469
|
const digest = hash.digest("hex");
|
|
447
|
-
return digest ===
|
|
470
|
+
return digest === expected;
|
|
448
471
|
}
|
|
449
472
|
async function waitForLock(lockPath, config) {
|
|
450
473
|
const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/constants.ts","../src/tokenizer.ts","../src/ml-detector.ts","../src/model-manager.ts","../src/errors.ts","../src/index.ts"],"sourcesContent":["import { homedir, platform } from 'os';\nimport { join } from 'path';\n\nexport const MODEL_VERSION = 'v1';\nexport const HF_REPO_ID = 'stylusnexus/agent-armor-classifier';\nexport const MODEL_FILENAME = 'model_quantized.onnx';\n\nexport const REQUIRED_MODEL_FILES = [\n 'model_quantized.onnx',\n 'tokenizer.json',\n 'label_map.json',\n] as const;\n\nexport const OPTIONAL_MODEL_FILES = [\n 'tokenizer_config.json',\n 'special_tokens_map.json',\n] as const;\n\nexport const MODEL_CHECKSUM = 'PLACEHOLDER_UPDATE_AFTER_FIRST_PUBLISH';\n\nexport const LABELS = [\n 'hidden-html',\n 'metadata-injection',\n 'dynamic-cloaking',\n 'syntactic-masking',\n 'embedded-jailbreak',\n 'data-exfiltration',\n 'sub-agent-spawning',\n 'rag-knowledge-poisoning',\n 'latent-memory-poisoning',\n 'contextual-learning-trap',\n 'biased-framing',\n 'oversight-evasion',\n 'persona-hyperstition',\n 'benign',\n] as const;\n\nexport const LABEL_TO_INDEX = Object.fromEntries(\n LABELS.map((label, i) => [label, i])\n) as Record<(typeof LABELS)[number], number>;\n\nexport function getDefaultCacheDir(): string {\n const envOverride = process.env.AGENTARMOR_CACHE_DIR;\n if (envOverride) return envOverride;\n\n const xdg = process.env.XDG_CACHE_HOME;\n if (xdg) return join(xdg, 'agentarmor', MODEL_VERSION);\n\n if (platform() === 'darwin') {\n return join(homedir(), 'Library', 'Caches', 'agentarmor', MODEL_VERSION);\n }\n\n return join(homedir(), '.cache', 'agentarmor', MODEL_VERSION);\n}\n\nexport const DEFAULT_TIMEOUT_MS = 120_000;\nexport const DEFAULT_RETRIES = 2;\n","import { readFile } from 'fs/promises';\n\n/**\n * Shape of the HuggingFace tokenizer.json we care about.\n * Full spec is much larger; we only read vocab + added_tokens.\n */\ninterface TokenizerJson {\n model: {\n vocab: Record<string, number>;\n };\n added_tokens: Array<{\n id: number;\n content: string;\n }>;\n}\n\nconst DEFAULT_SPECIAL: Record<string, number> = {\n '[UNK]': 0,\n '[CLS]': 1,\n '[SEP]': 2,\n '[PAD]': 0,\n};\n\n/**\n * Minimal WordPiece tokenizer for ONNX classification inference.\n *\n * Loads a HuggingFace `tokenizer.json` and produces `input_ids` +\n * `attention_mask` as BigInt64Arrays (ONNX Runtime requires int64 tensors).\n *\n * This intentionally covers the 90% case — full HuggingFace tokenizers\n * handle BPE, normalization, pre-tokenization, etc.\n */\nexport class Tokenizer {\n private readonly vocab: Map<string, number>;\n private readonly unkId: number;\n private readonly clsId: number;\n private readonly sepId: number;\n private readonly padId: number;\n\n private constructor(vocab: Map<string, number>, specialTokens: Record<string, number>) {\n this.vocab = vocab;\n this.unkId = specialTokens['[UNK]'] ?? DEFAULT_SPECIAL['[UNK]'];\n this.clsId = specialTokens['[CLS]'] ?? DEFAULT_SPECIAL['[CLS]'];\n this.sepId = specialTokens['[SEP]'] ?? DEFAULT_SPECIAL['[SEP]'];\n this.padId = specialTokens['[PAD]'] ?? DEFAULT_SPECIAL['[PAD]'];\n }\n\n /**\n * Load a tokenizer from a HuggingFace `tokenizer.json` file.\n */\n static async fromFile(path: string): Promise<Tokenizer> {\n const raw = await readFile(path, 'utf-8');\n const json: TokenizerJson = JSON.parse(raw);\n\n const vocab = new Map<string, number>(Object.entries(json.model.vocab));\n\n // Merge added_tokens into vocab so special tokens are resolvable\n const specialTokens: Record<string, number> = { ...DEFAULT_SPECIAL };\n for (const token of json.added_tokens) {\n vocab.set(token.content, token.id);\n if (token.content in DEFAULT_SPECIAL) {\n specialTokens[token.content] = token.id;\n }\n }\n\n return new Tokenizer(vocab, specialTokens);\n }\n\n /**\n * Encode text into `input_ids` and `attention_mask` BigInt64Arrays.\n *\n * Tokenization:\n * 1. Lowercase and split on whitespace\n * 2. WordPiece subword splitting for OOV words\n * 3. Wrap with [CLS] ... [SEP]\n * 4. Pad or truncate to `maxLength`\n */\n encode(\n text: string,\n maxLength: number = 512,\n ): { inputIds: BigInt64Array; attentionMask: BigInt64Array } {\n const tokens: number[] = [this.clsId];\n\n const words = text.toLowerCase().split(/\\s+/).filter(Boolean);\n\n for (const word of words) {\n const wordTokens = this.wordPieceTokenize(word);\n tokens.push(...wordTokens);\n }\n\n tokens.push(this.sepId);\n\n // Truncate content tokens if over maxLength (keep CLS at start, SEP at end)\n if (tokens.length > maxLength) {\n tokens.length = maxLength;\n tokens[maxLength - 1] = this.sepId;\n }\n\n const inputIds = new BigInt64Array(maxLength);\n const attentionMask = new BigInt64Array(maxLength);\n\n for (let i = 0; i < tokens.length; i++) {\n inputIds[i] = BigInt(tokens[i]);\n attentionMask[i] = 1n;\n }\n\n // Remaining positions stay 0n (pad token = 0, mask = 0)\n for (let i = tokens.length; i < maxLength; i++) {\n inputIds[i] = BigInt(this.padId);\n // attentionMask[i] is already 0n\n }\n\n return { inputIds, attentionMask };\n }\n\n /**\n * WordPiece tokenization for a single word.\n * Tries to greedily match the longest prefix in vocab, then continues\n * with `##` prefixed subwords. Falls back to [UNK] if no match at all.\n */\n private wordPieceTokenize(word: string): number[] {\n // Fast path: whole word exists in vocab\n if (this.vocab.has(word)) {\n return [this.vocab.get(word)!];\n }\n\n const tokens: number[] = [];\n let start = 0;\n\n while (start < word.length) {\n let end = word.length;\n let matched = false;\n\n while (start < end) {\n const substr = start === 0 ? word.slice(0, end) : `##${word.slice(start, end)}`;\n\n if (this.vocab.has(substr)) {\n tokens.push(this.vocab.get(substr)!);\n matched = true;\n break;\n }\n\n end--;\n }\n\n if (!matched) {\n // Entire word is unresolvable — return single [UNK]\n return [this.unkId];\n }\n\n start = end;\n }\n\n return tokens;\n }\n}\n","import { LABELS } from './constants';\nimport { Tokenizer } from './tokenizer';\nimport type { ModelArtifacts } from './model-manager';\n\n// Inline types matching @stylusnexus/agentarmor's Detector interface\n// These will be compatible at runtime via structural typing\ninterface DetectorOptions {\n strictness?: 'permissive' | 'balanced' | 'strict';\n}\n\ninterface DetectorResult {\n threats: Threat[];\n}\n\ninterface Threat {\n category: string;\n type: string;\n severity: 'low' | 'medium' | 'high' | 'critical';\n confidence: number;\n description: string;\n evidence: string;\n location?: { offset: number; length: number };\n detectorId: string;\n source: 'pattern' | 'ml' | 'custom';\n}\n\ninterface Detector {\n id: string;\n name: string;\n category: string;\n scan(content: string, options?: DetectorOptions): DetectorResult;\n scanAsync?(content: string, options?: DetectorOptions): Promise<DetectorResult>;\n sanitize(content: string, threats: Threat[]): string;\n}\n\n// ONNX Runtime types\ninterface OrtSession {\n run(feeds: Record<string, any>): Promise<Record<string, any>>;\n}\n\ninterface OrtModule {\n InferenceSession: { create(path: string): Promise<OrtSession> };\n Tensor: new (type: string, data: any, dims: number[]) => any;\n}\n\nconst THRESHOLDS: Record<string, number> = {\n strict: 0.3,\n balanced: 0.5,\n permissive: 0.7,\n};\n\nconst LABEL_TO_CATEGORY: Record<string, string> = {\n 'hidden-html': 'content-injection',\n 'metadata-injection': 'content-injection',\n 'dynamic-cloaking': 'content-injection',\n 'syntactic-masking': 'content-injection',\n 'embedded-jailbreak': 'behavioural-control',\n 'data-exfiltration': 'behavioural-control',\n 'sub-agent-spawning': 'behavioural-control',\n 'rag-knowledge-poisoning': 'cognitive-state',\n 'latent-memory-poisoning': 'cognitive-state',\n 'contextual-learning-trap': 'cognitive-state',\n 'biased-framing': 'semantic-manipulation',\n 'oversight-evasion': 'semantic-manipulation',\n 'persona-hyperstition': 'semantic-manipulation',\n 'benign': 'content-injection',\n};\n\nexport class MLDetector implements Detector {\n readonly id = 'ml-classifier';\n readonly name = 'ML Classifier (DeBERTa-v3-small)';\n readonly category = 'content-injection';\n\n private session: OrtSession;\n private tokenizer: Tokenizer;\n private ort: OrtModule;\n\n private constructor(session: OrtSession, tokenizer: Tokenizer, ort: OrtModule) {\n this.session = session;\n this.tokenizer = tokenizer;\n this.ort = ort;\n }\n\n static async create(artifacts: ModelArtifacts): Promise<MLDetector> {\n const ort = await import('onnxruntime-node') as unknown as OrtModule;\n const session = await ort.InferenceSession.create(artifacts.modelPath);\n const tokenizer = await Tokenizer.fromFile(artifacts.tokenizerPath);\n return new MLDetector(session, tokenizer, ort);\n }\n\n // Sync scan returns empty — ML inference is async only\n scan(_content: string, _options?: DetectorOptions): DetectorResult {\n return { threats: [] };\n }\n\n // Async scan runs ONNX inference\n async scanAsync(content: string, options?: DetectorOptions): Promise<DetectorResult> {\n const strictness = options?.strictness ?? 'balanced';\n const threshold = THRESHOLDS[strictness] ?? THRESHOLDS.balanced;\n\n const { inputIds, attentionMask } = this.tokenizer.encode(content, 512);\n\n const feeds: Record<string, any> = {\n input_ids: new this.ort.Tensor('int64', inputIds, [1, 512]),\n attention_mask: new this.ort.Tensor('int64', attentionMask, [1, 512]),\n };\n\n const results = await this.session.run(feeds);\n const logits = results.logits?.data as Float32Array;\n if (!logits) return { threats: [] };\n\n const threats: Threat[] = [];\n for (let i = 0; i < LABELS.length; i++) {\n const label = LABELS[i];\n if (label === 'benign') continue;\n\n const prob = 1 / (1 + Math.exp(-logits[i]));\n if (prob >= threshold) {\n threats.push({\n category: LABEL_TO_CATEGORY[label] ?? 'content-injection',\n type: label,\n severity: prob >= 0.9 ? 'critical' : prob >= 0.7 ? 'high' : prob >= 0.5 ? 'medium' : 'low',\n confidence: prob,\n description: `ML classifier detected ${label} (confidence: ${(prob * 100).toFixed(1)}%)`,\n evidence: content.slice(0, 200),\n detectorId: 'ml-classifier',\n source: 'ml',\n });\n }\n }\n\n return { threats };\n }\n\n // ML detector doesn't modify content — pattern detectors handle sanitization\n sanitize(content: string, _threats: Threat[]): string {\n return content;\n }\n}\n","import { createHash } from 'crypto';\nimport { createReadStream, createWriteStream } from 'fs';\nimport { access, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';\nimport { get as httpsGet } from 'https';\nimport { join } from 'path';\nimport { pipeline } from 'stream/promises';\n\nimport {\n DEFAULT_RETRIES,\n DEFAULT_TIMEOUT_MS,\n HF_REPO_ID,\n MODEL_CHECKSUM,\n MODEL_FILENAME,\n OPTIONAL_MODEL_FILES,\n REQUIRED_MODEL_FILES,\n getDefaultCacheDir,\n} from './constants';\nimport { AgentArmorModelError } from './errors';\n\nexport interface ModelArtifacts {\n modelPath: string;\n tokenizerPath: string;\n labelMapPath: string;\n modelDir: string;\n}\n\ninterface MLConfigLike {\n modelDir?: string;\n enabled?: boolean;\n modelUrl?: string;\n download?: {\n timeoutMs?: number;\n retries?: number;\n onProgress?: (bytesReceived: number, totalBytes: number) => void;\n };\n}\n\nfunction artifactsFrom(dir: string): ModelArtifacts {\n return {\n modelPath: join(dir, MODEL_FILENAME),\n tokenizerPath: join(dir, 'tokenizer.json'),\n labelMapPath: join(dir, 'label_map.json'),\n modelDir: dir,\n };\n}\n\n/**\n * Validate that all required model files exist in a directory.\n * Throws AgentArmorModelError('MODEL_NOT_FOUND') with a helpful message if any are missing.\n */\nexport async function validateModelDir(dir: string): Promise<void> {\n const missing: string[] = [];\n for (const file of REQUIRED_MODEL_FILES) {\n try {\n await access(join(dir, file));\n } catch {\n missing.push(file);\n }\n }\n if (missing.length > 0) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Missing required model files in ${dir}: ${missing.join(', ')}. ` +\n `Required files: ${REQUIRED_MODEL_FILES.join(', ')}`,\n );\n }\n}\n\n/**\n * Resolve model artifacts — either from a user-provided modelDir or from the cache.\n * Downloads from HuggingFace if not cached.\n */\nexport async function resolveModel(config: MLConfigLike = {}): Promise<ModelArtifacts> {\n const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;\n\n if (modelDir) {\n await validateModelDir(modelDir);\n return artifactsFrom(modelDir);\n }\n\n const cacheDir = getDefaultCacheDir();\n await mkdir(cacheDir, { recursive: true });\n\n // Check if a valid cached model exists\n try {\n await validateModelDir(cacheDir);\n return artifactsFrom(cacheDir);\n } catch {\n // Not cached — download\n }\n\n await downloadWithLock(cacheDir, config);\n return artifactsFrom(cacheDir);\n}\n\n/**\n * Acquire a lock file, download all model files, verify checksum, then release the lock.\n * If another process holds the lock, wait for it.\n */\nexport async function downloadWithLock(\n cacheDir: string,\n config: MLConfigLike,\n): Promise<void> {\n const lockPath = join(cacheDir, 'model.onnx.lock');\n\n let lockFd;\n try {\n lockFd = await open(lockPath, 'wx');\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n await waitForLock(lockPath, config);\n // After lock is released, check if model is now valid\n try {\n await validateModelDir(cacheDir);\n return;\n } catch {\n // Still missing — acquire lock and download ourselves\n lockFd = await open(lockPath, 'wx');\n }\n } else {\n throw err;\n }\n }\n\n try {\n // Download required files\n for (const file of REQUIRED_MODEL_FILES) {\n await downloadFile(file, cacheDir, config, false);\n }\n\n // Download optional files (silently skip on 404)\n for (const file of OPTIONAL_MODEL_FILES) {\n await downloadFile(file, cacheDir, config, true);\n }\n\n // Verify checksum of the main model file\n const modelPath = join(cacheDir, MODEL_FILENAME);\n const checksumOk = await verifyChecksum(modelPath);\n if (!checksumOk) {\n // Clean up the bad download\n for (const file of REQUIRED_MODEL_FILES) {\n await unlink(join(cacheDir, file)).catch(() => {});\n }\n throw new AgentArmorModelError(\n 'CHECKSUM_MISMATCH',\n `Model file checksum verification failed for ${modelPath}`,\n );\n }\n } finally {\n await lockFd.close();\n await unlink(lockPath).catch(() => {});\n }\n}\n\n/**\n * Download a single file from HuggingFace (or custom modelUrl) to destDir.\n * Downloads to a .tmp file, then atomically renames on success.\n * Retries with exponential backoff. Optional files return silently on 404.\n */\nexport async function downloadFile(\n filename: string,\n destDir: string,\n config: MLConfigLike,\n optional: boolean,\n): Promise<void> {\n const retries = config.download?.retries ?? DEFAULT_RETRIES;\n const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const onProgress = config.download?.onProgress;\n\n let baseUrl: string;\n if (config.modelUrl) {\n baseUrl = config.modelUrl.replace(/\\/$/, '');\n } else {\n baseUrl = `https://huggingface.co/${HF_REPO_ID}/resolve/main`;\n }\n\n const url = `${baseUrl}/${filename}`;\n const destPath = join(destDir, filename);\n const tmpPath = `${destPath}.tmp`;\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_TIMEOUT',\n `Download of ${filename} timed out after ${timeoutMs}ms`,\n ),\n );\n }, timeoutMs);\n\n const makeRequest = (requestUrl: string, redirectCount = 0): void => {\n if (redirectCount > 5) {\n clearTimeout(timer);\n reject(new AgentArmorModelError('DOWNLOAD_FAILED', `Too many redirects for ${filename}`));\n return;\n }\n\n const protocol = requestUrl.startsWith('https') ? httpsGet : httpsGet;\n const req = protocol(requestUrl, (res) => {\n if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {\n makeRequest(res.headers.location, redirectCount + 1);\n return;\n }\n\n if (res.statusCode === 404 && optional) {\n clearTimeout(timer);\n res.resume();\n resolve();\n return;\n }\n\n if (res.statusCode !== 200) {\n clearTimeout(timer);\n res.resume();\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Failed to download ${filename}: HTTP ${res.statusCode}`,\n ),\n );\n return;\n }\n\n const totalBytes = parseInt(res.headers['content-length'] || '0', 10);\n let receivedBytes = 0;\n\n if (onProgress) {\n res.on('data', (chunk: Buffer) => {\n receivedBytes += chunk.length;\n onProgress(receivedBytes, totalBytes);\n });\n }\n\n const ws = createWriteStream(tmpPath);\n pipeline(res, ws)\n .then(() => {\n clearTimeout(timer);\n resolve();\n })\n .catch((pipeErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Failed to write ${filename}`, pipeErr),\n );\n });\n });\n\n req.on('error', (reqErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Network error downloading ${filename}`, reqErr),\n );\n });\n };\n\n makeRequest(url);\n });\n\n // Atomic rename\n await rename(tmpPath, destPath);\n return;\n } catch (err) {\n // Clean up tmp file on failure\n await unlink(tmpPath).catch(() => {});\n\n if (err instanceof AgentArmorModelError && err.code === 'DOWNLOAD_TIMEOUT') {\n throw err;\n }\n\n // If optional and this was a 404-like error, just return\n if (optional && err instanceof AgentArmorModelError && err.code === 'DOWNLOAD_FAILED') {\n return;\n }\n\n if (attempt < retries) {\n // Exponential backoff: 1s, 2s, 4s...\n const delay = 1000 * Math.pow(2, attempt);\n await new Promise((r) => setTimeout(r, delay));\n continue;\n }\n\n throw err;\n }\n }\n}\n\n/**\n * Verify SHA-256 checksum of a file against MODEL_CHECKSUM.\n * Returns true if checksum matches. Skips (returns true) if checksum is a placeholder.\n */\nexport async function verifyChecksum(filePath: string): Promise<boolean> {\n if (MODEL_CHECKSUM.startsWith('PLACEHOLDER')) {\n return true;\n }\n\n const hash = createHash('sha256');\n const stream = createReadStream(filePath);\n for await (const chunk of stream) {\n hash.update(chunk);\n }\n const digest = hash.digest('hex');\n return digest === MODEL_CHECKSUM;\n}\n\n/**\n * Wait for a lock file to be released by another process.\n * Polls every 2 seconds. Breaks stale lock after timeout.\n */\nexport async function waitForLock(lockPath: string, config: MLConfigLike): Promise<void> {\n const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const pollInterval = 2000;\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeoutMs) {\n try {\n await access(lockPath);\n } catch {\n // Lock file gone — we can proceed\n return;\n }\n\n // Check for stale lock (older than timeout)\n try {\n const lockStat = await stat(lockPath);\n const lockAge = Date.now() - lockStat.mtimeMs;\n if (lockAge > timeoutMs) {\n // Stale lock — break it\n await unlink(lockPath).catch(() => {});\n return;\n }\n } catch {\n // Lock disappeared while checking — that's fine\n return;\n }\n\n await new Promise((r) => setTimeout(r, pollInterval));\n }\n\n // Timed out waiting — break the stale lock\n await unlink(lockPath).catch(() => {});\n throw new AgentArmorModelError(\n 'LOCK_TIMEOUT',\n `Timed out waiting for lock file ${lockPath} after ${timeoutMs}ms`,\n );\n}\n","export type ModelErrorCode =\n | 'MODEL_NOT_FOUND'\n | 'CHECKSUM_MISMATCH'\n | 'DOWNLOAD_FAILED'\n | 'DOWNLOAD_TIMEOUT'\n | 'DISK_FULL'\n | 'LOCK_TIMEOUT';\n\nexport class AgentArmorModelError extends Error {\n readonly code: ModelErrorCode;\n readonly cause?: Error;\n\n constructor(code: ModelErrorCode, message: string, cause?: Error) {\n super(message);\n this.name = 'AgentArmorModelError';\n this.code = code;\n this.cause = cause;\n }\n}\n","import { MLDetector } from './ml-detector';\nimport { resolveModel } from './model-manager';\n\nexport { AgentArmorModelError } from './errors';\nexport { MLDetector } from './ml-detector';\nexport type { ModelArtifacts } from './model-manager';\n\n/**\n * Create an ML detector from config.\n * Called by AgentArmor.create() when ml config is provided.\n */\nexport async function createMLDetector(mlConfig: {\n modelDir?: string;\n enabled?: boolean;\n modelUrl?: string;\n download?: {\n timeoutMs?: number;\n retries?: number;\n onProgress?: (bytesReceived: number, totalBytes: number) => void;\n };\n}): Promise<MLDetector> {\n const artifacts = await resolveModel(mlConfig);\n return MLDetector.create(artifacts);\n}\n"],"mappings":";AAAA,SAAS,SAAS,gBAAgB;AAClC,SAAS,YAAY;AAEd,IAAM,gBAAgB;AACtB,IAAM,aAAa;AACnB,IAAM,iBAAiB;AAEvB,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AACF;AAEO,IAAM,iBAAiB;AAEvB,IAAM,SAAS;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,iBAAiB,OAAO;AAAA,EACnC,OAAO,IAAI,CAAC,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC;AACrC;AAEO,SAAS,qBAA6B;AAC3C,QAAM,cAAc,QAAQ,IAAI;AAChC,MAAI,YAAa,QAAO;AAExB,QAAM,MAAM,QAAQ,IAAI;AACxB,MAAI,IAAK,QAAO,KAAK,KAAK,cAAc,aAAa;AAErD,MAAI,SAAS,MAAM,UAAU;AAC3B,WAAO,KAAK,QAAQ,GAAG,WAAW,UAAU,cAAc,aAAa;AAAA,EACzE;AAEA,SAAO,KAAK,QAAQ,GAAG,UAAU,cAAc,aAAa;AAC9D;AAEO,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB;;;ACxD/B,SAAS,gBAAgB;AAgBzB,IAAM,kBAA0C;AAAA,EAC9C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AACX;AAWO,IAAM,YAAN,MAAM,WAAU;AAAA,EACJ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,OAA4B,eAAuC;AACrF,SAAK,QAAQ;AACb,SAAK,QAAQ,cAAc,OAAO,KAAK,gBAA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tD;AAGA,QAAM,OAAO,QAAQ,EAAE,MAAM,MAAM;AAAA,EAAC,CAAC;AACrC,QAAM,IAAI;AAAA,IACR;AAAA,IACA,mCAAmC,QAAQ,UAAU,SAAS;AAAA,EAChE;AACF;;;AE/UA,eAAsB,iBAAiB,UASf;AACtB,QAAM,YAAY,MAAM,aAAa,QAAQ;AAC7C,SAAO,WAAW,OAAO,SAAS;AACpC;","names":["join","join"]}
|
|
1
|
+
{"version":3,"sources":["../src/constants.ts","../src/tokenizer.ts","../src/errors.ts","../src/ml-detector.ts","../src/model-manager.ts","../src/index.ts"],"sourcesContent":["import { homedir, platform } from 'os';\nimport { join } from 'path';\n\nexport const MODEL_VERSION = 'v1';\nexport const HF_REPO_ID = 'stylusnexus/agent-armor-classifier';\nexport const MODEL_FILENAME = 'model_quantized.onnx';\n\nexport const REQUIRED_MODEL_FILES = [\n 'model_quantized.onnx',\n 'tokenizer.json',\n 'label_map.json',\n] as const;\n\nexport const OPTIONAL_MODEL_FILES = [\n 'tokenizer_config.json',\n 'special_tokens_map.json',\n] as const;\n\nexport const MODEL_CHECKSUM = '5d4c8551c958f398181c60239aebedbaa4ed5b641d1645904d2de9c2d02bd41f';\n\nexport const LABELS = [\n 'hidden-html',\n 'metadata-injection',\n 'dynamic-cloaking',\n 'syntactic-masking',\n 'embedded-jailbreak',\n 'data-exfiltration',\n 'sub-agent-spawning',\n 'rag-knowledge-poisoning',\n 'latent-memory-poisoning',\n 'contextual-learning-trap',\n 'biased-framing',\n 'oversight-evasion',\n 'persona-hyperstition',\n 'benign',\n] as const;\n\nexport const LABEL_TO_INDEX = Object.fromEntries(\n LABELS.map((label, i) => [label, i])\n) as Record<(typeof LABELS)[number], number>;\n\nexport function getDefaultCacheDir(): string {\n const envOverride = process.env.AGENTARMOR_CACHE_DIR;\n if (envOverride) return envOverride;\n\n const xdg = process.env.XDG_CACHE_HOME;\n if (xdg) return join(xdg, 'agentarmor', MODEL_VERSION);\n\n if (platform() === 'darwin') {\n return join(homedir(), 'Library', 'Caches', 'agentarmor', MODEL_VERSION);\n }\n\n return join(homedir(), '.cache', 'agentarmor', MODEL_VERSION);\n}\n\nexport const DEFAULT_TIMEOUT_MS = 120_000;\nexport const DEFAULT_RETRIES = 2;\n","import { readFile } from 'fs/promises';\nimport { AgentArmorModelError } from './errors';\n\n/**\n * Shape of the HuggingFace tokenizer.json we care about.\n * Full spec is much larger; we only read vocab + added_tokens.\n *\n * Both fields are optional here on purpose: this describes a file we did not\n * write and cannot assume is well-formed (users may point `modelDir` at their\n * own directory). `fromFile` validates rather than trusting the annotation.\n */\ninterface TokenizerJson {\n model?: {\n vocab?: Record<string, number>;\n };\n added_tokens?: Array<{\n id: number;\n content: string;\n }>;\n}\n\nconst DEFAULT_SPECIAL: Record<string, number> = {\n '[UNK]': 0,\n '[CLS]': 1,\n '[SEP]': 2,\n '[PAD]': 0,\n};\n\n/**\n * Minimal WordPiece tokenizer for ONNX classification inference.\n *\n * Loads a HuggingFace `tokenizer.json` and produces `input_ids` +\n * `attention_mask` as BigInt64Arrays (ONNX Runtime requires int64 tensors).\n *\n * This intentionally covers the 90% case — full HuggingFace tokenizers\n * handle BPE, normalization, pre-tokenization, etc.\n */\nexport class Tokenizer {\n private readonly vocab: Map<string, number>;\n private readonly unkId: number;\n private readonly clsId: number;\n private readonly sepId: number;\n private readonly padId: number;\n\n private constructor(vocab: Map<string, number>, specialTokens: Record<string, number>) {\n this.vocab = vocab;\n this.unkId = specialTokens['[UNK]'] ?? DEFAULT_SPECIAL['[UNK]'];\n this.clsId = specialTokens['[CLS]'] ?? DEFAULT_SPECIAL['[CLS]'];\n this.sepId = specialTokens['[SEP]'] ?? DEFAULT_SPECIAL['[SEP]'];\n this.padId = specialTokens['[PAD]'] ?? DEFAULT_SPECIAL['[PAD]'];\n }\n\n /**\n * Load a tokenizer from a HuggingFace `tokenizer.json` file.\n */\n static async fromFile(path: string): Promise<Tokenizer> {\n const raw = await readFile(path, 'utf-8');\n\n let json: TokenizerJson;\n try {\n json = JSON.parse(raw) as TokenizerJson;\n } catch (err) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} is not valid JSON. The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`,\n err instanceof Error ? err : undefined\n );\n }\n\n // A truncated or hand-assembled tokenizer.json used to fail here with a bare\n // TypeError from deep inside this function, escaping the typed-error contract\n // every other load path in this package honours. MODEL_NOT_FOUND is the right\n // code even though the file exists: the correct recovery is the same one — go\n // get the artifacts again.\n if (!json.model?.vocab) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} is missing \"model.vocab\". The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`\n );\n }\n\n const vocab = new Map<string, number>(Object.entries(json.model.vocab));\n\n // `added_tokens` absent is tolerated rather than fatal — the special tokens\n // it usually supplies fall back to DEFAULT_SPECIAL, so the tokenizer is still\n // usable. Only a missing vocab makes it unusable.\n const specialTokens: Record<string, number> = { ...DEFAULT_SPECIAL };\n for (const token of json.added_tokens ?? []) {\n vocab.set(token.content, token.id);\n if (token.content in DEFAULT_SPECIAL) {\n specialTokens[token.content] = token.id;\n }\n }\n\n return new Tokenizer(vocab, specialTokens);\n }\n\n /**\n * Encode text into `input_ids` and `attention_mask` BigInt64Arrays.\n *\n * Tokenization:\n * 1. Lowercase and split on whitespace\n * 2. WordPiece subword splitting for OOV words\n * 3. Wrap with [CLS] ... [SEP]\n * 4. Pad or truncate to `maxLength`\n */\n encode(\n text: string,\n maxLength: number = 512,\n ): { inputIds: BigInt64Array; attentionMask: BigInt64Array } {\n const tokens: number[] = [this.clsId];\n\n const words = text.toLowerCase().split(/\\s+/).filter(Boolean);\n\n for (const word of words) {\n const wordTokens = this.wordPieceTokenize(word);\n tokens.push(...wordTokens);\n }\n\n tokens.push(this.sepId);\n\n // Truncate content tokens if over maxLength (keep CLS at start, SEP at end)\n if (tokens.length > maxLength) {\n tokens.length = maxLength;\n tokens[maxLength - 1] = this.sepId;\n }\n\n const inputIds = new BigInt64Array(maxLength);\n const attentionMask = new BigInt64Array(maxLength);\n\n for (let i = 0; i < tokens.length; i++) {\n inputIds[i] = BigInt(tokens[i]);\n attentionMask[i] = 1n;\n }\n\n // Remaining positions stay 0n (pad token = 0, mask = 0)\n for (let i = tokens.length; i < maxLength; i++) {\n inputIds[i] = BigInt(this.padId);\n // attentionMask[i] is already 0n\n }\n\n return { inputIds, attentionMask };\n }\n\n /**\n * WordPiece tokenization for a single word.\n * Tries to greedily match the longest prefix in vocab, then continues\n * with `##` prefixed subwords. Falls back to [UNK] if no match at all.\n */\n private wordPieceTokenize(word: string): number[] {\n // Fast path: whole word exists in vocab\n if (this.vocab.has(word)) {\n return [this.vocab.get(word)!];\n }\n\n const tokens: number[] = [];\n let start = 0;\n\n while (start < word.length) {\n let end = word.length;\n let matched = false;\n\n while (start < end) {\n const substr = start === 0 ? word.slice(0, end) : `##${word.slice(start, end)}`;\n\n if (this.vocab.has(substr)) {\n tokens.push(this.vocab.get(substr)!);\n matched = true;\n break;\n }\n\n end--;\n }\n\n if (!matched) {\n // Entire word is unresolvable — return single [UNK]\n return [this.unkId];\n }\n\n start = end;\n }\n\n return tokens;\n }\n}\n","/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */\nexport type ModelErrorCode =\n | 'MODEL_NOT_FOUND'\n | 'CHECKSUM_MISMATCH'\n | 'DOWNLOAD_FAILED'\n | 'DOWNLOAD_TIMEOUT'\n | 'DISK_FULL'\n | 'LOCK_TIMEOUT';\n\n/** Thrown when the ML model can't be resolved (missing, corrupt, or unreachable). */\nexport class AgentArmorModelError extends Error {\n /** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */\n readonly code: ModelErrorCode;\n /** The underlying error, when this wraps one (e.g. a failed fetch). */\n readonly cause?: Error;\n\n constructor(code: ModelErrorCode, message: string, cause?: Error) {\n super(message);\n this.name = 'AgentArmorModelError';\n this.code = code;\n this.cause = cause;\n }\n}\n","import { LABELS, MODEL_VERSION } from './constants';\nimport { Tokenizer } from './tokenizer';\nimport type { ModelArtifacts } from './model-manager';\n\n// Inline types matching @stylusnexus/agentarmor's Detector interface\n// These will be compatible at runtime via structural typing\ninterface DetectorOptions {\n strictness?: 'permissive' | 'balanced' | 'strict';\n}\n\ninterface DetectorResult {\n threats: Threat[];\n}\n\ninterface Threat {\n category: string;\n type: string;\n severity: 'low' | 'medium' | 'high' | 'critical';\n confidence: number;\n description: string;\n evidence: string;\n location?: { offset: number; length: number };\n detectorId: string;\n source: 'pattern' | 'ml' | 'custom';\n}\n\ninterface Detector {\n id: string;\n name: string;\n category: string;\n scan(content: string, options?: DetectorOptions): DetectorResult;\n scanAsync?(content: string, options?: DetectorOptions): Promise<DetectorResult>;\n sanitize(content: string, threats: Threat[]): string;\n}\n\n// ONNX Runtime types\ninterface OrtSession {\n run(feeds: Record<string, any>): Promise<Record<string, any>>;\n}\n\ninterface OrtModule {\n InferenceSession: { create(path: string): Promise<OrtSession> };\n Tensor: new (type: string, data: any, dims: number[]) => any;\n}\n\nconst THRESHOLDS: Record<string, number> = {\n strict: 0.3,\n balanced: 0.5,\n permissive: 0.7,\n};\n\nconst LABEL_TO_CATEGORY: Record<string, string> = {\n 'hidden-html': 'content-injection',\n 'metadata-injection': 'content-injection',\n 'dynamic-cloaking': 'content-injection',\n 'syntactic-masking': 'content-injection',\n 'embedded-jailbreak': 'behavioural-control',\n 'data-exfiltration': 'behavioural-control',\n 'sub-agent-spawning': 'behavioural-control',\n 'rag-knowledge-poisoning': 'cognitive-state',\n 'latent-memory-poisoning': 'cognitive-state',\n 'contextual-learning-trap': 'cognitive-state',\n 'biased-framing': 'semantic-manipulation',\n 'oversight-evasion': 'semantic-manipulation',\n 'persona-hyperstition': 'semantic-manipulation',\n 'benign': 'content-injection',\n};\n\n/**\n * ONNX-based detector running the DeBERTa-v3-small multi-label classifier.\n * Implements Agent Armor's `Detector` interface via structural typing —\n * {@link MLDetector.create} loads the model; {@link MLDetector.scanAsync}\n * runs inference. {@link MLDetector.scan} (sync) always returns no threats,\n * since ONNX inference is async-only.\n */\nexport class MLDetector implements Detector {\n /** Unique identifier for this detector. */\n readonly id = 'ml-classifier';\n /** Human-readable name. */\n readonly name = 'ML Classifier (DeBERTa-v3-small)';\n /** Trap category this detector's labels currently map into. */\n readonly category = 'content-injection';\n /** Model version — surfaced on AuditRecord.mlModelVersion when this detector ran (#75). */\n readonly version = MODEL_VERSION;\n\n private session: OrtSession;\n private tokenizer: Tokenizer;\n private ort: OrtModule;\n\n private constructor(session: OrtSession, tokenizer: Tokenizer, ort: OrtModule) {\n this.session = session;\n this.tokenizer = tokenizer;\n this.ort = ort;\n }\n\n /** Loads the ONNX session and tokenizer from resolved {@link ModelArtifacts}. */\n static async create(artifacts: ModelArtifacts): Promise<MLDetector> {\n const ort = await import('onnxruntime-node') as unknown as OrtModule;\n const session = await ort.InferenceSession.create(artifacts.modelPath);\n const tokenizer = await Tokenizer.fromFile(artifacts.tokenizerPath);\n return new MLDetector(session, tokenizer, ort);\n }\n\n /** Always returns no threats — ML inference is async-only, use {@link scanAsync}. */\n scan(_content: string, _options?: DetectorOptions): DetectorResult {\n return { threats: [] };\n }\n\n /** Tokenizes `content`, runs ONNX inference, and returns threats above the strictness threshold. */\n async scanAsync(content: string, options?: DetectorOptions): Promise<DetectorResult> {\n const strictness = options?.strictness ?? 'balanced';\n const threshold = THRESHOLDS[strictness] ?? THRESHOLDS.balanced;\n\n const { inputIds, attentionMask } = this.tokenizer.encode(content, 512);\n\n const feeds: Record<string, any> = {\n input_ids: new this.ort.Tensor('int64', inputIds, [1, 512]),\n attention_mask: new this.ort.Tensor('int64', attentionMask, [1, 512]),\n };\n\n const results = await this.session.run(feeds);\n const logits = results.logits?.data as Float32Array;\n if (!logits) return { threats: [] };\n\n const threats: Threat[] = [];\n for (let i = 0; i < LABELS.length; i++) {\n const label = LABELS[i];\n if (label === 'benign') continue;\n\n const prob = 1 / (1 + Math.exp(-logits[i]));\n if (prob >= threshold) {\n threats.push({\n category: LABEL_TO_CATEGORY[label] ?? 'content-injection',\n type: label,\n severity: prob >= 0.9 ? 'critical' : prob >= 0.7 ? 'high' : prob >= 0.5 ? 'medium' : 'low',\n confidence: prob,\n description: `ML classifier detected ${label} (confidence: ${(prob * 100).toFixed(1)}%)`,\n evidence: content.slice(0, 200),\n detectorId: 'ml-classifier',\n source: 'ml',\n });\n }\n }\n\n return { threats };\n }\n\n /** Passthrough — the ML detector doesn't modify content; pattern detectors sanitize. */\n sanitize(content: string, _threats: Threat[]): string {\n return content;\n }\n}\n","import { createHash } from 'crypto';\nimport { createReadStream, createWriteStream } from 'fs';\nimport { access, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';\nimport { get as httpsGet } from 'https';\nimport { join } from 'path';\nimport { pipeline } from 'stream/promises';\n\nimport {\n DEFAULT_RETRIES,\n DEFAULT_TIMEOUT_MS,\n HF_REPO_ID,\n MODEL_CHECKSUM,\n MODEL_FILENAME,\n OPTIONAL_MODEL_FILES,\n REQUIRED_MODEL_FILES,\n getDefaultCacheDir,\n} from './constants';\nimport { AgentArmorModelError } from './errors';\n\n/** Resolved on-disk paths to the ONNX model and its supporting files. */\nexport interface ModelArtifacts {\n /** Path to `model_quantized.onnx`. */\n modelPath: string;\n /** Path to `tokenizer.json`. */\n tokenizerPath: string;\n /** Path to `label_map.json`. */\n labelMapPath: string;\n /** Directory containing all resolved model files. */\n modelDir: string;\n}\n\ninterface MLConfigLike {\n modelDir?: string;\n enabled?: boolean;\n modelUrl?: string;\n download?: {\n timeoutMs?: number;\n retries?: number;\n onProgress?: (bytesReceived: number, totalBytes: number) => void;\n };\n}\n\nfunction artifactsFrom(dir: string): ModelArtifacts {\n return {\n modelPath: join(dir, MODEL_FILENAME),\n tokenizerPath: join(dir, 'tokenizer.json'),\n labelMapPath: join(dir, 'label_map.json'),\n modelDir: dir,\n };\n}\n\n/**\n * Validate that all required model files exist in a directory.\n * Throws AgentArmorModelError('MODEL_NOT_FOUND') with a helpful message if any are missing.\n */\nexport async function validateModelDir(dir: string): Promise<void> {\n const missing: string[] = [];\n for (const file of REQUIRED_MODEL_FILES) {\n try {\n await access(join(dir, file));\n } catch {\n missing.push(file);\n }\n }\n if (missing.length > 0) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Missing required model files in ${dir}: ${missing.join(', ')}. ` +\n `Required files: ${REQUIRED_MODEL_FILES.join(', ')}`,\n );\n }\n}\n\n/**\n * Resolve model artifacts — either from a user-provided modelDir or from the cache.\n * Downloads from HuggingFace if not cached.\n */\nexport async function resolveModel(config: MLConfigLike = {}): Promise<ModelArtifacts> {\n const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;\n\n if (modelDir) {\n await validateModelDir(modelDir);\n return artifactsFrom(modelDir);\n }\n\n const cacheDir = getDefaultCacheDir();\n await mkdir(cacheDir, { recursive: true });\n\n // Check if a valid cached model exists\n try {\n await validateModelDir(cacheDir);\n return artifactsFrom(cacheDir);\n } catch {\n // Not cached — download\n }\n\n await downloadWithLock(cacheDir, config);\n return artifactsFrom(cacheDir);\n}\n\n/**\n * Acquire a lock file, download all model files, verify checksum, then release the lock.\n * If another process holds the lock, wait for it.\n */\nexport async function downloadWithLock(\n cacheDir: string,\n config: MLConfigLike,\n): Promise<void> {\n const lockPath = join(cacheDir, 'model.onnx.lock');\n\n let lockFd;\n try {\n lockFd = await open(lockPath, 'wx');\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === 'EEXIST') {\n await waitForLock(lockPath, config);\n // After lock is released, check if model is now valid\n try {\n await validateModelDir(cacheDir);\n return;\n } catch {\n // Still missing — acquire lock and download ourselves\n lockFd = await open(lockPath, 'wx');\n }\n } else {\n throw err;\n }\n }\n\n try {\n // Download required files\n for (const file of REQUIRED_MODEL_FILES) {\n await downloadFile(file, cacheDir, config, false);\n }\n\n // Download optional files (silently skip on 404)\n for (const file of OPTIONAL_MODEL_FILES) {\n await downloadFile(file, cacheDir, config, true);\n }\n\n // Verify checksum of the main model file\n const modelPath = join(cacheDir, MODEL_FILENAME);\n const checksumOk = await verifyChecksum(modelPath);\n if (!checksumOk) {\n // Clean up the bad download\n for (const file of REQUIRED_MODEL_FILES) {\n await unlink(join(cacheDir, file)).catch(() => {});\n }\n throw new AgentArmorModelError(\n 'CHECKSUM_MISMATCH',\n `Model file checksum verification failed for ${modelPath}`,\n );\n }\n } finally {\n await lockFd.close();\n await unlink(lockPath).catch(() => {});\n }\n}\n\n/**\n * Download a single file from HuggingFace (or custom modelUrl) to destDir.\n * Downloads to a .tmp file, then atomically renames on success.\n * Retries with exponential backoff. Optional files return silently on 404.\n */\nexport async function downloadFile(\n filename: string,\n destDir: string,\n config: MLConfigLike,\n optional: boolean,\n): Promise<void> {\n const retries = config.download?.retries ?? DEFAULT_RETRIES;\n const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const onProgress = config.download?.onProgress;\n\n let baseUrl: string;\n if (config.modelUrl) {\n baseUrl = config.modelUrl.replace(/\\/$/, '');\n } else {\n baseUrl = `https://huggingface.co/${HF_REPO_ID}/resolve/main`;\n }\n\n const url = `${baseUrl}/${filename}`;\n const destPath = join(destDir, filename);\n const tmpPath = `${destPath}.tmp`;\n\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_TIMEOUT',\n `Download of ${filename} timed out after ${timeoutMs}ms`,\n ),\n );\n }, timeoutMs);\n\n const makeRequest = (requestUrl: string, redirectCount = 0): void => {\n if (redirectCount > 5) {\n clearTimeout(timer);\n reject(new AgentArmorModelError('DOWNLOAD_FAILED', `Too many redirects for ${filename}`));\n return;\n }\n\n const protocol = requestUrl.startsWith('https') ? httpsGet : httpsGet;\n const req = protocol(requestUrl, (res) => {\n if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {\n makeRequest(res.headers.location, redirectCount + 1);\n return;\n }\n\n if (res.statusCode === 404 && optional) {\n clearTimeout(timer);\n res.resume();\n resolve();\n return;\n }\n\n if (res.statusCode !== 200) {\n clearTimeout(timer);\n res.resume();\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Failed to download ${filename}: HTTP ${res.statusCode}`,\n ),\n );\n return;\n }\n\n const totalBytes = parseInt(res.headers['content-length'] || '0', 10);\n let receivedBytes = 0;\n\n if (onProgress) {\n res.on('data', (chunk: Buffer) => {\n receivedBytes += chunk.length;\n onProgress(receivedBytes, totalBytes);\n });\n }\n\n const ws = createWriteStream(tmpPath);\n pipeline(res, ws)\n .then(() => {\n clearTimeout(timer);\n resolve();\n })\n .catch((pipeErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Failed to write ${filename}`, pipeErr),\n );\n });\n });\n\n req.on('error', (reqErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Network error downloading ${filename}`, reqErr),\n );\n });\n };\n\n makeRequest(url);\n });\n\n // Atomic rename\n await rename(tmpPath, destPath);\n return;\n } catch (err) {\n // Clean up tmp file on failure\n await unlink(tmpPath).catch(() => {});\n\n if (err instanceof AgentArmorModelError && err.code === 'DOWNLOAD_TIMEOUT') {\n throw err;\n }\n\n // If optional and this was a 404-like error, just return\n if (optional && err instanceof AgentArmorModelError && err.code === 'DOWNLOAD_FAILED') {\n return;\n }\n\n if (attempt < retries) {\n // Exponential backoff: 1s, 2s, 4s...\n const delay = 1000 * Math.pow(2, attempt);\n await new Promise((r) => setTimeout(r, delay));\n continue;\n }\n\n throw err;\n }\n }\n}\n\n/**\n * Verify the SHA-256 checksum of a file against an expected value (defaults to\n * the shipped MODEL_CHECKSUM). Returns true if the digest matches. Skips\n * verification (returns true) when the expected checksum is a placeholder.\n *\n * `expected` is parameterized so the behavior can be exercised independently of\n * whichever real checksum the package currently ships.\n */\nexport async function verifyChecksum(\n filePath: string,\n expected: string = MODEL_CHECKSUM,\n): Promise<boolean> {\n if (expected.startsWith('PLACEHOLDER')) {\n return true;\n }\n\n const hash = createHash('sha256');\n const stream = createReadStream(filePath);\n for await (const chunk of stream) {\n hash.update(chunk);\n }\n const digest = hash.digest('hex');\n return digest === expected;\n}\n\n/**\n * Wait for a lock file to be released by another process.\n * Polls every 2 seconds. Breaks stale lock after timeout.\n */\nexport async function waitForLock(lockPath: string, config: MLConfigLike): Promise<void> {\n const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const pollInterval = 2000;\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeoutMs) {\n try {\n await access(lockPath);\n } catch {\n // Lock file gone — we can proceed\n return;\n }\n\n // Check for stale lock (older than timeout)\n try {\n const lockStat = await stat(lockPath);\n const lockAge = Date.now() - lockStat.mtimeMs;\n if (lockAge > timeoutMs) {\n // Stale lock — break it\n await unlink(lockPath).catch(() => {});\n return;\n }\n } catch {\n // Lock disappeared while checking — that's fine\n return;\n }\n\n await new Promise((r) => setTimeout(r, pollInterval));\n }\n\n // Timed out waiting — break the stale lock\n await unlink(lockPath).catch(() => {});\n throw new AgentArmorModelError(\n 'LOCK_TIMEOUT',\n `Timed out waiting for lock file ${lockPath} after ${timeoutMs}ms`,\n );\n}\n","import { MLDetector } from './ml-detector';\nimport { resolveModel } from './model-manager';\n\nexport { AgentArmorModelError } from './errors';\nexport { MLDetector } from './ml-detector';\nexport type { ModelArtifacts } from './model-manager';\n\n/**\n * Create an ML detector from config.\n * Called by AgentArmor.create() when ml config is provided.\n */\nexport async function createMLDetector(mlConfig: {\n modelDir?: string;\n enabled?: boolean;\n modelUrl?: string;\n download?: {\n timeoutMs?: number;\n retries?: number;\n onProgress?: (bytesReceived: number, totalBytes: number) => void;\n };\n}): Promise<MLDetector> {\n const artifacts = await resolveModel(mlConfig);\n return MLDetector.create(artifacts);\n}\n"],"mappings":";AAAA,SAAS,SAAS,gBAAgB;AAClC,SAAS,YAAY;AAEd,IAA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AI,IAAI,SAAS;AACtC,UAAI,UAAU,WAAW;AAEvB,cAAM,OAAO,QAAQ,EAAE,MAAM,MAAM;AAAA,QAAC,CAAC;AACrC;AAAA,MACF;AAAA,IACF,QAAQ;AAEN;AAAA,IACF;AAEA,UAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,YAAY,CAAC;AAAA,EACtD;AAGA,QAAM,OAAO,QAAQ,EAAE,MAAM,MAAM;AAAA,EAAC,CAAC;AACrC,QAAM,IAAI;AAAA,IACR;AAAA,IACA,mCAAmC,QAAQ,UAAU,SAAS;AAAA,EAChE;AACF;;;AC3VA,eAAsB,iBAAiB,UASf;AACtB,QAAM,YAAY,MAAM,aAAa,QAAQ;AAC7C,SAAO,WAAW,OAAO,SAAS;AACpC;","names":["join","join"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stylusnexus/agentarmor-ml",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "ML classifier add-on for Agent Armor. Downloads and runs a DeBERTa-v3-small ONNX model for agent trap detection.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -19,9 +19,19 @@
|
|
|
19
19
|
"build": "tsup",
|
|
20
20
|
"dev": "tsup --watch",
|
|
21
21
|
"test": "vitest run",
|
|
22
|
-
"typecheck": "tsc --noEmit"
|
|
22
|
+
"typecheck": "tsc --noEmit",
|
|
23
|
+
"docs:build": "typedoc",
|
|
24
|
+
"check:model": "tsx scripts/check-model-integrity.ts",
|
|
25
|
+
"check:model:deep": "tsx scripts/check-model-integrity.ts --deep",
|
|
26
|
+
"typecheck:scripts": "tsc -p tsconfig.scripts.json"
|
|
23
27
|
},
|
|
24
|
-
"keywords": [
|
|
28
|
+
"keywords": [
|
|
29
|
+
"ai-security",
|
|
30
|
+
"agent-safety",
|
|
31
|
+
"ml-classifier",
|
|
32
|
+
"onnx",
|
|
33
|
+
"agent-armor"
|
|
34
|
+
],
|
|
25
35
|
"author": "StylusNexus",
|
|
26
36
|
"license": "MIT",
|
|
27
37
|
"peerDependencies": {
|
|
@@ -33,15 +43,26 @@
|
|
|
33
43
|
"devDependencies": {
|
|
34
44
|
"@types/node": "^22.0.0",
|
|
35
45
|
"tsup": "^8.5.0",
|
|
46
|
+
"tsx": "^4.20.6",
|
|
47
|
+
"typedoc": "^0.28.20",
|
|
36
48
|
"typescript": "^6.0.0",
|
|
37
49
|
"vitest": "^4.1.0"
|
|
38
50
|
},
|
|
39
|
-
"files": [
|
|
51
|
+
"files": [
|
|
52
|
+
"dist",
|
|
53
|
+
"README.md",
|
|
54
|
+
"LICENSE"
|
|
55
|
+
],
|
|
40
56
|
"repository": {
|
|
41
57
|
"type": "git",
|
|
42
58
|
"url": "git+https://github.com/stylusnexus/agent-armor.git",
|
|
43
59
|
"directory": "packages/ml"
|
|
44
60
|
},
|
|
45
61
|
"homepage": "https://agentarmor.dev",
|
|
46
|
-
"engines": {
|
|
62
|
+
"engines": {
|
|
63
|
+
"node": ">=18.0.0"
|
|
64
|
+
},
|
|
65
|
+
"overrides": {
|
|
66
|
+
"esbuild": "^0.28.1"
|
|
67
|
+
}
|
|
47
68
|
}
|