kontext-sdk 0.3.1 → 0.5.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.d.mts CHANGED
@@ -102,109 +102,6 @@ declare class JsonFileExporter implements EventExporter {
102
102
  /** Get the output directory path. */
103
103
  getOutputDir(): string;
104
104
  }
105
- /**
106
- * Generic HTTP exporter that sends batched events to any HTTP endpoint.
107
- * Events are buffered and sent in configurable batch sizes.
108
- *
109
- * @example
110
- * ```typescript
111
- * const kontext = Kontext.init({
112
- * projectId: 'my-project',
113
- * environment: 'production',
114
- * exporter: new HttpExporter({
115
- * endpoint: 'https://my-analytics.example.com/v1/events',
116
- * headers: { 'Authorization': 'Bearer my-token' },
117
- * }),
118
- * });
119
- * ```
120
- */
121
- declare class HttpExporter implements EventExporter {
122
- private readonly endpoint;
123
- private readonly headers;
124
- private readonly batchSize;
125
- private readonly timeoutMs;
126
- private buffer;
127
- constructor(options: {
128
- endpoint: string;
129
- headers?: Record<string, string>;
130
- batchSize?: number;
131
- timeoutMs?: number;
132
- });
133
- export(events: ActionLog[]): Promise<ExporterResult>;
134
- flush(): Promise<void>;
135
- shutdown(): Promise<void>;
136
- }
137
- /**
138
- * Cloud exporter for Pro and Enterprise plans.
139
- * Ships events to the Kontext Cloud API (api.getkontext.com) with automatic
140
- * batching, retry, and GENIUS Act-compliant retention.
141
- *
142
- * Events sent via this exporter are stored in Kontext's GCP infrastructure
143
- * with configurable retention policies aligned with regulatory requirements:
144
- * - 5-year default retention (BSA/AML)
145
- * - WORM-compatible immutable storage (SEC 17a-4 / CFTC 1.31)
146
- * - US-based data residency (GCP us-central1)
147
- * - AES-256 encryption at rest, TLS 1.3 in transit
148
- *
149
- * @example
150
- * ```typescript
151
- * const kontext = Kontext.init({
152
- * apiKey: 'sk_live_...',
153
- * projectId: 'my-project',
154
- * environment: 'production',
155
- * plan: 'pro',
156
- * exporter: new KontextCloudExporter({
157
- * apiKey: 'sk_live_...',
158
- * projectId: 'my-project',
159
- * }),
160
- * });
161
- * ```
162
- */
163
- declare class KontextCloudExporter implements EventExporter {
164
- private readonly apiKey;
165
- private readonly projectId;
166
- private readonly apiUrl;
167
- private readonly batchSize;
168
- private readonly timeoutMs;
169
- private readonly retryAttempts;
170
- private readonly retryDelayMs;
171
- private buffer;
172
- constructor(options: {
173
- apiKey: string;
174
- projectId: string;
175
- apiUrl?: string;
176
- batchSize?: number;
177
- timeoutMs?: number;
178
- retryAttempts?: number;
179
- retryDelayMs?: number;
180
- });
181
- export(events: ActionLog[]): Promise<ExporterResult>;
182
- flush(): Promise<void>;
183
- shutdown(): Promise<void>;
184
- }
185
- /**
186
- * Composite exporter that fans out events to multiple exporters.
187
- * Useful for sending events to both local files and cloud simultaneously.
188
- *
189
- * @example
190
- * ```typescript
191
- * const kontext = Kontext.init({
192
- * projectId: 'my-project',
193
- * environment: 'production',
194
- * exporter: new MultiExporter([
195
- * new JsonFileExporter({ outputDir: './backup' }),
196
- * new KontextCloudExporter({ apiKey: 'sk_live_...', projectId: 'my-project' }),
197
- * ]),
198
- * });
199
- * ```
200
- */
201
- declare class MultiExporter implements EventExporter {
202
- private readonly exporters;
203
- constructor(exporters: EventExporter[]);
204
- export(events: ActionLog[]): Promise<ExporterResult>;
205
- flush(): Promise<void>;
206
- shutdown(): Promise<void>;
207
- }
208
105
 
209
106
  /**
210
107
  * Interface for pluggable storage backends.
@@ -295,7 +192,7 @@ type TaskStatus = 'pending' | 'in_progress' | 'confirmed' | 'failed' | 'expired'
295
192
  /** Supported export formats */
296
193
  type ExportFormat = 'json' | 'csv';
297
194
  /** Report types */
298
- type ReportType = 'compliance' | 'transaction' | 'anomaly' | 'sar' | 'ctr';
195
+ type ReportType = 'compliance' | 'transaction' | 'anomaly';
299
196
  /** Anomaly detection rule types */
300
197
  type AnomalyRuleType = 'unusualAmount' | 'frequencySpike' | 'newDestination' | 'offHoursActivity' | 'rapidSuccession' | 'roundAmount';
301
198
  /** SDK initialization configuration */
@@ -320,6 +217,19 @@ interface KontextConfig {
320
217
  logLevel?: 'debug' | 'info' | 'warn' | 'error';
321
218
  /** Pluggable storage adapter for persistence (default: in-memory) */
322
219
  storage?: StorageAdapter;
220
+ /**
221
+ * Anomaly detection rules to enable at init time.
222
+ * When provided, anomaly detection is automatically enabled and every
223
+ * verify() call includes anomaly results in its response.
224
+ *
225
+ * Free-tier rules: `unusualAmount`, `frequencySpike`
226
+ * Pay as you go rules: `newDestination`, `offHoursActivity`, `rapidSuccession`, `roundAmount`
227
+ */
228
+ anomalyRules?: AnomalyRuleType[];
229
+ /**
230
+ * Thresholds for anomaly detection. Only used when `anomalyRules` is set.
231
+ */
232
+ anomalyThresholds?: AnomalyThresholds;
323
233
  /**
324
234
  * Pluggable event exporter for shipping events to external systems.
325
235
  * Follows the OpenTelemetry exporter pattern.
@@ -328,9 +238,6 @@ interface KontextConfig {
328
238
  * - `NoopExporter` (default) — discards events, current SDK behavior
329
239
  * - `ConsoleExporter` — prints events to stdout
330
240
  * - `JsonFileExporter` — writes JSONL files to disk
331
- * - `HttpExporter` — sends batched events to any HTTP endpoint
332
- * - `KontextCloudExporter` — ships to Kontext Cloud (Pro/Enterprise)
333
- * - `MultiExporter` — fans out to multiple exporters
334
241
  *
335
242
  * @example
336
243
  * ```typescript
@@ -389,11 +296,34 @@ interface KontextConfig {
389
296
  */
390
297
  featureFlags?: FeatureFlagConfig;
391
298
  /**
392
- * Approval policies for human-in-the-loop review. When provided, the SDK
393
- * initializes an `ApprovalManager` that evaluates actions against these
394
- * policies and blocks execution until a human decides.
299
+ * User / tenant identifier for storage isolation.
300
+ * Required when using FirestoreStorageAdapter. Logs for each userId
301
+ * are stored under separate Firestore paths:
302
+ * users/{userId}/projects/{projectId}/...
303
+ *
304
+ * Use a stable, opaque identifier: your auth system's user ID,
305
+ * a Stripe customer ID, or a hash of the API key.
306
+ */
307
+ userId?: string;
308
+ /**
309
+ * When set, verify() auto-creates a pending task if the transaction
310
+ * amount exceeds this threshold (string, to preserve decimal precision).
311
+ * The task is returned in `result.task` and `result.requiresApproval`
312
+ * is set to `true`. Your agent should wait for confirmTask() before
313
+ * executing the transfer.
314
+ *
315
+ * Free tier feature — works with createTask() / confirmTask().
316
+ *
317
+ * @example
318
+ * ```typescript
319
+ * const ctx = Kontext.init({
320
+ * projectId: 'my-agent',
321
+ * environment: 'production',
322
+ * approvalThreshold: '3000', // auto-task above $3K
323
+ * });
324
+ * ```
395
325
  */
396
- approvalPolicies?: ApprovalPolicy[];
326
+ approvalThreshold?: string;
397
327
  }
398
328
  /**
399
329
  * Interface for metadata validation. Compatible with Zod schemas and any
@@ -413,6 +343,8 @@ interface ActionLog {
413
343
  projectId: string;
414
344
  /** ID of the agent performing the action */
415
345
  agentId: string;
346
+ /** Session ID grouping all steps in one agent run */
347
+ sessionId?: string;
416
348
  /** Correlation ID for tracing related actions */
417
349
  correlationId: string;
418
350
  /** Type of action */
