-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent-shell-queue.el
More file actions
4987 lines (4565 loc) · 241 KB
/
agent-shell-queue.el
File metadata and controls
4987 lines (4565 loc) · 241 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") (annotated-completing-read "0.1") (agent-shell "0.1"))
;; 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)
(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.")
(declare-function shell-maker-busy "shell-maker")
(declare-function agent-shell-subscribe-to "agent-shell")
(declare-function agent-shell-unsubscribe "agent-shell")
(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")
(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
(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 "/background "
"String prepended to prompts flagged for background sub-agent execution.")
(defvar agent-shell-queue-clear-command "/clear"
"Command string sent when a clear item is dequeued.")
(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.")
(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'.")
;;; Struct macro
(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))))))
;;; Executor registry
(cl-defstruct (agent-shell-queue-executor
(:constructor agent-shell-queue-executor--make)
(:copier nil))
"Registry entry pairing a serializable NAME with an EXECUTOR function and
an optional CAPTURE 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."
name executor capture)
(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)
"Register EXECUTOR (and optional CAPTURE) 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.
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)
(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))))
;;; 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))
(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."
(let* ((current (agent-shell-queue-item--make))
(old-len (length item))
(new-len (length current)))
(if (= old-len new-len)
item
(dotimes (i (1- (min old-len new-len)))
(aset current (1+ i) (aref item (1+ i))))
current)))
(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. 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-map #'agent-shell-queue--migrate-item-if-stale (cdr bucket))))
(agent-shell-queue-store-items agent-shell-queue--store)))
(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.")
(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
(paused nil) ; boolean: global pause flag
(session-paused nil) ; list of buffer names paused from dispatch
(editing-ids nil)) ; list of item IDs currently open in an edit buffer
(defvar agent-shell-queue--queue
(agent-shell-queue-queue--make)
"The active queue object. Persisted via `savehist-additional-variables'.")
(defun agent-shell-queue-pause ()
"Pause the global queue; no new items will be dispatched."
(interactive)
(setf (agent-shell-queue-queue-paused agent-shell-queue--queue) t)
(message "agent-shell-queue: PAUSED — no new items will be dispatched")
(agent-shell-queue--refresh-buffer))
(defun agent-shell-queue-resume ()
"Resume the global queue after being paused."
(interactive)
(setf (agent-shell-queue-queue-paused agent-shell-queue--queue) nil)
(message "agent-shell-queue: running")
(agent-shell-queue--refresh-buffer))
(defun agent-shell-queue-unpause-all-sessions ()
"Clear the per-session pause list, resuming all individually paused sessions."
(interactive)
(setf (agent-shell-queue-queue-session-paused agent-shell-queue--queue) nil)
(message "agent-shell-queue: all session pauses cleared")
(agent-shell-queue--refresh-buffer))
(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)))
(cl-pushnew name (agent-shell-queue-queue-session-paused agent-shell-queue--queue) :test #'equal)
(message "agent-shell-queue: %s PAUSED" name)
(agent-shell-queue--refresh-buffer)))
(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)))
(setf (agent-shell-queue-queue-session-paused agent-shell-queue--queue)
(delete name (agent-shell-queue-queue-session-paused agent-shell-queue--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)))
(cdr (assoc name (agent-shell-queue-store-items agent-shell-queue--store))))
(agent-shell-queue--save)
(message "agent-shell-queue: %s resumed" name)
(agent-shell-queue--refresh-buffer)
(agent-shell-queue--send-next-for-buffer buf)))
(defun agent-shell-queue--on-interrupt (&optional _force)
"Pause the per-buffer queue when `agent-shell-interrupt' is called.
Installed as :before advice on `agent-shell-interrupt'."
(when (and (derived-mode-p 'agent-shell-mode)
(assoc (buffer-name) (agent-shell-queue-store-items agent-shell-queue--store)))
(cl-pushnew (buffer-name) (agent-shell-queue-queue-session-paused agent-shell-queue--queue) :test #'equal)
(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.")
(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)
(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)
(defun agent-shell-queue-toggle-intercept-mode (&optional buf)
"Toggle shell-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
(setq agent-shell-queue-intercept-mode (not agent-shell-queue-intercept-mode))
(message "agent-shell-queue intercept: %s in %s"
(if agent-shell-queue-intercept-mode "ENABLED" "disabled")
(buffer-name buf))
(agent-shell-queue--refresh-buffer))))
(defun agent-shell-queue-enable-intercept-mode (&optional buf)
"Enable 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
(setq agent-shell-queue-intercept-mode t)
(message "agent-shell-queue intercept: ENABLED in %s" (buffer-name buf))
(agent-shell-queue--refresh-buffer))))
(defun agent-shell-queue-disable-intercept-mode (&optional buf)
"Disable intercept mode in BUF."
(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
(setq agent-shell-queue-intercept-mode nil)
(message "agent-shell-queue intercept: disabled in %s" (buffer-name buf))
(agent-shell-queue--refresh-buffer))))
(defun agent-shell-queue--default-state-file ()
"Default queue state file path under `user-emacs-directory'."
(expand-file-name (concat "agent-shell-queue."
(substring (agent-shell-queue-format-file-extension
agent-shell-queue-serialization-format)
1))
user-emacs-directory))
(defun agent-shell-queue--default-archive-file ()
"Default JSONL archive file path under `user-emacs-directory'."
(expand-file-name "agent-shell-queue-archive.jsonl" user-emacs-directory))
(defun agent-shell-queue--archive-file ()
"Return the resolved archive file path, or nil if archiving is disabled."
(when agent-shell-queue-archive-enabled
(funcall agent-shell-queue-archive-file-function)))
(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)
"Select a live agent-shell buffer via PROMPT using queue-state annotations."
(let* ((bufs (or (agent-shell-buffers)
(user-error "No live agent-shell buffers")))
(table (seq-map (lambda (buf)
(cons (buffer-name buf)
(agent-shell-queue--buffer-state-label
(buffer-name buf))))
bufs)))
(get-buffer
(annotated-completing-read table
:prompt prompt
:category 'agent-shell-buffer
:require-match t))))
(defvar agent-shell-queue--loaded nil
"Non-nil after the on-disk state has been read into memory.")
(defvar agent-shell-queue--idle-timer nil
"Idle timer for auto-sending active queue items.")
(defvar agent-shell-queue--subscriptions nil
"Alist of (BUF-NAME . TOKEN) for active `turn-complete' subscriptions.
Each entry is registered when the first item is queued for that buffer and
removed when the queue for that buffer empties or the buffer is killed.")
(defvar agent-shell-queue-blocked-session-modes '("dontAsk" "plan")
"Session mode IDs that block queue dispatch.
When a target shell is in one of these modes the item is not sent and
the session queue is paused until the mode changes.")
(defun agent-shell-queue--gen-id ()
"Generate a short unique item ID: q + one digit + four alphanumeric chars."
(let ((chars "abcdefghijklmnopqrstuvwxyz0123456789"))
(concat "q"
(number-to-string (random 10))
(apply #'string
(seq-map (lambda (_it) (aref chars (random 36))) (make-list 4 nil))))))
(defun agent-shell-queue--clean-args (args)
"Remove trailing whitespace from every line of ARGS."
(string-join (seq-map #'string-trim-right (split-string args "\n")) "\n"))
(defun agent-shell-queue--make-item (prompt &optional background kind)
"Return a new active queue item for PROMPT."
(agent-shell-queue-item--make
:id (agent-shell-queue--gen-id)
:args (agent-shell-queue--clean-args prompt)
:status 'active
:kind (or kind 'prompt)
:background background
:created (float-time)))
;;; Local utilities
(defun agent-shell-queue--state-file ()
"Return the path to the on-disk queue state file."
(funcall agent-shell-queue-state-file-function))
(defun agent-shell-queue--current-store ()
"Return the live store, ensuring format and file reflect current config."
(setf (agent-shell-queue-store-format agent-shell-queue--store)
agent-shell-queue-serialization-format)
(setf (agent-shell-queue-store-file agent-shell-queue--store)
(agent-shell-queue--state-file))
agent-shell-queue--store)
(defun agent-shell-queue--pick-buffer (prompt)
"Pick a live agent-shell buffer using PROMPT."
(funcall agent-shell-queue-pick-buffer-function prompt))
(defun agent-shell-queue--format-age (delta)
"Format DELTA time-value as a short relative age string.
Alternative using stdlib: (car (split-string (format-seconds \"%dd %hh %mm %ss%z\" s)))
but that yields \"0d\" for a zero delta instead of \"0s\"."
(let ((s (float-time delta)))
(cond ((< s 60) (format "%ds" (truncate s)))
((< s 3600) (format "%dm" (truncate (/ s 60))))
((< s 86400) (format "%dh" (truncate (/ s 3600))))
(t (format "%dd" (truncate (/ s 86400)))))))
;;; Persistence
;; -- plist format --
(defun agent-shell-queue--serialize-plist (items)
"Serialize ITEMS to an s-expression string (plist item format)."
(with-temp-buffer
(prin1 (seq-map (lambda (it) (cons (car it) (seq-map #'agent-shell-queue-item-to-plist (cdr it)))) items)
(current-buffer))
(buffer-string)))
(defun agent-shell-queue--deserialize-plist (str)
"Deserialize STR (plist format) into an items alist."
(let ((data (read str)))
(unless (listp data)
(error "Expected list, got %S" data))
(seq-map (lambda (it) (cons (car it) (seq-map #'agent-shell-queue-item-from-plist (cdr it)))) data)))
;; -- JSON format --
(defun agent-shell-queue--item-to-json (item)
"Convert ITEM to a JSON-serializable plist.
Status is stored as a string; background as a JSON boolean;
executor as its registry name string or JSON null."
(list
:id (agent-shell-queue-item-id item)
:args (agent-shell-queue-item-args item)
:status (symbol-name (agent-shell-queue-item-status item))
:kind (symbol-name (or (agent-shell-queue-item-kind item) 'prompt))
:background (if (agent-shell-queue-item-background item) t :false)
:created (agent-shell-queue-item-created item)
:dispatched (or (agent-shell-queue-item-dispatched item) :null)
:completed (or (agent-shell-queue-item-completed item) :null)
:response (or (agent-shell-queue-item-response item) :null)
:outcome (if-let* ((o (agent-shell-queue-item-outcome item))) (symbol-name o) :null)
:directory (or (agent-shell-queue-item-directory item) :null)
:executor (or (agent-shell-queue--executor-name (agent-shell-queue-item-executor item)) :null)))
(defun agent-shell-queue--item-from-json (obj)
"Reconstruct a queue item from JSON-parsed plist OBJ.
Status is interned; background truthy only when exactly `t';
executor resolved from the registry (nil when absent or unknown)."
(agent-shell-queue-item--make
:id (plist-get obj :id)
:args (or (plist-get obj :args) (plist-get obj :prompt))
:status (intern (plist-get obj :status))
:kind (intern (or (plist-get obj :kind) "prompt"))
:background (eq t (plist-get obj :background))
:created (plist-get obj :created)
:dispatched (plist-get obj :dispatched)
:completed (plist-get obj :completed)
:response (let ((r (plist-get obj :response))) (unless (eq r :null) r))
:outcome (when-let* ((o (plist-get obj :outcome))) (unless (eq o :null) (intern o)))
:directory (let ((d (plist-get obj :directory))) (unless (eq d :null) d))
:executor (let ((e (plist-get obj :executor)))
(unless (or (null e) (eq e :null))
(agent-shell-queue--executor-from-plist e)))))
(defun agent-shell-queue--serialize-json (items)
"Serialize ITEMS to a JSON string."
(unless (fboundp 'json-serialize)
(error "json-serialize not available (requires Emacs 27+)"))
(json-serialize
(vconcat
(seq-map (lambda (it)
(list :buffer (car it)
:items (vconcat (seq-map #'agent-shell-queue--item-to-json (cdr it)))))
items))))
(defun agent-shell-queue--deserialize-json (str)
"Deserialize STR (JSON format) into an items alist."
(unless (fboundp 'json-parse-string)
(error "json-parse-string not available (requires Emacs 27+)"))
(thread-last (json-parse-string str
:object-type 'plist
:array-type 'list
:null-object nil
:false-object nil)
(seq-map (lambda (bucket)
(cons (plist-get bucket :buffer)
(seq-map #'agent-shell-queue--item-from-json
(plist-get bucket :items)))))))
;; -- YAML format --
(defun agent-shell-queue--item-to-yaml (item)
"Convert ITEM to a hash-table suitable for `yaml-encode'.
Status is stored as a string; background as t or nil."
(let ((h (make-hash-table :test 'equal)))
(map-put! h "id" (agent-shell-queue-item-id item))
(map-put! h "args" (agent-shell-queue-item-args item))
(map-put! h "status" (symbol-name (agent-shell-queue-item-status item)))
(map-put! h "kind" (symbol-name (or (agent-shell-queue-item-kind item) 'prompt)))
(map-put! h "background" (if (agent-shell-queue-item-background item) t nil))
(map-put! h "created" (agent-shell-queue-item-created item))
(map-put! h "dispatched" (agent-shell-queue-item-dispatched item))
(map-put! h "completed" (agent-shell-queue-item-completed item))
(map-put! h "response" (or (agent-shell-queue-item-response item) :null))
(map-put! h "outcome" (if-let* ((o (agent-shell-queue-item-outcome item))) (symbol-name o) :null))
(map-put! h "directory" (or (agent-shell-queue-item-directory item) :null))
(map-put! h "executor" (or (agent-shell-queue--executor-name (agent-shell-queue-item-executor item)) :null))
h))
(defun agent-shell-queue--item-from-yaml (obj)
"Reconstruct a queue item from a hash-table OBJ produced by `yaml-parse-string'."
(agent-shell-queue-item--make
:id (map-elt obj "id")
:args (or (map-elt obj "args") (map-elt obj "prompt"))
:status (intern (map-elt obj "status"))
:kind (intern (or (map-elt obj "kind") "prompt"))
:background (eq t (map-elt obj "background"))
:created (map-elt obj "created")
:dispatched (map-elt obj "dispatched")
:completed (map-elt obj "completed")
:response (let ((r (map-elt obj "response"))) (unless (eq r :null) r))
:outcome (when-let* ((o (map-elt obj "outcome"))) (unless (eq o :null) (intern o)))
:directory (let ((d (map-elt obj "directory"))) (unless (eq d :null) d))
:executor (let ((e (map-elt obj "executor")))
(unless (or (null e) (eq e :null))
(agent-shell-queue--executor-from-plist e)))))
(defun agent-shell-queue--serialize-yaml (items)
"Serialize ITEMS to a YAML string via `yaml-encode'."
(unless (fboundp 'yaml-encode)
(error "yaml-encode not available; install the `yaml' package"))
(yaml-encode
(vconcat
(seq-map (lambda (pair)
(let ((h (make-hash-table :test 'equal)))
(map-put! h "buffer" (car pair))
(map-put! h "items" (vconcat (seq-map #'agent-shell-queue--item-to-yaml (cdr pair))))
h))
items))))
(defun agent-shell-queue--deserialize-yaml (str)
"Deserialize STR (YAML format) into an items alist via `yaml-parse-string'."
(unless (fboundp 'yaml-parse-string)
(error "yaml-parse-string not available; install the `yaml' package"))
(thread-last (yaml-parse-string str
:object-type 'hash-table
:sequence-type 'list
:null-object nil
:false-object nil)
(seq-map (lambda (bucket)
(cons (map-elt bucket "buffer")
(seq-map #'agent-shell-queue--item-from-yaml
(map-elt bucket "items")))))))
;; -- Serialization generics --
(cl-defgeneric agent-shell-queue--serialize-items (format items)
"Serialize ITEMS for FORMAT, returning a string.
Signals an error for unknown formats.")
(cl-defgeneric agent-shell-queue--deserialize-items (format string)
"Deserialize STRING for FORMAT, returning an items alist.
Signals an error for unknown formats.")
(cl-defgeneric agent-shell-queue-format-file-extension (_format)
"Return the file extension string (with leading dot) for FORMAT."
".el")
(cl-defmethod agent-shell-queue--serialize-items ((_format (eql plist)) items)
(agent-shell-queue--serialize-plist items))
(cl-defmethod agent-shell-queue--deserialize-items ((_format (eql plist)) string)
(agent-shell-queue--deserialize-plist string))
(cl-defmethod agent-shell-queue-format-file-extension ((_format (eql plist)))
".el")
(cl-defmethod agent-shell-queue--serialize-items ((_format (eql json)) items)
(agent-shell-queue--serialize-json items))
(cl-defmethod agent-shell-queue--deserialize-items ((_format (eql json)) string)
(agent-shell-queue--deserialize-json string))
(cl-defmethod agent-shell-queue-format-file-extension ((_format (eql json)))
".json")
(cl-defmethod agent-shell-queue--serialize-items ((_format (eql yaml)) items)
(agent-shell-queue--serialize-yaml items))
(cl-defmethod agent-shell-queue--deserialize-items ((_format (eql yaml)) string)
(agent-shell-queue--deserialize-yaml string))
(cl-defmethod agent-shell-queue-format-file-extension ((_format (eql yaml)))
".yaml")
(defun agent-shell-queue-register-format (fmt serialize-fn deserialize-fn)
"Register serialization FORMAT with SERIALIZE-FN and DESERIALIZE-FN.
FMT is a symbol; SERIALIZE-FN takes one argument (an items alist) and returns
a string; DESERIALIZE-FN takes a string and returns an items alist.
Installs cl-generic methods for `agent-shell-queue--serialize-items' and
`agent-shell-queue--deserialize-items' specialised on (eql FMT)."
(eval `(cl-defmethod agent-shell-queue--serialize-items ((_format (eql ,fmt)) items)
(funcall ,serialize-fn items))
t)
(eval `(cl-defmethod agent-shell-queue--deserialize-items ((_format (eql ,fmt)) string)
(funcall ,deserialize-fn string))
t))
(defun agent-shell-queue-serialize (store)
"Serialize STORE to a string using the format recorded in STORE."
(agent-shell-queue--serialize-items
(agent-shell-queue-store-format store)
(agent-shell-queue-store-items store)))
(defun agent-shell-queue-deserialize (store string)
"Parse STRING using the format in STORE, returning an items alist."
(agent-shell-queue--deserialize-items
(agent-shell-queue-store-format store)
string))
(defun agent-shell-queue--safe-save-directory ()
"Return the directory for safe-save backups.
Uses `agent-shell-queue-safe-save-directory' when set, otherwise
a subdirectory of `temporary-file-directory' named emacs-<instance>."
(or agent-shell-queue-safe-save-directory
(expand-file-name
(format "emacs-%s"
(if (functionp agent-shell-queue-instance-name)
(funcall agent-shell-queue-instance-name)
agent-shell-queue-instance-name))
(temporary-file-directory))))
(defun agent-shell-queue--save ()
"Persist all queue items; all items are persisted regardless of status.
Delegates to `agent-shell-queue-save-function' when set; otherwise writes
to the file in the current store.
When `agent-shell-queue-safe-save' is non-nil and no custom save function
is set, writes a versioned backup before overwriting the state file."
(if agent-shell-queue-save-function
(funcall agent-shell-queue-save-function)
(let* ((base-store (agent-shell-queue--current-store))
(store (agent-shell-queue--make-store
:items (agent-shell-queue-store-items base-store)
:format (agent-shell-queue-store-format base-store)
:file (agent-shell-queue-store-file base-store)))
(serialized (agent-shell-queue-serialize store))
(file (agent-shell-queue-store-file store)))
(when-let* ((_ agent-shell-queue-safe-save)
(_ (file-exists-p file))
(fmt (or agent-shell-queue-safe-save-format
(agent-shell-queue-store-format store)))
(ext (agent-shell-queue-format-file-extension fmt))
(dir (agent-shell-queue--safe-save-directory))
(backup (expand-file-name
(format "agent-shell-queue-archive-%d%s"
(truncate (float-time)) ext)
dir)))
(make-directory dir t)
(with-temp-file backup
(insert (agent-shell-queue-serialize
(agent-shell-queue--make-store
:items (agent-shell-queue-store-items base-store)
:format fmt
:file nil)))))
(make-directory (file-name-directory file) t)
(with-temp-file file
(insert serialized))))
(setq agent-shell-queue--last-flush-time (float-time))
(when agent-shell-queue-auto-flush-interval
(setq agent-shell-queue--next-flush-time
(time-add (current-time)
(seconds-to-time agent-shell-queue-auto-flush-interval)))))
(defun agent-shell-queue--append-done-log (buf-name item)
"Append a JSON line for the completed ITEM in BUF-NAME to the done log.
No-op when `agent-shell-queue-done-log-file' is nil."
(when agent-shell-queue-done-log-file
(condition-case err
(let ((entry (json-serialize
(list :id (agent-shell-queue-item-id item)
:target buf-name
:args (agent-shell-queue-item-args item)
:background (if (agent-shell-queue-item-background item) t :false)
:created (agent-shell-queue-item-created item)
:completed (float-time)))))
(make-directory (file-name-directory agent-shell-queue-done-log-file) t)
(write-region (concat entry "\n") nil agent-shell-queue-done-log-file t 'silent))
(error (message "agent-shell-queue: done-log write failed: %s" err)))))
(defun agent-shell-queue--write-archive (buf-name item)
"Append a JSONL record for ITEM in BUF-NAME to `agent-shell-queue-archive-file'.
The record includes the target buffer's directory, instance name, whether the
item was dispatched, ISO-8601 archive timestamp, and runtime (dispatched→completed)."
(when-let* ((file (agent-shell-queue--archive-file)))
(condition-case err
(let* ((path (when-let* ((buf (get-buffer buf-name))
((buffer-live-p buf)))
(buffer-local-value 'default-directory buf)))
(dispatched (agent-shell-queue-item-dispatched item))
(completed (agent-shell-queue-item-completed item))
(runtime (when (and dispatched completed) (- completed dispatched)))
(instance (if (functionp agent-shell-queue-instance-name)
(funcall agent-shell-queue-instance-name)
agent-shell-queue-instance-name))
(entry (json-serialize
(list :id (agent-shell-queue-item-id item)
:args (agent-shell-queue-item-args item)
:status (symbol-name (agent-shell-queue-item-status item))
:background (if (agent-shell-queue-item-background item) t :false)
:target buf-name
:path (or path :null)
:instance (or instance :null)
:ran (if dispatched t :false)
:archived (format-time-string "%Y-%m-%dT%H:%M:%S")
:created (or (agent-shell-queue-item-created item) :null)
:dispatched (or dispatched :null)
:completed (or completed :null)
:runtime (or runtime :null)
:outcome (if-let* ((o (agent-shell-queue-item-outcome item))) (symbol-name o) :null)))))
(make-directory (file-name-directory file) t)
;; Advisory lock via Emacs's own .#file mechanism — no subprocess,
;; no persistent fd. write-region with append opens, writes, closes.
(unwind-protect
(progn
(lock-file file)
(write-region (concat entry "\n") nil file t 'silent))
(unlock-file file)))
(error (message "agent-shell-queue: archive write failed: %s" err)))))
;;;###autoload
(defun agent-shell-queue-buffer-archive ()
"Archive the item at point to the archive file and remove it from the queue.
Archiving must be enabled via `agent-shell-queue-archive-enabled'.
The destination path is provided by `agent-shell-queue-archive-file-function'."
(interactive)
(unless agent-shell-queue-archive-enabled
(user-error "Enable archiving by setting `agent-shell-queue-archive-enabled' to t"))
(when-let* ((id (tabulated-list-get-id))
(pair (agent-shell-queue--item-by-id id))
(item (cdr pair)))
(agent-shell-queue--assert-not-running item)
(agent-shell-queue--write-archive (car pair) item)
(agent-shell-queue-remove id)
(agent-shell-queue-buffer-refresh)
(message "agent-shell-queue: archived %s" id)))
(defun agent-shell-queue--load ()
"Populate the live store items from the durable store.
Delegates to `agent-shell-queue-load-function' when set; otherwise reads
from the file in the current store. After loading, items with status
`running' are normalized to `active' since a running item from a previous
session cannot be resumed and must be re-dispatched."
(if agent-shell-queue-load-function
(condition-case err
(funcall agent-shell-queue-load-function)
(error (message "agent-shell-queue: load failed: %s" err)))
(let* ((store (agent-shell-queue--current-store))
(file (agent-shell-queue-store-file store)))
(when (file-exists-p file)
(condition-case err
(setf (agent-shell-queue-store-items agent-shell-queue--store)
(agent-shell-queue-deserialize
store
(with-temp-buffer
(insert-file-contents file)
(buffer-string))))
(error (message "agent-shell-queue: ignoring unreadable state: %s" err)))))
;; Items that were running when the session ended cannot be resumed.
;; Normalize them to active so they will be re-dispatched.
(seq-do (lambda (pair)
(seq-do (lambda (item)
(when (eq (agent-shell-queue-item-status item) 'running)
(setf (agent-shell-queue-item-status item) 'active)
(setf (agent-shell-queue-item-dispatched item) nil)))
(cdr pair)))
(agent-shell-queue-store-items agent-shell-queue--store))))
(defun agent-shell-queue--ensure-loaded ()
"Load queue state from disk on first call."
(unless agent-shell-queue--loaded
(agent-shell-queue--load)
(setq agent-shell-queue--loaded t)))
(add-hook 'kill-emacs-hook #'agent-shell-queue--save)
;;; Store predicates
(defun agent-shell-queue--item-id-matches-p (id item)
"Return non-nil when ITEM's id equals ID."
(equal (agent-shell-queue-item-id item) id))
(defun agent-shell-queue--bucket-empty-p (pair)
"Return non-nil when PAIR is a bucket cell whose item list is empty."
(null (cdr pair)))
(defun agent-shell-queue--wait-timer-id-matches-p (id pair)
"Return non-nil when PAIR is a wait-timer cell keyed by ID."
(equal (car pair) id))
;;; Queue operations