@stylusnexus/agentarmor-ml 0.1.9 → 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/LICENSE +21 -0
- package/README.md +43 -3
- package/dist/cli.js +134 -22
- package/dist/index.d.mts +7 -2
- package/dist/index.d.ts +7 -2
- package/dist/index.js +104 -22
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +105 -23
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stylus Nexus Holdings LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
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
|
|
|
@@ -48,7 +48,7 @@ Subsequent runs load from cache with no network calls.
|
|
|
48
48
|
const armor = await AgentArmor.create({
|
|
49
49
|
ml: {
|
|
50
50
|
enabled: true,
|
|
51
|
-
// Point to a local
|
|
51
|
+
// Point to the pinned model release in a local directory (skips download)
|
|
52
52
|
modelDir: './models/agentarmor',
|
|
53
53
|
// Behavior when model is unavailable
|
|
54
54
|
onUnavailable: 'warn-and-skip', // 'throw' | 'warn-and-skip' | 'silent-skip'
|
|
@@ -64,6 +64,40 @@ const armor = await AgentArmor.create({
|
|
|
64
64
|
});
|
|
65
65
|
```
|
|
66
66
|
|
|
67
|
+
`modelDir` is checked against the package's pinned SHA-256 digests. For a custom or retrained model, provide all three artifact checksums:
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
const armor = await AgentArmor.create({
|
|
71
|
+
ml: {
|
|
72
|
+
enabled: true,
|
|
73
|
+
modelDir: './models/custom',
|
|
74
|
+
modelChecksums: {
|
|
75
|
+
'model_quantized.onnx': '<64-character SHA-256 hex>',
|
|
76
|
+
'tokenizer.json': '<64-character SHA-256 hex>',
|
|
77
|
+
'label_map.json': '<64-character SHA-256 hex>',
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
```
|
|
82
|
+
|
|
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
|
+
|
|
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
|
+
|
|
67
101
|
## CLI
|
|
68
102
|
|
|
69
103
|
Pre-download the model or manage the cache:
|
|
@@ -80,9 +114,15 @@ agentarmor-ml cache-info
|
|
|
80
114
|
agentarmor-ml clear-cache
|
|
81
115
|
```
|
|
82
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
|
+
|
|
83
121
|
## Inference Details
|
|
84
122
|
|
|
85
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.
|
|
124
|
+
- Caps text passed into the native tokenizer at 16,384 UTF-16 code units to bound work on very long or unbroken input.
|
|
125
|
+
- Verifies SHA-256 checksums for the ONNX model, tokenizer and label map on download and whenever it reuses the cache. Update all three pinned digests alongside a model release.
|
|
86
126
|
- If most of an input's tokens are unknown to the tokenizer, the ML result is dropped and the pattern detectors carry the scan. The scan result lists it in `stats.detectorsSkipped`, and `on.warn` fires once
|
|
87
127
|
- Runs ONNX inference with INT8 quantization via `onnxruntime-node`
|
|
88
128
|
- Applies sigmoid on logits with strictness-based thresholds: `strict=0.3`, `balanced=0.5`, `permissive=0.7`
|
|
@@ -92,7 +132,7 @@ agentarmor-ml clear-cache
|
|
|
92
132
|
|
|
93
133
|
Treat the classifier as a second opinion for triage, not a gate. The regex result stays the thing that blocks content. Measured on 2026-10-08 on the shipped INT8 model (see the [main README](https://github.com/stylusnexus/agent-armor#how-well-it-works) for the full table):
|
|
94
134
|
|
|
95
|
-
- **False flags on real documents.** The model in `0.1.7` flags 57% of 1,000 real READMEs, docs, policies, agent files and templates from 215 public repositories at the default threshold (the first model, 35%). The retrained model in
|
|
135
|
+
- **False flags on real documents.** The model in `0.1.7` flags 57% of 1,000 real READMEs, docs, policies, agent files and templates from 215 public repositories at the default threshold (the first model, 35%). The retrained model in `0.1.8` flags 0.3% of them (3 of 1,000; the plausible range is 0.1% to 0.9%) and 9 of 339 short NotInject prompts, and catches 95 of 110 held-out attacks at a 1% false-flag rate. Those 1,000 documents are the set the retrain was built to fix, so treat 0.3% as a tuned result, not a fresh test; 90 of them share 30% or more of their wording with training text, and none were read one by one. The 110 held-out attacks have been reused across seven training runs, and the gain over the previous retrain is in false flags, not detection (84 vs 87 of 110 at the default threshold, not significantly different). A fresh test set is tracked in [#298](https://github.com/stylusnexus/agent-armor/issues/298). If you are on `0.1.7`, use it on short text such as tool outputs and prompts, not on long documents.
|
|
96
136
|
- **Languages.** English and Chinese only. In probes, "ignore all previous instructions" in Spanish, German and Russian was not flagged.
|
|
97
137
|
- **Long text.** The model reads at most 512 tokens (about 2,000 characters). An attack after about 600 tokens is missed, so split long documents into chunks ([#274](https://github.com/stylusnexus/agent-armor/issues/274)). Detection is lower toward the end of the window.
|
|
98
138
|
- **The label is a hint.** It often names a different trap type than a person would.
|
package/dist/cli.js
CHANGED
|
@@ -20,6 +20,11 @@ var REQUIRED_MODEL_FILES = [
|
|
|
20
20
|
];
|
|
21
21
|
var OPTIONAL_MODEL_FILES = ["tokenizer_config.json", "special_tokens_map.json"];
|
|
22
22
|
var MODEL_CHECKSUM = "17a4ae95494348929833a5ef8de8007c82d84e4b9c8bf4c53d4530688aec03a0";
|
|
23
|
+
var REQUIRED_MODEL_CHECKSUMS = {
|
|
24
|
+
"model_quantized.onnx": MODEL_CHECKSUM,
|
|
25
|
+
"tokenizer.json": "2b37df34524d914c6f15ddccdb324c98d43358d5f68a52758fcc87721c3dd16d",
|
|
26
|
+
"label_map.json": "a4de5af7e74d57145f719c1ed7694943a1e6e4890387216acaa3e9c25c7ac574"
|
|
27
|
+
};
|
|
23
28
|
var LABELS = [
|
|
24
29
|
"hidden-html",
|
|
25
30
|
"metadata-injection",
|
|
@@ -73,6 +78,7 @@ var AgentArmorModelError = class extends Error {
|
|
|
73
78
|
};
|
|
74
79
|
|
|
75
80
|
// src/model-manager.ts
|
|
81
|
+
var LOCK_FILENAME = "model.onnx.lock";
|
|
76
82
|
function artifactsFrom(dir) {
|
|
77
83
|
return {
|
|
78
84
|
modelPath: (0, import_path2.join)(dir, MODEL_FILENAME),
|
|
@@ -81,7 +87,7 @@ function artifactsFrom(dir) {
|
|
|
81
87
|
modelDir: dir
|
|
82
88
|
};
|
|
83
89
|
}
|
|
84
|
-
async function validateModelDir(dir) {
|
|
90
|
+
async function validateModelDir(dir, checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
85
91
|
const missing = [];
|
|
86
92
|
for (const file of REQUIRED_MODEL_FILES) {
|
|
87
93
|
try {
|
|
@@ -96,25 +102,67 @@ async function validateModelDir(dir) {
|
|
|
96
102
|
`Missing required model files in ${dir}: ${missing.join(", ")}. Required files: ${REQUIRED_MODEL_FILES.join(", ")}`
|
|
97
103
|
);
|
|
98
104
|
}
|
|
105
|
+
await verifyRequiredModelChecksums(dir, checksums);
|
|
106
|
+
}
|
|
107
|
+
function assertModelChecksums(checksums = REQUIRED_MODEL_CHECKSUMS) {
|
|
108
|
+
const invalid = REQUIRED_MODEL_FILES.filter(
|
|
109
|
+
(file) => !/^[a-f0-9]{64}$/i.test(checksums?.[file] ?? "")
|
|
110
|
+
);
|
|
111
|
+
if (invalid.length > 0) {
|
|
112
|
+
throw new AgentArmorModelError(
|
|
113
|
+
"CHECKSUM_REQUIRED",
|
|
114
|
+
`A valid SHA-256 checksum is required for each model artifact; missing or invalid: ${invalid.join(", ")}`
|
|
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);
|
|
126
|
+
for (const file of REQUIRED_MODEL_FILES) {
|
|
127
|
+
const path = (0, import_path2.join)(dir, file);
|
|
128
|
+
if (!await verifyChecksum(path, checksums[file])) {
|
|
129
|
+
throw new AgentArmorModelError(
|
|
130
|
+
"CHECKSUM_MISMATCH",
|
|
131
|
+
`Required model file checksum verification failed for ${path}`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
99
135
|
}
|
|
100
136
|
async function resolveModel(config = {}) {
|
|
137
|
+
assertModelChecksums(config.modelChecksums);
|
|
101
138
|
const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;
|
|
102
139
|
if (modelDir) {
|
|
103
|
-
await validateModelDir(modelDir);
|
|
140
|
+
await validateModelDir(modelDir, config.modelChecksums);
|
|
104
141
|
return artifactsFrom(modelDir);
|
|
105
142
|
}
|
|
106
|
-
const cacheDir =
|
|
143
|
+
const cacheDir = getModelCacheDir(config);
|
|
107
144
|
await (0, import_promises.mkdir)(cacheDir, { recursive: true });
|
|
108
145
|
try {
|
|
109
|
-
await validateModelDir(cacheDir);
|
|
146
|
+
await validateModelDir(cacheDir, config.modelChecksums);
|
|
110
147
|
return artifactsFrom(cacheDir);
|
|
111
|
-
} catch {
|
|
148
|
+
} catch (err) {
|
|
149
|
+
if (!isCacheMiss(err)) throw err;
|
|
112
150
|
}
|
|
113
151
|
await downloadWithLock(cacheDir, config);
|
|
114
152
|
return artifactsFrom(cacheDir);
|
|
115
153
|
}
|
|
154
|
+
function getModelCacheDir(config) {
|
|
155
|
+
if (!config.modelChecksums && !config.modelUrl) return getDefaultCacheDir();
|
|
156
|
+
const source = config.modelUrl ?? `https://huggingface.co/${HF_REPO_ID}/resolve/${HF_REVISION}`;
|
|
157
|
+
const checksumIdentity = REQUIRED_MODEL_FILES.map(
|
|
158
|
+
(file) => `${file}:${config.modelChecksums?.[file] ?? REQUIRED_MODEL_CHECKSUMS[file]}`
|
|
159
|
+
).join("\n");
|
|
160
|
+
const key = (0, import_crypto.createHash)("sha256").update(`${source}
|
|
161
|
+
${checksumIdentity}`).digest("hex");
|
|
162
|
+
return (0, import_path2.join)(getDefaultCacheDir(), "custom", key);
|
|
163
|
+
}
|
|
116
164
|
async function downloadWithLock(cacheDir, config) {
|
|
117
|
-
const lockPath = (0, import_path2.join)(cacheDir,
|
|
165
|
+
const lockPath = (0, import_path2.join)(cacheDir, LOCK_FILENAME);
|
|
118
166
|
let lockFd;
|
|
119
167
|
try {
|
|
120
168
|
lockFd = await (0, import_promises.open)(lockPath, "wx");
|
|
@@ -122,9 +170,10 @@ async function downloadWithLock(cacheDir, config) {
|
|
|
122
170
|
if (err.code === "EEXIST") {
|
|
123
171
|
await waitForLock(lockPath, config);
|
|
124
172
|
try {
|
|
125
|
-
await validateModelDir(cacheDir);
|
|
173
|
+
await validateModelDir(cacheDir, config.modelChecksums);
|
|
126
174
|
return;
|
|
127
|
-
} catch {
|
|
175
|
+
} catch (validateErr) {
|
|
176
|
+
if (!isCacheMiss(validateErr)) throw validateErr;
|
|
128
177
|
lockFd = await (0, import_promises.open)(lockPath, "wx");
|
|
129
178
|
}
|
|
130
179
|
} else {
|
|
@@ -138,17 +187,14 @@ async function downloadWithLock(cacheDir, config) {
|
|
|
138
187
|
for (const file of OPTIONAL_MODEL_FILES) {
|
|
139
188
|
await downloadFile(file, cacheDir, config, true);
|
|
140
189
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
190
|
+
try {
|
|
191
|
+
await validateModelDir(cacheDir, config.modelChecksums);
|
|
192
|
+
} catch (err) {
|
|
144
193
|
for (const file of REQUIRED_MODEL_FILES) {
|
|
145
194
|
await (0, import_promises.unlink)((0, import_path2.join)(cacheDir, file)).catch(() => {
|
|
146
195
|
});
|
|
147
196
|
}
|
|
148
|
-
throw
|
|
149
|
-
"CHECKSUM_MISMATCH",
|
|
150
|
-
`Model file checksum verification failed for ${modelPath}`
|
|
151
|
-
);
|
|
197
|
+
throw err;
|
|
152
198
|
}
|
|
153
199
|
} finally {
|
|
154
200
|
await lockFd.close();
|
|
@@ -156,6 +202,42 @@ async function downloadWithLock(cacheDir, config) {
|
|
|
156
202
|
});
|
|
157
203
|
}
|
|
158
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
|
+
}
|
|
159
241
|
async function downloadFile(filename, destDir, config, optional) {
|
|
160
242
|
const retries = config.download?.retries ?? DEFAULT_RETRIES;
|
|
161
243
|
const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
@@ -171,7 +253,10 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
171
253
|
const tmpPath = `${destPath}.tmp`;
|
|
172
254
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
173
255
|
try {
|
|
256
|
+
await (0, import_promises.unlink)(tmpPath).catch(() => {
|
|
257
|
+
});
|
|
174
258
|
await new Promise((resolve2, reject) => {
|
|
259
|
+
let activeRequest;
|
|
175
260
|
const timer = setTimeout(() => {
|
|
176
261
|
reject(
|
|
177
262
|
new AgentArmorModelError(
|
|
@@ -179,6 +264,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
179
264
|
`Download of ${filename} timed out after ${timeoutMs}ms`
|
|
180
265
|
)
|
|
181
266
|
);
|
|
267
|
+
activeRequest?.destroy();
|
|
182
268
|
}, timeoutMs);
|
|
183
269
|
const makeRequest = (requestUrl, redirectCount = 0) => {
|
|
184
270
|
if (redirectCount > 5) {
|
|
@@ -188,11 +274,25 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
188
274
|
);
|
|
189
275
|
return;
|
|
190
276
|
}
|
|
191
|
-
const
|
|
192
|
-
const req = protocol(requestUrl, (res) => {
|
|
277
|
+
const req = (0, import_https.get)(requestUrl, (res) => {
|
|
193
278
|
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
194
279
|
res.resume();
|
|
195
|
-
|
|
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
|
+
}
|
|
196
296
|
return;
|
|
197
297
|
}
|
|
198
298
|
if (res.statusCode === 404 && optional) {
|
|
@@ -220,7 +320,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
220
320
|
onProgress(receivedBytes, totalBytes);
|
|
221
321
|
});
|
|
222
322
|
}
|
|
223
|
-
const ws = (0, import_fs.createWriteStream)(tmpPath);
|
|
323
|
+
const ws = (0, import_fs.createWriteStream)(tmpPath, { flags: "wx" });
|
|
224
324
|
(0, import_promises2.pipeline)(res, ws).then(() => {
|
|
225
325
|
clearTimeout(timer);
|
|
226
326
|
resolve2();
|
|
@@ -235,6 +335,7 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
235
335
|
);
|
|
236
336
|
});
|
|
237
337
|
});
|
|
338
|
+
activeRequest = req;
|
|
238
339
|
req.on("error", (reqErr) => {
|
|
239
340
|
clearTimeout(timer);
|
|
240
341
|
reject(
|
|
@@ -246,7 +347,18 @@ async function downloadFile(filename, destDir, config, optional) {
|
|
|
246
347
|
);
|
|
247
348
|
});
|
|
248
349
|
};
|
|
249
|
-
|
|
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
|
+
}
|
|
250
362
|
});
|
|
251
363
|
await (0, import_promises.rename)(tmpPath, destPath);
|
|
252
364
|
return;
|
|
@@ -278,7 +390,7 @@ async function verifyChecksum(filePath, expected = MODEL_CHECKSUM) {
|
|
|
278
390
|
hash.update(chunk);
|
|
279
391
|
}
|
|
280
392
|
const digest = hash.digest("hex");
|
|
281
|
-
return digest === expected;
|
|
393
|
+
return digest === expected.toLowerCase();
|
|
282
394
|
}
|
|
283
395
|
async function waitForLock(lockPath, config) {
|
|
284
396
|
const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
@@ -387,7 +499,7 @@ Download failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
|
387
499
|
async function cmdClearCache() {
|
|
388
500
|
const cacheDir = getDefaultCacheDir();
|
|
389
501
|
try {
|
|
390
|
-
await (
|
|
502
|
+
await clearCache(cacheDir);
|
|
391
503
|
console.log(`Cache cleared: ${cacheDir}`);
|
|
392
504
|
} catch (err) {
|
|
393
505
|
console.error(`Failed to clear cache: ${err instanceof Error ? err.message : String(err)}`);
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
declare const REQUIRED_MODEL_FILES: readonly ["model_quantized.onnx", "tokenizer.json", "label_map.json"];
|
|
2
|
+
/** SHA-256 digests for every required artifact, used to pin custom model directories. */
|
|
3
|
+
type ModelArtifactChecksums = Record<(typeof REQUIRED_MODEL_FILES)[number], string>;
|
|
4
|
+
|
|
1
5
|
/** Resolved on-disk paths to the ONNX model and its supporting files. */
|
|
2
6
|
interface ModelArtifacts {
|
|
3
7
|
/** Path to `model_quantized.onnx`. */
|
|
@@ -72,7 +76,7 @@ declare class MLDetector implements Detector {
|
|
|
72
76
|
}
|
|
73
77
|
|
|
74
78
|
/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */
|
|
75
|
-
type ModelErrorCode = 'MODEL_NOT_FOUND' | 'CHECKSUM_MISMATCH' | 'DOWNLOAD_FAILED' | 'DOWNLOAD_TIMEOUT' | 'DISK_FULL' | 'LOCK_TIMEOUT' | 'UNSUPPORTED_TOKENIZER' | 'TOKENIZER_LOAD_FAILED';
|
|
79
|
+
type ModelErrorCode = 'MODEL_NOT_FOUND' | 'CHECKSUM_MISMATCH' | 'CHECKSUM_REQUIRED' | 'DOWNLOAD_FAILED' | 'DOWNLOAD_TIMEOUT' | 'DISK_FULL' | 'LOCK_TIMEOUT' | 'UNSUPPORTED_TOKENIZER' | 'TOKENIZER_LOAD_FAILED';
|
|
76
80
|
/** Thrown when the ML model can't be resolved (missing, corrupt, or unreachable). */
|
|
77
81
|
declare class AgentArmorModelError extends Error {
|
|
78
82
|
/** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */
|
|
@@ -88,6 +92,7 @@ declare class AgentArmorModelError extends Error {
|
|
|
88
92
|
*/
|
|
89
93
|
declare function createMLDetector(mlConfig: {
|
|
90
94
|
modelDir?: string;
|
|
95
|
+
modelChecksums?: ModelArtifactChecksums;
|
|
91
96
|
enabled?: boolean;
|
|
92
97
|
modelUrl?: string;
|
|
93
98
|
download?: {
|
|
@@ -97,4 +102,4 @@ declare function createMLDetector(mlConfig: {
|
|
|
97
102
|
};
|
|
98
103
|
}): Promise<MLDetector>;
|
|
99
104
|
|
|
100
|
-
export { AgentArmorModelError, MLDetector, type ModelArtifacts, createMLDetector };
|
|
105
|
+
export { AgentArmorModelError, MLDetector, type ModelArtifactChecksums, type ModelArtifacts, createMLDetector };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
declare const REQUIRED_MODEL_FILES: readonly ["model_quantized.onnx", "tokenizer.json", "label_map.json"];
|
|
2
|
+
/** SHA-256 digests for every required artifact, used to pin custom model directories. */
|
|
3
|
+
type ModelArtifactChecksums = Record<(typeof REQUIRED_MODEL_FILES)[number], string>;
|
|
4
|
+
|
|
1
5
|
/** Resolved on-disk paths to the ONNX model and its supporting files. */
|
|
2
6
|
interface ModelArtifacts {
|
|
3
7
|
/** Path to `model_quantized.onnx`. */
|
|
@@ -72,7 +76,7 @@ declare class MLDetector implements Detector {
|
|
|
72
76
|
}
|
|
73
77
|
|
|
74
78
|
/** Error codes {@link AgentArmorModelError} can carry when model resolution fails. */
|
|
75
|
-
type ModelErrorCode = 'MODEL_NOT_FOUND' | 'CHECKSUM_MISMATCH' | 'DOWNLOAD_FAILED' | 'DOWNLOAD_TIMEOUT' | 'DISK_FULL' | 'LOCK_TIMEOUT' | 'UNSUPPORTED_TOKENIZER' | 'TOKENIZER_LOAD_FAILED';
|
|
79
|
+
type ModelErrorCode = 'MODEL_NOT_FOUND' | 'CHECKSUM_MISMATCH' | 'CHECKSUM_REQUIRED' | 'DOWNLOAD_FAILED' | 'DOWNLOAD_TIMEOUT' | 'DISK_FULL' | 'LOCK_TIMEOUT' | 'UNSUPPORTED_TOKENIZER' | 'TOKENIZER_LOAD_FAILED';
|
|
76
80
|
/** Thrown when the ML model can't be resolved (missing, corrupt, or unreachable). */
|
|
77
81
|
declare class AgentArmorModelError extends Error {
|
|
78
82
|
/** Which failure mode this is — use this to branch on recoverable vs. fatal cases. */
|
|
@@ -88,6 +92,7 @@ declare class AgentArmorModelError extends Error {
|
|
|
88
92
|
*/
|
|
89
93
|
declare function createMLDetector(mlConfig: {
|
|
90
94
|
modelDir?: string;
|
|
95
|
+
modelChecksums?: ModelArtifactChecksums;
|
|
91
96
|
enabled?: boolean;
|
|
92
97
|
modelUrl?: string;
|
|
93
98
|
download?: {
|
|
@@ -97,4 +102,4 @@ declare function createMLDetector(mlConfig: {
|
|
|
97
102
|
};
|
|
98
103
|
}): Promise<MLDetector>;
|
|
99
104
|
|
|
100
|
-
export { AgentArmorModelError, MLDetector, type ModelArtifacts, createMLDetector };
|
|
105
|
+
export { AgentArmorModelError, MLDetector, type ModelArtifactChecksums, type ModelArtifacts, createMLDetector };
|