@rookdaemon/agora 0.4.6 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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\ntype ConfigPeer = ReturnType<typeof loadPeerConfig>['peers'][string];\n\nfunction resolvePeerEntry(peers: Record<string, ConfigPeer>, identifier: string): { key: string; peer: ConfigPeer } | undefined {\n const direct = peers[identifier];\n if (direct) {\n return { key: identifier, peer: direct };\n }\n\n for (const [key, peer] of Object.entries(peers)) {\n if (peer.publicKey === identifier || peer.name === identifier) {\n return { key, peer };\n }\n }\n\n return undefined;\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/update the peer (canonical key is full public key)\n const existingByPubKey = Object.entries(config.peers).find(([, peer]) => peer.publicKey === pubkey);\n if (existingByPubKey && existingByPubKey[0] !== pubkey) {\n delete config.peers[existingByPubKey[0]];\n }\n\n config.peers[pubkey] = {\n publicKey: pubkey,\n name,\n };\n\n if (url && token) {\n config.peers[pubkey].url = url;\n config.peers[pubkey].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 peerRef = 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 const resolved = resolvePeerEntry(config.peers, peerRef);\n if (!resolved) {\n console.error(`Error: Peer '${peerRef}' not found.`);\n process.exit(1);\n }\n\n delete config.peers[resolved.key];\n savePeerConfig(configPath, config);\n output({ \n status: 'removed',\n name: peerRef \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 config.peers[peer.publicKey] = {\n publicKey: peer.publicKey,\n name: peer.metadata?.name,\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 peerRef = 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 const resolved = resolvePeerEntry(config.peers, peerRef);\n if (!resolved) {\n console.error(`Error: Peer '${peerRef}' not found.`);\n process.exit(1);\n }\n\n const peer = resolved.peer;\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 '${peerRef}' 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: peerRef,\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: peerRef,\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: peerRef,\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: peerRef,\n type: messageType,\n transport: 'relay'\n }, options.pretty || false);\n } else {\n output({ \n status: 'failed',\n peer: peerRef,\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 '${peerRef}' 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 [, peer] of Object.entries(config.peers)) {\n const peerLabel = peer.name || peer.publicKey;\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: peerLabel,\n status: 'sent',\n transport: 'http',\n httpStatus: result.status,\n });\n } else {\n results.push({\n peer: peerLabel,\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: peerLabel,\n status: 'sent',\n transport: 'relay',\n });\n } else {\n results.push({\n peer: peerLabel,\n status: 'failed',\n transport: 'relay',\n error: result.error,\n });\n }\n } else {\n results.push({\n peer: peerLabel,\n status: 'unreachable',\n error: 'No HTTP endpoint and no relay configured',\n });\n }\n } catch (e) {\n results.push({\n peer: peerLabel,\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 peerRef = 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 const resolved = resolvePeerEntry(config.peers, peerRef);\n if (!resolved) {\n console.error(`Error: Peer '${peerRef}' not found.`);\n process.exit(1);\n }\n\n const peer = resolved.peer;\n\n if (!peer.url) {\n console.error(`Error: Peer '${peerRef}' 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: peerRef,\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,MAC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AACH,kBAAM,uBAAuB,eAAe,OAAO;AACnD;AAAA,UACF,KAAK;AACH,kBAAM,uBAAuB,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 { compactInlineReferences, expand, expandInlineReferences, 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\ntype ConfigPeer = ReturnType<typeof loadPeerConfig>['peers'][string];\n\nfunction resolvePeerEntry(peers: Record<string, ConfigPeer>, identifier: string): { key: string; peer: ConfigPeer } | undefined {\n const expanded = expand(identifier, peers);\n if (expanded && peers[expanded]) {\n return { key: expanded, peer: peers[expanded] };\n }\n\n const direct = peers[identifier];\n if (direct) {\n return { key: identifier, peer: direct };\n }\n\n for (const [key, peer] of Object.entries(peers)) {\n if (peer.publicKey === identifier || peer.name === identifier) {\n return { key, peer };\n }\n }\n\n return undefined;\n}\n\nfunction compactPayloadTextReferences(payload: unknown, peers: Record<string, ConfigPeer>): unknown {\n if (!payload || typeof payload !== 'object') {\n return payload;\n }\n if ('text' in payload && typeof (payload as Record<string, unknown>).text === 'string') {\n return {\n ...(payload as Record<string, unknown>),\n text: compactInlineReferences((payload as { text: string }).text, peers),\n };\n }\n return payload;\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/update the peer (canonical key is full public key)\n const existingByPubKey = Object.entries(config.peers).find(([, peer]) => peer.publicKey === pubkey);\n if (existingByPubKey && existingByPubKey[0] !== pubkey) {\n delete config.peers[existingByPubKey[0]];\n }\n\n config.peers[pubkey] = {\n publicKey: pubkey,\n name,\n };\n\n if (url && token) {\n config.peers[pubkey].url = url;\n config.peers[pubkey].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 peerRef = 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 const resolved = resolvePeerEntry(config.peers, peerRef);\n if (!resolved) {\n console.error(`Error: Peer '${peerRef}' not found.`);\n process.exit(1);\n }\n\n delete config.peers[resolved.key];\n savePeerConfig(configPath, config);\n output({ \n status: 'removed',\n name: peerRef \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 config.peers[peer.publicKey] = {\n publicKey: peer.publicKey,\n name: peer.metadata?.name,\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 peerRef = 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 const resolved = resolvePeerEntry(config.peers, peerRef);\n if (!resolved) {\n console.error(`Error: Peer '${peerRef}' not found.`);\n process.exit(1);\n }\n\n const peer = resolved.peer;\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: expandInlineReferences(args.slice(1).join(' '), config.peers) };\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 '${peerRef}' 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: peerRef,\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: peerRef,\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: peerRef,\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: peerRef,\n type: messageType,\n transport: 'relay'\n }, options.pretty || false);\n } else {\n output({ \n status: 'failed',\n peer: peerRef,\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 '${peerRef}' 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 from: result.envelope.from,\n to: result.envelope.to,\n type: result.envelope.type,\n payload: compactPayloadTextReferences(result.envelope.payload, config.peers),\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 * Disabled to enforce strict peer-to-peer semantics.\n */\nasync function handleAnnounce(options: CliOptions & { name?: string; version?: string }): Promise<void> {\n void options;\n console.error('Error: `agora announce` is disabled. Agora now supports strict peer-to-peer only (no all/broadcast).');\n console.error('Use: agora send <peer> --type announce --payload <json>');\n process.exit(1);\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 peerRef = 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 const resolved = resolvePeerEntry(config.peers, peerRef);\n if (!resolved) {\n console.error(`Error: Peer '${peerRef}' not found.`);\n process.exit(1);\n }\n\n const peer = resolved.peer;\n\n if (!peer.url) {\n console.error(`Error: Peer '${peerRef}' 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: peerRef,\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 from: envelope.from,\n to: envelope.to,\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 * 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 Date.now(),\n undefined,\n [this.identity.publicKey]\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.from;\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.from !== 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":";;;;;;;;;;;;;;;;;;;;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,MAAM,mEAAmE;AACjF,oBAAQ,KAAK,CAAC;AAAA,QAClB;AACA;AAAA,MACF,KAAK;AACH,cAAM,WAAW,CAAC,YAAY,GAAG,aAAa,GAAG,OAAO;AACxD;AAAA,MACF,KAAK;AACH,qBAAa,CAAC,YAAY,GAAG,aAAa,EAAE,OAAO,OAAO,GAAG,OAAO;AACpE;AAAA,MACF,KAAK;AACH,cAAM,YAAY,OAAO;AACzB;AAAA,MACF,KAAK;AACH,cAAM,YAAY,OAAO;AACzB;AAAA,MACF,KAAK;AACH,gBAAQ,YAAY;AAAA,UAClB,KAAK;AACH,kBAAM,uBAAuB,eAAe,OAAO;AACnD;AAAA,UACF,KAAK;AACH,kBAAM,uBAAuB,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"]}
package/dist/index.d.ts CHANGED
@@ -60,8 +60,10 @@ interface Envelope<T = unknown> {
60
60
  id: string;
61
61
  /** Message type */
62
62
  type: MessageType;
63
- /** Sender's public key (hex-encoded ed25519) */
64
- sender: string;
63
+ /** Sender peer ID (full ID) */
64
+ from: string;
65
+ /** Recipient peer IDs (full IDs) */
66
+ to: string[];
65
67
  /** Unix timestamp (ms) when the message was created */
66
68
  timestamp: number;
67
69
  /** Optional: ID of the message this is responding to */
@@ -75,7 +77,7 @@ interface Envelope<T = unknown> {
75
77
  * Canonical form of an envelope for signing/hashing.
76
78
  * Deterministic JSON serialization: recursively sorted keys, no whitespace.
77
79
  */
78
- declare function canonicalize(type: MessageType, sender: string, timestamp: number, payload: unknown, inReplyTo?: string): string;
80
+ declare function canonicalize(type: MessageType, from: string, to: string[], timestamp: number, payload: unknown, inReplyTo?: string): string;
79
81
  /**
80
82
  * Compute the content-addressed ID for a message.
81
83
  */
@@ -83,14 +85,15 @@ declare function computeId(canonical: string): string;
83
85
  /**
84
86
  * Create a signed envelope.
85
87
  * @param type - Message type
86
- * @param sender - Sender's public key (hex)
88
+ * @param from - Sender's public key (hex)
87
89
  * @param privateKey - Sender's private key (hex) for signing
88
90
  * @param payload - The message payload
89
91
  * @param timestamp - Timestamp for the envelope (ms), defaults to Date.now()
90
92
  * @param inReplyTo - Optional ID of the message being replied to
93
+ * @param to - Recipient peer ID(s)
91
94
  * @returns A signed Envelope
92
95
  */
93
- declare function createEnvelope<T>(type: MessageType, sender: string, privateKey: string, payload: T, timestamp?: number, inReplyTo?: string): Envelope<T>;
96
+ declare function createEnvelope<T>(type: MessageType, from: string, privateKey: string, payload: T, timestamp?: number, inReplyTo?: string, to?: string | string[]): Envelope<T>;
94
97
  /**
95
98
  * Verify an envelope's integrity and authenticity.
96
99
  * Checks:
@@ -350,7 +353,7 @@ declare class DiscoveryService {
350
353
  announce(capabilities: Capability[], metadata?: {
351
354
  name?: string;
352
355
  version?: string;
353
- }): Envelope<CapabilityAnnouncePayload>;
356
+ }, recipients?: string[]): Envelope<CapabilityAnnouncePayload>;
354
357
  /**
355
358
  * Handle an incoming capability_announce message.
356
359
  * Updates the peer store with the announced capabilities.
@@ -753,7 +756,7 @@ declare class RelayServer extends EventEmitter {
753
756
  * Messages sent from client to relay server
754
757
  */
755
758
  interface RelayClientMessage {
756
- type: 'register' | 'message' | 'broadcast' | 'ping';
759
+ type: 'register' | 'message' | 'ping';
757
760
  publicKey?: string;
758
761
  name?: string;
759
762
  to?: string;
@@ -852,13 +855,6 @@ declare class RelayClient extends EventEmitter {
852
855
  ok: boolean;
853
856
  error?: string;
854
857
  }>;
855
- /**
856
- * Broadcast a message to all connected peers
857
- */
858
- broadcast(envelope: Envelope): Promise<{
859
- ok: boolean;
860
- error?: string;
861
- }>;
862
858
  /**
863
859
  * Get list of currently online peers
864
860
  */
@@ -1058,10 +1054,11 @@ interface RelayInterface {
1058
1054
  /**
1059
1055
  * Envelope creation function interface (matches createEnvelope from message/envelope).
1060
1056
  */
1061
- type CreateEnvelopeFn = (type: string, sender: string, privateKey: string, payload: unknown, timestamp?: number, inReplyTo?: string) => {
1057
+ type CreateEnvelopeFn = (type: string, from: string, to: string[], privateKey: string, payload: unknown, timestamp?: number, inReplyTo?: string) => {
1062
1058
  id: string;
1063
1059
  type: string;
1064
- sender: string;
1060
+ from: string;
1061
+ to: string[];
1065
1062
  timestamp: number;
1066
1063
  payload: unknown;
1067
1064
  signature: string;
@@ -1125,6 +1122,32 @@ declare function runRelay(options?: RunRelayOptions): Promise<{
1125
1122
  * @returns "..." followed by the last 8 characters of the key
1126
1123
  */
1127
1124
  declare function shortKey(publicKey: string): string;
1125
+ interface PeerReferenceEntry {
1126
+ publicKey: string;
1127
+ name?: string;
1128
+ }
1129
+ type PeerReferenceDirectory = Record<string, PeerReferenceEntry> | Map<string, PeerReferenceEntry> | PeerReferenceEntry[];
1130
+ /**
1131
+ * Shorten a full peer ID for display/reference.
1132
+ * Priority:
1133
+ * - Unique configured name => "name"
1134
+ * - Duplicate configured name => "name...<last8>"
1135
+ * - Unknown/no-name => "...<last8>"
1136
+ */
1137
+ declare function shorten(id: string, directory?: PeerReferenceDirectory): string;
1138
+ /**
1139
+ * Expand a short peer reference to a full ID.
1140
+ * Supports: full ID, unique name, ...last8, and name...last8.
1141
+ */
1142
+ declare function expand(shortId: string, directory: PeerReferenceDirectory): string | undefined;
1143
+ /**
1144
+ * Expand inline @references in text to full IDs using configured peers.
1145
+ */
1146
+ declare function expandInlineReferences(text: string, directory: PeerReferenceDirectory): string;
1147
+ /**
1148
+ * Compact inline @<full-id> references for rendering.
1149
+ */
1150
+ declare function compactInlineReferences(text: string, directory: PeerReferenceDirectory): string;
1128
1151
  /**
1129
1152
  * Resolves the name to broadcast when connecting to a relay.
1130
1153
  * Priority order:
@@ -1759,4 +1782,4 @@ declare function syncReputationFromPeer(agentPublicKey: string, domain: string,
1759
1782
  skipped: number;
1760
1783
  }>;
1761
1784
 
1762
- export { type AgoraConfig, type AgoraIdentity, type AgoraPeerConfig, AgoraService, type AgoraServiceConfig, type AnnouncePayload, type AuthenticatedRequest, type BootstrapConfig, type BufferedMessage, type Capability, type CapabilityAnnouncePayload, type CapabilityQueryPayload, type CapabilityResponsePayload, type CommitRecord, type CreateEnvelopeFn, DEFAULT_BOOTSTRAP_RELAYS, type DecodeInboundResult, type DiscoverPayload, type DiscoverResponsePayload, DiscoveryService, type Envelope, IGNORED_FILE_NAME, IgnoredPeersManager, type JwtPayload, type KeyPair, type Logger, MessageBuffer, MessageStore, type MessageType, type PaperDiscoveryPayload, type Peer, type PeerConfig, type PeerConfigFile, type PeerDiscoveryConfig, type PeerDiscoveryEvents, PeerDiscoveryService, type PeerListRequestPayload, type PeerListResponsePayload, type PeerReferralPayload, PeerStore, RelayClient, type RelayClientConfig, type RelayClientEvents, type RelayClientFactory, type RelayClientLike, type RelayClientMessage, type RelayConfig, type RelayEnvelopeDedupOptions, type RelayInterface, type RelayMessageHandler, type RelayMessageHandlerWithName, type RelayPeer, type RelayRateLimitOptions, RelayServer, type RelayServerEvents, type RelayServerMessage, type RelayServerOptions, type ReplyToEnvelopeOptions, type ReputationQuery, type ReputationResponse, ReputationStore, type RestSession, type RevealRecord, type RevocationRecord, type RunRelayOptions, type SendMessageOptions, type SendMessageResult, type StoredMessage, type TransportConfig, type TrustScore, type TrustScoreOptions, type ValidationResult, type VerificationRecord, type VerifyEnvelopeFn, canonicalize, computeAllTrustScores, computeId, computeTrustScore, computeTrustScores, createCapability, createCommit, createEnvelope, createRestRouter, createReveal, createToken, createVerification, decay, decodeInboundEnvelope, exportKeyPair, formatDisplayName, generateKeyPair, getDefaultBootstrapRelay, getDefaultConfigPath, getIgnoredPeersPath, handleReputationQuery, hashPrediction, importKeyPair, initPeerConfig, loadAgoraConfig, loadAgoraConfigAsync, loadIgnoredPeers, loadPeerConfig, parseBootstrapRelay, requireAuth, resolveBroadcastName, revokeToken, runRelay, saveIgnoredPeers, savePeerConfig, sendToPeer, shortKey, signMessage, syncReputationFromPeer, validateCapability, validateCommitRecord, validatePeerListRequest, validatePeerListResponse, validatePeerReferral, validateRevealRecord, validateVerificationRecord, verifyEnvelope, verifyReveal, verifySignature, verifyVerificationSignature };
1785
+ export { type AgoraConfig, type AgoraIdentity, type AgoraPeerConfig, AgoraService, type AgoraServiceConfig, type AnnouncePayload, type AuthenticatedRequest, type BootstrapConfig, type BufferedMessage, type Capability, type CapabilityAnnouncePayload, type CapabilityQueryPayload, type CapabilityResponsePayload, type CommitRecord, type CreateEnvelopeFn, DEFAULT_BOOTSTRAP_RELAYS, type DecodeInboundResult, type DiscoverPayload, type DiscoverResponsePayload, DiscoveryService, type Envelope, IGNORED_FILE_NAME, IgnoredPeersManager, type JwtPayload, type KeyPair, type Logger, MessageBuffer, MessageStore, type MessageType, type PaperDiscoveryPayload, type Peer, type PeerConfig, type PeerConfigFile, type PeerDiscoveryConfig, type PeerDiscoveryEvents, PeerDiscoveryService, type PeerListRequestPayload, type PeerListResponsePayload, type PeerReferralPayload, PeerStore, RelayClient, type RelayClientConfig, type RelayClientEvents, type RelayClientFactory, type RelayClientLike, type RelayClientMessage, type RelayConfig, type RelayEnvelopeDedupOptions, type RelayInterface, type RelayMessageHandler, type RelayMessageHandlerWithName, type RelayPeer, type RelayRateLimitOptions, RelayServer, type RelayServerEvents, type RelayServerMessage, type RelayServerOptions, type ReplyToEnvelopeOptions, type ReputationQuery, type ReputationResponse, ReputationStore, type RestSession, type RevealRecord, type RevocationRecord, type RunRelayOptions, type SendMessageOptions, type SendMessageResult, type StoredMessage, type TransportConfig, type TrustScore, type TrustScoreOptions, type ValidationResult, type VerificationRecord, type VerifyEnvelopeFn, canonicalize, compactInlineReferences, computeAllTrustScores, computeId, computeTrustScore, computeTrustScores, createCapability, createCommit, createEnvelope, createRestRouter, createReveal, createToken, createVerification, decay, decodeInboundEnvelope, expand, expandInlineReferences, exportKeyPair, formatDisplayName, generateKeyPair, getDefaultBootstrapRelay, getDefaultConfigPath, getIgnoredPeersPath, handleReputationQuery, hashPrediction, importKeyPair, initPeerConfig, loadAgoraConfig, loadAgoraConfigAsync, loadIgnoredPeers, loadPeerConfig, parseBootstrapRelay, requireAuth, resolveBroadcastName, revokeToken, runRelay, saveIgnoredPeers, savePeerConfig, sendToPeer, shortKey, shorten, signMessage, syncReputationFromPeer, validateCapability, validateCommitRecord, validatePeerListRequest, validatePeerListResponse, validatePeerReferral, validateRevealRecord, validateVerificationRecord, verifyEnvelope, verifyReveal, verifySignature, verifyVerificationSignature };