@kya-os/checkpoint-wasm-runtime 1.0.0

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.
Files changed (71) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/adapters.d.mts +257 -0
  3. package/dist/adapters.d.ts +257 -0
  4. package/dist/adapters.js +603 -0
  5. package/dist/adapters.js.map +1 -0
  6. package/dist/adapters.mjs +586 -0
  7. package/dist/adapters.mjs.map +1 -0
  8. package/dist/dynamic-loader-cS-pUisw.d.ts +65 -0
  9. package/dist/dynamic-loader-qGJacfEC.d.mts +65 -0
  10. package/dist/edge.d.mts +22 -0
  11. package/dist/edge.d.ts +22 -0
  12. package/dist/edge.js +1403 -0
  13. package/dist/edge.js.map +1 -0
  14. package/dist/edge.mjs +1391 -0
  15. package/dist/edge.mjs.map +1 -0
  16. package/dist/engine-edge.d.mts +58 -0
  17. package/dist/engine-edge.d.ts +58 -0
  18. package/dist/engine-edge.js +537 -0
  19. package/dist/engine-edge.js.map +1 -0
  20. package/dist/engine-edge.mjs +533 -0
  21. package/dist/engine-edge.mjs.map +1 -0
  22. package/dist/engine.d.mts +34 -0
  23. package/dist/engine.d.ts +34 -0
  24. package/dist/engine.js +11 -0
  25. package/dist/engine.js.map +1 -0
  26. package/dist/engine.mjs +9 -0
  27. package/dist/engine.mjs.map +1 -0
  28. package/dist/index.d.mts +58 -0
  29. package/dist/index.d.ts +58 -0
  30. package/dist/index.js +1652 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/index.mjs +1637 -0
  33. package/dist/index.mjs.map +1 -0
  34. package/dist/node.d.mts +26 -0
  35. package/dist/node.d.ts +26 -0
  36. package/dist/node.js +972 -0
  37. package/dist/node.js.map +1 -0
  38. package/dist/node.mjs +960 -0
  39. package/dist/node.mjs.map +1 -0
  40. package/dist/orchestrator-edge.d.mts +243 -0
  41. package/dist/orchestrator-edge.d.ts +243 -0
  42. package/dist/orchestrator-edge.js +1076 -0
  43. package/dist/orchestrator-edge.js.map +1 -0
  44. package/dist/orchestrator-edge.mjs +1065 -0
  45. package/dist/orchestrator-edge.mjs.map +1 -0
  46. package/dist/orchestrator.d.mts +50 -0
  47. package/dist/orchestrator.d.ts +50 -0
  48. package/dist/orchestrator.js +1185 -0
  49. package/dist/orchestrator.js.map +1 -0
  50. package/dist/orchestrator.mjs +1172 -0
  51. package/dist/orchestrator.mjs.map +1 -0
  52. package/dist/rules-detector-DjbTJ1-Q.d.mts +470 -0
  53. package/dist/rules-detector-DjbTJ1-Q.d.ts +470 -0
  54. package/dist/static-loader-C1hUlksK.d.ts +72 -0
  55. package/dist/static-loader-Ds4iNw7c.d.mts +72 -0
  56. package/dist/types-D0j85fF0.d.mts +163 -0
  57. package/dist/types-D0j85fF0.d.ts +163 -0
  58. package/package.json +141 -0
  59. package/wasm/agentshield_wasm.d.ts +485 -0
  60. package/wasm/agentshield_wasm.js +1551 -0
  61. package/wasm/agentshield_wasm_bg.wasm +0 -0
  62. package/wasm/agentshield_wasm_bg.wasm.d.ts +97 -0
  63. package/wasm/kya-os-engine/kya_os_engine.d.ts +24 -0
  64. package/wasm/kya-os-engine/kya_os_engine.js +517 -0
  65. package/wasm/kya-os-engine/kya_os_engine_bg.wasm +0 -0
  66. package/wasm/kya-os-engine/kya_os_engine_bg.wasm.d.ts +8 -0
  67. package/wasm/kya-os-engine-web/kya_os_engine.d.ts +56 -0
  68. package/wasm/kya-os-engine-web/kya_os_engine.js +574 -0
  69. package/wasm/kya-os-engine-web/kya_os_engine_bg.wasm +0 -0
  70. package/wasm/kya-os-engine-web/kya_os_engine_bg.wasm.d.ts +8 -0
  71. package/wasm/package.json +30 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,1637 @@
