blyte 0.57.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
989
990
991
992
993
994
995
996
997
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::cli::SurfaceArgs;
use crate::http::{Request, Response};
use crate::queue_actions::{Action, Hold};
use crate::repl::ReplConfig;
use crate::requests::{Publisher, RealPublisher, RequestActionError, RequestsState};
use crate::session::{AgentRunner, AnswerError, ApprovalAnswer, Attachment, Session};

pub const TOKEN_HEADER: &str = "X-Blyte-Token";

const INDEX_HTML: &str = include_str!("../assets/surface/index.html");
const MAX_WAIT_MS: u64 = 25_000;
const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
const TOKEN_BYTES: usize = 32;

static SESSION_COUNTER: AtomicU64 = AtomicU64::new(1);

pub struct Surface {
    pub root: PathBuf,
    pub repo: String,
    pub session: Session,
    pub session_id: String,
    pub started_at: u64,
    pub days: u64,
    pub token: String,
    pub requests: Arc<RequestsState>,
    pub publisher: Arc<dyn Publisher>,
}

pub fn generate_token() -> Result<String, String> {
    let mut bytes = [0u8; TOKEN_BYTES];
    let mut file = std::fs::File::open("/dev/urandom")
        .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
    file.read_exact(&mut bytes)
        .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        out.push(HEX[(byte >> 4) as usize] as char);
        out.push(HEX[(byte & 0x0f) as usize] as char);
    }
    Ok(out)
}

pub fn constant_time_eq(provided: &[u8], expected: &[u8]) -> bool {
    let mut diff = provided.len() ^ expected.len();
    for (i, &exp) in expected.iter().enumerate() {
        let prov = provided.get(i).copied().unwrap_or(0);
        diff |= usize::from(prov ^ exp);
    }
    std::hint::black_box(diff) == 0
}

fn has_valid_token(surface: &Surface, req: &Request) -> bool {
    if surface.token.is_empty() {
        return false;
    }
    let mut values = req.header_values(TOKEN_HEADER);
    let Some(provided) = values.next() else {
        return false;
    };
    if values.next().is_some() {
        return false;
    }
    constant_time_eq(provided.as_bytes(), surface.token.as_bytes())
}

#[derive(Serialize, Deserialize)]
struct SurfaceFile {
    pid: u32,
    port: u16,
    session_id: String,
    started_at: u64,
}

#[derive(Serialize)]
struct RunWithHold<'a> {
    #[serde(flatten)]
    run: &'a crate::replay::Run,
    hold: Option<Hold>,
}

#[derive(Serialize)]
struct LiveRunsResponse<'a> {
    generated_at: u64,
    repo: &'a str,
    running: &'a [crate::live_runs::RunningRun],
    runs: Vec<RunWithHold<'a>>,
    skipped: &'a [crate::replay::Skipped],
}

fn json_error(status: u16, msg: impl Into<String>) -> Response {
    Response::json(status, &serde_json::json!({ "error": msg.into() }))
}

fn method_not_allowed(req: &Request) -> Response {
    json_error(
        405,
        format!("method {} not allowed for {}", req.method, req.path),
    )
}

fn is_valid_run_id(id: &str) -> bool {
    !id.is_empty()
        && id != "."
        && id != ".."
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
}

fn parse_json_object(body: &[u8]) -> Result<serde_json::Map<String, serde_json::Value>, Response> {
    let val: serde_json::Value = serde_json::from_slice(body)
        .map_err(|e| json_error(400, format!("invalid JSON body: {e}")))?;
    val.as_object()
        .cloned()
        .ok_or_else(|| json_error(400, "request body must be a JSON object"))
}

fn session_response(surface: &Surface) -> Response {
    let info = surface.session.info();
    Response::json(
        200,
        &serde_json::json!({
            "session_id": surface.session_id,
            "repo": surface.repo,
            "started_at": surface.started_at,
            "model": info.model,
            "effort": info.effort,
            "effort_supported": info.effort_supported,
            "busy": info.busy,
            "queued": info.queued,
            "last_seq": info.last_seq,
        }),
    )
}

