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