-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
294 lines (239 loc) · 8.41 KB
/
cli.js
File metadata and controls
294 lines (239 loc) · 8.41 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
#!/usr/bin/env bun
import { chatWithUser } from "./agent/agent.js";
import readline from "readline";
// Store the next page token for pagination
let nextPageToken = null;
let currentUserId = "user123"; // Default user ID
// Extract token from agent response
function extractToken(responseText) {
const friendlyRegex = /Next Page Token: (\S+)/;
const match = responseText.match(friendlyRegex);
if (match) {
return match[1];
}
const delimitedRegex = /---NEXT_PAGE_TOKEN_START---(.*?)---NEXT_PAGE_TOKEN_END---/;
const delimitedMatch = responseText.match(delimitedRegex);
return delimitedMatch ? delimitedMatch[1] : null;
}
// Create readline interface
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Prompt helper function
function prompt(question) {
return new Promise((resolve) => {
rl.question(question, resolve);
});
}
// Display welcome message and help
function displayWelcome() {
console.log(`
╔════════════════════════════════════════╗
║ 🚀 EMAIL AGENT ║
║ Your AI Email Assistant ║
╚════════════════════════════════════════╝
Available commands:
📧 fetch - Get your latest 10 emails
➡️ next - Get next page of emails
✉️ send - Send a new email
↩️ reply - Reply to an email from memory
❓ help - Show this help message
🚪 exit - Exit the application
Type a command to get started!
`);
}
// Display help
function displayHelp() {
console.log(`
📚 COMMAND HELP:
📧 fetch
Retrieves your latest 10 emails and stores them in memory.
Usage: Just type 'fetch'
➡️ next
Gets the next page of emails (if available from previous fetch).
Usage: Just type 'next'
✉️ send
Sends a new email to someone.
Usage: Type 'send' and follow the prompts for:
- Recipient email address
- Subject line
- Email content instruction
↩️ reply
Replies to an email from your recent emails in memory.
Usage: Type 'reply' and provide:
- Email identifier(s): You can use:
* Single identifier: 'govind@email.com' or 'Update on project'
* Multiple identifiers: 'govind@email.com, Update on project'
* Gmail ID: 'abc123def456' (most precise)
- Reply content instruction
❓ help
Shows this help message
🚪 exit
Exits the Email Agent
`);
}
// Handle fetch emails command
async function handleFetch() {
console.log("\n📧 Fetching your latest emails...\n");
try {
const query = `Get my latest 10 emails. userId: ${currentUserId}`;
const response = await chatWithUser(query);
// Extract and store next page token
const token = extractToken(response);
if (token && token !== 'null') {
nextPageToken = token;
console.log(`\n💡 More emails available. Use 'next' command to see them.`);
} else {
nextPageToken = null;
console.log(`\n📭 No more emails to fetch.`);
}
console.log("\n" + response);
} catch (error) {
console.error("\n❌ Error fetching emails:", error.message);
}
}
// Handle next page of emails
async function handleNext() {
if (!nextPageToken) {
console.log("\n📭 No more emails available. Use 'fetch' to get the latest emails first.");
return;
}
console.log("\n➡️ Fetching next page of emails...\n");
try {
const query = `Get my next 10 emails using pageToken: ${nextPageToken}. userId: ${currentUserId}`;
const response = await chatWithUser(query);
// Extract and store next page token
const token = extractToken(response);
if (token && token !== 'null') {
nextPageToken = token;
console.log(`\n💡 More emails available. Use 'next' command to continue.`);
} else {
nextPageToken = null;
console.log(`\n📭 No more emails to fetch.`);
}
console.log("\n" + response);
} catch (error) {
console.error("\n❌ Error fetching next emails:", error.message);
}
}
// Handle send email command
async function handleSend() {
console.log("\n✉️ Send a New Email");
console.log("━━━━━━━━━━━━━━━━━━━\n");
try {
const recipient = await prompt("📮 Recipient email address: ");
if (!recipient.trim()) {
console.log("❌ Recipient email is required!");
return;
}
const subject = await prompt("📝 Subject line: ");
if (!subject.trim()) {
console.log("❌ Subject is required!");
return;
}
const instruction = await prompt("💭 What should the email say? (describe the content): ");
if (!instruction.trim()) {
console.log("❌ Email content instruction is required!");
return;
}
console.log("\n📤 Sending email...\n");
const query = `Send a new email to ${recipient} with the subject '${subject}' and the body instruction '${instruction}'.`;
const response = await chatWithUser(query);
console.log("\n" + response);
} catch (error) {
console.error("\n❌ Error sending email:", error.message);
}
}
// Handle reply to email command
async function handleReply() {
console.log("\n↩️ Reply to an Email");
console.log("━━━━━━━━━━━━━━━━━━\n");
try {
// Import and check memory
const { getLastFetchedEmails } = await import("./aiServices/memory.js");
const cachedEmails = getLastFetchedEmails();
if (cachedEmails.length === 0) {
console.log("❌ No emails found in memory! Please use 'fetch' or 'next' to load emails first.");
return;
}
console.log(`📋 Found ${cachedEmails.length} emails in memory. Here are some examples:`);
cachedEmails.slice(0, 3).forEach((email, index) => {
console.log(` ${index + 1}. From: ${email.from} | Subject: ${email.subject?.substring(0, 50) || 'No subject'}...`);
});
console.log("");
console.log("💡 Tip: You can use multiple identifiers separated by commas for better matching");
console.log(" Example: 'govind@email.com, Update on project' or 'LinkedIn, invitation'");
console.log("");
const identifier = await prompt("🔍 Enter email identifier(s) (sender name, subject, or ID): ");
if (!identifier.trim()) {
console.log("❌ Email identifier is required!");
return;
}
const instruction = await prompt("💭 What should your reply say? (describe the reply content): ");
if (!instruction.trim()) {
console.log("❌ Reply content instruction is required!");
return;
}
console.log("\n📤 Sending reply...\n");
const query = `Reply to the email identified by "${identifier}" with the following content: ${instruction}`;
const response = await chatWithUser(query);
console.log("\n" + response);
} catch (error) {
console.error("\n❌ Error sending reply:", error.message);
}
}
// Main CLI loop
async function main() {
displayWelcome();
while (true) {
try {
const input = await prompt("\n🤖 Email Agent > ");
const command = input.trim().toLowerCase();
console.log(); // Add spacing
switch (command) {
case 'fetch':
await handleFetch();
break;
case 'next':
await handleNext();
break;
case 'send':
await handleSend();
break;
case 'reply':
await handleReply();
break;
case 'help':
displayHelp();
break;
case 'exit':
case 'quit':
case 'q':
console.log("👋 Thanks for using Email Agent! Goodbye!");
rl.close();
process.exit(0);
break;
case '':
// Empty input, just continue
break;
default:
console.log(`❓ Unknown command: '${command}'\nType 'help' to see available commands.`);
break;
}
} catch (error) {
console.error("❌ Unexpected error:", error.message);
}
}
}
// Handle process termination
process.on('SIGINT', () => {
console.log("\n\n👋 Thanks for using Email Agent! Goodbye!");
rl.close();
process.exit(0);
});
// Start the CLI
main().catch((error) => {
console.error("❌ Failed to start Email Agent:", error.message);
process.exit(1);
});