fn handle_events(surface: &Surface, req: &Request) -> Response {
    let after_raw = match req.query_value("after") {
        Some(v) => v,
        None => return json_error(400, "missing required query parameter: after"),
    };
    let after = match after_raw.parse::<u64>() {
        Ok(v) => v,
        Err(_) => {
            return json_error(
                400,
                format!("query parameter after must be a non-negative integer, got '{after_raw}'"),
            );
        }
    };
    let wait_ms = match req.query_value("wait_ms") {
        None => 0,
        Some(raw) => match raw.parse::<u64>() {
            Ok(v) if v <= MAX_WAIT_MS => v,
            Ok(v) => {
                return json_error(
                    400,
                    format!("query parameter wait_ms must be at most {MAX_WAIT_MS}, got {v}"),
                );
            }
            Err(_) => {
                return json_error(
                    400,
                    format!("query parameter wait_ms must be a non-negative integer, got '{raw}'"),
                );
            }
        },
    };
    let entries = surface
        .session
        .entries_after(after, Duration::from_millis(wait_ms));
    let last_seq = surface.session.info().last_seq;
    Response::json(
        200,
        &serde_json::json!({
            "entries": entries,
            "last_seq": last_seq,
        }),
    )
}

fn handle_post_message(surface: &Surface, req: &Request) -> Response {
    let obj = match parse_json_object(&req.body) {
        Ok(o) => o,
        Err(resp) => return resp,
    };
    let text = match obj.get("text") {
        Some(serde_json::Value::String(s)) => s.clone(),
        Some(_) => return json_error(400, "field text must be a string"),
        None => return json_error(400, "missing required field: text"),
    };
    let report_ids: Vec<String> = match obj.get("reports") {
        None | Some(serde_json::Value::Null) => Vec::new(),
        Some(serde_json::Value::Array(arr)) => {
            let mut ids = Vec::with_capacity(arr.len());
            for item in arr {
                match item.as_str() {
                    Some(s) => ids.push(s.to_string()),
                    None => return json_error(400, "field reports must be an array of strings"),
                }
            }
            ids
        }
        Some(_) => return json_error(400, "field reports must be an array of strings"),
    };

    let mut attachments = Vec::with_capacity(report_ids.len());
    for id in report_ids {
        let path = surface.root.join(".wt").join(format!("{id}.report.md"));
        if !is_valid_run_id(&id) {
            return json_error(
                400,
                format!("invalid report run id '{id}' (path: {})", path.display()),
            );
        }
        match std::fs::read_to_string(&path) {
            Ok(body) => attachments.push(Attachment {
                run: id,
                text: body,
            }),
            Err(e) => {
                return json_error(
                    400,
                    format!(
                        "cannot read report for run '{id}' at {}: {e}",
                        path.display()
                    ),
                );
            }
        }
    }

    match surface.session.submit(&text, attachments) {
        Ok(seq) => Response::json(200, &serde_json::json!({ "seq": seq })),
        Err(e) => json_error(400, e),
    }
}

fn handle_models() -> Response {
    let discovered = blyte_provider::discover_all_models();
    let mut models = Vec::new();
    let mut unavailable = Vec::new();
    let mut error_parts = Vec::new();

    for (provider, result) in discovered {
        match result {
            Ok(list) => {
                for m in list {
                    let effort_supported = crate::session::model_supports_effort(&m.id);
                    models.push(serde_json::json!({
                        "id": m.id,
                        "effort_supported": effort_supported,
                    }));
                }
            }
            Err(e) => {
                let err_text = e.to_string();
                error_parts.push(format!("{provider}: {err_text}"));
                unavailable.push(serde_json::json!({
                    "provider": provider,
                    "error": err_text,
                }));
            }
        }
    }

    if models.is_empty() {
        let msg = if error_parts.is_empty() {
            "no models listed by any provider".to_string()
        } else {
            format!("no models available: {}", error_parts.join("; "))
        };
        return json_error(502, msg);
    }

    Response::json(
        200,
        &serde_json::json!({
            "models": models,
            "unavailable": unavailable,
        }),
    )
}

