-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
608 lines (538 loc) · 16.6 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
import fs from "node:fs";
import { Worker, type WorkerOptions } from "node:worker_threads";
import { createClient, getDataPath } from "@helpers/client";
import { personalities } from "@helpers/tests";
import {
Dm,
type Client,
type DecodedMessage,
type XmtpEnv,
} from "@xmtp/node-sdk";
import OpenAI from "openai";
import type { typeOfResponse, typeofStream, WorkerBase } from "./manager";
// Worker thread code as a string
const workerThreadCode = `
import { parentPort, workerData } from "node:worker_threads";
import type { Client } from "@xmtp/node-sdk";
// The Worker must be run in a worker thread, so confirm \`parentPort\` is defined
if (!parentPort) {
throw new Error("This module must be run as a worker thread");
}
// Optional logs to see what's being passed into the worker.
console.log("[Worker] Started with workerData:", workerData);
// Listen for messages from the parent
parentPort.on("message", (message: { type: string; data: any }) => {
switch (message.type) {
case "initialize":
// You can add logs or do any one-time setup here.
console.log("[Worker] Received 'initialize' message:", message.data);
break;
default:
console.log(\`[Worker] Received unknown message type: \${message.type}\`);
break;
}
});
// Re-export anything needed in the worker environment (if necessary)
export type { Client };
`;
// Bootstrap code that loads the worker thread code
const workerBootstrap = /* JavaScript */ `
import { parentPort, workerData } from "node:worker_threads";
// Execute the worker code
const workerCode = ${JSON.stringify(workerThreadCode)};
const workerModule = new Function('require', 'parentPort', 'workerData', 'process', workerCode);
// Get the require function
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath("${import.meta.url}");
const require = createRequire(__filename);
// Execute the worker code
workerModule(require, parentPort, workerData, process);
`;
// Define generic message types for different stream events
interface BaseStreamMessage {
type: string;
}
interface StreamTextMessage extends BaseStreamMessage {
type: "stream_message";
message: {
conversationId: string;
senderInboxId: string;
content: string;
contentType?: {
typeId: string;
};
};
}
interface StreamGroupUpdateMessage extends BaseStreamMessage {
type: "stream_group_updated";
group: {
conversationId: string;
name: string;
};
}
interface StreamConversationMessage extends BaseStreamMessage {
type: "stream_conversation";
conversation: {
id: string;
peerAddress?: string;
};
}
interface StreamConsentMessage extends BaseStreamMessage {
type: "stream_consent";
consentUpdate: {
inboxId: string;
consentValue: boolean;
};
}
type StreamMessage =
| StreamTextMessage
| StreamGroupUpdateMessage
| StreamConversationMessage
| StreamConsentMessage;
export class WorkerClient extends Worker {
public name: string;
private testName: string;
private nameId: string;
private walletKey: string;
private encryptionKeyHex: string;
private typeofStream: typeofStream;
private typeOfResponse: typeOfResponse;
private folder: string;
private sdkVersion: string;
private libXmtpVersion: string;
public address!: `0x${string}`;
public client!: Client;
private env: XmtpEnv;
constructor(
worker: WorkerBase,
typeofStream: typeofStream,
typeOfResponse: typeOfResponse,
env: XmtpEnv,
options: WorkerOptions = {},
) {
options.workerData = {
worker,
};
super(new URL(`data:text/javascript,${workerBootstrap}`), options);
this.typeOfResponse = typeOfResponse;
this.typeofStream = typeofStream;
this.name = worker.name;
this.sdkVersion = worker.sdkVersion;
this.libXmtpVersion = worker.libXmtpVersion;
this.folder = worker.folder;
this.env = env;
this.nameId = worker.name + "-" + worker.sdkVersion;
this.testName = worker.testName;
this.walletKey = worker.walletKey;
this.encryptionKeyHex = worker.encryptionKey;
this.setupEventHandlers();
}
/**
* Reinstalls the worker
*/
public async reinstall(): Promise<void> {
console.log(`[${this.nameId}] Reinstalling worker`);
await this.terminate();
await this.clearDB();
await this.initialize();
}
private setupEventHandlers() {
// Log messages from the Worker
this.on("message", (message) => {
console.log(`[${this.nameId}] Worker message:`, message);
});
// Handle Worker errors
this.on("error", (error) => {
console.error(`[${this.nameId}] Worker error:`, error);
});
// Handle Worker exit
this.on("exit", (code) => {
if (code !== 0) {
console.error(`[${this.nameId}] Worker stopped with exit code ${code}`);
}
});
}
/**
* Initializes the underlying XMTP client in the Worker.
* Returns the XMTP Client object for convenience.
*/
async initialize(): Promise<{
client: Client;
dbPath: string;
installationId: string;
address: `0x${string}`;
}> {
// Tell the Worker to do any internal initialization
this.postMessage({
type: "initialize",
data: {
name: this.name,
folder: this.folder,
sdkVersion: this.sdkVersion,
libXmtpVersion: this.libXmtpVersion,
},
});
const { client, dbPath, address } = await createClient(
this.walletKey as `0x${string}`,
this.encryptionKeyHex,
{
sdkVersion: this.sdkVersion,
name: this.name,
testName: this.testName,
folder: this.folder,
},
this.env,
);
this.client = client as Client;
this.address = address;
this.startStream();
const installationId = this.client.installationId;
return {
client: this.client,
dbPath,
address: address,
installationId,
};
}
/**
* Unified method to start the appropriate stream based on configuration
*/
private startStream() {
try {
switch (this.typeofStream) {
case "message":
this.initMessageStream();
break;
case "conversation":
this.initConversationStream();
break;
case "consent":
this.initConsentStream();
break;
// Add additional stream types as needed
}
} catch (error) {
console.error(
`[${this.nameId}] Failed to start ${this.typeofStream} stream:`,
error,
);
throw error;
}
}
/**
* Initialize message stream for both regular messages and group updates
*/
private initMessageStream() {
void (async () => {
while (true) {
try {
console.log("initMessageStream");
const stream = await this.client.conversations.streamAllMessages();
for await (const message of stream) {
if (
!message ||
message?.senderInboxId.toLowerCase() ===
this.client.inboxId.toLowerCase()
) {
continue;
}
if (message?.contentType?.typeId === "group_updated") {
if (this.listenerCount("message") > 0) {
this.emit("message", {
type: "stream_group_updated",
group: message,
});
}
continue;
}
if (message.contentType?.typeId === "text") {
// Handle auto-responses if enabled
if (this.shouldRespondToMessage(message)) {
await this.handleResponse(message);
continue;
}
// Emit standard message
if (this.listenerCount("message") > 0) {
this.emit("message", { type: "stream_message", message });
}
}
}
} catch (error) {
console.error("maints:message " + String(error));
}
}
})();
}
/**
* Check if a message should trigger a response
*/
private shouldRespondToMessage(message: DecodedMessage): boolean {
if (this.typeOfResponse === "none") return false;
const conversation = this.client.conversations.getConversationById(
message.conversationId,
);
const baseName = this.name.split("-")[0].toLowerCase();
const isDm = conversation instanceof Dm;
const content = (message.content as string).toLowerCase();
//
return (
(message?.contentType?.typeId === "text" &&
content.includes(baseName) &&
!content.includes("/") &&
!content.includes("workers") &&
!content.includes("members") &&
!content.includes("admins")) ||
isDm
);
}
/**
* Handle generating and sending GPT responses
*/
private async handleResponse(message: DecodedMessage) {
console.time(`[${this.nameId}] Worker response`);
try {
// Get the conversation from the message
const conversation = await this.client.conversations.getConversationById(
message.conversationId,
);
if (!conversation) {
console.error(`[${this.nameId}] Conversation not found for response`);
return;
}
if (this.typeOfResponse === "gpt") {
const messages = await conversation?.messages();
const baseName = this.name.split("-")[0].toLowerCase();
// Generate a response using OpenAI
const response = await this.generateOpenAIResponse(
message.content as string,
messages ?? [],
baseName,
);
console.log(
`[${this.nameId}] GPT response: "${response.slice(0, 50)}..."`,
);
// Send the response
await conversation?.send(response);
} else {
await conversation?.send(`${this.nameId} says: gm`);
}
} catch (error) {
console.error(`[${this.nameId}] Error generating response:`, error);
} finally {
console.timeEnd(`[${this.nameId}] Worker response`);
}
}
/**
* Initialize conversation stream
*/
private initConversationStream() {
void (async () => {
while (true) {
try {
const stream = await this.client.conversations.stream();
for await (const conversation of stream) {
if (!conversation?.id) continue;
if (this.listenerCount("message") > 0) {
this.emit("message", {
type: "stream_conversation",
conversation,
});
}
}
} catch (error) {
console.error("maints:conversation " + String(error));
}
}
})();
}
/**
* Initialize consent stream
*/
private initConsentStream() {
void (async () => {
while (true) {
try {
const stream = await this.client.preferences.streamConsent();
for await (const consentUpdate of stream) {
if (this.listenerCount("message") > 0) {
this.emit("message", {
type: "stream_consent",
consentUpdate,
});
}
}
} catch (error) {
console.error("maints:consent " + String(error));
}
}
})();
}
/**
* Collects stream events of specified type
*/
collectStreamEvents<T extends StreamMessage>(options: {
type: "message" | "conversation" | "consent" | "group_updated";
filterFn?: (msg: StreamMessage) => boolean;
count: number;
additionalInfo?: Record<string, string | number | boolean>;
}): Promise<T[]> {
const { type, filterFn, count, additionalInfo = {} } = options;
const filterInfo = Object.entries(additionalInfo)
.map(([key, value]) => `${key}:${value}`)
.join(", ");
console.log(
`[${this.nameId}] Collecting ${count} ${type}${filterInfo ? ` (${filterInfo})` : ""}`,
);
return new Promise((resolve) => {
const events: T[] = [];
const onMessage = (msg: StreamMessage) => {
const isRightType = msg.type === `stream_${type}`;
const passesFilter = !filterFn || filterFn(msg);
if (isRightType && passesFilter) {
events.push(msg as T);
if (events.length >= count) {
this.off("message", onMessage);
resolve(events);
}
}
};
this.on("message", onMessage);
});
}
/**
* Collect messages with specific criteria
*/
collectMessages(
groupId: string,
typeId: string,
count: number,
): Promise<StreamTextMessage[]> {
return this.collectStreamEvents<StreamTextMessage>({
type: "message",
filterFn: (msg) => {
if (msg.type !== "stream_message") return false;
const streamMsg = msg;
const conversationId = streamMsg.message.conversationId;
const contentType = streamMsg.message.contentType;
return groupId === conversationId && contentType?.typeId === typeId;
},
count,
additionalInfo: { groupId, contentType: typeId },
});
}
/**
* Collect group update messages for a specific group
*/
collectGroupUpdates(
groupId: string,
count: number,
): Promise<StreamGroupUpdateMessage[]> {
return this.collectStreamEvents<StreamGroupUpdateMessage>({
type: "group_updated",
filterFn: (msg) => {
if (msg.type !== "stream_group_updated") return false;
const streamMsg = msg;
return groupId === streamMsg.group.conversationId;
},
count,
additionalInfo: { groupId },
});
}
/**
* Collect conversations
*/
collectConversations(
fromPeerAddress: string,
count: number = 1,
): Promise<StreamConversationMessage[]> {
return this.collectStreamEvents<StreamConversationMessage>({
type: "conversation",
count,
additionalInfo: { fromPeerAddress },
});
}
/**
* Collect consent updates
*/
collectConsentUpdates(count: number = 1): Promise<StreamConsentMessage[]> {
return this.collectStreamEvents<StreamConsentMessage>({
type: "consent",
count,
});
}
/**
* Generates a response using OpenAI based on the message content.
*/
private async generateOpenAIResponse(
message: string,
history: DecodedMessage[],
workerName: string,
): Promise<string> {
// First check if OPENAI_API_KEY is configured
if (!process.env.OPENAI_API_KEY) {
console.warn(
"OPENAI_API_KEY is not set in environment variables. GPT workers may not function properly.",
);
return `${workerName}: Sorry, I'm not able to generate a response right now.`;
}
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
console.log(
`[${this.nameId}] Generating OpenAI response for message: ${message}`,
);
// Find matching personality or use a default
const personality =
personalities.find((p) => p.name === workerName)?.personality ||
"You are a helpful assistant with a friendly personality.";
// Prepare recent message history
const recentHistory =
history
?.slice(-10)
.map((m) => m.content as string)
.join("\n") || "";
const systemPrompt = `You are ${workerName}.
Keep your responses concise (under 100 words) and friendly.
Never mention other workers in your responses. Never answer more than 1 question per response.
Personality:
${personality}
For context, these were the last messages in the conversation:
${recentHistory}`;
try {
const completion = await openai.chat.completions.create({
messages: [
{
role: "system",
content: systemPrompt,
},
{ role: "user", content: message },
],
model: "gpt-4.1-mini",
});
return `${workerName}:\n${
completion.choices[0]?.message?.content ||
"I'm not sure how to respond to that."
}`;
} catch (error) {
console.error(`[${this.nameId}] OpenAI API error:`, error);
return `${workerName}: Sorry, I couldn't process that request right now.`;
}
}
/**
* Clears the database for this worker
* @returns true if the database was cleared, false otherwise
*/
clearDB(): Promise<boolean> {
const dataPath =
getDataPath(this.testName) + "/" + this.name + "/" + this.folder;
console.log(`[${this.nameId}] Clearing database at ${dataPath}`);
try {
if (fs.existsSync(dataPath)) {
fs.rmSync(dataPath, { recursive: true, force: true });
}
return Promise.resolve(true);
} catch (error) {
console.error(`[${this.nameId}] Error clearing database:`, error);
return Promise.resolve(false);
}
}
}