-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
513 lines (448 loc) · 13.6 KB
/
server.ts
File metadata and controls
513 lines (448 loc) · 13.6 KB
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
import { openai } from "@ai-sdk/openai";
import {
Agent,
ConsentState,
ConversationType,
type DecodedMessage,
type ExtractCodecContentTypes,
LogLevel,
} from "@xmtp/agent-sdk";
import { getTestUrl } from "@xmtp/agent-sdk/debug";
import {
ContentTypeGroupUpdated,
GroupUpdatedCodec,
} from "@xmtp/content-type-group-updated";
import {
ContentTypeReaction,
type Reaction,
ReactionCodec,
} from "@xmtp/content-type-reaction";
import {
ContentTypeReply,
type Reply,
ReplyCodec,
} from "@xmtp/content-type-reply";
import { ContentTypeText, TextCodec } from "@xmtp/content-type-text";
import {
ContentTypeTransactionReference,
TransactionReferenceCodec,
} from "@xmtp/content-type-transaction-reference";
import {
ContentTypeWalletSendCalls,
WalletSendCallsCodec,
} from "@xmtp/content-type-wallet-send-calls";
import { generateText } from "ai";
import type { Address, Hex, Signature, TypedDataDomain } from "viem";
import { sendToAgent } from "@/helpers/bitte-client";
import {
extractMessageContent,
getDbPath,
getEncryptionKeyFromHex,
logAgentDetails,
} from "@/helpers/client";
import {
AGENT_CHAT_ID,
XMTP_DB_ENCRYPTION_KEY,
XMTP_ENV,
} from "@/helpers/config";
// Import the transaction helpers
import {
extractSignerAddress,
handleEvmTransaction,
validateEvmTxResponse,
} from "@/helpers/transaction-helpers";
// [All your existing type definitions remain the same]
export interface TypedDataTypes {
name: string;
type: string;
}
export type TypedMessageTypes = {
[key: string]: TypedDataTypes[];
};
export type EIP712TypedData = {
domain: TypedDataDomain;
types: TypedMessageTypes;
message: Record<string, unknown>;
primaryType: string;
};
export interface TransactionWithSignature {
transaction: Hex;
signature: Signature;
}
export interface EthTransactionParams {
from: Hex;
to: Hex;
gas?: Hex;
value?: Hex;
data?: Hex;
}
export type PersonalSignParams = [Hex, Address];
export type EthSignParams = [Address, Hex];
export type TypedDataParams = [Hex, string];
export type SessionRequestParams =
| EthTransactionParams[]
| Hex
| PersonalSignParams
| EthSignParams
| TypedDataParams;
export declare const signMethods: readonly [
"eth_sign",
"personal_sign",
"eth_sendTransaction",
"eth_signTypedData",
"eth_signTypedData_v4",
];
export type SignMethod = (typeof signMethods)[number];
export type SignRequestData = {
method: SignMethod;
chainId: number;
params: SessionRequestParams;
};
// Type definitions for tool calls
interface ToolCallWithArgs {
toolCallId: string;
toolName: string;
args: Record<string, unknown>;
}
interface ToolCallWithResult {
toolCallId: string;
result: {
data?: { evmSignRequest: SignRequestData } | { swapArgs: SwapArgs };
error?: string;
};
ui?: Record<string, unknown>;
}
type ToolCall = ToolCallWithArgs | ToolCallWithResult;
interface SwapArgs {
sellToken: string;
buyToken: string;
}
interface CompletionResponse {
toolCalls?: ToolCall[];
content: string;
raw?: string;
finishReason?: string;
usage?: {
promptTokens: number;
completionTokens: number;
} | null;
isContinued?: boolean;
isError?: boolean;
}
// [All your existing constants and helper functions remain the same]
export const generateReaction = async ({
messageContent,
reference,
referenceInboxId,
}: {
messageContent: string;
reference: string;
referenceInboxId?: string;
}): Promise<Reaction> => {
const emoji = await generateText({
model: openai("gpt-4.1-nano"),
prompt: `Return only a single emoji that matches the sentiment of this message: ${messageContent}. Do not include any other text or explanation.`,
});
return {
reference,
action: "added",
content: emoji.text,
schema: "unicode",
referenceInboxId,
};
};
const CODECS = [
new ReactionCodec(),
new WalletSendCallsCodec(),
new TransactionReferenceCodec(),
new ReplyCodec(),
new TextCodec(),
new GroupUpdatedCodec(),
];
export type ClientContentTypes = ExtractCodecContentTypes<typeof CODECS>;
// Create the signer and client
// const signer = createSigner(WALLET_KEY);
const dbEncryptionKey = getEncryptionKeyFromHex(XMTP_DB_ENCRYPTION_KEY);
// const client = await Client.create(signer, {
// dbEncryptionKey,
// env: XMTP_ENV,
// dbPath: getDbPath(XMTP_ENV),
// codecs: CODECS,
// loggingLevel: LogLevel.error,
// });
// 2. Spin up the agent
const agent = (await Agent.createFromEnv({
env: "dev", // or 'production'
dbEncryptionKey,
dbPath: getDbPath(XMTP_ENV),
codecs: CODECS,
loggingLevel: LogLevel.error,
})) as Agent<ClientContentTypes>;
// 4. Log when we're ready
agent.on("start", () => {
console.log(`Waiting for messages...`);
console.log(`Address: ${agent.address}`);
console.log(`🔗 ${getTestUrl(agent.client)}`);
});
await agent.start();
const client = agent.client;
// Log agent details
void logAgentDetails(client);
// Retry configuration
const MAX_RETRIES = 5;
const RETRY_INTERVAL = 5000; // 5 seconds
let retries = MAX_RETRIES;
const retry = () => {
console.log(`Retrying in ${RETRY_INTERVAL / 1000}s, ${retries} retries left`);
if (retries > 0) {
retries--;
setTimeout(() => {
handleStream();
}, RETRY_INTERVAL);
} else {
console.log("Max retries reached, ending process");
process.exit(1);
}
};
const onFail = () => {
console.log("Stream failed");
retry();
};
// Main stream handling function
const handleStream = async () => {
try {
const clientIdentifier = await client.signer?.getIdentifier();
const clientEvmAddress = clientIdentifier?.identifier;
const clientInboxId = client.inboxId;
await client.conversations.syncAll([ConsentState.Allowed]);
console.log("Synced all conversations");
const stream = await client.conversations.streamAllMessages({
consentStates: [ConsentState.Allowed],
onValue: undefined,
onError: undefined,
onFail,
conversationType: ConversationType.Dm,
});
console.log("Waiting for messages...");
// Process messages from the stream
for await (const message of stream) {
try {
// skip if the message is not valid
if (!message || !message.contentType) continue;
const senderInboxId = message.senderInboxId;
// skip if the message is from the agent
if (senderInboxId === clientInboxId) continue;
// skip if the message is a reaction
if (message.contentType.sameAs(ContentTypeReaction)) continue;
const conversation = await client.conversations.getConversationById(
message.conversationId,
);
// skip if the conversation is not found
if (!conversation) {
console.error(
`Conversation with id ${message.conversationId} not found`,
);
continue;
}
// skip if message content is not valid
const messageContent = extractMessageContent(message);
if (!messageContent || messageContent === "") continue;
// Hardcoded to DM only for now
const isDm = true;
const isGroup = false;
const isSync = !isDm && !isGroup;
console.log({
isDm,
isGroup,
isSync,
content: messageContent,
});
// Skip group update messages
if (message.contentType.sameAs(ContentTypeGroupUpdated)) {
continue;
}
// if is DM or Group message, handle the conversation
if ((isDm || isGroup) && messageContent) {
// Check if this is the agent's first message in the conversation
const messages = await conversation.messages();
// const hasAgentReplied = messages.some(
// (msg) => msg.senderInboxId === clientInboxId,
// );
// TODO: fix welcome message
// if (!hasAgentReplied) {
// await conversation.send(WELCOME_MESSAGE, ContentTypeText);
// continue; // Skip AI response generation for welcome messages
// }
// Helper functions for group chat filtering
const isReplyToAgent = (message: DecodedMessage) => {
if (!message.contentType?.sameAs(ContentTypeReply)) return false;
const replyContent = message.content as Reply;
return messages.some(
(msg) =>
msg.id === replyContent.reference &&
msg.senderInboxId === clientInboxId,
);
};
const isTaggingClient = (messageContent: string) => {
const clientTags = [
`@${clientEvmAddress}`,
`@${AGENT_CHAT_ID}`,
"@bitte",
];
return clientTags.some((tag) =>
messageContent.toLowerCase().includes(tag.toLowerCase()),
);
};
// Skip group messages with no mention or reply to client
if (
isGroup &&
!isTaggingClient(messageContent) &&
!isReplyToAgent(message)
) {
continue;
}
// if not a transaction reference message, generate a reaction
if (!message.contentType.sameAs(ContentTypeTransactionReference)) {
// Generate and send a reaction
const reaction = await generateReaction({
messageContent,
reference: message.id,
referenceInboxId: senderInboxId,
});
await conversation.send(reaction, ContentTypeReaction);
}
// Get sender's EVM address
const inboxState =
await agent.client.preferences.inboxStateFromInboxIds([
senderInboxId,
]);
const addressFromInboxId =
inboxState?.[0]?.identifiers?.[0]?.identifier;
const chatId = `xmtp-${conversation.id}`;
console.log("Message Content", messageContent);
// Get AI response
const completion: CompletionResponse = await sendToAgent({
chatId,
message: messageContent,
evmAddress: addressFromInboxId,
contextMessage: `This is a ${
isGroup ? "group" : "DM"
} chat from within The Base App using XMTP. Keep responses brief when possible. Use plain text and emojis, do not include link, markdown, or html formatting.
The user's EVM address is ${addressFromInboxId}.
- Your are an agent built by the Bitte Protocol Team (Bitte.ai). Do not mention OpenAI or any other LLMs.`,
});
console.log("Completion", JSON.stringify(completion, null, 2));
// Handle tool calls using the transaction helpers
if (completion.toolCalls && completion.toolCalls.length > 0) {
for (const toolCall of completion.toolCalls) {
if ("result" in toolCall && toolCall.result?.data) {
const data = toolCall.result.data;
// Only process if data is an object (not string, number, etc.)
if (typeof data === "object" && data !== null) {
// Handle EVM sign requests using the helper functions
if ("evmSignRequest" in data && data.evmSignRequest) {
try {
// Validate the response
const validatedResponse = validateEvmTxResponse({
evmSignRequest: data.evmSignRequest,
});
// Extract signer address from the request (optional - for verification)
const signerFromRequest = extractSignerAddress(
validatedResponse.evmSignRequest,
);
// Use XMTP address as primary, but log if there's a mismatch
const userAddress = addressFromInboxId as `0x${string}`;
if (
signerFromRequest.toLowerCase() !==
userAddress.toLowerCase()
) {
console.warn(
`Address mismatch: XMTP=${userAddress}, Request=${signerFromRequest}`,
);
}
// Convert to wallet send calls
const result = await handleEvmTransaction(
validatedResponse,
userAddress,
);
if (result.success) {
// Send the wallet send calls
await conversation.send(
result.data,
ContentTypeWalletSendCalls,
);
} else {
console.error(
"❌ Failed to convert EVM transaction:",
result.error,
);
// Optionally send an error message to the user
await conversation.send(
`Sorry, I encountered an error processing your transaction: ${result.error}`,
ContentTypeText,
);
}
} catch (error) {
console.error(
"❌ Error processing EVM sign request:",
error,
);
// Log the actual data that caused the error
console.error(
"Data that caused error:",
JSON.stringify(data, null, 2),
);
// Optionally send an error message to the user
const errorMessage =
error instanceof Error
? error.message
: "Unknown error occurred";
await conversation.send(
`Sorry, I couldn't process your transaction request: ${errorMessage}`,
ContentTypeText,
);
}
}
// Handle other tool call types here if needed
}
// Silently ignore other data types
}
}
}
const isTransactionReference = message?.contentType?.sameAs(
ContentTypeTransactionReference,
);
// send tx reference to agent
if (isTransactionReference) {
await conversation.send(
`Transaction reference: ${message.content}`,
ContentTypeTransactionReference,
);
}
// Send AI response (ignore transaction references)
if (completion.content && !isTransactionReference) {
// handle group messages
if (isGroup) {
const reply: Reply = {
reference: message.id,
contentType: ContentTypeText,
content: completion.content,
};
await conversation.send(reply, ContentTypeReply);
// handle DM messages
} else {
await conversation.send(completion.content, ContentTypeText);
}
}
}
} catch (error) {
console.error("❌ Error processing message:", error);
}
}
} catch (error) {
console.error("❌ Stream error:", error);
onFail();
}
};
// Start the stream handling
handleStream();