fn handle_post_model(surface: &Surface, req: &Request) -> Response {
    let obj = match parse_json_object(&req.body) {
        Ok(o) => o,
        Err(resp) => return resp,
    };
    let model = match obj.get("model") {
        Some(serde_json::Value::String(s)) => s.clone(),
        Some(_) => return json_error(400, "field model must be a string"),
        None => return json_error(400, "missing required field: model"),
    };
    if model.trim().is_empty() {
        return json_error(400, "field model must not be empty");
    }
    if let Err(e) = blyte_provider::resolve_provider(Some(&model)) {
        return json_error(400, e.to_string());
    }
    if let Err(e) = surface.session.set_model(&model) {
        return json_error(400, e);
    }
    session_response(surface)
}

fn handle_post_effort(surface: &Surface, req: &Request) -> Response {
    let obj = match parse_json_object(&req.body) {
        Ok(o) => o,
        Err(resp) => return resp,
    };
    let effort = match obj.get("effort") {
        Some(serde_json::Value::Null) => None,
        Some(serde_json::Value::String(s)) => Some(s.clone()),
        Some(_) => return json_error(400, "field effort must be a string or null"),
        None => return json_error(400, "missing required field: effort"),
    };
    if let Err(e) = surface.session.set_effort(effort.as_deref()) {
        return json_error(400, e);
    }
    session_response(surface)
}

fn handle_post_approval(surface: &Surface, id: &str, req: &Request) -> Response {
    let obj = match parse_json_object(&req.body) {
        Ok(o) => o,
        Err(resp) => return resp,
    };
    if obj.len() != 1 {
        return json_error(400, "request body must contain only field answer");
    }
    let answer = match obj.get("answer") {
        Some(serde_json::Value::String(s)) if s == "yes" => ApprovalAnswer::Yes,
        Some(serde_json::Value::String(s)) if s == "no" => ApprovalAnswer::No,
        Some(serde_json::Value::String(other)) => {
            return json_error(
                400,
                format!("field answer must be \"yes\" or \"no\", got '{other}'"),
            );
        }
        Some(_) => return json_error(400, "field answer must be \"yes\" or \"no\""),
        None => return json_error(400, "missing required field: answer"),
    };
    match surface.session.answer_approval(id, answer) {
        Ok(seq) => Response::json(
            200,
            &serde_json::json!({
                "id": id,
                "answer": answer.as_str(),
                "seq": seq,
            }),
        ),
        Err(AnswerError::NotFound) => json_error(404, format!("unknown approval id: {id}")),
        Err(AnswerError::AlreadyAnswered) => {
            json_error(409, format!("approval {id} has already been answered"))
        }
    }
}

fn handle_runs(surface: &Surface, now: u64) -> Response {
    let mut live = match crate::live_runs::collect(&surface.root, now, surface.days) {
        Ok(l) => l,
        Err(e) => return json_error(500, e),
    };
    let mut any_written = false;
    for run in &live.runs {
        if run.checks_recorded {
            continue;
        }
        match crate::queue_actions::ensure_checks(&surface.root, &run.id) {
            Ok(true) => any_written = true,
            Ok(false) => {}
            Err(e) => return json_error(500, e),
        }
    }
    if any_written {
        live = match crate::live_runs::collect(&surface.root, now, surface.days) {
            Ok(l) => l,
            Err(e) => return json_error(500, e),
        };
    }

    let mut runs_with_hold = Vec::with_capacity(live.runs.len());
    for run in &live.runs {
        let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
            Ok(h) => h,
            Err(e) => return json_error(500, e),
        };
        runs_with_hold.push(RunWithHold { run, hold });
    }

    let mut triggered = BTreeSet::new();
    for run in &live.runs {
        if run.research {
            continue;
        }
        if let Some(ref req_id) = run.request {
            if triggered.insert(req_id.clone()) {
                if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
                    surface
                        .session
                        .record_error(&format!("combine trigger failed for {req_id}: {e}"));
                }
            }
        }
    }

    let payload = LiveRunsResponse {
        generated_at: live.generated_at,
        repo: &live.repo,
        running: &live.running,
        runs: runs_with_hold,
        skipped: &live.skipped,
    };
    match serde_json::to_value(&payload) {
        Ok(val) => Response::json(200, &val),
        Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
    }
}

