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