Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

20.5 KB
Raw Blame
//! Settings → Computer: whether bots use this computer (its Chrome and shell) or the isolated
//! vm containers, and the approval every local shell command needs.
use super::AppState;
use crate::broker::{ApprovalDecision, ApprovalRequest};
use crate::db::models::NewApproval;
use crate::drivers::events::RuntimeEvent;
use crate::sandbox::agent_vm;
use crate::sandbox::computer::{self, ComputerMode};
use axum::{extract::State, http::StatusCode, Json};
use serde::Deserialize;
use serde_json::{json, Value};
use std::path::Path;

/// The mode in force: the saved choice, else `KWNT_COMPUTER_MODE`, else the platform default.
pub async fn current_mode(state: &AppState) -> ComputerMode {
    let saved = state
        .db
        .get_setting(computer::SETTING_KEY)
        .await
        .ok()
        .flatten();
    computer::current_mode(saved.as_deref())
}

/// Points the browser service at the mode in force. On a change the old browser is
/// disconnected (never closed) and the next browser call opens a page in the new one.
pub async fn apply_mode(state: &AppState) -> ComputerMode {
    let mode = current_mode(state).await;
    if state.browser_service.mode() != mode {
        let mut controllers = state.browser_controllers.lock().await;
        if state.browser_service.set_mode(mode).await {
            for team_id in controllers.drain().map(|(id, _)| super::browser_pages::page_team(&id).to_string()).collect::<std::collections::BTreeSet<_>>() {
                let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {
                    team_id,
                    container_name: "browser-service".into(),
                    is_running: false,
                });
            }
        }
    }
    mode
}

/// The view, asking Docker once (`docker version`, up to 3 s).
async fn view(state: &AppState) -> Value {
    let docker = state.sandbox_manager.is_docker_available().await;
    view_with(state, docker).await
}

/// The view for a Docker answer the caller already has, so one request asks Docker once and its
/// checks and its reply can't disagree (a save used to ask up to three times).
async fn view_with(state: &AppState, docker: bool) -> Value {
    let mode = current_mode(state).await;
    let local = computer::local_reason();
    let vm = computer::vm_unavailable_reason(
        docker,
        state.browser_service.has_endpoint(),
        crate::doctor::Platform::detect(),
    );
    let window = computer::window_reason();
    let isolate_claude = isolate_claude_setting(state).await;
    let (claude_cli, _) = crate::drivers::engines::EngineId::of_family(crate::profiles::Engine::Claude);
    let (toggle, agents) = state
        .agent_vm
        .view(agent_vm::ViewInputs {
            setting_on: isolate_claude,
            vm_mode: mode == ComputerMode::Vm,
            docker,
            cli_account: state.engines.is_enabled(claude_cli),
        })
        .await;
    json!({
        "mode": mode,
        "available": {"local": local.is_none(), "vm": vm.is_none()},
        "reasons": {"local": local, "vm": vm},
        "isolates": computer::vm_isolates(docker),
        "window": {
            "visible": mode == ComputerMode::Local && state.browser_service.local_window(),
            "available": window.is_none(),
            "reason": window,
        },
        // The private browser kwnt downloads when there's no Chrome (O5). The UI shows its
        // `error` line, with "Try again", only while `state` is "failed".
        "browser_setup": state.browser_service.chrome_setup().view(),
        // Run Claude inside the VM (design/ui.md): the saved switch, whether it can be turned
        // on now, and where each engine runs right now
        "isolate_claude": isolate_claude,
        "isolate_claude_toggle": toggle,
        "agents": agents,
    })
}

/// The person's "Run Claude inside the VM" switch (off unless they turned it on).
pub async fn isolate_claude_setting(state: &AppState) -> bool {
    state.db.get_setting(agent_vm::SETTING_KEY).await.ok().flatten().is_some_and(|v| v == "true")
}

