1 //! Inference backend abstraction.
2 //!
3 //! The agent loop only needs to send a turn (optionally with tools) and return
4 //! tool results. This module defines that seam as the `InferenceBackend` trait
5 //! plus a few neutral types, with two implementations:
6 //!
7 //! - `LocalBackend` runs on-device through the `onde` crate (`ChatEngine`).
8 //! - `OpenAiBackend` talks to any OpenAI-compatible HTTP endpoint, configured by
9 //! `base_url`, `api_key`, and `model`.
10 //!
11 //! The trait exposes neither `onde` nor OpenAI types, so the loop does not depend
12 //! on a specific backend.
13 //!
14 //! The seam is consumed by both surfaces: the interactive client (`#[cfg(unix)]`,
15 //! see `run_interactive` in `main.rs` and `mod tui` in `chat.rs`) and the ACP
16 //! server's prompt loop. Some items are still reached only through the
17 //! Unix-only interactive paths, so the dead-code lint stays suppressed on
18 //! non-Unix targets only — Unix builds keep full coverage.
19 #![cfg_attr(not(unix), allow(dead_code))]
20
21 use std::sync::Arc;
22
23 use async_trait::async_trait;
24 use onde::inference::{ChatEngine, ChatMessage, ChatRole, ToolDefinition};
25 use serde::Deserialize;
26 use tokio::sync::Mutex;
27
28 // ── Neutral types ───────────────────────────────────────────────────────────────
29
30 /// A tool the model may call, in a provider-neutral form. `parameters_schema` is
31 /// a JSON Schema encoded as a string (matching how siGit already declares tools).
32 #[derive(Debug, Clone)]
33 pub struct ToolSpec {
34 pub name: String,
35 pub description: String,
36 pub parameters_schema: String,
37 }
38
39 /// A tool call requested by the model.
40 #[derive(Debug, Clone)]
41 pub struct ToolCall {
42 pub id: String,
43 pub name: String,
44 /// Arguments as a JSON-encoded string.
45 pub arguments: String,
46 }
47
48 /// The output of executing one tool call, fed back to the model.
49 #[derive(Debug, Clone)]
50 pub struct ToolResult {
51 pub tool_call_id: String,
52 pub content: String,
53 }
54
55 /// The result of one assistant turn: free text and/or tool calls.
56 #[derive(Debug, Clone, Default)]
57 pub struct TurnResult {
58 pub text: String,
59 pub tool_calls: Vec<ToolCall>,
60 }
61
62 /// Backend errors are plain strings. Callers map them to ACP errors.
63 pub type BackendError = String;
64
65 /// Rough context budget for a conversation, in estimated tokens (see
66 /// [`estimate_tokens`]). When a snapshot exceeds this, the agent loops compact
67 /// history before the next tool round.
68 pub const DEFAULT_CONTEXT_TOKEN_BUDGET: usize = 24_000;
69
70 /// How many trailing messages survive a compaction verbatim (the rest are
71 /// folded into the summary).
72 pub const COMPACT_KEEP_LAST: usize = 6;
73
74 /// The summarization request sent to the model when compacting history.
75 const SUMMARIZE_PROMPT: &str = "Summarize this coding session so far: decisions made, \
76 files touched, current state, open items. Be concise and factual.";
77
78 /// Crude token estimate for a history snapshot: serialized characters / 4.
79 /// Deliberately model-agnostic — it only needs to be in the right ballpark to
80 /// decide when compaction is worth an extra inference round.
81 pub fn estimate_tokens(history: &[serde_json::Value]) -> usize {
82 let chars: usize = history
83 .iter()
84 .map(|message| message.to_string().chars().count())
85 .sum();
86 chars / 4
87 }
88
89 /// A sink for streaming assistant text deltas to the UI as they are produced.
90 ///
91 /// When a caller passes `Some(sink)`, a streaming-capable backend forwards each
92 /// text fragment through it as the model emits it; the returned [`TurnResult`]
93 /// still carries the fully assembled text (and any tool calls). When the sink is
94 /// `None`, the backend runs in non-streaming mode. Unbounded so the inference
95 /// task never blocks on a slow consumer.
96 pub type TokenSink = tokio::sync::mpsc::UnboundedSender<String>;
97
98 // ── The trait ───────────────────────────────────────────────────────────────────
99
100 /// A swappable inference backend driving siGit Code's agent loop.
101 #[async_trait]
102 pub trait InferenceBackend: Send + Sync {
103 /// Start an assistant turn from a new user message, offering `tools`.
104 ///
105 /// If `sink` is `Some`, text is streamed through it as it is generated. A
106 /// backend may decline to stream a given round (for example, on-device
107 /// inference cannot stream while it is still deciding whether to call a
108 /// tool); in that case the text is delivered only via the returned result.
109 async fn send_message_with_tools(
110 &self,
111 text: &str,
112 tools: &[ToolSpec],
113 sink: Option<&TokenSink>,
114 ) -> Result<TurnResult, BackendError>;
115
116 /// Continue the turn by returning tool results. `tools` may be `None` on the
117 /// final round to force a text answer. `sink` streams that text when set.
118 async fn send_tool_results(
119 &self,
120 results: Vec<ToolResult>,
121 tools: Option<&[ToolSpec]>,
122 sink: Option<&TokenSink>,
123 ) -> Result<TurnResult, BackendError>;
124
125 /// Record tool results in the conversation history *without* asking the
126 /// model to continue the turn. Used when a turn is abandoned mid-round
127 /// (the user cancelled at the permission gate): by then the assistant
128 /// message carrying the tool calls is already in history, and leaving them
129 /// unanswered makes strict OpenAI-compatible endpoints reject every later
130 /// request in the session.
131 async fn record_cancelled_tool_results(&self, results: Vec<ToolResult>);
132
133 /// Whether inference runs over the network (a configured provider) rather
134 /// than on-device. Drives UI labelling so the displayed model can't claim a
135 /// local model while requests actually go to the cloud.
136 fn is_remote(&self) -> bool;
137
138 /// A serializable snapshot of the conversation history, one JSON object per
139 /// message (`{"role": ..., "content": ...}` at minimum). The snapshot is
140 /// what the session store persists; it includes any seeded system message
141 /// so [`InferenceBackend::restore_history`] can replace state wholesale.
142 async fn history_snapshot(&self) -> Vec<serde_json::Value>;
143
144 /// Replace the conversation history with a previously saved snapshot.
145 /// Backends that cannot represent every entry (e.g. on-device history has
146 /// no tool-call structure) flatten what they can and drop the rest.
147 async fn restore_history(&self, history: Vec<serde_json::Value>);
148
149 /// Shrink the conversation history: summarize everything so far with one
150 /// extra (non-streaming) inference round, then rebuild history as
151 /// `[system message, summary, last keep_last non-system messages]`. On
152 /// error the original history is left in place.
153 async fn compact_history(&self, keep_last: usize) -> Result<(), BackendError>;
154 }
155
156 // ── Local backend (onde ChatEngine) ──────────────────────────────────────────────
157
158 /// On-device inference. A thin adapter over `onde::ChatEngine`.
159 pub struct LocalBackend {
160 engine: Arc<ChatEngine>,
161 }
162
163 impl LocalBackend {
164 pub fn new(engine: Arc<ChatEngine>) -> Self {
165 Self { engine }
166 }
167 }
168
169 fn to_onde_tools(tools: &[ToolSpec]) -> Vec<ToolDefinition> {
170 tools
171 .iter()
172 .map(|tool| ToolDefinition {
173 name: tool.name.clone(),
174 description: tool.description.clone(),
175 parameters_schema: tool.parameters_schema.clone(),
176 })
177 .collect()
178 }
179
180 #[async_trait]
181 impl InferenceBackend for LocalBackend {
182 async fn send_message_with_tools(
183 &self,
184 text: &str,
185 tools: &[ToolSpec],
186 sink: Option<&TokenSink>,
187 ) -> Result<TurnResult, BackendError> {
188 // onde's tool-aware path is non-streaming: it has to buffer the whole
189 // reply to detect tool calls. We can only stream when no tools are on
190 // offer (a plain answer), which is exactly the tools-disabled case.
191 if let Some(sink) = sink
192 && tools.is_empty()
193 {
194 let rx = self
195 .engine
196 .stream_message(text)
197 .await
198 .map_err(|error| error.to_string())?;
199 return drain_onde_stream(rx, sink).await;
200 }
201
202 let onde_tools = to_onde_tools(tools);
203 let result = self
204 .engine
205 .send_message_with_tools(text, &onde_tools)
206 .await
207 .map_err(|error| error.to_string())?;
208 Ok(onde_result_to_turn(result))
209 }
210
211 async fn send_tool_results(
212 &self,
213 results: Vec<ToolResult>,
214 tools: Option<&[ToolSpec]>,
215 sink: Option<&TokenSink>,
216 ) -> Result<TurnResult, BackendError> {
217 let onde_results: Vec<onde::inference::ToolResult> = results
218 .into_iter()
219 .map(|result| onde::inference::ToolResult {
220 tool_call_id: result.tool_call_id,
221 content: result.content,
222 })
223 .collect();
224
225 // The final round passes `tools = None` to force a text answer; that's
226 // the only round onde can stream, since no further tool calls are parsed.
227 if let Some(sink) = sink
228 && tools.is_none()
229 {
230 let rx = self
231 .engine
232 .stream_tool_results(onde_results, None)
233 .await
234 .map_err(|error| error.to_string())?;
235 return drain_onde_stream(rx, sink).await;
236 }
237
238 let onde_tools = tools.map(to_onde_tools);
239 let result = self
240 .engine
241 .send_tool_results(onde_results, onde_tools.as_deref())
242 .await
243 .map_err(|error| error.to_string())?;
244 Ok(onde_result_to_turn(result))
245 }
246
247 async fn record_cancelled_tool_results(&self, _results: Vec<ToolResult>) {
248 // onde's public API cannot append tool-result history entries without
249 // running another inference round, so the dangling tool call stays in
250 // its history. The chat template replays it as-is, which local models
251 // tolerate — worst case the model re-issues the call next turn.
252 }
253
254 fn is_remote(&self) -> bool {
255 false
256 }
257
258 async fn history_snapshot(&self) -> Vec<serde_json::Value> {
259 // onde's `history()` already flattens tool entries: assistant tool
260 // calls become plain assistant text and tool results are omitted, so
261 // the snapshot is lossy for tool-heavy turns (acceptable in this MVP).
262 self.engine
263 .history()
264 .await
265 .iter()
266 .map(|message| {
267 serde_json::json!({
268 "role": message.role.to_string(),
269 "content": message.content,
270 })
271 })
272 .collect()
273 }
274
275 async fn restore_history(&self, history: Vec<serde_json::Value>) {
276 self.engine.clear_history().await;
277 for entry in history {
278 let role = entry["role"].as_str().unwrap_or("");
279 let content = entry["content"].as_str().unwrap_or("").to_string();
280 // Tool-call-only assistant entries and empty tool results carry no
281 // text a plain chat history can replay; drop them.
282 if content.is_empty() && role != "user" && role != "system" {
283 continue;
284 }
285 let message = match role {
286 "system" => ChatMessage::system(content),
287 "user" => ChatMessage::user(content),
288 "assistant" => ChatMessage::assistant(content),
289 // Tool results flatten to plain text (MVP; acceptable loss).
290 "tool" => ChatMessage::user(format!("[tool result]\n{content}")),
291 _ => continue,
292 };
293 self.engine.push_history(message).await;
294 }
295 }
296
297 async fn compact_history(&self, keep_last: usize) -> Result<(), BackendError> {
298 let snapshot = self.engine.history().await;
299 // One plain (tool-free) inference round produces the summary. On error
300 // history is untouched — send_message only mutates it on success, and
301 // whatever it appended is wiped by the clear below anyway.
302 let result = self
303 .engine
304 .send_message(SUMMARIZE_PROMPT)
305 .await
306 .map_err(|error| error.to_string())?;
307 // Local models may reason in <think> blocks; keep only the visible part.
308 let (_think, summary) = crate::chat::strip_think_blocks(&result.text);
309
310 self.engine.clear_history().await;
311 // Leading system messages carry the session context; keep them all.
312 for message in snapshot
313 .iter()
314 .take_while(|message| message.role == ChatRole::System)
315 {
316 self.engine.push_history(message.clone()).await;
317 }
318 self.engine
319 .push_history(ChatMessage::user(format!(
320 "[Conversation summary]\n{summary}"
321 )))
322 .await;
323 let non_system: Vec<&ChatMessage> = snapshot
324 .iter()
325 .filter(|message| message.role != ChatRole::System)
326 .collect();
327 let tail_start = non_system.len().saturating_sub(keep_last);
328 for message in &non_system[tail_start..] {
329 self.engine.push_history((*message).clone()).await;
330 }
331 Ok(())
332 }
333 }
334
335 /// Drain an onde streaming receiver, forwarding each token to `sink` and
336 /// assembling the full text. onde reports stream failures as a final chunk whose
337 /// `finish_reason` is `"error: …"`; surface those as a backend error.
338 async fn drain_onde_stream(
339 mut rx: tokio::sync::mpsc::Receiver<onde::inference::StreamChunk>,
340 sink: &TokenSink,
341 ) -> Result<TurnResult, BackendError> {
342 let mut text = String::new();
343 while let Some(chunk) = rx.recv().await {
344 if !chunk.delta.is_empty() {
345 text.push_str(&chunk.delta);
346 // The receiver is the UI; if it's gone the turn is being cancelled,
347 // so stop assembling rather than spinning the model to completion.
348 if sink.send(chunk.delta).is_err() {
349 break;
350 }
351 }
352 if chunk.done {
353 if let Some(reason) = chunk.finish_reason
354 && let Some(message) = reason.strip_prefix("error: ")
355 {
356 return Err(message.to_string());
357 }
358 break;
359 }
360 }
361 Ok(TurnResult {
362 text,
363 tool_calls: Vec::new(),
364 })
365 }
366
367 /// Convert an `onde` tool-aware result into the neutral [`TurnResult`].
368 fn onde_result_to_turn(result: onde::inference::ToolAwareResult) -> TurnResult {
369 TurnResult {
370 text: result.text,
371 tool_calls: result
372 .tool_calls
373 .into_iter()
374 .map(|call| ToolCall {
375 id: call.id,
376 name: call.function_name,
377 arguments: call.arguments,
378 })
379 .collect(),
380 }
381 }
382
383 // ── OpenAI-compatible backend ─────────────────────────────────────────────────────
384
385 /// Inference against any OpenAI-compatible Chat Completions endpoint.
386 ///
387 /// Conversation state is held client-side and replayed on every request, so the
388 /// endpoint can be stateless. Standard OpenAI function-calling is used end to
389 /// end (`tools`, `choices[].message.tool_calls`, `role: "tool"` follow-ups).
390 pub struct OpenAiBackend {
391 base_url: String,
392 api_key: String,
393 model: String,
394 http: reqwest::Client,
395 /// The full message list sent on each request (system + turns + tool results).
396 history: Mutex<Vec<serde_json::Value>>,
397 }
398
399 impl OpenAiBackend {
400 /// Build a backend for `{base_url, api_key, model}`, seeding the optional
401 /// system prompt. `base_url` should include the API root (e.g. ending in
402 /// `/v1`); the chat path is appended.
403 pub fn new(
404 base_url: impl Into<String>,
405 api_key: impl Into<String>,
406 model: impl Into<String>,
407 system_prompt: Option<String>,
408 ) -> Self {
409 let mut history = Vec::new();
410 if let Some(prompt) = system_prompt {
411 history.push(serde_json::json!({ "role": "system", "content": prompt }));
412 }
413 Self {
414 base_url: base_url.into(),
415 api_key: api_key.into(),
416 model: model.into(),
417 http: reqwest::Client::new(),
418 history: Mutex::new(history),
419 }
420 }
421
422 fn tools_json(tools: &[ToolSpec]) -> Vec<serde_json::Value> {
423 tools
424 .iter()
425 .map(|tool| {
426 // parameters_schema is a JSON string; parse it, defaulting to an
427 // empty object schema if malformed.
428 let parameters: serde_json::Value = serde_json::from_str(&tool.parameters_schema)
429 .unwrap_or_else(|_| serde_json::json!({ "type": "object", "properties": {} }));
430 serde_json::json!({
431 "type": "function",
432 "function": {
433 "name": tool.name,
434 "description": tool.description,
435 "parameters": parameters,
436 }
437 })
438 })
439 .collect()
440 }
441
442 /// POST the current history (plus `tools`) and apply the assistant reply to
443 /// history, returning the neutral turn result. Streams via SSE when `sink`
444 /// is set; otherwise reads a single JSON response.
445 async fn complete(
446 &self,
447 tools: Option<&[ToolSpec]>,
448 sink: Option<&TokenSink>,
449 ) -> Result<TurnResult, BackendError> {
450 let url = format!("{}/chat/completions", self.base_url.trim_end_matches('/'));
451 let streaming = sink.is_some();
452
453 let mut body = serde_json::json!({
454 "model": self.model,
455 "messages": *self.history.lock().await,
456 "stream": streaming,
457 });
458 if let Some(tools) = tools
459 && !tools.is_empty()
460 {
461 body["tools"] = serde_json::Value::Array(Self::tools_json(tools));
462 // OpenAI specifies `auto` as the default when tools are present,
463 // but not every OpenAI-compatible gateway implements that default.
464 // Sending it explicitly is important for the cloud path: otherwise
465 // a model can describe the action it intends to take as text and
466 // end the turn without returning a tool call at all.
467 body["tool_choice"] = serde_json::Value::String("auto".to_string());
468 }
469
470 let response = self
471 .http
472 .post(&url)
473 .bearer_auth(&self.api_key)
474 .json(&body)
475 .send()
476 .await
477 .map_err(|error| format!("request to {url} failed: {error}"))?;
478
479 if !response.status().is_success() {
480 let status = response.status();
481 let detail = response.text().await.unwrap_or_default();
482 return Err(format!("endpoint returned {status}: {detail}"));
483 }
484
485 if let Some(sink) = sink {
486 self.consume_stream(response, sink).await
487 } else {
488 self.consume_json(response).await
489 }
490 }
491
492 /// Parse a single non-streaming chat-completion response.
493 async fn consume_json(&self, response: reqwest::Response) -> Result<TurnResult, BackendError> {
494 let parsed: ChatCompletion = response
495 .json()
496 .await
497 .map_err(|error| format!("response parse error: {error}"))?;
498
499 let message = parsed
500 .choices
501 .into_iter()
502 .next()
503 .map(|choice| choice.message)
504 .ok_or_else(|| "endpoint returned no choices".to_string())?;
505
506 let text = message.content.clone().unwrap_or_default();
507 let tool_calls: Vec<ToolCall> = message
508 .tool_calls
509 .iter()
510 .flatten()
511 .map(|call| ToolCall {
512 id: call.id.clone(),
513 name: call.function.name.clone(),
514 arguments: call.function.arguments.clone(),
515 })
516 .collect();
517
518 // Record the assistant turn so later tool results have context.
519 self.history.lock().await.push(message.into_history_value());
520
521 Ok(TurnResult { text, tool_calls })
522 }
523
524 /// Consume an OpenAI Server-Sent Events stream, forwarding content deltas to
525 /// `sink` and reassembling any tool calls (which arrive fragmented across
526 /// chunks, keyed by `index`).
527 async fn consume_stream(
528 &self,
529 response: reqwest::Response,
530 sink: &TokenSink,
531 ) -> Result<TurnResult, BackendError> {
532 use futures::StreamExt;
533
534 let mut stream = response.bytes_stream();
535 // Newlines are ASCII, so splitting raw bytes on `\n` never bisects a
536 // multibyte UTF-8 sequence; we only lossily decode whole lines.
537 let mut buffer: Vec<u8> = Vec::new();
538 let mut text = String::new();
539 let mut tool_accum: Vec<StreamingToolCall> = Vec::new();
540 let mut done = false;
541
542 while let Some(item) = stream.next().await {
543 let bytes = item.map_err(|error| format!("stream read error: {error}"))?;
544 buffer.extend_from_slice(&bytes);
545
546 while let Some(pos) = buffer.iter().position(|&b| b == b'\n') {
547 let line: Vec<u8> = buffer.drain(..=pos).collect();
548 let line = String::from_utf8_lossy(&line);
549 let line = line.trim();
550
551 let Some(data) = line.strip_prefix("data:") else {
552 continue;
553 };
554 let data = data.trim();
555 if data == "[DONE]" {
556 done = true;
557 break;
558 }
559 if data.is_empty() {
560 continue;
561 }
562
563 let chunk: StreamCompletion = match serde_json::from_str(data) {
564 Ok(chunk) => chunk,
565 // Skip keep-alive comments and anything we can't parse rather
566 // than aborting a turn over one malformed frame.
567 Err(_) => continue,
568 };
569
570 let Some(choice) = chunk.choices.into_iter().next() else {
571 continue;
572 };
573 if let Some(content) = choice.delta.content
574 && !content.is_empty()
575 {
576 text.push_str(&content);
577 if sink.send(content).is_err() {
578 // Consumer dropped (turn cancelled) — stop reading.
579 done = true;
580 break;
581 }
582 }
583 for delta in choice.delta.tool_calls.into_iter().flatten() {
584 let index = delta.index.unwrap_or(0) as usize;
585 if tool_accum.len() <= index {
586 tool_accum.resize_with(index + 1, StreamingToolCall::default);
587 }
588 let slot = &mut tool_accum[index];
589 if let Some(id) = delta.id {
590 slot.id = id;
591 }
592 if let Some(function) = delta.function {
593 if let Some(name) = function.name {
594 slot.name = name;
595 }
596 if let Some(arguments) = function.arguments {
597 slot.arguments.push_str(&arguments);
598 }
599 }
600 }
601 }
602
603 if done {
604 break;
605 }
606 }
607
608 let tool_calls: Vec<ToolCall> = tool_accum
609 .iter()
610 .filter(|call| !call.name.is_empty())
611 .enumerate()
612 .map(|(index, call)| ToolCall {
613 id: if call.id.is_empty() {
614 format!("call_{index}")
615 } else {
616 call.id.clone()
617 },
618 name: call.name.clone(),
619 arguments: call.arguments.clone(),
620 })
621 .collect();
622
623 // Record the assistant turn so later tool results have context.
624 self.history
625 .lock()
626 .await
627 .push(streamed_assistant_history(&text, &tool_calls));
628
629 Ok(TurnResult { text, tool_calls })
630 }
631 }
632
633 /// One tool call being reassembled from streamed deltas.
634 #[derive(Default)]
635 struct StreamingToolCall {
636 id: String,
637 name: String,
638 arguments: String,
639 }
640
641 /// Rebuild the assistant message for replay in history after a streamed turn,
642 /// preserving any tool calls so the follow-up request is well-formed. Mirrors
643 /// [`ResponseMessage::into_history_value`] for the non-streaming path.
644 fn streamed_assistant_history(text: &str, tool_calls: &[ToolCall]) -> serde_json::Value {
645 let mut message = serde_json::json!({ "role": "assistant" });
646 message["content"] = if text.is_empty() {
647 serde_json::Value::Null
648 } else {
649 serde_json::Value::String(text.to_string())
650 };
651 if !tool_calls.is_empty() {
652 message["tool_calls"] = serde_json::json!(
653 tool_calls
654 .iter()
655 .map(|call| serde_json::json!({
656 "id": call.id,
657 "type": "function",
658 "function": {
659 "name": call.name,
660 "arguments": call.arguments,
661 }
662 }))
663 .collect::<Vec<_>>()
664 );
665 }
666 message
667 }
668
669 #[async_trait]
670 impl InferenceBackend for OpenAiBackend {
671 async fn send_message_with_tools(
672 &self,
673 text: &str,
674 tools: &[ToolSpec],
675 sink: Option<&TokenSink>,
676 ) -> Result<TurnResult, BackendError> {
677 self.history
678 .lock()
679 .await
680 .push(serde_json::json!({ "role": "user", "content": text }));
681 self.complete(Some(tools), sink).await
682 }
683
684 async fn send_tool_results(
685 &self,
686 results: Vec<ToolResult>,
687 tools: Option<&[ToolSpec]>,
688 sink: Option<&TokenSink>,
689 ) -> Result<TurnResult, BackendError> {
690 {
691 let mut history = self.history.lock().await;
692 for result in results {
693 history.push(serde_json::json!({
694 "role": "tool",
695 "tool_call_id": result.tool_call_id,
696 "content": result.content,
697 }));
698 }
699 }
700 self.complete(tools, sink).await
701 }
702
703 async fn record_cancelled_tool_results(&self, results: Vec<ToolResult>) {
704 let mut history = self.history.lock().await;
705 for result in results {
706 history.push(serde_json::json!({
707 "role": "tool",
708 "tool_call_id": result.tool_call_id,
709 "content": result.content,
710 }));
711 }
712 }
713
714 fn is_remote(&self) -> bool {
715 true
716 }
717
718 async fn history_snapshot(&self) -> Vec<serde_json::Value> {
719 self.history.lock().await.clone()
720 }
721
722 async fn restore_history(&self, history: Vec<serde_json::Value>) {
723 // The snapshot includes the seeded system message, so a wholesale
724 // replacement restores exactly what was saved.
725 *self.history.lock().await = history;
726 }
727
728 async fn compact_history(&self, keep_last: usize) -> Result<(), BackendError> {
729 let snapshot: Vec<serde_json::Value> = self.history.lock().await.clone();
730
731 // Ask the endpoint for a summary of the conversation so far, through
732 // the ordinary completion machinery (non-streaming).
733 self.history
734 .lock()
735 .await
736 .push(serde_json::json!({ "role": "user", "content": SUMMARIZE_PROMPT }));
737 let summary = match self.complete(None, None).await {
738 Ok(result) => result.text,
739 Err(error) => {
740 // Roll back the summarization request; the turn never happened.
741 *self.history.lock().await = snapshot;
742 return Err(error);
743 }
744 };
745
746 let system = snapshot
747 .first()
748 .filter(|message| message["role"] == "system")
749 .cloned();
750 let non_system: Vec<serde_json::Value> = snapshot
751 .iter()
752 .filter(|message| message["role"] != "system")
753 .cloned()
754 .collect();
755 let tail_start = non_system.len().saturating_sub(keep_last);
756 let mut tail = non_system[tail_start..].to_vec();
757 // Drop leading tool results whose assistant tool-call message was
758 // summarized away — strict endpoints reject orphaned `role: "tool"`
759 // entries on the very next request.
760 while tail
761 .first()
762 .is_some_and(|message| message["role"] == "tool")
763 {
764 tail.remove(0);
765 }
766
767 let mut rebuilt = Vec::new();
768 if let Some(system) = system {
769 rebuilt.push(system);
770 }
771 rebuilt.push(serde_json::json!({
772 "role": "user",
773 "content": format!("[Conversation summary]\n{summary}"),
774 }));
775 rebuilt.extend(tail);
776 *self.history.lock().await = rebuilt;
777 Ok(())
778 }
779 }
780
781 // ── OpenAI response shapes ────────────────────────────────────────────────────────
782
783 #[derive(Debug, Deserialize)]
784 struct ChatCompletion {
785 #[serde(default)]
786 choices: Vec<CompletionChoice>,
787 }
788
789 #[derive(Debug, Deserialize)]
790 struct CompletionChoice {
791 message: ResponseMessage,
792 }
793
794 #[derive(Debug, Deserialize)]
795 struct ResponseMessage {
796 #[serde(default)]
797 content: Option<String>,
798 #[serde(default)]
799 tool_calls: Option<Vec<ResponseToolCall>>,
800 }
801
802 impl ResponseMessage {
803 /// Reconstruct the assistant message for replay in history, preserving any
804 /// tool calls so the follow-up request is well-formed.
805 fn into_history_value(self) -> serde_json::Value {
806 let mut message = serde_json::json!({ "role": "assistant" });
807 message["content"] = match self.content {
808 Some(text) => serde_json::Value::String(text),
809 None => serde_json::Value::Null,
810 };
811 if let Some(tool_calls) = self.tool_calls {
812 message["tool_calls"] = serde_json::json!(
813 tool_calls
814 .into_iter()
815 .map(|call| serde_json::json!({
816 "id": call.id,
817 "type": "function",
818 "function": {
819 "name": call.function.name,
820 "arguments": call.function.arguments,
821 }
822 }))
823 .collect::<Vec<_>>()
824 );
825 }
826 message
827 }
828 }
829
830 #[derive(Debug, Deserialize)]
831 struct ResponseToolCall {
832 id: String,
833 function: ResponseFunction,
834 }
835
836 #[derive(Debug, Deserialize)]
837 struct ResponseFunction {
838 name: String,
839 #[serde(default)]
840 arguments: String,
841 }
842
843 // ── OpenAI streaming (SSE) chunk shapes ─────────────────────────────────────────
844
845 #[derive(Debug, Deserialize)]
846 struct StreamCompletion {
847 #[serde(default)]
848 choices: Vec<StreamChoice>,
849 }
850
851 #[derive(Debug, Deserialize)]
852 struct StreamChoice {
853 #[serde(default)]
854 delta: StreamDelta,
855 }
856
857 #[derive(Debug, Default, Deserialize)]
858 struct StreamDelta {
859 #[serde(default)]
860 content: Option<String>,
861 #[serde(default)]
862 tool_calls: Option<Vec<StreamToolCallDelta>>,
863 }
864
865 #[derive(Debug, Deserialize)]
866 struct StreamToolCallDelta {
867 #[serde(default)]
868 index: Option<u32>,
869 #[serde(default)]
870 id: Option<String>,
871 #[serde(default)]
872 function: Option<StreamFunctionDelta>,
873 }
874
875 #[derive(Debug, Deserialize)]
876 struct StreamFunctionDelta {
877 #[serde(default)]
878 name: Option<String>,
879 #[serde(default)]
880 arguments: Option<String>,
881 }
882
883 // ── Carrying a conversation across a model switch ────────────────────────────
884
885 /// The part of a history snapshot that survives a model switch: every
886 /// non-system message, with half-finished tool plumbing repaired.
887 ///
888 /// System messages are dropped because the backend being switched *to* seeds
889 /// its own — a different model's prompt, or a freshly pushed session-context
890 /// message. A switch can land mid-turn, after the assistant asked for a tool
891 /// but before the results came back; a tool call with no matching result (or a
892 /// result with no matching call) makes strict OpenAI-compatible endpoints
893 /// reject every later request in the session, so those halves are stripped
894 /// instead of carried.
895 pub fn carryover_history(snapshot: Vec<serde_json::Value>) -> Vec<serde_json::Value> {
896 let answered: std::collections::HashSet<String> = snapshot
897 .iter()
898 .filter(|message| message["role"] == "tool")
899 .filter_map(|message| message["tool_call_id"].as_str().map(str::to_string))
900 .collect();
901
902 let mut carried: Vec<serde_json::Value> = Vec::with_capacity(snapshot.len());
903 let mut called: std::collections::HashSet<String> = std::collections::HashSet::new();
904
905 for mut message in snapshot {
906 match message["role"].as_str().unwrap_or_default() {
907 "system" => continue,
908 "assistant" => {
909 if let Some(calls) = message["tool_calls"].as_array() {
910 let kept: Vec<serde_json::Value> = calls
911 .iter()
912 .filter(|call| call["id"].as_str().is_some_and(|id| answered.contains(id)))
913 .cloned()
914 .collect();
915 if kept.is_empty() {
916 // Only unanswered requests: keep whatever text came
917 // with them, drop the message if there was none.
918 if let Some(object) = message.as_object_mut() {
919 object.remove("tool_calls");
920 }
921 if message["content"].as_str().unwrap_or_default().is_empty() {
922 continue;
923 }
924 } else {
925 for call in &kept {
926 called.insert(call["id"].as_str().unwrap_or_default().to_string());
927 }
928 message["tool_calls"] = serde_json::Value::Array(kept);
929 }
930 }
931 carried.push(message);
932 }
933 "tool" => {
934 let answers_a_kept_call = message["tool_call_id"]
935 .as_str()
936 .is_some_and(|id| called.contains(id));
937 if answers_a_kept_call {
938 carried.push(message);
939 }
940 }
941 _ => carried.push(message),
942 }
943 }
944
945 carried
946 }
947
948 /// Replay `carried` (from [`carryover_history`]) into `backend`, on top of the
949 /// system messages `backend` seeded for itself. Used when a model switch
950 /// installs a new backend — or reloads the on-device engine, which wipes its
951 /// history — so the thread continues under the new model instead of restarting.
952 pub async fn adopt_carryover(backend: &dyn InferenceBackend, carried: Vec<serde_json::Value>) {
953 if carried.is_empty() {
954 return;
955 }
956 let mut rebuilt: Vec<serde_json::Value> = backend
957 .history_snapshot()
958 .await
959 .into_iter()
960 .take_while(|message| message["role"] == "system")
961 .collect();
962 rebuilt.extend(carried);
963 backend.restore_history(rebuilt).await;
964 }
965
966 #[cfg(test)]
967 mod tests {
968 use super::*;
969
970 #[test]
971 fn tools_json_wraps_function_schema() {
972 let tools = vec![ToolSpec {
973 name: "read_file".to_string(),
974 description: "Read a file".to_string(),
975 parameters_schema: r#"{"type":"object","properties":{"path":{"type":"string"}}}"#
976 .to_string(),
977 }];
978 let json = OpenAiBackend::tools_json(&tools);
979 assert_eq!(json[0]["type"], "function");
980 assert_eq!(json[0]["function"]["name"], "read_file");
981 assert_eq!(
982 json[0]["function"]["parameters"]["properties"]["path"]["type"],
983 "string"
984 );
985 }
986
987 #[test]
988 fn malformed_schema_falls_back_to_empty_object() {
989 let tools = vec![ToolSpec {
990 name: "x".to_string(),
991 description: String::new(),
992 parameters_schema: "not json".to_string(),
993 }];
994 let json = OpenAiBackend::tools_json(&tools);
995 assert_eq!(json[0]["function"]["parameters"]["type"], "object");
996 }
997
998 #[test]
999 fn streamed_assistant_history_omits_empty_tool_calls() {
1000 let value = streamed_assistant_history("hello", &[]);
1001 assert_eq!(value["role"], "assistant");
1002 assert_eq!(value["content"], "hello");
1003 assert!(value.get("tool_calls").is_none());
1004 }
1005
1006 #[test]
1007 fn streamed_assistant_history_preserves_tool_calls() {
1008 let calls = vec![ToolCall {
1009 id: "call_0".to_string(),
1010 name: "read_file".to_string(),
1011 arguments: r#"{"path":"a.rs"}"#.to_string(),
1012 }];
1013 let value = streamed_assistant_history("", &calls);
1014 assert!(value["content"].is_null());
1015 assert_eq!(value["tool_calls"][0]["id"], "call_0");
1016 assert_eq!(value["tool_calls"][0]["type"], "function");
1017 assert_eq!(value["tool_calls"][0]["function"]["name"], "read_file");
1018 assert_eq!(
1019 value["tool_calls"][0]["function"]["arguments"],
1020 r#"{"path":"a.rs"}"#
1021 );
1022 }
1023
1024 #[tokio::test]
1025 async fn cancelled_tool_results_close_out_history() {
1026 let backend = OpenAiBackend::new("http://localhost", "", "test-model", None);
1027 backend
1028 .history
1029 .lock()
1030 .await
1031 .push(streamed_assistant_history(
1032 "",
1033 &[ToolCall {
1034 id: "call_9".to_string(),
1035 name: "run_command".to_string(),
1036 arguments: r#"{"command":"ls"}"#.to_string(),
1037 }],
1038 ));
1039
1040 backend
1041 .record_cancelled_tool_results(vec![ToolResult {
1042 tool_call_id: "call_9".to_string(),
1043 content: "cancelled by the user".to_string(),
1044 }])
1045 .await;
1046
1047 let history = backend.history.lock().await;
1048 let last = history.last().unwrap();
1049 assert_eq!(last["role"], "tool");
1050 assert_eq!(last["tool_call_id"], "call_9");
1051 assert_eq!(last["content"], "cancelled by the user");
1052 }
1053
1054 #[test]
1055 fn carryover_drops_system_messages_and_keeps_the_turns() {
1056 let snapshot = vec![
1057 serde_json::json!({ "role": "system", "content": "old prompt" }),
1058 serde_json::json!({ "role": "user", "content": "hello" }),
1059 serde_json::json!({ "role": "assistant", "content": "hi" }),
1060 ];
1061
1062 let carried = carryover_history(snapshot);
1063
1064 assert_eq!(carried.len(), 2);
1065 assert_eq!(carried[0]["role"], "user");
1066 assert_eq!(carried[1]["content"], "hi");
1067 }
1068
1069 #[test]
1070 fn carryover_strips_a_tool_call_that_never_got_a_result() {
1071 // Switching mid-turn: the assistant asked for a tool, nothing answered.
1072 let snapshot = vec![
1073 serde_json::json!({ "role": "user", "content": "read a.rs" }),
1074 streamed_assistant_history(
1075 "on it",
1076 &[ToolCall {
1077 id: "call_1".to_string(),
1078 name: "read_file".to_string(),
1079 arguments: "{}".to_string(),
1080 }],
1081 ),
1082 ];
1083
1084 let carried = carryover_history(snapshot);
1085
1086 assert_eq!(carried.len(), 2);
1087 assert_eq!(carried[1]["content"], "on it");
1088 assert!(
1089 carried[1].get("tool_calls").is_none(),
1090 "an unanswered tool call must not survive the switch"
1091 );
1092 }
1093
1094 #[test]
1095 fn carryover_drops_a_textless_unanswered_tool_call_and_its_late_result() {
1096 let snapshot = vec![
1097 streamed_assistant_history(
1098 "",
1099 &[ToolCall {
1100 id: "call_1".to_string(),
1101 name: "read_file".to_string(),
1102 arguments: "{}".to_string(),
1103 }],
1104 ),
1105 // An orphan: its assistant message is gone with the line above.
1106 serde_json::json!({
1107 "role": "tool",
1108 "tool_call_id": "call_other",
1109 "content": "file contents",
1110 }),
1111 ];
1112
1113 assert!(carryover_history(snapshot).is_empty());
1114 }
1115
1116 #[test]
1117 fn carryover_keeps_an_answered_tool_call_paired_with_its_result() {
1118 let snapshot = vec![
1119 streamed_assistant_history(
1120 "",
1121 &[ToolCall {
1122 id: "call_1".to_string(),
1123 name: "read_file".to_string(),
1124 arguments: "{}".to_string(),
1125 }],
1126 ),
1127 serde_json::json!({
1128 "role": "tool",
1129 "tool_call_id": "call_1",
1130 "content": "file contents",
1131 }),
1132 ];
1133
1134 let carried = carryover_history(snapshot);
1135
1136 assert_eq!(carried.len(), 2);
1137 assert_eq!(carried[0]["tool_calls"][0]["id"], "call_1");
1138 assert_eq!(carried[1]["tool_call_id"], "call_1");
1139 }
1140
1141 #[tokio::test]
1142 async fn adopt_carryover_replays_the_thread_under_the_new_system_prompt() {
1143 let new_backend =
1144 OpenAiBackend::new("http://localhost", "", "m", Some("new prompt".into()));
1145
1146 let carried = carryover_history(vec![
1147 serde_json::json!({ "role": "system", "content": "old prompt" }),
1148 serde_json::json!({ "role": "user", "content": "hello" }),
1149 serde_json::json!({ "role": "assistant", "content": "hi" }),
1150 ]);
1151 adopt_carryover(&new_backend, carried).await;
1152
1153 let history = new_backend.history_snapshot().await;
1154 assert_eq!(history.len(), 3);
1155 assert_eq!(history[0]["role"], "system");
1156 assert_eq!(history[0]["content"], "new prompt");
1157 assert_eq!(history[1]["content"], "hello");
1158 assert_eq!(history[2]["content"], "hi");
1159 }
1160
1161 #[tokio::test]
1162 async fn adopt_carryover_leaves_a_fresh_backend_alone() {
1163 let new_backend =
1164 OpenAiBackend::new("http://localhost", "", "m", Some("new prompt".into()));
1165
1166 adopt_carryover(&new_backend, Vec::new()).await;
1167
1168 let history = new_backend.history_snapshot().await;
1169 assert_eq!(history.len(), 1);
1170 assert_eq!(history[0]["content"], "new prompt");
1171 }
1172
1173 #[test]
1174 fn estimate_tokens_scales_with_serialized_size() {
1175 assert_eq!(estimate_tokens(&[]), 0);
1176
1177 let short = vec![serde_json::json!({ "role": "user", "content": "hi" })];
1178 let long = vec![serde_json::json!({ "role": "user", "content": "x".repeat(4_000) })];
1179 let short_estimate = estimate_tokens(&short);
1180 let long_estimate = estimate_tokens(&long);
1181
1182 assert!(short_estimate > 0, "non-empty history estimates > 0 tokens");
1183 assert!(long_estimate > short_estimate, "longer history costs more");
1184 // 4,000 content chars / 4 ≈ 1,000 tokens, plus a little JSON framing.
1185 assert!((1_000..1_100).contains(&long_estimate), "{long_estimate}");
1186 }
1187
1188 #[tokio::test]
1189 async fn openai_snapshot_restore_round_trips_exactly() {
1190 let backend = OpenAiBackend::new("http://localhost", "", "m", Some("be helpful".into()));
1191 {
1192 let mut history = backend.history.lock().await;
1193 history.push(serde_json::json!({ "role": "user", "content": "hello" }));
1194 history.push(streamed_assistant_history(
1195 "",
1196 &[ToolCall {
1197 id: "call_1".to_string(),
1198 name: "read_file".to_string(),
1199 arguments: r#"{"path":"a.rs"}"#.to_string(),
1200 }],
1201 ));
1202 history.push(serde_json::json!({
1203 "role": "tool", "tool_call_id": "call_1", "content": "fn main() {}",
1204 }));
1205 history.push(serde_json::json!({ "role": "assistant", "content": "done" }));
1206 }
1207 let snapshot = backend.history_snapshot().await;
1208 assert_eq!(
1209 snapshot[0]["role"], "system",
1210 "snapshot keeps the system message"
1211 );
1212
1213 // Restoring into a backend seeded with a *different* system prompt must
1214 // replace everything, including that seed.
1215 let restored = OpenAiBackend::new("http://localhost", "", "m", Some("other seed".into()));
1216 restored.restore_history(snapshot.clone()).await;
1217 assert_eq!(restored.history_snapshot().await, snapshot);
1218 }
1219
1220 /// Minimal scripted OpenAI-compatible endpoint: accepts one HTTP request on
1221 /// a std listener and answers with a fixed non-streaming completion.
1222 fn spawn_completion_stub(summary: &str) -> std::net::SocketAddr {
1223 use std::io::{Read, Write};
1224
1225 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1226 let addr = listener.local_addr().unwrap();
1227 let body = serde_json::json!({
1228 "choices": [{ "message": { "role": "assistant", "content": summary } }]
1229 })
1230 .to_string();
1231 std::thread::spawn(move || {
1232 let (mut stream, _) = listener.accept().unwrap();
1233 // Read until the full request (headers + content-length body) is in.
1234 let mut request = Vec::new();
1235 let mut chunk = [0u8; 4096];
1236 loop {
1237 let n = stream.read(&mut chunk).unwrap_or(0);
1238 if n == 0 {
1239 break;
1240 }
1241 request.extend_from_slice(&chunk[..n]);
1242 if let Some(headers_end) =
1243 request.windows(4).position(|window| window == b"\r\n\r\n")
1244 {
1245 let headers = String::from_utf8_lossy(&request[..headers_end]);
1246 let content_length = headers
1247 .lines()
1248 .find_map(|line| {
1249 line.to_ascii_lowercase()
1250 .strip_prefix("content-length:")
1251 .map(|value| value.trim().parse::<usize>().unwrap_or(0))
1252 })
1253 .unwrap_or(0);
1254 if request.len() >= headers_end + 4 + content_length {
1255 break;
1256 }
1257 }
1258 }
1259 let response = format!(
1260 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\
1261 content-length: {}\r\nconnection: close\r\n\r\n{}",
1262 body.len(),
1263 body
1264 );
1265 let _ = stream.write_all(response.as_bytes());
1266 });
1267 addr
1268 }
1269
1270 #[tokio::test]
1271 async fn compact_history_rebuilds_system_summary_and_tail() {
1272 let addr = spawn_completion_stub("We refactored backend.rs; tests pass.");
1273 let backend = OpenAiBackend::new(
1274 format!("http://{addr}/v1"),
1275 "test-key",
1276 "test-model",
1277 Some("be helpful".into()),
1278 );
1279 {
1280 let mut history = backend.history.lock().await;
1281 for i in 0..5 {
1282 let role = if i % 2 == 0 { "user" } else { "assistant" };
1283 history.push(serde_json::json!({
1284 "role": role, "content": format!("message {i}"),
1285 }));
1286 }
1287 }
1288
1289 backend.compact_history(2).await.unwrap();
1290
1291 let history = backend.history_snapshot().await;
1292 assert_eq!(history.len(), 4, "system + summary + last 2: {history:?}");
1293 assert_eq!(history[0]["role"], "system");
1294 assert_eq!(history[0]["content"], "be helpful");
1295 assert_eq!(history[1]["role"], "user");
1296 let summary_text = history[1]["content"].as_str().unwrap();
1297 assert!(summary_text.starts_with("[Conversation summary]\n"));
1298 assert!(summary_text.contains("We refactored backend.rs; tests pass."));
1299 assert_eq!(
1300 history[2],
1301 serde_json::json!({ "role": "assistant", "content": "message 3" })
1302 );
1303 assert_eq!(
1304 history[3],
1305 serde_json::json!({ "role": "user", "content": "message 4" })
1306 );
1307 }
1308
1309 #[tokio::test]
1310 async fn compact_history_failure_leaves_history_intact() {
1311 // No listener at this address: the summarization request fails, and
1312 // history must roll back to exactly what it was.
1313 let backend =
1314 OpenAiBackend::new("http://127.0.0.1:9", "", "test-model", Some("sys".into()));
1315 backend
1316 .history
1317 .lock()
1318 .await
1319 .push(serde_json::json!({ "role": "user", "content": "hello" }));
1320 let before = backend.history_snapshot().await;
1321
1322 assert!(backend.compact_history(2).await.is_err());
1323 assert_eq!(backend.history_snapshot().await, before);
1324 }
1325
1326 #[test]
1327 fn assistant_message_with_tool_calls_round_trips() {
1328 let message = ResponseMessage {
1329 content: None,
1330 tool_calls: Some(vec![ResponseToolCall {
1331 id: "call_1".to_string(),
1332 function: ResponseFunction {
1333 name: "read_file".to_string(),
1334 arguments: r#"{"path":"a.rs"}"#.to_string(),
1335 },
1336 }]),
1337 };
1338 let value = message.into_history_value();
1339 assert_eq!(value["role"], "assistant");
1340 assert!(value["content"].is_null());
1341 assert_eq!(value["tool_calls"][0]["id"], "call_1");
1342 assert_eq!(value["tool_calls"][0]["type"], "function");
1343 assert_eq!(value["tool_calls"][0]["function"]["name"], "read_file");
1344 }
1345 }