fn handle_run_diff(surface: &Surface, id: &str) -> Response {
    if !is_valid_run_id(id) {
        return json_error(404, format!("unknown run: {id}"));
    }
    let wt_dir = surface.root.join(".wt");
    let wt = wt_dir.join(id);
    let summary = wt_dir.join(format!("{id}.json"));
    let report_json = wt_dir.join(format!("{id}.report.json"));
    let report_md = wt_dir.join(format!("{id}.report.md"));
    if !wt.exists() && !summary.exists() && !report_json.exists() && !report_md.exists() {
        return json_error(404, format!("unknown run: {id}"));
    }
    match crate::queue_actions::compute_review(&surface.root, id, true) {
        Ok(data) => {
            let body = if !data.wt_exists {
                "(worktree removed)\n".to_string()
            } else if data.diff_out.is_empty() {
                String::new()
            } else {
                format!("{}\n", data.diff_out)
            };
            Response::text(200, &body)
        }
        Err(e) => {
            if !wt.is_dir() || !wt.join(".git").exists() {
                json_error(404, e)
            } else {
                json_error(500, e)
            }
        }
    }
}

fn parse_action(raw: &str) -> Result<Action, String> {
    match raw {
        "accept" => Ok(Action::Accept),
        "send_back" => Ok(Action::SendBack),
        "redo" => Ok(Action::Redo),
        "hold" => Ok(Action::Hold),
        "mark_read" => Ok(Action::MarkRead),
        other => Err(format!(
            "unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
        )),
    }
}

fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
    let obj = match parse_json_object(&req.body) {
        Ok(o) => o,
        Err(resp) => return resp,
    };
    let action_str = match obj.get("action") {
        Some(serde_json::Value::String(s)) => s.clone(),
        Some(_) => return json_error(400, "field action must be a string"),
        None => return json_error(400, "missing required field: action"),
    };
    let action = match parse_action(&action_str) {
        Ok(a) => a,
        Err(e) => return json_error(400, e),
    };
    let note = match obj.get("note") {
        None | Some(serde_json::Value::Null) => None,
        Some(serde_json::Value::String(s)) => Some(s.clone()),
        Some(_) => return json_error(400, "field note must be a string or null"),
    };

    let decision =
        match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
            Ok(d) => d,
            Err(e) => return json_error(400, e),
        };
    let seq = match surface.session.record_decision(
        &decision.run,
        &action_str,
        decision.note.as_deref(),
        decision.orchestrator_message.as_deref(),
    ) {
        Ok(s) => s,
        Err(e) => return json_error(500, e),
    };
    if action == Action::Accept {
        match crate::requests::run_request_id(&surface.root, &decision.run) {
            Ok(Some(req_id)) => {
                if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
                    surface
                        .session
                        .record_error(&format!("combine trigger failed for {req_id}: {e}"));
                }
            }
            Ok(None) => {}
            Err(e) => return json_error(500, e),
        }
    }
    Response::json(
        200,
        &serde_json::json!({
            "decision": {
                "run": decision.run,
                "action": action_str,
                "note": decision.note,
                "orchestrator_message": decision.orchestrator_message,
            },
            "seq": seq,
        }),
    )
}

fn handle_map(surface: &Surface) -> Response {
    match crate::map::build(&surface.root, &surface.repo) {
        Ok(data) => match serde_json::to_value(&data) {
            Ok(val) => Response::json(200, &val),
            Err(e) => json_error(500, format!("failed to serialize map: {e}")),
        },
        Err(e) => json_error(422, e),
    }
}

