@rookdaemon/agora 0.8.1 → 0.8.2

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transport/peer-config.ts","../src/transport/http.ts","../src/transport/relay.ts","../src/config.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 { 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 { 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 /** Optional convenience alias only (not identity) */\n name?: 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 allRecipients?: 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 allRecipients ?? [peerPublicKey]\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.from.substring(0, 16)}`,\n deliver: false,\n };\n\n // Build headers — only include Authorization when a token is configured\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n if (peer.token) {\n headers['Authorization'] = `Bearer ${peer.token}`;\n }\n\n const requestBody = JSON.stringify(webhookPayload);\n\n // Send HTTP POST (retry once on network error, not on 4xx/5xx)\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n const response = await fetch(`${peer.url}/agent`, {\n method: 'POST',\n headers,\n body: requestBody,\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 if (attempt === 1) {\n return {\n ok: false,\n status: 0,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n // First attempt failed with network error — retry once\n }\n }\n\n // Unreachable, but satisfies TypeScript\n return { ok: false, status: 0, error: 'Unexpected send failure' };\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.from);\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 allRecipients?: 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 allRecipients ?? [peerPublicKey]\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 allRecipients ?? [peerPublicKey]\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","import { readFileSync, existsSync, readdirSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { resolve, join, dirname } 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 [key, entry] of Object.entries(config.peers)) {\n const peer = entry as Record<string, unknown>;\n if (peer && typeof peer.publicKey === 'string') {\n peers[peer.publicKey as string] = {\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 : (key !== peer.publicKey ? key : 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\n// ---------------------------------------------------------------------------\n// Profile support\n// ---------------------------------------------------------------------------\n\n/**\n * Base directory for agora config: AGORA_CONFIG_DIR env or ~/.config/agora\n */\nexport function getConfigDir(): string {\n if (process.env.AGORA_CONFIG_DIR) {\n return resolve(process.env.AGORA_CONFIG_DIR);\n }\n return resolve(homedir(), '.config', 'agora');\n}\n\n/**\n * Resolve the config path for a given profile name.\n * - undefined / \"default\" → ~/.config/agora/config.json (existing behaviour)\n * - \"stefan\" → ~/.config/agora/profiles/stefan/config.json\n */\nexport function getProfileConfigPath(profile?: string): string {\n if (process.env.AGORA_CONFIG) {\n return resolve(process.env.AGORA_CONFIG);\n }\n const base = getConfigDir();\n if (!profile || profile === 'default') {\n return join(base, 'config.json');\n }\n return join(base, 'profiles', profile, 'config.json');\n}\n\n/**\n * List available profiles.\n * Returns an array of profile names. \"default\" is included if config.json exists.\n */\nexport function listProfiles(): string[] {\n const base = getConfigDir();\n const profiles: string[] = [];\n\n // Default profile\n if (existsSync(join(base, 'config.json'))) {\n profiles.push('default');\n }\n\n // Named profiles\n const profilesDir = join(base, 'profiles');\n if (existsSync(profilesDir)) {\n for (const entry of readdirSync(profilesDir, { withFileTypes: true })) {\n if (entry.isDirectory() && existsSync(join(profilesDir, entry.name, 'config.json'))) {\n profiles.push(entry.name);\n }\n }\n }\n\n return profiles;\n}\n\n// ---------------------------------------------------------------------------\n// Export / Import\n// ---------------------------------------------------------------------------\n\nexport interface ExportedConfig {\n /** Schema version for forward-compat */\n version: 1;\n identity?: AgoraIdentity;\n peers: Record<string, AgoraPeerConfig>;\n relay?: RelayConfig;\n}\n\nexport interface ImportResult {\n peersAdded: string[];\n peersSkipped: string[];\n identityImported: boolean;\n relayImported: boolean;\n}\n\n/**\n * Export the config (or just peers) as a portable JSON object.\n */\nexport function exportConfig(\n config: AgoraConfig,\n opts: { includeIdentity?: boolean } = {},\n): ExportedConfig {\n const exported: ExportedConfig = {\n version: 1,\n peers: Object.fromEntries(\n Object.entries(config.peers).map(([k, v]) => [k, { ...v }]),\n ),\n };\n if (opts.includeIdentity) {\n exported.identity = { ...config.identity };\n }\n if (config.relay) {\n exported.relay = { ...config.relay };\n }\n return exported;\n}\n\n/**\n * Import peers (and optionally identity/relay) into an existing config.\n * Merges peers by public key — existing peers are NOT overwritten.\n */\nexport function importConfig(\n target: AgoraConfig,\n incoming: ExportedConfig,\n opts: { overwriteIdentity?: boolean; overwriteRelay?: boolean } = {},\n): ImportResult {\n const result: ImportResult = {\n peersAdded: [],\n peersSkipped: [],\n identityImported: false,\n relayImported: false,\n };\n\n // Merge peers\n for (const [key, peer] of Object.entries(incoming.peers)) {\n if (target.peers[key]) {\n result.peersSkipped.push(key);\n } else {\n target.peers[key] = { ...peer };\n result.peersAdded.push(key);\n }\n }\n\n // Identity\n if (opts.overwriteIdentity && incoming.identity) {\n target.identity = { ...incoming.identity };\n result.identityImported = true;\n }\n\n // Relay\n if (opts.overwriteRelay && incoming.relay) {\n target.relay = { ...incoming.relay };\n result.relayImported = true;\n }\n\n return result;\n}\n\n/**\n * Save an AgoraConfig to disk (creates parent dirs as needed).\n */\nexport function saveAgoraConfig(path: string, config: AgoraConfig): void {\n const dir = dirname(path);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n const raw: Record<string, unknown> = {\n identity: config.identity,\n peers: config.peers,\n };\n if (config.relay) {\n raw.relay = config.relay;\n }\n writeFileSync(path, JSON.stringify(raw, null, 2) + '\\n', 'utf-8');\n}\n","import { EventEmitter } from 'node:events';\nimport WebSocket from 'ws';\nimport { createEnvelope, verifyEnvelope, type Envelope, type MessageType } 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) => 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 * Create a signed envelope and send it to each recipient.\n * Each envelope lists ALL recipients in the `to` field so receivers\n * know the full participant list (needed for multi-party replies).\n * Returns the list of failures (empty means all succeeded).\n */\n async sendToRecipients(\n recipients: string[],\n type: MessageType,\n payload: unknown,\n inReplyTo?: string,\n ): Promise<{ ok: boolean; errors: Array<{ recipient: string; error: string }> }> {\n if (!this.connected()) {\n return { ok: false, errors: [{ recipient: '*', error: 'Not connected to relay' }] };\n }\n\n const unique = Array.from(new Set(recipients.filter(Boolean)));\n const errors: Array<{ recipient: string; error: string }> = [];\n\n for (const recipient of unique) {\n const envelope = createEnvelope(\n type,\n this.config.publicKey,\n this.config.privateKey,\n payload,\n Date.now(),\n inReplyTo,\n unique,\n );\n const result = await this.send(recipient, envelope);\n if (!result.ok) {\n errors.push({ recipient, error: result.error ?? 'unknown error' });\n }\n }\n\n return { ok: errors.length === 0, errors };\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 };\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 const envelopeFrom = msg.envelope.from;\n if (envelopeFrom !== msg.from) {\n this.emit('error', new Error('Envelope sender does not match relay from field'));\n return;\n }\n\n // Emit verified message — relay name hint is intentionally discarded;\n // identity display must be derived from verified keys only.\n this.emit('message', msg.envelope, msg.from);\n }\n break;\n\n case 'peer_online':\n if (msg.publicKey) {\n const peer: RelayPeer = {\n publicKey: msg.publicKey,\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 Date.now(),\n undefined,\n [this.config.relayPublicKey]\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 Date.now(),\n undefined,\n [recipientPublicKey]\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.from !== 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\nexport interface PeerReferenceEntry {\n publicKey: string;\n name?: string;\n}\n\nexport type PeerReferenceDirectory =\n | Record<string, PeerReferenceEntry>\n | Map<string, PeerReferenceEntry>\n | PeerReferenceEntry[];\n\nfunction toDirectoryEntries(directory?: PeerReferenceDirectory): PeerReferenceEntry[] {\n if (!directory) {\n return [];\n }\n if (Array.isArray(directory)) {\n return directory.filter((p) => typeof p.publicKey === 'string' && p.publicKey.length > 0);\n }\n if (directory instanceof Map) {\n return Array.from(directory.values()).filter((p) => typeof p.publicKey === 'string' && p.publicKey.length > 0);\n }\n return Object.values(directory).filter((p) => typeof p.publicKey === 'string' && p.publicKey.length > 0);\n}\n\n/**\n * Merge a base directory with additional entries (e.g. seen keys).\n * Base entries take priority — if a key appears in both, the base entry (with name) wins.\n */\nexport function mergeDirectories(\n base: PeerReferenceDirectory,\n ...additional: PeerReferenceEntry[][]\n): PeerReferenceEntry[] {\n const byKey = new Map<string, PeerReferenceEntry>();\n // Additional entries first (lower priority)\n for (const entries of additional) {\n for (const entry of entries) {\n if (typeof entry.publicKey === 'string' && entry.publicKey.length > 0) {\n byKey.set(entry.publicKey, entry);\n }\n }\n }\n // Base entries override (higher priority — they have names)\n for (const entry of toDirectoryEntries(base)) {\n byKey.set(entry.publicKey, entry);\n }\n return Array.from(byKey.values());\n}\n\nfunction findById(id: string, directory?: PeerReferenceDirectory): PeerReferenceEntry | undefined {\n return toDirectoryEntries(directory).find((entry) => entry.publicKey === id);\n}\n\n/**\n * Shorten a full peer ID for display/reference.\n * Canonical form:\n * - Configured name => \"name@<last8>\"\n * - Unknown/no-name => \"@<last8>\"\n */\nexport function shorten(id: string, directory?: PeerReferenceDirectory): string {\n const suffix = id.slice(-8);\n const entry = findById(id, directory);\n if (!entry?.name) {\n return `@${suffix}`;\n }\n return `${entry.name}@${suffix}`;\n}\n\n/**\n * Expand a short peer reference to a full ID.\n * Supports: full ID, unique name, name@last8, @last8.\n * Also supports legacy name...last8 and ...last8 forms.\n */\nexport function expand(shortId: string, directory: PeerReferenceDirectory): string | undefined {\n const entries = toDirectoryEntries(directory);\n if (entries.length === 0) {\n return undefined;\n }\n\n const token = shortId.trim();\n const direct = entries.find((entry) => entry.publicKey === token);\n if (direct) {\n return direct.publicKey;\n }\n\n // name@suffix8 (current canonical form)\n const namedAtSuffix = token.match(/^(.+)@([0-9a-fA-F]{8})$/);\n if (namedAtSuffix) {\n const [, name, suffix] = namedAtSuffix;\n const matches = entries.filter((entry) => entry.name === name && entry.publicKey.toLowerCase().endsWith(suffix.toLowerCase()));\n if (matches.length === 1) {\n return matches[0].publicKey;\n }\n return undefined;\n }\n\n // @suffix8 (current canonical form for unknown peers)\n const atSuffixOnly = token.match(/^@([0-9a-fA-F]{8})$/);\n if (atSuffixOnly) {\n const [, suffix] = atSuffixOnly;\n const matches = entries.filter((entry) => entry.publicKey.toLowerCase().endsWith(suffix.toLowerCase()));\n if (matches.length === 1) {\n return matches[0].publicKey;\n }\n return undefined;\n }\n\n // Legacy: name...suffix8\n const namedWithSuffix = token.match(/^(.+)\\.\\.\\.([0-9a-fA-F]{8})$/);\n if (namedWithSuffix) {\n const [, name, suffix] = namedWithSuffix;\n const matches = entries.filter((entry) => entry.name === name && entry.publicKey.toLowerCase().endsWith(suffix.toLowerCase()));\n if (matches.length === 1) {\n return matches[0].publicKey;\n }\n return undefined;\n }\n\n // Legacy: ...suffix8\n const suffixOnly = token.match(/^\\.\\.\\.([0-9a-fA-F]{8})$/);\n if (suffixOnly) {\n const [, suffix] = suffixOnly;\n const matches = entries.filter((entry) => entry.publicKey.toLowerCase().endsWith(suffix.toLowerCase()));\n if (matches.length === 1) {\n return matches[0].publicKey;\n }\n return undefined;\n }\n\n const byName = entries.filter((entry) => entry.name === token);\n if (byName.length === 1) {\n return byName[0].publicKey;\n }\n\n return undefined;\n}\n\n/**\n * Expand inline @references in text to full IDs using configured peers.\n */\nexport function expandInlineReferences(text: string, directory: PeerReferenceDirectory): string {\n return text.replace(/@([^\\s]+)/g, (_full, token: string) => {\n const resolved = expand(token, directory);\n return resolved ? `@${resolved}` : `@${token}`;\n });\n}\n\n/**\n * Compact inline @<full-id> references for rendering.\n */\nexport function compactInlineReferences(text: string, directory: PeerReferenceDirectory): string {\n return text.replace(/@([0-9a-fA-F]{16,})/g, (_full, id: string) => `@${shorten(id, directory)}`);\n}\n\n/**\n * Compact inline @<full-id> references only when the full ID exists in the\n * provided directory. Unknown IDs remain unchanged.\n */\nexport function compactKnownInlineReferences(text: string, directory: PeerReferenceDirectory): string {\n return text.replace(/@([0-9a-fA-F]{16,})/g, (_full, id: string) => {\n const known = findById(id, directory);\n if (!known) {\n return `@${id}`;\n }\n return `@${shorten(id, directory)}`;\n });\n}\n\n/**\n * Extract text content from an envelope payload.\n * Handles { text: string } objects, plain strings, and fallback to JSON.\n * All output is sanitized.\n */\nexport function extractTextFromPayload(payload: unknown): string {\n if (payload && typeof payload === 'object' && 'text' in payload && typeof (payload as { text: unknown }).text === 'string') {\n return sanitizeText((payload as { text: string }).text);\n }\n if (typeof payload === 'string') return sanitizeText(payload);\n return sanitizeText(JSON.stringify(payload ?? ''));\n}\n\n/**\n * Strip characters that can crash downstream width/segmenter logic in UIs.\n * Removes control chars (except newline/tab) and replaces lone surrogates.\n */\nexport function sanitizeText(text: string): string {\n return text\n .replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F]/g, '')\n .replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])/g, '\\uFFFD')\n .replace(/(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, '\\uFFFD');\n}\n\n/**\n * Resolve a display name for a peer.\n * Only returns locally configured names from the peer directory.\n * Identity must be derived from verified keys — sender-claimed names are never accepted.\n */\nexport function resolveDisplayName(\n publicKey: string,\n directory?: PeerReferenceDirectory,\n): string | undefined {\n const entry = findById(publicKey, directory);\n if (entry?.name) {\n return entry.name;\n }\n\n return undefined;\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 using the canonical moniker form.\n * If name exists: \"name@3f8c2247\" (same form as shorten())\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 suffix = publicKey.slice(-8);\n // If name is undefined, empty, or is already a short ID, return only short ID\n if (!name || name.trim() === '' || name.startsWith('...') || name.startsWith('@')) {\n return `@${suffix}`;\n }\n return `${name}@${suffix}`;\n}\n\n/**\n * A conversation entry with FROM/TO metadata, used for CONVERSATION.md formatting.\n */\nexport interface ConversationEntry {\n timestamp: number;\n from: string;\n to: string[];\n text: string;\n}\n\n/**\n * Format a conversation entry as a single line for CONVERSATION.md.\n * Format: [ISO_TIMESTAMP] **FROM:** sender **TO:** recipient1, recipient2 text\n */\nexport function formatConversationLine(entry: ConversationEntry): string {\n const ts = new Date(entry.timestamp).toISOString();\n const toList = entry.to.length > 0 ? entry.to.join(', ') : '(none)';\n const safeText = entry.text.replace(/\\r?\\n/g, ' ');\n return `[${ts}] **FROM:** ${entry.from} **TO:** ${toList} ${safeText}`;\n}\n\n/**\n * Parse a single CONVERSATION.md line back into a ConversationEntry.\n * Returns null if the line doesn't match the expected format.\n */\nexport function parseConversationLine(line: string): ConversationEntry | null {\n const match = line.match(\n /^\\[([^\\]]+)\\] \\*\\*FROM:\\*\\* (\\S+) \\*\\*TO:\\*\\* ([^\\s,]+(?:, [^\\s,]+)*|\\(none\\))(?: (.*))?$/\n );\n if (!match) return null;\n const [, ts, from, toRaw, text] = match;\n const timestamp = new Date(ts).getTime();\n if (isNaN(timestamp)) return null;\n const to = toRaw === '(none)' ? [] : toRaw.split(', ').filter(Boolean);\n return { timestamp, from, to, text: text ?? '' };\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, undefined, [verifier]);\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 from: record.verifier,\n to: [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, undefined, [agent]);\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, undefined, [agent]);\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 * Options for recursive trust score computation.\n */\nexport interface TrustScoreOptions {\n /**\n * Optional function to get verifier's trust score for recursive weighting.\n * When provided, each verification is weighted by the verifier's own trust score.\n * Defaults to returning 1.0 (flat weighting, backward compatible).\n * New agents with no score should return 0.5 (neutral bootstrapping weight).\n */\n getVerifierScore?: (verifier: string, domain: string) => number;\n /**\n * Maximum recursion depth for recursive scoring. Default: 3.\n * At depth 0, flat weighting (1.0) is used instead of calling getVerifierScore.\n */\n maxDepth?: number;\n /**\n * Internal: set of agents currently being scored, used for cycle detection.\n * Pass a shared mutable Set when making recursive calls to enable cycle detection.\n * When a verifier is found in this set, neutral weight (0.5) is used instead of recursing.\n */\n visitedAgents?: Set<string>;\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 * @param options - Optional settings for recursive scoring and cycle detection\n * @returns TrustScore object with computed reputation\n */\nexport function computeTrustScore(\n agent: string,\n domain: string,\n verifications: VerificationRecord[],\n currentTime: number,\n options?: TrustScoreOptions\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 const maxDepth = options?.maxDepth ?? 3;\n const visitedAgents = options?.visitedAgents;\n const getVerifierScore = options?.getVerifierScore;\n\n // Mark current agent as being scored (cycle detection)\n if (visitedAgents) {\n visitedAgents.add(agent);\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\n // Determine verifier trust weight for recursive scoring\n let verifierTrustWeight: number;\n if (!getVerifierScore || maxDepth <= 0) {\n // No recursive scoring or depth limit reached — use flat weight\n verifierTrustWeight = 1.0;\n } else if (visitedAgents?.has(verification.verifier)) {\n // Cycle detected — use neutral weight (0.5) instead of recursing\n verifierTrustWeight = 0.5;\n } else {\n verifierTrustWeight = getVerifierScore(verification.verifier, domain);\n }\n\n const weight = verdict * verification.confidence * decayFactor * verifierTrustWeight;\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 // Backtrack: remove current agent from visited set for correct DFS traversal\n if (visitedAgents) {\n visitedAgents.delete(agent);\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,cAAc,eAAe,kBAAkB;AA2BjD,SAAS,eAAe,MAA8B;AAC3D,QAAM,UAAU,aAAa,MAAM,OAAO;AAC1C,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KAAK,IAAI,GAAG,sBAAsB,IAAI,OAAK,EAAE,SAAS,CAAC;AAG5E,QAAM,eAAe,MAAM,KAAK,gBAAgB,QAAQ,CAAC,EACtD,KAAK,CAAC,GAAG,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,EAC1B,MAAM,GAAG,CAAC,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":["resolve","readFileSync","existsSync","writeFileSync","WebSocket","WebSocket","resolve","EventEmitter","EventEmitter","resolve","dirname","dirname"]}
@@ -349,7 +349,6 @@ var RelayServer = class _RelayServer extends EventEmitter {
349
349
  return;
350
350
  }
351
351
  const publicKey = msg.publicKey;
352
- const name = msg.name;
353
352
  agentPublicKey = publicKey;
354
353
  sessionId = crypto.randomUUID();
355
354
  if (!this.sessions.has(publicKey) && this.sessions.size >= this.maxPeers) {
@@ -359,7 +358,6 @@ var RelayServer = class _RelayServer extends EventEmitter {
359
358
  }
360
359
  const agent = {
361
360
  publicKey,
362
- name,
363
361
  socket,
364
362
  lastSeen: Date.now()
365
363
  };
@@ -370,14 +368,13 @@ var RelayServer = class _RelayServer extends EventEmitter {
370
368
  const isFirstSession = this.sessions.get(publicKey).size === 1;
371
369
  this.emit("agent-registered", publicKey);
372
370
  const peers = [];
373
- for (const [key, sessionMap] of this.sessions) {
371
+ for (const [key] of this.sessions) {
374
372
  if (key === publicKey) continue;
375
- const firstAgent = sessionMap.values().next().value;
376
- peers.push({ publicKey: key, name: firstAgent?.name });
373
+ peers.push({ publicKey: key });
377
374
  }
378
375
  for (const storagePeer of this.storagePeers) {
379
376
  if (storagePeer !== publicKey && !this.sessions.has(storagePeer)) {
380
- peers.push({ publicKey: storagePeer, name: void 0 });
377
+ peers.push({ publicKey: storagePeer });
381
378
  }
382
379
  }
383
380
  socket.send(JSON.stringify({
@@ -387,7 +384,7 @@ var RelayServer = class _RelayServer extends EventEmitter {
387
384
  peers
388
385
  }));
389
386
  if (isFirstSession) {
390
- this.broadcastPeerEvent("peer_online", publicKey, name);
387
+ this.broadcastPeerEvent("peer_online", publicKey);
391
388
  }
392
389
  if (this.store && this.storagePeers.includes(publicKey)) {
393
390
  const queued = this.store.load(publicKey);
@@ -457,7 +454,7 @@ var RelayServer = class _RelayServer extends EventEmitter {
457
454
  });
458
455
  this.emit("message-relayed", agentPublicKey, msg.to, envelope);
459
456
  } else {
460
- this.sendError(socket, "Recipient not connected", "unknown_recipient");
457
+ this.sendError(socket, `Recipient not connected: ${msg.to}`, "unknown_recipient");
461
458
  }
462
459
  return;
463
460
  }
@@ -492,15 +489,13 @@ var RelayServer = class _RelayServer extends EventEmitter {
492
489
  if (agentPublicKey && sessionId) {
493
490
  const sessionMap = this.sessions.get(agentPublicKey);
494
491
  if (sessionMap) {
495
- const agent = sessionMap.get(sessionId);
496
- const agentName = agent?.name;
497
492
  sessionMap.delete(sessionId);
498
493
  if (sessionMap.size === 0) {
499
494
  this.sessions.delete(agentPublicKey);
500
495
  this.emit("agent-disconnected", agentPublicKey);
501
496
  this.emit("disconnection", agentPublicKey);
502
497
  if (!this.storagePeers.includes(agentPublicKey)) {
503
- this.broadcastPeerEvent("peer_offline", agentPublicKey, agentName);
498
+ this.broadcastPeerEvent("peer_offline", agentPublicKey);
504
499
  }
505
500
  }
506
501
  }
@@ -527,11 +522,10 @@ var RelayServer = class _RelayServer extends EventEmitter {
527
522
  /**
528
523
  * Broadcast a peer event to all connected agents (all sessions except the one for publicKey)
529
524
  */
530
- broadcastPeerEvent(eventType, publicKey, name) {
525
+ broadcastPeerEvent(eventType, publicKey) {
531
526
  const message = {
532
527
  type: eventType,
533
- publicKey,
534
- name
528
+ publicKey
535
529
  };
536
530
  const messageStr = JSON.stringify(message);
537
531
  for (const [key, sessionMap] of this.sessions) {
@@ -573,8 +567,7 @@ var RelayServer = class _RelayServer extends EventEmitter {
573
567
  const response = {
574
568
  peers: peers.map((p) => ({
575
569
  publicKey: p.publicKey,
576
- metadata: p.name || p.metadata ? {
577
- name: p.name,
570
+ metadata: p.metadata ? {
578
571
  version: p.metadata?.version,
579
572
  capabilities: p.metadata?.capabilities
580
573
  } : void 0,
@@ -596,7 +589,6 @@ var RelayServer = class _RelayServer extends EventEmitter {
596
589
  const relayMessage = {
597
590
  type: "message",
598
591
  from: this.identity.publicKey,
599
- name: "relay",
600
592
  envelope: responseEnvelope
601
593
  };
602
594
  try {
@@ -620,4 +612,4 @@ export {
620
612
  MessageStore,
621
613
  RelayServer
622
614
  };
623
- //# sourceMappingURL=chunk-MJGCRX6B.js.map
615
+ //# sourceMappingURL=chunk-EFX36SN3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/identity/keypair.ts","../src/message/envelope.ts","../src/relay/store.ts","../src/relay/server.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 { 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 peer ID (full ID) */\n from: string;\n /** Recipient peer IDs (full IDs) */\n to: 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(\n type: MessageType,\n from: string,\n to: string[],\n timestamp: number,\n payload: unknown,\n inReplyTo?: string,\n): string {\n const obj: Record<string, unknown> = { from, payload, timestamp, to, type };\n if (inReplyTo !== undefined) {\n obj.inReplyTo = inReplyTo;\n }\n return stableStringify(obj);\n}\n\nfunction normalizeRecipients(from: string, to?: string | string[]): string[] {\n const list = Array.isArray(to) ? to : (typeof to === 'string' ? [to] : [from]);\n const unique = new Set<string>();\n for (const recipient of list) {\n if (typeof recipient === 'string' && recipient.trim().length > 0) {\n unique.add(recipient);\n }\n }\n if (unique.size === 0) {\n unique.add(from);\n }\n return Array.from(unique);\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 from - 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 * @param to - Recipient peer ID(s)\n * @returns A signed Envelope\n */\nexport function createEnvelope<T>(\n type: MessageType,\n from: string,\n privateKey: string,\n payload: T,\n timestamp: number = Date.now(),\n inReplyTo?: string,\n to?: string | string[],\n): Envelope<T> {\n const recipients = normalizeRecipients(from, to);\n const canonical = canonicalize(type, from, recipients, timestamp, payload, inReplyTo);\n const id = computeId(canonical);\n const signature = signMessage(canonical, privateKey);\n\n return {\n id,\n type,\n from,\n to: recipients,\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, from, to, timestamp, payload, signature, inReplyTo } = envelope;\n if (!from || !Array.isArray(to) || to.length === 0) {\n return { valid: false, reason: 'invalid_routing_fields' };\n }\n\n // Reconstruct canonical form.\n const canonical = canonicalize(type, from, to, 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 const sigValid = verifySignature(canonical, signature, from);\n if (!sigValid) {\n return { valid: false, reason: 'signature_invalid' };\n }\n\n return { valid: true };\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 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\ninterface SenderWindow {\n count: number;\n windowStart: number;\n}\n\nexport interface RelayRateLimitOptions {\n enabled?: boolean;\n maxMessages?: number;\n windowMs?: number;\n}\n\nexport interface RelayEnvelopeDedupOptions {\n enabled?: boolean;\n maxIds?: number;\n}\n\n/**\n * Represents a connected agent in the relay\n */\ninterface ConnectedAgent {\n /** Agent's public key */\n publicKey: 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 /** Emitted when a session disconnects (same as agent-disconnected for compatibility) */\n 'disconnection': (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 /** Maximum number of concurrent registered peers (default: 100) */\n maxPeers?: number;\n /** Per-sender sliding-window message rate limiting */\n rateLimit?: RelayRateLimitOptions;\n /** Envelope ID deduplication options */\n envelopeDedup?: RelayEnvelopeDedupOptions;\n}\n\nexport class RelayServer extends EventEmitter {\n private wss: WebSocketServer | null = null;\n /** publicKey -> sessionId -> ConnectedAgent (multiple sessions per key) */\n private sessions = new Map<string, Map<string, ConnectedAgent>>();\n private identity?: { publicKey: string; privateKey: string };\n private storagePeers: string[] = [];\n private store: MessageStore | null = null;\n private maxPeers: number = 100;\n private readonly senderWindows: Map<string, SenderWindow> = new Map();\n private static readonly MAX_SENDER_ENTRIES = 500;\n private readonly processedEnvelopeIds: Set<string> = new Set();\n private rateLimitEnabled = true;\n private rateLimitMaxMessages = 10;\n private rateLimitWindowMs = 60_000;\n private envelopeDedupEnabled = true;\n private envelopeDedupMaxIds = 1000;\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 if (opts.maxPeers !== undefined) {\n this.maxPeers = opts.maxPeers;\n }\n if (opts.rateLimit) {\n if (opts.rateLimit.enabled !== undefined) {\n this.rateLimitEnabled = opts.rateLimit.enabled;\n }\n if (opts.rateLimit.maxMessages !== undefined && opts.rateLimit.maxMessages > 0) {\n this.rateLimitMaxMessages = opts.rateLimit.maxMessages;\n }\n if (opts.rateLimit.windowMs !== undefined && opts.rateLimit.windowMs > 0) {\n this.rateLimitWindowMs = opts.rateLimit.windowMs;\n }\n }\n if (opts.envelopeDedup) {\n if (opts.envelopeDedup.enabled !== undefined) {\n this.envelopeDedupEnabled = opts.envelopeDedup.enabled;\n }\n if (opts.envelopeDedup.maxIds !== undefined && opts.envelopeDedup.maxIds > 0) {\n this.envelopeDedupMaxIds = opts.envelopeDedup.maxIds;\n }\n }\n }\n }\n\n private isRateLimitedSender(senderPublicKey: string): boolean {\n if (!this.rateLimitEnabled) {\n return false;\n }\n\n const now = Date.now();\n const window = this.senderWindows.get(senderPublicKey);\n\n if (this.senderWindows.size >= RelayServer.MAX_SENDER_ENTRIES && !window) {\n this.evictOldestSenderWindow();\n }\n\n if (!window || (now - window.windowStart) > this.rateLimitWindowMs) {\n this.senderWindows.set(senderPublicKey, { count: 1, windowStart: now });\n return false;\n }\n\n window.count++;\n return window.count > this.rateLimitMaxMessages;\n }\n\n private evictOldestSenderWindow(): void {\n let oldestKey: string | null = null;\n let oldestTime = Infinity;\n\n for (const [key, window] of this.senderWindows.entries()) {\n if (window.windowStart < oldestTime) {\n oldestTime = window.windowStart;\n oldestKey = key;\n }\n }\n\n if (oldestKey !== null) {\n this.senderWindows.delete(oldestKey);\n }\n }\n\n private isDuplicateEnvelopeId(envelopeId: string): boolean {\n if (!this.envelopeDedupEnabled) {\n return false;\n }\n\n if (this.processedEnvelopeIds.has(envelopeId)) {\n return true;\n }\n\n this.processedEnvelopeIds.add(envelopeId);\n if (this.processedEnvelopeIds.size > this.envelopeDedupMaxIds) {\n const oldest = this.processedEnvelopeIds.values().next().value;\n if (oldest !== undefined) {\n this.processedEnvelopeIds.delete(oldest);\n }\n }\n\n return false;\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 (all sessions)\n for (const sessionMap of this.sessions.values()) {\n for (const agent of sessionMap.values()) {\n agent.socket.close();\n }\n }\n this.sessions.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 one connected agent per public key (first session). For backward compatibility.\n */\n getAgents(): Map<string, ConnectedAgent> {\n const out = new Map<string, ConnectedAgent>();\n for (const [key, sessionMap] of this.sessions) {\n const first = sessionMap.values().next().value;\n if (first) out.set(key, first);\n }\n return out;\n }\n\n /**\n * Handle incoming connection\n */\n private handleConnection(socket: WebSocket): void {\n let agentPublicKey: string | null = null;\n let sessionId: 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 agentPublicKey = publicKey;\n sessionId = crypto.randomUUID();\n\n // Allow multiple sessions per publicKey; only enforce max unique peers\n if (!this.sessions.has(publicKey) && this.sessions.size >= this.maxPeers) {\n this.sendError(socket, `Relay is at capacity (max ${this.maxPeers} peers)`);\n socket.close();\n return;\n }\n\n const agent: ConnectedAgent = {\n publicKey,\n socket,\n lastSeen: Date.now(),\n };\n\n if (!this.sessions.has(publicKey)) {\n this.sessions.set(publicKey, new Map());\n }\n this.sessions.get(publicKey)!.set(sessionId, agent);\n const isFirstSession = this.sessions.get(publicKey)!.size === 1;\n\n this.emit('agent-registered', publicKey);\n\n // Build peers list: one entry per connected publicKey + storage peers\n const peers: Array<{ publicKey: string }> = [];\n for (const [key] of this.sessions) {\n if (key === publicKey) continue;\n peers.push({ publicKey: key });\n }\n for (const storagePeer of this.storagePeers) {\n if (storagePeer !== publicKey && !this.sessions.has(storagePeer)) {\n peers.push({ publicKey: storagePeer });\n }\n }\n\n socket.send(JSON.stringify({\n type: 'registered',\n publicKey,\n sessionId,\n peers,\n }));\n\n // Notify other agents only when this is the first session for this peer\n if (isFirstSession) {\n this.broadcastPeerEvent('peer_online', publicKey);\n }\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 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 const envelopeFrom = envelope.from;\n if (envelopeFrom !== agentPublicKey) {\n this.sendError(socket, 'Envelope sender does not match registered public key');\n return;\n }\n\n // Strict p2p routing: envelope.to must include the relay transport recipient.\n if (!Array.isArray(envelope.to) || envelope.to.length === 0 || !envelope.to.includes(msg.to)) {\n this.sendError(socket, 'Envelope recipients do not include requested relay recipient');\n return;\n }\n\n if (this.isRateLimitedSender(agentPublicKey)) {\n return;\n }\n\n if (this.isDuplicateEnvelopeId(envelope.id)) {\n return;\n }\n\n // Update lastSeen for any session of sender\n const senderSessionMap = this.sessions.get(agentPublicKey);\n if (senderSessionMap) {\n for (const a of senderSessionMap.values()) {\n a.lastSeen = Date.now();\n }\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 all recipient sessions\n const recipientSessionMap = this.sessions.get(msg.to);\n const openRecipients = recipientSessionMap\n ? Array.from(recipientSessionMap.values()).filter(a => a.socket.readyState === WebSocket.OPEN)\n : [];\n if (openRecipients.length === 0) {\n // If recipient is a storage peer, queue the message\n if (this.store && this.storagePeers.includes(msg.to)) {\n this.store.save(msg.to, {\n from: agentPublicKey,\n envelope,\n });\n this.emit('message-relayed', agentPublicKey, msg.to, envelope);\n } else {\n this.sendError(socket, `Recipient not connected: ${msg.to}`, 'unknown_recipient');\n }\n return;\n }\n\n // Forward envelope to all sessions of the recipient\n try {\n const relayMessage = {\n type: 'message',\n from: agentPublicKey,\n envelope,\n };\n const messageStr = JSON.stringify(relayMessage);\n for (const recipient of openRecipients) {\n recipient.socket.send(messageStr);\n }\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 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 && sessionId) {\n const sessionMap = this.sessions.get(agentPublicKey);\n if (sessionMap) {\n sessionMap.delete(sessionId);\n if (sessionMap.size === 0) {\n this.sessions.delete(agentPublicKey);\n this.emit('agent-disconnected', agentPublicKey);\n this.emit('disconnection', 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);\n }\n }\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, code?: string): void {\n try {\n if (socket.readyState === WebSocket.OPEN) {\n const payload: { type: 'error'; message: string; code?: string } = { type: 'error', message };\n if (code) payload.code = code;\n socket.send(JSON.stringify(payload));\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 (all sessions except the one for publicKey)\n */\n private broadcastPeerEvent(eventType: 'peer_online' | 'peer_offline', publicKey: string): void {\n const message = {\n type: eventType,\n publicKey,\n };\n const messageStr = JSON.stringify(message);\n\n for (const [key, sessionMap] of this.sessions) {\n if (key === publicKey) continue;\n for (const agent of sessionMap.values()) {\n if (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 /**\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 // One entry per publicKey (first session for lastSeen/metadata)\n const peersList: ConnectedAgent[] = [];\n for (const [key, sessionMap] of this.sessions) {\n if (key === requesterPublicKey) continue;\n const first = sessionMap.values().next().value;\n if (first) peersList.push(first);\n }\n\n let peers = peersList;\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.metadata ? {\n version: p.metadata?.version,\n capabilities: p.metadata?.capabilities,\n } : undefined,\n lastSeen: p.lastSeen,\n })),\n totalPeers: this.sessions.size - (this.sessions.has(requesterPublicKey) ? 1 : 0),\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 [requesterPublicKey]\n );\n\n // Send response\n const relayMessage = {\n type: 'message',\n from: this.identity.publicKey,\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"],"mappings":";AAAA,SAAS,MAAM,QAAQ,2BAA2B;AAc3C,SAAS,kBAA2B;AACzC,QAAM,EAAE,WAAW,WAAW,IAAI,oBAAoB,SAAS;AAE/D,SAAO;AAAA,IACL,WAAW,UAAU,OAAO,EAAE,MAAM,QAAQ,QAAQ,MAAM,CAAC,EAAE,SAAS,KAAK;AAAA,IAC3E,YAAY,WAAW,OAAO,EAAE,MAAM,SAAS,QAAQ,MAAM,CAAC,EAAE,SAAS,KAAK;AAAA,EAChF;AACF;AAQO,SAAS,YAAY,SAA0B,eAA+B;AACnF,QAAM,gBAAgB,OAAO,YAAY,WAAW,OAAO,KAAK,OAAO,IAAI;AAC3E,QAAM,aAAa,OAAO,KAAK,eAAe,KAAK;AAEnD,QAAM,YAAY,KAAK,MAAM,eAAe;AAAA,IAC1C,KAAK;AAAA,IACL,QAAQ;AAAA,IACR,MAAM;AAAA,EACR,CAAC;AAED,SAAO,UAAU,SAAS,KAAK;AACjC;AASO,SAAS,gBACd,SACA,cACA,cACS;AACT,QAAM,gBAAgB,OAAO,YAAY,WAAW,OAAO,KAAK,OAAO,IAAI;AAC3E,QAAM,YAAY,OAAO,KAAK,cAAc,KAAK;AACjD,QAAM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EA,QAAI;AACF,aAAO,KAAK,KAAK,UAAU,YAAY,CAAC;AAAA,IAC1C,SAAS,KAAK;AACZ,WAAK,KAAK,SAAS,IAAI,MAAM,sCAAsC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE,CAAC;AAAA,IACxH;AAAA,EACF;AACF;","names":[]}
@@ -2,7 +2,7 @@ import {
2
2
  RelayServer,
3
3
  createEnvelope,
4
4
  verifyEnvelope
5
- } from "./chunk-MJGCRX6B.js";
5
+ } from "./chunk-EFX36SN3.js";
6
6
 
7
7
  // src/relay/message-buffer.ts
8
8
  var MAX_MESSAGES_PER_AGENT = 100;
@@ -172,7 +172,7 @@ function createRestRouter(relay, buffer, sessions, createEnv, verifyEnv, rateLim
172
172
  buffer.add(to, msg);
173
173
  });
174
174
  router.post("/v1/register", async (req, res) => {
175
- const { publicKey, privateKey, name, metadata } = req.body;
175
+ const { publicKey, privateKey, metadata } = req.body;
176
176
  if (!publicKey || typeof publicKey !== "string") {
177
177
  res.status(400).json({ error: "publicKey is required" });
178
178
  return;
@@ -194,12 +194,11 @@ function createRestRouter(relay, buffer, sessions, createEnv, verifyEnv, rateLim
194
194
  res.status(400).json({ error: "Key pair verification failed: " + verification.reason });
195
195
  return;
196
196
  }
197
- const { token, expiresAt } = createToken({ publicKey, name });
197
+ const { token, expiresAt } = createToken({ publicKey });
198
198
  pruneExpiredSessions(sessions, buffer);
199
199
  const session = {
200
200
  publicKey,
201
201
  privateKey,
202
- name,
203
202
  metadata,
204
203
  registeredAt: Date.now(),
205
204
  expiresAt,
@@ -212,7 +211,6 @@ function createRestRouter(relay, buffer, sessions, createEnv, verifyEnv, rateLim
212
211
  if (agent.publicKey !== publicKey) {
213
212
  peers.push({
214
213
  publicKey: agent.publicKey,
215
- name: agent.name,
216
214
  lastSeen: agent.lastSeen
217
215
  });
218
216
  }
@@ -221,7 +219,6 @@ function createRestRouter(relay, buffer, sessions, createEnv, verifyEnv, rateLim
221
219
  if (s.publicKey !== publicKey && !wsAgents.has(s.publicKey)) {
222
220
  peers.push({
223
221
  publicKey: s.publicKey,
224
- name: s.name,
225
222
  lastSeen: s.registeredAt
226
223
  });
227
224
  }
@@ -273,7 +270,6 @@ function createRestRouter(relay, buffer, sessions, createEnv, verifyEnv, rateLim
273
270
  const relayMsg = JSON.stringify({
274
271
  type: "message",
275
272
  from: senderPublicKey,
276
- name: session.name,
277
273
  envelope
278
274
  });
279
275
  ws.send(relayMsg);
@@ -300,7 +296,7 @@ function createRestRouter(relay, buffer, sessions, createEnv, verifyEnv, rateLim
300
296
  res.json({ ok: true, envelopeId: envelope.id });
301
297
  return;
302
298
  }
303
- res.status(404).json({ error: "Recipient not connected" });
299
+ res.status(404).json({ error: `Recipient not connected: ${to}` });
304
300
  }
305
301
  );
306
302
  router.get(
@@ -314,7 +310,6 @@ function createRestRouter(relay, buffer, sessions, createEnv, verifyEnv, rateLim
314
310
  if (agent.publicKey !== callerPublicKey) {
315
311
  peerList.push({
316
312
  publicKey: agent.publicKey,
317
- name: agent.name,
318
313
  lastSeen: agent.lastSeen,
319
314
  metadata: agent.metadata
320
315
  });
@@ -324,7 +319,6 @@ function createRestRouter(relay, buffer, sessions, createEnv, verifyEnv, rateLim
324
319
  if (s.publicKey !== callerPublicKey && !wsAgents.has(s.publicKey)) {
325
320
  peerList.push({
326
321
  publicKey: s.publicKey,
327
- name: s.name,
328
322
  lastSeen: s.registeredAt,
329
323
  metadata: s.metadata
330
324
  });
@@ -448,4 +442,4 @@ export {
448
442
  createRestRouter,
449
443
  runRelay
450
444
  };
451
- //# sourceMappingURL=chunk-OVDMZHTX.js.map
445
+ //# sourceMappingURL=chunk-RG3ZM57F.js.map