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.

Live activity steps and human browser steps

Lin3943d45c2d47
diff --git a/docs/live-activity.md b/docs/live-activity.md
new file mode 100644
index 00000000..a4ba4c02
--- /dev/null
+++ b/docs/live-activity.md
@@ -0,0 +1,222 @@
+# Live activity and human steps: API
+
+Backend for two UI features on branch `live-activity`:
+
+1. **Live activity**: what a bot is doing while it works (thinking, each tool it runs, waits for
+ approval or for the person), streamed over SSE and kept on the reply after a reload.
+2. **Human step**: a bot (or kwnt itself, on a CAPTCHA) asks the person to do one step in the
+ bot browser (sign in, solve a CAPTCHA, something else), then waits for Done or Decline.
+
+All events arrive on the existing SSE stream as `{ "type": ..., "data": ... }`. Turn events are
+*scoped*: `turn_id`, `kwant_id`, `context_id` and (in threads) `thread_id` sit next to `type`.
+
+## 1. Live activity
+
+### SSE `activity` (scoped)
+
+Sent every time a step starts or changes. Replace the step with the same `data.step.id` in the
+turn's list (keyed by `turn_id`); append it if it's new.
+
+```json
+{
+ "type": "activity",
+ "turn_id": "…", "kwant_id": "…", "context_id": "…", "thread_id": "…",
+ "data": {
+ "step": {
+ "id": "s3",
+ "kind": "tool",
+ "status": "failed",
+ "title": "Running `cargo test`",
+ "tool": "Bash",
+ "detail": "exit code 101",
+ "started_at": "2026-10-22T10:00:01.120Z",
+ "ended_at": "2026-10-22T10:00:09.480Z",
+ "duration_ms": 8360
+ }
+ }
+}
+```
+
+| field | meaning |
+|---|---|
+| `id` | `s1`, `s2`, … in start order, unique within the turn |
+| `kind` | `thinking`, `tool`, `approval`, `human_step`, `note` |
+| `status` | `running` (thinking/tool), `waiting` (approval/human_step), `ok`, `failed`, `done`, `declined`, `stopped` (the turn ended while it was open, or an approval timed out) |
+| `title` | short, human, already redacted: "Running `cargo test`", "Opening github.com", "Reading …/src/main.rs", "Searching the web for “rust sse”", "Using tool (github)", "Waiting for your approval: Running `rm -rf build`", "Waiting for you: Log in to GitHub" |
+| `tool` | optional. The raw tool name (`Bash`, `mcp__github__create_issue`, `command_execution`) |
+| `detail` | optional. The full command or address, or why the tool failed (redacted, ≤500 chars) |
+| `text` | optional. The thinking step's whole text, set once the step ends |
+| `ref_id` | optional. For `approval` it is the approval ticket, and for `human_step` it is the human-step id. Use it to link to the card |
+| `started_at`, `ended_at` | RFC 3339 with milliseconds. `ended_at` is missing while the step is open |
+| `duration_ms` | set once the step ends |
+
+**Thinking text streams live** as the existing `ThinkingDelta` event (`data` is a string chunk,
+scoped to the turn). The `activity` step of kind `thinking` only marks start (`running`) and end
+(`ok`, with `text`). While it's running, show the `ThinkingDelta` text under it.
+
+A `note` step (status `ok`) explains a limit, e.g. for engines that don't share thinking:
+"This engine doesn't share its thinking here; you'll see what it says between steps and each
+tool it runs." It is the first step of such turns.
+
+### After a reload: `meta.activity` on the reply
+
+The saved bot reply (message `meta`, a JSON string in the message row) gets:
+
+```json
+{ "activity": { "steps": [ <step>, … ], "dropped": 12 } }
+```
+
+`dropped` appears only when steps past the cap were left out. The caps are 200 steps per reply and
+16,000 thinking characters per reply (the rest is cut with "…"). Titles are cut at 160 characters
+and details at 500. Steps still open when the turn ended are saved as `stopped`.
+
+### Redaction
+
+Titles, details and thinking text pass through redaction before they leave the server:
+
+- the turn's MCP secret values are masked as `********`
+- `key=value` / `"key": "value"` credentials (password, token, secret, api_key, …)
+- `Bearer …` headers
+- passwords inside URLs
+- Slack and AWS keys
+- whole words that look like provider keys: `sk-…`, `xai-…`, `ghp_…`/`gho_…`/`ghu_…`/`ghs_…`/`ghr_…`, `github_pat_…`, `glpat-…`, `AIza…`, `hf_…`, `npm_…`
+
+### Per-engine coverage
+
+| engine | thinking | tool steps | approvals |
+|---|---|---|---|
+| claude (CLI) | yes. Streamed `thinking_delta` blocks (or whole `thinking` blocks), when the model thinks | yes, from `tool_use` / `tool_result`. Failures carry the error text | yes |
+| codex (CLI) | yes, from reasoning summaries (`codex exec --json` `reasoning` items) | yes: commands (with exit code), file changes, MCP calls, web searches, plan updates | yes (kwnt MCP tools) |
+| grok (CLI) | yes, from `thought` stream events | yes, from `tool_call` / `tool_call_update` (failed status carries the error) | yes (kwnt MCP tools) |
+| API engines (anthropic_api, openai_api, xai_api, ollama, custom_api) | **no**. These get the `note` step. The text the model writes before a tool call still arrives as `ThinkingDelta` | yes | yes |
+
+## 2. Human step
+
+### The agent tool
+
+`request_human_step` on the agents' own MCP server (offered in chat turns that have a bot
+browser):
+
+```json
+{ "reason": "Log in to GitHub so I can open the PR", "kind": "sign_in", "url": "https://github.com/login" }
+```
+
+`kind` is one of `sign_in`, `captcha` or `other`. `reason` is required and at most 300
+characters. `url` is optional, must be http(s), and is stored without user info, query or
+fragment.
+
+The turn waits until the person answers, the turn is stopped, or the wait runs out (a few
+minutes). If the wait runs out, the step stays open and the agent is told to end its turn. When
+the person answers later, a **new turn** starts in the same chat with the outcome.
+
+**Auto-raise:** when a `browser_open`, `browser_page` or `browser_act` tool lands on a CAPTCHA or
+anti-bot wall (`detect_bot_wall`), kwnt raises a `captcha` step itself (`source: "auto"`), waits
+the same way, and after Done shows the agent the page again. Login pages are **not**
+auto-detected. Agents ask for those with the tool.
+
+While a step is open in a bot browser:
+
+- the bot's browser tools are refused ("The browser is waiting on the person …")
+- the browser controller is held for the person, so live-view input goes through even without `take_control` (and `take_control` answers `{"type":"control","active":true}`)
+
+The person can use the live view freely.
+
+A turn that asks again while its step is open gets the same step back, so no second card is
+created. Each agent can have at most 5 open steps.
+
+### SSE `human_step_updated` (not scoped; routed to the step's chat)
+
+Sent when a step opens and when it closes.
+
+```json
+{ "type": "human_step_updated", "data": { "step": <HumanStep> } }
+```
+
+`HumanStep`:
+
+```json
+{
+ "id": "uuid",
+ "kwant_id": "…",
+ "channel_id": null,
+ "direct_kwant_id": "…",
+ "thread_id": null,
+ "turn_id": "…",
+ "kind": "sign_in",
+ "reason": "Log in to GitHub so I can open the PR",
+ "url": "https://github.com/login",
+ "sandbox_target": "…",
+ "source": "bot",
+ "status": "open",
+ "message_id": "…",
+ "created_at": "2026-10-22T10:00:00Z",
+ "closed_at": null
+}
+```
+
+`status` is one of `open`, `done`, `declined` or `cancelled` (the turn was stopped). `source` is
+`bot` (the agent asked) or `auto` (kwnt saw a CAPTCHA). `sandbox_target` is the bot-browser id
+(team, channel or kwant), which is the same id the live browser panel uses.
+
+### The card message
+
+Opening a step also adds a chat message (`message_added`) from the bot. Its text is something like:
+
+> Sign in needed: Log in to GitHub so I can open the PR
+> https://github.com/login
+>
+> Do it in the browser panel, then press Done.
+
+Its `meta` holds:
+
+```json
+{ "kind": "human_step", "human_step_id": "…", "step_kind": "sign_in", "reason": "…", "url": "…",
+ "sandbox_target": "…", "source": "bot", "status": "open" }
+```
+
+The card's `meta.status` is updated in place when the step closes. Render it as a card with
+**Done** and **Decline** buttons while `status == "open"`, plus "Open browser" (the panel for
+`sandbox_target`). When the person answers, a user message `Done` / `Declined` is added with
+`meta: {"kind":"human_step_reply","human_step_id":"…","status":"done"}`.
+
+### Notification
+
+The standard `Notify` event and webhook use `kind: "human_step"`. The title is "<Bot> needs you in
+the browser". The body is "<Sign in needed | Human check needed | Your help is needed>. Open the
+chat, do it in the browser panel, then press Done." The body never includes the reason or URL.
+
+`human_step` was added to `NOTIFY_KINDS`. People who saved a custom notification list must turn it
+on, so the settings UI needs a label for it, e.g. "A bot needs you in the browser".
+
+### Live activity
+
+While the step is open, the turn shows an `activity` step with kind `human_step`, status `waiting`,
+title "Waiting for you: <reason>" and `ref_id` set to the step id. When the step closes, that
+activity step settles as `done`, `declined` or `stopped`.
+
+### Endpoints
+
+| method | path | body | result |
+|---|---|---|---|
+| GET | `/api/human-steps?status=&context_id=&space=` | | `[HumanStep]`, newest first, at most 100. `context_id` is a channel, thread or direct-chat kwant id. Use `status=open` after a reload |
+| GET | `/api/human-steps/:id` | | `{ "step": HumanStep, "waiting": bool }`. `waiting` is true while a live turn waits on it |
+| POST | `/api/human-steps/:id/done` | none | `{ "step": HumanStep, "resumed": "turn" \| "new_turn" }` |
+| POST | `/api/human-steps/:id/decline` | none | same |
+
+Errors:
+
+- `404` when the step is unknown
+- `409 {"error":"the step is already done"}` when it is no longer open
+- `400` for an unknown `status` in the list query
+
+Done and Decline hand the browser back to the bot (once no other step is open in it). Then
+either the waiting turn continues with the outcome (`resumed: "turn"`), or a new turn starts in
+the same chat (`resumed: "new_turn"`).
+
+### Known limits
+
+- The person-hold on the browser lives in memory. After a kwnt restart an open step still blocks
+ the bot's browser tools (that check reads the database), but live-view input needs
+ `take_control` again.
+- If the browser wasn't running when the step opened, only the database check protects it: bot
+ tools are refused, and the person takes control as usual.
diff --git a/src/db/human_steps.rs b/src/db/human_steps.rs
new file mode 100644
index 00000000..49a9436d
--- /dev/null
+++ b/src/db/human_steps.rs
@@ -0,0 +1,326 @@
+//! Steps only the person can do in the bot browser (`request_human_step`): sign in, solve a
+//! CAPTCHA, or something else. A step is `open` until the person marks it done or declines it,
+//! or its turn is stopped (`cancelled`).
+
+use super::models::{Message, MessageExtra, NewMessage};
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use sqlx::FromRow;
+use uuid::Uuid;
+
+pub const MAX_REASON_CHARS: usize = 300;
+pub const MAX_URL_CHARS: usize = 300;
+/// Most open steps per agent; an agent can't flood the person.
+pub const MAX_OPEN_PER_KWANT: i64 = 5;
+
+pub const HUMAN_STEP_KINDS: [&str; 3] = ["sign_in", "captcha", "other"];
+/// "open", "done", "declined" or "cancelled" (its turn was stopped).
+pub const HUMAN_STEP_STATUSES: [&str; 4] = ["open", "done", "declined", "cancelled"];
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct HumanStep {
+ pub id: String,
+ pub kwant_id: String,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ /// The turn that asked; it may have ended since (a late answer starts a new turn).
+ pub turn_id: Option<String>,
+ pub kind: String,
+ pub reason: String,
+ /// Where to do it: scheme, host and path only, never a query or a password.
+ pub url: Option<String>,
+ /// The bot browser it happens in (team, channel or kwant id).
+ pub sandbox_target: Option<String>,
+ /// "bot" (the agent asked) or "auto" (kwnt saw a CAPTCHA).
+ pub source: String,
+ pub status: String,
+ /// The chat message that shows the step.
+ pub message_id: Option<String>,
+ pub created_at: DateTime<Utc>,
+ pub closed_at: Option<DateTime<Utc>>,
+}
+
+impl HumanStep {
+ /// The chat id the step was asked in: channel, thread or the direct chat's kwant.
+ pub fn context_id(&self) -> String {
+ self.channel_id
+ .clone()
+ .or_else(|| self.thread_id.clone())
+ .or_else(|| self.direct_kwant_id.clone())
+ .unwrap_or_else(|| self.kwant_id.clone())
+ }
+}
+
+#[derive(Debug, thiserror::Error, PartialEq)]
+pub enum HumanStepError {
+ #[error("{0}")]
+ Invalid(String),
+ #[error("you already have {MAX_OPEN_PER_KWANT} steps waiting on the person; wait for them first")]
+ TooManyOpen,
+ #[error("database error")]
+ Db,
+}
+
+impl From<DbError> for HumanStepError {
+ fn from(_: DbError) -> Self {
+ HumanStepError::Db
+ }
+}
+
+impl From<sqlx::Error> for HumanStepError {
+ fn from(_: sqlx::Error) -> Self {
+ HumanStepError::Db
+ }
+}
+
+/// The URL as it is kept and shown: http(s) only, without user info, query or fragment, which
+/// can hold tokens. `None` when there is no usable URL.
+pub fn clean_url(raw: &str) -> Option<String> {
+ let mut url = url::Url::parse(raw.trim()).ok()?;
+ if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
+ return None;
+ }
+ let _ = url.set_username("");
+ let _ = url.set_password(None);
+ url.set_query(None);
+ url.set_fragment(None);
+ let s = url.to_string();
+ (s.chars().count() <= MAX_URL_CHARS).then_some(s)
+}
+
+/// A request's kind, reason and URL, checked and trimmed.
+pub fn clean_request(kind: &str, reason: &str, url: Option<&str>) -> Result<(String, String, Option<String>), HumanStepError> {
+ let kind = kind.trim();
+ if !HUMAN_STEP_KINDS.contains(&kind) {
+ return Err(HumanStepError::Invalid("kind must be sign_in, captcha or other".into()));
+ }
+ let reason = reason.split_whitespace().collect::<Vec<_>>().join(" ");
+ if reason.is_empty() {
+ return Err(HumanStepError::Invalid("reason is required".into()));
+ }
+ if reason.chars().count() > MAX_REASON_CHARS {
+ return Err(HumanStepError::Invalid(format!("reason is longer than {MAX_REASON_CHARS} characters")));
+ }
+ let url = match url.map(str::trim).filter(|u| !u.is_empty()) {
+ Some(u) => Some(clean_url(u).ok_or_else(|| HumanStepError::Invalid("url must be an http(s) address".into()))?),
+ None => None,
+ };
+ Ok((kind.to_string(), reason, url))
+}
+
+/// Where a step is asked.
+#[derive(Debug, Clone, Default)]
+pub struct HumanStepPlace {
+ pub kwant_id: String,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub turn_id: Option<String>,
+ pub sandbox_target: Option<String>,
+}
+
+/// A new step (with `true`), or the turn's step that is already open (with `false`).
+pub type Created = (HumanStep, bool, Option<Message>);
+
+impl Database {
+ pub(super) async fn migrate_human_steps(&self) -> Result<(), DbError> {
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS human_steps (
+ id TEXT PRIMARY KEY,
+ kwant_id TEXT NOT NULL,
+ channel_id TEXT,
+ direct_kwant_id TEXT,
+ thread_id TEXT,
+ turn_id TEXT,
+ kind TEXT NOT NULL CHECK (kind IN ('sign_in', 'captcha', 'other')),
+ reason TEXT NOT NULL,
+ url TEXT,
+ sandbox_target TEXT,
+ source TEXT NOT NULL CHECK (source IN ('bot', 'auto')),
+ status TEXT NOT NULL CHECK (status IN ('open', 'done', 'declined', 'cancelled')),
+ message_id TEXT,
+ created_at TIMESTAMP NOT NULL,
+ closed_at TIMESTAMP
+ )",
+ "CREATE INDEX IF NOT EXISTS human_steps_by_status ON human_steps (status, kwant_id)",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ /// Saves a step together with the chat message that shows it (built by `card`), in one
+ /// transaction. A turn that asks again while its step is open gets that step back, so a
+ /// retrying agent (or the CAPTCHA check firing on every page) doesn't pile up cards.
+ pub async fn create_human_step_with_card(
+ &self,
+ place: &HumanStepPlace,
+ kind: &str,
+ reason: &str,
+ url: Option<&str>,
+ source: &str,
+ card: impl FnOnce(&HumanStep) -> Option<(NewMessage, MessageExtra)>,
+ ) -> Result<Created, HumanStepError> {
+ let mut tx = self.pool.begin().await?;
+ let get = "SELECT * FROM human_steps WHERE id = ?";
+ // Writes first so the transaction holds SQLite's write lock before it reads
+ let id = Uuid::new_v4().to_string();
+ let inserted = sqlx::query(
+ "INSERT INTO human_steps (id, kwant_id, channel_id, direct_kwant_id, thread_id, turn_id, kind, reason, url, sandbox_target, source, status, created_at)
+ SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, 'open', ?12
+ WHERE (SELECT COUNT(*) FROM human_steps WHERE kwant_id = ?2 AND status = 'open') < ?13
+ AND NOT EXISTS (SELECT 1 FROM human_steps WHERE status = 'open' AND ?6 IS NOT NULL AND turn_id = ?6)",
+ )
+ .bind(&id)
+ .bind(&place.kwant_id)
+ .bind(&place.channel_id)
+ .bind(&place.direct_kwant_id)
+ .bind(&place.thread_id)
+ .bind(&place.turn_id)
+ .bind(kind)
+ .bind(reason)
+ .bind(url)
+ .bind(&place.sandbox_target)
+ .bind(source)
+ .bind(Utc::now())
+ .bind(MAX_OPEN_PER_KWANT)
+ .execute(&mut *tx)
+ .await?;
+ if inserted.rows_affected() == 0 {
+ let existing = match &place.turn_id {
+ Some(t) => {
+ sqlx::query_as::<_, HumanStep>("SELECT * FROM human_steps WHERE status = 'open' AND turn_id = ? LIMIT 1")
+ .bind(t)
+ .fetch_optional(&mut *tx)
+ .await?
+ }
+ None => None,
+ };
+ tx.commit().await?;
+ return match existing {
+ Some(step) => Ok((step, false, None)),
+ None => Err(HumanStepError::TooManyOpen),
+ };
+ }
+ let mut step = sqlx::query_as::<_, HumanStep>(get).bind(&id).fetch_one(&mut *tx).await?;
+ let mut message = None;
+ if let Some((msg, extra)) = card(&step) {
+ let saved = super::insert_message_on(&mut tx, &msg, &extra).await?;
+ sqlx::query("UPDATE human_steps SET message_id = ? WHERE id = ?").bind(&saved.id).bind(&id).execute(&mut *tx).await?;
+ step = sqlx::query_as::<_, HumanStep>(get).bind(&id).fetch_one(&mut *tx).await?;
+ message = Some(saved);
+ }
+ tx.commit().await?;
+ Ok((step, true, message))
+ }
+
+ pub async fn get_human_step(&self, id: &str) -> Result<Option<HumanStep>, DbError> {
+ Ok(sqlx::query_as::<_, HumanStep>("SELECT * FROM human_steps WHERE id = ?")
+ .bind(id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// Steps, newest first, at most 100: by status and/or chat (channel, thread or direct-chat
+ /// kwant id); `space` keeps the steps of that space's kwants (all when `None`).
+ pub async fn list_human_steps(
+ &self,
+ status: Option<&str>,
+ context_id: Option<&str>,
+ space: Option<&super::spaces::SpaceId>,
+ ) -> Result<Vec<HumanStep>, DbError> {
+ Ok(sqlx::query_as::<_, HumanStep>(
+ "SELECT * FROM human_steps
+ WHERE (?1 IS NULL OR status = ?1)
+ AND (?2 IS NULL OR channel_id = ?2 OR thread_id = ?2 OR direct_kwant_id = ?2)
+ AND (?3 IS NULL OR COALESCE((SELECT k.space_id FROM kwants k WHERE k.id = human_steps.kwant_id), 'spc_default') = ?3)
+ ORDER BY created_at DESC LIMIT 100",
+ )
+ .bind(status)
+ .bind(context_id)
+ .bind(space.map(|s| s.as_str()))
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// The open steps of one turn.
+ pub async fn open_human_steps_for_turn(&self, turn_id: &str) -> Result<Vec<HumanStep>, DbError> {
+ Ok(sqlx::query_as::<_, HumanStep>("SELECT * FROM human_steps WHERE status = 'open' AND turn_id = ?")
+ .bind(turn_id)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// Whether a step is open in this bot browser (it stays the person's until then).
+ pub async fn human_step_open_in(&self, sandbox_target: &str) -> Result<bool, DbError> {
+ let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM human_steps WHERE status = 'open' AND sandbox_target = ?")
+ .bind(sandbox_target)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(n > 0)
+ }
+
+ /// Closes an open step; `false` when it wasn't open any more (someone else closed it).
+ pub async fn close_human_step(&self, id: &str, status: &str) -> Result<bool, DbError> {
+ let done = sqlx::query("UPDATE human_steps SET status = ?, closed_at = ? WHERE id = ? AND status = 'open'")
+ .bind(status)
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(done.rows_affected() == 1)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn requests_are_checked_and_urls_lose_their_secrets() {
+ assert!(clean_request("sign_in", "Log in to GitHub", None).is_ok());
+ assert!(clean_request("login", "Log in", None).is_err());
+ assert!(clean_request("other", " ", None).is_err());
+ assert!(clean_request("other", &"r".repeat(301), None).is_err());
+ assert!(clean_request("captcha", "Solve it", Some("javascript:alert(1)")).is_err());
+ let (_, reason, url) =
+ clean_request("sign_in", " Log in\n to GitHub ", Some("https://me:[email protected]/login?return_to=x&token=abc#f")).unwrap();
+ assert_eq!(reason, "Log in to GitHub");
+ assert_eq!(url.as_deref(), Some("https://github.com/login"));
+ }
+
+ #[tokio::test]
+ async fn a_step_closes_once_and_a_turn_gets_its_open_step_back() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let place = |turn: &str| HumanStepPlace {
+ kwant_id: "k".into(),
+ direct_kwant_id: Some("k".into()),
+ turn_id: Some(turn.into()),
+ sandbox_target: Some("k".into()),
+ ..Default::default()
+ };
+ let (s, new, _) = db.create_human_step_with_card(&place("t1"), "sign_in", "Log in", None, "bot", |_| None).await.unwrap();
+ assert!(new);
+ assert_eq!(s.context_id(), "k");
+ assert!(db.human_step_open_in("k").await.unwrap());
+ let (again, new, _) = db.create_human_step_with_card(&place("t1"), "captcha", "Solve", None, "auto", |_| None).await.unwrap();
+ assert!(!new);
+ assert_eq!(again.id, s.id);
+ assert_eq!(db.open_human_steps_for_turn("t1").await.unwrap().len(), 1);
+ assert!(db.close_human_step(&s.id, "done").await.unwrap());
+ assert!(!db.close_human_step(&s.id, "declined").await.unwrap());
+ let closed = db.get_human_step(&s.id).await.unwrap().unwrap();
+ assert_eq!(closed.status, "done");
+ assert!(closed.closed_at.is_some());
+ assert!(!db.human_step_open_in("k").await.unwrap());
+ for i in 0..MAX_OPEN_PER_KWANT {
+ db.create_human_step_with_card(&place(&format!("t{}", i + 10)), "other", "Do it", None, "bot", |_| None).await.unwrap();
+ }
+ let full = db.create_human_step_with_card(&place("t99"), "other", "Do it", None, "bot", |_| None).await;
+ assert_eq!(full.err(), Some(HumanStepError::TooManyOpen));
+ assert_eq!(db.list_human_steps(Some("open"), Some("k"), None).await.unwrap().len() as i64, MAX_OPEN_PER_KWANT);
+ }
+}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index ee2e1c1a..b25223ed 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -7,6 +7,7 @@ pub mod parallel;
pub mod documents;
pub mod history;
pub mod attachments;
+pub mod human_steps;
pub mod questions;
pub mod skills;
pub mod away;
@@ -139,6 +140,7 @@ impl Database {
db.migrate_threads().await?;
db.migrate_skills().await?;
db.migrate_questions().await?;
+ db.migrate_human_steps().await?;
db.migrate_attachments().await?;
db.migrate_history().await?;
db.migrate_away().await?;
diff --git a/src/drivers/activity.rs b/src/drivers/activity.rs
new file mode 100644
index 00000000..20f8a002
--- /dev/null
+++ b/src/drivers/activity.rs
@@ -0,0 +1,533 @@
+//! Live activity: what a bot is doing during a turn, as a short list of steps (thinking, a tool
+//! run, a wait for an approval or for the person). Each change to a step is broadcast as an
+//! `activity` event while the turn runs, and the whole list is kept on the reply's
+//! `meta.activity` so it still shows after a reload. See
+//! `docs/live-activity.md` for the wire shapes.
+//!
+//! Titles and details are made for people ("Running `cargo test`", "Opening github.com") and are
+//! redacted: known secret values, `key=value` credentials, bearer tokens and provider-looking keys
+//! never leave this module.
+
+use super::events::RuntimeEvent;
+use serde::Serialize;
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::time::Instant;
+
+/// Most steps kept on one reply; later ones are counted in `dropped`.
+pub const MAX_STEPS: usize = 200;
+/// Most thinking text kept on one reply, over all its thinking steps (characters).
+pub const MAX_THINKING_CHARS: usize = 16_000;
+/// Longest step title (characters).
+pub const MAX_TITLE: usize = 160;
+/// Longest step detail (characters).
+pub const MAX_DETAIL: usize = 500;
+
+/// One thing the bot did, or is doing, in a turn.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct Step {
+ /// `s1`, `s2`, … in the order the steps started; unique within the turn.
+ pub id: String,
+ /// "thinking", "tool", "approval", "human_step" or "note".
+ pub kind: &'static str,
+ /// "running", "waiting", "ok", "failed", "done", "declined" or "stopped".
+ pub status: &'static str,
+ pub title: String,
+ /// The tool's own name (`Bash`, `mcp__github__create_issue`), for tool and approval steps.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tool: Option<String>,
+ /// More about the step: the full command or address, or why a tool failed.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub detail: Option<String>,
+ /// A thinking step's text, once the step ends (it streams as `thinking_delta` before that).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub text: Option<String>,
+ /// The approval ticket or human-step id the step waits on.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ref_id: Option<String>,
+ pub started_at: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ended_at: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub duration_ms: Option<u64>,
+ #[serde(skip)]
+ clock: Option<Instant>,
+}
+
+impl Step {
+ pub fn to_json(&self) -> Value {
+ serde_json::to_value(self).unwrap_or(Value::Null)
+ }
+
+ fn is_open(&self) -> bool {
+ matches!(self.status, "running" | "waiting")
+ }
+}
+
+/// The steps of one turn.
+#[derive(Debug, Default)]
+pub struct ActivityLog {
+ steps: Vec<Step>,
+ /// Tool call id → index in `steps`.
+ tools: HashMap<String, usize>,
+ /// The thinking step still taking text.
+ thinking: Option<usize>,
+ thinking_chars: usize,
+ dropped: usize,
+ secrets: Vec<String>,
+}
+
+fn now() -> String {
+ chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
+}
+
+impl ActivityLog {
+ /// A log that also masks these exact values (the turn's MCP secrets).
+ pub fn with_secrets(secrets: Vec<String>) -> Self {
+ Self { secrets, ..Default::default() }
+ }
+
+ /// Masks these values too, from now on.
+ pub fn add_secrets(&mut self, secrets: impl IntoIterator<Item = String>) {
+ self.secrets.extend(secrets.into_iter().filter(|s| !s.is_empty()));
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.steps.is_empty()
+ }
+
+ pub fn steps(&self) -> &[Step] {
+ &self.steps
+ }
+
+ /// Masks secrets in text shown on a step.
+ pub fn redact(&self, text: &str) -> String {
+ redact(text, &self.secrets)
+ }
+
+ fn push(&mut self, kind: &'static str, status: &'static str, title: String) -> Option<usize> {
+ if self.steps.len() >= MAX_STEPS {
+ self.dropped += 1;
+ return None;
+ }
+ self.steps.push(Step {
+ id: format!("s{}", self.steps.len() + 1),
+ kind,
+ status,
+ title: cut(&self.redact(&title), MAX_TITLE),
+ tool: None,
+ detail: None,
+ text: None,
+ ref_id: None,
+ started_at: now(),
+ ended_at: None,
+ duration_ms: None,
+ clock: Some(Instant::now()),
+ });
+ Some(self.steps.len() - 1)
+ }
+
+ fn end(&mut self, i: usize, status: &'static str) -> Step {
+ let step = &mut self.steps[i];
+ step.status = status;
+ step.ended_at = Some(now());
+ step.duration_ms = step.clock.map(|c| c.elapsed().as_millis() as u64);
+ step.clone()
+ }
+
+ /// Ends the open thinking step, if any.
+ fn close_thinking(&mut self) -> Option<Step> {
+ let i = self.thinking.take()?;
+ if let Some(text) = self.steps[i].text.take() {
+ self.steps[i].text = Some(self.redact(&text));
+ }
+ Some(self.end(i, "ok"))
+ }
+
+ /// Takes one event a driver sent and returns the steps it started or changed, ready to
+ /// broadcast. Thinking text only starts a step: the text itself streams as `thinking_delta`
+ /// and is kept on the step when it ends.
+ pub fn observe(&mut self, event: &RuntimeEvent) -> Vec<Step> {
+ let mut changed = Vec::new();
+ match event.unscoped() {
+ RuntimeEvent::ThinkingDelta(text) => {
+ if text.trim().is_empty() && self.thinking.is_none() {
+ return changed;
+ }
+ let i = match self.thinking {
+ Some(i) => i,
+ None => {
+ let Some(i) = self.push("thinking", "running", "Thinking".into()) else {
+ return changed;
+ };
+ self.thinking = Some(i);
+ changed.push(self.steps[i].clone());
+ i
+ }
+ };
+ let room = MAX_THINKING_CHARS.saturating_sub(self.thinking_chars);
+ if room > 0 {
+ let kept: String = text.chars().take(room).collect();
+ self.thinking_chars += kept.chars().count();
+ self.steps[i].text.get_or_insert_with(String::new).push_str(&kept);
+ }
+ }
+ RuntimeEvent::TextDelta(text) if !text.trim().is_empty() => {
+ changed.extend(self.close_thinking());
+ }
+ RuntimeEvent::ToolCallPending { id, name, args } => {
+ changed.extend(self.close_thinking());
+ let (title, detail) = summarize(name, args);
+ if let Some(i) = self.push("tool", "running", title) {
+ self.steps[i].tool = Some(name.clone());
+ self.steps[i].detail = detail.map(|d| cut(&self.redact(&d), MAX_DETAIL));
+ self.tools.insert(id.clone(), i);
+ changed.push(self.steps[i].clone());
+ }
+ }
+ RuntimeEvent::ToolCallCompleted { id, result } => {
+ changed.extend(self.close_thinking());
+ if let Some(i) = self.tools.remove(id) {
+ let failed = matches!(result["status"].as_str(), Some("error" | "failed" | "denied" | "cancelled"));
+ if failed {
+ let why = ["error", "content", "message"]
+ .iter()
+ .find_map(|k| result[*k].as_str().filter(|s| !s.trim().is_empty()));
+ if let Some(why) = why {
+ self.steps[i].detail = Some(cut(&self.redact(why.trim()), MAX_DETAIL));
+ }
+ }
+ changed.push(self.end(i, if failed { "failed" } else { "ok" }));
+ }
+ }
+ _ => {}
+ }
+ changed
+ }
+
+ /// A note from kwnt itself, such as which engine can't show its thinking.
+ pub fn note(&mut self, title: &str) -> Option<Step> {
+ let i = self.push("note", "ok", title.to_string())?;
+ Some(self.end(i, "ok"))
+ }
+
+ /// A step that waits on the person: an approval card (`kind` "approval") or a human step.
+ /// Returns the steps to broadcast: the thinking step it ended, if any, then the new one.
+ pub fn wait(&mut self, kind: &'static str, ref_id: &str, title: &str, tool: Option<&str>) -> Vec<Step> {
+ let mut changed: Vec<Step> = self.close_thinking().into_iter().collect();
+ if let Some(i) = self.push(kind, "waiting", title.to_string()) {
+ self.steps[i].ref_id = Some(ref_id.to_string());
+ self.steps[i].tool = tool.map(str::to_string);
+ changed.push(self.steps[i].clone());
+ }
+ changed
+ }
+
+ /// Ends the waiting step for `ref_id` with `status` ("ok", "done", "declined", "stopped").
+ pub fn settle(&mut self, ref_id: &str, status: &'static str) -> Option<Step> {
+ let i = self
+ .steps
+ .iter()
+ .rposition(|s| s.ref_id.as_deref() == Some(ref_id) && s.is_open())?;
+ Some(self.end(i, status))
+ }
+
+ /// Ends the turn: thinking closes, and anything still running or waiting is marked "stopped".
+ pub fn finish(&mut self) -> Vec<Step> {
+ let mut changed: Vec<Step> = self.close_thinking().into_iter().collect();
+ self.tools.clear();
+ for i in 0..self.steps.len() {
+ if self.steps[i].is_open() {
+ changed.push(self.end(i, "stopped"));
+ }
+ }
+ changed
+ }
+
+ /// What is saved on the reply as `meta.activity`.
+ pub fn to_json(&self) -> Value {
+ let mut v = json!({ "steps": self.steps.iter().map(Step::to_json).collect::<Vec<_>>() });
+ if self.dropped > 0 {
+ v["dropped"] = json!(self.dropped);
+ }
+ v
+ }
+}
+
+/// At most `max` characters, with `…` when cut.
+fn cut(text: &str, max: usize) -> String {
+ match text.char_indices().nth(max.saturating_sub(1)) {
+ Some((idx, _)) if text.chars().count() > max => format!("{}…", &text[..idx]),
+ _ => text.to_string(),
+ }
+}
+
+/// Prefixes of provider keys and tokens that are hidden whole wherever they appear.
+const TOKEN_PREFIXES: [&str; 12] = [
+ "sk-", "xai-", "ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_", "glpat-", "AIza", "hf_", "npm_",
+];
+
+/// Masks secrets in text shown to people: the exact `secrets`, then credentials written as
+/// `key=value`, `Bearer …`, URL passwords and provider-looking tokens.
+pub fn redact(text: &str, secrets: &[String]) -> String {
+ let text = crate::mcp::redact(text, secrets);
+ let text = crate::profiles::classify::mask_credentials(&text);
+ let mut out = String::with_capacity(text.len());
+ let mut word_start = None;
+ let is_token_char = |c: char| c.is_ascii_alphanumeric() || "-_".contains(c);
+ let flush = |out: &mut String, word: &str| {
+ let secret = word.len() >= 16 && TOKEN_PREFIXES.iter().any(|p| word.starts_with(p) && word.len() > p.len() + 8);
+ out.push_str(if secret { "[redacted]" } else { word });
+ };
+ for (i, c) in text.char_indices() {
+ match (is_token_char(c), word_start) {
+ (true, None) => word_start = Some(i),
+ (false, Some(s)) => {
+ flush(&mut out, &text[s..i]);
+ word_start = None;
+ out.push(c);
+ }
+ (false, None) => out.push(c),
+ (true, Some(_)) => {}
+ }
+ }
+ if let Some(s) = word_start {
+ flush(&mut out, &text[s..]);
+ }
+ out
+}
+
+fn arg<'a>(args: &'a Value, keys: &[&str]) -> Option<&'a str> {
+ keys.iter().find_map(|k| args.get(*k).and_then(Value::as_str)).filter(|s| !s.trim().is_empty())
+}
+
+/// The host of a URL, or the text itself when it isn't one.
+fn host_of(url: &str) -> String {
+ url::Url::parse(url)
+ .ok()
+ .and_then(|u| u.host_str().map(|h| h.trim_start_matches("www.").to_string()))
+ .unwrap_or_else(|| url.to_string())
+}
+
+/// The last two parts of a path: enough to recognise the file without the whole folder.
+fn short_path(path: &str) -> String {
+ let parts: Vec<&str> = path.trim_end_matches('/').rsplit('/').take(2).collect();
+ let short = parts.into_iter().rev().collect::<Vec<_>>().join("/");
+ if short.len() < path.trim_end_matches('/').len() {
+ format!("…/{short}")
+ } else {
+ short
+ }
+}
+
+/// A command as one line: the array form joined, a `bash -lc '…'` wrapper unwrapped.
+fn command_line(args: &Value) -> Option<String> {
+ let raw = match args.get("command").or_else(|| args.get("cmd")) {
+ Some(Value::String(s)) => s.clone(),
+ Some(Value::Array(parts)) => {
+ let parts: Vec<&str> = parts.iter().filter_map(Value::as_str).collect();
+ match parts.as_slice() {
+ [shell, flag, script] if shell.ends_with("sh") && flag.starts_with('-') && flag.contains('c') => {
+ script.to_string()
+ }
+ _ => parts.join(" "),
+ }
+ }
+ _ => return None,
+ };
+ let line = raw.split_whitespace().collect::<Vec<_>>().join(" ");
+ // codex prints its commands as `bash -lc '…'`
+ let line = ["bash -lc ", "/bin/bash -lc ", "zsh -lc ", "/bin/zsh -lc ", "sh -c "]
+ .iter()
+ .find_map(|p| line.strip_prefix(p))
+ .map(|rest| rest.trim_matches(|c| c == '\'' || c == '"').to_string())
+ .unwrap_or(line);
+ (!line.is_empty()).then_some(line)
+}
+
+/// A short title for a tool call, and the detail to show when the step is opened (the whole
+/// command, address or query). Neither is redacted here.
+pub fn summarize(name: &str, args: &Value) -> (String, Option<String>) {
+ // `mcp__server__tool`: kwnt's own tools read as built-ins, others name their server
+ let (server, tool) = match name.strip_prefix("mcp__").and_then(|r| r.split_once("__")) {
+ Some(("kwnt" | "kwant", t)) => (None, t),
+ Some((s, t)) => (Some(s), t),
+ None => (None, name),
+ };
+ let lower = tool.to_ascii_lowercase();
+ let path = || arg(args, &["file_path", "path", "filePath", "notebook_path", "target_file"]).map(short_path);
+ let url = arg(args, &["url", "href", "uri"]);
+ match lower.as_str() {
+ "bash" | "shell" | "exec" | "exec_command" | "command_execution" | "run_terminal_cmd" | "run_shell_command"
+ | "local_shell" => match command_line(args) {
+ Some(cmd) => (format!("Running `{}`", cut(&cmd, 80)), Some(cmd)),
+ None => ("Running a command".into(), None),
+ },
+ "read" | "read_file" | "view" | "cat" => (path().map_or("Reading a file".into(), |p| format!("Reading {p}")), None),
+ "edit" | "multiedit" | "edit_file" | "str_replace" | "str_replace_based_edit_tool" | "apply_patch" | "file_change"
+ | "notebookedit" => (path().map_or("Editing files".into(), |p| format!("Editing {p}")), None),
+ "write" | "write_file" | "create_file" => (path().map_or("Writing a file".into(), |p| format!("Writing {p}")), None),
+ "glob" | "grep" | "search_files" | "list_dir" | "ls" | "find" => {
+ match arg(args, &["pattern", "query", "glob", "path"]) {
+ Some(p) => (format!("Searching files for `{}`", cut(p, 60)), None),
+ None => ("Searching files".into(), None),
+ }
+ }
+ "webfetch" | "fetch" | "web_fetch" | "browser_open" | "browser_navigate" | "navigate" | "open_url" => match url {
+ Some(u) => (format!("Opening {}", host_of(u)), Some(u.to_string())),
+ None => ("Opening a page".into(), None),
+ },
+ "websearch" | "web_search" | "search" => match arg(args, &["query", "q"]) {
+ Some(q) => (format!("Searching the web for “{}”", cut(q, 80)), None),
+ None => ("Searching the web".into(), None),
+ },
+ "browser_page" | "browser_snapshot" | "browser_read" => ("Reading the browser page".into(), None),
+ "browser_act" | "browser_click" | "browser_type" => ("Using the browser".into(), None),
+ "ask_user" => ("Asking you a question".into(), None),
+ "request_human_step" => ("Asking you to do a step in the browser".into(), arg(args, &["reason"]).map(str::to_string)),
+ "task" | "agent" => match arg(args, &["description", "subagent_type"]) {
+ Some(d) => (format!("Starting a helper: {}", cut(d, 80)), None),
+ None => ("Starting a helper".into(), None),
+ },
+ "todowrite" | "todo_list" | "update_plan" => ("Updating the plan".into(), None),
+ _ => {
+ let shown = match server {
+ Some(s) => format!("Using {tool} ({s})"),
+ None => format!("Using {tool}"),
+ };
+ (shown, url.map(str::to_string))
+ }
+ }
+}
+
+/// What an engine can't show of its thinking, as the note opening a turn's steps; `None` when
+/// it streams its thinking (claude's thinking blocks, codex's reasoning summaries, grok's
+/// thoughts). `engine` is an `EngineId::as_str`.
+pub fn thinking_note(engine: &str) -> Option<&'static str> {
+ match engine {
+ "claude" | "codex" | "grok" => None,
+ // the API drivers read whole replies: no reasoning, only what the model says between tools
+ _ => Some("This engine doesn't share its thinking here; you'll see what it says between steps and each tool it runs."),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn pending(id: &str, name: &str, args: Value) -> RuntimeEvent {
+ RuntimeEvent::ToolCallPending { id: id.into(), name: name.into(), args }
+ }
+
+ fn done(id: &str, status: &str) -> RuntimeEvent {
+ RuntimeEvent::ToolCallCompleted { id: id.into(), result: json!({ "status": status }) }
+ }
+
+ #[test]
+ fn steps_follow_thinking_and_tool_runs() {
+ let mut log = ActivityLog::default();
+ let started = log.observe(&RuntimeEvent::ThinkingDelta("Let me check ".into()));
+ assert_eq!((started[0].kind, started[0].status), ("thinking", "running"));
+ // more thinking text changes nothing on the wire
+ assert!(log.observe(&RuntimeEvent::ThinkingDelta("the tests.".into())).is_empty());
+ let changed = log.observe(&pending("t1", "Bash", json!({"command": "cargo test -q"})));
+ assert_eq!(changed.len(), 2, "thinking ends when the tool starts");
+ assert_eq!((changed[0].status, changed[0].text.as_deref()), ("ok", Some("Let me check the tests.")));
+ assert_eq!(changed[1].title, "Running `cargo test -q`");
+ assert_eq!((changed[1].id.as_str(), changed[1].status), ("s2", "running"));
+ let ended = log.observe(&done("t1", "error"));
+ assert_eq!(ended[0].status, "failed");
+ assert!(ended[0].duration_ms.is_some() && ended[0].ended_at.is_some());
+ let saved = log.to_json();
+ assert_eq!(saved["steps"].as_array().unwrap().len(), 2);
+ assert!(saved.get("dropped").is_none());
+ }
+
+ #[test]
+ fn a_failed_tool_says_why_redacted() {
+ let mut log = ActivityLog::with_secrets(vec!["hunter2hunter2".into()]);
+ log.observe(&pending("a", "mcp__github__create_issue", json!({})));
+ let ended = log.observe(&RuntimeEvent::ToolCallCompleted {
+ id: "a".into(),
+ result: json!({"status": "error", "content": "401 for token hunter2hunter2"}),
+ });
+ assert_eq!(ended[0].title, "Using create_issue (github)");
+ assert_eq!(ended[0].detail.as_deref(), Some("401 for token ********"));
+ }
+
+ #[test]
+ fn steps_and_thinking_are_capped() {
+ let mut log = ActivityLog::default();
+ for i in 0..MAX_STEPS + 5 {
+ log.observe(&pending(&i.to_string(), "Read", json!({"file_path": "a.rs"})));
+ log.observe(&done(&i.to_string(), "ok"));
+ }
+ assert_eq!(log.steps().len(), MAX_STEPS);
+ assert_eq!(log.to_json()["dropped"], 5);
+
+ let mut log = ActivityLog::default();
+ log.observe(&RuntimeEvent::ThinkingDelta("x".repeat(MAX_THINKING_CHARS + 50)));
+ let closed = log.finish();
+ assert_eq!(closed[0].text.as_ref().unwrap().len(), MAX_THINKING_CHARS);
+ }
+
+ #[test]
+ fn waits_settle_and_finish_stops_what_is_open() {
+ let mut log = ActivityLog::default();
+ let w = log.wait("approval", "ap1", "Waiting for your approval: Bash", Some("Bash")).remove(0);
+ assert_eq!((w.kind, w.status, w.ref_id.as_deref()), ("approval", "waiting", Some("ap1")));
+ assert_eq!(log.settle("ap1", "ok").unwrap().status, "ok");
+ assert!(log.settle("ap1", "ok").is_none(), "settled once");
+ log.observe(&pending("t", "Read", json!({})));
+ log.wait("human_step", "hs1", "Waiting for you to sign in", None);
+ let stopped = log.finish();
+ assert_eq!(stopped.iter().map(|s| s.status).collect::<Vec<_>>(), ["stopped", "stopped"]);
+ }
+
+ #[test]
+ fn summaries_are_short_and_human() {
+ let cases = [
+ ("Bash", json!({"command": "cargo test\n --all"}), "Running `cargo test --all`"),
+ ("command_execution", json!({"command": ["bash", "-lc", "ls -la"]}), "Running `ls -la`"),
+ ("command_execution", json!({"command": "bash -lc 'cargo test'"}), "Running `cargo test`"),
+ ("Read", json!({"file_path": "/srv/app/src/main.rs"}), "Reading …/src/main.rs"),
+ ("Edit", json!({"file_path": "main.rs"}), "Editing main.rs"),
+ ("WebFetch", json!({"url": "https://www.github.com/x/y"}), "Opening github.com"),
+ ("mcp__kwnt__browser_open", json!({"url": "https://example.com/login"}), "Opening example.com"),
+ ("WebSearch", json!({"query": "rust sse"}), "Searching the web for “rust sse”"),
+ ("mcp__kwnt__ask_user", json!({}), "Asking you a question"),
+ ("mcp__linear__list_issues", json!({}), "Using list_issues (linear)"),
+ ("something_else", json!({}), "Using something_else"),
+ ];
+ for (name, args, want) in cases {
+ assert_eq!(summarize(name, &args).0, want, "{name}");
+ }
+ let long = "x".repeat(300);
+ let mut log = ActivityLog::default();
+ let s = log.observe(&pending("1", "Bash", json!({"command": long})));
+ assert!(s[0].title.chars().count() <= MAX_TITLE);
+ assert!(s[0].detail.as_ref().unwrap().chars().count() <= MAX_DETAIL);
+ }
+
+ #[test]
+ fn redaction_hides_secrets_in_titles_and_details() {
+ let mut log = ActivityLog::with_secrets(vec!["s3cr3t-value-123".into()]);
+ let s = log.observe(&pending(
+ "1",
+ "Bash",
+ json!({"command": "curl -H 'Authorization: Bearer abc.def.ghi' https://u:[email protected]/?token=zzz9 && OPENAI_API_KEY=sk-proj-abcdefghijklmnop1234 run --pass s3cr3t-value-123"}),
+ ));
+ let shown = format!("{} {}", s[0].title, s[0].detail.as_deref().unwrap());
+ for leaked in ["abc.def.ghi", ":pw@", "zzz9", "sk-proj", "s3cr3t-value-123"] {
+ assert!(!shown.contains(leaked), "{leaked} leaked in {shown}");
+ }
+ assert!(shown.contains("curl"));
+ for (text, want) in [
+ ("push with ghp_abcdefghijklmnopqrstuvwxyz0123", "push with [redacted]"),
+ ("key xai-AbCdEfGhIjKlMnOpQrSt9 here", "key [redacted] here"),
+ ("the sk- prefix and skip-this", "the sk- prefix and skip-this"),
+ ] {
+ assert_eq!(redact(text, &[]), want);
+ }
+ }
+}
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index d268395b..37136fd5 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -522,7 +522,20 @@ impl CliDriver {
}
super::grok::StreamEvent::Error(message) => run.errors.push(message),
super::grok::StreamEvent::End { stop_reason } => run.stop_reason = stop_reason,
- super::grok::StreamEvent::ToolCall => run.tool_calls = true,
+ super::grok::StreamEvent::Thought(text) => {
+ let _ = event_tx.send(RuntimeEvent::ThinkingDelta(text)).await;
+ }
+ super::grok::StreamEvent::ToolStart { id, name, args } => {
+ run.tool_calls = true;
+ let _ = event_tx.send(RuntimeEvent::ToolCallPending { id, name, args }).await;
+ }
+ super::grok::StreamEvent::ToolEnd { id, ok, error } => {
+ let result = match error {
+ Some(why) if !ok => serde_json::json!({ "status": "error", "error": why }),
+ _ => serde_json::json!({ "status": "ok" }),
+ };
+ let _ = event_tx.send(RuntimeEvent::ToolCallCompleted { id, result }).await;
+ }
}
}
@@ -678,8 +691,9 @@ const CLAUDE_SHOWN_ARGS_MAX: usize = 2000;
const CLAUDE_PROGRESS_EVERY: Duration = Duration::from_secs(1);
/// What `claude -p --output-format stream-json` prints, one JSON object per line, turned into
-/// events as it arrives: each tool call claude starts and finishes, and `Progress` for anything
-/// else, so the turn's stall watchdog sees a claude that is still working and pauses while a tool
+/// events as it arrives: its thinking (`ThinkingDelta`, from the partial `thinking_delta`s, or
+/// from whole `thinking` blocks when it doesn't stream them), each tool call claude starts and
+/// finishes, and `Progress` for anything else, so the turn's stall watchdog sees a claude that is still working and pauses while a tool
/// (or its approval card) runs. Keeps the final `result` line for [`ClaudeResult::parse`].
#[derive(Default)]
struct ClaudeStream {
@@ -691,6 +705,8 @@ struct ClaudeStream {
/// Output that isn't JSON (an older claude without `stream-json`).
plain: String,
last_progress: Option<Instant>,
+ /// Thinking arrived as partial deltas, so the whole `thinking` blocks repeat it.
+ thinking_streamed: bool,
}
impl ClaudeStream {
@@ -710,7 +726,23 @@ impl ClaudeStream {
let blocks = v["message"]["content"].as_array().map(Vec::as_slice).unwrap_or_default();
match v["type"].as_str() {
Some("result") => self.result_line = Some(line.to_string()),
+ Some("stream_event") => {
+ let delta = &v["event"]["delta"];
+ if v["event"]["type"] == "content_block_delta" && delta["type"] == "thinking_delta" {
+ if let Some(text) = delta["thinking"].as_str().filter(|t| !t.is_empty()) {
+ self.thinking_streamed = true;
+ events.push(RuntimeEvent::ThinkingDelta(text.to_string()));
+ }
+ }
+ }
Some("assistant") => {
+ if !self.thinking_streamed {
+ for b in blocks.iter().filter(|b| b["type"] == "thinking") {
+ if let Some(text) = b["thinking"].as_str().filter(|t| !t.trim().is_empty()) {
+ events.push(RuntimeEvent::ThinkingDelta(format!("{text}\n")));
+ }
+ }
+ }
for b in blocks.iter().filter(|b| b["type"] == "tool_use") {
let Some(id) = b["id"].as_str().filter(|id| self.seen.insert(id.to_string())) else {
continue;
@@ -758,9 +790,41 @@ impl ClaudeStream {
}
}
+/// A CLI's line-per-event stdout, read as it arrives.
+trait LineStream {
+ fn line(&mut self, line: &str, now: Instant) -> Vec<RuntimeEvent>;
+ /// For a line too long to read whole.
+ fn skipped(&mut self, now: Instant) -> Vec<RuntimeEvent>;
+}
+
+impl LineStream for ClaudeStream {
+ fn line(&mut self, line: &str, now: Instant) -> Vec<RuntimeEvent> {
+ ClaudeStream::line(self, line, now)
+ }
+ fn skipped(&mut self, now: Instant) -> Vec<RuntimeEvent> {
+ self.progress(now)
+ }
+}
+
+impl LineStream for super::codex_json::CodexStream {
+ fn line(&mut self, line: &str, _: Instant) -> Vec<RuntimeEvent> {
+ super::codex_json::CodexStream::line(self, line)
+ }
+ fn skipped(&mut self, _: Instant) -> Vec<RuntimeEvent> {
+ Vec::new()
+ }
+}
+
/// Reads claude's `stream-json` stdout to the end, sending its events as they arrive.
-async fn read_claude_stream<R: tokio::io::AsyncRead + Unpin>(mut pipe: R, event_tx: &mpsc::Sender<RuntimeEvent>) -> String {
+async fn read_claude_stream<R: tokio::io::AsyncRead + Unpin>(pipe: R, event_tx: &mpsc::Sender<RuntimeEvent>) -> String {
let mut stream = ClaudeStream::default();
+ read_lines(pipe, &mut stream, event_tx).await;
+ stream.into_stdout()
+}
+
+/// Reads a CLI's stdout to the end, one line at a time, sending the events `stream` makes of
+/// each line as they arrive. A line longer than [`CLAUDE_LINE_MAX`] is skipped.
+async fn read_lines<R: tokio::io::AsyncRead + Unpin, S: LineStream>(mut pipe: R, stream: &mut S, event_tx: &mpsc::Sender<RuntimeEvent>) {
let mut line: Vec<u8> = Vec::new();
// The rest of a line longer than CLAUDE_LINE_MAX is being skipped
let mut skipping = false;
@@ -785,7 +849,7 @@ async fn read_claude_stream<R: tokio::io::AsyncRead + Unpin>(mut pipe: R, event_
}
}
let events = if ended {
- let events = if skipping { stream.progress(Instant::now()) } else { stream.line(&String::from_utf8_lossy(&line), Instant::now()) };
+ let events = if skipping { stream.skipped(Instant::now()) } else { stream.line(&String::from_utf8_lossy(&line), Instant::now()) };
line.clear();
skipping = false;
events
@@ -802,7 +866,6 @@ async fn read_claude_stream<R: tokio::io::AsyncRead + Unpin>(mut pipe: R, event_
let _ = event_tx.send(event).await;
}
}
- stream.into_stdout()
}
/// What `claude -p --output-format stream-json` reports on its final `result` line.
@@ -989,7 +1052,9 @@ impl Driver for CliDriver {
// commands; blank it there (a `set` entry merges, keeping the user's policy)
cmd.arg("-c").arg(format!("shell_environment_policy.set.{}=\"\"", crate::mcp::GATEWAY_TOKEN_ENV));
}
- cmd.arg("-o")
+ // its steps as JSON events on stdout (live activity); the reply still comes from -o
+ cmd.arg("--json")
+ .arg("-o")
.arg(&out_file)
.arg(&full_prompt);
codex_out_file = Some(out_file);
@@ -1123,13 +1188,9 @@ impl Driver for CliDriver {
cmd.args(&env.args);
}
- // codex's reply comes from its -o file; an unread pipe could fill up and stall the CLI
+ // codex's reply comes from its -o file; its stdout carries the `--json` steps
cmd.stdin(Stdio::null());
- cmd.stdout(if codex_out_file.is_some() {
- Stdio::null()
- } else {
- Stdio::piped()
- });
+ cmd.stdout(Stdio::piped());
// codex reports a usage limit or sign-out only on stderr
cmd.stderr(if codex_out_file.is_some() {
Stdio::piped()
@@ -1145,8 +1206,15 @@ impl Driver for CliDriver {
let mut group = ProcessGroup::of(&child);
let stdout_pipe = child.stdout.take();
let stderr_pipe = child.stderr.take();
+ let is_codex = codex_out_file.is_some();
+ let mut codex_stream = super::codex_json::CodexStream::default();
+ let codex_stream_ref = &mut codex_stream;
let read_stdout = async {
match stdout_pipe {
+ Some(stdout) if is_codex => {
+ read_lines(stdout, codex_stream_ref, &event_tx).await;
+ String::new()
+ }
Some(stdout) => read_claude_stream(stdout, &event_tx).await,
None => String::new(),
}
@@ -1168,8 +1236,11 @@ impl Driver for CliDriver {
.unwrap_or_default();
let _ = tokio::fs::remove_file(out_file).await;
let failed = !exit.is_some_and(|s| s.success());
- if content.trim().is_empty() && failed && !codex_had_effects(&stderr) {
- if let Some(failure) = refusal(&codex_error_lines(&stderr)) {
+ // with --json the final error and the steps are on stdout, not stderr
+ let had_effects = codex_stream.had_effects || codex_had_effects(&stderr);
+ if content.trim().is_empty() && failed && !had_effects {
+ let errors = format!("{}\n{}", codex_error_lines(&stderr), codex_stream.errors);
+ if let Some(failure) = refusal(errors.trim()) {
return Ok(TurnOutput::refused(failure));
}
}
diff --git a/src/drivers/codex_json.rs b/src/drivers/codex_json.rs
new file mode 100644
index 00000000..722a3670
--- /dev/null
+++ b/src/drivers/codex_json.rs
@@ -0,0 +1,187 @@
+//! What `codex exec --json` prints on stdout, one JSON event per line, turned into events as it
+//! arrives: its reasoning summaries (`ThinkingDelta`) and each command, file change, MCP tool
+//! call, web search and plan update it starts and finishes. The reply itself still comes from
+//! codex's `-o` file. Errors are kept for the refusal check, since `--json` moves the final
+//! error from stderr to stdout.
+
+use super::events::RuntimeEvent;
+use serde_json::{json, Value};
+use std::collections::HashSet;
+
+/// Longest error text kept from codex's events, over all of them.
+const ERRORS_MAX: usize = 4000;
+
+#[derive(Default)]
+pub struct CodexStream {
+ /// Items started and not yet finished, by item id.
+ running: HashSet<String>,
+ /// Items already finished, so a repeated `item.completed` isn't reported twice.
+ finished: HashSet<String>,
+ /// It ran a command, changed a file or called a tool.
+ pub had_effects: bool,
+ /// The turn's errors, one per line, retries left out.
+ pub errors: String,
+}
+
+/// The tool name and arguments an item is shown with, or `None` for items that aren't tool runs.
+fn as_tool(item: &Value) -> Option<(String, Value)> {
+ let s = |k: &str| item[k].as_str().unwrap_or_default().to_string();
+ Some(match item["type"].as_str()? {
+ "command_execution" => ("command_execution".into(), json!({ "command": item["command"] })),
+ "file_change" => {
+ let path = item["changes"].as_array().and_then(|c| c.first()).map(|c| c["path"].clone());
+ ("file_change".into(), json!({ "path": path.unwrap_or(Value::Null) }))
+ }
+ "mcp_tool_call" => (format!("mcp__{}__{}", s("server"), s("tool")), item["arguments"].clone()),
+ "web_search" => ("web_search".into(), json!({ "query": item["query"] })),
+ "todo_list" => ("todo_list".into(), json!({})),
+ _ => return None,
+ })
+}
+
+/// How a finished item went: `ok`, or `error` with why.
+fn outcome(item: &Value) -> Value {
+ let status = item["status"].as_str().unwrap_or_default();
+ match item["type"].as_str() {
+ Some("command_execution") => match item["exit_code"].as_i64() {
+ Some(0) if status != "failed" => json!({ "status": "ok" }),
+ Some(code) => json!({ "status": "error", "error": format!("exit code {code}") }),
+ None if status == "failed" || status == "declined" => json!({ "status": "error", "error": status }),
+ None => json!({ "status": "ok" }),
+ },
+ _ if status == "failed" || status == "declined" || item["error"].is_object() => {
+ let why = item["error"]["message"].as_str().unwrap_or(status);
+ json!({ "status": "error", "error": why })
+ }
+ _ => json!({ "status": "ok" }),
+ }
+}
+
+impl CodexStream {
+ fn keep_error(&mut self, message: &str) {
+ let message = message.trim();
+ // "Reconnecting... 2/5 (…)" is a retry; the error that ends the turn follows it
+ if message.is_empty() || message.starts_with("Reconnecting") || self.errors.len() >= ERRORS_MAX {
+ return;
+ }
+ if !self.errors.lines().any(|l| l == message) {
+ self.errors.push_str(message);
+ self.errors.push('\n');
+ }
+ }
+
+ pub fn line(&mut self, line: &str) -> Vec<RuntimeEvent> {
+ let Ok(v) = serde_json::from_str::<Value>(line.trim()) else {
+ return Vec::new();
+ };
+ let mut events = Vec::new();
+ let item = &v["item"];
+ let id = item["id"].as_str().unwrap_or_default().to_string();
+ match v["type"].as_str() {
+ Some("error") => self.keep_error(v["message"].as_str().unwrap_or_default()),
+ Some("turn.failed") => self.keep_error(v["error"]["message"].as_str().unwrap_or_default()),
+ Some("item.started") => {
+ if let Some((name, args)) = as_tool(item).filter(|_| !id.is_empty()) {
+ if self.running.insert(id.clone()) {
+ self.had_effects |= item["type"] != "todo_list";
+ events.push(RuntimeEvent::ToolCallPending { id, name, args });
+ }
+ }
+ }
+ Some("item.completed") => match item["type"].as_str() {
+ Some("reasoning") => {
+ if let Some(text) = item["text"].as_str().filter(|t| !t.trim().is_empty()) {
+ events.push(RuntimeEvent::ThinkingDelta(format!("{}\n", text.trim_end())));
+ }
+ }
+ Some("error") => self.keep_error(item["message"].as_str().unwrap_or_default()),
+ _ => {
+ if let Some((name, args)) = as_tool(item).filter(|_| !id.is_empty()) {
+ if self.finished.insert(id.clone()) {
+ self.had_effects |= item["type"] != "todo_list";
+ // a file change is often only reported once it's done
+ if !self.running.remove(&id) {
+ events.push(RuntimeEvent::ToolCallPending { id: id.clone(), name, args });
+ }
+ events.push(RuntimeEvent::ToolCallCompleted { id, result: outcome(item) });
+ }
+ }
+ }
+ },
+ _ => {}
+ }
+ events
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn kinds(events: &[RuntimeEvent]) -> Vec<String> {
+ events
+ .iter()
+ .map(|e| match e {
+ RuntimeEvent::ThinkingDelta(t) => format!("think {}", t.trim()),
+ RuntimeEvent::ToolCallPending { id, name, .. } => format!("start {id} {name}"),
+ RuntimeEvent::ToolCallCompleted { id, result } => format!(
+ "end {id} {}{}",
+ result["status"].as_str().unwrap_or(""),
+ result["error"].as_str().map(|e| format!(" ({e})")).unwrap_or_default()
+ ),
+ other => format!("{other:?}"),
+ })
+ .collect()
+ }
+
+ fn run(fixture: &str) -> (CodexStream, Vec<String>) {
+ let mut s = CodexStream::default();
+ let events: Vec<RuntimeEvent> = fixture.lines().flat_map(|l| s.line(l)).collect();
+ (s, kinds(&events))
+ }
+
+ /// A working codex turn, shaped like codex-cli 0.16x `exec --json` output.
+ const WORKING: &str = include_str!("fixtures/codex_exec_json.jsonl");
+ /// codex with no sign-in: retries, a fallback notice, then the error that ends the turn.
+ const SIGNED_OUT: &str = include_str!("fixtures/codex_exec_json_401.jsonl");
+
+ #[test]
+ fn codex_json_reports_reasoning_and_each_tool_run() {
+ let (s, kinds) = run(WORKING);
+ assert_eq!(
+ kinds,
+ [
+ "think **Checking the tests**\n\nI'll run the test suite first.",
+ "start item_1 command_execution",
+ "end item_1 error (exit code 101)",
+ "start item_2 file_change",
+ "end item_2 ok",
+ "start item_3 mcp__github__create_issue",
+ "end item_3 error (forbidden)",
+ "start item_4 web_search",
+ "end item_4 ok",
+ ]
+ );
+ assert!(s.had_effects);
+ assert!(s.errors.is_empty());
+ }
+
+ #[test]
+ fn codex_json_keeps_the_error_that_ended_the_turn_for_the_refusal_check() {
+ let (s, kinds) = run(SIGNED_OUT);
+ assert!(kinds.is_empty(), "{kinds:?}");
+ assert!(!s.had_effects);
+ assert!(!s.errors.contains("Reconnecting"), "{}", s.errors);
+ assert!(s.errors.contains("unexpected status 401 Unauthorized"), "{}", s.errors);
+ assert_eq!(s.errors.lines().count(), 2, "the fallback notice and the final error, once each: {}", s.errors);
+ }
+
+ #[test]
+ fn codex_json_titles_read_like_people_wrote_them() {
+ let mut s = CodexStream::default();
+ let events = s.line(r#"{"type":"item.started","item":{"id":"i","type":"command_execution","command":"bash -lc 'cargo test'","status":"in_progress"}}"#);
+ let RuntimeEvent::ToolCallPending { name, args, .. } = &events[0] else { panic!() };
+ assert_eq!(crate::drivers::activity::summarize(name, args).0, "Running `cargo test`");
+ assert!(s.line("not json").is_empty());
+ }
+}
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index 33c9b33f..b3a53104 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -90,6 +90,16 @@ pub enum RuntimeEvent {
/// A question an agent asked the user was asked, answered or cancelled.
#[serde(rename = "question_updated", alias = "QuestionUpdated")]
QuestionUpdated { question: Value },
+ /// A step of a running turn started or changed (thinking, a tool run, a wait for an approval
+ /// or for the person). Only sent inside a turn (`Scoped`); `step` is the whole step, so a
+ /// client replaces the one with the same `id`. See [`crate::drivers::activity::Step`].
+ #[serde(rename = "activity", alias = "Activity")]
+ Activity { step: Value },
+ /// A bot asked the person to do a step in the browser (sign in, solve a CAPTCHA), or the
+ /// step was done, declined or cancelled; `step` is the whole record. See
+ /// `crate::db::human_steps`.
+ #[serde(rename = "human_step_updated", alias = "HumanStepUpdated")]
+ HumanStepUpdated { step: Value },
/// An MCP server an agent suggested was suggested, installed or dismissed; `suggestion` is the
/// whole record. See `crate::db::mcp_suggestions`.
#[serde(rename = "mcp_suggestion_updated", alias = "McpSuggestionUpdated")]
@@ -218,8 +228,8 @@ pub enum RuntimeEvent {
run_id: String,
status: String,
},
- /// Something the user asked to be told about. `kind` is "turn_finished", "approval_needed"
- /// or "routine_failed". `body` never holds chat text, tool arguments or secrets.
+ /// Something the user asked to be told about. `kind` is one of `continuity::NOTIFY_KINDS`
+ /// ("turn_finished", "approval_needed", "human_step", …). `body` never holds chat text, tool arguments or secrets.
#[serde(rename = "notify", alias = "Notify")]
Notify {
kind: String,
diff --git a/src/drivers/fixtures/codex_exec_json.jsonl b/src/drivers/fixtures/codex_exec_json.jsonl
new file mode 100644
index 00000000..632e12fd
--- /dev/null
+++ b/src/drivers/fixtures/codex_exec_json.jsonl
@@ -0,0 +1,15 @@
+{"type":"thread.started","thread_id":"00000000-0000-0000-0000-000000000001"}
+{"type":"turn.started"}
+{"type":"item.started","item":{"id":"item_0","type":"reasoning","text":""}}
+{"type":"item.completed","item":{"id":"item_0","type":"reasoning","text":"**Checking the tests**\n\nI'll run the test suite first."}}
+{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"bash -lc 'cargo test -q'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
+{"type":"item.updated","item":{"id":"item_1","type":"command_execution","command":"bash -lc 'cargo test -q'","aggregated_output":"running 3 tests\n","exit_code":null,"status":"in_progress"}}
+{"type":"item.completed","item":{"id":"item_1","type":"command_execution","command":"bash -lc 'cargo test -q'","aggregated_output":"test result: FAILED. 2 passed; 1 failed\n","exit_code":101,"status":"failed"}}
+{"type":"item.completed","item":{"id":"item_2","type":"file_change","changes":[{"path":"src/lib.rs","kind":"update"}],"status":"completed"}}
+{"type":"item.completed","item":{"id":"item_2","type":"file_change","changes":[{"path":"src/lib.rs","kind":"update"}],"status":"completed"}}
+{"type":"item.started","item":{"id":"item_3","type":"mcp_tool_call","server":"github","tool":"create_issue","arguments":{"title":"Flaky test"},"result":null,"error":null,"status":"in_progress"}}
+{"type":"item.completed","item":{"id":"item_3","type":"mcp_tool_call","server":"github","tool":"create_issue","arguments":{"title":"Flaky test"},"result":null,"error":{"message":"forbidden"},"status":"failed"}}
+{"type":"item.started","item":{"id":"item_4","type":"web_search","query":"cargo test flaky"}}
+{"type":"item.completed","item":{"id":"item_4","type":"web_search","query":"cargo test flaky"}}
+{"type":"item.completed","item":{"id":"item_5","type":"agent_message","text":"One test fails; I opened an issue."}}
+{"type":"turn.completed","usage":{"input_tokens":1200,"cached_input_tokens":800,"output_tokens":90}}
diff --git a/src/drivers/fixtures/codex_exec_json_401.jsonl b/src/drivers/fixtures/codex_exec_json_401.jsonl
new file mode 100644
index 00000000..43717f18
--- /dev/null
+++ b/src/drivers/fixtures/codex_exec_json_401.jsonl
@@ -0,0 +1,14 @@
+{"type":"thread.started","thread_id":"00000000-0000-0000-0000-000000000002"}
+{"type":"turn.started"}
+{"type":"error","message":"Reconnecting... 2/5 (unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: wss://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA)"}
+{"type":"error","message":"Reconnecting... 3/5 (unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: wss://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA)"}
+{"type":"error","message":"Reconnecting... 4/5 (unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: wss://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA)"}
+{"type":"error","message":"Reconnecting... 5/5 (unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: wss://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA)"}
+{"type":"item.completed","item":{"id":"item_0","type":"error","message":"Falling back from WebSockets to HTTPS transport. unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: wss://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA"}}
+{"type":"error","message":"Reconnecting... 1/5 (unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA, request id: req_0)"}
+{"type":"error","message":"Reconnecting... 2/5 (unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA, request id: req_0)"}
+{"type":"error","message":"Reconnecting... 3/5 (unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA, request id: req_0)"}
+{"type":"error","message":"Reconnecting... 4/5 (unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA, request id: req_0)"}
+{"type":"error","message":"Reconnecting... 5/5 (unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA, request id: req_0)"}
+{"type":"error","message":"unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA, request id: req_0"}
+{"type":"turn.failed","error":{"message":"unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses, cf-ray: 0000000000000000-AAA, request id: req_0"}}
diff --git a/src/drivers/fixtures/grok_streaming.jsonl b/src/drivers/fixtures/grok_streaming.jsonl
new file mode 100644
index 00000000..aec5de82
--- /dev/null
+++ b/src/drivers/fixtures/grok_streaming.jsonl
@@ -0,0 +1,12 @@
+{"type":"available_commands","commands":[]}
+{"type":"thought","data":"Let me look at the entry point. "}
+{"type":"thought","data":"Then run the tests."}
+{"type":"tool_call","toolCallId":"call_1","title":"Read","kind":"read","status":"in_progress","toolName":"read_file","rawInput":{"path":"src/main.rs"}}
+{"type":"tool_call_update","toolCallId":"call_1","status":"completed","rawOutput":{"content":"fn main() {}"}}
+{"type":"tool_call","toolCallId":"call_2","title":"Terminal","kind":"execute","status":"pending","toolName":"run_terminal_cmd","rawInput":{"command":"cargo test"}}
+{"type":"tool_call_update","toolCallId":"call_2","status":"in_progress"}
+{"type":"tool_call_update","toolCallId":"call_2","status":"failed","rawOutput":{"error":"exit status 101"}}
+{"type":"tool_call_update","toolCallId":"call_2","status":"failed","rawOutput":{"error":"exit status 101"}}
+{"type":"usage","inputTokens":100,"outputTokens":20}
+{"type":"text","data":"Two tests fail."}
+{"type":"end","stopReason":"end_turn"}
diff --git a/src/drivers/grok.rs b/src/drivers/grok.rs
index 3a978e82..a69225ea 100644
--- a/src/drivers/grok.rs
+++ b/src/drivers/grok.rs
@@ -332,8 +332,12 @@ pub enum StreamEvent {
Error(String),
/// The run ended; `stop_reason` is e.g. `end_turn`, `refusal`, `cancelled`.
End { stop_reason: Option<String> },
- /// grok called a tool: the turn has had effects, so it must not be retried elsewhere.
- ToolCall,
+ /// A piece of grok's thinking (`thought`).
+ Thought(String),
+ /// grok started a tool: the turn has had effects, so it must not be retried elsewhere.
+ ToolStart { id: String, name: String, args: serde_json::Value },
+ /// A tool grok started finished; `error` says why when it didn't succeed.
+ ToolEnd { id: String, ok: bool, error: Option<String> },
}
/// Splits grok's NDJSON output into events. Lines that aren't JSON are passed on as text, so
@@ -341,6 +345,10 @@ pub enum StreamEvent {
#[derive(Debug, Default)]
pub struct StreamParser {
pending: String,
+ /// Tools started and not yet finished, by `toolCallId`.
+ running: std::collections::HashSet<String>,
+ /// Tools seen at all, so a repeated update doesn't start one again.
+ seen: std::collections::HashSet<String>,
}
impl StreamParser {
@@ -349,7 +357,7 @@ impl StreamParser {
let mut events = Vec::new();
while let Some(end) = self.pending.find('\n') {
let line: String = self.pending.drain(..=end).collect();
- events.extend(parse_line(&line));
+ events.extend(self.parse_line(&line));
}
events
}
@@ -357,7 +365,44 @@ impl StreamParser {
/// Whatever is left after the last newline.
pub fn finish(&mut self) -> Vec<StreamEvent> {
let rest = std::mem::take(&mut self.pending);
- parse_line(&rest).into_iter().collect()
+ self.parse_line(&rest)
+ }
+
+ fn parse_line(&mut self, line: &str) -> Vec<StreamEvent> {
+ let Ok(value) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
+ return parse_line(line).into_iter().collect();
+ };
+ if !matches!(value["type"].as_str(), Some("tool_call" | "tool_call_update")) {
+ return parse_line(line).into_iter().collect();
+ }
+ // `tool_call` starts a tool, `tool_call_update` moves it on; either can come first
+ let id = match value["toolCallId"].as_str().filter(|i| !i.is_empty()) {
+ Some(id) => id.to_string(),
+ None => format!("grok-{}", self.seen.len() + 1),
+ };
+ let mut events = Vec::new();
+ if self.seen.insert(id.clone()) {
+ let name = ["toolName", "title", "kind"]
+ .iter()
+ .find_map(|k| value[*k].as_str().filter(|n| !n.is_empty()))
+ .unwrap_or("tool")
+ .to_string();
+ let args = value.get("rawInput").cloned().unwrap_or(serde_json::Value::Null);
+ self.running.insert(id.clone());
+ events.push(StreamEvent::ToolStart { id: id.clone(), name, args });
+ }
+ let status = value["status"].as_str().unwrap_or_default();
+ if matches!(status, "completed" | "failed" | "cancelled") && self.running.remove(&id) {
+ let error = (status != "completed").then(|| {
+ value["rawOutput"]["error"]
+ .as_str()
+ .or_else(|| value["error"].as_str())
+ .unwrap_or(status)
+ .to_string()
+ });
+ events.push(StreamEvent::ToolEnd { id, ok: status == "completed", error });
+ }
+ events
}
}
@@ -382,7 +427,10 @@ fn parse_line(line: &str) -> Option<StreamEvent> {
Some("end") => Some(StreamEvent::End {
stop_reason: value["stopReason"].as_str().map(str::to_string),
}),
- Some("tool_call") | Some("tool_call_update") => Some(StreamEvent::ToolCall),
+ Some("thought") => value["data"]
+ .as_str()
+ .filter(|t| !t.is_empty())
+ .map(|t| StreamEvent::Thought(t.to_string())),
Some(_) => None,
None => Some(StreamEvent::Text(line.to_string())),
}
@@ -557,7 +605,7 @@ include_only = ["*"]
[
StreamEvent::Text("Hel".into()),
StreamEvent::Text("lo\n".into()),
- StreamEvent::ToolCall,
+ StreamEvent::ToolStart { id: "c1".into(), name: "tool".into(), args: serde_json::Value::Null },
StreamEvent::Text("plain line\n".into()),
StreamEvent::Error("boom".into()),
StreamEvent::End {
@@ -568,6 +616,40 @@ include_only = ["*"]
assert!(parser.finish().is_empty());
}
+ /// A grok turn in `--output-format streaming-json`, shaped like the headless-mode guide's
+ /// examples: thoughts, a tool that works, one that fails, and an update repeated.
+ const STREAMING_JSON: &str = include_str!("fixtures/grok_streaming.jsonl");
+
+ #[test]
+ fn grok_stream_reports_thoughts_and_tool_runs() {
+ let mut parser = StreamParser::default();
+ let mut events = parser.push(STREAMING_JSON);
+ events.extend(parser.finish());
+ let shown: Vec<String> = events
+ .iter()
+ .map(|e| match e {
+ StreamEvent::Thought(t) => format!("think {t}"),
+ StreamEvent::ToolStart { id, name, args } => format!("start {id} {name} {args}"),
+ StreamEvent::ToolEnd { id, ok, error } => format!("end {id} {ok} {}", error.as_deref().unwrap_or("-")),
+ StreamEvent::Text(t) => format!("text {t}"),
+ other => format!("{other:?}"),
+ })
+ .collect();
+ assert_eq!(
+ shown,
+ [
+ "think Let me look at the entry point. ",
+ "think Then run the tests.",
+ r#"start call_1 read_file {"path":"src/main.rs"}"#,
+ "end call_1 true -",
+ r#"start call_2 run_terminal_cmd {"command":"cargo test"}"#,
+ "end call_2 false exit status 101",
+ "text Two tests fail.",
+ "End { stop_reason: Some(\"end_turn\") }",
+ ]
+ );
+ }
+
#[test]
fn empty_reply_explains_refused_tools() {
let stderr = "warn: x\npermission required: run_terminal_cmd was not run, as a headless run cannot ask for approval\npermission required: kwnt__alpha-ping was not run, as a headless run cannot ask for approval\npermission required: run_terminal_cmd was not run, as a headless run cannot ask for approval\n";
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index e4c9e22e..8a5e5caa 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -1,5 +1,7 @@
+pub mod activity;
pub mod api;
pub mod cli;
+pub mod codex_json;
pub mod custom;
pub mod engines;
pub mod events;
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 81a2e757..75f80111 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -236,6 +236,9 @@ pub struct BrowserController {
target_id: Option<String>,
browser_level: bool,
pub control: Arc<RwLock<()>>,
+ /// Held while a human step (sign in, CAPTCHA) waits on the person: bot actions get
+ /// `HumanControl` and the person's live-view input goes through without taking control.
+ held_for_person: Arc<std::sync::Mutex<Option<OwnedRwLockWriteGuard<()>>>>,
}
impl std::fmt::Debug for BrowserController {
@@ -262,6 +265,7 @@ impl BrowserController {
target_id: None,
browser_level: false,
control: Arc::new(RwLock::new(())),
+ held_for_person: Arc::default(),
}
}
@@ -282,6 +286,27 @@ impl BrowserController {
self.control.clone().try_write_owned().map_err(|_| BrowserError::HumanControl)
}
+ /// Locks the browser to the person until [`Self::release_person_hold`]. Waits briefly for a
+ /// bot action in flight; `false` if it couldn't (the person already has control, say).
+ pub async fn hold_for_person(&self) -> bool {
+ if self.is_held_for_person() {
+ return true;
+ }
+ let Ok(guard) = timeout(std::time::Duration::from_secs(5), self.control.clone().write_owned()).await else {
+ return false;
+ };
+ *self.held_for_person.lock().unwrap_or_else(|e| e.into_inner()) = Some(guard);
+ true
+ }
+
+ pub fn release_person_hold(&self) {
+ self.held_for_person.lock().unwrap_or_else(|e| e.into_inner()).take();
+ }
+
+ pub fn is_held_for_person(&self) -> bool {
+ self.held_for_person.lock().unwrap_or_else(|e| e.into_inner()).is_some()
+ }
+
pub fn is_managed_session(&self) -> bool { self.target_id.is_some() }
pub async fn refresh_location(&self) -> Result<(), BrowserError> {
diff --git a/src/server/activity.rs b/src/server/activity.rs
new file mode 100644
index 00000000..26079b14
--- /dev/null
+++ b/src/server/activity.rs
@@ -0,0 +1,141 @@
+//! A running turn's live activity (see [`crate::drivers::activity`]): the turn's events feed its
+//! log, and every changed step goes out as a scoped `activity` event. Turns are registered by id
+//! so code that only knows the turn id (approval cards, human steps) can add a waiting step.
+
+use crate::drivers::activity::{ActivityLog, Step};
+use crate::drivers::events::{RuntimeEvent, TurnTag};
+use serde_json::Value;
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, OnceLock, Weak};
+use tokio::sync::broadcast;
+
+/// The activity of one running turn.
+pub struct TurnActivity {
+ log: Mutex<ActivityLog>,
+ sender: broadcast::Sender<RuntimeEvent>,
+ tag: TurnTag,
+}
+
+fn turns() -> &'static Mutex<HashMap<String, Weak<TurnActivity>>> {
+ static TURNS: OnceLock<Mutex<HashMap<String, Weak<TurnActivity>>>> = OnceLock::new();
+ TURNS.get_or_init(Default::default)
+}
+
+impl TurnActivity {
+ /// Starts the turn's log and registers it under its turn id until it is dropped.
+ pub fn start(sender: broadcast::Sender<RuntimeEvent>, tag: TurnTag) -> Arc<Self> {
+ let this = Arc::new(Self { log: Mutex::new(ActivityLog::default()), sender, tag });
+ let mut all = turns().lock().unwrap_or_else(|e| e.into_inner());
+ all.retain(|_, w| w.strong_count() > 0);
+ all.insert(this.tag.turn_id.clone(), Arc::downgrade(&this));
+ this
+ }
+
+ /// The running turn with this id, if any.
+ pub fn find(turn_id: &str) -> Option<Arc<Self>> {
+ turns().lock().unwrap_or_else(|e| e.into_inner()).get(turn_id).and_then(Weak::upgrade)
+ }
+
+ fn with_log<T>(&self, f: impl FnOnce(&mut ActivityLog) -> T) -> T {
+ f(&mut self.log.lock().unwrap_or_else(|e| e.into_inner()))
+ }
+
+ fn send(&self, steps: impl IntoIterator<Item = Step>) {
+ for step in steps {
+ let _ = self.sender.send(RuntimeEvent::Scoped {
+ tag: self.tag.clone(),
+ event: Box::new(RuntimeEvent::Activity { step: step.to_json() }),
+ });
+ }
+ }
+
+ /// Masks these values on every step from now on (the turn's MCP secrets).
+ pub fn add_secrets(&self, secrets: Vec<String>) {
+ self.with_log(|log| log.add_secrets(secrets));
+ }
+
+ pub fn observe(&self, event: &RuntimeEvent) {
+ let steps = self.with_log(|log| log.observe(event));
+ self.send(steps);
+ }
+
+ pub fn note(&self, title: &str) {
+ let step = self.with_log(|log| log.note(title));
+ self.send(step);
+ }
+
+ pub fn wait(&self, kind: &'static str, ref_id: &str, title: &str, tool: Option<&str>) {
+ let steps = self.with_log(|log| log.wait(kind, ref_id, title, tool));
+ self.send(steps);
+ }
+
+ pub fn settle(&self, ref_id: &str, status: &'static str) {
+ let step = self.with_log(|log| log.settle(ref_id, status));
+ self.send(step);
+ }
+
+ /// Ends the turn's open steps and returns what to save on the reply as `meta.activity`
+ /// (`None` when nothing happened).
+ pub fn finish(&self) -> Option<Value> {
+ let (steps, saved) = self.with_log(|log| {
+ let steps = log.finish();
+ (steps, (!log.is_empty()).then(|| log.to_json()))
+ });
+ self.send(steps);
+ saved
+ }
+}
+
+/// An approval card for `turn_id` is waiting on the person.
+pub fn approval_waiting(turn_id: &str, ticket: &str, tool_name: &str) {
+ if let Some(turn) = TurnActivity::find(turn_id) {
+ let (title, _) = crate::drivers::activity::summarize(tool_name, &Value::Null);
+ turn.wait("approval", ticket, &format!("Waiting for your approval: {title}"), Some(tool_name));
+ }
+}
+
+/// An approval card for `turn_id` was answered ("ok" allowed, "declined") or stopped waiting.
+pub fn approval_settled(turn_id: &str, ticket: &str, status: &'static str) {
+ if let Some(turn) = TurnActivity::find(turn_id) {
+ turn.settle(ticket, status);
+ }
+}
+
+/// Adds `meta.activity` to a reply's meta.
+pub fn with_activity(meta: Option<Value>, activity: Option<Value>) -> Option<Value> {
+ let Some(activity) = activity else { return meta };
+ let mut meta = meta.unwrap_or_else(|| serde_json::json!({}));
+ if meta.is_object() {
+ meta["activity"] = activity;
+ }
+ Some(meta)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn steps_go_out_scoped_and_approvals_find_their_turn() {
+ let (tx, mut rx) = broadcast::channel(16);
+ let tag = TurnTag { turn_id: "turn-activity-test".into(), kwant_id: "k".into(), context_id: "c".into(), thread_id: None };
+ let turn = TurnActivity::start(tx, tag);
+ turn.observe(&RuntimeEvent::ToolCallPending { id: "1".into(), name: "Bash".into(), args: json!({"command": "ls"}) });
+ approval_waiting("turn-activity-test", "ap", "Bash");
+ approval_settled("turn-activity-test", "ap", "ok");
+ approval_waiting("another-turn", "ap2", "Bash");
+ let wire: Vec<Value> = std::iter::from_fn(|| rx.try_recv().ok()).map(|e| e.to_wire()).collect();
+ assert_eq!(wire.len(), 3);
+ assert_eq!(wire[0]["type"], "activity");
+ assert_eq!(wire[0]["turn_id"], "turn-activity-test");
+ assert_eq!(wire[0]["data"]["step"]["title"], "Running `ls`");
+ assert_eq!(wire[1]["data"]["step"]["status"], "waiting");
+ assert_eq!(wire[2]["data"]["step"]["status"], "ok");
+ let saved = turn.finish().unwrap();
+ assert_eq!(saved["steps"][0]["status"], "stopped");
+ drop(turn);
+ assert!(TurnActivity::find("turn-activity-test").is_none());
+ assert_eq!(with_activity(None, Some(json!({"steps": []}))).unwrap()["activity"]["steps"], json!([]));
+ }
+}
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 38bad907..b2951866 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -150,7 +150,8 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
}
}
"take_control" => {
- if lease.is_none() {
+ // A pending human step already holds the browser for the person
+ if lease.is_none() && !ctrl.is_held_for_person() {
match ctrl.take_control().await {
Ok(guard) => lease = Some(guard),
Err(error) => { send(&mut socket, json!({"type":"error","error":error.to_string()})).await?; continue; }
@@ -163,7 +164,7 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
send(&mut socket, json!({"type":"control","active":false})).await?;
}
_ => {
- let result = if lease.is_none() { Err(BrowserError::HumanControl) } else {
+ let result = if lease.is_none() && !ctrl.is_held_for_person() { Err(BrowserError::HumanControl) } else {
match serde_json::from_value::<BrowserInput>(value.clone()) {
Ok(input) => ctrl.dispatch_input(input).await,
Err(_) => Err(BrowserError::Protocol("Invalid browser input".into())),
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 743debaf..58e092c4 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -34,7 +34,7 @@ const AGENT_SEARCH_LIMIT: i64 = 20;
/// Longest notification body.
pub const NOTIFY_BODY_CHARS: usize = 200;
const WEBHOOK_TIMEOUT: Duration = Duration::from_secs(5);
-pub const NOTIFY_KINDS: [&str; 8] = [
+pub const NOTIFY_KINDS: [&str; 9] = [
"turn_finished",
"approval_needed",
"routine_failed",
@@ -43,6 +43,7 @@ pub const NOTIFY_KINDS: [&str; 8] = [
"skill_proposed",
"question_asked",
"loose_ends",
+ "human_step",
];
const MASK: &str = "••••••••";
@@ -289,6 +290,9 @@ fn tool_list(scope: &SelfScope) -> Value {
list.extend(super::attachments::tools());
if scope.cancel.is_some() {
list.extend(super::questions::tools());
+ if scope.sandbox_target.is_some() {
+ list.extend(super::human_steps::tools());
+ }
}
}
}
@@ -336,7 +340,32 @@ pub const BROWSER_ACT: &str = "browser_act";
/// Runs one `browser_*` tool on the turn's own sandbox through the same handlers as the HTTP
/// browser API, so control (409), CAPTCHA notices and panel updates behave the same.
-async fn call_browser_tool(state: &AppState, target: &str, name: &str, args: &Value) -> (String, bool) {
+async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, name: &str, args: &Value) -> (String, bool) {
+ if super::human_steps::browser_is_held(state, target).await {
+ return (
+ "The browser is waiting on the person (a sign-in or CAPTCHA step). Stop browser actions until they finish it.".into(),
+ true,
+ );
+ }
+ let (text, is_error) = run_browser_tool(state, target, name, args).await;
+ // A CAPTCHA wall: ask the person to solve it, then show the agent the page they left
+ if !is_error {
+ if let Ok(page) = serde_json::from_str::<Value>(&text) {
+ if page["blocked"] == json!(true) {
+ if let Some(note) = super::human_steps::raise_for_bot_wall(state, scope, &page).await {
+ if super::human_steps::browser_is_held(state, target).await {
+ return (note, false);
+ }
+ let (after, _) = run_browser_tool(state, target, BROWSER_PAGE, &Value::Null).await;
+ return (format!("{note}\n\nThe page now:\n{after}"), false);
+ }
+ }
+ }
+ }
+ (text, is_error)
+}
+
+async fn run_browser_tool(state: &AppState, target: &str, name: &str, args: &Value) -> (String, bool) {
use super::routes::{act_sandbox, get_sandbox_page, navigate_sandbox, InteractPayload, NavigatePayload};
let state = State(state.clone());
let target = Path(target.to_string());
@@ -641,12 +670,13 @@ async fn call_tool(
}
}
BROWSER_OPEN | BROWSER_PAGE | BROWSER_ACT => match &scope.sandbox_target {
- Some(target) => call_browser_tool(state, target, name, args).await,
+ Some(target) => call_browser_tool(state, scope, target, name, args).await,
None => (format!("Unknown tool {name}."), true),
},
"skill_propose" => super::skills::tool_propose(state, scope, args).await,
"skill_get" => super::skills::tool_get(state, scope, args).await,
"ask_user" => super::questions::tool_ask(state, scope, args).await,
+ super::human_steps::TOOL => super::human_steps::tool_request(state, scope, args).await,
"mcp_search" => super::mcp_suggest::tool_search(state, scope, args).await,
"mcp_suggest" => super::mcp_suggest::tool_suggest(state, scope, args).await,
n if super::bot_actions::handles(n) => super::bot_actions::call(state, scope, n, args).await,
diff --git a/src/server/human_steps.rs b/src/server/human_steps.rs
new file mode 100644
index 00000000..064c6aaa
--- /dev/null
+++ b/src/server/human_steps.rs
@@ -0,0 +1,510 @@
+//! Steps only the person can do in the bot browser: sign in, solve a CAPTCHA, or something else.
+//! An agent calls `request_human_step` (or kwnt raises one itself when a browser tool lands on a
+//! CAPTCHA): the step is saved as a card in its chat, the UI gets `human_step_updated` +
+//! `message_added` and a `human_step` notification, the browser is held for the person, and the
+//! turn waits until they press Done or Decline (`POST /api/human-steps/:id/done|decline`). 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 the outcome. Stopping the turn cancels the step.
+
+use super::continuity::{notify, Notification, SelfScope};
+use super::routes::{scope_for, try_kwant_turn, TurnOpts};
+use super::AppState;
+use crate::db::human_steps::{clean_request, HumanStep, HumanStepError, HumanStepPlace, HUMAN_STEP_STATUSES};
+use crate::db::models::{MessageExtra, NewMessage};
+use crate::drivers::events::RuntimeEvent;
+use axum::{
+ extract::{Path, Query, State},
+ http::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;
+
+pub const TOOL: &str = "request_human_step";
+
+/// What a waiting step is woken with.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum Outcome {
+ Done,
+ Declined,
+}
+
+impl Outcome {
+ fn status(self) -> &'static str {
+ match self {
+ Outcome::Done => "done",
+ Outcome::Declined => "declined",
+ }
+ }
+}
+
+/// The turns waiting on a human step, by step id. Empty (no cost) when unused.
+pub struct HumanStepHub {
+ waiters: Mutex<HashMap<String, oneshot::Sender<Outcome>>>,
+ wait_ms: AtomicU64,
+}
+
+impl Default for HumanStepHub {
+ 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 HumanStepHub {
+ /// How long a turn waits before it is told 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<Outcome> {
+ let (tx, rx) = oneshot::channel();
+ self.waiters.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), tx);
+ rx
+ }
+
+ fn take(&self, id: &str) -> Option<oneshot::Sender<Outcome>> {
+ self.waiters.lock().unwrap_or_else(|e| e.into_inner()).remove(id)
+ }
+
+ /// Wakes the turn waiting on this step; `false` when no live turn waits.
+ pub fn wake(&self, id: &str, outcome: Outcome) -> bool {
+ self.take(id).is_some_and(|tx| tx.send(outcome).is_ok())
+ }
+
+ /// Whether a live turn is waiting on this step.
+ pub fn is_waiting(&self, id: &str) -> bool {
+ self.waiters.lock().unwrap_or_else(|e| e.into_inner()).contains_key(id)
+ }
+}
+
+/// Removes the waiter when the tool call ends any way (also when the CLI hangs up).
+struct WaiterGuard<'a> {
+ hub: &'a HumanStepHub,
+ id: String,
+}
+
+impl Drop for WaiterGuard<'_> {
+ fn drop(&mut self) {
+ self.hub.take(&self.id);
+ }
+}
+
+fn kind_label(kind: &str) -> &'static str {
+ match kind {
+ "sign_in" => "Sign in needed",
+ "captcha" => "Human check needed",
+ _ => "Your help is needed",
+ }
+}
+
+fn card_meta(s: &HumanStep) -> Value {
+ json!({
+ "kind": "human_step",
+ "human_step_id": s.id,
+ "step_kind": s.kind,
+ "reason": s.reason,
+ "url": s.url,
+ "sandbox_target": s.sandbox_target,
+ "source": s.source,
+ "status": s.status,
+ })
+}
+
+fn place_message(s: &HumanStep, role: &str, sender: &str, text: String) -> (NewMessage, MessageExtra) {
+ (
+ NewMessage {
+ channel_id: s.channel_id.clone(),
+ direct_kwant_id: s.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: s.thread_id.clone(), meta: None },
+ )
+}
+
+/// Sends `human_step_updated` and refreshes the step's card in the chat.
+async fn changed(state: &AppState, s: &HumanStep) {
+ if let Some(mid) = &s.message_id {
+ let _ = state.db.set_message_meta(mid, &card_meta(s)).await;
+ }
+ let _ = state.event_sender.send(RuntimeEvent::HumanStepUpdated { step: serde_json::to_value(s).unwrap_or(Value::Null) });
+}
+
+/// Holds the browser for the person, if it is running.
+async fn hold_browser(state: &AppState, target: Option<&str>) {
+ let Some(target) = target else { return };
+ let ctrl = state.browser_controllers.lock().await.get(target).cloned();
+ if let Some(ctrl) = ctrl {
+ if !ctrl.hold_for_person().await {
+ tracing::info!("human step: the browser is busy or already the person's; bot actions are refused until it closes");
+ }
+ }
+}
+
+/// Hands the browser back once no step is open in it any more.
+async fn release_browser(state: &AppState, target: Option<&str>) {
+ let Some(target) = target else { return };
+ if state.db.human_step_open_in(target).await.unwrap_or(false) {
+ return;
+ }
+ if let Some(ctrl) = state.browser_controllers.lock().await.get(target) {
+ ctrl.release_person_hold();
+ }
+}
+
+/// Closes an open step, hands the browser back and announces it; `None` if it wasn't open.
+async fn close(state: &AppState, id: &str, status: &'static str) -> Option<HumanStep> {
+ if !state.db.close_human_step(id, status).await.ok()? {
+ return None;
+ }
+ let s = state.db.get_human_step(id).await.ok().flatten()?;
+ release_browser(state, s.sandbox_target.as_deref()).await;
+ if let Some(turn) = s.turn_id.as_deref().and_then(super::activity::TurnActivity::find) {
+ turn.settle(&s.id, if status == "cancelled" { "stopped" } else { status });
+ }
+ changed(state, &s).await;
+ Some(s)
+}
+
+/// Whether a human step holds this bot browser: bot actions wait until it closes.
+pub async fn browser_is_held(state: &AppState, target: &str) -> bool {
+ state.db.human_step_open_in(target).await.unwrap_or(false)
+}
+
+// Agent tool
+
+pub const DESCRIPTION: &str = "Ask the person to do one step in the bot browser that only they can do: sign in \
+ (kind sign_in), solve a CAPTCHA or human check (kind captcha), or something else that needs them (kind other, \
+ e.g. approve a 2FA prompt). Never ask for passwords or codes in chat; use this instead. The browser is handed to \
+ them and your turn waits (a few minutes at most) until they press Done or Decline; the tool returns which. \
+ After Done, look at the page again before you continue.";
+
+pub fn tools() -> Vec<Value> {
+ vec![json!({
+ "name": TOOL,
+ "description": DESCRIPTION,
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "reason": {"type": "string", "description": "What to do and why, in one sentence (max 300 characters)"},
+ "kind": {"type": "string", "enum": ["sign_in", "captcha", "other"]},
+ "url": {"type": "string", "description": "The page it happens on (optional)"},
+ },
+ "required": ["reason", "kind"],
+ },
+ })]
+}
+
+/// `request_human_step{reason, kind, url}` from the agent.
+pub async fn tool_request(state: &AppState, scope: &SelfScope, args: &Value) -> (String, bool) {
+ let (kind, reason, url) = match clean_request(
+ args["kind"].as_str().unwrap_or(""),
+ args["reason"].as_str().unwrap_or(""),
+ args["url"].as_str(),
+ ) {
+ Ok(v) => v,
+ Err(e) => return (e.to_string(), true),
+ };
+ match raise(state, scope, &kind, &reason, url.as_deref(), "bot").await {
+ Ok(outcome) => (outcome_text(outcome), false),
+ Err(e) => (e, true),
+ }
+}
+
+/// What the agent is told about the outcome.
+fn outcome_text(outcome: Option<Outcome>) -> String {
+ match outcome {
+ Some(Outcome::Done) => "The person says the step is done and handed the browser back. Look at the page \
+ again (browser_page) before you continue."
+ .into(),
+ Some(Outcome::Declined) => "The person declined the step. Don't ask again: carry on without it if you can, or \
+ end your turn and say plainly what is blocked."
+ .into(),
+ None => "The person hasn't done the step yet. Don't ask again: end your turn now with a short note on what \
+ you're waiting for. When they finish, you'll get a new turn."
+ .into(),
+ }
+}
+
+/// Opens a step for the turn (or finds the one it already has open), tells the person, holds
+/// the browser and waits. `Ok(None)` when the wait ran out; `Err` with what to tell the agent.
+pub async fn raise(
+ state: &AppState,
+ scope: &SelfScope,
+ kind: &str,
+ reason: &str,
+ url: Option<&str>,
+ source: &str,
+) -> Result<Option<Outcome>, String> {
+ let (Some(origin), Some(cancel)) = (&scope.origin, &scope.cancel) else {
+ return Err("You can only ask the person for a step from a chat.".into());
+ };
+ let place = HumanStepPlace {
+ 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(),
+ sandbox_target: scope.sandbox_target.clone(),
+ };
+ // Like ask_user, the step, its card and the waiter appear together
+ let hub = &state.human_steps;
+ let mut waiter = None;
+ let created = state
+ .db
+ .create_human_step_with_card(&place, kind, reason, url, source, |s| {
+ waiter = Some((s.id.clone(), hub.register(&s.id)));
+ let mut text = format!("{}: {}", kind_label(&s.kind), s.reason);
+ if let Some(u) = &s.url {
+ text.push_str(&format!("\n{u}"));
+ }
+ text.push_str("\n\nDo it in the browser panel, then press Done.");
+ let (msg, extra) = place_message(s, "kwant", &scope.kwant_id, text);
+ Some((msg, MessageExtra { meta: Some(card_meta(s)), ..extra }))
+ })
+ .await;
+ let (step, is_new, card) = match created {
+ Ok(v) => v,
+ Err(e) => {
+ if let Some((id, _)) = waiter {
+ hub.take(&id);
+ }
+ return Err(match e {
+ HumanStepError::Db => "Could not save the step.".into(),
+ e => e.to_string(),
+ });
+ }
+ };
+ // The turn asked again for a step it already has open: wait on that one
+ let mut rx = match waiter {
+ Some((_, rx)) => rx,
+ None => hub.register(&step.id),
+ };
+ let _guard = WaiterGuard { hub, id: step.id.clone() };
+ if is_new {
+ hold_browser(state, step.sandbox_target.as_deref()).await;
+ if let Some(card) = card {
+ if let Some(t) = &step.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, &step).await;
+ if let Some(turn) = step.turn_id.as_deref().and_then(super::activity::TurnActivity::find) {
+ let title = format!("Waiting for you: {}", step.reason);
+ turn.wait("human_step", &step.id, &title, Some(TOOL));
+ }
+ notify(
+ state,
+ Notification {
+ kind: "human_step",
+ kwant_id: scope.kwant_id.clone(),
+ kwant_name: scope.kwant_name.clone(),
+ channel_id: origin.channel_id.clone(),
+ title: format!("{} needs you in the browser", scope.kwant_name),
+ body: format!("{}. Open the chat, do it in the browser panel, then press Done.", kind_label(&step.kind)),
+ },
+ )
+ .await;
+ tracing::info!(human_step_id = %step.id, kwant_id = %scope.kwant_id, source, "agent asked the person for a browser step");
+ }
+
+ tokio::select! {
+ r = &mut rx => Ok(r.ok()),
+ _ = cancel.cancelled() => {
+ close(state, &step.id, "cancelled").await;
+ Err("The user stopped this turn. End it now.".into())
+ }
+ _ = tokio::time::sleep(hub.wait()) => {
+ hub.take(&step.id);
+ // An answer that arrived just as the wait ran out still counts
+ Ok(rx.try_recv().ok())
+ }
+ }
+}
+
+/// Raised by kwnt when a browser tool lands on a CAPTCHA: the turn waits for the person like
+/// for `request_human_step`, then gets the page again. `None` when there's no chat to ask in.
+pub async fn raise_for_bot_wall(state: &AppState, scope: &SelfScope, page: &Value) -> Option<String> {
+ scope.origin.as_ref()?;
+ scope.cancel.as_ref()?;
+ let url = page["url"].as_str().and_then(crate::db::human_steps::clean_url);
+ let host = url.as_deref().and_then(|u| url::Url::parse(u).ok()).and_then(|u| u.host_str().map(str::to_string));
+ let reason = match host {
+ Some(h) => format!("{h} is showing a CAPTCHA / human check to the bot browser. Please solve it."),
+ None => "The page is showing a CAPTCHA / human check to the bot browser. Please solve it.".into(),
+ };
+ Some(match raise(state, scope, "captcha", &reason, url.as_deref(), "auto").await {
+ Ok(outcome) => format!("A CAPTCHA blocked the page, so the person was asked to solve it. {}", outcome_text(outcome)),
+ Err(e) => e,
+ })
+}
+
+// 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/human-steps?status=&context_id=&space=`: the space's steps, newest first.
+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 !HUMAN_STEP_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_human_steps(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<HumanStep, StatusCode> {
+ match state.db.get_human_step(id).await {
+ Ok(Some(s)) => Ok(s),
+ 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(s) => Json(json!({"step": s, "waiting": state.human_steps.is_waiting(&s.id)})).into_response(),
+ Err(r) => r.into_response(),
+ }
+}
+
+/// `POST /api/human-steps/:id/done`: the person did the step.
+pub async fn done(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ finish(&state, &id, Outcome::Done).await
+}
+
+/// `POST /api/human-steps/:id/decline`: the person won't do it.
+pub async fn decline(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ finish(&state, &id, Outcome::Declined).await
+}
+
+/// Closes the step, hands the browser back and tells the turn: the waiting turn at once, or a
+/// new turn in the same chat if it already ended.
+async fn finish(state: &AppState, id: &str, outcome: Outcome) -> Response {
+ let s = match load(state, id).await {
+ Ok(s) => s,
+ Err(r) => return r.into_response(),
+ };
+ if s.status != "open" {
+ return error(StatusCode::CONFLICT, format!("the step is already {}", s.status));
+ }
+ let Some(s) = close(state, id, outcome.status()).await else {
+ return error(StatusCode::CONFLICT, "the step was just closed");
+ };
+ let text = match outcome {
+ Outcome::Done => "Done",
+ Outcome::Declined => "Declined",
+ };
+ let (msg, extra) = place_message(&s, "user", "user", text.into());
+ let meta = json!({"kind": "human_step_reply", "human_step_id": s.id, "status": s.status});
+ if let Ok(saved) = state.db.insert_message_with(&msg, &MessageExtra { meta: Some(meta), ..extra }).await {
+ if let Some(t) = &s.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) });
+ }
+ let live = state.human_steps.wake(&s.id, outcome);
+ if !live {
+ resume(state, &s, outcome).await;
+ }
+ Json(json!({"step": s, "resumed": if live { "turn" } else { "new_turn" }})).into_response()
+}
+
+/// A late answer: a new turn in the step's chat, queued like any other turn.
+async fn resume(state: &AppState, s: &HumanStep, outcome: Outcome) {
+ let Ok(Some(kwant)) = state.db.get_kwant(&s.kwant_id).await else {
+ return;
+ };
+ let depth = match &s.thread_id {
+ Some(t) => state.db.delegation_for_thread(t).await.ok().flatten().map(|d| d.depth).unwrap_or(0),
+ None => 0,
+ };
+ let job = state.turns.start_job([s.context_id(), s.id.clone()]);
+ let Ok(scope) = scope_for(state, &kwant, s.channel_id.clone(), s.thread_id.clone(), &job, depth).await else {
+ return;
+ };
+ let prompt = match outcome {
+ Outcome::Done => format!(
+ "[The person did the browser step you asked for earlier]\nStep: {}\n\nLook at the browser page again and continue the task.",
+ s.reason
+ ),
+ Outcome::Declined => format!(
+ "[The person declined the browser step you asked for earlier]\nStep: {}\n\nDon't ask again. Carry on without it if you can, or say plainly what is blocked.",
+ s.reason
+ ),
+ };
+ tokio::spawn(async move {
+ let _job = job;
+ let _ = try_kwant_turn(&scope, &kwant, prompt, TurnOpts::default()).await;
+ });
+}
+
+/// After a turn was stopped: its open steps are cancelled and the browser handed back.
+pub async fn cancel_for_turn(state: &AppState, turn_id: &str) {
+ for s in state.db.open_human_steps_for_turn(turn_id).await.unwrap_or_default() {
+ drop(state.human_steps.take(&s.id));
+ close(state, &s.id, "cancelled").await;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn the_hub_wakes_the_waiting_turn_once() {
+ let hub = HumanStepHub::default();
+ let rx = hub.register("s1");
+ assert!(hub.is_waiting("s1"));
+ assert!(hub.wake("s1", Outcome::Declined));
+ assert_eq!(rx.await.unwrap(), Outcome::Declined);
+ assert!(!hub.is_waiting("s1"));
+ assert!(!hub.wake("s1", Outcome::Done), "nobody waits any more: a new turn starts instead");
+ let rx = hub.register("s2");
+ drop(rx);
+ assert!(!hub.wake("s2", Outcome::Done), "the tool call already ended");
+ }
+
+ #[test]
+ fn the_agent_hears_each_outcome_plainly() {
+ assert!(outcome_text(Some(Outcome::Done)).contains("Look at the page"));
+ assert!(outcome_text(Some(Outcome::Declined)).contains("declined"));
+ assert!(outcome_text(None).contains("end your turn"));
+ }
+}
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 0cc9c281..bfb536a3 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -263,9 +263,17 @@ impl ToolApprover for BrokerApprover {
tool_name: req.tool_name.clone(),
details,
});
+ super::activity::approval_waiting(&req.turn_id, &ticket, &req.tool_name);
let decision = tokio::time::timeout(self.timeout, rx).await;
guard.id = None;
+ let settled = match &decision {
+ Ok(Ok(ApprovalDecision::AllowOnce | ApprovalDecision::AlwaysAllowSession)) => "ok",
+ Ok(_) => "declined",
+ // the card stays up, but this turn stops waiting for it
+ Err(_) => "stopped",
+ };
+ super::activity::approval_settled(&req.turn_id, &ticket, settled);
match decision {
Ok(Ok(ApprovalDecision::AllowOnce)) => ApprovalOutcome::Allowed,
Ok(Ok(ApprovalDecision::AlwaysAllowSession)) => {
diff --git a/src/server/mod.rs b/src/server/mod.rs
index dc40e940..5b51fa62 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -18,6 +18,8 @@ pub mod delegation;
pub mod parked;
pub mod attachments;
pub mod questions;
+pub mod activity;
+pub mod human_steps;
pub mod skills;
pub mod spaces;
pub mod away;
@@ -78,6 +80,8 @@ pub struct AppState {
pub scheduler_wake: Arc<tokio::sync::Notify>,
/// `ask_user` calls waiting for the user's answer.
pub questions: Arc<questions::QuestionHub>,
+ /// `request_human_step` calls waiting for the person to sign in or solve a CAPTCHA.
+ pub human_steps: Arc<human_steps::HumanStepHub>,
/// "Sign in with Claude" for the Claude engine.
pub claude_login: Arc<engine_login::ClaudeLogin>,
/// The MCP Registry agents search and suggest servers from (`KWNT_MCP_REGISTRY_URL`).
@@ -127,6 +131,7 @@ impl AppState {
running_routines: Default::default(),
scheduler_wake: Default::default(),
questions: Default::default(),
+ human_steps: Default::default(),
claude_login: Default::default(),
mcp_registry: Arc::new(crate::mcp::registry::McpRegistry::from_env()),
credentials: Arc::new(crate::sandbox::vault::PasswordVault::open(&config_data_dir)),
@@ -303,6 +308,10 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/questions/:id", get(questions::get))
.route("/api/questions/:id/answer", post(questions::answer))
.route("/api/questions/:id/cancel", post(questions::cancel))
+ .route("/api/human-steps", get(human_steps::list))
+ .route("/api/human-steps/:id", get(human_steps::get))
+ .route("/api/human-steps/:id/done", post(human_steps::done))
+ .route("/api/human-steps/:id/decline", post(human_steps::decline))
.route("/api/skills", get(skills::list).post(skills::create))
.route("/api/skills/:id", get(skills::get).patch(skills::update).delete(skills::remove))
.route("/api/skills/:id/diff", get(skills::diff))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index a427e77b..6d236fb3 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1356,6 +1356,7 @@ pub(super) async fn try_kwant_turn(
let reply = run_kwant_turn_inner(scope, target_kwant, prompt, opts, &tag).await;
if scope.cancel_token.is_cancelled() {
super::questions::cancel_for_turn(&scope.state, &tag.turn_id).await;
+ super::human_steps::cancel_for_turn(&scope.state, &tag.turn_id).await;
}
ended.outcome = match (&reply, scope.cancel_token.is_cancelled()) {
(Ok(_), _) => "completed",
@@ -1458,6 +1459,8 @@ impl Drop for TurnEndedGuard {
struct TurnEvents {
sender: tokio::sync::broadcast::Sender<RuntimeEvent>,
tag: crate::drivers::events::TurnTag,
+ /// The turn's live steps, fed by the driver's events.
+ activity: std::sync::Arc<super::activity::TurnActivity>,
}
impl TurnEvents {
@@ -1524,7 +1527,11 @@ async fn run_kwant_turn_inner(
tag: &crate::drivers::events::TurnTag,
) -> Result<String, String> {
let state = &scope.state;
- let event_broadcast = TurnEvents { sender: state.event_sender.clone(), tag: tag.clone() };
+ let event_broadcast = TurnEvents {
+ sender: state.event_sender.clone(),
+ tag: tag.clone(),
+ activity: super::activity::TurnActivity::start(state.event_sender.clone(), tag.clone()),
+ };
let park_prompt = prompt.clone();
let db = state.db.clone();
let router = state.router.clone();
@@ -1756,6 +1763,9 @@ async fn run_kwant_turn_inner(
)
.await;
let mcp_ctx = mcp_turn.as_ref().map(|(ctx, _)| ctx.clone());
+ if let Some(ctx) = &mcp_ctx {
+ event_broadcast.activity.add_secrets(ctx.secret_values());
+ }
let with_tools = mcp_ctx
.as_ref()
.is_some_and(|c| c.servers.iter().any(|s| s.name == crate::mcp::SELF_SERVER_NAME));
@@ -1886,6 +1896,11 @@ async fn run_kwant_turn_inner(
.unwrap_or_default(),
)));
}
+ if ran_on.is_none() {
+ if let Some(note) = runs_on.and_then(|e| crate::drivers::activity::thinking_note(e.as_str())) {
+ event_broadcast.activity.note(note);
+ }
+ }
ran_on = runs_on.map(|e| RanOn {
engine: e,
profile_id: profile.as_ref().map(|p| p.id.clone()),
@@ -1943,6 +1958,7 @@ async fn run_kwant_turn_inner(
_ => false,
};
side_effects |= visible;
+ event_broadcast.activity.observe(&event);
event_broadcast.send(event);
}
None => break,
@@ -2070,6 +2086,8 @@ async fn run_kwant_turn_inner(
super::mcp_runtime::finish_turn(state, token).await;
}
let mcp_records = mcp_ctx.map(|c| c.take_records()).filter(|r| !r.is_empty());
+ // Ends what still runs; kept on the reply so the steps show after a reload
+ let activity = event_broadcast.activity.finish();
let with_notices = |reasoning: Option<String>| -> Option<String> {
if notices.is_empty() {
@@ -2088,7 +2106,7 @@ async fn run_kwant_turn_inner(
reasoning_content: with_notices(opts.label.clone()),
..scope.message("kwant", &target_kwant.name, text.clone())
};
- scope.save(&msg, gave_up_meta).await;
+ scope.save(&msg, super::activity::with_activity(gave_up_meta, activity)).await;
return Err(text);
} else if let Some(Ok(Ok(output))) = driver_result {
// This chat got through: a turn parked behind a usage limit would only repeat it
@@ -2152,6 +2170,7 @@ async fn run_kwant_turn_inner(
if let Some(routing) = &opts.routing {
meta.get_or_insert_with(|| serde_json::json!({}))["routing"] = routing.clone();
}
+ let meta = super::activity::with_activity(meta, activity);
scope.save(&asst_msg, meta).await;
}
return Ok(output.text);
diff --git a/src/server/sse.rs b/src/server/sse.rs
index c3015ae5..3a577d4f 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -52,7 +52,11 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {
match event {
E::Scoped { tag, .. } => contexts([&Some(tag.context_id.clone()), &Some(tag.kwant_id.clone())]),
// Only ever sent inside a turn (`Scoped`); bare, they belong nowhere
- E::TextDelta(_) | E::ThinkingDelta(_) | E::ToolCallPending { .. } | E::ToolCallCompleted { .. } => Vec::new(),
+ E::TextDelta(_)
+ | E::ThinkingDelta(_)
+ | E::ToolCallPending { .. }
+ | E::ToolCallCompleted { .. }
+ | E::Activity { .. } => Vec::new(),
// Never broadcast: the turn's stall watchdog takes it
E::Progress => Vec::new(),
E::ApprovalRequired { id, .. } | E::ApprovalWithdrawn { id } => vec![Owner::Approval(id.clone())],
@@ -77,8 +81,8 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {
out.extend(fields(skill, &["id"], Owner::Skill));
out
}
- E::QuestionUpdated { question } => fields(
- question,
+ E::QuestionUpdated { question: v } | E::HumanStepUpdated { step: v } => fields(
+ v,
&["kwant_id", "channel_id", "direct_kwant_id", "thread_id"],
Owner::Context,
),
@@ -215,6 +219,8 @@ mod tests {
E::MessageAdded { message: json!({"id": "m", "channel_id": "c"}) },
E::SkillUpdated { skill: json!({"id": "s", "kwant_id": null, "deleted": true}) },
E::QuestionUpdated { question: json!({"id": "q", "kwant_id": "k"}) },
+ E::Activity { step: json!({"id": "s1"}) },
+ E::HumanStepUpdated { step: json!({"id": "h", "kwant_id": "k"}) },
E::McpSuggestionUpdated { suggestion: json!({"id": "g", "space_id": "spc_default", "kwant_id": "k"}) },
E::BotActionUpdated { action: json!({"id": "b", "space_id": "spc_default", "kwant_id": "k"}) },
E::HireUpdated { hire: json!({"id": "h", "space_id": "spc_default", "kwant_id": "k"}) },
@@ -293,6 +299,8 @@ mod tests {
| E::MessageAdded { .. }
| E::SkillUpdated { .. }
| E::QuestionUpdated { .. }
+ | E::Activity { .. }
+ | E::HumanStepUpdated { .. }
| E::McpSuggestionUpdated { .. }
| E::BotActionUpdated { .. }
| E::HireUpdated { .. }
@@ -322,7 +330,7 @@ mod tests {
#[test]
fn every_event_is_placed_in_a_space_or_is_global() {
// Only ever sent inside a turn; bare, they are dropped from scoped streams on purpose
- let turn_only = ["TextDelta", "ThinkingDelta", "ToolCallPending", "ToolCallCompleted", "Progress"];
+ let turn_only = ["TextDelta", "ThinkingDelta", "ToolCallPending", "ToolCallCompleted", "Progress", "activity"];
for e in samples() {
let t = wire_type(&e);
if turn_only.contains(&t.as_str()) && !matches!(e, RuntimeEvent::Scoped { .. }) {
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index 4dd6d030..f66095ac 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -1312,7 +1312,7 @@ async fn webhook_setting_is_https_only_and_masked() {
assert_eq!(s["notify_webhook_url"], "");
assert_eq!(
s["notify_on"],
- json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends"])
+ json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step"])
);
let (status, _) = req(
diff --git a/tests/human_step_test.rs b/tests/human_step_test.rs
new file mode 100644
index 00000000..81ca2b8d
--- /dev/null
+++ b/tests/human_step_test.rs
@@ -0,0 +1,171 @@
+//! Human steps: `request_human_step` pauses the turn with a card and a `human_step`
+//! notification, Done or Decline resumes it with that outcome, Stop cancels it, a late answer
+//! starts a new turn, and the bot's browser tools are refused while a step is open.
+
+mod common;
+
+use axum::http::StatusCode;
+use common::*;
+use kwnt::RuntimeEvent;
+use serde_json::{json, Value};
+use std::time::Duration;
+
+fn step_marker(kind: &str, reason: &str) -> String {
+ call_tool_marker("request_human_step", json!({"kind": kind, "reason": reason, "url": "https://me:[email protected]/login?token=abc"}))
+}
+
+/// Waits until `ctx` has an open step, and returns it.
+async fn open_step(env: &Env, ctx: &str) -> Value {
+ for _ in 0..300 {
+ let (s, list) = call(&env.app, "GET", &format!("/api/human-steps?status=open&context_id={ctx}"), None).await;
+ assert_eq!(s, StatusCode::OK);
+ if let Some(step) = list.as_array().and_then(|l| l.first()) {
+ return step.clone();
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ panic!("no open human step in {ctx}");
+}
+
+async fn step(env: &Env, id: &str) -> Value {
+ let (s, v) = call(&env.app, "GET", &format!("/api/human-steps/{id}"), None).await;
+ assert_eq!(s, StatusCode::OK);
+ v
+}
+
+#[tokio::test]
+async fn done_resumes_the_waiting_turn() {
+ let env = setup().await;
+ let mut rx = env.state.event_sender.subscribe();
+ send_direct(&env, &env.a, &format!("Open the PR {} REPLYTAG:h1", step_marker("sign_in", "Log in to Example")), json!({})).await;
+ let s = open_step(&env, &env.a).await;
+ let id = s["id"].as_str().unwrap().to_string();
+ assert_eq!(s["kind"], "sign_in");
+ assert_eq!(s["source"], "bot");
+ assert_eq!(s["url"], "https://example.com/login", "no password or query kept");
+ assert!(step(&env, &id).await["waiting"].as_bool().unwrap());
+
+ let card = messages(&env, &env.a).await.into_iter().find(|m| m.text.starts_with("Sign in needed")).unwrap();
+ let meta: Value = serde_json::from_str(card.meta.as_deref().unwrap()).unwrap();
+ assert_eq!((meta["kind"].as_str(), meta["human_step_id"].as_str(), meta["status"].as_str()), (Some("human_step"), Some(id.as_str()), Some("open")));
+ assert!(!card.text.contains("pw") && !card.text.contains("token"));
+
+ // The bot's browser is the person's while the step is open
+ if let Some(target) = s["sandbox_target"].as_str() {
+ assert!(kwnt::server::human_steps::browser_is_held(&env.state, target).await);
+ }
+
+ let (code, v) = call(&env.app, "POST", &format!("/api/human-steps/{id}/done"), None).await;
+ assert_eq!(code, StatusCode::OK, "{v}");
+ assert_eq!(v["resumed"], "turn");
+ let reply = wait_reply(&env, &env.a, "answer h1").await;
+ assert!(reply.text.contains("TOOL[The person says the step is done"), "{}", reply.text);
+ assert_eq!(step(&env, &id).await["step"]["status"], "done");
+ if let Some(target) = s["sandbox_target"].as_str() {
+ assert!(!kwnt::server::human_steps::browser_is_held(&env.state, target).await, "handed back");
+ }
+ let card = messages(&env, &env.a).await.into_iter().find(|m| m.id == card.id).unwrap();
+ assert!(card.meta.as_deref().unwrap().contains("\"status\":\"done\""));
+
+ let (mut opened, mut closed, mut notified, mut waiting, mut settled) = (false, false, false, false, false);
+ while let Ok(e) = rx.try_recv() {
+ match e.unscoped() {
+ RuntimeEvent::HumanStepUpdated { step } if step["id"] == id.as_str() => match step["status"].as_str() {
+ Some("open") => opened = true,
+ Some("done") => closed = true,
+ _ => {}
+ },
+ RuntimeEvent::Notify { kind, body, .. } if kind == "human_step" => {
+ assert!(!body.contains("Example") && !body.contains("example.com"), "no reason or URL in the notification");
+ notified = true;
+ }
+ RuntimeEvent::Activity { step } if step["ref_id"] == id.as_str() => {
+ assert_eq!(step["kind"], "human_step");
+ match step["status"].as_str() {
+ Some("waiting") => waiting = true,
+ Some("done") => settled = true,
+ _ => {}
+ }
+ }
+ _ => {}
+ }
+ }
+ assert!(opened && closed && notified, "opened {opened} closed {closed} notified {notified}");
+ assert!(waiting && settled, "activity waiting {waiting} settled {settled}");
+
+ let (code, _) = call(&env.app, "POST", &format!("/api/human-steps/{id}/decline"), None).await;
+ assert_eq!(code, StatusCode::CONFLICT, "closed once only");
+}
+
+#[tokio::test]
+async fn decline_tells_the_turn_to_carry_on_without_it() {
+ let env = setup().await;
+ send_direct(&env, &env.a, &format!("{} REPLYTAG:h2", step_marker("captcha", "Solve the check")), json!({})).await;
+ let s = open_step(&env, &env.a).await;
+ let (code, v) = call(&env.app, "POST", &format!("/api/human-steps/{}/decline", s["id"].as_str().unwrap()), None).await;
+ assert_eq!(code, StatusCode::OK, "{v}");
+ assert_eq!(v["step"]["status"], "declined");
+ let reply = wait_reply(&env, &env.a, "answer h2").await;
+ assert!(reply.text.contains("declined the step"), "{}", reply.text);
+ assert!(!reply.text.contains("TOOLERROR"));
+}
+
+#[tokio::test]
+async fn stop_cancels_the_step() {
+ let env = setup().await;
+ send_direct(&env, &env.a, &format!("{} REPLYTAG:h3", step_marker("other", "Approve the 2FA prompt")), json!({})).await;
+ let s = open_step(&env, &env.a).await;
+ let id = s["id"].as_str().unwrap();
+ let (code, v) = call(&env.app, "POST", "/api/chat/cancel", Some(json!({"kwant_id": env.a}))).await;
+ assert_eq!(code, StatusCode::OK, "{v}");
+ wait_for("step cancelled", || async { step(&env, id).await["step"]["status"] == "cancelled" }).await;
+ let (code, _) = call(&env.app, "POST", &format!("/api/human-steps/{id}/done"), None).await;
+ assert_eq!(code, StatusCode::CONFLICT);
+}
+
+#[tokio::test]
+async fn a_late_done_starts_a_new_turn() {
+ let env = setup().await;
+ env.state.human_steps.set_wait(Duration::from_millis(300));
+ send_direct(&env, &env.a, &format!("{} REPLYTAG:h4", step_marker("sign_in", "LATE_STEP log in")), json!({})).await;
+ let reply = wait_reply(&env, &env.a, "answer h4").await;
+ assert!(reply.text.contains("hasn't done the step yet"), "{}", reply.text);
+ let s = open_step(&env, &env.a).await;
+ let id = s["id"].as_str().unwrap();
+ assert_eq!(step(&env, id).await["waiting"], false);
+ let (code, v) = call(&env.app, "POST", &format!("/api/human-steps/{id}/done"), None).await;
+ assert_eq!(code, StatusCode::OK, "{v}");
+ assert_eq!(v["resumed"], "new_turn");
+ wait_for("the resumed turn", || async { !invocations_with("Step: LATE_STEP log in").is_empty() }).await;
+ assert_eq!(invocations_with("Step: LATE_STEP log in").len(), 1);
+}
+
+#[tokio::test]
+async fn input_and_routes_are_checked() {
+ let env = setup().await;
+ for (m, u) in [("GET", "/api/human-steps/nope"), ("POST", "/api/human-steps/nope/done"), ("POST", "/api/human-steps/nope/decline")] {
+ let (s, _) = call(&env.app, m, u, None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "{m} {u}");
+ }
+ let (s, _) = call(&env.app, "GET", "/api/human-steps?status=bogus", None).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+ for (tag, args) in [
+ ("v1", json!({"kind": "login", "reason": "x"})),
+ ("v2", json!({"kind": "sign_in", "reason": " "})),
+ ("v3", json!({"kind": "other", "reason": "x", "url": "file:///etc/passwd"})),
+ ] {
+ send_direct(&env, &env.b, &format!("{} REPLYTAG:{tag}", call_tool_marker("request_human_step", args)), json!({})).await;
+ let r = wait_reply(&env, &env.b, &format!("answer {tag}")).await;
+ assert!(r.text.contains("TOOLERROR"), "{}", r.text);
+ }
+ let (_, list) = call(&env.app, "GET", &format!("/api/human-steps?context_id={}", env.b), None).await;
+ assert!(list.as_array().unwrap().is_empty());
+ for (m, u) in [
+ ("GET", "/api/human-steps"),
+ ("GET", "/api/human-steps/x"),
+ ("POST", "/api/human-steps/x/done"),
+ ("POST", "/api/human-steps/x/decline"),
+ ] {
+ assert_eq!(call_remote(&env.app, m, u).await, StatusCode::UNAUTHORIZED, "{m} {u}");
+ }
+}