summaryrefslogtreecommitdiffstats
path: root/src/provider.rs
diff options
context:
space:
mode:
authorsalmonik <salmonik@tuta.io>2026-11-15 03:11:22 +0100
committersalmonik <salmonik@tuta.io>2026-11-15 03:11:22 +0100
commit343f2a8a6148b8004d6f4d74fb779b4f30c9686a (patch)
tree2ea1ddab346565309da644517c3478d2a9096e55 /src/provider.rs
parentM0: streaming provider, SSE decoder, mock provider, i686 build gate (diff)
downloadagent686-343f2a8a6148b8004d6f4d74fb779b4f30c9686a.tar.gz
agent686-343f2a8a6148b8004d6f4d74fb779b4f30c9686a.zip
M1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate
- append-only JSONL sessions with --continue/--session; reasoning stored, stripped on replay - read/write/edit/grep/glob + bash with timeout and capped output - diff-preview approval for the first edit of a session, per-call approval for bash - system prompt frozen per session with AGENTS.md snapshot and change warning - SIGINT aborts the turn, second Ctrl-C exits - glibc gate ignores weak symbols; verified in linux/386 debian:12 - acceptance test (calculator in C) passes on both x86-64 and i386
Diffstat (limited to 'src/provider.rs')
-rw-r--r--src/provider.rs64
1 files changed, 41 insertions, 23 deletions
diff --git a/src/provider.rs b/src/provider.rs
index a2aed64..bc1bd99 100644
--- a/src/provider.rs
+++ b/src/provider.rs
@@ -44,7 +44,35 @@ pub struct Outcome {
44 pub tool_calls: Vec<ToolCall>, 44 pub tool_calls: Vec<ToolCall>,
45 pub finish: Option<String>, 45 pub finish: Option<String>,
46 pub usage: Option<Value>, 46 pub usage: Option<Value>,
47 pub opencode: Option<Value>, 47}
48
49impl Outcome {
50 pub fn allowance(&self) -> Option<f64> {
51 self.usage
52 .as_ref()?
53 .get("opencode")?
54 .get("allowance")?
55 .as_f64()
56 }
57
58 pub fn list_cost(&self) -> Option<f64> {
59 self.usage
60 .as_ref()?
61 .get("opencode")?
62 .get("list_cost")?
63 .as_f64()
64 }
65
66 pub fn tokens(&self) -> (Option<u64>, Option<u64>) {
67 let usage = match &self.usage {
68 Some(u) => u,
69 None => return (None, None),
70 };
71 (
72 usage.get("prompt_tokens").and_then(|v| v.as_u64()),
73 usage.get("completion_tokens").and_then(|v| v.as_u64()),
74 )
75 }
48} 76}
49 77
50pub trait Sink { 78pub trait Sink {
@@ -92,19 +120,22 @@ impl SseDecoder {
92pub fn chat( 120pub fn chat(
93 cfg: &Config, 121 cfg: &Config,
94 messages: &[Value], 122 messages: &[Value],
123 tools: &[Value],
95 cancel: &AtomicBool, 124 cancel: &AtomicBool,
96 sink: &mut dyn Sink, 125 sink: &mut dyn Sink,
97) -> Result<Outcome, Error> { 126) -> Result<Outcome, Error> {
98 // serde_json::Value is ordered by key, not by insertion, so the serialised 127 // serde_json::Value orders objects by key, so the serialised bytes are
99 // bytes are stable for the same input. That is what keeps the cache warm; 128 // stable for the same input. That is what keeps the provider's prompt cache
100 // do not switch this to a struct with fields in a different order, and do 129 // warm. Do not add anything session-varying here.
101 // not add anything session-varying to the system message. 130 let mut body = serde_json::json!({
102 let body = serde_json::json!({
103 "model": cfg.model, 131 "model": cfg.model,
104 "messages": messages, 132 "messages": messages,
105 "stream": true, 133 "stream": true,
106 "stream_options": { "include_usage": true }, 134 "stream_options": { "include_usage": true },
107 }); 135 });
136 if !tools.is_empty() {
137 body["tools"] = Value::Array(tools.to_vec());
138 }
108 let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; 139 let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?;
109 140
110 let agent: ureq::Agent = ureq::Agent::config_builder() 141 let agent: ureq::Agent = ureq::Agent::config_builder()
@@ -169,23 +200,15 @@ pub fn chat(
169 } 200 }
170 let chunk: Chunk = match serde_json::from_str(&data) { 201 let chunk: Chunk = match serde_json::from_str(&data) {
171 Ok(c) => c, 202 Ok(c) => c,
172 // A malformed frame is dropped rather than killing the turn; the 203 // A malformed frame is dropped rather than killing the turn.
173 // stream is the only recovery path and it is still valid SSE.
174 Err(_) => continue, 204 Err(_) => continue,
175 }; 205 };
176 apply_chunk(&chunk, &mut outcome, sink); 206 apply_chunk(&chunk, &mut outcome, sink);
177 } 207 }
178 } 208 }
179 209
180 if let Some(usage) = &outcome.usage { 210 if outcome.usage.as_ref().is_some_and(|u| u.is_null()) {
181 if usage.is_null() { 211 outcome.usage = None;
182 outcome.usage = None;
183 }
184 }
185 if let Some(opencode) = &outcome.opencode {
186 if opencode.is_null() {
187 outcome.opencode = None;
188 }
189 } 212 }
190 213
191 sink.done(&outcome, started.elapsed()); 214 sink.done(&outcome, started.elapsed());
@@ -196,9 +219,6 @@ fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) {
196 if let Some(usage) = &chunk.usage { 219 if let Some(usage) = &chunk.usage {
197 outcome.usage = Some(usage.clone()); 220 outcome.usage = Some(usage.clone());
198 } 221 }
199 if let Some(opencode) = &chunk.opencode {
200 outcome.opencode = Some(opencode.clone());
201 }
202 for choice in &chunk.choices { 222 for choice in &chunk.choices {
203 if let Some(r) = &choice.delta.reasoning_content { 223 if let Some(r) = &choice.delta.reasoning_content {
204 if !r.is_empty() { 224 if !r.is_empty() {
@@ -266,7 +286,7 @@ fn error_message(body: &str) -> String {
266 truncate(body.trim(), 500) 286 truncate(body.trim(), 500)
267} 287}
268 288
269fn truncate(s: &str, max: usize) -> String { 289pub fn truncate(s: &str, max: usize) -> String {
270 match s.char_indices().nth(max) { 290 match s.char_indices().nth(max) {
271 Some((i, _)) => format!("{}…", &s[..i]), 291 Some((i, _)) => format!("{}…", &s[..i]),
272 None => s.to_string(), 292 None => s.to_string(),
@@ -279,8 +299,6 @@ struct Chunk {
279 choices: Vec<Choice>, 299 choices: Vec<Choice>,
280 #[serde(default)] 300 #[serde(default)]
281 usage: Option<Value>, 301 usage: Option<Value>,
282 #[serde(default)]
283 opencode: Option<Value>,
284} 302}
285 303
286#[derive(Debug, Deserialize)] 304#[derive(Debug, Deserialize)]