@rookdaemon/agora 0.2.8 → 0.2.9

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.
Files changed (143) hide show
  1. package/dist/chunk-JUOGKXFN.js +1645 -0
  2. package/dist/chunk-JUOGKXFN.js.map +1 -0
  3. package/dist/cli.d.ts +0 -2
  4. package/dist/cli.js +1163 -1137
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.d.ts +1613 -30
  7. package/dist/index.js +1135 -29
  8. package/dist/index.js.map +1 -1
  9. package/package.json +4 -2
  10. package/dist/cli.d.ts.map +0 -1
  11. package/dist/config.d.ts +0 -59
  12. package/dist/config.d.ts.map +0 -1
  13. package/dist/config.js +0 -115
  14. package/dist/config.js.map +0 -1
  15. package/dist/discovery/bootstrap.d.ts +0 -32
  16. package/dist/discovery/bootstrap.d.ts.map +0 -1
  17. package/dist/discovery/bootstrap.js +0 -36
  18. package/dist/discovery/bootstrap.js.map +0 -1
  19. package/dist/discovery/peer-discovery.d.ts +0 -59
  20. package/dist/discovery/peer-discovery.d.ts.map +0 -1
  21. package/dist/discovery/peer-discovery.js +0 -108
  22. package/dist/discovery/peer-discovery.js.map +0 -1
  23. package/dist/identity/keypair.d.ts +0 -42
  24. package/dist/identity/keypair.d.ts.map +0 -1
  25. package/dist/identity/keypair.js +0 -83
  26. package/dist/identity/keypair.js.map +0 -1
  27. package/dist/index.d.ts.map +0 -1
  28. package/dist/message/envelope.d.ts +0 -59
  29. package/dist/message/envelope.d.ts.map +0 -1
  30. package/dist/message/envelope.js +0 -83
  31. package/dist/message/envelope.js.map +0 -1
  32. package/dist/message/types/paper-discovery.d.ts +0 -28
  33. package/dist/message/types/paper-discovery.d.ts.map +0 -1
  34. package/dist/message/types/paper-discovery.js +0 -2
  35. package/dist/message/types/paper-discovery.js.map +0 -1
  36. package/dist/message/types/peer-discovery.d.ts +0 -78
  37. package/dist/message/types/peer-discovery.d.ts.map +0 -1
  38. package/dist/message/types/peer-discovery.js +0 -90
  39. package/dist/message/types/peer-discovery.js.map +0 -1
  40. package/dist/peer/client.d.ts +0 -50
  41. package/dist/peer/client.d.ts.map +0 -1
  42. package/dist/peer/client.js +0 -138
  43. package/dist/peer/client.js.map +0 -1
  44. package/dist/peer/manager.d.ts +0 -65
  45. package/dist/peer/manager.d.ts.map +0 -1
  46. package/dist/peer/manager.js +0 -153
  47. package/dist/peer/manager.js.map +0 -1
  48. package/dist/peer/server.d.ts +0 -65
  49. package/dist/peer/server.d.ts.map +0 -1
  50. package/dist/peer/server.js +0 -154
  51. package/dist/peer/server.js.map +0 -1
  52. package/dist/registry/capability.d.ts +0 -44
  53. package/dist/registry/capability.d.ts.map +0 -1
  54. package/dist/registry/capability.js +0 -94
  55. package/dist/registry/capability.js.map +0 -1
  56. package/dist/registry/discovery-service.d.ts +0 -64
  57. package/dist/registry/discovery-service.d.ts.map +0 -1
  58. package/dist/registry/discovery-service.js +0 -129
  59. package/dist/registry/discovery-service.js.map +0 -1
  60. package/dist/registry/messages.d.ts +0 -105
  61. package/dist/registry/messages.d.ts.map +0 -1
  62. package/dist/registry/messages.js +0 -2
  63. package/dist/registry/messages.js.map +0 -1
  64. package/dist/registry/peer-store.d.ts +0 -57
  65. package/dist/registry/peer-store.d.ts.map +0 -1
  66. package/dist/registry/peer-store.js +0 -92
  67. package/dist/registry/peer-store.js.map +0 -1
  68. package/dist/registry/peer.d.ts +0 -20
  69. package/dist/registry/peer.d.ts.map +0 -1
  70. package/dist/registry/peer.js +0 -2
  71. package/dist/registry/peer.js.map +0 -1
  72. package/dist/relay/client.d.ts +0 -112
  73. package/dist/relay/client.d.ts.map +0 -1
  74. package/dist/relay/client.js +0 -281
  75. package/dist/relay/client.js.map +0 -1
  76. package/dist/relay/jwt-auth.d.ts +0 -40
  77. package/dist/relay/jwt-auth.d.ts.map +0 -1
  78. package/dist/relay/jwt-auth.js +0 -109
  79. package/dist/relay/jwt-auth.js.map +0 -1
  80. package/dist/relay/message-buffer.d.ts +0 -41
  81. package/dist/relay/message-buffer.d.ts.map +0 -1
  82. package/dist/relay/message-buffer.js +0 -53
  83. package/dist/relay/message-buffer.js.map +0 -1
  84. package/dist/relay/rest-api.d.ts +0 -68
  85. package/dist/relay/rest-api.d.ts.map +0 -1
  86. package/dist/relay/rest-api.js +0 -225
  87. package/dist/relay/rest-api.js.map +0 -1
  88. package/dist/relay/run-relay.d.ts +0 -33
  89. package/dist/relay/run-relay.d.ts.map +0 -1
  90. package/dist/relay/run-relay.js +0 -57
  91. package/dist/relay/run-relay.js.map +0 -1
  92. package/dist/relay/server.d.ts +0 -91
  93. package/dist/relay/server.d.ts.map +0 -1
  94. package/dist/relay/server.js +0 -385
  95. package/dist/relay/server.js.map +0 -1
  96. package/dist/relay/store.d.ts +0 -19
  97. package/dist/relay/store.d.ts.map +0 -1
  98. package/dist/relay/store.js +0 -55
  99. package/dist/relay/store.js.map +0 -1
  100. package/dist/relay/types.d.ts +0 -35
  101. package/dist/relay/types.d.ts.map +0 -1
  102. package/dist/relay/types.js +0 -2
  103. package/dist/relay/types.js.map +0 -1
  104. package/dist/reputation/commit-reveal.d.ts +0 -45
  105. package/dist/reputation/commit-reveal.d.ts.map +0 -1
  106. package/dist/reputation/commit-reveal.js +0 -125
  107. package/dist/reputation/commit-reveal.js.map +0 -1
  108. package/dist/reputation/scoring.d.ts +0 -31
  109. package/dist/reputation/scoring.d.ts.map +0 -1
  110. package/dist/reputation/scoring.js +0 -105
  111. package/dist/reputation/scoring.js.map +0 -1
  112. package/dist/reputation/store.d.ts +0 -83
  113. package/dist/reputation/store.d.ts.map +0 -1
  114. package/dist/reputation/store.js +0 -202
  115. package/dist/reputation/store.js.map +0 -1
  116. package/dist/reputation/types.d.ts +0 -150
  117. package/dist/reputation/types.d.ts.map +0 -1
  118. package/dist/reputation/types.js +0 -113
  119. package/dist/reputation/types.js.map +0 -1
  120. package/dist/reputation/verification.d.ts +0 -28
  121. package/dist/reputation/verification.d.ts.map +0 -1
  122. package/dist/reputation/verification.js +0 -91
  123. package/dist/reputation/verification.js.map +0 -1
  124. package/dist/service.d.ts +0 -90
  125. package/dist/service.d.ts.map +0 -1
  126. package/dist/service.js +0 -176
  127. package/dist/service.js.map +0 -1
  128. package/dist/transport/http.d.ts +0 -41
  129. package/dist/transport/http.d.ts.map +0 -1
  130. package/dist/transport/http.js +0 -103
  131. package/dist/transport/http.js.map +0 -1
  132. package/dist/transport/peer-config.d.ts +0 -38
  133. package/dist/transport/peer-config.d.ts.map +0 -1
  134. package/dist/transport/peer-config.js +0 -41
  135. package/dist/transport/peer-config.js.map +0 -1
  136. package/dist/transport/relay.d.ts +0 -30
  137. package/dist/transport/relay.d.ts.map +0 -1
  138. package/dist/transport/relay.js +0 -85
  139. package/dist/transport/relay.js.map +0 -1
  140. package/dist/utils.d.ts +0 -40
  141. package/dist/utils.d.ts.map +0 -1
  142. package/dist/utils.js +0 -59
  143. package/dist/utils.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/identity/keypair.ts","../src/transport/peer-config.ts","../src/message/envelope.ts","../src/transport/http.ts","../src/transport/relay.ts","../src/relay/store.ts","../src/relay/server.ts","../src/relay/client.ts","../src/discovery/peer-discovery.ts","../src/discovery/bootstrap.ts","../src/utils.ts","../src/reputation/types.ts","../src/reputation/store.ts","../src/reputation/verification.ts","../src/reputation/commit-reveal.ts","../src/reputation/scoring.ts"],"sourcesContent":["import { sign, verify, generateKeyPairSync } from 'node:crypto';\n\n/**\n * Represents an ed25519 key pair for agent identity\n */\nexport interface KeyPair {\n publicKey: string; // hex-encoded\n privateKey: string; // hex-encoded\n}\n\n/**\n * Generates a new ed25519 key pair\n * @returns KeyPair with hex-encoded public and private keys\n */\nexport function generateKeyPair(): KeyPair {\n const { publicKey, privateKey } = generateKeyPairSync('ed25519');\n \n return {\n publicKey: publicKey.export({ type: 'spki', format: 'der' }).toString('hex'),\n privateKey: privateKey.export({ type: 'pkcs8', format: 'der' }).toString('hex'),\n };\n}\n\n/**\n * Signs a message with the private key\n * @param message - The message to sign (string or Buffer)\n * @param privateKeyHex - The private key in hex format\n * @returns Signature as hex string\n */\nexport function signMessage(message: string | Buffer, privateKeyHex: string): string {\n const messageBuffer = typeof message === 'string' ? Buffer.from(message) : message;\n const privateKey = Buffer.from(privateKeyHex, 'hex');\n \n const signature = sign(null, messageBuffer, {\n key: privateKey,\n format: 'der',\n type: 'pkcs8',\n });\n \n return signature.toString('hex');\n}\n\n/**\n * Verifies a signature with the public key\n * @param message - The original message (string or Buffer)\n * @param signatureHex - The signature in hex format\n * @param publicKeyHex - The public key in hex format\n * @returns true if signature is valid, false otherwise\n */\nexport function verifySignature(\n message: string | Buffer,\n signatureHex: string,\n publicKeyHex: string\n): boolean {\n const messageBuffer = typeof message === 'string' ? Buffer.from(message) : message;\n const signature = Buffer.from(signatureHex, 'hex');\n const publicKey = Buffer.from(publicKeyHex, 'hex');\n \n try {\n return verify(null, messageBuffer, {\n key: publicKey,\n format: 'der',\n type: 'spki',\n }, signature);\n } catch {\n return false;\n }\n}\n\n/**\n * Exports a key pair to a JSON-serializable format\n * @param keyPair - The key pair to export\n * @returns KeyPair object with hex-encoded keys\n */\nexport function exportKeyPair(keyPair: KeyPair): KeyPair {\n return {\n publicKey: keyPair.publicKey,\n privateKey: keyPair.privateKey,\n };\n}\n\n/**\n * Imports a key pair from hex strings\n * @param publicKeyHex - The public key in hex format\n * @param privateKeyHex - The private key in hex format\n * @returns KeyPair object\n * @throws Error if keys are not valid hex strings\n */\nexport function importKeyPair(publicKeyHex: string, privateKeyHex: string): KeyPair {\n // Validate that keys are valid hex strings\n const hexPattern = /^[0-9a-f]+$/i;\n if (!hexPattern.test(publicKeyHex)) {\n throw new Error('Invalid public key: must be a hex string');\n }\n if (!hexPattern.test(privateKeyHex)) {\n throw new Error('Invalid private key: must be a hex string');\n }\n \n return {\n publicKey: publicKeyHex,\n privateKey: privateKeyHex,\n };\n}\n","import { readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { generateKeyPair } from '../identity/keypair';\n\nexport interface PeerConfigFile {\n identity: {\n publicKey: string;\n privateKey: string;\n name?: string;\n };\n relay?: string | {\n url: string;\n name?: string;\n };\n peers: Record<string, {\n url?: string;\n token?: string;\n publicKey: string;\n name?: string;\n }>;\n}\n\n/**\n * Load peer configuration from a JSON file.\n * @param path - Path to the config file\n * @returns The parsed configuration\n * @throws Error if file doesn't exist or contains invalid JSON\n */\nexport function loadPeerConfig(path: string): PeerConfigFile {\n const content = readFileSync(path, 'utf-8');\n return JSON.parse(content) as PeerConfigFile;\n}\n\n/**\n * Save peer configuration to a JSON file.\n * @param path - Path to the config file\n * @param config - The configuration to save\n */\nexport function savePeerConfig(path: string, config: PeerConfigFile): void {\n const content = JSON.stringify(config, null, 2);\n writeFileSync(path, content, 'utf-8');\n}\n\n/**\n * Initialize peer configuration, generating a new keypair if the file doesn't exist.\n * If the file exists, loads and returns it.\n * @param path - Path to the config file\n * @returns The configuration (loaded or newly created)\n */\nexport function initPeerConfig(path: string): PeerConfigFile {\n if (existsSync(path)) {\n return loadPeerConfig(path);\n }\n\n // Generate new keypair and create initial config\n const identity = generateKeyPair();\n const config: PeerConfigFile = {\n identity,\n peers: {},\n };\n\n savePeerConfig(path, config);\n return config;\n}\n","import { createHash } from 'node:crypto';\nimport { signMessage, verifySignature } from '../identity/keypair';\n\n/**\n * Message types on the Agora network.\n * Every piece of data flowing between agents is wrapped in an envelope.\n */\nexport type MessageType =\n | 'announce' // Agent publishes capabilities/state\n | 'discover' // Agent requests peer discovery\n | 'request' // Agent requests a service\n | 'response' // Agent responds to a request\n | 'publish' // Agent publishes knowledge/state\n | 'subscribe' // Agent subscribes to a topic/domain\n | 'verify' // Agent verifies another agent's claim\n | 'ack' // Acknowledgement\n | 'error' // Error response\n | 'paper_discovery' // Agent publishes a discovered academic paper\n | 'peer_list_request' // Request peer list from relay\n | 'peer_list_response' // Relay responds with connected peers\n | 'peer_referral' // Agent recommends another agent\n | 'capability_announce' // Agent publishes capabilities to network\n | 'capability_query' // Agent queries for capabilities\n | 'capability_response' // Response with matching peers\n | 'commit' // Agent commits to a prediction (commit-reveal pattern)\n | 'reveal' // Agent reveals prediction and outcome\n | 'verification' // Agent verifies another agent's output\n | 'revocation' // Agent revokes a prior verification\n | 'reputation_query' // Agent queries for reputation data\n | 'reputation_response'; // Response to reputation query\n\n/**\n * The signed envelope that wraps every message on the network.\n * Content-addressed: the ID is the hash of the canonical payload.\n * Signed: every envelope carries a signature from the sender's private key.\n */\nexport interface Envelope<T = unknown> {\n /** Content-addressed ID: SHA-256 hash of canonical payload */\n id: string;\n /** Message type */\n type: MessageType;\n /** Sender's public key (hex-encoded ed25519) */\n sender: string;\n /** Unix timestamp (ms) when the message was created */\n timestamp: number;\n /** Optional: ID of the message this is responding to */\n inReplyTo?: string;\n /** The actual payload */\n payload: T;\n /** ed25519 signature over the canonical form (hex-encoded) */\n signature: string;\n}\n\n/**\n * Deterministic JSON serialization with recursively sorted 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 * Canonical form of an envelope for signing/hashing.\n * Deterministic JSON serialization: recursively sorted keys, no whitespace.\n */\nexport function canonicalize(type: MessageType, sender: string, timestamp: number, payload: unknown, inReplyTo?: string): string {\n const obj: Record<string, unknown> = { payload, sender, timestamp, type };\n if (inReplyTo !== undefined) {\n obj.inReplyTo = inReplyTo;\n }\n return stableStringify(obj);\n}\n\n/**\n * Compute the content-addressed ID for a message.\n */\nexport function computeId(canonical: string): string {\n return createHash('sha256').update(canonical).digest('hex');\n}\n\n/**\n * Create a signed envelope.\n * @param type - Message type\n * @param sender - Sender's public key (hex)\n * @param privateKey - Sender's private key (hex) for signing\n * @param payload - The message payload\n * @param timestamp - Timestamp for the envelope (ms), defaults to Date.now()\n * @param inReplyTo - Optional ID of the message being replied to\n * @returns A signed Envelope\n */\nexport function createEnvelope<T>(\n type: MessageType,\n sender: string,\n privateKey: string,\n payload: T,\n timestamp: number = Date.now(),\n inReplyTo?: string,\n): Envelope<T> {\n const canonical = canonicalize(type, sender, timestamp, payload, inReplyTo);\n const id = computeId(canonical);\n const signature = signMessage(canonical, privateKey);\n\n return {\n id,\n type,\n sender,\n timestamp,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n payload,\n signature,\n };\n}\n\n/**\n * Verify an envelope's integrity and authenticity.\n * Checks:\n * 1. Canonical form matches the ID (content-addressing)\n * 2. Signature is valid for the sender's public key\n * \n * @returns Object with `valid` boolean and optional `reason` for failure\n */\nexport function verifyEnvelope(envelope: Envelope): { valid: boolean; reason?: string } {\n const { id, type, sender, timestamp, payload, signature, inReplyTo } = envelope;\n\n // Reconstruct canonical form\n const canonical = canonicalize(type, sender, timestamp, payload, inReplyTo);\n\n // Check content-addressed ID\n const expectedId = computeId(canonical);\n if (id !== expectedId) {\n return { valid: false, reason: 'id_mismatch' };\n }\n\n // Check signature\n const sigValid = verifySignature(canonical, signature, sender);\n if (!sigValid) {\n return { valid: false, reason: 'signature_invalid' };\n }\n\n return { valid: true };\n}\n","import { createEnvelope, verifyEnvelope, type Envelope, type MessageType } from '../message/envelope';\n\nexport interface PeerConfig {\n /** Peer's webhook URL, e.g. http://localhost:18790/hooks (undefined for relay-only peers) */\n url?: string;\n /** Peer's webhook auth token (undefined for relay-only peers) */\n token?: string;\n /** Peer's public key (hex) for verifying responses */\n publicKey: string;\n}\n\nexport interface TransportConfig {\n /** This agent's keypair */\n identity: { publicKey: string; privateKey: string };\n /** Known peers */\n peers: Map<string, PeerConfig>;\n}\n\n/**\n * Send a signed envelope to a peer via HTTP webhook.\n * Creates the envelope, signs it, and POSTs to the peer's /hooks/agent endpoint.\n * Returns the HTTP status code.\n */\nexport async function sendToPeer(\n config: TransportConfig,\n peerPublicKey: string,\n type: MessageType,\n payload: unknown,\n inReplyTo?: string\n): Promise<{ ok: boolean; status: number; error?: string }> {\n // Look up peer config\n const peer = config.peers.get(peerPublicKey);\n if (!peer) {\n return { ok: false, status: 0, error: 'Unknown peer' };\n }\n\n // Relay-only peer — no webhook URL configured\n if (!peer.url) {\n return { ok: false, status: 0, error: 'No webhook URL configured' };\n }\n\n // Create and sign the envelope\n const envelope = createEnvelope(\n type,\n config.identity.publicKey,\n config.identity.privateKey,\n payload,\n Date.now(),\n inReplyTo\n );\n\n // Encode envelope as base64url\n const envelopeJson = JSON.stringify(envelope);\n const envelopeBase64 = Buffer.from(envelopeJson).toString('base64url');\n\n // Construct webhook payload\n const webhookPayload = {\n message: `[AGORA_ENVELOPE]${envelopeBase64}`,\n name: 'Agora',\n sessionKey: `agora:${envelope.sender.substring(0, 16)}`,\n deliver: false,\n };\n\n // Send HTTP POST\n try {\n const response = await fetch(`${peer.url}/agent`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${peer.token}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(webhookPayload),\n });\n\n return {\n ok: response.ok,\n status: response.status,\n error: response.ok ? undefined : await response.text(),\n };\n } catch (err) {\n return {\n ok: false,\n status: 0,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\n/**\n * Decode and verify an inbound Agora envelope from a webhook message.\n * Expects the message to start with [AGORA_ENVELOPE] followed by base64.\n * Returns the verified envelope or an error.\n */\nexport function decodeInboundEnvelope(\n message: string,\n knownPeers: Map<string, PeerConfig>\n): { ok: true; envelope: Envelope } | { ok: false; reason: string } {\n // Check for AGORA_ENVELOPE prefix\n const prefix = '[AGORA_ENVELOPE]';\n if (!message.startsWith(prefix)) {\n return { ok: false, reason: 'not_agora_message' };\n }\n\n // Extract base64 payload\n const base64Payload = message.substring(prefix.length);\n \n // Check for empty payload\n if (!base64Payload) {\n return { ok: false, reason: 'invalid_base64' };\n }\n \n // Decode base64\n let envelopeJson: string;\n try {\n const decoded = Buffer.from(base64Payload, 'base64url');\n // Check if decoded buffer is empty or contains invalid data\n if (decoded.length === 0) {\n return { ok: false, reason: 'invalid_base64' };\n }\n envelopeJson = decoded.toString('utf-8');\n } catch {\n return { ok: false, reason: 'invalid_base64' };\n }\n\n // Parse JSON\n let envelope: Envelope;\n try {\n envelope = JSON.parse(envelopeJson);\n } catch {\n return { ok: false, reason: 'invalid_json' };\n }\n\n // Verify envelope integrity\n const verification = verifyEnvelope(envelope);\n if (!verification.valid) {\n return { ok: false, reason: verification.reason || 'verification_failed' };\n }\n\n // Check if sender is a known peer\n const senderKnown = knownPeers.has(envelope.sender);\n if (!senderKnown) {\n return { ok: false, reason: 'unknown_sender' };\n }\n\n return { ok: true, envelope };\n}\n","import WebSocket from 'ws';\nimport { createEnvelope, type Envelope, type MessageType } from '../message/envelope';\n\n/** Minimal interface for a connected relay client (avoids importing full RelayClient) */\nexport interface RelayClientSender {\n connected(): boolean;\n send(to: string, envelope: Envelope): Promise<{ ok: boolean; error?: string }>;\n}\n\nexport interface RelayTransportConfig {\n /** This agent's keypair */\n identity: { publicKey: string; privateKey: string };\n /** Relay server WebSocket URL (e.g., wss://agora-relay.lbsa71.net) */\n relayUrl: string;\n /** Optional persistent relay client (if provided, will use it instead of connect-per-message) */\n relayClient?: RelayClientSender;\n}\n\n/**\n * Send a signed envelope to a peer via relay server.\n * If a persistent relayClient is provided in the config, uses that.\n * Otherwise, connects to relay, registers, sends message, and disconnects.\n */\nexport async function sendViaRelay(\n config: RelayTransportConfig,\n peerPublicKey: string,\n type: MessageType,\n payload: unknown,\n inReplyTo?: string\n): Promise<{ ok: boolean; error?: string }> {\n // If a persistent relay client is available, use it\n if (config.relayClient && config.relayClient.connected()) {\n const envelope = createEnvelope(\n type,\n config.identity.publicKey,\n config.identity.privateKey,\n payload,\n Date.now(),\n inReplyTo\n );\n return config.relayClient.send(peerPublicKey, envelope);\n }\n\n // Otherwise, fall back to connect-per-message\n return new Promise((resolve) => {\n const ws = new WebSocket(config.relayUrl);\n let registered = false;\n let messageSent = false;\n let resolved = false;\n\n // Helper to resolve once\n const resolveOnce = (result: { ok: boolean; error?: string }): void => {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n resolve(result);\n }\n };\n\n // Set timeout for the entire operation\n const timeout = setTimeout(() => {\n if (!messageSent) {\n ws.close();\n resolveOnce({ ok: false, error: 'Relay connection timeout' });\n }\n }, 10000); // 10 second timeout\n\n ws.on('open', () => {\n // Send register message\n const registerMsg = {\n type: 'register',\n publicKey: config.identity.publicKey,\n };\n ws.send(JSON.stringify(registerMsg));\n });\n\n ws.on('message', (data: WebSocket.Data) => {\n try {\n const msg = JSON.parse(data.toString());\n\n if (msg.type === 'registered' && !registered) {\n registered = true;\n\n // Create and sign the envelope\n const envelope: Envelope = createEnvelope(\n type,\n config.identity.publicKey,\n config.identity.privateKey,\n payload,\n Date.now(),\n inReplyTo\n );\n\n // Send message via relay\n const relayMsg = {\n type: 'message',\n to: peerPublicKey,\n envelope,\n };\n ws.send(JSON.stringify(relayMsg));\n messageSent = true;\n\n // Close connection after sending\n setTimeout(() => {\n ws.close();\n resolveOnce({ ok: true });\n }, 100); // Small delay to ensure message is sent\n } else if (msg.type === 'error') {\n ws.close();\n resolveOnce({ ok: false, error: msg.message || 'Relay server error' });\n }\n } catch (err) {\n ws.close();\n resolveOnce({ ok: false, error: err instanceof Error ? err.message : String(err) });\n }\n });\n\n ws.on('error', (err) => {\n ws.close();\n resolveOnce({ ok: false, error: err.message });\n });\n\n ws.on('close', () => {\n if (!messageSent) {\n resolveOnce({ ok: false, error: 'Connection closed before message sent' });\n }\n });\n });\n}\n","/**\n * store.ts — File-based message store for offline peers.\n * When the relay has storage enabled for certain public keys, messages\n * for offline recipients are persisted and delivered when they connect.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nexport interface StoredMessage {\n from: string;\n name?: string;\n envelope: object;\n}\n\nexport class MessageStore {\n private storageDir: string;\n\n constructor(storageDir: string) {\n this.storageDir = storageDir;\n fs.mkdirSync(storageDir, { recursive: true });\n }\n\n private recipientDir(publicKey: string): string {\n const safe = publicKey.replace(/[^a-zA-Z0-9_-]/g, '_');\n return path.join(this.storageDir, safe);\n }\n\n save(recipientKey: string, message: StoredMessage): void {\n const dir = this.recipientDir(recipientKey);\n fs.mkdirSync(dir, { recursive: true });\n const filename = `${Date.now()}-${crypto.randomUUID()}.json`;\n fs.writeFileSync(path.join(dir, filename), JSON.stringify(message));\n }\n\n load(recipientKey: string): StoredMessage[] {\n const dir = this.recipientDir(recipientKey);\n if (!fs.existsSync(dir)) return [];\n const files = fs.readdirSync(dir).sort();\n const messages: StoredMessage[] = [];\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n try {\n const data = fs.readFileSync(path.join(dir, file), 'utf8');\n messages.push(JSON.parse(data) as StoredMessage);\n } catch {\n // Skip files that cannot be read or parsed\n }\n }\n return messages;\n }\n\n clear(recipientKey: string): void {\n const dir = this.recipientDir(recipientKey);\n if (!fs.existsSync(dir)) return;\n const files = fs.readdirSync(dir);\n for (const file of files) {\n if (file.endsWith('.json')) {\n fs.unlinkSync(path.join(dir, file));\n }\n }\n }\n}\n","import { EventEmitter } from 'node:events';\nimport { WebSocketServer, WebSocket } from 'ws';\nimport { verifyEnvelope, createEnvelope, type Envelope } from '../message/envelope';\nimport type { PeerListRequestPayload, PeerListResponsePayload } from '../message/types/peer-discovery';\nimport { MessageStore } from './store';\n\n/**\n * Represents a connected agent in the relay\n */\ninterface ConnectedAgent {\n /** Agent's public key */\n publicKey: string;\n /** Optional agent name */\n name?: string;\n /** WebSocket connection */\n socket: WebSocket;\n /** Last seen timestamp (ms) */\n lastSeen: number;\n /** Optional metadata */\n metadata?: {\n version?: string;\n capabilities?: string[];\n };\n}\n\n/**\n * Events emitted by RelayServer\n */\nexport interface RelayServerEvents {\n 'agent-registered': (publicKey: string) => void;\n 'agent-disconnected': (publicKey: string) => void;\n 'message-relayed': (from: string, to: string, envelope: Envelope) => void;\n 'error': (error: Error) => void;\n}\n\n/**\n * WebSocket relay server for routing messages between agents.\n * \n * Agents connect to the relay and register with their public key.\n * Messages are routed to recipients based on the 'to' field.\n * All envelopes are verified before being forwarded.\n */\nexport interface RelayServerOptions {\n /** Optional relay identity for peer_list_request handling */\n identity?: { publicKey: string; privateKey: string };\n /** Public keys that should have messages stored when offline */\n storagePeers?: string[];\n /** Directory for persisting messages for storage peers */\n storageDir?: string;\n}\n\nexport class RelayServer extends EventEmitter {\n private wss: WebSocketServer | null = null;\n private agents = new Map<string, ConnectedAgent>();\n private identity?: { publicKey: string; privateKey: string };\n private storagePeers: string[] = [];\n private store: MessageStore | null = null;\n\n constructor(options?: { publicKey: string; privateKey: string } | RelayServerOptions) {\n super();\n if (options) {\n if ('identity' in options && options.identity) {\n this.identity = options.identity;\n } else if ('publicKey' in options && 'privateKey' in options) {\n this.identity = { publicKey: options.publicKey, privateKey: options.privateKey };\n }\n const opts = options as RelayServerOptions;\n if (opts.storagePeers?.length && opts.storageDir) {\n this.storagePeers = opts.storagePeers;\n this.store = new MessageStore(opts.storageDir);\n }\n }\n }\n\n /**\n * Start the relay server\n * @param port - Port to listen on\n * @param host - Optional host (default: all interfaces)\n */\n start(port: number, host?: string): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n this.wss = new WebSocketServer({ port, host: host ?? '0.0.0.0' });\n let resolved = false;\n\n this.wss.on('error', (error) => {\n this.emit('error', error);\n if (!resolved) {\n resolved = true;\n reject(error);\n }\n });\n\n this.wss.on('listening', () => {\n if (!resolved) {\n resolved = true;\n resolve();\n }\n });\n\n this.wss.on('connection', (socket: WebSocket) => {\n this.handleConnection(socket);\n });\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Stop the relay server\n */\n async stop(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!this.wss) {\n resolve();\n return;\n }\n\n // Close all agent connections\n for (const agent of this.agents.values()) {\n agent.socket.close();\n }\n this.agents.clear();\n\n this.wss.close((err) => {\n if (err) {\n reject(err);\n } else {\n this.wss = null;\n resolve();\n }\n });\n });\n }\n\n /**\n * Get all connected agents\n */\n getAgents(): Map<string, ConnectedAgent> {\n return new Map(this.agents);\n }\n\n /**\n * Handle incoming connection\n */\n private handleConnection(socket: WebSocket): void {\n let agentPublicKey: string | null = null;\n\n socket.on('message', (data: Buffer) => {\n try {\n const msg = JSON.parse(data.toString());\n\n // Handle registration\n if (msg.type === 'register' && !agentPublicKey) {\n if (!msg.publicKey || typeof msg.publicKey !== 'string') {\n this.sendError(socket, 'Invalid registration: missing or invalid publicKey');\n socket.close();\n return;\n }\n\n const publicKey = msg.publicKey;\n const name = msg.name;\n agentPublicKey = publicKey;\n\n // If this pubkey was already connected, close the old connection\n const existing = this.agents.get(publicKey);\n if (existing) {\n existing.socket.close();\n }\n\n const agent: ConnectedAgent = {\n publicKey,\n name,\n socket,\n lastSeen: Date.now(),\n };\n\n this.agents.set(publicKey, agent);\n this.emit('agent-registered', publicKey);\n\n // Build peers list: connected agents + storage peers (always considered \"connected\" for store-and-forward)\n let peers = Array.from(this.agents.values())\n .filter(a => a.publicKey !== publicKey)\n .map(a => ({ publicKey: a.publicKey, name: a.name }));\n for (const storagePeer of this.storagePeers) {\n if (storagePeer !== publicKey && !this.agents.has(storagePeer)) {\n peers.push({ publicKey: storagePeer, name: undefined });\n }\n }\n\n socket.send(JSON.stringify({\n type: 'registered',\n publicKey,\n peers,\n }));\n\n // Notify other agents that this agent is now online\n this.broadcastPeerEvent('peer_online', publicKey, name);\n\n // Deliver any stored messages for this peer\n if (this.store && this.storagePeers.includes(publicKey)) {\n const queued = this.store.load(publicKey);\n for (const stored of queued) {\n socket.send(JSON.stringify({\n type: 'message',\n from: stored.from,\n name: stored.name,\n envelope: stored.envelope,\n }));\n }\n this.store.clear(publicKey);\n }\n return;\n }\n\n // Require registration before processing messages\n if (!agentPublicKey) {\n this.sendError(socket, 'Not registered: send registration message first');\n socket.close();\n return;\n }\n\n // Handle message relay\n if (msg.type === 'message') {\n if (!msg.to || typeof msg.to !== 'string') {\n this.sendError(socket, 'Invalid message: missing or invalid \"to\" field');\n return;\n }\n\n if (!msg.envelope || typeof msg.envelope !== 'object') {\n this.sendError(socket, 'Invalid message: missing or invalid \"envelope\" field');\n return;\n }\n\n const envelope = msg.envelope as Envelope;\n\n // Verify envelope signature\n const verification = verifyEnvelope(envelope);\n if (!verification.valid) {\n this.sendError(socket, `Invalid envelope: ${verification.reason || 'verification failed'}`);\n return;\n }\n\n // Verify sender matches registered agent\n if (envelope.sender !== agentPublicKey) {\n this.sendError(socket, 'Envelope sender does not match registered public key');\n return;\n }\n\n // Update lastSeen timestamp\n const senderAgent = this.agents.get(agentPublicKey);\n if (senderAgent) {\n senderAgent.lastSeen = Date.now();\n }\n\n // Handle peer_list_request directed at relay\n if (envelope.type === 'peer_list_request' && this.identity && msg.to === this.identity.publicKey) {\n this.handlePeerListRequest(envelope as Envelope<PeerListRequestPayload>, socket, agentPublicKey);\n return;\n }\n\n // Find recipient\n const recipient = this.agents.get(msg.to);\n if (!recipient || recipient.socket.readyState !== WebSocket.OPEN) {\n // If recipient is a storage peer, queue the message\n if (this.store && this.storagePeers.includes(msg.to)) {\n const senderAgent = this.agents.get(agentPublicKey);\n this.store.save(msg.to, {\n from: agentPublicKey,\n name: senderAgent?.name,\n envelope,\n });\n this.emit('message-relayed', agentPublicKey, msg.to, envelope);\n } else {\n this.sendError(socket, 'Recipient not connected');\n }\n return;\n }\n\n // Forward envelope to recipient wrapped in relay message format\n try {\n const senderAgent = this.agents.get(agentPublicKey);\n const relayMessage = {\n type: 'message',\n from: agentPublicKey,\n name: senderAgent?.name,\n envelope,\n };\n recipient.socket.send(JSON.stringify(relayMessage));\n this.emit('message-relayed', agentPublicKey, msg.to, envelope);\n } catch (err) {\n this.sendError(socket, 'Failed to relay message');\n this.emit('error', err as Error);\n }\n return;\n }\n\n // Handle broadcast: same validation as message, then forward to all other agents\n if (msg.type === 'broadcast') {\n if (!msg.envelope || typeof msg.envelope !== 'object') {\n this.sendError(socket, 'Invalid broadcast: missing or invalid \"envelope\" field');\n return;\n }\n\n const envelope = msg.envelope as Envelope;\n\n const verification = verifyEnvelope(envelope);\n if (!verification.valid) {\n this.sendError(socket, `Invalid envelope: ${verification.reason || 'verification failed'}`);\n return;\n }\n\n if (envelope.sender !== agentPublicKey) {\n this.sendError(socket, 'Envelope sender does not match registered public key');\n return;\n }\n\n // Update lastSeen timestamp\n const senderAgentBroadcast = this.agents.get(agentPublicKey);\n if (senderAgentBroadcast) {\n senderAgentBroadcast.lastSeen = Date.now();\n }\n\n const senderAgent = this.agents.get(agentPublicKey);\n const relayMessage = {\n type: 'message' as const,\n from: agentPublicKey,\n name: senderAgent?.name,\n envelope,\n };\n const messageStr = JSON.stringify(relayMessage);\n\n for (const agent of this.agents.values()) {\n if (agent.publicKey !== agentPublicKey && agent.socket.readyState === WebSocket.OPEN) {\n try {\n agent.socket.send(messageStr);\n } catch (err) {\n this.emit('error', err as Error);\n }\n }\n }\n return;\n }\n\n // Handle ping\n if (msg.type === 'ping') {\n socket.send(JSON.stringify({ type: 'pong' }));\n return;\n }\n\n // Unknown message type\n this.sendError(socket, `Unknown message type: ${msg.type}`);\n } catch (err) {\n // Invalid JSON or other parsing errors\n this.emit('error', new Error(`Message parsing failed: ${err instanceof Error ? err.message : String(err)}`));\n this.sendError(socket, 'Invalid message format');\n }\n });\n\n socket.on('close', () => {\n if (agentPublicKey) {\n const agent = this.agents.get(agentPublicKey);\n const agentName = agent?.name;\n this.agents.delete(agentPublicKey);\n this.emit('agent-disconnected', agentPublicKey);\n // Storage-enabled peers are always considered connected; skip peer_offline for them\n if (!this.storagePeers.includes(agentPublicKey)) {\n this.broadcastPeerEvent('peer_offline', agentPublicKey, agentName);\n }\n }\n });\n\n socket.on('error', (error) => {\n this.emit('error', error);\n });\n }\n\n /**\n * Send an error message to a client\n */\n private sendError(socket: WebSocket, message: string): void {\n try {\n if (socket.readyState === WebSocket.OPEN) {\n socket.send(JSON.stringify({ type: 'error', message }));\n }\n } catch (err) {\n // Log errors when sending error messages, but don't propagate to avoid cascading failures\n this.emit('error', new Error(`Failed to send error message: ${err instanceof Error ? err.message : String(err)}`));\n }\n }\n\n /**\n * Broadcast a peer event to all connected agents\n */\n private broadcastPeerEvent(eventType: 'peer_online' | 'peer_offline', publicKey: string, name?: string): void {\n const message = {\n type: eventType,\n publicKey,\n name,\n };\n const messageStr = JSON.stringify(message);\n\n for (const agent of this.agents.values()) {\n // Don't send the event to the agent it's about\n if (agent.publicKey !== publicKey && agent.socket.readyState === WebSocket.OPEN) {\n try {\n agent.socket.send(messageStr);\n } catch (err) {\n this.emit('error', new Error(`Failed to send ${eventType} event: ${err instanceof Error ? err.message : String(err)}`));\n }\n }\n }\n }\n\n /**\n * Handle peer list request from an agent\n */\n private handlePeerListRequest(envelope: Envelope<PeerListRequestPayload>, socket: WebSocket, requesterPublicKey: string): void {\n if (!this.identity) {\n this.sendError(socket, 'Relay does not support peer discovery (no identity configured)');\n return;\n }\n\n const { filters } = envelope.payload;\n const now = Date.now();\n\n let peers = Array.from(this.agents.values());\n\n // Filter out requester first\n peers = peers.filter(p => p.publicKey !== requesterPublicKey);\n\n // Apply filters\n if (filters?.activeWithin) {\n peers = peers.filter(p => (now - p.lastSeen) < filters.activeWithin!);\n }\n\n if (filters?.limit && filters.limit > 0) {\n peers = peers.slice(0, filters.limit);\n }\n\n // Build response payload\n const response: PeerListResponsePayload = {\n peers: peers.map(p => ({\n publicKey: p.publicKey,\n metadata: p.name || p.metadata ? {\n name: p.name,\n version: p.metadata?.version,\n capabilities: p.metadata?.capabilities,\n } : undefined,\n lastSeen: p.lastSeen,\n })),\n totalPeers: this.agents.size - 1, // Exclude requester from count\n relayPublicKey: this.identity.publicKey,\n };\n\n // Create signed envelope\n const responseEnvelope = createEnvelope(\n 'peer_list_response',\n this.identity.publicKey,\n this.identity.privateKey,\n response,\n Date.now(),\n envelope.id // Reply to the request\n );\n\n // Send response\n const relayMessage = {\n type: 'message',\n from: this.identity.publicKey,\n name: 'relay',\n envelope: responseEnvelope,\n };\n\n try {\n socket.send(JSON.stringify(relayMessage));\n } catch (err) {\n this.emit('error', new Error(`Failed to send peer list response: ${err instanceof Error ? err.message : String(err)}`));\n }\n }\n}\n","import { EventEmitter } from 'node:events';\nimport WebSocket from 'ws';\nimport { verifyEnvelope, type Envelope } from '../message/envelope';\nimport type { RelayClientMessage, RelayServerMessage, RelayPeer } from './types';\n\n/**\n * Configuration for RelayClient\n */\nexport interface RelayClientConfig {\n /** WebSocket URL of the relay server */\n relayUrl: string;\n /** Agent's public key */\n publicKey: string;\n /** Agent's private key (for signing) */\n privateKey: string;\n /** Optional name for this agent */\n name?: string;\n /** Keepalive ping interval in milliseconds (default: 30000) */\n pingInterval?: number;\n /** Maximum reconnection delay in milliseconds (default: 60000) */\n maxReconnectDelay?: number;\n}\n\n/**\n * Events emitted by RelayClient\n */\nexport interface RelayClientEvents {\n /** Emitted when successfully connected and registered */\n 'connected': () => void;\n /** Emitted when disconnected from relay */\n 'disconnected': () => void;\n /** Emitted when a verified message is received */\n 'message': (envelope: Envelope, from: string, fromName?: string) => void;\n /** Emitted when a peer comes online */\n 'peer_online': (peer: RelayPeer) => void;\n /** Emitted when a peer goes offline */\n 'peer_offline': (peer: RelayPeer) => void;\n /** Emitted on errors */\n 'error': (error: Error) => void;\n}\n\n/**\n * Persistent WebSocket client for the Agora relay server.\n * Maintains a long-lived connection, handles reconnection, and routes messages.\n */\nexport class RelayClient extends EventEmitter {\n private ws: WebSocket | null = null;\n private config: RelayClientConfig;\n private reconnectAttempts = 0;\n private reconnectTimeout: NodeJS.Timeout | null = null;\n private pingInterval: NodeJS.Timeout | null = null;\n private isConnected = false;\n private isRegistered = false;\n private shouldReconnect = true;\n private onlinePeers = new Map<string, RelayPeer>();\n\n constructor(config: RelayClientConfig) {\n super();\n this.config = {\n pingInterval: 30000,\n maxReconnectDelay: 60000,\n ...config,\n };\n }\n\n /**\n * Connect to the relay server\n */\n async connect(): Promise<void> {\n if (this.ws && (this.ws.readyState === WebSocket.CONNECTING || this.ws.readyState === WebSocket.OPEN)) {\n return;\n }\n\n this.shouldReconnect = true;\n return this.doConnect();\n }\n\n /**\n * Disconnect from the relay server\n */\n disconnect(): void {\n this.shouldReconnect = false;\n this.cleanup();\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }\n\n /**\n * Check if currently connected and registered\n */\n connected(): boolean {\n return this.isConnected && this.isRegistered;\n }\n\n /**\n * Send a message to a specific peer\n */\n async send(to: string, envelope: Envelope): Promise<{ ok: boolean; error?: string }> {\n if (!this.connected()) {\n return { ok: false, error: 'Not connected to relay' };\n }\n\n const message: RelayClientMessage = {\n type: 'message',\n to,\n envelope,\n };\n\n try {\n this.ws!.send(JSON.stringify(message));\n return { ok: true };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n }\n\n /**\n * Broadcast a message to all connected peers\n */\n async broadcast(envelope: Envelope): Promise<{ ok: boolean; error?: string }> {\n if (!this.connected()) {\n return { ok: false, error: 'Not connected to relay' };\n }\n\n const message: RelayClientMessage = {\n type: 'broadcast',\n envelope,\n };\n\n try {\n this.ws!.send(JSON.stringify(message));\n return { ok: true };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n }\n\n /**\n * Get list of currently online peers\n */\n getOnlinePeers(): RelayPeer[] {\n return Array.from(this.onlinePeers.values());\n }\n\n /**\n * Check if a specific peer is online\n */\n isPeerOnline(publicKey: string): boolean {\n return this.onlinePeers.has(publicKey);\n }\n\n /**\n * Internal: Perform connection\n */\n private async doConnect(): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n this.ws = new WebSocket(this.config.relayUrl);\n let resolved = false;\n\n const resolveOnce = (callback: () => void): void => {\n if (!resolved) {\n resolved = true;\n callback();\n }\n };\n\n this.ws.on('open', () => {\n this.isConnected = true;\n this.reconnectAttempts = 0;\n this.startPingInterval();\n\n // Send registration message\n const registerMsg: RelayClientMessage = {\n type: 'register',\n publicKey: this.config.publicKey,\n name: this.config.name,\n };\n this.ws!.send(JSON.stringify(registerMsg));\n });\n\n this.ws.on('message', (data: WebSocket.Data) => {\n try {\n const msg = JSON.parse(data.toString()) as RelayServerMessage;\n this.handleMessage(msg);\n\n // Resolve promise on successful registration\n if (msg.type === 'registered' && !resolved) {\n resolveOnce(() => resolve());\n }\n } catch (err) {\n this.emit('error', new Error(`Failed to parse message: ${err instanceof Error ? err.message : String(err)}`));\n }\n });\n\n this.ws.on('close', () => {\n this.isConnected = false;\n this.isRegistered = false;\n this.cleanup();\n this.emit('disconnected');\n\n if (this.shouldReconnect) {\n this.scheduleReconnect();\n }\n\n if (!resolved) {\n resolveOnce(() => reject(new Error('Connection closed before registration')));\n }\n });\n\n this.ws.on('error', (err) => {\n this.emit('error', err);\n if (!resolved) {\n resolveOnce(() => reject(err));\n }\n });\n } catch (err) {\n reject(err);\n }\n });\n }\n\n /**\n * Handle incoming message from relay\n */\n private handleMessage(msg: RelayServerMessage): void {\n switch (msg.type) {\n case 'registered':\n this.isRegistered = true;\n if (msg.peers) {\n // Populate initial peer list\n for (const peer of msg.peers) {\n this.onlinePeers.set(peer.publicKey, peer);\n }\n }\n this.emit('connected');\n break;\n\n case 'message':\n if (msg.envelope && msg.from) {\n // Verify envelope signature\n const verification = verifyEnvelope(msg.envelope);\n if (!verification.valid) {\n this.emit('error', new Error(`Invalid envelope signature: ${verification.reason}`));\n return;\n }\n\n // Verify sender matches 'from' field\n if (msg.envelope.sender !== msg.from) {\n this.emit('error', new Error('Envelope sender does not match relay from field'));\n return;\n }\n\n // Emit verified message\n this.emit('message', msg.envelope, msg.from, msg.name);\n }\n break;\n\n case 'peer_online':\n if (msg.publicKey) {\n const peer: RelayPeer = {\n publicKey: msg.publicKey,\n name: msg.name,\n };\n this.onlinePeers.set(msg.publicKey, peer);\n this.emit('peer_online', peer);\n }\n break;\n\n case 'peer_offline':\n if (msg.publicKey) {\n const peer = this.onlinePeers.get(msg.publicKey);\n if (peer) {\n this.onlinePeers.delete(msg.publicKey);\n this.emit('peer_offline', peer);\n }\n }\n break;\n\n case 'error':\n this.emit('error', new Error(`Relay error: ${msg.message || 'Unknown error'}`));\n break;\n\n case 'pong':\n // Keepalive response, no action needed\n break;\n\n default:\n // Unknown message type, ignore\n break;\n }\n }\n\n /**\n * Schedule reconnection with exponential backoff\n */\n private scheduleReconnect(): void {\n if (this.reconnectTimeout) {\n return;\n }\n\n // Exponential backoff: 1s, 2s, 4s, 8s, 16s, 32s, 60s (max)\n const delay = Math.min(\n 1000 * Math.pow(2, this.reconnectAttempts),\n this.config.maxReconnectDelay!\n );\n\n this.reconnectAttempts++;\n\n this.reconnectTimeout = setTimeout(() => {\n this.reconnectTimeout = null;\n if (this.shouldReconnect) {\n this.doConnect().catch((err) => {\n this.emit('error', err);\n });\n }\n }, delay);\n }\n\n /**\n * Start periodic ping messages\n */\n private startPingInterval(): void {\n this.stopPingInterval();\n this.pingInterval = setInterval(() => {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n const ping: RelayClientMessage = { type: 'ping' };\n this.ws.send(JSON.stringify(ping));\n }\n }, this.config.pingInterval!);\n }\n\n /**\n * Stop ping interval\n */\n private stopPingInterval(): void {\n if (this.pingInterval) {\n clearInterval(this.pingInterval);\n this.pingInterval = null;\n }\n }\n\n /**\n * Cleanup resources\n */\n private cleanup(): void {\n this.stopPingInterval();\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n this.onlinePeers.clear();\n }\n}\n","import { EventEmitter } from 'node:events';\nimport { createEnvelope, verifyEnvelope, type Envelope } from '../message/envelope';\nimport type { RelayClient } from '../relay/client';\nimport type { PeerListRequestPayload, PeerListResponsePayload, PeerReferralPayload } from '../message/types/peer-discovery';\n\n/**\n * Configuration for PeerDiscoveryService\n */\nexport interface PeerDiscoveryConfig {\n /** Agent's public key */\n publicKey: string;\n /** Agent's private key for signing */\n privateKey: string;\n /** RelayClient instance for communication */\n relayClient: RelayClient;\n /** Public key of the relay server (for sending peer list requests) */\n relayPublicKey?: string;\n}\n\n/**\n * Events emitted by PeerDiscoveryService\n */\nexport interface PeerDiscoveryEvents {\n /** Emitted when peers are discovered */\n 'peers-discovered': (peers: PeerListResponsePayload['peers']) => void;\n /** Emitted when a peer referral is received */\n 'peer-referral': (referral: PeerReferralPayload, from: string) => void;\n /** Emitted on errors */\n 'error': (error: Error) => void;\n}\n\n/**\n * Service for discovering peers on the Agora network\n */\nexport class PeerDiscoveryService extends EventEmitter {\n private config: PeerDiscoveryConfig;\n\n constructor(config: PeerDiscoveryConfig) {\n super();\n this.config = config;\n\n // Listen for peer list responses and referrals\n this.config.relayClient.on('message', (envelope: Envelope, from: string) => {\n if (envelope.type === 'peer_list_response') {\n this.handlePeerList(envelope as Envelope<PeerListResponsePayload>);\n } else if (envelope.type === 'peer_referral') {\n this.handleReferral(envelope as Envelope<PeerReferralPayload>, from);\n }\n });\n }\n\n /**\n * Request peer list from relay\n */\n async discoverViaRelay(filters?: PeerListRequestPayload['filters']): Promise<PeerListResponsePayload | null> {\n if (!this.config.relayPublicKey) {\n throw new Error('Relay public key not configured');\n }\n\n if (!this.config.relayClient.connected()) {\n throw new Error('Not connected to relay');\n }\n\n const payload: PeerListRequestPayload = filters ? { filters } : {};\n\n const envelope = createEnvelope(\n 'peer_list_request',\n this.config.publicKey,\n this.config.privateKey,\n payload\n );\n\n // Send request to relay\n const result = await this.config.relayClient.send(this.config.relayPublicKey, envelope);\n if (!result.ok) {\n throw new Error(`Failed to send peer list request: ${result.error}`);\n }\n\n // Wait for response (with timeout)\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n cleanup();\n reject(new Error('Peer list request timed out'));\n }, 10000); // 10 second timeout\n\n const messageHandler = (responseEnvelope: Envelope, from: string): void => {\n if (responseEnvelope.type === 'peer_list_response' && \n responseEnvelope.inReplyTo === envelope.id &&\n from === this.config.relayPublicKey) {\n cleanup();\n resolve(responseEnvelope.payload as PeerListResponsePayload);\n }\n };\n\n const cleanup = (): void => {\n clearTimeout(timeout);\n this.config.relayClient.off('message', messageHandler);\n };\n\n this.config.relayClient.on('message', messageHandler);\n });\n }\n\n /**\n * Send peer referral to another agent\n */\n async referPeer(\n recipientPublicKey: string,\n referredPublicKey: string,\n metadata?: { name?: string; endpoint?: string; comment?: string; trustScore?: number }\n ): Promise<{ ok: boolean; error?: string }> {\n if (!this.config.relayClient.connected()) {\n return { ok: false, error: 'Not connected to relay' };\n }\n\n const payload: PeerReferralPayload = {\n publicKey: referredPublicKey,\n endpoint: metadata?.endpoint,\n metadata: metadata?.name ? { name: metadata.name } : undefined,\n comment: metadata?.comment,\n trustScore: metadata?.trustScore,\n };\n\n const envelope = createEnvelope(\n 'peer_referral',\n this.config.publicKey,\n this.config.privateKey,\n payload\n );\n\n return this.config.relayClient.send(recipientPublicKey, envelope);\n }\n\n /**\n * Handle incoming peer referral\n */\n private handleReferral(envelope: Envelope<PeerReferralPayload>, from: string): void {\n // Verify envelope\n const verification = verifyEnvelope(envelope);\n if (!verification.valid) {\n this.emit('error', new Error(`Invalid peer referral: ${verification.reason}`));\n return;\n }\n\n // Emit event for application to handle\n this.emit('peer-referral', envelope.payload, from);\n }\n\n /**\n * Handle incoming peer list from relay\n */\n private handlePeerList(envelope: Envelope<PeerListResponsePayload>): void {\n // Verify envelope\n const verification = verifyEnvelope(envelope);\n if (!verification.valid) {\n this.emit('error', new Error(`Invalid peer list response: ${verification.reason}`));\n return;\n }\n\n // Verify sender is the relay\n if (envelope.sender !== this.config.relayPublicKey) {\n this.emit('error', new Error('Peer list response not from configured relay'));\n return;\n }\n\n // Emit event\n this.emit('peers-discovered', envelope.payload.peers);\n }\n}\n","/**\n * Bootstrap configuration for peer discovery on the Agora network.\n * Provides default bootstrap relays for initial network entry.\n */\n\n/**\n * Default bootstrap relay servers\n * These are well-known relays that serve as initial entry points to the network\n */\nexport const DEFAULT_BOOTSTRAP_RELAYS = [\n {\n url: 'wss://agora-relay.lbsa71.net',\n name: 'Primary Bootstrap Relay',\n // Note: Public key would need to be set when the relay is actually deployed\n // For now, this is a placeholder that would be configured when the relay is running\n },\n];\n\n/**\n * Configuration for bootstrap connection\n */\nexport interface BootstrapConfig {\n /** Bootstrap relay URL */\n relayUrl: string;\n /** Optional relay public key (for verification) */\n relayPublicKey?: string;\n /** Connection timeout in ms (default: 10000) */\n timeout?: number;\n}\n\n/**\n * Get default bootstrap relay configuration\n */\nexport function getDefaultBootstrapRelay(): BootstrapConfig {\n return {\n relayUrl: DEFAULT_BOOTSTRAP_RELAYS[0].url,\n timeout: 10000,\n };\n}\n\n/**\n * Parse bootstrap relay URL and optional public key\n */\nexport function parseBootstrapRelay(url: string, publicKey?: string): BootstrapConfig {\n return {\n relayUrl: url,\n relayPublicKey: publicKey,\n timeout: 10000,\n };\n}\n","/**\n * Get a short display version of a public key using the last 8 characters.\n * Ed25519 public keys all share the same OID prefix, so the last 8 characters\n * are more distinguishable than the first 8.\n *\n * @param publicKey - The full public key hex string\n * @returns \"...\" followed by the last 8 characters of the key\n */\nexport function shortKey(publicKey: string): string {\n return \"...\" + publicKey.slice(-8);\n}\n\n/**\n * Resolves the name to broadcast when connecting to a relay.\n * Priority order:\n * 1. CLI --name flag\n * 2. config.relay.name (if relay is an object with name property)\n * 3. config.identity.name\n * 4. undefined (no name broadcast)\n *\n * @param config - The Agora configuration (or compatible config with identity and optional relay)\n * @param cliName - Optional name from CLI --name flag\n * @returns The resolved name to broadcast, or undefined if none available\n */\nexport function resolveBroadcastName(\n config: { identity: { name?: string }; relay?: { name?: string } | string },\n cliName?: string\n): string | undefined {\n // Priority 1: CLI --name flag\n if (cliName) {\n return cliName;\n }\n\n // Priority 2: config.relay.name (if relay is an object with name property)\n if (config.relay) {\n if (typeof config.relay === 'object' && config.relay.name) {\n return config.relay.name;\n }\n }\n\n // Priority 3: config.identity.name\n if (config.identity.name) {\n return config.identity.name;\n }\n\n // Priority 4: No name available\n return undefined;\n}\n\n/**\n * Formats a display name with short ID postfix.\n * If name exists: \"name (...3f8c2247)\"\n * If no name: \"...3f8c2247\" (short ID only)\n *\n * @param name - Optional name to display (should not be a short ID)\n * @param publicKey - The public key to use for short ID\n * @returns Formatted display string\n */\nexport function formatDisplayName(name: string | undefined, publicKey: string): string {\n const shortId = shortKey(publicKey);\n // If name is undefined, empty, or is already a short ID, return only short ID\n if (!name || name.trim() === '' || name.startsWith('...')) {\n return shortId;\n }\n return `${name} (${shortId})`;\n}\n","/**\n * Core data structures for the Agora reputation layer.\n * Phase 1: Verification records, commit-reveal patterns, and trust scoring.\n */\n\n/**\n * A cryptographically signed verification of another agent's output or claim.\n * Core primitive for building computational reputation.\n */\nexport interface VerificationRecord {\n /** Content-addressed ID (hash of canonical JSON) */\n id: string;\n \n /** Public key of verifying agent */\n verifier: string;\n \n /** ID of message/output being verified */\n target: string;\n \n /** Capability domain (e.g., 'ocr', 'summarization', 'code_review') */\n domain: string;\n \n /** Verification verdict */\n verdict: 'correct' | 'incorrect' | 'disputed';\n \n /** Verifier's confidence in their check (0-1) */\n confidence: number;\n \n /** Optional link to independent verification data */\n evidence?: string;\n \n /** Unix timestamp (ms) */\n timestamp: number;\n \n /** Ed25519 signature over canonical JSON */\n signature: string;\n}\n\n/**\n * A commitment to a prediction before outcome is known.\n * Prevents post-hoc editing of predictions.\n */\nexport interface CommitRecord {\n /** Content-addressed ID */\n id: string;\n \n /** Public key of committing agent */\n agent: string;\n \n /** Domain of prediction */\n domain: string;\n \n /** SHA-256 hash of prediction string */\n commitment: string;\n \n /** Unix timestamp (ms) */\n timestamp: number;\n \n /** Expiry time (ms) - commitment invalid after this */\n expiry: number;\n \n /** Ed25519 signature */\n signature: string;\n}\n\n/**\n * Reveals the prediction and outcome after commitment expiry.\n * Enables verification of prediction accuracy.\n */\nexport interface RevealRecord {\n /** Content-addressed ID */\n id: string;\n \n /** Public key of revealing agent */\n agent: string;\n \n /** ID of original commit message */\n commitmentId: string;\n \n /** Original prediction (plaintext) */\n prediction: string;\n \n /** Observed outcome */\n outcome: string;\n \n /** Evidence for outcome (optional) */\n evidence?: string;\n \n /** Unix timestamp (ms) */\n timestamp: number;\n \n /** Ed25519 signature */\n signature: string;\n}\n\n/**\n * Computed reputation score for an agent in a specific domain.\n * Derived from verification history, not stored directly.\n */\nexport interface TrustScore {\n /** Public key of agent being scored */\n agent: string;\n \n /** Domain of reputation */\n domain: string;\n \n /** Computed score (0-1, where 1 = highest trust) */\n score: number;\n \n /** Number of verifications considered */\n verificationCount: number;\n \n /** Timestamp of most recent verification (ms) */\n lastVerified: number;\n \n /** Public keys of top verifiers (by weight) */\n topVerifiers: string[];\n}\n\n/**\n * Request for reputation data about a specific agent.\n */\nexport interface ReputationQuery {\n /** Public key of agent being queried */\n agent: string;\n \n /** Optional: filter by capability domain */\n domain?: string;\n \n /** Optional: only include verifications after this timestamp */\n after?: number;\n}\n\n/**\n * Response containing reputation data for a queried agent.\n */\nexport interface ReputationResponse {\n /** Public key of agent being reported on */\n agent: string;\n \n /** Domain filter (if requested) */\n domain?: string;\n \n /** Verification records matching the query */\n verifications: VerificationRecord[];\n \n /** Computed trust scores by domain */\n scores: Record<string, TrustScore>;\n}\n\n/**\n * Revocation of a previously issued verification.\n * Used when a verifier discovers their verification was incorrect.\n */\nexport interface RevocationRecord {\n /** Content-addressed ID of this revocation */\n id: string;\n \n /** Public key of agent revoking (must match original verifier) */\n verifier: string;\n \n /** ID of verification being revoked */\n verificationId: string;\n \n /** Reason for revocation */\n reason: string;\n \n /** Unix timestamp (ms) */\n timestamp: number;\n \n /** Ed25519 signature */\n signature: string;\n}\n\n/**\n * Validation result structure\n */\nexport interface ValidationResult {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Validate a verification record structure\n */\nexport function validateVerificationRecord(record: unknown): ValidationResult {\n const errors: string[] = [];\n \n if (typeof record !== 'object' || record === null) {\n return { valid: false, errors: ['Record must be an object'] };\n }\n \n const r = record as Record<string, unknown>;\n \n if (typeof r.id !== 'string' || r.id.length === 0) {\n errors.push('id must be a non-empty string');\n }\n \n if (typeof r.verifier !== 'string' || r.verifier.length === 0) {\n errors.push('verifier must be a non-empty string');\n }\n \n if (typeof r.target !== 'string' || r.target.length === 0) {\n errors.push('target must be a non-empty string');\n }\n \n if (typeof r.domain !== 'string' || r.domain.length === 0) {\n errors.push('domain must be a non-empty string');\n }\n \n if (!['correct', 'incorrect', 'disputed'].includes(r.verdict as string)) {\n errors.push('verdict must be one of: correct, incorrect, disputed');\n }\n \n if (typeof r.confidence !== 'number' || r.confidence < 0 || r.confidence > 1) {\n errors.push('confidence must be a number between 0 and 1');\n }\n \n if (r.evidence !== undefined && typeof r.evidence !== 'string') {\n errors.push('evidence must be a string if provided');\n }\n \n if (typeof r.timestamp !== 'number' || r.timestamp <= 0) {\n errors.push('timestamp must be a positive number');\n }\n \n if (typeof r.signature !== 'string' || r.signature.length === 0) {\n errors.push('signature must be a non-empty string');\n }\n \n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate a commit record structure\n */\nexport function validateCommitRecord(record: unknown): ValidationResult {\n const errors: string[] = [];\n \n if (typeof record !== 'object' || record === null) {\n return { valid: false, errors: ['Record must be an object'] };\n }\n \n const r = record as Record<string, unknown>;\n \n if (typeof r.id !== 'string' || r.id.length === 0) {\n errors.push('id must be a non-empty string');\n }\n \n if (typeof r.agent !== 'string' || r.agent.length === 0) {\n errors.push('agent must be a non-empty string');\n }\n \n if (typeof r.domain !== 'string' || r.domain.length === 0) {\n errors.push('domain must be a non-empty string');\n }\n \n if (typeof r.commitment !== 'string' || r.commitment.length !== 64) {\n errors.push('commitment must be a 64-character hex string (SHA-256 hash)');\n }\n \n if (typeof r.timestamp !== 'number' || r.timestamp <= 0) {\n errors.push('timestamp must be a positive number');\n }\n \n if (typeof r.expiry !== 'number' || r.expiry <= 0) {\n errors.push('expiry must be a positive number');\n }\n \n if (typeof r.expiry === 'number' && typeof r.timestamp === 'number' && r.expiry <= r.timestamp) {\n errors.push('expiry must be after timestamp');\n }\n \n if (typeof r.signature !== 'string' || r.signature.length === 0) {\n errors.push('signature must be a non-empty string');\n }\n \n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate a reveal record structure\n */\nexport function validateRevealRecord(record: unknown): ValidationResult {\n const errors: string[] = [];\n \n if (typeof record !== 'object' || record === null) {\n return { valid: false, errors: ['Record must be an object'] };\n }\n \n const r = record as Record<string, unknown>;\n \n if (typeof r.id !== 'string' || r.id.length === 0) {\n errors.push('id must be a non-empty string');\n }\n \n if (typeof r.agent !== 'string' || r.agent.length === 0) {\n errors.push('agent must be a non-empty string');\n }\n \n if (typeof r.commitmentId !== 'string' || r.commitmentId.length === 0) {\n errors.push('commitmentId must be a non-empty string');\n }\n \n if (typeof r.prediction !== 'string' || r.prediction.length === 0) {\n errors.push('prediction must be a non-empty string');\n }\n \n if (typeof r.outcome !== 'string' || r.outcome.length === 0) {\n errors.push('outcome must be a non-empty string');\n }\n \n if (r.evidence !== undefined && typeof r.evidence !== 'string') {\n errors.push('evidence must be a string if provided');\n }\n \n if (typeof r.timestamp !== 'number' || r.timestamp <= 0) {\n errors.push('timestamp must be a positive number');\n }\n \n if (typeof r.signature !== 'string' || r.signature.length === 0) {\n errors.push('signature must be a non-empty string');\n }\n \n return { valid: errors.length === 0, errors };\n}\n","/**\n * Local reputation store using JSONL append-only log.\n * Stores verification records, commits, and reveals.\n */\n\nimport { promises as fs } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { VerificationRecord, CommitRecord, RevealRecord } from './types';\nimport { validateVerificationRecord, validateCommitRecord, validateRevealRecord } from './types';\n\n/**\n * Record type discriminator for JSONL storage\n */\ntype StoredRecord = \n | ({ type: 'verification' } & VerificationRecord)\n | ({ type: 'commit' } & CommitRecord)\n | ({ type: 'reveal' } & RevealRecord);\n\n/**\n * Reputation store with JSONL persistence\n */\nexport class ReputationStore {\n private filePath: string;\n private verifications: Map<string, VerificationRecord> = new Map();\n private commits: Map<string, CommitRecord> = new Map();\n private reveals: Map<string, RevealRecord> = new Map();\n private loaded = false;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n /**\n * Load records from JSONL file\n */\n async load(): Promise<void> {\n try {\n const content = await fs.readFile(this.filePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(line => line.length > 0);\n \n for (const line of lines) {\n try {\n const record = JSON.parse(line) as StoredRecord;\n \n switch (record.type) {\n case 'verification': {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...verification } = record;\n const validation = validateVerificationRecord(verification);\n if (validation.valid) {\n this.verifications.set(verification.id, verification as VerificationRecord);\n }\n break;\n }\n case 'commit': {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...commit } = record;\n const validation = validateCommitRecord(commit);\n if (validation.valid) {\n this.commits.set(commit.id, commit as CommitRecord);\n }\n break;\n }\n case 'reveal': {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...reveal } = record;\n const validation = validateRevealRecord(reveal);\n if (validation.valid) {\n this.reveals.set(reveal.id, reveal as RevealRecord);\n }\n break;\n }\n }\n } catch {\n // Skip invalid lines\n continue;\n }\n }\n \n this.loaded = true;\n } catch (error) {\n // File doesn't exist yet - that's okay for first run\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n this.loaded = true;\n return;\n }\n throw error;\n }\n }\n\n /**\n * Ensure the store is loaded\n */\n private async ensureLoaded(): Promise<void> {\n if (!this.loaded) {\n await this.load();\n }\n }\n\n /**\n * Append a record to the JSONL file\n */\n private async appendToFile(record: StoredRecord): Promise<void> {\n // Ensure directory exists\n await fs.mkdir(dirname(this.filePath), { recursive: true });\n \n // Append JSONL line\n const line = JSON.stringify(record) + '\\n';\n await fs.appendFile(this.filePath, line, 'utf-8');\n }\n\n /**\n * Add a verification record\n */\n async addVerification(verification: VerificationRecord): Promise<void> {\n await this.ensureLoaded();\n \n const validation = validateVerificationRecord(verification);\n if (!validation.valid) {\n throw new Error(`Invalid verification: ${validation.errors.join(', ')}`);\n }\n \n this.verifications.set(verification.id, verification);\n await this.appendToFile({ type: 'verification', ...verification });\n }\n\n /**\n * Add a commit record\n */\n async addCommit(commit: CommitRecord): Promise<void> {\n await this.ensureLoaded();\n \n const validation = validateCommitRecord(commit);\n if (!validation.valid) {\n throw new Error(`Invalid commit: ${validation.errors.join(', ')}`);\n }\n \n this.commits.set(commit.id, commit);\n await this.appendToFile({ type: 'commit', ...commit });\n }\n\n /**\n * Add a reveal record\n */\n async addReveal(reveal: RevealRecord): Promise<void> {\n await this.ensureLoaded();\n \n const validation = validateRevealRecord(reveal);\n if (!validation.valid) {\n throw new Error(`Invalid reveal: ${validation.errors.join(', ')}`);\n }\n \n this.reveals.set(reveal.id, reveal);\n await this.appendToFile({ type: 'reveal', ...reveal });\n }\n\n /**\n * Get all verifications\n */\n async getVerifications(): Promise<VerificationRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.verifications.values());\n }\n\n /**\n * Get verifications for a specific target\n */\n async getVerificationsByTarget(target: string): Promise<VerificationRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.verifications.values()).filter(v => v.target === target);\n }\n\n /**\n * Get verifications by domain\n */\n async getVerificationsByDomain(domain: string): Promise<VerificationRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.verifications.values()).filter(v => v.domain === domain);\n }\n\n /**\n * Get verifications for an agent (where they are the target of verification)\n * This requires looking up the target message to find the agent\n * For now, we'll return all verifications and let the caller filter\n */\n async getVerificationsByDomainForAgent(domain: string): Promise<VerificationRecord[]> {\n return this.getVerificationsByDomain(domain);\n }\n\n /**\n * Get all commits\n */\n async getCommits(): Promise<CommitRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.commits.values());\n }\n\n /**\n * Get commit by ID\n */\n async getCommit(id: string): Promise<CommitRecord | null> {\n await this.ensureLoaded();\n return this.commits.get(id) || null;\n }\n\n /**\n * Get commits by agent\n */\n async getCommitsByAgent(agent: string): Promise<CommitRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.commits.values()).filter(c => c.agent === agent);\n }\n\n /**\n * Get all reveals\n */\n async getReveals(): Promise<RevealRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.reveals.values());\n }\n\n /**\n * Get reveal by commitment ID\n */\n async getRevealByCommitment(commitmentId: string): Promise<RevealRecord | null> {\n await this.ensureLoaded();\n return Array.from(this.reveals.values()).find(r => r.commitmentId === commitmentId) || null;\n }\n\n /**\n * Get reveals by agent\n */\n async getRevealsByAgent(agent: string): Promise<RevealRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.reveals.values()).filter(r => r.agent === agent);\n }\n}\n","/**\n * Verification record creation and validation.\n * Core primitive for computational reputation.\n */\n\nimport { createEnvelope, verifyEnvelope } from '../message/envelope';\nimport type { VerificationRecord } from './types';\nimport { validateVerificationRecord } from './types';\n\n/**\n * Create a signed verification record\n * @param verifier - Public key of the verifying agent\n * @param privateKey - Private key for signing\n * @param target - ID of the message/output being verified\n * @param domain - Capability domain\n * @param verdict - Verification verdict\n * @param confidence - Verifier's confidence (0-1)\n * @param timestamp - Timestamp for the verification (ms)\n * @param evidence - Optional link to verification evidence\n * @returns Signed VerificationRecord\n */\nexport function createVerification(\n verifier: string,\n privateKey: string,\n target: string,\n domain: string,\n verdict: 'correct' | 'incorrect' | 'disputed',\n confidence: number,\n timestamp: number,\n evidence?: string\n): VerificationRecord {\n // Validate confidence range\n if (confidence < 0 || confidence > 1) {\n throw new Error('confidence must be between 0 and 1');\n }\n \n // Create the payload for signing\n const payload: Record<string, unknown> = {\n verifier,\n target,\n domain,\n verdict,\n confidence,\n timestamp,\n };\n \n if (evidence !== undefined) {\n payload.evidence = evidence;\n }\n \n // Create signed envelope with type 'verification'\n const envelope = createEnvelope('verification', verifier, privateKey, payload, timestamp);\n \n // Return verification record\n const record: VerificationRecord = {\n id: envelope.id,\n verifier,\n target,\n domain,\n verdict,\n confidence,\n timestamp,\n signature: envelope.signature,\n };\n \n if (evidence !== undefined) {\n record.evidence = evidence;\n }\n \n return record;\n}\n\n/**\n * Verify the cryptographic signature of a verification record\n * @param record - The verification record to verify\n * @returns Object with valid flag and optional reason for failure\n */\nexport function verifyVerificationSignature(\n record: VerificationRecord\n): { valid: boolean; reason?: string } {\n // First validate the structure\n const structureValidation = validateVerificationRecord(record);\n if (!structureValidation.valid) {\n return { \n valid: false, \n reason: `Invalid structure: ${structureValidation.errors.join(', ')}` \n };\n }\n \n // Reconstruct the envelope for signature verification\n const payload: Record<string, unknown> = {\n verifier: record.verifier,\n target: record.target,\n domain: record.domain,\n verdict: record.verdict,\n confidence: record.confidence,\n timestamp: record.timestamp,\n };\n \n if (record.evidence !== undefined) {\n payload.evidence = record.evidence;\n }\n \n const envelope = {\n id: record.id,\n type: 'verification' as const,\n sender: record.verifier,\n timestamp: record.timestamp,\n payload,\n signature: record.signature,\n };\n \n // Verify the envelope signature\n return verifyEnvelope(envelope);\n}\n","/**\n * Commit-reveal pattern implementation for tamper-proof predictions.\n * Agents commit to predictions before outcomes are known, then reveal after.\n */\n\nimport { createHash } from 'node:crypto';\nimport { createEnvelope } from '../message/envelope';\nimport type { CommitRecord, RevealRecord } from './types';\nimport { validateCommitRecord, validateRevealRecord } from './types';\n\n/**\n * Create a commitment hash for a prediction\n * @param prediction - The prediction string\n * @returns SHA-256 hash of the prediction (hex string)\n */\nexport function hashPrediction(prediction: string): string {\n return createHash('sha256').update(prediction).digest('hex');\n}\n\n/**\n * Create a signed commit record\n * @param agent - Public key of the committing agent\n * @param privateKey - Private key for signing\n * @param domain - Domain of the prediction\n * @param prediction - The prediction to commit to\n * @param timestamp - Timestamp for the commit (ms)\n * @param expiryMs - Expiry time in milliseconds from timestamp\n * @returns Signed CommitRecord\n */\nexport function createCommit(\n agent: string,\n privateKey: string,\n domain: string,\n prediction: string,\n timestamp: number,\n expiryMs: number\n): CommitRecord {\n const commitment = hashPrediction(prediction);\n const expiry = timestamp + expiryMs;\n \n // Create the payload for signing\n const payload = {\n agent,\n domain,\n commitment,\n timestamp,\n expiry,\n };\n \n // Create signed envelope with type 'commit'\n const envelope = createEnvelope('commit', agent, privateKey, payload, timestamp);\n \n // Return commit record\n return {\n id: envelope.id,\n agent,\n domain,\n commitment,\n timestamp,\n expiry,\n signature: envelope.signature,\n };\n}\n\n/**\n * Create a signed reveal record\n * @param agent - Public key of the revealing agent\n * @param privateKey - Private key for signing\n * @param commitmentId - ID of the original commit record\n * @param prediction - The original prediction (plaintext)\n * @param outcome - The observed outcome\n * @param timestamp - Timestamp for the reveal (ms)\n * @param evidence - Optional evidence for the outcome\n * @returns Signed RevealRecord\n */\nexport function createReveal(\n agent: string,\n privateKey: string,\n commitmentId: string,\n prediction: string,\n outcome: string,\n timestamp: number,\n evidence?: string\n): RevealRecord {\n \n // Create the payload for signing\n const payload: Record<string, unknown> = {\n agent,\n commitmentId,\n prediction,\n outcome,\n timestamp,\n };\n \n if (evidence !== undefined) {\n payload.evidence = evidence;\n }\n \n // Create signed envelope with type 'reveal'\n const envelope = createEnvelope('reveal', agent, privateKey, payload, timestamp);\n \n // Return reveal record\n const record: RevealRecord = {\n id: envelope.id,\n agent,\n commitmentId,\n prediction,\n outcome,\n timestamp,\n signature: envelope.signature,\n };\n \n if (evidence !== undefined) {\n record.evidence = evidence;\n }\n \n return record;\n}\n\n/**\n * Verify a reveal against its commitment\n * @param commit - The original commit record\n * @param reveal - The reveal record\n * @returns Object with valid flag and optional reason for failure\n */\nexport function verifyReveal(\n commit: CommitRecord,\n reveal: RevealRecord\n): { valid: boolean; reason?: string } {\n // Validate structures\n const commitValidation = validateCommitRecord(commit);\n if (!commitValidation.valid) {\n return { valid: false, reason: `Invalid commit: ${commitValidation.errors.join(', ')}` };\n }\n \n const revealValidation = validateRevealRecord(reveal);\n if (!revealValidation.valid) {\n return { valid: false, reason: `Invalid reveal: ${revealValidation.errors.join(', ')}` };\n }\n \n // Check that reveal references the correct commit\n if (reveal.commitmentId !== commit.id) {\n return { valid: false, reason: 'Reveal does not reference this commit' };\n }\n \n // Check that agents match\n if (reveal.agent !== commit.agent) {\n return { valid: false, reason: 'Reveal agent does not match commit agent' };\n }\n \n // Check that reveal is after commit expiry\n if (reveal.timestamp < commit.expiry) {\n return { valid: false, reason: 'Reveal timestamp is before commit expiry' };\n }\n \n // Verify that the prediction hash matches the commitment\n const predictedHash = hashPrediction(reveal.prediction);\n if (predictedHash !== commit.commitment) {\n return { valid: false, reason: 'Prediction hash does not match commitment' };\n }\n \n return { valid: true };\n}\n","/**\n * Trust score computation with exponential time decay.\n * Domain-specific reputation scoring from verification history.\n */\n\nimport type { VerificationRecord, TrustScore } from './types';\n\n/**\n * Exponential decay function for time-based reputation degradation.\n * @param deltaTimeMs - Time since verification (milliseconds)\n * @param lambda - Decay rate (default: ln(2)/70 ≈ 0.0099, giving 70-day half-life)\n * @returns Weight multiplier (0-1)\n */\nexport function decay(deltaTimeMs: number, lambda = Math.log(2) / 70): number {\n const deltaDays = deltaTimeMs / (1000 * 60 * 60 * 24);\n return Math.exp(-lambda * deltaDays);\n}\n\n/**\n * Compute verdict weight\n * @param verdict - Verification verdict\n * @returns Weight value (+1 for correct, -1 for incorrect, 0 for disputed)\n */\nfunction verdictWeight(verdict: 'correct' | 'incorrect' | 'disputed'): number {\n switch (verdict) {\n case 'correct':\n return 1;\n case 'incorrect':\n return -1;\n case 'disputed':\n return 0;\n }\n}\n\n/**\n * Compute trust score for an agent in a specific domain\n * @param agent - Public key of the agent being scored\n * @param domain - Capability domain\n * @param verifications - All verification records (will be filtered by target and domain)\n * @param currentTime - Current timestamp (ms)\n * @returns TrustScore object with computed reputation\n */\nexport function computeTrustScore(\n agent: string,\n domain: string,\n verifications: VerificationRecord[],\n currentTime: number\n): TrustScore {\n // Filter verifications for this agent and domain\n const relevantVerifications = verifications.filter(\n v => v.target === agent && v.domain === domain\n );\n \n if (relevantVerifications.length === 0) {\n return {\n agent,\n domain,\n score: 0,\n verificationCount: 0,\n lastVerified: 0,\n topVerifiers: [],\n };\n }\n \n // Compute weighted score with time decay\n let totalWeight = 0;\n const verifierWeights = new Map<string, number>();\n \n for (const verification of relevantVerifications) {\n const deltaTime = currentTime - verification.timestamp;\n const decayFactor = decay(deltaTime);\n const verdict = verdictWeight(verification.verdict);\n const weight = verdict * verification.confidence * decayFactor;\n \n totalWeight += weight;\n \n // Track verifier contributions\n const currentVerifierWeight = verifierWeights.get(verification.verifier) || 0;\n verifierWeights.set(verification.verifier, currentVerifierWeight + Math.abs(weight));\n }\n \n // Normalize score to 0-1 range\n // Positive verifications push toward 1, negative push toward 0\n const rawScore = totalWeight / Math.max(relevantVerifications.length, 1);\n const normalizedScore = Math.max(0, Math.min(1, (rawScore + 1) / 2));\n \n // Find most recent verification\n const lastVerified = Math.max(...relevantVerifications.map(v => v.timestamp));\n \n // Get top verifiers by absolute weight\n const topVerifiers = Array.from(verifierWeights.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([verifier]) => verifier);\n \n return {\n agent,\n domain,\n score: normalizedScore,\n verificationCount: relevantVerifications.length,\n lastVerified,\n topVerifiers,\n };\n}\n\n/**\n * Compute trust scores for an agent across multiple domains\n * @param agent - Public key of the agent being scored\n * @param verifications - All verification records\n * @param currentTime - Current timestamp (ms)\n * @returns Map of domain to TrustScore\n */\nexport function computeTrustScores(\n agent: string,\n verifications: VerificationRecord[],\n currentTime: number\n): Map<string, TrustScore> {\n // Get unique domains for this agent\n const domains = new Set(\n verifications\n .filter(v => v.target === agent)\n .map(v => v.domain)\n );\n \n const scores = new Map<string, TrustScore>();\n for (const domain of domains) {\n const score = computeTrustScore(agent, domain, verifications, currentTime);\n scores.set(domain, score);\n }\n \n return scores;\n}\n\n// Alias for backward compatibility\nexport const computeAllTrustScores = computeTrustScores;\n"],"mappings":";AAAA,SAAS,MAAM,QAAQ,2BAA2B;AAc3C,SAAS,kBAA2B;AACzC,QAAM,EAAE,WAAW,WAAW,IAAI,oBAAoB,SAAS;AAE/D,SAA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EACV,IAAI,CAAC,CAAC,QAAQ,MAAM,QAAQ;AAE/B,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,mBAAmB,sBAAsB;AAAA,IACzC;AAAA,IACA;AAAA,EACF;AACF;AASO,SAAS,mBACd,OACA,eACA,aACyB;AAEzB,QAAM,UAAU,IAAI;AAAA,IAClB,cACG,OAAO,OAAK,EAAE,WAAW,KAAK,EAC9B,IAAI,OAAK,EAAE,MAAM;AAAA,EACtB;AAEA,QAAM,SAAS,oBAAI,IAAwB;AAC3C,aAAW,UAAU,SAAS;AAC5B,UAAM,QAAQ,kBAAkB,OAAO,QAAQ,eAAe,WAAW;AACzE,WAAO,IAAI,QAAQ,KAAK;AAAA,EAC1B;AAEA,SAAO;AACT;AAGO,IAAM,wBAAwB;","names":["path","WebSocket","WebSocket","senderAgent","EventEmitter","WebSocket","EventEmitter","WebSocket","EventEmitter","EventEmitter","fs","fs","createHash","createHash"]}
package/dist/cli.d.ts CHANGED
@@ -1,3 +1 @@
1
1
  #!/usr/bin/env node
2
- export {};
3
- //# sourceMappingURL=cli.d.ts.map