blyte 0.84.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
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
use std::collections::BTreeSet;
use std::fmt::Write as _;
use std::io::{ErrorKind, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use crate::serve::TOKEN_HEADER;
use crate::session::{Entry, EntryBody};
use crate::surface_dir::{is_running, list_records_for_root};
use crate::surface_registry::{
    find_by_name, first_line, live_entries, report_unreadable, RegistryEntry, SurfaceState,
};

const OPEN_CODE_TIMEOUT: Duration = Duration::from_secs(5);
const RELOAD_WAIT_TIMEOUT: Duration = Duration::from_secs(20);
const RELOAD_POLL_INTERVAL: Duration = Duration::from_millis(100);
const MAX_OPEN_CODE_RESPONSE_BYTES: usize = 64 * 1024;
const RUNS_WINDOW_DAYS: u64 = 14;

/// A stopped surface belonging to a folder.
///
/// `last_used` is in Unix seconds: the `ts` of the last complete entry in
/// `entries.jsonl`, or the record's `started_at` when that file is absent or
/// has no entries (a surface that was started and never used was last used
/// when it started).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct StoppedSurface {
    pub id: String,
    pub name: String,
    pub last_used: u64,
    pub last_message: Option<String>,
}

fn scan_entries_summary(path: &Path) -> Result<(Option<u64>, Option<String>), String> {
    let bytes = match std::fs::read(path) {
        Ok(b) => b,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((None, None)),
        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
    };

    let mut last_ts: Option<u64> = None;
    let mut last_user_text: Option<String> = None;
    let mut pos = 0usize;
    let mut line_no = 0usize;
    while pos < bytes.len() {
        line_no += 1;
        let start = pos;
        let end = match bytes[pos..].iter().position(|&b| b == b'\n') {
            Some(rel) => pos + rel + 1,
            None => bytes.len(),
        };
        let is_last_without_newline = end == bytes.len() && !bytes[start..end].ends_with(b"\n");
        let line_slice = &bytes[start..end];
        let parsed = std::str::from_utf8(line_slice)
            .map_err(|e| e.to_string())
            .and_then(|s| serde_json::from_str::<Entry>(s).map_err(|e| e.to_string()));
        match parsed {
            Ok(entry) => {
                last_ts = Some(entry.ts);
                if let EntryBody::UserMessage { text, .. } = entry.body {
                    last_user_text = Some(text);
                }
            }
            Err(reason) => {
                if !is_last_without_newline {
                    return Err(format!(
                        "invalid entry in {} at line {}: {}",
                        path.display(),
                        line_no,
                        reason
                    ));
                }
            }
        }
        pos = end;
    }

    let last_message = last_user_text.and_then(|text| {
        let line = first_line(&text);
        if line.is_empty() {
            None
        } else {
            Some(line)
        }
    });

    Ok((last_ts, last_message))
}

fn stopped_surfaces_for_root(root: &Path, state_dir: &Path) -> Result<Vec<StoppedSurface>, String> {
    let records = list_records_for_root(root, Some(state_dir))?;
    let mut stopped = Vec::new();
    for located in records {
        if is_running(&located.record) {
            continue;
        }
        let entries_path = located.dir.join("entries.jsonl");
        let (last_ts, last_message) = scan_entries_summary(&entries_path)?;
        let last_used = last_ts.unwrap_or(located.record.started_at);
        stopped.push(StoppedSurface {
            id: located.record.id,
            name: located.record.name,
            last_used,
            last_message,
        });
    }
    stopped.sort_by(|a, b| b.last_used.cmp(&a.last_used).then_with(|| a.id.cmp(&b.id)));
    Ok(stopped)
}

/// Collect stopped surfaces belonging to `folder`, newest first by `last_used`, then by `id`.
pub fn stopped_surfaces(folder: &Path, state_dir: &Path) -> Result<Vec<StoppedSurface>, String> {
    let root = crate::serve::resolve_folder(folder)?;
    stopped_surfaces_for_root(&root, state_dir)
}