@@ -434,6 +366,8 @@ interface LogActionInput {
434
366
  description: string;
435
367
  /** ID of the agent performing the action */
436
368
  agentId: string;
369
+ /** Optional session ID grouping all steps in a single agent run */
370
+ sessionId?: string;
437
371
  /** Optional correlation ID (auto-generated if not provided) */
438
372
  correlationId?: string;
439
373
  /** Arbitrary metadata */
@@ -455,6 +389,8 @@ interface LogTransactionInput {
455
389
  to: string;
456
390
  /** ID of the agent initiating the transaction */
457
391
  agentId: string;
392
+ /** Optional session ID grouping all steps in a single agent run */
393
+ sessionId?: string;
458
394
  /** Optional correlation ID */
459
395
  correlationId?: string;
460
396
  /** Additional transaction metadata */
@@ -609,87 +545,47 @@ interface ExportResult {
609
545
  /** Terminal digest of the chain at time of export */
610
546
  terminalDigest?: string;
611
547
  }
612
- /** Subject information for SAR/CTR reports */
613
- interface ReportSubject {
614
- /** Subject name or identifier */
615
- name: string;
616
- /** Agent ID (if applicable) */
617
- agentId?: string;
618
- /** Wallet addresses associated with the subject */
619
- addresses: string[];
620
- /** Additional identifying information */
621
- identifiers?: Record<string, string>;
622
- }
623
- /** Suspicious Activity Report template */
624
- interface SARReport {
625
- /** Report ID */
548
+ /** Detected anomaly event */
549
+ interface AnomalyEvent {
550
+ /** Unique anomaly ID */
626
551
  id: string;
627
- /** Report type discriminator */
628
- type: 'sar';
629
- /** Generation timestamp */
630
- generatedAt: string;
631
- /** Reporting period */
632
- period: DateRange;
633
- /** Project ID */
634
- projectId: string;
635
- /** Filing institution information */
636
- filingInstitution: string;
637
- /** Subject(s) of the report */
638
- subjects: ReportSubject[];
639
- /** Narrative summary of suspicious activity */
640
- narrative: string;
641
- /** Suspicious activity categories */
642
- activityCategories: string[];
643
- /** Total amount involved */
644
- totalAmount: string;
645
- /** Currency/token */
646
- currency: string;
647
- /** Transactions flagged as suspicious */
648
- suspiciousTransactions: TransactionRecord[];
649
- /** Related anomalies */
650
- anomalies: AnomalyEvent[];
651
- /** Supporting action logs */
652
- supportingActions: ActionLog[];
653
- /** Whether this is a continuing activity report */
654
- isContinuingActivity: boolean;
655
- /** Prior report ID if continuing */
656
- priorReportId: string | null;
657
- /** Status of the report */
658
- status: 'draft' | 'review' | 'filed';
552
+ /** Anomaly type/rule that triggered */
553
+ type: AnomalyRuleType;
554
+ /** Severity level */
555
+ severity: AnomalySeverity;
556
+ /** Human-readable description */
557
+ description: string;
558
+ /** ID of the agent involved */
559
+ agentId: string;
560
+ /** Related action log ID */
561
+ actionId: string;
562
+ /** Detection timestamp */
563
+ detectedAt: string;
564
+ /** Related data */
565
+ data: Record<string, unknown>;
566
+ /** Whether the anomaly has been reviewed */
567
+ reviewed: boolean;
659
568
  }
660
- /** Currency Transaction Report template */
661
- interface CTRReport {
662
- /** Report ID */
663
- id: string;
664
- /** Report type discriminator */
665
- type: 'ctr';
666
- /** Generation timestamp */
667
- generatedAt: string;
668
- /** Reporting period */
669
- period: DateRange;
670
- /** Project ID */
671
- projectId: string;
672
- /** Filing institution information */
673
- filingInstitution: string;
674
- /** Person/entity conducting the transactions */
675
- conductors: ReportSubject[];
676
- /** Transactions included in the report */
677
- transactions: TransactionRecord[];
678
- /** Total cash-in amount */
679
- totalCashIn: string;
680
- /** Total cash-out amount */
681
- totalCashOut: string;
682
- /** Currency/token */
683
- currency: string;
684
- /** Whether multiple transactions are aggregated */
685
- isAggregated: boolean;
686
- /** Chains involved */
687
- chainsInvolved: Chain[];
688
- /** Supporting action logs */
689
- supportingActions: ActionLog[];
690
- /** Status of the report */
691
- status: 'draft' | 'review' | 'filed';
569
+ /** Anomaly detection configuration */
570
+ interface AnomalyDetectionConfig {
571
+ /** Detection rules to enable */
572
+ rules: AnomalyRuleType[];
573
+ /** Thresholds for detection */
574
+ thresholds?: AnomalyThresholds;
575
+ }
576
+ /** Configurable anomaly thresholds */
577
+ interface AnomalyThresholds {
578
+ /** Maximum transaction amount before flagging */
579
+ maxAmount?: string;
580
+ /** Maximum transactions per hour */
581
+ maxFrequency?: number;
582
+ /** Hours considered "off-hours" (24h format, e.g., [22, 23, 0, 1, 2, 3, 4, 5]) */
583
+ offHours?: number[];
584
+ /** Minimum seconds between transactions before "rapid succession" flag */
585
+ minIntervalSeconds?: number;
692
586
  }
587
+ /** Anomaly event callback */
588
+ type AnomalyCallback = (anomaly: AnomalyEvent) => void;
693
589
  /** Trust score result for an agent */
694
590
  interface TrustScore {
695
591
  /** Agent ID */
@@ -740,99 +636,6 @@ interface RiskFactor {
740
636
  /** Human-readable description */
741
637
  description: string;
742
638
  }
743
- /** Anomaly detection configuration */
744
- interface AnomalyDetectionConfig {
745
- /** Detection rules to enable */
746
- rules: AnomalyRuleType[];
747
- /** Thresholds for detection */
748
- thresholds?: AnomalyThresholds;
749
- }
750
- /** Configurable anomaly thresholds */
751
- interface AnomalyThresholds {
752
- /** Maximum transaction amount before flagging */
753
- maxAmount?: string;
754
- /** Maximum transactions per hour */
755
- maxFrequency?: number;
756
- /** Hours considered "off-hours" (24h format, e.g., [22, 23, 0, 1, 2, 3, 4, 5]) */
757
- offHours?: number[];
758
- /** Minimum seconds between transactions before "rapid succession" flag */
759
- minIntervalSeconds?: number;
760
- }
761
- /** Detected anomaly event */
762
- interface AnomalyEvent {
763
- /** Unique anomaly ID */
764
- id: string;
765
- /** Anomaly type/rule that triggered */
766
- type: AnomalyRuleType;
767
- /** Severity level */
768
- severity: AnomalySeverity;
769
- /** Human-readable description */
770
- description: string;
771
- /** ID of the agent involved */
772
- agentId: string;
773
- /** Related action log ID */
774
- actionId: string;
775
- /** Detection timestamp */
776
- detectedAt: string;
777
- /** Related data */
778
- data: Record<string, unknown>;
779
- /** Whether the anomaly has been reviewed */
780
- reviewed: boolean;
781
- }
782
- /** Anomaly event callback */
783
- type AnomalyCallback = (anomaly: AnomalyEvent) => void;
784
- /** USDC compliance check result */
785
- interface UsdcComplianceCheck {
786
- /** Whether the transaction is compliant */
787
- compliant: boolean;
788
- /** List of compliance checks performed */
789
- checks: ComplianceCheckResult[];
790
- /** Overall risk level */
791
- riskLevel: 'low' | 'medium' | 'high' | 'critical';
792
- /** Recommendations */
793
- recommendations: string[];
794
- }
795
- /** Individual compliance check result */
796
- interface ComplianceCheckResult {
797
- /** Check name */
798
- name: string;
799
- /** Whether the check passed */
800
- passed: boolean;
801
- /** Human-readable description */
802
- description: string;
803
- /** Severity if failed */
804
- severity: AnomalySeverity;
805
- }
806
- /** Input for logging agent reasoning */
807
- interface LogReasoningInput {
808
- /** ID of the agent making the decision */
809
- agentId: string;
810
- /** What action was taken or is being considered */
811
- action: string;
812
- /** The agent's reasoning/justification */
813
- reasoning: string;
814
- /** Optional confidence score (0-1) */
815
- confidence?: number;
816
- /** Optional additional context */
817
- context?: Record<string, unknown>;
818
- }
819
- /** A reasoning entry stored in the action log */
820
- interface ReasoningEntry {
821
- /** Unique reasoning entry identifier */
822
- id: string;
823
- /** Timestamp of the reasoning entry */
824
- timestamp: string;
825
- /** ID of the agent making the decision */
826
- agentId: string;
827
- /** What action was taken or is being considered */
828
- action: string;
829
- /** The agent's reasoning/justification */
830
- reasoning: string;
831
- /** Confidence score (0-1), defaults to 1.0 */
832
- confidence: number;
833
- /** Additional context */
834
- context: Record<string, unknown>;
835
- }
836
639
  /** Input for generating a compliance certificate */
837
640
  interface GenerateComplianceCertificateInput {
838
641
  /** ID of the agent to generate the certificate for */
@@ -880,6 +683,28 @@ interface ComplianceCertificate {
880
683
  /** SHA-256 hash of the certificate content for integrity verification */
881
684
  contentHash: string;
882
685
  }
686
+ /** USDC compliance check result */
687
+ interface UsdcComplianceCheck {
688
+ /** Whether the transaction is compliant */
689
+ compliant: boolean;
690
+ /** List of compliance checks performed */
691
+ checks: ComplianceCheckResult[];
692
+ /** Overall risk level */
693
+ riskLevel: 'low' | 'medium' | 'high' | 'critical';
694
+ /** Recommendations */
695
+ recommendations: string[];
696
+ }
697
+ /** Individual compliance check result */
698
+ interface ComplianceCheckResult {
699
+ /** Check name */
700
+ name: string;
701
+ /** Whether the check passed */
702
+ passed: boolean;
703
+ /** Human-readable description */
704
+ description: string;
705
+ /** Severity if failed */
706
+ severity: AnomalySeverity;
707
+ }
883
708
  /** Scope of a feature flag */
884
709
  type FlagScope = 'sdk' | 'server' | 'website' | 'all';
885
710
  /** Plan-based targeting for a single environment */
@@ -921,79 +746,105 @@ interface FeatureFlagConfig {
921
746
  /** Scope filter — only load flags matching this scope (or 'all') */
922
747
  scope?: FlagScope;
923
748
  }
924
- /** Types of approval policies that can trigger human review */
925
- type ApprovalPolicyType = 'amount-threshold' | 'low-trust-score' | 'anomaly-detected' | 'new-destination' | 'manual';
926
- /** Status of an approval request */
927
- type ApprovalStatus = 'pending' | 'approved' | 'rejected' | 'expired';
928
- /** Configurable policy that determines when human approval is required */
929
- interface ApprovalPolicy {
930
- type: ApprovalPolicyType;
931
- enabled: boolean;
932
- params: Record<string, unknown>;
933
- requiredEvidence?: string[];
934
- }
935
- /** A pending or resolved approval request */
936
- interface ApprovalRequest {
937
- id: string;
938
- actionId: string;
939
- agentId: string;
940
- status: ApprovalStatus;
941
- triggeredPolicies: ApprovalPolicyType[];
942
- riskAssessment: {
943
- score: number;
944
- factors: string[];
945
- };
946
- requiredEvidence: string[];
947
- decision: ApprovalDecision | null;
948
- createdAt: string;
949
- expiresAt: string;
950
- metadata: Record<string, unknown>;
951
- }
952
- /** Decision made by a human reviewer */
953
- interface ApprovalDecision {
954
- decision: 'approve' | 'reject';
955
- decidedBy: string;
956
- reason: string;
957
- evidence?: Record<string, unknown>;
958
- conditions?: string[];
959
- decidedAt: string;
749
+ /** Input for the verify() convenience method */
750
+ interface VerifyInput extends LogTransactionInput {
751
+ /** Agent reasoning for this transaction (logged into digest chain if provided) */
752
+ reasoning?: string;
753
+ /** Confidence level 0–1 for the reasoning */
754
+ confidence?: number;
755
+ /** Additional reasoning context */
756
+ context?: Record<string, unknown>;
960
757
  }
961
- /** Result of evaluating an action against approval policies */
962
- interface ApprovalEvaluation {
963
- required: boolean;
964
- requestId?: string;
965
- triggeredPolicies: ApprovalPolicyType[];
966
- riskAssessment: {
967
- score: number;
968
- factors: string[];
758
+ /** Result of the verify() convenience method */
759
+ interface VerifyResult {
760
+ /** Whether the transaction passed all compliance checks */
761
+ compliant: boolean;
762
+ /** Individual compliance check results */
763
+ checks: ComplianceCheckResult[];
764
+ /** Overall risk level */
765
+ riskLevel: 'low' | 'medium' | 'high' | 'critical';
766
+ /** Recommended actions */
767
+ recommendations: string[];
768
+ /** The logged transaction record */
769
+ transaction: TransactionRecord;
770
+ /** Agent trust score (auto-computed when agentId is present) */
771
+ trustScore: TrustScore;
772
+ /** Anomalies detected for this transaction (empty if anomaly detection not configured) */
773
+ anomalies: AnomalyEvent[];
774
+ /** Digest chain proof at time of verification */
775
+ digestProof: {
776
+ terminalDigest: string;
777
+ chainLength: number;
778
+ valid: boolean;
969
779
  };
780
+ /** Reasoning entry ID (present when reasoning was provided in input) */
781
+ reasoningId?: string;
782
+ /** True when the transaction amount exceeds the approvalThreshold */
783
+ requiresApproval?: boolean;
784
+ /** The pending approval task (present when requiresApproval is true) */
785
+ task?: Task;
970
786
  }
971
- /** Input for evaluating whether an action requires approval */
972
- interface EvaluateApprovalInput {
973
- actionId: string;
787
+ /**
788
+ * Input for logging an agent's reasoning/decision step.
789
+ * Supports full trace reconstruction via sessionId + step sequencing.
790
+ */
791
+ interface LogReasoningInput {
792
+ /** ID of the agent performing the reasoning */
974
793
  agentId: string;
975
- amount?: string;
976
- destination?: string;
977
- trustScore?: number;
978
- anomalies?: Array<{
979
- type: string;
980
- severity: string;
981
- }>;
982
- metadata?: Record<string, unknown>;
983
- }
984
- /** Input for submitting a human decision on an approval request */
985
- interface SubmitDecisionInput {
986
- requestId: string;
987
- decision: 'approve' | 'reject';
988
- decidedBy: string;
989
- reason: string;
990
- evidence?: Record<string, unknown>;
991
- conditions?: string[];
992
- }
993
- /** Error codes for Kontext SDK */
994
- declare enum KontextErrorCode {
995
- INITIALIZATION_ERROR = "INITIALIZATION_ERROR",
996
- VALIDATION_ERROR = "VALIDATION_ERROR",
794
+ /**
795
+ * Session ID grouping all steps in one agent run.
796
+ * Use Kontext.generateSessionId() or your framework's run ID
797
+ * (LangGraph thread_id, Vercel AI id, OpenAI run_id).
798
+ */
799
+ sessionId?: string;
800
+ /** Step number within the session (for ordering) */
801
+ step?: number;
802
+ /** Parent step number (links this step to a prior decision) */
803
+ parentStep?: number;
804
+ /** The action or decision being made (e.g., 'evaluate-transfer') */
805
+ action: string;
806
+ /** Natural language explanation of the reasoning */
807
+ reasoning: string;
808
+ /** Confidence level 0–1 */
809
+ confidence?: number;
810
+ /** Tool or method called as a result of this reasoning */
811
+ toolCall?: string;
812
+ /** Result returned by the tool call */
813
+ toolResult?: unknown;
814
+ /** Additional context */
815
+ context?: Record<string, unknown>;
816
+ }
817
+ /** A stored reasoning/decision entry in the audit trail */
818
+ interface ReasoningEntry {
819
+ /** Unique entry ID */
820
+ id: string;
821
+ /** Timestamp */
822
+ timestamp: string;
823
+ /** Agent ID */
824
+ agentId: string;
825
+ /** Session ID */
826
+ sessionId?: string;
827
+ /** Step number */
828
+ step?: number;
829
+ /** Parent step */
830
+ parentStep?: number;
831
+ /** Action name */
832
+ action: string;
833
+ /** Reasoning text */
834
+ reasoning: string;
835
+ /** Confidence 0–1 */
836
+ confidence: number;
837
+ /** Tool called */
838
+ toolCall?: string;
839
+ /** Tool result */
840
+ toolResult?: unknown;
841
+ /** Context */
842
+ context: Record<string, unknown>;
843
+ }
844
+ /** Error codes for Kontext SDK */
845
+ declare enum KontextErrorCode {
846
+ INITIALIZATION_ERROR = "INITIALIZATION_ERROR",
847
+ VALIDATION_ERROR = "VALIDATION_ERROR",
997
848
  TASK_NOT_FOUND = "TASK_NOT_FOUND",
998
849
  TASK_ALREADY_CONFIRMED = "TASK_ALREADY_CONFIRMED",
999
850
  TASK_EXPIRED = "TASK_EXPIRED",
@@ -1417,13 +1268,12 @@ declare class Kontext {
1417
1268
  private readonly logger;
1418
1269
  private readonly taskManager;
1419
1270
  private readonly auditExporter;
1420
- private readonly trustScorer;
1421
- private readonly anomalyDetector;
1422
1271
  private readonly mode;
1423
1272
  private readonly planManager;
1424
1273
  private readonly exporter;
1425
1274
  private readonly featureFlagManager;
1426
- private approvalManager;
1275
+ private readonly trustScorer;
1276
+ private readonly anomalyDetector;
1427
1277
  private constructor();
1428
1278
  /**
1429
1279
  * Initialize the Kontext SDK.
@@ -1556,58 +1406,6 @@ declare class Kontext {
1556
1406
  * @returns Compliance report with summary and detailed records
1557
1407
  */
1558
1408
  generateReport(options: ReportOptions): Promise<ComplianceReport>;
1559
- /**
1560
- * Generate a Suspicious Activity Report (SAR) template.
1561
- *
1562
- * This produces a structured SAR template populated with data from the SDK.
1563
- * It is a template/structure, not an actual regulatory filing.
1564
- *
1565
- * @param options - Report configuration
1566
- * @returns SAR report template
1567
- */
1568
- generateSARReport(options: ReportOptions): Promise<SARReport>;
1569
- /**
1570
- * Generate a Currency Transaction Report (CTR) template.
1571
- *
1572
- * This produces a structured CTR template for transactions that meet or
1573
- * exceed reporting thresholds. It is a template/structure, not an actual
1574
- * regulatory filing.
1575
- *
1576
- * @param options - Report configuration
1577
- * @returns CTR report template
1578
- */
1579
- generateCTRReport(options: ReportOptions): Promise<CTRReport>;
1580
- /**
1581
- * Get the trust score for an agent.
1582
- *
1583
- * @param agentId - Agent identifier
1584
- * @returns Trust score with factor breakdown
1585
- */
1586
- getTrustScore(agentId: string): Promise<TrustScore>;
1587
- /**
1588
- * Evaluate the risk of a specific transaction.
1589
- *
1590
- * @param tx - Transaction to evaluate
1591
- * @returns Transaction evaluation with risk score and recommendation
1592
- */
1593
- evaluateTransaction(tx: LogTransactionInput): Promise<TransactionEvaluation>;
1594
- /**
1595
- * Enable anomaly detection with the specified rules and thresholds.
1596
- *
1597
- * @param config - Detection configuration
1598
- */
1599
- enableAnomalyDetection(config: AnomalyDetectionConfig): void;
1600
- /**
1601
- * Disable anomaly detection.
1602
- */
1603
- disableAnomalyDetection(): void;
1604
- /**
1605
- * Register a callback for anomaly events.
1606
- *
1607
- * @param callback - Function to call when an anomaly is detected
1608
- * @returns Unsubscribe function
1609
- */
1610
- onAnomaly(callback: AnomalyCallback): () => void;
1611
1409
  /**
1612
1410
  * Get the terminal digest — the latest SHA-256 hash in the rolling digest chain.
1613
1411
  * Embed this in outgoing messages as tamper-evident proof of the entire action history.
@@ -1640,6 +1438,65 @@ declare class Kontext {
1640
1438
  * @returns A copy of the action log array
1641
1439
  */
1642
1440
  getActions(): ActionLog[];
1441
+ /**
1442
+ * Generate a unique session ID for a single agent run.
1443
+ * Pass this as `sessionId` to logReasoning(), log(), logTransaction(),
1444
+ * and verify() calls within the same run to group them in the audit trail.
1445
+ *
1446
+ * Compatible with framework run IDs: pass LangGraph thread_id,
1447
+ * Vercel AI id, or OpenAI run_id directly instead if you prefer.
1448
+ *
1449
+ * @returns A short unique session identifier
1450
+ */
1451
+ static generateSessionId(): string;
1452
+ /**
1453
+ * Log an agent's reasoning step into the tamper-evident digest chain.
1454
+ *
1455
+ * Each entry records why the agent took an action, optionally linked
1456
+ * to a tool call. All entries for a sessionId can be replayed in
1457
+ * order via step numbering to reconstruct the full decision trace.
1458
+ *
1459
+ * @param input - Reasoning details including agentId, action, reasoning text
1460
+ * @returns The created reasoning entry
1461
+ *
1462
+ * @example
1463
+ * ```typescript
1464
+ * const sessionId = Kontext.generateSessionId();
1465
+ *
1466
+ * await ctx.logReasoning({
1467
+ * agentId: 'payment-agent-v1',
1468
+ * sessionId,
1469
+ * step: 1,
1470
+ * action: 'evaluate-transfer',
1471
+ * reasoning: 'User requested $5K USDC to 0xabc. Running compliance check first.',
1472
+ * confidence: 0.95,
1473
+ * toolCall: 'verify',
1474
+ * });
1475
+ *
1476
+ * const result = await ctx.verify({ ..., sessionId });
1477
+ *
1478
+ * await ctx.logReasoning({
1479
+ * agentId: 'payment-agent-v1',
1480
+ * sessionId,
1481
+ * step: 2,
1482
+ * parentStep: 1,
1483
+ * action: 'compliance-passed',
1484
+ * reasoning: 'verify() returned compliant=true, riskLevel=low. Proceeding.',
1485
+ * confidence: 0.99,
1486
+ * context: { riskLevel: result.riskLevel },
1487
+ * });
1488
+ * ```
1489
+ */
1490
+ logReasoning(input: LogReasoningInput): Promise<ReasoningEntry>;
1491
+ /**
1492
+ * Get all reasoning entries for a specific agent, optionally filtered
1493
+ * by session ID to retrieve a single run's decision trace.
1494
+ *
1495
+ * @param agentId - Agent identifier
1496
+ * @param sessionId - Optional: filter to a single run
1497
+ * @returns Array of reasoning entries in chronological order
1498
+ */
1499
+ getReasoningEntries(agentId: string, sessionId?: string): ReasoningEntry[];
1643
1500
  /**
1644
1501
  * Run USDC-specific compliance checks on a transaction.
1645
1502
  *
@@ -1648,47 +1505,99 @@ declare class Kontext {
1648
1505
  */
1649
1506
  checkUsdcCompliance(tx: LogTransactionInput): UsdcComplianceCheck;
1650
1507
  /**
1651
- * Log an agent's reasoning/justification for an action.
1652
- * The reasoning entry is recorded into the digest chain as a tamper-evident
1653
- * part of the audit trail (type: 'reasoning').
1508
+ * Verify a transaction: compliance check, transaction log, trust score,
1509
+ * anomaly detection, reasoning, and digest proof all in one call.
1654
1510
  *
1655
- * @param input - Reasoning details
1656
- * @returns The created reasoning entry
1511
+ * @param input - Transaction details with optional reasoning
1512
+ * @returns Full verification result including compliance, trust, anomalies, and digest proof
1657
1513
  *
1658
1514
  * @example
1659
1515
  * ```typescript
1660
- * const entry = await kontext.logReasoning({
1661
- * agentId: 'payment-agent-1',
1662
- * action: 'approve_transfer',
1663
- * reasoning: 'Recipient is a verified vendor with 50+ prior transactions',
1516
+ * const result = await ctx.verify({
1517
+ * txHash: '0xabc...', chain: 'base', amount: '5000', token: 'USDC',
1518
+ * from: '0xsender', to: '0xrecipient', agentId: 'agent-v1',
1519
+ * reasoning: 'Transfer within daily limit. Recipient in allowlist.',
1664
1520
  * confidence: 0.95,
1665
- * context: { recipientId: 'vendor-42' },
1666
1521
  * });
1522
+ *
1523
+ * // result.compliant — boolean
1524
+ * // result.trustScore — { score: 87, level: 'high', factors: [...] }
1525
+ * // result.anomalies — any flags triggered
1526
+ * // result.digestProof — { terminalDigest, chainLength, valid }
1527
+ * // result.reasoningId — ID of the reasoning entry (if reasoning provided)
1667
1528
  * ```
1668
1529
  */
1669
- logReasoning(input: LogReasoningInput): Promise<ReasoningEntry>;
1530
+ verify(input: VerifyInput): Promise<VerifyResult>;
1670
1531
  /**
1671
- * Get all reasoning entries for a specific agent.
1532
+ * Get the trust score for an agent based on historical behavioral signals.
1533
+ *
1534
+ * Computes a 0–100 score across 5 factors: history depth, task completion
1535
+ * rate, anomaly frequency, transaction consistency, and compliance adherence.
1672
1536
  *
1673
1537
  * @param agentId - Agent identifier
1674
- * @returns Array of reasoning entries
1538
+ * @returns Trust score with factor breakdown and level ('untrusted'|'low'|'medium'|'high'|'verified')
1539
+ */
1540
+ getTrustScore(agentId: string): Promise<TrustScore>;
1541
+ /**
1542
+ * Evaluate the risk of a specific transaction before or after executing it.
1543
+ *
1544
+ * @param tx - Transaction to evaluate
1545
+ * @returns Risk evaluation with score, factors, and recommendation (approve/review/block)
1546
+ */
1547
+ evaluateTransaction(tx: LogTransactionInput): Promise<TransactionEvaluation>;
1548
+ /**
1549
+ * Enable anomaly detection with the specified rules and thresholds.
1550
+ *
1551
+ * Free-tier rules: `unusualAmount`, `frequencySpike`
1552
+ * Pay as you go rules: `newDestination`, `offHoursActivity`, `rapidSuccession`, `roundAmount`
1553
+ *
1554
+ * @param config - Detection configuration with rules and optional thresholds
1555
+ *
1556
+ * @example
1557
+ * ```typescript
1558
+ * ctx.enableAnomalyDetection({
1559
+ * rules: ['unusualAmount', 'frequencySpike'],
1560
+ * thresholds: { maxAmount: '10000', maxFrequency: 30 },
1561
+ * });
1562
+ * ctx.onAnomaly((event) => {
1563
+ * console.log(`Anomaly: ${event.type} [${event.severity}]`);
1564
+ * });
1565
+ * ```
1566
+ */
1567
+ enableAnomalyDetection(config: AnomalyDetectionConfig): void;
1568
+ /**
1569
+ * Disable anomaly detection.
1570
+ */
1571
+ disableAnomalyDetection(): void;
1572
+ /**
1573
+ * Register a callback for anomaly events.
1574
+ *
1575
+ * @param callback - Function to call when an anomaly is detected
1576
+ * @returns Unsubscribe function
1675
1577
  */
1676
- getReasoningEntries(agentId: string): ReasoningEntry[];
1578
+ onAnomaly(callback: AnomalyCallback): () => void;
1677
1579
  /**
1678
- * Generate a compliance certificate that summarizes agent actions and
1679
- * verifies the terminal digest.
1580
+ * Generate a compliance certificate that summarizes an agent's actions
1581
+ * and cryptographically verifies the digest chain integrity.
1680
1582
  *
1681
- * @param input - Certificate generation options
1682
- * @returns A compliance certificate with digest chain verification
1583
+ * The certificate includes: action/transaction/reasoning counts, digest chain
1584
+ * verification status (Patent US 12,463,819 B1), the agent's current trust
1585
+ * score, and an overall compliance status. A SHA-256 content hash of the
1586
+ * certificate itself is included for tamper-evidence.
1587
+ *
1588
+ * @param input - Certificate generation options (agentId, optional timeRange, includeReasoning)
1589
+ * @returns Compliance certificate with digest chain proof and trust score
1683
1590
  *
1684
1591
  * @example
1685
1592
  * ```typescript
1686
- * const cert = await kontext.generateComplianceCertificate({
1687
- * agentId: 'payment-agent-1',
1593
+ * const cert = await ctx.generateComplianceCertificate({
1594
+ * agentId: 'payment-agent-v1',
1688
1595
  * includeReasoning: true,
1689
1596
  * });
1690
- * console.log(cert.complianceStatus); // 'compliant'
1691
- * console.log(cert.digestChain.verified); // true
1597
+ * console.log(cert.complianceStatus); // 'compliant'
1598
+ * console.log(cert.digestChain.verified); // true
1599
+ * console.log(cert.trustScore); // 87
1600
+ * console.log(cert.contentHash); // sha256 of certificate
1692
1601
  * ```
1693
1602
  */
1694
1603
  generateComplianceCertificate(input: GenerateComplianceCertificateInput): Promise<ComplianceCertificate>;
@@ -1751,142 +1660,155 @@ declare class Kontext {
1751
1660
  */
1752
1661
  getFeatureFlagManager(): FeatureFlagManager | null;
1753
1662
  /**
1754
- * Set or replace approval policies. Creates a new ApprovalManager.
1755
- *
1756
- * @param policies - Approval policy configurations
1663
+ * Gracefully shut down the SDK, flushing any pending data.
1757
1664
  */
1758
- setApprovalPolicies(policies: ApprovalPolicy[]): void;
1665
+ destroy(): Promise<void>;
1666
+ }
1667
+
1668
+ interface FirestoreStorageConfig {
1669
+ /** GCP project ID — use "Kontext" for the Kontext production project */
1670
+ gcpProjectId: string;
1759
1671
  /**
1760
- * Evaluate an action against the configured approval policies.
1761
- *
1762
- * @param input - Action details to evaluate
1763
- * @returns Evaluation result indicating whether approval is required
1764
- * @throws KontextError if no approval policies are configured
1672
+ * The user/tenant ID that owns these logs. Required for data isolation.
1673
+ * Use a stable identifier: Stripe customer ID, your auth system's user ID,
1674
+ * or a deterministic hash of the API key.
1765
1675
  */
1766
- evaluateApproval(input: EvaluateApprovalInput): ApprovalEvaluation;
1676
+ userId: string;
1767
1677
  /**
1768
- * Submit a human decision on a pending approval request.
1769
- *
1770
- * @param input - Decision details
1771
- * @returns The updated ApprovalRequest
1772
- * @throws KontextError if no approval policies are configured
1678
+ * OAuth2 access token for the Firestore REST API.
1679
+ * On GCP (Cloud Run, GCE, GKE): omit — the adapter will fetch a token
1680
+ * from the GCP metadata server automatically.
1681
+ * For local dev or other environments: pass a token from Application Default
1682
+ * Credentials (`gcloud auth print-access-token`).
1773
1683
  */
1774
- submitApprovalDecision(input: SubmitDecisionInput): ApprovalRequest;
1684
+ accessToken?: string;
1775
1685
  /**
1776
- * Get an approval request by ID.
1777
- *
1778
- * @param requestId - The approval request identifier
1779
- * @returns The approval request, or undefined if not found
1686
+ * Firestore database ID. Defaults to '(default)'.
1687
+ * Change only if you created a named database in the GCP console.
1780
1688
  */
1781
- getApprovalRequest(requestId: string): ApprovalRequest | undefined;
1689
+ databaseId?: string;
1782
1690
  /**
1783
- * Get all pending approval requests.
1784
- *
1785
- * @returns Array of pending approval requests
1691
+ * Whether to write each record as an individual Firestore document
1692
+ * in addition to the bulk flush writes. Enables real-time querying
1693
+ * per-action, per-session, per-agent.
1694
+ * @default true
1786
1695
  */
1787
- getPendingApprovals(): ApprovalRequest[];
1696
+ writeDocumentsIndividually?: boolean;
1788
1697
  /**
1789
- * Gracefully shut down the SDK, flushing any pending data.
1698
+ * Custom Firestore REST base URL. Override for testing or emulator use.
1699
+ * @default 'https://firestore.googleapis.com'
1790
1700
  */
1791
- destroy(): Promise<void>;
1701
+ firestoreBaseUrl?: string;
1792
1702
  }
1793
-
1794
1703
  /**
1795
- * ApprovalManager evaluates proposed actions against configurable policies
1796
- * and blocks execution until a human reviewer approves or rejects.
1704
+ * Persistent, hierarchical Firestore storage adapter for Kontext audit logs.
1705
+ *
1706
+ * Stores compliance logs by user → project → agent → session, enabling
1707
+ * regulatory-grade queries: "show me all transactions agent X made in
1708
+ * session Y" or "export all logs for user Z".
1797
1709
  *
1798
- * Policies:
1799
- * - **amount-threshold** — triggers when amount exceeds a configured threshold
1800
- * - **low-trust-score** — triggers when the agent's trust score is below minimum
1801
- * - **anomaly-detected** — triggers when anomalies of sufficient severity are present
1802
- * - **new-destination** — triggers when the destination address has not been seen before
1803
- * - **manual** — always triggers, requiring explicit human approval
1710
+ * Works as a drop-in replacement for FileStorage:
1804
1711
  *
1805
1712
  * @example
1806
1713
  * ```typescript
1807
- * const manager = new ApprovalManager([
1808
- * { type: 'amount-threshold', enabled: true, params: { threshold: '10000' } },
1809
- * { type: 'manual', enabled: false, params: {} },
1810
- * ]);
1714
+ * import { Kontext, FirestoreStorageAdapter } from 'kontext-sdk';
1811
1715
  *
1812
- * const evaluation = manager.evaluate({
1813
- * actionId: 'action-1',
1814
- * agentId: 'agent-1',
1815
- * amount: '25000',
1716
+ * const ctx = Kontext.init({
1717
+ * projectId: 'treasury-agent',
1718
+ * environment: 'production',
1719
+ * storage: new FirestoreStorageAdapter({
1720
+ * gcpProjectId: 'Kontext',
1721
+ * userId: 'user-abc123',
1722
+ * }),
1816
1723
  * });
1817
1724
  *
1818
- * if (evaluation.required) {
1819
- * // Wait for human decision
1820
- * const request = manager.submitDecision({
1821
- * requestId: evaluation.requestId!,
1822
- * decision: 'approve',
1823
- * decidedBy: 'admin@example.com',
1824
- * reason: 'Verified recipient',
1825
- * });
1826
- * }
1725
+ * // After this, all verify(), log(), logReasoning() calls are
1726
+ * // persisted to Firestore at:
1727
+ * // users/user-abc123/projects/treasury-agent/agents/{agentId}/sessions/{sessionId}/...
1827
1728
  * ```
1828
1729
  */
1829
- declare class ApprovalManager {
1830
- private readonly policies;
1831
- private readonly expiresInMs;
1832
- private readonly requests;
1833
- private readonly seenDestinations;
1834
- constructor(policies: ApprovalPolicy[], expiresInMs?: number);
1835
- /**
1836
- * Evaluate an action against all enabled policies.
1837
- * If any policy triggers, an ApprovalRequest is created and the evaluation
1838
- * returns `required: true` with the request ID.
1839
- *
1840
- * @param input - Action details to evaluate
1841
- * @returns Evaluation result indicating whether approval is required
1842
- */
1843
- evaluate(input: EvaluateApprovalInput): ApprovalEvaluation;
1730
+ declare class FirestoreStorageAdapter implements StorageAdapter {
1731
+ private readonly config;
1732
+ /** In-memory cache for load() — avoids re-fetching on every store.restore() */
1733
+ private cache;
1734
+ /** Token cache: avoid metadata server round-trips on every write */
1735
+ private cachedToken;
1736
+ private tokenExpiresAt;
1737
+ constructor(config: FirestoreStorageConfig);
1844
1738
  /**
1845
- * Submit a human decision on a pending approval request.
1739
+ * Save data under a Kontext storage key.
1846
1740
  *
1847
- * @param input - Decision details
1848
- * @returns The updated ApprovalRequest
1849
- * @throws KontextError if request not found, expired, or missing required evidence
1741
+ * The flat key space (kontext:actions, kontext:transactions, etc.) is mapped
1742
+ * to structured Firestore paths. List data (actions, transactions) is written
1743
+ * as individual documents under sub-collections for queryability.
1850
1744
  */
1851
- submitDecision(input: SubmitDecisionInput): ApprovalRequest;
1745
+ save(key: string, data: unknown): Promise<void>;
1852
1746
  /**
1853
- * Get an approval request by ID.
1854
- *
1855
- * @param requestId - The approval request identifier
1856
- * @returns The approval request, or undefined if not found
1747
+ * Load data for a Kontext storage key.
1748
+ * Returns cached data if available (populated by save()).
1749
+ * Falls back to Firestore fetch for cold starts.
1857
1750
  */
1858
- getRequest(requestId: string): ApprovalRequest | undefined;
1751
+ load(key: string): Promise<unknown | null>;
1752
+ delete(key: string): Promise<void>;
1753
+ list(prefix?: string): Promise<string[]>;
1859
1754
  /**
1860
- * Get all pending approval requests.
1755
+ * Write a single action log to its canonical Firestore path.
1756
+ * Called by the SDK when `writeDocumentsIndividually` is true.
1861
1757
  *
1862
- * @returns Array of pending approval requests
1758
+ * Path: users/{userId}/projects/{projectId}/agents/{agentId}/sessions/{sessionId}/actions/{actionId}
1863
1759
  */
1864
- getPendingRequests(): ApprovalRequest[];
1760
+ writeAction(action: ActionLog): Promise<void>;
1865
1761
  /**
1866
- * Get all approval requests for a specific agent.
1762
+ * Write a single transaction record to its canonical Firestore path.
1867
1763
  *
1868
- * @param agentId - The agent identifier
1869
- * @returns Array of approval requests for the agent
1764
+ * Path: users/{userId}/projects/{projectId}/agents/{agentId}/sessions/{sessionId}/transactions/{txId}
1870
1765
  */
1871
- getRequestsByAgent(agentId: string): ApprovalRequest[];
1766
+ writeTransaction(tx: TransactionRecord): Promise<void>;
1872
1767
  /**
1873
- * Check if an approval request has been approved.
1768
+ * Write a single task to its canonical Firestore path.
1874
1769
  *
1875
- * @param requestId - The approval request identifier
1876
- * @returns Whether the request is approved
1770
+ * Path: users/{userId}/projects/{projectId}/tasks/{taskId}
1877
1771
  */
1878
- isApproved(requestId: string): boolean;
1879
- private evaluatePolicy;
1880
- private evaluateAmountThreshold;
1881
- private evaluateLowTrustScore;
1882
- private evaluateAnomalyDetected;
1883
- private evaluateNewDestination;
1884
- private calculateRiskScore;
1885
- private collectRequiredEvidence;
1772
+ writeTask(task: Task): Promise<void>;
1773
+ private get basePath();
1774
+ private actionPath;
1775
+ private transactionPath;
1776
+ private taskPath;
1777
+ private anomalyPath;
1778
+ private keyToPath;
1779
+ private saveActionList;
1780
+ private saveTransactionList;
1781
+ private saveTaskList;
1782
+ private saveAnomalyList;
1783
+ private loadActionList;
1784
+ private loadTransactionList;
1785
+ private loadTaskList;
1786
+ private loadAnomalyList;
1787
+ private firestoreBase;
1788
+ /** Save an arbitrary JS object as a Firestore document at the given path. */
1789
+ private saveDocument;
1790
+ /** Load a document at the given Firestore path. Returns null if not found. */
1791
+ private loadDocument;
1792
+ /** Delete a document at the given Firestore path. */
1793
+ private deleteDocument;
1794
+ /**
1795
+ * List all documents in a collection and deserialize them.
1796
+ * Used for tasks (simple flat collection).
1797
+ */
1798
+ private queryCollection;
1799
+ /**
1800
+ * Run a Firestore collection group query to fetch documents across all
1801
+ * nested sub-collections with the given name (e.g., 'actions' across all
1802
+ * agents and sessions).
1803
+ *
1804
+ * Scoped to the user's project root to prevent cross-tenant reads.
1805
+ */
1806
+ private queryCollectionGroup;
1807
+ private getToken;
1886
1808
  }
1887
1809
 
1888
1810
  /** Features gated by plan tier */
1889
- type GatedFeature = 'advanced-anomaly-rules' | 'sar-ctr-reports' | 'webhooks' | 'ofac-screening' | 'csv-export' | 'multi-chain' | 'cftc-compliance' | 'circle-wallets' | 'circle-compliance' | 'gas-station' | 'cctp-transfers' | 'approval-policies' | 'unified-screening' | 'blocklist-manager';
1811
+ type GatedFeature = 'advanced-anomaly-rules' | 'sar-ctr-reports' | 'webhooks' | 'ofac-screening' | 'csv-export' | 'multi-chain' | 'cftc-compliance' | 'circle-wallets' | 'circle-compliance' | 'gas-station' | 'cctp-transfers' | 'approval-policies' | 'unified-screening' | 'blocklist-manager' | 'kya-identity' | 'kya-behavioral';
1890
1812
  /**
1891
1813
  * Check if a feature is available on the given plan.
1892
1814
  * Returns true if allowed, false if not.
@@ -1897,298 +1819,6 @@ declare function isFeatureAvailable(feature: GatedFeature, currentPlan: PlanTier
1897
1819
  */
1898
1820
  declare function requirePlan(feature: GatedFeature, currentPlan: PlanTier): void;
1899
1821
 
1900
- /** OFAC sanctions list identifiers */
1901
- type SanctionsList = 'SDN' | 'SSI' | 'CAPTA' | 'NS-MBS' | 'CONSOLIDATED' | 'DELISTED' | 'COMMUNITY';
1902
- /** Sanctioned jurisdiction identifiers (ISO 3166-1 alpha-2 where applicable) */
1903
- type SanctionedJurisdiction = 'KP' | 'IR' | 'CU' | 'SY' | 'RU_CRIMEA' | 'RU_DNR' | 'RU_LNR' | 'RU_ZAPORIZHZHIA' | 'RU_KHERSON' | 'BY' | 'VE' | 'MM' | 'SD' | 'SO';
1904
- /** Risk level for sanctions screening */
1905
- type SanctionsRiskLevel = 'NONE' | 'LOW' | 'MEDIUM' | 'HIGH' | 'SEVERE' | 'BLOCKED';
1906
- /** Entity type for sanctions context */
1907
- type SanctionedEntityType = 'MIXER' | 'EXCHANGE' | 'INDIVIDUAL' | 'GROUP' | 'PROTOCOL' | 'UNKNOWN';
1908
- /** A sanctioned address entry with metadata */
1909
- interface SanctionedAddressEntry {
1910
- /** The blockchain address */
1911
- address: string;
1912
- /** Which sanctions list(s) this address appears on */
1913
- lists: SanctionsList[];
1914
- /** The entity name associated with this address */
1915
- entityName: string;
1916
- /** Entity type */
1917
- entityType: SanctionedEntityType;
1918
- /** ISO date when the address was first sanctioned */
1919
- dateAdded: string;
1920
- /** ISO date when the address was removed (if applicable) */
1921
- dateRemoved: string | null;
1922
- /** Blockchain network(s) this address is relevant to */
1923
- chains: string[];
1924
- /** Additional notes */
1925
- notes: string;
1926
- }
1927
- /** Result of a comprehensive sanctions screening */
1928
- interface ComprehensiveSanctionsResult {
1929
- /** Whether any sanctions match was found */
1930
- sanctioned: boolean;
1931
- /** Overall risk level */
1932
- riskLevel: SanctionsRiskLevel;
1933
- /** Numeric risk score (0-100) */
1934
- riskScore: number;
1935
- /** The address that was screened */
1936
- address: string;
1937
- /** Direct address matches */
1938
- directMatches: SanctionsMatch[];
1939
- /** Jurisdictional flags */
1940
- jurisdictionFlags: JurisdictionFlag[];
1941
- /** Pattern-based flags */
1942
- patternFlags: PatternFlag[];
1943
- /** 50% rule flags */
1944
- ownershipFlags: OwnershipFlag[];
1945
- /** Screening timestamp */
1946
- screenedAt: string;
1947
- /** Lists that were checked */
1948
- listsChecked: SanctionsList[];
1949
- /** Recommendations */
1950
- recommendations: string[];
1951
- }
1952
- /** A match against a sanctions list */
1953
- interface SanctionsMatch {
1954
- /** The matched address */
1955
- matchedAddress: string;
1956
- /** Which list the match is on */
1957
- list: SanctionsList;
1958
- /** Entity name */
1959
- entityName: string;
1960
- /** Entity type */
1961
- entityType: SanctionedEntityType;
1962
- /** Match confidence (0-1, 1.0 = exact match) */
1963
- confidence: number;
1964
- /** Whether this is currently active or delisted */
1965
- active: boolean;
1966
- }
1967
- /** A jurisdictional screening flag */
1968
- interface JurisdictionFlag {
1969
- /** The flagged jurisdiction */
1970
- jurisdiction: SanctionedJurisdiction;
1971
- /** Human-readable jurisdiction name */
1972
- name: string;
1973
- /** Reason for the flag */
1974
- reason: string;
1975
- /** Risk level for this jurisdiction */
1976
- riskLevel: SanctionsRiskLevel;
1977
- }
1978
- /** A pattern-based flag */
1979
- interface PatternFlag {
1980
- /** Pattern type */
1981
- pattern: 'MIXING' | 'CHAIN_HOPPING' | 'STRUCTURING' | 'RAPID_MOVEMENT' | 'PEELING_CHAIN';
1982
- /** Human-readable description */
1983
- description: string;
1984
- /** Severity */
1985
- severity: SanctionsRiskLevel;
1986
- /** Evidence for the flag */
1987
- evidence: string[];
1988
- }
1989
- /** A 50% rule ownership flag */
1990
- interface OwnershipFlag {
1991
- /** The entity that may be controlled by a sanctioned party */
1992
- entityName: string;
1993
- /** The sanctioned parent entity */
1994
- sanctionedParent: string;
1995
- /** Estimated ownership percentage */
1996
- ownershipPercentage: number;
1997
- /** Source of the ownership data */
1998
- source: string;
1999
- }
2000
- /** Transaction data for pattern analysis */
2001
- interface TransactionForAnalysis {
2002
- txHash: string;
2003
- from: string;
2004
- to: string;
2005
- amount: number;
2006
- chain: string;
2007
- timestamp: string;
2008
- }
2009
- /** Entity name for fuzzy matching */
2010
- interface EntityNameEntry {
2011
- /** Canonical name */
2012
- name: string;
2013
- /** Known aliases */
2014
- aliases: string[];
2015
- /** Associated addresses */
2016
- addresses: string[];
2017
- /** Sanctions list */
2018
- list: SanctionsList;
2019
- }
2020
- /** Sanctions list metadata */
2021
- interface SanctionsListMetadata {
2022
- /** When the list was last updated */
2023
- lastUpdated: string;
2024
- /** Number of addresses in the list */
2025
- addressCount: number;
2026
- /** Number of entities in the list */
2027
- entityCount: number;
2028
- /** Source URL */
2029
- sourceUrl: string;
2030
- /** Version/hash of the list */
2031
- version: string;
2032
- }
2033
- interface JurisdictionInfo {
2034
- code: SanctionedJurisdiction;
2035
- name: string;
2036
- sanctionsProgram: string;
2037
- riskLevel: SanctionsRiskLevel;
2038
- comprehensive: boolean;
2039
- }
2040
- /**
2041
- * Comprehensive OFAC sanctions screening engine.
2042
- *
2043
- * Goes beyond simple address matching to provide multi-layered screening
2044
- * aligned with GENIUS Act requirements and OFAC compliance best practices.
2045
- *
2046
- * Features:
2047
- * - SDN and Consolidated Sanctions List address matching
2048
- * - Delisted address risk flagging (e.g., former Tornado Cash contracts)
2049
- * - Jurisdictional screening for sanctioned countries
2050
- * - 50% Rule ownership flagging
2051
- * - Fuzzy entity name matching with alias support
2052
- * - Transaction pattern analysis (mixing, chain-hopping, structuring)
2053
- * - Sanctions list update mechanism
2054
- * - Comprehensive risk scoring
2055
- *
2056
- * @example
2057
- * ```typescript
2058
- * const screener = new OFACSanctionsScreener();
2059
- *
2060
- * // Screen a single address
2061
- * const result = screener.screenAddress('0x098B716B...');
2062
- * if (result.sanctioned) {
2063
- * console.log('BLOCKED:', result.recommendations);
2064
- * }
2065
- *
2066
- * // Screen with jurisdiction context
2067
- * const result2 = screener.screenAddress('0x...', { jurisdiction: 'IR' });
2068
- *
2069
- * // Fuzzy entity name search
2070
- * const matches = screener.searchEntityName('Lazarus');
2071
- * ```
2072
- */
2073
- declare class OFACSanctionsScreener {
2074
- /**
2075
- * Check if an address is on an active sanctions list.
2076
- * Returns true only for currently sanctioned (non-delisted) addresses.
2077
- */
2078
- isActivelySanctioned(address: string): boolean;
2079
- /**
2080
- * Check if an address has ever appeared on any sanctions list,
2081
- * including those that have been delisted.
2082
- */
2083
- hasAnySanctionsHistory(address: string): boolean;
2084
- /**
2085
- * Get the full entry for a sanctioned address.
2086
- */
2087
- getAddressEntry(address: string): SanctionedAddressEntry | undefined;
2088
- /**
2089
- * Perform a comprehensive sanctions screening on an address.
2090
- * Checks against all lists, evaluates jurisdiction, and computes risk score.
2091
- */
2092
- screenAddress(address: string, context?: {
2093
- jurisdiction?: SanctionedJurisdiction;
2094
- counterpartyAddress?: string;
2095
- amount?: number;
2096
- chain?: string;
2097
- }): ComprehensiveSanctionsResult;
2098
- /**
2099
- * Screen a jurisdiction for sanctions.
2100
- */
2101
- screenJurisdiction(code: string): JurisdictionFlag | null;
2102
- /**
2103
- * Get all sanctioned jurisdictions.
2104
- */
2105
- getSanctionedJurisdictions(): JurisdictionInfo[];
2106
- /**
2107
- * Check if a jurisdiction has comprehensive sanctions (all transactions blocked).
2108
- */
2109
- isComprehensiveSanctions(code: SanctionedJurisdiction): boolean;
2110
- /**
2111
- * Search for sanctioned entities by name with fuzzy matching.
2112
- * Uses normalized Levenshtein distance and alias matching.
2113
- *
2114
- * @param query - Name to search for
2115
- * @param threshold - Minimum similarity score (0-1, default 0.6)
2116
- * @returns Matching entities sorted by relevance
2117
- */
2118
- searchEntityName(query: string, threshold?: number): Array<{
2119
- entity: EntityNameEntry;
2120
- similarity: number;
2121
- matchedOn: string;
2122
- }>;
2123
- /**
2124
- * Check if an entity may be subject to the OFAC 50% Rule.
2125
- *
2126
- * Under the 50% Rule, entities owned 50% or more (individually or in
2127
- * aggregate) by one or more sanctioned persons are themselves blocked,
2128
- * even if not explicitly named on the SDN list.
2129
- *
2130
- * This method checks a provided ownership structure against known
2131
- * sanctioned entities.
2132
- *
2133
- * @param ownershipEntries - Array of { ownerName, ownershipPercentage } objects
2134
- * @returns Array of OwnershipFlag for any sanctioned owners
2135
- */
2136
- checkFiftyPercentRule(entityName: string, ownershipEntries: Array<{
2137
- ownerName: string;
2138
- ownershipPercentage: number;
2139
- }>): OwnershipFlag[];
2140
- /**
2141
- * Analyze a set of transactions for patterns associated with sanctions evasion.
2142
- *
2143
- * Detects:
2144
- * - Mixing/tumbling indicators (interaction with known mixers)
2145
- * - Chain-hopping patterns (rapid cross-chain movements)
2146
- * - Structuring (amounts just below reporting thresholds)
2147
- * - Rapid fund movement through intermediaries
2148
- * - Peeling chain patterns
2149
- */
2150
- analyzeTransactionPatterns(transactions: TransactionForAnalysis[]): PatternFlag[];
2151
- private detectMixingPattern;
2152
- private detectChainHopping;
2153
- private detectStructuring;
2154
- private detectRapidMovement;
2155
- private detectPeelingChain;
2156
- /**
2157
- * Add new sanctioned addresses to the database at runtime.
2158
- * Returns the count of newly added addresses.
2159
- */
2160
- addAddresses(entries: SanctionedAddressEntry[]): number;
2161
- /**
2162
- * Add new entity names for fuzzy matching.
2163
- */
2164
- addEntities(entities: EntityNameEntry[]): number;
2165
- /**
2166
- * Get current sanctions list metadata.
2167
- */
2168
- getListMetadata(): SanctionsListMetadata;
2169
- /**
2170
- * Get all active sanctioned addresses (non-delisted).
2171
- */
2172
- getActiveSanctionedAddresses(): string[];
2173
- /**
2174
- * Get all sanctioned addresses including delisted.
2175
- */
2176
- getAllAddresses(): string[];
2177
- /**
2178
- * Get the count of active sanctioned addresses.
2179
- */
2180
- getActiveAddressCount(): number;
2181
- /**
2182
- * Get the count of all addresses (including delisted).
2183
- */
2184
- getTotalAddressCount(): number;
2185
- /**
2186
- * Get all entity names in the database.
2187
- */
2188
- getEntities(): EntityNameEntry[];
2189
- }
2190
- declare const ofacScreener: OFACSanctionsScreener;
2191
-
2192
1822
  /**
2193
1823
  * Result of a sanctions check with list matching details.
2194
1824
  */
@@ -2301,31 +1931,6 @@ declare class UsdcCompliance {
2301
1931
  * @returns The size of the current sanctions list
2302
1932
  */
2303
1933
  static getSanctionsListSize(): number;
2304
- /**
2305
- * Perform comprehensive OFAC sanctions screening using the advanced
2306
- * OFACSanctionsScreener. This goes beyond simple address matching to
2307
- * include jurisdictional screening, delisted address detection, and
2308
- * entity metadata.
2309
- *
2310
- * @param address - The address to screen
2311
- * @param context - Optional context for enhanced screening
2312
- * @returns ComprehensiveSanctionsResult with full screening details
2313
- */
2314
- static screenComprehensive(address: string, context?: {
2315
- jurisdiction?: string;
2316
- counterpartyAddress?: string;
2317
- amount?: number;
2318
- chain?: string;
2319
- }): ComprehensiveSanctionsResult;
2320
- /**
2321
- * Check if an address is actively sanctioned (non-delisted).
2322
- * Unlike isSanctioned(), this excludes addresses that have been removed
2323
- * from the SDN list (e.g., Tornado Cash contracts post-March 2025).
2324
- *
2325
- * @param address - The address to check
2326
- * @returns true if the address is on an active sanctions list
2327
- */
2328
- static isActivelySanctioned(address: string): boolean;
2329
1934
  private static checkTokenType;
2330
1935
  private static checkChainSupport;
2331
1936
  private static checkAddressFormat;
@@ -2336,2661 +1941,349 @@ declare class UsdcCompliance {
2336
1941
  private static generateRecommendations;
2337
1942
  }
2338
1943
 
2339
- /** CCTP protocol version */
2340
- type CCTPVersion = 'v1' | 'v2';
2341
- /** CCTP message status */
2342
- type CCTPMessageStatus = 'pending' | 'attested' | 'confirmed' | 'failed';
2343
- /** CCTP V2 hook definition for post-transfer automation */
2344
- interface CCTPHook {
2345
- /** Target contract address on the destination chain */
2346
- targetContract: string;
2347
- /** Encoded function call data */
2348
- callData: string;
2349
- /** Maximum gas for hook execution */
2350
- gasLimit: number;
2351
- /** Human-readable description of the hook */
2352
- description?: string;
2353
- }
2354
- /** Input for initiating a CCTP V2 fast transfer */
2355
- interface InitiateFastTransferInput {
2356
- /** Source chain */
2357
- sourceChain: Chain;
2358
- /** Destination chain */
2359
- destinationChain: Chain;
2360
- /** Transfer amount */
2361
- amount: string;
2362
- /** Token being transferred */
2363
- token: Token;
2364
- /** Sender address */
2365
- sender: string;
2366
- /** Recipient address */
2367
- recipient: string;
2368
- /** Source chain transaction hash */
2369
- sourceTxHash: string;
2370
- /** Agent initiating the transfer */
2371
- agentId: string;
2372
- /** Maximum finality time the sender will accept (seconds) */
2373
- maxFinalitySeconds?: number;
2374
- /** Optional hooks to execute after transfer completes */
2375
- hooks?: CCTPHook[];
2376
- /** Optional nonce */
2377
- nonce?: number;
2378
- /** Optional correlation ID */
2379
- correlationId?: string;
2380
- /** Optional metadata */
2381
- metadata?: Record<string, unknown>;
2382
- }
2383
- /** A cross-chain transfer record */
2384
- interface CrossChainTransfer {
2385
- /** Unique transfer identifier */
2386
- id: string;
2387
- /** Source chain */
2388
- sourceChain: Chain;
2389
- /** Destination chain */
2390
- destinationChain: Chain;
2391
- /** CCTP domain ID for source */
2392
- sourceDomain: number;
2393
- /** CCTP domain ID for destination */
2394
- destinationDomain: number;
2395
- /** Transfer amount (string to preserve precision) */
2396
- amount: string;
2397
- /** Token being transferred */
2398
- token: Token;
2399
- /** Sender address on source chain */
2400
- sender: string;
2401
- /** Recipient address on destination chain */
2402
- recipient: string;
2403
- /** Source chain transaction hash */
2404
- sourceTxHash: string;
2405
- /** Destination chain transaction hash (set after confirmation) */
2406
- destinationTxHash: string | null;
2407
- /** CCTP message hash for attestation tracking */
2408
- messageHash: string | null;
2409
- /** Current status of the transfer */
2410
- status: CCTPMessageStatus;
2411
- /** Nonce from the CCTP MessageSent event */
2412
- nonce: number | null;
2413
- /** Timestamp when the transfer was initiated */
2414
- initiatedAt: string;
2415
- /** Timestamp when attestation was received */
2416
- attestedAt: string | null;
2417
- /** Timestamp when the transfer was confirmed on destination */
2418
- confirmedAt: string | null;
2419
- /** Correlation ID linking source and destination actions */
2420
- correlationId: string;
2421
- /** Agent that initiated the transfer */
2422
- agentId: string;
2423
- /** Additional metadata */
2424
- metadata: Record<string, unknown>;
2425
- /** CCTP protocol version used */
2426
- version?: CCTPVersion;
2427
- /** Whether this is a fast transfer (V2) */
2428
- isFastTransfer?: boolean;
2429
- /** Post-transfer hooks (V2) */
2430
- hooks?: CCTPHook[];
2431
- /** Hook execution results (V2) */
2432
- hookResults?: CCTPHookResult[];
2433
- }
2434
- /** Input for initiating a cross-chain transfer record */
2435
- interface InitiateCCTPTransferInput {
2436
- /** Source chain */
2437
- sourceChain: Chain;
2438
- /** Destination chain */
2439
- destinationChain: Chain;
2440
- /** Transfer amount */
2441
- amount: string;
2442
- /** Token being transferred */
2443
- token: Token;
2444
- /** Sender address */
2445
- sender: string;
2446
- /** Recipient address */
2447
- recipient: string;
2448
- /** Source chain transaction hash (from depositForBurn) */
2449
- sourceTxHash: string;
2450
- /** Agent initiating the transfer */
2451
- agentId: string;
2452
- /** Optional nonce from the MessageSent event */
2453
- nonce?: number;
2454
- /** Optional correlation ID */
2455
- correlationId?: string;
2456
- /** Optional metadata */
2457
- metadata?: Record<string, unknown>;
2458
- }
2459
- /** Input for recording a CCTP attestation */
2460
- interface CCTPAttestationInput {
2461
- /** The cross-chain transfer ID */
2462
- transferId: string;
2463
- /** The message hash from the attestation service */
2464
- messageHash: string;
2465
- /** Optional attestation metadata */
2466
- metadata?: Record<string, unknown>;
2467
- }
2468
- /** Input for confirming a cross-chain transfer on destination */
2469
- interface ConfirmCCTPTransferInput {
2470
- /** The cross-chain transfer ID */
2471
- transferId: string;
2472
- /** Destination chain transaction hash (from receiveMessage) */
2473
- destinationTxHash: string;
2474
- /** Optional metadata */
2475
- metadata?: Record<string, unknown>;
2476
- }
2477
- /** Validation result for a cross-chain transfer */
2478
- interface CCTPValidationResult {
2479
- /** Whether the transfer configuration is valid */
2480
- valid: boolean;
2481
- /** Validation checks performed */
2482
- checks: CCTPValidationCheck[];
2483
- /** Overall risk level */
2484
- riskLevel: 'low' | 'medium' | 'high' | 'critical';
2485
- /** Recommendations */
2486
- recommendations: string[];
2487
- }
2488
- /** Individual validation check */
2489
- interface CCTPValidationCheck {
2490
- /** Check name */
2491
- name: string;
2492
- /** Whether the check passed */
2493
- passed: boolean;
2494
- /** Description */
2495
- description: string;
2496
- /** Severity if failed */
2497
- severity: AnomalySeverity;
2498
- }
2499
- /** Cross-chain audit trail entry */
2500
- interface CrossChainAuditEntry {
2501
- /** The transfer record */
2502
- transfer: CrossChainTransfer;
2503
- /** Source chain action log ID (from logTransaction) */
2504
- sourceActionId: string | null;
2505
- /** Destination chain action log ID (from logTransaction) */
2506
- destinationActionId: string | null;
2507
- /** Whether source and destination are linked */
2508
- linked: boolean;
2509
- /** Duration from initiation to confirmation in milliseconds */
2510
- durationMs: number | null;
2511
- }
2512
- /** Result of a CCTP V2 hook execution */
2513
- interface CCTPHookResult {
2514
- /** Target contract address */
2515
- targetContract: string;
2516
- /** Whether the hook executed successfully */
2517
- success: boolean;
2518
- /** Transaction hash of the hook execution */
2519
- transactionHash?: string;
2520
- /** Error message if the hook failed */
2521
- error?: string;
2522
- /** Gas used by the hook */
2523
- gasUsed?: number;
2524
- }
2525
- /** Validation result for a CCTP V2 fast transfer */
2526
- interface FastTransferValidation {
2527
- /** Whether the fast transfer route is supported */
2528
- fastTransferAvailable: boolean;
2529
- /** Estimated finality time in seconds */
2530
- estimatedFinalitySeconds: number;
2531
- /** Whether hooks are valid */
2532
- hooksValid: boolean;
2533
- /** Hook validation details */
2534
- hookValidation: {
2535
- index: number;
2536
- valid: boolean;
2537
- reason?: string;
2538
- }[];
2539
- /** Standard validation result */
2540
- standardValidation: CCTPValidationResult;
2541
- }
2542
- /**
2543
- * CCTPTransferManager handles cross-chain transfer tracking and validation
2544
- * for Circle's Cross-Chain Transfer Protocol.
2545
- *
2546
- * Provides:
2547
- * - Transfer validation (source chain to destination chain)
2548
- * - CCTP message attestation logging
2549
- * - Cross-chain audit trail linking
2550
- * - Transfer lifecycle tracking (pending -> attested -> confirmed)
2551
- */
2552
- declare class CCTPTransferManager {
2553
- private transfers;
2554
- private actionLinks;
2555
- /**
2556
- * Validate a cross-chain transfer before execution.
2557
- *
2558
- * Checks include:
2559
- * - Source and destination chain support
2560
- * - Route validity (different chains)
2561
- * - Token support on both chains
2562
- * - Amount validation
2563
- * - Address format validation
2564
- *
2565
- * @param input - Transfer details to validate
2566
- * @returns Validation result with checks and recommendations
2567
- */
2568
- validateTransfer(input: InitiateCCTPTransferInput): CCTPValidationResult;
2569
- /**
2570
- * Record a new cross-chain transfer initiated via CCTP depositForBurn.
2571
- *
2572
- * @param input - Transfer initiation details
2573
- * @returns The created CrossChainTransfer record
2574
- */
2575
- initiateTransfer(input: InitiateCCTPTransferInput): CrossChainTransfer;
2576
- /**
2577
- * Record a CCTP attestation for a pending transfer.
2578
- * Called after the attestation service has signed the burn message.
2579
- *
2580
- * @param input - Attestation details
2581
- * @returns The updated CrossChainTransfer record
2582
- * @throws Error if transfer not found or not in pending status
2583
- */
2584
- recordAttestation(input: CCTPAttestationInput): CrossChainTransfer;
2585
- /**
2586
- * Confirm a cross-chain transfer has been received on the destination chain.
2587
- * Called after receiveMessage has been executed on the destination.
2588
- *
2589
- * @param input - Confirmation details
2590
- * @returns The updated CrossChainTransfer record
2591
- * @throws Error if transfer not found or not in attested status
2592
- */
2593
- confirmTransfer(input: ConfirmCCTPTransferInput): CrossChainTransfer;
2594
- /**
2595
- * Mark a transfer as failed.
2596
- *
2597
- * @param transferId - The transfer to mark as failed
2598
- * @param reason - Reason for failure
2599
- * @returns The updated CrossChainTransfer record
2600
- */
2601
- failTransfer(transferId: string, reason: string): CrossChainTransfer;
2602
- /**
2603
- * Link a Kontext action log ID to a cross-chain transfer.
2604
- * Used to correlate source and destination chain actions in the audit trail.
2605
- *
2606
- * @param transferId - The cross-chain transfer ID
2607
- * @param actionId - The action log ID to link
2608
- * @param side - Whether this is the source or destination action
2609
- */
2610
- linkAction(transferId: string, actionId: string, side: 'source' | 'destination'): void;
2611
- /**
2612
- * Get a cross-chain transfer by ID.
2613
- */
2614
- getTransfer(transferId: string): CrossChainTransfer | undefined;
2615
- /**
2616
- * Get all cross-chain transfers, optionally filtered by status.
2617
- */
2618
- getTransfers(status?: CCTPMessageStatus): CrossChainTransfer[];
2619
- /**
2620
- * Get transfers by correlation ID.
2621
- * Useful for finding all transfers related to a single workflow.
2622
- */
2623
- getTransfersByCorrelation(correlationId: string): CrossChainTransfer[];
2624
- /**
2625
- * Build a cross-chain audit trail for a given transfer.
2626
- * Links source and destination chain actions together.
2627
- *
2628
- * @param transferId - The transfer to build an audit trail for
2629
- * @returns CrossChainAuditEntry with linked action references
2630
- */
2631
- getAuditEntry(transferId: string): CrossChainAuditEntry | undefined;
2632
- /**
2633
- * Build audit trail entries for all transfers, optionally filtered.
2634
- *
2635
- * @param agentId - Optional filter by agent
2636
- * @returns Array of CrossChainAuditEntry records
2637
- */
2638
- getAuditTrail(agentId?: string): CrossChainAuditEntry[];
2639
- /**
2640
- * Validate a fast transfer request (CCTP V2).
2641
- * Checks route eligibility, hook validity, and standard validation.
2642
- *
2643
- * @param input - Fast transfer details
2644
- * @returns FastTransferValidation with availability and hook checks
2645
- */
2646
- validateFastTransfer(input: InitiateFastTransferInput): FastTransferValidation;
2647
- /**
2648
- * Initiate a CCTP V2 fast transfer with optional hooks.
2649
- *
2650
- * Fast transfers use CCTP V2's sub-minute finality on supported routes.
2651
- * Hooks allow automated post-transfer actions on the destination chain.
2652
- *
2653
- * @param input - Fast transfer details including optional hooks
2654
- * @returns The created CrossChainTransfer record with V2 metadata
2655
- */
2656
- initiateFastTransfer(input: InitiateFastTransferInput): CrossChainTransfer;
2657
- /**
2658
- * Record hook execution results for a V2 transfer.
2659
- *
2660
- * @param transferId - The transfer ID
2661
- * @param results - Array of hook execution results
2662
- * @returns The updated transfer
2663
- */
2664
- recordHookResults(transferId: string, results: CCTPHookResult[]): CrossChainTransfer;
2665
- /**
2666
- * Check if a route supports CCTP V2 fast transfers.
2667
- *
2668
- * @param sourceChain - Source blockchain network
2669
- * @param destinationChain - Destination blockchain network
2670
- * @returns Whether fast transfer is available
2671
- */
2672
- static isFastTransferAvailable(sourceChain: Chain, destinationChain: Chain): boolean;
2673
- /**
2674
- * Get the CCTP domain ID for a given chain.
2675
- *
2676
- * @param chain - The blockchain network
2677
- * @returns The CCTP domain ID, or undefined for unsupported chains
2678
- */
2679
- static getDomainId(chain: Chain): number | undefined;
2680
- /**
2681
- * Get the chains supported for CCTP transfers.
2682
- */
2683
- static getSupportedChains(): Chain[];
2684
- /**
2685
- * Get the list of V2 fast-transfer eligible routes.
2686
- *
2687
- * @returns Array of route strings in "source->destination" format
2688
- */
2689
- static getFastTransferRoutes(): string[];
2690
- private checkChainSupport;
2691
- private checkRouteValidity;
2692
- private checkTokenSupport;
2693
- private checkAmountValidity;
2694
- private checkAddressFormat;
2695
- private generateRecommendations;
2696
- }
2697
-
2698
- /** Configuration options for the CircleWalletManager */
2699
- interface CircleWalletOptions {
2700
- /** Entity secret ciphertext for developer-controlled wallets */
2701
- entitySecretCiphertext?: string;
2702
- /** Default blockchain network for new wallets */
2703
- defaultChain?: Chain;
2704
- /** Automatically log all wallet operations through Kontext (default: true) */
2705
- autoLog?: boolean;
2706
- /** Require compliance check before transfers (default: true) */
2707
- requireCompliance?: boolean;
2708
- }
2709
- /** A wallet set (group of wallets) */
2710
- interface WalletSet {
2711
- /** Unique wallet set identifier */
2712
- id: string;
2713
- /** Human-readable name */
2714
- name: string;
2715
- /** Custody type */
2716
- custodyType: 'DEVELOPER' | 'USER';
2717
- /** Creation timestamp */
2718
- createdAt: string;
2719
- }
2720
- /** A Circle programmable wallet */
2721
- interface CircleWallet {
2722
- /** Unique wallet identifier */
2723
- id: string;
2724
- /** Parent wallet set ID */
2725
- walletSetId: string;
2726
- /** On-chain address */
2727
- address: string;
2728
- /** Blockchain network */
2729
- chain: Chain;
2730
- /** Custody type */
2731
- custodyType: 'DEVELOPER' | 'USER';
2732
- /** Wallet state */
2733
- state: 'LIVE' | 'FROZEN';
2734
- /** Creation timestamp */
2735
- createDate: string;
2736
- }
2737
- /** Options for creating a new wallet */
2738
- interface CreateWalletOptions {
2739
- /** Blockchain network for the wallet */
2740
- chain: Chain;
2741
- /** Custody type (default: 'DEVELOPER') */
2742
- custodyType?: 'DEVELOPER' | 'USER';
2743
- /** Additional metadata */
2744
- metadata?: Record<string, string>;
2745
- }
2746
- /** Input for a compliant transfer */
2747
- interface CompliantTransferInput {
2748
- /** Source wallet ID */
2749
- walletId: string;
2750
- /** Destination on-chain address */
2751
- destinationAddress: string;
2752
- /** Transfer amount (string to preserve precision) */
2753
- amount: string;
2754
- /** Blockchain network (defaults to wallet's chain) */
2755
- chain?: Chain;
2756
- /** Token to transfer */
2757
- token?: 'USDC' | 'EURC';
2758
- /** Agent initiating the transfer */
2759
- agent?: string;
2760
- /** Additional metadata */
2761
- metadata?: Record<string, any>;
2762
- }
2763
- /** Result of a compliant transfer */
2764
- interface CompliantTransferResult {
2765
- /** Circle transfer identifier */
2766
- transferId: string;
2767
- /** Source wallet ID */
2768
- walletId: string;
2769
- /** Transfer status */
2770
- status: 'COMPLETED' | 'BLOCKED' | 'PENDING_REVIEW';
2771
- /** Compliance check details */
2772
- complianceCheck: ComplianceCheckSummary;
2773
- /** Kontext action log ID */
2774
- kontextLogId: string;
2775
- /** Trust score at time of transfer */
2776
- trustScore: number;
2777
- /** Transfer amount */
2778
- amount: string;
2779
- /** Blockchain network */
2780
- chain: Chain;
2781
- /** On-chain transaction hash (if completed) */
2782
- transactionHash?: string;
2783
- /** Reason the transfer was blocked (if blocked) */
2784
- blockedReason?: string;
2785
- }
2786
- /** Summary of compliance check for a transfer */
2787
- interface ComplianceCheckSummary {
2788
- /** Whether the check passed */
2789
- passed: boolean;
2790
- /** Risk level */
2791
- riskLevel: AnomalySeverity;
2792
- /** Individual check results */
2793
- checks: ComplianceCheckResult[];
2794
- /** Recommendations */
2795
- recommendations: string[];
2796
- }
2797
- /** Wallet balance information */
2798
- interface WalletBalance {
2799
- /** Wallet identifier */
2800
- walletId: string;
2801
- /** Blockchain network */
2802
- chain: Chain;
2803
- /** Token balances */
2804
- balances: {
2805
- token: string;
2806
- amount: string;
2807
- }[];
2808
- }
2809
- /**
2810
- * Adapter interface for Circle API calls.
2811
- * Allows swapping between simulation and live implementations.
2812
- */
2813
- interface CircleApiAdapter {
2814
- createWalletSet(name: string, custodyType: string): Promise<{
2815
- id: string;
2816
- }>;
2817
- createWallet(walletSetId: string, chain: Chain, custodyType: string): Promise<{
2818
- id: string;
2819
- address: string;
2820
- }>;
2821
- getWallet(walletId: string): Promise<{
2822
- id: string;
2823
- address: string;
2824
- chain: Chain;
2825
- state: string;
2826
- } | null>;
2827
- listWallets(walletSetId: string): Promise<{
2828
- id: string;
2829
- address: string;
2830
- chain: Chain;
2831
- state: string;
2832
- }[]>;
2833
- transfer(params: {
2834
- walletId: string;
2835
- destinationAddress: string;
2836
- amount: string;
2837
- chain: Chain;
2838
- token: string;
2839
- }): Promise<{
2840
- transferId: string;
2841
- transactionHash: string;
2842
- }>;
2843
- getBalance(walletId: string): Promise<{
2844
- balances: {
2845
- token: string;
2846
- amount: string;
2847
- }[];
2848
- }>;
2849
- }
2850
- /** Minimal interface for the Kontext client used by CircleWalletManager */
2851
- interface KontextLike$2 {
2852
- log(input: {
2853
- type: string;
2854
- description: string;
2855
- agentId: string;
2856
- metadata?: Record<string, unknown>;
2857
- }): Promise<ActionLog>;
2858
- logTransaction(input: LogTransactionInput): Promise<ActionLog>;
2859
- getTrustScore(agentId: string): Promise<{
2860
- score: number;
2861
- }>;
2862
- checkUsdcCompliance(tx: LogTransactionInput): {
2863
- compliant: boolean;
2864
- checks: ComplianceCheckResult[];
2865
- riskLevel: AnomalySeverity;
2866
- recommendations: string[];
2867
- };
2868
- }
2869
- /**
2870
- * Manages Circle Programmable Wallets with integrated Kontext compliance
2871
- * and audit logging.
2872
- *
2873
- * All wallet operations are automatically logged through Kontext's rolling
2874
- * SHA-256 digest chain. Transfers are wrapped with compliance checks that
2875
- * must pass before execution.
2876
- *
2877
- * @example
2878
- * ```typescript
2879
- * import { Kontext } from 'kontext-sdk';
2880
- * import { CircleWalletManager } from 'kontext-sdk';
2881
- *
2882
- * const kontext = Kontext.init({ projectId: 'my-project', environment: 'production' });
2883
- * const wallets = new CircleWalletManager(kontext, 'circle-api-key');
2884
- *
2885
- * const walletSet = await wallets.createWalletSet('Operations');
2886
- * const wallet = await wallets.createWallet(walletSet.id, { chain: 'base' });
2887
- *
2888
- * const result = await wallets.transferWithCompliance({
2889
- * walletId: wallet.id,
2890
- * destinationAddress: '0x...',
2891
- * amount: '100',
2892
- * agent: 'payment-agent',
2893
- * });
2894
- * ```
2895
- */
2896
- declare class CircleWalletManager {
2897
- private readonly kontext;
2898
- private readonly adapter;
2899
- private readonly options;
2900
- private readonly isLiveMode;
2901
- private walletSets;
2902
- private wallets;
2903
- private walletSetWallets;
2904
- private auditTrail;
2905
- /**
2906
- * Create a new CircleWalletManager.
2907
- *
2908
- * @param kontextClient - Initialized Kontext SDK client
2909
- * @param circleApiKey - Circle API key (optional; omit for simulation mode)
2910
- * @param options - Configuration options
2911
- */
2912
- constructor(kontextClient: KontextLike$2, circleApiKey?: string, options?: CircleWalletOptions);
2913
- /**
2914
- * Create a new wallet set (a logical group of wallets).
2915
- *
2916
- * @param name - Human-readable name for the wallet set
2917
- * @param metadata - Optional metadata key-value pairs
2918
- * @returns The created WalletSet
2919
- */
2920
- createWalletSet(name: string, metadata?: Record<string, string>): Promise<WalletSet>;
2921
- /**
2922
- * Create a new wallet within a wallet set.
2923
- *
2924
- * @param walletSetId - Parent wallet set ID
2925
- * @param options - Wallet creation options
2926
- * @returns The created CircleWallet
2927
- */
2928
- createWallet(walletSetId: string, options: CreateWalletOptions): Promise<CircleWallet>;
2929
- /**
2930
- * Get a wallet by its ID.
2931
- *
2932
- * @param walletId - Wallet identifier
2933
- * @returns The CircleWallet, or throws if not found
2934
- */
2935
- getWallet(walletId: string): Promise<CircleWallet>;
2936
- /**
2937
- * List all wallets in a wallet set.
2938
- *
2939
- * @param walletSetId - Wallet set identifier
2940
- * @returns Array of CircleWallet records
2941
- */
2942
- listWallets(walletSetId: string): Promise<CircleWallet[]>;
2943
- /**
2944
- * Execute a USDC/EURC transfer with integrated compliance checks.
2945
- *
2946
- * The transfer flow:
2947
- * 1. Validate the source wallet exists and is live
2948
- * 2. Run Kontext compliance checks on the transaction
2949
- * 3. Get the agent's trust score
2950
- * 4. If compliance passes, execute the transfer via Circle
2951
- * 5. Log the entire operation through Kontext's audit system
2952
- *
2953
- * @param input - Transfer details
2954
- * @returns CompliantTransferResult with status and audit trail
2955
- */
2956
- transferWithCompliance(input: CompliantTransferInput): Promise<CompliantTransferResult>;
2957
- /**
2958
- * Get the token balances for a wallet.
2959
- *
2960
- * @param walletId - Wallet identifier
2961
- * @param chain - Optional chain override
2962
- * @returns WalletBalance with token amounts
2963
- */
2964
- getBalance(walletId: string, chain?: Chain): Promise<WalletBalance>;
2965
- /**
2966
- * Get the Kontext audit trail for a specific wallet.
2967
- *
2968
- * @param walletId - Wallet identifier
2969
- * @returns Array of ActionLog entries related to this wallet
2970
- */
2971
- getWalletAuditTrail(walletId: string): Promise<ActionLog[]>;
2972
- /**
2973
- * Run Kontext compliance checks on a transfer.
2974
- */
2975
- private runComplianceCheck;
2976
- /**
2977
- * Log an operation through the Kontext client.
2978
- */
2979
- private logOperation;
2980
- }
2981
-
2982
- /** Input for screening a transaction */
2983
- interface ScreenTransactionInput {
2984
- /** Sender address */
2985
- from: string;
2986
- /** Recipient address */
2987
- to: string;
2988
- /** Transfer amount */
2989
- amount: string;
2990
- /** Blockchain network */
2991
- chain: Chain;
2992
- /** Token being transferred */
2993
- token?: string;
2994
- }
2995
- /** Result of dual screening (Circle + Kontext) */
2996
- interface DualScreenResult {
2997
- /** Circle's screening result */
2998
- circleScreening: {
2999
- /** Whether the transaction is approved by Circle */
3000
- approved: boolean;
3001
- /** Risk level from Circle's screening */
3002
- riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'SEVERE';
3003
- /** Flags raised by Circle's screening */
3004
- flags: string[];
3005
- };
3006
- /** Kontext's screening result */
3007
- kontextScreening: {
3008
- /** Trust score (0-100) */
3009
- trustScore: number;
3010
- /** Whether anomaly was detected */
3011
- anomalyDetected: boolean;
3012
- /** Whether compliance checks passed */
3013
- complianceApproved: boolean;
3014
- /** Flags raised by Kontext screening */
3015
- flags: string[];
3016
- };
3017
- /** Combined decision from both systems */
3018
- combinedDecision: 'APPROVE' | 'REVIEW' | 'BLOCK';
3019
- /** Kontext audit log ID */
3020
- auditLogId: string;
3021
- }
3022
- /** Result of screening a single address */
3023
- interface AddressScreenResult {
3024
- /** The screened address */
3025
- address: string;
3026
- /** Blockchain network */
3027
- chain: Chain;
3028
- /** Whether the address is sanctioned */
3029
- sanctioned: boolean;
3030
- /** Risk level */
3031
- riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'SEVERE';
3032
- /** Flags raised */
3033
- flags: string[];
3034
- /** Screening timestamp */
3035
- screenedAt: string;
3036
- }
3037
- /** Input for comprehensive risk assessment */
3038
- interface RiskAssessmentInput {
3039
- /** Address to assess */
3040
- address: string;
3041
- /** Blockchain network */
3042
- chain: Chain;
3043
- /** Agent ID for trust scoring */
3044
- agentId?: string;
3045
- /** Transaction amount for contextual assessment */
3046
- amount?: string;
3047
- /** Token for contextual assessment */
3048
- token?: string;
3049
- }
3050
- /** Comprehensive risk assessment result */
3051
- interface ComprehensiveRiskResult {
3052
- /** Overall risk level */
3053
- overallRisk: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
3054
- /** Circle-derived risk score (0-100) */
3055
- circleRiskScore: number;
3056
- /** Kontext trust score (0-100) */
3057
- kontextTrustScore: number;
3058
- /** Combined weighted score (0-100, higher = riskier) */
3059
- combinedScore: number;
3060
- /** Action recommendation */
3061
- recommendation: 'PROCEED' | 'MANUAL_REVIEW' | 'BLOCK';
3062
- /** Individual risk factors */
3063
- factors: ComprehensiveRiskFactor[];
3064
- /** Kontext audit log ID */
3065
- auditLogId: string;
3066
- }
3067
- /** Risk factor in comprehensive assessment */
3068
- interface ComprehensiveRiskFactor {
3069
- /** Factor name */
3070
- name: string;
3071
- /** Risk score contribution (0-100) */
3072
- score: number;
3073
- /** Human-readable description */
3074
- description: string;
3075
- }
3076
- /**
3077
- * Adapter interface for Circle's compliance screening API.
3078
- */
3079
- interface CircleComplianceAdapter {
3080
- screenTransaction(input: ScreenTransactionInput): Promise<{
3081
- approved: boolean;
3082
- riskLevel: string;
3083
- flags: string[];
3084
- }>;
3085
- screenAddress(address: string, chain: Chain): Promise<{
3086
- sanctioned: boolean;
3087
- riskLevel: string;
3088
- flags: string[];
3089
- }>;
3090
- }
3091
- /** Minimal interface for the Kontext client used by CircleComplianceEngine */
3092
- interface KontextLike$1 {
3093
- log(input: {
3094
- type: string;
3095
- description: string;
3096
- agentId: string;
3097
- metadata?: Record<string, unknown>;
3098
- }): Promise<ActionLog>;
3099
- getTrustScore(agentId: string): Promise<{
3100
- score: number;
3101
- }>;
3102
- checkUsdcCompliance(tx: LogTransactionInput): {
3103
- compliant: boolean;
3104
- checks: ComplianceCheckResult[];
3105
- riskLevel: AnomalySeverity;
3106
- recommendations: string[];
3107
- };
3108
- }
3109
- /**
3110
- * Dual-layer compliance engine combining Circle's transaction screening
3111
- * with Kontext's trust scoring and anomaly detection.
3112
- *
3113
- * Every screening operation is logged through Kontext's tamper-evident
3114
- * audit system for regulatory compliance.
3115
- *
3116
- * @example
3117
- * ```typescript
3118
- * const kontext = Kontext.init({ projectId: 'my-project', environment: 'production' });
3119
- * const compliance = new CircleComplianceEngine(kontext);
3120
- *
3121
- * const result = await compliance.screenTransaction({
3122
- * from: '0xSender...',
3123
- * to: '0xRecipient...',
3124
- * amount: '5000',
3125
- * chain: 'base',
3126
- * });
3127
- *
3128
- * if (result.combinedDecision === 'BLOCK') {
3129
- * console.log('Transaction blocked');
3130
- * }
3131
- * ```
3132
- */
3133
- declare class CircleComplianceEngine {
3134
- private readonly kontext;
3135
- private readonly adapter;
3136
- private readonly isLiveMode;
3137
- /**
3138
- * Create a new CircleComplianceEngine.
3139
- *
3140
- * @param kontextClient - Initialized Kontext SDK client
3141
- * @param circleApiKey - Circle API key (optional; omit for simulation mode)
3142
- */
3143
- constructor(kontextClient: KontextLike$1, circleApiKey?: string);
3144
- /**
3145
- * Screen a transaction through both Circle and Kontext compliance systems.
3146
- *
3147
- * @param input - Transaction details to screen
3148
- * @returns DualScreenResult with combined decision
3149
- */
3150
- screenTransaction(input: ScreenTransactionInput): Promise<DualScreenResult>;
3151
- /**
3152
- * Screen an address for sanctions and risk.
3153
- *
3154
- * @param address - On-chain address to screen
3155
- * @param chain - Blockchain network
3156
- * @returns AddressScreenResult with risk assessment
3157
- */
3158
- screenAddress(address: string, chain: Chain): Promise<AddressScreenResult>;
3159
- /**
3160
- * Get a comprehensive risk assessment combining Circle screening with
3161
- * Kontext trust scoring.
3162
- *
3163
- * @param input - Assessment input
3164
- * @returns ComprehensiveRiskResult with combined scoring
3165
- */
3166
- getComprehensiveRisk(input: RiskAssessmentInput): Promise<ComprehensiveRiskResult>;
3167
- /**
3168
- * Run Kontext-side screening using USDC compliance checks and trust scoring.
3169
- */
3170
- private runKontextScreening;
3171
- /**
3172
- * Determine the combined decision based on both screening results.
3173
- */
3174
- private determineCombinedDecision;
3175
- /**
3176
- * Convert a risk level string to a numeric score.
3177
- */
3178
- private riskLevelToScore;
3179
- }
3180
-
3181
- /** Gas sponsorship eligibility result */
3182
- interface GasEligibility {
3183
- /** Whether the wallet is eligible for sponsored gas */
3184
- eligible: boolean;
3185
- /** Maximum sponsored amount in native token */
3186
- maxSponsoredAmount: string;
3187
- /** Supported operations */
3188
- supportedOperations: string[];
3189
- /** Remaining daily quota */
3190
- remainingDailyQuota: string;
3191
- /** Reason if not eligible */
3192
- reason?: string;
3193
- }
3194
- /** Input for gas estimation */
3195
- interface GasEstimateInput {
3196
- /** Source wallet ID */
3197
- walletId: string;
3198
- /** Destination address */
3199
- destinationAddress: string;
3200
- /** Transfer amount */
3201
- amount: string;
3202
- /** Blockchain network */
3203
- chain: Chain;
3204
- /** Token being transferred */
3205
- token?: string;
3206
- }
3207
- /** Gas estimate result */
3208
- interface GasEstimate {
3209
- /** Estimated gas cost in native token */
3210
- estimatedGas: string;
3211
- /** Whether this gas would be sponsored */
3212
- sponsored: boolean;
3213
- /** Amount the user would pay (zero if fully sponsored) */
3214
- userCost: string;
3215
- /** Amount Circle would sponsor */
3216
- sponsoredAmount: string;
3217
- /** Chain the estimate is for */
3218
- chain: Chain;
3219
- /** Native token used for gas */
3220
- nativeToken: string;
3221
- }
3222
- /** Input for logging a gas sponsorship event */
3223
- interface GasSponsorshipLog {
3224
- /** Wallet ID that received sponsorship */
3225
- walletId: string;
3226
- /** Transaction hash of the sponsored transaction */
3227
- transactionHash: string;
3228
- /** Amount of gas sponsored */
3229
- sponsoredGasAmount: string;
3230
- /** Chain the sponsorship occurred on */
3231
- chain: Chain;
3232
- /** Agent that initiated the transaction */
3233
- agent?: string;
3234
- /** Additional metadata */
3235
- metadata?: Record<string, unknown>;
3236
- }
3237
- /**
3238
- * Adapter interface for Circle Gas Station API.
3239
- */
3240
- interface GasStationAdapter {
3241
- checkEligibility(walletId: string, chain: Chain): Promise<GasEligibility>;
3242
- estimateGas(input: GasEstimateInput): Promise<GasEstimate>;
3243
- }
3244
- /** Minimal interface for the Kontext client used by GasStationManager */
3245
- interface KontextLike {
3246
- log(input: {
3247
- type: string;
3248
- description: string;
3249
- agentId: string;
3250
- metadata?: Record<string, unknown>;
3251
- }): Promise<ActionLog>;
3252
- }
3253
- /**
3254
- * Manages Circle Gas Station (sponsored gas) with integrated Kontext audit
3255
- * logging for compliance tracking.
3256
- *
3257
- * Gas sponsorship events are logged through Kontext's tamper-evident audit
3258
- * system to maintain a clear record of subsidized transactions.
3259
- *
3260
- * @example
3261
- * ```typescript
3262
- * const kontext = Kontext.init({ projectId: 'my-project', environment: 'production' });
3263
- * const gasStation = new GasStationManager(kontext);
3264
- *
3265
- * const eligibility = await gasStation.checkEligibility('wallet-123', 'base');
3266
- * if (eligibility.eligible) {
3267
- * const estimate = await gasStation.estimateGas({
3268
- * walletId: 'wallet-123',
3269
- * destinationAddress: '0x...',
3270
- * amount: '100',
3271
- * chain: 'base',
3272
- * });
3273
- * console.log(`Gas sponsored: ${estimate.sponsored}`);
3274
- * }
3275
- * ```
3276
- */
3277
- declare class GasStationManager {
3278
- private readonly kontext;
3279
- private readonly adapter;
3280
- private readonly isLiveMode;
3281
- /**
3282
- * Create a new GasStationManager.
3283
- *
3284
- * @param kontextClient - Initialized Kontext SDK client
3285
- * @param circleApiKey - Circle API key (optional; omit for simulation mode)
3286
- */
3287
- constructor(kontextClient: KontextLike, circleApiKey?: string);
3288
- /**
3289
- * Check if a wallet is eligible for gas sponsorship on a given chain.
3290
- *
3291
- * @param walletId - Wallet identifier
3292
- * @param chain - Blockchain network
3293
- * @returns GasEligibility with details
3294
- */
3295
- checkEligibility(walletId: string, chain: Chain): Promise<GasEligibility>;
3296
- /**
3297
- * Estimate gas cost for a transfer and determine sponsorship.
3298
- *
3299
- * @param input - Transfer details for estimation
3300
- * @returns GasEstimate with sponsorship information
3301
- */
3302
- estimateGas(input: GasEstimateInput): Promise<GasEstimate>;
3303
- /**
3304
- * Log a gas sponsorship event for audit purposes.
3305
- *
3306
- * Call this after a sponsored transaction has been confirmed on-chain
3307
- * to record the sponsorship in Kontext's audit trail.
3308
- *
3309
- * @param input - Sponsorship event details
3310
- * @returns The created ActionLog entry
3311
- */
3312
- logGasSponsorship(input: GasSponsorshipLog): Promise<ActionLog>;
3313
- /**
3314
- * Get the list of chains eligible for gas sponsorship.
3315
- *
3316
- * @returns Array of supported chains
3317
- */
3318
- static getEligibleChains(): Chain[];
3319
- /**
3320
- * Get the native gas token for a chain.
3321
- *
3322
- * @param chain - Blockchain network
3323
- * @returns Native token symbol
3324
- */
3325
- static getNativeToken(chain: Chain): string;
3326
- }
3327
-
3328
- /** Supported webhook event types */
3329
- type WebhookEventType = 'anomaly.detected' | 'task.confirmed' | 'task.failed' | 'trust.score_changed' | 'approval.required' | 'approval.decided';
3330
- /** Webhook registration configuration */
3331
- interface WebhookConfig {
3332
- /** Unique identifier for this webhook */
3333
- id: string;
3334
- /** Target URL to receive webhook POST requests */
3335
- url: string;
3336
- /** Event types to listen for */
3337
- events: WebhookEventType[];
3338
- /** Optional secret for HMAC signature verification */
3339
- secret?: string;
3340
- /** Whether this webhook is active */
3341
- active: boolean;
3342
- /** When this webhook was registered */
3343
- createdAt: string;
3344
- /** Optional metadata */
3345
- metadata?: Record<string, unknown>;
3346
- }
3347
- /** Input for registering a new webhook */
3348
- interface RegisterWebhookInput {
3349
- /** Target URL */
3350
- url: string;
3351
- /** Event types to listen for */
3352
- events: WebhookEventType[];
3353
- /** Optional secret for payload signing */
3354
- secret?: string;
3355
- /** Optional metadata */
3356
- metadata?: Record<string, unknown>;
3357
- }
3358
- /** Webhook delivery payload */
3359
- interface WebhookPayload {
3360
- /** Unique delivery ID */
3361
- id: string;
3362
- /** Event type */
3363
- event: WebhookEventType;
3364
- /** Timestamp of the event */
3365
- timestamp: string;
3366
- /** Event-specific data */
3367
- data: Record<string, unknown>;
3368
- }
3369
- /** Result of a webhook delivery attempt */
3370
- interface WebhookDeliveryResult {
3371
- /** Webhook ID */
3372
- webhookId: string;
3373
- /** Delivery payload ID */
3374
- payloadId: string;
3375
- /** Whether delivery succeeded */
3376
- success: boolean;
3377
- /** HTTP status code (if applicable) */
3378
- statusCode: number | null;
3379
- /** Number of attempts made */
3380
- attempts: number;
3381
- /** Error message if failed */
3382
- error: string | null;
3383
- /** Timestamp of last attempt */
3384
- lastAttemptAt: string;
3385
- }
3386
- /** Retry configuration */
3387
- interface WebhookRetryConfig {
3388
- /** Maximum number of retry attempts */
3389
- maxRetries: number;
3390
- /** Base delay in milliseconds for exponential backoff */
3391
- baseDelayMs: number;
3392
- /** Maximum delay in milliseconds */
3393
- maxDelayMs: number;
3394
- }
3395
- /**
3396
- * WebhookManager handles registration and delivery of webhook notifications
3397
- * for SDK events including anomaly detection, task confirmation, and trust
3398
- * score changes.
3399
- *
3400
- * Features:
3401
- * - Register multiple webhook URLs with event type filtering
3402
- * - Automatic retry with exponential backoff on delivery failure
3403
- * - Delivery result tracking
3404
- * - Enable/disable individual webhooks
3405
- *
3406
- * @example
3407
- * ```typescript
3408
- * const manager = new WebhookManager();
3409
- *
3410
- * manager.register({
3411
- * url: 'https://example.com/webhooks/kontext',
3412
- * events: ['anomaly.detected', 'task.confirmed'],
3413
- * });
3414
- *
3415
- * // Webhooks fire automatically when events occur
3416
- * await manager.notifyAnomalyDetected(anomalyEvent);
3417
- * ```
3418
- */
3419
- declare class WebhookManager {
3420
- private webhooks;
3421
- private deliveryResults;
3422
- private retryConfig;
3423
- private fetchFn;
3424
- constructor(retryConfig?: Partial<WebhookRetryConfig>, fetchFn?: typeof fetch);
3425
- /**
3426
- * Register a new webhook endpoint.
3427
- *
3428
- * @param input - Webhook configuration
3429
- * @returns The created WebhookConfig
3430
- */
3431
- register(input: RegisterWebhookInput): WebhookConfig;
3432
- /**
3433
- * Unregister a webhook by ID.
3434
- *
3435
- * @param webhookId - The webhook to remove
3436
- * @returns Whether the webhook was found and removed
3437
- */
3438
- unregister(webhookId: string): boolean;
3439
- /**
3440
- * Enable or disable a webhook.
3441
- *
3442
- * @param webhookId - The webhook to update
3443
- * @param active - Whether to enable or disable
3444
- * @returns The updated WebhookConfig, or undefined if not found
3445
- */
3446
- setActive(webhookId: string, active: boolean): WebhookConfig | undefined;
3447
- /**
3448
- * Get all registered webhooks.
3449
- * Secrets are redacted to prevent accidental exposure in logs or API responses.
3450
- */
3451
- getWebhooks(): WebhookConfig[];
3452
- /**
3453
- * Get a specific webhook by ID.
3454
- * The secret is redacted to prevent accidental exposure in logs or API responses.
3455
- */
3456
- getWebhook(webhookId: string): WebhookConfig | undefined;
3457
- /**
3458
- * Get delivery results for a specific webhook or all webhooks.
3459
- */
3460
- getDeliveryResults(webhookId?: string): WebhookDeliveryResult[];
3461
- /**
3462
- * Notify all subscribed webhooks of an anomaly detection event.
3463
- *
3464
- * @param anomaly - The detected anomaly event
3465
- * @returns Array of delivery results
3466
- */
3467
- notifyAnomalyDetected(anomaly: AnomalyEvent): Promise<WebhookDeliveryResult[]>;
3468
- /**
3469
- * Notify all subscribed webhooks of a task confirmation.
3470
- *
3471
- * @param task - The confirmed task
3472
- * @returns Array of delivery results
3473
- */
3474
- notifyTaskConfirmed(task: Task): Promise<WebhookDeliveryResult[]>;
3475
- /**
3476
- * Notify all subscribed webhooks of a task failure.
3477
- *
3478
- * @param task - The failed task
3479
- * @returns Array of delivery results
3480
- */
3481
- notifyTaskFailed(task: Task): Promise<WebhookDeliveryResult[]>;
3482
- /**
3483
- * Notify all subscribed webhooks of a trust score change.
3484
- *
3485
- * @param trustScore - The new trust score
3486
- * @param previousScore - The previous score value (if known)
3487
- * @returns Array of delivery results
3488
- */
3489
- notifyTrustScoreChanged(trustScore: TrustScore, previousScore?: number): Promise<WebhookDeliveryResult[]>;
3490
- /**
3491
- * Notify all subscribed webhooks that an approval is required.
3492
- *
3493
- * @param request - The approval request that was created
3494
- * @returns Array of delivery results
3495
- */
3496
- notifyApprovalRequired(request: ApprovalRequest): Promise<WebhookDeliveryResult[]>;
3497
- /**
3498
- * Notify all subscribed webhooks that an approval decision was made.
3499
- *
3500
- * @param request - The approval request with the decision
3501
- * @returns Array of delivery results
3502
- */
3503
- notifyApprovalDecided(request: ApprovalRequest): Promise<WebhookDeliveryResult[]>;
3504
- private deliver;
3505
- private deliverToWebhook;
3506
- private computeSignature;
3507
- private sleep;
3508
- /**
3509
- * Verify a webhook signature using constant-time comparison to prevent
3510
- * timing attacks. Use this in your webhook handler to validate incoming
3511
- * payloads from Kontext.
3512
- *
3513
- * @param payload - The raw JSON payload body (string)
3514
- * @param signature - The signature from the X-Kontext-Signature header
3515
- * @param secret - The webhook secret used during registration
3516
- * @returns Whether the signature is valid
3517
- *
3518
- * @example
3519
- * ```typescript
3520
- * const isValid = WebhookManager.verifySignature(
3521
- * req.body, // raw JSON string
3522
- * req.headers['x-kontext-signature'],
3523
- * 'my-webhook-secret',
3524
- * );
3525
- * if (!isValid) return res.status(401).send('Invalid signature');
3526
- * ```
3527
- */
3528
- static verifySignature(payload: string, signature: string, secret: string): boolean;
3529
- }
3530
-
3531
- /** AI operation types recognized by the Vercel AI SDK middleware. */
3532
- type AIOperationType = 'generate' | 'stream' | 'object' | 'embed' | 'embedMany';
3533
- /**
3534
- * Configuration options for the Kontext Vercel AI SDK middleware.
3535
- *
3536
- * Controls which operations are logged, how tool calls are handled,
3537
- * and whether financial compliance checks are triggered.
3538
- */
3539
- interface KontextAIOptions {
3540
- /** Agent identifier for audit logs. Defaults to `'vercel-ai'`. */
3541
- agentId?: string;
3542
- /**
3543
- * Tool names that involve financial transactions.
3544
- * When a tool call matches one of these names, Kontext will automatically
3545
- * log a `LogTransactionInput` with the extracted amount, triggering
3546
- * compliance checks and anomaly detection.
3547
- */
3548
- financialTools?: string[];
3549
- /**
3550
- * Whether to include tool call arguments in the audit log.
3551
- * Defaults to `false` for privacy. Set to `true` for full traceability.
3552
- */
3553
- logToolArgs?: boolean;
3554
- /**
3555
- * Default currency for financial tool calls.
3556
- * Defaults to `'USDC'`.
3557
- */
3558
- defaultCurrency?: string;
3559
- /**
3560
- * Trust score threshold (0-100). If the agent's trust score is below
3561
- * this threshold, tool calls will be blocked and `onBlocked` will fire.
3562
- */
3563
- trustThreshold?: number;
3564
- /**
3565
- * Callback invoked when a tool call is blocked due to trust threshold
3566
- * or other compliance rules.
3567
- */
3568
- onBlocked?: (toolCall: BlockedToolCall, reason: string) => void;
3569
- }
3570
- /**
3571
- * A tool call that was blocked by the Kontext middleware.
3572
- */
3573
- interface BlockedToolCall {
3574
- /** The name of the tool that was blocked. */
3575
- toolName: string;
3576
- /** The arguments that were passed to the tool. */
3577
- args: unknown;
3578
- }
3579
- /**
3580
- * Input options for the one-line `createKontextAI` setup function.
3581
- * Combines Kontext SDK configuration with AI middleware options.
3582
- */
3583
- interface CreateKontextAIInput {
3584
- /** Kontext project identifier. */
3585
- projectId: string;
3586
- /** Deployment environment. */
3587
- environment?: Environment;
3588
- /** Optional API key for cloud mode. */
3589
- apiKey?: string;
3590
- /** Enable debug logging. */
3591
- debug?: boolean;
3592
- /** Agent identifier for audit logs. */
3593
- agentId?: string;
3594
- /** Tool names that involve financial transactions. */
3595
- financialTools?: string[];
3596
- /** Whether to log tool arguments. */
3597
- logToolArgs?: boolean;
3598
- /** Default currency for financial tool calls. */
3599
- defaultCurrency?: string;
3600
- /** Trust score threshold for blocking tool calls. */
3601
- trustThreshold?: number;
3602
- /** Callback when a tool call is blocked. */
3603
- onBlocked?: (toolCall: BlockedToolCall, reason: string) => void;
3604
- }
3605
- /**
3606
- * Return type from `createKontextAI`.
3607
- */
3608
- interface CreateKontextAIResult {
3609
- /** The wrapped language model with Kontext middleware applied. */
3610
- model: unknown;
3611
- /** The Kontext client instance for direct access to audit, trust, and compliance APIs. */
3612
- kontext: Kontext;
3613
- }
3614
- /**
3615
- * Options for the `withKontext` Next.js route handler wrapper.
3616
- */
3617
- interface WithKontextOptions {
3618
- /** Kontext project identifier. */
3619
- projectId?: string;
3620
- /** Deployment environment. */
3621
- environment?: Environment;
3622
- /** Optional API key for cloud mode. */
3623
- apiKey?: string;
3624
- /** Agent identifier for audit logs. */
3625
- agentId?: string;
3626
- /** Enable debug logging. */
3627
- debug?: boolean;
3628
- }
3629
- /**
3630
- * Context object passed to route handlers wrapped with `withKontext`.
3631
- * Provides a pre-configured Kontext client and a helper to wrap AI models.
3632
- */
3633
- interface KontextAIContext {
3634
- /** The Kontext client instance. */
3635
- kontext: Kontext;
3636
- /**
3637
- * Wrap an AI model with Kontext middleware for automatic audit logging.
3638
- *
3639
- * @param model - A Vercel AI SDK language model
3640
- * @param options - Additional middleware options
3641
- * @returns The wrapped model
3642
- */
3643
- wrapModel: (model: unknown, options?: KontextAIOptions) => unknown;
3644
- /** Unique request identifier for correlating logs. */
3645
- requestId: string;
3646
- }
3647
- /**
3648
- * Creates a Kontext middleware object for the Vercel AI SDK.
3649
- *
3650
- * This middleware intercepts every `generateText()`, `streamText()`, and
3651
- * `generateObject()` call and automatically logs each operation, tool
3652
- * invocation, and result into the Kontext tamper-evident digest chain.
3653
- *
3654
- * The middleware conforms to the Vercel AI SDK middleware interface:
3655
- * - `transformParams` — Logs the AI request before execution
3656
- * - `wrapGenerate` — Wraps synchronous generation to log tool calls and results
3657
- * - `wrapStream` — Wraps streaming generation to log stream lifecycle events
3658
- *
3659
- * @param kontext - An initialized Kontext client instance
3660
- * @param options - Middleware configuration options
3661
- * @returns A Vercel AI SDK middleware object
3662
- *
3663
- * @example
3664
- * ```typescript
3665
- * import { Kontext } from 'kontext-sdk';
3666
- * import { experimental_wrapLanguageModel as wrapLanguageModel } from 'ai';
3667
- * import { openai } from '@ai-sdk/openai';
3668
- *
3669
- * const kontext = Kontext.init({ projectId: 'my-app', environment: 'production' });
3670
- *
3671
- * const model = wrapLanguageModel({
3672
- * model: openai('gpt-4o'),
3673
- * middleware: kontextMiddleware(kontext, {
3674
- * agentId: 'payment-agent',
3675
- * financialTools: ['transfer_usdc', 'send_payment'],
3676
- * }),
3677
- * });
3678
- *
3679
- * // Every generateText / streamText call is now automatically audited.
3680
- * ```
3681
- */
3682
- declare function kontextMiddleware(kontext: Kontext, options?: KontextAIOptions): {
3683
- transformParams: (ctx: {
3684
- params: Record<string, unknown>;
3685
- type: string;
3686
- }) => Promise<Record<string, unknown>>;
3687
- wrapGenerate: (ctx: {
3688
- doGenerate: () => Promise<Record<string, unknown>>;
3689
- params: Record<string, unknown>;
3690
- }) => Promise<Record<string, unknown>>;
3691
- wrapStream: (ctx: {
3692
- doStream: () => Promise<{
3693
- stream: ReadableStream;
3694
- [key: string]: unknown;
3695
- }>;
3696
- params: Record<string, unknown>;
3697
- }) => Promise<{
3698
- [key: string]: unknown;
3699
- stream: ReadableStream;
3700
- }>;
3701
- };
3702
- /**
3703
- * Wraps a Vercel AI SDK language model with Kontext middleware for
3704
- * automatic audit logging of all AI operations.
3705
- *
3706
- * This function applies the Kontext middleware using the Vercel AI SDK's
3707
- * `experimental_wrapLanguageModel` pattern. The returned model can be
3708
- * used directly with `generateText()`, `streamText()`, and `generateObject()`.
3709
- *
3710
- * @param model - A Vercel AI SDK language model (e.g., `openai('gpt-4o')`)
3711
- * @param kontext - An initialized Kontext client instance
3712
- * @param options - Middleware configuration options
3713
- * @returns A wrapped language model with Kontext audit logging
3714
- *
3715
- * @example
3716
- * ```typescript
3717
- * import { openai } from '@ai-sdk/openai';
3718
- * import { Kontext, kontextWrapModel } from 'kontext-sdk';
3719
- * import { generateText } from 'ai';
3720
- *
3721
- * const kontext = Kontext.init({ projectId: 'my-app', environment: 'production' });
3722
- * const model = kontextWrapModel(openai('gpt-4o'), kontext, {
3723
- * agentId: 'support-agent',
3724
- * financialTools: ['transfer_usdc'],
3725
- * });
3726
- *
3727
- * const result = await generateText({ model, prompt: 'Send 100 USDC to Alice' });
3728
- * // All operations automatically logged with SHA-256 digest chains
3729
- * ```
3730
- */
3731
- declare function kontextWrapModel(model: unknown, kontext: Kontext, options?: KontextAIOptions): unknown;
3732
- /**
3733
- * One-line Kontext + Vercel AI SDK setup.
3734
- *
3735
- * Creates a Kontext client and wraps a Vercel AI SDK language model in a
3736
- * single function call. The returned model automatically logs every AI
3737
- * operation with tamper-evident SHA-256 digest chains.
3738
- *
3739
- * @param model - A Vercel AI SDK language model (e.g., `openai('gpt-4o')`)
3740
- * @param input - Combined Kontext and AI middleware configuration
3741
- * @returns An object containing the wrapped model and the Kontext client
3742
- *
3743
- * @example
3744
- * ```typescript
3745
- * import { openai } from '@ai-sdk/openai';
3746
- * import { createKontextAI } from 'kontext-sdk';
3747
- * import { generateText } from 'ai';
3748
- *
3749
- * const { model, kontext } = createKontextAI(openai('gpt-4o'), {
3750
- * projectId: 'payment-app',
3751
- * agentId: 'payment-agent',
3752
- * financialTools: ['transfer_usdc', 'send_payment'],
3753
- * });
3754
- *
3755
- * const result = await generateText({ model, tools, prompt: 'Pay 50 USDC' });
3756
- * // All tool calls are automatically logged with digest chains.
3757
- *
3758
- * // Access the audit trail
3759
- * const chain = kontext.exportDigestChain();
3760
- * console.log('Terminal digest:', kontext.getTerminalDigest());
3761
- * ```
3762
- */
3763
- declare function createKontextAI(model: unknown, input: CreateKontextAIInput): CreateKontextAIResult;
3764
- /**
3765
- * Wraps a Next.js API route handler with Kontext audit logging.
3766
- *
3767
- * Every incoming request is logged with a unique request ID, and a
3768
- * pre-configured `KontextAIContext` is passed to the handler. The context
3769
- * provides a `wrapModel()` helper for wrapping AI models inside the handler.
3770
- *
3771
- * On completion, the request lifecycle (including duration and status code)
3772
- * is logged to the digest chain.
3773
- *
3774
- * @param handler - The route handler function
3775
- * @param options - Kontext configuration for the route
3776
- * @returns A standard Next.js route handler function
3777
- *
3778
- * @example
3779
- * ```typescript
3780
- * // app/api/chat/route.ts
3781
- * import { withKontext } from 'kontext-sdk';
3782
- * import { openai } from '@ai-sdk/openai';
3783
- * import { generateText } from 'ai';
3784
- *
3785
- * export const POST = withKontext(async (req, ctx) => {
3786
- * const { messages } = await req.json();
3787
- *
3788
- * const model = ctx.wrapModel(openai('gpt-4o'), {
3789
- * financialTools: ['transfer_usdc'],
3790
- * });
3791
- *
3792
- * const result = await generateText({ model, messages });
3793
- * return Response.json(result);
3794
- * }, {
3795
- * projectId: 'my-app',
3796
- * environment: 'production',
3797
- * });
3798
- * ```
3799
- */
3800
- declare function withKontext(handler: (req: Request, ctx: KontextAIContext) => Promise<Response>, options?: WithKontextOptions): (req: Request) => Promise<Response>;
3801
- /**
3802
- * Extract a numeric amount from tool call arguments.
3803
- *
3804
- * Searches for common field names (`amount`, `value`, `total`, `payment`,
3805
- * `transfer`) in the arguments object and returns the first valid number found.
3806
- *
3807
- * @param args - The tool call arguments (typically a JSON object)
3808
- * @returns The extracted numeric amount, or `null` if no amount was found
3809
- */
3810
- declare function extractAmount(args: unknown): number | null;
3811
-
3812
- /** CFTC account classification for segregated funds */
3813
- type CFTCAccountClass = 'futures' | 'cleared_swaps' | '30.7';
3814
- /** Digital asset classification per CFTC Letter 26-05 */
3815
- type DigitalAssetType = 'payment_stablecoin' | 'btc' | 'eth' | 'other_digital_asset';
3816
- /** Collateral valuation record for a digital asset held as customer margin */
3817
- interface CollateralValuation {
3818
- /** Unique valuation ID */
3819
- id: string;
3820
- /** ISO 8601 timestamp of the valuation */
3821
- timestamp: string;
3822
- /** CFTC account class (futures, cleared_swaps, 30.7) */
3823
- accountClass: CFTCAccountClass;
3824
- /** Type of digital asset */
3825
- assetType: DigitalAssetType;
3826
- /** Asset symbol (e.g., USDC, BTC, ETH) */
3827
- assetSymbol: string;
3828
- /** Quantity of asset held */
3829
- quantity: number;
3830
- /** Market value in USD */
3831
- marketValue: number;
3832
- /** Haircut percentage applied (0.0 - 1.0) */
3833
- haircutPercentage: number;
3834
- /** Absolute haircut value in USD */
3835
- haircutValue: number;
3836
- /** Net collateral value after haircut (marketValue - haircutValue) */
3837
- netValue: number;
3838
- /** DCO reference for the haircut schedule (optional) */
3839
- dcoReference?: string;
3840
- /** Valuation methodology */
3841
- valuationMethod: string;
3842
- /** Agent that performed the valuation */
3843
- agentId: string;
3844
- /** Additional metadata */
3845
- metadata?: Record<string, unknown>;
3846
- }
3847
- /** Daily segregation calculation per CFTC Reg 1.20 / 30.7 */
3848
- interface SegregationCalculation {
3849
- /** Unique calculation ID */
3850
- id: string;
3851
- /** ISO 8601 timestamp of the calculation */
3852
- timestamp: string;
3853
- /** CFTC account class */
3854
- accountClass: CFTCAccountClass;
3855
- /** Total customer funds on deposit */
3856
- totalCustomerFunds: number;
3857
- /** Required segregated amount */
3858
- requiredAmount: number;
3859
- /** Excess (positive) or deficit (negative) */
3860
- excessDeficit: number;
3861
- /** Breakdown of digital assets in the segregation calculation */
3862
- digitalAssetBreakdown: Array<{
3863
- assetType: DigitalAssetType;
3864
- assetSymbol: string;
3865
- quantity: number;
3866
- marketValue: number;
3867
- haircutValue: number;
3868
- netValue: number;
3869
- }>;
3870
- /** Residual interest amount */
3871
- residualInterest: number;
3872
- /** Agent that performed the calculation */
3873
- agentId: string;
3874
- /** Additional metadata */
3875
- metadata?: Record<string, unknown>;
3876
- }
3877
- /** Weekly digital asset report aggregating collateral positions */
3878
- interface DigitalAssetReport {
3879
- /** Unique report ID */
3880
- id: string;
3881
- /** Date the report was generated (ISO 8601 date string) */
3882
- reportDate: string;
3883
- /** Start of the reporting period (ISO 8601) */
3884
- reportPeriodStart: string;
3885
- /** End of the reporting period (ISO 8601) */
3886
- reportPeriodEnd: string;
3887
- /** CFTC account class */
3888
- accountClass: CFTCAccountClass;
3889
- /** Aggregated asset positions */
3890
- assets: Array<{
3891
- assetType: DigitalAssetType;
3892
- assetSymbol: string;
3893
- totalQuantity: number;
3894
- totalMarketValue: number;
3895
- totalHaircutValue: number;
3896
- totalNetValue: number;
3897
- }>;
3898
- /** Sum of all asset market values */
3899
- totalMarketValue: number;
3900
- /** Sum of all asset net values (after haircuts) */
3901
- totalNetValue: number;
3902
- /** ISO 8601 timestamp when the report was generated */
3903
- generatedAt: string;
3904
- }
3905
- /** Incident report for cybersecurity or operational events */
3906
- interface IncidentReport {
3907
- /** Unique incident ID */
3908
- id: string;
3909
- /** ISO 8601 timestamp of the incident */
3910
- timestamp: string;
3911
- /** Severity level */
3912
- severity: 'critical' | 'high' | 'medium' | 'low';
3913
- /** Type of incident */
3914
- incidentType: 'cybersecurity' | 'operational' | 'system_failure' | 'disruption';
3915
- /** Description of the incident */
3916
- description: string;
3917
- /** Systems affected by the incident */
3918
- affectedSystems: string[];
3919
- /** Number of customers affected (optional) */
3920
- affectedCustomerCount?: number;
3921
- /** Financial impact in USD (optional) */
3922
- financialImpact?: number;
3923
- /** Current resolution status */
3924
- resolutionStatus: 'open' | 'investigating' | 'resolved';
3925
- /** Agent that reported the incident */
3926
- agentId: string;
3927
- /** Additional metadata */
3928
- metadata?: Record<string, unknown>;
3929
- }
3930
- /** Configuration options for the CFTC compliance module */
3931
- interface CFTCComplianceConfig {
3932
- /** Minimum haircut for non-BTC/ETH, non-stablecoin digital assets (default 0.20) */
3933
- minimumNonBtcEthHaircut?: number;
3934
- /** Whether to enforce haircut validation on collateral logging (default true) */
3935
- enableHaircutValidation?: boolean;
3936
- /** Whether to enable weekly reporting features */
3937
- enableWeeklyReporting?: boolean;
3938
- /** Date from which to start generating reports */
3939
- reportingStartDate?: Date;
3940
- }
3941
- /** Result of a haircut validation check */
3942
- interface HaircutValidationResult {
3943
- /** Whether the haircut meets the minimum requirement */
3944
- valid: boolean;
3945
- /** The minimum required haircut for this asset type */
3946
- minimumRequired: number;
3947
- /** Human-readable explanation */
3948
- message: string;
3949
- }
3950
- /**
3951
- * CFTC compliance module for FCM digital asset margin requirements.
3952
- *
3953
- * Implements the record-keeping and reporting requirements introduced by
3954
- * CFTC Letter No. 26-05 (Feb 6, 2026), which permits FCMs to accept
3955
- * stablecoins and digital assets as customer margin collateral.
3956
- *
3957
- * @example
3958
- * ```typescript
3959
- * const cftc = new CFTCCompliance();
3960
- *
3961
- * // Log a collateral valuation
3962
- * const valuation = cftc.logCollateralValuation({
3963
- * accountClass: 'futures',
3964
- * assetType: 'payment_stablecoin',
3965
- * assetSymbol: 'USDC',
3966
- * quantity: 1_000_000,
3967
- * marketValue: 1_000_000,
3968
- * haircutPercentage: 0.02,
3969
- * haircutValue: 20_000,
3970
- * netValue: 980_000,
3971
- * valuationMethod: 'mark_to_market',
3972
- * agentId: 'margin-agent-1',
3973
- * });
3974
- *
3975
- * // Generate a weekly report
3976
- * const report = cftc.generateWeeklyDigitalAssetReport(
3977
- * 'futures',
3978
- * new Date('2026-02-01'),
3979
- * new Date('2026-02-07'),
3980
- * );
3981
- * ```
3982
- */
3983
- declare class CFTCCompliance {
3984
- private readonly config;
3985
- private collateralValuations;
3986
- private segregationCalculations;
3987
- private incidents;
3988
- constructor(config?: CFTCComplianceConfig);
3989
- /**
3990
- * Log a collateral valuation for a digital asset held as customer margin.
3991
- *
3992
- * Validates the haircut percentage against CFTC requirements when
3993
- * `enableHaircutValidation` is true (default).
3994
- *
3995
- * @param input - Collateral valuation data (id and timestamp are auto-generated if omitted)
3996
- * @returns The stored CollateralValuation record
3997
- * @throws Error if haircut validation fails for the given asset type
3998
- */
3999
- logCollateralValuation(input: Omit<CollateralValuation, 'id' | 'timestamp'> & {
4000
- id?: string;
4001
- timestamp?: string;
4002
- }): CollateralValuation;
4003
- /**
4004
- * Log a daily segregation calculation for a given account class.
4005
- *
4006
- * @param input - Segregation calculation data (id and timestamp are auto-generated if omitted)
4007
- * @returns The stored SegregationCalculation record
4008
- */
4009
- logSegregationCalculation(input: Omit<SegregationCalculation, 'id' | 'timestamp'> & {
4010
- id?: string;
4011
- timestamp?: string;
4012
- }): SegregationCalculation;
4013
- /**
4014
- * Log an incident (cybersecurity, operational, system failure, or disruption).
4015
- *
4016
- * @param input - Incident data (id and timestamp are auto-generated if omitted)
4017
- * @returns The stored IncidentReport record
4018
- */
4019
- logIncident(input: Omit<IncidentReport, 'id' | 'timestamp'> & {
4020
- id?: string;
4021
- timestamp?: string;
4022
- }): IncidentReport;
4023
- /**
4024
- * Generate a weekly digital asset report aggregating collateral valuations
4025
- * for a given account class and date range.
4026
- *
4027
- * @param accountClass - The CFTC account class to report on
4028
- * @param periodStart - Start of the reporting period
4029
- * @param periodEnd - End of the reporting period
4030
- * @returns DigitalAssetReport with aggregated positions
4031
- */
4032
- generateWeeklyDigitalAssetReport(accountClass: CFTCAccountClass, periodStart: Date, periodEnd: Date): DigitalAssetReport;
4033
- /**
4034
- * Get the most recent segregation calculation for a given account class
4035
- * and date.
4036
- *
4037
- * @param accountClass - The CFTC account class
4038
- * @param date - The date to retrieve the calculation for
4039
- * @returns The most recent SegregationCalculation for that day, or undefined
4040
- */
4041
- generateDailySegregationReport(accountClass: CFTCAccountClass, date: Date): SegregationCalculation | undefined;
4042
- /**
4043
- * Query collateral valuations with optional filters.
4044
- *
4045
- * @param filters - Optional filter criteria
4046
- * @returns Array of matching CollateralValuation records
4047
- */
4048
- getCollateralValuations(filters?: {
4049
- accountClass?: CFTCAccountClass;
4050
- assetType?: DigitalAssetType;
4051
- startDate?: Date;
4052
- endDate?: Date;
4053
- }): CollateralValuation[];
4054
- /**
4055
- * Query incident reports with optional filters.
4056
- *
4057
- * @param filters - Optional filter criteria
4058
- * @returns Array of matching IncidentReport records
4059
- */
4060
- getIncidents(filters?: {
4061
- severity?: IncidentReport['severity'];
4062
- status?: IncidentReport['resolutionStatus'];
4063
- startDate?: Date;
4064
- endDate?: Date;
4065
- }): IncidentReport[];
4066
- /**
4067
- * Query segregation calculations with optional filters.
4068
- *
4069
- * @param filters - Optional filter criteria
4070
- * @returns Array of matching SegregationCalculation records
4071
- */
4072
- getSegregationCalculations(filters?: {
4073
- accountClass?: CFTCAccountClass;
4074
- startDate?: Date;
4075
- endDate?: Date;
4076
- }): SegregationCalculation[];
4077
- /**
4078
- * Validate a haircut percentage against CFTC Letter 26-05 requirements.
4079
- *
4080
- * Rules:
4081
- * - Payment stablecoins: no minimum haircut required
4082
- * - BTC / ETH: no minimum (deferred to DCO haircut schedule)
4083
- * - Other digital assets: minimum 20% haircut required
4084
- *
4085
- * @param assetType - The digital asset type
4086
- * @param haircutPercentage - The proposed haircut (0.0 - 1.0)
4087
- * @returns HaircutValidationResult with validity, minimum, and message
4088
- */
4089
- validateHaircut(assetType: DigitalAssetType, haircutPercentage: number): HaircutValidationResult;
4090
- /**
4091
- * Export CFTC compliance data in JSON or CSV format.
4092
- *
4093
- * @param options - Export options including format, report type, and filters
4094
- * @returns Formatted string (JSON or CSV)
4095
- */
4096
- exportCFTCReport(options: {
4097
- format: 'json' | 'csv';
4098
- reportType: 'weekly_digital_assets' | 'daily_segregation' | 'incidents';
4099
- accountClass?: CFTCAccountClass;
4100
- startDate?: Date;
4101
- endDate?: Date;
4102
- }): string;
4103
- }
4104
-
4105
- /** Risk categories matching Circle Compliance Engine taxonomy */
4106
- type RiskCategory = 'SANCTIONS' | 'TERRORIST_FINANCING' | 'CSAM' | 'ILLICIT_BEHAVIOR' | 'GAMBLING' | 'FROZEN' | 'CUSTOM_BLOCKLIST' | 'PEP' | 'DARKNET' | 'RANSOMWARE' | 'MIXER' | 'SCAM' | 'STOLEN_FUNDS' | 'UNKNOWN';
4107
- /** Risk severity tiers (aligned with Circle's scoring) */
4108
- type RiskSeverity = 'BLOCKLIST' | 'SEVERE' | 'HIGH' | 'MEDIUM' | 'LOW' | 'NONE';
4109
- /** Actions a screening rule can trigger */
4110
- type ScreeningAction = 'DENY' | 'REVIEW' | 'FREEZE_WALLET' | 'ALERT' | 'ALLOW';
4111
- /** Direction of transaction flow */
4112
- type TransactionDirection = 'INBOUND' | 'OUTBOUND' | 'BOTH';
4113
- /** A single risk signal from a screening provider */
4114
- interface RiskSignal {
4115
- /** The provider that generated this signal */
4116
- provider: string;
4117
- /** Risk category */
4118
- category: RiskCategory;
4119
- /** Risk severity */
4120
- severity: RiskSeverity;
4121
- /** Numeric risk score (0-100) */
4122
- riskScore: number;
4123
- /** Actions recommended by this signal */
4124
- actions: ScreeningAction[];
4125
- /** Human-readable description of the risk */
4126
- description: string;
4127
- /** Optional entity name associated with the risk */
4128
- entityName?: string;
4129
- /** Optional entity type */
4130
- entityType?: string;
4131
- /** Whether this signal applies to inbound, outbound, or both */
4132
- direction: TransactionDirection;
4133
- /** Additional metadata from the provider */
4134
- metadata?: Record<string, unknown>;
4135
- }
4136
- /** Result from a single screening provider */
4137
- interface ProviderScreeningResult {
4138
- /** Provider name */
4139
- provider: string;
4140
- /** Whether the address was found in this provider's data */
4141
- matched: boolean;
4142
- /** Risk signals detected */
4143
- signals: RiskSignal[];
4144
- /** Whether the screening was successful (false if provider errored) */
4145
- success: boolean;
4146
- /** Error message if the provider failed */
4147
- error?: string;
4148
- /** Screening latency in milliseconds */
4149
- latencyMs: number;
4150
- /** Timestamp of the screening */
4151
- screenedAt: string;
4152
- }
4153
- /** Input for screening an address */
4154
- interface ScreenAddressInput {
4155
- /** The blockchain address to screen */
4156
- address: string;
4157
- /** Blockchain network */
4158
- chain: Chain;
4159
- /** Optional transaction amount for contextual risk */
4160
- amount?: string;
4161
- /** Optional counterparty address */
4162
- counterparty?: string;
4163
- /** Transaction direction */
4164
- direction?: TransactionDirection;
4165
- }
4166
- /** Input for screening a transaction */
4167
- interface ScreenTransactionProviderInput {
4168
- /** Sender address */
4169
- from: string;
4170
- /** Recipient address */
4171
- to: string;
4172
- /** Transfer amount */
4173
- amount: string;
4174
- /** Blockchain network */
4175
- chain: Chain;
4176
- /** Token being transferred */
4177
- token?: string;
4178
- }
4179
- /**
4180
- * Interface that all screening providers must implement.
4181
- *
4182
- * Providers are responsible for checking addresses/transactions against
4183
- * their data source and returning structured risk signals.
4184
- */
4185
- interface ScreeningProvider {
4186
- /** Unique provider name (e.g., 'chainalysis-free', 'opensanctions') */
4187
- readonly name: string;
4188
- /** Risk categories this provider can detect */
4189
- readonly supportedCategories: RiskCategory[];
4190
- /** Chains this provider supports (empty = all chains) */
4191
- readonly supportedChains: Chain[];
4192
- /**
4193
- * Screen a single address for risk.
4194
- * Returns provider-specific risk signals.
4195
- */
4196
- screenAddress(input: ScreenAddressInput): Promise<ProviderScreeningResult>;
4197
- /**
4198
- * Screen a transaction (both sender and recipient).
4199
- * Default implementation screens both addresses individually.
4200
- */
4201
- screenTransaction?(input: ScreenTransactionProviderInput): Promise<ProviderScreeningResult>;
4202
- /**
4203
- * Initialize the provider (e.g., fetch initial data, warm caches).
4204
- * Called once when added to the aggregator.
4205
- */
4206
- initialize?(): Promise<void>;
4207
- /**
4208
- * Check if the provider is healthy and able to screen.
4209
- */
4210
- isHealthy(): Promise<boolean>;
4211
- }
4212
- /** A blocklist or allowlist entry */
4213
- interface ListEntry {
4214
- /** The blockchain address */
4215
- address: string;
4216
- /** Which chains this entry applies to (empty = all) */
4217
- chains: Chain[];
4218
- /** Reason for listing */
4219
- reason: string;
4220
- /** Who added this entry */
4221
- addedBy: string;
4222
- /** When the entry was added */
4223
- addedAt: string;
4224
- /** Optional expiration date */
4225
- expiresAt?: string;
4226
- /** Optional metadata */
4227
- metadata?: Record<string, unknown>;
4228
- }
4229
- /** Blocklist manager configuration */
4230
- interface BlocklistConfig {
4231
- /** Path to persist blocklist data (optional) */
4232
- persistPath?: string;
4233
- /** Whether allowlist takes priority over blocklist */
4234
- allowlistPriority?: boolean;
4235
- /** Current plan tier — required for plan gate enforcement (Pro+) */
4236
- plan?: PlanTier;
4237
- }
4238
- /** Aggregated screening result combining all provider results */
4239
- interface UnifiedScreeningResult {
4240
- /** The screened address */
4241
- address: string;
4242
- /** Blockchain network */
4243
- chain: Chain;
4244
- /** Final aggregated decision */
4245
- decision: 'APPROVE' | 'REVIEW' | 'BLOCK';
4246
- /** Recommended actions (union of all provider actions) */
4247
- actions: ScreeningAction[];
4248
- /** Highest risk severity across all providers */
4249
- highestSeverity: RiskSeverity;
4250
- /** Aggregated risk score (0-100, weighted average across providers) */
4251
- aggregateRiskScore: number;
4252
- /** All risk categories detected across providers */
4253
- categories: RiskCategory[];
4254
- /** Individual provider results */
4255
- providerResults: ProviderScreeningResult[];
4256
- /** All risk signals from all providers */
4257
- allSignals: RiskSignal[];
4258
- /** Number of providers that were consulted */
4259
- providersConsulted: number;
4260
- /** Number of providers that succeeded */
4261
- providersSucceeded: number;
4262
- /** Total screening latency in milliseconds */
4263
- totalLatencyMs: number;
4264
- /** Screening timestamp */
4265
- screenedAt: string;
4266
- /** Whether the address is on the user's allowlist (overrides block) */
4267
- allowlisted: boolean;
4268
- /** Whether the address is on the user's blocklist */
4269
- blocklisted: boolean;
4270
- }
4271
- /** Configuration for the screening aggregator */
4272
- interface ScreeningAggregatorConfig {
4273
- /** Minimum providers that must succeed for a valid result (default: 1) */
4274
- minProviderSuccess?: number;
4275
- /** Timeout per provider in milliseconds (default: 5000) */
4276
- providerTimeoutMs?: number;
4277
- /** Whether to run providers in parallel (default: true) */
4278
- parallel?: boolean;
4279
- /** Risk score threshold for BLOCK decision (default: 80) */
4280
- blockThreshold?: number;
4281
- /** Risk score threshold for REVIEW decision (default: 40) */
4282
- reviewThreshold?: number;
4283
- /** Custom provider weights for aggregation (provider name -> weight 0-1) */
4284
- providerWeights?: Record<string, number>;
4285
- /** Blocklist configuration */
4286
- blocklist?: BlocklistConfig;
1944
+ /**
1945
+ * In-memory data store for the Kontext SDK.
1946
+ * Holds all action logs, transactions, tasks, and anomaly events.
1947
+ *
1948
+ * When a StorageAdapter is provided, call `flush()` to persist state
1949
+ * and `restore()` to reload from storage.
1950
+ */
1951
+ declare class KontextStore {
1952
+ private actions;
1953
+ private transactions;
1954
+ private tasks;
1955
+ private anomalies;
1956
+ private storageAdapter;
1957
+ private readonly maxEntries;
1958
+ constructor(maxEntries?: number);
1959
+ /**
1960
+ * Attach a storage adapter for persistence.
1961
+ *
1962
+ * @param adapter - The storage backend to use
1963
+ */
1964
+ setStorageAdapter(adapter: StorageAdapter): void;
1965
+ /**
1966
+ * Get the currently attached storage adapter (if any).
1967
+ */
1968
+ getStorageAdapter(): StorageAdapter | null;
1969
+ /**
1970
+ * Persist all current in-memory state to the attached storage adapter.
1971
+ * No-op if no adapter is attached.
1972
+ */
1973
+ flush(): Promise<void>;
1974
+ /**
1975
+ * Restore in-memory state from the attached storage adapter.
1976
+ * Merges loaded data with any existing in-memory data.
1977
+ * No-op if no adapter is attached.
1978
+ */
1979
+ restore(): Promise<void>;
1980
+ /** Append an action log entry. Evicts oldest 10% when maxEntries is exceeded. */
1981
+ addAction(action: ActionLog): void;
1982
+ /** Retrieve all action log entries. */
1983
+ getActions(): ActionLog[];
1984
+ /** Retrieve actions filtered by a predicate. */
1985
+ queryActions(predicate: (action: ActionLog) => boolean): ActionLog[];
1986
+ /** Get actions for a specific agent. */
1987
+ getActionsByAgent(agentId: string): ActionLog[];
1988
+ /** Get actions for a specific session (across all agents). */
1989
+ getActionsBySession(sessionId: string): ActionLog[];
1990
+ /** Append a transaction record. Evicts oldest 10% when maxEntries is exceeded. */
1991
+ addTransaction(tx: TransactionRecord): void;
1992
+ /** Retrieve all transaction records. */
1993
+ getTransactions(): TransactionRecord[];
1994
+ /** Retrieve transactions filtered by a predicate. */
1995
+ queryTransactions(predicate: (tx: TransactionRecord) => boolean): TransactionRecord[];
1996
+ /** Get transactions for a specific agent. */
1997
+ getTransactionsByAgent(agentId: string): TransactionRecord[];
1998
+ /** Get the most recent N transactions for an agent. */
1999
+ getRecentTransactions(agentId: string, limit: number): TransactionRecord[];
2000
+ /** Store a task. */
2001
+ addTask(task: Task): void;
2002
+ /** Retrieve a task by ID. */
2003
+ getTask(taskId: string): Task | undefined;
2004
+ /** Update a task. */
2005
+ updateTask(taskId: string, updates: Partial<Task>): Task | undefined;
2006
+ /** Retrieve all tasks. */
2007
+ getTasks(): Task[];
2008
+ /** Retrieve tasks filtered by a predicate. */
2009
+ queryTasks(predicate: (task: Task) => boolean): Task[];
2010
+ /** Append an anomaly event. Evicts oldest 10% when maxEntries is exceeded. */
2011
+ addAnomaly(anomaly: AnomalyEvent): void;
2012
+ /** Retrieve all anomaly events. */
2013
+ getAnomalies(): AnomalyEvent[];
2014
+ /** Retrieve anomalies filtered by a predicate. */
2015
+ queryAnomalies(predicate: (anomaly: AnomalyEvent) => boolean): AnomalyEvent[];
2016
+ /** Get total record counts across all stores. */
2017
+ getCounts(): {
2018
+ actions: number;
2019
+ transactions: number;
2020
+ tasks: number;
2021
+ anomalies: number;
2022
+ };
2023
+ /** Clear all stored data. Useful for testing. */
2024
+ clear(): void;
4287
2025
  }
4288
2026
 
2027
+ /** Pre-fetched data for a single agent, passed to factor methods to avoid redundant store queries. */
2028
+ interface AgentData {
2029
+ actions: ActionLog[];
2030
+ transactions: TransactionRecord[];
2031
+ tasks: Task[];
2032
+ anomalies: AnomalyEvent[];
2033
+ }
4289
2034
  /**
4290
- * Manages user-defined blocklist and allowlist addresses for compliance
4291
- * screening. Maps to Circle Compliance Engine Rule #3 (Custom Blocklist).
2035
+ * TrustScorer computes trust scores for agents and risk scores for transactions.
4292
2036
  *
4293
- * Features:
4294
- * - O(1) address lookup via Map with lowercase keys
4295
- * - Per-chain filtering: entries can target specific chains or all chains
4296
- * - Time-based expiration: entries with an `expiresAt` date are skipped
4297
- * (not removed) when expired
4298
- * - Bulk import/export for list management
2037
+ * This MVP implementation uses rule-based scoring across multiple factors:
2038
+ * - **History depth**: More transaction history = higher trust.
2039
+ * - **Task completion rate**: Higher completion rate = higher trust.
2040
+ * - **Anomaly frequency**: Fewer anomalies = higher trust.
2041
+ * - **Transaction consistency**: Consistent patterns = higher trust.
2042
+ * - **Compliance adherence**: Following compliance rules = higher trust.
4299
2043
  *
4300
- * @example
4301
- * ```typescript
4302
- * const manager = new BlocklistManager();
4303
- *
4304
- * manager.addToBlocklist({
4305
- * address: '0xBadActor...',
4306
- * chains: ['ethereum', 'base'],
4307
- * reason: 'Known phishing address',
4308
- * addedBy: 'compliance-team',
4309
- * addedAt: new Date().toISOString(),
4310
- * expiresAt: '2026-12-31T23:59:59Z',
4311
- * });
2044
+ * Scores range from 0-100 with levels: untrusted, low, medium, high, verified.
4312
2045
  *
4313
- * if (manager.isBlocklisted('0xbadactor...', 'ethereum')) {
4314
- * // Block the transaction
4315
- * }
4316
- * ```
2046
+ * In a production system, these rules would be augmented with ML-based scoring,
2047
+ * graph analysis, and external reputation data.
4317
2048
  */
4318
- declare class BlocklistManager {
4319
- /** Internal blocklist store — lowercase address -> ListEntry */
4320
- private readonly blocklist;
4321
- /** Internal allowlist store — lowercase address -> ListEntry */
4322
- private readonly allowlist;
4323
- /** Optional configuration */
2049
+ declare class TrustScorer {
4324
2050
  private readonly config;
4325
- constructor(config?: BlocklistConfig);
4326
- /**
4327
- * Add an address to the blocklist.
4328
- *
4329
- * If the address already exists, the entry is overwritten with the new one.
4330
- *
4331
- * @param entry - The list entry to add
4332
- */
4333
- addToBlocklist(entry: ListEntry): void;
4334
- /**
4335
- * Add an address to the allowlist.
4336
- *
4337
- * If the address already exists, the entry is overwritten with the new one.
4338
- *
4339
- * @param entry - The list entry to add
4340
- */
4341
- addToAllowlist(entry: ListEntry): void;
2051
+ private readonly store;
2052
+ constructor(config: KontextConfig, store: KontextStore);
4342
2053
  /**
4343
- * Remove an address from the blocklist.
2054
+ * Compute the trust score for a given agent.
4344
2055
  *
4345
- * @param address - The blockchain address to remove (case-insensitive)
4346
- * @returns `true` if the address was found and removed, `false` otherwise
4347
- */
4348
- removeFromBlocklist(address: string): boolean;
4349
- /**
4350
- * Remove an address from the allowlist.
2056
+ * @param agentId - The agent identifier
2057
+ * @returns TrustScore with overall score, factor breakdown, and trust level
4351
2058
  *
4352
- * @param address - The blockchain address to remove (case-insensitive)
4353
- * @returns `true` if the address was found and removed, `false` otherwise
2059
+ * @example
2060
+ * ```typescript
2061
+ * const score = await scorer.getTrustScore('payment-agent-1');
2062
+ * console.log(`Trust: ${score.score}/100 (${score.level})`);
2063
+ * ```
4354
2064
  */
4355
- removeFromAllowlist(address: string): boolean;
2065
+ getTrustScore(agentId: string): Promise<TrustScore>;
4356
2066
  /**
4357
- * Check whether an address is on the blocklist.
2067
+ * Evaluate the risk of a specific transaction.
4358
2068
  *
4359
- * Performs case-insensitive lookup and honors:
4360
- * - Chain filtering: if the entry specifies chains, the address is only
4361
- * considered blocklisted if the given chain matches (or entry has no chains).
4362
- * - Expiration: if the entry has an `expiresAt` date in the past, it is
4363
- * skipped (not removed from storage).
2069
+ * @param tx - Transaction input to evaluate
2070
+ * @returns TransactionEvaluation with risk score, factors, and recommendation
4364
2071
  *
4365
- * @param address - The blockchain address to check
4366
- * @param chain - Optional chain to filter against
4367
- * @returns `true` if the address is actively blocklisted
2072
+ * @example
2073
+ * ```typescript
2074
+ * const eval = await scorer.evaluateTransaction({
2075
+ * txHash: '0x...',
2076
+ * chain: 'base',
2077
+ * amount: '50000',
2078
+ * token: 'USDC',
2079
+ * from: '0xSender',
2080
+ * to: '0xReceiver',
2081
+ * agentId: 'agent-1',
2082
+ * });
2083
+ * if (eval.flagged) console.log('Transaction flagged for review');
2084
+ * ```
4368
2085
  */
4369
- isBlocklisted(address: string, chain?: Chain): boolean;
2086
+ evaluateTransaction(tx: LogTransactionInput): Promise<TransactionEvaluation>;
2087
+ private computeAgentFactors;
4370
2088
  /**
4371
- * Check whether an address is on the allowlist.
2089
+ * History depth factor: more recorded actions = more data to assess trust.
4372
2090
  *
4373
- * Same matching semantics as {@link isBlocklisted}: case-insensitive,
4374
- * chain-aware, and expiration-aware.
4375
- *
4376
- * @param address - The blockchain address to check
4377
- * @param chain - Optional chain to filter against
4378
- * @returns `true` if the address is actively allowlisted
4379
- */
4380
- isAllowlisted(address: string, chain?: Chain): boolean;
4381
- /**
4382
- * Return all blocklist entries.
4383
- */
4384
- getBlocklist(): ListEntry[];
4385
- /**
4386
- * Return all allowlist entries.
2091
+ * Scoring curve (step function, not linear) prevents gaming by spamming
2092
+ * low-value actions — crossing each tier requires meaningfully more history:
2093
+ * - 0 actions → 10 (minimal trust, new agent)
2094
+ * - 1-4 30 (some activity but too little to draw conclusions)
2095
+ * - 5-19 50 (neutral, moderate activity)
2096
+ * - 20-49 70 (established agent with reasonable track record)
2097
+ * - 50-99 → 85 (well-established agent)
2098
+ * - 100+ → 95 (capped below 100 because history alone doesn't guarantee trust)
4387
2099
  */
4388
- getAllowlist(): ListEntry[];
2100
+ private computeHistoryDepthFactor;
4389
2101
  /**
4390
- * Bulk-import entries into either the blocklist or allowlist.
2102
+ * Task completion factor: agents that confirm tasks build trust, failures erode it.
4391
2103
  *
4392
- * @param entries - Array of list entries to import
4393
- * @param type - Target list: `'blocklist'` or `'allowlist'`
4394
- * @returns The number of entries that were imported
2104
+ * Formula: score = (completionRate * 100) - (failureRate * 30)
2105
+ * - The 30x failure penalty means each failure costs 3x more than a confirmation gains.
2106
+ * This asymmetry reflects real-world trust: it takes many good actions to build trust
2107
+ * but only a few failures to lose it.
2108
+ * - Returns 50 (neutral) when no tasks exist, avoiding penalizing new agents.
4395
2109
  */
4396
- importList(entries: ListEntry[], type: 'blocklist' | 'allowlist'): number;
2110
+ private computeTaskCompletionFactor;
4397
2111
  /**
4398
- * Export all entries from either the blocklist or allowlist.
2112
+ * Anomaly frequency factor: fewer anomalies relative to total actions = higher trust.
4399
2113
  *
4400
- * @param type - Source list: `'blocklist'` or `'allowlist'`
4401
- * @returns Array of all list entries (including expired ones)
4402
- */
4403
- exportList(type: 'blocklist' | 'allowlist'): ListEntry[];
4404
- /**
4405
- * Check whether an address is present and active in a given list map.
4406
- * Expired entries are skipped but not removed from storage.
4407
- */
4408
- private isListed;
4409
- }
4410
- /**
4411
- * Combines results from multiple {@link ScreeningProvider} instances into a
4412
- * unified screening decision.
4413
- *
4414
- * The aggregator:
4415
- * - Checks the optional {@link BlocklistManager} first (allowlist and blocklist)
4416
- * - Runs all providers in parallel (configurable) with per-provider timeout
4417
- * - Computes a weighted-average aggregate risk score
4418
- * - Determines the final decision based on configurable thresholds
4419
- * - Enforces minimum provider success requirements
4420
- *
4421
- * @example
4422
- * ```typescript
4423
- * const aggregator = new ScreeningAggregator(
4424
- * [ofacProvider, chainalysisProvider, openSanctionsProvider],
4425
- * {
4426
- * blockThreshold: 80,
4427
- * reviewThreshold: 40,
4428
- * providerTimeoutMs: 5000,
4429
- * minProviderSuccess: 2,
4430
- * providerWeights: {
4431
- * 'ofac-list': 1.0,
4432
- * 'chainalysis-free': 0.8,
4433
- * 'opensanctions': 0.6,
4434
- * },
4435
- * },
4436
- * blocklistManager,
4437
- * );
4438
- *
4439
- * const result = await aggregator.screenAddress({
4440
- * address: '0x...',
4441
- * chain: 'ethereum',
4442
- * });
4443
- *
4444
- * switch (result.decision) {
4445
- * case 'BLOCK': // Deny transaction
4446
- * case 'REVIEW': // Flag for manual review
4447
- * case 'APPROVE': // Proceed
4448
- * }
4449
- * ```
4450
- */
4451
- declare class ScreeningAggregator {
4452
- private providers;
4453
- private readonly config;
4454
- private readonly blocklist;
4455
- /**
4456
- * Create a new ScreeningAggregator.
2114
+ * Uses anomaly rate (anomalies / actions) with step-function scoring:
2115
+ * - 0% 100 (clean record)
2116
+ * - <1% → 90 (near-perfect, occasional false positive acceptable)
2117
+ * - <5% → 70 (some noise but generally clean)
2118
+ * - <10% → 50 (neutral, warrants monitoring)
2119
+ * - <25% 30 (concerning pattern)
2120
+ * - 25%+ 10 (severe anomaly rate)
4457
2121
  *
4458
- * @param providers - Array of screening providers to aggregate
4459
- * @param config - Optional aggregator configuration
4460
- * @param blocklist - Optional blocklist manager for custom block/allow lists
2122
+ * Critical anomalies incur a -15 point penalty each, high anomalies -8 each.
2123
+ * This severity weighting ensures a single critical anomaly (e.g., sanctions hit)
2124
+ * has outsized impact compared to multiple low-severity anomalies.
4461
2125
  */
4462
- constructor(providers: ScreeningProvider[], config?: ScreeningAggregatorConfig, blocklist?: BlocklistManager);
2126
+ private computeAnomalyFrequencyFactor;
4463
2127
  /**
4464
- * Screen a single address through all providers and return a unified result.
2128
+ * Transaction consistency factor: stable spending patterns indicate legitimate usage.
4465
2129
  *
4466
- * Execution order:
4467
- * 1. Check allowlist (if allowlisted AND `config.blocklist.allowlistPriority`, approve immediately)
4468
- * 2. Check blocklist (if blocklisted, block immediately with CUSTOM_BLOCKLIST category)
4469
- * 3. Run all providers (parallel or sequential) with per-provider timeout
4470
- * 4. Aggregate results into a unified decision
2130
+ * Uses the coefficient of variation (CV = stdDev / mean) to measure amount regularity:
2131
+ * - CV < 0.1 95 (extremely consistent, e.g., recurring payroll)
2132
+ * - CV < 0.3 80 (fairly consistent with some variance)
2133
+ * - CV < 0.5 65 (moderate variance, common for operational spending)
2134
+ * - CV < 1.0 45 (high variance, warrants attention)
2135
+ * - CV < 2.0 → 30 (very erratic, potential structuring)
2136
+ * - CV 2.0+ → 15 (extreme variance, strong structuring indicator)
4471
2137
  *
4472
- * @param input - Address screening input
4473
- * @returns Unified screening result with aggregated decision
2138
+ * Also penalizes -15 points when >80% of destinations are unique with >5 txs,
2139
+ * which is a common money-laundering pattern (spray-and-pray distribution).
4474
2140
  */
4475
- screenAddress(input: ScreenAddressInput): Promise<UnifiedScreeningResult>;
2141
+ private computeTransactionConsistencyFactor;
4476
2142
  /**
4477
- * Screen a transaction by screening both sender and recipient addresses.
2143
+ * Compliance adherence factor: agents that follow the task-confirm-evidence workflow
2144
+ * demonstrate higher operational integrity.
4478
2145
  *
4479
- * The combined decision is the worst (most restrictive) of the two
4480
- * individual decisions: BLOCK > REVIEW > APPROVE.
2146
+ * Scoring:
2147
+ * - Base score: 50 (neutral)
2148
+ * - +30 max for evidence rate (confirmedTasksWithEvidence / confirmedTasks)
2149
+ * - +20 max for coverage rate (tasks / transactions, capped at 1.0)
4481
2150
  *
4482
- * @param input - Transaction screening input
4483
- * @returns Sender result, recipient result, and combined decision
2151
+ * The rationale: tasks with evidence prove the agent completed auditable work.
2152
+ * Coverage rate measures what fraction of financial activity has corresponding
2153
+ * task tracking — higher coverage means better compliance discipline.
4484
2154
  */
4485
- screenTransaction(input: ScreenTransactionProviderInput): Promise<{
4486
- sender: UnifiedScreeningResult;
4487
- recipient: UnifiedScreeningResult;
4488
- combinedDecision: 'APPROVE' | 'REVIEW' | 'BLOCK';
4489
- }>;
2155
+ private computeComplianceAdherenceFactor;
2156
+ private computeTransactionRiskFactors;
4490
2157
  /**
4491
- * Add a screening provider at runtime.
2158
+ * Amount risk: higher transaction amounts carry inherently higher risk.
4492
2159
  *
4493
- * @param provider - The provider to add
4494
- */
4495
- addProvider(provider: ScreeningProvider): void;
4496
- /**
4497
- * Remove a screening provider by name.
2160
+ * Tiers are aligned with common fintech thresholds:
2161
+ * - <$100: near-zero risk (5), micro-transactions
2162
+ * - <$1K: low risk (15), typical consumer spending
2163
+ * - <$10K: moderate (30), approaches CTR reporting thresholds
2164
+ * - <$50K: elevated (55), large business transactions
2165
+ * - <$100K: high (75), requires enhanced due diligence
2166
+ * - $100K+: very high (95), institutional-scale transfers
4498
2167
  *
4499
- * @param name - The provider name to remove
4500
- * @returns `true` if the provider was found and removed, `false` otherwise
2168
+ * Additional +20 penalty when amount exceeds 5x the agent's historical average,
2169
+ * detecting sudden spending spikes that could indicate account compromise.
4501
2170
  */
4502
- removeProvider(name: string): boolean;
2171
+ private computeAmountRisk;
2172
+ private computeNewDestinationRisk;
2173
+ private computeFrequencyRisk;
2174
+ private computeAgentRisk;
4503
2175
  /**
4504
- * List the names of all registered providers.
2176
+ * Round amount risk: round numbers are a structuring indicator in AML heuristics.
4505
2177
  *
4506
- * @returns Array of provider name strings
4507
- */
4508
- getProviders(): string[];
4509
- /**
4510
- * Check the health of all registered providers.
2178
+ * Money launderers often transact in round amounts (e.g., $10,000 exactly) or
2179
+ * just under regulatory thresholds (e.g., $9,500 to avoid $10K CTR filing).
4511
2180
  *
4512
- * @returns A record mapping provider name to its health status
4513
- */
4514
- healthCheck(): Promise<Record<string, boolean>>;
4515
- /**
4516
- * Execute all providers against the given input, respecting the parallel
4517
- * configuration and per-provider timeout.
4518
- */
4519
- private runProviders;
4520
- /**
4521
- * Run all providers in parallel using Promise.allSettled, with per-provider
4522
- * timeout enforcement.
4523
- */
4524
- private runProvidersParallel;
4525
- /**
4526
- * Run all providers sequentially (one at a time), with per-provider
4527
- * timeout enforcement.
4528
- */
4529
- private runProvidersSequential;
4530
- /**
4531
- * Aggregate individual provider results into a unified screening result.
4532
- */
4533
- private aggregateResults;
4534
- /**
4535
- * Compute the weighted average risk score across successful provider results.
2181
+ * Scoring:
2182
+ * - Non-round amounts: 5 (baseline, most legitimate transactions)
2183
+ * - Multiples of $1,000: 15 (mildly suspicious)
2184
+ * - Multiples of $10,000: 25 (more suspicious)
2185
+ * - Amounts $9,000-$10,000: +20 penalty (classic structuring band)
4536
2186
  *
4537
- * Uses `config.providerWeights` when set; otherwise treats all providers
4538
- * with equal weight. Only providers that succeeded are included in the
4539
- * computation. If no providers succeeded, returns 0.
4540
- */
4541
- private computeWeightedRiskScore;
4542
- /**
4543
- * Build an immediate APPROVE result for an allowlisted address.
4544
- */
4545
- private buildAllowlistedResult;
4546
- /**
4547
- * Build an immediate BLOCK result for a blocklisted address.
2187
+ * This factor alone rarely triggers flagging it contributes to the composite
2188
+ * risk score alongside amount, frequency, and destination analysis.
4548
2189
  */
4549
- private buildBlocklistedResult;
2190
+ private computeRoundAmountRisk;
2191
+ private scoreToLevel;
2192
+ private riskScoreToLevel;
4550
2193
  }
4551
- /**
4552
- * Convenience factory for creating a {@link ScreeningAggregator} with optional
4553
- * blocklist support.
4554
- *
4555
- * @param providers - Array of screening providers to aggregate
4556
- * @param config - Optional aggregator configuration
4557
- * @param blocklist - Optional blocklist manager
4558
- * @returns A configured ScreeningAggregator instance
4559
- *
4560
- * @example
4561
- * ```typescript
4562
- * const aggregator = createScreeningAggregator(
4563
- * [ofacProvider, chainalysisProvider],
4564
- * { blockThreshold: 75 },
4565
- * myBlocklistManager,
4566
- * );
4567
- * ```
4568
- */
4569
- declare function createScreeningAggregator(providers: ScreeningProvider[], config?: ScreeningAggregatorConfig, blocklist?: BlocklistManager): ScreeningAggregator;
4570
2194
 
4571
- /** Configuration for the OFACListProvider */
4572
- interface OFACListProviderConfig {
4573
- /**
4574
- * How often to re-fetch the address list from GitHub, in milliseconds.
4575
- * @default 86400000 (24 hours)
4576
- */
4577
- updateIntervalMs?: number;
4578
- /**
4579
- * GitHub branch containing the auto-generated list files.
4580
- * @default 'lists'
4581
- */
4582
- githubBranch?: string;
4583
- /**
4584
- * If true, fall back to the built-in `ofacScreener` from `./ofac-sanctions.js`
4585
- * when the GitHub fetch fails during initialization.
4586
- * @default false
4587
- */
4588
- fallbackToBuiltin?: boolean;
4589
- }
4590
2195
  /**
4591
- * OFAC sanctions screening provider backed by the 0xB10C GitHub repository.
4592
- *
4593
- * The repository's `lists` branch contains nightly-updated plain text files
4594
- * with one sanctioned digital currency address per line, sourced from the
4595
- * official U.S. Treasury OFAC SDN list. This provider fetches the ETH
4596
- * address file, parses it into a `Set<string>` for O(1) lookups, and
4597
- * periodically re-fetches to stay current.
4598
- *
4599
- * Because Ethereum-format addresses are valid across all EVM-compatible
4600
- * chains, this provider supports screening on any EVM chain.
4601
- *
4602
- * @example
4603
- * ```typescript
4604
- * const provider = new OFACListProvider({ fallbackToBuiltin: true });
4605
- * await provider.initialize();
4606
- *
4607
- * const result = await provider.screenAddress({
4608
- * address: '0x098B716B8Aaf21512996dC57EB0615e2383E2f96',
4609
- * chain: 'ethereum',
4610
- * });
4611
- *
4612
- * if (result.matched) {
4613
- * console.log('OFAC sanctioned address detected');
4614
- * }
4615
- *
4616
- * // Cleanup when done
4617
- * provider.dispose();
4618
- * ```
2196
+ * AnomalyDetector monitors agent actions and transactions for suspicious patterns.
2197
+ *
2198
+ * Supported detection rules:
2199
+ * - **unusualAmount**: Flags transactions above a configured threshold or
2200
+ * significantly above the agent's historical average.
2201
+ * - **frequencySpike**: Flags when an agent's transaction rate exceeds
2202
+ * the configured maximum per hour.
2203
+ * - **newDestination**: Flags transactions to previously unseen addresses.
2204
+ * - **offHoursActivity**: Flags activity during configured off-hours (UTC).
2205
+ * - **rapidSuccession**: Flags transactions that occur within a very short
2206
+ * time interval of each other.
2207
+ * - **roundAmount**: Flags round-number amounts that may indicate structuring.
2208
+ *
2209
+ * Severity levels: low, medium, high, critical.
4619
2210
  */
4620
- declare class OFACListProvider implements ScreeningProvider {
4621
- readonly name = "ofac-list-auto";
4622
- readonly supportedCategories: RiskCategory[];
4623
- readonly supportedChains: Chain[];
4624
- /** Lowercased sanctioned addresses for O(1) lookup */
4625
- private sanctionedAddresses;
4626
- /** ISO timestamp of the last successful address list update */
4627
- private lastUpdatedAt;
4628
- /** Handle for the periodic re-fetch interval */
4629
- private refreshInterval;
4630
- /** Resolved configuration with defaults applied */
2211
+ declare class AnomalyDetector {
4631
2212
  private readonly config;
4632
- constructor(config?: OFACListProviderConfig);
4633
- /**
4634
- * Fetch the initial address list from GitHub and schedule periodic refreshes.
4635
- *
4636
- * If the fetch fails and `fallbackToBuiltin` is enabled, the provider will
4637
- * populate its address set from the built-in `ofacScreener` instead of
4638
- * throwing. This ensures screening can proceed even if GitHub is unreachable.
4639
- */
4640
- initialize(): Promise<void>;
4641
- /**
4642
- * Screen a single address against the OFAC sanctioned addresses set.
4643
- *
4644
- * @param input - The address and chain to screen
4645
- * @returns A ProviderScreeningResult with match information and risk signals
4646
- */
4647
- screenAddress(input: ScreenAddressInput): Promise<ProviderScreeningResult>;
4648
- /**
4649
- * Returns true if the address set has been successfully populated.
4650
- * A healthy provider has at least one address loaded.
4651
- */
4652
- isHealthy(): Promise<boolean>;
2213
+ private readonly store;
2214
+ private detectionConfig;
2215
+ private thresholds;
2216
+ private callbacks;
2217
+ private enabled;
2218
+ constructor(config: KontextConfig, store: KontextStore);
4653
2219
  /**
4654
- * Return provider statistics for observability and monitoring.
2220
+ * Enable anomaly detection with the specified configuration.
4655
2221
  *
4656
- * @returns Object containing the current address count and last update timestamp
4657
- */
4658
- getStats(): {
4659
- addressCount: number;
4660
- lastUpdatedAt: string | null;
4661
- };
4662
- /**
4663
- * Clear the periodic refresh interval and release resources.
4664
- * Call this when the provider is no longer needed to prevent memory leaks.
4665
- */
4666
- dispose(): void;
4667
- /**
4668
- * Fetch the sanctioned ETH address list from GitHub and parse it into
4669
- * the internal Set. Falls back to the built-in screener if configured.
4670
- */
4671
- private fetchAddressList;
4672
- /**
4673
- * Parse a plain text address list into a Set of lowercased addresses.
4674
- * Handles:
4675
- * - Empty lines
4676
- * - Lines with leading/trailing whitespace
4677
- * - Comment lines starting with '#'
4678
- * - Carriage return / line feed differences
4679
- */
4680
- private parseAddressList;
4681
- }
4682
- /** Configuration for the ChainalysisOracleProvider */
4683
- interface ChainalysisOracleProviderConfig {
4684
- /**
4685
- * Mapping of chain names to JSON-RPC endpoint URLs.
4686
- * Only chains with an entry here will be screenable.
2222
+ * @param detectionConfig - Rules and thresholds for detection
4687
2223
  *
4688
2224
  * @example
4689
2225
  * ```typescript
4690
- * {
4691
- * ethereum: 'https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY',
4692
- * polygon: 'https://polygon-mainnet.g.alchemy.com/v2/YOUR_KEY',
4693
- * }
2226
+ * detector.enableAnomalyDetection({
2227
+ * rules: ['unusualAmount', 'frequencySpike', 'newDestination'],
2228
+ * thresholds: { maxAmount: '10000', maxFrequency: 50 },
2229
+ * });
4694
2230
  * ```
4695
2231
  */
4696
- rpcUrls: Record<string, string>;
4697
- /**
4698
- * How long to cache oracle results per address+chain pair, in milliseconds.
4699
- * @default 300000 (5 minutes)
4700
- */
4701
- cacheTimeMs?: number;
4702
- }
4703
- /**
4704
- * Chainalysis on-chain sanctions oracle screening provider.
4705
- *
4706
- * The Chainalysis sanctions oracle is a free, permissionless smart contract
4707
- * deployed at `0x40C57923924B5c5c5455c48D93317139ADDaC8fb` on multiple EVM
4708
- * chains. It exposes a single `isSanctioned(address)` view function that
4709
- * returns true if the address appears on the Chainalysis sanctions list.
4710
- *
4711
- * This provider makes raw `eth_call` JSON-RPC requests to the oracle --
4712
- * no ethers.js or web3.js dependency required. Results are cached per
4713
- * address+chain pair to reduce RPC call volume.
4714
- *
4715
- * Supported chains: Ethereum, Polygon, Arbitrum, Optimism, Base, Avalanche.
4716
- *
4717
- * @see https://go.chainalysis.com/chainalysis-oracle-docs.html
4718
- *
4719
- * @example
4720
- * ```typescript
4721
- * const provider = new ChainalysisOracleProvider({
4722
- * rpcUrls: {
4723
- * ethereum: 'https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY',
4724
- * polygon: 'https://polygon-mainnet.g.alchemy.com/v2/YOUR_KEY',
4725
- * },
4726
- * cacheTimeMs: 60_000, // 1 minute cache
4727
- * });
4728
- *
4729
- * const result = await provider.screenAddress({
4730
- * address: '0x098B716B8Aaf21512996dC57EB0615e2383E2f96',
4731
- * chain: 'ethereum',
4732
- * });
4733
- *
4734
- * if (result.matched) {
4735
- * console.log('Address flagged by Chainalysis oracle');
4736
- * }
4737
- * ```
4738
- */
4739
- declare class ChainalysisOracleProvider implements ScreeningProvider {
4740
- readonly name = "chainalysis-oracle";
4741
- readonly supportedCategories: RiskCategory[];
4742
- readonly supportedChains: Chain[];
4743
- /** RPC URL mapping: chain name -> JSON-RPC endpoint */
4744
- private readonly rpcUrls;
4745
- /** Cache TTL in milliseconds */
4746
- private readonly cacheTimeMs;
4747
- /** In-memory cache keyed by `${chain}:${lowercasedAddress}` */
4748
- private readonly cache;
4749
- constructor(config: ChainalysisOracleProviderConfig);
4750
- /**
4751
- * Screen a single address using the Chainalysis on-chain sanctions oracle.
4752
- *
4753
- * Makes an `eth_call` to the oracle contract on the specified chain. If no
4754
- * RPC URL is configured for the chain, returns a failed result with an error.
4755
- *
4756
- * @param input - The address and chain to screen
4757
- * @returns A ProviderScreeningResult with oracle verdict and risk signals
4758
- */
4759
- screenAddress(input: ScreenAddressInput): Promise<ProviderScreeningResult>;
4760
- /**
4761
- * Verify RPC connectivity by calling the oracle with the zero address.
4762
- *
4763
- * The zero address (`0x0000...0000`) should not be sanctioned, so the oracle
4764
- * should return `false`. Any successful response (true or false) indicates
4765
- * the RPC and oracle contract are reachable.
4766
- */
4767
- isHealthy(): Promise<boolean>;
4768
- /**
4769
- * Make a raw `eth_call` to the Chainalysis oracle's `isSanctioned(address)` function.
4770
- *
4771
- * @param rpcUrl - JSON-RPC endpoint URL
4772
- * @param address - Lowercased Ethereum address to check (with or without 0x prefix)
4773
- * @returns true if the oracle reports the address as sanctioned
4774
- */
4775
- private callOracle;
4776
- /**
4777
- * Decode an ABI-encoded boolean return value from an eth_call.
4778
- *
4779
- * The return data is a 32-byte (64 hex char) value. Any non-zero value
4780
- * is treated as `true` per Solidity's bool encoding.
4781
- *
4782
- * @param hexData - The hex-encoded return data (with 0x prefix)
4783
- * @returns The decoded boolean value
4784
- */
4785
- private decodeBoolResult;
4786
- /**
4787
- * Look up a cached oracle result. Returns null if no valid cache entry exists.
4788
- *
4789
- * @param cacheKey - The cache key (`chain:address`)
4790
- * @returns The cached sanctioned boolean, or null if not cached / expired
4791
- */
4792
- private getCachedResult;
4793
- /**
4794
- * Store an oracle result in the cache.
4795
- *
4796
- * @param cacheKey - The cache key (`chain:address`)
4797
- * @param sanctioned - Whether the address is sanctioned
4798
- */
4799
- private setCachedResult;
4800
- }
4801
-
4802
- /** Configuration for the Chainalysis free-tier API provider */
4803
- interface ChainalysisFreeAPIConfig {
4804
- /** API key obtained from Chainalysis registration */
4805
- apiKey: string;
4806
- /** Base URL override (defaults to public Chainalysis endpoint) */
4807
- baseUrl?: string;
4808
- /** Cache TTL in milliseconds (default: 15 minutes) */
4809
- cacheTimeMs?: number;
4810
- }
4811
- /**
4812
- * Screening provider that integrates with the Chainalysis free-tier
4813
- * sanctions screening REST API.
4814
- *
4815
- * The free tier provides sanctions-only screening and is chain-agnostic
4816
- * for address lookups. Results are cached in memory to reduce API calls.
4817
- *
4818
- * @see https://www.chainalysis.com/free-cryptocurrency-sanctions-screening-tools/
4819
- *
4820
- * @example
4821
- * ```typescript
4822
- * const provider = new ChainalysisFreeAPIProvider({
4823
- * apiKey: process.env.CHAINALYSIS_API_KEY!,
4824
- * });
4825
- *
4826
- * await provider.initialize();
4827
- *
4828
- * const result = await provider.screenAddress({
4829
- * address: '0x...',
4830
- * chain: 'ethereum',
4831
- * });
4832
- *
4833
- * if (result.matched) {
4834
- * console.log('Sanctions match:', result.signals);
4835
- * }
4836
- * ```
4837
- */
4838
- declare class ChainalysisFreeAPIProvider implements ScreeningProvider {
4839
- readonly name = "chainalysis-free-api";
4840
- readonly supportedCategories: RiskCategory[];
4841
- readonly supportedChains: Chain[];
4842
- private readonly apiKey;
4843
- private readonly baseUrl;
4844
- private readonly cache;
4845
- private lastCallAt;
4846
- private lastCallSuccess;
4847
- private apiKeyValid;
4848
- constructor(config: ChainalysisFreeAPIConfig);
4849
- /**
4850
- * Verify API key validity by making a test call against the zero address.
4851
- * Throws if the API key is invalid or the service is unreachable.
4852
- */
4853
- initialize(): Promise<void>;
4854
- /**
4855
- * Screen an address against the Chainalysis sanctions database.
4856
- *
4857
- * Checks the in-memory cache first. On a cache miss, calls the Chainalysis
4858
- * free API and maps each identification to a SEVERE-level RiskSignal.
4859
- *
4860
- * @param input - Address screening input
4861
- * @returns Screening result with any detected sanctions signals
4862
- */
4863
- screenAddress(input: ScreenAddressInput): Promise<ProviderScreeningResult>;
4864
- /**
4865
- * Returns true if the last API call succeeded within the last 5 minutes.
4866
- */
4867
- isHealthy(): Promise<boolean>;
4868
- /**
4869
- * Return operational statistics for monitoring and debugging.
4870
- */
4871
- getStats(): {
4872
- cachedEntries: number;
4873
- lastCallAt: string | null;
4874
- apiKeyValid: boolean;
4875
- };
4876
- }
4877
- /** Configuration for the OpenSanctions API provider */
4878
- interface OpenSanctionsConfig {
4879
- /** API key for OpenSanctions */
4880
- apiKey: string;
4881
- /** Base URL override (defaults to https://api.opensanctions.org) */
4882
- baseUrl?: string;
4883
- /** Minimum match score threshold (0-1, default: 0.7) */
4884
- minMatchScore?: number;
4885
- /** Cache TTL in milliseconds (default: 30 minutes) */
4886
- cacheTimeMs?: number;
4887
- }
4888
- /**
4889
- * Screening provider that integrates with the OpenSanctions API for
4890
- * comprehensive entity screening across 325+ global data sources.
4891
- *
4892
- * Covers sanctions lists (OFAC, EU, UN), PEP databases, crime-related
4893
- * entities, and persons of interest. Uses the CryptoWallet schema for
4894
- * address-based matching and supports entity name search.
4895
- *
4896
- * @see https://www.opensanctions.org/docs/api/
4897
- *
4898
- * @example
4899
- * ```typescript
4900
- * const provider = new OpenSanctionsProvider({
4901
- * apiKey: process.env.OPENSANCTIONS_API_KEY!,
4902
- * minMatchScore: 0.8,
4903
- * });
4904
- *
4905
- * await provider.initialize();
4906
- *
4907
- * const result = await provider.screenAddress({
4908
- * address: '0x...',
4909
- * chain: 'ethereum',
4910
- * });
4911
- *
4912
- * // Entity name search
4913
- * const entities = await provider.searchEntity('Lazarus Group');
4914
- * ```
4915
- */
4916
- declare class OpenSanctionsProvider implements ScreeningProvider {
4917
- readonly name = "opensanctions";
4918
- readonly supportedCategories: RiskCategory[];
4919
- readonly supportedChains: Chain[];
4920
- private readonly apiKey;
4921
- private readonly baseUrl;
4922
- private readonly minMatchScore;
4923
- private readonly cache;
4924
- private lastCallAt;
4925
- private lastCallSuccess;
4926
- constructor(config: OpenSanctionsConfig);
2232
+ enableAnomalyDetection(detectionConfig: AnomalyDetectionConfig): void;
4927
2233
  /**
4928
- * Test API connectivity by making a lightweight search request.
4929
- * Throws if the API key is invalid or the service is unreachable.
2234
+ * Disable anomaly detection.
4930
2235
  */
4931
- initialize(): Promise<void>;
2236
+ disableAnomalyDetection(): void;
4932
2237
  /**
4933
- * Screen an address against the OpenSanctions database using the
4934
- * CryptoWallet entity match endpoint.
2238
+ * Register a callback for anomaly events.
4935
2239
  *
4936
- * Results with a score below `minMatchScore` are filtered out. Each
4937
- * qualifying result is mapped to a RiskSignal with category derived
4938
- * from the entity's `topics` property.
2240
+ * @param callback - Function to call when an anomaly is detected
2241
+ * @returns Unsubscribe function
4939
2242
  *
4940
- * @param input - Address screening input
4941
- * @returns Screening result with detected risk signals
2243
+ * @example
2244
+ * ```typescript
2245
+ * const unsub = detector.onAnomaly((anomaly) => {
2246
+ * console.log(`Anomaly: ${anomaly.type} [${anomaly.severity}]`);
2247
+ * });
2248
+ * // Later: unsub();
2249
+ * ```
4942
2250
  */
4943
- screenAddress(input: ScreenAddressInput): Promise<ProviderScreeningResult>;
2251
+ onAnomaly(callback: AnomalyCallback): () => void;
4944
2252
  /**
4945
- * Search for entities by name using the OpenSanctions search endpoint.
4946
- *
4947
- * This is an additional method beyond the ScreeningProvider interface,
4948
- * useful for entity-level due diligence and KYC workflows.
2253
+ * Evaluate a transaction against all enabled detection rules.
2254
+ * Called automatically when transactions are logged (via the client).
4949
2255
  *
4950
- * @param name - Entity name to search for
4951
- * @returns Array of matching entities with scores and metadata
4952
- */
4953
- searchEntity(name: string): Promise<Array<{
4954
- id: string;
4955
- caption: string;
4956
- score: number;
4957
- datasets: string[];
4958
- topics: string[];
4959
- }>>;
4960
- /**
4961
- * Returns true if the API was reachable on the last call.
2256
+ * @param tx - The transaction record to evaluate
2257
+ * @returns Array of detected anomalies (empty if none)
4962
2258
  */
4963
- isHealthy(): Promise<boolean>;
2259
+ evaluateTransaction(tx: TransactionRecord): AnomalyEvent[];
4964
2260
  /**
4965
- * Return operational statistics for monitoring and debugging.
4966
- */
4967
- getStats(): {
4968
- cachedEntries: number;
4969
- lastCallAt: string | null;
4970
- };
4971
- /**
4972
- * Resolve the risk category from an OpenSanctions entity's topics.
2261
+ * Evaluate a generic action against all enabled detection rules.
4973
2262
  *
4974
- * Topic mapping:
4975
- * - "sanction" -> SANCTIONS
4976
- * - "pep" -> PEP
4977
- * - "poi" -> ILLICIT_BEHAVIOR (person of interest)
4978
- * - "crime" -> ILLICIT_BEHAVIOR
4979
- * - (default) -> SANCTIONS (conservative fallback)
2263
+ * @param action - The action log to evaluate
2264
+ * @returns Array of detected anomalies (empty if none)
4980
2265
  */
4981
- private resolveCategory;
2266
+ evaluateAction(action: ActionLog): AnomalyEvent[];
4982
2267
  /**
4983
- * Resolve risk severity from the match confidence score.
4984
- *
4985
- * - >= 0.95 -> SEVERE
4986
- * - >= 0.80 -> HIGH
4987
- * - >= 0.70 -> MEDIUM
2268
+ * Check whether anomaly detection is currently enabled.
4988
2269
  */
4989
- private resolveSeverity;
2270
+ isEnabled(): boolean;
4990
2271
  /**
4991
- * Resolve recommended actions based on the risk severity.
2272
+ * Get the current detection configuration.
4992
2273
  */
4993
- private resolveActions;
2274
+ getConfig(): AnomalyDetectionConfig | null;
2275
+ private runRule;
2276
+ private runActionRule;
2277
+ private checkUnusualAmount;
2278
+ private checkFrequencySpike;
2279
+ private checkNewDestination;
2280
+ private checkOffHours;
2281
+ private checkRapidSuccession;
2282
+ private checkRoundAmount;
2283
+ private checkOffHoursAction;
2284
+ private checkActionFrequencySpike;
2285
+ private createAnomaly;
2286
+ private notifyCallbacks;
4994
2287
  }
4995
2288
 
4996
- export { type AIOperationType, type ActionLog, type AddressScreenResult, type AnomalyCallback, type AnomalyDetectionConfig, type AnomalyEvent, type AnomalyRuleType, type AnomalySeverity, type AnomalyThresholds, type ApprovalDecision, type ApprovalEvaluation, ApprovalManager, type ApprovalPolicy, type ApprovalPolicyType, type ApprovalRequest, type ApprovalStatus, type BlockedToolCall, type BlocklistConfig, BlocklistManager, type CCTPAttestationInput, type CCTPHook, type CCTPHookResult, type CCTPMessageStatus, CCTPTransferManager, type CCTPValidationCheck, type CCTPValidationResult, type CCTPVersion, type CFTCAccountClass, CFTCCompliance, type CFTCComplianceConfig, type CTRReport, type Chain, ChainalysisFreeAPIProvider, ChainalysisOracleProvider, type CircleApiAdapter, type CircleComplianceAdapter, CircleComplianceEngine, type CircleWallet, CircleWalletManager, type CircleWalletOptions, type CollateralValuation, type ComplianceCertificate, type ComplianceCheckResult, type ComplianceCheckSummary, type ComplianceReport, type CompliantTransferInput, type CompliantTransferResult, type ComprehensiveRiskFactor, type ComprehensiveRiskResult, type ComprehensiveSanctionsResult, type ConfirmCCTPTransferInput, type ConfirmTaskInput, ConsoleExporter, type CreateKontextAIInput, type CreateKontextAIResult, type CreateTaskInput, type CreateWalletOptions, type CrossChainAuditEntry, type CrossChainTransfer, type DateRange, DigestChain, type DigestLink, type DigestVerification, type DigitalAssetReport, type DigitalAssetType, type DualScreenResult, type EntityNameEntry, type Environment, type EvaluateApprovalInput, type EventExporter, type ExportFormat, type ExportOptions, type ExportResult, type ExporterResult, type FastTransferValidation, type FeatureFlag, type FeatureFlagConfig, FeatureFlagManager, FileStorage, type FlagPlanTargeting, type FlagScope, type FlagTargeting, type GasEligibility, type GasEstimate, type GasEstimateInput, type GasSponsorshipLog, type GasStationAdapter, GasStationManager, type GatedFeature, type GenerateComplianceCertificateInput, HttpExporter, type IncidentReport, type InitiateCCTPTransferInput, type InitiateFastTransferInput, JsonFileExporter, type JurisdictionFlag, Kontext, type KontextAIContext, type KontextAIOptions, KontextCloudExporter, type KontextConfig, KontextError, KontextErrorCode, type KontextMode, type LimitEvent, type ListEntry, type LogActionInput, type LogLevel, type LogReasoningInput, type LogTransactionInput, MemoryStorage, type MetadataValidator, MultiExporter, NoopExporter, OFACListProvider, OFACSanctionsScreener, OpenSanctionsProvider, type OwnershipFlag, PLAN_LIMITS, type PatternFlag, type PlanConfig, PlanManager, type PlanTier, type PlanUsage, type PrecisionTimestamp, type ProviderScreeningResult, type ReasoningEntry, type RegisterWebhookInput, type ReportOptions, type ReportSubject, type ReportType, type RiskAssessmentInput, type RiskCategory, type RiskFactor, type RiskSeverity, type RiskSignal, type SARReport, type SanctionedAddressEntry, type SanctionedEntityType, type SanctionedJurisdiction, type SanctionsCheckResult, type SanctionsList, type SanctionsListMetadata, type SanctionsMatch, type SanctionsRiskLevel, type ScreenAddressInput, type ScreenTransactionInput, type ScreenTransactionProviderInput, type ScreeningAction, ScreeningAggregator, type ScreeningAggregatorConfig, type ScreeningProvider, type SegregationCalculation, type StorageAdapter, type SubmitDecisionInput, type Task, type TaskEvidence, type TaskStatus, type Token, type TransactionDirection, type TransactionEvaluation, type TransactionForAnalysis, type TransactionRecord, type TrustFactor, type TrustScore, type UnifiedScreeningResult, UsdcCompliance, type UsdcComplianceCheck, type WalletBalance, type WalletSet, type WebhookConfig, type WebhookDeliveryResult, type WebhookEventType, WebhookManager, type WebhookPayload, type WebhookRetryConfig, type WithKontextOptions, createKontextAI, createScreeningAggregator, extractAmount, isFeatureAvailable, kontextMiddleware, kontextWrapModel, ofacScreener, requirePlan, verifyExportedChain, withKontext };
2289
+ export { type ActionLog, type AgentData, type AnomalyCallback, type AnomalyDetectionConfig, AnomalyDetector, type AnomalyEvent, type AnomalyRuleType, type AnomalySeverity, type AnomalyThresholds, type Chain, type ComplianceCertificate, type ComplianceCheckResult, type ComplianceReport, type ConfirmTaskInput, ConsoleExporter, type CreateTaskInput, type DateRange, DigestChain, type DigestLink, type DigestVerification, type Environment, type EventExporter, type ExportFormat, type ExportOptions, type ExportResult, type ExporterResult, type FeatureFlag, type FeatureFlagConfig, FeatureFlagManager, FileStorage, FirestoreStorageAdapter, type FirestoreStorageConfig, type FlagPlanTargeting, type FlagScope, type FlagTargeting, type GatedFeature, type GenerateComplianceCertificateInput, JsonFileExporter, Kontext, type KontextConfig, KontextError, KontextErrorCode, type KontextMode, type LimitEvent, type LogActionInput, type LogLevel, type LogReasoningInput, type LogTransactionInput, MemoryStorage, type MetadataValidator, NoopExporter, PLAN_LIMITS, type PlanConfig, PlanManager, type PlanTier, type PlanUsage, type PrecisionTimestamp, type ReasoningEntry, type ReportOptions, type ReportType, type RiskFactor, type SanctionsCheckResult, type StorageAdapter, type Task, type TaskEvidence, type TaskStatus, type Token, type TransactionEvaluation, type TransactionRecord, type TrustFactor, type TrustScore, TrustScorer, UsdcCompliance, type UsdcComplianceCheck, type VerifyInput, type VerifyResult, isFeatureAvailable, requirePlan, verifyExportedChain };