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
682pub fn build_models_response(
683 discovered: &[(String, Result<Vec<blyte_provider::ModelInfo>, String>)],
684) -> Response {
685 let mut models = Vec::new();
686 let mut unavailable = Vec::new();
687 let mut error_parts = Vec::new();
688
689 for (provider, result) in discovered {
690 match result {
691 Ok(list) => {
692 for m in list {
693 let effort_supported = crate::session::model_supports_effort(&m.id);
694 models.push(serde_json::json!({
695 "id": m.id,
696 "provider": m.provider,
697 "effort_supported": effort_supported,
698 "input_token_limit": m.input_token_limit,
699 }));
700 }
701 }
702 Err(err_text) => {
703 error_parts.push(format!("{provider}: {err_text}"));
704 unavailable.push(serde_json::json!({
705 "provider": provider,
706 "error": err_text,
707 }));
708 }
709 }
710 }
711
712 if models.is_empty() {
713 let msg = if error_parts.is_empty() {
714 "no models listed by any provider".to_string()
715 } else {
716 format!("no models available: {}", error_parts.join("; "))
717 };
718 return json_error(502, msg);
719 }
720
721 Response::json(
722 200,
723 &serde_json::json!({
724 "models": models,
725 "unavailable": unavailable,
726 }),
727 )
728}
729
730fn handle_models(surface: &Surface) -> Response {
731 match surface
732 .session
733 .discovered_models_cached(blyte_provider::discover_all_models)
734 {
735 Ok(discovered) => build_models_response(&discovered),
736 Err(e) => json_error(500, e),
737 }
738}
739
740fn handle_post_model(surface: &Surface, req: &Request) -> Response {
741 let obj = match parse_json_object(&req.body) {
742 Ok(o) => o,
743 Err(resp) => return resp,
744 };
745 let model = match obj.get("model") {
746 Some(serde_json::Value::String(s)) => s.clone(),
747 Some(_) => return json_error(400, "field model must be a string"),
748 None => return json_error(400, "missing required field: model"),
749 };
750 if model.trim().is_empty() {
751 return json_error(400, "field model must not be empty");
752 }
753 if let Err(e) = blyte_provider::resolve_provider(Some(&model)) {
754 return json_error(400, e.to_string());
755 }
756 if let Err(e) = surface.session.set_model(&model) {
757 return json_error(400, e);
758 }
759 session_response(surface)
760}
761
762fn handle_post_effort(surface: &Surface, req: &Request) -> Response {
763 let obj = match parse_json_object(&req.body) {
764 Ok(o) => o,
765 Err(resp) => return resp,
766 };
767 let effort = match obj.get("effort") {
768 Some(serde_json::Value::Null) => None,
769 Some(serde_json::Value::String(s)) => Some(s.clone()),
770 Some(_) => return json_error(400, "field effort must be a string or null"),
771 None => return json_error(400, "missing required field: effort"),
772 };
773 if let Err(e) = surface.session.set_effort(effort.as_deref()) {
774 return json_error(400, e);
775 }
776 session_response(surface)
777}
778
779fn handle_post_seen(surface: &Surface) -> Response {
780 surface.session.mark_seen();
781 Response::text(204, "")
782}
783
784fn handle_post_approval(surface: &Surface, id: &str, req: &Request) -> Response {
785 let obj = match parse_json_object(&req.body) {
786 Ok(o) => o,
787 Err(resp) => return resp,
788 };
789 if obj.len() != 1 {
790 return json_error(400, "request body must contain only field answer");
791 }
792 let answer = match obj.get("answer") {
793 Some(serde_json::Value::String(s)) if s == "yes" => ApprovalAnswer::Yes,
794 Some(serde_json::Value::String(s)) if s == "no" => ApprovalAnswer::No,
795 Some(serde_json::Value::String(other)) => {
796 return json_error(
797 400,
798 format!("field answer must be \"yes\" or \"no\", got '{other}'"),
799 );
800 }
801 Some(_) => return json_error(400, "field answer must be \"yes\" or \"no\""),
802 None => return json_error(400, "missing required field: answer"),
803 };
804 match surface.session.answer_approval(id, answer) {
805 Ok(seq) => Response::json(
806 200,
807 &serde_json::json!({
808 "id": id,
809 "answer": answer.as_str(),
810 "seq": seq,
811 }),
812 ),
813 Err(AnswerError::NotFound) => json_error(404, format!("unknown approval id: {id}")),
814 Err(AnswerError::AlreadyAnswered) => {
815 json_error(409, format!("approval {id} has already been answered"))
816 }
817 }
818}
819
820pub fn reconcile_runs(
821 surface: &Surface,
822 now: u64,
823) -> Result<(crate::live_runs::LiveRuns, Vec<String>), String> {
824 let _guard = surface
825 .reconcile_lock
826 .lock()
827 .unwrap_or_else(|e| e.into_inner());
828 if !is_repository(&surface.root)? {
829 let records_dir = crate::dispatch_in_place::records_dir_for(&surface.root)?;
830 let owned = crate::requests::owned_run_ids_in(&records_dir, &surface.surface_id)?;
831 let mut live =
832 crate::live_runs::collect_in_place(&surface.root, &records_dir, now, surface.days)?;
833 live.running.retain(|run| owned.contains(&run.id));
834 live.runs.retain(|run| owned.contains(&run.id));
835
836 let mut errors = Vec::new();
837 if let Err(e) = crate::run_results::report_finished_runs_in(surface, &records_dir) {
838 errors.push(format!("run report failed: {e}"));
839 }
840 return Ok((live, errors));
841 }
842 let owned = crate::requests::owned_run_ids(surface)?;
843 let mut live = crate::live_runs::collect(&surface.root, now, surface.days)?;
844 let mut any_written = false;
845 for run in &live.runs {
846 if !owned.contains(&run.id) || run.checks_recorded {
847 continue;
848 }
849 if crate::queue_actions::ensure_checks(&surface.root, &run.id)? {
850 any_written = true;
851 }
852 }
853 if any_written {
854 live = crate::live_runs::collect(&surface.root, now, surface.days)?;
855 }
856 live.running.retain(|run| owned.contains(&run.id));
857 live.runs.retain(|run| owned.contains(&run.id));
858
859 let mut errors = Vec::new();
860 if let Err(e) = crate::run_results::report_finished_runs(surface) {
861 errors.push(format!("run report failed: {e}"));
862 }
863
864 let mut triggered = BTreeSet::new();
865 for run in &live.runs {
866 if run.research {
867 continue;
868 }
869 if let Some(ref req_id) = run.request {
870 if triggered.insert(req_id.clone()) {
871 if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
872 errors.push(format!("combine trigger failed for {req_id}: {e}"));
873 }
874 }
875 }
876 }
877
878 Ok((live, errors))
879}
880
881fn handle_runs(surface: &Surface, now: u64) -> Response {
882 let is_repo = match is_repository(&surface.root) {
883 Ok(v) => v,
884 Err(e) => return json_error(500, e),
885 };
886 let (live, errors) = match reconcile_runs(surface, now) {
887 Ok(res) => res,
888 Err(e) => return json_error(500, e),
889 };
890 for msg in errors {
891 surface.session.record_error(&msg);
892 }
893
894 let mut runs_with_hold = Vec::with_capacity(live.runs.len());
895 if is_repo {
896 let run_refs: Vec<(&str, Option<&str>)> = live
897 .runs
898 .iter()
899 .map(|run| (run.id.as_str(), run.request.as_deref()))
900 .collect();
901 let combined_ids = match crate::requests::combined_run_ids(&surface.root, &run_refs) {
902 Ok(ids) => ids,
903 Err(e) => return json_error(500, e),
904 };
905
906 for run in &live.runs {
907 let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
908 Ok(h) => h,
909 Err(e) => return json_error(500, e),
910 };
911 let combined = combined_ids.contains(&run.id);
912 runs_with_hold.push(RunWithHold {
913 run,
914 hold,
915 combined,
916 in_place: false,
917 undone: false,
918 });
919 }
920 } else {
921 let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
922 Ok(dir) => dir,
923 Err(e) => return json_error(500, e),
924 };
925 for run in &live.runs {
926 let hold = match crate::queue_actions::read_hold_in(&records_dir, &run.id) {
927 Ok(h) => h,
928 Err(e) => return json_error(500, e),
929 };
930 let undone = crate::in_place_review::is_undone(&records_dir, &run.id);
931 runs_with_hold.push(RunWithHold {
932 run,
933 hold,
934 combined: false,
935 in_place: true,
936 undone,
937 });
938 }
939 }
940
941 let payload = LiveRunsResponse {
942 generated_at: live.generated_at,
943 repo: &live.repo,
944 running: &live.running,
945 runs: runs_with_hold,
946 skipped: &live.skipped,
947 };
948 match serde_json::to_value(&payload) {
949 Ok(val) => Response::json(200, &val),
950 Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
951 }
952}
953
954fn handle_runs_changed(surface: &Surface) -> Response {
955 surface.reconcile_requested.store(true, Ordering::Release);
956 Response::json(202, &serde_json::json!({}))
957}
958
959const NOT_A_GIT_REPO_ERROR: &str = "this folder is not a git repository";
960
961fn require_repository(root: &Path) -> Result<(), Response> {
962 match is_repository(root) {
963 Ok(true) => Ok(()),
964 Ok(false) => Err(json_error(409, NOT_A_GIT_REPO_ERROR)),
965 Err(e) => Err(json_error(500, e)),
966 }
967}
968
969fn handle_run_diff(surface: &Surface, id: &str) -> Response {
970 let is_repo = match is_repository(&surface.root) {
971 Ok(v) => v,
972 Err(e) => return json_error(500, e),
973 };
974 if !is_valid_run_id(id) {
975 return json_error(404, format!("unknown run: {id}"));
976 }
977 if !is_repo {
978 let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
979 Ok(dir) => dir,
980 Err(e) => return json_error(500, e),
981 };
982 let start = records_dir.join(format!("{id}.start.json"));
983 let summary = records_dir.join(format!("{id}.json"));
984 let report_json = records_dir.join(format!("{id}.report.json"));
985 let report_md = records_dir.join(format!("{id}.report.md"));
986 if !start.exists() && !summary.exists() && !report_json.exists() && !report_md.exists() {
987 return json_error(404, format!("unknown run: {id}"));
988 }
989 if let Err(err) = crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
990 {
991 return request_action_error_response(err);
992 }
993 return match crate::in_place_review::diff_for_run(&records_dir, id) {
994 Ok(body) => Response::text(200, &body),
995 Err(e) => {
996 if !summary.exists() || e.contains("No such file") || e.contains("missing manifest")
997 {
998 json_error(404, e)
999 } else {
1000 json_error(500, e)
1001 }
1002 }
1003 };
1004 }
1005 let wt_dir = surface.root.join(".wt");
1006 let wt = wt_dir.join(id);
1007 let start = wt_dir.join(format!("{id}.start.json"));
1008 let summary = wt_dir.join(format!("{id}.json"));
1009 let report_json = wt_dir.join(format!("{id}.report.json"));
1010 let report_md = wt_dir.join(format!("{id}.report.md"));
1011 if !wt.exists()
1012 && !start.exists()
1013 && !summary.exists()
1014 && !report_json.exists()
1015 && !report_md.exists()
1016 {
1017 return json_error(404, format!("unknown run: {id}"));
1018 }
1019 if let Err(err) = crate::requests::run_owner_check(surface, id) {
1020 return request_action_error_response(err);
1021 }
1022 match crate::queue_actions::compute_review(&surface.root, id, true) {
1023 Ok(data) => {
1024 let body = if !data.wt_exists {
1025 "(worktree removed)\n".to_string()
1026 } else if data.diff_out.is_empty() {
1027 String::new()
1028 } else {
1029 format!("{}\n", data.diff_out)
1030 };
1031 Response::text(200, &body)
1032 }
1033 Err(e) => {
1034 if !wt.is_dir() || !wt.join(".git").exists() {
1035 json_error(404, e)
1036 } else {
1037 json_error(500, e)
1038 }
1039 }
1040 }
1041}
1042
1043fn handle_run_undo(surface: &Surface, id: &str) -> Response {
1044 let is_repo = match is_repository(&surface.root) {
1045 Ok(v) => v,
1046 Err(e) => return json_error(500, e),
1047 };
1048 if is_repo {
1049 return json_error(
1050 409,
1051 "undo is for runs in a folder that is not a git repository",
1052 );
1053 }
1054 if !is_valid_run_id(id) {
1055 return json_error(404, format!("unknown run: {id}"));
1056 }
1057 let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
1058 Ok(dir) => dir,
1059 Err(e) => return json_error(500, e),
1060 };
1061 let run_exists = records_dir.join(format!("{id}.start.json")).exists()
1062 || records_dir.join(format!("{id}.json")).exists()
1063 || records_dir.join(format!("{id}.report.json")).exists()
1064 || records_dir.join(format!("{id}.report.md")).exists();
1065 if run_exists {
1066 if let Err(err) = crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
1067 {
1068 return request_action_error_response(err);
1069 }
1070 }
1071 match crate::in_place_review::undo_in(&surface.root, id) {
1072 Ok(lines) => Response::json(200, &serde_json::json!({ "lines": lines })),
1073 Err(msg) => json_error(409, msg),
1074 }
1075}
1076
1077fn parse_action(raw: &str) -> Result<Action, String> {
1078 match raw {
1079 "accept" => Ok(Action::Accept),
1080 "send_back" => Ok(Action::SendBack),
1081 "redo" => Ok(Action::Redo),
1082 "hold" => Ok(Action::Hold),
1083 "mark_read" => Ok(Action::MarkRead),
1084 other => Err(format!(
1085 "unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
1086 )),
1087 }
1088}
1089
1090fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
1091 let is_repo = match is_repository(&surface.root) {
1092 Ok(v) => v,
1093 Err(e) => return json_error(500, e),
1094 };
1095 let obj = match parse_json_object(&req.body) {
1096 Ok(o) => o,
1097 Err(resp) => return resp,
1098 };
1099 let action_str = match obj.get("action") {
1100 Some(serde_json::Value::String(s)) => s.clone(),
1101 Some(_) => return json_error(400, "field action must be a string"),
1102 None => return json_error(400, "missing required field: action"),
1103 };
1104 let action = match parse_action(&action_str) {
1105 Ok(a) => a,
1106 Err(e) => return json_error(400, e),
1107 };
1108 let note = match obj.get("note") {
1109 None | Some(serde_json::Value::Null) => None,
1110 Some(serde_json::Value::String(s)) => Some(s.clone()),
1111 Some(_) => return json_error(400, "field note must be a string or null"),
1112 };
1113
1114 let decision = if is_repo {
1115 let wt_dir = surface.root.join(".wt");
1116 let run_exists = is_valid_run_id(id)
1117 && (wt_dir.join(id).exists()
1118 || wt_dir.join(format!("{id}.start.json")).exists()
1119 || wt_dir.join(format!("{id}.json")).exists()
1120 || wt_dir.join(format!("{id}.report.json")).exists()
1121 || wt_dir.join(format!("{id}.report.md")).exists());
1122 if run_exists {
1123 if let Err(err) = crate::requests::run_owner_check(surface, id) {
1124 return request_action_error_response(err);
1125 }
1126 }
1127 match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
1128 Ok(d) => d,
1129 Err(e) => return json_error(400, e),
1130 }
1131 } else {
1132 let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
1133 Ok(dir) => dir,
1134 Err(e) => return json_error(500, e),
1135 };
1136 let run_exists = is_valid_run_id(id)
1137 && (records_dir.join(format!("{id}.start.json")).exists()
1138 || records_dir.join(format!("{id}.json")).exists()
1139 || records_dir.join(format!("{id}.report.json")).exists()
1140 || records_dir.join(format!("{id}.report.md")).exists());
1141 if run_exists {
1142 if let Err(err) =
1143 crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
1144 {
1145 return request_action_error_response(err);
1146 }
1147 }
1148 match crate::queue_actions::decide_in_place(&records_dir, id, action, note.as_deref(), now)
1149 {
1150 Ok(d) => d,
1151 Err(e) => return json_error(400, e),
1152 }
1153 };
1154 let seq = match surface.session.record_decision(
1155 &decision.run,
1156 &action_str,
1157 decision.note.as_deref(),
1158 decision.conversation_message.as_deref(),
1159 ) {
1160 Ok(s) => s,
1161 Err(e) => return json_error(500, e),
1162 };
1163 if is_repo && action == Action::Accept {
1164 match crate::requests::run_request_id(&surface.root, &decision.run) {
1165 Ok(Some(req_id)) => {
1166 if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
1167 surface
1168 .session
1169 .record_error(&format!("combine trigger failed for {req_id}: {e}"));
1170 }
1171 }
1172 Ok(None) => {}
1173 Err(e) => return json_error(500, e),
1174 }
1175 }
1176 Response::json(
1177 200,
1178 &serde_json::json!({
1179 "decision": {
1180 "run": decision.run,
1181 "action": action_str,
1182 "note": decision.note,
1183 "conversation_message": decision.conversation_message,
1184 },
1185 "seq": seq,
1186 }),
1187 )
1188}
1189
1190fn handle_map(surface: &Surface) -> Response {
1191 match crate::map::build(&surface.root, &surface.repo) {
1192 Ok(data) => match serde_json::to_value(&data) {
1193 Ok(val) => Response::json(200, &val),
1194 Err(e) => json_error(500, format!("failed to serialize map: {e}")),
1195 },
1196 Err(e) => json_error(422, e),
1197 }
1198}
1199
1200fn handle_requests(surface: &Surface) -> Response {
1201 match is_repository(&surface.root) {
1202 Ok(true) => {}
1203 Ok(false) => return Response::json(200, &serde_json::json!([])),
1204 Err(e) => return json_error(500, e),
1205 }
1206 match crate::requests::list_requests(surface) {
1207 Ok(list) => match serde_json::to_value(&list) {
1208 Ok(val) => Response::json(200, &val),
1209 Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
1210 },
1211 Err(e) => json_error(500, e),
1212 }
1213}
1214
1215fn request_action_error_response(err: RequestActionError) -> Response {
1216 match err {
1217 RequestActionError::BadRequest(msg) => json_error(400, msg),
1218 RequestActionError::NotOwned(msg) => json_error(403, msg),
1219 RequestActionError::Conflict(msg) => json_error(409, msg),
1220 RequestActionError::Internal(msg) => json_error(500, msg),
1221 }
1222}
1223
1224fn handle_request_push(surface: &Surface, id: &str) -> Response {
1225 if let Err(resp) = require_repository(&surface.root) {
1226 return resp;
1227 }
1228 match crate::requests::push_request(surface, id) {
1229 Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
1230 Err(err) => request_action_error_response(err),
1231 }
1232}
1233
1234fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
1235 if let Err(resp) = require_repository(&surface.root) {
1236 return resp;
1237 }
1238 if let Err(e) = crate::dispatch::validate_request_id(id) {
1239 return json_error(400, e);
1240 }
1241 let obj = match parse_json_object(&req.body) {
1242 Ok(o) => o,
1243 Err(resp) => return resp,
1244 };
1245 let title = match obj.get("title") {
1246 Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
1247 Some(serde_json::Value::String(_)) => {
1248 return json_error(400, "field title must not be empty");
1249 }
1250 Some(_) => return json_error(400, "field title must be a string"),
1251 None => return json_error(400, "missing required field: title"),
1252 };
1253 let body = match obj.get("body") {
1254 None | Some(serde_json::Value::Null) => String::new(),
1255 Some(serde_json::Value::String(s)) => s.clone(),
1256 Some(_) => return json_error(400, "field body must be a string"),
1257 };
1258 match crate::requests::open_request_pull_request(surface, id, &title, &body) {
1259 Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
1260 Err(err) => request_action_error_response(err),
1261 }
1262}
1263
1264#[derive(Serialize)]
1265struct McpToolApi {
1266 name: String,
1267 exposed_name: String,
1268 description: Option<String>,
1269 read_only: bool,
1270}
1271
1272#[derive(Serialize)]
1273struct McpOAuthApi {
1274 client_id: Option<String>,
1275 has_client_secret: bool,
1276 callback_port: Option<u16>,
1277 scopes: Option<Vec<String>>,
1278}
1279
1280#[derive(Serialize)]
1281struct McpServerApi {
1282 name: String,
1283 transport: String,
1284 target: String,
1285 source: &'static str,
1286 trusted: bool,
1287 enabled: bool,
1288 approval: &'static str,
1289 status: &'static str,
1290 last_error: Option<String>,
1291 has_oauth_tokens: bool,
1292 oauth: Option<McpOAuthApi>,
1293 tools: Vec<McpToolApi>,
1294}
1295
1296fn has_stored_oauth_tokens(store: &crate::mcp::oauth::McpAuthStore, name: &str) -> bool {
1297 store.get(name).is_some_and(|auth| {
1298 auth.access_token.as_deref().is_some_and(|t| !t.is_empty())
1299 || auth.refresh_token.as_deref().is_some_and(|t| !t.is_empty())
1300 })
1301}
1302
1303fn mcp_server_to_api(
1304 surface: &Surface,
1305 snapshot: crate::mcp::McpServerSnapshot,
1306 auth_store: &crate::mcp::oauth::McpAuthStore,
1307) -> McpServerApi {
1308 let (status, last_error) = if snapshot.auth_in_progress {
1309 ("auth_in_progress", None)
1310 } else {
1311 match &snapshot.status {
1312 crate::mcp::ServerStatus::Connected => ("connected", None),
1313 crate::mcp::ServerStatus::NeedsAuth => ("needs_auth", None),
1314 crate::mcp::ServerStatus::Disabled => ("disabled", None),
1315 crate::mcp::ServerStatus::UntrustedProject => ("untrusted_project", None),
1316 crate::mcp::ServerStatus::Error(msg) => {
1317 ("error", Some(surface.mcp.redact_text(msg, &surface.root)))
1318 }
1319 }
1320 };
1321 let has_oauth_tokens = has_stored_oauth_tokens(auth_store, &snapshot.name);
1322 let oauth = snapshot.oauth.map(|o| McpOAuthApi {
1323 client_id: o.client_id,
1324 has_client_secret: o.has_client_secret,
1325 callback_port: o.callback_port,
1326 scopes: o.scopes,
1327 });
1328 let tools = snapshot
1329 .tools
1330 .into_iter()
1331 .map(|tool| McpToolApi {
1332 name: tool.name,
1333 exposed_name: tool.exposed_name,
1334 description: tool.description,
1335 read_only: tool.read_only_hint == Some(true),
1336 })
1337 .collect();
1338 McpServerApi {
1339 name: snapshot.name,
1340 transport: snapshot.transport,
1341 target: surface.mcp.redact_text(&snapshot.target, &surface.root),
1342 source: snapshot.source.as_str(),
1343 trusted: snapshot.trusted,
1344 enabled: snapshot.enabled,
1345 approval: snapshot.approval.as_str(),
1346 status,
1347 last_error,
1348 has_oauth_tokens,
1349 oauth,
1350 tools,
1351 }
1352}
1353
1354fn mcp_error_response(surface: &Surface, err: String) -> Response {
1355 let safe = surface.mcp.redact_text(&err, &surface.root);
1356 let status = if safe.contains("not found") {
1357 404
1358 } else if safe.contains("already exists") || safe.contains("already in progress") {
1359 409
1360 } else {
1361 400
1362 };
1363 json_error(status, safe)
1364}
1365
1366fn parse_approval_policy(raw: &str) -> Result<crate::mcp::ApprovalPolicy, Response> {
1367 match raw {
1368 "read_only" => Ok(crate::mcp::ApprovalPolicy::ReadOnly),
1369 "auto" => Ok(crate::mcp::ApprovalPolicy::Auto),
1370 "ask" => Ok(crate::mcp::ApprovalPolicy::Ask),
1371 _ => Err(json_error(
1372 400,
1373 format!("invalid approval policy '{raw}'; expected read_only, auto, or ask"),
1374 )),
1375 }
1376}
1377
1378fn parse_string_map(
1379 obj: &serde_json::Map<String, serde_json::Value>,
1380 field: &str,
1381) -> Result<std::collections::BTreeMap<String, String>, Response> {
1382 let Some(val) = obj.get(field) else {
1383 return Ok(std::collections::BTreeMap::new());
1384 };
1385 if val.is_null() {
1386 return Ok(std::collections::BTreeMap::new());
1387 }
1388 let Some(map) = val.as_object() else {
1389 return Err(json_error(400, format!("field {field} must be an object")));
1390 };
1391 let mut out = std::collections::BTreeMap::new();
1392 for (k, v) in map {
1393 let Some(s) = v.as_str() else {
1394 return Err(json_error(
1395 400,
1396 format!("field {field}.{k} must be a string"),
1397 ));
1398 };
1399 if k.trim().is_empty() {
1400 return Err(json_error(
1401 400,
1402 format!("field {field} cannot contain empty keys"),
1403 ));
1404 }
1405 out.insert(k.clone(), s.to_string());
1406 }
1407 Ok(out)
1408}
1409
1410fn load_mcp_auth_store(surface: &Surface) -> Result<crate::mcp::oauth::McpAuthStore, Response> {
1411 let path = surface.mcp.auth_store_path();
1412 crate::mcp::oauth::McpAuthStore::load(path).map_err(|err| {
1413 let safe = surface.mcp.redact_text(
1414 &format!("failed to load MCP auth store: {err}"),
1415 &surface.root,
1416 );
1417 json_error(500, safe)
1418 })
1419}
1420
1421fn mcp_server_response(surface: &Surface, snapshot: crate::mcp::McpServerSnapshot) -> Response {
1422 let auth_store = match load_mcp_auth_store(surface) {
1423 Ok(store) => store,
1424 Err(resp) => return resp,
1425 };
1426 let server = mcp_server_to_api(surface, snapshot, &auth_store);
1427 match serde_json::to_value(&server) {
1428 Ok(val) => Response::json(200, &serde_json::json!({ "server": val })),
1429 Err(e) => json_error(500, format!("failed to serialize MCP server: {e}")),
1430 }
1431}
1432
1433fn handle_mcp_list_servers(surface: &Surface) -> Response {
1434 let auth_store = match load_mcp_auth_store(surface) {
1435 Ok(store) => store,
1436 Err(resp) => return resp,
1437 };
1438 let servers: Vec<McpServerApi> = surface
1439 .mcp
1440 .list_servers()
1441 .into_iter()
1442 .map(|snap| mcp_server_to_api(surface, snap, &auth_store))
1443 .collect();
1444 match serde_json::to_value(&servers) {
1445 Ok(val) => Response::json(200, &serde_json::json!({ "servers": val })),
1446 Err(e) => json_error(500, format!("failed to serialize MCP servers: {e}")),
1447 }
1448}
1449
1450fn parse_oauth_patch_object(
1451 map: &serde_json::Map<String, serde_json::Value>,
1452) -> Result<crate::mcp::OAuthConfigPatch, Response> {
1453 let client_id = match map.get("client_id") {
1454 None | Some(serde_json::Value::Null) => None,
1455 Some(serde_json::Value::String(s)) => {
1456 let trimmed = s.trim();
1457 if trimmed.is_empty() {
1458 None
1459 } else {
1460 Some(trimmed.to_string())
1461 }
1462 }
1463 Some(_) => return Err(json_error(400, "field oauth.client_id must be a string")),
1464 };
1465 let client_secret = match map.get("client_secret") {
1466 None | Some(serde_json::Value::Null) => None,
1467 Some(serde_json::Value::String(s)) => {
1468 let trimmed = s.trim();
1469 if trimmed.is_empty() {
1470 None
1471 } else {
1472 Some(trimmed.to_string())
1473 }
1474 }
1475 Some(_) => {
1476 return Err(json_error(
1477 400,
1478 "field oauth.client_secret must be a string",
1479 ));
1480 }
1481 };
1482 let clear_client_secret = match map.get("clear_client_secret") {
1483 None | Some(serde_json::Value::Null) => false,
1484 Some(serde_json::Value::Bool(b)) => *b,
1485 Some(_) => {
1486 return Err(json_error(
1487 400,
1488 "field oauth.clear_client_secret must be a boolean",
1489 ));
1490 }
1491 };
1492 let callback_port = match map.get("callback_port") {
1493 None | Some(serde_json::Value::Null) => None,
1494 Some(serde_json::Value::Number(n)) => {
1495 let Some(v) = n.as_u64() else {
1496 return Err(json_error(
1497 400,
1498 "field oauth.callback_port must be an integer between 1 and 65535",
1499 ));
1500 };
1501 if v == 0 || v > u16::MAX as u64 {
1502 return Err(json_error(
1503 400,
1504 "field oauth.callback_port must be an integer between 1 and 65535",
1505 ));
1506 }
1507 Some(v as u16)
1508 }
1509 Some(serde_json::Value::String(s)) => {
1510 let trimmed = s.trim();
1511 if trimmed.is_empty() {
1512 None
1513 } else {
1514 match trimmed.parse::<u16>() {
1515 Ok(p) if p > 0 => Some(p),
1516 _ => {
1517 return Err(json_error(
1518 400,
1519 "field oauth.callback_port must be an integer between 1 and 65535",
1520 ));
1521 }
1522 }
1523 }
1524 }
1525 Some(_) => {
1526 return Err(json_error(
1527 400,
1528 "field oauth.callback_port must be an integer between 1 and 65535",
1529 ));
1530 }
1531 };
1532 let scopes = match map.get("scopes") {
1533 None | Some(serde_json::Value::Null) => None,
1534 Some(serde_json::Value::Array(items)) => {
1535 let mut out = Vec::with_capacity(items.len());
1536 for item in items {
1537 let Some(s) = item.as_str() else {
1538 return Err(json_error(
1539 400,
1540 "field oauth.scopes must be an array of strings",
1541 ));
1542 };
1543 let trimmed = s.trim();
1544 if !trimmed.is_empty() {
1545 out.push(trimmed.to_string());
1546 }
1547 }
1548 if out.is_empty() {
1549 None
1550 } else {
1551 Some(out)
1552 }
1553 }
1554 Some(serde_json::Value::String(s)) => {
1555 let parsed: Vec<String> = s
1556 .split(|c: char| c.is_whitespace() || c == ',')
1557 .map(str::trim)
1558 .filter(|item| !item.is_empty())
1559 .map(str::to_string)
1560 .collect();
1561 if parsed.is_empty() {
1562 None
1563 } else {
1564 Some(parsed)
1565 }
1566 }
1567 Some(_) => {
1568 return Err(json_error(
1569 400,
1570 "field oauth.scopes must be an array of strings",
1571 ));
1572 }
1573 };
1574 Ok(crate::mcp::OAuthConfigPatch {
1575 client_id,
1576 client_secret,
1577 clear_client_secret,
1578 callback_port,
1579 scopes,
1580 })
1581}
1582
1583fn parse_optional_oauth_config(
1584 obj: &serde_json::Map<String, serde_json::Value>,
1585) -> Result<Option<crate::mcp::OAuthClientConfig>, Response> {
1586 let Some(val) = obj.get("oauth") else {
1587 return Ok(None);
1588 };
1589 if val.is_null() {
1590 return Ok(None);
1591 }
1592 let Some(map) = val.as_object() else {
1593 return Err(json_error(400, "field oauth must be an object"));
1594 };
1595 let patch = parse_oauth_patch_object(map)?;
1596 let cfg = crate::mcp::OAuthClientConfig {
1597 client_id: patch.client_id,
1598 client_secret: if patch.clear_client_secret {
1599 None
1600 } else {
1601 patch.client_secret
1602 },
1603 callback_port: patch.callback_port,
1604 scopes: patch.scopes,
1605 };
1606 if cfg.is_empty() {
1607 Ok(None)
1608 } else {
1609 Ok(Some(cfg))
1610 }
1611}
1612
1613fn handle_mcp_add_server(surface: &Surface, req: &Request) -> Response {
1614 let obj = match parse_json_object(&req.body) {
1615 Ok(o) => o,
1616 Err(resp) => return resp,
1617 };
1618 let Some(name) = obj.get("name").and_then(|v| v.as_str()).map(str::trim) else {
1619 return json_error(400, "missing or invalid field name");
1620 };
1621 if name.is_empty() {
1622 return json_error(400, "field name must not be empty");
1623 }
1624 let url = match obj.get("url") {
1625 None | Some(serde_json::Value::Null) => None,
1626 Some(serde_json::Value::String(s)) => {
1627 let trimmed = s.trim();
1628 if trimmed.is_empty() {
1629 None
1630 } else {
1631 Some(trimmed.to_string())
1632 }
1633 }
1634 Some(_) => return json_error(400, "field url must be a string"),
1635 };
1636 let command = match obj.get("command") {
1637 None | Some(serde_json::Value::Null) => None,
1638 Some(serde_json::Value::String(s)) => {
1639 let trimmed = s.trim();
1640 if trimmed.is_empty() {
1641 None
1642 } else {
1643 Some(trimmed.to_string())
1644 }
1645 }
1646 Some(_) => return json_error(400, "field command must be a string"),
1647 };
1648 let args = match obj.get("args") {
1649 None | Some(serde_json::Value::Null) => Vec::new(),
1650 Some(serde_json::Value::Array(items)) => {
1651 let mut parsed = Vec::with_capacity(items.len());
1652 for item in items {
1653 let Some(s) = item.as_str() else {
1654 return json_error(400, "field args must be an array of strings");
1655 };
1656 parsed.push(s.to_string());
1657 }
1658 parsed
1659 }
1660 Some(_) => return json_error(400, "field args must be an array of strings"),
1661 };
1662 let headers = match parse_string_map(&obj, "headers") {
1663 Ok(m) => m,
1664 Err(resp) => return resp,
1665 };
1666 let env = match parse_string_map(&obj, "env") {
1667 Ok(m) => m,
1668 Err(resp) => return resp,
1669 };
1670 let oauth = match parse_optional_oauth_config(&obj) {
1671 Ok(o) => o,
1672 Err(resp) => return resp,
1673 };
1674 let approval = match obj.get("approval") {
1675 None | Some(serde_json::Value::Null) => crate::mcp::ApprovalPolicy::ReadOnly,
1676 Some(serde_json::Value::String(s)) => match parse_approval_policy(s) {
1677 Ok(p) => p,
1678 Err(resp) => return resp,
1679 },
1680 Some(_) => return json_error(400, "field approval must be a string"),
1681 };
1682 let replace = match obj.get("replace") {
1683 None | Some(serde_json::Value::Null) => false,
1684 Some(serde_json::Value::Bool(b)) => *b,
1685 Some(_) => return json_error(400, "field replace must be a boolean"),
1686 };
1687 let config = match (url, command) {
1688 (Some(url), None) => {
1689 let mut cfg = crate::mcp::ServerConfig::http(url, headers, approval);
1690 cfg.oauth = oauth;
1691 cfg
1692 }
1693 (None, Some(command)) => {
1694 if oauth.is_some() {
1695 return json_error(
1696 400,
1697 "oauth settings can only be configured for HTTP servers",
1698 );
1699 }
1700 crate::mcp::ServerConfig::stdio(command, args, env, approval)
1701 }
1702 (Some(_), Some(_)) => {
1703 return json_error(400, "specify either url or command, not both");
1704 }
1705 (None, None) => {
1706 return json_error(400, "must specify either url or command");
1707 }
1708 };
1709 match surface.mcp.add_server(name, config, replace) {
1710 Ok(snapshot) => mcp_server_response(surface, snapshot),
1711 Err(err) => mcp_error_response(surface, err),
1712 }
1713}
1714
1715fn handle_mcp_oauth_server(surface: &Surface, name: &str, req: &Request) -> Response {
1716 let obj = match parse_json_object(&req.body) {
1717 Ok(o) => o,
1718 Err(resp) => return resp,
1719 };
1720 let patch_obj = match obj.get("oauth") {
1721 Some(serde_json::Value::Object(inner)) => inner,
1722 Some(serde_json::Value::Null) => {
1723 return match surface.mcp.update_server_oauth(
1724 name,
1725 crate::mcp::OAuthConfigPatch {
1726 clear_client_secret: true,
1727 ..crate::mcp::OAuthConfigPatch::default()
1728 },
1729 ) {
1730 Ok(snapshot) => mcp_server_response(surface, snapshot),
1731 Err(err) => mcp_error_response(surface, err),
1732 };
1733 }
1734 Some(_) => return json_error(400, "field oauth must be an object"),
1735 None => &obj,
1736 };
1737 let patch = match parse_oauth_patch_object(patch_obj) {
1738 Ok(p) => p,
1739 Err(resp) => return resp,
1740 };
1741 match surface.mcp.update_server_oauth(name, patch) {
1742 Ok(snapshot) => mcp_server_response(surface, snapshot),
1743 Err(err) => mcp_error_response(surface, err),
1744 }
1745}
1746
1747fn handle_mcp_remove_server(surface: &Surface, name: &str) -> Response {
1748 if let Some(existing) = surface.mcp.get_server(name) {
1749 if existing.source == crate::mcp::ServerSource::Project {
1750 return json_error(
1751 400,
1752 format!(
1753 "MCP server '{name}' is defined in project .mcp.json and cannot be removed here"
1754 ),
1755 );
1756 }
1757 }
1758 match surface.mcp.remove_server(name) {
1759 Ok(()) => Response::json(200, &serde_json::json!({ "removed": name })),
1760 Err(err) => mcp_error_response(surface, err),
1761 }
1762}
1763
1764fn handle_mcp_toggle_server(surface: &Surface, name: &str, req: &Request) -> Response {
1765 let obj = match parse_json_object(&req.body) {
1766 Ok(o) => o,
1767 Err(resp) => return resp,
1768 };
1769 let Some(enabled) = obj.get("enabled").and_then(|v| v.as_bool()) else {
1770 return json_error(400, "missing or invalid boolean field enabled");
1771 };
1772 match surface.mcp.set_enabled(name, enabled) {
1773 Ok(snapshot) => mcp_server_response(surface, snapshot),
1774 Err(err) => mcp_error_response(surface, err),
1775 }
1776}
1777
1778fn handle_mcp_approval_server(surface: &Surface, name: &str, req: &Request) -> Response {
1779 let obj = match parse_json_object(&req.body) {
1780 Ok(o) => o,
1781 Err(resp) => return resp,
1782 };
1783 let Some(raw_approval) = obj.get("approval").and_then(|v| v.as_str()) else {
1784 return json_error(400, "missing or invalid string field approval");
1785 };
1786 let policy = match parse_approval_policy(raw_approval) {
1787 Ok(p) => p,
1788 Err(resp) => return resp,
1789 };
1790 match surface.mcp.set_approval_policy(name, policy) {
1791 Ok(snapshot) => mcp_server_response(surface, snapshot),
1792 Err(err) => mcp_error_response(surface, err),
1793 }
1794}
1795
1796fn handle_mcp_trust_server(surface: &Surface, name: &str) -> Response {
1797 match surface.mcp.trust_project_server(name) {
1798 Ok(snapshot) => mcp_server_response(surface, snapshot),
1799 Err(err) => mcp_error_response(surface, err),
1800 }
1801}
1802
1803fn handle_mcp_reconnect_server(surface: &Surface, name: &str) -> Response {
1804 match surface.mcp.reconnect_server(name) {
1805 Ok(snapshot) => mcp_server_response(surface, snapshot),
1806 Err(err) => mcp_error_response(surface, err),
1807 }
1808}
1809
1810fn handle_mcp_auth_server(surface: &Surface, name: &str) -> Response {
1811 match surface.mcp.start_oauth(name) {
1812 Ok(authorize_url) => {
1813 let auth_store = match load_mcp_auth_store(surface) {
1814 Ok(store) => store,
1815 Err(resp) => return resp,
1816 };
1817 let server = surface
1818 .mcp
1819 .get_server(name)
1820 .map(|snap| mcp_server_to_api(surface, snap, &auth_store));
1821 let server_val = match server {
1822 Some(s) => match serde_json::to_value(&s) {
1823 Ok(v) => v,
1824 Err(e) => {
1825 return json_error(500, format!("failed to serialize MCP server: {e}"))
1826 }
1827 },
1828 None => serde_json::Value::Null,
1829 };
1830 Response::json(
1831 200,
1832 &serde_json::json!({
1833 "authorize_url": authorize_url,
1834 "server": server_val,
1835 }),
1836 )
1837 }
1838 Err(err) => mcp_error_response(surface, err),
1839 }
1840}
1841
1842fn handle_mcp_logout_server(surface: &Surface, name: &str) -> Response {
1843 match surface.mcp.logout_server(name) {
1844 Ok(snapshot) => mcp_server_response(surface, snapshot),
1845 Err(err) => mcp_error_response(surface, err),
1846 }
1847}
1848
1849#[derive(Clone, Copy)]
1850enum ApiGetHandler {
1851 Session,
1852 Events,
1853 Models,
1854 Runs,
1855 Requests,
1856 Map,
1857 RunDiff,
1858 Usage,
1859}
1860
1861const API_GET_ROUTES: &[(&str, ApiGetHandler)] = &[
1862 ("/api/session", ApiGetHandler::Session),
1863 ("/api/session/events", ApiGetHandler::Events),
1864 ("/api/models", ApiGetHandler::Models),
1865 ("/api/runs", ApiGetHandler::Runs),
1866 ("/api/requests", ApiGetHandler::Requests),
1867 ("/api/map", ApiGetHandler::Map),
1868 ("/api/runs/{id}/diff", ApiGetHandler::RunDiff),
1869 ("/api/usage", ApiGetHandler::Usage),
1870];
1871
1872pub fn authenticated_api_get_routes() -> Vec<&'static str> {
1873 let mut routes: Vec<&'static str> =
1874 API_GET_ROUTES.iter().map(|(pattern, _)| *pattern).collect();
1875 routes.push("/api/mcp/servers");
1876 routes
1877}
1878
1879fn match_api_get_route<'a>(pattern: &str, path: &'a str) -> Option<Option<&'a str>> {
1880 if let Some((prefix, suffix)) = pattern.split_once("{id}") {
1881 let rest = path.strip_prefix(prefix)?;
1882 let id = rest.strip_suffix(suffix)?;
1883 if !id.is_empty() && !id.contains('/') {
1884 return Some(Some(id));
1885 }
1886 None
1887 } else if pattern == path {
1888 Some(None)
1889 } else {
1890 None
1891 }
1892}
1893
1894fn handle_post_open_code(surface: &Surface, now: u64) -> Response {
1895 match surface.open_codes.issue(now) {
1896 Ok(code) => Response::json(200, &serde_json::json!({ "code": code })),
1897 Err(e) => json_error(500, e),
1898 }
1899}
1900
1901fn handle_post_open(surface: &Surface, req: &Request, now: u64) -> Response {
1902 let forbidden = Response {
1903 status: 403,
1904 content_type: "application/json",
1905 body: b"{}".to_vec(),
1906 };
1907 let Ok(value) = serde_json::from_slice::<serde_json::Value>(&req.body) else {
1908 return forbidden;
1909 };
1910 let Some(code) = value.get("code").and_then(|v| v.as_str()) else {
1911 return forbidden;
1912 };
1913 match surface.open_codes.redeem(code, now) {
1914 Ok(true) => Response::json(200, &serde_json::json!({ "token": surface.token })),
1915 Ok(false) => forbidden,
1916 Err(e) => json_error(500, e),
1917 }
1918}
1919
1920pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
1921 route_inner(surface, req, now, None, None)
1922}
1923
1924fn route_inner(
1925 surface: &Surface,
1926 req: &Request,
1927 now: u64,
1928 stop_trigger: Option<&StopTrigger>,
1929 reload_trigger: Option<&ReloadTrigger>,
1930) -> Response {
1931 if req.path == "/api/peer/messages" && req.method == "POST" {
1932 if !has_valid_message_credential(surface, req) {
1933 return json_error(403, "missing or invalid message credential");
1934 }
1935 return handle_post_peer_message(surface, req);
1936 }
1937
1938 let is_health_get = req.path == "/api/health" && req.method == "GET";
1939 let is_open_post = req.path == "/api/open" && req.method == "POST";
1940 if (req.path.starts_with("/api/") || req.method == "POST" || req.method == "DELETE")
1941 && !is_health_get
1942 && !is_open_post
1943 && !has_valid_token(surface, req)
1944 {
1945 return json_error(
1946 403,
1947 "missing or invalid surface token; open the page from the URL blyte printed",
1948 );
1949 }
1950
1951 if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
1952 if req.method != "GET" {
1953 return method_not_allowed(req);
1954 }
1955 return Response {
1956 status,
1957 content_type,
1958 body,
1959 };
1960 }
1961
1962 if req.path == "/" || req.path == "/index.html" {
1963 if req.method != "GET" {
1964 return method_not_allowed(req);
1965 }
1966 return Response::html(INDEX_HTML.as_bytes().to_vec());
1967 }
1968
1969 if req.path == "/usage" {
1970 if req.method != "GET" {
1971 return method_not_allowed(req);
1972 }
1973 return Response::html(USAGE_HTML.as_bytes().to_vec());
1974 }
1975
1976 if req.path == "/api/health" {
1977 if req.method != "GET" {
1978 return method_not_allowed(req);
1979 }
1980 return health_response(surface);
1981 }
1982
1983 for &(pattern, handler) in API_GET_ROUTES {
1984 if let Some(id) = match_api_get_route(pattern, &req.path) {
1985 if req.method != "GET" {
1986 return method_not_allowed(req);
1987 }
1988 return match handler {
1989 ApiGetHandler::Session => session_response(surface),
1990 ApiGetHandler::Events => handle_events(surface, req),
1991 ApiGetHandler::Models => handle_models(surface),
1992 ApiGetHandler::Runs => handle_runs(surface, now),
1993 ApiGetHandler::Requests => handle_requests(surface),
1994 ApiGetHandler::Map => handle_map(surface),
1995 ApiGetHandler::RunDiff => handle_run_diff(surface, id.unwrap_or("")),
1996 ApiGetHandler::Usage => handle_usage(req, now),
1997 };
1998 }
1999 }
2000
2001 match req.path.as_str() {
2002 "/api/open" => {
2003 if req.method != "POST" {
2004 return method_not_allowed(req);
2005 }
2006 handle_post_open(surface, req, now)
2007 }
2008 "/api/surfaces" => {
2009 if req.method != "GET" {
2010 return method_not_allowed(req);
2011 }
2012 handle_surfaces(surface)
2013 }
2014 "/api/surfaces/start" => {
2015 if req.method != "POST" {
2016 return method_not_allowed(req);
2017 }
2018 handle_post_start_surface(req)
2019 }
2020 "/api/session/stop" => {
2021 if req.method != "POST" {
2022 return method_not_allowed(req);
2023 }
2024 handle_post_stop(stop_trigger)
2025 }
2026 "/api/stop" => {
2027 if req.method != "POST" {
2028 return method_not_allowed(req);
2029 }
2030 handle_post_api_stop(surface, req, stop_trigger)
2031 }
2032 "/api/reload" => {
2033 if req.method != "POST" {
2034 return method_not_allowed(req);
2035 }
2036 handle_post_reload(surface, reload_trigger)
2037 }
2038 "/api/session/open-codes" => {
2039 if req.method != "POST" {
2040 return method_not_allowed(req);
2041 }
2042 handle_post_open_code(surface, now)
2043 }
2044 "/api/session/messages" => {
2045 if req.method != "POST" {
2046 return method_not_allowed(req);
2047 }
2048 handle_post_message(surface, req)
2049 }
2050 "/api/session/attachments" => {
2051 if req.method != "POST" {
2052 return method_not_allowed(req);
2053 }
2054 handle_post_attachment(surface, req)
2055 }
2056 "/api/session/model" => {
2057 if req.method != "POST" {
2058 return method_not_allowed(req);
2059 }
2060 handle_post_model(surface, req)
2061 }
2062 "/api/session/effort" => {
2063 if req.method != "POST" {
2064 return method_not_allowed(req);
2065 }
2066 handle_post_effort(surface, req)
2067 }
2068 "/api/session/seen" => {
2069 if req.method != "POST" {
2070 return method_not_allowed(req);
2071 }
2072 handle_post_seen(surface)
2073 }
2074 "/api/runs/changed" => {
2075 if req.method != "POST" {
2076 return method_not_allowed(req);
2077 }
2078 handle_runs_changed(surface)
2079 }
2080 "/api/mcp/servers" => match req.method.as_str() {
2081 "GET" => handle_mcp_list_servers(surface),
2082 "POST" => handle_mcp_add_server(surface, req),
2083 _ => method_not_allowed(req),
2084 },
2085 path => {
2086 if let Some(rest) = path.strip_prefix("/api/mcp/servers/") {
2087 if !rest.is_empty() && !rest.contains('/') {
2088 if req.method != "DELETE" {
2089 return method_not_allowed(req);
2090 }
2091 return handle_mcp_remove_server(surface, rest);
2092 }
2093 if let Some((name, action)) = rest.split_once('/') {
2094 if !name.is_empty() && !action.contains('/') {
2095 if req.method != "POST" {
2096 return method_not_allowed(req);
2097 }
2098 return match action {
2099 "remove" => handle_mcp_remove_server(surface, name),
2100 "toggle" => handle_mcp_toggle_server(surface, name, req),
2101 "approval" => handle_mcp_approval_server(surface, name, req),
2102 "oauth" => handle_mcp_oauth_server(surface, name, req),
2103 "trust" => handle_mcp_trust_server(surface, name),
2104 "reconnect" => handle_mcp_reconnect_server(surface, name),
2105 "auth" => handle_mcp_auth_server(surface, name),
2106 "logout" => handle_mcp_logout_server(surface, name),
2107 _ => json_error(404, "not found"),
2108 };
2109 }
2110 }
2111 }
2112 if let Some(id) = path.strip_prefix("/api/session/attachments/") {
2113 if !id.is_empty() && !id.contains('/') {
2114 if req.method != "GET" {
2115 return method_not_allowed(req);
2116 }
2117 return handle_get_attachment(surface, id);
2118 }
2119 }
2120 if let Some(id) = path.strip_prefix("/api/session/approvals/") {
2121 if !id.is_empty() && !id.contains('/') {
2122 if req.method != "POST" {
2123 return method_not_allowed(req);
2124 }
2125 return handle_post_approval(surface, id, req);
2126 }
2127 }
2128 if let Some(rest) = path.strip_prefix("/api/runs/") {
2129 if let Some(id) = rest.strip_suffix("/decision") {
2130 if !id.is_empty() && !id.contains('/') {
2131 if req.method != "POST" {
2132 return method_not_allowed(req);
2133 }
2134 return handle_run_decision(surface, id, req, now);
2135 }
2136 }
2137 if let Some(id) = rest.strip_suffix("/undo") {
2138 if !id.is_empty() && !id.contains('/') {
2139 if req.method != "POST" {
2140 return method_not_allowed(req);
2141 }
2142 return handle_run_undo(surface, id);
2143 }
2144 }
2145 }
2146 if let Some(rest) = path.strip_prefix("/api/requests/") {
2147 if let Some(id) = rest.strip_suffix("/push") {
2148 if req.method != "POST" {
2149 return method_not_allowed(req);
2150 }
2151 return handle_request_push(surface, id);
2152 }
2153 if let Some(id) = rest.strip_suffix("/pull-request") {
2154 if req.method != "POST" {
2155 return method_not_allowed(req);
2156 }
2157 return handle_request_pull_request(surface, id, req);
2158 }
2159 }
2160 json_error(404, format!("not found: {}", req.path))
2161 }
2162 }
2163}
2164
2165enum GitToplevel {
2166 Repository(PathBuf),
2167 NotARepository,
2168}
2169
2170fn find_git_toplevel(dir: &Path) -> Result<GitToplevel, String> {
2171 let out = Command::new("git")
2172 .args(["rev-parse", "--show-toplevel"])
2173 .env("LC_ALL", "C")
2174 .current_dir(dir)
2175 .output()
2176 .map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
2177 if !out.status.success() {
2178 let stderr = String::from_utf8_lossy(&out.stderr);
2179 if stderr.contains("not a git repository (or any") {
2180 return Ok(GitToplevel::NotARepository);
2181 }
2182 let detail = stderr.trim();
2183 if detail.is_empty() {
2184 return Err(format!("not inside a git repository ({})", dir.display()));
2185 }
2186 return Err(format!(
2187 "not inside a git repository ({}): {detail}",
2188 dir.display()
2189 ));
2190 }
2191 let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
2192 if path_str.is_empty() {
2193 return Err(format!("not inside a git repository ({})", dir.display()));
2194 }
2195 Ok(GitToplevel::Repository(PathBuf::from(path_str)))
2196}
2197
2198pub(crate) fn is_repository(root: &Path) -> Result<bool, String> {
2199 match find_git_toplevel(root)? {
2200 GitToplevel::Repository(_) => Ok(true),
2201 GitToplevel::NotARepository => Ok(false),
2202 }
2203}
2204
2205fn resolve_denied_path(denied: &Path) -> Result<PathBuf, String> {
2206 let mut probe = denied;
2207 let mut tail = Vec::new();
2208 loop {
2209 match probe.canonicalize() {
2210 Ok(mut resolved) => {
2211 for part in tail.into_iter().rev() {
2212 resolved.push(part);
2213 }
2214 return Ok(resolved);
2215 }
2216 Err(e)
2217 if matches!(
2218 e.kind(),
2219 std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
2220 ) =>
2221 {
2222 let Some(name) = probe.file_name() else {
2223 return Err(format!("cannot canonicalize {}: {e}", denied.display()));
2224 };
2225 let Some(parent) = probe.parent() else {
2226 return Err(format!("cannot canonicalize {}: {e}", denied.display()));
2227 };
2228 tail.push(name.to_os_string());
2229 probe = parent;
2230 }
2231 Err(e) => {
2232 return Err(format!("cannot canonicalize {}: {e}", denied.display()));
2233 }
2234 }
2235 }
2236}
2237
2238pub fn check_linux_non_repo_root(root: &Path, home: &Path) -> Result<(), String> {
2239 let root_canon = root
2240 .canonicalize()
2241 .map_err(|e| format!("cannot canonicalize {}: {e}", root.display()))?;
2242 let home_canon = home
2243 .canonicalize()
2244 .map_err(|e| format!("cannot canonicalize home directory {}: {e}", home.display()))?;
2245 for denied in blyte_agent::sandbox::read_denied(&home_canon) {
2246 let denied_canon = resolve_denied_path(&denied)?;
2247 if denied.starts_with(&root_canon) || denied_canon.starts_with(&root_canon) {
2248 return Err(format!(
2249 "on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
2250 root_canon.display(),
2251 denied.display()
2252 ));
2253 }
2254 }
2255 if home_canon.starts_with(&root_canon) {
2256 return Err(format!(
2257 "on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
2258 root_canon.display(),
2259 home_canon.display()
2260 ));
2261 }
2262 Ok(())
2263}
2264
2265pub fn check_linux_non_repo_root_for_env(
2266 root: &Path,
2267 home: Option<&std::ffi::OsStr>,
2268) -> Result<(), String> {
2269 let home = home.filter(|h| !h.is_empty()).ok_or_else(|| {
2270 format!(
2271 "cannot check whether {} contains protected paths on Linux: HOME is not set",
2272 root.display()
2273 )
2274 })?;
2275 check_linux_non_repo_root(root, Path::new(home))
2276}
2277
2278fn resolve_main_checkout(worktree_root: &Path) -> Result<PathBuf, String> {
2279 let out = Command::new("git")
2280 .args([
2281 "rev-parse",
2282 "--path-format=absolute",
2283 "--git-dir",
2284 "--git-common-dir",
2285 ])
2286 .current_dir(worktree_root)
2287 .output()
2288 .map_err(|_| {
2289 format!(
2290 "cannot find the main checkout of {}",
2291 worktree_root.display()
2292 )
2293 })?;
2294 if !out.status.success() {
2295 return Err(format!(
2296 "cannot find the main checkout of {}",
2297 worktree_root.display()
2298 ));
2299 }
2300 let text = String::from_utf8_lossy(&out.stdout);
2301 let mut lines = text.lines();
2302 let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
2303 return Err(format!(
2304 "cannot find the main checkout of {}",
2305 worktree_root.display()
2306 ));
2307 };
2308 let git_dir_path = PathBuf::from(git_dir.trim());
2309 let common_dir_path = PathBuf::from(common_dir.trim());
2310 let git_dir_canon = git_dir_path
2311 .canonicalize()
2312 .map_err(|e| format!("cannot canonicalize {}: {e}", git_dir_path.display()))?;
2313 let common_dir_canon = common_dir_path
2314 .canonicalize()
2315 .map_err(|e| format!("cannot canonicalize {}: {e}", common_dir_path.display()))?;
2316 if git_dir_canon == common_dir_canon {
2317 return worktree_root
2318 .canonicalize()
2319 .map_err(|e| format!("cannot canonicalize {}: {e}", worktree_root.display()));
2320 }
2321 let main = crate::config::main_checkout(worktree_root).ok_or_else(|| {
2322 format!(
2323 "cannot find the main checkout of {}",
2324 worktree_root.display()
2325 )
2326 })?;
2327 main.canonicalize()
2328 .map_err(|e| format!("cannot canonicalize {}: {e}", main.display()))
2329}
2330
2331pub(crate) fn resolve_folder(folder: &Path) -> Result<PathBuf, String> {
2332 match find_git_toplevel(folder)? {
2333 GitToplevel::Repository(worktree_root) => resolve_main_checkout(&worktree_root),
2334 GitToplevel::NotARepository => folder
2335 .canonicalize()
2336 .map_err(|e| format!("cannot canonicalize {}: {e}", folder.display())),
2337 }
2338}
2339
2340fn current_branch(main_checkout: &Path) -> Result<Option<String>, String> {
2341 match find_git_toplevel(main_checkout)? {
2342 GitToplevel::NotARepository => return Ok(None),
2343 GitToplevel::Repository(_) => {}
2344 }
2345 if let Ok(out) = Command::new("git")
2346 .args(["rev-parse", "--abbrev-ref", "HEAD"])
2347 .current_dir(main_checkout)
2348 .output()
2349 {
2350 if out.status.success() {
2351 let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
2352 if !branch.is_empty() {
2353 return Ok(Some(branch));
2354 }
2355 }
2356 }
2357 if let Ok(out) = Command::new("git")
2358 .args(["symbolic-ref", "--short", "HEAD"])
2359 .current_dir(main_checkout)
2360 .output()
2361 {
2362 if out.status.success() {
2363 let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
2364 if !branch.is_empty() {
2365 return Ok(Some(branch));
2366 }
2367 }
2368 }
2369 Err(format!(
2370 "cannot read the current branch of {}",
2371 main_checkout.display()
2372 ))
2373}
2374
2375fn repo_name_for(root: &Path) -> Result<String, String> {
2376 root.file_name()
2377 .and_then(|s| s.to_str())
2378 .filter(|s| !s.is_empty())
2379 .map(String::from)
2380 .ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
2381}
2382
2383fn now_duration() -> Result<Duration, String> {
2384 SystemTime::now()
2385 .duration_since(UNIX_EPOCH)
2386 .map_err(|e| format!("system clock is before Unix epoch: {e}"))
2387}
2388
2389fn new_session_id(nanos: u128) -> String {
2390 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
2391 format!("surface-{}-{nanos}-{seq}", std::process::id())
2392}
2393
2394pub fn open_browser_in(open_in: OpenIn, url: &str) {
2395 crate::open_window::open_url(open_in, url);
2396}
2397
2398pub fn open_browser(url: &str) {
2399 open_browser_in(OpenIn::App, url);
2400}
2401
2402fn resolve_initial_model(config: &ReplConfig) -> String {
2403 if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
2404 return m.to_string();
2405 }
2406 if let Ok(m) = std::env::var("BLYTE_MODEL") {
2407 if !m.trim().is_empty() {
2408 return m;
2409 }
2410 }
2411 if let Ok(p) = blyte_provider::resolve_provider(None) {
2412 return p.model_id();
2413 }
2414 "gemini-3.8-flash-high".to_string()
2415}
2416
2417static SIGNAL_STOP: AtomicBool = AtomicBool::new(false);
2418static SIGNAL_INTERRUPT: AtomicBool = AtomicBool::new(false);
2419
2420#[cfg(unix)]
2421extern "C" fn handle_shutdown_signal(_: libc::c_int) {
2422 SIGNAL_STOP.store(true, Ordering::Relaxed);
2423}
2424
2425#[cfg(unix)]
2426extern "C" fn handle_interrupt_signal(_: libc::c_int) {
2427 SIGNAL_INTERRUPT.store(true, Ordering::Relaxed);
2428}
2429
2430fn ensure_token_dir(dir: &Path) -> Result<(), String> {
2431 #[cfg(unix)]
2432 {
2433 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
2434 if let Some(parent) = dir.parent() {
2435 std::fs::create_dir_all(parent)
2436 .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
2437 }
2438 let mut builder = std::fs::DirBuilder::new();
2439 builder.mode(0o700);
2440 match builder.create(dir) {
2441 Ok(()) => {}
2442 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2443 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
2444 .map_err(|e| format!("cannot set permissions on {}: {e}", dir.display()))?;
2445 }
2446 Err(e) => return Err(format!("cannot create {}: {e}", dir.display())),
2447 }
2448 Ok(())
2449 }
2450 #[cfg(not(unix))]
2451 {
2452 std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))
2453 }
2454}
2455
2456fn write_token_file(token_file_path: &Path, token: &str) -> Result<(), String> {
2457 let token_dir = token_file_path
2458 .parent()
2459 .ok_or_else(|| format!("invalid token path {}", token_file_path.display()))?;
2460 ensure_token_dir(token_dir)?;
2461 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
2462 let tmp_path = token_dir.join(format!(".surface.token.{}.{seq}.tmp", std::process::id()));
2463 let mut opts = std::fs::OpenOptions::new();
2464 opts.write(true).create_new(true);
2465 #[cfg(unix)]
2466 {
2467 opts.mode(0o600);
2468 }
2469 let mut file = opts
2470 .open(&tmp_path)
2471 .map_err(|e| format!("cannot create {}: {e}", token_file_path.display()))?;
2472 if let Err(e) = writeln!(file, "{token}") {
2473 let _ = std::fs::remove_file(&tmp_path);
2474 return Err(format!("cannot write {}: {e}", token_file_path.display()));
2475 }
2476 drop(file);
2477 if let Err(e) = std::fs::rename(&tmp_path, token_file_path) {
2478 let _ = std::fs::remove_file(&tmp_path);
2479 return Err(format!("cannot write {}: {e}", token_file_path.display()));
2480 }
2481 Ok(())
2482}
2483
2484struct TokenFileGuard {
2485 path: Option<PathBuf>,
2486}
2487
2488impl TokenFileGuard {
2489 fn new(path: PathBuf) -> Self {
2490 Self { path: Some(path) }
2491 }
2492
2493 fn disarm(&mut self) {
2494 self.path = None;
2495 }
2496}
2497
2498impl Drop for TokenFileGuard {
2499 fn drop(&mut self) {
2500 if let Some(ref path) = self.path {
2501 let _ = std::fs::remove_file(path);
2502 }
2503 }
2504}
2505
2506struct RegistryEntryGuard {
2507 dir: PathBuf,
2508 id: String,
2509}
2510
2511impl Drop for RegistryEntryGuard {
2512 fn drop(&mut self) {
2513 let _ = crate::surface_registry::remove_entry(&self.dir, &self.id);
2514 }
2515}
2516
2517struct PrivateTmpDirGuard {
2518 path: PathBuf,
2519}
2520
2521impl Drop for PrivateTmpDirGuard {
2522 fn drop(&mut self) {
2523 let _ = std::fs::remove_dir_all(&self.path);
2524 }
2525}
2526
2527struct PublishToolGuard;
2528
2529impl PublishToolGuard {
2530 fn install(surface: Arc<Surface>) -> Self {
2531 blyte_agent::tools::set_publish_tool(Some(Arc::new(
2532 crate::requests::SurfacePublishTool::new(surface),
2533 )));
2534 Self
2535 }
2536}
2537
2538impl Drop for PublishToolGuard {
2539 fn drop(&mut self) {
2540 blyte_agent::tools::set_publish_tool(None);
2541 }
2542}
2543
2544struct LandToolGuard;
2545
2546impl LandToolGuard {
2547 fn install(surface: Arc<Surface>) -> Self {
2548 blyte_agent::tools::set_land_tool(Some(Arc::new(crate::land::SurfaceLandTool::new(
2549 surface,
2550 ))));
2551 Self
2552 }
2553}
2554
2555impl Drop for LandToolGuard {
2556 fn drop(&mut self) {
2557 blyte_agent::tools::set_land_tool(None);
2558 }
2559}
2560
2561pub struct FrontEndContext {
2562 pub surface: Arc<Surface>,
2563 pub take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
2564}
2565
2566pub type FrontEnd = Box<dyn FnOnce(FrontEndContext) -> i32 + Send>;
2567
2568struct FrontEndSpec {
2569 front: FrontEnd,
2570 take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
2571}
2572
2573#[derive(Clone, Copy)]
2574enum FrontEndOutcome {
2575 Exited(i32),
2576 Panicked,
2577}
2578
2579struct StopControl<S> {
2580 should_stop: S,
2581 trigger: StopTrigger,
2582}
2583
2584fn atomic_stop_control(stop: Arc<AtomicBool>) -> StopControl<impl Fn() -> bool> {
2585 let stop_trigger_flag = Arc::clone(&stop);
2586 StopControl {
2587 should_stop: move || stop.load(Ordering::Acquire),
2588 trigger: Arc::new(move || stop_trigger_flag.store(true, Ordering::Release)),
2589 }
2590}
2591
2592pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
2593 SIGNAL_STOP.store(false, Ordering::Relaxed);
2594 #[cfg(unix)]
2595 unsafe {
2596 libc::signal(
2597 libc::SIGINT,
2598 handle_shutdown_signal as *const () as libc::sighandler_t,
2599 );
2600 libc::signal(
2601 libc::SIGTERM,
2602 handle_shutdown_signal as *const () as libc::sighandler_t,
2603 );
2604 }
2605 let open_in = args.open_in;
2606 let mut opener = |url: &str| open_browser_in(open_in, url);
2607 let stop_control = StopControl {
2608 should_stop: || SIGNAL_STOP.load(Ordering::Acquire),
2609 trigger: Arc::new(|| SIGNAL_STOP.store(true, Ordering::Release)),
2610 };
2611 run_inner(
2612 args,
2613 config,
2614 &mut std::io::stdout(),
2615 &mut std::io::stderr(),
2616 &mut opener,
2617 stop_control,
2618 None,
2619 None,
2620 )
2621}
2622
2623pub fn run_terminal(args: &SurfaceArgs, config: ReplConfig) -> i32 {
2624 run_with_front_end(
2625 args,
2626 config,
2627 Box::new(|ctx| {
2628 let stdin = std::io::stdin();
2629 let input_is_terminal = std::io::IsTerminal::is_terminal(&stdin);
2630 let mut stdout = std::io::stdout();
2631 let root = ctx.surface.root.clone();
2632 let options = crate::terminal_front::TerminalOptions {
2633 input_is_terminal,
2634 settle: Duration::from_secs(3),
2635 take_interrupt: ctx.take_interrupt,
2636 runs_working: Arc::new(move || crate::surfaces_cmd::count_running_runs(&root)),
2637 };
2638 crate::terminal_front::run_terminal_front(
2639 &ctx.surface.session,
2640 Box::new(std::io::BufReader::new(stdin)),
2641 &mut stdout,
2642 options,
2643 )
2644 }),
2645 )
2646}
2647
2648pub fn run_with_front_end(args: &SurfaceArgs, config: ReplConfig, front: FrontEnd) -> i32 {
2649 SIGNAL_STOP.store(false, Ordering::Relaxed);
2650 SIGNAL_INTERRUPT.store(false, Ordering::Relaxed);
2651 #[cfg(unix)]
2652 unsafe {
2653 libc::signal(
2654 libc::SIGINT,
2655 handle_interrupt_signal as *const () as libc::sighandler_t,
2656 );
2657 libc::signal(
2658 libc::SIGTERM,
2659 handle_shutdown_signal as *const () as libc::sighandler_t,
2660 );
2661 }
2662 let mut opener = |_: &str| {};
2663 let stop_control = StopControl {
2664 should_stop: || SIGNAL_STOP.load(Ordering::Acquire),
2665 trigger: Arc::new(|| SIGNAL_STOP.store(true, Ordering::Release)),
2666 };
2667 let take_interrupt: Arc<dyn Fn() -> bool + Send + Sync> =
2668 Arc::new(|| SIGNAL_INTERRUPT.swap(false, Ordering::AcqRel));
2669 run_inner(
2670 args,
2671 config,
2672 &mut std::io::stdout(),
2673 &mut std::io::stderr(),
2674 &mut opener,
2675 stop_control,
2676 None,
2677 Some(FrontEndSpec {
2678 front,
2679 take_interrupt,
2680 }),
2681 )
2682}
2683
2684pub fn run_with_io(
2685 args: &SurfaceArgs,
2686 config: ReplConfig,
2687 out: &mut dyn Write,
2688 err: &mut dyn Write,
2689) -> i32 {
2690 let open_in = args.open_in;
2691 let mut opener = |url: &str| open_browser_in(open_in, url);
2692 let stop = Arc::new(AtomicBool::new(false));
2693 run_inner(
2694 args,
2695 config,
2696 out,
2697 err,
2698 &mut opener,
2699 atomic_stop_control(stop),
2700 None,
2701 None,
2702 )
2703}
2704
2705pub fn run_with_hooks(
2706 args: &SurfaceArgs,
2707 config: ReplConfig,
2708 out: &mut dyn Write,
2709 err: &mut dyn Write,
2710 opener: &mut dyn FnMut(&str),
2711 stop: Arc<AtomicBool>,
2712) -> i32 {
2713 run_inner(
2714 args,
2715 config,
2716 out,
2717 err,
2718 opener,
2719 atomic_stop_control(stop),
2720 None,
2721 None,
2722 )
2723}
2724
2725pub type RunnerFactory = Box<
2726 dyn FnOnce(
2727 &ReplConfig,
2728 Arc<dyn blyte_agent::approval::Approver>,
2729 ) -> Result<(Box<dyn PromptRunner>, Option<PathBuf>), String>,
2730>;
2731
2732pub fn run_with_runner(
2733 args: &SurfaceArgs,
2734 config: ReplConfig,
2735 out: &mut dyn Write,
2736 err: &mut dyn Write,
2737 opener: &mut dyn FnMut(&str),
2738 stop: Arc<AtomicBool>,
2739 runner: Box<dyn PromptRunner>,
2740) -> i32 {
2741 run_inner(
2742 args,
2743 config,
2744 out,
2745 err,
2746 opener,
2747 atomic_stop_control(stop),
2748 Some(Box::new(|_, _| Ok((runner, None)))),
2749 None,
2750 )
2751}
2752
2753#[allow(clippy::too_many_arguments)]
2754pub fn run_with_front_end_and_runner(
2755 args: &SurfaceArgs,
2756 config: ReplConfig,
2757 out: &mut dyn Write,
2758 err: &mut dyn Write,
2759 stop: Arc<AtomicBool>,
2760 take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
2761 runner: Box<dyn PromptRunner>,
2762 front: FrontEnd,
2763) -> i32 {
2764 let mut opener = |_: &str| {};
2765 run_inner(
2766 args,
2767 config,
2768 out,
2769 err,
2770 &mut opener,
2771 atomic_stop_control(stop),
2772 Some(Box::new(|_, _| Ok((runner, None)))),
2773 Some(FrontEndSpec {
2774 front,
2775 take_interrupt,
2776 }),
2777 )
2778}
2779
2780pub fn run_with_runner_factory(
2781 args: &SurfaceArgs,
2782 config: ReplConfig,
2783 out: &mut dyn Write,
2784 err: &mut dyn Write,
2785 opener: &mut dyn FnMut(&str),
2786 stop: Arc<AtomicBool>,
2787 factory: RunnerFactory,
2788) -> i32 {
2789 run_inner(
2790 args,
2791 config,
2792 out,
2793 err,
2794 opener,
2795 atomic_stop_control(stop),
2796 Some(factory),
2797 None,
2798 )
2799}
2800
2801struct ReconcileTimerGuard {
2802 stop: Arc<AtomicBool>,
2803 handle: Option<std::thread::JoinHandle<()>>,
2804}
2805
2806impl Drop for ReconcileTimerGuard {
2807 fn drop(&mut self) {
2808 self.stop.store(true, Ordering::Release);
2809 if let Some(handle) = self.handle.take() {
2810 let _ = handle.join();
2811 }
2812 }
2813}
2814
2815fn spawn_reconcile_timer(surface: Arc<Surface>) -> ReconcileTimerGuard {
2816 let stop = Arc::new(AtomicBool::new(false));
2817 let thread_stop = Arc::clone(&stop);
2818 let handle = std::thread::spawn(move || {
2819 let mut after = surface.session.info().last_seq;
2820 let mut next_tick = Instant::now();
2821 let mut seen_errors: HashSet<String> = HashSet::new();
2822 while !thread_stop.load(Ordering::Acquire) {
2823 let wait = if surface.reconcile_requested.load(Ordering::Acquire) {
2824 Duration::ZERO
2825 } else {
2826 next_tick
2827 .saturating_duration_since(Instant::now())
2828 .min(RECONCILE_POLL_WAIT)
2829 };
2830 let entries = surface.session.entries_after(after, wait);
2831 let mut went_idle = false;
2832 for entry in entries {
2833 after = entry.seq;
2834 if matches!(entry.body, EntryBody::Idle { .. }) {
2835 went_idle = true;
2836 }
2837 }
2838 if thread_stop.load(Ordering::Acquire) {
2839 break;
2840 }
2841 let requested = surface.reconcile_requested.swap(false, Ordering::AcqRel);
2842 if went_idle || requested || Instant::now() >= next_tick {
2843 match now_duration().and_then(|d| reconcile_runs(&surface, d.as_secs())) {
2844 Ok((_, errors)) => {
2845 for msg in errors {
2846 if seen_errors.insert(msg.clone()) {
2847 surface.session.record_error(&msg);
2848 eprintln!("blyte: {msg}");
2849 }
2850 }
2851 }
2852 Err(e) => {
2853 if seen_errors.insert(e.clone()) {
2854 eprintln!("blyte: {e}");
2855 }
2856 }
2857 }
2858 next_tick = Instant::now() + RECONCILE_SAFETY_NET_INTERVAL;
2859 }
2860 }
2861 });
2862 ReconcileTimerGuard {
2863 stop,
2864 handle: Some(handle),
2865 }
2866}
2867
2868#[allow(clippy::too_many_arguments)]
2869fn run_inner<S>(
2870 args: &SurfaceArgs,
2871 mut config: ReplConfig,
2872 out: &mut dyn Write,
2873 err: &mut dyn Write,
2874 opener: &mut dyn FnMut(&str),
2875 stop_control: StopControl<S>,
2876 custom_runner: Option<RunnerFactory>,
2877 front_end: Option<FrontEndSpec>,
2878) -> i32
2879where
2880 S: Fn() -> bool,
2881{
2882 let StopControl {
2883 should_stop,
2884 trigger: stop_trigger,
2885 } = stop_control;
2886 let (main_checkout, is_repo) = match find_git_toplevel(&config.repo_root) {
2887 Ok(GitToplevel::Repository(worktree_root)) => {
2888 let main = match resolve_main_checkout(&worktree_root) {
2889 Ok(m) => m,
2890 Err(e) => {
2891 let _ = writeln!(err, "blyte: {e}");
2892 return 1;
2893 }
2894 };
2895 let same_checkout = match (worktree_root.canonicalize(), main.canonicalize()) {
2896 (Ok(a), Ok(b)) => a == b,
2897 _ => worktree_root == main,
2898 };
2899 if !same_checkout {
2900 let _ = writeln!(
2901 err,
2902 "blyte: started in a linked worktree ({}); this surface works in the main checkout {}",
2903 worktree_root.display(),
2904 main.display()
2905 );
2906 let _ = err.flush();
2907 }
2908 (main, true)
2909 }
2910 Ok(GitToplevel::NotARepository) => {
2911 let canonical = match config.repo_root.canonicalize() {
2912 Ok(c) => c,
2913 Err(e) => {
2914 let _ = writeln!(
2915 err,
2916 "blyte: cannot canonicalize {}: {e}",
2917 config.repo_root.display()
2918 );
2919 return 1;
2920 }
2921 };
2922 (canonical, false)
2923 }
2924 Err(e) => {
2925 let _ = writeln!(err, "blyte: {e}");
2926 return 1;
2927 }
2928 };
2929
2930 let repo = match repo_name_for(&main_checkout) {
2931 Ok(r) => r,
2932 Err(e) => {
2933 let _ = writeln!(err, "blyte: {e}");
2934 return 1;
2935 }
2936 };
2937
2938 #[cfg(target_os = "linux")]
2939 if !is_repo {
2940 if let Err(e) =
2941 check_linux_non_repo_root_for_env(&main_checkout, std::env::var_os("HOME").as_deref())
2942 {
2943 let _ = writeln!(err, "blyte: {e}");
2944 return 1;
2945 }
2946 }
2947
2948 let state_dir = match crate::surface_registry::state_dir() {
2949 Ok(d) => d,
2950 Err(e) => {
2951 let _ = writeln!(err, "blyte: {e}");
2952 return 1;
2953 }
2954 };
2955 let registry_dir = state_dir.join("surfaces");
2956
2957 let record_listing =
2958 match crate::surface_dir::list_records_for_root(&main_checkout, Some(&state_dir)) {
2959 Ok(listing) => listing,
2960 Err(e) => {
2961 let _ = writeln!(err, "blyte: {e}");
2962 return 1;
2963 }
2964 };
2965 crate::surface_registry::report_unreadable(&record_listing.unreadable, err);
2966 let mut running = Vec::new();
2967 let mut stopped = Vec::new();
2968 for located in record_listing.records {
2969 if crate::surface_dir::is_running(&located.record) {
2970 running.push(located);
2971 } else {
2972 stopped.push(located);
2973 }
2974 }
2975
2976 let live_registry = match crate::surface_registry::live_entries(®istry_dir) {
2977 Ok(listing) => {
2978 crate::surface_registry::report_unreadable(&listing.unreadable, err);
2979 listing.entries
2980 }
2981 Err(e) => {
2982 let _ = writeln!(err, "blyte: {e}");
2983 return 1;
2984 }
2985 };
2986 let mut running_names: Vec<String> = running.iter().map(|r| r.record.name.clone()).collect();
2987 for entry in &live_registry {
2988 if !running_names.iter().any(|n| n == &entry.name) {
2989 running_names.push(entry.name.clone());
2990 }
2991 }
2992
2993 let (surface_id, surface_name, surface_record_dir) = if let Some(ref target) = args.resume {
2994 if let Some(located) = running
2995 .iter()
2996 .find(|r| r.record.id == *target || r.record.name == *target)
2997 {
2998 let _ = writeln!(
2999 err,
3000 "blyte: surface {target} is already running (port {})",
3001 located.record.port
3002 );
3003 return 1;
3004 }
3005 let stopped_matches: Vec<&crate::surface_dir::LocatedRecord> = stopped
3006 .iter()
3007 .filter(|r| r.record.id == *target || r.record.name == *target)
3008 .collect();
3009 if stopped_matches.is_empty() {
3010 let _ = writeln!(
3011 err,
3012 "blyte: no stopped surface named {target} in {}",
3013 main_checkout.display()
3014 );
3015 return 1;
3016 }
3017 if stopped_matches.len() > 1 {
3018 let ids: Vec<&str> = stopped_matches
3019 .iter()
3020 .map(|r| r.record.id.as_str())
3021 .collect();
3022 let _ = writeln!(
3023 err,
3024 "blyte: more than one stopped surface is named {target}; resume by id: {}",
3025 ids.join(", ")
3026 );
3027 return 1;
3028 }
3029 let located = stopped_matches[0];
3030 if running_names.iter().any(|n| n == &located.record.name) {
3031 let _ = writeln!(
3032 err,
3033 "blyte: a running surface is already named {}; stop it or resume by another name",
3034 located.record.name
3035 );
3036 return 1;
3037 }
3038 (
3039 located.record.id.clone(),
3040 located.record.name.clone(),
3041 located.dir.clone(),
3042 )
3043 } else {
3044 let id = match crate::surface_dir::new_surface_id() {
3045 Ok(id) => id,
3046 Err(e) => {
3047 let _ = writeln!(err, "blyte: {e}");
3048 return 1;
3049 }
3050 };
3051 let name = match crate::surface_dir::pick_name(&repo, args.name.as_deref(), &running_names)
3052 {
3053 Ok(name) => name,
3054 Err(e) => {
3055 let _ = writeln!(err, "blyte: {e}");
3056 return 1;
3057 }
3058 };
3059 let record_dir = if is_repo {
3060 crate::surface_dir::surface_dir(&main_checkout, &id)
3061 } else {
3062 let store = match crate::surface_dir::folder_store(&state_dir, &main_checkout) {
3063 Ok(store) => store,
3064 Err(e) => {
3065 let _ = writeln!(err, "blyte: {e}");
3066 return 1;
3067 }
3068 };
3069 store.join("surfaces").join(&id)
3070 };
3071 (id, name, record_dir)
3072 };
3073
3074 let branch = match current_branch(&main_checkout) {
3075 Ok(b) => b,
3076 Err(e) => {
3077 let _ = writeln!(err, "blyte: {e}");
3078 return 1;
3079 }
3080 };
3081
3082 if !config.converse {
3083 config.converse = true;
3084 if config.max_turns == 25 || config.max_turns == 60 {
3085 config.max_turns = 1000;
3086 }
3087 if config.fold_budget.is_none() {
3088 config.fold_budget = Some(100_000);
3089 }
3090 }
3091 config.repo_root = main_checkout.clone();
3092
3093 let is_resume = args.resume.is_some();
3094 let model = resolve_initial_model(&config);
3095 let conversation_path = match crate::conversation_store::conversation_path_for_id(&surface_id) {
3096 Ok(p) => p,
3097 Err(e) => {
3098 let _ = writeln!(err, "blyte: {e}");
3099 let _ = err.flush();
3100 return 1;
3101 }
3102 };
3103 let (mut conversation_store, mut loaded_conversation) = if is_resume {
3104 match crate::conversation_store::ConversationStore::load(conversation_path) {
3105 Ok(pair) => pair,
3106 Err(e) => {
3107 let _ = writeln!(err, "blyte: {e}");
3108 let _ = err.flush();
3109 return 1;
3110 }
3111 }
3112 } else {
3113 match crate::conversation_store::ConversationStore::new_for_fresh(conversation_path) {
3114 Ok(store) => (store, None),
3115 Err(e) => {
3116 let _ = writeln!(err, "blyte: {e}");
3117 let _ = err.flush();
3118 return 1;
3119 }
3120 }
3121 };
3122 let (resume_memory, needs_digest_rewrite) = match loaded_conversation.as_mut() {
3123 Some(loaded) if !loaded.messages.is_empty() => {
3124 if crate::conversation_store::digest_for_provider_in_memory(loaded, &model) {
3125 (crate::session::ResumeMemoryState::Summarized, true)
3126 } else {
3127 (crate::session::ResumeMemoryState::Loaded, false)
3128 }
3129 }
3130 _ => (crate::session::ResumeMemoryState::NotLoaded, false),
3131 };
3132
3133 let started_dur = match now_duration() {
3134 Ok(d) => d,
3135 Err(e) => {
3136 let _ = writeln!(err, "blyte: {e}");
3137 return 1;
3138 }
3139 };
3140 let started_at = started_dur.as_secs();
3141 let session_id = new_session_id(started_dur.as_nanos());
3142 if std::env::var("BLYTE_SESSION")
3143 .map(|v| v.is_empty())
3144 .unwrap_or(true)
3145 {
3146 std::env::set_var("BLYTE_SESSION", &session_id);
3147 }
3148 std::env::set_var(crate::usage_log::SURFACE_ID_ENV, &surface_id);
3149 std::env::set_var(crate::usage_log::SURFACE_NAME_ENV, &surface_name);
3150
3151 let token_file_path = match blyte_agent::sandbox::surface_token_path_for_id(&surface_id) {
3152 Ok(p) => p,
3153 Err(e) => {
3154 let _ = writeln!(err, "blyte: {e}");
3155 return 1;
3156 }
3157 };
3158 let reuse_token_requested = std::env::var_os(RELOAD_REUSE_TOKEN_ENV).is_some();
3159 if reuse_token_requested {
3160 std::env::remove_var(RELOAD_REUSE_TOKEN_ENV);
3161 }
3162 let token = if is_resume && reuse_token_requested {
3163 match read_reused_token_file(&token_file_path) {
3164 Ok(t) => t,
3165 Err(e) => {
3166 let _ = writeln!(err, "blyte: {e}");
3167 return 1;
3168 }
3169 }
3170 } else {
3171 match generate_token() {
3172 Ok(t) => t,
3173 Err(e) => {
3174 let _ = writeln!(err, "blyte: {e}");
3175 return 1;
3176 }
3177 }
3178 };
3179 let message_credential = match generate_token() {
3180 Ok(t) => t,
3181 Err(e) => {
3182 let _ = writeln!(err, "blyte: {e}");
3183 return 1;
3184 }
3185 };
3186
3187 let bind_addr = format!("127.0.0.1:{}", args.port);
3188 let listener = match TcpListener::bind(&bind_addr) {
3189 Ok(l) => l,
3190 Err(e) => {
3191 let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
3192 return 1;
3193 }
3194 };
3195 let actual_port = match listener.local_addr() {
3196 Ok(a) => a.port(),
3197 Err(e) => {
3198 let _ = writeln!(err, "blyte: failed to read listener address: {e}");
3199 return 1;
3200 }
3201 };
3202
3203 if let Err(e) = write_token_file(&token_file_path, &token) {
3204 let _ = writeln!(err, "blyte: {e}");
3205 return 1;
3206 }
3207 let mut token_guard = TokenFileGuard::new(token_file_path.clone());
3208
3209 let message_file_path = match blyte_agent::sandbox::surface_message_path_for_id(&surface_id) {
3210 Ok(p) => p,
3211 Err(e) => {
3212 let _ = writeln!(err, "blyte: {e}");
3213 return 1;
3214 }
3215 };
3216 if let Err(e) = write_token_file(&message_file_path, &message_credential) {
3217 let _ = writeln!(err, "blyte: {e}");
3218 return 1;
3219 }
3220 let _message_guard = TokenFileGuard::new(message_file_path);
3221
3222 let mut starting_dir_guard = if is_resume {
3223 StartingDirGuard { dir: None }
3224 } else {
3225 if let Err(e) = crate::surface_dir::prepare_starting_dir(&surface_record_dir) {
3226 let _ = writeln!(err, "blyte: {e}");
3227 return 1;
3228 }
3229 StartingDirGuard {
3230 dir: Some(surface_record_dir.clone()),
3231 }
3232 };
3233 let attachments_dir = match prepare_attachments_dir(&surface_record_dir) {
3234 Ok(p) => p,
3235 Err(e) => {
3236 let _ = writeln!(err, "blyte: {e}");
3237 return 1;
3238 }
3239 };
3240 let mut read_roots = blyte_agent::tools::read_roots();
3241 if !read_roots.iter().any(|p| p == &attachments_dir) {
3242 read_roots.push(attachments_dir.clone());
3243 blyte_agent::tools::set_read_roots(read_roots);
3244 }
3245 let original_allow_read = config.allow_read.clone();
3246 if !config.allow_read.iter().any(|p| p == &attachments_dir) {
3247 config.allow_read.push(attachments_dir);
3248 }
3249 blyte_agent::tools::set_peer_tools(Some(Arc::new(crate::tell::SurfacePeerTools {
3250 registry_dir: registry_dir.clone(),
3251 surface_id: surface_id.clone(),
3252 surface_name: surface_name.clone(),
3253 repository: repo.clone(),
3254 })));
3255 let mcp = match crate::mcp::McpManager::from_default_paths(Some(&main_checkout)) {
3256 Ok(m) => Arc::new(m),
3257 Err(e) => {
3258 let _ = writeln!(err, "blyte: failed to load MCP configuration: {e}");
3259 let _ = err.flush();
3260 return 1;
3261 }
3262 };
3263 mcp.connect_all_in_background();
3264 let entries_log_path = surface_record_dir.join("entries.jsonl");
3265 blyte_agent::tools::set_blyte_surface(Some(surface_id.clone()));
3266 struct GlobalMcpToolsGuard {
3267 prev: Option<Arc<dyn blyte_agent::tools::McpToolAccess>>,
3268 }
3269 impl Drop for GlobalMcpToolsGuard {
3270 fn drop(&mut self) {
3271 blyte_agent::tools::set_global_mcp_tools(self.prev.take());
3272 }
3273 }
3274 let mut _global_mcp_guard: Option<GlobalMcpToolsGuard> = None;
3275 let mut _private_tmp_guard: Option<PrivateTmpDirGuard> = None;
3276 let mcp_for_session = Arc::clone(&mcp);
3277 let session = match Session::try_start_with_log_and_resume_io(
3278 model,
3279 Some(entries_log_path),
3280 resume_memory,
3281 err,
3282 |approver| match custom_runner {
3283 Some(factory) => {
3284 let (runner, tmpdir) = factory(&config, approver)?;
3285 _private_tmp_guard = tmpdir.map(|path| PrivateTmpDirGuard { path });
3286 if needs_digest_rewrite {
3287 if let Some(ref loaded) = loaded_conversation {
3288 conversation_store.rewrite(
3289 loaded.model.as_deref(),
3290 loaded.goal.as_deref(),
3291 &loaded.messages,
3292 )?;
3293 }
3294 }
3295 Ok(runner)
3296 }
3297 None => {
3298 let rewrite_payload = if needs_digest_rewrite {
3299 loaded_conversation.clone()
3300 } else {
3301 None
3302 };
3303 let approver_for_mcp = Arc::clone(&approver);
3304 let mut runner = AgentRunner::try_new_with_conversation(
3305 &config,
3306 approver,
3307 None,
3308 loaded_conversation,
3309 )?;
3310 _private_tmp_guard = runner.private_tmpdir().map(|path| PrivateTmpDirGuard {
3311 path: path.to_path_buf(),
3312 });
3313 if let Some(ref loaded) = rewrite_payload {
3314 conversation_store.rewrite(
3315 loaded.model.as_deref(),
3316 loaded.goal.as_deref(),
3317 &loaded.messages,
3318 )?;
3319 }
3320 let prev_global = blyte_agent::tools::global_mcp_tools()?;
3321 blyte_agent::tools::set_global_mcp_tools(Some(
3322 mcp_for_session.tool_access(Some(approver_for_mcp)),
3323 ));
3324 _global_mcp_guard = Some(GlobalMcpToolsGuard { prev: prev_global });
3325 runner.set_conversation_store(conversation_store);
3326 runner.set_mcp_manager(Arc::clone(&mcp_for_session));
3327 Ok(Box::new(runner) as Box<dyn crate::session::PromptRunner>)
3328 }
3329 },
3330 ) {
3331 Ok(s) => s,
3332 Err(e) => {
3333 let _ = writeln!(err, "blyte: {e}");
3334 let _ = err.flush();
3335 return 1;
3336 }
3337 };
3338 let runtime = match crate::surface_version::SurfaceRuntimeInfo::current() {
3339 Ok(info) => info,
3340 Err(e) => {
3341 let _ = writeln!(err, "blyte: {e}");
3342 let _ = err.flush();
3343 return 1;
3344 }
3345 };
3346 let record = SurfaceRecord {
3347 id: surface_id.clone(),
3348 name: surface_name.clone(),
3349 pid: std::process::id(),
3350 port: actual_port,
3351 session_id: session_id.clone(),
3352 started_at,
3353 };
3354 if let Err(e) = crate::surface_dir::write_record_in(&surface_record_dir, &record) {
3355 let _ = writeln!(err, "blyte: {e}");
3356 return 1;
3357 }
3358 starting_dir_guard.disarm();
3359 let registry_entry = crate::surface_registry::RegistryEntry {
3360 id: surface_id.clone(),
3361 name: surface_name.clone(),
3362 root: main_checkout.clone(),
3363 branch,
3364 pid: std::process::id(),
3365 port: actual_port,
3366 started_at,
3367 doing: "idle".to_string(),
3368 state: crate::surface_registry::SurfaceState::Idle,
3369 runtime: runtime.clone(),
3370 };
3371 if let Err(e) = crate::surface_registry::write_entry(®istry_dir, ®istry_entry) {
3372 let _ = writeln!(err, "blyte: {e}");
3373 return 1;
3374 }
3375 let _registry_guard = RegistryEntryGuard {
3376 dir: registry_dir.clone(),
3377 id: surface_id.clone(),
3378 };
3379 let hook_dir = registry_dir.clone();
3380 let hook_entry = registry_entry.clone();
3381 session.set_activity_hook(Box::new(move |prompt, state| {
3382 let doing = match prompt {
3383 Some(text) => {
3384 let line = crate::surface_registry::first_line(text);
3385 if line.is_empty() {
3386 "working".to_string()
3387 } else {
3388 line
3389 }
3390 }
3391 None => "idle".to_string(),
3392 };
3393 let branch = match current_branch(&hook_entry.root) {
3396 Ok(b) => b,
3397 Err(e) => {
3398 eprintln!("blyte: {e}");
3399 return;
3400 }
3401 };
3402 let entry = crate::surface_registry::RegistryEntry {
3403 branch,
3404 doing,
3405 state,
3406 ..hook_entry.clone()
3407 };
3408 if let Err(e) = crate::surface_registry::write_entry(&hook_dir, &entry) {
3409 eprintln!("blyte: {e}");
3410 }
3411 }));
3412
3413 if !is_repo {
3414 let _ = writeln!(
3415 err,
3416 "blyte: {} is not a git repository: runs edit this folder in place; combining and publishing are off",
3417 main_checkout.display()
3418 );
3419 let _ = err.flush();
3420 }
3421
3422 let open_codes = OpenCodes::new();
3423 let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
3424 let _ = writeln!(out, "blyte: surface {surface_name} at {url}");
3425 let _ = out.flush();
3426 if !args.no_open && front_end.is_none() {
3427 match issue_initial_open_code(&open_codes, now_duration()) {
3428 Ok(code) => {
3429 let open_url = format!("http://127.0.0.1:{actual_port}/#open={code}");
3430 opener(&open_url);
3431 }
3432 Err(e) => {
3433 let _ = writeln!(err, "blyte: failed to create open code: {e}");
3434 let _ = err.flush();
3435 }
3436 }
3437 }
3438
3439 let stop_surface_name = surface_name.clone();
3440 let reload_surface_id = surface_id.clone();
3441 let reload_workdir = main_checkout.clone();
3442 let is_terminal = front_end.is_some();
3443
3444 let surface = Arc::new(Surface {
3445 surface_id,
3446 surface_name,
3447 root: main_checkout,
3448 repo,
3449 session,
3450 session_id,
3451 started_at,
3452 runtime,
3453 days: args.days,
3454 token,
3455 message_credential,
3456 open_codes,
3457 requests: Arc::new(RequestsState::new()),
3458 publisher: Arc::new(RealPublisher),
3459 mcp,
3460 reconcile_lock: Mutex::new(()),
3461 reconcile_requested: AtomicBool::new(false),
3462 });
3463
3464 let timer_guard = spawn_reconcile_timer(Arc::clone(&surface));
3465 let _publish_tool_guard = PublishToolGuard::install(Arc::clone(&surface));
3466 let _land_tool_guard = LandToolGuard::install(Arc::clone(&surface));
3467
3468 let front_outcome = front_end.map(|spec| {
3469 let outcome = Arc::new(Mutex::new(None));
3470 let outcome_bg = Arc::clone(&outcome);
3471 let surface_bg = Arc::clone(&surface);
3472 let stop_trigger_bg = Arc::clone(&stop_trigger);
3473 std::thread::spawn(move || {
3474 let ctx = FrontEndContext {
3475 surface: surface_bg,
3476 take_interrupt: spec.take_interrupt,
3477 };
3478 let result =
3479 std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || (spec.front)(ctx)));
3480 let value = match result {
3481 Ok(code) => FrontEndOutcome::Exited(code),
3482 Err(_) => FrontEndOutcome::Panicked,
3483 };
3484 *outcome_bg.lock().unwrap_or_else(|e| e.into_inner()) = Some(value);
3485 stop_trigger_bg();
3486 });
3487 outcome
3488 });
3489
3490 let reload_requested = Arc::new(AtomicBool::new(false));
3491 let reload_trigger = ReloadTrigger {
3492 requested: Arc::clone(&reload_requested),
3493 stop: Arc::clone(&stop_trigger),
3494 };
3495 let surface_for_reload = Arc::clone(&surface);
3496
3497 let serve_result =
3498 crate::http::serve_until(listener, should_stop, move |req| match now_duration() {
3499 Ok(d) => route_inner(
3500 &surface,
3501 req,
3502 d.as_secs(),
3503 Some(&stop_trigger),
3504 Some(&reload_trigger),
3505 ),
3506 Err(e) => json_error(500, e),
3507 });
3508
3509 drop(_land_tool_guard);
3510 drop(_publish_tool_guard);
3511 drop(timer_guard);
3512
3513 if serve_result.is_ok() && reload_requested.load(Ordering::SeqCst) {
3514 let current_model = surface_for_reload.session.info().model;
3515 let exec_path = surface_for_reload.runtime.binary_fingerprint.path.clone();
3516 drop(surface_for_reload);
3517 drop(_registry_guard);
3518 drop(_message_guard);
3519 drop(_private_tmp_guard);
3520 if let Err(e) = crate::surface_version::verify_executable(&exec_path) {
3521 let _ = writeln!(err, "blyte: reload failed: {e}");
3522 let _ = err.flush();
3523 return 1;
3524 }
3525 let reload_args = build_reload_args(
3526 &reload_surface_id,
3527 actual_port,
3528 args,
3529 &config,
3530 &original_allow_read,
3531 ¤t_model,
3532 is_terminal,
3533 );
3534 let _ = writeln!(
3535 out,
3536 "blyte: reloading surface {stop_surface_name} with {}",
3537 exec_path.display()
3538 );
3539 let _ = out.flush();
3540 token_guard.disarm();
3541 return exec_reload(
3542 &exec_path,
3543 &reload_args,
3544 &reload_workdir,
3545 &token_file_path,
3546 err,
3547 );
3548 }
3549
3550 drop(surface_for_reload);
3551
3552 match serve_result {
3553 Ok(()) => {
3554 let _ = writeln!(
3555 out,
3556 "blyte: stopped surface {stop_surface_name}; resume with: blyte --resume {stop_surface_name}"
3557 );
3558 let _ = out.flush();
3559 match front_outcome
3560 .as_ref()
3561 .and_then(|o| *o.lock().unwrap_or_else(|e| e.into_inner()))
3562 {
3563 Some(FrontEndOutcome::Exited(code)) => code,
3564 Some(FrontEndOutcome::Panicked) => {
3565 let _ = writeln!(err, "blyte: the front end stopped unexpectedly");
3566 let _ = err.flush();
3567 1
3568 }
3569 None => 0,
3570 }
3571 }
3572 Err(e) => {
3573 let _ = writeln!(err, "blyte: server error: {e}");
3574 1
3575 }
3576 }
3577}
3578
3579fn issue_initial_open_code(
3580 open_codes: &OpenCodes,
3581 now: Result<Duration, String>,
3582) -> Result<String, String> {
3583 let now_secs = now?.as_secs();
3584 open_codes.issue(now_secs)
3585}
3586
3587fn canonicalize_attachments_dir(attachments_dir: &Path) -> Result<PathBuf, String> {
3588 std::fs::canonicalize(attachments_dir).map_err(|e| {
3589 format!(
3590 "failed to canonicalize attachments directory {}: {e}",
3591 attachments_dir.display()
3592 )
3593 })
3594}
3595
3596fn prepare_attachments_dir(surface_record_dir: &Path) -> Result<PathBuf, String> {
3597 let attachments_dir = crate::attachments::attachments_dir(surface_record_dir);
3598 std::fs::create_dir_all(&attachments_dir)
3599 .map_err(|e| format!("failed to create {}: {e}", attachments_dir.display()))?;
3600 canonicalize_attachments_dir(&attachments_dir)
3601}
3602
3603struct StartingDirGuard {
3604 dir: Option<PathBuf>,
3605}
3606
3607impl StartingDirGuard {
3608 fn disarm(&mut self) {
3609 self.dir = None;
3610 }
3611}
3612
3613impl Drop for StartingDirGuard {
3614 fn drop(&mut self) {
3615 if let Some(ref dir) = self.dir {
3616 crate::surface_dir::cleanup_starting_dir(dir);
3617 }
3618 }
3619}
3620
3621fn read_reused_token_file(path: &Path) -> Result<String, String> {
3622 let raw = std::fs::read_to_string(path)
3623 .map_err(|e| format!("cannot reuse surface token from {}: {e}", path.display()))?;
3624 let token = raw.trim().to_string();
3625 if token.is_empty() {
3626 return Err(format!(
3627 "surface token file {} is empty; cannot reuse token on reload",
3628 path.display()
3629 ));
3630 }
3631 Ok(token)
3632}
3633
3634pub fn build_reload_args(
3635 surface_id: &str,
3636 port: u16,
3637 args: &SurfaceArgs,
3638 config: &ReplConfig,
3639 allow_read: &[PathBuf],
3640 current_model: &str,
3641 is_terminal: bool,
3642) -> Vec<std::ffi::OsString> {
3643 use std::ffi::OsString;
3644
3645 let mut out: Vec<OsString> = vec![
3646 OsString::from("--resume"),
3647 OsString::from(surface_id),
3648 OsString::from("--port"),
3649 OsString::from(port.to_string()),
3650 OsString::from("--no-open"),
3651 ];
3652 if is_terminal {
3653 out.push(OsString::from("--terminal"));
3654 } else {
3655 out.push(OsString::from("--foreground"));
3656 let open_in = match args.open_in {
3657 OpenIn::App => "app",
3658 OpenIn::Browser => "browser",
3659 };
3660 out.push(OsString::from("--open-in"));
3661 out.push(OsString::from(open_in));
3662 }
3663 out.push(OsString::from("--days"));
3664 out.push(OsString::from(args.days.to_string()));
3665 if !current_model.trim().is_empty() {
3666 out.push(OsString::from("--model"));
3667 out.push(OsString::from(current_model));
3668 }
3669 if let Some(ref dispatch_cmd) = config.dispatch_cmd {
3670 out.push(OsString::from("--converse"));
3671 out.push(OsString::from("--dispatch-cmd"));
3672 out.push(OsString::from(dispatch_cmd));
3673 } else if let Some(ref gate) = config.gate {
3674 out.push(OsString::from("--gate"));
3675 out.push(OsString::from(gate));
3676 }
3677 out.push(OsString::from("--context"));
3678 out.push(OsString::from(&config.context_strategy));
3679 if let Some(ref container) = config.container {
3680 out.push(OsString::from("--container"));
3681 out.push(OsString::from(container));
3682 }
3683 out.push(OsString::from("--max-turns"));
3684 out.push(OsString::from(config.max_turns.to_string()));
3685 out.push(OsString::from("--max-gates"));
3686 out.push(OsString::from(config.max_gates.to_string()));
3687 out.push(OsString::from(format!("--rollback={}", config.rollback)));
3688 if let Some(fold_budget) = config.fold_budget {
3689 out.push(OsString::from("--fold-budget"));
3690 out.push(OsString::from(fold_budget.to_string()));
3691 }
3692 out.push(OsString::from("--sandbox"));
3693 out.push(OsString::from(&config.sandbox));
3694 if let Some(ref network) = config.network {
3695 out.push(OsString::from("--network"));
3696 out.push(OsString::from(network));
3697 }
3698 for path in allow_read {
3699 out.push(OsString::from("--allow-read"));
3700 out.push(path.as_os_str().to_os_string());
3701 }
3702 for var in &config.pass_env {
3703 out.push(OsString::from("--pass-env"));
3704 out.push(OsString::from(var));
3705 }
3706 out
3707}
3708
3709pub fn build_detached_args(args: &SurfaceArgs, config: &ReplConfig) -> Vec<std::ffi::OsString> {
3710 use std::ffi::OsString;
3711
3712 let mut out: Vec<OsString> = vec![
3713 OsString::from("--foreground"),
3714 OsString::from("--no-open"),
3715 OsString::from("--port"),
3716 OsString::from(args.port.to_string()),
3717 ];
3718 let open_in = match args.open_in {
3719 OpenIn::App => "app",
3720 OpenIn::Browser => "browser",
3721 };
3722 out.push(OsString::from("--open-in"));
3723 out.push(OsString::from(open_in));
3724 out.push(OsString::from("--days"));
3725 out.push(OsString::from(args.days.to_string()));
3726 if let Some(ref resume) = args.resume {
3727 out.push(OsString::from("--resume"));
3728 out.push(OsString::from(resume));
3729 } else if let Some(ref name) = args.name {
3730 out.push(OsString::from("--name"));
3731 out.push(OsString::from(name));
3732 }
3733 if let Some(ref model) = config.model {
3734 if !model.trim().is_empty() {
3735 out.push(OsString::from("--model"));
3736 out.push(OsString::from(model));
3737 }
3738 }
3739 if let Some(ref dispatch_cmd) = config.dispatch_cmd {
3740 out.push(OsString::from("--converse"));
3741 out.push(OsString::from("--dispatch-cmd"));
3742 out.push(OsString::from(dispatch_cmd));
3743 } else if let Some(ref gate) = config.gate {
3744 out.push(OsString::from("--gate"));
3745 out.push(OsString::from(gate));
3746 }
3747 out.push(OsString::from("--context"));
3748 out.push(OsString::from(&config.context_strategy));
3749 if let Some(ref container) = config.container {
3750 out.push(OsString::from("--container"));
3751 out.push(OsString::from(container));
3752 }
3753 out.push(OsString::from("--max-turns"));
3754 out.push(OsString::from(config.max_turns.to_string()));
3755 out.push(OsString::from("--max-gates"));
3756 out.push(OsString::from(config.max_gates.to_string()));
3757 out.push(OsString::from(format!("--rollback={}", config.rollback)));
3758 if let Some(fold_budget) = config.fold_budget {
3759 out.push(OsString::from("--fold-budget"));
3760 out.push(OsString::from(fold_budget.to_string()));
3761 }
3762 out.push(OsString::from("--sandbox"));
3763 out.push(OsString::from(&config.sandbox));
3764 if let Some(ref network) = config.network {
3765 out.push(OsString::from("--network"));
3766 out.push(OsString::from(network));
3767 }
3768 for path in &config.allow_read {
3769 out.push(OsString::from("--allow-read"));
3770 out.push(path.as_os_str().to_os_string());
3771 }
3772 for var in &config.pass_env {
3773 out.push(OsString::from("--pass-env"));
3774 out.push(OsString::from(var));
3775 }
3776 out
3777}
3778
3779#[cfg(unix)]
3780fn exec_reload<W: Write + ?Sized>(
3781 exec_path: &Path,
3782 reload_args: &[std::ffi::OsString],
3783 workdir: &Path,
3784 token_file_path: &Path,
3785 err: &mut W,
3786) -> i32 {
3787 use std::os::unix::process::CommandExt;
3788
3789 let exec_err = std::process::Command::new(exec_path)
3790 .args(reload_args)
3791 .current_dir(workdir)
3792 .env(RELOAD_REUSE_TOKEN_ENV, "1")
3793 .exec();
3794 let _ = std::fs::remove_file(token_file_path);
3795 let _ = writeln!(
3796 err,
3797 "blyte: failed to re-exec {}: {exec_err}",
3798 exec_path.display()
3799 );
3800 let _ = err.flush();
3801 1
3802}
3803
3804#[cfg(not(unix))]
3805fn exec_reload<W: Write + ?Sized>(
3806 exec_path: &Path,
3807 reload_args: &[std::ffi::OsString],
3808 workdir: &Path,
3809 token_file_path: &Path,
3810 err: &mut W,
3811) -> i32 {
3812 match std::process::Command::new(exec_path)
3813 .args(reload_args)
3814 .current_dir(workdir)
3815 .env(RELOAD_REUSE_TOKEN_ENV, "1")
3816 .status()
3817 {
3818 Ok(status) => match status.code() {
3819 Some(code) => code,
3820 None => 1,
3821 },
3822 Err(e) => {
3823 let _ = std::fs::remove_file(token_file_path);
3824 let _ = writeln!(
3825 err,
3826 "blyte: failed to re-launch {}: {e}",
3827 exec_path.display()
3828 );
3829 let _ = err.flush();
3830 1
3831 }
3832 }
3833}
3834
3835#[cfg(test)]
3836mod tests {
3837 use super::*;
3838
3839 #[test]
3840 fn canonicalize_attachments_dir_errors_when_missing() {
3841 let dir = tempfile::tempdir().unwrap();
3842 let missing = dir.path().join("does-not-exist").join("attachments");
3843 let err = canonicalize_attachments_dir(&missing).unwrap_err();
3844 assert!(
3845 err.contains(&missing.display().to_string()),
3846 "expected error to name missing path, got: {err}"
3847 );
3848 assert!(err.contains("canonicalize"), "unexpected error: {err}");
3849 }
3850
3851 #[cfg(unix)]
3852 #[test]
3853 fn canonicalize_attachments_dir_errors_on_dangling_symlink() {
3854 let dir = tempfile::tempdir().unwrap();
3855 let dangling = dir.path().join("attachments");
3856 std::os::unix::fs::symlink(dir.path().join("missing-target"), &dangling).unwrap();
3857 let err = canonicalize_attachments_dir(&dangling).unwrap_err();
3858 assert!(
3859 err.contains(&dangling.display().to_string()),
3860 "expected error to name symlink path, got: {err}"
3861 );
3862 assert!(err.contains("canonicalize"), "unexpected error: {err}");
3863 }
3864
3865 #[test]
3866 fn prepare_attachments_dir_errors_when_attachments_path_is_a_file() {
3867 let dir = tempfile::tempdir().unwrap();
3868 let blocker = crate::attachments::attachments_dir(dir.path());
3869 std::fs::write(&blocker, b"not a dir").unwrap();
3870 let err = prepare_attachments_dir(dir.path()).unwrap_err();
3871 assert!(
3872 err.contains(&blocker.display().to_string()),
3873 "expected error to name path, got: {err}"
3874 );
3875 }
3876
3877 fn poisoned_open_codes() -> OpenCodes {
3878 let codes = OpenCodes::new();
3879 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3880 let _guard = codes.entries.lock().unwrap();
3881 panic!("poison");
3882 }));
3883 codes
3884 }
3885
3886 #[test]
3887 fn open_codes_issue_errors_when_lock_poisoned() {
3888 let codes = poisoned_open_codes();
3889 let err = codes.issue(100).unwrap_err();
3890 assert!(err.contains("open codes"), "unexpected error: {err}");
3891 assert!(err.contains("poison"), "unexpected error: {err}");
3892 }
3893
3894 #[test]
3895 fn open_codes_redeem_errors_when_lock_poisoned() {
3896 let codes = poisoned_open_codes();
3897 let err = codes.redeem("some-code", 100).unwrap_err();
3898 assert!(err.contains("open codes"), "unexpected error: {err}");
3899 assert!(err.contains("poison"), "unexpected error: {err}");
3900 }
3901
3902 #[test]
3903 fn issue_initial_open_code_errors_when_clock_fails() {
3904 let codes = OpenCodes::new();
3905 let err = issue_initial_open_code(
3906 &codes,
3907 Err("system clock is before Unix epoch: test".to_string()),
3908 )
3909 .unwrap_err();
3910 assert!(err.contains("system clock"), "unexpected error: {err}");
3911 assert!(codes.entries.lock().unwrap().is_empty());
3912
3913 let code = issue_initial_open_code(&codes, Ok(Duration::from_secs(500))).unwrap();
3914 assert!(codes.redeem(&code, 500).unwrap());
3915 }
3916}