instinct-cli 0.3.10

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! `instinct serve`: the MCP tools over HTTP on 127.0.0.1, for local use (prototype).
//!
//! The HTTP framing (parse, admit, respond) is Helix-authored in `serve_http.hlx`. This file owns what Helix has no
//! construct for: the listener, the threads, the socket deadlines and the key file. Every JSON-RPC request goes to
//! `mcp_message`, the same function the stdio server runs, so the tools are identical on both transports.
use super::serve_http as http;
use super::{mcp_message, parse_json, receipt_stage, recall_index, Args, Json};
use std::io::{ErrorKind, Read, Write};
use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Open connections served at once; one more is answered 503 and closed.
const MAX_CONNECTIONS: usize = 8;
/// A client has this long, in total, to deliver its head and body.
const DEADLINE: Duration = Duration::from_secs(15);

struct Shared {
    path: PathBuf,
    key: String,
    origins: Vec<String>,
    allow_write: bool,
    cache: Mutex<Option<recall_index::Index>>,
    live: AtomicUsize,
}

fn data_dir(store: &Path) -> PathBuf {
    store.parent().filter(|d| !d.as_os_str().is_empty()).map_or_else(|| PathBuf::from("."), Path::to_path_buf)
}

fn random_hex() -> Result<String, String> {
    let mut bytes = [0u8; 32];
    #[cfg(unix)]
    std::fs::File::open("/dev/urandom").and_then(|mut f| f.read_exact(&mut bytes)).map_err(|e| format!("cannot read /dev/urandom: {e}"))?;
    #[cfg(not(unix))]
    {
        // std only: RandomState is seeded by the operating system (128 bits); each word mixes in a counter and the clock.
        use std::hash::{BuildHasher, Hasher};
        for (i, chunk) in bytes.chunks_mut(8).enumerate() {
            let mut h = std::collections::hash_map::RandomState::new().build_hasher();
            h.write_usize(i);
            h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()));
            chunk.copy_from_slice(&h.finish().to_le_bytes());
        }
    }
    Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}

fn init_key(dir: &Path) -> Result<String, String> {
    std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
    let file = dir.join("serve.key");
    let key = random_hex()?;
    let mut f = super::journal::private_options()
        .write(true)
        .create_new(true)
        .open(&file)
        .map_err(|e| format!("cannot create {} ({e}); delete the file to rotate the key", file.display()))?;
    writeln!(f, "{key}").map_err(|e| format!("cannot write {}: {e}", file.display()))?;
    Ok(key)
}

fn load_key(dir: &Path) -> Result<String, String> {
    let file = dir.join("serve.key");
    let text = std::fs::read_to_string(&file)
        .map_err(|_| format!("no key at {}; run `instinct serve --init-key` first (the server will not start without one)", file.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(&file).map_err(|e| e.to_string())?.permissions().mode();
        if mode & 0o077 != 0 {
            return Err(format!("{} is readable by others (mode {:o}); run chmod 600 on it", file.display(), mode & 0o777));
        }
    }
    let key = text.trim().to_string();
    if key.len() < 32 {
        return Err(format!("{} holds a key shorter than 32 characters", file.display()));
    }
    Ok(key)
}

/// `<data dir>/serve.origins`: one https origin per line, `#` comments. Missing file = no browser origin is allowed.
fn load_origins(dir: &Path) -> Result<Vec<String>, String> {
    let Ok(text) = std::fs::read_to_string(dir.join("serve.origins")) else { return Ok(Vec::new()) };
    let mut list = Vec::new();
    for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
        if !line.starts_with("https://") || line.ends_with('/') || line[8..].contains(['/', '?', '#', ' ']) {
            return Err(format!("serve.origins: `{line}` is not a bare https origin (https://host[:port])"));
        }
        list.push(line.to_string());
    }
    Ok(list)
}

