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.

Bots manage the app from chat: routines, bots, settings, spaces, channels

Lin (kwant bot)0d1824be3d2d
diff --git a/docs/bot-actions.md b/docs/bot-actions.md
new file mode 100644
index 00000000..86b76430
--- /dev/null
+++ b/docs/bot-actions.md
@@ -0,0 +1,117 @@
+# Bots changing the app (bot actions)
+
+Agents with their own tools (`kwnt_tools`, the self MCP server) can set up routines and manage the
+app when the person asks, in the same turn. Every tool wraps the HTTP handler the app uses, scoped
+to the turn's bot and its space. Code: `src/server/bot_actions.rs`, `src/db/bot_actions.rs`.
+
+## Tools
+
+| Tool | Arguments | Effect |
+|---|---|---|
+| `routine_list` | – | Routines in the bot's space |
+| `routine_create` | `name`, `instructions`, `schedule`, `bot?`, `channel?` | Applied, undo deletes it |
+| `routine_update` | `routine`, `name?`, `instructions?`, `schedule?`, `bot?`, `channel?` | Applied, undo restores |
+| `routine_pause` / `routine_resume` | `routine` | Applied, undo restores |
+| `routine_run_now` | `routine` | Logged with a card, no undo |
+| `routine_delete` | `routine` | Applied, undo recreates it (new id; the action is retargeted) |
+| `bot_list` | – | Bots, models, accounts, installed tool servers |
+| `bot_create` | `name`, `title`, `instructions`, `soul?`, `model?`, `profile_id?`, `avatar?` | Applied, undo deletes it if it has no history yet |
+| `bot_update` | `bot`, `name?`, `title?`, `instructions?`, `soul?`, `model?`, `profile_id?`, `avatar?`, `mcp_servers?` | Applied, undo restores fields, account and tool servers |
+| `bot_delete` | `bot`, `reason?` | **Pending** until the person confirms; only bots with no history |
+| `settings_get` | – | `timezone`, `max_turns_per_agent`, `max_turns_global`, `delegation_follow_up_minutes`, `notify_on` |
+| `settings_update` | `settings: {…}` (those keys only) | Applied, undo restores |
+| `space_get` / `space_list` | – | |
+| `space_create` | `name`, `icon?`, `color?` | Applied, undo archives it |
+| `space_update` | `name?`, `icon?`, `color?` (own space) | Applied, undo restores |
+| `space_archive` | `reason?` | **Pending** |
+| `channel_list` | – | |
+| `channel_create` | `name`, `description?`, `lead?`, `members?` | Applied, undo deletes it while it has no messages |
+| `channel_update` | `channel`, `instructions` | Applied, undo restores |
+| `profile_delete` | `profile_id`, `reason?` | **Pending** |
+
+- `routine`, `bot` and `channel` take an id or a name. `bot` defaults to the calling bot.
+- `channel` defaults to the chat the turn is in. `"direct"` means the bot's direct chat.
+- `schedule` can be one of:
+ - `{"type":"daily","time":"07:00","tz?"}`
+ - `{"type":"weekly","time":"09:30","weekdays":["mon"],"tz?"}`
+ - `{"type":"interval","every_minutes":60}`
+ - `{"type":"once","at":"<RFC 3339>"}`
+- Without `tz`, the `timezone` setting is used. If that isn't set either, the tool returns an error asking the bot to pass `tz` or ask the person.
+- Schedule and validation errors come back as tool errors (`isError: true`), and nothing changes.
+- A routine runs as its bot and delivers into its channel, or into that bot's direct chat. Created from a thread, it delivers to the thread's channel or direct chat, not into the thread.
+
+New setting: `GET/POST /api/settings` has `timezone` (IANA name; `""` means not set and clears it). Legacy names are canonicalised (Europe/Kiev → Europe/Kyiv).
+
+## Limits and scope
+
+- Each turn can make at most **10 changes**. Read-only tools don't count. Without a turn id, the limit is 10 changes per bot per 10 minutes.
+- Only the bot's own space is reachable. A target in another space gets: "That … is in another space … ask the person to switch to that space and do it there."
+- An archived space refuses changes.
+- Each change is logged in the `bot_actions` table with bot, turn, chat, before and after, and also written to `tracing::info!("bot changed the app")`.
+
+## Refused (the tool says where the person does it)
+
+| Category | Where the person goes |
+|---|---|
+| API keys, tokens, passwords, webhook URL (any `*key*`, `*token*`, `*secret*`, `*webhook*` setting) | Space settings → Accounts / App settings → Notifications |
+| Engines, sign-in and sign-out, Ollama URL, profiles | Space settings → Accounts / App settings |
+| How people sign in to kwnt (auth) | The host computer |
+| Approvals and questions | The card in the chat (there is no tool for these) |
+| Computer, sandbox or VM | App settings → Computer for browsing and commands |
+| `agent_tools` | App settings, person only |
+| Installing MCP servers, and MCP env or header values | `mcp_suggest` card; Space settings → Tools |
+
+`bot_update.mcp_servers` only assigns servers that are already installed in the space. Passing `env`, `headers`, `api_key`, `password` or `token` to `bot_create`/`bot_update` is refused.
+
+## The card
+
+Each action posts a message from the bot (`sender_role: "kwant"`, `sender_id: <bot name>`) into the chat of the turn: the channel, the direct chat or the thread. Example text: `Done: Created routine 'Morning motivation', daily 07:00 Europe/Berlin, delivering to #general.` A pending action reads `Needs your OK: …`.
+
+`message.meta`:
+
+```json
+{
+ "kind": "bot_action",
+ "action_id": "…",
+ "action": "routine_create",
+ "kwant_id": "…",
+ "target_kind": "routine",
+ "target_id": "…",
+ "summary": "created routine 'Morning motivation', daily 07:00 Europe/Berlin, delivering to #general",
+ "details": {
+ "routine_id": "…", "name": "Morning motivation", "kwant_id": "…", "bot_name": "Coach",
+ "schedule": {"type": "daily", "time": "07:00", "tz": "Europe/Berlin"},
+ "schedule_text": "daily 07:00 Europe/Berlin", "enabled": true,
+ "next_run_at": "…", "channel_id": "…", "delivers_to": "#general"
+ },
+ "status": "applied",
+ "can_undo": true,
+ "needs_confirmation": false,
+ "created_at": "…",
+ "resolved_at": null
+}
+```
+
+- `status` is one of `applied | undone | pending | confirmed | declined`.
+- `target_kind` is one of `routine | bot | settings | space | channel | profile`.
+- `details` depends on the target:
+ - routine: as above, plus `run_id` and `run_status` for `routine_run_now`;
+ - bot: `kwant_id, name, title, instructions, soul, avatar, model, profile_id, profile_failover, mcp_server_ids`;
+ - settings: only the changed keys;
+ - space: `space_id, name, icon, color, archived`;
+ - channel: `channel_id, name, instructions` or `lead_kwant_id, member_kwants`.
+- Pending actions also have `details.reason`.
+
+Suggested buttons:
+- **Undo** when `can_undo`.
+- **Confirm** and **Decline** when `needs_confirmation`.
+- For routines, **Edit** and **Pause** can open the routine in Space settings → Routines (`target_id`), or call `PUT /api/routines/:id` directly. Those edits are the person's own and are not bot actions.
+
+## Routes (person only)
+
+- `GET /api/bot-actions?space=&kwant_id=&status=`: the space's actions, newest first, at most 200. Each is a `BotAction` plus `card` (the meta above).
+- `POST /api/bot-actions/:id/undo`: returns 200 with the action.
+ - 409 if it isn't applied, if a newer applied change to the same target exists ("undo the newer change first: …"), or if it can't be put back safely (for example, a bot that already has history, or a channel with messages).
+- `POST /api/bot-actions/:id/confirm` and `POST /api/bot-actions/:id/decline`: only for pending actions; 409 otherwise.
+- All three return **403** for a turn token (self tools or MCP session) or any non-API bearer.
+- After a change, the card's meta is updated and SSE sends `bot_action_updated { action }`. That event is routed to the space and the chat context (channel, direct chat or thread).
diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs
new file mode 100644
index 00000000..2b6fa416
--- /dev/null
+++ b/src/db/bot_actions.rs
@@ -0,0 +1,307 @@
+//! Changes agents made to the app from a chat (`routine_create`, `bot_update`, …): the audit log
+//! and what Undo needs. A change applies at once (`applied`) and keeps a snapshot of what it
+//! replaced; the person can undo it (`undone`). Deletions only file a request (`pending`) that
+//! the person confirms (`confirmed`) or declines (`declined`).
+
+use super::models::{Message, MessageExtra, NewMessage};
+use super::spaces::SpaceId;
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use sqlx::FromRow;
+use uuid::Uuid;
+
+/// Most changes one turn may make.
+pub const MAX_PER_TURN: i64 = 10;
+
+pub const ACTION_STATUSES: [&str; 5] = ["applied", "undone", "pending", "confirmed", "declined"];
+
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct BotAction {
+ pub id: String,
+ pub space_id: String,
+ pub kwant_id: String,
+ pub turn_id: Option<String>,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ /// The tool that made it, e.g. `routine_create`.
+ pub action: String,
+ /// `routine`, `bot`, `settings`, `space`, `channel` or `profile`.
+ pub target_kind: String,
+ pub target_id: Option<String>,
+ /// One sentence for the card and the log.
+ pub summary: String,
+ /// What the change replaced (JSON), for Undo; `null` when there was nothing before.
+ #[serde(skip)]
+ pub before: Option<String>,
+ /// The result (JSON), shown on the card. Never holds secrets: no tool takes one.
+ #[serde(serialize_with = "as_json")]
+ pub after: Option<String>,
+ pub status: String,
+ pub message_id: Option<String>,
+ pub created_at: DateTime<Utc>,
+ pub resolved_at: Option<DateTime<Utc>>,
+}
+
+fn as_json<S: serde::Serializer>(raw: &Option<String>, s: S) -> Result<S::Ok, S::Error> {
+ let v: serde_json::Value = raw.as_deref().and_then(|r| serde_json::from_str(r).ok()).unwrap_or(serde_json::Value::Null);
+ v.serialize(s)
+}
+
+impl BotAction {
+ pub fn before_json(&self) -> serde_json::Value {
+ self.before.as_deref().and_then(|r| serde_json::from_str(r).ok()).unwrap_or(serde_json::Value::Null)
+ }
+
+ pub fn after_json(&self) -> serde_json::Value {
+ self.after.as_deref().and_then(|r| serde_json::from_str(r).ok()).unwrap_or(serde_json::Value::Null)
+ }
+}
+
+/// An action to record; the id and time are set on insert.
+#[derive(Debug, Clone, Default)]
+pub struct NewBotAction {
+ pub space_id: String,
+ pub kwant_id: String,
+ pub turn_id: Option<String>,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ pub action: String,
+ pub target_kind: String,
+ pub target_id: Option<String>,
+ pub summary: String,
+ pub before: Option<serde_json::Value>,
+ pub after: Option<serde_json::Value>,
+ pub status: String,
+}
+
+const GET: &str = "SELECT * FROM bot_actions WHERE id = ?";
+
+impl Database {
+ pub(super) async fn migrate_bot_actions(&self) -> Result<(), DbError> {
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS bot_actions (
+ id TEXT PRIMARY KEY,
+ space_id TEXT NOT NULL,
+ kwant_id TEXT NOT NULL,
+ turn_id TEXT,
+ channel_id TEXT,
+ direct_kwant_id TEXT,
+ thread_id TEXT,
+ action TEXT NOT NULL,
+ target_kind TEXT NOT NULL,
+ target_id TEXT,
+ summary TEXT NOT NULL,
+ before TEXT,
+ after TEXT,
+ status TEXT NOT NULL CHECK (status IN ('applied', 'undone', 'pending', 'confirmed', 'declined')),
+ message_id TEXT,
+ created_at TIMESTAMP NOT NULL,
+ resolved_at TIMESTAMP
+ )",
+ "CREATE INDEX IF NOT EXISTS bot_actions_by_space ON bot_actions (space_id, created_at)",
+ "CREATE INDEX IF NOT EXISTS bot_actions_by_turn ON bot_actions (turn_id)",
+ "CREATE INDEX IF NOT EXISTS bot_actions_by_target ON bot_actions (target_kind, target_id)",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ /// How many changes the turn has made; a turn without an id counts the agent's last 10 minutes.
+ pub async fn bot_actions_in_turn(&self, kwant_id: &str, turn_id: Option<&str>) -> Result<i64, DbError> {
+ let (n,): (i64,) = match turn_id {
+ Some(t) => sqlx::query_as("SELECT COUNT(*) FROM bot_actions WHERE turn_id = ?").bind(t).fetch_one(&self.pool).await?,
+ None => {
+ sqlx::query_as("SELECT COUNT(*) FROM bot_actions WHERE kwant_id = ? AND turn_id IS NULL AND created_at > ?")
+ .bind(kwant_id)
+ .bind(Utc::now() - chrono::Duration::minutes(10))
+ .fetch_one(&self.pool)
+ .await?
+ }
+ };
+ Ok(n)
+ }
+
+ /// Records an action together with the chat message that shows it (built by `card`), in one
+ /// transaction.
+ pub async fn record_bot_action(
+ &self,
+ new: &NewBotAction,
+ card: impl FnOnce(&BotAction) -> Option<(NewMessage, MessageExtra)>,
+ ) -> Result<(BotAction, Option<Message>), DbError> {
+ let mut tx = self.pool.begin().await?;
+ let id = Uuid::new_v4().to_string();
+ sqlx::query(
+ "INSERT INTO bot_actions (id, space_id, kwant_id, turn_id, channel_id, direct_kwant_id, thread_id, action,
+ target_kind, target_id, summary, before, after, status, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ )
+ .bind(&id)
+ .bind(&new.space_id)
+ .bind(&new.kwant_id)
+ .bind(&new.turn_id)
+ .bind(&new.channel_id)
+ .bind(&new.direct_kwant_id)
+ .bind(&new.thread_id)
+ .bind(&new.action)
+ .bind(&new.target_kind)
+ .bind(&new.target_id)
+ .bind(&new.summary)
+ .bind(new.before.as_ref().map(|v| v.to_string()))
+ .bind(new.after.as_ref().map(|v| v.to_string()))
+ .bind(&new.status)
+ .bind(Utc::now())
+ .execute(&mut *tx)
+ .await?;
+ let mut a = sqlx::query_as::<_, BotAction>(GET).bind(&id).fetch_one(&mut *tx).await?;
+ let mut message = None;
+ if let Some((msg, extra)) = card(&a) {
+ let saved = super::insert_message_on(&mut tx, &msg, &extra).await?;
+ sqlx::query("UPDATE bot_actions SET message_id = ? WHERE id = ?").bind(&saved.id).bind(&id).execute(&mut *tx).await?;
+ a = sqlx::query_as::<_, BotAction>(GET).bind(&id).fetch_one(&mut *tx).await?;
+ message = Some(saved);
+ }
+ tx.commit().await?;
+ Ok((a, message))
+ }
+
+ pub async fn get_bot_action(&self, id: &str) -> Result<Option<BotAction>, DbError> {
+ Ok(sqlx::query_as::<_, BotAction>(GET).bind(id).fetch_optional(&self.pool).await?)
+ }
+
+ /// A space's actions, newest first, at most 200; optionally by agent and/or status.
+ pub async fn list_bot_actions(
+ &self,
+ space: &SpaceId,
+ kwant_id: Option<&str>,
+ status: Option<&str>,
+ ) -> Result<Vec<BotAction>, DbError> {
+ Ok(sqlx::query_as::<_, BotAction>(
+ "SELECT * FROM bot_actions WHERE space_id = ?1 AND (?2 IS NULL OR kwant_id = ?2) AND (?3 IS NULL OR status = ?3)
+ ORDER BY created_at DESC, rowid DESC LIMIT 200",
+ )
+ .bind(space.as_str())
+ .bind(kwant_id)
+ .bind(status)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
+ /// A newer applied change to the same thing, which Undo would silently overwrite.
+ pub async fn newer_bot_action(&self, a: &BotAction) -> Result<Option<BotAction>, DbError> {
+ Ok(sqlx::query_as::<_, BotAction>(
+ "SELECT * FROM bot_actions WHERE target_kind = ? AND target_id IS ? AND status = 'applied' AND id != ?
+ AND (created_at > ? OR (created_at = ? AND rowid > (SELECT rowid FROM bot_actions WHERE id = ?)))
+ ORDER BY created_at DESC LIMIT 1",
+ )
+ .bind(&a.target_kind)
+ .bind(&a.target_id)
+ .bind(&a.id)
+ .bind(a.created_at)
+ .bind(a.created_at)
+ .bind(&a.id)
+ .fetch_optional(&self.pool)
+ .await?)
+ }
+
+ /// Moves an action from `from` to `to`; `false` when it wasn't in `from` (someone else won).
+ pub async fn resolve_bot_action(&self, id: &str, from: &str, to: &str) -> Result<bool, DbError> {
+ let done = sqlx::query("UPDATE bot_actions SET status = ?, resolved_at = ? WHERE id = ? AND status = ?")
+ .bind(to)
+ .bind(Utc::now())
+ .bind(id)
+ .bind(from)
+ .execute(&self.pool)
+ .await?;
+ Ok(done.rows_affected() == 1)
+ }
+
+ /// Puts an action back to `status` after its undo or confirm failed.
+ pub async fn reset_bot_action(&self, id: &str, status: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE bot_actions SET status = ?, resolved_at = NULL WHERE id = ?").bind(status).bind(id).execute(&self.pool).await?;
+ Ok(())
+ }
+
+ /// Points an action at the row its undo recreated (an undone delete gets a new id).
+ pub async fn retarget_bot_action(&self, id: &str, target_id: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE bot_actions SET target_id = ? WHERE id = ?").bind(target_id).bind(id).execute(&self.pool).await?;
+ Ok(())
+ }
+
+ /// Why a kwant can't be removed without losing anything, or `None` when it can: it leads a
+ /// channel or team, or has history (messages, threads, delegations, questions, files).
+ pub async fn kwant_in_use(&self, id: &str) -> Result<Option<&'static str>, DbError> {
+ let checks: [(&str, &'static str); 10] = [
+ ("SELECT COUNT(*) FROM channels WHERE lead_kwant_id = ?1", "it leads a channel"),
+ ("SELECT COUNT(*) FROM teams WHERE lead_kwant_id = ?1", "it leads a team"),
+ (
+ "SELECT COUNT(*) FROM messages WHERE direct_kwant_id = ?1 OR (sender_role = 'kwant' AND sender_id = (SELECT name FROM kwants WHERE id = ?1) \
+ AND (channel_id IN (SELECT id FROM channels WHERE space_id = (SELECT space_id FROM kwants WHERE id = ?1))))",
+ "it already has chat history",
+ ),
+ ("SELECT COUNT(*) FROM threads WHERE kwant_id = ?1", "it already has threads"),
+ ("SELECT COUNT(*) FROM delegations WHERE lead_kwant_id = ?1 OR specialist_kwant_id = ?1", "it already has delegated work"),
+ ("SELECT COUNT(*) FROM questions WHERE kwant_id = ?1", "it already asked questions"),
+ ("SELECT COUNT(*) FROM attachments WHERE kwant_id = ?1 OR direct_kwant_id = ?1", "it already has files"),
+ ("SELECT COUNT(*) FROM approvals WHERE kwant_id = ?1", "it already has approvals"),
+ ("SELECT COUNT(*) FROM skills WHERE kwant_id = ?1", "it already has skills"),
+ ("SELECT COUNT(*) FROM mcp_suggestions WHERE kwant_id = ?1 OR direct_kwant_id = ?1", "it already suggested tools"),
+ ];
+ for (sql, why) in checks {
+ let (n,): (i64,) = sqlx::query_as(sql).bind(id).fetch_one(&self.pool).await?;
+ if n > 0 {
+ return Ok(Some(why));
+ }
+ }
+ Ok(None)
+ }
+
+ /// Removes a kwant that [`Self::kwant_in_use`] cleared, with its memories, routines and
+ /// their runs, MCP opt-outs and channel/team memberships, in one transaction.
+ pub async fn delete_unused_kwant(&self, id: &str) -> Result<bool, DbError> {
+ let mut tx = self.pool.begin().await?;
+ for sql in [
+ "DELETE FROM routine_runs WHERE routine_id IN (SELECT id FROM routines WHERE kwant_id = ?)",
+ "DELETE FROM routines WHERE kwant_id = ?",
+ "DELETE FROM kwant_memories WHERE kwant_id = ?",
+ "DELETE FROM kwant_mcp_disabled WHERE kwant_id = ?",
+ "DELETE FROM kwant_mcp_servers WHERE kwant_id = ?",
+ ] {
+ sqlx::query(sql).bind(id).execute(&mut *tx).await?;
+ }
+ for table in ["channels", "teams"] {
+ let rows: Vec<(String, String)> =
+ sqlx::query_as(&format!("SELECT id, member_kwants FROM {table} WHERE member_kwants LIKE '%' || ? || '%'"))
+ .bind(id)
+ .fetch_all(&mut *tx)
+ .await?;
+ for (row_id, members) in rows {
+ let kept: Vec<String> =
+ serde_json::from_str::<Vec<String>>(&members).unwrap_or_default().into_iter().filter(|m| m != id).collect();
+ sqlx::query(&format!("UPDATE {table} SET member_kwants = ? WHERE id = ?"))
+ .bind(serde_json::to_string(&kept)?)
+ .bind(&row_id)
+ .execute(&mut *tx)
+ .await?;
+ }
+ }
+ let done = sqlx::query("DELETE FROM kwants WHERE id = ?").bind(id).execute(&mut *tx).await?;
+ tx.commit().await?;
+ Ok(done.rows_affected() == 1)
+ }
+
+ /// Removes a channel nobody has written in yet; `false` when it has messages or is #general.
+ pub async fn delete_empty_channel(&self, id: &str) -> Result<bool, DbError> {
+ let mut tx = self.pool.begin().await?;
+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM messages WHERE channel_id = ?").bind(id).fetch_one(&mut *tx).await?;
+ if n > 0 {
+ return Ok(false);
+ }
+ let done = sqlx::query("DELETE FROM channels WHERE id = ? AND name != 'general'").bind(id).execute(&mut *tx).await?;
+ tx.commit().await?;
+ Ok(done.rows_affected() == 1)
+ }
+}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 8ac0d69b..2b4726cf 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -10,6 +10,7 @@ pub mod away;
pub mod spaces;
pub mod custom_api;
pub mod mcp_suggestions;
+pub mod bot_actions;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -132,6 +133,7 @@ impl Database {
db.migrate_space_archive().await?;
db.migrate_custom_api().await?;
db.migrate_mcp_suggestions().await?;
+ db.migrate_bot_actions().await?;
}
Ok(db)
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index 67640c9b..6ac80fe5 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -91,6 +91,10 @@ pub enum RuntimeEvent {
/// whole record. See `crate::db::mcp_suggestions`.
#[serde(rename = "mcp_suggestion_updated", alias = "McpSuggestionUpdated")]
McpSuggestionUpdated { suggestion: Value },
+ /// A change an agent made from a chat was made, undone, confirmed or declined; `action` is the
+ /// whole record with its card. See `crate::db::bot_actions` and docs/bot-actions.md.
+ #[serde(rename = "bot_action_updated", alias = "BotActionUpdated")]
+ BotActionUpdated { action: Value },
/// An event from inside one turn, tagged with the turn and its chat. On the SSE wire it is
/// the inner event with `turn_id`, `kwant_id`, `context_id` and `thread_id` added at the top
/// level (see [`RuntimeEvent::to_wire`]), so clients that ignore the tags still work.
diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rs
new file mode 100644
index 00000000..72e6c8f5
--- /dev/null
+++ b/src/server/bot_actions.rs
@@ -0,0 +1,1630 @@
+//! Agents changing the app from a chat: routines, bots, non-secret settings, their space and its
+//! channels. Each tool wraps the HTTP handler the app itself uses, scoped to the turn's agent and
+//! its space. A change applies at once, is logged in `bot_actions` and shows as a card in the
+//! chat; the person can undo it (`POST /api/bot-actions/:id/undo`, which refuses agents' tokens).
+//! Deleting a bot, archiving a space or removing an account only files a request the person
+//! confirms. Secrets, sign-ins, approvals, MCP installs and the computer stay with the person.
+//! Contract: docs/bot-actions.md.
+
+// Helpers return the ready-made error `Response`
+#![allow(clippy::result_large_err)]
+
+use super::continuity::SelfScope;
+use super::scheduler::RoutinePayload;
+use super::spaces::Scope;
+use super::AppState;
+use crate::db::bot_actions::{BotAction, NewBotAction, ACTION_STATUSES, MAX_PER_TURN};
+use crate::db::models::{Kwant, MessageExtra, NewMessage};
+use crate::db::spaces::SpaceId;
+use crate::drivers::events::RuntimeEvent;
+use crate::routines::Schedule;
+use axum::{
+ extract::{Path, Query, State},
+ http::{HeaderMap, StatusCode, Uri},
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Deserialize;
+use serde_json::{json, Map, Value};
+
+/// The setting that holds the person's time zone (IANA); routines default to it.
+pub const TIMEZONE_SETTING: &str = "timezone";
+
+/// Settings agents may read and change; everything else in Settings is the person's.
+const SETTINGS: [&str; 5] = ["timezone", "max_turns_per_agent", "max_turns_global", "delegation_follow_up_minutes", "notify_on"];
+
+const AVATARS: [&str; 22] = [
+ "default", "architect", "tech_lead", "devops", "security", "fast", "designer", "data", "qa", "product", "writer", "research",
+ "teacher", "marketing", "legal", "coach", "traveler", "chef", "fitness", "party", "builder", "zen",
+];
+
+const TOOL_NAMES: [&str; 22] = [
+ "routine_list",
+ "routine_create",
+ "routine_update",
+ "routine_pause",
+ "routine_resume",
+ "routine_run_now",
+ "routine_delete",
+ "bot_list",
+ "bot_create",
+ "bot_update",
+ "bot_delete",
+ "settings_get",
+ "settings_update",
+ "space_get",
+ "space_list",
+ "space_create",
+ "space_update",
+ "space_archive",
+ "channel_list",
+ "channel_create",
+ "channel_update",
+ "profile_delete",
+];
+
+pub fn handles(name: &str) -> bool {
+ TOOL_NAMES.contains(&name)
+}
+
+fn schedule_schema() -> Value {
+ json!({
+ "type": "object",
+ "description": "{\"type\":\"daily\",\"time\":\"07:00\"} | {\"type\":\"weekly\",\"time\":\"09:30\",\"weekdays\":[\"mon\",\"fri\"]} \
+ | {\"type\":\"interval\",\"every_minutes\":60} (5-10080) | {\"type\":\"once\",\"at\":\"2026-10-20T07:00:00+02:00\"}. \
+ daily and weekly take an IANA `tz` (e.g. Europe/Berlin); without one the person's time zone from Settings is used.",
+ "properties": {
+ "type": {"type": "string", "enum": ["once", "daily", "weekly", "interval"]},
+ "time": {"type": "string", "description": "HH:MM, 24-hour"},
+ "weekdays": {"type": "array", "items": {"type": "string", "enum": ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]}},
+ "tz": {"type": "string"},
+ "every_minutes": {"type": "integer"},
+ "at": {"type": "string", "description": "RFC 3339 time with offset"},
+ },
+ "required": ["type"],
+ })
+}
+
+pub fn tools() -> Vec<Value> {
+ let routine_ref = json!({"type": "string", "description": "The routine's id, or its exact name"});
+ let bot_ref = json!({"type": "string", "description": "A bot in your space: its id or name"});
+ vec![
+ json!({
+ "name": "routine_list",
+ "description": "List the routines (scheduled runs) in your space, with their schedule, bot, chat and next run.",
+ "inputSchema": {"type": "object", "properties": {}},
+ }),
+ json!({
+ "name": "routine_create",
+ "description": "Schedule a routine: at each time, `instructions` are posted as a message to the bot, and the bot replies \
+ in the chat. Use it whenever the person asks for something to happen on its own (\"every morning\", \"each Friday\", \
+ \"remind me at 5\"). It applies at once and the person sees a card with Undo. By default the routine runs as you and \
+ delivers into this chat.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "description": "Short name, e.g. \"Morning motivation\" (max 100)"},
+ "instructions": {"type": "string", "description": "What the bot should do at each run, written as a request to it (max 4000)"},
+ "schedule": schedule_schema(),
+ "bot": bot_ref,
+ "channel": {"type": "string", "description": "Where it delivers: a channel's id or name, or \"direct\" for the bot's direct chat. Default: this chat"},
+ },
+ "required": ["name", "instructions", "schedule"],
+ },
+ }),
+ json!({
+ "name": "routine_update",
+ "description": "Change a routine in your space; give only what changes.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "routine": routine_ref,
+ "name": {"type": "string"},
+ "instructions": {"type": "string"},
+ "schedule": schedule_schema(),
+ "bot": bot_ref,
+ "channel": {"type": "string", "description": "A channel's id or name, or \"direct\""},
+ },
+ "required": ["routine"],
+ },
+ }),
+ json!({"name": "routine_pause", "description": "Pause a routine in your space until it is resumed.", "inputSchema": {"type": "object", "properties": {"routine": routine_ref}, "required": ["routine"]}}),
+ json!({"name": "routine_resume", "description": "Resume a paused routine in your space.", "inputSchema": {"type": "object", "properties": {"routine": routine_ref}, "required": ["routine"]}}),
+ json!({"name": "routine_run_now", "description": "Run a routine in your space once now, besides its schedule (e.g. so the person can see what it will send).", "inputSchema": {"type": "object", "properties": {"routine": routine_ref}, "required": ["routine"]}}),
+ json!({"name": "routine_delete", "description": "Delete a routine in your space (the person can undo it).", "inputSchema": {"type": "object", "properties": {"routine": routine_ref}, "required": ["routine"]}}),
+ json!({
+ "name": "bot_list",
+ "description": "List the bots in your space, plus the models and accounts a bot can use.",
+ "inputSchema": {"type": "object", "properties": {}},
+ }),
+ json!({
+ "name": "bot_create",
+ "description": "Add a new bot to your space. It applies at once and the person sees a card with Undo.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "description": "One word, no spaces or @, unique in the space, e.g. Chef"},
+ "title": {"type": "string", "description": "Its role, e.g. \"Recipe helper\""},
+ "instructions": {"type": "string", "description": "Its standing instructions: who it is and how it works"},
+ "soul": {"type": "string", "description": "Optional personality and voice"},
+ "model": {"type": "string", "description": "\"auto\" (default), an engine (claude, codex, grok, ollama, custom) or engine/model, from bot_list"},
+ "profile_id": {"type": "string", "description": "Optional account (from bot_list) for that engine"},
+ "avatar": {"type": "string", "enum": AVATARS},
+ },
+ "required": ["name", "title", "instructions"],
+ },
+ }),
+ json!({
+ "name": "bot_update",
+ "description": "Change a bot in your space (yourself included); give only what changes. `mcp_servers` sets exactly which \
+ already-installed tool servers it has, by name or id.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "bot": bot_ref,
+ "name": {"type": "string"},
+ "title": {"type": "string"},
+ "instructions": {"type": "string"},
+ "soul": {"type": "string"},
+ "model": {"type": "string"},
+ "profile_id": {"type": ["string", "null"], "description": "An account from bot_list, or null for the engine's default"},
+ "avatar": {"type": "string", "enum": AVATARS},
+ "mcp_servers": {"type": "array", "items": {"type": "string"}},
+ },
+ "required": ["bot"],
+ },
+ }),
+ json!({
+ "name": "bot_delete",
+ "description": "Ask the person to delete a bot in your space: they get a card to confirm. Only a bot with no history yet can be deleted.",
+ "inputSchema": {"type": "object", "properties": {"bot": bot_ref, "reason": {"type": "string"}}, "required": ["bot"]},
+ }),
+ json!({
+ "name": "settings_get",
+ "description": "Read the app settings you may change (time zone, parallel work limits, delegation follow-ups, which events notify the person).",
+ "inputSchema": {"type": "object", "properties": {}},
+ }),
+ json!({
+ "name": "settings_update",
+ "description": format!("Change app settings: {}. They apply to every space. Secrets, engines, sign-ins, approvals, \
+ the computer and tool servers stay with the person.", SETTINGS.join(", ")),
+ "inputSchema": {
+ "type": "object",
+ "properties": {"settings": {"type": "object", "description": "e.g. {\"timezone\": \"Europe/Berlin\"}"}},
+ "required": ["settings"],
+ },
+ }),
+ json!({"name": "space_get", "description": "Your space: its name, icon and colour.", "inputSchema": {"type": "object", "properties": {}}}),
+ json!({"name": "space_list", "description": "The spaces (separate sets of bots and chats) the person has.", "inputSchema": {"type": "object", "properties": {}}}),
+ json!({
+ "name": "space_create",
+ "description": "Create a new, empty space. You can't act inside it: the person opens it and adds bots there.",
+ "inputSchema": {"type": "object", "properties": {"name": {"type": "string"}, "icon": {"type": "string"}, "color": {"type": "string"}}, "required": ["name"]},
+ }),
+ json!({
+ "name": "space_update",
+ "description": "Rename or restyle your space.",
+ "inputSchema": {"type": "object", "properties": {"name": {"type": "string"}, "icon": {"type": "string"}, "color": {"type": ["string", "null"]}}},
+ }),
+ json!({
+ "name": "space_archive",
+ "description": "Ask the person to archive your space: they get a card to confirm.",
+ "inputSchema": {"type": "object", "properties": {"reason": {"type": "string"}}},
+ }),
+ json!({"name": "channel_list", "description": "The channels in your space.", "inputSchema": {"type": "object", "properties": {}}}),
+ json!({
+ "name": "channel_create",
+ "description": "Create a channel in your space. Members are bots of your space; you lead it unless `lead` says otherwise.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "description": {"type": "string"},
+ "lead": bot_ref,
+ "members": {"type": "array", "items": {"type": "string"}, "description": "Bots' ids or names"},
+ },
+ "required": ["name"],
+ },
+ }),
+ json!({
+ "name": "channel_update",
+ "description": "Set a channel's pinned instructions, which every bot there follows; \"\" clears them.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"channel": {"type": "string", "description": "Its id or name"}, "instructions": {"type": "string"}},
+ "required": ["channel", "instructions"],
+ },
+ }),
+ json!({
+ "name": "profile_delete",
+ "description": "Ask the person to remove an engine account (from bot_list) in your space: they get a card to confirm.",
+ "inputSchema": {"type": "object", "properties": {"profile_id": {"type": "string"}, "reason": {"type": "string"}}, "required": ["profile_id"]},
+ }),
+ ]
+}
+
+// Refusals: what stays with the person, and where they do it
+
+const SECRETS: &str = "Keys, tokens, passwords and webhook addresses are secrets you never handle. Ask the person to enter it \
+ themselves: API keys and engine accounts in Space settings → Accounts, the notification webhook in App settings → Notifications.";
+const ENGINES: &str = "Engines and their sign-in are the person's. Ask them to sign in, sign out or point to Ollama in Space settings → Accounts \
+ or App settings.";
+const AUTH: &str = "How people sign in to kwnt is the person's alone; ask them to change it on the computer kwnt runs on.";
+const APPROVALS: &str = "Approvals and questions are answered by the person, never by a bot: ask them to answer the card in the chat.";
+const COMPUTER: &str = "Where bots browse and run commands is the person's choice: ask them in App settings → Computer for browsing and commands.";
+const AGENT_TOOLS: &str = "Only the person can switch bots' own tools on or off, in App settings.";
+const MCP: &str = "Tool servers are installed by the person. Use mcp_suggest to offer one; they see an Install card. \
+ Their keys and headers are entered by the person in Space settings → Tools.";
+
+/// Why an agent may not change setting `key`, with where the person does it; `None` when it may.
+fn refused_setting(key: &str) -> Option<String> {
+ let k = key.trim().to_ascii_lowercase();
+ if SETTINGS.contains(&k.as_str()) {
+ return None;
+ }
+ let has = |words: &[&str]| words.iter().any(|w| k.contains(w));
+ let why = if has(&["key", "token", "password", "secret", "webhook", "credential"]) {
+ SECRETS
+ } else if has(&["auth", "login_", "sign_in", "signin"]) {
+ AUTH
+ } else if has(&["ollama", "engine", "login", "logout", "profile", "account"]) {
+ ENGINES
+ } else if has(&["approv", "permission", "question"]) {
+ APPROVALS
+ } else if has(&["computer", "machine", "sandbox", "vm"]) {
+ COMPUTER
+ } else if k == "agent_tools" {
+ AGENT_TOOLS
+ } else if has(&["mcp"]) {
+ MCP
+ } else {
+ return Some(format!("There is no setting \"{key}\" you can change; settings_get lists them: {}.", SETTINGS.join(", ")));
+ };
+ Some(why.to_string())
+}
+
+// Calling the app's own handlers
+
+/// The handler's JSON body, or its error message.
+async fn read(resp: Response) -> Result<Value, String> {
+ let status = resp.status();
+ let bytes = axum::body::to_bytes(resp.into_body(), 4 << 20).await.unwrap_or_default();
+ let body: Value =
+ serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).trim().to_string()));
+ if status.is_success() {
+ return Ok(body);
+ }
+ let message = body["error"]
+ .as_str()
+ .map(str::to_string)
+ .or_else(|| body.as_str().filter(|s| !s.is_empty()).map(str::to_string))
+ .unwrap_or_else(|| match status {
+ StatusCode::NOT_FOUND => "not found".into(),
+ StatusCode::BAD_REQUEST => "that isn't valid".into(),
+ StatusCode::CONFLICT => "that clashes with something that already exists".into(),
+ _ => status.canonical_reason().unwrap_or("failed").to_ascii_lowercase(),
+ });
+ Err(message)
+}
+
+fn space_uri(path: &str, space: &SpaceId) -> Uri {
+ format!("{path}?space={space}").parse().unwrap_or_else(|_| Uri::from_static("/"))
+}
+
+/// One tool call: the turn's agent and the space it may act in.
+struct Ctx<'a> {
+ state: &'a AppState,
+ scope: &'a SelfScope,
+ space: SpaceId,
+}
+
+type ToolResult = (String, bool);
+
+fn fail(msg: impl Into<String>) -> ToolResult {
+ (msg.into(), true)
+}
+
+fn other_space(what: &str) -> ToolResult {
+ fail(format!(
+ "That {what} is in another space. You can only change your own space; ask the person to switch to that space and do it there."
+ ))
+}
+
+fn arg<'v>(args: &'v Value, key: &str) -> Option<&'v str> {
+ args[key].as_str().map(str::trim).filter(|s| !s.is_empty())
+}
+
+pub async fn call(state: &AppState, scope: &SelfScope, name: &str, args: &Value) -> ToolResult {
+ let space = match state.db.space_of_kwant(&scope.kwant_id).await {
+ Ok(Some(s)) => s,
+ _ => return fail("Could not find your space."),
+ };
+ let cx = Ctx { state, scope, space };
+ let changes = !matches!(
+ name,
+ "routine_list" | "bot_list" | "settings_get" | "space_get" | "space_list" | "channel_list"
+ );
+ if changes {
+ if let Err(e) = super::spaces::ensure_active(state, &cx.space).await {
+ return fail(read(e).await.err().unwrap_or_else(|| "your space is archived".into()));
+ }
+ match state.db.bot_actions_in_turn(&scope.kwant_id, scope.turn_id.as_deref()).await {
+ Ok(n) if n >= MAX_PER_TURN => {
+ return fail(format!(
+ "You already made {MAX_PER_TURN} changes this turn, the most one turn may make. Tell the person what is left \
+ and let them ask again."
+ ))
+ }
+ Ok(_) => {}
+ Err(_) => return fail("Could not check your changes this turn."),
+ }
+ }
+ match name {
+ "routine_list" => cx.routine_list().await,
+ "routine_create" => cx.routine_create(args).await,
+ "routine_update" => cx.routine_update(args).await,
+ "routine_pause" => cx.routine_enable(args, false).await,
+ "routine_resume" => cx.routine_enable(args, true).await,
+ "routine_run_now" => cx.routine_run_now(args).await,
+ "routine_delete" => cx.routine_delete(args).await,
+ "bot_list" => cx.bot_list().await,
+ "bot_create" => cx.bot_create(args).await,
+ "bot_update" => cx.bot_update(args).await,
+ "bot_delete" => cx.bot_delete(args).await,
+ "settings_get" => cx.settings_get().await,
+ "settings_update" => cx.settings_update(args).await,
+ "space_get" => cx.space_get().await,
+ "space_list" => cx.space_list().await,
+ "space_create" => cx.space_create(args).await,
+ "space_update" => cx.space_update(args).await,
+ "space_archive" => cx.space_archive(args).await,
+ "channel_list" => cx.channel_list().await,
+ "channel_create" => cx.channel_create(args).await,
+ "channel_update" => cx.channel_update(args).await,
+ "profile_delete" => cx.profile_delete(args).await,
+ _ => fail(format!("Unknown tool {name}.")),
+ }
+}
+
+/// A schedule in words, for cards and replies: "daily 07:00 Europe/Berlin".
+pub fn schedule_text(s: &Value) -> String {
+ let str_of = |k: &str| s[k].as_str().unwrap_or("").to_string();
+ match s["type"].as_str() {
+ Some("once") => format!("once at {}", str_of("at")),
+ Some("daily") => format!("daily {} {}", str_of("time"), str_of("tz")),
+ Some("weekly") => {
+ let days: Vec<&str> = s["weekdays"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
+ format!("weekly on {} at {} {}", days.join(", "), str_of("time"), str_of("tz"))
+ }
+ Some("interval") => format!("every {} minutes", s["every_minutes"].as_i64().unwrap_or(0)),
+ _ => "an unknown schedule".into(),
+ }
+}
+
+impl Ctx<'_> {
+ fn db(&self) -> &crate::db::Database {
+ &self.state.db
+ }
+
+ // Lookups inside the agent's space
+
+ async fn bot(&self, reference: Option<&str>) -> Result<Kwant, ToolResult> {
+ let Some(r) = reference else {
+ return match self.db().get_kwant(&self.scope.kwant_id).await {
+ Ok(Some(k)) => Ok(k),
+ _ => Err(fail("Could not load you.")),
+ };
+ };
+ if let Ok(Some(k)) = self.db().get_kwant(r).await {
+ return if k.space_id == self.space.as_str() { Ok(k) } else { Err(other_space("bot")) };
+ }
+ let r = r.trim_start_matches('@');
+ let all = self.db().list_kwants(&self.space).await.unwrap_or_default();
+ all.into_iter()
+ .find(|k| k.name.eq_ignore_ascii_case(r))
+ .ok_or_else(|| fail(format!("There is no bot \"{r}\" in your space; bot_list shows them.")))
+ }
+
+ async fn channel(&self, reference: &str) -> Result<crate::db::models::Channel, ToolResult> {
+ if let Ok(Some(c)) = self.db().get_channel(reference).await {
+ return if c.space_id == self.space.as_str() { Ok(c) } else { Err(other_space("channel")) };
+ }
+ let r = reference.trim_start_matches('#');
+ let all = self.db().list_channels(&self.space).await.unwrap_or_default();
+ all.into_iter()
+ .find(|c| c.name.eq_ignore_ascii_case(r))
+ .ok_or_else(|| fail(format!("There is no channel \"{reference}\" in your space; channel_list shows them.")))
+ }
+
+ async fn routine(&self, args: &Value) -> Result<crate::db::continuity::RoutineRow, ToolResult> {
+ let Some(r) = arg(args, "routine") else {
+ return Err(fail("routine is required: its id or name"));
+ };
+ if let Ok(Some(row)) = self.db().get_routine(r).await {
+ return if row.space_id == self.space.as_str() { Ok(row) } else { Err(other_space("routine")) };
+ }
+ let all = self.db().list_routines(&self.space).await.unwrap_or_default();
+ let found: Vec<_> = all.into_iter().filter(|x| x.name.eq_ignore_ascii_case(r)).collect();
+ match found.len() {
+ 1 => Ok(found.into_iter().next().unwrap_or_else(|| unreachable!())),
+ 0 => Err(fail(format!("There is no routine \"{r}\" in your space; routine_list shows them."))),
+ _ => Err(fail(format!("Several routines are called \"{r}\"; give its id from routine_list."))),
+ }
+ }
+
+ /// Where a routine delivers: `Some(None)` for the bot's direct chat; `None` when not given.
+ async fn delivery(&self, args: &Value, target: &Kwant, default_here: bool) -> Result<Option<Option<String>>, ToolResult> {
+ match arg(args, "channel") {
+ Some(c) if c.eq_ignore_ascii_case("direct") => Ok(Some(None)),
+ Some(c) => Ok(Some(Some(self.channel(c).await?.id))),
+ None if !default_here => Ok(None),
+ None => {
+ let origin = self.scope.origin.as_ref();
+ match origin.and_then(|o| o.channel_id.clone()) {
+ Some(c) => Ok(Some(Some(c))),
+ None => {
+ let _ = target;
+ Ok(Some(None))
+ }
+ }
+ }
+ }
+ }
+
+ /// A schedule from the tool's arguments, with the person's time zone filled in.
+ async fn schedule(&self, raw: &Value) -> Result<Schedule, ToolResult> {
+ let mut raw = raw.clone();
+ if !raw.is_object() {
+ return Err(fail("schedule must be an object such as {\"type\":\"daily\",\"time\":\"07:00\"}"));
+ }
+ let needs_tz = matches!(raw["type"].as_str(), Some("daily" | "weekly"));
+ if needs_tz && raw["tz"].as_str().map(str::trim).unwrap_or("").is_empty() {
+ match self.db().get_setting(TIMEZONE_SETTING).await.ok().flatten().filter(|t| !t.trim().is_empty()) {
+ Some(tz) => raw["tz"] = json!(tz),
+ None => {
+ return Err(fail(
+ "The person's time zone isn't set. Pass schedule.tz (an IANA name like Europe/Berlin) if you know it, \
+ or ask the person which time zone they are in; settings_update {\"timezone\": …} saves it for next time.",
+ ))
+ }
+ }
+ }
+ let schedule: Schedule =
+ serde_json::from_value(raw).map_err(|e| fail(format!("schedule is not valid: {e}. Example: {{\"type\":\"daily\",\"time\":\"07:00\"}}")))?;
+ schedule.validate().map_err(|e| fail(format!("schedule is not valid: {e}")))?;
+ Ok(schedule)
+ }
+
+ fn where_text(&self, channel_id: &Option<String>, channels: &[crate::db::models::Channel], bot: &str) -> String {
+ match channel_id {
+ Some(c) => match channels.iter().find(|x| &x.id == c) {
+ Some(ch) => format!("#{}", ch.name),
+ None => "a channel".into(),
+ },
+ None => format!("the direct chat with {bot}"),
+ }
+ }
+
+ async fn routine_details(&self, view: &Value) -> Value {
+ let kwant_id = view["kwant_id"].as_str().unwrap_or("");
+ let bot = self.db().get_kwant(kwant_id).await.ok().flatten().map(|k| k.name).unwrap_or_default();
+ let channels = self.db().list_channels(&self.space).await.unwrap_or_default();
+ let channel_id = view["channel_id"].as_str().map(str::to_string);
+ json!({
+ "routine_id": view["id"],
+ "name": view["name"],
+ "kwant_id": kwant_id,
+ "bot_name": bot,
+ "schedule": view["schedule"],
+ "schedule_text": schedule_text(&view["schedule"]),
+ "enabled": view["enabled"],
+ "next_run_at": view["next_run_at"],
+ "channel_id": channel_id,
+ "delivers_to": self.where_text(&channel_id, &channels, &bot),
+ })
+ }
+
+ // Recording and the card
+
+ #[allow(clippy::too_many_arguments)]
+ async fn record(
+ &self,
+ action: &str,
+ target_kind: &str,
+ target_id: Option<String>,
+ summary: String,
+ before: Option<Value>,
+ after: Option<Value>,
+ status: &str,
+ ) -> Result<BotAction, String> {
+ let origin = self.scope.origin.as_ref();
+ let new = NewBotAction {
+ space_id: self.space.as_str().to_string(),
+ kwant_id: self.scope.kwant_id.clone(),
+ turn_id: self.scope.turn_id.clone(),
+ channel_id: origin.and_then(|o| o.channel_id.clone()),
+ direct_kwant_id: origin.and_then(|o| o.direct_kwant_id.clone()),
+ thread_id: origin.and_then(|o| o.thread_id.clone()),
+ action: action.into(),
+ target_kind: target_kind.into(),
+ target_id,
+ summary,
+ before,
+ after,
+ status: status.into(),
+ };
+ let sender = self.scope.kwant_name.clone();
+ let has_chat = origin.is_some_and(|o| o.channel_id.is_some() || o.direct_kwant_id.is_some() || o.thread_id.is_some());
+ let recorded = self
+ .db()
+ .record_bot_action(&new, |a| {
+ if !has_chat {
+ return None;
+ }
+ Some((
+ NewMessage {
+ // A thread's messages carry only the thread
+ channel_id: a.channel_id.clone().filter(|_| a.thread_id.is_none()),
+ direct_kwant_id: a.direct_kwant_id.clone().filter(|_| a.thread_id.is_none()),
+ sender_role: "kwant".into(),
+ sender_id: sender,
+ text: card_text(a),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ },
+ MessageExtra { thread_id: a.thread_id.clone(), meta: Some(card_meta(a)) },
+ ))
+ })
+ .await;
+ let (a, card) = recorded.map_err(|e| {
+ tracing::warn!(error = %e, action, "could not record a bot action");
+ "The change was made but could not be logged.".to_string()
+ })?;
+ if let Some(card) = card {
+ if let Some(t) = &a.thread_id {
+ let _ = self.db().touch_thread(t).await;
+ }
+ let _ = self.state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&card).unwrap_or(Value::Null) });
+ }
+ let _ = self.state.event_sender.send(RuntimeEvent::BotActionUpdated { action: action_json(&a) });
+ tracing::info!(action_id = %a.id, kwant_id = %a.kwant_id, turn_id = ?a.turn_id, action = %a.action,
+ target = ?a.target_id, status = %a.status, "bot changed the app");
+ Ok(a)
+ }
+
+ /// Records an applied change and words the tool's reply.
+ #[allow(clippy::too_many_arguments)]
+ async fn applied(
+ &self,
+ action: &str,
+ kind: &str,
+ id: Option<String>,
+ summary: String,
+ before: Option<Value>,
+ after: Value,
+ reply: String,
+ ) -> ToolResult {
+ match self.record(action, kind, id, summary, before, Some(after), "applied").await {
+ Ok(_) => (format!("{reply} The person sees a card with Undo. Tell them in one sentence what will happen."), false),
+ Err(e) => fail(format!("{reply} {e}")),
+ }
+ }
+
+ async fn requested(&self, action: &str, kind: &str, id: String, summary: String, after: Value) -> ToolResult {
+ match self.record(action, kind, Some(id), summary.clone(), None, Some(after), "pending").await {
+ Ok(_) => (
+ format!("Asked the person: {summary}. Nothing changes until they confirm the card. Tell them it is waiting for them."),
+ false,
+ ),
+ Err(e) => fail(e),
+ }
+ }
+
+ // Routines
+
+ async fn routine_list(&self) -> ToolResult {
+ let list = match read(super::scheduler::list(State(self.state.clone()), Scope(self.space.clone())).await).await {
+ Ok(Value::Array(l)) => l,
+ Ok(_) => Vec::new(),
+ Err(e) => return fail(e),
+ };
+ if list.is_empty() {
+ return ("No routines in your space yet.".into(), false);
+ }
+ let mut lines = Vec::new();
+ for r in &list {
+ let d = self.routine_details(r).await;
+ lines.push(format!(
+ "- [{}] \"{}\" by {}: {}{}, delivers to {}; next run {}",
+ r["id"].as_str().unwrap_or(""),
+ r["name"].as_str().unwrap_or(""),
+ d["bot_name"].as_str().unwrap_or(""),
+ d["schedule_text"].as_str().unwrap_or(""),
+ if r["enabled"].as_bool() == Some(true) { "" } else { " (paused)" },
+ d["delivers_to"].as_str().unwrap_or(""),
+ r["next_run_at"].as_str().unwrap_or("none"),
+ ));
+ }
+ (lines.join("\n"), false)
+ }
+
+ async fn routine_create(&self, args: &Value) -> ToolResult {
+ let target = match self.bot(arg(args, "bot")).await {
+ Ok(k) => k,
+ Err(e) => return e,
+ };
+ let schedule = match self.schedule(&args["schedule"]).await {
+ Ok(s) => s,
+ Err(e) => return e,
+ };
+ let channel_id = match self.delivery(args, &target, true).await {
+ Ok(c) => c,
+ Err(e) => return e,
+ };
+ let payload = RoutinePayload {
+ kwant_id: Some(target.id.clone()),
+ channel_id,
+ name: args["name"].as_str().map(str::to_string),
+ instructions: args["instructions"].as_str().map(str::to_string),
+ schedule: Some(schedule),
+ enabled: Some(true),
+ };
+ let resp = super::scheduler::create(
+ State(self.state.clone()),
+ Scope(self.space.clone()),
+ space_uri("/api/routines", &self.space),
+ Json(payload),
+ )
+ .await;
+ let view = match read(resp).await {
+ Ok(v) => v,
+ Err(e) => return fail(format!("The routine was not created: {e}")),
+ };
+ let d = self.routine_details(&view).await;
+ let summary = format!(
+ "created routine '{}', {}, delivering to {}",
+ view["name"].as_str().unwrap_or(""),
+ d["schedule_text"].as_str().unwrap_or(""),
+ d["delivers_to"].as_str().unwrap_or("")
+ );
+ let reply = format!(
+ "Created routine [{}] '{}': {} as {}, delivering to {}; first run {}.",
+ view["id"].as_str().unwrap_or(""),
+ view["name"].as_str().unwrap_or(""),
+ d["schedule_text"].as_str().unwrap_or(""),
+ target.name,
+ d["delivers_to"].as_str().unwrap_or(""),
+ view["next_run_at"].as_str().unwrap_or("not scheduled"),
+ );
+ self.applied("routine_create", "routine", view["id"].as_str().map(str::to_string), summary, None, d, reply).await
+ }
+
+ async fn routine_patch(&self, action: &str, row: crate::db::continuity::RoutineRow, payload: RoutinePayload, verb: &str) -> ToolResult {
+ let before = serde_json::to_value(super::scheduler::RoutineView::from(row.clone())).unwrap_or(Value::Null);
+ let resp = super::scheduler::update(State(self.state.clone()), Path(row.id.clone()), Json(payload)).await;
+ let view = match read(resp).await {
+ Ok(v) => v,
+ Err(e) => return fail(format!("The routine was not changed: {e}")),
+ };
+ let d = self.routine_details(&view).await;
+ let summary = format!("{verb} routine '{}', {}", view["name"].as_str().unwrap_or(""), d["schedule_text"].as_str().unwrap_or(""));
+ let reply = format!(
+ "{} routine '{}': {}, delivering to {}; next run {}.",
+ capitalize(verb),
+ view["name"].as_str().unwrap_or(""),
+ d["schedule_text"].as_str().unwrap_or(""),
+ d["delivers_to"].as_str().unwrap_or(""),
+ view["next_run_at"].as_str().unwrap_or("none (paused)"),
+ );
+ self.applied(action, "routine", Some(row.id), summary, Some(before), d, reply).await
+ }
+
+ async fn routine_update(&self, args: &Value) -> ToolResult {
+ let row = match self.routine(args).await {
+ Ok(r) => r,
+ Err(e) => return e,
+ };
+ let target = match arg(args, "bot") {
+ Some(b) => match self.bot(Some(b)).await {
+ Ok(k) => Some(k),
+ Err(e) => return e,
+ },
+ None => None,
+ };
+ let delivery_bot = match &target {
+ Some(k) => k.clone(),
+ None => match self.db().get_kwant(&row.kwant_id).await {
+ Ok(Some(k)) => k,
+ _ => return fail("Could not load the routine's bot."),
+ },
+ };
+ let schedule = if args["schedule"].is_null() {
+ None
+ } else {
+ match self.schedule(&args["schedule"]).await {
+ Ok(s) => Some(s),
+ Err(e) => return e,
+ }
+ };
+ let channel_id = match self.delivery(args, &delivery_bot, false).await {
+ Ok(c) => c,
+ Err(e) => return e,
+ };
+ let payload = RoutinePayload {
+ kwant_id: target.map(|k| k.id),
+ channel_id,
+ name: args["name"].as_str().map(str::to_string),
+ instructions: args["instructions"].as_str().map(str::to_string),
+ schedule,
+ enabled: None,
+ };
+ self.routine_patch("routine_update", row, payload, "updated").await
+ }
+
+ async fn routine_enable(&self, args: &Value, on: bool) -> ToolResult {
+ let row = match self.routine(args).await {
+ Ok(r) => r,
+ Err(e) => return e,
+ };
+ if row.enabled == on {
+ return (format!("Routine '{}' is already {}.", row.name, if on { "on" } else { "paused" }), false);
+ }
+ let payload = RoutinePayload { enabled: Some(on), ..Default::default() };
+ let (action, verb) = if on { ("routine_resume", "resumed") } else { ("routine_pause", "paused") };
+ self.routine_patch(action, row, payload, verb).await
+ }
+
+ async fn routine_run_now(&self, args: &Value) -> ToolResult {
+ let row = match self.routine(args).await {
+ Ok(r) => r,
+ Err(e) => return e,
+ };
+ let before = serde_json::to_value(super::scheduler::RoutineView::from(row.clone())).unwrap_or(Value::Null);
+ let d = self.routine_details(&before).await;
+ let run = match read(super::scheduler::run_now(State(self.state.clone()), Path(row.id.clone())).await).await {
+ Ok(r) => r,
+ Err(e) => return fail(format!("The routine did not run: {e}")),
+ };
+ let skipped = run["status"].as_str() == Some("skipped");
+ let mut after = d.clone();
+ after["run_id"] = run["id"].clone();
+ after["run_status"] = run["status"].clone();
+ let summary = format!("ran routine '{}' now", row.name);
+ let reply = if skipped {
+ format!("Routine '{}' is still running from before, so this run was skipped.", row.name)
+ } else {
+ format!("Started routine '{}' now; its reply arrives in {}.", row.name, d["delivers_to"].as_str().unwrap_or("its chat"))
+ };
+ match self.record("routine_run_now", "routine", Some(row.id), summary, None, Some(after), "applied").await {
+ Ok(_) => (reply, false),
+ Err(e) => fail(format!("{reply} {e}")),
+ }
+ }
+
+ async fn routine_delete(&self, args: &Value) -> ToolResult {
+ let row = match self.routine(args).await {
+ Ok(r) => r,
+ Err(e) => return e,
+ };
+ let before = serde_json::to_value(super::scheduler::RoutineView::from(row.clone())).unwrap_or(Value::Null);
+ let d = self.routine_details(&before).await;
+ if let Err(e) = read(super::scheduler::remove(State(self.state.clone()), Path(row.id.clone())).await).await {
+ return fail(format!("The routine was not deleted: {e}"));
+ }
+ let summary = format!("deleted routine '{}' ({})", row.name, d["schedule_text"].as_str().unwrap_or(""));
+ let reply = format!("Deleted routine '{}'.", row.name);
+ self.applied("routine_delete", "routine", Some(row.id), summary, Some(before), d, reply).await
+ }
+
+ // Bots
+
+ async fn bot_list(&self) -> ToolResult {
+ let bots = self.db().kwant_views(&self.space).await.unwrap_or_default();
+ let profiles = self.db().list_profiles(&self.space).await.unwrap_or_default();
+ let servers = self.db().list_mcp_servers(&self.space).await.unwrap_or_default();
+ let mut out = String::from("Bots in your space:\n");
+ for v in &bots {
+ let k = &v.kwant;
+ let tools: Vec<String> = match self.db().get_kwant_mcp_server_ids(&k.id).await {
+ Ok(ids) => servers.iter().filter(|s| ids.contains(&s.id)).map(|s| s.name.clone()).collect(),
+ Err(_) => Vec::new(),
+ };
+ out.push_str(&format!(
+ "- [{}] {} ({}), model {}{}{}{}\n",
+ k.id,
+ k.name,
+ k.title,
+ k.preferred_model,
+ v.profile_id.as_deref().map(|p| format!(", account {p}")).unwrap_or_default(),
+ if k.id == self.scope.kwant_id { " — you" } else { "" },
+ if tools.is_empty() { String::new() } else { format!(", tool servers: {}", tools.join(", ")) },
+ ));
+ }
+ out.push_str(
+ "\nModels: \"auto\" lets kwnt pick; or an engine — claude, codex, grok, ollama, custom — optionally with a model, \
+ e.g. claude/claude-sonnet-5-5.\n",
+ );
+ if profiles.is_empty() {
+ out.push_str("Accounts: none in this space yet (the person adds them in Space settings → Accounts).\n");
+ } else {
+ out.push_str("Accounts (profile_id for that engine):\n");
+ for p in profiles.iter().filter(|p| p.enabled) {
+ out.push_str(&format!("- [{}] {} ({}){}\n", p.id, p.name, p.engine, if p.is_default { ", default" } else { "" }));
+ }
+ }
+ if !servers.is_empty() {
+ out.push_str(&format!(
+ "Installed tool servers: {}\n",
+ servers.iter().map(|s| s.name.as_str()).collect::<Vec<_>>().join(", ")
+ ));
+ }
+ (out, false)
+ }
+
+ fn check_model(model: &str) -> Result<(), ToolResult> {
+ let pin = crate::router::parse_pin(model);
+ match pin.family.as_deref() {
+ None | Some("claude" | "codex" | "grok" | "custom" | "local_ollama") => Ok(()),
+ Some(_) => Err(fail(format!(
+ "Unknown model \"{model}\". Use \"auto\", an engine (claude, codex, grok, ollama, custom) or engine/model."
+ ))),
+ }
+ }
+
+ async fn bot_snapshot(&self, id: &str) -> Value {
+ let view = self.db().kwant_view(id).await.ok().flatten();
+ let mcp = self.db().get_kwant_mcp_server_ids(id).await.unwrap_or_default();
+ match view {
+ Some(v) => json!({
+ "kwant_id": v.kwant.id,
+ "name": v.kwant.name,
+ "title": v.kwant.title,
+ "instructions": v.kwant.persona_prompt,
+ "soul": v.kwant.soul,
+ "avatar": v.kwant.avatar_sprite,
+ "model": v.kwant.preferred_model,
+ "profile_id": v.profile_id,
+ "profile_failover": v.profile_failover,
+ "mcp_server_ids": mcp,
+ }),
+ None => Value::Null,
+ }
+ }
+
+ async fn bot_create(&self, args: &Value) -> ToolResult {
+ if let Some(r) = refuse_extra(args, &["mcp_env", "env", "headers", "api_key", "password", "token"]) {
+ return r;
+ }
+ let model = arg(args, "model").unwrap_or("auto").to_string();
+ if let Err(e) = Self::check_model(&model) {
+ return e;
+ }
+ let avatar = arg(args, "avatar").unwrap_or("default");
+ if !AVATARS.contains(&avatar) {
+ return fail(format!("Unknown avatar \"{avatar}\"; use one of {}.", AVATARS.join(", ")));
+ }
+ let (Some(name), Some(title), Some(instructions)) = (arg(args, "name"), arg(args, "title"), arg(args, "instructions")) else {
+ return fail("name, title and instructions are required");
+ };
+ let mut body = json!({
+ "name": name,
+ "title": title,
+ "persona_prompt": instructions,
+ "soul": arg(args, "soul").unwrap_or(""),
+ "avatar_sprite": avatar,
+ "driver_type": "api",
+ "preferred_model": model,
+ });
+ if let Some(p) = arg(args, "profile_id") {
+ body["profile_id"] = json!(p);
+ }
+ let payload = match serde_json::from_value(body) {
+ Ok(p) => p,
+ Err(e) => return fail(format!("The bot was not created: {e}")),
+ };
+ let resp = super::routes::create_kwant(State(self.state.clone()), Scope(self.space.clone()), Json(payload)).await.into_response();
+ let view = match read(resp).await {
+ Ok(v) => v,
+ Err(e) if e == "that isn't valid" => {
+ return fail("The bot was not created: the account doesn't exist in your space or is for another engine.")
+ }
+ Err(e) => return fail(format!("The bot was not created: {e}")),
+ };
+ let id = view["id"].as_str().unwrap_or("").to_string();
+ let after = self.bot_snapshot(&id).await;
+ let summary = format!("created bot {} ({}), model {}", name, title, after["model"].as_str().unwrap_or("auto"));
+ let reply = format!("Created bot {name} [{id}]: {title}. The person can chat with it right away.");
+ self.applied("bot_create", "bot", Some(id), summary, None, after, reply).await
+ }
+
+ async fn bot_update(&self, args: &Value) -> ToolResult {
+ if let Some(r) = refuse_extra(args, &["mcp_env", "env", "headers", "api_key", "password", "token"]) {
+ return r;
+ }
+ let target = match self.bot(arg(args, "bot")).await {
+ Ok(k) => k,
+ Err(e) => return e,
+ };
+ let before = self.bot_snapshot(&target.id).await;
+ let mcp_ids = match args.get("mcp_servers") {
+ None | Some(Value::Null) => None,
+ Some(Value::Array(list)) => {
+ let servers = self.db().list_mcp_servers(&self.space).await.unwrap_or_default();
+ let mut ids = Vec::new();
+ for item in list {
+ let r = item.as_str().unwrap_or("").trim();
+ match servers.iter().find(|s| s.id == r || s.name.eq_ignore_ascii_case(r)) {
+ Some(s) => ids.push(s.id.clone()),
+ None => {
+ return fail(format!(
+ "No tool server \"{r}\" is installed in your space. {MCP}"
+ ))
+ }
+ }
+ }
+ Some(ids)
+ }
+ Some(_) => return fail("mcp_servers must be a list of installed tool servers' names or ids"),
+ };
+ let model = arg(args, "model").map(str::to_string).unwrap_or_else(|| target.preferred_model.clone());
+ if let Err(e) = Self::check_model(&model) {
+ return e;
+ }
+ if let Some(a) = arg(args, "avatar") {
+ if !AVATARS.contains(&a) {
+ return fail(format!("Unknown avatar \"{a}\"; use one of {}.", AVATARS.join(", ")));
+ }
+ }
+ let mut body = json!({
+ "name": arg(args, "name").unwrap_or(&target.name),
+ "title": arg(args, "title").unwrap_or(&target.title),
+ "persona_prompt": arg(args, "instructions").unwrap_or(&target.persona_prompt),
+ "soul": args["soul"].as_str().map(str::trim).unwrap_or(&target.soul),
+ "avatar_sprite": arg(args, "avatar").unwrap_or(&target.avatar_sprite),
+ "preferred_model": model,
+ });
+ if args.get("profile_id").is_some() {
+ body["profile_id"] = args["profile_id"].clone();
+ }
+ let payload = match serde_json::from_value(body) {
+ Ok(p) => p,
+ Err(e) => return fail(format!("The bot was not changed: {e}")),
+ };
+ let resp = super::routes::update_kwant(State(self.state.clone()), Path(target.id.clone()), Json(payload)).await.into_response();
+ match read(resp).await {
+ Ok(_) => {}
+ Err(e) if e == "that isn't valid" => {
+ return fail("The bot was not changed: the account doesn't exist in your space or is for another engine.")
+ }
+ Err(e) => return fail(format!("The bot was not changed: {e}")),
+ }
+ if let Some(ids) = &mcp_ids {
+ if self.db().set_kwant_mcp_servers(&target.id, ids).await.is_err() {
+ return fail("The bot was changed, but its tool servers could not be set.");
+ }
+ }
+ let after = self.bot_snapshot(&target.id).await;
+ let changed: Vec<&str> = ["name", "title", "instructions", "soul", "avatar", "model", "profile_id", "mcp_server_ids"]
+ .into_iter()
+ .filter(|k| before[*k] != after[*k])
+ .collect();
+ if changed.is_empty() {
+ return (format!("Nothing changed for {}.", target.name), false);
+ }
+ let summary = format!("updated bot {}: {}", after["name"].as_str().unwrap_or(&target.name), changed.join(", ").replace("mcp_server_ids", "tool servers"));
+ let reply = format!("Updated {} ({}).", after["name"].as_str().unwrap_or(&target.name), changed.join(", "));
+ self.applied("bot_update", "bot", Some(target.id), summary, Some(before), after, reply).await
+ }
+
+ async fn bot_delete(&self, args: &Value) -> ToolResult {
+ let target = match self.bot(arg(args, "bot")).await {
+ Ok(k) => k,
+ Err(e) => return e,
+ };
+ if let Ok(Some(why)) = self.db().kwant_in_use(&target.id).await {
+ return fail(format!(
+ "{} can't be deleted: {why}, and deleting would lose it. kwnt only deletes bots with no history yet.",
+ target.name
+ ));
+ }
+ let mut after = self.bot_snapshot(&target.id).await;
+ after["reason"] = json!(arg(args, "reason"));
+ self.requested("bot_delete", "bot", target.id.clone(), format!("delete bot {}", target.name), after).await
+ }
+
+ // Settings
+
+ async fn settings_values(&self) -> Result<Map<String, Value>, String> {
+ let all = read(super::routes::get_settings(State(self.state.clone())).await.into_response()).await?;
+ let mut out = Map::new();
+ for k in SETTINGS {
+ out.insert(k.to_string(), all.get(k).cloned().unwrap_or(Value::Null));
+ }
+ Ok(out)
+ }
+
+ async fn settings_get(&self) -> ToolResult {
+ match self.settings_values().await {
+ Ok(v) => (
+ format!(
+ "{}\nThey apply to every space. timezone \"\" means not set; notify_on lists events that notify the person.",
+ Value::Object(v)
+ ),
+ false,
+ ),
+ Err(e) => fail(e),
+ }
+ }
+
+ async fn settings_update(&self, args: &Value) -> ToolResult {
+ let Some(changes) = args["settings"].as_object().filter(|m| !m.is_empty()) else {
+ return fail("settings must be an object such as {\"timezone\": \"Europe/Berlin\"}");
+ };
+ let refusals: Vec<String> = changes.keys().filter_map(|k| refused_setting(k).map(|why| format!("{k}: {why}"))).collect();
+ if !refusals.is_empty() {
+ return fail(format!("Nothing was changed. {}", refusals.join(" ")));
+ }
+ let before = match self.settings_values().await {
+ Ok(v) => v,
+ Err(e) => return fail(e),
+ };
+ let mut payload = Map::new();
+ for (k, v) in changes {
+ let k = k.trim().to_ascii_lowercase();
+ payload.insert(k, v.clone());
+ }
+ if let Err(e) = save_settings(self.state, Value::Object(payload.clone())).await {
+ return fail(format!("Nothing was changed: {e}"));
+ }
+ let after_all = match self.settings_values().await {
+ Ok(v) => v,
+ Err(e) => return fail(e),
+ };
+ let mut before_changed = Map::new();
+ let mut after_changed = Map::new();
+ for k in payload.keys() {
+ if before.get(k) != after_all.get(k) {
+ before_changed.insert(k.clone(), before.get(k).cloned().unwrap_or(Value::Null));
+ after_changed.insert(k.clone(), after_all.get(k).cloned().unwrap_or(Value::Null));
+ }
+ }
+ if after_changed.is_empty() {
+ return ("Those settings already had those values.".into(), false);
+ }
+ let words: Vec<String> = after_changed.iter().map(|(k, v)| format!("{k} = {v}")).collect();
+ let summary = format!("changed settings: {}", words.join(", "));
+ let reply = format!("Saved {} (for every space).", words.join(", "));
+ self.applied("settings_update", "settings", None, summary, Some(Value::Object(before_changed)), Value::Object(after_changed), reply)
+ .await
+ }
+
+ // Spaces
+
+ async fn space_json(&self, id: &SpaceId) -> Value {
+ match self.db().get_space(id).await.ok().flatten() {
+ Some(s) => json!({"space_id": s.id, "name": s.name, "icon": s.icon, "color": s.color, "archived": s.archived_at.is_some()}),
+ None => Value::Null,
+ }
+ }
+
+ async fn space_get(&self) -> ToolResult {
+ (self.space_json(&self.space).await.to_string(), false)
+ }
+
+ async fn space_list(&self) -> ToolResult {
+ let spaces = self.db().list_spaces().await.unwrap_or_default();
+ let lines: Vec<String> = spaces
+ .iter()
+ .map(|s| {
+ format!(
+ "- [{}] {}{}{}",
+ s.id,
+ s.name,
+ if s.archived_at.is_some() { " (archived)" } else { "" },
+ if s.id == self.space.as_str() { " — yours" } else { "" }
+ )
+ })
+ .collect();
+ (format!("{}\nYou can only change your own space.", lines.join("\n")), false)
+ }
+
+ async fn space_create(&self, args: &Value) -> ToolResult {
+ let Some(name) = arg(args, "name") else {
+ return fail("name is required");
+ };
+ let body = super::spaces::CreateBody {
+ name: name.to_string(),
+ icon: arg(args, "icon").map(str::to_string),
+ color: arg(args, "color").map(str::to_string),
+ this_machine_enabled: None,
+ };
+ let created = match read(super::spaces::create(State(self.state.clone()), Json(body)).await).await {
+ Ok(v) => v,
+ Err(e) => return fail(format!("The space was not created: {e}")),
+ };
+ let id = created["id"].as_str().unwrap_or("").to_string();
+ let after = self.space_json(&SpaceId::new(&id)).await;
+ let reply = format!("Created the space {name} [{id}]. It is empty; the person opens it from the space switcher to add bots.");
+ self.applied("space_create", "space", Some(id), format!("created space {name}"), None, after, reply).await
+ }
+
+ async fn space_update(&self, args: &Value) -> ToolResult {
+ if args.get("archived").is_some() {
+ return fail("Use space_archive to ask the person to archive the space.");
+ }
+ let before = self.space_json(&self.space).await;
+ let mut body = json!({});
+ for k in ["name", "icon"] {
+ if let Some(v) = arg(args, k) {
+ body[k] = json!(v);
+ }
+ }
+ if args.get("color").is_some() {
+ body["color"] = args["color"].clone();
+ }
+ if body.as_object().is_some_and(|m| m.is_empty()) {
+ return fail("Give a name, icon or color to change.");
+ }
+ let patch = match serde_json::from_value(body) {
+ Ok(p) => p,
+ Err(e) => return fail(format!("The space was not changed: {e}")),
+ };
+ if let Err(e) = read(super::spaces::update(State(self.state.clone()), Path(self.space.to_string()), Json(patch)).await).await {
+ return fail(format!("The space was not changed: {e}"));
+ }
+ let after = self.space_json(&self.space).await;
+ let summary = format!("updated space {}", after["name"].as_str().unwrap_or(""));
+ self.applied("space_update", "space", Some(self.space.to_string()), summary.clone(), Some(before), after, format!("{}.", capitalize(&summary)))
+ .await
+ }
+
+ async fn space_archive(&self, args: &Value) -> ToolResult {
+ if self.space.is_default() {
+ return fail("The Default space can't be archived.");
+ }
+ let mut after = self.space_json(&self.space).await;
+ let name = after["name"].as_str().unwrap_or("").to_string();
+ after["reason"] = json!(arg(args, "reason"));
+ self.requested("space_archive", "space", self.space.to_string(), format!("archive the space {name}"), after).await
+ }
+
+ // Channels
+
+ async fn channel_list(&self) -> ToolResult {
+ let channels = self.db().list_channels(&self.space).await.unwrap_or_default();
+ let bots = self.db().list_kwants(&self.space).await.unwrap_or_default();
+ let name_of = |id: &str| bots.iter().find(|k| k.id == id).map(|k| k.name.clone()).unwrap_or_else(|| id.to_string());
+ let lines: Vec<String> = channels
+ .iter()
+ .map(|c| {
+ format!(
+ "- [{}] #{} led by {}, members: {}",
+ c.id,
+ c.name,
+ name_of(&c.lead_kwant_id),
+ serde_json::from_str::<Vec<String>>(&c.member_kwants).unwrap_or_default().iter().map(|m| name_of(m)).collect::<Vec<_>>().join(", ")
+ )
+ })
+ .collect();
+ (if lines.is_empty() { "No channels yet.".into() } else { lines.join("\n") }, false)
+ }
+
+ async fn channel_create(&self, args: &Value) -> ToolResult {
+ let Some(name) = arg(args, "name") else {
+ return fail("name is required");
+ };
+ let lead = match self.bot(arg(args, "lead")).await {
+ Ok(k) => k,
+ Err(e) => return e,
+ };
+ let mut members = vec![lead.id.clone()];
+ if let Some(list) = args["members"].as_array() {
+ for m in list {
+ match self.bot(m.as_str()).await {
+ Ok(k) if !members.contains(&k.id) => members.push(k.id),
+ Ok(_) => {}
+ Err(e) => return e,
+ }
+ }
+ }
+ let input = crate::db::models::NewChannel {
+ name: name.to_string(),
+ description: arg(args, "description").map(str::to_string),
+ lead_kwant_id: lead.id.clone(),
+ member_kwants: members,
+ routing_mode: "auto".into(),
+ };
+ let resp = super::routes::create_channel(State(self.state.clone()), Scope(self.space.clone()), Json(input)).await.into_response();
+ let created = match read(resp).await {
+ Ok(v) => v,
+ Err(e) => return fail(format!("The channel was not created: {e}")),
+ };
+ let id = created["id"].as_str().unwrap_or("").to_string();
+ let after = json!({"channel_id": id, "name": created["name"], "lead_kwant_id": lead.id, "member_kwants": created["member_kwants"]});
+ let reply = format!("Created #{} [{id}], led by {}.", created["name"].as_str().unwrap_or(name), lead.name);
+ self.applied("channel_create", "channel", Some(id), format!("created channel #{name}"), None, after, reply).await
+ }
+
+ async fn channel_update(&self, args: &Value) -> ToolResult {
+ let Some(r) = arg(args, "channel") else {
+ return fail("channel is required");
+ };
+ let channel = match self.channel(r).await {
+ Ok(c) => c,
+ Err(e) => return e,
+ };
+ let Some(text) = args["instructions"].as_str() else {
+ return fail("instructions is required (\"\" clears them)");
+ };
+ let before = json!({"channel_id": channel.id, "name": channel.name, "instructions": self.db().channel_instructions(&channel.id).await.ok().flatten()});
+ let payload = super::continuity::InstructionsPayload { instructions: Some(text.to_string()) };
+ if let Err(e) = read(super::continuity::patch_channel(State(self.state.clone()), Path(channel.id.clone()), Json(payload)).await).await {
+ return fail(format!("The channel was not changed: {e}"));
+ }
+ let after = json!({"channel_id": channel.id, "name": channel.name, "instructions": self.db().channel_instructions(&channel.id).await.ok().flatten()});
+ let verb = if text.trim().is_empty() { "cleared" } else { "set" };
+ let summary = format!("{verb} the instructions of #{}", channel.name);
+ self.applied("channel_update", "channel", Some(channel.id), summary.clone(), Some(before), after, format!("{}.", capitalize(&summary)))
+ .await
+ }
+
+ // Accounts
+
+ async fn profile_delete(&self, args: &Value) -> ToolResult {
+ let Some(id) = arg(args, "profile_id") else {
+ return fail("profile_id is required (from bot_list)");
+ };
+ let profile = match self.db().get_profile(id).await {
+ Ok(Some(p)) => p,
+ Ok(None) => return fail("There is no such account; bot_list shows them."),
+ Err(_) => return fail("Could not load the account."),
+ };
+ if profile.space_id != self.space.as_str() {
+ return other_space("account");
+ }
+ if profile.kind == "system" {
+ return fail("The built-in account can't be removed.");
+ }
+ let after = json!({"profile_id": profile.id, "name": profile.name, "engine": profile.engine, "reason": arg(args, "reason")});
+ self.requested("profile_delete", "profile", profile.id.clone(), format!("remove the {} account {}", profile.engine, profile.name), after)
+ .await
+ }
+}
+
+fn capitalize(s: &str) -> String {
+ let mut c = s.chars();
+ match c.next() {
+ Some(f) => f.to_uppercase().chain(c).collect(),
+ None => String::new(),
+ }
+}
+
+/// A refusal when the agent passed an argument that would carry a secret or install something.
+fn refuse_extra(args: &Value, keys: &[&str]) -> Option<ToolResult> {
+ let found = keys.iter().find(|k| args.get(**k).is_some())?;
+ let why = match *found {
+ "mcp_env" | "env" | "headers" => MCP,
+ _ => SECRETS,
+ };
+ Some(fail(format!("Nothing was changed: {found} is not something you can set. {why}")))
+}
+
+async fn save_settings(state: &AppState, payload: Value) -> Result<(), String> {
+ let payload = serde_json::from_value(payload).map_err(|e| e.to_string())?;
+ read(super::routes::save_settings(State(state.clone()), Ok(Json(payload))).await.into_response()).await.map(|_| ())
+}
+
+// The card
+
+fn card_text(a: &BotAction) -> String {
+ let lead = match a.status.as_str() {
+ "pending" => "Needs your OK",
+ _ => "Done",
+ };
+ format!("{lead}: {}.", capitalize(&a.summary))
+}
+
+/// Whether the person can undo the action now.
+fn can_undo(a: &BotAction) -> bool {
+ a.status == "applied" && a.action != "routine_run_now"
+}
+
+/// The card's `meta` (docs/bot-actions.md).
+pub fn card_meta(a: &BotAction) -> Value {
+ json!({
+ "kind": "bot_action",
+ "action_id": a.id,
+ "action": a.action,
+ "kwant_id": a.kwant_id,
+ "target_kind": a.target_kind,
+ "target_id": a.target_id,
+ "summary": a.summary,
+ "details": a.after_json(),
+ "status": a.status,
+ "can_undo": can_undo(a),
+ "needs_confirmation": a.status == "pending",
+ "created_at": a.created_at,
+ "resolved_at": a.resolved_at,
+ })
+}
+
+fn action_json(a: &BotAction) -> Value {
+ let mut v = serde_json::to_value(a).unwrap_or(Value::Null);
+ v["card"] = card_meta(a);
+ v
+}
+
+async fn changed(state: &AppState, a: &BotAction) {
+ if let Some(mid) = &a.message_id {
+ let _ = state.db.set_message_meta(mid, &card_meta(a)).await;
+ }
+ let _ = state.event_sender.send(RuntimeEvent::BotActionUpdated { action: action_json(a) });
+}
+
+// Routes (the person's)
+
+fn error(status: StatusCode, message: impl Into<String>) -> Response {
+ (status, Json(json!({ "error": message.into() }))).into_response()
+}
+
+#[derive(Deserialize)]
+pub struct ListQuery {
+ pub status: Option<String>,
+ pub kwant_id: Option<String>,
+}
+
+/// `GET /api/bot-actions?space=&kwant_id=&status=`: the space's actions, newest first (max 200).
+pub async fn list(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<ListQuery>) -> Response {
+ let status = q.status.filter(|s| !s.is_empty());
+ if status.as_deref().is_some_and(|s| !ACTION_STATUSES.contains(&s)) {
+ return error(StatusCode::BAD_REQUEST, "unknown status");
+ }
+ let kwant = q.kwant_id.filter(|k| !k.is_empty());
+ match state.db.list_bot_actions(&space, kwant.as_deref(), status.as_deref()).await {
+ Ok(list) => Json(list.iter().map(action_json).collect::<Vec<_>>()).into_response(),
+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+}
+
+async fn load(state: &AppState, id: &str) -> Result<BotAction, Response> {
+ match state.db.get_bot_action(id).await {
+ Ok(Some(a)) => Ok(a),
+ Ok(None) => Err(error(StatusCode::NOT_FOUND, "action not found")),
+ Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
+ }
+}
+
+/// Moves the action from `from` to `to`, runs `work`, and puts it back if `work` fails.
+async fn resolve<F, Fut>(state: &AppState, headers: &HeaderMap, id: &str, from: &str, to: &str, work: F) -> Response
+where
+ F: FnOnce(BotAction) -> Fut,
+ Fut: std::future::Future<Output = Result<Option<String>, Response>>,
+{
+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(state, headers, "only the person can undo, confirm or decline a bot's change").await {
+ return r;
+ }
+ let a = match load(state, id).await {
+ Ok(a) => a,
+ Err(r) => return r,
+ };
+ if a.status != from {
+ return error(StatusCode::CONFLICT, format!("this change is {}", a.status));
+ }
+ match state.db.resolve_bot_action(id, from, to).await {
+ Ok(true) => {}
+ Ok(false) => return error(StatusCode::CONFLICT, "this change was just resolved by someone else"),
+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+ match work(a).await {
+ Ok(new_target) => {
+ if let Some(t) = new_target {
+ let _ = state.db.retarget_bot_action(id, &t).await;
+ }
+ let now = match load(state, id).await {
+ Ok(a) => a,
+ Err(r) => return r,
+ };
+ changed(state, &now).await;
+ tracing::info!(action_id = %now.id, status = %now.status, "the person resolved a bot action");
+ Json(action_json(&now)).into_response()
+ }
+ Err(r) => {
+ let _ = state.db.reset_bot_action(id, from).await;
+ r
+ }
+ }
+}
+
+/// `POST /api/bot-actions/:id/undo`: puts back what an applied change replaced. 409 when a newer
+/// change to the same thing would be overwritten, or the thing can't be put back safely.
+pub async fn undo(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+ if let Ok(Some(a)) = state.db.get_bot_action(&id).await {
+ if a.status == "applied" && !can_undo(&a) {
+ return error(StatusCode::CONFLICT, "a run that already started can't be undone");
+ }
+ if a.status == "applied" {
+ if let Ok(Some(newer)) = state.db.newer_bot_action(&a).await {
+ return error(StatusCode::CONFLICT, format!("undo the newer change first: {}", newer.summary));
+ }
+ }
+ }
+ let st = state.clone();
+ resolve(&state, &headers, &id, "applied", "undone", |a| async move { undo_action(&st, &a).await }).await
+}
+
+/// `POST /api/bot-actions/:id/confirm`: the person carries out a requested deletion.
+pub async fn confirm(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+ let st = state.clone();
+ resolve(&state, &headers, &id, "pending", "confirmed", |a| async move { confirm_action(&st, &a).await.map(|_| None) }).await
+}
+
+/// `POST /api/bot-actions/:id/decline`: the person turns a request down; nothing changes.
+pub async fn decline(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+ resolve(&state, &headers, &id, "pending", "declined", |_| async { Ok(None) }).await
+}
+
+async fn ok_or_conflict(resp: Response, what: &str) -> Result<Value, Response> {
+ read(resp).await.map_err(|e| error(StatusCode::CONFLICT, format!("{what}: {e}")))
+}
+
+async fn delete_unused_bot(state: &AppState, id: &str) -> Result<(), Response> {
+ match state.db.kwant_in_use(id).await {
+ Ok(None) => {}
+ Ok(Some(why)) => return Err(error(StatusCode::CONFLICT, format!("the bot can't be removed: {why}"))),
+ Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
+ }
+ match state.db.delete_unused_kwant(id).await {
+ Ok(true) => {
+ state.scheduler_wake.notify_one();
+ Ok(())
+ }
+ Ok(false) => Err(error(StatusCode::CONFLICT, "the bot no longer exists")),
+ Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
+ }
+}
+
+fn routine_payload(before: &Value) -> Result<RoutinePayload, Response> {
+ let schedule = serde_json::from_value(before["schedule"].clone())
+ .map_err(|_| error(StatusCode::CONFLICT, "the routine's old schedule is unreadable"))?;
+ Ok(RoutinePayload {
+ kwant_id: before["kwant_id"].as_str().map(str::to_string),
+ channel_id: Some(before["channel_id"].as_str().map(str::to_string)),
+ name: before["name"].as_str().map(str::to_string),
+ instructions: before["instructions"].as_str().map(str::to_string),
+ schedule: Some(schedule),
+ enabled: before["enabled"].as_bool(),
+ })
+}
+
+/// Puts back what `a` replaced; `Some(id)` when that made a new row (an undone delete).
+async fn undo_action(state: &AppState, a: &BotAction) -> Result<Option<String>, Response> {
+ let target = a.target_id.clone().unwrap_or_default();
+ let before = a.before_json();
+ let space = SpaceId::new(&a.space_id);
+ match a.action.as_str() {
+ "routine_create" => {
+ ok_or_conflict(super::scheduler::remove(State(state.clone()), Path(target)).await, "the routine can't be removed").await?;
+ }
+ "routine_update" | "routine_pause" | "routine_resume" => {
+ let p = routine_payload(&before)?;
+ ok_or_conflict(super::scheduler::update(State(state.clone()), Path(target), Json(p)).await, "the routine can't be put back")
+ .await?;
+ }
+ "routine_delete" => {
+ let p = routine_payload(&before)?;
+ let resp = super::scheduler::create(State(state.clone()), Scope(space.clone()), space_uri("/api/routines", &space), Json(p)).await;
+ let created = ok_or_conflict(resp, "the routine can't be recreated").await?;
+ return Ok(created["id"].as_str().map(str::to_string));
+ }
+ "bot_create" => delete_unused_bot(state, &target).await?,
+ "bot_update" => {
+ if state.db.get_kwant(&target).await.ok().flatten().is_none() {
+ return Err(error(StatusCode::CONFLICT, "the bot no longer exists"));
+ }
+ let body = json!({
+ "name": before["name"],
+ "title": before["title"],
+ "persona_prompt": before["instructions"],
+ "soul": before["soul"],
+ "avatar_sprite": before["avatar"],
+ "preferred_model": before["model"],
+ "profile_id": before["profile_id"],
+ "profile_failover": before["profile_failover"],
+ });
+ let payload = serde_json::from_value(body).map_err(|_| error(StatusCode::CONFLICT, "the bot's old settings are unreadable"))?;
+ ok_or_conflict(
+ super::routes::update_kwant(State(state.clone()), Path(target.clone()), Json(payload)).await.into_response(),
+ "the bot can't be put back",
+ )
+ .await?;
+ let ids: Vec<String> = serde_json::from_value(before["mcp_server_ids"].clone()).unwrap_or_default();
+ let installed: Vec<String> = state.db.list_mcp_servers(&space).await.unwrap_or_default().into_iter().map(|s| s.id).collect();
+ let ids: Vec<String> = ids.into_iter().filter(|i| installed.contains(i)).collect();
+ state.db.set_kwant_mcp_servers(&target, &ids).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
+ }
+ "settings_update" => {
+ let mut payload = before.as_object().cloned().unwrap_or_default();
+ // An unset time zone reads as "", which clears it again
+ if let Some(Value::Null) = payload.get("timezone") {
+ payload.insert("timezone".into(), json!(""));
+ }
+ save_settings(state, Value::Object(payload)).await.map_err(|e| error(StatusCode::CONFLICT, e))?;
+ }
+ "space_create" => {
+ let patch = serde_json::from_value(json!({"archived": true})).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
+ ok_or_conflict(super::spaces::update(State(state.clone()), Path(target), Json(patch)).await, "the space can't be archived")
+ .await?;
+ }
+ "space_update" => {
+ let patch = serde_json::from_value(json!({"name": before["name"], "icon": before["icon"], "color": before["color"]}))
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
+ ok_or_conflict(super::spaces::update(State(state.clone()), Path(target), Json(patch)).await, "the space can't be put back")
+ .await?;
+ }
+ "channel_create" => match state.db.delete_empty_channel(&target).await {
+ Ok(true) => {}
+ Ok(false) => return Err(error(StatusCode::CONFLICT, "the channel already has messages, so it is kept")),
+ Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
+ },
+ "channel_update" => {
+ let text = before["instructions"].as_str().unwrap_or("").to_string();
+ match state.db.set_channel_instructions(&target, &text).await {
+ Ok(true) => {}
+ Ok(false) => return Err(error(StatusCode::CONFLICT, "the channel no longer exists")),
+ Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),
+ }
+ }
+ _ => return Err(error(StatusCode::CONFLICT, "this change can't be undone")),
+ }
+ Ok(None)
+}
+
+async fn confirm_action(state: &AppState, a: &BotAction) -> Result<(), Response> {
+ let target = a.target_id.clone().unwrap_or_default();
+ match a.action.as_str() {
+ "bot_delete" => delete_unused_bot(state, &target).await,
+ "space_archive" => {
+ let patch = serde_json::from_value(json!({"archived": true})).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
+ ok_or_conflict(super::spaces::update(State(state.clone()), Path(target), Json(patch)).await, "the space can't be archived")
+ .await
+ .map(|_| ())
+ }
+ "profile_delete" => {
+ ok_or_conflict(super::profile_routes::remove(State(state.clone()), Path(target)).await, "the account can't be removed")
+ .await
+ .map(|_| ())
+ }
+ _ => Err(error(StatusCode::CONFLICT, "this request can't be confirmed")),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn settings_refusals_name_the_place() {
+ assert!(refused_setting("timezone").is_none());
+ assert!(refused_setting("anthropic_api_key").unwrap().contains("Accounts"));
+ assert!(refused_setting("notify_webhook_url").unwrap().contains("Notifications"));
+ assert!(refused_setting("ollama_url").unwrap().contains("Accounts"));
+ assert!(refused_setting("auth_token").unwrap().contains("secret"));
+ assert!(refused_setting("auth_mode").unwrap().contains("sign in to kwnt"));
+ assert!(refused_setting("auto_approve").unwrap().contains("Approvals"));
+ assert!(refused_setting("computer_mode").unwrap().contains("Computer"));
+ assert!(refused_setting("agent_tools").unwrap().contains("own tools"));
+ assert!(refused_setting("mcp_servers").unwrap().contains("mcp_suggest"));
+ assert!(refused_setting("colour").unwrap().contains("no setting"));
+ }
+
+ #[test]
+ fn schedules_read_as_words() {
+ assert_eq!(schedule_text(&json!({"type": "daily", "time": "07:00", "tz": "Europe/Berlin"})), "daily 07:00 Europe/Berlin");
+ assert_eq!(
+ schedule_text(&json!({"type": "weekly", "time": "09:30", "weekdays": ["mon", "fri"], "tz": "UTC"})),
+ "weekly on mon, fri at 09:30 UTC"
+ );
+ assert_eq!(schedule_text(&json!({"type": "interval", "every_minutes": 60})), "every 60 minutes");
+ }
+}
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 38fa4e06..5ac04440 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -97,7 +97,17 @@ pub async fn prompt_block(
- When a request needs a capability you don't have (a service, an app, live data), `mcp_search` looks for an MCP server \
that adds it and `mcp_suggest` offers one to the user as a one-click install card. You can't install anything yourself: \
suggest at most one or two good matches, then carry on with your reply as best you can without them. \
- Once the user installs one, its tools are yours from your next turn."
+ Once the user installs one, its tools are yours from your next turn.\n\
+ - You can set up and manage the app yourself; when asked, do it in that same turn instead of telling the user how. \
+ When the user wants something to happen on its own (\"every morning\", \"each Friday\", \"remind me at 5\"), \
+ `routine_create` schedules it (it runs as you and replies in this chat by default); `routine_list`, `routine_update`, \
+ `routine_pause`, `routine_resume`, `routine_run_now` and `routine_delete` manage routines. `bot_list`, `bot_create` and \
+ `bot_update` add and change bots, `settings_get`/`settings_update` change non-secret settings such as the time zone, \
+ and `space_*` and `channel_*` manage your space and its channels. Each change applies at once and the user sees a card \
+ with Undo; afterwards say in one sentence what will happen. The user may undo a change later, so check with the list tools \
+ before relying on an earlier one. Deleting a bot, a space or an account only asks the user to confirm. \
+ Never handle keys, passwords or sign-ins, answer approvals, install tool servers or change the computer: those tools \
+ tell you where in Settings the user does it."
));
}
out
@@ -218,6 +228,7 @@ fn tool_list(scope: &SelfScope) -> Value {
if let Some(list) = tools.as_array_mut() {
list.extend(super::skills::tools());
list.extend(super::mcp_suggest::tools());
+ list.extend(super::bot_actions::tools());
if scope.sandbox_target.is_some() {
list.extend(browser_tools());
}
@@ -587,6 +598,7 @@ async fn call_tool(
"ask_user" => super::questions::tool_ask(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,
"list_attachments" if scope.origin.is_some() => super::attachments::tool_list(state, scope).await,
"share_file" if scope.origin.is_some() => super::attachments::tool_share(state, scope, args).await,
"delegate" => super::delegation::tool_delegate(state, scope, args).await,
diff --git a/src/server/mcp_suggest.rs b/src/server/mcp_suggest.rs
index bf2e435b..7d9b0fe4 100644
--- a/src/server/mcp_suggest.rs
+++ b/src/server/mcp_suggest.rs
@@ -370,6 +370,13 @@ fn error(status: StatusCode, message: impl Into<String>) -> Response {
/// the API token: a request carrying one is an agent's, and agents may not install or dismiss.
#[allow(clippy::result_large_err)]
async fn refuse_agents(state: &AppState, headers: &HeaderMap) -> Result<(), Response> {
+ refuse_agent_tokens(state, headers, "only the person can install or dismiss suggested MCP servers").await
+}
+
+/// 403 `refusal` when the request carries an agent's turn token or any bearer that isn't the API
+/// token. A request with no token at all passes, as everywhere else (auth decides that).
+#[allow(clippy::result_large_err)]
+pub(super) async fn refuse_agent_tokens(state: &AppState, headers: &HeaderMap, refusal: &str) -> Result<(), Response> {
let presented: Vec<&str> = headers
.get_all(header::AUTHORIZATION)
.iter()
@@ -379,7 +386,7 @@ async fn refuse_agents(state: &AppState, headers: &HeaderMap) -> Result<(), Resp
for token in presented {
let turn_token = state.self_tools.lock().await.contains_key(token) || state.mcp_sessions.lock().await.contains_key(token);
if turn_token || !state.api_token.matches(token) {
- return Err(error(StatusCode::FORBIDDEN, "only the person can install or dismiss suggested MCP servers"));
+ return Err(error(StatusCode::FORBIDDEN, refusal));
}
}
Ok(())
diff --git a/src/server/mod.rs b/src/server/mod.rs
index d43d3bd5..39068fb7 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -21,6 +21,7 @@ pub mod spaces;
pub mod away;
pub mod computer;
pub mod mcp_suggest;
+pub mod bot_actions;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -192,6 +193,10 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/mcp/suggestions", get(mcp_suggest::list))
.route("/api/mcp/suggestions/:id/install", post(mcp_suggest::install))
.route("/api/mcp/suggestions/:id/dismiss", post(mcp_suggest::dismiss))
+ .route("/api/bot-actions", get(bot_actions::list))
+ .route("/api/bot-actions/:id/undo", post(bot_actions::undo))
+ .route("/api/bot-actions/:id/confirm", post(bot_actions::confirm))
+ .route("/api/bot-actions/:id/decline", post(bot_actions::decline))
.route("/api/channels/:id", get(continuity::get_channel).patch(continuity::patch_channel))
.route("/api/search", get(continuity::search))
.route("/api/kwants/:id/memories", get(continuity::list_memories).post(continuity::add_memory))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 2b7977bf..9b507a18 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2257,6 +2257,8 @@ pub struct SettingsResponse {
/// Whether turns get the agents' own tools (history search, memory); see
/// [`super::continuity::agent_tools_enabled`].
pub agent_tools: bool,
+ /// The person's IANA time zone, "" when not set; routines agents create default to it.
+ pub timezone: String,
}
/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of
@@ -2276,6 +2278,8 @@ pub struct SaveSettingsPayload {
pub delegation_follow_up_minutes: Option<i64>,
/// Stored as the `agent_tools` setting: "on" or "off".
pub agent_tools: Option<bool>,
+ /// An IANA name such as "Europe/Berlin"; "" clears it.
+ pub timezone: Option<String>,
}
pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
@@ -2306,6 +2310,7 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings
max_turns_global: state.turns.limiter.limits().1,
delegation_follow_up_minutes: super::delegation::follow_up_minutes(&state).await,
agent_tools: super::continuity::agent_tools_enabled(&state).await,
+ timezone: state.db.get_setting(super::bot_actions::TIMEZONE_SETTING).await.ok().flatten().unwrap_or_default(),
}))
}
@@ -2340,6 +2345,13 @@ pub async fn save_settings(
if payload.delegation_follow_up_minutes.is_some_and(|m| !(0..=max_minutes).contains(&m)) {
return bad(format!("delegation_follow_up_minutes must be 0–{max_minutes}"));
}
+ let timezone = payload.timezone.as_deref().map(crate::routines::canonical_tz);
+ if let Some(tz) = timezone.as_deref().filter(|t| !t.is_empty()) {
+ let probe = crate::routines::Schedule::Daily { time: "09:00".into(), tz: tz.to_string() };
+ if let Err(e) = probe.validate() {
+ return bad(e);
+ }
+ }
if let Err(e) =
super::continuity::save_notify_settings(&state, payload.notify_webhook_url, payload.notify_on).await
{
@@ -2391,6 +2403,9 @@ pub async fn save_settings(
if let Some(on) = payload.agent_tools {
let _ = state.db.set_setting("agent_tools", if on { "on" } else { "off" }).await;
}
+ if let Some(tz) = timezone {
+ let _ = state.db.set_setting(super::bot_actions::TIMEZONE_SETTING, &tz).await;
+ }
Ok(Json(json!({ "status": "saved" })))
}
diff --git a/src/server/sse.rs b/src/server/sse.rs
index a4ff8e30..41bc9275 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -85,6 +85,11 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {
out.extend(fields(suggestion, &["kwant_id", "channel_id", "direct_kwant_id", "thread_id"], Owner::Context));
out
}
+ E::BotActionUpdated { action } => {
+ let mut out = fields(action, &["space_id"], Owner::Space);
+ out.extend(fields(action, &["kwant_id", "channel_id", "direct_kwant_id", "thread_id"], Owner::Context));
+ out
+ }
E::ProfileSwitched { kwant_id, .. } | E::MemoryChanged { kwant_id } => contexts([&Some(kwant_id.clone())]),
E::DiscussionStarted { team_id, .. }
| E::BrowserNavigated { team_id, .. }
@@ -208,6 +213,7 @@ mod tests {
E::SkillUpdated { skill: json!({"id": "s", "kwant_id": null, "deleted": true}) },
E::QuestionUpdated { question: json!({"id": "q", "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::Scoped {
tag: TurnTag { turn_id: s("x"), kwant_id: s("k"), context_id: s("c"), thread_id: None },
event: Box::new(E::TextDelta(s("x"))),
@@ -282,6 +288,7 @@ mod tests {
| E::SkillUpdated { .. }
| E::QuestionUpdated { .. }
| E::McpSuggestionUpdated { .. }
+ | E::BotActionUpdated { .. }
| E::Scoped { .. }
| E::ProfileSwitched { .. }
| E::DiscussionStarted { .. }
diff --git a/tests/bot_actions_test.rs b/tests/bot_actions_test.rs
new file mode 100644
index 00000000..9f1341f7
--- /dev/null
+++ b/tests/bot_actions_test.rs
@@ -0,0 +1,487 @@
+//! Agents changing the app from a chat through their own tools: routines, bots, settings, their
+//! space and channels, each change shown as a card the person can undo; and everything that stays
+//! with the person (secrets, sign-ins, approvals, MCP installs, the computer, other spaces).
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{
+ models::{Channel, Kwant, Message},
+ spaces::SpaceId,
+ Database,
+ },
+ mcp::{self, McpServerInput},
+ router::LayaRouter,
+ server::{
+ continuity::{SelfScope, TurnOrigin},
+ create_router, mcp_runtime, AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+struct Env {
+ app: Router,
+ state: AppState,
+ bot: Kwant,
+ other: Kwant,
+ general: Channel,
+ _tmp: TempDir,
+}
+
+async fn setup() -> Env {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let space = SpaceId::default_space();
+ let kwants = state.db.list_kwants(&space).await.unwrap();
+ let general = state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap();
+ Env { app: create_router(state.clone()), bot: kwants[0].clone(), other: kwants[1].clone(), general, state, _tmp: tmp }
+}
+
+async fn call(app: &Router, method: &str, uri: &str, auth: Option<&str>, body: Option<Value>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ if let Some(token) = auth {
+ req = req.header("authorization", format!("Bearer {token}"));
+ }
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+fn rpc(method: &str, params: Value) -> Value {
+ json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
+}
+
+async fn tool(e: &Env, token: &str, name: &str, args: Value) -> (String, bool) {
+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc("tools/call", json!({"name": name, "arguments": args})))).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ (
+ v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(),
+ v["result"]["isError"].as_bool().unwrap_or(false),
+ )
+}
+
+async fn ok(e: &Env, token: &str, name: &str, args: Value) -> String {
+ let (text, err) = tool(e, token, name, args.clone()).await;
+ assert!(!err, "{name} {args} failed: {text}");
+ text
+}
+
+async fn refused(e: &Env, token: &str, name: &str, args: Value) -> String {
+ let (text, err) = tool(e, token, name, args.clone()).await;
+ assert!(err, "{name} {args} should be refused: {text}");
+ text
+}
+
+/// A turn of `bot` in #general with its own tools; returns the turn token.
+async fn turn_in(e: &Env, bot: &Kwant, origin: TurnOrigin, turn_id: &str) -> String {
+ let scope = SelfScope {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ origin: Some(origin),
+ turn_id: Some(turn_id.into()),
+ ..Default::default()
+ };
+ mcp_runtime::prepare_turn_with_self(&e.state, bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1
+}
+
+async fn turn(e: &Env, turn_id: &str) -> String {
+ let origin = TurnOrigin { channel_id: Some(e.general.id.clone()), ..Default::default() };
+ turn_in(e, &e.bot, origin, turn_id).await
+}
+
+async fn actions(e: &Env) -> Vec<Value> {
+ let (status, v) = call(&e.app, "GET", "/api/bot-actions", None, None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ v.as_array().unwrap().clone()
+}
+
+async fn last_action(e: &Env) -> Value {
+ actions(e).await.into_iter().next().expect("an action")
+}
+
+async fn messages(e: &Env, chat: &str) -> Vec<Message> {
+ e.state.db.list_messages(chat, 200).await.unwrap()
+}
+
+fn meta(m: &Message) -> Value {
+ m.meta.as_deref().map(|s| serde_json::from_str(s).unwrap()).unwrap_or(Value::Null)
+}
+
+async fn routines(e: &Env) -> Vec<Value> {
+ let (_, v) = call(&e.app, "GET", "/api/routines", None, None).await;
+ v.as_array().unwrap().clone()
+}
+
+async fn set_timezone(e: &Env, tz: &str) {
+ let (status, v) = call(&e.app, "POST", "/api/settings", None, Some(json!({"timezone": tz}))).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+}
+
+#[tokio::test]
+async fn routine_is_created_in_this_chat_as_this_bot_with_a_card_and_managed_through_tools() {
+ let e = setup().await;
+ let token = turn(&e, "t-routine").await;
+
+ // No time zone known yet: the agent is told to pass one or ask, and nothing is created
+ let text = refused(&e, &token, "routine_create", json!({"name": "Morning motivation", "instructions": "Send me motivation",
+ "schedule": {"type": "daily", "time": "07:00"}})).await;
+ assert!(text.contains("time zone"), "{text}");
+ assert!(routines(&e).await.is_empty());
+
+ set_timezone(&e, "Europe/Berlin").await;
+ let text = ok(&e, &token, "routine_create", json!({"name": "Morning motivation",
+ "instructions": "Send the person a short, upbeat motivation message for the day.",
+ "schedule": {"type": "daily", "time": "07:00"}})).await;
+ assert!(text.contains("daily 07:00 Europe/Berlin") && text.contains("#general"), "{text}");
+ let list = routines(&e).await;
+ assert_eq!(list.len(), 1);
+ let r = &list[0];
+ assert_eq!(r["kwant_id"], e.bot.id.as_str());
+ assert_eq!(r["channel_id"], e.general.id.as_str(), "delivers into the chat it was made in");
+ assert_eq!(r["schedule"]["tz"], "Europe/Berlin");
+ assert_eq!(r["enabled"], true);
+ let routine_id = r["id"].as_str().unwrap().to_string();
+
+ // The card: a message from the bot in this chat, with what Undo/Edit/Pause need
+ let a = last_action(&e).await;
+ assert_eq!((a["action"].as_str(), a["status"].as_str(), a["turn_id"].as_str()), (Some("routine_create"), Some("applied"), Some("t-routine")));
+ assert_eq!(a["kwant_id"], e.bot.id.as_str());
+ let card = messages(&e, &e.general.id).await.into_iter().find(|m| Some(m.id.as_str()) == a["message_id"].as_str()).expect("card");
+ assert_eq!((card.sender_role.as_str(), card.sender_id.as_str()), ("kwant", e.bot.name.as_str()));
+ assert!(card.text.contains("Morning motivation") && card.text.contains("daily 07:00 Europe/Berlin"), "{}", card.text);
+ let m = meta(&card);
+ assert_eq!(m["kind"], "bot_action");
+ assert_eq!(m["action_id"], a["id"]);
+ assert_eq!(m["target_kind"], "routine");
+ assert_eq!(m["target_id"], routine_id.as_str());
+ assert_eq!(m["can_undo"], true);
+ assert_eq!(m["needs_confirmation"], false);
+ assert_eq!(m["details"]["schedule_text"], "daily 07:00 Europe/Berlin");
+ assert_eq!(m["details"]["bot_name"], e.bot.name.as_str());
+
+ // List, update, pause, resume, by name
+ let text = ok(&e, &token, "routine_list", json!({})).await;
+ assert!(text.contains("Morning motivation") && text.contains("daily 07:00 Europe/Berlin"), "{text}");
+ let text = ok(&e, &token, "routine_update", json!({"routine": "Morning motivation", "schedule": {"type": "weekly", "time": "08:15",
+ "weekdays": ["mon", "fri"], "tz": "America/New_York"}})).await;
+ assert!(text.contains("weekly on mon, fri at 08:15 America/New_York"), "{text}");
+ ok(&e, &token, "routine_pause", json!({"routine": routine_id})).await;
+ assert_eq!(routines(&e).await[0]["enabled"], false);
+ ok(&e, &token, "routine_resume", json!({"routine": routine_id})).await;
+ assert_eq!(routines(&e).await[0]["enabled"], true);
+
+ // Run now: the routine's message lands in #general (the bot's reply needs an engine)
+ let text = ok(&e, &token, "routine_run_now", json!({"routine": "Morning motivation"})).await;
+ assert!(text.contains("#general"), "{text}");
+ let mut posted = false;
+ for _ in 0..50 {
+ if messages(&e, &e.general.id).await.iter().any(|m| m.sender_id == "Routine: Morning motivation") {
+ posted = true;
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ }
+ assert!(posted, "run_now posts the routine into its chat");
+ assert_eq!(last_action(&e).await["card"]["can_undo"], false, "a run can't be undone");
+
+ // Delete, then the person undoes it: the routine comes back
+ ok(&e, &token, "routine_delete", json!({"routine": routine_id})).await;
+ assert!(routines(&e).await.is_empty());
+ let del = last_action(&e).await;
+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", del["id"].as_str().unwrap()), None, None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(v["status"], "undone");
+ assert_eq!(v["card"]["status"], "undone");
+ let back = routines(&e).await;
+ assert_eq!(back.len(), 1);
+ assert_eq!(back[0]["name"], "Morning motivation");
+ assert_eq!(back[0]["channel_id"], e.general.id.as_str());
+ assert_eq!(v["target_id"], back[0]["id"], "the action now points at the recreated routine");
+ let card = messages(&e, &e.general.id).await.into_iter().find(|m| Some(m.id.as_str()) == del["message_id"].as_str()).unwrap();
+ assert_eq!(meta(&card)["status"], "undone", "the card follows");
+
+ // Undoing the create removes it
+ let create = actions(&e).await.into_iter().find(|a| a["action"] == "routine_create").unwrap();
+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), None, None).await;
+ // The routine it made was deleted and recreated, so that row is gone: a conflict, not a crash
+ assert_eq!(status, StatusCode::CONFLICT, "{v}");
+}
+
+#[tokio::test]
+async fn schedule_and_input_errors_are_tool_errors_and_create_nothing() {
+ let e = setup().await;
+ let token = turn(&e, "t-bad").await;
+ let make = |schedule: Value| json!({"name": "R", "instructions": "do it", "schedule": schedule});
+ for (schedule, needle) in [
+ (json!({"type": "daily", "time": "07:00", "tz": "Mars/Base"}), "time zone"),
+ (json!({"type": "daily", "time": "25:00", "tz": "UTC"}), "time"),
+ (json!({"type": "weekly", "time": "07:00", "weekdays": [], "tz": "UTC"}), "day"),
+ (json!({"type": "interval", "every_minutes": 1}), "minutes"),
+ (json!({"type": "once", "at": "2001-01-01T07:00:00Z"}), "future"),
+ (json!({"type": "hourly"}), "not valid"),
+ (json!("every morning"), "object"),
+ ] {
+ let text = refused(&e, &token, "routine_create", make(schedule.clone())).await;
+ assert!(text.to_lowercase().contains(needle), "{schedule}: {text}");
+ }
+ let text = refused(&e, &token, "routine_create", json!({"name": "", "instructions": "x", "schedule": {"type": "interval", "every_minutes": 60}})).await;
+ assert!(text.contains("name"), "{text}");
+ let text = refused(&e, &token, "routine_create", json!({"name": "R", "instructions": "x", "schedule": {"type": "interval", "every_minutes": 60}, "bot": "Nobody"})).await;
+ assert!(text.contains("no bot"), "{text}");
+ let text = refused(&e, &token, "routine_create", json!({"name": "R", "instructions": "x", "schedule": {"type": "interval", "every_minutes": 60}, "channel": "nope"})).await;
+ assert!(text.contains("no channel"), "{text}");
+ refused(&e, &token, "routine_pause", json!({"routine": "missing"})).await;
+ assert!(routines(&e).await.is_empty());
+ assert!(actions(&e).await.is_empty());
+
+ // Another bot and its direct chat can be the target
+ let text = ok(&e, &token, "routine_create", json!({"name": "R", "instructions": "x", "schedule": {"type": "interval", "every_minutes": 60},
+ "bot": e.other.name, "channel": "direct"})).await;
+ assert!(text.contains(&format!("direct chat with {}", e.other.name)), "{text}");
+ let r = &routines(&e).await[0];
+ assert_eq!((r["kwant_id"].as_str(), r["channel_id"].as_str()), (Some(e.other.id.as_str()), None));
+}
+
+#[tokio::test]
+async fn bots_are_created_and_updated_and_the_person_undoes_it() {
+ let e = setup().await;
+ let origin = TurnOrigin { direct_kwant_id: Some(e.bot.id.clone()), ..Default::default() };
+ let token = turn_in(&e, &e.bot, origin, "t-bots").await;
+
+ refused(&e, &token, "bot_create", json!({"name": "Two words", "title": "x", "instructions": "x"})).await;
+ let text = refused(&e, &token, "bot_create", json!({"name": "Chef", "title": "x", "instructions": "x", "model": "nonsense-model"})).await;
+ assert!(text.contains("Unknown model"), "{text}");
+ let text = refused(&e, &token, "bot_create", json!({"name": e.other.name, "title": "x", "instructions": "x"})).await;
+ assert!(text.contains("not created"), "{text}");
+
+ let text = ok(&e, &token, "bot_create", json!({"name": "Chef", "title": "Recipe helper",
+ "instructions": "You suggest recipes from what is in the fridge.", "model": "claude", "avatar": "chef"})).await;
+ assert!(text.contains("Created bot Chef"), "{text}");
+ let chef = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap().into_iter().find(|k| k.name == "Chef").expect("Chef");
+ assert_eq!((chef.title.as_str(), chef.persona_prompt.as_str(), chef.preferred_model.as_str()),
+ ("Recipe helper", "You suggest recipes from what is in the fridge.", "claude"));
+ let create = last_action(&e).await;
+ assert_eq!(create["target_id"], chef.id.as_str());
+ // Its card is in the direct chat where it was asked
+ let card = messages(&e, &e.bot.id).await.into_iter().find(|m| Some(m.id.as_str()) == create["message_id"].as_str()).expect("card");
+ assert!(card.text.contains("created bot Chef") || card.text.contains("Created bot Chef"), "{}", card.text);
+
+ // Update: fields and exactly which installed tool servers it has
+ let input: McpServerInput = serde_json::from_value(json!({"name": "notes", "transport": "http", "url": "http://127.0.0.1:9/mcp"})).unwrap();
+ let server = e.state.db.create_mcp_server(&SpaceId::default_space(), &mcp::build_server(input, None).unwrap()).await.unwrap();
+ let text = refused(&e, &token, "bot_update", json!({"bot": "Chef", "mcp_servers": ["github"]})).await;
+ assert!(text.contains("mcp_suggest"), "{text}");
+ let text = ok(&e, &token, "bot_update", json!({"bot": "Chef", "title": "Head chef", "mcp_servers": []})).await;
+ assert!(text.contains("title") && text.contains("mcp_server_ids"), "{text}");
+ let chef_now = e.state.db.get_kwant(&chef.id).await.unwrap().unwrap();
+ assert_eq!(chef_now.title, "Head chef");
+ assert!(e.state.db.get_kwant_mcp_server_ids(&chef.id).await.unwrap().is_empty());
+ let update = last_action(&e).await;
+
+ // Undoing the create while a newer change is applied: 409, undo that first
+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), None, None).await;
+ assert_eq!(status, StatusCode::CONFLICT, "{v}");
+ assert!(v["error"].as_str().unwrap().contains("newer"), "{v}");
+
+ // A bot's or turn's token can't undo; the person can
+ for bearer in [token.as_str(), "made-up-token"] {
+ let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", update["id"].as_str().unwrap()), Some(bearer), None).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ }
+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", update["id"].as_str().unwrap()), None, None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ let chef_back = e.state.db.get_kwant(&chef.id).await.unwrap().unwrap();
+ assert_eq!(chef_back.title, "Recipe helper");
+ assert_eq!(e.state.db.get_kwant_mcp_server_ids(&chef.id).await.unwrap(), vec![server.id.clone()]);
+
+ let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), Some(&token), None).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), None, None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert!(e.state.db.get_kwant(&chef.id).await.unwrap().is_none(), "undo removed Chef");
+ // Twice is a conflict
+ let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", create["id"].as_str().unwrap()), None, None).await;
+ assert_eq!(status, StatusCode::CONFLICT);
+}
+
+#[tokio::test]
+async fn deleting_a_bot_waits_for_the_person() {
+ let e = setup().await;
+ let token = turn(&e, "t-del").await;
+ ok(&e, &token, "bot_create", json!({"name": "Temp", "title": "t", "instructions": "t"})).await;
+ let temp = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap().into_iter().find(|k| k.name == "Temp").unwrap();
+ let text = ok(&e, &token, "bot_delete", json!({"bot": "Temp", "reason": "not needed"})).await;
+ assert!(text.contains("confirm"), "{text}");
+ assert!(e.state.db.get_kwant(&temp.id).await.unwrap().is_some(), "nothing happens before the person confirms");
+ let req = last_action(&e).await;
+ assert_eq!((req["status"].as_str(), req["card"]["needs_confirmation"].as_bool()), (Some("pending"), Some(true)));
+
+ // A bot can't confirm its own request
+ let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/confirm", req["id"].as_str().unwrap()), Some(&token), None).await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/confirm", req["id"].as_str().unwrap()), None, None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ assert_eq!(v["status"], "confirmed");
+ assert!(e.state.db.get_kwant(&temp.id).await.unwrap().is_none());
+
+ // A bot with history can't be deleted at all
+ e.state.db.insert_message(&kwnt::db::models::NewMessage {
+ channel_id: Some(e.general.id.clone()), direct_kwant_id: None, sender_role: "kwant".into(), sender_id: e.other.name.clone(),
+ text: "hello".into(), reasoning_content: None, tool_calls: None, tokens_used: 0,
+ }).await.unwrap();
+ let text = refused(&e, &token, "bot_delete", json!({"bot": e.other.name})).await;
+ assert!(text.contains("can't be deleted") || text.contains("history"), "{text}");
+
+ // Archiving the space: declined, nothing changes
+ let text = refused(&e, &token, "space_archive", json!({})).await;
+ assert!(text.contains("Default"), "{text}");
+}
+
+#[tokio::test]
+async fn non_secret_settings_change_and_undo() {
+ let e = setup().await;
+ let token = turn(&e, "t-settings").await;
+ let text = ok(&e, &token, "settings_get", json!({})).await;
+ assert!(text.contains("max_turns_per_agent") && !text.contains("api_key"), "{text}");
+ let text = ok(&e, &token, "settings_update", json!({"settings": {"max_turns_per_agent": 5, "timezone": "Europe/Kiev"}})).await;
+ assert!(text.contains("max_turns_per_agent = 5") && text.contains("Europe/Kyiv"), "{text}");
+ let (_, s) = call(&e.app, "GET", "/api/settings", None, None).await;
+ assert_eq!((s["max_turns_per_agent"].as_u64(), s["timezone"].as_str()), (Some(5), Some("Europe/Kyiv")));
+
+ let text = refused(&e, &token, "settings_update", json!({"settings": {"timezone": "Nowhere/City"}})).await;
+ assert!(text.contains("time zone"), "{text}");
+ let text = refused(&e, &token, "settings_update", json!({"settings": {"max_turns_global": 0}})).await;
+ assert!(text.contains("max_turns_global"), "{text}");
+
+ let a = last_action(&e).await;
+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", a["id"].as_str().unwrap()), None, None).await;
+ assert_eq!(status, StatusCode::OK, "{v}");
+ let (_, s) = call(&e.app, "GET", "/api/settings", None, None).await;
+ assert_eq!(s["timezone"], "", "undo clears the time zone it set");
+ assert_eq!(s["max_turns_per_agent"].as_u64(), Some(3), "back to the default");
+}
+
+#[tokio::test]
+async fn what_stays_with_the_person_is_refused_with_where_to_do_it() {
+ let e = setup().await;
+ let token = turn(&e, "t-refuse").await;
+ let (_, before) = call(&e.app, "GET", "/api/settings", None, None).await;
+ for (key, value, place) in [
+ ("anthropic_api_key", json!("sk-ant-xyz"), "Accounts"),
+ ("notify_webhook_url", json!("https://ntfy.sh/x"), "Notifications"),
+ ("ollama_url", json!("http://evil:11434"), "Accounts"),
+ ("engine_login", json!("claude"), "sign in"),
+ ("auth_mode", json!("none"), "sign in to kwnt"),
+ ("auto_approve", json!(true), "answer the card"),
+ ("computer_mode", json!("local"), "Computer for browsing and commands"),
+ ("agent_tools", json!(false), "Only the person"),
+ ("mcp_servers", json!([]), "mcp_suggest"),
+ ] {
+ let text = refused(&e, &token, "settings_update", json!({"settings": {key: value}})).await;
+ assert!(text.contains(place), "{key}: {text}");
+ assert!(text.contains("Nothing was changed"), "{key}: {text}");
+ }
+ // A refused key in a batch blocks the allowed one too
+ refused(&e, &token, "settings_update", json!({"settings": {"max_turns_global": 2, "xai_api_key": "k"}})).await;
+ let (_, after) = call(&e.app, "GET", "/api/settings", None, None).await;
+ assert_eq!(before, after);
+ assert!(!after.to_string().contains("sk-ant-xyz"));
+
+ // MCP env/header values and keys can't ride along on a bot
+ let text = refused(&e, &token, "bot_update", json!({"bot": e.bot.name, "env": {"GITHUB_TOKEN": "x"}})).await;
+ assert!(text.contains("Tools") && text.contains("mcp_suggest"), "{text}");
+ let text = refused(&e, &token, "bot_create", json!({"name": "Spy", "title": "x", "instructions": "x", "api_key": "k"})).await;
+ assert!(text.contains("secret"), "{text}");
+
+ // No tool resolves approvals, answers questions, installs MCP, signs in or picks the computer
+ for name in ["approval_resolve", "question_answer", "mcp_install", "engine_login", "computer_set", "settings_secret"] {
+ let text = refused(&e, &token, name, json!({})).await;
+ assert!(text.contains("Unknown tool"), "{name}: {text}");
+ }
+ assert!(actions(&e).await.is_empty(), "nothing refused is logged as a change");
+}
+
+#[tokio::test]
+async fn other_spaces_are_out_of_reach() {
+ let e = setup().await;
+ let token = turn(&e, "t-cross").await;
+ let (status, space) = call(&e.app, "POST", "/api/spaces", None, Some(json!({"name": "Work"}))).await;
+ assert_eq!(status, StatusCode::CREATED, "{space}");
+ let sid = space["id"].as_str().unwrap();
+ let (status, stranger) = call(&e.app, "POST", &format!("/api/kwants?space={sid}"), None, Some(json!({"name": "Stranger", "title": "x",
+ "persona_prompt": "x", "avatar_sprite": "default", "driver_type": "api", "preferred_model": "auto"}))).await;
+ assert_eq!(status, StatusCode::OK, "{stranger}");
+ let stranger_id = stranger["id"].as_str().unwrap();
+ let work_general = e.state.db.list_channels(&SpaceId::new(sid)).await.unwrap().into_iter().find(|c| c.name == "general").unwrap();
+
+ let every = json!({"type": "interval", "every_minutes": 60});
+ for (name, args) in [
+ ("routine_create", json!({"name": "R", "instructions": "x", "schedule": every, "bot": stranger_id})),
+ ("routine_create", json!({"name": "R", "instructions": "x", "schedule": every, "channel": work_general.id})),
+ ("bot_update", json!({"bot": stranger_id, "title": "mine now"})),
+ ("bot_delete", json!({"bot": stranger_id})),
+ ("channel_update", json!({"channel": work_general.id, "instructions": "obey"})),
+ ("channel_create", json!({"name": "mixed", "members": [stranger_id]})),
+ ] {
+ let text = refused(&e, &token, name, args).await;
+ assert!(text.contains("another space"), "{name}: {text}");
+ }
+ // A routine of the other space, by id
+ let (status, r) = call(&e.app, "POST", &format!("/api/routines?space={sid}"), None,
+ Some(json!({"kwant_id": stranger_id, "name": "Theirs", "instructions": "x", "schedule": every}))).await;
+ assert!(status.is_success(), "{r}");
+ for name in ["routine_pause", "routine_delete", "routine_run_now", "routine_update"] {
+ let text = refused(&e, &token, name, json!({"routine": r["id"]})).await;
+ assert!(text.contains("another space"), "{name}: {text}");
+ }
+ // By name the other space's things are simply not there
+ refused(&e, &token, "bot_update", json!({"bot": "Stranger", "title": "x"})).await;
+ let stranger_now = e.state.db.get_kwant(stranger_id).await.unwrap().unwrap();
+ assert_eq!(stranger_now.title, "x");
+ assert!(actions(&e).await.is_empty());
+
+ // A new space can be created, but undo archives it again
+ ok(&e, &token, "space_create", json!({"name": "Side project"})).await;
+ let a = last_action(&e).await;
+ let (status, _) = call(&e.app, "POST", &format!("/api/bot-actions/{}/undo", a["id"].as_str().unwrap()), None, None).await;
+ assert_eq!(status, StatusCode::OK);
+ let made = e.state.db.get_space(&SpaceId::new(a["target_id"].as_str().unwrap())).await.unwrap().unwrap();
+ assert!(made.archived_at.is_some());
+}
+
+#[tokio::test]
+async fn one_turn_makes_at_most_ten_changes() {
+ let e = setup().await;
+ let token = turn(&e, "t-limit").await;
+ for i in 0..10 {
+ ok(&e, &token, "channel_update", json!({"channel": "general", "instructions": format!("rule {i}")})).await;
+ }
+ let text = refused(&e, &token, "channel_update", json!({"channel": "general", "instructions": "rule 11"})).await;
+ assert!(text.contains("10 changes"), "{text}");
+ assert_eq!(e.state.db.channel_instructions(&e.general.id).await.unwrap().as_deref(), Some("rule 9"));
+ // Reading is still fine, and the next turn may change things again
+ ok(&e, &token, "routine_list", json!({})).await;
+ let next = turn(&e, "t-limit-2").await;
+ ok(&e, &next, "channel_update", json!({"channel": "general", "instructions": ""})).await;
+ assert_eq!(actions(&e).await.len(), 11);
+ let cards = messages(&e, &e.general.id).await.into_iter().filter(|m| meta(m)["kind"] == "bot_action").count();
+ assert_eq!(cards, 11);
+}
diff --git a/tests/continuity_test.rs b/tests/continuity_test.rs
index 5786b2ef..b3ecd7b2 100644
--- a/tests/continuity_test.rs
+++ b/tests/continuity_test.rs
@@ -762,7 +762,29 @@ async fn self_tools_are_scoped_to_the_turn_and_kwant() {
"skill_propose",
"skill_get",
"mcp_search",
- "mcp_suggest"
+ "mcp_suggest",
+ "routine_list",
+ "routine_create",
+ "routine_update",
+ "routine_pause",
+ "routine_resume",
+ "routine_run_now",
+ "routine_delete",
+ "bot_list",
+ "bot_create",
+ "bot_update",
+ "bot_delete",
+ "settings_get",
+ "settings_update",
+ "space_get",
+ "space_list",
+ "space_create",
+ "space_update",
+ "space_archive",
+ "channel_list",
+ "channel_create",
+ "channel_update",
+ "profile_delete",
]
);
diff --git a/tests/spaces_migration_test.rs b/tests/spaces_migration_test.rs
index 885f8911..9f2ba74e 100644
--- a/tests/spaces_migration_test.rs
+++ b/tests/spaces_migration_test.rs
@@ -66,7 +66,7 @@ async fn legacy(dir: &Path) -> SqlitePool {
/// from the Custom API change), without `space_id`, as quoted text.
async fn snapshot(pool: &SqlitePool) -> BTreeMap<String, Vec<String>> {
let tables: Vec<(String,)> = sqlx::query_as(
- "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT IN ('spaces', 'llm_profile_endpoints', 'mcp_suggestions') ORDER BY name",
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT IN ('spaces', 'llm_profile_endpoints', 'mcp_suggestions', 'bot_actions') ORDER BY name",
)
.fetch_all(pool)
.await