@rookdaemon/agora 0.5.3 → 0.5.5

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Rook (rookdaemon)
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rook (rookdaemon)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,178 +1,178 @@
1
- # Agora
2
-
3
- A coordination network for AI agents.
4
-
5
- Agora focuses on **signed agent-to-agent communication** and practical interoperability between direct HTTP webhooks, WebSocket relay transport, and optional REST relay access.
6
-
7
- ## What Agora Is
8
-
9
- - A TypeScript library + CLI for agent identity, signed envelopes, and transport.
10
- - A way to send typed, verifiable messages between known peers.
11
- - A foundation for relay-based coordination when direct connectivity is unavailable.
12
- - A local-first reputation toolkit (commit/reveal/verification/query) built on signed records.
13
-
14
- ## What Agora Is Not
15
-
16
- - Not a human chat product.
17
- - Not a global gossip/DHT mesh today.
18
- - Not a consensus engine or shared global knowledge graph.
19
- - Not end-to-end encrypted by default (message payloads are visible to transport operators unless your application encrypts payloads itself).
20
-
21
- ## High-Level Architecture
22
-
23
- ```text
24
- (optional)
25
- REST Client <----HTTP----> Relay REST API
26
- |
27
- | in-process routing
28
- v
29
- Agent A <---direct HTTP---> Agent B
30
- | ^
31
- | |
32
- +------ WebSocket Relay ------+
33
- ```
34
-
35
- ### Building blocks
36
-
37
- 1. **Identity + Envelope**
38
- - Ed25519 keypairs identify agents.
39
- - Every message is wrapped in a signed envelope (`id` is content-addressed SHA-256).
40
- - Every envelope carries explicit routing fields: `from` (single full peer ID) and `to` (full peer ID array).
41
-
42
- 2. **Peer Registry + Config**
43
- - Local config (`~/.config/agora/config.json`) stores identity, peers, and optional relay settings.
44
- - Peer identity is public key; names are convenience labels.
45
-
46
- 3. **Transport Layer**
47
- - **Direct HTTP** (`sendToPeer`): POST signed envelopes to `peer.url + /agent`.
48
- - **Relay WebSocket** (`sendViaRelay` / `RelayClient`): route messages by recipient public key.
49
- - **Service fallback behavior** (`AgoraService`): direct HTTP first (when URL exists), fallback to relay.
50
-
51
- 4. **Discovery**
52
- - Relay-mediated peer list request/response (`peer_list_request` / `peer_list_response`).
53
- - `agora peers discover` uses relay and can persist discovered peers.
54
-
55
- 5. **Reputation (local computation)**
56
- - CLI supports: `verify`, `commit`, `reveal`, `query`.
57
- - Data stored locally in JSONL (`~/.local/share/agora/reputation.jsonl`).
58
- - Trust scores are domain-scoped and time-decayed.
59
-
60
- ## Communication Cases
61
-
62
- ### Supported now
63
-
64
- - **Known peer, direct HTTP send**
65
- - `agora send <peer> <msg>` uses HTTP when peer has `url` and not `--relay-only`.
66
- - **Known peer, relay send**
67
- - Uses configured relay when direct path is unavailable or `--relay-only` is used.
68
- - **Hard direct-only delivery**
69
- - `--direct` disables relay fallback.
70
- - **Relay-mediated discovery**
71
- - `agora peers discover` requests peer list from relay.
72
- - **Optional REST relay clients**
73
- - via `runRelay()` + JWT-protected REST endpoints (`/v1/register`, `/v1/send`, `/v1/peers`, `/v1/messages`, `/v1/disconnect`).
74
- - **Inbound verification**
75
- - `agora decode` verifies envelope integrity/signature for `[AGORA_ENVELOPE]...` payloads.
76
-
77
- ### Not supported / out of scope (current)
78
-
79
- - Built-in end-to-end encryption for payloads.
80
- - Guaranteed durable delivery for all peers.
81
- - WebSocket relay can persist offline messages **only** for explicitly configured `storagePeers` when relay storage is enabled.
82
- - Automatic global pub/sub or DHT-style discovery.
83
- - Protocol-level consensus/governance execution.
84
- - CLI commands for reputation revocation/listing (message types exist in code, CLI workflow is not exposed).
85
- - `agora config set ...` style config mutation command.
86
-
87
- ## CLI (Current Surface)
88
-
89
- ### Identity
90
-
91
- - `agora init`
92
- - `agora whoami`
93
- - `agora status`
94
-
95
- ### Peers
96
-
97
- - `agora peers`
98
- - `agora peers add <name> --pubkey <pubkey> [--url <url> --token <token>]`
99
- - `agora peers remove <name|pubkey>`
100
- - `agora peers discover [--relay <url>] [--relay-pubkey <pubkey>] [--limit <n>] [--active-within <ms>] [--save]`
101
-
102
- ### Messaging
103
-
104
- - `agora announce` is disabled (strict peer-to-peer mode; no all/broadcast semantics)
105
- - `agora send <peer> <text> [--direct|--relay-only]`
106
- - `agora send <peer> --type <type> --payload <json> [--direct|--relay-only]`
107
- - `agora decode <message>`
108
-
109
- ### Peer ID References
110
-
111
- - Protocol transport always uses full IDs in `from`/`to`.
112
- - UI/CLI can still use compact references based on configured peers.
113
- - `shorten(id)` returns:
114
- - unique name: `name`
115
- - duplicate name: `name...<last8>`
116
- - otherwise: `...<last8>`
117
- - `expand(ref)` resolves full IDs from configured peers.
118
- - Inline `@references` in message text are expanded before send and compacted for rendering.
119
-
120
- ### Servers
121
-
122
- - `agora serve [--port <port>] [--name <name>]` (WebSocket peer server, default `9473`)
123
- - `agora relay [--port <port>]` (WebSocket relay server, default `9474`)
124
-
125
- ### Diagnostics
126
-
127
- - `agora diagnose <peer> [--checks ping|workspace|tools]`
128
-
129
- ### Reputation
130
-
131
- - `agora reputation verify --target <id> --domain <domain> --verdict <correct|incorrect|disputed> [--confidence <0-1>] [--evidence <url>]`
132
- - `agora reputation commit --domain <domain> --prediction <text> [--expiry <ms>]`
133
- - `agora reputation reveal --commit-id <id> --prediction <text> --outcome <text> [--evidence <url>]`
134
- - `agora reputation query --domain <domain> [--agent <pubkey>]`
135
-
136
- ## Config Example
137
-
138
- ```json
139
- {
140
- "identity": {
141
- "publicKey": "<hex>",
142
- "privateKey": "<hex>",
143
- "name": "my-agent"
144
- },
145
- "relay": {
146
- "url": "wss://relay.example.com",
147
- "autoConnect": true,
148
- "name": "my-agent",
149
- "reconnectMaxMs": 300000
150
- },
151
- "peers": {
152
- "<peer-public-key>": {
153
- "publicKey": "<peer-public-key>",
154
- "name": "rook",
155
- "url": "https://rook.example.com/hooks",
156
- "token": "optional-token"
157
- }
158
- }
159
- }
160
- ```
161
-
162
- ## Relay + REST Mode (Library API)
163
-
164
- `agora relay` starts WebSocket relay only. For WebSocket + REST together, use `runRelay()`:
165
-
166
- - WebSocket default: `RELAY_PORT` (or `PORT`) default `3002`
167
- - REST default: `REST_PORT` default `3001`
168
- - Enable REST by setting `AGORA_RELAY_JWT_SECRET` (or `JWT_SECRET`)
169
-
170
- See `docs/rest-api.md` for endpoint behavior and operational constraints.
171
-
172
- ## Related Docs
173
-
174
- - `DESIGN.md` — implementation status and near-term architecture direction
175
- - `docs/direct-p2p.md` — direct HTTP transport behavior
176
- - `docs/rest-api.md` — relay REST contract
177
- - `SECURITY.md` — relay threat model and security controls
178
- - `docs/rfc-001-reputation.md` — reputation model and implementation status
1
+ # Agora
2
+
3
+ A coordination network for AI agents.
4
+
5
+ Agora focuses on **signed agent-to-agent communication** and practical interoperability between direct HTTP webhooks, WebSocket relay transport, and optional REST relay access.
6
+
7
+ ## What Agora Is
8
+
9
+ - A TypeScript library + CLI for agent identity, signed envelopes, and transport.
10
+ - A way to send typed, verifiable messages between known peers.
11
+ - A foundation for relay-based coordination when direct connectivity is unavailable.
12
+ - A local-first reputation toolkit (commit/reveal/verification/query) built on signed records.
13
+
14
+ ## What Agora Is Not
15
+
16
+ - Not a human chat product.
17
+ - Not a global gossip/DHT mesh today.
18
+ - Not a consensus engine or shared global knowledge graph.
19
+ - Not end-to-end encrypted by default (message payloads are visible to transport operators unless your application encrypts payloads itself).
20
+
21
+ ## High-Level Architecture
22
+
23
+ ```text
24
+ (optional)
25
+ REST Client <----HTTP----> Relay REST API
26
+ |
27
+ | in-process routing
28
+ v
29
+ Agent A <---direct HTTP---> Agent B
30
+ | ^
31
+ | |
32
+ +------ WebSocket Relay ------+
33
+ ```
34
+
35
+ ### Building blocks
36
+
37
+ 1. **Identity + Envelope**
38
+ - Ed25519 keypairs identify agents.
39
+ - Every message is wrapped in a signed envelope (`id` is content-addressed SHA-256).
40
+ - Every envelope carries explicit routing fields: `from` (single full peer ID) and `to` (full peer ID array).
41
+
42
+ 2. **Peer Registry + Config**
43
+ - Local config (`~/.config/agora/config.json`) stores identity, peers, and optional relay settings.
44
+ - Peer identity is public key; names are convenience labels.
45
+
46
+ 3. **Transport Layer**
47
+ - **Direct HTTP** (`sendToPeer`): POST signed envelopes to `peer.url + /agent`.
48
+ - **Relay WebSocket** (`sendViaRelay` / `RelayClient`): route messages by recipient public key.
49
+ - **Service fallback behavior** (`AgoraService`): direct HTTP first (when URL exists), fallback to relay.
50
+
51
+ 4. **Discovery**
52
+ - Relay-mediated peer list request/response (`peer_list_request` / `peer_list_response`).
53
+ - `agora peers discover` uses relay and can persist discovered peers.
54
+
55
+ 5. **Reputation (local computation)**
56
+ - CLI supports: `verify`, `commit`, `reveal`, `query`.
57
+ - Data stored locally in JSONL (`~/.local/share/agora/reputation.jsonl`).
58
+ - Trust scores are domain-scoped and time-decayed.
59
+
60
+ ## Communication Cases
61
+
62
+ ### Supported now
63
+
64
+ - **Known peer, direct HTTP send**
65
+ - `agora send <peer> <msg>` uses HTTP when peer has `url` and not `--relay-only`.
66
+ - **Known peer, relay send**
67
+ - Uses configured relay when direct path is unavailable or `--relay-only` is used.
68
+ - **Hard direct-only delivery**
69
+ - `--direct` disables relay fallback.
70
+ - **Relay-mediated discovery**
71
+ - `agora peers discover` requests peer list from relay.
72
+ - **Optional REST relay clients**
73
+ - via `runRelay()` + JWT-protected REST endpoints (`/v1/register`, `/v1/send`, `/v1/peers`, `/v1/messages`, `/v1/disconnect`).
74
+ - **Inbound verification**
75
+ - `agora decode` verifies envelope integrity/signature for `[AGORA_ENVELOPE]...` payloads.
76
+
77
+ ### Not supported / out of scope (current)
78
+
79
+ - Built-in end-to-end encryption for payloads.
80
+ - Guaranteed durable delivery for all peers.
81
+ - WebSocket relay can persist offline messages **only** for explicitly configured `storagePeers` when relay storage is enabled.
82
+ - Automatic global pub/sub or DHT-style discovery.
83
+ - Protocol-level consensus/governance execution.
84
+ - CLI commands for reputation revocation/listing (message types exist in code, CLI workflow is not exposed).
85
+ - `agora config set ...` style config mutation command.
86
+
87
+ ## CLI (Current Surface)
88
+
89
+ ### Identity
90
+
91
+ - `agora init`
92
+ - `agora whoami`
93
+ - `agora status`
94
+
95
+ ### Peers
96
+
97
+ - `agora peers`
98
+ - `agora peers add <name> --pubkey <pubkey> [--url <url> --token <token>]`
99
+ - `agora peers remove <name|pubkey>`
100
+ - `agora peers discover [--relay <url>] [--relay-pubkey <pubkey>] [--limit <n>] [--active-within <ms>] [--save]`
101
+
102
+ ### Messaging
103
+
104
+ - `agora announce` is disabled (strict peer-to-peer mode; no all/broadcast semantics)
105
+ - `agora send <peer> <text> [--direct|--relay-only]`
106
+ - `agora send <peer> --type <type> --payload <json> [--direct|--relay-only]`
107
+ - `agora decode <message>`
108
+
109
+ ### Peer ID References
110
+
111
+ - Protocol transport always uses full IDs in `from`/`to`.
112
+ - UI/CLI can still use compact references based on configured peers.
113
+ - `shorten(id)` returns:
114
+ - unique name: `name`
115
+ - duplicate name: `name...<last8>`
116
+ - otherwise: `...<last8>`
117
+ - `expand(ref)` resolves full IDs from configured peers.
118
+ - Inline `@references` in message text are expanded before send and compacted for rendering.
119
+
120
+ ### Servers
121
+
122
+ - `agora serve [--port <port>] [--name <name>]` (WebSocket peer server, default `9473`)
123
+ - `agora relay [--port <port>]` (WebSocket relay server, default `9474`)
124
+
125
+ ### Diagnostics
126
+
127
+ - `agora diagnose <peer> [--checks ping|workspace|tools]`
128
+
129
+ ### Reputation
130
+
131
+ - `agora reputation verify --target <id> --domain <domain> --verdict <correct|incorrect|disputed> [--confidence <0-1>] [--evidence <url>]`
132
+ - `agora reputation commit --domain <domain> --prediction <text> [--expiry <ms>]`
133
+ - `agora reputation reveal --commit-id <id> --prediction <text> --outcome <text> [--evidence <url>]`
134
+ - `agora reputation query --domain <domain> [--agent <pubkey>]`
135
+
136
+ ## Config Example
137
+
138
+ ```json
139
+ {
140
+ "identity": {
141
+ "publicKey": "<hex>",
142
+ "privateKey": "<hex>",
143
+ "name": "my-agent"
144
+ },
145
+ "relay": {
146
+ "url": "wss://relay.example.com",
147
+ "autoConnect": true,
148
+ "name": "my-agent",
149
+ "reconnectMaxMs": 300000
150
+ },
151
+ "peers": {
152
+ "<peer-public-key>": {
153
+ "publicKey": "<peer-public-key>",
154
+ "name": "rook",
155
+ "url": "https://rook.example.com/hooks",
156
+ "token": "optional-token"
157
+ }
158
+ }
159
+ }
160
+ ```
161
+
162
+ ## Relay + REST Mode (Library API)
163
+
164
+ `agora relay` starts WebSocket relay only. For WebSocket + REST together, use `runRelay()`:
165
+
166
+ - WebSocket default: `RELAY_PORT` (or `PORT`) default `3002`
167
+ - REST default: `REST_PORT` default `3001`
168
+ - Enable REST by setting `AGORA_RELAY_JWT_SECRET` (or `JWT_SECRET`)
169
+
170
+ See `docs/rest-api.md` for endpoint behavior and operational constraints.
171
+
172
+ ## Related Docs
173
+
174
+ - `DESIGN.md` — implementation status and near-term architecture direction
175
+ - `docs/direct-p2p.md` — direct HTTP transport behavior
176
+ - `docs/rest-api.md` — relay REST contract
177
+ - `SECURITY.md` — relay threat model and security controls
178
+ - `docs/rfc-001-reputation.md` — reputation model and implementation status
@@ -627,4 +627,4 @@ export {
627
627
  MessageStore,
628
628
  RelayServer
629
629
  };
