@rookdaemon/agora 0.6.2 → 0.6.4
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/{chunk-MGIGMVXH.js → chunk-7MI2H3DB.js} +28 -13
- package/dist/chunk-7MI2H3DB.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +64 -12
- package/dist/index.js +109 -10
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-MGIGMVXH.js.map +0 -1
|
@@ -229,14 +229,14 @@ function parseConfig(config) {
|
|
|
229
229
|
};
|
|
230
230
|
const peers = {};
|
|
231
231
|
if (config.peers && typeof config.peers === "object") {
|
|
232
|
-
for (const entry of Object.
|
|
232
|
+
for (const [key, entry] of Object.entries(config.peers)) {
|
|
233
233
|
const peer = entry;
|
|
234
234
|
if (peer && typeof peer.publicKey === "string") {
|
|
235
235
|
peers[peer.publicKey] = {
|
|
236
236
|
publicKey: peer.publicKey,
|
|
237
237
|
url: typeof peer.url === "string" ? peer.url : void 0,
|
|
238
238
|
token: typeof peer.token === "string" ? peer.token : void 0,
|
|
239
|
-
name: typeof peer.name === "string" ? peer.name : void 0
|
|
239
|
+
name: typeof peer.name === "string" ? peer.name : key !== peer.publicKey ? key : void 0
|
|
240
240
|
};
|
|
241
241
|
}
|
|
242
242
|
}
|
|
@@ -797,7 +797,7 @@ function parseBootstrapRelay(url, publicKey) {
|
|
|
797
797
|
|
|
798
798
|
// src/utils.ts
|
|
799
799
|
function shortKey(publicKey) {
|
|
800
|
-
return "
|
|
800
|
+
return "@" + publicKey.slice(-8);
|
|
801
801
|
}
|
|
802
802
|
function toDirectoryEntries(directory) {
|
|
803
803
|
if (!directory) {
|
|
@@ -818,9 +818,9 @@ function shorten(id, directory) {
|
|
|
818
818
|
const suffix = id.slice(-8);
|
|
819
819
|
const entry = findById(id, directory);
|
|
820
820
|
if (!entry?.name) {
|
|
821
|
-
return
|
|
821
|
+
return `@${suffix}`;
|
|
822
822
|
}
|
|
823
|
-
return `${entry.name}
|
|
823
|
+
return `${entry.name}@${suffix}`;
|
|
824
824
|
}
|
|
825
825
|
function expand(shortId, directory) {
|
|
826
826
|
const entries = toDirectoryEntries(directory);
|
|
@@ -832,6 +832,24 @@ function expand(shortId, directory) {
|
|
|
832
832
|
if (direct) {
|
|
833
833
|
return direct.publicKey;
|
|
834
834
|
}
|
|
835
|
+
const namedAtSuffix = token.match(/^(.+)@([0-9a-fA-F]{8})$/);
|
|
836
|
+
if (namedAtSuffix) {
|
|
837
|
+
const [, name, suffix] = namedAtSuffix;
|
|
838
|
+
const matches = entries.filter((entry) => entry.name === name && entry.publicKey.toLowerCase().endsWith(suffix.toLowerCase()));
|
|
839
|
+
if (matches.length === 1) {
|
|
840
|
+
return matches[0].publicKey;
|
|
841
|
+
}
|
|
842
|
+
return void 0;
|
|
843
|
+
}
|
|
844
|
+
const atSuffixOnly = token.match(/^@([0-9a-fA-F]{8})$/);
|
|
845
|
+
if (atSuffixOnly) {
|
|
846
|
+
const [, suffix] = atSuffixOnly;
|
|
847
|
+
const matches = entries.filter((entry) => entry.publicKey.toLowerCase().endsWith(suffix.toLowerCase()));
|
|
848
|
+
if (matches.length === 1) {
|
|
849
|
+
return matches[0].publicKey;
|
|
850
|
+
}
|
|
851
|
+
return void 0;
|
|
852
|
+
}
|
|
835
853
|
const namedWithSuffix = token.match(/^(.+)\.\.\.([0-9a-fA-F]{8})$/);
|
|
836
854
|
if (namedWithSuffix) {
|
|
837
855
|
const [, name, suffix] = namedWithSuffix;
|
|
@@ -884,14 +902,11 @@ function extractTextFromPayload(payload) {
|
|
|
884
902
|
function sanitizeText(text) {
|
|
885
903
|
return text.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g, "").replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/g, "\uFFFD").replace(/(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
|
|
886
904
|
}
|
|
887
|
-
function resolveDisplayName(publicKey,
|
|
905
|
+
function resolveDisplayName(publicKey, _peerName, directory) {
|
|
888
906
|
const entry = findById(publicKey, directory);
|
|
889
907
|
if (entry?.name) {
|
|
890
908
|
return entry.name;
|
|
891
909
|
}
|
|
892
|
-
if (peerName && !peerName.startsWith("...")) {
|
|
893
|
-
return sanitizeText(peerName);
|
|
894
|
-
}
|
|
895
910
|
return void 0;
|
|
896
911
|
}
|
|
897
912
|
function resolveBroadcastName(config, cliName) {
|
|
@@ -910,10 +925,10 @@ function resolveBroadcastName(config, cliName) {
|
|
|
910
925
|
}
|
|
911
926
|
function formatDisplayName(name, publicKey) {
|
|
912
927
|
const suffix = publicKey.slice(-8);
|
|
913
|
-
if (!name || name.trim() === "" || name.startsWith("...")) {
|
|
914
|
-
return
|
|
928
|
+
if (!name || name.trim() === "" || name.startsWith("...") || name.startsWith("@")) {
|
|
929
|
+
return `@${suffix}`;
|
|
915
930
|
}
|
|
916
|
-
return `${name}
|
|
931
|
+
return `${name}@${suffix}`;
|
|
917
932
|
}
|
|
918
933
|
function formatConversationLine(entry) {
|
|
919
934
|
const ts = new Date(entry.timestamp).toISOString();
|
|
@@ -1492,4 +1507,4 @@ export {
|
|
|
1492
1507
|
computeTrustScores,
|
|
1493
1508
|
computeAllTrustScores
|
|
1494
1509
|
};
|
|
1495
|
-
//# sourceMappingURL=chunk-
|
|
1510
|
+
//# sourceMappingURL=chunk-7MI2H3DB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/transport/peer-config.ts","../src/transport/http.ts","../src/transport/relay.ts","../src/config.ts","../src/relay/client.ts","../src/discovery/peer-discovery.ts","../src/discovery/bootstrap.ts","../src/utils.ts","../src/reputation/types.ts","../src/reputation/store.ts","../src/reputation/verification.ts","../src/reputation/commit-reveal.ts","../src/reputation/scoring.ts"],"sourcesContent":["import { readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { generateKeyPair } from '../identity/keypair';\n\nexport interface PeerConfigFile {\n identity: {\n publicKey: string;\n privateKey: string;\n name?: string;\n };\n relay?: string | {\n url: string;\n name?: string;\n };\n peers: Record<string, {\n url?: string;\n token?: string;\n publicKey: string;\n name?: string;\n }>;\n}\n\n/**\n * Load peer configuration from a JSON file.\n * @param path - Path to the config file\n * @returns The parsed configuration\n * @throws Error if file doesn't exist or contains invalid JSON\n */\nexport function loadPeerConfig(path: string): PeerConfigFile {\n const content = readFileSync(path, 'utf-8');\n return JSON.parse(content) as PeerConfigFile;\n}\n\n/**\n * Save peer configuration to a JSON file.\n * @param path - Path to the config file\n * @param config - The configuration to save\n */\nexport function savePeerConfig(path: string, config: PeerConfigFile): void {\n const content = JSON.stringify(config, null, 2);\n writeFileSync(path, content, 'utf-8');\n}\n\n/**\n * Initialize peer configuration, generating a new keypair if the file doesn't exist.\n * If the file exists, loads and returns it.\n * @param path - Path to the config file\n * @returns The configuration (loaded or newly created)\n */\nexport function initPeerConfig(path: string): PeerConfigFile {\n if (existsSync(path)) {\n return loadPeerConfig(path);\n }\n\n // Generate new keypair and create initial config\n const identity = generateKeyPair();\n const config: PeerConfigFile = {\n identity,\n peers: {},\n };\n\n savePeerConfig(path, config);\n return config;\n}\n","import { createEnvelope, verifyEnvelope, type Envelope, type MessageType } from '../message/envelope';\r\n\r\nexport interface PeerConfig {\r\n /** Peer's webhook URL, e.g. http://localhost:18790/hooks (undefined for relay-only peers) */\r\n url?: string;\r\n /** Peer's webhook auth token (undefined for relay-only peers) */\r\n token?: string;\r\n /** Peer's public key (hex) for verifying responses */\r\n publicKey: string;\r\n /** Optional convenience alias only (not identity) */\r\n name?: string;\r\n}\r\n\r\nexport interface TransportConfig {\r\n /** This agent's keypair */\r\n identity: { publicKey: string; privateKey: string };\r\n /** Known peers */\r\n peers: Map<string, PeerConfig>;\r\n}\r\n\r\n/**\r\n * Send a signed envelope to a peer via HTTP webhook.\r\n * Creates the envelope, signs it, and POSTs to the peer's /hooks/agent endpoint.\r\n * Returns the HTTP status code.\r\n */\r\nexport async function sendToPeer(\r\n config: TransportConfig,\r\n peerPublicKey: string,\r\n type: MessageType,\r\n payload: unknown,\r\n inReplyTo?: string,\r\n allRecipients?: string[],\r\n): Promise<{ ok: boolean; status: number; error?: string }> {\r\n // Look up peer config\r\n const peer = config.peers.get(peerPublicKey);\r\n if (!peer) {\r\n return { ok: false, status: 0, error: 'Unknown peer' };\r\n }\r\n\r\n // Relay-only peer — no webhook URL configured\r\n if (!peer.url) {\r\n return { ok: false, status: 0, error: 'No webhook URL configured' };\r\n }\r\n\r\n // Create and sign the envelope\r\n const envelope = createEnvelope(\r\n type,\r\n config.identity.publicKey,\r\n config.identity.privateKey,\r\n payload,\r\n Date.now(),\r\n inReplyTo,\r\n allRecipients ?? [peerPublicKey]\r\n );\r\n\r\n // Encode envelope as base64url\r\n const envelopeJson = JSON.stringify(envelope);\r\n const envelopeBase64 = Buffer.from(envelopeJson).toString('base64url');\r\n\r\n // Construct webhook payload\r\n const webhookPayload = {\r\n message: `[AGORA_ENVELOPE]${envelopeBase64}`,\r\n name: 'Agora',\r\n sessionKey: `agora:${envelope.from.substring(0, 16)}`,\r\n deliver: false,\r\n };\r\n\r\n // Build headers — only include Authorization when a token is configured\r\n const headers: Record<string, string> = {\r\n 'Content-Type': 'application/json',\r\n };\r\n if (peer.token) {\r\n headers['Authorization'] = `Bearer ${peer.token}`;\r\n }\r\n\r\n const requestBody = JSON.stringify(webhookPayload);\r\n\r\n // Send HTTP POST (retry once on network error, not on 4xx/5xx)\r\n for (let attempt = 0; attempt < 2; attempt++) {\r\n try {\r\n const response = await fetch(`${peer.url}/agent`, {\r\n method: 'POST',\r\n headers,\r\n body: requestBody,\r\n });\r\n\r\n return {\r\n ok: response.ok,\r\n status: response.status,\r\n error: response.ok ? undefined : await response.text(),\r\n };\r\n } catch (err) {\r\n if (attempt === 1) {\r\n return {\r\n ok: false,\r\n status: 0,\r\n error: err instanceof Error ? err.message : String(err),\r\n };\r\n }\r\n // First attempt failed with network error — retry once\r\n }\r\n }\r\n\r\n // Unreachable, but satisfies TypeScript\r\n return { ok: false, status: 0, error: 'Unexpected send failure' };\r\n}\r\n\r\n/**\r\n * Decode and verify an inbound Agora envelope from a webhook message.\r\n * Expects the message to start with [AGORA_ENVELOPE] followed by base64.\r\n * Returns the verified envelope or an error.\r\n */\r\nexport function decodeInboundEnvelope(\r\n message: string,\r\n knownPeers: Map<string, PeerConfig>\r\n): { ok: true; envelope: Envelope } | { ok: false; reason: string } {\r\n // Check for AGORA_ENVELOPE prefix\r\n const prefix = '[AGORA_ENVELOPE]';\r\n if (!message.startsWith(prefix)) {\r\n return { ok: false, reason: 'not_agora_message' };\r\n }\r\n\r\n // Extract base64 payload\r\n const base64Payload = message.substring(prefix.length);\r\n \r\n // Check for empty payload\r\n if (!base64Payload) {\r\n return { ok: false, reason: 'invalid_base64' };\r\n }\r\n \r\n // Decode base64\r\n let envelopeJson: string;\r\n try {\r\n const decoded = Buffer.from(base64Payload, 'base64url');\r\n // Check if decoded buffer is empty or contains invalid data\r\n if (decoded.length === 0) {\r\n return { ok: false, reason: 'invalid_base64' };\r\n }\r\n envelopeJson = decoded.toString('utf-8');\r\n } catch {\r\n return { ok: false, reason: 'invalid_base64' };\r\n }\r\n\r\n // Parse JSON\r\n let envelope: Envelope;\r\n try {\r\n envelope = JSON.parse(envelopeJson);\r\n } catch {\r\n return { ok: false, reason: 'invalid_json' };\r\n }\r\n\r\n // Verify envelope integrity\r\n const verification = verifyEnvelope(envelope);\r\n if (!verification.valid) {\r\n return { ok: false, reason: verification.reason || 'verification_failed' };\r\n }\r\n\r\n // Check if sender is a known peer\r\n const senderKnown = knownPeers.has(envelope.from);\r\n if (!senderKnown) {\r\n return { ok: false, reason: 'unknown_sender' };\r\n }\r\n\r\n return { ok: true, envelope };\r\n}\r\n","import WebSocket from 'ws';\nimport { createEnvelope, type Envelope, type MessageType } from '../message/envelope';\n\n/** Minimal interface for a connected relay client (avoids importing full RelayClient) */\nexport interface RelayClientSender {\n connected(): boolean;\n send(to: string, envelope: Envelope): Promise<{ ok: boolean; error?: string }>;\n}\n\nexport interface RelayTransportConfig {\n /** This agent's keypair */\n identity: { publicKey: string; privateKey: string };\n /** Relay server WebSocket URL (e.g., wss://agora-relay.lbsa71.net) */\n relayUrl: string;\n /** Optional persistent relay client (if provided, will use it instead of connect-per-message) */\n relayClient?: RelayClientSender;\n}\n\n/**\n * Send a signed envelope to a peer via relay server.\n * If a persistent relayClient is provided in the config, uses that.\n * Otherwise, connects to relay, registers, sends message, and disconnects.\n */\nexport async function sendViaRelay(\n config: RelayTransportConfig,\n peerPublicKey: string,\n type: MessageType,\n payload: unknown,\n inReplyTo?: string,\n allRecipients?: string[],\n): Promise<{ ok: boolean; error?: string }> {\n // If a persistent relay client is available, use it\n if (config.relayClient && config.relayClient.connected()) {\n const envelope = createEnvelope(\n type,\n config.identity.publicKey,\n config.identity.privateKey,\n payload,\n Date.now(),\n inReplyTo,\n allRecipients ?? [peerPublicKey]\n );\n return config.relayClient.send(peerPublicKey, envelope);\n }\n\n // Otherwise, fall back to connect-per-message\n return new Promise((resolve) => {\n const ws = new WebSocket(config.relayUrl);\n let registered = false;\n let messageSent = false;\n let resolved = false;\n\n // Helper to resolve once\n const resolveOnce = (result: { ok: boolean; error?: string }): void => {\n if (!resolved) {\n resolved = true;\n clearTimeout(timeout);\n resolve(result);\n }\n };\n\n // Set timeout for the entire operation\n const timeout = setTimeout(() => {\n if (!messageSent) {\n ws.close();\n resolveOnce({ ok: false, error: 'Relay connection timeout' });\n }\n }, 10000); // 10 second timeout\n\n ws.on('open', () => {\n // Send register message\n const registerMsg = {\n type: 'register',\n publicKey: config.identity.publicKey,\n };\n ws.send(JSON.stringify(registerMsg));\n });\n\n ws.on('message', (data: WebSocket.Data) => {\n try {\n const msg = JSON.parse(data.toString());\n\n if (msg.type === 'registered' && !registered) {\n registered = true;\n\n // Create and sign the envelope\n const envelope: Envelope = createEnvelope(\n type,\n config.identity.publicKey,\n config.identity.privateKey,\n payload,\n Date.now(),\n inReplyTo,\n allRecipients ?? [peerPublicKey]\n );\n\n // Send message via relay\n const relayMsg = {\n type: 'message',\n to: peerPublicKey,\n envelope,\n };\n ws.send(JSON.stringify(relayMsg));\n messageSent = true;\n\n // Close connection after sending\n setTimeout(() => {\n ws.close();\n resolveOnce({ ok: true });\n }, 100); // Small delay to ensure message is sent\n } else if (msg.type === 'error') {\n ws.close();\n resolveOnce({ ok: false, error: msg.message || 'Relay server error' });\n }\n } catch (err) {\n ws.close();\n resolveOnce({ ok: false, error: err instanceof Error ? err.message : String(err) });\n }\n });\n\n ws.on('error', (err) => {\n ws.close();\n resolveOnce({ ok: false, error: err.message });\n });\n\n ws.on('close', () => {\n if (!messageSent) {\n resolveOnce({ ok: false, error: 'Connection closed before message sent' });\n }\n });\n });\n}\n","import { readFileSync, existsSync, readdirSync, mkdirSync, writeFileSync } from 'node:fs';\r\nimport { readFile } from 'node:fs/promises';\r\nimport { resolve, join, dirname } from 'node:path';\r\nimport { homedir } from 'node:os';\r\n\r\n/**\r\n * Normalized relay configuration (supports both string and object in config file).\r\n */\r\nexport interface RelayConfig {\r\n url: string;\r\n autoConnect: boolean;\r\n name?: string;\r\n reconnectMaxMs?: number;\r\n}\r\n\r\n/**\r\n * Peer entry in config (webhook URL, token, public key).\r\n */\r\nexport interface AgoraPeerConfig {\r\n publicKey: string;\r\n /** Webhook URL (undefined for relay-only peers) */\r\n url?: string;\r\n /** Webhook auth token (undefined for relay-only peers) */\r\n token?: string;\r\n name?: string;\r\n}\r\n\r\n/**\r\n * Identity with optional display name (e.g. for relay registration).\r\n */\r\nexport interface AgoraIdentity {\r\n publicKey: string;\r\n privateKey: string;\r\n name?: string;\r\n}\r\n\r\n/**\r\n * Canonical Agora configuration shape.\r\n * Use loadAgoraConfig() to load from file with normalized relay.\r\n */\r\nexport interface AgoraConfig {\r\n identity: AgoraIdentity;\r\n peers: Record<string, AgoraPeerConfig>;\r\n relay?: RelayConfig;\r\n}\r\n\r\n/**\r\n * Default config file path: AGORA_CONFIG env or ~/.config/agora/config.json\r\n */\r\nexport function getDefaultConfigPath(): string {\r\n if (process.env.AGORA_CONFIG) {\r\n return resolve(process.env.AGORA_CONFIG);\r\n }\r\n return resolve(homedir(), '.config', 'agora', 'config.json');\r\n}\r\n\r\n/**\r\n * Parse and normalize config from a JSON object (shared by sync and async loaders).\r\n */\r\nfunction parseConfig(config: Record<string, unknown>): AgoraConfig {\r\n const rawIdentity = config.identity as Record<string, unknown> | undefined;\r\n if (!rawIdentity?.publicKey || !rawIdentity?.privateKey) {\r\n throw new Error('Invalid config: missing identity.publicKey or identity.privateKey');\r\n }\r\n const identity: AgoraIdentity = {\r\n publicKey: rawIdentity.publicKey as string,\r\n privateKey: rawIdentity.privateKey as string,\r\n name: typeof rawIdentity.name === 'string' ? rawIdentity.name : undefined,\r\n };\r\n\r\n const peers: Record<string, AgoraPeerConfig> = {};\r\n if (config.peers && typeof config.peers === 'object') {\r\n for (const [key, entry] of Object.entries(config.peers)) {\r\n const peer = entry as Record<string, unknown>;\r\n if (peer && typeof peer.publicKey === 'string') {\r\n peers[peer.publicKey as string] = {\r\n publicKey: peer.publicKey as string,\r\n url: typeof peer.url === 'string' ? peer.url : undefined,\r\n token: typeof peer.token === 'string' ? peer.token : undefined,\r\n name: typeof peer.name === 'string' ? peer.name : (key !== peer.publicKey ? key : undefined),\r\n };\r\n }\r\n }\r\n }\r\n\r\n let relay: RelayConfig | undefined;\r\n const rawRelay = config.relay;\r\n if (typeof rawRelay === 'string') {\r\n relay = { url: rawRelay, autoConnect: true };\r\n } else if (rawRelay && typeof rawRelay === 'object') {\r\n const r = rawRelay as Record<string, unknown>;\r\n if (typeof r.url === 'string') {\r\n relay = {\r\n url: r.url,\r\n autoConnect: typeof r.autoConnect === 'boolean' ? r.autoConnect : true,\r\n name: typeof r.name === 'string' ? r.name : undefined,\r\n reconnectMaxMs: typeof r.reconnectMaxMs === 'number' ? r.reconnectMaxMs : undefined,\r\n };\r\n }\r\n }\r\n\r\n return {\r\n identity,\r\n peers,\r\n ...(relay ? { relay } : {}),\r\n };\r\n}\r\n\r\n/**\r\n * Load and normalize Agora configuration from a JSON file (sync).\r\n * Supports relay as string (backward compat) or object { url?, autoConnect?, name?, reconnectMaxMs? }.\r\n *\r\n * @param path - Config file path; defaults to getDefaultConfigPath()\r\n * @returns Normalized AgoraConfig\r\n * @throws Error if file doesn't exist or config is invalid\r\n */\r\nexport function loadAgoraConfig(path?: string): AgoraConfig {\r\n const configPath = path ?? getDefaultConfigPath();\r\n\r\n if (!existsSync(configPath)) {\r\n throw new Error(`Config file not found at ${configPath}. Run 'npx @rookdaemon/agora init' first.`);\r\n }\r\n\r\n const content = readFileSync(configPath, 'utf-8');\r\n let config: Record<string, unknown>;\r\n try {\r\n config = JSON.parse(content) as Record<string, unknown>;\r\n } catch {\r\n throw new Error(`Invalid JSON in config file: ${configPath}`);\r\n }\r\n\r\n return parseConfig(config);\r\n}\r\n\r\n/**\r\n * Load and normalize Agora configuration from a JSON file (async).\r\n *\r\n * @param path - Config file path; defaults to getDefaultConfigPath()\r\n * @returns Normalized AgoraConfig\r\n * @throws Error if file doesn't exist or config is invalid\r\n */\r\nexport async function loadAgoraConfigAsync(path?: string): Promise<AgoraConfig> {\r\n const configPath = path ?? getDefaultConfigPath();\r\n\r\n let content: string;\r\n try {\r\n content = await readFile(configPath, 'utf-8');\r\n } catch (err) {\r\n const code = err && typeof err === 'object' && 'code' in err ? (err as NodeJS.ErrnoException).code : undefined;\r\n if (code === 'ENOENT') {\r\n throw new Error(`Config file not found at ${configPath}. Run 'npx @rookdaemon/agora init' first.`);\r\n }\r\n throw err;\r\n }\r\n\r\n let config: Record<string, unknown>;\r\n try {\r\n config = JSON.parse(content) as Record<string, unknown>;\r\n } catch {\r\n throw new Error(`Invalid JSON in config file: ${configPath}`);\r\n }\r\n\r\n return parseConfig(config);\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Profile support\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Base directory for agora config: AGORA_CONFIG_DIR env or ~/.config/agora\r\n */\r\nexport function getConfigDir(): string {\r\n if (process.env.AGORA_CONFIG_DIR) {\r\n return resolve(process.env.AGORA_CONFIG_DIR);\r\n }\r\n return resolve(homedir(), '.config', 'agora');\r\n}\r\n\r\n/**\r\n * Resolve the config path for a given profile name.\r\n * - undefined / \"default\" → ~/.config/agora/config.json (existing behaviour)\r\n * - \"stefan\" → ~/.config/agora/profiles/stefan/config.json\r\n */\r\nexport function getProfileConfigPath(profile?: string): string {\r\n if (process.env.AGORA_CONFIG) {\r\n return resolve(process.env.AGORA_CONFIG);\r\n }\r\n const base = getConfigDir();\r\n if (!profile || profile === 'default') {\r\n return join(base, 'config.json');\r\n }\r\n return join(base, 'profiles', profile, 'config.json');\r\n}\r\n\r\n/**\r\n * List available profiles.\r\n * Returns an array of profile names. \"default\" is included if config.json exists.\r\n */\r\nexport function listProfiles(): string[] {\r\n const base = getConfigDir();\r\n const profiles: string[] = [];\r\n\r\n // Default profile\r\n if (existsSync(join(base, 'config.json'))) {\r\n profiles.push('default');\r\n }\r\n\r\n // Named profiles\r\n const profilesDir = join(base, 'profiles');\r\n if (existsSync(profilesDir)) {\r\n for (const entry of readdirSync(profilesDir, { withFileTypes: true })) {\r\n if (entry.isDirectory() && existsSync(join(profilesDir, entry.name, 'config.json'))) {\r\n profiles.push(entry.name);\r\n }\r\n }\r\n }\r\n\r\n return profiles;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Export / Import\r\n// ---------------------------------------------------------------------------\r\n\r\nexport interface ExportedConfig {\r\n /** Schema version for forward-compat */\r\n version: 1;\r\n identity?: AgoraIdentity;\r\n peers: Record<string, AgoraPeerConfig>;\r\n relay?: RelayConfig;\r\n}\r\n\r\nexport interface ImportResult {\r\n peersAdded: string[];\r\n peersSkipped: string[];\r\n identityImported: boolean;\r\n relayImported: boolean;\r\n}\r\n\r\n/**\r\n * Export the config (or just peers) as a portable JSON object.\r\n */\r\nexport function exportConfig(\r\n config: AgoraConfig,\r\n opts: { includeIdentity?: boolean } = {},\r\n): ExportedConfig {\r\n const exported: ExportedConfig = {\r\n version: 1,\r\n peers: Object.fromEntries(\r\n Object.entries(config.peers).map(([k, v]) => [k, { ...v }]),\r\n ),\r\n };\r\n if (opts.includeIdentity) {\r\n exported.identity = { ...config.identity };\r\n }\r\n if (config.relay) {\r\n exported.relay = { ...config.relay };\r\n }\r\n return exported;\r\n}\r\n\r\n/**\r\n * Import peers (and optionally identity/relay) into an existing config.\r\n * Merges peers by public key — existing peers are NOT overwritten.\r\n */\r\nexport function importConfig(\r\n target: AgoraConfig,\r\n incoming: ExportedConfig,\r\n opts: { overwriteIdentity?: boolean; overwriteRelay?: boolean } = {},\r\n): ImportResult {\r\n const result: ImportResult = {\r\n peersAdded: [],\r\n peersSkipped: [],\r\n identityImported: false,\r\n relayImported: false,\r\n };\r\n\r\n // Merge peers\r\n for (const [key, peer] of Object.entries(incoming.peers)) {\r\n if (target.peers[key]) {\r\n result.peersSkipped.push(key);\r\n } else {\r\n target.peers[key] = { ...peer };\r\n result.peersAdded.push(key);\r\n }\r\n }\r\n\r\n // Identity\r\n if (opts.overwriteIdentity && incoming.identity) {\r\n target.identity = { ...incoming.identity };\r\n result.identityImported = true;\r\n }\r\n\r\n // Relay\r\n if (opts.overwriteRelay && incoming.relay) {\r\n target.relay = { ...incoming.relay };\r\n result.relayImported = true;\r\n }\r\n\r\n return result;\r\n}\r\n\r\n/**\r\n * Save an AgoraConfig to disk (creates parent dirs as needed).\r\n */\r\nexport function saveAgoraConfig(path: string, config: AgoraConfig): void {\r\n const dir = dirname(path);\r\n if (!existsSync(dir)) {\r\n mkdirSync(dir, { recursive: true });\r\n }\r\n const raw: Record<string, unknown> = {\r\n identity: config.identity,\r\n peers: config.peers,\r\n };\r\n if (config.relay) {\r\n raw.relay = config.relay;\r\n }\r\n writeFileSync(path, JSON.stringify(raw, null, 2) + '\\n', 'utf-8');\r\n}\r\n","import { EventEmitter } from 'node:events';\nimport WebSocket from 'ws';\nimport { createEnvelope, verifyEnvelope, type Envelope, type MessageType } from '../message/envelope';\nimport type { RelayClientMessage, RelayServerMessage, RelayPeer } from './types';\n\n/**\n * Configuration for RelayClient\n */\nexport interface RelayClientConfig {\n /** WebSocket URL of the relay server */\n relayUrl: string;\n /** Agent's public key */\n publicKey: string;\n /** Agent's private key (for signing) */\n privateKey: string;\n /** Optional name for this agent */\n name?: string;\n /** Keepalive ping interval in milliseconds (default: 30000) */\n pingInterval?: number;\n /** Maximum reconnection delay in milliseconds (default: 60000) */\n maxReconnectDelay?: number;\n}\n\n/**\n * Events emitted by RelayClient\n */\nexport interface RelayClientEvents {\n /** Emitted when successfully connected and registered */\n 'connected': () => void;\n /** Emitted when disconnected from relay */\n 'disconnected': () => void;\n /** Emitted when a verified message is received */\n 'message': (envelope: Envelope, from: string, fromName?: string) => void;\n /** Emitted when a peer comes online */\n 'peer_online': (peer: RelayPeer) => void;\n /** Emitted when a peer goes offline */\n 'peer_offline': (peer: RelayPeer) => void;\n /** Emitted on errors */\n 'error': (error: Error) => void;\n}\n\n/**\n * Persistent WebSocket client for the Agora relay server.\n * Maintains a long-lived connection, handles reconnection, and routes messages.\n */\nexport class RelayClient extends EventEmitter {\n private ws: WebSocket | null = null;\n private config: RelayClientConfig;\n private reconnectAttempts = 0;\n private reconnectTimeout: NodeJS.Timeout | null = null;\n private pingInterval: NodeJS.Timeout | null = null;\n private isConnected = false;\n private isRegistered = false;\n private shouldReconnect = true;\n private onlinePeers = new Map<string, RelayPeer>();\n\n constructor(config: RelayClientConfig) {\n super();\n this.config = {\n pingInterval: 30000,\n maxReconnectDelay: 60000,\n ...config,\n };\n }\n\n /**\n * Connect to the relay server\n */\n async connect(): Promise<void> {\n if (this.ws && (this.ws.readyState === WebSocket.CONNECTING || this.ws.readyState === WebSocket.OPEN)) {\n return;\n }\n\n this.shouldReconnect = true;\n return this.doConnect();\n }\n\n /**\n * Disconnect from the relay server\n */\n disconnect(): void {\n this.shouldReconnect = false;\n this.cleanup();\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }\n\n /**\n * Check if currently connected and registered\n */\n connected(): boolean {\n return this.isConnected && this.isRegistered;\n }\n\n /**\n * Send a message to a specific peer\n */\n async send(to: string, envelope: Envelope): Promise<{ ok: boolean; error?: string }> {\n if (!this.connected()) {\n return { ok: false, error: 'Not connected to relay' };\n }\n\n const message: RelayClientMessage = {\n type: 'message',\n to,\n envelope,\n };\n\n try {\n this.ws!.send(JSON.stringify(message));\n return { ok: true };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n }\n\n /**\n * Create a signed envelope and send it to each recipient.\n * Each envelope lists ALL recipients in the `to` field so receivers\n * know the full participant list (needed for multi-party replies).\n * Returns the list of failures (empty means all succeeded).\n */\n async sendToRecipients(\n recipients: string[],\n type: MessageType,\n payload: unknown,\n inReplyTo?: string,\n ): Promise<{ ok: boolean; errors: Array<{ recipient: string; error: string }> }> {\n if (!this.connected()) {\n return { ok: false, errors: [{ recipient: '*', error: 'Not connected to relay' }] };\n }\n\n const unique = Array.from(new Set(recipients.filter(Boolean)));\n const errors: Array<{ recipient: string; error: string }> = [];\n\n for (const recipient of unique) {\n const envelope = createEnvelope(\n type,\n this.config.publicKey,\n this.config.privateKey,\n payload,\n Date.now(),\n inReplyTo,\n unique,\n );\n const result = await this.send(recipient, envelope);\n if (!result.ok) {\n errors.push({ recipient, error: result.error ?? 'unknown error' });\n }\n }\n\n return { ok: errors.length === 0, errors };\n }\n\n /**\n * Get list of currently online peers\n */\n getOnlinePeers(): RelayPeer[] {\n return Array.from(this.onlinePeers.values());\n }\n\n /**\n * Check if a specific peer is online\n */\n isPeerOnline(publicKey: string): boolean {\n return this.onlinePeers.has(publicKey);\n }\n\n /**\n * Internal: Perform connection\n */\n private async doConnect(): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n this.ws = new WebSocket(this.config.relayUrl);\n let resolved = false;\n\n const resolveOnce = (callback: () => void): void => {\n if (!resolved) {\n resolved = true;\n callback();\n }\n };\n\n this.ws.on('open', () => {\n this.isConnected = true;\n this.reconnectAttempts = 0;\n this.startPingInterval();\n\n // Send registration message\n const registerMsg: RelayClientMessage = {\n type: 'register',\n publicKey: this.config.publicKey,\n name: this.config.name,\n };\n this.ws!.send(JSON.stringify(registerMsg));\n });\n\n this.ws.on('message', (data: WebSocket.Data) => {\n try {\n const msg = JSON.parse(data.toString()) as RelayServerMessage;\n this.handleMessage(msg);\n\n // Resolve promise on successful registration\n if (msg.type === 'registered' && !resolved) {\n resolveOnce(() => resolve());\n }\n } catch (err) {\n this.emit('error', new Error(`Failed to parse message: ${err instanceof Error ? err.message : String(err)}`));\n }\n });\n\n this.ws.on('close', () => {\n this.isConnected = false;\n this.isRegistered = false;\n this.cleanup();\n this.emit('disconnected');\n\n if (this.shouldReconnect) {\n this.scheduleReconnect();\n }\n\n if (!resolved) {\n resolveOnce(() => reject(new Error('Connection closed before registration')));\n }\n });\n\n this.ws.on('error', (err) => {\n this.emit('error', err);\n if (!resolved) {\n resolveOnce(() => reject(err));\n }\n });\n } catch (err) {\n reject(err);\n }\n });\n }\n\n /**\n * Handle incoming message from relay\n */\n private handleMessage(msg: RelayServerMessage): void {\n switch (msg.type) {\n case 'registered':\n this.isRegistered = true;\n if (msg.peers) {\n // Populate initial peer list\n for (const peer of msg.peers) {\n this.onlinePeers.set(peer.publicKey, peer);\n }\n }\n this.emit('connected');\n break;\n\n case 'message':\n if (msg.envelope && msg.from) {\n // Verify envelope signature\n const verification = verifyEnvelope(msg.envelope);\n if (!verification.valid) {\n this.emit('error', new Error(`Invalid envelope signature: ${verification.reason}`));\n return;\n }\n\n // Verify sender matches 'from' field\n const envelopeFrom = msg.envelope.from;\n if (envelopeFrom !== msg.from) {\n this.emit('error', new Error('Envelope sender does not match relay from field'));\n return;\n }\n\n // Emit verified message\n this.emit('message', msg.envelope, msg.from, msg.name);\n }\n break;\n\n case 'peer_online':\n if (msg.publicKey) {\n const peer: RelayPeer = {\n publicKey: msg.publicKey,\n name: msg.name,\n };\n this.onlinePeers.set(msg.publicKey, peer);\n this.emit('peer_online', peer);\n }\n break;\n\n case 'peer_offline':\n if (msg.publicKey) {\n const peer = this.onlinePeers.get(msg.publicKey);\n if (peer) {\n this.onlinePeers.delete(msg.publicKey);\n this.emit('peer_offline', peer);\n }\n }\n break;\n\n case 'error':\n this.emit('error', new Error(`Relay error: ${msg.message || 'Unknown error'}`));\n break;\n\n case 'pong':\n // Keepalive response, no action needed\n break;\n\n default:\n // Unknown message type, ignore\n break;\n }\n }\n\n /**\n * Schedule reconnection with exponential backoff\n */\n private scheduleReconnect(): void {\n if (this.reconnectTimeout) {\n return;\n }\n\n // Exponential backoff: 1s, 2s, 4s, 8s, 16s, 32s, 60s (max)\n const delay = Math.min(\n 1000 * Math.pow(2, this.reconnectAttempts),\n this.config.maxReconnectDelay!\n );\n\n this.reconnectAttempts++;\n\n this.reconnectTimeout = setTimeout(() => {\n this.reconnectTimeout = null;\n if (this.shouldReconnect) {\n this.doConnect().catch((err) => {\n this.emit('error', err);\n });\n }\n }, delay);\n }\n\n /**\n * Start periodic ping messages\n */\n private startPingInterval(): void {\n this.stopPingInterval();\n this.pingInterval = setInterval(() => {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n const ping: RelayClientMessage = { type: 'ping' };\n this.ws.send(JSON.stringify(ping));\n }\n }, this.config.pingInterval!);\n }\n\n /**\n * Stop ping interval\n */\n private stopPingInterval(): void {\n if (this.pingInterval) {\n clearInterval(this.pingInterval);\n this.pingInterval = null;\n }\n }\n\n /**\n * Cleanup resources\n */\n private cleanup(): void {\n this.stopPingInterval();\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n }\n this.onlinePeers.clear();\n }\n}\n","import { EventEmitter } from 'node:events';\nimport { createEnvelope, verifyEnvelope, type Envelope } from '../message/envelope';\nimport type { RelayClient } from '../relay/client';\nimport type { PeerListRequestPayload, PeerListResponsePayload, PeerReferralPayload } from '../message/types/peer-discovery';\n\n/**\n * Configuration for PeerDiscoveryService\n */\nexport interface PeerDiscoveryConfig {\n /** Agent's public key */\n publicKey: string;\n /** Agent's private key for signing */\n privateKey: string;\n /** RelayClient instance for communication */\n relayClient: RelayClient;\n /** Public key of the relay server (for sending peer list requests) */\n relayPublicKey?: string;\n}\n\n/**\n * Events emitted by PeerDiscoveryService\n */\nexport interface PeerDiscoveryEvents {\n /** Emitted when peers are discovered */\n 'peers-discovered': (peers: PeerListResponsePayload['peers']) => void;\n /** Emitted when a peer referral is received */\n 'peer-referral': (referral: PeerReferralPayload, from: string) => void;\n /** Emitted on errors */\n 'error': (error: Error) => void;\n}\n\n/**\n * Service for discovering peers on the Agora network\n */\nexport class PeerDiscoveryService extends EventEmitter {\n private config: PeerDiscoveryConfig;\n\n constructor(config: PeerDiscoveryConfig) {\n super();\n this.config = config;\n\n // Listen for peer list responses and referrals\n this.config.relayClient.on('message', (envelope: Envelope, from: string) => {\n if (envelope.type === 'peer_list_response') {\n this.handlePeerList(envelope as Envelope<PeerListResponsePayload>);\n } else if (envelope.type === 'peer_referral') {\n this.handleReferral(envelope as Envelope<PeerReferralPayload>, from);\n }\n });\n }\n\n /**\n * Request peer list from relay\n */\n async discoverViaRelay(filters?: PeerListRequestPayload['filters']): Promise<PeerListResponsePayload | null> {\n if (!this.config.relayPublicKey) {\n throw new Error('Relay public key not configured');\n }\n\n if (!this.config.relayClient.connected()) {\n throw new Error('Not connected to relay');\n }\n\n const payload: PeerListRequestPayload = filters ? { filters } : {};\n\n const envelope = createEnvelope(\n 'peer_list_request',\n this.config.publicKey,\n this.config.privateKey,\n payload,\n Date.now(),\n undefined,\n [this.config.relayPublicKey]\n );\n\n // Send request to relay\n const result = await this.config.relayClient.send(this.config.relayPublicKey, envelope);\n if (!result.ok) {\n throw new Error(`Failed to send peer list request: ${result.error}`);\n }\n\n // Wait for response (with timeout)\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n cleanup();\n reject(new Error('Peer list request timed out'));\n }, 10000); // 10 second timeout\n\n const messageHandler = (responseEnvelope: Envelope, from: string): void => {\n if (responseEnvelope.type === 'peer_list_response' && \n responseEnvelope.inReplyTo === envelope.id &&\n from === this.config.relayPublicKey) {\n cleanup();\n resolve(responseEnvelope.payload as PeerListResponsePayload);\n }\n };\n\n const cleanup = (): void => {\n clearTimeout(timeout);\n this.config.relayClient.off('message', messageHandler);\n };\n\n this.config.relayClient.on('message', messageHandler);\n });\n }\n\n /**\n * Send peer referral to another agent\n */\n async referPeer(\n recipientPublicKey: string,\n referredPublicKey: string,\n metadata?: { name?: string; endpoint?: string; comment?: string; trustScore?: number }\n ): Promise<{ ok: boolean; error?: string }> {\n if (!this.config.relayClient.connected()) {\n return { ok: false, error: 'Not connected to relay' };\n }\n\n const payload: PeerReferralPayload = {\n publicKey: referredPublicKey,\n endpoint: metadata?.endpoint,\n metadata: metadata?.name ? { name: metadata.name } : undefined,\n comment: metadata?.comment,\n trustScore: metadata?.trustScore,\n };\n\n const envelope = createEnvelope(\n 'peer_referral',\n this.config.publicKey,\n this.config.privateKey,\n payload,\n Date.now(),\n undefined,\n [recipientPublicKey]\n );\n\n return this.config.relayClient.send(recipientPublicKey, envelope);\n }\n\n /**\n * Handle incoming peer referral\n */\n private handleReferral(envelope: Envelope<PeerReferralPayload>, from: string): void {\n // Verify envelope\n const verification = verifyEnvelope(envelope);\n if (!verification.valid) {\n this.emit('error', new Error(`Invalid peer referral: ${verification.reason}`));\n return;\n }\n\n // Emit event for application to handle\n this.emit('peer-referral', envelope.payload, from);\n }\n\n /**\n * Handle incoming peer list from relay\n */\n private handlePeerList(envelope: Envelope<PeerListResponsePayload>): void {\n // Verify envelope\n const verification = verifyEnvelope(envelope);\n if (!verification.valid) {\n this.emit('error', new Error(`Invalid peer list response: ${verification.reason}`));\n return;\n }\n\n // Verify sender is the relay\n if (envelope.from !== this.config.relayPublicKey) {\n this.emit('error', new Error('Peer list response not from configured relay'));\n return;\n }\n\n // Emit event\n this.emit('peers-discovered', envelope.payload.peers);\n }\n}\n","/**\r\n * Bootstrap configuration for peer discovery on the Agora network.\r\n * Provides default bootstrap relays for initial network entry.\r\n */\r\n\r\n/**\r\n * Default bootstrap relay servers\r\n * These are well-known relays that serve as initial entry points to the network\r\n */\r\nexport const DEFAULT_BOOTSTRAP_RELAYS = [\r\n {\r\n url: 'wss://agora-relay.lbsa71.net',\r\n name: 'Primary Bootstrap Relay',\r\n // Note: Public key would need to be set when the relay is actually deployed\r\n // For now, this is a placeholder that would be configured when the relay is running\r\n },\r\n];\r\n\r\n/**\r\n * Configuration for bootstrap connection\r\n */\r\nexport interface BootstrapConfig {\r\n /** Bootstrap relay URL */\r\n relayUrl: string;\r\n /** Optional relay public key (for verification) */\r\n relayPublicKey?: string;\r\n /** Connection timeout in ms (default: 10000) */\r\n timeout?: number;\r\n}\r\n\r\n/**\r\n * Get default bootstrap relay configuration\r\n */\r\nexport function getDefaultBootstrapRelay(): BootstrapConfig {\r\n return {\r\n relayUrl: DEFAULT_BOOTSTRAP_RELAYS[0].url,\r\n timeout: 10000,\r\n };\r\n}\r\n\r\n/**\r\n * Parse bootstrap relay URL and optional public key\r\n */\r\nexport function parseBootstrapRelay(url: string, publicKey?: string): BootstrapConfig {\r\n return {\r\n relayUrl: url,\r\n relayPublicKey: publicKey,\r\n timeout: 10000,\r\n };\r\n}\r\n","/**\r\n * Get a short display version of a public key using the last 8 characters.\r\n * Ed25519 public keys all share the same OID prefix, so the last 8 characters\r\n * are more distinguishable than the first 8.\r\n *\r\n * @param publicKey - The full public key hex string\r\n * @returns \"...\" followed by the last 8 characters of the key\r\n */\r\nexport function shortKey(publicKey: string): string {\r\n return \"@\" + publicKey.slice(-8);\r\n}\r\n\r\nexport interface PeerReferenceEntry {\r\n publicKey: string;\r\n name?: string;\r\n}\r\n\r\nexport type PeerReferenceDirectory =\r\n | Record<string, PeerReferenceEntry>\r\n | Map<string, PeerReferenceEntry>\r\n | PeerReferenceEntry[];\r\n\r\nfunction toDirectoryEntries(directory?: PeerReferenceDirectory): PeerReferenceEntry[] {\r\n if (!directory) {\r\n return [];\r\n }\r\n if (Array.isArray(directory)) {\r\n return directory.filter((p) => typeof p.publicKey === 'string' && p.publicKey.length > 0);\r\n }\r\n if (directory instanceof Map) {\r\n return Array.from(directory.values()).filter((p) => typeof p.publicKey === 'string' && p.publicKey.length > 0);\r\n }\r\n return Object.values(directory).filter((p) => typeof p.publicKey === 'string' && p.publicKey.length > 0);\r\n}\r\n\r\nfunction findById(id: string, directory?: PeerReferenceDirectory): PeerReferenceEntry | undefined {\r\n return toDirectoryEntries(directory).find((entry) => entry.publicKey === id);\r\n}\r\n\r\n/**\r\n * Shorten a full peer ID for display/reference.\r\n * Canonical form:\r\n * - Configured name => \"name@<last8>\"\r\n * - Unknown/no-name => \"@<last8>\"\r\n */\r\nexport function shorten(id: string, directory?: PeerReferenceDirectory): string {\r\n const suffix = id.slice(-8);\r\n const entry = findById(id, directory);\r\n if (!entry?.name) {\r\n return `@${suffix}`;\r\n }\r\n return `${entry.name}@${suffix}`;\r\n}\r\n\r\n/**\r\n * Expand a short peer reference to a full ID.\r\n * Supports: full ID, unique name, name@last8, @last8.\r\n * Also supports legacy name...last8 and ...last8 forms.\r\n */\r\nexport function expand(shortId: string, directory: PeerReferenceDirectory): string | undefined {\r\n const entries = toDirectoryEntries(directory);\r\n if (entries.length === 0) {\r\n return undefined;\r\n }\r\n\r\n const token = shortId.trim();\r\n const direct = entries.find((entry) => entry.publicKey === token);\r\n if (direct) {\r\n return direct.publicKey;\r\n }\r\n\r\n // name@suffix8 (current canonical form)\r\n const namedAtSuffix = token.match(/^(.+)@([0-9a-fA-F]{8})$/);\r\n if (namedAtSuffix) {\r\n const [, name, suffix] = namedAtSuffix;\r\n const matches = entries.filter((entry) => entry.name === name && entry.publicKey.toLowerCase().endsWith(suffix.toLowerCase()));\r\n if (matches.length === 1) {\r\n return matches[0].publicKey;\r\n }\r\n return undefined;\r\n }\r\n\r\n // @suffix8 (current canonical form for unknown peers)\r\n const atSuffixOnly = token.match(/^@([0-9a-fA-F]{8})$/);\r\n if (atSuffixOnly) {\r\n const [, suffix] = atSuffixOnly;\r\n const matches = entries.filter((entry) => entry.publicKey.toLowerCase().endsWith(suffix.toLowerCase()));\r\n if (matches.length === 1) {\r\n return matches[0].publicKey;\r\n }\r\n return undefined;\r\n }\r\n\r\n // Legacy: name...suffix8\r\n const namedWithSuffix = token.match(/^(.+)\\.\\.\\.([0-9a-fA-F]{8})$/);\r\n if (namedWithSuffix) {\r\n const [, name, suffix] = namedWithSuffix;\r\n const matches = entries.filter((entry) => entry.name === name && entry.publicKey.toLowerCase().endsWith(suffix.toLowerCase()));\r\n if (matches.length === 1) {\r\n return matches[0].publicKey;\r\n }\r\n return undefined;\r\n }\r\n\r\n // Legacy: ...suffix8\r\n const suffixOnly = token.match(/^\\.\\.\\.([0-9a-fA-F]{8})$/);\r\n if (suffixOnly) {\r\n const [, suffix] = suffixOnly;\r\n const matches = entries.filter((entry) => entry.publicKey.toLowerCase().endsWith(suffix.toLowerCase()));\r\n if (matches.length === 1) {\r\n return matches[0].publicKey;\r\n }\r\n return undefined;\r\n }\r\n\r\n const byName = entries.filter((entry) => entry.name === token);\r\n if (byName.length === 1) {\r\n return byName[0].publicKey;\r\n }\r\n\r\n return undefined;\r\n}\r\n\r\n/**\r\n * Expand inline @references in text to full IDs using configured peers.\r\n */\r\nexport function expandInlineReferences(text: string, directory: PeerReferenceDirectory): string {\r\n return text.replace(/@([^\\s]+)/g, (_full, token: string) => {\r\n const resolved = expand(token, directory);\r\n return resolved ? `@${resolved}` : `@${token}`;\r\n });\r\n}\r\n\r\n/**\r\n * Compact inline @<full-id> references for rendering.\r\n */\r\nexport function compactInlineReferences(text: string, directory: PeerReferenceDirectory): string {\r\n return text.replace(/@([0-9a-fA-F]{16,})/g, (_full, id: string) => `@${shorten(id, directory)}`);\r\n}\r\n\r\n/**\r\n * Compact inline @<full-id> references only when the full ID exists in the\r\n * provided directory. Unknown IDs remain unchanged.\r\n */\r\nexport function compactKnownInlineReferences(text: string, directory: PeerReferenceDirectory): string {\r\n return text.replace(/@([0-9a-fA-F]{16,})/g, (_full, id: string) => {\r\n const known = findById(id, directory);\r\n if (!known) {\r\n return `@${id}`;\r\n }\r\n return `@${shorten(id, directory)}`;\r\n });\r\n}\r\n\r\n/**\r\n * Extract text content from an envelope payload.\r\n * Handles { text: string } objects, plain strings, and fallback to JSON.\r\n * All output is sanitized.\r\n */\r\nexport function extractTextFromPayload(payload: unknown): string {\r\n if (payload && typeof payload === 'object' && 'text' in payload && typeof (payload as { text: unknown }).text === 'string') {\r\n return sanitizeText((payload as { text: string }).text);\r\n }\r\n if (typeof payload === 'string') return sanitizeText(payload);\r\n return sanitizeText(JSON.stringify(payload ?? ''));\r\n}\r\n\r\n/**\r\n * Strip characters that can crash downstream width/segmenter logic in UIs.\r\n * Removes control chars (except newline/tab) and replaces lone surrogates.\r\n */\r\nexport function sanitizeText(text: string): string {\r\n return text\r\n .replace(/[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F]/g, '')\r\n .replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])/g, '\\uFFFD')\r\n .replace(/(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, '\\uFFFD');\r\n}\r\n\r\n/**\r\n * Resolve a display name for a peer.\r\n * Only returns locally configured names from the peer directory.\r\n * Sender-claimed names are never used — identity must be derived from verified keys.\r\n */\r\nexport function resolveDisplayName(\r\n publicKey: string,\r\n _peerName?: string | undefined,\r\n directory?: PeerReferenceDirectory,\r\n): string | undefined {\r\n const entry = findById(publicKey, directory);\r\n if (entry?.name) {\r\n return entry.name;\r\n }\r\n\r\n return undefined;\r\n}\r\n\r\n/**\r\n * Resolves the name to broadcast when connecting to a relay.\r\n * Priority order:\r\n * 1. CLI --name flag\r\n * 2. config.relay.name (if relay is an object with name property)\r\n * 3. config.identity.name\r\n * 4. undefined (no name broadcast)\r\n *\r\n * @param config - The Agora configuration (or compatible config with identity and optional relay)\r\n * @param cliName - Optional name from CLI --name flag\r\n * @returns The resolved name to broadcast, or undefined if none available\r\n */\r\nexport function resolveBroadcastName(\r\n config: { identity: { name?: string }; relay?: { name?: string } | string },\r\n cliName?: string\r\n): string | undefined {\r\n // Priority 1: CLI --name flag\r\n if (cliName) {\r\n return cliName;\r\n }\r\n\r\n // Priority 2: config.relay.name (if relay is an object with name property)\r\n if (config.relay) {\r\n if (typeof config.relay === 'object' && config.relay.name) {\r\n return config.relay.name;\r\n }\r\n }\r\n\r\n // Priority 3: config.identity.name\r\n if (config.identity.name) {\r\n return config.identity.name;\r\n }\r\n\r\n // Priority 4: No name available\r\n return undefined;\r\n}\r\n\r\n/**\r\n * Formats a display name using the canonical moniker form.\r\n * If name exists: \"name@3f8c2247\" (same form as shorten())\r\n * If no name: \"@3f8c2247\" (short ID only)\r\n *\r\n * @param name - Optional name to display (should not be a short ID)\r\n * @param publicKey - The public key to use for short ID\r\n * @returns Formatted display string\r\n */\r\nexport function formatDisplayName(name: string | undefined, publicKey: string): string {\r\n const suffix = publicKey.slice(-8);\r\n // If name is undefined, empty, or is already a short ID, return only short ID\r\n if (!name || name.trim() === '' || name.startsWith('...') || name.startsWith('@')) {\r\n return `@${suffix}`;\r\n }\r\n return `${name}@${suffix}`;\r\n}\r\n\r\n/**\r\n * A conversation entry with FROM/TO metadata, used for CONVERSATION.md formatting.\r\n */\r\nexport interface ConversationEntry {\r\n timestamp: number;\r\n from: string;\r\n to: string[];\r\n text: string;\r\n}\r\n\r\n/**\r\n * Format a conversation entry as a single line for CONVERSATION.md.\r\n * Format: [ISO_TIMESTAMP] **FROM:** sender **TO:** recipient1, recipient2 text\r\n */\r\nexport function formatConversationLine(entry: ConversationEntry): string {\r\n const ts = new Date(entry.timestamp).toISOString();\r\n const toList = entry.to.length > 0 ? entry.to.join(', ') : '(none)';\r\n const safeText = entry.text.replace(/\\r?\\n/g, ' ');\r\n return `[${ts}] **FROM:** ${entry.from} **TO:** ${toList} ${safeText}`;\r\n}\r\n\r\n/**\r\n * Parse a single CONVERSATION.md line back into a ConversationEntry.\r\n * Returns null if the line doesn't match the expected format.\r\n */\r\nexport function parseConversationLine(line: string): ConversationEntry | null {\r\n const match = line.match(\r\n /^\\[([^\\]]+)\\] \\*\\*FROM:\\*\\* (\\S+) \\*\\*TO:\\*\\* ([^\\s,]+(?:, [^\\s,]+)*|\\(none\\))(?: (.*))?$/\r\n );\r\n if (!match) return null;\r\n const [, ts, from, toRaw, text] = match;\r\n const timestamp = new Date(ts).getTime();\r\n if (isNaN(timestamp)) return null;\r\n const to = toRaw === '(none)' ? [] : toRaw.split(', ').filter(Boolean);\r\n return { timestamp, from, to, text: text ?? '' };\r\n}\r\n","/**\r\n * Core data structures for the Agora reputation layer.\r\n * Phase 1: Verification records, commit-reveal patterns, and trust scoring.\r\n */\r\n\r\n/**\r\n * A cryptographically signed verification of another agent's output or claim.\r\n * Core primitive for building computational reputation.\r\n */\r\nexport interface VerificationRecord {\r\n /** Content-addressed ID (hash of canonical JSON) */\r\n id: string;\r\n \r\n /** Public key of verifying agent */\r\n verifier: string;\r\n \r\n /** ID of message/output being verified */\r\n target: string;\r\n \r\n /** Capability domain (e.g., 'ocr', 'summarization', 'code_review') */\r\n domain: string;\r\n \r\n /** Verification verdict */\r\n verdict: 'correct' | 'incorrect' | 'disputed';\r\n \r\n /** Verifier's confidence in their check (0-1) */\r\n confidence: number;\r\n \r\n /** Optional link to independent verification data */\r\n evidence?: string;\r\n \r\n /** Unix timestamp (ms) */\r\n timestamp: number;\r\n \r\n /** Ed25519 signature over canonical JSON */\r\n signature: string;\r\n}\r\n\r\n/**\r\n * A commitment to a prediction before outcome is known.\r\n * Prevents post-hoc editing of predictions.\r\n */\r\nexport interface CommitRecord {\r\n /** Content-addressed ID */\r\n id: string;\r\n \r\n /** Public key of committing agent */\r\n agent: string;\r\n \r\n /** Domain of prediction */\r\n domain: string;\r\n \r\n /** SHA-256 hash of prediction string */\r\n commitment: string;\r\n \r\n /** Unix timestamp (ms) */\r\n timestamp: number;\r\n \r\n /** Expiry time (ms) - commitment invalid after this */\r\n expiry: number;\r\n \r\n /** Ed25519 signature */\r\n signature: string;\r\n}\r\n\r\n/**\r\n * Reveals the prediction and outcome after commitment expiry.\r\n * Enables verification of prediction accuracy.\r\n */\r\nexport interface RevealRecord {\r\n /** Content-addressed ID */\r\n id: string;\r\n \r\n /** Public key of revealing agent */\r\n agent: string;\r\n \r\n /** ID of original commit message */\r\n commitmentId: string;\r\n \r\n /** Original prediction (plaintext) */\r\n prediction: string;\r\n \r\n /** Observed outcome */\r\n outcome: string;\r\n \r\n /** Evidence for outcome (optional) */\r\n evidence?: string;\r\n \r\n /** Unix timestamp (ms) */\r\n timestamp: number;\r\n \r\n /** Ed25519 signature */\r\n signature: string;\r\n}\r\n\r\n/**\r\n * Computed reputation score for an agent in a specific domain.\r\n * Derived from verification history, not stored directly.\r\n */\r\nexport interface TrustScore {\r\n /** Public key of agent being scored */\r\n agent: string;\r\n \r\n /** Domain of reputation */\r\n domain: string;\r\n \r\n /** Computed score (0-1, where 1 = highest trust) */\r\n score: number;\r\n \r\n /** Number of verifications considered */\r\n verificationCount: number;\r\n \r\n /** Timestamp of most recent verification (ms) */\r\n lastVerified: number;\r\n \r\n /** Public keys of top verifiers (by weight) */\r\n topVerifiers: string[];\r\n}\r\n\r\n/**\r\n * Request for reputation data about a specific agent.\r\n */\r\nexport interface ReputationQuery {\r\n /** Public key of agent being queried */\r\n agent: string;\r\n \r\n /** Optional: filter by capability domain */\r\n domain?: string;\r\n \r\n /** Optional: only include verifications after this timestamp */\r\n after?: number;\r\n}\r\n\r\n/**\r\n * Response containing reputation data for a queried agent.\r\n */\r\nexport interface ReputationResponse {\r\n /** Public key of agent being reported on */\r\n agent: string;\r\n \r\n /** Domain filter (if requested) */\r\n domain?: string;\r\n \r\n /** Verification records matching the query */\r\n verifications: VerificationRecord[];\r\n \r\n /** Computed trust scores by domain */\r\n scores: Record<string, TrustScore>;\r\n}\r\n\r\n/**\r\n * Revocation of a previously issued verification.\r\n * Used when a verifier discovers their verification was incorrect.\r\n */\r\nexport interface RevocationRecord {\r\n /** Content-addressed ID of this revocation */\r\n id: string;\r\n \r\n /** Public key of agent revoking (must match original verifier) */\r\n verifier: string;\r\n \r\n /** ID of verification being revoked */\r\n verificationId: string;\r\n \r\n /** Reason for revocation */\r\n reason: string;\r\n \r\n /** Unix timestamp (ms) */\r\n timestamp: number;\r\n \r\n /** Ed25519 signature */\r\n signature: string;\r\n}\r\n\r\n/**\r\n * Validation result structure\r\n */\r\nexport interface ValidationResult {\r\n valid: boolean;\r\n errors: string[];\r\n}\r\n\r\n/**\r\n * Validate a verification record structure\r\n */\r\nexport function validateVerificationRecord(record: unknown): ValidationResult {\r\n const errors: string[] = [];\r\n \r\n if (typeof record !== 'object' || record === null) {\r\n return { valid: false, errors: ['Record must be an object'] };\r\n }\r\n \r\n const r = record as Record<string, unknown>;\r\n \r\n if (typeof r.id !== 'string' || r.id.length === 0) {\r\n errors.push('id must be a non-empty string');\r\n }\r\n \r\n if (typeof r.verifier !== 'string' || r.verifier.length === 0) {\r\n errors.push('verifier must be a non-empty string');\r\n }\r\n \r\n if (typeof r.target !== 'string' || r.target.length === 0) {\r\n errors.push('target must be a non-empty string');\r\n }\r\n \r\n if (typeof r.domain !== 'string' || r.domain.length === 0) {\r\n errors.push('domain must be a non-empty string');\r\n }\r\n \r\n if (!['correct', 'incorrect', 'disputed'].includes(r.verdict as string)) {\r\n errors.push('verdict must be one of: correct, incorrect, disputed');\r\n }\r\n \r\n if (typeof r.confidence !== 'number' || r.confidence < 0 || r.confidence > 1) {\r\n errors.push('confidence must be a number between 0 and 1');\r\n }\r\n \r\n if (r.evidence !== undefined && typeof r.evidence !== 'string') {\r\n errors.push('evidence must be a string if provided');\r\n }\r\n \r\n if (typeof r.timestamp !== 'number' || r.timestamp <= 0) {\r\n errors.push('timestamp must be a positive number');\r\n }\r\n \r\n if (typeof r.signature !== 'string' || r.signature.length === 0) {\r\n errors.push('signature must be a non-empty string');\r\n }\r\n \r\n return { valid: errors.length === 0, errors };\r\n}\r\n\r\n/**\r\n * Validate a commit record structure\r\n */\r\nexport function validateCommitRecord(record: unknown): ValidationResult {\r\n const errors: string[] = [];\r\n \r\n if (typeof record !== 'object' || record === null) {\r\n return { valid: false, errors: ['Record must be an object'] };\r\n }\r\n \r\n const r = record as Record<string, unknown>;\r\n \r\n if (typeof r.id !== 'string' || r.id.length === 0) {\r\n errors.push('id must be a non-empty string');\r\n }\r\n \r\n if (typeof r.agent !== 'string' || r.agent.length === 0) {\r\n errors.push('agent must be a non-empty string');\r\n }\r\n \r\n if (typeof r.domain !== 'string' || r.domain.length === 0) {\r\n errors.push('domain must be a non-empty string');\r\n }\r\n \r\n if (typeof r.commitment !== 'string' || r.commitment.length !== 64) {\r\n errors.push('commitment must be a 64-character hex string (SHA-256 hash)');\r\n }\r\n \r\n if (typeof r.timestamp !== 'number' || r.timestamp <= 0) {\r\n errors.push('timestamp must be a positive number');\r\n }\r\n \r\n if (typeof r.expiry !== 'number' || r.expiry <= 0) {\r\n errors.push('expiry must be a positive number');\r\n }\r\n \r\n if (typeof r.expiry === 'number' && typeof r.timestamp === 'number' && r.expiry <= r.timestamp) {\r\n errors.push('expiry must be after timestamp');\r\n }\r\n \r\n if (typeof r.signature !== 'string' || r.signature.length === 0) {\r\n errors.push('signature must be a non-empty string');\r\n }\r\n \r\n return { valid: errors.length === 0, errors };\r\n}\r\n\r\n/**\r\n * Validate a reveal record structure\r\n */\r\nexport function validateRevealRecord(record: unknown): ValidationResult {\r\n const errors: string[] = [];\r\n \r\n if (typeof record !== 'object' || record === null) {\r\n return { valid: false, errors: ['Record must be an object'] };\r\n }\r\n \r\n const r = record as Record<string, unknown>;\r\n \r\n if (typeof r.id !== 'string' || r.id.length === 0) {\r\n errors.push('id must be a non-empty string');\r\n }\r\n \r\n if (typeof r.agent !== 'string' || r.agent.length === 0) {\r\n errors.push('agent must be a non-empty string');\r\n }\r\n \r\n if (typeof r.commitmentId !== 'string' || r.commitmentId.length === 0) {\r\n errors.push('commitmentId must be a non-empty string');\r\n }\r\n \r\n if (typeof r.prediction !== 'string' || r.prediction.length === 0) {\r\n errors.push('prediction must be a non-empty string');\r\n }\r\n \r\n if (typeof r.outcome !== 'string' || r.outcome.length === 0) {\r\n errors.push('outcome must be a non-empty string');\r\n }\r\n \r\n if (r.evidence !== undefined && typeof r.evidence !== 'string') {\r\n errors.push('evidence must be a string if provided');\r\n }\r\n \r\n if (typeof r.timestamp !== 'number' || r.timestamp <= 0) {\r\n errors.push('timestamp must be a positive number');\r\n }\r\n \r\n if (typeof r.signature !== 'string' || r.signature.length === 0) {\r\n errors.push('signature must be a non-empty string');\r\n }\r\n \r\n return { valid: errors.length === 0, errors };\r\n}\r\n","/**\n * Local reputation store using JSONL append-only log.\n * Stores verification records, commits, and reveals.\n */\n\nimport { promises as fs } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { VerificationRecord, CommitRecord, RevealRecord } from './types';\nimport { validateVerificationRecord, validateCommitRecord, validateRevealRecord } from './types';\n\n/**\n * Record type discriminator for JSONL storage\n */\ntype StoredRecord = \n | ({ type: 'verification' } & VerificationRecord)\n | ({ type: 'commit' } & CommitRecord)\n | ({ type: 'reveal' } & RevealRecord);\n\n/**\n * Reputation store with JSONL persistence\n */\nexport class ReputationStore {\n private filePath: string;\n private verifications: Map<string, VerificationRecord> = new Map();\n private commits: Map<string, CommitRecord> = new Map();\n private reveals: Map<string, RevealRecord> = new Map();\n private loaded = false;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n /**\n * Load records from JSONL file\n */\n async load(): Promise<void> {\n try {\n const content = await fs.readFile(this.filePath, 'utf-8');\n const lines = content.trim().split('\\n').filter(line => line.length > 0);\n \n for (const line of lines) {\n try {\n const record = JSON.parse(line) as StoredRecord;\n \n switch (record.type) {\n case 'verification': {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...verification } = record;\n const validation = validateVerificationRecord(verification);\n if (validation.valid) {\n this.verifications.set(verification.id, verification as VerificationRecord);\n }\n break;\n }\n case 'commit': {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...commit } = record;\n const validation = validateCommitRecord(commit);\n if (validation.valid) {\n this.commits.set(commit.id, commit as CommitRecord);\n }\n break;\n }\n case 'reveal': {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type: _type, ...reveal } = record;\n const validation = validateRevealRecord(reveal);\n if (validation.valid) {\n this.reveals.set(reveal.id, reveal as RevealRecord);\n }\n break;\n }\n }\n } catch {\n // Skip invalid lines\n continue;\n }\n }\n \n this.loaded = true;\n } catch (error) {\n // File doesn't exist yet - that's okay for first run\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n this.loaded = true;\n return;\n }\n throw error;\n }\n }\n\n /**\n * Ensure the store is loaded\n */\n private async ensureLoaded(): Promise<void> {\n if (!this.loaded) {\n await this.load();\n }\n }\n\n /**\n * Append a record to the JSONL file\n */\n private async appendToFile(record: StoredRecord): Promise<void> {\n // Ensure directory exists\n await fs.mkdir(dirname(this.filePath), { recursive: true });\n \n // Append JSONL line\n const line = JSON.stringify(record) + '\\n';\n await fs.appendFile(this.filePath, line, 'utf-8');\n }\n\n /**\n * Add a verification record\n */\n async addVerification(verification: VerificationRecord): Promise<void> {\n await this.ensureLoaded();\n \n const validation = validateVerificationRecord(verification);\n if (!validation.valid) {\n throw new Error(`Invalid verification: ${validation.errors.join(', ')}`);\n }\n \n this.verifications.set(verification.id, verification);\n await this.appendToFile({ type: 'verification', ...verification });\n }\n\n /**\n * Add a commit record\n */\n async addCommit(commit: CommitRecord): Promise<void> {\n await this.ensureLoaded();\n \n const validation = validateCommitRecord(commit);\n if (!validation.valid) {\n throw new Error(`Invalid commit: ${validation.errors.join(', ')}`);\n }\n \n this.commits.set(commit.id, commit);\n await this.appendToFile({ type: 'commit', ...commit });\n }\n\n /**\n * Add a reveal record\n */\n async addReveal(reveal: RevealRecord): Promise<void> {\n await this.ensureLoaded();\n \n const validation = validateRevealRecord(reveal);\n if (!validation.valid) {\n throw new Error(`Invalid reveal: ${validation.errors.join(', ')}`);\n }\n \n this.reveals.set(reveal.id, reveal);\n await this.appendToFile({ type: 'reveal', ...reveal });\n }\n\n /**\n * Get all verifications\n */\n async getVerifications(): Promise<VerificationRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.verifications.values());\n }\n\n /**\n * Get verifications for a specific target\n */\n async getVerificationsByTarget(target: string): Promise<VerificationRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.verifications.values()).filter(v => v.target === target);\n }\n\n /**\n * Get verifications by domain\n */\n async getVerificationsByDomain(domain: string): Promise<VerificationRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.verifications.values()).filter(v => v.domain === domain);\n }\n\n /**\n * Get verifications for an agent (where they are the target of verification)\n * This requires looking up the target message to find the agent\n * For now, we'll return all verifications and let the caller filter\n */\n async getVerificationsByDomainForAgent(domain: string): Promise<VerificationRecord[]> {\n return this.getVerificationsByDomain(domain);\n }\n\n /**\n * Get all commits\n */\n async getCommits(): Promise<CommitRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.commits.values());\n }\n\n /**\n * Get commit by ID\n */\n async getCommit(id: string): Promise<CommitRecord | null> {\n await this.ensureLoaded();\n return this.commits.get(id) || null;\n }\n\n /**\n * Get commits by agent\n */\n async getCommitsByAgent(agent: string): Promise<CommitRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.commits.values()).filter(c => c.agent === agent);\n }\n\n /**\n * Get all reveals\n */\n async getReveals(): Promise<RevealRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.reveals.values());\n }\n\n /**\n * Get reveal by commitment ID\n */\n async getRevealByCommitment(commitmentId: string): Promise<RevealRecord | null> {\n await this.ensureLoaded();\n return Array.from(this.reveals.values()).find(r => r.commitmentId === commitmentId) || null;\n }\n\n /**\n * Get reveals by agent\n */\n async getRevealsByAgent(agent: string): Promise<RevealRecord[]> {\n await this.ensureLoaded();\n return Array.from(this.reveals.values()).filter(r => r.agent === agent);\n }\n}\n","/**\n * Verification record creation and validation.\n * Core primitive for computational reputation.\n */\n\nimport { createEnvelope, verifyEnvelope } from '../message/envelope';\nimport type { VerificationRecord } from './types';\nimport { validateVerificationRecord } from './types';\n\n/**\n * Create a signed verification record\n * @param verifier - Public key of the verifying agent\n * @param privateKey - Private key for signing\n * @param target - ID of the message/output being verified\n * @param domain - Capability domain\n * @param verdict - Verification verdict\n * @param confidence - Verifier's confidence (0-1)\n * @param timestamp - Timestamp for the verification (ms)\n * @param evidence - Optional link to verification evidence\n * @returns Signed VerificationRecord\n */\nexport function createVerification(\n verifier: string,\n privateKey: string,\n target: string,\n domain: string,\n verdict: 'correct' | 'incorrect' | 'disputed',\n confidence: number,\n timestamp: number,\n evidence?: string\n): VerificationRecord {\n // Validate confidence range\n if (confidence < 0 || confidence > 1) {\n throw new Error('confidence must be between 0 and 1');\n }\n \n // Create the payload for signing\n const payload: Record<string, unknown> = {\n verifier,\n target,\n domain,\n verdict,\n confidence,\n timestamp,\n };\n \n if (evidence !== undefined) {\n payload.evidence = evidence;\n }\n \n // Create signed envelope with type 'verification'\n const envelope = createEnvelope('verification', verifier, privateKey, payload, timestamp, undefined, [verifier]);\n \n // Return verification record\n const record: VerificationRecord = {\n id: envelope.id,\n verifier,\n target,\n domain,\n verdict,\n confidence,\n timestamp,\n signature: envelope.signature,\n };\n \n if (evidence !== undefined) {\n record.evidence = evidence;\n }\n \n return record;\n}\n\n/**\n * Verify the cryptographic signature of a verification record\n * @param record - The verification record to verify\n * @returns Object with valid flag and optional reason for failure\n */\nexport function verifyVerificationSignature(\n record: VerificationRecord\n): { valid: boolean; reason?: string } {\n // First validate the structure\n const structureValidation = validateVerificationRecord(record);\n if (!structureValidation.valid) {\n return { \n valid: false, \n reason: `Invalid structure: ${structureValidation.errors.join(', ')}` \n };\n }\n \n // Reconstruct the envelope for signature verification\n const payload: Record<string, unknown> = {\n verifier: record.verifier,\n target: record.target,\n domain: record.domain,\n verdict: record.verdict,\n confidence: record.confidence,\n timestamp: record.timestamp,\n };\n \n if (record.evidence !== undefined) {\n payload.evidence = record.evidence;\n }\n \n const envelope = {\n id: record.id,\n type: 'verification' as const,\n from: record.verifier,\n to: [record.verifier],\n timestamp: record.timestamp,\n payload,\n signature: record.signature,\n };\n \n // Verify the envelope signature\n return verifyEnvelope(envelope);\n}\n","/**\n * Commit-reveal pattern implementation for tamper-proof predictions.\n * Agents commit to predictions before outcomes are known, then reveal after.\n */\n\nimport { createHash } from 'node:crypto';\nimport { createEnvelope } from '../message/envelope';\nimport type { CommitRecord, RevealRecord } from './types';\nimport { validateCommitRecord, validateRevealRecord } from './types';\n\n/**\n * Create a commitment hash for a prediction\n * @param prediction - The prediction string\n * @returns SHA-256 hash of the prediction (hex string)\n */\nexport function hashPrediction(prediction: string): string {\n return createHash('sha256').update(prediction).digest('hex');\n}\n\n/**\n * Create a signed commit record\n * @param agent - Public key of the committing agent\n * @param privateKey - Private key for signing\n * @param domain - Domain of the prediction\n * @param prediction - The prediction to commit to\n * @param timestamp - Timestamp for the commit (ms)\n * @param expiryMs - Expiry time in milliseconds from timestamp\n * @returns Signed CommitRecord\n */\nexport function createCommit(\n agent: string,\n privateKey: string,\n domain: string,\n prediction: string,\n timestamp: number,\n expiryMs: number\n): CommitRecord {\n const commitment = hashPrediction(prediction);\n const expiry = timestamp + expiryMs;\n \n // Create the payload for signing\n const payload = {\n agent,\n domain,\n commitment,\n timestamp,\n expiry,\n };\n \n // Create signed envelope with type 'commit'\n const envelope = createEnvelope('commit', agent, privateKey, payload, timestamp, undefined, [agent]);\n \n // Return commit record\n return {\n id: envelope.id,\n agent,\n domain,\n commitment,\n timestamp,\n expiry,\n signature: envelope.signature,\n };\n}\n\n/**\n * Create a signed reveal record\n * @param agent - Public key of the revealing agent\n * @param privateKey - Private key for signing\n * @param commitmentId - ID of the original commit record\n * @param prediction - The original prediction (plaintext)\n * @param outcome - The observed outcome\n * @param timestamp - Timestamp for the reveal (ms)\n * @param evidence - Optional evidence for the outcome\n * @returns Signed RevealRecord\n */\nexport function createReveal(\n agent: string,\n privateKey: string,\n commitmentId: string,\n prediction: string,\n outcome: string,\n timestamp: number,\n evidence?: string\n): RevealRecord {\n \n // Create the payload for signing\n const payload: Record<string, unknown> = {\n agent,\n commitmentId,\n prediction,\n outcome,\n timestamp,\n };\n \n if (evidence !== undefined) {\n payload.evidence = evidence;\n }\n \n // Create signed envelope with type 'reveal'\n const envelope = createEnvelope('reveal', agent, privateKey, payload, timestamp, undefined, [agent]);\n \n // Return reveal record\n const record: RevealRecord = {\n id: envelope.id,\n agent,\n commitmentId,\n prediction,\n outcome,\n timestamp,\n signature: envelope.signature,\n };\n \n if (evidence !== undefined) {\n record.evidence = evidence;\n }\n \n return record;\n}\n\n/**\n * Verify a reveal against its commitment\n * @param commit - The original commit record\n * @param reveal - The reveal record\n * @returns Object with valid flag and optional reason for failure\n */\nexport function verifyReveal(\n commit: CommitRecord,\n reveal: RevealRecord\n): { valid: boolean; reason?: string } {\n // Validate structures\n const commitValidation = validateCommitRecord(commit);\n if (!commitValidation.valid) {\n return { valid: false, reason: `Invalid commit: ${commitValidation.errors.join(', ')}` };\n }\n \n const revealValidation = validateRevealRecord(reveal);\n if (!revealValidation.valid) {\n return { valid: false, reason: `Invalid reveal: ${revealValidation.errors.join(', ')}` };\n }\n \n // Check that reveal references the correct commit\n if (reveal.commitmentId !== commit.id) {\n return { valid: false, reason: 'Reveal does not reference this commit' };\n }\n \n // Check that agents match\n if (reveal.agent !== commit.agent) {\n return { valid: false, reason: 'Reveal agent does not match commit agent' };\n }\n \n // Check that reveal is after commit expiry\n if (reveal.timestamp < commit.expiry) {\n return { valid: false, reason: 'Reveal timestamp is before commit expiry' };\n }\n \n // Verify that the prediction hash matches the commitment\n const predictedHash = hashPrediction(reveal.prediction);\n if (predictedHash !== commit.commitment) {\n return { valid: false, reason: 'Prediction hash does not match commitment' };\n }\n \n return { valid: true };\n}\n","/**\r\n * Trust score computation with exponential time decay.\r\n * Domain-specific reputation scoring from verification history.\r\n */\r\n\r\nimport type { VerificationRecord, TrustScore } from './types';\r\n\r\n/**\r\n * Exponential decay function for time-based reputation degradation.\r\n * @param deltaTimeMs - Time since verification (milliseconds)\r\n * @param lambda - Decay rate (default: ln(2)/70 ≈ 0.0099, giving 70-day half-life)\r\n * @returns Weight multiplier (0-1)\r\n */\r\nexport function decay(deltaTimeMs: number, lambda = Math.log(2) / 70): number {\r\n const deltaDays = deltaTimeMs / (1000 * 60 * 60 * 24);\r\n return Math.exp(-lambda * deltaDays);\r\n}\r\n\r\n/**\r\n * Compute verdict weight\r\n * @param verdict - Verification verdict\r\n * @returns Weight value (+1 for correct, -1 for incorrect, 0 for disputed)\r\n */\r\nfunction verdictWeight(verdict: 'correct' | 'incorrect' | 'disputed'): number {\r\n switch (verdict) {\r\n case 'correct':\r\n return 1;\r\n case 'incorrect':\r\n return -1;\r\n case 'disputed':\r\n return 0;\r\n }\r\n}\r\n\r\n/**\r\n * Options for recursive trust score computation.\r\n */\r\nexport interface TrustScoreOptions {\r\n /**\r\n * Optional function to get verifier's trust score for recursive weighting.\r\n * When provided, each verification is weighted by the verifier's own trust score.\r\n * Defaults to returning 1.0 (flat weighting, backward compatible).\r\n * New agents with no score should return 0.5 (neutral bootstrapping weight).\r\n */\r\n getVerifierScore?: (verifier: string, domain: string) => number;\r\n /**\r\n * Maximum recursion depth for recursive scoring. Default: 3.\r\n * At depth 0, flat weighting (1.0) is used instead of calling getVerifierScore.\r\n */\r\n maxDepth?: number;\r\n /**\r\n * Internal: set of agents currently being scored, used for cycle detection.\r\n * Pass a shared mutable Set when making recursive calls to enable cycle detection.\r\n * When a verifier is found in this set, neutral weight (0.5) is used instead of recursing.\r\n */\r\n visitedAgents?: Set<string>;\r\n}\r\n\r\n/**\r\n * Compute trust score for an agent in a specific domain\r\n * @param agent - Public key of the agent being scored\r\n * @param domain - Capability domain\r\n * @param verifications - All verification records (will be filtered by target and domain)\r\n * @param currentTime - Current timestamp (ms)\r\n * @param options - Optional settings for recursive scoring and cycle detection\r\n * @returns TrustScore object with computed reputation\r\n */\r\nexport function computeTrustScore(\r\n agent: string,\r\n domain: string,\r\n verifications: VerificationRecord[],\r\n currentTime: number,\r\n options?: TrustScoreOptions\r\n): TrustScore {\r\n // Filter verifications for this agent and domain\r\n const relevantVerifications = verifications.filter(\r\n v => v.target === agent && v.domain === domain\r\n );\r\n \r\n if (relevantVerifications.length === 0) {\r\n return {\r\n agent,\r\n domain,\r\n score: 0,\r\n verificationCount: 0,\r\n lastVerified: 0,\r\n topVerifiers: [],\r\n };\r\n }\r\n \r\n const maxDepth = options?.maxDepth ?? 3;\r\n const visitedAgents = options?.visitedAgents;\r\n const getVerifierScore = options?.getVerifierScore;\r\n\r\n // Mark current agent as being scored (cycle detection)\r\n if (visitedAgents) {\r\n visitedAgents.add(agent);\r\n }\r\n\r\n // Compute weighted score with time decay\r\n let totalWeight = 0;\r\n const verifierWeights = new Map<string, number>();\r\n \r\n for (const verification of relevantVerifications) {\r\n const deltaTime = currentTime - verification.timestamp;\r\n const decayFactor = decay(deltaTime);\r\n const verdict = verdictWeight(verification.verdict);\r\n\r\n // Determine verifier trust weight for recursive scoring\r\n let verifierTrustWeight: number;\r\n if (!getVerifierScore || maxDepth <= 0) {\r\n // No recursive scoring or depth limit reached — use flat weight\r\n verifierTrustWeight = 1.0;\r\n } else if (visitedAgents?.has(verification.verifier)) {\r\n // Cycle detected — use neutral weight (0.5) instead of recursing\r\n verifierTrustWeight = 0.5;\r\n } else {\r\n verifierTrustWeight = getVerifierScore(verification.verifier, domain);\r\n }\r\n\r\n const weight = verdict * verification.confidence * decayFactor * verifierTrustWeight;\r\n \r\n totalWeight += weight;\r\n \r\n // Track verifier contributions\r\n const currentVerifierWeight = verifierWeights.get(verification.verifier) ?? 0;\r\n verifierWeights.set(verification.verifier, currentVerifierWeight + Math.abs(weight));\r\n }\r\n\r\n // Backtrack: remove current agent from visited set for correct DFS traversal\r\n if (visitedAgents) {\r\n visitedAgents.delete(agent);\r\n }\r\n \r\n // Normalize score to 0-1 range\r\n // Positive verifications push toward 1, negative push toward 0\r\n const rawScore = totalWeight / Math.max(relevantVerifications.length, 1);\r\n const normalizedScore = Math.max(0, Math.min(1, (rawScore + 1) / 2));\r\n \r\n // Find most recent verification\r\n const lastVerified = Math.max(...relevantVerifications.map(v => v.timestamp));\r\n \r\n // Get top verifiers by absolute weight\r\n const topVerifiers = Array.from(verifierWeights.entries())\r\n .sort((a, b) => b[1] - a[1])\r\n .slice(0, 5)\r\n .map(([verifier]) => verifier);\r\n \r\n return {\r\n agent,\r\n domain,\r\n score: normalizedScore,\r\n verificationCount: relevantVerifications.length,\r\n lastVerified,\r\n topVerifiers,\r\n };\r\n}\r\n\r\n/**\r\n * Compute trust scores for an agent across multiple domains\r\n * @param agent - Public key of the agent being scored\r\n * @param verifications - All verification records\r\n * @param currentTime - Current timestamp (ms)\r\n * @returns Map of domain to TrustScore\r\n */\r\nexport function computeTrustScores(\r\n agent: string,\r\n verifications: VerificationRecord[],\r\n currentTime: number\r\n): Map<string, TrustScore> {\r\n // Get unique domains for this agent\r\n const domains = new Set(\r\n verifications\r\n .filter(v => v.target === agent)\r\n .map(v => v.domain)\r\n );\r\n \r\n const scores = new Map<string, TrustScore>();\r\n for (const domain of domains) {\r\n const score = computeTrustScore(agent, domain, verifications, currentTime);\r\n scores.set(domain, score);\r\n }\r\n \r\n return scores;\r\n}\r\n\r\n// Alias for backward compatibility\r\nexport const computeAllTrustScores = computeTrustScores;\r\n"],"mappings":";;;;;;;AAAA,SAAS,cAAc,eAAe,kBAAkB;AA2BjD,SAAS,eAAe,MAA8B;AAC3D,QAAM,UAAU,aAAa,MAAM,OAAO;AAC1C,SAAO,KAAK,MAAM,OAAO;AAC3B;AAOO,SAAS,eAAe,MAAc,QAA8B;AACzE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ACd,OACA,eACA,aACyB;AAEzB,QAAM,UAAU,IAAI;AAAA,IAClB,cACG,OAAO,OAAK,EAAE,WAAW,KAAK,EAC9B,IAAI,OAAK,EAAE,MAAM;AAAA,EACtB;AAEA,QAAM,SAAS,oBAAI,IAAwB;AAC3C,aAAW,UAAU,SAAS;AAC5B,UAAM,QAAQ,kBAAkB,OAAO,QAAQ,eAAe,WAAW;AACzE,WAAO,IAAI,QAAQ,KAAK;AAAA,EAC1B;AAEA,SAAO;AACT;AAGO,IAAM,wBAAwB;","names":["resolve","readFileSync","existsSync","writeFileSync","WebSocket","WebSocket","resolve","EventEmitter","EventEmitter","resolve","dirname","dirname"]}
|
package/dist/cli.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -45,6 +45,35 @@ declare function exportKeyPair(keyPair: KeyPair): KeyPair;
|
|
|
45
45
|
*/
|
|
46
46
|
declare function importKeyPair(publicKeyHex: string, privateKeyHex: string): KeyPair;
|
|
47
47
|
|
|
48
|
+
interface SeenKeyEntry {
|
|
49
|
+
publicKey: string;
|
|
50
|
+
firstSeen: number;
|
|
51
|
+
lastSeen: number;
|
|
52
|
+
seenCount: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Persists all encountered public keys to support reliable identity resolution.
|
|
56
|
+
* The full key remains the canonical identity — the shortened suffix is display only.
|
|
57
|
+
*/
|
|
58
|
+
declare class SeenKeyStore {
|
|
59
|
+
private readonly filePath;
|
|
60
|
+
private keys;
|
|
61
|
+
private dirty;
|
|
62
|
+
constructor(filePath: string);
|
|
63
|
+
/**
|
|
64
|
+
* Record a public key sighting. Adds or updates the entry.
|
|
65
|
+
*/
|
|
66
|
+
record(publicKey: string): void;
|
|
67
|
+
has(publicKey: string): boolean;
|
|
68
|
+
get(publicKey: string): SeenKeyEntry | undefined;
|
|
69
|
+
getAll(): SeenKeyEntry[];
|
|
70
|
+
/**
|
|
71
|
+
* Flush changes to disk. Call periodically or on shutdown.
|
|
72
|
+
*/
|
|
73
|
+
flush(): void;
|
|
74
|
+
private load;
|
|
75
|
+
}
|
|
76
|
+
|
|
48
77
|
/**
|
|
49
78
|
* Message types on the Agora network.
|
|
50
79
|
* Every piece of data flowing between agents is wrapped in an envelope.
|
|
@@ -1236,13 +1265,14 @@ type PeerReferenceDirectory = Record<string, PeerReferenceEntry> | Map<string, P
|
|
|
1236
1265
|
/**
|
|
1237
1266
|
* Shorten a full peer ID for display/reference.
|
|
1238
1267
|
* Canonical form:
|
|
1239
|
-
* - Configured name => "name
|
|
1240
|
-
* - Unknown/no-name => "
|
|
1268
|
+
* - Configured name => "name@<last8>"
|
|
1269
|
+
* - Unknown/no-name => "@<last8>"
|
|
1241
1270
|
*/
|
|
1242
1271
|
declare function shorten(id: string, directory?: PeerReferenceDirectory): string;
|
|
1243
1272
|
/**
|
|
1244
1273
|
* Expand a short peer reference to a full ID.
|
|
1245
|
-
* Supports: full ID, unique name,
|
|
1274
|
+
* Supports: full ID, unique name, name@last8, @last8.
|
|
1275
|
+
* Also supports legacy name...last8 and ...last8 forms.
|
|
1246
1276
|
*/
|
|
1247
1277
|
declare function expand(shortId: string, directory: PeerReferenceDirectory): string | undefined;
|
|
1248
1278
|
/**
|
|
@@ -1271,12 +1301,10 @@ declare function extractTextFromPayload(payload: unknown): string;
|
|
|
1271
1301
|
declare function sanitizeText(text: string): string;
|
|
1272
1302
|
/**
|
|
1273
1303
|
* Resolve a display name for a peer.
|
|
1274
|
-
*
|
|
1275
|
-
*
|
|
1276
|
-
* 2. relay-broadcast name (if not already a short-id token)
|
|
1277
|
-
* 3. undefined
|
|
1304
|
+
* Only returns locally configured names from the peer directory.
|
|
1305
|
+
* Sender-claimed names are never used — identity must be derived from verified keys.
|
|
1278
1306
|
*/
|
|
1279
|
-
declare function resolveDisplayName(publicKey: string,
|
|
1307
|
+
declare function resolveDisplayName(publicKey: string, _peerName?: string | undefined, directory?: PeerReferenceDirectory): string | undefined;
|
|
1280
1308
|
/**
|
|
1281
1309
|
* Resolves the name to broadcast when connecting to a relay.
|
|
1282
1310
|
* Priority order:
|
|
@@ -1298,9 +1326,9 @@ declare function resolveBroadcastName(config: {
|
|
|
1298
1326
|
} | string;
|
|
1299
1327
|
}, cliName?: string): string | undefined;
|
|
1300
1328
|
/**
|
|
1301
|
-
* Formats a display name using the canonical
|
|
1302
|
-
* If name exists: "name
|
|
1303
|
-
* If no name: "
|
|
1329
|
+
* Formats a display name using the canonical moniker form.
|
|
1330
|
+
* If name exists: "name@3f8c2247" (same form as shorten())
|
|
1331
|
+
* If no name: "@3f8c2247" (short ID only)
|
|
1304
1332
|
*
|
|
1305
1333
|
* @param name - Optional name to display (should not be a short ID)
|
|
1306
1334
|
* @param publicKey - The public key to use for short ID
|
|
@@ -1352,6 +1380,23 @@ interface SendMessageResult {
|
|
|
1352
1380
|
status: number;
|
|
1353
1381
|
error?: string;
|
|
1354
1382
|
}
|
|
1383
|
+
interface SendToAllOptions {
|
|
1384
|
+
/** Recipient identifiers — peer names, public keys, or short refs. */
|
|
1385
|
+
recipients: string[];
|
|
1386
|
+
type: MessageType;
|
|
1387
|
+
payload: unknown;
|
|
1388
|
+
inReplyTo?: string;
|
|
1389
|
+
direct?: boolean;
|
|
1390
|
+
relayOnly?: boolean;
|
|
1391
|
+
}
|
|
1392
|
+
interface SendToAllResult {
|
|
1393
|
+
/** True when at least one recipient succeeded (or recipients is empty). */
|
|
1394
|
+
ok: boolean;
|
|
1395
|
+
errors: Array<{
|
|
1396
|
+
recipient: string;
|
|
1397
|
+
error: string;
|
|
1398
|
+
}>;
|
|
1399
|
+
}
|
|
1355
1400
|
interface ReplyToEnvelopeOptions {
|
|
1356
1401
|
/** The public key of the target (from envelope.sender) */
|
|
1357
1402
|
targetPubkey: string;
|
|
@@ -1417,6 +1462,13 @@ declare class AgoraService {
|
|
|
1417
1462
|
* Tries HTTP webhook first; falls back to relay if HTTP is unavailable.
|
|
1418
1463
|
*/
|
|
1419
1464
|
sendMessage(options: SendMessageOptions): Promise<SendMessageResult>;
|
|
1465
|
+
/**
|
|
1466
|
+
* Send a message to multiple recipients.
|
|
1467
|
+
* Each envelope carries the full recipient list in its `to` field so every
|
|
1468
|
+
* receiver knows who else received the message (enables multi-party replies).
|
|
1469
|
+
* Delivery is attempted per-recipient via HTTP-first + relay fallback.
|
|
1470
|
+
*/
|
|
1471
|
+
sendToAll(options: SendToAllOptions): Promise<SendToAllResult>;
|
|
1420
1472
|
/**
|
|
1421
1473
|
* Reply to an envelope from any sender via relay.
|
|
1422
1474
|
* Unlike sendMessage(), this does NOT require the target to be a configured peer.
|
|
@@ -1932,4 +1984,4 @@ declare function syncReputationFromPeer(agentPublicKey: string, domain: string,
|
|
|
1932
1984
|
skipped: number;
|
|
1933
1985
|
}>;
|
|
1934
1986
|
|
|
1935
|
-
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 ConversationEntry, type CreateEnvelopeFn, DEFAULT_BOOTSTRAP_RELAYS, type DecodeInboundResult, type DiscoverPayload, type DiscoverResponsePayload, DiscoveryService, type Envelope, type ExportedConfig, IGNORED_FILE_NAME, IgnoredPeersManager, type ImportResult, InboundMessageGuard, type InboundSecurityOptions, 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 PeerReferenceDirectory, type PeerReferenceEntry, 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, compactKnownInlineReferences, computeAllTrustScores, computeId, computeTrustScore, computeTrustScores, createCapability, createCommit, createEnvelope, createRestRouter, createReveal, createToken, createVerification, decay, decodeInboundEnvelope, expand, expandInlineReferences, exportConfig, exportKeyPair, extractTextFromPayload, formatConversationLine, formatDisplayName, generateKeyPair, getConfigDir, getDefaultBootstrapRelay, getDefaultConfigPath, getIgnoredPeersPath, getProfileConfigPath, handleReputationQuery, hashPrediction, importConfig, importKeyPair, initPeerConfig, listProfiles, loadAgoraConfig, loadAgoraConfigAsync, loadIgnoredPeers, loadPeerConfig, parseBootstrapRelay, parseConversationLine, requireAuth, resolveBroadcastName, resolveDisplayName, revokeToken, runRelay, sanitizeText, saveAgoraConfig, saveIgnoredPeers, savePeerConfig, sendToPeer, shortKey, shorten, signMessage, syncReputationFromPeer, validateCapability, validateCommitRecord, validatePeerListRequest, validatePeerListResponse, validatePeerReferral, validateRevealRecord, validateVerificationRecord, verifyEnvelope, verifyReveal, verifySignature, verifyVerificationSignature };
|
|
1987
|
+
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 ConversationEntry, type CreateEnvelopeFn, DEFAULT_BOOTSTRAP_RELAYS, type DecodeInboundResult, type DiscoverPayload, type DiscoverResponsePayload, DiscoveryService, type Envelope, type ExportedConfig, IGNORED_FILE_NAME, IgnoredPeersManager, type ImportResult, InboundMessageGuard, type InboundSecurityOptions, 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 PeerReferenceDirectory, type PeerReferenceEntry, 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 SeenKeyEntry, SeenKeyStore, type SendMessageOptions, type SendMessageResult, type SendToAllOptions, type SendToAllResult, type StoredMessage, type TransportConfig, type TrustScore, type TrustScoreOptions, type ValidationResult, type VerificationRecord, type VerifyEnvelopeFn, canonicalize, compactInlineReferences, compactKnownInlineReferences, computeAllTrustScores, computeId, computeTrustScore, computeTrustScores, createCapability, createCommit, createEnvelope, createRestRouter, createReveal, createToken, createVerification, decay, decodeInboundEnvelope, expand, expandInlineReferences, exportConfig, exportKeyPair, extractTextFromPayload, formatConversationLine, formatDisplayName, generateKeyPair, getConfigDir, getDefaultBootstrapRelay, getDefaultConfigPath, getIgnoredPeersPath, getProfileConfigPath, handleReputationQuery, hashPrediction, importConfig, importKeyPair, initPeerConfig, listProfiles, loadAgoraConfig, loadAgoraConfigAsync, loadIgnoredPeers, loadPeerConfig, parseBootstrapRelay, parseConversationLine, requireAuth, resolveBroadcastName, resolveDisplayName, revokeToken, runRelay, sanitizeText, saveAgoraConfig, saveIgnoredPeers, savePeerConfig, sendToPeer, shortKey, shorten, signMessage, syncReputationFromPeer, validateCapability, validateCommitRecord, validatePeerListRequest, validatePeerListResponse, validatePeerReferral, validateRevealRecord, validateVerificationRecord, verifyEnvelope, verifyReveal, verifySignature, verifyVerificationSignature };
|