fn format_utc_minute(ts: u64) -> String {
    let days = (ts / 86_400) as i64;
    let secs_of_day = ts % 86_400;
    let hour = secs_of_day / 3_600;
    let min = (secs_of_day % 3_600) / 60;

    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = if m <= 2 { y + 1 } else { y };

    format!("{year:04}-{m:02}-{d:02} {hour:02}:{min:02}")
}

pub fn format_stopped_surfaces_table(entries: &[StoppedSurface], folder: &Path) -> String {
    if entries.is_empty() {
        return format!("no stopped surfaces in {}\n", folder.display());
    }

    let rows: Vec<(&str, &str, String, String)> = entries
        .iter()
        .map(|entry| {
            let last_used = format_utc_minute(entry.last_used);
            let message = match &entry.last_message {
                Some(msg) => msg.chars().take(60).collect(),
                None => "-".to_string(),
            };
            (entry.name.as_str(), entry.id.as_str(), last_used, message)
        })
        .collect();

    let name_w = rows
        .iter()
        .map(|row| row.0.chars().count())
        .max()
        .unwrap_or(0)
        .max("NAME".len());
    let id_w = rows
        .iter()
        .map(|row| row.1.chars().count())
        .max()
        .unwrap_or(0)
        .max("ID".len());
    let used_w = rows
        .iter()
        .map(|row| row.2.chars().count())
        .max()
        .unwrap_or(0)
        .max("LAST USED".len());

    let mut out = String::new();
    let _ = writeln!(
        out,
        "{:<name_w$}  {:<id_w$}  {:<used_w$}  LAST MESSAGE",
        "NAME", "ID", "LAST USED"
    );
    for (name, id, last_used, message) in rows {
        let _ = writeln!(
            out,
            "{name:<name_w$}  {id:<id_w$}  {last_used:<used_w$}  {message}"
        );
    }
    let _ = writeln!(out);
    let _ = writeln!(out, "resume with: blyte --resume <name or id>");
    out
}

pub fn run_stopped_surfaces(
    folder: &Path,
    state_dir: &Path,
    json: bool,
    out: &mut dyn Write,
    err: &mut dyn Write,
) -> i32 {
    let root = match crate::serve::resolve_folder(folder) {
        Ok(root) => root,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };
    let entries = match stopped_surfaces_for_root(&root, state_dir) {
        Ok(entries) => entries,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    if json {
        match serde_json::to_string_pretty(&entries) {
            Ok(text) => {
                let _ = writeln!(out, "{text}");
                return 0;
            }
            Err(e) => {
                let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
                return 1;
            }
        }
    }

    let _ = write!(out, "{}", format_stopped_surfaces_table(&entries, &root));
    0
}

fn repository_name(root: &Path) -> String {
    root.file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_else(|| root.display().to_string())
}

fn count_running_runs_at(root: &Path, now: SystemTime) -> Result<usize, String> {
    let now = now
        .duration_since(UNIX_EPOCH)
        .map_err(|e| format!("system clock is before UNIX_EPOCH: {e}"))?
        .as_secs();
    crate::live_runs::collect(root, now, RUNS_WINDOW_DAYS).map(|live| live.running.len())
}

pub fn count_running_runs(root: &Path) -> Result<usize, String> {
    count_running_runs_at(root, SystemTime::now())
}

fn format_surface_state(entry: &RegistryEntry) -> String {
    if entry.state != SurfaceState::Idle {
        return entry.state.display_label().to_string();
    }
    match count_running_runs(&entry.root) {
        Ok(0) => entry.state.display_label().to_string(),
        Ok(1) => "idle (1 run working)".to_string(),
        Ok(n) => format!("idle ({n} runs working)"),
        Err(err) => format!("idle (runs unknown: {err})"),
    }
}

fn format_surface_version(entry: &RegistryEntry) -> String {
    match entry.runtime.is_stale() {
        Ok(false) => entry.runtime.version.clone(),
        Ok(true) => format!("{} (stale)", entry.runtime.version),
        Err(err) => format!("{} (stale unknown: {err})", entry.runtime.version),
    }
}

#[derive(serde::Serialize)]
struct SurfaceJsonEntry<'a> {
    #[serde(flatten)]
    entry: &'a RegistryEntry,
    stale: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stale_error: Option<String>,
    runs_working: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    runs_error: Option<String>,
}

