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.

Import: pasted plain text becomes one bot's instructions; space export named after the space

Lin (kwant bot)5a327de1e02a
diff --git a/frontend/src/imports.ts b/frontend/src/imports.ts
index 7532e2f1..2450cb5d 100644
--- a/frontend/src/imports.ts
+++ b/frontend/src/imports.ts
@@ -259,6 +259,7 @@ const SOURCE_NAMES: Record<string, string> = {
openmaus: 'OpenMausBot',
'openmaus-grok': 'OpenMausBot',
zip: 'a zip',
+ 'plain-text': 'pasted text',
};
/** Where an import comes from, for "from …". `source.label` is often a bot name, so it isn't used. */
diff --git a/src/import/mod.rs b/src/import/mod.rs
index 96fe174c..2fe81c6a 100644
--- a/src/import/mod.rs
+++ b/src/import/mod.rs
@@ -17,6 +17,8 @@ use serde::{Deserialize, Serialize};
use std::collections::HashSet;
pub const BUNDLE_FORMAT: &str = "kwant.bundle/1";
+/// `source.kind` of pasted text that was taken as one bot's instructions.
+pub const PLAIN_TEXT_KIND: &str = "plain-text";
/// Pasted text (an export-prompt reply).
pub const MAX_TEXT_BYTES: usize = 256 * 1024;
@@ -79,7 +81,7 @@ pub struct Bundle {
#[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`, …).
+ /// `prompt-reply`, `plain-text`, or what an export-prompt reply says (`chatgpt`, `grok`, …).
#[serde(default)]
pub kind: String,
#[serde(default)]
@@ -375,6 +377,11 @@ pub fn normalize(mut bundle: Bundle, existing: &[String]) -> Checked {
bot.ref_ = r;
}
+ if bundle.source.kind == PLAIN_TEXT_KIND {
+ let who = bundle.bots.first().map(|b| b.ref_.clone());
+ warnings.push(Notice::new(who.as_deref(), "No name or memory found — we used the text as this bot's instructions. You can rename it after importing."));
+ }
+
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" };
diff --git a/src/import/parsers.rs b/src/import/parsers.rs
index d2b7b730..21f1f037 100644
--- a/src/import/parsers.rs
+++ b/src/import/parsers.rs
@@ -10,13 +10,14 @@
//! | 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 |
+//! | plain instructions | any other pasted text: one bot, the text as its instructions |
//! | 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,
+ MAX_TEXT_BYTES, MAX_ZIP_BYTES, PLAIN_TEXT_KIND,
};
use serde_json::Value;
@@ -58,12 +59,38 @@ pub fn parse_file(bytes: &[u8], filename: Option<&str>) -> Result<Bundle, Import
from_text(text, filename)
}
-/// Pasted text: usually the reply to the export prompt.
+/// Pasted text: usually the reply to the export prompt. Text that isn't one of the formats above
+/// and doesn't try to be (a bot's Instructions field copied as is) becomes one bot's instructions.
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)
+ let text = text.trim_start_matches('\u{feff}');
+ if text.trim().is_empty() {
+ return Err(invalid("There's nothing to import in this text. Paste your bot's reply or its instructions."));
+ }
+ match from_text(text, None) {
+ Err(ImportError::Invalid(_) | ImportError::Unsupported(_)) if !looks_structured(text) => Ok(from_plain_text(text)),
+ other => other,
+ }
+}
+
+/// Whether pasted text means to be JSON or front matter, so a broken reply still gets its error
+/// instead of being taken as instructions.
+fn looks_structured(text: &str) -> bool {
+ let t = text.trim_start();
+ t.starts_with('{') || t.starts_with("---") || t.contains("```json") || t.contains("\"format\"") || t.contains("kwant.bundle/")
+}
+
+/// One bot whose instructions are the whole text. Its name and title are the defaults
+/// [`super::normalize`] gives; it warns that nothing else was found.
+fn from_plain_text(text: &str) -> Bundle {
+ Bundle {
+ format: BUNDLE_FORMAT.into(),
+ source: Source { kind: PLAIN_TEXT_KIND.into(), ..Source::default() },
+ bots: vec![BotSpec { ref_: "main".into(), name: "Imported-bot".into(), persona_prompt: text.to_string(), ..BotSpec::default() }],
+ ..Bundle::default()
+ }
}
fn from_text(text: &str, filename: Option<&str>) -> Result<Bundle, ImportError> {
@@ -596,6 +623,21 @@ mod tests {
assert_eq!(json_block("```json\n{\"a\": 1}\nthe reply was cut"), Some("{\"a\": 1}"));
}
+ #[test]
+ fn pasted_plain_text_is_one_bot_and_broken_replies_keep_their_error() {
+ let b = parse_pasted("\u{feff}You review pull requests. Be kind.").unwrap();
+ assert_eq!(b.source.kind, crate::import::PLAIN_TEXT_KIND);
+ assert_eq!(b.bots.len(), 1);
+ assert_eq!(b.bots[0].persona_prompt, "You review pull requests. Be kind.");
+ // Braces in instructions aren't taken for a broken reply.
+ assert_eq!(parse_pasted("Greet {user} by name.").unwrap().bots[0].persona_prompt, "Greet {user} by name.");
+ assert!(matches!(parse_pasted(" \n"), Err(ImportError::Invalid(_))));
+ assert!(matches!(parse_pasted("{ \"format\": "), Err(ImportError::Invalid(_))));
+ assert!(matches!(parse_pasted("Here:\n```json\n{ nope }\n```"), Err(ImportError::Invalid(_))));
+ // A file upload doesn't fall back: an unknown file stays unknown.
+ assert!(parse_file(b"just words", Some("notes.txt")).is_err());
+ }
+
#[test]
fn memory_markdown() {
let m = memories_from_markdown("# Memory\n- likes tea\n- lives in\n Kyiv\n\nA paragraph\nover lines.");
diff --git a/src/import/prompts.rs b/src/import/prompts.rs
index 0ef0f728..72fe90fb 100644
--- a/src/import/prompts.rs
+++ b/src/import/prompts.rs
@@ -26,7 +26,7 @@ const SOURCES: [(&str, &str, &str, &str); 4] = [
(
"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.",
+ "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 instead copy its Instructions field from the GPT editor and paste that here; it becomes one bot's instructions.",
"chatgpt",
),
(
diff --git a/src/server/import_routes.rs b/src/server/import_routes.rs
index dd7c3cd4..30bf6955 100644
--- a/src/server/import_routes.rs
+++ b/src/server/import_routes.rs
@@ -263,8 +263,22 @@ pub async fn undo(State(state): State<AppState>, Scope(space): Scope, Path(id):
}
}
-fn download(bundle: &Bundle, name: &str) -> Response {
- let file: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' }).collect();
+/// A download file name from a bot or space name: ASCII letters, digits, `-` and `_`, other
+/// runs as one `-`; `fallback` when nothing is left.
+pub fn file_stem(name: &str, fallback: &str) -> String {
+ let mut out = String::new();
+ for c in name.chars() {
+ if c.is_ascii_alphanumeric() || c == '_' {
+ out.push(c);
+ } else if !out.ends_with('-') {
+ out.push('-');
+ }
+ }
+ let out = out.trim_matches('-');
+ if out.is_empty() { fallback.to_string() } else { out.chars().take(80).collect() }
+}
+
+fn download(bundle: &Bundle, file: &str) -> Response {
(
[(header::CONTENT_DISPOSITION, format!("attachment; filename=\"{file}.kwant.json\""))],
Json(bundle),
@@ -277,7 +291,7 @@ pub async fn export_kwant(State(state): State<AppState>, Path(id): Path<String>)
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)
+ download(&b, &file_stem(&name, &id))
}
Ok(None) => error(StatusCode::NOT_FOUND, "not_found", "bot not found"),
Err(e) => internal(e),
@@ -286,8 +300,12 @@ pub async fn export_kwant(State(state): State<AppState>, Path(id): Path<String>)
/// `GET /api/export?space=`: every bot and team in the space.
pub async fn export_space(State(state): State<AppState>, Scope(space): Scope) -> Response {
+ let name = match state.db.get_space(&space).await {
+ Ok(s) => s.map(|s| s.name).unwrap_or_default(),
+ Err(e) => return internal(e),
+ };
match state.db.export_space(&space).await {
- Ok(b) => download(&b, &format!("space-{}", space.as_str())),
+ Ok(b) => download(&b, &file_stem(&name, space.as_str())),
Err(e) => internal(e),
}
}
@@ -296,3 +314,17 @@ pub async fn export_space(State(state): State<AppState>, Scope(space): Scope) ->
pub async fn prompts() -> Response {
Json(import::prompts::export_prompts()).into_response()
}
+
+#[cfg(test)]
+mod tests {
+ use super::file_stem;
+
+ #[test]
+ fn file_stems() {
+ assert_eq!(file_stem("Default", "spc_x"), "Default");
+ assert_eq!(file_stem(" My Team / 2 ", "spc_x"), "My-Team-2");
+ assert_eq!(file_stem("Café", "spc_x"), "Caf");
+ assert_eq!(file_stem("★★", "spc_x"), "spc_x");
+ assert_eq!(file_stem("", "spc_x"), "spc_x");
+ }
+}
diff --git a/tests/import_test.rs b/tests/import_test.rs
index fa866dec..c49f5632 100644
--- a/tests/import_test.rs
+++ b/tests/import_test.rs
@@ -403,7 +403,10 @@ async fn oversize_and_unknown_inputs_are_refused() {
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
let (status, _) = json_call(&e.app, "POST", "/api/import/preview", json!({ "text": "x".repeat(300 * 1024) })).await;
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
- let (status, v) = json_call(&e.app, "POST", "/api/import/preview", json!({ "text": "just some words" })).await;
+ let (status, v) = json_call(&e.app, "POST", "/api/import/preview", json!({ "text": " \n\t " })).await;
+ assert_eq!((status, v["code"].as_str()), (StatusCode::UNPROCESSABLE_ENTITY, Some("invalid")), "{v}");
+ // A reply that means to be JSON but is broken keeps its error rather than becoming instructions.
+ let (status, v) = json_call(&e.app, "POST", "/api/import/preview", json!({ "text": "Here you go:\n```json\n{ \"format\": \"kwant.bundle/1\", \"bots\": [ }\n```" })).await;
assert_eq!((status, v["code"].as_str()), (StatusCode::UNPROCESSABLE_ENTITY, Some("invalid")), "{v}");
let (status, _) = send(&e.app, "POST", "/api/import/preview", "application/octet-stream", vec![0xff, 0xfe, 0x00]).await;
assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
@@ -492,3 +495,49 @@ async fn export_prompts_start_with_grok_chatgpt_claude() {
assert_eq!(ids, ["grok", "chatgpt", "claude", "other"]);
assert!(v[0]["prompt"].as_str().unwrap().contains("kwant.bundle/1"));
}
+
+#[tokio::test]
+async fn plain_text_becomes_one_bots_instructions_scrubbed_and_capped() {
+ let e = setup().await;
+ let before = row_counts(&e.tmp).await;
+ let text = "You are a friendly travel planner. Ask where {city} is before suggesting anything.\n\nKeep answers short.\nOur key is sk-ant-api03-FAKEFAKEFAKEFAKEFAKEFAKEFAKEFAKE.";
+ let (status, p) = json_call(&e.app, "POST", "/api/import/preview", json!({ "text": text })).await;
+ assert_eq!(status, StatusCode::OK, "{p}");
+ assert_eq!(p["can_apply"], true, "{p}");
+ assert_eq!(p["bundle"]["source"]["kind"], "plain-text");
+ assert_eq!(bot_names(&p), ["Imported-bot"]);
+ let persona = p["bundle"]["bots"][0]["persona_prompt"].as_str().unwrap();
+ assert!(persona.starts_with("You are a friendly travel planner. Ask where {city} is"), "{persona}");
+ assert!(!persona.contains("FAKEFAKE") && persona.contains("[removed key]"), "{persona}");
+ let warnings = p["warnings"].to_string();
+ assert!(warnings.contains("No name or memory found"), "{warnings}");
+ assert!(warnings.contains("key"), "{warnings}");
+ assert!(!warnings.contains("can't have spaces"), "the default name needs no cleaning: {warnings}");
+ assert_eq!(row_counts(&e.tmp).await, before, "preview writes nothing");
+
+ let (status, v) = apply(&e.app, &dflt(), &p["bundle"], &[]).await;
+ assert_eq!(status, StatusCode::CREATED, "{v}");
+ // A second paste gets a new name instead of overwriting the first.
+ let (_, again) = json_call(&e.app, "POST", "/api/import/preview", json!({ "text": "Be brief." })).await;
+ assert_eq!(bot_names(&again), ["Imported-bot-2"]);
+
+ // Over 16,000 characters: a problem in preview, nothing to apply.
+ let (status, p) = json_call(&e.app, "POST", "/api/import/preview", json!({ "text": "word ".repeat(4_000) })).await;
+ assert_eq!(status, StatusCode::OK, "{p}");
+ assert_eq!(p["can_apply"], false);
+ assert!(p["problems"][0]["message"].as_str().unwrap().contains("16,000"), "{p}");
+}
+
+#[tokio::test]
+async fn space_export_is_named_after_the_space() {
+ let e = setup().await;
+ let named = new_space(&e, "Travel Team!").await;
+ let symbols = new_space(&e, "★★★").await;
+ for (space, want) in [(dflt(), "Default.kwant.json".to_string()), (named, "Travel-Team.kwant.json".into()), (symbols.clone(), format!("{symbols}.kwant.json"))] {
+ let req = Request::builder().uri(format!("/api/export?space={space}")).body(Body::empty()).unwrap();
+ let resp = e.app.clone().oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let cd = resp.headers()["content-disposition"].to_str().unwrap().to_string();
+ assert_eq!(cd, format!("attachment; filename=\"{want}\""));
+ }
+}