1use serde::Serialize;
2use std::collections::{BTreeSet, HashSet};
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::queue_actions::{Action, Hold};
16use crate::repl::ReplConfig;
17use crate::requests::{Publisher, RealPublisher, RequestActionError, RequestsState};
18use crate::session::{AgentRunner, AnswerError, ApprovalAnswer, Attachment, EntryBody, Session};
19use crate::surface_dir::SurfaceRecord;
20
21pub const TOKEN_HEADER: &str = "X-Blyte-Token";
22pub const RECONCILE_SAFETY_NET_INTERVAL: Duration = Duration::from_secs(30);
23
24const INDEX_HTML: &str = include_str!("../assets/surface/index.html");
25const MAX_WAIT_MS: u64 = 25_000;
26const RECONCILE_POLL_WAIT: Duration = Duration::from_millis(50);
27const TOKEN_BYTES: usize = 32;
28
29static SESSION_COUNTER: AtomicU64 = AtomicU64::new(1);
30
31pub struct Surface {
32 pub surface_id: String,
33 pub surface_name: String,
34 pub root: PathBuf,
35 pub repo: String,
36 pub session: Session,
37 pub session_id: String,
38 pub started_at: u64,
39 pub days: u64,
40 pub token: String,
41 pub requests: Arc<RequestsState>,
42 pub publisher: Arc<dyn Publisher>,
43 pub reconcile_lock: Mutex<()>,
44 pub reconcile_requested: AtomicBool,
45}
46
47pub fn generate_token() -> Result<String, String> {
48 let mut bytes = [0u8; TOKEN_BYTES];
49 let mut file = std::fs::File::open("/dev/urandom")
50 .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
51 file.read_exact(&mut bytes)
52 .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
53 const HEX: &[u8; 16] = b"0123456789abcdef";
54 let mut out = String::with_capacity(bytes.len() * 2);
55 for byte in bytes {
56 out.push(HEX[(byte >> 4) as usize] as char);
57 out.push(HEX[(byte & 0x0f) as usize] as char);
58 }
59 Ok(out)
60}
61
62pub fn constant_time_eq(provided: &[u8], expected: &[u8]) -> bool {
63 let mut diff = provided.len() ^ expected.len();
64 for (i, &exp) in expected.iter().enumerate() {
65 let prov = provided.get(i).copied().unwrap_or(0);
66 diff |= usize::from(prov ^ exp);
67 }
68 std::hint::black_box(diff) == 0
69}
70
71fn has_valid_token(surface: &Surface, req: &Request) -> bool {
72 if surface.token.is_empty() {
73 return false;
74 }
75 let mut values = req.header_values(TOKEN_HEADER);
76 let Some(provided) = values.next() else {
77 return false;
78 };
79 if values.next().is_some() {
80 return false;
81 }
82 constant_time_eq(provided.as_bytes(), surface.token.as_bytes())
83}
84
85#[derive(Serialize)]
86struct RunWithHold<'a> {
87 #[serde(flatten)]
88 run: &'a crate::replay::Run,
89 hold: Option<Hold>,
90 combined: bool,
91}
92
93#[derive(Serialize)]
94struct LiveRunsResponse<'a> {
95 generated_at: u64,
96 repo: &'a str,
97 running: &'a [crate::live_runs::RunningRun],
98 runs: Vec<RunWithHold<'a>>,
99 skipped: &'a [crate::replay::Skipped],
100}
101
102fn json_error(status: u16, msg: impl Into<String>) -> Response {
103 Response::json(status, &serde_json::json!({ "error": msg.into() }))
104}
105
106fn method_not_allowed(req: &Request) -> Response {
107 json_error(
108 405,
109 format!("method {} not allowed for {}", req.method, req.path),
110 )
111}
112
113fn is_valid_run_id(id: &str) -> bool {
114 !id.is_empty()
115 && id != "."
116 && id != ".."
117 && id
118 .bytes()
119 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
120}
121
122fn parse_json_object(body: &[u8]) -> Result<serde_json::Map<String, serde_json::Value>, Response> {
123 let val: serde_json::Value = serde_json::from_slice(body)
124 .map_err(|e| json_error(400, format!("invalid JSON body: {e}")))?;
125 val.as_object()
126 .cloned()
127 .ok_or_else(|| json_error(400, "request body must be a JSON object"))
128}
129
130fn health_response(surface: &Surface) -> Response {
131 Response::json(
132 200,
133 &serde_json::json!({
134 "surface_id": surface.surface_id,
135 "surface_name": surface.surface_name,
136 "session_id": surface.session_id,
137 }),
138 )
139}
140
141fn session_response(surface: &Surface) -> Response {
142 let info = surface.session.info();
143 Response::json(
144 200,
145 &serde_json::json!({
146 "session_id": surface.session_id,
147 "surface_name": surface.surface_name,
148 "repo": surface.repo,
149 "started_at": surface.started_at,
150 "model": info.model,
151 "effort": info.effort,
152 "effort_supported": info.effort_supported,
153 "busy": info.busy,
154 "queued": info.queued,
155 "last_seq": info.last_seq,
156 }),
157 )
158}
159
160fn handle_events(surface: &Surface, req: &Request) -> Response {
161 let after_raw = match req.query_value("after") {
162 Some(v) => v,
163 None => return json_error(400, "missing required query parameter: after"),
164 };
165 let after = match after_raw.parse::<u64>() {
166 Ok(v) => v,
167 Err(_) => {
168 return json_error(
169 400,
170 format!("query parameter after must be a non-negative integer, got '{after_raw}'"),
171 );
172 }
173 };
174 let wait_ms = match req.query_value("wait_ms") {
175 None => 0,
176 Some(raw) => match raw.parse::<u64>() {
177 Ok(v) if v <= MAX_WAIT_MS => v,
178 Ok(v) => {
179 return json_error(
180 400,
181 format!("query parameter wait_ms must be at most {MAX_WAIT_MS}, got {v}"),
182 );
183 }
184 Err(_) => {
185 return json_error(
186 400,
187 format!("query parameter wait_ms must be a non-negative integer, got '{raw}'"),
188 );
189 }
190 },
191 };
192 let entries = surface
193 .session
194 .entries_after(after, Duration::from_millis(wait_ms));
195 let last_seq = surface.session.info().last_seq;
196 Response::json(
197 200,
198 &serde_json::json!({
199 "entries": entries,
200 "last_seq": last_seq,
201 }),
202 )
203}
204
205fn handle_post_message(surface: &Surface, req: &Request) -> Response {
206 let obj = match parse_json_object(&req.body) {
207 Ok(o) => o,
208 Err(resp) => return resp,
209 };
210 let text = match obj.get("text") {
211 Some(serde_json::Value::String(s)) => s.clone(),
212 Some(_) => return json_error(400, "field text must be a string"),
213 None => return json_error(400, "missing required field: text"),
214 };
215 let report_ids: Vec<String> = match obj.get("reports") {
216 None | Some(serde_json::Value::Null) => Vec::new(),
217 Some(serde_json::Value::Array(arr)) => {
218 let mut ids = Vec::with_capacity(arr.len());
219 for item in arr {
220 match item.as_str() {
221 Some(s) => ids.push(s.to_string()),
222 None => return json_error(400, "field reports must be an array of strings"),
223 }
224 }
225 ids
226 }
227 Some(_) => return json_error(400, "field reports must be an array of strings"),
228 };
229
230 let mut attachments = Vec::with_capacity(report_ids.len());
231 for id in report_ids {
232 let path = surface.root.join(".wt").join(format!("{id}.report.md"));
233 if !is_valid_run_id(&id) {
234 return json_error(
235 400,
236 format!("invalid report run id '{id}' (path: {})", path.display()),
237 );
238 }
239 match std::fs::read_to_string(&path) {
240 Ok(body) => attachments.push(Attachment {
241 run: id,
242 text: body,
243 }),
244 Err(e) => {
245 return json_error(
246 400,
247 format!(
248 "cannot read report for run '{id}' at {}: {e}",
249 path.display()
250 ),
251 );
252 }
253 }
254 }
255
256 match surface.session.submit(&text, attachments) {
257 Ok(seq) => Response::json(200, &serde_json::json!({ "seq": seq })),
258 Err(e) => json_error(400, e),
259 }
260}
261
262fn handle_models() -> Response {
263 let discovered = blyte_provider::discover_all_models();
264 let mut models = Vec::new();
265 let mut unavailable = Vec::new();
266 let mut error_parts = Vec::new();
267
268 for (provider, result) in discovered {
269 match result {
270 Ok(list) => {
271 for m in list {
272 let effort_supported = crate::session::model_supports_effort(&m.id);
273 models.push(serde_json::json!({
274 "id": m.id,
275 "effort_supported": effort_supported,
276 }));
277 }
278 }
279 Err(e) => {
280 let err_text = e.to_string();
281 error_parts.push(format!("{provider}: {err_text}"));
282 unavailable.push(serde_json::json!({
283 "provider": provider,
284 "error": err_text,
285 }));
286 }
287 }
288 }
289
290 if models.is_empty() {
291 let msg = if error_parts.is_empty() {
292 "no models listed by any provider".to_string()
293 } else {
294 format!("no models available: {}", error_parts.join("; "))
295 };
296 return json_error(502, msg);
297 }
298
299 Response::json(
300 200,
301 &serde_json::json!({
302 "models": models,
303 "unavailable": unavailable,
304 }),
305 )
306}
307
308fn handle_post_model(surface: &Surface, req: &Request) -> Response {
309 let obj = match parse_json_object(&req.body) {
310 Ok(o) => o,
311 Err(resp) => return resp,
312 };
313 let model = match obj.get("model") {
314 Some(serde_json::Value::String(s)) => s.clone(),
315 Some(_) => return json_error(400, "field model must be a string"),
316 None => return json_error(400, "missing required field: model"),
317 };
318 if model.trim().is_empty() {
319 return json_error(400, "field model must not be empty");
320 }
321 if let Err(e) = blyte_provider::resolve_provider(Some(&model)) {
322 return json_error(400, e.to_string());
323 }
324 if let Err(e) = surface.session.set_model(&model) {
325 return json_error(400, e);
326 }
327 session_response(surface)
328}
329
330fn handle_post_effort(surface: &Surface, req: &Request) -> Response {
331 let obj = match parse_json_object(&req.body) {
332 Ok(o) => o,
333 Err(resp) => return resp,
334 };
335 let effort = match obj.get("effort") {
336 Some(serde_json::Value::Null) => None,
337 Some(serde_json::Value::String(s)) => Some(s.clone()),
338 Some(_) => return json_error(400, "field effort must be a string or null"),
339 None => return json_error(400, "missing required field: effort"),
340 };
341 if let Err(e) = surface.session.set_effort(effort.as_deref()) {
342 return json_error(400, e);
343 }
344 session_response(surface)
345}
346
347fn handle_post_approval(surface: &Surface, id: &str, req: &Request) -> Response {
348 let obj = match parse_json_object(&req.body) {
349 Ok(o) => o,
350 Err(resp) => return resp,
351 };
352 if obj.len() != 1 {
353 return json_error(400, "request body must contain only field answer");
354 }
355 let answer = match obj.get("answer") {
356 Some(serde_json::Value::String(s)) if s == "yes" => ApprovalAnswer::Yes,
357 Some(serde_json::Value::String(s)) if s == "no" => ApprovalAnswer::No,
358 Some(serde_json::Value::String(other)) => {
359 return json_error(
360 400,
361 format!("field answer must be \"yes\" or \"no\", got '{other}'"),
362 );
363 }
364 Some(_) => return json_error(400, "field answer must be \"yes\" or \"no\""),
365 None => return json_error(400, "missing required field: answer"),
366 };
367 match surface.session.answer_approval(id, answer) {
368 Ok(seq) => Response::json(
369 200,
370 &serde_json::json!({
371 "id": id,
372 "answer": answer.as_str(),
373 "seq": seq,
374 }),
375 ),
376 Err(AnswerError::NotFound) => json_error(404, format!("unknown approval id: {id}")),
377 Err(AnswerError::AlreadyAnswered) => {
378 json_error(409, format!("approval {id} has already been answered"))
379 }
380 }
381}
382
383pub fn reconcile_runs(
384 surface: &Surface,
385 now: u64,
386) -> Result<(crate::live_runs::LiveRuns, Vec<String>), String> {
387 let _guard = surface
388 .reconcile_lock
389 .lock()
390 .unwrap_or_else(|e| e.into_inner());
391 let owned = crate::requests::owned_run_ids(surface)?;
392 let mut live = crate::live_runs::collect(&surface.root, now, surface.days)?;
393 let mut any_written = false;
394 for run in &live.runs {
395 if !owned.contains(&run.id) || run.checks_recorded {
396 continue;
397 }
398 if crate::queue_actions::ensure_checks(&surface.root, &run.id)? {
399 any_written = true;
400 }
401 }
402 if any_written {
403 live = crate::live_runs::collect(&surface.root, now, surface.days)?;
404 }
405 live.running.retain(|run| owned.contains(&run.id));
406 live.runs.retain(|run| owned.contains(&run.id));
407
408 let mut errors = Vec::new();
409 if let Err(e) = crate::run_results::report_finished_runs(surface) {
410 errors.push(format!("run report failed: {e}"));
411 }
412
413 let mut triggered = BTreeSet::new();
414 for run in &live.runs {
415 if run.research {
416 continue;
417 }
418 if let Some(ref req_id) = run.request {
419 if triggered.insert(req_id.clone()) {
420 if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
421 errors.push(format!("combine trigger failed for {req_id}: {e}"));
422 }
423 }
424 }
425 }
426
427 Ok((live, errors))
428}
429
430fn handle_runs(surface: &Surface, now: u64) -> Response {
431 let (live, errors) = match reconcile_runs(surface, now) {
432 Ok(res) => res,
433 Err(e) => return json_error(500, e),
434 };
435 for msg in errors {
436 surface.session.record_error(&msg);
437 }
438
439 let run_refs: Vec<(&str, Option<&str>)> = live
440 .runs
441 .iter()
442 .map(|run| (run.id.as_str(), run.request.as_deref()))
443 .collect();
444 let combined_ids = match crate::requests::combined_run_ids(&surface.root, &run_refs) {
445 Ok(ids) => ids,
446 Err(e) => return json_error(500, e),
447 };
448
449 let mut runs_with_hold = Vec::with_capacity(live.runs.len());
450 for run in &live.runs {
451 let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
452 Ok(h) => h,
453 Err(e) => return json_error(500, e),
454 };
455 let combined = combined_ids.contains(&run.id);
456 runs_with_hold.push(RunWithHold {
457 run,
458 hold,
459 combined,
460 });
461 }
462
463 let payload = LiveRunsResponse {
464 generated_at: live.generated_at,
465 repo: &live.repo,
466 running: &live.running,
467 runs: runs_with_hold,
468 skipped: &live.skipped,
469 };
470 match serde_json::to_value(&payload) {
471 Ok(val) => Response::json(200, &val),
472 Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
473 }
474}
475
476fn handle_runs_changed(surface: &Surface) -> Response {
477 surface.reconcile_requested.store(true, Ordering::Release);
478 Response::json(202, &serde_json::json!({}))
479}
480
481fn handle_run_diff(surface: &Surface, id: &str) -> Response {
482 if !is_valid_run_id(id) {
483 return json_error(404, format!("unknown run: {id}"));
484 }
485 let wt_dir = surface.root.join(".wt");
486 let wt = wt_dir.join(id);
487 let start = wt_dir.join(format!("{id}.start.json"));
488 let summary = wt_dir.join(format!("{id}.json"));
489 let report_json = wt_dir.join(format!("{id}.report.json"));
490 let report_md = wt_dir.join(format!("{id}.report.md"));
491 if !wt.exists()
492 && !start.exists()
493 && !summary.exists()
494 && !report_json.exists()
495 && !report_md.exists()
496 {
497 return json_error(404, format!("unknown run: {id}"));
498 }
499 if let Err(err) = crate::requests::run_owner_check(surface, id) {
500 return request_action_error_response(err);
501 }
502 match crate::queue_actions::compute_review(&surface.root, id, true) {
503 Ok(data) => {
504 let body = if !data.wt_exists {
505 "(worktree removed)\n".to_string()
506 } else if data.diff_out.is_empty() {
507 String::new()
508 } else {
509 format!("{}\n", data.diff_out)
510 };
511 Response::text(200, &body)
512 }
513 Err(e) => {
514 if !wt.is_dir() || !wt.join(".git").exists() {
515 json_error(404, e)
516 } else {
517 json_error(500, e)
518 }
519 }
520 }
521}
522
523fn parse_action(raw: &str) -> Result<Action, String> {
524 match raw {
525 "accept" => Ok(Action::Accept),
526 "send_back" => Ok(Action::SendBack),
527 "redo" => Ok(Action::Redo),
528 "hold" => Ok(Action::Hold),
529 "mark_read" => Ok(Action::MarkRead),
530 other => Err(format!(
531 "unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
532 )),
533 }
534}
535
536fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
537 let obj = match parse_json_object(&req.body) {
538 Ok(o) => o,
539 Err(resp) => return resp,
540 };
541 let action_str = match obj.get("action") {
542 Some(serde_json::Value::String(s)) => s.clone(),
543 Some(_) => return json_error(400, "field action must be a string"),
544 None => return json_error(400, "missing required field: action"),
545 };
546 let action = match parse_action(&action_str) {
547 Ok(a) => a,
548 Err(e) => return json_error(400, e),
549 };
550 let note = match obj.get("note") {
551 None | Some(serde_json::Value::Null) => None,
552 Some(serde_json::Value::String(s)) => Some(s.clone()),
553 Some(_) => return json_error(400, "field note must be a string or null"),
554 };
555
556 let wt_dir = surface.root.join(".wt");
557 let run_exists = is_valid_run_id(id)
558 && (wt_dir.join(id).exists()
559 || wt_dir.join(format!("{id}.start.json")).exists()
560 || wt_dir.join(format!("{id}.json")).exists()
561 || wt_dir.join(format!("{id}.report.json")).exists()
562 || wt_dir.join(format!("{id}.report.md")).exists());
563 if run_exists {
564 if let Err(err) = crate::requests::run_owner_check(surface, id) {
565 return request_action_error_response(err);
566 }
567 }
568
569 let decision =
570 match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
571 Ok(d) => d,
572 Err(e) => return json_error(400, e),
573 };
574 let seq = match surface.session.record_decision(
575 &decision.run,
576 &action_str,
577 decision.note.as_deref(),
578 decision.conversation_message.as_deref(),
579 ) {
580 Ok(s) => s,
581 Err(e) => return json_error(500, e),
582 };
583 if action == Action::Accept {
584 match crate::requests::run_request_id(&surface.root, &decision.run) {
585 Ok(Some(req_id)) => {
586 if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
587 surface
588 .session
589 .record_error(&format!("combine trigger failed for {req_id}: {e}"));
590 }
591 }
592 Ok(None) => {}
593 Err(e) => return json_error(500, e),
594 }
595 }
596 Response::json(
597 200,
598 &serde_json::json!({
599 "decision": {
600 "run": decision.run,
601 "action": action_str,
602 "note": decision.note,
603 "conversation_message": decision.conversation_message,
604 },
605 "seq": seq,
606 }),
607 )
608}
609
610fn handle_map(surface: &Surface) -> Response {
611 match crate::map::build(&surface.root, &surface.repo) {
612 Ok(data) => match serde_json::to_value(&data) {
613 Ok(val) => Response::json(200, &val),
614 Err(e) => json_error(500, format!("failed to serialize map: {e}")),
615 },
616 Err(e) => json_error(422, e),
617 }
618}
619
620fn handle_requests(surface: &Surface) -> Response {
621 match crate::requests::list_requests(surface) {
622 Ok(list) => match serde_json::to_value(&list) {
623 Ok(val) => Response::json(200, &val),
624 Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
625 },
626 Err(e) => json_error(500, e),
627 }
628}
629
630fn request_action_error_response(err: RequestActionError) -> Response {
631 match err {
632 RequestActionError::BadRequest(msg) => json_error(400, msg),
633 RequestActionError::NotOwned(msg) => json_error(403, msg),
634 RequestActionError::Conflict(msg) => json_error(409, msg),
635 RequestActionError::Internal(msg) => json_error(500, msg),
636 }
637}
638
639fn handle_request_push(surface: &Surface, id: &str) -> Response {
640 match crate::requests::push_request(surface, id) {
641 Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
642 Err(err) => request_action_error_response(err),
643 }
644}
645
646fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
647 if let Err(e) = crate::dispatch::validate_request_id(id) {
648 return json_error(400, e);
649 }
650 let obj = match parse_json_object(&req.body) {
651 Ok(o) => o,
652 Err(resp) => return resp,
653 };
654 let title = match obj.get("title") {
655 Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
656 Some(serde_json::Value::String(_)) => {
657 return json_error(400, "field title must not be empty");
658 }
659 Some(_) => return json_error(400, "field title must be a string"),
660 None => return json_error(400, "missing required field: title"),
661 };
662 let body = match obj.get("body") {
663 None | Some(serde_json::Value::Null) => String::new(),
664 Some(serde_json::Value::String(s)) => s.clone(),
665 Some(_) => return json_error(400, "field body must be a string"),
666 };
667 match crate::requests::open_request_pull_request(surface, id, &title, &body) {
668 Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
669 Err(err) => request_action_error_response(err),
670 }
671}
672
673#[derive(Clone, Copy)]
674enum ApiGetHandler {
675 Session,
676 Events,
677 Models,
678 Runs,
679 Requests,
680 Map,
681 RunDiff,
682}
683
684const API_GET_ROUTES: &[(&str, ApiGetHandler)] = &[
685 ("/api/session", ApiGetHandler::Session),
686 ("/api/session/events", ApiGetHandler::Events),
687 ("/api/models", ApiGetHandler::Models),
688 ("/api/runs", ApiGetHandler::Runs),
689 ("/api/requests", ApiGetHandler::Requests),
690 ("/api/map", ApiGetHandler::Map),
691 ("/api/runs/{id}/diff", ApiGetHandler::RunDiff),
692];
693
694pub fn authenticated_api_get_routes() -> Vec<&'static str> {
695 API_GET_ROUTES.iter().map(|(pattern, _)| *pattern).collect()
696}
697
698fn match_api_get_route<'a>(pattern: &str, path: &'a str) -> Option<Option<&'a str>> {
699 if let Some((prefix, suffix)) = pattern.split_once("{id}") {
700 let rest = path.strip_prefix(prefix)?;
701 let id = rest.strip_suffix(suffix)?;
702 if !id.is_empty() && !id.contains('/') {
703 return Some(Some(id));
704 }
705 None
706 } else if pattern == path {
707 Some(None)
708 } else {
709 None
710 }
711}
712
713pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
714 let is_health_get = req.path == "/api/health" && req.method == "GET";
715 if (req.path.starts_with("/api/") || req.method == "POST")
716 && !is_health_get
717 && !has_valid_token(surface, req)
718 {
719 return json_error(
720 403,
721 "missing or invalid surface token; open the page from the URL blyte printed",
722 );
723 }
724
725 if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
726 if req.method != "GET" {
727 return method_not_allowed(req);
728 }
729 return Response {
730 status,
731 content_type,
732 body,
733 };
734 }
735
736 if req.path == "/" || req.path == "/index.html" {
737 if req.method != "GET" {
738 return method_not_allowed(req);
739 }
740 return Response::html(INDEX_HTML.as_bytes().to_vec());
741 }
742
743 if req.path == "/api/health" {
744 if req.method != "GET" {
745 return method_not_allowed(req);
746 }
747 return health_response(surface);
748 }
749
750 for &(pattern, handler) in API_GET_ROUTES {
751 if let Some(id) = match_api_get_route(pattern, &req.path) {
752 if req.method != "GET" {
753 return method_not_allowed(req);
754 }
755 return match handler {
756 ApiGetHandler::Session => session_response(surface),
757 ApiGetHandler::Events => handle_events(surface, req),
758 ApiGetHandler::Models => handle_models(),
759 ApiGetHandler::Runs => handle_runs(surface, now),
760 ApiGetHandler::Requests => handle_requests(surface),
761 ApiGetHandler::Map => handle_map(surface),
762 ApiGetHandler::RunDiff => handle_run_diff(surface, id.unwrap_or("")),
763 };
764 }
765 }
766
767 match req.path.as_str() {
768 "/api/session/messages" => {
769 if req.method != "POST" {
770 return method_not_allowed(req);
771 }
772 handle_post_message(surface, req)
773 }
774 "/api/session/model" => {
775 if req.method != "POST" {
776 return method_not_allowed(req);
777 }
778 handle_post_model(surface, req)
779 }
780 "/api/session/effort" => {
781 if req.method != "POST" {
782 return method_not_allowed(req);
783 }
784 handle_post_effort(surface, req)
785 }
786 "/api/runs/changed" => {
787 if req.method != "POST" {
788 return method_not_allowed(req);
789 }
790 handle_runs_changed(surface)
791 }
792 path => {
793 if let Some(id) = path.strip_prefix("/api/session/approvals/") {
794 if !id.is_empty() && !id.contains('/') {
795 if req.method != "POST" {
796 return method_not_allowed(req);
797 }
798 return handle_post_approval(surface, id, req);
799 }
800 }
801 if let Some(rest) = path.strip_prefix("/api/runs/") {
802 if let Some(id) = rest.strip_suffix("/decision") {
803 if !id.is_empty() && !id.contains('/') {
804 if req.method != "POST" {
805 return method_not_allowed(req);
806 }
807 return handle_run_decision(surface, id, req, now);
808 }
809 }
810 }
811 if let Some(rest) = path.strip_prefix("/api/requests/") {
812 if let Some(id) = rest.strip_suffix("/push") {
813 if req.method != "POST" {
814 return method_not_allowed(req);
815 }
816 return handle_request_push(surface, id);
817 }
818 if let Some(id) = rest.strip_suffix("/pull-request") {
819 if req.method != "POST" {
820 return method_not_allowed(req);
821 }
822 return handle_request_pull_request(surface, id, req);
823 }
824 }
825 json_error(404, format!("not found: {}", req.path))
826 }
827 }
828}
829
830fn find_git_toplevel(dir: &Path) -> Result<PathBuf, String> {
831 let out = Command::new("git")
832 .args(["rev-parse", "--show-toplevel"])
833 .current_dir(dir)
834 .output()
835 .map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
836 if !out.status.success() {
837 return Err(format!("not inside a git repository ({})", dir.display()));
838 }
839 let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
840 if path_str.is_empty() {
841 return Err(format!("not inside a git repository ({})", dir.display()));
842 }
843 Ok(PathBuf::from(path_str))
844}
845
846fn resolve_main_checkout(worktree_root: &Path) -> Result<PathBuf, String> {
847 let out = Command::new("git")
848 .args([
849 "rev-parse",
850 "--path-format=absolute",
851 "--git-dir",
852 "--git-common-dir",
853 ])
854 .current_dir(worktree_root)
855 .output()
856 .map_err(|_| {
857 format!(
858 "cannot find the main checkout of {}",
859 worktree_root.display()
860 )
861 })?;
862 if !out.status.success() {
863 return Err(format!(
864 "cannot find the main checkout of {}",
865 worktree_root.display()
866 ));
867 }
868 let text = String::from_utf8_lossy(&out.stdout);
869 let mut lines = text.lines();
870 let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
871 return Err(format!(
872 "cannot find the main checkout of {}",
873 worktree_root.display()
874 ));
875 };
876 let git_dir_path = PathBuf::from(git_dir.trim());
877 let common_dir_path = PathBuf::from(common_dir.trim());
878 let same_git_dir = match (git_dir_path.canonicalize(), common_dir_path.canonicalize()) {
879 (Ok(a), Ok(b)) => a == b,
880 _ => git_dir_path == common_dir_path,
881 };
882 if same_git_dir {
883 return Ok(worktree_root.to_path_buf());
884 }
885 crate::config::main_checkout(worktree_root).ok_or_else(|| {
886 format!(
887 "cannot find the main checkout of {}",
888 worktree_root.display()
889 )
890 })
891}
892
893fn repo_name_for(root: &Path) -> Result<String, String> {
894 root.file_name()
895 .and_then(|s| s.to_str())
896 .filter(|s| !s.is_empty())
897 .map(String::from)
898 .ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
899}
900
901fn now_duration() -> Result<Duration, String> {
902 SystemTime::now()
903 .duration_since(UNIX_EPOCH)
904 .map_err(|e| format!("system clock is before Unix epoch: {e}"))
905}
906
907fn new_session_id(nanos: u128) -> String {
908 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
909 format!("surface-{}-{nanos}-{seq}", std::process::id())
910}
911
912fn open_browser(url: &str) {
913 #[cfg(target_os = "macos")]
914 let cmd = "open";
915 #[cfg(not(target_os = "macos"))]
916 let cmd = "xdg-open";
917 if let Err(e) = Command::new(cmd).arg(url).spawn() {
918 eprintln!("blyte: could not open a browser with {cmd}: {e}; open {url} yourself");
919 }
920}
921
922fn resolve_initial_model(config: &ReplConfig) -> String {
923 if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
924 return m.to_string();
925 }
926 if let Ok(m) = std::env::var("BLYTE_MODEL") {
927 if !m.trim().is_empty() {
928 return m;
929 }
930 }
931 if let Ok(p) = blyte_provider::resolve_provider(None) {
932 return p.model_id();
933 }
934 "gemini-3.8-flash-high".to_string()
935}
936
937#[cfg(unix)]
938static SIGNAL_STOP: AtomicBool = AtomicBool::new(false);
939
940#[cfg(unix)]
941extern "C" fn handle_shutdown_signal(_: libc::c_int) {
942 SIGNAL_STOP.store(true, Ordering::Relaxed);
943}
944
945fn ensure_token_dir(dir: &Path) -> Result<(), String> {
946 #[cfg(unix)]
947 {
948 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
949 if let Some(parent) = dir.parent() {
950 std::fs::create_dir_all(parent)
951 .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
952 }
953 let mut builder = std::fs::DirBuilder::new();
954 builder.mode(0o700);
955 match builder.create(dir) {
956 Ok(()) => {}
957 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
958 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
959 .map_err(|e| format!("cannot set permissions on {}: {e}", dir.display()))?;
960 }
961 Err(e) => return Err(format!("cannot create {}: {e}", dir.display())),
962 }
963 Ok(())
964 }
965 #[cfg(not(unix))]
966 {
967 std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))
968 }
969}
970
971fn write_token_file(token_file_path: &Path, token: &str) -> Result<(), String> {
972 let token_dir = token_file_path
973 .parent()
974 .ok_or_else(|| format!("invalid token path {}", token_file_path.display()))?;
975 ensure_token_dir(token_dir)?;
976 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
977 let tmp_path = token_dir.join(format!(".surface.token.{}.{seq}.tmp", std::process::id()));
978 let mut opts = std::fs::OpenOptions::new();
979 opts.write(true).create_new(true);
980 #[cfg(unix)]
981 {
982 opts.mode(0o600);
983 }
984 let mut file = opts
985 .open(&tmp_path)
986 .map_err(|e| format!("cannot create {}: {e}", token_file_path.display()))?;
987 if let Err(e) = writeln!(file, "{token}") {
988 let _ = std::fs::remove_file(&tmp_path);
989 return Err(format!("cannot write {}: {e}", token_file_path.display()));
990 }
991 drop(file);
992 if let Err(e) = std::fs::rename(&tmp_path, token_file_path) {
993 let _ = std::fs::remove_file(&tmp_path);
994 return Err(format!("cannot write {}: {e}", token_file_path.display()));
995 }
996 Ok(())
997}
998
999struct TokenFileGuard {
1000 path: PathBuf,
1001}
1002
1003impl Drop for TokenFileGuard {
1004 fn drop(&mut self) {
1005 let _ = std::fs::remove_file(&self.path);
1006 }
1007}
1008
1009pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
1010 #[cfg(unix)]
1011 {
1012 SIGNAL_STOP.store(false, Ordering::Relaxed);
1013 unsafe {
1014 libc::signal(
1015 libc::SIGINT,
1016 handle_shutdown_signal as *const () as libc::sighandler_t,
1017 );
1018 libc::signal(
1019 libc::SIGTERM,
1020 handle_shutdown_signal as *const () as libc::sighandler_t,
1021 );
1022 }
1023 }
1024 run_inner(
1025 args,
1026 config,
1027 &mut std::io::stdout(),
1028 &mut std::io::stderr(),
1029 &mut open_browser,
1030 || {
1031 #[cfg(unix)]
1032 {
1033 SIGNAL_STOP.load(Ordering::Relaxed)
1034 }
1035 #[cfg(not(unix))]
1036 {
1037 false
1038 }
1039 },
1040 )
1041}
1042
1043pub fn run_with_io(
1044 args: &SurfaceArgs,
1045 config: ReplConfig,
1046 out: &mut dyn Write,
1047 err: &mut dyn Write,
1048) -> i32 {
1049 run_inner(args, config, out, err, &mut open_browser, || false)
1050}
1051
1052pub fn run_with_hooks(
1053 args: &SurfaceArgs,
1054 config: ReplConfig,
1055 out: &mut dyn Write,
1056 err: &mut dyn Write,
1057 opener: &mut dyn FnMut(&str),
1058 stop: Arc<AtomicBool>,
1059) -> i32 {
1060 run_inner(args, config, out, err, opener, move || {
1061 stop.load(Ordering::Relaxed)
1062 })
1063}
1064
1065struct ReconcileTimerGuard {
1066 stop: Arc<AtomicBool>,
1067 handle: Option<std::thread::JoinHandle<()>>,
1068}
1069
1070impl Drop for ReconcileTimerGuard {
1071 fn drop(&mut self) {
1072 self.stop.store(true, Ordering::Release);
1073 if let Some(handle) = self.handle.take() {
1074 let _ = handle.join();
1075 }
1076 }
1077}
1078
1079fn spawn_reconcile_timer(surface: Arc<Surface>) -> ReconcileTimerGuard {
1080 let stop = Arc::new(AtomicBool::new(false));
1081 let thread_stop = Arc::clone(&stop);
1082 let handle = std::thread::spawn(move || {
1083 let mut after = surface.session.info().last_seq;
1084 let mut next_tick = Instant::now();
1085 let mut seen_errors: HashSet<String> = HashSet::new();
1086 while !thread_stop.load(Ordering::Acquire) {
1087 let wait = if surface.reconcile_requested.load(Ordering::Acquire) {
1088 Duration::ZERO
1089 } else {
1090 next_tick
1091 .saturating_duration_since(Instant::now())
1092 .min(RECONCILE_POLL_WAIT)
1093 };
1094 let entries = surface.session.entries_after(after, wait);
1095 let mut went_idle = false;
1096 for entry in entries {
1097 after = entry.seq;
1098 if matches!(entry.body, EntryBody::Idle { .. }) {
1099 went_idle = true;
1100 }
1101 }
1102 if thread_stop.load(Ordering::Acquire) {
1103 break;
1104 }
1105 let requested = surface.reconcile_requested.swap(false, Ordering::AcqRel);
1106 if went_idle || requested || Instant::now() >= next_tick {
1107 match now_duration().and_then(|d| reconcile_runs(&surface, d.as_secs())) {
1108 Ok((_, errors)) => {
1109 for msg in errors {
1110 if seen_errors.insert(msg.clone()) {
1111 surface.session.record_error(&msg);
1112 eprintln!("blyte: {msg}");
1113 }
1114 }
1115 }
1116 Err(e) => {
1117 if seen_errors.insert(e.clone()) {
1118 eprintln!("blyte: {e}");
1119 }
1120 }
1121 }
1122 next_tick = Instant::now() + RECONCILE_SAFETY_NET_INTERVAL;
1123 }
1124 }
1125 });
1126 ReconcileTimerGuard {
1127 stop,
1128 handle: Some(handle),
1129 }
1130}
1131
1132fn run_inner<S>(
1133 args: &SurfaceArgs,
1134 mut config: ReplConfig,
1135 out: &mut dyn Write,
1136 err: &mut dyn Write,
1137 opener: &mut dyn FnMut(&str),
1138 should_stop: S,
1139) -> i32
1140where
1141 S: Fn() -> bool,
1142{
1143 let worktree_root = match find_git_toplevel(&config.repo_root) {
1144 Ok(r) => r,
1145 Err(e) => {
1146 let _ = writeln!(err, "blyte: {e}");
1147 return 1;
1148 }
1149 };
1150 let main_checkout = match resolve_main_checkout(&worktree_root) {
1151 Ok(m) => m,
1152 Err(e) => {
1153 let _ = writeln!(err, "blyte: {e}");
1154 return 1;
1155 }
1156 };
1157 let same_checkout = match (worktree_root.canonicalize(), main_checkout.canonicalize()) {
1158 (Ok(a), Ok(b)) => a == b,
1159 _ => worktree_root == main_checkout,
1160 };
1161 if !same_checkout {
1162 let _ = writeln!(
1163 err,
1164 "blyte: started in a linked worktree ({}); this surface works in the main checkout {}",
1165 worktree_root.display(),
1166 main_checkout.display()
1167 );
1168 let _ = err.flush();
1169 }
1170
1171 let repo = match repo_name_for(&main_checkout) {
1172 Ok(r) => r,
1173 Err(e) => {
1174 let _ = writeln!(err, "blyte: {e}");
1175 return 1;
1176 }
1177 };
1178
1179 let all_records = match crate::surface_dir::list_records(&main_checkout) {
1180 Ok(r) => r,
1181 Err(e) => {
1182 let _ = writeln!(err, "blyte: {e}");
1183 return 1;
1184 }
1185 };
1186 let mut running = Vec::new();
1187 let mut stopped = Vec::new();
1188 for rec in all_records {
1189 if crate::surface_dir::is_running(&rec) {
1190 running.push(rec);
1191 } else {
1192 stopped.push(rec);
1193 }
1194 }
1195 let running_names: Vec<String> = running.iter().map(|r| r.name.clone()).collect();
1196
1197 let (surface_id, surface_name) = if let Some(ref target) = args.resume {
1198 if let Some(rec) = running
1199 .iter()
1200 .find(|r| r.id == *target || r.name == *target)
1201 {
1202 let _ = writeln!(
1203 err,
1204 "blyte: surface {target} is already running (port {})",
1205 rec.port
1206 );
1207 return 1;
1208 }
1209 let stopped_matches: Vec<&SurfaceRecord> = stopped
1210 .iter()
1211 .filter(|r| r.id == *target || r.name == *target)
1212 .collect();
1213 if stopped_matches.is_empty() {
1214 let _ = writeln!(
1215 err,
1216 "blyte: no stopped surface named {target} in {}",
1217 main_checkout.display()
1218 );
1219 return 1;
1220 }
1221 if stopped_matches.len() > 1 {
1222 let ids: Vec<&str> = stopped_matches.iter().map(|r| r.id.as_str()).collect();
1223 let _ = writeln!(
1224 err,
1225 "blyte: more than one stopped surface is named {target}; resume by id: {}",
1226 ids.join(", ")
1227 );
1228 return 1;
1229 }
1230 let rec = stopped_matches[0];
1231 if running_names.iter().any(|n| n == &rec.name) {
1232 let _ = writeln!(
1233 err,
1234 "blyte: a running surface is already named {}; stop it or resume by another name",
1235 rec.name
1236 );
1237 return 1;
1238 }
1239 (rec.id.clone(), rec.name.clone())
1240 } else {
1241 let id = match crate::surface_dir::new_surface_id() {
1242 Ok(id) => id,
1243 Err(e) => {
1244 let _ = writeln!(err, "blyte: {e}");
1245 return 1;
1246 }
1247 };
1248 let name = match crate::surface_dir::pick_name(&repo, args.name.as_deref(), &running_names)
1249 {
1250 Ok(name) => name,
1251 Err(e) => {
1252 let _ = writeln!(err, "blyte: {e}");
1253 return 1;
1254 }
1255 };
1256 (id, name)
1257 };
1258
1259 if !config.converse {
1260 config.converse = true;
1261 if config.max_turns == 25 || config.max_turns == 60 {
1262 config.max_turns = 1000;
1263 }
1264 if config.fold_budget.is_none() {
1265 config.fold_budget = Some(100_000);
1266 }
1267 }
1268 config.repo_root = main_checkout.clone();
1269
1270 let started_dur = match now_duration() {
1271 Ok(d) => d,
1272 Err(e) => {
1273 let _ = writeln!(err, "blyte: {e}");
1274 return 1;
1275 }
1276 };
1277 let started_at = started_dur.as_secs();
1278 let session_id = new_session_id(started_dur.as_nanos());
1279 if std::env::var("BLYTE_SESSION")
1280 .map(|v| v.is_empty())
1281 .unwrap_or(true)
1282 {
1283 std::env::set_var("BLYTE_SESSION", &session_id);
1284 }
1285
1286 let token = match generate_token() {
1287 Ok(t) => t,
1288 Err(e) => {
1289 let _ = writeln!(err, "blyte: {e}");
1290 return 1;
1291 }
1292 };
1293
1294 let bind_addr = format!("127.0.0.1:{}", args.port);
1295 let listener = match TcpListener::bind(&bind_addr) {
1296 Ok(l) => l,
1297 Err(e) => {
1298 let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
1299 return 1;
1300 }
1301 };
1302 let actual_port = match listener.local_addr() {
1303 Ok(a) => a.port(),
1304 Err(e) => {
1305 let _ = writeln!(err, "blyte: failed to read listener address: {e}");
1306 return 1;
1307 }
1308 };
1309
1310 let token_file_path = match blyte_agent::sandbox::surface_token_path_for_id(&surface_id) {
1311 Ok(p) => p,
1312 Err(e) => {
1313 let _ = writeln!(err, "blyte: {e}");
1314 return 1;
1315 }
1316 };
1317 if let Err(e) = write_token_file(&token_file_path, &token) {
1318 let _ = writeln!(err, "blyte: {e}");
1319 return 1;
1320 }
1321 let _token_guard = TokenFileGuard {
1322 path: token_file_path,
1323 };
1324
1325 let record = SurfaceRecord {
1328 id: surface_id.clone(),
1329 name: surface_name.clone(),
1330 pid: std::process::id(),
1331 port: actual_port,
1332 session_id: session_id.clone(),
1333 started_at,
1334 };
1335 if let Err(e) = crate::surface_dir::write_record(&main_checkout, &record) {
1336 let _ = writeln!(err, "blyte: {e}");
1337 return 1;
1338 }
1339 let entries_log_path = crate::surface_dir::entries_path(&main_checkout, &surface_id);
1340 blyte_agent::tools::set_blyte_surface(Some(surface_id.clone()));
1341 let model = resolve_initial_model(&config);
1342 let session = match Session::start_with_log_io(model, Some(entries_log_path), err, |approver| {
1343 Box::new(AgentRunner::new(&config, approver))
1344 }) {
1345 Ok(s) => s,
1346 Err(e) => {
1347 let _ = writeln!(err, "blyte: {e}");
1348 let _ = err.flush();
1349 return 1;
1350 }
1351 };
1352
1353 let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
1354 let _ = writeln!(out, "blyte: surface {surface_name} at {url}");
1355 let _ = out.flush();
1356 if !args.no_open {
1357 opener(&url);
1358 }
1359
1360 let surface = Arc::new(Surface {
1361 surface_id,
1362 surface_name,
1363 root: main_checkout,
1364 repo,
1365 session,
1366 session_id,
1367 started_at,
1368 days: args.days,
1369 token,
1370 requests: Arc::new(RequestsState::new()),
1371 publisher: Arc::new(RealPublisher),
1372 reconcile_lock: Mutex::new(()),
1373 reconcile_requested: AtomicBool::new(false),
1374 });
1375
1376 let timer_guard = spawn_reconcile_timer(Arc::clone(&surface));
1377
1378 let serve_result =
1379 crate::http::serve_until(listener, should_stop, move |req| match now_duration() {
1380 Ok(d) => route(&surface, req, d.as_secs()),
1381 Err(e) => json_error(500, e),
1382 });
1383
1384 drop(timer_guard);
1385
1386 match serve_result {
1387 Ok(()) => 0,
1388 Err(e) => {
1389 let _ = writeln!(err, "blyte: server error: {e}");
1390 1
1391 }
1392 }
1393}