/// `POST /api/settings/computer/browser`: "Try again" for the bots' private browser. Starts the
/// download again in the background and answers at once with the view (`browser_setup.state` is
/// then `downloading`, or `ready` if a browser is already there).
pub async fn retry_browser(State(state): State<AppState>) -> Json<Value> {
    state.browser_service.chrome_setup().retry();
    // let the background start mark itself downloading before answering
    for _ in 0..20 {
        let s = state.browser_service.chrome_setup().view().state;
        if s != crate::sandbox::chrome_download::SetupState::Failed {
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
    }
    Json(view(&state).await)
}

/// `GET /api/settings/computer`
pub async fn get_computer(State(state): State<AppState>) -> Json<Value> {
    Json(view(&state).await)
}

#[derive(Deserialize)]
pub struct ComputerPayload {
    pub mode: Option<ComputerMode>,
    pub isolate_claude: Option<bool>,
}

/// `PUT /api/settings/computer` with `{"mode":"local"|"vm"}` and/or `{"isolate_claude":bool}`:
/// saves the choice and switches at once. 400 for an unknown mode or one this computer cannot run
/// (with the reason), and for turning isolation on where the switch is unavailable (its `reason`).
/// Turning it off always works. Turning it on starts Claude's VM download in the background.
pub async fn put_computer(
    State(state): State<AppState>,
    payload: Result<Json<ComputerPayload>, axum::extract::rejection::JsonRejection>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
    let bad = |m: String| (StatusCode::BAD_REQUEST, Json(json!({ "error": m })));
    let failed = |e: crate::db::DbError| (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() })));
    let Json(ComputerPayload { mode, isolate_claude }) = payload
        .map_err(|_| bad("Send mode (\"local\" or \"vm\") and/or isolate_claude (true or false)".into()))?;
    if mode.is_none() && isolate_claude.is_none() {
        return Err(bad("Send mode (\"local\" or \"vm\") and/or isolate_claude (true or false)".into()));
    }
    // Ask Docker once for the whole save: the checks below and the reply use the same answer
    // (switching mode doesn't change whether Docker runs)
    let docker = state.sandbox_manager.is_docker_available().await;
    if let Some(on) = isolate_claude {
        if on {
            let current = view_with(&state, docker).await;
            if current["isolate_claude_toggle"]["available"] != json!(true) {
                // People's words in `error` (the Settings error line prints it); the code apart
                let reason = current["isolate_claude_toggle"]["reason"].as_str().unwrap_or("unavailable").to_string();
                let error = agent_vm::toggle_message(&reason);
                return Err((StatusCode::BAD_REQUEST, Json(json!({ "error": error, "code": reason }))));
            }
        }
        state.db.set_setting(agent_vm::SETTING_KEY, if on { "true" } else { "false" }).await.map_err(failed)?;
        if on {
            state.agent_vm.start_setup();
        }
    }
    let Some(mode) = mode else {
        return Ok(Json(view_with(&state, docker).await));
    };
    let current = view_with(&state, docker).await;
    if current["available"][mode.as_str()] != json!(true) {
        let reason = current["reasons"][mode.as_str()]
            .as_str()
            .unwrap_or("unavailable");
        return Err(bad(reason.to_string()));
    }
    state
        .db
        .set_setting(computer::SETTING_KEY, mode.as_str())
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": e.to_string() })),
            )
        })?;
    apply_mode(&state).await;
    Ok(Json(view_with(&state, docker).await))
}

#[derive(Deserialize)]
pub struct WindowPayload {
    pub visible: bool,
    /// With `visible`: the window is for a sign-in that refuses windowless browsers (the live
    /// view's "Sign in in Chrome"), so kwant puts Chrome back in the app once the pages have left
    /// the sign-in.
    #[serde(default)]
    pub until_signed_in: bool,
}