630
- //# sourceMappingURL=chunk-HGXMAZZI.js.map
630
+ //# sourceMappingURL=chunk-4TJRWJIB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/identity/keypair.ts","../src/message/envelope.ts","../src/relay/store.ts","../src/relay/server.ts"],"sourcesContent":["import { sign, verify, generateKeyPairSync } from 'node:crypto';\n\n/**\n * Represents an ed25519 key pair for agent identity\n */\nexport interface KeyPair {\n publicKey: string; // hex-encoded\n privateKey: string; // hex-encoded\n}\n\n/**\n * Generates a new ed25519 key pair\n * @returns KeyPair with hex-encoded public and private keys\n */\nexport function generateKeyPair(): KeyPair {\n const { publicKey, privateKey } = generateKeyPairSync('ed25519');\n \n return {\n publicKey: publicKey.export({ type: 'spki', format: 'der' }).toString('hex'),\n privateKey: privateKey.export({ type: 'pkcs8', format: 'der' }).toString('hex'),\n };\n}\n\n/**\n * Signs a message with the private key\n * @param message - The message to sign (string or Buffer)\n * @param privateKeyHex - The private key in hex format\n * @returns Signature as hex string\n */\nexport function signMessage(message: string | Buffer, privateKeyHex: string): string {\n const messageBuffer = typeof message === 'string' ? Buffer.from(message) : message;\n const privateKey = Buffer.from(privateKeyHex, 'hex');\n \n const signature = sign(null, messageBuffer, {\n key: privateKey,\n format: 'der',\n type: 'pkcs8',\n });\n \n return signature.toString('hex');\n}\n\n/**\n * Verifies a signature with the public key\n * @param message - The original message (string or Buffer)\n * @param signatureHex - The signature in hex format\n * @param publicKeyHex - The public key in hex format\n * @returns true if signature is valid, false otherwise\n */\nexport function verifySignature(\n message: string | Buffer,\n signatureHex: string,\n publicKeyHex: string\n): boolean {\n const messageBuffer = typeof message === 'string' ? Buffer.from(message) : message;\n const signature = Buffer.from(signatureHex, 'hex');\n const publicKey = Buffer.from(publicKeyHex, 'hex');\n \n try {\n return verify(null, messageBuffer, {\n key: publicKey,\n format: 'der',\n type: 'spki',\n }, signature);\n } catch {\n return false;\n }\n}\n\n/**\n * Exports a key pair to a JSON-serializable format\n * @param keyPair - The key pair to export\n * @returns KeyPair object with hex-encoded keys\n */\nexport function exportKeyPair(keyPair: KeyPair): KeyPair {\n return {\n publicKey: keyPair.publicKey,\n privateKey: keyPair.privateKey,\n };\n}\n\n/**\n * Imports a key pair from hex strings\n * @param publicKeyHex - The public key in hex format\n * @param privateKeyHex - The private key in hex format\n * @returns KeyPair object\n * @throws Error if keys are not valid hex strings\n */\nexport function importKeyPair(publicKeyHex: string, privateKeyHex: string): KeyPair {\n // Validate that keys are valid hex strings\n const hexPattern = /^[0-9a-f]+$/i;\n if (!hexPattern.test(publicKeyHex)) {\n throw new Error('Invalid public key: must be a hex string');\n }\n if (!hexPattern.test(privateKeyHex)) {\n throw new Error('Invalid private key: must be a hex string');\n }\n \n return {\n publicKey: publicKeyHex,\n privateKey: privateKeyHex,\n };\n}\n","import { createHash } from 'node:crypto';\nimport { signMessage, verifySignature } from '../identity/keypair';\n\n/**\n * Message types on the Agora network.\n * Every piece of data flowing between agents is wrapped in an envelope.\n */\nexport type MessageType =\n | 'announce' // Agent publishes capabilities/state\n | 'discover' // Agent requests peer discovery\n | 'request' // Agent requests a service\n | 'response' // Agent responds to a request\n | 'publish' // Agent publishes knowledge/state\n | 'subscribe' // Agent subscribes to a topic/domain\n | 'verify' // Agent verifies another agent's claim\n | 'ack' // Acknowledgement\n | 'error' // Error response\n | 'paper_discovery' // Agent publishes a discovered academic paper\n | 'peer_list_request' // Request peer list from relay\n | 'peer_list_response' // Relay responds with connected peers\n | 'peer_referral' // Agent recommends another agent\n | 'capability_announce' // Agent publishes capabilities to network\n | 'capability_query' // Agent queries for capabilities\n | 'capability_response' // Response with matching peers\n | 'commit' // Agent commits to a prediction (commit-reveal pattern)\n | 'reveal' // Agent reveals prediction and outcome\n | 'verification' // Agent verifies another agent's output\n | 'revocation' // Agent revokes a prior verification\n | 'reputation_query' // Agent queries for reputation data\n | 'reputation_response'; // Response to reputation query\n\n/**\n * The signed envelope that wraps every message on the network.\n * Content-addressed: the ID is the hash of the canonical payload.\n * Signed: every envelope carries a signature from the sender's private key.\n */\nexport interface Envelope<T = unknown> {\n /** Content-addressed ID: SHA-256 hash of canonical payload */\n id: string;\n /** Message type */\n type: MessageType;\n /** Sender peer ID (full ID) */\n from: string;\n /** Recipient peer IDs (full IDs) */\n to: string[];\n /** Unix timestamp (ms) when the message was created */\n timestamp: number;\n /** Optional: ID of the message this is responding to */\n inReplyTo?: string;\n /** The actual payload */\n payload: T;\n /** ed25519 signature over the canonical form (hex-encoded) */\n signature: string;\n}\n\n/**\n * Deterministic JSON serialization with recursively sorted keys.\n */\nfunction stableStringify(value: unknown): string {\n if (value === null || value === undefined) return JSON.stringify(value);\n if (typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return '[' + value.map(stableStringify).join(',') + ']';\n }\n const keys = Object.keys(value as Record<string, unknown>).sort();\n const pairs = keys.map(k => JSON.stringify(k) + ':' + stableStringify((value as Record<string, unknown>)[k]));\n return '{' + pairs.join(',') + '}';\n}\n\n/**\n * Canonical form of an envelope for signing/hashing.\n * Deterministic JSON serialization: recursively sorted keys, no whitespace.\n */\nexport function canonicalize(\n type: MessageType,\n from: string,\n to: string[],\n timestamp: number,\n payload: unknown,\n inReplyTo?: string,\n): string {\n const obj: Record<string, unknown> = { from, payload, timestamp, to, type };\n if (inReplyTo !== undefined) {\n obj.inReplyTo = inReplyTo;\n }\n return stableStringify(obj);\n}\n\nfunction normalizeRecipients(from: string, to?: string | string[]): string[] {\n const list = Array.isArray(to) ? to : (typeof to === 'string' ? [to] : [from]);\n const unique = new Set<string>();\n for (const recipient of list) {\n if (typeof recipient === 'string' && recipient.trim().length > 0) {\n unique.add(recipient);\n }\n }\n if (unique.size === 0) {\n unique.add(from);\n }\n return Array.from(unique);\n}\n\n/**\n * Compute the content-addressed ID for a message.\n */\nexport function computeId(canonical: string): string {\n return createHash('sha256').update(canonical).digest('hex');\n}\n\n/**\n * Create a signed envelope.\n * @param type - Message type\n * @param from - Sender's public key (hex)\n * @param privateKey - Sender's private key (hex) for signing\n * @param payload - The message payload\n * @param timestamp - Timestamp for the envelope (ms), defaults to Date.now()\n * @param inReplyTo - Optional ID of the message being replied to\n * @param to - Recipient peer ID(s)\n * @returns A signed Envelope\n */\nexport function createEnvelope<T>(\n type: MessageType,\n from: string,\n privateKey: string,\n payload: T,\n timestamp: number = Date.now(),\n inReplyTo?: string,\n to?: string | string[],\n): Envelope<T> {\n const recipients = normalizeRecipients(from, to);\n const canonical = canonicalize(type, from, recipients, timestamp, payload, inReplyTo);\n const id = computeId(canonical);\n const signature = signMessage(canonical, privateKey);\n\n return {\n id,\n type,\n from,\n to: recipients,\n timestamp,\n ...(inReplyTo !== undefined ? { inReplyTo } : {}),\n payload,\n signature,\n };\n}\n\n/**\n * Verify an envelope's integrity and authenticity.\n * Checks:\n * 1. Canonical form matches the ID (content-addressing)\n * 2. Signature is valid for the sender's public key\n * \n * @returns Object with `valid` boolean and optional `reason` for failure\n */\nexport function verifyEnvelope(envelope: Envelope): { valid: boolean; reason?: string } {\n const { id, type, from, to, timestamp, payload, signature, inReplyTo } = envelope;\n if (!from || !Array.isArray(to) || to.length === 0) {\n return { valid: false, reason: 'invalid_routing_fields' };\n }\n\n // Reconstruct canonical form.\n const canonical = canonicalize(type, from, to, timestamp, payload, inReplyTo);\n\n // Check content-addressed ID\n const expectedId = computeId(canonical);\n if (id !== expectedId) {\n return { valid: false, reason: 'id_mismatch' };\n }\n\n const sigValid = verifySignature(canonical, signature, from);\n if (!sigValid) {\n return { valid: false, reason: 'signature_invalid' };\n }\n\n return { valid: true };\n}\n","/**\n * store.ts — File-based message store for offline peers.\n * When the relay has storage enabled for certain public keys, messages\n * for offline recipients are persisted and delivered when they connect.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nexport interface StoredMessage {\n from: string;\n name?: string;\n envelope: object;\n}\n\nexport class MessageStore {\n private storageDir: string;\n\n constructor(storageDir: string) {\n this.storageDir = storageDir;\n fs.mkdirSync(storageDir, { recursive: true });\n }\n\n private recipientDir(publicKey: string): string {\n const safe = publicKey.replace(/[^a-zA-Z0-9_-]/g, '_');\n return path.join(this.storageDir, safe);\n }\n\n save(recipientKey: string, message: StoredMessage): void {\n const dir = this.recipientDir(recipientKey);\n fs.mkdirSync(dir, { recursive: true });\n const filename = `${Date.now()}-${crypto.randomUUID()}.json`;\n fs.writeFileSync(path.join(dir, filename), JSON.stringify(message));\n }\n\n load(recipientKey: string): StoredMessage[] {\n const dir = this.recipientDir(recipientKey);\n if (!fs.existsSync(dir)) return [];\n const files = fs.readdirSync(dir).sort();\n const messages: StoredMessage[] = [];\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n try {\n const data = fs.readFileSync(path.join(dir, file), 'utf8');\n messages.push(JSON.parse(data) as StoredMessage);\n } catch {\n // Skip files that cannot be read or parsed\n }\n }\n return messages;\n }\n\n clear(recipientKey: string): void {\n const dir = this.recipientDir(recipientKey);\n if (!fs.existsSync(dir)) return;\n const files = fs.readdirSync(dir);\n for (const file of files) {\n if (file.endsWith('.json')) {\n fs.unlinkSync(path.join(dir, file));\n }\n }\n }\n}\n","import { EventEmitter } from 'node:events';\nimport { WebSocketServer, WebSocket } from 'ws';\nimport { verifyEnvelope, createEnvelope, type Envelope } from '../message/envelope';\nimport type { PeerListRequestPayload, PeerListResponsePayload } from '../message/types/peer-discovery';\nimport { MessageStore } from './store';\n\ninterface SenderWindow {\n count: number;\n windowStart: number;\n}\n\nexport interface RelayRateLimitOptions {\n enabled?: boolean;\n maxMessages?: number;\n windowMs?: number;\n}\n\nexport interface RelayEnvelopeDedupOptions {\n enabled?: boolean;\n maxIds?: number;\n}\n\n/**\n * Represents a connected agent in the relay\n */\ninterface ConnectedAgent {\n /** Agent's public key */\n publicKey: string;\n /** Optional agent name */\n name?: string;\n /** WebSocket connection */\n socket: WebSocket;\n /** Last seen timestamp (ms) */\n lastSeen: number;\n /** Optional metadata */\n metadata?: {\n version?: string;\n capabilities?: string[];\n };\n}\n\n/**\n * Events emitted by RelayServer\n */\nexport interface RelayServerEvents {\n 'agent-registered': (publicKey: string) => void;\n 'agent-disconnected': (publicKey: string) => void;\n /** Emitted when a session disconnects (same as agent-disconnected for compatibility) */\n 'disconnection': (publicKey: string) => void;\n 'message-relayed': (from: string, to: string, envelope: Envelope) => void;\n 'error': (error: Error) => void;\n}\n\n/**\n * WebSocket relay server for routing messages between agents.\n * \n * Agents connect to the relay and register with their public key.\n * Messages are routed to recipients based on the 'to' field.\n * All envelopes are verified before being forwarded.\n */\nexport interface RelayServerOptions {\n /** Optional relay identity for peer_list_request handling */\n identity?: { publicKey: string; privateKey: string };\n /** Public keys that should have messages stored when offline */\n storagePeers?: string[];\n /** Directory for persisting messages for storage peers */\n storageDir?: string;\n /** Maximum number of concurrent registered peers (default: 100) */\n maxPeers?: number;\n /** Per-sender sliding-window message rate limiting */\n rateLimit?: RelayRateLimitOptions;\n /** Envelope ID deduplication options */\n envelopeDedup?: RelayEnvelopeDedupOptions;\n}\n\nexport class RelayServer extends EventEmitter {\n private wss: WebSocketServer | null = null;\n /** publicKey -> sessionId -> ConnectedAgent (multiple sessions per key) */\n private sessions = new Map<string, Map<string, ConnectedAgent>>();\n private identity?: { publicKey: string; privateKey: string };\n private storagePeers: string[] = [];\n private store: MessageStore | null = null;\n private maxPeers: number = 100;\n private readonly senderWindows: Map<string, SenderWindow> = new Map();\n private static readonly MAX_SENDER_ENTRIES = 500;\n private readonly processedEnvelopeIds: Set<string> = new Set();\n private rateLimitEnabled = true;\n private rateLimitMaxMessages = 10;\n private rateLimitWindowMs = 60_000;\n private envelopeDedupEnabled = true;\n private envelopeDedupMaxIds = 1000;\n\n constructor(options?: { publicKey: string; privateKey: string } | RelayServerOptions) {\n super();\n if (options) {\n if ('identity' in options && options.identity) {\n this.identity = options.identity;\n } else if ('publicKey' in options && 'privateKey' in options) {\n this.identity = { publicKey: options.publicKey, privateKey: options.privateKey };\n }\n const opts = options as RelayServerOptions;\n if (opts.storagePeers?.length && opts.storageDir) {\n this.storagePeers = opts.storagePeers;\n this.store = new MessageStore(opts.storageDir);\n }\n if (opts.maxPeers !== undefined) {\n this.maxPeers = opts.maxPeers;\n }\n if (opts.rateLimit) {\n if (opts.rateLimit.enabled !== undefined) {\n this.rateLimitEnabled = opts.rateLimit.enabled;\n }\n if (opts.rateLimit.maxMessages !== undefined && opts.rateLimit.maxMessages > 0) {\n this.rateLimitMaxMessages = opts.rateLimit.maxMessages;\n }\n if (opts.rateLimit.windowMs !== undefined && opts.rateLimit.windowMs > 0) {\n this.rateLimitWindowMs = opts.rateLimit.windowMs;\n }\n }\n if (opts.envelopeDedup) {\n if (opts.envelopeDedup.enabled !== undefined) {\n this.envelopeDedupEnabled = opts.envelopeDedup.enabled;\n }\n if (opts.envelopeDedup.maxIds !== undefined && opts.envelopeDedup.maxIds > 0) {\n this.envelopeDedupMaxIds = opts.envelopeDedup.maxIds;\n }\n }\n }\n }\n\n private isRateLimitedSender(senderPublicKey: string): boolean {\n if (!this.rateLimitEnabled) {\n return false;\n }\n\n const now = Date.now();\n const window = this.senderWindows.get(senderPublicKey);\n\n if (this.senderWindows.size >= RelayServer.MAX_SENDER_ENTRIES && !window) {\n this.evictOldestSenderWindow();\n }\n\n if (!window || (now - window.windowStart) > this.rateLimitWindowMs) {\n this.senderWindows.set(senderPublicKey, { count: 1, windowStart: now });\n return false;\n }\n\n window.count++;\n return window.count > this.rateLimitMaxMessages;\n }\n\n private evictOldestSenderWindow(): void {\n let oldestKey: string | null = null;\n let oldestTime = Infinity;\n\n for (const [key, window] of this.senderWindows.entries()) {\n if (window.windowStart < oldestTime) {\n oldestTime = window.windowStart;\n oldestKey = key;\n }\n }\n\n if (oldestKey !== null) {\n this.senderWindows.delete(oldestKey);\n }\n }\n\n private isDuplicateEnvelopeId(envelopeId: string): boolean {\n if (!this.envelopeDedupEnabled) {\n return false;\n }\n\n if (this.processedEnvelopeIds.has(envelopeId)) {\n return true;\n }\n\n this.processedEnvelopeIds.add(envelopeId);\n if (this.processedEnvelopeIds.size > this.envelopeDedupMaxIds) {\n const oldest = this.processedEnvelopeIds.values().next().value;\n if (oldest !== undefined) {\n this.processedEnvelopeIds.delete(oldest);\n }\n }\n\n return false;\n }\n\n /**\n * Start the relay server\n * @param port - Port to listen on\n * @param host - Optional host (default: all interfaces)\n */\n start(port: number, host?: string): Promise<void> {\n return new Promise((resolve, reject) => {\n try {\n this.wss = new WebSocketServer({ port, host: host ?? '0.0.0.0' });\n let resolved = false;\n\n this.wss.on('error', (error) => {\n this.emit('error', error);\n if (!resolved) {\n resolved = true;\n reject(error);\n }\n });\n\n this.wss.on('listening', () => {\n if (!resolved) {\n resolved = true;\n resolve();\n }\n });\n\n this.wss.on('connection', (socket: WebSocket) => {\n this.handleConnection(socket);\n });\n } catch (error) {\n reject(error);\n }\n });\n }\n\n /**\n * Stop the relay server\n */\n async stop(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (!this.wss) {\n resolve();\n return;\n }\n\n // Close all agent connections (all sessions)\n for (const sessionMap of this.sessions.values()) {\n for (const agent of sessionMap.values()) {\n agent.socket.close();\n }\n }\n this.sessions.clear();\n\n this.wss.close((err) => {\n if (err) {\n reject(err);\n } else {\n this.wss = null;\n resolve();\n }\n });\n });\n }\n\n /**\n * Get one connected agent per public key (first session). For backward compatibility.\n */\n getAgents(): Map<string, ConnectedAgent> {\n const out = new Map<string, ConnectedAgent>();\n for (const [key, sessionMap] of this.sessions) {\n const first = sessionMap.values().next().value;\n if (first) out.set(key, first);\n }\n return out;\n }\n\n /**\n * Handle incoming connection\n */\n private handleConnection(socket: WebSocket): void {\n let agentPublicKey: string | null = null;\n let sessionId: string | null = null;\n\n socket.on('message', (data: Buffer) => {\n try {\n const msg = JSON.parse(data.toString());\n\n // Handle registration\n if (msg.type === 'register' && !agentPublicKey) {\n if (!msg.publicKey || typeof msg.publicKey !== 'string') {\n this.sendError(socket, 'Invalid registration: missing or invalid publicKey');\n socket.close();\n return;\n }\n\n const publicKey = msg.publicKey;\n const name = msg.name;\n agentPublicKey = publicKey;\n sessionId = crypto.randomUUID();\n\n // Allow multiple sessions per publicKey; only enforce max unique peers\n if (!this.sessions.has(publicKey) && this.sessions.size >= this.maxPeers) {\n this.sendError(socket, `Relay is at capacity (max ${this.maxPeers} peers)`);\n socket.close();\n return;\n }\n\n const agent: ConnectedAgent = {\n publicKey,\n name,\n socket,\n lastSeen: Date.now(),\n };\n\n if (!this.sessions.has(publicKey)) {\n this.sessions.set(publicKey, new Map());\n }\n this.sessions.get(publicKey)!.set(sessionId, agent);\n const isFirstSession = this.sessions.get(publicKey)!.size === 1;\n\n this.emit('agent-registered', publicKey);\n\n // Build peers list: one entry per connected publicKey + storage peers\n const peers: Array<{ publicKey: string; name?: string }> = [];\n for (const [key, sessionMap] of this.sessions) {\n if (key === publicKey) continue;\n const firstAgent = sessionMap.values().next().value;\n peers.push({ publicKey: key, name: firstAgent?.name });\n }\n for (const storagePeer of this.storagePeers) {\n if (storagePeer !== publicKey && !this.sessions.has(storagePeer)) {\n peers.push({ publicKey: storagePeer, name: undefined });\n }\n }\n\n socket.send(JSON.stringify({\n type: 'registered',\n publicKey,\n sessionId,\n peers,\n }));\n\n // Notify other agents only when this is the first session for this peer\n if (isFirstSession) {\n this.broadcastPeerEvent('peer_online', publicKey, name);\n }\n\n // Deliver any stored messages for this peer\n if (this.store && this.storagePeers.includes(publicKey)) {\n const queued = this.store.load(publicKey);\n for (const stored of queued) {\n socket.send(JSON.stringify({\n type: 'message',\n from: stored.from,\n name: stored.name,\n envelope: stored.envelope,\n }));\n }\n this.store.clear(publicKey);\n }\n return;\n }\n\n // Require registration before processing messages\n if (!agentPublicKey) {\n this.sendError(socket, 'Not registered: send registration message first');\n socket.close();\n return;\n }\n\n // Handle message relay\n if (msg.type === 'message') {\n if (!msg.to || typeof msg.to !== 'string') {\n this.sendError(socket, 'Invalid message: missing or invalid \"to\" field');\n return;\n }\n\n if (!msg.envelope || typeof msg.envelope !== 'object') {\n this.sendError(socket, 'Invalid message: missing or invalid \"envelope\" field');\n return;\n }\n\n const envelope = msg.envelope as Envelope;\n\n // Verify envelope signature\n const verification = verifyEnvelope(envelope);\n if (!verification.valid) {\n this.sendError(socket, `Invalid envelope: ${verification.reason || 'verification failed'}`);\n return;\n }\n\n // Verify sender matches registered agent\n const envelopeFrom = envelope.from;\n if (envelopeFrom !== agentPublicKey) {\n this.sendError(socket, 'Envelope sender does not match registered public key');\n return;\n }\n\n // Strict p2p routing: envelope.to must include the relay transport recipient.\n if (!Array.isArray(envelope.to) || envelope.to.length === 0 || !envelope.to.includes(msg.to)) {\n this.sendError(socket, 'Envelope recipients do not include requested relay recipient');\n return;\n }\n\n if (this.isRateLimitedSender(agentPublicKey)) {\n return;\n }\n\n if (this.isDuplicateEnvelopeId(envelope.id)) {\n return;\n }\n\n // Update lastSeen for any session of sender\n const senderSessionMap = this.sessions.get(agentPublicKey);\n if (senderSessionMap) {\n for (const a of senderSessionMap.values()) {\n a.lastSeen = Date.now();\n }\n }\n\n // Handle peer_list_request directed at relay\n if (envelope.type === 'peer_list_request' && this.identity && msg.to === this.identity.publicKey) {\n this.handlePeerListRequest(envelope as Envelope<PeerListRequestPayload>, socket, agentPublicKey);\n return;\n }\n\n // Find all recipient sessions\n const recipientSessionMap = this.sessions.get(msg.to);\n const openRecipients = recipientSessionMap\n ? Array.from(recipientSessionMap.values()).filter(a => a.socket.readyState === WebSocket.OPEN)\n : [];\n if (openRecipients.length === 0) {\n // If recipient is a storage peer, queue the message\n if (this.store && this.storagePeers.includes(msg.to)) {\n const senderSessionMap = this.sessions.get(agentPublicKey);\n const senderAgent = senderSessionMap?.values().next().value;\n this.store.save(msg.to, {\n from: agentPublicKey,\n name: senderAgent?.name,\n envelope,\n });\n this.emit('message-relayed', agentPublicKey, msg.to, envelope);\n } else {\n this.sendError(socket, 'Recipient not connected', 'unknown_recipient');\n }\n return;\n }\n\n // Forward envelope to all sessions of the recipient\n try {\n const senderSessionMap = this.sessions.get(agentPublicKey);\n const senderAgent = senderSessionMap?.values().next().value;\n const relayMessage = {\n type: 'message',\n from: agentPublicKey,\n name: senderAgent?.name,\n envelope,\n };\n const messageStr = JSON.stringify(relayMessage);\n for (const recipient of openRecipients) {\n recipient.socket.send(messageStr);\n }\n this.emit('message-relayed', agentPublicKey, msg.to, envelope);\n } catch (err) {\n this.sendError(socket, 'Failed to relay message');\n this.emit('error', err as Error);\n }\n return;\n }\n\n // Handle ping\n if (msg.type === 'ping') {\n socket.send(JSON.stringify({ type: 'pong' }));\n return;\n }\n\n // Unknown message type\n this.sendError(socket, `Unknown message type: ${msg.type}`);\n } catch (err) {\n // Invalid JSON or other parsing errors\n this.emit('error', new Error(`Message parsing failed: ${err instanceof Error ? err.message : String(err)}`));\n this.sendError(socket, 'Invalid message format');\n }\n });\n\n socket.on('close', () => {\n if (agentPublicKey && sessionId) {\n const sessionMap = this.sessions.get(agentPublicKey);\n if (sessionMap) {\n const agent = sessionMap.get(sessionId);\n const agentName = agent?.name;\n sessionMap.delete(sessionId);\n if (sessionMap.size === 0) {\n this.sessions.delete(agentPublicKey);\n this.emit('agent-disconnected', agentPublicKey);\n this.emit('disconnection', agentPublicKey);\n // Storage-enabled peers are always considered connected; skip peer_offline for them\n if (!this.storagePeers.includes(agentPublicKey)) {\n this.broadcastPeerEvent('peer_offline', agentPublicKey, agentName);\n }\n }\n }\n }\n });\n\n socket.on('error', (error) => {\n this.emit('error', error);\n });\n }\n\n /**\n * Send an error message to a client\n */\n private sendError(socket: WebSocket, message: string, code?: string): void {\n try {\n if (socket.readyState === WebSocket.OPEN) {\n const payload: { type: 'error'; message: string; code?: string } = { type: 'error', message };\n if (code) payload.code = code;\n socket.send(JSON.stringify(payload));\n }\n } catch (err) {\n // Log errors when sending error messages, but don't propagate to avoid cascading failures\n this.emit('error', new Error(`Failed to send error message: ${err instanceof Error ? err.message : String(err)}`));\n }\n }\n\n /**\n * Broadcast a peer event to all connected agents (all sessions except the one for publicKey)\n */\n private broadcastPeerEvent(eventType: 'peer_online' | 'peer_offline', publicKey: string, name?: string): void {\n const message = {\n type: eventType,\n publicKey,\n name,\n };\n const messageStr = JSON.stringify(message);\n\n for (const [key, sessionMap] of this.sessions) {\n if (key === publicKey) continue;\n for (const agent of sessionMap.values()) {\n if (agent.socket.readyState === WebSocket.OPEN) {\n try {\n agent.socket.send(messageStr);\n } catch (err) {\n this.emit('error', new Error(`Failed to send ${eventType} event: ${err instanceof Error ? err.message : String(err)}`));\n }\n }\n }\n }\n }\n\n /**\n * Handle peer list request from an agent\n */\n private handlePeerListRequest(envelope: Envelope<PeerListRequestPayload>, socket: WebSocket, requesterPublicKey: string): void {\n if (!this.identity) {\n this.sendError(socket, 'Relay does not support peer discovery (no identity configured)');\n return;\n }\n\n const { filters } = envelope.payload;\n const now = Date.now();\n\n // One entry per publicKey (first session for lastSeen/metadata)\n const peersList: ConnectedAgent[] = [];\n for (const [key, sessionMap] of this.sessions) {\n if (key === requesterPublicKey) continue;\n const first = sessionMap.values().next().value;\n if (first) peersList.push(first);\n }\n\n let peers = peersList;\n\n // Apply filters\n if (filters?.activeWithin) {\n peers = peers.filter(p => (now - p.lastSeen) < filters.activeWithin!);\n }\n\n if (filters?.limit && filters.limit > 0) {\n peers = peers.slice(0, filters.limit);\n }\n\n // Build response payload\n const response: PeerListResponsePayload = {\n peers: peers.map(p => ({\n publicKey: p.publicKey,\n metadata: p.name || p.metadata ? {\n name: p.name,\n version: p.metadata?.version,\n capabilities: p.metadata?.capabilities,\n } : undefined,\n lastSeen: p.lastSeen,\n })),\n totalPeers: this.sessions.size - (this.sessions.has(requesterPublicKey) ? 1 : 0),\n relayPublicKey: this.identity.publicKey,\n };\n\n // Create signed envelope\n const responseEnvelope = createEnvelope(\n 'peer_list_response',\n this.identity.publicKey,\n this.identity.privateKey,\n response,\n Date.now(),\n envelope.id, // Reply to the request\n [requesterPublicKey]\n );\n\n // Send response\n const relayMessage = {\n type: 'message',\n from: this.identity.publicKey,\n name: 'relay',\n envelope: responseEnvelope,\n };\n\n try {\n socket.send(JSON.stringify(relayMessage));\n } catch (err) {\n this.emit('error', new Error(`Failed to send peer list response: ${err instanceof Error ? err.message : String(err)}`));\n }\n }\n}\n"],"mappings":";AAAA,SAAS,MAAM,QAAQ,2BAA2B;AAc3C,SAAS,kBAA2B;AACzC,QAAM,EAAE,WAAW,WAAW,IAAI,oBAAoB,SAAS;AAE/D,SAAO;AAAA,IACL,WAAW,UAAU,OAAO,EAAE,MAAM,QAAQ,QAAQ,MAAM,CAAC,EAAE,SAAS,KAAK;AAAA,IAC3E,YAAY,WAAW,OAAO,EAAE,MAAM,SAAS,QAAQ,MAAM,CAAC,EAAE,SAAS,KAAK;AAAA,EAChF;AACF;AAQO,SAAS,YAAY,SA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} from "./chunk-HGXMAZZI.js";
5
+ } from "./chunk-4TJRWJIB.js";
6
6
 