pub fn format_surfaces_table(entries: &[RegistryEntry], current_id: Option<&str>) -> String {
    if entries.is_empty() {
        return "no surfaces are running\n".to_string();
    }

    let rows: Vec<(String, String, &str, String, String, &str)> = entries
        .iter()
        .map(|entry| {
            let name = if current_id == Some(entry.id.as_str()) {
                format!("{} (this surface)", entry.name)
            } else {
                entry.name.clone()
            };
            (
                name,
                repository_name(&entry.root),
                entry.branch.as_deref().unwrap_or("-"),
                format_surface_version(entry),
                format_surface_state(entry),
                entry.doing.as_str(),
            )
        })
        .collect();

    let name_w = rows
        .iter()
        .map(|row| row.0.chars().count())
        .max()
        .unwrap_or(0)
        .max("NAME".len());
    let repo_w = rows
        .iter()
        .map(|row| row.1.chars().count())
        .max()
        .unwrap_or(0)
        .max("REPOSITORY".len());
    let branch_w = rows
        .iter()
        .map(|row| row.2.chars().count())
        .max()
        .unwrap_or(0)
        .max("BRANCH".len());
    let version_w = rows
        .iter()
        .map(|row| row.3.chars().count())
        .max()
        .unwrap_or(0)
        .max("VERSION".len());
    let state_w = rows
        .iter()
        .map(|row| row.4.chars().count())
        .max()
        .unwrap_or(0)
        .max("STATE".len());

    let mut out = String::new();
    let _ = writeln!(
        out,
        "{:<name_w$}  {:<repo_w$}  {:<branch_w$}  {:<version_w$}  {:<state_w$}  DOING",
        "NAME", "REPOSITORY", "BRANCH", "VERSION", "STATE"
    );
    for (name, repo, branch, version, state, doing) in rows {
        let _ = writeln!(
            out,
            "{name:<name_w$}  {repo:<repo_w$}  {branch:<branch_w$}  {version:<version_w$}  {state:<state_w$}  {doing}"
        );
    }
    out
}

pub fn run_surfaces(dir: &Path, json: bool, out: &mut dyn Write, err: &mut dyn Write) -> i32 {
    let listing = match live_entries(dir) {
        Ok(listing) => listing,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };
    report_unreadable(&listing.unreadable, err);

    if json {
        let payload: Vec<SurfaceJsonEntry<'_>> = listing
            .entries
            .iter()
            .map(|entry| {
                let (stale, stale_error) = match entry.runtime.is_stale() {
                    Ok(stale) => (Some(stale), None),
                    Err(stale_err) => (None, Some(stale_err)),
                };
                let (runs_working, runs_error) = match count_running_runs(&entry.root) {
                    Ok(count) => (Some(count), None),
                    Err(runs_err) => (None, Some(runs_err)),
                };
                SurfaceJsonEntry {
                    entry,
                    stale,
                    stale_error,
                    runs_working,
                    runs_error,
                }
            })
            .collect();
        match serde_json::to_string_pretty(&payload) {
            Ok(text) => {
                let _ = writeln!(out, "{text}");
                return 0;
            }
            Err(e) => {
                let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
                return 1;
            }
        }
    }

    let _ = write!(out, "{}", format_surfaces_table(&listing.entries, None));
    0
}

fn read_surface_token(entry: &RegistryEntry) -> Result<String, String> {
    let token_path = blyte_agent::sandbox::surface_token_path_for_id(&entry.id)?;
    let raw_token = std::fs::read_to_string(&token_path).map_err(|_| {
        format!(
            "surface {} has no usable token at {}",
            entry.name,
            token_path.display()
        )
    })?;
    let token = raw_token.trim();
    if token.is_empty() || token.contains(['\n', '\r']) {
        return Err(format!(
            "surface {} has no usable token at {}",
            entry.name,
            token_path.display()
        ));
    }
    Ok(token.to_string())
}