/// `PUT /api/settings/computer/window` with `{"visible":bool}`: in local mode, shows the bots'
/// Chrome as a real window (for a sign-in or CAPTCHA) or puts it back in the app. Each bot's open
/// page is reopened in the other form. 400 outside local mode or with no display for a window;
/// 502 if Chrome could not be restarted (the previous form is kept). `until_signed_in` puts it
/// back by itself when the sign-in is over (see [`back_after_signin`]).
pub async fn put_window(
    State(state): State<AppState>,
    payload: Result<Json<WindowPayload>, axum::extract::rejection::JsonRejection>,
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
    let fail = |status, m: String| (status, Json(json!({ "error": m })));
    let Json(WindowPayload { visible, until_signed_in }) = payload
        .map_err(|_| fail(StatusCode::BAD_REQUEST, "visible must be true or false".into()))?;
    if apply_mode(&state).await != ComputerMode::Local {
        return Err(fail(
            StatusCode::BAD_REQUEST,
            "The browser runs in the VM, which has no window to open. Switch to Local computer first.".into(),
        ));
    }
    if visible {
        if let Some(reason) = computer::window_reason() {
            return Err(fail(StatusCode::BAD_REQUEST, reason));
        }
    }
    // a newer switch, either way, ends the wait of an earlier sign-in
    let generation = WINDOW_SWITCHES.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
    if let Err(error) = switch_window(&state, visible).await {
        tracing::warn!("Could not restart local Chrome: {}", error);
        return Err(fail(StatusCode::BAD_GATEWAY, format!("Could not restart Chrome: {error}")));
    }
    if visible && until_signed_in {
        tokio::spawn(back_after_signin(state.clone(), generation));
    }
    Ok(Json(view(&state).await))
}

/// Counts window switches, so a sign-in wait can tell a newer switch happened.
static WINDOW_SWITCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Restarts the local Chrome with or without a window. The restarted Chrome has new pages: every
/// controller must reconnect, and each live view is told.
async fn switch_window(state: &AppState, visible: bool) -> Result<(), crate::sandbox::browser::BrowserError> {
    let mut controllers = state.browser_controllers.lock().await;
    state.browser_service.set_local_window(visible).await?;
    for team_id in controllers.drain().map(|(id, _)| super::browser_pages::page_team(&id).to_string()).collect::<std::collections::BTreeSet<_>>() {
        let _ = state.event_sender.send(RuntimeEvent::SandboxStatusChanged {
            team_id,
            container_name: "browser-service".into(),
            is_running: false,
        });
    }
    Ok(())
}

/// After "Sign in in Chrome": puts Chrome back in the app once no page is on a sign-in host any
/// more (two checks 2 s apart, after one was seen there). Stops waiting when the person put it
/// back themselves, another switch happened, Chrome closed, or after 30 minutes.
async fn back_after_signin(state: AppState, generation: u64) {
    use crate::sandbox::signin_gate;
    let current = || WINDOW_SWITCHES.load(std::sync::atomic::Ordering::SeqCst) == generation;
    let started = std::time::Instant::now();
    let mut seen = false;
    let mut gone = 0;
    while started.elapsed() < std::time::Duration::from_secs(30 * 60) {
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;
        if !current() || !state.browser_service.local_window() { return; }
        let Some(urls) = state.browser_service.local_page_urls().await else { return };
        let on_signin = urls.iter().any(|url| signin_gate::provider(url).is_some());
        seen |= on_signin;
        gone = if seen && !on_signin { gone + 1 } else { 0 };
        if gone >= 2 {
            if !current() { return; }
            WINDOW_SWITCHES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            match switch_window(&state, false).await {
                Ok(()) => tracing::info!("the sign-in in the Chrome window is over: back in the app"),
                Err(error) => tracing::warn!("Could not put Chrome back in the app after a sign-in: {}", error),
            }
            return;
        }
    }
}

