Skip to content

armgit / kanzo

Public Imported from GitHub
0

Self-hosted, sharable kanban for humans and agents. One 4.7 MB binary, 5 MB of RAM, 10 to 60 tokens per agent reply, starts in 3 ms, zero setup.

Let a joined computer's agents read the host's task images

emanuele-emc44ea6f1ab0c
diff --git a/src/mcp.rs b/src/mcp.rs
index d0fceed..2a4ca70 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -44,7 +44,8 @@ done and human tasks to the user.";
pub async fn serve(home: Home) -> Result<()> {
let cwd = std::env::current_dir().unwrap_or_default();
let repos = git_repos(&cwd);
- let ctx = Ctx { home, cwd: Some(cwd), repos, host: Default::default() };
+ let images = home.dir.join("images");
+ let ctx = Ctx { home, cwd: Some(cwd), repos, images, host: Default::default() };
let server = Kanzo { ctx: Arc::new(ctx), tool_router: Kanzo::tools() };
let service = server.serve(rmcp::transport::stdio()).await?;
service.waiting().await?;
@@ -55,7 +56,8 @@ pub async fn serve(home: Home) -> Result<()> {
/// checks (`web::protect`) guard it, including when it listens on the network, so
/// rmcp's localhost-only list is turned off here.
pub fn http_service(home: Home, shutdown: CancellationToken) -> StreamableHttpService<Kanzo, LocalSessionManager> {
- let ctx = Arc::new(Ctx { home, cwd: None, repos: Vec::new(), host: Default::default() });
+ let images = home.dir.join("images");
+ let ctx = Arc::new(Ctx { home, cwd: None, repos: Vec::new(), images, host: Default::default() });
let config = StreamableHttpServerConfig::default().disable_allowed_hosts().with_cancellation_token(shutdown);
// rmcp makes a server per session, and for some requests; the tool list is built once.
let tool_router = Kanzo::tools();
@@ -72,6 +74,9 @@ struct Ctx {
cwd: Option<PathBuf>,
/// GitHub repos (`owner/repo`) of the git remotes of `cwd`.
repos: Vec<String>,
+ /// Where the agent finds the images of tasks: on a computer that joined this board,
+ /// its own folder, which fetches them from here.
+ images: PathBuf,
/// The board this computer joined, while `kanzo mcp` uses it for the agent.
host: tokio::sync::Mutex<Option<share::Upstream>>,
}
@@ -293,6 +298,7 @@ impl Kanzo {
.filter(|r| !r.is_empty())
.map(String::from)
.collect(),
+ images: header(share::IMAGES_HEADER).map_or_else(|| self.ctx.images.clone(), PathBuf::from),
host: Default::default(),
}),
None => self.ctx.clone(),
@@ -554,7 +560,7 @@ impl ServerHandler for Kanzo {
{
let mut upstream = self.ctx.host.lock().await;
if upstream.as_ref().is_none_or(|u| u.host() != host) {
- *upstream = Some(share::Upstream::new(host, cwd, &self.ctx.repos));
+ *upstream = Some(share::Upstream::new(host, cwd, &self.ctx.repos, &self.ctx.images));
}
let client = context.peer.peer_info().and_then(|p| serde_json::to_value(&*p).ok());
let upstream = upstream.as_mut().expect("set above");
@@ -599,7 +605,7 @@ fn write_tags(out: &mut String, t: &Task) {
fn task_detail(ctx: &Ctx, store: &Store, t: &Task) -> store::Result<String> {
let comments = store.list_comments(t.id)?;
let images = store.list_images(t.id)?;
- let dir = ctx.home.dir.join("images");
+ let dir = &ctx.images;
let paths = |comment: Option<i64>| -> Vec<String> {
images.iter().filter(|i| i.comment_id == comment).map(|i| dir.join(&i.file).display().to_string()).collect()
};
diff --git a/src/share.rs b/src/share.rs
index 3905517..c0d79a0 100644
--- a/src/share.rs
+++ b/src/share.rs
@@ -7,7 +7,7 @@
use std::fmt::Write as _;
use std::io;
use std::net::{IpAddr, SocketAddr};
-use std::path::Path;
+use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::Duration;
@@ -33,6 +33,8 @@ pub const FILE: &str = "network";
/// project as it would on its own computer.
pub const FOLDER_HEADER: &str = "x-kanzo-folder";
pub const REPOS_HEADER: &str = "x-kanzo-repos";
+/// Where a guest's agent finds task images: its own folder, which fetches them from the host.
+pub const IMAGES_HEADER: &str = "x-kanzo-images";
/// Sent by a guest's board and `kanzo mcp`, so the host can list who's using it.
pub const COMPUTER_HEADER: &str = "x-kanzo-computer";
@@ -348,12 +350,13 @@ pub struct Upstream {
session: Option<String>,
folder: String,
repos: String,
+ images: PathBuf,
}
impl Upstream {
- pub fn new(host: String, folder: &Path, repos: &[String]) -> Self {
+ pub fn new(host: String, folder: &Path, repos: &[String], images: &Path) -> Self {
let folder = folder.display().to_string();
- Self { host, session: None, folder, repos: repos.join(",") }
+ Self { host, session: None, folder, repos: repos.join(","), images: images.to_path_buf() }
}
pub fn host(&self) -> &str {
@@ -397,17 +400,44 @@ impl Upstream {
let text =
result["content"].as_array().into_iter().flatten().filter_map(|c| c["text"].as_str()).collect::<Vec<_>>();
let text = text.join("\n");
+ self.fetch_images(&text).await;
if result["isError"] == true { Err(text) } else { Ok(text) }
}
+ /// Images live on the host. The host names them in this computer's images folder, and
+ /// this fetches the ones missing there; names are their content's hash, so a copy never goes stale.
+ async fn fetch_images(&self, text: &str) {
+ let folder = self.images.display().to_string();
+ for (at, _) in text.match_indices(&folder) {
+ let rest = text[at + folder.len()..].trim_start_matches(['/', '\\']);
+ let file: String = rest.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '.').collect();
+ let path = self.images.join(&file);
+ if !crate::store::valid_image_file(&file) || path.exists() {
+ continue;
+ }
+ let Ok(mut reply) = send(&self.host, "GET", &format!("/images/{file}"), &[], b"").await else { continue };
+ let mut bytes = Vec::new();
+ if reply.status == 200 && reply.body.read_to_end(&mut bytes).await.is_ok() {
+ // Under a temporary name first, so a half-written image never has the real one.
+ let partial = path.with_extension("part");
+ let saved = std::fs::create_dir_all(&self.images).and_then(|()| std::fs::write(&partial, &bytes));
+ if saved.is_ok() {
+ let _ = std::fs::rename(&partial, &path);
+ }
+ }
+ }
+ }
+
/// Sends one message: the status, and the messages the host answered with, as JSON
/// or as a stream of events.
async fn post(&mut self, line: &str) -> io::Result<(u16, Vec<Value>)> {
+ let images = self.images.display().to_string();
let mut headers = vec![
("content-type", "application/json"),
("accept", "application/json, text/event-stream"),
(FOLDER_HEADER, self.folder.as_str()),
(REPOS_HEADER, self.repos.as_str()),
+ (IMAGES_HEADER, images.as_str()),
(COMPUTER_HEADER, computer()),
];
if let Some(id) = &self.session {