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.

34.0 KB
Raw Blame
//! One-tap questions (batch 2 / C). An agent calls `ask_user` mid-turn: the question is saved as
//! a card in its chat, the UI gets `question_updated` + `message_added` and a `question_asked`
//! notification, and the tool waits for the answer while the turn stays live (and stoppable).
//! Only that turn waits: the agent's other chats and threads run as usual, since each turn has
//! its own job and slot. If nobody answers in time the tool tells the agent to wrap up, and a
//! later answer starts a new turn in the same chat with it.

use super::continuity::{notify, Notification, SelfScope};
use super::routes::{scope_for, try_kwant_turn, TurnOpts};
use super::AppState;
use crate::db::models::{MessageExtra, NewMessage};
use crate::db::questions::{clean_question, Question, QuestionError, QuestionPlace, QuestionReason, MAX_ANSWER_CHARS, QUESTION_STATUSES};
use crate::drivers::events::RuntimeEvent;
use axum::{
    extract::{Path, Query, State},
    http::{header, HeaderMap, StatusCode},
    response::{IntoResponse, Response},
    Json,
};
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::Duration;
use tokio::sync::oneshot;

/// What a waiting `ask_user` call is woken with.
#[derive(Debug)]
pub enum Reply {
    Answer(String),
    Dismissed,
}

/// The `ask_user` calls waiting for an answer, by question id. Empty (no cost) when unused.
pub struct QuestionHub {
    waiters: Mutex<HashMap<String, oneshot::Sender<Reply>>>,
    wait_ms: AtomicU64,
}

impl Default for QuestionHub {
    fn default() -> Self {
        Self {
            waiters: Mutex::default(),
            // Shorter than the CLIs' tool timeout (approval timeout + 30 s), so the tool answers first
            wait_ms: AtomicU64::new((crate::mcp::APPROVAL_TIMEOUT_SECS - 10) * 1000),
        }
    }
}

impl QuestionHub {
    /// How long `ask_user` waits before telling the agent to wrap up (tests shorten it).
    pub fn set_wait(&self, wait: Duration) {
        self.wait_ms.store(wait.as_millis() as u64, Ordering::Relaxed);
    }

    fn wait(&self) -> Duration {
        Duration::from_millis(self.wait_ms.load(Ordering::Relaxed))
    }

    fn register(&self, id: &str) -> oneshot::Receiver<Reply> {
        let (tx, rx) = oneshot::channel();
        self.waiters.lock().unwrap().insert(id.to_string(), tx);
        rx
    }

    fn take(&self, id: &str) -> Option<oneshot::Sender<Reply>> {
        self.waiters.lock().unwrap().remove(id)
    }

    /// Whether a live turn is waiting on this question.
    pub fn is_waiting(&self, id: &str) -> bool {
        self.waiters.lock().unwrap().contains_key(id)
    }
}

/// Removes the waiter when the tool call ends any way (also when the CLI hangs up).
struct WaiterGuard<'a> {
    hub: &'a QuestionHub,
    id: String,
}

impl Drop for WaiterGuard<'_> {
    fn drop(&mut self) {
        self.hub.take(&self.id);
    }
}

fn card_meta(q: &Question) -> Value {
    json!({
        "kind": "ask_user",
        "question_id": q.id,
        "question": q.question,
        "choices": q.choice_list(),
        "status": q.status,
        "answer": q.answer,
        "why_you": q.why_you,
        "checked": q.checked,
    })
}

fn place_message(q: &Question, role: &str, sender: &str, text: String) -> (NewMessage, MessageExtra) {
    (
        NewMessage {
            channel_id: q.channel_id.clone(),
            direct_kwant_id: q.direct_kwant_id.clone(),
            sender_role: role.into(),
            sender_id: sender.into(),
            text,
            reasoning_content: None,
            tool_calls: None,
            tokens_used: 0,
        },
        MessageExtra { thread_id: q.thread_id.clone(), meta: None },
    )
}

