-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent-shell-queue.el
More file actions
6752 lines (6199 loc) · 328 KB
/
Copy pathagent-shell-queue.el
File metadata and controls
6752 lines (6199 loc) · 328 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-queue.el --- Persistent prompt queue for agent-shell -*- lexical-binding: t -*-
;; Author: tycho garen
;; Maintainer: tychoish
;; Keywords: tools, agent-shell
;; Version: 0.1.0
;; URL: https://github.com/tychoish/dot-emacs
;; Package-Requires: ((emacs "29.1") (transient "0.4") (agent-shell "0.1") (alert "1.2"))
;; 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:
;; Implements a persistent prompt queue for agent-shell sessions, supporting
;; multi-session dispatch with pause, resume, and archive lifecycle management.
;; Queue state is serialized to plist, JSON, or YAML for session persistence
;; across Emacs restarts. Interactive capture, edit, and item-view buffers
;; allow queue manipulation without leaving Emacs. Fork operations split a
;; queue across multiple sessions for parallel workloads.
;;; Code:
(require 'cl-lib)
(require 'agent-shell)
(require 'annotated-completing-read)
(require 'transient)
(require 'alert)
(require 'agent-shell-queue-persistence)
(defface agent-shell-queue-blocked-face
'((t :foreground "darkorange3"))
"Face for queue items that are paused, deferred, or blocked.")
(defface agent-shell-queue-unassigned-face
'((t :foreground "cornflowerblue"))
"Face for queue items not yet assigned to any shell.")
(defface agent-shell-queue-detached-face
'((t :foreground "orange" :slant italic))
"Face for queue items whose target shell buffer no longer exists.")
(defface agent-shell-queue-compact-face
'((t :foreground "steelblue3"))
"Face for compact (non-LLM manual) work items.")
(defface agent-shell-queue-draft-face
'((t :foreground "gray50" :slant italic))
"Face for queue items saved as drafts (not yet queued for dispatch).")
(defconst agent-shell-queue--unassigned-key "(unassigned)"
"Alist bucket key for items not yet assigned to any shell.")
(defconst agent-shell-queue--dir-prefix "dir:"
"Prefix string identifying a directory-scoped queue bucket.")
(defun agent-shell-queue--canonicalize-dir (dir)
"Return expanded, canonicalized directory path for DIR."
(file-name-as-directory (expand-file-name (or dir default-directory))))
(defun agent-shell-queue--dir-bucket-p (bucket-name)
"Return non-nil if BUCKET-NAME is a directory queue bucket string."
(and (stringp bucket-name)
(string-prefix-p agent-shell-queue--dir-prefix bucket-name)))
(defun agent-shell-queue--dir-from-bucket (bucket-name)
"Extract directory path from BUCKET-NAME string, or nil if not a directory bucket."
(when (agent-shell-queue--dir-bucket-p bucket-name)
(substring bucket-name (length agent-shell-queue--dir-prefix))))
(defun agent-shell-queue--bucket-for-dir (dir)
"Return the directory queue bucket string for DIR."
(concat agent-shell-queue--dir-prefix (agent-shell-queue--canonicalize-dir dir)))
(defun agent-shell-queue--pick-shell-for-directory (dir item-id)
"Create an `agent-shell' buffer for DIR associated with ITEM-ID.
Creates a new shell in DIR via `agent-shell-new-shell' and appends `-ITEM-ID'
to its buffer name."
(let* ((canon-dir (agent-shell-queue--canonicalize-dir dir))
(before-bufs (agent-shell-buffers))
(default-directory canon-dir)
(buf (agent-shell-new-shell)))
(unless (and (bufferp buf) (buffer-live-p buf))
(setq buf (seq-find (lambda (b) (not (memq b before-bufs))) (agent-shell-buffers))))
(when (and buf (buffer-live-p buf))
(with-current-buffer buf
(when item-id
(rename-buffer (concat (buffer-name buf) "-" item-id) t))))
buf))
(declare-function shell-maker-busy "shell-maker")
(declare-function markdown-mode "markdown-mode")
(declare-function yaml-encode "yaml")
(declare-function yaml-parse-string "yaml")
(declare-function yaml-mode "yaml-mode")
(declare-function json-pretty-print-buffer "json")
(declare-function agent-shell-menu--session-shell-buffer "agent-shell-menu")
(defun agent-shell-queue--default-instance-name ()
"Return a string identifying the current Emacs instance."
(let ((d (daemonp)))
(cond ((eq d t) "primary")
(d d)
(t (system-name)))))
(defvar agent-shell-queue-instance-name #'agent-shell-queue--default-instance-name
"Instance identifier written into archive records.
May be a string or a zero-argument function that returns a string.
Defaults to the daemon name or system hostname. Override in config:
(setq agent-shell-queue-instance-name \"<name>\")
(setq agent-shell-queue-instance-name \\='get-instance-name")
;;; Configuration
(defcustom agent-shell-queue-default-pause-delay 0
"Default pause duration in seconds after one task completes before the next task runs.
Set to 0 or nil for no delay."
:type '(choice (const :tag "No delay" 0)
(integer :tag "Seconds")
(float :tag "Float seconds"))
:group 'agent-shell-queue)
(defcustom agent-shell-queue-alert-on-pause-start nil
"When non-nil, send an alert notification when a task pause or delay starts.
The notification message includes the duration of the pause."
:type 'boolean
:group 'agent-shell-queue)
(defcustom agent-shell-queue-alert-before-pause-end nil
"Duration in seconds before a pause ends to send an alert notification.
When non-nil and less than the total pause duration, an alert is sent when
`(total-pause-duration - alert-before-pause-end)` seconds elapses."
:type '(choice (const :tag "Disabled" nil)
(integer :tag "Seconds")
(float :tag "Float seconds"))
:group 'agent-shell-queue)
(defvar agent-shell-queue-serialization-format 'plist
"Format used to persist queue state to disk.
One of:
`plist' — s-expression with keyword-keyed plists (default; no extra deps)
`json' — JSON via built-in `json-serialize'/`json-parse-string' (Emacs 27+)
`yaml' — YAML via `yaml-encode'/`yaml-parse-string' from the `yaml' package")
(defvar agent-shell-queue-idle-delay 60.0
"Idle delay in seconds for the backup auto-send timer.
Primary draining happens via `shell-maker-finish-output' advice; this timer
is only a safety net for buffers that become idle outside that path.")
(defvar agent-shell-queue-background-prefix '((omp . "/background ") (t . "/background "))
"Alists of symbols mapping `<agent-shell-identifier>` to background command prefix string, or a function/value.")
(defvar agent-shell-queue-clear-command '((omp . "/fresh") (t . "/clear"))
"Alists of symbols mapping `<agent-shell-identifier>` to clear command string, or a function/value.")
(defun agent-shell-queue--get-background-prefix (buf)
"Resolve the background prefix for BUF based on its agent-shell configuration."
(let* ((buffer (get-buffer buf))
(config (and buffer (fboundp 'agent-shell-get-config) (agent-shell-get-config buffer)))
(ident (and config (map-elt config :identifier)))
(val agent-shell-queue-background-prefix))
(cond
((functionp val) (funcall val ident))
((listp val) (or (cdr (assq ident val)) (cdr (assq t val)) "/background "))
(t val))))
(defun agent-shell-queue--get-clear-command (buf)
"Resolve the clear command for BUF based on its agent-shell configuration."
(let* ((buffer (get-buffer buf))
(config (and buffer (fboundp 'agent-shell-get-config) (agent-shell-get-config buffer)))
(ident (and config (map-elt config :identifier)))
(val agent-shell-queue-clear-command))
(cond
((functionp val) (funcall val ident))
((listp val) (or (cdr (assq ident val)) (cdr (assq t val)) "/clear"))
(t val))))
(defvar agent-shell-queue-done-log-file nil
"File path for appending completed queue items as JSON lines.
When nil (the default), completed items are not logged to disk.")
(defvar agent-shell-queue-state-file-function #'agent-shell-queue--default-state-file
"Function returning the path to the queue state file.")
(defvar agent-shell-queue-pick-buffer-function #'agent-shell-queue--default-pick-buffer
"Function called with a PROMPT string to pick an agent-shell buffer.")
(defvar agent-shell-queue-archive-enabled nil
"When non-nil, completed items can be archived and `agent-shell-queue-buffer-archive'
is active. The destination path is controlled separately by
`agent-shell-queue-archive-file-function'. Set to t to enable archiving.")
(defvar agent-shell-queue-archive-file-function #'agent-shell-queue--default-archive-file
"Function returning the JSONL archive file path. Called with no arguments.
Override to store the archive at a custom location. Only consulted when
`agent-shell-queue-archive-enabled' is non-nil.")
(defcustom agent-shell-queue-response-max-length 8192
"Maximum length (in characters) of captured response text to store.
Responses longer than this are truncated with a \"…[truncated]\" suffix.
This prevents very large responses from bloating the queue state file.
Set to nil to disable truncation and store full responses.
Default: 8192 (8KB) — balances completeness with file size."
:type '(choice (integer :tag "Max length in characters")
(const :tag "No limit (store full responses)" nil))
:group 'agent-shell-queue)
(defconst agent-shell-queue-response-max-length-absolute 1048576
"Absolute maximum length (1MB) for response text, regardless of configuration.
This hard limit prevents pathological cases from consuming excessive memory
or creating unmanageable state files. Applies even when
`agent-shell-queue-response-max-length' is nil.")
(defvar agent-shell-queue--last-flush-time nil
"Float-time of the most recent queue state write to disk.")
(defvar agent-shell-queue--next-flush-time nil
"Time of the next scheduled auto-flush, or nil if none is pending.")
(defvar agent-shell-queue-auto-flush-interval 300
"Seconds between automatic queue flushes. Set to nil to disable.")
(defvar agent-shell-queue--stale-item-ids nil
"List of item IDs that failed dispatch due to struct mismatch after code reload.
These are automatically deferred and their buffers paused.")
(defvar agent-shell-queue-before-reload-hook nil
"Hook run just before code and state are reloaded.
Queue is paused and flushed to disk before this hook fires.")
(defvar agent-shell-queue-after-reload-hook nil
"Hook run after code and state have been reloaded from disk.")
(defvar agent-shell-queue--wait-timers nil
"Alist of (ITEM-ID . TIMER) for active wait-until items.
Timers are cancelled automatically when items are removed or the queue reloads.")
(defvar agent-shell-queue--compact-running nil
"List of (BUF-NAME . ITEM-ID) pairs for compact items currently dispatched.
Used by `agent-shell-queue-mark-done' to clean up session-pause state.")
(defvar agent-shell-queue--remove-all-confirmed nil
"When non-nil, skip per-item confirmation in remove commands.
Set to t when user answers \\='a\\=' (all) at a removal prompt.")
(defvar agent-shell-queue--response-start-positions nil
"Alist of (ITEM-ID . BUFFER-POSITION) recording where in the shell buffer
each dispatched LLM prompt begins. Used to capture the response text on
turn-complete and store it in the item's response field.")
(defvar agent-shell-queue-save-function nil
"When non-nil, called instead of the default file-based save logic.
The function is called with no arguments and must persist the current
queue items to a durable store.
Used by backends such as `agent-shell-queue-db' to bypass file I/O.")
(defvar agent-shell-queue-load-function nil
"When non-nil, called instead of the default file-based load logic.
The function is called with no arguments and must populate
the queue items from a durable store.
Used by backends such as `agent-shell-queue-db' to bypass file I/O.")
(defvar agent-shell-queue-safe-save nil
"When non-nil, write a versioned backup before each queue state save.
Backups are written to `agent-shell-queue-safe-save-directory' using the
format selected by `agent-shell-queue-safe-save-format'.
Has no effect when `agent-shell-queue-save-function' is set.")
(defvar agent-shell-queue-safe-save-directory nil
"Directory for versioned queue backups written when `agent-shell-queue-safe-save' is non-nil.
Nil means use a subdirectory of `temporary-file-directory' named
\"emacs-<instance>\" where <instance> comes from `agent-shell-queue-instance-name'.")
(defvar agent-shell-queue-safe-save-format nil
"Serialization format for safe-save backups, or nil to use `agent-shell-queue-serialization-format'.")
(defvar agent-shell-queue-safe-save-max-files nil
"Maximum number of versioned backup files to keep in the safe-save directory.
When non-nil and the backup count exceeds this limit, the oldest file is
deleted after each save — one file at a time so lowering the limit converges
gradually. Requires `agent-shell-queue-safe-save'.")
(defvar agent-shell-queue-idle-flush-delay nil
"Seconds of Emacs idle time after which the queue state is flushed to disk.
Set to nil to disable idle-triggered saves (default).")
(defvar agent-shell-queue-stall-timeout 180
"Seconds after dispatch before a still-running item is reported as stalled.
The ACP/shell-maker layer has no watchdog of its own: a wedged Lisp event
loop or a desynced busy flag leaves a dispatched item showing `running'
with no further user-visible feedback, indefinitely. This is a one-shot
check, not a retry loop — it only surfaces the condition via `alert', it
does not cancel or resend the item. Set to nil to disable.")
;;; macros
(defmacro with-agent-shell-queue (&rest body)
"Evaluate BODY inside the queue load/save/refresh lifecycle.
Ensures the queue is loaded before BODY runs, then persists state and
refreshes the queue display after BODY completes. Returns the value of
BODY's last form. Does not protect against errors — if BODY signals,
the save and refresh are skipped."
(declare (indent defun))
`(progn
(agent-shell-queue--ensure-loaded)
(prog1
(progn ,@body)
(agent-shell-queue--save)
(agent-shell-queue--refresh-buffer))))
(defmacro agent-shell-queue--defstruct (type-name &rest field-specs)
"Define a cl-defstruct TYPE-NAME with FIELD-SPECS and generate plist serializers.
Each spec in FIELD-SPECS is either a plain symbol or (SYMBOL &rest OPTIONS).
Supported options:
:no-serialize t — skip this field in to-plist and from-plist
:alias KEYWORD — also try KEYWORD when reading from plist (backward compat)
:to-plist FUNC — call (FUNC raw-value) when writing this field to a plist
:from-plist FUNC — call (FUNC plist-value) when reading this field from a plist
Generates constructor TYPE-NAME--make plus:
TYPE-NAME-to-plist — struct → keyword-keyed plist
TYPE-NAME-from-plist — keyword-keyed plist → struct"
(declare (indent 1))
(let* ((sname (symbol-name type-name))
(ctor (intern (concat sname "--make")))
(to-fn (intern (concat sname "-to-plist")))
(from-fn (intern (concat sname "-from-plist")))
(parsed (seq-map (lambda (spec)
(if (symbolp spec)
(list spec nil nil nil nil)
(let ((sym (car spec))
(opts (cdr spec)))
(list sym
(plist-get opts :no-serialize)
(plist-get opts :alias)
(plist-get opts :to-plist)
(plist-get opts :from-plist)))))
field-specs))
(field-names (seq-map #'car parsed))
(serializable (seq-remove (lambda (p) (pcase-let ((`(,_ ,no-ser . ,_) p)) no-ser)) parsed)))
`(progn
(cl-defstruct (,type-name (:constructor ,ctor) (:copier nil))
,@field-names)
(defun ,to-fn (item)
,(format "Convert %s ITEM to a keyword-keyed plist." sname)
(list ,@(cl-mapcan
(lambda (p)
(pcase-let ((`(,f ,_ ,_ ,to-plist-fn ,_) p))
(let* ((kw (intern (concat ":" (symbol-name f))))
(raw `(,(intern (concat sname "-" (symbol-name f))) item)))
(list kw (if to-plist-fn `(,to-plist-fn ,raw) raw)))))
serializable)))
(defun ,from-fn (plist)
,(format "Reconstruct a %s from keyword-keyed PLIST." sname)
(,ctor ,@(cl-mapcan
(lambda (p)
(pcase-let ((`(,f ,_ ,alias ,_ ,from-plist-fn) p))
(let* ((kw (intern (concat ":" (symbol-name f))))
(raw (if alias
`(or (plist-get plist ,kw) (plist-get plist ,alias))
`(plist-get plist ,kw))))
(list kw (if from-plist-fn `(,from-plist-fn ,raw) raw)))))
serializable))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Registries
(cl-defstruct (agent-shell-queue-executor
(:constructor agent-shell-queue-executor--make)
(:copier nil))
"Registry entry pairing a serializable NAME with an EXECUTOR function,
an optional CAPTURE function, and an optional CREATE function.
EXECUTOR: (item args) — called by `agent-shell-queue-send-item' to dispatch.
CAPTURE: () — called during item creation to produce the args value;
nil means fall back to the standard text-capture buffer.
CREATE: () — called by `agent-shell-queue-buffer-open-shell' when the
associated buffer is dead; should create and return a new
buffer of the same type, or nil to decline."
name executor capture create)
(defvar agent-shell-queue--executors nil
"List of `agent-shell-queue-executor' entries.
Only executors present here survive serialization. Register entries with
`agent-shell-queue-register-executor'.")
(defun agent-shell-queue-register-executor (name executor &optional capture create)
"Register EXECUTOR (and optional CAPTURE and CREATE) under NAME.
NAME may be a string or symbol; it is coerced to a string. Re-registering
an existing name replaces the entry. The name is written into serialized
queue state, so it must be stable across Emacs restarts.
CREATE, when provided, is a zero-arg function called by
`agent-shell-queue-buffer-open-shell' when the associated buffer is dead; it
should create and return a new buffer of the same type.
Returns EXECUTOR."
(let ((name-str (cond
((symbolp name) (symbol-name name))
((stringp name) name)
(t (user-error "impossible type for %s" name)))))
(setq agent-shell-queue--executors
(cons (agent-shell-queue-executor--make
:name name-str
:executor executor
:capture capture
:create create)
(seq-remove (lambda (e)
(equal name-str (agent-shell-queue-executor-name e)))
agent-shell-queue--executors)))
executor))
(defun agent-shell-queue--find-executor (name)
"Return the `agent-shell-queue-executor' entry for NAME, or nil."
(seq-find (lambda (e) (equal name (agent-shell-queue-executor-name e)))
agent-shell-queue--executors))
(defun agent-shell-queue--executor-name (fn)
"Return the registry name for FN, or nil if not registered."
(when-let* ((e (seq-find (lambda (e) (eq fn (agent-shell-queue-executor-executor e)))
agent-shell-queue--executors)))
(agent-shell-queue-executor-name e)))
(defun agent-shell-queue--executor-from-plist (name)
"Deserialize executor NAME via the registry.
Returns nil (kind-dispatch) when NAME is nil or not found; emits a
warning for non-nil names that have no registry entry."
(when name
(if-let* ((e (agent-shell-queue--find-executor name)))
(agent-shell-queue-executor-executor e)
(progn
(message "agent-shell-queue: unknown executor %S — item will use kind dispatch" name)
nil))))
(cl-defstruct (agent-shell-queue-item-type
(:constructor agent-shell-queue-item-type--make)
(:copier nil))
"Registry entry describing a queue item kind with its capabilities.
KIND: symbol — the :kind field value for items of this type.
LABEL: string — display name (Kind column and menus).
BUFFER-PRED: (lambda (buf)) → bool | nil means any buffer including unassigned.
DISPATCH-FN: (lambda (item buf-name)) — executes the item when dispatched.
INPUT-SPEC: plist describing how to collect user input:
(:kind capture :mode MODE) open capture buffer in MODE (nil → capture-mode)
(:kind read :prompt P :fn F) single read via function F called with P
(:kind none) no user input; args will be empty
(:kind special :fn F) zero-arg interactive function F handles everything"
kind label buffer-pred dispatch-fn input-spec)
(defvar agent-shell-queue--item-types nil
"List of `agent-shell-queue-item-type' entries.
Register entries with `agent-shell-queue-register-item-type'.
Built-in registrations are added at the end of this file.")
(defcustom agent-shell-queue-strict-buffer-assignment nil
"When non-nil, signal `user-error' when no compatible live buffer exists.
When nil (default), fall through to nil/unassigned assignment instead."
:type 'boolean
:group 'agent-shell-queue)
(cl-defun agent-shell-queue-register-item-type (&key kind label buffer-pred dispatch-fn input-spec)
"Register an item type in `agent-shell-queue--item-types'.
KIND is a symbol; re-registering an existing KIND replaces the entry.
See `agent-shell-queue-item-type' for field documentation."
(setq agent-shell-queue--item-types
(cons (agent-shell-queue-item-type--make
:kind kind :label label :buffer-pred buffer-pred
:dispatch-fn dispatch-fn :input-spec input-spec)
(seq-remove (lambda (e) (eq kind (agent-shell-queue-item-type-kind e)))
agent-shell-queue--item-types))))
(defun agent-shell-queue--type-for-kind (kind)
"Return the `agent-shell-queue-item-type' for KIND symbol, or nil."
(seq-find (lambda (e) (eq kind (agent-shell-queue-item-type-kind e)))
agent-shell-queue--item-types))
(defun agent-shell-queue--types-for-buffer (buf)
"Return item types compatible with BUF.
nil BUF (unassigned) accepts all types."
(if (null buf)
agent-shell-queue--item-types
(seq-filter (lambda (type)
(let ((pred (agent-shell-queue-item-type-buffer-pred type)))
(or (null pred) (funcall pred buf))))
agent-shell-queue--item-types)))
(defun agent-shell-queue--validate-kind-for-buffer (kind buf-or-nil)
"Signal `user-error' when KIND is incompatible with BUF-OR-NIL.
nil BUF-OR-NIL (unassigned) always accepts any kind. Returns t on success."
(when-let* ((buf buf-or-nil)
(type (agent-shell-queue--type-for-kind kind))
(pred (agent-shell-queue-item-type-buffer-pred type)))
(unless (funcall pred buf)
(user-error "Item kind '%s' cannot be assigned to buffer '%s'"
(agent-shell-queue-item-type-label type)
(buffer-name buf))))
t)
(defun agent-shell-queue--kind-needs-session-p (kind)
"Return non-nil when KIND requires agent-shell session-mode compatibility."
(when-let* ((type (agent-shell-queue--type-for-kind kind)))
(eq (agent-shell-queue-item-type-buffer-pred type)
#'agent-shell-queue--agent-shell-buffer-p)))
;;; Data model
(agent-shell-queue--defstruct agent-shell-queue-item
id
(args :alias :prompt)
status
kind
background
created
dispatched
completed
response
outcome
directory
(executor
:to-plist agent-shell-queue--executor-name
:from-plist agent-shell-queue--executor-from-plist)
;; Interjection fields — v1: one interjection per item.
;; interjection-prompt: text user typed; interjection-result: agent reply.
(interjection-prompt :no-serialize t)
(interjection-result :no-serialize t)
;; Re-enqueue tracking: reenqueued-from is the ID of the item this was
;; cloned from; reenqueued-as is a list of IDs created by re-enqueueing this.
reenqueued-from
reenqueued-as
(delay-before :alias :delay-before-dispatch)
(delay-after :alias :delay-after-complete))
(defun agent-shell-queue--item-well-formed-p (item)
"Return non-nil when ITEM has the minimum shape the queue UI requires.
Guards against a malformed persisted item (nil id/args/status) reaching
`agent-shell-queue-buffer-refresh', which errors on `split-string' with a
non-string ARGS."
(and (agent-shell-queue-item-id item)
(stringp (agent-shell-queue-item-args item))
(agent-shell-queue-item-status item)))
(defun agent-shell-queue--migrate-item-if-stale (item)
"Return ITEM or a current-layout copy with missing slots defaulted to nil.
Compares the vector length of ITEM against a freshly constructed default
instance; if shorter, copies the available slots into the new struct by index.
New trailing slots are left at nil. Handles future field additions without
modification. Returns nil (logging via `message') when ITEM cannot be
migrated to something matching `agent-shell-queue--item-well-formed-p' --
e.g. a persisted item so truncated that no fields overlap the current layout."
(let* ((current (agent-shell-queue-item--make))
(old-len (length item))
(new-len (length current))
(migrated (if (= old-len new-len)
item
(dotimes (i (1- (min old-len new-len)))
(aset current (1+ i) (aref item (1+ i))))
current)))
(if (agent-shell-queue--item-well-formed-p migrated)
migrated
(message "agent-shell-queue: dropping malformed item during migration: %S" migrated)
nil)))
(defun agent-shell-queue--migrate-all-stale-items ()
"Upgrade every in-memory item to the current struct layout.
Replaces old-format items (missing the outcome slot) in the live store with
freshly constructed equivalents, dropping any that come out malformed. Safe
to call repeatedly; up-to-date items are returned unchanged by
`agent-shell-queue--migrate-item-if-stale'."
(seq-do (lambda (bucket)
(setcdr bucket (seq-keep #'agent-shell-queue--migrate-item-if-stale (cdr bucket))))
(agent-shell-queue-store-items agent-shell-queue--store)))
(defun agent-shell-queue--migrate-deferred-statuses ()
"Convert any remaining `deferred' items to `blocked.skip' after load."
(seq-do (lambda (bucket)
(seq-do (lambda (item)
(when (eq (agent-shell-queue-item-status item) 'deferred)
(setf (agent-shell-queue-item-status item) 'blocked.skip)))
(cdr bucket)))
(agent-shell-queue-store-items agent-shell-queue--store)))
(defun agent-shell-queue--blocked-status-p (status)
"Return non-nil if STATUS is any blocked.* symbol."
(and status (string-prefix-p "blocked." (symbol-name status))))
(defun agent-shell-queue--blocked-p (item)
"Return non-nil if ITEM has any blocked.* status."
(agent-shell-queue--blocked-status-p (agent-shell-queue-item-status item)))
(cl-defstruct (agent-shell-queue-store
(:constructor agent-shell-queue--make-store)
(:copier nil))
"Queue state bundle: items, serialization format, and file path."
items ; (BUFFER-NAME . ITEM-LIST) alist
format ; symbol: plist | json | yaml
file) ; string: absolute path to state file
(defvar agent-shell-queue--items nil
"Items alist used by format-specific serializers (e.g. org).
Bound dynamically by `agent-shell-queue--serialize-items' methods
before calling the format's serialize helper.")
(defvar agent-shell-queue--store
(agent-shell-queue--make-store :items nil :format 'plist :file nil)
"Live queue store. Items are loaded from disk by --load, written by --save.")
(defun agent-shell-queue--sanitize-bucket (pair)
"Return PAIR with any malformed items removed, logging drops."
(let* ((before (cdr pair))
(after (seq-filter #'agent-shell-queue--item-well-formed-p before))
(dropped (- (length before) (length after))))
(when (> dropped 0)
(message "agent-shell-queue: dropped %d malformed item%s from bucket %s"
dropped (if (= dropped 1) "" "s") (car pair)))
(cons (car pair) after)))
(defun agent-shell-queue--restore-store-items (items)
"Set the live store's items to ITEMS, dropping malformed ones.
Called by the persistence layer after deserializing from disk. Defined here
so that the setf on the store struct slot stays in the same file as the struct."
(setf (agent-shell-queue-store-items agent-shell-queue--store)
(seq-map #'agent-shell-queue--sanitize-bucket items)))
(defun agent-shell-queue--normalize-running-item (item)
"Reset ITEM's status from `running' to `active' for cross-session reload.
Defined here so setf on item struct slots stays in the same file as the struct."
(setf (agent-shell-queue-item-status item) 'active)
(setf (agent-shell-queue-item-dispatched item) nil))
(cl-defstruct (agent-shell-queue-queue
(:constructor agent-shell-queue-queue--make)
(:copier nil))
"Queue runtime state and reference to the active store."
(store 'agent-shell-queue--store) ; symbol naming the live store variable
(session-paused nil) ; list of buffer names paused from dispatch
(editing-ids nil) ; list of item IDs currently open in an edit buffer
(interjection-pending nil) ; boolean: blocks dispatch while interjection is in progress
(halted-sessions nil)) ; list of buffer/bucket names halted on task abort/interrupt
(defvar agent-shell-queue--queue
(agent-shell-queue-queue--make)
"The active queue object. Persisted via `savehist-additional-variables'.")
(defun agent-shell-queue--halted-on-abort-p (name)
"Return non-nil when bucket or buffer NAME is halted due to task abort/interrupt."
(and agent-shell-queue--queue
name
(member (if (stringp name) name (symbol-name name))
(agent-shell-queue-queue-halted-sessions agent-shell-queue--queue))))
(defun agent-shell-queue--mark-halted-on-abort (name)
"Mark buffer or bucket NAME as halted on abort."
(when name
(let ((sname (if (stringp name) name (symbol-name name))))
(cl-pushnew sname
(agent-shell-queue-queue-halted-sessions agent-shell-queue--queue)
:test #'equal))))
(defun agent-shell-queue--clear-halted-on-abort (name)
"Clear halted on abort status for buffer or bucket NAME."
(when name
(let ((sname (if (stringp name) name (symbol-name name))))
(setf (agent-shell-queue-queue-halted-sessions agent-shell-queue--queue)
(delete sname
(agent-shell-queue-queue-halted-sessions agent-shell-queue--queue))))))
(defun agent-shell-queue--response-has-question-p (response-text)
"Return non-nil if RESPONSE-TEXT ends with an open question prompt."
(when response-text
(let ((trimmed (string-trim response-text)))
(or (string-match-p "\\?\\s-*\\'" trimmed)
(string-match-p "\\[y/N\\]\\s-*\\'" trimmed)
(string-match-p "\\(Would you like\\|Do you want\\|Should I\\).*\\?\\s-*\\'" trimmed)))))
(defun agent-shell-queue--verify-recovery (buf item response-text)
"Verify whether ITEM turn on BUF satisfies the 3 recovery criteria:
1. Uninterrupted (status is done, outcome is not aborted/interrupted).
2. No question (response-text does not end with open question).
3. Not in plan mode (buf mode-id not in `agent-shell-queue-blocked-session-modes`).
Returns non-nil when all three criteria are satisfied."
(and item
(eq (agent-shell-queue-item-status item) 'done)
(not (memq (agent-shell-queue-item-outcome item) '(aborted interrupted)))
(not (agent-shell-queue--response-has-question-p response-text))
(not (agent-shell-queue--session-mode-blocked-p buf))))
(defun agent-shell-queue-session-paused-p ()
"Return non-nil when the current buffer's session queue dispatch is paused."
(and agent-shell-queue--queue
(member (buffer-name (current-buffer))
(agent-shell-queue-queue-session-paused agent-shell-queue--queue))))
(defun agent-shell-queue--session-pause-name (name)
"Add NAME to the session-paused list and mark its active items blocked.runner.
Shared by `agent-shell-queue-session-pause' (single buffer), `agent-shell-queue-pause'
\(batch, every known buffer), and `agent-shell-queue--on-interrupt'."
(agent-shell-queue--cancel-pause-timer name)
(cl-pushnew name (agent-shell-queue-queue-session-paused agent-shell-queue--queue) :test #'equal)
(seq-do (lambda (item)
(when (eq (agent-shell-queue-item-status item) 'active)
(setf (agent-shell-queue-item-status item) 'blocked.runner)))
(cdr (assoc name (agent-shell-queue-store-items agent-shell-queue--store)))))
(defun agent-shell-queue--session-unpause-name (name)
"Remove NAME from session-paused and halted-sessions lists, marking its items active.
Shared by `agent-shell-queue-unpause-all-sessions' and `agent-shell-queue-session-resume'."
(setf (agent-shell-queue-queue-session-paused agent-shell-queue--queue)
(seq-remove (lambda (n) (equal n name))
(agent-shell-queue-queue-session-paused agent-shell-queue--queue)))
(agent-shell-queue--clear-halted-on-abort name)
(seq-do (lambda (item)
(when (eq (agent-shell-queue-item-status item) 'blocked.runner)
(setf (agent-shell-queue-item-status item) 'active)))
(cdr (assoc name (agent-shell-queue-store-items agent-shell-queue--store)))))
;;;###autoload
(defun agent-shell-queue-pause ()
"Pause dispatch for every known session (batch `agent-shell-queue-session-pause')."
(interactive)
(with-agent-shell-queue
(seq-do (lambda (bucket)
(agent-shell-queue--session-pause-name (car bucket)))
(agent-shell-queue-store-items agent-shell-queue--store))
(message "agent-shell-queue: all sessions PAUSED")))
;;;###autoload
(defun agent-shell-queue-resume ()
"Resume dispatch for every known session.
Alias for `agent-shell-queue-unpause-all-sessions'."
(interactive)
(agent-shell-queue-unpause-all-sessions))
(defun agent-shell-queue-unpause-all-sessions ()
"Clear the per-session pause list and halted-on-abort list."
(interactive)
(with-agent-shell-queue
(setf (agent-shell-queue-queue-session-paused agent-shell-queue--queue) nil)
(setf (agent-shell-queue-queue-halted-sessions agent-shell-queue--queue) nil)
(seq-do (lambda (item)
(when (eq (agent-shell-queue-item-status item) 'blocked.runner)
(setf (agent-shell-queue-item-status item) 'active)))
(seq-mapcat #'cdr (agent-shell-queue-store-items agent-shell-queue--store)))
(message "agent-shell-queue: all session pauses and halts cleared"))
(seq-do (lambda (bucket)
(when-let* ((buf (get-buffer (car bucket)))
(_ (buffer-live-p buf)))
(agent-shell-queue--send-next-for-buffer buf)))
(agent-shell-queue-store-items agent-shell-queue--store)))
(defun agent-shell-queue-session-pause (&optional buf)
"Pause dispatch for BUF (default: current agent-shell session)."
(interactive
(list (agent-shell-queue--pick-shell-with-state "Pause dispatch for: ")))
(when-let* ((name (buffer-name buf)))
(with-agent-shell-queue
(agent-shell-queue--session-pause-name name)
(message "agent-shell-queue: %s PAUSED" name))))
(defun agent-shell-queue-session-resume (&optional buf)
"Resume dispatch for BUF (default: current agent-shell session).
Any running `pause' or `compact' item for BUF is marked done automatically."
(interactive
(list (agent-shell-queue--pick-shell-with-state "Resume dispatch for: ")))
(when-let* ((name (buffer-name buf)))
(with-agent-shell-queue
(setq agent-shell-queue--compact-running
(seq-remove (lambda (it) (equal (car it) name)) agent-shell-queue--compact-running))
(seq-do (lambda (it)
(when (and (eq (agent-shell-queue-item-status it) 'running)
(memq (agent-shell-queue-item-kind it) '(pause compact)))
(setf (agent-shell-queue-item-status it) 'done)
(setf (agent-shell-queue-item-completed it) (float-time))
(agent-shell-queue--append-done-log name it)
(run-hook-with-args 'agent-shell-queue-item-done-hook name it)))
(cdr (assoc name (agent-shell-queue-store-items agent-shell-queue--store))))
(agent-shell-queue--session-unpause-name name)
(message "agent-shell-queue: %s resumed" name))
(agent-shell-queue--send-next-for-buffer buf)))
(defun agent-shell-queue--poll-for-idle-and-resume (buf attempt)
"Poll BUF until `shell-maker-busy' is nil, then call `agent-shell-queue-session-resume'.
Retries every 0.5 seconds up to 20 times (~10 seconds total).
Called by `agent-shell-queue-recover-stuck-shell'."
(cond
((not (buffer-live-p buf))
(message "agent-shell-queue: recovery abandoned — buffer was killed"))
((> attempt 20)
(message "agent-shell-queue: %s still busy after 10s — call `agent-shell-queue-session-resume' manually"
(buffer-name buf)))
((with-current-buffer buf (not (shell-maker-busy)))
(agent-shell-queue-session-resume buf))
(t
(run-with-timer 0.5 nil #'agent-shell-queue--poll-for-idle-and-resume buf (1+ attempt)))))
(defun agent-shell-queue-recover-stuck-shell (&optional buf)
"Interrupt a stuck shell and auto-resume queue dispatch when it becomes idle.
Marks any running item as aborted, sends an interrupt to the shell, then
polls until the shell is no longer busy before resuming dispatch.
Use this when the shell is frozen with no prompt appearing after the last turn."
(interactive
(list (agent-shell-queue--pick-shell-with-state "Recover stuck shell: ")))
(when-let* ((buf-name (buffer-name buf))
(_ (buffer-live-p buf)))
(with-agent-shell-queue
(seq-do (lambda (item)
(when (eq (agent-shell-queue-item-status item) 'running)
(setf (agent-shell-queue-item-status item) 'aborted)
(setf (agent-shell-queue-item-completed item) (float-time))
(setf (agent-shell-queue-item-outcome item) 'interrupted)))
(cdr (assoc buf-name (agent-shell-queue-store-items agent-shell-queue--store))))
(with-current-buffer buf
(agent-shell-interrupt)))
(message "agent-shell-queue: recovering %s — waiting for shell to become idle..." buf-name)
(agent-shell-queue--poll-for-idle-and-resume buf 0)))
(defun agent-shell-queue--on-interrupt (&optional _force)
"Flag the session and its bucket as halted-on-abort when `agent-shell-interrupt' is called.
Installed as :before advice on `agent-shell-interrupt'."
(agent-shell-queue--ensure-loaded)
(when-let* ((_ (derived-mode-p 'agent-shell-mode))
(buf-name (buffer-name)))
(agent-shell-queue--session-pause-name buf-name)
(agent-shell-queue--mark-halted-on-abort buf-name)
(when-let* ((running-item (seq-find (lambda (it) (eq (agent-shell-queue-item-status it) 'running))
(cdr (assoc buf-name (agent-shell-queue-store-items agent-shell-queue--store)))))
(dir (agent-shell-queue-item-directory running-item)))
(agent-shell-queue--mark-halted-on-abort (agent-shell-queue--bucket-for-dir dir)))
(agent-shell-queue--save)
(agent-shell-queue--refresh-buffer)))
(advice-add 'agent-shell-interrupt :before #'agent-shell-queue--on-interrupt)
(defvar-local agent-shell-queue-intercept-mode nil
"When non-nil in an agent-shell buffer, capture user-typed turns as queue items.")
(defvar-local agent-shell-queue-input-mode 'default
"Current input routing mode for this agent-shell buffer.
One of `default' (normal shell input), `queue-intercept' (capture user
input as queue items while still submitting), or `queue-only' (no prompt;
all input routed through the queue). Set via `agent-shell-queue-set-input-mode'.")
(defface agent-shell-queue-intercept-face
'((t :foreground "orange" :weight bold))
"Face for the [intercept] indicator appended to the prompt in queue-intercept mode.")
(defvar-local agent-shell-queue--intercept-overlay nil)
(defvar-local agent-shell-queue--intercept-sub-prompt nil)
(defun agent-shell-queue--on-submit-intercept (&rest _)
"Capture user-typed shell turn as a queue item when intercept mode is active.
Installed as :before advice on `shell-maker-submit'."
(when-let* ((_ agent-shell-queue-intercept-mode)
(_ (called-interactively-p 'interactive))
(_ (derived-mode-p 'agent-shell-mode))
(buf-name (buffer-name (current-buffer)))
(input (save-excursion
(goto-char (point-max))
(when (re-search-backward comint-prompt-regexp nil t)
(string-trim
(buffer-substring-no-properties (match-end 0) (point-max))))))
(_ (not (string-empty-p input)))
(_ (or (agent-shell-queue--ensure-loaded) t))
(item (agent-shell-queue--make-item input nil 'prompt)))
(setf (agent-shell-queue-item-status item) 'running)
(setf (agent-shell-queue-item-dispatched item) (float-time))
(agent-shell-queue--add-item-to-bucket buf-name item)
(agent-shell-queue--ensure-subscription (current-buffer))
(push (cons (agent-shell-queue-item-id item) (point-max))
agent-shell-queue--response-start-positions)
(agent-shell-queue--save)
(agent-shell-queue--refresh-buffer)))
(advice-add 'shell-maker-submit :before #'agent-shell-queue--on-submit-intercept)
(declare-function shell-maker-busy "shell-maker")
(defun agent-shell-queue--intercept-clear ()
(when (overlayp agent-shell-queue--intercept-overlay)
(delete-overlay agent-shell-queue--intercept-overlay)
(setq agent-shell-queue--intercept-overlay nil)))
(defun agent-shell-queue--intercept-show (_event)
(when (and (eq agent-shell-queue-input-mode 'queue-intercept)
(derived-mode-p 'agent-shell-mode))
(agent-shell-queue--intercept-clear)
(let ((ov (make-overlay (point-max) (point-max) nil t t)))
(overlay-put ov 'after-string
(propertize " [intercept]" 'face 'agent-shell-queue-intercept-face))
(overlay-put ov 'agent-shell-queue-intercept t)
(setq agent-shell-queue--intercept-overlay ov))))
(defun agent-shell-queue-set-input-mode (mode &optional buf)
"Set input MODE for BUF (default: current buffer).
MODE must be one of `default', `queue-intercept', or `queue-only'.
Enforces mutual exclusivity and updates the prompt indicator."
(unless (memq mode '(default queue-intercept queue-only))
(user-error "Invalid input mode %s: expected default, queue-intercept, or queue-only"
mode))
(with-current-buffer (or buf (current-buffer))
(setq agent-shell-queue-input-mode mode)
(setq agent-shell-queue-intercept-mode (eq mode 'queue-intercept))
(cond
((eq mode 'queue-only)
(agent-shell-queue--intercept-clear)
(when agent-shell-queue--intercept-sub-prompt
(agent-shell-unsubscribe :subscription agent-shell-queue--intercept-sub-prompt)
(setq agent-shell-queue--intercept-sub-prompt nil))
(unless agent-shell-queue-only-mode
(agent-shell-queue-only-mode 1)))
((eq mode 'queue-intercept)
(when agent-shell-queue-only-mode
(agent-shell-queue-only-mode -1))
(unless agent-shell-queue--intercept-sub-prompt
(setq agent-shell-queue--intercept-sub-prompt
(agent-shell-subscribe-to
:shell-buffer (current-buffer)
:event 'prompt-ready
:on-event #'agent-shell-queue--intercept-show)))
(unless (shell-maker-busy)
(agent-shell-queue--intercept-show nil)))
(t
(when agent-shell-queue-only-mode
(agent-shell-queue-only-mode -1))
(agent-shell-queue--intercept-clear)
(when agent-shell-queue--intercept-sub-prompt
(agent-shell-unsubscribe :subscription agent-shell-queue--intercept-sub-prompt)
(setq agent-shell-queue--intercept-sub-prompt nil))))
(agent-shell-queue--refresh-buffer)))
(defun agent-shell-queue-toggle-input-mode ()
"Cycle input mode in the current buffer: default → queue-intercept → queue-only → default."
(interactive)
(agent-shell-queue-set-input-mode
(pcase agent-shell-queue-input-mode
('default 'queue-intercept)
('queue-intercept 'queue-only)
(_ 'default))))
(defun agent-shell-queue-toggle-intercept-mode (&optional buf)
"Toggle queue-intercept mode for BUF; when active, user-typed turns are queued."
(interactive
(list (or (and (derived-mode-p 'agent-shell-mode) (current-buffer))
(agent-shell-queue--pick-buffer "Toggle intercept for: "))))
(when buf
(with-current-buffer buf
(agent-shell-queue-set-input-mode
(if (eq agent-shell-queue-input-mode 'queue-intercept) 'default 'queue-intercept))
(message "agent-shell-queue: input mode %s in %s"
agent-shell-queue-input-mode (buffer-name buf)))))
(defun agent-shell-queue-enable-intercept-mode (&optional buf)
"Enable queue-intercept mode in BUF so user-typed turns are captured as queue items."
(interactive
(list (or (and (derived-mode-p 'agent-shell-mode) (current-buffer))
(agent-shell-queue--pick-buffer "Enable intercept for: "))))
(when buf
(with-current-buffer buf
(agent-shell-queue-set-input-mode 'queue-intercept)
(message "agent-shell-queue: queue-intercept ENABLED in %s" (buffer-name buf)))))
(defun agent-shell-queue-disable-intercept-mode (&optional buf)
"Disable queue-intercept mode in BUF, returning it to default input mode."
(interactive
(list (or (and (derived-mode-p 'agent-shell-mode) (current-buffer))
(agent-shell-queue--pick-buffer "Disable intercept for: "))))
(when buf
(with-current-buffer buf
(when (eq agent-shell-queue-input-mode 'queue-intercept)
(agent-shell-queue-set-input-mode 'default))
(message "agent-shell-queue: queue-intercept disabled in %s" (buffer-name buf)))))
;;;###autoload
(defun agent-shell-queue-disable-intercept-mode-all ()
"Reset all live agent-shell buffers in queue-intercept mode to default."
(interactive)
(let ((cleared (seq-filter (lambda (buf)
(eq (buffer-local-value 'agent-shell-queue-input-mode buf)
'queue-intercept))
(agent-shell-buffers))))
(seq-do (lambda (buf)
(with-current-buffer buf
(agent-shell-queue-set-input-mode 'default)))
cleared)
(agent-shell-queue--refresh-buffer)
(message "agent-shell-queue: queue-intercept disabled in %d buffer(s)" (length cleared))))
(defun agent-shell-queue--default-pick-buffer (prompt)
"Pick a live agent-shell buffer using PROMPT via `completing-read'."
(when-let* ((bufs (agent-shell-buffers)))
(get-buffer (completing-read prompt (seq-map #'buffer-name bufs) nil t))))
(defun agent-shell-queue--pick-shell-with-state (prompt)