|
| 1 | +import { elizaLogger, IAgentRuntime } from "@ai16z/eliza"; |
| 2 | +import { |
| 3 | + ChatMessage, |
| 4 | + ChatRoom, |
| 5 | + EchoChamberConfig, |
| 6 | + ModelInfo, |
| 7 | + ListRoomsResponse, |
| 8 | + RoomHistoryResponse, |
| 9 | + MessageResponse, |
| 10 | +} from "./types"; |
| 11 | + |
| 12 | +const MAX_RETRIES = 3; |
| 13 | + |
| 14 | +const RETRY_DELAY = 5000; |
| 15 | + |
| 16 | +export class EchoChamberClient { |
| 17 | + private runtime: IAgentRuntime; |
| 18 | + private config: EchoChamberConfig; |
| 19 | + private apiUrl: string; |
| 20 | + private modelInfo: ModelInfo; |
| 21 | + private pollInterval: NodeJS.Timeout | null = null; |
| 22 | + private watchedRoom: string | null = null; |
| 23 | + |
| 24 | + constructor(runtime: IAgentRuntime, config: EchoChamberConfig) { |
| 25 | + this.runtime = runtime; |
| 26 | + this.config = config; |
| 27 | + this.apiUrl = `${config.apiUrl}/api/rooms`; |
| 28 | + this.modelInfo = { |
| 29 | + username: config.username || `agent-${runtime.agentId}`, |
| 30 | + model: config.model || runtime.modelProvider, |
| 31 | + }; |
| 32 | + } |
| 33 | + |
| 34 | + public getUsername(): string { |
| 35 | + return this.modelInfo.username; |
| 36 | + } |
| 37 | + |
| 38 | + public getModelInfo(): ModelInfo { |
| 39 | + return { ...this.modelInfo }; |
| 40 | + } |
| 41 | + |
| 42 | + public getConfig(): EchoChamberConfig { |
| 43 | + return { ...this.config }; |
| 44 | + } |
| 45 | + |
| 46 | + private getAuthHeaders(): { [key: string]: string } { |
| 47 | + return { |
| 48 | + "Content-Type": "application/json", |
| 49 | + "x-api-key": this.config.apiKey, |
| 50 | + }; |
| 51 | + } |
| 52 | + |
| 53 | + public async setWatchedRoom(roomId: string): Promise<void> { |
| 54 | + try { |
| 55 | + // Verify room exists |
| 56 | + const rooms = await this.listRooms(); |
| 57 | + const room = rooms.find((r) => r.id === roomId); |
| 58 | + |
| 59 | + if (!room) { |
| 60 | + throw new Error(`Room ${roomId} not found`); |
| 61 | + } |
| 62 | + |
| 63 | + // Set new watched room |
| 64 | + this.watchedRoom = roomId; |
| 65 | + |
| 66 | + elizaLogger.success(`Now watching room: ${room.name}`); |
| 67 | + } catch (error) { |
| 68 | + elizaLogger.error("Error setting watched room:", error); |
| 69 | + throw error; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + public getWatchedRoom(): string | null { |
| 74 | + return this.watchedRoom; |
| 75 | + } |
| 76 | + |
| 77 | + private async retryOperation<T>( |
| 78 | + operation: () => Promise<T>, |
| 79 | + retries: number = MAX_RETRIES |
| 80 | + ): Promise<T> { |
| 81 | + for (let i = 0; i < retries; i++) { |
| 82 | + try { |
| 83 | + return await operation(); |
| 84 | + } catch (error) { |
| 85 | + if (i === retries - 1) throw error; |
| 86 | + const delay = RETRY_DELAY * Math.pow(2, i); |
| 87 | + elizaLogger.warn(`Retrying operation in ${delay}ms...`); |
| 88 | + await new Promise((resolve) => setTimeout(resolve, delay)); |
| 89 | + } |
| 90 | + } |
| 91 | + throw new Error("Max retries exceeded"); |
| 92 | + } |
| 93 | + |
| 94 | + public async start(): Promise<void> { |
| 95 | + elizaLogger.log("🚀 Starting EchoChamber client..."); |
| 96 | + try { |
| 97 | + // Verify connection by listing rooms |
| 98 | + await this.retryOperation(() => this.listRooms()); |
| 99 | + elizaLogger.success( |
| 100 | + `✅ EchoChamber client successfully started for ${this.modelInfo.username}` |
| 101 | + ); |
| 102 | + |
| 103 | + // Join default room if specified and no specific room is being watched |
| 104 | + if (this.config.defaultRoom && !this.watchedRoom) { |
| 105 | + await this.setWatchedRoom(this.config.defaultRoom); |
| 106 | + } |
| 107 | + } catch (error) { |
| 108 | + elizaLogger.error("❌ Failed to start EchoChamber client:", error); |
| 109 | + throw error; |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + public async stop(): Promise<void> { |
| 114 | + if (this.pollInterval) { |
| 115 | + clearInterval(this.pollInterval); |
| 116 | + this.pollInterval = null; |
| 117 | + } |
| 118 | + |
| 119 | + // Leave watched room if any |
| 120 | + if (this.watchedRoom) { |
| 121 | + try { |
| 122 | + this.watchedRoom = null; |
| 123 | + } catch (error) { |
| 124 | + elizaLogger.error( |
| 125 | + `Error leaving room ${this.watchedRoom}:`, |
| 126 | + error |
| 127 | + ); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + elizaLogger.log("Stopping EchoChamber client..."); |
| 132 | + } |
| 133 | + |
| 134 | + public async listRooms(tags?: string[]): Promise<ChatRoom[]> { |
| 135 | + try { |
| 136 | + const url = new URL(this.apiUrl); |
| 137 | + if (tags?.length) { |
| 138 | + url.searchParams.append("tags", tags.join(",")); |
| 139 | + } |
| 140 | + |
| 141 | + const response = await fetch(url.toString()); |
| 142 | + if (!response.ok) { |
| 143 | + throw new Error(`Failed to list rooms: ${response.statusText}`); |
| 144 | + } |
| 145 | + |
| 146 | + const data = (await response.json()) as ListRoomsResponse; |
| 147 | + return data.rooms; |
| 148 | + } catch (error) { |
| 149 | + elizaLogger.error("Error listing rooms:", error); |
| 150 | + throw error; |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + public async getRoomHistory(roomId: string): Promise<ChatMessage[]> { |
| 155 | + return this.retryOperation(async () => { |
| 156 | + const response = await fetch(`${this.apiUrl}/${roomId}/history`); |
| 157 | + if (!response.ok) { |
| 158 | + throw new Error( |
| 159 | + `Failed to get room history: ${response.statusText}` |
| 160 | + ); |
| 161 | + } |
| 162 | + |
| 163 | + const data = (await response.json()) as RoomHistoryResponse; |
| 164 | + return data.messages; |
| 165 | + }); |
| 166 | + } |
| 167 | + |
| 168 | + public async sendMessage( |
| 169 | + roomId: string, |
| 170 | + content: string |
| 171 | + ): Promise<ChatMessage> { |
| 172 | + return this.retryOperation(async () => { |
| 173 | + const response = await fetch(`${this.apiUrl}/${roomId}/message`, { |
| 174 | + method: "POST", |
| 175 | + headers: this.getAuthHeaders(), |
| 176 | + body: JSON.stringify({ |
| 177 | + content, |
| 178 | + sender: this.modelInfo, |
| 179 | + }), |
| 180 | + }); |
| 181 | + |
| 182 | + if (!response.ok) { |
| 183 | + throw new Error( |
| 184 | + `Failed to send message: ${response.statusText}` |
| 185 | + ); |
| 186 | + } |
| 187 | + |
| 188 | + const data = (await response.json()) as MessageResponse; |
| 189 | + return data.message; |
| 190 | + }); |
| 191 | + } |
| 192 | +} |
0 commit comments