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