-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathpi-coding-agent-menu.el
More file actions
1720 lines (1606 loc) · 81.8 KB
/
Copy pathpi-coding-agent-menu.el
File metadata and controls
1720 lines (1606 loc) · 81.8 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
;;; pi-coding-agent-menu.el --- Transient menu and session management -*- lexical-binding: t; -*-
;; Copyright (C) 2026 Daniel Nouri
;; Author: Daniel Nouri <daniel.nouri@gmail.com>
;; Maintainer: Daniel Nouri <daniel.nouri@gmail.com>
;; URL: https://github.com/dnouri/pi-coding-agent
;; SPDX-License-Identifier: GPL-3.0-or-later
;; This file is not part of GNU Emacs.
;; This program 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 of the License, or
;; (at your option) any later version.
;;
;; This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Transient menu, session management, model selection, and command
;; infrastructure for pi-coding-agent.
;;
;; Key entry points:
;; `pi-coding-agent-menu' Transient menu (C-c C-p)
;; `pi-coding-agent-new-session' Start fresh session
;; `pi-coding-agent-resume-session' Resume previous session
;; `pi-coding-agent-reload' Restart pi process
;; `pi-coding-agent-select-model' Choose model interactively
;; `pi-coding-agent-select-thinking' Choose thinking level interactively
;; `pi-coding-agent-cycle-thinking' Cycle thinking levels from header-line
;; `pi-coding-agent-compact' Compact conversation context
;; `pi-coding-agent-fork' Fork from previous message
;;; Code:
(require 'cl-lib)
(require 'pi-coding-agent-render)
(require 'transient)
(defconst pi-coding-agent--minimum-transient-version "0.9.0"
"Minimum supported transient version.")
(defun pi-coding-agent--normalize-version (version)
"Return the numeric prefix of VERSION, or nil when none is present."
(when (and (stringp version)
(string-match "[0-9]+\\(?:\\.[0-9]+\\)*" version))
(match-string 0 version)))
(defun pi-coding-agent--version-at-least-p (version minimum)
"Return non-nil when VERSION satisfies MINIMUM.
VERSION may include a leading prefix like `v' or extra suffix text."
(let ((normalized (pi-coding-agent--normalize-version version)))
(and normalized
(not (version< normalized minimum)))))
(when (and (not (bound-and-true-p byte-compile-current-file))
(or (not (boundp 'transient-version))
(not (pi-coding-agent--version-at-least-p
transient-version
pi-coding-agent--minimum-transient-version))))
(display-warning 'pi-coding-agent
(format "pi-coding-agent requires transient >= %s, \
but %s is loaded.
Fix: upgrade transient from MELPA. If Emacs is using an older built-in
copy, set `package-install-upgrade-built-in' to t before running
M-x package-install RET transient RET, then restart Emacs."
pi-coding-agent--minimum-transient-version
(if (boundp 'transient-version)
transient-version
"unknown"))
:error))
;;;; Slash Commands via RPC
(defun pi-coding-agent--normalize-command (cmd &optional anchor)
"Normalize a command plist from the RPC wire format.
Lift `sourceInfo.scope' to `:location' and `sourceInfo.path' to
`:path' when present, mapping Pi's temporary scope to the menu's path bucket,
then drop the raw `:sourceInfo' key. Path values from
Pi are normalized to Emacs paths using ANCHOR or `default-directory'. Unsafe
passive backend path metadata is ignored rather than stored as navigable state.
Returns CMD (modified in place)."
(when-let* ((info (plist-get cmd :sourceInfo)))
(when-let* ((scope (plist-get info :scope)))
(plist-put cmd :location
(if (equal scope "temporary") "path" scope)))
(when-let* ((path (plist-get info :path)))
(plist-put cmd :path path))
(cl-remf cmd :sourceInfo))
(when-let* ((path (plist-get cmd :path)))
(if-let* ((emacs-path (pi-coding-agent--passive-emacs-path path anchor)))
(plist-put cmd :path emacs-path)
(cl-remf cmd :path)))
cmd)
(defun pi-coding-agent--fetch-commands (proc callback &optional anchor)
"Fetch available commands via RPC, call CALLBACK with result.
PROC is the pi process. CALLBACK receives the command list on success.
ANCHOR is the session directory used to normalize command source paths."
(pi-coding-agent--rpc-async proc '(:type "get_commands")
(lambda (response)
(when (eq (plist-get response :success) t)
(let* ((data (plist-get response :data))
(commands-vec (plist-get data :commands))
(commands (mapcar (lambda (cmd)
(pi-coding-agent--normalize-command
cmd anchor))
(append commands-vec nil))))
(funcall callback commands))))))
(defun pi-coding-agent--refresh-commands-ignoring-errors
(proc chat-buf generation anchor)
"Refresh CHAT-BUF commands from PROC without owning transition completion.
Synchronous command-fetch errors are reported but do not finish GENERATION;
state/history latches remain responsible for unlocking session switches once
those refreshes have been scheduled."
(condition-case err
(pi-coding-agent--fetch-commands
proc
(lambda (commands)
(when (pi-coding-agent--session-transition-current-p
chat-buf proc generation)
(with-current-buffer chat-buf
(pi-coding-agent--set-commands commands)
(pi-coding-agent--rebuild-commands-menu))))
anchor)
(error
(message "Pi: Failed to refresh commands - %s"
(error-message-string err)))))
;;;; Session Management
(defun pi-coding-agent--menu-state ()
"Return session state from the chat buffer.
State is buffer-local in the chat buffer; this accessor works
from either chat or input buffer."
(let ((chat-buf (pi-coding-agent--get-chat-buffer)))
(and chat-buf (buffer-local-value 'pi-coding-agent--state chat-buf))))
(defun pi-coding-agent--menu-model-description ()
"Return model description for transient menu."
(let* ((state (pi-coding-agent--menu-state))
(model (plist-get (plist-get state :model) :name))
(short (and model (pi-coding-agent--shorten-model-name model))))
(format "Model: %s" (or short "unknown"))))
(defun pi-coding-agent--menu-thinking-description ()
"Return thinking level description for transient menu."
(let* ((state (pi-coding-agent--menu-state))
(level (plist-get state :thinking-level)))
(format "Thinking: %s" (or level "off"))))
(defun pi-coding-agent--menu-description ()
"Return the transient menu summary line."
(concat (pi-coding-agent--menu-model-description) " • "
(pi-coding-agent--menu-thinking-description)))
(defun pi-coding-agent--menu-default-thinking-display-mode ()
"Return the completed-thinking display mode used for new chat buffers."
pi-coding-agent-thinking-display)
(defun pi-coding-agent--menu-current-thinking-display-mode ()
"Return the completed-thinking display mode for the linked chat buffer."
(let ((chat-buf (pi-coding-agent--get-chat-buffer)))
(if (and chat-buf (buffer-live-p chat-buf))
(with-current-buffer chat-buf
(pi-coding-agent--thinking-display-mode))
(pi-coding-agent--menu-default-thinking-display-mode))))
(defun pi-coding-agent--next-thinking-display-mode (mode)
"Return the thinking-display mode after MODE in the visible/hidden cycle."
(if (eq mode 'hidden) 'visible 'hidden))
(defclass pi-coding-agent--thinking-display-setting (transient-variable)
((getter :initarg :getter)
(setter :initarg :setter))
"Transient row that shows and changes a thinking-display mode.")
(cl-defmethod transient-init-value ((obj pi-coding-agent--thinking-display-setting))
"Initialize OBJ from its current thinking-display getter."
(oset obj value (funcall (oref obj getter))))
(cl-defmethod transient-infix-read ((obj pi-coding-agent--thinking-display-setting))
"Return the next visible/hidden thinking-display value for OBJ."
(pi-coding-agent--next-thinking-display-mode (oref obj value)))
(cl-defmethod transient-infix-set ((obj pi-coding-agent--thinking-display-setting) value)
"Set OBJ to VALUE using its configured thinking-display setter."
(funcall (oref obj setter) value)
(oset obj value value))
(cl-defmethod transient-format-value ((obj pi-coding-agent--thinking-display-setting))
"Format OBJ's current thinking-display value for the transient menu."
(propertize (symbol-name (oref obj value)) 'face 'transient-value))
;;;###autoload
(defun pi-coding-agent-new-session ()
"Start a new pi session (reset)."
(interactive)
(when-let* ((proc (pi-coding-agent--get-process))
(chat-buf (pi-coding-agent--get-chat-buffer)))
(pi-coding-agent--rpc-async proc '(:type "new_session")
(lambda (response)
(let* ((data (plist-get response :data))
(cancelled (plist-get data :cancelled)))
(if (and (eq (plist-get response :success) t)
(pi-coding-agent--json-false-p cancelled))
(when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(pi-coding-agent--clear-chat-buffer)
(pi-coding-agent--refresh-header))
(pi-coding-agent--refresh-session-state proc chat-buf)
(message "Pi: New session started"))
(message "Pi: New session cancelled")))))))
(defun pi-coding-agent--session-list-directory (&optional chat-buf)
"Return the directory containing CHAT-BUF's current JSONL session file.
Return nil when the current state has no usable session file. Relative
session file names are resolved from the chat buffer's stable session
directory."
(let ((chat-buf (or chat-buf (pi-coding-agent--get-chat-buffer))))
(when (and chat-buf (buffer-live-p chat-buf))
(with-current-buffer chat-buf
(when-let* ((session-file (plist-get pi-coding-agent--state
:session-file))
((stringp session-file))
((not (string-empty-p session-file))))
(when-let* ((emacs-session-file
(pi-coding-agent--emacs-path
session-file
(pi-coding-agent--chat-session-directory chat-buf))))
(pi-coding-agent--route-preserving-file-name-directory
emacs-session-file)))))))
(defun pi-coding-agent--with-session-list-directory (proc chat-buf callback)
"Call CALLBACK with the session list directory for CHAT-BUF.
When cached state has no session file, fetch fresh state from PROC first."
(if-let* ((session-dir (pi-coding-agent--session-list-directory chat-buf)))
(funcall callback session-dir)
(pi-coding-agent--rpc-async proc '(:type "get_state")
(lambda (response)
(when (and (eq (plist-get response :success) t)
(buffer-live-p chat-buf))
(pi-coding-agent--apply-state-response chat-buf response))
(when (buffer-live-p chat-buf)
(funcall callback
(pi-coding-agent--session-list-directory chat-buf)))))))
(defconst pi-coding-agent--session-line-type-re
"[ \t]*{[ \t]*\"type\"[ \t]*:[ \t]*\"%s\""
"Format string matching a JSONL line whose top-level type appears first.")
(defun pi-coding-agent--session-line-type-p (type)
"Return non-nil when the current line has top-level session TYPE.
Pi writes session JSONL with `type' as the first key. Matching that cheap
prefix lets resume count ordinary message lines without parsing their full
payloads."
(looking-at-p (format pi-coding-agent--session-line-type-re
(regexp-quote type))))
(defconst pi-coding-agent--session-metadata-fallback-max-line-length 8192
"Maximum line length parsed when the cheap session type prefix misses.")
(defun pi-coding-agent--session-current-line-data ()
"Parse the current JSONL line as a plist."
(json-parse-string (buffer-substring-no-properties
(point) (line-end-position))
:object-type 'plist))
(defun pi-coding-agent--session-small-current-line-data ()
"Parse the current line when it is small enough for metadata fallback."
(let ((end (line-end-position)))
(when (and (<= (- end (point))
pi-coding-agent--session-metadata-fallback-max-line-length)
(save-excursion
(skip-chars-forward " \t" end)
(< (point) end)))
(pi-coding-agent--session-current-line-data))))
(defun pi-coding-agent--session-first-message-text (data)
"Return first visible message text from parsed session DATA, or nil."
(let* ((message (plist-get data :message))
(content (plist-get message :content)))
(cond
((stringp content)
(unless (string-empty-p content) content))
((and (vectorp content) (> (length content) 0))
(plist-get (aref content 0) :text)))))
(defun pi-coding-agent--session-metadata (path)
"Extract metadata from session file PATH.
Returns plist with :modified-time, :first-message, :message-count,
:session-name, and :cwd, or nil on error. Session name comes from the
most recent session_info entry if present."
(condition-case nil
(let* ((attrs (file-attributes path))
(modified-time (file-attribute-modification-time attrs)))
(with-temp-buffer
(insert-file-contents path)
(let ((first-message nil)
(message-count 0)
(session-name nil)
(session-cwd nil)
(has-session-header nil))
(cl-labels
((apply-entry
(data &optional message-counted)
(pcase (plist-get data :type)
("message"
(unless message-counted
(setq message-count (1+ message-count)))
(unless first-message
(setq first-message
(pi-coding-agent--session-first-message-text
data))))
("session"
(setq has-session-header t
session-cwd
(pi-coding-agent--normalize-string-or-null
(plist-get data :cwd))))
("session_info"
(setq session-name
(pi-coding-agent--normalize-string-or-null
(plist-get data :name)))))))
(goto-char (point-min))
;; Count ordinary message lines by their cheap prefix. Only parse
;; session headers, session_info lines, and the first message whose
;; text is needed for the resume picker.
(while (not (eobp))
(cond
((pi-coding-agent--session-line-type-p "message")
(setq message-count (1+ message-count))
(unless first-message
(apply-entry (pi-coding-agent--session-current-line-data)
t)))
((or (pi-coding-agent--session-line-type-p "session")
(pi-coding-agent--session-line-type-p "session_info"))
(apply-entry (pi-coding-agent--session-current-line-data)))
(t
(when-let* ((data (pi-coding-agent--session-small-current-line-data)))
(apply-entry data))))
(forward-line 1)))
;; Only return metadata if we found a valid session header.
(when has-session-header
(list :modified-time modified-time
:first-message first-message
:message-count message-count
:session-name session-name
:cwd session-cwd)))))
(error nil)))
(defun pi-coding-agent--session-file-cwd-or-error (path)
"Return the recorded cwd from session file PATH, or signal `user-error'.
The returned directory is an Emacs path with a trailing slash. For remote
session files, the recorded process-local cwd is anchored to PATH's TRAMP
prefix. PATH must be a readable pi session file whose session header contains
a non-empty absolute cwd that names an existing directory."
(let ((session-file (pi-coding-agent--route-preserving-expand-file-name path)))
(unless (file-readable-p session-file)
(user-error "Session file is not readable: %s" session-file))
(let ((metadata (pi-coding-agent--session-metadata session-file)))
(unless metadata
(user-error "Not a pi session file: %s" session-file))
(let ((cwd (plist-get metadata :cwd)))
(unless (and (stringp cwd) (not (string-empty-p cwd)))
(user-error "Session file has no usable cwd: %s" session-file))
(when (file-remote-p cwd)
(user-error "Session file cwd must be process-local, not remote: %s\nSession file: %s"
cwd session-file))
(when (pi-coding-agent--remote-home-path-p cwd)
(user-error "Session file cwd must be absolute, not home-relative: %s\nSession file: %s"
cwd session-file))
(unless (file-name-absolute-p cwd)
(user-error "Session file cwd is not absolute: %s\nSession file: %s"
cwd session-file))
(let ((expanded-cwd (pi-coding-agent--emacs-directory cwd session-file)))
(unless (file-directory-p expanded-cwd)
(user-error "Stored session cwd is not an existing directory: %s\nSession file: %s"
expanded-cwd session-file))
expanded-cwd)))))
(defun pi-coding-agent--update-session-name-from-file (session-file)
"Update `pi-coding-agent--session-name' from SESSION-FILE metadata.
Call this from the chat buffer after switching or loading a session.
Return the parsed metadata, or nil when SESSION-FILE was not a pi session."
(when session-file
(let ((metadata (pi-coding-agent--session-metadata session-file)))
(setq pi-coding-agent--session-name (plist-get metadata :session-name))
metadata)))
(defun pi-coding-agent--session-entry (path)
"Return a resume-list entry for session file PATH, or nil.
The entry carries PATH and its parsed metadata so the resume picker does not
read the same JSONL file again while formatting completion choices."
(when-let* ((metadata (pi-coding-agent--session-metadata path)))
(list :path path :metadata metadata)))
(defun pi-coding-agent--list-session-entries (session-dir)
"List valid session entries in SESSION-DIR.
Entries are sorted by modification time with most recently used first."
(when (and session-dir (file-directory-p session-dir))
(let ((entries (delq nil
(mapcar #'pi-coding-agent--session-entry
(directory-files session-dir t
"\\.jsonl\\'")))))
(sort entries
(lambda (a b)
(time-less-p (plist-get (plist-get b :metadata) :modified-time)
(plist-get (plist-get a :metadata) :modified-time)))))))
(defun pi-coding-agent--list-sessions (session-dir)
"List valid session files in SESSION-DIR.
Returns absolute paths to JSONL pi sessions, sorted by modification time with
most recently used first."
(mapcar (lambda (entry) (plist-get entry :path))
(pi-coding-agent--list-session-entries session-dir)))
(defun pi-coding-agent--format-session-choice (path &optional metadata)
"Format session PATH for display in selector.
Returns (display-string . path) for `completing-read', or nil when PATH is not
a valid pi session. Prefers session name over first message when available.
Optional METADATA reuses data already collected by the session-list step."
(when-let* ((metadata (or metadata (pi-coding-agent--session-metadata path))))
(let* ((modified-time (plist-get metadata :modified-time))
(session-name (plist-get metadata :session-name))
(first-msg (plist-get metadata :first-message))
(msg-count (plist-get metadata :message-count))
(relative-time (pi-coding-agent--format-relative-time modified-time))
(label (cond
(session-name (pi-coding-agent--truncate-string session-name 50))
(first-msg (pi-coding-agent--truncate-string first-msg 50))
(t nil)))
(display (if label
(format "%s · %s (%d msgs)"
label relative-time msg-count)
(format "[empty session] · %s" relative-time))))
(cons display path))))
(defun pi-coding-agent--format-session-entry-choice (entry)
"Format resume-list ENTRY for display in the session selector."
(pi-coding-agent--format-session-choice
(plist-get entry :path)
(plist-get entry :metadata)))
(defun pi-coding-agent--uniquify-session-choices (choices)
"Return CHOICES with duplicate display strings made unique.
CHOICES is a list of (DISPLAY . PATH) pairs. Entries whose DISPLAY occurs
once are returned unchanged. Entries whose DISPLAY collides get their session
file base name appended."
(let ((counts (make-hash-table :test 'equal)))
(dolist (choice choices)
(puthash (car choice) (1+ (gethash (car choice) counts 0)) counts))
(mapcar
(lambda (choice)
(let ((display (car choice))
(path (cdr choice)))
(if (> (gethash display counts 0) 1)
(cons (format "%s · %s"
display
(file-name-base (directory-file-name path)))
path)
choice)))
choices)))
(defun pi-coding-agent--reset-session-state ()
"Reset all session-specific state for a new session.
Call this when starting a new session to ensure no stale state persists."
(dolist (marker (list pi-coding-agent--message-start-marker
pi-coding-agent--streaming-marker
pi-coding-agent--thinking-marker
pi-coding-agent--thinking-start-marker))
(when (markerp marker)
(set-marker marker nil)))
(setq pi-coding-agent--session-name nil
pi-coding-agent--cached-stats nil
pi-coding-agent--assistant-header-shown nil
pi-coding-agent--local-user-message nil
pi-coding-agent--extension-status nil
pi-coding-agent--working-message nil
pi-coding-agent--pre-compaction-status nil
pi-coding-agent--in-code-block nil
pi-coding-agent--in-thinking-block nil
pi-coding-agent--thinking-marker nil
pi-coding-agent--thinking-start-marker nil
pi-coding-agent--thinking-raw nil
pi-coding-agent--line-parse-state 'line-start
pi-coding-agent--pending-tool-overlay nil
pi-coding-agent--tool-block-order-counter 0
pi-coding-agent--thinking-block-order-counter 0)
(pi-coding-agent--set-activity-phase "idle" 'reset t)
(pi-coding-agent--clear-unsupported-extension-ui-warnings)
(pi-coding-agent--invalidate-history-loads)
(pi-coding-agent--finish-session-transition
pi-coding-agent--session-transition-generation)
;; Use accessors for cross-module state
(pi-coding-agent--cancel-followup-drain-timer)
(pi-coding-agent--invalidate-prompt-start-wait)
(pi-coding-agent--clear-followup-queue)
(pi-coding-agent--set-aborted nil)
(pi-coding-agent--set-canonical-messages nil)
(pi-coding-agent--set-message-start-marker nil)
(pi-coding-agent--set-streaming-marker nil)
(when pi-coding-agent--tool-args-cache
(clrhash pi-coding-agent--tool-args-cache))
(when pi-coding-agent--live-tool-blocks
(clrhash pi-coding-agent--live-tool-blocks)))
(defun pi-coding-agent--clear-chat-buffer ()
"Clear the chat buffer and display fresh startup header.
Used when starting a new session."
(when-let* ((chat-buf (pi-coding-agent--get-chat-buffer)))
(with-current-buffer chat-buf
(let ((inhibit-read-only t))
(pi-coding-agent--clear-render-artifacts)
(erase-buffer)
(insert (pi-coding-agent--format-startup-header))
(insert "\n")
(pi-coding-agent--reset-session-state)
(goto-char (point-max))))))
(defun pi-coding-agent--load-session-history
(proc callback &optional chat-buf completion-callback)
"Load and display session history from PROC.
Calls CALLBACK with message count when history is applied successfully.
CHAT-BUF is the target buffer; if nil, uses `pi-coding-agent--get-chat-buffer'.
Optional COMPLETION-CALLBACK is called after a current RPC response is handled,
even when the response failed or was not safe to render. Note: When called
from async callbacks, pass CHAT-BUF explicitly."
(let ((chat-buf (or chat-buf (pi-coding-agent--get-chat-buffer))))
(when (and chat-buf (buffer-live-p chat-buf))
(with-current-buffer chat-buf
(let ((generation (pi-coding-agent--invalidate-history-loads)))
(pi-coding-agent--rpc-async proc '(:type "get_messages")
(lambda (response)
(unwind-protect
(when (and (eq (plist-get response :success) t)
(buffer-live-p chat-buf))
(with-current-buffer chat-buf
(when (and (eq pi-coding-agent--process proc)
(= generation
pi-coding-agent--history-load-generation)
(pi-coding-agent--canonical-rerender-safe-p))
(let* ((messages (plist-get (plist-get response :data)
:messages))
(count (if (vectorp messages)
(length messages)
0)))
(pi-coding-agent--display-session-history
messages chat-buf)
;; Refresh header after loading history (resume/fork).
(pi-coding-agent--refresh-header)
(when callback
(funcall callback count))))))
(when completion-callback
(funcall completion-callback response))))))))))
(defun pi-coding-agent--session-transition-ready-p (chat-buf action)
"Return non-nil when CHAT-BUF may ACTION another session.
ACTION should be a short verb such as resume or fork for user messages."
(with-current-buffer chat-buf
(cond
((not (eq pi-coding-agent--status 'idle))
(message "Pi: Cannot %s while streaming" action)
nil)
((pi-coding-agent--session-busy-p)
(message "Pi: Cannot %s while Pi is busy" action)
nil)
(pi-coding-agent--local-user-message
(message "Pi: Wait for pi to echo your prompt before you %s" action)
nil)
(t t))))
(defun pi-coding-agent--make-session-transition-latch
(chat-buf proc generation count)
"Return a callback to finish transition GENERATION after COUNT invocations.
Only completions that still belong to CHAT-BUF, PROC, and GENERATION count, so
stale callbacks from older session switches cannot unlock newer transitions."
(let ((remaining count)
(finished nil))
(lambda (&rest _)
(when (and (not finished)
(pi-coding-agent--session-transition-current-p
chat-buf proc generation))
(setq remaining (1- remaining))
(when (<= remaining 0)
(setq finished t)
(when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(pi-coding-agent--finish-session-transition generation))))))))
(defun pi-coding-agent--refresh-transition-state-and-history
(proc chat-buf generation &optional session-file history-callback)
"Refresh state and history for CHAT-BUF through PROC in parallel.
The transition remains active until both the state and history RPC callbacks
for GENERATION have completed or failed. Synchronous scheduling errors finish
the transition before being re-signaled so the UI cannot stay wedged."
(let ((latch (pi-coding-agent--make-session-transition-latch
chat-buf proc generation 2)))
(condition-case err
(progn
(pi-coding-agent--refresh-session-state
proc chat-buf session-file generation latch)
(pi-coding-agent--load-session-history
proc history-callback chat-buf latch))
(error
(when (pi-coding-agent--session-transition-current-p
chat-buf proc generation)
(with-current-buffer chat-buf
(pi-coding-agent--finish-session-transition generation)))
(signal (car err) (cdr err))))))
(defun pi-coding-agent--refresh-session-state
(proc chat-buf &optional session-file generation completion-callback)
"Refresh session state for CHAT-BUF from PROC.
SESSION-FILE seeds the session-name cache when the switching action already
knows the selected file. Optional GENERATION ties the refresh to an existing
session transition; otherwise this function starts and finishes its own guard.
Optional COMPLETION-CALLBACK runs after a current get_state response is
handled, even when the response failed."
(when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(pi-coding-agent--set-canonical-messages nil)
(when session-file
(pi-coding-agent--update-session-name-from-file session-file))
(let* ((own-generation (null generation))
(generation (or generation
(pi-coding-agent--begin-session-transition))))
(pi-coding-agent--rpc-async proc '(:type "get_state")
(lambda (response)
(when (pi-coding-agent--session-transition-current-p
chat-buf proc generation)
(unwind-protect
(when (eq (plist-get response :success) t)
(pi-coding-agent--apply-state-response chat-buf response)
(when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(unless session-file
(when-let* ((current-session-file
(plist-get pi-coding-agent--state
:session-file)))
(pi-coding-agent--update-session-name-from-file
current-session-file)))
(force-mode-line-update t))))
(when completion-callback
(funcall completion-callback response))
(when (and own-generation (buffer-live-p chat-buf))
(with-current-buffer chat-buf
(pi-coding-agent--finish-session-transition
generation)))))))))))
;;;###autoload
(defun pi-coding-agent-reload ()
"Reload the current session by restarting the pi process.
Useful for reloading extensions, skills, prompts, and themes after
editing them, or when the pi process has died or become unresponsive.
Starts a fresh process, switches it back to the cached session file, then
replaces the old process, refreshes state and commands, and rebuilds the chat
buffer from session history."
(interactive)
(let* ((chat-buf (pi-coding-agent--get-chat-buffer))
(session-file (and chat-buf
(buffer-local-value 'pi-coding-agent--state chat-buf)
(plist-get (buffer-local-value 'pi-coding-agent--state chat-buf)
:session-file))))
(cond
((not chat-buf)
(message "Pi: No session to reload"))
((not session-file)
(message "Pi: No session file available - cannot reload"))
(t
(message "Pi: Reloading...")
(with-current-buffer chat-buf
(let ((dir (pi-coding-agent--session-directory)))
(unless (and (stringp dir)
(not (string-empty-p dir))
(file-name-absolute-p dir))
(user-error "Pi: Cannot reload from invalid session directory: %s"
dir))
(let ((session-path (pi-coding-agent--process-local-path
session-file dir))
(old-proc pi-coding-agent--process))
(setq pi-coding-agent--status 'idle)
(let* ((new-proc (pi-coding-agent--start-process dir))
(generation (pi-coding-agent--begin-session-transition
new-proc)))
(when (processp new-proc)
(set-process-buffer new-proc chat-buf)
(process-put new-proc 'pi-coding-agent-chat-buffer chat-buf)
(pi-coding-agent--register-display-handler new-proc)
(pi-coding-agent--rpc-async
new-proc
(list :type "switch_session" :sessionPath session-path)
(lambda (response)
(when (pi-coding-agent--session-transition-current-p
chat-buf new-proc generation)
(let* ((data (plist-get response :data))
(cancelled (plist-get data :cancelled)))
(if (and (eq (plist-get response :success) t)
(pi-coding-agent--json-false-p cancelled))
(let ((refresh-scheduled nil))
(condition-case err
(progn
(when (and (processp old-proc)
(not (eq old-proc new-proc)))
(pi-coding-agent--skip-process-kill-confirmation
old-proc)
(pi-coding-agent--unregister-display-handler
old-proc)
(when (process-live-p old-proc)
(delete-process old-proc)))
(when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(pi-coding-agent--set-process new-proc)))
(pi-coding-agent--refresh-transition-state-and-history
new-proc chat-buf generation session-file
(lambda (_count)
(message "Pi: Session reloaded")))
(setq refresh-scheduled t))
(error
(when (pi-coding-agent--session-transition-current-p
chat-buf new-proc generation)
(with-current-buffer chat-buf
(pi-coding-agent--finish-session-transition
generation)))
(message "Pi: Failed to reload - %s"
(error-message-string err))))
(when refresh-scheduled
(pi-coding-agent--refresh-commands-ignoring-errors
new-proc chat-buf generation dir)))
(pi-coding-agent--unregister-display-handler new-proc)
(when (process-live-p new-proc)
(delete-process new-proc))
(if (and cancelled
(not (pi-coding-agent--json-false-p cancelled)))
(message "Pi: Reload cancelled")
(message "Pi: Failed to reload - %s"
(or (plist-get response :error)
"unknown error")))
(when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(pi-coding-agent--finish-session-transition
generation)))))))))))))))))
(defun pi-coding-agent--resume-selected-session (proc chat-buf selected-path)
"Resume SELECTED-PATH using PROC and rebuild CHAT-BUF from its history."
(let* ((target-dir (pi-coding-agent--session-file-cwd-or-error selected-path))
(session (and (buffer-live-p chat-buf)
(pi-coding-agent--chat-session-name chat-buf)))
(existing-target (pi-coding-agent--find-session target-dir session)))
(when (and existing-target (not (eq existing-target chat-buf)))
(user-error "Pi session already open for: %s" target-dir))
(let* ((session-path (if (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(pi-coding-agent--process-local-path
selected-path
(pi-coding-agent--chat-session-directory chat-buf)))
(pi-coding-agent--process-local-path selected-path)))
(generation (when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(pi-coding-agent--begin-session-transition proc)))))
(pi-coding-agent--rpc-async
proc
(list :type "switch_session" :sessionPath session-path)
(lambda (response)
(when (pi-coding-agent--session-transition-current-p
chat-buf proc generation)
(let* ((data (plist-get response :data))
(cancelled (plist-get data :cancelled)))
(if (and (eq (plist-get response :success) t)
(pi-coding-agent--json-false-p cancelled))
(let ((refresh-scheduled nil))
(condition-case err
(progn
(when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(pi-coding-agent--retarget-session-buffers
target-dir)))
(pi-coding-agent--refresh-transition-state-and-history
proc chat-buf generation selected-path
(lambda (count)
(message "Pi: Resumed session (%d messages)" count)))
(setq refresh-scheduled t))
(error
(when (pi-coding-agent--session-transition-current-p
chat-buf proc generation)
(with-current-buffer chat-buf
(pi-coding-agent--finish-session-transition generation)))
(message "Pi: Failed to resume session - %s"
(error-message-string err))))
(when refresh-scheduled
(pi-coding-agent--refresh-commands-ignoring-errors
proc chat-buf generation target-dir)))
(message "Pi: Failed to resume session")
(when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(pi-coding-agent--finish-session-transition generation)))))))))))
(defun pi-coding-agent--resume-session-from-directory (proc chat-buf session-dir)
"Prompt for a session from SESSION-DIR, then resume it using PROC.
CHAT-BUF is rebuilt from the selected session history."
(let ((entries (pi-coding-agent--list-session-entries session-dir)))
(if (null entries)
(message "Pi: No previous sessions found")
(let* ((choices
(pi-coding-agent--uniquify-session-choices
(delq nil
(mapcar #'pi-coding-agent--format-session-entry-choice
entries))))
(choice-strings (mapcar #'car choices)))
(if (null choices)
(message "Pi: No previous sessions found")
(let* ((choice (completing-read
"Resume session: "
(lambda (string pred action)
(if (eq action 'metadata)
'(metadata (display-sort-function . identity))
(complete-with-action action choice-strings
string pred)))
nil t))
(selected-path (cdr (assoc choice choices))))
(when selected-path
(pi-coding-agent--resume-selected-session
proc chat-buf selected-path))))))))
(defun pi-coding-agent-resume-session ()
"Resume a previous pi session stored beside the current session file."
(interactive)
(when-let* ((proc (pi-coding-agent--get-process))
(chat-buf (pi-coding-agent--get-chat-buffer)))
(when (pi-coding-agent--session-transition-ready-p chat-buf "resume")
(pi-coding-agent--with-session-list-directory
proc chat-buf
(lambda (session-dir)
(cond
((not session-dir)
(message "Pi: Session file not available"))
((pi-coding-agent--session-transition-ready-p chat-buf "resume")
(pi-coding-agent--resume-session-from-directory
proc chat-buf session-dir))))))))
;;;; Model and Thinking
(defun pi-coding-agent-set-session-name (name)
"Set the session NAME for the current session.
The name is displayed in the resume picker and header-line."
(interactive
(let ((chat-buf (pi-coding-agent--get-chat-buffer)))
(list (read-string "Session name: "
(or (and chat-buf
(buffer-local-value 'pi-coding-agent--session-name chat-buf))
"")))))
(let* ((trimmed-name (string-trim name))
(chat-buf (pi-coding-agent--get-chat-buffer)))
(if (string-empty-p trimmed-name)
;; Consistent with TUI /name behavior
(let ((current-name (and chat-buf
(buffer-local-value 'pi-coding-agent--session-name chat-buf))))
(if current-name
(message "Pi: Session name: %s" current-name)
(message "Pi: No session name set")))
(let ((proc (pi-coding-agent--get-process)))
(unless proc
(user-error "No pi process running"))
(pi-coding-agent--rpc-async proc
(list :type "set_session_name" :name trimmed-name)
(lambda (response)
(if (eq (plist-get response :success) t)
(progn
(when (buffer-live-p chat-buf)
(with-current-buffer chat-buf
(setq pi-coding-agent--session-name trimmed-name)
(force-mode-line-update t)))
(message "Pi: Session name set to \"%s\"" trimmed-name))
(message "Pi: Failed to set session name: %s"
(or (plist-get response :error) "unknown error")))))))))
(defun pi-coding-agent-select-model (&optional initial-input)
"Select a model interactively.
Optional INITIAL-INPUT pre-fills the completion prompt for filtering."
(interactive)
(let ((proc (pi-coding-agent--get-process))
(chat-buf (pi-coding-agent--get-chat-buffer)))
(unless proc
(user-error "No pi process running"))
(let* ((state (pi-coding-agent--menu-state))
(response (pi-coding-agent--rpc-sync proc '(:type "get_available_models") 5))
(data (plist-get response :data))
(models (plist-get data :models))
(current-name (plist-get (plist-get state :model) :name))
(current-provider (plist-get (plist-get state :model) :provider))
(current-short (and current-name
(pi-coding-agent--shorten-model-name current-name)))
(current-display (and current-short current-provider
(format "%s [%s]" current-short current-provider)))
;; Build alist of (display-string . model-plist) for selection
;; Display includes provider for clarity
(model-alist (mapcar (lambda (m)
(let ((short (pi-coding-agent--shorten-model-name
(plist-get m :name)))
(prov (plist-get m :provider)))
(cons (format "%s [%s]" short (or prov "?"))
m)))
models))
(names (mapcar #'car model-alist))
(choice (let ((completion-ignore-case t)
(completion-styles '(basic flex)))
(if initial-input
;; Try auto-selecting on unique match
(let ((matches (completion-all-completions
initial-input names nil
(length initial-input))))
(when (consp matches)
(setcdr (last matches) nil))
(cond
((= (length matches) 1) (car matches))
((null matches)
(message "Pi: No model matching \"%s\"" initial-input)
nil)
(t (completing-read
(format "Model (current: %s): "
(or current-display "unknown"))
names nil t initial-input))))
(completing-read
(format "Model (current: %s): "
(or current-display "unknown"))
names nil t)))))
(when (and choice (not (equal choice current-display)))
(let* ((selected-model (cdr (assoc choice model-alist)))
(model-id (plist-get selected-model :id))
(provider (plist-get selected-model :provider)))
(pi-coding-agent--rpc-async proc (list :type "set_model"
:provider provider
:modelId model-id)
(lambda (resp)
(when (and (eq (plist-get resp :success) t)
(buffer-live-p chat-buf))
(with-current-buffer chat-buf
(pi-coding-agent--update-state-from-response resp)
(force-mode-line-update))
(message "Pi: Model set to %s" choice)))))))))
(defconst pi-coding-agent--thinking-levels '("off" "minimal" "low" "medium" "high" "xhigh")
"Thinking levels accepted by `set_thinking_level' RPC.
Unsupported levels are clamped to the current model's capabilities.")
(defun pi-coding-agent-cycle-thinking ()
"Cycle through thinking levels."
(interactive)
(when-let* ((proc (pi-coding-agent--get-process))
(chat-buf (pi-coding-agent--get-chat-buffer)))
(pi-coding-agent--rpc-async proc '(:type "cycle_thinking_level")
(lambda (response)
(when (and (eq (plist-get response :success) t)
(buffer-live-p chat-buf))
(with-current-buffer chat-buf
(pi-coding-agent--update-state-from-response response)
(force-mode-line-update)
(message "Pi: Thinking level: %s"
(plist-get pi-coding-agent--state :thinking-level))))))))
(defun pi-coding-agent--refresh-thinking-level-state (proc chat-buf)
"Refresh CHAT-BUF state from PROC after a thinking-level change.
Uses `get_state' so the UI reflects the server's actual level,
including any model-specific clamping."
(pi-coding-agent--rpc-async
proc '(:type "get_state")
(lambda (response)
(if (eq (plist-get response :success) t)
(let* ((data (plist-get response :data))
(level (or (plist-get data :thinkingLevel) "off")))
(pi-coding-agent--apply-state-response chat-buf response)
(message "Pi: Thinking level: %s" level))
(message "Pi: Thinking level updated, but failed to refresh state%s"
(if-let* ((error-text (plist-get response :error)))
(format ": %s" error-text)
""))))))
(defun pi-coding-agent-select-thinking ()
"Select a thinking level from the minibuffer."
(interactive)
(let ((proc (pi-coding-agent--get-process))
(chat-buf (pi-coding-agent--get-chat-buffer)))
(unless proc
(user-error "No pi process running"))
(unless chat-buf
(user-error "No pi session buffer"))
(let* ((state (pi-coding-agent--menu-state))
(current (or (plist-get state :thinking-level) "off"))
(choice (completing-read
(format "Thinking level (current: %s): " current)
pi-coding-agent--thinking-levels