Profpatsch/users/Profpatsch/pty-prompt/main.go
  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
// pty-prompt is a PTY broker for LLM-driven interactive prompts.
//
// An LLM (or any caller that cannot hold a persistent connection) drives an
// interactive program — e.g. `git add -p`, `git rebase -i`, an installer
// wizard — across many separate process invocations. The tricky part is that
// *something* has to keep the pseudo-terminal and the spawned process alive
// between those invocations. pty-prompt does that by splitting itself into:
//
//   - a background daemon that owns the PTY, the spawned child process and a
//     rolling buffer of everything the child has written, and
//   - a thin CLI client that the LLM calls once per request, talking to the
//     daemon over a unix-domain socket.
//
// The surface is intentionally tiny — five verbs:
//
//	start         spawn a command under a PTY held by a background daemon
//	step [TEXT]   write TEXT + Enter (or just re-poll if TEXT is omitted),
//	              wait for output to settle, return everything new since
//	              the input. With no TEXT it only re-polls.
//	wait          block until the child exits, then return everything since
//	              the call plus the exit status (no quiescence heuristic)
//	stop          graceful shutdown (SIGTERM, then SIGKILL after a grace)
//	kill-session  force shutdown (SIGKILL immediately)
//
// Because a prompt-based program never tells us "I am done", step uses a
// quiescence heuristic: after sending input we wait until the child has
// produced no new bytes for --timeout milliseconds, then return what
// accumulated. When you instead want to wait for real completion (e.g. a
// non-interactive build), the wait verb blocks until the child actually exits.
// Output is ANSI-stripped by default (pass --raw to keep escape codes, e.g. for
// full-screen TUIs).
package main

import (
	"bufio"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"

	"github.com/creack/pty"
)

const (
	defaultSession  = "default"
	defaultTimeout  = 500 * time.Millisecond // quiet period that counts as "settled"
	defaultMaxWait  = 30 * time.Second       // hard cap on how long a step read may block
	defaultWaitCap  = 60 * time.Minute       // default hard cap for the wait verb
	defaultCols     = 120
	defaultRows     = 40
	bufferCap       = 1 << 20 // keep at most the last 1 MiB of output
	pollInterval    = 20 * time.Millisecond
	daemonReadyByte = 'K'
)

// request is the wire format the client sends to the daemon (one JSON object
// per connection, newline-terminated).
type request struct {
	Op        string `json:"op"`                    // step | wait | status | stop | kill
	Text      string `json:"text,omitempty"`        // payload for step (Enter is always appended)
	TimeoutMs int    `json:"timeout_ms,omitempty"`  // step: quiescence window
	MaxWaitMs int    `json:"max_wait_ms,omitempty"` // wait: hard cap on how long to block for exit
	Raw       bool   `json:"raw,omitempty"`         // return raw bytes instead of ANSI-stripped
}

// response is what the daemon writes back (JSON, newline-terminated).
type response struct {
	Data      string `json:"data"`                 // output bytes since the input (ANSI-stripped unless raw)
	Exited    bool   `json:"exited"`               // has the child exited?
	ExitErr   string `json:"exit_err,omitempty"`   // child's exit error, if any
	Err       string `json:"err,omitempty"`        // protocol/handler error
	RunningMs int    `json:"running_ms,omitempty"` // ms since the session (daemon) started
	QuietMs   int    `json:"quiet_ms,omitempty"`   // ms since the child last produced output
}

func main() {
	if len(os.Args) < 2 {
		usage(os.Stderr)
		os.Exit(2)
	}
	cmd := os.Args[1]
	args := os.Args[2:]

	var err error
	switch cmd {
	case "__daemon":
		err = runDaemon(args)
	case "start":
		err = cmdStart(args)
	case "step":
		err = cmdStep(args)
	case "wait":
		err = cmdWait(args)
	case "stop":
		err = cmdStop(args)
	case "kill-session":
		err = cmdKill(args)
	case "-h", "--help", "help":
		usage(os.Stdout)
		return
	default:
		fmt.Fprintf(os.Stderr, "[pty-prompt: %s | unknown command %q]\n\n", nowStamp(), cmd)
		usage(os.Stderr)
		os.Exit(2)
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "[pty-prompt: %s | %v]\n", nowStamp(), err)
		os.Exit(1)
	}
}

