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