1
+ import { loadRulesSync } from '@kya-os/checkpoint-shared';
2
+
3
+ // src/types.ts
4
+ var CONFIDENCE = {
5
+ /** Minimum confidence for isAgent=true */
6
+ THRESHOLD_AGENT: 30,
7
+ /** Cryptographic signature verified */
8
+ SIGNATURE_VERIFIED: 100,
9
+ /** Signature header present but not verified */
10
+ SIGNATURE_PRESENT: 85,
11
+ /** Strong pattern match */
12
+ PATTERN_HIGH: 85,
13
+ /** Moderate pattern match */
14
+ PATTERN_MEDIUM: 60,
15
+ /** Weak pattern match */
16
+ PATTERN_LOW: 40,
17
+ /** Cloud IP detection only */
18
+ CLOUD_IP: 30
19
+ };
20
+
21
+ // src/wasm-detector.ts
22
+ function parseVerificationMethod(method) {
23
+ switch (method.toLowerCase()) {
24
+ case "signature":
25
+ return "signature";
26
+ case "pattern":
27
+ return "pattern";
28
+ case "behavioral":
29
+ return "behavioral";
30
+ case "network":
31
+ return "network";
32
+ case "mcp_i_handshake":
33
+ return "mcp_i_handshake";
34
+ default:
35
+ return "none";
36
+ }
37
+ }
38
+ function determineForgeabilityRisk(method, confidence) {
39
+ if (method === "signature" && confidence >= 90) {
40
+ return "low";
41
+ }
42
+ if (confidence >= 80) {
43
+ return "medium";
44
+ }
45
+ return "high";
46
+ }
47
+ function determineDetectionClass(isAgent, agentName, confidence) {
48
+ if (!isAgent || confidence < CONFIDENCE.THRESHOLD_AGENT) {
49
+ return { type: "Human" };
50
+ }
51
+ if (agentName) {
52
+ const aiAgentPatterns = [
53
+ "chatgpt",
54
+ "gpt",
55
+ "openai",
56
+ "claude",
57
+ "anthropic",
58
+ "perplexity",
59
+ "gemini",
60
+ "google ai",
61
+ "copilot",
62
+ "bing chat"
63
+ ];
64
+ const lowerName = agentName.toLowerCase();
65
+ if (aiAgentPatterns.some((pattern) => lowerName.includes(pattern))) {
66
+ return { type: "AiAgent", agentType: agentName };
67
+ }
68
+ const botPatterns = ["bot", "crawler", "spider", "scraper"];
69
+ if (botPatterns.some((pattern) => lowerName.includes(pattern))) {
70
+ return { type: "Bot", botType: agentName };
71
+ }
72
+ const automationPatterns = ["selenium", "puppeteer", "playwright", "cypress"];
73
+ if (automationPatterns.some((pattern) => lowerName.includes(pattern))) {
74
+ return { type: "Automation", toolType: agentName };
75
+ }
76
+ return { type: "AiAgent", agentType: agentName };
77
+ }
78
+ return { type: "Unknown" };
79
+ }
80
+ var WasmDetector = class {
81
+ /**
82
+ * Create a new WasmDetector
83
+ * @param loader - WASM loader (static for Edge, dynamic for Node.js)
84
+ * @param policyLoader - Optional policy loader for API key support
85
+ * @param options - Detector configuration options
86
+ */
87
+ constructor(loader, policyLoader, options = {}) {
88
+ this.loader = loader;
89
+ this.policyLoader = policyLoader;
90
+ this.options = options;
91
+ }
92
+ ready = false;
93
+ loadPromise = null;
94
+ /**
95
+ * Analyze a request and detect if it's from an agent
96
+ */
97
+ async detect(input) {
98
+ await this.ensureReady();
99
+ try {
100
+ const bindings = this.loader.getBindings();
101
+ const metadata = {
102
+ user_agent: input.userAgent || null,
103
+ ip_address: input.ipAddress || null,
104
+ headers: JSON.stringify(input.headers || {}),
105
+ timestamp: (input.timestamp || /* @__PURE__ */ new Date()).toISOString(),
106
+ url: input.url || null,
107
+ method: input.method || null,
108
+ client_fingerprint: input.clientFingerprint || null,
109
+ free: () => {
110
+ }
111
+ // No-op for JS
112
+ };
113
+ const wasmResult = bindings.detect_agent(metadata);
114
+ const verificationMethod = parseVerificationMethod(wasmResult.verification_method);
115
+ const forgeabilityRisk = determineForgeabilityRisk(verificationMethod, wasmResult.confidence);
116
+ const detectionClass = determineDetectionClass(
117
+ wasmResult.is_agent,
118
+ wasmResult.agent,
119
+ wasmResult.confidence
120
+ );
121
+ let result = {
122
+ isAgent: wasmResult.is_agent,
123
+ confidence: wasmResult.confidence,
124
+ // Already 0-100, no conversion!
125
+ detectionClass,
126
+ detectedAgent: wasmResult.agent ? {
127
+ type: this.inferAgentType(wasmResult.agent),
128
+ name: wasmResult.agent
129
+ } : void 0,
130
+ verificationMethod,
131
+ forgeabilityRisk,
132
+ reasons: this.extractReasons(wasmResult),
133
+ timestamp: /* @__PURE__ */ new Date()
134
+ };
135
+ if (this.policyLoader && this.options.apiKey) {
136
+ result = await this.applyPolicy(result);
137
+ }
138
+ return result;
139
+ } catch (error) {
140
+ if (this.options.debug) {
141
+ console.error("[WasmDetector] Detection error:", error);
142
+ }
143
+ return this.createDefaultResult();
144
+ }
145
+ }
146
+ /**
147
+ * Check if the detector is ready
148
+ */
149
+ isReady() {
150
+ return this.ready;
151
+ }
152
+ /**
153
+ * Ensure the detector is initialized
154
+ */
155
+ async ensureReady() {
156
+ if (this.ready) {
157
+ return;
158
+ }
159
+ if (this.loadPromise) {
160
+ return this.loadPromise;
161
+ }
162
+ this.loadPromise = this.initialize();
163
+ return this.loadPromise;
164
+ }
165
+ /**
166
+ * Get detector version
167
+ */
168
+ async getVersion() {
169
+ await this.ensureReady();
170
+ return this.loader.getBindings().get_version();
171
+ }
172
+ /**
173
+ * Initialize the detector
174
+ */
175
+ async initialize() {
176
+ try {
177
+ await this.loader.load();
178
+ this.ready = true;
179
+ if (this.options.debug) {
180
+ const version2 = this.loader.getBindings().get_version();
181
+ console.log(
182
+ `[WasmDetector] Initialized with WASM v${version2} (${this.loader.getStrategy()})`
183
+ );
184
+ }
185
+ } catch (error) {
186
+ this.loadPromise = null;
187
+ throw error;
188
+ }
189
+ }
190
+ /**
191
+ * Apply customer policy to detection result
192
+ */
193
+ async applyPolicy(result) {
194
+ if (!this.policyLoader || !this.options.apiKey) {
195
+ return result;
196
+ }
197
+ try {
198
+ let policy = this.policyLoader.getCachedPolicy(this.options.apiKey);
199
+ if (!policy) {
200
+ policy = await this.policyLoader.loadPolicy(this.options.apiKey);
201
+ }
202
+ return this.applyPolicyRules(result, policy);
203
+ } catch (error) {
204
+ if (this.options.debug) {
205
+ console.warn("[WasmDetector] Failed to load policy:", error);
206
+ }
207
+ return result;
208
+ }
209
+ }
210
+ /**
211
+ * Check if agent name matches a policy list entry
212
+ * Uses exact match or word-boundary prefix match to avoid false positives
213
+ * e.g., "gpt" matches "ChatGPT" and "GPT-4" but not "EgyptBot"
214
+ */
215
+ matchesPolicyEntry(agentName, policyEntry) {
216
+ const lowerAgent = agentName.toLowerCase();
217
+ const lowerEntry = policyEntry.toLowerCase();
218
+ if (lowerAgent === lowerEntry) {
219
+ return true;
220
+ }
221
+ const wordBoundaryRegex = new RegExp(
222
+ `(^|[^a-z0-9])${this.escapeRegex(lowerEntry)}($|[^a-z0-9])`,
223
+ "i"
224
+ );
225
+ return wordBoundaryRegex.test(lowerAgent);
226
+ }
227
+ /**
228
+ * Escape special regex characters in a string
229
+ */
230
+ escapeRegex(str) {
231
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
232
+ }
233
+ /**
234
+ * Apply policy rules to detection result
235
+ */
236
+ applyPolicyRules(result, policy) {
237
+ if (policy.denyList && result.detectedAgent) {
238
+ const agentName = result.detectedAgent.name;
239
+ const isDenied = policy.denyList.some((denied) => this.matchesPolicyEntry(agentName, denied));
240
+ if (isDenied) {
241
+ return {
242
+ ...result,
243
+ shouldBlock: true,
244
+ blockReason: "deny_list"
245
+ };
246
+ }
247
+ }
248
+ if (policy.allowList && policy.allowList.length > 0 && result.isAgent) {
249
+ const agentName = result.detectedAgent?.name;
250
+ if (!agentName) ; else {
251
+ const isAllowed = policy.allowList.some(
252
+ (allowed) => this.matchesPolicyEntry(agentName, allowed)
253
+ );
254
+ if (!isAllowed) {
255
+ return {
256
+ ...result,
257
+ shouldBlock: true,
258
+ blockReason: "not_in_allow_list"
259
+ };
260
+ }
261
+ return {
262
+ ...result,
263
+ shouldBlock: false
264
+ };
265
+ }
266
+ }
267
+ if (policy.blockThreshold !== void 0 && result.isAgent && result.confidence >= policy.blockThreshold) {
268
+ return {
269
+ ...result,
270
+ shouldBlock: true,
271
+ blockReason: "threshold"
272
+ };
273
+ }
274
+ return result;
275
+ }
276
+ /**
277
+ * Infer agent type from name
278
+ */
279
+ inferAgentType(agentName) {
280
+ const lowerName = agentName.toLowerCase();
281
+ if (lowerName.includes("chatgpt") || lowerName.includes("openai") || lowerName.includes("gpt")) {
282
+ return "openai";
283
+ }
284
+ if (lowerName.includes("claude") || lowerName.includes("anthropic")) {
285
+ return "anthropic";
286
+ }
287
+ if (lowerName.includes("perplexity")) {
288
+ return "perplexity";
289
+ }
290
+ if (lowerName.includes("gemini") || lowerName.includes("google")) {
291
+ return "google";
292
+ }
293
+ if (lowerName.includes("copilot") || lowerName.includes("bing")) {
294
+ return "microsoft";
295
+ }
296
+ return "unknown";
297
+ }
298
+ /**
299
+ * Extract reasons from WASM result
300
+ */
301
+ extractReasons(wasmResult) {
302
+ const reasons = [];
303
+ if (wasmResult.verification_method) {
304
+ reasons.push(`method:${wasmResult.verification_method}`);
305
+ }
306
+ if (wasmResult.agent) {
307
+ reasons.push(`agent:${wasmResult.agent.toLowerCase()}`);
308
+ }
309
+ return reasons;
310
+ }
311
+ /**
312
+ * Create default result (assumed human)
313
+ */
314
+ createDefaultResult() {
315
+ return {
316
+ isAgent: false,
317
+ confidence: 0,
318
+ detectionClass: { type: "Human" },
319
+ verificationMethod: "none",
320
+ forgeabilityRisk: "high",
321
+ reasons: ["detection_failed"],
322
+ timestamp: /* @__PURE__ */ new Date()
323
+ };
324
+ }
325
+ };
326
+
327
+ // src/wasm-bindgen/agentshield_wasm.js
328
+ var wasm;
329
+ var cachedTextDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8", { ignoreBOM: true, fatal: true }) : {
330
+ decode: () => {
331
+ throw Error("TextDecoder not available");
332
+ }
333
+ };
334
+ if (typeof TextDecoder !== "undefined") {
335
+ cachedTextDecoder.decode();
336
+ }
337
+ var cachedUint8ArrayMemory0 = null;
338
+ function getUint8ArrayMemory0() {
339
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
340
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
341
+ }
342
+ return cachedUint8ArrayMemory0;
343
+ }
344
+ function getStringFromWasm0(ptr, len) {
345
+ ptr = ptr >>> 0;
346
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
347
+ }
348
+ function logError(f, args) {
349
+ try {
350
+ return f.apply(this, args);
351
+ } catch (e) {
352
+ let error = (function() {
353
+ try {
354
+ return e instanceof Error ? `${e.message}
355
+
356
+ Stack:
357
+ ${e.stack}` : e.toString();
358
+ } catch (_) {
359
+ return "<failed to stringify thrown value>";
360
+ }
361
+ })();
362
+ console.error(
363
+ "wasm-bindgen: imported JS function that was not marked as `catch` threw an error:",
364
+ error
365
+ );
366
+ throw e;
367
+ }
368
+ }
369
+ var WASM_VECTOR_LEN = 0;
370
+ var cachedTextEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder("utf-8") : {
371
+ encode: () => {
372
+ throw Error("TextEncoder not available");
373
+ }
374
+ };
375
+ var encodeString = typeof cachedTextEncoder.encodeInto === "function" ? function(arg, view) {
376
+ return cachedTextEncoder.encodeInto(arg, view);
377
+ } : function(arg, view) {
378
+ const buf = cachedTextEncoder.encode(arg);
379
+ view.set(buf);
380
+ return {
381
+ read: arg.length,
382
+ written: buf.length
383
+ };
384
+ };
385
+ function passStringToWasm0(arg, malloc, realloc) {
386
+ if (typeof arg !== "string") throw new Error(`expected a string argument, found ${typeof arg}`);
387
+ if (realloc === void 0) {
388
+ const buf = cachedTextEncoder.encode(arg);
389
+ const ptr2 = malloc(buf.length, 1) >>> 0;
390
+ getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
391
+ WASM_VECTOR_LEN = buf.length;
392
+ return ptr2;
393
+ }
394
+ let len = arg.length;
395
+ let ptr = malloc(len, 1) >>> 0;
396
+ const mem = getUint8ArrayMemory0();
397
+ let offset = 0;
398
+ for (; offset < len; offset++) {
399
+ const code = arg.charCodeAt(offset);
400
+ if (code > 127) break;
401
+ mem[ptr + offset] = code;
402
+ }
403
+ if (offset !== len) {
404
+ if (offset !== 0) {
405
+ arg = arg.slice(offset);
406
+ }
407
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
408
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
409
+ const ret = encodeString(arg, view);
410
+ if (ret.read !== arg.length) throw new Error("failed to pass whole string");
411
+ offset += ret.written;
412
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
413
+ }
414
+ WASM_VECTOR_LEN = offset;
415
+ return ptr;
416
+ }
417
+ var cachedDataViewMemory0 = null;
418
+ function getDataViewMemory0() {
419
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || cachedDataViewMemory0.buffer.detached === void 0 && cachedDataViewMemory0.buffer !== wasm.memory.buffer) {
420
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
421
+ }
422
+ return cachedDataViewMemory0;
423
+ }
424
+ function _assertNum(n) {
425
+ if (typeof n !== "number") throw new Error(`expected a number argument, found ${typeof n}`);
426
+ }
427
+ function _assertBoolean(n) {
428
+ if (typeof n !== "boolean") {
429
+ throw new Error(`expected a boolean argument, found ${typeof n}`);
430
+ }
431
+ }
432
+ function isLikeNone(x) {
433
+ return x === void 0 || x === null;
434
+ }
435
+ function _assertClass(instance, klass) {
436
+ if (!(instance instanceof klass)) {
437
+ throw new Error(`expected instance of ${klass.name}`);
438
+ }
439
+ }
440
+ function takeFromExternrefTable0(idx) {
441
+ const value = wasm.__wbindgen_export_3.get(idx);
442
+ wasm.__externref_table_dealloc(idx);
443
+ return value;
444
+ }
445
+ function detect_agent(metadata) {
446
+ _assertClass(metadata, JsRequestMetadata);
447
+ if (metadata.__wbg_ptr === 0) {
448
+ throw new Error("Attempt to use a moved value");
449
+ }
450
+ const ret = wasm.detect_agent(metadata.__wbg_ptr);
451
+ if (ret[2]) {
452
+ throw takeFromExternrefTable0(ret[1]);
453
+ }
454
+ return JsDetectionResult.__wrap(ret[0]);
455
+ }
456
+ function version() {
457
+ let deferred1_0;
458
+ let deferred1_1;
459
+ try {
460
+ const ret = wasm.version();
461
+ deferred1_0 = ret[0];
462
+ deferred1_1 = ret[1];
463
+ return getStringFromWasm0(ret[0], ret[1]);
464
+ } finally {
465
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
466
+ }
467
+ }
468
+ var JsDetectionResultFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
469
+ }, unregister: () => {
470
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_jsdetectionresult_free(ptr >>> 0, 1));
471
+ var JsDetectionResult = class _JsDetectionResult {
472
+ constructor() {
473
+ throw new Error("cannot invoke `new` directly");
474
+ }
475
+ static __wrap(ptr) {
476
+ ptr = ptr >>> 0;
477
+ const obj = Object.create(_JsDetectionResult.prototype);
478
+ obj.__wbg_ptr = ptr;
479
+ JsDetectionResultFinalization.register(obj, obj.__wbg_ptr, obj);
480
+ return obj;
481
+ }
482
+ __destroy_into_raw() {
483
+ const ptr = this.__wbg_ptr;
484
+ this.__wbg_ptr = 0;
485
+ JsDetectionResultFinalization.unregister(this);
486
+ return ptr;
487
+ }
488
+ free() {
489
+ const ptr = this.__destroy_into_raw();
490
+ wasm.__wbg_jsdetectionresult_free(ptr, 0);
491
+ }
492
+ /**
493
+ * Whether the request was identified as coming from an agent
494
+ * @returns {boolean}
495
+ */
496
+ get is_agent() {
497
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
498
+ _assertNum(this.__wbg_ptr);
499
+ const ret = wasm.__wbg_get_jsdetectionresult_is_agent(this.__wbg_ptr);
500
+ return ret !== 0;
501
+ }
502
+ /**
503
+ * Whether the request was identified as coming from an agent
504
+ * @param {boolean} arg0
505
+ */
506
+ set is_agent(arg0) {
507
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
508
+ _assertNum(this.__wbg_ptr);
509
+ _assertBoolean(arg0);
510
+ wasm.__wbg_set_jsdetectionresult_is_agent(this.__wbg_ptr, arg0);
511
+ }
512
+ /**
513
+ * Confidence score (0.0 to 1.0)
514
+ * @returns {number}
515
+ */
516
+ get confidence() {
517
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
518
+ _assertNum(this.__wbg_ptr);
519
+ const ret = wasm.__wbg_get_jsdetectionresult_confidence(this.__wbg_ptr);
520
+ return ret;
521
+ }
522
+ /**
523
+ * Confidence score (0.0 to 1.0)
524
+ * @param {number} arg0
525
+ */
526
+ set confidence(arg0) {
527
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
528
+ _assertNum(this.__wbg_ptr);
529
+ wasm.__wbg_set_jsdetectionresult_confidence(this.__wbg_ptr, arg0);
530
+ }
531
+ /**
532
+ * Get the detected agent name
533
+ * @returns {string | undefined}
534
+ */
535
+ get agent() {
536
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
537
+ _assertNum(this.__wbg_ptr);
538
+ const ret = wasm.jsdetectionresult_agent(this.__wbg_ptr);
539
+ let v1;
540
+ if (ret[0] !== 0) {
541
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
542
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
543
+ }
544
+ return v1;
545
+ }
546
+ /**
547
+ * Get the verification method as a string
548
+ * @returns {string}
549
+ */
550
+ get verification_method() {
551
+ let deferred1_0;
552
+ let deferred1_1;
553
+ try {
554
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
555
+ _assertNum(this.__wbg_ptr);
556
+ const ret = wasm.jsdetectionresult_verification_method(this.__wbg_ptr);
557
+ deferred1_0 = ret[0];
558
+ deferred1_1 = ret[1];
559
+ return getStringFromWasm0(ret[0], ret[1]);
560
+ } finally {
561
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
562
+ }
563
+ }
564
+ /**
565
+ * Get the risk level as a string
566
+ * @returns {string}
567
+ */
568
+ get risk_level() {
569
+ let deferred1_0;
570
+ let deferred1_1;
571
+ try {
572
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
573
+ _assertNum(this.__wbg_ptr);
574
+ const ret = wasm.jsdetectionresult_risk_level(this.__wbg_ptr);
575
+ deferred1_0 = ret[0];
576
+ deferred1_1 = ret[1];
577
+ return getStringFromWasm0(ret[0], ret[1]);
578
+ } finally {
579
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
580
+ }
581
+ }
582
+ /**
583
+ * Get the timestamp as a string
584
+ * @returns {string}
585
+ */
586
+ get timestamp() {
587
+ let deferred1_0;
588
+ let deferred1_1;
589
+ try {
590
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
591
+ _assertNum(this.__wbg_ptr);
592
+ const ret = wasm.jsdetectionresult_timestamp(this.__wbg_ptr);
593
+ deferred1_0 = ret[0];
594
+ deferred1_1 = ret[1];
595
+ return getStringFromWasm0(ret[0], ret[1]);
596
+ } finally {
597
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
598
+ }
599
+ }
600
+ };
601
+ var JsRequestMetadataFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
602
+ }, unregister: () => {
603
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_jsrequestmetadata_free(ptr >>> 0, 1));
604
+ var JsRequestMetadata = class {
605
+ __destroy_into_raw() {
606
+ const ptr = this.__wbg_ptr;
607
+ this.__wbg_ptr = 0;
608
+ JsRequestMetadataFinalization.unregister(this);
609
+ return ptr;
610
+ }
611
+ free() {
612
+ const ptr = this.__destroy_into_raw();
613
+ wasm.__wbg_jsrequestmetadata_free(ptr, 0);
614
+ }
615
+ /**
616
+ * Constructor for JsRequestMetadata
617
+ * @param {string | null | undefined} user_agent
618
+ * @param {string | null | undefined} ip_address
619
+ * @param {string} headers
620
+ * @param {string} timestamp
621
+ * @param {string | null} [url]
622
+ * @param {string | null} [method]
623
+ * @param {string | null} [client_fingerprint]
624
+ */
625
+ constructor(user_agent, ip_address, headers, timestamp, url, method, client_fingerprint) {
626
+ var ptr0 = isLikeNone(user_agent) ? 0 : passStringToWasm0(user_agent, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
627
+ var len0 = WASM_VECTOR_LEN;
628
+ var ptr1 = isLikeNone(ip_address) ? 0 : passStringToWasm0(ip_address, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
629
+ var len1 = WASM_VECTOR_LEN;
630
+ const ptr2 = passStringToWasm0(headers, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
631
+ const len2 = WASM_VECTOR_LEN;
632
+ const ptr3 = passStringToWasm0(timestamp, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
633
+ const len3 = WASM_VECTOR_LEN;
634
+ var ptr4 = isLikeNone(url) ? 0 : passStringToWasm0(url, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
635
+ var len4 = WASM_VECTOR_LEN;
636
+ var ptr5 = isLikeNone(method) ? 0 : passStringToWasm0(method, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
637
+ var len5 = WASM_VECTOR_LEN;
638
+ var ptr6 = isLikeNone(client_fingerprint) ? 0 : passStringToWasm0(client_fingerprint, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
639
+ var len6 = WASM_VECTOR_LEN;
640
+ const ret = wasm.jsrequestmetadata_new(
641
+ ptr0,
642
+ len0,
643
+ ptr1,
644
+ len1,
645
+ ptr2,
646
+ len2,
647
+ ptr3,
648
+ len3,
649
+ ptr4,
650
+ len4,
651
+ ptr5,
652
+ len5,
653
+ ptr6,
654
+ len6
655
+ );
656
+ this.__wbg_ptr = ret >>> 0;
657
+ JsRequestMetadataFinalization.register(this, this.__wbg_ptr, this);
658
+ return this;
659
+ }
660
+ /**
661
+ * Get the user agent
662
+ * @returns {string | undefined}
663
+ */
664
+ get user_agent() {
665
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
666
+ _assertNum(this.__wbg_ptr);
667
+ const ret = wasm.jsrequestmetadata_user_agent(this.__wbg_ptr);
668
+ let v1;
669
+ if (ret[0] !== 0) {
670
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
671
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
672
+ }
673
+ return v1;
674
+ }
675
+ /**
676
+ * Get the IP address
677
+ * @returns {string | undefined}
678
+ */
679
+ get ip_address() {
680
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
681
+ _assertNum(this.__wbg_ptr);
682
+ const ret = wasm.jsrequestmetadata_ip_address(this.__wbg_ptr);
683
+ let v1;
684
+ if (ret[0] !== 0) {
685
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
686
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
687
+ }
688
+ return v1;
689
+ }
690
+ /**
691
+ * Get the headers as JSON string
692
+ * @returns {string}
693
+ */
694
+ get headers() {
695
+ let deferred1_0;
696
+ let deferred1_1;
697
+ try {
698
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
699
+ _assertNum(this.__wbg_ptr);
700
+ const ret = wasm.jsrequestmetadata_headers(this.__wbg_ptr);
701
+ deferred1_0 = ret[0];
702
+ deferred1_1 = ret[1];
703
+ return getStringFromWasm0(ret[0], ret[1]);
704
+ } finally {
705
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
706
+ }
707
+ }
708
+ /**
709
+ * Get the timestamp
710
+ * @returns {string}
711
+ */
712
+ get timestamp() {
713
+ let deferred1_0;
714
+ let deferred1_1;
715
+ try {
716
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
717
+ _assertNum(this.__wbg_ptr);
718
+ const ret = wasm.jsrequestmetadata_timestamp(this.__wbg_ptr);
719
+ deferred1_0 = ret[0];
720
+ deferred1_1 = ret[1];
721
+ return getStringFromWasm0(ret[0], ret[1]);
722
+ } finally {
723
+ wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
724
+ }
725
+ }
726
+ /**
727
+ * Get the URL
728
+ * @returns {string | undefined}
729
+ */
730
+ get url() {
731
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
732
+ _assertNum(this.__wbg_ptr);
733
+ const ret = wasm.jsrequestmetadata_url(this.__wbg_ptr);
734
+ let v1;
735
+ if (ret[0] !== 0) {
736
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
737
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
738
+ }
739
+ return v1;
740
+ }
741
+ /**
742
+ * Get the method
743
+ * @returns {string | undefined}
744
+ */
745
+ get method() {
746
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
747
+ _assertNum(this.__wbg_ptr);
748
+ const ret = wasm.jsrequestmetadata_method(this.__wbg_ptr);
749
+ let v1;
750
+ if (ret[0] !== 0) {
751
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
752
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
753
+ }
754
+ return v1;
755
+ }
756
+ /**
757
+ * Get the client fingerprint
758
+ * @returns {string | undefined}
759
+ */
760
+ get client_fingerprint() {
761
+ if (this.__wbg_ptr == 0) throw new Error("Attempt to use a moved value");
762
+ _assertNum(this.__wbg_ptr);
763
+ const ret = wasm.jsrequestmetadata_client_fingerprint(this.__wbg_ptr);
764
+ let v1;
765
+ if (ret[0] !== 0) {
766
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
767
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
768
+ }
769
+ return v1;
770
+ }
771
+ };
772
+ function __wbg_get_imports() {
773
+ const imports = {};
774
+ imports.wbg = {};
775
+ imports.wbg.__wbg_error_7534b8e9a36f1ab4 = function() {
776
+ return logError(function(arg0, arg1) {
777
+ let deferred0_0;
778
+ let deferred0_1;
779
+ try {
780
+ deferred0_0 = arg0;
781
+ deferred0_1 = arg1;
782
+ console.error(getStringFromWasm0(arg0, arg1));
783
+ } finally {
784
+ wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);
785
+ }
786
+ }, arguments);
787
+ };
788
+ imports.wbg.__wbg_getTime_46267b1c24877e30 = function() {
789
+ return logError(function(arg0) {
790
+ const ret = arg0.getTime();
791
+ return ret;
792
+ }, arguments);
793
+ };
794
+ imports.wbg.__wbg_log_c222819a41e063d3 = function() {
795
+ return logError(function(arg0) {
796
+ console.log(arg0);
797
+ }, arguments);
798
+ };
799
+ imports.wbg.__wbg_new_31a97dac4f10fab7 = function() {
800
+ return logError(function(arg0) {
801
+ const ret = new Date(arg0);
802
+ return ret;
803
+ }, arguments);
804
+ };
805
+ imports.wbg.__wbg_new_8a6f238a6ece86ea = function() {
806
+ return logError(function() {
807
+ const ret = new Error();
808
+ return ret;
809
+ }, arguments);
810
+ };
811
+ imports.wbg.__wbg_now_807e54c39636c349 = function() {
812
+ return logError(function() {
813
+ const ret = Date.now();
814
+ return ret;
815
+ }, arguments);
816
+ };
817
+ imports.wbg.__wbg_stack_0ed75d68575b0f3c = function() {
818
+ return logError(function(arg0, arg1) {
819
+ const ret = arg1.stack;
820
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
821
+ const len1 = WASM_VECTOR_LEN;
822
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
823
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
824
+ }, arguments);
825
+ };
826
+ imports.wbg.__wbindgen_init_externref_table = function() {
827
+ const table = wasm.__wbindgen_export_3;
828
+ const offset = table.grow(4);
829
+ table.set(0, void 0);
830
+ table.set(offset + 0, void 0);
831
+ table.set(offset + 1, null);
832
+ table.set(offset + 2, true);
833
+ table.set(offset + 3, false);
834
+ };
835
+ imports.wbg.__wbindgen_string_new = function(arg0, arg1) {
836
+ const ret = getStringFromWasm0(arg0, arg1);
837
+ return ret;
838
+ };
839
+ imports.wbg.__wbindgen_throw = function(arg0, arg1) {
840
+ throw new Error(getStringFromWasm0(arg0, arg1));
841
+ };
842
+ return imports;
843
+ }
844
+ function __wbg_finalize_init(instance, module) {
845
+ wasm = instance.exports;
846
+ cachedDataViewMemory0 = null;
847
+ cachedUint8ArrayMemory0 = null;
848
+ wasm.__wbindgen_start();
849
+ return wasm;
850
+ }
851
+ function initSync(module) {
852
+ if (wasm !== void 0) return wasm;
853
+ if (typeof module !== "undefined") {
854
+ if (Object.getPrototypeOf(module) === Object.prototype) {
855
+ ({ module } = module);
856
+ } else {
857
+ console.warn("using deprecated parameters for `initSync()`; pass a single object instead");
858
+ }
859
+ }
860
+ const imports = __wbg_get_imports();
861
+ if (!(module instanceof WebAssembly.Module)) {
862
+ module = new WebAssembly.Module(module);
863
+ }
864
+ const instance = new WebAssembly.Instance(module, imports);
865
+ return __wbg_finalize_init(instance);
866
+ }
867
+
868
+ // src/loaders/static-loader.ts
869
+ var StaticWasmLoader = class {
870
+ /**
871
+ * Create a new StaticWasmLoader
872
+ * @param wasmModule - Pre-compiled WebAssembly.Module from static import
873
+ */
874
+ constructor(wasmModule) {
875
+ this.wasmModule = wasmModule;
876
+ if (!wasmModule) {
877
+ throw new Error(
878
+ "StaticWasmLoader requires a WebAssembly.Module. Import with: import wasmModule from './wasm.wasm?module'"
879
+ );
880
+ }
881
+ }
882
+ bindings = null;
883
+ loadPromise = null;
884
+ wasmExports = null;
885
+ /**
886
+ * Load and instantiate the WASM module
887
+ */
888
+ async load() {
889
+ if (this.bindings) {
890
+ return;
891
+ }
892
+ if (this.loadPromise) {
893
+ return this.loadPromise;
894
+ }
895
+ this.loadPromise = this.doLoad();
896
+ return this.loadPromise;
897
+ }
898
+ /**
899
+ * Internal load implementation using wasm-bindgen initSync
900
+ */
901
+ async doLoad() {
902
+ try {
903
+ this.wasmExports = initSync({ module: this.wasmModule });
904
+ this.bindings = this.createBindings();
905
+ } catch (error) {
906
+ this.loadPromise = null;
907
+ throw new Error(
908
+ `Failed to instantiate WASM module: ${error instanceof Error ? error.message : String(error)}`
909
+ );
910
+ }
911
+ }
912
+ /**
913
+ * Get the WASM bindings after loading
914
+ */
915
+ getBindings() {
916
+ if (!this.bindings) {
917
+ throw new Error("WASM not loaded. Call load() first.");
918
+ }
919
+ return this.bindings;
920
+ }
921
+ /**
922
+ * Check if WASM is loaded
923
+ */
924
+ isLoaded() {
925
+ return this.bindings !== null;
926
+ }
927
+ /**
928
+ * Get the loading strategy name
929
+ */
930
+ getStrategy() {
931
+ return "static-import";
932
+ }
933
+ /**
934
+ * Create bindings wrapper using wasm-bindgen exports
935
+ */
936
+ createBindings() {
937
+ return {
938
+ detect_agent: (metadata) => {
939
+ const wasmMetadata = new JsRequestMetadata(
940
+ metadata.user_agent,
941
+ metadata.ip_address,
942
+ metadata.headers,
943
+ metadata.timestamp,
944
+ metadata.url,
945
+ metadata.method,
946
+ metadata.client_fingerprint
947
+ );
948
+ let result = null;
949
+ try {
950
+ result = detect_agent(wasmMetadata);
951
+ return {
952
+ is_agent: result.is_agent,
953
+ confidence: result.confidence,
954
+ agent: result.agent ?? null,
955
+ // Convert undefined to null
956
+ verification_method: result.verification_method,
957
+ risk_level: result.risk_level,
958
+ timestamp: result.timestamp
959
+ };
960
+ } finally {
961
+ result?.free();
962
+ wasmMetadata.free();
963
+ }
964
+ },
965
+ get_version: () => {
966
+ try {
967
+ return version();
968
+ } catch {
969
+ return "0.1.0-static";
970
+ }
971
+ },
972
+ get_build_info: () => {
973
+ return JSON.stringify({ version: "0.1.0", strategy: "static-import" });
974
+ }
975
+ };
976
+ }
977
+ };
978
+ function createStaticLoader(wasmModule) {
979
+ return new StaticWasmLoader(wasmModule);
980
+ }
981
+
982
+ // src/loaders/dynamic-loader.ts
983
+ async function findWasmModule() {
984
+ const wasmPaths = [
985
+ // Relative to this package
986
+ "../wasm/agentshield_wasm_bg.wasm",
987
+ "./wasm/agentshield_wasm_bg.wasm",
988
+ // From agentshield-core package
989
+ "@kya-os/checkpoint/wasm/agentshield_wasm_bg.wasm",
990
+ // From monorepo build output
991
+ "../../rust/target/wasm32-unknown-unknown/release/agentshield_wasm_bg.wasm"
992
+ ];
993
+ for (const path of wasmPaths) {
994
+ try {
995
+ const module = await import(
996
+ /* webpackIgnore: true */
997
+ path
998
+ );
999
+ if (module.default && module.default instanceof ArrayBuffer) {
1000
+ return module.default;
1001
+ }
1002
+ } catch {
1003
+ }
1004
+ }
1005
+ try {
1006
+ const fs = await import('fs/promises');
1007
+ const nodePath = await import('path');
1008
+ let moduleDir = null;
1009
+ try {
1010
+ const importMetaUrl = eval('typeof import.meta !== "undefined" && import.meta.url');
1011
+ if (importMetaUrl) {
1012
+ const url = await import('url');
1013
+ moduleDir = nodePath.dirname(url.fileURLToPath(importMetaUrl));
1014
+ }
1015
+ } catch {
1016
+ }
1017
+ if (!moduleDir) {
1018
+ try {
1019
+ const cjsDirname = eval('typeof __dirname !== "undefined" && __dirname');
1020
+ if (cjsDirname) {
1021
+ moduleDir = cjsDirname;
1022
+ }
1023
+ } catch {
1024
+ }
1025
+ }
1026
+ const fsWasmPaths = [
1027
+ nodePath.resolve(
1028
+ process.cwd(),
1029
+ "node_modules/@kya-os/checkpoint-wasm-runtime/wasm/agentshield_wasm_bg.wasm"
1030
+ ),
1031
+ nodePath.resolve(
1032
+ process.cwd(),
1033
+ "node_modules/@kya-os/checkpoint/dist/wasm/agentshield_wasm_bg.wasm"
1034
+ )
1035
+ ];
1036
+ if (moduleDir) {
1037
+ fsWasmPaths.unshift(
1038
+ nodePath.resolve(moduleDir, "../wasm/agentshield_wasm_bg.wasm"),
1039
+ nodePath.resolve(moduleDir, "../../wasm/agentshield_wasm_bg.wasm")
1040
+ );
1041
+ }
1042
+ for (const wasmPath of fsWasmPaths) {
1043
+ try {
1044
+ const buffer = await fs.readFile(wasmPath);
1045
+ const arrayBuffer = new ArrayBuffer(buffer.byteLength);
1046
+ new Uint8Array(arrayBuffer).set(buffer);
1047
+ return arrayBuffer;
1048
+ } catch {
1049
+ }
1050
+ }
1051
+ } catch {
1052
+ }
1053
+ throw new Error(
1054
+ "Could not find WASM module. Ensure @kya-os/checkpoint-wasm-runtime/wasm is installed."
1055
+ );
1056
+ }
1057
+ var JsRequestMetadata2 = class {
1058
+ constructor(user_agent, ip_address, headers, timestamp, url, method, client_fingerprint) {
1059
+ this.user_agent = user_agent;
1060
+ this.ip_address = ip_address;
1061
+ this.headers = headers;
1062
+ this.timestamp = timestamp;
1063
+ this.url = url;
1064
+ this.method = method;
1065
+ this.client_fingerprint = client_fingerprint;
1066
+ }
1067
+ free() {
1068
+ }
1069
+ };
1070
+ var DynamicWasmLoader = class {
1071
+ /**
1072
+ * Create a new DynamicWasmLoader
1073
+ * @param wasmPath - Optional custom path to WASM file
1074
+ */
1075
+ constructor(wasmPath) {
1076
+ this.wasmPath = wasmPath;
1077
+ }
1078
+ bindings = null;
1079
+ instance = null;
1080
+ loadPromise = null;
1081
+ /**
1082
+ * Load and compile the WASM module
1083
+ */
1084
+ async load() {
1085
+ if (this.bindings) {
1086
+ return;
1087
+ }
1088
+ if (this.loadPromise) {
1089
+ return this.loadPromise;
1090
+ }
1091
+ this.loadPromise = this.doLoad();
1092
+ return this.loadPromise;
1093
+ }
1094
+ async doLoad() {
1095
+ try {
1096
+ let wasmBuffer;
1097
+ if (this.wasmPath) {
1098
+ const fs2 = await import('fs/promises');
1099
+ const buffer = await fs2.readFile(this.wasmPath);
1100
+ wasmBuffer = new ArrayBuffer(buffer.byteLength);
1101
+ new Uint8Array(wasmBuffer).set(buffer);
1102
+ } else {
1103
+ wasmBuffer = await findWasmModule();
1104
+ }
1105
+ const compiled = await WebAssembly.compile(wasmBuffer);
1106
+ const imports = {
1107
+ wbg: this.createWasmBindgenImports()
1108
+ };
1109
+ this.instance = await WebAssembly.instantiate(compiled, imports);
1110
+ const exports$1 = this.instance.exports;
1111
+ this.bindings = this.createBindings(exports$1);
1112
+ } catch (error) {
1113
+ this.loadPromise = null;
1114
+ throw new Error(
1115
+ `Failed to load WASM module: ${error instanceof Error ? error.message : String(error)}`
1116
+ );
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Get the WASM bindings after loading
1121
+ */
1122
+ getBindings() {
1123
+ if (!this.bindings) {
1124
+ throw new Error("WASM not loaded. Call load() first.");
1125
+ }
1126
+ return this.bindings;
1127
+ }
1128
+ /**
1129
+ * Check if WASM is loaded
1130
+ */
1131
+ isLoaded() {
1132
+ return this.bindings !== null;
1133
+ }
1134
+ /**
1135
+ * Get the loading strategy name
1136
+ */
1137
+ getStrategy() {
1138
+ return "dynamic-compile";
1139
+ }
1140
+ /**
1141
+ * Create wasm-bindgen required imports
1142
+ */
1143
+ createWasmBindgenImports() {
1144
+ return {
1145
+ __wbg_log_f740dc2253ea759b: (ptr, len) => {
1146
+ console.log("[WASM]", ptr, len);
1147
+ },
1148
+ __wbg_error_f851667af71bcfc6: (ptr, len) => {
1149
+ console.error("[WASM Error]", ptr, len);
1150
+ },
1151
+ __wbg_now_c644db5194be8437: () => Date.now(),
1152
+ __wbindgen_throw: (ptr, len) => {
1153
+ throw new Error(`WASM threw: ${ptr}, ${len}`);
1154
+ },
1155
+ __wbindgen_object_drop_ref: () => {
1156
+ }
1157
+ };
1158
+ }
1159
+ /**
1160
+ * Create bindings wrapper from WASM exports
1161
+ */
1162
+ createBindings(exports$1) {
1163
+ const detectAgent = exports$1["detect_agent"];
1164
+ const getVersion = exports$1["get_version"];
1165
+ const getBuildInfo = exports$1["get_build_info"];
1166
+ if (!detectAgent) {
1167
+ throw new Error("WASM module missing detect_agent export");
1168
+ }
1169
+ return {
1170
+ detect_agent: (metadata) => {
1171
+ const wasmMetadata = new JsRequestMetadata2(
1172
+ metadata.user_agent,
1173
+ metadata.ip_address,
1174
+ metadata.headers,
1175
+ metadata.timestamp,
1176
+ metadata.url,
1177
+ metadata.method,
1178
+ metadata.client_fingerprint
1179
+ );
1180
+ try {
1181
+ return detectAgent(wasmMetadata);
1182
+ } finally {
1183
+ wasmMetadata.free();
1184
+ }
1185
+ },
1186
+ get_version: () => {
1187
+ if (getVersion) {
1188
+ return getVersion();
1189
+ }
1190
+ return "0.1.0-dynamic";
1191
+ },
1192
+ get_build_info: () => {
1193
+ if (getBuildInfo) {
1194
+ return getBuildInfo();
1195
+ }
1196
+ return JSON.stringify({ version: "0.1.0", strategy: "dynamic-compile" });
1197
+ }
1198
+ };
1199
+ }
1200
+ };
1201
+ function createDynamicLoader(wasmPath) {
1202
+ return new DynamicWasmLoader(wasmPath);
1203
+ }
1204
+
1205
+ // src/policy/policy-loader.ts
1206
+ var DEFAULT_CONFIG = {
1207
+ apiUrl: "https://api.agentshield.io",
1208
+ cacheTTL: 5 * 60 * 1e3,
1209
+ // 5 minutes
1210
+ maxCacheSize: 100,
1211
+ backgroundRefresh: true,
1212
+ timeout: 5e3
1213
+ };
1214
+ var PolicyLoader = class {
1215
+ cache = /* @__PURE__ */ new Map();
1216
+ config;
1217
+ constructor(config = {}) {
1218
+ this.config = { ...DEFAULT_CONFIG, ...config };
1219
+ }
1220
+ /**
1221
+ * Load policy for an API key
1222
+ */
1223
+ async loadPolicy(apiKey) {
1224
+ const cached = this.getCachedPolicy(apiKey);
1225
+ if (cached) {
1226
+ if (this.config.backgroundRefresh && this.shouldRefresh(apiKey)) {
1227
+ this.refreshInBackground(apiKey);
1228
+ }
1229
+ return cached;
1230
+ }
1231
+ return this.fetchPolicy(apiKey);
1232
+ }
1233
+ /**
1234
+ * Get cached policy if available and not expired
1235
+ */
1236
+ getCachedPolicy(apiKey) {
1237
+ const entry = this.cache.get(apiKey);
1238
+ if (!entry) {
1239
+ return null;
1240
+ }
1241
+ if (this.isExpired(entry)) {
1242
+ this.cache.delete(apiKey);
1243
+ return null;
1244
+ }
1245
+ return entry.policy;
1246
+ }
1247
+ /**
1248
+ * Invalidate cached policy
1249
+ */
1250
+ invalidateCache(apiKey) {
1251
+ this.cache.delete(apiKey);
1252
+ }
1253
+ /**
1254
+ * Fetch policy from API and cache it
1255
+ */
1256
+ async fetchPolicy(apiKey) {
1257
+ const policy = await this.fetchPolicyFromApi(apiKey);
1258
+ this.cachePolicy(apiKey, policy);
1259
+ return policy;
1260
+ }
1261
+ /**
1262
+ * Fetch policy from API without caching
1263
+ * Used internally for both direct fetches and background refreshes
1264
+ */
1265
+ async fetchPolicyFromApi(apiKey) {
1266
+ const controller = new AbortController();
1267
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1268
+ try {
1269
+ const response = await fetch(`${this.config.apiUrl}/api/v1/policy`, {
1270
+ method: "GET",
1271
+ headers: {
1272
+ Authorization: `Bearer ${apiKey}`,
1273
+ "Content-Type": "application/json",
1274
+ "User-Agent": "agentshield-wasm-runtime/0.1.0"
1275
+ },
1276
+ signal: controller.signal
1277
+ });
1278
+ clearTimeout(timeoutId);
1279
+ if (!response.ok) {
1280
+ if (response.status === 401) {
1281
+ throw new PolicyLoadError("Invalid API key", "INVALID_API_KEY");
1282
+ }
1283
+ if (response.status === 404) {
1284
+ return this.getDefaultPolicy(apiKey);
1285
+ }
1286
+ throw new PolicyLoadError(`Failed to load policy: ${response.status}`, "API_ERROR");
1287
+ }
1288
+ return await response.json();
1289
+ } catch (error) {
1290
+ clearTimeout(timeoutId);
1291
+ if (error instanceof PolicyLoadError) {
1292
+ throw error;
1293
+ }
1294
+ if (error instanceof Error && error.name === "AbortError") {
1295
+ throw new PolicyLoadError("Policy request timeout", "TIMEOUT");
1296
+ }
1297
+ throw new PolicyLoadError(
1298
+ `Failed to load policy: ${error instanceof Error ? error.message : "Unknown error"}`,
1299
+ "NETWORK_ERROR"
1300
+ );
1301
+ }
1302
+ }
1303
+ /**
1304
+ * Cache a policy
1305
+ */
1306
+ cachePolicy(apiKey, policy) {
1307
+ if (this.cache.size >= this.config.maxCacheSize) {
1308
+ const oldestKey = this.cache.keys().next().value;
1309
+ if (oldestKey) {
1310
+ this.cache.delete(oldestKey);
1311
+ }
1312
+ }
1313
+ this.cache.set(apiKey, {
1314
+ policy,
1315
+ loadedAt: Date.now(),
1316
+ refreshing: false
1317
+ });
1318
+ }
1319
+ /**
1320
+ * Check if cached entry is expired
1321
+ */
1322
+ isExpired(entry) {
1323
+ return Date.now() - entry.loadedAt > this.config.cacheTTL;
1324
+ }
1325
+ /**
1326
+ * Check if cache entry should be refreshed
1327
+ */
1328
+ shouldRefresh(apiKey) {
1329
+ const entry = this.cache.get(apiKey);
1330
+ if (!entry) {
1331
+ return false;
1332
+ }
1333
+ const refreshThreshold = this.config.cacheTTL * 0.8;
1334
+ return Date.now() - entry.loadedAt > refreshThreshold && !entry.refreshing;
1335
+ }
1336
+ /**
1337
+ * Refresh policy in background
1338
+ */
1339
+ async refreshInBackground(apiKey) {
1340
+ const entry = this.cache.get(apiKey);
1341
+ if (!entry || entry.refreshing) {
1342
+ return;
1343
+ }
1344
+ entry.refreshing = true;
1345
+ try {
1346
+ const policy = await this.fetchPolicyFromApi(apiKey);
1347
+ this.cachePolicy(apiKey, policy);
1348
+ } catch {
1349
+ } finally {
1350
+ const currentEntry = this.cache.get(apiKey);
1351
+ if (currentEntry && currentEntry.refreshing) {
1352
+ currentEntry.refreshing = false;
1353
+ }
1354
+ }
1355
+ }
1356
+ /**
1357
+ * Get default policy for a project
1358
+ */
1359
+ getDefaultPolicy(apiKey) {
1360
+ return {
1361
+ projectId: apiKey.split("_")[1] || "unknown",
1362
+ blockThreshold: 90
1363
+ };
1364
+ }
1365
+ };
1366
+ var PolicyLoadError = class extends Error {
1367
+ constructor(message, code) {
1368
+ super(message);
1369
+ this.code = code;
1370
+ this.name = "PolicyLoadError";
1371
+ }
1372
+ };
1373
+ function createPolicyLoader(config) {
1374
+ return new PolicyLoader(config);
1375
+ }
1376
+ var RulesDetector = class {
1377
+ rules = null;
1378
+ ready = false;
1379
+ /**
1380
+ * Analyze a request and detect if it's from an agent
1381
+ */
1382
+ async detect(input) {
1383
+ await this.ensureReady();
1384
+ const reasons = [];
1385
+ let confidence = 0;
1386
+ let detectedAgentName = null;
1387
+ let verificationMethod = "none";
1388
+ const userAgent = input.userAgent || input.headers["user-agent"] || "";
1389
+ const normalizedHeaders = this.normalizeHeaders(input.headers);
1390
+ if (userAgent && this.rules) {
1391
+ const uaMatch = this.matchUserAgent(userAgent);
1392
+ if (uaMatch) {
1393
+ confidence = Math.max(confidence, uaMatch.confidence);
1394
+ detectedAgentName = uaMatch.agentName;
1395
+ verificationMethod = "pattern";
1396
+ reasons.push(`pattern:${uaMatch.agentKey}`);
1397
+ }
1398
+ }
1399
+ if (this.rules) {
1400
+ const headerMatch = this.matchHeaders(normalizedHeaders);
1401
+ if (headerMatch.confidence > 0) {
1402
+ confidence = Math.max(confidence, headerMatch.confidence);
1403
+ reasons.push(`headers:${headerMatch.count}`);
1404
+ }
1405
+ }
1406
+ if (this.hasSignatureHeaders(normalizedHeaders)) {
1407
+ confidence = Math.max(confidence, CONFIDENCE.SIGNATURE_PRESENT);
1408
+ reasons.push("signature_headers_present");
1409
+ verificationMethod = "pattern";
1410
+ }
1411
+ const isAgent = confidence > CONFIDENCE.THRESHOLD_AGENT;
1412
+ const detectionClass = this.determineDetectionClass(isAgent, detectedAgentName, confidence);
1413
+ return {
1414
+ isAgent,
1415
+ confidence,
1416
+ detectionClass,
1417
+ detectedAgent: detectedAgentName ? {
1418
+ type: this.inferAgentType(detectedAgentName),
1419
+ name: detectedAgentName
1420
+ } : void 0,
1421
+ verificationMethod,
1422
+ forgeabilityRisk: "high",
1423
+ // JS fallback is always high risk
1424
+ reasons,
1425
+ timestamp: /* @__PURE__ */ new Date()
1426
+ };
1427
+ }
1428
+ /**
1429
+ * Check if the detector is ready
1430
+ */
1431
+ isReady() {
1432
+ return this.ready;
1433
+ }
1434
+ /**
1435
+ * Ensure the detector is initialized
1436
+ */
1437
+ async ensureReady() {
1438
+ if (this.ready) {
1439
+ return;
1440
+ }
1441
+ try {
1442
+ this.rules = loadRulesSync();
1443
+ this.ready = true;
1444
+ } catch (error) {
1445
+ console.warn("[RulesDetector] Failed to load rules:", error);
1446
+ this.ready = true;
1447
+ }
1448
+ }
1449
+ /**
1450
+ * Get detector version
1451
+ */
1452
+ async getVersion() {
1453
+ return "0.1.0-js-fallback";
1454
+ }
1455
+ /**
1456
+ * Normalize headers to lowercase keys
1457
+ */
1458
+ normalizeHeaders(headers) {
1459
+ const normalized = {};
1460
+ for (const [key, value] of Object.entries(headers)) {
1461
+ normalized[key.toLowerCase()] = value;
1462
+ }
1463
+ return normalized;
1464
+ }
1465
+ /**
1466
+ * Match user agent against rules
1467
+ */
1468
+ matchUserAgent(userAgent) {
1469
+ if (!this.rules) {
1470
+ return null;
1471
+ }
1472
+ const userAgents = this.rules.rules.userAgents;
1473
+ const genericKeys = ["generic_bot", "dev_tools", "automation_tools"];
1474
+ const entries = Object.entries(userAgents).sort((a, b) => {
1475
+ const aIsGeneric = genericKeys.includes(a[0]);
1476
+ const bIsGeneric = genericKeys.includes(b[0]);
1477
+ if (aIsGeneric && !bIsGeneric) return 1;
1478
+ if (!aIsGeneric && bIsGeneric) return -1;
1479
+ return 0;
1480
+ });
1481
+ for (const [agentKey, rule] of entries) {
1482
+ for (const pattern of rule.patterns) {
1483
+ try {
1484
+ const regex = new RegExp(pattern, "i");
1485
+ if (regex.test(userAgent)) {
1486
+ return {
1487
+ // Convert 0-1 rule confidence to 0-100 scale
1488
+ confidence: rule.confidence * 100,
1489
+ agentName: this.getAgentName(agentKey),
1490
+ agentKey
1491
+ };
1492
+ }
1493
+ } catch {
1494
+ }
1495
+ }
1496
+ }
1497
+ return null;
1498
+ }
1499
+ /**
1500
+ * Match headers against suspicious header rules
1501
+ */
1502
+ matchHeaders(headers) {
1503
+ if (!this.rules) {
1504
+ return { confidence: 0, count: 0 };
1505
+ }
1506
+ const suspicious = this.rules.rules.headers.suspicious || [];
1507
+ let maxConfidence = 0;
1508
+ let count = 0;
1509
+ for (const headerRule of suspicious) {
1510
+ if (headers[headerRule.name.toLowerCase()]) {
1511
+ maxConfidence = Math.max(maxConfidence, headerRule.confidence * 100);
1512
+ count++;
1513
+ }
1514
+ }
1515
+ return { confidence: maxConfidence, count };
1516
+ }
1517
+ /**
1518
+ * Check if signature headers are present
1519
+ */
1520
+ hasSignatureHeaders(headers) {
1521
+ return !!(headers["signature"] || headers["signature-input"] || headers["signature-agent"]);
1522
+ }
1523
+ /**
1524
+ * Get human-readable agent name from rule key
1525
+ */
1526
+ getAgentName(agentKey) {
1527
+ const nameMap = {
1528
+ openai_gptbot: "ChatGPT/GPTBot",
1529
+ anthropic_claude: "Claude",
1530
+ perplexity_bot: "Perplexity",
1531
+ google_ai: "Google AI",
1532
+ microsoft_ai: "Microsoft Copilot",
1533
+ meta_ai: "Meta AI",
1534
+ cohere_bot: "Cohere",
1535
+ huggingface_bot: "HuggingFace",
1536
+ generic_bot: "Generic Bot",
1537
+ dev_tools: "Development Tool",
1538
+ automation_tools: "Automation Tool"
1539
+ };
1540
+ return nameMap[agentKey] || agentKey;
1541
+ }
1542
+ /**
1543
+ * Infer agent type from name
1544
+ */
1545
+ inferAgentType(agentName) {
1546
+ const lowerName = agentName.toLowerCase();
1547
+ if (lowerName.includes("chatgpt") || lowerName.includes("gpt")) return "openai";
1548
+ if (lowerName.includes("claude")) return "anthropic";
1549
+ if (lowerName.includes("perplexity")) return "perplexity";
1550
+ if (lowerName.includes("google")) return "google";
1551
+ if (lowerName.includes("copilot") || lowerName.includes("bing")) return "microsoft";
1552
+ return "unknown";
1553
+ }
1554
+ /**
1555
+ * Determine detection class
1556
+ */
1557
+ determineDetectionClass(isAgent, agentName, confidence) {
1558
+ if (!isAgent || confidence < CONFIDENCE.THRESHOLD_AGENT) {
1559
+ return { type: "Human" };
1560
+ }
1561
+ if (agentName) {
1562
+ const lowerName = agentName.toLowerCase();
1563
+ const aiPatterns = ["chatgpt", "gpt", "claude", "perplexity", "gemini", "copilot"];
1564
+ if (aiPatterns.some((p) => lowerName.includes(p))) {
1565
+ return { type: "AiAgent", agentType: agentName };
1566
+ }
1567
+ if (lowerName.includes("bot") || lowerName.includes("crawler")) {
1568
+ return { type: "Bot", botType: agentName };
1569
+ }
1570
+ if (lowerName.includes("automation") || lowerName.includes("tool")) {
1571
+ return { type: "Automation", toolType: agentName };
1572
+ }
1573
+ return { type: "AiAgent", agentType: agentName };
1574
+ }
1575
+ return { type: "Unknown" };
1576
+ }
1577
+ };
1578
+ function createRulesDetector() {
1579
+ return new RulesDetector();
1580
+ }
1581
+
1582
+ // src/index.ts
1583
+ function detectRuntime() {
1584
+ if (typeof globalThis !== "undefined" && "EdgeRuntime" in globalThis) {
1585
+ return "edge";
1586
+ }
1587
+ if (typeof globalThis !== "undefined" && "caches" in globalThis && typeof globalThis.caches?.default !== "undefined") {
1588
+ return "edge";
1589
+ }
1590
+ if (typeof process !== "undefined" && process.versions?.node) {
1591
+ return "node";
1592
+ }
1593
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
1594
+ return "browser";
1595
+ }
1596
+ return "unknown";
1597
+ }
1598
+ function createDetector(options = {}) {
1599
+ const runtime = detectRuntime();
1600
+ const { fallbackToJS = true, wasmLoader } = options;
1601
+ if (wasmLoader) {
1602
+ const policyLoader = options.apiKey ? new PolicyLoader({
1603
+ apiUrl: options.policyApiUrl,
1604
+ cacheTTL: options.policyTTL
1605
+ }) : void 0;
1606
+ return new WasmDetector(wasmLoader, policyLoader, options);
1607
+ }
1608
+ if (runtime === "node") {
1609
+ const loader = new DynamicWasmLoader();
1610
+ const policyLoader = options.apiKey ? new PolicyLoader({
1611
+ apiUrl: options.policyApiUrl,
1612
+ cacheTTL: options.policyTTL
1613
+ }) : void 0;
1614
+ return new WasmDetector(loader, policyLoader, options);
1615
+ }
1616
+ if (fallbackToJS) {
1617
+ return new RulesDetector();
1618
+ }
1619
+ throw new Error(
1620
+ "WASM loader required for Edge Runtime. Use createEdgeDetector() with a static WASM import, or set fallbackToJS: true."
1621
+ );
1622
+ }
1623
+ function createEdgeDetector(wasmModule, options = {}) {
1624
+ const loader = new StaticWasmLoader(wasmModule);
1625
+ const policyLoader = options.apiKey ? new PolicyLoader({
1626
+ apiUrl: options.policyApiUrl,
1627
+ cacheTTL: options.policyTTL
1628
+ }) : void 0;
1629
+ return new WasmDetector(loader, policyLoader, options);
1630
+ }
1631
+ function createFallbackDetector() {
1632
+ return new RulesDetector();
1633
+ }
1634
+
1635
+ export { CONFIDENCE, DynamicWasmLoader, PolicyLoadError, PolicyLoader, RulesDetector, StaticWasmLoader, WasmDetector, createDetector, createDynamicLoader, createEdgeDetector, createFallbackDetector, createPolicyLoader, createRulesDetector, createStaticLoader };
1636
+ //# sourceMappingURL=index.mjs.map
1637
+ //# sourceMappingURL=index.mjs.map