kontext-sdk 0.5.0 → 0.6.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.ts CHANGED
@@ -178,7 +178,7 @@ declare class FileStorage implements StorageAdapter {
178
178
  /** Supported blockchain networks */
179
179
  type Chain = 'ethereum' | 'base' | 'polygon' | 'arbitrum' | 'optimism' | 'arc' | 'avalanche' | 'solana';
180
180
  /** Supported stablecoin tokens */
181
- type Token = 'USDC' | 'USDT' | 'DAI' | 'EURC';
181
+ type Token = 'USDC' | 'USDT' | 'DAI' | 'EURC' | 'USDP' | 'USDG';
182
182
  /** SDK operating mode */
183
183
  type KontextMode = 'local' | 'cloud';
184
184
  /** Log level for the SDK logger */
@@ -373,19 +373,19 @@ interface LogActionInput {
373
373
  /** Arbitrary metadata */
374
374
  metadata?: Record<string, unknown>;
375
375
  }
376
- /** Input for logging a cryptocurrency transaction */
376
+ /** Input for logging a transaction (crypto or general payment) */
377
377
  interface LogTransactionInput {
378
- /** On-chain transaction hash */
379
- txHash: string;
380
- /** Blockchain network */
381
- chain: Chain;
378
+ /** On-chain transaction hash (required for crypto, optional for general payments) */
379
+ txHash?: string;
380
+ /** Blockchain network (required for crypto, optional for general payments) */
381
+ chain?: Chain;
382
382
  /** Transaction amount (string to preserve decimal precision) */
383
383
  amount: string;
384
- /** Token being transferred */
385
- token: Token;
386
- /** Sender address */
384
+ /** Token being transferred (required for crypto, optional for general payments) */
385
+ token?: Token;
386
+ /** Sender address or entity name */
387
387
  from: string;
388
- /** Recipient address */
388
+ /** Recipient address or entity name */
389
389
  to: string;
390
390
  /** ID of the agent initiating the transaction */
391
391
  agentId: string;
@@ -395,17 +395,28 @@ interface LogTransactionInput {
395
395
  correlationId?: string;
396
396
  /** Additional transaction metadata */
397
397
  metadata?: Record<string, unknown>;
398
+ /** Currency code for general payments (e.g., 'USD', 'EUR'). Inferred from token for crypto. */
399
+ currency?: string;
400
+ /** Payment method (e.g., 'wire', 'ach', 'card', 'crypto') */
401
+ paymentMethod?: string;
402
+ /** External payment reference (invoice ID, wire reference, etc.) */
403
+ paymentReference?: string;
398
404
  }
399
405
  /** Stored transaction record */
400
406
  interface TransactionRecord extends ActionLog {
401
407
  type: 'transaction';
402
- txHash: string;
403
- chain: Chain;
408
+ txHash?: string;
409
+ chain?: Chain;
404
410
  amount: string;
405
- token: Token;
411
+ token?: Token;
406
412
  from: string;
407
413
  to: string;
414
+ currency?: string;
415
+ paymentMethod?: string;
416
+ paymentReference?: string;
408
417
  }
418
+ /** Check whether a transaction input has all crypto-specific fields */
419
+ declare function isCryptoTransaction(input: LogTransactionInput): boolean;
409
420
  /** Input for creating a new tracked task */
410
421
  interface CreateTaskInput {
411
422
  /** Human-readable task description */
@@ -612,8 +623,8 @@ interface TrustFactor {
612
623
  }
613
624
  /** Transaction evaluation result */
614
625
  interface TransactionEvaluation {
615
- /** Transaction hash */
616
- txHash: string;
626
+ /** Transaction hash (present for crypto transactions) */
627
+ txHash?: string;
617
628
  /** Risk score (0-100, higher = more risky) */
618
629
  riskScore: number;
619
630
  /** Risk level */
@@ -946,6 +957,16 @@ declare class DigestChain {
946
957
  * This can be embedded in outgoing messages as proof of the entire action history.
947
958
  */
948
959
  getTerminalDigest(): string;
960
+ /**
961
+ * Restore the terminal digest from persisted state.
962
+ * Called after loading actions from storage so that new actions
963
+ * chain correctly from the last stored digest instead of genesis.
964
+ *
965
+ * Does NOT reconstruct the links array — in-memory verification
966
+ * via verify() will not work after restore. Use the stored action
967
+ * digest/priorDigest fields for cross-process chain verification.
968
+ */
969
+ restoreTerminalDigest(digest: string): void;
949
970
  /**
950
971
  * Get the number of links in the chain.
951
972
  */
@@ -1346,6 +1367,8 @@ declare class Kontext {
1346
1367
  /**
1347
1368
  * Restore state from the attached storage adapter.
1348
1369
  * Loads previously persisted actions, transactions, tasks, and anomalies.
1370
+ * Also restores the digest chain's terminal digest so that new actions
1371
+ * chain correctly across process boundaries.
1349
1372
  * No-op if no storage adapter is configured.
1350
1373
  */
1351
1374
  restore(): Promise<void>;
@@ -1581,7 +1604,7 @@ declare class Kontext {
1581
1604
  * and cryptographically verifies the digest chain integrity.
1582
1605
  *
1583
1606
  * The certificate includes: action/transaction/reasoning counts, digest chain
1584
- * verification status (Patent US 12,463,819 B1), the agent's current trust
1607
+ * verification status (patented), the agent's current trust
1585
1608
  * score, and an overall compliance status. A SHA-256 content hash of the
1586
1609
  * certificate itself is included for tamper-evidence.
1587
1610
  *
@@ -1665,148 +1688,6 @@ declare class Kontext {
1665
1688
  destroy(): Promise<void>;
1666
1689
  }
1667
1690
 
1668
- interface FirestoreStorageConfig {
1669
- /** GCP project ID — use "Kontext" for the Kontext production project */
1670
- gcpProjectId: string;
1671
- /**
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.
1675
- */
1676
- userId: string;
1677
- /**
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`).
1683
- */
1684
- accessToken?: string;
1685
- /**
1686
- * Firestore database ID. Defaults to '(default)'.
1687
- * Change only if you created a named database in the GCP console.
1688
- */
1689
- databaseId?: string;
1690
- /**
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
1695
- */
1696
- writeDocumentsIndividually?: boolean;
1697
- /**
1698
- * Custom Firestore REST base URL. Override for testing or emulator use.
1699
- * @default 'https://firestore.googleapis.com'
1700
- */
1701
- firestoreBaseUrl?: string;
1702
- }
1703
- /**
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".
1709
- *
1710
- * Works as a drop-in replacement for FileStorage:
1711
- *
1712
- * @example
1713
- * ```typescript
1714
- * import { Kontext, FirestoreStorageAdapter } from 'kontext-sdk';
1715
- *
1716
- * const ctx = Kontext.init({
1717
- * projectId: 'treasury-agent',
1718
- * environment: 'production',
1719
- * storage: new FirestoreStorageAdapter({
1720
- * gcpProjectId: 'Kontext',
1721
- * userId: 'user-abc123',
1722
- * }),
1723
- * });
1724
- *
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}/...
1728
- * ```
1729
- */
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);
1738
- /**
1739
- * Save data under a Kontext storage key.
1740
- *
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.
1744
- */
1745
- save(key: string, data: unknown): Promise<void>;
1746
- /**
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.
1750
- */
1751
- load(key: string): Promise<unknown | null>;
1752
- delete(key: string): Promise<void>;
1753
- list(prefix?: string): Promise<string[]>;
1754
- /**
1755
- * Write a single action log to its canonical Firestore path.
1756
- * Called by the SDK when `writeDocumentsIndividually` is true.
1757
- *
1758
- * Path: users/{userId}/projects/{projectId}/agents/{agentId}/sessions/{sessionId}/actions/{actionId}
1759
- */
1760
- writeAction(action: ActionLog): Promise<void>;
1761
- /**
1762
- * Write a single transaction record to its canonical Firestore path.
1763
- *
1764
- * Path: users/{userId}/projects/{projectId}/agents/{agentId}/sessions/{sessionId}/transactions/{txId}
1765
- */
1766
- writeTransaction(tx: TransactionRecord): Promise<void>;
1767
- /**
1768
- * Write a single task to its canonical Firestore path.
1769
- *
1770
- * Path: users/{userId}/projects/{projectId}/tasks/{taskId}
1771
- */
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;
1808
- }
1809
-
1810
1691
  /** Features gated by plan tier */
1811
1692
  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';
1812
1693
  /**
@@ -1941,6 +1822,21 @@ declare class UsdcCompliance {
1941
1822
  private static generateRecommendations;
1942
1823
  }
1943
1824
 
1825
+ declare class PaymentCompliance {
1826
+ /**
1827
+ * Run compliance checks on a general payment.
1828
+ *
1829
+ * @param input - Payment to evaluate
1830
+ * @returns UsdcComplianceCheck with pass/fail results and recommendations
1831
+ */
1832
+ static checkPayment(input: LogTransactionInput): UsdcComplianceCheck;
1833
+ private static checkAmountValid;
1834
+ private static checkEntityScreening;
1835
+ private static checkEnhancedDueDiligence;
1836
+ private static checkReportingThreshold;
1837
+ private static generateRecommendations;
1838
+ }
1839
+
1944
1840
  /**
1945
1841
  * In-memory data store for the Kontext SDK.
1946
1842
  * Holds all action logs, transactions, tasks, and anomaly events.
@@ -2286,4 +2182,4 @@ declare class AnomalyDetector {
2286
2182
  private notifyCallbacks;
2287
2183
  }
2288
2184
 
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 };
2185
+ 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, 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, PaymentCompliance, 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, isCryptoTransaction, isFeatureAvailable, requirePlan, verifyExportedChain };