fn handle_requests(surface: &Surface) -> Response {
    match crate::requests::list_requests(surface) {
        Ok(list) => match serde_json::to_value(&list) {
            Ok(val) => Response::json(200, &val),
            Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
        },
        Err(e) => json_error(500, e),
    }
}

fn request_action_error_response(err: RequestActionError) -> Response {
    match err {
        RequestActionError::BadRequest(msg) => json_error(400, msg),
        RequestActionError::Conflict(msg) => json_error(409, msg),
        RequestActionError::Internal(msg) => json_error(500, msg),
    }
}

fn handle_request_push(surface: &Surface, id: &str) -> Response {
    match crate::requests::push_request(surface, id) {
        Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
        Err(err) => request_action_error_response(err),
    }
}

fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
    if let Err(e) = crate::dispatch::validate_request_id(id) {
        return json_error(400, e);
    }
    let obj = match parse_json_object(&req.body) {
        Ok(o) => o,
        Err(resp) => return resp,
    };
    let title = match obj.get("title") {
        Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
        Some(serde_json::Value::String(_)) => {
            return json_error(400, "field title must not be empty");
        }
        Some(_) => return json_error(400, "field title must be a string"),
        None => return json_error(400, "missing required field: title"),
    };
    let body = match obj.get("body") {
        None | Some(serde_json::Value::Null) => String::new(),
        Some(serde_json::Value::String(s)) => s.clone(),
        Some(_) => return json_error(400, "field body must be a string"),
    };
    match crate::requests::open_request_pull_request(surface, id, &title, &body) {
        Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
        Err(err) => request_action_error_response(err),
    }
}

pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
    if req.method == "POST" && !has_valid_token(surface, req) {
        return json_error(
            403,
            "missing or invalid surface token; open the page from the URL blyte printed",
        );
    }

    if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
        if req.method != "GET" {
            return method_not_allowed(req);
        }
        return Response {
            status,
            content_type,
            body,
        };
    }

    match req.path.as_str() {
        "/" | "/index.html" => {
            if req.method != "GET" {
                return method_not_allowed(req);
            }
            Response::html(INDEX_HTML.as_bytes().to_vec())
        }
        "/api/session" => {
            if req.method != "GET" {
                return method_not_allowed(req);
            }
            session_response(surface)
        }
        "/api/session/events" => {
            if req.method != "GET" {
                return method_not_allowed(req);
            }
            handle_events(surface, req)
        }
        "/api/session/messages" => {
            if req.method != "POST" {
                return method_not_allowed(req);
            }
            handle_post_message(surface, req)
        }
        "/api/models" => {
            if req.method != "GET" {
                return method_not_allowed(req);
            }
            handle_models()
        }
        "/api/session/model" => {
            if req.method != "POST" {
                return method_not_allowed(req);
            }
            handle_post_model(surface, req)
        }
        "/api/session/effort" => {
            if req.method != "POST" {
                return method_not_allowed(req);
            }
            handle_post_effort(surface, req)
        }
        "/api/runs" => {
            if req.method != "GET" {
                return method_not_allowed(req);
            }
            handle_runs(surface, now)
        }
        "/api/requests" => {
            if req.method != "GET" {
                return method_not_allowed(req);
            }
            handle_requests(surface)
        }
        "/api/map" => {
            if req.method != "GET" {
                return method_not_allowed(req);
            }
            handle_map(surface)
        }
        path => {
            if let Some(id) = path.strip_prefix("/api/session/approvals/") {
                if !id.is_empty() && !id.contains('/') {
                    if req.method != "POST" {
                        return method_not_allowed(req);
                    }
                    return handle_post_approval(surface, id, req);
                }
            }
            if let Some(rest) = path.strip_prefix("/api/runs/") {
                if let Some(id) = rest.strip_suffix("/diff") {
                    if !id.is_empty() && !id.contains('/') {
                        if req.method != "GET" {
                            return method_not_allowed(req);
                        }
                        return handle_run_diff(surface, id);
                    }
                }
                if let Some(id) = rest.strip_suffix("/decision") {
                    if !id.is_empty() && !id.contains('/') {
                        if req.method != "POST" {
                            return method_not_allowed(req);
                        }
                        return handle_run_decision(surface, id, req, now);
                    }
                }
            }
            if let Some(rest) = path.strip_prefix("/api/requests/") {
                if let Some(id) = rest.strip_suffix("/push") {
                    if req.method != "POST" {
                        return method_not_allowed(req);
                    }
                    return handle_request_push(surface, id);
                }
                if let Some(id) = rest.strip_suffix("/pull-request") {
                    if req.method != "POST" {
                        return method_not_allowed(req);
                    }
                    return handle_request_pull_request(surface, id, req);
                }
            }
            json_error(404, format!("not found: {}", req.path))
        }
    }
}