pub fn surface_url(entry: &RegistryEntry) -> Result<String, String> {
    let token = read_surface_token(entry)?;
    Ok(format!("http://127.0.0.1:{}/#token={token}", entry.port))
}

fn parse_http_status(head: &str) -> Result<u16, String> {
    let status_line = head.lines().next().unwrap_or("").trim_end_matches('\r');
    let mut parts = status_line.split_whitespace();
    let version = parts
        .next()
        .ok_or_else(|| "empty HTTP response".to_string())?;
    if !version.starts_with("HTTP/") {
        return Err("invalid HTTP response".to_string());
    }
    let code_str = parts
        .next()
        .ok_or_else(|| "missing HTTP status code".to_string())?;
    code_str
        .parse::<u16>()
        .map_err(|_| "invalid HTTP status code".to_string())
}

pub fn request_open_code(entry: &RegistryEntry, token: &str) -> Result<String, String> {
    request_open_code_at(&entry.name, entry.port, token)
}

pub fn request_open_code_at(name: &str, port: u16, token: &str) -> Result<String, String> {
    let deadline = Instant::now() + OPEN_CODE_TIMEOUT;
    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let mut stream = TcpStream::connect_timeout(&addr, OPEN_CODE_TIMEOUT).map_err(|e| {
        if e.kind() == ErrorKind::ConnectionRefused {
            format!("surface {name} refused the connection on port {port}")
        } else {
            format!("cannot connect to surface {name} on port {port}: {e}")
        }
    })?;

    let remaining = deadline.saturating_duration_since(Instant::now());
    if remaining.is_zero() {
        return Err(format!("surface {name} timed out on port {port}"));
    }
    let _ = stream.set_write_timeout(Some(remaining));

    let req = format!(
        "POST /api/session/open-codes HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"
    );
    stream
        .write_all(req.as_bytes())
        .map_err(|e| format!("failed to request an open code from surface {name}: {e}"))?;

    let mut raw = Vec::new();
    let mut chunk = [0u8; 4096];
    loop {
        if raw.len() >= MAX_OPEN_CODE_RESPONSE_BYTES {
            return Err(format!(
                "surface {name} gave an answer blyte does not understand"
            ));
        }
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            return Err(format!("surface {name} timed out on port {port}"));
        }
        let _ = stream.set_read_timeout(Some(remaining));
        let max_read = (MAX_OPEN_CODE_RESPONSE_BYTES - raw.len()).min(chunk.len());
        match stream.read(&mut chunk[..max_read]) {
            Ok(0) => break,
            Ok(n) => raw.extend_from_slice(&chunk[..n]),
            Err(e) if e.kind() == ErrorKind::Interrupted => continue,
            Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
                return Err(format!("surface {name} timed out on port {port}"));
            }
            Err(e) => {
                return Err(format!("failed to read answer from surface {name}: {e}"));
            }
        }
    }

    let text = std::str::from_utf8(&raw)
        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
    let (head, resp_body) = text
        .split_once("\r\n\r\n")
        .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
    let status = parse_http_status(head)
        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
    if status != 200 {
        return Err(format!(
            "surface {name} could not create an open code (HTTP {status})"
        ));
    }
    let parsed: serde_json::Value = serde_json::from_str(resp_body)
        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
    let code = parsed
        .get("code")
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
    Ok(code.to_string())
}

fn known_folders(state_dir: &Path, entries: &[RegistryEntry]) -> Result<Vec<String>, String> {
    let mut folders = BTreeSet::new();
    let repos_path = state_dir.join("repos");
    match std::fs::read_to_string(&repos_path) {
        Ok(content) => {
            for line in content.lines() {
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    continue;
                }
                let path = PathBuf::from(trimmed);
                if path.is_dir() {
                    folders.insert(trimmed.to_string());
                }
            }
        }
        Err(e) if e.kind() == ErrorKind::NotFound => {}
        Err(e) => {
            return Err(format!("failed to read {}: {e}", repos_path.display()));
        }
    }
    for entry in entries {
        folders.insert(entry.root.to_string_lossy().into_owned());
    }
    Ok(folders.into_iter().collect())
}

