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