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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Bots propose hiring a new bot; the person decides (deny / accept once / always accept)
Lin (kwant bot)61d5489531c4
diff --git a/docs/bot-actions.md b/docs/bot-actions.mdindex 86b76430..f197a23b 100644--- a/docs/bot-actions.md+++ b/docs/bot-actions.md@@ -115,3 +115,78 @@ Suggested buttons:- `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).++## Hiring++A bot does every request itself first, including suggesting a missing tool server with `mcp_suggest`. It may propose hiring a new bot only when:+- a specialist with its own instructions, tools, schedule or model would clearly do this kind of work better; or+- similar requests from the person have come up at least 3 times in this space.++The bot then carries on with the request itself. A proposal creates nothing on its own.++### Tools++- `propose_hire {name, role, instructions, model?, tools?, team?, reason, evidence, requested_by_person?}` records a pending proposal tied to the bot, turn and space, and posts a card in the turn's chat.+ - `evidence` is required and is checked by the server:+ - `{basis: "specialist", needs: [some of "instructions","tools","schedule","model"], gap: "<at least 20 chars>"}`; or+ - `{basis: "repeated", similar_requests: [message ids]}`, with at least 3 distinct messages from the person (`sender_role` user) in this space.+ - `tools` must be tool servers already installed in the space. `team` must be in the space; it defaults to the proposer's team.+ - `model` follows `bot_create`'s rules.+ - Refused:+ - more than 1 proposal per turn;+ - keys or accounts (`env`, `headers`, `api_key`, `password`, `token`, `mcp_env`, `profile_id`);+ - a name already used in the space;+ - a bot whose title is already a similar role;+ - a similar proposal already pending;+ - a role similar to one the person denied in this space (unless `requested_by_person`, which still always asks).+ - Roles are compared by their words, ignoring case, plurals and filler such as "bot" or "assistant". They are similar when more than half the words match.+- `hire_status {}` is read-only. It returns the policy, the automatic hires left, recent proposals and the denials.++### Decisions (person only; a turn token or non-API bearer gets 403)++- `POST /api/hires/:id/accept {}` (**Accept once**) creates the bot through the `bot_create` path, with title = role, its tools and no keys. It adds the bot to the team and the team's `team-<name>` channel, and logs a `bot_action` `bot_hire` that can be undone. The policy doesn't change, so the next proposal asks again.+- `POST /api/hires/:id/accept {"always": true}` (**Always accept**) does the same and sets the space's policy to `auto`. Later proposals in the space are then created at once (status `auto_accepted`) with an Undo card. The cap is 3 automatic hires per space in 24 hours; after that, proposals wait for the person again, with a `note` on the card.+- `POST /api/hires/:id/deny` creates nothing. It is remembered for the space, and the space's bots are told not to propose that kind of bot again unless the person asks.+- A proposal that was already decided returns 409.+- Undo goes through `POST /api/bot-actions/:action_id/undo`. It removes the hired bot and its team memberships while the bot has no history, and the proposal becomes `undone`.++### Routes++| Route | Who | Returns |+|---|---|---|+| `GET /api/hires?space=&status=` | anyone with the API | proposals newest first (≤200), each a `Hire` plus `card` |+| `POST /api/hires/:id/accept {always?}` | person | the `Hire` plus `card`; 409 when not pending or creation failed |+| `POST /api/hires/:id/deny` | person | the `Hire` plus `card`; 409 when not pending |+| `GET /api/spaces/:id/hire-policy` | anyone with the API (bots read it through `hire_status`) | `{space_id, policy: "ask"\|"auto", auto_hires_last_24h, auto_hires_per_day: 3, denied: [{hire_id,name,role,denied_at}], denials_cleared_at, updated_at}`; 404 for an unknown space |+| `PUT /api/spaces/:id/hire-policy {policy?, clear_denials?}` | person | same as GET; 400 for another policy value. `clear_denials: true` forgets the denials made so far |++`Hire` fields: `id, space_id, kwant_id` (the proposer), `turn_id, channel_id, direct_kwant_id, thread_id, name, role, role_key, instructions, model, tools` (server ids), `team_id, reason, evidence, requested_by_person, auto, status` (`pending|accepted|auto_accepted|denied|undone`), `hired_kwant_id, action_id, message_id, created_at, resolved_at`.++### The card++A message from the proposing bot carries `meta`:++```+{kind: "hire_proposal", hire_id, kwant_id, proposer_name, name, role, instructions, model,+ tools: [{id, name}], team: {id, name} | null, reason, evidence, requested_by_person,+ status, auto, choices: ["deny","accept_once","always_accept"] (pending only, else []),+ hired_kwant_id, action_id, can_undo, policy, note, created_at, resolved_at}+```++- Buttons:+ - **Deny** → `/deny`.+ - **Accept once** → `/accept {}`.+ - **Always accept** → `/accept {"always": true}`.+ - **Undo** when `can_undo` → `/api/bot-actions/{action_id}/undo`.+- The message text also changes with the status ("Wants to hire…", "Hired…", "Not hired…", "Hire undone…"), so bots reading the history see the decision.+- Each change sends SSE `hire_updated { hire }` (the `Hire` plus `card`), routed like `bot_action_updated`. A new card also sends `message_added`.++### What bots see++While a bot has its own tools, every turn includes a `[Hiring new bots in this space]` block. It contains:+- the bot-first rule;+- the policy, and the automatic hires left;+- up to 8 recent proposals with their status;+- every denial still in force.++Each space sees only its own block.diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rsindex 2b6fa416..9c788438 100644--- a/src/db/bot_actions.rs+++ b/src/db/bot_actions.rs@@ -234,7 +234,7 @@ impl Database {/// 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] = [+ let checks: [(&str, &'static str); 11] = [("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"),(@@ -249,6 +249,7 @@ impl Database {("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"),+ ("SELECT COUNT(*) FROM hire_proposals WHERE kwant_id = ?1", "it already proposed hiring bots"),];for (sql, why) in checks {let (n,): (i64,) = sqlx::query_as(sql).bind(id).fetch_one(&self.pool).await?;diff --git a/src/db/hires.rs b/src/db/hires.rsnew file mode 100644index 00000000..3a9a46ad--- /dev/null+++ b/src/db/hires.rs@@ -0,0 +1,409 @@+//! Bots proposing to hire a new bot (`propose_hire`), and how the person decides: Deny, Accept+//! once or Always accept. A proposal creates nothing by itself; the person's choice, and the+//! space's hire policy, are remembered per space and shown to its bots on their next turn.++use super::models::{Message, MessageExtra, NewMessage};+use super::spaces::SpaceId;+use super::{Database, DbError};+use chrono::{DateTime, Duration, Utc};+use serde::Serialize;+use sqlx::FromRow;+use uuid::Uuid;++/// `pending` waits for the person; `accepted` (by them) and `auto_accepted` (by the space's+/// "always accept" policy) made the bot; `denied` is remembered; `undone` means the person+/// took an accepted hire back.+pub const HIRE_STATUSES: [&str; 5] = ["pending", "accepted", "auto_accepted", "denied", "undone"];++/// Proposals one turn may make.+pub const MAX_PROPOSALS_PER_TURN: i64 = 1;+/// Bots "always accept" may create in a space in 24 hours; past it, proposals ask again.+pub const AUTO_HIRES_PER_DAY: i64 = 3;++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct Hire {+ pub id: String,+ pub space_id: String,+ /// The bot that proposed it.+ 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 name: String,+ pub role: String,+ /// `role` folded to lowercase words, for "was this kind of bot turned down?".+ pub role_key: String,+ pub instructions: String,+ pub model: String,+ /// JSON list of installed tool server ids.+ #[serde(serialize_with = "as_json")]+ pub tools: String,+ pub team_id: Option<String>,+ pub reason: String,+ /// JSON: `{basis, needs?, gap?, similar_requests?}`.+ #[serde(serialize_with = "as_json")]+ pub evidence: String,+ /// The bot said the person asked for this kind of bot (lifts an earlier Deny; never auto).+ pub requested_by_person: bool,+ /// Made by the space's "always accept" policy rather than the person's click.+ pub auto: bool,+ pub status: String,+ /// The bot it made, once accepted.+ pub hired_kwant_id: Option<String>,+ /// The `bot_actions` row Undo goes through.+ pub action_id: Option<String>,+ pub message_id: Option<String>,+ pub created_at: DateTime<Utc>,+ pub resolved_at: Option<DateTime<Utc>>,+}++fn as_json<S: serde::Serializer>(raw: &str, s: S) -> Result<S::Ok, S::Error> {+ let v: serde_json::Value = serde_json::from_str(raw).unwrap_or(serde_json::Value::Null);+ v.serialize(s)+}++impl Hire {+ pub fn tools_json(&self) -> Vec<String> {+ serde_json::from_str(&self.tools).unwrap_or_default()+ }+ pub fn evidence_json(&self) -> serde_json::Value {+ serde_json::from_str(&self.evidence).unwrap_or(serde_json::Value::Null)+ }+}++#[derive(Debug, Clone, Default)]+pub struct NewHire {+ 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 name: String,+ pub role: String,+ pub instructions: String,+ pub model: String,+ pub tools: Vec<String>,+ pub team_id: Option<String>,+ pub reason: String,+ pub evidence: serde_json::Value,+ pub requested_by_person: bool,+}++/// The space's hire policy: `ask` (default) or `auto`; denials before `denials_cleared_at` no+/// longer count.+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct HirePolicy {+ pub space_id: String,+ pub policy: String,+ pub denials_cleared_at: Option<DateTime<Utc>>,+ pub updated_at: Option<DateTime<Utc>>,+}++/// Lowercase words of a role, without filler, sorted: "Recipe helper" → "helper recipe".+pub fn role_key(role: &str) -> String {+ const FILLER: [&str; 10] = ["a", "an", "the", "and", "for", "of", "bot", "assistant", "agent", "to"];+ let mut words: Vec<String> = role+ .to_lowercase()+ .split(|c: char| !c.is_alphanumeric())+ .filter(|w| !w.is_empty() && !FILLER.contains(w))+ .map(|w| w.strip_suffix('s').filter(|s| s.len() > 2).unwrap_or(w).to_string())+ .collect();+ words.sort();+ words.dedup();+ words.join(" ")+}++/// Whether two role keys name the same kind of bot: equal, or sharing at least half their words.+pub fn similar_roles(a: &str, b: &str) -> bool {+ if a.is_empty() || b.is_empty() {+ return false;+ }+ if a == b {+ return true;+ }+ let wa: Vec<&str> = a.split(' ').collect();+ let wb: Vec<&str> = b.split(' ').collect();+ let shared = wa.iter().filter(|w| wb.contains(w)).count();+ shared * 2 > wa.len().max(wb.len())+}++const GET: &str = "SELECT * FROM hire_proposals WHERE id = ?";++impl Database {+ pub(super) async fn migrate_hires(&self) -> Result<(), DbError> {+ for stmt in [+ "CREATE TABLE IF NOT EXISTS hire_proposals (+ 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,+ name TEXT NOT NULL,+ role TEXT NOT NULL,+ role_key TEXT NOT NULL,+ instructions TEXT NOT NULL,+ model TEXT NOT NULL,+ tools TEXT NOT NULL,+ team_id TEXT,+ reason TEXT NOT NULL,+ evidence TEXT NOT NULL,+ requested_by_person BOOLEAN NOT NULL DEFAULT 0,+ auto BOOLEAN NOT NULL DEFAULT 0,+ status TEXT NOT NULL CHECK (status IN ('pending', 'accepted', 'auto_accepted', 'denied', 'undone')),+ hired_kwant_id TEXT,+ action_id TEXT,+ message_id TEXT,+ created_at TIMESTAMP NOT NULL,+ resolved_at TIMESTAMP+ )",+ "CREATE INDEX IF NOT EXISTS hire_proposals_by_space ON hire_proposals (space_id, created_at)",+ "CREATE INDEX IF NOT EXISTS hire_proposals_by_turn ON hire_proposals (turn_id)",+ "CREATE TABLE IF NOT EXISTS hire_policies (+ space_id TEXT PRIMARY KEY,+ policy TEXT NOT NULL CHECK (policy IN ('ask', 'auto')),+ denials_cleared_at TIMESTAMP,+ updated_at TIMESTAMP+ )",+ ] {+ sqlx::query(stmt).execute(&self.pool).await?;+ }+ Ok(())+ }++ pub async fn get_hire(&self, id: &str) -> Result<Option<Hire>, DbError> {+ Ok(sqlx::query_as::<_, Hire>(GET).bind(id).fetch_optional(&self.pool).await?)+ }++ /// The space's proposals, newest first (max 200).+ pub async fn list_hires(&self, space: &SpaceId, status: Option<&str>) -> Result<Vec<Hire>, DbError> {+ Ok(sqlx::query_as::<_, Hire>(+ "SELECT * FROM hire_proposals WHERE space_id = ? AND (?2 IS NULL OR status = ?2) ORDER BY created_at DESC LIMIT 200",+ )+ .bind(space.as_str())+ .bind(status)+ .fetch_all(&self.pool)+ .await?)+ }++ pub async fn hires_in_turn(&self, turn_id: &str) -> Result<i64, DbError> {+ let (n,): (i64,) =+ sqlx::query_as("SELECT COUNT(*) FROM hire_proposals WHERE turn_id = ?").bind(turn_id).fetch_one(&self.pool).await?;+ Ok(n)+ }++ /// Bots the space's policy created in the last 24 hours (undone ones count too).+ pub async fn auto_hires_today(&self, space: &SpaceId) -> Result<i64, DbError> {+ let (n,): (i64,) = sqlx::query_as(+ "SELECT COUNT(*) FROM hire_proposals WHERE space_id = ? AND auto = 1 AND resolved_at > ?",+ )+ .bind(space.as_str())+ .bind(Utc::now() - Duration::hours(24))+ .fetch_one(&self.pool)+ .await?;+ Ok(n)+ }++ pub async fn hire_policy(&self, space: &SpaceId) -> Result<HirePolicy, DbError> {+ let row = sqlx::query_as::<_, HirePolicy>("SELECT * FROM hire_policies WHERE space_id = ?")+ .bind(space.as_str())+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.unwrap_or(HirePolicy { space_id: space.as_str().into(), policy: "ask".into(), denials_cleared_at: None, updated_at: None }))+ }++ /// Sets the policy; `clear_denials` makes earlier Denies stop counting.+ pub async fn set_hire_policy(&self, space: &SpaceId, policy: &str, clear_denials: bool) -> Result<HirePolicy, DbError> {+ let now = Utc::now();+ let current = self.hire_policy(space).await?;+ let cleared = if clear_denials { Some(now) } else { current.denials_cleared_at };+ sqlx::query(+ "INSERT INTO hire_policies (space_id, policy, denials_cleared_at, updated_at) VALUES (?, ?, ?, ?)+ ON CONFLICT(space_id) DO UPDATE SET policy = excluded.policy, denials_cleared_at = excluded.denials_cleared_at,+ updated_at = excluded.updated_at",+ )+ .bind(space.as_str())+ .bind(policy)+ .bind(cleared)+ .bind(now)+ .execute(&self.pool)+ .await?;+ self.hire_policy(space).await+ }++ /// Denials that still count in the space, newest first.+ pub async fn active_denials(&self, space: &SpaceId) -> Result<Vec<Hire>, DbError> {+ let policy = self.hire_policy(space).await?;+ let list = self.list_hires(space, Some("denied")).await?;+ Ok(list.into_iter().filter(|h| policy.denials_cleared_at.is_none_or(|c| h.resolved_at.is_some_and(|r| r > c))).collect())+ }++ /// Records a proposal with the card message `card` builds, in one transaction.+ pub async fn record_hire(+ &self,+ new: &NewHire,+ card: impl FnOnce(&Hire) -> Option<(NewMessage, MessageExtra)>,+ ) -> Result<(Hire, Option<Message>), DbError> {+ let mut tx = self.pool.begin().await?;+ let id = Uuid::new_v4().to_string();+ sqlx::query(+ "INSERT INTO hire_proposals (id, space_id, kwant_id, turn_id, channel_id, direct_kwant_id, thread_id, name, role, role_key,+ instructions, model, tools, team_id, reason, evidence, requested_by_person, status, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)",+ )+ .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.name)+ .bind(&new.role)+ .bind(role_key(&new.role))+ .bind(&new.instructions)+ .bind(&new.model)+ .bind(serde_json::to_string(&new.tools)?)+ .bind(&new.team_id)+ .bind(&new.reason)+ .bind(new.evidence.to_string())+ .bind(new.requested_by_person)+ .bind(Utc::now())+ .execute(&mut *tx)+ .await?;+ let hire = sqlx::query_as::<_, Hire>(GET).bind(&id).fetch_one(&mut *tx).await?;+ let mut message = None;+ if let Some((msg, extra)) = card(&hire) {+ let m = super::insert_message_on(&mut tx, &msg, &extra).await?;+ sqlx::query("UPDATE hire_proposals SET message_id = ? WHERE id = ?").bind(&m.id).bind(&id).execute(&mut *tx).await?;+ message = Some(m);+ }+ tx.commit().await?;+ let hire = self.get_hire(&id).await?.ok_or(DbError::Sqlx(sqlx::Error::RowNotFound))?;+ Ok((hire, message))+ }++ /// Moves a proposal from `from` to `to`; `false` when it wasn't in `from` any more.+ pub async fn resolve_hire(&self, id: &str, from: &str, to: &str) -> Result<bool, DbError> {+ let done = sqlx::query("UPDATE hire_proposals 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)+ }++ pub async fn set_hire_result(&self, id: &str, kwant_id: Option<&str>, action_id: Option<&str>) -> Result<(), DbError> {+ sqlx::query("UPDATE hire_proposals SET hired_kwant_id = ?, action_id = ? WHERE id = ?")+ .bind(kwant_id)+ .bind(action_id)+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Marks a proposal as decided by the space's policy, for the daily cap.+ pub async fn mark_hire_auto(&self, id: &str) -> Result<(), DbError> {+ sqlx::query("UPDATE hire_proposals SET auto = 1 WHERE id = ?")+ .bind(id)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// The space a message belongs to (through its channel, direct chat or thread) and who sent it.+ /// When a message was posted.+ pub async fn message_created_at(&self, id: &str) -> Result<Option<DateTime<Utc>>, DbError> {+ Ok(sqlx::query_scalar("SELECT created_at FROM messages WHERE id = ?").bind(id).fetch_optional(&self.pool).await?)+ }++ /// Replaces a card message's text, so bots reading the history see the decision too.+ pub async fn set_message_text(&self, id: &str, text: &str) -> Result<(), DbError> {+ sqlx::query("UPDATE messages SET text = ? WHERE id = ?").bind(text).bind(id).execute(&self.pool).await?;+ Ok(())+ }++ pub async fn message_space_and_sender(&self, id: &str) -> Result<Option<(SpaceId, String)>, DbError> {+ type Row = (Option<String>, Option<String>, Option<String>, String);+ let row: Option<Row> =+ sqlx::query_as("SELECT channel_id, direct_kwant_id, thread_id, sender_role FROM messages WHERE id = ?")+ .bind(id)+ .fetch_optional(&self.pool)+ .await?;+ let Some((channel, direct, thread, role)) = row else {+ return Ok(None);+ };+ let space = if let Some(c) = channel {+ self.space_of_channel(&c).await?+ } else if let Some(k) = direct {+ self.space_of_kwant(&k).await?+ } else if let Some(t) = thread {+ self.space_of_thread(&t).await?+ } else {+ None+ };+ Ok(space.map(|s| (s, role)))+ }++ /// Adds a bot to a team and to the team's `team-<name>` channel.+ pub async fn add_team_member(&self, team_id: &str, kwant_id: &str) -> Result<bool, DbError> {+ let Some(team) = self.get_team(team_id).await? else {+ return Ok(false);+ };+ let mut members: Vec<String> = serde_json::from_str(&team.member_kwants).unwrap_or_default();+ if !members.iter().any(|m| m == kwant_id) {+ members.push(kwant_id.to_string());+ }+ let json = serde_json::to_string(&members)?;+ let mut tx = self.pool.begin().await?;+ sqlx::query("UPDATE teams SET member_kwants = ? WHERE id = ?").bind(&json).bind(team_id).execute(&mut *tx).await?;+ let channel: Option<(String, String)> = sqlx::query_as("SELECT id, member_kwants FROM channels WHERE name = ? AND space_id = ?")+ .bind(format!("team-{}", team.name))+ .bind(&team.space_id)+ .fetch_optional(&mut *tx)+ .await?;+ if let Some((cid, raw)) = channel {+ let mut cm: Vec<String> = serde_json::from_str(&raw).unwrap_or_default();+ if !cm.iter().any(|m| m == kwant_id) {+ cm.push(kwant_id.to_string());+ }+ sqlx::query("UPDATE channels SET member_kwants = ? WHERE id = ?")+ .bind(serde_json::to_string(&cm)?)+ .bind(cid)+ .execute(&mut *tx)+ .await?;+ }+ tx.commit().await?;+ Ok(true)+ }++ /// The team a bot leads or belongs to in its space, if any (the first one made).+ pub async fn team_of_kwant(&self, space: &SpaceId, kwant_id: &str) -> Result<Option<super::models::Team>, DbError> {+ let teams = self.list_teams(space).await?;+ Ok(teams.into_iter().find(|t| {+ t.lead_kwant_id == kwant_id || serde_json::from_str::<Vec<String>>(&t.member_kwants).unwrap_or_default().iter().any(|m| m == kwant_id)+ }))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn roles_compare_by_their_words() {+ assert_eq!(role_key("The Recipe helper bot"), "helper recipe");+ assert!(similar_roles(&role_key("Recipe helper"), &role_key("recipes helper")));+ assert!(similar_roles(&role_key("Weekly recipe planner"), &role_key("recipe planner")));+ assert!(!similar_roles(&role_key("Recipe helper"), &role_key("Recipe planner")));+ assert!(!similar_roles(&role_key("Backend engineer"), &role_key("Frontend engineer")));+ assert!(!similar_roles(&role_key("Recipe helper"), &role_key("Tax advisor")));+ assert!(!similar_roles("", "x"));+ }+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex 2b4726cf..ddba2d9c 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -11,6 +11,7 @@ pub mod spaces;pub mod custom_api;pub mod mcp_suggestions;pub mod bot_actions;+pub mod hires;/// What a space's #general says about itself.pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";@@ -134,6 +135,7 @@ impl Database {db.migrate_custom_api().await?;db.migrate_mcp_suggestions().await?;db.migrate_bot_actions().await?;+ db.migrate_hires().await?;}Ok(db)diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex 6ac80fe5..2237ce67 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -95,6 +95,10 @@ pub enum RuntimeEvent {/// 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 },+ /// A bot proposed hiring a new bot, or the person decided on (or undid) a hire; `hire` is the+ /// whole proposal with its `card`. See `crate::db::hires` and docs/bot-actions.md → "Hiring".+ #[serde(rename = "hire_updated", alias = "HireUpdated")]+ HireUpdated { hire: 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.rsindex 72e6c8f5..cebc8ab9 100644--- a/src/server/bot_actions.rs+++ b/src/server/bot_actions.rs@@ -863,35 +863,84 @@ impl Ctx<'_> {}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."- ))),- }+ check_model(model).map_err(fail)}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,- }+ bot_snapshot(self.state, id).await+ }+}++/// `Err` with the reason when `model` isn't "auto", an engine or engine/model.+pub(super) fn check_model(model: &str) -> Result<(), String> {+ let pin = crate::router::parse_pin(model);+ match pin.family.as_deref() {+ None | Some("claude" | "codex" | "grok" | "custom" | "local_ollama") => Ok(()),+ Some(_) => Err(format!(+ "Unknown model \"{model}\". Use \"auto\", an engine (claude, codex, grok, ollama, custom) or engine/model."+ )),}+}++/// What a bot is now, for cards and Undo.+pub(super) async fn bot_snapshot(state: &AppState, id: &str) -> Value {+ let view = state.db.kwant_view(id).await.ok().flatten();+ let mcp = state.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,+ }+}++/// Creates a bot in `space` through the app's own handler. `spec`: `name`, `title`,+/// `instructions`, `soul?`, `avatar?`, `model?`, `profile_id?`. Returns its view.+pub(super) async fn create_bot(state: &AppState, space: &SpaceId, spec: &Value) -> Result<Value, String> {+ let mut body = json!({+ "name": spec["name"],+ "title": spec["title"],+ "persona_prompt": spec["instructions"],+ "soul": spec["soul"].as_str().unwrap_or(""),+ "avatar_sprite": spec["avatar"].as_str().unwrap_or("default"),+ "driver_type": "api",+ "preferred_model": spec["model"].as_str().unwrap_or("auto"),+ });+ if let Some(p) = spec["profile_id"].as_str().filter(|p| !p.is_empty()) {+ body["profile_id"] = json!(p);+ }+ let payload = serde_json::from_value(body).map_err(|e| e.to_string())?;+ let resp = super::routes::create_kwant(State(state.clone()), Scope(space.clone()), Json(payload)).await.into_response();+ match read(resp).await {+ Ok(v) => Ok(v),+ Err(e) if e == "that isn't valid" => Err("the account doesn't exist in your space or is for another engine.".into()),+ Err(e) => Err(e),+ }+}+/// Records an applied change that already shows on another card (a hire), without a card of its+/// own; Undo goes through `POST /api/bot-actions/:id/undo` as usual.+pub(super) async fn record_quiet(state: &AppState, new: &NewBotAction) -> Result<BotAction, String> {+ let (a, _) = state.db.record_bot_action(new, |_| None).await.map_err(|e| {+ tracing::warn!(error = %e, action = %new.action, "could not record a bot action");+ "the change could not be logged".to_string()+ })?;+ let _ = 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)+}++impl Ctx<'_> {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;@@ -907,28 +956,17 @@ impl Ctx<'_> {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!({+ let spec = json!({"name": name,"title": title,- "persona_prompt": instructions,+ "instructions": instructions,"soul": arg(args, "soul").unwrap_or(""),- "avatar_sprite": avatar,- "driver_type": "api",- "preferred_model": model,+ "avatar": avatar,+ "model": model,+ "profile_id": arg(args, "profile_id"),});- 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 {+ let view = match create_bot(self.state, &self.space, &spec).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();@@ -1518,6 +1556,12 @@ async fn undo_action(state: &AppState, a: &BotAction) -> Result<Option<String>,return Ok(created["id"].as_str().map(str::to_string));}"bot_create" => delete_unused_bot(state, &target).await?,+ "bot_hire" => {+ delete_unused_bot(state, &target).await?;+ if let Some(hire) = a.after_json()["hire_id"].as_str() {+ super::hires::undone(state, hire).await;+ }+ }"bot_update" => {if state.db.get_kwant(&target).await.ok().flatten().is_none() {return Err(error(StatusCode::CONFLICT, "the bot no longer exists"));diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 5ac04440..69cb0ac3 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -107,8 +107,11 @@ pub async fn prompt_block(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."+ tell you where in Settings the user does it.\n\+ - `propose_hire` proposes a new bot for work a specialist would do better; the person decides. `hire_status` shows \+ the space's hire policy and decisions."));+ out.push_str(&super::hires::prompt_block(state, &crate::db::spaces::SpaceId::new(&kwant.space_id)).await);}out}@@ -229,6 +232,7 @@ fn tool_list(scope: &SelfScope) -> Value {list.extend(super::skills::tools());list.extend(super::mcp_suggest::tools());list.extend(super::bot_actions::tools());+ list.extend(super::hires::tools());if scope.sandbox_target.is_some() {list.extend(browser_tools());}@@ -599,6 +603,7 @@ async fn call_tool("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,+ n if super::hires::handles(n) => super::hires::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/hires.rs b/src/server/hires.rsnew file mode 100644index 00000000..6601db44--- /dev/null+++ b/src/server/hires.rs@@ -0,0 +1,752 @@+//! Bots proposing to hire a new bot, and the person deciding. `propose_hire` creates nothing: it+//! records a proposal tied to the bot, turn and space and posts a card with three choices for+//! the person: Deny, Accept once or Always accept (`POST /api/hires/:id/accept|deny`, person+//! only). Accepting creates the bot through the same path as `bot_create`, adds it to the team and+//! logs a `bot_hire` action the person can undo. "Always accept" sets the space's hire policy to+//! `auto`, so later proposals there are created at once (at most [`AUTO_HIRES_PER_DAY`] a day).+//! A Deny is remembered per space and blocks proposing that kind of bot again. Every bot in the+//! space sees the policy and recent decisions on its next turn ([`prompt_block`]).+//! Contract: docs/bot-actions.md → "Hiring".++#![allow(clippy::result_large_err)]++use super::continuity::SelfScope;+use super::spaces::Scope;+use super::AppState;+use crate::db::bot_actions::NewBotAction;+use crate::db::hires::{role_key, similar_roles, Hire, NewHire, AUTO_HIRES_PER_DAY, HIRE_STATUSES, MAX_PROPOSALS_PER_TURN};+use crate::db::models::{MessageExtra, NewMessage};+use crate::db::spaces::SpaceId;+use crate::drivers::events::RuntimeEvent;+use axum::{+ extract::{Path, Query, State},+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use serde::Deserialize;+use serde_json::{json, Value};++type ToolResult = (String, bool);++fn fail(msg: impl Into<String>) -> ToolResult {+ (msg.into(), true)+}++/// What a bot can name as the gap a new bot fills.+const NEEDS: [&str; 4] = ["instructions", "tools", "schedule", "model"];+/// Earlier similar requests from the person that count as "this keeps coming up".+const MIN_SIMILAR_REQUESTS: usize = 3;++pub fn handles(name: &str) -> bool {+ matches!(name, "propose_hire" | "hire_status")+}++pub fn tools() -> Vec<Value> {+ vec![+ json!({+ "name": "propose_hire",+ "description": "Propose hiring a new bot for your space; the person decides on a card (Deny, Accept once, Always accept). \+ Only after you tried the request yourself (and mcp_suggest for missing tools), and only when (a) a specialist with \+ its own instructions, tools, schedule or model would clearly do this kind of work better, or (b) similar requests \+ have come up at least 3 times in this space. It creates nothing by itself; carry on with the request yourself. \+ At most one proposal per turn. A kind of bot the person turned down is refused unless they asked for one.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "name": {"type": "string", "description": "One word, no spaces or @, unique in the space, e.g. Chef"},+ "role": {"type": "string", "description": "Its role, e.g. \"Recipe planner\""},+ "instructions": {"type": "string", "description": "Its standing instructions: who it is and how it works"},+ "model": {"type": "string", "description": "\"auto\" (default), an engine (claude, codex, grok, ollama, custom) or engine/model"},+ "tools": {"type": "array", "items": {"type": "string"}, "description": "Tool servers already installed in the space (names or ids) it should have"},+ "team": {"type": "string", "description": "The team it joins (id or name). Default: your team"},+ "reason": {"type": "string", "description": "Why a new bot does this better than you, in one or two sentences for the person"},+ "evidence": {+ "type": "object",+ "description": "What the proposal rests on. basis \"specialist\": needs (what it needs of its own: instructions, tools, schedule, model) and gap (what you can't do well). basis \"repeated\": similar_requests, the message ids of at least 3 earlier requests from the person in this space (search_history finds them).",+ "properties": {+ "basis": {"type": "string", "enum": ["specialist", "repeated"]},+ "needs": {"type": "array", "items": {"type": "string", "enum": NEEDS}},+ "gap": {"type": "string"},+ "similar_requests": {"type": "array", "items": {"type": "string"}},+ },+ "required": ["basis"],+ },+ "requested_by_person": {"type": "boolean", "description": "true only when the person asked for this kind of bot in this conversation"},+ },+ "required": ["name", "role", "instructions", "reason", "evidence"],+ },+ }),+ json!({+ "name": "hire_status",+ "description": "Your space's hire policy (ask each time, or always accept), how many automatic hires are left today, \+ and recent proposals with the person's decisions. Read-only: only the person changes the policy.",+ "inputSchema": {"type": "object", "properties": {}},+ }),+ ]+}++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."),+ };+ match name {+ "propose_hire" => propose(state, scope, &space, args).await,+ "hire_status" => (status_text(state, &space).await, false),+ _ => fail(format!("Unknown tool {name}.")),+ }+}++fn arg<'v>(args: &'v Value, key: &str) -> Option<&'v str> {+ args[key].as_str().map(str::trim).filter(|s| !s.is_empty())+}++/// The checked `evidence`, or why it doesn't hold up.+async fn check_evidence(state: &AppState, space: &SpaceId, raw: &Value) -> Result<Value, String> {+ const TRY_FIRST: &str = "Do the request yourself first; propose a hire only with real evidence.";+ match raw["basis"].as_str() {+ Some("specialist") => {+ let needs: Vec<String> = raw["needs"]+ .as_array()+ .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect())+ .unwrap_or_default();+ if needs.is_empty() || needs.iter().any(|n| !NEEDS.contains(&n.as_str())) {+ return Err(format!(+ "evidence.needs must say what the new bot needs of its own: some of {}. {TRY_FIRST}",+ NEEDS.join(", ")+ ));+ }+ let gap = raw["gap"].as_str().map(str::trim).unwrap_or("");+ if gap.chars().count() < 20 {+ return Err(format!("evidence.gap must say in a sentence what you can't do well yourself. {TRY_FIRST}"));+ }+ Ok(json!({"basis": "specialist", "needs": needs, "gap": gap}))+ }+ Some("repeated") => {+ let ids: Vec<String> = raw["similar_requests"]+ .as_array()+ .map(|a| {+ a.iter()+ .filter_map(|v| v.as_str().or_else(|| v["message_id"].as_str()))+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+ .collect()+ })+ .unwrap_or_default();+ let mut found = Vec::new();+ for id in &ids {+ if found.iter().any(|f: &Value| f["message_id"] == json!(id)) {+ continue;+ }+ match state.db.message_space_and_sender(id).await {+ Ok(Some((s, role))) if &s == space && role == "user" => {+ let at = state.db.message_created_at(id).await.ok().flatten();+ found.push(json!({"message_id": id, "at": at}));+ }+ Ok(Some((s, _))) if &s == space => {+ return Err(format!("Message {id} isn't a request from the person; give the person's own messages."))+ }+ _ => return Err(format!("There is no message {id} in your space; search_history finds earlier requests.")),+ }+ }+ if found.len() < MIN_SIMILAR_REQUESTS {+ return Err(format!(+ "evidence.similar_requests needs at least {MIN_SIMILAR_REQUESTS} different earlier requests from the person in \+ this space (message ids); you gave {}. {TRY_FIRST}",+ found.len()+ ));+ }+ Ok(json!({"basis": "repeated", "similar_requests": found}))+ }+ _ => Err(format!(+ "Nothing was proposed: evidence.basis must be \"specialist\" (with needs and gap) or \"repeated\" (with \+ similar_requests). {TRY_FIRST}"+ )),+ }+}++async fn propose(state: &AppState, scope: &SelfScope, space: &SpaceId, args: &Value) -> ToolResult {+ if let Err(e) = super::spaces::ensure_active(state, space).await {+ let _ = e;+ return fail("Your space is archived, so nothing can be added to it.");+ }+ if let Some(k) = ["env", "headers", "api_key", "password", "token", "mcp_env", "profile_id"].iter().find(|k| args.get(**k).is_some()) {+ return fail(format!(+ "Nothing was proposed: {k} is not something you can give a new bot. A new bot gets no keys or accounts; the person adds \+ them in Space settings → Accounts or Tools."+ ));+ }+ if let Some(t) = &scope.turn_id {+ match state.db.hires_in_turn(t).await {+ Ok(n) if n >= MAX_PROPOSALS_PER_TURN => {+ return fail("You already proposed a hire this turn; one per turn. Carry on with the request yourself.")+ }+ Ok(_) => {}+ Err(_) => return fail("Could not check your proposals this turn."),+ }+ }+ let (Some(name), Some(role), Some(instructions), Some(reason)) =+ (arg(args, "name"), arg(args, "role"), arg(args, "instructions"), arg(args, "reason"))+ else {+ return fail("Nothing was proposed: name, role, instructions, reason and evidence are required.");+ };+ if reason.chars().count() < 10 {+ return fail("Nothing was proposed: reason must tell the person in a sentence why a new bot does this better than you.");+ }+ let name = name.trim_start_matches('@');+ if name.chars().any(char::is_whitespace) {+ return fail("Nothing was proposed: name must be one word, e.g. Chef.");+ }+ let evidence = match check_evidence(state, space, &args["evidence"]).await {+ Ok(v) => v,+ Err(e) => return fail(format!("Nothing was proposed. {e}")),+ };+ let model = arg(args, "model").unwrap_or("auto").to_string();+ if let Err(e) = super::bot_actions::check_model(&model) {+ return fail(format!("Nothing was proposed. {e}"));+ }+ // Tools: only servers already installed in the space+ let mut tools = Vec::new();+ match args.get("tools") {+ None | Some(Value::Null) => {}+ Some(Value::Array(list)) => {+ let servers = state.db.list_mcp_servers(space).await.unwrap_or_default();+ 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) => tools.push(s.id.clone()),+ None => {+ return fail(format!(+ "Nothing was proposed: no tool server \"{r}\" is installed in your space. Suggest it with mcp_suggest; \+ the person installs it."+ ))+ }+ }+ }+ }+ Some(_) => return fail("Nothing was proposed: tools must be a list of installed tool servers' names or ids."),+ }+ // Team: the one named, or the proposer's+ let team = match arg(args, "team") {+ Some(t) => {+ let by_id = state.db.get_team(t).await.ok().flatten();+ let team = match by_id {+ Some(team) => Some(team),+ None => state.db.list_teams(space).await.unwrap_or_default().into_iter().find(|x| x.name.eq_ignore_ascii_case(t)),+ };+ match team {+ Some(team) if team.space_id == space.as_str() => Some(team),+ Some(_) => return fail("That team is in another space. You can only hire into your own space."),+ None => return fail(format!("There is no team \"{t}\" in your space.")),+ }+ }+ None => state.db.team_of_kwant(space, &scope.kwant_id).await.ok().flatten(),+ };+ // Bot first: an existing bot that already does this+ let key = role_key(role);+ let bots = state.db.list_kwants(space).await.unwrap_or_default();+ if let Some(b) = bots.iter().find(|b| b.name.eq_ignore_ascii_case(name)) {+ return fail(format!("There is already a bot called {} in your space; ask it, or pick another name.", b.name));+ }+ if let Some(b) = bots.iter().find(|b| similar_roles(&role_key(&b.title), &key)) {+ return fail(format!(+ "{} ({}) already does this kind of work in your space. Hand the work to it, or update it with bot_update, instead of \+ hiring.",+ b.name, b.title+ ));+ }+ let requested = args["requested_by_person"].as_bool() == Some(true);+ // A kind of bot the person turned down stays turned down in this space+ let denials = state.db.active_denials(space).await.unwrap_or_default();+ let denied = denials.iter().find(|d| d.name.eq_ignore_ascii_case(name) || similar_roles(&d.role_key, &key));+ if let (Some(d), false) = (denied, requested) {+ return fail(format!(+ "The person turned down hiring {} ({}) in this space on {}. Don't propose this kind of bot again unless they ask for \+ one; carry on with the request yourself.",+ d.name,+ d.role,+ d.resolved_at.map(|t| t.format("%Y-%m-%d").to_string()).unwrap_or_default()+ ));+ }+ let pending = state.db.list_hires(space, Some("pending")).await.unwrap_or_default();+ if let Some(p) = pending.iter().find(|p| p.name.eq_ignore_ascii_case(name) || similar_roles(&p.role_key, &key)) {+ return fail(format!(+ "A proposal to hire {} ({}) is already waiting for the person. Don't propose it again; carry on with the request.",+ p.name, p.role+ ));+ }++ let origin = scope.origin.as_ref();+ let new = NewHire {+ space_id: space.as_str().into(),+ kwant_id: scope.kwant_id.clone(),+ turn_id: 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()),+ name: name.into(),+ role: role.into(),+ instructions: instructions.into(),+ model,+ tools,+ team_id: team.as_ref().map(|t| t.id.clone()),+ reason: reason.into(),+ evidence,+ requested_by_person: requested,+ };+ 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 sender = scope.kwant_name.clone();+ let mut card_meta = Value::Null;+ let recorded = state+ .db+ .record_hire(&new, |h| {+ if !has_chat {+ return None;+ }+ card_meta = json!({"kind": "hire_proposal", "hire_id": h.id, "status": "pending"});+ Some((+ NewMessage {+ channel_id: h.channel_id.clone().filter(|_| h.thread_id.is_none()),+ direct_kwant_id: h.direct_kwant_id.clone().filter(|_| h.thread_id.is_none()),+ sender_role: "kwant".into(),+ sender_id: sender,+ text: format!("Wants to hire {} ({}). Waiting for your choice: Deny, Accept once or Always accept.", h.name, h.role),+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 0,+ },+ MessageExtra { thread_id: h.thread_id.clone(), meta: Some(card_meta.clone()) },+ ))+ })+ .await;+ let (hire, card) = match recorded {+ Ok(r) => r,+ Err(e) => {+ tracing::warn!(error = %e, "could not record a hire proposal");+ return fail("Nothing was proposed: it could not be saved.");+ }+ };+ if let Some(card) = card {+ if let Some(t) = &hire.thread_id {+ let _ = state.db.touch_thread(t).await;+ }+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&card).unwrap_or(Value::Null) });+ }+ tracing::info!(hire_id = %hire.id, kwant_id = %hire.kwant_id, turn_id = ?hire.turn_id, role = %hire.role, "bot proposed a hire");++ // The space's policy may decide at once+ let policy = state.db.hire_policy(space).await.map(|p| p.policy).unwrap_or_else(|_| "ask".into());+ let mut note = None;+ if policy == "auto" && denied.is_none() {+ let used = state.db.auto_hires_today(space).await.unwrap_or(i64::MAX);+ if used < AUTO_HIRES_PER_DAY {+ return match accept(state, &hire, true).await {+ Ok(h) => (+ format!(+ "Hired {} ({}) at once: the person chose \"always accept\" for this space. They see a card with Undo. Tell \+ them in one sentence, then carry on with the request yourself; {} can take this kind of work from now on.",+ h.name, h.role, h.name+ ),+ false,+ ),+ Err((_, e)) => {+ refresh(state, &hire.id, Some(&format!("couldn't be created at once: {e}"))).await;+ (format!("The proposal is waiting for the person: {e}. Carry on with the request yourself."), false)+ }+ };+ }+ note = Some(format!("{AUTO_HIRES_PER_DAY} bots were already hired automatically in the last 24 hours, so this one asks you."));+ } else if denied.is_some() {+ note = Some("You turned this kind of bot down before; the bot says you asked for one now.".to_string());+ }+ refresh(state, &hire.id, note.as_deref()).await;+ (+ format!(+ "Proposed hiring {} ({}). Nothing is created until the person chooses on the card (Deny, Accept once or Always accept). \+ Tell them in one sentence, then carry on with the request yourself.",+ hire.name, hire.role+ ),+ false,+ )+}++// The card++fn card_text(h: &Hire, proposer: &str) -> String {+ match h.status.as_str() {+ "pending" => format!("Wants to hire {} ({}). Waiting for your choice: Deny, Accept once or Always accept.", h.name, h.role),+ "accepted" => format!("Hired {} ({}); you accepted. Undo removes it while it has no history.", h.name, h.role),+ "auto_accepted" => format!("Hired {} ({}) at once, as you chose \"always accept\". Undo removes it.", h.name, h.role),+ "denied" => format!("Not hired: {} ({}). {proposer} won't propose this kind of bot again in this space.", h.name, h.role),+ _ => format!("Hire undone: {} ({}) was removed.", h.name, h.role),+ }+}++/// The card's `meta` (docs/bot-actions.md → "Hiring").+pub async fn card_meta(state: &AppState, h: &Hire, note: Option<&str>) -> Value {+ let space = SpaceId::new(&h.space_id);+ let proposer = state.db.get_kwant(&h.kwant_id).await.ok().flatten().map(|k| k.name).unwrap_or_default();+ let team = match &h.team_id {+ Some(t) => state.db.get_team(t).await.ok().flatten().map(|t| json!({"id": t.id, "name": t.name})),+ None => None,+ }+ .unwrap_or(Value::Null);+ let servers = state.db.list_mcp_servers(&space).await.unwrap_or_default();+ let tools: Vec<Value> = h+ .tools_json()+ .iter()+ .map(|id| json!({"id": id, "name": servers.iter().find(|s| &s.id == id).map(|s| s.name.clone())}))+ .collect();+ let action_applied = match &h.action_id {+ Some(a) => state.db.get_bot_action(a).await.ok().flatten().is_some_and(|a| a.status == "applied"),+ None => false,+ };+ let policy = state.db.hire_policy(&space).await.map(|p| p.policy).unwrap_or_else(|_| "ask".into());+ json!({+ "kind": "hire_proposal",+ "hire_id": h.id,+ "kwant_id": h.kwant_id,+ "proposer_name": proposer,+ "name": h.name,+ "role": h.role,+ "instructions": h.instructions,+ "model": h.model,+ "tools": tools,+ "team": team,+ "reason": h.reason,+ "evidence": h.evidence_json(),+ "requested_by_person": h.requested_by_person,+ "status": h.status,+ "auto": h.auto,+ "choices": if h.status == "pending" { json!(["deny", "accept_once", "always_accept"]) } else { json!([]) },+ "hired_kwant_id": h.hired_kwant_id,+ "action_id": h.action_id,+ "can_undo": action_applied && matches!(h.status.as_str(), "accepted" | "auto_accepted"),+ "policy": policy,+ "note": note,+ "created_at": h.created_at,+ "resolved_at": h.resolved_at,+ })+}++async fn hire_json(state: &AppState, h: &Hire, note: Option<&str>) -> Value {+ let mut v = serde_json::to_value(h).unwrap_or(Value::Null);+ v["card"] = card_meta(state, h, note).await;+ v+}++/// Re-reads the proposal, updates its card in place and tells clients.+async fn refresh(state: &AppState, id: &str, note: Option<&str>) -> Option<Value> {+ let h = state.db.get_hire(id).await.ok().flatten()?;+ let v = hire_json(state, &h, note).await;+ if let Some(mid) = &h.message_id {+ let _ = state.db.set_message_meta(mid, &v["card"]).await;+ let proposer = state.db.get_kwant(&h.kwant_id).await.ok().flatten().map(|k| k.name).unwrap_or_else(|| "The bot".into());+ let _ = state.db.set_message_text(mid, &card_text(&h, &proposer)).await;+ }+ let _ = state.event_sender.send(RuntimeEvent::HireUpdated { hire: v.clone() });+ Some(v)+}++/// After the person undid a `bot_hire` action: the proposal reads "undone".+pub(super) async fn undone(state: &AppState, id: &str) {+ for from in ["accepted", "auto_accepted"] {+ if matches!(state.db.resolve_hire(id, from, "undone").await, Ok(true)) {+ break;+ }+ }+ refresh(state, id, None).await;+}++/// Creates the bot for a pending proposal: same path as `bot_create`, plus its tools and team,+/// logged as a `bot_hire` action for Undo. Puts the proposal back to pending on failure.+async fn accept(state: &AppState, h: &Hire, auto: bool) -> Result<Hire, (StatusCode, String)> {+ let to = if auto { "auto_accepted" } else { "accepted" };+ match state.db.resolve_hire(&h.id, "pending", to).await {+ Ok(true) => {}+ Ok(false) => return Err((StatusCode::CONFLICT, "this proposal was already decided".into())),+ Err(_) => return Err((StatusCode::INTERNAL_SERVER_ERROR, "could not save the decision".into())),+ }+ let space = SpaceId::new(&h.space_id);+ let back = |e: String| async move {+ let _ = state.db.resolve_hire(&h.id, to, "pending").await;+ Err((StatusCode::CONFLICT, e))+ };+ if super::spaces::ensure_active(state, &space).await.is_err() {+ return back("the space is archived".into()).await;+ }+ let spec = json!({"name": h.name, "title": h.role, "instructions": h.instructions, "model": h.model});+ let view = match super::bot_actions::create_bot(state, &space, &spec).await {+ Ok(v) => v,+ Err(e) => return back(format!("the bot could not be created: {e}")).await,+ };+ let id = view["id"].as_str().unwrap_or("").to_string();+ let installed: Vec<String> = state.db.list_mcp_servers(&space).await.unwrap_or_default().into_iter().map(|s| s.id).collect();+ let tools: Vec<String> = h.tools_json().into_iter().filter(|t| installed.contains(t)).collect();+ if !tools.is_empty() {+ let _ = state.db.set_kwant_mcp_servers(&id, &tools).await;+ }+ if let Some(t) = &h.team_id {+ let _ = state.db.add_team_member(t, &id).await;+ }+ let mut after = super::bot_actions::bot_snapshot(state, &id).await;+ after["hire_id"] = json!(h.id);+ after["team_id"] = json!(h.team_id);+ let new = NewBotAction {+ space_id: h.space_id.clone(),+ kwant_id: h.kwant_id.clone(),+ turn_id: h.turn_id.clone(),+ channel_id: h.channel_id.clone(),+ direct_kwant_id: h.direct_kwant_id.clone(),+ thread_id: h.thread_id.clone(),+ action: "bot_hire".into(),+ target_kind: "bot".into(),+ target_id: Some(id.clone()),+ summary: format!("hired bot {} ({})", h.name, h.role),+ before: None,+ after: Some(after),+ status: "applied".into(),+ };+ let action = super::bot_actions::record_quiet(state, &new).await.ok();+ let _ = state.db.set_hire_result(&h.id, Some(&id), action.as_ref().map(|a| a.id.as_str())).await;+ if auto {+ let _ = state.db.mark_hire_auto(&h.id).await;+ }+ state.scheduler_wake.notify_one();+ refresh(state, &h.id, None).await;+ tracing::info!(hire_id = %h.id, kwant_id = %id, auto, "a hire was accepted");+ state.db.get_hire(&h.id).await.ok().flatten().ok_or((StatusCode::INTERNAL_SERVER_ERROR, "lost the proposal".into()))+}++// What bots see++async fn status_text(state: &AppState, space: &SpaceId) -> String {+ let block = prompt_block(state, space).await;+ if block.is_empty() {+ "Hire policy: ask the person each time. No proposals in this space yet.".into()+ } else {+ block.trim().to_string()+ }+}++/// The space's hire policy and recent decisions, for every bot's next turn. Compact: at most 8+/// recent proposals plus the denials that still count.+pub async fn prompt_block(state: &AppState, space: &SpaceId) -> String {+ let policy = state.db.hire_policy(space).await.map(|p| p.policy).unwrap_or_else(|_| "ask".into());+ let recent = state.db.list_hires(space, None).await.unwrap_or_default();+ let denials = state.db.active_denials(space).await.unwrap_or_default();+ let policy_line = if policy == "auto" {+ let used = state.db.auto_hires_today(space).await.unwrap_or(0);+ format!(+ "Hire policy: always accept (the person chose it); {} of {AUTO_HIRES_PER_DAY} automatic hires left in the last 24 hours, \+ then proposals ask again.",+ (AUTO_HIRES_PER_DAY - used).max(0)+ )+ } else {+ "Hire policy: ask the person each time.".to_string()+ };+ let mut lines = Vec::new();+ let mut names = std::collections::HashMap::new();+ for h in recent.iter().filter(|h| h.status != "denied").take(8) {+ let proposer = match names.get(&h.kwant_id) {+ Some(n) => n,+ None => {+ let n = state.db.get_kwant(&h.kwant_id).await.ok().flatten().map(|k| k.name).unwrap_or_else(|| "a bot".into());+ names.entry(h.kwant_id.clone()).or_insert(n)+ }+ };+ let when = h.resolved_at.unwrap_or(h.created_at).format("%Y-%m-%d");+ let what = match h.status.as_str() {+ "pending" => "waiting for the person",+ "accepted" => "hired (the person accepted once)",+ "auto_accepted" => "hired automatically",+ _ => "hired, then undone by the person",+ };+ lines.push(format!("- {} ({}): {what}, {when}, proposed by {proposer}", h.name, h.role));+ }+ for d in denials.iter().take(10) {+ lines.push(format!(+ "- {} ({}): DENIED {}; don't propose this kind of bot again unless the person asks for one",+ d.name,+ d.role,+ d.resolved_at.map(|t| t.format("%Y-%m-%d").to_string()).unwrap_or_default()+ ));+ }+ let mut out = format!(+ "\n\n[Hiring new bots in this space]\n{policy_line}\n\+ Do every request yourself first (with mcp_suggest for a missing tool). Use `propose_hire` only when a specialist with its \+ own instructions, tools, schedule or model would clearly do this kind of work better, or when similar requests have come \+ up at least {MIN_SIMILAR_REQUESTS} times here; give the reason and the evidence, then carry on with the request yourself."+ );+ if !lines.is_empty() {+ out.push_str("\nProposals so far:\n");+ out.push_str(&lines.join("\n"));+ }+ out+}++// 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>,+}++/// `GET /api/hires?space=&status=`: the space's proposals with their cards, newest first.+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| !HIRE_STATUSES.contains(&s)) {+ return error(StatusCode::BAD_REQUEST, "unknown status");+ }+ match state.db.list_hires(&space, status.as_deref()).await {+ Ok(list) => {+ let mut out = Vec::new();+ for h in &list {+ out.push(hire_json(&state, h, None).await);+ }+ Json(out).into_response()+ }+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ }+}++async fn load_pending(state: &AppState, headers: &HeaderMap, id: &str) -> Result<Hire, Response> {+ super::mcp_suggest::refuse_agent_tokens(state, headers, "only the person decides on hiring a bot").await?;+ match state.db.get_hire(id).await {+ Ok(Some(h)) if h.status == "pending" => Ok(h),+ Ok(Some(h)) => Err(error(StatusCode::CONFLICT, format!("this proposal is {}", h.status))),+ Ok(None) => Err(error(StatusCode::NOT_FOUND, "proposal not found")),+ Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),+ }+}++#[derive(Deserialize, Default)]+pub struct AcceptBody {+ /// "Always accept": also set the space's policy to `auto`.+ #[serde(default)]+ pub always: bool,+}++/// `POST /api/hires/:id/accept {always?}`: Accept once, or Always accept.+pub async fn accept_route(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, body: Option<Json<AcceptBody>>) -> Response {+ let h = match load_pending(&state, &headers, &id).await {+ Ok(h) => h,+ Err(r) => return r,+ };+ let always = body.map(|b| b.always).unwrap_or(false);+ match accept(&state, &h, false).await {+ Ok(h) => {+ if always {+ let _ = state.db.set_hire_policy(&SpaceId::new(&h.space_id), "auto", false).await;+ }+ match refresh(&state, &h.id, None).await {+ Some(v) => Json(v).into_response(),+ None => StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ }+ }+ Err((status, e)) => {+ refresh(&state, &h.id, Some(&e)).await;+ error(status, e)+ }+ }+}++/// `POST /api/hires/:id/deny`: nothing is created, and the space remembers it.+pub async fn deny_route(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {+ let h = match load_pending(&state, &headers, &id).await {+ Ok(h) => h,+ Err(r) => return r,+ };+ match state.db.resolve_hire(&h.id, "pending", "denied").await {+ Ok(true) => {}+ Ok(false) => return error(StatusCode::CONFLICT, "this proposal was just decided"),+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ }+ tracing::info!(hire_id = %h.id, "the person denied a hire");+ match refresh(&state, &h.id, None).await {+ Some(v) => Json(v).into_response(),+ None => StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ }+}++async fn policy_json(state: &AppState, space: &SpaceId) -> Result<Value, Response> {+ let p = state.db.hire_policy(space).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;+ let used = state.db.auto_hires_today(space).await.unwrap_or(0);+ let denied: Vec<Value> = state+ .db+ .active_denials(space)+ .await+ .unwrap_or_default()+ .iter()+ .map(|d| json!({"hire_id": d.id, "name": d.name, "role": d.role, "denied_at": d.resolved_at}))+ .collect();+ Ok(json!({+ "space_id": space.as_str(),+ "policy": p.policy,+ "auto_hires_last_24h": used,+ "auto_hires_per_day": AUTO_HIRES_PER_DAY,+ "denied": denied,+ "denials_cleared_at": p.denials_cleared_at,+ "updated_at": p.updated_at,+ }))+}++async fn existing_space(state: &AppState, id: &str) -> Result<SpaceId, Response> {+ let space = SpaceId::new(id);+ match state.db.get_space(&space).await {+ Ok(Some(_)) => Ok(space),+ Ok(None) => Err(error(StatusCode::NOT_FOUND, "space not found")),+ Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR.into_response()),+ }+}++/// `GET /api/spaces/:id/hire-policy`+pub async fn get_policy(State(state): State<AppState>, Path(id): Path<String>) -> Response {+ let space = match existing_space(&state, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ match policy_json(&state, &space).await {+ Ok(v) => Json(v).into_response(),+ Err(r) => r,+ }+}++#[derive(Deserialize)]+pub struct PolicyBody {+ pub policy: Option<String>,+ #[serde(default)]+ pub clear_denials: bool,+}++/// `PUT /api/spaces/:id/hire-policy {policy?: "ask"|"auto", clear_denials?}`: the person only.+pub async fn put_policy(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, Json(body): Json<PolicyBody>) -> Response {+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person sets the hire policy").await {+ return r;+ }+ let space = match existing_space(&state, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ let current = match state.db.hire_policy(&space).await {+ Ok(p) => p.policy,+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ };+ let policy = body.policy.unwrap_or(current);+ if !matches!(policy.as_str(), "ask" | "auto") {+ return error(StatusCode::BAD_REQUEST, "policy must be \"ask\" or \"auto\"");+ }+ if state.db.set_hire_policy(&space, &policy, body.clear_denials).await.is_err() {+ return StatusCode::INTERNAL_SERVER_ERROR.into_response();+ }+ tracing::info!(space = %space, policy = %policy, clear_denials = body.clear_denials, "the person set the hire policy");+ match policy_json(&state, &space).await {+ Ok(v) => Json(v).into_response(),+ Err(r) => r,+ }+}diff --git a/src/server/mod.rs b/src/server/mod.rsindex 39068fb7..bda85ac2 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -22,6 +22,7 @@ pub mod away;pub mod computer;pub mod mcp_suggest;pub mod bot_actions;+pub mod hires;use crate::broker::PermissionBroker;use crate::config::Config;@@ -197,6 +198,10 @@ pub fn create_router(state: AppState) -> Router {.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/hires", get(hires::list))+ .route("/api/hires/:id/accept", post(hires::accept_route))+ .route("/api/hires/:id/deny", post(hires::deny_route))+ .route("/api/spaces/:id/hire-policy", get(hires::get_policy).put(hires::put_policy)).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/sse.rs b/src/server/sse.rsindex 41bc9275..9f74f285 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -85,9 +85,9 @@ 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));+ E::BotActionUpdated { action: v } | E::HireUpdated { hire: v } => {+ let mut out = fields(v, &["space_id"], Owner::Space);+ out.extend(fields(v, &["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())]),@@ -214,6 +214,7 @@ mod tests {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::HireUpdated { hire: json!({"id": "h", "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"))),@@ -289,6 +290,7 @@ mod tests {| E::QuestionUpdated { .. }| E::McpSuggestionUpdated { .. }| E::BotActionUpdated { .. }+ | E::HireUpdated { .. }| E::Scoped { .. }| E::ProfileSwitched { .. }| E::DiscussionStarted { .. }diff --git a/tests/continuity_test.rs b/tests/continuity_test.rsindex b3ecd7b2..89711aa8 100644--- a/tests/continuity_test.rs+++ b/tests/continuity_test.rs@@ -785,6 +785,8 @@ async fn self_tools_are_scoped_to_the_turn_and_kwant() {"channel_create","channel_update","profile_delete",+ "propose_hire",+ "hire_status",]);diff --git a/tests/hires_test.rs b/tests/hires_test.rsnew file mode 100644index 00000000..5426bf50--- /dev/null+++ b/tests/hires_test.rs@@ -0,0 +1,443 @@+//! Bots proposing to hire a new bot (`propose_hire`) and the person deciding: Deny, Accept once,+//! Always accept. A proposal creates nothing; only the person decides; decisions and the policy+//! are remembered per space and shown to the space's bots on their next turn.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{+ models::{Channel, Kwant, Message, NewMessage},+ spaces::SpaceId,+ Database,+ },+ router::LayaRouter,+ server::{+ continuity::{self, 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,+ 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(), 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))+}++async fn tool(e: &Env, token: &str, name: &str, args: Value) -> (String, bool) {+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args}});+ let (status, v) = call(&e.app, "POST", "/api/mcp/self", Some(token), Some(rpc)).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, args: Value) -> String {+ let (text, err) = tool(e, token, "propose_hire", args.clone()).await;+ assert!(!err, "propose_hire {args} failed: {text}");+ text+}++async fn refused(e: &Env, token: &str, args: Value) -> String {+ let (text, err) = tool(e, token, "propose_hire", args.clone()).await;+ assert!(err, "propose_hire {args} should be refused: {text}");+ text+}++/// A turn of `bot` in `channel` with its own tools; returns the turn token.+async fn turn_of(e: &Env, bot: &Kwant, channel: &str, turn_id: &str) -> String {+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ origin: Some(TurnOrigin { channel_id: Some(channel.into()), ..Default::default() }),+ 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 {+ turn_of(e, &e.bot, &e.general.id.clone(), turn_id).await+}++fn specialist(name: &str, role: &str) -> Value {+ json!({+ "name": name,+ "role": role,+ "instructions": format!("You are {name}, the {role}."),+ "reason": "A specialist with its own instructions does this better and every week.",+ "evidence": {"basis": "specialist", "needs": ["instructions", "schedule"], "gap": "I have no standing instructions or weekly schedule for this."},+ })+}++async fn hires(e: &Env, space: &str) -> Vec<Value> {+ let (status, v) = call(&e.app, "GET", &format!("/api/hires?space={space}"), None, None).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ v.as_array().unwrap().clone()+}++async fn latest(e: &Env) -> Value {+ hires(e, "spc_default").await.into_iter().next().expect("a proposal")+}++async fn bot_named(e: &Env, space: &str, name: &str) -> Option<Kwant> {+ e.state.db.list_kwants(&SpaceId::new(space)).await.unwrap().into_iter().find(|k| k.name == name)+}++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 card_of(e: &Env, hire: &Value) -> (Message, Value) {+ let m = messages(e, &e.general.id).await.into_iter().find(|m| meta(m)["hire_id"] == hire["id"]).expect("a card");+ let v = meta(&m);+ (m, v)+}++async fn next_turn_context(e: &Env) -> String {+ let bot = e.state.db.get_kwant(&e.bot.id).await.unwrap().unwrap();+ continuity::prompt_block(&e.state, &bot, None, None, true).await+}++async fn person_message(e: &Env, channel: &str, text: &str) -> String {+ let m = NewMessage {+ channel_id: Some(channel.into()),+ direct_kwant_id: None,+ sender_role: "user".into(),+ sender_id: "user".into(),+ text: text.into(),+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 0,+ };+ e.state.db.insert_message(&m).await.unwrap().id+}++#[tokio::test]+async fn a_proposal_needs_evidence_and_creates_nothing() {+ let e = setup().await;+ let before = e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap().len();+ let token = turn(&e, "t-ev").await;++ // No evidence, an unknown basis, thin specialist evidence, too few repeated requests: refused+ let mut none = specialist("Chef", "Recipe planner");+ none.as_object_mut().unwrap().remove("evidence");+ let text = refused(&e, &token, none).await;+ assert!(text.contains("Nothing was proposed"), "{text}");+ for evidence in [+ json!({}),+ json!({"basis": "vibes"}),+ json!({"basis": "specialist", "needs": [], "gap": "I have no standing instructions for recipes."}),+ json!({"basis": "specialist", "needs": ["instructions"], "gap": "short"}),+ json!({"basis": "specialist", "needs": ["a pony"], "gap": "I have no standing instructions for recipes."}),+ json!({"basis": "repeated", "similar_requests": []}),+ ] {+ let mut args = specialist("Chef", "Recipe planner");+ args["evidence"] = evidence.clone();+ let text = refused(&e, &token, args).await;+ assert!(text.contains("Nothing was proposed"), "{evidence}: {text}");+ }+ // "Repeated" counts the person's own requests in this space, each once+ let a = person_message(&e, &e.general.id, "plan dinners").await;+ let b = person_message(&e, &e.general.id, "plan lunches").await;+ let mut args = specialist("Chef", "Recipe planner");+ args["evidence"] = json!({"basis": "repeated", "similar_requests": [a, b, a]});+ let text = refused(&e, &token, args.clone()).await;+ assert!(text.contains("at least 3"), "{text}");+ assert!(hires(&e, "spc_default").await.is_empty());++ // With evidence: a pending proposal and a card, and still no new bot+ let c = person_message(&e, &e.general.id, "plan breakfasts").await;+ args["evidence"] = json!({"basis": "repeated", "similar_requests": [a, b, c]});+ let text = ok(&e, &token, args).await;+ assert!(text.contains("Nothing is created") && text.contains("carry on"), "{text}");+ assert_eq!(e.state.db.list_kwants(&SpaceId::default_space()).await.unwrap().len(), before);+ assert!(bot_named(&e, "spc_default", "Chef").await.is_none());+ let h = latest(&e).await;+ assert_eq!(h["status"], "pending");+ assert_eq!(h["turn_id"], "t-ev");+ assert_eq!(h["kwant_id"], json!(e.bot.id));+ let (m, card) = card_of(&e, &h).await;+ assert_eq!(m.sender_id, e.bot.name);+ assert_eq!(card["kind"], "hire_proposal");+ assert_eq!(card["choices"], json!(["deny", "accept_once", "always_accept"]));+ assert_eq!(card["evidence"]["similar_requests"].as_array().unwrap().len(), 3);+ assert_eq!(card["team"]["name"], "core-engineering", "defaults to the proposer's team");+ assert_eq!(card["can_undo"], false);++ // One proposal per turn+ let text = refused(&e, &token, specialist("Taxman", "Tax advisor")).await;+ assert!(text.contains("one per turn"), "{text}");+ // Keys and existing kinds of bots are refused+ let token = turn(&e, "t-ev2").await;+ let mut secret = specialist("Taxman", "Tax advisor");+ secret["env"] = json!({"API_KEY": "x"});+ assert!(refused(&e, &token, secret).await.contains("no keys"));+ let text = refused(&e, &token, specialist("Planner", "Recipe planner")).await;+ assert!(text.contains("already waiting"), "{text}");+ let text = refused(&e, &token, specialist("Arch2", "Systems Architect")).await;+ assert!(text.contains("already does this kind of work"), "{text}");+}++#[tokio::test]+async fn only_the_person_decides_and_accept_once_creates_the_bot_in_the_team() {+ let e = setup().await;+ let token = turn(&e, "t-acc").await;+ ok(&e, &token, specialist("Chef", "Recipe planner")).await;+ let h = latest(&e).await;+ let id = h["id"].as_str().unwrap();++ // A bot's turn token can't decide, set the policy, or deny+ for (method, uri, body) in [+ ("POST", format!("/api/hires/{id}/accept"), json!({})),+ ("POST", format!("/api/hires/{id}/accept"), json!({"always": true})),+ ("POST", format!("/api/hires/{id}/deny"), json!({})),+ ("PUT", "/api/spaces/spc_default/hire-policy".to_string(), json!({"policy": "auto"})),+ ] {+ let (status, v) = call(&e.app, method, &uri, Some(&token), Some(body)).await;+ assert_eq!(status, StatusCode::FORBIDDEN, "{uri}: {v}");+ }+ assert!(bot_named(&e, "spc_default", "Chef").await.is_none());+ assert_eq!(latest(&e).await["status"], "pending");+ // ... and a bot can read the policy+ let (text, err) = tool(&e, &token, "hire_status", json!({})).await;+ assert!(!err && text.contains("ask the person each time") && text.contains("Chef"), "{text}");++ // Accept once+ let (status, v) = call(&e.app, "POST", &format!("/api/hires/{id}/accept"), None, Some(json!({}))).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ assert_eq!(v["status"], "accepted");+ let chef = bot_named(&e, "spc_default", "Chef").await.expect("Chef was created");+ assert_eq!(chef.title, "Recipe planner");+ assert_eq!(v["hired_kwant_id"], json!(chef.id));+ let team = e.state.db.get_team_by_name(&SpaceId::default_space(), "core-engineering").await.unwrap().unwrap();+ assert!(team.member_kwants.contains(&chef.id), "joined the team");+ let team_channel = e.state.db.list_channels(&SpaceId::default_space()).await.unwrap().into_iter().find(|c| c.name == "team-core-engineering");+ if let Some(c) = team_channel {+ assert!(c.member_kwants.contains(&chef.id), "joined the team's channel");+ }+ let (m, card) = card_of(&e, &h).await;+ assert_eq!(card["status"], "accepted");+ assert_eq!(card["can_undo"], true);+ assert_eq!(card["choices"], json!([]));+ assert!(m.text.starts_with("Hired Chef"), "{}", m.text);+ // Deciding twice: conflict+ let (status, _) = call(&e.app, "POST", &format!("/api/hires/{id}/deny"), None, None).await;+ assert_eq!(status, StatusCode::CONFLICT);++ // Accept once doesn't change the policy: the next proposal asks again+ let (_, p) = call(&e.app, "GET", "/api/spaces/spc_default/hire-policy", None, None).await;+ assert_eq!(p["policy"], "ask");+ let token = turn(&e, "t-acc2").await;+ ok(&e, &token, specialist("Taxman", "Tax advisor")).await;+ assert_eq!(latest(&e).await["status"], "pending");+ assert!(bot_named(&e, "spc_default", "Taxman").await.is_none());++ // Undo through the bot action removes the hired bot and the card says so+ let action = card["action_id"].as_str().unwrap();+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{action}/undo"), None, None).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ assert!(bot_named(&e, "spc_default", "Chef").await.is_none());+ let team = e.state.db.get_team_by_name(&SpaceId::default_space(), "core-engineering").await.unwrap().unwrap();+ assert!(!team.member_kwants.contains(&chef.id));+ let (m, card) = card_of(&e, &h).await;+ assert_eq!(card["status"], "undone");+ assert_eq!(card["can_undo"], false);+ assert!(m.text.starts_with("Hire undone"), "{}", m.text);+}++#[tokio::test]+async fn always_accept_hires_at_once_with_undo_up_to_the_daily_cap() {+ let e = setup().await;+ let token = turn(&e, "t-al0").await;+ ok(&e, &token, specialist("Chef", "Recipe planner")).await;+ let id = latest(&e).await["id"].as_str().unwrap().to_string();+ let (status, v) = call(&e.app, "POST", &format!("/api/hires/{id}/accept"), None, Some(json!({"always": true}))).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ assert_eq!(v["card"]["policy"], "auto");+ let (_, p) = call(&e.app, "GET", "/api/spaces/spc_default/hire-policy", None, None).await;+ assert_eq!(p["policy"], "auto");+ assert_eq!(p["auto_hires_last_24h"], 0, "the person's own accept isn't automatic");++ // The next three are hired at once, each with an Undo card+ for (i, (name, role)) in [("Taxman", "Tax advisor"), ("Coach", "Fitness coach"), ("Gardener", "Garden designer")].iter().enumerate() {+ let token = turn(&e, &format!("t-al{}", i + 1)).await;+ let text = ok(&e, &token, specialist(name, role)).await;+ assert!(text.contains("Hired") && text.contains("always accept"), "{text}");+ let h = latest(&e).await;+ assert_eq!(h["status"], "auto_accepted");+ assert!(bot_named(&e, "spc_default", name).await.is_some(), "{name} created");+ let (m, card) = card_of(&e, &h).await;+ assert_eq!(card["can_undo"], true);+ assert_eq!(card["auto"], true);+ assert!(m.text.contains("always accept"), "{}", m.text);+ }+ // The fourth in 24 hours asks instead+ let token = turn(&e, "t-al4").await;+ let text = ok(&e, &token, specialist("Painter", "Portrait painter")).await;+ assert!(text.contains("Nothing is created"), "{text}");+ let h = latest(&e).await;+ assert_eq!(h["status"], "pending");+ assert!(bot_named(&e, "spc_default", "Painter").await.is_none());+ let (_, card) = card_of(&e, &h).await;+ assert!(card["note"].as_str().unwrap_or("").contains("already hired automatically"), "{card}");+ let (_, p) = call(&e.app, "GET", "/api/spaces/spc_default/hire-policy", None, None).await;+ assert_eq!(p["auto_hires_last_24h"], 3);++ // Undo an automatic hire+ let auto = hires(&e, "spc_default").await.into_iter().find(|h| h["name"] == "Coach").unwrap();+ let action = auto["action_id"].as_str().unwrap();+ let (status, v) = call(&e.app, "POST", &format!("/api/bot-actions/{action}/undo"), None, None).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ assert!(bot_named(&e, "spc_default", "Coach").await.is_none());++ // The person turns it back to asking+ let (status, p) = call(&e.app, "PUT", "/api/spaces/spc_default/hire-policy", None, Some(json!({"policy": "ask"}))).await;+ assert_eq!(status, StatusCode::OK, "{p}");+ assert_eq!(p["policy"], "ask");+ let (status, _) = call(&e.app, "PUT", "/api/spaces/spc_default/hire-policy", None, Some(json!({"policy": "yolo"}))).await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ let (status, _) = call(&e.app, "GET", "/api/spaces/spc_nope/hire-policy", None, None).await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn deny_is_remembered_in_its_space_only() {+ let e = setup().await;+ let token = turn(&e, "t-d1").await;+ ok(&e, &token, specialist("Chef", "Recipe planner")).await;+ let h = latest(&e).await;+ let (status, v) = call(&e.app, "POST", &format!("/api/hires/{}/deny", h["id"].as_str().unwrap()), None, None).await;+ assert_eq!(status, StatusCode::OK, "{v}");+ assert_eq!(v["status"], "denied");+ assert!(bot_named(&e, "spc_default", "Chef").await.is_none());+ let (m, card) = card_of(&e, &h).await;+ assert!(m.text.starts_with("Not hired"), "{}", m.text);+ assert_eq!(card["choices"], json!([]));++ // The same kind of bot under another name is refused in this space, even with "always accept"+ let (_, _) = call(&e.app, "PUT", "/api/spaces/spc_default/hire-policy", None, Some(json!({"policy": "auto"}))).await;+ for (i, (name, role)) in [("Cook", "recipes planner"), ("Chef", "Kitchen helper"), ("Menu", "Weekly recipe planner")].iter().enumerate() {+ let token = turn(&e, &format!("t-d2{i}")).await;+ let text = refused(&e, &token, specialist(name, role)).await;+ assert!(text.contains("turned down"), "{name}: {text}");+ }+ // A different kind of bot is fine+ let token = turn(&e, "t-d3").await;+ ok(&e, &token, specialist("Taxman", "Tax advisor")).await;+ // When the person asks for one, it may be proposed again, but it asks: never automatic+ let token = turn(&e, "t-d4").await;+ let mut asked = specialist("Cook", "Recipe planner");+ asked["requested_by_person"] = json!(true);+ ok(&e, &token, asked).await;+ let h = latest(&e).await;+ assert_eq!(h["status"], "pending");+ assert!(bot_named(&e, "spc_default", "Cook").await.is_none());++ // Another space doesn't inherit the denial+ let (status, space) = call(&e.app, "POST", "/api/spaces", None, Some(json!({"name": "Home"}))).await;+ assert_eq!(status, StatusCode::CREATED, "{space}");+ let sid = space["id"].as_str().unwrap();+ let (status, other) = call(&e.app, "POST", &format!("/api/kwants?space={sid}"), None, Some(json!({"name": "Helper", "title": "Generalist",+ "persona_prompt": "x", "avatar_sprite": "default", "driver_type": "api", "preferred_model": "auto"}))).await;+ assert_eq!(status, StatusCode::OK, "{other}");+ let other = e.state.db.get_kwant(other["id"].as_str().unwrap()).await.unwrap().unwrap();+ let home_general = e.state.db.list_channels(&SpaceId::new(sid)).await.unwrap().into_iter().find(|c| c.name == "general").unwrap();+ let token = turn_of(&e, &other, &home_general.id, "t-home").await;+ ok(&e, &token, specialist("Chef", "Recipe planner")).await;+ let home = hires(&e, sid).await;+ assert_eq!(home.len(), 1);+ assert_eq!(home[0]["status"], "pending", "Home's policy is its own: ask");+ let (_, p) = call(&e.app, "GET", &format!("/api/spaces/{sid}/hire-policy"), None, None).await;+ assert_eq!(p["denied"], json!([]));+ // A team from another space is refused+ let token = turn_of(&e, &other, &home_general.id, "t-home2").await;+ let mut cross = specialist("Taxman", "Tax advisor");+ cross["team"] = json!(e.state.db.get_team_by_name(&SpaceId::default_space(), "core-engineering").await.unwrap().unwrap().id);+ assert!(refused(&e, &token, cross).await.contains("another space"));++ // The person clears the denials: the kind can be proposed again+ let (status, p) = call(&e.app, "PUT", "/api/spaces/spc_default/hire-policy", None, Some(json!({"policy": "ask", "clear_denials": true}))).await;+ assert_eq!(status, StatusCode::OK, "{p}");+ assert_eq!(p["denied"], json!([]));+}++#[tokio::test]+async fn the_policy_and_decisions_appear_in_the_next_turn() {+ let e = setup().await;+ let ctx = next_turn_context(&e).await;+ assert!(ctx.contains("[Hiring new bots in this space]") && ctx.contains("ask the person each time"), "{ctx}");+ assert!(ctx.contains("yourself first"), "{ctx}");++ let token = turn(&e, "t-c1").await;+ ok(&e, &token, specialist("Chef", "Recipe planner")).await;+ let ctx = next_turn_context(&e).await;+ assert!(ctx.contains("Chef (Recipe planner): waiting for the person"), "{ctx}");++ let id = latest(&e).await["id"].as_str().unwrap().to_string();+ call(&e.app, "POST", &format!("/api/hires/{id}/deny"), None, None).await;+ let token = turn(&e, "t-c2").await;+ ok(&e, &token, specialist("Taxman", "Tax advisor")).await;+ let id = latest(&e).await["id"].as_str().unwrap().to_string();+ call(&e.app, "POST", &format!("/api/hires/{id}/accept"), None, Some(json!({"always": true}))).await;++ let ctx = next_turn_context(&e).await;+ assert!(ctx.contains("always accept"), "{ctx}");+ assert!(ctx.contains("3 of 3 automatic hires left"), "{ctx}");+ assert!(ctx.contains("Chef (Recipe planner): DENIED") && ctx.contains("unless the person asks"), "{ctx}");+ assert!(ctx.contains("Taxman (Tax advisor): hired (the person accepted once)"), "{ctx}");++ // Another space's bots see none of it+ let (_, space) = call(&e.app, "POST", "/api/spaces", None, Some(json!({"name": "Home"}))).await;+ let sid = space["id"].as_str().unwrap();+ let (_, other) = call(&e.app, "POST", &format!("/api/kwants?space={sid}"), None, Some(json!({"name": "Helper", "title": "Generalist",+ "persona_prompt": "x", "avatar_sprite": "default", "driver_type": "api", "preferred_model": "auto"}))).await;+ let other = e.state.db.get_kwant(other["id"].as_str().unwrap()).await.unwrap().unwrap();+ let ctx = continuity::prompt_block(&e.state, &other, None, None, true).await;+ assert!(ctx.contains("ask the person each time") && !ctx.contains("Chef") && !ctx.contains("Taxman"), "{ctx}");+}diff --git a/tests/spaces_migration_test.rs b/tests/spaces_migration_test.rsindex 9f2ba74e..afe594b8 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', 'bot_actions') 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', 'hire_proposals', 'hire_policies') ORDER BY name",).fetch_all(pool).await