func usage(w io.Writer) {
	fmt.Fprint(w, `pty-prompt — PTY broker for LLM-driven interactive prompts

USAGE:
  pty-prompt start [--session NAME] [--timeout MS] [--raw] -- CMD [ARGS...]
        Spawn CMD under a PTY held by a background daemon, then print the
        program's initial output (after it goes quiet for --timeout ms).

  pty-prompt step [--session NAME] [--timeout MS] [--raw] [TEXT]
        Write TEXT followed by Enter, wait for the output to settle, and print
        everything produced since the input. With no TEXT, only re-poll (useful
        when a program is still working). This is the one verb you iterate with:
        e.g. "pty-prompt step y" answers a prompt and shows the next one.

  pty-prompt wait [--session NAME] [--max-wait MS] [--raw]
        Block until the child exits, then print everything produced since the
        call plus the exit status. Unlike step, there is no quiet-window
        heuristic — the only stopping condition is real completion. Use this for
        non-interactive commands (e.g. a build) where you just want the result.
        --max-wait caps the block (default 60m) so a wedged child can't hang you.

  pty-prompt stop [--session NAME]
        Gracefully terminate the child (SIGTERM, then SIGKILL after a grace
        period) and shut the daemon down.

  pty-prompt kill-session [--session NAME]
        Force-terminate the child (SIGKILL immediately) and shut the daemon
        down. Use when a child is wedged and ignores SIGTERM.

NOTES:
  - --session defaults to "default", so simple use needs no name.
  - --timeout is the "quiet" window (ms) that counts as settled (default 500).
  - --max-wait (wait verb) caps how long to block for exit (default 60m).
  - Output is ANSI-stripped by default; pass --raw to keep escape codes (e.g.
    for full-screen TUIs).
  - There is no reliable "done" signal for prompt-based programs; step simply
    waits until no new bytes arrive for --timeout. When the child exits, step
    reports it. For a real "wait for completion", use the wait verb.
  - Every invocation prints a one-line status to stderr (program output stays
    on stdout), e.g.:
      [pty-prompt: 13:58:42 | running for 16s, quiet for 1.5s, still running]
      [pty-prompt: 14:00:56 | running for 2m14s, quiet for 0.3s, exited: exit status 1]
      [pty-prompt: 14:00:56 | ran for 2m14s, exited, session "build" stopped]
    The leading HH:MM:SS is the wall-clock time (an absolute reference across
    polls); "running for" is time since the session started; "quiet for" is time
    since the child last produced output (useful to tell progress from a hang).
`)
}

// ───────────────────────────── client side ─────────────────────────────

func cmdStart(args []string) error {
	session := defaultSession
	timeout := defaultTimeout
	raw := false
	var cmdArgs []string

	i := 0
	for i < len(args) {
		a := args[i]
		switch {
		case a == "--":
			cmdArgs = args[i+1:]
			i = len(args)
		case a == "--session":
			session, i = needVal(args, i)
		case strings.HasPrefix(a, "--session="):
			session = strings.TrimPrefix(a, "--session=")
			i++
		case a == "--timeout":
			var v string
			v, i = needVal(args, i)
			timeout = msOr(v, timeout)
		case a == "--raw":
			raw = true
			i++
		default:
			return fmt.Errorf("start: unexpected argument %q (did you forget -- before the command?)", a)
		}
	}
	if len(cmdArgs) == 0 {
		return errors.New("start: missing command; usage: pty-prompt start [opts] -- CMD [ARGS...]")
	}

	sock := socketPath(session)
	if isAlive(sock) {
		// Report how long the existing session has been running, if reachable.
		if resp, err := call(session, request{Op: "status"}); err == nil {
			return fmt.Errorf("session %q already running for %s (stop it first)",
				session, humanDuration(resp.RunningMs))
		}
		return fmt.Errorf("session %q already running (stop it first)", session)
	}
	_ = os.Remove(sock)
	if err := os.MkdirAll(filepath.Dir(sock), 0o700); err != nil {
		return err
	}

	// Re-exec ourselves as the detached daemon.
	self, err := os.Executable()
	if err != nil {
		return err
	}
	dArgs := []string{"__daemon",
		"--session", session,
		"--cols", strconv.Itoa(defaultCols),
		"--rows", strconv.Itoa(defaultRows),
		"--",
	}
	dArgs = append(dArgs, cmdArgs...)

	// Pipe so we can block until the daemon signals readiness.
	pr, pw, err := os.Pipe()
	if err != nil {
		return err
	}
	daemon := exec.Command(self, dArgs...)
	daemon.Stdin = nil
	daemon.Stdout = pw
	// Send the detached daemon's stderr to a per-session log file rather than
	// inheriting ours. The daemon outlives this `start` invocation; if it held
	// our stderr open, a caller that pipes `start` (e.g. `| tail`) would hang
	// waiting for EOF that never comes until the daemon dies.
	if logf, err := os.Create(socketPath(session) + ".log"); err == nil {
		daemon.Stderr = logf
		defer logf.Close()
	} else {
		daemon.Stderr = nil
	}
	daemon.SysProcAttr = &syscall.SysProcAttr{Setsid: true} // detach into its own session
	if err := daemon.Start(); err != nil {
		pr.Close()
		pw.Close()
		return err
	}
	pw.Close()
	// Wait for the readiness byte (or EOF on early failure).
	buf := make([]byte, 1)
	if _, err := io.ReadFull(pr, buf); err != nil {
		pr.Close()
		return fmt.Errorf("start: daemon failed to come up: %w", err)
	}
	pr.Close()
	_ = daemon.Process.Release()

	// Now grab the initial output.
	resp, err := call(session, request{Op: "step", TimeoutMs: int(timeout / time.Millisecond), Raw: raw})
	if err != nil {
		return err
	}
	return emit(resp)
}