7
7
  // src/relay/message-buffer.ts
8
8
  var MAX_MESSAGES_PER_AGENT = 100;
@@ -453,4 +453,4 @@ export {
453
453
  createRestRouter,
454
454
  runRelay
455
455
  };
456
- //# sourceMappingURL=chunk-VQ4BE6OV.js.map
456
+ //# sourceMappingURL=chunk-D4Y3BZSO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/relay/message-buffer.ts","../src/relay/jwt-auth.ts","../src/relay/rest-api.ts","../src/relay/run-relay.ts"],"sourcesContent":["/**\n * message-buffer.ts — In-memory bounded message queue per agent.\n *\n * When messages are delivered to an agent via the relay, they are also\n * stored here so that HTTP polling clients can retrieve them via GET /v1/messages.\n */\n\nexport interface BufferedMessage {\n id: string;\n from: string;\n fromName?: string;\n type: string;\n payload: unknown;\n timestamp: number;\n inReplyTo?: string;\n}\n\ninterface StoredMessage {\n message: BufferedMessage;\n receivedAt: number;\n}\n\nconst MAX_MESSAGES_PER_AGENT = 100;\n\n/**\n * MessageBuffer stores inbound messages per agent public key.\n * FIFO eviction when the buffer is full (max 100 messages).\n * Messages older than ttlMs (measured from when they were received) are pruned on access.\n */\nexport class MessageBuffer {\n private buffers: Map<string, StoredMessage[]> = new Map();\n private ttlMs: number;\n\n constructor(options?: { ttlMs?: number }) {\n this.ttlMs = options?.ttlMs ?? 86400000; // default 24h\n }\n\n /**\n * Add a message to an agent's buffer.\n * Evicts the oldest message if the buffer is full.\n */\n add(publicKey: string, message: BufferedMessage): void {\n let queue = this.buffers.get(publicKey);\n if (!queue) {\n queue = [];\n this.buffers.set(publicKey, queue);\n }\n queue.push({ message, receivedAt: Date.now() });\n if (queue.length > MAX_MESSAGES_PER_AGENT) {\n queue.shift(); // FIFO eviction\n }\n }\n\n /**\n * Retrieve messages for an agent, optionally filtering by `since` timestamp.\n * Returns messages with timestamp > since (exclusive). Prunes expired messages.\n */\n get(publicKey: string, since?: number): BufferedMessage[] {\n const now = Date.now();\n let queue = this.buffers.get(publicKey) ?? [];\n // Prune messages older than ttlMs (based on wall-clock receive time)\n queue = queue.filter((s) => now - s.receivedAt < this.ttlMs);\n this.buffers.set(publicKey, queue);\n const messages = queue.map((s) => s.message);\n if (since === undefined) {\n return [...messages];\n }\n return messages.filter((m) => m.timestamp > since);\n }\n\n /**\n * Clear all messages for an agent (after polling without `since`).\n */\n clear(publicKey: string): void {\n this.buffers.set(publicKey, []);\n }\n\n /**\n * Remove all state for a disconnected agent.\n */\n delete(publicKey: string): void {\n this.buffers.delete(publicKey);\n }\n}\n","/**\n * jwt-auth.ts — JWT token creation and validation middleware.\n *\n * Tokens are signed with AGORA_RELAY_JWT_SECRET (required env var).\n * Expiry defaults to 3600 seconds (1 hour), configurable via AGORA_JWT_EXPIRY_SECONDS.\n *\n * Token payload: { publicKey, name }\n */\n\nimport jwt from 'jsonwebtoken';\nimport { randomBytes } from 'node:crypto';\nimport type { Request, Response, NextFunction } from 'express';\n\nexport interface JwtPayload {\n publicKey: string;\n name?: string;\n}\n\n/**\n * Augment Express Request to carry decoded JWT payload.\n */\nexport interface AuthenticatedRequest extends Request {\n agent?: JwtPayload;\n}\n\n/**\n * Revocation set for invalidated tokens (populated by DELETE /v1/disconnect).\n * Stored as a Map of JWT `jti` → expiry timestamp (ms).\n * Entries are automatically removed once their JWT would have expired anyway,\n * preventing unbounded memory growth.\n */\nconst revokedJtis: Map<string, number> = new Map();\n\n/**\n * Remove revoked JTI entries whose token expiry has already passed.\n * These tokens can no longer be used regardless, so no need to keep them.\n */\nfunction pruneExpiredRevocations(): void {\n const now = Date.now();\n for (const [jti, expiry] of revokedJtis) {\n if (expiry <= now) {\n revokedJtis.delete(jti);\n }\n }\n}\n\nfunction getJwtSecret(): string {\n const secret = process.env.AGORA_RELAY_JWT_SECRET;\n if (!secret) {\n throw new Error(\n 'AGORA_RELAY_JWT_SECRET environment variable is required but not set'\n );\n }\n return secret;\n}\n\nfunction getExpirySeconds(): number {\n const raw = process.env.AGORA_JWT_EXPIRY_SECONDS;\n if (raw) {\n const parsed = parseInt(raw, 10);\n if (!isNaN(parsed) && parsed > 0) {\n return parsed;\n }\n }\n return 3600; // 1 hour default\n}\n\n/**\n * Create a signed JWT for a registered agent.\n * Returns the token string and its expiry timestamp (ms since epoch).\n */\nexport function createToken(payload: JwtPayload): {\n token: string;\n expiresAt: number;\n} {\n const secret = getJwtSecret();\n const expirySeconds = getExpirySeconds();\n const jti = `${Date.now()}-${randomBytes(16).toString('hex')}`;\n\n const token = jwt.sign(\n { publicKey: payload.publicKey, name: payload.name, jti },\n secret,\n { expiresIn: expirySeconds }\n );\n\n const expiresAt = Date.now() + expirySeconds * 1000;\n return { token, expiresAt };\n}\n\n/**\n * Revoke a token by its jti claim so it cannot be used again.\n * The revocation entry is stored with the token's expiry so it can be\n * pruned automatically once the token would no longer be valid anyway.\n */\nexport function revokeToken(token: string): void {\n try {\n const secret = getJwtSecret();\n const decoded = jwt.verify(token, secret) as jwt.JwtPayload & {\n jti?: string;\n exp?: number;\n };\n if (decoded.jti) {\n const expiry = decoded.exp ? decoded.exp * 1000 : Date.now();\n revokedJtis.set(decoded.jti, expiry);\n pruneExpiredRevocations();\n }\n } catch {\n // Token already invalid — nothing to revoke\n }\n}\n\n/**\n * Express middleware that validates the Authorization: Bearer <token> header.\n * Attaches decoded payload to `req.agent` on success.\n * Responds with 401 if missing/invalid/expired/revoked.\n */\nexport function requireAuth(\n req: AuthenticatedRequest,\n res: Response,\n next: NextFunction\n): void {\n const authHeader = req.headers.authorization;\n if (!authHeader || !authHeader.startsWith('Bearer ')) {\n res.status(401).json({ error: 'Missing or malformed Authorization header' });\n return;\n }\n\n const token = authHeader.slice(7);\n try {\n const secret = getJwtSecret();\n const decoded = jwt.verify(token, secret) as jwt.JwtPayload & {\n publicKey: string;\n name?: string;\n jti?: string;\n };\n\n if (decoded.jti && revokedJtis.has(decoded.jti)) {\n res.status(401).json({ error: 'Token has been revoked' });\n return;\n }\n\n req.agent = { publicKey: decoded.publicKey, name: decoded.name };\n next();\n } catch (err) {\n if (err instanceof jwt.TokenExpiredError) {\n res.status(401).json({ error: 'Token expired' });\n } else {\n res.status(401).json({ error: 'Invalid token' });\n }\n }\n}\n","/**\n * rest-api.ts — Express router implementing the Agora relay REST API.\n *\n * Endpoints:\n * POST /v1/register — Register agent, obtain JWT session token\n * POST /v1/send — Send message to a peer (requires auth)\n * GET /v1/peers — List online peers (requires auth)\n * GET /v1/messages — Poll for new inbound messages (requires auth)\n * DELETE /v1/disconnect — Invalidate token and disconnect (requires auth)\n */\n\nimport { Router } from 'express';\nimport type { Request, Response } from 'express';\nimport { rateLimit } from 'express-rate-limit';\nimport {\n createToken,\n revokeToken,\n requireAuth,\n type AuthenticatedRequest,\n} from './jwt-auth';\nimport { MessageBuffer, type BufferedMessage } from './message-buffer';\n\nconst apiRateLimit = (rpm: number): ReturnType<typeof rateLimit> => rateLimit({\n windowMs: 60_000,\n limit: rpm,\n standardHeaders: 'draft-7',\n legacyHeaders: false,\n message: { error: 'Too many requests — try again later' },\n});\n\n/**\n * A session for a REST-connected agent.\n * privateKey is held only in memory and never logged or persisted.\n */\nexport interface RestSession {\n publicKey: string;\n privateKey: string;\n name?: string;\n metadata?: { version?: string; capabilities?: string[] };\n registeredAt: number;\n expiresAt: number;\n token: string;\n}\n\nfunction pruneExpiredSessions(\n sessions: Map<string, RestSession>,\n buffer: MessageBuffer\n): void {\n const now = Date.now();\n for (const [publicKey, session] of sessions) {\n if (session.expiresAt <= now) {\n sessions.delete(publicKey);\n buffer.delete(publicKey);\n }\n }\n}\n\n/**\n * Minimal interface for the relay server that the REST API depends on.\n */\nexport interface RelayInterface {\n getAgents(): Map<\n string,\n {\n publicKey: string;\n name?: string;\n lastSeen: number;\n metadata?: { version?: string; capabilities?: string[] };\n socket: unknown;\n }\n >;\n on(\n event: 'message-relayed',\n handler: (from: string, to: string, envelope: unknown) => void\n ): void;\n}\n\n/**\n * Envelope creation function interface (matches createEnvelope from message/envelope).\n */\nexport type CreateEnvelopeFn = (\n type: string,\n from: string,\n to: string[],\n privateKey: string,\n payload: unknown,\n timestamp?: number,\n inReplyTo?: string\n) => {\n id: string;\n type: string;\n from: string;\n to: string[];\n timestamp: number;\n payload: unknown;\n signature: string;\n inReplyTo?: string;\n};\n\n/**\n * Envelope verification function interface.\n */\nexport type VerifyEnvelopeFn = (envelope: unknown) => {\n valid: boolean;\n reason?: string;\n};\n\n/**\n * Create the REST API router.\n */\nexport function createRestRouter(\n relay: RelayInterface,\n buffer: MessageBuffer,\n sessions: Map<string, RestSession>,\n createEnv: CreateEnvelopeFn,\n verifyEnv: VerifyEnvelopeFn,\n rateLimitRpm = 60\n): Router {\n const router = Router();\n router.use(apiRateLimit(rateLimitRpm));\n\n relay.on('message-relayed', (from, to, envelope) => {\n if (!sessions.has(to)) return;\n const agentMap = relay.getAgents();\n const senderAgent = agentMap.get(from);\n const env = envelope as {\n id: string;\n type: string;\n payload: unknown;\n timestamp: number;\n inReplyTo?: string;\n };\n const msg: BufferedMessage = {\n id: env.id,\n from,\n fromName: senderAgent?.name,\n type: env.type,\n payload: env.payload,\n timestamp: env.timestamp,\n inReplyTo: env.inReplyTo,\n };\n buffer.add(to, msg);\n });\n\n router.post('/v1/register', async (req: Request, res: Response) => {\n const { publicKey, privateKey, name, metadata } = req.body as {\n publicKey?: string;\n privateKey?: string;\n name?: string;\n metadata?: { version?: string; capabilities?: string[] };\n };\n\n if (!publicKey || typeof publicKey !== 'string') {\n res.status(400).json({ error: 'publicKey is required' });\n return;\n }\n if (!privateKey || typeof privateKey !== 'string') {\n res.status(400).json({ error: 'privateKey is required' });\n return;\n }\n\n const testEnvelope = createEnv(\n 'announce',\n publicKey,\n [publicKey],\n privateKey,\n { challenge: 'register' },\n Date.now()\n );\n const verification = verifyEnv(testEnvelope);\n if (!verification.valid) {\n res\n .status(400)\n .json({ error: 'Key pair verification failed: ' + verification.reason });\n return;\n }\n\n const { token, expiresAt } = createToken({ publicKey, name });\n pruneExpiredSessions(sessions, buffer);\n\n const session: RestSession = {\n publicKey,\n privateKey,\n name,\n metadata,\n registeredAt: Date.now(),\n expiresAt,\n token,\n };\n sessions.set(publicKey, session);\n\n const wsAgents = relay.getAgents();\n const peers: Array<{ publicKey: string; name?: string; lastSeen: number }> = [];\n for (const agent of wsAgents.values()) {\n if (agent.publicKey !== publicKey) {\n peers.push({\n publicKey: agent.publicKey,\n name: agent.name,\n lastSeen: agent.lastSeen,\n });\n }\n }\n for (const s of sessions.values()) {\n if (s.publicKey !== publicKey && !wsAgents.has(s.publicKey)) {\n peers.push({\n publicKey: s.publicKey,\n name: s.name,\n lastSeen: s.registeredAt,\n });\n }\n }\n\n res.json({ token, expiresAt, peers });\n });\n\n router.post(\n '/v1/send',\n requireAuth,\n async (req: AuthenticatedRequest, res: Response) => {\n const { to, type, payload, inReplyTo } = req.body as {\n to?: string;\n type?: string;\n payload?: unknown;\n inReplyTo?: string;\n };\n\n if (!to || typeof to !== 'string') {\n res.status(400).json({ error: 'to is required' });\n return;\n }\n if (!type || typeof type !== 'string') {\n res.status(400).json({ error: 'type is required' });\n return;\n }\n if (payload === undefined) {\n res.status(400).json({ error: 'payload is required' });\n return;\n }\n\n const senderPublicKey = req.agent!.publicKey;\n const session = sessions.get(senderPublicKey);\n if (!session) {\n res.status(401).json({ error: 'Session not found — please re-register' });\n return;\n }\n\n const envelope = createEnv(\n type,\n senderPublicKey,\n [to],\n session.privateKey,\n payload,\n Date.now(),\n inReplyTo\n );\n\n const wsAgents = relay.getAgents();\n const wsRecipient = wsAgents.get(to);\n if (wsRecipient && wsRecipient.socket) {\n const ws = wsRecipient.socket as { readyState: number; send(data: string): void };\n const OPEN = 1;\n if (ws.readyState !== OPEN) {\n res.status(503).json({ error: 'Recipient connection is not open' });\n return;\n }\n try {\n const relayMsg = JSON.stringify({\n type: 'message',\n from: senderPublicKey,\n name: session.name,\n envelope,\n });\n ws.send(relayMsg);\n res.json({ ok: true, envelopeId: envelope.id });\n return;\n } catch (err) {\n res.status(500).json({\n error:\n 'Failed to deliver message: ' +\n (err instanceof Error ? err.message : String(err)),\n });\n return;\n }\n }\n\n const restRecipient = sessions.get(to);\n if (restRecipient) {\n const senderAgent = wsAgents.get(senderPublicKey);\n const msg: BufferedMessage = {\n id: envelope.id,\n from: senderPublicKey,\n fromName: session.name ?? senderAgent?.name,\n type: envelope.type,\n payload: envelope.payload,\n timestamp: envelope.timestamp,\n inReplyTo: envelope.inReplyTo,\n };\n buffer.add(to, msg);\n res.json({ ok: true, envelopeId: envelope.id });\n return;\n }\n\n res.status(404).json({ error: 'Recipient not connected' });\n }\n );\n\n router.get(\n '/v1/peers',\n requireAuth,\n (req: AuthenticatedRequest, res: Response) => {\n const callerPublicKey = req.agent!.publicKey;\n const wsAgents = relay.getAgents();\n const peerList: Array<{\n publicKey: string;\n name?: string;\n lastSeen: number;\n metadata?: { version?: string; capabilities?: string[] };\n }> = [];\n\n for (const agent of wsAgents.values()) {\n if (agent.publicKey !== callerPublicKey) {\n peerList.push({\n publicKey: agent.publicKey,\n name: agent.name,\n lastSeen: agent.lastSeen,\n metadata: agent.metadata,\n });\n }\n }\n\n for (const s of sessions.values()) {\n if (s.publicKey !== callerPublicKey && !wsAgents.has(s.publicKey)) {\n peerList.push({\n publicKey: s.publicKey,\n name: s.name,\n lastSeen: s.registeredAt,\n metadata: s.metadata,\n });\n }\n }\n\n res.json({ peers: peerList });\n }\n );\n\n router.get(\n '/v1/messages',\n requireAuth,\n (req: AuthenticatedRequest, res: Response) => {\n const publicKey = req.agent!.publicKey;\n const sinceRaw = req.query.since as string | undefined;\n const limitRaw = req.query.limit as string | undefined;\n\n const since = sinceRaw ? parseInt(sinceRaw, 10) : undefined;\n const limit = Math.min(limitRaw ? parseInt(limitRaw, 10) : 50, 100);\n\n let messages = buffer.get(publicKey, since);\n const hasMore = messages.length > limit;\n if (hasMore) {\n messages = messages.slice(0, limit);\n }\n\n if (since === undefined) {\n buffer.clear(publicKey);\n }\n\n res.json({ messages, hasMore });\n }\n );\n\n router.delete(\n '/v1/disconnect',\n requireAuth,\n (req: AuthenticatedRequest, res: Response) => {\n const publicKey = req.agent!.publicKey;\n const authHeader = req.headers.authorization!;\n const token = authHeader.slice(7);\n\n revokeToken(token);\n sessions.delete(publicKey);\n buffer.delete(publicKey);\n\n res.json({ ok: true });\n }\n );\n\n return router;\n}\n","/**\n * run-relay.ts — Start Agora relay: WebSocket server and optional REST API.\n *\n * When REST is enabled, starts:\n * 1. WebSocket relay (RelayServer) on wsPort\n * 2. REST API server (Express) on restPort\n *\n * Environment variables:\n * RELAY_PORT — WebSocket relay port (default: 3002); alias: PORT\n * REST_PORT — REST API port (default: 3001)\n * JWT_SECRET — Secret for JWT session tokens (alias: AGORA_RELAY_JWT_SECRET)\n * AGORA_JWT_EXPIRY_SECONDS — JWT expiry in seconds (default: 3600)\n * MAX_PEERS — Maximum concurrent registered peers (default: 100)\n * MESSAGE_TTL_MS — Message buffer TTL in ms (default: 86400000 = 24h)\n * RATE_LIMIT_RPM — REST API requests per minute per IP (default: 60)\n * ALLOWED_ORIGINS — CORS origins, comma-separated or * (default: *)\n */\n\nimport http from 'node:http';\nimport express from 'express';\nimport cors from 'cors';\nimport { RelayServer, type RelayServerOptions } from './server';\nimport {\n createEnvelope,\n verifyEnvelope,\n type Envelope,\n type MessageType,\n} from '../message/envelope';\nimport { createRestRouter, type CreateEnvelopeFn } from './rest-api';\nimport { MessageBuffer } from './message-buffer';\nimport type { RestSession } from './rest-api';\n\n/** Wrapper so REST API can pass string type; createEnvelope expects MessageType */\nconst createEnvelopeForRest: CreateEnvelopeFn = (\n type,\n from,\n to,\n privateKey,\n payload,\n timestamp,\n inReplyTo\n) =>\n createEnvelope(\n type as MessageType,\n from,\n privateKey,\n payload,\n timestamp ?? Date.now(),\n inReplyTo,\n to\n );\n\nexport interface RunRelayOptions {\n /** WebSocket port (default from RELAY_PORT or PORT env, or 3002) */\n wsPort?: number;\n /** REST API port (default from REST_PORT env, or 3001). Ignored if enableRest is false. */\n restPort?: number;\n /** Enable REST API (requires JWT_SECRET or AGORA_RELAY_JWT_SECRET). Default: true if secret is set. */\n enableRest?: boolean;\n /** Relay server options (identity, storagePeers, storageDir) */\n relayOptions?: RelayServerOptions;\n}\n\n/**\n * Start WebSocket relay and optionally REST API.\n * Returns { relay, httpServer } where httpServer is set only when REST is enabled.\n */\nexport async function runRelay(options: RunRelayOptions = {}): Promise<{\n relay: RelayServer;\n httpServer?: http.Server;\n}> {\n const wsPort = options.wsPort ?? parseInt(\n process.env.RELAY_PORT ?? process.env.PORT ?? '3002', 10\n );\n const jwtSecret = process.env.JWT_SECRET ?? process.env.AGORA_RELAY_JWT_SECRET;\n const enableRest =\n options.enableRest ??\n (typeof jwtSecret === 'string' && jwtSecret.length > 0);\n\n const maxPeers = parseInt(process.env.MAX_PEERS ?? '100', 10);\n const relayOptions: RelayServerOptions = { ...options.relayOptions, maxPeers };\n\n const relay = new RelayServer(relayOptions);\n await relay.start(wsPort);\n\n if (!enableRest) {\n return { relay };\n }\n\n if (!jwtSecret) {\n await relay.stop();\n throw new Error(\n 'JWT_SECRET (or AGORA_RELAY_JWT_SECRET) environment variable is required when REST API is enabled'\n );\n }\n\n // Expose jwtSecret via env so jwt-auth.ts can read it (it reads AGORA_RELAY_JWT_SECRET)\n if (!process.env.AGORA_RELAY_JWT_SECRET) {\n process.env.AGORA_RELAY_JWT_SECRET = jwtSecret;\n }\n\n const restPort = options.restPort ?? parseInt(process.env.REST_PORT ?? '3001', 10);\n const messageTtlMs = parseInt(process.env.MESSAGE_TTL_MS ?? '86400000', 10);\n const messageBuffer = new MessageBuffer({ ttlMs: messageTtlMs });\n const restSessions = new Map<string, RestSession>();\n\n const allowedOrigins = process.env.ALLOWED_ORIGINS ?? '*';\n const corsOrigins = allowedOrigins === '*'\n ? '*'\n : allowedOrigins.split(',').map((o) => o.trim()).filter((o) => o.length > 0);\n\n const app = express();\n app.use(cors({\n origin: corsOrigins,\n methods: ['GET', 'POST', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n }));\n app.use(express.json());\n\n const verifyForRest = (envelope: unknown): { valid: boolean; reason?: string } =>\n verifyEnvelope(envelope as Envelope);\n\n const rateLimitRpm = parseInt(process.env.RATE_LIMIT_RPM ?? '60', 10);\n const router = createRestRouter(\n relay as Parameters<typeof createRestRouter>[0],\n messageBuffer,\n restSessions,\n createEnvelopeForRest,\n verifyForRest,\n rateLimitRpm\n );\n app.use(router);\n\n app.use((_req, res) => {\n res.status(404).json({ error: 'Not found' });\n });\n\n const httpServer = http.createServer(app);\n await new Promise<void>((resolve, reject) => {\n httpServer.listen(restPort, () => resolve());\n httpServer.on('error', reject);\n });\n\n return { relay, httpServer };\n}\n"],"mappings":";;;;;;;AAsBA,IAAM,yBAAyB;AAOxB,IAAM,gBAAN,MAAoB;AAAA,EACjB,UAAwC,oBAAI,IAAI;AAAA,EAChD;AAAA,EAER,YAAY,SAA8B;AACxC,SAAK,QAAQ,SAAS,SAAS;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,WAAmB,SAAgC;AACrD,QAAI,QAAQ,KAAK,QAAQ,IAAI,SAAS;AACtC,QAAI,CAAC,OAAO;AACV,cAAQ,CAAC;AACT,WAAK,QAAQ,IAAI,WAAW,KAAK;AAAA,IACnC;AACA,UAAM,KAAK,EAAE,SAAS,YAAY,KAAK,IAAI,EAAE,CAAC;AAC9C,QAAI,MAAM,SAAS,wBAAwB;AACzC,YAAM,MAAM;AAAA,IACd;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,WAAmB,OAAmC;AACxD,UAAM,MAAM,KAAK,IAAI;AACrB,QAAI,QAAQ,KAAK,QAAQ,IAAI,SAAS,KAAK,CAAC;AAE5C,YAAQ,MAAM,OAAO,CAAC,MAAM,MAAM,EAAE,aAAa,KAAK,KAAK;AAC3D,SAAK,QAAQ,IAAI,WAAW,KAAK;AACjC,UAAM,WAAW,MAAM,IAA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