fn find_git_toplevel(dir: &Path) -> Result<PathBuf, String> {
    let out = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(dir)
        .output()
        .map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
    if !out.status.success() {
        return Err(format!("not inside a git repository ({})", dir.display()));
    }
    let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if path_str.is_empty() {
        return Err(format!("not inside a git repository ({})", dir.display()));
    }
    Ok(PathBuf::from(path_str))
}

fn repo_name_for(root: &Path) -> Result<String, String> {
    root.file_name()
        .and_then(|s| s.to_str())
        .filter(|s| !s.is_empty())
        .map(String::from)
        .ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
}

fn now_duration() -> Result<Duration, String> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|e| format!("system clock is before Unix epoch: {e}"))
}

fn new_session_id(nanos: u128) -> String {
    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("surface-{}-{nanos}-{seq}", std::process::id())
}

fn probe_existing_surface(port: u16, expected_session_id: &str) -> bool {
    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let mut stream = match TcpStream::connect_timeout(&addr, PROBE_TIMEOUT) {
        Ok(s) => s,
        Err(_) => return false,
    };
    let _ = stream.set_read_timeout(Some(PROBE_TIMEOUT));
    let _ = stream.set_write_timeout(Some(PROBE_TIMEOUT));
    let req =
        format!("GET /api/session HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
    if stream.write_all(req.as_bytes()).is_err() {
        return false;
    }
    let mut raw = Vec::new();
    if stream.read_to_end(&mut raw).is_err() {
        return false;
    }
    let text = match std::str::from_utf8(&raw) {
        Ok(s) => s,
        Err(_) => return false,
    };
    let (head, body) = match text.split_once("\r\n\r\n") {
        Some(parts) => parts,
        None => return false,
    };
    let status_line = head.lines().next().unwrap_or("");
    if !(status_line.starts_with("HTTP/1.1 200") || status_line.starts_with("HTTP/1.0 200")) {
        return false;
    }
    let val: serde_json::Value = match serde_json::from_str(body) {
        Ok(v) => v,
        Err(_) => return false,
    };
    val.get("session_id").and_then(|v| v.as_str()) == Some(expected_session_id)
}

fn open_browser(url: &str) {
    #[cfg(target_os = "macos")]
    let cmd = "open";
    #[cfg(not(target_os = "macos"))]
    let cmd = "xdg-open";
    if let Err(e) = Command::new(cmd).arg(url).spawn() {
        eprintln!("blyte: could not open a browser with {cmd}: {e}; open {url} yourself");
    }
}

fn resolve_initial_model(config: &ReplConfig) -> String {
    if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
        return m.to_string();
    }
    if let Ok(m) = std::env::var("BLYTE_MODEL") {
        if !m.trim().is_empty() {
            return m;
        }
    }
    if let Ok(p) = blyte_provider::resolve_provider(None) {
        return p.model_id();
    }
    "gemini-3.8-flash-high".to_string()
}

pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
    run_with_io(args, config, &mut std::io::stdout(), &mut std::io::stderr())
}

