kontext-sdk 0.7.0 → 0.8.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
@@ -765,10 +765,6 @@ interface VerifyInput extends LogTransactionInput {
765
765
  confidence?: number;
766
766
  /** Additional reasoning context */
767
767
  context?: Record<string, unknown>;
768
- /** When provided, anchors the terminal digest on-chain after compliance checks */
769
- anchor?: OnChainAnchorConfig;
770
- /** Counterparty agent for bilateral A2A attestation exchange */
771
- counterparty?: CounterpartyConfig;
772
768
  }
773
769
  /** Result of the verify() convenience method */
774
770
  interface VerifyResult {
@@ -794,10 +790,6 @@ interface VerifyResult {
794
790
  };
795
791
  /** Reasoning entry ID (present when reasoning was provided in input) */
796
792
  reasoningId?: string;
797
- /** On-chain anchor proof (present when anchor config provided in input) */
798
- anchorProof?: AnchorResult;
799
- /** Counterparty attestation (present when counterparty config provided in input) */
800
- counterparty?: CounterpartyAttestation;
801
793
  /** True when the transaction amount exceeds the approvalThreshold */
802
794
  requiresApproval?: boolean;
803
795
  /** The pending approval task (present when requiresApproval is true) */
@@ -860,102 +852,6 @@ interface ReasoningEntry {
860
852
  /** Context */
861
853
  context: Record<string, unknown>;
862
854
  }
863
- /** Configuration for on-chain digest anchoring */
864
- interface OnChainAnchorConfig {
865
- /** JSON-RPC URL for the target chain */
866
- rpcUrl: string;
867
- /** KontextAnchor contract address */
868
- contractAddress: string;
869
- /** Private key of the signer (hex with 0x prefix). Required for write operations. */
870
- privateKey?: string;
871
- }
872
- /** Result of an on-chain anchor transaction */
873
- interface AnchorResult {
874
- /** The digest that was anchored */
875
- digest: string;
876
- /** The on-chain transaction hash */
877
- txHash: string;
878
- /** The block number containing the anchor */
879
- blockNumber: number;
880
- /** Block timestamp (unix seconds) */
881
- timestamp: number;
882
- /** Contract address used */
883
- contractAddress: string;
884
- /** Chain the anchor was submitted to */
885
- chain: string;
886
- }
887
- /** Result of verifying an anchor on-chain */
888
- interface AnchorVerification {
889
- /** Whether the digest was found on-chain */
890
- anchored: boolean;
891
- /** The digest that was checked */
892
- digest: string;
893
- /** Anchorer address (if anchored) */
894
- anchorer?: string;
895
- /** Project hash (if anchored) */
896
- projectHash?: string;
897
- /** Block timestamp (if anchored) */
898
- timestamp?: number;
899
- }
900
- /** Agent card served at /.well-known/kontext.json */
901
- interface AgentCard {
902
- /** Agent identifier */
903
- agentId: string;
904
- /** Kontext SDK version */
905
- kontextVersion: string;
906
- /** Supported capabilities (e.g., ['verify', 'attest']) */
907
- capabilities: string[];
908
- /** Attestation endpoint path (relative to host) */
909
- attestEndpoint: string;
910
- }
911
- /** Counterparty configuration for verify() */
912
- interface CounterpartyConfig {
913
- /** Base URL of the counterparty agent (e.g., https://agent.example.com) */
914
- endpoint: string;
915
- /** Expected agent ID (optional, verified against agent card) */
916
- agentId?: string;
917
- /** Timeout for attestation exchange in milliseconds (default: 10000) */
918
- timeoutMs?: number;
919
- }
920
- /** Attestation request sent to counterparty */
921
- interface AttestationRequest {
922
- /** Sender's terminal digest */
923
- senderDigest: string;
924
- /** Sender's agent ID */
925
- senderAgentId: string;
926
- /** Transaction hash */
927
- txHash?: string;
928
- /** Chain */
929
- chain?: string;
930
- /** Transfer amount */
931
- amount: string;
932
- /** Token */
933
- token?: string;
934
- /** Timestamp of the request */
935
- timestamp: string;
936
- }
937
- /** Attestation response from counterparty */
938
- interface AttestationResponse {
939
- /** Whether the counterparty attested */
940
- attested: boolean;
941
- /** Counterparty's terminal digest */
942
- receiverDigest: string;
943
- /** Counterparty's agent ID */
944
- receiverAgentId: string;
945
- /** Timestamp of attestation */
946
- timestamp: string;
947
- }
948
- /** Counterparty attestation result included in VerifyResult */
949
- interface CounterpartyAttestation {
950
- /** Whether the counterparty successfully attested */
951
- attested: boolean;
952
- /** Counterparty's digest (proof they ran compliance) */
953
- digest: string;
954
- /** Counterparty's agent ID */
955
- agentId: string;
956
- /** Attestation timestamp */
957
- timestamp: string;
958
- }
959
855
  /** Error codes for Kontext SDK */
960
856
  declare enum KontextErrorCode {
961
857
  INITIALIZATION_ERROR = "INITIALIZATION_ERROR",
@@ -1941,57 +1837,6 @@ declare class PaymentCompliance {
1941
1837
  private static generateRecommendations;
1942
1838
  }
1943
1839
 
1944
- /**
1945
- * Verify whether a digest has been anchored on-chain.
1946
- * Uses eth_call — no signing required, no dependencies.
1947
- */
1948
- declare function verifyAnchor(rpcUrl: string, contractAddress: string, digest: string): Promise<AnchorVerification>;
1949
- /**
1950
- * Get full anchor details for a digest.
1951
- * Returns null if the digest is not anchored.
1952
- */
1953
- declare function getAnchor(rpcUrl: string, contractAddress: string, digest: string): Promise<{
1954
- anchorer: string;
1955
- projectHash: string;
1956
- timestamp: number;
1957
- } | null>;
1958
- /**
1959
- * Anchor a digest hash on-chain via the KontextAnchor contract.
1960
- * Requires viem: `npm install viem`
1961
- */
1962
- declare function anchorDigest(config: OnChainAnchorConfig, digest: string, projectId: string): Promise<AnchorResult>;
1963
- /**
1964
- * Exporter that anchors terminal digest hashes on Base chain.
1965
- * Buffers events and anchors when batchSize is reached.
1966
- */
1967
- declare class OnChainExporter implements EventExporter {
1968
- private readonly config;
1969
- private readonly projectId;
1970
- private readonly batchSize;
1971
- private readonly getTerminalDigest;
1972
- private eventCount;
1973
- constructor(config: OnChainAnchorConfig, projectId: string, getTerminalDigest: () => string);
1974
- export(events: ActionLog[]): Promise<ExporterResult>;
1975
- flush(): Promise<void>;
1976
- shutdown(): Promise<void>;
1977
- }
1978
-
1979
- /**
1980
- * Fetch the counterparty's agent card from /.well-known/kontext.json
1981
- */
1982
- declare function fetchAgentCard(endpoint: string, timeoutMs?: number): Promise<AgentCard>;
1983
- /**
1984
- * Exchange compliance attestation with a counterparty agent.
1985
- *
1986
- * Flow:
1987
- * 1. Fetch counterparty's agent card from /.well-known/kontext.json
1988
- * 2. Validate agent ID if specified
1989
- * 3. Verify counterparty supports attestation
1990
- * 4. POST attestation request to counterparty's attest endpoint
1991
- * 5. Return counterparty's attestation response
1992
- */
1993
- declare function exchangeAttestation(config: CounterpartyConfig, request: AttestationRequest): Promise<CounterpartyAttestation>;
1994
-
1995
1840
  /**
1996
1841
  * In-memory data store for the Kontext SDK.
1997
1842
  * Holds all action logs, transactions, tasks, and anomaly events.
@@ -2337,4 +2182,4 @@ declare class AnomalyDetector {
2337
2182
  private notifyCallbacks;
2338
2183
  }
2339
2184
 
2340
- export { type ActionLog, type AgentCard, type AgentData, type AnchorResult, type AnchorVerification, type AnomalyCallback, type AnomalyDetectionConfig, AnomalyDetector, type AnomalyEvent, type AnomalyRuleType, type AnomalySeverity, type AnomalyThresholds, type AttestationRequest, type AttestationResponse, type Chain, type ComplianceCertificate, type ComplianceCheckResult, type ComplianceReport, type ConfirmTaskInput, ConsoleExporter, type CounterpartyAttestation, type CounterpartyConfig, 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, type OnChainAnchorConfig, OnChainExporter, 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, anchorDigest, exchangeAttestation, fetchAgentCard, getAnchor, isCryptoTransaction, isFeatureAvailable, requirePlan, verifyAnchor, 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 };
package/dist/index.d.ts CHANGED
@@ -765,10 +765,6 @@ interface VerifyInput extends LogTransactionInput {
765
765
  confidence?: number;
766
766
  /** Additional reasoning context */
767
767
  context?: Record<string, unknown>;
768
- /** When provided, anchors the terminal digest on-chain after compliance checks */
769
- anchor?: OnChainAnchorConfig;
770
- /** Counterparty agent for bilateral A2A attestation exchange */
771
- counterparty?: CounterpartyConfig;
772
768
  }
773
769
  /** Result of the verify() convenience method */
774
770
  interface VerifyResult {
@@ -794,10 +790,6 @@ interface VerifyResult {
794
790
  };
795
791
  /** Reasoning entry ID (present when reasoning was provided in input) */
796
792
  reasoningId?: string;
797
- /** On-chain anchor proof (present when anchor config provided in input) */
798
- anchorProof?: AnchorResult;
799
- /** Counterparty attestation (present when counterparty config provided in input) */
800
- counterparty?: CounterpartyAttestation;
801
793
  /** True when the transaction amount exceeds the approvalThreshold */
802
794
  requiresApproval?: boolean;
803
795
  /** The pending approval task (present when requiresApproval is true) */
@@ -860,102 +852,6 @@ interface ReasoningEntry {
860
852
  /** Context */
861
853
  context: Record<string, unknown>;
862
854
  }
863
- /** Configuration for on-chain digest anchoring */
864
- interface OnChainAnchorConfig {
865
- /** JSON-RPC URL for the target chain */
866
- rpcUrl: string;
867
- /** KontextAnchor contract address */
868
- contractAddress: string;
869
- /** Private key of the signer (hex with 0x prefix). Required for write operations. */
870
- privateKey?: string;
871
- }
872
- /** Result of an on-chain anchor transaction */
873
- interface AnchorResult {
874
- /** The digest that was anchored */
875
- digest: string;
876
- /** The on-chain transaction hash */
877
- txHash: string;
878
- /** The block number containing the anchor */
879
- blockNumber: number;
880
- /** Block timestamp (unix seconds) */
881
- timestamp: number;
882
- /** Contract address used */
883
- contractAddress: string;
884
- /** Chain the anchor was submitted to */
885
- chain: string;
886
- }
887
- /** Result of verifying an anchor on-chain */
888
- interface AnchorVerification {
889
- /** Whether the digest was found on-chain */
890
- anchored: boolean;
891
- /** The digest that was checked */
892
- digest: string;
893
- /** Anchorer address (if anchored) */
894
- anchorer?: string;
895
- /** Project hash (if anchored) */
896
- projectHash?: string;
897
- /** Block timestamp (if anchored) */
898
- timestamp?: number;
899
- }
900
- /** Agent card served at /.well-known/kontext.json */
901
- interface AgentCard {
902
- /** Agent identifier */
903
- agentId: string;
904
- /** Kontext SDK version */
905
- kontextVersion: string;
906
- /** Supported capabilities (e.g., ['verify', 'attest']) */
907
- capabilities: string[];
908
- /** Attestation endpoint path (relative to host) */
909
- attestEndpoint: string;
910
- }
911
- /** Counterparty configuration for verify() */
912
- interface CounterpartyConfig {
913
- /** Base URL of the counterparty agent (e.g., https://agent.example.com) */
914
- endpoint: string;
915
- /** Expected agent ID (optional, verified against agent card) */
916
- agentId?: string;
917
- /** Timeout for attestation exchange in milliseconds (default: 10000) */
918
- timeoutMs?: number;
919
- }
920
- /** Attestation request sent to counterparty */
921
- interface AttestationRequest {
922
- /** Sender's terminal digest */
923
- senderDigest: string;
924
- /** Sender's agent ID */
925
- senderAgentId: string;
926
- /** Transaction hash */
927
- txHash?: string;
928
- /** Chain */
929
- chain?: string;
930
- /** Transfer amount */
931
- amount: string;
932
- /** Token */
933
- token?: string;
934
- /** Timestamp of the request */
935
- timestamp: string;
936
- }
937
- /** Attestation response from counterparty */
938
- interface AttestationResponse {
939
- /** Whether the counterparty attested */
940
- attested: boolean;
941
- /** Counterparty's terminal digest */
942
- receiverDigest: string;
943
- /** Counterparty's agent ID */
944
- receiverAgentId: string;
945
- /** Timestamp of attestation */
946
- timestamp: string;
947
- }
948
- /** Counterparty attestation result included in VerifyResult */
949
- interface CounterpartyAttestation {
950
- /** Whether the counterparty successfully attested */
951
- attested: boolean;
952
- /** Counterparty's digest (proof they ran compliance) */
953
- digest: string;
954
- /** Counterparty's agent ID */
955
- agentId: string;
956
- /** Attestation timestamp */
957
- timestamp: string;
958
- }
959
855
  /** Error codes for Kontext SDK */
960
856
  declare enum KontextErrorCode {
961
857
  INITIALIZATION_ERROR = "INITIALIZATION_ERROR",
@@ -1941,57 +1837,6 @@ declare class PaymentCompliance {
1941
1837
  private static generateRecommendations;
1942
1838
  }
1943
1839
 
1944
- /**
1945
- * Verify whether a digest has been anchored on-chain.
1946
- * Uses eth_call — no signing required, no dependencies.
1947
- */
1948
- declare function verifyAnchor(rpcUrl: string, contractAddress: string, digest: string): Promise<AnchorVerification>;
1949
- /**
1950
- * Get full anchor details for a digest.
1951
- * Returns null if the digest is not anchored.
1952
- */
1953
- declare function getAnchor(rpcUrl: string, contractAddress: string, digest: string): Promise<{
1954
- anchorer: string;
1955
- projectHash: string;
1956
- timestamp: number;
1957
- } | null>;
1958
- /**
1959
- * Anchor a digest hash on-chain via the KontextAnchor contract.
1960
- * Requires viem: `npm install viem`
1961
- */
1962
- declare function anchorDigest(config: OnChainAnchorConfig, digest: string, projectId: string): Promise<AnchorResult>;
1963
- /**
1964
- * Exporter that anchors terminal digest hashes on Base chain.
1965
- * Buffers events and anchors when batchSize is reached.
1966
- */
1967
- declare class OnChainExporter implements EventExporter {
1968
- private readonly config;
1969
- private readonly projectId;
1970
- private readonly batchSize;
1971
- private readonly getTerminalDigest;
1972
- private eventCount;
1973
- constructor(config: OnChainAnchorConfig, projectId: string, getTerminalDigest: () => string);
1974
- export(events: ActionLog[]): Promise<ExporterResult>;
1975
- flush(): Promise<void>;
1976
- shutdown(): Promise<void>;
1977
- }
1978
-
1979
- /**
1980
- * Fetch the counterparty's agent card from /.well-known/kontext.json
1981
- */
1982
- declare function fetchAgentCard(endpoint: string, timeoutMs?: number): Promise<AgentCard>;
1983
- /**
1984
- * Exchange compliance attestation with a counterparty agent.
1985
- *
1986
- * Flow:
1987
- * 1. Fetch counterparty's agent card from /.well-known/kontext.json
1988
- * 2. Validate agent ID if specified
1989
- * 3. Verify counterparty supports attestation
1990
- * 4. POST attestation request to counterparty's attest endpoint
1991
- * 5. Return counterparty's attestation response
1992
- */
1993
- declare function exchangeAttestation(config: CounterpartyConfig, request: AttestationRequest): Promise<CounterpartyAttestation>;
1994
-
1995
1840
  /**
1996
1841
  * In-memory data store for the Kontext SDK.
1997
1842
  * Holds all action logs, transactions, tasks, and anomaly events.
@@ -2337,4 +2182,4 @@ declare class AnomalyDetector {
2337
2182
  private notifyCallbacks;
2338
2183
  }
2339
2184
 
2340
- export { type ActionLog, type AgentCard, type AgentData, type AnchorResult, type AnchorVerification, type AnomalyCallback, type AnomalyDetectionConfig, AnomalyDetector, type AnomalyEvent, type AnomalyRuleType, type AnomalySeverity, type AnomalyThresholds, type AttestationRequest, type AttestationResponse, type Chain, type ComplianceCertificate, type ComplianceCheckResult, type ComplianceReport, type ConfirmTaskInput, ConsoleExporter, type CounterpartyAttestation, type CounterpartyConfig, 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, type OnChainAnchorConfig, OnChainExporter, 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, anchorDigest, exchangeAttestation, fetchAgentCard, getAnchor, isCryptoTransaction, isFeatureAvailable, requirePlan, verifyAnchor, 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 };
package/dist/index.js CHANGED
@@ -25,229 +25,12 @@ function _interopNamespace(e) {
25
25
  var fs4__namespace = /*#__PURE__*/_interopNamespace(fs4);
26
26
  var path4__namespace = /*#__PURE__*/_interopNamespace(path4);
27
27
 
28
- var __defProp = Object.defineProperty;
29
- var __getOwnPropNames = Object.getOwnPropertyNames;
30
28
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
31
29
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
32
30
  }) : x)(function(x) {
33
31
  if (typeof require !== "undefined") return require.apply(this, arguments);
34
32
  throw Error('Dynamic require of "' + x + '" is not supported');
35
33
  });