pub fn surfaces_payload(
    registry_dir: &Path,
    state_dir: &Path,
    current_id: &str,
    stopped: &[StoppedSurface],
) -> Result<serde_json::Value, String> {
    let listing = live_entries(registry_dir)?;
    let mut entries = listing.entries;
    entries.sort_by(|a, b| {
        a.name
            .cmp(&b.name)
            .then_with(|| a.started_at.cmp(&b.started_at))
    });
    if !entries.iter().any(|entry| entry.id == current_id) {
        return Err(format!(
            "current surface {current_id} is not in the surface registry"
        ));
    }
    let folders = known_folders(state_dir, &entries)?;
    let surfaces: Vec<serde_json::Value> = entries
        .iter()
        .map(|entry| {
            let (url, error) = match surface_url(entry) {
                Ok(url) => (Some(url), None),
                Err(err) => (None, Some(err)),
            };
            let (stale, stale_error) = match entry.runtime.is_stale() {
                Ok(stale) => (Some(stale), None),
                Err(err) => (None, Some(err)),
            };
            serde_json::json!({
                "id": entry.id,
                "name": entry.name,
                "root": entry.root.to_string_lossy(),
                "branch": entry.branch,
                "doing": entry.doing,
                "state": entry.state,
                "version": entry.runtime.version,
                "boot_id": entry.runtime.boot_id,
                "stale": stale,
                "stale_error": stale_error,
                "current": entry.id == current_id,
                "url": url,
                "error": error,
            })
        })
        .collect();
    let unreadable: Vec<serde_json::Value> = listing
        .unreadable
        .iter()
        .map(|record| {
            serde_json::json!({
                "path": record.path.to_string_lossy(),
                "reason": record.reason,
            })
        })
        .collect();
    Ok(serde_json::json!({
        "surfaces": surfaces,
        "stopped": stopped,
        "folders": folders,
        "unreadable": unreadable,
    }))
}

pub fn run_open(
    dir: &Path,
    name: &str,
    opener: &dyn Fn(&str),
    out: &mut dyn Write,
    err: &mut dyn Write,
) -> i32 {
    let entry = match find_by_name(dir, name) {
        Ok(entry) => entry,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    let token = match read_surface_token(&entry) {
        Ok(token) => token,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    let code = match request_open_code(&entry, &token) {
        Ok(code) => code,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    let url = format!("http://127.0.0.1:{}/#open={code}", entry.port);
    opener(&url);
    let _ = writeln!(out, "blyte: opened surface {}", entry.name);
    0
}

fn http_json_request(
    name: &str,
    port: u16,
    method: &str,
    path: &str,
    token: &str,
    body: Option<&str>,
    timeout: Duration,
) -> Result<(u16, String), String> {
    let deadline = Instant::now() + timeout;
    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| {
        if e.kind() == ErrorKind::ConnectionRefused {
            format!("surface {name} refused the connection on port {port}")
        } else {
            format!("cannot connect to surface {name} on port {port}: {e}")
        }
    })?;

    let remaining = deadline.saturating_duration_since(Instant::now());
    if remaining.is_zero() {
        return Err(format!("surface {name} timed out on port {port}"));
    }
    let _ = stream.set_write_timeout(Some(remaining));

    let req = match body {
        Some(payload) => format!(
            "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
            payload.len()
        ),
        None => format!(
            "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nConnection: close\r\n\r\n"
        ),
    };
    stream
        .write_all(req.as_bytes())
        .map_err(|e| format!("failed to contact surface {name}: {e}"))?;

    let mut raw = Vec::new();
    let mut chunk = [0u8; 4096];
    loop {
        if raw.len() >= MAX_OPEN_CODE_RESPONSE_BYTES {
            return Err(format!(
                "surface {name} gave an answer blyte does not understand"
            ));
        }
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            return Err(format!("surface {name} timed out on port {port}"));
        }
        let _ = stream.set_read_timeout(Some(remaining));
        let max_read = (MAX_OPEN_CODE_RESPONSE_BYTES - raw.len()).min(chunk.len());
        match stream.read(&mut chunk[..max_read]) {
            Ok(0) => break,
            Ok(n) => raw.extend_from_slice(&chunk[..n]),
            Err(e) if e.kind() == ErrorKind::Interrupted => continue,
            Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
                return Err(format!("surface {name} timed out on port {port}"));
            }
            Err(e) => {
                return Err(format!("failed to read answer from surface {name}: {e}"));
            }
        }
    }

    let text = std::str::from_utf8(&raw)
        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
    let (head, resp_body) = text
        .split_once("\r\n\r\n")
        .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
    let status = parse_http_status(head)
        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
    Ok((status, resp_body.to_string()))
}

