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