/// The approvals the person set for the bot or team a local command runs for: a bot's own
/// setting, else the space of the bot or team. An unreadable setting asks.
async fn local_shell_approvals(state: &AppState, target_id: &str) -> String {
    use crate::db::approval_modes::ASK;
    if let Ok(Some(_)) = state.db.space_of_kwant(target_id).await {
        return state.db.kwant_approvals(target_id).await.map_or_else(|_| ASK.into(), |m| m.effective);
    }
    match state.db.space_of_team(target_id).await {
        Ok(Some(space)) => state.db.space_approvals(&space).await.unwrap_or_else(|_| ASK.into()),
        _ => ASK.into(),
    }
}

/// Asks the person before a shell command runs on their own computer, with no conversation to
/// remember "always allow" in (see [`approve_local_shell_in`]).
pub async fn approve_local_shell(state: &AppState, target_id: &str, command: &str, cwd: &Path) -> bool {
    approve_local_shell_with(state, target_id, command, cwd, None, None).await
}

/// [`approve_local_shell`] for a push the person's Retry or Override on a pre-push card may
/// already have approved (0.9.7): with `grant`, no card unless a floor asks.
pub async fn approve_local_shell_granted(state: &AppState, target_id: &str, command: &str, cwd: &Path, grant: Option<&crate::mcp::PrepushGrant>) -> bool {
    approve_local_shell_with(state, target_id, command, cwd, None, grant).await
}

/// Asks the person before a shell command runs on their own computer. Approvals `off` run it;
/// "Ask only when risky" runs it when [`crate::mcp::shell_risk`] finds it safe in `cwd`, and
/// remembers "Always this session" for `execute_shell` in `conversation`. Under `ask` every
/// command asks and "always allow" counts for this one command only.
pub async fn approve_local_shell_in(state: &AppState, target_id: &str, command: &str, cwd: &Path, conversation: Option<&str>) -> bool {
    approve_local_shell_with(state, target_id, command, cwd, conversation, None).await
}