pub fn request_reload(entry: &RegistryEntry, token: &str) -> Result<(), String> {
    let (status, resp_body) = http_json_request(
        &entry.name,
        entry.port,
        "POST",
        "/api/reload",
        token,
        Some("{}"),
        OPEN_CODE_TIMEOUT,
    )?;
    if status != 200 {
        let detail = serde_json::from_str::<serde_json::Value>(&resp_body)
            .ok()
            .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string));
        return match detail {
            Some(msg) if !msg.trim().is_empty() => Err(format!(
                "surface {} failed to reload (HTTP {status}): {msg}",
                entry.name
            )),
            _ => Err(format!(
                "surface {} failed to reload (HTTP {status})",
                entry.name
            )),
        };
    }
    let parsed: serde_json::Value = serde_json::from_str(&resp_body).map_err(|_| {
        format!(
            "surface {} gave an answer blyte does not understand",
            entry.name
        )
    })?;
    if parsed.get("reloading").and_then(|v| v.as_bool()) != Some(true) {
        return Err(format!(
            "surface {} gave an answer blyte does not understand",
            entry.name
        ));
    }
    Ok(())
}

fn wait_for_reloaded_surface(
    entry: &RegistryEntry,
    token: &str,
    timeout: Duration,
) -> Result<(String, String), String> {
    let deadline = Instant::now() + timeout;
    let mut last_error: Option<String> = None;
    while Instant::now() < deadline {
        let remaining = deadline.saturating_duration_since(Instant::now());
        let step_timeout = remaining.min(Duration::from_secs(2));
        match http_json_request(
            &entry.name,
            entry.port,
            "GET",
            "/api/session",
            token,
            None,
            step_timeout,
        ) {
            Ok((200, body)) => {
                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&body) {
                    if let (Some(boot_id), Some(version)) = (
                        parsed
                            .get("boot_id")
                            .and_then(|v| v.as_str())
                            .map(str::trim),
                        parsed
                            .get("version")
                            .and_then(|v| v.as_str())
                            .map(str::trim),
                    ) {
                        if !boot_id.is_empty() && boot_id != entry.runtime.boot_id {
                            return Ok((version.to_string(), boot_id.to_string()));
                        }
                    }
                }
            }
            Ok((status, _)) => {
                last_error = Some(format!("HTTP {status} while waiting for reload"));
            }
            Err(e) => {
                last_error = Some(e);
            }
        }
        std::thread::sleep(RELOAD_POLL_INTERVAL);
    }
    match last_error {
        Some(e) => Err(format!(
            "surface {} did not come back after reload within {}s ({e})",
            entry.name,
            timeout.as_secs()
        )),
        None => Err(format!(
            "surface {} did not report a new boot_id after reload within {}s",
            entry.name,
            timeout.as_secs()
        )),
    }
}

