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