-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcody.el
2544 lines (2294 loc) · 108 KB
/
cody.el
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
;; cody.el --- Sourcegraph Cody in Emacs -*- lexical-binding: t; -*-
;; Copyright (C) 2023 Sourcegraph, Inc.
;; Version: 0.2.0
;; Author: Keegan Carruthers-Smith <[email protected]>
;; Maintainer: Steve Yegge <[email protected]>
;; URL: https://github.com/sourcegraph/emacs-cody
;; Package-Requires: ((emacs "26.3") (jsonrpc "1.0.16") (uuidgen "20240201.2318"))
;; Keywords: completion convenience languages programming tools
;; This file is not part of GNU Emacs.
;;; Commentary:
;;
;; See ./README.org for installation information.
;;
;; `M-x cody-login` to start using Cody.
;;; Code:
(eval-when-compile (require 'cl-lib))
(eval-and-compile (require 'eieio-base))
(require 'auth-source)
(require 'jsonrpc)
(require 'uuidgen)
(require 'project)
(require 'ansi-color)
(require 'cody-diff)
(require 'cody-repo-util)
(require 'cody-dashboard)
;;; Custom variables.
(defgroup cody nil
"Sourcegraph Cody settings."
:group 'programming
:prefix "cody-")
(defcustom cody-telemetry-enable-p nil
"Non-nil to allow anonymized event/usage telemetry.
This information is used by Sourcegraph to improve Cody."
:group 'cody
:type 'boolean)
(defcustom cody-gc-workspace-timeout-sec 15 ;; 300
"Time to wait before garbage collecting an unused workspace."
:type 'integer
:group 'cody)
(defcustom cody--internal-anonymized-uuid nil
"A generated ID for telemetry, to tie usage events together.
This is generated and cached on first use, if telemetry is enabled."
:type 'string
:group 'cody)
(defgroup cody-completions nil
"Code autocompletion options."
:group 'cody
:prefix "cody-completion-"
:prefix "cody-completions-")
(defcustom cody-completions-auto-trigger-p t
"Non-nil to have Cody prompt with suggestions automatically.
Completion suggestions will appear after you stop typing for a while,
if any suggestions are available. Set this to nil if you prefer to
use manual completion triggering with `cody-request-completion'."
:group 'cody-completions
:type 'boolean)
(defcustom cody-completions-display-marker-p nil
"Non-nil to display completion markers in the minibuffer.
This helps distinguish Cody's completions from other packages."
:group 'cody-completions
:type 'boolean)
(defface cody-completion-face
'((t :inherit shadow
:slant italic
;;:background "#ffffcd" ; uncomment for debugging overlay spans
:foreground "#4c8da3"))
"Face for Cody completion overlay."
:group 'cody-completions)
(defcustom cody-completions-enable-cycling-p t
"Non-nil to allow cycling among alternative completion suggestions.
These are not always available, but when they are, you can cycle
between them with `cody-completion-cycle-next' and
`cody-completion-cycle-prev'. When nil, cycling is completely
disabled, and only the first option returned by the server is
ever displayed or interactible."
:group 'cody
:type 'boolean)
(defcustom cody-completions-cycling-help-p t
"Non-nil to show a message in the minibuffer for cycling completions.
If non-nil, and multiple completion suggestions are returned from the
server, it will show how many are available and how to cycle them.
If nil, no messages are printed when cycling is available or used."
:group 'cody
:type 'boolean)
(defcustom cody-default-branch-name "main"
"Default branch name for the current project."
:group 'cody
:type 'string)
(defcustom cody-remote-url-replacements ""
"Whitespace-separated pairs of replacements for repo URLs."
:group 'cody
:type 'string)
(defgroup cody-dev nil
"Cody developer/contributor configuration settings."
:group 'cody
:prefix "cody-dev-")
(defcustom cody-node-executable nil
"Hardwired path to the nodejs binary to use for Cody.
If nil, Cody will search for node using variable `exec-path'."
:group 'cody
:type 'string)
(defcustom cody-node-min-version "20.4.0"
"The minimum required version of Node.js."
:group 'cody-dev
:type 'string)
(defcustom cody-max-workspaces 1
"Maximum number of active workspace connections Cody will create.
Each workspace connection spins up its own Cody agent subprocess.
You can view all Cody workspaces with `cody-dashboard'."
:type 'number
:group 'cody-dev)
(defcustom cody-use-remote-agent nil
"Non-nil to connect to an agent running on `cody--dev-remote-agent-port`.
This is a setting for contributors to Cody-Emacs."
:group 'cody-dev
:type 'boolean)
(defcustom cody-remote-agent-port 3113
"The port on which to attach to a remote Agent.
The remote Agent is typically started by an IDE such as VS Code,
and enables you to set breakpoints on both sides of the protocol."
:group 'cody-dev
:type 'number)
(defcustom cody-enable-agent-debug nil
"Non-nil to enable debugging in the agent.
Sends this flag as part of the agent extension configuration."
:group 'cody-dev
:type 'boolean)
(defcustom cody-enable-agent-debug-verbose nil
"Non-nil to enable verbose debugging in the agent.
Sends this flag as part of the agent extension configuration."
:group 'cody-dev
:type 'boolean)
(defcustom cody-enable-event-tracing nil
"Non-nil to enable every agent to have an events buffer.
The events buffer can be reached via `cody-dashboard' and has a
trace of all events that are sent over the jsonrpc channel."
:group 'cody-dev
:type 'boolean)
(defcustom cody-panic-on-doc-desync nil
"Non-nil to ask the Agent to panic if we discover it is desynced.
De-syncing is when the Agent's copy of a document is out of sync with
the actual document in Emacs.
Setting this custom variable to non-nil, which should only be done in
development, sends extra metadata along with document changes, which the
Agent will compare against. Performance will be heavily impacted, with
the entire buffer being sent to Agent on every small change."
:group 'cody-dev
:type 'boolean)
(defclass cody-completion-item ()
((insertText :initarg :insertText
:initform nil
:type (or null string)
:accessor cody--completion-item-original-text
:documentation "The original suggested text.")
(range :initarg :range
:initform nil
:type (or null list)
:accessor cody--completion-item-range
:documentation "The range where the completion applies."))
"Represents a single alternative/suggestion in a completion response.")
(defclass cody-completion ()
((items :initarg :items
:initform nil
:type (or null vector)
:accessor cody--completion-items
:documentation "Vector of `cody-completion-item' instances.")
(completionEvent :initarg :completionEvent
:initform nil
:type (or null list)
:accessor cody--completion-event
:documentation "Event associated with the completion.")
(response :initarg :response
:initform nil
:type (or null list)
:accessor cody--completion-response
:documentation "Top-level jsonrpc protocol response object.")
(-current-item-index :initform 0
:type integer
:accessor cody--current-item-index
:documentation "Currently displayed alternative."))
"Represents the entire JSON-RPC response for a requested completion.")
(cl-defmethod cody--num-items ((cc cody-completion))
"Return the total number of alternative items for the completion CC."
(length (oref cc items)))
(cl-defmethod cody--multiple-items-p ((cc cody-completion))
"Return non-nil if the completion CC has two or more completion items."
(> (cody--num-items cc) 1))
(cl-defmethod cody--current-item ((cc cody-completion))
"Return the currently displayed variable `cody-completion-item', or nil.
Argument CC is the completion object."
(ignore-errors
(aref (cody--completion-items cc) (cody--current-item-index cc))))
(cl-defmethod cody--completion-text ((cc cody-completion))
"Retrieve the text of the selected variable `cody-completion-item'.
Argument CC is the completion object."
(when-let ((item (cody--current-item cc)))
(oref item insertText)))
(cl-defmethod cody-set-completion-event-prop ((cc cody-completion) prop value)
"Update the completion event in CC, setting PROP to VALUE."
(oset cc completionEvent
(plist-put (oref cc completionEvent) prop value)))
(cl-defmethod cody-completion-event-prop ((cc cody-completion) prop)
"Retrieve PROP from the completion event of CC."
(plist-get (oref cc completionEvent) prop))
(defclass cody-llm-site-configuration ()
((chatModel :initarg :chatModel
:initform nil
:type (or null string)
:accessor cody--llm-chat-model
:documentation "Chat model.")
(chatModelMaxTokens :initarg :chatModelMaxTokens
:initform nil
:type (or null integer)
:accessor cody--llm-chat-model-max-tokens
:documentation "Chat model max tokens.")
(fastChatModel :initarg :fastChatModel
:initform nil
:type (or null string)
:accessor cody--llm-fast-chat-model
:documentation "Fast chat model.")
(fastChatModelMaxTokens :initarg :fastChatModelMaxTokens
:initform nil
:type (or null integer)
:accessor cody--llm-fast-chat-model-max-tokens
:documentation "Fast chat model max tokens.")
(completionModel :initarg :completionModel
:initform nil
:type (or null string)
:accessor cody--llm-completion-model
:documentation "Completion model.")
(completionModelMaxTokens :initarg :completionModelMaxTokens
:initform nil
:type (or null integer)
:accessor cody--llm-completion-model-max-tokens
:documentation "Completion model max tokens.")
(provider :initarg :provider
:initform nil
:type (or null string)
:accessor cody--llm-provider
:documentation "Provider.")
(smartContextWindow :initarg :smartContextWindow
:initform nil
:type (or null boolean)
:accessor cody--llm-smart-context-window
:documentation "Smart context window."))
"Class representing Cody LLM site configuration.")
;; Update the cody-auth-status class
(defclass cody-auth-status ()
((username :initarg :username
:initform ""
:type string
:accessor cody--auth-status-username
:documentation "The username of the authenticated user.")
(endpoint :initarg :endpoint
:initform nil
:type (or null string)
:accessor cody--auth-status-endpoint
:documentation "The endpoint used for authentication.")
(isDotCom :initarg :isDotCom
:initform nil
:type boolean
:accessor cody--auth-status-is-dotcom
:documentation "Whether the server is dot-com.")
(isLoggedIn :initarg :isLoggedIn
:initform nil
:type boolean
:accessor cody--auth-status-is-logged-in
:documentation "Whether the user is logged in.")
(showInvalidAccessTokenError :initarg :showInvalidAccessTokenError
:initform nil
:type boolean
:accessor cody--auth-status-show-invalid-token-error
:documentation "Show invalid access token error.")
(authenticated :initarg :authenticated
:initform nil
:type boolean
:accessor cody--auth-status-authenticated
:documentation "Whether the user is authenticated.")
(hasVerifiedEmail :initarg :hasVerifiedEmail
:initform nil
:type boolean
:accessor cody--auth-status-has-verified-email
:documentation "Whether the user has a verified email.")
(requiresVerifiedEmail :initarg :requiresVerifiedEmail
:initform nil
:type boolean
:accessor cody--auth-status-requires-verified-email
:documentation "Whether user requires a verified email.")
(siteHasCodyEnabled :initarg :siteHasCodyEnabled
:initform nil
:type boolean
:accessor cody--auth-status-site-has-cody-enabled
:documentation "Whether the site has Cody enabled.")
(siteVersion :initarg :siteVersion
:initform ""
:type string
:accessor cody--auth-status-site-version
:documentation "The version of the site.")
(codyApiVersion :initarg :codyApiVersion
:initform 1
:type integer
:accessor cody--auth-status-cody-api-version
:documentation "The API version of Cody.")
(configOverwrites :initarg :configOverwrites
:initform nil
:type (or null cody-llm-site-configuration)
:accessor cody--auth-status-config-overwrites
:documentation "LLM configuration overwrites.")
(showNetworkError :initarg :showNetworkError
:initform nil
:type (or null boolean)
:accessor cody--auth-status-show-network-error
:documentation "Show network error status.")
(primaryEmail :initarg :primaryEmail
:initform ""
:type string
:accessor cody--auth-status-primary-email
:documentation "The primary email of the authenticated user.")
(displayName :initarg :displayName
:initform nil
:type (or null string)
:accessor cody--auth-status-display-name
:documentation "The display name of the authenticated user.")
(avatarURL :initarg :avatarURL
:initform ""
:type string
:accessor cody--auth-status-avatar-url
:documentation "The avatar URL of the authenticated user.")
(userCanUpgrade :initarg :userCanUpgrade
:initform nil
:type boolean
:accessor cody--auth-status-user-can-upgrade
:documentation "Whether the user can upgrade their plan."))
"Class representing authentication status.")
(defclass cody-server-info ()
((name :initarg :name
:initform ""
:type string
:accessor cody--server-info-name
:documentation "The name of the server.")
(authenticated :initarg :authenticated
:initform nil
:type (or null boolean)
:accessor cody--server-info-authenticated
:documentation "Whether the server is authenticated.")
(codyEnabled :initarg :codyEnabled
:initform nil
:type (or null boolean)
:accessor cody--server-info-cody-enabled
:documentation "Whether Cody is enabled on the server.")
(codyVersion :initarg :codyVersion
:initform nil
:type (or null string)
:accessor cody--server-info-cody-version
:documentation "The version of Cody on the server.")
(authStatus :initarg :authStatus
:initform nil
:type (or null cody-auth-status)
:accessor cody--server-info-auth-status
:documentation "The authentication status of the server."))
"Class representing server information.")
(defconst cody--dotcom-url "https://sourcegraph.com/")
(defconst cody--cody-agent
(file-name-concat (file-name-directory (or load-file-name
(buffer-file-name)))
"dist" "index.js")
"Path to bundled cody agent.")
;; It might seem odd to have a separate Node process for each workspace,
;; but it makes things more flexible in general; e.g. integration testing
;; without interfering with your normal Cody session, or hitting dev backends.
;; Other Cody clients (e.g. JetBrains) also have per-workspace agents.
(cl-defstruct cody-workspace
"Data associated with a workspace root and its connection.
Each Cody-enabled workspace has a separate Agent instance."
(root (getenv "HOME") :type string)
(uri (cody--uri-for (getenv "HOME")) :type string)
(connection nil :type (or null jsonrpc-process-connection))
(server-info nil :type (or null cody-server-info))
;; Possible values are: `unconnected', `connected', `error', 'closed'.
(status 'unconnected :type symbol)
(error nil :type (or null string)) ; last error encountered
(events-buffer nil :type (or null buffer))
(stderr-buffer nil :type (or null buffer)))
(defvar cody-workspaces (make-hash-table :test 'equal)
"Hash table mapping workspace root uris to `cody-workspace' structs.
Workspace roots are typically repo roots.")
(defvar cody--node-version-status nil
"Non-nil after `cody--check-node-version' is called.
The node version is only checked on Cody startup.
You can call `cody-restart' to force it to re-check the version.")
(defvar cody--unit-testing-p nil
"Set to non-nil during unit testing.
When testing, all calls to the agent are diverted.")
(defvar cody--integration-testing-p nil
"Set to non-nil during integration tests.
When testing, the calls go through to the LLM.")
(defvar cody--sourcegraph-host "sourcegraph.com"
"Sourcegraph host.")
(defvar cody--access-token nil
"Access token for `cody--sourcegraph-host'.")
(defconst cody-log-buffer-name "*cody-log*"
"Cody log messages.
This log is shared across all agent connections.")
(defvar cody-prefix-map nil "Map for bindings with Cody's prefix.")
(define-prefix-command 'cody-prefix-map)
(define-key cody-prefix-map (kbd "c") 'cody-request-completion)
(define-key cody-prefix-map (kbd "x") 'cody-mode) ; toggle cody-mode off for buffer
(defvar cody-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-c /") cody-prefix-map)
(define-key map (kbd "M-\\") 'cody-request-completion) ; for IntelliJ users
(define-key map (kbd "TAB") 'cody-completion-accept-key-dispatch)
(define-key map (kbd "C-g") 'cody-quit-key-dispatch)
(define-key map (kbd "ESC ESC ESC") 'cody-quit-key-dispatch)
(when cody-completions-enable-cycling-p
(define-key map (kbd "M-n") 'cody-completion-cycle-next-key-dispatch)
(define-key map (kbd "M-p") 'cody-completion-cycle-prev-key-dispatch))
map)
"Keymap for `cody-mode'.")
(defvar cody-completion-map (make-sparse-keymap)
"Keymap for cody completion overlay.")
(defconst cody--mode-hooks
'((before-change-functions . cody--before-change)
(after-change-functions . cody--after-change)
(window-selection-change-functions . cody--handle-focus-changed)
(window-buffer-change-functions . cody--handle-focus-changed)
(post-command-hook . cody--post-command)
(kill-buffer-hook . cody--kill-buffer-function)
(activate-mark-hook . cody--handle-selection-change)
(deactivate-mark-hook . cody--handle-selection-change)
(after-revert-hook . cody--after-revert))
"List of buffer-local hooks that Cody registers on in `cody-mode`.
These hooks enable it to keep buffers and selections synced
with the Cody Agent.")
(defvar cody--overlay-deltas nil
"List of overlays for Cody current completion suggestion.")
(defvar cody--completion nil
"Most recent completion response object from the Cody Agent.
This is an instance of a variable `cody-completion' object.
Each time we request a new completion, it gets discarded and replaced.")
(defvar cody--completion-timer nil
"Maybe trigger a completion each time Emacs goes idle.")
(defvar cody--completion-last-trigger-spot nil "Temp variable.")
(defsubst cody--cc ()
"Return the current buffer-local version of `cody--completion'."
cody--completion)
(defvar cody--completion-timestamps nil
"Tracks event timestamps for telemetry, as plist properties.")
(defvar cody--connection-global-error nil
"Non-nil when Cody fails to start an Agent subprocess.
Until this flag is cleared, it will not attempt to create any
new Agent processes.")
(defvar cody--vars nil
"Symbol used as scratch space for ephemeral temp variables.
Typically used for allowing before/after hooks to communicate data.
Symbol properties are used reduce namespace clutter.")
(defvar cody-connection-initialized-hook nil
"Hook run after `cody--connection' initializes a connection.
Each workspace has its own node subprocess and jsonrpc connection,
so this hook is run once per workspace that Cody opens.
If the connection failed, then the workspace status field will be `error'.")
(defsubst cody--timestamp ()
"Return seconds since epoch."
(float-time (current-time)))
(defvar-local cody--buffer-state nil
"The state of Cody in the current buffer.
Can be any of nil, `active', `inactive', 'error', or `ignored'.
If nil, the buffer's state has not yet been evaluated. Inactive means
its workspace is not currently live, so Cody is not tracking changes to
the file nor using it for context. Ignored means that an admin has
configured the file or repo to be excluded from Cody. The `error' state
usually means communication with the backend is down. The only way to
recover from this state is to restart it with `cody-workspace-reopen'.")
(defvar-local cody--buffer-document-state nil
"State machine to ensure that we sequence open/close/focus events.
States: nil = unopened, `opened' = opened, and `closed' = closed/error.
States must progress from nil -> opened -> closed, and didFocus events
can only be sent while the document state is `opened'.")
(defvar-local cody--last-selection nil
"Stores the last known selection range to detect changes.")
(defvar cody-mode-menu)
(defvar cody-mode-line-map
(let ((map (make-sparse-keymap)))
(define-key map [mode-line mouse-1] 'cody--mode-line-click)
(easy-menu-define cody-mode-menu map "Cody Mode Menu"
'("Cody"
["Dashboard" (cody-dashboard)]
["Turn Off" cody-mode]
["Help" (describe-function 'cody-mode)]))
map)
"Keymap for Cody mode line button.")
(defun cody--compute-logo-height ()
"Compute the desired height for the Cody logo as 85% of the mode line height."
(truncate (* 0.85 (frame-char-height))))
(defvar-local cody--mode-line-icon-evaluator
'(:eval (cody--evaluate-mode-line-icon))
"Descriptor for producing a custom menu in the mode line lighter.")
(defvar cody--post-command-debounce-timer nil)
;; Utilities
(defmacro cody--call-safely (func &rest args)
"Call FUNC with ARGS safely. Report an error if the call fails."
`(condition-case err
(apply ,func ,args)
(error (cody--log "Error calling %s: %s" (if (symbolp ,func)
(symbol-name ,func)
"a lambda")
err))))
(defsubst cody--bol ()
"Alias for `line-beginning-position'."
(line-beginning-position))
(defsubst cody--eol ()
"Alias for `line-end-position'."
(line-beginning-position))
(defsubst cody--buffer-string ()
"Return the entire current buffer's contents as a string."
(without-restriction
(buffer-substring-no-properties (point-min) (point-max))))
(defsubst cody--convert-json-false (val)
"Convert JSON false (:json-false) to nil. Leave other values unchanged."
(if (eq val :json-false) nil val))
(defun cody--buffer-visible-p (&optional buf)
"Return non-nil if BUF is active. BUF defaults to the current buffer."
(or cody--unit-testing-p
(let ((buffer (or buf (current-buffer))))
(and (eq buffer (window-buffer (selected-window)))
(get-buffer-window buffer t)))))
(defun cody--agent-command ()
"Command and arguments for running agent."
(let ((node-executable (or cody-node-executable (executable-find "node"))))
(unless node-executable
(error "Node.js executable not found in exec-path"))
(list node-executable
"--enable-source-maps"
cody--cody-agent
"api"
"jsonrpc-stdio")))
;; Add to your ~/.authinfo.gpg something that looks like
;; machine `cody--sourcegraph-host' login apikey password sgp_SECRET
(defun cody--access-token ()
"Fetch and cache the access token from ~/.authinfo.gpg."
(or cody--access-token
;; We are looking for an API key, so look for the first entry
;; where the secret starts with sgp_
(setq cody--access-token
(seq-some (lambda (found)
(let ((token (auth-info-password found)))
(if (string-prefix-p "sgp_" token) token)))
(auth-source-search
:max 10
:host cody--sourcegraph-host
:require '(:secret :host))))))
(defun cody--alive-p (&optional connection)
"Return non-nil if CONNECTION is a live process.
CONNECTION defaults to the current workspace's connection, if any."
(or cody--unit-testing-p
;; Don't call `cody--connection' here since it will spawn one.
;; Check the workspace to see if it has a live connection.
(when-let ((conn (or connection
(when-let* ((workspace-root (cody--workspace-root))
(workspace (gethash workspace-root cody-workspaces)))
(cody-workspace-connection workspace)))))
(let ((process (jsonrpc--process conn)))
(and process (zerop (process-exit-status process)))))))
(defun cody--connection (&optional restart-if-needed)
"Get or create the agent connection for the current workspace.
RESTART-IF-NEEDED, if non-nil, will attempt to start or restart the
connection if it is anything other than connected and active.
Return nil if there is no connection available, either because it is
still nil, or because it has failed in some way. Will not return a
dead connection."
(let* ((workspace (cody--current-workspace))
(connection (and workspace (cody-workspace-connection workspace))))
(cond
((cody--error-p) nil)
((cody--alive-p connection) connection)
;; All the error conditions are handled identically for now.
(t
(if (not restart-if-needed)
nil
(condition-case err
;; Restart and initialize.
(progn
(setq connection
(cody--connection-create-process-safe workspace))
;; Required before calling `cody--initialize-connection'.
(setf (cody-workspace-connection workspace) connection)
(with-timeout (10
(signal 'connection-timeout '("Timed out during handshake")))
(cody--initialize-connection workspace))
(if (cody--alive-p connection)
connection
nil))
(error
(cody--workspace-set-error
(format "initializing connection: %s" err)))))))))
(defun cody--connection-create-process-safe (workspace)
"Handle errors and timeouts around attaching to agent process for WORKSPACE.
If `cody--connection-global-error' is non-nil, return nil immediately.
Within a timeout of 10 seconds, attempt to create the process
using `cody--connection-create-process'.
Set a global error on timeout or if any other error occurs.
Return value, if non-nil, is a `jsonrpc-process-connection'."
(when (not cody--connection-global-error)
(condition-case err
(with-timeout (10
(signal 'connection-timeout '("Connection timed out")))
;; This is the meat; everything below is error handling.
(cody--connection-create-process workspace))
(error
;; Making the assumption that timing out means we'll never succeed -
;; the user will have to change something and explicitly reset.
(when (eq (car err) 'connection-timeout)
(setq cody--connection-global-error 'timed-out))
;; Whereas other errors _may_ only apply to this workspace, so we'll
;; just flag this one as being in error.
(cody--workspace-set-error
(if cody-use-remote-agent
(format "Could not attach to agent on port %d: %s"
cody-remote-agent-port
(error-message-string err))
(format "Could not create process: %s"
(error-message-string err)))
nil ; no error for format string; we already handled it.
workspace)
nil))))
(defun cody--connection-create-process (workspace)
"Create a local or network process for talking to the agent for WORKSPACE.
Return value is a `jsonrpc-process-connection'."
(let* ((workspace-root (cody-workspace-root workspace))
(events-buffer
(let ((buf (get-buffer-create (format "*cody events[%s]*"
workspace-root))))
(with-current-buffer buf
(buffer-disable-undo)
buf)))
(process-name (cody--workspace-process-name workspace))
(process-environment (cody--agent-process-environment))
(process (if cody-use-remote-agent
(make-network-process
:name process-name
:host 'local
:service cody-remote-agent-port
:coding 'utf-8-emacs-unix
:noquery t)
(make-process
:name process-name
:command (cody--agent-command)
:coding 'utf-8-emacs-unix
:connection-type 'pipe
:noquery t)))
(connection (make-instance
'jsonrpc-process-connection
:name process-name
:notification-dispatcher #'cody--notification-dispatcher
:request-dispatcher #'cody--request-dispatcher
:process process)))
(setf (cody-workspace-status workspace) 'connected)
(when cody-enable-event-tracing
(setf (jsonrpc--events-buffer connection) events-buffer)
(setf (cody-workspace-events-buffer workspace) events-buffer))
(setf (cody-workspace-stderr-buffer workspace)
(jsonrpc-stderr-buffer connection))
connection))
(defun cody--workspace-process-name (workspace)
"Create the process name for WORKSPACE.
/Path/to/workspace/root is changed to cody-path-to-workspace-root.
This name can be directly looked up more quickly on the workspace after it is set,
since it is immutable, using `(process-name (cody-workspace-process workspace))'."
(let ((root (replace-regexp-in-string "^/+\\|/+$" ""
(cody-workspace-root workspace))))
(setq root (replace-regexp-in-string "/" "-" root))
(setq root (replace-regexp-in-string " " "-" root))
(downcase (concat "cody-" root))))
(defun cody--initialize-connection (workspace)
"Send the protocol handshake requests for WORKSPACE."
;; client -> 'initialize -> host
(condition-case err
(let ((response
(cody--request 'initialize
(list
:name "Emacs"
:version "0.2"
:workspaceRootUri (cody--workspace-uri)
:capabilities (cody--client-capabilities)
:extensionConfiguration (cody--extension-configuration)))))
(when response
(setf (cody-workspace-server-info workspace)
(cody-populate-server-info response))))
(error (cody--workspace-set-error err)))
(condition-case err
(run-hooks 'cody-connection-initialized-hook)
(error (cody--log "Error in `cody--initialize-connection': %s" err)))
;; client -> 'initialized -> host
(condition-case err
(cody--notify 'initialized nil)
(error (cody--workspace-set-error err))))
(defun cody--agent-process-environment ()
"Return the environment variables to set in the Agent."
(list
(format "PATH=%s" (getenv "PATH")) ; Propagate PATH
(concat "CODY_CLIENT_INTEGRATION_TESTING="
(if cody--integration-testing-p "true" "false"))))
(defun cody-populate-server-info (response)
"Populate the ServerInfo instance from the RESPONSE.
Returns a `cody-server-info' instance."
(cl-labels ((cjf (val) (cody--convert-json-false val))
(create-cody-llm-site-configuration (config)
(when config
(make-instance
'cody-llm-site-configuration
:chatModel (plist-get config :chatModel)
:chatModelMaxTokens (cjf (plist-get config :chatModelMaxTokens))
:fastChatModel (plist-get config :fastChatModel)
:fastChatModelMaxTokens (cjf (plist-get config
:fastChatModelMaxTokens))
:completionModel (plist-get config :completionModel)
:completionModelMaxTokens (cjf (plist-get
config :completionModelMaxTokens))
:provider (plist-get config :provider)
:smartContextWindow (cjf (plist-get config :smartContextWindow))))))
(let* ((auth-status (plist-get response :authStatus))
(config-overwrites (create-cody-llm-site-configuration
(plist-get auth-status :configOverwrites)))
(auth-status-instance
(condition-case err
(make-instance
'cody-auth-status
:username (plist-get auth-status :username)
:endpoint (cjf (plist-get auth-status :endpoint))
:isDotCom (cjf (plist-get auth-status :isDotCom))
:isLoggedIn (cjf (plist-get auth-status :isLoggedIn))
:showInvalidAccessTokenError (cjf (plist-get
auth-status
:showInvalidAccessTokenError))
:authenticated (cjf (plist-get auth-status :authenticated))
:hasVerifiedEmail (cjf (plist-get auth-status :hasVerifiedEmail))
:requiresVerifiedEmail (cjf (plist-get auth-status
:requiresVerifiedEmail))
:siteHasCodyEnabled (cjf (plist-get auth-status :siteHasCodyEnabled))
:siteVersion (plist-get auth-status :siteVersion)
:codyApiVersion (cjf (plist-get auth-status :codyApiVersion))
:configOverwrites config-overwrites
:showNetworkError (cjf (plist-get auth-status :showNetworkError))
:primaryEmail (plist-get auth-status :primaryEmail)
:displayName (plist-get auth-status :displayName)
:avatarURL (plist-get auth-status :avatarURL)
:userCanUpgrade (cjf (plist-get auth-status :userCanUpgrade)))
(error
(message "Error creating cody-auth-status instance: %s" err)
(cody--workspace-set-error "Failed to create cody-auth-status instance" err)
(signal 'error err)))))
(make-instance 'cody-server-info
:name (plist-get response :name)
:authenticated (cjf (plist-get response :authenticated))
:codyEnabled (cjf (plist-get response :codyEnabled))
:codyVersion (plist-get response :codyVersion)
:authStatus auth-status-instance))))
(defun cody--client-capabilities ()
"Return the Cody features that we support in the Emacs client."
(list :edit "enabled"
:editWorkspace "enabled"
:codeLenses "enabled"
:showDocument "enabled"
:ignore "none"
:untitledDocuments "enabled"
:progressBars "none"))
(defun cody--extension-configuration ()
"Which `ExtensionConfiguration' parameters to send on Agent handshake."
(list :anonymousUserID (cody--internal-anonymized-uuid)
:serverEndpoint (concat "https://" cody--sourcegraph-host "/")
:accessToken (cody--access-token)
:debug cody-enable-agent-debug
:debug-verbose cody-enable-agent-debug-verbose
:codebase (cody--workspace-uri)
:customConfiguration (list (cons :cody.experimental.foldingRanges
"indentation-based"))))
;; This was used to switch workspaces before multi-workspace support.
;; Keeping it because there are other situations where we will need it.
(defun cody--notify-configuration-changed ()
"Notify the agent that the extension configuration has changed."
(let ((auth-status
(cody--request 'extensionConfiguration/change
(cody--extension-configuration))))
(unless (plist-get auth-status :authenticated)
(cody--log "Cody is no longer authenticated after config change: %s"
auth-status)
(message "Cody needs to re-authenticate")
(cody-logout))))
(defun cody--format-jsonrpc-error (jsonrpc-error)
"Format JSONRPC-ERROR as a concise string."
(let ((request-id (nth 1 jsonrpc-error))
(error-message (alist-get 'jsonrpc-error-message (nth 2 jsonrpc-error))))
(format "request id=%s failed: %s" request-id error-message)))
(defun cody--request (method params &rest args)
"Wrapper for `jsonrpc-request' that makes it testable."
(unless (or cody--unit-testing-p (cody--error-p))
(condition-case err
(when-let ((connection (cody--connection)))
(apply #'jsonrpc-request (cody--connection) method params args))
(error (cody--log "Unable to send request %s: %s" method err)))))
(defun cody--notify (method params &rest args)
"Helper to send a Cody request for METHOD with PARAMS."
(unless (or cody--unit-testing-p (cody--error-p))
(condition-case err
(if-let ((connection (cody--connection)))
(apply #'jsonrpc-notify connection method params args)
(cody--log "Skipped sending notification %s: null connection" method))
(error (cody--log "Unable to send %s: %s" method err)))))
(defun cody--check-node-version ()
"Signal an error if the default node.js version is too low.
Min version is configurable with `cody-node-min-version'."
(cond
(cody-use-remote-agent
t)
((eq cody--node-version-status 'good)
t)
((eq cody--node-version-status 'bad)
(error "Installed nodejs must be at least %s." cody-node-min-version))
(t
(let* ((cmd (concat (or cody-node-executable "node") " -v"))
(node-version (string-trim (shell-command-to-string cmd)))
minor major patch)
(if (not (string-match "^v\\([0-9]+\\)\\.\\([0-9]+\\)\\.\\([0-9]+\\)"
node-version))
(progn
(message "Error: Could not parse nodejs version string: %s"
node-version)
nil)
(setq major (string-to-number (match-string 1 node-version))
minor (string-to-number (match-string 2 node-version))
patch (string-to-number (match-string 3 node-version)))
(let* ((min-version-parts (split-string cody-node-min-version "\\."))
(min-major (string-to-number (nth 0 min-version-parts)))
(min-minor (string-to-number (nth 1 min-version-parts)))
(min-patch (string-to-number (nth 2 min-version-parts))))
;; For now, as of July 07 2024, make it exact, since 22.1.0 hangs Agent.
(if (and (= major min-major) (= minor min-minor) (= patch min-patch))
(setq cody--node-version-status 'good)
(setq cody--node-version-status 'bad)
(error
"Error: Installed nodejs version %s is not the required version %s"
node-version cody-node-min-version))))))))
(defun cody--get-custom-request-headers-as-map (custom-request-headers)
"Convert CUSTOM-REQUEST-HEADERS string to a map."
(let ((pairs (split-string custom-request-headers ",")))
(cl-loop for (key value) on pairs by #'cddr
collect (cons (string-trim key) (string-trim value)))))
(defun cody--logo-file (file-base)
"Construct path to bundled cody image file.
Argument FILE-BASE is the file base name sans directory."
(file-name-concat
(file-name-directory (directory-file-name
(file-name-directory cody--cody-agent)))
"icons"
file-base))
(defun cody-current-theme-dark-p ()
"Return t if the current theme is considered dark."
(eq (frame-parameter nil 'background-mode) 'dark))
(defmacro define-cached-icon (base-name &optional dual-theme)
"Define a function that returns a cached image for BASE-NAME.
This function considers the current theme (light or dark) and returns
an appropriate version of the icon. If DUAL-THEME is non-nil,
it indicates that the icon works for both light and dark themes."
(let* ((name (intern (format "cody--icon-%s" base-name)))
(light-filename (concat base-name ".png"))
(dark-filename (if dual-theme
(concat base-name ".png")
(concat base-name "_dark.png"))))
`(defun ,name ()
(let* ((file (if (cody-current-theme-dark-p) ,dark-filename ,light-filename))
(img (or (get ',name 'cached-image)
(put ',name 'cached-image
(create-image (cody--logo-file file))))))
(plist-put (cdr img) :height (cody--compute-logo-height))
img))))
(defmacro create-icon-functions ()
"Create functions for all necessary icons in the icons directory."
(let ((theme-dependent-icons '("logo-disabled"
"logo-monotone"
"error"))
(fixed-icons '("cody-logo-small"
"cody-logo"
"logo-mono-unavailable")))
`(progn
;; Generate functions for theme-dependent icons
,@(mapcar (lambda (name)
`(define-cached-icon ,name))
theme-dependent-icons)
;; Generate functions for fixed icons
,@(mapcar (lambda (name)
`(define-cached-icon ,name t))
fixed-icons))))
;; Execute the macro to create the necessary functions; e.g.,
;; `cody--logo-cody-logo-small'. They load their images lazily.
(create-icon-functions)