@rookdaemon/agora 0.4.0 → 0.4.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.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/peer/server.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { parseArgs } from 'node:util';\nimport { existsSync, mkdirSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { homedir } from 'node:os';\nimport { loadPeerConfig, savePeerConfig, initPeerConfig } from './transport/peer-config';\nimport { sendToPeer, decodeInboundEnvelope, type PeerConfig } from './transport/http';\nimport { sendViaRelay } from './transport/relay';\nimport type { MessageType } from './message/envelope';\nimport type { AnnouncePayload } from './registry/messages';\nimport { PeerServer } from './peer/server';\nimport { RelayServer } from './relay/server';\nimport { RelayClient } from './relay/client';\nimport { PeerDiscoveryService } from './discovery/peer-discovery';\nimport { getDefaultBootstrapRelay } from './discovery/bootstrap';\nimport { resolveBroadcastName } from './utils';\nimport { ReputationStore } from './reputation/store';\nimport { createVerification } from './reputation/verification';\nimport { createCommit, createReveal, verifyReveal } from './reputation/commit-reveal';\nimport { computeTrustScore } from './reputation/scoring';\n\ninterface CliOptions {\n config?: string;\n pretty?: boolean;\n}\n\n/**\n * Get the config file path from CLI options, environment, or default.\n */\nfunction getConfigPath(options: CliOptions): string {\n if (options.config) {\n return resolve(options.config);\n }\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 * Ensure the config directory exists.\n */\nfunction ensureConfigDir(configPath: string): void {\n const dir = dirname(configPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n}\n\n/**\n * Output data as JSON or pretty format.\n */\nfunction output(data: unknown, pretty: boolean): void {\n if (pretty) {\n // Pretty output for humans\n if (typeof data === 'object' && data !== null) {\n for (const [key, value] of Object.entries(data)) {\n if (Array.isArray(value)) {\n console.log(`${key}:`);\n for (const item of value) {\n if (typeof item === 'object' && item !== null) {\n const entries = Object.entries(item);\n console.log(` - ${entries.map(([k, v]) => `${k}: ${v}`).join(', ')}`);\n } else {\n console.log(` - ${item}`);\n }\n }\n } else if (typeof value === 'object' && value !== null) {\n console.log(`${key}:`);\n for (const [k, v] of Object.entries(value)) {\n console.log(` ${k}: ${v}`);\n }\n } else {\n console.log(`${key}: ${value}`);\n }\n }\n } else {\n console.log(data);\n }\n } else {\n // JSON output for programmatic use\n console.log(JSON.stringify(data, null, 2));\n }\n}\n\n/**\n * Handle the `agora init` command.\n */\nfunction handleInit(options: CliOptions): void {\n const configPath = getConfigPath(options);\n ensureConfigDir(configPath);\n\n if (existsSync(configPath)) {\n const config = loadPeerConfig(configPath);\n output({ \n status: 'already_initialized',\n publicKey: config.identity.publicKey,\n configPath \n }, options.pretty || false);\n process.exit(0);\n }\n\n const config = initPeerConfig(configPath);\n output({ \n status: 'initialized',\n publicKey: config.identity.publicKey,\n configPath \n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora whoami` command.\n */\nfunction handleWhoami(options: CliOptions): void {\n const configPath = getConfigPath(options);\n \n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n output({ \n publicKey: config.identity.publicKey,\n configPath \n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora peers add` command.\n */\nfunction handlePeersAdd(args: string[], options: CliOptions & { url?: string; token?: string; pubkey?: string }): void {\n if (args.length < 1) {\n console.error('Error: Missing peer name. Usage: agora peers add <name> --pubkey <pubkey> [--url <url> --token <token>]');\n process.exit(1);\n }\n\n const name = args[0];\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const url = options.url;\n const token = options.token;\n const pubkey = options.pubkey;\n\n if (!pubkey) {\n console.error('Error: Missing required --pubkey option.');\n process.exit(1);\n }\n\n // Validate that if one of url/token is provided, both must be\n if ((url && !token) || (!url && token)) {\n console.error('Error: Both --url and --token must be provided together.');\n process.exit(1);\n }\n\n // Check if we have HTTP transport or relay\n const config = loadPeerConfig(configPath);\n const hasHttpConfig = url && token;\n const hasRelay = config.relay;\n\n if (!hasHttpConfig && !hasRelay) {\n console.error('Error: Either (--url and --token) must be provided, or relay must be configured in config file.');\n process.exit(1);\n }\n\n // Add the peer\n config.peers[name] = {\n publicKey: pubkey,\n name, // Set name to match the key for consistency\n };\n\n if (url && token) {\n config.peers[name].url = url;\n config.peers[name].token = token;\n }\n\n savePeerConfig(configPath, config);\n \n const outputData: Record<string, unknown> = { \n status: 'added',\n name,\n publicKey: pubkey\n };\n \n if (url) {\n outputData.url = url;\n }\n \n output(outputData, options.pretty || false);\n}\n\n/**\n * Handle the `agora peers list` command.\n */\nfunction handlePeersList(options: CliOptions): void {\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const peers = Object.entries(config.peers).map(([key, peer]) => ({\n name: peer.name || key,\n url: peer.url,\n publicKey: peer.publicKey,\n }));\n\n output({ peers }, options.pretty || false);\n}\n\n/**\n * Handle the `agora peers remove` command.\n */\nfunction handlePeersRemove(args: string[], options: CliOptions): void {\n if (args.length < 1) {\n console.error('Error: Missing peer name. Usage: agora peers remove <name>');\n process.exit(1);\n }\n\n const name = args[0];\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n if (!config.peers[name]) {\n console.error(`Error: Peer '${name}' not found.`);\n process.exit(1);\n }\n\n delete config.peers[name];\n savePeerConfig(configPath, config);\n output({ \n status: 'removed',\n name \n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora peers discover` command.\n */\nasync function handlePeersDiscover(\n options: CliOptions & { \n relay?: string; \n 'relay-pubkey'?: string;\n limit?: string;\n 'active-within'?: string;\n save?: boolean;\n }\n): Promise<void> {\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n // Determine relay configuration\n let relayUrl: string;\n let relayPublicKey: string | undefined;\n\n if (options.relay) {\n // Use custom relay from command line\n relayUrl = options.relay;\n relayPublicKey = options['relay-pubkey'];\n } else if (config.relay) {\n // Use relay from config\n relayUrl = typeof config.relay === 'string' ? config.relay : config.relay.url;\n // TODO: Add relayPublicKey to config schema in future\n relayPublicKey = undefined;\n } else {\n // Use default bootstrap relay\n const bootstrap = getDefaultBootstrapRelay();\n relayUrl = bootstrap.relayUrl;\n relayPublicKey = bootstrap.relayPublicKey;\n }\n\n // Parse filters\n const filters: { activeWithin?: number; limit?: number } = {};\n if (options['active-within']) {\n const ms = parseInt(options['active-within'], 10);\n if (isNaN(ms) || ms <= 0) {\n console.error('Error: --active-within must be a positive number (milliseconds)');\n process.exit(1);\n }\n filters.activeWithin = ms;\n }\n if (options.limit) {\n const limit = parseInt(options.limit, 10);\n if (isNaN(limit) || limit <= 0) {\n console.error('Error: --limit must be a positive number');\n process.exit(1);\n }\n filters.limit = limit;\n }\n\n // Resolve broadcast name\n const broadcastName = resolveBroadcastName(config, undefined);\n\n // Connect to relay\n const relayClient = new RelayClient({\n relayUrl,\n publicKey: config.identity.publicKey,\n privateKey: config.identity.privateKey,\n name: broadcastName,\n });\n\n try {\n // Connect\n await relayClient.connect();\n\n // Create discovery service\n const discoveryService = new PeerDiscoveryService({\n publicKey: config.identity.publicKey,\n privateKey: config.identity.privateKey,\n relayClient,\n relayPublicKey,\n });\n\n // Discover peers\n const peerList = await discoveryService.discoverViaRelay(Object.keys(filters).length > 0 ? filters : undefined);\n\n if (!peerList) {\n output({\n status: 'no_response',\n message: 'No response from relay',\n }, options.pretty || false);\n process.exit(1);\n }\n\n // Save to config if requested\n if (options.save) {\n let savedCount = 0;\n for (const peer of peerList.peers) {\n // Only save if not already in config\n const existing = Object.values(config.peers).find(p => p.publicKey === peer.publicKey);\n if (!existing) {\n const peerName = peer.metadata?.name || `peer-${peer.publicKey.substring(0, 8)}`;\n config.peers[peerName] = {\n publicKey: peer.publicKey,\n name: peerName,\n };\n savedCount++;\n }\n }\n if (savedCount > 0) {\n savePeerConfig(configPath, config);\n }\n\n output({\n status: 'discovered',\n totalPeers: peerList.totalPeers,\n peersReturned: peerList.peers.length,\n peersSaved: savedCount,\n relayPublicKey: peerList.relayPublicKey,\n peers: peerList.peers.map(p => ({\n publicKey: p.publicKey,\n name: p.metadata?.name,\n version: p.metadata?.version,\n lastSeen: p.lastSeen,\n })),\n }, options.pretty || false);\n } else {\n output({\n status: 'discovered',\n totalPeers: peerList.totalPeers,\n peersReturned: peerList.peers.length,\n relayPublicKey: peerList.relayPublicKey,\n peers: peerList.peers.map(p => ({\n publicKey: p.publicKey,\n name: p.metadata?.name,\n version: p.metadata?.version,\n lastSeen: p.lastSeen,\n })),\n }, options.pretty || false);\n }\n } catch (e) {\n console.error('Error discovering peers:', e instanceof Error ? e.message : String(e));\n process.exit(1);\n } finally {\n relayClient.disconnect();\n }\n}\n\n/**\n * Handle the `agora send` command.\n */\nasync function handleSend(args: string[], options: CliOptions & { type?: string; payload?: string }): Promise<void> {\n if (args.length < 1) {\n console.error('Error: Missing peer name. Usage: agora send <name> <message> OR agora send <name> --type <type> --payload <json>');\n process.exit(1);\n }\n\n const name = args[0];\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n if (!config.peers[name]) {\n console.error(`Error: Peer '${name}' not found.`);\n process.exit(1);\n }\n\n const peer = config.peers[name];\n\n let messageType: MessageType;\n let messagePayload: unknown;\n\n if (options.type && options.payload) {\n // Typed message - validate it's a valid MessageType\n const validTypes: MessageType[] = ['announce', 'discover', 'request', 'response', 'publish', 'subscribe', 'verify', 'ack', 'error'];\n if (!validTypes.includes(options.type as MessageType)) {\n console.error(`Error: Invalid message type '${options.type}'. Valid types: ${validTypes.join(', ')}`);\n process.exit(1);\n }\n messageType = options.type as MessageType;\n try {\n messagePayload = JSON.parse(options.payload);\n } catch {\n console.error('Error: Invalid JSON payload.');\n process.exit(1);\n }\n } else {\n // Text message - use 'publish' type with text payload\n if (args.length < 2) {\n console.error('Error: Missing message text. Usage: agora send <name> <message>');\n process.exit(1);\n }\n messageType = 'publish';\n messagePayload = { text: args.slice(1).join(' ') };\n }\n\n // Determine transport method: HTTP or relay\n const hasHttpTransport = peer.url && peer.token;\n const hasRelay = config.relay;\n\n // Send the message\n try {\n if (hasHttpTransport) {\n // Use HTTP transport (existing behavior)\n // Non-null assertion: we know url and token are strings here\n const transportConfig = {\n identity: config.identity,\n peers: new Map<string, PeerConfig>([[peer.publicKey, {\n url: peer.url!,\n token: peer.token!,\n publicKey: peer.publicKey,\n }]]),\n };\n\n const result = await sendToPeer(\n transportConfig,\n peer.publicKey,\n messageType,\n messagePayload\n );\n\n if (result.ok) {\n output({ \n status: 'sent',\n peer: name,\n type: messageType,\n transport: 'http',\n httpStatus: result.status\n }, options.pretty || false);\n } else {\n output({ \n status: 'failed',\n peer: name,\n type: messageType,\n transport: 'http',\n httpStatus: result.status,\n error: result.error\n }, options.pretty || false);\n process.exit(1);\n }\n } else if (hasRelay && config.relay) {\n // Use relay transport\n // Extract URL from relay (string or object)\n const relayUrl = typeof config.relay === 'string' ? config.relay : config.relay.url;\n const relayConfig = {\n identity: config.identity,\n relayUrl,\n };\n\n const result = await sendViaRelay(\n relayConfig,\n peer.publicKey,\n messageType,\n messagePayload\n );\n\n if (result.ok) {\n output({ \n status: 'sent',\n peer: name,\n type: messageType,\n transport: 'relay'\n }, options.pretty || false);\n } else {\n output({ \n status: 'failed',\n peer: name,\n type: messageType,\n transport: 'relay',\n error: result.error\n }, options.pretty || false);\n process.exit(1);\n }\n } else {\n // Neither HTTP nor relay available\n console.error(`Error: Peer '${name}' unreachable. No HTTP endpoint and no relay configured.`);\n process.exit(1);\n }\n } catch (e) {\n console.error('Error sending message:', e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n}\n\n/**\n * Handle the `agora decode` command.\n */\nfunction handleDecode(args: string[], options: CliOptions): void {\n if (args.length < 1) {\n console.error('Error: Missing message. Usage: agora decode <message>');\n process.exit(1);\n }\n\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const peers = new Map<string, PeerConfig>();\n for (const [, val] of Object.entries(config.peers)) {\n // Only add peers with HTTP config to the map for decoding\n if (val.url && val.token) {\n peers.set(val.publicKey, {\n url: val.url,\n token: val.token,\n publicKey: val.publicKey,\n });\n }\n }\n\n const message = args.join(' ');\n const result = decodeInboundEnvelope(message, peers);\n\n if (result.ok) {\n output({\n status: 'verified',\n sender: result.envelope.sender,\n type: result.envelope.type,\n payload: result.envelope.payload,\n id: result.envelope.id,\n timestamp: result.envelope.timestamp,\n inReplyTo: result.envelope.inReplyTo || null,\n }, options.pretty || false);\n } else {\n output({\n status: 'failed',\n reason: result.reason,\n }, options.pretty || false);\n process.exit(1);\n }\n}\n\n/**\n * Handle the `agora status` command.\n */\nfunction handleStatus(options: CliOptions): void {\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const peerCount = Object.keys(config.peers).length;\n\n output({\n identity: config.identity.publicKey,\n configPath,\n relay: config.relay || 'not configured',\n peerCount,\n peers: Object.keys(config.peers),\n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora announce` command.\n * Broadcasts an announce message to all configured peers.\n */\nasync function handleAnnounce(options: CliOptions & { name?: string; version?: string }): Promise<void> {\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const peerCount = Object.keys(config.peers).length;\n\n if (peerCount === 0) {\n console.error('Error: No peers configured. Use `agora peers add` to add peers first.');\n process.exit(1);\n }\n\n // Create announce payload\n const announcePayload: AnnouncePayload = {\n capabilities: [],\n metadata: {\n name: options.name || 'agora-node',\n version: options.version || '0.1.0',\n },\n };\n\n // Send announce to all peers\n const results: Array<{ peer: string; status: string; transport?: string; httpStatus?: number; error?: string }> = [];\n\n for (const [name, peer] of Object.entries(config.peers)) {\n const hasHttpTransport = peer.url && peer.token;\n const hasRelay = config.relay;\n\n try {\n if (hasHttpTransport) {\n // Use HTTP transport\n const peers = new Map<string, PeerConfig>();\n peers.set(peer.publicKey, {\n url: peer.url!,\n token: peer.token!,\n publicKey: peer.publicKey,\n });\n\n const transportConfig = {\n identity: config.identity,\n peers,\n };\n\n const result = await sendToPeer(\n transportConfig,\n peer.publicKey,\n 'announce',\n announcePayload\n );\n\n if (result.ok) {\n results.push({\n peer: name,\n status: 'sent',\n transport: 'http',\n httpStatus: result.status,\n });\n } else {\n results.push({\n peer: name,\n status: 'failed',\n transport: 'http',\n httpStatus: result.status,\n error: result.error,\n });\n }\n } else if (hasRelay && config.relay) {\n // Use relay transport\n // Extract URL from relay (string or object)\n const relayUrl = typeof config.relay === 'string' ? config.relay : config.relay.url;\n const relayConfig = {\n identity: config.identity,\n relayUrl,\n };\n\n const result = await sendViaRelay(\n relayConfig,\n peer.publicKey,\n 'announce',\n announcePayload\n );\n\n if (result.ok) {\n results.push({\n peer: name,\n status: 'sent',\n transport: 'relay',\n });\n } else {\n results.push({\n peer: name,\n status: 'failed',\n transport: 'relay',\n error: result.error,\n });\n }\n } else {\n results.push({\n peer: name,\n status: 'unreachable',\n error: 'No HTTP endpoint and no relay configured',\n });\n }\n } catch (e) {\n results.push({\n peer: name,\n status: 'error',\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n\n output({ results }, options.pretty || false);\n}\n\n/**\n * Handle the `agora diagnose` command.\n * Run diagnostic checks on a peer (ping, workspace, tools).\n */\nasync function handleDiagnose(args: string[], options: CliOptions & { checks?: string }): Promise<void> {\n if (args.length < 1) {\n console.error('Error: Missing peer name. Usage: agora diagnose <name> [--checks <comma-separated-list>]');\n process.exit(1);\n }\n\n const name = args[0];\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n if (!config.peers[name]) {\n console.error(`Error: Peer '${name}' not found.`);\n process.exit(1);\n }\n\n const peer = config.peers[name];\n\n if (!peer.url) {\n console.error(`Error: Peer '${name}' has no URL configured. Cannot diagnose.`);\n process.exit(1);\n }\n\n // Parse checks parameter\n const checksParam = options.checks || 'ping';\n const requestedChecks = checksParam.split(',').map(c => c.trim());\n \n // Validate check types\n const validChecks = ['ping', 'workspace', 'tools'];\n for (const check of requestedChecks) {\n if (!validChecks.includes(check)) {\n console.error(`Error: Invalid check type '${check}'. Valid checks: ${validChecks.join(', ')}`);\n process.exit(1);\n }\n }\n\n // Result structure\n interface CheckResult {\n ok: boolean;\n latency_ms?: number;\n error?: string;\n implemented?: boolean;\n [key: string]: unknown;\n }\n \n const result: {\n peer: string;\n status: string;\n checks: Record<string, CheckResult>;\n timestamp: string;\n } = {\n peer: name,\n status: 'unknown',\n checks: {},\n timestamp: new Date().toISOString(),\n };\n\n // Run ping check\n if (requestedChecks.includes('ping')) {\n const startTime = Date.now();\n try {\n // Add timeout to prevent hanging on unreachable peers\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 10000);\n \n const response = await fetch(peer.url, {\n method: 'GET',\n headers: peer.token ? { 'Authorization': `Bearer ${peer.token}` } : {},\n signal: controller.signal,\n });\n \n clearTimeout(timeout);\n const latency = Date.now() - startTime;\n \n if (response.ok || response.status === 404 || response.status === 405) {\n // 404 or 405 means the endpoint exists but GET isn't supported - that's OK for a ping\n result.checks.ping = { ok: true, latency_ms: latency };\n } else {\n result.checks.ping = { ok: false, latency_ms: latency, error: `HTTP ${response.status}` };\n }\n } catch (err) {\n const latency = Date.now() - startTime;\n result.checks.ping = { \n ok: false, \n latency_ms: latency,\n error: err instanceof Error ? err.message : String(err) \n };\n }\n }\n\n // Run workspace check\n if (requestedChecks.includes('workspace')) {\n // This is a placeholder - actual implementation would depend on peer's diagnostic protocol\n result.checks.workspace = { \n ok: false,\n implemented: false,\n error: 'Workspace check requires peer diagnostic protocol support' \n };\n }\n\n // Run tools check\n if (requestedChecks.includes('tools')) {\n // This is a placeholder - actual implementation would depend on peer's diagnostic protocol\n result.checks.tools = { \n ok: false,\n implemented: false,\n error: 'Tools check requires peer diagnostic protocol support' \n };\n }\n\n // Determine overall status - only consider implemented checks\n const implementedChecks = Object.values(result.checks).filter(\n check => check.implemented !== false\n );\n \n if (implementedChecks.length === 0) {\n result.status = 'unknown';\n } else {\n const allOk = implementedChecks.every(check => check.ok);\n const anyOk = implementedChecks.some(check => check.ok);\n result.status = allOk ? 'healthy' : anyOk ? 'degraded' : 'unhealthy';\n }\n\n output(result, options.pretty || false);\n}\n\n/**\n * Handle the `agora serve` command.\n * Starts a persistent WebSocket server for incoming peer connections.\n */\nasync function handleServe(options: CliOptions & { port?: string; name?: string }): Promise<void> {\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const port = parseInt(options.port || '9473', 10);\n \n // Validate port\n if (isNaN(port) || port < 1 || port > 65535) {\n console.error(`Error: Invalid port number '${options.port}'. Port must be between 1 and 65535.`);\n process.exit(1);\n }\n \n // Resolve server name using priority: CLI --name, config.relay.name, config.identity.name, default\n const serverName = resolveBroadcastName(config, options.name) || 'agora-server';\n\n // Create announce payload\n const announcePayload: AnnouncePayload = {\n capabilities: [],\n metadata: {\n name: serverName,\n version: '0.1.0',\n },\n };\n\n // Create and configure PeerServer\n const server = new PeerServer(config.identity, announcePayload);\n\n // Setup event listeners\n server.on('peer-connected', (publicKey, peer) => {\n const peerName = peer.metadata?.name || publicKey.substring(0, 16);\n console.log(`[${new Date().toISOString()}] Peer connected: ${peerName} (${publicKey})`);\n });\n\n server.on('peer-disconnected', (publicKey) => {\n console.log(`[${new Date().toISOString()}] Peer disconnected: ${publicKey}`);\n });\n\n server.on('message-received', (envelope, fromPublicKey) => {\n console.log(`[${new Date().toISOString()}] Message from ${fromPublicKey}:`);\n console.log(JSON.stringify({\n id: envelope.id,\n type: envelope.type,\n sender: envelope.sender,\n timestamp: envelope.timestamp,\n payload: envelope.payload,\n }, null, 2));\n });\n\n server.on('error', (error) => {\n console.error(`[${new Date().toISOString()}] Error:`, error.message);\n });\n\n // Start the server\n try {\n await server.start(port);\n console.log(`[${new Date().toISOString()}] Agora server started`);\n console.log(` Name: ${serverName}`);\n console.log(` Public Key: ${config.identity.publicKey}`);\n console.log(` WebSocket Port: ${port}`);\n console.log(` Listening for peer connections...`);\n console.log('');\n console.log('Press Ctrl+C to stop the server');\n\n // Keep the process alive\n process.on('SIGINT', async () => {\n console.log(`\\n[${new Date().toISOString()}] Shutting down server...`);\n await server.stop();\n console.log('Server stopped');\n process.exit(0);\n });\n\n process.on('SIGTERM', async () => {\n console.log(`\\n[${new Date().toISOString()}] Shutting down server...`);\n await server.stop();\n console.log('Server stopped');\n process.exit(0);\n });\n } catch (error) {\n console.error('Failed to start server:', error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n}\n\n/**\n * Handle the `agora relay` command.\n * Starts a WebSocket relay server for routing messages between agents.\n */\nasync function handleRelay(options: CliOptions & { port?: string }): Promise<void> {\n const port = parseInt(options.port || '9474', 10);\n \n // Validate port\n if (isNaN(port) || port < 1 || port > 65535) {\n console.error(`Error: Invalid port number '${options.port}'. Port must be between 1 and 65535.`);\n process.exit(1);\n }\n\n // Create and configure RelayServer\n const server = new RelayServer();\n\n // Setup event listeners\n server.on('agent-registered', (publicKey) => {\n console.log(`[${new Date().toISOString()}] Agent registered: ${publicKey}`);\n });\n\n server.on('agent-disconnected', (publicKey) => {\n console.log(`[${new Date().toISOString()}] Agent disconnected: ${publicKey}`);\n });\n\n server.on('message-relayed', (from, to, envelope) => {\n console.log(`[${new Date().toISOString()}] Message relayed: ${from.substring(0, 16)}... → ${to.substring(0, 16)}... (type: ${envelope.type})`);\n });\n\n server.on('error', (error) => {\n console.error(`[${new Date().toISOString()}] Error:`, error.message);\n });\n\n // Start the server\n try {\n await server.start(port);\n console.log(`[${new Date().toISOString()}] Agora relay server started`);\n console.log(` WebSocket Port: ${port}`);\n console.log(` Connected agents: 0`);\n console.log(` Listening for agent connections...`);\n console.log('');\n console.log('Press Ctrl+C to stop the relay');\n\n // Shared shutdown handler\n const shutdown = async (): Promise<void> => {\n console.log(`\\n[${new Date().toISOString()}] Shutting down relay...`);\n await server.stop();\n console.log('Relay stopped');\n process.exit(0);\n };\n\n // Keep the process alive\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n } catch (error) {\n console.error('Failed to start relay:', error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n}\n\n/**\n * Get the reputation store file path.\n */\nfunction getReputationStorePath(): string {\n return resolve(homedir(), '.local', 'share', 'agora', 'reputation.jsonl');\n}\n\n/**\n * Handle the `agora reputation verify` command.\n * Creates a verification record for another agent's output.\n */\nasync function handleReputationVerify(\n args: string[],\n options: CliOptions & {\n target?: string;\n domain?: string;\n verdict?: string;\n confidence?: string;\n evidence?: string;\n }\n): Promise<void> {\n if (!options.target || !options.domain || !options.verdict) {\n console.error('Error: Missing required options');\n console.error('Usage: agora reputation verify --target <id> --domain <domain> --verdict <correct|incorrect|disputed> --confidence <0-1> [--evidence <url>]');\n process.exit(1);\n }\n\n // Validate verdict\n if (!['correct', 'incorrect', 'disputed'].includes(options.verdict)) {\n console.error('Error: verdict must be one of: correct, incorrect, disputed');\n process.exit(1);\n }\n\n // Parse confidence\n const confidence = options.confidence ? parseFloat(options.confidence) : 1.0;\n if (isNaN(confidence) || confidence < 0 || confidence > 1) {\n console.error('Error: confidence must be a number between 0 and 1');\n process.exit(1);\n }\n\n // Load config\n const configPath = getConfigPath(options);\n if (!existsSync(configPath)) {\n console.error(`Error: Config file not found at ${configPath}. Run 'agora init' first.`);\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n // Create verification\n const verification = createVerification(\n config.identity.publicKey,\n config.identity.privateKey,\n options.target,\n options.domain,\n options.verdict as 'correct' | 'incorrect' | 'disputed',\n confidence,\n Date.now(),\n options.evidence\n );\n\n // Save to reputation store\n const storePath = getReputationStorePath();\n const store = new ReputationStore(storePath);\n await store.addVerification(verification);\n\n output({\n status: 'verification_created',\n id: verification.id,\n verifier: verification.verifier,\n target: verification.target,\n domain: verification.domain,\n verdict: verification.verdict,\n confidence: verification.confidence,\n timestamp: verification.timestamp,\n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora reputation commit` command.\n * Creates a commitment to a prediction before outcome is known.\n */\nasync function handleReputationCommit(\n args: string[],\n options: CliOptions & {\n domain?: string;\n prediction?: string;\n expiry?: string;\n }\n): Promise<void> {\n if (!options.domain || !options.prediction) {\n console.error('Error: Missing required options');\n console.error('Usage: agora reputation commit --domain <domain> --prediction <text> [--expiry <milliseconds>]');\n console.error('Example: agora reputation commit --domain weather_forecast --prediction \"It will rain tomorrow\" --expiry 86400000');\n process.exit(1);\n }\n\n // Parse expiry (default 24 hours)\n const expiryMs = options.expiry ? parseInt(options.expiry, 10) : 86400000;\n if (isNaN(expiryMs) || expiryMs <= 0) {\n console.error('Error: expiry must be a positive number (milliseconds)');\n process.exit(1);\n }\n\n // Load config\n const configPath = getConfigPath(options);\n if (!existsSync(configPath)) {\n console.error(`Error: Config file not found at ${configPath}. Run 'agora init' first.`);\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n // Create commit\n const commit = createCommit(\n config.identity.publicKey,\n config.identity.privateKey,\n options.domain,\n options.prediction,\n Date.now(),\n expiryMs\n );\n\n // Save to reputation store\n const storePath = getReputationStorePath();\n const store = new ReputationStore(storePath);\n await store.addCommit(commit);\n\n output({\n status: 'commitment_created',\n id: commit.id,\n agent: commit.agent,\n domain: commit.domain,\n commitment: commit.commitment,\n timestamp: commit.timestamp,\n expiry: commit.expiry,\n note: 'Store this ID to reveal the prediction after expiry',\n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora reputation reveal` command.\n * Reveals a prediction and outcome after commitment expiry.\n */\nasync function handleReputationReveal(\n args: string[],\n options: CliOptions & {\n 'commit-id'?: string;\n prediction?: string;\n outcome?: string;\n evidence?: string;\n }\n): Promise<void> {\n if (!options['commit-id'] || !options.prediction || !options.outcome) {\n console.error('Error: Missing required options');\n console.error('Usage: agora reputation reveal --commit-id <id> --prediction <text> --outcome <text> [--evidence <url>]');\n process.exit(1);\n }\n\n // Load config\n const configPath = getConfigPath(options);\n if (!existsSync(configPath)) {\n console.error(`Error: Config file not found at ${configPath}. Run 'agora init' first.`);\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n // Load commit from store\n const storePath = getReputationStorePath();\n const store = new ReputationStore(storePath);\n const commit = await store.getCommit(options['commit-id']);\n\n if (!commit) {\n console.error(`Error: Commitment ${options['commit-id']} not found in local store`);\n process.exit(1);\n }\n\n // Create reveal\n const reveal = createReveal(\n config.identity.publicKey,\n config.identity.privateKey,\n options['commit-id'],\n options.prediction,\n options.outcome,\n Date.now(),\n options.evidence\n );\n \n // Verify the reveal against the commit\n const verification = verifyReveal(commit, reveal);\n if (!verification.valid) {\n console.error(`Error: Reveal verification failed: ${verification.reason}`);\n process.exit(1);\n }\n\n // Save to reputation store\n await store.addReveal(reveal);\n\n output({\n status: 'prediction_revealed',\n id: reveal.id,\n agent: reveal.agent,\n commitmentId: reveal.commitmentId,\n prediction: reveal.prediction,\n outcome: reveal.outcome,\n timestamp: reveal.timestamp,\n verified: true,\n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora reputation query` command.\n * Queries reputation score for an agent in a domain.\n */\nasync function handleReputationQuery(\n args: string[],\n options: CliOptions & {\n agent?: string;\n domain?: string;\n }\n): Promise<void> {\n if (!options.domain) {\n console.error('Error: Missing required option: --domain');\n console.error('Usage: agora reputation query --domain <domain> [--agent <pubkey>]');\n console.error('If --agent is omitted, shows reputation for current agent');\n process.exit(1);\n }\n\n // Load config\n const configPath = getConfigPath(options);\n if (!existsSync(configPath)) {\n console.error(`Error: Config file not found at ${configPath}. Run 'agora init' first.`);\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const agent = options.agent || config.identity.publicKey;\n\n // Load reputation store\n const storePath = getReputationStorePath();\n const store = new ReputationStore(storePath);\n const verifications = await store.getVerificationsByDomain(options.domain);\n\n // Filter verifications for this agent\n const agentVerifications = verifications.filter(v => v.target === agent);\n\n // Compute trust score\n const score = computeTrustScore(agent, options.domain, agentVerifications, Date.now());\n\n output({\n agent: score.agent,\n domain: score.domain,\n score: score.score,\n verificationCount: score.verificationCount,\n lastVerified: score.lastVerified,\n lastVerifiedDate: score.lastVerified > 0 ? new Date(score.lastVerified).toISOString() : 'never',\n topVerifiers: score.topVerifiers,\n }, options.pretty || false);\n}\n\n/**\n * Parse CLI arguments and route to appropriate handler.\n */\nasync function main(): Promise<void> {\n const args = process.argv.slice(2);\n\n if (args.length === 0) {\n console.error('Usage: agora <command> [options]');\n console.error('Commands: init, whoami, status, peers, announce, send, decode, serve, diagnose, relay, reputation');\n console.error(' peers subcommands: add, list, remove, discover');\n console.error(' reputation subcommands: verify, commit, reveal, query');\n process.exit(1);\n }\n\n // Parse global options\n const parsed = parseArgs({\n args,\n options: {\n config: { type: 'string' },\n pretty: { type: 'boolean' },\n url: { type: 'string' },\n token: { type: 'string' },\n pubkey: { type: 'string' },\n type: { type: 'string' },\n payload: { type: 'string' },\n name: { type: 'string' },\n version: { type: 'string' },\n port: { type: 'string' },\n checks: { type: 'string' },\n relay: { type: 'string' },\n 'relay-pubkey': { type: 'string' },\n limit: { type: 'string' },\n 'active-within': { type: 'string' },\n save: { type: 'boolean' },\n // Reputation options\n target: { type: 'string' },\n domain: { type: 'string' },\n verdict: { type: 'string' },\n confidence: { type: 'string' },\n evidence: { type: 'string' },\n prediction: { type: 'string' },\n expiry: { type: 'string' },\n 'commit-id': { type: 'string' },\n outcome: { type: 'string' },\n agent: { type: 'string' },\n },\n strict: false,\n allowPositionals: true,\n });\n\n const command = parsed.positionals[0];\n const subcommand = parsed.positionals[1];\n const remainingArgs = parsed.positionals.slice(2);\n\n const options: CliOptions & { \n type?: string; \n payload?: string; \n url?: string; \n token?: string; \n pubkey?: string; \n name?: string; \n version?: string; \n port?: string; \n checks?: string;\n relay?: string;\n 'relay-pubkey'?: string;\n limit?: string;\n 'active-within'?: string;\n save?: boolean;\n // Reputation options\n target?: string;\n domain?: string;\n verdict?: string;\n confidence?: string;\n evidence?: string;\n prediction?: string;\n outcome?: string;\n expiry?: string;\n 'commit-id'?: string;\n agent?: string;\n } = {\n config: typeof parsed.values.config === 'string' ? parsed.values.config : undefined,\n pretty: typeof parsed.values.pretty === 'boolean' ? parsed.values.pretty : undefined,\n type: typeof parsed.values.type === 'string' ? parsed.values.type : undefined,\n payload: typeof parsed.values.payload === 'string' ? parsed.values.payload : undefined,\n url: typeof parsed.values.url === 'string' ? parsed.values.url : undefined,\n token: typeof parsed.values.token === 'string' ? parsed.values.token : undefined,\n pubkey: typeof parsed.values.pubkey === 'string' ? parsed.values.pubkey : undefined,\n name: typeof parsed.values.name === 'string' ? parsed.values.name : undefined,\n version: typeof parsed.values.version === 'string' ? parsed.values.version : undefined,\n port: typeof parsed.values.port === 'string' ? parsed.values.port : undefined,\n checks: typeof parsed.values.checks === 'string' ? parsed.values.checks : undefined,\n relay: typeof parsed.values.relay === 'string' ? parsed.values.relay : undefined,\n 'relay-pubkey': typeof parsed.values['relay-pubkey'] === 'string' ? parsed.values['relay-pubkey'] : undefined,\n limit: typeof parsed.values.limit === 'string' ? parsed.values.limit : undefined,\n 'active-within': typeof parsed.values['active-within'] === 'string' ? parsed.values['active-within'] : undefined,\n save: typeof parsed.values.save === 'boolean' ? parsed.values.save : undefined,\n // Reputation options\n target: typeof parsed.values.target === 'string' ? parsed.values.target : undefined,\n domain: typeof parsed.values.domain === 'string' ? parsed.values.domain : undefined,\n verdict: typeof parsed.values.verdict === 'string' ? parsed.values.verdict : undefined,\n confidence: typeof parsed.values.confidence === 'string' ? parsed.values.confidence : undefined,\n evidence: typeof parsed.values.evidence === 'string' ? parsed.values.evidence : undefined,\n prediction: typeof parsed.values.prediction === 'string' ? parsed.values.prediction : undefined,\n expiry: typeof parsed.values.expiry === 'string' ? parsed.values.expiry : undefined,\n 'commit-id': typeof parsed.values['commit-id'] === 'string' ? parsed.values['commit-id'] : undefined,\n outcome: typeof parsed.values.outcome === 'string' ? parsed.values.outcome : undefined,\n agent: typeof parsed.values.agent === 'string' ? parsed.values.agent : undefined,\n };\n\n try {\n switch (command) {\n case 'init':\n handleInit(options);\n break;\n case 'whoami':\n handleWhoami(options);\n break;\n case 'status':\n handleStatus(options);\n break;\n case 'announce':\n await handleAnnounce(options);\n break;\n case 'diagnose':\n await handleDiagnose([subcommand, ...remainingArgs].filter(Boolean), options);\n break;\n case 'peers':\n switch (subcommand) {\n case 'add':\n handlePeersAdd(remainingArgs, options);\n break;\n case 'list':\n case undefined:\n // Allow 'agora peers' to work like 'agora peers list'\n handlePeersList(options);\n break;\n case 'remove':\n handlePeersRemove(remainingArgs, options);\n break;\n case 'discover':\n await handlePeersDiscover(options);\n break;\n default:\n console.error('Error: Unknown peers subcommand. Use: add, list, remove, discover');\n process.exit(1);\n }\n break;\n case 'send':\n await handleSend([subcommand, ...remainingArgs], options);\n break;\n case 'decode':\n handleDecode([subcommand, ...remainingArgs].filter(Boolean), options);\n break;\n case 'serve':\n await handleServe(options);\n break;\n case 'relay':\n await handleRelay(options);\n break;\n case 'reputation':\n switch (subcommand) {\n case 'verify':\n await handleReputationVerify(remainingArgs, options);\n break;\n case 'commit':\n await handleReputationCommit(remainingArgs, options);\n break;\n case 'reveal':\n await handleReputationReveal(remainingArgs, options);\n break;\n case 'query':\n await handleReputationQuery(remainingArgs, options);\n break;\n default:\n console.error('Error: Unknown reputation subcommand. Use: verify, commit, reveal, query');\n process.exit(1);\n }\n break;\n default:\n console.error(`Error: Unknown command '${command}'. Use: init, whoami, status, peers, announce, send, decode, serve, diagnose, relay, reputation`);\n process.exit(1);\n }\n } catch (e) {\n console.error('Error:', e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n}\n\nmain().catch((e) => {\n console.error('Fatal error:', e instanceof Error ? e.message : String(e));\n process.exit(1);\n});\n","import { EventEmitter } from 'node:events';\nimport { WebSocketServer, WebSocket } from 'ws';\nimport type { KeyPair } from '../identity/keypair';\nimport type { Envelope } from '../message/envelope';\nimport { createEnvelope, verifyEnvelope } from '../message/envelope';\nimport type { AnnouncePayload } from '../registry/messages';\n\n/**\n * Represents a connected peer\n */\nexport interface ConnectedPeer {\n /** Peer's public key */\n publicKey: string;\n /** WebSocket connection */\n socket: WebSocket;\n /** Whether the peer has been announced */\n announced: boolean;\n /** Peer metadata from announce message */\n metadata?: {\n name?: string;\n version?: string;\n };\n}\n\n/**\n * Events emitted by PeerServer\n */\nexport interface PeerServerEvents {\n 'peer-connected': (publicKey: string, peer: ConnectedPeer) => void;\n 'peer-disconnected': (publicKey: string) => void;\n 'message-received': (envelope: Envelope, fromPublicKey: string) => void;\n 'error': (error: Error) => void;\n}\n\n/**\n * WebSocket server for accepting peer connections\n */\nexport class PeerServer extends EventEmitter {\n private wss: WebSocketServer | null = null;\n private peers = new Map<string, ConnectedPeer>();\n private identity: KeyPair;\n private announcePayload: AnnouncePayload;\n\n constructor(identity: KeyPair, announcePayload: AnnouncePayload) {\n super();\n this.identity = identity;\n this.announcePayload = announcePayload;\n }\n\n /**\n * Start the WebSocket server\n */\n start(port: number): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n this.wss = new WebSocketServer({ port });\n\n this.wss.on('error', (error) => {\n this.emit('error', error);\n reject(error);\n });\n\n this.wss.on('listening', () => {\n resolve();\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 WebSocket 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 peer connections\n for (const peer of this.peers.values()) {\n peer.socket.close();\n }\n this.peers.clear();\n\n this.wss.close((err) => {\n if (err) {\n reject(err);\n } else {\n this.wss = null;\n resolve();\n }\n });\n });\n }\n\n /**\n * Get all connected peers\n */\n getPeers(): Map<string, ConnectedPeer> {\n return new Map(this.peers);\n }\n\n /**\n * Send a message to a specific peer\n */\n send(publicKey: string, envelope: Envelope): boolean {\n const peer = this.peers.get(publicKey);\n if (!peer || peer.socket.readyState !== WebSocket.OPEN) {\n return false;\n }\n\n try {\n peer.socket.send(JSON.stringify(envelope));\n return true;\n } catch (error) {\n this.emit('error', error as Error);\n return false;\n }\n }\n\n /**\n * Broadcast a message to all connected peers\n */\n broadcast(envelope: Envelope): void {\n for (const [publicKey, peer] of this.peers) {\n if (peer.socket.readyState === WebSocket.OPEN) {\n this.send(publicKey, envelope);\n }\n }\n }\n\n /**\n * Handle incoming connection\n */\n private handleConnection(socket: WebSocket): void {\n let peerPublicKey: string | null = null;\n\n // Send announce message immediately\n const announceEnvelope = createEnvelope(\n 'announce',\n this.identity.publicKey,\n this.identity.privateKey,\n this.announcePayload\n );\n socket.send(JSON.stringify(announceEnvelope));\n\n socket.on('message', (data: Buffer) => {\n try {\n const envelope = JSON.parse(data.toString()) as Envelope;\n\n // Verify envelope signature\n const verification = verifyEnvelope(envelope);\n if (!verification.valid) {\n // Drop invalid messages\n return;\n }\n\n // First message should be an announce\n if (!peerPublicKey) {\n if (envelope.type === 'announce') {\n peerPublicKey = envelope.sender;\n const payload = envelope.payload as AnnouncePayload;\n \n const peer: ConnectedPeer = {\n publicKey: peerPublicKey,\n socket,\n announced: true,\n metadata: payload.metadata,\n };\n\n this.peers.set(peerPublicKey, peer);\n this.emit('peer-connected', peerPublicKey, peer);\n }\n return;\n }\n\n // Verify the message is from the announced peer\n if (envelope.sender !== peerPublicKey) {\n // Drop messages from wrong sender\n return;\n }\n\n // Emit message-received event\n this.emit('message-received', envelope, peerPublicKey);\n } catch {\n // Invalid JSON or other parsing errors - drop the message\n }\n });\n\n socket.on('close', () => {\n if (peerPublicKey) {\n this.peers.delete(peerPublicKey);\n this.emit('peer-disconnected', peerPublicKey);\n }\n });\n\n socket.on('error', (error) => {\n this.emit('error', error);\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,iBAAiB;AAC1B,SAAS,YAAY,iBAAiB;AACtC,SAAS,SAAS,eAAe;AACjC,SAAS,eAAe;;;ACLxB,SAAS,oBAAoB;AAC7B,SAAS,iBAAiB,iBAAiB;AAoCpC,IAAM,aAAN,cAAyB,aAAa;AAAA,EACnC,MAA8B;AAAA,EAC9B,QAAQ,oBAAI,IAA2B;AAAA,EACvC;AAAA,EACA;AAAA,EAER,YAAY,UAAmB,iBAAkC;AAC/D,UAAM;AACN,SAAK,WAAW;AAChB,SAAK,kBAAkB;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,MAA6B;AACjC,WAAO,IAAI,QAAQ,CAACA,UAAS,WAAW;AACtC,UAAI;AACF,aAAK,MAAM,IAAI,gBAAgB,EAAE,KAAK,CAAC;AAEvC,aAAK,IAAI,GAAG,SAAS,CAAC,UAAU;AAC9B,eAAK,KAAK,SAAS,KAAK;AACxB,iBAAO,KAAK;AAAA,QACd,CAAC;AAED,aAAK,IAAI,GAAG,aAAa,MAAM;AAC7B,UAAAA,SAAQ;AAAA,QACV,CAAC;AAED,aAAK,IAAI,GAAG,cAAc,CAAC,WAAsB;AAC/C,eAAK,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BAAuB,eAAe,OAAO;AACnD;AAAA,UACF,KAAK;AACH,kBAAM,uBAAuB,eAAe,OAAO;AACnD;AAAA,UACF,KAAK;AACH,kBAAM,sBAAsB,eAAe,OAAO;AAClD;AAAA,UACF;AACE,oBAAQ,MAAM,0EAA0E;AACxF,oBAAQ,KAAK,CAAC;AAAA,QAClB;AACA;AAAA,MACF;AACE,gBAAQ,MAAM,2BAA2B,OAAO,iGAAiG;AACjJ,gBAAQ,KAAK,CAAC;AAAA,IAClB;AAAA,EACF,SAAS,GAAG;AACV,YAAQ,MAAM,UAAU,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;AAClE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,MAAM;AAClB,UAAQ,MAAM,gBAAgB,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;AACxE,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["resolve","config"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/peer/server.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { parseArgs } from 'node:util';\nimport { existsSync, mkdirSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { homedir } from 'node:os';\nimport { loadPeerConfig, savePeerConfig, initPeerConfig } from './transport/peer-config';\nimport { sendToPeer, decodeInboundEnvelope, type PeerConfig } from './transport/http';\nimport { sendViaRelay } from './transport/relay';\nimport type { MessageType } from './message/envelope';\nimport type { AnnouncePayload } from './registry/messages';\nimport { PeerServer } from './peer/server';\nimport { RelayServer } from './relay/server';\nimport { RelayClient } from './relay/client';\nimport { PeerDiscoveryService } from './discovery/peer-discovery';\nimport { getDefaultBootstrapRelay } from './discovery/bootstrap';\nimport { resolveBroadcastName } from './utils';\nimport { ReputationStore } from './reputation/store';\nimport { createVerification } from './reputation/verification';\nimport { createCommit, createReveal, verifyReveal } from './reputation/commit-reveal';\nimport { computeTrustScore } from './reputation/scoring';\n\ninterface CliOptions {\n config?: string;\n pretty?: boolean;\n}\n\n/**\n * Get the config file path from CLI options, environment, or default.\n */\nfunction getConfigPath(options: CliOptions): string {\n if (options.config) {\n return resolve(options.config);\n }\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 * Ensure the config directory exists.\n */\nfunction ensureConfigDir(configPath: string): void {\n const dir = dirname(configPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n}\n\n/**\n * Output data as JSON or pretty format.\n */\nfunction output(data: unknown, pretty: boolean): void {\n if (pretty) {\n // Pretty output for humans\n if (typeof data === 'object' && data !== null) {\n for (const [key, value] of Object.entries(data)) {\n if (Array.isArray(value)) {\n console.log(`${key}:`);\n for (const item of value) {\n if (typeof item === 'object' && item !== null) {\n const entries = Object.entries(item);\n console.log(` - ${entries.map(([k, v]) => `${k}: ${v}`).join(', ')}`);\n } else {\n console.log(` - ${item}`);\n }\n }\n } else if (typeof value === 'object' && value !== null) {\n console.log(`${key}:`);\n for (const [k, v] of Object.entries(value)) {\n console.log(` ${k}: ${v}`);\n }\n } else {\n console.log(`${key}: ${value}`);\n }\n }\n } else {\n console.log(data);\n }\n } else {\n // JSON output for programmatic use\n console.log(JSON.stringify(data, null, 2));\n }\n}\n\n/**\n * Handle the `agora init` command.\n */\nfunction handleInit(options: CliOptions): void {\n const configPath = getConfigPath(options);\n ensureConfigDir(configPath);\n\n if (existsSync(configPath)) {\n const config = loadPeerConfig(configPath);\n output({ \n status: 'already_initialized',\n publicKey: config.identity.publicKey,\n configPath \n }, options.pretty || false);\n process.exit(0);\n }\n\n const config = initPeerConfig(configPath);\n output({ \n status: 'initialized',\n publicKey: config.identity.publicKey,\n configPath \n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora whoami` command.\n */\nfunction handleWhoami(options: CliOptions): void {\n const configPath = getConfigPath(options);\n \n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n output({ \n publicKey: config.identity.publicKey,\n configPath \n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora peers add` command.\n */\nfunction handlePeersAdd(args: string[], options: CliOptions & { url?: string; token?: string; pubkey?: string }): void {\n if (args.length < 1) {\n console.error('Error: Missing peer name. Usage: agora peers add <name> --pubkey <pubkey> [--url <url> --token <token>]');\n process.exit(1);\n }\n\n const name = args[0];\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const url = options.url;\n const token = options.token;\n const pubkey = options.pubkey;\n\n if (!pubkey) {\n console.error('Error: Missing required --pubkey option.');\n process.exit(1);\n }\n\n // Validate that if one of url/token is provided, both must be\n if ((url && !token) || (!url && token)) {\n console.error('Error: Both --url and --token must be provided together.');\n process.exit(1);\n }\n\n // Check if we have HTTP transport or relay\n const config = loadPeerConfig(configPath);\n const hasHttpConfig = url && token;\n const hasRelay = config.relay;\n\n if (!hasHttpConfig && !hasRelay) {\n console.error('Error: Either (--url and --token) must be provided, or relay must be configured in config file.');\n process.exit(1);\n }\n\n // Add the peer\n config.peers[name] = {\n publicKey: pubkey,\n name, // Set name to match the key for consistency\n };\n\n if (url && token) {\n config.peers[name].url = url;\n config.peers[name].token = token;\n }\n\n savePeerConfig(configPath, config);\n \n const outputData: Record<string, unknown> = { \n status: 'added',\n name,\n publicKey: pubkey\n };\n \n if (url) {\n outputData.url = url;\n }\n \n output(outputData, options.pretty || false);\n}\n\n/**\n * Handle the `agora peers list` command.\n */\nfunction handlePeersList(options: CliOptions): void {\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const peers = Object.entries(config.peers).map(([key, peer]) => ({\n name: peer.name || key,\n url: peer.url,\n publicKey: peer.publicKey,\n }));\n\n output({ peers }, options.pretty || false);\n}\n\n/**\n * Handle the `agora peers remove` command.\n */\nfunction handlePeersRemove(args: string[], options: CliOptions): void {\n if (args.length < 1) {\n console.error('Error: Missing peer name. Usage: agora peers remove <name>');\n process.exit(1);\n }\n\n const name = args[0];\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n if (!config.peers[name]) {\n console.error(`Error: Peer '${name}' not found.`);\n process.exit(1);\n }\n\n delete config.peers[name];\n savePeerConfig(configPath, config);\n output({ \n status: 'removed',\n name \n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora peers discover` command.\n */\nasync function handlePeersDiscover(\n options: CliOptions & { \n relay?: string; \n 'relay-pubkey'?: string;\n limit?: string;\n 'active-within'?: string;\n save?: boolean;\n }\n): Promise<void> {\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n // Determine relay configuration\n let relayUrl: string;\n let relayPublicKey: string | undefined;\n\n if (options.relay) {\n // Use custom relay from command line\n relayUrl = options.relay;\n relayPublicKey = options['relay-pubkey'];\n } else if (config.relay) {\n // Use relay from config\n relayUrl = typeof config.relay === 'string' ? config.relay : config.relay.url;\n // TODO: Add relayPublicKey to config schema in future\n relayPublicKey = undefined;\n } else {\n // Use default bootstrap relay\n const bootstrap = getDefaultBootstrapRelay();\n relayUrl = bootstrap.relayUrl;\n relayPublicKey = bootstrap.relayPublicKey;\n }\n\n // Parse filters\n const filters: { activeWithin?: number; limit?: number } = {};\n if (options['active-within']) {\n const ms = parseInt(options['active-within'], 10);\n if (isNaN(ms) || ms <= 0) {\n console.error('Error: --active-within must be a positive number (milliseconds)');\n process.exit(1);\n }\n filters.activeWithin = ms;\n }\n if (options.limit) {\n const limit = parseInt(options.limit, 10);\n if (isNaN(limit) || limit <= 0) {\n console.error('Error: --limit must be a positive number');\n process.exit(1);\n }\n filters.limit = limit;\n }\n\n // Resolve broadcast name\n const broadcastName = resolveBroadcastName(config, undefined);\n\n // Connect to relay\n const relayClient = new RelayClient({\n relayUrl,\n publicKey: config.identity.publicKey,\n privateKey: config.identity.privateKey,\n name: broadcastName,\n });\n\n try {\n // Connect\n await relayClient.connect();\n\n // Create discovery service\n const discoveryService = new PeerDiscoveryService({\n publicKey: config.identity.publicKey,\n privateKey: config.identity.privateKey,\n relayClient,\n relayPublicKey,\n });\n\n // Discover peers\n const peerList = await discoveryService.discoverViaRelay(Object.keys(filters).length > 0 ? filters : undefined);\n\n if (!peerList) {\n output({\n status: 'no_response',\n message: 'No response from relay',\n }, options.pretty || false);\n process.exit(1);\n }\n\n // Save to config if requested\n if (options.save) {\n let savedCount = 0;\n for (const peer of peerList.peers) {\n // Only save if not already in config\n const existing = Object.values(config.peers).find(p => p.publicKey === peer.publicKey);\n if (!existing) {\n const peerName = peer.metadata?.name || `peer-${peer.publicKey.substring(0, 8)}`;\n config.peers[peerName] = {\n publicKey: peer.publicKey,\n name: peerName,\n };\n savedCount++;\n }\n }\n if (savedCount > 0) {\n savePeerConfig(configPath, config);\n }\n\n output({\n status: 'discovered',\n totalPeers: peerList.totalPeers,\n peersReturned: peerList.peers.length,\n peersSaved: savedCount,\n relayPublicKey: peerList.relayPublicKey,\n peers: peerList.peers.map(p => ({\n publicKey: p.publicKey,\n name: p.metadata?.name,\n version: p.metadata?.version,\n lastSeen: p.lastSeen,\n })),\n }, options.pretty || false);\n } else {\n output({\n status: 'discovered',\n totalPeers: peerList.totalPeers,\n peersReturned: peerList.peers.length,\n relayPublicKey: peerList.relayPublicKey,\n peers: peerList.peers.map(p => ({\n publicKey: p.publicKey,\n name: p.metadata?.name,\n version: p.metadata?.version,\n lastSeen: p.lastSeen,\n })),\n }, options.pretty || false);\n }\n } catch (e) {\n console.error('Error discovering peers:', e instanceof Error ? e.message : String(e));\n process.exit(1);\n } finally {\n relayClient.disconnect();\n }\n}\n\n/**\n * Handle the `agora send` command.\n */\nasync function handleSend(args: string[], options: CliOptions & { type?: string; payload?: string; direct?: boolean; 'relay-only'?: boolean }): Promise<void> {\n if (args.length < 1) {\n console.error('Error: Missing peer name. Usage: agora send <name> <message> OR agora send <name> --type <type> --payload <json>');\n process.exit(1);\n }\n\n const name = args[0];\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n if (!config.peers[name]) {\n console.error(`Error: Peer '${name}' not found.`);\n process.exit(1);\n }\n\n const peer = config.peers[name];\n\n let messageType: MessageType;\n let messagePayload: unknown;\n\n if (options.type && options.payload) {\n // Typed message - validate it's a valid MessageType\n const validTypes: MessageType[] = ['announce', 'discover', 'request', 'response', 'publish', 'subscribe', 'verify', 'ack', 'error'];\n if (!validTypes.includes(options.type as MessageType)) {\n console.error(`Error: Invalid message type '${options.type}'. Valid types: ${validTypes.join(', ')}`);\n process.exit(1);\n }\n messageType = options.type as MessageType;\n try {\n messagePayload = JSON.parse(options.payload);\n } catch {\n console.error('Error: Invalid JSON payload.');\n process.exit(1);\n }\n } else {\n // Text message - use 'publish' type with text payload\n if (args.length < 2) {\n console.error('Error: Missing message text. Usage: agora send <name> <message>');\n process.exit(1);\n }\n messageType = 'publish';\n messagePayload = { text: args.slice(1).join(' ') };\n }\n\n const isDirect = options.direct === true;\n const isRelayOnly = options['relay-only'] === true;\n\n // Validate flag combination\n if (isDirect && isRelayOnly) {\n console.error('Error: --direct and --relay-only are mutually exclusive.');\n process.exit(1);\n }\n\n // --direct requires the peer to have a URL\n if (isDirect && !peer.url) {\n console.error(`Error: --direct requested but peer '${name}' has no URL configured.`);\n process.exit(1);\n }\n\n // Whether to attempt HTTP transport for this send\n const shouldTryHttp = peer.url && !isRelayOnly;\n const hasRelay = config.relay;\n\n // Send the message\n try {\n if (shouldTryHttp) {\n // Use HTTP transport\n const transportConfig = {\n identity: config.identity,\n peers: new Map<string, PeerConfig>([[peer.publicKey, {\n url: peer.url!,\n token: peer.token,\n publicKey: peer.publicKey,\n }]]),\n };\n\n const result = await sendToPeer(\n transportConfig,\n peer.publicKey,\n messageType,\n messagePayload\n );\n\n if (result.ok) {\n output({ \n status: 'sent',\n peer: name,\n type: messageType,\n transport: 'http',\n httpStatus: result.status\n }, options.pretty || false);\n return;\n }\n\n // HTTP failed\n if (isDirect) {\n // --direct: do not fall back to relay\n output({ \n status: 'failed',\n peer: name,\n type: messageType,\n transport: 'http',\n httpStatus: result.status,\n error: result.error\n }, options.pretty || false);\n process.exit(1);\n }\n\n // Fall through to relay if available\n if (!hasRelay || !config.relay) {\n output({ \n status: 'failed',\n peer: name,\n type: messageType,\n transport: 'http',\n httpStatus: result.status,\n error: result.error\n }, options.pretty || false);\n process.exit(1);\n }\n }\n\n // Use relay transport (relay-only mode, or HTTP failed with relay available, or no URL)\n if (hasRelay && config.relay) {\n // Extract URL from relay (string or object)\n const relayUrl = typeof config.relay === 'string' ? config.relay : config.relay.url;\n const relayConfig = {\n identity: config.identity,\n relayUrl,\n };\n\n const result = await sendViaRelay(\n relayConfig,\n peer.publicKey,\n messageType,\n messagePayload\n );\n\n if (result.ok) {\n output({ \n status: 'sent',\n peer: name,\n type: messageType,\n transport: 'relay'\n }, options.pretty || false);\n } else {\n output({ \n status: 'failed',\n peer: name,\n type: messageType,\n transport: 'relay',\n error: result.error\n }, options.pretty || false);\n process.exit(1);\n }\n } else if (!shouldTryHttp) {\n // Neither HTTP nor relay available\n console.error(`Error: Peer '${name}' unreachable. No HTTP endpoint and no relay configured.`);\n process.exit(1);\n }\n } catch (e) {\n console.error('Error sending message:', e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n}\n\n/**\n * Handle the `agora decode` command.\n */\nfunction handleDecode(args: string[], options: CliOptions): void {\n if (args.length < 1) {\n console.error('Error: Missing message. Usage: agora decode <message>');\n process.exit(1);\n }\n\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const peers = new Map<string, PeerConfig>();\n for (const [, val] of Object.entries(config.peers)) {\n // Only add peers with HTTP config to the map for decoding\n if (val.url && val.token) {\n peers.set(val.publicKey, {\n url: val.url,\n token: val.token,\n publicKey: val.publicKey,\n });\n }\n }\n\n const message = args.join(' ');\n const result = decodeInboundEnvelope(message, peers);\n\n if (result.ok) {\n output({\n status: 'verified',\n sender: result.envelope.sender,\n type: result.envelope.type,\n payload: result.envelope.payload,\n id: result.envelope.id,\n timestamp: result.envelope.timestamp,\n inReplyTo: result.envelope.inReplyTo || null,\n }, options.pretty || false);\n } else {\n output({\n status: 'failed',\n reason: result.reason,\n }, options.pretty || false);\n process.exit(1);\n }\n}\n\n/**\n * Handle the `agora status` command.\n */\nfunction handleStatus(options: CliOptions): void {\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const peerCount = Object.keys(config.peers).length;\n\n output({\n identity: config.identity.publicKey,\n configPath,\n relay: config.relay || 'not configured',\n peerCount,\n peers: Object.keys(config.peers),\n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora announce` command.\n * Broadcasts an announce message to all configured peers.\n */\nasync function handleAnnounce(options: CliOptions & { name?: string; version?: string }): Promise<void> {\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const peerCount = Object.keys(config.peers).length;\n\n if (peerCount === 0) {\n console.error('Error: No peers configured. Use `agora peers add` to add peers first.');\n process.exit(1);\n }\n\n // Create announce payload\n const announcePayload: AnnouncePayload = {\n capabilities: [],\n metadata: {\n name: options.name || 'agora-node',\n version: options.version || '0.1.0',\n },\n };\n\n // Send announce to all peers\n const results: Array<{ peer: string; status: string; transport?: string; httpStatus?: number; error?: string }> = [];\n\n for (const [name, peer] of Object.entries(config.peers)) {\n const hasHttpTransport = peer.url && peer.token;\n const hasRelay = config.relay;\n\n try {\n if (hasHttpTransport) {\n // Use HTTP transport\n const peers = new Map<string, PeerConfig>();\n peers.set(peer.publicKey, {\n url: peer.url!,\n token: peer.token!,\n publicKey: peer.publicKey,\n });\n\n const transportConfig = {\n identity: config.identity,\n peers,\n };\n\n const result = await sendToPeer(\n transportConfig,\n peer.publicKey,\n 'announce',\n announcePayload\n );\n\n if (result.ok) {\n results.push({\n peer: name,\n status: 'sent',\n transport: 'http',\n httpStatus: result.status,\n });\n } else {\n results.push({\n peer: name,\n status: 'failed',\n transport: 'http',\n httpStatus: result.status,\n error: result.error,\n });\n }\n } else if (hasRelay && config.relay) {\n // Use relay transport\n // Extract URL from relay (string or object)\n const relayUrl = typeof config.relay === 'string' ? config.relay : config.relay.url;\n const relayConfig = {\n identity: config.identity,\n relayUrl,\n };\n\n const result = await sendViaRelay(\n relayConfig,\n peer.publicKey,\n 'announce',\n announcePayload\n );\n\n if (result.ok) {\n results.push({\n peer: name,\n status: 'sent',\n transport: 'relay',\n });\n } else {\n results.push({\n peer: name,\n status: 'failed',\n transport: 'relay',\n error: result.error,\n });\n }\n } else {\n results.push({\n peer: name,\n status: 'unreachable',\n error: 'No HTTP endpoint and no relay configured',\n });\n }\n } catch (e) {\n results.push({\n peer: name,\n status: 'error',\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n\n output({ results }, options.pretty || false);\n}\n\n/**\n * Handle the `agora diagnose` command.\n * Run diagnostic checks on a peer (ping, workspace, tools).\n */\nasync function handleDiagnose(args: string[], options: CliOptions & { checks?: string }): Promise<void> {\n if (args.length < 1) {\n console.error('Error: Missing peer name. Usage: agora diagnose <name> [--checks <comma-separated-list>]');\n process.exit(1);\n }\n\n const name = args[0];\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n if (!config.peers[name]) {\n console.error(`Error: Peer '${name}' not found.`);\n process.exit(1);\n }\n\n const peer = config.peers[name];\n\n if (!peer.url) {\n console.error(`Error: Peer '${name}' has no URL configured. Cannot diagnose.`);\n process.exit(1);\n }\n\n // Parse checks parameter\n const checksParam = options.checks || 'ping';\n const requestedChecks = checksParam.split(',').map(c => c.trim());\n \n // Validate check types\n const validChecks = ['ping', 'workspace', 'tools'];\n for (const check of requestedChecks) {\n if (!validChecks.includes(check)) {\n console.error(`Error: Invalid check type '${check}'. Valid checks: ${validChecks.join(', ')}`);\n process.exit(1);\n }\n }\n\n // Result structure\n interface CheckResult {\n ok: boolean;\n latency_ms?: number;\n error?: string;\n implemented?: boolean;\n [key: string]: unknown;\n }\n \n const result: {\n peer: string;\n status: string;\n checks: Record<string, CheckResult>;\n timestamp: string;\n } = {\n peer: name,\n status: 'unknown',\n checks: {},\n timestamp: new Date().toISOString(),\n };\n\n // Run ping check\n if (requestedChecks.includes('ping')) {\n const startTime = Date.now();\n try {\n // Add timeout to prevent hanging on unreachable peers\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 10000);\n \n const response = await fetch(peer.url, {\n method: 'GET',\n headers: peer.token ? { 'Authorization': `Bearer ${peer.token}` } : {},\n signal: controller.signal,\n });\n \n clearTimeout(timeout);\n const latency = Date.now() - startTime;\n \n if (response.ok || response.status === 404 || response.status === 405) {\n // 404 or 405 means the endpoint exists but GET isn't supported - that's OK for a ping\n result.checks.ping = { ok: true, latency_ms: latency };\n } else {\n result.checks.ping = { ok: false, latency_ms: latency, error: `HTTP ${response.status}` };\n }\n } catch (err) {\n const latency = Date.now() - startTime;\n result.checks.ping = { \n ok: false, \n latency_ms: latency,\n error: err instanceof Error ? err.message : String(err) \n };\n }\n }\n\n // Run workspace check\n if (requestedChecks.includes('workspace')) {\n // This is a placeholder - actual implementation would depend on peer's diagnostic protocol\n result.checks.workspace = { \n ok: false,\n implemented: false,\n error: 'Workspace check requires peer diagnostic protocol support' \n };\n }\n\n // Run tools check\n if (requestedChecks.includes('tools')) {\n // This is a placeholder - actual implementation would depend on peer's diagnostic protocol\n result.checks.tools = { \n ok: false,\n implemented: false,\n error: 'Tools check requires peer diagnostic protocol support' \n };\n }\n\n // Determine overall status - only consider implemented checks\n const implementedChecks = Object.values(result.checks).filter(\n check => check.implemented !== false\n );\n \n if (implementedChecks.length === 0) {\n result.status = 'unknown';\n } else {\n const allOk = implementedChecks.every(check => check.ok);\n const anyOk = implementedChecks.some(check => check.ok);\n result.status = allOk ? 'healthy' : anyOk ? 'degraded' : 'unhealthy';\n }\n\n output(result, options.pretty || false);\n}\n\n/**\n * Handle the `agora serve` command.\n * Starts a persistent WebSocket server for incoming peer connections.\n */\nasync function handleServe(options: CliOptions & { port?: string; name?: string }): Promise<void> {\n const configPath = getConfigPath(options);\n\n if (!existsSync(configPath)) {\n console.error('Error: Config file not found. Run `agora init` first.');\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const port = parseInt(options.port || '9473', 10);\n \n // Validate port\n if (isNaN(port) || port < 1 || port > 65535) {\n console.error(`Error: Invalid port number '${options.port}'. Port must be between 1 and 65535.`);\n process.exit(1);\n }\n \n // Resolve server name using priority: CLI --name, config.relay.name, config.identity.name, default\n const serverName = resolveBroadcastName(config, options.name) || 'agora-server';\n\n // Create announce payload\n const announcePayload: AnnouncePayload = {\n capabilities: [],\n metadata: {\n name: serverName,\n version: '0.1.0',\n },\n };\n\n // Create and configure PeerServer\n const server = new PeerServer(config.identity, announcePayload);\n\n // Setup event listeners\n server.on('peer-connected', (publicKey, peer) => {\n const peerName = peer.metadata?.name || publicKey.substring(0, 16);\n console.log(`[${new Date().toISOString()}] Peer connected: ${peerName} (${publicKey})`);\n });\n\n server.on('peer-disconnected', (publicKey) => {\n console.log(`[${new Date().toISOString()}] Peer disconnected: ${publicKey}`);\n });\n\n server.on('message-received', (envelope, fromPublicKey) => {\n console.log(`[${new Date().toISOString()}] Message from ${fromPublicKey}:`);\n console.log(JSON.stringify({\n id: envelope.id,\n type: envelope.type,\n sender: envelope.sender,\n timestamp: envelope.timestamp,\n payload: envelope.payload,\n }, null, 2));\n });\n\n server.on('error', (error) => {\n console.error(`[${new Date().toISOString()}] Error:`, error.message);\n });\n\n // Start the server\n try {\n await server.start(port);\n console.log(`[${new Date().toISOString()}] Agora server started`);\n console.log(` Name: ${serverName}`);\n console.log(` Public Key: ${config.identity.publicKey}`);\n console.log(` WebSocket Port: ${port}`);\n console.log(` Listening for peer connections...`);\n console.log('');\n console.log('Press Ctrl+C to stop the server');\n\n // Keep the process alive\n process.on('SIGINT', async () => {\n console.log(`\\n[${new Date().toISOString()}] Shutting down server...`);\n await server.stop();\n console.log('Server stopped');\n process.exit(0);\n });\n\n process.on('SIGTERM', async () => {\n console.log(`\\n[${new Date().toISOString()}] Shutting down server...`);\n await server.stop();\n console.log('Server stopped');\n process.exit(0);\n });\n } catch (error) {\n console.error('Failed to start server:', error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n}\n\n/**\n * Handle the `agora relay` command.\n * Starts a WebSocket relay server for routing messages between agents.\n */\nasync function handleRelay(options: CliOptions & { port?: string }): Promise<void> {\n const port = parseInt(options.port || '9474', 10);\n \n // Validate port\n if (isNaN(port) || port < 1 || port > 65535) {\n console.error(`Error: Invalid port number '${options.port}'. Port must be between 1 and 65535.`);\n process.exit(1);\n }\n\n // Create and configure RelayServer\n const server = new RelayServer();\n\n // Setup event listeners\n server.on('agent-registered', (publicKey) => {\n console.log(`[${new Date().toISOString()}] Agent registered: ${publicKey}`);\n });\n\n server.on('agent-disconnected', (publicKey) => {\n console.log(`[${new Date().toISOString()}] Agent disconnected: ${publicKey}`);\n });\n\n server.on('message-relayed', (from, to, envelope) => {\n console.log(`[${new Date().toISOString()}] Message relayed: ${from.substring(0, 16)}... → ${to.substring(0, 16)}... (type: ${envelope.type})`);\n });\n\n server.on('error', (error) => {\n console.error(`[${new Date().toISOString()}] Error:`, error.message);\n });\n\n // Start the server\n try {\n await server.start(port);\n console.log(`[${new Date().toISOString()}] Agora relay server started`);\n console.log(` WebSocket Port: ${port}`);\n console.log(` Connected agents: 0`);\n console.log(` Listening for agent connections...`);\n console.log('');\n console.log('Press Ctrl+C to stop the relay');\n\n // Shared shutdown handler\n const shutdown = async (): Promise<void> => {\n console.log(`\\n[${new Date().toISOString()}] Shutting down relay...`);\n await server.stop();\n console.log('Relay stopped');\n process.exit(0);\n };\n\n // Keep the process alive\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n } catch (error) {\n console.error('Failed to start relay:', error instanceof Error ? error.message : String(error));\n process.exit(1);\n }\n}\n\n/**\n * Get the reputation store file path.\n */\nfunction getReputationStorePath(): string {\n return resolve(homedir(), '.local', 'share', 'agora', 'reputation.jsonl');\n}\n\n/**\n * Handle the `agora reputation verify` command.\n * Creates a verification record for another agent's output.\n */\nasync function handleReputationVerify(\n args: string[],\n options: CliOptions & {\n target?: string;\n domain?: string;\n verdict?: string;\n confidence?: string;\n evidence?: string;\n }\n): Promise<void> {\n if (!options.target || !options.domain || !options.verdict) {\n console.error('Error: Missing required options');\n console.error('Usage: agora reputation verify --target <id> --domain <domain> --verdict <correct|incorrect|disputed> --confidence <0-1> [--evidence <url>]');\n process.exit(1);\n }\n\n // Validate verdict\n if (!['correct', 'incorrect', 'disputed'].includes(options.verdict)) {\n console.error('Error: verdict must be one of: correct, incorrect, disputed');\n process.exit(1);\n }\n\n // Parse confidence\n const confidence = options.confidence ? parseFloat(options.confidence) : 1.0;\n if (isNaN(confidence) || confidence < 0 || confidence > 1) {\n console.error('Error: confidence must be a number between 0 and 1');\n process.exit(1);\n }\n\n // Load config\n const configPath = getConfigPath(options);\n if (!existsSync(configPath)) {\n console.error(`Error: Config file not found at ${configPath}. Run 'agora init' first.`);\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n // Create verification\n const verification = createVerification(\n config.identity.publicKey,\n config.identity.privateKey,\n options.target,\n options.domain,\n options.verdict as 'correct' | 'incorrect' | 'disputed',\n confidence,\n Date.now(),\n options.evidence\n );\n\n // Save to reputation store\n const storePath = getReputationStorePath();\n const store = new ReputationStore(storePath);\n await store.addVerification(verification);\n\n output({\n status: 'verification_created',\n id: verification.id,\n verifier: verification.verifier,\n target: verification.target,\n domain: verification.domain,\n verdict: verification.verdict,\n confidence: verification.confidence,\n timestamp: verification.timestamp,\n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora reputation commit` command.\n * Creates a commitment to a prediction before outcome is known.\n */\nasync function handleReputationCommit(\n args: string[],\n options: CliOptions & {\n domain?: string;\n prediction?: string;\n expiry?: string;\n }\n): Promise<void> {\n if (!options.domain || !options.prediction) {\n console.error('Error: Missing required options');\n console.error('Usage: agora reputation commit --domain <domain> --prediction <text> [--expiry <milliseconds>]');\n console.error('Example: agora reputation commit --domain weather_forecast --prediction \"It will rain tomorrow\" --expiry 86400000');\n process.exit(1);\n }\n\n // Parse expiry (default 24 hours)\n const expiryMs = options.expiry ? parseInt(options.expiry, 10) : 86400000;\n if (isNaN(expiryMs) || expiryMs <= 0) {\n console.error('Error: expiry must be a positive number (milliseconds)');\n process.exit(1);\n }\n\n // Load config\n const configPath = getConfigPath(options);\n if (!existsSync(configPath)) {\n console.error(`Error: Config file not found at ${configPath}. Run 'agora init' first.`);\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n // Create commit\n const commit = createCommit(\n config.identity.publicKey,\n config.identity.privateKey,\n options.domain,\n options.prediction,\n Date.now(),\n expiryMs\n );\n\n // Save to reputation store\n const storePath = getReputationStorePath();\n const store = new ReputationStore(storePath);\n await store.addCommit(commit);\n\n output({\n status: 'commitment_created',\n id: commit.id,\n agent: commit.agent,\n domain: commit.domain,\n commitment: commit.commitment,\n timestamp: commit.timestamp,\n expiry: commit.expiry,\n note: 'Store this ID to reveal the prediction after expiry',\n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora reputation reveal` command.\n * Reveals a prediction and outcome after commitment expiry.\n */\nasync function handleReputationReveal(\n args: string[],\n options: CliOptions & {\n 'commit-id'?: string;\n prediction?: string;\n outcome?: string;\n evidence?: string;\n }\n): Promise<void> {\n if (!options['commit-id'] || !options.prediction || !options.outcome) {\n console.error('Error: Missing required options');\n console.error('Usage: agora reputation reveal --commit-id <id> --prediction <text> --outcome <text> [--evidence <url>]');\n process.exit(1);\n }\n\n // Load config\n const configPath = getConfigPath(options);\n if (!existsSync(configPath)) {\n console.error(`Error: Config file not found at ${configPath}. Run 'agora init' first.`);\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n\n // Load commit from store\n const storePath = getReputationStorePath();\n const store = new ReputationStore(storePath);\n const commit = await store.getCommit(options['commit-id']);\n\n if (!commit) {\n console.error(`Error: Commitment ${options['commit-id']} not found in local store`);\n process.exit(1);\n }\n\n // Create reveal\n const reveal = createReveal(\n config.identity.publicKey,\n config.identity.privateKey,\n options['commit-id'],\n options.prediction,\n options.outcome,\n Date.now(),\n options.evidence\n );\n \n // Verify the reveal against the commit\n const verification = verifyReveal(commit, reveal);\n if (!verification.valid) {\n console.error(`Error: Reveal verification failed: ${verification.reason}`);\n process.exit(1);\n }\n\n // Save to reputation store\n await store.addReveal(reveal);\n\n output({\n status: 'prediction_revealed',\n id: reveal.id,\n agent: reveal.agent,\n commitmentId: reveal.commitmentId,\n prediction: reveal.prediction,\n outcome: reveal.outcome,\n timestamp: reveal.timestamp,\n verified: true,\n }, options.pretty || false);\n}\n\n/**\n * Handle the `agora reputation query` command.\n * Queries reputation score for an agent in a domain.\n */\nasync function handleReputationQuery(\n args: string[],\n options: CliOptions & {\n agent?: string;\n domain?: string;\n }\n): Promise<void> {\n if (!options.domain) {\n console.error('Error: Missing required option: --domain');\n console.error('Usage: agora reputation query --domain <domain> [--agent <pubkey>]');\n console.error('If --agent is omitted, shows reputation for current agent');\n process.exit(1);\n }\n\n // Load config\n const configPath = getConfigPath(options);\n if (!existsSync(configPath)) {\n console.error(`Error: Config file not found at ${configPath}. Run 'agora init' first.`);\n process.exit(1);\n }\n\n const config = loadPeerConfig(configPath);\n const agent = options.agent || config.identity.publicKey;\n\n // Load reputation store\n const storePath = getReputationStorePath();\n const store = new ReputationStore(storePath);\n const verifications = await store.getVerificationsByDomain(options.domain);\n\n // Filter verifications for this agent\n const agentVerifications = verifications.filter(v => v.target === agent);\n\n // Compute trust score\n const score = computeTrustScore(agent, options.domain, agentVerifications, Date.now());\n\n output({\n agent: score.agent,\n domain: score.domain,\n score: score.score,\n verificationCount: score.verificationCount,\n lastVerified: score.lastVerified,\n lastVerifiedDate: score.lastVerified > 0 ? new Date(score.lastVerified).toISOString() : 'never',\n topVerifiers: score.topVerifiers,\n }, options.pretty || false);\n}\n\n/**\n * Parse CLI arguments and route to appropriate handler.\n */\nasync function main(): Promise<void> {\n const args = process.argv.slice(2);\n\n if (args.length === 0) {\n console.error('Usage: agora <command> [options]');\n console.error('Commands: init, whoami, status, peers, announce, send, decode, serve, diagnose, relay, reputation');\n console.error(' peers subcommands: add, list, remove, discover');\n console.error(' reputation subcommands: verify, commit, reveal, query');\n process.exit(1);\n }\n\n // Parse global options\n const parsed = parseArgs({\n args,\n options: {\n config: { type: 'string' },\n pretty: { type: 'boolean' },\n url: { type: 'string' },\n token: { type: 'string' },\n pubkey: { type: 'string' },\n type: { type: 'string' },\n payload: { type: 'string' },\n name: { type: 'string' },\n version: { type: 'string' },\n port: { type: 'string' },\n checks: { type: 'string' },\n relay: { type: 'string' },\n 'relay-pubkey': { type: 'string' },\n limit: { type: 'string' },\n 'active-within': { type: 'string' },\n save: { type: 'boolean' },\n // Reputation options\n target: { type: 'string' },\n domain: { type: 'string' },\n verdict: { type: 'string' },\n confidence: { type: 'string' },\n evidence: { type: 'string' },\n prediction: { type: 'string' },\n expiry: { type: 'string' },\n 'commit-id': { type: 'string' },\n outcome: { type: 'string' },\n agent: { type: 'string' },\n direct: { type: 'boolean' },\n 'relay-only': { type: 'boolean' },\n },\n strict: false,\n allowPositionals: true,\n });\n\n const command = parsed.positionals[0];\n const subcommand = parsed.positionals[1];\n const remainingArgs = parsed.positionals.slice(2);\n\n const options: CliOptions & { \n type?: string; \n payload?: string; \n url?: string; \n token?: string; \n pubkey?: string; \n name?: string; \n version?: string; \n port?: string; \n checks?: string;\n relay?: string;\n 'relay-pubkey'?: string;\n limit?: string;\n 'active-within'?: string;\n save?: boolean;\n // Reputation options\n target?: string;\n domain?: string;\n verdict?: string;\n confidence?: string;\n evidence?: string;\n prediction?: string;\n outcome?: string;\n expiry?: string;\n 'commit-id'?: string;\n agent?: string;\n direct?: boolean;\n 'relay-only'?: boolean;\n } = {\n config: typeof parsed.values.config === 'string' ? parsed.values.config : undefined,\n pretty: typeof parsed.values.pretty === 'boolean' ? parsed.values.pretty : undefined,\n type: typeof parsed.values.type === 'string' ? parsed.values.type : undefined,\n payload: typeof parsed.values.payload === 'string' ? parsed.values.payload : undefined,\n url: typeof parsed.values.url === 'string' ? parsed.values.url : undefined,\n token: typeof parsed.values.token === 'string' ? parsed.values.token : undefined,\n pubkey: typeof parsed.values.pubkey === 'string' ? parsed.values.pubkey : undefined,\n name: typeof parsed.values.name === 'string' ? parsed.values.name : undefined,\n version: typeof parsed.values.version === 'string' ? parsed.values.version : undefined,\n port: typeof parsed.values.port === 'string' ? parsed.values.port : undefined,\n checks: typeof parsed.values.checks === 'string' ? parsed.values.checks : undefined,\n relay: typeof parsed.values.relay === 'string' ? parsed.values.relay : undefined,\n 'relay-pubkey': typeof parsed.values['relay-pubkey'] === 'string' ? parsed.values['relay-pubkey'] : undefined,\n limit: typeof parsed.values.limit === 'string' ? parsed.values.limit : undefined,\n 'active-within': typeof parsed.values['active-within'] === 'string' ? parsed.values['active-within'] : undefined,\n save: typeof parsed.values.save === 'boolean' ? parsed.values.save : undefined,\n // Reputation options\n target: typeof parsed.values.target === 'string' ? parsed.values.target : undefined,\n domain: typeof parsed.values.domain === 'string' ? parsed.values.domain : undefined,\n verdict: typeof parsed.values.verdict === 'string' ? parsed.values.verdict : undefined,\n confidence: typeof parsed.values.confidence === 'string' ? parsed.values.confidence : undefined,\n evidence: typeof parsed.values.evidence === 'string' ? parsed.values.evidence : undefined,\n prediction: typeof parsed.values.prediction === 'string' ? parsed.values.prediction : undefined,\n expiry: typeof parsed.values.expiry === 'string' ? parsed.values.expiry : undefined,\n 'commit-id': typeof parsed.values['commit-id'] === 'string' ? parsed.values['commit-id'] : undefined,\n outcome: typeof parsed.values.outcome === 'string' ? parsed.values.outcome : undefined,\n agent: typeof parsed.values.agent === 'string' ? parsed.values.agent : undefined,\n direct: typeof parsed.values.direct === 'boolean' ? parsed.values.direct : undefined,\n 'relay-only': typeof parsed.values['relay-only'] === 'boolean' ? parsed.values['relay-only'] : undefined,\n };\n\n try {\n switch (command) {\n case 'init':\n handleInit(options);\n break;\n case 'whoami':\n handleWhoami(options);\n break;\n case 'status':\n handleStatus(options);\n break;\n case 'announce':\n await handleAnnounce(options);\n break;\n case 'diagnose':\n await handleDiagnose([subcommand, ...remainingArgs].filter(Boolean), options);\n break;\n case 'peers':\n switch (subcommand) {\n case 'add':\n handlePeersAdd(remainingArgs, options);\n break;\n case 'list':\n case undefined:\n // Allow 'agora peers' to work like 'agora peers list'\n handlePeersList(options);\n break;\n case 'remove':\n handlePeersRemove(remainingArgs, options);\n break;\n case 'discover':\n await handlePeersDiscover(options);\n break;\n default:\n console.error('Error: Unknown peers subcommand. Use: add, list, remove, discover');\n process.exit(1);\n }\n break;\n case 'send':\n await handleSend([subcommand, ...remainingArgs], options);\n break;\n case 'decode':\n handleDecode([subcommand, ...remainingArgs].filter(Boolean), options);\n break;\n case 'serve':\n await handleServe(options);\n break;\n case 'relay':\n await handleRelay(options);\n break;\n case 'reputation':\n switch (subcommand) {\n case 'verify':\n await handleReputationVerify(remainingArgs, options);\n break;\n case 'commit':\n await handleReputationCommit(remainingArgs, options);\n break;\n case 'reveal':\n await handleReputationReveal(remainingArgs, options);\n break;\n case 'query':\n await handleReputationQuery(remainingArgs, options);\n break;\n default:\n console.error('Error: Unknown reputation subcommand. Use: verify, commit, reveal, query');\n process.exit(1);\n }\n break;\n default:\n console.error(`Error: Unknown command '${command}'. Use: init, whoami, status, peers, announce, send, decode, serve, diagnose, relay, reputation`);\n process.exit(1);\n }\n } catch (e) {\n console.error('Error:', e instanceof Error ? e.message : String(e));\n process.exit(1);\n }\n}\n\nmain().catch((e) => {\n console.error('Fatal error:', e instanceof Error ? e.message : String(e));\n process.exit(1);\n});\n","import { EventEmitter } from 'node:events';\nimport { WebSocketServer, WebSocket } from 'ws';\nimport type { KeyPair } from '../identity/keypair';\nimport type { Envelope } from '../message/envelope';\nimport { createEnvelope, verifyEnvelope } from '../message/envelope';\nimport type { AnnouncePayload } from '../registry/messages';\n\n/**\n * Represents a connected peer\n */\nexport interface ConnectedPeer {\n /** Peer's public key */\n publicKey: string;\n /** WebSocket connection */\n socket: WebSocket;\n /** Whether the peer has been announced */\n announced: boolean;\n /** Peer metadata from announce message */\n metadata?: {\n name?: string;\n version?: string;\n };\n}\n\n/**\n * Events emitted by PeerServer\n */\nexport interface PeerServerEvents {\n 'peer-connected': (publicKey: string, peer: ConnectedPeer) => void;\n 'peer-disconnected': (publicKey: string) => void;\n 'message-received': (envelope: Envelope, fromPublicKey: string) => void;\n 'error': (error: Error) => void;\n}\n\n/**\n * WebSocket server for accepting peer connections\n */\nexport class PeerServer extends EventEmitter {\n private wss: WebSocketServer | null = null;\n private peers = new Map<string, ConnectedPeer>();\n private identity: KeyPair;\n private announcePayload: AnnouncePayload;\n\n constructor(identity: KeyPair, announcePayload: AnnouncePayload) {\n super();\n this.identity = identity;\n this.announcePayload = announcePayload;\n }\n\n /**\n * Start the WebSocket server\n */\n start(port: number): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n this.wss = new WebSocketServer({ port });\n\n this.wss.on('error', (error) => {\n this.emit('error', error);\n reject(error);\n });\n\n this.wss.on('listening', () => {\n resolve();\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 WebSocket 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 peer connections\n for (const peer of this.peers.values()) {\n peer.socket.close();\n }\n this.peers.clear();\n\n this.wss.close((err) => {\n if (err) {\n reject(err);\n } else {\n this.wss = null;\n resolve();\n }\n });\n });\n }\n\n /**\n * Get all connected peers\n */\n getPeers(): Map<string, ConnectedPeer> {\n return new Map(this.peers);\n }\n\n /**\n * Send a message to a specific peer\n */\n send(publicKey: string, envelope: Envelope): boolean {\n const peer = this.peers.get(publicKey);\n if (!peer || peer.socket.readyState !== WebSocket.OPEN) {\n return false;\n }\n\n try {\n peer.socket.send(JSON.stringify(envelope));\n return true;\n } catch (error) {\n this.emit('error', error as Error);\n return false;\n }\n }\n\n /**\n * Broadcast a message to all connected peers\n */\n broadcast(envelope: Envelope): void {\n for (const [publicKey, peer] of this.peers) {\n if (peer.socket.readyState === WebSocket.OPEN) {\n this.send(publicKey, envelope);\n }\n }\n }\n\n /**\n * Handle incoming connection\n */\n private handleConnection(socket: WebSocket): void {\n let peerPublicKey: string | null = null;\n\n // Send announce message immediately\n const announceEnvelope = createEnvelope(\n 'announce',\n this.identity.publicKey,\n this.identity.privateKey,\n this.announcePayload\n );\n socket.send(JSON.stringify(announceEnvelope));\n\n socket.on('message', (data: Buffer) => {\n try {\n const envelope = JSON.parse(data.toString()) as Envelope;\n\n // Verify envelope signature\n const verification = verifyEnvelope(envelope);\n if (!verification.valid) {\n // Drop invalid messages\n return;\n }\n\n // First message should be an announce\n if (!peerPublicKey) {\n if (envelope.type === 'announce') {\n peerPublicKey = envelope.sender;\n const payload = envelope.payload as AnnouncePayload;\n \n const peer: ConnectedPeer = {\n publicKey: peerPublicKey,\n socket,\n announced: true,\n metadata: payload.metadata,\n };\n\n this.peers.set(peerPublicKey, peer);\n this.emit('peer-connected', peerPublicKey, peer);\n }\n return;\n }\n\n // Verify the message is from the announced peer\n if (envelope.sender !== peerPublicKey) {\n // Drop messages from wrong sender\n return;\n }\n\n // Emit message-received event\n this.emit('message-received', envelope, peerPublicKey);\n } catch {\n // Invalid JSON or other parsing errors - drop the message\n }\n });\n\n socket.on('close', () => {\n if (peerPublicKey) {\n this.peers.delete(peerPublicKey);\n this.emit('peer-disconnected', peerPublicKey);\n }\n });\n\n socket.on('error', (error) => {\n this.emit('error', error);\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,iBAAiB;AAC1B,SAAS,YAAY,iBAAiB;AACtC,SAAS,SAAS,eAAe;AACjC,SAAS,eAAe;;;ACLxB,SAAS,oBAAoB;AAC7B,SAAS,iBAAiB,iBAAiB;AAoCpC,IAAM,aAAN,cAAyB,aAAa;AAAA,EACnC,MAA8B;AAAA,EAC9B,QAAQ,oBAAI,IAA2B;AAAA,EACvC;AAAA,EACA;AAAA,EAER,YAAY,UAAmB,iBAAkC;AAC/D,UAAM;AACN,SAAK,WAAW;AAChB,SAAK,kBAAkB;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,MAA6B;AACjC,WAAO,IAAI,QAAQ,CAACA,UAAS,WAAW;AACtC,UAAI;AACF,aAAK,MAAM,IAAI,gBAAgB,EAAE,KAAK,CAAC;AAEvC,aAAK,IAAI,GAAG,SAAS,CAAC,UAAU;AAC9B,eAAK,KAAK,SAAS,KAAK;AACxB,iBAAO,KAAK;AAAA,QACd,CAAC;AAED,aAAK,IAAI,GAAG,aAAa,MAAM;AAC7B,UAAAA,SAAQ;AAAA,QACV,CAAC;AAED,aAAK,IAAI,GAAG,cAAc,CAAC,WAAsB;AAC/C,eAAK,iBAAiB,MAAM;AAAA,QAC9B,CAAC;AAAA,MACH,SAAS,OAAO;AACd,eAAO,KAAK;AAAA,MACd;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,M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","config"]}
package/dist/index.d.ts CHANGED
@@ -654,6 +654,8 @@ interface ConnectedAgent {
654
654
  interface RelayServerEvents {
655
655
  'agent-registered': (publicKey: string) => void;
656
656
  'agent-disconnected': (publicKey: string) => void;
657
+ /** Emitted when a session disconnects (same as agent-disconnected for compatibility) */
658
+ 'disconnection': (publicKey: string) => void;
657
659
  'message-relayed': (from: string, to: string, envelope: Envelope) => void;
658
660
  'error': (error: Error) => void;
659
661
  }
@@ -674,13 +676,17 @@ interface RelayServerOptions {
674
676
  storagePeers?: string[];
675
677
  /** Directory for persisting messages for storage peers */
676
678
  storageDir?: string;
679
+ /** Maximum number of concurrent registered peers (default: 100) */
680
+ maxPeers?: number;
677
681
  }
678
682
  declare class RelayServer extends EventEmitter {
679
683
  private wss;
680
- private agents;
684
+ /** publicKey -> sessionId -> ConnectedAgent (multiple sessions per key) */
685
+ private sessions;
681
686
  private identity?;
682
687
  private storagePeers;
683
688
  private store;
689
+ private maxPeers;
684
690
  constructor(options?: {
685
691
  publicKey: string;
686
692
  privateKey: string;
@@ -696,7 +702,7 @@ declare class RelayServer extends EventEmitter {
696
702
  */
697
703
  stop(): Promise<void>;
698
704
  /**
699
- * Get all connected agents
705
+ * Get one connected agent per public key (first session). For backward compatibility.
700
706
  */
701
707
  getAgents(): Map<string, ConnectedAgent>;
702
708
  /**
@@ -708,7 +714,7 @@ declare class RelayServer extends EventEmitter {
708
714
  */
709
715
  private sendError;
710
716
  /**
711
- * Broadcast a peer event to all connected agents
717
+ * Broadcast a peer event to all connected agents (all sessions except the one for publicKey)
712
718
  */
713
719
  private broadcastPeerEvent;
714
720
  /**
@@ -733,6 +739,7 @@ interface RelayClientMessage {
733
739
  interface RelayServerMessage {
734
740
  type: 'registered' | 'message' | 'error' | 'pong' | 'peer_online' | 'peer_offline';
735
741
  publicKey?: string;
742
+ sessionId?: string;
736
743
  name?: string;
737
744
  from?: string;
738
745
  envelope?: Envelope;
@@ -878,9 +885,14 @@ interface BufferedMessage {
878
885
  /**
879
886
  * MessageBuffer stores inbound messages per agent public key.
880
887
  * FIFO eviction when the buffer is full (max 100 messages).
888
+ * Messages older than ttlMs (measured from when they were received) are pruned on access.
881
889
  */
882
890
  declare class MessageBuffer {
883
891
  private buffers;
892
+ private ttlMs;
893
+ constructor(options?: {
894
+ ttlMs?: number;
895
+ });
884
896
  /**
885
897
  * Add a message to an agent's buffer.
886
898
  * Evicts the oldest message if the buffer is full.
@@ -888,7 +900,7 @@ declare class MessageBuffer {
888
900
  add(publicKey: string, message: BufferedMessage): void;
889
901
  /**
890
902
  * Retrieve messages for an agent, optionally filtering by `since` timestamp.
891
- * Returns messages with timestamp > since (exclusive).
903
+ * Returns messages with timestamp > since (exclusive). Prunes expired messages.
892
904
  */
893
905
  get(publicKey: string, since?: number): BufferedMessage[];
894
906
  /**
@@ -1025,27 +1037,32 @@ type VerifyEnvelopeFn = (envelope: unknown) => {
1025
1037
  /**
1026
1038
  * Create the REST API router.
1027
1039
  */
1028
- declare function createRestRouter(relay: RelayInterface, buffer: MessageBuffer, sessions: Map<string, RestSession>, createEnv: CreateEnvelopeFn, verifyEnv: VerifyEnvelopeFn): Router;
1040
+ declare function createRestRouter(relay: RelayInterface, buffer: MessageBuffer, sessions: Map<string, RestSession>, createEnv: CreateEnvelopeFn, verifyEnv: VerifyEnvelopeFn, rateLimitRpm?: number): Router;
1029
1041
 
1030
1042
  /**
1031
1043
  * run-relay.ts — Start Agora relay: WebSocket server and optional REST API.
1032
1044
  *
1033
1045
  * When REST is enabled, starts:
1034
1046
  * 1. WebSocket relay (RelayServer) on wsPort
1035
- * 2. REST API server (Express) on restPort (default wsPort + 1)
1047
+ * 2. REST API server (Express) on restPort
1036
1048
  *
1037
- * Environment variables (when REST enabled):
1038
- * AGORA_RELAY_JWT_SECRET Required for REST (JWT signing)
1049
+ * Environment variables:
1050
+ * RELAY_PORT WebSocket relay port (default: 3002); alias: PORT
1051
+ * REST_PORT — REST API port (default: 3001)
1052
+ * JWT_SECRET — Secret for JWT session tokens (alias: AGORA_RELAY_JWT_SECRET)
1039
1053
  * AGORA_JWT_EXPIRY_SECONDS — JWT expiry in seconds (default: 3600)
1040
- * PORT WebSocket port (default: 3001); REST uses PORT+1
1054
+ * MAX_PEERS Maximum concurrent registered peers (default: 100)
1055
+ * MESSAGE_TTL_MS — Message buffer TTL in ms (default: 86400000 = 24h)
1056
+ * RATE_LIMIT_RPM — REST API requests per minute per IP (default: 60)
1057
+ * ALLOWED_ORIGINS — CORS origins, comma-separated or * (default: *)
1041
1058
  */
1042
1059
 
1043
1060
  interface RunRelayOptions {
1044
- /** WebSocket port (default from PORT env or 3001) */
1061
+ /** WebSocket port (default from RELAY_PORT or PORT env, or 3002) */
1045
1062
  wsPort?: number;
1046
- /** REST API port (default: wsPort + 1). Ignored if enableRest is false. */
1063
+ /** REST API port (default from REST_PORT env, or 3001). Ignored if enableRest is false. */
1047
1064
  restPort?: number;
1048
- /** Enable REST API (requires AGORA_RELAY_JWT_SECRET). Default: true if AGORA_RELAY_JWT_SECRET is set. */
1065
+ /** Enable REST API (requires JWT_SECRET or AGORA_RELAY_JWT_SECRET). Default: true if secret is set. */
1049
1066
  enableRest?: boolean;
1050
1067
  /** Relay server options (identity, storagePeers, storageDir) */
1051
1068
  relayOptions?: RelayServerOptions;
@@ -1112,6 +1129,10 @@ interface SendMessageOptions {
1112
1129
  type: MessageType;
1113
1130
  payload: unknown;
1114
1131
  inReplyTo?: string;
1132
+ /** Skip relay, send directly via HTTP only. Fails if peer has no URL or is unreachable. */
1133
+ direct?: boolean;
1134
+ /** Skip direct HTTP, always use relay even if peer has a URL. */
1135
+ relayOnly?: boolean;
1115
1136
  }
1116
1137
  interface SendMessageResult {
1117
1138
  ok: boolean;
@@ -1123,8 +1144,10 @@ interface DecodeInboundResult {
1123
1144
  envelope?: Envelope;
1124
1145
  reason?: string;
1125
1146
  }
1126
- type RelayMessageHandler = (envelope: Envelope) => void;
1147
+ /** Handler for relay messages. (envelope, fromPublicKey, fromName?) */
1127
1148
  type RelayMessageHandlerWithName = (envelope: Envelope, from: string, fromName?: string) => void;
1149
+ /** @deprecated Use RelayMessageHandlerWithName. Kept for backward compatibility. */
1150
+ type RelayMessageHandler = (envelope: Envelope) => void;
1128
1151
  interface Logger {
1129
1152
  debug(message: string): void;
1130
1153
  }
@@ -1155,11 +1178,16 @@ interface RelayClientFactory {
1155
1178
  declare class AgoraService {
1156
1179
  private config;
1157
1180
  private relayClient;
1158
- private relayMessageHandler;
1159
- private relayMessageHandlerWithName;
1181
+ private readonly onRelayMessage;
1160
1182
  private logger;
1161
1183
  private relayClientFactory;
1162
- constructor(config: AgoraServiceConfig, logger?: Logger, relayClientFactory?: RelayClientFactory);
1184
+ /**
1185
+ * @param config - Service config (identity, peers, optional relay)
1186
+ * @param onRelayMessage - Required callback for relay messages. Ensures no messages are lost between init and connect.
1187
+ * @param logger - Optional debug logger
1188
+ * @param relayClientFactory - Optional factory for relay client (for testing)
1189
+ */
1190
+ constructor(config: AgoraServiceConfig, onRelayMessage: RelayMessageHandlerWithName, logger?: Logger, relayClientFactory?: RelayClientFactory);
1163
1191
  /**
1164
1192
  * Send a signed message to a named peer.
1165
1193
  * Tries HTTP webhook first; falls back to relay if HTTP is unavailable.
@@ -1175,8 +1203,6 @@ declare class AgoraService {
1175
1203
  * Connect to the relay server.
1176
1204
  */
1177
1205
  connectRelay(url: string): Promise<void>;
1178
- setRelayMessageHandler(handler: RelayMessageHandler): void;
1179
- setRelayMessageHandlerWithName(handler: RelayMessageHandlerWithName): void;
1180
1206
  disconnectRelay(): Promise<void>;
1181
1207
  isRelayConnected(): boolean;
1182
1208
  /**