/// [`approve_local_shell_in`]; a `grant` (0.9.7) runs the command with no card when the payment
/// floor, Flight School and the production floor don't ask, and is used up.
async fn approve_local_shell_with(
    state: &AppState,
    target_id: &str,
    command: &str,
    cwd: &Path,
    conversation: Option<&str>,
    grant: Option<&crate::mcp::PrepushGrant>,
) -> bool {
    use crate::db::approval_modes::{OFF, SMART};
    let mode = local_shell_approvals(state, target_id).await;
    let verdict = (mode == SMART).then(|| match cwd.canonicalize() {
        Ok(folder) => crate::mcp::shell_risk::classify(command, &folder),
        Err(_) => crate::mcp::SmartVerdict::Ask("the bot's folder doesn't exist".into()),
    });
    let mut details = json!({
        "source": "local_shell",
        "tool": "execute_shell",
        "arguments": {"command": command, "cwd": cwd.to_string_lossy()},
        "kwant_id": target_id,
    });
    if let Some(v) = &verdict {
        details["smart_reason"] = json!(v.reason());
    }
    // The payment floor (D8): a command that pays always asks, and "always allow" covers it once
    let payment = crate::mcp::payment_floor::shell_reason(command);
    if let Some(why) = &payment {
        details["payment_reason"] = json!(why);
    }
    // Flight School (C3): below act, a command kwant runs always asks, approvals off or not
    let tier = match payment {
        Some(_) => None,
        None => super::missions::flight_school::shell_gate(&state.db, target_id).await,
    };
    if let Some(why) = &tier {
        details["tier_reason"] = json!(why);
    }
    // The production floor (plan §3.5): in a Dev mode space, a command that can reach production
    // always asks, and "always allow" covers this one command
    let floor = super::dev::floor::for_shell(&state.db, target_id, command, cwd).await;
    if let Some((_, card)) = &floor {
        details["prod_floor"] = card.clone();
    }
    // "Always this session" under smart: per bot and conversation, like claude's tools
    let remembered = conversation.filter(|_| mode == SMART && payment.is_none() && floor.is_none());
    if crate::sandbox::credentials::call_touches_kwnt_secrets(&details["arguments"], Some(cwd)) {
        tracing::warn!(target = %target_id, "refused a shell command that names kwnt's secret files");
        let record = NewApproval {
            turn_id: String::new(),
            kwant_id: target_id.to_string(),
            tool_name: "execute_shell".into(),
            parameters: details,
        };
        if let Err(e) = state.db.save_refused(&record).await {
            tracing::warn!(error = %e, "could not record a refused command");
        }
        return false;
    }
    // The person's Retry or Override approved this push already: no card, and the grant is used up
    if let Some(g) = grant.filter(|_| payment.is_none() && tier.is_none() && floor.is_none()) {
        if super::dev::prepush::use_grant(&state.db, &state.event_sender, g).await {
            tracing::info!(target = %target_id, grant = %g.id, card = %g.pressed_card_id, "ran a local push the person's {} approved", g.kind);
            details["prepush_grant"] = super::mcp_runtime::grant_details(g);
            let record = NewApproval { turn_id: String::new(), kwant_id: target_id.to_string(), tool_name: "execute_shell".into(), parameters: details };
            if let Err(e) = state.db.save_granted(&record).await {
                tracing::warn!(error = %e, "could not record a local push the person's grant approved");
            }
            return true;
        }
    }
    if let Some(conversation) = remembered {
        if state.broker.is_allowed_for_session(target_id, conversation, "execute_shell").await {
            return true;
        }
    }
    if payment.is_none() && tier.is_none() && floor.is_none() && (mode == OFF || verdict.as_ref().is_some_and(|v| v.is_allowed())) {
        if verdict.is_some() {
            tracing::info!(target = %target_id, "ran a local command without a card: not risky");
        }
        let record = NewApproval {
            turn_id: String::new(),
            kwant_id: target_id.to_string(),
            tool_name: "execute_shell".into(),
            parameters: details,
        };
        if let Err(e) = state.db.save_auto_allowed(&record).await {
            tracing::warn!(error = %e, "could not record a command that ran with approvals off");
        }
        return true;
    }
    // 31k: the waiter first, then the row, so a listed card is always answerable
    let ticket = uuid::Uuid::new_v4().to_string();
    let rx = state
        .broker
        .request_approval(ApprovalRequest {
            id: ticket.clone(),
            kwant_id: target_id.to_string(),
            tool_name: "execute_shell".into(),
            details: details.clone(),
        })
        .await;
    let saved = state
        .db
        .save_approval_with_id(
            &ticket,
            &NewApproval {
                turn_id: String::new(),
                kwant_id: target_id.to_string(),
                tool_name: "execute_shell".into(),
                parameters: details.clone(),
            },
            None,
        )
        .await;
    if let Err(e) = saved {
        state.broker.cancel(&ticket).await;
        tracing::warn!(error = %e, "could not store local shell approval; denying");
        return false;
    }
    super::mcp_runtime::card_listed(target_id).await;
    let _ = state.event_sender.send(RuntimeEvent::ApprovalRequired {
        id: ticket.clone(),
        tool_name: "execute_shell".into(),
        details,
    });
    match tokio::time::timeout(super::mcp_runtime::APPROVAL_TIMEOUT, rx).await {
        Ok(Ok(ApprovalDecision::AllowOnce)) => true,
        Ok(Ok(ApprovalDecision::AlwaysAllowSession)) => {
            if let Some(conversation) = remembered {
                state.broker.allow_for_session(target_id, conversation, "execute_shell").await;
            }
            true
        }
        Ok(_) => false,
        Err(_) => {
            if state.broker.cancel(&ticket).await {
                let _ = state.db.update_approval_status(&ticket, "expired").await;
                let _ = state
                    .event_sender
                    .send(RuntimeEvent::approval_withdrawn(ticket, "expired", None));
            }
            false
        }
    }
}