@rookdaemon/agora 0.4.5 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transport/peer-config.ts","../src/transport/http.ts","../src/transport/relay.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): 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 [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): 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 [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 [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 { EventEmitter } from 'node:events';\nimport WebSocket from 'ws';\nimport { verifyEnvelope, type Envelope } from '../message/envelope';\nimport type { RelayClientMessage, RelayServerMessage, RelayPeer } from './types';\n\n/**\n * Configuration for RelayClient\n */\nexport interface RelayClientConfig {\n /** WebSocket URL of the relay server */\n relayUrl: string;\n /** Agent's public key */\n publicKey: string;\n /** Agent's private key (for signing) */\n privateKey: string;\n /** Optional name for this agent */\n name?: string;\n /** Keepalive ping interval in milliseconds (default: 30000) */\n pingInterval?: number;\n /** Maximum reconnection delay in milliseconds (default: 60000) */\n maxReconnectDelay?: number;\n}\n\n/**\n * Events emitted by RelayClient\n */\nexport interface RelayClientEvents {\n /** Emitted when successfully connected and registered */\n 'connected': () => void;\n /** Emitted when disconnected from relay */\n 'disconnected': () => void;\n /** Emitted when a verified message is received */\n 'message': (envelope: Envelope, from: string, fromName?: string) => void;\n /** Emitted when a peer comes online */\n 'peer_online': (peer: RelayPeer) => void;\n /** Emitted when a peer goes offline */\n 'peer_offline': (peer: RelayPeer) => void;\n /** Emitted on errors */\n 'error': (error: Error) => void;\n}\n\n/**\n * Persistent WebSocket client for the Agora relay server.\n * Maintains a long-lived connection, handles reconnection, and routes messages.\n */\nexport class RelayClient extends EventEmitter {\n private ws: WebSocket | null = null;\n private config: RelayClientConfig;\n private reconnectAttempts = 0;\n private reconnectTimeout: NodeJS.Timeout | null = null;\n private pingInterval: NodeJS.Timeout | null = null;\n private isConnected = false;\n private isRegistered = false;\n private shouldReconnect = true;\n private onlinePeers = new Map<string, RelayPeer>();\n\n constructor(config: RelayClientConfig) {\n super();\n this.config = {\n pingInterval: 30000,\n maxReconnectDelay: 60000,\n ...config,\n };\n }\n\n /**\n * Connect to the relay server\n */\n async connect(): Promise<void> {\n if (this.ws && (this.ws.readyState === WebSocket.CONNECTING || this.ws.readyState === WebSocket.OPEN)) {\n return;\n }\n\n this.shouldReconnect = true;\n return this.doConnect();\n }\n\n /**\n * Disconnect from the relay server\n */\n disconnect(): void {\n this.shouldReconnect = false;\n this.cleanup();\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }\n\n /**\n * Check if currently connected and registered\n */\n connected(): boolean {\n return this.isConnected && this.isRegistered;\n }\n\n /**\n * Send a message to a specific peer\n */\n async send(to: string, envelope: Envelope): Promise<{ ok: boolean; error?: string }> {\n if (!this.connected()) {\n return { ok: false, error: 'Not connected to relay' };\n }\n\n const message: RelayClientMessage = {\n type: 'message',\n to,\n envelope,\n };\n\n try {\n this.ws!.send(JSON.stringify(message));\n return { ok: true };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n }\n\n /**\n * Get list of currently online peers\n */\n getOnlinePeers(): RelayPeer[] {\n return Array.from(this.onlinePeers.values());\n }\n\n /**\n * Check if a specific peer is online\n */\n isPeerOnline(publicKey: string): boolean {\n return this.onlinePeers.has(publicKey);\n }\n\n /**\n * Internal: Perform connection\n */\n private async doConnect(): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n this.ws = new WebSocket(this.config.relayUrl);\n let resolved = false;\n\n const resolveOnce = (callback: () => void): void => {\n if (!resolved) {\n resolved = true;\n callback();\n }\n };\n\n this.ws.on('open', () => {\n this.isConnected = true;\n this.reconnectAttempts = 0;\n this.startPingInterval();\n\n // Send registration message\n const registerMsg: RelayClientMessage = {\n type: 'register',\n publicKey: this.config.publicKey,\n name: this.config.name,\n };\n this.ws!.send(JSON.stringify(registerMsg));\n });\n\n this.ws.on('message', (data: WebSocket.Data) => {\n try {\n const msg = JSON.parse(data.toString()) as RelayServerMessage;\n this.handleMessage(msg);\n\n // Resolve promise on successful registration\n if (msg.type === 'registered' && !resolved) {\n resolveOnce(() => resolve());\n }\n } catch (err) {\n this.emit('error', new Error(`Failed to parse message: ${err instanceof Error ? err.message : String(err)}`));\n }\n });\n\n this.ws.on('close', () => {\n this.isConnected = false;\n this.isRegistered = false;\n this.cleanup();\n this.emit('disconnected');\n\n if (this.shouldReconnect) {\n this.scheduleReconnect();\n }\n\n if (!resolved) {\n resolveOnce(() => reject(new Error('Connection closed before registration')));\n }\n });\n\n this.ws.on('error', (err) => {\n this.emit('error', err);\n if (!resolved) {\n resolveOnce(() => reject(err));\n }\n });\n } catch (err) {\n reject(err);\n }\n });\n }\n\n /**\n * Handle incoming message from relay\n */\n private handleMessage(msg: RelayServerMessage): void {\n switch (msg.type) {\n case 'registered':\n this.isRegistered = true;\n if (msg.peers) {\n // Populate initial peer list\n for (const peer of msg.peers) {\n this.onlinePeers.set(peer.publicKey, peer);\n }\n }\n this.emit('connected');\n break;\n\n case 'message':\n if (msg.envelope && msg.from) {\n // Verify envelope signature\n const verification = verifyEnvelope(msg.envelope);\n if (!verification.valid) {\n this.emit('error', new Error(`Invalid envelope signature: ${verification.reason}`));\n return;\n }\n\n // Verify sender matches 'from' field\n 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\n this.emit('message', msg.envelope, msg.from, msg.name);\n }\n break;\n\n case 'peer_online':\n if (msg.publicKey) {\n const peer: RelayPeer = {\n publicKey: msg.publicKey,\n name: msg.name,\n };\n this.onlinePeers.set(msg.publicKey, peer);\n this.emit('peer_online', peer);\n }\n break;\n\n case 'peer_offline':\n if (msg.publicKey) {\n const peer = this.onlinePeers.get(msg.publicKey);\n if (peer) {\n this.onlinePeers.delete(msg.publicKey);\n this.emit('peer_offline', peer);\n }\n }\n break;\n\n case 'error':\n this.emit('error', new Error(`Relay error: ${msg.message || 'Unknown error'}`));\n break;\n\n case 'pong':\n // Keepalive response, no action needed\n break;\n\n default:\n // Unknown message type, ignore\n break;\n }\n }\n\n /**\n * Schedule reconnection with exponential backoff\n */\n private scheduleReconnect(): void {\n if (this.reconnectTimeout) {\n return;\n }\n\n // Exponential backoff: 1s, 2s, 4s, 8s, 16s, 32s, 60s (max)\n const delay = Math.min(\n 1000 * Math.pow(2, this.reconnectAttempts),\n this.config.maxReconnectDelay!\n );\n\n this.reconnectAttempts++;\n\n this.reconnectTimeout = setTimeout(() => {\n this.reconnectTimeout = null;\n if (this.shouldReconnect) {\n this.doConnect().catch((err) => {\n this.emit('error', err);\n });\n }\n }, delay);\n }\n\n /**\n * Start periodic ping messages\n */\n private startPingInterval(): void {\n this.stopPingInterval();\n this.pingInterval = setInterval(() => {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n const ping: RelayClientMessage = { type: 'ping' };\n this.ws.send(JSON.stringify(ping));\n }\n }, this.config.pingInterval!);\n }\n\n /**\n * Stop ping interval\n */\n private stopPingInterval(): void {\n if (this.pingInterval) {\n clearInterval(this.pingInterval);\n this.pingInterval = null;\n }\n }\n\n /**\n * Cleanup resources\n */\n private cleanup(): void {\n this.stopPingInterval();\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n this.onlinePeers.clear();\n }\n}\n","import { EventEmitter } from 'node:events';\nimport { createEnvelope, verifyEnvelope, type Envelope } from '../message/envelope';\nimport type { RelayClient } from '../relay/client';\nimport type { PeerListRequestPayload, PeerListResponsePayload, PeerReferralPayload } from '../message/types/peer-discovery';\n\n/**\n * Configuration for PeerDiscoveryService\n */\nexport interface PeerDiscoveryConfig {\n /** Agent's public key */\n publicKey: string;\n /** Agent's private key for signing */\n privateKey: string;\n /** RelayClient instance for communication */\n relayClient: RelayClient;\n /** Public key of the relay server (for sending peer list requests) */\n relayPublicKey?: string;\n}\n\n/**\n * Events emitted by PeerDiscoveryService\n */\nexport interface PeerDiscoveryEvents {\n /** Emitted when peers are discovered */\n 'peers-discovered': (peers: PeerListResponsePayload['peers']) => void;\n /** Emitted when a peer referral is received */\n 'peer-referral': (referral: PeerReferralPayload, from: string) => void;\n /** Emitted on errors */\n 'error': (error: Error) => void;\n}\n\n/**\n * Service for discovering peers on the Agora network\n */\nexport class PeerDiscoveryService extends EventEmitter {\n private config: PeerDiscoveryConfig;\n\n constructor(config: PeerDiscoveryConfig) {\n super();\n this.config = config;\n\n // Listen for peer list responses and referrals\n this.config.relayClient.on('message', (envelope: Envelope, from: string) => {\n if (envelope.type === 'peer_list_response') {\n this.handlePeerList(envelope as Envelope<PeerListResponsePayload>);\n } else if (envelope.type === 'peer_referral') {\n this.handleReferral(envelope as Envelope<PeerReferralPayload>, from);\n }\n });\n }\n\n /**\n * Request peer list from relay\n */\n async discoverViaRelay(filters?: PeerListRequestPayload['filters']): Promise<PeerListResponsePayload | null> {\n if (!this.config.relayPublicKey) {\n throw new Error('Relay public key not configured');\n }\n\n if (!this.config.relayClient.connected()) {\n throw new Error('Not connected to relay');\n }\n\n const payload: PeerListRequestPayload = filters ? { filters } : {};\n\n const envelope = createEnvelope(\n 'peer_list_request',\n this.config.publicKey,\n this.config.privateKey,\n payload,\n 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\ninterface PeerReferenceEntry {\n publicKey: string;\n name?: string;\n}\n\ntype 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\nfunction findById(id: string, directory?: PeerReferenceDirectory): PeerReferenceEntry | undefined {\n return toDirectoryEntries(directory).find((entry) => entry.publicKey === id);\n}\n\nfunction countByName(directory?: PeerReferenceDirectory): Map<string, number> {\n const counts = new Map<string, number>();\n for (const entry of toDirectoryEntries(directory)) {\n if (!entry.name) continue;\n counts.set(entry.name, (counts.get(entry.name) ?? 0) + 1);\n }\n return counts;\n}\n\n/**\n * Shorten a full peer ID for display/reference.\n * Priority:\n * - Unique configured name => \"name\"\n * - Duplicate 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 const duplicateCount = countByName(directory).get(entry.name) ?? 0;\n if (duplicateCount > 1) {\n return `${entry.name}...${suffix}`;\n }\n return entry.name;\n}\n\n/**\n * Expand a short peer reference to a full ID.\n * Supports: full ID, unique name, ...last8, and name...last8.\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 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 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 * Resolves the name to broadcast when connecting to a relay.\n * Priority order:\n * 1. CLI --name flag\n * 2. config.relay.name (if relay is an object with name property)\n * 3. config.identity.name\n * 4. undefined (no name broadcast)\n *\n * @param config - The Agora configuration (or compatible config with identity and optional relay)\n * @param cliName - Optional name from CLI --name flag\n * @returns The resolved name to broadcast, or undefined if none available\n */\nexport function resolveBroadcastName(\n config: { identity: { name?: string }; relay?: { name?: string } | string },\n cliName?: string\n): string | undefined {\n // Priority 1: CLI --name flag\n if (cliName) {\n return cliName;\n }\n\n // Priority 2: config.relay.name (if relay is an object with name property)\n if (config.relay) {\n if (typeof config.relay === 'object' && config.relay.name) {\n return config.relay.name;\n }\n }\n\n // Priority 3: config.identity.name\n if (config.identity.name) {\n return config.identity.name;\n }\n\n // Priority 4: No name available\n return undefined;\n}\n\n/**\n * Formats a display name with short ID postfix.\n * If name exists: \"name (...3f8c2247)\"\n * If no name: \"...3f8c2247\" (short ID only)\n *\n * @param name - Optional name to display (should not be a short ID)\n * @param publicKey - The public key to use for short ID\n * @returns Formatted display string\n */\nexport function formatDisplayName(name: string | undefined, publicKey: string): string {\n const shortId = shortKey(publicKey);\n // If name is undefined, empty, or is already a short ID, return only short ID\n if (!name || name.trim() === '' || name.startsWith('...')) {\n return shortId;\n }\n return `${name} (${shortId})`;\n}\n","/**\n * Core data structures for the Agora reputation layer.\n * Phase 1: Verification records, commit-reveal patterns, and trust scoring.\n */\n\n/**\n * A cryptographically signed verification of another agent's output or claim.\n * Core primitive for building computational reputation.\n */\nexport interface VerificationRecord {\n /** Content-addressed ID (hash of canonical JSON) */\n id: string;\n \n /** Public key of verifying agent */\n verifier: string;\n \n /** ID of message/output being verified */\n target: string;\n \n /** Capability domain (e.g., 'ocr', 'summarization', 'code_review') */\n domain: string;\n \n /** Verification verdict */\n verdict: 'correct' | 'incorrect' | 'disputed';\n \n /** Verifier's confidence in their check (0-1) */\n confidence: number;\n \n /** Optional link to independent verification data */\n evidence?: string;\n \n /** Unix timestamp (ms) */\n timestamp: number;\n \n /** Ed25519 signature over canonical JSON */\n signature: string;\n}\n\n/**\n * A commitment to a prediction before outcome is known.\n * Prevents post-hoc editing of predictions.\n */\nexport interface CommitRecord {\n /** Content-addressed ID */\n id: string;\n \n /** Public key of committing agent */\n agent: string;\n \n /** Domain of prediction */\n domain: string;\n \n /** SHA-256 hash of prediction string */\n commitment: string;\n \n /** Unix timestamp (ms) */\n timestamp: number;\n \n /** Expiry time (ms) - commitment invalid after this */\n expiry: number;\n \n /** Ed25519 signature */\n signature: string;\n}\n\n/**\n * Reveals the prediction and outcome after commitment expiry.\n * Enables verification of prediction accuracy.\n */\nexport interface RevealRecord {\n /** Content-addressed ID */\n id: string;\n \n /** Public key of revealing agent */\n agent: string;\n \n /** ID of original commit message */\n commitmentId: string;\n \n /** Original prediction (plaintext) */\n prediction: string;\n \n /** Observed outcome */\n outcome: string;\n \n /** Evidence for outcome (optional) */\n evidence?: string;\n \n /** Unix timestamp (ms) */\n timestamp: number;\n \n /** Ed25519 signature */\n signature: string;\n}\n\n/**\n * Computed reputation score for an agent in a specific domain.\n * Derived from verification history, not stored directly.\n */\nexport interface TrustScore {\n /** Public key of agent being scored */\n agent: string;\n \n /** Domain of reputation */\n domain: string;\n \n /** Computed score (0-1, where 1 = highest trust) */\n score: number;\n \n /** Number of verifications considered */\n verificationCount: number;\n \n /** Timestamp of most recent verification (ms) */\n lastVerified: number;\n \n /** Public keys of top verifiers (by weight) */\n topVerifiers: string[];\n}\n\n/**\n * Request for reputation data about a specific agent.\n */\nexport interface ReputationQuery {\n /** Public key of agent being queried */\n agent: string;\n \n /** Optional: filter by capability domain */\n domain?: string;\n \n /** Optional: only include verifications after this timestamp */\n after?: number;\n}\n\n/**\n * Response containing reputation data for a queried agent.\n */\nexport interface ReputationResponse {\n /** Public key of agent being reported on */\n agent: string;\n \n /** Domain filter (if requested) */\n domain?: string;\n \n /** Verification records matching the query */\n verifications: VerificationRecord[];\n \n /** Computed trust scores by domain */\n scores: Record<string, TrustScore>;\n}\n\n/**\n * Revocation of a previously issued verification.\n * Used when a verifier discovers their verification was incorrect.\n */\nexport interface RevocationRecord {\n /** Content-addressed ID of this revocation */\n id: string;\n \n /** Public key of agent revoking (must match original verifier) */\n verifier: string;\n \n /** ID of verification being revoked */\n verificationId: string;\n \n /** Reason for revocation */\n reason: string;\n \n /** Unix timestamp (ms) */\n timestamp: number;\n \n /** Ed25519 signature */\n signature: string;\n}\n\n/**\n * Validation result structure\n */\nexport interface ValidationResult {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Validate a verification record structure\n */\nexport function validateVerificationRecord(record: unknown): ValidationResult {\n const errors: string[] = [];\n \n if (typeof record !== 'object' || record === null) {\n return { valid: false, errors: ['Record must be an object'] };\n }\n \n const r = record as Record<string, unknown>;\n \n if (typeof r.id !== 'string' || r.id.length === 0) {\n errors.push('id must be a non-empty string');\n }\n \n if (typeof r.verifier !== 'string' || r.verifier.length === 0) {\n errors.push('verifier must be a non-empty string');\n }\n \n if (typeof r.target !== 'string' || r.target.length === 0) {\n errors.push('target must be a non-empty string');\n }\n \n if (typeof r.domain !== 'string' || r.domain.length === 0) {\n errors.push('domain must be a non-empty string');\n }\n \n if (!['correct', 'incorrect', 'disputed'].includes(r.verdict as string)) {\n errors.push('verdict must be one of: correct, incorrect, disputed');\n }\n \n if (typeof r.confidence !== 'number' || r.confidence < 0 || r.confidence > 1) {\n errors.push('confidence must be a number between 0 and 1');\n }\n \n if (r.evidence !== undefined && typeof r.evidence !== 'string') {\n errors.push('evidence must be a string if provided');\n }\n \n if (typeof r.timestamp !== 'number' || r.timestamp <= 0) {\n errors.push('timestamp must be a positive number');\n }\n \n if (typeof r.signature !== 'string' || r.signature.length === 0) {\n errors.push('signature must be a non-empty string');\n }\n \n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate a commit record structure\n */\nexport function validateCommitRecord(record: unknown): ValidationResult {\n const errors: string[] = [];\n \n if (typeof record !== 'object' || record === null) {\n return { valid: false, errors: ['Record must be an object'] };\n }\n \n const r = record as Record<string, unknown>;\n \n if (typeof r.id !== 'string' || r.id.length === 0) {\n errors.push('id must be a non-empty string');\n }\n \n if (typeof r.agent !== 'string' || r.agent.length === 0) {\n errors.push('agent must be a non-empty string');\n }\n \n if (typeof r.domain !== 'string' || r.domain.length === 0) {\n errors.push('domain must be a non-empty string');\n }\n \n if (typeof r.commitment !== 'string' || r.commitment.length !== 64) {\n errors.push('commitment must be a 64-character hex string (SHA-256 hash)');\n }\n \n if (typeof r.timestamp !== 'number' || r.timestamp <= 0) {\n errors.push('timestamp must be a positive number');\n }\n \n if (typeof r.expiry !== 'number' || r.expiry <= 0) {\n errors.push('expiry must be a positive number');\n }\n \n if (typeof r.expiry === 'number' && typeof r.timestamp === 'number' && r.expiry <= r.timestamp) {\n errors.push('expiry must be after timestamp');\n }\n \n if (typeof r.signature !== 'string' || r.signature.length === 0) {\n errors.push('signature must be a non-empty string');\n }\n \n return { valid: errors.length === 0, errors };\n}\n\n/**\n * Validate a reveal record structure\n */\nexport function validateRevealRecord(record: unknown): ValidationResult {\n const errors: string[] = [];\n \n if (typeof record !== 'object' || record === null) {\n return { valid: false, errors: ['Record must be an object'] };\n }\n \n const r = record as Record<string, unknown>;\n \n if (typeof r.id !== 'string' || r.id.length === 0) {\n errors.push('id must be a non-empty string');\n }\n \n if (typeof r.agent !== 'string' || r.agent.length === 0) {\n errors.push('agent must be a non-empty string');\n }\n \n if (typeof r.commitmentId !== 'string' || r.commitmentId.length === 0) {\n errors.push('commitmentId must be a non-empty string');\n }\n \n if (typeof r.prediction !== 'string' || r.prediction.length === 0) {\n errors.push('prediction must be a non-empty string');\n }\n \n if (typeof r.outcome !== 'string' || r.outcome.length === 0) {\n errors.push('outcome must be a non-empty string');\n }\n \n if (r.evidence !== undefined && typeof r.evidence !== 'string') {\n errors.push('evidence must be a string if provided');\n }\n \n if (typeof r.timestamp !== 'number' || r.timestamp <= 0) {\n errors.push('timestamp must be a positive number');\n }\n \n if (typeof r.signature !== 'string' || r.signature.length === 0) {\n errors.push('signature must be a non-empty string');\n }\n \n return { valid: errors.length === 0, errors };\n}\n","/**\n * Local reputation store using JSONL append-only log.\n * Stores verification records, commits, and reveals.\n */\n\nimport { promises as fs } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { VerificationRecord, CommitRecord, RevealRecord } from './types';\nimport { validateVerificationRecord, validateCommitRecord, validateRevealRecord } from './types';\n\n/**\n * Record type discriminator for JSONL storage\n */\ntype StoredRecord = \n | ({ type: 'verification' } & VerificationRecord)\n | ({ type: 'commit' } & CommitRecord)\n | ({ type: 'reveal' } & RevealRecord);\n\n/**\n * Reputation store with JSONL persistence\n */\nexport class ReputationStore {\n private filePath: string;\n private verifications: Map<string, VerificationRecord> = new Map();\n private commits: Map<string, CommitRecord> = new Map();\n private reveals: Map<string, RevealRecord> = new Map();\n private loaded = false;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n /**\n * Load records from JSONL file\n */\n async load(): Promise<void> {\n try {\n const content = await fs.readFile(this.filePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(line => line.length > 0);\n \n for (const line of lines) {\n try {\n const record = JSON.parse(line) as StoredRecord;\n \n switch (record.type) {\n case 'verification': {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...verification } = record;\n const validation = validateVerificationRecord(verification);\n if (validation.valid) {\n this.verifications.set(verification.id, verification as VerificationRecord);\n }\n break;\n }\n case 'commit': {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...commit } = record;\n const validation = validateCommitRecord(commit);\n if (validation.valid) {\n this.commits.set(commit.id, commit as CommitRecord);\n }\n break;\n }\n case 'reveal': {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...reveal } = record;\n const validation = validateRevealRecord(reveal);\n if (validation.valid) {\n this.reveals.set(reveal.id, reveal as RevealRecord);\n }\n break;\n }\n }\n } catch {\n // Skip invalid lines\n continue;\n }\n }\n \n this.loaded = true;\n } catch (error) {\n // File doesn't exist yet - that's okay for first run\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n this.loaded = true;\n return;\n }\n throw error;\n }\n }\n\n /**\n * Ensure the store is loaded\n */\n private async ensureLoaded(): Promise<void> {\n if (!this.loaded) {\n await this.load();\n }\n }\n\n /**\n * Append a record to the JSONL file\n */\n private async appendToFile(record: StoredRecord): Promise<void> {\n // Ensure directory exists\n await fs.mkdir(dirname(this.filePath), { recursive: true });\n \n // Append JSONL line\n const line = JSON.stringify(record) + '\\n';\n await fs.appendFile(this.filePath, line, 'utf-8');\n }\n\n /**\n * Add a verification record\n */\n async addVerification(verification: VerificationRecord): Promise<void> {\n await this.ensureLoaded();\n \n const validation = validateVerificationRecord(verification);\n if (!validation.valid) {\n throw new Error(`Invalid verification: ${validation.errors.join(', ')}`);\n }\n \n this.verifications.set(verification.id, verification);\n await this.appendToFile({ type: 'verification', ...verification });\n }\n\n /**\n * Add a commit record\n */\n async addCommit(commit: CommitRecord): Promise<void> {\n await this.ensureLoaded();\n \n const validation = validateCommitRecord(commit);\n if (!validation.valid) {\n throw new Error(`Invalid commit: ${validation.errors.join(', ')}`);\n }\n \n this.commits.set(commit.id, commit);\n await this.appendToFile({ type: 'commit', ...commit });\n }\n\n /**\n * Add a reveal record\n */\n async addReveal(reveal: RevealRecord): Promise<void> {\n await this.ensureLoaded();\n \n const validation = validateRevealRecord(reveal);\n if (!validation.valid) {\n throw new Error(`Invalid reveal: ${validation.errors.join(', ')}`);\n }\n \n this.reveals.set(reveal.id, reveal);\n await this.appendToFile({ type: 'reveal', ...reveal });\n }\n\n /**\n * Get all verifications\n */\n async getVerifications(): Promise<VerificationRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.verifications.values());\n }\n\n /**\n * Get verifications for a specific target\n */\n async getVerificationsByTarget(target: string): Promise<VerificationRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.verifications.values()).filter(v => v.target === target);\n }\n\n /**\n * Get verifications by domain\n */\n async getVerificationsByDomain(domain: string): Promise<VerificationRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.verifications.values()).filter(v => v.domain === domain);\n }\n\n /**\n * Get verifications for an agent (where they are the target of verification)\n * This requires looking up the target message to find the agent\n * For now, we'll return all verifications and let the caller filter\n */\n async getVerificationsByDomainForAgent(domain: string): Promise<VerificationRecord[]> {\n return this.getVerificationsByDomain(domain);\n }\n\n /**\n * Get all commits\n */\n async getCommits(): Promise<CommitRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.commits.values());\n }\n\n /**\n * Get commit by ID\n */\n async getCommit(id: string): Promise<CommitRecord | null> {\n await this.ensureLoaded();\n return this.commits.get(id) || null;\n }\n\n /**\n * Get commits by agent\n */\n async getCommitsByAgent(agent: string): Promise<CommitRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.commits.values()).filter(c => c.agent === agent);\n }\n\n /**\n * Get all reveals\n */\n async getReveals(): Promise<RevealRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.reveals.values());\n }\n\n /**\n * Get reveal by commitment ID\n */\n async getRevealByCommitment(commitmentId: string): Promise<RevealRecord | null> {\n await this.ensureLoaded();\n return Array.from(this.reveals.values()).find(r => r.commitmentId === commitmentId) || null;\n }\n\n /**\n * Get reveals by agent\n */\n async getRevealsByAgent(agent: string): Promise<RevealRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.reveals.values()).filter(r => r.agent === agent);\n }\n}\n","/**\n * Verification record creation and validation.\n * Core primitive for computational reputation.\n */\n\nimport { createEnvelope, verifyEnvelope } from '../message/envelope';\nimport type { VerificationRecord } from './types';\nimport { validateVerificationRecord } from './types';\n\n/**\n * Create a signed verification record\n * @param verifier - Public key of the verifying agent\n * @param privateKey - Private key for signing\n * @param target - ID of the message/output being verified\n * @param domain - Capability domain\n * @param verdict - Verification verdict\n * @param confidence - Verifier's confidence (0-1)\n * @param timestamp - Timestamp for the verification (ms)\n * @param evidence - Optional link to verification evidence\n * @returns Signed VerificationRecord\n */\nexport function createVerification(\n verifier: string,\n privateKey: string,\n target: string,\n domain: string,\n verdict: 'correct' | 'incorrect' | 'disputed',\n confidence: number,\n timestamp: number,\n evidence?: string\n): VerificationRecord {\n // Validate confidence range\n if (confidence < 0 || confidence > 1) {\n throw new Error('confidence must be between 0 and 1');\n }\n \n // Create the payload for signing\n const payload: Record<string, unknown> = {\n verifier,\n target,\n domain,\n verdict,\n confidence,\n timestamp,\n };\n \n if (evidence !== undefined) {\n payload.evidence = evidence;\n }\n \n // Create signed envelope with type 'verification'\n const envelope = createEnvelope('verification', verifier, privateKey, payload, timestamp, 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,SAAO,KAAK,MAAM,OAAO;AAC3B;AAOO,SAAS,eAAe,MAAc,QAA8B;AACzE,QAAM,UAAU,KAAK,UAAU,QAAQ,MAAM,CAAC;AAC9C,gBAAc,MAAM,SAAS,OAAO;AACtC;AAQO,SAAS,eAAe,MAA8B;AAC3D,MAAI,WAAW,IAAI,GAAG;AACpB,WAAO,eAAe,IAAI;AAAA,EAC5B;AAGA,QAAM,WAAW,gBAAgB;AACjC,QAAM,SAAyB;AAAA,IAC7B;AAAA,IACA,OAAO,CAAC;AAAA,EACV;AAEA,iBAAe,MAAM,MAAM;AAC3B,SAAO;AACT;;;ACrCA,eAAsB,WACpB,QACA,eACA,MACA,SACA,WAC0D;AAE1D,QAAM,OAAO,OAAO,MAAM,IAAI,aAAa;AAC3C,MAAI,CAAC,MAAM;AACT,WAAO,EAAE,IAAI,OAAO,QAAQ,GAAG,OAAO,eAAe;AAAA,EACvD;AAGA,MAAI,CAAC,KAAK,KAAK;AACb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RelayClient,
5
5
  ReputationStore,
6
+ compactInlineReferences,
6
7
  computeTrustScore,
7
8
  createCommit,
8
9
  createReveal,
9
10
  createVerification,
10
11
  decodeInboundEnvelope,
12
+ expand,
13
+ expandInlineReferences,
11
14
  getDefaultBootstrapRelay,
12
15
  initPeerConfig,
13
16
  loadPeerConfig,
@@ -16,12 +19,12 @@ import {
16
19
  sendToPeer,
17
20
  sendViaRelay,
18
21
  verifyReveal
19
- } from "./chunk-NXPATMD4.js";
22
+ } from "./chunk-N2KHVHQX.js";
20
23
  import {
21
24
  RelayServer,
22
25
  createEnvelope,
23
26
  verifyEnvelope
24
- } from "./chunk-IR2AIJ3K.js";
27
+ } from "./chunk-4TJRWJIB.js";
25
28
 
26
29
  // src/cli.ts
27
30
  import { parseArgs } from "util";
@@ -109,16 +112,6 @@ var PeerServer = class extends EventEmitter {
109
112
  return false;
110
113
  }
111
114
  }
112
- /**
113
- * Broadcast a message to all connected peers
114
- */
115
- broadcast(envelope) {
116
- for (const [publicKey, peer] of this.peers) {
117
- if (peer.socket.readyState === WebSocket.OPEN) {
118
- this.send(publicKey, envelope);
119
- }
120
- }
121
- }
122
115
  /**
123
116
  * Handle incoming connection
124
117
  */
@@ -128,7 +121,10 @@ var PeerServer = class extends EventEmitter {
128
121
  "announce",
129
122
  this.identity.publicKey,
130
123
  this.identity.privateKey,
131
- this.announcePayload
124
+ this.announcePayload,
125
+ Date.now(),
126
+ void 0,
127
+ [this.identity.publicKey]
132
128
  );
133
129
  socket.send(JSON.stringify(announceEnvelope));
134
130
  socket.on("message", (data) => {
@@ -140,7 +136,7 @@ var PeerServer = class extends EventEmitter {
140
136
  }
141
137
  if (!peerPublicKey) {
142
138
  if (envelope.type === "announce") {
143
- peerPublicKey = envelope.sender;
139
+ peerPublicKey = envelope.from;
144
140
  const payload = envelope.payload;
145
141
  const peer = {
146
142
  publicKey: peerPublicKey,
@@ -153,7 +149,7 @@ var PeerServer = class extends EventEmitter {
153
149
  }
154
150
  return;
155
151
  }
156
- if (envelope.sender !== peerPublicKey) {
152
+ if (envelope.from !== peerPublicKey) {
157
153
  return;
158
154
  }
159
155
  this.emit("message-received", envelope, peerPublicKey);
@@ -173,6 +169,34 @@ var PeerServer = class extends EventEmitter {
173
169
  };
174
170
 
175
171
  // src/cli.ts
172
+ function resolvePeerEntry(peers, identifier) {
173
+ const expanded = expand(identifier, peers);
174
+ if (expanded && peers[expanded]) {
175
+ return { key: expanded, peer: peers[expanded] };
176
+ }
177
+ const direct = peers[identifier];
178
+ if (direct) {
179
+ return { key: identifier, peer: direct };
180
+ }
181
+ for (const [key, peer] of Object.entries(peers)) {
182
+ if (peer.publicKey === identifier || peer.name === identifier) {
183
+ return { key, peer };
184
+ }
185
+ }
186
+ return void 0;
187
+ }
188
+ function compactPayloadTextReferences(payload, peers) {
189
+ if (!payload || typeof payload !== "object") {
190
+ return payload;
191
+ }
192
+ if ("text" in payload && typeof payload.text === "string") {
193
+ return {
194
+ ...payload,
195
+ text: compactInlineReferences(payload.text, peers)
196
+ };
197
+ }
198
+ return payload;
199
+ }
176
200
  function getConfigPath(options) {
177
201
  if (options.config) {
178
202
  return resolve(options.config);
@@ -278,14 +302,17 @@ function handlePeersAdd(args, options) {
278
302
  console.error("Error: Either (--url and --token) must be provided, or relay must be configured in config file.");
279
303
  process.exit(1);
280
304
  }
281
- config.peers[name] = {
305
+ const existingByPubKey = Object.entries(config.peers).find(([, peer]) => peer.publicKey === pubkey);
306
+ if (existingByPubKey && existingByPubKey[0] !== pubkey) {
307
+ delete config.peers[existingByPubKey[0]];
308
+ }
309
+ config.peers[pubkey] = {
282
310
  publicKey: pubkey,
283
311
  name
284
- // Set name to match the key for consistency
285
312
  };
286
313
  if (url && token) {
287
- config.peers[name].url = url;
288
- config.peers[name].token = token;
314
+ config.peers[pubkey].url = url;
315
+ config.peers[pubkey].token = token;
289
316
  }
290
317
  savePeerConfig(configPath, config);
291
318
  const outputData = {
@@ -317,22 +344,23 @@ function handlePeersRemove(args, options) {
317
344
  console.error("Error: Missing peer name. Usage: agora peers remove <name>");
318
345
  process.exit(1);
319
346
  }
320
- const name = args[0];
347
+ const peerRef = args[0];
321
348
  const configPath = getConfigPath(options);
322
349
  if (!existsSync(configPath)) {
323
350
  console.error("Error: Config file not found. Run `agora init` first.");
324
351
  process.exit(1);
325
352
  }
326
353
  const config = loadPeerConfig(configPath);
327
- if (!config.peers[name]) {
328
- console.error(`Error: Peer '${name}' not found.`);
354
+ const resolved = resolvePeerEntry(config.peers, peerRef);
355
+ if (!resolved) {
356
+ console.error(`Error: Peer '${peerRef}' not found.`);
329
357
  process.exit(1);
330
358
  }
331
- delete config.peers[name];
359
+ delete config.peers[resolved.key];
332
360
  savePeerConfig(configPath, config);
333
361
  output({
334
362
  status: "removed",
335
- name
363
+ name: peerRef
336
364
  }, options.pretty || false);
337
365
  }
338
366
  async function handlePeersDiscover(options) {
@@ -400,10 +428,9 @@ async function handlePeersDiscover(options) {
400
428
  for (const peer of peerList.peers) {
401
429
  const existing = Object.values(config.peers).find((p) => p.publicKey === peer.publicKey);
402
430
  if (!existing) {
403
- const peerName = peer.metadata?.name || `peer-${peer.publicKey.substring(0, 8)}`;
404
- config.peers[peerName] = {
431
+ config.peers[peer.publicKey] = {
405
432
  publicKey: peer.publicKey,
406
- name: peerName
433
+ name: peer.metadata?.name
407
434
  };
408
435
  savedCount++;
409
436
  }
@@ -450,18 +477,19 @@ async function handleSend(args, options) {
450
477
  console.error("Error: Missing peer name. Usage: agora send <name> <message> OR agora send <name> --type <type> --payload <json>");
451
478
  process.exit(1);
452
479
  }
453
- const name = args[0];
480
+ const peerRef = args[0];
454
481
  const configPath = getConfigPath(options);
455
482
  if (!existsSync(configPath)) {
456
483
  console.error("Error: Config file not found. Run `agora init` first.");
457
484
  process.exit(1);
458
485
  }
459
486
  const config = loadPeerConfig(configPath);
460
- if (!config.peers[name]) {
461
- console.error(`Error: Peer '${name}' not found.`);
487
+ const resolved = resolvePeerEntry(config.peers, peerRef);
488
+ if (!resolved) {
489
+ console.error(`Error: Peer '${peerRef}' not found.`);
462
490
  process.exit(1);
463
491
  }
464
- const peer = config.peers[name];
492
+ const peer = resolved.peer;
465
493
  let messageType;
466
494
  let messagePayload;
467
495
  if (options.type && options.payload) {
@@ -483,7 +511,7 @@ async function handleSend(args, options) {
483
511
  process.exit(1);
484
512
  }
485
513
  messageType = "publish";
486
- messagePayload = { text: args.slice(1).join(" ") };
514
+ messagePayload = { text: expandInlineReferences(args.slice(1).join(" "), config.peers) };
487
515
  }
488
516
  const isDirect = options.direct === true;
489
517
  const isRelayOnly = options["relay-only"] === true;
@@ -492,7 +520,7 @@ async function handleSend(args, options) {
492
520
  process.exit(1);
493
521
  }
494
522
  if (isDirect && !peer.url) {
495
- console.error(`Error: --direct requested but peer '${name}' has no URL configured.`);
523
+ console.error(`Error: --direct requested but peer '${peerRef}' has no URL configured.`);
496
524
  process.exit(1);
497
525
  }
498
526
  const shouldTryHttp = peer.url && !isRelayOnly;
@@ -516,7 +544,7 @@ async function handleSend(args, options) {
516
544
  if (result.ok) {
517
545
  output({
518
546
  status: "sent",
519
- peer: name,
547
+ peer: peerRef,
520
548
  type: messageType,
521
549
  transport: "http",
522
550
  httpStatus: result.status
@@ -526,7 +554,7 @@ async function handleSend(args, options) {
526
554
  if (isDirect) {
527
555
  output({
528
556
  status: "failed",
529
- peer: name,
557
+ peer: peerRef,
530
558
  type: messageType,
531
559
  transport: "http",
532
560
  httpStatus: result.status,
@@ -537,7 +565,7 @@ async function handleSend(args, options) {
537
565
  if (!hasRelay || !config.relay) {
538
566
  output({
539
567
  status: "failed",
540
- peer: name,
568
+ peer: peerRef,
541
569
  type: messageType,
542
570
  transport: "http",
543
571
  httpStatus: result.status,
@@ -561,14 +589,14 @@ async function handleSend(args, options) {
561
589
  if (result.ok) {
562
590
  output({
563
591
  status: "sent",
564
- peer: name,
592
+ peer: peerRef,
565
593
  type: messageType,
566
594
  transport: "relay"
567
595
  }, options.pretty || false);
568
596
  } else {
569
597
  output({
570
598
  status: "failed",
571
- peer: name,
599
+ peer: peerRef,
572
600
  type: messageType,
573
601
  transport: "relay",
574
602
  error: result.error
@@ -576,7 +604,7 @@ async function handleSend(args, options) {
576
604
  process.exit(1);
577
605
  }
578
606
  } else if (!shouldTryHttp) {
579
- console.error(`Error: Peer '${name}' unreachable. No HTTP endpoint and no relay configured.`);
607
+ console.error(`Error: Peer '${peerRef}' unreachable. No HTTP endpoint and no relay configured.`);
580
608
  process.exit(1);
581
609
  }
582
610
  } catch (e) {
@@ -610,9 +638,10 @@ function handleDecode(args, options) {
610
638
  if (result.ok) {
611
639
  output({
612
640
  status: "verified",
613
- sender: result.envelope.sender,
641
+ from: result.envelope.from,
642
+ to: result.envelope.to,
614
643
  type: result.envelope.type,
615
- payload: result.envelope.payload,
644
+ payload: compactPayloadTextReferences(result.envelope.payload, config.peers),
616
645
  id: result.envelope.id,
617
646
  timestamp: result.envelope.timestamp,
618
647
  inReplyTo: result.envelope.inReplyTo || null
@@ -642,124 +671,31 @@ function handleStatus(options) {
642
671
  }, options.pretty || false);
643
672
  }
644
673
  async function handleAnnounce(options) {
645
- const configPath = getConfigPath(options);
646
- if (!existsSync(configPath)) {
647
- console.error("Error: Config file not found. Run `agora init` first.");
648
- process.exit(1);
649
- }
650
- const config = loadPeerConfig(configPath);
651
- const peerCount = Object.keys(config.peers).length;
652
- if (peerCount === 0) {
653
- console.error("Error: No peers configured. Use `agora peers add` to add peers first.");
654
- process.exit(1);
655
- }
656
- const announcePayload = {
657
- capabilities: [],
658
- metadata: {
659
- name: options.name || "agora-node",
660
- version: options.version || "0.1.0"
661
- }
662
- };
663
- const results = [];
664
- for (const [name, peer] of Object.entries(config.peers)) {
665
- const hasHttpTransport = peer.url && peer.token;
666
- const hasRelay = config.relay;
667
- try {
668
- if (hasHttpTransport) {
669
- const peers = /* @__PURE__ */ new Map();
670
- peers.set(peer.publicKey, {
671
- url: peer.url,
672
- token: peer.token,
673
- publicKey: peer.publicKey
674
- });
675
- const transportConfig = {
676
- identity: config.identity,
677
- peers
678
- };
679
- const result = await sendToPeer(
680
- transportConfig,
681
- peer.publicKey,
682
- "announce",
683
- announcePayload
684
- );
685
- if (result.ok) {
686
- results.push({
687
- peer: name,
688
- status: "sent",
689
- transport: "http",
690
- httpStatus: result.status
691
- });
692
- } else {
693
- results.push({
694
- peer: name,
695
- status: "failed",
696
- transport: "http",
697
- httpStatus: result.status,
698
- error: result.error
699
- });
700
- }
701
- } else if (hasRelay && config.relay) {
702
- const relayUrl = typeof config.relay === "string" ? config.relay : config.relay.url;
703
- const relayConfig = {
704
- identity: config.identity,
705
- relayUrl
706
- };
707
- const result = await sendViaRelay(
708
- relayConfig,
709
- peer.publicKey,
710
- "announce",
711
- announcePayload
712
- );
713
- if (result.ok) {
714
- results.push({
715
- peer: name,
716
- status: "sent",
717
- transport: "relay"
718
- });
719
- } else {
720
- results.push({
721
- peer: name,
722
- status: "failed",
723
- transport: "relay",
724
- error: result.error
725
- });
726
- }
727
- } else {
728
- results.push({
729
- peer: name,
730
- status: "unreachable",
731
- error: "No HTTP endpoint and no relay configured"
732
- });
733
- }
734
- } catch (e) {
735
- results.push({
736
- peer: name,
737
- status: "error",
738
- error: e instanceof Error ? e.message : String(e)
739
- });
740
- }
741
- }
742
- output({ results }, options.pretty || false);
674
+ void options;
675
+ console.error("Error: `agora announce` is disabled. Agora now supports strict peer-to-peer only (no all/broadcast).");
676
+ console.error("Use: agora send <peer> --type announce --payload <json>");
677
+ process.exit(1);
743
678
  }
744
679
  async function handleDiagnose(args, options) {
745
680
  if (args.length < 1) {
746
681
  console.error("Error: Missing peer name. Usage: agora diagnose <name> [--checks <comma-separated-list>]");
747
682
  process.exit(1);
748
683
  }
749
- const name = args[0];
684
+ const peerRef = args[0];
750
685
  const configPath = getConfigPath(options);
751
686
  if (!existsSync(configPath)) {
752
687
  console.error("Error: Config file not found. Run `agora init` first.");
753
688
  process.exit(1);
754
689
  }
755
690
  const config = loadPeerConfig(configPath);
756
- if (!config.peers[name]) {
757
- console.error(`Error: Peer '${name}' not found.`);
691
+ const resolved = resolvePeerEntry(config.peers, peerRef);
692
+ if (!resolved) {
693
+ console.error(`Error: Peer '${peerRef}' not found.`);
758
694
  process.exit(1);
759
695
  }
760
- const peer = config.peers[name];
696
+ const peer = resolved.peer;
761
697
  if (!peer.url) {
762
- console.error(`Error: Peer '${name}' has no URL configured. Cannot diagnose.`);
698
+ console.error(`Error: Peer '${peerRef}' has no URL configured. Cannot diagnose.`);
763
699
  process.exit(1);
764
700
  }
765
701
  const checksParam = options.checks || "ping";
@@ -772,7 +708,7 @@ async function handleDiagnose(args, options) {
772
708
  }
773
709
  }
774
710
  const result = {
775
- peer: name,
711
+ peer: peerRef,
776
712
  status: "unknown",
777
713
  checks: {},
778
714
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -862,7 +798,8 @@ async function handleServe(options) {
862
798
  console.log(JSON.stringify({
863
799
  id: envelope.id,
864
800
  type: envelope.type,
865
- sender: envelope.sender,
801
+ from: envelope.from,
802
+ to: envelope.to,
866
803
  timestamp: envelope.timestamp,
867
804
  payload: envelope.payload
868
805
  }, null, 2));