36
- var __esm = (fn, res) => function __init() {
37
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
38
- };
39
- var __export = (target, all) => {
40
- for (var name in all)
41
- __defProp(target, name, { get: all[name], enumerable: true });
42
- };
43
-
44
- // src/onchain.ts
45
- var onchain_exports = {};
46
- __export(onchain_exports, {
47
- OnChainExporter: () => exports.OnChainExporter,
48
- anchorDigest: () => anchorDigest,
49
- getAnchor: () => getAnchor,
50
- verifyAnchor: () => verifyAnchor
51
- });
52
- async function rpcCall(rpcUrl, method, params) {
53
- const res = await fetch(rpcUrl, {
54
- method: "POST",
55
- headers: { "Content-Type": "application/json" },
56
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params })
57
- });
58
- const json = await res.json();
59
- if (json.error) throw new Error(`RPC error: ${json.error.message}`);
60
- return json.result;
61
- }
62
- function encodeBytes32(hex) {
63
- const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
64
- return clean.padStart(64, "0");
65
- }
66
- function decodeUint256(hex) {
67
- const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
68
- return parseInt(clean, 16);
69
- }
70
- function decodeAddress(hex) {
71
- const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
72
- return "0x" + clean.slice(24);
73
- }
74
- async function verifyAnchor(rpcUrl, contractAddress, digest) {
75
- const calldata = SEL_VERIFY + encodeBytes32(digest);
76
- const result = await rpcCall(rpcUrl, "eth_call", [
77
- { to: contractAddress, data: calldata },
78
- "latest"
79
- ]);
80
- const anchored = decodeUint256(result) !== 0;
81
- return { anchored, digest };
82
- }
83
- async function getAnchor(rpcUrl, contractAddress, digest) {
84
- const calldata = SEL_GET_ANCHOR + encodeBytes32(digest);
85
- try {
86
- const result = await rpcCall(rpcUrl, "eth_call", [
87
- { to: contractAddress, data: calldata },
88
- "latest"
89
- ]);
90
- const clean = result.startsWith("0x") ? result.slice(2) : result;
91
- if (clean.length < 192) return null;
92
- const anchorer = decodeAddress(clean.slice(0, 64));
93
- const projectHash = "0x" + clean.slice(64, 128);
94
- const timestamp = decodeUint256("0x" + clean.slice(128, 192));
95
- return { anchorer, projectHash, timestamp };
96
- } catch {
97
- return null;
98
- }
99
- }
100
- async function anchorDigest(config, digest, projectId) {
101
- let viem;
102
- let viemChains;
103
- let viemAccounts;
104
- try {
105
- viem = await import('viem');
106
- viemChains = await import('viem/chains');
107
- viemAccounts = await import('viem/accounts');
108
- } catch {
109
- throw new Error(
110
- "On-chain anchoring requires viem. Install it: npm install viem"
111
- );
112
- }
113
- if (!config.privateKey) {
114
- throw new Error("privateKey is required for on-chain anchoring");
115
- }
116
- const account = viemAccounts.privateKeyToAccount(config.privateKey);
117
- const chain = config.rpcUrl.includes("sepolia") ? viemChains.baseSepolia : viemChains.base;
118
- const client = viem.createWalletClient({
119
- account,
120
- chain,
121
- transport: viem.http(config.rpcUrl)
122
- });
123
- const publicClient = viem.createPublicClient({
124
- chain,
125
- transport: viem.http(config.rpcUrl)
126
- });
127
- const projectHash = viem.keccak256(viem.toBytes(projectId));
128
- const digestBytes32 = digest.startsWith("0x") ? digest : `0x${digest}`;
129
- const abi = [
130
- {
131
- name: "anchor",
132
- type: "function",
133
- stateMutability: "nonpayable",
134
- inputs: [
135
- { name: "digest", type: "bytes32" },
136
- { name: "projectHash", type: "bytes32" }
137
- ],
138
- outputs: []
139
- }
140
- ];
141
- const txHash = await client.writeContract({
142
- address: config.contractAddress,
143
- abi,
144
- functionName: "anchor",
145
- args: [digestBytes32, projectHash]
146
- });
147
- const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
148
- return {
149
- digest,
150
- txHash,
151
- blockNumber: Number(receipt.blockNumber),
152
- timestamp: Math.floor(Date.now() / 1e3),
153
- contractAddress: config.contractAddress,
154
- chain: chain.name.toLowerCase()
155
- };
156
- }
157
- var SEL_VERIFY, SEL_GET_ANCHOR; exports.OnChainExporter = void 0;
158
- var init_onchain = __esm({
159
- "src/onchain.ts"() {
160
- SEL_VERIFY = "0x75e36616";
161
- SEL_GET_ANCHOR = "0x7feb51d9";
162
- exports.OnChainExporter = class {
163
- config;
164
- projectId;
165
- batchSize;
166
- getTerminalDigest;
167
- eventCount = 0;
168
- constructor(config, projectId, getTerminalDigest) {
169
- this.config = config;
170
- this.projectId = projectId;
171
- this.batchSize = 10;
172
- this.getTerminalDigest = getTerminalDigest;
173
- }
174
- async export(events) {
175
- this.eventCount += events.length;
176
- if (this.eventCount >= this.batchSize) {
177
- const digest = this.getTerminalDigest();
178
- await anchorDigest(this.config, digest, this.projectId);
179
- this.eventCount = 0;
180
- }
181
- return { success: true, exportedCount: events.length };
182
- }
183
- async flush() {
184
- if (this.eventCount > 0) {
185
- const digest = this.getTerminalDigest();
186
- await anchorDigest(this.config, digest, this.projectId);
187
- this.eventCount = 0;
188
- }
189
- }
190
- async shutdown() {
191
- await this.flush();
192
- }
193
- };
194
- }
195
- });
196
-
197
- // src/attestation.ts
198
- var attestation_exports = {};
199
- __export(attestation_exports, {
200
- exchangeAttestation: () => exchangeAttestation,
201
- fetchAgentCard: () => fetchAgentCard
202
- });
203
- async function fetchAgentCard(endpoint, timeoutMs = DEFAULT_TIMEOUT_MS) {
204
- const url = `${endpoint.replace(/\/$/, "")}/.well-known/kontext.json`;
205
- const response = await fetch(url, {
206
- signal: AbortSignal.timeout(timeoutMs),
207
- headers: { Accept: "application/json" }
208
- });
209
- if (!response.ok) {
210
- throw new Error(`Failed to fetch agent card from ${url}: ${response.status}`);
211
- }
212
- return response.json();
213
- }
214
- async function exchangeAttestation(config, request) {
215
- const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
216
- const card = await fetchAgentCard(config.endpoint, timeoutMs);
217
- if (config.agentId && card.agentId !== config.agentId) {
218
- throw new Error(
219
- `Agent ID mismatch: expected ${config.agentId}, got ${card.agentId}`
220
- );
221
- }
222
- if (!card.capabilities.includes("attest")) {
223
- throw new Error(
224
- `Counterparty ${card.agentId} does not support attestation`
225
- );
226
- }
227
- const attestUrl = `${config.endpoint.replace(/\/$/, "")}${card.attestEndpoint}`;
228
- const response = await fetch(attestUrl, {
229
- method: "POST",
230
- headers: { "Content-Type": "application/json" },
231
- body: JSON.stringify(request),
232
- signal: AbortSignal.timeout(timeoutMs)
233
- });
234
- if (!response.ok) {
235
- throw new Error(`Attestation request failed: ${response.status}`);
236
- }
237
- const result = await response.json();
238
- return {
239
- attested: result.attested,
240
- digest: result.receiverDigest,
241
- agentId: result.receiverAgentId,
242
- timestamp: result.timestamp
243
- };
244
- }
245
- var DEFAULT_TIMEOUT_MS;
246
- var init_attestation = __esm({
247
- "src/attestation.ts"() {
248
- DEFAULT_TIMEOUT_MS = 1e4;
249
- }
250
- });
251
34
 
