-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassistant_gmail.go
More file actions
4072 lines (3838 loc) · 122 KB
/
Copy pathassistant_gmail.go
File metadata and controls
4072 lines (3838 loc) · 122 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
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"html"
"io"
"mime"
"net"
"net/http"
"net/mail"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
)
const (
gmailAPIBaseURL = "https://gmail.googleapis.com"
gmailDeviceCodeURL = "https://oauth2.googleapis.com/device/code"
gmailTokenURL = "https://oauth2.googleapis.com/token"
gmailVerificationURL = "https://accounts.google.com/device"
gmailDefaultTimeout = 30 * time.Second
gmailTokenRefreshSlack = 60 * time.Second
gmailFetchConcurrency = 6
)
var gmailRequiredScopes = []string{
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.send",
"https://www.googleapis.com/auth/calendar",
}
type GmailCapability struct {
Config AssistantConfig
TokenPath string
CredPath string
AttachmentSaveDir string
BaseURL string
Client *http.Client
ProgressFn func(string)
AuthFn func(io.Writer) error
mu sync.Mutex
creds *gmailOAuthCredentials
token *gmailOAuthToken
email string
verified bool
}
func (g *GmailCapability) SetProgressReporter(fn func(string)) {
g.mu.Lock()
g.ProgressFn = fn
g.mu.Unlock()
}
type gmailOAuthCredentials struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret,omitempty"`
DeviceURL string `json:"device_url,omitempty"`
TokenURL string `json:"token_url,omitempty"`
Scopes []string `json:"scopes,omitempty"`
}
type gmailOAuthToken struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token,omitempty"`
TokenType string `json:"token_type,omitempty"`
Scope string `json:"scope,omitempty"`
Expiry time.Time `json:"expiry"`
}
type gmailDeviceCodeResponse struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURL string `json:"verification_url"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
type gmailTokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
ExpiresIn int `json:"expires_in"`
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
type gmailProfileResponse struct {
EmailAddress string `json:"emailAddress"`
MessagesTotal int `json:"messagesTotal"`
ThreadsTotal int `json:"threadsTotal"`
HistoryID string `json:"historyId"`
}
type gmailListMessagesResponse struct {
Messages []gmailMessageRef `json:"messages"`
NextPageToken string `json:"nextPageToken"`
ResultSizeEstimate int `json:"resultSizeEstimate"`
}
type gmailMessageRef struct {
ID string `json:"id"`
ThreadID string `json:"threadId"`
}
type gmailMessage struct {
ID string `json:"id"`
ThreadID string `json:"threadId"`
LabelIDs []string `json:"labelIds"`
Snippet string `json:"snippet"`
HistoryID string `json:"historyId"`
InternalDate string `json:"internalDate"`
Payload gmailMessagePart `json:"payload"`
SizeEstimate int64 `json:"sizeEstimate"`
}
type gmailMessagePart struct {
PartID string `json:"partId"`
MimeType string `json:"mimeType"`
Filename string `json:"filename"`
Body gmailMessageBody `json:"body"`
Headers []gmailHeader `json:"headers"`
Parts []gmailMessagePart `json:"parts"`
}
type gmailMessageBody struct {
Size int64 `json:"size"`
Data string `json:"data"`
AttachmentID string `json:"attachmentId"`
}
type gmailHeader struct {
Name string `json:"name"`
Value string `json:"value"`
}
type gmailAttachmentResponse struct {
AttachmentID string `json:"attachmentId"`
Size int64 `json:"size"`
Data string `json:"data"`
}
type gmailDraftRequest struct {
Message gmailRawMessage `json:"message"`
}
type gmailRawMessage struct {
Raw string `json:"raw"`
}
type gmailDraftResponse struct {
ID string `json:"id"`
Message gmailMessage `json:"message"`
}
type gmailSendResponse struct {
ID string `json:"id"`
}
type gmailAttachmentDownloadResult struct {
SavedPath string `json:"savedPath"`
Filename string `json:"filename"`
Bytes int64 `json:"bytes"`
Count int `json:"count,omitempty"`
MessageID string `json:"messageId,omitempty"`
ThreadID string `json:"threadId,omitempty"`
Subject string `json:"subject,omitempty"`
From string `json:"from,omitempty"`
Date time.Time `json:"date,omitempty"`
Files []gmailAttachmentDownloadFile `json:"files,omitempty"`
}
type gmailAttachmentDownloadFile struct {
MessageID string `json:"messageId,omitempty"`
ThreadID string `json:"threadId,omitempty"`
Subject string `json:"subject,omitempty"`
From string `json:"from,omitempty"`
Date time.Time `json:"date,omitempty"`
Filename string `json:"filename"`
MimeType string `json:"mimeType,omitempty"`
AttachmentID string `json:"attachmentId"`
SavedPath string `json:"savedPath"`
Bytes int64 `json:"bytes"`
}
type gmailAttachmentContentResult struct {
MessageID string `json:"messageId,omitempty"`
ThreadID string `json:"threadId,omitempty"`
Subject string `json:"subject,omitempty"`
From string `json:"from,omitempty"`
Date time.Time `json:"date,omitempty"`
Attachment AttachmentMeta `json:"attachment"`
Content AttachmentContent `json:"content"`
Preview string `json:"preview,omitempty"`
Readable bool `json:"readable"`
Error string `json:"error,omitempty"`
}
type gmailIndexedAttachmentSelection struct {
Index int
Total int
Selection gmailAttachmentSelection
}
type gmailThreadResult struct {
ThreadID string `json:"threadId"`
Subject string `json:"subject,omitempty"`
Participants []string `json:"participants,omitempty"`
MessageCount int `json:"messageCount,omitempty"`
AttachmentCount int `json:"attachmentCount,omitempty"`
EarliestDate time.Time `json:"earliestDate,omitempty"`
LatestDate time.Time `json:"latestDate,omitempty"`
Messages []NormalizedEmail `json:"messages"`
}
type gmailLabelMutationRequest struct {
AddLabelIDs []string `json:"addLabelIds,omitempty"`
RemoveLabelIDs []string `json:"removeLabelIds,omitempty"`
}
type gmailLabelMutationTarget struct {
Kind string `json:"kind"`
ThreadID string `json:"threadId,omitempty"`
MessageID string `json:"messageId,omitempty"`
Subject string `json:"subject,omitempty"`
From string `json:"from,omitempty"`
Date time.Time `json:"date,omitempty"`
MessageCount int `json:"messageCount,omitempty"`
Participants []string `json:"participants,omitempty"`
Unread bool `json:"unread,omitempty"`
}
func NewGmailCapability(cfg AssistantConfig) (*GmailCapability, error) {
tokenPath, err := gmailResolveTokenPath(cfg.GmailTokenPath)
if err != nil {
return nil, err
}
credPath, err := gmailResolveCredentialPath(cfg.GmailCredPath)
if err != nil {
return nil, err
}
cap := &GmailCapability{
Config: cfg,
TokenPath: tokenPath,
CredPath: credPath,
AttachmentSaveDir: strings.TrimSpace(cfg.AttachmentSaveDir),
BaseURL: gmailAPIBaseURL,
}
if creds, err := gmailLoadOAuthCredentials(cap.CredPath); err == nil {
cap.creds = creds
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
if token, err := gmailLoadOAuthToken(cap.TokenPath); err == nil {
cap.token = token
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
cap.Client = cap.authenticatedHTTPClient()
return cap, nil
}
func (g *GmailCapability) Name() string { return "gmail" }
func (g *GmailCapability) Description() string {
return "Read, search, and act on Gmail"
}
func (g *GmailCapability) Tools() []Tool {
return []Tool{
{Name: "gmail.status", Description: "Check whether Gmail is connected and report the connected address", ParamSchema: `{}`},
{Name: "gmail.search", Description: "Search Gmail messages with a Gmail query string or a natural-language fallback", ParamSchema: `{"type":"object","properties":{"query":{"type":"string"},"input":{"type":"string"},"max":{"type":"integer","minimum":1}}}`},
{Name: "gmail.read_message", Description: "Fetch one Gmail message and normalize its body to plain text", ParamSchema: `{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]}`},
{Name: "gmail.read_thread", Description: "Fetch a Gmail thread by thread id and normalize every message with thread context", ParamSchema: `{"type":"object","properties":{"id":{"type":"string"},"thread_id":{"type":"string"}}}`},
{Name: "gmail.fill_form", Description: "Inspect a form with the browser computer, gather answers from direct user instructions plus any available email context, and guide the user through review and browser-assisted filling. Accepts a direct form_url or an email message/thread reference.", ParamSchema: `{"type":"object","properties":{"message_id":{"type":"string"},"thread_id":{"type":"string"},"form_url":{"type":"string"}}}`},
{Name: "gmail.list_attachments", Description: "List attachment metadata for one message or a whole thread", ParamSchema: `{"type":"object","properties":{"message_id":{"type":"string"},"thread_id":{"type":"string"},"id":{"type":"string"}}}`},
{Name: "gmail.read_attachment", Description: "Read and extract text from one or more Gmail attachments without saving them to disk", ParamSchema: `{"type":"object","properties":{"message_id":{"type":"string"},"thread_id":{"type":"string"},"attachment_id":{"type":"string"},"attachment_ids":{"type":"array","items":{"type":"string"}},"filename":{"type":"string"},"filenames":{"type":"array","items":{"type":"string"}},"read_all":{"type":"boolean"},"all":{"type":"boolean"},"max_attachments":{"type":"integer","minimum":1}}}`},
{Name: "gmail.download_attachment", Description: "Download one attachment, or all matching attachments from a message or thread, to disk", ParamSchema: `{"type":"object","properties":{"message_id":{"type":"string"},"thread_id":{"type":"string"},"attachment_id":{"type":"string"},"attachment_ids":{"type":"array","items":{"type":"string"}},"filename":{"type":"string"},"filenames":{"type":"array","items":{"type":"string"}},"save_dir":{"type":"string"},"download_all":{"type":"boolean"},"all":{"type":"boolean"}}}`},
{Name: "gmail.archive_thread", Description: "Archive a Gmail thread, preferring thread context and accepting a message id when needed", ParamSchema: `{"type":"object","properties":{"thread_id":{"type":"string"},"message_id":{"type":"string"},"id":{"type":"string"}}}`},
{Name: "gmail.mark_read", Description: "Mark a Gmail thread or message as read, preferring thread context", ParamSchema: `{"type":"object","properties":{"thread_id":{"type":"string"},"message_id":{"type":"string"},"id":{"type":"string"}}}`},
{Name: "gmail.star_thread", Description: "Star a Gmail thread or message, preferring thread context", ParamSchema: `{"type":"object","properties":{"thread_id":{"type":"string"},"message_id":{"type":"string"},"id":{"type":"string"}}}`},
{Name: "gmail.extract_actions", Description: "Extract action items, deadlines, meeting requests, and entities from message text", ParamSchema: `{"type":"object","properties":{"text":{"type":"string"},"message_id":{"type":"string"}}}`},
{Name: "gmail.draft_reply", Description: "Compose a Gmail reply draft from a message or thread; send is supported behind confirmation", ParamSchema: `{"type":"object","properties":{"message_id":{"type":"string"},"thread_id":{"type":"string"},"body":{"type":"string"},"send":{"type":"boolean"},"experimental":{"type":"boolean"}},"required":["body"]}`},
{Name: "gmail.send_email", Description: "Compose a brand new Gmail email and either draft it or send it; supports file attachments and sending behind confirmation", ParamSchema: `{"type":"object","properties":{"to":{"type":"string"},"subject":{"type":"string"},"body":{"type":"string"},"attachment_path":{"type":"string"},"attachment_paths":{"type":"array","items":{"type":"string"}},"send":{"type":"boolean"}},"required":["to","subject","body"]}`},
}
}
func (g *GmailCapability) Execute(toolName string, params map[string]any) (ToolResult, error) {
switch toolName {
case "gmail.status":
return g.executeStatus()
case "gmail.search":
return g.executeSearch(params)
case "gmail.read_message":
return g.executeReadMessage(params)
case "gmail.read_thread":
return g.executeReadThread(params)
case "gmail.fill_form":
return ToolResult{Success: false, Error: "gmail.fill_form is handled by the assistant runtime"}, errors.New("gmail.fill_form is handled by the assistant runtime")
case "gmail.list_attachments":
return g.executeListAttachments(params)
case "gmail.read_attachment":
return g.executeReadAttachment(params)
case "gmail.download_attachment":
return g.executeDownloadAttachment(params)
case "gmail.archive_thread":
return g.executeArchiveThread(params)
case "gmail.mark_read":
return g.executeMarkRead(params)
case "gmail.star_thread":
return g.executeStarThread(params)
case "gmail.extract_actions":
return g.executeExtractActions(params)
case "gmail.draft_reply":
return g.executeDraftReply(params)
case "gmail.send_email":
return g.executeSendEmail(params)
default:
return ToolResult{Success: false, Error: fmt.Sprintf("unknown gmail tool %q", toolName)}, fmt.Errorf("unknown gmail tool %q", toolName)
}
}
func gmailAuth(w io.Writer, cfg AssistantConfig) error {
cap, err := NewGmailCapability(cfg)
if err != nil {
return err
}
return cap.Authenticate(w)
}
func (g *GmailCapability) Authenticate(w io.Writer) error {
if g.AuthFn != nil {
return g.AuthFn(w)
}
creds, err := g.loadOrCreateCredentials()
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("gmail OAuth client credentials are not configured; set JOT_GMAIL_CLIENT_ID and JOT_GMAIL_CLIENT_SECRET, or create %s", g.CredPath)
}
return err
}
redirectURI, authURL, state, codeVerifier, listener, codeCh, err := g.startAuthFlow(creds)
if err != nil {
return err
}
defer listener.Close()
if _, err := fmt.Fprintf(w, "open %s\n", authURL); err != nil {
return err
}
_ = openURLInBrowser(authURL)
code, returnedState, err := g.waitForAuthCode(codeCh)
if err != nil {
return err
}
if returnedState != state {
return errors.New("gmail auth state mismatch")
}
token, err := g.exchangeAuthCode(creds, code, redirectURI, codeVerifier)
if err != nil {
return err
}
g.mu.Lock()
g.token = token
g.creds = creds
g.email = ""
g.verified = true
g.mu.Unlock()
if err := gmailSaveOAuthCredentials(g.CredPath, creds); err != nil {
return err
}
if err := gmailSaveOAuthToken(g.TokenPath, token); err != nil {
return err
}
g.Client = g.authenticatedHTTPClient()
profile, err := g.profile()
if err == nil {
g.mu.Lock()
g.email = profile.EmailAddress
g.mu.Unlock()
if profile.EmailAddress != "" {
_, _ = fmt.Fprintf(w, "connected as %s\n", profile.EmailAddress)
}
return nil
}
_, _ = fmt.Fprintln(w, "connected")
return nil
}
func (g *GmailCapability) startAuthFlow(creds *gmailOAuthCredentials) (string, string, string, string, net.Listener, chan authCallbackResult, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return "", "", "", "", nil, nil, err
}
redirectURI := fmt.Sprintf("http://127.0.0.1:%d/oauth2callback", listener.Addr().(*net.TCPAddr).Port)
state, err := gmailRandomToken(24)
if err != nil {
listener.Close()
return "", "", "", "", nil, nil, err
}
codeVerifier, err := gmailRandomToken(48)
if err != nil {
listener.Close()
return "", "", "", "", nil, nil, err
}
sum := sha256.Sum256([]byte(codeVerifier))
codeChallenge := base64.RawURLEncoding.EncodeToString(sum[:])
query := url.Values{}
query.Set("client_id", creds.ClientID)
query.Set("redirect_uri", redirectURI)
query.Set("response_type", "code")
query.Set("scope", strings.Join(creds.ScopesOrDefault(), " "))
query.Set("access_type", "offline")
query.Set("prompt", "consent")
query.Set("include_granted_scopes", "true")
query.Set("state", state)
query.Set("code_challenge", codeChallenge)
query.Set("code_challenge_method", "S256")
authURL := "https://accounts.google.com/o/oauth2/v2/auth?" + query.Encode()
codeCh := make(chan authCallbackResult, 1)
mux := http.NewServeMux()
server := &http.Server{Handler: mux}
mux.HandleFunc("/oauth2callback", func(w http.ResponseWriter, r *http.Request) {
result := authCallbackResult{
Code: strings.TrimSpace(r.URL.Query().Get("code")),
State: strings.TrimSpace(r.URL.Query().Get("state")),
Error: strings.TrimSpace(r.URL.Query().Get("error")),
}
select {
case codeCh <- result:
default:
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if result.Error != "" {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, "<html><body><p>Gmail authorization failed. You can return to Jot.</p></body></html>")
return
}
_, _ = io.WriteString(w, "<html><body><p>Gmail connected. You can return to Jot.</p></body></html>")
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = server.Shutdown(ctx)
}()
})
go func() {
_ = server.Serve(listener)
}()
return redirectURI, authURL, state, codeVerifier, listener, codeCh, nil
}
type authCallbackResult struct {
Code string
State string
Error string
}
func (g *GmailCapability) waitForAuthCode(codeCh <-chan authCallbackResult) (string, string, error) {
select {
case result := <-codeCh:
if result.Error != "" {
return "", "", fmt.Errorf("gmail authorization failed: %s", result.Error)
}
if strings.TrimSpace(result.Code) == "" {
return "", "", errors.New("gmail authorization did not return a code")
}
return result.Code, result.State, nil
case <-time.After(5 * time.Minute):
return "", "", errors.New("timed out waiting for gmail authorization")
}
}
func (g *GmailCapability) exchangeAuthCode(creds *gmailOAuthCredentials, code string, redirectURI string, codeVerifier string) (*gmailOAuthToken, error) {
form := url.Values{}
form.Set("client_id", creds.ClientID)
form.Set("code", code)
form.Set("code_verifier", codeVerifier)
form.Set("grant_type", "authorization_code")
form.Set("redirect_uri", redirectURI)
if strings.TrimSpace(creds.ClientSecret) != "" {
form.Set("client_secret", creds.ClientSecret)
}
endpoint := creds.TokenURL
if endpoint == "" {
endpoint = gmailTokenURL
}
resp, err := http.PostForm(endpoint, form)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var tokenResp gmailTokenResponse
if err := gmailDecodeResponse(resp, &tokenResp); err != nil {
return nil, err
}
if tokenResp.AccessToken == "" {
return nil, errors.New("authorization code exchange did not return an access token")
}
return &gmailOAuthToken{
AccessToken: tokenResp.AccessToken,
RefreshToken: tokenResp.RefreshToken,
TokenType: tokenResp.TokenType,
Scope: tokenResp.Scope,
Expiry: time.Now().Add(time.Duration(max(tokenResp.ExpiresIn, 0)) * time.Second),
}, nil
}
func gmailRandomToken(byteCount int) (string, error) {
if byteCount <= 0 {
byteCount = 32
}
buf := make([]byte, byteCount)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(buf), nil
}
func (g *GmailCapability) executeStatus() (ToolResult, error) {
profile, err := g.profile()
if err != nil {
return ToolResult{
Success: true,
Data: map[string]any{
"connected": false,
"email": "",
},
Text: "gmail: not connected",
}, nil
}
return ToolResult{
Success: true,
Data: map[string]any{
"connected": true,
"email": profile.EmailAddress,
"sendReady": g.sendScopeAvailable(),
"tokenScope": g.tokenScopeSummary(),
},
Text: fmt.Sprintf("gmail: connected (%s)", profile.EmailAddress),
}, nil
}
func (g *GmailCapability) executeSearch(params map[string]any) (ToolResult, error) {
query := paramString(params, "query", "q", "input")
if strings.TrimSpace(query) == "" {
query = mapNLToGmailQuery(paramString(params, "input"))
}
query = strings.TrimSpace(query)
if query == "" {
return ToolResult{Success: false, Error: "query must be provided"}, errors.New("query must be provided")
}
maxResults := paramInt(params, 10, "max", "limit")
if maxResults <= 0 {
maxResults = 10
}
if maxResults > 50 {
maxResults = 50
}
messages, err := g.searchMessages(query, maxResults)
if err != nil {
return ToolResult{Success: false, Error: err.Error()}, err
}
summaries := make([]string, 0, len(messages))
for i, msg := range messages {
summaries = append(summaries, fmt.Sprintf("%d. %s", i+1, gmailOneLineSummary(msg)))
}
return ToolResult{
Success: true,
Data: messages,
Text: strings.Join(summaries, "\n"),
}, nil
}
func (g *GmailCapability) executeReadMessage(params map[string]any) (ToolResult, error) {
id := paramString(params, "id", "message_id")
if id == "" {
return ToolResult{Success: false, Error: "id must be provided"}, errors.New("id must be provided")
}
msg, err := g.readMessage(id)
if err != nil {
return ToolResult{Success: false, Error: err.Error()}, err
}
return ToolResult{Success: true, Data: msg, Text: gmailOneLineSummary(msg)}, nil
}
func (g *GmailCapability) executeReadThread(params map[string]any) (ToolResult, error) {
id := paramString(params, "id", "thread_id")
if id == "" {
return ToolResult{Success: false, Error: "id must be provided"}, errors.New("id must be provided")
}
thread, err := g.readThread(id)
if err != nil {
return ToolResult{Success: false, Error: err.Error()}, err
}
return ToolResult{
Success: true,
Data: thread,
Text: gmailThreadSummaryText(thread),
}, nil
}
func (g *GmailCapability) executeListAttachments(params map[string]any) (ToolResult, error) {
messageID := paramString(params, "message_id", "id")
threadID := paramString(params, "thread_id")
attachments, err := g.listAttachments(messageID, threadID)
if err != nil {
return ToolResult{Success: false, Error: err.Error()}, err
}
return ToolResult{
Success: true,
Data: attachments,
Text: gmailAttachmentListSummary(attachments),
}, nil
}
func (g *GmailCapability) executeReadAttachment(params map[string]any) (ToolResult, error) {
messageID := paramString(params, "message_id", "id")
threadID := paramString(params, "thread_id")
attachmentID := paramString(params, "attachment_id", "attachmentId")
attachmentIDs := paramStringSlice(params, "attachment_ids", "attachmentIds", "ids")
filename := paramString(params, "filename")
filenames := paramStringSlice(params, "filenames", "names")
readAll := paramBool(params, "read_all", "all")
maxAttachments := paramInt(params, 6, "max_attachments", "max", "limit")
if maxAttachments <= 0 {
maxAttachments = 6
}
if attachmentID == "" && len(attachmentIDs) == 0 && filename == "" && len(filenames) == 0 {
readAll = true
}
selections, err := g.selectAttachmentSelections(messageID, threadID, attachmentID, attachmentIDs, filename, filenames, readAll)
if err != nil {
return ToolResult{Success: false, Error: err.Error()}, err
}
truncated := false
if maxAttachments > 0 && len(selections) > maxAttachments {
selections = selections[:maxAttachments]
truncated = true
}
indexed := make([]gmailIndexedAttachmentSelection, 0, len(selections))
for i, selection := range selections {
indexed = append(indexed, gmailIndexedAttachmentSelection{
Index: i + 1,
Total: len(selections),
Selection: selection,
})
}
results := make([]gmailAttachmentContentResult, 0, len(selections))
readable := 0
results = gmailParallelMap(indexed, gmailFetchConcurrency, func(item gmailIndexedAttachmentSelection) (gmailAttachmentContentResult, bool) {
selection := item.Selection
g.reportProgress(gmailAttachmentProgressLabel(item))
entry := gmailAttachmentContentResult{
MessageID: selection.MessageID,
ThreadID: selection.ThreadID,
Subject: selection.Subject,
From: selection.From,
Date: selection.Date,
Attachment: selection.Attachment,
}
data, err := g.downloadAttachmentData(selection.MessageID, selection.Attachment.AttachmentID)
if err != nil {
entry.Error = err.Error()
g.reportProgress(gmailAttachmentFinishedLabel(item, err))
return entry, true
}
content, err := g.readAttachmentContentSmart(data, selection.Attachment)
if err != nil {
entry.Error = err.Error()
g.reportProgress(gmailAttachmentFinishedLabel(item, err))
return entry, true
}
entry.Content = content
entry.Preview = truncateForPrompt(content.Text, 600)
entry.Readable = strings.TrimSpace(content.Text) != "" || len(content.Tables) > 0
g.reportProgress(gmailAttachmentFinishedLabel(item, nil))
return entry, true
})
for _, result := range results {
if result.Readable {
readable++
}
}
text := gmailAttachmentReadSummary(results, truncated)
return ToolResult{
Success: true,
Data: map[string]any{
"attachments": results,
"count": len(results),
"readable": readable,
"truncated": truncated,
},
Text: text,
}, nil
}
func (g *GmailCapability) reportProgress(line string) {
g.mu.Lock()
fn := g.ProgressFn
g.mu.Unlock()
if fn != nil {
fn(line)
}
}
func gmailAttachmentProgressLabel(item gmailIndexedAttachmentSelection) string {
name := strings.TrimSpace(item.Selection.Attachment.Filename)
if name == "" {
name = strings.TrimSpace(item.Selection.Subject)
}
if name == "" {
name = "attachment"
}
return fmt.Sprintf("reading attachment %d/%d: %s...", item.Index, item.Total, name)
}
func gmailAttachmentFinishedLabel(item gmailIndexedAttachmentSelection, err error) string {
name := strings.TrimSpace(item.Selection.Attachment.Filename)
if name == "" {
name = strings.TrimSpace(item.Selection.Subject)
}
if name == "" {
name = "attachment"
}
if err != nil {
return fmt.Sprintf("finished attachment %d/%d: %s (error)", item.Index, item.Total, name)
}
return fmt.Sprintf("✓ finished attachment %d/%d: %s", item.Index, item.Total, name)
}
func (g *GmailCapability) readAttachmentContentSmart(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
content, err := ReadAttachmentContent(data, meta)
if !gmailAttachmentNeedsOCRFallback(content, meta) && (strings.TrimSpace(content.Text) != "" || len(content.Tables) > 0) {
if content.Metadata == nil {
content.Metadata = map[string]string{}
}
if err != nil && content.Metadata["source"] == "" {
content.Metadata["source"] = "primary reader returned partial content"
}
return content, nil
}
if ocrContent, ocrErr := gmailOCRAttachmentContent(data, meta); ocrErr == nil && (strings.TrimSpace(ocrContent.Text) != "" || len(ocrContent.Tables) > 0) {
if content.Metadata == nil {
content.Metadata = map[string]string{}
}
for k, v := range ocrContent.Metadata {
content.Metadata[k] = v
}
content.Text = strings.TrimSpace(ocrContent.Text)
content.Tables = append(content.Tables, ocrContent.Tables...)
content.Warnings = append(content.Warnings, ocrContent.Warnings...)
if len(content.Warnings) == 0 {
content.Warnings = append(content.Warnings, "ocr fallback used")
}
return content, nil
}
if err != nil {
return content, err
}
return content, nil
}
func gmailAttachmentNeedsOCRFallback(content AttachmentContent, meta AttachmentMeta) bool {
text := strings.TrimSpace(content.Text)
if text == "" && len(content.Tables) == 0 {
return true
}
if !gmailAttachmentLooksLikeOCRCandidate(meta) {
return false
}
if len(content.Tables) > 0 {
return false
}
if strings.EqualFold(text, "Image attachment") {
return true
}
if content.Metadata != nil && strings.EqualFold(content.Metadata["recovered_text"], "yes") {
return false
}
for _, warning := range content.Warnings {
lower := strings.ToLower(strings.TrimSpace(warning))
if strings.Contains(lower, "no embedded text was recovered") || strings.Contains(lower, "best-effort only") {
return true
}
}
return false
}
func gmailOCRAttachmentContent(data []byte, meta AttachmentMeta) (AttachmentContent, error) {
if !gmailAttachmentLooksLikeOCRCandidate(meta) {
return AttachmentContent{}, errors.New("attachment is not an OCR candidate")
}
tempDir, err := os.MkdirTemp("", "jot-ocr-*")
if err != nil {
return AttachmentContent{}, err
}
defer os.RemoveAll(tempDir)
ext := strings.ToLower(filepath.Ext(strings.TrimSpace(meta.Filename)))
if ext == "" {
ext = ".bin"
}
inputPath := filepath.Join(tempDir, "input"+ext)
if err := os.WriteFile(inputPath, data, 0o600); err != nil {
return AttachmentContent{}, err
}
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
ocrText, ocrWarnings, ocrMeta, ocrErr := gmailRunBestAvailableOCR(ctx, inputPath, tempDir)
if ocrErr == nil && strings.TrimSpace(ocrText) != "" {
return AttachmentContent{
Text: strings.TrimSpace(ocrText),
Metadata: ocrMeta,
Warnings: append([]string(nil), ocrWarnings...),
}, nil
}
if !gmailAttachmentLooksLikePdf(meta) {
if ocrErr != nil {
return AttachmentContent{}, ocrErr
}
return AttachmentContent{}, errors.New("ocr returned no text")
}
if convertedPath, convWarnings, convErr := gmailPreparePdfForOCR(ctx, inputPath, tempDir); convErr == nil && convertedPath != "" {
ocrText, ocrWarnings, ocrMeta, ocrErr = gmailRunBestAvailableOCR(ctx, convertedPath, tempDir)
if ocrErr == nil && strings.TrimSpace(ocrText) != "" {
warnings := append([]string(nil), convWarnings...)
warnings = append(warnings, ocrWarnings...)
metaMap := copyStringMap(ocrMeta)
if metaMap == nil {
metaMap = map[string]string{}
}
metaMap["mode"] = "pdf-converted"
return AttachmentContent{
Text: strings.TrimSpace(ocrText),
Metadata: metaMap,
Warnings: warnings,
}, nil
}
if ocrErr == nil {
ocrErr = errors.New("ocr returned no text")
}
if len(convWarnings) > 0 {
ocrWarnings = append(convWarnings, ocrWarnings...)
}
}
if ocrErr != nil {
return AttachmentContent{}, ocrErr
}
return AttachmentContent{}, errors.New("ocr returned no text")
}
func gmailRunBestAvailableOCR(ctx context.Context, inputPath, tempDir string) (string, []string, map[string]string, error) {
var errs []string
if tesseractPath, err := exec.LookPath("tesseract"); err == nil {
if text, warnings, ocrErr := gmailRunTesseractOCR(ctx, tesseractPath, inputPath, tempDir); ocrErr == nil && strings.TrimSpace(text) != "" {
return text, warnings, map[string]string{
"type": "ocr/tesseract",
"tool": "tesseract",
"mode": "direct",
}, nil
} else if ocrErr != nil {
errs = append(errs, ocrErr.Error())
}
} else if strings.TrimSpace(err.Error()) != "" {
errs = append(errs, err.Error())
}
if text, warnings, ocrErr := gmailRunWindowsOCR(ctx, inputPath, tempDir); ocrErr == nil && strings.TrimSpace(text) != "" {
return text, warnings, map[string]string{
"type": "ocr/windows",
"tool": "windows-ocr",
"mode": "direct",
}, nil
} else if ocrErr != nil {
errs = append(errs, ocrErr.Error())
}
if len(errs) == 0 {
errs = append(errs, "no OCR engine produced text")
}
return "", nil, nil, errors.New(strings.Join(uniqueTrimmedStrings(errs), "; "))
}
func gmailAttachmentLooksLikeOCRCandidate(meta AttachmentMeta) bool {
if gmailAttachmentLooksLikeImage(meta) {
return true
}
if gmailAttachmentLooksLikePdf(meta) {
return true
}
name := strings.ToLower(strings.TrimSpace(meta.Filename))
for _, token := range []string{"scan", "photo", "image", "screenshot", "passport", "id", "visa", "permit"} {
if strings.Contains(name, token) {
return true
}
}
return false
}
func gmailAttachmentLooksLikePdf(meta AttachmentMeta) bool {
name := strings.ToLower(strings.TrimSpace(meta.Filename))
mime := strings.ToLower(strings.TrimSpace(meta.MimeType))
if strings.Contains(mime, "pdf") {
return true
}
return strings.HasSuffix(name, ".pdf")
}
func gmailRunTesseractOCR(ctx context.Context, tesseractPath, inputPath, tempDir string) (string, []string, error) {
outputBase := filepath.Join(tempDir, "ocr-output")
cmd := exec.CommandContext(ctx, tesseractPath, inputPath, outputBase, "--psm", "6")
output, err := cmd.CombinedOutput()
if err != nil {
return "", nil, fmt.Errorf("tesseract OCR failed: %w: %s", err, strings.TrimSpace(string(output)))
}
text, err := os.ReadFile(outputBase + ".txt")
if err != nil {
return "", nil, err
}
return string(text), []string{"ocr fallback used"}, nil
}
func gmailRunWindowsOCR(ctx context.Context, inputPath, tempDir string) (string, []string, error) {
if runtime.GOOS != "windows" {
return "", nil, errors.New("windows ocr is only available on windows")
}
powershellPath, err := exec.LookPath("powershell")
if err != nil {
return "", nil, err
}
scriptPath := filepath.Join(tempDir, "windows-ocr.ps1")
outputPath := filepath.Join(tempDir, "windows-ocr.txt")
if err := os.WriteFile(scriptPath, []byte(gmailWindowsOCRScript()), 0o600); err != nil {
return "", nil, err
}
cmd := exec.CommandContext(ctx, powershellPath,
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy", "Bypass",
"-File", scriptPath,
"-ImagePath", inputPath,
"-OutputPath", outputPath,
)
output, err := cmd.CombinedOutput()
if err != nil {
return "", nil, fmt.Errorf("windows OCR failed: %w: %s", err, strings.TrimSpace(string(output)))
}
text, err := os.ReadFile(outputPath)
if err != nil {
return "", nil, err
}
return string(text), []string{"ocr fallback used", "windows ocr used"}, nil
}
func gmailWindowsOCRScript() string {
return strings.TrimSpace(`
param(
[Parameter(Mandatory = $true)][string]$ImagePath,
[Parameter(Mandatory = $true)][string]$OutputPath
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Runtime.WindowsRuntime | Out-Null
[void][Windows.Storage.StorageFile, Windows.Storage, ContentType=WindowsRuntime]
[void][Windows.Storage.FileAccessMode, Windows.Storage, ContentType=WindowsRuntime]
[void][Windows.Storage.Streams.IRandomAccessStream, Windows.Storage.Streams, ContentType=WindowsRuntime]
[void][Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType=WindowsRuntime]
[void][Windows.Graphics.Imaging.SoftwareBitmap, Windows.Foundation, ContentType=WindowsRuntime]
[void][Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType=WindowsRuntime]
[void][Windows.Media.Ocr.OcrResult, Windows.Foundation, ContentType=WindowsRuntime]