@stylusnexus/agentarmor-ml 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -0
- package/dist/cli.js +404 -0
- package/dist/index.d.mts +72 -0
- package/dist/index.d.ts +72 -0
- package/dist/index.js +529 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +490 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +47 -0
package/README.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# @stylusnexus/agentarmor-ml
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@stylusnexus/agentarmor-ml)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
|
|
6
|
+
ML classifier add-on for [Agent Armor](https://github.com/stylusnexus/agent-armor). Runs a DeBERTa-v3-small ONNX model locally for deeper agent trap detection that catches threats regex patterns might miss.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @stylusnexus/agentarmor @stylusnexus/agentarmor-ml
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
```typescript
|
|
17
|
+
import { AgentArmor } from '@stylusnexus/agentarmor';
|
|
18
|
+
|
|
19
|
+
const armor = await AgentArmor.create({
|
|
20
|
+
ml: { enabled: true },
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const result = await armor.scan(content);
|
|
24
|
+
|
|
25
|
+
// ML-detected threats have source: 'ml'
|
|
26
|
+
result.threats.filter(t => t.source === 'ml');
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## How It Works
|
|
30
|
+
|
|
31
|
+
On first use, the model (~140MB quantized ONNX) is downloaded from HuggingFace and cached locally:
|
|
32
|
+
|
|
33
|
+
- **macOS:** `~/Library/Caches/agentarmor/v1/`
|
|
34
|
+
- **Linux:** `~/.cache/agentarmor/v1/`
|
|
35
|
+
- **Custom:** Set `AGENTARMOR_CACHE_DIR` or pass `ml.modelDir` in config
|
|
36
|
+
|
|
37
|
+
Subsequent runs load from cache with no network calls.
|
|
38
|
+
|
|
39
|
+
## Configuration
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
const armor = await AgentArmor.create({
|
|
43
|
+
ml: {
|
|
44
|
+
enabled: true,
|
|
45
|
+
// Point to a local model directory (skips download)
|
|
46
|
+
modelDir: './models/agentarmor',
|
|
47
|
+
// Behavior when model is unavailable
|
|
48
|
+
onUnavailable: 'warn-and-skip', // 'throw' | 'warn-and-skip' | 'silent-skip'
|
|
49
|
+
// Download options
|
|
50
|
+
download: {
|
|
51
|
+
timeoutMs: 120_000,
|
|
52
|
+
retries: 2,
|
|
53
|
+
onProgress: (received, total) => {
|
|
54
|
+
console.log(`${Math.round(received / total * 100)}%`);
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## CLI
|
|
62
|
+
|
|
63
|
+
Pre-download the model or manage the cache:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
# Download model to cache (or custom directory)
|
|
67
|
+
agentarmor-ml download
|
|
68
|
+
agentarmor-ml download --dir ./models
|
|
69
|
+
|
|
70
|
+
# Show cache location and file sizes
|
|
71
|
+
agentarmor-ml cache-info
|
|
72
|
+
|
|
73
|
+
# Remove cached model
|
|
74
|
+
agentarmor-ml clear-cache
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Inference Details
|
|
78
|
+
|
|
79
|
+
- Tokenizes input to 512 tokens (WordPiece)
|
|
80
|
+
- Runs ONNX inference with INT8 quantization via `onnxruntime-node`
|
|
81
|
+
- Applies sigmoid on logits with strictness-based thresholds: `strict=0.3`, `balanced=0.5`, `permissive=0.7`
|
|
82
|
+
- `scan()` (sync) returns empty — ML inference is async-only via `scanAsync()`
|
|
83
|
+
|
|
84
|
+
## Deployment Notes
|
|
85
|
+
|
|
86
|
+
- **AWS Lambda:** 140MB model + ~40MB onnxruntime = ~180MB, fits the 250MB limit but is tight. Use `modelDir` to bundle the model in your deployment package.
|
|
87
|
+
- **Vercel Edge:** Not supported (ONNX runtime requires Node.js native bindings).
|
|
88
|
+
|
|
89
|
+
## Requirements
|
|
90
|
+
|
|
91
|
+
- Node.js >= 18
|
|
92
|
+
- Peer dependency: `@stylusnexus/agentarmor >= 0.2.0`
|
|
93
|
+
|
|
94
|
+
## License
|
|
95
|
+
|
|
96
|
+
MIT
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/cli.ts
|
|
5
|
+
var import_promises3 = require("fs/promises");
|
|
6
|
+
var import_path3 = require("path");
|
|
7
|
+
var import_fs2 = require("fs");
|
|
8
|
+
|
|
9
|
+
// src/constants.ts
|
|
10
|
+
var import_os = require("os");
|
|
11
|
+
var import_path = require("path");
|
|
12
|
+
var MODEL_VERSION = "v1";
|
|
13
|
+
var HF_REPO_ID = "stylusnexus/agent-armor-classifier";
|
|
14
|
+
var MODEL_FILENAME = "model_quantized.onnx";
|
|
15
|
+
var REQUIRED_MODEL_FILES = [
|
|
16
|
+
"model_quantized.onnx",
|
|
17
|
+
"tokenizer.json",
|
|
18
|
+
"label_map.json"
|
|
19
|
+
];
|
|
20
|
+
var OPTIONAL_MODEL_FILES = [
|
|
21
|
+
"tokenizer_config.json",
|
|
22
|
+
"special_tokens_map.json"
|
|
23
|
+
];
|
|
24
|
+
var MODEL_CHECKSUM = "PLACEHOLDER_UPDATE_AFTER_FIRST_PUBLISH";
|
|
25
|
+
var LABELS = [
|
|
26
|
+
"hidden-html",
|
|
27
|
+
"metadata-injection",
|
|
28
|
+
"dynamic-cloaking",
|
|
29
|
+
"syntactic-masking",
|
|
30
|
+
"embedded-jailbreak",
|
|
31
|
+
"data-exfiltration",
|
|
32
|
+
"sub-agent-spawning",
|
|
33
|
+
"rag-knowledge-poisoning",
|
|
34
|
+
"latent-memory-poisoning",
|
|
35
|
+
"contextual-learning-trap",
|
|
36
|
+
"biased-framing",
|
|
37
|
+
"oversight-evasion",
|
|
38
|
+
"persona-hyperstition",
|
|
39
|
+
"benign"
|
|
40
|
+
];
|
|
41
|
+
var LABEL_TO_INDEX = Object.fromEntries(
|
|
42
|
+
LABELS.map((label, i) => [label, i])
|
|
43
|
+
);
|
|
44
|
+
function getDefaultCacheDir() {
|
|
45
|
+
const envOverride = process.env.AGENTARMOR_CACHE_DIR;
|
|
46
|
+
if (envOverride) return envOverride;
|
|
47
|
+
const xdg = process.env.XDG_CACHE_HOME;
|
|
48
|
+
if (xdg) return (0, import_path.join)(xdg, "agentarmor", MODEL_VERSION);
|
|
49
|
+
if ((0, import_os.platform)() === "darwin") {
|
|
50
|
+
return (0, import_path.join)((0, import_os.homedir)(), "Library", "Caches", "agentarmor", MODEL_VERSION);
|
|
51
|
+
}
|
|
52
|
+
return (0, import_path.join)((0, import_os.homedir)(), ".cache", "agentarmor", MODEL_VERSION);
|
|
53
|
+
}
|
|
54
|
+
var DEFAULT_TIMEOUT_MS = 12e4;
|
|
55
|
+
var DEFAULT_RETRIES = 2;
|
|
56
|
+
|
|
57
|
+
// src/model-manager.ts
|
|
58
|
+
var import_crypto = require("crypto");
|
|
59
|
+
var import_fs = require("fs");
|
|
60
|
+
var import_promises = require("fs/promises");
|
|
61
|
+
var import_https = require("https");
|
|
62
|
+
var import_path2 = require("path");
|
|
63
|
+
var import_promises2 = require("stream/promises");
|
|
64
|
+
|
|
65
|
+
// src/errors.ts
|
|
66
|
+
var AgentArmorModelError = class extends Error {
|
|
67
|
+
code;
|
|
68
|
+
cause;
|
|
69
|
+
constructor(code, message, cause) {
|
|
70
|
+
super(message);
|
|
71
|
+
this.name = "AgentArmorModelError";
|
|
72
|
+
this.code = code;
|
|
73
|
+
this.cause = cause;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// src/model-manager.ts
|
|
78
|
+
function artifactsFrom(dir) {
|
|
79
|
+
return {
|
|
80
|
+
modelPath: (0, import_path2.join)(dir, MODEL_FILENAME),
|
|
81
|
+
tokenizerPath: (0, import_path2.join)(dir, "tokenizer.json"),
|
|
82
|
+
labelMapPath: (0, import_path2.join)(dir, "label_map.json"),
|
|
83
|
+
modelDir: dir
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
async function validateModelDir(dir) {
|
|
87
|
+
const missing = [];
|
|
88
|
+
for (const file of REQUIRED_MODEL_FILES) {
|
|
89
|
+
try {
|
|
90
|
+
await (0, import_promises.access)((0, import_path2.join)(dir, file));
|
|
91
|
+
} catch {
|
|
92
|
+
missing.push(file);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (missing.length > 0) {
|
|
96
|
+
throw new AgentArmorModelError(
|
|
97
|
+
"MODEL_NOT_FOUND",
|
|
98
|
+
`Missing required model files in ${dir}: ${missing.join(", ")}. Required files: ${REQUIRED_MODEL_FILES.join(", ")}`
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async function resolveModel(config = {}) {
|
|
103
|
+
const modelDir = config.modelDir || process.env.AGENTARMOR_MODEL_DIR;
|
|
104
|
+
if (modelDir) {
|
|
105
|
+
await validateModelDir(modelDir);
|
|
106
|
+
return artifactsFrom(modelDir);
|
|
107
|
+
}
|
|
108
|
+
const cacheDir = getDefaultCacheDir();
|
|
109
|
+
await (0, import_promises.mkdir)(cacheDir, { recursive: true });
|
|
110
|
+
try {
|
|
111
|
+
await validateModelDir(cacheDir);
|
|
112
|
+
return artifactsFrom(cacheDir);
|
|
113
|
+
} catch {
|
|
114
|
+
}
|
|
115
|
+
await downloadWithLock(cacheDir, config);
|
|
116
|
+
return artifactsFrom(cacheDir);
|
|
117
|
+
}
|
|
118
|
+
async function downloadWithLock(cacheDir, config) {
|
|
119
|
+
const lockPath = (0, import_path2.join)(cacheDir, "model.onnx.lock");
|
|
120
|
+
let lockFd;
|
|
121
|
+
try {
|
|
122
|
+
lockFd = await (0, import_promises.open)(lockPath, "wx");
|
|
123
|
+
} catch (err) {
|
|
124
|
+
if (err.code === "EEXIST") {
|
|
125
|
+
await waitForLock(lockPath, config);
|
|
126
|
+
try {
|
|
127
|
+
await validateModelDir(cacheDir);
|
|
128
|
+
return;
|
|
129
|
+
} catch {
|
|
130
|
+
lockFd = await (0, import_promises.open)(lockPath, "wx");
|
|
131
|
+
}
|
|
132
|
+
} else {
|
|
133
|
+
throw err;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
try {
|
|
137
|
+
for (const file of REQUIRED_MODEL_FILES) {
|
|
138
|
+
await downloadFile(file, cacheDir, config, false);
|
|
139
|
+
}
|
|
140
|
+
for (const file of OPTIONAL_MODEL_FILES) {
|
|
141
|
+
await downloadFile(file, cacheDir, config, true);
|
|
142
|
+
}
|
|
143
|
+
const modelPath = (0, import_path2.join)(cacheDir, MODEL_FILENAME);
|
|
144
|
+
const checksumOk = await verifyChecksum(modelPath);
|
|
145
|
+
if (!checksumOk) {
|
|
146
|
+
for (const file of REQUIRED_MODEL_FILES) {
|
|
147
|
+
await (0, import_promises.unlink)((0, import_path2.join)(cacheDir, file)).catch(() => {
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
throw new AgentArmorModelError(
|
|
151
|
+
"CHECKSUM_MISMATCH",
|
|
152
|
+
`Model file checksum verification failed for ${modelPath}`
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
} finally {
|
|
156
|
+
await lockFd.close();
|
|
157
|
+
await (0, import_promises.unlink)(lockPath).catch(() => {
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
async function downloadFile(filename, destDir, config, optional) {
|
|
162
|
+
const retries = config.download?.retries ?? DEFAULT_RETRIES;
|
|
163
|
+
const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
164
|
+
const onProgress = config.download?.onProgress;
|
|
165
|
+
let baseUrl;
|
|
166
|
+
if (config.modelUrl) {
|
|
167
|
+
baseUrl = config.modelUrl.replace(/\/$/, "");
|
|
168
|
+
} else {
|
|
169
|
+
baseUrl = `https://huggingface.co/${HF_REPO_ID}/resolve/main`;
|
|
170
|
+
}
|
|
171
|
+
const url = `${baseUrl}/${filename}`;
|
|
172
|
+
const destPath = (0, import_path2.join)(destDir, filename);
|
|
173
|
+
const tmpPath = `${destPath}.tmp`;
|
|
174
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
175
|
+
try {
|
|
176
|
+
await new Promise((resolve, reject) => {
|
|
177
|
+
const timer = setTimeout(() => {
|
|
178
|
+
reject(
|
|
179
|
+
new AgentArmorModelError(
|
|
180
|
+
"DOWNLOAD_TIMEOUT",
|
|
181
|
+
`Download of ${filename} timed out after ${timeoutMs}ms`
|
|
182
|
+
)
|
|
183
|
+
);
|
|
184
|
+
}, timeoutMs);
|
|
185
|
+
const makeRequest = (requestUrl, redirectCount = 0) => {
|
|
186
|
+
if (redirectCount > 5) {
|
|
187
|
+
clearTimeout(timer);
|
|
188
|
+
reject(new AgentArmorModelError("DOWNLOAD_FAILED", `Too many redirects for ${filename}`));
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const protocol = requestUrl.startsWith("https") ? import_https.get : import_https.get;
|
|
192
|
+
const req = protocol(requestUrl, (res) => {
|
|
193
|
+
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
194
|
+
makeRequest(res.headers.location, redirectCount + 1);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (res.statusCode === 404 && optional) {
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
res.resume();
|
|
200
|
+
resolve();
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
if (res.statusCode !== 200) {
|
|
204
|
+
clearTimeout(timer);
|
|
205
|
+
res.resume();
|
|
206
|
+
reject(
|
|
207
|
+
new AgentArmorModelError(
|
|
208
|
+
"DOWNLOAD_FAILED",
|
|
209
|
+
`Failed to download ${filename}: HTTP ${res.statusCode}`
|
|
210
|
+
)
|
|
211
|
+
);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const totalBytes = parseInt(res.headers["content-length"] || "0", 10);
|
|
215
|
+
let receivedBytes = 0;
|
|
216
|
+
if (onProgress) {
|
|
217
|
+
res.on("data", (chunk) => {
|
|
218
|
+
receivedBytes += chunk.length;
|
|
219
|
+
onProgress(receivedBytes, totalBytes);
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
const ws = (0, import_fs.createWriteStream)(tmpPath);
|
|
223
|
+
(0, import_promises2.pipeline)(res, ws).then(() => {
|
|
224
|
+
clearTimeout(timer);
|
|
225
|
+
resolve();
|
|
226
|
+
}).catch((pipeErr) => {
|
|
227
|
+
clearTimeout(timer);
|
|
228
|
+
reject(
|
|
229
|
+
new AgentArmorModelError("DOWNLOAD_FAILED", `Failed to write ${filename}`, pipeErr)
|
|
230
|
+
);
|
|
231
|
+
});
|
|
232
|
+
});
|
|
233
|
+
req.on("error", (reqErr) => {
|
|
234
|
+
clearTimeout(timer);
|
|
235
|
+
reject(
|
|
236
|
+
new AgentArmorModelError("DOWNLOAD_FAILED", `Network error downloading ${filename}`, reqErr)
|
|
237
|
+
);
|
|
238
|
+
});
|
|
239
|
+
};
|
|
240
|
+
makeRequest(url);
|
|
241
|
+
});
|
|
242
|
+
await (0, import_promises.rename)(tmpPath, destPath);
|
|
243
|
+
return;
|
|
244
|
+
} catch (err) {
|
|
245
|
+
await (0, import_promises.unlink)(tmpPath).catch(() => {
|
|
246
|
+
});
|
|
247
|
+
if (err instanceof AgentArmorModelError && err.code === "DOWNLOAD_TIMEOUT") {
|
|
248
|
+
throw err;
|
|
249
|
+
}
|
|
250
|
+
if (optional && err instanceof AgentArmorModelError && err.code === "DOWNLOAD_FAILED") {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (attempt < retries) {
|
|
254
|
+
const delay = 1e3 * Math.pow(2, attempt);
|
|
255
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
throw err;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
async function verifyChecksum(filePath) {
|
|
263
|
+
if (MODEL_CHECKSUM.startsWith("PLACEHOLDER")) {
|
|
264
|
+
return true;
|
|
265
|
+
}
|
|
266
|
+
const hash = (0, import_crypto.createHash)("sha256");
|
|
267
|
+
const stream = (0, import_fs.createReadStream)(filePath);
|
|
268
|
+
for await (const chunk of stream) {
|
|
269
|
+
hash.update(chunk);
|
|
270
|
+
}
|
|
271
|
+
const digest = hash.digest("hex");
|
|
272
|
+
return digest === MODEL_CHECKSUM;
|
|
273
|
+
}
|
|
274
|
+
async function waitForLock(lockPath, config) {
|
|
275
|
+
const timeoutMs = config.download?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
276
|
+
const pollInterval = 2e3;
|
|
277
|
+
const startTime = Date.now();
|
|
278
|
+
while (Date.now() - startTime < timeoutMs) {
|
|
279
|
+
try {
|
|
280
|
+
await (0, import_promises.access)(lockPath);
|
|
281
|
+
} catch {
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
const lockStat = await (0, import_promises.stat)(lockPath);
|
|
286
|
+
const lockAge = Date.now() - lockStat.mtimeMs;
|
|
287
|
+
if (lockAge > timeoutMs) {
|
|
288
|
+
await (0, import_promises.unlink)(lockPath).catch(() => {
|
|
289
|
+
});
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
} catch {
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
await new Promise((r) => setTimeout(r, pollInterval));
|
|
296
|
+
}
|
|
297
|
+
await (0, import_promises.unlink)(lockPath).catch(() => {
|
|
298
|
+
});
|
|
299
|
+
throw new AgentArmorModelError(
|
|
300
|
+
"LOCK_TIMEOUT",
|
|
301
|
+
`Timed out waiting for lock file ${lockPath} after ${timeoutMs}ms`
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// src/cli.ts
|
|
306
|
+
var COMMANDS = {
|
|
307
|
+
download: "Download model to a directory",
|
|
308
|
+
"clear-cache": "Clear cached models",
|
|
309
|
+
"cache-info": "Show cache directory and contents"
|
|
310
|
+
};
|
|
311
|
+
async function main() {
|
|
312
|
+
const args = process.argv.slice(2);
|
|
313
|
+
const command = args[0];
|
|
314
|
+
if (!command || command === "--help" || command === "-h") {
|
|
315
|
+
console.log("agentarmor-ml \u2014 ML classifier tools for Agent Armor\n");
|
|
316
|
+
console.log("Commands:");
|
|
317
|
+
for (const [cmd, desc] of Object.entries(COMMANDS)) {
|
|
318
|
+
console.log(` ${cmd.padEnd(15)} ${desc}`);
|
|
319
|
+
}
|
|
320
|
+
console.log("\nOptions:");
|
|
321
|
+
console.log(" --dir <path> Target directory for download");
|
|
322
|
+
console.log(" --quiet Suppress progress, output only final path");
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
switch (command) {
|
|
326
|
+
case "download":
|
|
327
|
+
await cmdDownload(args.slice(1));
|
|
328
|
+
break;
|
|
329
|
+
case "clear-cache":
|
|
330
|
+
await cmdClearCache();
|
|
331
|
+
break;
|
|
332
|
+
case "cache-info":
|
|
333
|
+
await cmdCacheInfo();
|
|
334
|
+
break;
|
|
335
|
+
default:
|
|
336
|
+
console.error(`Unknown command: ${command}`);
|
|
337
|
+
process.exit(1);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
async function cmdDownload(args) {
|
|
341
|
+
const dirIndex = args.indexOf("--dir");
|
|
342
|
+
const quiet = args.includes("--quiet");
|
|
343
|
+
const dir = dirIndex >= 0 ? args[dirIndex + 1] : void 0;
|
|
344
|
+
if (!dir) {
|
|
345
|
+
console.error("Error: --dir <path> is required");
|
|
346
|
+
process.exit(1);
|
|
347
|
+
}
|
|
348
|
+
const onProgress = quiet ? void 0 : (received, total) => {
|
|
349
|
+
if (total > 0) {
|
|
350
|
+
const pct = (received / total * 100).toFixed(1);
|
|
351
|
+
process.stdout.write(`\rDownloading... ${pct}% (${(received / 1e6).toFixed(1)}/${(total / 1e6).toFixed(1)} MB)`);
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
try {
|
|
355
|
+
const result = await resolveModel({
|
|
356
|
+
enabled: true,
|
|
357
|
+
download: { onProgress }
|
|
358
|
+
});
|
|
359
|
+
const resolvedDir = (0, import_path3.join)(process.cwd(), dir);
|
|
360
|
+
(0, import_fs2.mkdirSync)(resolvedDir, { recursive: true });
|
|
361
|
+
for (const file of REQUIRED_MODEL_FILES) {
|
|
362
|
+
const src = (0, import_path3.join)(result.modelDir, file);
|
|
363
|
+
const dest = (0, import_path3.join)(resolvedDir, file);
|
|
364
|
+
(0, import_fs2.copyFileSync)(src, dest);
|
|
365
|
+
}
|
|
366
|
+
if (!quiet) console.log("");
|
|
367
|
+
console.log(quiet ? (0, import_path3.join)(resolvedDir, "model_quantized.onnx") : `Model downloaded to: ${resolvedDir}`);
|
|
368
|
+
} catch (err) {
|
|
369
|
+
console.error(`
|
|
370
|
+
Download failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
371
|
+
process.exit(1);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
async function cmdClearCache() {
|
|
375
|
+
const cacheDir = getDefaultCacheDir();
|
|
376
|
+
try {
|
|
377
|
+
await (0, import_promises3.rm)(cacheDir, { recursive: true, force: true });
|
|
378
|
+
console.log(`Cache cleared: ${cacheDir}`);
|
|
379
|
+
} catch (err) {
|
|
380
|
+
console.error(`Failed to clear cache: ${err instanceof Error ? err.message : String(err)}`);
|
|
381
|
+
process.exit(1);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
async function cmdCacheInfo() {
|
|
385
|
+
const cacheDir = getDefaultCacheDir();
|
|
386
|
+
console.log(`Cache directory: ${cacheDir}`);
|
|
387
|
+
console.log(`Model version: ${MODEL_VERSION}`);
|
|
388
|
+
try {
|
|
389
|
+
const files = await (0, import_promises3.readdir)(cacheDir);
|
|
390
|
+
let totalSize = 0;
|
|
391
|
+
for (const file of files) {
|
|
392
|
+
const s = await (0, import_promises3.stat)((0, import_path3.join)(cacheDir, file));
|
|
393
|
+
totalSize += s.size;
|
|
394
|
+
console.log(` ${file} (${(s.size / 1e6).toFixed(1)} MB)`);
|
|
395
|
+
}
|
|
396
|
+
console.log(`Total: ${(totalSize / 1e6).toFixed(1)} MB`);
|
|
397
|
+
} catch {
|
|
398
|
+
console.log(" (empty or not yet downloaded)");
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
main().catch((err) => {
|
|
402
|
+
console.error(err);
|
|
403
|
+
process.exit(1);
|
|
404
|
+
});
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
interface ModelArtifacts {
|
|
2
|
+
modelPath: string;
|
|
3
|
+
tokenizerPath: string;
|
|
4
|
+
labelMapPath: string;
|
|
5
|
+
modelDir: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface DetectorOptions {
|
|
9
|
+
strictness?: 'permissive' | 'balanced' | 'strict';
|
|
10
|
+
}
|
|
11
|
+
interface DetectorResult {
|
|
12
|
+
threats: Threat[];
|
|
13
|
+
}
|
|
14
|
+
interface Threat {
|
|
15
|
+
category: string;
|
|
16
|
+
type: string;
|
|
17
|
+
severity: 'low' | 'medium' | 'high' | 'critical';
|
|
18
|
+
confidence: number;
|
|
19
|
+
description: string;
|
|
20
|
+
evidence: string;
|
|
21
|
+
location?: {
|
|
22
|
+
offset: number;
|
|
23
|
+
length: number;
|
|
24
|
+
};
|
|
25
|
+
detectorId: string;
|
|
26
|
+
source: 'pattern' | 'ml' | 'custom';
|
|
27
|
+
}
|
|
28
|
+
interface Detector {
|
|
29
|
+
id: string;
|
|
30
|
+
name: string;
|
|
31
|
+
category: string;
|
|
32
|
+
scan(content: string, options?: DetectorOptions): DetectorResult;
|
|
33
|
+
scanAsync?(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
34
|
+
sanitize(content: string, threats: Threat[]): string;
|
|
35
|
+
}
|
|
36
|
+
declare class MLDetector implements Detector {
|
|
37
|
+
readonly id = "ml-classifier";
|
|
38
|
+
readonly name = "ML Classifier (DeBERTa-v3-small)";
|
|
39
|
+
readonly category = "content-injection";
|
|
40
|
+
private session;
|
|
41
|
+
private tokenizer;
|
|
42
|
+
private ort;
|
|
43
|
+
private constructor();
|
|
44
|
+
static create(artifacts: ModelArtifacts): Promise<MLDetector>;
|
|
45
|
+
scan(_content: string, _options?: DetectorOptions): DetectorResult;
|
|
46
|
+
scanAsync(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
47
|
+
sanitize(content: string, _threats: Threat[]): string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type ModelErrorCode = 'MODEL_NOT_FOUND' | 'CHECKSUM_MISMATCH' | 'DOWNLOAD_FAILED' | 'DOWNLOAD_TIMEOUT' | 'DISK_FULL' | 'LOCK_TIMEOUT';
|
|
51
|
+
declare class AgentArmorModelError extends Error {
|
|
52
|
+
readonly code: ModelErrorCode;
|
|
53
|
+
readonly cause?: Error;
|
|
54
|
+
constructor(code: ModelErrorCode, message: string, cause?: Error);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Create an ML detector from config.
|
|
59
|
+
* Called by AgentArmor.create() when ml config is provided.
|
|
60
|
+
*/
|
|
61
|
+
declare function createMLDetector(mlConfig: {
|
|
62
|
+
modelDir?: string;
|
|
63
|
+
enabled?: boolean;
|
|
64
|
+
modelUrl?: string;
|
|
65
|
+
download?: {
|
|
66
|
+
timeoutMs?: number;
|
|
67
|
+
retries?: number;
|
|
68
|
+
onProgress?: (bytesReceived: number, totalBytes: number) => void;
|
|
69
|
+
};
|
|
70
|
+
}): Promise<MLDetector>;
|
|
71
|
+
|
|
72
|
+
export { AgentArmorModelError, MLDetector, type ModelArtifacts, createMLDetector };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
interface ModelArtifacts {
|
|
2
|
+
modelPath: string;
|
|
3
|
+
tokenizerPath: string;
|
|
4
|
+
labelMapPath: string;
|
|
5
|
+
modelDir: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface DetectorOptions {
|
|
9
|
+
strictness?: 'permissive' | 'balanced' | 'strict';
|
|
10
|
+
}
|
|
11
|
+
interface DetectorResult {
|
|
12
|
+
threats: Threat[];
|
|
13
|
+
}
|
|
14
|
+
interface Threat {
|
|
15
|
+
category: string;
|
|
16
|
+
type: string;
|
|
17
|
+
severity: 'low' | 'medium' | 'high' | 'critical';
|
|
18
|
+
confidence: number;
|
|
19
|
+
description: string;
|
|
20
|
+
evidence: string;
|
|
21
|
+
location?: {
|
|
22
|
+
offset: number;
|
|
23
|
+
length: number;
|
|
24
|
+
};
|
|
25
|
+
detectorId: string;
|
|
26
|
+
source: 'pattern' | 'ml' | 'custom';
|
|
27
|
+
}
|
|
28
|
+
interface Detector {
|
|
29
|
+
id: string;
|
|
30
|
+
name: string;
|
|
31
|
+
category: string;
|
|
32
|
+
scan(content: string, options?: DetectorOptions): DetectorResult;
|
|
33
|
+
scanAsync?(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
34
|
+
sanitize(content: string, threats: Threat[]): string;
|
|
35
|
+
}
|
|
36
|
+
declare class MLDetector implements Detector {
|
|
37
|
+
readonly id = "ml-classifier";
|
|
38
|
+
readonly name = "ML Classifier (DeBERTa-v3-small)";
|
|
39
|
+
readonly category = "content-injection";
|
|
40
|
+
private session;
|
|
41
|
+
private tokenizer;
|
|
42
|
+
private ort;
|
|
43
|
+
private constructor();
|
|
44
|
+
static create(artifacts: ModelArtifacts): Promise<MLDetector>;
|
|
45
|
+
scan(_content: string, _options?: DetectorOptions): DetectorResult;
|
|
46
|
+
scanAsync(content: string, options?: DetectorOptions): Promise<DetectorResult>;
|
|
47
|
+
sanitize(content: string, _threats: Threat[]): string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type ModelErrorCode = 'MODEL_NOT_FOUND' | 'CHECKSUM_MISMATCH' | 'DOWNLOAD_FAILED' | 'DOWNLOAD_TIMEOUT' | 'DISK_FULL' | 'LOCK_TIMEOUT';
|
|
51
|
+
declare class AgentArmorModelError extends Error {
|
|
52
|
+
readonly code: ModelErrorCode;
|
|
53
|
+
readonly cause?: Error;
|
|
54
|
+
constructor(code: ModelErrorCode, message: string, cause?: Error);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Create an ML detector from config.
|
|
59
|
+
* Called by AgentArmor.create() when ml config is provided.
|
|
60
|
+
*/
|
|
61
|
+
declare function createMLDetector(mlConfig: {
|
|
62
|
+
modelDir?: string;
|
|
63
|
+
enabled?: boolean;
|
|
64
|
+
modelUrl?: string;
|
|
65
|
+
download?: {
|
|
66
|
+
timeoutMs?: number;
|
|
67
|
+
retries?: number;
|
|
68
|
+
onProgress?: (bytesReceived: number, totalBytes: number) => void;
|
|
69
|
+
};
|
|
70
|
+
}): Promise<MLDetector>;
|
|
71
|
+
|
|
72
|
+
export { AgentArmorModelError, MLDetector, type ModelArtifacts, createMLDetector };
|