forked from xenodium/agent-shell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent-shell.el
More file actions
1958 lines (1769 loc) · 83.4 KB
/
agent-shell.el
File metadata and controls
1958 lines (1769 loc) · 83.4 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
;;; agent-shell.el --- An agent shell powered by ACP -*- lexical-binding: t; -*-
;; Copyright (C) 2024 Alvaro Ramirez
;; Author: Alvaro Ramirez https://xenodium.com
;; URL: https://github.com/xenodium/agent-shell
;; Version: 0.6.5
(defconst agent-shell--version "0.6.5")
;; This package is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; This package is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;;
;; agent-shell is driven by ACP (Agent Client Protocol) as per spec
;; https://agentclientprotocol.com
;;
;; Note: This package is in the very early stage and is likely
;; incomplete or may have some rough edges.
;;
;; Report issues at https://github.com/xenodium/agent-shell/issues
;;
;; ✨ Please support this work https://github.com/sponsors/xenodium ✨
;;; Code:
(require 'acp)
(eval-when-compile
(require 'cl-lib))
(require 'json)
(require 'map)
(unless (require 'markdown-overlays nil 'noerror)
(error "Please update 'shell-maker' to v0.82.2 or newer"))
(require 'shell-maker)
(require 'sui)
(require 'svg nil :noerror)
(require 'quick-diff)
(require 'agent-shell-anthropic)
(require 'agent-shell-google)
(require 'agent-shell-goose)
(require 'agent-shell-openai)
(require 'agent-shell-qwen)
(defcustom agent-shell-permission-icon "⚠"
"Icon displayed when shell commands require permission to execute.
You may use \"\" as an SF Symbol on macOS."
:type 'string
:group 'agent-shell)
(defcustom agent-shell-thought-process-icon "💡"
"Icon displayed during the AI's thought process.
You may use \"\" as an SF Symbol on macOS."
:type 'string
:group 'agent-shell)
(defcustom agent-shell-show-config-icons t
"Whether to show icons in agent config selection."
:type 'boolean
:group 'agent-shell)
(defcustom agent-shell-path-resolver-function nil
"Function for resolving remote paths on the local file-system, and vice versa.
Expects a function that takes the path as its single argument, and
returns the resolved path. Set to nil to disable mapping."
:type 'function
:group 'agent-shell)
(defcustom agent-shell-text-file-capabilities t
"Whether agents are initialized with read/write text file capabilities.
See `acp-make-initialize-request' for details."
:type 'boolean
:group 'agent-shell)
(defcustom agent-shell-display-action
'(display-buffer-same-window)
"Display action for agent shell buffers.
See `display-buffer' for the format of display actions."
:type '(cons (repeat function) alist)
:group 'agent-shell)
(defcustom agent-shell-file-completion-enabled nil
"Non-nil automatically enables file completion when starting shells."
:type 'boolean
:group 'agent-shell)
(defcustom agent-shell-header-style (if (display-graphic-p) 'graphical 'text)
"Style for agent shell buffer headers.
Can be one of:
\='graphical: Display header with icon and styled text.
\='text: Display simple text-only header.
nil: Display no header."
:type '(choice (const :tag "Graphical" graphical)
(const :tag "Text only" text)
(const :tag "No header" nil))
:group 'agent-shell)
(cl-defun agent-shell-make-agent-config (&key no-focus new-session mode-line-name welcome-function
buffer-name shell-prompt shell-prompt-regexp
client-maker
needs-authentication
authenticate-request-maker
icon-name
install-instructions)
"Create an agent configuration alist.
Keyword arguments:
- NO-FOCUS: Non-nil to avoid focusing the agent buffer
- NEW-SESSION: Non-nil to start a new session
- MODE-LINE-NAME: Name to display in the mode line
- WELCOME-FUNCTION: Function to call for welcome message
- BUFFER-NAME: Name of the agent buffer
- SHELL-PROMPT: The shell prompt string
- SHELL-PROMPT-REGEXP: Regexp to match the shell prompt
- CLIENT-MAKER: Function to create the client
- NEEDS-AUTHENTICATION: Non-nil authentication is required
- AUTHENTICATE-REQUEST-MAKER: Function to create authentication requests
- ICON-NAME: Name of the icon to use
- INSTALL-INSTRUCTIONS: Instructions to show when executable is not found
Returns an alist with all specified values."
`((:no-focus . ,no-focus)
(:new-session . ,new-session)
(:mode-line-name . ,mode-line-name)
(:welcome-function . ,welcome-function)
(:buffer-name . ,buffer-name)
(:shell-prompt . ,shell-prompt)
(:shell-prompt-regexp . ,shell-prompt-regexp)
(:client-maker . ,client-maker)
(:needs-authentication . ,needs-authentication)
(:authenticate-request-maker . ,authenticate-request-maker)
(:icon-name . ,icon-name)
(:install-instructions . ,install-instructions)))
(defun agent-shell--make-default-agent-configs ()
"Create a list of default agent configs.
This function aggregates agents from OpenAI, Anthropic, Google, and Goose."
(list (agent-shell-anthropic-make-claude-code-config)
(agent-shell-google-make-gemini-config)
(agent-shell-goose-make-agent-config)
(agent-shell-openai-make-codex-config)
(agent-shell-qwen-make-agent-config)))
(defcustom agent-shell-agent-configs
(agent-shell--make-default-agent-configs)
"The list of known agent configurations.
See `agent-shell-*-make-*-config' for details."
:type '(repeat (alist :key-type symbol :value-type sexp))
:group 'agent-shell)
(cl-defun agent-shell--make-state (&key buffer client-maker needs-authentication authenticate-request-maker)
"Construct shell agent state with BUFFER.
Shell state is provider-dependent and needs CLIENT-MAKER, NEEDS-AUTHENTICATION
and AUTHENTICATE-REQUEST-MAKER."
(list (cons :buffer buffer)
(cons :client nil)
(cons :client-maker client-maker)
(cons :initialized nil)
(cons :needs-authentication needs-authentication)
(cons :authenticate-request-maker authenticate-request-maker)
(cons :authenticated nil)
(cons :session-id nil)
(cons :last-entry-type nil)
(cons :chunked-group-count 0)
(cons :request-count 0)
(cons :tool-calls nil)
(cons :available-commands nil)))
(defvar-local agent-shell--state
(agent-shell--make-state))
(defvar agent-shell--shell-maker-config nil)
;;;###autoload
(defun agent-shell (&optional new-shell)
"Start or reuse an existing agent shell.
With prefix argument NEW-SHELL, force start a new shell."
(interactive "P")
(if (and (not new-shell)
(seq-first (agent-shell-buffers)))
(agent-shell--display-buffer (seq-first (agent-shell-buffers)))
(agent-shell-start :config (or (agent-shell-select-config
:prompt "Start new agent: ")
(error "No agent config found")))))
;;;###autoload
(defun agent-shell-toggle ()
"Toggle agent shell display."
(interactive)
(let ((shell-buffer (seq-first (agent-shell-project-buffers))))
(unless shell-buffer
(user-error "No agent shell buffers available for current project"))
(if-let ((window (get-buffer-window shell-buffer)))
(if (> (count-windows) 1)
(delete-window window)
(switch-to-prev-buffer))
(agent-shell--display-buffer shell-buffer))))
(cl-defun agent-shell-start (&key config)
"Programmatically start shell with CONFIG.
See `agent-shell-make-agent-config' for config format."
(agent-shell--apply
:function #'agent-shell--start
:alist config))
(cl-defun agent-shell--config-icon (&key config)
"Create icon string for CONFIG if available and icons are enabled.
Returns an empty string if no icon should be displayed."
(if-let* ((graphics-capable (display-graphic-p))
(icon-name (map-elt config :icon-name))
(icon-filename (agent-shell--fetch-agent-icon icon-name)))
(with-temp-buffer
(insert-image (create-image icon-filename nil nil
:ascent 'center
:height (frame-char-height)))
(buffer-string))
""))
(cl-defun agent-shell-select-config (&key prompt)
"Display PROMPT to select an agent config from `agent-shell-agent-configs'."
(let* ((configs agent-shell-agent-configs)
(choices (mapcar (lambda (config)
(let ((display-name (or (map-elt config :mode-line-name)
(map-elt config :buffer-name)
"Unknown Agent"))
(icon (when agent-shell-show-config-icons
(agent-shell--config-icon :config config))))
(cons (format "%s%s%s" icon (when icon " ") display-name)
config)))
configs))
(selected-name (completing-read (or prompt "Select agent: ") choices nil t)))
(map-elt choices selected-name)))
(defun agent-shell-buffers ()
"Return all shell buffers."
(seq-map #'buffer-name
(seq-filter (lambda (buffer)
(with-current-buffer buffer
(derived-mode-p 'agent-shell-mode)))
(buffer-list))))
(defun agent-shell-version ()
"Show `agent-shell' mode version."
(interactive)
(message "agent-shell v%s" agent-shell--version))
(defun agent-shell-interrupt ()
"Interrupt in-progress request."
(interactive)
(unless (eq major-mode 'agent-shell-mode)
(error "Not in a shell"))
(unless (map-elt (agent-shell--state) :session-id)
(error "No active session"))
(when (y-or-n-p "Abort?")
(acp-send-notification
:client (map-elt (agent-shell--state) :client)
:notification (acp-make-session-cancel-notification
:session-id (map-elt (agent-shell--state) :session-id)
:reason "User cancelled"))))
(cl-defun agent-shell--make-shell-maker-config (&key prompt prompt-regexp)
"Create `shell-maker' configuration with PROMPT and PROMPT-REGEXP."
(make-shell-maker-config
:name "agent"
:prompt prompt
:prompt-regexp prompt-regexp
:execute-command
(lambda (command shell)
(agent-shell--handle
:command command
:shell shell))))
(defvar-keymap agent-shell-mode-map
:parent shell-maker-mode-map
:doc "Keymap for `agent-shell-mode'."
"TAB" #'agent-shell-next-item
"<tab>" #'agent-shell-next-item
"<backtab>" #'agent-shell-previous-item
"S-TAB" #'agent-shell-previous-item
"C-c C-c" #'agent-shell-interrupt)
(shell-maker-define-major-mode (agent-shell--make-shell-maker-config) agent-shell-mode-map)
(cl-defun agent-shell--handle (&key command shell)
"Handle SHELL COMMAND (and lazy initialize the ACP stack).
SHELL is from `shell-maker'.
Flow:
Before a shell COMMAND can be sent as a prompt to the agent, a
handful of ACP initialization steps must take place (some asynchronously).
Once all initialization steps are cleared, only then the COMMAND
can be sent to the agent as a prompt (thus recursive nature of this function).
-> Initialize ACP client
|-> Subscribe to ACP events
|-> Initiate handshake (ie. initialize RPC)
|-> Authenticate (optional)
|-> Start prompt session
|-> Send COMMAND/prompt (finally!)"
(with-current-buffer (map-elt shell :buffer)
(unless (eq major-mode 'agent-shell-mode)
(error "Not in a shell"))
(map-put! (agent-shell--state) :request-count
;; TODO: Make public in shell-maker.
(shell-maker--current-request-id))
(cond ((not (map-elt (agent-shell--state) :client))
(when (agent-shell--initialize-client :shell shell)
(agent-shell--handle :command command :shell shell)))
((or (not (map-nested-elt (agent-shell--state) '(:client :request-handlers)))
(not (map-nested-elt (agent-shell--state) '(:client :notification-handlers)))
(not (map-nested-elt (agent-shell--state) '(:client :error-handlers))))
(when (agent-shell--initialize-subscriptions :shell shell)
(agent-shell--handle :command command :shell shell)))
((not (map-elt (agent-shell--state) :initialized))
(agent-shell--initiate-handshake
:shell shell
:on-initiated (lambda ()
(map-put! (agent-shell--state) :initialized t)
(agent-shell--handle :command command :shell shell))))
((and (map-elt (agent-shell--state) :needs-authentication)
(not (map-elt (agent-shell--state) :authenticated)))
(agent-shell--authenticate
:shell shell
:on-authenticated (lambda ()
(map-put! (agent-shell--state) :authenticated t)
(agent-shell--handle :command command :shell shell))))
((not (map-elt (agent-shell--state) :session-id))
(agent-shell--initiate-session
:shell shell
:on-session-init (lambda ()
(agent-shell--handle :command command :shell shell))))
(t
(agent-shell--send-command :prompt command :shell shell)))))
(cl-defun agent-shell--on-error (&key state error)
"Handle ERROR with SHELL an STATE."
(let-alist error
(agent-shell--update-dialog-block
:state state
:block-id "Error"
:body (or .message "Some error ¯\\_ (ツ)_/¯")
:create-new t
:navigation 'never)))
(cl-defun agent-shell--on-notification (&key state notification)
"Handle incoming notification using SHELL, STATE, and NOTIFICATION."
(let-alist notification
(cond ((equal .method "session/update")
(let ((update (map-elt (map-elt notification 'params) 'update)))
(cond
((equal (map-elt update 'sessionUpdate) "tool_call")
(agent-shell--save-tool-call
state
(map-elt update 'toolCallId)
(append (list (cons :title (map-elt update 'title))
(cons :status (map-elt update 'status))
(cons :kind (map-elt update 'kind))
(cons :command (map-nested-elt update '(rawInput command)))
(cons :description (map-nested-elt update '(rawInput description)))
(cons :content (map-elt update 'content)))
(when-let ((diff (agent-shell--make-diff-info (map-elt update 'content))))
(list (cons :diff diff)))))
(agent-shell--update-dialog-block
:state state
:block-id (map-elt update 'toolCallId)
:label-left (agent-shell-make-tool-call-label
state (map-elt update 'toolCallId)))
(map-put! state :last-entry-type "tool_call"))
((equal (map-elt update 'sessionUpdate) "agent_thought_chunk")
(let-alist update
;; (message "agent_thought_chunk: last-type=%s, will-append=%s"
;; (map-elt state :last-entry-type)
;; (equal (map-elt state :last-entry-type) "agent_thought_chunk"))
(unless (equal (map-elt state :last-entry-type)
"agent_thought_chunk")
(map-put! state :chunked-group-count (1+ (map-elt state :chunked-group-count))))
(agent-shell--update-dialog-block
:state state
:block-id (format "%s-agent_thought_chunk"
(map-elt state :chunked-group-count))
:label-left (concat
agent-shell-thought-process-icon
" "
(propertize "Thought process" 'font-lock-face font-lock-doc-markup-face))
:body .content.text
:append (equal (map-elt state :last-entry-type)
"agent_thought_chunk")))
(map-put! state :last-entry-type "agent_thought_chunk"))
((equal (map-elt update 'sessionUpdate) "agent_message_chunk")
(unless (equal (map-elt state :last-entry-type) "agent_message_chunk")
(map-put! state :chunked-group-count (1+ (map-elt state :chunked-group-count))))
(let-alist update
(agent-shell--update-dialog-block
:state state
:block-id (format "%s-agent_message_chunk"
(map-elt state :chunked-group-count))
:body .content.text
:create-new (not (equal (map-elt state :last-entry-type)
"agent_message_chunk"))
:append t
:navigation 'never))
(map-put! state :last-entry-type "agent_message_chunk"))
((equal (map-elt update 'sessionUpdate) "plan")
(let-alist update
(agent-shell--update-dialog-block
:state state
:block-id "plan"
:label-left (propertize "Plan" 'font-lock-face 'font-lock-doc-markup-face)
:body (agent-shell--format-plan .entries)
:expanded t))
(map-put! state :last-entry-type "plan"))
((equal (map-elt update 'sessionUpdate) "tool_call_update")
(let-alist update
;; Update stored tool call data with new status and content
(agent-shell--save-tool-call
state
.toolCallId
(append (list (cons :status (map-elt update 'status))
(cons :content (map-elt update 'content)))
(when-let ((diff (agent-shell--make-diff-info (map-elt update 'content))))
(list (cons :diff diff)))))
(let ((output (concat
"\n\n"
;; TODO: Consider if there are other
;; types of content to display.
(mapconcat (lambda (item)
(let-alist item
.content.text))
.content
"\n\n")
"\n\n")))
;; Hide permission after sending response.
;; Status and permission are no longer pending. User
;; likely selected one of: accepted/rejected/always.
;; Remove stale permission dialog.
(when (and (map-elt update 'status)
(not (equal (map-elt update 'status) "pending")))
;; block-id must be the same as the one used as
;; agent-shell--update-dialog-block param by "session/request_permission".
(agent-shell--delete-dialog-block :state state :block-id (format "permission-%s" .toolCallId)))
(agent-shell--update-dialog-block
:state state
:block-id .toolCallId
:label-left (agent-shell-make-tool-call-label
state .toolCallId)
:body (string-trim output))))
(map-put! state :last-entry-type "tool_call_update"))
((equal (map-elt update 'sessionUpdate) "available_commands_update")
(let-alist update
(map-put! state :available-commands (map-elt update 'availableCommands))
(agent-shell--update-dialog-block
:state state
:block-id "available_commands_update"
:label-left (propertize "Available commands" 'font-lock-face 'font-lock-doc-markup-face)
:body (agent-shell--format-available-commands (map-elt update 'availableCommands))))
(map-put! state :last-entry-type "available_commands_update"))
(t
(agent-shell--update-dialog-block
:state state
:block-id "Session Update - fallback"
:body (format "%s" notification)
:create-new t
:navigation 'never)
(map-put! state :last-entry-type nil)))))
(t
(agent-shell--update-dialog-block
:state state
:block-id "Notification - fallback"
:body (format "%s" notification)
:create-new t
:navigation 'never)
(map-put! state :last-entry-type nil)))))
(cl-defun agent-shell--on-request (&key state request)
"Handle incoming request using SHELL, STATE, and REQUEST."
(let-alist request
(cond ((equal .method "session/request_permission")
(agent-shell--save-tool-call
state .params.toolCall.toolCallId
(append (list (cons :title .params.toolCall.title)
(cons :status .params.toolCall.status)
(cons :kind .params.toolCall.kind))
(when-let ((diff (agent-shell--make-diff-info .params.toolCall.content)))
(list (cons :diff diff)))))
(agent-shell--update-dialog-block
:state state
;; block-id must be the same as the one used
;; in agent-shell--delete-dialog-block param.
:block-id (format "permission-%s" .params.toolCall.toolCallId)
:body (with-current-buffer (map-elt state :buffer)
(agent-shell--make-tool-call-permission-text
:request request
:client (map-elt state :client)
:state state))
:expanded t
:navigation 'never)
(agent-shell-jump-to-latest-permission-button-row)
(map-put! state :last-entry-type "session/request_permission"))
((equal .method "fs/read_text_file")
(agent-shell--on-fs-read-text-file-request
:state state
:request request))
((equal .method "fs/write_text_file")
(agent-shell--on-fs-write-text-file-request
:state state
:request request))
(t
(agent-shell--update-dialog-block
:state state
:block-id "Unhandled Incoming Request"
:body (format "⚠ Unhandled incoming request: \"%s\"" .method)
:create-new t
:navigation 'never)
(map-put! state :last-entry-type nil)))))
(cl-defun agent-shell--extract-buffer-text (&key buffer line limit)
"Extract text from BUFFER starting from LINE with optional LIMIT.
LINE defaults to 1, LIMIT defaults to nil (read to end)."
(with-current-buffer buffer
(save-excursion
(goto-char (point-min))
(when (and line (> line 1))
;; Seems odd to use forward-line but
;; that's what `goto-line' recommends.
(forward-line (1- line)))
(let ((start (point)))
(if limit
;; Seems odd to use forward-line but
;; that's what `goto-line' recommends.
(forward-line limit)
(goto-char (point-max)))
(buffer-substring-no-properties start (point))))))
(cl-defun agent-shell--on-fs-read-text-file-request (&key state request)
"Handle fs/read_text_file REQUEST with STATE."
(let-alist request
(condition-case err
(let* ((path (agent-shell--resolve-path .params.path))
(line (or .params.line 1))
(limit .params.limit)
(existing-buffer (find-buffer-visiting path))
(content (if existing-buffer
;; Read from open buffer (includes unsaved changes)
(agent-shell--extract-buffer-text :buffer existing-buffer :line line :limit limit)
;; No open buffer, read from file
(with-temp-buffer
(insert-file-contents path)
(agent-shell--extract-buffer-text :buffer (current-buffer) :line line :limit limit)))))
(acp-send-response
:client (map-elt state :client)
:response (acp-make-fs-read-text-file-response
:request-id .id
:content content)))
(error
(acp-send-response
:client (map-elt state :client)
:response (acp-make-fs-read-text-file-response
:request-id .id
:error (acp-make-error
:code -32603
:message (error-message-string err))))))))
(cl-defun agent-shell--on-fs-write-text-file-request (&key state request)
"Handle fs/write_text_file REQUEST with STATE."
(let-alist request
(condition-case err
(let* ((path (agent-shell--resolve-path .params.path))
(content .params.content)
(dir (file-name-directory path))
(buffer (find-buffer-visiting path)))
(when (and dir (not (file-exists-p dir)))
(make-directory dir t))
(if buffer
;; Buffer is open, write and save.
(with-current-buffer buffer
(let ((inhibit-read-only t))
(erase-buffer)
(insert content)
(basic-save-buffer)))
;; No open buffer, write to file directly.
(with-temp-file path
(insert content)))
(acp-send-response
:client (map-elt state :client)
:response (acp-make-fs-write-text-file-response
:request-id .id)))
(error
(acp-send-response
:client (map-elt state :client)
:response (acp-make-fs-write-text-file-response
:request-id .id
:error (acp-make-error
:code -32603
:message (error-message-string err))))))))
(defun agent-shell--resolve-path (path)
"Resolve PATH using `agent-shell-path-resolver-function'."
(funcall (or agent-shell-path-resolver-function #'identity) path))
(defun agent-shell--get-devcontainer-workspace-path (cwd)
"Return devcontainer workspaceFolder for CWD; signal error if none found.
See https://containers.dev for more information on devcontainers."
(let ((devcontainer-config-file-name (expand-file-name ".devcontainer/devcontainer.json" cwd)))
(condition-case _err
(or
(map-elt (json-read-file devcontainer-config-file-name) 'workspaceFolder)
(error "No workspace folder defined in %s" devcontainer-config-file-name))
(file-missing (error "Not found: %s" devcontainer-config-file-name))
(permission-denied (error "Not readable: %s" devcontainer-config-file-name))
(json-string-format (error "No valid JSON: %s" devcontainer-config-file-name)))))
(defun agent-shell--resolve-devcontainer-path (path)
"Resolve PATH from a devcontainer in the local filesystem, and vice versa.
For example:
- /workspace/README.md => /home/xenodium/projects/kitchen-sink/README.md
- /home/xenodium/projects/kitchen-sink/README.md => /workspace/README.md"
(let* ((cwd (agent-shell-cwd))
(devcontainer-path (agent-shell--get-devcontainer-workspace-path cwd)))
(if (string-prefix-p cwd path)
(string-replace cwd devcontainer-path path)
(if agent-shell-text-file-capabilities
(if-let* ((is-dev-container (string-prefix-p devcontainer-path path))
(local-path (expand-file-name (string-replace devcontainer-path cwd path))))
(or
(and (file-in-directory-p local-path cwd) local-path)
(error "Resolves to path outside of working directory: %s" path))
(error "Unexpected path outside of workspace folder: %s" path))
(error "Refuse to resolve to local filesystem with text file capabilities disabled: %s" path)))))
(defun agent-shell--stop-reason-description (stop-reason)
"Return a human-readable text description for STOP-REASON.
https://agentclientprotocol.com/protocol/schema#param-stop-reason"
(pcase stop-reason
("end_turn" "Finished")
("max_tokens" "Max token limit reached")
("max_turn_requests" "Exceeded request limit")
("refusal" "Refused")
("cancelled" "Cancelled")
(_ (format "Stop for unknown reason: %s" stop-reason))))
(defun agent-shell--format-available-commands (commands)
"Format COMMANDS for shell rendering."
(let ((max-name-length (cl-reduce #'max commands
:key (lambda (cmd)
(length (map-elt cmd 'name)))
:initial-value 0)))
(mapconcat
(lambda (cmd)
(let ((name (map-elt cmd 'name))
(desc (map-elt cmd 'description)))
(concat
;; For commands to be executable, they start with /
(propertize (format (format "/%%-%ds" max-name-length) name)
'font-lock-face 'font-lock-function-name-face)
" "
(propertize desc 'font-lock-face 'font-lock-comment-face))))
commands
"\n")))
(defun agent-shell--make-diff-info (acp-content)
"Make diff information from ACP's tool_call_update's ACP-CONTENT.
CONTENT is of the the type ToolCallContent as per ACP spec:
https://agentclientprotocol.com/protocol/schema#toolcallcontent
Returns in the form:
`((:old . old-text)
(:new . new-text)
(:file . file-path))."
(when-let* ((diff-item (cond
;; Single diff object
((and acp-content (equal (map-elt acp-content 'type) "diff"))
acp-content)
;; TODO: Is this needed?
;; Isn't acp-content always an alist?
;; Vector/array acp-content - find diff item
((vectorp acp-content)
(seq-find (lambda (item)
(equal (map-elt item 'type) "diff"))
acp-content))
;; TODO: Is this needed?
;; Isn't acp-content always an alist?
;; List acp-content - find diff item
((listp acp-content)
(seq-find (lambda (item)
(equal (map-elt item 'type) "diff"))
acp-content))))
(old-text (map-elt diff-item 'oldText))
(new-text (map-elt diff-item 'newText))
(file-path (map-elt diff-item 'path)))
(append (list (cons :old old-text)
(cons :new new-text))
(when file-path
(list (cons :file file-path))))))
(cl-defun agent-shell--make-error-handler (&key state shell)
"Create ACP error handler with SHELL STATE."
(lambda (error raw-message)
(let-alist error
(with-current-buffer (map-elt state :buffer)
(agent-shell--update-dialog-block
:state (agent-shell--state)
:block-id (format "failed-%s-id:%s-code:%s"
(map-elt state :request-count)
(or .id "?")
(or .code "?"))
:body (agent-shell--make-error-dialog-text
:code .code
:message .message
:raw-message raw-message)
:create-new t)))
;; TODO: Mark buffer command with shell failure.
(with-current-buffer (map-elt state :buffer)
(funcall (map-elt shell :finish-output) t))))
(defun agent-shell--save-tool-call (state tool-call-id tool-call)
"Store TOOL-CALL with TOOL-CALL-ID in STATE's :tool-calls alist."
(let* ((tool-calls (map-elt state :tool-calls))
(old-tool-call (map-elt tool-calls tool-call-id))
(updated-tools (copy-alist tool-calls))
(tool-call-overrides (seq-filter (lambda (pair)
(cdr pair))
tool-call)))
(setf (map-elt updated-tools tool-call-id)
(if old-tool-call
(map-merge 'alist old-tool-call tool-call-overrides)
tool-call-overrides))
(map-put! state :tool-calls updated-tools)))
(cl-defun agent-shell--make-error-dialog-text (&key code message raw-message)
"Create formatted error dialog text with CODE, MESSAGE, and RAW-MESSAGE."
(format "╭─
%s Error (%s) %s
%s
%s
╰─"
(propertize "⚠" 'font-lock-face 'error)
(or code "?")
(propertize "⚠" 'font-lock-face 'error)
(or message "¯\\_ (ツ)_/¯")
(agent-shell--make-button
:text "Details" :help "Details" :kind 'error
:action (lambda ()
(interactive)
(agent-shell--view-as-error
(with-temp-buffer
(let ((print-circle t))
(pp raw-message (current-buffer))
(buffer-string))))))))
(defun agent-shell--view-as-error (text)
"Display TEXT in a read-only error buffer."
(let ((buf (get-buffer-create "*acp error*")))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(insert text))
(read-only-mode 1))
(display-buffer buf)))
(defun agent-shell--clean-up ()
"Clean up resources.
For example, shut down ACP client."
(unless (eq major-mode 'agent-shell-mode)
(error "Not in a shell"))
(when (map-elt (agent-shell--state) :client)
(acp-shutdown :client (map-elt (agent-shell--state) :client))))
(defun agent-shell--status-label (status)
"Convert STATUS codes to user-visible labels."
(let* ((config (pcase status
("pending" '("pending" font-lock-comment-face))
("in_progress" '("in progress" warning))
("completed" '("completed" success))
("failed" '("failed" error))
(_ '("unknown" warning))))
(label (car config))
(face (cadr config))
(color (face-foreground face nil t)))
(agent-shell--add-text-properties
(propertize (format " %s " label) 'font-lock-face 'default)
'font-lock-face
`(:foreground ,color :box (:color ,color)))))
(defun agent-shell--shorten-paths (text)
"Shorten file paths in TEXT relative to project root.
\"/path/to/project/file.txt\" -> \"project/file.txt\""
(when text
(replace-regexp-in-string (regexp-quote (string-remove-suffix "/" (agent-shell-cwd)))
(file-name-base (string-remove-suffix "/" (agent-shell-cwd)))
(or text ""))))
(defun agent-shell-make-tool-call-label (state tool-call-id)
"Create tool call label from STATE using TOOL-CALL-ID."
(when-let ((tool-call (map-nested-elt state `(:tool-calls ,tool-call-id))))
(let* ((status (map-elt tool-call :status))
(status-label (when status
(agent-shell--status-label status)))
(kind (map-elt tool-call :kind))
(kind-label (when kind
(agent-shell--add-text-properties
(propertize (format " %s " kind) 'font-lock-face 'default)
'font-lock-face
`(:box t))))
(title (when (map-elt tool-call :title)
(agent-shell--shorten-paths (map-elt tool-call :title))))
(description (when (map-elt tool-call :description)
(agent-shell--shorten-paths (map-elt tool-call :description)))))
(concat
(when status-label
status-label)
(when (and status-label kind-label)
" ")
(when kind-label
kind-label)
(when (or title description)
" ")
(cond ((and title description
(not (equal (string-remove-prefix "`" (string-remove-suffix "`" (string-trim title)))
(string-remove-prefix "`" (string-remove-suffix "`" (string-trim description))))))
(concat
(propertize title 'font-lock-face 'font-lock-doc-markup-face)
" "
(propertize description 'font-lock-face 'font-lock-doc-face)))
(title
(propertize title 'font-lock-face 'font-lock-doc-markup-face))
(description
(propertize description 'font-lock-face 'font-lock-doc-markup-face)))))))
(defun agent-shell--format-plan (entries)
"Format plan ENTRIES for shell rendering."
(let* ((max-label-width
(apply #'max (cons 0 (mapcar (lambda (entry)
(length (agent-shell--status-label
(map-elt entry 'status))))
entries)))))
(mapconcat
(lambda (entry)
(let-alist entry
(let* ((status-label (agent-shell--status-label .status))
(label-length (length status-label))
;; Add 2 spaces to compensate box padding.
(padding (make-string
(max 1 (+ 2 (- max-label-width label-length)))
?\s)))
(concat
status-label
padding
.content))))
entries
"\n")))
(cl-defun agent-shell--make-button (&key text help kind action keymap)
"Make button with TEXT, HELP text, KIND, KEYMAP, and ACTION."
(let ((button (propertize
(format " %s " text)
'font-lock-face '(:box t)
'help-echo help
'pointer 'hand
'keymap (let ((map (make-sparse-keymap)))
(define-key map [mouse-1] action)
(define-key map (kbd "RET") action)
(define-key map [remap self-insert-command] 'ignore)
(when keymap
(set-keymap-parent map keymap))
map)
'button kind)))
button))
(defun agent-shell--add-text-properties (string &rest properties)
"Add text PROPERTIES to entire STRING and return the propertized string.
PROPERTIES should be a plist of property-value pairs."
(let ((str (copy-sequence string))
(len (length string)))
(while properties
(let ((prop (car properties))
(value (cadr properties)))
(if (memq prop '(face font-lock-face))
;; Merge face properties
(let ((existing (get-text-property 0 prop str)))
(put-text-property 0 len prop
(if existing
(list value existing)
value)
str))
;; Regular property replacement
(put-text-property 0 len prop value str))
(setq properties (cddr properties))))
str))
(cl-defun agent-shell--apply (&key function alist)
"Apply keyword ALIST to FUNCTION.
ALIST should be a list of keyword-value pairs like (:foo 1 :bar 2).
FUNCTION should be a function accepting keyword arguments (&key ...)."
(unless function
(error "Missing required argument: :function"))
(unless alist
(error "Missing required argument: :alist"))
(apply function
(mapcan (lambda (pair)
(list (car pair) (cdr pair)))
alist)))
(cl-defun agent-shell--start (&key no-focus new-session mode-line-name welcome-function
buffer-name shell-prompt shell-prompt-regexp
client-maker
needs-authentication
authenticate-request-maker
icon-name
install-instructions)
"Start an agent shell programmatically.
Set NO-FOCUS to start in background.
Set NEW-SESSION to start a separate new session.
Set MODE-LINE-NAME and BUFFER-NAME for display customization.
Set SHELL-PROMPT and SHELL-PROMPT-REGEXP for shell prompt display.
Set CLIENT-MAKER function to create the ACP client.
Set NEEDS-AUTHENTICATION if ACP agent requires client authentication.
Set AUTHENTICATE-REQUEST-MAKER to create authentication requests.
Set WELCOME-FUNCTION for custom welcome message.
Set INSTALL-INSTRUCTIONS for executable installation instructions.
Returns the shell buffer."
(unless (version<= "0.83.1" shell-maker-version)
(error "Please update shell-maker to version 0.83.1 or newer"))
(unless (version<= "0.3.1" acp-package-version)
(error "Please update acp.el to version 0.3.1 or newer"))
(with-temp-buffer ;; client-maker needs a buffer (use a temp one)
(unless (and client-maker (funcall client-maker (current-buffer)))
(error "No way to create a new client"))
(agent-shell--ensure-executable
(map-elt (funcall client-maker (current-buffer)) :command)
install-instructions))
(let* ((shell-maker-config (agent-shell--make-shell-maker-config
:prompt shell-prompt
:prompt-regexp shell-prompt-regexp))
(agent-shell--shell-maker-config shell-maker-config)
(default-directory (agent-shell-cwd))
(shell-buffer
(shell-maker-start agent-shell--shell-maker-config
no-focus
(or welcome-function #'shell-maker-welcome-message)
new-session
(concat buffer-name
" Agent @ "
(file-name-nondirectory
(string-remove-suffix "/" default-directory)))
mode-line-name)))
(with-current-buffer shell-buffer
;; Initialize buffer-local state
(setq-local agent-shell--state (agent-shell--make-state
:buffer shell-buffer
:client-maker client-maker
:needs-authentication needs-authentication
:authenticate-request-maker authenticate-request-maker))
;; Initialize buffer-local shell-maker-config
(setq-local agent-shell--shell-maker-config shell-maker-config)
(setq header-line-format (agent-shell--make-header
:icon-name icon-name
:title (concat buffer-name " Agent")
:location (string-remove-suffix "/" (abbreviate-file-name default-directory))))
(add-hook 'kill-buffer-hook #'agent-shell--clean-up nil t)
(sui-mode +1)
(when agent-shell-file-completion-enabled
(agent-shell-completion-mode +1)))