Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
API-engine bots read their own folder (read_file, list_dir) (#722)
Oleksandr Ivanchenko44e4487d400f
diff --git a/src/drivers/api.rs b/src/drivers/api.rsindex 6ac55710..64e8c93f 100644--- a/src/drivers/api.rs+++ b/src/drivers/api.rs@@ -460,7 +460,7 @@ const DEFER_TOOLS_ABOVE_CHARS: usize = 12_000;const UPFRONT_TOOLS_CHARS: usize = 8_000;/// kwnt's own tools a turn always gets in full: talking to the person, memory, teammates, the/// browser and files. The rest (routines, bots, spaces, settings, …) are a lookup away.-const CORE_SELF_TOOLS: [&str; 13] = [+const CORE_SELF_TOOLS: [&str; 15] = ["ask_user","search_history","memory_add",@@ -474,6 +474,8 @@ const CORE_SELF_TOOLS: [&str; 13] = ["list_attachments","read_attachment","share_file",+ "read_file",+ "list_dir",];const FIND_TOOLS: &str = "kwnt_find_tools";const CALL_TOOL: &str = "kwnt_call_tool";@@ -1664,6 +1666,11 @@ impl Driver for ApiDriver {..Default::default()})}++ /// An API turn's only tools are kwant's and its MCP servers': no shell, no file reads (#715)+ fn needs_folder_tools(&self) -> bool {+ true+ }}#[cfg(test)]diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex f70f7449..1d8723d5 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -1044,6 +1044,12 @@ pub trait Driver: Send + Sync {fn streams_progress(&self) -> bool {false}++ /// Whether this driver's engine has no file tools of its own, so kwant offers the bot+ /// `read_file`/`list_dir` on its own folder (#715). CLI engines read with their own tools.+ fn needs_folder_tools(&self) -> bool {+ false+ }}/// The driver for a turn on `target_model` without a profile, and the engine it runs on: thediff --git a/src/server/bot_files.rs b/src/server/bot_files.rsnew file mode 100644index 00000000..af03e60e--- /dev/null+++ b/src/server/bot_files.rs@@ -0,0 +1,439 @@+//! A bot's own folder (`bot-workspaces/<kwant id>`, see [`crate::tools::bot_workspace`]) as two+//! read-only tools, `read_file` and `list_dir`, for engines that have no file tools of their own:+//! API engines (Custom API, API keys). CLI engines (Claude, Codex, Grok) read with their own tools+//! and are never offered these (GitHub issue #715, reported with this patch shape by calintro).+//!+//! Read-only, for the same reason as `space_docs`: a bot shouldn't write the words it then quotes.+//! Every path stays inside the folder: `..`, absolute paths, and symlinks (to a file or a folder)+//! that lead out of it are refused with a plain sentence, never file contents. A path must exist+//! to be read; nothing here creates anything.++use serde_json::{json, Value};+use std::io::{BufRead, BufReader, Read};+use std::path::{Component, Path, PathBuf};++pub const READ_FILE: &str = "read_file";+pub const LIST_DIR: &str = "list_dir";++/// Lines a `read_file` page has when the bot gives no `limit`.+pub const DEFAULT_LINES: usize = 600;+/// Most lines one `read_file` page has.+pub const MAX_LINES: usize = 2_000;+/// A longer line is cut, so one huge line (minified JSON, a data URI) can't fill the turn.+pub const MAX_LINE_CHARS: usize = 2_000;+/// Most bytes of text one page carries; past it the page ends early and says where to go on.+pub const MAX_PAGE_BYTES: usize = 100_000;+/// Biggest file `read_file` opens.+pub const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024;+/// Most entries one `list_dir` answer names.+pub const MAX_ENTRIES: usize = 500;++/// What a path leading out of the folder gets.+pub const OUTSIDE: &str = "That path is outside your folder, so I can't open it. Use a path inside your folder, like notes.md or docs/plan.md.";++/// The tools, in the self server's schema shape.+pub fn tools() -> Vec<Value> {+ vec![+ json!({+ "name": READ_FILE,+ "description": format!(+ "Read a text file in your own folder (the files the person put there for you). Give a path inside the folder, like notes.md or docs/plan.md. \+ Long files come in pages of {DEFAULT_LINES} lines (at most {MAX_LINES}): the answer says how many lines the file has in total and the offset to read on from. \+ Quote only what you read here, never from memory."+ ),+ "inputSchema": {+ "type": "object",+ "properties": {+ "path": {"type": "string", "description": "The file's path inside your folder, e.g. notes.md"},+ "offset": {"type": "integer", "description": "Lines to skip from the start (0 = the first line). The answer gives the next offset."},+ "limit": {"type": "integer", "description": format!("How many lines to read ({DEFAULT_LINES} if left out, at most {MAX_LINES}).")},+ },+ "required": ["path"],+ },+ }),+ json!({+ "name": LIST_DIR,+ "description": "List the files and folders in your own folder, or in a folder inside it. Leave path out for the folder itself.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "path": {"type": "string", "description": "A folder inside your folder, e.g. docs. Leave out for the folder itself."},+ },+ },+ }),+ ]+}++pub fn is_tool(name: &str) -> bool {+ matches!(name, READ_FILE | LIST_DIR)+}++/// Runs `name` in `workspace`: `Ok` with the text the bot reads, `Err` with a plain sentence.+pub fn run(workspace: &Path, name: &str, args: &Value) -> Result<String, String> {+ let path = args["path"].as_str().unwrap_or("");+ match name {+ READ_FILE => {+ if path.trim().is_empty() {+ return Err("path is required: the file's path inside your folder, like notes.md.".into());+ }+ let offset = count_arg(&args["offset"]).unwrap_or(0);+ let limit = count_arg(&args["limit"]).unwrap_or(DEFAULT_LINES).clamp(1, MAX_LINES);+ read_file(workspace, path, offset, limit)+ }+ LIST_DIR => list_dir(workspace, path),+ _ => Err(format!("{name} isn't a folder tool.")),+ }+}++/// A non-negative count from a JSON number or numeric string; negatives count as 0.+fn count_arg(v: &Value) -> Option<usize> {+ if let Some(n) = v.as_u64() {+ return Some(usize::try_from(n).unwrap_or(usize::MAX));+ }+ if let Some(n) = v.as_i64() {+ return Some(n.max(0) as usize);+ }+ if let Some(f) = v.as_f64() {+ return Some(if f.is_finite() && f > 0.0 { f as usize } else { 0 });+ }+ v.as_str().and_then(|s| s.trim().parse::<usize>().ok())+}++/// `raw` inside `workspace`, as a real path that exists and doesn't lead out of it.+///+/// Stricter than `tools::file_ops::resolve_safe_path`: only plain names (and `.`) are allowed, so+/// `..`, `/abs` and `C:\` never reach the file system; the path must exist; and its canonical form+/// (every symlink followed) must still be under the folder's canonical form.+pub fn resolve(workspace: &Path, raw: &str) -> Result<PathBuf, String> {+ let raw = raw.trim();+ let rel = Path::new(raw);+ if rel.components().any(|c| !matches!(c, Component::Normal(_) | Component::CurDir)) {+ return Err(OUTSIDE.into());+ }+ let root = workspace.canonicalize().map_err(|_| "I couldn't open your folder.".to_string())?;+ let real = match root.join(rel).canonicalize() {+ Ok(real) => real,+ Err(_) => {+ // A link whose target is gone: say it leads out when it does, never "missing" for it+ if root.join(rel).symlink_metadata().is_ok() {+ return Err(OUTSIDE.into());+ }+ return Err(format!("There's no {} in your folder.", shown(raw)));+ }+ };+ if !real.starts_with(&root) {+ return Err(OUTSIDE.into());+ }+ Ok(real)+}++/// `raw` as the bot named it, `your folder` for the folder itself.+fn shown(raw: &str) -> String {+ match raw.trim() {+ "" | "." | "./" => "your folder".into(),+ s => s.to_string(),+ }+}++fn read_file(workspace: &Path, raw: &str, offset: usize, limit: usize) -> Result<String, String> {+ let path = resolve(workspace, raw)?;+ let name = shown(raw);+ let meta = std::fs::metadata(&path).map_err(|_| format!("I couldn't open {name}."))?;+ if meta.is_dir() {+ return Err(format!("{name} is a folder: list it with list_dir."));+ }+ if !meta.is_file() {+ return Err(format!("{name} isn't a text file, so I can't read it here."));+ }+ if meta.len() > MAX_FILE_BYTES {+ return Err(format!("{name} is too big to read here ({} MB; the limit is {} MB).", meta.len() / (1024 * 1024), MAX_FILE_BYTES / (1024 * 1024)));+ }+ let file = std::fs::File::open(&path).map_err(|_| format!("I couldn't open {name}."))?;+ // The whole file is checked (and its lines counted), so a binary tail never reaches the page+ let mut reader = BufReader::new(file.take(MAX_FILE_BYTES + 1));+ let not_text = || format!("{name} isn't a text file, so I can't read it here.");+ let mut buf = Vec::new();+ let mut total = 0usize;+ let mut page = String::new();+ let mut shown_lines = 0usize;+ let mut full = false;+ loop {+ buf.clear();+ let n = reader.read_until(b'\n', &mut buf).map_err(|_| format!("I couldn't read {name}."))?;+ if n == 0 {+ break;+ }+ if buf.contains(&0) {+ return Err(not_text());+ }+ let line = std::str::from_utf8(&buf).map_err(|_| not_text())?;+ let line = line.strip_suffix('\n').unwrap_or(line);+ let line = line.strip_suffix('\r').unwrap_or(line);+ let i = total;+ total += 1;+ if i < offset || shown_lines >= limit || full {+ continue;+ }+ let cut = cut_line(line);+ if !page.is_empty() && page.len() + cut.len() + 1 > MAX_PAGE_BYTES {+ full = true;+ continue;+ }+ page.push_str(&cut);+ page.push('\n');+ shown_lines += 1;+ }+ let lines = |n: usize| if n == 1 { "1 line".to_string() } else { format!("{n} lines") };+ if total == 0 {+ return Ok(format!("{name}: 0 lines total (the file is empty)."));+ }+ if shown_lines == 0 {+ return Ok(format!("{name}: {} total. Nothing from offset {offset} on: the file ends at line {total}.", lines(total)));+ }+ let first = offset + 1;+ let last = offset + shown_lines;+ let next = if last < total {+ format!(" To read on, call read_file with offset {last}.")+ } else {+ " That's the end of the file.".to_string()+ };+ Ok(format!("{name}: {} total. Lines {first}–{last}:{next}\n\n{page}", lines(total)))+}++/// `line`, cut to [`MAX_LINE_CHARS`] characters with a note when longer.+fn cut_line(line: &str) -> String {+ match line.char_indices().nth(MAX_LINE_CHARS) {+ Some((at, _)) => format!("{}… [line cut: {} characters]", &line[..at], line.chars().count()),+ None => line.to_string(),+ }+}++fn list_dir(workspace: &Path, raw: &str) -> Result<String, String> {+ let path = resolve(workspace, raw)?;+ let name = shown(raw);+ if !path.is_dir() {+ return Err(format!("{name} is a file: read it with read_file."));+ }+ let read = std::fs::read_dir(&path).map_err(|_| format!("I couldn't list {name}."))?;+ let mut entries: Vec<(String, String)> = Vec::new();+ for entry in read.flatten() {+ let file_name = entry.file_name().to_string_lossy().into_owned();+ // A link is shown as one, not followed: read_file says whether it stays inside the folder+ let kind = match entry.file_type() {+ Ok(t) if t.is_symlink() => format!("{file_name} (link)"),+ Ok(t) if t.is_dir() => format!("{file_name}/"),+ _ => {+ let bytes = entry.metadata().map(|m| m.len()).unwrap_or(0);+ format!("{file_name} ({})", size(bytes))+ }+ };+ entries.push((file_name, kind));+ }+ entries.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()).then(a.0.cmp(&b.0)));+ if entries.is_empty() {+ return Ok(format!("{name} is empty."));+ }+ let total = entries.len();+ let mut out = format!("{name}: {} {}.\n", total, if total == 1 { "entry" } else { "entries" });+ for (_, line) in entries.iter().take(MAX_ENTRIES) {+ out.push_str(line);+ out.push('\n');+ }+ if total > MAX_ENTRIES {+ out.push_str(&format!("… and {} more not listed.\n", total - MAX_ENTRIES));+ }+ Ok(out)+}++fn size(bytes: u64) -> String {+ match bytes {+ 1 => "1 byte".into(),+ b if b < 1024 => format!("{b} bytes"),+ b if b < 1024 * 1024 => format!("{:.1} KB", b as f64 / 1024.0),+ b => format!("{:.1} MB", b as f64 / (1024.0 * 1024.0)),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn folder() -> (tempfile::TempDir, PathBuf) {+ let tmp = tempfile::tempdir().unwrap();+ let ws = tmp.path().join("space").join("bot-workspaces").join("bot_a");+ std::fs::create_dir_all(&ws).unwrap();+ (tmp, ws)+ }++ fn read(ws: &Path, args: Value) -> Result<String, String> {+ run(ws, READ_FILE, &args)+ }++ #[test]+ fn reads_a_file_and_says_how_many_lines_it_has() {+ let (_t, ws) = folder();+ std::fs::write(ws.join("notes.md"), "one\ntwo\r\nthree").unwrap();+ let text = read(&ws, json!({"path": "notes.md"})).unwrap();+ assert!(text.starts_with("notes.md: 3 lines total. Lines 1–3: That's the end of the file.\n\none\ntwo\nthree\n"), "{text}");+ // ./ and nested paths are fine+ std::fs::create_dir_all(ws.join("docs")).unwrap();+ std::fs::write(ws.join("docs/plan.md"), "plan\n").unwrap();+ assert!(read(&ws, json!({"path": "./docs/plan.md"})).unwrap().contains("1 line total"));+ }++ #[test]+ fn a_long_file_reads_in_pages_and_an_offset_past_the_end_says_so() {+ let (_t, ws) = folder();+ let body: String = (1..=7_000).map(|i| format!("line {i}\n")).collect();+ std::fs::write(ws.join("big.txt"), body).unwrap();+ let first = read(&ws, json!({"path": "big.txt"})).unwrap();+ assert!(first.starts_with("big.txt: 7000 lines total. Lines 1–600: To read on, call read_file with offset 600."), "{first}");+ assert!(first.ends_with("line 600\n") && !first.contains("line 601\n"));+ // The bot pages on with the offset it was given+ let mut offset = 600;+ let mut pages = 1;+ loop {+ let page = read(&ws, json!({"path": "big.txt", "offset": offset, "limit": 2000})).unwrap();+ pages += 1;+ if page.contains("That's the end of the file.") {+ assert!(page.ends_with("line 7000\n"), "{}", &page[..200]);+ break;+ }+ let next = page.split("offset ").nth(1).unwrap().split('.').next().unwrap().parse::<usize>().unwrap();+ assert_eq!(next, offset + 2000);+ offset = next;+ }+ assert_eq!(pages, 5, "600 + 2000 + 2000 + 2000 + 400");+ // limit is capped at 2,000 and at least 1+ let capped = read(&ws, json!({"path": "big.txt", "limit": 50_000})).unwrap();+ assert!(capped.contains("Lines 1–2000:"), "{}", &capped[..120]);+ let one = read(&ws, json!({"path": "big.txt", "limit": 0, "offset": "9"})).unwrap();+ assert!(one.contains("Lines 10–10:"), "{}", &one[..120]);+ // Past the end: an empty page and the total+ let past = read(&ws, json!({"path": "big.txt", "offset": 8000})).unwrap();+ assert_eq!(past, "big.txt: 7000 lines total. Nothing from offset 8000 on: the file ends at line 7000.");+ let neg = read(&ws, json!({"path": "big.txt", "offset": -5, "limit": 1})).unwrap();+ assert!(neg.contains("Lines 1–1:"), "{neg}");+ }++ #[test]+ fn a_huge_line_is_cut_and_a_page_stays_small() {+ let (_t, ws) = folder();+ let long = "x".repeat(50_000);+ std::fs::write(ws.join("min.json"), format!("{long}\nshort\n")).unwrap();+ let text = read(&ws, json!({"path": "min.json"})).unwrap();+ assert!(text.contains("… [line cut: 50000 characters]"), "{}", &text[..200]);+ assert!(text.contains("\nshort\n"));+ assert!(text.len() < MAX_LINE_CHARS + 300, "{}", text.len());+ // Many long lines: the page ends early at its byte budget and says where to go on+ let wide: String = (0..2_000).map(|i| format!("{i:04}{}\n", "y".repeat(1_500))).collect();+ std::fs::write(ws.join("wide.txt"), wide).unwrap();+ let page = read(&ws, json!({"path": "wide.txt", "limit": 2000})).unwrap();+ assert!(page.len() <= MAX_PAGE_BYTES + 200, "{}", page.len());+ let shown = page.lines().filter(|l| l.contains("yyy")).count();+ assert!(shown > 0 && shown < 2_000, "{shown}");+ assert!(page.contains(&format!("To read on, call read_file with offset {shown}.")), "{}", &page[..200]);+ }++ #[test]+ fn binary_and_non_utf8_files_are_not_text() {+ let (_t, ws) = folder();+ std::fs::write(ws.join("img.png"), b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR").unwrap();+ std::fs::write(ws.join("latin1.txt"), b"caf\xe9 au lait\n").unwrap();+ // Text first, a binary tail later: still refused, never a page of the text part+ let mut tail = "fine line\n".repeat(700).into_bytes();+ tail.extend_from_slice(b"\0\x01\x02");+ std::fs::write(ws.join("mixed.log"), tail).unwrap();+ for f in ["img.png", "latin1.txt", "mixed.log"] {+ let e = read(&ws, json!({"path": f})).unwrap_err();+ assert_eq!(e, format!("{f} isn't a text file, so I can't read it here."));+ }+ assert_eq!(read(&ws, json!({"path": "empty.txt"})).unwrap_err(), "There's no empty.txt in your folder.");+ std::fs::write(ws.join("empty.txt"), "").unwrap();+ assert_eq!(read(&ws, json!({"path": "empty.txt"})).unwrap(), "empty.txt: 0 lines total (the file is empty).");+ }++ #[test]+ fn paths_out_of_the_folder_are_refused_with_no_contents() {+ let (tmp, ws) = folder();+ let secret = tmp.path().join("secret.txt");+ std::fs::write(&secret, "TOP SECRET\n").unwrap();+ // A teammate's folder in the same space+ let other = ws.parent().unwrap().join("bot_b");+ std::fs::create_dir_all(&other).unwrap();+ let theirs = other.join("notes.md");+ std::fs::write(&theirs, "B'S NOTES\n").unwrap();+ let bad = [+ "../secret.txt",+ "../../secret.txt",+ "../bot_b/notes.md",+ "docs/../../bot_b/notes.md",+ "..",+ secret.to_str().unwrap(),+ theirs.to_str().unwrap(),+ "/etc/passwd",+ "/",+ ];+ for p in bad {+ for tool in [READ_FILE, LIST_DIR] {+ let e = run(&ws, tool, &json!({"path": p})).unwrap_err();+ assert_eq!(e, OUTSIDE, "{tool} {p}");+ }+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::symlink;+ symlink(&secret, ws.join("link.txt")).unwrap();+ symlink(tmp.path(), ws.join("up")).unwrap();+ symlink(&other, ws.join("teammate")).unwrap();+ symlink(tmp.path().join("gone.txt"), ws.join("dangling.txt")).unwrap();+ // A link into a folder that doesn't exist yet: resolve_safe_path's "new file" branch+ // would let `dangling_dir/x` through; here it is refused+ symlink(tmp.path().join("later"), ws.join("dangling_dir")).unwrap();+ for p in ["link.txt", "up/secret.txt", "up", "teammate/notes.md", "teammate", "dangling.txt"] {+ for tool in [READ_FILE, LIST_DIR] {+ let e = run(&ws, tool, &json!({"path": p})).unwrap_err();+ assert_eq!(e, OUTSIDE, "{tool} {p}");+ }+ }+ let e = read(&ws, json!({"path": "dangling_dir/x.txt"})).unwrap_err();+ assert!(!e.contains("SECRET") && e.starts_with("There's no"), "{e}");+ std::fs::create_dir_all(tmp.path().join("later")).unwrap();+ std::fs::write(tmp.path().join("later/x.txt"), "LATER SECRET\n").unwrap();+ assert_eq!(read(&ws, json!({"path": "dangling_dir/x.txt"})).unwrap_err(), OUTSIDE);+ // A link that stays inside the folder is fine+ std::fs::write(ws.join("real.md"), "inside\n").unwrap();+ symlink(ws.join("real.md"), ws.join("alias.md")).unwrap();+ assert!(read(&ws, json!({"path": "alias.md"})).unwrap().contains("inside"));+ // The listing names links without following them+ let listed = run(&ws, LIST_DIR, &json!({})).unwrap();+ assert!(listed.contains("link.txt (link)") && listed.contains("up (link)"), "{listed}");+ assert!(!listed.contains("secret.txt"), "{listed}");+ }+ }++ #[test]+ fn lists_the_folder_sorted_with_kinds() {+ let (_t, ws) = folder();+ std::fs::write(ws.join("b.txt"), "12345").unwrap();+ std::fs::write(ws.join("A.md"), "").unwrap();+ std::fs::create_dir_all(ws.join("docs")).unwrap();+ std::fs::write(ws.join("docs/plan.md"), "p").unwrap();+ let text = run(&ws, LIST_DIR, &json!({})).unwrap();+ assert_eq!(text, "your folder: 3 entries.\nA.md (0 bytes)\nb.txt (5 bytes)\ndocs/\n");+ assert_eq!(run(&ws, LIST_DIR, &json!({"path": "docs"})).unwrap(), "docs: 1 entry.\nplan.md (1 byte)\n");+ assert_eq!(run(&ws, LIST_DIR, &json!({"path": "b.txt"})).unwrap_err(), "b.txt is a file: read it with read_file.");+ assert_eq!(read(&ws, json!({"path": "docs"})).unwrap_err(), "docs is a folder: list it with list_dir.");+ assert_eq!(read(&ws, json!({})).unwrap_err(), "path is required: the file's path inside your folder, like notes.md.");+ std::fs::create_dir_all(ws.join("empty")).unwrap();+ assert_eq!(run(&ws, LIST_DIR, &json!({"path": "empty"})).unwrap(), "empty is empty.");+ }++ #[test]+ fn the_schemas_offer_exactly_the_two_read_tools() {+ let names: Vec<String> = tools().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect();+ assert_eq!(names, [READ_FILE, LIST_DIR]);+ assert!(is_tool("read_file") && is_tool("list_dir") && !is_tool("write_file"));+ assert_eq!(tools()[0]["inputSchema"]["required"], json!(["path"]));+ }+}diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex fd377df2..fb497c1e 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -409,6 +409,18 @@ pub struct SelfScope {/// [`self_endpoint`], past `McpToolSession::call`'s guard; every clone of this turn's scope/// shares this one, and it goes when `finish_turn` drops the scope.pub repeats: Arc<crate::mcp::repeat_guard::RepeatGuard>,+ /// #715: the engine this turn runs on now has no file tools of its own (an API engine), so+ /// `read_file`/`list_dir` on the bot's own folder ([`super::bot_files`]) are offered. Set per+ /// engine attempt by the chat turn (a failover can move a turn from an API engine to a CLI);+ /// every clone of the turn's scope shares it. Off by default: CLI engines read with their own tools.+ pub folder_tools: Arc<std::sync::atomic::AtomicBool>,+}++impl SelfScope {+ /// Whether this turn is offered `read_file`/`list_dir` on its bot's own folder (see `folder_tools`).+ pub fn offers_folder_tools(&self) -> bool {+ self.folder_tools.load(std::sync::atomic::Ordering::Relaxed)+ }}/// Where a turn runs, for the delegation tools: results go back to this chat.@@ -474,6 +486,8 @@ pub(crate) const READ_ONLY_SELF_TOOLS: &[&str] = &["hire_status","list_attachments","read_attachment",+ super::bot_files::READ_FILE,+ super::bot_files::LIST_DIR,"mcp_search",super::page_source::TOOL,"skill_get",@@ -638,6 +652,9 @@ fn tool_list(scope: &SelfScope, board: bool, notes: bool) -> Value {list.extend(super::smart_results::present_result_tools());list.extend(super::mcp_suggest::tools());list.extend(super::page_source::tools());+ if scope.offers_folder_tools() {+ list.extend(super::bot_files::tools());+ }if notes {list.push(super::tool_notes::tool());}@@ -1347,6 +1364,20 @@ async fn call_tool(});};match name {+ // #715: the bot's own folder, read-only, on engines without file tools of their own+ n if super::bot_files::is_tool(n) => {+ if !scope.offers_folder_tools() {+ return (format!("{n} isn't offered on this engine: read files with your own tools."), true);+ }+ let Some(space) = db.space_of_kwant(&scope.kwant_id).await.ok().flatten() else {+ return ("I couldn't find your space.".into(), true);+ };+ let folder = crate::tools::bot_workspace(&crate::db::spaces::space_data_dir(&state.config.data_dir, &space), &scope.kwant_id);+ match super::bot_files::run(&folder, n, args) {+ Ok(text) => (text, false),+ Err(e) => (e, true),+ }+ }"search_history" => {let Some(query) = str_arg("query") else {return ("query is required".into(), true);@@ -2392,6 +2423,7 @@ mod tests {workspace: None,sandbox_target: browser.then(|| "t".into()),repeats: Default::default(),+ folder_tools: Default::default(),}}@@ -2404,6 +2436,34 @@ mod tests {.collect()}+ /// #715: only a turn on an engine without file tools (an API engine) is offered the bot's+ /// folder, once; a CLI turn (claude, codex, grok) gets nothing new next to its own Read/read_file.+ #[test]+ fn only_api_engine_turns_are_offered_the_folder_tools_once() {+ let cli = sign_in_scope(true, true, true);+ let list = names(&cli);+ assert!(!list.iter().any(|n| n == "read_file" || n == "list_dir" || n == "write_file"), "{list:?}");+ let api = sign_in_scope(true, true, true);+ api.folder_tools.store(true, std::sync::atomic::Ordering::Relaxed);+ let list = names(&api);+ for tool in ["read_file", "list_dir"] {+ assert_eq!(list.iter().filter(|n| *n == tool).count(), 1, "{tool}: {list:?}");+ }+ assert!(!list.iter().any(|n| n == "write_file"), "read-only: {list:?}");+ let mut unique = list.clone();+ unique.sort();+ unique.dedup();+ assert_eq!(unique.len(), list.len(), "no tool name twice: {list:?}");+ // Every clone of a turn's scope sees the attempt's engine (the registered one is a clone)+ let registered = cli.clone();+ cli.folder_tools.store(true, std::sync::atomic::Ordering::Relaxed);+ assert!(registered.offers_folder_tools());+ cli.folder_tools.store(false, std::sync::atomic::Ordering::Relaxed);+ assert!(!names(®istered).iter().any(|n| n == "read_file"));+ // Reads of the bot's own folder are free even in an always-ask turn+ assert!(READ_ONLY_SELF_TOOLS.contains(&"read_file") && READ_ONLY_SELF_TOOLS.contains(&"list_dir"));+ }+#[test]fn browser_sign_in_is_offered_with_both_tools_in_a_chat_turn() {// A chat turn, team lead included (routes.rs sets origin, cancel and the browser for every one)diff --git a/src/server/human_steps.rs b/src/server/human_steps.rsindex 8979318e..b0c4bf55 100644--- a/src/server/human_steps.rs+++ b/src/server/human_steps.rs@@ -938,6 +938,7 @@ mod tests {workspace: None,sandbox_target: Some("team".into()),repeats: Default::default(),+ folder_tools: Default::default(),}}diff --git a/src/server/missions/truth_ledger.rs b/src/server/missions/truth_ledger.rsindex 9b779b57..c1dac6a4 100644--- a/src/server/missions/truth_ledger.rs+++ b/src/server/missions/truth_ledger.rs@@ -103,8 +103,10 @@ const OUTSIDE_TOOLS: &[&str] = &["execute_shell",];-/// kwant's own tools that read outside text: a page, an attachment, another server's tools.-const OUTSIDE_SELF_TOOLS: &[&str] = &["read_attachment", "mcp_search", crate::server::page_source::TOOL];+/// kwant's own tools that read outside text: a page, an attachment, a file in the bot's folder+/// (put there by the person, or fetched by an earlier turn), another server's tools.+const OUTSIDE_SELF_TOOLS: &[&str] =+ &["read_attachment", crate::server::bot_files::READ_FILE, "mcp_search", crate::server::page_source::TOOL];fn outside_self_tool(tool: &str) -> bool {tool.starts_with("browser_") || OUTSIDE_SELF_TOOLS.contains(&tool)diff --git a/src/server/mod.rs b/src/server/mod.rsindex ba132fc4..0ee6814c 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -48,6 +48,7 @@ pub mod computer;pub mod mcp_directory;pub mod mcp_suggest;pub mod page_source;+pub mod bot_files;pub mod tool_failures;pub mod tool_notes;pub mod openai_key;diff --git a/src/server/routes.rs b/src/server/routes.rsindex 45840e53..b538e5e6 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3011,6 +3011,7 @@ async fn run_kwant_turn_inner(workspace: workspace_dir.clone(),sandbox_target: Some(sandbox_target.clone()),repeats: Default::default(),+ folder_tools: Default::default(),};// A replay works in its own scratch browser and asks nobodylet _turn_on_browser = opts.rehearse.is_none().then(|| state.human_steps.track_turn(&sandbox_target, turn_scope.clone()));@@ -3445,6 +3446,8 @@ async fn run_kwant_turn_inner(break;}};+ // #715: an API engine has no file tools of its own, so this attempt offers the bot's folder+ turn_scope.folder_tools.store(driver.needs_folder_tools(), std::sync::atomic::Ordering::Relaxed);// The model for the engine this attempt runs on: the pinned one, else the effort's tierlet runs_on = host_engine.or_else(|| profile.as_ref().and_then(super::profile_turn::profile_engine));let custom = profile.as_ref().filter(|p| p.kind == "custom_api");diff --git a/tests/bot_files_test.rs b/tests/bot_files_test.rsnew file mode 100644index 00000000..01de09df--- /dev/null+++ b/tests/bot_files_test.rs@@ -0,0 +1,299 @@+//! #715: a bot on an API engine reads its own folder (`bot-workspaces/<kwant id>`) with+//! `read_file`/`list_dir`; CLI engines are offered nothing new. End to end: a Custom API account+//! against a fake OpenAI-compatible server that calls `read_file` on notes.md and answers with the+//! line count it read. Then, at kwant's tool endpoint: a teammate's folder, `..`, absolute paths and+//! symlinks are refused; a bot with no space is told so; a CLI turn's list has no folder tools and a+//! call to one is refused; a customer's turn still asks before a read.++mod common;++use axum::{+ extract::State,+ http::{HeaderMap, StatusCode},+ response::IntoResponse,+ routing::{get, post},+ Json, Router,+};+use common::*;+use kwnt::drivers::RuntimeEvent;+use kwnt::server::bot_files::OUTSIDE;+use kwnt::server::continuity::{SelfScope, TurnOrigin};+use kwnt::server::mcp_runtime;+use serde_json::{json, Value};+use std::path::PathBuf;+use std::sync::atomic::Ordering;+use std::sync::{Arc, Mutex};+use std::time::Duration;++const KEY: &str = "sk-custom-files-0123456789";+const LINES: usize = 7_160;++/// Every chat request the fake model got.+type Seen = Arc<Mutex<Vec<Value>>>;++/// A fake OpenAI-compatible server: lists one model; a request with `read_file` offered and no+/// tool result yet calls it on notes.md; one with a tool result answers with that result's first+/// line; anything else says no file tool was offered.+async fn fake_model() -> (String, Seen) {+ let seen: Seen = Arc::default();+ let app = Router::new()+ .route("/v1/models", get(|| async { Json(json!({"data": [{"id": "gpt-files"}]})) }))+ .route(+ "/v1/chat/completions",+ post(|State(seen): State<Seen>, h: HeaderMap, Json(body): Json<Value>| async move {+ seen.lock().unwrap().push(body.clone());+ if h.get("authorization").and_then(|v| v.to_str().ok()) != Some(&format!("Bearer {KEY}")) {+ return (StatusCode::UNAUTHORIZED, "bad key").into_response();+ }+ let reply = |content: String| Json(json!({"choices": [{"message": {"role": "assistant", "content": content}}], "usage": {"total_tokens": 9}})).into_response();+ let messages = body["messages"].as_array().cloned().unwrap_or_default();+ if let Some(result) = messages.iter().rev().find(|m| m["role"] == "tool") {+ let text = result["content"].as_str().unwrap_or("").lines().next().unwrap_or("").to_string();+ return reply(format!("I read it: {text}"));+ }+ let offered = body["tools"].as_array().into_iter().flatten().any(|t| t["function"]["name"] == "mcp__kwnt_tools__read_file");+ if !offered || body["stream"] == true {+ return reply("NO FILE TOOL".into());+ }+ Json(json!({+ "choices": [{"message": {"role": "assistant", "content": "", "tool_calls": [{+ "id": "call_read", "type": "function",+ "function": {"name": "mcp__kwnt_tools__read_file", "arguments": "{\"path\":\"notes.md\"}"},+ }]}}],+ "usage": {"total_tokens": 9},+ }))+ .into_response()+ }),+ )+ .with_state(seen.clone());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let root = format!("http://{}", listener.local_addr().unwrap());+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ (root, seen)+}++/// A bot's own folder, as kwant makes it.+async fn folder_of(env: &Env, kwant: &str) -> PathBuf {+ let space = env.state.db.space_of_kwant(kwant).await.unwrap().unwrap();+ kwnt::tools::bot_workspace(&kwnt::db::spaces::space_data_dir(&env.state.config.data_dir, &space), kwant)+}++/// The bot's last saved reply.+async fn last_reply(env: &Env, kwant: &str) -> String {+ let saved = env.state.db.list_messages(kwant, 10).await.unwrap();+ saved.iter().rev().find(|m| m.sender_role == "kwant").map(|m| m.text.clone()).unwrap_or_default()+}++/// Sends `prompt` to `kwant` and waits for its turn to end.+async fn turn(env: &Env, kwant: &str, prompt: &str) {+ let mut rx = env.state.event_sender.subscribe();+ send_direct(env, kwant, prompt, json!({})).await;+ tokio::time::timeout(Duration::from_secs(90), async {+ while let Ok(e) = rx.recv().await {+ if matches!(e.unscoped(), RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kwant) {+ break;+ }+ }+ })+ .await+ .expect("turn did not end");+}++#[tokio::test]+async fn a_custom_api_bot_reads_notes_md_in_its_folder_and_gets_the_line_count() {+ let env = setup().await;+ let (root, seen) = fake_model().await;+ let (s, space) = call(&env.app, "POST", "/api/spaces", Some(json!({"name": "API files", "icon": "🧪", "this_machine_enabled": false}))).await;+ assert_eq!(s, StatusCode::CREATED, "{space}");+ let space = space["id"].as_str().unwrap().to_string();+ let (s, acct) = call(+ &env.app,+ "POST",+ &format!("/api/profiles?space={space}"),+ Some(json!({"engine": "custom", "kind": "custom_api", "name": "Fake OpenAI", "protocol": "openai-chat", "base_url": format!("{root}/v1"), "api_key": KEY, "model": "gpt-files"})),+ )+ .await;+ assert_eq!(s, StatusCode::CREATED, "{acct}");+ let (s, bot) = call(+ &env.app,+ "POST",+ &format!("/api/kwants?space={space}"),+ Some(json!({"name": "Reader", "title": "Tester", "persona_prompt": "", "avatar_sprite": "s", "driver_type": "api", "preferred_model": "custom"})),+ )+ .await;+ assert!(s.is_success(), "{s} {bot}");+ let kid = bot["id"].as_str().unwrap().to_string();+ let folder = folder_of(&env, &kid).await;+ let notes: String = (1..=LINES).map(|i| format!("note {i}\n")).collect();+ std::fs::write(folder.join("notes.md"), notes).unwrap();++ turn(&env, &kid, "read the file notes.md from your workspace and tell me how many lines it has").await;++ let reply = last_reply(&env, &kid).await;+ assert!(reply.starts_with("I read it:") && reply.contains(&format!("notes.md: {LINES} lines total. Lines 1–600:")), "{reply}");+ let seen = seen.lock().unwrap();+ let first = seen.iter().find(|b| b["tools"].is_array()).expect("a request with tools");+ let names: Vec<&str> = first["tools"].as_array().unwrap().iter().filter_map(|t| t["function"]["name"].as_str()).collect();+ for tool in ["mcp__kwnt_tools__read_file", "mcp__kwnt_tools__list_dir"] {+ assert_eq!(names.iter().filter(|n| **n == tool).count(), 1, "{tool} offered once, up front: {names:?}");+ }+ assert!(!names.iter().any(|n| n.ends_with("write_file")), "read-only: {names:?}");+ // The page went back to the model as the tool's result, with the file's own words+ let result = seen.iter().flat_map(|b| b["messages"].as_array().cloned().unwrap_or_default()).find(|m| m["role"] == "tool").expect("a tool result");+ let text = result["content"].as_str().unwrap();+ assert!(text.contains("note 1\n") && text.contains("note 600\n") && !text.contains("note 601\n"), "{}", &text[..200.min(text.len())]);+}++/// A live turn for `scope`'s bot opened the way a chat turn opens it, on an API engine or not;+/// returns its token.+async fn open_turn(env: &Env, scope: SelfScope, api: bool, opts: mcp_runtime::TurnApprovalOpts) -> String {+ let k = env.state.db.get_kwant(&env.a).await.unwrap().unwrap();+ scope.folder_tools.store(api, Ordering::Relaxed);+ let turn = scope.turn_id.clone();+ mcp_runtime::prepare_turn_with_opts(&env.state, &k, turn, None, Some(scope), opts).await.unwrap().1+}++fn scope_of(kwant: &str, turn: &str) -> SelfScope {+ SelfScope {+ kwant_id: kwant.into(),+ kwant_name: "Bot".into(),+ origin: Some(TurnOrigin { direct_kwant_id: Some(kwant.into()), ..Default::default() }),+ turn_id: Some(turn.into()),+ ..Default::default()+ }+}++async fn rpc(env: &Env, token: &str, method: &str, params: Value) -> Value {+ let (s, v) = call_with(+ &env.app,+ "POST",+ "/api/mcp/self",+ Some(json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})),+ &[("authorization", format!("Bearer {token}").as_str())],+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ v["result"].clone()+}++/// (text, isError) of a call to kwant's own `tool`.+async fn tool(env: &Env, token: &str, name: &str, args: Value) -> (String, bool) {+ let r = rpc(env, token, "tools/call", json!({"name": name, "arguments": args})).await;+ let text = r["content"].as_array().unwrap().iter().filter_map(|c| c["text"].as_str()).collect::<Vec<_>>().join("\n");+ (text, r["isError"].as_bool().unwrap())+}++async fn listed(env: &Env, token: &str) -> Vec<String> {+ let r = rpc(env, token, "tools/list", json!({})).await;+ r["tools"].as_array().unwrap().iter().filter_map(|t| t["name"].as_str().map(String::from)).collect()+}++#[tokio::test]+async fn the_endpoint_keeps_a_bot_inside_its_own_folder() {+ let env = setup().await;+ let mine = folder_of(&env, &env.a).await;+ let theirs = folder_of(&env, &env.b).await;+ assert_eq!(mine.parent(), theirs.parent(), "two bots of one space");+ std::fs::write(mine.join("notes.md"), "mine\n").unwrap();+ std::fs::write(theirs.join("secret.md"), "B ONLY\n").unwrap();+ let tok = open_turn(&env, scope_of(&env.a, "turn-files"), true, Default::default()).await;++ let (text, err) = tool(&env, &tok, "read_file", json!({"path": "notes.md"})).await;+ assert!(!err && text.contains("1 line total") && text.ends_with("mine\n"), "{text}");+ let (text, err) = tool(&env, &tok, "list_dir", json!({})).await;+ assert!(!err && text.contains("notes.md (5 bytes)"), "{text}");++ let b_dir = theirs.file_name().unwrap().to_str().unwrap().to_string();+ let mut bad: Vec<String> = vec![+ format!("../{b_dir}/secret.md"),+ format!("../{b_dir}"),+ theirs.join("secret.md").to_string_lossy().into_owned(),+ "../../../../etc/passwd".into(),+ "/etc/passwd".into(),+ ];+ // Symlinks are unix-only here; `cfg!` (not `#[cfg]`) keeps `bad` mutated on+ // every target, so Windows clippy sees no unused `mut`.+ #[cfg(unix)]+ {+ std::os::unix::fs::symlink(&theirs, mine.join("teammate")).unwrap();+ std::os::unix::fs::symlink(theirs.join("secret.md"), mine.join("their.md")).unwrap();+ }+ if cfg!(unix) {+ bad.extend(["teammate/secret.md".into(), "teammate".into(), "their.md".into()]);+ }+ for path in &bad {+ for name in ["read_file", "list_dir"] {+ let (text, err) = tool(&env, &tok, name, json!({"path": path})).await;+ assert!(err, "{name} {path}");+ assert_eq!(text, OUTSIDE, "{name} {path}");+ }+ }+ mcp_runtime::finish_turn(&env.state, &tok).await;++ // A bot whose space can't be found+ let ghost = open_turn(&env, scope_of("ghost-bot", "turn-ghost"), true, Default::default()).await;+ assert_eq!(tool(&env, &ghost, "read_file", json!({"path": "notes.md"})).await, ("I couldn't find your space.".into(), true));+ mcp_runtime::finish_turn(&env.state, &ghost).await;+}++#[tokio::test]+async fn cli_turns_get_no_folder_tools_and_a_call_to_one_is_refused() {+ let env = setup().await;+ std::fs::write(folder_of(&env, &env.a).await.join("notes.md"), "mine\n").unwrap();+ // At the endpoint: the list a CLI turn reads has neither tool, and a call is refused+ let cli = open_turn(&env, scope_of(&env.a, "turn-cli"), false, Default::default()).await;+ let names = listed(&env, &cli).await;+ assert!(!names.iter().any(|n| n == "read_file" || n == "list_dir"), "{names:?}");+ let (text, err) = tool(&env, &cli, "read_file", json!({"path": "notes.md"})).await;+ assert!(err && text.contains("isn't offered on this engine"), "{text}");+ mcp_runtime::finish_turn(&env.state, &cli).await;+ let api = open_turn(&env, scope_of(&env.a, "turn-api"), true, Default::default()).await;+ let names = listed(&env, &api).await;+ for t in ["read_file", "list_dir"] {+ assert_eq!(names.iter().filter(|n| *n == t).count(), 1, "{t}: {names:?}");+ }+ mcp_runtime::finish_turn(&env.state, &api).await;++ // A whole turn on the fake claude CLI: the call doesn't run+ let marker = call_tool_marker("read_file", json!({"path": "notes.md"}));+ send_direct(&env, &env.a, &format!("{marker} REPLYTAG:cli"), json!({})).await;+ let reply = wait_reply(&env, &env.a, "answer cli").await;+ assert!(reply.text.contains("isn't offered on this engine") && reply.text.contains("TOOLERROR"), "{}", reply.text);+ assert!(!reply.text.contains("mine"), "{}", reply.text);+}++#[tokio::test]+async fn reads_need_no_card_in_an_always_ask_turn_but_a_customer_turn_still_asks() {+ use kwnt::mcp::{ToolApprovalRequest, ToolApprover, SELF_SERVER_NAME};+ let env = setup().await;+ std::fs::write(folder_of(&env, &env.a).await.join("notes.md"), "mine\n").unwrap();+ // A turn kwnt started on its own asks for everything but kwant's own reads+ let approver = kwnt::server::continuity::SelfToolsApprover {+ inner: Arc::new(kwnt::mcp::FixedApprover(false)),+ always_ask: true,+ browser: None,+ };+ let req = |tool: &str| ToolApprovalRequest {+ kwant_id: env.a.clone(),+ kwant_name: "A".into(),+ turn_id: "t".into(),+ tool_name: format!("mcp__{SELF_SERVER_NAME}__{tool}"),+ server: SELF_SERVER_NAME.into(),+ tool: tool.into(),+ arguments: json!({"path": "notes.md"}),+ builtin: None,+ smart: None,+ payment: None,+ };+ assert!(approver.approve(req("read_file")).await);+ assert!(approver.approve(req("list_dir")).await);+ assert!(!approver.approve(req("memory_add")).await, "the approver still asks for a write");++ // A customer's message started this turn: kwant's endpoint runs no call the approver didn't allow+ let opts = mcp_runtime::TurnApprovalOpts { every_call: true, ..Default::default() };+ let customer = open_turn(&env, scope_of(&env.a, "turn-customer"), true, opts).await;+ let (text, err) = tool(&env, &customer, "read_file", json!({"path": "notes.md"})).await;+ assert!(err, "{text}");+ assert_eq!(text, mcp_runtime::EVERY_CALL_REFUSED);+ mcp_runtime::finish_turn(&env.state, &customer).await;+}diff --git a/tests/spaces_isolation_test.rs b/tests/spaces_isolation_test.rsindex a6b3c955..6a4389fb 100644--- a/tests/spaces_isolation_test.rs+++ b/tests/spaces_isolation_test.rs@@ -326,6 +326,7 @@ async fn delegation_without_a_member_list_stays_in_the_leads_space() {workspace: None,sandbox_target: None,repeats: Default::default(),+ folder_tools: Default::default(),};let (text, is_error) = delegation::tool_delegate(&env.state, &scope, &json!({"to": "Remy", "task": "help"})).await;assert!(is_error, "{text}");@@ -502,6 +503,7 @@ async fn the_search_tool_only_finds_messages_in_the_agents_space() {workspace: None,sandbox_target: None,repeats: Default::default(),+ folder_tools: Default::default(),},);let resp = env