// cmdStep is the one verb you iterate with: write TEXT + Enter (or just
// re-poll if TEXT is omitted), wait for the output to settle, and print
// everything produced since the input.
func cmdStep(args []string) error {
	session := defaultSession
	timeout := defaultTimeout
	raw := false
	var rest []string

	i := 0
	for i < len(args) {
		a := args[i]
		switch {
		case a == "--session":
			session, i = needVal(args, i)
		case strings.HasPrefix(a, "--session="):
			session = strings.TrimPrefix(a, "--session=")
			i++
		case a == "--timeout":
			var v string
			v, i = needVal(args, i)
			timeout = msOr(v, timeout)
		case a == "--raw":
			raw = true
			i++
		case a == "--":
			rest = append(rest, args[i+1:]...)
			i = len(args)
		default:
			rest = append(rest, a)
			i++
		}
	}
	// TEXT is optional: with no TEXT, step only re-polls (no input written).
	text := strings.Join(rest, " ")
	resp, err := call(session, request{
		Op:        "step",
		Text:      text,
		TimeoutMs: int(timeout / time.Millisecond),
		Raw:       raw,
	})
	if err != nil {
		return err
	}
	return emit(resp)
}

// cmdWait blocks until the child exits, then prints everything produced since
// the call plus the exit status. Unlike step, it has no quiet-window heuristic:
// the only stopping condition is real completion (bounded by --max-wait).
func cmdWait(args []string) error {
	session := defaultSession
	maxWait := defaultWaitCap
	raw := false

	i := 0
	for i < len(args) {
		a := args[i]
		switch {
		case a == "--session":
			session, i = needVal(args, i)
		case strings.HasPrefix(a, "--session="):
			session = strings.TrimPrefix(a, "--session=")
			i++
		case a == "--max-wait":
			var v string
			v, i = needVal(args, i)
			maxWait = msOr(v, maxWait)
		case strings.HasPrefix(a, "--max-wait="):
			maxWait = msOr(strings.TrimPrefix(a, "--max-wait="), maxWait)
			i++
		case a == "--raw":
			raw = true
			i++
		default:
			return fmt.Errorf("wait: unexpected argument %q", a)
		}
	}

	resp, err := call(session, request{
		Op:        "wait",
		MaxWaitMs: int(maxWait / time.Millisecond),
		Raw:       raw,
	})
	if err != nil {
		return err
	}
	return emit(resp)
}

func cmdStop(args []string) error {
	return shutdown(sessionOnly(args), "stop")
}

func cmdKill(args []string) error {
	return shutdown(sessionOnly(args), "kill")
}