pub fn run_with_io(
    args: &SurfaceArgs,
    mut config: ReplConfig,
    out: &mut dyn Write,
    err: &mut dyn Write,
) -> i32 {
    let root = match find_git_toplevel(&config.repo_root) {
        Ok(r) => r,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };
    let repo = match repo_name_for(&root) {
        Ok(r) => r,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    let wt_dir = root.join(".wt");
    let surface_file_path = wt_dir.join("surface.json");
    match std::fs::read_to_string(&surface_file_path) {
        Ok(raw) => match serde_json::from_str::<SurfaceFile>(&raw) {
            Ok(existing) => {
                if probe_existing_surface(existing.port, &existing.session_id) {
                    let url = format!("http://127.0.0.1:{}/", existing.port);
                    let _ = writeln!(out, "blyte: surface already running at {url}");
                    let _ = out.flush();
                    if !args.no_open {
                        open_browser(&url);
                    }
                    return 0;
                }
                let _ = writeln!(
                    err,
                    "blyte: stale surface file {} (port {}, session {}); replacing it",
                    surface_file_path.display(),
                    existing.port,
                    existing.session_id
                );
                let _ = err.flush();
            }
            Err(e) => {
                let _ = writeln!(
                    err,
                    "blyte: cannot parse {}: {e}",
                    surface_file_path.display()
                );
                return 1;
            }
        },
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => {
            let _ = writeln!(
                err,
                "blyte: cannot read {}: {e}",
                surface_file_path.display()
            );
            return 1;
        }
    }

    if !config.orchestrate {
        config.orchestrate = true;
        if config.max_turns == 25 || config.max_turns == 60 {
            config.max_turns = 1000;
        }
        if config.fold_budget.is_none() {
            config.fold_budget = Some(100_000);
        }
    }
    config.repo_root = root.clone();

    let model = resolve_initial_model(&config);
    let session = Session::start_with(model, |approver| {
        Box::new(AgentRunner::new(&config, approver))
    });
    let started_dur = match now_duration() {
        Ok(d) => d,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };
    let started_at = started_dur.as_secs();
    let session_id = new_session_id(started_dur.as_nanos());
    let token = match generate_token() {
        Ok(t) => t,
        Err(e) => {
            let _ = writeln!(err, "blyte: {e}");
            return 1;
        }
    };

    let bind_addr = format!("127.0.0.1:{}", args.port);
    let listener = match TcpListener::bind(&bind_addr) {
        Ok(l) => l,
        Err(e) => {
            let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
            return 1;
        }
    };
    let actual_port = match listener.local_addr() {
        Ok(a) => a.port(),
        Err(e) => {
            let _ = writeln!(err, "blyte: failed to read listener address: {e}");
            return 1;
        }
    };

    if let Err(e) = std::fs::create_dir_all(&wt_dir) {
        let _ = writeln!(err, "blyte: cannot create {}: {e}", wt_dir.display());
        return 1;
    }
    let record = SurfaceFile {
        pid: std::process::id(),
        port: actual_port,
        session_id: session_id.clone(),
        started_at,
    };
    let record_json = match serde_json::to_string_pretty(&record) {
        Ok(s) => s + "\n",
        Err(e) => {
            let _ = writeln!(err, "blyte: cannot serialize surface file: {e}");
            return 1;
        }
    };
    if let Err(e) = std::fs::write(&surface_file_path, record_json) {
        let _ = writeln!(
            err,
            "blyte: cannot write {}: {e}",
            surface_file_path.display()
        );
        return 1;
    }

    let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
    let _ = writeln!(out, "blyte: surface at {url}");
    let _ = out.flush();
    if !args.no_open {
        open_browser(&url);
    }

    let surface = Arc::new(Surface {
        root,
        repo,
        session,
        session_id,
        started_at,
        days: args.days,
        token,
        requests: Arc::new(RequestsState::new()),
        publisher: Arc::new(RealPublisher),
    });

    let serve_result = crate::http::serve(listener, move |req| match now_duration() {
        Ok(d) => route(&surface, req, d.as_secs()),
        Err(e) => json_error(500, e),
    });

    let _ = std::fs::remove_file(&surface_file_path);

    match serve_result {
        Ok(()) => 0,
        Err(e) => {
            let _ = writeln!(err, "blyte: server error: {e}");
            1
        }
    }
}