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.

0.8.0 import A1–A3: five formats, this computer, GitHub links (#455)

Oleksandr Ivanchenko80981faf5591
diff --git a/src/import/archive.rs b/src/import/archive.rs
index 51eb5977..e814eebf 100644
--- a/src/import/archive.rs
+++ b/src/import/archive.rs
@@ -17,6 +17,8 @@ pub struct Entry {
pub struct Unzipped {
pub entries: Vec<Entry>,
pub skipped: Vec<String>,
+ /// The archive comment (codeload writes the commit id there).
+ pub comment: Option<String>,
}
const READ_EXTENSIONS: [&str; 4] = [".json", ".md", ".png", ".txt"];
@@ -40,15 +42,100 @@ fn safe_path(name: &str) -> Option<String> {
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.
+/// Dotfiles kwant reads even though they're hidden: Paperclip's `.paperclip.yaml` (only its
+/// `routines`) and Hermes' `skills/.bundled_manifest` (which skills Hermes seeded itself).
+pub const READ_DOTFILES: [&str; 2] = [".paperclip.yaml", ".bundled_manifest"];
+/// Repository archives (GitHub links) may hold this many entries; kwant still reads at most
+/// [`MAX_ZIP_ENTRIES`] files out of them.
+pub const MAX_REPO_ZIP_ENTRIES: usize = 5_000;
+
+/// How a zip is read: an upload, or a repository archive fetched from a GitHub link.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum ZipKind<'a> {
+ #[default]
+ Upload,
+ /// Up to [`MAX_REPO_ZIP_ENTRIES`] entries. codeload's top folder (`<repo>-<ref>/`) is stripped
+ /// first, so every rule below sees the path inside the repo (`.claude/agents/x.md`). Only files
+ /// a format can use are inflated (see [`wanted_in_repo`]), at most [`MAX_ZIP_ENTRIES`] of them;
+ /// nested archives are skipped, not refused, since they are never opened. With a `subpath`
+ /// (a `/tree/<ref>/<path>` or `/blob/<ref>/<path>` link), files outside it are listed by name
+ /// only: never inflated, never counted. Licence files at the top of the repo are the one
+ /// exception, so the import can still name the repo's licence.
+ Repo { subpath: Option<&'a str> },
+}
+
+/// The one top folder every entry of a repository archive sits in (`<repo>-<ref>`), if there is
+/// one. Read from the zip's directory alone; nothing is inflated.
+fn common_top<R: Read + std::io::Seek>(zip: &zip::ZipArchive<R>) -> Option<String> {
+ let mut top: Option<String> = None;
+ for name in zip.file_names() {
+ let path = safe_path(&name.ok()?)?;
+ let (first, _) = path.split_once('/')?;
+ match &top {
+ None if !first.is_empty() => top = Some(first.to_string()),
+ Some(t) if t == first => {}
+ _ => return None,
+ }
+ }
+ top
+}
+
+/// A path part (after the first) that starts with `.`: `skills/.system/…`, `skills/.hub/…`. The
+/// first may be hidden so a picked `.openclaw` or `.hermes` folder (or a repo's `.claude`) still
+/// reads. For repository archives this runs on the path without the top folder.
+fn in_hidden_folder(lower: &str) -> bool {
+ let parts: Vec<&str> = lower.split('/').collect();
+ parts.len() > 2 && parts[1..parts.len() - 1].iter().any(|p| p.starts_with('.'))
+}
+
+/// A licence file at any level: `LICENSE`, `LICENSE.md`, `LICENCE.txt`, `COPYING`, ….
+pub fn is_licence_file(lower_base: &str) -> bool {
+ let stem = lower_base.split('.').next().unwrap_or(lower_base);
+ matches!(stem, "license" | "licence" | "copying") && (lower_base == stem || lower_base.ends_with(".md") || lower_base.ends_with(".txt"))
+}
+
+/// Files of a repository archive that some import format reads. Everything else in a repo
+/// (code, docs, a skill's reference notes) is skipped without being inflated.
+pub fn wanted_in_repo(lower: &str) -> bool {
+ let base = lower.rsplit('/').next().unwrap_or(lower);
+ const NAMES: [&str; 14] = [
+ "skill.md", "agents.md", "agents.override.md", "soul.md", "identity.md", "user.md", "memory.md", "company.md",
+ "team.md", "task.md", "employee.json", "schedule.md", ".paperclip.yaml", ".bundled_manifest",
+ ];
+ if NAMES.contains(&base) || is_licence_file(base) {
+ return true;
+ }
+ let parent = lower.rsplit('/').nth(1).unwrap_or("");
+ // Claude Code agents (`agents/*.md`), Hermes memories, kwant bundles and other JSON exports
+ (parent == "agents" && base.ends_with(".md")) || (parent == "memories" && base.ends_with(".md")) || (base.ends_with(".json") && !lower.contains("node_modules/") && base != "package.json" && base != "package-lock.json" && base != "tsconfig.json")
+}
+
+/// Reads the bot-relevant files of an uploaded zip. See [`read_zip_as`].
pub fn read_zip(bytes: &[u8]) -> Result<Unzipped, ImportError> {
+ read_zip_as(bytes, ZipKind::Upload)
+}
+
+/// Reads the bot-relevant files of a zip. Rejects the whole zip for unsafe paths, nested
+/// archives (uploads), encryption, too many entries, or more than [`MAX_UNZIPPED_BYTES`] once
+/// inflated.
+pub fn read_zip_as(bytes: &[u8], kind: ZipKind<'_>) -> 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 (repo, sub) = match kind {
+ ZipKind::Upload => (false, None),
+ ZipKind::Repo { subpath } => (true, subpath.map(|p| p.trim_matches('/').to_lowercase()).filter(|p| !p.is_empty())),
+ };
+ let max_entries = if repo { MAX_REPO_ZIP_ENTRIES } else { MAX_ZIP_ENTRIES };
+ if zip.len() > max_entries {
+ return Err(if repo {
+ ImportError::TooLarge(format!("This repository has more than {max_entries} files."))
+ } else {
+ invalid(&format!("This zip has more than {max_entries} files."))
+ });
}
+ let top = if repo { common_top(&zip) } else { None };
let mut out = Unzipped::default();
let mut total: u64 = 0;
+ let mut read = 0usize;
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();
@@ -56,15 +143,43 @@ pub fn read_zip(bytes: &[u8]) -> Result<Unzipped, ImportError> {
if file.is_dir() {
continue;
}
+ let path = match &top {
+ Some(t) => path[t.len() + 1..].to_string(),
+ None => path,
+ };
let lower = path.to_lowercase();
+ let base = lower.rsplit('/').next().unwrap_or(&lower);
+ if let Some(sub) = &sub {
+ let inside = lower == *sub || lower.starts_with(&format!("{sub}/"));
+ let top_licence = !lower.contains('/') && is_licence_file(&lower);
+ if !inside && !top_licence {
+ out.skipped.push(path);
+ continue;
+ }
+ }
if ARCHIVE_EXTENSIONS.iter().any(|e| lower.ends_with(e)) {
+ if repo {
+ out.skipped.push(path);
+ continue;
+ }
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)) {
+ let readable = READ_EXTENSIONS.iter().any(|e| lower.ends_with(e)) || READ_DOTFILES.contains(&base) || is_licence_file(base);
+ let hidden = base.starts_with('.') && !READ_DOTFILES.contains(&base);
+ if hidden
+ || in_hidden_folder(&lower)
+ || lower.starts_with("__macosx/")
+ || CHAT_FILES.contains(&base)
+ || !readable
+ || (repo && !wanted_in_repo(&lower))
+ {
out.skipped.push(path);
continue;
}
+ read += 1;
+ if read > MAX_ZIP_ENTRIES {
+ return Err(ImportError::TooLarge(format!("This has more than {MAX_ZIP_ENTRIES} files kwant would read.")));
+ }
// The size header can lie, so count what actually comes out.
let mut buf = Vec::new();
(&mut file)
@@ -80,6 +195,7 @@ pub fn read_zip(bytes: &[u8]) -> Result<Unzipped, ImportError> {
}
out.entries.push(Entry { path, bytes: buf });
}
+ out.comment = std::str::from_utf8(zip.comment()).ok().map(|c| c.trim().to_string()).filter(|c| !c.is_empty());
Ok(out)
}
diff --git a/src/import/github.rs b/src/import/github.rs
new file mode 100644
index 00000000..d31d4d0d
--- /dev/null
+++ b/src/import/github.rs
@@ -0,0 +1,247 @@
+//! Import from a GitHub link (0.8.0 A3). Only `github.com` links are accepted, and the only host
+//! ever contacted is `codeload.github.com`: one `GET` of the repository zip, no redirects
+//! followed, no cookies, no token (public repositories only), at most 20 MB.
+
+use super::parsers::{self, RepoZip};
+use super::{Bundle, ImportError, MAX_ZIP_BYTES};
+use serde::Serialize;
+use std::time::Duration;
+
+pub const CODELOAD: &str = "https://codeload.github.com";
+pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
+pub const TOTAL_TIMEOUT: Duration = Duration::from_secs(60);
+const MAX_PART: usize = 100;
+
+/// A parsed `github.com` link.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct RepoLink {
+ pub owner: String,
+ pub repo: String,
+ /// `None`: the default branch (`HEAD`).
+ pub ref_: Option<String>,
+ /// A folder (`/tree/…`) or file (`/blob/…`) inside the repository.
+ pub path: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Licence {
+ pub spdx: Option<String>,
+ pub name: String,
+ pub file: String,
+}
+
+/// The `github` block of a preview.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct GithubInfo {
+ pub owner: String,
+ pub repo: String,
+ #[serde(rename = "ref")]
+ pub ref_: String,
+ pub path: Option<String>,
+ pub commit: Option<String>,
+ pub licence: Option<Licence>,
+}
+
+#[derive(Debug, PartialEq)]
+pub enum GithubError {
+ /// 422 `not_github`
+ NotGithub(String),
+ /// 422 `redirect`
+ Redirect,
+ /// 404 `not_found`
+ NotFound,
+ /// 502 `fetch_failed`
+ FetchFailed(String),
+ /// 413 / 415 / 422 from the zip reader
+ Import(ImportError),
+}
+
+fn not_github(msg: &str) -> GithubError {
+ GithubError::NotGithub(msg.into())
+}
+
+fn plain_part(p: &str) -> bool {
+ !p.is_empty() && p.len() <= MAX_PART && p != "." && p != ".." && p.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
+}
+
+/// Reads a link the person pasted. Refuses any host but `github.com` / `www.github.com`, any
+/// scheme but https, user info, a port, and shapes other than the repo, `/tree/` and `/blob/`.
+pub fn parse_link(raw: &str) -> Result<RepoLink, GithubError> {
+ let raw = raw.trim();
+ if raw.is_empty() || raw.len() > 2048 || raw.chars().any(|c| c.is_control() || c.is_whitespace()) {
+ return Err(not_github("Paste a link to a repository on github.com."));
+ }
+ // `url` would quietly resolve `..`, `.` and their encoded forms: refuse them as written
+ let lower = raw.to_lowercase();
+ if ["%2e", "%2f", "%5c", "\\"].iter().any(|m| lower.contains(m)) || raw.split(['/', '?', '#']).any(|s| s == ".." || s == ".") {
+ return Err(not_github("Use a link to a repository, a folder (…/tree/<branch>/…) or a file (…/blob/<branch>/…) on github.com."));
+ }
+ let with_scheme = if raw.contains("://") { raw.to_string() } else { format!("https://{raw}") };
+ let url = url::Url::parse(&with_scheme).map_err(|_| not_github("That isn't a link kwant can read."))?;
+ if url.scheme() != "https" {
+ return Err(not_github("Only https links to github.com are supported."));
+ }
+ if !url.username().is_empty() || url.password().is_some() || url.port().is_some() {
+ return Err(not_github("Links with a user name, password or port aren't supported."));
+ }
+ match url.host() {
+ Some(url::Host::Domain(h)) if h.eq_ignore_ascii_case("github.com") || h.eq_ignore_ascii_case("www.github.com") => {}
+ _ => return Err(not_github("Only links to github.com are supported.")),
+ }
+ let parts: Vec<&str> = url.path().trim_end_matches('/').split('/').skip(1).collect();
+ let bad_shape = || not_github("Use a link to a repository, a folder (…/tree/<branch>/…) or a file (…/blob/<branch>/…) on github.com.");
+ let (owner, repo, rest) = match parts.as_slice() {
+ [o, r, rest @ ..] => (*o, r.strip_suffix(".git").unwrap_or(r), rest),
+ _ => return Err(bad_shape()),
+ };
+ if !plain_part(owner) || !plain_part(repo) {
+ return Err(bad_shape());
+ }
+ let (ref_, path) = match rest {
+ [] => (None, None),
+ ["tree", r] => (Some(*r), None),
+ ["tree", r, p @ ..] | ["blob", r, p @ ..] if !p.is_empty() => {
+ // `url` already resolved `.` and `..`; refuse anything odd that is left
+ if p.iter().any(|s| s.is_empty() || *s == "." || *s == ".." || s.contains('%')) {
+ return Err(bad_shape());
+ }
+ (Some(*r), Some(p.join("/")))
+ }
+ _ => return Err(bad_shape()),
+ };
+ if let Some(r) = ref_ {
+ if !plain_part(r) {
+ return Err(not_github("Branch names with / or other special characters aren't supported yet."));
+ }
+ }
+ Ok(RepoLink { owner: owner.into(), repo: repo.into(), ref_: ref_.map(Into::into), path })
+}
+
+/// `https://codeload.github.com/<owner>/<repo>/zip/<ref>`; `base` is swapped only in tests.
+pub fn zip_url(base: &str, link: &RepoLink) -> String {
+ format!("{base}/{}/{}/zip/{}", link.owner, link.repo, link.ref_.as_deref().unwrap_or("HEAD"))
+}
+
+/// Fetches the zip at `url`: no redirects, 20 MB at most (refused up front when the length says
+/// so, counted while streaming otherwise).
+pub async fn fetch(url: &str) -> Result<Vec<u8>, GithubError> {
+ let client = reqwest::Client::builder()
+ .redirect(reqwest::redirect::Policy::none())
+ .connect_timeout(CONNECT_TIMEOUT)
+ .timeout(TOTAL_TIMEOUT)
+ .user_agent(concat!("kwant/", env!("CARGO_PKG_VERSION")))
+ .build()
+ .map_err(|_| GithubError::FetchFailed("kwant couldn't start the download.".into()))?;
+ let failed = |e: reqwest::Error| {
+ let why = if e.is_timeout() { "GitHub took too long to answer" } else { "kwant couldn't reach GitHub" };
+ GithubError::FetchFailed(format!("{why}. Try again in a moment."))
+ };
+ let mut resp = client.get(url).send().await.map_err(failed)?;
+ let status = resp.status();
+ if status.is_redirection() {
+ return Err(GithubError::Redirect);
+ }
+ if status == reqwest::StatusCode::NOT_FOUND {
+ return Err(GithubError::NotFound);
+ }
+ if !status.is_success() {
+ return Err(GithubError::FetchFailed(format!("GitHub answered {}. Try again in a moment.", status.as_u16())));
+ }
+ let too_large = || GithubError::Import(ImportError::TooLarge("This repository is larger than 20 MB, so kwant can't fetch it. Download the folder you want, zip it and import the zip instead.".into()));
+ if resp.content_length().is_some_and(|n| n > MAX_ZIP_BYTES as u64) {
+ return Err(too_large());
+ }
+ let mut body = Vec::new();
+ while let Some(chunk) = resp.chunk().await.map_err(failed)? {
+ if body.len() + chunk.len() > MAX_ZIP_BYTES {
+ return Err(too_large());
+ }
+ body.extend_from_slice(&chunk);
+ }
+ Ok(body)
+}
+
+/// A best guess at the SPDX id of a licence text.
+pub fn guess_spdx(text: &str) -> Option<(&'static str, &'static str)> {
+ let t: String = text.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase();
+ let has = |s: &str| t.contains(s);
+ Some(if has("gnu affero general public license") {
+ ("AGPL-3.0", "GNU Affero General Public License v3.0")
+ } else if has("gnu lesser general public license") {
+ ("LGPL-3.0", "GNU Lesser General Public License v3.0")
+ } else if has("gnu general public license") && has("version 3") {
+ ("GPL-3.0", "GNU General Public License v3.0")
+ } else if has("gnu general public license") && has("version 2") {
+ ("GPL-2.0", "GNU General Public License v2.0")
+ } else if has("mozilla public license") && has("2.0") {
+ ("MPL-2.0", "Mozilla Public License 2.0")
+ } else if has("apache license") && has("version 2.0") {
+ ("Apache-2.0", "Apache License 2.0")
+ } else if has("this is free and unencumbered software released into the public domain") {
+ ("Unlicense", "The Unlicense")
+ } else if has("cc0 1.0 universal") {
+ ("CC0-1.0", "Creative Commons Zero v1.0 Universal")
+ } else if has("attribution-sharealike 4.0") {
+ ("CC-BY-SA-4.0", "Creative Commons Attribution Share Alike 4.0")
+ } else if has("attribution 4.0 international") {
+ ("CC-BY-4.0", "Creative Commons Attribution 4.0")
+ } else if has("permission is hereby granted, free of charge") {
+ ("MIT", "MIT License")
+ } else if has("permission to use, copy, modify, and/or distribute this software for any purpose with or without fee") {
+ ("ISC", "ISC License")
+ } else if has("redistribution and use in source and binary forms") {
+ if has("neither the name") || has("may be used to endorse or promote") {
+ ("BSD-3-Clause", "BSD 3-Clause License")
+ } else {
+ ("BSD-2-Clause", "BSD 2-Clause License")
+ }
+ } else {
+ return None;
+ })
+}
+
+pub fn licence_of(found: Option<(String, String)>) -> Option<Licence> {
+ let (file, text) = found?;
+ Some(match guess_spdx(&text) {
+ Some((spdx, name)) => Licence { spdx: Some(spdx.into()), name: name.into(), file },
+ None => Licence { spdx: None, name: "Unknown licence".into(), file },
+ })
+}
+
+pub const NO_LICENCE: &str = "This repository has no licence file, so you may not have the right to reuse it.";
+
+/// Reads the fetched zip into a bundle and the `github` block.
+pub fn read(link: &RepoLink, zip: &[u8]) -> Result<(Bundle, GithubInfo), GithubError> {
+ if !zip.starts_with(b"PK") {
+ return Err(GithubError::Import(ImportError::Invalid("GitHub didn't send a zip.".into())));
+ }
+ let (mut bundle, RepoZip { commit, licence }) = parsers::parse_repo_zip(zip, link.path.as_deref()).map_err(GithubError::Import)?;
+ let licence = licence_of(licence);
+ let shown = format!("github.com/{}/{}", link.owner, link.repo);
+ bundle.source.label = Some(match &link.path {
+ Some(p) => format!("{shown}/{p}"),
+ None => shown.clone(),
+ });
+ let which = licence.as_ref().map_or("no licence file".to_string(), |l| l.spdx.clone().unwrap_or_else(|| l.name.clone()));
+ bundle.omitted.push(format!("From {shown} ({which})"));
+ let commit = commit.map(|c| c.trim().to_string()).filter(|c| c.len() == 40 && c.chars().all(|ch| ch.is_ascii_hexdigit()));
+ let info = GithubInfo {
+ owner: link.owner.clone(),
+ repo: link.repo.clone(),
+ ref_: link.ref_.clone().unwrap_or_else(|| "HEAD".into()),
+ path: link.path.clone(),
+ commit,
+ licence,
+ };
+ Ok((bundle, info))
+}
+
+/// Fetches and reads `raw` (a pasted link) from `base` (codeload outside tests).
+pub async fn preview(base: &str, raw: &str) -> Result<(Bundle, GithubInfo), GithubError> {
+ let link = parse_link(raw)?;
+ let zip = fetch(&zip_url(base, &link)).await?;
+ read(&link, &zip)
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/src/import/github/tests.rs b/src/import/github/tests.rs
new file mode 100644
index 00000000..636b4656
--- /dev/null
+++ b/src/import/github/tests.rs
@@ -0,0 +1,279 @@
+use super::*;
+use std::io::Write as _;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+fn link(owner: &str, repo: &str, r: Option<&str>, path: Option<&str>) -> RepoLink {
+ RepoLink { owner: owner.into(), repo: repo.into(), ref_: r.map(Into::into), path: path.map(Into::into) }
+}
+
+#[test]
+fn accepted_link_shapes() {
+ let cases = [
+ ("https://github.com/coreyhaines31/marketingskills", link("coreyhaines31", "marketingskills", None, None)),
+ ("github.com/o/r", link("o", "r", None, None)),
+ ("www.github.com/o/r.git/", link("o", "r", None, None)),
+ ("https://GitHub.com/o/r/tree/v1.2", link("o", "r", Some("v1.2"), None)),
+ ("https://github.com/o/r/tree/main/skills/seo", link("o", "r", Some("main"), Some("skills/seo"))),
+ ("https://github.com/o/r/blob/main/skills/seo/SKILL.md", link("o", "r", Some("main"), Some("skills/seo/SKILL.md"))),
+ ("https://github.com/o/r/blob/main/AGENTS.md?plain=1#L3", link("o", "r", Some("main"), Some("AGENTS.md"))),
+ ];
+ for (raw, want) in cases {
+ assert_eq!(parse_link(raw), Ok(want), "{raw}");
+ }
+ assert_eq!(zip_url(CODELOAD, &link("o", "r", None, None)), "https://codeload.github.com/o/r/zip/HEAD");
+ assert_eq!(zip_url(CODELOAD, &link("o", "r", Some("v2"), Some("x"))), "https://codeload.github.com/o/r/zip/v2");
+}
+
+#[test]
+fn other_hosts_and_shapes_are_refused() {
+ for raw in [
+ "https://gitlab.com/o/r",
+ "https://github.com.evil.example/o/r",
+ "https://evil.example/github.com/o/r",
+ "https://raw.githubusercontent.com/o/r/main/SKILL.md",
+ "https://codeload.github.com/o/r/zip/HEAD",
+ "https://api.github.com/repos/o/r",
+ "https://gist.github.com/o/abc",
+ "http://github.com/o/r",
+ "ftp://github.com/o/r",
+ "file:///etc/passwd",
+ "https://user:[email protected]/o/r",
+ "https://[email protected]/o/r",
+ "https://github.com:8443/o/r",
+ "https://github.com./o/r",
+ "https://127.0.0.1/o/r",
+ "https://github.com/o",
+ "https://github.com/o/r/issues/1",
+ "https://github.com/o/r/tree/feature/x%2F..%2F..",
+ "https://github.com/o/r/tree/main/a/%2e%2e/b",
+ "https://github.com/o/r/blob/main",
+ "https://github.com/o/r/archive/refs/heads/main.zip",
+ "https://github.com/o%2Fx/r",
+ "https://github.com/../r",
+ "https://github.com/o/r/tree/main/./x",
+ "https://github.com/o/r/tree/main/a\\..\\b",
+ "",
+ "github.com/o/r with space",
+ ] {
+ assert!(matches!(parse_link(raw), Err(GithubError::NotGithub(_))), "{raw} was accepted: {:?}", parse_link(raw));
+ }
+}
+
+#[test]
+fn licence_guesses() {
+ let mit = "MIT License\n\nCopyright (c) 2025\n\nPermission is hereby granted, free of charge, to any person obtaining a copy";
+ assert_eq!(guess_spdx(mit), Some(("MIT", "MIT License")));
+ assert_eq!(guess_spdx("Apache License\n Version 2.0, January 2004"), Some(("Apache-2.0", "Apache License 2.0")));
+ assert_eq!(guess_spdx("GNU AFFERO GENERAL PUBLIC LICENSE Version 3"), Some(("AGPL-3.0", "GNU Affero General Public License v3.0")));
+ assert_eq!(guess_spdx("GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007").map(|g| g.0), Some("GPL-3.0"));
+ assert_eq!(guess_spdx("Redistribution and use in source and binary forms ... Neither the name of").map(|g| g.0), Some("BSD-3-Clause"));
+ assert_eq!(guess_spdx("All rights reserved. Do not copy."), None);
+ assert_eq!(licence_of(Some(("COPYING".into(), "whatever".into()))), Some(Licence { spdx: None, name: "Unknown licence".into(), file: "COPYING".into() }));
+ assert_eq!(licence_of(None), None);
+}
+
+const SHA: &str = "2cdd34e1f0d7bfa5b9dfadecf3d72b525fbb1577";
+
+fn repo_zip(files: &[(&str, &str)]) -> Vec<u8> {
+ repo_zip_in("skills-main", files)
+}
+
+/// A codeload-shaped zip: every file under `<top>/`.
+fn repo_zip_in(top: &str, files: &[(&str, &str)]) -> Vec<u8> {
+ let mut out = std::io::Cursor::new(Vec::new());
+ {
+ let mut z = zip::ZipWriter::new(&mut out);
+ let opts = zip::write::SimpleFileOptions::default();
+ z.add_directory(format!("{top}/"), opts).unwrap();
+ for (name, text) in files {
+ z.start_file(format!("{top}/{name}"), opts).unwrap();
+ z.write_all(text.as_bytes()).unwrap();
+ }
+ z.set_comment(SHA.to_string()).unwrap();
+ z.finish().unwrap();
+ }
+ out.into_inner()
+}
+
+fn skill(name: &str) -> String {
+ format!("---\nname: {name}\ndescription: Does {name}.\n---\n\nSteps.\n")
+}
+
+#[test]
+fn reads_a_repo_with_licence_commit_and_path() {
+ let zip = repo_zip(&[
+ ("LICENSE", "Permission is hereby granted, free of charge, to any person"),
+ ("README.md", "# Skills"),
+ ("seo/SKILL.md", &skill("seo")),
+ ("copy/SKILL.md", &skill("copy")),
+ ("src/main.rs", "fn main() {}"),
+ ]);
+ let (b, info) = read(&link("o", "skills", None, None), &zip).unwrap();
+ assert_eq!(b.skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["seo", "copy"]);
+ assert_eq!(b.source.label.as_deref(), Some("github.com/o/skills"));
+ assert!(b.omitted.contains(&"From github.com/o/skills (MIT)".to_string()), "{:?}", b.omitted);
+ assert_eq!(info.commit.as_deref(), Some(SHA));
+ assert_eq!(info.ref_, "HEAD");
+ assert_eq!(info.licence, Some(Licence { spdx: Some("MIT".into()), name: "MIT License".into(), file: "LICENSE".into() }));
+ let json = serde_json::to_value(&info).unwrap();
+ assert_eq!(json["ref"], "HEAD");
+
+ let (b, info) = read(&link("o", "skills", Some("main"), Some("seo")), &zip).unwrap();
+ assert_eq!(b.skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["seo"]);
+ assert_eq!(b.source.label.as_deref(), Some("github.com/o/skills/seo"));
+ assert_eq!(info.path.as_deref(), Some("seo"));
+
+ let (b, _) = read(&link("o", "skills", Some("main"), Some("copy/SKILL.md")), &zip).unwrap();
+ assert_eq!(b.skills.len(), 1);
+
+ assert!(matches!(read(&link("o", "skills", None, Some("nope")), &zip), Err(GithubError::Import(ImportError::Unsupported(_)))));
+}
+
+/// Review #455 item 1: a `/tree/<ref>/<path>` link reads only `<path>`. 501 `.json` files outside
+/// it (over the 500 readable-file cap) are listed by name, never inflated or counted.
+#[test]
+fn a_subpath_link_counts_only_files_inside_it() {
+ let outside: Vec<(String, String)> = (0..501).map(|i| (format!("i18n/{i:03}.json"), "{\"hello\": \"hi\"}".to_string())).collect();
+ let mut files: Vec<(&str, &str)> = outside.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect();
+ let seo = skill("seo");
+ files.push(("skills/seo/SKILL.md", &seo));
+ files.push(("LICENSE", "Permission is hereby granted, free of charge, to any person"));
+ let zip = repo_zip_in("r-main", &files);
+
+ let (b, info) = read(&link("o", "r", Some("main"), Some("skills")), &zip).unwrap();
+ assert_eq!(b.skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["seo"]);
+ assert_eq!(info.licence.and_then(|l| l.spdx).as_deref(), Some("MIT"), "the repo's top licence is still read");
+
+ // At the reader: only the folder (and the top licence) is inflated; the rest is named only.
+ let un = crate::import::archive::read_zip_as(&zip, crate::import::archive::ZipKind::Repo { subpath: Some("skills") }).unwrap();
+ assert_eq!(un.entries.iter().map(|e| e.path.as_str()).collect::<Vec<_>>(), ["skills/seo/SKILL.md", "LICENSE"]);
+ assert_eq!(un.skipped.iter().filter(|p| p.starts_with("i18n/")).count(), 501);
+
+ // The whole repo has 501 readable .json files: over the cap.
+ assert!(matches!(read(&link("o", "r", Some("main"), None), &zip), Err(GithubError::Import(ImportError::TooLarge(_)))));
+}
+
+/// Review #455 item 2: the hidden-folder rule runs after `<repo>-<ref>/` is stripped, as for an
+/// upload, so a repo's `.claude/agents` and `.claude/skills` are read; `skills/.system` stays skipped.
+#[test]
+fn a_repos_claude_folder_is_read_and_hidden_subfolders_are_not() {
+ let zip = repo_zip_in(
+ "r-main",
+ &[
+ (".claude/agents/a.md", "---\nname: reviewer\ndescription: Reviews code.\n---\n\nReview the diff.\n"),
+ (".claude/skills/s/SKILL.md", &skill("s")),
+ ("skills/.system/x/SKILL.md", &skill("x")),
+ ],
+ );
+ let un = crate::import::archive::read_zip_as(&zip, crate::import::archive::ZipKind::Repo { subpath: None }).unwrap();
+ assert_eq!(un.entries.iter().map(|e| e.path.as_str()).collect::<Vec<_>>(), [".claude/agents/a.md", ".claude/skills/s/SKILL.md"]);
+ assert!(un.skipped.contains(&"skills/.system/x/SKILL.md".to_string()), "{:?}", un.skipped);
+
+ // One bot and one skill; as for an upload, a skill next to a single agent is that agent's.
+ let (b, _) = read(&link("o", "r", Some("main"), None), &zip).unwrap();
+ assert_eq!(b.bots.iter().map(|x| x.name.as_str()).collect::<Vec<_>>(), ["reviewer"]);
+ assert_eq!(b.bots[0].skills.iter().map(|x| x.name.as_str()).collect::<Vec<_>>(), ["s"]);
+ assert!(b.skills.is_empty(), "{:?}", b.skills);
+}
+
+/// Review #455 item 2: a link straight to `/tree/main/.claude/agents` previews the bot.
+#[tokio::test]
+async fn a_link_to_a_repos_claude_agents_folder_previews_the_bot() {
+ let zip = repo_zip_in(
+ "r-main",
+ &[
+ (".claude/agents/a.md", "---\nname: reviewer\ndescription: Reviews code.\n---\n\nReview the diff.\n"),
+ (".claude/skills/s/SKILL.md", &skill("s")),
+ ],
+ );
+ let (base, seen) = mock(http("200 OK", &format!("Content-Length: {}\r\n", zip.len()), &zip)).await;
+ let (b, info) = preview(&base, "https://github.com/o/r/tree/main/.claude/agents").await.unwrap();
+ assert_eq!(b.bots.iter().map(|x| x.name.as_str()).collect::<Vec<_>>(), ["reviewer"]);
+ assert!(b.skills.is_empty(), "{:?}", b.skills);
+ assert_eq!(info.path.as_deref(), Some(".claude/agents"));
+ assert_eq!(seen.lock().unwrap().as_slice(), ["GET /o/r/zip/main HTTP/1.1"]);
+}
+
+#[test]
+fn no_licence_is_named_and_not_a_zip_is_invalid() {
+ let zip = repo_zip(&[("seo/SKILL.md", &skill("seo"))]);
+ let (b, info) = read(&link("o", "r", None, None), &zip).unwrap();
+ assert_eq!(info.licence, None);
+ assert!(b.omitted.contains(&"From github.com/o/r (no licence file)".to_string()));
+ assert!(matches!(read(&link("o", "r", None, None), b"<html>rate limited</html>"), Err(GithubError::Import(ImportError::Invalid(_)))));
+}
+
+/// Serves one canned HTTP response per connection on 127.0.0.1 and records the request lines.
+async fn mock(response: Vec<u8>) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
+ let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let seen2 = seen.clone();
+ tokio::spawn(async move {
+ while let Ok((mut sock, _)) = listener.accept().await {
+ let mut buf = vec![0u8; 8192];
+ let n = sock.read(&mut buf).await.unwrap_or(0);
+ let head = String::from_utf8_lossy(&buf[..n]).lines().next().unwrap_or_default().to_string();
+ seen2.lock().unwrap().push(head);
+ let _ = sock.write_all(&response).await;
+ let _ = sock.shutdown().await;
+ }
+ });
+ (base, seen)
+}
+
+fn http(status: &str, headers: &str, body: &[u8]) -> Vec<u8> {
+ let mut r = format!("HTTP/1.1 {status}\r\n{headers}Connection: close\r\n\r\n").into_bytes();
+ r.extend_from_slice(body);
+ r
+}
+
+#[tokio::test]
+async fn fetches_the_zip() {
+ let zip = repo_zip(&[("LICENSE", "Apache License Version 2.0"), ("seo/SKILL.md", &skill("seo"))]);
+ let (base, seen) = mock(http("200 OK", &format!("Content-Type: application/zip\r\nContent-Length: {}\r\n", zip.len()), &zip)).await;
+ let (b, info) = preview(&base, "https://github.com/o/skills/tree/main").await.unwrap();
+ assert_eq!(b.skills.len(), 1);
+ assert_eq!(info.licence.and_then(|l| l.spdx).as_deref(), Some("Apache-2.0"));
+ assert_eq!(seen.lock().unwrap().as_slice(), ["GET /o/skills/zip/main HTTP/1.1"]);
+}
+
+#[tokio::test]
+async fn redirects_are_refused_not_followed() {
+ let (target, target_seen) = mock(http("200 OK", "Content-Length: 2\r\n", b"PK")).await;
+ let (base, seen) = mock(http("302 Found", &format!("Location: {target}/elsewhere\r\nContent-Length: 0\r\n"), b"")).await;
+ assert_eq!(preview(&base, "github.com/o/r").await.unwrap_err(), GithubError::Redirect);
+ assert_eq!(seen.lock().unwrap().len(), 1);
+ assert!(target_seen.lock().unwrap().is_empty(), "the redirect was followed");
+}
+
+#[tokio::test]
+async fn oversize_zips_are_refused() {
+ // Refused from the length alone, before the body
+ // Review #455 item 3: no advice to link a folder (codeload always sends the whole repo).
+ const TOO_LARGE: &str = "This repository is larger than 20 MB, so kwant can't fetch it. Download the folder you want, zip it and import the zip instead.";
+ let (base, _) = mock(http("200 OK", &format!("Content-Length: {}\r\n", MAX_ZIP_BYTES + 1), b"PK")).await;
+ assert_eq!(preview(&base, "github.com/o/r/tree/main/skills").await.unwrap_err(), GithubError::Import(ImportError::TooLarge(TOO_LARGE.into())));
+ // No length: counted while streaming
+ let big = vec![b'x'; MAX_ZIP_BYTES + 1024];
+ let (base, _) = mock(http("200 OK", "", &big)).await;
+ assert_eq!(preview(&base, "github.com/o/r").await.unwrap_err(), GithubError::Import(ImportError::TooLarge(TOO_LARGE.into())));
+}
+
+#[tokio::test]
+async fn statuses_map_to_errors() {
+ let (base, _) = mock(http("404 Not Found", "Content-Length: 0\r\n", b"")).await;
+ assert_eq!(preview(&base, "github.com/o/private").await.unwrap_err(), GithubError::NotFound);
+ let (base, _) = mock(http("429 Too Many Requests", "Content-Length: 0\r\n", b"")).await;
+ assert!(matches!(preview(&base, "github.com/o/r").await, Err(GithubError::FetchFailed(_))));
+ // Nothing listening
+ let closed = {
+ let l = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
+ format!("http://{}", l.local_addr().unwrap())
+ };
+ assert!(matches!(preview(&closed, "github.com/o/r").await, Err(GithubError::FetchFailed(_))));
+ // A link to another host never reaches the network
+ let (base, seen) = mock(http("200 OK", "Content-Length: 0\r\n", b"")).await;
+ assert!(matches!(preview(&base, "https://gitlab.com/o/r").await, Err(GithubError::NotGithub(_))));
+ assert!(seen.lock().unwrap().is_empty());
+}
diff --git a/src/import/local.rs b/src/import/local.rs
new file mode 100644
index 00000000..27f9e8d0
--- /dev/null
+++ b/src/import/local.rs
@@ -0,0 +1,366 @@
+//! "Found on this computer" (0.8.0 A2): bots and skills other agent apps keep in the person's
+//! home folder: `~/.openclaw`, `~/.hermes`, `~/.claude/agents`, `~/.claude/skills` and `~/.codex`
+//! (or `CODEX_HOME`).
+//!
+//! [`scan`] only lists folders (names, kinds and sizes from `lstat`); the one file it reads is
+//! Hermes' `skills/.bundled_manifest`, a list of skill names, so skills Hermes installed itself
+//! aren't counted. [`read`] opens only the files each format uses, every one from the source
+//! folder's own descriptor with `O_NOFOLLOW` on each step ([`crate::sandbox::safe_fs::Dir`]): a
+//! symlink anywhere is skipped and named, never followed. Key stores (`.env`, `auth.json`,
+//! `openclaw.json`, `credentials/`, `config.toml`, `state.db`, sessions) are never opened.
+
+use super::archive::{Entry, Unzipped};
+use super::parsers::{self, formats};
+use super::{Bundle, ImportError, BUNDLE_FORMAT, MAX_FILE_BYTES, MAX_UNZIPPED_BYTES, MAX_ZIP_ENTRIES};
+use crate::sandbox::safe_fs::{self, Dir, Kind};
+use serde::Serialize;
+use std::collections::BTreeSet;
+use std::path::{Path, PathBuf};
+
+/// Folders deeper than this below a source aren't looked at.
+pub const MAX_DEPTH: usize = 6;
+/// At most this many names per source in the list.
+pub const MAX_NAMES: usize = 50;
+/// At most this many sources ticked at once.
+pub const MAX_PICKED: usize = 10;
+
+pub const CLAUDE_AGENTS: &str = "claude-code";
+pub const CLAUDE_SKILLS: &str = "skill";
+
+/// One source found on this computer, as the list shows it.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Found {
+ pub id: String,
+ pub kind: String,
+ pub label: String,
+ /// Shown with `~` for the home folder.
+ pub path: String,
+ pub bots: usize,
+ pub skills: usize,
+ /// Memory files (MEMORY.md, USER.md), not entries: entries would need reading.
+ pub memories: usize,
+ pub names: Vec<String>,
+ pub too_large: bool,
+}
+
+/// What the files of a source are for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Use {
+ /// Opened and read on import.
+ Read,
+ /// Only its name counts (a daily log, a first-run script): never opened.
+ Seen,
+}
+
+/// A source and where it lives.
+struct Located {
+ found: Found,
+ /// The source folder, opened without following a symlink on the way.
+ dir: Dir,
+ /// Allowlisted files below it: relative path, use, size at listing time.
+ files: Vec<(String, Use, u64)>,
+ /// Files that are symlinks where a file kwant reads would be.
+ links: Vec<String>,
+}
+
+fn shown(home: &Path, path: &Path) -> String {
+ match path.strip_prefix(home) {
+ Ok(rel) => Path::new("~").join(rel).display().to_string(),
+ Err(_) => path.display().to_string(),
+ }
+}
+
+/// Whether `rel` (lower case, `/`-separated, no leading slash) is a file `kind` uses.
+fn wanted(kind: &str, rel: &str) -> Option<Use> {
+ let parts: Vec<&str> = rel.split('/').collect();
+ let base = *parts.last()?;
+ match (kind, parts.as_slice()) {
+ (formats::OPENCLAW, [_]) => match base {
+ "soul.md" | "agents.md" | "identity.md" | "user.md" | "memory.md" => Some(Use::Read),
+ "boot.md" | "bootstrap.md" => Some(Use::Seen),
+ _ => None,
+ },
+ (formats::OPENCLAW, ["memory", f]) if f.ends_with(".md") => Some(Use::Seen),
+ (formats::OPENCLAW | formats::CODEX, ["skills", _, "skill.md"]) => Some(Use::Read),
+ (formats::HERMES, ["soul.md"] | ["memories", "memory.md" | "user.md"] | ["skills", ".bundled_manifest"]) => Some(Use::Read),
+ (formats::HERMES, ["skills", .., "skill.md"]) if parts.len() >= 3 => Some(Use::Read),
+ (formats::CODEX, ["agents.md" | "agents.override.md"]) => Some(Use::Read),
+ (CLAUDE_AGENTS, [.., f]) if parts.len() <= 2 && f.ends_with(".md") => Some(Use::Read),
+ (CLAUDE_SKILLS, [_, "skill.md"]) => Some(Use::Read),
+ _ => None,
+ }
+}
+
+/// Whether to look inside the folder `rel` of a `kind` source.
+fn descend(kind: &str, rel: &str) -> bool {
+ let parts: Vec<&str> = rel.split('/').collect();
+ if parts.iter().any(|p| p.starts_with('.')) {
+ return false;
+ }
+ match kind {
+ formats::OPENCLAW => matches!(parts.as_slice(), ["skills"] | ["skills", _] | ["memory"]),
+ formats::CODEX => matches!(parts.as_slice(), ["skills"] | ["skills", _]),
+ // Profiles are sources of their own.
+ formats::HERMES => matches!(parts.first(), Some(&"memories") | Some(&"skills")),
+ CLAUDE_AGENTS => parts.len() == 1,
+ CLAUDE_SKILLS => parts.len() == 1,
+ _ => false,
+ }
+}
+
+/// Lists the files a `kind` source uses: names and sizes only.
+fn walk(dir: &Dir, kind: &str, prefix: &str, depth: usize, files: &mut Vec<(String, Use, u64)>, links: &mut Vec<String>) {
+ let Ok(mut entries) = dir.list() else { return };
+ entries.sort_by(|a, b| a.name.cmp(&b.name));
+ for e in entries {
+ let Some(name) = e.name.to_str() else { continue };
+ let rel = if prefix.is_empty() { name.to_string() } else { format!("{prefix}/{name}") };
+ let lower = rel.to_lowercase();
+ match e.kind {
+ Kind::File => {
+ if let Some(u) = wanted(kind, &lower) {
+ files.push((rel, u, e.len));
+ }
+ }
+ Kind::Dir if depth < MAX_DEPTH && descend(kind, &lower) => {
+ if let Ok(sub) = dir.open_dir(Path::new(name)) {
+ walk(&sub, kind, &rel, depth + 1, files, links);
+ }
+ }
+ Kind::Symlink if wanted(kind, &lower).is_some() || descend(kind, &lower) => links.push(rel),
+ _ => {}
+ }
+ }
+}
+
+fn skill_folder(rel: &str) -> Option<String> {
+ let (dir, base) = rel.rsplit_once('/')?;
+ base.eq_ignore_ascii_case("skill.md").then(|| dir.rsplit('/').next().unwrap_or(dir).to_string())
+}
+
+/// Skill names Hermes seeded itself (`skills/.bundled_manifest`), read from the source's handle.
+fn hermes_bundled(dir: &Dir, files: &[(String, Use, u64)]) -> BTreeSet<String> {
+ let Some((rel, _, _)) = files.iter().find(|(r, _, _)| r.eq_ignore_ascii_case("skills/.bundled_manifest")) else { return BTreeSet::new() };
+ let Ok(text) = dir.open_file(Path::new(rel)).and_then(|f| safe_fs::read_capped(f, 256 * 1024)) else { return BTreeSet::new() };
+ String::from_utf8_lossy(&text).lines().filter_map(|l| l.split(':').next()).map(|n| n.trim().to_lowercase()).filter(|n| !n.is_empty()).collect()
+}
+
+fn locate(dir: Dir, id: String, kind: &str, label: String, path: String) -> Option<Located> {
+ let (mut files, mut links) = (Vec::new(), Vec::new());
+ walk(&dir, kind, "", 0, &mut files, &mut links);
+ let bundled = if kind == formats::HERMES { hermes_bundled(&dir, &files) } else { BTreeSet::new() };
+ let mut names = BTreeSet::new();
+ let mut skills = 0;
+ let mut bots = 0;
+ let mut memories = 0;
+ for (rel, u, _) in &files {
+ if *u != Use::Read {
+ continue;
+ }
+ let lower = rel.to_lowercase();
+ if let Some(folder) = skill_folder(rel) {
+ if kind == formats::HERMES && bundled.contains(&folder.to_lowercase()) {
+ continue;
+ }
+ skills += 1;
+ names.insert(folder);
+ } else if kind == CLAUDE_AGENTS {
+ bots += 1;
+ names.insert(rel.rsplit('/').next().unwrap_or(rel).trim_end_matches(".md").to_string());
+ } else if matches!(lower.as_str(), "memory.md" | "user.md" | "memories/memory.md" | "memories/user.md") {
+ memories += 1;
+ }
+ }
+ let read: Vec<&(String, Use, u64)> = files.iter().filter(|(r, u, _)| *u == Use::Read && !r.ends_with(".bundled_manifest")).collect();
+ let has_bot_file = read.iter().any(|(r, _, _)| skill_folder(r).is_none());
+ if matches!(kind, formats::OPENCLAW | formats::HERMES | formats::CODEX) && has_bot_file {
+ bots = 1;
+ }
+ if bots == 0 && skills == 0 {
+ return None;
+ }
+ let total: u64 = read.iter().map(|(_, _, n)| n).sum();
+ let found = Found {
+ id,
+ kind: kind.to_string(),
+ label,
+ path,
+ bots,
+ skills,
+ memories,
+ names: names.into_iter().take(MAX_NAMES).collect(),
+ too_large: read.len() > MAX_ZIP_ENTRIES || total > MAX_UNZIPPED_BYTES,
+ };
+ Some(Located { found, dir, files, links })
+}
+
+/// A name that is safe in an id: letters, digits, `-`, `_` and `.`, at most 64.
+fn plain_name(n: &str) -> bool {
+ !n.is_empty() && n.len() <= 64 && n.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
+}
+
+/// Subfolders of `dir` (real folders only) whose names start with `prefix`, with the rest of the name.
+fn subdirs<'a>(dir: &'a Dir, prefix: &'a str) -> impl Iterator<Item = (String, String)> + 'a {
+ let mut list = dir.list().unwrap_or_default();
+ list.sort_by(|a, b| a.name.cmp(&b.name));
+ list.into_iter().filter(|e| e.kind == Kind::Dir).filter_map(move |e| {
+ let name = e.name.to_str()?.to_string();
+ let rest = name.strip_prefix(prefix)?.to_string();
+ Some((name, rest))
+ })
+}
+
+fn find_all(home: &Path, codex_home: Option<&Path>) -> Vec<Located> {
+ let Ok(home_dir) = Dir::open(home) else { return Vec::new() };
+ let mut out = Vec::new();
+ let mut add = |dir: std::io::Result<Dir>, id: String, kind: &str, label: String, path: PathBuf| {
+ if let Ok(d) = dir {
+ if let Some(l) = locate(d, id, kind, label, shown(home, &path)) {
+ out.push(l);
+ }
+ }
+ };
+ // OpenClaw: ~/.openclaw/workspace, extra agents in workspace-<agentId>, profiles in ~/.openclaw-<profile>
+ if let Ok(oc) = home_dir.open_dir(Path::new(".openclaw")) {
+ add(oc.open_dir(Path::new("workspace")), "openclaw".into(), formats::OPENCLAW, "OpenClaw".into(), home.join(".openclaw/workspace"));
+ for (name, agent) in subdirs(&oc, "workspace-").collect::<Vec<_>>() {
+ if plain_name(&agent) {
+ let label = format!("OpenClaw ({agent})");
+ add(oc.open_dir(Path::new(&name)), format!("openclaw:{agent}"), formats::OPENCLAW, label, home.join(".openclaw").join(&name));
+ }
+ }
+ }
+ for (name, profile) in subdirs(&home_dir, ".openclaw-").collect::<Vec<_>>() {
+ if plain_name(&profile) {
+ let dir = home_dir.open_dir(&Path::new(&name).join("workspace"));
+ add(dir, format!("openclaw-{profile}"), formats::OPENCLAW, format!("OpenClaw ({profile} profile)"), home.join(&name).join("workspace"));
+ }
+ }
+ // Hermes: ~/.hermes and ~/.hermes/profiles/<name>
+ if let Ok(hm) = home_dir.open_dir(Path::new(".hermes")) {
+ let profiles = hm.open_dir(Path::new("profiles")).ok();
+ add(Ok(hm), "hermes".into(), formats::HERMES, "Hermes Agent".into(), home.join(".hermes"));
+ if let Some(p) = profiles {
+ for (name, _) in subdirs(&p, "").collect::<Vec<_>>() {
+ if plain_name(&name) {
+ let label = format!("Hermes Agent ({name} profile)");
+ add(p.open_dir(Path::new(&name)), format!("hermes:{name}"), formats::HERMES, label, home.join(".hermes/profiles").join(&name));
+ }
+ }
+ }
+ }
+ add(home_dir.open_dir(Path::new(".claude/agents")), "claude-agents".into(), CLAUDE_AGENTS, "Claude Code agents".into(), home.join(".claude/agents"));
+ add(home_dir.open_dir(Path::new(".claude/skills")), "claude-skills".into(), CLAUDE_SKILLS, "Claude Code skills".into(), home.join(".claude/skills"));
+ // Codex: CODEX_HOME when set (refused when any part of it is a symlink the person doesn't own as root), else ~/.codex
+ match codex_home.filter(|p| p.is_absolute()) {
+ Some(p) => add(Dir::open_strict(p), "codex".into(), formats::CODEX, "Codex".into(), p.to_path_buf()),
+ None => add(home_dir.open_dir(Path::new(".codex")), "codex".into(), formats::CODEX, "Codex".into(), home.join(".codex")),
+ }
+ out
+}
+
+/// What other agent apps keep in `home`. Lists folders only (see the module notes).
+pub fn scan(home: &Path, codex_home: Option<&Path>) -> Vec<Found> {
+ find_all(home, codex_home).into_iter().map(|l| l.found).collect()
+}
+
+/// The person's home folder and `CODEX_HOME`, as the app sees them.
+pub fn home() -> Option<(PathBuf, Option<PathBuf>)> {
+ let home = dirs::home_dir()?;
+ let codex = std::env::var_os("CODEX_HOME").map(PathBuf::from).filter(|p| !p.as_os_str().is_empty());
+ Some((home, codex))
+}
+
+#[derive(Debug, PartialEq)]
+pub enum ReadError {
+ /// An id that isn't on this computer (any longer).
+ NotFound(String),
+ Import(ImportError),
+}
+
+/// Reads the ticked sources into one bundle. Ids are the ones [`scan`] gave.
+pub fn read(home: &Path, codex_home: Option<&Path>, ids: &[String]) -> Result<Bundle, ReadError> {
+ let mut all = find_all(home, codex_home);
+ let mut picked = Vec::new();
+ for id in ids {
+ let Some(i) = all.iter().position(|l| &l.found.id == id) else { return Err(ReadError::NotFound(id.clone())) };
+ picked.push(all.swap_remove(i));
+ }
+ let too_large = |m: String| ReadError::Import(ImportError::TooLarge(m));
+ let (mut count, mut total) = (0usize, 0u64);
+ let mut merged = Bundle { format: BUNDLE_FORMAT.into(), ..Bundle::default() };
+ let mut kinds = BTreeSet::new();
+ let mut labels = Vec::new();
+ for l in picked {
+ let mut entries = Vec::new();
+ let mut seen = Vec::new();
+ let mut skipped = l.links.clone();
+ for (rel, u, _) in &l.files {
+ if *u == Use::Seen {
+ seen.push(rel.clone());
+ continue;
+ }
+ count += 1;
+ if count > MAX_ZIP_ENTRIES {
+ return Err(too_large(format!("These folders have more than {MAX_ZIP_ENTRIES} files kwant would read. Zip the parts you want instead.")));
+ }
+ match l.dir.open_file(Path::new(rel)).and_then(|f| safe_fs::read_capped(f, MAX_FILE_BYTES as u64)) {
+ Ok(bytes) => {
+ total += bytes.len() as u64;
+ if total > MAX_UNZIPPED_BYTES {
+ return Err(too_large("These folders hold more than 50 MB kwant would read. Zip the parts you want instead.".into()));
+ }
+ entries.push(Entry { path: rel.clone(), bytes });
+ }
+ Err(e) if safe_fs::is_too_large(&e) => return Err(too_large(format!("{}/{rel} is larger than 4 MB.", l.found.path))),
+ // A symlink, a FIFO or a file gone since the listing: skipped and named.
+ Err(_) => skipped.push(rel.clone()),
+ }
+ }
+ let mut b = match l.found.kind.as_str() {
+ k @ (formats::OPENCLAW | formats::HERMES | formats::CODEX) => {
+ seen.extend(skipped.iter().cloned());
+ let tree = formats::Tree::new(&entries, &seen);
+ let mut b = formats::parse_kind(k, &tree).unwrap_or_default();
+ name_after_source(&mut b, &l.found);
+ b
+ }
+ _ => parsers::from_entries(Unzipped { entries, skipped: Vec::new(), comment: None }, true).map_err(ReadError::Import)?,
+ };
+ if !skipped.is_empty() {
+ let shown: Vec<&str> = skipped.iter().take(10).map(String::as_str).collect();
+ b.omitted.push(super::cut(&format!("Skipped in {} (links or unreadable): {}", l.found.path, shown.join(", ")), 200));
+ }
+ kinds.insert(l.found.kind.clone());
+ labels.push(l.found.label.clone());
+ merged.bots.extend(b.bots);
+ merged.teams.extend(b.teams);
+ merged.skills.extend(b.skills);
+ merged.omitted.extend(b.omitted);
+ }
+ if merged.bots.is_empty() && merged.skills.is_empty() {
+ return Err(ReadError::Import(ImportError::Unsupported("There are no bots or skills kwant can read here.".into())));
+ }
+ merged.source.kind = if kinds.len() == 1 { kinds.into_iter().next().unwrap_or_default() } else { "local".into() };
+ merged.source.label = Some(format!("Found on this computer: {}", labels.join(", ")));
+ Ok(merged)
+}
+
+/// A profile or extra agent is named after its folder unless its own files name it.
+fn name_after_source(b: &mut Bundle, found: &Found) {
+ let Some(bot) = b.bots.first_mut() else { return };
+ let given = match found.id.split_once([':', '-']) {
+ Some((_, n)) if !n.is_empty() => n.to_string(),
+ _ => return,
+ };
+ if bot.name == "OpenClaw" || bot.name == "Hermes" {
+ bot.ref_ = super::slug(&given);
+ bot.name = given;
+ if found.kind == formats::HERMES {
+ bot.title = "Hermes Agent profile".into();
+ }
+ }
+}
+
+#[cfg(all(test, unix))]
+mod tests;
diff --git a/src/import/local/tests.rs b/src/import/local/tests.rs
new file mode 100644
index 00000000..013345d9
--- /dev/null
+++ b/src/import/local/tests.rs
@@ -0,0 +1,215 @@
+use super::*;
+use std::fs;
+use std::os::unix::fs::symlink;
+
+/// Looks like a key; must never appear in anything kwant imports.
+const KEY: &str = "sk-test-NEVER-IMPORT-0123456789abcdef";
+
+fn put(root: &Path, rel: &str, text: &str) {
+ let p = root.join(rel);
+ fs::create_dir_all(p.parent().unwrap()).unwrap();
+ fs::write(p, text).unwrap();
+}
+
+fn skill(name: &str) -> String {
+ format!("---\nname: {name}\ndescription: Does {name}.\n---\n\nSteps for {name}.\n")
+}
+
+/// A home folder with every kind of source, plus key stores next to them.
+fn home_with_everything() -> tempfile::TempDir {
+ let tmp = tempfile::tempdir().unwrap();
+ let h = tmp.path();
+ put(h, ".openclaw/workspace/SOUL.md", "Calm and direct.");
+ put(h, ".openclaw/workspace/AGENTS.md", "Answer briefly.");
+ put(h, ".openclaw/workspace/IDENTITY.md", "- **Name:** Clawdia\n- **Emoji:** 🦞\n");
+ put(h, ".openclaw/workspace/MEMORY.md", "- Likes tea\n");
+ put(h, ".openclaw/workspace/memory/2026-11-01.md", "daily log");
+ put(h, ".openclaw/workspace/skills/weather/SKILL.md", &skill("weather"));
+ put(h, ".openclaw/openclaw.json", &format!("{{\"apiKey\": \"{KEY}\"}}"));
+ put(h, ".openclaw/credentials/oauth.json", KEY);
+ put(h, ".hermes/SOUL.md", "Hermes soul.");
+ put(h, ".hermes/memories/MEMORY.md", "Uses metric units\n§\nWorks at night\n");
+ put(h, ".hermes/memories/USER.md", "Name is Sam\n");
+ put(h, ".hermes/skills/.bundled_manifest", "arxiv:abc123\n");
+ put(h, ".hermes/skills/research/arxiv/SKILL.md", &skill("arxiv"));
+ put(h, ".hermes/skills/mine/SKILL.md", &skill("mine"));
+ put(h, ".hermes/.env", &format!("OPENAI_API_KEY={KEY}\n"));
+ put(h, ".hermes/auth.json", KEY);
+ put(h, ".hermes/config.yaml", &format!("api_key: {KEY}\n"));
+ put(h, ".hermes/profiles/work/SOUL.md", "Work soul.");
+ put(h, ".hermes/profiles/work/.env", KEY);
+ put(h, ".claude/agents/reviewer.md", "---\nname: reviewer\ndescription: Reviews code.\n---\n\nReview the diff.\n");
+ put(h, ".claude/skills/pdf/SKILL.md", &skill("pdf"));
+ put(h, ".claude/.credentials.json", KEY);
+ put(h, ".codex/AGENTS.md", "Prefer small diffs.");
+ put(h, ".codex/auth.json", KEY);
+ put(h, ".codex/config.toml", &format!("api_key = \"{KEY}\"\n"));
+ tmp
+}
+
+fn by_id<'a>(found: &'a [Found], id: &str) -> &'a Found {
+ found.iter().find(|f| f.id == id).unwrap_or_else(|| panic!("{id} not found in {found:?}"))
+}
+
+#[test]
+fn scan_lists_names_and_counts() {
+ let tmp = home_with_everything();
+ let found = scan(tmp.path(), None);
+ let ids: Vec<&str> = found.iter().map(|f| f.id.as_str()).collect();
+ assert_eq!(ids, ["openclaw", "hermes", "hermes:work", "claude-agents", "claude-skills", "codex"]);
+
+ let oc = by_id(&found, "openclaw");
+ assert_eq!((oc.kind.as_str(), oc.label.as_str(), oc.path.as_str()), ("openclaw", "OpenClaw", "~/.openclaw/workspace"));
+ assert_eq!((oc.bots, oc.skills, oc.memories, oc.too_large), (1, 1, 1, false));
+ assert_eq!(oc.names, ["weather"]);
+
+ // The skill Hermes bundled itself isn't counted
+ let hm = by_id(&found, "hermes");
+ assert_eq!((hm.bots, hm.skills, hm.memories), (1, 1, 2));
+ assert_eq!(hm.names, ["mine"]);
+ assert_eq!(by_id(&found, "hermes:work").label, "Hermes Agent (work profile)");
+
+ let ca = by_id(&found, "claude-agents");
+ assert_eq!((ca.kind.as_str(), ca.bots, ca.names.clone()), ("claude-code", 1, vec!["reviewer".to_string()]));
+ let cs = by_id(&found, "claude-skills");
+ assert_eq!((cs.kind.as_str(), cs.bots, cs.skills), ("skill", 0, 1));
+ let cx = by_id(&found, "codex");
+ assert_eq!((cx.bots, cx.skills, cx.path.as_str()), (1, 0, "~/.codex"));
+
+ let json = serde_json::to_string(&found).unwrap();
+ assert!(!json.contains(KEY));
+}
+
+#[test]
+fn key_stores_are_never_wanted() {
+ for (kind, rel) in [
+ (formats::OPENCLAW, "openclaw.json"),
+ (formats::OPENCLAW, "credentials/oauth.json"),
+ (formats::OPENCLAW, ".env"),
+ (formats::HERMES, ".env"),
+ (formats::HERMES, "auth.json"),
+ (formats::HERMES, "config.yaml"),
+ (formats::HERMES, "state.db"),
+ (formats::HERMES, "sessions/abc.json"),
+ (formats::CODEX, "auth.json"),
+ (formats::CODEX, "config.toml"),
+ (formats::CODEX, "sessions/2026/rollout.jsonl"),
+ (CLAUDE_AGENTS, ".credentials.json"),
+ (CLAUDE_SKILLS, "pdf/scripts/run.py"),
+ ] {
+ assert_eq!(wanted(kind, rel), None, "{kind} {rel}");
+ }
+ assert!(!descend(formats::OPENCLAW, "credentials"));
+ assert!(!descend(formats::CODEX, "sessions"));
+ assert!(!descend(formats::HERMES, "profiles"));
+}
+
+#[test]
+fn read_merges_sources_and_never_reads_keys() {
+ let tmp = home_with_everything();
+ // A key file kwant can't open: if import tried, it would be named as skipped
+ fs::set_permissions(tmp.path().join(".hermes/auth.json"), std::os::unix::fs::PermissionsExt::from_mode(0o000)).unwrap();
+ let ids: Vec<String> = ["openclaw", "hermes", "claude-agents", "claude-skills", "codex"].map(String::from).to_vec();
+ let b = read(tmp.path(), None, &ids).unwrap();
+ assert_eq!(b.source.kind, "local");
+ assert_eq!(b.source.label.as_deref(), Some("Found on this computer: OpenClaw, Hermes Agent, Claude Code agents, Claude Code skills, Codex"));
+ let names: Vec<&str> = b.bots.iter().map(|x| x.name.as_str()).collect();
+ assert_eq!(names, ["Clawdia", "Hermes", "reviewer", "Codex"]);
+ let hermes = &b.bots[1];
+ assert!(hermes.memories.iter().any(|m| m.contains("metric")), "{:?}", hermes.memories);
+ assert_eq!(hermes.skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["mine"]);
+ assert!(b.skills.iter().any(|s| s.name == "pdf"));
+ let json = serde_json::to_string(&b).unwrap();
+ assert!(!json.contains(KEY), "a key was imported");
+ assert!(!json.contains("auth.json") || !json.contains("Skipped"), "a key store was opened: {:?}", b.omitted);
+ assert!(!b.omitted.iter().any(|o| o.starts_with("Skipped")), "{:?}", b.omitted);
+}
+
+#[test]
+fn one_source_keeps_its_kind_and_profiles_are_named() {
+ let tmp = home_with_everything();
+ let b = read(tmp.path(), None, &["hermes:work".into()]).unwrap();
+ assert_eq!(b.source.kind, "hermes");
+ assert_eq!(b.source.label.as_deref(), Some("Found on this computer: Hermes Agent (work profile)"));
+ assert_eq!((b.bots[0].name.as_str(), b.bots[0].title.as_str()), ("work", "Hermes Agent profile"));
+}
+
+#[test]
+fn unknown_ids_are_not_found() {
+ let tmp = home_with_everything();
+ assert_eq!(read(tmp.path(), None, &["../../etc".into()]), Err(ReadError::NotFound("../../etc".into())));
+ assert_eq!(read(tmp.path(), None, &["openclaw:nope".into()]), Err(ReadError::NotFound("openclaw:nope".into())));
+}
+
+#[test]
+fn symlinked_folders_count_as_not_found() {
+ let tmp = tempfile::tempdir().unwrap();
+ let elsewhere = tempfile::tempdir().unwrap();
+ put(elsewhere.path(), "AGENTS.md", "Outside the home folder.");
+ put(elsewhere.path(), "SKILL.md", &skill("outside"));
+ symlink(elsewhere.path(), tmp.path().join(".codex")).unwrap();
+ fs::create_dir_all(tmp.path().join(".claude")).unwrap();
+ symlink(elsewhere.path(), tmp.path().join(".claude/agents")).unwrap();
+ // A skill folder that is a link is skipped, the real one next to it read
+ put(tmp.path(), ".claude/skills/real/SKILL.md", &skill("real"));
+ fs::create_dir_all(elsewhere.path().join("linked")).unwrap();
+ put(elsewhere.path(), "linked/SKILL.md", &skill("linked"));
+ symlink(elsewhere.path().join("linked"), tmp.path().join(".claude/skills/linked")).unwrap();
+
+ let found = scan(tmp.path(), None);
+ assert_eq!(found.iter().map(|f| f.id.as_str()).collect::<Vec<_>>(), ["claude-skills"]);
+ assert_eq!(found[0].names, ["real"]);
+ assert_eq!(read(tmp.path(), None, &["codex".into()]), Err(ReadError::NotFound("codex".into())));
+
+ let b = read(tmp.path(), None, &["claude-skills".into()]).unwrap();
+ assert_eq!(b.skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["real"]);
+ assert!(b.omitted.iter().any(|o| o.contains("Skipped") && o.contains("linked")), "{:?}", b.omitted);
+}
+
+#[test]
+fn a_symlinked_file_is_skipped_and_named() {
+ let tmp = tempfile::tempdir().unwrap();
+ let elsewhere = tempfile::tempdir().unwrap();
+ put(elsewhere.path(), "secret.txt", KEY);
+ put(tmp.path(), ".openclaw/workspace/AGENTS.md", "Answer briefly.");
+ put(tmp.path(), ".openclaw/workspace/IDENTITY.md", "- **Name:** Clawdia\n");
+ symlink(elsewhere.path().join("secret.txt"), tmp.path().join(".openclaw/workspace/SOUL.md")).unwrap();
+ let b = read(tmp.path(), None, &["openclaw".into()]).unwrap();
+ let json = serde_json::to_string(&b).unwrap();
+ assert!(!json.contains(KEY));
+ assert!(b.omitted.iter().any(|o| o.contains("Skipped") && o.contains("SOUL.md")), "{:?}", b.omitted);
+}
+
+#[test]
+fn codex_home_is_honoured_but_not_through_a_link() {
+ let tmp = tempfile::tempdir().unwrap();
+ let codex = tempfile::tempdir().unwrap();
+ put(codex.path(), "AGENTS.md", "From CODEX_HOME.");
+ put(tmp.path(), ".codex/AGENTS.md", "From ~/.codex.");
+ let real = codex.path().canonicalize().unwrap();
+ let b = read(tmp.path(), Some(&real), &["codex".into()]).unwrap();
+ assert!(b.bots[0].persona_prompt.contains("From CODEX_HOME."), "{:?}", b.bots[0].persona_prompt);
+
+ let link = tmp.path().join("codex-link");
+ symlink(&real, &link).unwrap();
+ assert!(scan(tmp.path(), Some(&link)).iter().all(|f| f.id != "codex"));
+}
+
+#[test]
+fn more_than_500_files_is_too_large() {
+ let tmp = tempfile::tempdir().unwrap();
+ for i in 0..=MAX_ZIP_ENTRIES {
+ put(tmp.path(), &format!(".claude/agents/a{i:03}.md"), "Be helpful.");
+ }
+ let found = scan(tmp.path(), None);
+ assert!(found[0].too_large);
+ assert_eq!(found[0].names.len(), MAX_NAMES);
+ assert!(matches!(read(tmp.path(), None, &["claude-agents".into()]), Err(ReadError::Import(ImportError::TooLarge(_)))));
+}
+
+#[test]
+fn an_empty_home_finds_nothing() {
+ let tmp = tempfile::tempdir().unwrap();
+ assert!(scan(tmp.path(), None).is_empty());
+ assert!(scan(&tmp.path().join("missing"), None).is_empty());
+}
diff --git a/src/import/mod.rs b/src/import/mod.rs
index f755eac6..d7d8594b 100644
--- a/src/import/mod.rs
+++ b/src/import/mod.rs
@@ -6,6 +6,8 @@
//! stored. See `IMPORT-API.md` in the onboarding notes for the HTTP side.
pub mod archive;
+pub mod github;
+pub mod local;
pub mod parsers;
pub mod prompts;
pub mod scrub;
diff --git a/src/import/parsers.rs b/src/import/parsers.rs
index 8e08783d..2e839d26 100644
--- a/src/import/parsers.rs
+++ b/src/import/parsers.rs
@@ -11,6 +11,8 @@
//! | 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 |
+//! | OpenClaw, Hermes Agent, Codex, Paperclip, ai-employees | a folder (zip, folder pick, GitHub repo, this computer); see [`formats`] |
+//! | Codex `AGENTS.md` | a lone `AGENTS.md` / `AGENTS.override.md` file |
//! | zip | any mix of the files above |
use super::archive::{self, PNG_SIGNATURE};
@@ -21,6 +23,8 @@ use super::{
};
use serde_json::Value;
+pub mod formats;
+
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;
@@ -133,6 +137,9 @@ fn from_plain_text(text: &str) -> Bundle {
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 is_agents_md(filename) {
+ return Ok(agents_md_file(text));
+ }
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);
@@ -281,6 +288,38 @@ fn front_matter(text: &str) -> Result<(Value, &str), ImportError> {
Ok((v, body))
}
+fn base_name(filename: Option<&str>) -> &str {
+ filename.map(|f| f.rsplit(['/', '\\']).next().unwrap_or(f)).unwrap_or("")
+}
+
+/// `AGENTS.md` or `AGENTS.override.md` (Codex, and Paperclip agents).
+fn is_agents_md(filename: Option<&str>) -> bool {
+ let b = base_name(filename);
+ b.eq_ignore_ascii_case("AGENTS.md") || b.eq_ignore_ascii_case("AGENTS.override.md")
+}
+
+/// A lone `AGENTS.md`: a Paperclip agent when it has front matter with a `name`, else one Codex
+/// bot whose instructions are the file.
+fn agents_md_file(text: &str) -> Bundle {
+ if let Ok((mut fm, body)) = front_matter(text) {
+ drop_secret_fields(&mut fm);
+ if !s(&fm, "name").trim().is_empty() {
+ let mut b = bundle(formats::PAPERCLIP, Some("Paperclip".into()));
+ b.bots.push(BotSpec {
+ ref_: super::slug(&any_s(&fm, &["slug", "name"])),
+ name: s(&fm, "name"),
+ title: any_s(&fm, &["title", "role"]),
+ persona_prompt: body.trim().to_string(),
+ ..BotSpec::default()
+ });
+ return b;
+ }
+ }
+ let mut b = bundle(formats::CODEX, Some("Codex".into()));
+ b.bots.push(formats::codex_bot(text.trim().to_string(), Vec::new()));
+ b
+}
+
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)
}
@@ -604,16 +643,78 @@ fn from_openmaus_grok(v: &Value) -> Bundle {
// ── zip ───────────────────────────────────────────────────────────────────
fn from_zip(bytes: &[u8]) -> Result<Bundle, ImportError> {
- let unzipped = archive::read_zip(bytes)?;
+ from_entries(archive::read_zip(bytes)?, false)
+}
+
+/// What a GitHub repository archive held besides its bots: the commit and its licence file.
+#[derive(Debug, Default, Clone, PartialEq)]
+pub struct RepoZip {
+ /// codeload writes the commit id into the archive comment.
+ pub commit: Option<String>,
+ /// The licence file at the top of the repo (else of the folder imported): path and text.
+ pub licence: Option<(String, String)>,
+}
+
+/// A repository archive from codeload: `<repo>-<ref>/…`. `subpath` limits the import to one
+/// folder or file of the repo. Files no format reads aren't inflated, and nothing that fails to
+/// parse stops the rest.
+pub fn parse_repo_zip(bytes: &[u8], subpath: Option<&str>) -> Result<(Bundle, RepoZip), ImportError> {
+ if bytes.len() > MAX_ZIP_BYTES {
+ return Err(too_large("A repository", "20 MB"));
+ }
+ // The reader strips `<repo>-<ref>/` and inflates nothing outside `subpath` but top licences.
+ let mut unzipped = archive::read_zip_as(bytes, archive::ZipKind::Repo { subpath })?;
+ let licence_at = |dir: &str| {
+ unzipped
+ .entries
+ .iter()
+ .filter(|e| {
+ let (d, b) = e.path.rsplit_once('/').unwrap_or(("", &e.path));
+ d.eq_ignore_ascii_case(dir) && archive::is_licence_file(&b.to_lowercase())
+ })
+ .min_by_key(|e| e.path.len())
+ .map(|e| (e.path.clone(), String::from_utf8_lossy(&e.bytes).into_owned()))
+ };
+ let sub = subpath.map(|p| p.trim_matches('/').to_lowercase()).filter(|p| !p.is_empty());
+ let licence = licence_at("").or_else(|| sub.as_deref().and_then(licence_at));
+ let info = RepoZip { commit: unzipped.comment.take(), licence };
+ if let Some(sub) = &sub {
+ let inside = |p: &str| {
+ let l = p.to_lowercase();
+ l == *sub || l.starts_with(&format!("{sub}/"))
+ };
+ unzipped.entries.retain(|e| inside(&e.path));
+ unzipped.skipped.retain(|p| inside(p));
+ if unzipped.entries.is_empty() && unzipped.skipped.is_empty() {
+ return Err(ImportError::Unsupported(format!("There's nothing at {sub} in this repository.")));
+ }
+ }
+ let bundle = from_entries(unzipped, true)?;
+ Ok((bundle, info))
+}
+
+/// A folder's files (from a zip, a repo or this computer): one of the [`formats`] when the files
+/// say so, else each file on its own. `lenient` (repos, this computer) leaves a file that fails
+/// to parse unread instead of refusing the whole import.
+pub(crate) fn from_entries(unzipped: archive::Unzipped, lenient: bool) -> Result<Bundle, ImportError> {
+ let tree = formats::Tree::new(&unzipped.entries, &unzipped.skipped);
+ if let Some(b) = formats::detect(&tree) {
+ if b.bots.is_empty() && b.skills.is_empty() {
+ return Err(ImportError::Unsupported("This folder has no bots or skills kwant can read.".into()));
+ }
+ return Ok(b);
+ }
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();
+ let base = lower.rsplit('/').next().unwrap_or(&lower);
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)) => {
+ match std::str::from_utf8(&e.bytes).ok().and_then(|t| front_matter(t.trim_start_matches('\u{feff}')).ok()) {
+ Some((mut fm, body)) => {
+ drop_secret_fields(&mut fm);
skills.push(skill_from_markdown(&fm, body, Some(&e.path)));
kinds.insert("skill".to_string());
}
@@ -622,9 +723,20 @@ fn from_zip(bytes: &[u8]) -> Result<Bundle, ImportError> {
continue;
}
if e.bytes.starts_with(&ZIP_MAGIC) || e.bytes.starts_with(&EMPTY_ZIP_MAGIC) {
+ if lenient {
+ unread.push(e.path.clone());
+ continue;
+ }
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") {
+ // A repo's AGENTS.md is notes for coding agents, not a bot; licences and dotfiles are
+ // only read by the formats above.
+ if lower.ends_with(".txt")
+ || lower.ends_with("readme.md")
+ || is_agents_md(Some(&e.path))
+ || archive::is_licence_file(base)
+ || archive::READ_DOTFILES.contains(&base)
+ {
unread.push(e.path.clone());
continue;
}
@@ -637,6 +749,7 @@ fn from_zip(bytes: &[u8]) -> Result<Bundle, ImportError> {
merged.omitted.extend(b.omitted);
}
Err(ImportError::Unsupported(_)) => unread.push(e.path.clone()),
+ Err(_) if lenient => unread.push(e.path.clone()),
Err(err) => return Err(invalid(format!("{}: {err}", e.path))),
}
}
@@ -647,7 +760,7 @@ fn from_zip(bytes: &[u8]) -> Result<Bundle, ImportError> {
}
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 lenient { "This has no bots or skills kwant can read." } else { "This zip has no bots or skills kwant can read. Chat-history exports aren't imported." }.into(),
));
}
if kinds.len() == 1 {
@@ -657,7 +770,8 @@ fn from_zip(bytes: &[u8]) -> Result<Bundle, ImportError> {
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));
+ let what = if lenient { "Files that weren't read" } else { "Files in the zip that weren't read" };
+ merged.omitted.push(cut(&format!("{what}: {}{more}", shown.join(", ")), 200));
}
Ok(merged)
}
diff --git a/src/import/parsers/formats.rs b/src/import/parsers/formats.rs
new file mode 100644
index 00000000..4c77bd3d
--- /dev/null
+++ b/src/import/parsers/formats.rs
@@ -0,0 +1,693 @@
+//! Agent homes and kits from other apps (0.8.0 A1): OpenClaw workspaces, Hermes Agent homes and
+//! profiles, Codex homes, Paperclip companies and ai-employees kits. Each arrives as a folder (a
+//! zip, a folder pick, a GitHub repo or a folder found on this computer) and is read from a
+//! [`Tree`] of the files kwant opened. Only named files are used; key stores (`.env`,
+//! `auth.json`, `openclaw.json`, `credentials/`, `config.toml`) are never among them.
+//!
+//! Sources checked (cited in the PR):
+//! - OpenClaw (MIT): docs/concepts/agent-workspace.md, docs/reference/templates/IDENTITY.md
+//! - Hermes Agent (MIT): website/docs/user-guide/features/memory.md, profiles.md, skills.md,
+//! tools/skills_sync.py (`.bundled_manifest`)
+//! - Codex (Apache-2.0): codex-rs/core/src/agents_md.rs (`AGENTS.override.md` before `AGENTS.md`)
+//! - Paperclip (MIT): docs/companies/companies-spec.md (agentcompanies/v1-draft)
+//! - ai-employees (MIT): employees/*/employee.json (`ai-employee/1`), SCHEDULE.md, AGENTS.md
+
+use super::{any_s, arr, bundle, front_matter, memories_from_markdown, s, skill_from_markdown, texts};
+use crate::db::continuity::MAX_INSTRUCTIONS_CHARS;
+use crate::import::archive::Entry;
+use crate::import::scrub::drop_secret_fields;
+use crate::import::{cut, slug, BotSpec, Bundle, RoutineSpec, SkillSpec, TeamSpec};
+use serde_json::Value;
+use std::collections::{BTreeMap, BTreeSet};
+
+pub const OPENCLAW: &str = "openclaw";
+pub const HERMES: &str = "hermes";
+pub const CODEX: &str = "codex";
+pub const PAPERCLIP: &str = "paperclip";
+pub const AI_EMPLOYEES: &str = "ai-employees";
+
+/// The files of one folder, looked up without regard to case. `known` also holds the paths that
+/// were seen but not opened (a Codex `config.toml`), which only ever count as markers.
+pub struct Tree<'a> {
+ files: BTreeMap<String, (&'a str, &'a [u8])>,
+ known: BTreeSet<String>,
+}
+
+impl<'a> Tree<'a> {
+ pub fn new(entries: &'a [Entry], seen: &'a [String]) -> Self {
+ let files: BTreeMap<String, (&str, &[u8])> =
+ entries.iter().map(|e| (e.path.to_lowercase(), (e.path.as_str(), e.bytes.as_slice()))).collect();
+ let known = files.keys().cloned().chain(seen.iter().map(|p| p.to_lowercase())).collect();
+ Tree { files, known }
+ }
+
+ fn has(&self, path: &str) -> bool {
+ self.known.contains(&path.to_lowercase())
+ }
+
+ fn text(&self, path: &str) -> Option<&'a str> {
+ let (_, bytes) = self.files.get(&path.to_lowercase())?;
+ std::str::from_utf8(bytes).ok().map(|t| t.trim_start_matches('\u{feff}'))
+ }
+
+ /// The text, or nothing when it is only whitespace.
+ fn nonempty(&self, path: &str) -> Option<&'a str> {
+ self.text(path).filter(|t| !t.trim().is_empty())
+ }
+
+ /// Opened files under `dir` (lower-case path, original path, bytes).
+ fn under<'b>(&'b self, dir: &str) -> impl Iterator<Item = (&'b str, &'a str, &'a [u8])> + 'b {
+ let prefix = if dir.is_empty() { String::new() } else { format!("{}/", dir.to_lowercase()) };
+ self.files.iter().filter(move |(k, _)| k.starts_with(&prefix)).map(|(k, (p, b))| (k.as_str(), *p, *b))
+ }
+
+ fn paths(&self) -> impl Iterator<Item = &String> {
+ self.known.iter()
+ }
+}
+
+fn join(dir: &str, name: &str) -> String {
+ if dir.is_empty() {
+ name.to_string()
+ } else {
+ format!("{dir}/{name}")
+ }
+}
+
+fn parent(path: &str) -> &str {
+ path.rsplit_once('/').map(|(p, _)| p).unwrap_or("")
+}
+
+fn base(path: &str) -> &str {
+ path.rsplit('/').next().unwrap_or(path)
+}
+
+/// `dir` when `path` ends with `/suffix` (or is `suffix`).
+fn root_of<'p>(path: &'p str, suffix: &str) -> Option<&'p str> {
+ if path == suffix {
+ return Some("");
+ }
+ path.strip_suffix(suffix).and_then(|p| p.strip_suffix('/'))
+}
+
+/// Roots in order, without ones that sit inside another root.
+fn outermost(mut roots: Vec<String>) -> Vec<String> {
+ roots.sort();
+ roots.dedup();
+ let all = roots.clone();
+ roots.retain(|r| !all.iter().any(|o| o != r && (o.is_empty() || r.starts_with(&format!("{o}/")))));
+ roots
+}
+
+/// Original-case version of a lower-case dir, for names shown to the person.
+fn shown_dir(t: &Tree, lower_dir: &str) -> String {
+ t.files
+ .values()
+ .find_map(|(p, _)| p.to_lowercase().starts_with(&format!("{lower_dir}/")).then(|| p[..lower_dir.len()].to_string()))
+ .unwrap_or_else(|| lower_dir.to_string())
+}
+
+/// The body after optional `---` front matter.
+fn without_front_matter(text: &str) -> &str {
+ match front_matter(text) {
+ Ok((_, body)) => body,
+ Err(_) => text,
+ }
+}
+
+/// `SKILL.md` files under `dir/skills`: directly (`skills/<name>/SKILL.md`) or, with `nested`, at any
+/// depth (Hermes: `skills/<category>/<name>/SKILL.md`). Returns them and how many couldn't be read.
+fn skills_in(t: &Tree, dir: &str, nested: bool, leave_out: &BTreeSet<String>) -> (Vec<SkillSpec>, usize, usize) {
+ let skills_dir = join(dir, "skills");
+ let mut out = Vec::new();
+ let (mut unreadable, mut left_out) = (0, 0);
+ for (lower, path, bytes) in t.under(&skills_dir) {
+ if base(lower) != "skill.md" {
+ continue;
+ }
+ let depth = lower[skills_dir.len() + 1..].matches('/').count();
+ if depth < 1 || (!nested && depth != 1) {
+ continue;
+ }
+ let folder = base(parent(lower)).to_string();
+ if leave_out.contains(&folder) {
+ left_out += 1;
+ continue;
+ }
+ match std::str::from_utf8(bytes).ok().and_then(|text| front_matter(text.trim_start_matches('\u{feff}')).ok()) {
+ Some((mut fm, body)) => {
+ drop_secret_fields(&mut fm);
+ out.push(skill_from_markdown(&fm, body, Some(path)));
+ }
+ None => unreadable += 1,
+ }
+ }
+ (out, unreadable, left_out)
+}
+
+fn plural(n: usize, one: &str, many: &str) -> String {
+ format!("{n} {}", if n == 1 { one } else { many })
+}
+
+fn note_unreadable(b: &mut Bundle, n: usize) {
+ if n > 0 {
+ b.omitted.push(format!("{} without valid front matter", plural(n, "SKILL.md", "SKILL.md files")));
+ }
+}
+
+/// What the files say this folder is, when it is one of the formats here.
+pub fn detect(t: &Tree) -> Option<Bundle> {
+ let roots = ai_employee_roots(t);
+ if !roots.is_empty() {
+ return Some(ai_employees(t, &roots));
+ }
+ let roots = paperclip_roots(t);
+ if !roots.is_empty() {
+ return Some(paperclip(t, &roots));
+ }
+ let hermes_roots = hermes_roots(t);
+ if !hermes_roots.is_empty() {
+ return Some(hermes(t, &hermes_roots));
+ }
+ let roots = openclaw_roots(t);
+ if !roots.is_empty() {
+ return Some(openclaw(t, &roots));
+ }
+ let roots = codex_roots(t);
+ if !roots.is_empty() {
+ return Some(codex(t, &roots));
+ }
+ None
+}
+
+/// A folder whose kind is already known (found on this computer), read from its root.
+pub fn parse_kind(kind: &str, t: &Tree) -> Option<Bundle> {
+ let root = vec![String::new()];
+ match kind {
+ OPENCLAW => Some(openclaw(t, &root)),
+ HERMES => Some(hermes(t, &root)),
+ CODEX => Some(codex(t, &root)),
+ _ => None,
+ }
+}
+
+// ── OpenClaw ──────────────────────────────────────────────────────────────
+
+fn openclaw_roots(t: &Tree) -> Vec<String> {
+ let mut roots = Vec::new();
+ for p in t.paths() {
+ let Some(dir) = root_of(p, "soul.md").or_else(|| root_of(p, "identity.md")) else { continue };
+ let workspace_file = ["agents.md", "user.md", "memory.md", "tools.md", "heartbeat.md"].iter().any(|f| t.has(&join(dir, f)))
+ || t.paths().any(|q| q.starts_with(&join(dir, "memory/")));
+ if workspace_file {
+ roots.push(dir.to_string());
+ }
+ }
+ roots.sort();
+ roots.dedup();
+ roots
+}
+
+/// `- **Name:** Clawd` lines (labels any case; `_(…)_` placeholders and empty values left out).
+fn identity_fields(text: &str) -> BTreeMap<String, String> {
+ let mut out = BTreeMap::new();
+ for line in without_front_matter(text).lines() {
+ let l = line.trim().trim_start_matches(['-', '*']).trim().replace("**", "");
+ let Some((label, value)) = l.split_once(':') else { continue };
+ let label = label.trim().to_lowercase();
+ if !matches!(label.as_str(), "name" | "creature" | "vibe" | "theme" | "emoji" | "avatar") {
+ continue;
+ }
+ let value = value.trim().trim_matches('_').trim();
+ if value.is_empty() || (value.starts_with('(') && value.ends_with(')')) {
+ continue;
+ }
+ out.entry(label).or_insert_with(|| value.to_string());
+ }
+ out
+}
+
+fn openclaw(t: &Tree, roots: &[String]) -> Bundle {
+ let mut b = bundle(OPENCLAW, Some("OpenClaw".into()));
+ let (mut logs, mut boot, mut unreadable) = (0, false, 0);
+ for dir in roots {
+ let id = t.text(&join(dir, "IDENTITY.md")).map(identity_fields).unwrap_or_default();
+ // `workspace-<agentId>` is one agent of a multi-agent setup; `workspace` the default one.
+ let shown = shown_dir(t, dir);
+ let folder = base(&shown);
+ let fallback = match folder.to_lowercase() {
+ f if f.is_empty() || f == "workspace" || f.starts_with('.') => "OpenClaw".to_string(),
+ f if f.starts_with("workspace-") => folder["workspace-".len()..].to_string(),
+ _ => folder.to_string(),
+ };
+ let name = id.get("name").cloned().unwrap_or(fallback);
+ let title = ["theme", "creature", "vibe"].iter().find_map(|k| id.get(*k).cloned()).unwrap_or_else(|| "OpenClaw agent".into());
+ let mut persona = t.text(&join(dir, "AGENTS.md")).map(|a| without_front_matter(a).trim().to_string()).unwrap_or_default();
+ let extra: Vec<String> =
+ [("Creature", "creature"), ("Vibe", "vibe")].iter().filter_map(|(label, k)| id.get(*k).map(|v| format!("- {label}: {v}"))).collect();
+ if !extra.is_empty() {
+ persona = format!("{persona}\n\n## Identity\n{}", extra.join("\n")).trim().to_string();
+ }
+ let mut memories = t.text(&join(dir, "MEMORY.md")).map(|m| memories_from_markdown(without_front_matter(m))).unwrap_or_default();
+ if let Some(user) = t.text(&join(dir, "USER.md")) {
+ memories.extend(memories_from_markdown(without_front_matter(user)).into_iter().map(|m| format!("About the person: {m}")));
+ }
+ let (skills, bad, _) = skills_in(t, dir, false, &BTreeSet::new());
+ unreadable += bad;
+ logs += t.paths().filter(|p| p.starts_with(&join(dir, "memory/")) && p.ends_with(".md")).count();
+ boot |= t.has(&join(dir, "BOOT.md")) || t.has(&join(dir, "BOOTSTRAP.md"));
+ b.bots.push(BotSpec {
+ ref_: slug(&name),
+ avatar_hint: id.get("emoji").cloned(),
+ soul: t.text(&join(dir, "SOUL.md")).map(|s| without_front_matter(s).trim().to_string()).unwrap_or_default(),
+ name,
+ title,
+ persona_prompt: persona,
+ memories,
+ skills,
+ ..BotSpec::default()
+ });
+ }
+ if logs > 0 {
+ b.omitted.push(format!("{} (memory/*.md) weren't imported", plural(logs, "daily memory log", "daily memory logs")));
+ }
+ if boot {
+ b.omitted.push("BOOT.md and BOOTSTRAP.md (first-run scripts) weren't imported".into());
+ }
+ note_unreadable(&mut b, unreadable);
+ b
+}
+
+// ── Hermes Agent ──────────────────────────────────────────────────────────
+
+fn hermes_roots(t: &Tree) -> Vec<String> {
+ let mut roots: Vec<String> = t
+ .paths()
+ .filter_map(|p| root_of(p, "memories/memory.md").or_else(|| root_of(p, "memories/user.md")).or_else(|| root_of(p, "skills/.bundled_manifest")))
+ .map(str::to_string)
+ .collect();
+ roots.sort();
+ roots.dedup();
+ roots
+}
+
+/// Hermes memory entries: separated by lines that hold only `§`.
+fn hermes_entries(text: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ let mut cur = String::new();
+ for line in text.lines() {
+ if line.trim() == "§" {
+ out.push(std::mem::take(&mut cur));
+ } else {
+ cur.push_str(line);
+ cur.push('\n');
+ }
+ }
+ out.push(cur);
+ out.into_iter().map(|e| e.trim().to_string()).filter(|e| !e.is_empty()).collect()
+}
+
+/// Skill names in `skills/.bundled_manifest` (`name:hash` lines, or plain names in v1).
+fn bundled_skills(text: &str) -> BTreeSet<String> {
+ text.lines().filter_map(|l| l.split(':').next()).map(|n| n.trim().to_lowercase()).filter(|n| !n.is_empty()).collect()
+}
+
+fn hermes(t: &Tree, roots: &[String]) -> Bundle {
+ let mut b = bundle(HERMES, Some("Hermes Agent".into()));
+ let (mut seeded, mut unreadable) = (0, 0);
+ for dir in roots {
+ let shown = shown_dir(t, dir);
+ // `profiles/<name>/` is a Hermes profile: its own bot, named after it.
+ let profile = shown.rsplit_once('/').filter(|(p, _)| base(p).eq_ignore_ascii_case("profiles")).map(|(_, n)| n.to_string());
+ let name = profile.clone().unwrap_or_else(|| "Hermes".into());
+ let bundled = t.text(&join(dir, "skills/.bundled_manifest")).map(bundled_skills).unwrap_or_default();
+ let (skills, bad, left_out) = skills_in(t, dir, true, &bundled);
+ seeded += left_out;
+ unreadable += bad;
+ let mut memories = t.text(&join(dir, "memories/MEMORY.md")).map(hermes_entries).unwrap_or_default();
+ if let Some(user) = t.text(&join(dir, "memories/USER.md")) {
+ memories.extend(hermes_entries(user).into_iter().map(|m| format!("About the person: {m}")));
+ }
+ b.bots.push(BotSpec {
+ ref_: slug(&name),
+ name,
+ title: match profile {
+ Some(_) => "Hermes Agent profile".into(),
+ None => "Hermes Agent".into(),
+ },
+ soul: t.text(&join(dir, "SOUL.md")).map(|s| s.trim().to_string()).unwrap_or_default(),
+ memories,
+ skills,
+ ..BotSpec::default()
+ });
+ }
+ if seeded > 0 {
+ b.omitted.push(format!("{} that Hermes installs itself (skills/.bundled_manifest) weren't imported", plural(seeded, "skill", "skills")));
+ }
+ b.omitted.push("Hermes keys and settings (.env, auth.json, config.yaml) are never read".into());
+ note_unreadable(&mut b, unreadable);
+ b
+}
+
+// ── Codex ─────────────────────────────────────────────────────────────────
+
+fn codex_roots(t: &Tree) -> Vec<String> {
+ let mut roots = Vec::new();
+ for p in t.paths() {
+ let Some(dir) = root_of(p, "agents.md").or_else(|| root_of(p, "agents.override.md")) else { continue };
+ if t.has(&join(dir, "soul.md")) {
+ continue;
+ }
+ if t.has(&join(dir, "config.toml")) || t.has(&join(dir, "agents.override.md")) || base(dir) == ".codex" {
+ roots.push(dir.to_string());
+ }
+ }
+ outermost(roots)
+}
+
+/// Codex reads `AGENTS.override.md` when it has text, else `AGENTS.md`.
+pub fn codex_instructions(override_md: Option<&str>, agents_md: Option<&str>) -> String {
+ override_md.filter(|t| !t.trim().is_empty()).or(agents_md).unwrap_or("").trim().to_string()
+}
+
+fn codex(t: &Tree, roots: &[String]) -> Bundle {
+ let mut b = bundle(CODEX, Some("Codex".into()));
+ let mut unreadable = 0;
+ for dir in roots {
+ let (skills, bad, _) = skills_in(t, dir, false, &BTreeSet::new());
+ unreadable += bad;
+ b.bots.push(codex_bot(codex_instructions(t.nonempty(&join(dir, "AGENTS.override.md")), t.text(&join(dir, "AGENTS.md"))), skills));
+ }
+ b.omitted.push("Codex sign-in and settings (auth.json, config.toml) are never read".into());
+ note_unreadable(&mut b, unreadable);
+ b
+}
+
+pub fn codex_bot(instructions: String, skills: Vec<SkillSpec>) -> BotSpec {
+ BotSpec {
+ ref_: "codex".into(),
+ name: "Codex".into(),
+ title: "Coding agent (from Codex)".into(),
+ persona_prompt: instructions,
+ skills,
+ ..BotSpec::default()
+ }
+}
+
+// ── Paperclip ─────────────────────────────────────────────────────────────
+
+fn has_front_matter(t: &Tree, path: &str) -> bool {
+ t.text(path).is_some_and(|x| front_matter(x).is_ok())
+}
+
+/// `<root>/agents/<slug>/AGENTS.md` → `<root>`.
+fn paperclip_agent_root(lower: &str) -> Option<&str> {
+ let agent_dir = root_of(lower, "agents.md")?;
+ let agents = parent(agent_dir);
+ (base(agents) == "agents").then(|| parent(agents))
+}
+
+fn paperclip_roots(t: &Tree) -> Vec<String> {
+ let mut roots: Vec<String> = t.paths().filter_map(|p| root_of(p, "company.md")).filter(|d| has_front_matter(t, &join(d, "company.md"))).map(str::to_string).collect();
+ if roots.is_empty() {
+ roots = t.paths().filter_map(|p| root_of(p, "team.md")).filter(|d| has_front_matter(t, &join(d, "team.md"))).map(str::to_string).collect();
+ }
+ if roots.is_empty() {
+ roots = t
+ .paths()
+ .filter(|p| has_front_matter(t, p))
+ .filter_map(|p| paperclip_agent_root(p))
+ .map(str::to_string)
+ .collect();
+ }
+ outermost(roots)
+}
+
+/// The agent slug a Paperclip path names: `../cto/AGENTS.md` and `agents/cto/AGENTS.md` → `cto`;
+/// a bare `cto` stays `cto`.
+fn agent_slug_of(reference: &str) -> String {
+ let r = reference.trim().replace('\\', "/").to_lowercase();
+ match root_of(&r, "agents.md") {
+ Some(dir) => base(dir).to_string(),
+ None => base(r.trim_end_matches('/')).to_string(),
+ }
+}
+
+/// One Paperclip agent: its slug (folder, or front matter `slug`), front matter and body.
+struct PaperclipAgent {
+ slug: String,
+ fm: Value,
+ body: String,
+}
+
+fn paperclip(t: &Tree, roots: &[String]) -> Bundle {
+ let mut b = bundle(PAPERCLIP, Some("Paperclip".into()));
+ let (mut projects, mut one_off, mut unreadable) = (0, 0, 0);
+ for root in roots {
+ let prefix = if root.is_empty() { String::new() } else { format!("{root}/") };
+ let company = t.text(&join(root, "COMPANY.md")).and_then(|x| front_matter(x).ok());
+ let team_md = t.text(&join(root, "TEAM.md")).and_then(|x| front_matter(x).ok());
+ projects += t.paths().filter(|p| p.starts_with(&prefix) && base(p) == "project.md").count();
+
+ // Skills by short name: `skills/<shortname>/SKILL.md`.
+ let mut skills: BTreeMap<String, SkillSpec> = BTreeMap::new();
+ let mut agents: Vec<PaperclipAgent> = Vec::new();
+ let mut tasks: Vec<(String, Value, String)> = Vec::new();
+ for (lower, path, bytes) in t.under(root) {
+ let is_skill = base(lower) == "skill.md" && base(parent(parent(lower))) == "skills";
+ let is_agent = paperclip_agent_root(lower).is_some();
+ let is_task = base(lower) == "task.md";
+ if !(is_skill || is_agent || is_task) {
+ continue;
+ }
+ let Some((mut fm, body)) = std::str::from_utf8(bytes).ok().and_then(|x| front_matter(x.trim_start_matches('\u{feff}')).ok()) else {
+ unreadable += usize::from(is_skill);
+ continue;
+ };
+ drop_secret_fields(&mut fm);
+ let folder = base(parent(lower)).to_string();
+ if is_skill {
+ skills.insert(folder, skill_from_markdown(&fm, body, Some(path)));
+ } else if is_agent {
+ let own = s(&fm, "slug").trim().to_lowercase();
+ agents.push(PaperclipAgent { slug: if own.is_empty() { folder } else { own }, fm, body: body.trim().to_string() });
+ } else {
+ let own = s(&fm, "slug").trim().to_lowercase();
+ tasks.push((if own.is_empty() { folder } else { own }, fm, body.trim().to_string()));
+ }
+ }
+ let known: BTreeSet<String> = agents.iter().map(|a| a.slug.clone()).collect();
+
+ // Recurring tasks become routines; their schedule lives in .paperclip.yaml `routines`.
+ let triggers = t
+ .text(&join(root, ".paperclip.yaml"))
+ .and_then(|y| serde_norway::from_str::<Value>(y).ok())
+ .and_then(|v| v.get("routines").cloned())
+ .unwrap_or(Value::Null);
+ let mut routines: BTreeMap<String, Vec<RoutineSpec>> = BTreeMap::new();
+ for (task_slug, fm, body) in tasks {
+ let recurring = fm.get("recurring").and_then(Value::as_bool).unwrap_or(false);
+ let assignee = agent_slug_of(&s(&fm, "assignee"));
+ if !recurring || !known.contains(&assignee) {
+ one_off += 1;
+ continue;
+ }
+ let schedule_text = arr(triggers.get(&task_slug).unwrap_or(&Value::Null), "triggers")
+ .iter()
+ .find(|tr| s(tr, "kind") == "schedule" && !s(tr, "cronExpression").trim().is_empty())
+ .map(|tr| match s(tr, "timezone").trim() {
+ "" => s(tr, "cronExpression").trim().to_string(),
+ zone => format!("{} ({zone})", s(tr, "cronExpression").trim()),
+ });
+ let name = any_s(&fm, &["name", "title"]);
+ routines.entry(assignee).or_default().push(RoutineSpec {
+ name: if name.trim().is_empty() { task_slug } else { name },
+ instructions: cut(&body, MAX_INSTRUCTIONS_CHARS),
+ schedule_text,
+ ..RoutineSpec::default()
+ });
+ }
+
+ // The lead: TEAM.md's manager, else the agent that reports to nobody.
+ let mut lead = team_md.as_ref().map(|(fm, _)| agent_slug_of(&s(fm, "manager"))).filter(|m| known.contains(m));
+ let mut used = BTreeSet::new();
+ let mut members = Vec::new();
+ for a in &agents {
+ if lead.is_none() && matches!(a.fm.get("reportsTo"), None | Some(Value::Null)) {
+ lead = Some(a.slug.clone());
+ }
+ let mut own = Vec::new();
+ for wanted in texts(arr(&a.fm, "skills")) {
+ let w = wanted.trim().replace('\\', "/").to_lowercase();
+ let short = base(root_of(&w, "skill.md").unwrap_or(w.trim_end_matches('/'))).to_string();
+ if let Some(sk) = skills.get(&short) {
+ own.push(sk.clone());
+ used.insert(short);
+ }
+ }
+ members.push(slug(&a.slug));
+ b.bots.push(BotSpec {
+ ref_: slug(&a.slug),
+ name: any_s(&a.fm, &["name", "slug"]),
+ title: any_s(&a.fm, &["title", "role"]),
+ persona_prompt: a.body.clone(),
+ skills: own,
+ routines: routines.remove(&a.slug).unwrap_or_default(),
+ ..BotSpec::default()
+ });
+ }
+ b.skills.extend(skills.into_iter().filter(|(k, _)| !used.contains(k)).map(|(_, v)| v));
+ if members.len() > 1 {
+ let header = team_md.as_ref().or(company.as_ref()).map(|(fm, _)| fm);
+ let name = header.map(|fm| s(fm, "name")).filter(|n| !n.trim().is_empty()).unwrap_or_else(|| {
+ let d = base(&shown_dir(t, root)).to_string();
+ if d.is_empty() { "Paperclip company".into() } else { d }
+ });
+ let mut instructions: Vec<String> = Vec::new();
+ for (fm, _) in [&company, &team_md].into_iter().flatten() {
+ let d = s(fm, "description").trim().to_string();
+ if !d.is_empty() && !instructions.contains(&d) {
+ instructions.push(d);
+ }
+ }
+ if let Some((fm, _)) = &company {
+ let goals = texts(arr(fm, "goals"));
+ if !goals.is_empty() {
+ instructions.push(format!("Company goals:\n{}", goals.iter().map(|g| format!("- {}", g.trim())).collect::<Vec<_>>().join("\n")));
+ }
+ }
+ let lead = lead.map(|l| slug(&l));
+ b.teams.push(TeamSpec {
+ name,
+ members: members.into_iter().filter(|r| Some(r) != lead.as_ref()).collect(),
+ lead,
+ instructions: Some(instructions.join("\n\n")).filter(|i| !i.is_empty()),
+ });
+ }
+ }
+ if projects > 0 {
+ b.omitted.push(format!("{} weren't imported", plural(projects, "project", "projects")));
+ }
+ if one_off > 0 {
+ b.omitted.push(format!("{} that aren't recurring (or have no agent here) weren't imported", plural(one_off, "task", "tasks")));
+ }
+ b.omitted.push("Paperclip adapters, environment inputs and secrets (.paperclip.yaml) are never imported".into());
+ note_unreadable(&mut b, unreadable);
+ b
+}
+
+// ── ai-employees ──────────────────────────────────────────────────────────
+
+fn ai_employee_roots(t: &Tree) -> Vec<String> {
+ let mut roots: Vec<String> = t
+ .paths()
+ .filter_map(|p| root_of(p, "employee.json"))
+ .filter(|d| {
+ t.text(&join(d, "employee.json"))
+ .and_then(|x| serde_json::from_str::<Value>(x).ok())
+ .is_some_and(|v| s(&v, "schema").starts_with("ai-employee/"))
+ })
+ .map(str::to_string)
+ .collect();
+ roots.sort();
+ roots.dedup();
+ roots
+}
+
+/// `mon-fri` + `07:15` → `15 7 * * 1-5`; days the cron can't say (`first-weekday`, `off`) stay as
+/// written, so the routine arrives at the usual placeholder with a warning.
+pub fn ai_employee_schedule(days: &str, fire: &str) -> String {
+ let days = days.trim().trim_matches('`').to_lowercase();
+ let fire = fire.trim().trim_matches('`');
+ let dow = match days.as_str() {
+ "mon-fri" => Some("1-5"),
+ "mon" => Some("1"),
+ "tue" => Some("2"),
+ "wed" => Some("3"),
+ "thu" => Some("4"),
+ "fri" => Some("5"),
+ "sat" => Some("6"),
+ "sun" => Some("0"),
+ _ => None,
+ };
+ let hm = fire.split_once(':').and_then(|(h, m)| Some((h.trim().parse::<u8>().ok()?, m.trim().parse::<u8>().ok()?))).filter(|(h, m)| *h < 24 && *m < 60);
+ match (dow, hm) {
+ (Some(d), Some((h, m))) => format!("{m} {h} * * {d}"),
+ _ => format!("{days} {fire}"),
+ }
+}
+
+/// `SCHEDULE.md` table rows: `| \`routine\` | \`days\` | fire | …`.
+fn schedule_rows(text: &str) -> Vec<(String, String, String)> {
+ text.lines()
+ .filter_map(|l| {
+ let cells: Vec<&str> = l.trim().trim_matches('|').split('|').map(|c| c.trim()).collect();
+ if cells.len() < 3 || !cells[0].starts_with('`') {
+ return None;
+ }
+ let id = cells[0].trim_matches('`').to_string();
+ (cells[2].contains(':') && !id.is_empty()).then(|| (id, cells[1].trim_matches('`').to_string(), cells[2].to_string()))
+ })
+ .collect()
+}
+
+fn ai_employees(t: &Tree, roots: &[String]) -> Bundle {
+ let mut b = bundle(AI_EMPLOYEES, Some("AI Employees".into()));
+ let mut any_routines = false;
+ for dir in roots {
+ let Some(mut v) = t.text(&join(dir, "employee.json")).and_then(|x| serde_json::from_str::<Value>(x).ok()) else { continue };
+ drop_secret_fields(&mut v);
+ let name = any_s(&v, &["name", "slug"]);
+ let mut rows: Vec<(String, String, String)> =
+ arr(&v, "routines").iter().map(|r| (any_s(r, &["id", "name"]), s(r, "days"), s(r, "fire"))).filter(|(id, _, _)| !id.is_empty()).collect();
+ if rows.is_empty() {
+ rows = t.text(&join(dir, "SCHEDULE.md")).map(schedule_rows).unwrap_or_default();
+ }
+ let routines: Vec<RoutineSpec> = rows
+ .into_iter()
+ .map(|(id, days, fire)| {
+ let description = t
+ .text(&join(dir, &format!("routines/{id}/SKILL.md")))
+ .and_then(|x| front_matter(x).ok())
+ .map(|(fm, _)| s(&fm, "description"))
+ .unwrap_or_default();
+ let instructions = format!(
+ "{}\n\nFollow routines/{id}/SKILL.md in the {name} kit folder (github.com/markfulton/ai-employees). As the kit's AGENTS.md says, read CONTRACT.md, ROLE.md and your row in SCHEDULE.md first.",
+ description.trim()
+ );
+ RoutineSpec {
+ name: id,
+ instructions: cut(instructions.trim(), MAX_INSTRUCTIONS_CHARS),
+ schedule_text: Some(ai_employee_schedule(&days, &fire)),
+ ..RoutineSpec::default()
+ }
+ })
+ .collect();
+ any_routines |= !routines.is_empty();
+ let tool_hints = arr(&v, "connections")
+ .iter()
+ .map(|c| {
+ let providers = texts(arr(c, "providers"));
+ if providers.is_empty() { s(c, "capability") } else { format!("{} ({})", s(c, "capability"), providers.join(", ")) }
+ })
+ .filter(|h| !h.trim().is_empty())
+ .collect();
+ b.bots.push(BotSpec {
+ ref_: slug(&any_s(&v, &["slug", "name"])),
+ name,
+ title: s(&v, "role"),
+ persona_prompt: t.text(&join(dir, "AGENTS.md")).map(|a| a.trim().to_string()).unwrap_or_default(),
+ routines,
+ tool_hints,
+ ..BotSpec::default()
+ });
+ }
+ if any_routines {
+ b.omitted.push("AI Employee routines run from the kit's own folder (CONTRACT.md, SCHEDULE.md, scripts); only their names, schedules and a pointer were imported".into());
+ b.omitted.push("Routine times are the kit's local machine time and were set in UTC: check each before turning it on".into());
+ }
+ b
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/src/import/parsers/formats/tests.rs b/src/import/parsers/formats/tests.rs
new file mode 100644
index 00000000..c5c5b7be
--- /dev/null
+++ b/src/import/parsers/formats/tests.rs
@@ -0,0 +1,337 @@
+//! Each format from a small folder shaped like its project's own docs (sources in `formats.rs`).
+
+use super::*;
+use crate::import::parsers::{parse_file, parse_repo_zip};
+use crate::import::{normalize, read_schedule, ImportError};
+use std::io::Write;
+
+/// A fake key that must never reach a bundle.
+const KEY: &str = "sk-ant-api03-ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
+
+pub(crate) fn zip_of(files: &[(&str, &str)], comment: Option<&str>) -> Vec<u8> {
+ let mut out = std::io::Cursor::new(Vec::new());
+ {
+ let mut zip = zip::ZipWriter::new(&mut out);
+ let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ for (path, text) in files {
+ zip.start_file(*path, opts).unwrap();
+ zip.write_all(text.as_bytes()).unwrap();
+ }
+ if let Some(c) = comment {
+ zip.set_comment(c.to_string()).unwrap();
+ }
+ zip.finish().unwrap();
+ }
+ out.into_inner()
+}
+
+fn import(files: &[(&str, &str)]) -> Bundle {
+ parse_file(&zip_of(files, None), Some("folder.zip")).unwrap()
+}
+
+fn no_key(b: &Bundle) {
+ let json = serde_json::to_string(b).unwrap();
+ assert!(!json.contains(KEY), "a key reached the bundle: {json}");
+}
+
+// ── OpenClaw ──────────────────────────────────────────────────────────────
+
+const IDENTITY: &str = "---\nsummary: \"Agent identity record\"\n---\n# IDENTITY.md - Who Am I?\n\n- **Name:** Clawd\n- **Creature:** a space lobster\n- **Vibe:** calm, dry humour\n- **Emoji:** 🦞\n- **Avatar:**\n _(workspace-relative path, http(s) URL, or data URI)_\n";
+
+#[test]
+fn openclaw_workspace() {
+ let b = import(&[
+ (".openclaw/openclaw.json", &format!("{{\"auth\": {{\"anthropic\": \"{KEY}\"}}}}")),
+ (".openclaw/credentials/anthropic.json", &format!("{{\"key\": \"{KEY}\"}}")),
+ (".openclaw/workspace/SOUL.md", "Be genuinely helpful."),
+ (".openclaw/workspace/AGENTS.md", "# AGENTS.md\nRead SOUL.md first. Keep notes."),
+ (".openclaw/workspace/IDENTITY.md", IDENTITY),
+ (".openclaw/workspace/USER.md", "# USER.md\n- Name: Oleks\n- Timezone: Europe/Ljubljana"),
+ (".openclaw/workspace/MEMORY.md", "# Memory\n- Ships kwant on Mondays.\n- Prefers short replies."),
+ (".openclaw/workspace/memory/2026-11-08.md", "Daily log"),
+ (".openclaw/workspace/BOOTSTRAP.md", "First run"),
+ (".openclaw/workspace/skills/weather/SKILL.md", "---\nname: weather\ndescription: Look up the weather\n---\nUse wttr.in."),
+ (".openclaw/workspace-research/SOUL.md", "Dig deep."),
+ (".openclaw/workspace-research/AGENTS.md", "You research."),
+ ]);
+ assert_eq!(b.source.kind, OPENCLAW);
+ assert_eq!(b.bots.len(), 2);
+ let main = b.bots.iter().find(|x| x.name == "Clawd").expect("named from IDENTITY.md");
+ assert_eq!(main.title, "a space lobster");
+ assert_eq!(main.avatar_hint.as_deref(), Some("🦞"));
+ assert_eq!(main.soul, "Be genuinely helpful.");
+ assert!(main.persona_prompt.starts_with("# AGENTS.md\nRead SOUL.md first."));
+ assert!(main.persona_prompt.contains("- Vibe: calm, dry humour"));
+ assert!(main.memories.contains(&"Ships kwant on Mondays.".to_string()));
+ assert!(main.memories.contains(&"About the person: Timezone: Europe/Ljubljana".to_string()));
+ assert_eq!(main.skills.len(), 1);
+ assert_eq!(main.skills[0].name, "weather");
+ let research = b.bots.iter().find(|x| x.name == "research").expect("workspace-<agentId>");
+ assert_eq!(research.persona_prompt, "You research.");
+ assert!(b.omitted.iter().any(|o| o.contains("1 daily memory log")));
+ assert!(b.omitted.iter().any(|o| o.contains("BOOTSTRAP.md")));
+ no_key(&b);
+ let checked = normalize(b, &[]);
+ assert!(checked.problems.is_empty(), "{:?}", checked.problems);
+}
+
+#[test]
+fn identity_lines() {
+ let f = identity_fields(IDENTITY);
+ assert_eq!(f.get("name").map(String::as_str), Some("Clawd"));
+ assert_eq!(f.get("emoji").map(String::as_str), Some("🦞"));
+ assert!(!f.contains_key("avatar"), "placeholder on the next line is ignored");
+ let template = "- **Name:**\n _(pick something you like)_\n- **Theme:** _(e.g. noir)_";
+ assert!(identity_fields(template).is_empty());
+}
+
+// ── Hermes Agent ──────────────────────────────────────────────────────────
+
+#[test]
+fn hermes_home_and_profile() {
+ let b = import(&[
+ (".hermes/.env", &format!("ANTHROPIC_API_KEY={KEY}")),
+ (".hermes/auth.json", &format!("{{\"token\": \"{KEY}\"}}")),
+ (".hermes/SOUL.md", "You are Hermes."),
+ (".hermes/memories/MEMORY.md", "Project kwant is Rust.\n§\nDeploys go through Ada,\nnever directly.\n§\n"),
+ (".hermes/memories/USER.md", "Oleks likes short answers."),
+ (".hermes/skills/.bundled_manifest", "arxiv:0f3c\nweb-search:99aa\n"),
+ (".hermes/skills/research/arxiv/SKILL.md", "---\nname: arxiv\ndescription: Search arXiv\n---\nSeeded."),
+ (".hermes/skills/mine/release-notes/SKILL.md", "---\nname: release-notes\ndescription: Write release notes\n---\nKeep it short."),
+ (".hermes/skills/.hub/x/SKILL.md", "---\nname: hub\ndescription: x\n---\nx"),
+ (".hermes/profiles/coder/SOUL.md", "You write code."),
+ (".hermes/profiles/coder/memories/MEMORY.md", "Uses cargo via heavy."),
+ ]);
+ assert_eq!(b.source.kind, HERMES);
+ assert_eq!(b.bots.len(), 2);
+ let home = b.bots.iter().find(|x| x.name == "Hermes").unwrap();
+ assert_eq!(home.soul, "You are Hermes.");
+ assert_eq!(home.memories, vec!["Project kwant is Rust.", "Deploys go through Ada,\nnever directly.", "About the person: Oleks likes short answers."]);
+ assert_eq!(home.skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), vec!["release-notes"]);
+ let coder = b.bots.iter().find(|x| x.name == "coder").unwrap();
+ assert_eq!(coder.title, "Hermes Agent profile");
+ assert_eq!(coder.memories, vec!["Uses cargo via heavy."]);
+ assert!(b.omitted.iter().any(|o| o.starts_with("1 skill that Hermes installs itself")));
+ no_key(&b);
+}
+
+#[test]
+fn hermes_memory_entries() {
+ assert_eq!(hermes_entries("a\n§\n\n§\nb\nc"), vec!["a", "b\nc"]);
+ assert_eq!(bundled_skills("arxiv:1\nplain\n\n"), ["arxiv", "plain"].iter().map(|s| s.to_string()).collect());
+}
+
+// ── Codex ─────────────────────────────────────────────────────────────────
+
+#[test]
+fn codex_home() {
+ let b = import(&[
+ (".codex/AGENTS.md", "Always run the tests."),
+ (".codex/config.toml", &format!("model = \"gpt-5\"\napi_key = \"{KEY}\"")),
+ (".codex/auth.json", &format!("{{\"OPENAI_API_KEY\": \"{KEY}\"}}")),
+ (".codex/skills/review/SKILL.md", "---\nname: review\ndescription: Review a diff\n---\nLook for bugs."),
+ ]);
+ assert_eq!(b.source.kind, CODEX);
+ assert_eq!(b.bots.len(), 1);
+ assert_eq!(b.bots[0].name, "Codex");
+ assert_eq!(b.bots[0].persona_prompt, "Always run the tests.");
+ assert_eq!(b.bots[0].skills[0].name, "review");
+ no_key(&b);
+}
+
+#[test]
+fn codex_override_wins_when_it_has_text() {
+ assert_eq!(codex_instructions(Some("Override."), Some("Base.")), "Override.");
+ assert_eq!(codex_instructions(Some(" \n"), Some("Base.")), "Base.");
+ let b = import(&[("codex/AGENTS.override.md", "Override."), ("codex/AGENTS.md", "Base.")]);
+ assert_eq!(b.bots[0].persona_prompt, "Override.");
+}
+
+#[test]
+fn lone_agents_md_is_one_codex_bot() {
+ let b = parse_file(b"# Repo rules\nUse cargo through bin/heavy.", Some("AGENTS.md")).unwrap();
+ assert_eq!(b.source.kind, CODEX);
+ assert_eq!(b.bots[0].persona_prompt, "# Repo rules\nUse cargo through bin/heavy.");
+ let b = parse_file(b"---\nname: CTO\ntitle: Chief Technology Officer\nreportsTo: ceo\n---\nOwn the stack.", Some("agents/cto/AGENTS.md")).unwrap();
+ assert_eq!(b.source.kind, PAPERCLIP);
+ assert_eq!((b.bots[0].name.as_str(), b.bots[0].title.as_str()), ("CTO", "Chief Technology Officer"));
+}
+
+#[test]
+fn a_repos_agents_md_is_not_a_bot() {
+ let b = import(&[
+ ("AGENTS.md", "Notes for coding agents working in this repo."),
+ ("skills/seo-audit/SKILL.md", "---\nname: seo-audit\ndescription: Audit a site\n---\nSteps."),
+ ("skills/copywriting/SKILL.md", "---\nname: copywriting\ndescription: Write copy\n---\nSteps."),
+ ]);
+ assert!(b.bots.is_empty());
+ assert_eq!(b.skills.len(), 2);
+}
+
+// ── Paperclip ─────────────────────────────────────────────────────────────
+
+fn paperclip_company() -> Vec<(&'static str, String)> {
+ vec![
+ ("acme/COMPANY.md", "---\nname: Acme\ndescription: We ship small tools.\nschema: agentcompanies/v1\ngoals:\n - Reach 1000 users\n - Keep costs low\n---\nAbout Acme.".into()),
+ ("acme/agents/ceo/AGENTS.md", "---\nname: CEO\ntitle: Chief Executive Officer\nreportsTo: null\nskills:\n - review\n---\nRun the company.".into()),
+ ("acme/agents/cto/AGENTS.md", "---\nname: CTO\ntitle: Chief Technology Officer\nreportsTo: ceo\nskills:\n - ../../skills/missing/SKILL.md\n---\nOwn the stack.".into()),
+ ("acme/skills/review/SKILL.md", "---\nname: review\ndescription: Review work\n---\nCheck it.".into()),
+ ("acme/skills/shared-notes/SKILL.md", "---\nname: shared-notes\ndescription: Keep notes\n---\nWrite them down.".into()),
+ ("acme/tasks/monday-review/TASK.md", "---\nname: Monday Review\nassignee: ceo\nrecurring: true\n---\nReview last week.".into()),
+ ("acme/tasks/kickoff/TASK.md", "---\nname: Kickoff\nassignee: cto\n---\nStart.".into()),
+ ("acme/projects/q2/PROJECT.md", "---\nname: Q2\n---\nLaunch.".into()),
+ (
+ "acme/.paperclip.yaml",
+ format!("routines:\n monday-review:\n triggers:\n - kind: schedule\n cronExpression: \"0 9 * * 1\"\n timezone: America/Chicago\nagents:\n ceo:\n adapter:\n env:\n ANTHROPIC_API_KEY: {KEY}\n"),
+ ),
+ ]
+}
+
+#[test]
+fn paperclip_company_becomes_a_team() {
+ let files = paperclip_company();
+ let refs: Vec<(&str, &str)> = files.iter().map(|(p, t)| (*p, t.as_str())).collect();
+ let b = import(&refs);
+ assert_eq!(b.source.kind, PAPERCLIP);
+ assert_eq!(b.bots.len(), 2);
+ let ceo = b.bots.iter().find(|x| x.ref_ == "ceo").unwrap();
+ assert_eq!(ceo.title, "Chief Executive Officer");
+ assert_eq!(ceo.persona_prompt, "Run the company.");
+ assert_eq!(ceo.skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), vec!["review"]);
+ assert_eq!(ceo.routines.len(), 1);
+ assert_eq!(ceo.routines[0].name, "Monday Review");
+ assert_eq!(ceo.routines[0].schedule_text.as_deref(), Some("0 9 * * 1 (America/Chicago)"));
+ assert!(read_schedule(&ceo.routines[0]).is_some(), "the cron and zone are read");
+ assert_eq!(b.skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), vec!["shared-notes"]);
+ let team = &b.teams[0];
+ assert_eq!(team.name, "Acme");
+ assert_eq!(team.lead.as_deref(), Some("ceo"));
+ assert_eq!(team.members, vec!["cto"]);
+ let instructions = team.instructions.as_deref().unwrap();
+ assert!(instructions.starts_with("We ship small tools."));
+ assert!(instructions.contains("Company goals:\n- Reach 1000 users\n- Keep costs low"));
+ assert!(b.omitted.iter().any(|o| o == "1 project weren't imported" || o.starts_with("1 project")));
+ assert!(b.omitted.iter().any(|o| o.starts_with("1 task that aren't recurring")));
+ no_key(&b);
+ let checked = normalize(b, &[]);
+ assert!(checked.problems.is_empty(), "{:?}", checked.problems);
+}
+
+#[test]
+fn paperclip_team_manager_is_the_lead() {
+ let b = import(&[
+ ("eng/TEAM.md", "---\nname: Engineering\ndescription: Platform team\nmanager: ../cto/AGENTS.md\n---\n"),
+ ("eng/agents/cto/AGENTS.md", "---\nname: CTO\nreportsTo: ceo\n---\nLead."),
+ ("eng/agents/dev/AGENTS.md", "---\nname: Dev\nreportsTo: null\n---\nBuild."),
+ ]);
+ assert_eq!(b.teams[0].name, "Engineering");
+ assert_eq!(b.teams[0].lead.as_deref(), Some("cto"));
+ assert_eq!(b.teams[0].members, vec!["dev"]);
+}
+
+// ── ai-employees ──────────────────────────────────────────────────────────
+
+const EMPLOYEE: &str = r#"{
+ "schema": "ai-employee/1",
+ "slug": "seo-employee",
+ "name": "SEO/AEO Employee",
+ "role": "Search, content and answer visibility",
+ "license": "MIT",
+ "connections": [
+ {"capability": "search.performance.read", "providers": ["openseo", "search-console-api"], "required": false},
+ {"capability": "cms.write", "providers": []}
+ ],
+ "routines": [
+ {"id": "seo-standup", "days": "mon-fri", "fire": "07:15", "window_start": "07:00", "window_end": "11:30"},
+ {"id": "seo-index-sweep", "days": "tue", "fire": "11:00"},
+ {"id": "seo-intake-and-map", "days": "first-weekday", "fire": "14:30"}
+ ]
+}"#;
+
+#[test]
+fn ai_employee_kit() {
+ let b = import(&[
+ ("ai-employees/employees/seo-employee/employee.json", EMPLOYEE),
+ ("ai-employees/employees/seo-employee/AGENTS.md", "# SEO/AEO Employee\nPaste this into the Instructions field."),
+ ("ai-employees/employees/seo-employee/routines/seo-standup/SKILL.md", "---\nname: seo-standup\ndescription: Morning standup for the SEO desk\n---\nLong steps…"),
+ ("ai-employees/employees/seo-employee/SCHEDULE.md", "| routine | days | fire |\n|---|---|---|\n| `ignored` | `mon` | 01:00 |"),
+ ("ai-employees/README.md", "Kits"),
+ ]);
+ assert_eq!(b.source.kind, AI_EMPLOYEES);
+ let bot = &b.bots[0];
+ assert_eq!(bot.name, "SEO/AEO Employee");
+ assert_eq!(bot.ref_, "seo-employee");
+ assert_eq!(bot.title, "Search, content and answer visibility");
+ assert!(bot.persona_prompt.contains("Paste this into the Instructions field."));
+ assert_eq!(bot.tool_hints, vec!["search.performance.read (openseo, search-console-api)", "cms.write"]);
+ let names: Vec<&str> = bot.routines.iter().map(|r| r.name.as_str()).collect();
+ assert_eq!(names, vec!["seo-standup", "seo-index-sweep", "seo-intake-and-map"]);
+ assert_eq!(bot.routines[0].schedule_text.as_deref(), Some("15 7 * * 1-5"));
+ assert!(bot.routines[0].instructions.starts_with("Morning standup for the SEO desk"));
+ assert!(bot.routines[0].instructions.contains("routines/seo-standup/SKILL.md"));
+ assert_eq!(bot.routines[1].schedule_text.as_deref(), Some("0 11 * * 2"));
+ assert!(read_schedule(&bot.routines[2]).is_none(), "first-weekday has no cron; it gets the placeholder");
+ assert!(b.omitted.iter().any(|o| o.contains("set in UTC")));
+ let checked = normalize(b, &[]);
+ assert!(checked.problems.is_empty(), "{:?}", checked.problems);
+}
+
+#[test]
+fn ai_employee_schedule_rows() {
+ assert_eq!(ai_employee_schedule("`mon-fri`", "08:00"), "0 8 * * 1-5");
+ assert_eq!(ai_employee_schedule("sun", "23:59"), "59 23 * * 0");
+ assert_eq!(ai_employee_schedule("off", "09:00"), "off 09:00");
+ assert_eq!(ai_employee_schedule("mon", "25:00"), "mon 25:00");
+ let rows = schedule_rows("| `seo-standup` | `mon-fri` | 07:15 | 07:00 |\n|---|---|---|\n| routine | days | fire |");
+ assert_eq!(rows, vec![("seo-standup".to_string(), "mon-fri".to_string(), "07:15".to_string())]);
+}
+
+// ── GitHub repository archives ────────────────────────────────────────────
+
+#[test]
+fn repo_zip_strips_the_top_folder_and_reads_the_licence_and_commit() {
+ let bytes = zip_of(
+ &[
+ ("marketingskills-HEAD/LICENSE", "MIT License\n\nCopyright (c) 2025 Corey Haines"),
+ ("marketingskills-HEAD/AGENTS.md", "Notes for agents."),
+ ("marketingskills-HEAD/README.md", "Readme"),
+ ("marketingskills-HEAD/skills/seo-audit/SKILL.md", "---\nname: seo-audit\ndescription: Audit a site\n---\nSteps."),
+ ("marketingskills-HEAD/skills/seo-audit/references/notes.md", "Not a skill"),
+ ("marketingskills-HEAD/skills/copywriting/SKILL.md", "---\nname: copywriting\ndescription: Write copy\n---\nSteps."),
+ ("marketingskills-HEAD/.github/workflows/ci.json", "{}"),
+ ("marketingskills-HEAD/tools/bundle.zip", "PK\u{3}\u{4}not really"),
+ ("marketingskills-HEAD/package.json", "{\"name\": \"x\"}"),
+ ],
+ Some("4e1f0c2d9a7b6e5f4e1f0c2d9a7b6e5f4e1f0c2d"),
+ );
+ let (b, info) = parse_repo_zip(&bytes, None).unwrap();
+ assert!(b.bots.is_empty());
+ assert_eq!(b.skills.len(), 2);
+ assert_eq!(info.commit.as_deref(), Some("4e1f0c2d9a7b6e5f4e1f0c2d9a7b6e5f4e1f0c2d"));
+ let (path, text) = info.licence.unwrap();
+ assert_eq!(path, "LICENSE");
+ assert!(text.starts_with("MIT License"));
+ // One folder of the repo.
+ let (b, _) = parse_repo_zip(&bytes, Some("skills/copywriting")).unwrap();
+ assert_eq!(b.skills.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), vec!["copywriting"]);
+ assert!(matches!(parse_repo_zip(&bytes, Some("nope")), Err(ImportError::Unsupported(_))));
+}
+
+#[test]
+fn repo_zip_entry_cap() {
+ let names: Vec<String> = (0..crate::import::archive::MAX_REPO_ZIP_ENTRIES + 1).map(|i| format!("r-HEAD/src/f{i}.rs")).collect();
+ let files: Vec<(&str, &str)> = names.iter().map(|n| (n.as_str(), "")).collect();
+ assert!(matches!(parse_repo_zip(&zip_of(&files, None), None), Err(ImportError::TooLarge(_))));
+ // A repo of mostly code under the cap reads fine: code isn't inflated or counted.
+ let mut names: Vec<String> = (0..1500).map(|i| format!("r-HEAD/src/f{i}.md")).collect();
+ names.push("r-HEAD/skills/a/SKILL.md".into());
+ let files: Vec<(&str, &str)> = names.iter().map(|n| (n.as_str(), if n.ends_with("SKILL.md") { "---\nname: a\ndescription: b\n---\nc" } else { "x" })).collect();
+ let (b, _) = parse_repo_zip(&zip_of(&files, None), None).unwrap();
+ assert_eq!(b.skills.len(), 1);
+}
+
+#[test]
+fn uploads_still_refuse_nested_archives() {
+ let bytes = zip_of(&[("a/SKILL.md", "---\nname: a\ndescription: b\n---\nc"), ("a/inner.zip", "PK")], None);
+ assert!(matches!(parse_file(&bytes, Some("x.zip")), Err(ImportError::Invalid(_))));
+}
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 28fa6a07..b7f4c24f 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -426,6 +426,10 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "facts", ..] => true,
["", "api", "skills", ..] => *method != Method::GET && *method != Method::HEAD,
["", "api", "bot-actions" | "imports", _, "undo"] => *method == Method::POST,
+ // Import from this computer reads the person's home folder (other apps' bots, memories and
+ // skills), and a GitHub link makes the server fetch from the internet: both the person's
+ // (0.8.0 A2/A3), the list included
+ ["", "api", "import", "local" | "github", ..] => true,
_ => false,
}
}
@@ -1071,6 +1075,10 @@ mod tests {
assert!(person_only(&del, "/api/teams/t1/"));
assert!(person_only(&post, "/api/bot-actions/b1/undo"));
assert!(person_only(&post, "/api/imports/i1/undo"));
+ assert!(person_only(&get, "/api/import/local"));
+ assert!(person_only(&post, "/api/import/local/preview"));
+ assert!(person_only(&post, "/api/import/github/preview"));
+ assert!(!person_only(&get, "/api/import/prompts"));
assert!(!person_only(&put, "/api/kwants/k1"));
assert!(!person_only(&get, "/api/teams/t1"));
assert!(!person_only(&post, "/api/bot-actions/b1/confirm"));
diff --git a/src/server/import_routes.rs b/src/server/import_routes.rs
index 50e71ebc..6956cab1 100644
--- a/src/server/import_routes.rs
+++ b/src/server/import_routes.rs
@@ -7,6 +7,10 @@
//! - `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, ….
+//! - `GET /api/import/local`, `POST /api/import/local/preview?space=`: bots and skills other agent
+//! apps keep in this computer's home folder (the app on this computer only; see `import::local`).
+//! - `POST /api/import/github/preview?space=`: `{ "url": … }`, a public repository on github.com,
+//! fetched from codeload only (see `import::github`).
use super::spaces::Scope;
use super::AppState;
@@ -15,7 +19,7 @@ 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},
+ extract::{ConnectInfo, Path, Query, State},
http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response},
Json,
@@ -24,6 +28,7 @@ use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashSet;
+use std::net::SocketAddr;
/// An apply body: a bundle with up to 50 bots of 2 × 16k characters, plus skills.
const MAX_APPLY_BYTES: usize = 8 * 1024 * 1024;
@@ -108,13 +113,118 @@ pub async fn preview(State(state): State<AppState>, Scope(space): Scope, Query(q
Ok(b) => b,
Err(e) => return import_error(e),
};
- let names = match names_in(&state, &space).await {
- Ok(n) => n,
- Err(r) => return r,
- };
+ match checked_preview(&state, &space, bundle).await {
+ Ok(p) => Json(p).into_response(),
+ Err(r) => r,
+ }
+}
+
+/// The checks every preview runs against the space's names.
+#[allow(clippy::result_large_err)]
+async fn checked_preview(state: &AppState, space: &SpaceId, bundle: Bundle) -> Result<Preview, Response> {
+ let names = names_in(state, space).await?;
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()
+ Ok(Preview { checked, can_apply })
+}
+
+const NOT_LOCAL: &str = "Only the kwant app on this computer can look for bots here.";
+
+fn is_local(headers: &HeaderMap, peer: &Option<ConnectInfo<SocketAddr>>) -> bool {
+ super::auth::is_local(headers, peer.as_ref().map(|c| c.0.ip()))
+}
+
+/// `GET /api/import/local`: what other agent apps keep on this computer, names and counts only.
+/// Anywhere but the app on this computer, `available: false` and nothing listed.
+pub async fn local_list(peer: Option<ConnectInfo<SocketAddr>>, headers: HeaderMap) -> Response {
+ if !is_local(&headers, &peer) {
+ return Json(json!({ "available": false, "reason": NOT_LOCAL, "sources": [] })).into_response();
+ }
+ let Some((home, codex)) = import::local::home() else {
+ return Json(json!({ "available": false, "reason": "kwant couldn't find your home folder.", "sources": [] })).into_response();
+ };
+ let found = tokio::task::spawn_blocking(move || import::local::scan(&home, codex.as_deref())).await.unwrap_or_default();
+ Json(json!({ "available": true, "sources": found })).into_response()
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct LocalPick {
+ sources: Vec<String>,
+}
+
+/// `POST /api/import/local/preview`: `{ "sources": [ids] }` from the list, read into one preview.
+pub async fn local_preview(State(state): State<AppState>, Scope(space): Scope, peer: Option<ConnectInfo<SocketAddr>>, headers: HeaderMap, body: Body) -> Response {
+ if !is_local(&headers, &peer) {
+ return error(StatusCode::FORBIDDEN, "local_only", NOT_LOCAL);
+ }
+ let bytes = match read_body(&headers, body, 64 * 1024, "A list of sources").await {
+ Ok(b) => b,
+ Err(r) => return r,
+ };
+ let bad = |m: &str| error(StatusCode::BAD_REQUEST, "bad_request", m);
+ let Ok(pick) = serde_json::from_slice::<LocalPick>(&bytes) else { return bad("Send {\"sources\": [ids]} from the list.") };
+ if pick.sources.is_empty() || pick.sources.len() > import::local::MAX_PICKED {
+ return bad("Tick between 1 and 10 sources.");
+ }
+ if pick.sources.iter().collect::<HashSet<_>>().len() != pick.sources.len() {
+ return bad("A source is ticked twice.");
+ }
+ let Some((home, codex)) = import::local::home() else { return error(StatusCode::NOT_FOUND, "not_found", "kwant couldn't find your home folder.") };
+ let read = tokio::task::spawn_blocking(move || import::local::read(&home, codex.as_deref(), &pick.sources)).await;
+ let bundle = match read {
+ Ok(Ok(b)) => b,
+ Ok(Err(import::local::ReadError::NotFound(id))) => return error(StatusCode::NOT_FOUND, "not_found", format!("{id} isn't on this computer any more. Refresh the list.")),
+ Ok(Err(import::local::ReadError::Import(e))) => return import_error(e),
+ Err(e) => return internal(e),
+ };
+ match checked_preview(&state, &space, bundle).await {
+ Ok(p) => Json(p).into_response(),
+ Err(r) => r,
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct GithubLink {
+ url: String,
+}
+
+#[derive(Serialize)]
+struct GithubPreview {
+ #[serde(flatten)]
+ preview: Preview,
+ github: import::github::GithubInfo,
+}
+
+/// `POST /api/import/github/preview`: `{ "url": … }`, a public repository on github.com.
+pub async fn github_preview(State(state): State<AppState>, Scope(space): Scope, headers: HeaderMap, body: Body) -> Response {
+ let bytes = match read_body(&headers, body, 16 * 1024, "A link").await {
+ Ok(b) => b,
+ Err(r) => return r,
+ };
+ let Ok(link) = serde_json::from_slice::<GithubLink>(&bytes) else {
+ return error(StatusCode::BAD_REQUEST, "bad_request", "Send {\"url\": \"https://github.com/…\"}.");
+ };
+ use import::github::{self, GithubError};
+ let (bundle, info) = match github::preview(github::CODELOAD, &link.url).await {
+ Ok(r) => r,
+ Err(GithubError::NotGithub(m)) => return error(StatusCode::UNPROCESSABLE_ENTITY, "not_github", m),
+ Err(GithubError::Redirect) => {
+ return error(StatusCode::UNPROCESSABLE_ENTITY, "redirect", "GitHub answered with a redirect, which kwant doesn't follow. Check the link (a renamed repository needs its new name).")
+ }
+ Err(GithubError::NotFound) => return error(StatusCode::NOT_FOUND, "not_found", "There's no public repository or branch at this link. Private repositories can't be imported from a link."),
+ Err(GithubError::FetchFailed(m)) => return error(StatusCode::BAD_GATEWAY, "fetch_failed", m),
+ Err(GithubError::Import(e)) => return import_error(e),
+ };
+ let mut preview = match checked_preview(&state, &space, bundle).await {
+ Ok(p) => p,
+ Err(r) => return r,
+ };
+ if info.licence.is_none() {
+ preview.checked.warnings.push(import::Notice { bot: None, message: github::NO_LICENCE.into() });
+ }
+ Json(GithubPreview { preview, github: info }).into_response()
}
#[derive(Deserialize)]
diff --git a/src/server/mod.rs b/src/server/mod.rs
index fd937fb9..9c4a70d7 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -259,6 +259,9 @@ pub fn create_router(state: AppState) -> Router {
.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/import/local", get(import_routes::local_list))
+ .route("/api/import/local/preview", post(import_routes::local_preview))
+ .route("/api/import/github/preview", post(import_routes::github_preview))
.route("/api/imports", get(import_routes::list))
.route("/api/imports/:id", get(import_routes::get))
.route("/api/imports/:id/undo", post(import_routes::undo))
diff --git a/tests/import_test.rs b/tests/import_test.rs
index 7b63ca0c..ba2c7517 100644
--- a/tests/import_test.rs
+++ b/tests/import_test.rs
@@ -923,3 +923,95 @@ async fn covers_and_avoids_survive_create_export_and_import() {
let scope = e.state.db.get_scope(copy).await.unwrap();
assert_eq!((scope.covers.len(), scope.avoids.clone()), (20, vec!["legal advice".to_string()]));
}
+
+// ── 0.8.0 A2/A3: from this computer and from a GitHub link ──────────────────
+
+/// A bot's turn token in #general of the default space.
+async fn bot_token(e: &Env) -> String {
+ use kwnt::server::{
+ continuity::{SelfScope, TurnOrigin},
+ mcp_runtime,
+ };
+ let space = SpaceId::default_space();
+ let new = NewKwant { name: "Ana".into(), title: "Reporter".into(), persona_prompt: String::new(), soul: String::new(), avatar_sprite: "s".into(), driver_type: "cli".into(), preferred_model: "codex".into() };
+ let bot = e.state.db.create_kwant(&space, &new).await.unwrap();
+ let general = e.state.db.list_channels(&space).await.unwrap().into_iter().find(|c| c.name == "general").unwrap();
+ let scope = SelfScope {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ origin: Some(TurnOrigin { channel_id: Some(general.id.clone()), ..Default::default() }),
+ turn_id: Some("t-import".into()),
+ ..Default::default()
+ };
+ mcp_runtime::prepare_turn_with_self(&e.state, &bot, Some("t-import".into()), None, Some(scope)).await.unwrap().1
+}
+
+async fn call_as(e: &Env, method: &str, uri: &str, bearer: &str, extra: &[(&str, &str)], body: Option<Value>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(uri).header("authorization", format!("Bearer {bearer}"));
+ for (k, v) in extra {
+ req = req.header(*k, *v);
+ }
+ let req = match body {
+ Some(b) => req.header("content-type", "application/json").body(Body::from(b.to_string())),
+ None => req.body(Body::empty()),
+ }
+ .unwrap();
+ let resp = e.app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+#[tokio::test]
+async fn bots_cannot_look_on_this_computer_or_fetch_github() {
+ let e = setup().await;
+ let token = bot_token(&e).await;
+ let space = dflt();
+ for (method, uri, body) in [
+ ("GET", "/api/import/local".to_string(), None),
+ ("POST", format!("/api/import/local/preview?space={space}"), Some(json!({"sources": ["codex"]}))),
+ ("POST", format!("/api/import/github/preview?space={space}"), Some(json!({"url": "https://github.com/o/r"}))),
+ ] {
+ let (s, v) = call_as(&e, method, &uri, &token, &[], body).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{uri}: {v}");
+ assert_eq!(v["code"], "person_only", "{uri}");
+ }
+}
+
+#[tokio::test]
+async fn this_computer_is_only_for_the_app_on_it() {
+ let e = setup().await;
+ let token = e.state.api_token.reveal().to_string();
+ let space = dflt();
+ // Through a proxy (or from another machine): nothing is listed and nothing is read
+ let remote = [("x-forwarded-for", "203.0.113.9")];
+ let (s, v) = call_as(&e, "GET", "/api/import/local", &token, &remote, None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(v, json!({"available": false, "reason": "Only the kwant app on this computer can look for bots here.", "sources": []}));
+ let (s, v) = call_as(&e, "POST", &format!("/api/import/local/preview?space={space}"), &token, &remote, Some(json!({"sources": ["codex"]}))).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::FORBIDDEN, Some("local_only")));
+
+ // On this computer: bad picks are refused before anything is read
+ let uri = format!("/api/import/local/preview?space={space}");
+ for body in [json!({"sources": []}), json!({"sources": ["codex", "codex"]}), json!({"sources": (0..11).map(|i| format!("s{i}")).collect::<Vec<_>>()}), json!({"paths": ["/etc"]})] {
+ let (s, v) = call_as(&e, "POST", &uri, &token, &[], Some(body.clone())).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::BAD_REQUEST, Some("bad_request")), "{body}");
+ }
+ let (s, v) = call_as(&e, "POST", &uri, &token, &[], Some(json!({"sources": ["../../etc"]}))).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::NOT_FOUND, Some("not_found")), "{v}");
+ let (s, v) = call_as(&e, "GET", "/api/import/local", &token, &[], None).await;
+ assert_eq!((s, v["available"].as_bool()), (StatusCode::OK, Some(true)), "{v}");
+}
+
+#[tokio::test]
+async fn github_links_are_checked_before_any_fetch() {
+ let e = setup().await;
+ let token = e.state.api_token.reveal().to_string();
+ let uri = format!("/api/import/github/preview?space={}", dflt());
+ for url in ["https://gitlab.com/o/r", "http://github.com/o/r", "https://github.com:444/o/r", "https://[email protected]/o/r", "https://raw.githubusercontent.com/o/r/main/SKILL.md"] {
+ let (s, v) = call_as(&e, "POST", &uri, &token, &[], Some(json!({ "url": url }))).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::UNPROCESSABLE_ENTITY, Some("not_github")), "{url}: {v}");
+ }
+ let (s, v) = call_as(&e, "POST", &uri, &token, &[], Some(json!({ "link": "https://github.com/o/r" }))).await;
+ assert_eq!((s, v["code"].as_str()), (StatusCode::BAD_REQUEST, Some("bad_request")));
+}