Repository navigation
Expand file tree
/
Copy pathread.ts
More file actions
363 lines (332 loc) · 11.1 KB
/
Copy pathread.ts
File metadata and controls
363 lines (332 loc) · 11.1 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
import { createLogger } from '@sim/logger'
import type { GmailAttachment, GmailReadParams, GmailToolResponse } from '@/tools/gmail/types'
import {
createMessagesSummary,
GMAIL_API_BASE,
processMessage,
processMessageForSummary,
} from '@/tools/gmail/utils'
import type { ToolConfig } from '@/tools/types'
const logger = createLogger('GmailReadTool')
export const gmailReadTool: ToolConfig<GmailReadParams, GmailToolResponse> = {
id: 'gmail_read',
name: 'Gmail Read',
description: 'Read emails from Gmail',
version: '1.0.0',
oauth: {
required: true,
provider: 'google-email',
},
params: {
accessToken: {
type: 'string',
required: true,
visibility: 'hidden',
description: 'Access token for Gmail API',
},
messageId: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description: 'Gmail message ID to read (e.g., 18f1a2b3c4d5e6f7)',
},
folder: {
type: 'string',
required: false,
visibility: 'user-or-llm',
description:
'Folder/label to read emails from (e.g., INBOX, SENT, DRAFT, TRASH, SPAM, or custom label name)',
},
unreadOnly: {
type: 'boolean',
required: false,
visibility: 'user-or-llm',
description: 'Set to true to only retrieve unread messages',
},
maxResults: {
type: 'number',
required: false,
visibility: 'user-or-llm',
description: 'Maximum number of messages to retrieve (default: 1, max: 10)',
},
includeAttachments: {
type: 'boolean',
required: false,
visibility: 'user-or-llm',
description: 'Set to true to download and include email attachments',
},
},
request: {
url: (params) => {
// If a specific message ID is provided, fetch that message directly with full format
if (params.messageId) {
return `${GMAIL_API_BASE}/messages/${params.messageId}?format=full`
}
// Otherwise, list messages from the specified folder or INBOX by default
const url = new URL(`${GMAIL_API_BASE}/messages`)
// Build query parameters for the folder/label
const queryParams = []
// Add unread filter if specified
if (params.unreadOnly) {
queryParams.push('is:unread')
}
if (params.folder) {
// If it's a system label like INBOX, SENT, etc., use it directly
if (['INBOX', 'SENT', 'DRAFT', 'TRASH', 'SPAM'].includes(params.folder)) {
queryParams.push(`in:${params.folder.toLowerCase()}`)
} else {
// Otherwise, it's a user-defined label
queryParams.push(`label:${params.folder}`)
}
} else {
// Default to INBOX if no folder is specified
queryParams.push('in:inbox')
}
// Only add query if we have parameters
if (queryParams.length > 0) {
url.searchParams.append('q', queryParams.join(' '))
}
// Set max results (default to 1 for simplicity, max 10)
const maxResults = params.maxResults ? Math.min(Number(params.maxResults), 10) : 1
url.searchParams.append('maxResults', maxResults.toString())
return url.toString()
},
method: 'GET',
headers: (params: GmailReadParams) => ({
Authorization: `Bearer ${params.accessToken}`,
'Content-Type': 'application/json',
}),
},
transformResponse: async (response: Response, params?: GmailReadParams) => {
const data = await response.json()
// If we're fetching a single message directly (by ID)
if (params?.messageId) {
return await processMessage(data, params)
}
// If we're listing messages, we need to fetch each message's details
if (data.messages && Array.isArray(data.messages)) {
// Return a message if no emails found
if (data.messages.length === 0) {
return {
success: true,
output: {
content: 'No messages found in the selected folder.',
metadata: {
results: [], // Use SearchMetadata format
},
},
}
}
// For agentic workflows, we'll fetch the first message by default
// If maxResults > 1, we'll return a summary of messages found
const maxResults = params?.maxResults ? Math.min(Number(params.maxResults), 10) : 1
if (maxResults === 1) {
try {
// Get the first message details
const messageId = data.messages[0].id
const messageResponse = await fetch(
`${GMAIL_API_BASE}/messages/${messageId}?format=full`,
{
headers: {
Authorization: `Bearer ${params?.accessToken || ''}`,
'Content-Type': 'application/json',
},
}
)
if (!messageResponse.ok) {
const errorData = await messageResponse.json()
throw new Error(errorData.error?.message || 'Failed to fetch message details')
}
const message = await messageResponse.json()
return await processMessage(message, params)
} catch (error: any) {
return {
success: true,
output: {
content: `Found messages but couldn't retrieve details: ${error.message || 'Unknown error'}`,
metadata: {
results: data.messages.map((msg: any) => ({
id: msg.id,
threadId: msg.threadId,
})),
},
},
}
}
} else {
// If maxResults > 1, fetch details for all messages
try {
const messagePromises = data.messages.slice(0, maxResults).map(async (msg: any) => {
const messageResponse = await fetch(
`${GMAIL_API_BASE}/messages/${msg.id}?format=full`,
{
headers: {
Authorization: `Bearer ${params?.accessToken || ''}`,
'Content-Type': 'application/json',
},
}
)
if (!messageResponse.ok) {
throw new Error(`Failed to fetch details for message ${msg.id}`)
}
return await messageResponse.json()
})
const messages = await Promise.all(messagePromises)
// Create summary from processed messages first
const summaryMessages = messages.map(processMessageForSummary)
const allAttachments: GmailAttachment[] = []
if (params?.includeAttachments) {
for (const msg of messages) {
try {
const processedResult = await processMessage(msg, params)
if (
processedResult.output.attachments &&
processedResult.output.attachments.length > 0
) {
allAttachments.push(...processedResult.output.attachments)
}
} catch (error: any) {
logger.error(`Error processing message ${msg.id} for attachments:`, error)
}
}
}
return {
success: true,
output: {
content: createMessagesSummary(summaryMessages),
metadata: {
results: summaryMessages.map((msg) => ({
id: msg.id,
threadId: msg.threadId,
subject: msg.subject,
from: msg.from,
to: msg.to,
date: msg.date,
})),
},
attachments: allAttachments,
},
}
} catch (error: any) {
return {
success: true,
output: {
content: `Found ${data.messages.length} messages but couldn't retrieve all details: ${error.message || 'Unknown error'}`,
metadata: {
results: data.messages.map((msg: any) => ({
id: msg.id,
threadId: msg.threadId,
})),
},
attachments: [],
},
}
}
}
}
// Fallback for unexpected response format
return {
success: true,
output: {
content: 'Unexpected response format from Gmail API',
metadata: {
results: [],
},
},
}
},
outputs: {
content: { type: 'string', description: 'Text content of the email' },
metadata: { type: 'json', description: 'Metadata of the email' },
attachments: { type: 'file[]', description: 'Attachments of the email' },
},
}
interface GmailReadV2Response {
success: boolean
output: {
id?: string
threadId?: string
labelIds?: string[]
from?: string
to?: string
subject?: string
date?: string
body?: string
hasAttachments?: boolean
attachmentCount?: number
attachments?: GmailAttachment[]
results?: Array<Record<string, any>>
}
}
export const gmailReadV2Tool: ToolConfig<GmailReadParams, GmailReadV2Response> = {
id: 'gmail_read_v2',
name: 'Gmail Read',
description: 'Read emails from Gmail. Returns API-aligned fields only.',
version: '2.0.0',
oauth: gmailReadTool.oauth,
params: gmailReadTool.params,
request: gmailReadTool.request,
transformResponse: async (response: Response, params?: GmailReadParams) => {
const legacy = await gmailReadTool.transformResponse!(response, params)
if (!legacy.success) {
return {
success: false,
output: {},
error: legacy.error,
}
}
const metadata = (legacy.output.metadata || {}) as any
return {
success: true,
output: {
id: metadata.id,
threadId: metadata.threadId,
labelIds: metadata.labelIds,
from: metadata.from,
to: metadata.to,
subject: metadata.subject,
date: metadata.date,
body: legacy.output.content,
hasAttachments: metadata.hasAttachments,
attachmentCount: metadata.attachmentCount,
attachments: legacy.output.attachments || [],
results: metadata.results,
},
}
},
outputs: {
id: { type: 'string', description: 'Gmail message ID', optional: true },
threadId: { type: 'string', description: 'Gmail thread ID', optional: true },
labelIds: {
type: 'array',
items: { type: 'string' },
description: 'Email labels',
optional: true,
},
from: { type: 'string', description: 'Sender email address', optional: true },
to: { type: 'string', description: 'Recipient email address', optional: true },
subject: { type: 'string', description: 'Email subject', optional: true },
date: { type: 'string', description: 'Email date', optional: true },
body: {
type: 'string',
description: 'Email body text (best-effort plain text)',
optional: true,
},
hasAttachments: {
type: 'boolean',
description: 'Whether the email has attachments',
optional: true,
},
attachmentCount: { type: 'number', description: 'Number of attachments', optional: true },
attachments: {
type: 'file[]',
description: 'Downloaded attachments (if enabled)',
optional: true,
},
results: {
type: 'json',
description: 'Summary results when reading multiple messages',
optional: true,
},
},
}