@highway1/core 0.1.63 → 0.1.78

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
@@ -59,23 +59,120 @@ declare function signMessage(payload: Uint8Array, privateKey: Uint8Array, public
59
59
  */
60
60
  declare function verifyMessage(signedMessage: SignedMessage, expectedPublicKey: Uint8Array): Promise<boolean>;
61
61
 
62
+ /**
63
+ * Agent Aliases - CVP-0014 Part 1
64
+ *
65
+ * Local petname-to-DID mapping for easier agent addressing.
66
+ * Aliases are stored in ~/.clawiverse/config.json under the "aliases" key.
67
+ *
68
+ * Note: This module provides the core logic. The actual config storage
69
+ * is handled by the CLI layer (packages/cli/src/config.ts).
70
+ */
71
+ interface AliasMap {
72
+ [alias: string]: string;
73
+ }
74
+ /**
75
+ * Validate alias name according to CVP-0014 rules:
76
+ * - Lowercase alphanumeric + hyphens: [a-z0-9][a-z0-9-]*
77
+ * - Max 32 characters
78
+ * - Cannot start with "did:" (reserved for DID prefix detection)
79
+ */
80
+ declare function validateAliasName(alias: string): {
81
+ valid: boolean;
82
+ error?: string;
83
+ };
84
+ /**
85
+ * Resolve a DID from various input formats:
86
+ * 1. If input starts with "did:" → return as-is
87
+ * 2. If input matches a local alias → return the mapped DID (caller must provide aliases)
88
+ * 3. Otherwise → return undefined (caller can attempt discovery)
89
+ */
90
+ declare function resolveDid(input: string, aliases: AliasMap): string | undefined;
91
+ /**
92
+ * Reverse lookup: find alias for a DID
93
+ * Returns the first matching alias, or undefined if no alias exists
94
+ */
95
+ declare function reverseAlias(did: string, aliases: AliasMap): string | undefined;
96
+ /**
97
+ * Format DID for display with optional alias
98
+ * Returns: "alias" if alias exists, otherwise full DID
99
+ */
100
+ declare function formatDidWithAlias(did: string, aliases: AliasMap): string;
101
+ /**
102
+ * Format DID for detailed display with alias
103
+ * Returns: "alias (did:...)" if alias exists, otherwise full DID
104
+ */
105
+ declare function formatDidWithAliasDetailed(did: string, aliases: AliasMap, truncate?: boolean): string;
106
+
107
+ interface DIDDocument {
108
+ '@context': string[];
109
+ id: string;
110
+ verificationMethod: VerificationMethod[];
111
+ authentication: string[];
112
+ assertionMethod: string[];
113
+ keyAgreement?: string[];
114
+ service?: ServiceEndpoint[];
115
+ }
116
+ interface VerificationMethod {
117
+ id: string;
118
+ type: string;
119
+ controller: string;
120
+ publicKeyMultibase: string;
121
+ }
122
+ interface ServiceEndpoint {
123
+ id: string;
124
+ type: string;
125
+ serviceEndpoint: string;
126
+ }
127
+ /**
128
+ * Create a DID Document for a did:clawiverse identity
129
+ */
130
+ declare function createDIDDocument(publicKey: Uint8Array, services?: ServiceEndpoint[]): DIDDocument;
131
+ /**
132
+ * Validate a DID Document structure
133
+ */
134
+ declare function validateDIDDocument(doc: unknown): doc is DIDDocument;
135
+
136
+ interface AnonymousIdentity {
137
+ did: string;
138
+ publicKey: string;
139
+ privateKey: string;
140
+ agentCard: {
141
+ name: string;
142
+ description: string;
143
+ capabilities: string[];
144
+ };
145
+ }
146
+ /**
147
+ * Generate an anonymous identity for frictionless onboarding
148
+ * Creates identity with pattern "Agent-{last8chars_of_DID}" and generic description
149
+ */
150
+ declare function generateAnonymousIdentity(): Promise<AnonymousIdentity>;
151
+
62
152
  /**
63
153
  * Trust Score System
64
154
  *
65
155
  * Tracks agent reputation based on interactions, endorsements,
66
156
  * and network behavior.
67
157
  */
158
+ /**
159
+ * Trust status for an agent
160
+ */
161
+ type TrustStatus = 'unknown' | 'known' | 'suspicious' | 'blocked' | 'allowed';
68
162
  /**
69
163
  * Trust Score Metrics
70
164
  */
71
165
  interface TrustScore {
72
166
  interactionScore: number;
73
167
  endorsements: number;
168
+ endorsementScore: number;
74
169
  completionRate: number;
75
170
  responseTime: number;
76
171
  uptime: number;
77
172
  lastUpdated: number;
78
173
  totalInteractions: number;
174
+ recentSuccessRate: number;
175
+ status: TrustStatus;
79
176
  }
80
177
  /**
81
178
  * Interaction Record
@@ -95,6 +192,7 @@ interface Interaction {
95
192
  interface InteractionStats {
96
193
  totalInteractions: number;
97
194
  successRate: number;
195
+ recentSuccessRate: number;
98
196
  avgResponseTime: number;
99
197
  lastInteraction: number;
100
198
  }
@@ -103,11 +201,15 @@ interface InteractionStats {
103
201
  */
104
202
  declare class TrustMetrics {
105
203
  /**
106
- * Calculate trust score from interaction history
204
+ * Calculate trust score from interaction history.
205
+ * @param endorsementScore - Average endorsement score (0-1), not count
107
206
  */
108
- calculateScore(stats: InteractionStats, endorsements: number, uptime: number): TrustScore;
207
+ calculateScore(stats: InteractionStats, endorsementScore: number, uptime: number): TrustScore;
208
+ private deriveStatus;
109
209
  /**
110
210
  * Calculate overall trust level (0-1)
211
+ * @param score - TrustScore
212
+ * @param endorsementScore - Average endorsement score (0-1)
111
213
  */
112
214
  calculateOverallTrust(score: TrustScore): number;
113
215
  /**
@@ -202,7 +304,7 @@ declare function downgradeToLegacyCard(card: AgentCard): LegacyAgentCard;
202
304
  */
203
305
 
204
306
  declare const RELAY_PROTOCOL_VERSION = 1;
205
- type RelayMessageType = 'HELLO' | 'WELCOME' | 'SEND' | 'DELIVER' | 'DISCOVER' | 'DISCOVERED' | 'PING' | 'PONG' | 'ACK' | 'DELIVERY_REPORT' | 'FETCH_CARD' | 'CARD' | 'GOODBYE' | 'INDEX_SYNC' | 'ROUTE' | 'SYNC_HELLO' | 'SYNC_REQUEST' | 'SYNC_RESPONSE' | 'SYNC_PUSH' | 'SYNC_RECONCILE';
307
+ type RelayMessageType = 'HELLO' | 'WELCOME' | 'SEND' | 'DELIVER' | 'DISCOVER' | 'DISCOVERED' | 'PING' | 'PONG' | 'ACK' | 'DELIVERY_REPORT' | 'FETCH_CARD' | 'CARD' | 'GOODBYE' | 'INDEX_SYNC' | 'ROUTE' | 'SYNC_HELLO' | 'SYNC_REQUEST' | 'SYNC_RESPONSE' | 'SYNC_PUSH' | 'SYNC_RECONCILE' | 'ENDORSE' | 'ENDORSE_ACK' | 'TRUST_QUERY' | 'TRUST_RESULT' | 'PUBLISH_CARD' | 'UNPUBLISH_CARD';
206
308
  interface HelloMessage {
207
309
  type: 'HELLO';
208
310
  protocolVersion: number;
@@ -325,7 +427,40 @@ interface SyncReconcileMessage {
325
427
  type: 'SYNC_RECONCILE';
326
428
  dids: string[];
327
429
  }
328
- type RelayMessage = HelloMessage | WelcomeMessage | SendMessage | DeliverMessage | DiscoverMessage | DiscoveredMessage | AckMessage | DeliveryReportMessage | PingMessage | PongMessage | FetchCardMessage | CardMessage | GoodbyeMessage | IndexSyncMessage | RouteMessage | SyncHelloMessage | SyncRequestMessage | SyncResponseMessage | SyncPushMessage | SyncReconcileMessage;
430
+ interface TrustQueryMessage {
431
+ type: 'TRUST_QUERY';
432
+ target: string;
433
+ domain?: string;
434
+ since?: number;
435
+ cursor?: string;
436
+ }
437
+ interface TrustResultEndorsement {
438
+ version: 2;
439
+ from: string;
440
+ to: string;
441
+ score: number;
442
+ domain?: string;
443
+ reason: string;
444
+ timestamp: number;
445
+ expires?: number;
446
+ signature: string;
447
+ }
448
+ interface TrustResultMessage {
449
+ type: 'TRUST_RESULT';
450
+ target: string;
451
+ endorsements: TrustResultEndorsement[];
452
+ endorsementCount: number;
453
+ averageScore: number;
454
+ nextCursor?: string;
455
+ }
456
+ interface PublishCardMessage {
457
+ type: 'PUBLISH_CARD';
458
+ card?: AgentCard;
459
+ }
460
+ interface UnpublishCardMessage {
461
+ type: 'UNPUBLISH_CARD';
462
+ }
463
+ type RelayMessage = HelloMessage | WelcomeMessage | SendMessage | DeliverMessage | DiscoverMessage | DiscoveredMessage | AckMessage | DeliveryReportMessage | PingMessage | PongMessage | FetchCardMessage | CardMessage | GoodbyeMessage | IndexSyncMessage | RouteMessage | SyncHelloMessage | SyncRequestMessage | SyncResponseMessage | SyncPushMessage | SyncReconcileMessage | TrustQueryMessage | TrustResultMessage | PublishCardMessage | UnpublishCardMessage;
329
464
 
330
465
  /**
331
466
  * CVP-0011: WebSocket relay client with reconnection logic
@@ -351,6 +486,9 @@ interface RelayClient {
351
486
  sendEnvelope(toDid: string, envelopeBytes: Uint8Array): Promise<void>;
352
487
  discover(query: string, minTrust?: number, limit?: number): Promise<DiscoveredAgent[]>;
353
488
  fetchCard(did: string): Promise<AgentCard | null>;
489
+ queryTrust(target: string, domain?: string, since?: number, cursor?: string): Promise<TrustResultMessage>;
490
+ publishCard(card?: AgentCard): Promise<void>;
491
+ unpublishCard(): Promise<void>;
354
492
  onDeliver(handler: MessageDeliveryHandler): void;
355
493
  onDeliveryReport(handler: DeliveryReportHandler): void;
356
494
  isConnected(): boolean;
@@ -467,12 +605,15 @@ declare function isValidContext(context: unknown): boolean;
467
605
  * Agent Card Encoder - Dual Encoding Support
468
606
  *
469
607
  * Provides bidirectional conversion between:
470
- * - CBOR (compact binary) for DHT storage
608
+ * - CBOR (compact binary) for relay/discovery storage compatibility
471
609
  * - JSON-LD (semantic) for Web publishing
472
610
  */
473
611
 
474
612
  /**
475
- * Encode Agent Card as CBOR for DHT storage
613
+ * Encode Agent Card as compact CBOR.
614
+ *
615
+ * The helper keeps its historical name because older APIs referenced
616
+ * "DHT encoding", but the current architecture uses relay-backed discovery.
476
617
  */
477
618
  declare function encodeForDHT(card: AgentCard): Uint8Array;
478
619
  /**
@@ -500,14 +641,10 @@ declare function getEncodedSize(card: AgentCard): {
500
641
  };
501
642
 
502
643
  /**
503
- * Search Index for Agent Discovery
504
- *
505
- * Maintains a local index of discovered agents for fast semantic search
644
+ * CVP-0011: Relay-backed discovery operations
645
+ * Keeps a legacy discovery-operations shape, but is fully backed by relay queries.
506
646
  */
507
647
 
508
- /**
509
- * Semantic Query Interface
510
- */
511
648
  interface SemanticQuery {
512
649
  text?: string;
513
650
  capability?: string;
@@ -519,68 +656,6 @@ interface SemanticQuery {
519
656
  };
520
657
  limit?: number;
521
658
  }
522
- /**
523
- * Search Result with Score
524
- */
525
- interface SearchResult {
526
- card: AgentCard;
527
- score: number;
528
- }
529
- /**
530
- * Search Index Implementation
531
- */
532
- declare class SearchIndex {
533
- private cards;
534
- private lunrIndex?;
535
- private fuse?;
536
- private needsRebuild;
537
- /**
538
- * Add or update an Agent Card in the index
539
- */
540
- indexAgentCard(card: AgentCard): void;
541
- /**
542
- * Remove an Agent Card from the index
543
- */
544
- removeAgentCard(did: string): void;
545
- /**
546
- * Search for agents matching a query
547
- */
548
- search(query: SemanticQuery): SearchResult[];
549
- /**
550
- * Get all indexed cards
551
- */
552
- getAllCards(): AgentCard[];
553
- /**
554
- * Clear the index
555
- */
556
- clear(): void;
557
- /**
558
- * Get index size
559
- */
560
- size(): number;
561
- /**
562
- * Rebuild search indexes
563
- */
564
- private rebuild;
565
- /**
566
- * Search by text using Lunr
567
- */
568
- private searchByText;
569
- /**
570
- * Search by capability using Fuse
571
- */
572
- private searchByCapability;
573
- /**
574
- * Apply filters to search results
575
- */
576
- private applyFilters;
577
- }
578
-
579
- /**
580
- * CVP-0011: Relay-backed discovery operations
581
- * Implements the same DHTOperations interface shape but backed by relay queries
582
- */
583
-
584
659
  interface RelayIndexOperations {
585
660
  publishAgentCard: (card: AgentCard) => Promise<void>;
586
661
  queryAgentCard: (did: string) => Promise<AgentCard | null>;
@@ -596,161 +671,32 @@ interface RelayIndexOperations {
596
671
  */
597
672
  declare function createRelayIndexOperations(client: RelayClient): RelayIndexOperations;
598
673
 
599
- /**
600
- * Capability Matcher
601
- *
602
- * Matches semantic queries against agent capabilities
603
- */
604
-
605
- /**
606
- * Capability Matcher
607
- */
608
- declare class CapabilityMatcher {
609
- /**
610
- * Match a query against a capability
611
- * Returns a score between 0 and 1
612
- */
613
- match(query: SemanticQuery, capability: Capability): number;
614
- /**
615
- * Extract keywords from natural language text
616
- */
617
- extractKeywords(text: string): string[];
618
- /**
619
- * Match keywords against capability
620
- */
621
- matchKeywords(keywords: string[], capability: Capability): number;
622
- /**
623
- * Check if query matches capability type hierarchy
624
- */
625
- matchesType(query: string, type: string): boolean;
626
- /**
627
- * Fuzzy string matching using Levenshtein distance
628
- */
629
- private fuzzyMatch;
630
- /**
631
- * Calculate Levenshtein distance between two strings
632
- */
633
- private levenshteinDistance;
634
- }
635
-
636
- interface ResolvedDID {
637
- peerId: string;
638
- multiaddrs: string[];
639
- }
640
- interface DHTOperations {
641
- publishAgentCard: (card: AgentCard) => Promise<void>;
642
- queryAgentCard: (did: string) => Promise<AgentCard | null>;
643
- queryByCapability: (capability: string) => Promise<AgentCard[]>;
644
- searchSemantic: (query: SemanticQuery) => Promise<AgentCard[]>;
645
- resolveDID: (did: string) => Promise<ResolvedDID | null>;
646
- queryRelayPeers: () => Promise<string[]>;
647
- }
648
-
649
- /**
650
- * Semantic Search Engine
651
- *
652
- * Provides intelligent agent discovery through semantic search
653
- * with local-first strategy and network fallback
654
- */
655
-
656
- /**
657
- * Semantic Search Engine
658
- */
659
- declare class SemanticSearchEngine {
660
- private dht?;
661
- private index;
662
- private matcher;
663
- constructor(dht?: DHTOperations | undefined);
664
- /**
665
- * Main search interface
666
- * Local-first with network fallback
667
- */
668
- search(query: SemanticQuery): Promise<AgentCard[]>;
669
- /**
670
- * Index an Agent Card for local search
671
- */
672
- indexAgentCard(card: AgentCard): void;
673
- /**
674
- * Remove an Agent Card from local index
675
- */
676
- removeAgentCard(did: string): void;
677
- /**
678
- * Get all indexed cards
679
- */
680
- getAllIndexedCards(): AgentCard[];
681
- /**
682
- * Clear local index
683
- */
684
- clearIndex(): void;
685
- /**
686
- * Get index size
687
- */
688
- getIndexSize(): number;
689
- /**
690
- * Search network via DHT
691
- */
692
- private searchNetwork;
693
- /**
694
- * Merge local and network results, removing duplicates
695
- */
696
- private mergeResults;
697
- /**
698
- * Score a card against a query
699
- */
700
- private scoreCard;
701
- /**
702
- * Extract primary capability from natural language text
703
- */
704
- private extractPrimaryCapability;
705
- }
706
- /**
707
- * Create a semantic search engine
708
- */
709
- declare function createSemanticSearch(dht?: DHTOperations): SemanticSearchEngine;
710
-
674
+ type LegacyMessageEnvelopeType = 'request' | 'response' | 'notification';
675
+ type MessageEnvelopeType = 'message' | 'reply';
676
+ type AnyMessageEnvelopeType = MessageEnvelopeType | LegacyMessageEnvelopeType;
711
677
  interface MessageEnvelope {
712
678
  id: string;
713
679
  from: string;
714
680
  to: string;
715
- type: 'request' | 'response' | 'notification';
681
+ type: MessageEnvelopeType;
716
682
  protocol: string;
717
683
  payload: unknown;
718
684
  timestamp: number;
719
685
  signature: string;
720
686
  replyTo?: string;
687
+ threadId?: string;
721
688
  }
722
- /**
723
- * Create a message envelope
724
- */
725
- declare function createEnvelope(from: string, to: string, type: 'request' | 'response' | 'notification', protocol: string, payload: unknown, replyTo?: string): Omit<MessageEnvelope, 'signature'>;
726
- /**
727
- * Sign a message envelope
728
- */
689
+ declare function normalizeEnvelopeType(type: string): MessageEnvelopeType | undefined;
690
+ declare function normalizeEnvelope(msg: unknown): MessageEnvelope | undefined;
691
+ declare function createEnvelope(from: string, to: string, type: AnyMessageEnvelopeType, protocol: string, payload: unknown, replyTo?: string, threadId?: string): Omit<MessageEnvelope, 'signature'>;
729
692
  declare function signEnvelope(envelope: Omit<MessageEnvelope, 'signature'>, signFn: (data: Uint8Array) => Promise<Uint8Array>): Promise<MessageEnvelope>;
730
- /**
731
- * Verify a message envelope signature
732
- */
733
693
  declare function verifyEnvelope(envelope: MessageEnvelope, verifyFn: (signature: Uint8Array, data: Uint8Array) => Promise<boolean>): Promise<boolean>;
734
- /**
735
- * Validate message envelope structure
736
- */
737
694
  declare function validateEnvelope(msg: unknown): msg is MessageEnvelope;
695
+ declare function generateThreadId(): string;
738
696
 
739
- /**
740
- * Encode a message envelope to CBOR
741
- */
742
697
  declare function encodeMessage(envelope: MessageEnvelope): Uint8Array;
743
- /**
744
- * Decode a CBOR message to envelope
745
- */
746
698
  declare function decodeMessage(data: Uint8Array): MessageEnvelope;
747
- /**
748
- * Encode message to JSON (for debugging/logging)
749
- */
750
699
  declare function encodeMessageJSON(envelope: MessageEnvelope): string;
751
- /**
752
- * Decode JSON message to envelope
753
- */
754
700
  declare function decodeMessageJSON(json: string): MessageEnvelope;
755
701
 
756
702
  type MessageHandler = (envelope: MessageEnvelope) => Promise<MessageEnvelope | void>;
@@ -758,13 +704,10 @@ interface MessageRouter {
758
704
  registerHandler: (protocol: string, handler: MessageHandler) => void;
759
705
  unregisterHandler: (protocol: string) => void;
760
706
  registerCatchAllHandler: (handler: MessageHandler) => void;
761
- sendMessage: (envelope: MessageEnvelope) => Promise<MessageEnvelope | void>;
707
+ sendMessage: (envelope: MessageEnvelope) => Promise<void>;
762
708
  start: () => Promise<void>;
763
709
  stop: () => Promise<void>;
764
710
  }
765
- /**
766
- * Create a message router using relay client (CVP-0011)
767
- */
768
711
  declare function createMessageRouter(relayClient: RelayClient, verifyFn: (signature: Uint8Array, data: Uint8Array) => Promise<boolean>): MessageRouter;
769
712
 
770
713
  /**
@@ -792,6 +735,7 @@ interface StoredMessage {
792
735
  sentAt?: number;
793
736
  readAt?: number;
794
737
  trustScore?: number;
738
+ trustStatus?: TrustStatus;
795
739
  error?: string;
796
740
  }
797
741
  /**
@@ -803,9 +747,24 @@ interface MessageFilter {
803
747
  protocol?: string | string[];
804
748
  minTrustScore?: number;
805
749
  maxAge?: number;
806
- type?: 'request' | 'response' | 'notification';
750
+ type?: MessageEnvelopeType;
751
+ replyTo?: string | string[];
807
752
  unreadOnly?: boolean;
808
753
  status?: MessageStatus | MessageStatus[];
754
+ threadId?: string;
755
+ }
756
+ /**
757
+ * Session metadata for conversation threads (CVP-0014)
758
+ */
759
+ interface SessionMeta {
760
+ threadId: string;
761
+ peerDid: string;
762
+ startedAt: number;
763
+ lastMessageAt: number;
764
+ messageCount: number;
765
+ title?: string;
766
+ archived?: boolean;
767
+ archivedAt?: number;
809
768
  }
810
769
  /**
811
770
  * Pagination options
@@ -866,6 +825,7 @@ interface DefenseResult {
866
825
  allowed: boolean;
867
826
  reason?: 'blocked' | 'duplicate' | 'trust_too_low' | 'rate_limited' | 'invalid';
868
827
  trustScore?: number;
828
+ trustStatus?: TrustStatus;
869
829
  remainingTokens?: number;
870
830
  resetTime?: number;
871
831
  }
@@ -927,6 +887,8 @@ declare class MessageStorage {
927
887
  queryMessages(direction: 'inbound' | 'outbound', filter?: MessageFilter, pagination?: PaginationOptions): Promise<MessagePage>;
928
888
  private matchesFilter;
929
889
  countMessages(direction: 'inbound' | 'outbound', filter?: MessageFilter): Promise<number>;
890
+ private normalizeStoredMessage;
891
+ private requireStoredMessage;
930
892
  putBlock(entry: BlocklistEntry): Promise<void>;
931
893
  getBlock(did: string): Promise<BlocklistEntry | null>;
932
894
  deleteBlock(did: string): Promise<void>;
@@ -941,15 +903,52 @@ declare class MessageStorage {
941
903
  putRateLimit(state: RateLimitState): Promise<void>;
942
904
  getRateLimit(did: string): Promise<RateLimitState | null>;
943
905
  cleanupRateLimits(maxAgeMs: number): Promise<void>;
906
+ private updateSessionMeta;
907
+ getSession(threadId: string): Promise<{
908
+ peerDid: string;
909
+ threadId: string;
910
+ messageCount: number;
911
+ lastMessageAt: number;
912
+ startedAt?: number;
913
+ title?: string;
914
+ archived?: boolean;
915
+ archivedAt?: number;
916
+ } | null>;
917
+ listSessions(peerDid?: string, limit?: number, includeArchived?: boolean): Promise<Array<{
918
+ peerDid: string;
919
+ threadId: string;
920
+ messageCount: number;
921
+ lastMessageAt: number;
922
+ startedAt?: number;
923
+ title?: string;
924
+ archived?: boolean;
925
+ archivedAt?: number;
926
+ }>>;
927
+ archiveSession(threadId: string): Promise<void>;
928
+ unarchiveSession(threadId: string): Promise<void>;
929
+ listArchivedSessions(peerDid?: string, limit?: number): Promise<Array<{
930
+ peerDid: string;
931
+ threadId: string;
932
+ messageCount: number;
933
+ lastMessageAt: number;
934
+ startedAt?: number;
935
+ title?: string;
936
+ archived?: boolean;
937
+ archivedAt?: number;
938
+ }>>;
939
+ searchSessions(query: string, limit?: number): Promise<Array<{
940
+ peerDid: string;
941
+ threadId: string;
942
+ messageCount: number;
943
+ lastMessageAt: number;
944
+ startedAt?: number;
945
+ title?: string;
946
+ archived?: boolean;
947
+ archivedAt?: number;
948
+ }>>;
949
+ queryMessagesByThread(threadId: string, pagination?: PaginationOptions): Promise<MessagePage>;
944
950
  }
945
951
 
946
- /**
947
- * Message Queue
948
- *
949
- * Persistent inbox/outbox backed by LevelDB.
950
- * Supports real-time subscriptions and pagination.
951
- */
952
-
953
952
  interface MessageQueueConfig {
954
953
  dbPath: string;
955
954
  }
@@ -967,7 +966,7 @@ declare class MessageQueue {
967
966
  deleteMessage(id: string): Promise<void>;
968
967
  getOutbox(pagination?: PaginationOptions): Promise<MessagePage>;
969
968
  retryMessage(id: string): Promise<void>;
970
- enqueueInbound(envelope: MessageEnvelope, trustScore?: number): Promise<StoredMessage>;
969
+ enqueueInbound(envelope: MessageEnvelope, trustScore?: number, trustStatus?: StoredMessage['trustStatus']): Promise<StoredMessage>;
971
970
  enqueueOutbound(envelope: MessageEnvelope): Promise<StoredMessage>;
972
971
  markOutboundDelivered(id: string): Promise<void>;
973
972
  markOutboundFailed(id: string, error: string): Promise<void>;
@@ -984,7 +983,7 @@ declare class MessageQueue {
984
983
  * Protects the network from Sybil attacks through:
985
984
  * - Entry cost (Hashcash challenges)
986
985
  * - Progressive trust (rate limiting for new agents)
987
- * - DHT region protection (prefer established peers)
986
+ * - Discovery hardening (prefer established peers)
988
987
  */
989
988
  /**
990
989
  * Hashcash Challenge
@@ -1107,7 +1106,7 @@ declare class InteractionHistory {
1107
1106
  */
1108
1107
 
1109
1108
  /**
1110
- * Endorsement Record
1109
+ * Endorsement Record v1 (legacy)
1111
1110
  */
1112
1111
  interface Endorsement {
1113
1112
  from: string;
@@ -1117,6 +1116,33 @@ interface Endorsement {
1117
1116
  timestamp: number;
1118
1117
  signature: string;
1119
1118
  }
1119
+ /**
1120
+ * Endorsement Record v2 (CVP-0017)
1121
+ */
1122
+ interface EndorsementV2 {
1123
+ version: 2;
1124
+ from: string;
1125
+ to: string;
1126
+ score: number;
1127
+ domain?: string;
1128
+ reason: string;
1129
+ timestamp: number;
1130
+ expires?: number;
1131
+ signature: string;
1132
+ }
1133
+ /**
1134
+ * Domain velocity categories for time decay
1135
+ */
1136
+ declare const FAST_DOMAINS: string[];
1137
+ declare const SLOW_DOMAINS: string[];
1138
+ /**
1139
+ * Default expiration by domain (in days)
1140
+ */
1141
+ declare function getDefaultExpiration(domain?: string): number;
1142
+ /**
1143
+ * Validate domain string
1144
+ */
1145
+ declare function validateDomain(domain: string): boolean;
1120
1146
  /**
1121
1147
  * Sign function type
1122
1148
  */
@@ -1133,13 +1159,25 @@ declare class EndorsementManager {
1133
1159
  private getPublicKey;
1134
1160
  constructor(db: Level<string, Endorsement>, getPublicKey: (did: string) => Promise<Uint8Array>);
1135
1161
  /**
1136
- * Create an endorsement
1162
+ * Create an endorsement (v2)
1163
+ */
1164
+ endorseV2(fromDid: string, toDid: string, score: number, reason: string, signFn: SignFunction, domain?: string, expires?: number): Promise<EndorsementV2>;
1165
+ /**
1166
+ * Create an endorsement (v1 - legacy)
1137
1167
  */
1138
1168
  endorse(fromDid: string, toDid: string, score: number, reason: string, signFn: SignFunction): Promise<Endorsement>;
1139
1169
  /**
1140
- * Verify endorsement signature
1170
+ * Verify endorsement signature (v2)
1171
+ */
1172
+ verifyV2(endorsement: EndorsementV2, verifyFn: VerifyFunction): Promise<boolean>;
1173
+ /**
1174
+ * Verify endorsement signature (v1)
1141
1175
  */
1142
1176
  verify(endorsement: Endorsement, verifyFn: VerifyFunction): Promise<boolean>;
1177
+ /**
1178
+ * Upgrade v1 endorsement to v2
1179
+ */
1180
+ upgradeEndorsement(e: Endorsement): EndorsementV2;
1143
1181
  /**
1144
1182
  * Publish endorsement to local database
1145
1183
  */
@@ -1160,6 +1198,143 @@ declare class EndorsementManager {
1160
1198
  * Delete an endorsement
1161
1199
  */
1162
1200
  deleteEndorsement(fromDid: string, toDid: string): Promise<void>;
1201
+ /**
1202
+ * Publish endorsement to relay (CVP-0017)
1203
+ */
1204
+ publishToRelay(relay: {
1205
+ publishEndorsement: (e: EndorsementV2) => Promise<{
1206
+ id: string;
1207
+ stored: boolean;
1208
+ error?: string;
1209
+ }>;
1210
+ }, endorsement: EndorsementV2): Promise<{
1211
+ id: string;
1212
+ stored: boolean;
1213
+ error?: string;
1214
+ }>;
1215
+ /**
1216
+ * Query endorsements from relay (CVP-0017)
1217
+ */
1218
+ queryFromRelay(relay: {
1219
+ queryTrust: (target: string, domain?: string, since?: number) => Promise<{
1220
+ endorsements: EndorsementV2[];
1221
+ endorsementCount?: number;
1222
+ averageScore?: number;
1223
+ }>;
1224
+ }, target: string, domain?: string, since?: number): Promise<{
1225
+ endorsements: EndorsementV2[];
1226
+ total: number;
1227
+ averageScore: number;
1228
+ }>;
1229
+ }
1230
+
1231
+ /**
1232
+ * CVP-0017: Trust Computation Engine
1233
+ *
1234
+ * Implements EigenTrust-lite algorithm with:
1235
+ * - Recursive endorser weighting (endorsements from trusted agents count more)
1236
+ * - Domain-aware time decay (fast/slow/default domains)
1237
+ * - Collusion detection (Tarjan's SCC algorithm)
1238
+ * - Configurable recursion depth (default 3, max 6)
1239
+ * - Seed peer bootstrapping
1240
+ */
1241
+
1242
+ /**
1243
+ * Trust computation configuration
1244
+ */
1245
+ interface TrustConfig {
1246
+ seedPeers?: string[];
1247
+ maxRecursionDepth?: number;
1248
+ decayHalfLife?: {
1249
+ default?: number;
1250
+ [domain: string]: number | undefined;
1251
+ };
1252
+ localInteractionWeight?: number;
1253
+ networkEndorsementWeight?: number;
1254
+ }
1255
+ /**
1256
+ * Trust computation result
1257
+ */
1258
+ interface TrustResult {
1259
+ score: number;
1260
+ localScore: number;
1261
+ networkScore: number;
1262
+ endorsementCount: number;
1263
+ collusionDetected: boolean;
1264
+ computedAt: number;
1265
+ }
1266
+ /**
1267
+ * Trust Computer
1268
+ */
1269
+ declare class TrustComputer {
1270
+ private config;
1271
+ private cache;
1272
+ private readonly CACHE_TTL;
1273
+ private sccPenaltyCache;
1274
+ private sccCacheExpiresAt;
1275
+ private readonly SCC_CACHE_TTL;
1276
+ private endorsementsByTarget;
1277
+ constructor(config?: TrustConfig);
1278
+ /**
1279
+ * Compute trust score for a target DID.
1280
+ * allEndorsements: flat list of all endorsements known to the caller (used for recursive weight lookup).
1281
+ */
1282
+ compute(target: string, endorsements: EndorsementV2[], localInteractionScore?: number, localInteractionCount?: number, domain?: string, allEndorsements?: EndorsementV2[]): TrustResult;
1283
+ /**
1284
+ * Compute network trust score using EigenTrust-lite
1285
+ */
1286
+ private computeNetworkTrust;
1287
+ /**
1288
+ * Get endorser weight (recursive EigenTrust-lite).
1289
+ * Uses endorsementsByTarget populated by compute() for local graph traversal.
1290
+ */
1291
+ private getEndorserWeight;
1292
+ /**
1293
+ * Compute time decay for an endorsement
1294
+ */
1295
+ private computeTimeDecay;
1296
+ /**
1297
+ * Get decay half-life for a domain
1298
+ */
1299
+ private getDecayHalfLife;
1300
+ /**
1301
+ * Detect collusion using Tarjan's SCC algorithm
1302
+ */
1303
+ private detectCollusion;
1304
+ /**
1305
+ * Build endorsement graph
1306
+ */
1307
+ private buildGraph;
1308
+ /**
1309
+ * Find strongly connected components using Tarjan's algorithm
1310
+ */
1311
+ private findSCCs;
1312
+ /**
1313
+ * Rebuild the SCC penalty cache from a full endorsement graph.
1314
+ * Called lazily when the cache is stale.
1315
+ */
1316
+ private rebuildSccPenaltyCache;
1317
+ /**
1318
+ * Get collusion penalty for an endorser.
1319
+ * Returns 0.1 if the endorser is in a detected collusion cluster, 1.0 otherwise.
1320
+ */
1321
+ private getCollusionPenalty;
1322
+ /**
1323
+ * Filter endorsements by domain
1324
+ */
1325
+ private filterByDomain;
1326
+ /**
1327
+ * Get cache key
1328
+ */
1329
+ private getCacheKey;
1330
+ /**
1331
+ * Clear cache
1332
+ */
1333
+ clearCache(): void;
1334
+ /**
1335
+ * Update configuration
1336
+ */
1337
+ updateConfig(config: Partial<TrustConfig>): void;
1163
1338
  }
1164
1339
 
1165
1340
  /**
@@ -1179,6 +1354,7 @@ declare class TrustSystem {
1179
1354
  private sybilDefense;
1180
1355
  private trustCache;
1181
1356
  private readonly CACHE_TTL;
1357
+ private uptimeTracker;
1182
1358
  constructor(config: TrustSystemConfig);
1183
1359
  /**
1184
1360
  * Initialize the trust system
@@ -1192,6 +1368,19 @@ declare class TrustSystem {
1192
1368
  * Record an interaction
1193
1369
  */
1194
1370
  recordInteraction(interaction: Interaction): Promise<void>;
1371
+ /**
1372
+ * Record agent coming online (for uptime tracking)
1373
+ */
1374
+ recordOnline(agentDid: string): void;
1375
+ /**
1376
+ * Record agent going offline (for uptime tracking)
1377
+ */
1378
+ recordOffline(agentDid: string): void;
1379
+ /**
1380
+ * Get uptime ratio for an agent (0.0 - 1.0)
1381
+ * Based on time since first seen vs total online time.
1382
+ */
1383
+ getUptime(agentDid: string): number;
1195
1384
  /**
1196
1385
  * Get trust score for an agent
1197
1386
  */
@@ -1219,7 +1408,7 @@ declare class TrustSystem {
1219
1408
  /**
1220
1409
  * Verify Sybil defense challenge
1221
1410
  */
1222
- verifyChallenge(solution: any): boolean;
1411
+ verifyChallenge(solution: ChallengeSolution): boolean;
1223
1412
  /**
1224
1413
  * Get peer trust level
1225
1414
  */
@@ -1371,4 +1560,4 @@ declare class MessagingError extends ClawiverseError {
1371
1560
  constructor(message: string, details?: unknown);
1372
1561
  }
1373
1562
 
1374
- export { type AckMessage, type AgentCard, type AllowlistEntry, type BlocklistEntry, CLAWIVERSE_CONTEXT, type Capability, CapabilityMatcher, type CapabilityParameter, CapabilityTypes, type CardMessage, type Challenge, type ChallengeSolution, ClawiverseError, DEFAULT_RATE_LIMIT_TIERS, type DefenseConfig, DefenseMiddleware, type DefenseResult, type DeliverMessage, type DeliveryReportHandler, type DeliveryReportMessage, type DiscoverMessage, type DiscoveredAgent, type DiscoveredMessage, DiscoveryError, type Endorsement, EndorsementManager, type FetchCardMessage, type GoodbyeMessage, type HelloMessage, IdentityError, type IndexSyncMessage, type Interaction, InteractionHistory, type InteractionStats, type KeyPair, type LegacyAgentCard, LogLevel, Logger, type MessageCallback, type MessageDeliveryHandler, type MessageDirection, type MessageEnvelope, type MessageFilter, type MessageHandler, type MessagePage, MessageQueue, type MessageQueueConfig, type MessageRouter, type MessageStatus, MessageStorage, MessagingError, type PaginationOptions, ParameterTypes, type PeerTrustLevel, type PingMessage, type PongMessage, type PresenceProof, type QueueStats, RELAY_PROTOCOL_VERSION, type RateLimitResult, type RateLimitState, type RateLimitTiers, type RelayClient, type RelayClientConfig, type RelayIndexOperations, type RelayMessage, type RelayMessageType, type RouteMessage, SCHEMA_ORG_CONTEXT, SearchIndex, type SearchResult, type SeenEntry, type SemanticQuery, SemanticSearchEngine, type SendMessage, type SignFunction, type SignedMessage, type StoredMessage, type SubscriptionFilter, SybilDefense, type SyncEvent, type SyncHelloMessage, type SyncPushMessage, type SyncReconcileMessage, type SyncRequestMessage, type SyncResponseMessage, TokenBucket, type TokenBucketConfig, TransportError, TrustMetrics, type TrustScore, TrustSystem, type TrustSystemConfig, type VerifyFunction, type WelcomeMessage, clawiverseContext, createAgentCard, createDefaultTrustScore, createEnvelope, createLegacyAgentCard, createLogger, createMessageRouter, createRelayClient, createRelayIndexOperations, createSemanticSearch, createTrustSystem, decodeAgentCard, decodeFromCBOR, decodeFromJSON, decodeMessage, decodeMessageJSON, deriveDID, downgradeToLegacyCard, encodeForDHT, encodeForWeb, encodeMessage, encodeMessageJSON, exportKeyPair, extractPublicKey, generateKeyPair, getAgentCardContext, getEncodedSize, getTierConfig, importKeyPair, isLegacyCard, isValidContext, matchesCapability, sign, signAgentCard, signEnvelope, signMessage, upgradeLegacyCard, validateAgentCard, validateDID, validateEnvelope, verify, verifyAgentCard, verifyEnvelope, verifyMessage };
1563
+ export { type AckMessage, type AgentCard, type AliasMap, type AllowlistEntry, type AnonymousIdentity, type AnyMessageEnvelopeType, type BlocklistEntry, CLAWIVERSE_CONTEXT, type Capability, type CapabilityParameter, CapabilityTypes, type CardMessage, type Challenge, type ChallengeSolution, ClawiverseError, DEFAULT_RATE_LIMIT_TIERS, type DIDDocument, type DefenseConfig, DefenseMiddleware, type DefenseResult, type DeliverMessage, type DeliveryReportHandler, type DeliveryReportMessage, type DiscoverMessage, type DiscoveredAgent, type DiscoveredMessage, DiscoveryError, type Endorsement, EndorsementManager, type EndorsementV2, FAST_DOMAINS, type FetchCardMessage, type GoodbyeMessage, type HelloMessage, IdentityError, type IndexSyncMessage, type Interaction, InteractionHistory, type InteractionStats, type KeyPair, type LegacyAgentCard, type LegacyMessageEnvelopeType, LogLevel, Logger, type MessageCallback, type MessageDeliveryHandler, type MessageDirection, type MessageEnvelope, type MessageEnvelopeType, type MessageFilter, type MessageHandler, type MessagePage, MessageQueue, type MessageQueueConfig, type MessageRouter, type MessageStatus, MessageStorage, MessagingError, type PaginationOptions, ParameterTypes, type PeerTrustLevel, type PingMessage, type PongMessage, type PresenceProof, type PublishCardMessage, type QueueStats, RELAY_PROTOCOL_VERSION, type RateLimitResult, type RateLimitState, type RateLimitTiers, type RelayClient, type RelayClientConfig, type RelayIndexOperations, type RelayMessage, type RelayMessageType, type RouteMessage, SCHEMA_ORG_CONTEXT, SLOW_DOMAINS, type SeenEntry, type SemanticQuery, type SendMessage, type ServiceEndpoint, type SessionMeta, type SignFunction, type SignedMessage, type StoredMessage, type SubscriptionFilter, SybilDefense, type SyncEvent, type SyncHelloMessage, type SyncPushMessage, type SyncReconcileMessage, type SyncRequestMessage, type SyncResponseMessage, TokenBucket, type TokenBucketConfig, TransportError, TrustComputer, type TrustConfig, TrustMetrics, type TrustQueryMessage, type TrustResult, type TrustResultEndorsement, type TrustResultMessage, type TrustScore, type TrustStatus, TrustSystem, type TrustSystemConfig, type UnpublishCardMessage, type VerificationMethod, type VerifyFunction, type WelcomeMessage, clawiverseContext, createAgentCard, createDIDDocument, createDefaultTrustScore, createEnvelope, createLegacyAgentCard, createLogger, createMessageRouter, createRelayClient, createRelayIndexOperations, createTrustSystem, decodeAgentCard, decodeFromCBOR, decodeFromJSON, decodeMessage, decodeMessageJSON, deriveDID, downgradeToLegacyCard, encodeForDHT, encodeForWeb, encodeMessage, encodeMessageJSON, exportKeyPair, extractPublicKey, formatDidWithAlias, formatDidWithAliasDetailed, generateAnonymousIdentity, generateKeyPair, generateThreadId, getAgentCardContext, getDefaultExpiration, getEncodedSize, getTierConfig, importKeyPair, isLegacyCard, isValidContext, matchesCapability, normalizeEnvelope, normalizeEnvelopeType, resolveDid, reverseAlias, sign, signAgentCard, signEnvelope, signMessage, upgradeLegacyCard, validateAgentCard, validateAliasName, validateDID, validateDIDDocument, validateDomain, validateEnvelope, verify, verifyAgentCard, verifyEnvelope, verifyMessage };