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