fn select_reload_targets(
    dir: &Path,
    cwd: &Path,
    target: Option<&str>,
    all: bool,
    err: &mut dyn Write,
) -> Result<Vec<RegistryEntry>, String> {
    let listing = live_entries(dir)?;
    report_unreadable(&listing.unreadable, err);
    let mut entries = listing.entries;
    entries.sort_by(|a, b| {
        a.name
            .cmp(&b.name)
            .then_with(|| a.started_at.cmp(&b.started_at))
    });

    if all {
        return Ok(entries);
    }

    if let Some(name_or_id) = target {
        let matches: Vec<RegistryEntry> = entries
            .iter()
            .filter(|e| e.id == name_or_id || e.name == name_or_id)
            .cloned()
            .collect();
        return match matches.len() {
            0 => {
                if entries.is_empty() {
                    Err(format!(
                        "no running surface named {name_or_id} (no surfaces are running)"
                    ))
                } else {
                    let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
                    Err(format!(
                        "no running surface named {name_or_id}; running surfaces: {}",
                        names.join(", ")
                    ))
                }
            }
            1 => Ok(matches),
            _ => {
                let ids: Vec<&str> = matches.iter().map(|e| e.id.as_str()).collect();
                Err(format!(
                    "more than one running surface is named {name_or_id}; specify by id: {}",
                    ids.join(", ")
                ))
            }
        };
    }

    let root = crate::serve::resolve_folder(cwd)?;
    let matches: Vec<RegistryEntry> = entries.into_iter().filter(|e| e.root == root).collect();
    match matches.len() {
        0 => Err(format!("no running surface for {}", root.display())),
        1 => Ok(matches),
        _ => {
            let names: Vec<String> = matches
                .iter()
                .map(|e| format!("{} ({})", e.name, e.id))
                .collect();
            Err(format!(
                "multiple surfaces are running for {}; specify one by name or id: {}",
                root.display(),
                names.join(", ")
            ))
        }
    }
}

pub fn run_reload(
    dir: &Path,
    cwd: &Path,
    target: Option<&str>,
    all: bool,
    out: &mut dyn Write,
    err: &mut dyn Write,
) -> i32 {
    let targets = match select_reload_targets(dir, cwd, target, all, err) {
        Ok(targets) => targets,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    if targets.is_empty() {
        let _ = writeln!(out, "blyte: no surfaces are running");
        return 0;
    }

    let mut had_error = false;
    let mut pending: Vec<(RegistryEntry, String)> = Vec::new();
    for entry in targets {
        let token = match read_surface_token(&entry) {
            Ok(token) => token,
            Err(e) => {
                let _ = writeln!(err, "blyte: {e}");
                had_error = true;
                continue;
            }
        };
        if let Err(e) = request_reload(&entry, &token) {
            let _ = writeln!(err, "blyte: {e}");
            had_error = true;
            continue;
        }
        pending.push((entry, token));
    }

    for (entry, token) in pending {
        match wait_for_reloaded_surface(&entry, &token, RELOAD_WAIT_TIMEOUT) {
            Ok((new_version, _new_boot_id)) => {
                if !new_version.is_empty() && new_version != entry.runtime.version {
                    let _ = writeln!(
                        out,
                        "blyte: reloaded surface {} ({} -> {})",
                        entry.name, entry.runtime.version, new_version
                    );
                } else {
                    let version_label = if new_version.is_empty() {
                        entry.runtime.version.as_str()
                    } else {
                        new_version.as_str()
                    };
                    let _ = writeln!(
                        out,
                        "blyte: reloaded surface {} ({version_label})",
                        entry.name
                    );
                }
            }
            Err(e) => {
                let _ = writeln!(err, "blyte: {e}");
                had_error = true;
            }
        }
    }

    if had_error {
        1
    } else {
        0
    }
}

#[cfg(test)]
mod tests {
    use super::count_running_runs_at;
    use std::time::{Duration, UNIX_EPOCH};

    #[test]
    fn count_running_runs_at_rejects_pre_epoch_time() {
        let tmp = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(tmp.path().join(".git")).expect("create .git");
        let pre_epoch = UNIX_EPOCH
            .checked_sub(Duration::from_secs(1))
            .expect("pre-epoch SystemTime");

        let err = count_running_runs_at(tmp.path(), pre_epoch)
            .expect_err("expected error for system clock before UNIX_EPOCH");
        assert!(
            err.contains("UNIX_EPOCH"),
            "error should name UNIX_EPOCH: {err}"
        );
    }
}