@stylusnexus/agentarmor-ml 0.1.10 → 0.1.11
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 +21 -1
- package/dist/cli.js +89 -10
- package/dist/index.js +52 -9
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +53 -10
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -38,7 +38,7 @@ On first use, the model (~165MB quantized ONNX) is downloaded from HuggingFace a
|
|
|
38
38
|
|
|
39
39
|
- **macOS:** `~/Library/Caches/agentarmor/v2/`
|
|
40
40
|
- **Linux:** `~/.cache/agentarmor/v2/`
|
|
41
|
-
- **Custom:** Set `AGENTARMOR_CACHE_DIR` or pass `ml.modelDir`
|
|
41
|
+
- **Custom:** Set `AGENTARMOR_CACHE_DIR` to move the cache, or pass `ml.modelDir` (or set `AGENTARMOR_MODEL_DIR`) to use a model directory instead of the cache
|
|
42
42
|
|
|
43
43
|
Subsequent runs load from cache with no network calls.
|
|
44
44
|
|
|
@@ -82,6 +82,22 @@ const armor = await AgentArmor.create({
|
|
|
82
82
|
|
|
83
83
|
Every retrain release must update the pinned checksums in `packages/ml/src/constants.ts`; changing a custom model does not require a tokenization-code change.
|
|
84
84
|
|
|
85
|
+
### `AGENTARMOR_MODEL_DIR`
|
|
86
|
+
|
|
87
|
+
When `ml.enabled` is set and `modelDir` isn't, the package reads the model directory from `AGENTARMOR_MODEL_DIR`. Use it for an offline or pre-downloaded copy of the **pinned** model release, for example one fetched with `agentarmor-ml download --dir`.
|
|
88
|
+
|
|
89
|
+
The directory is checked like `modelDir`: against the package's pinned digests unless `modelChecksums` is passed in code. There is no environment variable for checksums. Pointing `AGENTARMOR_MODEL_DIR` at a custom or retrained model fails with `CHECKSUM_MISMATCH` unless the code also passes that model's `modelChecksums`.
|
|
90
|
+
|
|
91
|
+
### When the model check fails
|
|
92
|
+
|
|
93
|
+
Model loading fails with an `AgentArmorModelError` whose `code` says why:
|
|
94
|
+
|
|
95
|
+
- `CHECKSUM_REQUIRED`: `modelChecksums` is missing an entry, or a digest isn't 64 hex characters. This is checked before any file is read or downloaded.
|
|
96
|
+
- `CHECKSUM_MISMATCH`: a model file doesn't match its digest.
|
|
97
|
+
- `MODEL_NOT_FOUND`: a required file is missing from `modelDir` or `AGENTARMOR_MODEL_DIR`.
|
|
98
|
+
|
|
99
|
+
With the default `onUnavailable: 'warn-and-skip'`, the ML layer is skipped with a warning (through `on.warn` if set, otherwise `console.warn`), and scans run with the pattern detectors only. Set `onUnavailable: 'throw'` to fail startup instead.
|
|
100
|
+
|
|
85
101
|
## CLI
|
|
86
102
|
|
|
87
103
|
Pre-download the model or manage the cache:
|
|
@@ -98,6 +114,10 @@ agentarmor-ml cache-info
|
|
|
98
114
|
agentarmor-ml clear-cache
|
|
99
115
|
```
|
|
100
116
|
|
|
117
|
+
`clear-cache` deletes only the files this package writes. Anything else in the cache folder stays.
|
|
118
|
+
|
|
119
|
+
Keep the cache folder private. If you set `AGENTARMOR_CACHE_DIR` or `XDG_CACHE_HOME`, don't point it at a folder that other users can write to: they could replace model files after the checksum check.
|
|
120
|
+
|
|
101
121
|
## Inference Details
|
|
102
122
|
|
|
103
123
|
- Tokenizes input to 512 tokens with the Hugging Face [`tokenizers`](https://www.npmjs.com/package/tokenizers) package, reading the model's own `tokenizer.json` (SentencePiece Unigram). A retrained model needs no code change; a test fails if the ids drift from the Python training tokenizer.
|
package/dist/cli.js
CHANGED
|
@@ -78,6 +78,7 @@ var AgentArmorModelError = class extends Error {
|
|
|
78
78
|
};
|
|
79
79
|
|
|
80
80
|
// src/model-manager.ts
|
|
81
|
+
var LOCK_FILENAME = "model.onnx.lock";
|
|
81
82
|
function artifactsFrom(dir) {
|
|
82
83
|
return {
|
|
83
84
|
modelPath: (0, import_path2.join)(dir, MODEL_FILENAME),
|
|
@@ -103,7 +104,7 @@ async function validateModelDir(dir, checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
|
103
104
|
}
|
|
104
105
|
await verifyRequiredModelChecksums(dir, checksums);
|
|
105
106
|
}
|
|
106
|
-
|
|
107
|
+
function assertModelChecksums(checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
107
108
|
const invalid = REQUIRED_MODEL_FILES.filter(
|
|
108
109
|
(file) => !/^[a-f0-9]{64}$/i.test(checksums?.[file] ?? "")
|
|
109
110
|
);
|
|
@@ -113,6 +114,15 @@ async function verifyRequiredModelChecksums(dir, checksums = REQUIRED_MODEL_CHEC
|
|
|
113
114
|
`A valid SHA-256 checksum is required for each model artifact; missing or invalid: ${invalid.join(", ")}`
|
|
114
115
|
);
|
|
115
116
|
}
|
|
117
|
+
}
|
|
118
|
+
function isCacheMiss(err) {
|
|
119
|
+
if (err instanceof AgentArmorModelError) {
|
|
120
|
+
return err.code === "MODEL_NOT_FOUND" || err.code === "CHECKSUM_MISMATCH";
|
|
121
|
+
}
|
|
122
|
+
return err?.code === "ENOENT";
|
|
123
|
+
}
|
|
124
|
+
async function verifyRequiredModelChecksums(dir, checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
125
|
+
assertModelChecksums(checksums);
|
|
116
126
|
for (const file of REQUIRED_MODEL_FILES) {
|
|
117
127
|
const path = (0, import_path2.join)(dir, file);
|
|
118
128
|
if (!await verifyChecksum(path, checksums[file])) {
|
|
@@ -124,6 +134,7 @@ async function verifyRequiredModelChecksums(dir, checksums = REQUIRED_MODEL_CHEC
|
|
|
124
134
|
}
|
|
125
135
|
}
|
|
126
136
|
async function resolveModel(config = {}) {
|
|
137
|
+
assertModelChecksums(config.modelChecksums);
|
|
127
138
|
const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;
|
|
128
139
|
if (modelDir) {
|
|
129
140
|
await validateModelDir(modelDir, config.modelChecksums);
|
|
@@ -134,7 +145,8 @@ async function resolveModel(config = {}) {
|
|
|
134
145
|
try {
|
|
135
146
|
await validateModelDir(cacheDir, config.modelChecksums);
|
|
136
147
|
return artifactsFrom(cacheDir);
|
|
137
|
-
} catch {
|
|
148
|
+
} catch (err) {
|
|
149
|
+
if (!isCacheMiss(err)) throw err;
|
|
138
150
|
}
|
|
139
151
|
await downloadWithLock(cacheDir, config);
|
|
140
152
|
return artifactsFrom(cacheDir);
|
|
@@ -150,7 +162,7 @@ ${checksumIdentity}`).digest("hex");
|
|
|
150
162
|
return (0, import_path2.join)(getDefaultCacheDir(), "custom", key);
|
|
151
163
|
}
|
|
152
164
|
async function downloadWithLock(cacheDir, config) {
|
|
153
|
-
const lockPath = (0, import_path2.join)(cacheDir,
|
|
165
|
+
const lockPath = (0, import_path2.join)(cacheDir, LOCK_FILENAME);
|
|
154
166
|
let lockFd;
|
|
155
167
|
try {
|
|
156
168
|
lockFd = await (0, import_promises.open)(lockPath, "wx");
|
|
@@ -160,7 +172,8 @@ async function downloadWithLock(cacheDir, config) {
|
|
|
160
172
|
try {
|
|
161
173
|
await validateModelDir(cacheDir, config.modelChecksums);
|
|
162
174
|
return;
|
|
163
|
-
} catch {
|
|
175
|
+
} catch (validateErr) {
|
|
176
|
+
if (!isCacheMiss(validateErr)) throw validateErr;
|
|
164
177
|
lockFd = await (0, import_promises.open)(lockPath, "wx");
|
|
165
178
|
}
|
|
166
179
|
} else {
|
|
@@ -189,6 +202,42 @@ async function downloadWithLock(cacheDir, config) {
|
|
|
189
202
|
});
|
|
190
203
|
}
|
|
191
204
|
}
|
|
205
|
+
async function clearCache(cacheDir) {
|
|
206
|
+
const customDir = (0, import_path2.join)(cacheDir, "custom");
|
|
207
|
+
const isCustomDir = await (0, import_promises.lstat)(customDir).then(
|
|
208
|
+
(s) => s.isDirectory(),
|
|
209
|
+
() => false
|
|
210
|
+
);
|
|
211
|
+
if (isCustomDir) {
|
|
212
|
+
for (const entry of await (0, import_promises.readdir)(customDir, { withFileTypes: true })) {
|
|
213
|
+
if (entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)) {
|
|
214
|
+
await removeCacheFiles((0, import_path2.join)(customDir, entry.name));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
await removeIfEmpty(customDir);
|
|
218
|
+
}
|
|
219
|
+
await removeCacheFiles(cacheDir);
|
|
220
|
+
}
|
|
221
|
+
async function removeCacheFiles(dir) {
|
|
222
|
+
const files = [...REQUIRED_MODEL_FILES, ...OPTIONAL_MODEL_FILES];
|
|
223
|
+
const names = [...files, ...files.map((file) => `${file}.tmp`), LOCK_FILENAME];
|
|
224
|
+
let failure;
|
|
225
|
+
for (const name of names) {
|
|
226
|
+
await (0, import_promises.unlink)((0, import_path2.join)(dir, name)).catch(ignoreCodes("ENOENT")).catch((err) => {
|
|
227
|
+
failure ??= err;
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
if (failure) throw failure;
|
|
231
|
+
await removeIfEmpty(dir);
|
|
232
|
+
}
|
|
233
|
+
async function removeIfEmpty(dir) {
|
|
234
|
+
await (0, import_promises.rmdir)(dir).catch(ignoreCodes("ENOENT", "ENOTEMPTY", "EEXIST", "ENOTDIR"));
|
|
235
|
+
}
|
|
236
|
+
function ignoreCodes(...codes) {
|
|
237
|
+
return (err) => {
|
|
238
|
+
if (!codes.includes(err.code ?? "")) throw err;
|
|
239
|
+
};
|
|
240
|
+
}
|
|
192
241
|
async function downloadFile(filename, destDir, config, optional) {
|
|
193
242
|
const retries = config.download?.retries ?? DEFAULT_RETRIES;
|
|
194
243
|
const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
@@ -204,7 +253,10 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
204
253
|
const tmpPath = `${destPath}.tmp`;
|
|
205
254
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
206
255
|
try {
|
|
256
|
+
await (0, import_promises.unlink)(tmpPath).catch(() => {
|
|
257
|
+
});
|
|
207
258
|
await new Promise((resolve2, reject) => {
|
|
259
|
+
let activeRequest;
|
|
208
260
|
const timer = setTimeout(() => {
|
|
209
261
|
reject(
|
|
210
262
|
new AgentArmorModelError(
|
|
@@ -212,6 +264,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
212
264
|
`Download of ${filename} timed out after ${timeoutMs}ms`
|
|
213
265
|
)
|
|
214
266
|
);
|
|
267
|
+
activeRequest?.destroy();
|
|
215
268
|
}, timeoutMs);
|
|
216
269
|
const makeRequest = (requestUrl, redirectCount = 0) => {
|
|
217
270
|
if (redirectCount > 5) {
|
|
@@ -221,11 +274,25 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
221
274
|
);
|
|
222
275
|
return;
|
|
223
276
|
}
|
|
224
|
-
const
|
|
225
|
-
const req = protocol(requestUrl, (res) => {
|
|
277
|
+
const req = (0, import_https.get)(requestUrl, (res) => {
|
|
226
278
|
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
227
279
|
res.resume();
|
|
228
|
-
|
|
280
|
+
try {
|
|
281
|
+
const next = new URL(res.headers.location, requestUrl);
|
|
282
|
+
if (next.protocol !== "https:") {
|
|
283
|
+
throw new Error(`Redirect to ${next.protocol} is not allowed`);
|
|
284
|
+
}
|
|
285
|
+
makeRequest(next.toString(), redirectCount + 1);
|
|
286
|
+
} catch (redirectErr) {
|
|
287
|
+
clearTimeout(timer);
|
|
288
|
+
reject(
|
|
289
|
+
new AgentArmorModelError(
|
|
290
|
+
"DOWNLOAD_FAILED",
|
|
291
|
+
`Invalid redirect while downloading ${filename}`,
|
|
292
|
+
redirectErr
|
|
293
|
+
)
|
|
294
|
+
);
|
|
295
|
+
}
|
|
229
296
|
return;
|
|
230
297
|
}
|
|
231
298
|
if (res.statusCode === 404 && optional) {
|
|
@@ -253,7 +320,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
253
320
|
onProgress(receivedBytes, totalBytes);
|
|
254
321
|
});
|
|
255
322
|
}
|
|
256
|
-
const ws = (0, import_fs.createWriteStream)(tmpPath);
|
|
323
|
+
const ws = (0, import_fs.createWriteStream)(tmpPath, { flags: "wx" });
|
|
257
324
|
(0, import_promises2.pipeline)(res, ws).then(() => {
|
|
258
325
|
clearTimeout(timer);
|
|
259
326
|
resolve2();
|
|
@@ -268,6 +335,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
268
335
|
);
|
|
269
336
|
});
|
|
270
337
|
});
|
|
338
|
+
activeRequest = req;
|
|
271
339
|
req.on("error", (reqErr) => {
|
|
272
340
|
clearTimeout(timer);
|
|
273
341
|
reject(
|
|
@@ -279,7 +347,18 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
279
347
|
);
|
|
280
348
|
});
|
|
281
349
|
};
|
|
282
|
-
|
|
350
|
+
try {
|
|
351
|
+
makeRequest(url);
|
|
352
|
+
} catch (urlErr) {
|
|
353
|
+
clearTimeout(timer);
|
|
354
|
+
reject(
|
|
355
|
+
new AgentArmorModelError(
|
|
356
|
+
"DOWNLOAD_FAILED",
|
|
357
|
+
`Invalid download address for ${filename}`,
|
|
358
|
+
urlErr
|
|
359
|
+
)
|
|
360
|
+
);
|
|
361
|
+
}
|
|
283
362
|
});
|
|
284
363
|
await (0, import_promises.rename)(tmpPath, destPath);
|
|
285
364
|
return;
|
|
@@ -420,7 +499,7 @@ Download failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
|
420
499
|
async function cmdClearCache() {
|
|
421
500
|
const cacheDir = getDefaultCacheDir();
|
|
422
501
|
try {
|
|
423
|
-
await (
|
|
502
|
+
await clearCache(cacheDir);
|
|
424
503
|
console.log(`Cache cleared: ${cacheDir}`);
|
|
425
504
|
} catch (err) {
|
|
426
505
|
console.error(`Failed to clear cache: ${err instanceof Error ? err.message : String(err)}`);
|
package/dist/index.js
CHANGED
|
@@ -318,6 +318,7 @@ var import_promises2 = require("fs/promises");
|
|
|
318
318
|
var import_https = require("https");
|
|
319
319
|
var import_path2 = require("path");
|
|
320
320
|
var import_promises3 = require("stream/promises");
|
|
321
|
+
var LOCK_FILENAME = "model.onnx.lock";
|
|
321
322
|
function artifactsFrom(dir) {
|
|
322
323
|
return {
|
|
323
324
|
modelPath: (0, import_path2.join)(dir, MODEL_FILENAME),
|
|
@@ -343,7 +344,7 @@ async function validateModelDir(dir, checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
|
343
344
|
}
|
|
344
345
|
await verifyRequiredModelChecksums(dir, checksums);
|
|
345
346
|
}
|
|
346
|
-
|
|
347
|
+
function assertModelChecksums(checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
347
348
|
const invalid = REQUIRED_MODEL_FILES.filter(
|
|
348
349
|
(file) => !/^[a-f0-9]{64}$/i.test(checksums?.[file] ?? "")
|
|
349
350
|
);
|
|
@@ -353,6 +354,15 @@ async function verifyRequiredModelChecksums(dir, checksums = REQUIRED_MODEL_CHEC
|
|
|
353
354
|
`A valid SHA-256 checksum is required for each model artifact; missing or invalid: ${invalid.join(", ")}`
|
|
354
355
|
);
|
|
355
356
|
}
|
|
357
|
+
}
|
|
358
|
+
function isCacheMiss(err) {
|
|
359
|
+
if (err instanceof AgentArmorModelError) {
|
|
360
|
+
return err.code === "MODEL_NOT_FOUND" || err.code === "CHECKSUM_MISMATCH";
|
|
361
|
+
}
|
|
362
|
+
return err?.code === "ENOENT";
|
|
363
|
+
}
|
|
364
|
+
async function verifyRequiredModelChecksums(dir, checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
365
|
+
assertModelChecksums(checksums);
|
|
356
366
|
for (const file of REQUIRED_MODEL_FILES) {
|
|
357
367
|
const path = (0, import_path2.join)(dir, file);
|
|
358
368
|
if (!await verifyChecksum(path, checksums[file])) {
|
|
@@ -364,6 +374,7 @@ async function verifyRequiredModelChecksums(dir, checksums = REQUIRED_MODEL_CHEC
|
|
|
364
374
|
}
|
|
365
375
|
}
|
|
366
376
|
async function resolveModel(config = {}) {
|
|
377
|
+
assertModelChecksums(config.modelChecksums);
|
|
367
378
|
const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;
|
|
368
379
|
if (modelDir) {
|
|
369
380
|
await validateModelDir(modelDir, config.modelChecksums);
|
|
@@ -374,7 +385,8 @@ async function resolveModel(config = {}) {
|
|
|
374
385
|
try {
|
|
375
386
|
await validateModelDir(cacheDir, config.modelChecksums);
|
|
376
387
|
return artifactsFrom(cacheDir);
|
|
377
|
-
} catch {
|
|
388
|
+
} catch (err) {
|
|
389
|
+
if (!isCacheMiss(err)) throw err;
|
|
378
390
|
}
|
|
379
391
|
await downloadWithLock(cacheDir, config);
|
|
380
392
|
return artifactsFrom(cacheDir);
|
|
@@ -390,7 +402,7 @@ ${checksumIdentity}`).digest("hex");
|
|
|
390
402
|
return (0, import_path2.join)(getDefaultCacheDir(), "custom", key);
|
|
391
403
|
}
|
|
392
404
|
async function downloadWithLock(cacheDir, config) {
|
|
393
|
-
const lockPath = (0, import_path2.join)(cacheDir,
|
|
405
|
+
const lockPath = (0, import_path2.join)(cacheDir, LOCK_FILENAME);
|
|
394
406
|
let lockFd;
|
|
395
407
|
try {
|
|
396
408
|
lockFd = await (0, import_promises2.open)(lockPath, "wx");
|
|
@@ -400,7 +412,8 @@ async function downloadWithLock(cacheDir, config) {
|
|
|
400
412
|
try {
|
|
401
413
|
await validateModelDir(cacheDir, config.modelChecksums);
|
|
402
414
|
return;
|
|
403
|
-
} catch {
|
|
415
|
+
} catch (validateErr) {
|
|
416
|
+
if (!isCacheMiss(validateErr)) throw validateErr;
|
|
404
417
|
lockFd = await (0, import_promises2.open)(lockPath, "wx");
|
|
405
418
|
}
|
|
406
419
|
} else {
|
|
@@ -444,7 +457,10 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
444
457
|
const tmpPath = `${destPath}.tmp`;
|
|
445
458
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
446
459
|
try {
|
|
460
|
+
await (0, import_promises2.unlink)(tmpPath).catch(() => {
|
|
461
|
+
});
|
|
447
462
|
await new Promise((resolve, reject) => {
|
|
463
|
+
let activeRequest;
|
|
448
464
|
const timer = setTimeout(() => {
|
|
449
465
|
reject(
|
|
450
466
|
new AgentArmorModelError(
|
|
@@ -452,6 +468,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
452
468
|
`Download of ${filename} timed out after ${timeoutMs}ms`
|
|
453
469
|
)
|
|
454
470
|
);
|
|
471
|
+
activeRequest?.destroy();
|
|
455
472
|
}, timeoutMs);
|
|
456
473
|
const makeRequest = (requestUrl, redirectCount = 0) => {
|
|
457
474
|
if (redirectCount > 5) {
|
|
@@ -461,11 +478,25 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
461
478
|
);
|
|
462
479
|
return;
|
|
463
480
|
}
|
|
464
|
-
const
|
|
465
|
-
const req = protocol(requestUrl, (res) => {
|
|
481
|
+
const req = (0, import_https.get)(requestUrl, (res) => {
|
|
466
482
|
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
467
483
|
res.resume();
|
|
468
|
-
|
|
484
|
+
try {
|
|
485
|
+
const next = new URL(res.headers.location, requestUrl);
|
|
486
|
+
if (next.protocol !== "https:") {
|
|
487
|
+
throw new Error(`Redirect to ${next.protocol} is not allowed`);
|
|
488
|
+
}
|
|
489
|
+
makeRequest(next.toString(), redirectCount + 1);
|
|
490
|
+
} catch (redirectErr) {
|
|
491
|
+
clearTimeout(timer);
|
|
492
|
+
reject(
|
|
493
|
+
new AgentArmorModelError(
|
|
494
|
+
"DOWNLOAD_FAILED",
|
|
495
|
+
`Invalid redirect while downloading ${filename}`,
|
|
496
|
+
redirectErr
|
|
497
|
+
)
|
|
498
|
+
);
|
|
499
|
+
}
|
|
469
500
|
return;
|
|
470
501
|
}
|
|
471
502
|
if (res.statusCode === 404 && optional) {
|
|
@@ -493,7 +524,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
493
524
|
onProgress(receivedBytes, totalBytes);
|
|
494
525
|
});
|
|
495
526
|
}
|
|
496
|
-
const ws = (0, import_fs.createWriteStream)(tmpPath);
|
|
527
|
+
const ws = (0, import_fs.createWriteStream)(tmpPath, { flags: "wx" });
|
|
497
528
|
(0, import_promises3.pipeline)(res, ws).then(() => {
|
|
498
529
|
clearTimeout(timer);
|
|
499
530
|
resolve();
|
|
@@ -508,6 +539,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
508
539
|
);
|
|
509
540
|
});
|
|
510
541
|
});
|
|
542
|
+
activeRequest = req;
|
|
511
543
|
req.on("error", (reqErr) => {
|
|
512
544
|
clearTimeout(timer);
|
|
513
545
|
reject(
|
|
@@ -519,7 +551,18 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
519
551
|
);
|
|
520
552
|
});
|
|
521
553
|
};
|
|
522
|
-
|
|
554
|
+
try {
|
|
555
|
+
makeRequest(url);
|
|
556
|
+
} catch (urlErr) {
|
|
557
|
+
clearTimeout(timer);
|
|
558
|
+
reject(
|
|
559
|
+
new AgentArmorModelError(
|
|
560
|
+
"DOWNLOAD_FAILED",
|
|
561
|
+
`Invalid download address for ${filename}`,
|
|
562
|
+
urlErr
|
|
563
|
+
)
|
|
564
|
+
);
|
|
565
|
+
}
|
|
523
566
|
});
|
|
524
567
|
await (0, import_promises2.rename)(tmpPath, destPath);
|
|
525
568
|
return;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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';\nimport type { ModelArtifactChecksums } from './constants';\n\nexport { AgentArmorModelError } from './errors';\nexport { MLDetector } from './ml-detector';\nexport type { ModelArtifacts } from './model-manager';\nexport type { ModelArtifactChecksums } from './constants';\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 modelChecksums?: ModelArtifactChecksums;\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 = 'v3';\nexport const HF_REPO_ID = 'stylusnexus/agent-armor-classifier';\n/**\n * The Hugging Face branch or tag the package downloads from. Pinned so that a\n * newer model pushed to `main` cannot break the checksum of an older package\n * version. A retrain publishes to a new revision and bumps this with\n * MODEL_VERSION and REQUIRED_MODEL_CHECKSUMS in one change.\n */\nexport const HF_REVISION = 'v3';\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 = ['tokenizer_config.json', 'special_tokens_map.json'] as const;\n\nexport const MODEL_CHECKSUM = '17a4ae95494348929833a5ef8de8007c82d84e4b9c8bf4c53d4530688aec03a0';\n\n/** SHA-256 digests for the required files at HF_REVISION. Update with every model release. */\nexport const REQUIRED_MODEL_CHECKSUMS: Readonly<\n Record<(typeof REQUIRED_MODEL_FILES)[number], string>\n> = {\n 'model_quantized.onnx': MODEL_CHECKSUM,\n 'tokenizer.json': '2b37df34524d914c6f15ddccdb324c98d43358d5f68a52758fcc87721c3dd16d',\n 'label_map.json': 'a4de5af7e74d57145f719c1ed7694943a1e6e4890387216acaa3e9c25c7ac574',\n};\n\n/** SHA-256 digests for every required artifact, used to pin custom model directories. */\nexport type ModelArtifactChecksums = Record<(typeof REQUIRED_MODEL_FILES)[number], string>;\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(LABELS.map((label, i) => [label, i])) as Record<\n (typeof LABELS)[number],\n number\n>;\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 * The slice of the model's `tokenizer.json` that this file checks before\n * handing it to the Hugging Face tokenizer. Every field is optional because the\n * file may be hand-assembled or truncated (users can point `modelDir` at their\n * own directory), so `fromFile` validates rather than trusting the annotation.\n */\ninterface TokenizerJson {\n model?: { type?: string };\n added_tokens?: Array<{ id: number; content: string }>;\n}\n\n/** The subset of the `tokenizers` package this wrapper calls. */\ninterface HfEncoding {\n getIds(): number[];\n}\ninterface HfTokenizer {\n disablePadding(): void;\n disableTruncation(): void;\n encode(\n text: string,\n pair: string | null,\n options: { addSpecialTokens: boolean },\n ): Promise<HfEncoding>;\n}\ninterface HfTokenizersModule {\n Tokenizer: { fromFile(path: string): HfTokenizer };\n}\n\n/** Tokenizer families the shipped model has been checked against golden ids for. */\nconst SUPPORTED_MODEL_TYPES = ['Unigram'];\n\nconst REQUIRED_SPECIAL = ['[PAD]', '[CLS]', '[SEP]', '[UNK]'] as const;\n\n/** Bound tokenizer work even when callers pass a single enormous token. */\nexport const MAX_TOKENIZER_INPUT_CHARS = 16_384;\n\n/** Result of {@link Tokenizer.encode}. */\nexport interface Encoded {\n inputIds: BigInt64Array;\n attentionMask: BigInt64Array;\n /** Share of the content tokens (everything except [CLS] and [SEP]) that are [UNK]. */\n unknownRatio: number;\n}\n\n/**\n * Turns text into the `input_ids` and `attention_mask` int64 tensors the ONNX\n * classifier expects.\n *\n * Tokenization is done by the Hugging Face `tokenizers` package reading the\n * model's own `tokenizer.json`, so the ids match what the model saw in training\n * (the training script uses the same Rust code through Python). This file holds\n * no tokenization logic of its own. A retrain that ships a new `tokenizer.json`\n * works without changing tokenization code. A retrain must update the pinned\n * tokenizer checksum in `constants.ts`; the golden-id test in\n * `__tests__/tokenizer-golden.test.ts` checks that output still matches the\n * Python tokenizer.\n */\nexport class Tokenizer {\n private constructor(\n private readonly hf: HfTokenizer,\n private readonly clsId: number,\n private readonly sepId: number,\n private readonly padId: number,\n private readonly unkId: number,\n ) {}\n\n /** Load a tokenizer from the model's `tokenizer.json`. */\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 const type = json.model?.type;\n if (!type) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} is missing \"model.type\". The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`,\n );\n }\n if (!SUPPORTED_MODEL_TYPES.includes(type)) {\n throw new AgentArmorModelError(\n 'UNSUPPORTED_TOKENIZER',\n `Tokenizer file at ${path} is a \"${type}\" tokenizer; this version of @stylusnexus/agentarmor-ml only has golden-id coverage for ${SUPPORTED_MODEL_TYPES.join(', ')}. Update the package, or add golden fixtures for the new tokenizer type before using it.`,\n );\n }\n\n const special: Record<string, number> = {};\n for (const token of json.added_tokens ?? []) special[token.content] = token.id;\n const missing = REQUIRED_SPECIAL.filter((name) => !(name in special));\n if (missing.length > 0) {\n throw new AgentArmorModelError(\n 'UNSUPPORTED_TOKENIZER',\n `Tokenizer file at ${path} does not define the special tokens ${missing.join(', ')}.`,\n );\n }\n\n let mod: HfTokenizersModule;\n try {\n mod = (await import('tokenizers')) as unknown as HfTokenizersModule;\n } catch (err) {\n throw new AgentArmorModelError(\n 'TOKENIZER_LOAD_FAILED',\n `Could not load the \"tokenizers\" package (a native add-on with prebuilt binaries for macOS, Linux and Windows): ${err instanceof Error ? err.message : String(err)}`,\n err instanceof Error ? err : undefined,\n );\n }\n\n let hf: HfTokenizer;\n try {\n hf = mod.Tokenizer.fromFile(path);\n } catch (err) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} could not be parsed: ${err instanceof Error ? err.message : String(err)}`,\n err instanceof Error ? err : undefined,\n );\n }\n // The file may carry its own padding and truncation settings (this one pads\n // every input to 512). Turn both off and apply them here, so the output does\n // not depend on whatever the file happens to say.\n hf.disablePadding();\n hf.disableTruncation();\n\n return new Tokenizer(\n hf,\n special['[CLS]'],\n special['[SEP]'],\n special['[PAD]'],\n special['[UNK]'],\n );\n }\n\n /**\n * Encode text into `input_ids` and `attention_mask`, padded or cut to exactly\n * `maxLength` positions. Text that is too long is cut after `maxLength - 1`\n * ids and ends with [SEP], like the training tokenizer's truncation.\n */\n async encode(text: string, maxLength: number = 512): Promise<Encoded> {\n let boundedText = text.slice(0, MAX_TOKENIZER_INPUT_CHARS);\n // String.slice is UTF-16 based; do not pass a dangling high surrogate to\n // the native tokenizer when the cap lands between a surrogate pair.\n const lastCodeUnit = boundedText.charCodeAt(boundedText.length - 1);\n if (lastCodeUnit >= 0xd800 && lastCodeUnit <= 0xdbff) {\n boundedText = boundedText.slice(0, -1);\n }\n const encoding = await this.hf.encode(boundedText, null, { addSpecialTokens: true });\n let ids = encoding.getIds();\n\n if (ids.length > maxLength) {\n ids = ids.slice(0, maxLength);\n ids[maxLength - 1] = this.sepId;\n }\n\n const inputIds = new BigInt64Array(maxLength).fill(BigInt(this.padId));\n const attentionMask = new BigInt64Array(maxLength);\n let unknown = 0;\n for (let i = 0; i < ids.length; i++) {\n inputIds[i] = BigInt(ids[i]);\n attentionMask[i] = 1n;\n if (ids[i] === this.unkId) unknown++;\n }\n\n const content = Math.max(ids.length - 2, 0);\n return { inputIds, attentionMask, unknownRatio: content === 0 ? 0 : unknown / content };\n }\n}\n","/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */\nexport type ModelErrorCode =\n | 'MODEL_NOT_FOUND'\n | 'CHECKSUM_MISMATCH'\n | 'CHECKSUM_REQUIRED'\n | 'DOWNLOAD_FAILED'\n | 'DOWNLOAD_TIMEOUT'\n | 'DISK_FULL'\n | 'LOCK_TIMEOUT'\n | 'UNSUPPORTED_TOKENIZER'\n | 'TOKENIZER_LOAD_FAILED';\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 skipped?: { reason: string };\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\n/** More than this share of unknown content tokens means the tokenizer does not fit the model. */\nconst MAX_UNKNOWN_RATIO = 0.5;\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 // Load the tokenizer first: it can reject the model directory, and a session\n // created before that would be left open.\n const tokenizer = await Tokenizer.fromFile(artifacts.tokenizerPath);\n const session = await ort.InferenceSession.create(artifacts.modelPath);\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, unknownRatio } = await this.tokenizer.encode(content, 512);\n\n // Mostly unknown ids means the tokenizer and the model disagree (the failure\n // behind #271). The output would only reflect the input's length, so drop the\n // ML result and let the pattern detectors carry the scan. The skip is\n // reported in the result; AgentArmor turns it into one on.warn event.\n if (unknownRatio > MAX_UNKNOWN_RATIO && content.length > 5) {\n return {\n threats: [],\n skipped: {\n reason: `${(unknownRatio * 100).toFixed(0)}% of the tokens are unknown, so the tokenizer does not match the model (see https://github.com/stylusnexus/agent-armor/issues/271)`,\n },\n };\n }\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:\n 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 HF_REVISION,\n MODEL_CHECKSUM,\n MODEL_FILENAME,\n type ModelArtifactChecksums,\n OPTIONAL_MODEL_FILES,\n REQUIRED_MODEL_FILES,\n REQUIRED_MODEL_CHECKSUMS,\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 modelChecksums?: ModelArtifactChecksums;\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(\n dir: string,\n checksums: ModelArtifactChecksums = REQUIRED_MODEL_CHECKSUMS,\n): 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 await verifyRequiredModelChecksums(dir, checksums);\n}\n\n/** Verify pinned SHA-256 digests for all required artifacts in a complete directory. */\nexport async function verifyRequiredModelChecksums(\n dir: string,\n checksums: ModelArtifactChecksums = REQUIRED_MODEL_CHECKSUMS,\n): Promise<void> {\n const invalid = REQUIRED_MODEL_FILES.filter(\n (file) => !/^[a-f0-9]{64}$/i.test(checksums?.[file] ?? ''),\n );\n if (invalid.length > 0) {\n throw new AgentArmorModelError(\n 'CHECKSUM_REQUIRED',\n `A valid SHA-256 checksum is required for each model artifact; missing or invalid: ${invalid.join(', ')}`,\n );\n }\n for (const file of REQUIRED_MODEL_FILES) {\n const path = join(dir, file);\n if (!(await verifyChecksum(path, checksums[file]))) {\n throw new AgentArmorModelError(\n 'CHECKSUM_MISMATCH',\n `Required model file checksum verification failed for ${path}`,\n );\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, config.modelChecksums);\n return artifactsFrom(modelDir);\n }\n\n // Keep custom model sources/checksums out of the shared pinned-release cache.\n // Otherwise one caller can overwrite or invalidate artifacts another caller\n // expects to match the package-pinned digests.\n const cacheDir = getModelCacheDir(config);\n await mkdir(cacheDir, { recursive: true });\n\n // Check if a valid cached model exists\n try {\n await validateModelDir(cacheDir, config.modelChecksums);\n return artifactsFrom(cacheDir);\n } catch {\n // Not cached — download\n }\n\n await downloadWithLock(cacheDir, config);\n return artifactsFrom(cacheDir);\n}\n\nexport function getModelCacheDir(config: MLConfigLike): string {\n if (!config.modelChecksums && !config.modelUrl) return getDefaultCacheDir();\n\n const source = config.modelUrl ?? `https://huggingface.co/${HF_REPO_ID}/resolve/${HF_REVISION}`;\n const checksumIdentity = REQUIRED_MODEL_FILES.map(\n (file) => `${file}:${config.modelChecksums?.[file] ?? REQUIRED_MODEL_CHECKSUMS[file]}`,\n ).join('\\n');\n const key = createHash('sha256').update(`${source}\\n${checksumIdentity}`).digest('hex');\n return join(getDefaultCacheDir(), 'custom', key);\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(cacheDir: string, config: MLConfigLike): 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, config.modelChecksums);\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 every required artifact before treating the cache as usable.\n try {\n await validateModelDir(cacheDir, config.modelChecksums);\n } catch (err) {\n // Clean up the bad download\n for (const file of REQUIRED_MODEL_FILES) {\n await unlink(join(cacheDir, file)).catch(() => {});\n }\n throw err;\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/${HF_REVISION}`;\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(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Too many redirects for ${filename}`),\n );\n return;\n }\n\n const protocol = requestUrl.startsWith('https') ? httpsGet : httpsGet;\n const req = protocol(requestUrl, (res) => {\n if (\n res.statusCode &&\n res.statusCode >= 300 &&\n res.statusCode < 400 &&\n res.headers.location\n ) {\n // Hugging Face redirects a branch download to a relative path\n // (/api/resolve-cache/...), so resolve it against the current URL.\n res.resume();\n makeRequest(new URL(res.headers.location, requestUrl).toString(), 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(\n 'DOWNLOAD_FAILED',\n `Failed to write ${filename}`,\n pipeErr,\n ),\n );\n });\n });\n\n req.on('error', (reqErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Network error downloading ${filename}`,\n reqErr,\n ),\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.toLowerCase();\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;AAOnB,IAAM,cAAc;AACpB,IAAM,iBAAiB;AAEvB,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,uBAAuB,CAAC,yBAAyB,yBAAyB;AAEhF,IAAM,iBAAiB;AAGvB,IAAM,2BAET;AAAA,EACF,wBAAwB;AAAA,EACxB,kBAAkB;AAAA,EAClB,kBAAkB;AACpB;AAKO,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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;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;;;ALpZA,eAAsB,iBAAiB,UAUf;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';\nimport type { ModelArtifactChecksums } from './constants';\n\nexport { AgentArmorModelError } from './errors';\nexport { MLDetector } from './ml-detector';\nexport type { ModelArtifacts } from './model-manager';\nexport type { ModelArtifactChecksums } from './constants';\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 modelChecksums?: ModelArtifactChecksums;\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 = 'v3';\nexport const HF_REPO_ID = 'stylusnexus/agent-armor-classifier';\n/**\n * The Hugging Face branch or tag the package downloads from. Pinned so that a\n * newer model pushed to `main` cannot break the checksum of an older package\n * version. A retrain publishes to a new revision and bumps this with\n * MODEL_VERSION and REQUIRED_MODEL_CHECKSUMS in one change.\n */\nexport const HF_REVISION = 'v3';\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 = ['tokenizer_config.json', 'special_tokens_map.json'] as const;\n\nexport const MODEL_CHECKSUM = '17a4ae95494348929833a5ef8de8007c82d84e4b9c8bf4c53d4530688aec03a0';\n\n/** SHA-256 digests for the required files at HF_REVISION. Update with every model release. */\nexport const REQUIRED_MODEL_CHECKSUMS: Readonly<\n Record<(typeof REQUIRED_MODEL_FILES)[number], string>\n> = {\n 'model_quantized.onnx': MODEL_CHECKSUM,\n 'tokenizer.json': '2b37df34524d914c6f15ddccdb324c98d43358d5f68a52758fcc87721c3dd16d',\n 'label_map.json': 'a4de5af7e74d57145f719c1ed7694943a1e6e4890387216acaa3e9c25c7ac574',\n};\n\n/** SHA-256 digests for every required artifact, used to pin custom model directories. */\nexport type ModelArtifactChecksums = Record<(typeof REQUIRED_MODEL_FILES)[number], string>;\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(LABELS.map((label, i) => [label, i])) as Record<\n (typeof LABELS)[number],\n number\n>;\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 * The slice of the model's `tokenizer.json` that this file checks before\n * handing it to the Hugging Face tokenizer. Every field is optional because the\n * file may be hand-assembled or truncated (users can point `modelDir` at their\n * own directory), so `fromFile` validates rather than trusting the annotation.\n */\ninterface TokenizerJson {\n model?: { type?: string };\n added_tokens?: Array<{ id: number; content: string }>;\n}\n\n/** The subset of the `tokenizers` package this wrapper calls. */\ninterface HfEncoding {\n getIds(): number[];\n}\ninterface HfTokenizer {\n disablePadding(): void;\n disableTruncation(): void;\n encode(\n text: string,\n pair: string | null,\n options: { addSpecialTokens: boolean },\n ): Promise<HfEncoding>;\n}\ninterface HfTokenizersModule {\n Tokenizer: { fromFile(path: string): HfTokenizer };\n}\n\n/** Tokenizer families the shipped model has been checked against golden ids for. */\nconst SUPPORTED_MODEL_TYPES = ['Unigram'];\n\nconst REQUIRED_SPECIAL = ['[PAD]', '[CLS]', '[SEP]', '[UNK]'] as const;\n\n/** Bound tokenizer work even when callers pass a single enormous token. */\nexport const MAX_TOKENIZER_INPUT_CHARS = 16_384;\n\n/** Result of {@link Tokenizer.encode}. */\nexport interface Encoded {\n inputIds: BigInt64Array;\n attentionMask: BigInt64Array;\n /** Share of the content tokens (everything except [CLS] and [SEP]) that are [UNK]. */\n unknownRatio: number;\n}\n\n/**\n * Turns text into the `input_ids` and `attention_mask` int64 tensors the ONNX\n * classifier expects.\n *\n * Tokenization is done by the Hugging Face `tokenizers` package reading the\n * model's own `tokenizer.json`, so the ids match what the model saw in training\n * (the training script uses the same Rust code through Python). This file holds\n * no tokenization logic of its own. A retrain that ships a new `tokenizer.json`\n * works without changing tokenization code. A retrain must update the pinned\n * tokenizer checksum in `constants.ts`; the golden-id test in\n * `__tests__/tokenizer-golden.test.ts` checks that output still matches the\n * Python tokenizer.\n */\nexport class Tokenizer {\n private constructor(\n private readonly hf: HfTokenizer,\n private readonly clsId: number,\n private readonly sepId: number,\n private readonly padId: number,\n private readonly unkId: number,\n ) {}\n\n /** Load a tokenizer from the model's `tokenizer.json`. */\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 const type = json.model?.type;\n if (!type) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} is missing \"model.type\". The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`,\n );\n }\n if (!SUPPORTED_MODEL_TYPES.includes(type)) {\n throw new AgentArmorModelError(\n 'UNSUPPORTED_TOKENIZER',\n `Tokenizer file at ${path} is a \"${type}\" tokenizer; this version of @stylusnexus/agentarmor-ml only has golden-id coverage for ${SUPPORTED_MODEL_TYPES.join(', ')}. Update the package, or add golden fixtures for the new tokenizer type before using it.`,\n );\n }\n\n const special: Record<string, number> = {};\n for (const token of json.added_tokens ?? []) special[token.content] = token.id;\n const missing = REQUIRED_SPECIAL.filter((name) => !(name in special));\n if (missing.length > 0) {\n throw new AgentArmorModelError(\n 'UNSUPPORTED_TOKENIZER',\n `Tokenizer file at ${path} does not define the special tokens ${missing.join(', ')}.`,\n );\n }\n\n let mod: HfTokenizersModule;\n try {\n mod = (await import('tokenizers')) as unknown as HfTokenizersModule;\n } catch (err) {\n throw new AgentArmorModelError(\n 'TOKENIZER_LOAD_FAILED',\n `Could not load the \"tokenizers\" package (a native add-on with prebuilt binaries for macOS, Linux and Windows): ${err instanceof Error ? err.message : String(err)}`,\n err instanceof Error ? err : undefined,\n );\n }\n\n let hf: HfTokenizer;\n try {\n hf = mod.Tokenizer.fromFile(path);\n } catch (err) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} could not be parsed: ${err instanceof Error ? err.message : String(err)}`,\n err instanceof Error ? err : undefined,\n );\n }\n // The file may carry its own padding and truncation settings (this one pads\n // every input to 512). Turn both off and apply them here, so the output does\n // not depend on whatever the file happens to say.\n hf.disablePadding();\n hf.disableTruncation();\n\n return new Tokenizer(\n hf,\n special['[CLS]'],\n special['[SEP]'],\n special['[PAD]'],\n special['[UNK]'],\n );\n }\n\n /**\n * Encode text into `input_ids` and `attention_mask`, padded or cut to exactly\n * `maxLength` positions. Text that is too long is cut after `maxLength - 1`\n * ids and ends with [SEP], like the training tokenizer's truncation.\n */\n async encode(text: string, maxLength: number = 512): Promise<Encoded> {\n let boundedText = text.slice(0, MAX_TOKENIZER_INPUT_CHARS);\n // String.slice is UTF-16 based; do not pass a dangling high surrogate to\n // the native tokenizer when the cap lands between a surrogate pair.\n const lastCodeUnit = boundedText.charCodeAt(boundedText.length - 1);\n if (lastCodeUnit >= 0xd800 && lastCodeUnit <= 0xdbff) {\n boundedText = boundedText.slice(0, -1);\n }\n const encoding = await this.hf.encode(boundedText, null, { addSpecialTokens: true });\n let ids = encoding.getIds();\n\n if (ids.length > maxLength) {\n ids = ids.slice(0, maxLength);\n ids[maxLength - 1] = this.sepId;\n }\n\n const inputIds = new BigInt64Array(maxLength).fill(BigInt(this.padId));\n const attentionMask = new BigInt64Array(maxLength);\n let unknown = 0;\n for (let i = 0; i < ids.length; i++) {\n inputIds[i] = BigInt(ids[i]);\n attentionMask[i] = 1n;\n if (ids[i] === this.unkId) unknown++;\n }\n\n const content = Math.max(ids.length - 2, 0);\n return { inputIds, attentionMask, unknownRatio: content === 0 ? 0 : unknown / content };\n }\n}\n","/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */\nexport type ModelErrorCode =\n | 'MODEL_NOT_FOUND'\n | 'CHECKSUM_MISMATCH'\n | 'CHECKSUM_REQUIRED'\n | 'DOWNLOAD_FAILED'\n | 'DOWNLOAD_TIMEOUT'\n | 'DISK_FULL'\n | 'LOCK_TIMEOUT'\n | 'UNSUPPORTED_TOKENIZER'\n | 'TOKENIZER_LOAD_FAILED';\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 skipped?: { reason: string };\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\n/** More than this share of unknown content tokens means the tokenizer does not fit the model. */\nconst MAX_UNKNOWN_RATIO = 0.5;\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 // Load the tokenizer first: it can reject the model directory, and a session\n // created before that would be left open.\n const tokenizer = await Tokenizer.fromFile(artifacts.tokenizerPath);\n const session = await ort.InferenceSession.create(artifacts.modelPath);\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, unknownRatio } = await this.tokenizer.encode(content, 512);\n\n // Mostly unknown ids means the tokenizer and the model disagree (the failure\n // behind #271). The output would only reflect the input's length, so drop the\n // ML result and let the pattern detectors carry the scan. The skip is\n // reported in the result; AgentArmor turns it into one on.warn event.\n if (unknownRatio > MAX_UNKNOWN_RATIO && content.length > 5) {\n return {\n threats: [],\n skipped: {\n reason: `${(unknownRatio * 100).toFixed(0)}% of the tokens are unknown, so the tokenizer does not match the model (see https://github.com/stylusnexus/agent-armor/issues/271)`,\n },\n };\n }\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:\n 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, lstat, mkdir, open, readdir, rename, rmdir, 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 HF_REVISION,\n MODEL_CHECKSUM,\n MODEL_FILENAME,\n type ModelArtifactChecksums,\n OPTIONAL_MODEL_FILES,\n REQUIRED_MODEL_FILES,\n REQUIRED_MODEL_CHECKSUMS,\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 modelChecksums?: ModelArtifactChecksums;\n enabled?: boolean;\n modelUrl?: string;\n download?: {\n timeoutMs?: number;\n retries?: number;\n onProgress?: (bytesReceived: number, totalBytes: number) => void;\n };\n}\n\nconst LOCK_FILENAME = 'model.onnx.lock';\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(\n dir: string,\n checksums: ModelArtifactChecksums = REQUIRED_MODEL_CHECKSUMS,\n): 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 await verifyRequiredModelChecksums(dir, checksums);\n}\n\n/**\n * Throw CHECKSUM_REQUIRED unless every required artifact has a 64-character\n * hex SHA-256 digest. Needs no file I/O, so a bad config fails before any\n * cache read or download.\n */\nfunction assertModelChecksums(checksums: ModelArtifactChecksums = REQUIRED_MODEL_CHECKSUMS): void {\n const invalid = REQUIRED_MODEL_FILES.filter(\n (file) => !/^[a-f0-9]{64}$/i.test(checksums?.[file] ?? ''),\n );\n if (invalid.length > 0) {\n throw new AgentArmorModelError(\n 'CHECKSUM_REQUIRED',\n `A valid SHA-256 checksum is required for each model artifact; missing or invalid: ${invalid.join(', ')}`,\n );\n }\n}\n\n/**\n * Whether a failed cache check means \"download again\": a required file is\n * missing or does not match its digest. Any other error (a bad checksum\n * config, an unreadable cache) would fail the same way after a download.\n */\nfunction isCacheMiss(err: unknown): boolean {\n if (err instanceof AgentArmorModelError) {\n return err.code === 'MODEL_NOT_FOUND' || err.code === 'CHECKSUM_MISMATCH';\n }\n return (err as NodeJS.ErrnoException | undefined)?.code === 'ENOENT';\n}\n\n/** Verify pinned SHA-256 digests for all required artifacts in a complete directory. */\nexport async function verifyRequiredModelChecksums(\n dir: string,\n checksums: ModelArtifactChecksums = REQUIRED_MODEL_CHECKSUMS,\n): Promise<void> {\n assertModelChecksums(checksums);\n for (const file of REQUIRED_MODEL_FILES) {\n const path = join(dir, file);\n if (!(await verifyChecksum(path, checksums[file]))) {\n throw new AgentArmorModelError(\n 'CHECKSUM_MISMATCH',\n `Required model file checksum verification failed for ${path}`,\n );\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 // A bad checksum config would fail again after every download (#359).\n assertModelChecksums(config.modelChecksums);\n\n const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;\n\n if (modelDir) {\n await validateModelDir(modelDir, config.modelChecksums);\n return artifactsFrom(modelDir);\n }\n\n // Keep custom model sources/checksums out of the shared pinned-release cache.\n // Otherwise one caller can overwrite or invalidate artifacts another caller\n // expects to match the package-pinned digests.\n const cacheDir = getModelCacheDir(config);\n await mkdir(cacheDir, { recursive: true });\n\n // Check if a valid cached model exists\n try {\n await validateModelDir(cacheDir, config.modelChecksums);\n return artifactsFrom(cacheDir);\n } catch (err) {\n if (!isCacheMiss(err)) throw err;\n // Not cached — download\n }\n\n await downloadWithLock(cacheDir, config);\n return artifactsFrom(cacheDir);\n}\n\nexport function getModelCacheDir(config: MLConfigLike): string {\n if (!config.modelChecksums && !config.modelUrl) return getDefaultCacheDir();\n\n const source = config.modelUrl ?? `https://huggingface.co/${HF_REPO_ID}/resolve/${HF_REVISION}`;\n const checksumIdentity = REQUIRED_MODEL_FILES.map(\n (file) => `${file}:${config.modelChecksums?.[file] ?? REQUIRED_MODEL_CHECKSUMS[file]}`,\n ).join('\\n');\n const key = createHash('sha256').update(`${source}\\n${checksumIdentity}`).digest('hex');\n return join(getDefaultCacheDir(), 'custom', key);\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(cacheDir: string, config: MLConfigLike): Promise<void> {\n const lockPath = join(cacheDir, LOCK_FILENAME);\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, config.modelChecksums);\n return;\n } catch (validateErr) {\n if (!isCacheMiss(validateErr)) throw validateErr;\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 every required artifact before treating the cache as usable.\n try {\n await validateModelDir(cacheDir, config.modelChecksums);\n } catch (err) {\n // Clean up the bad download\n for (const file of REQUIRED_MODEL_FILES) {\n await unlink(join(cacheDir, file)).catch(() => {});\n }\n throw err;\n }\n } finally {\n await lockFd.close();\n await unlink(lockPath).catch(() => {});\n }\n}\n\n/**\n * Delete the files this package writes to a cache directory, including the\n * caches for custom model sources. `AGENTARMOR_CACHE_DIR` can name a folder that\n * holds other data, so anything else stays. A folder is removed only if empty.\n */\nexport async function clearCache(cacheDir: string): Promise<void> {\n const customDir = join(cacheDir, 'custom');\n // lstat, so that a symlinked `custom` folder is not followed.\n const isCustomDir = await lstat(customDir).then(\n (s) => s.isDirectory(),\n () => false,\n );\n if (isCustomDir) {\n for (const entry of await readdir(customDir, { withFileTypes: true })) {\n if (entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)) {\n await removeCacheFiles(join(customDir, entry.name));\n }\n }\n await removeIfEmpty(customDir);\n }\n await removeCacheFiles(cacheDir);\n}\n\nasync function removeCacheFiles(dir: string): Promise<void> {\n const files = [...REQUIRED_MODEL_FILES, ...OPTIONAL_MODEL_FILES];\n const names = [...files, ...files.map((file) => `${file}.tmp`), LOCK_FILENAME];\n // Try every file before reporting the first one that could not be deleted.\n let failure: unknown;\n for (const name of names) {\n await unlink(join(dir, name))\n .catch(ignoreCodes('ENOENT'))\n .catch((err: unknown) => {\n failure ??= err;\n });\n }\n if (failure) throw failure;\n await removeIfEmpty(dir);\n}\n\nasync function removeIfEmpty(dir: string): Promise<void> {\n // ENOTDIR: the path is a symlink to a folder. Leave the link in place.\n await rmdir(dir).catch(ignoreCodes('ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'));\n}\n\nfunction ignoreCodes(...codes: string[]) {\n return (err: NodeJS.ErrnoException): void => {\n if (!codes.includes(err.code ?? '')) throw err;\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/${HF_REVISION}`;\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 // Remove a leftover temp file (or a symlink planted there) so that the\n // exclusive create below writes only to a new file.\n await unlink(tmpPath).catch(() => {});\n\n await new Promise<void>((resolve, reject) => {\n let activeRequest: ReturnType<typeof httpsGet> | undefined;\n const timer = setTimeout(() => {\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_TIMEOUT',\n `Download of ${filename} timed out after ${timeoutMs}ms`,\n ),\n );\n activeRequest?.destroy();\n }, timeoutMs);\n\n const makeRequest = (requestUrl: string, redirectCount = 0): void => {\n if (redirectCount > 5) {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Too many redirects for ${filename}`),\n );\n return;\n }\n\n const req = httpsGet(requestUrl, (res) => {\n if (\n res.statusCode &&\n res.statusCode >= 300 &&\n res.statusCode < 400 &&\n res.headers.location\n ) {\n // Hugging Face redirects a branch download to a relative path\n // (/api/resolve-cache/...), so resolve it against the current URL.\n res.resume();\n // This runs outside the promise executor, so a throw here would\n // end the host process instead of rejecting.\n try {\n const next = new URL(res.headers.location, requestUrl);\n if (next.protocol !== 'https:') {\n throw new Error(`Redirect to ${next.protocol} is not allowed`);\n }\n makeRequest(next.toString(), redirectCount + 1);\n } catch (redirectErr) {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Invalid redirect while downloading ${filename}`,\n redirectErr as Error,\n ),\n );\n }\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, { flags: 'wx' });\n pipeline(res, ws)\n .then(() => {\n clearTimeout(timer);\n resolve();\n })\n .catch((pipeErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Failed to write ${filename}`,\n pipeErr,\n ),\n );\n });\n });\n\n activeRequest = req;\n\n req.on('error', (reqErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Network error downloading ${filename}`,\n reqErr,\n ),\n );\n });\n };\n\n try {\n makeRequest(url);\n } catch (urlErr) {\n // https.get throws at once for an http or malformed address.\n clearTimeout(timer);\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Invalid download address for ${filename}`,\n urlErr as Error,\n ),\n );\n }\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.toLowerCase();\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;AAOnB,IAAM,cAAc;AACpB,IAAM,iBAAiB;AA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AAC;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;;;ALtgBA,eAAsB,iBAAiB,UAUf;AACtB,QAAM,YAAY,MAAM,aAAa,QAAQ;AAC7C,SAAO,WAAW,OAAO,SAAS;AACpC;","names":["import_promises","import_path","httpsGet"]}
|
package/dist/index.mjs
CHANGED
|
@@ -276,10 +276,11 @@ var MLDetector = class _MLDetector {
|
|
|
276
276
|
// src/model-manager.ts
|
|
277
277
|
import { createHash } from "crypto";
|
|
278
278
|
import { createReadStream, createWriteStream } from "fs";
|
|
279
|
-
import { access, mkdir, open, rename, stat, unlink } from "fs/promises";
|
|
279
|
+
import { access, lstat, mkdir, open, readdir, rename, rmdir, stat, unlink } from "fs/promises";
|
|
280
280
|
import { get as httpsGet } from "https";
|
|
281
281
|
import { join as join2 } from "path";
|
|
282
282
|
import { pipeline } from "stream/promises";
|
|
283
|
+
var LOCK_FILENAME = "model.onnx.lock";
|
|
283
284
|
function artifactsFrom(dir) {
|
|
284
285
|
return {
|
|
285
286
|
modelPath: join2(dir, MODEL_FILENAME),
|
|
@@ -305,7 +306,7 @@ async function validateModelDir(dir, checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
|
305
306
|
}
|
|
306
307
|
await verifyRequiredModelChecksums(dir, checksums);
|
|
307
308
|
}
|
|
308
|
-
|
|
309
|
+
function assertModelChecksums(checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
309
310
|
const invalid = REQUIRED_MODEL_FILES.filter(
|
|
310
311
|
(file) => !/^[a-f0-9]{64}$/i.test(checksums?.[file] ?? "")
|
|
311
312
|
);
|
|
@@ -315,6 +316,15 @@ async function verifyRequiredModelChecksums(dir, checksums = REQUIRED_MODEL_CHEC
|
|
|
315
316
|
`A valid SHA-256 checksum is required for each model artifact; missing or invalid: ${invalid.join(", ")}`
|
|
316
317
|
);
|
|
317
318
|
}
|
|
319
|
+
}
|
|
320
|
+
function isCacheMiss(err) {
|
|
321
|
+
if (err instanceof AgentArmorModelError) {
|
|
322
|
+
return err.code === "MODEL_NOT_FOUND" || err.code === "CHECKSUM_MISMATCH";
|
|
323
|
+
}
|
|
324
|
+
return err?.code === "ENOENT";
|
|
325
|
+
}
|
|
326
|
+
async function verifyRequiredModelChecksums(dir, checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
327
|
+
assertModelChecksums(checksums);
|
|
318
328
|
for (const file of REQUIRED_MODEL_FILES) {
|
|
319
329
|
const path = join2(dir, file);
|
|
320
330
|
if (!await verifyChecksum(path, checksums[file])) {
|
|
@@ -326,6 +336,7 @@ async function verifyRequiredModelChecksums(dir, checksums = REQUIRED_MODEL_CHEC
|
|
|
326
336
|
}
|
|
327
337
|
}
|
|
328
338
|
async function resolveModel(config = {}) {
|
|
339
|
+
assertModelChecksums(config.modelChecksums);
|
|
329
340
|
const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;
|
|
330
341
|
if (modelDir) {
|
|
331
342
|
await validateModelDir(modelDir, config.modelChecksums);
|
|
@@ -336,7 +347,8 @@ async function resolveModel(config = {}) {
|
|
|
336
347
|
try {
|
|
337
348
|
await validateModelDir(cacheDir, config.modelChecksums);
|
|
338
349
|
return artifactsFrom(cacheDir);
|
|
339
|
-
} catch {
|
|
350
|
+
} catch (err) {
|
|
351
|
+
if (!isCacheMiss(err)) throw err;
|
|
340
352
|
}
|
|
341
353
|
await downloadWithLock(cacheDir, config);
|
|
342
354
|
return artifactsFrom(cacheDir);
|
|
@@ -352,7 +364,7 @@ ${checksumIdentity}`).digest("hex");
|
|
|
352
364
|
return join2(getDefaultCacheDir(), "custom", key);
|
|
353
365
|
}
|
|
354
366
|
async function downloadWithLock(cacheDir, config) {
|
|
355
|
-
const lockPath = join2(cacheDir,
|
|
367
|
+
const lockPath = join2(cacheDir, LOCK_FILENAME);
|
|
356
368
|
let lockFd;
|
|
357
369
|
try {
|
|
358
370
|
lockFd = await open(lockPath, "wx");
|
|
@@ -362,7 +374,8 @@ async function downloadWithLock(cacheDir, config) {
|
|
|
362
374
|
try {
|
|
363
375
|
await validateModelDir(cacheDir, config.modelChecksums);
|
|
364
376
|
return;
|
|
365
|
-
} catch {
|
|
377
|
+
} catch (validateErr) {
|
|
378
|
+
if (!isCacheMiss(validateErr)) throw validateErr;
|
|
366
379
|
lockFd = await open(lockPath, "wx");
|
|
367
380
|
}
|
|
368
381
|
} else {
|
|
@@ -406,7 +419,10 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
406
419
|
const tmpPath = `${destPath}.tmp`;
|
|
407
420
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
408
421
|
try {
|
|
422
|
+
await unlink(tmpPath).catch(() => {
|
|
423
|
+
});
|
|
409
424
|
await new Promise((resolve, reject) => {
|
|
425
|
+
let activeRequest;
|
|
410
426
|
const timer = setTimeout(() => {
|
|
411
427
|
reject(
|
|
412
428
|
new AgentArmorModelError(
|
|
@@ -414,6 +430,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
414
430
|
`Download of ${filename} timed out after ${timeoutMs}ms`
|
|
415
431
|
)
|
|
416
432
|
);
|
|
433
|
+
activeRequest?.destroy();
|
|
417
434
|
}, timeoutMs);
|
|
418
435
|
const makeRequest = (requestUrl, redirectCount = 0) => {
|
|
419
436
|
if (redirectCount > 5) {
|
|
@@ -423,11 +440,25 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
423
440
|
);
|
|
424
441
|
return;
|
|
425
442
|
}
|
|
426
|
-
const
|
|
427
|
-
const req = protocol(requestUrl, (res) => {
|
|
443
|
+
const req = httpsGet(requestUrl, (res) => {
|
|
428
444
|
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
429
445
|
res.resume();
|
|
430
|
-
|
|
446
|
+
try {
|
|
447
|
+
const next = new URL(res.headers.location, requestUrl);
|
|
448
|
+
if (next.protocol !== "https:") {
|
|
449
|
+
throw new Error(`Redirect to ${next.protocol} is not allowed`);
|
|
450
|
+
}
|
|
451
|
+
makeRequest(next.toString(), redirectCount + 1);
|
|
452
|
+
} catch (redirectErr) {
|
|
453
|
+
clearTimeout(timer);
|
|
454
|
+
reject(
|
|
455
|
+
new AgentArmorModelError(
|
|
456
|
+
"DOWNLOAD_FAILED",
|
|
457
|
+
`Invalid redirect while downloading ${filename}`,
|
|
458
|
+
redirectErr
|
|
459
|
+
)
|
|
460
|
+
);
|
|
461
|
+
}
|
|
431
462
|
return;
|
|
432
463
|
}
|
|
433
464
|
if (res.statusCode === 404 && optional) {
|
|
@@ -455,7 +486,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
455
486
|
onProgress(receivedBytes, totalBytes);
|
|
456
487
|
});
|
|
457
488
|
}
|
|
458
|
-
const ws = createWriteStream(tmpPath);
|
|
489
|
+
const ws = createWriteStream(tmpPath, { flags: "wx" });
|
|
459
490
|
pipeline(res, ws).then(() => {
|
|
460
491
|
clearTimeout(timer);
|
|
461
492
|
resolve();
|
|
@@ -470,6 +501,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
470
501
|
);
|
|
471
502
|
});
|
|
472
503
|
});
|
|
504
|
+
activeRequest = req;
|
|
473
505
|
req.on("error", (reqErr) => {
|
|
474
506
|
clearTimeout(timer);
|
|
475
507
|
reject(
|
|
@@ -481,7 +513,18 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
481
513
|
);
|
|
482
514
|
});
|
|
483
515
|
};
|
|
484
|
-
|
|
516
|
+
try {
|
|
517
|
+
makeRequest(url);
|
|
518
|
+
} catch (urlErr) {
|
|
519
|
+
clearTimeout(timer);
|
|
520
|
+
reject(
|
|
521
|
+
new AgentArmorModelError(
|
|
522
|
+
"DOWNLOAD_FAILED",
|
|
523
|
+
`Invalid download address for ${filename}`,
|
|
524
|
+
urlErr
|
|
525
|
+
)
|
|
526
|
+
);
|
|
527
|
+
}
|
|
485
528
|
});
|
|
486
529
|
await rename(tmpPath, destPath);
|
|
487
530
|
return;
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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 = 'v3';\nexport const HF_REPO_ID = 'stylusnexus/agent-armor-classifier';\n/**\n * The Hugging Face branch or tag the package downloads from. Pinned so that a\n * newer model pushed to `main` cannot break the checksum of an older package\n * version. A retrain publishes to a new revision and bumps this with\n * MODEL_VERSION and REQUIRED_MODEL_CHECKSUMS in one change.\n */\nexport const HF_REVISION = 'v3';\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 = ['tokenizer_config.json', 'special_tokens_map.json'] as const;\n\nexport const MODEL_CHECKSUM = '17a4ae95494348929833a5ef8de8007c82d84e4b9c8bf4c53d4530688aec03a0';\n\n/** SHA-256 digests for the required files at HF_REVISION. Update with every model release. */\nexport const REQUIRED_MODEL_CHECKSUMS: Readonly<\n Record<(typeof REQUIRED_MODEL_FILES)[number], string>\n> = {\n 'model_quantized.onnx': MODEL_CHECKSUM,\n 'tokenizer.json': '2b37df34524d914c6f15ddccdb324c98d43358d5f68a52758fcc87721c3dd16d',\n 'label_map.json': 'a4de5af7e74d57145f719c1ed7694943a1e6e4890387216acaa3e9c25c7ac574',\n};\n\n/** SHA-256 digests for every required artifact, used to pin custom model directories. */\nexport type ModelArtifactChecksums = Record<(typeof REQUIRED_MODEL_FILES)[number], string>;\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(LABELS.map((label, i) => [label, i])) as Record<\n (typeof LABELS)[number],\n number\n>;\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 * The slice of the model's `tokenizer.json` that this file checks before\n * handing it to the Hugging Face tokenizer. Every field is optional because the\n * file may be hand-assembled or truncated (users can point `modelDir` at their\n * own directory), so `fromFile` validates rather than trusting the annotation.\n */\ninterface TokenizerJson {\n model?: { type?: string };\n added_tokens?: Array<{ id: number; content: string }>;\n}\n\n/** The subset of the `tokenizers` package this wrapper calls. */\ninterface HfEncoding {\n getIds(): number[];\n}\ninterface HfTokenizer {\n disablePadding(): void;\n disableTruncation(): void;\n encode(\n text: string,\n pair: string | null,\n options: { addSpecialTokens: boolean },\n ): Promise<HfEncoding>;\n}\ninterface HfTokenizersModule {\n Tokenizer: { fromFile(path: string): HfTokenizer };\n}\n\n/** Tokenizer families the shipped model has been checked against golden ids for. */\nconst SUPPORTED_MODEL_TYPES = ['Unigram'];\n\nconst REQUIRED_SPECIAL = ['[PAD]', '[CLS]', '[SEP]', '[UNK]'] as const;\n\n/** Bound tokenizer work even when callers pass a single enormous token. */\nexport const MAX_TOKENIZER_INPUT_CHARS = 16_384;\n\n/** Result of {@link Tokenizer.encode}. */\nexport interface Encoded {\n inputIds: BigInt64Array;\n attentionMask: BigInt64Array;\n /** Share of the content tokens (everything except [CLS] and [SEP]) that are [UNK]. */\n unknownRatio: number;\n}\n\n/**\n * Turns text into the `input_ids` and `attention_mask` int64 tensors the ONNX\n * classifier expects.\n *\n * Tokenization is done by the Hugging Face `tokenizers` package reading the\n * model's own `tokenizer.json`, so the ids match what the model saw in training\n * (the training script uses the same Rust code through Python). This file holds\n * no tokenization logic of its own. A retrain that ships a new `tokenizer.json`\n * works without changing tokenization code. A retrain must update the pinned\n * tokenizer checksum in `constants.ts`; the golden-id test in\n * `__tests__/tokenizer-golden.test.ts` checks that output still matches the\n * Python tokenizer.\n */\nexport class Tokenizer {\n private constructor(\n private readonly hf: HfTokenizer,\n private readonly clsId: number,\n private readonly sepId: number,\n private readonly padId: number,\n private readonly unkId: number,\n ) {}\n\n /** Load a tokenizer from the model's `tokenizer.json`. */\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 const type = json.model?.type;\n if (!type) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} is missing \"model.type\". The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`,\n );\n }\n if (!SUPPORTED_MODEL_TYPES.includes(type)) {\n throw new AgentArmorModelError(\n 'UNSUPPORTED_TOKENIZER',\n `Tokenizer file at ${path} is a \"${type}\" tokenizer; this version of @stylusnexus/agentarmor-ml only has golden-id coverage for ${SUPPORTED_MODEL_TYPES.join(', ')}. Update the package, or add golden fixtures for the new tokenizer type before using it.`,\n );\n }\n\n const special: Record<string, number> = {};\n for (const token of json.added_tokens ?? []) special[token.content] = token.id;\n const missing = REQUIRED_SPECIAL.filter((name) => !(name in special));\n if (missing.length > 0) {\n throw new AgentArmorModelError(\n 'UNSUPPORTED_TOKENIZER',\n `Tokenizer file at ${path} does not define the special tokens ${missing.join(', ')}.`,\n );\n }\n\n let mod: HfTokenizersModule;\n try {\n mod = (await import('tokenizers')) as unknown as HfTokenizersModule;\n } catch (err) {\n throw new AgentArmorModelError(\n 'TOKENIZER_LOAD_FAILED',\n `Could not load the \"tokenizers\" package (a native add-on with prebuilt binaries for macOS, Linux and Windows): ${err instanceof Error ? err.message : String(err)}`,\n err instanceof Error ? err : undefined,\n );\n }\n\n let hf: HfTokenizer;\n try {\n hf = mod.Tokenizer.fromFile(path);\n } catch (err) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} could not be parsed: ${err instanceof Error ? err.message : String(err)}`,\n err instanceof Error ? err : undefined,\n );\n }\n // The file may carry its own padding and truncation settings (this one pads\n // every input to 512). Turn both off and apply them here, so the output does\n // not depend on whatever the file happens to say.\n hf.disablePadding();\n hf.disableTruncation();\n\n return new Tokenizer(\n hf,\n special['[CLS]'],\n special['[SEP]'],\n special['[PAD]'],\n special['[UNK]'],\n );\n }\n\n /**\n * Encode text into `input_ids` and `attention_mask`, padded or cut to exactly\n * `maxLength` positions. Text that is too long is cut after `maxLength - 1`\n * ids and ends with [SEP], like the training tokenizer's truncation.\n */\n async encode(text: string, maxLength: number = 512): Promise<Encoded> {\n let boundedText = text.slice(0, MAX_TOKENIZER_INPUT_CHARS);\n // String.slice is UTF-16 based; do not pass a dangling high surrogate to\n // the native tokenizer when the cap lands between a surrogate pair.\n const lastCodeUnit = boundedText.charCodeAt(boundedText.length - 1);\n if (lastCodeUnit >= 0xd800 && lastCodeUnit <= 0xdbff) {\n boundedText = boundedText.slice(0, -1);\n }\n const encoding = await this.hf.encode(boundedText, null, { addSpecialTokens: true });\n let ids = encoding.getIds();\n\n if (ids.length > maxLength) {\n ids = ids.slice(0, maxLength);\n ids[maxLength - 1] = this.sepId;\n }\n\n const inputIds = new BigInt64Array(maxLength).fill(BigInt(this.padId));\n const attentionMask = new BigInt64Array(maxLength);\n let unknown = 0;\n for (let i = 0; i < ids.length; i++) {\n inputIds[i] = BigInt(ids[i]);\n attentionMask[i] = 1n;\n if (ids[i] === this.unkId) unknown++;\n }\n\n const content = Math.max(ids.length - 2, 0);\n return { inputIds, attentionMask, unknownRatio: content === 0 ? 0 : unknown / content };\n }\n}\n","/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */\nexport type ModelErrorCode =\n | 'MODEL_NOT_FOUND'\n | 'CHECKSUM_MISMATCH'\n | 'CHECKSUM_REQUIRED'\n | 'DOWNLOAD_FAILED'\n | 'DOWNLOAD_TIMEOUT'\n | 'DISK_FULL'\n | 'LOCK_TIMEOUT'\n | 'UNSUPPORTED_TOKENIZER'\n | 'TOKENIZER_LOAD_FAILED';\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 skipped?: { reason: string };\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\n/** More than this share of unknown content tokens means the tokenizer does not fit the model. */\nconst MAX_UNKNOWN_RATIO = 0.5;\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 // Load the tokenizer first: it can reject the model directory, and a session\n // created before that would be left open.\n const tokenizer = await Tokenizer.fromFile(artifacts.tokenizerPath);\n const session = await ort.InferenceSession.create(artifacts.modelPath);\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, unknownRatio } = await this.tokenizer.encode(content, 512);\n\n // Mostly unknown ids means the tokenizer and the model disagree (the failure\n // behind #271). The output would only reflect the input's length, so drop the\n // ML result and let the pattern detectors carry the scan. The skip is\n // reported in the result; AgentArmor turns it into one on.warn event.\n if (unknownRatio > MAX_UNKNOWN_RATIO && content.length > 5) {\n return {\n threats: [],\n skipped: {\n reason: `${(unknownRatio * 100).toFixed(0)}% of the tokens are unknown, so the tokenizer does not match the model (see https://github.com/stylusnexus/agent-armor/issues/271)`,\n },\n };\n }\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:\n 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 HF_REVISION,\n MODEL_CHECKSUM,\n MODEL_FILENAME,\n type ModelArtifactChecksums,\n OPTIONAL_MODEL_FILES,\n REQUIRED_MODEL_FILES,\n REQUIRED_MODEL_CHECKSUMS,\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 modelChecksums?: ModelArtifactChecksums;\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(\n dir: string,\n checksums: ModelArtifactChecksums = REQUIRED_MODEL_CHECKSUMS,\n): 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 await verifyRequiredModelChecksums(dir, checksums);\n}\n\n/** Verify pinned SHA-256 digests for all required artifacts in a complete directory. */\nexport async function verifyRequiredModelChecksums(\n dir: string,\n checksums: ModelArtifactChecksums = REQUIRED_MODEL_CHECKSUMS,\n): Promise<void> {\n const invalid = REQUIRED_MODEL_FILES.filter(\n (file) => !/^[a-f0-9]{64}$/i.test(checksums?.[file] ?? ''),\n );\n if (invalid.length > 0) {\n throw new AgentArmorModelError(\n 'CHECKSUM_REQUIRED',\n `A valid SHA-256 checksum is required for each model artifact; missing or invalid: ${invalid.join(', ')}`,\n );\n }\n for (const file of REQUIRED_MODEL_FILES) {\n const path = join(dir, file);\n if (!(await verifyChecksum(path, checksums[file]))) {\n throw new AgentArmorModelError(\n 'CHECKSUM_MISMATCH',\n `Required model file checksum verification failed for ${path}`,\n );\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, config.modelChecksums);\n return artifactsFrom(modelDir);\n }\n\n // Keep custom model sources/checksums out of the shared pinned-release cache.\n // Otherwise one caller can overwrite or invalidate artifacts another caller\n // expects to match the package-pinned digests.\n const cacheDir = getModelCacheDir(config);\n await mkdir(cacheDir, { recursive: true });\n\n // Check if a valid cached model exists\n try {\n await validateModelDir(cacheDir, config.modelChecksums);\n return artifactsFrom(cacheDir);\n } catch {\n // Not cached — download\n }\n\n await downloadWithLock(cacheDir, config);\n return artifactsFrom(cacheDir);\n}\n\nexport function getModelCacheDir(config: MLConfigLike): string {\n if (!config.modelChecksums && !config.modelUrl) return getDefaultCacheDir();\n\n const source = config.modelUrl ?? `https://huggingface.co/${HF_REPO_ID}/resolve/${HF_REVISION}`;\n const checksumIdentity = REQUIRED_MODEL_FILES.map(\n (file) => `${file}:${config.modelChecksums?.[file] ?? REQUIRED_MODEL_CHECKSUMS[file]}`,\n ).join('\\n');\n const key = createHash('sha256').update(`${source}\\n${checksumIdentity}`).digest('hex');\n return join(getDefaultCacheDir(), 'custom', key);\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(cacheDir: string, config: MLConfigLike): 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, config.modelChecksums);\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 every required artifact before treating the cache as usable.\n try {\n await validateModelDir(cacheDir, config.modelChecksums);\n } catch (err) {\n // Clean up the bad download\n for (const file of REQUIRED_MODEL_FILES) {\n await unlink(join(cacheDir, file)).catch(() => {});\n }\n throw err;\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/${HF_REVISION}`;\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(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Too many redirects for ${filename}`),\n );\n return;\n }\n\n const protocol = requestUrl.startsWith('https') ? httpsGet : httpsGet;\n const req = protocol(requestUrl, (res) => {\n if (\n res.statusCode &&\n res.statusCode >= 300 &&\n res.statusCode < 400 &&\n res.headers.location\n ) {\n // Hugging Face redirects a branch download to a relative path\n // (/api/resolve-cache/...), so resolve it against the current URL.\n res.resume();\n makeRequest(new URL(res.headers.location, requestUrl).toString(), 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(\n 'DOWNLOAD_FAILED',\n `Failed to write ${filename}`,\n pipeErr,\n ),\n );\n });\n });\n\n req.on('error', (reqErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Network error downloading ${filename}`,\n reqErr,\n ),\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.toLowerCase();\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';\nimport type { ModelArtifactChecksums } from './constants';\n\nexport { AgentArmorModelError } from './errors';\nexport { MLDetector } from './ml-detector';\nexport type { ModelArtifacts } from './model-manager';\nexport type { ModelArtifactChecksums } from './constants';\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 modelChecksums?: ModelArtifactChecksums;\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(mlCon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,WAAW,SAAS,YAAY;AACzC;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,YAAM,OAAO,QAAQ;AAAA,IACvB,QAAQ;AAEN;AAAA,IACF;AAGA,QAAI;AACF,YAAM,WAAW,MAAM,KAAK,QAAQ;AACpC,YAAM,UAAU,KAAK,IAAI,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;;;ACpZA,eAAsB,iBAAiB,UAUf;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 = 'v3';\nexport const HF_REPO_ID = 'stylusnexus/agent-armor-classifier';\n/**\n * The Hugging Face branch or tag the package downloads from. Pinned so that a\n * newer model pushed to `main` cannot break the checksum of an older package\n * version. A retrain publishes to a new revision and bumps this with\n * MODEL_VERSION and REQUIRED_MODEL_CHECKSUMS in one change.\n */\nexport const HF_REVISION = 'v3';\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 = ['tokenizer_config.json', 'special_tokens_map.json'] as const;\n\nexport const MODEL_CHECKSUM = '17a4ae95494348929833a5ef8de8007c82d84e4b9c8bf4c53d4530688aec03a0';\n\n/** SHA-256 digests for the required files at HF_REVISION. Update with every model release. */\nexport const REQUIRED_MODEL_CHECKSUMS: Readonly<\n Record<(typeof REQUIRED_MODEL_FILES)[number], string>\n> = {\n 'model_quantized.onnx': MODEL_CHECKSUM,\n 'tokenizer.json': '2b37df34524d914c6f15ddccdb324c98d43358d5f68a52758fcc87721c3dd16d',\n 'label_map.json': 'a4de5af7e74d57145f719c1ed7694943a1e6e4890387216acaa3e9c25c7ac574',\n};\n\n/** SHA-256 digests for every required artifact, used to pin custom model directories. */\nexport type ModelArtifactChecksums = Record<(typeof REQUIRED_MODEL_FILES)[number], string>;\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(LABELS.map((label, i) => [label, i])) as Record<\n (typeof LABELS)[number],\n number\n>;\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 * The slice of the model's `tokenizer.json` that this file checks before\n * handing it to the Hugging Face tokenizer. Every field is optional because the\n * file may be hand-assembled or truncated (users can point `modelDir` at their\n * own directory), so `fromFile` validates rather than trusting the annotation.\n */\ninterface TokenizerJson {\n model?: { type?: string };\n added_tokens?: Array<{ id: number; content: string }>;\n}\n\n/** The subset of the `tokenizers` package this wrapper calls. */\ninterface HfEncoding {\n getIds(): number[];\n}\ninterface HfTokenizer {\n disablePadding(): void;\n disableTruncation(): void;\n encode(\n text: string,\n pair: string | null,\n options: { addSpecialTokens: boolean },\n ): Promise<HfEncoding>;\n}\ninterface HfTokenizersModule {\n Tokenizer: { fromFile(path: string): HfTokenizer };\n}\n\n/** Tokenizer families the shipped model has been checked against golden ids for. */\nconst SUPPORTED_MODEL_TYPES = ['Unigram'];\n\nconst REQUIRED_SPECIAL = ['[PAD]', '[CLS]', '[SEP]', '[UNK]'] as const;\n\n/** Bound tokenizer work even when callers pass a single enormous token. */\nexport const MAX_TOKENIZER_INPUT_CHARS = 16_384;\n\n/** Result of {@link Tokenizer.encode}. */\nexport interface Encoded {\n inputIds: BigInt64Array;\n attentionMask: BigInt64Array;\n /** Share of the content tokens (everything except [CLS] and [SEP]) that are [UNK]. */\n unknownRatio: number;\n}\n\n/**\n * Turns text into the `input_ids` and `attention_mask` int64 tensors the ONNX\n * classifier expects.\n *\n * Tokenization is done by the Hugging Face `tokenizers` package reading the\n * model's own `tokenizer.json`, so the ids match what the model saw in training\n * (the training script uses the same Rust code through Python). This file holds\n * no tokenization logic of its own. A retrain that ships a new `tokenizer.json`\n * works without changing tokenization code. A retrain must update the pinned\n * tokenizer checksum in `constants.ts`; the golden-id test in\n * `__tests__/tokenizer-golden.test.ts` checks that output still matches the\n * Python tokenizer.\n */\nexport class Tokenizer {\n private constructor(\n private readonly hf: HfTokenizer,\n private readonly clsId: number,\n private readonly sepId: number,\n private readonly padId: number,\n private readonly unkId: number,\n ) {}\n\n /** Load a tokenizer from the model's `tokenizer.json`. */\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 const type = json.model?.type;\n if (!type) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} is missing \"model.type\". The model directory is corrupt or incomplete; re-download or point modelDir at a complete set of artifacts.`,\n );\n }\n if (!SUPPORTED_MODEL_TYPES.includes(type)) {\n throw new AgentArmorModelError(\n 'UNSUPPORTED_TOKENIZER',\n `Tokenizer file at ${path} is a \"${type}\" tokenizer; this version of @stylusnexus/agentarmor-ml only has golden-id coverage for ${SUPPORTED_MODEL_TYPES.join(', ')}. Update the package, or add golden fixtures for the new tokenizer type before using it.`,\n );\n }\n\n const special: Record<string, number> = {};\n for (const token of json.added_tokens ?? []) special[token.content] = token.id;\n const missing = REQUIRED_SPECIAL.filter((name) => !(name in special));\n if (missing.length > 0) {\n throw new AgentArmorModelError(\n 'UNSUPPORTED_TOKENIZER',\n `Tokenizer file at ${path} does not define the special tokens ${missing.join(', ')}.`,\n );\n }\n\n let mod: HfTokenizersModule;\n try {\n mod = (await import('tokenizers')) as unknown as HfTokenizersModule;\n } catch (err) {\n throw new AgentArmorModelError(\n 'TOKENIZER_LOAD_FAILED',\n `Could not load the \"tokenizers\" package (a native add-on with prebuilt binaries for macOS, Linux and Windows): ${err instanceof Error ? err.message : String(err)}`,\n err instanceof Error ? err : undefined,\n );\n }\n\n let hf: HfTokenizer;\n try {\n hf = mod.Tokenizer.fromFile(path);\n } catch (err) {\n throw new AgentArmorModelError(\n 'MODEL_NOT_FOUND',\n `Tokenizer file at ${path} could not be parsed: ${err instanceof Error ? err.message : String(err)}`,\n err instanceof Error ? err : undefined,\n );\n }\n // The file may carry its own padding and truncation settings (this one pads\n // every input to 512). Turn both off and apply them here, so the output does\n // not depend on whatever the file happens to say.\n hf.disablePadding();\n hf.disableTruncation();\n\n return new Tokenizer(\n hf,\n special['[CLS]'],\n special['[SEP]'],\n special['[PAD]'],\n special['[UNK]'],\n );\n }\n\n /**\n * Encode text into `input_ids` and `attention_mask`, padded or cut to exactly\n * `maxLength` positions. Text that is too long is cut after `maxLength - 1`\n * ids and ends with [SEP], like the training tokenizer's truncation.\n */\n async encode(text: string, maxLength: number = 512): Promise<Encoded> {\n let boundedText = text.slice(0, MAX_TOKENIZER_INPUT_CHARS);\n // String.slice is UTF-16 based; do not pass a dangling high surrogate to\n // the native tokenizer when the cap lands between a surrogate pair.\n const lastCodeUnit = boundedText.charCodeAt(boundedText.length - 1);\n if (lastCodeUnit >= 0xd800 && lastCodeUnit <= 0xdbff) {\n boundedText = boundedText.slice(0, -1);\n }\n const encoding = await this.hf.encode(boundedText, null, { addSpecialTokens: true });\n let ids = encoding.getIds();\n\n if (ids.length > maxLength) {\n ids = ids.slice(0, maxLength);\n ids[maxLength - 1] = this.sepId;\n }\n\n const inputIds = new BigInt64Array(maxLength).fill(BigInt(this.padId));\n const attentionMask = new BigInt64Array(maxLength);\n let unknown = 0;\n for (let i = 0; i < ids.length; i++) {\n inputIds[i] = BigInt(ids[i]);\n attentionMask[i] = 1n;\n if (ids[i] === this.unkId) unknown++;\n }\n\n const content = Math.max(ids.length - 2, 0);\n return { inputIds, attentionMask, unknownRatio: content === 0 ? 0 : unknown / content };\n }\n}\n","/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */\nexport type ModelErrorCode =\n | 'MODEL_NOT_FOUND'\n | 'CHECKSUM_MISMATCH'\n | 'CHECKSUM_REQUIRED'\n | 'DOWNLOAD_FAILED'\n | 'DOWNLOAD_TIMEOUT'\n | 'DISK_FULL'\n | 'LOCK_TIMEOUT'\n | 'UNSUPPORTED_TOKENIZER'\n | 'TOKENIZER_LOAD_FAILED';\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 skipped?: { reason: string };\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\n/** More than this share of unknown content tokens means the tokenizer does not fit the model. */\nconst MAX_UNKNOWN_RATIO = 0.5;\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 // Load the tokenizer first: it can reject the model directory, and a session\n // created before that would be left open.\n const tokenizer = await Tokenizer.fromFile(artifacts.tokenizerPath);\n const session = await ort.InferenceSession.create(artifacts.modelPath);\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, unknownRatio } = await this.tokenizer.encode(content, 512);\n\n // Mostly unknown ids means the tokenizer and the model disagree (the failure\n // behind #271). The output would only reflect the input's length, so drop the\n // ML result and let the pattern detectors carry the scan. The skip is\n // reported in the result; AgentArmor turns it into one on.warn event.\n if (unknownRatio > MAX_UNKNOWN_RATIO && content.length > 5) {\n return {\n threats: [],\n skipped: {\n reason: `${(unknownRatio * 100).toFixed(0)}% of the tokens are unknown, so the tokenizer does not match the model (see https://github.com/stylusnexus/agent-armor/issues/271)`,\n },\n };\n }\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:\n 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, lstat, mkdir, open, readdir, rename, rmdir, 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 HF_REVISION,\n MODEL_CHECKSUM,\n MODEL_FILENAME,\n type ModelArtifactChecksums,\n OPTIONAL_MODEL_FILES,\n REQUIRED_MODEL_FILES,\n REQUIRED_MODEL_CHECKSUMS,\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 modelChecksums?: ModelArtifactChecksums;\n enabled?: boolean;\n modelUrl?: string;\n download?: {\n timeoutMs?: number;\n retries?: number;\n onProgress?: (bytesReceived: number, totalBytes: number) => void;\n };\n}\n\nconst LOCK_FILENAME = 'model.onnx.lock';\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(\n dir: string,\n checksums: ModelArtifactChecksums = REQUIRED_MODEL_CHECKSUMS,\n): 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 await verifyRequiredModelChecksums(dir, checksums);\n}\n\n/**\n * Throw CHECKSUM_REQUIRED unless every required artifact has a 64-character\n * hex SHA-256 digest. Needs no file I/O, so a bad config fails before any\n * cache read or download.\n */\nfunction assertModelChecksums(checksums: ModelArtifactChecksums = REQUIRED_MODEL_CHECKSUMS): void {\n const invalid = REQUIRED_MODEL_FILES.filter(\n (file) => !/^[a-f0-9]{64}$/i.test(checksums?.[file] ?? ''),\n );\n if (invalid.length > 0) {\n throw new AgentArmorModelError(\n 'CHECKSUM_REQUIRED',\n `A valid SHA-256 checksum is required for each model artifact; missing or invalid: ${invalid.join(', ')}`,\n );\n }\n}\n\n/**\n * Whether a failed cache check means \"download again\": a required file is\n * missing or does not match its digest. Any other error (a bad checksum\n * config, an unreadable cache) would fail the same way after a download.\n */\nfunction isCacheMiss(err: unknown): boolean {\n if (err instanceof AgentArmorModelError) {\n return err.code === 'MODEL_NOT_FOUND' || err.code === 'CHECKSUM_MISMATCH';\n }\n return (err as NodeJS.ErrnoException | undefined)?.code === 'ENOENT';\n}\n\n/** Verify pinned SHA-256 digests for all required artifacts in a complete directory. */\nexport async function verifyRequiredModelChecksums(\n dir: string,\n checksums: ModelArtifactChecksums = REQUIRED_MODEL_CHECKSUMS,\n): Promise<void> {\n assertModelChecksums(checksums);\n for (const file of REQUIRED_MODEL_FILES) {\n const path = join(dir, file);\n if (!(await verifyChecksum(path, checksums[file]))) {\n throw new AgentArmorModelError(\n 'CHECKSUM_MISMATCH',\n `Required model file checksum verification failed for ${path}`,\n );\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 // A bad checksum config would fail again after every download (#359).\n assertModelChecksums(config.modelChecksums);\n\n const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;\n\n if (modelDir) {\n await validateModelDir(modelDir, config.modelChecksums);\n return artifactsFrom(modelDir);\n }\n\n // Keep custom model sources/checksums out of the shared pinned-release cache.\n // Otherwise one caller can overwrite or invalidate artifacts another caller\n // expects to match the package-pinned digests.\n const cacheDir = getModelCacheDir(config);\n await mkdir(cacheDir, { recursive: true });\n\n // Check if a valid cached model exists\n try {\n await validateModelDir(cacheDir, config.modelChecksums);\n return artifactsFrom(cacheDir);\n } catch (err) {\n if (!isCacheMiss(err)) throw err;\n // Not cached — download\n }\n\n await downloadWithLock(cacheDir, config);\n return artifactsFrom(cacheDir);\n}\n\nexport function getModelCacheDir(config: MLConfigLike): string {\n if (!config.modelChecksums && !config.modelUrl) return getDefaultCacheDir();\n\n const source = config.modelUrl ?? `https://huggingface.co/${HF_REPO_ID}/resolve/${HF_REVISION}`;\n const checksumIdentity = REQUIRED_MODEL_FILES.map(\n (file) => `${file}:${config.modelChecksums?.[file] ?? REQUIRED_MODEL_CHECKSUMS[file]}`,\n ).join('\\n');\n const key = createHash('sha256').update(`${source}\\n${checksumIdentity}`).digest('hex');\n return join(getDefaultCacheDir(), 'custom', key);\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(cacheDir: string, config: MLConfigLike): Promise<void> {\n const lockPath = join(cacheDir, LOCK_FILENAME);\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, config.modelChecksums);\n return;\n } catch (validateErr) {\n if (!isCacheMiss(validateErr)) throw validateErr;\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 every required artifact before treating the cache as usable.\n try {\n await validateModelDir(cacheDir, config.modelChecksums);\n } catch (err) {\n // Clean up the bad download\n for (const file of REQUIRED_MODEL_FILES) {\n await unlink(join(cacheDir, file)).catch(() => {});\n }\n throw err;\n }\n } finally {\n await lockFd.close();\n await unlink(lockPath).catch(() => {});\n }\n}\n\n/**\n * Delete the files this package writes to a cache directory, including the\n * caches for custom model sources. `AGENTARMOR_CACHE_DIR` can name a folder that\n * holds other data, so anything else stays. A folder is removed only if empty.\n */\nexport async function clearCache(cacheDir: string): Promise<void> {\n const customDir = join(cacheDir, 'custom');\n // lstat, so that a symlinked `custom` folder is not followed.\n const isCustomDir = await lstat(customDir).then(\n (s) => s.isDirectory(),\n () => false,\n );\n if (isCustomDir) {\n for (const entry of await readdir(customDir, { withFileTypes: true })) {\n if (entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)) {\n await removeCacheFiles(join(customDir, entry.name));\n }\n }\n await removeIfEmpty(customDir);\n }\n await removeCacheFiles(cacheDir);\n}\n\nasync function removeCacheFiles(dir: string): Promise<void> {\n const files = [...REQUIRED_MODEL_FILES, ...OPTIONAL_MODEL_FILES];\n const names = [...files, ...files.map((file) => `${file}.tmp`), LOCK_FILENAME];\n // Try every file before reporting the first one that could not be deleted.\n let failure: unknown;\n for (const name of names) {\n await unlink(join(dir, name))\n .catch(ignoreCodes('ENOENT'))\n .catch((err: unknown) => {\n failure ??= err;\n });\n }\n if (failure) throw failure;\n await removeIfEmpty(dir);\n}\n\nasync function removeIfEmpty(dir: string): Promise<void> {\n // ENOTDIR: the path is a symlink to a folder. Leave the link in place.\n await rmdir(dir).catch(ignoreCodes('ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'));\n}\n\nfunction ignoreCodes(...codes: string[]) {\n return (err: NodeJS.ErrnoException): void => {\n if (!codes.includes(err.code ?? '')) throw err;\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/${HF_REVISION}`;\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 // Remove a leftover temp file (or a symlink planted there) so that the\n // exclusive create below writes only to a new file.\n await unlink(tmpPath).catch(() => {});\n\n await new Promise<void>((resolve, reject) => {\n let activeRequest: ReturnType<typeof httpsGet> | undefined;\n const timer = setTimeout(() => {\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_TIMEOUT',\n `Download of ${filename} timed out after ${timeoutMs}ms`,\n ),\n );\n activeRequest?.destroy();\n }, timeoutMs);\n\n const makeRequest = (requestUrl: string, redirectCount = 0): void => {\n if (redirectCount > 5) {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError('DOWNLOAD_FAILED', `Too many redirects for ${filename}`),\n );\n return;\n }\n\n const req = httpsGet(requestUrl, (res) => {\n if (\n res.statusCode &&\n res.statusCode >= 300 &&\n res.statusCode < 400 &&\n res.headers.location\n ) {\n // Hugging Face redirects a branch download to a relative path\n // (/api/resolve-cache/...), so resolve it against the current URL.\n res.resume();\n // This runs outside the promise executor, so a throw here would\n // end the host process instead of rejecting.\n try {\n const next = new URL(res.headers.location, requestUrl);\n if (next.protocol !== 'https:') {\n throw new Error(`Redirect to ${next.protocol} is not allowed`);\n }\n makeRequest(next.toString(), redirectCount + 1);\n } catch (redirectErr) {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Invalid redirect while downloading ${filename}`,\n redirectErr as Error,\n ),\n );\n }\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, { flags: 'wx' });\n pipeline(res, ws)\n .then(() => {\n clearTimeout(timer);\n resolve();\n })\n .catch((pipeErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Failed to write ${filename}`,\n pipeErr,\n ),\n );\n });\n });\n\n activeRequest = req;\n\n req.on('error', (reqErr) => {\n clearTimeout(timer);\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Network error downloading ${filename}`,\n reqErr,\n ),\n );\n });\n };\n\n try {\n makeRequest(url);\n } catch (urlErr) {\n // https.get throws at once for an http or malformed address.\n clearTimeout(timer);\n reject(\n new AgentArmorModelError(\n 'DOWNLOAD_FAILED',\n `Invalid download address for ${filename}`,\n urlErr as Error,\n ),\n );\n }\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.toLowerCase();\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';\nimport type { ModelArtifactChecksums } from './constants';\n\nexport { AgentArmorModelError } from './errors';\nexport { MLDetector } from './ml-detector';\nexport type { ModelArtifacts } from './model-manager';\nexport type { ModelArtifactChecksums } from './constants';\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 modelChecksums?: ModelArtifactChecksums;\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;AAOnB,IAAM,cAAc;AACpB,IAAM,iBAAiB;AAEvB,IAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,uBAAuB,CAAC,yBAAyB,yBAAyB;AAEhF,IAAM,iBAAiB;AAGvB,IAAM,2BAET;AAAA,EACF,wBAAwB;AAAA,EACxB,kBAAkB;AAAA,EAClB,kBAAkB;AACpB;AAKO,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,YAAY,OAAO,IAAI,CAAC,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;AAK9E,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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A,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,YAAM,OAAO,QAAQ;AAAA,IACvB,QAAQ;AAEN;AAAA,IACF;AAGA,QAAI;AACF,YAAM,WAAW,MAAM,KAAK,QAAQ;AACpC,YAAM,UAAU,KAAK,IAAI,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;;;ACtgBA,eAAsB,iBAAiB,UAUf;AACtB,QAAM,YAAY,MAAM,aAAa,QAAQ;AAC7C,SAAO,WAAW,OAAO,SAAS;AACpC;","names":["join","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.11",
|
|
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",
|