Skip to main content

blyte_cli/
serve.rs

1use serde::Serialize;
2use std::collections::{BTreeSet, HashSet, VecDeque};
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::open_window::OpenIn;
16use crate::queue_actions::{Action, Hold};
17use crate::repl::ReplConfig;
18use crate::requests::{Publisher, RealPublisher, RequestActionError, RequestsState};
19use crate::session::{
20    AgentRunner, AnswerError, ApprovalAnswer, Attachment, EntryBody, PeerDelivery, PromptRunner,
21    Session,
22};
23use crate::surface_dir::SurfaceRecord;
24
25pub const TOKEN_HEADER: &str = "X-Blyte-Token";
26pub const MESSAGE_HEADER: &str = "X-Blyte-Message-Credential";
27pub const RECONCILE_SAFETY_NET_INTERVAL: Duration = Duration::from_secs(30);
28pub const OPEN_CODE_TTL_SECS: u64 = 60;
29pub const MAX_OPEN_CODES: usize = 16;
30
31const INDEX_HTML: &str = include_str!("../assets/surface/index.html");
32const USAGE_HTML: &str = include_str!("../assets/usage/index.html");
33const MAX_WAIT_MS: u64 = 25_000;
34const RECONCILE_POLL_WAIT: Duration = Duration::from_millis(50);
35const TOKEN_BYTES: usize = 32;
36const MAX_PEER_TEXT_BYTES: usize = 16_384;
37const MAX_PEER_REPO_CHARS: usize = 200;
38
39static SESSION_COUNTER: AtomicU64 = AtomicU64::new(1);
40
41struct OpenCodeEntry {
42    code: String,
43    created_at: u64,
44}
45
46#[derive(Default)]
47pub struct OpenCodes {
48    entries: Mutex<VecDeque<OpenCodeEntry>>,
49}
50
51impl OpenCodes {
52    pub fn new() -> Self {
53        Self {
54            entries: Mutex::new(VecDeque::new()),
55        }
56    }
57
58    pub fn issue(&self, now: u64) -> Result<String, String> {
59        let code = generate_token()?;
60        let mut entries = self
61            .entries
62            .lock()
63            .map_err(|e| format!("open codes lock poisoned: {e}"))?;
64        while entries.len() >= MAX_OPEN_CODES {
65            entries.pop_front();
66        }
67        entries.push_back(OpenCodeEntry {
68            code: code.clone(),
69            created_at: now,
70        });
71        Ok(code)
72    }
73
74    pub fn redeem(&self, provided: &str, now: u64) -> Result<bool, String> {
75        if provided.is_empty() {
76            return Ok(false);
77        }
78        let mut entries = self
79            .entries
80            .lock()
81            .map_err(|e| format!("open codes lock poisoned: {e}"))?;
82        let mut matched_idx = None;
83        for (idx, entry) in entries.iter().enumerate() {
84            if constant_time_eq(provided.as_bytes(), entry.code.as_bytes()) {
85                matched_idx = Some(idx);
86            }
87        }
88        let Some(idx) = matched_idx else {
89            entries.retain(|e| now.saturating_sub(e.created_at) <= OPEN_CODE_TTL_SECS);
90            return Ok(false);
91        };
92        let entry = entries.remove(idx).unwrap();
93        entries.retain(|e| now.saturating_sub(e.created_at) <= OPEN_CODE_TTL_SECS);
94        Ok(now.saturating_sub(entry.created_at) <= OPEN_CODE_TTL_SECS)
95    }
96}
97
98pub struct Surface {
99    pub surface_id: String,
100    pub surface_name: String,
101    pub root: PathBuf,
102    pub repo: String,
103    pub session: Session,
104    pub session_id: String,
105    pub started_at: u64,
106    pub runtime: crate::surface_version::SurfaceRuntimeInfo,
107    pub days: u64,
108    pub token: String,
109    pub message_credential: String,
110    pub open_codes: OpenCodes,
111    pub requests: Arc<RequestsState>,
112    pub publisher: Arc<dyn Publisher>,
113    pub reconcile_lock: Mutex<()>,
114    pub reconcile_requested: AtomicBool,
115}
116
117pub fn generate_token() -> Result<String, String> {
118    let mut bytes = [0u8; TOKEN_BYTES];
119    let mut file = std::fs::File::open("/dev/urandom")
120        .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
121    file.read_exact(&mut bytes)
122        .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
123    const HEX: &[u8; 16] = b"0123456789abcdef";
124    let mut out = String::with_capacity(bytes.len() * 2);
125    for byte in bytes {
126        out.push(HEX[(byte >> 4) as usize] as char);
127        out.push(HEX[(byte & 0x0f) as usize] as char);
128    }
129    Ok(out)
130}
131
132pub fn constant_time_eq(provided: &[u8], expected: &[u8]) -> bool {
133    let mut diff = provided.len() ^ expected.len();
134    for (i, &exp) in expected.iter().enumerate() {
135        let prov = provided.get(i).copied().unwrap_or(0);
136        diff |= usize::from(prov ^ exp);
137    }
138    std::hint::black_box(diff) == 0
139}
140
141fn has_valid_token(surface: &Surface, req: &Request) -> bool {
142    if surface.token.is_empty() {
143        return false;
144    }
145    let mut values = req.header_values(TOKEN_HEADER);
146    let Some(provided) = values.next() else {
147        return false;
148    };
149    if values.next().is_some() {
150        return false;
151    }
152    constant_time_eq(provided.as_bytes(), surface.token.as_bytes())
153}
154
155fn has_valid_message_credential(surface: &Surface, req: &Request) -> bool {
156    if surface.message_credential.is_empty() {
157        return false;
158    }
159    let mut values = req.header_values(MESSAGE_HEADER);
160    let Some(provided) = values.next() else {
161        return false;
162    };
163    if values.next().is_some() {
164        return false;
165    }
166    constant_time_eq(provided.as_bytes(), surface.message_credential.as_bytes())
167}
168
169#[derive(Serialize)]
170struct RunWithHold<'a> {
171    #[serde(flatten)]
172    run: &'a crate::replay::Run,
173    hold: Option<Hold>,
174    combined: bool,
175    #[serde(skip_serializing_if = "std::ops::Not::not")]
176    in_place: bool,
177    #[serde(skip_serializing_if = "std::ops::Not::not")]
178    undone: bool,
179}
180
181#[derive(Serialize)]
182struct LiveRunsResponse<'a> {
183    generated_at: u64,
184    repo: &'a str,
185    running: &'a [crate::live_runs::RunningRun],
186    runs: Vec<RunWithHold<'a>>,
187    skipped: &'a [crate::replay::Skipped],
188}
189
190fn json_error(status: u16, msg: impl Into<String>) -> Response {
191    Response::json(status, &serde_json::json!({ "error": msg.into() }))
192}
193
194fn method_not_allowed(req: &Request) -> Response {
195    json_error(
196        405,
197        format!("method {} not allowed for {}", req.method, req.path),
198    )
199}
200
201fn is_valid_run_id(id: &str) -> bool {
202    !id.is_empty()
203        && id != "."
204        && id != ".."
205        && id
206            .bytes()
207            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
208}
209
210fn parse_json_object(body: &[u8]) -> Result<serde_json::Map<String, serde_json::Value>, Response> {
211    let val: serde_json::Value = serde_json::from_slice(body)
212        .map_err(|e| json_error(400, format!("invalid JSON body: {e}")))?;
213    val.as_object()
214        .cloned()
215        .ok_or_else(|| json_error(400, "request body must be a JSON object"))
216}
217
218fn handle_surfaces(surface: &Surface) -> Response {
219    let state_dir = match crate::surface_registry::state_dir() {
220        Ok(dir) => dir,
221        Err(e) => return json_error(500, e),
222    };
223    let registry_dir = state_dir.join("surfaces");
224    let stopped = match crate::surfaces_cmd::stopped_surfaces(&surface.root, &state_dir) {
225        Ok(stopped) => stopped,
226        Err(e) => return json_error(500, e),
227    };
228    match crate::surfaces_cmd::surfaces_payload(
229        &registry_dir,
230        &state_dir,
231        &surface.surface_id,
232        &stopped,
233    ) {
234        Ok(payload) => Response::json(200, &payload),
235        Err(e) => json_error(500, e),
236    }
237}
238
239fn handle_post_start_surface(req: &Request) -> Response {
240    let obj = match parse_json_object(&req.body) {
241        Ok(o) => o,
242        Err(resp) => return resp,
243    };
244    let Some(folder) = obj.get("folder").and_then(|v| v.as_str()) else {
245        return json_error(400, "missing or invalid field folder");
246    };
247    let state_dir = match crate::surface_registry::state_dir() {
248        Ok(dir) => dir,
249        Err(e) => return json_error(500, e),
250    };
251    match crate::surface_start::start_surface_in(folder, &state_dir) {
252        Ok(started) => Response::json(
253            200,
254            &serde_json::json!({
255                "name": started.name,
256                "url": started.url,
257            }),
258        ),
259        Err(crate::surface_start::StartError::BadRequest(msg)) => json_error(400, msg),
260        Err(crate::surface_start::StartError::Internal(msg)) => json_error(500, msg),
261    }
262}
263
264pub const RELOAD_REUSE_TOKEN_ENV: &str = "BLYTE_RELOAD_REUSE_TOKEN";
265
266type StopTrigger = Arc<dyn Fn() + Send + Sync>;
267
268struct ReloadTrigger {
269    requested: Arc<AtomicBool>,
270    stop: StopTrigger,
271}
272
273fn handle_post_stop(stop_trigger: Option<&StopTrigger>) -> Response {
274    if let Some(trigger) = stop_trigger {
275        let trigger = Arc::clone(trigger);
276        std::thread::spawn(move || {
277            std::thread::sleep(Duration::from_millis(50));
278            trigger();
279        });
280    }
281    Response::json(202, &serde_json::json!({ "stopping": true }))
282}
283
284fn handle_post_api_stop(
285    surface: &Surface,
286    req: &Request,
287    stop_trigger: Option<&StopTrigger>,
288) -> Response {
289    let body_text = match std::str::from_utf8(&req.body) {
290        Ok(text) => text,
291        Err(_) => return json_error(400, "request body must be valid UTF-8"),
292    };
293    let trimmed = body_text.trim();
294    let force = if trimmed.is_empty() {
295        false
296    } else {
297        let parsed: serde_json::Value = match serde_json::from_str(trimmed) {
298            Ok(v) => v,
299            Err(_) => return json_error(400, "invalid JSON body"),
300        };
301        match parsed.as_object() {
302            Some(obj) => match obj.get("force") {
303                None => false,
304                Some(serde_json::Value::Bool(b)) => *b,
305                Some(_) => return json_error(400, "field `force` must be a boolean"),
306            },
307            None => return json_error(400, "request body must be a JSON object"),
308        }
309    };
310    if !force && surface.session.info().busy {
311        return json_error(
312            409,
313            "cannot stop while a turn is in progress; pass force to stop anyway",
314        );
315    }
316    handle_post_stop(stop_trigger)
317}
318
319fn handle_post_reload(surface: &Surface, reload_trigger: Option<&ReloadTrigger>) -> Response {
320    if surface.session.info().busy {
321        return json_error(409, "cannot reload while a turn is in progress");
322    }
323    if let Err(e) = surface.runtime.verify_executable() {
324        return json_error(500, e);
325    }
326    if let Some(trigger) = reload_trigger {
327        if trigger.requested.swap(true, Ordering::SeqCst) {
328            return json_error(409, "reload is already in progress");
329        }
330        let stop = Arc::clone(&trigger.stop);
331        std::thread::spawn(move || {
332            std::thread::sleep(Duration::from_millis(50));
333            stop();
334        });
335    }
336    Response::json(200, &serde_json::json!({ "reloading": true }))
337}
338
339fn health_response(surface: &Surface) -> Response {
340    Response::json(
341        200,
342        &serde_json::json!({
343            "surface_id": surface.surface_id,
344            "surface_name": surface.surface_name,
345            "session_id": surface.session_id,
346        }),
347    )
348}
349
350fn session_response(surface: &Surface) -> Response {
351    let info = surface.session.info();
352    let repository = match is_repository(&surface.root) {
353        Ok(v) => v,
354        Err(e) => return json_error(500, e),
355    };
356    let stale = match surface.runtime.is_stale() {
357        Ok(v) => v,
358        Err(e) => return json_error(500, e),
359    };
360    Response::json(
361        200,
362        &serde_json::json!({
363            "session_id": surface.session_id,
364            "surface_name": surface.surface_name,
365            "repo": surface.repo,
366            "repository": repository,
367            "started_at": surface.started_at,
368            "version": surface.runtime.version,
369            "boot_id": surface.runtime.boot_id,
370            "stale": stale,
371            "model": info.model,
372            "effort": info.effort,
373            "effort_supported": info.effort_supported,
374            "busy": info.busy,
375            "queued": info.queued,
376            "last_seq": info.last_seq,
377            "state": info.state,
378        }),
379    )
380}
381
382fn handle_events(surface: &Surface, req: &Request) -> Response {
383    let after_raw = match req.query_value("after") {
384        Some(v) => v,
385        None => return json_error(400, "missing required query parameter: after"),
386    };
387    let after = match after_raw.parse::<u64>() {
388        Ok(v) => v,
389        Err(_) => {
390            return json_error(
391                400,
392                format!("query parameter after must be a non-negative integer, got '{after_raw}'"),
393            );
394        }
395    };
396    let wait_ms = match req.query_value("wait_ms") {
397        None => 0,
398        Some(raw) => match raw.parse::<u64>() {
399            Ok(v) if v <= MAX_WAIT_MS => v,
400            Ok(v) => {
401                return json_error(
402                    400,
403                    format!("query parameter wait_ms must be at most {MAX_WAIT_MS}, got {v}"),
404                );
405            }
406            Err(_) => {
407                return json_error(
408                    400,
409                    format!("query parameter wait_ms must be a non-negative integer, got '{raw}'"),
410                );
411            }
412        },
413    };
414    let entries = surface
415        .session
416        .entries_after(after, Duration::from_millis(wait_ms));
417    let last_seq = surface.session.info().last_seq;
418    Response::json(
419        200,
420        &serde_json::json!({
421            "entries": entries,
422            "last_seq": last_seq,
423        }),
424    )
425}
426
427fn handle_usage(req: &Request, now: u64) -> Response {
428    let since = match req.query_value("since") {
429        None => None,
430        Some(raw) => {
431            let parsed = if raw.bytes().all(|b| b.is_ascii_digit()) {
432                raw.parse::<u64>().ok()
433            } else {
434                None
435            };
436            match parsed {
437                Some(ts) => Some(ts),
438                None => return json_error(400, format!("since must be unix seconds, got {raw}")),
439            }
440        }
441    };
442    let Some(log_path) = crate::usage_log::default_path() else {
443        return json_error(404, "the usage log is switched off (BLYTE_USAGE_LOG=off)");
444    };
445    match crate::usage_report::build(&log_path, since, now) {
446        Ok(report) => match serde_json::to_value(&report) {
447            Ok(value) => Response::json(200, &value),
448            Err(err) => json_error(500, format!("failed to serialise usage report: {err}")),
449        },
450        Err(err) => json_error(500, err),
451    }
452}
453
454fn handle_post_message(surface: &Surface, req: &Request) -> Response {
455    let obj = match parse_json_object(&req.body) {
456        Ok(o) => o,
457        Err(resp) => return resp,
458    };
459    let attachment_ids: Vec<String> = match obj.get("attachments") {
460        None | Some(serde_json::Value::Null) => Vec::new(),
461        Some(serde_json::Value::Array(arr)) => {
462            let mut ids = Vec::with_capacity(arr.len());
463            for item in arr {
464                match item.as_str() {
465                    Some(s) => ids.push(s.to_string()),
466                    None => {
467                        return json_error(400, "field attachments must be an array of strings");
468                    }
469                }
470            }
471            ids
472        }
473        Some(_) => return json_error(400, "field attachments must be an array of strings"),
474    };
475    let text = match obj.get("text") {
476        Some(serde_json::Value::String(s)) => s.clone(),
477        Some(serde_json::Value::Null) | None if !attachment_ids.is_empty() => String::new(),
478        Some(_) => return json_error(400, "field text must be a string"),
479        None => return json_error(400, "missing required field: text"),
480    };
481    let report_ids: Vec<String> = match obj.get("reports") {
482        None | Some(serde_json::Value::Null) => Vec::new(),
483        Some(serde_json::Value::Array(arr)) => {
484            let mut ids = Vec::with_capacity(arr.len());
485            for item in arr {
486                match item.as_str() {
487                    Some(s) => ids.push(s.to_string()),
488                    None => return json_error(400, "field reports must be an array of strings"),
489                }
490            }
491            ids
492        }
493        Some(_) => return json_error(400, "field reports must be an array of strings"),
494    };
495    let pastes: Vec<crate::session::Paste> = match obj.get("pastes") {
496        None | Some(serde_json::Value::Null) => Vec::new(),
497        Some(serde_json::Value::Array(arr)) => {
498            let mut out = Vec::with_capacity(arr.len());
499            for item in arr {
500                match serde_json::from_value::<crate::session::Paste>(item.clone()) {
501                    Ok(p) => out.push(p),
502                    Err(e) => return json_error(400, format!("invalid paste entry: {e}")),
503                }
504            }
505            out
506        }
507        Some(_) => return json_error(400, "field pastes must be an array"),
508    };
509
510    let mut report_attachments = Vec::with_capacity(report_ids.len());
511    for id in report_ids {
512        let path = surface.root.join(".wt").join(format!("{id}.report.md"));
513        if !is_valid_run_id(&id) {
514            return json_error(
515                400,
516                format!("invalid report run id '{id}' (path: {})", path.display()),
517            );
518        }
519        match std::fs::read_to_string(&path) {
520            Ok(body) => report_attachments.push(Attachment {
521                run: id,
522                text: body,
523            }),
524            Err(e) => {
525                return json_error(
526                    400,
527                    format!(
528                        "cannot read report for run '{id}' at {}: {e}",
529                        path.display()
530                    ),
531                );
532            }
533        }
534    }
535
536    let mut file_attachments = Vec::with_capacity(attachment_ids.len());
537    if !attachment_ids.is_empty() {
538        let Some(record_dir) = surface.session.attachments_root() else {
539            return json_error(500, "attachments directory is not configured");
540        };
541        for id in attachment_ids {
542            match crate::attachments::load_with_path(&record_dir, &id) {
543                Ok((meta, path, _)) => {
544                    file_attachments.push(crate::session::QueuedAttachment { meta, path })
545                }
546                Err(e) => return json_error(400, e),
547            }
548        }
549    }
550
551    match surface.session.submit_with_attachments(
552        &text,
553        report_attachments,
554        file_attachments,
555        pastes,
556    ) {
557        Ok(seq) => Response::json(200, &serde_json::json!({ "seq": seq })),
558        Err(e) => json_error(400, e),
559    }
560}
561
562fn handle_post_attachment(surface: &Surface, req: &Request) -> Response {
563    let Some(raw_name) = req
564        .query_value("name")
565        .map(str::trim)
566        .filter(|s| !s.is_empty())
567    else {
568        return json_error(400, "missing required query parameter: name");
569    };
570    if req.body.len() > crate::attachments::MAX_ATTACHMENT_BYTES {
571        return Response::text(
572            413,
573            &format!("{raw_name} is larger than the 10 MiB limit for one file"),
574        );
575    }
576    if req.body.is_empty() {
577        return json_error(400, format!("{raw_name} is empty"));
578    }
579    let Some(record_dir) = surface.session.attachments_root() else {
580        return json_error(500, "attachments directory is not configured");
581    };
582    match crate::attachments::store(&record_dir, raw_name, &req.body) {
583        Ok(meta) => match serde_json::to_value(&meta) {
584            Ok(v) => Response::json(200, &v),
585            Err(e) => json_error(500, format!("failed to serialise attachment metadata: {e}")),
586        },
587        Err(e) => json_error(400, e),
588    }
589}
590
591fn handle_get_attachment(surface: &Surface, id: &str) -> Response {
592    let Some(record_dir) = surface.session.attachments_root() else {
593        return json_error(500, "attachments directory is not configured");
594    };
595    match crate::attachments::load(&record_dir, id) {
596        Ok((_meta, bytes)) => {
597            let content_type =
598                crate::attachments::detect_image(&bytes).unwrap_or("application/octet-stream");
599            Response::bytes(200, content_type, bytes)
600        }
601        Err(e) => json_error(404, e),
602    }
603}
604
605fn handle_post_peer_message(surface: &Surface, req: &Request) -> Response {
606    let obj = match parse_json_object(&req.body) {
607        Ok(o) => o,
608        Err(resp) => return resp,
609    };
610    for key in obj.keys() {
611        if !matches!(key.as_str(), "from_name" | "from_repository" | "text") {
612            return json_error(400, format!("unexpected field: {key}"));
613        }
614    }
615    let from_name = match obj.get("from_name") {
616        Some(serde_json::Value::String(s)) => s.clone(),
617        Some(_) => return json_error(400, "field from_name must be a string"),
618        None => return json_error(400, "missing required field: from_name"),
619    };
620    if let Err(e) = crate::surface_dir::validate_surface_name(&from_name) {
621        return json_error(400, format!("invalid from_name: {e}"));
622    }
623    let from_repository = match obj.get("from_repository") {
624        Some(serde_json::Value::String(s)) => s.clone(),
625        Some(_) => return json_error(400, "field from_repository must be a string"),
626        None => return json_error(400, "missing required field: from_repository"),
627    };
628    let repo_chars = from_repository.chars().count();
629    if repo_chars == 0 || repo_chars > MAX_PEER_REPO_CHARS {
630        return json_error(
631            400,
632            format!("field from_repository must be 1 to {MAX_PEER_REPO_CHARS} characters"),
633        );
634    }
635    if from_repository.chars().any(char::is_control) {
636        return json_error(
637            400,
638            "field from_repository must not contain control characters",
639        );
640    }
641    let text = match obj.get("text") {
642        Some(serde_json::Value::String(s)) => s.clone(),
643        Some(_) => return json_error(400, "field text must be a string"),
644        None => return json_error(400, "missing required field: text"),
645    };
646    if text.trim().is_empty() {
647        return json_error(400, "field text must not be blank");
648    }
649    if text.len() > MAX_PEER_TEXT_BYTES {
650        return json_error(
651            400,
652            format!("field text must be at most {MAX_PEER_TEXT_BYTES} bytes"),
653        );
654    }
655
656    match surface
657        .session
658        .submit_peer(&from_name, &from_repository, &text)
659    {
660        Ok(PeerDelivery::Delivered) => {
661            Response::json(200, &serde_json::json!({ "status": "delivered" }))
662        }
663        Ok(PeerDelivery::Held) => Response::json(200, &serde_json::json!({ "status": "held" })),
664        Err(e) => json_error(400, e),
665    }
666}
667
668fn handle_models() -> Response {
669    let discovered = blyte_provider::discover_all_models();
670    let mut models = Vec::new();
671    let mut unavailable = Vec::new();
672    let mut error_parts = Vec::new();
673
674    for (provider, result) in discovered {
675        match result {
676            Ok(list) => {
677                for m in list {
678                    let effort_supported = crate::session::model_supports_effort(&m.id);
679                    models.push(serde_json::json!({
680                        "id": m.id,
681                        "effort_supported": effort_supported,
682                    }));
683                }
684            }
685            Err(e) => {
686                let err_text = e.to_string();
687                error_parts.push(format!("{provider}: {err_text}"));
688                unavailable.push(serde_json::json!({
689                    "provider": provider,
690                    "error": err_text,
691                }));
692            }
693        }
694    }
695
696    if models.is_empty() {
697        let msg = if error_parts.is_empty() {
698            "no models listed by any provider".to_string()
699        } else {
700            format!("no models available: {}", error_parts.join("; "))
701        };
702        return json_error(502, msg);
703    }
704
705    Response::json(
706        200,
707        &serde_json::json!({
708            "models": models,
709            "unavailable": unavailable,
710        }),
711    )
712}
713
714fn handle_post_model(surface: &Surface, req: &Request) -> Response {
715    let obj = match parse_json_object(&req.body) {
716        Ok(o) => o,
717        Err(resp) => return resp,
718    };
719    let model = match obj.get("model") {
720        Some(serde_json::Value::String(s)) => s.clone(),
721        Some(_) => return json_error(400, "field model must be a string"),
722        None => return json_error(400, "missing required field: model"),
723    };
724    if model.trim().is_empty() {
725        return json_error(400, "field model must not be empty");
726    }
727    if let Err(e) = blyte_provider::resolve_provider(Some(&model)) {
728        return json_error(400, e.to_string());
729    }
730    if let Err(e) = surface.session.set_model(&model) {
731        return json_error(400, e);
732    }
733    session_response(surface)
734}
735
736fn handle_post_effort(surface: &Surface, req: &Request) -> Response {
737    let obj = match parse_json_object(&req.body) {
738        Ok(o) => o,
739        Err(resp) => return resp,
740    };
741    let effort = match obj.get("effort") {
742        Some(serde_json::Value::Null) => None,
743        Some(serde_json::Value::String(s)) => Some(s.clone()),
744        Some(_) => return json_error(400, "field effort must be a string or null"),
745        None => return json_error(400, "missing required field: effort"),
746    };
747    if let Err(e) = surface.session.set_effort(effort.as_deref()) {
748        return json_error(400, e);
749    }
750    session_response(surface)
751}
752
753fn handle_post_seen(surface: &Surface) -> Response {
754    surface.session.mark_seen();
755    Response::text(204, "")
756}
757
758fn handle_post_approval(surface: &Surface, id: &str, req: &Request) -> Response {
759    let obj = match parse_json_object(&req.body) {
760        Ok(o) => o,
761        Err(resp) => return resp,
762    };
763    if obj.len() != 1 {
764        return json_error(400, "request body must contain only field answer");
765    }
766    let answer = match obj.get("answer") {
767        Some(serde_json::Value::String(s)) if s == "yes" => ApprovalAnswer::Yes,
768        Some(serde_json::Value::String(s)) if s == "no" => ApprovalAnswer::No,
769        Some(serde_json::Value::String(other)) => {
770            return json_error(
771                400,
772                format!("field answer must be \"yes\" or \"no\", got '{other}'"),
773            );
774        }
775        Some(_) => return json_error(400, "field answer must be \"yes\" or \"no\""),
776        None => return json_error(400, "missing required field: answer"),
777    };
778    match surface.session.answer_approval(id, answer) {
779        Ok(seq) => Response::json(
780            200,
781            &serde_json::json!({
782                "id": id,
783                "answer": answer.as_str(),
784                "seq": seq,
785            }),
786        ),
787        Err(AnswerError::NotFound) => json_error(404, format!("unknown approval id: {id}")),
788        Err(AnswerError::AlreadyAnswered) => {
789            json_error(409, format!("approval {id} has already been answered"))
790        }
791    }
792}
793
794pub fn reconcile_runs(
795    surface: &Surface,
796    now: u64,
797) -> Result<(crate::live_runs::LiveRuns, Vec<String>), String> {
798    let _guard = surface
799        .reconcile_lock
800        .lock()
801        .unwrap_or_else(|e| e.into_inner());
802    if !is_repository(&surface.root)? {
803        let records_dir = crate::dispatch_in_place::records_dir_for(&surface.root)?;
804        let owned = crate::requests::owned_run_ids_in(&records_dir, &surface.surface_id)?;
805        let mut live =
806            crate::live_runs::collect_in_place(&surface.root, &records_dir, now, surface.days)?;
807        live.running.retain(|run| owned.contains(&run.id));
808        live.runs.retain(|run| owned.contains(&run.id));
809
810        let mut errors = Vec::new();
811        if let Err(e) = crate::run_results::report_finished_runs_in(surface, &records_dir) {
812            errors.push(format!("run report failed: {e}"));
813        }
814        return Ok((live, errors));
815    }
816    let owned = crate::requests::owned_run_ids(surface)?;
817    let mut live = crate::live_runs::collect(&surface.root, now, surface.days)?;
818    let mut any_written = false;
819    for run in &live.runs {
820        if !owned.contains(&run.id) || run.checks_recorded {
821            continue;
822        }
823        if crate::queue_actions::ensure_checks(&surface.root, &run.id)? {
824            any_written = true;
825        }
826    }
827    if any_written {
828        live = crate::live_runs::collect(&surface.root, now, surface.days)?;
829    }
830    live.running.retain(|run| owned.contains(&run.id));
831    live.runs.retain(|run| owned.contains(&run.id));
832
833    let mut errors = Vec::new();
834    if let Err(e) = crate::run_results::report_finished_runs(surface) {
835        errors.push(format!("run report failed: {e}"));
836    }
837
838    let mut triggered = BTreeSet::new();
839    for run in &live.runs {
840        if run.research {
841            continue;
842        }
843        if let Some(ref req_id) = run.request {
844            if triggered.insert(req_id.clone()) {
845                if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
846                    errors.push(format!("combine trigger failed for {req_id}: {e}"));
847                }
848            }
849        }
850    }
851
852    Ok((live, errors))
853}
854
855fn handle_runs(surface: &Surface, now: u64) -> Response {
856    let is_repo = match is_repository(&surface.root) {
857        Ok(v) => v,
858        Err(e) => return json_error(500, e),
859    };
860    let (live, errors) = match reconcile_runs(surface, now) {
861        Ok(res) => res,
862        Err(e) => return json_error(500, e),
863    };
864    for msg in errors {
865        surface.session.record_error(&msg);
866    }
867
868    let mut runs_with_hold = Vec::with_capacity(live.runs.len());
869    if is_repo {
870        let run_refs: Vec<(&str, Option<&str>)> = live
871            .runs
872            .iter()
873            .map(|run| (run.id.as_str(), run.request.as_deref()))
874            .collect();
875        let combined_ids = match crate::requests::combined_run_ids(&surface.root, &run_refs) {
876            Ok(ids) => ids,
877            Err(e) => return json_error(500, e),
878        };
879
880        for run in &live.runs {
881            let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
882                Ok(h) => h,
883                Err(e) => return json_error(500, e),
884            };
885            let combined = combined_ids.contains(&run.id);
886            runs_with_hold.push(RunWithHold {
887                run,
888                hold,
889                combined,
890                in_place: false,
891                undone: false,
892            });
893        }
894    } else {
895        let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
896            Ok(dir) => dir,
897            Err(e) => return json_error(500, e),
898        };
899        for run in &live.runs {
900            let hold = match crate::queue_actions::read_hold_in(&records_dir, &run.id) {
901                Ok(h) => h,
902                Err(e) => return json_error(500, e),
903            };
904            let undone = crate::in_place_review::is_undone(&records_dir, &run.id);
905            runs_with_hold.push(RunWithHold {
906                run,
907                hold,
908                combined: false,
909                in_place: true,
910                undone,
911            });
912        }
913    }
914
915    let payload = LiveRunsResponse {
916        generated_at: live.generated_at,
917        repo: &live.repo,
918        running: &live.running,
919        runs: runs_with_hold,
920        skipped: &live.skipped,
921    };
922    match serde_json::to_value(&payload) {
923        Ok(val) => Response::json(200, &val),
924        Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
925    }
926}
927
928fn handle_runs_changed(surface: &Surface) -> Response {
929    surface.reconcile_requested.store(true, Ordering::Release);
930    Response::json(202, &serde_json::json!({}))
931}
932
933const NOT_A_GIT_REPO_ERROR: &str = "this folder is not a git repository";
934
935fn require_repository(root: &Path) -> Result<(), Response> {
936    match is_repository(root) {
937        Ok(true) => Ok(()),
938        Ok(false) => Err(json_error(409, NOT_A_GIT_REPO_ERROR)),
939        Err(e) => Err(json_error(500, e)),
940    }
941}
942
943fn handle_run_diff(surface: &Surface, id: &str) -> Response {
944    let is_repo = match is_repository(&surface.root) {
945        Ok(v) => v,
946        Err(e) => return json_error(500, e),
947    };
948    if !is_valid_run_id(id) {
949        return json_error(404, format!("unknown run: {id}"));
950    }
951    if !is_repo {
952        let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
953            Ok(dir) => dir,
954            Err(e) => return json_error(500, e),
955        };
956        let start = records_dir.join(format!("{id}.start.json"));
957        let summary = records_dir.join(format!("{id}.json"));
958        let report_json = records_dir.join(format!("{id}.report.json"));
959        let report_md = records_dir.join(format!("{id}.report.md"));
960        if !start.exists() && !summary.exists() && !report_json.exists() && !report_md.exists() {
961            return json_error(404, format!("unknown run: {id}"));
962        }
963        if let Err(err) = crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
964        {
965            return request_action_error_response(err);
966        }
967        return match crate::in_place_review::diff_for_run(&records_dir, id) {
968            Ok(body) => Response::text(200, &body),
969            Err(e) => {
970                if !summary.exists() || e.contains("No such file") || e.contains("missing manifest")
971                {
972                    json_error(404, e)
973                } else {
974                    json_error(500, e)
975                }
976            }
977        };
978    }
979    let wt_dir = surface.root.join(".wt");
980    let wt = wt_dir.join(id);
981    let start = wt_dir.join(format!("{id}.start.json"));
982    let summary = wt_dir.join(format!("{id}.json"));
983    let report_json = wt_dir.join(format!("{id}.report.json"));
984    let report_md = wt_dir.join(format!("{id}.report.md"));
985    if !wt.exists()
986        && !start.exists()
987        && !summary.exists()
988        && !report_json.exists()
989        && !report_md.exists()
990    {
991        return json_error(404, format!("unknown run: {id}"));
992    }
993    if let Err(err) = crate::requests::run_owner_check(surface, id) {
994        return request_action_error_response(err);
995    }
996    match crate::queue_actions::compute_review(&surface.root, id, true) {
997        Ok(data) => {
998            let body = if !data.wt_exists {
999                "(worktree removed)\n".to_string()
1000            } else if data.diff_out.is_empty() {
1001                String::new()
1002            } else {
1003                format!("{}\n", data.diff_out)
1004            };
1005            Response::text(200, &body)
1006        }
1007        Err(e) => {
1008            if !wt.is_dir() || !wt.join(".git").exists() {
1009                json_error(404, e)
1010            } else {
1011                json_error(500, e)
1012            }
1013        }
1014    }
1015}
1016
1017fn handle_run_undo(surface: &Surface, id: &str) -> Response {
1018    let is_repo = match is_repository(&surface.root) {
1019        Ok(v) => v,
1020        Err(e) => return json_error(500, e),
1021    };
1022    if is_repo {
1023        return json_error(
1024            409,
1025            "undo is for runs in a folder that is not a git repository",
1026        );
1027    }
1028    if !is_valid_run_id(id) {
1029        return json_error(404, format!("unknown run: {id}"));
1030    }
1031    let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
1032        Ok(dir) => dir,
1033        Err(e) => return json_error(500, e),
1034    };
1035    let run_exists = records_dir.join(format!("{id}.start.json")).exists()
1036        || records_dir.join(format!("{id}.json")).exists()
1037        || records_dir.join(format!("{id}.report.json")).exists()
1038        || records_dir.join(format!("{id}.report.md")).exists();
1039    if run_exists {
1040        if let Err(err) = crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
1041        {
1042            return request_action_error_response(err);
1043        }
1044    }
1045    match crate::in_place_review::undo_in(&surface.root, id) {
1046        Ok(lines) => Response::json(200, &serde_json::json!({ "lines": lines })),
1047        Err(msg) => json_error(409, msg),
1048    }
1049}
1050
1051fn parse_action(raw: &str) -> Result<Action, String> {
1052    match raw {
1053        "accept" => Ok(Action::Accept),
1054        "send_back" => Ok(Action::SendBack),
1055        "redo" => Ok(Action::Redo),
1056        "hold" => Ok(Action::Hold),
1057        "mark_read" => Ok(Action::MarkRead),
1058        other => Err(format!(
1059            "unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
1060        )),
1061    }
1062}
1063
1064fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
1065    let is_repo = match is_repository(&surface.root) {
1066        Ok(v) => v,
1067        Err(e) => return json_error(500, e),
1068    };
1069    let obj = match parse_json_object(&req.body) {
1070        Ok(o) => o,
1071        Err(resp) => return resp,
1072    };
1073    let action_str = match obj.get("action") {
1074        Some(serde_json::Value::String(s)) => s.clone(),
1075        Some(_) => return json_error(400, "field action must be a string"),
1076        None => return json_error(400, "missing required field: action"),
1077    };
1078    let action = match parse_action(&action_str) {
1079        Ok(a) => a,
1080        Err(e) => return json_error(400, e),
1081    };
1082    let note = match obj.get("note") {
1083        None | Some(serde_json::Value::Null) => None,
1084        Some(serde_json::Value::String(s)) => Some(s.clone()),
1085        Some(_) => return json_error(400, "field note must be a string or null"),
1086    };
1087
1088    let decision = if is_repo {
1089        let wt_dir = surface.root.join(".wt");
1090        let run_exists = is_valid_run_id(id)
1091            && (wt_dir.join(id).exists()
1092                || wt_dir.join(format!("{id}.start.json")).exists()
1093                || wt_dir.join(format!("{id}.json")).exists()
1094                || wt_dir.join(format!("{id}.report.json")).exists()
1095                || wt_dir.join(format!("{id}.report.md")).exists());
1096        if run_exists {
1097            if let Err(err) = crate::requests::run_owner_check(surface, id) {
1098                return request_action_error_response(err);
1099            }
1100        }
1101        match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
1102            Ok(d) => d,
1103            Err(e) => return json_error(400, e),
1104        }
1105    } else {
1106        let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
1107            Ok(dir) => dir,
1108            Err(e) => return json_error(500, e),
1109        };
1110        let run_exists = is_valid_run_id(id)
1111            && (records_dir.join(format!("{id}.start.json")).exists()
1112                || records_dir.join(format!("{id}.json")).exists()
1113                || records_dir.join(format!("{id}.report.json")).exists()
1114                || records_dir.join(format!("{id}.report.md")).exists());
1115        if run_exists {
1116            if let Err(err) =
1117                crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
1118            {
1119                return request_action_error_response(err);
1120            }
1121        }
1122        match crate::queue_actions::decide_in_place(&records_dir, id, action, note.as_deref(), now)
1123        {
1124            Ok(d) => d,
1125            Err(e) => return json_error(400, e),
1126        }
1127    };
1128    let seq = match surface.session.record_decision(
1129        &decision.run,
1130        &action_str,
1131        decision.note.as_deref(),
1132        decision.conversation_message.as_deref(),
1133    ) {
1134        Ok(s) => s,
1135        Err(e) => return json_error(500, e),
1136    };
1137    if is_repo && action == Action::Accept {
1138        match crate::requests::run_request_id(&surface.root, &decision.run) {
1139            Ok(Some(req_id)) => {
1140                if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
1141                    surface
1142                        .session
1143                        .record_error(&format!("combine trigger failed for {req_id}: {e}"));
1144                }
1145            }
1146            Ok(None) => {}
1147            Err(e) => return json_error(500, e),
1148        }
1149    }
1150    Response::json(
1151        200,
1152        &serde_json::json!({
1153            "decision": {
1154                "run": decision.run,
1155                "action": action_str,
1156                "note": decision.note,
1157                "conversation_message": decision.conversation_message,
1158            },
1159            "seq": seq,
1160        }),
1161    )
1162}
1163
1164fn handle_map(surface: &Surface) -> Response {
1165    match crate::map::build(&surface.root, &surface.repo) {
1166        Ok(data) => match serde_json::to_value(&data) {
1167            Ok(val) => Response::json(200, &val),
1168            Err(e) => json_error(500, format!("failed to serialize map: {e}")),
1169        },
1170        Err(e) => json_error(422, e),
1171    }
1172}
1173
1174fn handle_requests(surface: &Surface) -> Response {
1175    match is_repository(&surface.root) {
1176        Ok(true) => {}
1177        Ok(false) => return Response::json(200, &serde_json::json!([])),
1178        Err(e) => return json_error(500, e),
1179    }
1180    match crate::requests::list_requests(surface) {
1181        Ok(list) => match serde_json::to_value(&list) {
1182            Ok(val) => Response::json(200, &val),
1183            Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
1184        },
1185        Err(e) => json_error(500, e),
1186    }
1187}
1188
1189fn request_action_error_response(err: RequestActionError) -> Response {
1190    match err {
1191        RequestActionError::BadRequest(msg) => json_error(400, msg),
1192        RequestActionError::NotOwned(msg) => json_error(403, msg),
1193        RequestActionError::Conflict(msg) => json_error(409, msg),
1194        RequestActionError::Internal(msg) => json_error(500, msg),
1195    }
1196}
1197
1198fn handle_request_push(surface: &Surface, id: &str) -> Response {
1199    if let Err(resp) = require_repository(&surface.root) {
1200        return resp;
1201    }
1202    match crate::requests::push_request(surface, id) {
1203        Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
1204        Err(err) => request_action_error_response(err),
1205    }
1206}
1207
1208fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
1209    if let Err(resp) = require_repository(&surface.root) {
1210        return resp;
1211    }
1212    if let Err(e) = crate::dispatch::validate_request_id(id) {
1213        return json_error(400, e);
1214    }
1215    let obj = match parse_json_object(&req.body) {
1216        Ok(o) => o,
1217        Err(resp) => return resp,
1218    };
1219    let title = match obj.get("title") {
1220        Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
1221        Some(serde_json::Value::String(_)) => {
1222            return json_error(400, "field title must not be empty");
1223        }
1224        Some(_) => return json_error(400, "field title must be a string"),
1225        None => return json_error(400, "missing required field: title"),
1226    };
1227    let body = match obj.get("body") {
1228        None | Some(serde_json::Value::Null) => String::new(),
1229        Some(serde_json::Value::String(s)) => s.clone(),
1230        Some(_) => return json_error(400, "field body must be a string"),
1231    };
1232    match crate::requests::open_request_pull_request(surface, id, &title, &body) {
1233        Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
1234        Err(err) => request_action_error_response(err),
1235    }
1236}
1237
1238#[derive(Clone, Copy)]
1239enum ApiGetHandler {
1240    Session,
1241    Events,
1242    Models,
1243    Runs,
1244    Requests,
1245    Map,
1246    RunDiff,
1247    Usage,
1248}
1249
1250const API_GET_ROUTES: &[(&str, ApiGetHandler)] = &[
1251    ("/api/session", ApiGetHandler::Session),
1252    ("/api/session/events", ApiGetHandler::Events),
1253    ("/api/models", ApiGetHandler::Models),
1254    ("/api/runs", ApiGetHandler::Runs),
1255    ("/api/requests", ApiGetHandler::Requests),
1256    ("/api/map", ApiGetHandler::Map),
1257    ("/api/runs/{id}/diff", ApiGetHandler::RunDiff),
1258    ("/api/usage", ApiGetHandler::Usage),
1259];
1260
1261pub fn authenticated_api_get_routes() -> Vec<&'static str> {
1262    API_GET_ROUTES.iter().map(|(pattern, _)| *pattern).collect()
1263}
1264
1265fn match_api_get_route<'a>(pattern: &str, path: &'a str) -> Option<Option<&'a str>> {
1266    if let Some((prefix, suffix)) = pattern.split_once("{id}") {
1267        let rest = path.strip_prefix(prefix)?;
1268        let id = rest.strip_suffix(suffix)?;
1269        if !id.is_empty() && !id.contains('/') {
1270            return Some(Some(id));
1271        }
1272        None
1273    } else if pattern == path {
1274        Some(None)
1275    } else {
1276        None
1277    }
1278}
1279
1280fn handle_post_open_code(surface: &Surface, now: u64) -> Response {
1281    match surface.open_codes.issue(now) {
1282        Ok(code) => Response::json(200, &serde_json::json!({ "code": code })),
1283        Err(e) => json_error(500, e),
1284    }
1285}
1286
1287fn handle_post_open(surface: &Surface, req: &Request, now: u64) -> Response {
1288    let forbidden = Response {
1289        status: 403,
1290        content_type: "application/json",
1291        body: b"{}".to_vec(),
1292    };
1293    let Ok(value) = serde_json::from_slice::<serde_json::Value>(&req.body) else {
1294        return forbidden;
1295    };
1296    let Some(code) = value.get("code").and_then(|v| v.as_str()) else {
1297        return forbidden;
1298    };
1299    match surface.open_codes.redeem(code, now) {
1300        Ok(true) => Response::json(200, &serde_json::json!({ "token": surface.token })),
1301        Ok(false) => forbidden,
1302        Err(e) => json_error(500, e),
1303    }
1304}
1305
1306pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
1307    route_inner(surface, req, now, None, None)
1308}
1309
1310fn route_inner(
1311    surface: &Surface,
1312    req: &Request,
1313    now: u64,
1314    stop_trigger: Option<&StopTrigger>,
1315    reload_trigger: Option<&ReloadTrigger>,
1316) -> Response {
1317    if req.path == "/api/peer/messages" && req.method == "POST" {
1318        if !has_valid_message_credential(surface, req) {
1319            return json_error(403, "missing or invalid message credential");
1320        }
1321        return handle_post_peer_message(surface, req);
1322    }
1323
1324    let is_health_get = req.path == "/api/health" && req.method == "GET";
1325    let is_open_post = req.path == "/api/open" && req.method == "POST";
1326    if (req.path.starts_with("/api/") || req.method == "POST")
1327        && !is_health_get
1328        && !is_open_post
1329        && !has_valid_token(surface, req)
1330    {
1331        return json_error(
1332            403,
1333            "missing or invalid surface token; open the page from the URL blyte printed",
1334        );
1335    }
1336
1337    if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
1338        if req.method != "GET" {
1339            return method_not_allowed(req);
1340        }
1341        return Response {
1342            status,
1343            content_type,
1344            body,
1345        };
1346    }
1347
1348    if req.path == "/" || req.path == "/index.html" {
1349        if req.method != "GET" {
1350            return method_not_allowed(req);
1351        }
1352        return Response::html(INDEX_HTML.as_bytes().to_vec());
1353    }
1354
1355    if req.path == "/usage" {
1356        if req.method != "GET" {
1357            return method_not_allowed(req);
1358        }
1359        return Response::html(USAGE_HTML.as_bytes().to_vec());
1360    }
1361
1362    if req.path == "/api/health" {
1363        if req.method != "GET" {
1364            return method_not_allowed(req);
1365        }
1366        return health_response(surface);
1367    }
1368
1369    for &(pattern, handler) in API_GET_ROUTES {
1370        if let Some(id) = match_api_get_route(pattern, &req.path) {
1371            if req.method != "GET" {
1372                return method_not_allowed(req);
1373            }
1374            return match handler {
1375                ApiGetHandler::Session => session_response(surface),
1376                ApiGetHandler::Events => handle_events(surface, req),
1377                ApiGetHandler::Models => handle_models(),
1378                ApiGetHandler::Runs => handle_runs(surface, now),
1379                ApiGetHandler::Requests => handle_requests(surface),
1380                ApiGetHandler::Map => handle_map(surface),
1381                ApiGetHandler::RunDiff => handle_run_diff(surface, id.unwrap_or("")),
1382                ApiGetHandler::Usage => handle_usage(req, now),
1383            };
1384        }
1385    }
1386
1387    match req.path.as_str() {
1388        "/api/open" => {
1389            if req.method != "POST" {
1390                return method_not_allowed(req);
1391            }
1392            handle_post_open(surface, req, now)
1393        }
1394        "/api/surfaces" => {
1395            if req.method != "GET" {
1396                return method_not_allowed(req);
1397            }
1398            handle_surfaces(surface)
1399        }
1400        "/api/surfaces/start" => {
1401            if req.method != "POST" {
1402                return method_not_allowed(req);
1403            }
1404            handle_post_start_surface(req)
1405        }
1406        "/api/session/stop" => {
1407            if req.method != "POST" {
1408                return method_not_allowed(req);
1409            }
1410            handle_post_stop(stop_trigger)
1411        }
1412        "/api/stop" => {
1413            if req.method != "POST" {
1414                return method_not_allowed(req);
1415            }
1416            handle_post_api_stop(surface, req, stop_trigger)
1417        }
1418        "/api/reload" => {
1419            if req.method != "POST" {
1420                return method_not_allowed(req);
1421            }
1422            handle_post_reload(surface, reload_trigger)
1423        }
1424        "/api/session/open-codes" => {
1425            if req.method != "POST" {
1426                return method_not_allowed(req);
1427            }
1428            handle_post_open_code(surface, now)
1429        }
1430        "/api/session/messages" => {
1431            if req.method != "POST" {
1432                return method_not_allowed(req);
1433            }
1434            handle_post_message(surface, req)
1435        }
1436        "/api/session/attachments" => {
1437            if req.method != "POST" {
1438                return method_not_allowed(req);
1439            }
1440            handle_post_attachment(surface, req)
1441        }
1442        "/api/session/model" => {
1443            if req.method != "POST" {
1444                return method_not_allowed(req);
1445            }
1446            handle_post_model(surface, req)
1447        }
1448        "/api/session/effort" => {
1449            if req.method != "POST" {
1450                return method_not_allowed(req);
1451            }
1452            handle_post_effort(surface, req)
1453        }
1454        "/api/session/seen" => {
1455            if req.method != "POST" {
1456                return method_not_allowed(req);
1457            }
1458            handle_post_seen(surface)
1459        }
1460        "/api/runs/changed" => {
1461            if req.method != "POST" {
1462                return method_not_allowed(req);
1463            }
1464            handle_runs_changed(surface)
1465        }
1466        path => {
1467            if let Some(id) = path.strip_prefix("/api/session/attachments/") {
1468                if !id.is_empty() && !id.contains('/') {
1469                    if req.method != "GET" {
1470                        return method_not_allowed(req);
1471                    }
1472                    return handle_get_attachment(surface, id);
1473                }
1474            }
1475            if let Some(id) = path.strip_prefix("/api/session/approvals/") {
1476                if !id.is_empty() && !id.contains('/') {
1477                    if req.method != "POST" {
1478                        return method_not_allowed(req);
1479                    }
1480                    return handle_post_approval(surface, id, req);
1481                }
1482            }
1483            if let Some(rest) = path.strip_prefix("/api/runs/") {
1484                if let Some(id) = rest.strip_suffix("/decision") {
1485                    if !id.is_empty() && !id.contains('/') {
1486                        if req.method != "POST" {
1487                            return method_not_allowed(req);
1488                        }
1489                        return handle_run_decision(surface, id, req, now);
1490                    }
1491                }
1492                if let Some(id) = rest.strip_suffix("/undo") {
1493                    if !id.is_empty() && !id.contains('/') {
1494                        if req.method != "POST" {
1495                            return method_not_allowed(req);
1496                        }
1497                        return handle_run_undo(surface, id);
1498                    }
1499                }
1500            }
1501            if let Some(rest) = path.strip_prefix("/api/requests/") {
1502                if let Some(id) = rest.strip_suffix("/push") {
1503                    if req.method != "POST" {
1504                        return method_not_allowed(req);
1505                    }
1506                    return handle_request_push(surface, id);
1507                }
1508                if let Some(id) = rest.strip_suffix("/pull-request") {
1509                    if req.method != "POST" {
1510                        return method_not_allowed(req);
1511                    }
1512                    return handle_request_pull_request(surface, id, req);
1513                }
1514            }
1515            json_error(404, format!("not found: {}", req.path))
1516        }
1517    }
1518}
1519
1520enum GitToplevel {
1521    Repository(PathBuf),
1522    NotARepository,
1523}
1524
1525fn find_git_toplevel(dir: &Path) -> Result<GitToplevel, String> {
1526    let out = Command::new("git")
1527        .args(["rev-parse", "--show-toplevel"])
1528        .env("LC_ALL", "C")
1529        .current_dir(dir)
1530        .output()
1531        .map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
1532    if !out.status.success() {
1533        let stderr = String::from_utf8_lossy(&out.stderr);
1534        if stderr.contains("not a git repository (or any") {
1535            return Ok(GitToplevel::NotARepository);
1536        }
1537        let detail = stderr.trim();
1538        if detail.is_empty() {
1539            return Err(format!("not inside a git repository ({})", dir.display()));
1540        }
1541        return Err(format!(
1542            "not inside a git repository ({}): {detail}",
1543            dir.display()
1544        ));
1545    }
1546    let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
1547    if path_str.is_empty() {
1548        return Err(format!("not inside a git repository ({})", dir.display()));
1549    }
1550    Ok(GitToplevel::Repository(PathBuf::from(path_str)))
1551}
1552
1553pub(crate) fn is_repository(root: &Path) -> Result<bool, String> {
1554    match find_git_toplevel(root)? {
1555        GitToplevel::Repository(_) => Ok(true),
1556        GitToplevel::NotARepository => Ok(false),
1557    }
1558}
1559
1560fn resolve_denied_path(denied: &Path) -> Result<PathBuf, String> {
1561    let mut probe = denied;
1562    let mut tail = Vec::new();
1563    loop {
1564        match probe.canonicalize() {
1565            Ok(mut resolved) => {
1566                for part in tail.into_iter().rev() {
1567                    resolved.push(part);
1568                }
1569                return Ok(resolved);
1570            }
1571            Err(e)
1572                if matches!(
1573                    e.kind(),
1574                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
1575                ) =>
1576            {
1577                let Some(name) = probe.file_name() else {
1578                    return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1579                };
1580                let Some(parent) = probe.parent() else {
1581                    return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1582                };
1583                tail.push(name.to_os_string());
1584                probe = parent;
1585            }
1586            Err(e) => {
1587                return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1588            }
1589        }
1590    }
1591}
1592
1593pub fn check_linux_non_repo_root(root: &Path, home: &Path) -> Result<(), String> {
1594    let root_canon = root
1595        .canonicalize()
1596        .map_err(|e| format!("cannot canonicalize {}: {e}", root.display()))?;
1597    let home_canon = home
1598        .canonicalize()
1599        .map_err(|e| format!("cannot canonicalize home directory {}: {e}", home.display()))?;
1600    for denied in blyte_agent::sandbox::read_denied(&home_canon) {
1601        let denied_canon = resolve_denied_path(&denied)?;
1602        if denied.starts_with(&root_canon) || denied_canon.starts_with(&root_canon) {
1603            return Err(format!(
1604                "on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
1605                root_canon.display(),
1606                denied.display()
1607            ));
1608        }
1609    }
1610    if home_canon.starts_with(&root_canon) {
1611        return Err(format!(
1612            "on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
1613            root_canon.display(),
1614            home_canon.display()
1615        ));
1616    }
1617    Ok(())
1618}
1619
1620pub fn check_linux_non_repo_root_for_env(
1621    root: &Path,
1622    home: Option<&std::ffi::OsStr>,
1623) -> Result<(), String> {
1624    let home = home.filter(|h| !h.is_empty()).ok_or_else(|| {
1625        format!(
1626            "cannot check whether {} contains protected paths on Linux: HOME is not set",
1627            root.display()
1628        )
1629    })?;
1630    check_linux_non_repo_root(root, Path::new(home))
1631}
1632
1633fn resolve_main_checkout(worktree_root: &Path) -> Result<PathBuf, String> {
1634    let out = Command::new("git")
1635        .args([
1636            "rev-parse",
1637            "--path-format=absolute",
1638            "--git-dir",
1639            "--git-common-dir",
1640        ])
1641        .current_dir(worktree_root)
1642        .output()
1643        .map_err(|_| {
1644            format!(
1645                "cannot find the main checkout of {}",
1646                worktree_root.display()
1647            )
1648        })?;
1649    if !out.status.success() {
1650        return Err(format!(
1651            "cannot find the main checkout of {}",
1652            worktree_root.display()
1653        ));
1654    }
1655    let text = String::from_utf8_lossy(&out.stdout);
1656    let mut lines = text.lines();
1657    let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
1658        return Err(format!(
1659            "cannot find the main checkout of {}",
1660            worktree_root.display()
1661        ));
1662    };
1663    let git_dir_path = PathBuf::from(git_dir.trim());
1664    let common_dir_path = PathBuf::from(common_dir.trim());
1665    let git_dir_canon = git_dir_path
1666        .canonicalize()
1667        .map_err(|e| format!("cannot canonicalize {}: {e}", git_dir_path.display()))?;
1668    let common_dir_canon = common_dir_path
1669        .canonicalize()
1670        .map_err(|e| format!("cannot canonicalize {}: {e}", common_dir_path.display()))?;
1671    if git_dir_canon == common_dir_canon {
1672        return worktree_root
1673            .canonicalize()
1674            .map_err(|e| format!("cannot canonicalize {}: {e}", worktree_root.display()));
1675    }
1676    let main = crate::config::main_checkout(worktree_root).ok_or_else(|| {
1677        format!(
1678            "cannot find the main checkout of {}",
1679            worktree_root.display()
1680        )
1681    })?;
1682    main.canonicalize()
1683        .map_err(|e| format!("cannot canonicalize {}: {e}", main.display()))
1684}
1685
1686pub(crate) fn resolve_folder(folder: &Path) -> Result<PathBuf, String> {
1687    match find_git_toplevel(folder)? {
1688        GitToplevel::Repository(worktree_root) => resolve_main_checkout(&worktree_root),
1689        GitToplevel::NotARepository => folder
1690            .canonicalize()
1691            .map_err(|e| format!("cannot canonicalize {}: {e}", folder.display())),
1692    }
1693}
1694
1695fn current_branch(main_checkout: &Path) -> Result<Option<String>, String> {
1696    match find_git_toplevel(main_checkout)? {
1697        GitToplevel::NotARepository => return Ok(None),
1698        GitToplevel::Repository(_) => {}
1699    }
1700    if let Ok(out) = Command::new("git")
1701        .args(["rev-parse", "--abbrev-ref", "HEAD"])
1702        .current_dir(main_checkout)
1703        .output()
1704    {
1705        if out.status.success() {
1706            let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
1707            if !branch.is_empty() {
1708                return Ok(Some(branch));
1709            }
1710        }
1711    }
1712    if let Ok(out) = Command::new("git")
1713        .args(["symbolic-ref", "--short", "HEAD"])
1714        .current_dir(main_checkout)
1715        .output()
1716    {
1717        if out.status.success() {
1718            let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
1719            if !branch.is_empty() {
1720                return Ok(Some(branch));
1721            }
1722        }
1723    }
1724    Err(format!(
1725        "cannot read the current branch of {}",
1726        main_checkout.display()
1727    ))
1728}
1729
1730fn repo_name_for(root: &Path) -> Result<String, String> {
1731    root.file_name()
1732        .and_then(|s| s.to_str())
1733        .filter(|s| !s.is_empty())
1734        .map(String::from)
1735        .ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
1736}
1737
1738fn now_duration() -> Result<Duration, String> {
1739    SystemTime::now()
1740        .duration_since(UNIX_EPOCH)
1741        .map_err(|e| format!("system clock is before Unix epoch: {e}"))
1742}
1743
1744fn new_session_id(nanos: u128) -> String {
1745    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1746    format!("surface-{}-{nanos}-{seq}", std::process::id())
1747}
1748
1749pub fn open_browser_in(open_in: OpenIn, url: &str) {
1750    crate::open_window::open_url(open_in, url);
1751}
1752
1753pub fn open_browser(url: &str) {
1754    open_browser_in(OpenIn::App, url);
1755}
1756
1757fn resolve_initial_model(config: &ReplConfig) -> String {
1758    if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
1759        return m.to_string();
1760    }
1761    if let Ok(m) = std::env::var("BLYTE_MODEL") {
1762        if !m.trim().is_empty() {
1763            return m;
1764        }
1765    }
1766    if let Ok(p) = blyte_provider::resolve_provider(None) {
1767        return p.model_id();
1768    }
1769    "gemini-3.8-flash-high".to_string()
1770}
1771
1772static SIGNAL_STOP: AtomicBool = AtomicBool::new(false);
1773static SIGNAL_INTERRUPT: AtomicBool = AtomicBool::new(false);
1774
1775#[cfg(unix)]
1776extern "C" fn handle_shutdown_signal(_: libc::c_int) {
1777    SIGNAL_STOP.store(true, Ordering::Relaxed);
1778}
1779
1780#[cfg(unix)]
1781extern "C" fn handle_interrupt_signal(_: libc::c_int) {
1782    SIGNAL_INTERRUPT.store(true, Ordering::Relaxed);
1783}
1784
1785fn ensure_token_dir(dir: &Path) -> Result<(), String> {
1786    #[cfg(unix)]
1787    {
1788        use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
1789        if let Some(parent) = dir.parent() {
1790            std::fs::create_dir_all(parent)
1791                .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
1792        }
1793        let mut builder = std::fs::DirBuilder::new();
1794        builder.mode(0o700);
1795        match builder.create(dir) {
1796            Ok(()) => {}
1797            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1798                std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
1799                    .map_err(|e| format!("cannot set permissions on {}: {e}", dir.display()))?;
1800            }
1801            Err(e) => return Err(format!("cannot create {}: {e}", dir.display())),
1802        }
1803        Ok(())
1804    }
1805    #[cfg(not(unix))]
1806    {
1807        std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))
1808    }
1809}
1810
1811fn write_token_file(token_file_path: &Path, token: &str) -> Result<(), String> {
1812    let token_dir = token_file_path
1813        .parent()
1814        .ok_or_else(|| format!("invalid token path {}", token_file_path.display()))?;
1815    ensure_token_dir(token_dir)?;
1816    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1817    let tmp_path = token_dir.join(format!(".surface.token.{}.{seq}.tmp", std::process::id()));
1818    let mut opts = std::fs::OpenOptions::new();
1819    opts.write(true).create_new(true);
1820    #[cfg(unix)]
1821    {
1822        opts.mode(0o600);
1823    }
1824    let mut file = opts
1825        .open(&tmp_path)
1826        .map_err(|e| format!("cannot create {}: {e}", token_file_path.display()))?;
1827    if let Err(e) = writeln!(file, "{token}") {
1828        let _ = std::fs::remove_file(&tmp_path);
1829        return Err(format!("cannot write {}: {e}", token_file_path.display()));
1830    }
1831    drop(file);
1832    if let Err(e) = std::fs::rename(&tmp_path, token_file_path) {
1833        let _ = std::fs::remove_file(&tmp_path);
1834        return Err(format!("cannot write {}: {e}", token_file_path.display()));
1835    }
1836    Ok(())
1837}
1838
1839struct TokenFileGuard {
1840    path: Option<PathBuf>,
1841}
1842
1843impl TokenFileGuard {
1844    fn new(path: PathBuf) -> Self {
1845        Self { path: Some(path) }
1846    }
1847
1848    fn disarm(&mut self) {
1849        self.path = None;
1850    }
1851}
1852
1853impl Drop for TokenFileGuard {
1854    fn drop(&mut self) {
1855        if let Some(ref path) = self.path {
1856            let _ = std::fs::remove_file(path);
1857        }
1858    }
1859}
1860
1861struct RegistryEntryGuard {
1862    dir: PathBuf,
1863    id: String,
1864}
1865
1866impl Drop for RegistryEntryGuard {
1867    fn drop(&mut self) {
1868        let _ = crate::surface_registry::remove_entry(&self.dir, &self.id);
1869    }
1870}
1871
1872struct PrivateTmpDirGuard {
1873    path: PathBuf,
1874}
1875
1876impl Drop for PrivateTmpDirGuard {
1877    fn drop(&mut self) {
1878        let _ = std::fs::remove_dir_all(&self.path);
1879    }
1880}
1881
1882struct PublishToolGuard;
1883
1884impl PublishToolGuard {
1885    fn install(surface: Arc<Surface>) -> Self {
1886        blyte_agent::tools::set_publish_tool(Some(Arc::new(
1887            crate::requests::SurfacePublishTool::new(surface),
1888        )));
1889        Self
1890    }
1891}
1892
1893impl Drop for PublishToolGuard {
1894    fn drop(&mut self) {
1895        blyte_agent::tools::set_publish_tool(None);
1896    }
1897}
1898
1899struct LandToolGuard;
1900
1901impl LandToolGuard {
1902    fn install(surface: Arc<Surface>) -> Self {
1903        blyte_agent::tools::set_land_tool(Some(Arc::new(crate::land::SurfaceLandTool::new(
1904            surface,
1905        ))));
1906        Self
1907    }
1908}
1909
1910impl Drop for LandToolGuard {
1911    fn drop(&mut self) {
1912        blyte_agent::tools::set_land_tool(None);
1913    }
1914}
1915
1916pub struct FrontEndContext {
1917    pub surface: Arc<Surface>,
1918    pub take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
1919}
1920
1921pub type FrontEnd = Box<dyn FnOnce(FrontEndContext) -> i32 + Send>;
1922
1923struct FrontEndSpec {
1924    front: FrontEnd,
1925    take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
1926}
1927
1928#[derive(Clone, Copy)]
1929enum FrontEndOutcome {
1930    Exited(i32),
1931    Panicked,
1932}
1933
1934struct StopControl<S> {
1935    should_stop: S,
1936    trigger: StopTrigger,
1937}
1938
1939fn atomic_stop_control(stop: Arc<AtomicBool>) -> StopControl<impl Fn() -> bool> {
1940    let stop_trigger_flag = Arc::clone(&stop);
1941    StopControl {
1942        should_stop: move || stop.load(Ordering::Acquire),
1943        trigger: Arc::new(move || stop_trigger_flag.store(true, Ordering::Release)),
1944    }
1945}
1946
1947pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
1948    SIGNAL_STOP.store(false, Ordering::Relaxed);
1949    #[cfg(unix)]
1950    unsafe {
1951        libc::signal(
1952            libc::SIGINT,
1953            handle_shutdown_signal as *const () as libc::sighandler_t,
1954        );
1955        libc::signal(
1956            libc::SIGTERM,
1957            handle_shutdown_signal as *const () as libc::sighandler_t,
1958        );
1959    }
1960    let open_in = args.open_in;
1961    let mut opener = |url: &str| open_browser_in(open_in, url);
1962    let stop_control = StopControl {
1963        should_stop: || SIGNAL_STOP.load(Ordering::Acquire),
1964        trigger: Arc::new(|| SIGNAL_STOP.store(true, Ordering::Release)),
1965    };
1966    run_inner(
1967        args,
1968        config,
1969        &mut std::io::stdout(),
1970        &mut std::io::stderr(),
1971        &mut opener,
1972        stop_control,
1973        None,
1974        None,
1975    )
1976}
1977
1978pub fn run_terminal(args: &SurfaceArgs, config: ReplConfig) -> i32 {
1979    run_with_front_end(
1980        args,
1981        config,
1982        Box::new(|ctx| {
1983            let stdin = std::io::stdin();
1984            let input_is_terminal = std::io::IsTerminal::is_terminal(&stdin);
1985            let mut stdout = std::io::stdout();
1986            let root = ctx.surface.root.clone();
1987            let options = crate::terminal_front::TerminalOptions {
1988                input_is_terminal,
1989                settle: Duration::from_secs(3),
1990                take_interrupt: ctx.take_interrupt,
1991                runs_working: Arc::new(move || crate::surfaces_cmd::count_running_runs(&root)),
1992            };
1993            crate::terminal_front::run_terminal_front(
1994                &ctx.surface.session,
1995                Box::new(std::io::BufReader::new(stdin)),
1996                &mut stdout,
1997                options,
1998            )
1999        }),
2000    )
2001}
2002
2003pub fn run_with_front_end(args: &SurfaceArgs, config: ReplConfig, front: FrontEnd) -> i32 {
2004    SIGNAL_STOP.store(false, Ordering::Relaxed);
2005    SIGNAL_INTERRUPT.store(false, Ordering::Relaxed);
2006    #[cfg(unix)]
2007    unsafe {
2008        libc::signal(
2009            libc::SIGINT,
2010            handle_interrupt_signal as *const () as libc::sighandler_t,
2011        );
2012        libc::signal(
2013            libc::SIGTERM,
2014            handle_shutdown_signal as *const () as libc::sighandler_t,
2015        );
2016    }
2017    let mut opener = |_: &str| {};
2018    let stop_control = StopControl {
2019        should_stop: || SIGNAL_STOP.load(Ordering::Acquire),
2020        trigger: Arc::new(|| SIGNAL_STOP.store(true, Ordering::Release)),
2021    };
2022    let take_interrupt: Arc<dyn Fn() -> bool + Send + Sync> =
2023        Arc::new(|| SIGNAL_INTERRUPT.swap(false, Ordering::AcqRel));
2024    run_inner(
2025        args,
2026        config,
2027        &mut std::io::stdout(),
2028        &mut std::io::stderr(),
2029        &mut opener,
2030        stop_control,
2031        None,
2032        Some(FrontEndSpec {
2033            front,
2034            take_interrupt,
2035        }),
2036    )
2037}
2038
2039pub fn run_with_io(
2040    args: &SurfaceArgs,
2041    config: ReplConfig,
2042    out: &mut dyn Write,
2043    err: &mut dyn Write,
2044) -> i32 {
2045    let open_in = args.open_in;
2046    let mut opener = |url: &str| open_browser_in(open_in, url);
2047    let stop = Arc::new(AtomicBool::new(false));
2048    run_inner(
2049        args,
2050        config,
2051        out,
2052        err,
2053        &mut opener,
2054        atomic_stop_control(stop),
2055        None,
2056        None,
2057    )
2058}
2059
2060pub fn run_with_hooks(
2061    args: &SurfaceArgs,
2062    config: ReplConfig,
2063    out: &mut dyn Write,
2064    err: &mut dyn Write,
2065    opener: &mut dyn FnMut(&str),
2066    stop: Arc<AtomicBool>,
2067) -> i32 {
2068    run_inner(
2069        args,
2070        config,
2071        out,
2072        err,
2073        opener,
2074        atomic_stop_control(stop),
2075        None,
2076        None,
2077    )
2078}
2079
2080pub type RunnerFactory = Box<
2081    dyn FnOnce(
2082        &ReplConfig,
2083        Arc<dyn blyte_agent::approval::Approver>,
2084    ) -> Result<(Box<dyn PromptRunner>, Option<PathBuf>), String>,
2085>;
2086
2087pub fn run_with_runner(
2088    args: &SurfaceArgs,
2089    config: ReplConfig,
2090    out: &mut dyn Write,
2091    err: &mut dyn Write,
2092    opener: &mut dyn FnMut(&str),
2093    stop: Arc<AtomicBool>,
2094    runner: Box<dyn PromptRunner>,
2095) -> i32 {
2096    run_inner(
2097        args,
2098        config,
2099        out,
2100        err,
2101        opener,
2102        atomic_stop_control(stop),
2103        Some(Box::new(|_, _| Ok((runner, None)))),
2104        None,
2105    )
2106}
2107
2108#[allow(clippy::too_many_arguments)]
2109pub fn run_with_front_end_and_runner(
2110    args: &SurfaceArgs,
2111    config: ReplConfig,
2112    out: &mut dyn Write,
2113    err: &mut dyn Write,
2114    stop: Arc<AtomicBool>,
2115    take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
2116    runner: Box<dyn PromptRunner>,
2117    front: FrontEnd,
2118) -> i32 {
2119    let mut opener = |_: &str| {};
2120    run_inner(
2121        args,
2122        config,
2123        out,
2124        err,
2125        &mut opener,
2126        atomic_stop_control(stop),
2127        Some(Box::new(|_, _| Ok((runner, None)))),
2128        Some(FrontEndSpec {
2129            front,
2130            take_interrupt,
2131        }),
2132    )
2133}
2134
2135pub fn run_with_runner_factory(
2136    args: &SurfaceArgs,
2137    config: ReplConfig,
2138    out: &mut dyn Write,
2139    err: &mut dyn Write,
2140    opener: &mut dyn FnMut(&str),
2141    stop: Arc<AtomicBool>,
2142    factory: RunnerFactory,
2143) -> i32 {
2144    run_inner(
2145        args,
2146        config,
2147        out,
2148        err,
2149        opener,
2150        atomic_stop_control(stop),
2151        Some(factory),
2152        None,
2153    )
2154}
2155
2156struct ReconcileTimerGuard {
2157    stop: Arc<AtomicBool>,
2158    handle: Option<std::thread::JoinHandle<()>>,
2159}
2160
2161impl Drop for ReconcileTimerGuard {
2162    fn drop(&mut self) {
2163        self.stop.store(true, Ordering::Release);
2164        if let Some(handle) = self.handle.take() {
2165            let _ = handle.join();
2166        }
2167    }
2168}
2169
2170fn spawn_reconcile_timer(surface: Arc<Surface>) -> ReconcileTimerGuard {
2171    let stop = Arc::new(AtomicBool::new(false));
2172    let thread_stop = Arc::clone(&stop);
2173    let handle = std::thread::spawn(move || {
2174        let mut after = surface.session.info().last_seq;
2175        let mut next_tick = Instant::now();
2176        let mut seen_errors: HashSet<String> = HashSet::new();
2177        while !thread_stop.load(Ordering::Acquire) {
2178            let wait = if surface.reconcile_requested.load(Ordering::Acquire) {
2179                Duration::ZERO
2180            } else {
2181                next_tick
2182                    .saturating_duration_since(Instant::now())
2183                    .min(RECONCILE_POLL_WAIT)
2184            };
2185            let entries = surface.session.entries_after(after, wait);
2186            let mut went_idle = false;
2187            for entry in entries {
2188                after = entry.seq;
2189                if matches!(entry.body, EntryBody::Idle { .. }) {
2190                    went_idle = true;
2191                }
2192            }
2193            if thread_stop.load(Ordering::Acquire) {
2194                break;
2195            }
2196            let requested = surface.reconcile_requested.swap(false, Ordering::AcqRel);
2197            if went_idle || requested || Instant::now() >= next_tick {
2198                match now_duration().and_then(|d| reconcile_runs(&surface, d.as_secs())) {
2199                    Ok((_, errors)) => {
2200                        for msg in errors {
2201                            if seen_errors.insert(msg.clone()) {
2202                                surface.session.record_error(&msg);
2203                                eprintln!("blyte: {msg}");
2204                            }
2205                        }
2206                    }
2207                    Err(e) => {
2208                        if seen_errors.insert(e.clone()) {
2209                            eprintln!("blyte: {e}");
2210                        }
2211                    }
2212                }
2213                next_tick = Instant::now() + RECONCILE_SAFETY_NET_INTERVAL;
2214            }
2215        }
2216    });
2217    ReconcileTimerGuard {
2218        stop,
2219        handle: Some(handle),
2220    }
2221}
2222
2223#[allow(clippy::too_many_arguments)]
2224fn run_inner<S>(
2225    args: &SurfaceArgs,
2226    mut config: ReplConfig,
2227    out: &mut dyn Write,
2228    err: &mut dyn Write,
2229    opener: &mut dyn FnMut(&str),
2230    stop_control: StopControl<S>,
2231    custom_runner: Option<RunnerFactory>,
2232    front_end: Option<FrontEndSpec>,
2233) -> i32
2234where
2235    S: Fn() -> bool,
2236{
2237    let StopControl {
2238        should_stop,
2239        trigger: stop_trigger,
2240    } = stop_control;
2241    let (main_checkout, is_repo) = match find_git_toplevel(&config.repo_root) {
2242        Ok(GitToplevel::Repository(worktree_root)) => {
2243            let main = match resolve_main_checkout(&worktree_root) {
2244                Ok(m) => m,
2245                Err(e) => {
2246                    let _ = writeln!(err, "blyte: {e}");
2247                    return 1;
2248                }
2249            };
2250            let same_checkout = match (worktree_root.canonicalize(), main.canonicalize()) {
2251                (Ok(a), Ok(b)) => a == b,
2252                _ => worktree_root == main,
2253            };
2254            if !same_checkout {
2255                let _ = writeln!(
2256                    err,
2257                    "blyte: started in a linked worktree ({}); this surface works in the main checkout {}",
2258                    worktree_root.display(),
2259                    main.display()
2260                );
2261                let _ = err.flush();
2262            }
2263            (main, true)
2264        }
2265        Ok(GitToplevel::NotARepository) => {
2266            let canonical = match config.repo_root.canonicalize() {
2267                Ok(c) => c,
2268                Err(e) => {
2269                    let _ = writeln!(
2270                        err,
2271                        "blyte: cannot canonicalize {}: {e}",
2272                        config.repo_root.display()
2273                    );
2274                    return 1;
2275                }
2276            };
2277            (canonical, false)
2278        }
2279        Err(e) => {
2280            let _ = writeln!(err, "blyte: {e}");
2281            return 1;
2282        }
2283    };
2284
2285    let repo = match repo_name_for(&main_checkout) {
2286        Ok(r) => r,
2287        Err(e) => {
2288            let _ = writeln!(err, "blyte: {e}");
2289            return 1;
2290        }
2291    };
2292
2293    #[cfg(target_os = "linux")]
2294    if !is_repo {
2295        if let Err(e) =
2296            check_linux_non_repo_root_for_env(&main_checkout, std::env::var_os("HOME").as_deref())
2297        {
2298            let _ = writeln!(err, "blyte: {e}");
2299            return 1;
2300        }
2301    }
2302
2303    let state_dir = match crate::surface_registry::state_dir() {
2304        Ok(d) => d,
2305        Err(e) => {
2306            let _ = writeln!(err, "blyte: {e}");
2307            return 1;
2308        }
2309    };
2310    let registry_dir = state_dir.join("surfaces");
2311
2312    let all_records =
2313        match crate::surface_dir::list_records_for_root(&main_checkout, Some(&state_dir)) {
2314            Ok(r) => r,
2315            Err(e) => {
2316                let _ = writeln!(err, "blyte: {e}");
2317                return 1;
2318            }
2319        };
2320    let mut running = Vec::new();
2321    let mut stopped = Vec::new();
2322    for located in all_records {
2323        if crate::surface_dir::is_running(&located.record) {
2324            running.push(located);
2325        } else {
2326            stopped.push(located);
2327        }
2328    }
2329
2330    let live_registry = match crate::surface_registry::live_entries(&registry_dir) {
2331        Ok(listing) => {
2332            crate::surface_registry::report_unreadable(&listing.unreadable, err);
2333            listing.entries
2334        }
2335        Err(e) => {
2336            let _ = writeln!(err, "blyte: {e}");
2337            return 1;
2338        }
2339    };
2340    let mut running_names: Vec<String> = running.iter().map(|r| r.record.name.clone()).collect();
2341    for entry in &live_registry {
2342        if !running_names.iter().any(|n| n == &entry.name) {
2343            running_names.push(entry.name.clone());
2344        }
2345    }
2346
2347    let (surface_id, surface_name, surface_record_dir) = if let Some(ref target) = args.resume {
2348        if let Some(located) = running
2349            .iter()
2350            .find(|r| r.record.id == *target || r.record.name == *target)
2351        {
2352            let _ = writeln!(
2353                err,
2354                "blyte: surface {target} is already running (port {})",
2355                located.record.port
2356            );
2357            return 1;
2358        }
2359        let stopped_matches: Vec<&crate::surface_dir::LocatedRecord> = stopped
2360            .iter()
2361            .filter(|r| r.record.id == *target || r.record.name == *target)
2362            .collect();
2363        if stopped_matches.is_empty() {
2364            let _ = writeln!(
2365                err,
2366                "blyte: no stopped surface named {target} in {}",
2367                main_checkout.display()
2368            );
2369            return 1;
2370        }
2371        if stopped_matches.len() > 1 {
2372            let ids: Vec<&str> = stopped_matches
2373                .iter()
2374                .map(|r| r.record.id.as_str())
2375                .collect();
2376            let _ = writeln!(
2377                err,
2378                "blyte: more than one stopped surface is named {target}; resume by id: {}",
2379                ids.join(", ")
2380            );
2381            return 1;
2382        }
2383        let located = stopped_matches[0];
2384        if running_names.iter().any(|n| n == &located.record.name) {
2385            let _ = writeln!(
2386                err,
2387                "blyte: a running surface is already named {}; stop it or resume by another name",
2388                located.record.name
2389            );
2390            return 1;
2391        }
2392        (
2393            located.record.id.clone(),
2394            located.record.name.clone(),
2395            located.dir.clone(),
2396        )
2397    } else {
2398        let id = match crate::surface_dir::new_surface_id() {
2399            Ok(id) => id,
2400            Err(e) => {
2401                let _ = writeln!(err, "blyte: {e}");
2402                return 1;
2403            }
2404        };
2405        let name = match crate::surface_dir::pick_name(&repo, args.name.as_deref(), &running_names)
2406        {
2407            Ok(name) => name,
2408            Err(e) => {
2409                let _ = writeln!(err, "blyte: {e}");
2410                return 1;
2411            }
2412        };
2413        let record_dir = if is_repo {
2414            crate::surface_dir::surface_dir(&main_checkout, &id)
2415        } else {
2416            let store = match crate::surface_dir::folder_store(&state_dir, &main_checkout) {
2417                Ok(store) => store,
2418                Err(e) => {
2419                    let _ = writeln!(err, "blyte: {e}");
2420                    return 1;
2421                }
2422            };
2423            store.join("surfaces").join(&id)
2424        };
2425        (id, name, record_dir)
2426    };
2427
2428    let branch = match current_branch(&main_checkout) {
2429        Ok(b) => b,
2430        Err(e) => {
2431            let _ = writeln!(err, "blyte: {e}");
2432            return 1;
2433        }
2434    };
2435
2436    if !config.converse {
2437        config.converse = true;
2438        if config.max_turns == 25 || config.max_turns == 60 {
2439            config.max_turns = 1000;
2440        }
2441        if config.fold_budget.is_none() {
2442            config.fold_budget = Some(100_000);
2443        }
2444    }
2445    config.repo_root = main_checkout.clone();
2446
2447    let is_resume = args.resume.is_some();
2448    let model = resolve_initial_model(&config);
2449    let conversation_path = match crate::conversation_store::conversation_path_for_id(&surface_id) {
2450        Ok(p) => p,
2451        Err(e) => {
2452            let _ = writeln!(err, "blyte: {e}");
2453            let _ = err.flush();
2454            return 1;
2455        }
2456    };
2457    let (mut conversation_store, mut loaded_conversation) = if is_resume {
2458        match crate::conversation_store::ConversationStore::load(conversation_path) {
2459            Ok(pair) => pair,
2460            Err(e) => {
2461                let _ = writeln!(err, "blyte: {e}");
2462                let _ = err.flush();
2463                return 1;
2464            }
2465        }
2466    } else {
2467        match crate::conversation_store::ConversationStore::new_for_fresh(conversation_path) {
2468            Ok(store) => (store, None),
2469            Err(e) => {
2470                let _ = writeln!(err, "blyte: {e}");
2471                let _ = err.flush();
2472                return 1;
2473            }
2474        }
2475    };
2476    let (resume_memory, needs_digest_rewrite) = match loaded_conversation.as_mut() {
2477        Some(loaded) if !loaded.messages.is_empty() => {
2478            if crate::conversation_store::digest_for_provider_in_memory(loaded, &model) {
2479                (crate::session::ResumeMemoryState::Summarized, true)
2480            } else {
2481                (crate::session::ResumeMemoryState::Loaded, false)
2482            }
2483        }
2484        _ => (crate::session::ResumeMemoryState::NotLoaded, false),
2485    };
2486
2487    let started_dur = match now_duration() {
2488        Ok(d) => d,
2489        Err(e) => {
2490            let _ = writeln!(err, "blyte: {e}");
2491            return 1;
2492        }
2493    };
2494    let started_at = started_dur.as_secs();
2495    let session_id = new_session_id(started_dur.as_nanos());
2496    if std::env::var("BLYTE_SESSION")
2497        .map(|v| v.is_empty())
2498        .unwrap_or(true)
2499    {
2500        std::env::set_var("BLYTE_SESSION", &session_id);
2501    }
2502    std::env::set_var(crate::usage_log::SURFACE_ID_ENV, &surface_id);
2503    std::env::set_var(crate::usage_log::SURFACE_NAME_ENV, &surface_name);
2504
2505    let token_file_path = match blyte_agent::sandbox::surface_token_path_for_id(&surface_id) {
2506        Ok(p) => p,
2507        Err(e) => {
2508            let _ = writeln!(err, "blyte: {e}");
2509            return 1;
2510        }
2511    };
2512    let reuse_token_requested = std::env::var_os(RELOAD_REUSE_TOKEN_ENV).is_some();
2513    if reuse_token_requested {
2514        std::env::remove_var(RELOAD_REUSE_TOKEN_ENV);
2515    }
2516    let token = if is_resume && reuse_token_requested {
2517        match read_reused_token_file(&token_file_path) {
2518            Ok(t) => t,
2519            Err(e) => {
2520                let _ = writeln!(err, "blyte: {e}");
2521                return 1;
2522            }
2523        }
2524    } else {
2525        match generate_token() {
2526            Ok(t) => t,
2527            Err(e) => {
2528                let _ = writeln!(err, "blyte: {e}");
2529                return 1;
2530            }
2531        }
2532    };
2533    let message_credential = match generate_token() {
2534        Ok(t) => t,
2535        Err(e) => {
2536            let _ = writeln!(err, "blyte: {e}");
2537            return 1;
2538        }
2539    };
2540
2541    let bind_addr = format!("127.0.0.1:{}", args.port);
2542    let listener = match TcpListener::bind(&bind_addr) {
2543        Ok(l) => l,
2544        Err(e) => {
2545            let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
2546            return 1;
2547        }
2548    };
2549    let actual_port = match listener.local_addr() {
2550        Ok(a) => a.port(),
2551        Err(e) => {
2552            let _ = writeln!(err, "blyte: failed to read listener address: {e}");
2553            return 1;
2554        }
2555    };
2556
2557    if let Err(e) = write_token_file(&token_file_path, &token) {
2558        let _ = writeln!(err, "blyte: {e}");
2559        return 1;
2560    }
2561    let mut token_guard = TokenFileGuard::new(token_file_path.clone());
2562
2563    let message_file_path = match blyte_agent::sandbox::surface_message_path_for_id(&surface_id) {
2564        Ok(p) => p,
2565        Err(e) => {
2566            let _ = writeln!(err, "blyte: {e}");
2567            return 1;
2568        }
2569    };
2570    if let Err(e) = write_token_file(&message_file_path, &message_credential) {
2571        let _ = writeln!(err, "blyte: {e}");
2572        return 1;
2573    }
2574    let _message_guard = TokenFileGuard::new(message_file_path);
2575
2576    let mut starting_dir_guard = if is_resume {
2577        StartingDirGuard { dir: None }
2578    } else {
2579        if let Err(e) = crate::surface_dir::prepare_starting_dir(&surface_record_dir) {
2580            let _ = writeln!(err, "blyte: {e}");
2581            return 1;
2582        }
2583        StartingDirGuard {
2584            dir: Some(surface_record_dir.clone()),
2585        }
2586    };
2587    let attachments_dir = match prepare_attachments_dir(&surface_record_dir) {
2588        Ok(p) => p,
2589        Err(e) => {
2590            let _ = writeln!(err, "blyte: {e}");
2591            return 1;
2592        }
2593    };
2594    let mut read_roots = blyte_agent::tools::read_roots();
2595    if !read_roots.iter().any(|p| p == &attachments_dir) {
2596        read_roots.push(attachments_dir.clone());
2597        blyte_agent::tools::set_read_roots(read_roots);
2598    }
2599    let original_allow_read = config.allow_read.clone();
2600    if !config.allow_read.iter().any(|p| p == &attachments_dir) {
2601        config.allow_read.push(attachments_dir);
2602    }
2603    blyte_agent::tools::set_peer_tools(Some(Arc::new(crate::tell::SurfacePeerTools {
2604        registry_dir: registry_dir.clone(),
2605        surface_id: surface_id.clone(),
2606        surface_name: surface_name.clone(),
2607        repository: repo.clone(),
2608    })));
2609    let entries_log_path = surface_record_dir.join("entries.jsonl");
2610    blyte_agent::tools::set_blyte_surface(Some(surface_id.clone()));
2611    let mut _private_tmp_guard: Option<PrivateTmpDirGuard> = None;
2612    let session = match Session::try_start_with_log_and_resume_io(
2613        model,
2614        Some(entries_log_path),
2615        resume_memory,
2616        err,
2617        |approver| match custom_runner {
2618            Some(factory) => {
2619                let (runner, tmpdir) = factory(&config, approver)?;
2620                _private_tmp_guard = tmpdir.map(|path| PrivateTmpDirGuard { path });
2621                if needs_digest_rewrite {
2622                    if let Some(ref loaded) = loaded_conversation {
2623                        conversation_store.rewrite(
2624                            loaded.model.as_deref(),
2625                            loaded.goal.as_deref(),
2626                            &loaded.messages,
2627                        )?;
2628                    }
2629                }
2630                Ok(runner)
2631            }
2632            None => {
2633                let rewrite_payload = if needs_digest_rewrite {
2634                    loaded_conversation.clone()
2635                } else {
2636                    None
2637                };
2638                let mut runner = AgentRunner::try_new_with_conversation(
2639                    &config,
2640                    approver,
2641                    None,
2642                    loaded_conversation,
2643                )?;
2644                _private_tmp_guard = runner.private_tmpdir().map(|path| PrivateTmpDirGuard {
2645                    path: path.to_path_buf(),
2646                });
2647                if let Some(ref loaded) = rewrite_payload {
2648                    conversation_store.rewrite(
2649                        loaded.model.as_deref(),
2650                        loaded.goal.as_deref(),
2651                        &loaded.messages,
2652                    )?;
2653                }
2654                runner.set_conversation_store(conversation_store);
2655                Ok(Box::new(runner) as Box<dyn crate::session::PromptRunner>)
2656            }
2657        },
2658    ) {
2659        Ok(s) => s,
2660        Err(e) => {
2661            let _ = writeln!(err, "blyte: {e}");
2662            let _ = err.flush();
2663            return 1;
2664        }
2665    };
2666    let runtime = match crate::surface_version::SurfaceRuntimeInfo::current() {
2667        Ok(info) => info,
2668        Err(e) => {
2669            let _ = writeln!(err, "blyte: {e}");
2670            let _ = err.flush();
2671            return 1;
2672        }
2673    };
2674    let record = SurfaceRecord {
2675        id: surface_id.clone(),
2676        name: surface_name.clone(),
2677        pid: std::process::id(),
2678        port: actual_port,
2679        session_id: session_id.clone(),
2680        started_at,
2681        runtime: runtime.clone(),
2682    };
2683    if let Err(e) = crate::surface_dir::write_record_in(&surface_record_dir, &record) {
2684        let _ = writeln!(err, "blyte: {e}");
2685        return 1;
2686    }
2687    starting_dir_guard.disarm();
2688    let registry_entry = crate::surface_registry::RegistryEntry {
2689        id: surface_id.clone(),
2690        name: surface_name.clone(),
2691        root: main_checkout.clone(),
2692        branch,
2693        pid: std::process::id(),
2694        port: actual_port,
2695        started_at,
2696        doing: "idle".to_string(),
2697        state: crate::surface_registry::SurfaceState::Idle,
2698        runtime: runtime.clone(),
2699    };
2700    if let Err(e) = crate::surface_registry::write_entry(&registry_dir, &registry_entry) {
2701        let _ = writeln!(err, "blyte: {e}");
2702        return 1;
2703    }
2704    let _registry_guard = RegistryEntryGuard {
2705        dir: registry_dir.clone(),
2706        id: surface_id.clone(),
2707    };
2708    let hook_dir = registry_dir.clone();
2709    let hook_entry = registry_entry.clone();
2710    session.set_activity_hook(Box::new(move |prompt, state| {
2711        let doing = match prompt {
2712            Some(text) => {
2713                let line = crate::surface_registry::first_line(text);
2714                if line.is_empty() {
2715                    "working".to_string()
2716                } else {
2717                    line
2718                }
2719            }
2720            None => "idle".to_string(),
2721        };
2722        // The whole entry is written, not only the changed field: another process removes an
2723        // entry whose surface did not answer its health check in time, and this puts it back.
2724        let branch = match current_branch(&hook_entry.root) {
2725            Ok(b) => b,
2726            Err(e) => {
2727                eprintln!("blyte: {e}");
2728                return;
2729            }
2730        };
2731        let entry = crate::surface_registry::RegistryEntry {
2732            branch,
2733            doing,
2734            state,
2735            ..hook_entry.clone()
2736        };
2737        if let Err(e) = crate::surface_registry::write_entry(&hook_dir, &entry) {
2738            eprintln!("blyte: {e}");
2739        }
2740    }));
2741
2742    if !is_repo {
2743        let _ = writeln!(
2744            err,
2745            "blyte: {} is not a git repository: runs edit this folder in place; combining and publishing are off",
2746            main_checkout.display()
2747        );
2748        let _ = err.flush();
2749    }
2750
2751    let open_codes = OpenCodes::new();
2752    let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
2753    let _ = writeln!(out, "blyte: surface {surface_name} at {url}");
2754    let _ = out.flush();
2755    if !args.no_open && front_end.is_none() {
2756        match issue_initial_open_code(&open_codes, now_duration()) {
2757            Ok(code) => {
2758                let open_url = format!("http://127.0.0.1:{actual_port}/#open={code}");
2759                opener(&open_url);
2760            }
2761            Err(e) => {
2762                let _ = writeln!(err, "blyte: failed to create open code: {e}");
2763                let _ = err.flush();
2764            }
2765        }
2766    }
2767
2768    let stop_surface_name = surface_name.clone();
2769    let reload_surface_id = surface_id.clone();
2770    let reload_workdir = main_checkout.clone();
2771    let is_terminal = front_end.is_some();
2772
2773    let surface = Arc::new(Surface {
2774        surface_id,
2775        surface_name,
2776        root: main_checkout,
2777        repo,
2778        session,
2779        session_id,
2780        started_at,
2781        runtime,
2782        days: args.days,
2783        token,
2784        message_credential,
2785        open_codes,
2786        requests: Arc::new(RequestsState::new()),
2787        publisher: Arc::new(RealPublisher),
2788        reconcile_lock: Mutex::new(()),
2789        reconcile_requested: AtomicBool::new(false),
2790    });
2791
2792    let timer_guard = spawn_reconcile_timer(Arc::clone(&surface));
2793    let _publish_tool_guard = PublishToolGuard::install(Arc::clone(&surface));
2794    let _land_tool_guard = LandToolGuard::install(Arc::clone(&surface));
2795
2796    let front_outcome = front_end.map(|spec| {
2797        let outcome = Arc::new(Mutex::new(None));
2798        let outcome_bg = Arc::clone(&outcome);
2799        let surface_bg = Arc::clone(&surface);
2800        let stop_trigger_bg = Arc::clone(&stop_trigger);
2801        std::thread::spawn(move || {
2802            let ctx = FrontEndContext {
2803                surface: surface_bg,
2804                take_interrupt: spec.take_interrupt,
2805            };
2806            let result =
2807                std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || (spec.front)(ctx)));
2808            let value = match result {
2809                Ok(code) => FrontEndOutcome::Exited(code),
2810                Err(_) => FrontEndOutcome::Panicked,
2811            };
2812            *outcome_bg.lock().unwrap_or_else(|e| e.into_inner()) = Some(value);
2813            stop_trigger_bg();
2814        });
2815        outcome
2816    });
2817
2818    let reload_requested = Arc::new(AtomicBool::new(false));
2819    let reload_trigger = ReloadTrigger {
2820        requested: Arc::clone(&reload_requested),
2821        stop: Arc::clone(&stop_trigger),
2822    };
2823    let surface_for_reload = Arc::clone(&surface);
2824
2825    let serve_result =
2826        crate::http::serve_until(listener, should_stop, move |req| match now_duration() {
2827            Ok(d) => route_inner(
2828                &surface,
2829                req,
2830                d.as_secs(),
2831                Some(&stop_trigger),
2832                Some(&reload_trigger),
2833            ),
2834            Err(e) => json_error(500, e),
2835        });
2836
2837    drop(_land_tool_guard);
2838    drop(_publish_tool_guard);
2839    drop(timer_guard);
2840
2841    if serve_result.is_ok() && reload_requested.load(Ordering::SeqCst) {
2842        let current_model = surface_for_reload.session.info().model;
2843        let exec_path = surface_for_reload.runtime.binary_fingerprint.path.clone();
2844        drop(surface_for_reload);
2845        drop(_registry_guard);
2846        drop(_message_guard);
2847        drop(_private_tmp_guard);
2848        if let Err(e) = crate::surface_version::verify_executable(&exec_path) {
2849            let _ = writeln!(err, "blyte: reload failed: {e}");
2850            let _ = err.flush();
2851            return 1;
2852        }
2853        let reload_args = build_reload_args(
2854            &reload_surface_id,
2855            actual_port,
2856            args,
2857            &config,
2858            &original_allow_read,
2859            &current_model,
2860            is_terminal,
2861        );
2862        let _ = writeln!(
2863            out,
2864            "blyte: reloading surface {stop_surface_name} with {}",
2865            exec_path.display()
2866        );
2867        let _ = out.flush();
2868        token_guard.disarm();
2869        return exec_reload(
2870            &exec_path,
2871            &reload_args,
2872            &reload_workdir,
2873            &token_file_path,
2874            err,
2875        );
2876    }
2877
2878    drop(surface_for_reload);
2879
2880    match serve_result {
2881        Ok(()) => {
2882            let _ = writeln!(
2883                out,
2884                "blyte: stopped surface {stop_surface_name}; resume with: blyte --resume {stop_surface_name}"
2885            );
2886            let _ = out.flush();
2887            match front_outcome
2888                .as_ref()
2889                .and_then(|o| *o.lock().unwrap_or_else(|e| e.into_inner()))
2890            {
2891                Some(FrontEndOutcome::Exited(code)) => code,
2892                Some(FrontEndOutcome::Panicked) => {
2893                    let _ = writeln!(err, "blyte: the front end stopped unexpectedly");
2894                    let _ = err.flush();
2895                    1
2896                }
2897                None => 0,
2898            }
2899        }
2900        Err(e) => {
2901            let _ = writeln!(err, "blyte: server error: {e}");
2902            1
2903        }
2904    }
2905}
2906
2907fn issue_initial_open_code(
2908    open_codes: &OpenCodes,
2909    now: Result<Duration, String>,
2910) -> Result<String, String> {
2911    let now_secs = now?.as_secs();
2912    open_codes.issue(now_secs)
2913}
2914
2915fn canonicalize_attachments_dir(attachments_dir: &Path) -> Result<PathBuf, String> {
2916    std::fs::canonicalize(attachments_dir).map_err(|e| {
2917        format!(
2918            "failed to canonicalize attachments directory {}: {e}",
2919            attachments_dir.display()
2920        )
2921    })
2922}
2923
2924fn prepare_attachments_dir(surface_record_dir: &Path) -> Result<PathBuf, String> {
2925    let attachments_dir = crate::attachments::attachments_dir(surface_record_dir);
2926    std::fs::create_dir_all(&attachments_dir)
2927        .map_err(|e| format!("failed to create {}: {e}", attachments_dir.display()))?;
2928    canonicalize_attachments_dir(&attachments_dir)
2929}
2930
2931struct StartingDirGuard {
2932    dir: Option<PathBuf>,
2933}
2934
2935impl StartingDirGuard {
2936    fn disarm(&mut self) {
2937        self.dir = None;
2938    }
2939}
2940
2941impl Drop for StartingDirGuard {
2942    fn drop(&mut self) {
2943        if let Some(ref dir) = self.dir {
2944            crate::surface_dir::cleanup_starting_dir(dir);
2945        }
2946    }
2947}
2948
2949fn read_reused_token_file(path: &Path) -> Result<String, String> {
2950    let raw = std::fs::read_to_string(path)
2951        .map_err(|e| format!("cannot reuse surface token from {}: {e}", path.display()))?;
2952    let token = raw.trim().to_string();
2953    if token.is_empty() {
2954        return Err(format!(
2955            "surface token file {} is empty; cannot reuse token on reload",
2956            path.display()
2957        ));
2958    }
2959    Ok(token)
2960}
2961
2962pub fn build_reload_args(
2963    surface_id: &str,
2964    port: u16,
2965    args: &SurfaceArgs,
2966    config: &ReplConfig,
2967    allow_read: &[PathBuf],
2968    current_model: &str,
2969    is_terminal: bool,
2970) -> Vec<std::ffi::OsString> {
2971    use std::ffi::OsString;
2972
2973    let mut out: Vec<OsString> = vec![
2974        OsString::from("--resume"),
2975        OsString::from(surface_id),
2976        OsString::from("--port"),
2977        OsString::from(port.to_string()),
2978        OsString::from("--no-open"),
2979    ];
2980    if is_terminal {
2981        out.push(OsString::from("--terminal"));
2982    } else {
2983        out.push(OsString::from("--foreground"));
2984        let open_in = match args.open_in {
2985            OpenIn::App => "app",
2986            OpenIn::Browser => "browser",
2987        };
2988        out.push(OsString::from("--open-in"));
2989        out.push(OsString::from(open_in));
2990    }
2991    out.push(OsString::from("--days"));
2992    out.push(OsString::from(args.days.to_string()));
2993    if !current_model.trim().is_empty() {
2994        out.push(OsString::from("--model"));
2995        out.push(OsString::from(current_model));
2996    }
2997    if let Some(ref dispatch_cmd) = config.dispatch_cmd {
2998        out.push(OsString::from("--converse"));
2999        out.push(OsString::from("--dispatch-cmd"));
3000        out.push(OsString::from(dispatch_cmd));
3001    } else if let Some(ref gate) = config.gate {
3002        out.push(OsString::from("--gate"));
3003        out.push(OsString::from(gate));
3004    }
3005    out.push(OsString::from("--context"));
3006    out.push(OsString::from(&config.context_strategy));
3007    if let Some(ref container) = config.container {
3008        out.push(OsString::from("--container"));
3009        out.push(OsString::from(container));
3010    }
3011    out.push(OsString::from("--max-turns"));
3012    out.push(OsString::from(config.max_turns.to_string()));
3013    out.push(OsString::from("--max-gates"));
3014    out.push(OsString::from(config.max_gates.to_string()));
3015    out.push(OsString::from(format!("--rollback={}", config.rollback)));
3016    if let Some(fold_budget) = config.fold_budget {
3017        out.push(OsString::from("--fold-budget"));
3018        out.push(OsString::from(fold_budget.to_string()));
3019    }
3020    out.push(OsString::from("--sandbox"));
3021    out.push(OsString::from(&config.sandbox));
3022    if let Some(ref network) = config.network {
3023        out.push(OsString::from("--network"));
3024        out.push(OsString::from(network));
3025    }
3026    for path in allow_read {
3027        out.push(OsString::from("--allow-read"));
3028        out.push(path.as_os_str().to_os_string());
3029    }
3030    for var in &config.pass_env {
3031        out.push(OsString::from("--pass-env"));
3032        out.push(OsString::from(var));
3033    }
3034    out
3035}
3036
3037pub fn build_detached_args(args: &SurfaceArgs, config: &ReplConfig) -> Vec<std::ffi::OsString> {
3038    use std::ffi::OsString;
3039
3040    let mut out: Vec<OsString> = vec![
3041        OsString::from("--foreground"),
3042        OsString::from("--no-open"),
3043        OsString::from("--port"),
3044        OsString::from(args.port.to_string()),
3045    ];
3046    let open_in = match args.open_in {
3047        OpenIn::App => "app",
3048        OpenIn::Browser => "browser",
3049    };
3050    out.push(OsString::from("--open-in"));
3051    out.push(OsString::from(open_in));
3052    out.push(OsString::from("--days"));
3053    out.push(OsString::from(args.days.to_string()));
3054    if let Some(ref resume) = args.resume {
3055        out.push(OsString::from("--resume"));
3056        out.push(OsString::from(resume));
3057    } else if let Some(ref name) = args.name {
3058        out.push(OsString::from("--name"));
3059        out.push(OsString::from(name));
3060    }
3061    if let Some(ref model) = config.model {
3062        if !model.trim().is_empty() {
3063            out.push(OsString::from("--model"));
3064            out.push(OsString::from(model));
3065        }
3066    }
3067    if let Some(ref dispatch_cmd) = config.dispatch_cmd {
3068        out.push(OsString::from("--converse"));
3069        out.push(OsString::from("--dispatch-cmd"));
3070        out.push(OsString::from(dispatch_cmd));
3071    } else if let Some(ref gate) = config.gate {
3072        out.push(OsString::from("--gate"));
3073        out.push(OsString::from(gate));
3074    }
3075    out.push(OsString::from("--context"));
3076    out.push(OsString::from(&config.context_strategy));
3077    if let Some(ref container) = config.container {
3078        out.push(OsString::from("--container"));
3079        out.push(OsString::from(container));
3080    }
3081    out.push(OsString::from("--max-turns"));
3082    out.push(OsString::from(config.max_turns.to_string()));
3083    out.push(OsString::from("--max-gates"));
3084    out.push(OsString::from(config.max_gates.to_string()));
3085    out.push(OsString::from(format!("--rollback={}", config.rollback)));
3086    if let Some(fold_budget) = config.fold_budget {
3087        out.push(OsString::from("--fold-budget"));
3088        out.push(OsString::from(fold_budget.to_string()));
3089    }
3090    out.push(OsString::from("--sandbox"));
3091    out.push(OsString::from(&config.sandbox));
3092    if let Some(ref network) = config.network {
3093        out.push(OsString::from("--network"));
3094        out.push(OsString::from(network));
3095    }
3096    for path in &config.allow_read {
3097        out.push(OsString::from("--allow-read"));
3098        out.push(path.as_os_str().to_os_string());
3099    }
3100    for var in &config.pass_env {
3101        out.push(OsString::from("--pass-env"));
3102        out.push(OsString::from(var));
3103    }
3104    out
3105}
3106
3107#[cfg(unix)]
3108fn exec_reload<W: Write + ?Sized>(
3109    exec_path: &Path,
3110    reload_args: &[std::ffi::OsString],
3111    workdir: &Path,
3112    token_file_path: &Path,
3113    err: &mut W,
3114) -> i32 {
3115    use std::os::unix::process::CommandExt;
3116
3117    let exec_err = std::process::Command::new(exec_path)
3118        .args(reload_args)
3119        .current_dir(workdir)
3120        .env(RELOAD_REUSE_TOKEN_ENV, "1")
3121        .exec();
3122    let _ = std::fs::remove_file(token_file_path);
3123    let _ = writeln!(
3124        err,
3125        "blyte: failed to re-exec {}: {exec_err}",
3126        exec_path.display()
3127    );
3128    let _ = err.flush();
3129    1
3130}
3131
3132#[cfg(not(unix))]
3133fn exec_reload<W: Write + ?Sized>(
3134    exec_path: &Path,
3135    reload_args: &[std::ffi::OsString],
3136    workdir: &Path,
3137    token_file_path: &Path,
3138    err: &mut W,
3139) -> i32 {
3140    match std::process::Command::new(exec_path)
3141        .args(reload_args)
3142        .current_dir(workdir)
3143        .env(RELOAD_REUSE_TOKEN_ENV, "1")
3144        .status()
3145    {
3146        Ok(status) => match status.code() {
3147            Some(code) => code,
3148            None => 1,
3149        },
3150        Err(e) => {
3151            let _ = std::fs::remove_file(token_file_path);
3152            let _ = writeln!(
3153                err,
3154                "blyte: failed to re-launch {}: {e}",
3155                exec_path.display()
3156            );
3157            let _ = err.flush();
3158            1
3159        }
3160    }
3161}
3162
3163#[cfg(test)]
3164mod tests {
3165    use super::*;
3166
3167    #[test]
3168    fn canonicalize_attachments_dir_errors_when_missing() {
3169        let dir = tempfile::tempdir().unwrap();
3170        let missing = dir.path().join("does-not-exist").join("attachments");
3171        let err = canonicalize_attachments_dir(&missing).unwrap_err();
3172        assert!(
3173            err.contains(&missing.display().to_string()),
3174            "expected error to name missing path, got: {err}"
3175        );
3176        assert!(err.contains("canonicalize"), "unexpected error: {err}");
3177    }
3178
3179    #[cfg(unix)]
3180    #[test]
3181    fn canonicalize_attachments_dir_errors_on_dangling_symlink() {
3182        let dir = tempfile::tempdir().unwrap();
3183        let dangling = dir.path().join("attachments");
3184        std::os::unix::fs::symlink(dir.path().join("missing-target"), &dangling).unwrap();
3185        let err = canonicalize_attachments_dir(&dangling).unwrap_err();
3186        assert!(
3187            err.contains(&dangling.display().to_string()),
3188            "expected error to name symlink path, got: {err}"
3189        );
3190        assert!(err.contains("canonicalize"), "unexpected error: {err}");
3191    }
3192
3193    #[test]
3194    fn prepare_attachments_dir_errors_when_attachments_path_is_a_file() {
3195        let dir = tempfile::tempdir().unwrap();
3196        let blocker = crate::attachments::attachments_dir(dir.path());
3197        std::fs::write(&blocker, b"not a dir").unwrap();
3198        let err = prepare_attachments_dir(dir.path()).unwrap_err();
3199        assert!(
3200            err.contains(&blocker.display().to_string()),
3201            "expected error to name path, got: {err}"
3202        );
3203    }
3204
3205    fn poisoned_open_codes() -> OpenCodes {
3206        let codes = OpenCodes::new();
3207        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3208            let _guard = codes.entries.lock().unwrap();
3209            panic!("poison");
3210        }));
3211        codes
3212    }
3213
3214    #[test]
3215    fn open_codes_issue_errors_when_lock_poisoned() {
3216        let codes = poisoned_open_codes();
3217        let err = codes.issue(100).unwrap_err();
3218        assert!(err.contains("open codes"), "unexpected error: {err}");
3219        assert!(err.contains("poison"), "unexpected error: {err}");
3220    }
3221
3222    #[test]
3223    fn open_codes_redeem_errors_when_lock_poisoned() {
3224        let codes = poisoned_open_codes();
3225        let err = codes.redeem("some-code", 100).unwrap_err();
3226        assert!(err.contains("open codes"), "unexpected error: {err}");
3227        assert!(err.contains("poison"), "unexpected error: {err}");
3228    }
3229
3230    #[test]
3231    fn issue_initial_open_code_errors_when_clock_fails() {
3232        let codes = OpenCodes::new();
3233        let err = issue_initial_open_code(
3234            &codes,
3235            Err("system clock is before Unix epoch: test".to_string()),
3236        )
3237        .unwrap_err();
3238        assert!(err.contains("system clock"), "unexpected error: {err}");
3239        assert!(codes.entries.lock().unwrap().is_empty());
3240
3241        let code = issue_initial_open_code(&codes, Ok(Duration::from_secs(500))).unwrap();
3242        assert!(codes.redeem(&code, 500).unwrap());
3243    }
3244}