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::{
19 AgentRunner, AnswerError, ApprovalAnswer, Attachment, EntryBody, PeerDelivery, PromptRunner,
20 Session,
21};
22use crate::surface_dir::SurfaceRecord;
23
24pub const TOKEN_HEADER: &str = "X-Blyte-Token";
25pub const MESSAGE_HEADER: &str = "X-Blyte-Message-Credential";
26pub const RECONCILE_SAFETY_NET_INTERVAL: Duration = Duration::from_secs(30);
27
28const INDEX_HTML: &str = include_str!("../assets/surface/index.html");
29const MAX_WAIT_MS: u64 = 25_000;
30const RECONCILE_POLL_WAIT: Duration = Duration::from_millis(50);
31const TOKEN_BYTES: usize = 32;
32const MAX_PEER_TEXT_BYTES: usize = 16_384;
33const MAX_PEER_REPO_CHARS: usize = 200;
34
35static SESSION_COUNTER: AtomicU64 = AtomicU64::new(1);
36
37pub struct Surface {
38 pub surface_id: String,
39 pub surface_name: String,
40 pub root: PathBuf,
41 pub repo: String,
42 pub session: Session,
43 pub session_id: String,
44 pub started_at: u64,
45 pub days: u64,
46 pub token: String,
47 pub message_credential: String,
48 pub requests: Arc<RequestsState>,
49 pub publisher: Arc<dyn Publisher>,
50 pub reconcile_lock: Mutex<()>,
51 pub reconcile_requested: AtomicBool,
52}
53
54pub fn generate_token() -> Result<String, String> {
55 let mut bytes = [0u8; TOKEN_BYTES];
56 let mut file = std::fs::File::open("/dev/urandom")
57 .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
58 file.read_exact(&mut bytes)
59 .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
60 const HEX: &[u8; 16] = b"0123456789abcdef";
61 let mut out = String::with_capacity(bytes.len() * 2);
62 for byte in bytes {
63 out.push(HEX[(byte >> 4) as usize] as char);
64 out.push(HEX[(byte & 0x0f) as usize] as char);
65 }
66 Ok(out)
67}
68
69pub fn constant_time_eq(provided: &[u8], expected: &[u8]) -> bool {
70 let mut diff = provided.len() ^ expected.len();
71 for (i, &exp) in expected.iter().enumerate() {
72 let prov = provided.get(i).copied().unwrap_or(0);
73 diff |= usize::from(prov ^ exp);
74 }
75 std::hint::black_box(diff) == 0
76}
77
78fn has_valid_token(surface: &Surface, req: &Request) -> bool {
79 if surface.token.is_empty() {
80 return false;
81 }
82 let mut values = req.header_values(TOKEN_HEADER);
83 let Some(provided) = values.next() else {
84 return false;
85 };
86 if values.next().is_some() {
87 return false;
88 }
89 constant_time_eq(provided.as_bytes(), surface.token.as_bytes())
90}
91
92fn has_valid_message_credential(surface: &Surface, req: &Request) -> bool {
93 if surface.message_credential.is_empty() {
94 return false;
95 }
96 let mut values = req.header_values(MESSAGE_HEADER);
97 let Some(provided) = values.next() else {
98 return false;
99 };
100 if values.next().is_some() {
101 return false;
102 }
103 constant_time_eq(provided.as_bytes(), surface.message_credential.as_bytes())
104}
105
106#[derive(Serialize)]
107struct RunWithHold<'a> {
108 #[serde(flatten)]
109 run: &'a crate::replay::Run,
110 hold: Option<Hold>,
111 combined: bool,
112}
113
114#[derive(Serialize)]
115struct LiveRunsResponse<'a> {
116 generated_at: u64,
117 repo: &'a str,
118 running: &'a [crate::live_runs::RunningRun],
119 runs: Vec<RunWithHold<'a>>,
120 skipped: &'a [crate::replay::Skipped],
121}
122
123fn json_error(status: u16, msg: impl Into<String>) -> Response {
124 Response::json(status, &serde_json::json!({ "error": msg.into() }))
125}
126
127fn method_not_allowed(req: &Request) -> Response {
128 json_error(
129 405,
130 format!("method {} not allowed for {}", req.method, req.path),
131 )
132}
133
134fn is_valid_run_id(id: &str) -> bool {
135 !id.is_empty()
136 && id != "."
137 && id != ".."
138 && id
139 .bytes()
140 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
141}
142
143fn parse_json_object(body: &[u8]) -> Result<serde_json::Map<String, serde_json::Value>, Response> {
144 let val: serde_json::Value = serde_json::from_slice(body)
145 .map_err(|e| json_error(400, format!("invalid JSON body: {e}")))?;
146 val.as_object()
147 .cloned()
148 .ok_or_else(|| json_error(400, "request body must be a JSON object"))
149}
150
151fn health_response(surface: &Surface) -> Response {
152 Response::json(
153 200,
154 &serde_json::json!({
155 "surface_id": surface.surface_id,
156 "surface_name": surface.surface_name,
157 "session_id": surface.session_id,
158 }),
159 )
160}
161
162fn session_response(surface: &Surface) -> Response {
163 let info = surface.session.info();
164 let repository = match is_repository(&surface.root) {
165 Ok(v) => v,
166 Err(e) => return json_error(500, e),
167 };
168 Response::json(
169 200,
170 &serde_json::json!({
171 "session_id": surface.session_id,
172 "surface_name": surface.surface_name,
173 "repo": surface.repo,
174 "repository": repository,
175 "started_at": surface.started_at,
176 "model": info.model,
177 "effort": info.effort,
178 "effort_supported": info.effort_supported,
179 "busy": info.busy,
180 "queued": info.queued,
181 "last_seq": info.last_seq,
182 }),
183 )
184}
185
186fn handle_events(surface: &Surface, req: &Request) -> Response {
187 let after_raw = match req.query_value("after") {
188 Some(v) => v,
189 None => return json_error(400, "missing required query parameter: after"),
190 };
191 let after = match after_raw.parse::<u64>() {
192 Ok(v) => v,
193 Err(_) => {
194 return json_error(
195 400,
196 format!("query parameter after must be a non-negative integer, got '{after_raw}'"),
197 );
198 }
199 };
200 let wait_ms = match req.query_value("wait_ms") {
201 None => 0,
202 Some(raw) => match raw.parse::<u64>() {
203 Ok(v) if v <= MAX_WAIT_MS => v,
204 Ok(v) => {
205 return json_error(
206 400,
207 format!("query parameter wait_ms must be at most {MAX_WAIT_MS}, got {v}"),
208 );
209 }
210 Err(_) => {
211 return json_error(
212 400,
213 format!("query parameter wait_ms must be a non-negative integer, got '{raw}'"),
214 );
215 }
216 },
217 };
218 let entries = surface
219 .session
220 .entries_after(after, Duration::from_millis(wait_ms));
221 let last_seq = surface.session.info().last_seq;
222 Response::json(
223 200,
224 &serde_json::json!({
225 "entries": entries,
226 "last_seq": last_seq,
227 }),
228 )
229}
230
231fn handle_post_message(surface: &Surface, req: &Request) -> Response {
232 let obj = match parse_json_object(&req.body) {
233 Ok(o) => o,
234 Err(resp) => return resp,
235 };
236 let attachment_ids: Vec<String> = match obj.get("attachments") {
237 None | Some(serde_json::Value::Null) => Vec::new(),
238 Some(serde_json::Value::Array(arr)) => {
239 let mut ids = Vec::with_capacity(arr.len());
240 for item in arr {
241 match item.as_str() {
242 Some(s) => ids.push(s.to_string()),
243 None => {
244 return json_error(400, "field attachments must be an array of strings");
245 }
246 }
247 }
248 ids
249 }
250 Some(_) => return json_error(400, "field attachments must be an array of strings"),
251 };
252 let text = match obj.get("text") {
253 Some(serde_json::Value::String(s)) => s.clone(),
254 Some(serde_json::Value::Null) | None if !attachment_ids.is_empty() => String::new(),
255 Some(_) => return json_error(400, "field text must be a string"),
256 None => return json_error(400, "missing required field: text"),
257 };
258 let report_ids: Vec<String> = match obj.get("reports") {
259 None | Some(serde_json::Value::Null) => Vec::new(),
260 Some(serde_json::Value::Array(arr)) => {
261 let mut ids = Vec::with_capacity(arr.len());
262 for item in arr {
263 match item.as_str() {
264 Some(s) => ids.push(s.to_string()),
265 None => return json_error(400, "field reports must be an array of strings"),
266 }
267 }
268 ids
269 }
270 Some(_) => return json_error(400, "field reports must be an array of strings"),
271 };
272 let pastes: Vec<crate::session::Paste> = match obj.get("pastes") {
273 None | Some(serde_json::Value::Null) => Vec::new(),
274 Some(serde_json::Value::Array(arr)) => {
275 let mut out = Vec::with_capacity(arr.len());
276 for item in arr {
277 match serde_json::from_value::<crate::session::Paste>(item.clone()) {
278 Ok(p) => out.push(p),
279 Err(e) => return json_error(400, format!("invalid paste entry: {e}")),
280 }
281 }
282 out
283 }
284 Some(_) => return json_error(400, "field pastes must be an array"),
285 };
286
287 let mut report_attachments = Vec::with_capacity(report_ids.len());
288 for id in report_ids {
289 let path = surface.root.join(".wt").join(format!("{id}.report.md"));
290 if !is_valid_run_id(&id) {
291 return json_error(
292 400,
293 format!("invalid report run id '{id}' (path: {})", path.display()),
294 );
295 }
296 match std::fs::read_to_string(&path) {
297 Ok(body) => report_attachments.push(Attachment {
298 run: id,
299 text: body,
300 }),
301 Err(e) => {
302 return json_error(
303 400,
304 format!(
305 "cannot read report for run '{id}' at {}: {e}",
306 path.display()
307 ),
308 );
309 }
310 }
311 }
312
313 let mut file_attachments = Vec::with_capacity(attachment_ids.len());
314 if !attachment_ids.is_empty() {
315 let Some(record_dir) = surface.session.attachments_root() else {
316 return json_error(500, "attachments directory is not configured");
317 };
318 for id in attachment_ids {
319 match crate::attachments::load_with_path(&record_dir, &id) {
320 Ok((meta, path, _)) => {
321 file_attachments.push(crate::session::QueuedAttachment { meta, path })
322 }
323 Err(e) => return json_error(400, e),
324 }
325 }
326 }
327
328 match surface.session.submit_with_attachments(
329 &text,
330 report_attachments,
331 file_attachments,
332 pastes,
333 ) {
334 Ok(seq) => Response::json(200, &serde_json::json!({ "seq": seq })),
335 Err(e) => json_error(400, e),
336 }
337}
338
339fn handle_post_attachment(surface: &Surface, req: &Request) -> Response {
340 let Some(raw_name) = req
341 .query_value("name")
342 .map(str::trim)
343 .filter(|s| !s.is_empty())
344 else {
345 return json_error(400, "missing required query parameter: name");
346 };
347 if req.body.len() > crate::attachments::MAX_ATTACHMENT_BYTES {
348 return Response::text(
349 413,
350 &format!("{raw_name} is larger than the 10 MiB limit for one file"),
351 );
352 }
353 if req.body.is_empty() {
354 return json_error(400, format!("{raw_name} is empty"));
355 }
356 let Some(record_dir) = surface.session.attachments_root() else {
357 return json_error(500, "attachments directory is not configured");
358 };
359 match crate::attachments::store(&record_dir, raw_name, &req.body) {
360 Ok(meta) => match serde_json::to_value(&meta) {
361 Ok(v) => Response::json(200, &v),
362 Err(e) => json_error(500, format!("failed to serialise attachment metadata: {e}")),
363 },
364 Err(e) => json_error(400, e),
365 }
366}
367
368fn handle_get_attachment(surface: &Surface, id: &str) -> Response {
369 let Some(record_dir) = surface.session.attachments_root() else {
370 return json_error(500, "attachments directory is not configured");
371 };
372 match crate::attachments::load(&record_dir, id) {
373 Ok((_meta, bytes)) => {
374 let content_type =
375 crate::attachments::detect_image(&bytes).unwrap_or("application/octet-stream");
376 Response::bytes(200, content_type, bytes)
377 }
378 Err(e) => json_error(404, e),
379 }
380}
381
382fn handle_post_peer_message(surface: &Surface, req: &Request) -> Response {
383 let obj = match parse_json_object(&req.body) {
384 Ok(o) => o,
385 Err(resp) => return resp,
386 };
387 for key in obj.keys() {
388 if !matches!(key.as_str(), "from_name" | "from_repository" | "text") {
389 return json_error(400, format!("unexpected field: {key}"));
390 }
391 }
392 let from_name = match obj.get("from_name") {
393 Some(serde_json::Value::String(s)) => s.clone(),
394 Some(_) => return json_error(400, "field from_name must be a string"),
395 None => return json_error(400, "missing required field: from_name"),
396 };
397 if let Err(e) = crate::surface_dir::validate_surface_name(&from_name) {
398 return json_error(400, format!("invalid from_name: {e}"));
399 }
400 let from_repository = match obj.get("from_repository") {
401 Some(serde_json::Value::String(s)) => s.clone(),
402 Some(_) => return json_error(400, "field from_repository must be a string"),
403 None => return json_error(400, "missing required field: from_repository"),
404 };
405 let repo_chars = from_repository.chars().count();
406 if repo_chars == 0 || repo_chars > MAX_PEER_REPO_CHARS {
407 return json_error(
408 400,
409 format!("field from_repository must be 1 to {MAX_PEER_REPO_CHARS} characters"),
410 );
411 }
412 if from_repository.chars().any(char::is_control) {
413 return json_error(
414 400,
415 "field from_repository must not contain control characters",
416 );
417 }
418 let text = match obj.get("text") {
419 Some(serde_json::Value::String(s)) => s.clone(),
420 Some(_) => return json_error(400, "field text must be a string"),
421 None => return json_error(400, "missing required field: text"),
422 };
423 if text.trim().is_empty() {
424 return json_error(400, "field text must not be blank");
425 }
426 if text.len() > MAX_PEER_TEXT_BYTES {
427 return json_error(
428 400,
429 format!("field text must be at most {MAX_PEER_TEXT_BYTES} bytes"),
430 );
431 }
432
433 match surface
434 .session
435 .submit_peer(&from_name, &from_repository, &text)
436 {
437 Ok(PeerDelivery::Delivered) => {
438 Response::json(200, &serde_json::json!({ "status": "delivered" }))
439 }
440 Ok(PeerDelivery::Held) => Response::json(200, &serde_json::json!({ "status": "held" })),
441 Err(e) => json_error(400, e),
442 }
443}
444
445fn handle_models() -> Response {
446 let discovered = blyte_provider::discover_all_models();
447 let mut models = Vec::new();
448 let mut unavailable = Vec::new();
449 let mut error_parts = Vec::new();
450
451 for (provider, result) in discovered {
452 match result {
453 Ok(list) => {
454 for m in list {
455 let effort_supported = crate::session::model_supports_effort(&m.id);
456 models.push(serde_json::json!({
457 "id": m.id,
458 "effort_supported": effort_supported,
459 }));
460 }
461 }
462 Err(e) => {
463 let err_text = e.to_string();
464 error_parts.push(format!("{provider}: {err_text}"));
465 unavailable.push(serde_json::json!({
466 "provider": provider,
467 "error": err_text,
468 }));
469 }
470 }
471 }
472
473 if models.is_empty() {
474 let msg = if error_parts.is_empty() {
475 "no models listed by any provider".to_string()
476 } else {
477 format!("no models available: {}", error_parts.join("; "))
478 };
479 return json_error(502, msg);
480 }
481
482 Response::json(
483 200,
484 &serde_json::json!({
485 "models": models,
486 "unavailable": unavailable,
487 }),
488 )
489}
490
491fn handle_post_model(surface: &Surface, req: &Request) -> Response {
492 let obj = match parse_json_object(&req.body) {
493 Ok(o) => o,
494 Err(resp) => return resp,
495 };
496 let model = match obj.get("model") {
497 Some(serde_json::Value::String(s)) => s.clone(),
498 Some(_) => return json_error(400, "field model must be a string"),
499 None => return json_error(400, "missing required field: model"),
500 };
501 if model.trim().is_empty() {
502 return json_error(400, "field model must not be empty");
503 }
504 if let Err(e) = blyte_provider::resolve_provider(Some(&model)) {
505 return json_error(400, e.to_string());
506 }
507 if let Err(e) = surface.session.set_model(&model) {
508 return json_error(400, e);
509 }
510 session_response(surface)
511}
512
513fn handle_post_effort(surface: &Surface, req: &Request) -> Response {
514 let obj = match parse_json_object(&req.body) {
515 Ok(o) => o,
516 Err(resp) => return resp,
517 };
518 let effort = match obj.get("effort") {
519 Some(serde_json::Value::Null) => None,
520 Some(serde_json::Value::String(s)) => Some(s.clone()),
521 Some(_) => return json_error(400, "field effort must be a string or null"),
522 None => return json_error(400, "missing required field: effort"),
523 };
524 if let Err(e) = surface.session.set_effort(effort.as_deref()) {
525 return json_error(400, e);
526 }
527 session_response(surface)
528}
529
530fn handle_post_approval(surface: &Surface, id: &str, req: &Request) -> Response {
531 let obj = match parse_json_object(&req.body) {
532 Ok(o) => o,
533 Err(resp) => return resp,
534 };
535 if obj.len() != 1 {
536 return json_error(400, "request body must contain only field answer");
537 }
538 let answer = match obj.get("answer") {
539 Some(serde_json::Value::String(s)) if s == "yes" => ApprovalAnswer::Yes,
540 Some(serde_json::Value::String(s)) if s == "no" => ApprovalAnswer::No,
541 Some(serde_json::Value::String(other)) => {
542 return json_error(
543 400,
544 format!("field answer must be \"yes\" or \"no\", got '{other}'"),
545 );
546 }
547 Some(_) => return json_error(400, "field answer must be \"yes\" or \"no\""),
548 None => return json_error(400, "missing required field: answer"),
549 };
550 match surface.session.answer_approval(id, answer) {
551 Ok(seq) => Response::json(
552 200,
553 &serde_json::json!({
554 "id": id,
555 "answer": answer.as_str(),
556 "seq": seq,
557 }),
558 ),
559 Err(AnswerError::NotFound) => json_error(404, format!("unknown approval id: {id}")),
560 Err(AnswerError::AlreadyAnswered) => {
561 json_error(409, format!("approval {id} has already been answered"))
562 }
563 }
564}
565
566pub fn reconcile_runs(
567 surface: &Surface,
568 now: u64,
569) -> Result<(crate::live_runs::LiveRuns, Vec<String>), String> {
570 let _guard = surface
571 .reconcile_lock
572 .lock()
573 .unwrap_or_else(|e| e.into_inner());
574 if !is_repository(&surface.root)? {
575 return Ok((
576 crate::live_runs::LiveRuns {
577 generated_at: now,
578 repo: surface.repo.clone(),
579 running: Vec::new(),
580 runs: Vec::new(),
581 skipped: Vec::new(),
582 },
583 Vec::new(),
584 ));
585 }
586 let owned = crate::requests::owned_run_ids(surface)?;
587 let mut live = crate::live_runs::collect(&surface.root, now, surface.days)?;
588 let mut any_written = false;
589 for run in &live.runs {
590 if !owned.contains(&run.id) || run.checks_recorded {
591 continue;
592 }
593 if crate::queue_actions::ensure_checks(&surface.root, &run.id)? {
594 any_written = true;
595 }
596 }
597 if any_written {
598 live = crate::live_runs::collect(&surface.root, now, surface.days)?;
599 }
600 live.running.retain(|run| owned.contains(&run.id));
601 live.runs.retain(|run| owned.contains(&run.id));
602
603 let mut errors = Vec::new();
604 if let Err(e) = crate::run_results::report_finished_runs(surface) {
605 errors.push(format!("run report failed: {e}"));
606 }
607
608 let mut triggered = BTreeSet::new();
609 for run in &live.runs {
610 if run.research {
611 continue;
612 }
613 if let Some(ref req_id) = run.request {
614 if triggered.insert(req_id.clone()) {
615 if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
616 errors.push(format!("combine trigger failed for {req_id}: {e}"));
617 }
618 }
619 }
620 }
621
622 Ok((live, errors))
623}
624
625fn handle_runs(surface: &Surface, now: u64) -> Response {
626 let (live, errors) = match reconcile_runs(surface, now) {
627 Ok(res) => res,
628 Err(e) => return json_error(500, e),
629 };
630 for msg in errors {
631 surface.session.record_error(&msg);
632 }
633
634 let run_refs: Vec<(&str, Option<&str>)> = live
635 .runs
636 .iter()
637 .map(|run| (run.id.as_str(), run.request.as_deref()))
638 .collect();
639 let combined_ids = match crate::requests::combined_run_ids(&surface.root, &run_refs) {
640 Ok(ids) => ids,
641 Err(e) => return json_error(500, e),
642 };
643
644 let mut runs_with_hold = Vec::with_capacity(live.runs.len());
645 for run in &live.runs {
646 let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
647 Ok(h) => h,
648 Err(e) => return json_error(500, e),
649 };
650 let combined = combined_ids.contains(&run.id);
651 runs_with_hold.push(RunWithHold {
652 run,
653 hold,
654 combined,
655 });
656 }
657
658 let payload = LiveRunsResponse {
659 generated_at: live.generated_at,
660 repo: &live.repo,
661 running: &live.running,
662 runs: runs_with_hold,
663 skipped: &live.skipped,
664 };
665 match serde_json::to_value(&payload) {
666 Ok(val) => Response::json(200, &val),
667 Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
668 }
669}
670
671fn handle_runs_changed(surface: &Surface) -> Response {
672 surface.reconcile_requested.store(true, Ordering::Release);
673 Response::json(202, &serde_json::json!({}))
674}
675
676const NOT_A_GIT_REPO_ERROR: &str = "this folder is not a git repository";
677
678fn require_repository(root: &Path) -> Result<(), Response> {
679 match is_repository(root) {
680 Ok(true) => Ok(()),
681 Ok(false) => Err(json_error(409, NOT_A_GIT_REPO_ERROR)),
682 Err(e) => Err(json_error(500, e)),
683 }
684}
685
686fn handle_run_diff(surface: &Surface, id: &str) -> Response {
687 if let Err(resp) = require_repository(&surface.root) {
688 return resp;
689 }
690 if !is_valid_run_id(id) {
691 return json_error(404, format!("unknown run: {id}"));
692 }
693 let wt_dir = surface.root.join(".wt");
694 let wt = wt_dir.join(id);
695 let start = wt_dir.join(format!("{id}.start.json"));
696 let summary = wt_dir.join(format!("{id}.json"));
697 let report_json = wt_dir.join(format!("{id}.report.json"));
698 let report_md = wt_dir.join(format!("{id}.report.md"));
699 if !wt.exists()
700 && !start.exists()
701 && !summary.exists()
702 && !report_json.exists()
703 && !report_md.exists()
704 {
705 return json_error(404, format!("unknown run: {id}"));
706 }
707 if let Err(err) = crate::requests::run_owner_check(surface, id) {
708 return request_action_error_response(err);
709 }
710 match crate::queue_actions::compute_review(&surface.root, id, true) {
711 Ok(data) => {
712 let body = if !data.wt_exists {
713 "(worktree removed)\n".to_string()
714 } else if data.diff_out.is_empty() {
715 String::new()
716 } else {
717 format!("{}\n", data.diff_out)
718 };
719 Response::text(200, &body)
720 }
721 Err(e) => {
722 if !wt.is_dir() || !wt.join(".git").exists() {
723 json_error(404, e)
724 } else {
725 json_error(500, e)
726 }
727 }
728 }
729}
730
731fn parse_action(raw: &str) -> Result<Action, String> {
732 match raw {
733 "accept" => Ok(Action::Accept),
734 "send_back" => Ok(Action::SendBack),
735 "redo" => Ok(Action::Redo),
736 "hold" => Ok(Action::Hold),
737 "mark_read" => Ok(Action::MarkRead),
738 other => Err(format!(
739 "unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
740 )),
741 }
742}
743
744fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
745 if let Err(resp) = require_repository(&surface.root) {
746 return resp;
747 }
748 let obj = match parse_json_object(&req.body) {
749 Ok(o) => o,
750 Err(resp) => return resp,
751 };
752 let action_str = match obj.get("action") {
753 Some(serde_json::Value::String(s)) => s.clone(),
754 Some(_) => return json_error(400, "field action must be a string"),
755 None => return json_error(400, "missing required field: action"),
756 };
757 let action = match parse_action(&action_str) {
758 Ok(a) => a,
759 Err(e) => return json_error(400, e),
760 };
761 let note = match obj.get("note") {
762 None | Some(serde_json::Value::Null) => None,
763 Some(serde_json::Value::String(s)) => Some(s.clone()),
764 Some(_) => return json_error(400, "field note must be a string or null"),
765 };
766
767 let wt_dir = surface.root.join(".wt");
768 let run_exists = is_valid_run_id(id)
769 && (wt_dir.join(id).exists()
770 || wt_dir.join(format!("{id}.start.json")).exists()
771 || wt_dir.join(format!("{id}.json")).exists()
772 || wt_dir.join(format!("{id}.report.json")).exists()
773 || wt_dir.join(format!("{id}.report.md")).exists());
774 if run_exists {
775 if let Err(err) = crate::requests::run_owner_check(surface, id) {
776 return request_action_error_response(err);
777 }
778 }
779
780 let decision =
781 match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
782 Ok(d) => d,
783 Err(e) => return json_error(400, e),
784 };
785 let seq = match surface.session.record_decision(
786 &decision.run,
787 &action_str,
788 decision.note.as_deref(),
789 decision.conversation_message.as_deref(),
790 ) {
791 Ok(s) => s,
792 Err(e) => return json_error(500, e),
793 };
794 if action == Action::Accept {
795 match crate::requests::run_request_id(&surface.root, &decision.run) {
796 Ok(Some(req_id)) => {
797 if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
798 surface
799 .session
800 .record_error(&format!("combine trigger failed for {req_id}: {e}"));
801 }
802 }
803 Ok(None) => {}
804 Err(e) => return json_error(500, e),
805 }
806 }
807 Response::json(
808 200,
809 &serde_json::json!({
810 "decision": {
811 "run": decision.run,
812 "action": action_str,
813 "note": decision.note,
814 "conversation_message": decision.conversation_message,
815 },
816 "seq": seq,
817 }),
818 )
819}
820
821fn handle_map(surface: &Surface) -> Response {
822 match crate::map::build(&surface.root, &surface.repo) {
823 Ok(data) => match serde_json::to_value(&data) {
824 Ok(val) => Response::json(200, &val),
825 Err(e) => json_error(500, format!("failed to serialize map: {e}")),
826 },
827 Err(e) => json_error(422, e),
828 }
829}
830
831fn handle_requests(surface: &Surface) -> Response {
832 match is_repository(&surface.root) {
833 Ok(true) => {}
834 Ok(false) => return Response::json(200, &serde_json::json!([])),
835 Err(e) => return json_error(500, e),
836 }
837 match crate::requests::list_requests(surface) {
838 Ok(list) => match serde_json::to_value(&list) {
839 Ok(val) => Response::json(200, &val),
840 Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
841 },
842 Err(e) => json_error(500, e),
843 }
844}
845
846fn request_action_error_response(err: RequestActionError) -> Response {
847 match err {
848 RequestActionError::BadRequest(msg) => json_error(400, msg),
849 RequestActionError::NotOwned(msg) => json_error(403, msg),
850 RequestActionError::Conflict(msg) => json_error(409, msg),
851 RequestActionError::Internal(msg) => json_error(500, msg),
852 }
853}
854
855fn handle_request_push(surface: &Surface, id: &str) -> Response {
856 if let Err(resp) = require_repository(&surface.root) {
857 return resp;
858 }
859 match crate::requests::push_request(surface, id) {
860 Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
861 Err(err) => request_action_error_response(err),
862 }
863}
864
865fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
866 if let Err(resp) = require_repository(&surface.root) {
867 return resp;
868 }
869 if let Err(e) = crate::dispatch::validate_request_id(id) {
870 return json_error(400, e);
871 }
872 let obj = match parse_json_object(&req.body) {
873 Ok(o) => o,
874 Err(resp) => return resp,
875 };
876 let title = match obj.get("title") {
877 Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
878 Some(serde_json::Value::String(_)) => {
879 return json_error(400, "field title must not be empty");
880 }
881 Some(_) => return json_error(400, "field title must be a string"),
882 None => return json_error(400, "missing required field: title"),
883 };
884 let body = match obj.get("body") {
885 None | Some(serde_json::Value::Null) => String::new(),
886 Some(serde_json::Value::String(s)) => s.clone(),
887 Some(_) => return json_error(400, "field body must be a string"),
888 };
889 match crate::requests::open_request_pull_request(surface, id, &title, &body) {
890 Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
891 Err(err) => request_action_error_response(err),
892 }
893}
894
895#[derive(Clone, Copy)]
896enum ApiGetHandler {
897 Session,
898 Events,
899 Models,
900 Runs,
901 Requests,
902 Map,
903 RunDiff,
904}
905
906const API_GET_ROUTES: &[(&str, ApiGetHandler)] = &[
907 ("/api/session", ApiGetHandler::Session),
908 ("/api/session/events", ApiGetHandler::Events),
909 ("/api/models", ApiGetHandler::Models),
910 ("/api/runs", ApiGetHandler::Runs),
911 ("/api/requests", ApiGetHandler::Requests),
912 ("/api/map", ApiGetHandler::Map),
913 ("/api/runs/{id}/diff", ApiGetHandler::RunDiff),
914];
915
916pub fn authenticated_api_get_routes() -> Vec<&'static str> {
917 API_GET_ROUTES.iter().map(|(pattern, _)| *pattern).collect()
918}
919
920fn match_api_get_route<'a>(pattern: &str, path: &'a str) -> Option<Option<&'a str>> {
921 if let Some((prefix, suffix)) = pattern.split_once("{id}") {
922 let rest = path.strip_prefix(prefix)?;
923 let id = rest.strip_suffix(suffix)?;
924 if !id.is_empty() && !id.contains('/') {
925 return Some(Some(id));
926 }
927 None
928 } else if pattern == path {
929 Some(None)
930 } else {
931 None
932 }
933}
934
935pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
936 if req.path == "/api/peer/messages" && req.method == "POST" {
937 if !has_valid_message_credential(surface, req) {
938 return json_error(403, "missing or invalid message credential");
939 }
940 return handle_post_peer_message(surface, req);
941 }
942
943 let is_health_get = req.path == "/api/health" && req.method == "GET";
944 if (req.path.starts_with("/api/") || req.method == "POST")
945 && !is_health_get
946 && !has_valid_token(surface, req)
947 {
948 return json_error(
949 403,
950 "missing or invalid surface token; open the page from the URL blyte printed",
951 );
952 }
953
954 if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
955 if req.method != "GET" {
956 return method_not_allowed(req);
957 }
958 return Response {
959 status,
960 content_type,
961 body,
962 };
963 }
964
965 if req.path == "/" || req.path == "/index.html" {
966 if req.method != "GET" {
967 return method_not_allowed(req);
968 }
969 return Response::html(INDEX_HTML.as_bytes().to_vec());
970 }
971
972 if req.path == "/api/health" {
973 if req.method != "GET" {
974 return method_not_allowed(req);
975 }
976 return health_response(surface);
977 }
978
979 for &(pattern, handler) in API_GET_ROUTES {
980 if let Some(id) = match_api_get_route(pattern, &req.path) {
981 if req.method != "GET" {
982 return method_not_allowed(req);
983 }
984 return match handler {
985 ApiGetHandler::Session => session_response(surface),
986 ApiGetHandler::Events => handle_events(surface, req),
987 ApiGetHandler::Models => handle_models(),
988 ApiGetHandler::Runs => handle_runs(surface, now),
989 ApiGetHandler::Requests => handle_requests(surface),
990 ApiGetHandler::Map => handle_map(surface),
991 ApiGetHandler::RunDiff => handle_run_diff(surface, id.unwrap_or("")),
992 };
993 }
994 }
995
996 match req.path.as_str() {
997 "/api/session/messages" => {
998 if req.method != "POST" {
999 return method_not_allowed(req);
1000 }
1001 handle_post_message(surface, req)
1002 }
1003 "/api/session/attachments" => {
1004 if req.method != "POST" {
1005 return method_not_allowed(req);
1006 }
1007 handle_post_attachment(surface, req)
1008 }
1009 "/api/session/model" => {
1010 if req.method != "POST" {
1011 return method_not_allowed(req);
1012 }
1013 handle_post_model(surface, req)
1014 }
1015 "/api/session/effort" => {
1016 if req.method != "POST" {
1017 return method_not_allowed(req);
1018 }
1019 handle_post_effort(surface, req)
1020 }
1021 "/api/runs/changed" => {
1022 if req.method != "POST" {
1023 return method_not_allowed(req);
1024 }
1025 handle_runs_changed(surface)
1026 }
1027 path => {
1028 if let Some(id) = path.strip_prefix("/api/session/attachments/") {
1029 if !id.is_empty() && !id.contains('/') {
1030 if req.method != "GET" {
1031 return method_not_allowed(req);
1032 }
1033 return handle_get_attachment(surface, id);
1034 }
1035 }
1036 if let Some(id) = path.strip_prefix("/api/session/approvals/") {
1037 if !id.is_empty() && !id.contains('/') {
1038 if req.method != "POST" {
1039 return method_not_allowed(req);
1040 }
1041 return handle_post_approval(surface, id, req);
1042 }
1043 }
1044 if let Some(rest) = path.strip_prefix("/api/runs/") {
1045 if let Some(id) = rest.strip_suffix("/decision") {
1046 if !id.is_empty() && !id.contains('/') {
1047 if req.method != "POST" {
1048 return method_not_allowed(req);
1049 }
1050 return handle_run_decision(surface, id, req, now);
1051 }
1052 }
1053 }
1054 if let Some(rest) = path.strip_prefix("/api/requests/") {
1055 if let Some(id) = rest.strip_suffix("/push") {
1056 if req.method != "POST" {
1057 return method_not_allowed(req);
1058 }
1059 return handle_request_push(surface, id);
1060 }
1061 if let Some(id) = rest.strip_suffix("/pull-request") {
1062 if req.method != "POST" {
1063 return method_not_allowed(req);
1064 }
1065 return handle_request_pull_request(surface, id, req);
1066 }
1067 }
1068 json_error(404, format!("not found: {}", req.path))
1069 }
1070 }
1071}
1072
1073enum GitToplevel {
1074 Repository(PathBuf),
1075 NotARepository,
1076}
1077
1078fn find_git_toplevel(dir: &Path) -> Result<GitToplevel, String> {
1079 let out = Command::new("git")
1080 .args(["rev-parse", "--show-toplevel"])
1081 .env("LC_ALL", "C")
1082 .current_dir(dir)
1083 .output()
1084 .map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
1085 if !out.status.success() {
1086 let stderr = String::from_utf8_lossy(&out.stderr);
1087 if stderr.contains("not a git repository (or any") {
1088 return Ok(GitToplevel::NotARepository);
1089 }
1090 let detail = stderr.trim();
1091 if detail.is_empty() {
1092 return Err(format!("not inside a git repository ({})", dir.display()));
1093 }
1094 return Err(format!(
1095 "not inside a git repository ({}): {detail}",
1096 dir.display()
1097 ));
1098 }
1099 let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
1100 if path_str.is_empty() {
1101 return Err(format!("not inside a git repository ({})", dir.display()));
1102 }
1103 Ok(GitToplevel::Repository(PathBuf::from(path_str)))
1104}
1105
1106pub(crate) fn is_repository(root: &Path) -> Result<bool, String> {
1107 match find_git_toplevel(root)? {
1108 GitToplevel::Repository(_) => Ok(true),
1109 GitToplevel::NotARepository => Ok(false),
1110 }
1111}
1112
1113fn resolve_denied_path(denied: &Path) -> Result<PathBuf, String> {
1114 let mut probe = denied;
1115 let mut tail = Vec::new();
1116 loop {
1117 match probe.canonicalize() {
1118 Ok(mut resolved) => {
1119 for part in tail.into_iter().rev() {
1120 resolved.push(part);
1121 }
1122 return Ok(resolved);
1123 }
1124 Err(e)
1125 if matches!(
1126 e.kind(),
1127 std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
1128 ) =>
1129 {
1130 let Some(name) = probe.file_name() else {
1131 return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1132 };
1133 let Some(parent) = probe.parent() else {
1134 return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1135 };
1136 tail.push(name.to_os_string());
1137 probe = parent;
1138 }
1139 Err(e) => {
1140 return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1141 }
1142 }
1143 }
1144}
1145
1146pub fn check_linux_non_repo_root(root: &Path, home: &Path) -> Result<(), String> {
1147 let root_canon = root
1148 .canonicalize()
1149 .map_err(|e| format!("cannot canonicalize {}: {e}", root.display()))?;
1150 let home_canon = home
1151 .canonicalize()
1152 .map_err(|e| format!("cannot canonicalize home directory {}: {e}", home.display()))?;
1153 for denied in blyte_agent::sandbox::read_denied(&home_canon) {
1154 let denied_canon = resolve_denied_path(&denied)?;
1155 if denied.starts_with(&root_canon) || denied_canon.starts_with(&root_canon) {
1156 return Err(format!(
1157 "on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
1158 root_canon.display(),
1159 denied.display()
1160 ));
1161 }
1162 }
1163 if home_canon.starts_with(&root_canon) {
1164 return Err(format!(
1165 "on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
1166 root_canon.display(),
1167 home_canon.display()
1168 ));
1169 }
1170 Ok(())
1171}
1172
1173pub fn check_linux_non_repo_root_for_env(
1174 root: &Path,
1175 home: Option<&std::ffi::OsStr>,
1176) -> Result<(), String> {
1177 let home = home.filter(|h| !h.is_empty()).ok_or_else(|| {
1178 format!(
1179 "cannot check whether {} contains protected paths on Linux: HOME is not set",
1180 root.display()
1181 )
1182 })?;
1183 check_linux_non_repo_root(root, Path::new(home))
1184}
1185
1186fn resolve_main_checkout(worktree_root: &Path) -> Result<PathBuf, String> {
1187 let out = Command::new("git")
1188 .args([
1189 "rev-parse",
1190 "--path-format=absolute",
1191 "--git-dir",
1192 "--git-common-dir",
1193 ])
1194 .current_dir(worktree_root)
1195 .output()
1196 .map_err(|_| {
1197 format!(
1198 "cannot find the main checkout of {}",
1199 worktree_root.display()
1200 )
1201 })?;
1202 if !out.status.success() {
1203 return Err(format!(
1204 "cannot find the main checkout of {}",
1205 worktree_root.display()
1206 ));
1207 }
1208 let text = String::from_utf8_lossy(&out.stdout);
1209 let mut lines = text.lines();
1210 let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
1211 return Err(format!(
1212 "cannot find the main checkout of {}",
1213 worktree_root.display()
1214 ));
1215 };
1216 let git_dir_path = PathBuf::from(git_dir.trim());
1217 let common_dir_path = PathBuf::from(common_dir.trim());
1218 let same_git_dir = match (git_dir_path.canonicalize(), common_dir_path.canonicalize()) {
1219 (Ok(a), Ok(b)) => a == b,
1220 _ => git_dir_path == common_dir_path,
1221 };
1222 if same_git_dir {
1223 return Ok(worktree_root.to_path_buf());
1224 }
1225 crate::config::main_checkout(worktree_root).ok_or_else(|| {
1226 format!(
1227 "cannot find the main checkout of {}",
1228 worktree_root.display()
1229 )
1230 })
1231}
1232
1233fn current_branch(main_checkout: &Path) -> Result<Option<String>, String> {
1234 match find_git_toplevel(main_checkout)? {
1235 GitToplevel::NotARepository => return Ok(None),
1236 GitToplevel::Repository(_) => {}
1237 }
1238 if let Ok(out) = Command::new("git")
1239 .args(["rev-parse", "--abbrev-ref", "HEAD"])
1240 .current_dir(main_checkout)
1241 .output()
1242 {
1243 if out.status.success() {
1244 let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
1245 if !branch.is_empty() {
1246 return Ok(Some(branch));
1247 }
1248 }
1249 }
1250 if let Ok(out) = Command::new("git")
1251 .args(["symbolic-ref", "--short", "HEAD"])
1252 .current_dir(main_checkout)
1253 .output()
1254 {
1255 if out.status.success() {
1256 let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
1257 if !branch.is_empty() {
1258 return Ok(Some(branch));
1259 }
1260 }
1261 }
1262 Err(format!(
1263 "cannot read the current branch of {}",
1264 main_checkout.display()
1265 ))
1266}
1267
1268fn repo_name_for(root: &Path) -> Result<String, String> {
1269 root.file_name()
1270 .and_then(|s| s.to_str())
1271 .filter(|s| !s.is_empty())
1272 .map(String::from)
1273 .ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
1274}
1275
1276fn now_duration() -> Result<Duration, String> {
1277 SystemTime::now()
1278 .duration_since(UNIX_EPOCH)
1279 .map_err(|e| format!("system clock is before Unix epoch: {e}"))
1280}
1281
1282fn new_session_id(nanos: u128) -> String {
1283 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1284 format!("surface-{}-{nanos}-{seq}", std::process::id())
1285}
1286
1287pub fn open_browser(url: &str) {
1288 #[cfg(target_os = "macos")]
1289 let cmd = "open";
1290 #[cfg(not(target_os = "macos"))]
1291 let cmd = "xdg-open";
1292 if let Err(e) = Command::new(cmd).arg(url).spawn() {
1293 eprintln!("blyte: could not open a browser with {cmd}: {e}; open {url} yourself");
1294 }
1295}
1296
1297fn resolve_initial_model(config: &ReplConfig) -> String {
1298 if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
1299 return m.to_string();
1300 }
1301 if let Ok(m) = std::env::var("BLYTE_MODEL") {
1302 if !m.trim().is_empty() {
1303 return m;
1304 }
1305 }
1306 if let Ok(p) = blyte_provider::resolve_provider(None) {
1307 return p.model_id();
1308 }
1309 "gemini-3.8-flash-high".to_string()
1310}
1311
1312#[cfg(unix)]
1313static SIGNAL_STOP: AtomicBool = AtomicBool::new(false);
1314
1315#[cfg(unix)]
1316extern "C" fn handle_shutdown_signal(_: libc::c_int) {
1317 SIGNAL_STOP.store(true, Ordering::Relaxed);
1318}
1319
1320fn ensure_token_dir(dir: &Path) -> Result<(), String> {
1321 #[cfg(unix)]
1322 {
1323 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
1324 if let Some(parent) = dir.parent() {
1325 std::fs::create_dir_all(parent)
1326 .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
1327 }
1328 let mut builder = std::fs::DirBuilder::new();
1329 builder.mode(0o700);
1330 match builder.create(dir) {
1331 Ok(()) => {}
1332 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1333 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
1334 .map_err(|e| format!("cannot set permissions on {}: {e}", dir.display()))?;
1335 }
1336 Err(e) => return Err(format!("cannot create {}: {e}", dir.display())),
1337 }
1338 Ok(())
1339 }
1340 #[cfg(not(unix))]
1341 {
1342 std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))
1343 }
1344}
1345
1346fn write_token_file(token_file_path: &Path, token: &str) -> Result<(), String> {
1347 let token_dir = token_file_path
1348 .parent()
1349 .ok_or_else(|| format!("invalid token path {}", token_file_path.display()))?;
1350 ensure_token_dir(token_dir)?;
1351 let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1352 let tmp_path = token_dir.join(format!(".surface.token.{}.{seq}.tmp", std::process::id()));
1353 let mut opts = std::fs::OpenOptions::new();
1354 opts.write(true).create_new(true);
1355 #[cfg(unix)]
1356 {
1357 opts.mode(0o600);
1358 }
1359 let mut file = opts
1360 .open(&tmp_path)
1361 .map_err(|e| format!("cannot create {}: {e}", token_file_path.display()))?;
1362 if let Err(e) = writeln!(file, "{token}") {
1363 let _ = std::fs::remove_file(&tmp_path);
1364 return Err(format!("cannot write {}: {e}", token_file_path.display()));
1365 }
1366 drop(file);
1367 if let Err(e) = std::fs::rename(&tmp_path, token_file_path) {
1368 let _ = std::fs::remove_file(&tmp_path);
1369 return Err(format!("cannot write {}: {e}", token_file_path.display()));
1370 }
1371 Ok(())
1372}
1373
1374struct TokenFileGuard {
1375 path: PathBuf,
1376}
1377
1378impl Drop for TokenFileGuard {
1379 fn drop(&mut self) {
1380 let _ = std::fs::remove_file(&self.path);
1381 }
1382}
1383
1384struct RegistryEntryGuard {
1385 dir: PathBuf,
1386 id: String,
1387}
1388
1389impl Drop for RegistryEntryGuard {
1390 fn drop(&mut self) {
1391 let _ = crate::surface_registry::remove_entry(&self.dir, &self.id);
1392 }
1393}
1394
1395struct PrivateTmpDirGuard {
1396 path: PathBuf,
1397}
1398
1399impl Drop for PrivateTmpDirGuard {
1400 fn drop(&mut self) {
1401 let _ = std::fs::remove_dir_all(&self.path);
1402 }
1403}
1404
1405struct PublishToolGuard;
1406
1407impl PublishToolGuard {
1408 fn install(surface: Arc<Surface>) -> Self {
1409 blyte_agent::tools::set_publish_tool(Some(Arc::new(
1410 crate::requests::SurfacePublishTool::new(surface),
1411 )));
1412 Self
1413 }
1414}
1415
1416impl Drop for PublishToolGuard {
1417 fn drop(&mut self) {
1418 blyte_agent::tools::set_publish_tool(None);
1419 }
1420}
1421
1422pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
1423 #[cfg(unix)]
1424 {
1425 SIGNAL_STOP.store(false, Ordering::Relaxed);
1426 unsafe {
1427 libc::signal(
1428 libc::SIGINT,
1429 handle_shutdown_signal as *const () as libc::sighandler_t,
1430 );
1431 libc::signal(
1432 libc::SIGTERM,
1433 handle_shutdown_signal as *const () as libc::sighandler_t,
1434 );
1435 }
1436 }
1437 run_inner(
1438 args,
1439 config,
1440 &mut std::io::stdout(),
1441 &mut std::io::stderr(),
1442 &mut open_browser,
1443 || {
1444 #[cfg(unix)]
1445 {
1446 SIGNAL_STOP.load(Ordering::Relaxed)
1447 }
1448 #[cfg(not(unix))]
1449 {
1450 false
1451 }
1452 },
1453 None,
1454 )
1455}
1456
1457pub fn run_with_io(
1458 args: &SurfaceArgs,
1459 config: ReplConfig,
1460 out: &mut dyn Write,
1461 err: &mut dyn Write,
1462) -> i32 {
1463 run_inner(args, config, out, err, &mut open_browser, || false, None)
1464}
1465
1466pub fn run_with_hooks(
1467 args: &SurfaceArgs,
1468 config: ReplConfig,
1469 out: &mut dyn Write,
1470 err: &mut dyn Write,
1471 opener: &mut dyn FnMut(&str),
1472 stop: Arc<AtomicBool>,
1473) -> i32 {
1474 run_inner(
1475 args,
1476 config,
1477 out,
1478 err,
1479 opener,
1480 move || stop.load(Ordering::Relaxed),
1481 None,
1482 )
1483}
1484
1485pub type RunnerFactory = Box<
1486 dyn FnOnce(
1487 &ReplConfig,
1488 Arc<dyn blyte_agent::approval::Approver>,
1489 ) -> Result<(Box<dyn PromptRunner>, Option<PathBuf>), String>,
1490>;
1491
1492pub fn run_with_runner(
1493 args: &SurfaceArgs,
1494 config: ReplConfig,
1495 out: &mut dyn Write,
1496 err: &mut dyn Write,
1497 opener: &mut dyn FnMut(&str),
1498 stop: Arc<AtomicBool>,
1499 runner: Box<dyn PromptRunner>,
1500) -> i32 {
1501 run_inner(
1502 args,
1503 config,
1504 out,
1505 err,
1506 opener,
1507 move || stop.load(Ordering::Relaxed),
1508 Some(Box::new(|_, _| Ok((runner, None)))),
1509 )
1510}
1511
1512pub fn run_with_runner_factory(
1513 args: &SurfaceArgs,
1514 config: ReplConfig,
1515 out: &mut dyn Write,
1516 err: &mut dyn Write,
1517 opener: &mut dyn FnMut(&str),
1518 stop: Arc<AtomicBool>,
1519 factory: RunnerFactory,
1520) -> i32 {
1521 run_inner(
1522 args,
1523 config,
1524 out,
1525 err,
1526 opener,
1527 move || stop.load(Ordering::Relaxed),
1528 Some(factory),
1529 )
1530}
1531
1532struct ReconcileTimerGuard {
1533 stop: Arc<AtomicBool>,
1534 handle: Option<std::thread::JoinHandle<()>>,
1535}
1536
1537impl Drop for ReconcileTimerGuard {
1538 fn drop(&mut self) {
1539 self.stop.store(true, Ordering::Release);
1540 if let Some(handle) = self.handle.take() {
1541 let _ = handle.join();
1542 }
1543 }
1544}
1545
1546fn spawn_reconcile_timer(surface: Arc<Surface>) -> ReconcileTimerGuard {
1547 let stop = Arc::new(AtomicBool::new(false));
1548 let thread_stop = Arc::clone(&stop);
1549 let handle = std::thread::spawn(move || {
1550 let mut after = surface.session.info().last_seq;
1551 let mut next_tick = Instant::now();
1552 let mut seen_errors: HashSet<String> = HashSet::new();
1553 while !thread_stop.load(Ordering::Acquire) {
1554 let wait = if surface.reconcile_requested.load(Ordering::Acquire) {
1555 Duration::ZERO
1556 } else {
1557 next_tick
1558 .saturating_duration_since(Instant::now())
1559 .min(RECONCILE_POLL_WAIT)
1560 };
1561 let entries = surface.session.entries_after(after, wait);
1562 let mut went_idle = false;
1563 for entry in entries {
1564 after = entry.seq;
1565 if matches!(entry.body, EntryBody::Idle { .. }) {
1566 went_idle = true;
1567 }
1568 }
1569 if thread_stop.load(Ordering::Acquire) {
1570 break;
1571 }
1572 let requested = surface.reconcile_requested.swap(false, Ordering::AcqRel);
1573 if went_idle || requested || Instant::now() >= next_tick {
1574 match now_duration().and_then(|d| reconcile_runs(&surface, d.as_secs())) {
1575 Ok((_, errors)) => {
1576 for msg in errors {
1577 if seen_errors.insert(msg.clone()) {
1578 surface.session.record_error(&msg);
1579 eprintln!("blyte: {msg}");
1580 }
1581 }
1582 }
1583 Err(e) => {
1584 if seen_errors.insert(e.clone()) {
1585 eprintln!("blyte: {e}");
1586 }
1587 }
1588 }
1589 next_tick = Instant::now() + RECONCILE_SAFETY_NET_INTERVAL;
1590 }
1591 }
1592 });
1593 ReconcileTimerGuard {
1594 stop,
1595 handle: Some(handle),
1596 }
1597}
1598
1599fn run_inner<S>(
1600 args: &SurfaceArgs,
1601 mut config: ReplConfig,
1602 out: &mut dyn Write,
1603 err: &mut dyn Write,
1604 opener: &mut dyn FnMut(&str),
1605 should_stop: S,
1606 custom_runner: Option<RunnerFactory>,
1607) -> i32
1608where
1609 S: Fn() -> bool,
1610{
1611 let (main_checkout, is_repo) = match find_git_toplevel(&config.repo_root) {
1612 Ok(GitToplevel::Repository(worktree_root)) => {
1613 let main = match resolve_main_checkout(&worktree_root) {
1614 Ok(m) => m,
1615 Err(e) => {
1616 let _ = writeln!(err, "blyte: {e}");
1617 return 1;
1618 }
1619 };
1620 let same_checkout = match (worktree_root.canonicalize(), main.canonicalize()) {
1621 (Ok(a), Ok(b)) => a == b,
1622 _ => worktree_root == main,
1623 };
1624 if !same_checkout {
1625 let _ = writeln!(
1626 err,
1627 "blyte: started in a linked worktree ({}); this surface works in the main checkout {}",
1628 worktree_root.display(),
1629 main.display()
1630 );
1631 let _ = err.flush();
1632 }
1633 (main, true)
1634 }
1635 Ok(GitToplevel::NotARepository) => {
1636 let canonical = match config.repo_root.canonicalize() {
1637 Ok(c) => c,
1638 Err(e) => {
1639 let _ = writeln!(
1640 err,
1641 "blyte: cannot canonicalize {}: {e}",
1642 config.repo_root.display()
1643 );
1644 return 1;
1645 }
1646 };
1647 (canonical, false)
1648 }
1649 Err(e) => {
1650 let _ = writeln!(err, "blyte: {e}");
1651 return 1;
1652 }
1653 };
1654
1655 let repo = match repo_name_for(&main_checkout) {
1656 Ok(r) => r,
1657 Err(e) => {
1658 let _ = writeln!(err, "blyte: {e}");
1659 return 1;
1660 }
1661 };
1662
1663 #[cfg(target_os = "linux")]
1664 if !is_repo {
1665 if let Err(e) =
1666 check_linux_non_repo_root_for_env(&main_checkout, std::env::var_os("HOME").as_deref())
1667 {
1668 let _ = writeln!(err, "blyte: {e}");
1669 return 1;
1670 }
1671 }
1672
1673 let state_dir = match crate::surface_registry::state_dir() {
1674 Ok(d) => d,
1675 Err(e) => {
1676 let _ = writeln!(err, "blyte: {e}");
1677 return 1;
1678 }
1679 };
1680 let registry_dir = state_dir.join("surfaces");
1681
1682 let all_records =
1683 match crate::surface_dir::list_records_for_root(&main_checkout, Some(&state_dir)) {
1684 Ok(r) => r,
1685 Err(e) => {
1686 let _ = writeln!(err, "blyte: {e}");
1687 return 1;
1688 }
1689 };
1690 let mut running = Vec::new();
1691 let mut stopped = Vec::new();
1692 for located in all_records {
1693 if crate::surface_dir::is_running(&located.record) {
1694 running.push(located);
1695 } else {
1696 stopped.push(located);
1697 }
1698 }
1699
1700 let live_registry = match crate::surface_registry::live_entries(®istry_dir) {
1701 Ok(entries) => entries,
1702 Err(e) => {
1703 let _ = writeln!(err, "blyte: {e}");
1704 return 1;
1705 }
1706 };
1707 let mut running_names: Vec<String> = running.iter().map(|r| r.record.name.clone()).collect();
1708 for entry in &live_registry {
1709 if !running_names.iter().any(|n| n == &entry.name) {
1710 running_names.push(entry.name.clone());
1711 }
1712 }
1713
1714 let (surface_id, surface_name, surface_record_dir) = if let Some(ref target) = args.resume {
1715 if let Some(located) = running
1716 .iter()
1717 .find(|r| r.record.id == *target || r.record.name == *target)
1718 {
1719 let _ = writeln!(
1720 err,
1721 "blyte: surface {target} is already running (port {})",
1722 located.record.port
1723 );
1724 return 1;
1725 }
1726 let stopped_matches: Vec<&crate::surface_dir::LocatedRecord> = stopped
1727 .iter()
1728 .filter(|r| r.record.id == *target || r.record.name == *target)
1729 .collect();
1730 if stopped_matches.is_empty() {
1731 let _ = writeln!(
1732 err,
1733 "blyte: no stopped surface named {target} in {}",
1734 main_checkout.display()
1735 );
1736 return 1;
1737 }
1738 if stopped_matches.len() > 1 {
1739 let ids: Vec<&str> = stopped_matches
1740 .iter()
1741 .map(|r| r.record.id.as_str())
1742 .collect();
1743 let _ = writeln!(
1744 err,
1745 "blyte: more than one stopped surface is named {target}; resume by id: {}",
1746 ids.join(", ")
1747 );
1748 return 1;
1749 }
1750 let located = stopped_matches[0];
1751 if running_names.iter().any(|n| n == &located.record.name) {
1752 let _ = writeln!(
1753 err,
1754 "blyte: a running surface is already named {}; stop it or resume by another name",
1755 located.record.name
1756 );
1757 return 1;
1758 }
1759 (
1760 located.record.id.clone(),
1761 located.record.name.clone(),
1762 located.dir.clone(),
1763 )
1764 } else {
1765 let id = match crate::surface_dir::new_surface_id() {
1766 Ok(id) => id,
1767 Err(e) => {
1768 let _ = writeln!(err, "blyte: {e}");
1769 return 1;
1770 }
1771 };
1772 let name = match crate::surface_dir::pick_name(&repo, args.name.as_deref(), &running_names)
1773 {
1774 Ok(name) => name,
1775 Err(e) => {
1776 let _ = writeln!(err, "blyte: {e}");
1777 return 1;
1778 }
1779 };
1780 let record_dir = if is_repo {
1781 crate::surface_dir::surface_dir(&main_checkout, &id)
1782 } else {
1783 let store = match crate::surface_dir::folder_store(&state_dir, &main_checkout) {
1784 Ok(store) => store,
1785 Err(e) => {
1786 let _ = writeln!(err, "blyte: {e}");
1787 return 1;
1788 }
1789 };
1790 store.join("surfaces").join(&id)
1791 };
1792 (id, name, record_dir)
1793 };
1794
1795 let branch = match current_branch(&main_checkout) {
1796 Ok(b) => b,
1797 Err(e) => {
1798 let _ = writeln!(err, "blyte: {e}");
1799 return 1;
1800 }
1801 };
1802
1803 if !config.converse {
1804 config.converse = true;
1805 if config.max_turns == 25 || config.max_turns == 60 {
1806 config.max_turns = 1000;
1807 }
1808 if config.fold_budget.is_none() {
1809 config.fold_budget = Some(100_000);
1810 }
1811 }
1812 config.repo_root = main_checkout.clone();
1813
1814 let started_dur = match now_duration() {
1815 Ok(d) => d,
1816 Err(e) => {
1817 let _ = writeln!(err, "blyte: {e}");
1818 return 1;
1819 }
1820 };
1821 let started_at = started_dur.as_secs();
1822 let session_id = new_session_id(started_dur.as_nanos());
1823 if std::env::var("BLYTE_SESSION")
1824 .map(|v| v.is_empty())
1825 .unwrap_or(true)
1826 {
1827 std::env::set_var("BLYTE_SESSION", &session_id);
1828 }
1829
1830 let token = match generate_token() {
1831 Ok(t) => t,
1832 Err(e) => {
1833 let _ = writeln!(err, "blyte: {e}");
1834 return 1;
1835 }
1836 };
1837 let message_credential = match generate_token() {
1838 Ok(t) => t,
1839 Err(e) => {
1840 let _ = writeln!(err, "blyte: {e}");
1841 return 1;
1842 }
1843 };
1844
1845 let bind_addr = format!("127.0.0.1:{}", args.port);
1846 let listener = match TcpListener::bind(&bind_addr) {
1847 Ok(l) => l,
1848 Err(e) => {
1849 let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
1850 return 1;
1851 }
1852 };
1853 let actual_port = match listener.local_addr() {
1854 Ok(a) => a.port(),
1855 Err(e) => {
1856 let _ = writeln!(err, "blyte: failed to read listener address: {e}");
1857 return 1;
1858 }
1859 };
1860
1861 let token_file_path = match blyte_agent::sandbox::surface_token_path_for_id(&surface_id) {
1862 Ok(p) => p,
1863 Err(e) => {
1864 let _ = writeln!(err, "blyte: {e}");
1865 return 1;
1866 }
1867 };
1868 if let Err(e) = write_token_file(&token_file_path, &token) {
1869 let _ = writeln!(err, "blyte: {e}");
1870 return 1;
1871 }
1872 let _token_guard = TokenFileGuard {
1873 path: token_file_path,
1874 };
1875
1876 let message_file_path = match blyte_agent::sandbox::surface_message_path_for_id(&surface_id) {
1877 Ok(p) => p,
1878 Err(e) => {
1879 let _ = writeln!(err, "blyte: {e}");
1880 return 1;
1881 }
1882 };
1883 if let Err(e) = write_token_file(&message_file_path, &message_credential) {
1884 let _ = writeln!(err, "blyte: {e}");
1885 return 1;
1886 }
1887 let _message_guard = TokenFileGuard {
1888 path: message_file_path,
1889 };
1890
1891 let record = SurfaceRecord {
1894 id: surface_id.clone(),
1895 name: surface_name.clone(),
1896 pid: std::process::id(),
1897 port: actual_port,
1898 session_id: session_id.clone(),
1899 started_at,
1900 };
1901 if let Err(e) = crate::surface_dir::write_record_in(&surface_record_dir, &record) {
1902 let _ = writeln!(err, "blyte: {e}");
1903 return 1;
1904 }
1905 let attachments_dir = match prepare_attachments_dir(&surface_record_dir) {
1906 Ok(p) => p,
1907 Err(e) => {
1908 let _ = writeln!(err, "blyte: {e}");
1909 return 1;
1910 }
1911 };
1912 let mut read_roots = blyte_agent::tools::read_roots();
1913 if !read_roots.iter().any(|p| p == &attachments_dir) {
1914 read_roots.push(attachments_dir.clone());
1915 blyte_agent::tools::set_read_roots(read_roots);
1916 }
1917 if !config.allow_read.iter().any(|p| p == &attachments_dir) {
1918 config.allow_read.push(attachments_dir);
1919 }
1920 let registry_entry = crate::surface_registry::RegistryEntry {
1921 id: surface_id.clone(),
1922 name: surface_name.clone(),
1923 root: main_checkout.clone(),
1924 branch,
1925 pid: std::process::id(),
1926 port: actual_port,
1927 started_at,
1928 doing: "idle".to_string(),
1929 };
1930 if let Err(e) = crate::surface_registry::write_entry(®istry_dir, ®istry_entry) {
1931 let _ = writeln!(err, "blyte: {e}");
1932 return 1;
1933 }
1934 let _registry_guard = RegistryEntryGuard {
1935 dir: registry_dir.clone(),
1936 id: surface_id.clone(),
1937 };
1938 blyte_agent::tools::set_peer_tools(Some(Arc::new(crate::tell::SurfacePeerTools {
1939 registry_dir: registry_dir.clone(),
1940 surface_id: surface_id.clone(),
1941 surface_name: surface_name.clone(),
1942 repository: repo.clone(),
1943 })));
1944 let entries_log_path = surface_record_dir.join("entries.jsonl");
1945 blyte_agent::tools::set_blyte_surface(Some(surface_id.clone()));
1946 let model = resolve_initial_model(&config);
1947 let mut _private_tmp_guard: Option<PrivateTmpDirGuard> = None;
1948 let session =
1949 match Session::try_start_with_log_io(model, Some(entries_log_path), err, |approver| {
1950 match custom_runner {
1951 Some(factory) => {
1952 let (runner, tmpdir) = factory(&config, approver)?;
1953 _private_tmp_guard = tmpdir.map(|path| PrivateTmpDirGuard { path });
1954 Ok(runner)
1955 }
1956 None => {
1957 let runner = AgentRunner::try_new(&config, approver)?;
1958 _private_tmp_guard = runner.private_tmpdir().map(|path| PrivateTmpDirGuard {
1959 path: path.to_path_buf(),
1960 });
1961 Ok(Box::new(runner) as Box<dyn crate::session::PromptRunner>)
1962 }
1963 }
1964 }) {
1965 Ok(s) => s,
1966 Err(e) => {
1967 let _ = writeln!(err, "blyte: {e}");
1968 let _ = err.flush();
1969 return 1;
1970 }
1971 };
1972 let hook_dir = registry_dir.clone();
1973 let hook_entry = registry_entry.clone();
1974 session.set_activity_hook(Box::new(move |prompt| {
1975 let doing = match prompt {
1976 Some(text) => {
1977 let line = crate::surface_registry::first_line(text);
1978 if line.is_empty() {
1979 "working".to_string()
1980 } else {
1981 line
1982 }
1983 }
1984 None => "idle".to_string(),
1985 };
1986 let branch = match current_branch(&hook_entry.root) {
1989 Ok(b) => b,
1990 Err(e) => {
1991 eprintln!("blyte: {e}");
1992 return;
1993 }
1994 };
1995 let entry = crate::surface_registry::RegistryEntry {
1996 branch,
1997 doing,
1998 ..hook_entry.clone()
1999 };
2000 if let Err(e) = crate::surface_registry::write_entry(&hook_dir, &entry) {
2001 eprintln!("blyte: {e}");
2002 }
2003 }));
2004
2005 if !is_repo {
2006 let _ = writeln!(
2007 err,
2008 "blyte: {} is not a git repository: runs, combining and publishing are off until it is one",
2009 main_checkout.display()
2010 );
2011 let _ = err.flush();
2012 }
2013
2014 let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
2015 let _ = writeln!(out, "blyte: surface {surface_name} at {url}");
2016 let _ = out.flush();
2017 if !args.no_open {
2018 opener(&url);
2019 }
2020
2021 let surface = Arc::new(Surface {
2022 surface_id,
2023 surface_name,
2024 root: main_checkout,
2025 repo,
2026 session,
2027 session_id,
2028 started_at,
2029 days: args.days,
2030 token,
2031 message_credential,
2032 requests: Arc::new(RequestsState::new()),
2033 publisher: Arc::new(RealPublisher),
2034 reconcile_lock: Mutex::new(()),
2035 reconcile_requested: AtomicBool::new(false),
2036 });
2037
2038 let timer_guard = spawn_reconcile_timer(Arc::clone(&surface));
2039 let _publish_tool_guard = PublishToolGuard::install(Arc::clone(&surface));
2040
2041 let serve_result =
2042 crate::http::serve_until(listener, should_stop, move |req| match now_duration() {
2043 Ok(d) => route(&surface, req, d.as_secs()),
2044 Err(e) => json_error(500, e),
2045 });
2046
2047 drop(_publish_tool_guard);
2048 drop(timer_guard);
2049
2050 match serve_result {
2051 Ok(()) => 0,
2052 Err(e) => {
2053 let _ = writeln!(err, "blyte: server error: {e}");
2054 1
2055 }
2056 }
2057}
2058
2059fn canonicalize_attachments_dir(attachments_dir: &Path) -> Result<PathBuf, String> {
2060 std::fs::canonicalize(attachments_dir).map_err(|e| {
2061 format!(
2062 "failed to canonicalize attachments directory {}: {e}",
2063 attachments_dir.display()
2064 )
2065 })
2066}
2067
2068fn prepare_attachments_dir(surface_record_dir: &Path) -> Result<PathBuf, String> {
2069 let attachments_dir = crate::attachments::attachments_dir(surface_record_dir);
2070 std::fs::create_dir_all(&attachments_dir)
2071 .map_err(|e| format!("failed to create {}: {e}", attachments_dir.display()))?;
2072 canonicalize_attachments_dir(&attachments_dir)
2073}
2074
2075#[cfg(test)]
2076mod tests {
2077 use super::*;
2078
2079 #[test]
2080 fn canonicalize_attachments_dir_errors_when_missing() {
2081 let dir = tempfile::tempdir().unwrap();
2082 let missing = dir.path().join("does-not-exist").join("attachments");
2083 let err = canonicalize_attachments_dir(&missing).unwrap_err();
2084 assert!(
2085 err.contains(&missing.display().to_string()),
2086 "expected error to name missing path, got: {err}"
2087 );
2088 assert!(err.contains("canonicalize"), "unexpected error: {err}");
2089 }
2090
2091 #[cfg(unix)]
2092 #[test]
2093 fn canonicalize_attachments_dir_errors_on_dangling_symlink() {
2094 let dir = tempfile::tempdir().unwrap();
2095 let dangling = dir.path().join("attachments");
2096 std::os::unix::fs::symlink(dir.path().join("missing-target"), &dangling).unwrap();
2097 let err = canonicalize_attachments_dir(&dangling).unwrap_err();
2098 assert!(
2099 err.contains(&dangling.display().to_string()),
2100 "expected error to name symlink path, got: {err}"
2101 );
2102 assert!(err.contains("canonicalize"), "unexpected error: {err}");
2103 }
2104
2105 #[test]
2106 fn prepare_attachments_dir_errors_when_attachments_path_is_a_file() {
2107 let dir = tempfile::tempdir().unwrap();
2108 let blocker = crate::attachments::attachments_dir(dir.path());
2109 std::fs::write(&blocker, b"not a dir").unwrap();
2110 let err = prepare_attachments_dir(dir.path()).unwrap_err();
2111 assert!(
2112 err.contains(&blocker.display().to_string()),
2113 "expected error to name path, got: {err}"
2114 );
2115 }
2116}