async fn save_message(state: &AppState, q: &Question, role: &str, sender: &str, text: String, meta: Value) -> Option<String> {
    let (msg, extra) = place_message(q, role, sender, text);
    let saved = state.db.insert_message_with(&msg, &MessageExtra { meta: Some(meta), ..extra }).await.ok()?;
    if let Some(t) = &q.thread_id {
        let _ = state.db.touch_thread(t).await;
    }
    let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or(Value::Null) });
    Some(saved.id)
}

/// Sends `question_updated` and refreshes the question's card in the chat.
async fn changed(state: &AppState, q: &Question) {
    if let Some(mid) = &q.message_id {
        let mut meta = card_meta(q);
        // Keys kwnt added to the card (a keep-going card's marker) outlive its answer
        let old = state.db.get_message(mid).await.ok().flatten().and_then(|m| serde_json::from_str::<Value>(m.meta.as_deref()?).ok());
        if let (Some(Value::Object(old)), Some(new)) = (old, meta.as_object_mut()) {
            for (k, v) in old {
                new.entry(k).or_insert(v);
            }
        }
        let _ = state.db.set_message_meta(mid, &meta).await;
    }
    let _ = state.event_sender.send(RuntimeEvent::QuestionUpdated { question: serde_json::to_value(q).unwrap_or(Value::Null) });
}

/// Closes an open question and announces it; `None` if it wasn't open any more.
async fn close(state: &AppState, id: &str, status: &str, answer: Option<&str>) -> Option<Question> {
    close_via(state, id, status, answer, None).await
}

/// [`close`], noting where it was answered (`answered_via`, e.g. "telegram") before it's announced.
async fn close_via(state: &AppState, id: &str, status: &str, answer: Option<&str>, via: Option<&str>) -> Option<Question> {
    if !state.db.close_question(id, status, answer).await.ok()? {
        return None;
    }
    if let Some(via) = via {
        let _ = state.db.set_answered_via("questions", id, via).await;
    }
    // Nothing waits on the person for it any more, and its reminder (if not sent yet) never goes out
    let rows = state.db.close_waiting_for_question(id).await.unwrap_or_default();
    super::waiting::closed(state, &rows, super::waiting::REASON_ANSWERED);
    let q = state.db.get_question(id).await.ok().flatten()?;
    changed(state, &q).await;
    if status == "answered" {
        super::decide::note_answer(state, &q).await;
    }
    Some(q)
}

// Agent tool

/// When to ask: only for a step that can't be undone or reaches outside, or a choice with no
/// sensible default. Reversible choices are made, stated and carried on with.
pub const ASK_USER_DESCRIPTION: &str = "Ask the user one short question, only when you can't go on without their decision: \
    a step that can't be undone or reaches outside (sending, publishing, paying, deleting, contacting someone), or a choice \
    with no sensible default. For a reversible choice (wording, order, which of two fine options, a setting that can be \
    changed later) don't ask: pick the sensible option, state the assumption in your reply and continue. \
    Give 2 to 5 short choices; the user can also type their own answer. Your turn waits for the answer \
    (a few minutes at most) and the tool returns it. Don't ask what you can find out or decide yourself. \
    Say why only the user can answer (why_you) and what you already checked (checked).";

/// Why only the person can answer: the values `ask_user`'s `why_you` takes.
pub const WHY_YOU: [&str; 6] = ["irreversible", "outside", "money", "secret_or_signin", "taste_no_signal", "missing_after_research"];

/// Longest `checked` kept, in characters.
pub const MAX_CHECKED_CHARS: usize = 500;

/// Person decision notes after which "no signal on their taste" stops being a reason to ask.
pub const TASTE_NOTES: usize = 3;

/// The tool's answer to an `ask_user` call without a reason.
pub const DECIDE_YOURSELF: &str = "Not asked: decide it yourself. Pick the option you think is best, apply it, and say in \
    your reply what you chose, why, and that the user can change it. If only the user can answer (it can't be undone, \
    reaches outside, costs money, needs a secret or sign-in, or research found nothing), call ask_user again with why_you \
    and checked (what you already looked at).";

/// The tool's answer to "no signal on their taste" once there are notes on how the person decides.
pub const PREDICT_TASTE: &str = "Not asked: there are notes on how the user usually decides (see [How the person usually \
    decides]). Predict their pick from those, apply it, and say it was predicted from their earlier choices and how to \
    change it.";

