//! A stand-in for a model provider, served beside the package source so the //! self-check can reach a "model" with no key and no internet: Anthropic's //! Messages API (`POST /v1/messages`, `stream: true`), answered as server- //! sent events in chunks, as the real one does. //! //! It is a script, not a model: what it answers follows from the last //! message, so a check knows what to expect. //! //! - A user's text `call ` is answered with that tool call. //! Several, separated by ` ; `, are answered as several calls at once. //! - Tool results are answered with text: `done: ` and each result's //! content, an error's marked `error: `. //! - Any other text is answered `You said: ` and the text. //! //! The key must be [`KEY`]; any other is a 401, as a provider answers. use pinnacle_json::Value; use std::io::Write; /// The only key the stand-in takes. pub const KEY: &str = "test-key"; /// Answers one request to `/v1/messages` on `stream`. pub fn answer(headers: &[(String, String)], body: &[u8], mut stream: &std::net::TcpStream) { let header = |name: &str| { headers .iter() .find(|(n, _)| n.eq_ignore_ascii_case(name)) .map(|(_, v)| v.as_str()) }; if header("x-api-key") != Some(KEY) { let error = r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#; let _ = write!( stream, "HTTP/1.1 401 Unauthorized\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{error}", error.len() ); return; } let request = std::str::from_utf8(body) .ok() .and_then(|t| pinnacle_json::parse(t).ok()) .unwrap_or(Value::Null); let blocks = reply(&request); let _ = write!( stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n" ); let mut send = |event: &str, data: Value| { let text = format!("event: {event}\ndata: {data}\n\n"); let _ = write!(stream, "{:x}\r\n{text}\r\n", text.len()); }; let input_tokens = body.len() as u64 / 4; send( "message_start", pinnacle_json::parse(&format!( r#"{{"type":"message_start","message":{{"id":"msg_stand_in","type":"message","role":"assistant","content":[],"model":"stand-in","stop_reason":null,"usage":{{"input_tokens":{input_tokens},"output_tokens":1}}}}}}"# )) .unwrap(), ); let mut stop = "end_turn"; for (index, block) in blocks.iter().enumerate() { let index = Value::from(index as u64); match block { Block::Text(text) => { send( "content_block_start", Value::object([ ("type", "content_block_start".into()), ("index", index.clone()), ( "content_block", Value::object([("type", "text".into()), ("text", "".into())]), ), ]), ); // In pieces, as a model's text arrives. let chars: Vec = text.chars().collect(); for piece in chars.chunks(7) { send( "content_block_delta", Value::object([ ("type", "content_block_delta".into()), ("index", index.clone()), ( "delta", Value::object([ ("type", "text_delta".into()), ("text", piece.iter().collect::().into()), ]), ), ]), ); } } Block::Call { id, name, input } => { stop = "tool_use"; send( "content_block_start", Value::object([ ("type", "content_block_start".into()), ("index", index.clone()), ( "content_block", Value::object([ ("type", "tool_use".into()), ("id", id.as_str().into()), ("name", name.as_str().into()), ("input", Value::object::<&str>([])), ]), ), ]), ); let json: Vec = input.chars().collect(); for piece in json.chunks(5) { send( "content_block_delta", Value::object([ ("type", "content_block_delta".into()), ("index", index.clone()), ( "delta", Value::object([ ("type", "input_json_delta".into()), ("partial_json", piece.iter().collect::().into()), ]), ), ]), ); } } } send( "content_block_stop", Value::object([("type", "content_block_stop".into()), ("index", index)]), ); } send( "message_delta", pinnacle_json::parse(&format!( r#"{{"type":"message_delta","delta":{{"stop_reason":"{stop}"}},"usage":{{"output_tokens":9}}}}"# )) .unwrap(), ); send("message_stop", Value::object([("type", "message_stop".into())])); let _ = write!(stream, "0\r\n\r\n"); } enum Block { Text(String), Call { id: String, name: String, input: String }, } /// What the script answers to `request`. fn reply(request: &Value) -> Vec { let Some(last) = request.get("messages").as_array().and_then(|m| m.last()) else { return vec![Block::Text("You said nothing".into())]; }; let content = last.get("content"); if let Some(text) = content.as_str() { return from_text(text); } let blocks = content.as_array().unwrap_or(&[]); let results: Vec = blocks .iter() .filter(|b| b.get("type").as_str() == Some("tool_result")) .map(|b| { let text = match b.get("content") { Value::String(s) => s.clone(), Value::Array(parts) => parts.iter().filter_map(|p| p.get("text").as_str()).collect(), _ => String::new(), }; match b.get("is_error").as_bool() { Some(true) => format!("error: {text}"), _ => text, } }) .collect(); if !results.is_empty() { return vec![Block::Text(format!("done: {}", results.join(" | ")))]; } let text: String = blocks.iter().filter_map(|b| b.get("text").as_str()).collect(); from_text(&text) } fn from_text(text: &str) -> Vec { let calls: Vec = text .split(" ; ") .enumerate() .filter_map(|(i, part)| { let rest = part.trim().strip_prefix("call ")?; let (name, input) = rest.split_once(' ').unwrap_or((rest, "{}")); Some(Block::Call { id: format!("toolu_{i}"), name: name.into(), input: input.into(), }) }) .collect(); if calls.is_empty() { vec![Block::Text(format!("You said: {text}"))] } else { calls } }