use serde::Serialize;
use std::collections::{BTreeSet, HashSet, VecDeque};
use std::io::{Read, Write};
use std::net::TcpListener;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use crate::cli::SurfaceArgs;
use crate::http::{Request, Response};
use crate::open_window::OpenIn;
use crate::queue_actions::{Action, Hold};
use crate::repl::ReplConfig;
use crate::requests::{Publisher, RealPublisher, RequestActionError, RequestsState};
use crate::session::{
AgentRunner, AnswerError, ApprovalAnswer, Attachment, EntryBody, PeerDelivery, PromptRunner,
Session,
};
use crate::surface_dir::SurfaceRecord;
pub const TOKEN_HEADER: &str = "X-Blyte-Token";
pub const MESSAGE_HEADER: &str = "X-Blyte-Message-Credential";
pub const RECONCILE_SAFETY_NET_INTERVAL: Duration = Duration::from_secs(30);
pub const OPEN_CODE_TTL_SECS: u64 = 60;
pub const MAX_OPEN_CODES: usize = 16;
const INDEX_HTML: &str = include_str!("../assets/surface/index.html");
const USAGE_HTML: &str = include_str!("../assets/usage/index.html");
const MAX_WAIT_MS: u64 = 25_000;
const RECONCILE_POLL_WAIT: Duration = Duration::from_millis(50);
const TOKEN_BYTES: usize = 32;
const MAX_PEER_TEXT_BYTES: usize = 16_384;
const MAX_PEER_REPO_CHARS: usize = 200;
static SESSION_COUNTER: AtomicU64 = AtomicU64::new(1);
struct OpenCodeEntry {
code: String,
created_at: u64,
}
#[derive(Default)]
pub struct OpenCodes {
entries: Mutex<VecDeque<OpenCodeEntry>>,
}
impl OpenCodes {
pub fn new() -> Self {
Self {
entries: Mutex::new(VecDeque::new()),
}
}
pub fn issue(&self, now: u64) -> Result<String, String> {
let code = generate_token()?;
let mut entries = self
.entries
.lock()
.map_err(|e| format!("open codes lock poisoned: {e}"))?;
while entries.len() >= MAX_OPEN_CODES {
entries.pop_front();
}
entries.push_back(OpenCodeEntry {
code: code.clone(),
created_at: now,
});
Ok(code)
}
pub fn redeem(&self, provided: &str, now: u64) -> Result<bool, String> {
if provided.is_empty() {
return Ok(false);
}
let mut entries = self
.entries
.lock()
.map_err(|e| format!("open codes lock poisoned: {e}"))?;
let mut matched_idx = None;
for (idx, entry) in entries.iter().enumerate() {
if constant_time_eq(provided.as_bytes(), entry.code.as_bytes()) {
matched_idx = Some(idx);
}
}
let Some(idx) = matched_idx else {
entries.retain(|e| now.saturating_sub(e.created_at) <= OPEN_CODE_TTL_SECS);
return Ok(false);
};
let entry = entries.remove(idx).unwrap();
entries.retain(|e| now.saturating_sub(e.created_at) <= OPEN_CODE_TTL_SECS);
Ok(now.saturating_sub(entry.created_at) <= OPEN_CODE_TTL_SECS)
}
}
pub struct Surface {
pub surface_id: String,
pub surface_name: String,
pub root: PathBuf,
pub repo: String,
pub session: Session,
pub session_id: String,
pub started_at: u64,
pub runtime: crate::surface_version::SurfaceRuntimeInfo,
pub days: u64,
pub token: String,
pub message_credential: String,
pub open_codes: OpenCodes,
pub requests: Arc<RequestsState>,
pub publisher: Arc<dyn Publisher>,
pub reconcile_lock: Mutex<()>,
pub reconcile_requested: AtomicBool,
}
pub fn generate_token() -> Result<String, String> {
let mut bytes = [0u8; TOKEN_BYTES];
let mut file = std::fs::File::open("/dev/urandom")
.map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
file.read_exact(&mut bytes)
.map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push(HEX[(byte >> 4) as usize] as char);
out.push(HEX[(byte & 0x0f) as usize] as char);
}
Ok(out)
}
pub fn constant_time_eq(provided: &[u8], expected: &[u8]) -> bool {
let mut diff = provided.len() ^ expected.len();
for (i, &exp) in expected.iter().enumerate() {
let prov = provided.get(i).copied().unwrap_or(0);
diff |= usize::from(prov ^ exp);
}
std::hint::black_box(diff) == 0
}
fn has_valid_token(surface: &Surface, req: &Request) -> bool {
if surface.token.is_empty() {
return false;
}
let mut values = req.header_values(TOKEN_HEADER);
let Some(provided) = values.next() else {
return false;
};
if values.next().is_some() {
return false;
}
constant_time_eq(provided.as_bytes(), surface.token.as_bytes())
}
fn has_valid_message_credential(surface: &Surface, req: &Request) -> bool {
if surface.message_credential.is_empty() {
return false;
}
let mut values = req.header_values(MESSAGE_HEADER);
let Some(provided) = values.next() else {
return false;
};
if values.next().is_some() {
return false;
}
constant_time_eq(provided.as_bytes(), surface.message_credential.as_bytes())
}
#[derive(Serialize)]
struct RunWithHold<'a> {
#[serde(flatten)]
run: &'a crate::replay::Run,
hold: Option<Hold>,
combined: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
in_place: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
undone: bool,
}
#[derive(Serialize)]
struct LiveRunsResponse<'a> {
generated_at: u64,
repo: &'a str,
running: &'a [crate::live_runs::RunningRun],
runs: Vec<RunWithHold<'a>>,
skipped: &'a [crate::replay::Skipped],
}
fn json_error(status: u16, msg: impl Into<String>) -> Response {
Response::json(status, &serde_json::json!({ "error": msg.into() }))
}
fn method_not_allowed(req: &Request) -> Response {
json_error(
405,
format!("method {} not allowed for {}", req.method, req.path),
)
}
fn is_valid_run_id(id: &str) -> bool {
!id.is_empty()
&& id != "."
&& id != ".."
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
}
fn parse_json_object(body: &[u8]) -> Result<serde_json::Map<String, serde_json::Value>, Response> {
let val: serde_json::Value = serde_json::from_slice(body)
.map_err(|e| json_error(400, format!("invalid JSON body: {e}")))?;
val.as_object()
.cloned()
.ok_or_else(|| json_error(400, "request body must be a JSON object"))
}
fn handle_surfaces(surface: &Surface) -> Response {
let state_dir = match crate::surface_registry::state_dir() {
Ok(dir) => dir,
Err(e) => return json_error(500, e),
};
let registry_dir = state_dir.join("surfaces");
let stopped = match crate::surfaces_cmd::stopped_surfaces(&surface.root, &state_dir) {
Ok(stopped) => stopped,
Err(e) => return json_error(500, e),
};
match crate::surfaces_cmd::surfaces_payload(
®istry_dir,
&state_dir,
&surface.surface_id,
&stopped,
) {
Ok(payload) => Response::json(200, &payload),
Err(e) => json_error(500, e),
}
}
fn handle_post_start_surface(req: &Request) -> Response {
let obj = match parse_json_object(&req.body) {
Ok(o) => o,
Err(resp) => return resp,
};
let Some(folder) = obj.get("folder").and_then(|v| v.as_str()) else {
return json_error(400, "missing or invalid field folder");
};
let state_dir = match crate::surface_registry::state_dir() {
Ok(dir) => dir,
Err(e) => return json_error(500, e),
};
match crate::surface_start::start_surface_in(folder, &state_dir) {
Ok(started) => Response::json(
200,
&serde_json::json!({
"name": started.name,
"url": started.url,
}),
),
Err(crate::surface_start::StartError::BadRequest(msg)) => json_error(400, msg),
Err(crate::surface_start::StartError::Internal(msg)) => json_error(500, msg),
}
}
pub const RELOAD_REUSE_TOKEN_ENV: &str = "BLYTE_RELOAD_REUSE_TOKEN";
type StopTrigger = Arc<dyn Fn() + Send + Sync>;
struct ReloadTrigger {
requested: Arc<AtomicBool>,
stop: StopTrigger,
}
fn handle_post_stop(stop_trigger: Option<&StopTrigger>) -> Response {
if let Some(trigger) = stop_trigger {
let trigger = Arc::clone(trigger);
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(50));
trigger();
});
}
Response::json(202, &serde_json::json!({ "stopping": true }))
}
fn handle_post_reload(surface: &Surface, reload_trigger: Option<&ReloadTrigger>) -> Response {
if surface.session.info().busy {
return json_error(409, "cannot reload while a turn is in progress");
}
if let Err(e) = surface.runtime.verify_executable() {
return json_error(500, e);
}
if let Some(trigger) = reload_trigger {
if trigger.requested.swap(true, Ordering::SeqCst) {
return json_error(409, "reload is already in progress");
}
let stop = Arc::clone(&trigger.stop);
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(50));
stop();
});
}
Response::json(200, &serde_json::json!({ "reloading": true }))
}
fn health_response(surface: &Surface) -> Response {
Response::json(
200,
&serde_json::json!({
"surface_id": surface.surface_id,
"surface_name": surface.surface_name,
"session_id": surface.session_id,
}),
)
}
fn session_response(surface: &Surface) -> Response {
let info = surface.session.info();
let repository = match is_repository(&surface.root) {
Ok(v) => v,
Err(e) => return json_error(500, e),
};
let stale = match surface.runtime.is_stale() {
Ok(v) => v,
Err(e) => return json_error(500, e),
};
Response::json(
200,
&serde_json::json!({
"session_id": surface.session_id,
"surface_name": surface.surface_name,
"repo": surface.repo,
"repository": repository,
"started_at": surface.started_at,
"version": surface.runtime.version,
"boot_id": surface.runtime.boot_id,
"stale": stale,
"model": info.model,
"effort": info.effort,
"effort_supported": info.effort_supported,
"busy": info.busy,
"queued": info.queued,
"last_seq": info.last_seq,
"state": info.state,
}),
)
}
fn handle_events(surface: &Surface, req: &Request) -> Response {
let after_raw = match req.query_value("after") {
Some(v) => v,
None => return json_error(400, "missing required query parameter: after"),
};
let after = match after_raw.parse::<u64>() {
Ok(v) => v,
Err(_) => {
return json_error(
400,
format!("query parameter after must be a non-negative integer, got '{after_raw}'"),
);
}
};
let wait_ms = match req.query_value("wait_ms") {
None => 0,
Some(raw) => match raw.parse::<u64>() {
Ok(v) if v <= MAX_WAIT_MS => v,
Ok(v) => {
return json_error(
400,
format!("query parameter wait_ms must be at most {MAX_WAIT_MS}, got {v}"),
);
}
Err(_) => {
return json_error(
400,
format!("query parameter wait_ms must be a non-negative integer, got '{raw}'"),
);
}
},
};
let entries = surface
.session
.entries_after(after, Duration::from_millis(wait_ms));
let last_seq = surface.session.info().last_seq;
Response::json(
200,
&serde_json::json!({
"entries": entries,
"last_seq": last_seq,
}),
)
}
fn handle_usage(req: &Request, now: u64) -> Response {
let since = match req.query_value("since") {
None => None,
Some(raw) => {
let parsed = if raw.bytes().all(|b| b.is_ascii_digit()) {
raw.parse::<u64>().ok()
} else {
None
};
match parsed {
Some(ts) => Some(ts),
None => return json_error(400, format!("since must be unix seconds, got {raw}")),
}
}
};
let Some(log_path) = crate::usage_log::default_path() else {
return json_error(404, "the usage log is switched off (BLYTE_USAGE_LOG=off)");
};
match crate::usage_report::build(&log_path, since, now) {
Ok(report) => match serde_json::to_value(&report) {
Ok(value) => Response::json(200, &value),
Err(err) => json_error(500, format!("failed to serialise usage report: {err}")),
},
Err(err) => json_error(500, err),
}
}
fn handle_post_message(surface: &Surface, req: &Request) -> Response {
let obj = match parse_json_object(&req.body) {
Ok(o) => o,
Err(resp) => return resp,
};
let attachment_ids: Vec<String> = match obj.get("attachments") {
None | Some(serde_json::Value::Null) => Vec::new(),
Some(serde_json::Value::Array(arr)) => {
let mut ids = Vec::with_capacity(arr.len());
for item in arr {
match item.as_str() {
Some(s) => ids.push(s.to_string()),
None => {
return json_error(400, "field attachments must be an array of strings");
}
}
}
ids
}
Some(_) => return json_error(400, "field attachments must be an array of strings"),
};
let text = match obj.get("text") {
Some(serde_json::Value::String(s)) => s.clone(),
Some(serde_json::Value::Null) | None if !attachment_ids.is_empty() => String::new(),
Some(_) => return json_error(400, "field text must be a string"),
None => return json_error(400, "missing required field: text"),
};
let report_ids: Vec<String> = match obj.get("reports") {
None | Some(serde_json::Value::Null) => Vec::new(),
Some(serde_json::Value::Array(arr)) => {
let mut ids = Vec::with_capacity(arr.len());
for item in arr {
match item.as_str() {
Some(s) => ids.push(s.to_string()),
None => return json_error(400, "field reports must be an array of strings"),
}
}
ids
}
Some(_) => return json_error(400, "field reports must be an array of strings"),
};
let pastes: Vec<crate::session::Paste> = match obj.get("pastes") {
None | Some(serde_json::Value::Null) => Vec::new(),
Some(serde_json::Value::Array(arr)) => {
let mut out = Vec::with_capacity(arr.len());
for item in arr {
match serde_json::from_value::<crate::session::Paste>(item.clone()) {
Ok(p) => out.push(p),
Err(e) => return json_error(400, format!("invalid paste entry: {e}")),
}
}
out
}
Some(_) => return json_error(400, "field pastes must be an array"),
};
let mut report_attachments = Vec::with_capacity(report_ids.len());
for id in report_ids {
let path = surface.root.join(".wt").join(format!("{id}.report.md"));
if !is_valid_run_id(&id) {
return json_error(
400,
format!("invalid report run id '{id}' (path: {})", path.display()),
);
}
match std::fs::read_to_string(&path) {
Ok(body) => report_attachments.push(Attachment {
run: id,
text: body,
}),
Err(e) => {
return json_error(
400,
format!(
"cannot read report for run '{id}' at {}: {e}",
path.display()
),
);
}
}
}
let mut file_attachments = Vec::with_capacity(attachment_ids.len());
if !attachment_ids.is_empty() {
let Some(record_dir) = surface.session.attachments_root() else {
return json_error(500, "attachments directory is not configured");
};
for id in attachment_ids {
match crate::attachments::load_with_path(&record_dir, &id) {
Ok((meta, path, _)) => {
file_attachments.push(crate::session::QueuedAttachment { meta, path })
}
Err(e) => return json_error(400, e),
}
}
}
match surface.session.submit_with_attachments(
&text,
report_attachments,
file_attachments,
pastes,
) {
Ok(seq) => Response::json(200, &serde_json::json!({ "seq": seq })),
Err(e) => json_error(400, e),
}
}
fn handle_post_attachment(surface: &Surface, req: &Request) -> Response {
let Some(raw_name) = req
.query_value("name")
.map(str::trim)
.filter(|s| !s.is_empty())
else {
return json_error(400, "missing required query parameter: name");
};
if req.body.len() > crate::attachments::MAX_ATTACHMENT_BYTES {
return Response::text(
413,
&format!("{raw_name} is larger than the 10 MiB limit for one file"),
);
}
if req.body.is_empty() {
return json_error(400, format!("{raw_name} is empty"));
}
let Some(record_dir) = surface.session.attachments_root() else {
return json_error(500, "attachments directory is not configured");
};
match crate::attachments::store(&record_dir, raw_name, &req.body) {
Ok(meta) => match serde_json::to_value(&meta) {
Ok(v) => Response::json(200, &v),
Err(e) => json_error(500, format!("failed to serialise attachment metadata: {e}")),
},
Err(e) => json_error(400, e),
}
}
fn handle_get_attachment(surface: &Surface, id: &str) -> Response {
let Some(record_dir) = surface.session.attachments_root() else {
return json_error(500, "attachments directory is not configured");
};
match crate::attachments::load(&record_dir, id) {
Ok((_meta, bytes)) => {
let content_type =
crate::attachments::detect_image(&bytes).unwrap_or("application/octet-stream");
Response::bytes(200, content_type, bytes)
}
Err(e) => json_error(404, e),
}
}
fn handle_post_peer_message(surface: &Surface, req: &Request) -> Response {
let obj = match parse_json_object(&req.body) {
Ok(o) => o,
Err(resp) => return resp,
};
for key in obj.keys() {
if !matches!(key.as_str(), "from_name" | "from_repository" | "text") {
return json_error(400, format!("unexpected field: {key}"));
}
}
let from_name = match obj.get("from_name") {
Some(serde_json::Value::String(s)) => s.clone(),
Some(_) => return json_error(400, "field from_name must be a string"),
None => return json_error(400, "missing required field: from_name"),
};
if let Err(e) = crate::surface_dir::validate_surface_name(&from_name) {
return json_error(400, format!("invalid from_name: {e}"));
}
let from_repository = match obj.get("from_repository") {
Some(serde_json::Value::String(s)) => s.clone(),
Some(_) => return json_error(400, "field from_repository must be a string"),
None => return json_error(400, "missing required field: from_repository"),
};
let repo_chars = from_repository.chars().count();
if repo_chars == 0 || repo_chars > MAX_PEER_REPO_CHARS {
return json_error(
400,
format!("field from_repository must be 1 to {MAX_PEER_REPO_CHARS} characters"),
);
}
if from_repository.chars().any(char::is_control) {
return json_error(
400,
"field from_repository must not contain control characters",
);
}
let text = match obj.get("text") {
Some(serde_json::Value::String(s)) => s.clone(),
Some(_) => return json_error(400, "field text must be a string"),
None => return json_error(400, "missing required field: text"),
};
if text.trim().is_empty() {
return json_error(400, "field text must not be blank");
}
if text.len() > MAX_PEER_TEXT_BYTES {
return json_error(
400,
format!("field text must be at most {MAX_PEER_TEXT_BYTES} bytes"),
);
}
match surface
.session
.submit_peer(&from_name, &from_repository, &text)
{
Ok(PeerDelivery::Delivered) => {
Response::json(200, &serde_json::json!({ "status": "delivered" }))
}
Ok(PeerDelivery::Held) => Response::json(200, &serde_json::json!({ "status": "held" })),
Err(e) => json_error(400, e),
}
}
fn handle_models() -> Response {
let discovered = blyte_provider::discover_all_models();
let mut models = Vec::new();
let mut unavailable = Vec::new();
let mut error_parts = Vec::new();
for (provider, result) in discovered {
match result {
Ok(list) => {
for m in list {
let effort_supported = crate::session::model_supports_effort(&m.id);
models.push(serde_json::json!({
"id": m.id,
"effort_supported": effort_supported,
}));
}
}
Err(e) => {
let err_text = e.to_string();
error_parts.push(format!("{provider}: {err_text}"));
unavailable.push(serde_json::json!({
"provider": provider,
"error": err_text,
}));
}
}
}
if models.is_empty() {
let msg = if error_parts.is_empty() {
"no models listed by any provider".to_string()
} else {
format!("no models available: {}", error_parts.join("; "))
};
return json_error(502, msg);
}
Response::json(
200,
&serde_json::json!({
"models": models,
"unavailable": unavailable,
}),
)
}
fn handle_post_model(surface: &Surface, req: &Request) -> Response {
let obj = match parse_json_object(&req.body) {
Ok(o) => o,
Err(resp) => return resp,
};
let model = match obj.get("model") {
Some(serde_json::Value::String(s)) => s.clone(),
Some(_) => return json_error(400, "field model must be a string"),
None => return json_error(400, "missing required field: model"),
};
if model.trim().is_empty() {
return json_error(400, "field model must not be empty");
}
if let Err(e) = blyte_provider::resolve_provider(Some(&model)) {
return json_error(400, e.to_string());
}
if let Err(e) = surface.session.set_model(&model) {
return json_error(400, e);
}
session_response(surface)
}
fn handle_post_effort(surface: &Surface, req: &Request) -> Response {
let obj = match parse_json_object(&req.body) {
Ok(o) => o,
Err(resp) => return resp,
};
let effort = match obj.get("effort") {
Some(serde_json::Value::Null) => None,
Some(serde_json::Value::String(s)) => Some(s.clone()),
Some(_) => return json_error(400, "field effort must be a string or null"),
None => return json_error(400, "missing required field: effort"),
};
if let Err(e) = surface.session.set_effort(effort.as_deref()) {
return json_error(400, e);
}
session_response(surface)
}
fn handle_post_seen(surface: &Surface) -> Response {
surface.session.mark_seen();
Response::text(204, "")
}
fn handle_post_approval(surface: &Surface, id: &str, req: &Request) -> Response {
let obj = match parse_json_object(&req.body) {
Ok(o) => o,
Err(resp) => return resp,
};
if obj.len() != 1 {
return json_error(400, "request body must contain only field answer");
}
let answer = match obj.get("answer") {
Some(serde_json::Value::String(s)) if s == "yes" => ApprovalAnswer::Yes,
Some(serde_json::Value::String(s)) if s == "no" => ApprovalAnswer::No,
Some(serde_json::Value::String(other)) => {
return json_error(
400,
format!("field answer must be \"yes\" or \"no\", got '{other}'"),
);
}
Some(_) => return json_error(400, "field answer must be \"yes\" or \"no\""),
None => return json_error(400, "missing required field: answer"),
};
match surface.session.answer_approval(id, answer) {
Ok(seq) => Response::json(
200,
&serde_json::json!({
"id": id,
"answer": answer.as_str(),
"seq": seq,
}),
),
Err(AnswerError::NotFound) => json_error(404, format!("unknown approval id: {id}")),
Err(AnswerError::AlreadyAnswered) => {
json_error(409, format!("approval {id} has already been answered"))
}
}
}
pub fn reconcile_runs(
surface: &Surface,
now: u64,
) -> Result<(crate::live_runs::LiveRuns, Vec<String>), String> {
let _guard = surface
.reconcile_lock
.lock()
.unwrap_or_else(|e| e.into_inner());
if !is_repository(&surface.root)? {
let records_dir = crate::dispatch_in_place::records_dir_for(&surface.root)?;
let owned = crate::requests::owned_run_ids_in(&records_dir, &surface.surface_id)?;
let mut live =
crate::live_runs::collect_in_place(&surface.root, &records_dir, now, surface.days)?;
live.running.retain(|run| owned.contains(&run.id));
live.runs.retain(|run| owned.contains(&run.id));
let mut errors = Vec::new();
if let Err(e) = crate::run_results::report_finished_runs_in(surface, &records_dir) {
errors.push(format!("run report failed: {e}"));
}
return Ok((live, errors));
}
let owned = crate::requests::owned_run_ids(surface)?;
let mut live = crate::live_runs::collect(&surface.root, now, surface.days)?;
let mut any_written = false;
for run in &live.runs {
if !owned.contains(&run.id) || run.checks_recorded {
continue;
}
if crate::queue_actions::ensure_checks(&surface.root, &run.id)? {
any_written = true;
}
}
if any_written {
live = crate::live_runs::collect(&surface.root, now, surface.days)?;
}
live.running.retain(|run| owned.contains(&run.id));
live.runs.retain(|run| owned.contains(&run.id));
let mut errors = Vec::new();
if let Err(e) = crate::run_results::report_finished_runs(surface) {
errors.push(format!("run report failed: {e}"));
}
let mut triggered = BTreeSet::new();
for run in &live.runs {
if run.research {
continue;
}
if let Some(ref req_id) = run.request {
if triggered.insert(req_id.clone()) {
if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
errors.push(format!("combine trigger failed for {req_id}: {e}"));
}
}
}
}
Ok((live, errors))
}
fn handle_runs(surface: &Surface, now: u64) -> Response {
let is_repo = match is_repository(&surface.root) {
Ok(v) => v,
Err(e) => return json_error(500, e),
};
let (live, errors) = match reconcile_runs(surface, now) {
Ok(res) => res,
Err(e) => return json_error(500, e),
};
for msg in errors {
surface.session.record_error(&msg);
}
let mut runs_with_hold = Vec::with_capacity(live.runs.len());
if is_repo {
let run_refs: Vec<(&str, Option<&str>)> = live
.runs
.iter()
.map(|run| (run.id.as_str(), run.request.as_deref()))
.collect();
let combined_ids = match crate::requests::combined_run_ids(&surface.root, &run_refs) {
Ok(ids) => ids,
Err(e) => return json_error(500, e),
};
for run in &live.runs {
let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
Ok(h) => h,
Err(e) => return json_error(500, e),
};
let combined = combined_ids.contains(&run.id);
runs_with_hold.push(RunWithHold {
run,
hold,
combined,
in_place: false,
undone: false,
});
}
} else {
let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
Ok(dir) => dir,
Err(e) => return json_error(500, e),
};
for run in &live.runs {
let hold = match crate::queue_actions::read_hold_in(&records_dir, &run.id) {
Ok(h) => h,
Err(e) => return json_error(500, e),
};
let undone = crate::in_place_review::is_undone(&records_dir, &run.id);
runs_with_hold.push(RunWithHold {
run,
hold,
combined: false,
in_place: true,
undone,
});
}
}
let payload = LiveRunsResponse {
generated_at: live.generated_at,
repo: &live.repo,
running: &live.running,
runs: runs_with_hold,
skipped: &live.skipped,
};
match serde_json::to_value(&payload) {
Ok(val) => Response::json(200, &val),
Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
}
}
fn handle_runs_changed(surface: &Surface) -> Response {
surface.reconcile_requested.store(true, Ordering::Release);
Response::json(202, &serde_json::json!({}))
}
const NOT_A_GIT_REPO_ERROR: &str = "this folder is not a git repository";
fn require_repository(root: &Path) -> Result<(), Response> {
match is_repository(root) {
Ok(true) => Ok(()),
Ok(false) => Err(json_error(409, NOT_A_GIT_REPO_ERROR)),
Err(e) => Err(json_error(500, e)),
}
}
fn handle_run_diff(surface: &Surface, id: &str) -> Response {
let is_repo = match is_repository(&surface.root) {
Ok(v) => v,
Err(e) => return json_error(500, e),
};
if !is_valid_run_id(id) {
return json_error(404, format!("unknown run: {id}"));
}
if !is_repo {
let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
Ok(dir) => dir,
Err(e) => return json_error(500, e),
};
let start = records_dir.join(format!("{id}.start.json"));
let summary = records_dir.join(format!("{id}.json"));
let report_json = records_dir.join(format!("{id}.report.json"));
let report_md = records_dir.join(format!("{id}.report.md"));
if !start.exists() && !summary.exists() && !report_json.exists() && !report_md.exists() {
return json_error(404, format!("unknown run: {id}"));
}
if let Err(err) = crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
{
return request_action_error_response(err);
}
return match crate::in_place_review::diff_for_run(&records_dir, id) {
Ok(body) => Response::text(200, &body),
Err(e) => {
if !summary.exists() || e.contains("No such file") || e.contains("missing manifest")
{
json_error(404, e)
} else {
json_error(500, e)
}
}
};
}
let wt_dir = surface.root.join(".wt");
let wt = wt_dir.join(id);
let start = wt_dir.join(format!("{id}.start.json"));
let summary = wt_dir.join(format!("{id}.json"));
let report_json = wt_dir.join(format!("{id}.report.json"));
let report_md = wt_dir.join(format!("{id}.report.md"));
if !wt.exists()
&& !start.exists()
&& !summary.exists()
&& !report_json.exists()
&& !report_md.exists()
{
return json_error(404, format!("unknown run: {id}"));
}
if let Err(err) = crate::requests::run_owner_check(surface, id) {
return request_action_error_response(err);
}
match crate::queue_actions::compute_review(&surface.root, id, true) {
Ok(data) => {
let body = if !data.wt_exists {
"(worktree removed)\n".to_string()
} else if data.diff_out.is_empty() {
String::new()
} else {
format!("{}\n", data.diff_out)
};
Response::text(200, &body)
}
Err(e) => {
if !wt.is_dir() || !wt.join(".git").exists() {
json_error(404, e)
} else {
json_error(500, e)
}
}
}
}
fn handle_run_undo(surface: &Surface, id: &str) -> Response {
let is_repo = match is_repository(&surface.root) {
Ok(v) => v,
Err(e) => return json_error(500, e),
};
if is_repo {
return json_error(
409,
"undo is for runs in a folder that is not a git repository",
);
}
if !is_valid_run_id(id) {
return json_error(404, format!("unknown run: {id}"));
}
let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
Ok(dir) => dir,
Err(e) => return json_error(500, e),
};
let run_exists = records_dir.join(format!("{id}.start.json")).exists()
|| records_dir.join(format!("{id}.json")).exists()
|| records_dir.join(format!("{id}.report.json")).exists()
|| records_dir.join(format!("{id}.report.md")).exists();
if run_exists {
if let Err(err) = crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
{
return request_action_error_response(err);
}
}
match crate::in_place_review::undo_in(&surface.root, id) {
Ok(lines) => Response::json(200, &serde_json::json!({ "lines": lines })),
Err(msg) => json_error(409, msg),
}
}
fn parse_action(raw: &str) -> Result<Action, String> {
match raw {
"accept" => Ok(Action::Accept),
"send_back" => Ok(Action::SendBack),
"redo" => Ok(Action::Redo),
"hold" => Ok(Action::Hold),
"mark_read" => Ok(Action::MarkRead),
other => Err(format!(
"unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
)),
}
}
fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
let is_repo = match is_repository(&surface.root) {
Ok(v) => v,
Err(e) => return json_error(500, e),
};
let obj = match parse_json_object(&req.body) {
Ok(o) => o,
Err(resp) => return resp,
};
let action_str = match obj.get("action") {
Some(serde_json::Value::String(s)) => s.clone(),
Some(_) => return json_error(400, "field action must be a string"),
None => return json_error(400, "missing required field: action"),
};
let action = match parse_action(&action_str) {
Ok(a) => a,
Err(e) => return json_error(400, e),
};
let note = match obj.get("note") {
None | Some(serde_json::Value::Null) => None,
Some(serde_json::Value::String(s)) => Some(s.clone()),
Some(_) => return json_error(400, "field note must be a string or null"),
};
let decision = if is_repo {
let wt_dir = surface.root.join(".wt");
let run_exists = is_valid_run_id(id)
&& (wt_dir.join(id).exists()
|| wt_dir.join(format!("{id}.start.json")).exists()
|| wt_dir.join(format!("{id}.json")).exists()
|| wt_dir.join(format!("{id}.report.json")).exists()
|| wt_dir.join(format!("{id}.report.md")).exists());
if run_exists {
if let Err(err) = crate::requests::run_owner_check(surface, id) {
return request_action_error_response(err);
}
}
match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
Ok(d) => d,
Err(e) => return json_error(400, e),
}
} else {
let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
Ok(dir) => dir,
Err(e) => return json_error(500, e),
};
let run_exists = is_valid_run_id(id)
&& (records_dir.join(format!("{id}.start.json")).exists()
|| records_dir.join(format!("{id}.json")).exists()
|| records_dir.join(format!("{id}.report.json")).exists()
|| records_dir.join(format!("{id}.report.md")).exists());
if run_exists {
if let Err(err) =
crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
{
return request_action_error_response(err);
}
}
match crate::queue_actions::decide_in_place(&records_dir, id, action, note.as_deref(), now)
{
Ok(d) => d,
Err(e) => return json_error(400, e),
}
};
let seq = match surface.session.record_decision(
&decision.run,
&action_str,
decision.note.as_deref(),
decision.conversation_message.as_deref(),
) {
Ok(s) => s,
Err(e) => return json_error(500, e),
};
if is_repo && action == Action::Accept {
match crate::requests::run_request_id(&surface.root, &decision.run) {
Ok(Some(req_id)) => {
if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
surface
.session
.record_error(&format!("combine trigger failed for {req_id}: {e}"));
}
}
Ok(None) => {}
Err(e) => return json_error(500, e),
}
}
Response::json(
200,
&serde_json::json!({
"decision": {
"run": decision.run,
"action": action_str,
"note": decision.note,
"conversation_message": decision.conversation_message,
},
"seq": seq,
}),
)
}
fn handle_map(surface: &Surface) -> Response {
match crate::map::build(&surface.root, &surface.repo) {
Ok(data) => match serde_json::to_value(&data) {
Ok(val) => Response::json(200, &val),
Err(e) => json_error(500, format!("failed to serialize map: {e}")),
},
Err(e) => json_error(422, e),
}
}
fn handle_requests(surface: &Surface) -> Response {
match is_repository(&surface.root) {
Ok(true) => {}
Ok(false) => return Response::json(200, &serde_json::json!([])),
Err(e) => return json_error(500, e),
}
match crate::requests::list_requests(surface) {
Ok(list) => match serde_json::to_value(&list) {
Ok(val) => Response::json(200, &val),
Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
},
Err(e) => json_error(500, e),
}
}
fn request_action_error_response(err: RequestActionError) -> Response {
match err {
RequestActionError::BadRequest(msg) => json_error(400, msg),
RequestActionError::NotOwned(msg) => json_error(403, msg),
RequestActionError::Conflict(msg) => json_error(409, msg),
RequestActionError::Internal(msg) => json_error(500, msg),
}
}
fn handle_request_push(surface: &Surface, id: &str) -> Response {
if let Err(resp) = require_repository(&surface.root) {
return resp;
}
match crate::requests::push_request(surface, id) {
Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
Err(err) => request_action_error_response(err),
}
}
fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
if let Err(resp) = require_repository(&surface.root) {
return resp;
}
if let Err(e) = crate::dispatch::validate_request_id(id) {
return json_error(400, e);
}
let obj = match parse_json_object(&req.body) {
Ok(o) => o,
Err(resp) => return resp,
};
let title = match obj.get("title") {
Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
Some(serde_json::Value::String(_)) => {
return json_error(400, "field title must not be empty");
}
Some(_) => return json_error(400, "field title must be a string"),
None => return json_error(400, "missing required field: title"),
};
let body = match obj.get("body") {
None | Some(serde_json::Value::Null) => String::new(),
Some(serde_json::Value::String(s)) => s.clone(),
Some(_) => return json_error(400, "field body must be a string"),
};
match crate::requests::open_request_pull_request(surface, id, &title, &body) {
Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
Err(err) => request_action_error_response(err),
}
}
#[derive(Clone, Copy)]
enum ApiGetHandler {
Session,
Events,
Models,
Runs,
Requests,
Map,
RunDiff,
Usage,
}
const API_GET_ROUTES: &[(&str, ApiGetHandler)] = &[
("/api/session", ApiGetHandler::Session),
("/api/session/events", ApiGetHandler::Events),
("/api/models", ApiGetHandler::Models),
("/api/runs", ApiGetHandler::Runs),
("/api/requests", ApiGetHandler::Requests),
("/api/map", ApiGetHandler::Map),
("/api/runs/{id}/diff", ApiGetHandler::RunDiff),
("/api/usage", ApiGetHandler::Usage),
];
pub fn authenticated_api_get_routes() -> Vec<&'static str> {
API_GET_ROUTES.iter().map(|(pattern, _)| *pattern).collect()
}
fn match_api_get_route<'a>(pattern: &str, path: &'a str) -> Option<Option<&'a str>> {
if let Some((prefix, suffix)) = pattern.split_once("{id}") {
let rest = path.strip_prefix(prefix)?;
let id = rest.strip_suffix(suffix)?;
if !id.is_empty() && !id.contains('/') {
return Some(Some(id));
}
None
} else if pattern == path {
Some(None)
} else {
None
}
}
fn handle_post_open_code(surface: &Surface, now: u64) -> Response {
match surface.open_codes.issue(now) {
Ok(code) => Response::json(200, &serde_json::json!({ "code": code })),
Err(e) => json_error(500, e),
}
}
fn handle_post_open(surface: &Surface, req: &Request, now: u64) -> Response {
let forbidden = Response {
status: 403,
content_type: "application/json",
body: b"{}".to_vec(),
};
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&req.body) else {
return forbidden;
};
let Some(code) = value.get("code").and_then(|v| v.as_str()) else {
return forbidden;
};
match surface.open_codes.redeem(code, now) {
Ok(true) => Response::json(200, &serde_json::json!({ "token": surface.token })),
Ok(false) => forbidden,
Err(e) => json_error(500, e),
}
}
pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
route_inner(surface, req, now, None, None)
}
fn route_inner(
surface: &Surface,
req: &Request,
now: u64,
stop_trigger: Option<&StopTrigger>,
reload_trigger: Option<&ReloadTrigger>,
) -> Response {
if req.path == "/api/peer/messages" && req.method == "POST" {
if !has_valid_message_credential(surface, req) {
return json_error(403, "missing or invalid message credential");
}
return handle_post_peer_message(surface, req);
}
let is_health_get = req.path == "/api/health" && req.method == "GET";
let is_open_post = req.path == "/api/open" && req.method == "POST";
if (req.path.starts_with("/api/") || req.method == "POST")
&& !is_health_get
&& !is_open_post
&& !has_valid_token(surface, req)
{
return json_error(
403,
"missing or invalid surface token; open the page from the URL blyte printed",
);
}
if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
if req.method != "GET" {
return method_not_allowed(req);
}
return Response {
status,
content_type,
body,
};
}
if req.path == "/" || req.path == "/index.html" {
if req.method != "GET" {
return method_not_allowed(req);
}
return Response::html(INDEX_HTML.as_bytes().to_vec());
}
if req.path == "/usage" {
if req.method != "GET" {
return method_not_allowed(req);
}
return Response::html(USAGE_HTML.as_bytes().to_vec());
}
if req.path == "/api/health" {
if req.method != "GET" {
return method_not_allowed(req);
}
return health_response(surface);
}
for &(pattern, handler) in API_GET_ROUTES {
if let Some(id) = match_api_get_route(pattern, &req.path) {
if req.method != "GET" {
return method_not_allowed(req);
}
return match handler {
ApiGetHandler::Session => session_response(surface),
ApiGetHandler::Events => handle_events(surface, req),
ApiGetHandler::Models => handle_models(),
ApiGetHandler::Runs => handle_runs(surface, now),
ApiGetHandler::Requests => handle_requests(surface),
ApiGetHandler::Map => handle_map(surface),
ApiGetHandler::RunDiff => handle_run_diff(surface, id.unwrap_or("")),
ApiGetHandler::Usage => handle_usage(req, now),
};
}
}
match req.path.as_str() {
"/api/open" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_post_open(surface, req, now)
}
"/api/surfaces" => {
if req.method != "GET" {
return method_not_allowed(req);
}
handle_surfaces(surface)
}
"/api/surfaces/start" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_post_start_surface(req)
}
"/api/session/stop" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_post_stop(stop_trigger)
}
"/api/reload" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_post_reload(surface, reload_trigger)
}
"/api/session/open-codes" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_post_open_code(surface, now)
}
"/api/session/messages" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_post_message(surface, req)
}
"/api/session/attachments" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_post_attachment(surface, req)
}
"/api/session/model" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_post_model(surface, req)
}
"/api/session/effort" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_post_effort(surface, req)
}
"/api/session/seen" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_post_seen(surface)
}
"/api/runs/changed" => {
if req.method != "POST" {
return method_not_allowed(req);
}
handle_runs_changed(surface)
}
path => {
if let Some(id) = path.strip_prefix("/api/session/attachments/") {
if !id.is_empty() && !id.contains('/') {
if req.method != "GET" {
return method_not_allowed(req);
}
return handle_get_attachment(surface, id);
}
}
if let Some(id) = path.strip_prefix("/api/session/approvals/") {
if !id.is_empty() && !id.contains('/') {
if req.method != "POST" {
return method_not_allowed(req);
}
return handle_post_approval(surface, id, req);
}
}
if let Some(rest) = path.strip_prefix("/api/runs/") {
if let Some(id) = rest.strip_suffix("/decision") {
if !id.is_empty() && !id.contains('/') {
if req.method != "POST" {
return method_not_allowed(req);
}
return handle_run_decision(surface, id, req, now);
}
}
if let Some(id) = rest.strip_suffix("/undo") {
if !id.is_empty() && !id.contains('/') {
if req.method != "POST" {
return method_not_allowed(req);
}
return handle_run_undo(surface, id);
}
}
}
if let Some(rest) = path.strip_prefix("/api/requests/") {
if let Some(id) = rest.strip_suffix("/push") {
if req.method != "POST" {
return method_not_allowed(req);
}
return handle_request_push(surface, id);
}
if let Some(id) = rest.strip_suffix("/pull-request") {
if req.method != "POST" {
return method_not_allowed(req);
}
return handle_request_pull_request(surface, id, req);
}
}
json_error(404, format!("not found: {}", req.path))
}
}
}
enum GitToplevel {
Repository(PathBuf),
NotARepository,
}
fn find_git_toplevel(dir: &Path) -> Result<GitToplevel, String> {
let out = Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.env("LC_ALL", "C")
.current_dir(dir)
.output()
.map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
if stderr.contains("not a git repository (or any") {
return Ok(GitToplevel::NotARepository);
}
let detail = stderr.trim();
if detail.is_empty() {
return Err(format!("not inside a git repository ({})", dir.display()));
}
return Err(format!(
"not inside a git repository ({}): {detail}",
dir.display()
));
}
let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
if path_str.is_empty() {
return Err(format!("not inside a git repository ({})", dir.display()));
}
Ok(GitToplevel::Repository(PathBuf::from(path_str)))
}
pub(crate) fn is_repository(root: &Path) -> Result<bool, String> {
match find_git_toplevel(root)? {
GitToplevel::Repository(_) => Ok(true),
GitToplevel::NotARepository => Ok(false),
}
}
fn resolve_denied_path(denied: &Path) -> Result<PathBuf, String> {
let mut probe = denied;
let mut tail = Vec::new();
loop {
match probe.canonicalize() {
Ok(mut resolved) => {
for part in tail.into_iter().rev() {
resolved.push(part);
}
return Ok(resolved);
}
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
) =>
{
let Some(name) = probe.file_name() else {
return Err(format!("cannot canonicalize {}: {e}", denied.display()));
};
let Some(parent) = probe.parent() else {
return Err(format!("cannot canonicalize {}: {e}", denied.display()));
};
tail.push(name.to_os_string());
probe = parent;
}
Err(e) => {
return Err(format!("cannot canonicalize {}: {e}", denied.display()));
}
}
}
}
pub fn check_linux_non_repo_root(root: &Path, home: &Path) -> Result<(), String> {
let root_canon = root
.canonicalize()
.map_err(|e| format!("cannot canonicalize {}: {e}", root.display()))?;
let home_canon = home
.canonicalize()
.map_err(|e| format!("cannot canonicalize home directory {}: {e}", home.display()))?;
for denied in blyte_agent::sandbox::read_denied(&home_canon) {
let denied_canon = resolve_denied_path(&denied)?;
if denied.starts_with(&root_canon) || denied_canon.starts_with(&root_canon) {
return Err(format!(
"on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
root_canon.display(),
denied.display()
));
}
}
if home_canon.starts_with(&root_canon) {
return Err(format!(
"on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
root_canon.display(),
home_canon.display()
));
}
Ok(())
}
pub fn check_linux_non_repo_root_for_env(
root: &Path,
home: Option<&std::ffi::OsStr>,
) -> Result<(), String> {
let home = home.filter(|h| !h.is_empty()).ok_or_else(|| {
format!(
"cannot check whether {} contains protected paths on Linux: HOME is not set",
root.display()
)
})?;
check_linux_non_repo_root(root, Path::new(home))
}
fn resolve_main_checkout(worktree_root: &Path) -> Result<PathBuf, String> {
let out = Command::new("git")
.args([
"rev-parse",
"--path-format=absolute",
"--git-dir",
"--git-common-dir",
])
.current_dir(worktree_root)
.output()
.map_err(|_| {
format!(
"cannot find the main checkout of {}",
worktree_root.display()
)
})?;
if !out.status.success() {
return Err(format!(
"cannot find the main checkout of {}",
worktree_root.display()
));
}
let text = String::from_utf8_lossy(&out.stdout);
let mut lines = text.lines();
let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
return Err(format!(
"cannot find the main checkout of {}",
worktree_root.display()
));
};
let git_dir_path = PathBuf::from(git_dir.trim());
let common_dir_path = PathBuf::from(common_dir.trim());
let git_dir_canon = git_dir_path
.canonicalize()
.map_err(|e| format!("cannot canonicalize {}: {e}", git_dir_path.display()))?;
let common_dir_canon = common_dir_path
.canonicalize()
.map_err(|e| format!("cannot canonicalize {}: {e}", common_dir_path.display()))?;
if git_dir_canon == common_dir_canon {
return worktree_root
.canonicalize()
.map_err(|e| format!("cannot canonicalize {}: {e}", worktree_root.display()));
}
let main = crate::config::main_checkout(worktree_root).ok_or_else(|| {
format!(
"cannot find the main checkout of {}",
worktree_root.display()
)
})?;
main.canonicalize()
.map_err(|e| format!("cannot canonicalize {}: {e}", main.display()))
}
pub(crate) fn resolve_folder(folder: &Path) -> Result<PathBuf, String> {
match find_git_toplevel(folder)? {
GitToplevel::Repository(worktree_root) => resolve_main_checkout(&worktree_root),
GitToplevel::NotARepository => folder
.canonicalize()
.map_err(|e| format!("cannot canonicalize {}: {e}", folder.display())),
}
}
fn current_branch(main_checkout: &Path) -> Result<Option<String>, String> {
match find_git_toplevel(main_checkout)? {
GitToplevel::NotARepository => return Ok(None),
GitToplevel::Repository(_) => {}
}
if let Ok(out) = Command::new("git")
.args(["rev-parse", "--abbrev-ref", "HEAD"])
.current_dir(main_checkout)
.output()
{
if out.status.success() {
let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !branch.is_empty() {
return Ok(Some(branch));
}
}
}
if let Ok(out) = Command::new("git")
.args(["symbolic-ref", "--short", "HEAD"])
.current_dir(main_checkout)
.output()
{
if out.status.success() {
let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !branch.is_empty() {
return Ok(Some(branch));
}
}
}
Err(format!(
"cannot read the current branch of {}",
main_checkout.display()
))
}
fn repo_name_for(root: &Path) -> Result<String, String> {
root.file_name()
.and_then(|s| s.to_str())
.filter(|s| !s.is_empty())
.map(String::from)
.ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
}
fn now_duration() -> Result<Duration, String> {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| format!("system clock is before Unix epoch: {e}"))
}
fn new_session_id(nanos: u128) -> String {
let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
format!("surface-{}-{nanos}-{seq}", std::process::id())
}
pub fn open_browser_in(open_in: OpenIn, url: &str) {
crate::open_window::open_url(open_in, url);
}
pub fn open_browser(url: &str) {
open_browser_in(OpenIn::App, url);
}
fn resolve_initial_model(config: &ReplConfig) -> String {
if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
return m.to_string();
}
if let Ok(m) = std::env::var("BLYTE_MODEL") {
if !m.trim().is_empty() {
return m;
}
}
if let Ok(p) = blyte_provider::resolve_provider(None) {
return p.model_id();
}
"gemini-3.8-flash-high".to_string()
}
static SIGNAL_STOP: AtomicBool = AtomicBool::new(false);
static SIGNAL_INTERRUPT: AtomicBool = AtomicBool::new(false);
#[cfg(unix)]
extern "C" fn handle_shutdown_signal(_: libc::c_int) {
SIGNAL_STOP.store(true, Ordering::Relaxed);
}
#[cfg(unix)]
extern "C" fn handle_interrupt_signal(_: libc::c_int) {
SIGNAL_INTERRUPT.store(true, Ordering::Relaxed);
}
fn ensure_token_dir(dir: &Path) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
if let Some(parent) = dir.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
}
let mut builder = std::fs::DirBuilder::new();
builder.mode(0o700);
match builder.create(dir) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
.map_err(|e| format!("cannot set permissions on {}: {e}", dir.display()))?;
}
Err(e) => return Err(format!("cannot create {}: {e}", dir.display())),
}
Ok(())
}
#[cfg(not(unix))]
{
std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))
}
}
fn write_token_file(token_file_path: &Path, token: &str) -> Result<(), String> {
let token_dir = token_file_path
.parent()
.ok_or_else(|| format!("invalid token path {}", token_file_path.display()))?;
ensure_token_dir(token_dir)?;
let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
let tmp_path = token_dir.join(format!(".surface.token.{}.{seq}.tmp", std::process::id()));
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
opts.mode(0o600);
}
let mut file = opts
.open(&tmp_path)
.map_err(|e| format!("cannot create {}: {e}", token_file_path.display()))?;
if let Err(e) = writeln!(file, "{token}") {
let _ = std::fs::remove_file(&tmp_path);
return Err(format!("cannot write {}: {e}", token_file_path.display()));
}
drop(file);
if let Err(e) = std::fs::rename(&tmp_path, token_file_path) {
let _ = std::fs::remove_file(&tmp_path);
return Err(format!("cannot write {}: {e}", token_file_path.display()));
}
Ok(())
}
struct TokenFileGuard {
path: Option<PathBuf>,
}
impl TokenFileGuard {
fn new(path: PathBuf) -> Self {
Self { path: Some(path) }
}
fn disarm(&mut self) {
self.path = None;
}
}
impl Drop for TokenFileGuard {
fn drop(&mut self) {
if let Some(ref path) = self.path {
let _ = std::fs::remove_file(path);
}
}
}
struct RegistryEntryGuard {
dir: PathBuf,
id: String,
}
impl Drop for RegistryEntryGuard {
fn drop(&mut self) {
let _ = crate::surface_registry::remove_entry(&self.dir, &self.id);
}
}
struct PrivateTmpDirGuard {
path: PathBuf,
}
impl Drop for PrivateTmpDirGuard {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
struct PublishToolGuard;
impl PublishToolGuard {
fn install(surface: Arc<Surface>) -> Self {
blyte_agent::tools::set_publish_tool(Some(Arc::new(
crate::requests::SurfacePublishTool::new(surface),
)));
Self
}
}
impl Drop for PublishToolGuard {
fn drop(&mut self) {
blyte_agent::tools::set_publish_tool(None);
}
}
struct LandToolGuard;
impl LandToolGuard {
fn install(surface: Arc<Surface>) -> Self {
blyte_agent::tools::set_land_tool(Some(Arc::new(crate::land::SurfaceLandTool::new(
surface,
))));
Self
}
}
impl Drop for LandToolGuard {
fn drop(&mut self) {
blyte_agent::tools::set_land_tool(None);
}
}
pub struct FrontEndContext {
pub surface: Arc<Surface>,
pub take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
}
pub type FrontEnd = Box<dyn FnOnce(FrontEndContext) -> i32 + Send>;
struct FrontEndSpec {
front: FrontEnd,
take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
}
#[derive(Clone, Copy)]
enum FrontEndOutcome {
Exited(i32),
Panicked,
}
struct StopControl<S> {
should_stop: S,
trigger: StopTrigger,
}
fn atomic_stop_control(stop: Arc<AtomicBool>) -> StopControl<impl Fn() -> bool> {
let stop_trigger_flag = Arc::clone(&stop);
StopControl {
should_stop: move || stop.load(Ordering::Acquire),
trigger: Arc::new(move || stop_trigger_flag.store(true, Ordering::Release)),
}
}
pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
SIGNAL_STOP.store(false, Ordering::Relaxed);
#[cfg(unix)]
unsafe {
libc::signal(
libc::SIGINT,
handle_shutdown_signal as *const () as libc::sighandler_t,
);
libc::signal(
libc::SIGTERM,
handle_shutdown_signal as *const () as libc::sighandler_t,
);
}
let open_in = args.open_in;
let mut opener = |url: &str| open_browser_in(open_in, url);
let stop_control = StopControl {
should_stop: || SIGNAL_STOP.load(Ordering::Acquire),
trigger: Arc::new(|| SIGNAL_STOP.store(true, Ordering::Release)),
};
run_inner(
args,
config,
&mut std::io::stdout(),
&mut std::io::stderr(),
&mut opener,
stop_control,
None,
None,
)
}
pub fn run_terminal(args: &SurfaceArgs, config: ReplConfig) -> i32 {
run_with_front_end(
args,
config,
Box::new(|ctx| {
let stdin = std::io::stdin();
let input_is_terminal = std::io::IsTerminal::is_terminal(&stdin);
let mut stdout = std::io::stdout();
let root = ctx.surface.root.clone();
let options = crate::terminal_front::TerminalOptions {
input_is_terminal,
settle: Duration::from_secs(3),
take_interrupt: ctx.take_interrupt,
runs_working: Arc::new(move || crate::surfaces_cmd::count_running_runs(&root)),
};
crate::terminal_front::run_terminal_front(
&ctx.surface.session,
Box::new(std::io::BufReader::new(stdin)),
&mut stdout,
options,
)
}),
)
}
pub fn run_with_front_end(args: &SurfaceArgs, config: ReplConfig, front: FrontEnd) -> i32 {
SIGNAL_STOP.store(false, Ordering::Relaxed);
SIGNAL_INTERRUPT.store(false, Ordering::Relaxed);
#[cfg(unix)]
unsafe {
libc::signal(
libc::SIGINT,
handle_interrupt_signal as *const () as libc::sighandler_t,
);
libc::signal(
libc::SIGTERM,
handle_shutdown_signal as *const () as libc::sighandler_t,
);
}
let mut opener = |_: &str| {};
let stop_control = StopControl {
should_stop: || SIGNAL_STOP.load(Ordering::Acquire),
trigger: Arc::new(|| SIGNAL_STOP.store(true, Ordering::Release)),
};
let take_interrupt: Arc<dyn Fn() -> bool + Send + Sync> =
Arc::new(|| SIGNAL_INTERRUPT.swap(false, Ordering::AcqRel));
run_inner(
args,
config,
&mut std::io::stdout(),
&mut std::io::stderr(),
&mut opener,
stop_control,
None,
Some(FrontEndSpec {
front,
take_interrupt,
}),
)
}
pub fn run_with_io(
args: &SurfaceArgs,
config: ReplConfig,
out: &mut dyn Write,
err: &mut dyn Write,
) -> i32 {
let open_in = args.open_in;
let mut opener = |url: &str| open_browser_in(open_in, url);
let stop = Arc::new(AtomicBool::new(false));
run_inner(
args,
config,
out,
err,
&mut opener,
atomic_stop_control(stop),
None,
None,
)
}
pub fn run_with_hooks(
args: &SurfaceArgs,
config: ReplConfig,
out: &mut dyn Write,
err: &mut dyn Write,
opener: &mut dyn FnMut(&str),
stop: Arc<AtomicBool>,
) -> i32 {
run_inner(
args,
config,
out,
err,
opener,
atomic_stop_control(stop),
None,
None,
)
}
pub type RunnerFactory = Box<
dyn FnOnce(
&ReplConfig,
Arc<dyn blyte_agent::approval::Approver>,
) -> Result<(Box<dyn PromptRunner>, Option<PathBuf>), String>,
>;
pub fn run_with_runner(
args: &SurfaceArgs,
config: ReplConfig,
out: &mut dyn Write,
err: &mut dyn Write,
opener: &mut dyn FnMut(&str),
stop: Arc<AtomicBool>,
runner: Box<dyn PromptRunner>,
) -> i32 {
run_inner(
args,
config,
out,
err,
opener,
atomic_stop_control(stop),
Some(Box::new(|_, _| Ok((runner, None)))),
None,
)
}
#[allow(clippy::too_many_arguments)]
pub fn run_with_front_end_and_runner(
args: &SurfaceArgs,
config: ReplConfig,
out: &mut dyn Write,
err: &mut dyn Write,
stop: Arc<AtomicBool>,
take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
runner: Box<dyn PromptRunner>,
front: FrontEnd,
) -> i32 {
let mut opener = |_: &str| {};
run_inner(
args,
config,
out,
err,
&mut opener,
atomic_stop_control(stop),
Some(Box::new(|_, _| Ok((runner, None)))),
Some(FrontEndSpec {
front,
take_interrupt,
}),
)
}
pub fn run_with_runner_factory(
args: &SurfaceArgs,
config: ReplConfig,
out: &mut dyn Write,
err: &mut dyn Write,
opener: &mut dyn FnMut(&str),
stop: Arc<AtomicBool>,
factory: RunnerFactory,
) -> i32 {
run_inner(
args,
config,
out,
err,
opener,
atomic_stop_control(stop),
Some(factory),
None,
)
}
struct ReconcileTimerGuard {
stop: Arc<AtomicBool>,
handle: Option<std::thread::JoinHandle<()>>,
}
impl Drop for ReconcileTimerGuard {
fn drop(&mut self) {
self.stop.store(true, Ordering::Release);
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
}
fn spawn_reconcile_timer(surface: Arc<Surface>) -> ReconcileTimerGuard {
let stop = Arc::new(AtomicBool::new(false));
let thread_stop = Arc::clone(&stop);
let handle = std::thread::spawn(move || {
let mut after = surface.session.info().last_seq;
let mut next_tick = Instant::now();
let mut seen_errors: HashSet<String> = HashSet::new();
while !thread_stop.load(Ordering::Acquire) {
let wait = if surface.reconcile_requested.load(Ordering::Acquire) {
Duration::ZERO
} else {
next_tick
.saturating_duration_since(Instant::now())
.min(RECONCILE_POLL_WAIT)
};
let entries = surface.session.entries_after(after, wait);
let mut went_idle = false;
for entry in entries {
after = entry.seq;
if matches!(entry.body, EntryBody::Idle { .. }) {
went_idle = true;
}
}
if thread_stop.load(Ordering::Acquire) {
break;
}
let requested = surface.reconcile_requested.swap(false, Ordering::AcqRel);
if went_idle || requested || Instant::now() >= next_tick {
match now_duration().and_then(|d| reconcile_runs(&surface, d.as_secs())) {
Ok((_, errors)) => {
for msg in errors {
if seen_errors.insert(msg.clone()) {
surface.session.record_error(&msg);
eprintln!("blyte: {msg}");
}
}
}
Err(e) => {
if seen_errors.insert(e.clone()) {
eprintln!("blyte: {e}");
}
}
}
next_tick = Instant::now() + RECONCILE_SAFETY_NET_INTERVAL;
}
}
});
ReconcileTimerGuard {
stop,
handle: Some(handle),
}
}
#[allow(clippy::too_many_arguments)]
fn run_inner<S>(
args: &SurfaceArgs,
mut config: ReplConfig,
out: &mut dyn Write,
err: &mut dyn Write,
opener: &mut dyn FnMut(&str),
stop_control: StopControl<S>,
custom_runner: Option<RunnerFactory>,
front_end: Option<FrontEndSpec>,
) -> i32
where
S: Fn() -> bool,
{
let StopControl {
should_stop,
trigger: stop_trigger,
} = stop_control;
let (main_checkout, is_repo) = match find_git_toplevel(&config.repo_root) {
Ok(GitToplevel::Repository(worktree_root)) => {
let main = match resolve_main_checkout(&worktree_root) {
Ok(m) => m,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let same_checkout = match (worktree_root.canonicalize(), main.canonicalize()) {
(Ok(a), Ok(b)) => a == b,
_ => worktree_root == main,
};
if !same_checkout {
let _ = writeln!(
err,
"blyte: started in a linked worktree ({}); this surface works in the main checkout {}",
worktree_root.display(),
main.display()
);
let _ = err.flush();
}
(main, true)
}
Ok(GitToplevel::NotARepository) => {
let canonical = match config.repo_root.canonicalize() {
Ok(c) => c,
Err(e) => {
let _ = writeln!(
err,
"blyte: cannot canonicalize {}: {e}",
config.repo_root.display()
);
return 1;
}
};
(canonical, false)
}
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let repo = match repo_name_for(&main_checkout) {
Ok(r) => r,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
#[cfg(target_os = "linux")]
if !is_repo {
if let Err(e) =
check_linux_non_repo_root_for_env(&main_checkout, std::env::var_os("HOME").as_deref())
{
let _ = writeln!(err, "blyte: {e}");
return 1;
}
}
let state_dir = match crate::surface_registry::state_dir() {
Ok(d) => d,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let registry_dir = state_dir.join("surfaces");
let all_records =
match crate::surface_dir::list_records_for_root(&main_checkout, Some(&state_dir)) {
Ok(r) => r,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let mut running = Vec::new();
let mut stopped = Vec::new();
for located in all_records {
if crate::surface_dir::is_running(&located.record) {
running.push(located);
} else {
stopped.push(located);
}
}
let live_registry = match crate::surface_registry::live_entries(®istry_dir) {
Ok(listing) => {
crate::surface_registry::report_unreadable(&listing.unreadable, err);
listing.entries
}
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let mut running_names: Vec<String> = running.iter().map(|r| r.record.name.clone()).collect();
for entry in &live_registry {
if !running_names.iter().any(|n| n == &entry.name) {
running_names.push(entry.name.clone());
}
}
let (surface_id, surface_name, surface_record_dir) = if let Some(ref target) = args.resume {
if let Some(located) = running
.iter()
.find(|r| r.record.id == *target || r.record.name == *target)
{
let _ = writeln!(
err,
"blyte: surface {target} is already running (port {})",
located.record.port
);
return 1;
}
let stopped_matches: Vec<&crate::surface_dir::LocatedRecord> = stopped
.iter()
.filter(|r| r.record.id == *target || r.record.name == *target)
.collect();
if stopped_matches.is_empty() {
let _ = writeln!(
err,
"blyte: no stopped surface named {target} in {}",
main_checkout.display()
);
return 1;
}
if stopped_matches.len() > 1 {
let ids: Vec<&str> = stopped_matches
.iter()
.map(|r| r.record.id.as_str())
.collect();
let _ = writeln!(
err,
"blyte: more than one stopped surface is named {target}; resume by id: {}",
ids.join(", ")
);
return 1;
}
let located = stopped_matches[0];
if running_names.iter().any(|n| n == &located.record.name) {
let _ = writeln!(
err,
"blyte: a running surface is already named {}; stop it or resume by another name",
located.record.name
);
return 1;
}
(
located.record.id.clone(),
located.record.name.clone(),
located.dir.clone(),
)
} else {
let id = match crate::surface_dir::new_surface_id() {
Ok(id) => id,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let name = match crate::surface_dir::pick_name(&repo, args.name.as_deref(), &running_names)
{
Ok(name) => name,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let record_dir = if is_repo {
crate::surface_dir::surface_dir(&main_checkout, &id)
} else {
let store = match crate::surface_dir::folder_store(&state_dir, &main_checkout) {
Ok(store) => store,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
store.join("surfaces").join(&id)
};
(id, name, record_dir)
};
let branch = match current_branch(&main_checkout) {
Ok(b) => b,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
if !config.converse {
config.converse = true;
if config.max_turns == 25 || config.max_turns == 60 {
config.max_turns = 1000;
}
if config.fold_budget.is_none() {
config.fold_budget = Some(100_000);
}
}
config.repo_root = main_checkout.clone();
let is_resume = args.resume.is_some();
let model = resolve_initial_model(&config);
let conversation_path = match crate::conversation_store::conversation_path_for_id(&surface_id) {
Ok(p) => p,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
let _ = err.flush();
return 1;
}
};
let (mut conversation_store, mut loaded_conversation) = if is_resume {
match crate::conversation_store::ConversationStore::load(conversation_path) {
Ok(pair) => pair,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
let _ = err.flush();
return 1;
}
}
} else {
match crate::conversation_store::ConversationStore::new_for_fresh(conversation_path) {
Ok(store) => (store, None),
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
let _ = err.flush();
return 1;
}
}
};
let (resume_memory, needs_digest_rewrite) = match loaded_conversation.as_mut() {
Some(loaded) if !loaded.messages.is_empty() => {
if crate::conversation_store::digest_for_provider_in_memory(loaded, &model) {
(crate::session::ResumeMemoryState::Summarized, true)
} else {
(crate::session::ResumeMemoryState::Loaded, false)
}
}
_ => (crate::session::ResumeMemoryState::NotLoaded, false),
};
let started_dur = match now_duration() {
Ok(d) => d,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let started_at = started_dur.as_secs();
let session_id = new_session_id(started_dur.as_nanos());
if std::env::var("BLYTE_SESSION")
.map(|v| v.is_empty())
.unwrap_or(true)
{
std::env::set_var("BLYTE_SESSION", &session_id);
}
std::env::set_var(crate::usage_log::SURFACE_ID_ENV, &surface_id);
std::env::set_var(crate::usage_log::SURFACE_NAME_ENV, &surface_name);
let token_file_path = match blyte_agent::sandbox::surface_token_path_for_id(&surface_id) {
Ok(p) => p,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let reuse_token_requested = std::env::var_os(RELOAD_REUSE_TOKEN_ENV).is_some();
if reuse_token_requested {
std::env::remove_var(RELOAD_REUSE_TOKEN_ENV);
}
let token = if is_resume && reuse_token_requested {
match read_reused_token_file(&token_file_path) {
Ok(t) => t,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
}
} else {
match generate_token() {
Ok(t) => t,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
}
};
let message_credential = match generate_token() {
Ok(t) => t,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let bind_addr = format!("127.0.0.1:{}", args.port);
let listener = match TcpListener::bind(&bind_addr) {
Ok(l) => l,
Err(e) => {
let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
return 1;
}
};
let actual_port = match listener.local_addr() {
Ok(a) => a.port(),
Err(e) => {
let _ = writeln!(err, "blyte: failed to read listener address: {e}");
return 1;
}
};
if let Err(e) = write_token_file(&token_file_path, &token) {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
let mut token_guard = TokenFileGuard::new(token_file_path.clone());
let message_file_path = match blyte_agent::sandbox::surface_message_path_for_id(&surface_id) {
Ok(p) => p,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
if let Err(e) = write_token_file(&message_file_path, &message_credential) {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
let _message_guard = TokenFileGuard::new(message_file_path);
let mut starting_dir_guard = if is_resume {
StartingDirGuard { dir: None }
} else {
if let Err(e) = crate::surface_dir::prepare_starting_dir(&surface_record_dir) {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
StartingDirGuard {
dir: Some(surface_record_dir.clone()),
}
};
let attachments_dir = match prepare_attachments_dir(&surface_record_dir) {
Ok(p) => p,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
};
let mut read_roots = blyte_agent::tools::read_roots();
if !read_roots.iter().any(|p| p == &attachments_dir) {
read_roots.push(attachments_dir.clone());
blyte_agent::tools::set_read_roots(read_roots);
}
let original_allow_read = config.allow_read.clone();
if !config.allow_read.iter().any(|p| p == &attachments_dir) {
config.allow_read.push(attachments_dir);
}
blyte_agent::tools::set_peer_tools(Some(Arc::new(crate::tell::SurfacePeerTools {
registry_dir: registry_dir.clone(),
surface_id: surface_id.clone(),
surface_name: surface_name.clone(),
repository: repo.clone(),
})));
let entries_log_path = surface_record_dir.join("entries.jsonl");
blyte_agent::tools::set_blyte_surface(Some(surface_id.clone()));
let mut _private_tmp_guard: Option<PrivateTmpDirGuard> = None;
let session = match Session::try_start_with_log_and_resume_io(
model,
Some(entries_log_path),
resume_memory,
err,
|approver| match custom_runner {
Some(factory) => {
let (runner, tmpdir) = factory(&config, approver)?;
_private_tmp_guard = tmpdir.map(|path| PrivateTmpDirGuard { path });
if needs_digest_rewrite {
if let Some(ref loaded) = loaded_conversation {
conversation_store.rewrite(
loaded.model.as_deref(),
loaded.goal.as_deref(),
&loaded.messages,
)?;
}
}
Ok(runner)
}
None => {
let rewrite_payload = if needs_digest_rewrite {
loaded_conversation.clone()
} else {
None
};
let mut runner = AgentRunner::try_new_with_conversation(
&config,
approver,
None,
loaded_conversation,
)?;
_private_tmp_guard = runner.private_tmpdir().map(|path| PrivateTmpDirGuard {
path: path.to_path_buf(),
});
if let Some(ref loaded) = rewrite_payload {
conversation_store.rewrite(
loaded.model.as_deref(),
loaded.goal.as_deref(),
&loaded.messages,
)?;
}
runner.set_conversation_store(conversation_store);
Ok(Box::new(runner) as Box<dyn crate::session::PromptRunner>)
}
},
) {
Ok(s) => s,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
let _ = err.flush();
return 1;
}
};
let runtime = match crate::surface_version::SurfaceRuntimeInfo::current() {
Ok(info) => info,
Err(e) => {
let _ = writeln!(err, "blyte: {e}");
let _ = err.flush();
return 1;
}
};
let record = SurfaceRecord {
id: surface_id.clone(),
name: surface_name.clone(),
pid: std::process::id(),
port: actual_port,
session_id: session_id.clone(),
started_at,
runtime: runtime.clone(),
};
if let Err(e) = crate::surface_dir::write_record_in(&surface_record_dir, &record) {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
starting_dir_guard.disarm();
let registry_entry = crate::surface_registry::RegistryEntry {
id: surface_id.clone(),
name: surface_name.clone(),
root: main_checkout.clone(),
branch,
pid: std::process::id(),
port: actual_port,
started_at,
doing: "idle".to_string(),
state: crate::surface_registry::SurfaceState::Idle,
runtime: runtime.clone(),
};
if let Err(e) = crate::surface_registry::write_entry(®istry_dir, ®istry_entry) {
let _ = writeln!(err, "blyte: {e}");
return 1;
}
let _registry_guard = RegistryEntryGuard {
dir: registry_dir.clone(),
id: surface_id.clone(),
};
let hook_dir = registry_dir.clone();
let hook_entry = registry_entry.clone();
session.set_activity_hook(Box::new(move |prompt, state| {
let doing = match prompt {
Some(text) => {
let line = crate::surface_registry::first_line(text);
if line.is_empty() {
"working".to_string()
} else {
line
}
}
None => "idle".to_string(),
};
let branch = match current_branch(&hook_entry.root) {
Ok(b) => b,
Err(e) => {
eprintln!("blyte: {e}");
return;
}
};
let entry = crate::surface_registry::RegistryEntry {
branch,
doing,
state,
..hook_entry.clone()
};
if let Err(e) = crate::surface_registry::write_entry(&hook_dir, &entry) {
eprintln!("blyte: {e}");
}
}));
if !is_repo {
let _ = writeln!(
err,
"blyte: {} is not a git repository: runs edit this folder in place; combining and publishing are off",
main_checkout.display()
);
let _ = err.flush();
}
let open_codes = OpenCodes::new();
let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
let _ = writeln!(out, "blyte: surface {surface_name} at {url}");
let _ = out.flush();
if !args.no_open && front_end.is_none() {
match issue_initial_open_code(&open_codes, now_duration()) {
Ok(code) => {
let open_url = format!("http://127.0.0.1:{actual_port}/#open={code}");
opener(&open_url);
}
Err(e) => {
let _ = writeln!(err, "blyte: failed to create open code: {e}");
let _ = err.flush();
}
}
}
let stop_surface_name = surface_name.clone();
let reload_surface_id = surface_id.clone();
let reload_workdir = main_checkout.clone();
let is_terminal = front_end.is_some();
let surface = Arc::new(Surface {
surface_id,
surface_name,
root: main_checkout,
repo,
session,
session_id,
started_at,
runtime,
days: args.days,
token,
message_credential,
open_codes,
requests: Arc::new(RequestsState::new()),
publisher: Arc::new(RealPublisher),
reconcile_lock: Mutex::new(()),
reconcile_requested: AtomicBool::new(false),
});
let timer_guard = spawn_reconcile_timer(Arc::clone(&surface));
let _publish_tool_guard = PublishToolGuard::install(Arc::clone(&surface));
let _land_tool_guard = LandToolGuard::install(Arc::clone(&surface));
let front_outcome = front_end.map(|spec| {
let outcome = Arc::new(Mutex::new(None));
let outcome_bg = Arc::clone(&outcome);
let surface_bg = Arc::clone(&surface);
let stop_trigger_bg = Arc::clone(&stop_trigger);
std::thread::spawn(move || {
let ctx = FrontEndContext {
surface: surface_bg,
take_interrupt: spec.take_interrupt,
};
let result =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || (spec.front)(ctx)));
let value = match result {
Ok(code) => FrontEndOutcome::Exited(code),
Err(_) => FrontEndOutcome::Panicked,
};
*outcome_bg.lock().unwrap_or_else(|e| e.into_inner()) = Some(value);
stop_trigger_bg();
});
outcome
});
let reload_requested = Arc::new(AtomicBool::new(false));
let reload_trigger = ReloadTrigger {
requested: Arc::clone(&reload_requested),
stop: Arc::clone(&stop_trigger),
};
let surface_for_reload = Arc::clone(&surface);
let serve_result =
crate::http::serve_until(listener, should_stop, move |req| match now_duration() {
Ok(d) => route_inner(
&surface,
req,
d.as_secs(),
Some(&stop_trigger),
Some(&reload_trigger),
),
Err(e) => json_error(500, e),
});
drop(_land_tool_guard);
drop(_publish_tool_guard);
drop(timer_guard);
if serve_result.is_ok() && reload_requested.load(Ordering::SeqCst) {
let current_model = surface_for_reload.session.info().model;
let exec_path = surface_for_reload.runtime.binary_fingerprint.path.clone();
drop(surface_for_reload);
drop(_registry_guard);
drop(_message_guard);
drop(_private_tmp_guard);
if let Err(e) = crate::surface_version::verify_executable(&exec_path) {
let _ = writeln!(err, "blyte: reload failed: {e}");
let _ = err.flush();
return 1;
}
let reload_args = build_reload_args(
&reload_surface_id,
actual_port,
args,
&config,
&original_allow_read,
¤t_model,
is_terminal,
);
let _ = writeln!(
out,
"blyte: reloading surface {stop_surface_name} with {}",
exec_path.display()
);
let _ = out.flush();
token_guard.disarm();
return exec_reload(
&exec_path,
&reload_args,
&reload_workdir,
&token_file_path,
err,
);
}
drop(surface_for_reload);
match serve_result {
Ok(()) => {
let _ = writeln!(
out,
"blyte: stopped surface {stop_surface_name}; resume with: blyte --resume {stop_surface_name}"
);
let _ = out.flush();
match front_outcome
.as_ref()
.and_then(|o| *o.lock().unwrap_or_else(|e| e.into_inner()))
{
Some(FrontEndOutcome::Exited(code)) => code,
Some(FrontEndOutcome::Panicked) => {
let _ = writeln!(err, "blyte: the front end stopped unexpectedly");
let _ = err.flush();
1
}
None => 0,
}
}
Err(e) => {
let _ = writeln!(err, "blyte: server error: {e}");
1
}
}
}
fn issue_initial_open_code(
open_codes: &OpenCodes,
now: Result<Duration, String>,
) -> Result<String, String> {
let now_secs = now?.as_secs();
open_codes.issue(now_secs)
}
fn canonicalize_attachments_dir(attachments_dir: &Path) -> Result<PathBuf, String> {
std::fs::canonicalize(attachments_dir).map_err(|e| {
format!(
"failed to canonicalize attachments directory {}: {e}",
attachments_dir.display()
)
})
}
fn prepare_attachments_dir(surface_record_dir: &Path) -> Result<PathBuf, String> {
let attachments_dir = crate::attachments::attachments_dir(surface_record_dir);
std::fs::create_dir_all(&attachments_dir)
.map_err(|e| format!("failed to create {}: {e}", attachments_dir.display()))?;
canonicalize_attachments_dir(&attachments_dir)
}
struct StartingDirGuard {
dir: Option<PathBuf>,
}
impl StartingDirGuard {
fn disarm(&mut self) {
self.dir = None;
}
}
impl Drop for StartingDirGuard {
fn drop(&mut self) {
if let Some(ref dir) = self.dir {
crate::surface_dir::cleanup_starting_dir(dir);
}
}
}
fn read_reused_token_file(path: &Path) -> Result<String, String> {
let raw = std::fs::read_to_string(path)
.map_err(|e| format!("cannot reuse surface token from {}: {e}", path.display()))?;
let token = raw.trim().to_string();
if token.is_empty() {
return Err(format!(
"surface token file {} is empty; cannot reuse token on reload",
path.display()
));
}
Ok(token)
}
pub fn build_reload_args(
surface_id: &str,
port: u16,
args: &SurfaceArgs,
config: &ReplConfig,
allow_read: &[PathBuf],
current_model: &str,
is_terminal: bool,
) -> Vec<std::ffi::OsString> {
use std::ffi::OsString;
let mut out: Vec<OsString> = vec![
OsString::from("--resume"),
OsString::from(surface_id),
OsString::from("--port"),
OsString::from(port.to_string()),
OsString::from("--no-open"),
];
if is_terminal {
out.push(OsString::from("--terminal"));
} else {
let open_in = match args.open_in {
OpenIn::App => "app",
OpenIn::Browser => "browser",
};
out.push(OsString::from("--open-in"));
out.push(OsString::from(open_in));
}
out.push(OsString::from("--days"));
out.push(OsString::from(args.days.to_string()));
if !current_model.trim().is_empty() {
out.push(OsString::from("--model"));
out.push(OsString::from(current_model));
}
if let Some(ref dispatch_cmd) = config.dispatch_cmd {
out.push(OsString::from("--converse"));
out.push(OsString::from("--dispatch-cmd"));
out.push(OsString::from(dispatch_cmd));
} else if let Some(ref gate) = config.gate {
out.push(OsString::from("--gate"));
out.push(OsString::from(gate));
}
out.push(OsString::from("--context"));
out.push(OsString::from(&config.context_strategy));
if let Some(ref container) = config.container {
out.push(OsString::from("--container"));
out.push(OsString::from(container));
}
out.push(OsString::from("--max-turns"));
out.push(OsString::from(config.max_turns.to_string()));
out.push(OsString::from("--max-gates"));
out.push(OsString::from(config.max_gates.to_string()));
out.push(OsString::from(format!("--rollback={}", config.rollback)));
if let Some(fold_budget) = config.fold_budget {
out.push(OsString::from("--fold-budget"));
out.push(OsString::from(fold_budget.to_string()));
}
out.push(OsString::from("--sandbox"));
out.push(OsString::from(&config.sandbox));
if let Some(ref network) = config.network {
out.push(OsString::from("--network"));
out.push(OsString::from(network));
}
for path in allow_read {
out.push(OsString::from("--allow-read"));
out.push(path.as_os_str().to_os_string());
}
for var in &config.pass_env {
out.push(OsString::from("--pass-env"));
out.push(OsString::from(var));
}
out
}
#[cfg(unix)]
fn exec_reload<W: Write + ?Sized>(
exec_path: &Path,
reload_args: &[std::ffi::OsString],
workdir: &Path,
token_file_path: &Path,
err: &mut W,
) -> i32 {
use std::os::unix::process::CommandExt;
let exec_err = std::process::Command::new(exec_path)
.args(reload_args)
.current_dir(workdir)
.env(RELOAD_REUSE_TOKEN_ENV, "1")
.exec();
let _ = std::fs::remove_file(token_file_path);
let _ = writeln!(
err,
"blyte: failed to re-exec {}: {exec_err}",
exec_path.display()
);
let _ = err.flush();
1
}
#[cfg(not(unix))]
fn exec_reload<W: Write + ?Sized>(
exec_path: &Path,
reload_args: &[std::ffi::OsString],
workdir: &Path,
token_file_path: &Path,
err: &mut W,
) -> i32 {
match std::process::Command::new(exec_path)
.args(reload_args)
.current_dir(workdir)
.env(RELOAD_REUSE_TOKEN_ENV, "1")
.status()
{
Ok(status) => match status.code() {
Some(code) => code,
None => 1,
},
Err(e) => {
let _ = std::fs::remove_file(token_file_path);
let _ = writeln!(
err,
"blyte: failed to re-launch {}: {e}",
exec_path.display()
);
let _ = err.flush();
1
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn canonicalize_attachments_dir_errors_when_missing() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("does-not-exist").join("attachments");
let err = canonicalize_attachments_dir(&missing).unwrap_err();
assert!(
err.contains(&missing.display().to_string()),
"expected error to name missing path, got: {err}"
);
assert!(err.contains("canonicalize"), "unexpected error: {err}");
}
#[cfg(unix)]
#[test]
fn canonicalize_attachments_dir_errors_on_dangling_symlink() {
let dir = tempfile::tempdir().unwrap();
let dangling = dir.path().join("attachments");
std::os::unix::fs::symlink(dir.path().join("missing-target"), &dangling).unwrap();
let err = canonicalize_attachments_dir(&dangling).unwrap_err();
assert!(
err.contains(&dangling.display().to_string()),
"expected error to name symlink path, got: {err}"
);
assert!(err.contains("canonicalize"), "unexpected error: {err}");
}
#[test]
fn prepare_attachments_dir_errors_when_attachments_path_is_a_file() {
let dir = tempfile::tempdir().unwrap();
let blocker = crate::attachments::attachments_dir(dir.path());
std::fs::write(&blocker, b"not a dir").unwrap();
let err = prepare_attachments_dir(dir.path()).unwrap_err();
assert!(
err.contains(&blocker.display().to_string()),
"expected error to name path, got: {err}"
);
}
fn poisoned_open_codes() -> OpenCodes {
let codes = OpenCodes::new();
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _guard = codes.entries.lock().unwrap();
panic!("poison");
}));
codes
}
#[test]
fn open_codes_issue_errors_when_lock_poisoned() {
let codes = poisoned_open_codes();
let err = codes.issue(100).unwrap_err();
assert!(err.contains("open codes"), "unexpected error: {err}");
assert!(err.contains("poison"), "unexpected error: {err}");
}
#[test]
fn open_codes_redeem_errors_when_lock_poisoned() {
let codes = poisoned_open_codes();
let err = codes.redeem("some-code", 100).unwrap_err();
assert!(err.contains("open codes"), "unexpected error: {err}");
assert!(err.contains("poison"), "unexpected error: {err}");
}
#[test]
fn issue_initial_open_code_errors_when_clock_fails() {
let codes = OpenCodes::new();
let err = issue_initial_open_code(
&codes,
Err("system clock is before Unix epoch: test".to_string()),
)
.unwrap_err();
assert!(err.contains("system clock"), "unexpected error: {err}");
assert!(codes.entries.lock().unwrap().is_empty());
let code = issue_initial_open_code(&codes, Ok(Duration::from_secs(500))).unwrap();
assert!(codes.redeem(&code, 500).unwrap());
}
}