// shutdown sends a stop/kill request and waits for the daemon to tear down its
// socket so a subsequent start sees a clean slate.
func shutdown(session, op string) error {
	resp, err := call(session, request{Op: op})
	if err != nil && !errors.Is(err, io.EOF) {
		// The daemon closes the connection as it exits, so EOF is expected.
		if !isConnReset(err) {
			return err
		}
	}
	sock := socketPath(session)
	deadline := time.Now().Add(3 * time.Second)
	for time.Now().Before(deadline) {
		if !isAlive(sock) {
			break
		}
		time.Sleep(20 * time.Millisecond)
	}
	_ = os.Remove(sock)
	_ = os.Remove(sock + ".log")

	// At-stop child state, folded into the status line alongside the run time.
	state := "still running at stop"
	if resp.Exited {
		if resp.ExitErr != "" {
			state = "exited: " + resp.ExitErr
		} else {
			state = "exited"
		}
	}
	fmt.Fprintf(os.Stderr, "[pty-prompt: %s | ran for %s, %s, session %q stopped]\n",
		nowStamp(), humanDuration(resp.RunningMs), state, session)
	return nil
}

// call connects to a session daemon, sends one request and reads one response.
func call(session string, req request) (response, error) {
	sock := socketPath(session)
	conn, err := net.DialTimeout("unix", sock, 2*time.Second)
	if err != nil {
		return response{}, fmt.Errorf("no running session %q (start one with: pty-prompt start --session %s -- CMD)", session, session)
	}
	defer conn.Close()

	enc := json.NewEncoder(conn)
	if err := enc.Encode(req); err != nil {
		return response{}, err
	}
	var resp response
	dec := json.NewDecoder(bufio.NewReader(conn))
	if err := dec.Decode(&resp); err != nil {
		return response{}, err
	}
	if resp.Err != "" {
		return resp, fmt.Errorf("%s", resp.Err)
	}
	return resp, nil
}

// emit prints the raw program output to stdout and a one-line status to stderr.
// The status line is always printed — including when there is no new output
// (the common "still running, nothing new" poll) — since that is exactly when
// the running/quiet timing is most useful.
func emit(resp response) error {
	io.WriteString(os.Stdout, resp.Data)
	state := "still running"
	if resp.Exited {
		if resp.ExitErr != "" {
			state = "exited: " + resp.ExitErr
		} else {
			state = "exited"
		}
	}
	fmt.Fprintf(os.Stderr, "[pty-prompt: %s | running for %s, quiet for %s, %s]\n",
		nowStamp(), humanDuration(resp.RunningMs), humanDuration(resp.QuietMs), state)
	return nil
}

// ───────────────────────────── daemon side ─────────────────────────────

type broker struct {
	mu        sync.Mutex
	buf       []byte    // rolling output buffer (capped at bufferCap)
	lastData  time.Time // when the last byte arrived
	startedAt time.Time // when the session (daemon) started
	exited    bool
	exitErr   error
	ptmx      *os.File
	cmd       *exec.Cmd

	ctx    context.Context    // cancelled when the daemon should shut down
	cancel context.CancelFunc // call to request shutdown (stop op, signal, child exit)

	waitOnce sync.Once // guards the single allowed exec.Cmd.Wait()
	termOnce sync.Once // guards teardown so it runs exactly once
}

// reap calls cmd.Wait() at most once and records the exit status. Both the
// read loop (on PTY EOF) and terminate() funnel through here, so Wait is never
// called twice.
func (b *broker) reap() {
	b.waitOnce.Do(func() {
		werr := b.cmd.Wait()
		b.mu.Lock()
		b.exited = true
		b.exitErr = werr
		b.mu.Unlock()
	})
}

