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