252
35
  // src/utils.ts
253
36
  function generateId() {
@@ -3995,24 +3778,6 @@ var Kontext = class _Kontext {
3995
3778
  const verification = this.verifyDigestChain();
3996
3779
  const chainLength = this.logger.getDigestChain().getChainLength();
3997
3780
  const terminalDigest = this.getTerminalDigest();
3998
- let anchorProof;
3999
- if (input.anchor) {
4000
- const { anchorDigest: anchorDigest2 } = await Promise.resolve().then(() => (init_onchain(), onchain_exports));
4001
- anchorProof = await anchorDigest2(input.anchor, terminalDigest, this.config.projectId);
4002
- }
4003
- let counterpartyResult;
4004
- if (input.counterparty) {
4005
- const { exchangeAttestation: exchangeAttestation2 } = await Promise.resolve().then(() => (init_attestation(), attestation_exports));
4006
- counterpartyResult = await exchangeAttestation2(input.counterparty, {
4007
- senderDigest: terminalDigest,
4008
- senderAgentId: input.agentId,
4009
- txHash: input.txHash,
4010
- chain: input.chain,
4011
- amount: input.amount,
4012
- token: input.token,
4013
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
4014
- });
4015
- }
4016
3781
  let requiresApproval;
4017
3782
  let task;
4018
3783
  if (this.config.approvalThreshold) {
@@ -4054,9 +3819,7 @@ var Kontext = class _Kontext {
4054
3819
  valid: verification.valid
4055
3820
  },
4056
3821
  ...reasoningId ? { reasoningId } : {},
4057
- ...requiresApproval ? { requiresApproval, task } : {},
4058
- ...anchorProof ? { anchorProof } : {},
4059
- ...counterpartyResult ? { counterparty: counterpartyResult } : {}
3822
+ ...requiresApproval ? { requiresApproval, task } : {}
4060
3823
  };
4061
3824
  }
4062
3825
  // --------------------------------------------------------------------------
@@ -4437,10 +4200,6 @@ var FileStorage = class {
4437
4200
  }
4438
4201
  };