func runDaemon(args []string) error {
	session := defaultSession
	cols, rows := defaultCols, defaultRows
	var cmdArgs []string

	i := 0
	for i < len(args) {
		a := args[i]
		switch {
		case a == "--session":
			session, i = needVal(args, i)
		case a == "--cols":
			var v string
			v, i = needVal(args, i)
			cols = atoiOr(v, cols)
		case a == "--rows":
			var v string
			v, i = needVal(args, i)
			rows = atoiOr(v, rows)
		case a == "--":
			cmdArgs = args[i+1:]
			i = len(args)
		default:
			return fmt.Errorf("__daemon: unexpected arg %q", a)
		}
	}
	if len(cmdArgs) == 0 {
		return errors.New("__daemon: missing command")
	}

	sock := socketPath(session)
	ln, err := net.Listen("unix", sock)
	if err != nil {
		return fmt.Errorf("__daemon: listen: %w", err)
	}
	defer ln.Close()
	defer os.Remove(sock)

	child := exec.Command(cmdArgs[0], cmdArgs[1:]...)
	child.Env = append(os.Environ(), "TERM=xterm-256color")
	ptmx, err := pty.StartWithSize(child, &pty.Winsize{Cols: uint16(cols), Rows: uint16(rows)})
	if err != nil {
		return fmt.Errorf("__daemon: start pty: %w", err)
	}
	defer ptmx.Close()

	// The daemon's whole lifecycle hangs off this context. It is cancelled by:
	//   - a SIGTERM/SIGINT (via signal.NotifyContext),
	//   - a `stop` request from a client,
	//   - the child process exiting (readLoop calls cancel()).
	ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
	defer cancel()

	now := time.Now()
	b := &broker{ptmx: ptmx, cmd: child, lastData: now, startedAt: now, ctx: ctx, cancel: cancel}

	// Reader goroutine: drain the PTY into the rolling buffer until EOF.
	go b.readLoop()

	// When the context is cancelled, terminate the child and unblock Accept by
	// closing the listener. This is the single, deterministic shutdown path.
	go func() {
		<-ctx.Done()
		b.terminate()
		ln.Close()
	}()

	// Tell the parent (start) we are ready to accept connections.
	if _, err := os.Stdout.Write([]byte{daemonReadyByte}); err == nil {
		os.Stdout.Close()
	}

	for {
		conn, err := ln.Accept()
		if err != nil {
			return nil // listener closed → context cancelled, shutting down
		}
		b.handle(conn)
		conn.Close()
	}
}

func (b *broker) readLoop() {
	rd := make([]byte, 4096)
	for {
		n, err := b.ptmx.Read(rd)
		if n > 0 {
			b.mu.Lock()
			b.buf = append(b.buf, rd[:n]...)
			if len(b.buf) > bufferCap {
				b.buf = b.buf[len(b.buf)-bufferCap:]
			}
			b.lastData = time.Now()
			b.mu.Unlock()
		}
		if err != nil {
			// EOF / child closed the PTY: record exit status. We do NOT cancel
			// the context here — the daemon stays up after the child exits so a
			// final `read`/`status` can still retrieve the last output and the
			// exit result. Shutdown happens on an explicit `stop` or a signal.
			b.reap()
			return
		}
	}
}

// handle processes a single request.
func (b *broker) handle(conn net.Conn) {
	var req request
	dec := json.NewDecoder(conn)
	if err := dec.Decode(&req); err != nil {
		writeResp(conn, response{Err: "bad request: " + err.Error()})
		return
	}

	timeout := durMs(req.TimeoutMs, defaultTimeout)
	maxWait := defaultMaxWait

	switch req.Op {
	case "step":
		// Mark the buffer position before writing, so the snapshot returns only
		// what the child produces in response (including the echo of our input).
		marker := b.bufLen()
		if req.Text != "" {
			if _, err := b.ptmx.Write([]byte(req.Text + "\r")); err != nil {
				writeResp(conn, response{Err: "write: " + err.Error()})
				return
			}
			// Wait for the child to start responding before measuring quiescence.
			// Otherwise, on a slow program (or right after start, while the shell
			// is still enabling echo), the quiet window can elapse before any
			// byte arrives and we return an empty reply.
			b.waitForData(marker, timeout, maxWait)
		}
		b.waitQuiet(timeout, maxWait)
		writeResp(conn, b.snapshot(marker, req.Raw))

	case "wait":
		// Block until the child exits (or the hard cap elapses), then return
		// everything produced since this call. Unlike step, the only stopping
		// condition is real completion — no quiet-window heuristic.
		marker := b.bufLen()
		cap := durMs(req.MaxWaitMs, defaultWaitCap)
		b.waitExit(cap)
		writeResp(conn, b.snapshot(marker, req.Raw))

	case "status":
		// Read-only probe: report timing and child state without touching input.
		writeResp(conn, b.statusResp())

	case "stop":
		writeResp(conn, b.statusResp())
		// Graceful shutdown: cancelling the context runs terminate() (SIGTERM,
		// then SIGKILL after a grace) and tears down the listener.
		b.cancel()

	case "kill":
		writeResp(conn, b.statusResp())
		// Force shutdown: SIGKILL the child immediately, then cancel so the
		// listener and daemon tear down.
		b.forceKill()
		b.cancel()

	default:
		writeResp(conn, response{Err: "unknown op: " + req.Op})
	}
}

