kontext-sdk 0.8.0 → 0.10.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.
package/dist/index.mjs CHANGED
@@ -1,13 +1,320 @@
1
1
  import { createHash } from 'crypto';
2
- import * as fs4 from 'fs';
3
- import * as path4 from 'path';
2
+ import * as fs5 from 'fs';
3
+ import * as path5 from 'path';
4
4
 
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
7
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6
8
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
7
9
  }) : x)(function(x) {
8
10
  if (typeof require !== "undefined") return require.apply(this, arguments);
9
11
  throw Error('Dynamic require of "' + x + '" is not supported');
10
12
  });
13
+ var __esm = (fn, res) => function __init() {
14
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
+ };
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+
21
+ // src/integrations/erc8021.ts
22
+ var erc8021_exports = {};
23
+ __export(erc8021_exports, {
24
+ KONTEXT_BUILDER_CODE: () => KONTEXT_BUILDER_CODE,
25
+ encodeERC8021Suffix: () => encodeERC8021Suffix,
26
+ fetchTransactionAttribution: () => fetchTransactionAttribution,
27
+ parseERC8021Suffix: () => parseERC8021Suffix
28
+ });
29
+ function encodeERC8021Suffix(codes) {
30
+ if (codes.length === 0) {
31
+ throw new Error("ERC-8021: at least one builder code is required");
32
+ }
33
+ const codesStr = codes.join(",");
34
+ let codesHex = "";
35
+ for (let i = 0; i < codesStr.length; i++) {
36
+ codesHex += codesStr.charCodeAt(i).toString(16).padStart(2, "0");
37
+ }
38
+ const codesLength = codesStr.length;
39
+ if (codesLength > 255) {
40
+ throw new Error("ERC-8021: combined codes length exceeds 255 bytes");
41
+ }
42
+ const codesLengthHex = codesLength.toString(16).padStart(2, "0");
43
+ const schemaId = "00";
44
+ return codesLengthHex + codesHex + schemaId + ERC_8021_MARKER;
45
+ }
46
+ function parseERC8021Suffix(calldata) {
47
+ const clean = calldata.startsWith("0x") ? calldata.slice(2) : calldata;
48
+ if (clean.length < 38) return null;
49
+ const markerStart = clean.length - 32;
50
+ const marker = clean.slice(markerStart);
51
+ if (marker !== ERC_8021_MARKER) return null;
52
+ const schemaIdStart = markerStart - 2;
53
+ const schemaId = parseInt(clean.slice(schemaIdStart, markerStart), 16);
54
+ if (isNaN(schemaId)) return null;
55
+ let codesLength = 0;
56
+ let codesLengthPos = 0;
57
+ for (let L = 1; L <= 255; L++) {
58
+ const candidatePos = schemaIdStart - L * 2 - 2;
59
+ if (candidatePos < 0) break;
60
+ const candidate = parseInt(clean.slice(candidatePos, candidatePos + 2), 16);
61
+ if (candidate === L) {
62
+ codesLength = L;
63
+ codesLengthPos = candidatePos;
64
+ break;
65
+ }
66
+ }
67
+ if (codesLength === 0) return null;
68
+ const codesHex = clean.slice(codesLengthPos + 2, codesLengthPos + 2 + codesLength * 2);
69
+ let codesStr = "";
70
+ for (let i = 0; i < codesHex.length; i += 2) {
71
+ codesStr += String.fromCharCode(parseInt(codesHex.slice(i, i + 2), 16));
72
+ }
73
+ const codes = codesStr.split(",").filter((c) => c.length > 0);
74
+ if (codes.length === 0) return null;
75
+ const rawSuffix = "0x" + clean.slice(codesLengthPos);
76
+ return { codes, schemaId, rawSuffix };
77
+ }
78
+ async function fetchTransactionAttribution(rpcUrl, txHash) {
79
+ try {
80
+ const res = await fetch(rpcUrl, {
81
+ method: "POST",
82
+ headers: { "Content-Type": "application/json" },
83
+ body: JSON.stringify({
84
+ jsonrpc: "2.0",
85
+ id: 1,
86
+ method: "eth_getTransactionByHash",
87
+ params: [txHash]
88
+ })
89
+ });
90
+ const json = await res.json();
91
+ if (json.error || !json.result?.input) return null;
92
+ return parseERC8021Suffix(json.result.input);
93
+ } catch {
94
+ return null;
95
+ }
96
+ }
97
+ var ERC_8021_MARKER, KONTEXT_BUILDER_CODE;
98
+ var init_erc8021 = __esm({
99
+ "src/integrations/erc8021.ts"() {
100
+ ERC_8021_MARKER = "80218021802180218021802180218021";
101
+ KONTEXT_BUILDER_CODE = "kontext";
102
+ }
103
+ });
104
+
105
+ // src/onchain.ts
106
+ var onchain_exports = {};
107
+ __export(onchain_exports, {
108
+ OnChainExporter: () => OnChainExporter,
109
+ anchorDigest: () => anchorDigest,
110
+ getAnchor: () => getAnchor,
111
+ verifyAnchor: () => verifyAnchor
112
+ });
113
+ async function rpcCall(rpcUrl, method, params) {
114
+ const res = await fetch(rpcUrl, {
115
+ method: "POST",
116
+ headers: { "Content-Type": "application/json" },
117
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params })
118
+ });
119
+ const json = await res.json();
120
+ if (json.error) throw new Error(`RPC error: ${json.error.message}`);
121
+ return json.result;
122
+ }
123
+ function encodeBytes32(hex) {
124
+ const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
125
+ return clean.padStart(64, "0");
126
+ }
127
+ function decodeUint256(hex) {
128
+ const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
129
+ return parseInt(clean, 16);
130
+ }
131
+ function decodeAddress(hex) {
132
+ const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
133
+ return "0x" + clean.slice(24);
134
+ }
135
+ async function verifyAnchor(rpcUrl, contractAddress, digest) {
136
+ const calldata = SEL_VERIFY + encodeBytes32(digest);
137
+ const result = await rpcCall(rpcUrl, "eth_call", [
138
+ { to: contractAddress, data: calldata },
139
+ "latest"
140
+ ]);
141
+ const anchored = decodeUint256(result) !== 0;
142
+ return { anchored, digest };
143
+ }
144
+ async function getAnchor(rpcUrl, contractAddress, digest) {
145
+ const calldata = SEL_GET_ANCHOR + encodeBytes32(digest);
146
+ try {
147
+ const result = await rpcCall(rpcUrl, "eth_call", [
148
+ { to: contractAddress, data: calldata },
149
+ "latest"
150
+ ]);
151
+ const clean = result.startsWith("0x") ? result.slice(2) : result;
152
+ if (clean.length < 192) return null;
153
+ const anchorer = decodeAddress(clean.slice(0, 64));
154
+ const projectHash = "0x" + clean.slice(64, 128);
155
+ const timestamp = decodeUint256("0x" + clean.slice(128, 192));
156
+ return { anchorer, projectHash, timestamp };
157
+ } catch {
158
+ return null;
159
+ }
160
+ }
161
+ async function anchorDigest(config, digest, projectId) {
162
+ let viem;
163
+ let viemChains;
164
+ let viemAccounts;
165
+ try {
166
+ viem = await import('viem');
167
+ viemChains = await import('viem/chains');
168
+ viemAccounts = await import('viem/accounts');
169
+ } catch {
170
+ throw new Error(
171
+ "On-chain anchoring requires viem. Install it: npm install viem"
172
+ );
173
+ }
174
+ if (!config.privateKey) {
175
+ throw new Error("privateKey is required for on-chain anchoring");
176
+ }
177
+ const account = viemAccounts.privateKeyToAccount(config.privateKey);
178
+ const chain = config.rpcUrl.includes("sepolia") ? viemChains.baseSepolia : viemChains.base;
179
+ const client = viem.createWalletClient({
180
+ account,
181
+ chain,
182
+ transport: viem.http(config.rpcUrl)
183
+ });
184
+ const publicClient = viem.createPublicClient({
185
+ chain,
186
+ transport: viem.http(config.rpcUrl)
187
+ });
188
+ const projectHash = viem.keccak256(viem.toBytes(projectId));
189
+ const digestBytes32 = digest.startsWith("0x") ? digest : `0x${digest}`;
190
+ const abi = [
191
+ {
192
+ name: "anchor",
193
+ type: "function",
194
+ stateMutability: "nonpayable",
195
+ inputs: [
196
+ { name: "digest", type: "bytes32" },
197
+ { name: "projectHash", type: "bytes32" }
198
+ ],
199
+ outputs: []
200
+ }
201
+ ];
202
+ const { encodeERC8021Suffix: encodeERC8021Suffix2, KONTEXT_BUILDER_CODE: KONTEXT_BUILDER_CODE2 } = await Promise.resolve().then(() => (init_erc8021(), erc8021_exports));
203
+ const calldata = viem.encodeFunctionData({
204
+ abi,
205
+ functionName: "anchor",
206
+ args: [digestBytes32, projectHash]
207
+ });
208
+ const builderCode = config.builderCode ?? KONTEXT_BUILDER_CODE2;
209
+ const suffix = encodeERC8021Suffix2([builderCode]);
210
+ const txHash = await client.sendTransaction({
211
+ to: config.contractAddress,
212
+ data: calldata + suffix
213
+ });
214
+ const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
215
+ return {
216
+ digest,
217
+ txHash,
218
+ blockNumber: Number(receipt.blockNumber),
219
+ timestamp: Math.floor(Date.now() / 1e3),
220
+ contractAddress: config.contractAddress,
221
+ chain: chain.name.toLowerCase()
222
+ };
223
+ }
224
+ var SEL_VERIFY, SEL_GET_ANCHOR, OnChainExporter;
225
+ var init_onchain = __esm({
226
+ "src/onchain.ts"() {
227
+ SEL_VERIFY = "0x75e36616";
228
+ SEL_GET_ANCHOR = "0x7feb51d9";
229
+ OnChainExporter = class {
230
+ config;
231
+ projectId;
232
+ batchSize;
233
+ getTerminalDigest;
234
+ eventCount = 0;
235
+ constructor(config, projectId, getTerminalDigest) {
236
+ this.config = config;
237
+ this.projectId = projectId;
238
+ this.batchSize = 10;
239
+ this.getTerminalDigest = getTerminalDigest;
240
+ }
241
+ async export(events) {
242
+ this.eventCount += events.length;
243
+ if (this.eventCount >= this.batchSize) {
244
+ const digest = this.getTerminalDigest();
245
+ await anchorDigest(this.config, digest, this.projectId);
246
+ this.eventCount = 0;
247
+ }
248
+ return { success: true, exportedCount: events.length };
249
+ }
250
+ async flush() {
251
+ if (this.eventCount > 0) {
252
+ const digest = this.getTerminalDigest();
253
+ await anchorDigest(this.config, digest, this.projectId);
254
+ this.eventCount = 0;
255
+ }
256
+ }
257
+ async shutdown() {
258
+ await this.flush();
259
+ }
260
+ };
261
+ }
262
+ });
263
+
264
+ // src/attestation.ts
265
+ var attestation_exports = {};
266
+ __export(attestation_exports, {
267
+ exchangeAttestation: () => exchangeAttestation,
268
+ fetchAgentCard: () => fetchAgentCard
269
+ });
270
+ async function fetchAgentCard(endpoint, timeoutMs = DEFAULT_TIMEOUT_MS) {
271
+ const url = `${endpoint.replace(/\/$/, "")}/.well-known/kontext.json`;
272
+ const response = await fetch(url, {
273
+ signal: AbortSignal.timeout(timeoutMs),
274
+ headers: { Accept: "application/json" }
275
+ });
276
+ if (!response.ok) {
277
+ throw new Error(`Failed to fetch agent card from ${url}: ${response.status}`);
278
+ }
279
+ return response.json();
280
+ }
281
+ async function exchangeAttestation(config, request) {
282
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
283
+ const card = await fetchAgentCard(config.endpoint, timeoutMs);
284
+ if (config.agentId && card.agentId !== config.agentId) {
285
+ throw new Error(
286
+ `Agent ID mismatch: expected ${config.agentId}, got ${card.agentId}`
287
+ );
288
+ }
289
+ if (!card.capabilities.includes("attest")) {
290
+ throw new Error(
291
+ `Counterparty ${card.agentId} does not support attestation`
292
+ );
293
+ }
294
+ const attestUrl = `${config.endpoint.replace(/\/$/, "")}${card.attestEndpoint}`;
295
+ const response = await fetch(attestUrl, {
296
+ method: "POST",
297
+ headers: { "Content-Type": "application/json" },
298
+ body: JSON.stringify(request),
299
+ signal: AbortSignal.timeout(timeoutMs)
300
+ });
301
+ if (!response.ok) {
302
+ throw new Error(`Attestation request failed: ${response.status}`);
303
+ }
304
+ const result = await response.json();
305
+ return {
306
+ attested: result.attested,
307
+ digest: result.receiverDigest,
308
+ agentId: result.receiverAgentId,
309
+ timestamp: result.timestamp
310
+ };
311
+ }
312
+ var DEFAULT_TIMEOUT_MS;
313
+ var init_attestation = __esm({
314
+ "src/attestation.ts"() {
315
+ DEFAULT_TIMEOUT_MS = 1e4;
316
+ }
317
+ });
11
318
 
12
319
  // src/utils.ts
