Skip to main content

blyte_cli/
serve.rs

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