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.

Bot import and export: kwant.bundle/1, parsers, preview/apply/undo, 16k persona/soul cap

Lin (kwant bot)6c114dfac342
diff --git a/Cargo.lock b/Cargo.lock
index 95b5f130..9b3418d0 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -257,6 +257,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
[[package]]
name = "chrono"
version = "0.4.45"
@@ -394,6 +400,15 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
+[[package]]
+name = "crc32fast"
+version = "1.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
+dependencies = [
+ "cfg-if",
+]
+
[[package]]
name = "crossbeam-queue"
version = "0.3.14"
@@ -578,6 +593,15 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
+[[package]]
+name = "flate2"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
+dependencies = [
+ "zlib-rs",
+]
+
[[package]]
name = "flume"
version = "0.11.1"
@@ -1164,6 +1188,7 @@ dependencies = [
"rust-embed",
"serde",
"serde_json",
+ "serde_norway",
"sha2 0.10.9",
"sqlx",
"tempfile",
@@ -1180,6 +1205,7 @@ dependencies = [
"tz-rs",
"url",
"uuid",
+ "zip",
]
[[package]]
@@ -1334,6 +1360,18 @@ dependencies = [
"tempfile",
]
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+]
+
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
@@ -1931,6 +1969,19 @@ dependencies = [
"zmij",
]
+[[package]]
+name = "serde_norway"
+version = "0.9.42"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e408f29489b5fd500fab51ff1484fc859bb655f32c671f307dcd733b72e8168c"
+dependencies = [
+ "indexmap",
+ "itoa",
+ "ryu",
+ "serde",
+ "unsafe-libyaml-norway",
+]
+
[[package]]
name = "serde_path_to_error"
version = "0.1.20"
@@ -2031,6 +2082,12 @@ dependencies = [
"rand_core",
]
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
[[package]]
name = "simdutf8"
version = "0.1.5"
@@ -2744,6 +2801,12 @@ dependencies = [
"utf-8",
]
+[[package]]
+name = "typed-path"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
+
[[package]]
name = "typenum"
version = "1.20.1"
@@ -2789,6 +2852,12 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
+[[package]]
+name = "unsafe-libyaml-norway"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39abd59bf32521c7f2301b52d05a6a2c975b6003521cbd0c6dc1582f0a22104"
+
[[package]]
name = "untrusted"
version = "0.9.0"
@@ -3338,8 +3407,41 @@ dependencies = [
"syn 3.0.9",
]
+[[package]]
+name = "zip"
+version = "9.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e"
+dependencies = [
+ "crc32fast",
+ "flate2",
+ "indexmap",
+ "memchr",
+ "nix",
+ "typed-path",
+ "zopfli",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
+
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zopfli"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
+dependencies = [
+ "bumpalo",
+ "crc32fast",
+ "log",
+ "simd-adler32",
+]
diff --git a/Cargo.toml b/Cargo.toml
index e5bbba7a..8e369aa7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -41,6 +41,8 @@ base64 = "0.22"
url = "2"
tz-rs = "0.7"
percent-encoding = "2"
+zip = { version = "9", default-features = false, features = ["deflate"] }
+serde_norway = "0.9"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
diff --git a/src/db/imports.rs b/src/db/imports.rs
new file mode 100644
index 00000000..6cc0c6ba
--- /dev/null
+++ b/src/db/imports.rs
@@ -0,0 +1,602 @@
+//! Imports: applying a checked [`Bundle`] in one transaction, remembering exactly what it
+//! created (ids only, never the content), undoing it, and exporting bots back out as bundles.
+
+use super::models::Kwant;
+use super::spaces::SpaceId;
+use super::{Database, DbError};
+use crate::import::{scrub, BotSpec, Bundle, RoutineSpec, SkillSpec, Source, TeamSpec, BUNDLE_FORMAT};
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use sqlx::FromRow;
+use std::collections::HashMap;
+use uuid::Uuid;
+
+/// The avatars kwant draws; an import's `avatar_hint` is used when it names one.
+pub 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",
+];
+
+/// One bot an import created, and what it looked like then (to tell if it was edited since).
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct CreatedKwant {
+ #[serde(rename = "ref")]
+ pub ref_: String,
+ pub id: String,
+ pub name: String,
+ pub fingerprint: String,
+}
+
+/// Everything an import created, by id.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct Created {
+ pub kwants: Vec<CreatedKwant>,
+ pub skills: Vec<String>,
+ pub routines: Vec<String>,
+ pub teams: Vec<String>,
+ pub channels: Vec<String>,
+ pub memories: usize,
+}
+
+#[derive(Debug, Clone, FromRow)]
+struct ImportRow {
+ id: String,
+ space_id: String,
+ source_kind: String,
+ created: String,
+ status: String,
+ created_at: DateTime<Utc>,
+ undone_at: Option<DateTime<Utc>>,
+}
+
+/// An import as the API shows it.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct ImportRecord {
+ pub id: String,
+ pub space_id: String,
+ pub source_kind: String,
+ /// `applied` or `undone`.
+ pub status: String,
+ pub created: Created,
+ pub created_at: DateTime<Utc>,
+ pub undone_at: Option<DateTime<Utc>>,
+}
+
+impl TryFrom<ImportRow> for ImportRecord {
+ type Error = DbError;
+ fn try_from(r: ImportRow) -> Result<Self, DbError> {
+ Ok(ImportRecord {
+ id: r.id,
+ space_id: r.space_id,
+ source_kind: r.source_kind,
+ status: r.status,
+ created: serde_json::from_str(&r.created)?,
+ created_at: r.created_at,
+ undone_at: r.undone_at,
+ })
+ }
+}
+
+/// Why an import can't be undone.
+#[derive(Debug)]
+pub enum UndoError {
+ NotFound,
+ AlreadyUndone,
+ /// Bots changed since the import; undoing again with `force` removes them anyway.
+ Edited(Vec<String>),
+ /// Bots that have been used (chats, threads, files, …): never removed by undo.
+ InUse(Vec<String>),
+ Db(DbError),
+}
+
+impl From<DbError> for UndoError {
+ fn from(e: DbError) -> Self {
+ UndoError::Db(e)
+ }
+}
+
+impl From<sqlx::Error> for UndoError {
+ fn from(e: sqlx::Error) -> Self {
+ UndoError::Db(e.into())
+ }
+}
+
+/// What a bot looks like, as a hash: name, title, instructions, soul, avatar and model.
+fn fingerprint(name: &str, title: &str, persona: &str, soul: &str, avatar: &str, model: &str) -> String {
+ let mut h = Sha256::new();
+ for part in [name, title, persona, soul, avatar, model] {
+ h.update((part.len() as u64).to_le_bytes());
+ h.update(part.as_bytes());
+ }
+ format!("{:x}", h.finalize())
+}
+
+fn kwant_fingerprint(k: &Kwant) -> String {
+ fingerprint(&k.name, &k.title, &k.persona_prompt, &k.soul, &k.avatar_sprite, &k.preferred_model)
+}
+
+/// What kwant's own history tables say about a kwant: anything here means it has been used.
+const USE_CHECKS: [(&str, &str); 9] = [
+ (
+ "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 has chat history",
+ ),
+ ("SELECT COUNT(*) FROM threads WHERE kwant_id = ?1", "it has threads"),
+ ("SELECT COUNT(*) FROM delegations WHERE lead_kwant_id = ?1 OR specialist_kwant_id = ?1", "it has delegated work"),
+ ("SELECT COUNT(*) FROM questions WHERE kwant_id = ?1", "it asked questions"),
+ ("SELECT COUNT(*) FROM attachments WHERE kwant_id = ?1 OR direct_kwant_id = ?1", "it has files"),
+ ("SELECT COUNT(*) FROM approvals WHERE kwant_id = ?1", "it has approvals"),
+ ("SELECT COUNT(*) FROM mcp_suggestions WHERE kwant_id = ?1 OR direct_kwant_id = ?1", "it suggested tools"),
+ ("SELECT COUNT(*) FROM hire_proposals WHERE kwant_id = ?1", "it proposed hiring bots"),
+ ("SELECT COUNT(*) FROM routine_runs WHERE routine_id IN (SELECT id FROM routines WHERE kwant_id = ?1)", "its routines have run"),
+];
+
+fn in_list(ids: &[String]) -> String {
+ vec!["?"; ids.len().max(1)].join(", ")
+}
+
+impl Database {
+ pub(super) async fn migrate_imports(&self) -> Result<(), DbError> {
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS imports (
+ id TEXT PRIMARY KEY,
+ space_id TEXT NOT NULL,
+ source_kind TEXT NOT NULL,
+ created TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('applied', 'undone')),
+ created_at TIMESTAMP NOT NULL,
+ undone_at TIMESTAMP
+ )",
+ "CREATE INDEX IF NOT EXISTS imports_by_space ON imports (space_id, created_at)",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ pub async fn get_import(&self, id: &str) -> Result<Option<ImportRecord>, DbError> {
+ let row = sqlx::query_as::<_, ImportRow>("SELECT * FROM imports WHERE id = ?").bind(id).fetch_optional(&self.pool).await?;
+ row.map(ImportRecord::try_from).transpose()
+ }
+
+ /// The space's imports, newest first.
+ pub async fn list_imports(&self, space: &SpaceId) -> Result<Vec<ImportRecord>, DbError> {
+ let rows = sqlx::query_as::<_, ImportRow>("SELECT * FROM imports WHERE space_id = ? ORDER BY created_at DESC, rowid DESC LIMIT 100")
+ .bind(space.as_str())
+ .fetch_all(&self.pool)
+ .await?;
+ rows.into_iter().map(ImportRecord::try_from).collect()
+ }
+
+ /// Creates everything in a bundle that [`crate::import::normalize`] checked, in one
+ /// transaction: bots (no tools, model `auto`), memories, skills `pending`, routines paused,
+ /// teams with their channels, and the space's #general when it has none yet. Fails with
+ /// [`DbError::Conflict`] if a bot or team name was taken in the meantime.
+ pub async fn apply_import(&self, space: &SpaceId, bundle: &Bundle) -> Result<ImportRecord, DbError> {
+ let mut created = Created::default();
+ let now = Utc::now();
+ let mut tx = self.pool.begin().await?;
+ let mut ids: HashMap<&str, String> = HashMap::new();
+
+ for bot in &bundle.bots {
+ let (taken,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM kwants WHERE space_id = ? AND name = ? COLLATE NOCASE")
+ .bind(space.as_str())
+ .bind(&bot.name)
+ .fetch_one(&mut *tx)
+ .await?;
+ if taken > 0 {
+ return Err(DbError::Conflict(format!("a bot called {} already exists in this space; preview again", bot.name)));
+ }
+ let id = Uuid::new_v4().to_string();
+ let avatar = bot.avatar_hint.as_deref().filter(|a| AVATARS.contains(a)).unwrap_or("default");
+ sqlx::query(
+ "INSERT INTO kwants (id, name, title, persona_prompt, soul, avatar_sprite, driver_type, preferred_model, space_id)
+ VALUES (?, ?, ?, ?, ?, ?, 'api', 'auto', ?)",
+ )
+ .bind(&id)
+ .bind(&bot.name)
+ .bind(&bot.title)
+ .bind(&bot.persona_prompt)
+ .bind(&bot.soul)
+ .bind(avatar)
+ .bind(space.as_str())
+ .execute(&mut *tx)
+ .await?;
+ // No tools: opted out of every MCP server the space has now.
+ sqlx::query("INSERT OR IGNORE INTO kwant_mcp_disabled (kwant_id, server_id) SELECT ?, id FROM mcp_servers WHERE space_id = ?")
+ .bind(&id)
+ .bind(space.as_str())
+ .execute(&mut *tx)
+ .await?;
+ for text in &bot.memories {
+ sqlx::query("INSERT INTO kwant_memories (id, kwant_id, text, source, created_at, updated_at) VALUES (?, ?, ?, 'user', ?, ?)")
+ .bind(Uuid::new_v4().to_string())
+ .bind(&id)
+ .bind(text)
+ .bind(now)
+ .bind(now)
+ .execute(&mut *tx)
+ .await?;
+ created.memories += 1;
+ }
+ for skill in &bot.skills {
+ created.skills.push(insert_pending_skill(&mut tx, space, Some(&id), skill, now).await?);
+ }
+ for r in &bot.routines {
+ created.routines.push(insert_paused_routine(&mut tx, space, &id, r, now).await?);
+ }
+ created.kwants.push(CreatedKwant {
+ ref_: bot.ref_.clone(),
+ id: id.clone(),
+ name: bot.name.clone(),
+ fingerprint: fingerprint(&bot.name, &bot.title, &bot.persona_prompt, &bot.soul, avatar, "auto"),
+ });
+ ids.insert(bot.ref_.as_str(), id);
+ }
+ for skill in &bundle.skills {
+ created.skills.push(insert_pending_skill(&mut tx, space, None, skill, now).await?);
+ }
+
+ for team in &bundle.teams {
+ let members: Vec<String> = team.members.iter().filter_map(|r| ids.get(r.as_str()).cloned()).collect();
+ let Some(lead) = team.lead.as_deref().and_then(|r| ids.get(r)).or(members.first()).cloned() else { continue };
+ let name = free_team_name(&mut tx, space, &team.name).await?;
+ let team_id = Uuid::new_v4().to_string();
+ let members_json = serde_json::to_string(&members)?;
+ sqlx::query(
+ "INSERT INTO teams (id, name, description, icon, lead_kwant_id, member_kwants, space_id, instructions) VALUES (?, ?, ?, 'users', ?, ?, ?, ?)",
+ )
+ .bind(&team_id)
+ .bind(&name)
+ .bind(Some(format!("Imported from {}", bundle.source.kind)))
+ .bind(&lead)
+ .bind(&members_json)
+ .bind(space.as_str())
+ .bind(&team.instructions)
+ .execute(&mut *tx)
+ .await?;
+ created.teams.push(team_id);
+ let channel = format!("team-{name}");
+ let (exists,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM channels WHERE space_id = ? AND name = ?")
+ .bind(space.as_str())
+ .bind(&channel)
+ .fetch_one(&mut *tx)
+ .await?;
+ if exists == 0 {
+ created.channels.push(insert_channel(&mut tx, space, &channel, None, &lead, &members_json).await?);
+ }
+ }
+
+ // A new space's #general appears with its first bot, as when one is created by hand.
+ if let (false, Some(first)) = (space.is_default(), created.kwants.first()) {
+ let (general,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM channels WHERE space_id = ? AND name = 'general'")
+ .bind(space.as_str())
+ .fetch_one(&mut *tx)
+ .await?;
+ if general == 0 {
+ let members = serde_json::to_string(&[&first.id])?;
+ created.channels.push(insert_channel(&mut tx, space, "general", Some(super::GENERAL_DESCRIPTION), &first.id, &members).await?);
+ }
+ }
+
+ let id = Uuid::new_v4().to_string();
+ sqlx::query("INSERT INTO imports (id, space_id, source_kind, created, status, created_at) VALUES (?, ?, ?, ?, 'applied', ?)")
+ .bind(&id)
+ .bind(space.as_str())
+ .bind(&bundle.source.kind)
+ .bind(serde_json::to_string(&created)?)
+ .bind(now)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ self.get_import(&id).await?.ok_or(DbError::Sqlx(sqlx::Error::RowNotFound))
+ }
+
+ /// Removes exactly what an import created, in one transaction. Bots that were used since
+ /// (chats, threads, files, other skills, leading something the import didn't make) are
+ /// never removed; bots that were only edited are removed with `force`. Bots already
+ /// deleted by hand are skipped.
+ pub async fn undo_import(&self, id: &str, force: bool) -> Result<ImportRecord, UndoError> {
+ let record = self.get_import(id).await?.ok_or(UndoError::NotFound)?;
+ if record.status != "applied" {
+ return Err(UndoError::AlreadyUndone);
+ }
+ let c = &record.created;
+ let mut live = Vec::new();
+ let mut edited = Vec::new();
+ for k in &c.kwants {
+ if let Some(now) = self.get_kwant(&k.id).await? {
+ if kwant_fingerprint(&now) != k.fingerprint {
+ edited.push(now.name.clone());
+ }
+ live.push(now);
+ }
+ }
+ let mut in_use = Vec::new();
+ for k in &live {
+ if let Some(why) = self.used_since_import(&k.id, c).await? {
+ in_use.push(format!("{} ({why})", k.name));
+ }
+ }
+ if !c.channels.is_empty() {
+ let sql = format!("SELECT name FROM channels WHERE id IN ({}) AND id IN (SELECT channel_id FROM messages)", in_list(&c.channels));
+ let mut q = sqlx::query_as::<_, (String,)>(&sql);
+ for ch in &c.channels {
+ q = q.bind(ch);
+ }
+ for (name,) in q.fetch_all(&self.pool).await? {
+ in_use.push(format!("#{name} (it has messages)"));
+ }
+ }
+ if !in_use.is_empty() {
+ return Err(UndoError::InUse(in_use));
+ }
+ if !edited.is_empty() && !force {
+ return Err(UndoError::Edited(edited));
+ }
+
+ let mut tx = self.pool.begin().await?;
+ for table in ["teams", "channels"] {
+ let list = if table == "teams" { &c.teams } else { &c.channels };
+ for row in list {
+ sqlx::query(&format!("DELETE FROM {table} WHERE id = ?")).bind(row).execute(&mut *tx).await?;
+ }
+ }
+ for skill in &c.skills {
+ sqlx::query("DELETE FROM skills WHERE id = ?").bind(skill).execute(&mut *tx).await?;
+ }
+ for routine in &c.routines {
+ sqlx::query("DELETE FROM routine_runs WHERE routine_id = ?").bind(routine).execute(&mut *tx).await?;
+ sqlx::query("DELETE FROM routines WHERE id = ?").bind(routine).execute(&mut *tx).await?;
+ }
+ for k in &live {
+ 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(&k.id).execute(&mut *tx).await?;
+ }
+ // Memberships the person added since (another team or channel) go with it.
+ 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(&k.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 != k.id).collect();
+ sqlx::query(&format!("UPDATE {table} SET member_kwants = ? WHERE id = ?"))
+ .bind(serde_json::to_string(&kept).map_err(DbError::from)?)
+ .bind(&row_id)
+ .execute(&mut *tx)
+ .await?;
+ }
+ }
+ sqlx::query("DELETE FROM kwants WHERE id = ?").bind(&k.id).execute(&mut *tx).await?;
+ }
+ sqlx::query("UPDATE imports SET status = 'undone', undone_at = ? WHERE id = ? AND status = 'applied'")
+ .bind(Utc::now())
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ self.get_import(id).await?.ok_or(UndoError::NotFound)
+ }
+
+ /// Why an imported kwant can't be removed by undo: history, or rows the import didn't make.
+ async fn used_since_import(&self, kwant_id: &str, c: &Created) -> Result<Option<&'static str>, DbError> {
+ for (sql, why) in USE_CHECKS {
+ let (n,): (i64,) = sqlx::query_as(sql).bind(kwant_id).fetch_one(&self.pool).await?;
+ if n > 0 {
+ return Ok(Some(why));
+ }
+ }
+ let foreign: [(&str, &[String], &'static str); 3] = [
+ ("SELECT COUNT(*) FROM skills WHERE kwant_id = ? AND id NOT IN ({})", &c.skills, "it has skills added after the import"),
+ ("SELECT COUNT(*) FROM channels WHERE lead_kwant_id = ? AND id NOT IN ({})", &c.channels, "it leads a channel"),
+ ("SELECT COUNT(*) FROM teams WHERE lead_kwant_id = ? AND id NOT IN ({})", &c.teams, "it leads a team"),
+ ];
+ for (sql, ours, why) in foreign {
+ let sql = sql.replace("{}", &in_list(ours));
+ let mut q = sqlx::query_as::<_, (i64,)>(&sql).bind(kwant_id);
+ if ours.is_empty() {
+ q = q.bind("");
+ }
+ for id in ours {
+ q = q.bind(id);
+ }
+ if q.fetch_one(&self.pool).await?.0 > 0 {
+ return Ok(Some(why));
+ }
+ }
+ Ok(None)
+ }
+
+ /// One bot as a bundle entry: profile, memories, its live and pending skills, routines
+ /// (with their schedules) and the names of its tools. Keys are scrubbed by the caller.
+ async fn export_bot(&self, k: &Kwant) -> Result<BotSpec, DbError> {
+ let memories = self.list_memories(&k.id).await?.into_iter().map(|m| m.text).collect();
+ let skills: Vec<SkillSpec> = sqlx::query_as::<_, (String, String, String)>(
+ "SELECT name, description, body FROM skills WHERE kwant_id = ? AND status IN ('enabled', 'disabled', 'pending') ORDER BY name, created_at",
+ )
+ .bind(&k.id)
+ .fetch_all(&self.pool)
+ .await?
+ .into_iter()
+ .map(|(name, description, body)| SkillSpec { name, description, body })
+ .collect();
+ let routines = sqlx::query_as::<_, (String, String, String)>(
+ "SELECT name, instructions, schedule FROM routines WHERE kwant_id = ? ORDER BY created_at, rowid",
+ )
+ .bind(&k.id)
+ .fetch_all(&self.pool)
+ .await?
+ .into_iter()
+ .map(|(name, instructions, schedule)| RoutineSpec { name, instructions, schedule: serde_json::from_str(&schedule).ok(), schedule_text: None })
+ .collect();
+ let tool_hints = self.list_active_mcp_servers_for_kwant(&k.id).await?.into_iter().map(|s| s.name).collect();
+ Ok(BotSpec {
+ ref_: k.name.clone(),
+ name: k.name.clone(),
+ title: k.title.clone(),
+ persona_prompt: k.persona_prompt.clone(),
+ soul: k.soul.clone(),
+ avatar_hint: Some(k.avatar_sprite.clone()),
+ model_hint: Some(k.preferred_model.clone()),
+ memories,
+ skills,
+ routines,
+ tool_hints,
+ ..BotSpec::default()
+ })
+ }
+
+ /// A bundle with one bot.
+ pub async fn export_kwant(&self, id: &str) -> Result<Option<Bundle>, DbError> {
+ let Some(k) = self.get_kwant(id).await? else { return Ok(None) };
+ let mut b = export_bundle(format!("bot {}", k.name));
+ b.bots.push(self.export_bot(&k).await?);
+ scrub::scrub_bundle(&mut b);
+ Ok(Some(b))
+ }
+
+ /// A bundle with every bot and team in the space, and its shared skills.
+ pub async fn export_space(&self, space: &SpaceId) -> Result<Bundle, DbError> {
+ let label = self.get_space(space).await?.map(|s| s.name).unwrap_or_else(|| space.as_str().to_string());
+ let mut b = export_bundle(format!("space {label}"));
+ let kwants = self.list_kwants(space).await?;
+ let names: HashMap<&str, &str> = kwants.iter().map(|k| (k.id.as_str(), k.name.as_str())).collect();
+ for k in &kwants {
+ b.bots.push(self.export_bot(k).await?);
+ }
+ for t in self.list_teams(space).await? {
+ let members: Vec<String> = serde_json::from_str::<Vec<String>>(&t.member_kwants)
+ .unwrap_or_default()
+ .iter()
+ .filter_map(|id| names.get(id.as_str()).map(|n| n.to_string()))
+ .collect();
+ b.teams.push(TeamSpec {
+ name: t.name.clone(),
+ lead: names.get(t.lead_kwant_id.as_str()).map(|n| n.to_string()),
+ members,
+ instructions: t.instructions.clone().filter(|i| !i.is_empty()),
+ });
+ }
+ b.skills = sqlx::query_as::<_, (String, String, String)>(
+ "SELECT name, description, body FROM skills WHERE kwant_id IS NULL AND space_id = ? AND status IN ('enabled', 'disabled', 'pending') ORDER BY name",
+ )
+ .bind(space.as_str())
+ .fetch_all(&self.pool)
+ .await?
+ .into_iter()
+ .map(|(name, description, body)| SkillSpec { name, description, body })
+ .collect();
+ scrub::scrub_bundle(&mut b);
+ Ok(b)
+ }
+}
+
+fn export_bundle(label: String) -> Bundle {
+ Bundle {
+ format: BUNDLE_FORMAT.into(),
+ source: Source { kind: "kwant".into(), label: Some(label), exported_at: Some(Utc::now().to_rfc3339()) },
+ omitted: vec!["Chat history, files, tool connections and keys are never exported".into()],
+ ..Bundle::default()
+ }
+}
+
+async fn insert_pending_skill(
+ tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
+ space: &SpaceId,
+ kwant_id: Option<&str>,
+ skill: &SkillSpec,
+ now: DateTime<Utc>,
+) -> Result<String, DbError> {
+ let id = Uuid::new_v4().to_string();
+ sqlx::query(
+ "INSERT INTO skills (id, kwant_id, name, description, body, status, source, created_at, updated_at, space_id)
+ VALUES (?, ?, ?, ?, ?, 'pending', 'user', ?, ?, ?)",
+ )
+ .bind(&id)
+ .bind(kwant_id)
+ .bind(&skill.name)
+ .bind(&skill.description)
+ .bind(&skill.body)
+ .bind(now)
+ .bind(now)
+ .bind(space.as_str())
+ .execute(&mut **tx)
+ .await?;
+ Ok(id)
+}
+
+async fn insert_paused_routine(
+ tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
+ space: &SpaceId,
+ kwant_id: &str,
+ r: &RoutineSpec,
+ now: DateTime<Utc>,
+) -> Result<String, DbError> {
+ let schedule = r
+ .schedule
+ .clone()
+ .and_then(|v| serde_json::from_value::<crate::routines::Schedule>(v).ok())
+ .filter(|s| s.validate().is_ok())
+ .unwrap_or_else(crate::import::placeholder_schedule);
+ let id = Uuid::new_v4().to_string();
+ sqlx::query(
+ "INSERT INTO routines (id, kwant_id, channel_id, name, instructions, schedule, enabled, next_run_at, created_at, space_id)
+ VALUES (?, ?, NULL, ?, ?, ?, 0, NULL, ?, ?)",
+ )
+ .bind(&id)
+ .bind(kwant_id)
+ .bind(&r.name)
+ .bind(&r.instructions)
+ .bind(serde_json::to_string(&schedule)?)
+ .bind(now)
+ .bind(space.as_str())
+ .execute(&mut **tx)
+ .await?;
+ Ok(id)
+}
+
+async fn insert_channel(
+ tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
+ space: &SpaceId,
+ name: &str,
+ description: Option<&str>,
+ lead: &str,
+ members_json: &str,
+) -> Result<String, DbError> {
+ let id = Uuid::new_v4().to_string();
+ sqlx::query("INSERT INTO channels (id, name, description, lead_kwant_id, member_kwants, routing_mode, space_id) VALUES (?, ?, ?, ?, ?, 'auto', ?)")
+ .bind(&id)
+ .bind(name)
+ .bind(description)
+ .bind(lead)
+ .bind(members_json)
+ .bind(space.as_str())
+ .execute(&mut **tx)
+ .await?;
+ Ok(id)
+}
+
+/// `name`, or `name 2`, `name 3`, …: the first no team in the space has (any case).
+async fn free_team_name(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, space: &SpaceId, name: &str) -> Result<String, DbError> {
+ for n in 1..1000 {
+ let candidate = if n == 1 { name.to_string() } else { format!("{name} {n}") };
+ let (taken,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM teams WHERE space_id = ? AND name = ? COLLATE NOCASE")
+ .bind(space.as_str())
+ .bind(&candidate)
+ .fetch_one(&mut **tx)
+ .await?;
+ if taken == 0 {
+ return Ok(candidate);
+ }
+ }
+ Err(DbError::Conflict(format!("too many teams called {name}")))
+}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index ddba2d9c..c4cda901 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -12,6 +12,7 @@ pub mod custom_api;
pub mod mcp_suggestions;
pub mod bot_actions;
pub mod hires;
+pub mod imports;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -136,6 +137,7 @@ impl Database {
db.migrate_mcp_suggestions().await?;
db.migrate_bot_actions().await?;
db.migrate_hires().await?;
+ db.migrate_imports().await?;
}
Ok(db)
diff --git a/src/import/archive.rs b/src/import/archive.rs
new file mode 100644
index 00000000..51eb5977
--- /dev/null
+++ b/src/import/archive.rs
@@ -0,0 +1,151 @@
+//! Reading containers in memory, defensively: zips (no paths outside the archive, no nested
+//! archives, inflated size counted as it is read) and the text chunks of character-card PNGs.
+
+use super::{ImportError, MAX_FILE_BYTES, MAX_UNZIPPED_BYTES, MAX_ZIP_ENTRIES};
+use base64::Engine;
+use std::io::{Cursor, Read};
+
+/// One file read out of a zip.
+#[derive(Debug, Clone)]
+pub struct Entry {
+ pub path: String,
+ pub bytes: Vec<u8>,
+}
+
+/// What a zip held: the files kwant may read, and what it left alone.
+#[derive(Debug, Default)]
+pub struct Unzipped {
+ pub entries: Vec<Entry>,
+ pub skipped: Vec<String>,
+}
+
+const READ_EXTENSIONS: [&str; 4] = [".json", ".md", ".png", ".txt"];
+const ARCHIVE_EXTENSIONS: [&str; 9] = [".zip", ".gz", ".tgz", ".tar", ".7z", ".rar", ".xz", ".bz2", ".zst"];
+/// Chat history never comes in (v1), so these aren't even inflated.
+const CHAT_FILES: [&str; 3] = ["conversations.json", "chat.html", "conversations.html"];
+
+fn invalid(msg: &str) -> ImportError {
+ ImportError::Invalid(msg.into())
+}
+
+/// A path stays inside the archive: relative, no `..`, no drive letters.
+fn safe_path(name: &str) -> Option<String> {
+ let name = name.replace('\\', "/");
+ if name.starts_with('/') || name.contains(':') || name.contains('\0') {
+ return None;
+ }
+ if name.split('/').any(|part| part == "..") {
+ return None;
+ }
+ Some(name.trim_start_matches("./").to_string())
+}
+
+/// Reads the bot-relevant files of a zip. Rejects the whole zip for unsafe paths, nested
+/// archives, encryption, too many entries, or more than [`MAX_UNZIPPED_BYTES`] once inflated.
+pub fn read_zip(bytes: &[u8]) -> Result<Unzipped, ImportError> {
+ let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|_| invalid("This zip can't be read."))?;
+ if zip.len() > MAX_ZIP_ENTRIES {
+ return Err(invalid(&format!("This zip has more than {MAX_ZIP_ENTRIES} files.")));
+ }
+ let mut out = Unzipped::default();
+ let mut total: u64 = 0;
+ for i in 0..zip.len() {
+ let mut file = zip.by_index(i).map_err(|_| invalid("A file in this zip can't be read (it may be encrypted)."))?;
+ let raw_name = file.name().map_err(|_| invalid("A file name in this zip can't be read."))?.to_string();
+ let path = safe_path(&raw_name).ok_or_else(|| invalid("This zip has a file path that points outside it, so it wasn't opened."))?;
+ if file.is_dir() {
+ continue;
+ }
+ let lower = path.to_lowercase();
+ if ARCHIVE_EXTENSIONS.iter().any(|e| lower.ends_with(e)) {
+ return Err(invalid("This zip contains another archive. Unpack it and import the inner file instead."));
+ }
+ let base = lower.rsplit('/').next().unwrap_or(&lower);
+ if base.starts_with('.') || lower.starts_with("__macosx/") || CHAT_FILES.contains(&base) || !READ_EXTENSIONS.iter().any(|e| lower.ends_with(e)) {
+ out.skipped.push(path);
+ continue;
+ }
+ // The size header can lie, so count what actually comes out.
+ let mut buf = Vec::new();
+ (&mut file)
+ .take(MAX_FILE_BYTES as u64 + 1)
+ .read_to_end(&mut buf)
+ .map_err(|_| invalid("A file in this zip is damaged."))?;
+ if buf.len() > MAX_FILE_BYTES {
+ return Err(ImportError::TooLarge(format!("{path} is larger than 4 MB once unpacked.")));
+ }
+ total += buf.len() as u64;
+ if total > MAX_UNZIPPED_BYTES {
+ return Err(ImportError::TooLarge("This zip is larger than 50 MB once unpacked.".into()));
+ }
+ out.entries.push(Entry { path, bytes: buf });
+ }
+ Ok(out)
+}
+
+pub const PNG_SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
+
+/// The character card JSON in a PNG's `ccv3` (preferred) or `chara` text chunk.
+pub fn card_json_from_png(bytes: &[u8]) -> Result<serde_json::Value, ImportError> {
+ if !bytes.starts_with(&PNG_SIGNATURE) {
+ return Err(invalid("This isn't a PNG."));
+ }
+ let mut pos = PNG_SIGNATURE.len();
+ let (mut chara, mut ccv3) = (None, None);
+ while pos + 8 <= bytes.len() {
+ let len = u32::from_be_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) as usize;
+ let kind = &bytes[pos + 4..pos + 8];
+ let start = pos + 8;
+ let end = start.checked_add(len).filter(|e| e + 4 <= bytes.len()).ok_or_else(|| invalid("This PNG is damaged."))?;
+ let data = &bytes[start..end];
+ if kind == b"IEND" {
+ break;
+ }
+ let text = match kind {
+ b"tEXt" => data.iter().position(|b| *b == 0).map(|z| (&data[..z], &data[z + 1..])),
+ // keyword \0 compressed-flag method language \0 translated \0 text; compressed ones are skipped
+ b"iTXt" => data.iter().position(|b| *b == 0).and_then(|z| {
+ let rest = data.get(z + 1..)?;
+ if *rest.first()? != 0 {
+ return None;
+ }
+ let rest = rest.get(2..)?;
+ let lang_end = rest.iter().position(|b| *b == 0)?;
+ let rest = &rest[lang_end + 1..];
+ let tr_end = rest.iter().position(|b| *b == 0)?;
+ Some((&data[..z], &rest[tr_end + 1..]))
+ }),
+ _ => None,
+ };
+ if let Some((keyword, value)) = text {
+ match keyword {
+ b"ccv3" => ccv3 = Some(value),
+ b"chara" => chara = Some(value),
+ _ => {}
+ }
+ }
+ pos = end + 4;
+ }
+ let raw = ccv3.or(chara).ok_or_else(|| ImportError::Unsupported("This PNG has no character card in it.".into()))?;
+ let cleaned: Vec<u8> = raw.iter().copied().filter(|b| !b.is_ascii_whitespace()).collect();
+ let decoded = base64::engine::general_purpose::STANDARD
+ .decode(&cleaned)
+ .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(&cleaned))
+ .map_err(|_| invalid("The character card in this PNG isn't valid."))?;
+ serde_json::from_slice(&decoded).map_err(|_| invalid("The character card in this PNG isn't valid JSON."))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn unsafe_paths() {
+ assert_eq!(safe_path("agents/a.md").as_deref(), Some("agents/a.md"));
+ assert_eq!(safe_path("../x.md"), None);
+ assert_eq!(safe_path("a/../../x.md"), None);
+ assert_eq!(safe_path("/etc/passwd"), None);
+ assert_eq!(safe_path("C:\\x.md"), None);
+ assert_eq!(safe_path("a\\..\\x.md"), None);
+ }
+}
diff --git a/src/import/mod.rs b/src/import/mod.rs
new file mode 100644
index 00000000..96fe174c
--- /dev/null
+++ b/src/import/mod.rs
@@ -0,0 +1,647 @@
+//! Bringing bots in from other apps, and taking them out again.
+//!
+//! Every source (a Claude Code agent, a character card, a Grok Bot bundle, an OpenMausBot
+//! package, a pasted export-prompt reply, …) is first turned into one [`Bundle`] in memory.
+//! Only that bundle is checked ([`normalize`]), previewed and applied; the upload itself is never
+//! stored. See `IMPORT-API.md` in the onboarding notes for the HTTP side.
+
+pub mod archive;
+pub mod parsers;
+pub mod prompts;
+pub mod scrub;
+
+use crate::db::continuity::{clean_memory_text, MAX_INSTRUCTIONS_CHARS, MAX_MEMORIES_PER_KWANT, MAX_MEMORY_CHARS};
+use crate::db::skills::{clean_skill_name, clean_skill_text, MAX_PENDING_PER_KWANT, MAX_SKILL_DESCRIPTION_CHARS};
+use crate::routines::Schedule;
+use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
+
+pub const BUNDLE_FORMAT: &str = "kwant.bundle/1";
+
+/// Pasted text (an export-prompt reply).
+pub const MAX_TEXT_BYTES: usize = 256 * 1024;
+/// One JSON, Markdown or PNG file.
+pub const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;
+/// A zip as uploaded.
+pub const MAX_ZIP_BYTES: usize = 20 * 1024 * 1024;
+/// Everything read out of one zip, counted as it is inflated.
+pub const MAX_UNZIPPED_BYTES: u64 = 50 * 1024 * 1024;
+pub const MAX_ZIP_ENTRIES: usize = 500;
+pub const MAX_BOTS: usize = 50;
+pub const MAX_TEAMS: usize = 10;
+/// Instructions (`persona_prompt`) and `soul`, here and on every bot create and edit.
+pub const MAX_PERSONA_CHARS: usize = 16_000;
+pub const MAX_NAME_CHARS: usize = 40;
+pub const MAX_TITLE_CHARS: usize = 100;
+pub const MAX_ROUTINE_NAME_CHARS: usize = 100;
+pub const MAX_ROUTINES_PER_BOT: usize = 20;
+pub const MAX_STARTERS: usize = 10;
+pub const MAX_STARTER_CHARS: usize = 1_000;
+pub const MAX_HINTS: usize = 50;
+pub const MAX_HINT_CHARS: usize = 200;
+pub const MAX_SHARED_SKILLS: usize = 50;
+pub const MAX_TEAM_NAME_CHARS: usize = 60;
+
+/// The message every create and edit path gives for an over-long persona or soul.
+pub fn persona_too_long(field: &str) -> String {
+ format!("{field} can be at most 16,000 characters")
+}
+
+/// `None` when instructions and soul fit [`MAX_PERSONA_CHARS`], else the error to show.
+pub fn check_persona_caps(persona_prompt: &str, soul: &str) -> Option<String> {
+ if persona_prompt.chars().count() > MAX_PERSONA_CHARS {
+ return Some(persona_too_long("instructions"));
+ }
+ if soul.chars().count() > MAX_PERSONA_CHARS {
+ return Some(persona_too_long("soul"));
+ }
+ None
+}
+
+/// `kwant.bundle/1`: bots, their memories, skills and routines, and teams, from anywhere.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct Bundle {
+ pub format: String,
+ #[serde(default)]
+ pub source: Source,
+ #[serde(default)]
+ pub bots: Vec<BotSpec>,
+ #[serde(default)]
+ pub teams: Vec<TeamSpec>,
+ /// Skills not tied to one bot; they become the space's shared skills.
+ #[serde(default)]
+ pub skills: Vec<SkillSpec>,
+ /// What the source had that kwant doesn't import, in words.
+ #[serde(default)]
+ pub omitted: Vec<String>,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct Source {
+ /// `kwant`, `claude-code`, `skill`, `character-card`, `grokbot`, `openmaus`, `openmaus-grok`,
+ /// `prompt-reply`, or what an export-prompt reply says (`chatgpt`, `grok`, …).
+ #[serde(default)]
+ pub kind: String,
+ #[serde(default)]
+ pub label: Option<String>,
+ #[serde(default)]
+ pub exported_at: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct BotSpec {
+ /// The bot's id within the bundle; teams name bots by it.
+ #[serde(rename = "ref", default)]
+ pub ref_: String,
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub title: String,
+ /// The bot's instructions.
+ #[serde(default)]
+ pub persona_prompt: String,
+ #[serde(default)]
+ pub soul: String,
+ #[serde(default)]
+ pub avatar_hint: Option<String>,
+ #[serde(default)]
+ pub model_hint: Option<String>,
+ /// Conversation starters: shown in the preview; kwant has no field for them yet.
+ #[serde(default)]
+ pub starters: Vec<String>,
+ #[serde(default)]
+ pub memories: Vec<String>,
+ #[serde(default)]
+ pub skills: Vec<SkillSpec>,
+ #[serde(default)]
+ pub routines: Vec<RoutineSpec>,
+ /// Tools the bot used: shown, never connected.
+ #[serde(default)]
+ pub tool_hints: Vec<String>,
+ /// Files the bot had: "not imported, re-attach these".
+ #[serde(default)]
+ pub knowledge_files: Vec<String>,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct SkillSpec {
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub description: String,
+ #[serde(default)]
+ pub body: String,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct RoutineSpec {
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub instructions: String,
+ /// A kwant [`Schedule`] as JSON; when absent or invalid, `schedule_text` is read.
+ #[serde(default)]
+ pub schedule: Option<serde_json::Value>,
+ /// The schedule as the source wrote it: a cron line, `09:00`, `daily 09:00`, ….
+ #[serde(default)]
+ pub schedule_text: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct TeamSpec {
+ #[serde(default)]
+ pub name: String,
+ /// A bot `ref`.
+ #[serde(default)]
+ pub lead: Option<String>,
+ /// Bot `ref`s.
+ #[serde(default)]
+ pub members: Vec<String>,
+ #[serde(default)]
+ pub instructions: Option<String>,
+}
+
+/// Something the preview tells the person, about one bot (`bot` = its ref) or the whole import.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Notice {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub bot: Option<String>,
+ pub message: String,
+}
+
+impl Notice {
+ fn new(bot: Option<&str>, message: impl Into<String>) -> Self {
+ Notice { bot: bot.map(str::to_string), message: message.into() }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Rename {
+ #[serde(rename = "ref")]
+ pub ref_: String,
+ pub from: String,
+ pub to: String,
+}
+
+/// A checked bundle and what the person should know before applying it.
+#[derive(Debug, Clone, Serialize)]
+pub struct Checked {
+ pub bundle: Bundle,
+ /// Kept, but worth a look (a removed key, a suspicious line, a routine with no schedule, …).
+ pub warnings: Vec<Notice>,
+ /// Not imported (too long, too many, invalid).
+ pub dropped: Vec<Notice>,
+ /// Stop the import until fixed (instructions over 16,000 characters, too many bots).
+ pub problems: Vec<Notice>,
+ /// Bots that get a new name because the space (or the bundle) already has theirs.
+ pub renames: Vec<Rename>,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum ImportError {
+ /// 413
+ TooLarge(String),
+ /// 415: not a format kwant reads.
+ Unsupported(String),
+ /// 422: a known format with bad content, or an unsafe archive.
+ Invalid(String),
+}
+
+impl std::fmt::Display for ImportError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ ImportError::TooLarge(m) | ImportError::Unsupported(m) | ImportError::Invalid(m) => f.write_str(m),
+ }
+ }
+}
+
+impl std::error::Error for ImportError {}
+
+/// Cuts `s` to at most `max` characters.
+pub(crate) fn cut(s: &str, max: usize) -> String {
+ s.chars().take(max).collect()
+}
+
+/// A bot name kwant accepts: no spaces or `@`, at most [`MAX_NAME_CHARS`].
+pub fn clean_bot_name(raw: &str) -> String {
+ let joined = raw.split_whitespace().collect::<Vec<_>>().join("-");
+ let name: String = joined.chars().filter(|c| *c != '@' && !c.is_control()).collect();
+ let name = cut(name.trim_matches('-'), MAX_NAME_CHARS);
+ if name.is_empty() {
+ "Imported-bot".into()
+ } else {
+ name
+ }
+}
+
+/// `name`, or `name-2`, `name-3`, … : the first one nobody in `taken` (lowercase) has.
+fn free_name(name: &str, taken: &HashSet<String>) -> String {
+ if !taken.contains(&name.to_lowercase()) {
+ return name.to_string();
+ }
+ (2..)
+ .map(|n| {
+ let suffix = format!("-{n}");
+ format!("{}{suffix}", cut(name, MAX_NAME_CHARS - suffix.len()))
+ })
+ .find(|c| !taken.contains(&c.to_lowercase()))
+ .unwrap_or_else(|| name.to_string())
+}
+
+/// Splits a memory into entries of at most [`MAX_MEMORY_CHARS`]: at sentence ends when it can,
+/// else at spaces, else anywhere. Whitespace is collapsed as stored memories are.
+pub fn split_memory(text: &str) -> Vec<String> {
+ let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ let mut out = Vec::new();
+ let mut rest = text.as_str();
+ while rest.chars().count() > MAX_MEMORY_CHARS {
+ let limit = rest.char_indices().nth(MAX_MEMORY_CHARS).map(|(i, _)| i).unwrap_or(rest.len());
+ let head = &rest[..limit];
+ let at = head
+ .rmatch_indices([' '])
+ .map(|(i, _)| i)
+ .find(|&i| i > 0 && head[..i].ends_with(['.', '!', '?']))
+ .or_else(|| head.rfind(' ').filter(|&i| i > 0))
+ .unwrap_or(limit);
+ out.push(rest[..at].trim().to_string());
+ rest = rest[at..].trim_start();
+ }
+ if !rest.is_empty() {
+ out.push(rest.to_string());
+ }
+ out.retain(|s| !s.is_empty());
+ out
+}
+
+/// Reads a routine's schedule: kwant JSON first, then the source's text. Imported routines
+/// always arrive paused, so a schedule only has to be valid, not right.
+pub fn read_schedule(spec: &RoutineSpec) -> Option<Schedule> {
+ if let Some(v) = &spec.schedule {
+ if let Ok(s) = serde_json::from_value::<Schedule>(v.clone()) {
+ if s.validate().is_ok() {
+ return Some(s.canonical());
+ }
+ }
+ }
+ let text = spec.schedule_text.as_deref()?.trim();
+ schedule_from_text(text)
+}
+
+fn schedule_from_text(text: &str) -> Option<Schedule> {
+ let lower = text.to_lowercase();
+ let lower = lower.trim();
+ let tz = "UTC".to_string();
+ // "daily 09:00", "every day at 9:00", "09:00"
+ let time = lower
+ .trim_start_matches("every day")
+ .trim_start_matches("daily")
+ .trim_start_matches(" at")
+ .trim();
+ if let Some(t) = clock(time) {
+ return Some(Schedule::Daily { time: t, tz });
+ }
+ let fields: Vec<&str> = text.split_whitespace().collect();
+ if fields.len() == 5 {
+ let s = Schedule::Cron { expression: fields.join(" "), tz };
+ if s.validate().is_ok() {
+ return Some(s.canonical());
+ }
+ }
+ None
+}
+
+/// `H:MM` or `HH:MM` as `HH:MM`.
+fn clock(s: &str) -> Option<String> {
+ let (h, m) = s.split_once(':')?;
+ let (h, m): (u32, u32) = (h.parse().ok()?, m.parse().ok()?);
+ (h < 24 && m < 60).then(|| format!("{h:02}:{m:02}"))
+}
+
+/// What kwant puts in place of a schedule it couldn't read: the routine arrives paused anyway.
+pub fn placeholder_schedule() -> Schedule {
+ Schedule::Daily { time: "09:00".into(), tz: "UTC".into() }
+}
+
+/// Text that might be someone steering the bot rather than describing it. Flagged, never removed.
+pub fn suspicious(text: &str) -> Vec<&'static str> {
+ let lower = text.to_lowercase();
+ let mut found = Vec::new();
+ if lower.contains("http://") || lower.contains("https://") {
+ found.push("contains a web address");
+ }
+ if ["ignore previous", "ignore all previous", "ignore the above", "disregard previous", "disregard all previous"]
+ .iter()
+ .any(|p| lower.contains(p))
+ {
+ found.push("tells the bot to ignore earlier instructions");
+ }
+ if ["send it to", "send them to", "post it to", "upload it to", "forward it to", "email it to", "exfiltrat"]
+ .iter()
+ .any(|p| lower.contains(p))
+ {
+ found.push("tells the bot to send data somewhere");
+ }
+ if text.contains(['\u{200b}', '\u{200c}', '\u{200d}', '\u{2060}', '\u{feff}'])
+ || text.contains(" ")
+ || text.contains("\n\n\n\n\n\n\n\n\n\n")
+ {
+ found.push("has long or invisible whitespace that could hide text");
+ }
+ found
+}
+
+/// Checks and tidies `bundle` for a space whose bots are called `existing` (any case). Pure: the
+/// same input always gives the same result, so apply re-runs it on what the preview returned.
+pub fn normalize(mut bundle: Bundle, existing: &[String]) -> Checked {
+ let mut warnings = Vec::new();
+ let mut dropped = Vec::new();
+ let mut problems = Vec::new();
+ let mut renames = Vec::new();
+
+ bundle.format = BUNDLE_FORMAT.into();
+ bundle.source.kind = cut(bundle.source.kind.trim(), 40);
+ bundle.source.label = bundle.source.label.as_deref().map(|l| cut(l.trim(), 200));
+ bundle.source.exported_at = bundle.source.exported_at.as_deref().map(|l| cut(l.trim(), 40));
+
+ let mut refs = HashSet::new();
+ for (i, bot) in bundle.bots.iter_mut().enumerate() {
+ let mut r = cut(bot.ref_.trim(), 80);
+ let mut n = i + 1;
+ while r.is_empty() || refs.contains(&r) {
+ r = format!("bot-{n}");
+ n += 1;
+ }
+ refs.insert(r.clone());
+ bot.ref_ = r;
+ }
+
+ let removed = scrub::scrub_bundle(&mut bundle);
+ for (bot, count) in removed {
+ let what = if count == 1 { "something that looked like an API key" } else { "things that looked like API keys" };
+ warnings.push(Notice::new(bot.as_deref(), format!("We removed {what}. It shows as [removed key].")));
+ }
+
+ if bundle.bots.len() > MAX_BOTS {
+ problems.push(Notice::new(None, format!("One import can bring at most {MAX_BOTS} bots; this has {}.", bundle.bots.len())));
+ }
+ if bundle.teams.len() > MAX_TEAMS {
+ problems.push(Notice::new(None, format!("One import can bring at most {MAX_TEAMS} teams; this has {}.", bundle.teams.len())));
+ }
+
+ let mut taken: HashSet<String> = existing.iter().map(|n| n.to_lowercase()).collect();
+ for bot in bundle.bots.iter_mut() {
+ let r = bot.ref_.clone();
+ let who = Some(r.as_str());
+
+ let wanted = clean_bot_name(&bot.name);
+ let name = free_name(&wanted, &taken);
+ if name != wanted {
+ renames.push(Rename { ref_: r.clone(), from: wanted.clone(), to: name.clone() });
+ } else if wanted != bot.name.trim() {
+ warnings.push(Notice::new(who, format!("Bot names can't have spaces or @, so \"{}\" becomes {wanted}.", bot.name.trim())));
+ }
+ taken.insert(name.to_lowercase());
+ bot.name = name;
+
+ bot.title = cut(bot.title.split_whitespace().collect::<Vec<_>>().join(" ").as_str(), MAX_TITLE_CHARS);
+ if bot.title.is_empty() {
+ bot.title = "Imported bot".into();
+ }
+ bot.persona_prompt = bot.persona_prompt.replace("\r\n", "\n").trim().to_string();
+ bot.soul = bot.soul.replace("\r\n", "\n").trim().to_string();
+ if bot.persona_prompt.is_empty() {
+ warnings.push(Notice::new(who, "This bot has no instructions; it will act on its title alone until you add some."));
+ }
+ for (field, text) in [("instructions", &bot.persona_prompt), ("soul", &bot.soul)] {
+ let n = text.chars().count();
+ if n > MAX_PERSONA_CHARS {
+ problems.push(Notice::new(who, format!("{} ({n} now). Shorten it here before importing.", persona_too_long(&format!("{}'s {field}", bot.name)))));
+ }
+ for why in suspicious(text) {
+ warnings.push(Notice::new(who, format!("The {field} {why}. Read it before importing.")));
+ }
+ }
+ bot.avatar_hint = bot.avatar_hint.as_deref().map(|a| cut(a.trim(), 40)).filter(|a| !a.is_empty());
+ bot.model_hint = bot.model_hint.as_deref().map(|a| cut(a.trim(), 100)).filter(|a| !a.is_empty());
+ bot.starters = tidy_list(&bot.starters, MAX_STARTERS, MAX_STARTER_CHARS);
+ bot.tool_hints = tidy_list(&bot.tool_hints, MAX_HINTS, MAX_HINT_CHARS);
+ bot.knowledge_files = tidy_list(&bot.knowledge_files, MAX_HINTS, MAX_HINT_CHARS);
+ if let Some(model) = bot.model_hint.as_deref().filter(|m| !m.eq_ignore_ascii_case("auto")) {
+ warnings.push(Notice::new(who, format!("It used the model {model}; here it starts on auto. Pick a model after importing.")));
+ }
+ if !bot.tool_hints.is_empty() {
+ warnings.push(Notice::new(who, format!("It used tools ({}). Imported bots start with no tools; connect the ones it needs.", bot.tool_hints.join(", "))));
+ }
+ if !bot.knowledge_files.is_empty() {
+ dropped.push(Notice::new(who, format!("Files aren't brought over: {}. Attach them again if the bot needs them.", bot.knowledge_files.join(", "))));
+ }
+ if !bot.starters.is_empty() {
+ dropped.push(Notice::new(who, format!("{} conversation starter(s): kwant has no place for them yet.", bot.starters.len())));
+ }
+
+ let mut memories: Vec<String> = bot.memories.iter().flat_map(|m| split_memory(m)).collect();
+ if memories.len() > bot.memories.iter().filter(|m| !m.trim().is_empty()).count() {
+ warnings.push(Notice::new(who, format!("Long memories were split into entries of at most {MAX_MEMORY_CHARS} characters.")));
+ }
+ let cap = MAX_MEMORIES_PER_KWANT as usize;
+ if memories.len() > cap {
+ for m in &memories[cap..] {
+ dropped.push(Notice::new(who, format!("Memory (over the {cap}-memory limit): {}", cut(m, 80))));
+ }
+ memories.truncate(cap);
+ }
+ memories.retain(|m| clean_memory_text(m).is_ok());
+ bot.memories = memories;
+
+ bot.skills = tidy_skills(std::mem::take(&mut bot.skills), MAX_PENDING_PER_KWANT as usize, who, &mut warnings, &mut dropped);
+ bot.routines = tidy_routines(std::mem::take(&mut bot.routines), who, &mut warnings, &mut dropped);
+ }
+ bundle.skills = tidy_skills(std::mem::take(&mut bundle.skills), MAX_SHARED_SKILLS, None, &mut warnings, &mut dropped);
+
+ let mut team_names = HashSet::new();
+ let teams = std::mem::take(&mut bundle.teams);
+ for mut team in teams {
+ team.name = cut(team.name.split_whitespace().collect::<Vec<_>>().join(" ").as_str(), MAX_TEAM_NAME_CHARS);
+ let mut members: Vec<String> = Vec::new();
+ for m in team.lead.iter().chain(team.members.iter()) {
+ let m = m.trim().to_string();
+ if refs.contains(&m) && !members.contains(&m) {
+ members.push(m);
+ } else if !refs.contains(&m) {
+ warnings.push(Notice::new(None, format!("Team {}: {m} isn't a bot in this import, so it was left out.", team.name)));
+ }
+ }
+ if team.name.is_empty() || members.is_empty() || !team_names.insert(team.name.to_lowercase()) {
+ dropped.push(Notice::new(None, format!("Team \"{}\": it needs a unique name and at least one imported bot.", team.name)));
+ continue;
+ }
+ team.lead = members.first().cloned();
+ team.members = members;
+ team.instructions = team.instructions.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(|s| {
+ if s.chars().count() > MAX_INSTRUCTIONS_CHARS {
+ warnings.push(Notice::new(None, format!("Team {}'s instructions were cut to {MAX_INSTRUCTIONS_CHARS} characters.", team.name)));
+ }
+ cut(s, MAX_INSTRUCTIONS_CHARS)
+ });
+ bundle.teams.push(team);
+ }
+
+ bundle.omitted = tidy_list(&bundle.omitted, MAX_HINTS, MAX_HINT_CHARS);
+ Checked { bundle, warnings, dropped, problems, renames }
+}
+
+fn tidy_list(items: &[String], max_items: usize, max_chars: usize) -> Vec<String> {
+ let mut out: Vec<String> = Vec::new();
+ for i in items {
+ let i = cut(i.trim(), max_chars);
+ if !i.is_empty() && !out.contains(&i) {
+ out.push(i);
+ }
+ }
+ out.truncate(max_items);
+ out
+}
+
+fn tidy_skills(
+ skills: Vec<SkillSpec>,
+ max: usize,
+ who: Option<&str>,
+ warnings: &mut Vec<Notice>,
+ dropped: &mut Vec<Notice>,
+) -> Vec<SkillSpec> {
+ let mut out: Vec<SkillSpec> = Vec::new();
+ for s in skills {
+ let slug = slug(&s.name);
+ let description = if s.description.trim().is_empty() {
+ first_line(&s.body)
+ } else {
+ s.description.clone()
+ };
+ let description = cut(description.split_whitespace().collect::<Vec<_>>().join(" ").as_str(), MAX_SKILL_DESCRIPTION_CHARS);
+ let mut name = slug.clone();
+ let mut n = 2;
+ while out.iter().any(|o| o.name == name) {
+ name = format!("{}-{n}", cut(&slug, 44));
+ n += 1;
+ }
+ match clean_skill_text(&name, &description, &s.body) {
+ Ok(text) if out.len() < max => {
+ for why in suspicious(&text.body) {
+ warnings.push(Notice::new(who, format!("Skill {}: it {why}.", text.name)));
+ }
+ out.push(SkillSpec { name: text.name, description: text.description, body: text.body });
+ }
+ Ok(text) => dropped.push(Notice::new(who, format!("Skill {} (more than {max} skills).", text.name))),
+ Err(e) => dropped.push(Notice::new(who, format!("Skill {}: {e}.", if s.name.trim().is_empty() { "(unnamed)" } else { s.name.trim() }))),
+ }
+ }
+ out
+}
+
+fn tidy_routines(
+ routines: Vec<RoutineSpec>,
+ who: Option<&str>,
+ warnings: &mut Vec<Notice>,
+ dropped: &mut Vec<Notice>,
+) -> Vec<RoutineSpec> {
+ let mut out = Vec::new();
+ for r in routines {
+ let name = cut(r.name.split_whitespace().collect::<Vec<_>>().join(" ").as_str(), MAX_ROUTINE_NAME_CHARS);
+ let instructions = r.instructions.trim().to_string();
+ let label = if name.is_empty() { "(unnamed)".to_string() } else { name.clone() };
+ if name.is_empty() || instructions.is_empty() {
+ dropped.push(Notice::new(who, format!("Routine {label}: it needs a name and instructions.")));
+ continue;
+ }
+ if instructions.chars().count() > MAX_INSTRUCTIONS_CHARS {
+ dropped.push(Notice::new(who, format!("Routine {label}: instructions are longer than {MAX_INSTRUCTIONS_CHARS} characters.")));
+ continue;
+ }
+ if out.len() >= MAX_ROUTINES_PER_BOT {
+ dropped.push(Notice::new(who, format!("Routine {label} (more than {MAX_ROUTINES_PER_BOT} routines).")));
+ continue;
+ }
+ let schedule = match read_schedule(&r) {
+ Some(s) => s,
+ None => {
+ warnings.push(Notice::new(
+ who,
+ format!("Routine {label}: we couldn't read its schedule ({}), so it arrives paused at daily 09:00 UTC. Set the time before turning it on.", r.schedule_text.as_deref().unwrap_or("none")),
+ ));
+ placeholder_schedule()
+ }
+ };
+ out.push(RoutineSpec {
+ name,
+ instructions,
+ schedule: serde_json::to_value(&schedule).ok(),
+ schedule_text: r.schedule_text.map(|t| cut(t.trim(), 200)),
+ });
+ }
+ out
+}
+
+/// A skill name as kwant stores it, from whatever the source called it.
+pub(crate) fn slug(raw: &str) -> String {
+ let mut s = String::new();
+ for c in raw.trim().trim_start_matches('/').to_lowercase().chars() {
+ if c.is_ascii_lowercase() || c.is_ascii_digit() {
+ s.push(c);
+ } else if !s.ends_with('-') {
+ s.push('-');
+ }
+ }
+ let s = cut(s.trim_matches('-'), 48).trim_end_matches('-').to_string();
+ match clean_skill_name(&s) {
+ Ok(s) => s,
+ Err(_) => "imported-skill".into(),
+ }
+}
+
+/// The first non-empty line, without Markdown heading marks.
+pub(crate) fn first_line(text: &str) -> String {
+ text.lines()
+ .map(|l| l.trim().trim_start_matches('#').trim())
+ .find(|l| !l.is_empty() && *l != "---")
+ .unwrap_or("")
+ .to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn memories_split_at_sentences_and_fit() {
+ let long = "One sentence here. ".repeat(60);
+ let parts = split_memory(&long);
+ assert!(parts.len() > 1);
+ assert!(parts.iter().all(|p| p.chars().count() <= MAX_MEMORY_CHARS && p.ends_with('.')));
+ let no_spaces = "x".repeat(1200);
+ let parts = split_memory(&no_spaces);
+ assert_eq!(parts.len(), 3);
+ assert!(parts.iter().all(|p| p.chars().count() <= MAX_MEMORY_CHARS));
+ }
+
+ #[test]
+ fn names_are_cleaned_and_renamed_on_clash() {
+ assert_eq!(clean_bot_name(" Code Reviewer @x "), "Code-Reviewer-x");
+ assert_eq!(clean_bot_name(" "), "Imported-bot");
+ let taken: HashSet<String> = ["ada".into(), "ada-2".into()].into_iter().collect();
+ assert_eq!(free_name("Ada", &taken), "Ada-3");
+ }
+
+ #[test]
+ fn schedules_from_text() {
+ assert_eq!(schedule_from_text("09:30"), Some(Schedule::Daily { time: "09:30".into(), tz: "UTC".into() }));
+ assert_eq!(schedule_from_text("daily 7:05"), Some(Schedule::Daily { time: "07:05".into(), tz: "UTC".into() }));
+ assert!(matches!(schedule_from_text("0 9 * * 1-5"), Some(Schedule::Cron { .. })));
+ assert_eq!(schedule_from_text("whenever it feels right"), None);
+ }
+
+ #[test]
+ fn slugs() {
+ assert_eq!(slug("/Release Checklist!"), "release-checklist");
+ assert_eq!(slug("???"), "imported-skill");
+ }
+}
diff --git a/src/import/parsers.rs b/src/import/parsers.rs
new file mode 100644
index 00000000..d2b7b730
--- /dev/null
+++ b/src/import/parsers.rs
@@ -0,0 +1,604 @@
+//! Turning each supported source into a [`Bundle`]. Parsers only map fields; limits, names and
+//! secrets are handled once, in [`super::normalize`].
+//!
+//! | source | how it's recognised |
+//! |---|---|
+//! | `kwant.bundle/1` | JSON `"format": "kwant.bundle/1"` |
+//! | Claude Code agent | Markdown with `---` front matter (`name`, `description`, `tools`, `model`) |
+//! | Agent Skill | a `SKILL.md` (front matter `name`, `description`) |
+//! | Character Card V1/V2/V3 | JSON `"spec": "chara_card_v2"/"chara_card_v3"` or V1 fields; PNG `ccv3`/`chara` chunk |
+//! | Grok Bot | JSON `"format": "grokbot-bundle/v1"` |
+//! | OpenMausBot | JSON `"format": "openmaus.package"` (v1, v2), or `"openmaus.grok/1"` |
+//! | export-prompt reply | pasted text holding one of the JSON forms above, usually in a ```json block |
+//! | zip | any mix of the files above |
+
+use super::archive::{self, PNG_SIGNATURE};
+use super::scrub::drop_secret_fields;
+use super::{
+ cut, first_line, BotSpec, Bundle, ImportError, RoutineSpec, SkillSpec, Source, TeamSpec, BUNDLE_FORMAT, MAX_FILE_BYTES,
+ MAX_TEXT_BYTES, MAX_ZIP_BYTES,
+};
+use serde_json::Value;
+
+const ZIP_MAGIC: [u8; 4] = [b'P', b'K', 3, 4];
+const EMPTY_ZIP_MAGIC: [u8; 4] = [b'P', b'K', 5, 6];
+const MAX_FRONT_MATTER_BYTES: usize = 64 * 1024;
+
+fn unsupported() -> ImportError {
+ ImportError::Unsupported(
+ "kwant can't read this. Use a kwant bundle, a Claude Code agent or SKILL.md, a character card (JSON or PNG), \
+ a Grok Bot or OpenMausBot export, or paste the reply to the export prompt."
+ .into(),
+ )
+}
+
+fn invalid(msg: impl Into<String>) -> ImportError {
+ ImportError::Invalid(msg.into())
+}
+
+fn too_large(what: &str, limit: &str) -> ImportError {
+ ImportError::TooLarge(format!("{what} can be at most {limit}."))
+}
+
+/// An uploaded file. `filename` helps tell a SKILL.md from an agent.
+pub fn parse_file(bytes: &[u8], filename: Option<&str>) -> Result<Bundle, ImportError> {
+ if bytes.starts_with(&ZIP_MAGIC) || bytes.starts_with(&EMPTY_ZIP_MAGIC) {
+ if bytes.len() > MAX_ZIP_BYTES {
+ return Err(too_large("A zip", "20 MB"));
+ }
+ return from_zip(bytes);
+ }
+ if bytes.len() > MAX_FILE_BYTES {
+ return Err(too_large("A file", "4 MB"));
+ }
+ if bytes.starts_with(&PNG_SIGNATURE) {
+ return from_value(archive::card_json_from_png(bytes)?);
+ }
+ let text = std::str::from_utf8(bytes).map_err(|_| unsupported())?;
+ from_text(text, filename)
+}
+
+/// Pasted text: usually the reply to the export prompt.
+pub fn parse_pasted(text: &str) -> Result<Bundle, ImportError> {
+ if text.len() > MAX_TEXT_BYTES {
+ return Err(too_large("Pasted text", "256 KB"));
+ }
+ from_text(text, None)
+}
+
+fn from_text(text: &str, filename: Option<&str>) -> Result<Bundle, ImportError> {
+ let text = text.trim_start_matches('\u{feff}');
+ let trimmed = text.trim_start();
+ if trimmed.starts_with('{') {
+ let v: Value = serde_json::from_str(trimmed).map_err(|e| invalid(format!("This JSON isn't valid ({e}).")))?;
+ return from_value(v);
+ }
+ if trimmed.starts_with("---") {
+ return from_markdown(trimmed, filename);
+ }
+ let json = json_block(text).ok_or_else(|| {
+ invalid("We couldn't find a JSON block in this text. Paste the whole reply, including the ```json part.")
+ })?;
+ let v: Value = serde_json::from_str(json).map_err(|e| invalid(format!("The JSON block in this reply isn't valid ({e}).")))?;
+ let mut b = from_value(v)?;
+ if b.source.kind.is_empty() || b.source.kind == "kwant" {
+ b.source.kind = "prompt-reply".into();
+ }
+ Ok(b)
+}
+
+/// The JSON in a pasted reply: a ```json fence (or any fence starting with `{`), else the span
+/// from the first `{` to the last `}`.
+pub fn json_block(text: &str) -> Option<&str> {
+ let mut rest = text;
+ while let Some(open) = rest.find("```") {
+ let after = &rest[open + 3..];
+ let body_start = after.find('\n').map(|i| i + 1).unwrap_or(after.len());
+ let body = &after[body_start..];
+ let close = body.find("```").unwrap_or(body.len());
+ let inner = body[..close].trim();
+ // An unclosed fence runs to the end of the reply; the object still ends at its last brace.
+ if let (true, Some(end)) = (inner.starts_with('{'), inner.rfind('}')) {
+ return Some(&inner[..=end]);
+ }
+ rest = &body[(close + 3).min(body.len())..];
+ }
+ let (a, b) = (text.find('{')?, text.rfind('}')?);
+ (a < b).then(|| &text[a..=b])
+}
+
+/// Any of the JSON sources.
+pub fn from_value(mut v: Value) -> Result<Bundle, ImportError> {
+ drop_secret_fields(&mut v);
+ let format = v.get("format").and_then(Value::as_str).unwrap_or("").to_string();
+ let spec = v.get("spec").and_then(Value::as_str).unwrap_or("").to_string();
+ match (format.as_str(), spec.as_str()) {
+ (BUNDLE_FORMAT, _) => serde_json::from_value::<Bundle>(v).map_err(|e| invalid(format!("This kwant bundle isn't valid ({e})."))),
+ ("grokbot-bundle/v1", _) => Ok(from_grokbot(&v)),
+ ("openmaus.package", _) => from_openmaus_package(&v),
+ ("openmaus.grok/1", _) => Ok(from_openmaus_grok(&v)),
+ (_, "chara_card_v2" | "chara_card_v3") => Ok(from_card(v.get("data").unwrap_or(&Value::Null), &spec)),
+ _ if v.get("first_mes").is_some() && v.get("name").is_some() => Ok(from_card(&v, "chara_card_v1")),
+ _ => Err(unsupported()),
+ }
+}
+
+// ── helpers over loose JSON ───────────────────────────────────────────────
+
+fn s(v: &Value, key: &str) -> String {
+ match v.get(key) {
+ Some(Value::String(t)) => t.clone(),
+ Some(Value::Number(n)) => n.to_string(),
+ _ => String::new(),
+ }
+}
+
+/// The first non-empty string field of `keys`.
+fn any_s(v: &Value, keys: &[&str]) -> String {
+ keys.iter().map(|k| s(v, k)).find(|t| !t.trim().is_empty()).unwrap_or_default()
+}
+
+fn arr<'a>(v: &'a Value, key: &str) -> &'a [Value] {
+ v.get(key).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[])
+}
+
+/// Strings, or objects' `text`/`content`/`name`, from a list.
+fn texts(items: &[Value]) -> Vec<String> {
+ items
+ .iter()
+ .map(|i| match i {
+ Value::String(t) => t.clone(),
+ other => any_s(other, &["text", "content", "name", "id", "label"]),
+ })
+ .filter(|t| !t.trim().is_empty())
+ .collect()
+}
+
+fn bundle(kind: &str, label: Option<String>) -> Bundle {
+ Bundle {
+ format: BUNDLE_FORMAT.into(),
+ source: Source { kind: kind.into(), label, exported_at: None },
+ ..Bundle::default()
+ }
+}
+
+/// Memories written as a Markdown file: one per bullet or paragraph, headings left out.
+fn memories_from_markdown(text: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ let mut para = String::new();
+ for line in text.lines() {
+ let t = line.trim();
+ let bullet = t.strip_prefix("- ").or_else(|| t.strip_prefix("* "));
+ if t.is_empty() || t.starts_with('#') || bullet.is_some() {
+ if !para.trim().is_empty() {
+ out.push(std::mem::take(&mut para).trim().to_string());
+ }
+ para.clear();
+ if let Some(b) = bullet {
+ para.push_str(b);
+ }
+ continue;
+ }
+ para.push(' ');
+ para.push_str(t);
+ }
+ if !para.trim().is_empty() {
+ out.push(para.trim().to_string());
+ }
+ out
+}
+
+// ── Markdown: Claude Code agents and SKILL.md ─────────────────────────────
+
+/// Front matter as JSON, and the body after it.
+fn front_matter(text: &str) -> Result<(Value, &str), ImportError> {
+ let rest = text.trim_start().strip_prefix("---").ok_or_else(unsupported)?;
+ let end = rest.find("\n---").ok_or_else(|| invalid("The front matter (between the --- lines) isn't closed."))?;
+ let yaml = &rest[..end];
+ if yaml.len() > MAX_FRONT_MATTER_BYTES {
+ return Err(too_large("Front matter", "64 KB"));
+ }
+ let body = rest[end + 4..].trim_start_matches('-');
+ let body = body.strip_prefix("\r\n").or_else(|| body.strip_prefix('\n')).unwrap_or(body);
+ let v: Value = serde_norway::from_str(yaml).map_err(|_| invalid("The front matter isn't valid YAML."))?;
+ if !v.is_object() {
+ return Err(invalid("The front matter isn't a list of fields."));
+ }
+ Ok((v, body))
+}
+
+fn is_skill_file(filename: Option<&str>) -> bool {
+ filename.map(|f| f.rsplit(['/', '\\']).next().unwrap_or(f).eq_ignore_ascii_case("SKILL.md")).unwrap_or(false)
+}
+
+fn from_markdown(text: &str, filename: Option<&str>) -> Result<Bundle, ImportError> {
+ let (mut fm, body) = front_matter(text)?;
+ drop_secret_fields(&mut fm);
+ let is_agent_fm = ["tools", "model", "color"].iter().any(|k| fm.get(k).is_some());
+ if is_skill_file(filename) || (!is_agent_fm && fm.get("license").is_some()) {
+ let mut b = bundle("skill", None);
+ b.skills.push(skill_from_markdown(&fm, body, filename));
+ return Ok(b);
+ }
+ Ok(claude_code_agent(&fm, body, filename))
+}
+
+fn skill_from_markdown(fm: &Value, body: &str, filename: Option<&str>) -> SkillSpec {
+ let mut name = s(fm, "name");
+ if name.trim().is_empty() {
+ // skills/<name>/SKILL.md
+ name = filename.and_then(|f| f.replace('\\', "/").rsplit('/').nth(1).map(str::to_string)).unwrap_or_default();
+ }
+ SkillSpec { name, description: s(fm, "description"), body: body.to_string() }
+}
+
+/// A Claude Code subagent (`.claude/agents/<name>.md`).
+fn claude_code_agent(fm: &Value, body: &str, filename: Option<&str>) -> Bundle {
+ let file_stem = filename
+ .map(|f| f.replace('\\', "/"))
+ .and_then(|f| f.rsplit('/').next().map(|n| n.trim_end_matches(".md").to_string()))
+ .unwrap_or_default();
+ let name = Some(s(fm, "name")).filter(|n| !n.trim().is_empty()).unwrap_or(file_stem);
+ let description = s(fm, "description");
+ let sentence = description.split(['.', '\n']).next().unwrap_or("").trim().to_string();
+ let tools = match fm.get("tools") {
+ Some(Value::String(t)) => t.split(',').map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect(),
+ Some(Value::Array(items)) => texts(items),
+ _ => Vec::new(),
+ };
+ let mut persona = body.trim().to_string();
+ if description.chars().count() > sentence.chars().count() + 1 {
+ persona = format!("{persona}\n\n## When to use this bot\n{}", description.trim());
+ }
+ let mut b = bundle("claude-code", None);
+ b.bots.push(BotSpec {
+ ref_: super::slug(&name),
+ name,
+ title: if sentence.is_empty() { "Claude Code agent".into() } else { sentence },
+ persona_prompt: persona.trim().to_string(),
+ model_hint: Some(s(fm, "model")).filter(|m| !m.is_empty()),
+ tool_hints: tools,
+ ..BotSpec::default()
+ });
+ b
+}
+
+// ── Character cards ───────────────────────────────────────────────────────
+
+/// Character Card V1 (fields at the top), V2 and V3 (fields under `data`).
+fn from_card(d: &Value, spec: &str) -> Bundle {
+ let name = s(d, "name");
+ let fill = |t: String| {
+ t.replace("{{original}}", "")
+ .replace("{{char}}", &name)
+ .replace("{{Char}}", &name)
+ .replace("<BOT>", &name)
+ .replace("{{user}}", "the user")
+ .replace("{{User}}", "the user")
+ .replace("<USER>", "the user")
+ .trim()
+ .to_string()
+ };
+ let mut parts = Vec::new();
+ for (heading, key) in [
+ ("", "system_prompt"),
+ ("## Character", "description"),
+ ("## Scenario", "scenario"),
+ ("## Example dialogue", "mes_example"),
+ ("## Always remember", "post_history_instructions"),
+ ] {
+ let t = fill(s(d, key));
+ if !t.is_empty() {
+ parts.push(if heading.is_empty() { t } else { format!("{heading}\n{t}") });
+ }
+ }
+ let mut starters = vec![fill(s(d, "first_mes"))];
+ starters.extend(texts(arr(d, "alternate_greetings")).into_iter().map(fill));
+ starters.retain(|t| !t.is_empty());
+ let mut omitted = Vec::new();
+ if d.get("character_book").is_some_and(|b| !b.is_null()) {
+ omitted.push("Lorebook (character_book): kwant has no lorebooks".to_string());
+ }
+ if !arr(d, "assets").is_empty() {
+ omitted.push("Card assets (images, sounds)".to_string());
+ }
+ let mut b = bundle("character-card", Some(spec.to_string()));
+ b.bots.push(BotSpec {
+ ref_: super::slug(&name),
+ name: name.clone(),
+ title: Some(fill(s(d, "nickname"))).filter(|t| !t.is_empty()).unwrap_or_else(|| "Character".into()),
+ persona_prompt: parts.join("\n\n"),
+ soul: fill(s(d, "personality")),
+ starters,
+ ..BotSpec::default()
+ });
+ b.omitted = omitted;
+ b
+}
+
+// ── Grok Bot ──────────────────────────────────────────────────────────────
+
+/// `grokbot-bundle/v1` from pi-grokbot-import.
+fn from_grokbot(v: &Value) -> Bundle {
+ let src = v.get("source").cloned().unwrap_or(Value::Null);
+ let p = v.get("persona").cloned().unwrap_or(Value::Null);
+ let name = any_s(&p, &["name"]);
+ let mut b = bundle("grokbot", Some(any_s(&src, &["url", "id"])).filter(|l| !l.is_empty()));
+ b.source.exported_at = Some(s(v, "exportedAt")).filter(|t| !t.is_empty());
+ let memories = arr(v, "memories").iter().map(|m| any_s(m, &["text", "content"])).filter(|t| !t.trim().is_empty()).collect();
+ let skills = arr(v, "skills")
+ .iter()
+ .map(|sk| SkillSpec { name: s(sk, "name"), description: s(sk, "description"), body: any_s(sk, &["body", "instructions", "content"]) })
+ .collect();
+ let routines = arr(v, "routines")
+ .iter()
+ .map(|r| RoutineSpec {
+ name: s(r, "name"),
+ instructions: any_s(r, &["prompt", "instructions"]),
+ schedule: None,
+ schedule_text: Some(any_s(r, &["schedule", "cron", "time"])).filter(|t| !t.is_empty()),
+ })
+ .collect();
+ let tool_hints = arr(v, "plugins")
+ .iter()
+ .map(|pl| {
+ let (id, note) = (s(pl, "id"), s(pl, "note"));
+ if note.is_empty() { id } else { format!("{id}: {note}") }
+ })
+ .filter(|t| !t.is_empty())
+ .collect();
+ b.bots.push(BotSpec {
+ ref_: super::slug(&name),
+ name,
+ title: any_s(&p, &["title"]),
+ persona_prompt: any_s(&p, &["instructions", "systemPrompt", "description"]),
+ avatar_hint: Some(any_s(&p, &["avatarShape"])).filter(|t| !t.is_empty()),
+ memories,
+ skills,
+ routines,
+ tool_hints,
+ ..BotSpec::default()
+ });
+ b.omitted = texts(arr(v, "omitted"));
+ if s(&src, "mode") == "metadata-only" {
+ b.omitted.push("This Grok Bot export was metadata-only, so its instructions may be missing".into());
+ }
+ b
+}
+
+// ── OpenMausBot ───────────────────────────────────────────────────────────
+
+/// A package schedule as kwant JSON, else its words.
+fn openmaus_schedule(sch: &Value) -> (Option<Value>, Option<String>) {
+ let days = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
+ match s(sch, "type").as_str() {
+ "cron" => (
+ Some(serde_json::json!({"type": "cron", "expression": s(sch, "expression"), "tz": any_s(sch, &["timeZone", "tz"])})),
+ Some(s(sch, "expression")),
+ ),
+ "daily" => {
+ let wd: Vec<String> = arr(sch, "weekdays").iter().filter_map(Value::as_u64).filter_map(|d| days.get(d as usize)).map(|d| d.to_string()).collect();
+ let time = s(sch, "time");
+ if wd.is_empty() || wd.len() == 7 {
+ (Some(serde_json::json!({"type": "daily", "time": time, "tz": "UTC"})), Some(time))
+ } else {
+ (Some(serde_json::json!({"type": "weekly", "time": time, "weekdays": wd, "tz": "UTC"})), Some(time))
+ }
+ }
+ "interval" => (
+ Some(serde_json::json!({"type": "interval", "every_minutes": sch.get("everyMinutes").and_then(Value::as_i64).unwrap_or(60)})),
+ None,
+ ),
+ "once" => {
+ let at = sch.get("at").and_then(Value::as_i64).and_then(chrono::DateTime::from_timestamp_millis);
+ (at.map(|at| serde_json::json!({"type": "once", "at": at.to_rfc3339()})), None)
+ }
+ _ => (None, Some(sch.to_string()).filter(|t| t != "null")),
+ }
+}
+
+/// `openmaus.package` v1 and v2: bots, their playbooks and skills, routines, and the team.
+fn from_openmaus_package(v: &Value) -> Result<Bundle, ImportError> {
+ let version = v.get("version").and_then(Value::as_u64).unwrap_or(0);
+ if !(1..=2).contains(&version) {
+ return Err(invalid("This OpenMausBot package version isn't supported."));
+ }
+ let pkg = v.get("package").ok_or_else(|| invalid("This OpenMausBot package has no contents."))?;
+ let mut b = bundle("openmaus", Some(any_s(pkg, &["name", "id"])).filter(|t| !t.is_empty()));
+ let skills_by_name: Vec<SkillSpec> = pkg
+ .get("skills")
+ .map(|sk| arr(sk, "entries"))
+ .unwrap_or(&[])
+ .iter()
+ .map(|e| SkillSpec { name: s(e, "name"), description: s(e, "description"), body: any_s(e, &["instructions", "body"]) })
+ .collect();
+ let playbooks: Vec<(String, SkillSpec)> = arr(pkg, "playbooks")
+ .iter()
+ .map(|p| (s(p, "key"), SkillSpec { name: any_s(p, &["key", "name"]), description: any_s(p, &["summary", "name"]), body: s(p, "instructions") }))
+ .collect();
+ let mut used = std::collections::HashSet::new();
+ for a in arr(pkg, "agents") {
+ let key = s(a, "key");
+ let mut skills = Vec::new();
+ for name in texts(arr(a, "skills")) {
+ if let Some(sk) = skills_by_name.iter().find(|sk| sk.name == name) {
+ skills.push(sk.clone());
+ used.insert(name);
+ }
+ }
+ for pb in texts(arr(a, "playbooks")) {
+ if let Some((_, sk)) = playbooks.iter().find(|(k, _)| *k == pb) {
+ skills.push(sk.clone());
+ }
+ }
+ let mut memories = Vec::new();
+ if let Some(Value::Object(files)) = a.get("seed").and_then(|sd| sd.get("memory")) {
+ for text in files.values().filter_map(Value::as_str) {
+ memories.extend(memories_from_markdown(text));
+ }
+ }
+ let soul = s(a, "soul");
+ let description = s(a, "description");
+ b.bots.push(BotSpec {
+ ref_: key,
+ name: s(a, "name"),
+ title: s(a, "title"),
+ persona_prompt: if soul.trim().is_empty() { description } else { soul },
+ avatar_hint: a.get("appearance").map(|ap| s(ap, "color")).filter(|c| !c.is_empty()),
+ memories,
+ skills,
+ tool_hints: texts(arr(a, "connections")),
+ ..BotSpec::default()
+ });
+ }
+ b.skills = skills_by_name.into_iter().filter(|sk| !used.contains(&sk.name)).collect();
+ for r in arr(pkg, "routines") {
+ let (schedule, schedule_text) = openmaus_schedule(r.get("schedule").unwrap_or(&Value::Null));
+ let spec = RoutineSpec { name: s(r, "name"), instructions: any_s(r, &["prompt", "instructions"]), schedule, schedule_text };
+ let agent = s(r, "agent");
+ match b.bots.iter_mut().find(|bot| bot.ref_ == agent) {
+ Some(bot) => bot.routines.push(spec),
+ None => b.omitted.push(format!("Routine {} (its bot isn't in the package)", spec.name)),
+ }
+ }
+ if let Some(team) = pkg.get("team").filter(|t| t.is_object()) {
+ let leader = Some(s(team, "leader")).filter(|l| !l.is_empty()).or_else(|| Some(s(pkg, "chiefOfStaff")).filter(|l| !l.is_empty()));
+ b.teams.push(TeamSpec {
+ name: s(team, "name"),
+ lead: leader,
+ members: b.bots.iter().map(|bot| bot.ref_.clone()).collect(),
+ instructions: Some(s(team, "brief")).filter(|t| !t.is_empty()),
+ });
+ }
+ for (key, what) in [("rooms", "Rooms"), ("connections", "Connected apps (sign in again in kwant)"), ("presets", "Preset bots"), ("examples", "Examples")] {
+ if !arr(pkg, key).is_empty() {
+ b.omitted.push(what.into());
+ }
+ }
+ Ok(b)
+}
+
+/// `openmaus.grok/1`: an OpenMausBot bot's reply to its Grok export prompt. Its field list
+/// isn't published, so common names are read and the rest is ignored.
+fn from_openmaus_grok(v: &Value) -> Bundle {
+ let bot = v.get("bot").filter(|b| b.is_object()).unwrap_or(v);
+ let name = any_s(bot, &["name"]);
+ let mut b = bundle("openmaus-grok", None);
+ let skills = arr(bot, "skills")
+ .iter()
+ .map(|sk| match sk {
+ Value::String(t) => SkillSpec { name: first_line(t), description: String::new(), body: t.clone() },
+ o => SkillSpec { name: s(o, "name"), description: s(o, "description"), body: any_s(o, &["instructions", "body", "content"]) },
+ })
+ .collect();
+ let routines = arr(bot, "routines")
+ .iter()
+ .map(|r| RoutineSpec {
+ name: any_s(r, &["name", "title"]),
+ instructions: any_s(r, &["prompt", "instructions", "task"]),
+ schedule: None,
+ schedule_text: Some(any_s(r, &["schedule", "cron", "time", "when"])).filter(|t| !t.is_empty()),
+ })
+ .collect();
+ let mut tool_hints = texts(arr(bot, "connectedApps"));
+ tool_hints.extend(texts(arr(bot, "apps")));
+ tool_hints.extend(texts(arr(bot, "connected_apps")));
+ let memories = match bot.get("memories").or_else(|| bot.get("memory")) {
+ Some(Value::Array(items)) => texts(items),
+ Some(Value::String(t)) => memories_from_markdown(t),
+ _ => Vec::new(),
+ };
+ b.bots.push(BotSpec {
+ ref_: super::slug(&name),
+ name,
+ title: any_s(bot, &["title", "role", "description"]),
+ persona_prompt: any_s(bot, &["instructions", "soul", "systemPrompt", "description"]),
+ memories,
+ skills,
+ routines,
+ tool_hints,
+ ..BotSpec::default()
+ });
+ b
+}
+
+// ── zip ───────────────────────────────────────────────────────────────────
+
+fn from_zip(bytes: &[u8]) -> Result<Bundle, ImportError> {
+ let unzipped = archive::read_zip(bytes)?;
+ let mut merged = bundle("zip", None);
+ let mut skills = Vec::new();
+ let mut kinds = std::collections::BTreeSet::new();
+ let mut unread = Vec::new();
+ for e in &unzipped.entries {
+ let lower = e.path.to_lowercase();
+ if is_skill_file(Some(&e.path)) {
+ match std::str::from_utf8(&e.bytes).ok().and_then(|t| front_matter(t).ok()) {
+ Some((fm, body)) => {
+ skills.push(skill_from_markdown(&fm, body, Some(&e.path)));
+ kinds.insert("skill".to_string());
+ }
+ None => unread.push(e.path.clone()),
+ }
+ continue;
+ }
+ if e.bytes.starts_with(&ZIP_MAGIC) || e.bytes.starts_with(&EMPTY_ZIP_MAGIC) {
+ return Err(invalid("This zip contains another archive. Unpack it and import the inner file instead."));
+ }
+ if lower.ends_with(".txt") || lower.ends_with("readme.md") {
+ unread.push(e.path.clone());
+ continue;
+ }
+ match parse_file(&e.bytes, Some(&e.path)) {
+ Ok(b) => {
+ kinds.insert(b.source.kind.clone());
+ merged.bots.extend(b.bots);
+ merged.teams.extend(b.teams);
+ merged.skills.extend(b.skills);
+ merged.omitted.extend(b.omitted);
+ }
+ Err(ImportError::Unsupported(_)) => unread.push(e.path.clone()),
+ Err(err) => return Err(invalid(format!("{}: {err}", e.path))),
+ }
+ }
+ // Skills next to a single agent are that agent's; otherwise the space shares them.
+ match merged.bots.as_mut_slice() {
+ [only] => only.skills.extend(skills),
+ _ => merged.skills.extend(skills),
+ }
+ if merged.bots.is_empty() && merged.skills.is_empty() {
+ return Err(ImportError::Unsupported(
+ "This zip has no bots or skills kwant can read. Chat-history exports aren't imported.".into(),
+ ));
+ }
+ if kinds.len() == 1 {
+ merged.source.kind = kinds.into_iter().next().unwrap_or_default();
+ }
+ let not_read: Vec<String> = unzipped.skipped.into_iter().chain(unread).collect();
+ if !not_read.is_empty() {
+ let shown: Vec<String> = not_read.iter().take(10).cloned().collect();
+ let more = if not_read.len() > 10 { format!(" and {} more", not_read.len() - 10) } else { String::new() };
+ merged.omitted.push(cut(&format!("Files in the zip that weren't read: {}{more}", shown.join(", ")), 200));
+ }
+ Ok(merged)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn json_block_from_reply() {
+ let reply = "Sure! Here it is:\n```json\n{\"format\": \"kwant.bundle/1\"}\n```\nAnything else?";
+ assert_eq!(json_block(reply), Some("{\"format\": \"kwant.bundle/1\"}"));
+ assert_eq!(json_block("prefix {\"a\": 1} suffix"), Some("{\"a\": 1}"));
+ assert_eq!(json_block("no json here"), None);
+ assert_eq!(json_block("```json\n{\"a\": 1}\nthe reply was cut"), Some("{\"a\": 1}"));
+ }
+
+ #[test]
+ fn memory_markdown() {
+ let m = memories_from_markdown("# Memory\n- likes tea\n- lives in\n Kyiv\n\nA paragraph\nover lines.");
+ assert_eq!(m, vec!["likes tea", "lives in Kyiv", "A paragraph over lines."]);
+ }
+}
diff --git a/src/import/prompts.rs b/src/import/prompts.rs
new file mode 100644
index 00000000..0ef0f728
--- /dev/null
+++ b/src/import/prompts.rs
@@ -0,0 +1,118 @@
+//! The export prompt: what a person sends their bot in another app, so the bot replies with a
+//! `kwant.bundle/1` they can paste back. This is the one source of truth for the text; the
+//! Import dialog gets it from `GET /api/import/prompts`.
+
+use serde::Serialize;
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ExportPrompt {
+ /// `grok`, `chatgpt`, `claude`, `other`.
+ pub id: &'static str,
+ /// "Bring a bot from …"
+ pub label: &'static str,
+ /// Where the person sends the prompt, in one sentence.
+ pub where_to_send: &'static str,
+ pub prompt: String,
+}
+
+/// In the order the "Bring a bot from…" list shows them.
+const SOURCES: [(&str, &str, &str, &str); 4] = [
+ (
+ "grok",
+ "Grok",
+ "Open the Grok Project or Grok bot you want to bring over and send it this message in a new chat.",
+ "grok",
+ ),
+ (
+ "chatgpt",
+ "ChatGPT",
+ "Open your custom GPT (or the ChatGPT Project) and send it this message in a new chat. For a custom GPT you edit yourself, you can also copy the Instructions field from the GPT editor.",
+ "chatgpt",
+ ),
+ (
+ "claude",
+ "Claude",
+ "Open the Claude Project you want to bring over and send it this message in a new chat in that project.",
+ "claude",
+ ),
+ ("other", "Another app", "Open the bot or assistant you want to bring over and send it this message.", "other"),
+];
+
+const TEMPLATE: &str = r#"I'm moving you to another app called kwant. Please describe yourself so I can recreate you there.
+
+Reply with exactly one JSON code block and nothing else, in this shape:
+
+{
+ "format": "kwant.bundle/1",
+ "source": { "kind": "{{KIND}}", "label": "<your name in {{APP}}>" },
+ "bots": [
+ {
+ "ref": "main",
+ "name": "<your name, one word>",
+ "title": "<your role in a few words>",
+ "persona_prompt": "<your full instructions / system prompt, WORD FOR WORD, not a summary>",
+ "soul": "<your personality and tone, if it isn't already in the instructions>",
+ "starters": ["<conversation starters, if you have any>"],
+ "memories": ["<each thing you remember about me, one fact per item>"],
+ "skills": [
+ { "name": "<short-name>", "description": "<one line: when to use it>", "body": "<the steps, word for word>" }
+ ],
+ "routines": [
+ { "name": "<scheduled task name>", "instructions": "<what to do each time>", "schedule_text": "<cron line like 0 9 * * 1-5, or a time like 09:00>" }
+ ],
+ "tool_hints": ["<tools, actions, plugins or connected apps you use>"],
+ "knowledge_files": ["<names of files you were given>"]
+ }
+ ],
+ "omitted": ["<anything you have that doesn't fit above>"]
+}
+
+Rules:
+- Copy your instructions exactly as written. Don't shorten, paraphrase or improve them.
+- Leave out empty lists rather than inventing content.
+- Never include passwords, API keys, tokens or other secrets. Write [secret] instead.
+- Don't include our past conversations.
+- Use straight JSON: double quotes, no comments, no trailing commas."#;
+
+fn app_name(id: &str) -> &'static str {
+ match id {
+ "grok" => "Grok",
+ "chatgpt" => "ChatGPT",
+ "claude" => "Claude",
+ _ => "this app",
+ }
+}
+
+/// Every source's prompt, in display order.
+pub fn export_prompts() -> Vec<ExportPrompt> {
+ SOURCES
+ .iter()
+ .map(|(id, label, where_to_send, kind)| ExportPrompt {
+ id,
+ label,
+ where_to_send,
+ prompt: TEMPLATE.replace("{{KIND}}", kind).replace("{{APP}}", app_name(id)),
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn prompts_start_with_grok_chatgpt_claude() {
+ let ids: Vec<&str> = export_prompts().iter().map(|p| p.id).collect();
+ assert_eq!(ids, ["grok", "chatgpt", "claude", "other"]);
+ assert!(export_prompts().iter().all(|p| !p.prompt.contains("{{")));
+ }
+
+ #[test]
+ fn prompt_example_is_a_valid_bundle_shape() {
+ let p = &export_prompts()[0].prompt;
+ let json = crate::import::parsers::json_block(p).unwrap();
+ let b: crate::import::Bundle = serde_json::from_str(json).unwrap();
+ assert_eq!(b.format, crate::import::BUNDLE_FORMAT);
+ assert_eq!(b.source.kind, "grok");
+ }
+}
diff --git a/src/import/scrub.rs b/src/import/scrub.rs
new file mode 100644
index 00000000..8a008f3e
--- /dev/null
+++ b/src/import/scrub.rs
@@ -0,0 +1,201 @@
+//! Keys never travel: anything shaped like an API key, token or password is removed from an
+//! import before anyone sees it, and fields named like secrets are dropped from source JSON.
+
+use super::Bundle;
+use serde_json::Value;
+
+pub const REDACTED: &str = "[removed key]";
+
+/// Words that, in a JSON key, mean its value is a secret.
+const SECRET_KEY_WORDS: [&str; 10] =
+ ["apikey", "api_key", "api-key", "token", "secret", "password", "passwd", "authorization", "credential", "private_key"];
+
+/// Labels that, written just before a long value, mean the value is a secret (`password: hunter2…`).
+const SECRET_LABELS: [&str; 9] =
+ ["api_key", "api-key", "apikey", "api key", "token", "secret", "password", "bearer", "authorization"];
+
+/// Removes, at any depth, object fields whose names say they hold a secret (and `env` and
+/// `headers`, which carry them in tool configs).
+pub fn drop_secret_fields(v: &mut Value) {
+ match v {
+ Value::Object(map) => {
+ map.retain(|k, _| {
+ let k = k.to_lowercase();
+ k != "env" && k != "headers" && !SECRET_KEY_WORDS.iter().any(|w| k.contains(w))
+ });
+ map.values_mut().for_each(drop_secret_fields);
+ }
+ Value::Array(items) => items.iter_mut().for_each(drop_secret_fields),
+ _ => {}
+ }
+}
+
+fn is_token_byte(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')
+}
+
+/// Whether one word looks like a key from a known provider, or a JWT.
+fn looks_like_key(t: &str) -> bool {
+ let long = |min: usize| t.len() >= min;
+ let prefixed = |prefixes: &[&str], min: usize| prefixes.iter().any(|p| t.starts_with(p)) && long(min);
+ if prefixed(&["sk-", "xai-", "rk_live_", "sk_live_", "sk_test_"], 20)
+ || prefixed(&["AIza"], 30)
+ || prefixed(&["ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_", "glpat-"], 24)
+ || prefixed(&["xoxb-", "xoxp-", "xoxa-", "xoxr-", "xoxs-"], 20)
+ || prefixed(&["hf_"], 30)
+ {
+ return true;
+ }
+ // AWS access key id
+ if t.len() == 20 && (t.starts_with("AKIA") || t.starts_with("ASIA")) && t.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()) {
+ return true;
+ }
+ // JWT: three base64url parts, the header starting {"
+ let parts: Vec<&str> = t.split('.').collect();
+ parts.len() == 3 && t.starts_with("eyJ") && long(30) && parts.iter().all(|p| p.len() >= 4)
+}
+
+/// A long value with letters and digits right after a secret label.
+fn labelled_secret(before: &str, t: &str) -> bool {
+ if t.len() < 12 || !t.bytes().any(|b| b.is_ascii_digit()) || !t.bytes().any(|b| b.is_ascii_alphabetic()) {
+ return false;
+ }
+ let mut label = before.trim_end_matches([' ', ':', '=', '"', '\'', '\t']).to_lowercase();
+ let mut changed = label.len() != before.len();
+ // `password is …`, `token was …`
+ for filler in [" is", " was", " are"] {
+ if let Some(rest) = label.strip_suffix(filler) {
+ label = rest.trim_end().to_string();
+ changed = true;
+ }
+ }
+ (changed || label.ends_with("bearer")) && SECRET_LABELS.iter().any(|l| label.ends_with(l))
+}
+
+/// `text` with key-like words replaced by [`REDACTED`], and how many there were.
+pub fn scrub_text(text: &str) -> (String, usize) {
+ let bytes = text.as_bytes();
+ let mut out = String::with_capacity(text.len());
+ let mut count = 0;
+ let mut last = 0;
+ let mut i = 0;
+ while i < bytes.len() {
+ if !is_token_byte(bytes[i]) {
+ i += 1;
+ continue;
+ }
+ let start = i;
+ while i < bytes.len() && is_token_byte(bytes[i]) {
+ i += 1;
+ }
+ // Token bytes are ASCII, so these are char boundaries.
+ let word = text[start..i].trim_end_matches(['.', '-']);
+ let end = start + word.len();
+ let mut from = start.saturating_sub(40);
+ while !text.is_char_boundary(from) {
+ from += 1;
+ }
+ let before = &text[from..start];
+ if looks_like_key(word) || labelled_secret(before, word) {
+ out.push_str(&text[last..start]);
+ out.push_str(REDACTED);
+ last = end;
+ count += 1;
+ }
+ }
+ out.push_str(&text[last..]);
+ (out, count)
+}
+
+fn scrub_in_place(s: &mut String) -> usize {
+ let (clean, n) = scrub_text(s);
+ if n > 0 {
+ *s = clean;
+ }
+ n
+}
+
+/// Scrubs every text in the bundle. Returns, per bot ref (`None` = teams, shared skills and
+/// the rest), how many keys were removed; only places with removals are listed.
+pub fn scrub_bundle(b: &mut Bundle) -> Vec<(Option<String>, usize)> {
+ let mut found = Vec::new();
+ for bot in &mut b.bots {
+ let mut n = 0;
+ for s in [&mut bot.name, &mut bot.title, &mut bot.persona_prompt, &mut bot.soul] {
+ n += scrub_in_place(s);
+ }
+ for s in bot.starters.iter_mut().chain(&mut bot.memories).chain(&mut bot.tool_hints).chain(&mut bot.knowledge_files) {
+ n += scrub_in_place(s);
+ }
+ for s in bot.avatar_hint.iter_mut().chain(bot.model_hint.iter_mut()) {
+ n += scrub_in_place(s);
+ }
+ for sk in &mut bot.skills {
+ n += scrub_in_place(&mut sk.name) + scrub_in_place(&mut sk.description) + scrub_in_place(&mut sk.body);
+ }
+ for r in &mut bot.routines {
+ n += scrub_in_place(&mut r.name) + scrub_in_place(&mut r.instructions);
+ if let Some(t) = &mut r.schedule_text {
+ n += scrub_in_place(t);
+ }
+ }
+ if n > 0 {
+ found.push((Some(bot.ref_.clone()), n));
+ }
+ }
+ let mut n = 0;
+ for t in &mut b.teams {
+ n += scrub_in_place(&mut t.name);
+ if let Some(i) = &mut t.instructions {
+ n += scrub_in_place(i);
+ }
+ }
+ for sk in &mut b.skills {
+ n += scrub_in_place(&mut sk.name) + scrub_in_place(&mut sk.description) + scrub_in_place(&mut sk.body);
+ }
+ for s in b.omitted.iter_mut() {
+ n += scrub_in_place(s);
+ }
+ if let Some(l) = &mut b.source.label {
+ n += scrub_in_place(l);
+ }
+ if n > 0 {
+ found.push((None, n));
+ }
+ found
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn provider_keys_are_removed() {
+ let text = "Use sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAA and xai-BBBBBBBBBBBBBBBBBBBBBBBB, \
+ AIzaSyCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC or ghp_DDDDDDDDDDDDDDDDDDDDDDDDDDDD.";
+ let (out, n) = scrub_text(text);
+ assert_eq!(n, 4, "{out}");
+ assert!(!out.contains("sk-ant") && !out.contains("xai-B") && !out.contains("AIza") && !out.contains("ghp_"));
+ assert!(out.ends_with("[removed key]."));
+ }
+
+ #[test]
+ fn jwts_and_labelled_secrets_are_removed() {
+ let (out, n) = scrub_text("token: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abcdefghijkl and password = hunter2hunter2X9");
+ assert_eq!(n, 2, "{out}");
+ assert!(!out.contains("eyJ") && !out.contains("hunter2"));
+ }
+
+ #[test]
+ fn ordinary_words_stay() {
+ let text = "Ask about the sk-learn task; the tokenizer is fine. My password policy is strict.";
+ assert_eq!(scrub_text(text), (text.to_string(), 0));
+ }
+
+ #[test]
+ fn secret_fields_are_dropped() {
+ let mut v = serde_json::json!({"name": "x", "apiKey": "abc", "nested": [{"env": {"A": "b"}, "Authorization": "c", "ok": 1}]});
+ drop_secret_fields(&mut v);
+ assert_eq!(v, serde_json::json!({"name": "x", "nested": [{"ok": 1}]}));
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
index 3e1e1b09..727296d9 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -3,6 +3,7 @@ pub mod config;
pub mod db;
pub mod drivers;
pub mod embedded;
+pub mod import;
pub mod mcp;
pub mod profiles;
pub mod router;
diff --git a/src/server/import_routes.rs b/src/server/import_routes.rs
new file mode 100644
index 00000000..dd7c3cd4
--- /dev/null
+++ b/src/server/import_routes.rs
@@ -0,0 +1,298 @@
+//! Bringing bots in from other apps and taking them out again.
+//!
+//! - `POST /api/import/preview?space=&filename=`: a file as the raw body, or JSON `{ "text": … }`
+//! for a pasted reply. Parses and checks it; writes nothing and keeps nothing.
+//! - `POST /api/import/apply?space=`: `{ "bundle": …, "skip": [refs] }`, the bundle preview
+//! returned. Checks it again and creates it all in one transaction.
+//! - `GET /api/imports?space=`, `GET /api/imports/:id?space=`, `POST /api/imports/:id/undo?space=`.
+//! - `GET /api/kwants/:id/export`, `GET /api/export?space=`: `kwant.bundle/1`, keys scrubbed.
+//! - `GET /api/import/prompts`: the export prompt to send a bot in Grok, ChatGPT, Claude, ….
+
+use super::spaces::Scope;
+use super::AppState;
+use crate::db::imports::{ImportRecord, UndoError};
+use crate::db::spaces::SpaceId;
+use crate::import::{self, parsers, Bundle, Checked, ImportError, BUNDLE_FORMAT, MAX_ZIP_BYTES};
+use axum::{
+ body::Body,
+ extract::{Path, Query, State},
+ http::{header, HeaderMap, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use futures::StreamExt;
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+use std::collections::HashSet;
+
+/// An apply body: a bundle with up to 50 bots of 2 × 16k characters, plus skills.
+const MAX_APPLY_BYTES: usize = 8 * 1024 * 1024;
+
+fn error(status: StatusCode, code: &str, message: impl Into<String>) -> Response {
+ (status, Json(json!({ "error": message.into(), "code": code }))).into_response()
+}
+
+fn import_error(e: ImportError) -> Response {
+ match e {
+ ImportError::TooLarge(m) => error(StatusCode::PAYLOAD_TOO_LARGE, "too_large", m),
+ ImportError::Unsupported(m) => error(StatusCode::UNSUPPORTED_MEDIA_TYPE, "unsupported", m),
+ ImportError::Invalid(m) => error(StatusCode::UNPROCESSABLE_ENTITY, "invalid", m),
+ }
+}
+
+fn internal(e: impl std::fmt::Display) -> Response {
+ tracing::warn!(error = %e, "import failed");
+ error(StatusCode::INTERNAL_SERVER_ERROR, "internal", "database error")
+}
+
+/// The body, read up to `limit` bytes. Only kept in memory for this request.
+#[allow(clippy::result_large_err)]
+async fn read_body(headers: &HeaderMap, body: Body, limit: usize, what: &str) -> Result<Vec<u8>, Response> {
+ let too_large = || error(StatusCode::PAYLOAD_TOO_LARGE, "too_large", format!("{what} can be at most {} MB.", limit / (1024 * 1024)));
+ let declared = headers.get(header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<usize>().ok());
+ if declared.is_some_and(|n| n > limit) {
+ return Err(too_large());
+ }
+ let mut out = Vec::with_capacity(declared.unwrap_or(0).min(limit));
+ let mut stream = body.into_data_stream();
+ while let Some(chunk) = stream.next().await {
+ let chunk = chunk.map_err(|_| error(StatusCode::BAD_REQUEST, "invalid", "The upload was interrupted."))?;
+ if out.len() + chunk.len() > limit {
+ return Err(too_large());
+ }
+ out.extend_from_slice(&chunk);
+ }
+ Ok(out)
+}
+
+#[allow(clippy::result_large_err)]
+async fn names_in(state: &AppState, space: &SpaceId) -> Result<Vec<String>, Response> {
+ state.db.list_kwants(space).await.map(|ks| ks.into_iter().map(|k| k.name).collect()).map_err(internal)
+}
+
+#[derive(Deserialize)]
+pub struct PreviewQuery {
+ filename: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct Pasted {
+ text: String,
+}
+
+#[derive(Serialize)]
+pub struct Preview {
+ #[serde(flatten)]
+ checked: Checked,
+ /// True when nothing in `problems` stops the import.
+ can_apply: bool,
+}
+
+/// `POST /api/import/preview`. A JSON body `{ "text": … }` (Content-Type `application/json`)
+/// is pasted text; anything else is a file, named by `?filename=`.
+pub async fn preview(State(state): State<AppState>, Scope(space): Scope, Query(q): Query<PreviewQuery>, headers: HeaderMap, body: Body) -> Response {
+ let bytes = match read_body(&headers, body, MAX_ZIP_BYTES, "A file").await {
+ Ok(b) => b,
+ Err(r) => return r,
+ };
+ if bytes.is_empty() {
+ return error(StatusCode::BAD_REQUEST, "empty", "Nothing was sent.");
+ }
+ let is_json = headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|c| c.starts_with("application/json"));
+ let parsed = match (is_json, serde_json::from_slice::<Pasted>(&bytes)) {
+ (true, Ok(p)) => parsers::parse_pasted(&p.text),
+ _ => parsers::parse_file(&bytes, q.filename.as_deref()),
+ };
+ drop(bytes);
+ let bundle = match parsed {
+ Ok(b) => b,
+ Err(e) => return import_error(e),
+ };
+ let names = match names_in(&state, &space).await {
+ Ok(n) => n,
+ Err(r) => return r,
+ };
+ let checked = import::normalize(bundle, &names);
+ let can_apply = checked.problems.is_empty() && !(checked.bundle.bots.is_empty() && checked.bundle.skills.is_empty());
+ Json(Preview { checked, can_apply }).into_response()
+}
+
+#[derive(Deserialize)]
+struct ApplyRequest {
+ bundle: Bundle,
+ #[serde(default)]
+ skip: Vec<String>,
+}
+
+#[derive(Serialize)]
+pub struct Applied {
+ import: ImportRecord,
+ warnings: Vec<import::Notice>,
+ dropped: Vec<import::Notice>,
+ renames: Vec<import::Rename>,
+}
+
+/// `POST /api/import/apply`. Bots named in `skip` (by `ref`) are left out, and teams lose them.
+pub async fn apply(State(state): State<AppState>, Scope(space): Scope, headers: HeaderMap, body: Body) -> Response {
+ let bytes = match read_body(&headers, body, MAX_APPLY_BYTES, "An import").await {
+ Ok(b) => b,
+ Err(r) => return r,
+ };
+ let req: ApplyRequest = match serde_json::from_slice(&bytes) {
+ Ok(r) => r,
+ Err(e) => return error(StatusCode::UNPROCESSABLE_ENTITY, "invalid", format!("This isn't an import from preview: {e}")),
+ };
+ let mut bundle = req.bundle;
+ if bundle.format != BUNDLE_FORMAT {
+ return error(StatusCode::UNPROCESSABLE_ENTITY, "invalid", format!("Send the bundle preview returned (format {BUNDLE_FORMAT})."));
+ }
+ let skip: HashSet<&str> = req.skip.iter().map(String::as_str).collect();
+ bundle.bots.retain(|b| !skip.contains(b.ref_.as_str()));
+ for t in &mut bundle.teams {
+ t.members.retain(|m| !skip.contains(m.as_str()));
+ if t.lead.as_deref().is_some_and(|l| skip.contains(l)) {
+ t.lead = None;
+ }
+ }
+ bundle.teams.retain(|t| !t.members.is_empty());
+ let names = match names_in(&state, &space).await {
+ Ok(n) => n,
+ Err(r) => return r,
+ };
+ let checked = import::normalize(bundle, &names);
+ if !checked.problems.is_empty() {
+ return (StatusCode::BAD_REQUEST, Json(json!({
+ "error": checked.problems.iter().map(|p| p.message.as_str()).collect::<Vec<_>>().join(" "),
+ "code": "problems",
+ "problems": checked.problems,
+ })))
+ .into_response();
+ }
+ if checked.bundle.bots.is_empty() && checked.bundle.skills.is_empty() {
+ return error(StatusCode::BAD_REQUEST, "empty", "There's nothing left to import.");
+ }
+ match state.db.apply_import(&space, &checked.bundle).await {
+ Ok(import) => {
+ tracing::info!(import_id = %import.id, space = %space, bots = import.created.kwants.len(), "import applied");
+ (
+ StatusCode::CREATED,
+ Json(Applied { import, warnings: checked.warnings, dropped: checked.dropped, renames: checked.renames }),
+ )
+ .into_response()
+ }
+ Err(crate::db::DbError::Conflict(m)) => error(StatusCode::CONFLICT, "name_taken", m),
+ Err(e) => internal(e),
+ }
+}
+
+/// The import, if it is in `space` (404 otherwise, as for any row in another space).
+#[allow(clippy::result_large_err)]
+async fn import_in(state: &AppState, space: &SpaceId, id: &str) -> Result<ImportRecord, Response> {
+ match state.db.get_import(id).await {
+ Ok(Some(r)) if r.space_id == space.as_str() => Ok(r),
+ Ok(_) => Err(error(StatusCode::NOT_FOUND, "not_found", "No such import in this space.")),
+ Err(e) => Err(internal(e)),
+ }
+}
+
+/// `GET /api/imports`: the space's imports, newest first.
+pub async fn list(State(state): State<AppState>, Scope(space): Scope) -> Response {
+ match state.db.list_imports(&space).await {
+ Ok(list) => Json(list).into_response(),
+ Err(e) => internal(e),
+ }
+}
+
+/// `GET /api/imports/:id`.
+pub async fn get(State(state): State<AppState>, Scope(space): Scope, Path(id): Path<String>) -> Response {
+ match import_in(&state, &space, &id).await {
+ Ok(r) => Json(r).into_response(),
+ Err(r) => r,
+ }
+}
+
+#[derive(Deserialize, Default)]
+struct UndoRequest {
+ #[serde(default)]
+ force: bool,
+}
+
+/// `POST /api/imports/:id/undo`, optional body `{ "force": true }` to remove bots edited since.
+pub async fn undo(State(state): State<AppState>, Scope(space): Scope, Path(id): Path<String>, headers: HeaderMap, body: Body) -> Response {
+ if let Err(r) = import_in(&state, &space, &id).await {
+ return r;
+ }
+ let bytes = match read_body(&headers, body, 4096, "An undo").await {
+ Ok(b) => b,
+ Err(r) => return r,
+ };
+ let req: UndoRequest = if bytes.iter().all(u8::is_ascii_whitespace) || bytes.trim_ascii() == b"null" {
+ UndoRequest::default()
+ } else {
+ match serde_json::from_slice(&bytes) {
+ Ok(r) => r,
+ Err(_) => return error(StatusCode::UNPROCESSABLE_ENTITY, "invalid", "Send {\"force\": true} or nothing."),
+ }
+ };
+ match state.db.undo_import(&id, req.force).await {
+ Ok(r) => {
+ tracing::info!(import_id = %id, space = %space, "import undone");
+ Json(r).into_response()
+ }
+ Err(UndoError::NotFound) => error(StatusCode::NOT_FOUND, "not_found", "No such import in this space."),
+ Err(UndoError::AlreadyUndone) => error(StatusCode::CONFLICT, "already_undone", "This import was already undone."),
+ Err(UndoError::Edited(names)) => (
+ StatusCode::CONFLICT,
+ Json(json!({
+ "error": format!("{} changed since the import. Undo anyway to remove them with your changes.", names.join(", ")),
+ "code": "edited",
+ "edited": names,
+ })),
+ )
+ .into_response(),
+ Err(UndoError::InUse(what)) => (
+ StatusCode::CONFLICT,
+ Json(json!({
+ "error": format!("This import is in use, so it can't be undone: {}. Delete those bots one by one instead.", what.join("; ")),
+ "code": "in_use",
+ "in_use": what,
+ })),
+ )
+ .into_response(),
+ Err(UndoError::Db(e)) => internal(e),
+ }
+}
+
+fn download(bundle: &Bundle, name: &str) -> Response {
+ let file: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' }).collect();
+ (
+ [(header::CONTENT_DISPOSITION, format!("attachment; filename=\"{file}.kwant.json\""))],
+ Json(bundle),
+ )
+ .into_response()
+}
+
+/// `GET /api/kwants/:id/export` (the row guard checks `?space=`).
+pub async fn export_kwant(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ match state.db.export_kwant(&id).await {
+ Ok(Some(b)) => {
+ let name = b.bots.first().map(|k| k.name.clone()).unwrap_or_default();
+ download(&b, &name)
+ }
+ Ok(None) => error(StatusCode::NOT_FOUND, "not_found", "bot not found"),
+ Err(e) => internal(e),
+ }
+}
+
+/// `GET /api/export?space=`: every bot and team in the space.
+pub async fn export_space(State(state): State<AppState>, Scope(space): Scope) -> Response {
+ match state.db.export_space(&space).await {
+ Ok(b) => download(&b, &format!("space-{}", space.as_str())),
+ Err(e) => internal(e),
+ }
+}
+
+/// `GET /api/import/prompts`.
+pub async fn prompts() -> Response {
+ Json(import::prompts::export_prompts()).into_response()
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index bda85ac2..f1da4347 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -23,6 +23,7 @@ pub mod computer;
pub mod mcp_suggest;
pub mod bot_actions;
pub mod hires;
+pub mod import_routes;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -152,6 +153,14 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/laya/status", get(routes::laya_status))
.route("/api/kwants", get(routes::list_kwants).post(routes::create_kwant))
.route("/api/kwants/:id", put(routes::update_kwant))
+ .route("/api/kwants/:id/export", get(import_routes::export_kwant))
+ .route("/api/export", get(import_routes::export_space))
+ .route("/api/import/prompts", get(import_routes::prompts))
+ .route("/api/import/preview", post(import_routes::preview))
+ .route("/api/import/apply", post(import_routes::apply))
+ .route("/api/imports", get(import_routes::list))
+ .route("/api/imports/:id", get(import_routes::get))
+ .route("/api/imports/:id/undo", post(import_routes::undo))
.route("/api/channels", get(routes::list_channels).post(routes::create_channel))
.route("/api/channels/:id/messages", get(routes::list_messages))
.route("/api/teams", get(routes::list_teams).post(routes::create_team))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 26cc766e..2460efca 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -226,6 +226,9 @@ pub async fn create_kwant(
Scope(space): Scope,
Json(mut payload): Json<CreateKwantRequest>,
) -> Result<Json<KwantView>, Response> {
+ if let Some(msg) = crate::import::check_persona_caps(&payload.base.persona_prompt, &payload.base.soul) {
+ return Err(api_error(StatusCode::BAD_REQUEST, &msg));
+ }
validate_kwant_name(&state, &space, &mut payload.base.name, None).await?;
check_binding(&state, &space, &payload.binding, &payload.base.preferred_model)
.await
@@ -261,6 +264,9 @@ pub async fn update_kwant(
Path(id): Path<String>,
Json(mut payload): Json<UpdateKwantRequest>,
) -> Result<Json<KwantView>, Response> {
+ if let Some(msg) = crate::import::check_persona_caps(&payload.base.persona_prompt, &payload.base.soul) {
+ return Err(api_error(StatusCode::BAD_REQUEST, &msg));
+ }
let space = state
.db
.space_of_kwant(&id)