@rookdaemon/agora 0.4.3 → 0.4.4

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
@@ -956,6 +956,11 @@ declare class MessageStore {
956
956
  clear(recipientKey: string): void;
957
957
  }
958
958
 
959
+ declare const IGNORED_FILE_NAME = "IGNORED_PEERS.md";
960
+ declare function getIgnoredPeersPath(storageDir?: string): string;
961
+ declare function loadIgnoredPeers(filePath?: string): string[];
962
+ declare function saveIgnoredPeers(peers: string[], filePath?: string): void;
963
+
959
964
  /**
960
965
  * jwt-auth.ts — JWT token creation and validation middleware.
961
966
  *
@@ -1742,4 +1747,4 @@ declare function syncReputationFromPeer(agentPublicKey: string, domain: string,
1742
1747
  skipped: number;
1743
1748
  }>;
1744
1749
 
1745
- export { type AgoraConfig, type AgoraIdentity, type AgoraPeerConfig, AgoraService, type AgoraServiceConfig, type AnnouncePayload, type AuthenticatedRequest, type BootstrapConfig, type BufferedMessage, type Capability, type CapabilityAnnouncePayload, type CapabilityQueryPayload, type CapabilityResponsePayload, type CommitRecord, type CreateEnvelopeFn, DEFAULT_BOOTSTRAP_RELAYS, type DecodeInboundResult, type DiscoverPayload, type DiscoverResponsePayload, DiscoveryService, type Envelope, type JwtPayload, type KeyPair, type Logger, MessageBuffer, MessageStore, type MessageType, type PaperDiscoveryPayload, type Peer, type PeerConfig, type PeerConfigFile, type PeerDiscoveryConfig, type PeerDiscoveryEvents, PeerDiscoveryService, type PeerListRequestPayload, type PeerListResponsePayload, type PeerReferralPayload, PeerStore, RelayClient, type RelayClientConfig, type RelayClientEvents, type RelayClientFactory, type RelayClientLike, type RelayClientMessage, type RelayConfig, type RelayEnvelopeDedupOptions, type RelayInterface, type RelayMessageHandler, type RelayMessageHandlerWithName, type RelayPeer, type RelayRateLimitOptions, RelayServer, type RelayServerEvents, type RelayServerMessage, type RelayServerOptions, type ReplyToEnvelopeOptions, type ReputationQuery, type ReputationResponse, ReputationStore, type RestSession, type RevealRecord, type RevocationRecord, type RunRelayOptions, type SendMessageOptions, type SendMessageResult, type StoredMessage, type TransportConfig, type TrustScore, type TrustScoreOptions, type ValidationResult, type VerificationRecord, type VerifyEnvelopeFn, canonicalize, computeAllTrustScores, computeId, computeTrustScore, computeTrustScores, createCapability, createCommit, createEnvelope, createRestRouter, createReveal, createToken, createVerification, decay, decodeInboundEnvelope, exportKeyPair, formatDisplayName, generateKeyPair, getDefaultBootstrapRelay, getDefaultConfigPath, handleReputationQuery, hashPrediction, importKeyPair, initPeerConfig, loadAgoraConfig, loadAgoraConfigAsync, loadPeerConfig, parseBootstrapRelay, requireAuth, resolveBroadcastName, revokeToken, runRelay, savePeerConfig, sendToPeer, shortKey, signMessage, syncReputationFromPeer, validateCapability, validateCommitRecord, validatePeerListRequest, validatePeerListResponse, validatePeerReferral, validateRevealRecord, validateVerificationRecord, verifyEnvelope, verifyReveal, verifySignature, verifyVerificationSignature };
1750
+ export { type AgoraConfig, type AgoraIdentity, type AgoraPeerConfig, AgoraService, type AgoraServiceConfig, type AnnouncePayload, type AuthenticatedRequest, type BootstrapConfig, type BufferedMessage, type Capability, type CapabilityAnnouncePayload, type CapabilityQueryPayload, type CapabilityResponsePayload, type CommitRecord, type CreateEnvelopeFn, DEFAULT_BOOTSTRAP_RELAYS, type DecodeInboundResult, type DiscoverPayload, type DiscoverResponsePayload, DiscoveryService, type Envelope, IGNORED_FILE_NAME, type JwtPayload, type KeyPair, type Logger, MessageBuffer, MessageStore, type MessageType, type PaperDiscoveryPayload, type Peer, type PeerConfig, type PeerConfigFile, type PeerDiscoveryConfig, type PeerDiscoveryEvents, PeerDiscoveryService, type PeerListRequestPayload, type PeerListResponsePayload, type PeerReferralPayload, PeerStore, RelayClient, type RelayClientConfig, type RelayClientEvents, type RelayClientFactory, type RelayClientLike, type RelayClientMessage, type RelayConfig, type RelayEnvelopeDedupOptions, type RelayInterface, type RelayMessageHandler, type RelayMessageHandlerWithName, type RelayPeer, type RelayRateLimitOptions, RelayServer, type RelayServerEvents, type RelayServerMessage, type RelayServerOptions, type ReplyToEnvelopeOptions, type ReputationQuery, type ReputationResponse, ReputationStore, type RestSession, type RevealRecord, type RevocationRecord, type RunRelayOptions, type SendMessageOptions, type SendMessageResult, type StoredMessage, type TransportConfig, type TrustScore, type TrustScoreOptions, type ValidationResult, type VerificationRecord, type VerifyEnvelopeFn, canonicalize, computeAllTrustScores, computeId, computeTrustScore, computeTrustScores, createCapability, createCommit, createEnvelope, createRestRouter, createReveal, createToken, createVerification, decay, decodeInboundEnvelope, exportKeyPair, formatDisplayName, generateKeyPair, getDefaultBootstrapRelay, getDefaultConfigPath, getIgnoredPeersPath, handleReputationQuery, hashPrediction, importKeyPair, initPeerConfig, loadAgoraConfig, loadAgoraConfigAsync, loadIgnoredPeers, loadPeerConfig, parseBootstrapRelay, requireAuth, resolveBroadcastName, revokeToken, runRelay, saveIgnoredPeers, savePeerConfig, sendToPeer, shortKey, signMessage, syncReputationFromPeer, validateCapability, validateCommitRecord, validatePeerListRequest, validatePeerListResponse, validatePeerReferral, validateRevealRecord, validateVerificationRecord, verifyEnvelope, verifyReveal, verifySignature, verifyVerificationSignature };
package/dist/index.js CHANGED
@@ -505,6 +505,39 @@ async function loadAgoraConfigAsync(path) {
505
505
  return parseConfig(config);
506
506
  }
507
507
 
508
+ // src/relay/ignored-peers.ts
509
+ import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync2, mkdirSync } from "fs";
510
+ import { join, dirname } from "path";
511
+ var IGNORED_FILE_NAME = "IGNORED_PEERS.md";
512
+ function getIgnoredPeersPath(storageDir) {
513
+ if (storageDir) {
514
+ return join(storageDir, IGNORED_FILE_NAME);
515
+ }
516
+ const configPath = getDefaultConfigPath();
517
+ return join(dirname(configPath), IGNORED_FILE_NAME);
518
+ }
519
+ function loadIgnoredPeers(filePath) {
520
+ const path = filePath ?? getIgnoredPeersPath();
521
+ if (!existsSync2(path)) return [];
522
+ const lines = readFileSync2(path, "utf-8").split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
523
+ return Array.from(new Set(lines));
524
+ }
525
+ function saveIgnoredPeers(peers, filePath) {
526
+ const path = filePath ?? getIgnoredPeersPath();
527
+ const dir = dirname(path);
528
+ if (!existsSync2(dir)) {
529
+ mkdirSync(dir, { recursive: true });
530
+ }
531
+ const unique = Array.from(new Set(peers.map((peer) => peer.trim()).filter(Boolean))).sort();
532
+ const content = [
533
+ "# Ignored peers",
534
+ "# One public key per line",
535
+ ...unique,
536
+ ""
537
+ ].join("\n");
538
+ writeFileSync(path, content, "utf-8");
539
+ }
540
+
508
541
  // src/service.ts
509
542
  var AgoraService = class {
510
543
  config;
@@ -787,6 +820,7 @@ export {
787
820
  AgoraService,
788
821
  DEFAULT_BOOTSTRAP_RELAYS,
789
822
  DiscoveryService,
823
+ IGNORED_FILE_NAME,
790
824
  MessageBuffer,
791
825
  MessageStore,
792
826
  PeerDiscoveryService,
@@ -813,18 +847,21 @@ export {
813
847
  generateKeyPair,
814
848
  getDefaultBootstrapRelay,
815
849
  getDefaultConfigPath,
850
+ getIgnoredPeersPath,
816
851
  handleReputationQuery,
817
852
  hashPrediction,
818
853
  importKeyPair,
819
854
  initPeerConfig,
820
855
  loadAgoraConfig,
821
856
  loadAgoraConfigAsync,
857
+ loadIgnoredPeers,
822
858
  loadPeerConfig,
823
859
  parseBootstrapRelay,
824
860
  requireAuth,
825
861
  resolveBroadcastName,
826
862
  revokeToken,
827
863
  runRelay,
864
+ saveIgnoredPeers,
828
865
  savePeerConfig,
829
866
  sendToPeer,
830
867
  shortKey,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/registry/capability.ts","../src/registry/peer-store.ts","../src/registry/discovery-service.ts","../src/message/types/peer-discovery.ts","../src/config.ts","../src/service.ts","../src/reputation/network.ts","../src/reputation/sync.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\n/**\n * A capability describes something an agent can do\n */\nexport interface Capability {\n /** Unique ID (content-addressed hash of name + version + schema) */\n id: string;\n /** Human-readable name: 'code-review', 'summarization', 'translation' */\n name: string;\n /** Semantic version */\n version: string;\n /** What the capability does */\n description: string;\n /** JSON Schema for expected input */\n inputSchema?: object;\n /** JSON Schema for expected output */\n outputSchema?: object;\n /** Discovery tags: ['code', 'typescript', 'review'] */\n tags: string[];\n}\n\n/**\n * Deterministic JSON serialization for capability hashing.\n * Recursively sorts object keys.\n */\nfunction stableStringify(value: unknown): string {\n if (value === null || value === undefined) return JSON.stringify(value);\n if (typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return '[' + value.map(stableStringify).join(',') + ']';\n }\n const keys = Object.keys(value as Record<string, unknown>).sort();\n const pairs = keys.map(k => JSON.stringify(k) + ':' + stableStringify((value as Record<string, unknown>)[k]));\n return '{' + pairs.join(',') + '}';\n}\n\n/**\n * Compute content-addressed ID for a capability based on name, version, and schemas.\n */\nfunction computeCapabilityId(name: string, version: string, inputSchema?: object, outputSchema?: object): string {\n const data = {\n name,\n version,\n ...(inputSchema !== undefined ? { inputSchema } : {}),\n ...(outputSchema !== undefined ? { outputSchema } : {}),\n };\n const canonical = stableStringify(data);\n return createHash('sha256').update(canonical).digest('hex');\n}\n\n/**\n * Creates a capability with a content-addressed ID.\n * \n * @param name - Human-readable capability name\n * @param version - Semantic version string\n * @param description - Description of what the capability does\n * @param options - Optional input/output schemas and tags\n * @returns A Capability object with computed ID\n */\nexport function createCapability(\n name: string,\n version: string,\n description: string,\n options: {\n inputSchema?: object;\n outputSchema?: object;\n tags?: string[];\n } = {}\n): Capability {\n const { inputSchema, outputSchema, tags = [] } = options;\n \n const id = computeCapabilityId(name, version, inputSchema, outputSchema);\n \n return {\n id,\n name,\n version,\n description,\n ...(inputSchema !== undefined ? { inputSchema } : {}),\n ...(outputSchema !== undefined ? { outputSchema } : {}),\n tags,\n };\n}\n\n/**\n * Validates that a capability has all required fields.\n * \n * @param capability - The capability to validate\n * @returns Object with `valid` boolean and optional `errors` array\n */\nexport function validateCapability(capability: unknown): { valid: boolean; errors?: string[] } {\n const errors: string[] = [];\n \n if (!capability || typeof capability !== 'object') {\n return { valid: false, errors: ['Capability must be an object'] };\n }\n \n const cap = capability as Record<string, unknown>;\n \n if (!cap.id || typeof cap.id !== 'string') {\n errors.push('Missing or invalid field: id (must be a string)');\n }\n \n if (!cap.name || typeof cap.name !== 'string') {\n errors.push('Missing or invalid field: name (must be a string)');\n }\n \n if (!cap.version || typeof cap.version !== 'string') {\n errors.push('Missing or invalid field: version (must be a string)');\n }\n \n if (!cap.description || typeof cap.description !== 'string') {\n errors.push('Missing or invalid field: description (must be a string)');\n }\n \n if (!Array.isArray(cap.tags)) {\n errors.push('Missing or invalid field: tags (must be an array)');\n } else if (!cap.tags.every(tag => typeof tag === 'string')) {\n errors.push('Invalid field: tags (all elements must be strings)');\n }\n \n if (cap.inputSchema !== undefined && (typeof cap.inputSchema !== 'object' || cap.inputSchema === null)) {\n errors.push('Invalid field: inputSchema (must be an object)');\n }\n \n if (cap.outputSchema !== undefined && (typeof cap.outputSchema !== 'object' || cap.outputSchema === null)) {\n errors.push('Invalid field: outputSchema (must be an object)');\n }\n \n if (errors.length > 0) {\n return { valid: false, errors };\n }\n \n return { valid: true };\n}\n","import type { Peer } from './peer';\n\n/**\n * In-memory store for known peers on the network\n */\nexport class PeerStore {\n private peers: Map<string, Peer> = new Map();\n\n /**\n * Add or update a peer in the store.\n * If a peer with the same publicKey exists, it will be updated.\n * \n * @param peer - The peer to add or update\n */\n addOrUpdatePeer(peer: Peer): void {\n this.peers.set(peer.publicKey, peer);\n }\n\n /**\n * Remove a peer from the store.\n * \n * @param publicKey - The public key of the peer to remove\n * @returns true if the peer was removed, false if it didn't exist\n */\n removePeer(publicKey: string): boolean {\n return this.peers.delete(publicKey);\n }\n\n /**\n * Get a peer by their public key.\n * \n * @param publicKey - The public key of the peer to retrieve\n * @returns The peer if found, undefined otherwise\n */\n getPeer(publicKey: string): Peer | undefined {\n return this.peers.get(publicKey);\n }\n\n /**\n * Find all peers that offer a specific capability by name.\n * \n * @param name - The capability name to search for\n * @returns Array of peers that have a capability with the given name\n */\n findByCapability(name: string): Peer[] {\n const result: Peer[] = [];\n \n for (const peer of this.peers.values()) {\n const hasCapability = peer.capabilities.some(cap => cap.name === name);\n if (hasCapability) {\n result.push(peer);\n }\n }\n \n return result;\n }\n\n /**\n * Find all peers that have capabilities with a specific tag.\n * \n * @param tag - The tag to search for\n * @returns Array of peers that have at least one capability with the given tag\n */\n findByTag(tag: string): Peer[] {\n const result: Peer[] = [];\n \n for (const peer of this.peers.values()) {\n const hasTag = peer.capabilities.some(cap => cap.tags.includes(tag));\n if (hasTag) {\n result.push(peer);\n }\n }\n \n return result;\n }\n\n /**\n * Get all peers in the store.\n * \n * @returns Array of all peers\n */\n allPeers(): Peer[] {\n return Array.from(this.peers.values());\n }\n\n /**\n * Remove peers that haven't been seen within the specified time window.\n * \n * @param maxAgeMs - Maximum age in milliseconds. Peers older than this will be removed.\n * @param currentTime - Current timestamp (ms), defaults to Date.now()\n * @returns Number of peers removed\n */\n prune(maxAgeMs: number, currentTime: number = Date.now()): number {\n const cutoff = currentTime - maxAgeMs;\n let removed = 0;\n \n for (const [publicKey, peer] of this.peers.entries()) {\n if (peer.lastSeen < cutoff) {\n this.peers.delete(publicKey);\n removed++;\n }\n }\n \n return removed;\n }\n}\n","import { createEnvelope, type Envelope } from '../message/envelope';\nimport { PeerStore } from './peer-store';\nimport type { Capability } from './capability';\nimport type { Peer } from './peer';\nimport type {\n CapabilityAnnouncePayload,\n CapabilityQueryPayload,\n CapabilityResponsePayload,\n} from './messages';\n\n/**\n * DiscoveryService manages capability-based peer discovery.\n * It maintains a local index of peer capabilities and handles\n * capability announce, query, and response messages.\n */\nexport class DiscoveryService {\n constructor(\n private peerStore: PeerStore,\n private identity: { publicKey: string; privateKey: string }\n ) {}\n\n /**\n * Announce own capabilities to the network.\n * Creates a capability_announce envelope that can be broadcast to peers.\n * \n * @param capabilities - List of capabilities this agent offers\n * @param metadata - Optional metadata about this agent\n * @returns A signed capability_announce envelope\n */\n announce(\n capabilities: Capability[],\n metadata?: { name?: string; version?: string }\n ): Envelope<CapabilityAnnouncePayload> {\n const payload: CapabilityAnnouncePayload = {\n publicKey: this.identity.publicKey,\n capabilities,\n metadata: metadata ? {\n ...metadata,\n lastSeen: Date.now(),\n } : {\n lastSeen: Date.now(),\n },\n };\n\n return createEnvelope(\n 'capability_announce',\n this.identity.publicKey,\n this.identity.privateKey,\n payload\n );\n }\n\n /**\n * Handle an incoming capability_announce message.\n * Updates the peer store with the announced capabilities.\n * \n * @param envelope - The capability_announce envelope to process\n */\n handleAnnounce(envelope: Envelope<CapabilityAnnouncePayload>): void {\n const { payload } = envelope;\n \n const peer: Peer = {\n publicKey: payload.publicKey,\n capabilities: payload.capabilities,\n lastSeen: payload.metadata?.lastSeen || envelope.timestamp,\n metadata: payload.metadata ? {\n name: payload.metadata.name,\n version: payload.metadata.version,\n } : undefined,\n };\n\n this.peerStore.addOrUpdatePeer(peer);\n }\n\n /**\n * Create a capability query payload.\n * \n * @param queryType - Type of query: 'name', 'tag', or 'schema'\n * @param query - The query value (capability name, tag, or schema)\n * @param filters - Optional filters (limit, minTrustScore)\n * @returns A capability_query payload\n */\n query(\n queryType: 'name' | 'tag' | 'schema',\n query: string | object,\n filters?: { limit?: number; minTrustScore?: number }\n ): CapabilityQueryPayload {\n return {\n queryType,\n query,\n filters,\n };\n }\n\n /**\n * Handle an incoming capability_query message.\n * Searches the local peer store and returns matching peers.\n * \n * @param envelope - The capability_query envelope to process\n * @returns A capability_response envelope with matching peers\n */\n handleQuery(\n envelope: Envelope<CapabilityQueryPayload>\n ): Envelope<CapabilityResponsePayload> {\n const { payload } = envelope;\n let peers: Peer[] = [];\n\n // Execute query based on type\n if (payload.queryType === 'name' && typeof payload.query === 'string') {\n peers = this.peerStore.findByCapability(payload.query);\n } else if (payload.queryType === 'tag' && typeof payload.query === 'string') {\n peers = this.peerStore.findByTag(payload.query);\n } else if (payload.queryType === 'schema') {\n // Schema-based matching is deferred to Phase 2b\n // For now, return empty results\n peers = [];\n }\n\n // Apply filters\n const limit = payload.filters?.limit;\n const totalMatches = peers.length;\n \n if (limit !== undefined && limit > 0) {\n peers = peers.slice(0, limit);\n }\n\n // Transform peers to response format\n const responsePeers = peers.map(peer => ({\n publicKey: peer.publicKey,\n capabilities: peer.capabilities,\n metadata: peer.metadata ? {\n name: peer.metadata.name,\n version: peer.metadata.version,\n lastSeen: peer.lastSeen,\n } : {\n lastSeen: peer.lastSeen,\n },\n // Trust score integration deferred to Phase 2b (RFC-001)\n trustScore: undefined,\n }));\n\n const responsePayload: CapabilityResponsePayload = {\n queryId: envelope.id,\n peers: responsePeers,\n totalMatches,\n };\n\n return createEnvelope(\n 'capability_response',\n this.identity.publicKey,\n this.identity.privateKey,\n responsePayload,\n Date.now(),\n envelope.id // inReplyTo\n );\n }\n\n /**\n * Remove peers that haven't been seen within the specified time window.\n * \n * @param maxAgeMs - Maximum age in milliseconds\n * @returns Number of peers removed\n */\n pruneStale(maxAgeMs: number, currentTime: number = Date.now()): number {\n return this.peerStore.prune(maxAgeMs, currentTime);\n }\n}\n","/**\n * Peer discovery message types for the Agora network.\n */\n\n/**\n * Request peer list from relay\n */\nexport interface PeerListRequestPayload {\n /** Optional filters */\n filters?: {\n /** Only peers seen in last N ms */\n activeWithin?: number;\n /** Maximum peers to return */\n limit?: number;\n };\n}\n\n/**\n * Relay responds with connected peers\n */\nexport interface PeerListResponsePayload {\n /** List of known peers */\n peers: Array<{\n /** Peer's Ed25519 public key */\n publicKey: string;\n /** Optional metadata (if peer announced) */\n metadata?: {\n name?: string;\n version?: string;\n capabilities?: string[];\n };\n /** Last seen timestamp (ms) */\n lastSeen: number;\n }>;\n /** Total peer count (may be > peers.length if limited) */\n totalPeers: number;\n /** Relay's public key (for trust verification) */\n relayPublicKey: string;\n}\n\n/**\n * Agent recommends another agent\n */\nexport interface PeerReferralPayload {\n /** Referred peer's public key */\n publicKey: string;\n /** Optional endpoint (if known) */\n endpoint?: string;\n /** Optional metadata */\n metadata?: {\n name?: string;\n version?: string;\n capabilities?: string[];\n };\n /** Referrer's comment */\n comment?: string;\n /** Trust hint (RFC-001 integration) */\n trustScore?: number;\n}\n\n/**\n * Validate PeerListRequestPayload\n */\nexport function validatePeerListRequest(payload: unknown): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n if (typeof payload !== 'object' || payload === null) {\n errors.push('Payload must be an object');\n return { valid: false, errors };\n }\n\n const p = payload as Record<string, unknown>;\n\n if (p.filters !== undefined) {\n if (typeof p.filters !== 'object' || p.filters === null) {\n errors.push('filters must be an object');\n } else {\n const filters = p.filters as Record<string, unknown>;\n if (filters.activeWithin !== undefined && typeof filters.activeWithin !== 'number') {\n errors.push('filters.activeWithin must be a number');\n }\n if (filters.limit !== undefined && typeof filters.limit !== 'number') {\n errors.push('filters.limit must be a number');\n }\n }\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate PeerListResponsePayload\n */\nexport function validatePeerListResponse(payload: unknown): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n if (typeof payload !== 'object' || payload === null) {\n errors.push('Payload must be an object');\n return { valid: false, errors };\n }\n\n const p = payload as Record<string, unknown>;\n\n if (!Array.isArray(p.peers)) {\n errors.push('peers must be an array');\n } else {\n p.peers.forEach((peer, index) => {\n if (typeof peer !== 'object' || peer === null) {\n errors.push(`peers[${index}] must be an object`);\n return;\n }\n const peerObj = peer as Record<string, unknown>;\n if (typeof peerObj.publicKey !== 'string') {\n errors.push(`peers[${index}].publicKey must be a string`);\n }\n if (typeof peerObj.lastSeen !== 'number') {\n errors.push(`peers[${index}].lastSeen must be a number`);\n }\n });\n }\n\n if (typeof p.totalPeers !== 'number') {\n errors.push('totalPeers must be a number');\n }\n\n if (typeof p.relayPublicKey !== 'string') {\n errors.push('relayPublicKey must be a string');\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate PeerReferralPayload\n */\nexport function validatePeerReferral(payload: unknown): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n if (typeof payload !== 'object' || payload === null) {\n errors.push('Payload must be an object');\n return { valid: false, errors };\n }\n\n const p = payload as Record<string, unknown>;\n\n if (typeof p.publicKey !== 'string') {\n errors.push('publicKey must be a string');\n }\n\n if (p.endpoint !== undefined && typeof p.endpoint !== 'string') {\n errors.push('endpoint must be a string');\n }\n\n if (p.comment !== undefined && typeof p.comment !== 'string') {\n errors.push('comment must be a string');\n }\n\n if (p.trustScore !== undefined && typeof p.trustScore !== 'number') {\n errors.push('trustScore must be a number');\n }\n\n return { valid: errors.length === 0, errors };\n}\n","import { readFileSync, existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { homedir } from 'node:os';\n\n/**\n * Normalized relay configuration (supports both string and object in config file).\n */\nexport interface RelayConfig {\n url: string;\n autoConnect: boolean;\n name?: string;\n reconnectMaxMs?: number;\n}\n\n/**\n * Peer entry in config (webhook URL, token, public key).\n */\nexport interface AgoraPeerConfig {\n publicKey: string;\n /** Webhook URL (undefined for relay-only peers) */\n url?: string;\n /** Webhook auth token (undefined for relay-only peers) */\n token?: string;\n name?: string;\n}\n\n/**\n * Identity with optional display name (e.g. for relay registration).\n */\nexport interface AgoraIdentity {\n publicKey: string;\n privateKey: string;\n name?: string;\n}\n\n/**\n * Canonical Agora configuration shape.\n * Use loadAgoraConfig() to load from file with normalized relay.\n */\nexport interface AgoraConfig {\n identity: AgoraIdentity;\n peers: Record<string, AgoraPeerConfig>;\n relay?: RelayConfig;\n}\n\n/**\n * Default config file path: AGORA_CONFIG env or ~/.config/agora/config.json\n */\nexport function getDefaultConfigPath(): string {\n if (process.env.AGORA_CONFIG) {\n return resolve(process.env.AGORA_CONFIG);\n }\n return resolve(homedir(), '.config', 'agora', 'config.json');\n}\n\n/**\n * Parse and normalize config from a JSON object (shared by sync and async loaders).\n */\nfunction parseConfig(config: Record<string, unknown>): AgoraConfig {\n const rawIdentity = config.identity as Record<string, unknown> | undefined;\n if (!rawIdentity?.publicKey || !rawIdentity?.privateKey) {\n throw new Error('Invalid config: missing identity.publicKey or identity.privateKey');\n }\n const identity: AgoraIdentity = {\n publicKey: rawIdentity.publicKey as string,\n privateKey: rawIdentity.privateKey as string,\n name: typeof rawIdentity.name === 'string' ? rawIdentity.name : undefined,\n };\n\n const peers: Record<string, AgoraPeerConfig> = {};\n if (config.peers && typeof config.peers === 'object') {\n for (const [name, entry] of Object.entries(config.peers)) {\n const peer = entry as Record<string, unknown>;\n if (peer && typeof peer.publicKey === 'string') {\n peers[name] = {\n publicKey: peer.publicKey as string,\n url: typeof peer.url === 'string' ? peer.url : undefined,\n token: typeof peer.token === 'string' ? peer.token : undefined,\n name: typeof peer.name === 'string' ? peer.name : undefined,\n };\n }\n }\n }\n\n let relay: RelayConfig | undefined;\n const rawRelay = config.relay;\n if (typeof rawRelay === 'string') {\n relay = { url: rawRelay, autoConnect: true };\n } else if (rawRelay && typeof rawRelay === 'object') {\n const r = rawRelay as Record<string, unknown>;\n if (typeof r.url === 'string') {\n relay = {\n url: r.url,\n autoConnect: typeof r.autoConnect === 'boolean' ? r.autoConnect : true,\n name: typeof r.name === 'string' ? r.name : undefined,\n reconnectMaxMs: typeof r.reconnectMaxMs === 'number' ? r.reconnectMaxMs : undefined,\n };\n }\n }\n\n return {\n identity,\n peers,\n ...(relay ? { relay } : {}),\n };\n}\n\n/**\n * Load and normalize Agora configuration from a JSON file (sync).\n * Supports relay as string (backward compat) or object { url?, autoConnect?, name?, reconnectMaxMs? }.\n *\n * @param path - Config file path; defaults to getDefaultConfigPath()\n * @returns Normalized AgoraConfig\n * @throws Error if file doesn't exist or config is invalid\n */\nexport function loadAgoraConfig(path?: string): AgoraConfig {\n const configPath = path ?? getDefaultConfigPath();\n\n if (!existsSync(configPath)) {\n throw new Error(`Config file not found at ${configPath}. Run 'npx @rookdaemon/agora init' first.`);\n }\n\n const content = readFileSync(configPath, 'utf-8');\n let config: Record<string, unknown>;\n try {\n config = JSON.parse(content) as Record<string, unknown>;\n } catch {\n throw new Error(`Invalid JSON in config file: ${configPath}`);\n }\n\n return parseConfig(config);\n}\n\n/**\n * Load and normalize Agora configuration from a JSON file (async).\n *\n * @param path - Config file path; defaults to getDefaultConfigPath()\n * @returns Normalized AgoraConfig\n * @throws Error if file doesn't exist or config is invalid\n */\nexport async function loadAgoraConfigAsync(path?: string): Promise<AgoraConfig> {\n const configPath = path ?? getDefaultConfigPath();\n\n let content: string;\n try {\n content = await readFile(configPath, 'utf-8');\n } catch (err) {\n const code = err && typeof err === 'object' && 'code' in err ? (err as NodeJS.ErrnoException).code : undefined;\n if (code === 'ENOENT') {\n throw new Error(`Config file not found at ${configPath}. Run 'npx @rookdaemon/agora init' first.`);\n }\n throw err;\n }\n\n let config: Record<string, unknown>;\n try {\n config = JSON.parse(content) as Record<string, unknown>;\n } catch {\n throw new Error(`Invalid JSON in config file: ${configPath}`);\n }\n\n return parseConfig(config);\n}\n","import type { AgoraIdentity, RelayConfig } from './config';\nimport { getDefaultConfigPath, loadAgoraConfigAsync } from './config';\nimport type { Envelope } from './message/envelope';\nimport type { MessageType } from './message/envelope';\nimport { RelayClient } from './relay/client';\nimport type { PeerConfig } from './transport/http';\nimport { decodeInboundEnvelope, sendToPeer } from './transport/http';\nimport { sendViaRelay } from './transport/relay';\nimport { shortKey } from './utils';\n\n/**\n * Service config: identity, peers keyed by name, optional relay.\n */\nexport interface AgoraServiceConfig {\n identity: AgoraIdentity;\n peers: Map<string, PeerConfig>;\n relay?: RelayConfig;\n}\n\nexport interface SendMessageOptions {\n peerName: string;\n type: MessageType;\n payload: unknown;\n inReplyTo?: string;\n /** Skip relay, send directly via HTTP only. Fails if peer has no URL or is unreachable. */\n direct?: boolean;\n /** Skip direct HTTP, always use relay even if peer has a URL. */\n relayOnly?: boolean;\n}\n\nexport interface SendMessageResult {\n ok: boolean;\n status: number;\n error?: string;\n}\n\nexport interface ReplyToEnvelopeOptions {\n /** The public key of the target (from envelope.sender) */\n targetPubkey: string;\n /** Message type for the reply */\n type: MessageType;\n /** Reply payload */\n payload: unknown;\n /** The envelope ID being replied to (required — this IS a reply) */\n inReplyTo: string;\n}\n\nexport interface DecodeInboundResult {\n ok: boolean;\n envelope?: Envelope;\n reason?: string;\n}\n\n/** Handler for relay messages. (envelope, fromPublicKey, fromName?) */\nexport type RelayMessageHandlerWithName = (envelope: Envelope, from: string, fromName?: string) => void;\n\n/** @deprecated Use RelayMessageHandlerWithName. Kept for backward compatibility. */\nexport type RelayMessageHandler = (envelope: Envelope) => void;\n\nexport interface Logger {\n debug(message: string): void;\n}\n\nexport interface RelayClientLike {\n connect(): Promise<void>;\n disconnect(): void;\n connected(): boolean;\n send(to: string, envelope: Envelope): Promise<{ ok: boolean; error?: string }>;\n on(event: 'message', handler: (envelope: Envelope, from: string, fromName?: string) => void): void;\n on(event: 'error', handler: (error: Error) => void): void;\n}\n\nexport interface RelayClientFactory {\n (opts: {\n relayUrl: string;\n publicKey: string;\n privateKey: string;\n name?: string;\n pingInterval: number;\n maxReconnectDelay: number;\n }): RelayClientLike;\n}\n\n/**\n * High-level Agora service: send by peer name, decode inbound, relay lifecycle.\n */\nexport class AgoraService {\n private config: AgoraServiceConfig;\n private relayClient: RelayClientLike | null = null;\n private readonly onRelayMessage: RelayMessageHandlerWithName;\n private logger: Logger | null;\n private relayClientFactory: RelayClientFactory | null;\n\n /**\n * @param config - Service config (identity, peers, optional relay)\n * @param onRelayMessage - Required callback for relay messages. Ensures no messages are lost between init and connect.\n * @param logger - Optional debug logger\n * @param relayClientFactory - Optional factory for relay client (for testing)\n */\n constructor(\n config: AgoraServiceConfig,\n onRelayMessage: RelayMessageHandlerWithName,\n logger?: Logger,\n relayClientFactory?: RelayClientFactory\n ) {\n this.config = config;\n this.onRelayMessage = onRelayMessage;\n this.logger = logger ?? null;\n this.relayClientFactory = relayClientFactory ?? null;\n }\n\n /**\n * Send a signed message to a named peer.\n * Tries HTTP webhook first; falls back to relay if HTTP is unavailable.\n */\n async sendMessage(options: SendMessageOptions): Promise<SendMessageResult> {\n const peer = this.config.peers.get(options.peerName);\n if (!peer) {\n return {\n ok: false,\n status: 0,\n error: `Unknown peer: ${options.peerName}`,\n };\n }\n\n // Try HTTP first (only if peer has a webhook URL and --relay-only not set)\n if (peer.url && !options.relayOnly) {\n const transportConfig = {\n identity: {\n publicKey: this.config.identity.publicKey,\n privateKey: this.config.identity.privateKey,\n },\n peers: new Map<string, PeerConfig>([[peer.publicKey, peer]]),\n };\n\n const httpResult = await sendToPeer(\n transportConfig,\n peer.publicKey,\n options.type,\n options.payload,\n options.inReplyTo\n );\n\n if (httpResult.ok) {\n return httpResult;\n }\n\n this.logger?.debug(`HTTP send to ${options.peerName} failed: ${httpResult.error}`);\n\n // --direct flag: do not fall back to relay\n if (options.direct) {\n return {\n ok: false,\n status: httpResult.status,\n error: `Direct send to ${options.peerName} failed: ${httpResult.error}`,\n };\n }\n } else if (options.direct && !peer.url) {\n // --direct requested but peer has no URL configured\n return {\n ok: false,\n status: 0,\n error: `Direct send failed: peer '${options.peerName}' has no URL configured`,\n };\n }\n\n // Fall back to relay\n if (this.relayClient?.connected() && this.config.relay) {\n const relayResult = await sendViaRelay(\n {\n identity: this.config.identity,\n relayUrl: this.config.relay.url,\n relayClient: this.relayClient,\n },\n peer.publicKey,\n options.type,\n options.payload,\n options.inReplyTo\n );\n\n return {\n ok: relayResult.ok,\n status: 0,\n error: relayResult.error,\n };\n }\n\n // Both failed\n return {\n ok: false,\n status: 0,\n error: peer.url\n ? `HTTP send failed and relay not available for peer: ${options.peerName}`\n : `No webhook URL and relay not available for peer: ${options.peerName}`,\n };\n }\n\n /**\n * Reply to an envelope from any sender via relay.\n * Unlike sendMessage(), this does NOT require the target to be a configured peer.\n * Uses the target's public key directly — relay-only (no HTTP, since unknown peers have no URL).\n */\n async replyToEnvelope(options: ReplyToEnvelopeOptions): Promise<SendMessageResult> {\n if (!this.relayClient?.connected() || !this.config.relay) {\n return {\n ok: false,\n status: 0,\n error: 'Relay not connected — cannot reply to envelope without relay',\n };\n }\n\n this.logger?.debug(\n `Replying to envelope via relay: target=${shortKey(options.targetPubkey)} type=${options.type} inReplyTo=${options.inReplyTo}`\n );\n\n const relayResult = await sendViaRelay(\n {\n identity: this.config.identity,\n relayUrl: this.config.relay.url,\n relayClient: this.relayClient,\n },\n options.targetPubkey,\n options.type,\n options.payload,\n options.inReplyTo\n );\n\n return {\n ok: relayResult.ok,\n status: 0,\n error: relayResult.error,\n };\n }\n\n /**\n * Decode and verify an inbound envelope from a webhook message.\n */\n async decodeInbound(message: string): Promise<DecodeInboundResult> {\n const peersByPubKey = new Map<string, PeerConfig>();\n for (const peer of this.config.peers.values()) {\n peersByPubKey.set(peer.publicKey, peer);\n }\n const result = decodeInboundEnvelope(message, peersByPubKey);\n if (result.ok) {\n return { ok: true, envelope: result.envelope };\n }\n return { ok: false, reason: result.reason };\n }\n\n getPeers(): string[] {\n return Array.from(this.config.peers.keys());\n }\n\n getPeerConfig(name: string): PeerConfig | undefined {\n return this.config.peers.get(name);\n }\n\n /**\n * Connect to the relay server.\n */\n async connectRelay(url: string): Promise<void> {\n if (this.relayClient) {\n return;\n }\n\n const maxReconnectDelay = this.config.relay?.reconnectMaxMs ?? 300000;\n let name = this.config.identity.name ?? this.config.relay?.name;\n // Never use the short key (id) as the relay display name; treat it as no name\n if (name && name === shortKey(this.config.identity.publicKey)) {\n name = undefined;\n }\n const opts = {\n relayUrl: url,\n publicKey: this.config.identity.publicKey,\n privateKey: this.config.identity.privateKey,\n name,\n pingInterval: 30000,\n maxReconnectDelay,\n };\n\n if (this.relayClientFactory) {\n this.relayClient = this.relayClientFactory(opts);\n } else {\n this.relayClient = new RelayClient(opts);\n }\n\n this.relayClient.on('error', (error: Error) => {\n this.logger?.debug(`Agora relay error: ${error.message}`);\n });\n\n this.relayClient.on('message', (envelope: Envelope, from: string, fromName?: string) => {\n this.onRelayMessage(envelope, from, fromName);\n });\n\n try {\n await this.relayClient.connect();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger?.debug(`Agora relay connect failed (${url}): ${message}`);\n this.relayClient = null;\n }\n }\n\n async disconnectRelay(): Promise<void> {\n if (this.relayClient) {\n this.relayClient.disconnect();\n this.relayClient = null;\n }\n }\n\n isRelayConnected(): boolean {\n return this.relayClient?.connected() ?? false;\n }\n\n /**\n * Load Agora configuration and return service config (peers as Map).\n */\n static async loadConfig(path?: string): Promise<AgoraServiceConfig> {\n const configPath = path ?? getDefaultConfigPath();\n const loaded = await loadAgoraConfigAsync(configPath);\n\n const peers = new Map<string, PeerConfig>();\n for (const [name, p] of Object.entries(loaded.peers)) {\n peers.set(name, {\n publicKey: p.publicKey,\n url: p.url,\n token: p.token,\n } satisfies PeerConfig);\n }\n\n return {\n identity: loaded.identity,\n peers,\n relay: loaded.relay,\n };\n }\n}\n","/**\n * Network reputation query handler.\n * Handles incoming reputation_query messages and returns reputation_response.\n */\n\nimport type { ReputationQuery, ReputationResponse, TrustScore } from './types.js';\nimport { computeTrustScore, computeTrustScores } from './scoring.js';\nimport type { ReputationStore } from './store.js';\n\n/** Maximum number of verification records to include in a response */\nconst MAX_VERIFICATIONS_IN_RESPONSE = 50;\n\n/**\n * Handle an incoming reputation query by reading from the local store,\n * computing trust scores, and returning a response.\n *\n * @param query - The reputation query (agent, optional domain, optional after timestamp)\n * @param store - Local reputation store to read from\n * @param currentTime - Current timestamp (ms) for score computation\n * @returns Reputation response with computed scores and verification records\n */\nexport async function handleReputationQuery(\n query: ReputationQuery,\n store: ReputationStore,\n currentTime: number\n): Promise<ReputationResponse> {\n // Get all verifications from the store for score computation\n const allVerifications = await store.getVerifications();\n\n // Filter to verifications targeting the queried agent\n let relevantVerifications = allVerifications.filter(v => v.target === query.agent);\n\n // Apply domain filter if specified\n if (query.domain !== undefined) {\n relevantVerifications = relevantVerifications.filter(v => v.domain === query.domain);\n }\n\n // Apply after-timestamp filter if specified\n if (query.after !== undefined) {\n const after = query.after;\n relevantVerifications = relevantVerifications.filter(v => v.timestamp > after);\n }\n\n // Compute trust scores\n let scores: Record<string, TrustScore>;\n\n if (query.domain !== undefined) {\n const score = computeTrustScore(query.agent, query.domain, allVerifications, currentTime);\n scores = { [query.domain]: score };\n } else {\n const scoreMap = computeTrustScores(query.agent, allVerifications, currentTime);\n scores = {};\n for (const [domain, score] of scoreMap.entries()) {\n scores[domain] = score;\n }\n }\n\n // Size-limit verifications to most recent MAX_VERIFICATIONS_IN_RESPONSE\n const limitedVerifications = relevantVerifications\n .slice()\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, MAX_VERIFICATIONS_IN_RESPONSE);\n\n const response: ReputationResponse = {\n agent: query.agent,\n verifications: limitedVerifications,\n scores,\n };\n\n if (query.domain !== undefined) {\n response.domain = query.domain;\n }\n\n return response;\n}\n","/**\n * Cross-peer reputation synchronization.\n * Pull and merge verification records from trusted peers.\n */\n\nimport type { ReputationQuery, ReputationResponse } from './types.js';\nimport { verifyVerificationSignature } from './verification.js';\nimport type { ReputationStore } from './store.js';\n\n/**\n * Pull reputation data from a peer and merge it into the local store.\n *\n * Flow:\n * 1. Send `reputation_query` to peer via sendMessage\n * 2. Receive `reputation_response` with verification records\n * 3. For each record: verify signature, check domain matches, check not duplicate\n * 4. Append new records to local store\n * 5. Return count of added/skipped\n *\n * @param agentPublicKey - Public key of the agent whose reputation to sync\n * @param domain - Domain to sync reputation for\n * @param store - Local reputation store to merge records into\n * @param sendMessage - Function that sends a reputation_query and returns the response\n * @returns Counts of records added and skipped\n */\nexport async function syncReputationFromPeer(\n agentPublicKey: string,\n domain: string,\n store: ReputationStore,\n sendMessage: (type: string, payload: ReputationQuery) => Promise<ReputationResponse>\n): Promise<{ added: number; skipped: number }> {\n // Build and send the query\n const query: ReputationQuery = {\n agent: agentPublicKey,\n domain,\n };\n\n const response = await sendMessage('reputation_query', query);\n\n // Build set of existing record IDs for fast deduplication\n const existing = await store.getVerifications();\n const existingIds = new Set(existing.map(v => v.id));\n\n let added = 0;\n let skipped = 0;\n\n for (const record of response.verifications) {\n // Skip duplicate records (content-addressed by ID)\n if (existingIds.has(record.id)) {\n skipped++;\n continue;\n }\n\n // Verify cryptographic signature before accepting\n const sigResult = verifyVerificationSignature(record);\n if (!sigResult.valid) {\n skipped++;\n continue;\n }\n\n // Ensure the record's domain matches what we requested\n if (record.domain !== domain) {\n skipped++;\n continue;\n }\n\n // Add to local store and track for deduplication within this batch\n await store.addVerification(record);\n existingIds.add(record.id);\n added++;\n }\n\n return { added, skipped };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AA0B3B,SAAS,gBAAgB,OAAwB;AAC/C,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO,KAAK,UAAU,KAAK;AACtE,MAAI,OAAO,UAAU,SAAU,QAAO,KAAK,UAAU,KAAK;AAC1D,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,MAAM,IAAI,eAAe,EAAE,KAAK,GAAG,IAAI;AAAA,EACtD;AACA,QAAM,OAAO,OAAO,KAAK,KAAgC,EAAE,KAAK;AAChE,QAAM,QAAQ,KAAK,IAAI,OAAK,KAAK,UAAU,CAAC,IAAI,MAAM,gBAAiB,MAAkC,CAAC,CAAC,CAAC;AAC5G,SAAO,MAAM,MAAM,KAAK,GAAG,IAAI;AACjC;AAKA,SAAS,oBAAoB,MAAc,SAAiB,aAAsB,cAA+B;AAC/G,QAAM,OAAO;AAAA,IACX;AAAA,IACA;AAAA,IACA,GAAI,gBAAgB,SAAY,EAAE,YAAY,IAAI,CAAC;AAAA,IACnD,GAAI,iBAAiB,SAAY,EAAE,aAAa,IAAI,CAAC;AAAA,EACvD;AACA,QAAM,YAAY,gBAAgB,IAAI;AACtC,SAAO,WAAW,QAAQ,EAAE,OAAO,SAAS,EAAE,OAAO,KAAK;AAC5D;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;AACL,UAAM,WAAW,mBAAmB,MAAM,OAAO,kBAAkB,WAAW;AAC9E,aAAS,CAAC;AACV,eAAW,CAAC,QAAQ,KAAK,KAAK,SAAS,QAAQ,GAAG;AAChD,aAAO,MAAM,IAAI;AAAA,IACnB;AAAA,EACF;AAGA,QAAM,uBAAuB,sBAC1B,MAAM,EACN,KAAK,CAAC,GAAG,MAAM,EAAE,YAAY,EAAE,SAAS,EACxC,MAAM,GAAG,6BAA6B;AAEzC,QAAM,WAA+B;AAAA,IACnC,OAAO,MAAM;AAAA,IACb,eAAe;AAAA,IACf;AAAA,EACF;AAEA,MAAI,MAAM,WAAW,QAAW;AAC9B,aAAS,SAAS,MAAM;AAAA,EAC1B;AAEA,SAAO;AACT;;;ACjDA,eAAsB,uBACpB,gBACA,QACA,OACA,aAC6C;AAE7C,QAAM,QAAyB;AAAA,IAC7B,OAAO;AAAA,IACP;AAAA,EACF;AAEA,QAAM,WAAW,MAAM,YAAY,oBAAoB,KAAK;AAG5D,QAAM,WAAW,MAAM,MAAM,iBAAiB;AAC9C,QAAM,cAAc,IAAI,IAAI,SAAS,IAAI,OAAK,EAAE,EAAE,CAAC;AAEnD,MAAI,QAAQ;AACZ,MAAI,UAAU;AAEd,aAAW,UAAU,SAAS,eAAe;AAE3C,QAAI,YAAY,IAAI,OAAO,EAAE,GAAG;AAC9B;AACA;AAAA,IACF;AAGA,UAAM,YAAY,4BAA4B,MAAM;AACpD,QAAI,CAAC,UAAU,OAAO;AACpB;AACA;AAAA,IACF;AAGA,QAAI,OAAO,WAAW,QAAQ;AAC5B;AACA;AAAA,IACF;AAGA,UAAM,MAAM,gBAAgB,MAAM;AAClC,gBAAY,IAAI,OAAO,EAAE;AACzB;AAAA,EACF;AAEA,SAAO,EAAE,OAAO,QAAQ;AAC1B;","names":[]}
1
+ {"version":3,"sources":["../src/registry/capability.ts","../src/registry/peer-store.ts","../src/registry/discovery-service.ts","../src/message/types/peer-discovery.ts","../src/config.ts","../src/relay/ignored-peers.ts","../src/service.ts","../src/reputation/network.ts","../src/reputation/sync.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\n/**\n * A capability describes something an agent can do\n */\nexport interface Capability {\n /** Unique ID (content-addressed hash of name + version + schema) */\n id: string;\n /** Human-readable name: 'code-review', 'summarization', 'translation' */\n name: string;\n /** Semantic version */\n version: string;\n /** What the capability does */\n description: string;\n /** JSON Schema for expected input */\n inputSchema?: object;\n /** JSON Schema for expected output */\n outputSchema?: object;\n /** Discovery tags: ['code', 'typescript', 'review'] */\n tags: string[];\n}\n\n/**\n * Deterministic JSON serialization for capability hashing.\n * Recursively sorts object keys.\n */\nfunction stableStringify(value: unknown): string {\n if (value === null || value === undefined) return JSON.stringify(value);\n if (typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return '[' + value.map(stableStringify).join(',') + ']';\n }\n const keys = Object.keys(value as Record<string, unknown>).sort();\n const pairs = keys.map(k => JSON.stringify(k) + ':' + stableStringify((value as Record<string, unknown>)[k]));\n return '{' + pairs.join(',') + '}';\n}\n\n/**\n * Compute content-addressed ID for a capability based on name, version, and schemas.\n */\nfunction computeCapabilityId(name: string, version: string, inputSchema?: object, outputSchema?: object): string {\n const data = {\n name,\n version,\n ...(inputSchema !== undefined ? { inputSchema } : {}),\n ...(outputSchema !== undefined ? { outputSchema } : {}),\n };\n const canonical = stableStringify(data);\n return createHash('sha256').update(canonical).digest('hex');\n}\n\n/**\n * Creates a capability with a content-addressed ID.\n * \n * @param name - Human-readable capability name\n * @param version - Semantic version string\n * @param description - Description of what the capability does\n * @param options - Optional input/output schemas and tags\n * @returns A Capability object with computed ID\n */\nexport function createCapability(\n name: string,\n version: string,\n description: string,\n options: {\n inputSchema?: object;\n outputSchema?: object;\n tags?: string[];\n } = {}\n): Capability {\n const { inputSchema, outputSchema, tags = [] } = options;\n \n const id = computeCapabilityId(name, version, inputSchema, outputSchema);\n \n return {\n id,\n name,\n version,\n description,\n ...(inputSchema !== undefined ? { inputSchema } : {}),\n ...(outputSchema !== undefined ? { outputSchema } : {}),\n tags,\n };\n}\n\n/**\n * Validates that a capability has all required fields.\n * \n * @param capability - The capability to validate\n * @returns Object with `valid` boolean and optional `errors` array\n */\nexport function validateCapability(capability: unknown): { valid: boolean; errors?: string[] } {\n const errors: string[] = [];\n \n if (!capability || typeof capability !== 'object') {\n return { valid: false, errors: ['Capability must be an object'] };\n }\n \n const cap = capability as Record<string, unknown>;\n \n if (!cap.id || typeof cap.id !== 'string') {\n errors.push('Missing or invalid field: id (must be a string)');\n }\n \n if (!cap.name || typeof cap.name !== 'string') {\n errors.push('Missing or invalid field: name (must be a string)');\n }\n \n if (!cap.version || typeof cap.version !== 'string') {\n errors.push('Missing or invalid field: version (must be a string)');\n }\n \n if (!cap.description || typeof cap.description !== 'string') {\n errors.push('Missing or invalid field: description (must be a string)');\n }\n \n if (!Array.isArray(cap.tags)) {\n errors.push('Missing or invalid field: tags (must be an array)');\n } else if (!cap.tags.every(tag => typeof tag === 'string')) {\n errors.push('Invalid field: tags (all elements must be strings)');\n }\n \n if (cap.inputSchema !== undefined && (typeof cap.inputSchema !== 'object' || cap.inputSchema === null)) {\n errors.push('Invalid field: inputSchema (must be an object)');\n }\n \n if (cap.outputSchema !== undefined && (typeof cap.outputSchema !== 'object' || cap.outputSchema === null)) {\n errors.push('Invalid field: outputSchema (must be an object)');\n }\n \n if (errors.length > 0) {\n return { valid: false, errors };\n }\n \n return { valid: true };\n}\n","import type { Peer } from './peer';\n\n/**\n * In-memory store for known peers on the network\n */\nexport class PeerStore {\n private peers: Map<string, Peer> = new Map();\n\n /**\n * Add or update a peer in the store.\n * If a peer with the same publicKey exists, it will be updated.\n * \n * @param peer - The peer to add or update\n */\n addOrUpdatePeer(peer: Peer): void {\n this.peers.set(peer.publicKey, peer);\n }\n\n /**\n * Remove a peer from the store.\n * \n * @param publicKey - The public key of the peer to remove\n * @returns true if the peer was removed, false if it didn't exist\n */\n removePeer(publicKey: string): boolean {\n return this.peers.delete(publicKey);\n }\n\n /**\n * Get a peer by their public key.\n * \n * @param publicKey - The public key of the peer to retrieve\n * @returns The peer if found, undefined otherwise\n */\n getPeer(publicKey: string): Peer | undefined {\n return this.peers.get(publicKey);\n }\n\n /**\n * Find all peers that offer a specific capability by name.\n * \n * @param name - The capability name to search for\n * @returns Array of peers that have a capability with the given name\n */\n findByCapability(name: string): Peer[] {\n const result: Peer[] = [];\n \n for (const peer of this.peers.values()) {\n const hasCapability = peer.capabilities.some(cap => cap.name === name);\n if (hasCapability) {\n result.push(peer);\n }\n }\n \n return result;\n }\n\n /**\n * Find all peers that have capabilities with a specific tag.\n * \n * @param tag - The tag to search for\n * @returns Array of peers that have at least one capability with the given tag\n */\n findByTag(tag: string): Peer[] {\n const result: Peer[] = [];\n \n for (const peer of this.peers.values()) {\n const hasTag = peer.capabilities.some(cap => cap.tags.includes(tag));\n if (hasTag) {\n result.push(peer);\n }\n }\n \n return result;\n }\n\n /**\n * Get all peers in the store.\n * \n * @returns Array of all peers\n */\n allPeers(): Peer[] {\n return Array.from(this.peers.values());\n }\n\n /**\n * Remove peers that haven't been seen within the specified time window.\n * \n * @param maxAgeMs - Maximum age in milliseconds. Peers older than this will be removed.\n * @param currentTime - Current timestamp (ms), defaults to Date.now()\n * @returns Number of peers removed\n */\n prune(maxAgeMs: number, currentTime: number = Date.now()): number {\n const cutoff = currentTime - maxAgeMs;\n let removed = 0;\n \n for (const [publicKey, peer] of this.peers.entries()) {\n if (peer.lastSeen < cutoff) {\n this.peers.delete(publicKey);\n removed++;\n }\n }\n \n return removed;\n }\n}\n","import { createEnvelope, type Envelope } from '../message/envelope';\nimport { PeerStore } from './peer-store';\nimport type { Capability } from './capability';\nimport type { Peer } from './peer';\nimport type {\n CapabilityAnnouncePayload,\n CapabilityQueryPayload,\n CapabilityResponsePayload,\n} from './messages';\n\n/**\n * DiscoveryService manages capability-based peer discovery.\n * It maintains a local index of peer capabilities and handles\n * capability announce, query, and response messages.\n */\nexport class DiscoveryService {\n constructor(\n private peerStore: PeerStore,\n private identity: { publicKey: string; privateKey: string }\n ) {}\n\n /**\n * Announce own capabilities to the network.\n * Creates a capability_announce envelope that can be broadcast to peers.\n * \n * @param capabilities - List of capabilities this agent offers\n * @param metadata - Optional metadata about this agent\n * @returns A signed capability_announce envelope\n */\n announce(\n capabilities: Capability[],\n metadata?: { name?: string; version?: string }\n ): Envelope<CapabilityAnnouncePayload> {\n const payload: CapabilityAnnouncePayload = {\n publicKey: this.identity.publicKey,\n capabilities,\n metadata: metadata ? {\n ...metadata,\n lastSeen: Date.now(),\n } : {\n lastSeen: Date.now(),\n },\n };\n\n return createEnvelope(\n 'capability_announce',\n this.identity.publicKey,\n this.identity.privateKey,\n payload\n );\n }\n\n /**\n * Handle an incoming capability_announce message.\n * Updates the peer store with the announced capabilities.\n * \n * @param envelope - The capability_announce envelope to process\n */\n handleAnnounce(envelope: Envelope<CapabilityAnnouncePayload>): void {\n const { payload } = envelope;\n \n const peer: Peer = {\n publicKey: payload.publicKey,\n capabilities: payload.capabilities,\n lastSeen: payload.metadata?.lastSeen || envelope.timestamp,\n metadata: payload.metadata ? {\n name: payload.metadata.name,\n version: payload.metadata.version,\n } : undefined,\n };\n\n this.peerStore.addOrUpdatePeer(peer);\n }\n\n /**\n * Create a capability query payload.\n * \n * @param queryType - Type of query: 'name', 'tag', or 'schema'\n * @param query - The query value (capability name, tag, or schema)\n * @param filters - Optional filters (limit, minTrustScore)\n * @returns A capability_query payload\n */\n query(\n queryType: 'name' | 'tag' | 'schema',\n query: string | object,\n filters?: { limit?: number; minTrustScore?: number }\n ): CapabilityQueryPayload {\n return {\n queryType,\n query,\n filters,\n };\n }\n\n /**\n * Handle an incoming capability_query message.\n * Searches the local peer store and returns matching peers.\n * \n * @param envelope - The capability_query envelope to process\n * @returns A capability_response envelope with matching peers\n */\n handleQuery(\n envelope: Envelope<CapabilityQueryPayload>\n ): Envelope<CapabilityResponsePayload> {\n const { payload } = envelope;\n let peers: Peer[] = [];\n\n // Execute query based on type\n if (payload.queryType === 'name' && typeof payload.query === 'string') {\n peers = this.peerStore.findByCapability(payload.query);\n } else if (payload.queryType === 'tag' && typeof payload.query === 'string') {\n peers = this.peerStore.findByTag(payload.query);\n } else if (payload.queryType === 'schema') {\n // Schema-based matching is deferred to Phase 2b\n // For now, return empty results\n peers = [];\n }\n\n // Apply filters\n const limit = payload.filters?.limit;\n const totalMatches = peers.length;\n \n if (limit !== undefined && limit > 0) {\n peers = peers.slice(0, limit);\n }\n\n // Transform peers to response format\n const responsePeers = peers.map(peer => ({\n publicKey: peer.publicKey,\n capabilities: peer.capabilities,\n metadata: peer.metadata ? {\n name: peer.metadata.name,\n version: peer.metadata.version,\n lastSeen: peer.lastSeen,\n } : {\n lastSeen: peer.lastSeen,\n },\n // Trust score integration deferred to Phase 2b (RFC-001)\n trustScore: undefined,\n }));\n\n const responsePayload: CapabilityResponsePayload = {\n queryId: envelope.id,\n peers: responsePeers,\n totalMatches,\n };\n\n return createEnvelope(\n 'capability_response',\n this.identity.publicKey,\n this.identity.privateKey,\n responsePayload,\n Date.now(),\n envelope.id // inReplyTo\n );\n }\n\n /**\n * Remove peers that haven't been seen within the specified time window.\n * \n * @param maxAgeMs - Maximum age in milliseconds\n * @returns Number of peers removed\n */\n pruneStale(maxAgeMs: number, currentTime: number = Date.now()): number {\n return this.peerStore.prune(maxAgeMs, currentTime);\n }\n}\n","/**\n * Peer discovery message types for the Agora network.\n */\n\n/**\n * Request peer list from relay\n */\nexport interface PeerListRequestPayload {\n /** Optional filters */\n filters?: {\n /** Only peers seen in last N ms */\n activeWithin?: number;\n /** Maximum peers to return */\n limit?: number;\n };\n}\n\n/**\n * Relay responds with connected peers\n */\nexport interface PeerListResponsePayload {\n /** List of known peers */\n peers: Array<{\n /** Peer's Ed25519 public key */\n publicKey: string;\n /** Optional metadata (if peer announced) */\n metadata?: {\n name?: string;\n version?: string;\n capabilities?: string[];\n };\n /** Last seen timestamp (ms) */\n lastSeen: number;\n }>;\n /** Total peer count (may be > peers.length if limited) */\n totalPeers: number;\n /** Relay's public key (for trust verification) */\n relayPublicKey: string;\n}\n\n/**\n * Agent recommends another agent\n */\nexport interface PeerReferralPayload {\n /** Referred peer's public key */\n publicKey: string;\n /** Optional endpoint (if known) */\n endpoint?: string;\n /** Optional metadata */\n metadata?: {\n name?: string;\n version?: string;\n capabilities?: string[];\n };\n /** Referrer's comment */\n comment?: string;\n /** Trust hint (RFC-001 integration) */\n trustScore?: number;\n}\n\n/**\n * Validate PeerListRequestPayload\n */\nexport function validatePeerListRequest(payload: unknown): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n if (typeof payload !== 'object' || payload === null) {\n errors.push('Payload must be an object');\n return { valid: false, errors };\n }\n\n const p = payload as Record<string, unknown>;\n\n if (p.filters !== undefined) {\n if (typeof p.filters !== 'object' || p.filters === null) {\n errors.push('filters must be an object');\n } else {\n const filters = p.filters as Record<string, unknown>;\n if (filters.activeWithin !== undefined && typeof filters.activeWithin !== 'number') {\n errors.push('filters.activeWithin must be a number');\n }\n if (filters.limit !== undefined && typeof filters.limit !== 'number') {\n errors.push('filters.limit must be a number');\n }\n }\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate PeerListResponsePayload\n */\nexport function validatePeerListResponse(payload: unknown): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n if (typeof payload !== 'object' || payload === null) {\n errors.push('Payload must be an object');\n return { valid: false, errors };\n }\n\n const p = payload as Record<string, unknown>;\n\n if (!Array.isArray(p.peers)) {\n errors.push('peers must be an array');\n } else {\n p.peers.forEach((peer, index) => {\n if (typeof peer !== 'object' || peer === null) {\n errors.push(`peers[${index}] must be an object`);\n return;\n }\n const peerObj = peer as Record<string, unknown>;\n if (typeof peerObj.publicKey !== 'string') {\n errors.push(`peers[${index}].publicKey must be a string`);\n }\n if (typeof peerObj.lastSeen !== 'number') {\n errors.push(`peers[${index}].lastSeen must be a number`);\n }\n });\n }\n\n if (typeof p.totalPeers !== 'number') {\n errors.push('totalPeers must be a number');\n }\n\n if (typeof p.relayPublicKey !== 'string') {\n errors.push('relayPublicKey must be a string');\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate PeerReferralPayload\n */\nexport function validatePeerReferral(payload: unknown): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n if (typeof payload !== 'object' || payload === null) {\n errors.push('Payload must be an object');\n return { valid: false, errors };\n }\n\n const p = payload as Record<string, unknown>;\n\n if (typeof p.publicKey !== 'string') {\n errors.push('publicKey must be a string');\n }\n\n if (p.endpoint !== undefined && typeof p.endpoint !== 'string') {\n errors.push('endpoint must be a string');\n }\n\n if (p.comment !== undefined && typeof p.comment !== 'string') {\n errors.push('comment must be a string');\n }\n\n if (p.trustScore !== undefined && typeof p.trustScore !== 'number') {\n errors.push('trustScore must be a number');\n }\n\n return { valid: errors.length === 0, errors };\n}\n","import { readFileSync, existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { homedir } from 'node:os';\n\n/**\n * Normalized relay configuration (supports both string and object in config file).\n */\nexport interface RelayConfig {\n url: string;\n autoConnect: boolean;\n name?: string;\n reconnectMaxMs?: number;\n}\n\n/**\n * Peer entry in config (webhook URL, token, public key).\n */\nexport interface AgoraPeerConfig {\n publicKey: string;\n /** Webhook URL (undefined for relay-only peers) */\n url?: string;\n /** Webhook auth token (undefined for relay-only peers) */\n token?: string;\n name?: string;\n}\n\n/**\n * Identity with optional display name (e.g. for relay registration).\n */\nexport interface AgoraIdentity {\n publicKey: string;\n privateKey: string;\n name?: string;\n}\n\n/**\n * Canonical Agora configuration shape.\n * Use loadAgoraConfig() to load from file with normalized relay.\n */\nexport interface AgoraConfig {\n identity: AgoraIdentity;\n peers: Record<string, AgoraPeerConfig>;\n relay?: RelayConfig;\n}\n\n/**\n * Default config file path: AGORA_CONFIG env or ~/.config/agora/config.json\n */\nexport function getDefaultConfigPath(): string {\n if (process.env.AGORA_CONFIG) {\n return resolve(process.env.AGORA_CONFIG);\n }\n return resolve(homedir(), '.config', 'agora', 'config.json');\n}\n\n/**\n * Parse and normalize config from a JSON object (shared by sync and async loaders).\n */\nfunction parseConfig(config: Record<string, unknown>): AgoraConfig {\n const rawIdentity = config.identity as Record<string, unknown> | undefined;\n if (!rawIdentity?.publicKey || !rawIdentity?.privateKey) {\n throw new Error('Invalid config: missing identity.publicKey or identity.privateKey');\n }\n const identity: AgoraIdentity = {\n publicKey: rawIdentity.publicKey as string,\n privateKey: rawIdentity.privateKey as string,\n name: typeof rawIdentity.name === 'string' ? rawIdentity.name : undefined,\n };\n\n const peers: Record<string, AgoraPeerConfig> = {};\n if (config.peers && typeof config.peers === 'object') {\n for (const [name, entry] of Object.entries(config.peers)) {\n const peer = entry as Record<string, unknown>;\n if (peer && typeof peer.publicKey === 'string') {\n peers[name] = {\n publicKey: peer.publicKey as string,\n url: typeof peer.url === 'string' ? peer.url : undefined,\n token: typeof peer.token === 'string' ? peer.token : undefined,\n name: typeof peer.name === 'string' ? peer.name : undefined,\n };\n }\n }\n }\n\n let relay: RelayConfig | undefined;\n const rawRelay = config.relay;\n if (typeof rawRelay === 'string') {\n relay = { url: rawRelay, autoConnect: true };\n } else if (rawRelay && typeof rawRelay === 'object') {\n const r = rawRelay as Record<string, unknown>;\n if (typeof r.url === 'string') {\n relay = {\n url: r.url,\n autoConnect: typeof r.autoConnect === 'boolean' ? r.autoConnect : true,\n name: typeof r.name === 'string' ? r.name : undefined,\n reconnectMaxMs: typeof r.reconnectMaxMs === 'number' ? r.reconnectMaxMs : undefined,\n };\n }\n }\n\n return {\n identity,\n peers,\n ...(relay ? { relay } : {}),\n };\n}\n\n/**\n * Load and normalize Agora configuration from a JSON file (sync).\n * Supports relay as string (backward compat) or object { url?, autoConnect?, name?, reconnectMaxMs? }.\n *\n * @param path - Config file path; defaults to getDefaultConfigPath()\n * @returns Normalized AgoraConfig\n * @throws Error if file doesn't exist or config is invalid\n */\nexport function loadAgoraConfig(path?: string): AgoraConfig {\n const configPath = path ?? getDefaultConfigPath();\n\n if (!existsSync(configPath)) {\n throw new Error(`Config file not found at ${configPath}. Run 'npx @rookdaemon/agora init' first.`);\n }\n\n const content = readFileSync(configPath, 'utf-8');\n let config: Record<string, unknown>;\n try {\n config = JSON.parse(content) as Record<string, unknown>;\n } catch {\n throw new Error(`Invalid JSON in config file: ${configPath}`);\n }\n\n return parseConfig(config);\n}\n\n/**\n * Load and normalize Agora configuration from a JSON file (async).\n *\n * @param path - Config file path; defaults to getDefaultConfigPath()\n * @returns Normalized AgoraConfig\n * @throws Error if file doesn't exist or config is invalid\n */\nexport async function loadAgoraConfigAsync(path?: string): Promise<AgoraConfig> {\n const configPath = path ?? getDefaultConfigPath();\n\n let content: string;\n try {\n content = await readFile(configPath, 'utf-8');\n } catch (err) {\n const code = err && typeof err === 'object' && 'code' in err ? (err as NodeJS.ErrnoException).code : undefined;\n if (code === 'ENOENT') {\n throw new Error(`Config file not found at ${configPath}. Run 'npx @rookdaemon/agora init' first.`);\n }\n throw err;\n }\n\n let config: Record<string, unknown>;\n try {\n config = JSON.parse(content) as Record<string, unknown>;\n } catch {\n throw new Error(`Invalid JSON in config file: ${configPath}`);\n }\n\n return parseConfig(config);\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\nimport { getDefaultConfigPath } from '../config';\n\nexport const IGNORED_FILE_NAME = 'IGNORED_PEERS.md';\n\nexport function getIgnoredPeersPath(storageDir?: string): string {\n if (storageDir) {\n return join(storageDir, IGNORED_FILE_NAME);\n }\n const configPath = getDefaultConfigPath();\n return join(dirname(configPath), IGNORED_FILE_NAME);\n}\n\nexport function loadIgnoredPeers(filePath?: string): string[] {\n const path = filePath ?? getIgnoredPeersPath();\n if (!existsSync(path)) return [];\n\n const lines = readFileSync(path, 'utf-8')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith('#'));\n\n return Array.from(new Set(lines));\n}\n\nexport function saveIgnoredPeers(peers: string[], filePath?: string): void {\n const path = filePath ?? getIgnoredPeersPath();\n const dir = dirname(path);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n const unique = Array.from(new Set(peers.map((peer) => peer.trim()).filter(Boolean))).sort();\n const content = [\n '# Ignored peers',\n '# One public key per line',\n ...unique,\n '',\n ].join('\\n');\n\n writeFileSync(path, content, 'utf-8');\n}\n","import type { AgoraIdentity, RelayConfig } from './config';\nimport { getDefaultConfigPath, loadAgoraConfigAsync } from './config';\nimport type { Envelope } from './message/envelope';\nimport type { MessageType } from './message/envelope';\nimport { RelayClient } from './relay/client';\nimport type { PeerConfig } from './transport/http';\nimport { decodeInboundEnvelope, sendToPeer } from './transport/http';\nimport { sendViaRelay } from './transport/relay';\nimport { shortKey } from './utils';\n\n/**\n * Service config: identity, peers keyed by name, optional relay.\n */\nexport interface AgoraServiceConfig {\n identity: AgoraIdentity;\n peers: Map<string, PeerConfig>;\n relay?: RelayConfig;\n}\n\nexport interface SendMessageOptions {\n peerName: string;\n type: MessageType;\n payload: unknown;\n inReplyTo?: string;\n /** Skip relay, send directly via HTTP only. Fails if peer has no URL or is unreachable. */\n direct?: boolean;\n /** Skip direct HTTP, always use relay even if peer has a URL. */\n relayOnly?: boolean;\n}\n\nexport interface SendMessageResult {\n ok: boolean;\n status: number;\n error?: string;\n}\n\nexport interface ReplyToEnvelopeOptions {\n /** The public key of the target (from envelope.sender) */\n targetPubkey: string;\n /** Message type for the reply */\n type: MessageType;\n /** Reply payload */\n payload: unknown;\n /** The envelope ID being replied to (required — this IS a reply) */\n inReplyTo: string;\n}\n\nexport interface DecodeInboundResult {\n ok: boolean;\n envelope?: Envelope;\n reason?: string;\n}\n\n/** Handler for relay messages. (envelope, fromPublicKey, fromName?) */\nexport type RelayMessageHandlerWithName = (envelope: Envelope, from: string, fromName?: string) => void;\n\n/** @deprecated Use RelayMessageHandlerWithName. Kept for backward compatibility. */\nexport type RelayMessageHandler = (envelope: Envelope) => void;\n\nexport interface Logger {\n debug(message: string): void;\n}\n\nexport interface RelayClientLike {\n connect(): Promise<void>;\n disconnect(): void;\n connected(): boolean;\n send(to: string, envelope: Envelope): Promise<{ ok: boolean; error?: string }>;\n on(event: 'message', handler: (envelope: Envelope, from: string, fromName?: string) => void): void;\n on(event: 'error', handler: (error: Error) => void): void;\n}\n\nexport interface RelayClientFactory {\n (opts: {\n relayUrl: string;\n publicKey: string;\n privateKey: string;\n name?: string;\n pingInterval: number;\n maxReconnectDelay: number;\n }): RelayClientLike;\n}\n\n/**\n * High-level Agora service: send by peer name, decode inbound, relay lifecycle.\n */\nexport class AgoraService {\n private config: AgoraServiceConfig;\n private relayClient: RelayClientLike | null = null;\n private readonly onRelayMessage: RelayMessageHandlerWithName;\n private logger: Logger | null;\n private relayClientFactory: RelayClientFactory | null;\n\n /**\n * @param config - Service config (identity, peers, optional relay)\n * @param onRelayMessage - Required callback for relay messages. Ensures no messages are lost between init and connect.\n * @param logger - Optional debug logger\n * @param relayClientFactory - Optional factory for relay client (for testing)\n */\n constructor(\n config: AgoraServiceConfig,\n onRelayMessage: RelayMessageHandlerWithName,\n logger?: Logger,\n relayClientFactory?: RelayClientFactory\n ) {\n this.config = config;\n this.onRelayMessage = onRelayMessage;\n this.logger = logger ?? null;\n this.relayClientFactory = relayClientFactory ?? null;\n }\n\n /**\n * Send a signed message to a named peer.\n * Tries HTTP webhook first; falls back to relay if HTTP is unavailable.\n */\n async sendMessage(options: SendMessageOptions): Promise<SendMessageResult> {\n const peer = this.config.peers.get(options.peerName);\n if (!peer) {\n return {\n ok: false,\n status: 0,\n error: `Unknown peer: ${options.peerName}`,\n };\n }\n\n // Try HTTP first (only if peer has a webhook URL and --relay-only not set)\n if (peer.url && !options.relayOnly) {\n const transportConfig = {\n identity: {\n publicKey: this.config.identity.publicKey,\n privateKey: this.config.identity.privateKey,\n },\n peers: new Map<string, PeerConfig>([[peer.publicKey, peer]]),\n };\n\n const httpResult = await sendToPeer(\n transportConfig,\n peer.publicKey,\n options.type,\n options.payload,\n options.inReplyTo\n );\n\n if (httpResult.ok) {\n return httpResult;\n }\n\n this.logger?.debug(`HTTP send to ${options.peerName} failed: ${httpResult.error}`);\n\n // --direct flag: do not fall back to relay\n if (options.direct) {\n return {\n ok: false,\n status: httpResult.status,\n error: `Direct send to ${options.peerName} failed: ${httpResult.error}`,\n };\n }\n } else if (options.direct && !peer.url) {\n // --direct requested but peer has no URL configured\n return {\n ok: false,\n status: 0,\n error: `Direct send failed: peer '${options.peerName}' has no URL configured`,\n };\n }\n\n // Fall back to relay\n if (this.relayClient?.connected() && this.config.relay) {\n const relayResult = await sendViaRelay(\n {\n identity: this.config.identity,\n relayUrl: this.config.relay.url,\n relayClient: this.relayClient,\n },\n peer.publicKey,\n options.type,\n options.payload,\n options.inReplyTo\n );\n\n return {\n ok: relayResult.ok,\n status: 0,\n error: relayResult.error,\n };\n }\n\n // Both failed\n return {\n ok: false,\n status: 0,\n error: peer.url\n ? `HTTP send failed and relay not available for peer: ${options.peerName}`\n : `No webhook URL and relay not available for peer: ${options.peerName}`,\n };\n }\n\n /**\n * Reply to an envelope from any sender via relay.\n * Unlike sendMessage(), this does NOT require the target to be a configured peer.\n * Uses the target's public key directly — relay-only (no HTTP, since unknown peers have no URL).\n */\n async replyToEnvelope(options: ReplyToEnvelopeOptions): Promise<SendMessageResult> {\n if (!this.relayClient?.connected() || !this.config.relay) {\n return {\n ok: false,\n status: 0,\n error: 'Relay not connected — cannot reply to envelope without relay',\n };\n }\n\n this.logger?.debug(\n `Replying to envelope via relay: target=${shortKey(options.targetPubkey)} type=${options.type} inReplyTo=${options.inReplyTo}`\n );\n\n const relayResult = await sendViaRelay(\n {\n identity: this.config.identity,\n relayUrl: this.config.relay.url,\n relayClient: this.relayClient,\n },\n options.targetPubkey,\n options.type,\n options.payload,\n options.inReplyTo\n );\n\n return {\n ok: relayResult.ok,\n status: 0,\n error: relayResult.error,\n };\n }\n\n /**\n * Decode and verify an inbound envelope from a webhook message.\n */\n async decodeInbound(message: string): Promise<DecodeInboundResult> {\n const peersByPubKey = new Map<string, PeerConfig>();\n for (const peer of this.config.peers.values()) {\n peersByPubKey.set(peer.publicKey, peer);\n }\n const result = decodeInboundEnvelope(message, peersByPubKey);\n if (result.ok) {\n return { ok: true, envelope: result.envelope };\n }\n return { ok: false, reason: result.reason };\n }\n\n getPeers(): string[] {\n return Array.from(this.config.peers.keys());\n }\n\n getPeerConfig(name: string): PeerConfig | undefined {\n return this.config.peers.get(name);\n }\n\n /**\n * Connect to the relay server.\n */\n async connectRelay(url: string): Promise<void> {\n if (this.relayClient) {\n return;\n }\n\n const maxReconnectDelay = this.config.relay?.reconnectMaxMs ?? 300000;\n let name = this.config.identity.name ?? this.config.relay?.name;\n // Never use the short key (id) as the relay display name; treat it as no name\n if (name && name === shortKey(this.config.identity.publicKey)) {\n name = undefined;\n }\n const opts = {\n relayUrl: url,\n publicKey: this.config.identity.publicKey,\n privateKey: this.config.identity.privateKey,\n name,\n pingInterval: 30000,\n maxReconnectDelay,\n };\n\n if (this.relayClientFactory) {\n this.relayClient = this.relayClientFactory(opts);\n } else {\n this.relayClient = new RelayClient(opts);\n }\n\n this.relayClient.on('error', (error: Error) => {\n this.logger?.debug(`Agora relay error: ${error.message}`);\n });\n\n this.relayClient.on('message', (envelope: Envelope, from: string, fromName?: string) => {\n this.onRelayMessage(envelope, from, fromName);\n });\n\n try {\n await this.relayClient.connect();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger?.debug(`Agora relay connect failed (${url}): ${message}`);\n this.relayClient = null;\n }\n }\n\n async disconnectRelay(): Promise<void> {\n if (this.relayClient) {\n this.relayClient.disconnect();\n this.relayClient = null;\n }\n }\n\n isRelayConnected(): boolean {\n return this.relayClient?.connected() ?? false;\n }\n\n /**\n * Load Agora configuration and return service config (peers as Map).\n */\n static async loadConfig(path?: string): Promise<AgoraServiceConfig> {\n const configPath = path ?? getDefaultConfigPath();\n const loaded = await loadAgoraConfigAsync(configPath);\n\n const peers = new Map<string, PeerConfig>();\n for (const [name, p] of Object.entries(loaded.peers)) {\n peers.set(name, {\n publicKey: p.publicKey,\n url: p.url,\n token: p.token,\n } satisfies PeerConfig);\n }\n\n return {\n identity: loaded.identity,\n peers,\n relay: loaded.relay,\n };\n }\n}\n","/**\n * Network reputation query handler.\n * Handles incoming reputation_query messages and returns reputation_response.\n */\n\nimport type { ReputationQuery, ReputationResponse, TrustScore } from './types.js';\nimport { computeTrustScore, computeTrustScores } from './scoring.js';\nimport type { ReputationStore } from './store.js';\n\n/** Maximum number of verification records to include in a response */\nconst MAX_VERIFICATIONS_IN_RESPONSE = 50;\n\n/**\n * Handle an incoming reputation query by reading from the local store,\n * computing trust scores, and returning a response.\n *\n * @param query - The reputation query (agent, optional domain, optional after timestamp)\n * @param store - Local reputation store to read from\n * @param currentTime - Current timestamp (ms) for score computation\n * @returns Reputation response with computed scores and verification records\n */\nexport async function handleReputationQuery(\n query: ReputationQuery,\n store: ReputationStore,\n currentTime: number\n): Promise<ReputationResponse> {\n // Get all verifications from the store for score computation\n const allVerifications = await store.getVerifications();\n\n // Filter to verifications targeting the queried agent\n let relevantVerifications = allVerifications.filter(v => v.target === query.agent);\n\n // Apply domain filter if specified\n if (query.domain !== undefined) {\n relevantVerifications = relevantVerifications.filter(v => v.domain === query.domain);\n }\n\n // Apply after-timestamp filter if specified\n if (query.after !== undefined) {\n const after = query.after;\n relevantVerifications = relevantVerifications.filter(v => v.timestamp > after);\n }\n\n // Compute trust scores\n let scores: Record<string, TrustScore>;\n\n if (query.domain !== undefined) {\n const score = computeTrustScore(query.agent, query.domain, allVerifications, currentTime);\n scores = { [query.domain]: score };\n } else {\n const scoreMap = computeTrustScores(query.agent, allVerifications, currentTime);\n scores = {};\n for (const [domain, score] of scoreMap.entries()) {\n scores[domain] = score;\n }\n }\n\n // Size-limit verifications to most recent MAX_VERIFICATIONS_IN_RESPONSE\n const limitedVerifications = relevantVerifications\n .slice()\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, MAX_VERIFICATIONS_IN_RESPONSE);\n\n const response: ReputationResponse = {\n agent: query.agent,\n verifications: limitedVerifications,\n scores,\n };\n\n if (query.domain !== undefined) {\n response.domain = query.domain;\n }\n\n return response;\n}\n","/**\n * Cross-peer reputation synchronization.\n * Pull and merge verification records from trusted peers.\n */\n\nimport type { ReputationQuery, ReputationResponse } from './types.js';\nimport { verifyVerificationSignature } from './verification.js';\nimport type { ReputationStore } from './store.js';\n\n/**\n * Pull reputation data from a peer and merge it into the local store.\n *\n * Flow:\n * 1. Send `reputation_query` to peer via sendMessage\n * 2. Receive `reputation_response` with verification records\n * 3. For each record: verify signature, check domain matches, check not duplicate\n * 4. Append new records to local store\n * 5. Return count of added/skipped\n *\n * @param agentPublicKey - Public key of the agent whose reputation to sync\n * @param domain - Domain to sync reputation for\n * @param store - Local reputation store to merge records into\n * @param sendMessage - Function that sends a reputation_query and returns the response\n * @returns Counts of records added and skipped\n */\nexport async function syncReputationFromPeer(\n agentPublicKey: string,\n domain: string,\n store: ReputationStore,\n sendMessage: (type: string, payload: ReputationQuery) => Promise<ReputationResponse>\n): Promise<{ added: number; skipped: number }> {\n // Build and send the query\n const query: ReputationQuery = {\n agent: agentPublicKey,\n domain,\n };\n\n const response = await sendMessage('reputation_query', query);\n\n // Build set of existing record IDs for fast deduplication\n const existing = await store.getVerifications();\n const existingIds = new Set(existing.map(v => v.id));\n\n let added = 0;\n let skipped = 0;\n\n for (const record of response.verifications) {\n // Skip duplicate records (content-addressed by ID)\n if (existingIds.has(record.id)) {\n skipped++;\n continue;\n }\n\n // Verify cryptographic signature before accepting\n const sigResult = verifyVerificationSignature(record);\n if (!sigResult.valid) {\n skipped++;\n continue;\n }\n\n // Ensure the record's domain matches what we requested\n if (record.domain !== domain) {\n skipped++;\n continue;\n }\n\n // Add to local store and track for deduplication within this batch\n await store.addVerification(record);\n existingIds.add(record.id);\n added++;\n }\n\n return { added, skipped };\n}\n"],"mappings":";;;;;;;;;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ACF;AAEA,QAAM,WAAW,MAAM,YAAY,oBAAoB,KAAK;AAG5D,QAAM,WAAW,MAAM,MAAM,iBAAiB;AAC9C,QAAM,cAAc,IAAI,IAAI,SAAS,IAAI,OAAK,EAAE,EAAE,CAAC;AAEnD,MAAI,QAAQ;AACZ,MAAI,UAAU;AAEd,aAAW,UAAU,SAAS,eAAe;AAE3C,QAAI,YAAY,IAAI,OAAO,EAAE,GAAG;AAC9B;AACA;AAAA,IACF;AAGA,UAAM,YAAY,4BAA4B,MAAM;AACpD,QAAI,CAAC,UAAU,OAAO;AACpB;AACA;AAAA,IACF;AAGA,QAAI,OAAO,WAAW,QAAQ;AAC5B;AACA;AAAA,IACF;AAGA,UAAM,MAAM,gBAAgB,MAAM;AAClC,gBAAY,IAAI,OAAO,EAAE;AACzB;AAAA,EACF;AAEA,SAAO,EAAE,OAAO,QAAQ;AAC1B;","names":["readFileSync","existsSync","existsSync","readFileSync"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rookdaemon/agora",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "description": "A coordination network for AI agents",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",