1use serde::{Deserialize, Serialize};
2use std::collections::{BTreeSet, HashSet};
3use std::io::{Read, Write};
4use std::net::{SocketAddr, TcpListener, TcpStream};
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};
19
20pub const TOKEN_HEADER: &str = "X-Blyte-Token";
21pub const RECONCILE_SAFETY_NET_INTERVAL: Duration = Duration::from_secs(30);
22
23const INDEX_HTML: &str = include_str!("../assets/surface/index.html");
24const MAX_WAIT_MS: u64 = 25_000;
25const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
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 root: PathBuf,
33 pub repo: String,
34 pub session: Session,
35 pub session_id: String,
36 pub started_at: u64,
37 pub days: u64,
38 pub token: String,
39 pub requests: Arc<RequestsState>,
40 pub publisher: Arc<dyn Publisher>,
41 pub reconcile_lock: Mutex<()>,
42 pub reconcile_requested: AtomicBool,
43}
44
45pub fn generate_token() -> Result<String, String> {
46 let mut bytes = [0u8; TOKEN_BYTES];
47 let mut file = std::fs::File::open("/dev/urandom")
48 .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
49 file.read_exact(&mut bytes)
50 .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
51 const HEX: &[u8; 16] = b"0123456789abcdef";
52 let mut out = String::with_capacity(bytes.len() * 2);
53 for byte in bytes {
54 out.push(HEX[(byte >> 4) as usize] as char);
55 out.push(HEX[(byte & 0x0f) as usize] as char);
56 }
57 Ok(out)
58}
59
60pub fn constant_time_eq(provided: &[u8], expected: &[u8]) -> bool {
61 let mut diff = provided.len() ^ expected.len();
62 for (i, &exp) in expected.iter().enumerate() {
63 let prov = provided.get(i).copied().unwrap_or(0);
64 diff |= usize::from(prov ^ exp);
65 }
66 std::hint::black_box(diff) == 0
67}
68
69fn has_valid_token(surface: &Surface, req: &Request) -> bool {
70 if surface.token.is_empty() {
71 return false;
72 }
73 let mut values = req.header_values(TOKEN_HEADER);
74 let Some(provided) = values.next() else {
75 return false;
76 };
77 if values.next().is_some() {
78 return false;
79 }
80 constant_time_eq(provided.as_bytes(), surface.token.as_bytes())
81}
82
83#[derive(Serialize, Deserialize)]
84struct SurfaceFile {
85 pid: u32,
86 port: u16,
87 session_id: String,
88 started_at: u64,
89}
90
91#[derive(Serialize)]
92struct RunWithHold<'a> {
93 #[serde(flatten)]
94 run: &'a crate::replay::Run,
95 hold: Option<Hold>,
96}
97
98#[derive(Serialize)]
99struct LiveRunsResponse<'a> {
100 generated_at: u64,
101 repo: &'a str,
102 running: &'a [crate::live_runs::RunningRun],
103 runs: Vec<RunWithHold<'a>>,
104 skipped: &'a [crate::replay::Skipped],
105}
106
107fn json_error(status: u16, msg: impl Into<String>) -> Response {
108 Response::json(status, &serde_json::json!({ "error": msg.into() }))
109}
110
111fn method_not_allowed(req: &Request) -> Response {
112 json_error(
113 405,
114 format!("method {} not allowed for {}", req.method, req.path),
115 )
116}
117
118fn is_valid_run_id(id: &str) -> bool {
119 !id.is_empty()
120 && id != "."
121 && id != ".."
122 && id
123 .bytes()
124 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
125}
126
127fn parse_json_object(body: &[u8]) -> Result<serde_json::Map<String, serde_json::Value>, Response> {
128 let val: serde_json::Value = serde_json::from_slice(body)
129 .map_err(|e| json_error(400, format!("invalid JSON body: {e}")))?;
130 val.as_object()
131 .cloned()
132 .ok_or_else(|| json_error(400, "request body must be a JSON object"))
133}
134
135fn health_response(surface: &Surface) -> Response {
136 Response::json(
137 200,
138 &serde_json::json!({ "session_id": surface.session_id }),
139 )
140}
141
142fn session_response(surface: &Surface) -> Response {
143 let info = surface.session.info();
144 Response::json(
145 200,
146 &serde_json::json!({
147 "session_id": surface.session_id,
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
383fn 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 mut live = crate::live_runs::collect(&surface.root, now, surface.days)?;
392 let mut any_written = false;
393 for run in &live.runs {
394 if run.checks_recorded {
395 continue;
396 }
397 if crate::queue_actions::ensure_checks(&surface.root, &run.id)? {
398 any_written = true;
399 }
400 }
401 if any_written {
402 live = crate::live_runs::collect(&surface.root, now, surface.days)?;
403 }
404
405 let mut errors = Vec::new();
406 if let Err(e) = crate::run_results::report_finished_runs(surface) {
407 errors.push(format!("run report failed: {e}"));
408 }
409
410 let mut triggered = BTreeSet::new();
411 for run in &live.runs {
412 if run.research {
413 continue;
414 }
415 if let Some(ref req_id) = run.request {
416 if triggered.insert(req_id.clone()) {
417 if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
418 errors.push(format!("combine trigger failed for {req_id}: {e}"));
419 }
420 }
421 }
422 }
423
424 Ok((live, errors))
425}
426
427fn handle_runs(surface: &Surface, now: u64) -> Response {
428 let (live, errors) = match reconcile_runs(surface, now) {
429 Ok(res) => res,
430 Err(e) => return json_error(500, e),
431 };
432 for msg in errors {
433 surface.session.record_error(&msg);
434 }
435
436 let mut runs_with_hold = Vec::with_capacity(live.runs.len());
437 for run in &live.runs {
438 let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
439 Ok(h) => h,
440 Err(e) => return json_error(500, e),
441 };
442 runs_with_hold.push(RunWithHold { run, hold });
443 }
444
445 let payload = LiveRunsResponse {
446 generated_at: live.generated_at,
447 repo: &live.repo,
448 running: &live.running,
449 runs: runs_with_hold,
450 skipped: &live.skipped,
451 };
452 match serde_json::to_value(&payload) {
453 Ok(val) => Response::json(200, &val),
454 Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
455 }
456}
457
458fn handle_runs_changed(surface: &Surface) -> Response {
459 surface.reconcile_requested.store(true, Ordering::Release);
460 Response::json(202, &serde_json::json!({}))
461}
462
463fn handle_run_diff(surface: &Surface, id: &str) -> Response {
464 if !is_valid_run_id(id) {
465 return json_error(404, format!("unknown run: {id}"));
466 }
467 let wt_dir = surface.root.join(".wt");
468 let wt = wt_dir.join(id);
469 let summary = wt_dir.join(format!("{id}.json"));
470 let report_json = wt_dir.join(format!("{id}.report.json"));
471 let report_md = wt_dir.join(format!("{id}.report.md"));
472 if !wt.exists() && !summary.exists() && !report_json.exists() && !report_md.exists() {
473 return json_error(404, format!("unknown run: {id}"));
474 }
475 match crate::queue_actions::compute_review(&surface.root, id, true) {
476 Ok(data) => {
477 let body = if !data.wt_exists {
478 "(worktree removed)\n".to_string()
479 } else if data.diff_out.is_empty() {
480 String::new()
481 } else {
482 format!("{}\n", data.diff_out)
483 };
484 Response::text(200, &body)
485 }
486 Err(e) => {
487 if !wt.is_dir() || !wt.join(".git").exists() {
488 json_error(404, e)
489 } else {
490 json_error(500, e)
491 }
492 }
493 }
494}
495
496fn parse_action(raw: &str) -> Result<Action, String> {
497 match raw {
498 "accept" => Ok(Action::Accept),
499 "send_back" => Ok(Action::SendBack),
500 "redo" => Ok(Action::Redo),
501 "hold" => Ok(Action::Hold),
502 "mark_read" => Ok(Action::MarkRead),
503 other => Err(format!(
504 "unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
505 )),
506 }
507}
508
509fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
510 let obj = match parse_json_object(&req.body) {
511 Ok(o) => o,
512 Err(resp) => return resp,
513 };
514 let action_str = match obj.get("action") {
515 Some(serde_json::Value::String(s)) => s.clone(),
516 Some(_) => return json_error(400, "field action must be a string"),
517 None => return json_error(400, "missing required field: action"),
518 };
519 let action = match parse_action(&action_str) {
520 Ok(a) => a,
521 Err(e) => return json_error(400, e),
522 };
523 let note = match obj.get("note") {
524 None | Some(serde_json::Value::Null) => None,
525 Some(serde_json::Value::String(s)) => Some(s.clone()),
526 Some(_) => return json_error(400, "field note must be a string or null"),
527 };
528
529 let decision =
530 match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
531 Ok(d) => d,
532 Err(e) => return json_error(400, e),
533 };
534 let seq = match surface.session.record_decision(
535 &decision.run,
536 &action_str,
537 decision.note.as_deref(),
538 decision.orchestrator_message.as_deref(),
539 ) {
540 Ok(s) => s,
541 Err(e) => return json_error(500, e),
542 };
543 if action == Action::Accept {
544 match crate::requests::run_request_id(&surface.root, &decision.run) {
545 Ok(Some(req_id)) => {
546 if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
547 surface
548 .session
549 .record_error(&format!("combine trigger failed for {req_id}: {e}"));
550 }
551 }
552 Ok(None) => {}
553 Err(e) => return json_error(500, e),
554 }
555 }
556 Response::json(
557 200,
558 &serde_json::json!({
559 "decision": {
560 "run": decision.run,
561 "action": action_str,
562 "note": decision.note,
563 "orchestrator_message": decision.orchestrator_message,
564 },
565 "seq": seq,
566 }),
567 )
568}
569
570fn handle_map(surface: &Surface) -> Response {
571 match crate::map::build(&surface.root, &surface.repo) {
572 Ok(data) => match serde_json::to_value(&data) {
573 Ok(val) => Response::json(200, &val),
574 Err(e) => json_error(500, format!("failed to serialize map: {e}")),
575 },
576 Err(e) => json_error(422, e),
577 }
578}
579
580fn handle_requests(surface: &Surface) -> Response {
581 match crate::requests::list_requests(surface) {
582 Ok(list) => match serde_json::to_value(&list) {
583 Ok(val) => Response::json(200, &val),
584 Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
585 },
586 Err(e) => json_error(500, e),
587 }
588}
589
590fn request_action_error_response(err: RequestActionError) -> Response {
591 match err {
592 RequestActionError::BadRequest(msg) => json_error(400, msg),
593 RequestActionError::Conflict(msg) => json_error(409, msg),
594 RequestActionError::Internal(msg) => json_error(500, msg),
595 }
596}
597
598fn handle_request_push(surface: &Surface, id: &str) -> Response {
599 match crate::requests::push_request(surface, id) {
600 Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
601 Err(err) => request_action_error_response(err),
602 }
603}
604
605fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
606 if let Err(e) = crate::dispatch::validate_request_id(id) {
607 return json_error(400, e);
608 }
609 let obj = match parse_json_object(&req.body) {
610 Ok(o) => o,
611 Err(resp) => return resp,
612 };
613 let title = match obj.get("title") {
614 Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
615 Some(serde_json::Value::String(_)) => {
616 return json_error(400, "field title must not be empty");
617 }
618 Some(_) => return json_error(400, "field title must be a string"),
619 None => return json_error(400, "missing required field: title"),
620 };
621 let body = match obj.get("body") {
622 None | Some(serde_json::Value::Null) => String::new(),
623 Some(serde_json::Value::String(s)) => s.clone(),
624 Some(_) => return json_error(400, "field body must be a string"),
625 };
626 match crate::requests::open_request_pull_request(surface, id, &title, &body) {
627 Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
628 Err(err) => request_action_error_response(err),
629 }
630}
631
632#[derive(Clone, Copy)]
633enum ApiGetHandler {
634 Session,
635 Events,
636 Models,
637 Runs,
638 Requests,
639 Map,
640 RunDiff,
641}
642
643const API_GET_ROUTES: &[(&str, ApiGetHandler)] = &[
644 ("/api/session", ApiGetHandler::Session),
645 ("/api/session/events", ApiGetHandler::Events),
646 ("/api/models", ApiGetHandler::Models),
647 ("/api/runs", ApiGetHandler::Runs),
648 ("/api/requests", ApiGetHandler::Requests),
649 ("/api/map", ApiGetHandler::Map),
650 ("/api/runs/{id}/diff", ApiGetHandler::RunDiff),
651];
652
653pub fn authenticated_api_get_routes() -> Vec<&'static str> {
654 API_GET_ROUTES.iter().map(|(pattern, _)| *pattern).collect()
655}
656
657fn match_api_get_route<'a>(pattern: &str, path: &'a str) -> Option<Option<&'a str>> {
658 if let Some((prefix, suffix)) = pattern.split_once("{id}") {
659 let rest = path.strip_prefix(prefix)?;
660 let id = rest.strip_suffix(suffix)?;
661 if !id.is_empty() && !id.contains('/') {
662 return Some(Some(id));
663 }
664 None
665 } else if pattern == path {
666 Some(None)
667 } else {
668 None
669 }
670}
671
672pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
673 let is_health_get = req.path == "/api/health" && req.method == "GET";
674 if (req.path.starts_with("/api/") || req.method == "POST")
675 && !is_health_get
676 && !has_valid_token(surface, req)
677 {
678 return json_error(
679 403,
680 "missing or invalid surface token; open the page from the URL blyte printed",
681 );
682 }
683
684 if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
685 if req.method != "GET" {
686 return method_not_allowed(req);
687 }
688 return Response {
689 status,
690 content_type,
691 body,
692 };
693 }
694
695 if req.path == "/" || req.path == "/index.html" {
696 if req.method != "GET" {
697 return method_not_allowed(req);
698 }
699 return Response::html(INDEX_HTML.as_bytes().to_vec());
700 }
701
702 if req.path == "/api/health" {
703 if req.method != "GET" {
704 return method_not_allowed(req);
705 }
706 return health_response(surface);
707 }
708
709 for &(pattern, handler) in API_GET_ROUTES {
710 if let Some(id) = match_api_get_route(pattern, &req.path) {
711 if req.method != "GET" {
712 return method_not_allowed(req);
713 }
714 return match handler {
715 ApiGetHandler::Session => session_response(surface),
716 ApiGetHandler::Events => handle_events(surface, req),
717 ApiGetHandler::Models => handle_models(),
718 ApiGetHandler::Runs => handle_runs(surface, now),
719 ApiGetHandler::Requests => handle_requests(surface),
720 ApiGetHandler::Map => handle_map(surface),
721 ApiGetHandler::RunDiff => handle_run_diff(surface, id.unwrap_or("")),
722 };
723 }
724 }
725
726 match req.path.as_str() {
727 "/api/session/messages" => {
728 if req.method != "POST" {
729 return method_not_allowed(req);
730 }
731 handle_post_message(surface, req)
732 }
733 "/api/session/model" => {
734 if req.method != "POST" {
735 return method_not_allowed(req);
736 }
737 handle_post_model(surface, req)
738 }
739 "/api/session/effort" => {
740 if req.method != "POST" {
741 return method_not_allowed(req);
742 }
743 handle_post_effort(surface, req)
744 }
745 "/api/runs/changed" => {
746 if req.method != "POST" {
747 return method_not_allowed(req);
748 }
749 handle_runs_changed(surface)
750 }
751 path => {
752 if let Some(id) = path.strip_prefix("/api/session/approvals/") {
753 if !id.is_empty() && !id.contains('/') {
754 if req.method != "POST" {
755 return method_not_allowed(req);
756 }
757 return handle_post_approval(surface, id, req);
758 }
759 }
760 if let Some(rest) = path.strip_prefix("/api/runs/") {
761 if let Some(id) = rest.strip_suffix("/decision") {
762 if !id.is_empty() && !id.contains('/') {
763 if req.method != "POST" {
764 return method_not_allowed(req);
765 }
766 return handle_run_decision(surface, id, req, now);
767 }
768 }
769 }
770 if let Some(rest) = path.strip_prefix("/api/requests/") {
771 if let Some(id) = rest.strip_suffix("/push") {
772 if req.method != "POST" {
773 return method_not_allowed(req);
774 }
775 return handle_request_push(surface, id);
776 }
777 if let Some(id) = rest.strip_suffix("/pull-request") {
778 if req.method != "POST" {
779 return method_not_allowed(req);
780 }
781 return handle_request_pull_request(surface, id, req);
782 }
783 }
784 json_error(404, format!("not found: {}", req.path))
785 }
786 }
787}
788
789fn find_git_toplevel(dir: &Path) -> Result<PathBuf, String> {
790 let out = Command::new("git")
791 .args(["rev-parse", "--show-toplevel"])
792 .current_dir(dir)
793 .output()
794 .map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
795 if !out.status.success() {
796 return Err(format!("not inside a git repository ({})", dir.display()));
797 }
798 let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
799 if path_str.is_empty() {
800 return Err(format!("not inside a git repository ({})", dir.display()));
801 }
802 Ok(PathBuf::from(path_str))
803}
804
805fn repo_name_for(root: &Path) -> Result<String, String> {
806 root.file_name()
807 .and_then(|s| s.to_str())
808 .filter(|s| !s.is_empty())
809 .map(String::from)
810 .ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
811}
812
813fn now_duration() -> Result<Duration, String> {
814 SystemTime::now()
815 .duration_since(UNIX_EPOCH)
816 .map_err(|e| format!("system clock is before Unix epoch: {e}"))
817}
818
819fn new_session_id(nanos: u128) -> String {
820 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
821 format!("surface-{}-{nanos}-{seq}", std::process::id())
822}
823
824fn probe_existing_surface(port: u16, expected_session_id: &str) -> bool {
825 let addr = SocketAddr::from(([127, 0, 0, 1], port));
826 let mut stream = match TcpStream::connect_timeout(&addr, PROBE_TIMEOUT) {
827 Ok(s) => s,
828 Err(_) => return false,
829 };
830 let _ = stream.set_read_timeout(Some(PROBE_TIMEOUT));
831 let _ = stream.set_write_timeout(Some(PROBE_TIMEOUT));
832 let req =
833 format!("GET /api/health HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
834 if stream.write_all(req.as_bytes()).is_err() {
835 return false;
836 }
837 let mut raw = Vec::new();
838 if stream.read_to_end(&mut raw).is_err() {
839 return false;
840 }
841 let text = match std::str::from_utf8(&raw) {
842 Ok(s) => s,
843 Err(_) => return false,
844 };
845 let (head, body) = match text.split_once("\r\n\r\n") {
846 Some(parts) => parts,
847 None => return false,
848 };
849 let status_line = head.lines().next().unwrap_or("");
850 if !(status_line.starts_with("HTTP/1.1 200") || status_line.starts_with("HTTP/1.0 200")) {
851 return false;
852 }
853 let val: serde_json::Value = match serde_json::from_str(body) {
854 Ok(v) => v,
855 Err(_) => return false,
856 };
857 val.get("session_id").and_then(|v| v.as_str()) == Some(expected_session_id)
858}
859
860fn open_browser(url: &str) {
861 #[cfg(target_os = "macos")]
862 let cmd = "open";
863 #[cfg(not(target_os = "macos"))]
864 let cmd = "xdg-open";
865 if let Err(e) = Command::new(cmd).arg(url).spawn() {
866 eprintln!("blyte: could not open a browser with {cmd}: {e}; open {url} yourself");
867 }
868}
869
870fn resolve_initial_model(config: &ReplConfig) -> String {
871 if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
872 return m.to_string();
873 }
874 if let Ok(m) = std::env::var("BLYTE_MODEL") {
875 if !m.trim().is_empty() {
876 return m;
877 }
878 }
879 if let Ok(p) = blyte_provider::resolve_provider(None) {
880 return p.model_id();
881 }
882 "gemini-3.8-flash-high".to_string()
883}
884
885#[cfg(unix)]
886static SIGNAL_STOP: AtomicBool = AtomicBool::new(false);
887
888#[cfg(unix)]
889extern "C" fn handle_shutdown_signal(_: libc::c_int) {
890 SIGNAL_STOP.store(true, Ordering::Relaxed);
891}
892
893fn write_token_file(wt_dir: &Path, token_file_path: &Path, token: &str) -> Result<(), String> {
894 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
895 let tmp_path = wt_dir.join(format!(".surface.token.{}.{seq}.tmp", std::process::id()));
896 let mut opts = std::fs::OpenOptions::new();
897 opts.write(true).create_new(true);
898 #[cfg(unix)]
899 {
900 opts.mode(0o600);
901 }
902 let mut file = opts
903 .open(&tmp_path)
904 .map_err(|e| format!("cannot create {}: {e}", token_file_path.display()))?;
905 if let Err(e) = writeln!(file, "{token}") {
906 let _ = std::fs::remove_file(&tmp_path);
907 return Err(format!("cannot write {}: {e}", token_file_path.display()));
908 }
909 drop(file);
910 if let Err(e) = std::fs::rename(&tmp_path, token_file_path) {
911 let _ = std::fs::remove_file(&tmp_path);
912 return Err(format!("cannot write {}: {e}", token_file_path.display()));
913 }
914 Ok(())
915}
916
917fn read_token_file(token_file_path: &Path) -> Result<String, String> {
918 let raw = std::fs::read_to_string(token_file_path)
919 .map_err(|e| format!("cannot read {}: {e}", token_file_path.display()))?;
920 let token = raw.trim().to_string();
921 if token.is_empty() {
922 return Err(format!("{} is empty", token_file_path.display()));
923 }
924 Ok(token)
925}
926
927pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
928 #[cfg(unix)]
929 {
930 SIGNAL_STOP.store(false, Ordering::Relaxed);
931 unsafe {
932 libc::signal(
933 libc::SIGINT,
934 handle_shutdown_signal as *const () as libc::sighandler_t,
935 );
936 libc::signal(
937 libc::SIGTERM,
938 handle_shutdown_signal as *const () as libc::sighandler_t,
939 );
940 }
941 }
942 run_inner(
943 args,
944 config,
945 &mut std::io::stdout(),
946 &mut std::io::stderr(),
947 &mut open_browser,
948 || {
949 #[cfg(unix)]
950 {
951 SIGNAL_STOP.load(Ordering::Relaxed)
952 }
953 #[cfg(not(unix))]
954 {
955 false
956 }
957 },
958 )
959}
960
961pub fn run_with_io(
962 args: &SurfaceArgs,
963 config: ReplConfig,
964 out: &mut dyn Write,
965 err: &mut dyn Write,
966) -> i32 {
967 run_inner(args, config, out, err, &mut open_browser, || false)
968}
969
970pub fn run_with_hooks(
971 args: &SurfaceArgs,
972 config: ReplConfig,
973 out: &mut dyn Write,
974 err: &mut dyn Write,
975 opener: &mut dyn FnMut(&str),
976 stop: Arc<AtomicBool>,
977) -> i32 {
978 run_inner(args, config, out, err, opener, move || {
979 stop.load(Ordering::Relaxed)
980 })
981}
982
983struct ReconcileTimerGuard {
984 stop: Arc<AtomicBool>,
985 handle: Option<std::thread::JoinHandle<()>>,
986}
987
988impl Drop for ReconcileTimerGuard {
989 fn drop(&mut self) {
990 self.stop.store(true, Ordering::Release);
991 if let Some(handle) = self.handle.take() {
992 let _ = handle.join();
993 }
994 }
995}
996
997fn spawn_reconcile_timer(surface: Arc<Surface>) -> ReconcileTimerGuard {
998 let stop = Arc::new(AtomicBool::new(false));
999 let thread_stop = Arc::clone(&stop);
1000 let handle = std::thread::spawn(move || {
1001 let mut after = surface.session.info().last_seq;
1002 let mut next_tick = Instant::now();
1003 let mut seen_errors: HashSet<String> = HashSet::new();
1004 while !thread_stop.load(Ordering::Acquire) {
1005 let wait = if surface.reconcile_requested.load(Ordering::Acquire) {
1006 Duration::ZERO
1007 } else {
1008 next_tick
1009 .saturating_duration_since(Instant::now())
1010 .min(RECONCILE_POLL_WAIT)
1011 };
1012 let entries = surface.session.entries_after(after, wait);
1013 let mut went_idle = false;
1014 for entry in entries {
1015 after = entry.seq;
1016 if matches!(entry.body, EntryBody::Idle { .. }) {
1017 went_idle = true;
1018 }
1019 }
1020 if thread_stop.load(Ordering::Acquire) {
1021 break;
1022 }
1023 let requested = surface.reconcile_requested.swap(false, Ordering::AcqRel);
1024 if went_idle || requested || Instant::now() >= next_tick {
1025 match now_duration().and_then(|d| reconcile_runs(&surface, d.as_secs())) {
1026 Ok((_, errors)) => {
1027 for msg in errors {
1028 if seen_errors.insert(msg.clone()) {
1029 surface.session.record_error(&msg);
1030 eprintln!("blyte: {msg}");
1031 }
1032 }
1033 }
1034 Err(e) => {
1035 if seen_errors.insert(e.clone()) {
1036 eprintln!("blyte: {e}");
1037 }
1038 }
1039 }
1040 next_tick = Instant::now() + RECONCILE_SAFETY_NET_INTERVAL;
1041 }
1042 }
1043 });
1044 ReconcileTimerGuard {
1045 stop,
1046 handle: Some(handle),
1047 }
1048}
1049
1050fn run_inner<S>(
1051 args: &SurfaceArgs,
1052 mut config: ReplConfig,
1053 out: &mut dyn Write,
1054 err: &mut dyn Write,
1055 opener: &mut dyn FnMut(&str),
1056 should_stop: S,
1057) -> i32
1058where
1059 S: Fn() -> bool,
1060{
1061 let root = match find_git_toplevel(&config.repo_root) {
1062 Ok(r) => r,
1063 Err(e) => {
1064 let _ = writeln!(err, "blyte: {e}");
1065 return 1;
1066 }
1067 };
1068 let repo = match repo_name_for(&root) {
1069 Ok(r) => r,
1070 Err(e) => {
1071 let _ = writeln!(err, "blyte: {e}");
1072 return 1;
1073 }
1074 };
1075
1076 let wt_dir = root.join(".wt");
1077 let surface_file_path = wt_dir.join("surface.json");
1078 let token_file_path = wt_dir.join("surface.token");
1079 match std::fs::read_to_string(&surface_file_path) {
1080 Ok(raw) => match serde_json::from_str::<SurfaceFile>(&raw) {
1081 Ok(existing) => {
1082 if probe_existing_surface(existing.port, &existing.session_id) {
1083 let token = match read_token_file(&token_file_path) {
1084 Ok(t) => t,
1085 Err(e) => {
1086 let _ = writeln!(err, "blyte: {e}");
1087 let _ = err.flush();
1088 return 1;
1089 }
1090 };
1091 let url = format!("http://127.0.0.1:{}/#token={token}", existing.port);
1092 let _ = writeln!(out, "blyte: surface already running at {url}");
1093 let _ = out.flush();
1094 if !args.no_open {
1095 opener(&url);
1096 }
1097 return 0;
1098 }
1099 let _ = writeln!(
1100 err,
1101 "blyte: stale surface file {} (port {}, session {}); replacing it",
1102 surface_file_path.display(),
1103 existing.port,
1104 existing.session_id
1105 );
1106 let _ = err.flush();
1107 }
1108 Err(e) => {
1109 let _ = writeln!(
1110 err,
1111 "blyte: cannot parse {}: {e}",
1112 surface_file_path.display()
1113 );
1114 return 1;
1115 }
1116 },
1117 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1118 Err(e) => {
1119 let _ = writeln!(
1120 err,
1121 "blyte: cannot read {}: {e}",
1122 surface_file_path.display()
1123 );
1124 return 1;
1125 }
1126 }
1127
1128 if !config.orchestrate {
1129 config.orchestrate = true;
1130 if config.max_turns == 25 || config.max_turns == 60 {
1131 config.max_turns = 1000;
1132 }
1133 if config.fold_budget.is_none() {
1134 config.fold_budget = Some(100_000);
1135 }
1136 }
1137 config.repo_root = root.clone();
1138
1139 let started_dur = match now_duration() {
1140 Ok(d) => d,
1141 Err(e) => {
1142 let _ = writeln!(err, "blyte: {e}");
1143 return 1;
1144 }
1145 };
1146 let started_at = started_dur.as_secs();
1147 let session_id = new_session_id(started_dur.as_nanos());
1148 if std::env::var("BLYTE_SESSION")
1149 .map(|v| v.is_empty())
1150 .unwrap_or(true)
1151 {
1152 std::env::set_var("BLYTE_SESSION", &session_id);
1153 }
1154
1155 let token = match generate_token() {
1156 Ok(t) => t,
1157 Err(e) => {
1158 let _ = writeln!(err, "blyte: {e}");
1159 return 1;
1160 }
1161 };
1162
1163 let bind_addr = format!("127.0.0.1:{}", args.port);
1164 let listener = match TcpListener::bind(&bind_addr) {
1165 Ok(l) => l,
1166 Err(e) => {
1167 let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
1168 return 1;
1169 }
1170 };
1171 let actual_port = match listener.local_addr() {
1172 Ok(a) => a.port(),
1173 Err(e) => {
1174 let _ = writeln!(err, "blyte: failed to read listener address: {e}");
1175 return 1;
1176 }
1177 };
1178
1179 let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
1180 let entries_log_path = main_checkout
1181 .join(".wt")
1182 .join("sessions")
1183 .join("entries.jsonl");
1184 let model = resolve_initial_model(&config);
1185 let session = match Session::start_with_log_io(model, Some(entries_log_path), err, |approver| {
1186 Box::new(AgentRunner::new(&config, approver))
1187 }) {
1188 Ok(s) => s,
1189 Err(e) => {
1190 let _ = writeln!(err, "blyte: {e}");
1191 let _ = err.flush();
1192 return 1;
1193 }
1194 };
1195
1196 if let Err(e) = std::fs::create_dir_all(&wt_dir) {
1197 let _ = writeln!(err, "blyte: cannot create {}: {e}", wt_dir.display());
1198 return 1;
1199 }
1200 if let Err(e) = write_token_file(&wt_dir, &token_file_path, &token) {
1201 let _ = writeln!(err, "blyte: {e}");
1202 return 1;
1203 }
1204 let record = SurfaceFile {
1205 pid: std::process::id(),
1206 port: actual_port,
1207 session_id: session_id.clone(),
1208 started_at,
1209 };
1210 let record_json = match serde_json::to_string_pretty(&record) {
1211 Ok(s) => s + "\n",
1212 Err(e) => {
1213 let _ = std::fs::remove_file(&token_file_path);
1214 let _ = writeln!(err, "blyte: cannot serialize surface file: {e}");
1215 return 1;
1216 }
1217 };
1218 if let Err(e) = std::fs::write(&surface_file_path, record_json) {
1219 let _ = std::fs::remove_file(&token_file_path);
1220 let _ = writeln!(
1221 err,
1222 "blyte: cannot write {}: {e}",
1223 surface_file_path.display()
1224 );
1225 return 1;
1226 }
1227
1228 let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
1229 let _ = writeln!(out, "blyte: surface at {url}");
1230 let _ = out.flush();
1231 if !args.no_open {
1232 opener(&url);
1233 }
1234
1235 let surface = Arc::new(Surface {
1236 root,
1237 repo,
1238 session,
1239 session_id,
1240 started_at,
1241 days: args.days,
1242 token,
1243 requests: Arc::new(RequestsState::new()),
1244 publisher: Arc::new(RealPublisher),
1245 reconcile_lock: Mutex::new(()),
1246 reconcile_requested: AtomicBool::new(false),
1247 });
1248
1249 let timer_guard = spawn_reconcile_timer(Arc::clone(&surface));
1250
1251 let serve_result =
1252 crate::http::serve_until(listener, should_stop, move |req| match now_duration() {
1253 Ok(d) => route(&surface, req, d.as_secs()),
1254 Err(e) => json_error(500, e),
1255 });
1256
1257 drop(timer_guard);
1258
1259 let _ = std::fs::remove_file(&surface_file_path);
1260 let _ = std::fs::remove_file(&token_file_path);
1261
1262 match serve_result {
1263 Ok(()) => 0,
1264 Err(e) => {
1265 let _ = writeln!(err, "blyte: server error: {e}");
1266 1
1267 }
1268 }
1269}