@framers/agentos-ext-email-gmail 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,98 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License.
30
+
31
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License.
34
+
35
+ Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
36
+
37
+ 4. Redistribution.
38
+
39
+ You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
40
+
41
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
42
+
43
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
44
+
45
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
46
+
47
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
48
+
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
50
+
51
+ 5. Submission of Contributions.
52
+
53
+ Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
54
+
55
+ 6. Trademarks.
56
+
57
+ This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
58
+
59
+ 7. Disclaimer of Warranty.
60
+
61
+ Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
62
+
63
+ 8. Limitation of Liability.
64
+
65
+ In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
66
+
67
+ 9. Accepting Warranty or Additional Liability.
68
+
69
+ While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
70
+
71
+ END OF TERMS AND CONDITIONS
72
+
73
+ APPENDIX: How to apply the Apache License to your work.
74
+
75
+ To apply the Apache License to your work, attach the following
76
+ boilerplate notice, with the fields enclosed by brackets "[]"
77
+ replaced with your own identifying information. (Don't include
78
+ the brackets!) The text should be enclosed in the appropriate
79
+ comment syntax for the file format. We also recommend that a
80
+ file or class name and description of purpose be included on the
81
+ same "printed page" as the copyright notice for easier
82
+ identification within third-party archives.
83
+
84
+ Copyright (c) 2025 Framers
85
+
86
+ Licensed under the Apache License, Version 2.0 (the "License");
87
+ you may not use this file except in compliance with the License.
88
+ You may obtain a copy of the License at
89
+
90
+ http://www.apache.org/licenses/LICENSE-2.0
91
+
92
+ Unless required by applicable law or agreed to in writing, software
93
+ distributed under the License is distributed on an "AS IS" BASIS,
94
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
95
+ See the License for the specific language governing permissions and
96
+ limitations under the License.
97
+
98
+
@@ -0,0 +1,92 @@
1
+ /**
2
+ * @fileoverview Gmail API wrapper using Google OAuth2.
3
+ * Handles authentication, message CRUD, search, and label management.
4
+ *
5
+ * @module @framers/agentos-ext-email-gmail/GmailService
6
+ */
7
+ export interface GmailConfig {
8
+ clientId: string;
9
+ clientSecret: string;
10
+ refreshToken: string;
11
+ }
12
+ export interface EmailMessage {
13
+ id: string;
14
+ threadId: string;
15
+ subject: string;
16
+ from: string;
17
+ to: string[];
18
+ cc?: string[];
19
+ date: string;
20
+ snippet: string;
21
+ body: string;
22
+ labelIds: string[];
23
+ isUnread: boolean;
24
+ }
25
+ export interface EmailLabel {
26
+ id: string;
27
+ name: string;
28
+ type: string;
29
+ messagesTotal?: number;
30
+ messagesUnread?: number;
31
+ }
32
+ export interface ListMessagesOptions {
33
+ query?: string;
34
+ labelIds?: string[];
35
+ maxResults?: number;
36
+ }
37
+ export declare class GmailService {
38
+ private oauth2Client;
39
+ private gmail;
40
+ private initialized;
41
+ private readonly config;
42
+ constructor(config: GmailConfig);
43
+ initialize(): Promise<void>;
44
+ shutdown(): Promise<void>;
45
+ get isInitialized(): boolean;
46
+ private get api();
47
+ getProfile(): Promise<{
48
+ emailAddress: string;
49
+ messagesTotal: number;
50
+ threadsTotal: number;
51
+ }>;
52
+ /**
53
+ * Lists messages matching optional query and label filters.
54
+ * Returns full message details (not just IDs) by batch-fetching each result.
55
+ */
56
+ listMessages(options?: ListMessagesOptions): Promise<EmailMessage[]>;
57
+ /**
58
+ * Retrieves a single message by ID with full content.
59
+ */
60
+ getMessage(messageId: string): Promise<EmailMessage>;
61
+ /**
62
+ * Composes and sends a new email.
63
+ */
64
+ sendMessage(opts: {
65
+ to: string;
66
+ subject: string;
67
+ body: string;
68
+ cc?: string;
69
+ bcc?: string;
70
+ }): Promise<{
71
+ id: string;
72
+ threadId: string;
73
+ }>;
74
+ /**
75
+ * Replies to an existing message within its thread.
76
+ * Preserves In-Reply-To and References headers for proper threading.
77
+ */
78
+ replyToMessage(messageId: string, body: string): Promise<{
79
+ id: string;
80
+ threadId: string;
81
+ }>;
82
+ /**
83
+ * Searches messages using Gmail query syntax.
84
+ * Delegates to listMessages with the query parameter.
85
+ */
86
+ searchMessages(query: string, maxResults?: number): Promise<EmailMessage[]>;
87
+ /**
88
+ * Lists all labels (folders) in the user's mailbox.
89
+ */
90
+ listLabels(): Promise<EmailLabel[]>;
91
+ }
92
+ //# sourceMappingURL=GmailService.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GmailService.d.ts","sourceRoot":"","sources":["../src/GmailService.ts"],"names":[],"mappings":"AACA;;;;;GAKG;AASH,MAAM,WAAW,WAAW;IAC1B,QAAQ,E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AC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC;IAWlG;;;OAGG;IACG,YAAY,CAAC,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IA4B9E;;OAEG;IACG,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAS1D;;OAEG;IACG,WAAW,CAAC,IAAI,EAAE;QACtB,EAAE,EAAE,MAAM,CAAC;QACX,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,EAAE,CAAC,EAAE,MAAM,CAAC;QACZ,GAAG,CAAC,EAAE,MAAM,CAAC;KACd,GAAG,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;IAsB7C;;;OAGG;IACG,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;IAsChG;;;OAGG;IACG,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,UAAU,SAAK,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IAM7E;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;CA+B1C"}
@@ -0,0 +1,318 @@
1
+ "use strict";
2
+ // @ts-nocheck
3
+ /**
4
+ * @fileoverview Gmail API wrapper using Google OAuth2.
5
+ * Handles authentication, message CRUD, search, and label management.
6
+ *
7
+ * @module @framers/agentos-ext-email-gmail/GmailService
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.GmailService = void 0;
11
+ const googleapis_1 = require("googleapis");
12
+ const google_auth_library_1 = require("google-auth-library");
13
+ // ---------------------------------------------------------------------------
14
+ // Helpers
15
+ // ---------------------------------------------------------------------------
16
+ /**
17
+ * Extracts a header value from a Gmail message payload.
18
+ */
19
+ function getHeader(headers, name) {
20
+ if (!headers)
21
+ return '';
22
+ const header = headers.find((h) => h.name?.toLowerCase() === name.toLowerCase());
23
+ return header?.value ?? '';
24
+ }
25
+ /**
26
+ * Parses a comma-separated address list into individual addresses.
27
+ */
28
+ function parseAddressList(raw) {
29
+ if (!raw)
30
+ return [];
31
+ return raw
32
+ .split(',')
33
+ .map((a) => a.trim())
34
+ .filter(Boolean);
35
+ }
36
+ /**
37
+ * Recursively extracts the text body from a MIME message payload.
38
+ * Prefers text/plain; falls back to text/html with tags stripped.
39
+ */
40
+ function extractBody(payload) {
41
+ if (!payload)
42
+ return '';
43
+ // Single-part message
44
+ if (payload.body?.data) {
45
+ const decoded = Buffer.from(payload.body.data, 'base64url').toString('utf-8');
46
+ if (payload.mimeType === 'text/plain')
47
+ return decoded;
48
+ if (payload.mimeType === 'text/html')
49
+ return stripHtml(decoded);
50
+ return decoded;
51
+ }
52
+ // Multipart — walk parts, prefer text/plain
53
+ if (payload.parts && payload.parts.length > 0) {
54
+ // First pass: look for text/plain
55
+ for (const part of payload.parts) {
56
+ if (part.mimeType === 'text/plain' && part.body?.data) {
57
+ return Buffer.from(part.body.data, 'base64url').toString('utf-8');
58
+ }
59
+ }
60
+ // Second pass: look for text/html
61
+ for (const part of payload.parts) {
62
+ if (part.mimeType === 'text/html' && part.body?.data) {
63
+ return stripHtml(Buffer.from(part.body.data, 'base64url').toString('utf-8'));
64
+ }
65
+ }
66
+ // Third pass: recurse into nested multipart
67
+ for (const part of payload.parts) {
68
+ if (part.mimeType?.startsWith('multipart/')) {
69
+ const nested = extractBody(part);
70
+ if (nested)
71
+ return nested;
72
+ }
73
+ }
74
+ }
75
+ return '';
76
+ }
77
+ /**
78
+ * Naive HTML tag stripper for fallback body extraction.
79
+ */
80
+ function stripHtml(html) {
81
+ return html
82
+ .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
83
+ .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
84
+ .replace(/<[^>]+>/g, '')
85
+ .replace(/&nbsp;/gi, ' ')
86
+ .replace(/&amp;/gi, '&')
87
+ .replace(/&lt;/gi, '<')
88
+ .replace(/&gt;/gi, '>')
89
+ .replace(/&quot;/gi, '"')
90
+ .replace(/\n{3,}/g, '\n\n')
91
+ .trim();
92
+ }
93
+ /**
94
+ * Converts a raw Gmail API message into a normalized EmailMessage.
95
+ */
96
+ function parseMessage(msg) {
97
+ const headers = msg.payload?.headers;
98
+ return {
99
+ id: msg.id ?? '',
100
+ threadId: msg.threadId ?? '',
101
+ subject: getHeader(headers, 'Subject'),
102
+ from: getHeader(headers, 'From'),
103
+ to: parseAddressList(getHeader(headers, 'To')),
104
+ cc: parseAddressList(getHeader(headers, 'Cc')) || undefined,
105
+ date: getHeader(headers, 'Date'),
106
+ snippet: msg.snippet ?? '',
107
+ body: extractBody(msg.payload),
108
+ labelIds: msg.labelIds ?? [],
109
+ isUnread: (msg.labelIds ?? []).includes('UNREAD'),
110
+ };
111
+ }
112
+ /**
113
+ * Builds an RFC 2822 formatted email string and base64url-encodes it
114
+ * for the Gmail API send endpoint.
115
+ */
116
+ function buildRawEmail(opts) {
117
+ const lines = [];
118
+ if (opts.from)
119
+ lines.push(`From: ${opts.from}`);
120
+ lines.push(`To: ${opts.to}`);
121
+ if (opts.cc)
122
+ lines.push(`Cc: ${opts.cc}`);
123
+ if (opts.bcc)
124
+ lines.push(`Bcc: ${opts.bcc}`);
125
+ lines.push(`Subject: ${opts.subject}`);
126
+ if (opts.inReplyTo)
127
+ lines.push(`In-Reply-To: ${opts.inReplyTo}`);
128
+ if (opts.references)
129
+ lines.push(`References: ${opts.references}`);
130
+ lines.push('Content-Type: text/plain; charset="UTF-8"');
131
+ lines.push('MIME-Version: 1.0');
132
+ lines.push('');
133
+ lines.push(opts.body);
134
+ const raw = lines.join('\r\n');
135
+ return Buffer.from(raw, 'utf-8').toString('base64url');
136
+ }
137
+ // ---------------------------------------------------------------------------
138
+ // Service
139
+ // ---------------------------------------------------------------------------
140
+ class GmailService {
141
+ constructor(config) {
142
+ this.oauth2Client = null;
143
+ this.gmail = null;
144
+ this.initialized = false;
145
+ this.config = config;
146
+ }
147
+ // ---- Lifecycle ----------------------------------------------------------
148
+ async initialize() {
149
+ if (this.initialized)
150
+ return;
151
+ this.oauth2Client = new google_auth_library_1.OAuth2Client(this.config.clientId, this.config.clientSecret);
152
+ this.oauth2Client.setCredentials({
153
+ refresh_token: this.config.refreshToken,
154
+ });
155
+ this.gmail = googleapis_1.google.gmail({ version: 'v1', auth: this.oauth2Client });
156
+ this.initialized = true;
157
+ }
158
+ async shutdown() {
159
+ this.gmail = null;
160
+ this.oauth2Client = null;
161
+ this.initialized = false;
162
+ }
163
+ get isInitialized() {
164
+ return this.initialized;
165
+ }
166
+ get api() {
167
+ if (!this.gmail)
168
+ throw new Error('GmailService not initialized. Call initialize() first.');
169
+ return this.gmail;
170
+ }
171
+ // ---- Profile ------------------------------------------------------------
172
+ async getProfile() {
173
+ const res = await this.api.users.getProfile({ userId: 'me' });
174
+ return {
175
+ emailAddress: res.data.emailAddress ?? '',
176
+ messagesTotal: res.data.messagesTotal ?? 0,
177
+ threadsTotal: res.data.threadsTotal ?? 0,
178
+ };
179
+ }
180
+ // ---- Messages -----------------------------------------------------------
181
+ /**
182
+ * Lists messages matching optional query and label filters.
183
+ * Returns full message details (not just IDs) by batch-fetching each result.
184
+ */
185
+ async listMessages(options = {}) {
186
+ const { query, labelIds, maxResults = 10 } = options;
187
+ const listRes = await this.api.users.messages.list({
188
+ userId: 'me',
189
+ q: query,
190
+ labelIds: labelIds,
191
+ maxResults,
192
+ });
193
+ const messageStubs = listRes.data.messages ?? [];
194
+ if (messageStubs.length === 0)
195
+ return [];
196
+ // Batch-fetch full message details
197
+ const messages = await Promise.all(messageStubs.map(async (stub) => {
198
+ const full = await this.api.users.messages.get({
199
+ userId: 'me',
200
+ id: stub.id,
201
+ format: 'full',
202
+ });
203
+ return parseMessage(full.data);
204
+ }));
205
+ return messages;
206
+ }
207
+ /**
208
+ * Retrieves a single message by ID with full content.
209
+ */
210
+ async getMessage(messageId) {
211
+ const res = await this.api.users.messages.get({
212
+ userId: 'me',
213
+ id: messageId,
214
+ format: 'full',
215
+ });
216
+ return parseMessage(res.data);
217
+ }
218
+ /**
219
+ * Composes and sends a new email.
220
+ */
221
+ async sendMessage(opts) {
222
+ const profile = await this.getProfile();
223
+ const raw = buildRawEmail({
224
+ from: profile.emailAddress,
225
+ to: opts.to,
226
+ subject: opts.subject,
227
+ body: opts.body,
228
+ cc: opts.cc,
229
+ bcc: opts.bcc,
230
+ });
231
+ const res = await this.api.users.messages.send({
232
+ userId: 'me',
233
+ requestBody: { raw },
234
+ });
235
+ return {
236
+ id: res.data.id ?? '',
237
+ threadId: res.data.threadId ?? '',
238
+ };
239
+ }
240
+ /**
241
+ * Replies to an existing message within its thread.
242
+ * Preserves In-Reply-To and References headers for proper threading.
243
+ */
244
+ async replyToMessage(messageId, body) {
245
+ // Fetch original message for threading headers
246
+ const original = await this.api.users.messages.get({
247
+ userId: 'me',
248
+ id: messageId,
249
+ format: 'full',
250
+ });
251
+ const headers = original.data.payload?.headers;
252
+ const messageIdHeader = getHeader(headers, 'Message-ID') || getHeader(headers, 'Message-Id');
253
+ const subject = getHeader(headers, 'Subject');
254
+ const from = getHeader(headers, 'From');
255
+ const replySubject = subject.startsWith('Re:') ? subject : `Re: ${subject}`;
256
+ const profile = await this.getProfile();
257
+ const raw = buildRawEmail({
258
+ from: profile.emailAddress,
259
+ to: from,
260
+ subject: replySubject,
261
+ body,
262
+ inReplyTo: messageIdHeader,
263
+ references: messageIdHeader,
264
+ });
265
+ const res = await this.api.users.messages.send({
266
+ userId: 'me',
267
+ requestBody: {
268
+ raw,
269
+ threadId: original.data.threadId ?? undefined,
270
+ },
271
+ });
272
+ return {
273
+ id: res.data.id ?? '',
274
+ threadId: res.data.threadId ?? '',
275
+ };
276
+ }
277
+ /**
278
+ * Searches messages using Gmail query syntax.
279
+ * Delegates to listMessages with the query parameter.
280
+ */
281
+ async searchMessages(query, maxResults = 10) {
282
+ return this.listMessages({ query, maxResults });
283
+ }
284
+ // ---- Labels -------------------------------------------------------------
285
+ /**
286
+ * Lists all labels (folders) in the user's mailbox.
287
+ */
288
+ async listLabels() {
289
+ const res = await this.api.users.labels.list({ userId: 'me' });
290
+ const labels = res.data.labels ?? [];
291
+ // Fetch detail for each label to get message counts
292
+ const detailed = await Promise.all(labels.map(async (label) => {
293
+ try {
294
+ const detail = await this.api.users.labels.get({
295
+ userId: 'me',
296
+ id: label.id,
297
+ });
298
+ return {
299
+ id: detail.data.id ?? '',
300
+ name: detail.data.name ?? '',
301
+ type: detail.data.type ?? 'user',
302
+ messagesTotal: detail.data.messagesTotal ?? undefined,
303
+ messagesUnread: detail.data.messagesUnread ?? undefined,
304
+ };
305
+ }
306
+ catch {
307
+ return {
308
+ id: label.id ?? '',
309
+ name: label.name ?? '',
310
+ type: label.type ?? 'user',
311
+ };
312
+ }
313
+ }));
314
+ return detailed;
315
+ }
316
+ }
317
+ exports.GmailService = GmailService;
318
+ //# sourceMappingURL=GmailService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GmailService.js","sourceRoot":"","sources":["../src/GmailService.ts"],"names":[],"mappings":";AAAA,cAAc;AACd;;;;;GAKG;;;AAEH,2CAAmD;AACnD,6DAAmD;AAwCnD,8EAA8E;AAC9E,UAAU;AACV,8EAA8E;AAE9E;;GAEG;AACH,SAAS,SAAS,CAChB,OAAwD,EACxD,IAAY;IAEZ,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IACxB,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,WAAW,EAAE,KAAK,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;IACjF,OAAO,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC;AAC7B,CAAC;AAED;;GAEG;AACH,SAAS,gBAAgB,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5B,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,IAAI,MAAM;oBAChC,aAAa,EAAE,MAAM,CAAC,IAAI,CAAC,aAAa,IAAI,SAAS;oBACrD,cAAc,EAAE,MAAM,CAAC,IAAI,CAAC,cAAc,IAAI,SAAS;iBAC1C,CAAC;YAClB,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO;oBACL,EAAE,EAAE,KAAK,CAAC,EAAE,IAAI,EAAE;oBAClB,IAAI,EAAE,KAAK,CAAC,IAAI,IAAI,EAAE;oBACtB,IAAI,EAAE,KAAK,CAAC,IAAI,IAAI,MAAM;iBACb,CAAC;YAClB,CAAC;QACH,CAAC,CAAC,CACH,CAAC;QAEF,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF;AAzND,oCAyNC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @fileoverview Gmail Email Extension for AgentOS.
3
+ *
4
+ * Provides 6 ITool descriptors for email operations via the Google Gmail API:
5
+ * list messages, read message, send message, reply to message, search, and list labels.
6
+ *
7
+ * @module @framers/agentos-ext-email-gmail
8
+ */
9
+ import type { ExtensionContext, ExtensionPack } from '@framers/agentos';
10
+ import { GmailService } from './GmailService';
11
+ import { GmailListMessagesTool } from './tools/listMessages';
12
+ import { GmailReadMessageTool } from './tools/readMessage';
13
+ import { GmailSendMessageTool } from './tools/sendMessage';
14
+ import { GmailReplyMessageTool } from './tools/replyMessage';
15
+ import { GmailSearchMessagesTool } from './tools/searchMessages';
16
+ import { GmailListLabelsTool } from './tools/listLabels';
17
+ export interface GmailExtensionOptions {
18
+ clientId?: string;
19
+ clientSecret?: string;
20
+ refreshToken?: string;
21
+ priority?: number;
22
+ }
23
+ export declare function createExtensionPack(context: ExtensionContext): ExtensionPack;
24
+ export { GmailService, GmailListMessagesTool, GmailReadMessageTool, GmailSendMessageTool, GmailReplyMessageTool, GmailSearchMessagesTool, GmailListLabelsTool, };
25
+ export type { GmailConfig, EmailMessage, EmailLabel, ListMessagesOptions } from './GmailService';
26
+ export default createExtensionPack;
27
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,YAAY,EAAoB,MAAM,gBAAgB,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEzD,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AA0BD,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,gBAAgB,GAAG,aAAa,CA4D5E;AAED,OAAO,EACL,YAAY,EACZ,qBAAqB,EACrB,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,uBAAuB,EACvB,mBAAmB,GACpB,CAAC;AACF,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACjG,eAAe,mBAAmB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ // @ts-nocheck
3
+ /**
4
+ * @fileoverview Gmail Email Extension for AgentOS.
5
+ *
6
+ * Provides 6 ITool descriptors for email operations via the Google Gmail API:
7
+ * list messages, read message, send message, reply to message, search, and list labels.
8
+ *
9
+ * @module @framers/agentos-ext-email-gmail
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.GmailListLabelsTool = exports.GmailSearchMessagesTool = exports.GmailReplyMessageTool = exports.GmailSendMessageTool = exports.GmailReadMessageTool = exports.GmailListMessagesTool = exports.GmailService = void 0;
13
+ exports.createExtensionPack = createExtensionPack;
14
+ const GmailService_1 = require("./GmailService");
15
+ Object.defineProperty(exports, "GmailService", { enumerable: true, get: function () { return GmailService_1.GmailService; } });
16
+ const listMessages_1 = require("./tools/listMessages");
17
+ Object.defineProperty(exports, "GmailListMessagesTool", { enumerable: true, get: function () { return listMessages_1.GmailListMessagesTool; } });
18
+ const readMessage_1 = require("./tools/readMessage");
19
+ Object.defineProperty(exports, "GmailReadMessageTool", { enumerable: true, get: function () { return readMessage_1.GmailReadMessageTool; } });
20
+ const sendMessage_1 = require("./tools/sendMessage");
21
+ Object.defineProperty(exports, "GmailSendMessageTool", { enumerable: true, get: function () { return sendMessage_1.GmailSendMessageTool; } });
22
+ const replyMessage_1 = require("./tools/replyMessage");
23
+ Object.defineProperty(exports, "GmailReplyMessageTool", { enumerable: true, get: function () { return replyMessage_1.GmailReplyMessageTool; } });
24
+ const searchMessages_1 = require("./tools/searchMessages");
25
+ Object.defineProperty(exports, "GmailSearchMessagesTool", { enumerable: true, get: function () { return searchMessages_1.GmailSearchMessagesTool; } });
26
+ const listLabels_1 = require("./tools/listLabels");
27
+ Object.defineProperty(exports, "GmailListLabelsTool", { enumerable: true, get: function () { return listLabels_1.GmailListLabelsTool; } });
28
+ /**
29
+ * Resolves a Google OAuth credential from options, secrets map, or environment variables.
30
+ */
31
+ function resolveCredential(name, optionValue, secrets, secretKey, envNames) {
32
+ if (optionValue)
33
+ return optionValue;
34
+ if (secrets?.[secretKey])
35
+ return secrets[secretKey];
36
+ for (const envName of envNames) {
37
+ if (process.env[envName])
38
+ return process.env[envName];
39
+ }
40
+ throw new Error(`Gmail ${name} not found. Provide via options.${name}, secrets["${secretKey}"], ` +
41
+ `or one of these env vars: ${envNames.join(', ')}.`);
42
+ }
43
+ function createExtensionPack(context) {
44
+ const options = (context.options ?? {});
45
+ const clientId = resolveCredential('clientId', options.clientId, options.secrets, 'google.clientId', ['GOOGLE_CLIENT_ID', 'GMAIL_CLIENT_ID']);
46
+ const clientSecret = resolveCredential('clientSecret', options.clientSecret, options.secrets, 'google.clientSecret', ['GOOGLE_CLIENT_SECRET', 'GMAIL_CLIENT_SECRET']);
47
+ const refreshToken = resolveCredential('refreshToken', options.refreshToken, options.secrets, 'google.refreshToken', ['GOOGLE_REFRESH_TOKEN', 'GMAIL_REFRESH_TOKEN']);
48
+ const config = { clientId, clientSecret, refreshToken };
49
+ const service = new GmailService_1.GmailService(config);
50
+ const listMessagesTool = new listMessages_1.GmailListMessagesTool(service);
51
+ const readMessageTool = new readMessage_1.GmailReadMessageTool(service);
52
+ const sendMessageTool = new sendMessage_1.GmailSendMessageTool(service);
53
+ const replyMessageTool = new replyMessage_1.GmailReplyMessageTool(service);
54
+ const searchMessagesTool = new searchMessages_1.GmailSearchMessagesTool(service);
55
+ const listLabelsTool = new listLabels_1.GmailListLabelsTool(service);
56
+ const priority = options.priority ?? 50;
57
+ return {
58
+ name: '@framers/agentos-ext-email-gmail',
59
+ version: '0.1.0',
60
+ descriptors: [
61
+ { id: 'gmailListMessages', kind: 'tool', priority, payload: listMessagesTool },
62
+ { id: 'gmailReadMessage', kind: 'tool', priority, payload: readMessageTool },
63
+ { id: 'gmailSendMessage', kind: 'tool', priority, payload: sendMessageTool },
64
+ { id: 'gmailReplyMessage', kind: 'tool', priority, payload: replyMessageTool },
65
+ { id: 'gmailSearchMessages', kind: 'tool', priority, payload: searchMessagesTool },
66
+ { id: 'gmailListLabels', kind: 'tool', priority, payload: listLabelsTool },
67
+ { id: 'gmailService', kind: 'productivity', priority, payload: service },
68
+ ],
69
+ onActivate: async () => {
70
+ await service.initialize();
71
+ context.logger?.info('[Gmail] Extension activated');
72
+ },
73
+ onDeactivate: async () => {
74
+ await service.shutdown();
75
+ context.logger?.info('[Gmail] Extension deactivated');
76
+ },
77
+ };
78
+ }
79
+ exports.default = createExtensionPack;
80
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,cAAc;AACd;;;;;;;GAOG;;;AA0CH,kDA4DC;AAnGD,iDAAgE;AAsG9D,6FAtGO,2BAAY,OAsGP;AArGd,uDAA6D;AAsG3D,sGAtGO,oCAAqB,OAsGP;AArGvB,qDAA2D;AAsGzD,qGAtGO,kCAAoB,OAsGP;AArGtB,qDAA2D;AAsGzD,qGAtGO,kCAAoB,OAsGP;AArGtB,uDAA6D;AAsG3D,sGAtGO,oCAAqB,OAsGP;AArGvB,2DAAiE;AAsG/D,wGAtGO,wCAAuB,OAsGP;AArGzB,mDAAyD;AAsGvD,oGAtGO,gCAAmB,OAsGP;AA7FrB;;GAEG;AACH,SAAS,iBAAiB,CACxB,IAAY,EACZ,WAA+B,EAC/B,OAA2C,EAC3C,SAAiB,EACjB,QAAkB;IAElB,IAAI,WAAW;QAAE,OAAO,WAAW,CAAC;IAEpC,IAAI,OAAO,EAAE,CAAC,SAAS,CAAC;QAAE,OAAO,OAAO,CAAC,SAAS,CAAC,CAAC;IAEpD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;YAAE,OAAO,OAAO,CAAC,GAAG,CAAC,OAAO,CAAE,CAAC;IACzD,CAAC;IAED,MAAM,IAAI,KAAK,CACb,SAAS,IAAI,mCAAmC,IAAI,cAAc,SAAS,MAAM;QACjF,6BAA6B,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CACpD,CAAC;AACJ,CAAC;AAED,SAAgB,mBAAmB,CAAC,OAAyB;IAC3D,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