// waitForData blocks until the buffer has grown past `marker` (i.e. the child
// produced at least one byte in response to our input), or until `grace`
// elapses, or until the child exits / the daemon shuts down. It bounds the
// wait by maxWait as a safety net. This absorbs the startup/slow-program race
// where the quiescence window would otherwise expire before any reply arrives.
func (b *broker) waitForData(marker int, grace, maxWait time.Duration) {
	bound := grace
	if maxWait < bound {
		bound = maxWait
	}
	ctx, cancel := context.WithTimeout(b.ctx, bound)
	defer cancel()

	ticker := time.NewTicker(pollInterval)
	defer ticker.Stop()

	for {
		b.mu.Lock()
		grown := len(b.buf) > marker
		exited := b.exited
		b.mu.Unlock()

		if grown || exited {
			return
		}
		select {
		case <-ctx.Done():
			return
		case <-ticker.C:
		}
	}
}

// waitQuiet blocks until the child has produced no new output for `quiet`,
// or until `maxWait` elapses, or until the daemon's context is cancelled
// (shutdown). If the child has already exited and the buffer is drained, it
// returns promptly.
func (b *broker) waitQuiet(quiet, maxWait time.Duration) {
	ctx, cancel := context.WithTimeout(b.ctx, maxWait)
	defer cancel()

	ticker := time.NewTicker(pollInterval)
	defer ticker.Stop()

	for {
		b.mu.Lock()
		idle := time.Since(b.lastData)
		exited := b.exited
		b.mu.Unlock()

		if idle >= quiet {
			return
		}
		if exited && idle >= quiet/2 {
			// Child is gone; don't wait the full window for nothing.
			return
		}

		select {
		case <-ctx.Done():
			// maxWait elapsed or the daemon is shutting down.
			return
		case <-ticker.C:
		}
	}
}

// waitExit blocks until the child process has exited, or until `cap` elapses,
// or until the daemon's context is cancelled (shutdown). This is the "wait for
// completion" primitive behind the wait verb: its only stopping condition is
// real exit, not a quiescence heuristic.
func (b *broker) waitExit(cap time.Duration) {
	ctx, cancel := context.WithTimeout(b.ctx, cap)
	defer cancel()

	ticker := time.NewTicker(pollInterval)
	defer ticker.Stop()

	for {
		b.mu.Lock()
		exited := b.exited
		b.mu.Unlock()

		if exited {
			return
		}
		select {
		case <-ctx.Done():
			// cap elapsed or the daemon is shutting down.
			return
		case <-ticker.C:
		}
	}
}

// snapshot returns the bytes produced since `marker`. Output is ANSI-stripped
// unless raw is set.
func (b *broker) snapshot(marker int, raw bool) response {
	b.mu.Lock()
	defer b.mu.Unlock()
	if marker > len(b.buf) {
		marker = len(b.buf)
	}
	data := b.buf[marker:]
	out := string(data)
	if !raw {
		out = stripANSI(out)
	}
	return response{
		Data:      out,
		Exited:    b.exited,
		ExitErr:   errStr(b.exitErr),
		RunningMs: int(time.Since(b.startedAt) / time.Millisecond),
		QuietMs:   int(time.Since(b.lastData) / time.Millisecond),
	}
}

func (b *broker) bufLen() int {
	b.mu.Lock()
	defer b.mu.Unlock()
	return len(b.buf)
}

func (b *broker) state() (exited bool, exitErr error) {
	b.mu.Lock()
	defer b.mu.Unlock()
	return b.exited, b.exitErr
}

// statusResp reports the child's exit state plus timing (running/quiet), with
// no output payload. Used by the status/stop/kill ops.
func (b *broker) statusResp() response {
	b.mu.Lock()
	defer b.mu.Unlock()
	return response{
		Exited:    b.exited,
		ExitErr:   errStr(b.exitErr),
		RunningMs: int(time.Since(b.startedAt) / time.Millisecond),
		QuietMs:   int(time.Since(b.lastData) / time.Millisecond),
	}
}

// terminate shuts the child down cleanly (SIGTERM, then SIGKILL after a grace
// period) and closes the PTY. It is idempotent.
func (b *broker) terminate() {
	b.termOnce.Do(func() {
		b.mu.Lock()
		exited := b.exited
		proc := b.cmd.Process
		b.mu.Unlock()

		if !exited && proc != nil {
			_ = proc.Signal(syscall.SIGTERM)
			done := make(chan struct{})
			go func() { b.reap(); close(done) }()
			select {
			case <-done:
			case <-time.After(2 * time.Second):
				_ = proc.Kill()
				b.reap()
			}
		}
		// Closing the PTY also unblocks readLoop's Read.
		_ = b.ptmx.Close()
	})
}

