use std::ops::Range;
use std::sync::mpsc::{self, Receiver, Sender};
use std::time::Duration;
use serde_json::{Value, json};
pub const DEFAULT_MODEL: &str = "claude-opus-5";
pub const DEBOUNCE: Duration = Duration::from_millis(500);
const LINES_BEFORE: usize = 80;
const LINES_AFTER: usize = 30;
const MAX_TOKENS: u64 = 256;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(8);
const SYSTEM: &str = "You are a code completion engine inside a text editor. The user message is a file with the marker <CURSOR> where the caret is. Reply with ONLY the text to insert at <CURSOR>: no explanation, no code fences, no repetition of text already before or after the marker. Prefer completing the current line; continue onto following lines only when the next lines are obvious. If nothing should be inserted, reply with nothing.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Backend {
Claude { base_url: String, api_key: String },
Local { base_url: String },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
pub backend: Backend,
pub model: String,
}
pub fn resolve(
local: Option<(String, Option<String>)>,
env: impl Fn(&str) -> Option<String>,
) -> Result<Config, String> {
let model_override = env("CROFT_COMPLETE_MODEL").filter(|m| !m.is_empty());
let url_override = env("CROFT_COMPLETE_URL").filter(|u| !u.is_empty());
if let Some((base_url, model)) = local {
let Some(model) = model_override.or(model) else {
return Err(String::from(
"the local navigator names no model; set CROFT_COMPLETE_MODEL",
));
};
return Ok(Config {
backend: Backend::Local {
base_url: url_override.unwrap_or(base_url),
},
model,
});
}
let Some(api_key) = env("ANTHROPIC_API_KEY").filter(|k| !k.is_empty()) else {
return Err(String::from(
"set ANTHROPIC_API_KEY, or seat a local model with croft pair",
));
};
let base_url = url_override.unwrap_or_else(|| String::from("https://api.anthropic.com"));
if !crate::pair::local::credential_allowed(&base_url) {
return Err(String::from(
"ANTHROPIC_API_KEY is sent only over https or to this machine, and CROFT_COMPLETE_URL is neither",
));
}
Ok(Config {
backend: Backend::Claude { base_url, api_key },
model: model_override.unwrap_or_else(|| String::from(DEFAULT_MODEL)),
})
}
pub fn prompt(lines: &[String], row: usize, col: usize) -> String {
let start = row.saturating_sub(LINES_BEFORE);
let end = (row + LINES_AFTER + 1).min(lines.len());
let mut out = String::new();
for (i, line) in lines.iter().enumerate().take(end).skip(start) {
if i == row {
let byte = line
.char_indices()
.nth(col)
.map(|(b, _)| b)
.unwrap_or(line.len());
out.push_str(&line[..byte]);
out.push_str("<CURSOR>");
out.push_str(&line[byte..]);
} else {
out.push_str(line);
}
out.push('\n');
}
out
}
pub fn request_body(config: &Config, prompt: &str) -> Value {
let mut body = json!({
"model": config.model,
"max_tokens": MAX_TOKENS,
"system": SYSTEM,
"messages": [{ "role": "user", "content": prompt }],
});
if matches!(config.backend, Backend::Claude { .. }) {
body["output_config"] = json!({ "effort": "low" });
body["fallbacks"] = json!("default");
}
body
}
pub fn parse_response(body: &Value) -> Option<String> {
if body.get("stop_reason").and_then(Value::as_str) == Some("refusal") {
return None;
}
let text: String = body
.get("content")?
.as_array()?
.iter()
.filter(|b| b.get("type").and_then(Value::as_str) == Some("text"))
.filter_map(|b| b.get("text").and_then(Value::as_str))
.collect();
let cleaned = strip_fence(&text);
(!cleaned.trim().is_empty()).then(|| cleaned.to_string())
}
pub fn next_word_len(text: &str) -> usize {
let is_word = |c: char| c.is_alphanumeric() || c == '_';
let body = text.trim_start();
let lead = text.len() - body.len();
let Some(first) = body.chars().next() else {
return text.len();
};
let word = is_word(first);
let run = body
.char_indices()
.find(|&(_, c)| c.is_whitespace() || is_word(c) != word)
.map_or(body.len(), |(i, _)| i);
lead + run
}
pub fn next_line_len(text: &str) -> usize {
let skip = usize::from(text.starts_with('\n'));
text[skip..].find('\n').map_or(text.len(), |i| skip + i)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ghost {
pub row: usize,
pub col: usize,
pub seq: u64,
pub text: String,
pub replaces: Option<Range<usize>>,
}
impl Ghost {
pub fn insert(row: usize, col: usize, seq: u64, text: String) -> Self {
Ghost {
row,
col,
seq,
text,
replaces: None,
}
}
pub fn replacing(
row: usize,
col: usize,
seq: u64,
line: &str,
range: Range<usize>,
text: String,
) -> Option<Self> {
if range.start > col || col > range.end || range.end > line.chars().count() {
return None;
}
let typed: String = line.chars().take(col).skip(range.start).collect();
let after: String = line.chars().take(range.end).skip(col).collect();
let ahead = text
.strip_prefix(typed.as_str())
.and_then(|rest| rest.strip_suffix(after.as_str()));
let (text, replaces) = match ahead {
Some(middle) => (middle.to_string(), None),
None => (text, Some(range)),
};
(!text.trim().is_empty()).then_some(Ghost {
row,
col,
seq,
text,
replaces,
})
}
}
fn strip_fence(text: &str) -> &str {
let t = text.trim_end();
let Some(rest) = t.strip_prefix("```") else {
return text.trim_end_matches('\n');
};
let body = rest.split_once('\n').map(|(_, b)| b).unwrap_or("");
body.strip_suffix("```")
.unwrap_or(body)
.trim_end_matches('\n')
}
#[derive(Debug, Clone)]
pub struct Job {
pub id: u64,
pub config: Config,
pub prompt: String,
}
#[derive(Debug)]
pub struct Done {
pub id: u64,
pub result: Result<Option<String>, String>,
}
pub struct Worker {
tx: Sender<Job>,
rx: Receiver<Done>,
}
impl Worker {
pub fn spawn() -> Self {
let (job_tx, job_rx) = mpsc::channel::<Job>();
let (done_tx, done_rx) = mpsc::channel::<Done>();
std::thread::Builder::new()
.name("croft-inline-complete".into())
.spawn(move || {
while let Ok(mut job) = job_rx.recv() {
while let Ok(newer) = job_rx.try_recv() {
job = newer;
}
let result = send(&job.config, &job.prompt);
if done_tx.send(Done { id: job.id, result }).is_err() {
return;
}
}
})
.expect("spawn inline-complete thread");
Worker {
tx: job_tx,
rx: done_rx,
}
}
pub fn submit(&self, job: Job) {
let _ = self.tx.send(job);
}
pub fn try_recv(&self) -> Option<Done> {
self.rx.try_recv().ok()
}
}
fn send(config: &Config, prompt: &str) -> Result<Option<String>, String> {
let agent = ureq3::Agent::config_builder()
.timeout_global(Some(REQUEST_TIMEOUT))
.max_redirects(0)
.http_status_as_error(false)
.build()
.new_agent();
let (base_url, key) = match &config.backend {
Backend::Claude { base_url, api_key } => (base_url.as_str(), Some(api_key.as_str())),
Backend::Local { base_url } => (base_url.as_str(), None),
};
let mut req = agent
.post(format!("{}/v1/messages", base_url.trim_end_matches('/')))
.header("content-type", "application/json")
.header("anthropic-version", "2023-06-01");
if let Some(key) = key {
req = req
.header("x-api-key", key)
.header("anthropic-beta", "server-side-fallback-2026-07-01");
}
let mut resp = req
.send(request_body(config, prompt).to_string())
.map_err(|e| format!("request failed: {e}"))?;
let status = resp.status();
let text = resp
.body_mut()
.read_to_string()
.map_err(|e| format!("reading the answer: {e}"))?;
if !status.is_success() {
let why = serde_json::from_str::<Value>(&text)
.ok()
.and_then(|v| {
v.pointer("/error/message")
.and_then(Value::as_str)
.map(str::to_string)
})
.unwrap_or_else(|| text.chars().take(200).collect());
return Err(format!("{status}: {why}"));
}
let body: Value = serde_json::from_str(&text).map_err(|e| format!("unreadable answer: {e}"))?;
Ok(parse_response(&body))
}
#[cfg(test)]
mod tests {
#[test]
fn next_word_takes_leading_space_and_one_word() {
let text = "\n total = a + b\n return total";
assert_eq!(&text[..next_word_len(text)], "\n total");
let rest = &text[next_word_len(text)..];
assert_eq!(&rest[..next_word_len(rest)], " =");
assert_eq!(next_word_len("foo_bar(1)"), 7);
assert_eq!(next_word_len("();"), 3);
}
#[test]
fn next_word_of_blank_text_takes_it_all() {
assert_eq!(next_word_len(" \n "), 6);
assert_eq!(next_word_len(""), 0);
}
#[test]
fn next_line_takes_one_line_without_the_break_after_it() {
let text = "\n total = a + b\n return total";
assert_eq!(&text[..next_line_len(text)], "\n total = a + b");
assert_eq!(next_line_len("1 + 1;"), 6);
assert_eq!(&"x)\ny"[..next_line_len("x)\ny")], "x)");
}
use super::*;
#[test]
fn a_replacement_that_types_ahead_is_ghost_text_at_the_caret() {
let line = " let x = pri";
let g = Ghost::replacing(0, 15, 7, line, 12..15, String::from("println!()")).unwrap();
assert_eq!(g, Ghost::insert(0, 15, 7, String::from("ntln!()")));
let closing = Ghost::replacing(0, 4, 1, "foo()", 0..5, String::from("foo(bar)"));
assert_eq!(closing.map(|g| g.text).as_deref(), Some("bar"));
}
#[test]
fn a_replacement_that_rewrites_the_typed_text_keeps_its_range() {
let line = "let x = pritn";
let g = Ghost::replacing(0, 13, 2, line, 8..13, String::from("println!()")).unwrap();
assert_eq!(g.text, "println!()");
assert_eq!(g.replaces, Some(8..13));
let dropped = Ghost::replacing(0, 4, 1, "foo()", 0..5, String::from("foo(x, y"));
assert_eq!(
dropped.and_then(|g| g.replaces),
Some(0..5),
"the `)` after the caret is not kept, so it is replaced"
);
let blanks = Ghost::replacing(0, 7, 1, "x = \"ab ", 4..9, String::from("\"abc\""));
assert_eq!(
blanks.and_then(|g| g.replaces),
Some(4..9),
"blanks the answer drops are replaced, not left after it"
);
}
#[test]
fn a_replacement_off_the_caret_or_changing_nothing_is_dropped() {
let line = "let x = 1";
let text = || String::from("let y = 2");
assert_eq!(Ghost::replacing(0, 9, 0, line, 0..3, text()), None);
assert_eq!(Ghost::replacing(0, 9, 0, line, 0..12, text()), None);
assert_eq!(
Ghost::replacing(0, 9, 0, line, 8..9, String::from("1")),
None
);
let wide = "é = ";
let g = Ghost::replacing(0, 4, 0, wide, 0..4, String::from("é = 1")).unwrap();
assert_eq!(g.text, "1", "columns are chars, not bytes");
}
fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let owned: Vec<(String, String)> = pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
move |k| {
owned
.iter()
.find(|(key, _)| key == k)
.map(|(_, v)| v.clone())
}
}
#[test]
fn a_local_navigator_wins_then_the_api_key_then_nothing() {
let local = Some((
String::from("http://localhost:11434"),
Some(String::from("qwen")),
));
assert_eq!(
resolve(local, env_of(&[("ANTHROPIC_API_KEY", "k")])),
Ok(Config {
backend: Backend::Local {
base_url: String::from("http://localhost:11434")
},
model: String::from("qwen"),
})
);
assert_eq!(
resolve(None, env_of(&[("ANTHROPIC_API_KEY", "k")])).map(|c| c.model),
Ok(String::from(DEFAULT_MODEL))
);
assert!(resolve(None, env_of(&[])).is_err());
assert_eq!(
resolve(
None,
env_of(&[("ANTHROPIC_API_KEY", "k"), ("CROFT_COMPLETE_MODEL", "m")])
)
.map(|c| c.model),
Ok(String::from("m"))
);
}
#[test]
fn the_api_key_goes_only_to_https_or_this_machine() {
let with_url = |url: &str| {
resolve(
None,
env_of(&[("ANTHROPIC_API_KEY", "k"), ("CROFT_COMPLETE_URL", url)]),
)
};
for remote in [
"http://proxy.lan:8080",
"http://10.0.0.5",
"http://localhost:pass@evil.example",
"ftp://api.example",
"not a url",
] {
let refused = with_url(remote);
assert!(refused.is_err(), "{remote} must not receive the key");
assert!(!refused.unwrap_err().contains(remote));
}
for allowed in [
"https://gateway.example",
"http://localhost:8080",
"http://127.0.0.1:9000",
"http://[::1]:9000",
] {
assert_eq!(
with_url(allowed).map(|c| c.backend),
Ok(Backend::Claude {
base_url: String::from(allowed),
api_key: String::from("k"),
}),
"{allowed} may receive the key"
);
}
}
#[test]
fn the_prompt_marks_the_caret_in_a_window_of_lines() {
let lines: Vec<String> = ["fn main() {", " let x = ", "}"]
.iter()
.map(|s| s.to_string())
.collect();
assert_eq!(
prompt(&lines, 1, 12),
"fn main() {\n let x = <CURSOR>\n}\n"
);
}
#[test]
fn the_claude_request_asks_for_low_effort_and_server_side_fallbacks() {
let claude = Config {
backend: Backend::Claude {
base_url: String::from("https://api.anthropic.com"),
api_key: String::from("k"),
},
model: String::from(DEFAULT_MODEL),
};
let body = request_body(&claude, "p");
assert_eq!(body["output_config"]["effort"], "low");
assert_eq!(body["fallbacks"], "default");
assert_eq!(body["messages"][0]["content"], "p");
let local = Config {
backend: Backend::Local {
base_url: String::from("http://localhost:11434"),
},
model: String::from("qwen"),
};
let body = request_body(&local, "p");
assert!(
body.get("fallbacks").is_none(),
"local servers get the minimal payload"
);
}
#[test]
fn responses_are_cleaned_and_refusals_give_nothing() {
let ok = json!({"stop_reason": "end_turn", "content": [
{"type": "thinking", "thinking": ""},
{"type": "text", "text": "42;\n"}
]});
assert_eq!(parse_response(&ok).as_deref(), Some("42;"));
let fenced = json!({"content": [{"type": "text", "text": "```rust\nfoo()\n```"}]});
assert_eq!(parse_response(&fenced).as_deref(), Some("foo()"));
let refused = json!({"stop_reason": "refusal", "content": []});
assert_eq!(parse_response(&refused), None);
let empty = json!({"content": [{"type": "text", "text": " "}]});
assert_eq!(parse_response(&empty), None);
}
}