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