repositories / smith
smith
There are many coding harnesses - but this one is fast
owned by admin
plugins/protocol-anthropic/src/lib.rs
Raw//! Anthropic Messages protocol component.
#![expect(missing_docs, reason = "wit-bindgen generates the world surface")]
#![expect(clippy::pedantic, reason = "wit-bindgen generates the world surface")]
wit_bindgen::generate!({ path: "../../wit/smith-plugin.wit", world: "plugin-world" });
use exports::smith::plugin::plugin::{Guest as PluginGuest, ToolDeclaration};
use exports::smith::plugin::provider::{
CatalogSnapshot, DecodeStep, Guest as ProviderGuest, MessageBlock, MessageRole,
ProviderRequest, ProviderSettings, RequestTemplate, SettingsProvenance, StopReason,
StreamEvent, ToolUse, Usage,
};
use exports::smith::plugin::registration::{
CredentialSource, Guest as RegistrationGuest, ProtocolBinding, ProviderContribution,
Registrations,
};
use serde_json::{Value, json};
struct AnthropicProtocol;
impl RegistrationGuest for AnthropicProtocol {
fn declare() -> Registrations {
Registrations {
credential_sources: vec![CredentialSource {
id: "connection-api-key".to_string(),
}],
providers: vec![ProviderContribution {
id: "anthropic".to_string(),
protocol: ProtocolBinding::AnthropicMessages,
credential_source_id: "connection-api-key".to_string(),
}],
models: Vec::new(),
}
}
}
impl PluginGuest for AnthropicProtocol {
fn declare_tools() -> Vec<ToolDeclaration> {
Vec::new()
}
fn invoke(_name: String, _input_json: String) -> Result<String, String> {
Err("protocol declares no tools".into())
}
}
impl ProviderGuest for AnthropicProtocol {
fn declare_settings() -> ProviderSettings {
ProviderSettings {
include_usage: true,
subscription: false,
provenance: SettingsProvenance::BuiltIn,
}
}
fn validate_settings(settings: ProviderSettings) -> Result<ProviderSettings, String> {
settings
.include_usage
.then_some(settings)
.ok_or_else(|| "protocol setting include_usage must be true".into())
}
fn build_request(
model: String,
request: ProviderRequest,
settings: ProviderSettings,
catalog: CatalogSnapshot,
) -> Result<RequestTemplate, String> {
Self::validate_settings(settings)?;
if !catalog.models.iter().any(|entry| entry.id == model) {
return Err("provider catalog snapshot does not admit model".into());
}
let mut system = String::new();
let mut messages = Vec::new();
for message in request.messages {
match message.role {
MessageRole::System => {
if !system.is_empty() {
system.push('\n');
}
system.push_str(&text(&message.blocks));
}
MessageRole::User => messages.push(
json!({"role":"user","content":[{"type":"text","text":text(&message.blocks)}]}),
),
MessageRole::Assistant => messages
.push(json!({"role":"assistant","content":assistant_blocks(&message.blocks)?})),
MessageRole::Tool => {
messages.push(json!({"role":"user","content":tool_results(&message.blocks)}))
}
}
}
let mut body = json!({"model":model,"max_tokens":request.output_tokens_max.unwrap_or(4096),"messages":messages,"stream":true});
if settings.subscription {
let mut blocks = vec![
json!({"type":"text","text":"You are Claude Code, Anthropic's official CLI for Claude."}),
];
if !system.is_empty() {
blocks.push(json!({"type":"text","text":system}));
}
body["system"] = Value::Array(blocks);
} else if !system.is_empty() {
body["system"] = json!(system);
}
if !request.tools.is_empty() {
body["tools"] = Value::Array(request.tools.into_iter().map(|tool| serde_json::from_str::<Value>(&tool.input_schema_json).map(|schema| json!({"name":tool.name,"description":tool.description,"input_schema":schema})).map_err(|error| format!("tool schema is not JSON: {error}"))).collect::<Result<_,_>>()?);
}
Ok(RequestTemplate {
url: "https://protocol.invalid/messages".into(),
authorization: "{{secret:anthropic-connection}}".into(),
body: body.to_string(),
})
}
fn decode_response(
state: Vec<u8>,
chunk: Vec<u8>,
finished: bool,
) -> Result<DecodeStep, String> {
let mut state: Value = if state.is_empty() {
json!({"pending":[],"tools":{},"usage":{"input":0,"output":0,"hit":0,"write":0},"reason":null,"stopped":false})
} else {
serde_json::from_slice(&state).map_err(|e| e.to_string())?
};
let mut pending = state["pending"]
.as_array()
.ok_or("invalid codec pending bytes")?
.iter()
.map(|byte| {
byte.as_u64()
.and_then(|n| u8::try_from(n).ok())
.ok_or("invalid codec pending byte")
})
.collect::<Result<Vec<_>, _>>()?;
pending.extend(chunk);
let mut events = Vec::new();
while let Some((data, rest)) = sse(&pending) {
pending = rest;
process(
&mut state,
std::str::from_utf8(&data).map_err(|e| e.to_string())?,
&mut events,
)?;
}
if finished {
if !pending.is_empty() {
process(
&mut state,
std::str::from_utf8(&pending).map_err(|e| e.to_string())?,
&mut events,
)?;
}
if !state["stopped"].as_bool().unwrap_or(false) {
return Err("provider stream ended before message_stop".into());
}
pending.clear();
}
state["pending"] = json!(pending);
Ok(DecodeStep {
state: serde_json::to_vec(&state).map_err(|e| e.to_string())?,
events,
})
}
}
fn text(blocks: &[MessageBlock]) -> String {
blocks
.iter()
.filter_map(|block| {
if let MessageBlock::Text(text) = block {
Some(text.as_str())
} else {
None
}
})
.collect::<Vec<_>>()
.join("\n")
}
fn assistant_blocks(blocks: &[MessageBlock]) -> Result<Vec<Value>, String> {
blocks.iter().filter_map(|block| match block { MessageBlock::Text(text) => Some(Ok(json!({"type":"text","text":text}))), MessageBlock::ToolUse(call) => Some(serde_json::from_str::<Value>(&call.input_json).map(|input| json!({"type":"tool_use","id":call.call_id,"name":call.name,"input":input})).map_err(|e| format!("tool arguments are not JSON: {e}"))), _ => None }).collect()
}
fn tool_results(blocks: &[MessageBlock]) -> Vec<Value> {
blocks.iter().filter_map(|block| if let MessageBlock::ToolResult(result) = block { Some(json!({"type":"tool_result","tool_use_id":result.call_id,"content":result.output})) } else { None }).collect()
}
fn sse(bytes: &[u8]) -> Option<(Vec<u8>, Vec<u8>)> {
let mut data = Vec::new();
let mut consumed = 0;
for raw in bytes.split_inclusive(|byte| *byte == b'\n') {
let length = raw.len();
let line = raw.strip_suffix(b"\n").unwrap_or(raw);
let line = line.strip_suffix(b"\r").unwrap_or(line);
if line.is_empty() {
if !data.is_empty() {
return Some((data, bytes[consumed + length..].to_vec()));
}
} else if let Some(value) = line.strip_prefix(b"data:") {
data.extend_from_slice(value.strip_prefix(b" ").unwrap_or(value));
}
consumed += length;
}
None
}
fn process(state: &mut Value, data: &str, events: &mut Vec<StreamEvent>) -> Result<(), String> {
let value: Value =
serde_json::from_str(data.trim()).map_err(|e| format!("event payload is not JSON: {e}"))?;
match value["type"].as_str() {
Some("message_start") => {
state["usage"]["input"] = value
.pointer("/message/usage/input_tokens")
.cloned()
.unwrap_or_else(|| json!(0));
}
Some("content_block_start") => {
if value.pointer("/content_block/type").and_then(Value::as_str) == Some("tool_use") {
let index = value["index"]
.as_u64()
.ok_or("tool block without index")?
.to_string();
state["tools"][index] = json!({"call_id":value.pointer("/content_block/id").and_then(Value::as_str).ok_or("tool block without id")?,"name":value.pointer("/content_block/name").and_then(Value::as_str).ok_or("tool block without name")?,"input":""});
}
}
Some("content_block_delta") => match value.pointer("/delta/type").and_then(Value::as_str) {
Some("text_delta") => {
if let Some(text) = value
.pointer("/delta/text")
.and_then(Value::as_str)
.filter(|x| !x.is_empty())
{
events.push(StreamEvent::Text(text.into()));
}
}
Some("thinking_delta") => {
if let Some(text) = value
.pointer("/delta/thinking")
.and_then(Value::as_str)
.filter(|x| !x.is_empty())
{
events.push(StreamEvent::Thinking(text.into()));
}
}
Some("input_json_delta") => {
let index = value["index"]
.as_u64()
.ok_or("tool delta without index")?
.to_string();
state["tools"][&index]["input"] = json!(format!(
"{}{}",
state["tools"][&index]["input"].as_str().unwrap_or_default(),
value
.pointer("/delta/partial_json")
.and_then(Value::as_str)
.unwrap_or_default()
));
}
Some(kind) => return Err(format!("unknown delta type {kind}")),
None => return Err("content block delta without type".into()),
},
Some("message_delta") => {
state["reason"] = value
.pointer("/delta/stop_reason")
.cloned()
.unwrap_or(Value::Null);
for (field, path) in [
("output", "/usage/output_tokens"),
("hit", "/usage/cache_read_input_tokens"),
("write", "/usage/cache_creation_input_tokens"),
] {
if let Some(number) = value.pointer(path).and_then(Value::as_u64) {
state["usage"][field] = json!(number);
}
}
}
Some("message_stop") => {
let reason = match state["reason"]
.as_str()
.ok_or("message_stop without stop reason")?
{
"end_turn" => StopReason::EndTurn,
"max_tokens" => StopReason::Limit,
"tool_use" => StopReason::ToolUse,
"stop_sequence" => StopReason::StopSequence,
"refusal" => StopReason::Refusal,
"pause_turn" => {
return Err("pause_turn requires server-side tool result handling".into());
}
other => return Err(format!("unmapped stop reason {other}")),
};
let tools = state["tools"].as_object().ok_or("invalid tool state")?;
if !tools.is_empty() {
return Err("message_stop with unfinished tool blocks".into());
}
events.push(StreamEvent::Stop((
reason,
Some(Usage {
input_tokens: state["usage"]["input"].as_u64().unwrap_or(0),
output_tokens: state["usage"]["output"].as_u64().unwrap_or(0),
input_cache_hit_tokens: state["usage"]["hit"].as_u64().unwrap_or(0),
input_cache_write_tokens: state["usage"]["write"].as_u64().unwrap_or(0),
}),
)));
state["stopped"] = json!(true);
}
Some("content_block_stop") => {
let index = value["index"]
.as_u64()
.ok_or("tool stop without index")?
.to_string();
if let Some(tool) = state["tools"]
.as_object_mut()
.ok_or("invalid tool state")?
.remove(&index)
{
let input = tool["input"].as_str().unwrap_or_default();
let input = if input.trim().is_empty() {
"{}".to_string()
} else {
serde_json::from_str::<Value>(input)
.map_err(|e| format!("partial_json arguments do not assemble: {e}"))?
.to_string()
};
events.push(StreamEvent::ToolUse(ToolUse {
name: tool["name"]
.as_str()
.ok_or("tool block without name")?
.into(),
input_json: input,
call_id: tool["call_id"]
.as_str()
.ok_or("tool block without id")?
.into(),
}));
}
}
Some("ping") => {}
Some("error") => {
return Err(value
.pointer("/error/message")
.and_then(Value::as_str)
.unwrap_or("provider error")
.into());
}
other => return Err(format!("unknown event type {other:?}")),
};
Ok(())
}
export!(AnthropicProtocol);