pub fn tools() -> Vec<Value> {
    vec![json!({
        "name": "ask_user",
        "description": ASK_USER_DESCRIPTION,
        "inputSchema": {
            "type": "object",
            "properties": {
                "question": {"type": "string", "description": "The question (max 500 characters)"},
                "choices": {
                    "type": "array",
                    "items": {"type": "string"},
                    "minItems": 2,
                    "maxItems": 5,
                    "description": "2 to 5 short answers to pick from (max 80 characters each)",
                },
                "why_you": {
                    "type": "string",
                    "enum": WHY_YOU,
                    "description": "Why only the user can answer: irreversible, outside (contacts someone), money, \
                        secret_or_signin, taste_no_signal (a taste choice with nothing to go on), or missing_after_research",
                },
                "checked": {"type": "string", "description": "What you already checked or tried before asking (max 500 characters)"},
            },
            "required": ["question", "choices", "why_you", "checked"],
        },
    })]
}

pub async fn tool_ask(state: &AppState, scope: &SelfScope, args: &Value) -> (String, bool) {
    let (Some(origin), Some(cancel)) = (&scope.origin, &scope.cancel) else {
        return ("You can only ask the user from a chat.".into(), true);
    };
    let choices: Vec<String> = match args["choices"].as_array() {
        Some(list) => list.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect(),
        None => Vec::new(),
    };
    let (question, choices) = match clean_question(args["question"].as_str().unwrap_or(""), &choices) {
        Ok(v) => v,
        Err(e) => return (e.to_string(), true),
    };
    let why_you = args["why_you"].as_str().map(str::trim).filter(|w| WHY_YOU.contains(w)).map(str::to_string);
    let checked: Option<String> =
        args["checked"].as_str().map(str::trim).filter(|c| !c.is_empty()).map(|c| c.chars().take(MAX_CHECKED_CHARS).collect());
    // With decide-first on, a question needs a reason only the person can answer it
    if super::decide::enabled(state).await {
        if why_you.is_none() || checked.is_none() {
            return (DECIDE_YOURSELF.into(), true);
        }
        if why_you.as_deref() == Some("taste_no_signal") {
            let space = state.db.space_of_kwant(&scope.kwant_id).await.ok().flatten();
            let notes = match &space {
                Some(s) => state.db.list_decision_notes(s, &["answered", "changed"], TASTE_NOTES as i64).await.unwrap_or_default().len(),
                None => 0,
            };
            if notes >= TASTE_NOTES {
                return (PREDICT_TASTE.into(), true);
            }
        }
    }
    let place = QuestionPlace {
        kwant_id: scope.kwant_id.clone(),
        channel_id: origin.channel_id.clone(),
        direct_kwant_id: origin.direct_kwant_id.clone(),
        thread_id: origin.thread_id.clone(),
        turn_id: scope.turn_id.clone(),
    };
    // The question, its card and the waiter appear together: the waiter is registered inside the
    // transaction, so neither a list poll nor a very fast answer can see one without the others.
    // The text keeps the choices readable in history and for older clients; the card uses meta
    let hub = &state.questions;
    let reason = QuestionReason { why_you: why_you.as_deref(), checked: checked.as_deref() };
    let mut waiter = None;
    let created = state
        .db
        .create_question_with_card(&place, &question, &choices, reason, |q| {
            waiter = Some((q.id.clone(), hub.register(&q.id)));
            let text = format!("{}\n\nChoices: {}", q.question, choices.join(" · "));
            let (msg, extra) = place_message(q, "kwant", &scope.kwant_id, text);
            Some((msg, MessageExtra { meta: Some(card_meta(q)), ..extra }))
        })
        .await;
    let (q, card) = match created {
        Ok(v) => v,
        Err(e) => {
            if let Some((id, _)) = waiter {
                hub.take(&id);
            }
            return match e {
                QuestionError::Db => ("Could not save the question.".into(), true),
                e => (e.to_string(), true),
            };
        }
    };
    let Some((_, mut rx)) = waiter else {
        return ("Could not save the question.".into(), true);
    };
    let _guard = WaiterGuard { hub, id: q.id.clone() };
    if let Some(card) = card {
        if let Some(t) = &q.thread_id {
            let _ = state.db.touch_thread(t).await;
        }
        let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&card).unwrap_or(Value::Null) });
    }
    changed(state, &q).await;
    notify(
        state,
        Notification {
            kind: "question_asked",
            kwant_id: scope.kwant_id.clone(),
            kwant_name: scope.kwant_name.clone(),
            channel_id: origin.channel_id.clone(),
            title: format!("{} has a question", scope.kwant_name),
            body: "Open the chat to answer.".into(),
            thread_id: q.thread_id.clone(),
            card_id: None,
        },
    )
    .await;
    tracing::info!(question_id = %q.id, kwant_id = %scope.kwant_id, "agent asked the user");

    let reply = tokio::select! {
        r = &mut rx => r.ok(),
        _ = cancel.cancelled() => {
            close(state, &q.id, "cancelled", None).await;
            return ("The user stopped this turn. End it now.".into(), true);
        }
        _ = tokio::time::sleep(hub.wait()) => {
            hub.take(&q.id);
            // An answer that arrived just as the wait ran out still counts
            rx.try_recv().ok()
        }
    };
    match reply {
        Some(Reply::Answer(a)) => (format!("The user answered: {a}"), false),
        Some(Reply::Dismissed) => (
            "The user dismissed the question without answering. Carry on with your best judgment, or stop if you can't.".into(),
            false,
        ),
        None => (
            "The user hasn't answered yet. Don't ask again: end your turn now with a short note on what you're waiting for. \
            When they answer, you'll get a new turn with their answer."
                .into(),
            false,
        ),
    }
}

