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