13
320
  function generateId() {
@@ -912,13 +1219,17 @@ var STORAGE_KEYS = {
912
1219
  actions: "kontext:actions",
913
1220
  transactions: "kontext:transactions",
914
1221
  tasks: "kontext:tasks",
915
- anomalies: "kontext:anomalies"
1222
+ anomalies: "kontext:anomalies",
1223
+ sessions: "kontext:sessions",
1224
+ checkpoints: "kontext:checkpoints"
916
1225
  };
917
1226
  var KontextStore = class {
918
1227
  actions = [];
919
1228
  transactions = [];
920
1229
  tasks = /* @__PURE__ */ new Map();
921
1230
  anomalies = [];
1231
+ sessions = /* @__PURE__ */ new Map();
1232
+ checkpoints = /* @__PURE__ */ new Map();
922
1233
  storageAdapter = null;
923
1234
  maxEntries;
924
1235
  constructor(maxEntries = DEFAULT_MAX_ENTRIES) {
@@ -951,11 +1262,15 @@ var KontextStore = class {
951
1262
  const transactionsSnapshot = [...this.transactions];
952
1263
  const tasksSnapshot = Array.from(this.tasks.entries());
953
1264
  const anomaliesSnapshot = [...this.anomalies];
1265
+ const sessionsSnapshot = Array.from(this.sessions.entries());
1266
+ const checkpointsSnapshot = Array.from(this.checkpoints.entries());
954
1267
  await Promise.all([
955
1268
  this.storageAdapter.save(STORAGE_KEYS.actions, actionsSnapshot),
956
1269
  this.storageAdapter.save(STORAGE_KEYS.transactions, transactionsSnapshot),
957
1270
  this.storageAdapter.save(STORAGE_KEYS.tasks, tasksSnapshot),
958
- this.storageAdapter.save(STORAGE_KEYS.anomalies, anomaliesSnapshot)
1271
+ this.storageAdapter.save(STORAGE_KEYS.anomalies, anomaliesSnapshot),
1272
+ this.storageAdapter.save(STORAGE_KEYS.sessions, sessionsSnapshot),
1273
+ this.storageAdapter.save(STORAGE_KEYS.checkpoints, checkpointsSnapshot)
959
1274
  ]);
960
1275
  }
961
1276
  /**
@@ -965,11 +1280,13 @@ var KontextStore = class {
965
1280
  */
966
1281
  async restore() {
967
1282
  if (!this.storageAdapter) return;
968
- const [actions, transactions, tasksEntries, anomalies] = await Promise.all([
1283
+ const [actions, transactions, tasksEntries, anomalies, sessionsEntries, checkpointsEntries] = await Promise.all([
969
1284
  this.storageAdapter.load(STORAGE_KEYS.actions),
970
1285
  this.storageAdapter.load(STORAGE_KEYS.transactions),
971
1286
  this.storageAdapter.load(STORAGE_KEYS.tasks),
972
- this.storageAdapter.load(STORAGE_KEYS.anomalies)
1287
+ this.storageAdapter.load(STORAGE_KEYS.anomalies),
1288
+ this.storageAdapter.load(STORAGE_KEYS.sessions),
1289
+ this.storageAdapter.load(STORAGE_KEYS.checkpoints)
973
1290
  ]);
974
1291
  if (Array.isArray(actions)) {
975
1292
  this.actions = actions;
@@ -983,6 +1300,12 @@ var KontextStore = class {
983
1300
  if (Array.isArray(anomalies)) {
984
1301
  this.anomalies = anomalies;
985
1302
  }
1303
+ if (Array.isArray(sessionsEntries)) {
1304
+ this.sessions = new Map(sessionsEntries);
1305
+ }
1306
+ if (Array.isArray(checkpointsEntries)) {
1307
+ this.checkpoints = new Map(checkpointsEntries);
1308
+ }
986
1309
  }
987
1310
  // --------------------------------------------------------------------------
988
1311
  // Actions
@@ -1082,6 +1405,60 @@ var KontextStore = class {
1082
1405
  return this.anomalies.filter(predicate);
1083
1406
  }
1084
1407
  // --------------------------------------------------------------------------
1408
+ // Sessions (Provenance Layer 1)
1409
+ // --------------------------------------------------------------------------
1410
+ /** Store a session. */
1411
+ addSession(session) {
1412
+ this.sessions.set(session.sessionId, session);
1413
+ }
1414
+ /** Retrieve a session by ID. */
1415
+ getSession(sessionId) {
1416
+ return this.sessions.get(sessionId);
1417
+ }
1418
+ /** Update a session. */
1419
+ updateSession(sessionId, updates) {
1420
+ const existing = this.sessions.get(sessionId);
1421
+ if (!existing) return void 0;
1422
+ const updated = { ...existing, ...updates };
1423
+ this.sessions.set(sessionId, updated);
1424
+ return updated;
1425
+ }
1426
+ /** Retrieve all sessions. */
1427
+ getSessions() {
1428
+ return Array.from(this.sessions.values());
1429
+ }
1430
+ /** Retrieve sessions filtered by a predicate. */
1431
+ querySessions(predicate) {
1432
+ return Array.from(this.sessions.values()).filter(predicate);
1433
+ }
1434
+ // --------------------------------------------------------------------------
1435
+ // Checkpoints (Provenance Layer 3)
1436
+ // --------------------------------------------------------------------------
1437
+ /** Store a checkpoint. */
1438
+ addCheckpoint(checkpoint) {
1439
+ this.checkpoints.set(checkpoint.id, checkpoint);
1440
+ }
1441
+ /** Retrieve a checkpoint by ID. */
1442
+ getCheckpoint(checkpointId) {
1443
+ return this.checkpoints.get(checkpointId);
1444
+ }
1445
+ /** Update a checkpoint. */
1446
+ updateCheckpoint(checkpointId, updates) {
1447
+ const existing = this.checkpoints.get(checkpointId);
1448
+ if (!existing) return void 0;
1449
+ const updated = { ...existing, ...updates };
1450
+ this.checkpoints.set(checkpointId, updated);
1451
+ return updated;
1452
+ }
1453
+ /** Retrieve all checkpoints. */
1454
+ getCheckpoints() {
1455
+ return Array.from(this.checkpoints.values());
1456
+ }
1457
+ /** Retrieve checkpoints filtered by a predicate. */
1458
+ queryCheckpoints(predicate) {
1459
+ return Array.from(this.checkpoints.values()).filter(predicate);
1460
+ }
1461
+ // --------------------------------------------------------------------------
1085
1462
  // Utilities
1086
1463
  // --------------------------------------------------------------------------
1087
1464
  /** Get total record counts across all stores. */
@@ -1090,7 +1467,9 @@ var KontextStore = class {
1090
1467
  actions: this.actions.length,
1091
1468
  transactions: this.transactions.length,
1092
1469
  tasks: this.tasks.size,
1093
- anomalies: this.anomalies.length
1470
+ anomalies: this.anomalies.length,
1471
+ sessions: this.sessions.size,
1472
+ checkpoints: this.checkpoints.size
1094
1473
  };
1095
1474
  }
1096
1475
  /** Clear all stored data. Useful for testing. */
@@ -1099,6 +1478,8 @@ var KontextStore = class {
1099
1478
  this.transactions = [];
1100
1479
  this.tasks.clear();
1101
1480
  this.anomalies = [];
1481
+ this.sessions.clear();
1482
+ this.checkpoints.clear();
1102
1483
  }
1103
1484
  };
1104
1485
  var DIGEST_EXCLUDED_FIELDS = /* @__PURE__ */ new Set(["digest", "priorDigest"]);
@@ -1570,13 +1951,13 @@ var ActionLogger = class {
1570
1951
  }
1571
1952
  flushToFile(actions) {
1572
1953
  const outputDir = this.config.localOutputDir ?? ".kontext";
1573
- const logDir = path4.join(outputDir, "logs");
1954
+ const logDir = path5.join(outputDir, "logs");
1574
1955
  try {
1575
- fs4.mkdirSync(logDir, { recursive: true });
1956
+ fs5.mkdirSync(logDir, { recursive: true });
1576
1957
  const filename = `actions-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.jsonl`;
1577
- const filePath = path4.join(logDir, filename);
1958
+ const filePath = path5.join(logDir, filename);
1578
1959
  const lines = actions.map((a) => JSON.stringify(a)).join("\n") + "\n";
1579
- fs4.appendFileSync(filePath, lines, "utf-8");
1960
+ fs5.appendFileSync(filePath, lines, "utf-8");
1580
1961
  } catch (error) {
1581
1962
  this.emitLog("warn", "Failed to write log file", { error });
1582
1963
  }
@@ -2116,17 +2497,9 @@ var AuditExporter = class {
2116
2497
  return sections.join("\n\n");
2117
2498
  }
2118
2499
  };
2119
- var USDC_CONTRACTS = {
2120
- ethereum: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
2121
- base: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
2122
- polygon: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
2123
- arbitrum: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
2124
- optimism: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",
2125
- // Arc (Circle's stablecoin-native blockchain) -- placeholder address, update when Arc mainnet launches
2126
- arc: "0xa0c0000000000000000000000000000000000001"
2127
- };
2128
- var SANCTIONED_ADDRESSES = [
2129
- // --- ACTIVELY SANCTIONED (SDN) ---
2500
+
2501
+ // src/integrations/data/ofac-addresses.ts
2502
+ var OFAC_SDN_ACTIVE_ADDRESSES = [
2130
2503
  // Lazarus Group / DPRK (Ronin Bridge hack)
2131
2504
  "0x098B716B8Aaf21512996dC57EB0615e2383E2f96",
2132
2505
  "0xa0e1c89Ef1a489c9C7dE96311eD5Ce5D32c20E4B",
@@ -2150,8 +2523,9 @@ var SANCTIONED_ADDRESSES = [
2150
2523
  "0x931546D9e66836AbF687d2bc64B30407bAc8C568",
2151
2524
  "0x43fa21d92141BA9db43052492E0DeEE5aa5f0A93",
2152
2525
  // Zedcex / Zedxion (IRGC-linked, sanctioned June 2024)
2153
- "0xaeAAc358560e11f52454D997AAFF2c5731B6f8a6",
2154
- // --- DELISTED (formerly sanctioned, retained for backward compat) ---
2526
+ "0xaeAAc358560e11f52454D997AAFF2c5731B6f8a6"
2527
+ ];
2528
+ var OFAC_SDN_DELISTED_ADDRESSES = [
2155
2529
  // Tornado Cash contracts (sanctioned Aug 2022, DELISTED March 21, 2025)
2156
2530
  "0xd90e2f925DA726b50C4Ed8D0Fb90Ad053324F31b",
2157
2531
  "0xd96f2B1c14Db8458374d9Aca76E26c3D18364307",
@@ -2173,15 +2547,29 @@ var SANCTIONED_ADDRESSES = [
2173
2547
  "0x722122dF12D4e14e13Ac3b6895a86e84145b6967"
2174
2548
  // Tornado Cash / Sinbad.io
2175
2549
  ];
2550
+ var OFAC_SDN_ADDRESSES = [
2551
+ ...OFAC_SDN_ACTIVE_ADDRESSES,
2552
+ ...OFAC_SDN_DELISTED_ADDRESSES
2553
+ ];
2554
+ var USDC_CONTRACTS = {
2555
+ ethereum: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
2556
+ base: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
2557
+ polygon: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
2558
+ arbitrum: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
2559
+ optimism: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",
2560
+ // Arc (Circle's stablecoin-native blockchain) -- placeholder address, update when Arc mainnet launches
2561
+ arc: "0xa0c0000000000000000000000000000000000001"
2562
+ };
2563
+ var SANCTIONED_ADDRESSES = [...OFAC_SDN_ADDRESSES];
2176
2564
  var SANCTIONED_SET = new Set(
2177
2565
  SANCTIONED_ADDRESSES.map((addr) => addr.toLowerCase())
2178
2566
  );
2179
2567
  function loadCachedSDN() {
2180
2568
  try {
2181
2569
  const dataDir = process.env["KONTEXT_DATA_DIR"] || ".kontext";
2182
- const cachePath = path4.join(dataDir, "ofac-sdn-cache.json");
2183
- if (fs4.existsSync(cachePath)) {
2184
- const cache = JSON.parse(fs4.readFileSync(cachePath, "utf-8"));
2570
+ const cachePath = path5.join(dataDir, "ofac-sdn-cache.json");
2571
+ if (fs5.existsSync(cachePath)) {
2572
+ const cache = JSON.parse(fs5.readFileSync(cachePath, "utf-8"));
2185
2573
  if (Array.isArray(cache.addresses)) {
2186
2574
  for (const addr of cache.addresses) {
2187
2575
  SANCTIONED_SET.add(String(addr).toLowerCase());
@@ -2668,11 +3056,301 @@ var PaymentCompliance = class _PaymentCompliance {
2668
3056
  }
2669
3057
  };
2670
3058
 
3059
+ // src/integrations/screening-provider.ts
3060
+ var ETH_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;
3061
+ function isBlockchainAddress(query) {
3062
+ return ETH_ADDRESS_RE.test(query);
3063
+ }
3064
+ function providerSupportsQuery(provider, query) {
3065
+ const isAddr = isBlockchainAddress(query);
3066
+ if (isAddr) {
3067
+ return provider.queryTypes.includes("address") || provider.queryTypes.includes("both");
3068
+ }
3069
+ return provider.queryTypes.includes("entity_name") || provider.queryTypes.includes("both");
3070
+ }
3071
+ var TOKEN_REQUIRED_LISTS = {
3072
+ USDC: ["OFAC_SDN"],
3073
+ EURC: ["EU_CONSOLIDATED"],
3074
+ USDT: ["OFAC_SDN", "EU_CONSOLIDATED"],
3075
+ DAI: ["OFAC_SDN", "EU_CONSOLIDATED"],
3076
+ USDP: ["OFAC_SDN"],
3077
+ USDG: ["OFAC_SDN"]
3078
+ };
3079
+ var CURRENCY_REQUIRED_LISTS = {
3080
+ USD: ["OFAC_SDN"],
3081
+ EUR: ["EU_CONSOLIDATED"],
3082
+ GBP: ["UK_OFSI"],
3083
+ AED: ["UAE_LOCAL", "UN_SECURITY_COUNCIL"],
3084
+ INR: ["UN_SECURITY_COUNCIL", "INDIA_DOMESTIC"],
3085
+ SGD: ["MAS_TFS", "UN_SECURITY_COUNCIL"],
3086
+ CNY: ["UN_SECURITY_COUNCIL"],
3087
+ CNH: ["UN_SECURITY_COUNCIL"],
3088
+ HKD: ["HK_UNSO", "UN_SECURITY_COUNCIL"],
3089
+ NZD: ["UN_SECURITY_COUNCIL", "NZ_DESIGNATED"],
3090
+ KRW: ["UN_SECURITY_COUNCIL", "KOFIU_DOMESTIC"],
3091
+ MYR: ["BNM_DOMESTIC", "UN_SECURITY_COUNCIL"],
3092
+ THB: ["UN_SECURITY_COUNCIL", "AMLO_DOMESTIC"]
3093
+ };
3094
+ var DEFAULT_REQUIRED_LISTS = [
3095
+ "OFAC_SDN",
3096
+ "EU_CONSOLIDATED",
3097
+ "UN_SECURITY_COUNCIL"
3098
+ ];
3099
+ function getRequiredLists(context) {
3100
+ if (!context) return DEFAULT_REQUIRED_LISTS;
3101
+ if (context.token && typeof context.token === "string") {
3102
+ const tokenLists = TOKEN_REQUIRED_LISTS[context.token];
3103
+ if (tokenLists) return tokenLists;
3104
+ }
3105
+ if (context.currency && typeof context.currency === "string") {
3106
+ const currencyLists = CURRENCY_REQUIRED_LISTS[context.currency];
3107
+ if (currencyLists) return currencyLists;
3108
+ }
3109
+ return DEFAULT_REQUIRED_LISTS;
3110
+ }
3111
+
3112
+ // src/integrations/screening-aggregator.ts
3113
+ var ScreeningAggregator = class {
3114
+ providers;
3115
+ consensus;
3116
+ blocklistSet;
3117
+ allowlistSet;
3118
+ continueOnError;
3119
+ providerTimeoutMs;
3120
+ onEvent;
3121
+ constructor(config) {
3122
+ this.providers = config.providers;
3123
+ this.consensus = config.consensus ?? "ANY_MATCH";
3124
+ this.blocklistSet = new Set(
3125
+ (config.blocklist ?? []).map((s) => s.toLowerCase())
3126
+ );
3127
+ this.allowlistSet = new Set(
3128
+ (config.allowlist ?? []).map((s) => s.toLowerCase())
3129
+ );
3130
+ this.continueOnError = config.continueOnError ?? true;
3131
+ this.providerTimeoutMs = config.providerTimeoutMs;
3132
+ this.onEvent = config.onEvent;
3133
+ }
3134
+ /**
3135
+ * Screen a single query (address or entity name).
3136
+ */
3137
+ async screen(query, context) {
3138
+ const start = Date.now();
3139
+ const queryLower = query.toLowerCase();
3140
+ const queryType = isBlockchainAddress(query) ? "address" : "entity_name";
3141
+ this.onEvent?.();
3142
+ if (this.allowlistSet.has(queryLower)) {
3143
+ return this.buildResult({
3144
+ queryType,
3145
+ start,
3146
+ allowlisted: true,
3147
+ context
3148
+ });
3149
+ }
3150
+ if (this.blocklistSet.has(queryLower)) {
3151
+ return this.buildResult({
3152
+ queryType,
3153
+ start,
3154
+ blocklisted: true,
3155
+ context
3156
+ });
3157
+ }
3158
+ const compatibleProviders = this.providers.filter(
3159
+ (p) => p.isAvailable() && providerSupportsQuery(p, query)
3160
+ );
3161
+ if (compatibleProviders.length === 0) {
3162
+ return this.buildResult({
3163
+ queryType,
3164
+ start,
3165
+ providerResults: [],
3166
+ context
3167
+ });
3168
+ }
3169
+ const results = [];
3170
+ const errors = [];
3171
+ const promises = compatibleProviders.map(async (provider) => {
3172
+ try {
3173
+ const result = await this.runWithTimeout(provider, query, context);
3174
+ return { type: "success", result };
3175
+ } catch (err) {
3176
+ const errorMsg = err instanceof Error ? err.message : String(err);
3177
+ return { type: "error", providerId: provider.id, error: errorMsg };
3178
+ }
3179
+ });
3180
+ const settled = await Promise.all(promises);
3181
+ for (const outcome of settled) {
3182
+ if (outcome.type === "success") {
3183
+ results.push(outcome.result);
3184
+ } else {
3185
+ if (!this.continueOnError) {
3186
+ throw new Error(outcome.error);
3187
+ }
3188
+ errors.push({ providerId: outcome.providerId, error: outcome.error });
3189
+ }
3190
+ }
3191
+ return this.buildResult({
3192
+ queryType,
3193
+ start,
3194
+ providerResults: results,
3195
+ errors,
3196
+ context
3197
+ });
3198
+ }
3199
+ /**
3200
+ * Screen multiple queries in batch.
3201
+ */
3202
+ async screenBatch(queries, context) {
3203
+ const results = /* @__PURE__ */ new Map();
3204
+ const promises = queries.map(async (query) => {
3205
+ const result = await this.screen(query, context);
3206
+ return { query, result };
3207
+ });
3208
+ const settled = await Promise.all(promises);
3209
+ for (const { query, result } of settled) {
3210
+ results.set(query, result);
3211
+ }
3212
+ return results;
3213
+ }
3214
+ /**
3215
+ * Get available providers, optionally filtered by query type.
3216
+ */
3217
+ getAvailableProviders(queryType) {
3218
+ return this.providers.filter((p) => {
3219
+ if (!p.isAvailable()) return false;
3220
+ if (!queryType) return true;
3221
+ return p.queryTypes.includes(queryType) || p.queryTypes.includes("both");
3222
+ });
3223
+ }
3224
+ /**
3225
+ * Get the union of all sanctions lists covered by available providers.
3226
+ */
3227
+ getCoveredLists() {
3228
+ const lists = /* @__PURE__ */ new Set();
3229
+ for (const p of this.providers) {
3230
+ if (p.isAvailable()) {
3231
+ for (const list of p.lists) {
3232
+ lists.add(list);
3233
+ }
3234
+ }
3235
+ }
3236
+ return Array.from(lists);
3237
+ }
3238
+ // --------------------------------------------------------------------------
3239
+ // Private
3240
+ // --------------------------------------------------------------------------
3241
+ async runWithTimeout(provider, query, context) {
3242
+ if (!this.providerTimeoutMs) {
3243
+ return provider.screen(query, context);
3244
+ }
3245
+ return Promise.race([
3246
+ provider.screen(query, context),
3247
+ new Promise(
3248
+ (_, reject) => setTimeout(
3249
+ () => reject(new Error(`Provider ${provider.id} timed out after ${this.providerTimeoutMs}ms`)),
3250
+ this.providerTimeoutMs
3251
+ )
3252
+ )
3253
+ ]);
3254
+ }
3255
+ buildResult(opts) {
3256
+ const {
3257
+ queryType,
3258
+ start,
3259
+ providerResults = [],
3260
+ errors = [],
3261
+ blocklisted = false,
3262
+ allowlisted = false,
3263
+ context
3264
+ } = opts;
3265
+ if (blocklisted) {
3266
+ return {
3267
+ providerId: "aggregator",
3268
+ hit: true,
3269
+ matches: [],
3270
+ listsChecked: [],
3271
+ entriesSearched: 0,
3272
+ durationMs: Date.now() - start,
3273
+ queryType,
3274
+ totalProviders: 0,
3275
+ hitCount: 0,
3276
+ consensus: this.consensus,
3277
+ blocklisted: true,
3278
+ errors: [],
3279
+ uncoveredLists: [],
3280
+ providerResults: []
3281
+ };
3282
+ }
3283
+ if (allowlisted) {
3284
+ return {
3285
+ providerId: "aggregator",
3286
+ hit: false,
3287
+ matches: [],
3288
+ listsChecked: [],
3289
+ entriesSearched: 0,
3290
+ durationMs: Date.now() - start,
3291
+ queryType,
3292
+ totalProviders: 0,
3293
+ hitCount: 0,
3294
+ consensus: this.consensus,
3295
+ allowlisted: true,
3296
+ errors: [],
3297
+ uncoveredLists: [],
3298
+ providerResults: []
3299
+ };
3300
+ }
3301
+ const allMatches = [];
3302
+ const allListsChecked = /* @__PURE__ */ new Set();
3303
+ let totalEntries = 0;
3304
+ for (const r of providerResults) {
3305
+ allMatches.push(...r.matches);
3306
+ for (const list of r.listsChecked) {
3307
+ allListsChecked.add(list);
3308
+ }
3309
+ totalEntries += r.entriesSearched;
3310
+ }
3311
+ const hitCount = providerResults.filter((r) => r.hit).length;
3312
+ const totalProviders = providerResults.length;
3313
+ let hit;
3314
+ switch (this.consensus) {
3315
+ case "ALL_MATCH":
3316
+ hit = totalProviders > 0 && hitCount === totalProviders;
3317
+ break;
3318
+ case "MAJORITY":
3319
+ hit = totalProviders > 0 && hitCount > totalProviders / 2;
3320
+ break;
3321
+ case "ANY_MATCH":
3322
+ default:
3323
+ hit = hitCount > 0;
3324
+ break;
3325
+ }
3326
+ const requiredLists = getRequiredLists(context);
3327
+ const coveredLists = allListsChecked;
3328
+ const uncoveredLists = requiredLists.filter(
3329
+ (l) => !coveredLists.has(l)
3330
+ );
3331
+ return {
3332
+ providerId: "aggregator",
3333
+ hit,
3334
+ matches: allMatches,
3335
+ listsChecked: Array.from(allListsChecked),
3336
+ entriesSearched: totalEntries,
3337
+ durationMs: Date.now() - start,
3338
+ queryType,
3339
+ totalProviders,
3340
+ hitCount,
3341
+ consensus: this.consensus,
3342
+ errors,
3343
+ uncoveredLists,
3344
+ providerResults
3345
+ };
3346
+ }
3347
+ };
3348
+
2671
3349
  // src/plans.ts
2672
3350
  var PLAN_LIMITS = {
2673
3351
  free: 2e4,
2674
- pro: 1e5,
2675
- // per user/seat
3352
+ pro: Infinity,
3353
+ // usage-based: $2/1K events above 20K free
2676
3354
  enterprise: Infinity
2677
3355
  };
2678
3356
  var DEFAULT_WARNING_THRESHOLD = 0.8;
@@ -2719,10 +3397,7 @@ var PlanManager = class _PlanManager {
2719
3397
  }
2720
3398
  /** Get the event limit for the current plan (Pro is multiplied by seats) */
2721
3399
  getLimit() {
2722
- const base = PLAN_LIMITS[this.tier];
2723
- if (base === Infinity) return Infinity;
2724
- if (this.tier === "pro") return base * this.seats;
2725
- return base;
3400
+ return PLAN_LIMITS[this.tier];
2726
3401
  }
2727
3402
  /** Get the current number of seats */
2728
3403
  getSeats() {
@@ -2927,12 +3602,7 @@ var PlanManager = class _PlanManager {
2927
3602
  logLimitMessage() {
2928
3603
  if (this.tier === "free") {
2929
3604
  console.warn(
2930
- `You've reached the 20,000 event limit on the Free plan. Upgrade to Pro for 100K events/user/mo and full compliance features \u2192 ${this.upgradeUrl}`
2931
- );
2932
- } else if (this.tier === "pro") {
2933
- const effectiveLimit = (1e5 * this.seats).toLocaleString();
2934
- console.warn(
2935
- `You've reached the ${effectiveLimit} event limit on Pro (${this.seats} seat${this.seats !== 1 ? "s" : ""}). Add seats or contact us for Enterprise pricing \u2192 ${this.enterpriseContactUrl}`
3605
+ `You've reached the 20,000 event limit on the Free plan. Upgrade to Pro ($2/1K events above 20K free) \u2192 ${this.upgradeUrl}`
2936
3606
  );
2937
3607
  }
2938
3608
  }
@@ -3020,7 +3690,7 @@ var JsonFileExporter = class {
3020
3690
  buffer = [];
3021
3691
  bufferSize;
3022
3692
  constructor(options) {
3023
- this.outputDir = path4.resolve(options?.outputDir ?? ".kontext/exports");
3693
+ this.outputDir = path5.resolve(options?.outputDir ?? ".kontext/exports");
3024
3694
  this.bufferSize = options?.bufferSize ?? 1;
3025
3695
  }
3026
3696
  async export(events) {
@@ -3035,11 +3705,11 @@ var JsonFileExporter = class {
3035
3705
  const toWrite = [...this.buffer];
3036
3706
  this.buffer = [];
3037
3707
  try {
3038
- fs4.mkdirSync(this.outputDir, { recursive: true });
3708
+ fs5.mkdirSync(this.outputDir, { recursive: true });
3039
3709
  const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
3040
- const filePath = path4.join(this.outputDir, `events-${date}.jsonl`);
3710
+ const filePath = path5.join(this.outputDir, `events-${date}.jsonl`);
3041
3711
  const lines = toWrite.map((e) => JSON.stringify(e)).join("\n") + "\n";
3042
- fs4.appendFileSync(filePath, lines, "utf-8");
3712
+ fs5.appendFileSync(filePath, lines, "utf-8");
3043
3713
  } catch (error) {
3044
3714
  console.warn("[Kontext JsonFileExporter] Failed to write events:", error);
3045
3715
  }
@@ -3209,61 +3879,1820 @@ function extractDocumentId(resourceName) {
3209
3879
  const parts = resourceName.split("/");
3210
3880
  return parts[parts.length - 1] ?? resourceName;
3211
3881
  }
3882
+ var CONFIG_FILENAME = "kontext.config.json";
3883
+ function loadConfigFile(startDir) {
3884
+ const dir = startDir ?? process.cwd();
3885
+ const filePath = findConfigFile(dir);
3886
+ if (!filePath) return null;
3887
+ try {
3888
+ const raw = fs5.readFileSync(filePath, "utf-8");
3889
+ const parsed = JSON.parse(raw);
3890
+ if (!parsed.projectId || typeof parsed.projectId !== "string") {
3891
+ return null;
3892
+ }
3893
+ return parsed;
3894
+ } catch {
3895
+ return null;
3896
+ }
3897
+ }
3898
+ function findConfigFile(dir) {
3899
+ let current = path5.resolve(dir);
3900
+ const root = path5.parse(current).root;
3901
+ while (true) {
3902
+ const candidate = path5.join(current, CONFIG_FILENAME);
3903
+ if (fs5.existsSync(candidate)) {
3904
+ return candidate;
3905
+ }
3906
+ const parent = path5.dirname(current);
3907
+ if (parent === current || current === root) {
3908
+ return null;
3909
+ }
3910
+ current = parent;
3911
+ }
3912
+ }
3212
3913
 
3213
- // src/client.ts
3214
- var PLAN_STORAGE_KEY = "kontext:plan";
3215
- var Kontext = class _Kontext {
3914
+ // src/integrations/data/stablecoin-contracts.ts
3915
+ var STABLECOIN_CONTRACTS = {
3916
+ // USDC (6 decimals)
3917
+ "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48": { token: "USDC", chain: "ethereum", decimals: 6 },
3918
+ "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913": { token: "USDC", chain: "base", decimals: 6 },
3919
+ "0x3c499c542cef5e3811e1192ce70d8cc03d5c3359": { token: "USDC", chain: "polygon", decimals: 6 },
3920
+ "0xaf88d065e77c8cc2239327c5edb3a432268e5831": { token: "USDC", chain: "arbitrum", decimals: 6 },
3921
+ "0x0b2c639c533813f4aa9d7837caf62653d097ff85": { token: "USDC", chain: "optimism", decimals: 6 },
3922
+ "0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e": { token: "USDC", chain: "avalanche", decimals: 6 },
3923
+ // USDT (6 decimals)
3924
+ "0xdac17f958d2ee523a2206206994597c13d831ec7": { token: "USDT", chain: "ethereum", decimals: 6 },
3925
+ "0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9": { token: "USDT", chain: "arbitrum", decimals: 6 },
3926
+ "0x94b008aa00579c1307b0ef2c499ad98a8ce58e58": { token: "USDT", chain: "optimism", decimals: 6 },
3927
+ "0xc2132d05d31c914a87c6611c10748aeb04b58e8f": { token: "USDT", chain: "polygon", decimals: 6 },
3928
+ // DAI (18 decimals)
3929
+ "0x6b175474e89094c44da98b954eedeac495271d0f": { token: "DAI", chain: "ethereum", decimals: 18 },
3930
+ "0x50c5725949a6f0c72e6c4a641f24049a917db0cb": { token: "DAI", chain: "base", decimals: 18 },
3931
+ // EURC (6 decimals)
3932
+ "0x1abaea1f7c830bd89acc67ec4af516284b1bc33c": { token: "EURC", chain: "ethereum", decimals: 6 },
3933
+ "0x60a3e35cc302bfa44cb288bc5a4f316fdb1adb42": { token: "EURC", chain: "base", decimals: 6 }
3934
+ };
3935
+ new Set(Object.keys(STABLECOIN_CONTRACTS));
3936
+ var CHAIN_ID_MAP = {
3937
+ 1: "ethereum",
3938
+ 8453: "base",
3939
+ 137: "polygon",
3940
+ 42161: "arbitrum",
3941
+ 10: "optimism",
3942
+ 43114: "avalanche"
3943
+ };
3944
+ var TRANSFER_SELECTOR = "0xa9059cbb";
3945
+ var TRANSFER_FROM_SELECTOR = "0x23b872dd";
3946
+ var TRANSFER_EVENT_ABI = {
3947
+ type: "event",
3948
+ name: "Transfer",
3949
+ inputs: [
3950
+ { type: "address", name: "from", indexed: true },
3951
+ { type: "address", name: "to", indexed: true },
3952
+ { type: "uint256", name: "value", indexed: false }
3953
+ ]
3954
+ };
3955
+
3956
+ // src/integrations/wallet-monitor.ts
3957
+ var WalletMonitor = class {
3958
+ kontext;
3216
3959
  config;
3217
- store;
3218
- logger;
3219
- taskManager;
3220
- auditExporter;
3221
- mode;
3222
- planManager;
3223
- exporter;
3224
- featureFlagManager;
3225
- trustScorer;
3226
- anomalyDetector;
3227
- constructor(config) {
3960
+ agentId;
3961
+ tokens;
3962
+ unwatchers = [];
3963
+ running = false;
3964
+ /** Shared dedup set — tracks recently verified txHashes (populated by both layers) */
3965
+ verifiedTxHashes = /* @__PURE__ */ new Set();
3966
+ cleanupTimer = null;
3967
+ txTimestamps = /* @__PURE__ */ new Map();
3968
+ constructor(kontext, config, options) {
3969
+ this.kontext = kontext;
3228
3970
  this.config = config;
3229
- this.mode = config.apiKey ? "cloud" : "local";
3230
- this.store = new KontextStore();
3231
- if (config.metadataSchema && typeof config.metadataSchema.parse !== "function") {
3232
- throw new KontextError(
3233
- "INITIALIZATION_ERROR" /* INITIALIZATION_ERROR */,
3234
- "metadataSchema must have a parse() method"
3971
+ this.agentId = options?.agentId ?? "wallet-monitor";
3972
+ this.tokens = options?.tokens ? new Set(options.tokens) : null;
3973
+ }
3974
+ /**
3975
+ * Mark a txHash as already verified (called by the viem interceptor layer).
3976
+ * The monitor will skip this tx if it later sees it on-chain.
3977
+ */
3978
+ markVerified(txHash) {
3979
+ const lower = txHash.toLowerCase();
3980
+ this.verifiedTxHashes.add(lower);
3981
+ this.txTimestamps.set(lower, Date.now());
3982
+ }
3983
+ /**
3984
+ * Start watching all configured chains for stablecoin transfers.
3985
+ * Dynamically imports viem — requires viem as a peer dependency.
3986
+ */
3987
+ async start() {
3988
+ if (this.running) return;
3989
+ let viem;
3990
+ try {
3991
+ viem = await import('viem');
3992
+ } catch {
3993
+ throw new Error(
3994
+ "Wallet monitoring requires viem. Install it: npm install viem"
3235
3995
  );
3236
3996
  }
3237
- if (config.storage) {
3238
- this.store.setStorageAdapter(config.storage);
3239
- }
3240
- const planTier = config.plan ?? "free";
3241
- this.planManager = new PlanManager(planTier, void 0, config.seats ?? 1);
3242
- if (config.upgradeUrl) {
3243
- this.planManager.upgradeUrl = config.upgradeUrl;
3244
- }
3245
- this.exporter = config.exporter ?? new NoopExporter();
3246
- this.logger = new ActionLogger(config, this.store);
3247
- this.taskManager = new TaskManager(config, this.store);
3248
- this.auditExporter = new AuditExporter(config, this.store);
3249
- this.trustScorer = new TrustScorer(config, this.store);
3250
- this.anomalyDetector = new AnomalyDetector(config, this.store);
3251
- this.featureFlagManager = config.featureFlags ? new FeatureFlagManager(config.featureFlags) : null;
3252
- if (config.anomalyRules && config.anomalyRules.length > 0) {
3253
- const advancedRules = ["newDestination", "offHoursActivity", "rapidSuccession", "roundAmount"];
3254
- const hasAdvanced = config.anomalyRules.some((r) => advancedRules.includes(r));
3255
- if (hasAdvanced) {
3256
- requirePlan("advanced-anomaly-rules", planTier);
3257
- }
3258
- this.anomalyDetector.enableAnomalyDetection({
3259
- rules: config.anomalyRules,
3260
- thresholds: config.anomalyThresholds
3997
+ const { createPublicClient, http } = viem;
3998
+ const wallets = this.config.wallets.map((w) => w.toLowerCase());
3999
+ const pollingInterval = this.config.pollingIntervalMs ?? 12e3;
4000
+ const contractsByChain = /* @__PURE__ */ new Map();
4001
+ for (const [address, info] of Object.entries(STABLECOIN_CONTRACTS)) {
4002
+ if (this.tokens && !this.tokens.has(info.token)) continue;
4003
+ const existing = contractsByChain.get(info.chain) ?? [];
4004
+ existing.push({ address, info });
4005
+ contractsByChain.set(info.chain, existing);
4006
+ }
4007
+ for (const [chain, contracts] of contractsByChain) {
4008
+ const rpcUrl = this.config.rpcEndpoints[chain];
4009
+ if (!rpcUrl) continue;
4010
+ const client = createPublicClient({
4011
+ transport: http(rpcUrl)
3261
4012
  });
4013
+ for (const { address, info } of contracts) {
4014
+ const unwatch = client.watchEvent({
4015
+ address,
4016
+ event: TRANSFER_EVENT_ABI,
4017
+ args: { from: wallets.length === 1 ? wallets[0] : wallets },
4018
+ poll: true,
4019
+ pollingInterval,
4020
+ onLogs: (logs) => {
4021
+ for (const log of logs) {
4022
+ this.handleTransferLog(log, info);
4023
+ }
4024
+ }
4025
+ });
4026
+ this.unwatchers.push(unwatch);
4027
+ }
3262
4028
  }
4029
+ this.cleanupTimer = setInterval(() => {
4030
+ const cutoff = Date.now() - 5 * 60 * 1e3;
4031
+ for (const [hash, ts] of this.txTimestamps) {
4032
+ if (ts < cutoff) {
4033
+ this.verifiedTxHashes.delete(hash);
4034
+ this.txTimestamps.delete(hash);
4035
+ }
4036
+ }
4037
+ }, 6e4);
4038
+ this.running = true;
3263
4039
  }
3264
- /**
3265
- * Initialize the Kontext SDK.
3266
- *
4040
+ /** Stop all watchers and cleanup */
4041
+ stop() {
4042
+ for (const unwatch of this.unwatchers) {
4043
+ try {
4044
+ unwatch();
4045
+ } catch {
4046
+ }
4047
+ }
4048
+ this.unwatchers.length = 0;
4049
+ if (this.cleanupTimer) {
4050
+ clearInterval(this.cleanupTimer);
4051
+ this.cleanupTimer = null;
4052
+ }
4053
+ this.running = false;
4054
+ }
4055
+ isRunning() {
4056
+ return this.running;
4057
+ }
4058
+ handleTransferLog(log, contractInfo) {
4059
+ const txHash = log.transactionHash;
4060
+ if (!txHash) return;
4061
+ const lowerHash = txHash.toLowerCase();
4062
+ if (this.verifiedTxHashes.has(lowerHash)) return;
4063
+ this.markVerified(txHash);
4064
+ const from = log.args?.from?.toLowerCase() ?? "";
4065
+ const to = log.args?.to?.toLowerCase() ?? "";
4066
+ const value = log.args?.value;
4067
+ if (!from || !to || value === void 0) return;
4068
+ const amount = formatTokenAmount(value, contractInfo.decimals);
4069
+ const verifyInput = {
4070
+ txHash,
4071
+ chain: contractInfo.chain,
4072
+ amount,
4073
+ token: contractInfo.token,
4074
+ from,
4075
+ to,
4076
+ agentId: this.agentId,
4077
+ metadata: {
4078
+ source: "wallet-monitor",
4079
+ contractAddress: log.address
4080
+ }
4081
+ };
4082
+ this.kontext.verify(verifyInput).catch(() => {
4083
+ });
4084
+ }
4085
+ };
4086
+ function formatTokenAmount(amount, decimals) {
4087
+ const divisor = BigInt(10 ** decimals);
4088
+ const whole = amount / divisor;
4089
+ const fraction = amount % divisor;
4090
+ if (fraction === 0n) return whole.toString();
4091
+ const fractionStr = fraction.toString().padStart(decimals, "0").replace(/0+$/, "");
4092
+ return `${whole}.${fractionStr}`;
4093
+ }
4094
+ var ProvenanceManager = class {
4095
+ store;
4096
+ logger;
4097
+ constructor(store, logger) {
4098
+ this.store = store;
4099
+ this.logger = logger;
4100
+ }
4101
+ // --------------------------------------------------------------------------
4102
+ // Layer 1: Session Delegation
4103
+ // --------------------------------------------------------------------------
4104
+ /**
4105
+ * Create a delegated agent session. Records the delegation in the
4106
+ * tamper-evident digest chain as the session's genesis event.
4107
+ */
4108
+ async createSession(input) {
4109
+ if (!input.agentId) {
4110
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, "agentId is required");
4111
+ }
4112
+ if (!input.delegatedBy) {
4113
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, "delegatedBy is required");
4114
+ }
4115
+ if (!input.scope || input.scope.length === 0) {
4116
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, "scope must contain at least one capability");
4117
+ }
4118
+ const sessionId = generateId();
4119
+ const createdAt = now();
4120
+ const constraints = input.constraints ? {
4121
+ ...input.constraints,
4122
+ ...input.constraints.allowedRecipients ? { allowedRecipients: input.constraints.allowedRecipients.map((a) => a.toLowerCase()) } : {}
4123
+ } : void 0;
4124
+ const session = {
4125
+ sessionId,
4126
+ agentId: input.agentId,
4127
+ delegatedBy: input.delegatedBy,
4128
+ scope: [...input.scope],
4129
+ ...constraints ? { constraints } : {},
4130
+ status: "active",
4131
+ createdAt,
4132
+ ...input.expiresIn ? { expiresAt: new Date(Date.now() + input.expiresIn).toISOString() } : {},
4133
+ metadata: input.metadata ? { ...input.metadata } : {}
4134
+ };
4135
+ const action = await this.logger.log({
4136
+ type: "session-start",
4137
+ description: `Session created: ${input.agentId} delegated by ${input.delegatedBy}`,
4138
+ agentId: input.agentId,
4139
+ sessionId,
4140
+ metadata: {
4141
+ delegatedBy: input.delegatedBy,
4142
+ scope: input.scope,
4143
+ ...constraints ? { constraints } : {}
4144
+ }
4145
+ });
4146
+ session.digest = action.digest;
4147
+ session.priorDigest = action.priorDigest;
4148
+ this.store.addSession(session);
4149
+ return { ...session, scope: [...session.scope] };
4150
+ }
4151
+ /**
4152
+ * Get an agent session by ID. Automatically marks expired sessions.
4153
+ */
4154
+ getSession(sessionId) {
4155
+ const session = this.store.getSession(sessionId);
4156
+ if (!session) return void 0;
4157
+ if (session.status === "active" && session.expiresAt && new Date(session.expiresAt) < /* @__PURE__ */ new Date()) {
4158
+ this.store.updateSession(sessionId, { status: "expired" });
4159
+ return { ...session, status: "expired", scope: [...session.scope] };
4160
+ }
4161
+ return { ...session, scope: [...session.scope] };
4162
+ }
4163
+ /**
4164
+ * Get all agent sessions.
4165
+ */
4166
+ getSessions() {
4167
+ return this.store.getSessions().map((s) => {
4168
+ if (s.status === "active" && s.expiresAt && new Date(s.expiresAt) < /* @__PURE__ */ new Date()) {
4169
+ this.store.updateSession(s.sessionId, { status: "expired" });
4170
+ return { ...s, status: "expired", scope: [...s.scope] };
4171
+ }
4172
+ return { ...s, scope: [...s.scope] };
4173
+ });
4174
+ }
4175
+ /**
4176
+ * End an active agent session. Records the termination in the digest chain.
4177
+ */
4178
+ async endSession(sessionId) {
4179
+ const session = this.store.getSession(sessionId);
4180
+ if (!session) {
4181
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, `Session not found: ${sessionId}`);
4182
+ }
4183
+ if (session.status !== "active") {
4184
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, `Session is already ${session.status}: ${sessionId}`);
4185
+ }
4186
+ const endedAt = now();
4187
+ await this.logger.log({
4188
+ type: "session-end",
4189
+ description: `Session ended: ${session.agentId}`,
4190
+ agentId: session.agentId,
4191
+ sessionId,
4192
+ metadata: { delegatedBy: session.delegatedBy }
4193
+ });
4194
+ const updated = this.store.updateSession(sessionId, { status: "ended", endedAt });
4195
+ if (!updated) {
4196
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, `Failed to update session: ${sessionId}`);
4197
+ }
4198
+ return { ...updated, scope: [...updated.scope] };
4199
+ }
4200
+ /**
4201
+ * Check whether an action is within a session's delegated scope.
4202
+ */
4203
+ validateScope(sessionId, action) {
4204
+ const session = this.getSession(sessionId);
4205
+ if (!session || session.status !== "active") return false;
4206
+ return session.scope.includes(action);
4207
+ }
4208
+ /**
4209
+ * Check whether a transaction meets session constraints.
4210
+ */
4211
+ validateConstraints(sessionId, input) {
4212
+ const session = this.getSession(sessionId);
4213
+ if (!session || session.status !== "active") return false;
4214
+ if (!session.constraints) return true;
4215
+ const c = session.constraints;
4216
+ if (c.maxAmount && input.amount) {
4217
+ if (parseAmount(input.amount) > parseAmount(c.maxAmount)) return false;
4218
+ }
4219
+ if (c.allowedChains && input.chain) {
4220
+ if (!c.allowedChains.includes(input.chain)) return false;
4221
+ }
4222
+ if (c.allowedTokens && input.token) {
4223
+ if (!c.allowedTokens.includes(input.token)) return false;
4224
+ }
4225
+ if (c.allowedRecipients && input.to) {
4226
+ if (!c.allowedRecipients.includes(input.to.toLowerCase())) return false;
4227
+ }
4228
+ return true;
4229
+ }
4230
+ // --------------------------------------------------------------------------
4231
+ // Layer 3: Checkpoints & Human Attestation
4232
+ // --------------------------------------------------------------------------
4233
+ /**
4234
+ * Create a provenance checkpoint -- a review point where a human
4235
+ * can attest to a batch of agent actions.
4236
+ */
4237
+ async createCheckpoint(input) {
4238
+ const session = this.getSession(input.sessionId);
4239
+ if (!session) {
4240
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, `Session not found: ${input.sessionId}`);
4241
+ }
4242
+ if (session.status !== "active") {
4243
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, `Session is ${session.status}: ${input.sessionId}`);
4244
+ }
4245
+ if (!input.actionIds || input.actionIds.length === 0) {
4246
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, "actionIds must contain at least one action");
4247
+ }
4248
+ if (!input.summary) {
4249
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, "summary is required");
4250
+ }
4251
+ const sessionActions = this.store.getActionsBySession(input.sessionId);
4252
+ const sessionActionIds = new Set(sessionActions.map((a) => a.id));
4253
+ for (const actionId of input.actionIds) {
4254
+ if (!sessionActionIds.has(actionId)) {
4255
+ throw new KontextError(
4256
+ "VALIDATION_ERROR" /* VALIDATION_ERROR */,
4257
+ `Action ${actionId} not found in session ${input.sessionId}`
4258
+ );
4259
+ }
4260
+ }
4261
+ const actionDigests = input.actionIds.map((id) => {
4262
+ const action = sessionActions.find((a) => a.id === id);
4263
+ return action?.digest ?? "";
4264
+ }).sort();
4265
+ const hash = createHash("sha256");
4266
+ hash.update(actionDigests.join(""));
4267
+ const actionsDigest = hash.digest("hex");
4268
+ const checkpointId = generateId();
4269
+ const createdAt = now();
4270
+ const checkpoint = {
4271
+ id: checkpointId,
4272
+ sessionId: input.sessionId,
4273
+ actionIds: [...input.actionIds],
4274
+ summary: input.summary,
4275
+ actionsDigest,
4276
+ status: "pending",
4277
+ createdAt,
4278
+ ...input.expiresIn ? { expiresAt: new Date(Date.now() + input.expiresIn).toISOString() } : {}
4279
+ };
4280
+ await this.logger.log({
4281
+ type: "checkpoint-created",
4282
+ description: `Checkpoint created: ${input.summary}`,
4283
+ agentId: session.agentId,
4284
+ sessionId: input.sessionId,
4285
+ metadata: {
4286
+ checkpointId,
4287
+ actionCount: input.actionIds.length,
4288
+ actionsDigest
4289
+ }
4290
+ });
4291
+ this.store.addCheckpoint(checkpoint);
4292
+ return { ...checkpoint, actionIds: [...checkpoint.actionIds] };
4293
+ }
4294
+ /**
4295
+ * Attach an externally-produced human attestation to a checkpoint.
4296
+ * The attestation includes a cryptographic signature that the agent
4297
+ * never touches -- key separation is the critical security property.
4298
+ */
4299
+ async attachAttestation(checkpointId, attestation) {
4300
+ const checkpoint = this.store.getCheckpoint(checkpointId);
4301
+ if (!checkpoint) {
4302
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, `Checkpoint not found: ${checkpointId}`);
4303
+ }
4304
+ if (checkpoint.status === "pending" && checkpoint.expiresAt && new Date(checkpoint.expiresAt) < /* @__PURE__ */ new Date()) {
4305
+ this.store.updateCheckpoint(checkpointId, { status: "expired" });
4306
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, `Checkpoint expired: ${checkpointId}`);
4307
+ }
4308
+ if (checkpoint.status !== "pending") {
4309
+ throw new KontextError(
4310
+ "VALIDATION_ERROR" /* VALIDATION_ERROR */,
4311
+ `Checkpoint is already ${checkpoint.status}: ${checkpointId}`
4312
+ );
4313
+ }
4314
+ if (attestation.checkpointId !== checkpointId) {
4315
+ throw new KontextError(
4316
+ "VALIDATION_ERROR" /* VALIDATION_ERROR */,
4317
+ `Attestation checkpointId mismatch: expected ${checkpointId}, got ${attestation.checkpointId}`
4318
+ );
4319
+ }
4320
+ const newStatus = attestation.decision === "approved" ? "attested" : "rejected";
4321
+ const session = this.store.getSession(checkpoint.sessionId);
4322
+ const agentId = session?.agentId ?? "unknown";
4323
+ await this.logger.log({
4324
+ type: `checkpoint-${newStatus}`,
4325
+ description: `Checkpoint ${newStatus} by ${attestation.reviewerId}`,
4326
+ agentId,
4327
+ sessionId: checkpoint.sessionId,
4328
+ metadata: {
4329
+ checkpointId,
4330
+ reviewerId: attestation.reviewerId,
4331
+ decision: attestation.decision,
4332
+ attestationId: attestation.attestationId
4333
+ }
4334
+ });
4335
+ const updated = this.store.updateCheckpoint(checkpointId, {
4336
+ status: newStatus,
4337
+ attestation
4338
+ });
4339
+ if (!updated) {
4340
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, `Failed to update checkpoint: ${checkpointId}`);
4341
+ }
4342
+ return { ...updated, actionIds: [...updated.actionIds] };
4343
+ }
4344
+ /**
4345
+ * Get a checkpoint by ID. Automatically marks expired checkpoints.
4346
+ */
4347
+ getCheckpoint(checkpointId) {
4348
+ const cp = this.store.getCheckpoint(checkpointId);
4349
+ if (!cp) return void 0;
4350
+ if (cp.status === "pending" && cp.expiresAt && new Date(cp.expiresAt) < /* @__PURE__ */ new Date()) {
4351
+ this.store.updateCheckpoint(checkpointId, { status: "expired" });
4352
+ return { ...cp, status: "expired", actionIds: [...cp.actionIds] };
4353
+ }
4354
+ return { ...cp, actionIds: [...cp.actionIds] };
4355
+ }
4356
+ /**
4357
+ * Get all checkpoints, optionally filtered by session.
4358
+ */
4359
+ getCheckpoints(sessionId) {
4360
+ const all = sessionId ? this.store.queryCheckpoints((cp) => cp.sessionId === sessionId) : this.store.getCheckpoints();
4361
+ return all.map((cp) => {
4362
+ if (cp.status === "pending" && cp.expiresAt && new Date(cp.expiresAt) < /* @__PURE__ */ new Date()) {
4363
+ this.store.updateCheckpoint(cp.id, { status: "expired" });
4364
+ return { ...cp, status: "expired", actionIds: [...cp.actionIds] };
4365
+ }
4366
+ return { ...cp, actionIds: [...cp.actionIds] };
4367
+ });
4368
+ }
4369
+ // --------------------------------------------------------------------------
4370
+ // Provenance Bundle Export
4371
+ // --------------------------------------------------------------------------
4372
+ /**
4373
+ * Export the full provenance bundle for a session.
4374
+ */
4375
+ getProvenanceBundle(sessionId) {
4376
+ const session = this.getSession(sessionId);
4377
+ if (!session) {
4378
+ throw new KontextError("VALIDATION_ERROR" /* VALIDATION_ERROR */, `Session not found: ${sessionId}`);
4379
+ }
4380
+ const sessionActions = this.store.getActionsBySession(sessionId);
4381
+ const checkpoints = this.getCheckpoints(sessionId);
4382
+ const actions = sessionActions.filter((a) => a.digest && a.priorDigest).map((a) => ({
4383
+ actionId: a.id,
4384
+ type: a.type,
4385
+ digest: a.digest,
4386
+ priorDigest: a.priorDigest,
4387
+ sessionId,
4388
+ timestamp: a.timestamp
4389
+ }));
4390
+ const attestedCheckpoints = checkpoints.filter((cp) => cp.status === "attested");
4391
+ const attestedActionIds = /* @__PURE__ */ new Set();
4392
+ for (const cp of attestedCheckpoints) {
4393
+ for (const actionId of cp.actionIds) {
4394
+ attestedActionIds.add(actionId);
4395
+ }
4396
+ }
4397
+ const userActions = sessionActions.filter(
4398
+ (a) => !a.type.startsWith("session-") && !a.type.startsWith("checkpoint-")
4399
+ );
4400
+ const verification = {
4401
+ digestChainValid: this.logger.verifyChain(this.store.getActions()).valid,
4402
+ totalActions: userActions.length,
4403
+ humanAttested: userActions.filter((a) => attestedActionIds.has(a.id)).length,
4404
+ sessionScoped: userActions.length,
4405
+ unattested: userActions.filter((a) => !attestedActionIds.has(a.id)).length
4406
+ };
4407
+ return {
4408
+ session,
4409
+ actions,
4410
+ checkpoints,
4411
+ verification,
4412
+ generatedAt: now()
4413
+ };
4414
+ }
4415
+ };
4416
+
4417
+ // src/kya/identity-registry.ts
4418
+ var AgentIdentityRegistry = class {
4419
+ /** agentId -> AgentIdentity */
4420
+ identities = /* @__PURE__ */ new Map();
4421
+ /** normalized address -> agentId (reverse index) */
4422
+ walletIndex = /* @__PURE__ */ new Map();
4423
+ /**
4424
+ * Register a new agent identity.
4425
+ */
4426
+ register(input) {
4427
+ if (this.identities.has(input.agentId)) {
4428
+ throw new Error(`Identity already registered for agent: ${input.agentId}`);
4429
+ }
4430
+ const timestamp = now();
4431
+ const wallets = (input.wallets ?? []).map((w) => ({
4432
+ address: w.address.toLowerCase(),
4433
+ chain: w.chain,
4434
+ verified: false,
4435
+ addedAt: timestamp,
4436
+ label: w.label
4437
+ }));
4438
+ const identity = {
4439
+ agentId: input.agentId,
4440
+ displayName: input.displayName,
4441
+ entityType: input.entityType ?? "unknown",
4442
+ wallets,
4443
+ kycReferences: [],
4444
+ contactUri: input.contactUri,
4445
+ metadata: input.metadata ?? {},
4446
+ createdAt: timestamp,
4447
+ updatedAt: timestamp
4448
+ };
4449
+ this.identities.set(input.agentId, identity);
4450
+ for (const wallet of wallets) {
4451
+ this.walletIndex.set(wallet.address, input.agentId);
4452
+ }
4453
+ return { ...identity, wallets: [...wallets] };
4454
+ }
4455
+ /**
4456
+ * Update an existing agent identity.
4457
+ */
4458
+ update(agentId, input) {
4459
+ const existing = this.identities.get(agentId);
4460
+ if (!existing) {
4461
+ throw new Error(`Identity not found for agent: ${agentId}`);
4462
+ }
4463
+ const updated = {
4464
+ ...existing,
4465
+ updatedAt: now()
4466
+ };
4467
+ if (input.displayName !== void 0) updated.displayName = input.displayName;
4468
+ if (input.entityType !== void 0) updated.entityType = input.entityType;
4469
+ if (input.contactUri !== void 0) updated.contactUri = input.contactUri;
4470
+ if (input.metadata !== void 0) {
4471
+ updated.metadata = { ...existing.metadata, ...input.metadata };
4472
+ }
4473
+ this.identities.set(agentId, updated);
4474
+ return { ...updated, wallets: [...updated.wallets] };
4475
+ }
4476
+ /**
4477
+ * Get an agent identity by agent ID.
4478
+ */
4479
+ get(agentId) {
4480
+ const identity = this.identities.get(agentId);
4481
+ if (!identity) return void 0;
4482
+ return { ...identity, wallets: [...identity.wallets] };
4483
+ }
4484
+ /**
4485
+ * Remove an agent identity and all wallet index entries.
4486
+ */
4487
+ remove(agentId) {
4488
+ const identity = this.identities.get(agentId);
4489
+ if (!identity) return false;
4490
+ for (const wallet of identity.wallets) {
4491
+ this.walletIndex.delete(wallet.address);
4492
+ }
4493
+ this.identities.delete(agentId);
4494
+ return true;
4495
+ }
4496
+ /**
4497
+ * Get all registered identities.
4498
+ */
4499
+ getAll() {
4500
+ return Array.from(this.identities.values()).map((id) => ({
4501
+ ...id,
4502
+ wallets: [...id.wallets]
4503
+ }));
4504
+ }
4505
+ // --------------------------------------------------------------------------
4506
+ // Wallet Operations
4507
+ // --------------------------------------------------------------------------
4508
+ /**
4509
+ * Add a wallet to an existing agent identity.
4510
+ */
4511
+ addWallet(agentId, wallet) {
4512
+ const identity = this.identities.get(agentId);
4513
+ if (!identity) {
4514
+ throw new Error(`Identity not found for agent: ${agentId}`);
4515
+ }
4516
+ const normalized = wallet.address.toLowerCase();
4517
+ const existingOwner = this.walletIndex.get(normalized);
4518
+ if (existingOwner && existingOwner !== agentId) {
4519
+ throw new Error(`Wallet ${normalized} is already registered to agent: ${existingOwner}`);
4520
+ }
4521
+ if (identity.wallets.some((w) => w.address === normalized)) {
4522
+ return { ...identity, wallets: [...identity.wallets] };
4523
+ }
4524
+ const mapping = {
4525
+ address: normalized,
4526
+ chain: wallet.chain,
4527
+ verified: false,
4528
+ addedAt: now(),
4529
+ label: wallet.label
4530
+ };
4531
+ identity.wallets.push(mapping);
4532
+ identity.updatedAt = now();
4533
+ this.walletIndex.set(normalized, agentId);
4534
+ return { ...identity, wallets: [...identity.wallets] };
4535
+ }
4536
+ /**
4537
+ * Remove a wallet from an agent identity.
4538
+ */
4539
+ removeWallet(agentId, address) {
4540
+ const identity = this.identities.get(agentId);
4541
+ if (!identity) {
4542
+ throw new Error(`Identity not found for agent: ${agentId}`);
4543
+ }
4544
+ const normalized = address.toLowerCase();
4545
+ identity.wallets = identity.wallets.filter((w) => w.address !== normalized);
4546
+ identity.updatedAt = now();
4547
+ this.walletIndex.delete(normalized);
4548
+ return { ...identity, wallets: [...identity.wallets] };
4549
+ }
4550
+ /**
4551
+ * Look up an agent identity by wallet address.
4552
+ */
4553
+ lookupByWallet(address) {
4554
+ const agentId = this.walletIndex.get(address.toLowerCase());
4555
+ if (!agentId) return void 0;
4556
+ return this.get(agentId);
4557
+ }
4558
+ // --------------------------------------------------------------------------
4559
+ // KYC Operations
4560
+ // --------------------------------------------------------------------------
4561
+ /**
4562
+ * Add a KYC provider reference to an agent identity.
4563
+ */
4564
+ addKycReference(agentId, reference) {
4565
+ const identity = this.identities.get(agentId);
4566
+ if (!identity) {
4567
+ throw new Error(`Identity not found for agent: ${agentId}`);
4568
+ }
4569
+ identity.kycReferences.push(reference);
4570
+ identity.updatedAt = now();
4571
+ return { ...identity, wallets: [...identity.wallets] };
4572
+ }
4573
+ /**
4574
+ * Get the overall KYC status for an agent.
4575
+ * Returns the best status from all references.
4576
+ */
4577
+ getKycStatus(agentId) {
4578
+ const identity = this.identities.get(agentId);
4579
+ if (!identity || identity.kycReferences.length === 0) return "none";
4580
+ const statusPriority = {
4581
+ verified: 4,
4582
+ pending: 3,
4583
+ expired: 2,
4584
+ rejected: 1,
4585
+ none: 0
4586
+ };
4587
+ let best = "none";
4588
+ for (const ref of identity.kycReferences) {
4589
+ if (statusPriority[ref.status] > statusPriority[best]) {
4590
+ best = ref.status;
4591
+ }
4592
+ }
4593
+ return best;
4594
+ }
4595
+ /**
4596
+ * Check if an agent has at least one verified and non-expired KYC reference.
4597
+ */
4598
+ hasVerifiedKyc(agentId) {
4599
+ const identity = this.identities.get(agentId);
4600
+ if (!identity) return false;
4601
+ const currentTime = (/* @__PURE__ */ new Date()).toISOString();
4602
+ return identity.kycReferences.some(
4603
+ (ref) => ref.status === "verified" && (ref.expiresAt === null || ref.expiresAt > currentTime)
4604
+ );
4605
+ }
4606
+ };
4607
+
4608
+ // src/kya/wallet-clustering.ts
4609
+ var UnionFind = class {
4610
+ parent = /* @__PURE__ */ new Map();
4611
+ rank = /* @__PURE__ */ new Map();
4612
+ /**
4613
+ * Find the representative of the set containing x.
4614
+ * Uses path compression for amortized near-constant time.
4615
+ */
4616
+ find(x) {
4617
+ if (!this.parent.has(x)) {
4618
+ this.parent.set(x, x);
4619
+ this.rank.set(x, 0);
4620
+ }
4621
+ let root = x;
4622
+ while (this.parent.get(root) !== root) {
4623
+ root = this.parent.get(root);
4624
+ }
4625
+ let current = x;
4626
+ while (current !== root) {
4627
+ const next = this.parent.get(current);
4628
+ this.parent.set(current, root);
4629
+ current = next;
4630
+ }
4631
+ return root;
4632
+ }
4633
+ /**
4634
+ * Union the sets containing x and y.
4635
+ * Uses union-by-rank for balanced trees.
4636
+ */
4637
+ union(x, y) {
4638
+ const rootX = this.find(x);
4639
+ const rootY = this.find(y);
4640
+ if (rootX === rootY) return;
4641
+ const rankX = this.rank.get(rootX);
4642
+ const rankY = this.rank.get(rootY);
4643
+ if (rankX < rankY) {
4644
+ this.parent.set(rootX, rootY);
4645
+ } else if (rankX > rankY) {
4646
+ this.parent.set(rootY, rootX);
4647
+ } else {
4648
+ this.parent.set(rootY, rootX);
4649
+ this.rank.set(rootX, rankX + 1);
4650
+ }
4651
+ }
4652
+ /**
4653
+ * Check if x and y are in the same set.
4654
+ */
4655
+ connected(x, y) {
4656
+ return this.find(x) === this.find(y);
4657
+ }
4658
+ /**
4659
+ * Get all components as arrays of elements.
4660
+ */
4661
+ getComponents() {
4662
+ const components = /* @__PURE__ */ new Map();
4663
+ for (const key of this.parent.keys()) {
4664
+ const root = this.find(key);
4665
+ if (!components.has(root)) {
4666
+ components.set(root, []);
4667
+ }
4668
+ components.get(root).push(key);
4669
+ }
4670
+ return Array.from(components.values());
4671
+ }
4672
+ /**
4673
+ * Get the component containing x.
4674
+ */
4675
+ getComponentOf(x) {
4676
+ const root = this.find(x);
4677
+ const component = [];
4678
+ for (const key of this.parent.keys()) {
4679
+ if (this.find(key) === root) {
4680
+ component.push(key);
4681
+ }
4682
+ }
4683
+ return component;
4684
+ }
4685
+ };
4686
+ var WalletClusterer = class {
4687
+ config;
4688
+ cachedClusters = null;
4689
+ constructor(config = {}) {
4690
+ this.config = {
4691
+ temporalWindowSeconds: config.temporalWindowSeconds ?? 60,
4692
+ minDestinationOverlap: config.minDestinationOverlap ?? 0.3,
4693
+ minGasSponsoredWallets: config.minGasSponsoredWallets ?? 3
4694
+ };
4695
+ }
4696
+ /**
4697
+ * Analyze transactions from the store and registry to produce wallet clusters.
4698
+ */
4699
+ analyzeFromStore(store, registry) {
4700
+ const uf = new UnionFind();
4701
+ const evidence = [];
4702
+ const transactions = store.getTransactions();
4703
+ const timestamp = now();
4704
+ for (const tx of transactions) {
4705
+ uf.find(tx.from.toLowerCase());
4706
+ uf.find(tx.to.toLowerCase());
4707
+ }
4708
+ this.applyCommonAgent(store, uf, evidence, timestamp);
4709
+ this.applyFundingChain(store, uf, evidence, timestamp);
4710
+ this.applyGasSponsorship(store, uf, evidence, timestamp);
4711
+ this.applyTemporalCoSpending(store, uf, evidence, timestamp);
4712
+ if (registry) {
4713
+ this.applyDeclaredWallets(registry, uf, evidence, timestamp);
4714
+ }
4715
+ const clusters = this.buildClusters(uf, evidence, store, registry, timestamp);
4716
+ this.cachedClusters = clusters;
4717
+ return clusters;
4718
+ }
4719
+ /**
4720
+ * Get cached clusters (or empty if not analyzed yet).
4721
+ */
4722
+ getClusters() {
4723
+ return this.cachedClusters ?? [];
4724
+ }
4725
+ /**
4726
+ * Invalidate the cached clusters.
4727
+ */
4728
+ invalidateCache() {
4729
+ this.cachedClusters = null;
4730
+ }
4731
+ // --------------------------------------------------------------------------
4732
+ // Heuristics
4733
+ // --------------------------------------------------------------------------
4734
+ /**
4735
+ * Heuristic 1: Common Agent (confidence 0.9)
4736
+ * Same agentId used multiple addresses -> union all from/to per agent.
4737
+ */
4738
+ applyCommonAgent(store, uf, evidence, timestamp) {
4739
+ const transactions = store.getTransactions();
4740
+ const agentAddresses = /* @__PURE__ */ new Map();
4741
+ for (const tx of transactions) {
4742
+ const from = tx.from.toLowerCase();
4743
+ const agentId = tx.agentId;
4744
+ if (!agentAddresses.has(agentId)) {
4745
+ agentAddresses.set(agentId, /* @__PURE__ */ new Set());
4746
+ }
4747
+ agentAddresses.get(agentId).add(from);
4748
+ }
4749
+ for (const [, addresses] of agentAddresses) {
4750
+ const addrs = Array.from(addresses);
4751
+ for (let i = 1; i < addrs.length; i++) {
4752
+ if (!uf.connected(addrs[0], addrs[i])) {
4753
+ uf.union(addrs[0], addrs[i]);
4754
+ evidence.push({
4755
+ heuristic: "common-agent",
4756
+ confidence: 0.9,
4757
+ addresses: [addrs[0], addrs[i]],
4758
+ detectedAt: timestamp
4759
+ });
4760
+ }
4761
+ }
4762
+ }
4763
+ }
4764
+ /**
4765
+ * Heuristic 2: Funding Chain (confidence 0.7)
4766
+ * If A sends to B, and A is agent-associated -> union A and B.
4767
+ */
4768
+ applyFundingChain(store, uf, evidence, timestamp) {
4769
+ const transactions = store.getTransactions();
4770
+ const agentAssociated = /* @__PURE__ */ new Set();
4771
+ for (const tx of transactions) {
4772
+ agentAssociated.add(tx.from.toLowerCase());
4773
+ }
4774
+ for (const tx of transactions) {
4775
+ const from = tx.from.toLowerCase();
4776
+ const to = tx.to.toLowerCase();
4777
+ if (agentAssociated.has(from) && !uf.connected(from, to)) {
4778
+ uf.union(from, to);
4779
+ evidence.push({
4780
+ heuristic: "funding-chain",
4781
+ confidence: 0.7,
4782
+ addresses: [from, to],
4783
+ detectedAt: timestamp
4784
+ });
4785
+ }
4786
+ }
4787
+ }
4788
+ /**
4789
+ * Heuristic 3: Gas Sponsorship (confidence 0.75)
4790
+ * If G is from in transfers to 3+ distinct agent wallets -> union G with all.
4791
+ */
4792
+ applyGasSponsorship(store, uf, evidence, timestamp) {
4793
+ const transactions = store.getTransactions();
4794
+ const agentFromAddresses = /* @__PURE__ */ new Set();
4795
+ for (const tx of transactions) {
4796
+ agentFromAddresses.add(tx.from.toLowerCase());
4797
+ }
4798
+ const senderToRecipients = /* @__PURE__ */ new Map();
4799
+ for (const tx of transactions) {
4800
+ const from = tx.from.toLowerCase();
4801
+ const to = tx.to.toLowerCase();
4802
+ if (!senderToRecipients.has(from)) {
4803
+ senderToRecipients.set(from, /* @__PURE__ */ new Set());
4804
+ }
4805
+ senderToRecipients.get(from).add(to);
4806
+ }
4807
+ for (const [sender, recipients] of senderToRecipients) {
4808
+ const agentRecipients = Array.from(recipients).filter(
4809
+ (r) => agentFromAddresses.has(r)
4810
+ );
4811
+ if (agentRecipients.length >= this.config.minGasSponsoredWallets) {
4812
+ for (const recipient of agentRecipients) {
4813
+ if (!uf.connected(sender, recipient)) {
4814
+ uf.union(sender, recipient);
4815
+ evidence.push({
4816
+ heuristic: "gas-sponsorship",
4817
+ confidence: 0.75,
4818
+ addresses: [sender, recipient],
4819
+ detectedAt: timestamp,
4820
+ detail: `Sender ${sender} sponsors ${agentRecipients.length} agent wallets`
4821
+ });
4822
+ }
4823
+ }
4824
+ }
4825
+ }
4826
+ }
4827
+ /**
4828
+ * Heuristic 4: Temporal Co-Spending (confidence 0.6)
4829
+ * Addresses transacting within a window with destination overlap.
4830
+ */
4831
+ applyTemporalCoSpending(store, uf, evidence, timestamp) {
4832
+ const transactions = store.getTransactions();
4833
+ if (transactions.length < 2) return;
4834
+ const txByFrom = /* @__PURE__ */ new Map();
4835
+ for (const tx of transactions) {
4836
+ const from = tx.from.toLowerCase();
4837
+ const to = tx.to.toLowerCase();
4838
+ if (!txByFrom.has(from)) {
4839
+ txByFrom.set(from, []);
4840
+ }
4841
+ txByFrom.get(from).push({
4842
+ to,
4843
+ time: new Date(tx.timestamp).getTime() / 1e3
4844
+ });
4845
+ }
4846
+ const fromAddresses = Array.from(txByFrom.keys());
4847
+ for (let i = 0; i < fromAddresses.length; i++) {
4848
+ for (let j = i + 1; j < fromAddresses.length; j++) {
4849
+ const addrA = fromAddresses[i];
4850
+ const addrB = fromAddresses[j];
4851
+ const txsA = txByFrom.get(addrA);
4852
+ const txsB = txByFrom.get(addrB);
4853
+ let hasTemporalOverlap = false;
4854
+ for (const a of txsA) {
4855
+ for (const b of txsB) {
4856
+ if (Math.abs(a.time - b.time) <= this.config.temporalWindowSeconds) {
4857
+ hasTemporalOverlap = true;
4858
+ break;
4859
+ }
4860
+ }
4861
+ if (hasTemporalOverlap) break;
4862
+ }
4863
+ if (!hasTemporalOverlap) continue;
4864
+ const destsA = new Set(txsA.map((t) => t.to));
4865
+ const destsB = new Set(txsB.map((t) => t.to));
4866
+ const intersection = new Set([...destsA].filter((d) => destsB.has(d)));
4867
+ const union = /* @__PURE__ */ new Set([...destsA, ...destsB]);
4868
+ const overlapRatio = union.size > 0 ? intersection.size / union.size : 0;
4869
+ if (overlapRatio >= this.config.minDestinationOverlap) {
4870
+ if (!uf.connected(addrA, addrB)) {
4871
+ uf.union(addrA, addrB);
4872
+ evidence.push({
4873
+ heuristic: "temporal-co-spending",
4874
+ confidence: 0.6,
4875
+ addresses: [addrA, addrB],
4876
+ detectedAt: timestamp,
4877
+ detail: `Overlap ratio: ${overlapRatio.toFixed(2)}`
4878
+ });
4879
+ }
4880
+ }
4881
+ }
4882
+ }
4883
+ }
4884
+ /**
4885
+ * Heuristic 5: Declared Wallets (confidence 1.0)
4886
+ * All wallets declared by the same identity are unioned.
4887
+ */
4888
+ applyDeclaredWallets(registry, uf, evidence, timestamp) {
4889
+ const identities = registry.getAll();
4890
+ for (const identity of identities) {
4891
+ const addrs = identity.wallets.map((w) => w.address);
4892
+ for (let i = 1; i < addrs.length; i++) {
4893
+ if (!uf.connected(addrs[0], addrs[i])) {
4894
+ uf.union(addrs[0], addrs[i]);
4895
+ evidence.push({
4896
+ heuristic: "declared-wallets",
4897
+ confidence: 1,
4898
+ addresses: [addrs[0], addrs[i]],
4899
+ detectedAt: timestamp
4900
+ });
4901
+ }
4902
+ }
4903
+ }
4904
+ }
4905
+ // --------------------------------------------------------------------------
4906
+ // Cluster Building
4907
+ // --------------------------------------------------------------------------
4908
+ buildClusters(uf, evidence, store, registry, timestamp) {
4909
+ const components = uf.getComponents();
4910
+ const clusters = [];
4911
+ const evidenceByAddress = /* @__PURE__ */ new Map();
4912
+ for (const e of evidence) {
4913
+ for (const addr of e.addresses) {
4914
+ if (!evidenceByAddress.has(addr)) {
4915
+ evidenceByAddress.set(addr, []);
4916
+ }
4917
+ evidenceByAddress.get(addr).push(e);
4918
+ }
4919
+ }
4920
+ const addressToAgents = /* @__PURE__ */ new Map();
4921
+ for (const tx of store.getTransactions()) {
4922
+ const from = tx.from.toLowerCase();
4923
+ if (!addressToAgents.has(from)) {
4924
+ addressToAgents.set(from, /* @__PURE__ */ new Set());
4925
+ }
4926
+ addressToAgents.get(from).add(tx.agentId);
4927
+ }
4928
+ if (registry) {
4929
+ for (const identity of registry.getAll()) {
4930
+ for (const wallet of identity.wallets) {
4931
+ if (!addressToAgents.has(wallet.address)) {
4932
+ addressToAgents.set(wallet.address, /* @__PURE__ */ new Set());
4933
+ }
4934
+ addressToAgents.get(wallet.address).add(identity.agentId);
4935
+ }
4936
+ }
4937
+ }
4938
+ for (const component of components) {
4939
+ if (component.length < 2) continue;
4940
+ const clusterEvidence = [];
4941
+ const seen = /* @__PURE__ */ new Set();
4942
+ for (const addr of component) {
4943
+ const addrEvidence = evidenceByAddress.get(addr) ?? [];
4944
+ for (const e of addrEvidence) {
4945
+ const key = `${e.heuristic}:${e.addresses[0]}:${e.addresses[1]}`;
4946
+ if (!seen.has(key)) {
4947
+ seen.add(key);
4948
+ clusterEvidence.push(e);
4949
+ }
4950
+ }
4951
+ }
4952
+ const agentIds = /* @__PURE__ */ new Set();
4953
+ for (const addr of component) {
4954
+ const agents = addressToAgents.get(addr);
4955
+ if (agents) {
4956
+ for (const a of agents) agentIds.add(a);
4957
+ }
4958
+ }
4959
+ const maxConfidence = clusterEvidence.length > 0 ? Math.max(...clusterEvidence.map((e) => e.confidence)) : 0;
4960
+ clusters.push({
4961
+ id: generateId(),
4962
+ addresses: component.sort(),
4963
+ agentIds: Array.from(agentIds).sort(),
4964
+ evidence: clusterEvidence,
4965
+ confidence: maxConfidence,
4966
+ createdAt: timestamp
4967
+ });
4968
+ }
4969
+ return clusters;
4970
+ }
4971
+ };
4972
+
4973
+ // src/kya/behavioral-fingerprint.ts
4974
+ var MIN_SAMPLE_SIZE = 5;
4975
+ var BehavioralFingerprinter = class {
4976
+ /**
4977
+ * Compute a behavioral embedding for an agent from their transaction history.
4978
+ * Returns null if the agent has fewer than MIN_SAMPLE_SIZE transactions.
4979
+ */
4980
+ computeEmbedding(agentId, store) {
4981
+ const transactions = store.getTransactionsByAgent(agentId);
4982
+ if (transactions.length < MIN_SAMPLE_SIZE) return null;
4983
+ return {
4984
+ agentId,
4985
+ temporal: this.extractTemporalFeatures(transactions),
4986
+ financial: this.extractFinancialFeatures(transactions),
4987
+ network: this.extractNetworkFeatures(transactions),
4988
+ operational: this.extractOperationalFeatures(transactions),
4989
+ sampleSize: transactions.length,
4990
+ computedAt: now()
4991
+ };
4992
+ }
4993
+ /**
4994
+ * Compute cosine similarity between two behavioral embeddings.
4995
+ * Returns a value in [0, 1] where 1 means identical and 0 means orthogonal.
4996
+ */
4997
+ cosineSimilarity(a, b) {
4998
+ const vecA = this.flattenEmbedding(a);
4999
+ const vecB = this.flattenEmbedding(b);
5000
+ let dot = 0;
5001
+ let magA = 0;
5002
+ let magB = 0;
5003
+ for (let i = 0; i < vecA.length; i++) {
5004
+ dot += vecA[i] * vecB[i];
5005
+ magA += vecA[i] * vecA[i];
5006
+ magB += vecB[i] * vecB[i];
5007
+ }
5008
+ const denominator = Math.sqrt(magA) * Math.sqrt(magB);
5009
+ if (denominator === 0) return 0;
5010
+ return dot / denominator;
5011
+ }
5012
+ // --------------------------------------------------------------------------
5013
+ // Feature Extraction
5014
+ // --------------------------------------------------------------------------
5015
+ extractTemporalFeatures(txs) {
5016
+ const sorted = [...txs].sort(
5017
+ (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
5018
+ );
5019
+ const intervals = [];
5020
+ for (let i = 1; i < sorted.length; i++) {
5021
+ const diff = (new Date(sorted[i].timestamp).getTime() - new Date(sorted[i - 1].timestamp).getTime()) / 1e3;
5022
+ intervals.push(diff);
5023
+ }
5024
+ const meanInterval = intervals.length > 0 ? intervals.reduce((s, v) => s + v, 0) / intervals.length : 0;
5025
+ const stddevInterval = intervals.length > 1 ? Math.sqrt(
5026
+ intervals.reduce((s, v) => s + (v - meanInterval) ** 2, 0) / (intervals.length - 1)
5027
+ ) : 0;
5028
+ const hourCounts = new Array(24).fill(0);
5029
+ for (const tx of txs) {
5030
+ const hour = new Date(tx.timestamp).getUTCHours();
5031
+ hourCounts[hour] = (hourCounts[hour] ?? 0) + 1;
5032
+ }
5033
+ const hourTotal = hourCounts.reduce((s, v) => s + v, 0);
5034
+ const hourHistogram = hourTotal > 0 ? hourCounts.map((c) => c / hourTotal) : hourCounts;
5035
+ const dayCounts = new Array(7).fill(0);
5036
+ for (const tx of txs) {
5037
+ const day = new Date(tx.timestamp).getUTCDay();
5038
+ dayCounts[day] = (dayCounts[day] ?? 0) + 1;
5039
+ }
5040
+ const dayTotal = dayCounts.reduce((s, v) => s + v, 0);
5041
+ const dayHistogram = dayTotal > 0 ? dayCounts.map((c) => c / dayTotal) : dayCounts;
5042
+ return {
5043
+ meanIntervalSeconds: meanInterval,
5044
+ stddevIntervalSeconds: stddevInterval,
5045
+ hourHistogram,
5046
+ dayHistogram
5047
+ };
5048
+ }
5049
+ extractFinancialFeatures(txs) {
5050
+ const amounts = txs.map((tx) => parseFloat(tx.amount)).filter((a) => !isNaN(a));
5051
+ if (amounts.length === 0) {
5052
+ return {
5053
+ meanAmount: 0,
5054
+ stddevAmount: 0,
5055
+ medianAmount: 0,
5056
+ roundAmountRatio: 0,
5057
+ percentiles: [0, 0, 0, 0, 0]
5058
+ };
5059
+ }
5060
+ const sorted = [...amounts].sort((a, b) => a - b);
5061
+ const mean = amounts.reduce((s, v) => s + v, 0) / amounts.length;
5062
+ const stddev = amounts.length > 1 ? Math.sqrt(
5063
+ amounts.reduce((s, v) => s + (v - mean) ** 2, 0) / (amounts.length - 1)
5064
+ ) : 0;
5065
+ const median = this.percentile(sorted, 50);
5066
+ const roundCount = amounts.filter((a) => a % 100 === 0).length;
5067
+ return {
5068
+ meanAmount: mean,
5069
+ stddevAmount: stddev,
5070
+ medianAmount: median,
5071
+ roundAmountRatio: amounts.length > 0 ? roundCount / amounts.length : 0,
5072
+ percentiles: [
5073
+ this.percentile(sorted, 10),
5074
+ this.percentile(sorted, 25),
5075
+ this.percentile(sorted, 50),
5076
+ this.percentile(sorted, 75),
5077
+ this.percentile(sorted, 90)
5078
+ ]
5079
+ };
5080
+ }
5081
+ extractNetworkFeatures(txs) {
5082
+ const destinations = txs.map((tx) => tx.to.toLowerCase());
5083
+ const sources = txs.map((tx) => tx.from.toLowerCase());
5084
+ const uniqueDests = new Set(destinations);
5085
+ const uniqueSrcs = new Set(sources);
5086
+ const reuseRatio = destinations.length > 0 ? 1 - uniqueDests.size / destinations.length : 0;
5087
+ const destCounts = /* @__PURE__ */ new Map();
5088
+ for (const d of destinations) {
5089
+ destCounts.set(d, (destCounts.get(d) ?? 0) + 1);
5090
+ }
5091
+ let hhi = 0;
5092
+ for (const count of destCounts.values()) {
5093
+ const share = count / destinations.length;
5094
+ hhi += share * share;
5095
+ }
5096
+ return {
5097
+ uniqueDestinations: uniqueDests.size,
5098
+ reuseRatio,
5099
+ concentrationIndex: hhi,
5100
+ uniqueSources: uniqueSrcs.size
5101
+ };
5102
+ }
5103
+ extractOperationalFeatures(txs) {
5104
+ const chainCounts = /* @__PURE__ */ new Map();
5105
+ const tokenCounts = /* @__PURE__ */ new Map();
5106
+ for (const tx of txs) {
5107
+ const chain = tx.chain ?? "unknown";
5108
+ const token = tx.token ?? "unknown";
5109
+ chainCounts.set(chain, (chainCounts.get(chain) ?? 0) + 1);
5110
+ tokenCounts.set(token, (tokenCounts.get(token) ?? 0) + 1);
5111
+ }
5112
+ const total = txs.length;
5113
+ const chainDistribution = {};
5114
+ for (const [chain, count] of chainCounts) {
5115
+ chainDistribution[chain] = total > 0 ? count / total : 0;
5116
+ }
5117
+ const tokenDistribution = {};
5118
+ for (const [token, count] of tokenCounts) {
5119
+ tokenDistribution[token] = total > 0 ? count / total : 0;
5120
+ }
5121
+ const primaryChain = chainCounts.size > 0 ? Array.from(chainCounts.entries()).sort((a, b) => b[1] - a[1])[0][0] : "";
5122
+ const primaryToken = tokenCounts.size > 0 ? Array.from(tokenCounts.entries()).sort((a, b) => b[1] - a[1])[0][0] : "";
5123
+ return {
5124
+ chainDistribution,
5125
+ tokenDistribution,
5126
+ primaryChain,
5127
+ primaryToken
5128
+ };
5129
+ }
5130
+ // --------------------------------------------------------------------------
5131
+ // Helpers
5132
+ // --------------------------------------------------------------------------
5133
+ percentile(sorted, p) {
5134
+ if (sorted.length === 0) return 0;
5135
+ const idx = p / 100 * (sorted.length - 1);
5136
+ const lower = Math.floor(idx);
5137
+ const upper = Math.ceil(idx);
5138
+ if (lower === upper) return sorted[lower];
5139
+ return sorted[lower] + (sorted[upper] - sorted[lower]) * (idx - lower);
5140
+ }
5141
+ /**
5142
+ * Flatten an embedding into a numeric vector for cosine similarity.
5143
+ * Log-scales magnitude values with log(1+x).
5144
+ */
5145
+ flattenEmbedding(e) {
5146
+ const vec = [];
5147
+ vec.push(Math.log(1 + e.temporal.meanIntervalSeconds));
5148
+ vec.push(Math.log(1 + e.temporal.stddevIntervalSeconds));
5149
+ vec.push(...e.temporal.hourHistogram);
5150
+ vec.push(...e.temporal.dayHistogram);
5151
+ vec.push(Math.log(1 + e.financial.meanAmount));
5152
+ vec.push(Math.log(1 + e.financial.stddevAmount));
5153
+ vec.push(Math.log(1 + e.financial.medianAmount));
5154
+ vec.push(e.financial.roundAmountRatio);
5155
+ vec.push(...e.financial.percentiles.map((p) => Math.log(1 + p)));
5156
+ vec.push(Math.log(1 + e.network.uniqueDestinations));
5157
+ vec.push(e.network.reuseRatio);
5158
+ vec.push(e.network.concentrationIndex);
5159
+ vec.push(Math.log(1 + e.network.uniqueSources));
5160
+ const chainValues = Object.values(e.operational.chainDistribution).sort(
5161
+ (a, b) => b - a
5162
+ );
5163
+ const tokenValues = Object.values(e.operational.tokenDistribution).sort(
5164
+ (a, b) => b - a
5165
+ );
5166
+ for (let i = 0; i < 5; i++) {
5167
+ vec.push(chainValues[i] ?? 0);
5168
+ }
5169
+ for (let i = 0; i < 5; i++) {
5170
+ vec.push(tokenValues[i] ?? 0);
5171
+ }
5172
+ return vec;
5173
+ }
5174
+ };
5175
+
5176
+ // src/kya/cross-session-linker.ts
5177
+ var WALLET_OVERLAP_WEIGHT = 0.4;
5178
+ var BEHAVIORAL_SIMILARITY_WEIGHT = 0.35;
5179
+ var DECLARED_IDENTITY_WEIGHT = 0.25;
5180
+ var CrossSessionLinker = class {
5181
+ config;
5182
+ links = /* @__PURE__ */ new Map();
5183
+ constructor(config = {}) {
5184
+ this.config = {
5185
+ minBehavioralSimilarity: config.minBehavioralSimilarity ?? 0.85,
5186
+ minLinkConfidence: config.minLinkConfidence ?? 0.6
5187
+ };
5188
+ }
5189
+ /**
5190
+ * Analyze all agents and create links between those with sufficient signals.
5191
+ */
5192
+ analyzeAndLink(store, registry, clusterer, fingerprinter) {
5193
+ const newLinks = [];
5194
+ const agentIds = /* @__PURE__ */ new Set();
5195
+ for (const tx of store.getTransactions()) {
5196
+ agentIds.add(tx.agentId);
5197
+ }
5198
+ for (const action of store.getActions()) {
5199
+ agentIds.add(action.agentId);
5200
+ }
5201
+ const agents = Array.from(agentIds);
5202
+ const clusters = clusterer.getClusters();
5203
+ for (let i = 0; i < agents.length; i++) {
5204
+ for (let j = i + 1; j < agents.length; j++) {
5205
+ const agentA = agents[i];
5206
+ const agentB = agents[j];
5207
+ const existingKey = this.getLinkKey(agentA, agentB);
5208
+ if (this.links.has(existingKey)) continue;
5209
+ const signals = [];
5210
+ const walletOverlap = this.computeWalletOverlap(
5211
+ agentA,
5212
+ agentB,
5213
+ clusters
5214
+ );
5215
+ if (walletOverlap > 0) {
5216
+ signals.push({
5217
+ type: "wallet-overlap",
5218
+ strength: walletOverlap,
5219
+ weight: WALLET_OVERLAP_WEIGHT
5220
+ });
5221
+ }
5222
+ const embeddingA = fingerprinter.computeEmbedding(agentA, store);
5223
+ const embeddingB = fingerprinter.computeEmbedding(agentB, store);
5224
+ if (embeddingA && embeddingB) {
5225
+ const similarity = fingerprinter.cosineSimilarity(embeddingA, embeddingB);
5226
+ if (similarity >= this.config.minBehavioralSimilarity) {
5227
+ signals.push({
5228
+ type: "behavioral-similarity",
5229
+ strength: similarity,
5230
+ weight: BEHAVIORAL_SIMILARITY_WEIGHT
5231
+ });
5232
+ }
5233
+ }
5234
+ const declaredStrength = this.computeDeclaredIdentitySignal(
5235
+ agentA,
5236
+ agentB,
5237
+ registry
5238
+ );
5239
+ if (declaredStrength > 0) {
5240
+ signals.push({
5241
+ type: "declared-identity",
5242
+ strength: declaredStrength,
5243
+ weight: DECLARED_IDENTITY_WEIGHT
5244
+ });
5245
+ }
5246
+ if (signals.length === 0) continue;
5247
+ const confidence = signals.reduce((sum, s) => sum + s.strength * s.weight, 0) / signals.reduce((sum, s) => sum + s.weight, 0);
5248
+ if (confidence >= this.config.minLinkConfidence) {
5249
+ const link = {
5250
+ id: generateId(),
5251
+ agentIdA: agentA,
5252
+ agentIdB: agentB,
5253
+ confidence,
5254
+ signals,
5255
+ status: "inferred",
5256
+ createdAt: now()
5257
+ };
5258
+ this.links.set(existingKey, link);
5259
+ newLinks.push(link);
5260
+ }
5261
+ }
5262
+ }
5263
+ return newLinks;
5264
+ }
5265
+ /**
5266
+ * Manually link two agents.
5267
+ */
5268
+ manualLink(agentIdA, agentIdB, reviewedBy) {
5269
+ const key = this.getLinkKey(agentIdA, agentIdB);
5270
+ const existing = this.links.get(key);
5271
+ if (existing) {
5272
+ existing.status = "confirmed";
5273
+ existing.reviewedBy = reviewedBy;
5274
+ existing.reviewedAt = now();
5275
+ return { ...existing };
5276
+ }
5277
+ const link = {
5278
+ id: generateId(),
5279
+ agentIdA,
5280
+ agentIdB,
5281
+ confidence: 1,
5282
+ signals: [
5283
+ {
5284
+ type: "declared-identity",
5285
+ strength: 1,
5286
+ weight: 1,
5287
+ detail: `Manually linked by ${reviewedBy}`
5288
+ }
5289
+ ],
5290
+ status: "confirmed",
5291
+ createdAt: now(),
5292
+ reviewedBy,
5293
+ reviewedAt: now()
5294
+ };
5295
+ this.links.set(key, link);
5296
+ return { ...link };
5297
+ }
5298
+ /**
5299
+ * Review a link (confirm or reject).
5300
+ */
5301
+ reviewLink(linkId, decision, reviewedBy) {
5302
+ for (const link of this.links.values()) {
5303
+ if (link.id === linkId) {
5304
+ link.status = decision;
5305
+ link.reviewedBy = reviewedBy;
5306
+ link.reviewedAt = now();
5307
+ return { ...link };
5308
+ }
5309
+ }
5310
+ return void 0;
5311
+ }
5312
+ /**
5313
+ * Get all agents linked to the given agent.
5314
+ */
5315
+ getLinkedAgents(agentId) {
5316
+ const linked = /* @__PURE__ */ new Set();
5317
+ for (const link of this.links.values()) {
5318
+ if (link.status === "rejected") continue;
5319
+ if (link.agentIdA === agentId) linked.add(link.agentIdB);
5320
+ if (link.agentIdB === agentId) linked.add(link.agentIdA);
5321
+ }
5322
+ return Array.from(linked);
5323
+ }
5324
+ /**
5325
+ * Get all links for a specific agent.
5326
+ */
5327
+ getLinksForAgent(agentId) {
5328
+ const result = [];
5329
+ for (const link of this.links.values()) {
5330
+ if (link.agentIdA === agentId || link.agentIdB === agentId) {
5331
+ result.push({ ...link });
5332
+ }
5333
+ }
5334
+ return result;
5335
+ }
5336
+ /**
5337
+ * Get all links.
5338
+ */
5339
+ getAllLinks() {
5340
+ return Array.from(this.links.values()).map((l) => ({ ...l }));
5341
+ }
5342
+ // --------------------------------------------------------------------------
5343
+ // Private Helpers
5344
+ // --------------------------------------------------------------------------
5345
+ getLinkKey(a, b) {
5346
+ return a < b ? `${a}:${b}` : `${b}:${a}`;
5347
+ }
5348
+ computeWalletOverlap(agentA, agentB, clusters) {
5349
+ const clustersA = /* @__PURE__ */ new Set();
5350
+ const clustersB = /* @__PURE__ */ new Set();
5351
+ for (const cluster of clusters) {
5352
+ if (cluster.agentIds.includes(agentA)) {
5353
+ for (const addr of cluster.addresses) clustersA.add(addr);
5354
+ }
5355
+ if (cluster.agentIds.includes(agentB)) {
5356
+ for (const addr of cluster.addresses) clustersB.add(addr);
5357
+ }
5358
+ }
5359
+ if (clustersA.size === 0 || clustersB.size === 0) return 0;
5360
+ const intersection = new Set([...clustersA].filter((a) => clustersB.has(a)));
5361
+ const union = /* @__PURE__ */ new Set([...clustersA, ...clustersB]);
5362
+ return union.size > 0 ? intersection.size / union.size : 0;
5363
+ }
5364
+ computeDeclaredIdentitySignal(agentA, agentB, registry) {
5365
+ const identityA = registry.get(agentA);
5366
+ const identityB = registry.get(agentB);
5367
+ if (!identityA || !identityB) return 0;
5368
+ const walletsA = new Set(identityA.wallets.map((w) => w.address));
5369
+ const walletsB = new Set(identityB.wallets.map((w) => w.address));
5370
+ const sharedWallets = [...walletsA].filter((w) => walletsB.has(w));
5371
+ if (sharedWallets.length > 0) return 1;
5372
+ const kycRefsA = new Set(
5373
+ identityA.kycReferences.map((r) => `${r.provider}:${r.referenceId}`)
5374
+ );
5375
+ const kycRefsB = new Set(
5376
+ identityB.kycReferences.map((r) => `${r.provider}:${r.referenceId}`)
5377
+ );
5378
+ const sharedKyc = [...kycRefsA].filter((r) => kycRefsB.has(r));
5379
+ if (sharedKyc.length > 0) return 1;
5380
+ return 0;
5381
+ }
5382
+ };
5383
+
5384
+ // src/kya/confidence-scorer.ts
5385
+ var KYAConfidenceScorer = class {
5386
+ weights;
5387
+ constructor(config = {}) {
5388
+ this.weights = {
5389
+ declaredIdentity: config.declaredIdentityWeight ?? 0.2,
5390
+ kycVerification: config.kycVerificationWeight ?? 0.3,
5391
+ walletGraph: config.walletGraphWeight ?? 0.2,
5392
+ behavioralConsistency: config.behavioralConsistencyWeight ?? 0.2,
5393
+ externalEnrichment: config.externalEnrichmentWeight ?? 0.1
5394
+ };
5395
+ }
5396
+ /**
5397
+ * Compute a composite confidence score for an agent.
5398
+ */
5399
+ computeScore(agentId, registry, clusterer, fingerprinter, linker, store) {
5400
+ const components = [];
5401
+ const declaredScore = this.scoreDeclaredIdentity(agentId, registry);
5402
+ components.push({
5403
+ name: "Declared Identity",
5404
+ score: declaredScore.score,
5405
+ weight: this.weights.declaredIdentity,
5406
+ weightedScore: declaredScore.score * this.weights.declaredIdentity,
5407
+ detail: declaredScore.detail
5408
+ });
5409
+ const kycScore = this.scoreKycVerification(agentId, registry);
5410
+ components.push({
5411
+ name: "KYC Verification",
5412
+ score: kycScore.score,
5413
+ weight: this.weights.kycVerification,
5414
+ weightedScore: kycScore.score * this.weights.kycVerification,
5415
+ detail: kycScore.detail
5416
+ });
5417
+ const walletScore = this.scoreWalletGraph(agentId, clusterer);
5418
+ components.push({
5419
+ name: "Wallet Graph",
5420
+ score: walletScore.score,
5421
+ weight: this.weights.walletGraph,
5422
+ weightedScore: walletScore.score * this.weights.walletGraph,
5423
+ detail: walletScore.detail
5424
+ });
5425
+ const behavioralScore = this.scoreBehavioralConsistency(
5426
+ agentId,
5427
+ fingerprinter,
5428
+ linker,
5429
+ store
5430
+ );
5431
+ components.push({
5432
+ name: "Behavioral Consistency",
5433
+ score: behavioralScore.score,
5434
+ weight: this.weights.behavioralConsistency,
5435
+ weightedScore: behavioralScore.score * this.weights.behavioralConsistency,
5436
+ detail: behavioralScore.detail
5437
+ });
5438
+ const externalScore = this.scoreExternalEnrichment(agentId, registry);
5439
+ components.push({
5440
+ name: "External Enrichment",
5441
+ score: externalScore.score,
5442
+ weight: this.weights.externalEnrichment,
5443
+ weightedScore: externalScore.score * this.weights.externalEnrichment,
5444
+ detail: externalScore.detail
5445
+ });
5446
+ const totalWeight = components.reduce((sum, c) => sum + c.weight, 0);
5447
+ const overallScore = totalWeight > 0 ? Math.round(components.reduce((sum, c) => sum + c.weightedScore, 0) / totalWeight) : 0;
5448
+ return {
5449
+ agentId,
5450
+ score: overallScore,
5451
+ level: this.scoreToLevel(overallScore),
5452
+ components,
5453
+ computedAt: now()
5454
+ };
5455
+ }
5456
+ // --------------------------------------------------------------------------
5457
+ // Component Scorers
5458
+ // --------------------------------------------------------------------------
5459
+ scoreDeclaredIdentity(agentId, registry) {
5460
+ const identity = registry.get(agentId);
5461
+ if (!identity) return { score: 0, detail: "No declared identity" };
5462
+ let score = 30;
5463
+ const parts = ["identity registered"];
5464
+ if (identity.displayName) {
5465
+ score += 10;
5466
+ parts.push("displayName set");
5467
+ }
5468
+ if (identity.entityType !== "unknown") {
5469
+ score += 10;
5470
+ parts.push(`entityType: ${identity.entityType}`);
5471
+ }
5472
+ if (identity.wallets.length > 0) {
5473
+ score += 20;
5474
+ parts.push(`${identity.wallets.length} wallet(s)`);
5475
+ }
5476
+ if (identity.contactUri) {
5477
+ score += 10;
5478
+ parts.push("contactUri set");
5479
+ }
5480
+ if (Object.keys(identity.metadata).length > 0) {
5481
+ score += 20;
5482
+ parts.push("metadata provided");
5483
+ }
5484
+ return { score: Math.min(100, score), detail: parts.join(", ") };
5485
+ }
5486
+ scoreKycVerification(agentId, registry) {
5487
+ const identity = registry.get(agentId);
5488
+ if (!identity || identity.kycReferences.length === 0) {
5489
+ return { score: 0, detail: "No KYC verification" };
5490
+ }
5491
+ const refs = identity.kycReferences;
5492
+ const hasRejected = refs.some((r) => r.status === "rejected");
5493
+ const verifiedRefs = refs.filter((r) => r.status === "verified");
5494
+ const pendingRefs = refs.filter((r) => r.status === "pending");
5495
+ const currentTime = (/* @__PURE__ */ new Date()).toISOString();
5496
+ const activeVerified = verifiedRefs.filter(
5497
+ (r) => r.expiresAt === null || r.expiresAt > currentTime
5498
+ );
5499
+ if (hasRejected && verifiedRefs.length === 0) {
5500
+ return { score: 10, detail: "KYC rejected, capped at 10" };
5501
+ }
5502
+ if (pendingRefs.length > 0 && verifiedRefs.length === 0) {
5503
+ return { score: 20, detail: "KYC pending" };
5504
+ }
5505
+ if (verifiedRefs.length > 0) {
5506
+ let score = 90;
5507
+ const parts = [`${verifiedRefs.length} verified`];
5508
+ if (activeVerified.length > 0) {
5509
+ score = 100;
5510
+ parts.push("non-expired");
5511
+ }
5512
+ if (verifiedRefs.length > 1) {
5513
+ score = Math.min(100, score + 10);
5514
+ parts.push("multiple providers");
5515
+ }
5516
+ return { score, detail: parts.join(", ") };
5517
+ }
5518
+ return { score: 0, detail: "No KYC verification" };
5519
+ }
5520
+ scoreWalletGraph(agentId, clusterer) {
5521
+ const clusters = clusterer.getClusters();
5522
+ const agentClusters = clusters.filter((c) => c.agentIds.includes(agentId));
5523
+ if (agentClusters.length === 0) {
5524
+ return { score: 20, detail: "No wallet cluster" };
5525
+ }
5526
+ const totalAddresses = new Set(
5527
+ agentClusters.flatMap((c) => c.addresses)
5528
+ ).size;
5529
+ if (totalAddresses === 1) {
5530
+ return { score: 40, detail: "1 address in cluster" };
5531
+ }
5532
+ const heuristics = new Set(
5533
+ agentClusters.flatMap((c) => c.evidence.map((e) => e.heuristic))
5534
+ );
5535
+ const hasDeclared = heuristics.has("declared-wallets");
5536
+ const hasAuto = heuristics.size > (hasDeclared ? 1 : 0);
5537
+ if (hasDeclared && hasAuto) {
5538
+ return {
5539
+ score: 85,
5540
+ detail: `${totalAddresses} addresses, declared + auto heuristics`
5541
+ };
5542
+ }
5543
+ if (heuristics.size > 1) {
5544
+ return {
5545
+ score: 70,
5546
+ detail: `${totalAddresses} addresses, ${heuristics.size} heuristic types`
5547
+ };
5548
+ }
5549
+ return {
5550
+ score: 50,
5551
+ detail: `${totalAddresses} addresses, single heuristic`
5552
+ };
5553
+ }
5554
+ scoreBehavioralConsistency(agentId, fingerprinter, linker, store) {
5555
+ const embedding = fingerprinter.computeEmbedding(agentId, store);
5556
+ if (!embedding) {
5557
+ return { score: 30, detail: "Insufficient data for embedding" };
5558
+ }
5559
+ const links = linker.getLinksForAgent(agentId);
5560
+ const confirmedLinks = links.filter((l) => l.status === "confirmed");
5561
+ if (confirmedLinks.length === 0 && links.length === 0) {
5562
+ return { score: 50, detail: "Embedding computed, no links" };
5563
+ }
5564
+ let maxSimilarity = 0;
5565
+ for (const link of confirmedLinks) {
5566
+ const behavioralSignal = link.signals.find(
5567
+ (s) => s.type === "behavioral-similarity"
5568
+ );
5569
+ if (behavioralSignal && behavioralSignal.strength > maxSimilarity) {
5570
+ maxSimilarity = behavioralSignal.strength;
5571
+ }
5572
+ }
5573
+ if (maxSimilarity > 0.9) {
5574
+ return { score: 95, detail: `Confirmed link similarity: ${maxSimilarity.toFixed(2)}` };
5575
+ }
5576
+ if (maxSimilarity > 0.8) {
5577
+ return { score: 85, detail: `Confirmed link similarity: ${maxSimilarity.toFixed(2)}` };
5578
+ }
5579
+ if (confirmedLinks.length > 0) {
5580
+ return { score: 70, detail: `${confirmedLinks.length} confirmed link(s)` };
5581
+ }
5582
+ return { score: 50, detail: "Embedding computed, no confirmed links" };
5583
+ }
5584
+ scoreExternalEnrichment(agentId, registry) {
5585
+ const identity = registry.get(agentId);
5586
+ if (!identity) {
5587
+ return { score: 50, detail: "Default (neutral), no identity" };
5588
+ }
5589
+ const riskLevels = identity.kycReferences.filter((r) => r.riskLevel).map((r) => r.riskLevel);
5590
+ if (riskLevels.length === 0) {
5591
+ return { score: 50, detail: "Default (neutral), no risk data" };
5592
+ }
5593
+ if (riskLevels.includes("high")) {
5594
+ return { score: 20, detail: "High risk from external provider" };
5595
+ }
5596
+ if (riskLevels.includes("low")) {
5597
+ return { score: 80, detail: "Low risk from external provider" };
5598
+ }
5599
+ return { score: 50, detail: "Medium risk from external provider" };
5600
+ }
5601
+ // --------------------------------------------------------------------------
5602
+ // Helpers
5603
+ // --------------------------------------------------------------------------
5604
+ scoreToLevel(score) {
5605
+ if (score >= 85) return "verified";
5606
+ if (score >= 65) return "high";
5607
+ if (score >= 40) return "medium";
5608
+ if (score >= 20) return "low";
5609
+ return "unknown";
5610
+ }
5611
+ };
5612
+
5613
+ // src/client.ts
5614
+ var PLAN_STORAGE_KEY = "kontext:plan";
5615
+ var Kontext = class _Kontext {
5616
+ config;
5617
+ store;
5618
+ logger;
5619
+ taskManager;
5620
+ auditExporter;
5621
+ mode;
5622
+ planManager;
5623
+ exporter;
5624
+ featureFlagManager;
5625
+ trustScorer;
5626
+ anomalyDetector;
5627
+ screeningAggregator;
5628
+ walletMonitor = null;
5629
+ provenanceManager = null;
5630
+ identityRegistry = null;
5631
+ walletClusterer = null;
5632
+ behavioralFingerprinter = null;
5633
+ crossSessionLinker = null;
5634
+ confidenceScorer = null;
5635
+ constructor(config) {
5636
+ this.config = config;
5637
+ this.mode = config.apiKey ? "cloud" : "local";
5638
+ this.store = new KontextStore();
5639
+ if (config.metadataSchema && typeof config.metadataSchema.parse !== "function") {
5640
+ throw new KontextError(
5641
+ "INITIALIZATION_ERROR" /* INITIALIZATION_ERROR */,
5642
+ "metadataSchema must have a parse() method"
5643
+ );
5644
+ }
5645
+ if (config.storage) {
5646
+ this.store.setStorageAdapter(config.storage);
5647
+ }
5648
+ const planTier = config.plan ?? "free";
5649
+ this.planManager = new PlanManager(planTier, void 0, config.seats ?? 1);
5650
+ if (config.upgradeUrl) {
5651
+ this.planManager.upgradeUrl = config.upgradeUrl;
5652
+ }
5653
+ this.exporter = config.exporter ?? new NoopExporter();
5654
+ this.logger = new ActionLogger(config, this.store);
5655
+ this.taskManager = new TaskManager(config, this.store);
5656
+ this.auditExporter = new AuditExporter(config, this.store);
5657
+ this.trustScorer = new TrustScorer(config, this.store);
5658
+ this.anomalyDetector = new AnomalyDetector(config, this.store);
5659
+ this.featureFlagManager = config.featureFlags ? new FeatureFlagManager(config.featureFlags) : null;
5660
+ this.screeningAggregator = config.screening ? new ScreeningAggregator({
5661
+ providers: config.screening.providers,
5662
+ consensus: config.screening.consensus,
5663
+ blocklist: config.screening.blocklist,
5664
+ allowlist: config.screening.allowlist,
5665
+ providerTimeoutMs: config.screening.providerTimeoutMs,
5666
+ onEvent: () => this.planManager.recordEvent()
5667
+ }) : null;
5668
+ if (config.anomalyRules && config.anomalyRules.length > 0) {
5669
+ const advancedRules = ["newDestination", "offHoursActivity", "rapidSuccession", "roundAmount"];
5670
+ const hasAdvanced = config.anomalyRules.some((r) => advancedRules.includes(r));
5671
+ if (hasAdvanced) {
5672
+ requirePlan("advanced-anomaly-rules", planTier);
5673
+ }
5674
+ this.anomalyDetector.enableAnomalyDetection({
5675
+ rules: config.anomalyRules,
5676
+ thresholds: config.anomalyThresholds
5677
+ });
5678
+ }
5679
+ if (config.walletMonitoring && config.walletMonitoring.wallets.length > 0) {
5680
+ const tokens = config.policy?.allowedTokens;
5681
+ this.walletMonitor = new WalletMonitor(
5682
+ this,
5683
+ config.walletMonitoring,
5684
+ { agentId: config.agentId, tokens: tokens ?? void 0 }
5685
+ );
5686
+ this.walletMonitor.start().catch((err) => {
5687
+ if (config.debug) {
5688
+ console.debug(`[Kontext] Wallet monitor failed to start: ${err}`);
5689
+ }
5690
+ });
5691
+ }
5692
+ }
5693
+ /**
5694
+ * Initialize the Kontext SDK.
5695
+ *
3267
5696
  * @param config - Configuration options
3268
5697
  * @returns Initialized Kontext client instance
3269
5698
  *
@@ -3291,6 +5720,29 @@ var Kontext = class _Kontext {
3291
5720
  * ```
3292
5721
  */
3293
5722
  static init(config) {
5723
+ if (!config) {
5724
+ const fileConfig = loadConfigFile();
5725
+ if (!fileConfig) {
5726
+ throw new KontextError(
5727
+ "INITIALIZATION_ERROR" /* INITIALIZATION_ERROR */,
5728
+ "No config provided and no kontext.config.json found. Run `npx kontext init` to create one, or pass config to Kontext.init()."
5729
+ );
5730
+ }
5731
+ const mapped = {
5732
+ projectId: fileConfig.projectId,
5733
+ environment: fileConfig.environment ?? "production",
5734
+ apiKey: fileConfig.apiKey,
5735
+ agentId: fileConfig.agentId,
5736
+ interceptorMode: fileConfig.mode,
5737
+ policy: {
5738
+ allowedTokens: fileConfig.tokens,
5739
+ corridors: fileConfig.corridors?.from ? { blocked: fileConfig.corridors.to ? [{ from: fileConfig.corridors.from, to: fileConfig.corridors.to }] : void 0 } : void 0,
5740
+ thresholds: fileConfig.thresholds ? { edd: fileConfig.thresholds.alertAmount ? Number(fileConfig.thresholds.alertAmount) : void 0 } : void 0
5741
+ },
5742
+ walletMonitoring: fileConfig.wallets && fileConfig.wallets.length > 0 && fileConfig.rpcEndpoints ? { wallets: fileConfig.wallets, rpcEndpoints: fileConfig.rpcEndpoints } : void 0
5743
+ };
5744
+ return _Kontext.init(mapped);
5745
+ }
3294
5746
  if (!config.projectId || config.projectId.trim() === "") {
3295
5747
  throw new KontextError(
3296
5748
  "INITIALIZATION_ERROR" /* INITIALIZATION_ERROR */,
@@ -3348,6 +5800,147 @@ var Kontext = class _Kontext {
3348
5800
  );
3349
5801
  }
3350
5802
  }
5803
+ /**
5804
+ * Map aggregated screening results into UsdcComplianceCheck format.
5805
+ * Produces the same check/riskLevel/recommendations shape as
5806
+ * UsdcCompliance.checkTransaction() and PaymentCompliance.checkPayment().
5807
+ */
5808
+ buildComplianceFromScreening(input, fromResult, toResult) {
5809
+ const checks = [];
5810
+ const fromHit = fromResult.hit;
5811
+ const fromProviders = fromResult.providerResults.filter((r) => r.hit).map((r) => r.providerId).join(", ");
5812
+ checks.push({
5813
+ name: "sanctions_sender",
5814
+ passed: !fromHit,
5815
+ description: fromHit ? `Sender flagged by: ${fromProviders}` : `Sender cleared (${fromResult.totalProviders} provider${fromResult.totalProviders !== 1 ? "s" : ""} checked)`,
5816
+ severity: fromHit ? "critical" : "low"
5817
+ });
5818
+ const toHit = toResult.hit;
5819
+ const toProviders = toResult.providerResults.filter((r) => r.hit).map((r) => r.providerId).join(", ");
5820
+ checks.push({
5821
+ name: "sanctions_recipient",
5822
+ passed: !toHit,
5823
+ description: toHit ? `Recipient flagged by: ${toProviders}` : `Recipient cleared (${toResult.totalProviders} provider${toResult.totalProviders !== 1 ? "s" : ""} checked)`,
5824
+ severity: toHit ? "critical" : "low"
5825
+ });
5826
+ const allUncovered = [
5827
+ .../* @__PURE__ */ new Set([...fromResult.uncoveredLists, ...toResult.uncoveredLists])
5828
+ ];
5829
+ if (allUncovered.length > 0) {
5830
+ checks.push({
5831
+ name: "jurisdiction_coverage",
5832
+ passed: false,
5833
+ description: `Required lists not covered: ${allUncovered.join(", ")}`,
5834
+ severity: "medium"
5835
+ });
5836
+ }
5837
+ const thresholds = this.config.policy?.thresholds;
5838
+ const eddThreshold = thresholds?.edd ?? 3e3;
5839
+ const reportingThreshold = thresholds?.reporting ?? 1e4;
5840
+ const largeThreshold = thresholds?.largeTransaction ?? 5e4;
5841
+ const amount = parseAmount(input.amount);
5842
+ if (amount >= eddThreshold) {
5843
+ checks.push({
5844
+ name: "enhanced_due_diligence",
5845
+ passed: false,
5846
+ description: `Amount $${amount.toLocaleString()} meets EDD threshold ($${eddThreshold.toLocaleString()})`,
5847
+ severity: "low"
5848
+ });
5849
+ }
5850
+ if (amount >= reportingThreshold) {
5851
+ checks.push({
5852
+ name: "reporting_threshold",
5853
+ passed: false,
5854
+ description: `Amount $${amount.toLocaleString()} meets CTR threshold ($${reportingThreshold.toLocaleString()})`,
5855
+ severity: "low"
5856
+ });
5857
+ }
5858
+ if (amount >= largeThreshold) {
5859
+ checks.push({
5860
+ name: "large_transaction",
5861
+ passed: false,
5862
+ description: `Large transaction: $${amount.toLocaleString()} exceeds $${largeThreshold.toLocaleString()}`,
5863
+ severity: "medium"
5864
+ });
5865
+ }
5866
+ const allErrors = [...fromResult.errors, ...toResult.errors];
5867
+ if (allErrors.length > 0) {
5868
+ checks.push({
5869
+ name: "screening_errors",
5870
+ passed: false,
5871
+ description: `Provider errors: ${allErrors.map((e) => `${e.providerId}: ${e.error}`).join("; ")}`,
5872
+ severity: "medium"
5873
+ });
5874
+ }
5875
+ const failedChecks = checks.filter((c) => !c.passed);
5876
+ const compliant = failedChecks.every((c) => c.severity === "low");
5877
+ const severityOrder = ["low", "medium", "high", "critical"];
5878
+ const highestSeverity = failedChecks.reduce(
5879
+ (max, c) => severityOrder.indexOf(c.severity) > severityOrder.indexOf(max) ? c.severity : max,
5880
+ "low"
5881
+ );
5882
+ const recommendations = [];
5883
+ if (fromHit || toHit) {
5884
+ recommendations.push("Block transaction: sanctions match detected");
5885
+ }
5886
+ if (allUncovered.length > 0) {
5887
+ recommendations.push(`Add providers covering: ${allUncovered.join(", ")}`);
5888
+ }
5889
+ if (amount >= eddThreshold && amount < reportingThreshold) {
5890
+ recommendations.push("Collect enhanced due diligence information");
5891
+ }
5892
+ if (amount >= reportingThreshold) {
5893
+ recommendations.push("File Currency Transaction Report (CTR)");
5894
+ }
5895
+ return {
5896
+ compliant,
5897
+ checks,
5898
+ riskLevel: highestSeverity,
5899
+ recommendations
5900
+ };
5901
+ }
5902
+ /** Lazy-init ProvenanceManager on first use. */
5903
+ getProvenanceManager() {
5904
+ if (!this.provenanceManager) {
5905
+ this.provenanceManager = new ProvenanceManager(this.store, this.logger);
5906
+ }
5907
+ return this.provenanceManager;
5908
+ }
5909
+ /** Lazy-init AgentIdentityRegistry on first use. */
5910
+ getIdentityRegistry() {
5911
+ if (!this.identityRegistry) {
5912
+ this.identityRegistry = new AgentIdentityRegistry();
5913
+ }
5914
+ return this.identityRegistry;
5915
+ }
5916
+ /** Lazy-init WalletClusterer on first use. */
5917
+ getWalletClusterer() {
5918
+ if (!this.walletClusterer) {
5919
+ this.walletClusterer = new WalletClusterer();
5920
+ }
5921
+ return this.walletClusterer;
5922
+ }
5923
+ /** Lazy-init BehavioralFingerprinter on first use. */
5924
+ getBehavioralFingerprinter() {
5925
+ if (!this.behavioralFingerprinter) {
5926
+ this.behavioralFingerprinter = new BehavioralFingerprinter();
5927
+ }
5928
+ return this.behavioralFingerprinter;
5929
+ }
5930
+ /** Lazy-init CrossSessionLinker on first use. */
5931
+ getCrossSessionLinker() {
5932
+ if (!this.crossSessionLinker) {
5933
+ this.crossSessionLinker = new CrossSessionLinker();
5934
+ }
5935
+ return this.crossSessionLinker;
5936
+ }
5937
+ /** Lazy-init KYAConfidenceScorer on first use. */
5938
+ getConfidenceScorer() {
5939
+ if (!this.confidenceScorer) {
5940
+ this.confidenceScorer = new KYAConfidenceScorer();
5941
+ }
5942
+ return this.confidenceScorer;
5943
+ }
3351
5944
  // --------------------------------------------------------------------------
3352
5945
  // Action Logging
3353
5946
  // --------------------------------------------------------------------------
@@ -3378,7 +5971,7 @@ var Kontext = class _Kontext {
3378
5971
  * @returns The created transaction record
3379
5972
  */
3380
5973
  async logTransaction(input) {
3381
- if (input.chain && input.chain !== "base") {
5974
+ if (input.chain && input.chain !== "base" && input.chain !== "arc") {
3382
5975
  requirePlan("multi-chain", this.planManager.getTier());
3383
5976
  }
3384
5977
  this.validateMetadata(input.metadata);
@@ -3733,7 +6326,28 @@ var Kontext = class _Kontext {
3733
6326
  */
3734
6327
  async verify(input) {
3735
6328
  const transaction = await this.logTransaction(input);
3736
- const compliance = isCryptoTransaction(input) ? UsdcCompliance.checkTransaction(input) : PaymentCompliance.checkPayment(input);
6329
+ let compliance;
6330
+ if (this.screeningAggregator) {
6331
+ const fromResult = await this.screeningAggregator.screen(input.from, {
6332
+ chain: input.chain,
6333
+ token: input.token,
6334
+ currency: input.currency,
6335
+ amount: input.amount,
6336
+ agentId: input.agentId
6337
+ });
6338
+ const toResult = await this.screeningAggregator.screen(input.to, {
6339
+ chain: input.chain,
6340
+ token: input.token,
6341
+ currency: input.currency,
6342
+ amount: input.amount,
6343
+ agentId: input.agentId
6344
+ });
6345
+ compliance = this.buildComplianceFromScreening(input, fromResult, toResult);
6346
+ } else if (isCryptoTransaction(input)) {
6347
+ compliance = UsdcCompliance.checkTransaction(input);
6348
+ } else {
6349
+ compliance = PaymentCompliance.checkPayment(input);
6350
+ }
3737
6351
  let reasoningId;
3738
6352
  if (input.reasoning) {
3739
6353
  const entry = await this.logReasoning({
@@ -3755,6 +6369,29 @@ var Kontext = class _Kontext {
3755
6369
  const verification = this.verifyDigestChain();
3756
6370
  const chainLength = this.logger.getDigestChain().getChainLength();
3757
6371
  const terminalDigest = this.getTerminalDigest();
6372
+ let anchorProof;
6373
+ if (input.anchor) {
6374
+ const { anchorDigest: anchorDigest2 } = await Promise.resolve().then(() => (init_onchain(), onchain_exports));
6375
+ anchorProof = await anchorDigest2(input.anchor, terminalDigest, this.config.projectId);
6376
+ }
6377
+ let counterpartyResult;
6378
+ if (input.counterparty) {
6379
+ const { exchangeAttestation: exchangeAttestation2 } = await Promise.resolve().then(() => (init_attestation(), attestation_exports));
6380
+ counterpartyResult = await exchangeAttestation2(input.counterparty, {
6381
+ senderDigest: terminalDigest,
6382
+ senderAgentId: input.agentId,
6383
+ txHash: input.txHash,
6384
+ chain: input.chain,
6385
+ amount: input.amount,
6386
+ token: input.token,
6387
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
6388
+ });
6389
+ }
6390
+ let attribution;
6391
+ if (input.erc8021 && input.txHash) {
6392
+ const { fetchTransactionAttribution: fetchTransactionAttribution2 } = await Promise.resolve().then(() => (init_erc8021(), erc8021_exports));
6393
+ attribution = await fetchTransactionAttribution2(input.erc8021.rpcUrl, input.txHash) ?? void 0;
6394
+ }
3758
6395
  let requiresApproval;
3759
6396
  let task;
3760
6397
  if (this.config.approvalThreshold) {
@@ -3796,7 +6433,10 @@ var Kontext = class _Kontext {
3796
6433
  valid: verification.valid
3797
6434
  },
3798
6435
  ...reasoningId ? { reasoningId } : {},
3799
- ...requiresApproval ? { requiresApproval, task } : {}
6436
+ ...requiresApproval ? { requiresApproval, task } : {},
6437
+ ...anchorProof ? { anchorProof } : {},
6438
+ ...counterpartyResult ? { counterparty: counterpartyResult } : {},
6439
+ ...attribution ? { attribution } : {}
3800
6440
  };
3801
6441
  }
3802
6442
  // --------------------------------------------------------------------------
@@ -3976,10 +6616,211 @@ var Kontext = class _Kontext {
3976
6616
  actions: actionSummary,
3977
6617
  reasoning: reasoningEntries
3978
6618
  };
3979
- const hash = createHash("sha256");
3980
- hash.update(JSON.stringify(certificateContent));
3981
- const contentHash = hash.digest("hex");
3982
- return { ...certificateContent, contentHash };
6619
+ const hash = createHash("sha256");
6620
+ hash.update(JSON.stringify(certificateContent));
6621
+ const contentHash = hash.digest("hex");
6622
+ return { ...certificateContent, contentHash };
6623
+ }
6624
+ // --------------------------------------------------------------------------
6625
+ // Agent Provenance
6626
+ // --------------------------------------------------------------------------
6627
+ /**
6628
+ * Create a delegated agent session. Records the delegation in the
6629
+ * tamper-evident digest chain as the session's genesis event.
6630
+ */
6631
+ async createAgentSession(input) {
6632
+ return this.getProvenanceManager().createSession(input);
6633
+ }
6634
+ /**
6635
+ * Get an agent session by ID. Automatically marks expired sessions.
6636
+ */
6637
+ getAgentSession(sessionId) {
6638
+ return this.getProvenanceManager().getSession(sessionId);
6639
+ }
6640
+ /**
6641
+ * Get all agent sessions.
6642
+ */
6643
+ getAgentSessions() {
6644
+ return this.getProvenanceManager().getSessions();
6645
+ }
6646
+ /**
6647
+ * End an active agent session. Records the termination in the digest chain.
6648
+ */
6649
+ async endAgentSession(sessionId) {
6650
+ return this.getProvenanceManager().endSession(sessionId);
6651
+ }
6652
+ /**
6653
+ * Check whether an action is within a session's delegated scope.
6654
+ */
6655
+ validateSessionScope(sessionId, action) {
6656
+ return this.getProvenanceManager().validateScope(sessionId, action);
6657
+ }
6658
+ /**
6659
+ * Get all actions bound to a session (via sessionId on log/verify calls).
6660
+ */
6661
+ getSessionActions(sessionId) {
6662
+ return this.store.getActionsBySession(sessionId);
6663
+ }
6664
+ /**
6665
+ * Create a provenance checkpoint -- a review point where a human
6666
+ * can attest to a batch of agent actions.
6667
+ */
6668
+ async createCheckpoint(input) {
6669
+ return this.getProvenanceManager().createCheckpoint(input);
6670
+ }
6671
+ /**
6672
+ * Attach an externally-produced human attestation to a checkpoint.
6673
+ * The attestation includes a cryptographic signature that the agent
6674
+ * never touches -- key separation is the critical security property.
6675
+ */
6676
+ async attachAttestation(checkpointId, attestation) {
6677
+ return this.getProvenanceManager().attachAttestation(checkpointId, attestation);
6678
+ }
6679
+ /**
6680
+ * Get a checkpoint by ID.
6681
+ */
6682
+ getCheckpoint(checkpointId) {
6683
+ return this.getProvenanceManager().getCheckpoint(checkpointId);
6684
+ }
6685
+ /**
6686
+ * Get all checkpoints, optionally filtered by session.
6687
+ */
6688
+ getCheckpoints(sessionId) {
6689
+ return this.getProvenanceManager().getCheckpoints(sessionId);
6690
+ }
6691
+ /**
6692
+ * Export the full provenance bundle for a session: session record,
6693
+ * all bound actions, all checkpoints, and verification stats.
6694
+ */
6695
+ getProvenanceBundle(sessionId) {
6696
+ return this.getProvenanceManager().getProvenanceBundle(sessionId);
6697
+ }
6698
+ // --------------------------------------------------------------------------
6699
+ // Agent Forensics (KYA)
6700
+ // --------------------------------------------------------------------------
6701
+ /**
6702
+ * Register a new agent identity with optional wallet mappings.
6703
+ * Requires Pro plan.
6704
+ */
6705
+ registerAgentIdentity(input) {
6706
+ requirePlan("kya-identity", this.planManager.getTier());
6707
+ return this.getIdentityRegistry().register(input);
6708
+ }
6709
+ /**
6710
+ * Get a registered agent identity by ID.
6711
+ * Requires Pro plan.
6712
+ */
6713
+ getAgentIdentity(agentId) {
6714
+ requirePlan("kya-identity", this.planManager.getTier());
6715
+ return this.getIdentityRegistry().get(agentId);
6716
+ }
6717
+ /**
6718
+ * Update an existing agent identity.
6719
+ * Requires Pro plan.
6720
+ */
6721
+ updateAgentIdentity(agentId, input) {
6722
+ requirePlan("kya-identity", this.planManager.getTier());
6723
+ return this.getIdentityRegistry().update(agentId, input);
6724
+ }
6725
+ /**
6726
+ * Remove an agent identity.
6727
+ * Requires Pro plan.
6728
+ */
6729
+ removeAgentIdentity(agentId) {
6730
+ requirePlan("kya-identity", this.planManager.getTier());
6731
+ return this.getIdentityRegistry().remove(agentId);
6732
+ }
6733
+ /**
6734
+ * Add a wallet to an existing agent identity.
6735
+ * Requires Pro plan.
6736
+ */
6737
+ addAgentWallet(agentId, wallet) {
6738
+ requirePlan("kya-identity", this.planManager.getTier());
6739
+ return this.getIdentityRegistry().addWallet(agentId, wallet);
6740
+ }
6741
+ /**
6742
+ * Look up which agent owns a wallet address.
6743
+ * Requires Pro plan.
6744
+ */
6745
+ lookupAgentByWallet(address) {
6746
+ requirePlan("kya-identity", this.planManager.getTier());
6747
+ return this.getIdentityRegistry().lookupByWallet(address);
6748
+ }
6749
+ /**
6750
+ * Compute wallet clusters from transaction patterns and declared identities.
6751
+ * Requires Pro plan.
6752
+ */
6753
+ getWalletClusters() {
6754
+ requirePlan("kya-identity", this.planManager.getTier());
6755
+ const clusterer = this.getWalletClusterer();
6756
+ clusterer.analyzeFromStore(this.store, this.getIdentityRegistry());
6757
+ return clusterer.getClusters();
6758
+ }
6759
+ /**
6760
+ * Export all KYA data as a single envelope.
6761
+ * Requires Pro plan.
6762
+ */
6763
+ getKYAExport() {
6764
+ requirePlan("kya-identity", this.planManager.getTier());
6765
+ const registry = this.getIdentityRegistry();
6766
+ const clusterer = this.getWalletClusterer();
6767
+ clusterer.analyzeFromStore(this.store, registry);
6768
+ return {
6769
+ identities: registry.getAll(),
6770
+ clusters: clusterer.getClusters(),
6771
+ embeddings: [],
6772
+ links: [],
6773
+ scores: [],
6774
+ generatedAt: now()
6775
+ };
6776
+ }
6777
+ /**
6778
+ * Compute a behavioral embedding for an agent from transaction history.
6779
+ * Returns null if insufficient data. Requires Enterprise plan.
6780
+ */
6781
+ computeBehavioralEmbedding(agentId) {
6782
+ requirePlan("kya-behavioral", this.planManager.getTier());
6783
+ return this.getBehavioralFingerprinter().computeEmbedding(agentId, this.store);
6784
+ }
6785
+ /**
6786
+ * Analyze all agents and create cross-session links.
6787
+ * Requires Enterprise plan.
6788
+ */
6789
+ analyzeAgentLinks() {
6790
+ requirePlan("kya-behavioral", this.planManager.getTier());
6791
+ const clusterer = this.getWalletClusterer();
6792
+ clusterer.analyzeFromStore(this.store, this.getIdentityRegistry());
6793
+ return this.getCrossSessionLinker().analyzeAndLink(
6794
+ this.store,
6795
+ this.getIdentityRegistry(),
6796
+ clusterer,
6797
+ this.getBehavioralFingerprinter()
6798
+ );
6799
+ }
6800
+ /**
6801
+ * Get agents linked to a specific agent.
6802
+ * Requires Enterprise plan.
6803
+ */
6804
+ getLinkedAgents(agentId) {
6805
+ requirePlan("kya-behavioral", this.planManager.getTier());
6806
+ return this.getCrossSessionLinker().getLinkedAgents(agentId);
6807
+ }
6808
+ /**
6809
+ * Compute a composite identity confidence score for an agent.
6810
+ * Requires Enterprise plan.
6811
+ */
6812
+ getKYAConfidenceScore(agentId) {
6813
+ requirePlan("kya-behavioral", this.planManager.getTier());
6814
+ const clusterer = this.getWalletClusterer();
6815
+ clusterer.analyzeFromStore(this.store, this.getIdentityRegistry());
6816
+ return this.getConfidenceScorer().computeScore(
6817
+ agentId,
6818
+ this.getIdentityRegistry(),
6819
+ clusterer,
6820
+ this.getBehavioralFingerprinter(),
6821
+ this.getCrossSessionLinker(),
6822
+ this.store
6823
+ );
3983
6824
  }
3984
6825
  // --------------------------------------------------------------------------
3985
6826
  // Plan & Usage Metering
@@ -4082,9 +6923,20 @@ var Kontext = class _Kontext {
4082
6923
  // Lifecycle
4083
6924
  // --------------------------------------------------------------------------
4084
6925
  /**
4085
- * Gracefully shut down the SDK, flushing any pending data.
6926
+ * Get the wallet monitor instance (or null if not configured).
6927
+ * Used by the viem interceptor for dedup registration.
6928
+ */
6929
+ getWalletMonitor() {
6930
+ return this.walletMonitor;
6931
+ }
6932
+ /**
6933
+ * Gracefully shut down the SDK, flushing any pending data and stopping watchers.
4086
6934
  */
4087
6935
  async destroy() {
6936
+ if (this.walletMonitor) {
6937
+ this.walletMonitor.stop();
6938
+ this.walletMonitor = null;
6939
+ }
4088
6940
  await this.logger.destroy();
4089
6941
  await this.exporter.shutdown();
4090
6942
  }
@@ -4114,20 +6966,20 @@ var MemoryStorage = class {
4114
6966
  var FileStorage = class {
4115
6967
  baseDir;
4116
6968
  constructor(baseDir) {
4117
- this.baseDir = path4.resolve(baseDir);
6969
+ this.baseDir = path5.resolve(baseDir);
4118
6970
  }
4119
6971
  async save(key, data) {
4120
- fs4.mkdirSync(this.baseDir, { recursive: true });
6972
+ fs5.mkdirSync(this.baseDir, { recursive: true });
4121
6973
  const filePath = this.keyToPath(key);
4122
- const dir = path4.dirname(filePath);
4123
- fs4.mkdirSync(dir, { recursive: true });
4124
- fs4.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
6974
+ const dir = path5.dirname(filePath);
6975
+ fs5.mkdirSync(dir, { recursive: true });
6976
+ fs5.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
4125
6977
  }
4126
6978
  async load(key) {
4127
6979
  const filePath = this.keyToPath(key);
4128
- if (!fs4.existsSync(filePath)) return null;
6980
+ if (!fs5.existsSync(filePath)) return null;
4129
6981
  try {
4130
- const raw = fs4.readFileSync(filePath, "utf-8");
6982
+ const raw = fs5.readFileSync(filePath, "utf-8");
4131
6983
  return JSON.parse(raw);
4132
6984
  } catch {
4133
6985
  return null;
@@ -4135,12 +6987,12 @@ var FileStorage = class {
4135
6987
  }
4136
6988
  async delete(key) {
4137
6989
  const filePath = this.keyToPath(key);
4138
- if (fs4.existsSync(filePath)) {
4139
- fs4.unlinkSync(filePath);
6990
+ if (fs5.existsSync(filePath)) {
6991
+ fs5.unlinkSync(filePath);
4140
6992
  }
4141
6993
  }
4142
6994
  async list(prefix) {
4143
- if (!fs4.existsSync(this.baseDir)) return [];
6995
+ if (!fs5.existsSync(this.baseDir)) return [];
4144
6996
  return this.listRecursive(this.baseDir, prefix);
4145
6997
  }
4146
6998
  /** Get the base directory path. */
@@ -4152,18 +7004,18 @@ var FileStorage = class {
4152
7004
  // --------------------------------------------------------------------------
4153
7005
  keyToPath(key) {
4154
7006
  const safeName = key.replace(/[<>"|?*]/g, "_");
4155
- return path4.join(this.baseDir, `${safeName}.json`);
7007
+ return path5.join(this.baseDir, `${safeName}.json`);
4156
7008
  }
4157
7009
  pathToKey(filePath) {
4158
- const relative2 = path4.relative(this.baseDir, filePath);
7010
+ const relative2 = path5.relative(this.baseDir, filePath);
4159
7011
  return relative2.replace(/\.json$/, "");
4160
7012
  }
4161
7013
  listRecursive(dir, prefix) {
4162
7014
  const keys = [];
4163
- if (!fs4.existsSync(dir)) return keys;
4164
- const entries = fs4.readdirSync(dir, { withFileTypes: true });
7015
+ if (!fs5.existsSync(dir)) return keys;
7016
+ const entries = fs5.readdirSync(dir, { withFileTypes: true });
4165
7017
  for (const entry of entries) {
4166
- const fullPath = path4.join(dir, entry.name);
7018
+ const fullPath = path5.join(dir, entry.name);
4167
7019
  if (entry.isDirectory()) {
4168
7020
  keys.push(...this.listRecursive(fullPath, prefix));
4169
7021
  } else if (entry.isFile() && entry.name.endsWith(".json")) {
@@ -4177,6 +7029,906 @@ var FileStorage = class {
4177
7029
  }
4178
7030
  };
4179
7031
 
4180
- export { AnomalyDetector, ConsoleExporter, DigestChain, FeatureFlagManager, FileStorage, JsonFileExporter, Kontext, KontextError, KontextErrorCode, MemoryStorage, NoopExporter, PLAN_LIMITS, PaymentCompliance, PlanManager, TrustScorer, UsdcCompliance, isCryptoTransaction, isFeatureAvailable, requirePlan, verifyExportedChain };
7032
+ // src/index.ts
7033
+ init_onchain();
7034
+ init_erc8021();
7035
+ init_attestation();
7036
+
7037
+ // src/integrations/provider-treasury-sdn.ts
7038
+ var ACTIVE_SET = new Set(
7039
+ OFAC_SDN_ACTIVE_ADDRESSES.map((a) => a.toLowerCase())
7040
+ );
7041
+ var DELISTED_SET = new Set(
7042
+ OFAC_SDN_DELISTED_ADDRESSES.map((a) => a.toLowerCase())
7043
+ );
7044
+ var ALL_SET = new Set(
7045
+ OFAC_SDN_ADDRESSES.map((a) => a.toLowerCase())
7046
+ );
7047
+ var ORIGINAL_CASE = /* @__PURE__ */ new Map();
7048
+ for (const addr of OFAC_SDN_ADDRESSES) {
7049
+ ORIGINAL_CASE.set(addr.toLowerCase(), addr);
7050
+ }
7051
+ var OFACAddressProvider = class {
7052
+ id = "ofac-sdn-address";
7053
+ name = "OFAC SDN Address Screener";
7054
+ lists = ["OFAC_SDN"];
7055
+ requiresApiKey = false;
7056
+ browserCompatible = true;
7057
+ queryTypes = ["address"];
7058
+ async screen(query, _context) {
7059
+ const start = Date.now();
7060
+ const lower = query.toLowerCase();
7061
+ const matches = [];
7062
+ if (ACTIVE_SET.has(lower)) {
7063
+ const originalAddr = ORIGINAL_CASE.get(lower) ?? query;
7064
+ matches.push({
7065
+ list: "OFAC_SDN",
7066
+ matchType: "exact_address",
7067
+ similarity: 1,
7068
+ matchedValue: originalAddr,
7069
+ entityStatus: "active",
7070
+ program: "SDN"
7071
+ });
7072
+ } else if (DELISTED_SET.has(lower)) {
7073
+ const originalAddr = ORIGINAL_CASE.get(lower) ?? query;
7074
+ matches.push({
7075
+ list: "OFAC_SDN",
7076
+ matchType: "exact_address",
7077
+ similarity: 1,
7078
+ matchedValue: originalAddr,
7079
+ entityStatus: "delisted",
7080
+ program: "SDN_DELISTED"
7081
+ });
7082
+ }
7083
+ const hasActiveHit = matches.some((m) => m.entityStatus === "active");
7084
+ return {
7085
+ providerId: this.id,
7086
+ hit: hasActiveHit,
7087
+ matches,
7088
+ listsChecked: this.lists,
7089
+ entriesSearched: ALL_SET.size,
7090
+ durationMs: Date.now() - start
7091
+ };
7092
+ }
7093
+ isAvailable() {
7094
+ return true;
7095
+ }
7096
+ getEntryCount() {
7097
+ return ALL_SET.size;
7098
+ }
7099
+ };
7100
+
7101
+ // src/integrations/provider-ofac-entity.ts
7102
+ var NAME_MATCH_THRESHOLD2 = 0.85;
7103
+ var MIN_MATCH_LENGTH = 4;
7104
+ var _screener2 = null;
7105
+ var _screenerLoaded2 = false;
7106
+ function getScreener2() {
7107
+ if (!_screenerLoaded2) {
7108
+ _screenerLoaded2 = true;
7109
+ try {
7110
+ const mod = __require("./ofac-sanctions.js");
7111
+ if (mod.OFACSanctionsScreener) {
7112
+ _screener2 = new mod.OFACSanctionsScreener();
7113
+ }
7114
+ } catch {
7115
+ }
7116
+ }
7117
+ return _screener2;
7118
+ }
7119
+ var OFACEntityProvider = class {
7120
+ id = "ofac-sdn-entity";
7121
+ name = "OFAC SDN Entity Screener";
7122
+ lists = ["OFAC_SDN"];
7123
+ requiresApiKey = false;
7124
+ browserCompatible = false;
7125
+ queryTypes = ["entity_name"];
7126
+ async screen(query, _context) {
7127
+ const start = Date.now();
7128
+ const screener = getScreener2();
7129
+ if (!screener) {
7130
+ return {
7131
+ providerId: this.id,
7132
+ hit: false,
7133
+ matches: [],
7134
+ listsChecked: this.lists,
7135
+ entriesSearched: 0,
7136
+ durationMs: Date.now() - start,
7137
+ error: "OFACSanctionsScreener not available"
7138
+ };
7139
+ }
7140
+ const rawMatches = screener.searchEntityName(query, NAME_MATCH_THRESHOLD2);
7141
+ const filteredMatches = rawMatches.filter(
7142
+ (m) => m.similarity >= NAME_MATCH_THRESHOLD2 && m.matchedOn.length >= MIN_MATCH_LENGTH
7143
+ );
7144
+ const matches = filteredMatches.map((m) => {
7145
+ const isActive = m.entity.list !== "DELISTED";
7146
+ return {
7147
+ list: "OFAC_SDN",
7148
+ matchType: m.similarity >= 0.99 ? "exact_address" : "fuzzy_name",
7149
+ similarity: m.similarity,
7150
+ matchedValue: m.matchedOn,
7151
+ entityStatus: isActive ? "active" : "delisted",
7152
+ entityName: m.entity.name,
7153
+ program: m.entity.programs?.[0]
7154
+ };
7155
+ });
7156
+ const hasActiveHit = matches.some((m) => m.entityStatus === "active");
7157
+ return {
7158
+ providerId: this.id,
7159
+ hit: hasActiveHit,
7160
+ matches,
7161
+ listsChecked: this.lists,
7162
+ entriesSearched: screener.getEntityCount?.() ?? 0,
7163
+ durationMs: Date.now() - start
7164
+ };
7165
+ }
7166
+ isAvailable() {
7167
+ return getScreener2() !== null;
7168
+ }
7169
+ getEntryCount() {
7170
+ const screener = getScreener2();
7171
+ return screener?.getEntityCount?.() ?? 0;
7172
+ }
7173
+ };
7174
+
7175
+ // src/integrations/data/uk-ofsi-addresses.ts
7176
+ var UK_OFSI_ADDRESSES = [
7177
+ // Garantex (designated under Russia sanctions regime, May 2024)
7178
+ "0x6F1cA141A28907F78Ebaa64f83E4AE6038d3cbe7",
7179
+ // Lazarus Group / DPRK (overlaps with OFAC SDN but independently listed by OFSI)
7180
+ "0x098B716B8Aaf21512996dC57EB0615e2383E2f96",
7181
+ "0xa0e1c89Ef1a489c9C7dE96311eD5Ce5D32c20E4B",
7182
+ "0x3Cffd56B47B7b41c56258D9C7731ABaDc360E460",
7183
+ "0x53b6936513e738f44FB50d2b9476730C0Ab3Bfc1",
7184
+ // DPRK-linked addresses (OFSI cyber programme)
7185
+ "0x7F367cC41522cE07553e823bf3be79A889DEbe1B",
7186
+ "0x01e2919679362dFBC9ee1644Ba9C6da6D6245BB1"
7187
+ ];
7188
+
7189
+ // src/integrations/provider-uk-ofsi.ts
7190
+ var ADDRESS_SET = new Set(
7191
+ UK_OFSI_ADDRESSES.map((a) => a.toLowerCase())
7192
+ );
7193
+ var ORIGINAL_CASE2 = /* @__PURE__ */ new Map();
7194
+ for (const addr of UK_OFSI_ADDRESSES) {
7195
+ ORIGINAL_CASE2.set(addr.toLowerCase(), addr);
7196
+ }
7197
+ var UKOFSIProvider = class {
7198
+ id = "uk-ofsi-address";
7199
+ name = "UK OFSI Address Screener";
7200
+ lists = ["UK_OFSI"];
7201
+ requiresApiKey = false;
7202
+ browserCompatible = true;
7203
+ queryTypes = ["address"];
7204
+ async screen(query, _context) {
7205
+ const start = Date.now();
7206
+ const lower = query.toLowerCase();
7207
+ const matches = [];
7208
+ if (ADDRESS_SET.has(lower)) {
7209
+ const originalAddr = ORIGINAL_CASE2.get(lower) ?? query;
7210
+ matches.push({
7211
+ list: "UK_OFSI",
7212
+ matchType: "exact_address",
7213
+ similarity: 1,
7214
+ matchedValue: originalAddr,
7215
+ entityStatus: "active",
7216
+ program: "OFSI_CONSOLIDATED"
7217
+ });
7218
+ }
7219
+ return {
7220
+ providerId: this.id,
7221
+ hit: matches.length > 0,
7222
+ matches,
7223
+ listsChecked: this.lists,
7224
+ entriesSearched: ADDRESS_SET.size,
7225
+ durationMs: Date.now() - start
7226
+ };
7227
+ }
7228
+ isAvailable() {
7229
+ return true;
7230
+ }
7231
+ getEntryCount() {
7232
+ return ADDRESS_SET.size;
7233
+ }
7234
+ };
7235
+
7236
+ // src/integrations/provider-opensanctions-local.ts
7237
+ var NAME_MATCH_THRESHOLD3 = 0.85;
7238
+ var MIN_MATCH_LENGTH2 = 4;
7239
+ var DEFAULT_DATA_DIR = ".kontext/sanctions";
7240
+ function trigramSimilarity(a, b) {
7241
+ const aNorm = a.toLowerCase().trim();
7242
+ const bNorm = b.toLowerCase().trim();
7243
+ if (aNorm === bNorm) return 1;
7244
+ if (aNorm.length < 2 || bNorm.length < 2) return 0;
7245
+ const trigramsA = /* @__PURE__ */ new Set();
7246
+ const trigramsB = /* @__PURE__ */ new Set();
7247
+ for (let i = 0; i <= aNorm.length - 3; i++) {
7248
+ trigramsA.add(aNorm.slice(i, i + 3));
7249
+ }
7250
+ for (let i = 0; i <= bNorm.length - 3; i++) {
7251
+ trigramsB.add(bNorm.slice(i, i + 3));
7252
+ }
7253
+ if (trigramsA.size === 0 || trigramsB.size === 0) return 0;
7254
+ let intersection = 0;
7255
+ for (const t of trigramsA) {
7256
+ if (trigramsB.has(t)) intersection++;
7257
+ }
7258
+ return 2 * intersection / (trigramsA.size + trigramsB.size);
7259
+ }
7260
+ var OpenSanctionsLocalProvider = class {
7261
+ id = "opensanctions-local";
7262
+ name = "OpenSanctions (Local Data)";
7263
+ lists = ["OPENSANCTIONS"];
7264
+ requiresApiKey = false;
7265
+ browserCompatible = false;
7266
+ queryTypes = ["both"];
7267
+ dataDir;
7268
+ entities = [];
7269
+ addressSet = /* @__PURE__ */ new Set();
7270
+ addressToEntity = /* @__PURE__ */ new Map();
7271
+ loaded = false;
7272
+ constructor(dataDir) {
7273
+ this.dataDir = dataDir ?? this.resolveDataDir();
7274
+ }
7275
+ async screen(query, _context) {
7276
+ const start = Date.now();
7277
+ if (!this.loaded) {
7278
+ this.loadData();
7279
+ }
7280
+ if (this.entities.length === 0) {
7281
+ return {
7282
+ providerId: this.id,
7283
+ hit: false,
7284
+ matches: [],
7285
+ listsChecked: this.lists,
7286
+ entriesSearched: 0,
7287
+ durationMs: Date.now() - start,
7288
+ error: "No local OpenSanctions data. Run: kontext sync --lists default"
7289
+ };
7290
+ }
7291
+ const matches = isBlockchainAddress(query) ? this.screenAddress(query) : this.screenEntityName(query);
7292
+ const hasActiveHit = matches.some((m) => m.entityStatus === "active");
7293
+ return {
7294
+ providerId: this.id,
7295
+ hit: hasActiveHit,
7296
+ matches,
7297
+ listsChecked: this.lists,
7298
+ entriesSearched: this.entities.length,
7299
+ durationMs: Date.now() - start
7300
+ };
7301
+ }
7302
+ isAvailable() {
7303
+ if (!this.loaded) {
7304
+ this.loadData();
7305
+ }
7306
+ return this.entities.length > 0;
7307
+ }
7308
+ getEntryCount() {
7309
+ if (!this.loaded) {
7310
+ this.loadData();
7311
+ }
7312
+ return this.entities.length;
7313
+ }
7314
+ async sync() {
7315
+ this.loaded = false;
7316
+ this.loadData();
7317
+ return { updated: true, count: this.entities.length };
7318
+ }
7319
+ // --------------------------------------------------------------------------
7320
+ // Private
7321
+ // --------------------------------------------------------------------------
7322
+ screenAddress(address) {
7323
+ const lower = address.toLowerCase();
7324
+ const entity = this.addressToEntity.get(lower);
7325
+ if (!entity) return [];
7326
+ const entityStatus = this.getEntityStatus(entity);
7327
+ return [
7328
+ {
7329
+ list: "OPENSANCTIONS",
7330
+ matchType: "exact_address",
7331
+ similarity: 1,
7332
+ matchedValue: address,
7333
+ entityStatus,
7334
+ entityName: entity.caption,
7335
+ program: entity.datasets.join(", ")
7336
+ }
7337
+ ];
7338
+ }
7339
+ screenEntityName(query) {
7340
+ const matches = [];
7341
+ const queryLower = query.toLowerCase().trim();
7342
+ for (const entity of this.entities) {
7343
+ const captionSim = trigramSimilarity(queryLower, entity.caption);
7344
+ if (captionSim >= NAME_MATCH_THRESHOLD3 && entity.caption.length >= MIN_MATCH_LENGTH2) {
7345
+ matches.push(this.entityToMatch(entity, entity.caption, captionSim));
7346
+ continue;
7347
+ }
7348
+ const aliases = entity.properties["alias"] ?? [];
7349
+ for (const alias of aliases) {
7350
+ const aliasSim = trigramSimilarity(queryLower, alias);
7351
+ if (aliasSim >= NAME_MATCH_THRESHOLD3 && alias.length >= MIN_MATCH_LENGTH2) {
7352
+ matches.push(this.entityToMatch(entity, alias, aliasSim));
7353
+ break;
7354
+ }
7355
+ }
7356
+ }
7357
+ matches.sort((a, b) => b.similarity - a.similarity);
7358
+ return matches.slice(0, 5);
7359
+ }
7360
+ entityToMatch(entity, matchedValue, similarity) {
7361
+ return {
7362
+ list: "OPENSANCTIONS",
7363
+ matchType: similarity >= 0.99 ? "exact_address" : "fuzzy_name",
7364
+ similarity,
7365
+ matchedValue,
7366
+ entityStatus: this.getEntityStatus(entity),
7367
+ entityName: entity.caption,
7368
+ program: entity.datasets.join(", ")
7369
+ };
7370
+ }
7371
+ getEntityStatus(entity) {
7372
+ return "active";
7373
+ }
7374
+ loadData() {
7375
+ this.loaded = true;
7376
+ this.entities = [];
7377
+ this.addressSet.clear();
7378
+ this.addressToEntity.clear();
7379
+ try {
7380
+ const fs6 = __require("fs");
7381
+ const pathMod = __require("path");
7382
+ const dataPath = pathMod.resolve(this.dataDir);
7383
+ if (!fs6.existsSync(dataPath)) return;
7384
+ const files = fs6.readdirSync(dataPath).filter(
7385
+ (f) => f.endsWith(".json")
7386
+ );
7387
+ for (const file of files) {
7388
+ const filePath = pathMod.join(dataPath, file);
7389
+ const content = fs6.readFileSync(filePath, "utf-8");
7390
+ const lines = content.split("\n").filter((l) => l.trim());
7391
+ for (const line of lines) {
7392
+ try {
7393
+ const entity = JSON.parse(line);
7394
+ this.entities.push(entity);
7395
+ const addresses = entity.properties["cryptoAddress"] ?? [];
7396
+ for (const addr of addresses) {
7397
+ const lower = addr.toLowerCase();
7398
+ this.addressSet.add(lower);
7399
+ this.addressToEntity.set(lower, entity);
7400
+ }
7401
+ } catch {
7402
+ }
7403
+ }
7404
+ }
7405
+ } catch {
7406
+ }
7407
+ }
7408
+ resolveDataDir() {
7409
+ try {
7410
+ const os = __require("os");
7411
+ const pathMod = __require("path");
7412
+ return pathMod.join(os.homedir(), DEFAULT_DATA_DIR);
7413
+ } catch {
7414
+ return DEFAULT_DATA_DIR;
7415
+ }
7416
+ }
7417
+ };
7418
+
7419
+ // src/integrations/provider-apis.ts
7420
+ var OpenSanctionsProvider = class {
7421
+ id = "opensanctions-api";
7422
+ name = "OpenSanctions (API)";
7423
+ lists = ["OPENSANCTIONS"];
7424
+ requiresApiKey = true;
7425
+ browserCompatible = false;
7426
+ queryTypes = ["both"];
7427
+ apiKey;
7428
+ baseUrl;
7429
+ dataset;
7430
+ constructor(config) {
7431
+ this.apiKey = config.apiKey;
7432
+ this.baseUrl = config.baseUrl ?? "https://api.opensanctions.org";
7433
+ this.dataset = config.dataset ?? "default";
7434
+ }
7435
+ async screen(query, _context) {
7436
+ const start = Date.now();
7437
+ const isAddr = isBlockchainAddress(query);
7438
+ const schema = isAddr ? "CryptoWallet" : "LegalEntity";
7439
+ const properties = isAddr ? { cryptoAddress: [query] } : { name: [query] };
7440
+ const body = {
7441
+ queries: {
7442
+ q: {
7443
+ schema,
7444
+ properties
7445
+ }
7446
+ }
7447
+ };
7448
+ try {
7449
+ const response = await fetch(
7450
+ `${this.baseUrl}/match/${this.dataset}`,
7451
+ {
7452
+ method: "POST",
7453
+ headers: {
7454
+ "Content-Type": "application/json",
7455
+ "Authorization": `ApiKey ${this.apiKey}`
7456
+ },
7457
+ body: JSON.stringify(body)
7458
+ }
7459
+ );
7460
+ if (!response.ok) {
7461
+ return {
7462
+ providerId: this.id,
7463
+ hit: false,
7464
+ matches: [],
7465
+ listsChecked: this.lists,
7466
+ entriesSearched: 0,
7467
+ durationMs: Date.now() - start,
7468
+ error: `OpenSanctions API error: ${response.status} ${response.statusText}`
7469
+ };
7470
+ }
7471
+ const data = await response.json();
7472
+ const queryResult = data.responses?.["q"];
7473
+ if (!queryResult) {
7474
+ return {
7475
+ providerId: this.id,
7476
+ hit: false,
7477
+ matches: [],
7478
+ listsChecked: this.lists,
7479
+ entriesSearched: 0,
7480
+ durationMs: Date.now() - start
7481
+ };
7482
+ }
7483
+ const matches = queryResult.results.filter((r) => r.match && r.score >= 0.7).map((r) => ({
7484
+ list: "OPENSANCTIONS",
7485
+ matchType: r.score >= 0.99 ? "exact_address" : "fuzzy_name",
7486
+ similarity: r.score,
7487
+ matchedValue: r.caption,
7488
+ entityStatus: "active",
7489
+ entityName: r.caption,
7490
+ program: r.datasets.join(", ")
7491
+ }));
7492
+ const hasActiveHit = matches.some((m) => m.entityStatus === "active");
7493
+ return {
7494
+ providerId: this.id,
7495
+ hit: hasActiveHit,
7496
+ matches,
7497
+ listsChecked: this.lists,
7498
+ entriesSearched: queryResult.total?.value ?? 0,
7499
+ durationMs: Date.now() - start
7500
+ };
7501
+ } catch (err) {
7502
+ return {
7503
+ providerId: this.id,
7504
+ hit: false,
7505
+ matches: [],
7506
+ listsChecked: this.lists,
7507
+ entriesSearched: 0,
7508
+ durationMs: Date.now() - start,
7509
+ error: `OpenSanctions API error: ${err instanceof Error ? err.message : String(err)}`
7510
+ };
7511
+ }
7512
+ }
7513
+ isAvailable() {
7514
+ return !!this.apiKey;
7515
+ }
7516
+ };
7517
+ var ChainalysisFreeAPIProvider = class {
7518
+ id = "chainalysis-free-api";
7519
+ name = "Chainalysis Free API";
7520
+ lists = ["CHAINALYSIS"];
7521
+ requiresApiKey = true;
7522
+ browserCompatible = false;
7523
+ queryTypes = ["address"];
7524
+ apiKey;
7525
+ baseUrl;
7526
+ constructor(config) {
7527
+ this.apiKey = config.apiKey;
7528
+ this.baseUrl = config.baseUrl ?? "https://public.chainalysis.com/api/v1";
7529
+ }
7530
+ async screen(query, _context) {
7531
+ const start = Date.now();
7532
+ try {
7533
+ const response = await fetch(
7534
+ `${this.baseUrl}/address/${query}`,
7535
+ {
7536
+ method: "GET",
7537
+ headers: {
7538
+ "X-API-Key": this.apiKey,
7539
+ "Accept": "application/json"
7540
+ }
7541
+ }
7542
+ );
7543
+ if (!response.ok) {
7544
+ return {
7545
+ providerId: this.id,
7546
+ hit: false,
7547
+ matches: [],
7548
+ listsChecked: this.lists,
7549
+ entriesSearched: 0,
7550
+ durationMs: Date.now() - start,
7551
+ error: `Chainalysis API error: ${response.status} ${response.statusText}`
7552
+ };
7553
+ }
7554
+ const data = await response.json();
7555
+ const identifications = data.identifications ?? [];
7556
+ const matches = identifications.map((id) => ({
7557
+ list: "CHAINALYSIS",
7558
+ matchType: "exact_address",
7559
+ similarity: 1,
7560
+ matchedValue: query,
7561
+ entityStatus: "active",
7562
+ entityName: id.name,
7563
+ program: id.category
7564
+ }));
7565
+ return {
7566
+ providerId: this.id,
7567
+ hit: matches.length > 0,
7568
+ matches,
7569
+ listsChecked: this.lists,
7570
+ entriesSearched: 1,
7571
+ durationMs: Date.now() - start
7572
+ };
7573
+ } catch (err) {
7574
+ return {
7575
+ providerId: this.id,
7576
+ hit: false,
7577
+ matches: [],
7578
+ listsChecked: this.lists,
7579
+ entriesSearched: 0,
7580
+ durationMs: Date.now() - start,
7581
+ error: `Chainalysis API error: ${err instanceof Error ? err.message : String(err)}`
7582
+ };
7583
+ }
7584
+ }
7585
+ isAvailable() {
7586
+ return !!this.apiKey;
7587
+ }
7588
+ };
7589
+
7590
+ // src/integrations/provider-ofac.ts
7591
+ var ORACLE_CONTRACT = "0x40C57923924B5c5c5455c48D93317139ADDaC8fb";
7592
+ var IS_SANCTIONED_SELECTOR = "0xdfb80831";
7593
+ var ChainalysisOracleProvider = class {
7594
+ id = "chainalysis-oracle";
7595
+ name = "Chainalysis OFAC Oracle";
7596
+ lists = ["OFAC_SDN", "CHAINALYSIS"];
7597
+ requiresApiKey = true;
7598
+ browserCompatible = false;
7599
+ queryTypes = ["address"];
7600
+ apiKey;
7601
+ rpcUrl;
7602
+ apiBaseUrl;
7603
+ constructor(config) {
7604
+ this.apiKey = config.apiKey;
7605
+ this.rpcUrl = config.rpcUrl;
7606
+ this.apiBaseUrl = config.apiBaseUrl ?? "https://public.chainalysis.com/api/v1";
7607
+ }
7608
+ async screen(query, _context) {
7609
+ const start = Date.now();
7610
+ if (this.rpcUrl) {
7611
+ return this.screenOnChain(query, start);
7612
+ }
7613
+ if (this.apiKey) {
7614
+ return this.screenApi(query, start);
7615
+ }
7616
+ return {
7617
+ providerId: this.id,
7618
+ hit: false,
7619
+ matches: [],
7620
+ listsChecked: this.lists,
7621
+ entriesSearched: 0,
7622
+ durationMs: Date.now() - start,
7623
+ error: "No API key or RPC URL configured"
7624
+ };
7625
+ }
7626
+ isAvailable() {
7627
+ return !!(this.apiKey || this.rpcUrl);
7628
+ }
7629
+ // --------------------------------------------------------------------------
7630
+ // On-chain oracle query
7631
+ // --------------------------------------------------------------------------
7632
+ async screenOnChain(address, start) {
7633
+ try {
7634
+ const paddedAddress = address.toLowerCase().replace("0x", "").padStart(64, "0");
7635
+ const callData = IS_SANCTIONED_SELECTOR + paddedAddress;
7636
+ const response = await fetch(this.rpcUrl, {
7637
+ method: "POST",
7638
+ headers: { "Content-Type": "application/json" },
7639
+ body: JSON.stringify({
7640
+ jsonrpc: "2.0",
7641
+ id: 1,
7642
+ method: "eth_call",
7643
+ params: [
7644
+ { to: ORACLE_CONTRACT, data: callData },
7645
+ "latest"
7646
+ ]
7647
+ })
7648
+ });
7649
+ if (!response.ok) {
7650
+ return this.errorResult(start, `RPC error: ${response.status}`);
7651
+ }
7652
+ const data = await response.json();
7653
+ if (data.error) {
7654
+ return this.errorResult(start, `RPC error: ${data.error.message}`);
7655
+ }
7656
+ const isSanctioned = data.result ? parseInt(data.result.slice(-2), 16) === 1 : false;
7657
+ const matches = isSanctioned ? [{
7658
+ list: "OFAC_SDN",
7659
+ matchType: "exact_address",
7660
+ similarity: 1,
7661
+ matchedValue: address,
7662
+ entityStatus: "active",
7663
+ program: "CHAINALYSIS_ORACLE"
7664
+ }] : [];
7665
+ return {
7666
+ providerId: this.id,
7667
+ hit: isSanctioned,
7668
+ matches,
7669
+ listsChecked: this.lists,
7670
+ entriesSearched: 1,
7671
+ durationMs: Date.now() - start
7672
+ };
7673
+ } catch (err) {
7674
+ return this.errorResult(
7675
+ start,
7676
+ `Oracle query failed: ${err instanceof Error ? err.message : String(err)}`
7677
+ );
7678
+ }
7679
+ }
7680
+ // --------------------------------------------------------------------------
7681
+ // REST API query
7682
+ // --------------------------------------------------------------------------
7683
+ async screenApi(address, start) {
7684
+ try {
7685
+ const response = await fetch(
7686
+ `${this.apiBaseUrl}/address/${address}`,
7687
+ {
7688
+ method: "GET",
7689
+ headers: {
7690
+ "X-API-Key": this.apiKey,
7691
+ "Accept": "application/json"
7692
+ }
7693
+ }
7694
+ );
7695
+ if (!response.ok) {
7696
+ return this.errorResult(
7697
+ start,
7698
+ `Chainalysis API error: ${response.status} ${response.statusText}`
7699
+ );
7700
+ }
7701
+ const data = await response.json();
7702
+ const identifications = data.identifications ?? [];
7703
+ const matches = identifications.map((id) => ({
7704
+ list: "OFAC_SDN",
7705
+ matchType: "exact_address",
7706
+ similarity: 1,
7707
+ matchedValue: address,
7708
+ entityStatus: "active",
7709
+ entityName: id.name,
7710
+ program: id.category
7711
+ }));
7712
+ return {
7713
+ providerId: this.id,
7714
+ hit: matches.length > 0,
7715
+ matches,
7716
+ listsChecked: this.lists,
7717
+ entriesSearched: 1,
7718
+ durationMs: Date.now() - start
7719
+ };
7720
+ } catch (err) {
7721
+ return this.errorResult(
7722
+ start,
7723
+ `Chainalysis API error: ${err instanceof Error ? err.message : String(err)}`
7724
+ );
7725
+ }
7726
+ }
7727
+ errorResult(start, error) {
7728
+ return {
7729
+ providerId: this.id,
7730
+ hit: false,
7731
+ matches: [],
7732
+ listsChecked: this.lists,
7733
+ entriesSearched: 0,
7734
+ durationMs: Date.now() - start,
7735
+ error
7736
+ };
7737
+ }
7738
+ };
7739
+
7740
+ // src/integrations/viem-interceptor.ts
7741
+ var ViemComplianceError = class extends Error {
7742
+ result;
7743
+ from;
7744
+ to;
7745
+ amount;
7746
+ constructor(message, result, details) {
7747
+ super(message);
7748
+ this.name = "ViemComplianceError";
7749
+ this.result = result;
7750
+ this.from = details.from;
7751
+ this.to = details.to;
7752
+ this.amount = details.amount;
7753
+ }
7754
+ };
7755
+ function withKontextCompliance(client, kontext, options) {
7756
+ const config = kontext.getConfig();
7757
+ const agentId = options?.agentId ?? config.agentId ?? "viem-agent";
7758
+ const mode = options?.mode ?? config.interceptorMode ?? "post-send";
7759
+ const sessionId = options?.sessionId;
7760
+ const metadata = options?.metadata;
7761
+ const onVerify = options?.onVerify;
7762
+ const onError = options?.onError;
7763
+ const allowedTokens = options?.tokens ? new Set(options.tokens) : config.policy?.allowedTokens ? new Set(config.policy.allowedTokens) : null;
7764
+ const allowedChains = options?.chains ? new Set(options.chains) : null;
7765
+ const allowedContracts = /* @__PURE__ */ new Set();
7766
+ for (const [address, info] of Object.entries(STABLECOIN_CONTRACTS)) {
7767
+ if (allowedTokens && !allowedTokens.has(info.token)) continue;
7768
+ if (allowedChains && !allowedChains.has(info.chain)) continue;
7769
+ allowedContracts.add(address);
7770
+ }
7771
+ const monitor = kontext.getWalletMonitor?.() ?? null;
7772
+ return client.extend((baseClient) => ({
7773
+ async sendTransaction(params) {
7774
+ const target = params.to?.toLowerCase();
7775
+ if (!target || !allowedContracts.has(target)) {
7776
+ return baseClient.sendTransaction(params);
7777
+ }
7778
+ const decoded = params.data ? decodeTransferCalldata(params.data) : null;
7779
+ if (!decoded) {
7780
+ return baseClient.sendTransaction(params);
7781
+ }
7782
+ const contractInfo = STABLECOIN_CONTRACTS[target];
7783
+ const verifyInput = buildVerifyInput(
7784
+ decoded,
7785
+ contractInfo,
7786
+ params,
7787
+ baseClient,
7788
+ agentId,
7789
+ sessionId,
7790
+ metadata
7791
+ );
7792
+ if (mode === "pre-send" || mode === "both") {
7793
+ await runPreSendScreen(kontext, verifyInput);
7794
+ }
7795
+ const txHash = await baseClient.sendTransaction(params);
7796
+ if (mode === "post-send" || mode === "both") {
7797
+ monitor?.markVerified(txHash);
7798
+ runPostSendVerify(kontext, { ...verifyInput, txHash }, txHash, onVerify, onError);
7799
+ }
7800
+ return txHash;
7801
+ },
7802
+ async writeContract(params) {
7803
+ if (!baseClient.writeContract) {
7804
+ throw new Error("writeContract not available on this client");
7805
+ }
7806
+ const target = params.address?.toLowerCase();
7807
+ if (!target || !allowedContracts.has(target)) {
7808
+ return baseClient.writeContract(params);
7809
+ }
7810
+ const fn = params.functionName;
7811
+ if (fn !== "transfer" && fn !== "transferFrom") {
7812
+ return baseClient.writeContract(params);
7813
+ }
7814
+ const decoded = decodeWriteContractArgs(fn, params.args);
7815
+ if (!decoded) {
7816
+ return baseClient.writeContract(params);
7817
+ }
7818
+ const contractInfo = STABLECOIN_CONTRACTS[target];
7819
+ const verifyInput = buildVerifyInput(
7820
+ decoded,
7821
+ contractInfo,
7822
+ params,
7823
+ baseClient,
7824
+ agentId,
7825
+ sessionId,
7826
+ metadata
7827
+ );
7828
+ if (mode === "pre-send" || mode === "both") {
7829
+ await runPreSendScreen(kontext, verifyInput);
7830
+ }
7831
+ const txHash = await baseClient.writeContract(params);
7832
+ if (mode === "post-send" || mode === "both") {
7833
+ monitor?.markVerified(txHash);
7834
+ runPostSendVerify(kontext, { ...verifyInput, txHash }, txHash, onVerify, onError);
7835
+ }
7836
+ return txHash;
7837
+ }
7838
+ }));
7839
+ }
7840
+ function buildVerifyInput(decoded, contractInfo, params, client, agentId, sessionId, metadata) {
7841
+ const chain = client.chain?.id ? CHAIN_ID_MAP[client.chain.id] ?? contractInfo.chain : contractInfo.chain;
7842
+ const from = (decoded.from ?? params.account?.address ?? client.account?.address ?? params.from ?? "").toLowerCase();
7843
+ return {
7844
+ txHash: "",
7845
+ chain,
7846
+ amount: formatTokenAmount2(decoded.amount, contractInfo.decimals),
7847
+ token: contractInfo.token,
7848
+ from,
7849
+ to: decoded.to.toLowerCase(),
7850
+ agentId,
7851
+ sessionId,
7852
+ metadata: {
7853
+ ...metadata,
7854
+ source: "viem-auto-instrumentation",
7855
+ contractAddress: params.to ?? params.address
7856
+ }
7857
+ };
7858
+ }
7859
+ function runPostSendVerify(kontext, input, txHash, onVerify, onError) {
7860
+ kontext.verify(input).then(
7861
+ (result) => {
7862
+ if (onVerify) {
7863
+ try {
7864
+ const p = onVerify(result, txHash);
7865
+ if (p && typeof p.catch === "function") {
7866
+ p.catch(() => {
7867
+ });
7868
+ }
7869
+ } catch {
7870
+ }
7871
+ }
7872
+ },
7873
+ (error) => {
7874
+ if (onError) {
7875
+ try {
7876
+ const p = onError(error, txHash);
7877
+ if (p && typeof p.catch === "function") {
7878
+ p.catch(() => {
7879
+ });
7880
+ }
7881
+ } catch {
7882
+ }
7883
+ }
7884
+ }
7885
+ );
7886
+ }
7887
+ async function runPreSendScreen(kontext, input) {
7888
+ const result = await kontext.verify({ ...input, txHash: "pre-screening" });
7889
+ if (!result.compliant) {
7890
+ throw new ViemComplianceError(
7891
+ `Transaction blocked: ${result.recommendations?.[0] ?? "compliance check failed"}`,
7892
+ result,
7893
+ { from: input.from, to: input.to, amount: input.amount }
7894
+ );
7895
+ }
7896
+ }
7897
+ function decodeTransferCalldata(data) {
7898
+ if (!data || data.length < 10) return null;
7899
+ const selector = data.slice(0, 10).toLowerCase();
7900
+ if (selector === TRANSFER_SELECTOR && data.length >= 138) {
7901
+ const to = "0x" + data.slice(34, 74);
7902
+ const amount = BigInt("0x" + data.slice(74, 138));
7903
+ return { to, amount };
7904
+ }
7905
+ if (selector === TRANSFER_FROM_SELECTOR && data.length >= 202) {
7906
+ const from = "0x" + data.slice(34, 74);
7907
+ const to = "0x" + data.slice(98, 138);
7908
+ const amount = BigInt("0x" + data.slice(138, 202));
7909
+ return { from, to, amount };
7910
+ }
7911
+ return null;
7912
+ }
7913
+ function decodeWriteContractArgs(functionName, args) {
7914
+ if (!args || !Array.isArray(args)) return null;
7915
+ if (functionName === "transfer" && args.length >= 2) {
7916
+ return { to: String(args[0]), amount: BigInt(args[1]) };
7917
+ }
7918
+ if (functionName === "transferFrom" && args.length >= 3) {
7919
+ return { from: String(args[0]), to: String(args[1]), amount: BigInt(args[2]) };
7920
+ }
7921
+ return null;
7922
+ }
7923
+ function formatTokenAmount2(amount, decimals) {
7924
+ const divisor = BigInt(10 ** decimals);
7925
+ const whole = amount / divisor;
7926
+ const fraction = amount % divisor;
7927
+ if (fraction === 0n) return whole.toString();
7928
+ const fractionStr = fraction.toString().padStart(decimals, "0").replace(/0+$/, "");
7929
+ return `${whole}.${fractionStr}`;
7930
+ }
7931
+
7932
+ export { AgentIdentityRegistry, AnomalyDetector, BehavioralFingerprinter, CHAIN_ID_MAP, CURRENCY_REQUIRED_LISTS, ChainalysisFreeAPIProvider, ChainalysisOracleProvider, ConsoleExporter, CrossSessionLinker, DigestChain, FeatureFlagManager, FileStorage, JsonFileExporter, KONTEXT_BUILDER_CODE, KYAConfidenceScorer, Kontext, KontextError, KontextErrorCode, MemoryStorage, NoopExporter, OFACAddressProvider, OFACEntityProvider, OnChainExporter, OpenSanctionsLocalProvider, OpenSanctionsProvider, PLAN_LIMITS, PaymentCompliance, PlanManager, ProvenanceManager, STABLECOIN_CONTRACTS, ScreeningAggregator, TOKEN_REQUIRED_LISTS, TrustScorer, UKOFSIProvider, UsdcCompliance, ViemComplianceError, WalletClusterer, WalletMonitor, anchorDigest, encodeERC8021Suffix, exchangeAttestation, fetchAgentCard, fetchTransactionAttribution, getAnchor, getRequiredLists, isBlockchainAddress, isCryptoTransaction, isFeatureAvailable, loadConfigFile, parseERC8021Suffix, providerSupportsQuery, requirePlan, verifyAnchor, verifyExportedChain, withKontextCompliance };
4181
7933
  //# sourceMappingURL=index.mjs.map
4182
7934
  //# sourceMappingURL=index.mjs.map