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    #[serde(skip_serializing_if = "std::ops::Not::not")]
113    in_place: bool,
114    #[serde(skip_serializing_if = "std::ops::Not::not")]
115    undone: bool,
116}
117
118#[derive(Serialize)]
119struct LiveRunsResponse<'a> {
120    generated_at: u64,
121    repo: &'a str,
122    running: &'a [crate::live_runs::RunningRun],
123    runs: Vec<RunWithHold<'a>>,
124    skipped: &'a [crate::replay::Skipped],
125}
126
127fn json_error(status: u16, msg: impl Into<String>) -> Response {
128    Response::json(status, &serde_json::json!({ "error": msg.into() }))
129}
130
131fn method_not_allowed(req: &Request) -> Response {
132    json_error(
133        405,
134        format!("method {} not allowed for {}", req.method, req.path),
135    )
136}
137
138fn is_valid_run_id(id: &str) -> bool {
139    !id.is_empty()
140        && id != "."
141        && id != ".."
142        && id
143            .bytes()
144            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
145}
146
147fn parse_json_object(body: &[u8]) -> Result<serde_json::Map<String, serde_json::Value>, Response> {
148    let val: serde_json::Value = serde_json::from_slice(body)
149        .map_err(|e| json_error(400, format!("invalid JSON body: {e}")))?;
150    val.as_object()
151        .cloned()
152        .ok_or_else(|| json_error(400, "request body must be a JSON object"))
153}
154
155fn handle_surfaces(surface: &Surface) -> Response {
156    let state_dir = match crate::surface_registry::state_dir() {
157        Ok(dir) => dir,
158        Err(e) => return json_error(500, e),
159    };
160    let registry_dir = state_dir.join("surfaces");
161    let stopped = match crate::surfaces_cmd::stopped_surfaces(&surface.root, &state_dir) {
162        Ok(stopped) => stopped,
163        Err(e) => return json_error(500, e),
164    };
165    match crate::surfaces_cmd::surfaces_payload(&registry_dir, &surface.surface_id, &stopped) {
166        Ok(payload) => Response::json(200, &payload),
167        Err(e) => json_error(500, e),
168    }
169}
170
171fn health_response(surface: &Surface) -> Response {
172    Response::json(
173        200,
174        &serde_json::json!({
175            "surface_id": surface.surface_id,
176            "surface_name": surface.surface_name,
177            "session_id": surface.session_id,
178        }),
179    )
180}
181
182fn session_response(surface: &Surface) -> Response {
183    let info = surface.session.info();
184    let repository = match is_repository(&surface.root) {
185        Ok(v) => v,
186        Err(e) => return json_error(500, e),
187    };
188    Response::json(
189        200,
190        &serde_json::json!({
191            "session_id": surface.session_id,
192            "surface_name": surface.surface_name,
193            "repo": surface.repo,
194            "repository": repository,
195            "started_at": surface.started_at,
196            "model": info.model,
197            "effort": info.effort,
198            "effort_supported": info.effort_supported,
199            "busy": info.busy,
200            "queued": info.queued,
201            "last_seq": info.last_seq,
202        }),
203    )
204}
205
206fn handle_events(surface: &Surface, req: &Request) -> Response {
207    let after_raw = match req.query_value("after") {
208        Some(v) => v,
209        None => return json_error(400, "missing required query parameter: after"),
210    };
211    let after = match after_raw.parse::<u64>() {
212        Ok(v) => v,
213        Err(_) => {
214            return json_error(
215                400,
216                format!("query parameter after must be a non-negative integer, got '{after_raw}'"),
217            );
218        }
219    };
220    let wait_ms = match req.query_value("wait_ms") {
221        None => 0,
222        Some(raw) => match raw.parse::<u64>() {
223            Ok(v) if v <= MAX_WAIT_MS => v,
224            Ok(v) => {
225                return json_error(
226                    400,
227                    format!("query parameter wait_ms must be at most {MAX_WAIT_MS}, got {v}"),
228                );
229            }
230            Err(_) => {
231                return json_error(
232                    400,
233                    format!("query parameter wait_ms must be a non-negative integer, got '{raw}'"),
234                );
235            }
236        },
237    };
238    let entries = surface
239        .session
240        .entries_after(after, Duration::from_millis(wait_ms));
241    let last_seq = surface.session.info().last_seq;
242    Response::json(
243        200,
244        &serde_json::json!({
245            "entries": entries,
246            "last_seq": last_seq,
247        }),
248    )
249}
250
251fn handle_post_message(surface: &Surface, req: &Request) -> Response {
252    let obj = match parse_json_object(&req.body) {
253        Ok(o) => o,
254        Err(resp) => return resp,
255    };
256    let attachment_ids: Vec<String> = match obj.get("attachments") {
257        None | Some(serde_json::Value::Null) => Vec::new(),
258        Some(serde_json::Value::Array(arr)) => {
259            let mut ids = Vec::with_capacity(arr.len());
260            for item in arr {
261                match item.as_str() {
262                    Some(s) => ids.push(s.to_string()),
263                    None => {
264                        return json_error(400, "field attachments must be an array of strings");
265                    }
266                }
267            }
268            ids
269        }
270        Some(_) => return json_error(400, "field attachments must be an array of strings"),
271    };
272    let text = match obj.get("text") {
273        Some(serde_json::Value::String(s)) => s.clone(),
274        Some(serde_json::Value::Null) | None if !attachment_ids.is_empty() => String::new(),
275        Some(_) => return json_error(400, "field text must be a string"),
276        None => return json_error(400, "missing required field: text"),
277    };
278    let report_ids: Vec<String> = match obj.get("reports") {
279        None | Some(serde_json::Value::Null) => Vec::new(),
280        Some(serde_json::Value::Array(arr)) => {
281            let mut ids = Vec::with_capacity(arr.len());
282            for item in arr {
283                match item.as_str() {
284                    Some(s) => ids.push(s.to_string()),
285                    None => return json_error(400, "field reports must be an array of strings"),
286                }
287            }
288            ids
289        }
290        Some(_) => return json_error(400, "field reports must be an array of strings"),
291    };
292    let pastes: Vec<crate::session::Paste> = match obj.get("pastes") {
293        None | Some(serde_json::Value::Null) => Vec::new(),
294        Some(serde_json::Value::Array(arr)) => {
295            let mut out = Vec::with_capacity(arr.len());
296            for item in arr {
297                match serde_json::from_value::<crate::session::Paste>(item.clone()) {
298                    Ok(p) => out.push(p),
299                    Err(e) => return json_error(400, format!("invalid paste entry: {e}")),
300                }
301            }
302            out
303        }
304        Some(_) => return json_error(400, "field pastes must be an array"),
305    };
306
307    let mut report_attachments = Vec::with_capacity(report_ids.len());
308    for id in report_ids {
309        let path = surface.root.join(".wt").join(format!("{id}.report.md"));
310        if !is_valid_run_id(&id) {
311            return json_error(
312                400,
313                format!("invalid report run id '{id}' (path: {})", path.display()),
314            );
315        }
316        match std::fs::read_to_string(&path) {
317            Ok(body) => report_attachments.push(Attachment {
318                run: id,
319                text: body,
320            }),
321            Err(e) => {
322                return json_error(
323                    400,
324                    format!(
325                        "cannot read report for run '{id}' at {}: {e}",
326                        path.display()
327                    ),
328                );
329            }
330        }
331    }
332
333    let mut file_attachments = Vec::with_capacity(attachment_ids.len());
334    if !attachment_ids.is_empty() {
335        let Some(record_dir) = surface.session.attachments_root() else {
336            return json_error(500, "attachments directory is not configured");
337        };
338        for id in attachment_ids {
339            match crate::attachments::load_with_path(&record_dir, &id) {
340                Ok((meta, path, _)) => {
341                    file_attachments.push(crate::session::QueuedAttachment { meta, path })
342                }
343                Err(e) => return json_error(400, e),
344            }
345        }
346    }
347
348    match surface.session.submit_with_attachments(
349        &text,
350        report_attachments,
351        file_attachments,
352        pastes,
353    ) {
354        Ok(seq) => Response::json(200, &serde_json::json!({ "seq": seq })),
355        Err(e) => json_error(400, e),
356    }
357}
358
359fn handle_post_attachment(surface: &Surface, req: &Request) -> Response {
360    let Some(raw_name) = req
361        .query_value("name")
362        .map(str::trim)
363        .filter(|s| !s.is_empty())
364    else {
365        return json_error(400, "missing required query parameter: name");
366    };
367    if req.body.len() > crate::attachments::MAX_ATTACHMENT_BYTES {
368        return Response::text(
369            413,
370            &format!("{raw_name} is larger than the 10 MiB limit for one file"),
371        );
372    }
373    if req.body.is_empty() {
374        return json_error(400, format!("{raw_name} is empty"));
375    }
376    let Some(record_dir) = surface.session.attachments_root() else {
377        return json_error(500, "attachments directory is not configured");
378    };
379    match crate::attachments::store(&record_dir, raw_name, &req.body) {
380        Ok(meta) => match serde_json::to_value(&meta) {
381            Ok(v) => Response::json(200, &v),
382            Err(e) => json_error(500, format!("failed to serialise attachment metadata: {e}")),
383        },
384        Err(e) => json_error(400, e),
385    }
386}
387
388fn handle_get_attachment(surface: &Surface, id: &str) -> Response {
389    let Some(record_dir) = surface.session.attachments_root() else {
390        return json_error(500, "attachments directory is not configured");
391    };
392    match crate::attachments::load(&record_dir, id) {
393        Ok((_meta, bytes)) => {
394            let content_type =
395                crate::attachments::detect_image(&bytes).unwrap_or("application/octet-stream");
396            Response::bytes(200, content_type, bytes)
397        }
398        Err(e) => json_error(404, e),
399    }
400}
401
402fn handle_post_peer_message(surface: &Surface, req: &Request) -> Response {
403    let obj = match parse_json_object(&req.body) {
404        Ok(o) => o,
405        Err(resp) => return resp,
406    };
407    for key in obj.keys() {
408        if !matches!(key.as_str(), "from_name" | "from_repository" | "text") {
409            return json_error(400, format!("unexpected field: {key}"));
410        }
411    }
412    let from_name = match obj.get("from_name") {
413        Some(serde_json::Value::String(s)) => s.clone(),
414        Some(_) => return json_error(400, "field from_name must be a string"),
415        None => return json_error(400, "missing required field: from_name"),
416    };
417    if let Err(e) = crate::surface_dir::validate_surface_name(&from_name) {
418        return json_error(400, format!("invalid from_name: {e}"));
419    }
420    let from_repository = match obj.get("from_repository") {
421        Some(serde_json::Value::String(s)) => s.clone(),
422        Some(_) => return json_error(400, "field from_repository must be a string"),
423        None => return json_error(400, "missing required field: from_repository"),
424    };
425    let repo_chars = from_repository.chars().count();
426    if repo_chars == 0 || repo_chars > MAX_PEER_REPO_CHARS {
427        return json_error(
428            400,
429            format!("field from_repository must be 1 to {MAX_PEER_REPO_CHARS} characters"),
430        );
431    }
432    if from_repository.chars().any(char::is_control) {
433        return json_error(
434            400,
435            "field from_repository must not contain control characters",
436        );
437    }
438    let text = match obj.get("text") {
439        Some(serde_json::Value::String(s)) => s.clone(),
440        Some(_) => return json_error(400, "field text must be a string"),
441        None => return json_error(400, "missing required field: text"),
442    };
443    if text.trim().is_empty() {
444        return json_error(400, "field text must not be blank");
445    }
446    if text.len() > MAX_PEER_TEXT_BYTES {
447        return json_error(
448            400,
449            format!("field text must be at most {MAX_PEER_TEXT_BYTES} bytes"),
450        );
451    }
452
453    match surface
454        .session
455        .submit_peer(&from_name, &from_repository, &text)
456    {
457        Ok(PeerDelivery::Delivered) => {
458            Response::json(200, &serde_json::json!({ "status": "delivered" }))
459        }
460        Ok(PeerDelivery::Held) => Response::json(200, &serde_json::json!({ "status": "held" })),
461        Err(e) => json_error(400, e),
462    }
463}
464
465fn handle_models() -> Response {
466    let discovered = blyte_provider::discover_all_models();
467    let mut models = Vec::new();
468    let mut unavailable = Vec::new();
469    let mut error_parts = Vec::new();
470
471    for (provider, result) in discovered {
472        match result {
473            Ok(list) => {
474                for m in list {
475                    let effort_supported = crate::session::model_supports_effort(&m.id);
476                    models.push(serde_json::json!({
477                        "id": m.id,
478                        "effort_supported": effort_supported,
479                    }));
480                }
481            }
482            Err(e) => {
483                let err_text = e.to_string();
484                error_parts.push(format!("{provider}: {err_text}"));
485                unavailable.push(serde_json::json!({
486                    "provider": provider,
487                    "error": err_text,
488                }));
489            }
490        }
491    }
492
493    if models.is_empty() {
494        let msg = if error_parts.is_empty() {
495            "no models listed by any provider".to_string()
496        } else {
497            format!("no models available: {}", error_parts.join("; "))
498        };
499        return json_error(502, msg);
500    }
501
502    Response::json(
503        200,
504        &serde_json::json!({
505            "models": models,
506            "unavailable": unavailable,
507        }),
508    )
509}
510
511fn handle_post_model(surface: &Surface, req: &Request) -> Response {
512    let obj = match parse_json_object(&req.body) {
513        Ok(o) => o,
514        Err(resp) => return resp,
515    };
516    let model = match obj.get("model") {
517        Some(serde_json::Value::String(s)) => s.clone(),
518        Some(_) => return json_error(400, "field model must be a string"),
519        None => return json_error(400, "missing required field: model"),
520    };
521    if model.trim().is_empty() {
522        return json_error(400, "field model must not be empty");
523    }
524    if let Err(e) = blyte_provider::resolve_provider(Some(&model)) {
525        return json_error(400, e.to_string());
526    }
527    if let Err(e) = surface.session.set_model(&model) {
528        return json_error(400, e);
529    }
530    session_response(surface)
531}
532
533fn handle_post_effort(surface: &Surface, req: &Request) -> Response {
534    let obj = match parse_json_object(&req.body) {
535        Ok(o) => o,
536        Err(resp) => return resp,
537    };
538    let effort = match obj.get("effort") {
539        Some(serde_json::Value::Null) => None,
540        Some(serde_json::Value::String(s)) => Some(s.clone()),
541        Some(_) => return json_error(400, "field effort must be a string or null"),
542        None => return json_error(400, "missing required field: effort"),
543    };
544    if let Err(e) = surface.session.set_effort(effort.as_deref()) {
545        return json_error(400, e);
546    }
547    session_response(surface)
548}
549
550fn handle_post_approval(surface: &Surface, id: &str, req: &Request) -> Response {
551    let obj = match parse_json_object(&req.body) {
552        Ok(o) => o,
553        Err(resp) => return resp,
554    };
555    if obj.len() != 1 {
556        return json_error(400, "request body must contain only field answer");
557    }
558    let answer = match obj.get("answer") {
559        Some(serde_json::Value::String(s)) if s == "yes" => ApprovalAnswer::Yes,
560        Some(serde_json::Value::String(s)) if s == "no" => ApprovalAnswer::No,
561        Some(serde_json::Value::String(other)) => {
562            return json_error(
563                400,
564                format!("field answer must be \"yes\" or \"no\", got '{other}'"),
565            );
566        }
567        Some(_) => return json_error(400, "field answer must be \"yes\" or \"no\""),
568        None => return json_error(400, "missing required field: answer"),
569    };
570    match surface.session.answer_approval(id, answer) {
571        Ok(seq) => Response::json(
572            200,
573            &serde_json::json!({
574                "id": id,
575                "answer": answer.as_str(),
576                "seq": seq,
577            }),
578        ),
579        Err(AnswerError::NotFound) => json_error(404, format!("unknown approval id: {id}")),
580        Err(AnswerError::AlreadyAnswered) => {
581            json_error(409, format!("approval {id} has already been answered"))
582        }
583    }
584}
585
586pub fn reconcile_runs(
587    surface: &Surface,
588    now: u64,
589) -> Result<(crate::live_runs::LiveRuns, Vec<String>), String> {
590    let _guard = surface
591        .reconcile_lock
592        .lock()
593        .unwrap_or_else(|e| e.into_inner());
594    if !is_repository(&surface.root)? {
595        let records_dir = crate::dispatch_in_place::records_dir_for(&surface.root)?;
596        let owned = crate::requests::owned_run_ids_in(&records_dir, &surface.surface_id)?;
597        let mut live =
598            crate::live_runs::collect_in_place(&surface.root, &records_dir, now, surface.days)?;
599        live.running.retain(|run| owned.contains(&run.id));
600        live.runs.retain(|run| owned.contains(&run.id));
601
602        let mut errors = Vec::new();
603        if let Err(e) = crate::run_results::report_finished_runs_in(surface, &records_dir) {
604            errors.push(format!("run report failed: {e}"));
605        }
606        return Ok((live, errors));
607    }
608    let owned = crate::requests::owned_run_ids(surface)?;
609    let mut live = crate::live_runs::collect(&surface.root, now, surface.days)?;
610    let mut any_written = false;
611    for run in &live.runs {
612        if !owned.contains(&run.id) || run.checks_recorded {
613            continue;
614        }
615        if crate::queue_actions::ensure_checks(&surface.root, &run.id)? {
616            any_written = true;
617        }
618    }
619    if any_written {
620        live = crate::live_runs::collect(&surface.root, now, surface.days)?;
621    }
622    live.running.retain(|run| owned.contains(&run.id));
623    live.runs.retain(|run| owned.contains(&run.id));
624
625    let mut errors = Vec::new();
626    if let Err(e) = crate::run_results::report_finished_runs(surface) {
627        errors.push(format!("run report failed: {e}"));
628    }
629
630    let mut triggered = BTreeSet::new();
631    for run in &live.runs {
632        if run.research {
633            continue;
634        }
635        if let Some(ref req_id) = run.request {
636            if triggered.insert(req_id.clone()) {
637                if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
638                    errors.push(format!("combine trigger failed for {req_id}: {e}"));
639                }
640            }
641        }
642    }
643
644    Ok((live, errors))
645}
646
647fn handle_runs(surface: &Surface, now: u64) -> Response {
648    let is_repo = match is_repository(&surface.root) {
649        Ok(v) => v,
650        Err(e) => return json_error(500, e),
651    };
652    let (live, errors) = match reconcile_runs(surface, now) {
653        Ok(res) => res,
654        Err(e) => return json_error(500, e),
655    };
656    for msg in errors {
657        surface.session.record_error(&msg);
658    }
659
660    let mut runs_with_hold = Vec::with_capacity(live.runs.len());
661    if is_repo {
662        let run_refs: Vec<(&str, Option<&str>)> = live
663            .runs
664            .iter()
665            .map(|run| (run.id.as_str(), run.request.as_deref()))
666            .collect();
667        let combined_ids = match crate::requests::combined_run_ids(&surface.root, &run_refs) {
668            Ok(ids) => ids,
669            Err(e) => return json_error(500, e),
670        };
671
672        for run in &live.runs {
673            let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
674                Ok(h) => h,
675                Err(e) => return json_error(500, e),
676            };
677            let combined = combined_ids.contains(&run.id);
678            runs_with_hold.push(RunWithHold {
679                run,
680                hold,
681                combined,
682                in_place: false,
683                undone: false,
684            });
685        }
686    } else {
687        let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
688            Ok(dir) => dir,
689            Err(e) => return json_error(500, e),
690        };
691        for run in &live.runs {
692            let hold = match crate::queue_actions::read_hold_in(&records_dir, &run.id) {
693                Ok(h) => h,
694                Err(e) => return json_error(500, e),
695            };
696            let undone = crate::in_place_review::is_undone(&records_dir, &run.id);
697            runs_with_hold.push(RunWithHold {
698                run,
699                hold,
700                combined: false,
701                in_place: true,
702                undone,
703            });
704        }
705    }
706
707    let payload = LiveRunsResponse {
708        generated_at: live.generated_at,
709        repo: &live.repo,
710        running: &live.running,
711        runs: runs_with_hold,
712        skipped: &live.skipped,
713    };
714    match serde_json::to_value(&payload) {
715        Ok(val) => Response::json(200, &val),
716        Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
717    }
718}
719
720fn handle_runs_changed(surface: &Surface) -> Response {
721    surface.reconcile_requested.store(true, Ordering::Release);
722    Response::json(202, &serde_json::json!({}))
723}
724
725const NOT_A_GIT_REPO_ERROR: &str = "this folder is not a git repository";
726
727fn require_repository(root: &Path) -> Result<(), Response> {
728    match is_repository(root) {
729        Ok(true) => Ok(()),
730        Ok(false) => Err(json_error(409, NOT_A_GIT_REPO_ERROR)),
731        Err(e) => Err(json_error(500, e)),
732    }
733}
734
735fn handle_run_diff(surface: &Surface, id: &str) -> Response {
736    let is_repo = match is_repository(&surface.root) {
737        Ok(v) => v,
738        Err(e) => return json_error(500, e),
739    };
740    if !is_valid_run_id(id) {
741        return json_error(404, format!("unknown run: {id}"));
742    }
743    if !is_repo {
744        let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
745            Ok(dir) => dir,
746            Err(e) => return json_error(500, e),
747        };
748        let start = records_dir.join(format!("{id}.start.json"));
749        let summary = records_dir.join(format!("{id}.json"));
750        let report_json = records_dir.join(format!("{id}.report.json"));
751        let report_md = records_dir.join(format!("{id}.report.md"));
752        if !start.exists() && !summary.exists() && !report_json.exists() && !report_md.exists() {
753            return json_error(404, format!("unknown run: {id}"));
754        }
755        if let Err(err) = crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
756        {
757            return request_action_error_response(err);
758        }
759        return match crate::in_place_review::diff_for_run(&records_dir, id) {
760            Ok(body) => Response::text(200, &body),
761            Err(e) => {
762                if !summary.exists() || e.contains("No such file") || e.contains("missing manifest")
763                {
764                    json_error(404, e)
765                } else {
766                    json_error(500, e)
767                }
768            }
769        };
770    }
771    let wt_dir = surface.root.join(".wt");
772    let wt = wt_dir.join(id);
773    let start = wt_dir.join(format!("{id}.start.json"));
774    let summary = wt_dir.join(format!("{id}.json"));
775    let report_json = wt_dir.join(format!("{id}.report.json"));
776    let report_md = wt_dir.join(format!("{id}.report.md"));
777    if !wt.exists()
778        && !start.exists()
779        && !summary.exists()
780        && !report_json.exists()
781        && !report_md.exists()
782    {
783        return json_error(404, format!("unknown run: {id}"));
784    }
785    if let Err(err) = crate::requests::run_owner_check(surface, id) {
786        return request_action_error_response(err);
787    }
788    match crate::queue_actions::compute_review(&surface.root, id, true) {
789        Ok(data) => {
790            let body = if !data.wt_exists {
791                "(worktree removed)\n".to_string()
792            } else if data.diff_out.is_empty() {
793                String::new()
794            } else {
795                format!("{}\n", data.diff_out)
796            };
797            Response::text(200, &body)
798        }
799        Err(e) => {
800            if !wt.is_dir() || !wt.join(".git").exists() {
801                json_error(404, e)
802            } else {
803                json_error(500, e)
804            }
805        }
806    }
807}
808
809fn handle_run_undo(surface: &Surface, id: &str) -> Response {
810    let is_repo = match is_repository(&surface.root) {
811        Ok(v) => v,
812        Err(e) => return json_error(500, e),
813    };
814    if is_repo {
815        return json_error(
816            409,
817            "undo is for runs in a folder that is not a git repository",
818        );
819    }
820    if !is_valid_run_id(id) {
821        return json_error(404, format!("unknown run: {id}"));
822    }
823    let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
824        Ok(dir) => dir,
825        Err(e) => return json_error(500, e),
826    };
827    let run_exists = records_dir.join(format!("{id}.start.json")).exists()
828        || records_dir.join(format!("{id}.json")).exists()
829        || records_dir.join(format!("{id}.report.json")).exists()
830        || records_dir.join(format!("{id}.report.md")).exists();
831    if run_exists {
832        if let Err(err) = crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
833        {
834            return request_action_error_response(err);
835        }
836    }
837    match crate::in_place_review::undo_in(&surface.root, id) {
838        Ok(lines) => Response::json(200, &serde_json::json!({ "lines": lines })),
839        Err(msg) => json_error(409, msg),
840    }
841}
842
843fn parse_action(raw: &str) -> Result<Action, String> {
844    match raw {
845        "accept" => Ok(Action::Accept),
846        "send_back" => Ok(Action::SendBack),
847        "redo" => Ok(Action::Redo),
848        "hold" => Ok(Action::Hold),
849        "mark_read" => Ok(Action::MarkRead),
850        other => Err(format!(
851            "unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
852        )),
853    }
854}
855
856fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
857    let is_repo = match is_repository(&surface.root) {
858        Ok(v) => v,
859        Err(e) => return json_error(500, e),
860    };
861    let obj = match parse_json_object(&req.body) {
862        Ok(o) => o,
863        Err(resp) => return resp,
864    };
865    let action_str = match obj.get("action") {
866        Some(serde_json::Value::String(s)) => s.clone(),
867        Some(_) => return json_error(400, "field action must be a string"),
868        None => return json_error(400, "missing required field: action"),
869    };
870    let action = match parse_action(&action_str) {
871        Ok(a) => a,
872        Err(e) => return json_error(400, e),
873    };
874    let note = match obj.get("note") {
875        None | Some(serde_json::Value::Null) => None,
876        Some(serde_json::Value::String(s)) => Some(s.clone()),
877        Some(_) => return json_error(400, "field note must be a string or null"),
878    };
879
880    let decision = if is_repo {
881        let wt_dir = surface.root.join(".wt");
882        let run_exists = is_valid_run_id(id)
883            && (wt_dir.join(id).exists()
884                || wt_dir.join(format!("{id}.start.json")).exists()
885                || wt_dir.join(format!("{id}.json")).exists()
886                || wt_dir.join(format!("{id}.report.json")).exists()
887                || wt_dir.join(format!("{id}.report.md")).exists());
888        if run_exists {
889            if let Err(err) = crate::requests::run_owner_check(surface, id) {
890                return request_action_error_response(err);
891            }
892        }
893        match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
894            Ok(d) => d,
895            Err(e) => return json_error(400, e),
896        }
897    } else {
898        let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
899            Ok(dir) => dir,
900            Err(e) => return json_error(500, e),
901        };
902        let run_exists = is_valid_run_id(id)
903            && (records_dir.join(format!("{id}.start.json")).exists()
904                || records_dir.join(format!("{id}.json")).exists()
905                || records_dir.join(format!("{id}.report.json")).exists()
906                || records_dir.join(format!("{id}.report.md")).exists());
907        if run_exists {
908            if let Err(err) =
909                crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
910            {
911                return request_action_error_response(err);
912            }
913        }
914        match crate::queue_actions::decide_in_place(&records_dir, id, action, note.as_deref(), now)
915        {
916            Ok(d) => d,
917            Err(e) => return json_error(400, e),
918        }
919    };
920    let seq = match surface.session.record_decision(
921        &decision.run,
922        &action_str,
923        decision.note.as_deref(),
924        decision.conversation_message.as_deref(),
925    ) {
926        Ok(s) => s,
927        Err(e) => return json_error(500, e),
928    };
929    if is_repo && action == Action::Accept {
930        match crate::requests::run_request_id(&surface.root, &decision.run) {
931            Ok(Some(req_id)) => {
932                if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
933                    surface
934                        .session
935                        .record_error(&format!("combine trigger failed for {req_id}: {e}"));
936                }
937            }
938            Ok(None) => {}
939            Err(e) => return json_error(500, e),
940        }
941    }
942    Response::json(
943        200,
944        &serde_json::json!({
945            "decision": {
946                "run": decision.run,
947                "action": action_str,
948                "note": decision.note,
949                "conversation_message": decision.conversation_message,
950            },
951            "seq": seq,
952        }),
953    )
954}
955
956fn handle_map(surface: &Surface) -> Response {
957    match crate::map::build(&surface.root, &surface.repo) {
958        Ok(data) => match serde_json::to_value(&data) {
959            Ok(val) => Response::json(200, &val),
960            Err(e) => json_error(500, format!("failed to serialize map: {e}")),
961        },
962        Err(e) => json_error(422, e),
963    }
964}
965
966fn handle_requests(surface: &Surface) -> Response {
967    match is_repository(&surface.root) {
968        Ok(true) => {}
969        Ok(false) => return Response::json(200, &serde_json::json!([])),
970        Err(e) => return json_error(500, e),
971    }
972    match crate::requests::list_requests(surface) {
973        Ok(list) => match serde_json::to_value(&list) {
974            Ok(val) => Response::json(200, &val),
975            Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
976        },
977        Err(e) => json_error(500, e),
978    }
979}
980
981fn request_action_error_response(err: RequestActionError) -> Response {
982    match err {
983        RequestActionError::BadRequest(msg) => json_error(400, msg),
984        RequestActionError::NotOwned(msg) => json_error(403, msg),
985        RequestActionError::Conflict(msg) => json_error(409, msg),
986        RequestActionError::Internal(msg) => json_error(500, msg),
987    }
988}
989
990fn handle_request_push(surface: &Surface, id: &str) -> Response {
991    if let Err(resp) = require_repository(&surface.root) {
992        return resp;
993    }
994    match crate::requests::push_request(surface, id) {
995        Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
996        Err(err) => request_action_error_response(err),
997    }
998}
999
1000fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
1001    if let Err(resp) = require_repository(&surface.root) {
1002        return resp;
1003    }
1004    if let Err(e) = crate::dispatch::validate_request_id(id) {
1005        return json_error(400, e);
1006    }
1007    let obj = match parse_json_object(&req.body) {
1008        Ok(o) => o,
1009        Err(resp) => return resp,
1010    };
1011    let title = match obj.get("title") {
1012        Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
1013        Some(serde_json::Value::String(_)) => {
1014            return json_error(400, "field title must not be empty");
1015        }
1016        Some(_) => return json_error(400, "field title must be a string"),
1017        None => return json_error(400, "missing required field: title"),
1018    };
1019    let body = match obj.get("body") {
1020        None | Some(serde_json::Value::Null) => String::new(),
1021        Some(serde_json::Value::String(s)) => s.clone(),
1022        Some(_) => return json_error(400, "field body must be a string"),
1023    };
1024    match crate::requests::open_request_pull_request(surface, id, &title, &body) {
1025        Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
1026        Err(err) => request_action_error_response(err),
1027    }
1028}
1029
1030#[derive(Clone, Copy)]
1031enum ApiGetHandler {
1032    Session,
1033    Events,
1034    Models,
1035    Runs,
1036    Requests,
1037    Map,
1038    RunDiff,
1039}
1040
1041const API_GET_ROUTES: &[(&str, ApiGetHandler)] = &[
1042    ("/api/session", ApiGetHandler::Session),
1043    ("/api/session/events", ApiGetHandler::Events),
1044    ("/api/models", ApiGetHandler::Models),
1045    ("/api/runs", ApiGetHandler::Runs),
1046    ("/api/requests", ApiGetHandler::Requests),
1047    ("/api/map", ApiGetHandler::Map),
1048    ("/api/runs/{id}/diff", ApiGetHandler::RunDiff),
1049];
1050
1051pub fn authenticated_api_get_routes() -> Vec<&'static str> {
1052    API_GET_ROUTES.iter().map(|(pattern, _)| *pattern).collect()
1053}
1054
1055fn match_api_get_route<'a>(pattern: &str, path: &'a str) -> Option<Option<&'a str>> {
1056    if let Some((prefix, suffix)) = pattern.split_once("{id}") {
1057        let rest = path.strip_prefix(prefix)?;
1058        let id = rest.strip_suffix(suffix)?;
1059        if !id.is_empty() && !id.contains('/') {
1060            return Some(Some(id));
1061        }
1062        None
1063    } else if pattern == path {
1064        Some(None)
1065    } else {
1066        None
1067    }
1068}
1069
1070pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
1071    if req.path == "/api/peer/messages" && req.method == "POST" {
1072        if !has_valid_message_credential(surface, req) {
1073            return json_error(403, "missing or invalid message credential");
1074        }
1075        return handle_post_peer_message(surface, req);
1076    }
1077
1078    let is_health_get = req.path == "/api/health" && req.method == "GET";
1079    if (req.path.starts_with("/api/") || req.method == "POST")
1080        && !is_health_get
1081        && !has_valid_token(surface, req)
1082    {
1083        return json_error(
1084            403,
1085            "missing or invalid surface token; open the page from the URL blyte printed",
1086        );
1087    }
1088
1089    if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
1090        if req.method != "GET" {
1091            return method_not_allowed(req);
1092        }
1093        return Response {
1094            status,
1095            content_type,
1096            body,
1097        };
1098    }
1099
1100    if req.path == "/" || req.path == "/index.html" {
1101        if req.method != "GET" {
1102            return method_not_allowed(req);
1103        }
1104        return Response::html(INDEX_HTML.as_bytes().to_vec());
1105    }
1106
1107    if req.path == "/api/health" {
1108        if req.method != "GET" {
1109            return method_not_allowed(req);
1110        }
1111        return health_response(surface);
1112    }
1113
1114    for &(pattern, handler) in API_GET_ROUTES {
1115        if let Some(id) = match_api_get_route(pattern, &req.path) {
1116            if req.method != "GET" {
1117                return method_not_allowed(req);
1118            }
1119            return match handler {
1120                ApiGetHandler::Session => session_response(surface),
1121                ApiGetHandler::Events => handle_events(surface, req),
1122                ApiGetHandler::Models => handle_models(),
1123                ApiGetHandler::Runs => handle_runs(surface, now),
1124                ApiGetHandler::Requests => handle_requests(surface),
1125                ApiGetHandler::Map => handle_map(surface),
1126                ApiGetHandler::RunDiff => handle_run_diff(surface, id.unwrap_or("")),
1127            };
1128        }
1129    }
1130
1131    match req.path.as_str() {
1132        "/api/surfaces" => {
1133            if req.method != "GET" {
1134                return method_not_allowed(req);
1135            }
1136            handle_surfaces(surface)
1137        }
1138        "/api/session/messages" => {
1139            if req.method != "POST" {
1140                return method_not_allowed(req);
1141            }
1142            handle_post_message(surface, req)
1143        }
1144        "/api/session/attachments" => {
1145            if req.method != "POST" {
1146                return method_not_allowed(req);
1147            }
1148            handle_post_attachment(surface, req)
1149        }
1150        "/api/session/model" => {
1151            if req.method != "POST" {
1152                return method_not_allowed(req);
1153            }
1154            handle_post_model(surface, req)
1155        }
1156        "/api/session/effort" => {
1157            if req.method != "POST" {
1158                return method_not_allowed(req);
1159            }
1160            handle_post_effort(surface, req)
1161        }
1162        "/api/runs/changed" => {
1163            if req.method != "POST" {
1164                return method_not_allowed(req);
1165            }
1166            handle_runs_changed(surface)
1167        }
1168        path => {
1169            if let Some(id) = path.strip_prefix("/api/session/attachments/") {
1170                if !id.is_empty() && !id.contains('/') {
1171                    if req.method != "GET" {
1172                        return method_not_allowed(req);
1173                    }
1174                    return handle_get_attachment(surface, id);
1175                }
1176            }
1177            if let Some(id) = path.strip_prefix("/api/session/approvals/") {
1178                if !id.is_empty() && !id.contains('/') {
1179                    if req.method != "POST" {
1180                        return method_not_allowed(req);
1181                    }
1182                    return handle_post_approval(surface, id, req);
1183                }
1184            }
1185            if let Some(rest) = path.strip_prefix("/api/runs/") {
1186                if let Some(id) = rest.strip_suffix("/decision") {
1187                    if !id.is_empty() && !id.contains('/') {
1188                        if req.method != "POST" {
1189                            return method_not_allowed(req);
1190                        }
1191                        return handle_run_decision(surface, id, req, now);
1192                    }
1193                }
1194                if let Some(id) = rest.strip_suffix("/undo") {
1195                    if !id.is_empty() && !id.contains('/') {
1196                        if req.method != "POST" {
1197                            return method_not_allowed(req);
1198                        }
1199                        return handle_run_undo(surface, id);
1200                    }
1201                }
1202            }
1203            if let Some(rest) = path.strip_prefix("/api/requests/") {
1204                if let Some(id) = rest.strip_suffix("/push") {
1205                    if req.method != "POST" {
1206                        return method_not_allowed(req);
1207                    }
1208                    return handle_request_push(surface, id);
1209                }
1210                if let Some(id) = rest.strip_suffix("/pull-request") {
1211                    if req.method != "POST" {
1212                        return method_not_allowed(req);
1213                    }
1214                    return handle_request_pull_request(surface, id, req);
1215                }
1216            }
1217            json_error(404, format!("not found: {}", req.path))
1218        }
1219    }
1220}
1221
1222enum GitToplevel {
1223    Repository(PathBuf),
1224    NotARepository,
1225}
1226
1227fn find_git_toplevel(dir: &Path) -> Result<GitToplevel, String> {
1228    let out = Command::new("git")
1229        .args(["rev-parse", "--show-toplevel"])
1230        .env("LC_ALL", "C")
1231        .current_dir(dir)
1232        .output()
1233        .map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
1234    if !out.status.success() {
1235        let stderr = String::from_utf8_lossy(&out.stderr);
1236        if stderr.contains("not a git repository (or any") {
1237            return Ok(GitToplevel::NotARepository);
1238        }
1239        let detail = stderr.trim();
1240        if detail.is_empty() {
1241            return Err(format!("not inside a git repository ({})", dir.display()));
1242        }
1243        return Err(format!(
1244            "not inside a git repository ({}): {detail}",
1245            dir.display()
1246        ));
1247    }
1248    let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
1249    if path_str.is_empty() {
1250        return Err(format!("not inside a git repository ({})", dir.display()));
1251    }
1252    Ok(GitToplevel::Repository(PathBuf::from(path_str)))
1253}
1254
1255pub(crate) fn is_repository(root: &Path) -> Result<bool, String> {
1256    match find_git_toplevel(root)? {
1257        GitToplevel::Repository(_) => Ok(true),
1258        GitToplevel::NotARepository => Ok(false),
1259    }
1260}
1261
1262fn resolve_denied_path(denied: &Path) -> Result<PathBuf, String> {
1263    let mut probe = denied;
1264    let mut tail = Vec::new();
1265    loop {
1266        match probe.canonicalize() {
1267            Ok(mut resolved) => {
1268                for part in tail.into_iter().rev() {
1269                    resolved.push(part);
1270                }
1271                return Ok(resolved);
1272            }
1273            Err(e)
1274                if matches!(
1275                    e.kind(),
1276                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
1277                ) =>
1278            {
1279                let Some(name) = probe.file_name() else {
1280                    return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1281                };
1282                let Some(parent) = probe.parent() else {
1283                    return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1284                };
1285                tail.push(name.to_os_string());
1286                probe = parent;
1287            }
1288            Err(e) => {
1289                return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1290            }
1291        }
1292    }
1293}
1294
1295pub fn check_linux_non_repo_root(root: &Path, home: &Path) -> Result<(), String> {
1296    let root_canon = root
1297        .canonicalize()
1298        .map_err(|e| format!("cannot canonicalize {}: {e}", root.display()))?;
1299    let home_canon = home
1300        .canonicalize()
1301        .map_err(|e| format!("cannot canonicalize home directory {}: {e}", home.display()))?;
1302    for denied in blyte_agent::sandbox::read_denied(&home_canon) {
1303        let denied_canon = resolve_denied_path(&denied)?;
1304        if denied.starts_with(&root_canon) || denied_canon.starts_with(&root_canon) {
1305            return Err(format!(
1306                "on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
1307                root_canon.display(),
1308                denied.display()
1309            ));
1310        }
1311    }
1312    if home_canon.starts_with(&root_canon) {
1313        return Err(format!(
1314            "on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
1315            root_canon.display(),
1316            home_canon.display()
1317        ));
1318    }
1319    Ok(())
1320}
1321
1322pub fn check_linux_non_repo_root_for_env(
1323    root: &Path,
1324    home: Option<&std::ffi::OsStr>,
1325) -> Result<(), String> {
1326    let home = home.filter(|h| !h.is_empty()).ok_or_else(|| {
1327        format!(
1328            "cannot check whether {} contains protected paths on Linux: HOME is not set",
1329            root.display()
1330        )
1331    })?;
1332    check_linux_non_repo_root(root, Path::new(home))
1333}
1334
1335fn resolve_main_checkout(worktree_root: &Path) -> Result<PathBuf, String> {
1336    let out = Command::new("git")
1337        .args([
1338            "rev-parse",
1339            "--path-format=absolute",
1340            "--git-dir",
1341            "--git-common-dir",
1342        ])
1343        .current_dir(worktree_root)
1344        .output()
1345        .map_err(|_| {
1346            format!(
1347                "cannot find the main checkout of {}",
1348                worktree_root.display()
1349            )
1350        })?;
1351    if !out.status.success() {
1352        return Err(format!(
1353            "cannot find the main checkout of {}",
1354            worktree_root.display()
1355        ));
1356    }
1357    let text = String::from_utf8_lossy(&out.stdout);
1358    let mut lines = text.lines();
1359    let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
1360        return Err(format!(
1361            "cannot find the main checkout of {}",
1362            worktree_root.display()
1363        ));
1364    };
1365    let git_dir_path = PathBuf::from(git_dir.trim());
1366    let common_dir_path = PathBuf::from(common_dir.trim());
1367    let git_dir_canon = git_dir_path
1368        .canonicalize()
1369        .map_err(|e| format!("cannot canonicalize {}: {e}", git_dir_path.display()))?;
1370    let common_dir_canon = common_dir_path
1371        .canonicalize()
1372        .map_err(|e| format!("cannot canonicalize {}: {e}", common_dir_path.display()))?;
1373    if git_dir_canon == common_dir_canon {
1374        return worktree_root
1375            .canonicalize()
1376            .map_err(|e| format!("cannot canonicalize {}: {e}", worktree_root.display()));
1377    }
1378    let main = crate::config::main_checkout(worktree_root).ok_or_else(|| {
1379        format!(
1380            "cannot find the main checkout of {}",
1381            worktree_root.display()
1382        )
1383    })?;
1384    main.canonicalize()
1385        .map_err(|e| format!("cannot canonicalize {}: {e}", main.display()))
1386}
1387
1388pub(crate) fn resolve_folder(folder: &Path) -> Result<PathBuf, String> {
1389    match find_git_toplevel(folder)? {
1390        GitToplevel::Repository(worktree_root) => resolve_main_checkout(&worktree_root),
1391        GitToplevel::NotARepository => folder
1392            .canonicalize()
1393            .map_err(|e| format!("cannot canonicalize {}: {e}", folder.display())),
1394    }
1395}
1396
1397fn current_branch(main_checkout: &Path) -> Result<Option<String>, String> {
1398    match find_git_toplevel(main_checkout)? {
1399        GitToplevel::NotARepository => return Ok(None),
1400        GitToplevel::Repository(_) => {}
1401    }
1402    if let Ok(out) = Command::new("git")
1403        .args(["rev-parse", "--abbrev-ref", "HEAD"])
1404        .current_dir(main_checkout)
1405        .output()
1406    {
1407        if out.status.success() {
1408            let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
1409            if !branch.is_empty() {
1410                return Ok(Some(branch));
1411            }
1412        }
1413    }
1414    if let Ok(out) = Command::new("git")
1415        .args(["symbolic-ref", "--short", "HEAD"])
1416        .current_dir(main_checkout)
1417        .output()
1418    {
1419        if out.status.success() {
1420            let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
1421            if !branch.is_empty() {
1422                return Ok(Some(branch));
1423            }
1424        }
1425    }
1426    Err(format!(
1427        "cannot read the current branch of {}",
1428        main_checkout.display()
1429    ))
1430}
1431
1432fn repo_name_for(root: &Path) -> Result<String, String> {
1433    root.file_name()
1434        .and_then(|s| s.to_str())
1435        .filter(|s| !s.is_empty())
1436        .map(String::from)
1437        .ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
1438}
1439
1440fn now_duration() -> Result<Duration, String> {
1441    SystemTime::now()
1442        .duration_since(UNIX_EPOCH)
1443        .map_err(|e| format!("system clock is before Unix epoch: {e}"))
1444}
1445
1446fn new_session_id(nanos: u128) -> String {
1447    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1448    format!("surface-{}-{nanos}-{seq}", std::process::id())
1449}
1450
1451pub fn open_browser(url: &str) {
1452    #[cfg(target_os = "macos")]
1453    let cmd = "open";
1454    #[cfg(not(target_os = "macos"))]
1455    let cmd = "xdg-open";
1456    if let Err(e) = Command::new(cmd).arg(url).spawn() {
1457        eprintln!("blyte: could not open a browser with {cmd}: {e}; open {url} yourself");
1458    }
1459}
1460
1461fn resolve_initial_model(config: &ReplConfig) -> String {
1462    if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
1463        return m.to_string();
1464    }
1465    if let Ok(m) = std::env::var("BLYTE_MODEL") {
1466        if !m.trim().is_empty() {
1467            return m;
1468        }
1469    }
1470    if let Ok(p) = blyte_provider::resolve_provider(None) {
1471        return p.model_id();
1472    }
1473    "gemini-3.8-flash-high".to_string()
1474}
1475
1476#[cfg(unix)]
1477static SIGNAL_STOP: AtomicBool = AtomicBool::new(false);
1478
1479#[cfg(unix)]
1480extern "C" fn handle_shutdown_signal(_: libc::c_int) {
1481    SIGNAL_STOP.store(true, Ordering::Relaxed);
1482}
1483
1484fn ensure_token_dir(dir: &Path) -> Result<(), String> {
1485    #[cfg(unix)]
1486    {
1487        use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
1488        if let Some(parent) = dir.parent() {
1489            std::fs::create_dir_all(parent)
1490                .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
1491        }
1492        let mut builder = std::fs::DirBuilder::new();
1493        builder.mode(0o700);
1494        match builder.create(dir) {
1495            Ok(()) => {}
1496            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1497                std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
1498                    .map_err(|e| format!("cannot set permissions on {}: {e}", dir.display()))?;
1499            }
1500            Err(e) => return Err(format!("cannot create {}: {e}", dir.display())),
1501        }
1502        Ok(())
1503    }
1504    #[cfg(not(unix))]
1505    {
1506        std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))
1507    }
1508}
1509
1510fn write_token_file(token_file_path: &Path, token: &str) -> Result<(), String> {
1511    let token_dir = token_file_path
1512        .parent()
1513        .ok_or_else(|| format!("invalid token path {}", token_file_path.display()))?;
1514    ensure_token_dir(token_dir)?;
1515    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1516    let tmp_path = token_dir.join(format!(".surface.token.{}.{seq}.tmp", std::process::id()));
1517    let mut opts = std::fs::OpenOptions::new();
1518    opts.write(true).create_new(true);
1519    #[cfg(unix)]
1520    {
1521        opts.mode(0o600);
1522    }
1523    let mut file = opts
1524        .open(&tmp_path)
1525        .map_err(|e| format!("cannot create {}: {e}", token_file_path.display()))?;
1526    if let Err(e) = writeln!(file, "{token}") {
1527        let _ = std::fs::remove_file(&tmp_path);
1528        return Err(format!("cannot write {}: {e}", token_file_path.display()));
1529    }
1530    drop(file);
1531    if let Err(e) = std::fs::rename(&tmp_path, token_file_path) {
1532        let _ = std::fs::remove_file(&tmp_path);
1533        return Err(format!("cannot write {}: {e}", token_file_path.display()));
1534    }
1535    Ok(())
1536}
1537
1538struct TokenFileGuard {
1539    path: PathBuf,
1540}
1541
1542impl Drop for TokenFileGuard {
1543    fn drop(&mut self) {
1544        let _ = std::fs::remove_file(&self.path);
1545    }
1546}
1547
1548struct RegistryEntryGuard {
1549    dir: PathBuf,
1550    id: String,
1551}
1552
1553impl Drop for RegistryEntryGuard {
1554    fn drop(&mut self) {
1555        let _ = crate::surface_registry::remove_entry(&self.dir, &self.id);
1556    }
1557}
1558
1559struct PrivateTmpDirGuard {
1560    path: PathBuf,
1561}
1562
1563impl Drop for PrivateTmpDirGuard {
1564    fn drop(&mut self) {
1565        let _ = std::fs::remove_dir_all(&self.path);
1566    }
1567}
1568
1569struct PublishToolGuard;
1570
1571impl PublishToolGuard {
1572    fn install(surface: Arc<Surface>) -> Self {
1573        blyte_agent::tools::set_publish_tool(Some(Arc::new(
1574            crate::requests::SurfacePublishTool::new(surface),
1575        )));
1576        Self
1577    }
1578}
1579
1580impl Drop for PublishToolGuard {
1581    fn drop(&mut self) {
1582        blyte_agent::tools::set_publish_tool(None);
1583    }
1584}
1585
1586pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
1587    #[cfg(unix)]
1588    {
1589        SIGNAL_STOP.store(false, Ordering::Relaxed);
1590        unsafe {
1591            libc::signal(
1592                libc::SIGINT,
1593                handle_shutdown_signal as *const () as libc::sighandler_t,
1594            );
1595            libc::signal(
1596                libc::SIGTERM,
1597                handle_shutdown_signal as *const () as libc::sighandler_t,
1598            );
1599        }
1600    }
1601    run_inner(
1602        args,
1603        config,
1604        &mut std::io::stdout(),
1605        &mut std::io::stderr(),
1606        &mut open_browser,
1607        || {
1608            #[cfg(unix)]
1609            {
1610                SIGNAL_STOP.load(Ordering::Relaxed)
1611            }
1612            #[cfg(not(unix))]
1613            {
1614                false
1615            }
1616        },
1617        None,
1618    )
1619}
1620
1621pub fn run_with_io(
1622    args: &SurfaceArgs,
1623    config: ReplConfig,
1624    out: &mut dyn Write,
1625    err: &mut dyn Write,
1626) -> i32 {
1627    run_inner(args, config, out, err, &mut open_browser, || false, None)
1628}
1629
1630pub fn run_with_hooks(
1631    args: &SurfaceArgs,
1632    config: ReplConfig,
1633    out: &mut dyn Write,
1634    err: &mut dyn Write,
1635    opener: &mut dyn FnMut(&str),
1636    stop: Arc<AtomicBool>,
1637) -> i32 {
1638    run_inner(
1639        args,
1640        config,
1641        out,
1642        err,
1643        opener,
1644        move || stop.load(Ordering::Relaxed),
1645        None,
1646    )
1647}
1648
1649pub type RunnerFactory = Box<
1650    dyn FnOnce(
1651        &ReplConfig,
1652        Arc<dyn blyte_agent::approval::Approver>,
1653    ) -> Result<(Box<dyn PromptRunner>, Option<PathBuf>), String>,
1654>;
1655
1656pub fn run_with_runner(
1657    args: &SurfaceArgs,
1658    config: ReplConfig,
1659    out: &mut dyn Write,
1660    err: &mut dyn Write,
1661    opener: &mut dyn FnMut(&str),
1662    stop: Arc<AtomicBool>,
1663    runner: Box<dyn PromptRunner>,
1664) -> i32 {
1665    run_inner(
1666        args,
1667        config,
1668        out,
1669        err,
1670        opener,
1671        move || stop.load(Ordering::Relaxed),
1672        Some(Box::new(|_, _| Ok((runner, None)))),
1673    )
1674}
1675
1676pub fn run_with_runner_factory(
1677    args: &SurfaceArgs,
1678    config: ReplConfig,
1679    out: &mut dyn Write,
1680    err: &mut dyn Write,
1681    opener: &mut dyn FnMut(&str),
1682    stop: Arc<AtomicBool>,
1683    factory: RunnerFactory,
1684) -> i32 {
1685    run_inner(
1686        args,
1687        config,
1688        out,
1689        err,
1690        opener,
1691        move || stop.load(Ordering::Relaxed),
1692        Some(factory),
1693    )
1694}
1695
1696struct ReconcileTimerGuard {
1697    stop: Arc<AtomicBool>,
1698    handle: Option<std::thread::JoinHandle<()>>,
1699}
1700
1701impl Drop for ReconcileTimerGuard {
1702    fn drop(&mut self) {
1703        self.stop.store(true, Ordering::Release);
1704        if let Some(handle) = self.handle.take() {
1705            let _ = handle.join();
1706        }
1707    }
1708}
1709
1710fn spawn_reconcile_timer(surface: Arc<Surface>) -> ReconcileTimerGuard {
1711    let stop = Arc::new(AtomicBool::new(false));
1712    let thread_stop = Arc::clone(&stop);
1713    let handle = std::thread::spawn(move || {
1714        let mut after = surface.session.info().last_seq;
1715        let mut next_tick = Instant::now();
1716        let mut seen_errors: HashSet<String> = HashSet::new();
1717        while !thread_stop.load(Ordering::Acquire) {
1718            let wait = if surface.reconcile_requested.load(Ordering::Acquire) {
1719                Duration::ZERO
1720            } else {
1721                next_tick
1722                    .saturating_duration_since(Instant::now())
1723                    .min(RECONCILE_POLL_WAIT)
1724            };
1725            let entries = surface.session.entries_after(after, wait);
1726            let mut went_idle = false;
1727            for entry in entries {
1728                after = entry.seq;
1729                if matches!(entry.body, EntryBody::Idle { .. }) {
1730                    went_idle = true;
1731                }
1732            }
1733            if thread_stop.load(Ordering::Acquire) {
1734                break;
1735            }
1736            let requested = surface.reconcile_requested.swap(false, Ordering::AcqRel);
1737            if went_idle || requested || Instant::now() >= next_tick {
1738                match now_duration().and_then(|d| reconcile_runs(&surface, d.as_secs())) {
1739                    Ok((_, errors)) => {
1740                        for msg in errors {
1741                            if seen_errors.insert(msg.clone()) {
1742                                surface.session.record_error(&msg);
1743                                eprintln!("blyte: {msg}");
1744                            }
1745                        }
1746                    }
1747                    Err(e) => {
1748                        if seen_errors.insert(e.clone()) {
1749                            eprintln!("blyte: {e}");
1750                        }
1751                    }
1752                }
1753                next_tick = Instant::now() + RECONCILE_SAFETY_NET_INTERVAL;
1754            }
1755        }
1756    });
1757    ReconcileTimerGuard {
1758        stop,
1759        handle: Some(handle),
1760    }
1761}
1762
1763fn run_inner<S>(
1764    args: &SurfaceArgs,
1765    mut config: ReplConfig,
1766    out: &mut dyn Write,
1767    err: &mut dyn Write,
1768    opener: &mut dyn FnMut(&str),
1769    should_stop: S,
1770    custom_runner: Option<RunnerFactory>,
1771) -> i32
1772where
1773    S: Fn() -> bool,
1774{
1775    let (main_checkout, is_repo) = match find_git_toplevel(&config.repo_root) {
1776        Ok(GitToplevel::Repository(worktree_root)) => {
1777            let main = match resolve_main_checkout(&worktree_root) {
1778                Ok(m) => m,
1779                Err(e) => {
1780                    let _ = writeln!(err, "blyte: {e}");
1781                    return 1;
1782                }
1783            };
1784            let same_checkout = match (worktree_root.canonicalize(), main.canonicalize()) {
1785                (Ok(a), Ok(b)) => a == b,
1786                _ => worktree_root == main,
1787            };
1788            if !same_checkout {
1789                let _ = writeln!(
1790                    err,
1791                    "blyte: started in a linked worktree ({}); this surface works in the main checkout {}",
1792                    worktree_root.display(),
1793                    main.display()
1794                );
1795                let _ = err.flush();
1796            }
1797            (main, true)
1798        }
1799        Ok(GitToplevel::NotARepository) => {
1800            let canonical = match config.repo_root.canonicalize() {
1801                Ok(c) => c,
1802                Err(e) => {
1803                    let _ = writeln!(
1804                        err,
1805                        "blyte: cannot canonicalize {}: {e}",
1806                        config.repo_root.display()
1807                    );
1808                    return 1;
1809                }
1810            };
1811            (canonical, false)
1812        }
1813        Err(e) => {
1814            let _ = writeln!(err, "blyte: {e}");
1815            return 1;
1816        }
1817    };
1818
1819    let repo = match repo_name_for(&main_checkout) {
1820        Ok(r) => r,
1821        Err(e) => {
1822            let _ = writeln!(err, "blyte: {e}");
1823            return 1;
1824        }
1825    };
1826
1827    #[cfg(target_os = "linux")]
1828    if !is_repo {
1829        if let Err(e) =
1830            check_linux_non_repo_root_for_env(&main_checkout, std::env::var_os("HOME").as_deref())
1831        {
1832            let _ = writeln!(err, "blyte: {e}");
1833            return 1;
1834        }
1835    }
1836
1837    let state_dir = match crate::surface_registry::state_dir() {
1838        Ok(d) => d,
1839        Err(e) => {
1840            let _ = writeln!(err, "blyte: {e}");
1841            return 1;
1842        }
1843    };
1844    let registry_dir = state_dir.join("surfaces");
1845
1846    let all_records =
1847        match crate::surface_dir::list_records_for_root(&main_checkout, Some(&state_dir)) {
1848            Ok(r) => r,
1849            Err(e) => {
1850                let _ = writeln!(err, "blyte: {e}");
1851                return 1;
1852            }
1853        };
1854    let mut running = Vec::new();
1855    let mut stopped = Vec::new();
1856    for located in all_records {
1857        if crate::surface_dir::is_running(&located.record) {
1858            running.push(located);
1859        } else {
1860            stopped.push(located);
1861        }
1862    }
1863
1864    let live_registry = match crate::surface_registry::live_entries(&registry_dir) {
1865        Ok(entries) => entries,
1866        Err(e) => {
1867            let _ = writeln!(err, "blyte: {e}");
1868            return 1;
1869        }
1870    };
1871    let mut running_names: Vec<String> = running.iter().map(|r| r.record.name.clone()).collect();
1872    for entry in &live_registry {
1873        if !running_names.iter().any(|n| n == &entry.name) {
1874            running_names.push(entry.name.clone());
1875        }
1876    }
1877
1878    let (surface_id, surface_name, surface_record_dir) = if let Some(ref target) = args.resume {
1879        if let Some(located) = running
1880            .iter()
1881            .find(|r| r.record.id == *target || r.record.name == *target)
1882        {
1883            let _ = writeln!(
1884                err,
1885                "blyte: surface {target} is already running (port {})",
1886                located.record.port
1887            );
1888            return 1;
1889        }
1890        let stopped_matches: Vec<&crate::surface_dir::LocatedRecord> = stopped
1891            .iter()
1892            .filter(|r| r.record.id == *target || r.record.name == *target)
1893            .collect();
1894        if stopped_matches.is_empty() {
1895            let _ = writeln!(
1896                err,
1897                "blyte: no stopped surface named {target} in {}",
1898                main_checkout.display()
1899            );
1900            return 1;
1901        }
1902        if stopped_matches.len() > 1 {
1903            let ids: Vec<&str> = stopped_matches
1904                .iter()
1905                .map(|r| r.record.id.as_str())
1906                .collect();
1907            let _ = writeln!(
1908                err,
1909                "blyte: more than one stopped surface is named {target}; resume by id: {}",
1910                ids.join(", ")
1911            );
1912            return 1;
1913        }
1914        let located = stopped_matches[0];
1915        if running_names.iter().any(|n| n == &located.record.name) {
1916            let _ = writeln!(
1917                err,
1918                "blyte: a running surface is already named {}; stop it or resume by another name",
1919                located.record.name
1920            );
1921            return 1;
1922        }
1923        (
1924            located.record.id.clone(),
1925            located.record.name.clone(),
1926            located.dir.clone(),
1927        )
1928    } else {
1929        let id = match crate::surface_dir::new_surface_id() {
1930            Ok(id) => id,
1931            Err(e) => {
1932                let _ = writeln!(err, "blyte: {e}");
1933                return 1;
1934            }
1935        };
1936        let name = match crate::surface_dir::pick_name(&repo, args.name.as_deref(), &running_names)
1937        {
1938            Ok(name) => name,
1939            Err(e) => {
1940                let _ = writeln!(err, "blyte: {e}");
1941                return 1;
1942            }
1943        };
1944        let record_dir = if is_repo {
1945            crate::surface_dir::surface_dir(&main_checkout, &id)
1946        } else {
1947            let store = match crate::surface_dir::folder_store(&state_dir, &main_checkout) {
1948                Ok(store) => store,
1949                Err(e) => {
1950                    let _ = writeln!(err, "blyte: {e}");
1951                    return 1;
1952                }
1953            };
1954            store.join("surfaces").join(&id)
1955        };
1956        (id, name, record_dir)
1957    };
1958
1959    let branch = match current_branch(&main_checkout) {
1960        Ok(b) => b,
1961        Err(e) => {
1962            let _ = writeln!(err, "blyte: {e}");
1963            return 1;
1964        }
1965    };
1966
1967    if !config.converse {
1968        config.converse = true;
1969        if config.max_turns == 25 || config.max_turns == 60 {
1970            config.max_turns = 1000;
1971        }
1972        if config.fold_budget.is_none() {
1973            config.fold_budget = Some(100_000);
1974        }
1975    }
1976    config.repo_root = main_checkout.clone();
1977
1978    let is_resume = args.resume.is_some();
1979    let model = resolve_initial_model(&config);
1980    let conversation_path = match crate::conversation_store::conversation_path_for_id(&surface_id) {
1981        Ok(p) => p,
1982        Err(e) => {
1983            let _ = writeln!(err, "blyte: {e}");
1984            let _ = err.flush();
1985            return 1;
1986        }
1987    };
1988    let (mut conversation_store, mut loaded_conversation) = if is_resume {
1989        match crate::conversation_store::ConversationStore::load(conversation_path) {
1990            Ok(pair) => pair,
1991            Err(e) => {
1992                let _ = writeln!(err, "blyte: {e}");
1993                let _ = err.flush();
1994                return 1;
1995            }
1996        }
1997    } else {
1998        match crate::conversation_store::ConversationStore::new_for_fresh(conversation_path) {
1999            Ok(store) => (store, None),
2000            Err(e) => {
2001                let _ = writeln!(err, "blyte: {e}");
2002                let _ = err.flush();
2003                return 1;
2004            }
2005        }
2006    };
2007    let (resume_memory, needs_digest_rewrite) = match loaded_conversation.as_mut() {
2008        Some(loaded) if !loaded.messages.is_empty() => {
2009            if crate::conversation_store::digest_for_provider_in_memory(loaded, &model) {
2010                (crate::session::ResumeMemoryState::Summarized, true)
2011            } else {
2012                (crate::session::ResumeMemoryState::Loaded, false)
2013            }
2014        }
2015        _ => (crate::session::ResumeMemoryState::NotLoaded, false),
2016    };
2017
2018    let started_dur = match now_duration() {
2019        Ok(d) => d,
2020        Err(e) => {
2021            let _ = writeln!(err, "blyte: {e}");
2022            return 1;
2023        }
2024    };
2025    let started_at = started_dur.as_secs();
2026    let session_id = new_session_id(started_dur.as_nanos());
2027    if std::env::var("BLYTE_SESSION")
2028        .map(|v| v.is_empty())
2029        .unwrap_or(true)
2030    {
2031        std::env::set_var("BLYTE_SESSION", &session_id);
2032    }
2033
2034    let token = match generate_token() {
2035        Ok(t) => t,
2036        Err(e) => {
2037            let _ = writeln!(err, "blyte: {e}");
2038            return 1;
2039        }
2040    };
2041    let message_credential = match generate_token() {
2042        Ok(t) => t,
2043        Err(e) => {
2044            let _ = writeln!(err, "blyte: {e}");
2045            return 1;
2046        }
2047    };
2048
2049    let bind_addr = format!("127.0.0.1:{}", args.port);
2050    let listener = match TcpListener::bind(&bind_addr) {
2051        Ok(l) => l,
2052        Err(e) => {
2053            let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
2054            return 1;
2055        }
2056    };
2057    let actual_port = match listener.local_addr() {
2058        Ok(a) => a.port(),
2059        Err(e) => {
2060            let _ = writeln!(err, "blyte: failed to read listener address: {e}");
2061            return 1;
2062        }
2063    };
2064
2065    let token_file_path = match blyte_agent::sandbox::surface_token_path_for_id(&surface_id) {
2066        Ok(p) => p,
2067        Err(e) => {
2068            let _ = writeln!(err, "blyte: {e}");
2069            return 1;
2070        }
2071    };
2072    if let Err(e) = write_token_file(&token_file_path, &token) {
2073        let _ = writeln!(err, "blyte: {e}");
2074        return 1;
2075    }
2076    let _token_guard = TokenFileGuard {
2077        path: token_file_path,
2078    };
2079
2080    let message_file_path = match blyte_agent::sandbox::surface_message_path_for_id(&surface_id) {
2081        Ok(p) => p,
2082        Err(e) => {
2083            let _ = writeln!(err, "blyte: {e}");
2084            return 1;
2085        }
2086    };
2087    if let Err(e) = write_token_file(&message_file_path, &message_credential) {
2088        let _ = writeln!(err, "blyte: {e}");
2089        return 1;
2090    }
2091    let _message_guard = TokenFileGuard {
2092        path: message_file_path,
2093    };
2094
2095    let mut starting_dir_guard = if is_resume {
2096        StartingDirGuard { dir: None }
2097    } else {
2098        if let Err(e) = crate::surface_dir::prepare_starting_dir(&surface_record_dir) {
2099            let _ = writeln!(err, "blyte: {e}");
2100            return 1;
2101        }
2102        StartingDirGuard {
2103            dir: Some(surface_record_dir.clone()),
2104        }
2105    };
2106    let attachments_dir = match prepare_attachments_dir(&surface_record_dir) {
2107        Ok(p) => p,
2108        Err(e) => {
2109            let _ = writeln!(err, "blyte: {e}");
2110            return 1;
2111        }
2112    };
2113    let mut read_roots = blyte_agent::tools::read_roots();
2114    if !read_roots.iter().any(|p| p == &attachments_dir) {
2115        read_roots.push(attachments_dir.clone());
2116        blyte_agent::tools::set_read_roots(read_roots);
2117    }
2118    if !config.allow_read.iter().any(|p| p == &attachments_dir) {
2119        config.allow_read.push(attachments_dir);
2120    }
2121    blyte_agent::tools::set_peer_tools(Some(Arc::new(crate::tell::SurfacePeerTools {
2122        registry_dir: registry_dir.clone(),
2123        surface_id: surface_id.clone(),
2124        surface_name: surface_name.clone(),
2125        repository: repo.clone(),
2126    })));
2127    let entries_log_path = surface_record_dir.join("entries.jsonl");
2128    blyte_agent::tools::set_blyte_surface(Some(surface_id.clone()));
2129    let mut _private_tmp_guard: Option<PrivateTmpDirGuard> = None;
2130    let session = match Session::try_start_with_log_and_resume_io(
2131        model,
2132        Some(entries_log_path),
2133        resume_memory,
2134        err,
2135        |approver| match custom_runner {
2136            Some(factory) => {
2137                let (runner, tmpdir) = factory(&config, approver)?;
2138                _private_tmp_guard = tmpdir.map(|path| PrivateTmpDirGuard { path });
2139                if needs_digest_rewrite {
2140                    if let Some(ref loaded) = loaded_conversation {
2141                        conversation_store.rewrite(
2142                            loaded.model.as_deref(),
2143                            loaded.goal.as_deref(),
2144                            &loaded.messages,
2145                        )?;
2146                    }
2147                }
2148                Ok(runner)
2149            }
2150            None => {
2151                let rewrite_payload = if needs_digest_rewrite {
2152                    loaded_conversation.clone()
2153                } else {
2154                    None
2155                };
2156                let mut runner = AgentRunner::try_new_with_conversation(
2157                    &config,
2158                    approver,
2159                    None,
2160                    loaded_conversation,
2161                )?;
2162                _private_tmp_guard = runner.private_tmpdir().map(|path| PrivateTmpDirGuard {
2163                    path: path.to_path_buf(),
2164                });
2165                if let Some(ref loaded) = rewrite_payload {
2166                    conversation_store.rewrite(
2167                        loaded.model.as_deref(),
2168                        loaded.goal.as_deref(),
2169                        &loaded.messages,
2170                    )?;
2171                }
2172                runner.set_conversation_store(conversation_store);
2173                Ok(Box::new(runner) as Box<dyn crate::session::PromptRunner>)
2174            }
2175        },
2176    ) {
2177        Ok(s) => s,
2178        Err(e) => {
2179            let _ = writeln!(err, "blyte: {e}");
2180            let _ = err.flush();
2181            return 1;
2182        }
2183    };
2184    let record = SurfaceRecord {
2185        id: surface_id.clone(),
2186        name: surface_name.clone(),
2187        pid: std::process::id(),
2188        port: actual_port,
2189        session_id: session_id.clone(),
2190        started_at,
2191    };
2192    if let Err(e) = crate::surface_dir::write_record_in(&surface_record_dir, &record) {
2193        let _ = writeln!(err, "blyte: {e}");
2194        return 1;
2195    }
2196    starting_dir_guard.disarm();
2197    let registry_entry = crate::surface_registry::RegistryEntry {
2198        id: surface_id.clone(),
2199        name: surface_name.clone(),
2200        root: main_checkout.clone(),
2201        branch,
2202        pid: std::process::id(),
2203        port: actual_port,
2204        started_at,
2205        doing: "idle".to_string(),
2206    };
2207    if let Err(e) = crate::surface_registry::write_entry(&registry_dir, &registry_entry) {
2208        let _ = writeln!(err, "blyte: {e}");
2209        return 1;
2210    }
2211    let _registry_guard = RegistryEntryGuard {
2212        dir: registry_dir.clone(),
2213        id: surface_id.clone(),
2214    };
2215    let hook_dir = registry_dir.clone();
2216    let hook_entry = registry_entry.clone();
2217    session.set_activity_hook(Box::new(move |prompt| {
2218        let doing = match prompt {
2219            Some(text) => {
2220                let line = crate::surface_registry::first_line(text);
2221                if line.is_empty() {
2222                    "working".to_string()
2223                } else {
2224                    line
2225                }
2226            }
2227            None => "idle".to_string(),
2228        };
2229        // The whole entry is written, not only the changed field: another process removes an
2230        // entry whose surface did not answer its health check in time, and this puts it back.
2231        let branch = match current_branch(&hook_entry.root) {
2232            Ok(b) => b,
2233            Err(e) => {
2234                eprintln!("blyte: {e}");
2235                return;
2236            }
2237        };
2238        let entry = crate::surface_registry::RegistryEntry {
2239            branch,
2240            doing,
2241            ..hook_entry.clone()
2242        };
2243        if let Err(e) = crate::surface_registry::write_entry(&hook_dir, &entry) {
2244            eprintln!("blyte: {e}");
2245        }
2246    }));
2247
2248    if !is_repo {
2249        let _ = writeln!(
2250            err,
2251            "blyte: {} is not a git repository: runs edit this folder in place; combining and publishing are off",
2252            main_checkout.display()
2253        );
2254        let _ = err.flush();
2255    }
2256
2257    let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
2258    let _ = writeln!(out, "blyte: surface {surface_name} at {url}");
2259    let _ = out.flush();
2260    if !args.no_open {
2261        opener(&url);
2262    }
2263
2264    let stop_surface_name = surface_name.clone();
2265
2266    let surface = Arc::new(Surface {
2267        surface_id,
2268        surface_name,
2269        root: main_checkout,
2270        repo,
2271        session,
2272        session_id,
2273        started_at,
2274        days: args.days,
2275        token,
2276        message_credential,
2277        requests: Arc::new(RequestsState::new()),
2278        publisher: Arc::new(RealPublisher),
2279        reconcile_lock: Mutex::new(()),
2280        reconcile_requested: AtomicBool::new(false),
2281    });
2282
2283    let timer_guard = spawn_reconcile_timer(Arc::clone(&surface));
2284    let _publish_tool_guard = PublishToolGuard::install(Arc::clone(&surface));
2285
2286    let serve_result =
2287        crate::http::serve_until(listener, should_stop, move |req| match now_duration() {
2288            Ok(d) => route(&surface, req, d.as_secs()),
2289            Err(e) => json_error(500, e),
2290        });
2291
2292    drop(_publish_tool_guard);
2293    drop(timer_guard);
2294
2295    match serve_result {
2296        Ok(()) => {
2297            let _ = writeln!(
2298                out,
2299                "blyte: stopped surface {stop_surface_name}; resume with: blyte --resume {stop_surface_name}"
2300            );
2301            let _ = out.flush();
2302            0
2303        }
2304        Err(e) => {
2305            let _ = writeln!(err, "blyte: server error: {e}");
2306            1
2307        }
2308    }
2309}
2310
2311fn canonicalize_attachments_dir(attachments_dir: &Path) -> Result<PathBuf, String> {
2312    std::fs::canonicalize(attachments_dir).map_err(|e| {
2313        format!(
2314            "failed to canonicalize attachments directory {}: {e}",
2315            attachments_dir.display()
2316        )
2317    })
2318}
2319
2320fn prepare_attachments_dir(surface_record_dir: &Path) -> Result<PathBuf, String> {
2321    let attachments_dir = crate::attachments::attachments_dir(surface_record_dir);
2322    std::fs::create_dir_all(&attachments_dir)
2323        .map_err(|e| format!("failed to create {}: {e}", attachments_dir.display()))?;
2324    canonicalize_attachments_dir(&attachments_dir)
2325}
2326
2327struct StartingDirGuard {
2328    dir: Option<PathBuf>,
2329}
2330
2331impl StartingDirGuard {
2332    fn disarm(&mut self) {
2333        self.dir = None;
2334    }
2335}
2336
2337impl Drop for StartingDirGuard {
2338    fn drop(&mut self) {
2339        if let Some(ref dir) = self.dir {
2340            crate::surface_dir::cleanup_starting_dir(dir);
2341        }
2342    }
2343}
2344
2345#[cfg(test)]
2346mod tests {
2347    use super::*;
2348
2349    #[test]
2350    fn canonicalize_attachments_dir_errors_when_missing() {
2351        let dir = tempfile::tempdir().unwrap();
2352        let missing = dir.path().join("does-not-exist").join("attachments");
2353        let err = canonicalize_attachments_dir(&missing).unwrap_err();
2354        assert!(
2355            err.contains(&missing.display().to_string()),
2356            "expected error to name missing path, got: {err}"
2357        );
2358        assert!(err.contains("canonicalize"), "unexpected error: {err}");
2359    }
2360
2361    #[cfg(unix)]
2362    #[test]
2363    fn canonicalize_attachments_dir_errors_on_dangling_symlink() {
2364        let dir = tempfile::tempdir().unwrap();
2365        let dangling = dir.path().join("attachments");
2366        std::os::unix::fs::symlink(dir.path().join("missing-target"), &dangling).unwrap();
2367        let err = canonicalize_attachments_dir(&dangling).unwrap_err();
2368        assert!(
2369            err.contains(&dangling.display().to_string()),
2370            "expected error to name symlink path, got: {err}"
2371        );
2372        assert!(err.contains("canonicalize"), "unexpected error: {err}");
2373    }
2374
2375    #[test]
2376    fn prepare_attachments_dir_errors_when_attachments_path_is_a_file() {
2377        let dir = tempfile::tempdir().unwrap();
2378        let blocker = crate::attachments::attachments_dir(dir.path());
2379        std::fs::write(&blocker, b"not a dir").unwrap();
2380        let err = prepare_attachments_dir(dir.path()).unwrap_err();
2381        assert!(
2382            err.contains(&blocker.display().to_string()),
2383            "expected error to name path, got: {err}"
2384        );
2385    }
2386}