instinct-cli 0.3.7

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
// generated by hxc 1.0.0-acgt-compiler from src/serve_http.hlx -- do not edit by hand

#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
    let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
    if !ok {
        eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
    }
    ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    c
}

// hlx:5
pub const MAX_BODY: usize = 1 << 20;
// hlx:6
pub const MAX_HEAD: usize = 16 * 1024;
// hlx:7
const VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];
// hlx:9
#[derive(Debug, Default)]
// hlx:10
pub struct Head {
    // hlx:11
    pub method: String,
    // hlx:12
    pub path: String,
    // hlx:13
    pub headers: Vec<(String, String)>,
    // hlx:14
    pub length: Option<usize>,
    // hlx:15
}
// hlx:18
pub fn head_end(buf: &[u8]) -> Option<usize> {
    // hlx:19
    buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4)
    // hlx:20
}
// hlx:23
pub fn parse_head(raw: &[u8]) -> Result<Head, u16> {
    // hlx:24
    let text = std::str::from_utf8(raw).map_err(|_| 400u16)?;
    // hlx:25
    let mut lines = text.trim_end_matches("\r\n").split("\r\n");
    // hlx:26
    let request = lines.next().unwrap_or("");
    // hlx:27
    let mut parts = request.split(' ');
    // hlx:28
    let (Some(method), Some(target), Some(version), None) =
        (parts.next(), parts.next(), parts.next(), parts.next())
    else {
        return Err(400);
    };
    // hlx:29
    if !version.starts_with("HTTP/1.") || method.is_empty() || !target.starts_with('/') {
        // hlx:30
        return Err(400);
        // hlx:31
    }
    // hlx:32
    let mut head = Head {
        method: method.to_string(),
        path: target.split('?').next().unwrap_or("").to_string(),
        ..Head::default()
    };
    // hlx:33
    for line in lines {
        // hlx:34
        if line.starts_with(' ') || line.starts_with('\t') {
            // hlx:35
            return Err(400);
            // hlx:36
        }
        // hlx:37
        let Some((name, value)) = line.split_once(':') else {
            return Err(400);
        };
        // hlx:38
        let name = name.to_ascii_lowercase();
        // hlx:39
        if name.is_empty() || name.contains(' ') {
            // hlx:40
            return Err(400);
            // hlx:41
        }
        // hlx:42
        if name == "transfer-encoding" {
            // hlx:43
            return Err(501);
            // hlx:44
        }
        // hlx:45
        if name == "content-length" {
            // hlx:46
            let n = value.trim().parse::<usize>().map_err(|_| 400u16)?;
            // hlx:47
            if head.length.is_some() {
                // hlx:48
                return Err(400);
                // hlx:49
            }
            // hlx:50
            head.length = Some(n);
            // hlx:51
        }
        // hlx:52
        head.headers.push((name, value.trim().to_string()));
        // hlx:53
    }
    // hlx:54
    Ok(head)
    // hlx:55
}
// hlx:57
pub fn header<'a>(head: &'a Head, name: &str) -> Option<&'a str> {
    // hlx:58
    head.headers
        .iter()
        .find(|(k, _)| k == name)
        .map(|(_, v)| v.as_str())
    // hlx:59
}
// hlx:62
pub fn same_secret(a: &[u8], b: &[u8]) -> bool {
    // hlx:63
    if a.len() != b.len() {
        // hlx:64
        return false;
        // hlx:65
    }
    // hlx:66
    let mut diff = 0u8;
    // hlx:67
    for (x, y) in a.iter().zip(b.iter()) {
        // hlx:68
        diff |= x ^ y;
        // hlx:69
    }
    // hlx:70
    std::hint::black_box(diff) == 0
    // hlx:71
}
// hlx:74
pub fn origin_ok(origin: &str, allow: &[String]) -> bool {
    // hlx:75
    origin.starts_with("https://") && allow.iter().any(|a| a.eq_ignore_ascii_case(origin))
    // hlx:76
}
// hlx:78
pub fn version_ok(value: &str) -> bool {
    // hlx:79
    VERSIONS.contains(&value)
    // hlx:80
}
// hlx:83
pub fn admit(head: &Head, key: &str, allow: &[String]) -> Result<(), u16> {
    // hlx:84
    if head.path != "/mcp" {
        // hlx:85
        return Err(404);
        // hlx:86
    }
    // hlx:87
    if let Some(origin) = header(head, "origin") {
        // hlx:88
        if !origin_ok(origin, allow) {
            // hlx:89
            return Err(403);
            // hlx:90
        }
        // hlx:91
    }
    // hlx:92
    let sent = header(head, "x-api-key").unwrap_or("");
    // hlx:93
    if key.is_empty() || !same_secret(sent.as_bytes(), key.as_bytes()) {
        // hlx:94
        return Err(401);
        // hlx:95
    }
    // hlx:96
    if head.method != "POST" {
        // hlx:97
        return Err(405);
        // hlx:98
    }
    // hlx:99
    if let Some(v) = header(head, "mcp-protocol-version") {
        // hlx:100
        if !version_ok(v) {
            // hlx:101
            return Err(400);
            // hlx:102
        }
        // hlx:103
    }
    // hlx:104
    match head.length {
        // hlx:105
        None => return Err(411),
        // hlx:106
        Some(n) if n > MAX_BODY => return Err(413),
        // hlx:107
        Some(_) => {} // hlx:108
    }
    // hlx:109
    Ok(())
    // hlx:110
}
// hlx:112
pub fn reason(status: u16) -> &'static str {
    // hlx:113
    match status {
        200 => "OK",
        202 => "Accepted",
        400 => "Bad Request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not Found",
        405 => "Method Not Allowed",
        408 => "Request Timeout",
        411 => "Length Required",
        413 => "Content Too Large",
        431 => "Request Header Fields Too Large",
        501 => "Not Implemented",
        503 => "Service Unavailable",
        _ => "Internal Server Error",
    }
    // hlx:114
}
// hlx:117
pub fn reply(status: u16, body: &str) -> Vec<u8> {
    // hlx:118
    let none = status == 202;
    // hlx:119
    let mut out = format!(
        "HTTP/1.1 {status} {}\r\nConnection: close\r\nCache-Control: no-store\r\n",
        reason(status)
    );
    // hlx:120
    if status == 405 {
        // hlx:121
        out.push_str("Allow: POST\r\n");
        // hlx:122
    }
    // hlx:123
    if none {
        // hlx:124
        out.push_str("Content-Length: 0\r\n\r\n");
        // hlx:125
    } else {
        // hlx:126
        out.push_str(&format!(
            "Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
            body.len()
        ));
        // hlx:127
    }
    // hlx:128
    out.into_bytes()
    // hlx:129
}
// hlx:132
pub fn refusal(status: u16) -> Vec<u8> {
    // hlx:133
    reply(
        status,
        &format!(
            "{{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{{\"code\":-32000,\"message\":\"{}\"}}}}",
            reason(status)
        ),
    )
    // hlx:134
}