Skip to main content

blyte_cli/
serve.rs

1use serde::{Deserialize, Serialize};
2use std::collections::BTreeSet;
3use std::io::{Read, Write};
4use std::net::{SocketAddr, TcpListener, TcpStream};
5use std::path::{Path, PathBuf};
6use std::process::Command;
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::Arc;
9use std::time::{Duration, SystemTime, UNIX_EPOCH};
10
11use crate::cli::SurfaceArgs;
12use crate::http::{Request, Response};
13use crate::queue_actions::{Action, Hold};
14use crate::repl::ReplConfig;
15use crate::requests::{Publisher, RealPublisher, RequestActionError, RequestsState};
16use crate::session::{AgentRunner, AnswerError, ApprovalAnswer, Attachment, Session};
17
18pub const TOKEN_HEADER: &str = "X-Blyte-Token";
19
20const INDEX_HTML: &str = include_str!("../assets/surface/index.html");
21const MAX_WAIT_MS: u64 = 25_000;
22const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
23const TOKEN_BYTES: usize = 32;
24
25static SESSION_COUNTER: AtomicU64 = AtomicU64::new(1);
26
27pub struct Surface {
28    pub root: PathBuf,
29    pub repo: String,
30    pub session: Session,
31    pub session_id: String,
32    pub started_at: u64,
33    pub days: u64,
34    pub token: String,
35    pub requests: Arc<RequestsState>,
36    pub publisher: Arc<dyn Publisher>,
37}
38
39pub fn generate_token() -> Result<String, String> {
40    let mut bytes = [0u8; TOKEN_BYTES];
41    let mut file = std::fs::File::open("/dev/urandom")
42        .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
43    file.read_exact(&mut bytes)
44        .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
45    const HEX: &[u8; 16] = b"0123456789abcdef";
46    let mut out = String::with_capacity(bytes.len() * 2);
47    for byte in bytes {
48        out.push(HEX[(byte >> 4) as usize] as char);
49        out.push(HEX[(byte & 0x0f) as usize] as char);
50    }
51    Ok(out)
52}
53
54pub fn constant_time_eq(provided: &[u8], expected: &[u8]) -> bool {
55    let mut diff = provided.len() ^ expected.len();
56    for (i, &exp) in expected.iter().enumerate() {
57        let prov = provided.get(i).copied().unwrap_or(0);
58        diff |= usize::from(prov ^ exp);
59    }
60    std::hint::black_box(diff) == 0
61}
62
63fn has_valid_token(surface: &Surface, req: &Request) -> bool {
64    if surface.token.is_empty() {
65        return false;
66    }
67    let mut values = req.header_values(TOKEN_HEADER);
68    let Some(provided) = values.next() else {
69        return false;
70    };
71    if values.next().is_some() {
72        return false;
73    }
74    constant_time_eq(provided.as_bytes(), surface.token.as_bytes())
75}
76
77#[derive(Serialize, Deserialize)]
78struct SurfaceFile {
79    pid: u32,
80    port: u16,
81    session_id: String,
82    started_at: u64,
83}
84
85#[derive(Serialize)]
86struct RunWithHold<'a> {
87    #[serde(flatten)]
88    run: &'a crate::replay::Run,
89    hold: Option<Hold>,
90}
91
92#[derive(Serialize)]
93struct LiveRunsResponse<'a> {
94    generated_at: u64,
95    repo: &'a str,
96    running: &'a [crate::live_runs::RunningRun],
97    runs: Vec<RunWithHold<'a>>,
98    skipped: &'a [crate::replay::Skipped],
99}
100
101fn json_error(status: u16, msg: impl Into<String>) -> Response {
102    Response::json(status, &serde_json::json!({ "error": msg.into() }))
103}
104
105fn method_not_allowed(req: &Request) -> Response {
106    json_error(
107        405,
108        format!("method {} not allowed for {}", req.method, req.path),
109    )
110}
111
112fn is_valid_run_id(id: &str) -> bool {
113    !id.is_empty()
114        && id != "."
115        && id != ".."
116        && id
117            .bytes()
118            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
119}
120
121fn parse_json_object(body: &[u8]) -> Result<serde_json::Map<String, serde_json::Value>, Response> {
122    let val: serde_json::Value = serde_json::from_slice(body)
123        .map_err(|e| json_error(400, format!("invalid JSON body: {e}")))?;
124    val.as_object()
125        .cloned()
126        .ok_or_else(|| json_error(400, "request body must be a JSON object"))
127}
128
129fn session_response(surface: &Surface) -> Response {
130    let info = surface.session.info();
131    Response::json(
132        200,
133        &serde_json::json!({
134            "session_id": surface.session_id,
135            "repo": surface.repo,
136            "started_at": surface.started_at,
137            "model": info.model,
138            "effort": info.effort,
139            "effort_supported": info.effort_supported,
140            "busy": info.busy,
141            "queued": info.queued,
142            "last_seq": info.last_seq,
143        }),
144    )
145}
146
147fn handle_events(surface: &Surface, req: &Request) -> Response {
148    let after_raw = match req.query_value("after") {
149        Some(v) => v,
150        None => return json_error(400, "missing required query parameter: after"),
151    };
152    let after = match after_raw.parse::<u64>() {
153        Ok(v) => v,
154        Err(_) => {
155            return json_error(
156                400,
157                format!("query parameter after must be a non-negative integer, got '{after_raw}'"),
158            );
159        }
160    };
161    let wait_ms = match req.query_value("wait_ms") {
162        None => 0,
163        Some(raw) => match raw.parse::<u64>() {
164            Ok(v) if v <= MAX_WAIT_MS => v,
165            Ok(v) => {
166                return json_error(
167                    400,
168                    format!("query parameter wait_ms must be at most {MAX_WAIT_MS}, got {v}"),
169                );
170            }
171            Err(_) => {
172                return json_error(
173                    400,
174                    format!("query parameter wait_ms must be a non-negative integer, got '{raw}'"),
175                );
176            }
177        },
178    };
179    let entries = surface
180        .session
181        .entries_after(after, Duration::from_millis(wait_ms));
182    let last_seq = surface.session.info().last_seq;
183    Response::json(
184        200,
185        &serde_json::json!({
186            "entries": entries,
187            "last_seq": last_seq,
188        }),
189    )
190}
191
192fn handle_post_message(surface: &Surface, req: &Request) -> Response {
193    let obj = match parse_json_object(&req.body) {
194        Ok(o) => o,
195        Err(resp) => return resp,
196    };
197    let text = match obj.get("text") {
198        Some(serde_json::Value::String(s)) => s.clone(),
199        Some(_) => return json_error(400, "field text must be a string"),
200        None => return json_error(400, "missing required field: text"),
201    };
202    let report_ids: Vec<String> = match obj.get("reports") {
203        None | Some(serde_json::Value::Null) => Vec::new(),
204        Some(serde_json::Value::Array(arr)) => {
205            let mut ids = Vec::with_capacity(arr.len());
206            for item in arr {
207                match item.as_str() {
208                    Some(s) => ids.push(s.to_string()),
209                    None => return json_error(400, "field reports must be an array of strings"),
210                }
211            }
212            ids
213        }
214        Some(_) => return json_error(400, "field reports must be an array of strings"),
215    };
216
217    let mut attachments = Vec::with_capacity(report_ids.len());
218    for id in report_ids {
219        let path = surface.root.join(".wt").join(format!("{id}.report.md"));
220        if !is_valid_run_id(&id) {
221            return json_error(
222                400,
223                format!("invalid report run id '{id}' (path: {})", path.display()),
224            );
225        }
226        match std::fs::read_to_string(&path) {
227            Ok(body) => attachments.push(Attachment {
228                run: id,
229                text: body,
230            }),
231            Err(e) => {
232                return json_error(
233                    400,
234                    format!(
235                        "cannot read report for run '{id}' at {}: {e}",
236                        path.display()
237                    ),
238                );
239            }
240        }
241    }
242
243    match surface.session.submit(&text, attachments) {
244        Ok(seq) => Response::json(200, &serde_json::json!({ "seq": seq })),
245        Err(e) => json_error(400, e),
246    }
247}
248
249fn handle_models() -> Response {
250    let discovered = blyte_provider::discover_all_models();
251    let mut models = Vec::new();
252    let mut unavailable = Vec::new();
253    let mut error_parts = Vec::new();
254
255    for (provider, result) in discovered {
256        match result {
257            Ok(list) => {
258                for m in list {
259                    let effort_supported = crate::session::model_supports_effort(&m.id);
260                    models.push(serde_json::json!({
261                        "id": m.id,
262                        "effort_supported": effort_supported,
263                    }));
264                }
265            }
266            Err(e) => {
267                let err_text = e.to_string();
268                error_parts.push(format!("{provider}: {err_text}"));
269                unavailable.push(serde_json::json!({
270                    "provider": provider,
271                    "error": err_text,
272                }));
273            }
274        }
275    }
276
277    if models.is_empty() {
278        let msg = if error_parts.is_empty() {
279            "no models listed by any provider".to_string()
280        } else {
281            format!("no models available: {}", error_parts.join("; "))
282        };
283        return json_error(502, msg);
284    }
285
286    Response::json(
287        200,
288        &serde_json::json!({
289            "models": models,
290            "unavailable": unavailable,
291        }),
292    )
293}
294
295fn handle_post_model(surface: &Surface, req: &Request) -> Response {
296    let obj = match parse_json_object(&req.body) {
297        Ok(o) => o,
298        Err(resp) => return resp,
299    };
300    let model = match obj.get("model") {
301        Some(serde_json::Value::String(s)) => s.clone(),
302        Some(_) => return json_error(400, "field model must be a string"),
303        None => return json_error(400, "missing required field: model"),
304    };
305    if model.trim().is_empty() {
306        return json_error(400, "field model must not be empty");
307    }
308    if let Err(e) = blyte_provider::resolve_provider(Some(&model)) {
309        return json_error(400, e.to_string());
310    }
311    if let Err(e) = surface.session.set_model(&model) {
312        return json_error(400, e);
313    }
314    session_response(surface)
315}
316
317fn handle_post_effort(surface: &Surface, req: &Request) -> Response {
318    let obj = match parse_json_object(&req.body) {
319        Ok(o) => o,
320        Err(resp) => return resp,
321    };
322    let effort = match obj.get("effort") {
323        Some(serde_json::Value::Null) => None,
324        Some(serde_json::Value::String(s)) => Some(s.clone()),
325        Some(_) => return json_error(400, "field effort must be a string or null"),
326        None => return json_error(400, "missing required field: effort"),
327    };
328    if let Err(e) = surface.session.set_effort(effort.as_deref()) {
329        return json_error(400, e);
330    }
331    session_response(surface)
332}
333
334fn handle_post_approval(surface: &Surface, id: &str, req: &Request) -> Response {
335    let obj = match parse_json_object(&req.body) {
336        Ok(o) => o,
337        Err(resp) => return resp,
338    };
339    if obj.len() != 1 {
340        return json_error(400, "request body must contain only field answer");
341    }
342    let answer = match obj.get("answer") {
343        Some(serde_json::Value::String(s)) if s == "yes" => ApprovalAnswer::Yes,
344        Some(serde_json::Value::String(s)) if s == "no" => ApprovalAnswer::No,
345        Some(serde_json::Value::String(other)) => {
346            return json_error(
347                400,
348                format!("field answer must be \"yes\" or \"no\", got '{other}'"),
349            );
350        }
351        Some(_) => return json_error(400, "field answer must be \"yes\" or \"no\""),
352        None => return json_error(400, "missing required field: answer"),
353    };
354    match surface.session.answer_approval(id, answer) {
355        Ok(seq) => Response::json(
356            200,
357            &serde_json::json!({
358                "id": id,
359                "answer": answer.as_str(),
360                "seq": seq,
361            }),
362        ),
363        Err(AnswerError::NotFound) => json_error(404, format!("unknown approval id: {id}")),
364        Err(AnswerError::AlreadyAnswered) => {
365            json_error(409, format!("approval {id} has already been answered"))
366        }
367    }
368}
369
370fn handle_runs(surface: &Surface, now: u64) -> Response {
371    let mut live = match crate::live_runs::collect(&surface.root, now, surface.days) {
372        Ok(l) => l,
373        Err(e) => return json_error(500, e),
374    };
375    let mut any_written = false;
376    for run in &live.runs {
377        if run.checks_recorded {
378            continue;
379        }
380        match crate::queue_actions::ensure_checks(&surface.root, &run.id) {
381            Ok(true) => any_written = true,
382            Ok(false) => {}
383            Err(e) => return json_error(500, e),
384        }
385    }
386    if any_written {
387        live = match crate::live_runs::collect(&surface.root, now, surface.days) {
388            Ok(l) => l,
389            Err(e) => return json_error(500, e),
390        };
391    }
392
393    let mut runs_with_hold = Vec::with_capacity(live.runs.len());
394    for run in &live.runs {
395        let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
396            Ok(h) => h,
397            Err(e) => return json_error(500, e),
398        };
399        runs_with_hold.push(RunWithHold { run, hold });
400    }
401
402    let mut triggered = BTreeSet::new();
403    for run in &live.runs {
404        if run.research {
405            continue;
406        }
407        if let Some(ref req_id) = run.request {
408            if triggered.insert(req_id.clone()) {
409                if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
410                    surface
411                        .session
412                        .record_error(&format!("combine trigger failed for {req_id}: {e}"));
413                }
414            }
415        }
416    }
417
418    let payload = LiveRunsResponse {
419        generated_at: live.generated_at,
420        repo: &live.repo,
421        running: &live.running,
422        runs: runs_with_hold,
423        skipped: &live.skipped,
424    };
425    match serde_json::to_value(&payload) {
426        Ok(val) => Response::json(200, &val),
427        Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
428    }
429}
430
431fn handle_run_diff(surface: &Surface, id: &str) -> Response {
432    if !is_valid_run_id(id) {
433        return json_error(404, format!("unknown run: {id}"));
434    }
435    let wt_dir = surface.root.join(".wt");
436    let wt = wt_dir.join(id);
437    let summary = wt_dir.join(format!("{id}.json"));
438    let report_json = wt_dir.join(format!("{id}.report.json"));
439    let report_md = wt_dir.join(format!("{id}.report.md"));
440    if !wt.exists() && !summary.exists() && !report_json.exists() && !report_md.exists() {
441        return json_error(404, format!("unknown run: {id}"));
442    }
443    match crate::queue_actions::compute_review(&surface.root, id, true) {
444        Ok(data) => {
445            let body = if !data.wt_exists {
446                "(worktree removed)\n".to_string()
447            } else if data.diff_out.is_empty() {
448                String::new()
449            } else {
450                format!("{}\n", data.diff_out)
451            };
452            Response::text(200, &body)
453        }
454        Err(e) => {
455            if !wt.is_dir() || !wt.join(".git").exists() {
456                json_error(404, e)
457            } else {
458                json_error(500, e)
459            }
460        }
461    }
462}
463
464fn parse_action(raw: &str) -> Result<Action, String> {
465    match raw {
466        "accept" => Ok(Action::Accept),
467        "send_back" => Ok(Action::SendBack),
468        "redo" => Ok(Action::Redo),
469        "hold" => Ok(Action::Hold),
470        "mark_read" => Ok(Action::MarkRead),
471        other => Err(format!(
472            "unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
473        )),
474    }
475}
476
477fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
478    let obj = match parse_json_object(&req.body) {
479        Ok(o) => o,
480        Err(resp) => return resp,
481    };
482    let action_str = match obj.get("action") {
483        Some(serde_json::Value::String(s)) => s.clone(),
484        Some(_) => return json_error(400, "field action must be a string"),
485        None => return json_error(400, "missing required field: action"),
486    };
487    let action = match parse_action(&action_str) {
488        Ok(a) => a,
489        Err(e) => return json_error(400, e),
490    };
491    let note = match obj.get("note") {
492        None | Some(serde_json::Value::Null) => None,
493        Some(serde_json::Value::String(s)) => Some(s.clone()),
494        Some(_) => return json_error(400, "field note must be a string or null"),
495    };
496
497    let decision =
498        match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
499            Ok(d) => d,
500            Err(e) => return json_error(400, e),
501        };
502    let seq = match surface.session.record_decision(
503        &decision.run,
504        &action_str,
505        decision.note.as_deref(),
506        decision.orchestrator_message.as_deref(),
507    ) {
508        Ok(s) => s,
509        Err(e) => return json_error(500, e),
510    };
511    if action == Action::Accept {
512        match crate::requests::run_request_id(&surface.root, &decision.run) {
513            Ok(Some(req_id)) => {
514                if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
515                    surface
516                        .session
517                        .record_error(&format!("combine trigger failed for {req_id}: {e}"));
518                }
519            }
520            Ok(None) => {}
521            Err(e) => return json_error(500, e),
522        }
523    }
524    Response::json(
525        200,
526        &serde_json::json!({
527            "decision": {
528                "run": decision.run,
529                "action": action_str,
530                "note": decision.note,
531                "orchestrator_message": decision.orchestrator_message,
532            },
533            "seq": seq,
534        }),
535    )
536}
537
538fn handle_map(surface: &Surface) -> Response {
539    match crate::map::build(&surface.root, &surface.repo) {
540        Ok(data) => match serde_json::to_value(&data) {
541            Ok(val) => Response::json(200, &val),
542            Err(e) => json_error(500, format!("failed to serialize map: {e}")),
543        },
544        Err(e) => json_error(422, e),
545    }
546}
547
548fn handle_requests(surface: &Surface) -> Response {
549    match crate::requests::list_requests(surface) {
550        Ok(list) => match serde_json::to_value(&list) {
551            Ok(val) => Response::json(200, &val),
552            Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
553        },
554        Err(e) => json_error(500, e),
555    }
556}
557
558fn request_action_error_response(err: RequestActionError) -> Response {
559    match err {
560        RequestActionError::BadRequest(msg) => json_error(400, msg),
561        RequestActionError::Conflict(msg) => json_error(409, msg),
562        RequestActionError::Internal(msg) => json_error(500, msg),
563    }
564}
565
566fn handle_request_push(surface: &Surface, id: &str) -> Response {
567    match crate::requests::push_request(surface, id) {
568        Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
569        Err(err) => request_action_error_response(err),
570    }
571}
572
573fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
574    if let Err(e) = crate::dispatch::validate_request_id(id) {
575        return json_error(400, e);
576    }
577    let obj = match parse_json_object(&req.body) {
578        Ok(o) => o,
579        Err(resp) => return resp,
580    };
581    let title = match obj.get("title") {
582        Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
583        Some(serde_json::Value::String(_)) => {
584            return json_error(400, "field title must not be empty");
585        }
586        Some(_) => return json_error(400, "field title must be a string"),
587        None => return json_error(400, "missing required field: title"),
588    };
589    let body = match obj.get("body") {
590        None | Some(serde_json::Value::Null) => String::new(),
591        Some(serde_json::Value::String(s)) => s.clone(),
592        Some(_) => return json_error(400, "field body must be a string"),
593    };
594    match crate::requests::open_request_pull_request(surface, id, &title, &body) {
595        Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
596        Err(err) => request_action_error_response(err),
597    }
598}
599
600pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
601    if req.method == "POST" && !has_valid_token(surface, req) {
602        return json_error(
603            403,
604            "missing or invalid surface token; open the page from the URL blyte printed",
605        );
606    }
607
608    if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
609        if req.method != "GET" {
610            return method_not_allowed(req);
611        }
612        return Response {
613            status,
614            content_type,
615            body,
616        };
617    }
618
619    match req.path.as_str() {
620        "/" | "/index.html" => {
621            if req.method != "GET" {
622                return method_not_allowed(req);
623            }
624            Response::html(INDEX_HTML.as_bytes().to_vec())
625        }
626        "/api/session" => {
627            if req.method != "GET" {
628                return method_not_allowed(req);
629            }
630            session_response(surface)
631        }
632        "/api/session/events" => {
633            if req.method != "GET" {
634                return method_not_allowed(req);
635            }
636            handle_events(surface, req)
637        }
638        "/api/session/messages" => {
639            if req.method != "POST" {
640                return method_not_allowed(req);
641            }
642            handle_post_message(surface, req)
643        }
644        "/api/models" => {
645            if req.method != "GET" {
646                return method_not_allowed(req);
647            }
648            handle_models()
649        }
650        "/api/session/model" => {
651            if req.method != "POST" {
652                return method_not_allowed(req);
653            }
654            handle_post_model(surface, req)
655        }
656        "/api/session/effort" => {
657            if req.method != "POST" {
658                return method_not_allowed(req);
659            }
660            handle_post_effort(surface, req)
661        }
662        "/api/runs" => {
663            if req.method != "GET" {
664                return method_not_allowed(req);
665            }
666            handle_runs(surface, now)
667        }
668        "/api/requests" => {
669            if req.method != "GET" {
670                return method_not_allowed(req);
671            }
672            handle_requests(surface)
673        }
674        "/api/map" => {
675            if req.method != "GET" {
676                return method_not_allowed(req);
677            }
678            handle_map(surface)
679        }
680        path => {
681            if let Some(id) = path.strip_prefix("/api/session/approvals/") {
682                if !id.is_empty() && !id.contains('/') {
683                    if req.method != "POST" {
684                        return method_not_allowed(req);
685                    }
686                    return handle_post_approval(surface, id, req);
687                }
688            }
689            if let Some(rest) = path.strip_prefix("/api/runs/") {
690                if let Some(id) = rest.strip_suffix("/diff") {
691                    if !id.is_empty() && !id.contains('/') {
692                        if req.method != "GET" {
693                            return method_not_allowed(req);
694                        }
695                        return handle_run_diff(surface, id);
696                    }
697                }
698                if let Some(id) = rest.strip_suffix("/decision") {
699                    if !id.is_empty() && !id.contains('/') {
700                        if req.method != "POST" {
701                            return method_not_allowed(req);
702                        }
703                        return handle_run_decision(surface, id, req, now);
704                    }
705                }
706            }
707            if let Some(rest) = path.strip_prefix("/api/requests/") {
708                if let Some(id) = rest.strip_suffix("/push") {
709                    if req.method != "POST" {
710                        return method_not_allowed(req);
711                    }
712                    return handle_request_push(surface, id);
713                }
714                if let Some(id) = rest.strip_suffix("/pull-request") {
715                    if req.method != "POST" {
716                        return method_not_allowed(req);
717                    }
718                    return handle_request_pull_request(surface, id, req);
719                }
720            }
721            json_error(404, format!("not found: {}", req.path))
722        }
723    }
724}
725
726fn find_git_toplevel(dir: &Path) -> Result<PathBuf, String> {
727    let out = Command::new("git")
728        .args(["rev-parse", "--show-toplevel"])
729        .current_dir(dir)
730        .output()
731        .map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
732    if !out.status.success() {
733        return Err(format!("not inside a git repository ({})", dir.display()));
734    }
735    let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
736    if path_str.is_empty() {
737        return Err(format!("not inside a git repository ({})", dir.display()));
738    }
739    Ok(PathBuf::from(path_str))
740}
741
742fn repo_name_for(root: &Path) -> Result<String, String> {
743    root.file_name()
744        .and_then(|s| s.to_str())
745        .filter(|s| !s.is_empty())
746        .map(String::from)
747        .ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
748}
749
750fn now_duration() -> Result<Duration, String> {
751    SystemTime::now()
752        .duration_since(UNIX_EPOCH)
753        .map_err(|e| format!("system clock is before Unix epoch: {e}"))
754}
755
756fn new_session_id(nanos: u128) -> String {
757    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
758    format!("surface-{}-{nanos}-{seq}", std::process::id())
759}
760
761fn probe_existing_surface(port: u16, expected_session_id: &str) -> bool {
762    let addr = SocketAddr::from(([127, 0, 0, 1], port));
763    let mut stream = match TcpStream::connect_timeout(&addr, PROBE_TIMEOUT) {
764        Ok(s) => s,
765        Err(_) => return false,
766    };
767    let _ = stream.set_read_timeout(Some(PROBE_TIMEOUT));
768    let _ = stream.set_write_timeout(Some(PROBE_TIMEOUT));
769    let req =
770        format!("GET /api/session HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
771    if stream.write_all(req.as_bytes()).is_err() {
772        return false;
773    }
774    let mut raw = Vec::new();
775    if stream.read_to_end(&mut raw).is_err() {
776        return false;
777    }
778    let text = match std::str::from_utf8(&raw) {
779        Ok(s) => s,
780        Err(_) => return false,
781    };
782    let (head, body) = match text.split_once("\r\n\r\n") {
783        Some(parts) => parts,
784        None => return false,
785    };
786    let status_line = head.lines().next().unwrap_or("");
787    if !(status_line.starts_with("HTTP/1.1 200") || status_line.starts_with("HTTP/1.0 200")) {
788        return false;
789    }
790    let val: serde_json::Value = match serde_json::from_str(body) {
791        Ok(v) => v,
792        Err(_) => return false,
793    };
794    val.get("session_id").and_then(|v| v.as_str()) == Some(expected_session_id)
795}
796
797fn open_browser(url: &str) {
798    #[cfg(target_os = "macos")]
799    let cmd = "open";
800    #[cfg(not(target_os = "macos"))]
801    let cmd = "xdg-open";
802    if let Err(e) = Command::new(cmd).arg(url).spawn() {
803        eprintln!("blyte: could not open a browser with {cmd}: {e}; open {url} yourself");
804    }
805}
806
807fn resolve_initial_model(config: &ReplConfig) -> String {
808    if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
809        return m.to_string();
810    }
811    if let Ok(m) = std::env::var("BLYTE_MODEL") {
812        if !m.trim().is_empty() {
813            return m;
814        }
815    }
816    if let Ok(p) = blyte_provider::resolve_provider(None) {
817        return p.model_id();
818    }
819    "gemini-3.8-flash-high".to_string()
820}
821
822pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
823    run_with_io(args, config, &mut std::io::stdout(), &mut std::io::stderr())
824}
825
826pub fn run_with_io(
827    args: &SurfaceArgs,
828    mut config: ReplConfig,
829    out: &mut dyn Write,
830    err: &mut dyn Write,
831) -> i32 {
832    let root = match find_git_toplevel(&config.repo_root) {
833        Ok(r) => r,
834        Err(e) => {
835            let _ = writeln!(err, "blyte: {e}");
836            return 1;
837        }
838    };
839    let repo = match repo_name_for(&root) {
840        Ok(r) => r,
841        Err(e) => {
842            let _ = writeln!(err, "blyte: {e}");
843            return 1;
844        }
845    };
846
847    let wt_dir = root.join(".wt");
848    let surface_file_path = wt_dir.join("surface.json");
849    match std::fs::read_to_string(&surface_file_path) {
850        Ok(raw) => match serde_json::from_str::<SurfaceFile>(&raw) {
851            Ok(existing) => {
852                if probe_existing_surface(existing.port, &existing.session_id) {
853                    let url = format!("http://127.0.0.1:{}/", existing.port);
854                    let _ = writeln!(out, "blyte: surface already running at {url}");
855                    let _ = out.flush();
856                    if !args.no_open {
857                        open_browser(&url);
858                    }
859                    return 0;
860                }
861                let _ = writeln!(
862                    err,
863                    "blyte: stale surface file {} (port {}, session {}); replacing it",
864                    surface_file_path.display(),
865                    existing.port,
866                    existing.session_id
867                );
868                let _ = err.flush();
869            }
870            Err(e) => {
871                let _ = writeln!(
872                    err,
873                    "blyte: cannot parse {}: {e}",
874                    surface_file_path.display()
875                );
876                return 1;
877            }
878        },
879        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
880        Err(e) => {
881            let _ = writeln!(
882                err,
883                "blyte: cannot read {}: {e}",
884                surface_file_path.display()
885            );
886            return 1;
887        }
888    }
889
890    if !config.orchestrate {
891        config.orchestrate = true;
892        if config.max_turns == 25 || config.max_turns == 60 {
893            config.max_turns = 1000;
894        }
895        if config.fold_budget.is_none() {
896            config.fold_budget = Some(100_000);
897        }
898    }
899    config.repo_root = root.clone();
900
901    let model = resolve_initial_model(&config);
902    let session = Session::start_with(model, |approver| {
903        Box::new(AgentRunner::new(&config, approver))
904    });
905    let started_dur = match now_duration() {
906        Ok(d) => d,
907        Err(e) => {
908            let _ = writeln!(err, "blyte: {e}");
909            return 1;
910        }
911    };
912    let started_at = started_dur.as_secs();
913    let session_id = new_session_id(started_dur.as_nanos());
914    let token = match generate_token() {
915        Ok(t) => t,
916        Err(e) => {
917            let _ = writeln!(err, "blyte: {e}");
918            return 1;
919        }
920    };
921
922    let bind_addr = format!("127.0.0.1:{}", args.port);
923    let listener = match TcpListener::bind(&bind_addr) {
924        Ok(l) => l,
925        Err(e) => {
926            let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
927            return 1;
928        }
929    };
930    let actual_port = match listener.local_addr() {
931        Ok(a) => a.port(),
932        Err(e) => {
933            let _ = writeln!(err, "blyte: failed to read listener address: {e}");
934            return 1;
935        }
936    };
937
938    if let Err(e) = std::fs::create_dir_all(&wt_dir) {
939        let _ = writeln!(err, "blyte: cannot create {}: {e}", wt_dir.display());
940        return 1;
941    }
942    let record = SurfaceFile {
943        pid: std::process::id(),
944        port: actual_port,
945        session_id: session_id.clone(),
946        started_at,
947    };
948    let record_json = match serde_json::to_string_pretty(&record) {
949        Ok(s) => s + "\n",
950        Err(e) => {
951            let _ = writeln!(err, "blyte: cannot serialize surface file: {e}");
952            return 1;
953        }
954    };
955    if let Err(e) = std::fs::write(&surface_file_path, record_json) {
956        let _ = writeln!(
957            err,
958            "blyte: cannot write {}: {e}",
959            surface_file_path.display()
960        );
961        return 1;
962    }
963
964    let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
965    let _ = writeln!(out, "blyte: surface at {url}");
966    let _ = out.flush();
967    if !args.no_open {
968        open_browser(&url);
969    }
970
971    let surface = Arc::new(Surface {
972        root,
973        repo,
974        session,
975        session_id,
976        started_at,
977        days: args.days,
978        token,
979        requests: Arc::new(RequestsState::new()),
980        publisher: Arc::new(RealPublisher),
981    });
982
983    let serve_result = crate::http::serve(listener, move |req| match now_duration() {
984        Ok(d) => route(&surface, req, d.as_secs()),
985        Err(e) => json_error(500, e),
986    });
987
988    let _ = std::fs::remove_file(&surface_file_path);
989
990    match serve_result {
991        Ok(()) => 0,
992        Err(e) => {
993            let _ = writeln!(err, "blyte: server error: {e}");
994            1
995        }
996    }
997}