// Routes

#[derive(Deserialize)]
pub struct ListQuery {
    pub status: Option<String>,
    pub context_id: Option<String>,
}

fn error(status: StatusCode, message: impl Into<String>) -> Response {
    (status, Json(json!({ "error": message.into() }))).into_response()
}

/// `GET /api/questions?status=&context_id=&space=`: the space's questions, newest first (to show open cards after a reload).
pub async fn list(
    State(state): State<AppState>,
    super::spaces::Scope(space): super::spaces::Scope,
    Query(q): Query<ListQuery>,
) -> Response {
    let status = q.status.filter(|s| !s.is_empty());
    if let Some(s) = &status {
        if !QUESTION_STATUSES.contains(&s.as_str()) {
            return error(StatusCode::BAD_REQUEST, "unknown status");
        }
    }
    let context = q.context_id.as_deref().filter(|c| !c.is_empty());
    match state.db.list_questions(status.as_deref(), context, Some(&space)).await {
        Ok(list) => Json(list).into_response(),
        Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
    }
}

async fn load(state: &AppState, id: &str) -> Result<Question, StatusCode> {
    match state.db.get_question(id).await {
        Ok(Some(q)) => Ok(q),
        Ok(None) => Err(StatusCode::NOT_FOUND),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

pub async fn get(State(state): State<AppState>, Path(id): Path<String>) -> Response {
    match load(&state, &id).await {
        Ok(q) => Json(json!({"question": q, "waiting": state.questions.is_waiting(&q.id)})).into_response(),
        Err(r) => r.into_response(),
    }
}

#[derive(Deserialize, Default)]
pub struct AnswerPayload {
    /// Index into the question's choices.
    pub choice: Option<usize>,
    /// The user's own answer.
    pub text: Option<String>,
}

/// `POST /api/questions/:id/answer {choice} | {text}`: the waiting turn gets it at once; if the
/// turn already ended, a new turn starts in the same chat with the answer.
pub async fn answer(State(state): State<AppState>, Path(id): Path<String>, Json(p): Json<AnswerPayload>) -> Response {
    let q = match load(&state, &id).await {
        Ok(q) => q,
        Err(r) => return r.into_response(),
    };
    let text = match (p.choice, p.text.as_deref().map(str::trim)) {
        (Some(i), None) => match q.choice_list().get(i) {
            Some(c) => c.clone(),
            None => return error(StatusCode::BAD_REQUEST, "no such choice"),
        },
        (None, Some(t)) if !t.is_empty() => {
            if t.chars().count() > MAX_ANSWER_CHARS {
                return error(StatusCode::BAD_REQUEST, format!("the answer is longer than {MAX_ANSWER_CHARS} characters"));
            }
            t.to_string()
        }
        _ => return error(StatusCode::BAD_REQUEST, "give either a choice or a non-empty text"),
    };
    if q.status != "open" {
        return error(StatusCode::CONFLICT, format!("the question is already {}", q.status));
    }
    let Some((q, live)) = answer_with(&state, &id, &text).await else {
        return error(StatusCode::CONFLICT, "the question was just closed");
    };
    Json(json!({"question": q, "resumed": if live { "turn" } else { "new_turn" }})).into_response()
}

/// Answers an open question as if on its card: it closes, the answer is saved where it was
/// asked, and the turn waiting on it gets it (`true`), or a new turn continues with it (`false`;
/// in a delegation's thread that goes back to the lead). `None` when it wasn't open any more.
pub async fn answer_with(state: &AppState, id: &str, text: &str) -> Option<(Question, bool)> {
    answer_via(state, id, text, None).await
}

/// [`answer_with`] from somewhere other than kwant (`via`: "telegram"): the question records
/// `answered_via` and the answer message carries `source`.
pub async fn answer_via(state: &AppState, id: &str, text: &str, via: Option<&str>) -> Option<(Question, bool)> {
    let text: String = text.trim().chars().take(MAX_ANSWER_CHARS).collect();
    let q = close_via(state, id, "answered", Some(&text), via).await?;
    let mut meta = json!({"kind": "question_answer", "question_id": q.id});
    if let Some(via) = via {
        meta["source"] = json!(via);
    }
    save_message(state, &q, "user", "user", text.clone(), meta).await;
    let live = match state.questions.take(&q.id) {
        Some(tx) => tx.send(Reply::Answer(text.clone())).is_ok(),
        None => false,
    };
    // A Dev mode brief's question has no turn behind it: the brief takes the answer instead; the
    // "Keep going?" card starts a keep-going turn (or ends the chain)
    if !live
        && !super::keep_going::on_card_answer(state, &q, &text).await
        && !super::dev::tickets::hooks::on_question(state, &q, Some(&text), "card").await
    {
        resume(state, &q, &text).await;
    }
    Some((q, live))
}

/// The person answered an open question by typing in the chat instead of on its card (their
/// message is already saved). The question closes with that text; a turn still waiting on it gets
/// the answer and `true` comes back, so no new turn is started. `false` when no turn is waiting
/// (the caller routes the message to the bot that asked) or the question was already closed.
pub async fn answer_by_message(state: &AppState, id: &str, text: &str) -> bool {
    let text: String = text.trim().chars().take(MAX_ANSWER_CHARS).collect();
    if close(state, id, "answered", Some(&text)).await.is_none() {
        return false;
    }
    match state.questions.take(id) {
        Some(tx) => tx.send(Reply::Answer(text)).is_ok(),
        None => false,
    }
}

/// A late answer: a new turn in the question's chat, queued like any other turn. In an ended
/// delegation's thread the result also goes back to the lead (see
/// [`super::delegation::resume_after_answer`]).
async fn resume(state: &AppState, q: &Question, answer: &str) {
    let Ok(Some(kwant)) = state.db.get_kwant(&q.kwant_id).await else {
        return;
    };
    let delegation = match &q.thread_id {
        Some(t) => state.db.delegation_for_thread(t).await.ok().flatten(),
        None => None,
    };
    let prompt = format!(
        "[The user answered the question you asked earlier]\nQuestion: {}\nAnswer: {answer}\n\nContinue the task with this answer.",
        q.question
    );
    // The specialist of an ended delegation asked it: its new result goes back to the lead
    if let Some(d) = delegation.clone().filter(|d| d.specialist_kwant_id == q.kwant_id) {
        if super::delegation::resume_after_answer(state, d, &q.id, prompt.clone()).await {
            return;
        }
    }
    let depth = delegation.map(|d| d.depth).unwrap_or(0);
    // A card kwant made from a lead's prose question: the lead's chain goes on from the answer
    let in_chat = q.thread_id.is_none();
    let chain = in_chat && super::keep_going::card_has(state, q, super::keep_going::ASK_KEY).await;
    let job = state.turns.start_job([q.context_id(), q.id.clone()]);
    let Ok(scope) = scope_for(state, &kwant, q.channel_id.clone(), q.thread_id.clone(), &job, depth).await else {
        return;
    };
    let answer = answer.to_string();
    tokio::spawn(async move {
        let _job = job;
        let snap = super::keep_going::snapshot(&scope.state, &scope.context_id(&kwant), &kwant).await;
        let Ok(reply) = try_kwant_turn(&scope, &kwant, prompt, TurnOpts::default()).await else {
            return;
        };
        // Like any reply in a person's chat: an @mention hands on (a late answer used to end
        // there, so a lead's "@Writer, go ahead" after it did nothing)
        if in_chat {
            super::routes::run_handoffs_boxed(&scope, std::slice::from_ref(&kwant.id), &[(kwant.clone(), reply.clone())], &answer).await;
            super::asks::consolidate(&scope).await;
        }
        if chain {
            super::keep_going::after_lead_turn(&scope, &kwant, snap, reply).await;
        }
    });
}

/// After a turn was stopped: its questions that are still open are cancelled, so a late answer
/// doesn't restart work the user stopped. One indexed query, only for stopped turns.
pub async fn cancel_for_turn(state: &AppState, turn_id: &str) {
    let open = state.db.list_questions(Some("open"), None, None).await.unwrap_or_default();
    for q in open.iter().filter(|q| q.turn_id.as_deref() == Some(turn_id)) {
        if let Some(tx) = state.questions.take(&q.id) {
            drop(tx);
        }
        close(state, &q.id, "cancelled", None).await;
    }
}

/// The bot a bearer token belongs to while its turn runs: its own tools' token or its MCP
/// session's (the same token, kept in both maps).
async fn turn_token_bot(state: &AppState, token: &str) -> Option<String> {
    if let Some(s) = state.self_tools.lock().await.get(token) {
        return Some(s.kwant_id.clone());
    }
    state.mcp_sessions.lock().await.get(token).map(|s| s.kwant_id.clone())
}

/// Why this caller may not dismiss `q`; `None` for the person (no bearer, or the API token) and
/// for the bot that asked it (its live turn token). Any other bearer gets a 403: another bot's
/// turn token, and one that is no live turn's and not the API token (an ended turn's, a made-up
/// one), so a bot can't dismiss a question it didn't ask (#653, Rigel). The app and the desktop
/// app send no bearer; Telegram cancels in-process, not through this route.
async fn cancel_refusal(state: &AppState, headers: &HeaderMap, q: &Question) -> Option<Response> {
    let presented: Vec<&str> = headers
        .get_all(header::AUTHORIZATION)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .map(|v| v.strip_prefix("Bearer ").unwrap_or(v).trim())
        .collect();
    for token in presented {
        let allowed = match turn_token_bot(state, token).await {
            Some(bot) => bot == q.kwant_id,
            None => state.api_token.matches(token),
        };
        if !allowed {
            let msg = "only the person or the bot that asked can dismiss this question";
            return Some((StatusCode::FORBIDDEN, Json(json!({ "error": msg, "code": "not_the_asker" }))).into_response());
        }
    }
    None
}

/// `POST /api/questions/:id/cancel`: the person, or the bot that asked, dismisses the question; a
/// waiting turn carries on without an answer. Another bot gets a 403 ([`cancel_refusal`]).
pub async fn cancel(State(state): State<AppState>, Path(id): Path<String>, headers: HeaderMap) -> Response {
    let q = match load(&state, &id).await {
        Ok(q) => q,
        Err(r) => return r.into_response(),
    };
    if let Some(refused) = cancel_refusal(&state, &headers, &q).await {
        return refused;
    }
    if q.status != "open" {
        return error(StatusCode::CONFLICT, format!("the question is already {}", q.status));
    }
    let Some(q) = close(&state, &id, "cancelled", None).await else {
        return error(StatusCode::CONFLICT, "the question was just closed");
    };
    if let Some(tx) = state.questions.take(&q.id) {
        let _ = tx.send(Reply::Dismissed);
    } else {
        // A Dev mode brief's question: dismissing it takes its default
        super::dev::tickets::hooks::on_question(&state, &q, None, "dismissed").await;
    }
    Json(q).into_response()
}

// Questions kwant asks with no turn waiting (a Dev mode brief's, J8)

/// Saves one open question with its card in `place`, with no turn waiting on it: an answer on the
/// card, in the chat or elsewhere is taken by whoever asked (see [`super::dev::tickets::hooks`]).
/// `None` when it couldn't be saved (too long, too many open).
pub async fn ask_without_waiter(state: &AppState, place: &QuestionPlace, kwant_name: &str, question: &str, choices: &[String], reason: QuestionReason<'_>) -> Option<Question> {
    let created = state
        .db
        .create_question_with_card(place, question, choices, reason, |q| {
            let text = match choices.is_empty() {
                true => q.question.clone(),
                false => format!("{}\n\nChoices: {}", q.question, choices.join(" · ")),
            };
            let (msg, extra) = place_message(q, "kwant", &place.kwant_id, text);
            Some((msg, MessageExtra { meta: Some(card_meta(q)), ..extra }))
        })
        .await;
    let (q, card) = match created {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(error = %e, kwant_id = %place.kwant_id, "could not save a question");
            return None;
        }
    };
    if let Some(card) = card {
        if let Some(t) = &q.thread_id {
            let _ = state.db.touch_thread(t).await;
        }
        let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&card).unwrap_or(Value::Null) });
    }
    changed(state, &q).await;
    notify(
        state,
        Notification {
            kind: "question_asked",
            kwant_id: place.kwant_id.clone(),
            kwant_name: kwant_name.to_string(),
            channel_id: q.channel_id.clone(),
            title: format!("{kwant_name} has a question"),
            body: "Open the chat to answer.".into(),
            thread_id: q.thread_id.clone(),
            card_id: None,
        },
    )
    .await;
    Some(q)
}

