harness_core/model.rs
1use crate::{Context, error::ModelError};
2use async_trait::async_trait;
3use serde::{Deserialize, Serialize};
4
5/// Information about a configured model — uniform across providers.
6///
7/// `handle` is the user-chosen logical identifier (used in logs, metrics,
8/// and `harness.toml` selectors); `model` is the wire-protocol model id
9/// sent to the provider.
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct ModelInfo {
12 pub handle: String,
13 pub provider: String,
14 pub model: String,
15 pub context_window: u32,
16 pub input_cost_usd_per_million_tokens: Option<f64>,
17 pub output_cost_usd_per_million_tokens: Option<f64>,
18 pub supports_tool_use: bool,
19 pub supports_streaming: bool,
20 /// Whether the provider will answer from live web results using its own
21 /// built-in search (Gemini's `google_search`, and friends). Distinct from
22 /// `supports_tool_use`: this is search the provider runs server-side, not a
23 /// tool we hand it.
24 #[serde(default)]
25 pub supports_web_grounding: bool,
26}
27
28#[derive(Debug, Clone, Default, Serialize, Deserialize)]
29pub struct ModelOutput {
30 pub text: Option<String>,
31 pub tool_calls: Vec<ToolCall>,
32 pub usage: Usage,
33 pub stop_reason: StopReason,
34 /// Provider-specific reasoning trace (DeepSeek `reasoning_content`,
35 /// Anthropic `thinking` blocks). Pushed back to the API verbatim on
36 /// subsequent calls; required by providers that gate on it.
37 #[serde(default, skip_serializing_if = "Option::is_none")]
38 pub reasoning: Option<String>,
39 /// Images the model emitted this turn. Empty for text-only models.
40 ///
41 /// Populated from the OpenAI-compatible `message.images[]` channel, which
42 /// is how Gemini image models answer through a chat endpoint. Before this
43 /// field existed those images were silently discarded by serde and the
44 /// caller saw only `text: None` — an empty answer with no way to learn
45 /// why.
46 #[serde(default, skip_serializing_if = "Vec::is_empty")]
47 pub images: Vec<crate::image::GeneratedImage>,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct ToolCall {
52 pub id: String,
53 pub name: String,
54 pub args: serde_json::Value,
55}
56
57#[derive(Debug, Clone, Default, Serialize, Deserialize)]
58pub struct Usage {
59 pub input_tokens: u32,
60 pub output_tokens: u32,
61 pub cached_input_tokens: u32,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
65#[serde(rename_all = "snake_case")]
66#[non_exhaustive]
67pub enum StopReason {
68 #[default]
69 EndTurn,
70 ToolUse,
71 MaxTokens,
72 StopSequence,
73 Other,
74}
75
76/// Streaming delta — incremental output from the model.
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[non_exhaustive]
79pub enum ModelDelta {
80 Text(String),
81 ToolCallStart {
82 id: String,
83 name: String,
84 },
85 ToolCallArgs {
86 id: String,
87 partial_json: String,
88 },
89 ToolCallEnd {
90 id: String,
91 },
92 Usage(Usage),
93 Stop(StopReason),
94 /// Provider-specific reasoning trace that must round-trip on the next
95 /// request. DeepSeek thinking content, Anthropic thinking blocks, and
96 /// Gemini raw `parts` (with thoughtSignatures) all flow through this —
97 /// the AgentLoop folds them into the final `ModelOutput.reasoning`
98 /// without surfacing them to user-visible token streams.
99 Reasoning(String),
100}
101
102#[async_trait]
103pub trait Model: Send + Sync + 'static {
104 async fn complete(&self, ctx: &Context) -> Result<ModelOutput, ModelError>;
105
106 /// Answer `query` from live web results, using the provider's OWN search.
107 ///
108 /// Returns `None` when the provider has no such thing, which is the default
109 /// — callers fall back to a search index. The answer comes back as prose
110 /// with its sources, not as a result list, because that is what these
111 /// providers return.
112 ///
113 /// Why it is a separate call rather than a tool the loop can pick: the
114 /// providers that offer built-in search generally refuse to accept it in
115 /// the same request as function declarations. Gemini answers *"Please
116 /// enable tool_config.include_server_side_tool_invocations to use Built-in
117 /// tools with Function calling"*, and OpenAI-compatible gateways in front
118 /// of it usually drop that switch. So grounding has to happen in its own
119 /// tool-free request, and hiding that here keeps every caller from
120 /// rediscovering it.
121 async fn search_web(&self, query: &str) -> Option<Result<String, ModelError>> {
122 let _ = query;
123 None
124 }
125
126 /// Streaming is optional; default implementation falls back to `complete`.
127 async fn stream(
128 &self,
129 ctx: &Context,
130 ) -> Result<futures::stream::BoxStream<'static, Result<ModelDelta, ModelError>>, ModelError>
131 {
132 let out = self.complete(ctx).await?;
133 let deltas: Vec<Result<ModelDelta, ModelError>> = out
134 .text
135 .into_iter()
136 .map(|t| Ok(ModelDelta::Text(t)))
137 .chain(std::iter::once(Ok(ModelDelta::Stop(out.stop_reason))))
138 .collect();
139 Ok(Box::pin(futures::stream::iter(deltas)))
140 }
141
142 fn info(&self) -> ModelInfo;
143}
144
145/// A concrete newtype wrapping a boxed model, so an `Arc<dyn Model>` can be used
146/// where a concrete `M: Model` is required (e.g. `Subagent::new` / `AgentLoop<M>`).
147///
148/// We deliberately do NOT `impl Model for Arc<dyn Model>` directly. Doing so
149/// changes `.stream()` method resolution on EVERY `Arc<dyn Model>` value in the
150/// program (from a deref to `dyn Model` into the Arc impl's `async fn stream`
151/// RPITIT), and proving that boxed streaming future is `Send` inside a `Send`
152/// context (e.g. an axum handler driving the streaming loop) overflows the
153/// auto-trait solver (E0275). Wrapping in this concrete newtype gives callers
154/// `DynModel: Model` without touching resolution for bare `Arc<dyn Model>`.
155pub struct DynModel(pub std::sync::Arc<dyn Model>);
156
157#[async_trait]
158impl Model for DynModel {
159 async fn complete(&self, ctx: &Context) -> Result<ModelOutput, ModelError> {
160 self.0.complete(ctx).await
161 }
162 async fn stream(
163 &self,
164 ctx: &Context,
165 ) -> Result<futures::stream::BoxStream<'static, Result<ModelDelta, ModelError>>, ModelError>
166 {
167 self.0.stream(ctx).await
168 }
169 fn info(&self) -> ModelInfo {
170 self.0.info()
171 }
172 // Forwarded explicitly: the trait's default returns `None`, so leaning on
173 // it here would silently strip grounding from every boxed model — a
174 // capability the inner model advertises via `supports_web_grounding` and
175 // then could never deliver.
176 async fn search_web(&self, query: &str) -> Option<Result<String, ModelError>> {
177 self.0.search_web(query).await
178 }
179}
180
181#[cfg(test)]
182mod arc_model_tests {
183 use super::*;
184 use std::sync::Arc;
185
186 struct Dummy;
187
188 #[async_trait]
189 impl Model for Dummy {
190 async fn complete(&self, _ctx: &Context) -> Result<ModelOutput, ModelError> {
191 Ok(ModelOutput {
192 text: Some("ok".into()),
193 ..Default::default()
194 })
195 }
196 fn info(&self) -> ModelInfo {
197 ModelInfo {
198 handle: "dummy".into(),
199 provider: "test".into(),
200 model: "dummy".into(),
201 context_window: 8192,
202 input_cost_usd_per_million_tokens: None,
203 output_cost_usd_per_million_tokens: None,
204 supports_tool_use: false,
205 supports_streaming: false,
206 supports_web_grounding: false,
207 }
208 }
209 }
210
211 fn assert_is_model<M: Model>(_m: &M) {}
212
213 #[tokio::test]
214 async fn dyn_model_wrapper_is_a_model() {
215 let m: Arc<dyn Model> = Arc::new(Dummy);
216 let wrapped = DynModel(m);
217 assert_is_model(&wrapped); // compiles only if DynModel: Model
218 let out = wrapped
219 .complete(&Context::new(crate::Task {
220 description: "x".into(),
221 source: None,
222 deadline: None,
223 }))
224 .await
225 .unwrap();
226 assert_eq!(out.text.as_deref(), Some("ok"));
227 }
228}