4439
4202
 
4440
- // src/index.ts
4441
- init_onchain();
4442
- init_attestation();
4443
-
4444
4203
  exports.AnomalyDetector = AnomalyDetector;
4445
4204
  exports.ConsoleExporter = ConsoleExporter;
4446
4205
  exports.DigestChain = DigestChain;
@@ -4457,14 +4216,9 @@ exports.PaymentCompliance = PaymentCompliance;
4457
4216
  exports.PlanManager = PlanManager;
4458
4217
  exports.TrustScorer = TrustScorer;
4459
4218
  exports.UsdcCompliance = UsdcCompliance;
4460
- exports.anchorDigest = anchorDigest;
4461
- exports.exchangeAttestation = exchangeAttestation;
4462
- exports.fetchAgentCard = fetchAgentCard;
4463
- exports.getAnchor = getAnchor;
4464
4219
  exports.isCryptoTransaction = isCryptoTransaction;
4465
4220
  exports.isFeatureAvailable = isFeatureAvailable;
4466
4221
  exports.requirePlan = requirePlan;
4467
- exports.verifyAnchor = verifyAnchor;
4468
4222
  exports.verifyExportedChain = verifyExportedChain;
4469
4223
  //# sourceMappingURL=index.js.map
4470
4224
  //# sourceMappingURL=index.js.map