/// Closes an open question kwant asked without a waiter, answered somewhere other than its card
/// (the chat, Go with the defaults, Jira): its card shows the answer. `None` if it wasn't open.
pub async fn close_answered(state: &AppState, id: &str, answer: &str) -> Option<Question> {
    let answer: String = answer.trim().chars().take(MAX_ANSWER_CHARS).collect();
    close(state, id, "answered", Some(&answer)).await
}

// The claude CLI's own question tool

/// The claude CLI's built-in question tool. Under `-p` nobody can answer it inside the turn, so
/// its questions are saved as open questions with cards: the person sees them, can answer later
/// (a new turn gets the answer) and they count as waiting on the person.
pub const NATIVE_ASK_TOOL: &str = "AskUserQuestion";

/// The questions in an `AskUserQuestion` call, `{"questions": [{"question", "options": [{"label"}]}]}`,
/// cleaned: each question clipped to the usual length, at most 5 distinct choices (it may have
/// fewer than 2, the person can always type an answer). Inputs too long to pass whole arrive as
/// a clipped JSON string; their question texts are still read, without choices.
pub fn native_questions(args: &Value) -> Vec<(String, Vec<String>)> {
    let clip = |s: &str, n: usize| -> String { s.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(n).collect() };
    let parsed;
    let args = match args {
        Value::String(raw) => match serde_json::from_str::<Value>(raw) {
            Ok(v) => {
                parsed = v;
                &parsed
            }
            Err(_) => {
                return strings_after(raw, "\"question\"")
                    .iter()
                    .map(|q| clip(q, crate::db::questions::MAX_QUESTION_CHARS))
                    .filter(|q| !q.is_empty())
                    .map(|q| (q, Vec::new()))
                    .collect()
            }
        },
        v => v,
    };
    let mut out = Vec::new();
    for item in args["questions"].as_array().map(Vec::as_slice).unwrap_or_default() {
        let q = clip(item["question"].as_str().unwrap_or(""), crate::db::questions::MAX_QUESTION_CHARS);
        if q.is_empty() {
            continue;
        }
        let mut choices: Vec<String> = Vec::new();
        for o in item["options"].as_array().map(Vec::as_slice).unwrap_or_default() {
            let label = o["label"].as_str().or_else(|| o.as_str()).unwrap_or("");
            let c = clip(label, crate::db::questions::MAX_CHOICE_CHARS);
            if !c.is_empty() && !choices.iter().any(|x| x.eq_ignore_ascii_case(&c)) && choices.len() < crate::db::questions::MAX_CHOICES {
                choices.push(c);
            }
        }
        out.push((q, choices));
    }
    out
}

