Classify every comment as tautology, stale, excuse or decision record. Tautology/stale/excuse comments are deleted (excuses filed as issues #196-#236), decisions moved to docs/adr/0001-0034. - scripts/lint-comments.sh + .comment-baseline: per-file comment count may only go down; wired into tests/all.sh - .claude/skills/delete-comment: repeatable audit workflow - cargo fmt applied to touched crates Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
349 lines
8.5 KiB
Rust
349 lines
8.5 KiB
Rust
pub mod anthropic;
|
|
pub mod auth;
|
|
pub mod claude_cli;
|
|
pub mod codex;
|
|
pub mod models;
|
|
pub mod openai_compat;
|
|
|
|
use futures::stream::BoxStream;
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::Value;
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum Role {
|
|
User,
|
|
Assistant,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
#[serde(tag = "type", rename_all = "snake_case")]
|
|
pub enum ContentBlock {
|
|
Text {
|
|
text: String,
|
|
},
|
|
Thinking {
|
|
thinking: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
signature: Option<String>,
|
|
},
|
|
Image {
|
|
media_type: String,
|
|
data: String,
|
|
},
|
|
ToolUse {
|
|
id: String,
|
|
name: String,
|
|
input: Value,
|
|
},
|
|
ToolResult {
|
|
tool_use_id: String,
|
|
content: String,
|
|
#[serde(default)]
|
|
is_error: bool,
|
|
},
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct Message {
|
|
pub role: Role,
|
|
pub content: Vec<ContentBlock>,
|
|
}
|
|
|
|
impl Message {
|
|
pub fn user(text: impl Into<String>) -> Self {
|
|
Self {
|
|
role: Role::User,
|
|
content: vec![ContentBlock::Text { text: text.into() }],
|
|
}
|
|
}
|
|
pub fn text(&self) -> String {
|
|
self.content
|
|
.iter()
|
|
.filter_map(|b| match b {
|
|
ContentBlock::Text { text } => Some(text.as_str()),
|
|
_ => None,
|
|
})
|
|
.collect()
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct ToolSpec {
|
|
pub name: String,
|
|
pub description: String,
|
|
pub input_schema: Value,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
|
pub struct Usage {
|
|
pub input_tokens: u64,
|
|
pub output_tokens: u64,
|
|
#[serde(default)]
|
|
pub cache_read_tokens: u64,
|
|
#[serde(default)]
|
|
pub cache_write_tokens: u64,
|
|
}
|
|
|
|
impl Usage {
|
|
pub fn add(&mut self, o: &Usage) {
|
|
self.input_tokens += o.input_tokens;
|
|
self.output_tokens += o.output_tokens;
|
|
self.cache_read_tokens += o.cache_read_tokens;
|
|
self.cache_write_tokens += o.cache_write_tokens;
|
|
}
|
|
pub fn cost(&self, p: &Pricing) -> f64 {
|
|
(self.input_tokens as f64 * p.input
|
|
+ self.output_tokens as f64 * p.output
|
|
+ self.cache_read_tokens as f64 * p.cache_read
|
|
+ self.cache_write_tokens as f64 * p.cache_write)
|
|
/ 1e6
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
|
|
pub struct Pricing {
|
|
pub input: f64,
|
|
pub output: f64,
|
|
pub cache_read: f64,
|
|
pub cache_write: f64,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
|
pub struct Quota {
|
|
pub windows: Vec<QuotaWindow>,
|
|
pub credits: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct QuotaWindow {
|
|
pub label: String,
|
|
pub used_pct: f64,
|
|
pub resets_at: Option<u64>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum StopReason {
|
|
EndTurn,
|
|
ToolUse,
|
|
MaxTokens,
|
|
Other,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum Effort {
|
|
Off,
|
|
Low,
|
|
#[default]
|
|
Medium,
|
|
High,
|
|
}
|
|
|
|
impl Effort {
|
|
pub const ALL: [Effort; 4] = [Effort::Off, Effort::Low, Effort::Medium, Effort::High];
|
|
|
|
pub fn default_for(k: auth::Kind) -> Self {
|
|
match k {
|
|
auth::Kind::Claude => Effort::Off,
|
|
auth::Kind::Codex => Effort::Medium,
|
|
auth::Kind::Custom => Effort::Off,
|
|
}
|
|
}
|
|
|
|
pub fn levels(k: auth::Kind) -> &'static [Effort] {
|
|
match k {
|
|
auth::Kind::Claude | auth::Kind::Custom => &Self::ALL,
|
|
auth::Kind::Codex => &Self::ALL[1..],
|
|
}
|
|
}
|
|
|
|
pub fn next(self, k: auth::Kind) -> Self {
|
|
let l = Self::levels(k);
|
|
l.iter()
|
|
.position(|&e| e == self)
|
|
.map_or(l[0], |i| l[(i + 1) % l.len()])
|
|
}
|
|
|
|
pub fn name(self) -> &'static str {
|
|
match self {
|
|
Effort::Off => "off",
|
|
Effort::Low => "low",
|
|
Effort::Medium => "medium",
|
|
Effort::High => "high",
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod effort_tests {
|
|
use super::*;
|
|
use auth::Kind;
|
|
|
|
#[test]
|
|
fn cycle_wraps_and_codex_skips_off() {
|
|
let mut e = Effort::Off;
|
|
let seen: Vec<_> = (0..5)
|
|
.map(|_| {
|
|
e = e.next(Kind::Claude);
|
|
e
|
|
})
|
|
.collect();
|
|
assert_eq!(
|
|
seen,
|
|
[
|
|
Effort::Low,
|
|
Effort::Medium,
|
|
Effort::High,
|
|
Effort::Off,
|
|
Effort::Low
|
|
]
|
|
);
|
|
assert_eq!(Effort::High.next(Kind::Codex), Effort::Low);
|
|
assert_eq!(
|
|
Effort::Off.next(Kind::Codex),
|
|
Effort::Low,
|
|
"unsupported level"
|
|
);
|
|
assert_eq!("high".parse::<Effort>(), Ok(Effort::High));
|
|
assert!("max".parse::<Effort>().is_err());
|
|
}
|
|
}
|
|
|
|
impl std::str::FromStr for Effort {
|
|
type Err = String;
|
|
fn from_str(s: &str) -> std::result::Result<Self, String> {
|
|
Self::ALL
|
|
.into_iter()
|
|
.find(|e| e.name() == s)
|
|
.ok_or_else(|| format!("unknown level {s:?} (off, low, medium, high)"))
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct Request {
|
|
pub model: String,
|
|
pub system: String,
|
|
pub messages: Vec<Message>,
|
|
pub tools: Vec<ToolSpec>,
|
|
pub max_tokens: u32,
|
|
pub effort: Effort,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
#[serde(tag = "type", rename_all = "snake_case")]
|
|
pub enum StreamEvent {
|
|
TextDelta {
|
|
text: String,
|
|
},
|
|
ThinkingDelta {
|
|
text: String,
|
|
},
|
|
ToolUseStart {
|
|
id: String,
|
|
name: String,
|
|
},
|
|
ToolRun {
|
|
id: String,
|
|
name: String,
|
|
input: serde_json::Value,
|
|
content: String,
|
|
is_error: bool,
|
|
},
|
|
Quota(Quota),
|
|
Done {
|
|
message: Message,
|
|
stop: StopReason,
|
|
usage: Usage,
|
|
},
|
|
}
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum Error {
|
|
#[error("http: {0}")]
|
|
Http(String),
|
|
#[error("api {status}: {body}")]
|
|
Api { status: u16, body: String },
|
|
#[error("decode: {0}")]
|
|
Decode(String),
|
|
}
|
|
|
|
pub type Result<T> = std::result::Result<T, Error>;
|
|
|
|
#[async_trait::async_trait]
|
|
pub trait Provider: Send + Sync {
|
|
async fn stream(&self, req: Request) -> Result<BoxStream<'static, Result<StreamEvent>>>;
|
|
async fn models(&self) -> Result<Vec<models::ModelInfo>> {
|
|
Ok(vec![])
|
|
}
|
|
}
|
|
|
|
pub(crate) fn with_quota(
|
|
q: Option<Quota>,
|
|
s: BoxStream<'static, Result<StreamEvent>>,
|
|
) -> BoxStream<'static, Result<StreamEvent>> {
|
|
use futures::StreamExt;
|
|
futures::stream::iter(q.map(|q| Ok(StreamEvent::Quota(q))))
|
|
.chain(s)
|
|
.boxed()
|
|
}
|
|
|
|
pub(crate) fn hdr<'a>(h: &'a reqwest::header::HeaderMap, k: &str) -> Option<&'a str> {
|
|
h.get(k)?
|
|
.to_str()
|
|
.ok()
|
|
.map(str::trim)
|
|
.filter(|v| !v.is_empty())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use serde_json::json;
|
|
|
|
#[test]
|
|
fn round_trip() {
|
|
let m = Message {
|
|
role: Role::Assistant,
|
|
content: vec![
|
|
ContentBlock::Text { text: "hi".into() },
|
|
ContentBlock::ToolUse {
|
|
id: "t1".into(),
|
|
name: "read".into(),
|
|
input: json!({"path": "a"}),
|
|
},
|
|
ContentBlock::ToolResult {
|
|
tool_use_id: "t1".into(),
|
|
content: "x".into(),
|
|
is_error: false,
|
|
},
|
|
],
|
|
};
|
|
let s = serde_json::to_string(&m).unwrap();
|
|
assert_eq!(serde_json::from_str::<Message>(&s).unwrap(), m);
|
|
let e = StreamEvent::Done {
|
|
message: m,
|
|
stop: StopReason::ToolUse,
|
|
usage: Usage::default(),
|
|
};
|
|
let s = serde_json::to_string(&e).unwrap();
|
|
assert_eq!(serde_json::from_str::<StreamEvent>(&s).unwrap(), e);
|
|
}
|
|
|
|
#[test]
|
|
fn cost() {
|
|
let u = Usage {
|
|
input_tokens: 1_000_000,
|
|
output_tokens: 500_000,
|
|
..Default::default()
|
|
};
|
|
let p = Pricing {
|
|
input: 3.0,
|
|
output: 15.0,
|
|
..Default::default()
|
|
};
|
|
assert!((u.cost(&p) - 10.5).abs() < 1e-9);
|
|
}
|
|
}
|