// forceKill SIGKILLs the child immediately (no SIGTERM grace). Safe to call
// before terminate(); the subsequent context-cancel-driven terminate() is a
// no-op for the already-dead process and still closes the PTY.
func (b *broker) forceKill() {
	b.mu.Lock()
	exited := b.exited
	proc := b.cmd.Process
	b.mu.Unlock()
	if !exited && proc != nil {
		_ = proc.Kill()
		b.reap()
	}
}

func writeResp(conn net.Conn, resp response) {
	enc := json.NewEncoder(conn)
	_ = enc.Encode(resp)
}

// ───────────────────────────── helpers ─────────────────────────────

// ansiRe matches the terminal escape sequences we strip from returned output:
// CSI sequences (cursor moves, colours, erases: ESC [ ... final-byte), OSC
// sequences (ESC ] ... BEL or ST), and lone two-byte escapes (e.g. ESC =).
var ansiRe = regexp.MustCompile(`\x1b\[[0-9;?]*[ -/]*[@-~]` +
	`|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)` +
	`|\x1b[@-Z\\-_]`)

// stripANSI removes ANSI escape sequences and carriage returns so the caller
// gets clean, line-oriented text. CR is dropped (PTYs emit CRLF) but other
// printable content and newlines are preserved.
func stripANSI(s string) string {
	s = ansiRe.ReplaceAllString(s, "")
	s = strings.ReplaceAll(s, "\r", "")
	return s
}

func socketDir() string {
	base := os.Getenv("XDG_RUNTIME_DIR")
	if base == "" {
		base = os.TempDir()
	}
	return filepath.Join(base, "pty-prompt")
}

func socketPath(session string) string {
	return filepath.Join(socketDir(), session+".sock")
}

// isAlive reports whether a daemon is accepting connections on sock.
func isAlive(sock string) bool {
	conn, err := net.DialTimeout("unix", sock, 500*time.Millisecond)
	if err != nil {
		return false
	}
	conn.Close()
	return true
}

func needVal(args []string, i int) (string, int) {
	if i+1 >= len(args) {
		return "", i + 1
	}
	return args[i+1], i + 2
}

func sessionOnly(args []string) string {
	session := defaultSession
	for i := 0; i < len(args); i++ {
		switch {
		case args[i] == "--session" && i+1 < len(args):
			session = args[i+1]
			i++
		case strings.HasPrefix(args[i], "--session="):
			session = strings.TrimPrefix(args[i], "--session=")
		}
	}
	return session
}

func atoiOr(s string, def int) int {
	if n, err := strconv.Atoi(s); err == nil {
		return n
	}
	return def
}

func msOr(s string, def time.Duration) time.Duration {
	if n, err := strconv.Atoi(s); err == nil && n >= 0 {
		return time.Duration(n) * time.Millisecond
	}
	return def
}

func durMs(ms int, def time.Duration) time.Duration {
	if ms <= 0 {
		return def
	}
	return time.Duration(ms) * time.Millisecond
}

// humanDuration renders a millisecond count as a short, human-readable string:
// sub-second values keep one decimal ("0.4s"), whole seconds up to a minute are
// plain ("16s"), and a minute or more is "Mm Ss" ("2m14s").
func humanDuration(ms int) string {
	if ms < 0 {
		ms = 0
	}
	if ms < 1000 {
		return fmt.Sprintf("%.1fs", float64(ms)/1000)
	}
	secs := ms / 1000
	if secs < 60 {
		return fmt.Sprintf("%ds", secs)
	}
	return fmt.Sprintf("%dm%ds", secs/60, secs%60)
}

// nowStamp is the current local wall-clock time as HH:MM:SS, prefixed to every
// status line so a caller polling across separate invocations has an absolute
// time reference (not just relative running/quiet durations).
func nowStamp() string {
	return time.Now().Format("15:04:05")
}

func errStr(err error) string {
	if err == nil {
		return ""
	}
	return err.Error()
}

func isConnReset(err error) bool {
	return errors.Is(err, syscall.ECONNRESET) || errors.Is(err, io.ErrUnexpectedEOF)
}