/// The JSON string values after each `key:` in clipped JSON text; a string cut off at the end is
/// skipped.
fn strings_after(raw: &str, key: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut rest = raw;
    while let Some(i) = rest.find(key) {
        rest = &rest[i + key.len()..];
        let Some(open) = rest.trim_start().strip_prefix(':').map(str::trim_start).and_then(|r| r.strip_prefix('"')) else {
            continue;
        };
        let mut escaped = false;
        let end = open.char_indices().find(|&(_, c)| {
            let close = c == '"' && !escaped;
            escaped = c == '\\' && !escaped;
            close
        });
        if let Some((end, _)) = end {
            if let Ok(s) = serde_json::from_str::<String>(&format!("\"{}\"", &open[..end])) {
                out.push(s);
            }
        }
    }
    out
}

/// Saves the questions of a claude `AskUserQuestion` call as open questions with cards in the
/// turn's chat, and tells the person. Returns how many were saved.
pub async fn record_native(state: &AppState, place: &QuestionPlace, kwant_name: &str, args: &Value) -> usize {
    let mut saved = 0;
    for (question, choices) in native_questions(args) {
        let created = state
            .db
            .create_question_with_card(place, &question, &choices, QuestionReason::default(), |q| {
                let text = match choices.is_empty() {
                    true => q.question.clone(),
                    false => format!("{}\n\nChoices: {}", q.question, choices.join(" · ")),
                };
                let (msg, extra) = place_message(q, "kwant", &place.kwant_id, text);
                Some((msg, MessageExtra { meta: Some(card_meta(q)), ..extra }))
            })
            .await;
        let (q, card) = match created {
            Ok(v) => v,
            Err(e) => {
                tracing::warn!(error = %e, kwant_id = %place.kwant_id, "could not save a claude AskUserQuestion");
                break;
            }
        };
        if let Some(card) = card {
            if let Some(t) = &q.thread_id {
                let _ = state.db.touch_thread(t).await;
            }
            let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&card).unwrap_or(Value::Null) });
        }
        changed(state, &q).await;
        notify(
            state,
            Notification {
                kind: "question_asked",
                kwant_id: place.kwant_id.clone(),
                kwant_name: kwant_name.to_string(),
                channel_id: q.channel_id.clone(),
                title: format!("{kwant_name} has a question"),
                body: "Open the chat to answer.".into(),
                thread_id: q.thread_id.clone(),
                card_id: None,
            },
        )
        .await;
        tracing::info!(question_id = %q.id, kwant_id = %place.kwant_id, "saved a claude AskUserQuestion");
        saved += 1;
    }
    saved
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn native_questions_are_read() {
        let args = json!({"questions": [
            {"question": "Which  plan?", "header": "Plan", "multiSelect": false,
             "options": [{"label": "Pro", "description": "x"}, {"label": "pro"}, {"label": "Max"}]},
            {"question": "  ", "options": []},
            {"question": "Anything to add?"},
        ]});
        assert_eq!(
            native_questions(&args),
            vec![("Which plan?".to_string(), vec!["Pro".to_string(), "Max".to_string()]), ("Anything to add?".to_string(), vec![])]
        );
        let long = format!("{{\"questions\":[{{\"question\":\"Ship \\\"it\\\" now?\",\"options\":[{{\"label\":\"{}", "y".repeat(3000));
        let clipped = Value::String(long.chars().take(2000).collect());
        assert_eq!(native_questions(&clipped), vec![("Ship \"it\" now?".to_string(), vec![])]);
        assert!(native_questions(&json!({"todos": []})).is_empty());
    }
}