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