pub fn run(a: &Args, path: &PathBuf) -> Result<(), String> {
    let dir = data_dir(path);
    if a.flag("init-key") {
        let key = init_key(&dir)?;
        println!("{key}");
        eprintln!("instinct serve: key written to {} (mode 0600). This is the only time it is printed.", dir.join("serve.key").display());
        return Ok(());
    }
    if let Some(host) = a.opt("host") {
        if host != "127.0.0.1" {
            return Err(format!("instinct serve binds 127.0.0.1 only in this version (got {host}). Public exposure needs a separate reviewed design"));
        }
    }
    let port = match a.opt("port") {
        None => 8787,
        Some(p) => p.parse::<u16>().map_err(|_| format!("--port needs a number from 0 to 65535 (got {p})"))?,
    };
    let key = load_key(&dir)?;
    let origins = load_origins(&dir)?;
    // The address is built from the constant, never from user text.
    let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))).map_err(|e| format!("cannot bind 127.0.0.1:{port}: {e}"))?;
    let bound = listener.local_addr().map_err(|e| e.to_string())?;
    if !bound.ip().is_loopback() {
        return Err(format!("refusing to serve on {bound}: not a loopback address"));
    }
    let allow_write = a.flag("allow-write");
    let shared = Arc::new(Shared { path: path.clone(), key, origins, allow_write, cache: Mutex::new(None), live: AtomicUsize::new(0) });
    println!("instinct serve: listening on http://{bound}/mcp ({})", if allow_write { "writes allowed" } else { "read-only" });
    let _ = std::io::stdout().flush();
    for conn in listener.incoming() {
        let Ok(stream) = conn else { continue };
        let sh = Arc::clone(&shared);
        if sh.live.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS {
            sh.live.fetch_sub(1, Ordering::SeqCst);
            let mut s = stream;
            let _ = s.write_all(&http::refusal(503));
            continue;
        }
        std::thread::spawn(move || {
            serve_one(stream, &sh);
            sh.live.fetch_sub(1, Ordering::SeqCst);
        });
    }
    Ok(())
}

fn fill(s: &mut TcpStream, buf: &mut Vec<u8>, started: Instant) -> Result<(), u16> {
    let left = DEADLINE.checked_sub(started.elapsed()).filter(|d| !d.is_zero()).ok_or(408u16)?;
    s.set_read_timeout(Some(left)).map_err(|_| 500u16)?;
    let mut chunk = [0u8; 4096];
    match s.read(&mut chunk) {
        Ok(0) => Err(400),
        Ok(n) => {
            buf.extend_from_slice(&chunk[..n]);
            Ok(())
        }
        Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => Err(408),
        Err(_) => Err(400),
    }
}

/// Read one request, answer it, close. The stored recall delivery receipt is staged after the reply is sent.
fn serve_one(mut s: TcpStream, sh: &Shared) {
    let _ = s.set_write_timeout(Some(Duration::from_secs(10)));
    let (bytes, delivery) = match exchange(&mut s, sh) {
        Ok(done) => done,
        Err(status) => (http::refusal(status), None),
    };
    let _ = s.write_all(&bytes);
    let _ = s.flush();
    if let Some((meta, text)) = delivery {
        if let Err(e) = receipt_stage(meta, "delivered", &text) {
            eprintln!("instinct telemetry: {e}");
        }
    }
}

fn exchange(s: &mut TcpStream, sh: &Shared) -> Result<(Vec<u8>, Option<(Json, String)>), u16> {
    let started = Instant::now();
    let mut buf = Vec::new();
    let end = loop {
        if let Some(end) = http::head_end(&buf) {
            break end;
        }
        if buf.len() > http::MAX_HEAD {
            return Err(431);
        }
        fill(s, &mut buf, started)?;
    };
    if end > http::MAX_HEAD {
        return Err(431);
    }
    let head = http::parse_head(&buf[..end])?;
    http::admit(&head, &sh.key, &sh.origins)?;
    let need = head.length.unwrap_or(0);
    while buf.len() < end + need {
        fill(s, &mut buf, started)?;
    }
    let body = std::str::from_utf8(&buf[end..end + need]).map_err(|_| 400u16)?;
    let msg = parse_json(body).map_err(|_| 400u16)?;
    // JSON-RPC batching was removed from the 2025-06-18 transport; only one message per POST.
    if !matches!(msg, Json::Obj(_)) {
        return Err(400);
    }
    // Notifications (no id) and responses (no method) are accepted and get no body.
    if msg.get("method").is_none() || msg.get("id").is_none() {
        return Ok((http::reply(202, ""), None));
    }
    let mut cache = sh.cache.lock().unwrap_or_else(|p| p.into_inner());
    let (reply, delivery) = mcp_message(&mut cache, &sh.path, body, sh.allow_write).ok_or(500u16)?;
    Ok((http::reply(200, &reply), delivery))
}