Skip to main content

blyte_cli/
serve.rs

1use serde::Serialize;
2use std::collections::{BTreeSet, HashSet};
3use std::io::{Read, Write};
4use std::net::TcpListener;
5#[cfg(unix)]
6use std::os::unix::fs::OpenOptionsExt;
7use std::path::{Path, PathBuf};
8use std::process::Command;
9use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
10use std::sync::{Arc, Mutex};
11use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
12
13use crate::cli::SurfaceArgs;
14use crate::http::{Request, Response};
15use crate::queue_actions::{Action, Hold};
16use crate::repl::ReplConfig;
17use crate::requests::{Publisher, RealPublisher, RequestActionError, RequestsState};
18use crate::session::{
19    AgentRunner, AnswerError, ApprovalAnswer, Attachment, EntryBody, PromptRunner, Session,
20};
21use crate::surface_dir::SurfaceRecord;
22
23pub const TOKEN_HEADER: &str = "X-Blyte-Token";
24pub const RECONCILE_SAFETY_NET_INTERVAL: Duration = Duration::from_secs(30);
25
26const INDEX_HTML: &str = include_str!("../assets/surface/index.html");
27const MAX_WAIT_MS: u64 = 25_000;
28const RECONCILE_POLL_WAIT: Duration = Duration::from_millis(50);
29const TOKEN_BYTES: usize = 32;
30
31static SESSION_COUNTER: AtomicU64 = AtomicU64::new(1);
32
33pub struct Surface {
34    pub surface_id: String,
35    pub surface_name: String,
36    pub root: PathBuf,
37    pub repo: String,
38    pub session: Session,
39    pub session_id: String,
40    pub started_at: u64,
41    pub days: u64,
42    pub token: String,
43    pub requests: Arc<RequestsState>,
44    pub publisher: Arc<dyn Publisher>,
45    pub reconcile_lock: Mutex<()>,
46    pub reconcile_requested: AtomicBool,
47}
48
49pub fn generate_token() -> Result<String, String> {
50    let mut bytes = [0u8; TOKEN_BYTES];
51    let mut file = std::fs::File::open("/dev/urandom")
52        .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
53    file.read_exact(&mut bytes)
54        .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
55    const HEX: &[u8; 16] = b"0123456789abcdef";
56    let mut out = String::with_capacity(bytes.len() * 2);
57    for byte in bytes {
58        out.push(HEX[(byte >> 4) as usize] as char);
59        out.push(HEX[(byte & 0x0f) as usize] as char);
60    }
61    Ok(out)
62}
63
64pub fn constant_time_eq(provided: &[u8], expected: &[u8]) -> bool {
65    let mut diff = provided.len() ^ expected.len();
66    for (i, &exp) in expected.iter().enumerate() {
67        let prov = provided.get(i).copied().unwrap_or(0);
68        diff |= usize::from(prov ^ exp);
69    }
70    std::hint::black_box(diff) == 0
71}
72
73fn has_valid_token(surface: &Surface, req: &Request) -> bool {
74    if surface.token.is_empty() {
75        return false;
76    }
77    let mut values = req.header_values(TOKEN_HEADER);
78    let Some(provided) = values.next() else {
79        return false;
80    };
81    if values.next().is_some() {
82        return false;
83    }
84    constant_time_eq(provided.as_bytes(), surface.token.as_bytes())
85}
86
87#[derive(Serialize)]
88struct RunWithHold<'a> {
89    #[serde(flatten)]
90    run: &'a crate::replay::Run,
91    hold: Option<Hold>,
92    combined: bool,
93}
94
95#[derive(Serialize)]
96struct LiveRunsResponse<'a> {
97    generated_at: u64,
98    repo: &'a str,
99    running: &'a [crate::live_runs::RunningRun],
100    runs: Vec<RunWithHold<'a>>,
101    skipped: &'a [crate::replay::Skipped],
102}
103
104fn json_error(status: u16, msg: impl Into<String>) -> Response {
105    Response::json(status, &serde_json::json!({ "error": msg.into() }))
106}
107
108fn method_not_allowed(req: &Request) -> Response {
109    json_error(
110        405,
111        format!("method {} not allowed for {}", req.method, req.path),
112    )
113}
114
115fn is_valid_run_id(id: &str) -> bool {
116    !id.is_empty()
117        && id != "."
118        && id != ".."
119        && id
120            .bytes()
121            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
122}
123
124fn parse_json_object(body: &[u8]) -> Result<serde_json::Map<String, serde_json::Value>, Response> {
125    let val: serde_json::Value = serde_json::from_slice(body)
126        .map_err(|e| json_error(400, format!("invalid JSON body: {e}")))?;
127    val.as_object()
128        .cloned()
129        .ok_or_else(|| json_error(400, "request body must be a JSON object"))
130}
131
132fn health_response(surface: &Surface) -> Response {
133    Response::json(
134        200,
135        &serde_json::json!({
136            "surface_id": surface.surface_id,
137            "surface_name": surface.surface_name,
138            "session_id": surface.session_id,
139        }),
140    )
141}
142
143fn session_response(surface: &Surface) -> Response {
144    let info = surface.session.info();
145    Response::json(
146        200,
147        &serde_json::json!({
148            "session_id": surface.session_id,
149            "surface_name": surface.surface_name,
150            "repo": surface.repo,
151            "started_at": surface.started_at,
152            "model": info.model,
153            "effort": info.effort,
154            "effort_supported": info.effort_supported,
155            "busy": info.busy,
156            "queued": info.queued,
157            "last_seq": info.last_seq,
158        }),
159    )
160}
161
162fn handle_events(surface: &Surface, req: &Request) -> Response {
163    let after_raw = match req.query_value("after") {
164        Some(v) => v,
165        None => return json_error(400, "missing required query parameter: after"),
166    };
167    let after = match after_raw.parse::<u64>() {
168        Ok(v) => v,
169        Err(_) => {
170            return json_error(
171                400,
172                format!("query parameter after must be a non-negative integer, got '{after_raw}'"),
173            );
174        }
175    };
176    let wait_ms = match req.query_value("wait_ms") {
177        None => 0,
178        Some(raw) => match raw.parse::<u64>() {
179            Ok(v) if v <= MAX_WAIT_MS => v,
180            Ok(v) => {
181                return json_error(
182                    400,
183                    format!("query parameter wait_ms must be at most {MAX_WAIT_MS}, got {v}"),
184                );
185            }
186            Err(_) => {
187                return json_error(
188                    400,
189                    format!("query parameter wait_ms must be a non-negative integer, got '{raw}'"),
190                );
191            }
192        },
193    };
194    let entries = surface
195        .session
196        .entries_after(after, Duration::from_millis(wait_ms));
197    let last_seq = surface.session.info().last_seq;
198    Response::json(
199        200,
200        &serde_json::json!({
201            "entries": entries,
202            "last_seq": last_seq,
203        }),
204    )
205}
206
207fn handle_post_message(surface: &Surface, req: &Request) -> Response {
208    let obj = match parse_json_object(&req.body) {
209        Ok(o) => o,
210        Err(resp) => return resp,
211    };
212    let text = match obj.get("text") {
213        Some(serde_json::Value::String(s)) => s.clone(),
214        Some(_) => return json_error(400, "field text must be a string"),
215        None => return json_error(400, "missing required field: text"),
216    };
217    let report_ids: Vec<String> = match obj.get("reports") {
218        None | Some(serde_json::Value::Null) => Vec::new(),
219        Some(serde_json::Value::Array(arr)) => {
220            let mut ids = Vec::with_capacity(arr.len());
221            for item in arr {
222                match item.as_str() {
223                    Some(s) => ids.push(s.to_string()),
224                    None => return json_error(400, "field reports must be an array of strings"),
225                }
226            }
227            ids
228        }
229        Some(_) => return json_error(400, "field reports must be an array of strings"),
230    };
231
232    let mut attachments = Vec::with_capacity(report_ids.len());
233    for id in report_ids {
234        let path = surface.root.join(".wt").join(format!("{id}.report.md"));
235        if !is_valid_run_id(&id) {
236            return json_error(
237                400,
238                format!("invalid report run id '{id}' (path: {})", path.display()),
239            );
240        }
241        match std::fs::read_to_string(&path) {
242            Ok(body) => attachments.push(Attachment {
243                run: id,
244                text: body,
245            }),
246            Err(e) => {
247                return json_error(
248                    400,
249                    format!(
250                        "cannot read report for run '{id}' at {}: {e}",
251                        path.display()
252                    ),
253                );
254            }
255        }
256    }
257
258    match surface.session.submit(&text, attachments) {
259        Ok(seq) => Response::json(200, &serde_json::json!({ "seq": seq })),
260        Err(e) => json_error(400, e),
261    }
262}
263
264fn handle_models() -> Response {
265    let discovered = blyte_provider::discover_all_models();
266    let mut models = Vec::new();
267    let mut unavailable = Vec::new();
268    let mut error_parts = Vec::new();
269
270    for (provider, result) in discovered {
271        match result {
272            Ok(list) => {
273                for m in list {
274                    let effort_supported = crate::session::model_supports_effort(&m.id);
275                    models.push(serde_json::json!({
276                        "id": m.id,
277                        "effort_supported": effort_supported,
278                    }));
279                }
280            }
281            Err(e) => {
282                let err_text = e.to_string();
283                error_parts.push(format!("{provider}: {err_text}"));
284                unavailable.push(serde_json::json!({
285                    "provider": provider,
286                    "error": err_text,
287                }));
288            }
289        }
290    }
291
292    if models.is_empty() {
293        let msg = if error_parts.is_empty() {
294            "no models listed by any provider".to_string()
295        } else {
296            format!("no models available: {}", error_parts.join("; "))
297        };
298        return json_error(502, msg);
299    }
300
301    Response::json(
302        200,
303        &serde_json::json!({
304            "models": models,
305            "unavailable": unavailable,
306        }),
307    )
308}
309
310fn handle_post_model(surface: &Surface, req: &Request) -> Response {
311    let obj = match parse_json_object(&req.body) {
312        Ok(o) => o,
313        Err(resp) => return resp,
314    };
315    let model = match obj.get("model") {
316        Some(serde_json::Value::String(s)) => s.clone(),
317        Some(_) => return json_error(400, "field model must be a string"),
318        None => return json_error(400, "missing required field: model"),
319    };
320    if model.trim().is_empty() {
321        return json_error(400, "field model must not be empty");
322    }
323    if let Err(e) = blyte_provider::resolve_provider(Some(&model)) {
324        return json_error(400, e.to_string());
325    }
326    if let Err(e) = surface.session.set_model(&model) {
327        return json_error(400, e);
328    }
329    session_response(surface)
330}
331
332fn handle_post_effort(surface: &Surface, req: &Request) -> Response {
333    let obj = match parse_json_object(&req.body) {
334        Ok(o) => o,
335        Err(resp) => return resp,
336    };
337    let effort = match obj.get("effort") {
338        Some(serde_json::Value::Null) => None,
339        Some(serde_json::Value::String(s)) => Some(s.clone()),
340        Some(_) => return json_error(400, "field effort must be a string or null"),
341        None => return json_error(400, "missing required field: effort"),
342    };
343    if let Err(e) = surface.session.set_effort(effort.as_deref()) {
344        return json_error(400, e);
345    }
346    session_response(surface)
347}
348
349fn handle_post_approval(surface: &Surface, id: &str, req: &Request) -> Response {
350    let obj = match parse_json_object(&req.body) {
351        Ok(o) => o,
352        Err(resp) => return resp,
353    };
354    if obj.len() != 1 {
355        return json_error(400, "request body must contain only field answer");
356    }
357    let answer = match obj.get("answer") {
358        Some(serde_json::Value::String(s)) if s == "yes" => ApprovalAnswer::Yes,
359        Some(serde_json::Value::String(s)) if s == "no" => ApprovalAnswer::No,
360        Some(serde_json::Value::String(other)) => {
361            return json_error(
362                400,
363                format!("field answer must be \"yes\" or \"no\", got '{other}'"),
364            );
365        }
366        Some(_) => return json_error(400, "field answer must be \"yes\" or \"no\""),
367        None => return json_error(400, "missing required field: answer"),
368    };
369    match surface.session.answer_approval(id, answer) {
370        Ok(seq) => Response::json(
371            200,
372            &serde_json::json!({
373                "id": id,
374                "answer": answer.as_str(),
375                "seq": seq,
376            }),
377        ),
378        Err(AnswerError::NotFound) => json_error(404, format!("unknown approval id: {id}")),
379        Err(AnswerError::AlreadyAnswered) => {
380            json_error(409, format!("approval {id} has already been answered"))
381        }
382    }
383}
384
385pub fn reconcile_runs(
386    surface: &Surface,
387    now: u64,
388) -> Result<(crate::live_runs::LiveRuns, Vec<String>), String> {
389    let _guard = surface
390        .reconcile_lock
391        .lock()
392        .unwrap_or_else(|e| e.into_inner());
393    let owned = crate::requests::owned_run_ids(surface)?;
394    let mut live = crate::live_runs::collect(&surface.root, now, surface.days)?;
395    let mut any_written = false;
396    for run in &live.runs {
397        if !owned.contains(&run.id) || run.checks_recorded {
398            continue;
399        }
400        if crate::queue_actions::ensure_checks(&surface.root, &run.id)? {
401            any_written = true;
402        }
403    }
404    if any_written {
405        live = crate::live_runs::collect(&surface.root, now, surface.days)?;
406    }
407    live.running.retain(|run| owned.contains(&run.id));
408    live.runs.retain(|run| owned.contains(&run.id));
409
410    let mut errors = Vec::new();
411    if let Err(e) = crate::run_results::report_finished_runs(surface) {
412        errors.push(format!("run report failed: {e}"));
413    }
414
415    let mut triggered = BTreeSet::new();
416    for run in &live.runs {
417        if run.research {
418            continue;
419        }
420        if let Some(ref req_id) = run.request {
421            if triggered.insert(req_id.clone()) {
422                if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
423                    errors.push(format!("combine trigger failed for {req_id}: {e}"));
424                }
425            }
426        }
427    }
428
429    Ok((live, errors))
430}
431
432fn handle_runs(surface: &Surface, now: u64) -> Response {
433    let (live, errors) = match reconcile_runs(surface, now) {
434        Ok(res) => res,
435        Err(e) => return json_error(500, e),
436    };
437    for msg in errors {
438        surface.session.record_error(&msg);
439    }
440
441    let run_refs: Vec<(&str, Option<&str>)> = live
442        .runs
443        .iter()
444        .map(|run| (run.id.as_str(), run.request.as_deref()))
445        .collect();
446    let combined_ids = match crate::requests::combined_run_ids(&surface.root, &run_refs) {
447        Ok(ids) => ids,
448        Err(e) => return json_error(500, e),
449    };
450
451    let mut runs_with_hold = Vec::with_capacity(live.runs.len());
452    for run in &live.runs {
453        let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
454            Ok(h) => h,
455            Err(e) => return json_error(500, e),
456        };
457        let combined = combined_ids.contains(&run.id);
458        runs_with_hold.push(RunWithHold {
459            run,
460            hold,
461            combined,
462        });
463    }
464
465    let payload = LiveRunsResponse {
466        generated_at: live.generated_at,
467        repo: &live.repo,
468        running: &live.running,
469        runs: runs_with_hold,
470        skipped: &live.skipped,
471    };
472    match serde_json::to_value(&payload) {
473        Ok(val) => Response::json(200, &val),
474        Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
475    }
476}
477
478fn handle_runs_changed(surface: &Surface) -> Response {
479    surface.reconcile_requested.store(true, Ordering::Release);
480    Response::json(202, &serde_json::json!({}))
481}
482
483fn handle_run_diff(surface: &Surface, id: &str) -> Response {
484    if !is_valid_run_id(id) {
485        return json_error(404, format!("unknown run: {id}"));
486    }
487    let wt_dir = surface.root.join(".wt");
488    let wt = wt_dir.join(id);
489    let start = wt_dir.join(format!("{id}.start.json"));
490    let summary = wt_dir.join(format!("{id}.json"));
491    let report_json = wt_dir.join(format!("{id}.report.json"));
492    let report_md = wt_dir.join(format!("{id}.report.md"));
493    if !wt.exists()
494        && !start.exists()
495        && !summary.exists()
496        && !report_json.exists()
497        && !report_md.exists()
498    {
499        return json_error(404, format!("unknown run: {id}"));
500    }
501    if let Err(err) = crate::requests::run_owner_check(surface, id) {
502        return request_action_error_response(err);
503    }
504    match crate::queue_actions::compute_review(&surface.root, id, true) {
505        Ok(data) => {
506            let body = if !data.wt_exists {
507                "(worktree removed)\n".to_string()
508            } else if data.diff_out.is_empty() {
509                String::new()
510            } else {
511                format!("{}\n", data.diff_out)
512            };
513            Response::text(200, &body)
514        }
515        Err(e) => {
516            if !wt.is_dir() || !wt.join(".git").exists() {
517                json_error(404, e)
518            } else {
519                json_error(500, e)
520            }
521        }
522    }
523}
524
525fn parse_action(raw: &str) -> Result<Action, String> {
526    match raw {
527        "accept" => Ok(Action::Accept),
528        "send_back" => Ok(Action::SendBack),
529        "redo" => Ok(Action::Redo),
530        "hold" => Ok(Action::Hold),
531        "mark_read" => Ok(Action::MarkRead),
532        other => Err(format!(
533            "unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
534        )),
535    }
536}
537
538fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
539    let obj = match parse_json_object(&req.body) {
540        Ok(o) => o,
541        Err(resp) => return resp,
542    };
543    let action_str = match obj.get("action") {
544        Some(serde_json::Value::String(s)) => s.clone(),
545        Some(_) => return json_error(400, "field action must be a string"),
546        None => return json_error(400, "missing required field: action"),
547    };
548    let action = match parse_action(&action_str) {
549        Ok(a) => a,
550        Err(e) => return json_error(400, e),
551    };
552    let note = match obj.get("note") {
553        None | Some(serde_json::Value::Null) => None,
554        Some(serde_json::Value::String(s)) => Some(s.clone()),
555        Some(_) => return json_error(400, "field note must be a string or null"),
556    };
557
558    let wt_dir = surface.root.join(".wt");
559    let run_exists = is_valid_run_id(id)
560        && (wt_dir.join(id).exists()
561            || wt_dir.join(format!("{id}.start.json")).exists()
562            || wt_dir.join(format!("{id}.json")).exists()
563            || wt_dir.join(format!("{id}.report.json")).exists()
564            || wt_dir.join(format!("{id}.report.md")).exists());
565    if run_exists {
566        if let Err(err) = crate::requests::run_owner_check(surface, id) {
567            return request_action_error_response(err);
568        }
569    }
570
571    let decision =
572        match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
573            Ok(d) => d,
574            Err(e) => return json_error(400, e),
575        };
576    let seq = match surface.session.record_decision(
577        &decision.run,
578        &action_str,
579        decision.note.as_deref(),
580        decision.conversation_message.as_deref(),
581    ) {
582        Ok(s) => s,
583        Err(e) => return json_error(500, e),
584    };
585    if action == Action::Accept {
586        match crate::requests::run_request_id(&surface.root, &decision.run) {
587            Ok(Some(req_id)) => {
588                if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
589                    surface
590                        .session
591                        .record_error(&format!("combine trigger failed for {req_id}: {e}"));
592                }
593            }
594            Ok(None) => {}
595            Err(e) => return json_error(500, e),
596        }
597    }
598    Response::json(
599        200,
600        &serde_json::json!({
601            "decision": {
602                "run": decision.run,
603                "action": action_str,
604                "note": decision.note,
605                "conversation_message": decision.conversation_message,
606            },
607            "seq": seq,
608        }),
609    )
610}
611
612fn handle_map(surface: &Surface) -> Response {
613    match crate::map::build(&surface.root, &surface.repo) {
614        Ok(data) => match serde_json::to_value(&data) {
615            Ok(val) => Response::json(200, &val),
616            Err(e) => json_error(500, format!("failed to serialize map: {e}")),
617        },
618        Err(e) => json_error(422, e),
619    }
620}
621
622fn handle_requests(surface: &Surface) -> Response {
623    match crate::requests::list_requests(surface) {
624        Ok(list) => match serde_json::to_value(&list) {
625            Ok(val) => Response::json(200, &val),
626            Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
627        },
628        Err(e) => json_error(500, e),
629    }
630}
631
632fn request_action_error_response(err: RequestActionError) -> Response {
633    match err {
634        RequestActionError::BadRequest(msg) => json_error(400, msg),
635        RequestActionError::NotOwned(msg) => json_error(403, msg),
636        RequestActionError::Conflict(msg) => json_error(409, msg),
637        RequestActionError::Internal(msg) => json_error(500, msg),
638    }
639}
640
641fn handle_request_push(surface: &Surface, id: &str) -> Response {
642    match crate::requests::push_request(surface, id) {
643        Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
644        Err(err) => request_action_error_response(err),
645    }
646}
647
648fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
649    if let Err(e) = crate::dispatch::validate_request_id(id) {
650        return json_error(400, e);
651    }
652    let obj = match parse_json_object(&req.body) {
653        Ok(o) => o,
654        Err(resp) => return resp,
655    };
656    let title = match obj.get("title") {
657        Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
658        Some(serde_json::Value::String(_)) => {
659            return json_error(400, "field title must not be empty");
660        }
661        Some(_) => return json_error(400, "field title must be a string"),
662        None => return json_error(400, "missing required field: title"),
663    };
664    let body = match obj.get("body") {
665        None | Some(serde_json::Value::Null) => String::new(),
666        Some(serde_json::Value::String(s)) => s.clone(),
667        Some(_) => return json_error(400, "field body must be a string"),
668    };
669    match crate::requests::open_request_pull_request(surface, id, &title, &body) {
670        Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
671        Err(err) => request_action_error_response(err),
672    }
673}
674
675#[derive(Clone, Copy)]
676enum ApiGetHandler {
677    Session,
678    Events,
679    Models,
680    Runs,
681    Requests,
682    Map,
683    RunDiff,
684}
685
686const API_GET_ROUTES: &[(&str, ApiGetHandler)] = &[
687    ("/api/session", ApiGetHandler::Session),
688    ("/api/session/events", ApiGetHandler::Events),
689    ("/api/models", ApiGetHandler::Models),
690    ("/api/runs", ApiGetHandler::Runs),
691    ("/api/requests", ApiGetHandler::Requests),
692    ("/api/map", ApiGetHandler::Map),
693    ("/api/runs/{id}/diff", ApiGetHandler::RunDiff),
694];
695
696pub fn authenticated_api_get_routes() -> Vec<&'static str> {
697    API_GET_ROUTES.iter().map(|(pattern, _)| *pattern).collect()
698}
699
700fn match_api_get_route<'a>(pattern: &str, path: &'a str) -> Option<Option<&'a str>> {
701    if let Some((prefix, suffix)) = pattern.split_once("{id}") {
702        let rest = path.strip_prefix(prefix)?;
703        let id = rest.strip_suffix(suffix)?;
704        if !id.is_empty() && !id.contains('/') {
705            return Some(Some(id));
706        }
707        None
708    } else if pattern == path {
709        Some(None)
710    } else {
711        None
712    }
713}
714
715pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
716    let is_health_get = req.path == "/api/health" && req.method == "GET";
717    if (req.path.starts_with("/api/") || req.method == "POST")
718        && !is_health_get
719        && !has_valid_token(surface, req)
720    {
721        return json_error(
722            403,
723            "missing or invalid surface token; open the page from the URL blyte printed",
724        );
725    }
726
727    if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
728        if req.method != "GET" {
729            return method_not_allowed(req);
730        }
731        return Response {
732            status,
733            content_type,
734            body,
735        };
736    }
737
738    if req.path == "/" || req.path == "/index.html" {
739        if req.method != "GET" {
740            return method_not_allowed(req);
741        }
742        return Response::html(INDEX_HTML.as_bytes().to_vec());
743    }
744
745    if req.path == "/api/health" {
746        if req.method != "GET" {
747            return method_not_allowed(req);
748        }
749        return health_response(surface);
750    }
751
752    for &(pattern, handler) in API_GET_ROUTES {
753        if let Some(id) = match_api_get_route(pattern, &req.path) {
754            if req.method != "GET" {
755                return method_not_allowed(req);
756            }
757            return match handler {
758                ApiGetHandler::Session => session_response(surface),
759                ApiGetHandler::Events => handle_events(surface, req),
760                ApiGetHandler::Models => handle_models(),
761                ApiGetHandler::Runs => handle_runs(surface, now),
762                ApiGetHandler::Requests => handle_requests(surface),
763                ApiGetHandler::Map => handle_map(surface),
764                ApiGetHandler::RunDiff => handle_run_diff(surface, id.unwrap_or("")),
765            };
766        }
767    }
768
769    match req.path.as_str() {
770        "/api/session/messages" => {
771            if req.method != "POST" {
772                return method_not_allowed(req);
773            }
774            handle_post_message(surface, req)
775        }
776        "/api/session/model" => {
777            if req.method != "POST" {
778                return method_not_allowed(req);
779            }
780            handle_post_model(surface, req)
781        }
782        "/api/session/effort" => {
783            if req.method != "POST" {
784                return method_not_allowed(req);
785            }
786            handle_post_effort(surface, req)
787        }
788        "/api/runs/changed" => {
789            if req.method != "POST" {
790                return method_not_allowed(req);
791            }
792            handle_runs_changed(surface)
793        }
794        path => {
795            if let Some(id) = path.strip_prefix("/api/session/approvals/") {
796                if !id.is_empty() && !id.contains('/') {
797                    if req.method != "POST" {
798                        return method_not_allowed(req);
799                    }
800                    return handle_post_approval(surface, id, req);
801                }
802            }
803            if let Some(rest) = path.strip_prefix("/api/runs/") {
804                if let Some(id) = rest.strip_suffix("/decision") {
805                    if !id.is_empty() && !id.contains('/') {
806                        if req.method != "POST" {
807                            return method_not_allowed(req);
808                        }
809                        return handle_run_decision(surface, id, req, now);
810                    }
811                }
812            }
813            if let Some(rest) = path.strip_prefix("/api/requests/") {
814                if let Some(id) = rest.strip_suffix("/push") {
815                    if req.method != "POST" {
816                        return method_not_allowed(req);
817                    }
818                    return handle_request_push(surface, id);
819                }
820                if let Some(id) = rest.strip_suffix("/pull-request") {
821                    if req.method != "POST" {
822                        return method_not_allowed(req);
823                    }
824                    return handle_request_pull_request(surface, id, req);
825                }
826            }
827            json_error(404, format!("not found: {}", req.path))
828        }
829    }
830}
831
832fn find_git_toplevel(dir: &Path) -> Result<PathBuf, String> {
833    let out = Command::new("git")
834        .args(["rev-parse", "--show-toplevel"])
835        .current_dir(dir)
836        .output()
837        .map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
838    if !out.status.success() {
839        return Err(format!("not inside a git repository ({})", dir.display()));
840    }
841    let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
842    if path_str.is_empty() {
843        return Err(format!("not inside a git repository ({})", dir.display()));
844    }
845    Ok(PathBuf::from(path_str))
846}
847
848fn resolve_main_checkout(worktree_root: &Path) -> Result<PathBuf, String> {
849    let out = Command::new("git")
850        .args([
851            "rev-parse",
852            "--path-format=absolute",
853            "--git-dir",
854            "--git-common-dir",
855        ])
856        .current_dir(worktree_root)
857        .output()
858        .map_err(|_| {
859            format!(
860                "cannot find the main checkout of {}",
861                worktree_root.display()
862            )
863        })?;
864    if !out.status.success() {
865        return Err(format!(
866            "cannot find the main checkout of {}",
867            worktree_root.display()
868        ));
869    }
870    let text = String::from_utf8_lossy(&out.stdout);
871    let mut lines = text.lines();
872    let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
873        return Err(format!(
874            "cannot find the main checkout of {}",
875            worktree_root.display()
876        ));
877    };
878    let git_dir_path = PathBuf::from(git_dir.trim());
879    let common_dir_path = PathBuf::from(common_dir.trim());
880    let same_git_dir = match (git_dir_path.canonicalize(), common_dir_path.canonicalize()) {
881        (Ok(a), Ok(b)) => a == b,
882        _ => git_dir_path == common_dir_path,
883    };
884    if same_git_dir {
885        return Ok(worktree_root.to_path_buf());
886    }
887    crate::config::main_checkout(worktree_root).ok_or_else(|| {
888        format!(
889            "cannot find the main checkout of {}",
890            worktree_root.display()
891        )
892    })
893}
894
895fn current_branch(main_checkout: &Path) -> Result<String, String> {
896    if let Ok(out) = Command::new("git")
897        .args(["rev-parse", "--abbrev-ref", "HEAD"])
898        .current_dir(main_checkout)
899        .output()
900    {
901        if out.status.success() {
902            let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
903            if !branch.is_empty() {
904                return Ok(branch);
905            }
906        }
907    }
908    if let Ok(out) = Command::new("git")
909        .args(["symbolic-ref", "--short", "HEAD"])
910        .current_dir(main_checkout)
911        .output()
912    {
913        if out.status.success() {
914            let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
915            if !branch.is_empty() {
916                return Ok(branch);
917            }
918        }
919    }
920    Err(format!(
921        "cannot read the current branch of {}",
922        main_checkout.display()
923    ))
924}
925
926fn repo_name_for(root: &Path) -> Result<String, String> {
927    root.file_name()
928        .and_then(|s| s.to_str())
929        .filter(|s| !s.is_empty())
930        .map(String::from)
931        .ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
932}
933
934fn now_duration() -> Result<Duration, String> {
935    SystemTime::now()
936        .duration_since(UNIX_EPOCH)
937        .map_err(|e| format!("system clock is before Unix epoch: {e}"))
938}
939
940fn new_session_id(nanos: u128) -> String {
941    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
942    format!("surface-{}-{nanos}-{seq}", std::process::id())
943}
944
945pub fn open_browser(url: &str) {
946    #[cfg(target_os = "macos")]
947    let cmd = "open";
948    #[cfg(not(target_os = "macos"))]
949    let cmd = "xdg-open";
950    if let Err(e) = Command::new(cmd).arg(url).spawn() {
951        eprintln!("blyte: could not open a browser with {cmd}: {e}; open {url} yourself");
952    }
953}
954
955fn resolve_initial_model(config: &ReplConfig) -> String {
956    if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
957        return m.to_string();
958    }
959    if let Ok(m) = std::env::var("BLYTE_MODEL") {
960        if !m.trim().is_empty() {
961            return m;
962        }
963    }
964    if let Ok(p) = blyte_provider::resolve_provider(None) {
965        return p.model_id();
966    }
967    "gemini-3.8-flash-high".to_string()
968}
969
970#[cfg(unix)]
971static SIGNAL_STOP: AtomicBool = AtomicBool::new(false);
972
973#[cfg(unix)]
974extern "C" fn handle_shutdown_signal(_: libc::c_int) {
975    SIGNAL_STOP.store(true, Ordering::Relaxed);
976}
977
978fn ensure_token_dir(dir: &Path) -> Result<(), String> {
979    #[cfg(unix)]
980    {
981        use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
982        if let Some(parent) = dir.parent() {
983            std::fs::create_dir_all(parent)
984                .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
985        }
986        let mut builder = std::fs::DirBuilder::new();
987        builder.mode(0o700);
988        match builder.create(dir) {
989            Ok(()) => {}
990            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
991                std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
992                    .map_err(|e| format!("cannot set permissions on {}: {e}", dir.display()))?;
993            }
994            Err(e) => return Err(format!("cannot create {}: {e}", dir.display())),
995        }
996        Ok(())
997    }
998    #[cfg(not(unix))]
999    {
1000        std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))
1001    }
1002}
1003
1004fn write_token_file(token_file_path: &Path, token: &str) -> Result<(), String> {
1005    let token_dir = token_file_path
1006        .parent()
1007        .ok_or_else(|| format!("invalid token path {}", token_file_path.display()))?;
1008    ensure_token_dir(token_dir)?;
1009    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1010    let tmp_path = token_dir.join(format!(".surface.token.{}.{seq}.tmp", std::process::id()));
1011    let mut opts = std::fs::OpenOptions::new();
1012    opts.write(true).create_new(true);
1013    #[cfg(unix)]
1014    {
1015        opts.mode(0o600);
1016    }
1017    let mut file = opts
1018        .open(&tmp_path)
1019        .map_err(|e| format!("cannot create {}: {e}", token_file_path.display()))?;
1020    if let Err(e) = writeln!(file, "{token}") {
1021        let _ = std::fs::remove_file(&tmp_path);
1022        return Err(format!("cannot write {}: {e}", token_file_path.display()));
1023    }
1024    drop(file);
1025    if let Err(e) = std::fs::rename(&tmp_path, token_file_path) {
1026        let _ = std::fs::remove_file(&tmp_path);
1027        return Err(format!("cannot write {}: {e}", token_file_path.display()));
1028    }
1029    Ok(())
1030}
1031
1032struct TokenFileGuard {
1033    path: PathBuf,
1034}
1035
1036impl Drop for TokenFileGuard {
1037    fn drop(&mut self) {
1038        let _ = std::fs::remove_file(&self.path);
1039    }
1040}
1041
1042struct RegistryEntryGuard {
1043    dir: PathBuf,
1044    id: String,
1045}
1046
1047impl Drop for RegistryEntryGuard {
1048    fn drop(&mut self) {
1049        let _ = crate::surface_registry::remove_entry(&self.dir, &self.id);
1050    }
1051}
1052
1053pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
1054    #[cfg(unix)]
1055    {
1056        SIGNAL_STOP.store(false, Ordering::Relaxed);
1057        unsafe {
1058            libc::signal(
1059                libc::SIGINT,
1060                handle_shutdown_signal as *const () as libc::sighandler_t,
1061            );
1062            libc::signal(
1063                libc::SIGTERM,
1064                handle_shutdown_signal as *const () as libc::sighandler_t,
1065            );
1066        }
1067    }
1068    run_inner(
1069        args,
1070        config,
1071        &mut std::io::stdout(),
1072        &mut std::io::stderr(),
1073        &mut open_browser,
1074        || {
1075            #[cfg(unix)]
1076            {
1077                SIGNAL_STOP.load(Ordering::Relaxed)
1078            }
1079            #[cfg(not(unix))]
1080            {
1081                false
1082            }
1083        },
1084        None,
1085    )
1086}
1087
1088pub fn run_with_io(
1089    args: &SurfaceArgs,
1090    config: ReplConfig,
1091    out: &mut dyn Write,
1092    err: &mut dyn Write,
1093) -> i32 {
1094    run_inner(args, config, out, err, &mut open_browser, || false, None)
1095}
1096
1097pub fn run_with_hooks(
1098    args: &SurfaceArgs,
1099    config: ReplConfig,
1100    out: &mut dyn Write,
1101    err: &mut dyn Write,
1102    opener: &mut dyn FnMut(&str),
1103    stop: Arc<AtomicBool>,
1104) -> i32 {
1105    run_inner(
1106        args,
1107        config,
1108        out,
1109        err,
1110        opener,
1111        move || stop.load(Ordering::Relaxed),
1112        None,
1113    )
1114}
1115
1116pub fn run_with_runner(
1117    args: &SurfaceArgs,
1118    config: ReplConfig,
1119    out: &mut dyn Write,
1120    err: &mut dyn Write,
1121    opener: &mut dyn FnMut(&str),
1122    stop: Arc<AtomicBool>,
1123    runner: Box<dyn PromptRunner>,
1124) -> i32 {
1125    run_inner(
1126        args,
1127        config,
1128        out,
1129        err,
1130        opener,
1131        move || stop.load(Ordering::Relaxed),
1132        Some(runner),
1133    )
1134}
1135
1136struct ReconcileTimerGuard {
1137    stop: Arc<AtomicBool>,
1138    handle: Option<std::thread::JoinHandle<()>>,
1139}
1140
1141impl Drop for ReconcileTimerGuard {
1142    fn drop(&mut self) {
1143        self.stop.store(true, Ordering::Release);
1144        if let Some(handle) = self.handle.take() {
1145            let _ = handle.join();
1146        }
1147    }
1148}
1149
1150fn spawn_reconcile_timer(surface: Arc<Surface>) -> ReconcileTimerGuard {
1151    let stop = Arc::new(AtomicBool::new(false));
1152    let thread_stop = Arc::clone(&stop);
1153    let handle = std::thread::spawn(move || {
1154        let mut after = surface.session.info().last_seq;
1155        let mut next_tick = Instant::now();
1156        let mut seen_errors: HashSet<String> = HashSet::new();
1157        while !thread_stop.load(Ordering::Acquire) {
1158            let wait = if surface.reconcile_requested.load(Ordering::Acquire) {
1159                Duration::ZERO
1160            } else {
1161                next_tick
1162                    .saturating_duration_since(Instant::now())
1163                    .min(RECONCILE_POLL_WAIT)
1164            };
1165            let entries = surface.session.entries_after(after, wait);
1166            let mut went_idle = false;
1167            for entry in entries {
1168                after = entry.seq;
1169                if matches!(entry.body, EntryBody::Idle { .. }) {
1170                    went_idle = true;
1171                }
1172            }
1173            if thread_stop.load(Ordering::Acquire) {
1174                break;
1175            }
1176            let requested = surface.reconcile_requested.swap(false, Ordering::AcqRel);
1177            if went_idle || requested || Instant::now() >= next_tick {
1178                match now_duration().and_then(|d| reconcile_runs(&surface, d.as_secs())) {
1179                    Ok((_, errors)) => {
1180                        for msg in errors {
1181                            if seen_errors.insert(msg.clone()) {
1182                                surface.session.record_error(&msg);
1183                                eprintln!("blyte: {msg}");
1184                            }
1185                        }
1186                    }
1187                    Err(e) => {
1188                        if seen_errors.insert(e.clone()) {
1189                            eprintln!("blyte: {e}");
1190                        }
1191                    }
1192                }
1193                next_tick = Instant::now() + RECONCILE_SAFETY_NET_INTERVAL;
1194            }
1195        }
1196    });
1197    ReconcileTimerGuard {
1198        stop,
1199        handle: Some(handle),
1200    }
1201}
1202
1203fn run_inner<S>(
1204    args: &SurfaceArgs,
1205    mut config: ReplConfig,
1206    out: &mut dyn Write,
1207    err: &mut dyn Write,
1208    opener: &mut dyn FnMut(&str),
1209    should_stop: S,
1210    custom_runner: Option<Box<dyn PromptRunner>>,
1211) -> i32
1212where
1213    S: Fn() -> bool,
1214{
1215    let worktree_root = match find_git_toplevel(&config.repo_root) {
1216        Ok(r) => r,
1217        Err(e) => {
1218            let _ = writeln!(err, "blyte: {e}");
1219            return 1;
1220        }
1221    };
1222    let main_checkout = match resolve_main_checkout(&worktree_root) {
1223        Ok(m) => m,
1224        Err(e) => {
1225            let _ = writeln!(err, "blyte: {e}");
1226            return 1;
1227        }
1228    };
1229    let same_checkout = match (worktree_root.canonicalize(), main_checkout.canonicalize()) {
1230        (Ok(a), Ok(b)) => a == b,
1231        _ => worktree_root == main_checkout,
1232    };
1233    if !same_checkout {
1234        let _ = writeln!(
1235            err,
1236            "blyte: started in a linked worktree ({}); this surface works in the main checkout {}",
1237            worktree_root.display(),
1238            main_checkout.display()
1239        );
1240        let _ = err.flush();
1241    }
1242
1243    let repo = match repo_name_for(&main_checkout) {
1244        Ok(r) => r,
1245        Err(e) => {
1246            let _ = writeln!(err, "blyte: {e}");
1247            return 1;
1248        }
1249    };
1250
1251    let registry_dir = match crate::surface_registry::registry_dir() {
1252        Ok(d) => d,
1253        Err(e) => {
1254            let _ = writeln!(err, "blyte: {e}");
1255            return 1;
1256        }
1257    };
1258
1259    let all_records = match crate::surface_dir::list_records(&main_checkout) {
1260        Ok(r) => r,
1261        Err(e) => {
1262            let _ = writeln!(err, "blyte: {e}");
1263            return 1;
1264        }
1265    };
1266    let mut running = Vec::new();
1267    let mut stopped = Vec::new();
1268    for rec in all_records {
1269        if crate::surface_dir::is_running(&rec) {
1270            running.push(rec);
1271        } else {
1272            stopped.push(rec);
1273        }
1274    }
1275
1276    let live_registry = match crate::surface_registry::live_entries(&registry_dir) {
1277        Ok(entries) => entries,
1278        Err(e) => {
1279            let _ = writeln!(err, "blyte: {e}");
1280            return 1;
1281        }
1282    };
1283    let mut running_names: Vec<String> = running.iter().map(|r| r.name.clone()).collect();
1284    for entry in &live_registry {
1285        if !running_names.iter().any(|n| n == &entry.name) {
1286            running_names.push(entry.name.clone());
1287        }
1288    }
1289
1290    let (surface_id, surface_name) = if let Some(ref target) = args.resume {
1291        if let Some(rec) = running
1292            .iter()
1293            .find(|r| r.id == *target || r.name == *target)
1294        {
1295            let _ = writeln!(
1296                err,
1297                "blyte: surface {target} is already running (port {})",
1298                rec.port
1299            );
1300            return 1;
1301        }
1302        let stopped_matches: Vec<&SurfaceRecord> = stopped
1303            .iter()
1304            .filter(|r| r.id == *target || r.name == *target)
1305            .collect();
1306        if stopped_matches.is_empty() {
1307            let _ = writeln!(
1308                err,
1309                "blyte: no stopped surface named {target} in {}",
1310                main_checkout.display()
1311            );
1312            return 1;
1313        }
1314        if stopped_matches.len() > 1 {
1315            let ids: Vec<&str> = stopped_matches.iter().map(|r| r.id.as_str()).collect();
1316            let _ = writeln!(
1317                err,
1318                "blyte: more than one stopped surface is named {target}; resume by id: {}",
1319                ids.join(", ")
1320            );
1321            return 1;
1322        }
1323        let rec = stopped_matches[0];
1324        if running_names.iter().any(|n| n == &rec.name) {
1325            let _ = writeln!(
1326                err,
1327                "blyte: a running surface is already named {}; stop it or resume by another name",
1328                rec.name
1329            );
1330            return 1;
1331        }
1332        (rec.id.clone(), rec.name.clone())
1333    } else {
1334        let id = match crate::surface_dir::new_surface_id() {
1335            Ok(id) => id,
1336            Err(e) => {
1337                let _ = writeln!(err, "blyte: {e}");
1338                return 1;
1339            }
1340        };
1341        let name = match crate::surface_dir::pick_name(&repo, args.name.as_deref(), &running_names)
1342        {
1343            Ok(name) => name,
1344            Err(e) => {
1345                let _ = writeln!(err, "blyte: {e}");
1346                return 1;
1347            }
1348        };
1349        (id, name)
1350    };
1351
1352    let branch = match current_branch(&main_checkout) {
1353        Ok(b) => b,
1354        Err(e) => {
1355            let _ = writeln!(err, "blyte: {e}");
1356            return 1;
1357        }
1358    };
1359
1360    if !config.converse {
1361        config.converse = true;
1362        if config.max_turns == 25 || config.max_turns == 60 {
1363            config.max_turns = 1000;
1364        }
1365        if config.fold_budget.is_none() {
1366            config.fold_budget = Some(100_000);
1367        }
1368    }
1369    config.repo_root = main_checkout.clone();
1370
1371    let started_dur = match now_duration() {
1372        Ok(d) => d,
1373        Err(e) => {
1374            let _ = writeln!(err, "blyte: {e}");
1375            return 1;
1376        }
1377    };
1378    let started_at = started_dur.as_secs();
1379    let session_id = new_session_id(started_dur.as_nanos());
1380    if std::env::var("BLYTE_SESSION")
1381        .map(|v| v.is_empty())
1382        .unwrap_or(true)
1383    {
1384        std::env::set_var("BLYTE_SESSION", &session_id);
1385    }
1386
1387    let token = match generate_token() {
1388        Ok(t) => t,
1389        Err(e) => {
1390            let _ = writeln!(err, "blyte: {e}");
1391            return 1;
1392        }
1393    };
1394
1395    let bind_addr = format!("127.0.0.1:{}", args.port);
1396    let listener = match TcpListener::bind(&bind_addr) {
1397        Ok(l) => l,
1398        Err(e) => {
1399            let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
1400            return 1;
1401        }
1402    };
1403    let actual_port = match listener.local_addr() {
1404        Ok(a) => a.port(),
1405        Err(e) => {
1406            let _ = writeln!(err, "blyte: failed to read listener address: {e}");
1407            return 1;
1408        }
1409    };
1410
1411    let token_file_path = match blyte_agent::sandbox::surface_token_path_for_id(&surface_id) {
1412        Ok(p) => p,
1413        Err(e) => {
1414            let _ = writeln!(err, "blyte: {e}");
1415            return 1;
1416        }
1417    };
1418    if let Err(e) = write_token_file(&token_file_path, &token) {
1419        let _ = writeln!(err, "blyte: {e}");
1420        return 1;
1421    }
1422    let _token_guard = TokenFileGuard {
1423        path: token_file_path,
1424    };
1425
1426    // The record is written as soon as the directory exists: another start lists
1427    // every surface directory and fails on one that has no record.
1428    let record = SurfaceRecord {
1429        id: surface_id.clone(),
1430        name: surface_name.clone(),
1431        pid: std::process::id(),
1432        port: actual_port,
1433        session_id: session_id.clone(),
1434        started_at,
1435    };
1436    if let Err(e) = crate::surface_dir::write_record(&main_checkout, &record) {
1437        let _ = writeln!(err, "blyte: {e}");
1438        return 1;
1439    }
1440    let registry_entry = crate::surface_registry::RegistryEntry {
1441        id: surface_id.clone(),
1442        name: surface_name.clone(),
1443        root: main_checkout.clone(),
1444        branch,
1445        pid: std::process::id(),
1446        port: actual_port,
1447        started_at,
1448        doing: "idle".to_string(),
1449    };
1450    if let Err(e) = crate::surface_registry::write_entry(&registry_dir, &registry_entry) {
1451        let _ = writeln!(err, "blyte: {e}");
1452        return 1;
1453    }
1454    let _registry_guard = RegistryEntryGuard {
1455        dir: registry_dir.clone(),
1456        id: surface_id.clone(),
1457    };
1458    let entries_log_path = crate::surface_dir::entries_path(&main_checkout, &surface_id);
1459    blyte_agent::tools::set_blyte_surface(Some(surface_id.clone()));
1460    let model = resolve_initial_model(&config);
1461    let session = match Session::start_with_log_io(model, Some(entries_log_path), err, |approver| {
1462        custom_runner.unwrap_or_else(|| Box::new(AgentRunner::new(&config, approver)))
1463    }) {
1464        Ok(s) => s,
1465        Err(e) => {
1466            let _ = writeln!(err, "blyte: {e}");
1467            let _ = err.flush();
1468            return 1;
1469        }
1470    };
1471    let hook_dir = registry_dir.clone();
1472    let hook_entry = registry_entry.clone();
1473    session.set_activity_hook(Box::new(move |prompt| {
1474        let doing = match prompt {
1475            Some(text) => {
1476                let line = crate::surface_registry::first_line(text);
1477                if line.is_empty() {
1478                    "working".to_string()
1479                } else {
1480                    line
1481                }
1482            }
1483            None => "idle".to_string(),
1484        };
1485        // The whole entry is written, not only the changed field: another process removes an
1486        // entry whose surface did not answer its health check in time, and this puts it back.
1487        let entry = crate::surface_registry::RegistryEntry {
1488            doing,
1489            ..hook_entry.clone()
1490        };
1491        if let Err(e) = crate::surface_registry::write_entry(&hook_dir, &entry) {
1492            eprintln!("blyte: {e}");
1493        }
1494    }));
1495
1496    let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
1497    let _ = writeln!(out, "blyte: surface {surface_name} at {url}");
1498    let _ = out.flush();
1499    if !args.no_open {
1500        opener(&url);
1501    }
1502
1503    let surface = Arc::new(Surface {
1504        surface_id,
1505        surface_name,
1506        root: main_checkout,
1507        repo,
1508        session,
1509        session_id,
1510        started_at,
1511        days: args.days,
1512        token,
1513        requests: Arc::new(RequestsState::new()),
1514        publisher: Arc::new(RealPublisher),
1515        reconcile_lock: Mutex::new(()),
1516        reconcile_requested: AtomicBool::new(false),
1517    });
1518
1519    let timer_guard = spawn_reconcile_timer(Arc::clone(&surface));
1520
1521    let serve_result =
1522        crate::http::serve_until(listener, should_stop, move |req| match now_duration() {
1523            Ok(d) => route(&surface, req, d.as_secs()),
1524            Err(e) => json_error(500, e),
1525        });
1526
1527    drop(timer_guard);
1528
1529    match serve_result {
1530        Ok(()) => 0,
1531        Err(e) => {
1532            let _ = writeln!(err, "blyte: server error: {e}");
1533            1
1534        }
1535    }
1536}