Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / agentd / src / openrouter.rs

openrouter.rs514 lines · 17.7 KiBRaw
1//! OpenRouter chat-completions client (OpenAI tool-calling format).
2//!
3//! Only the chat-completions endpoint is used. `usage: {include: true}` is
4//! always sent so token counts and (when the provider supplies it) cost come
5//! back on every response; missing cost is tolerated as 0. In production the
6//! key comes from `OPENROUTER_API_KEY`; tests point `OPENROUTER_BASE_URL` at
7//! a local mock.
8
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, Serialize)]
12struct UsageOpt {
13 include: bool,
14}
15
16#[derive(Debug, Clone, Serialize)]
17struct ChatRequest<'a> {
18 model: &'a str,
19 messages: &'a [Message],
20 tools: &'a [ToolDef],
21 #[serde(skip_serializing_if = "Option::is_none")]
22 tool_choice: Option<&'a str>,
23 usage: UsageOpt,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct Message {
28 pub role: String,
29 #[serde(skip_serializing_if = "Option::is_none")]
30 pub content: Option<String>,
31 #[serde(skip_serializing_if = "Option::is_none")]
32 pub tool_calls: Option<Vec<ToolCall>>,
33 #[serde(skip_serializing_if = "Option::is_none")]
34 pub tool_call_id: Option<String>,
35 #[serde(skip_serializing_if = "Option::is_none")]
36 pub name: Option<String>,
37}
38
39impl Message {
40 pub fn system(content: String) -> Message {
41 Message {
42 role: "system".into(),
43 content: Some(content),
44 tool_calls: None,
45 tool_call_id: None,
46 name: None,
47 }
48 }
49 pub fn user(content: String) -> Message {
50 Message {
51 role: "user".into(),
52 content: Some(content),
53 tool_calls: None,
54 tool_call_id: None,
55 name: None,
56 }
57 }
58 /// Plain assistant-text constructor.
59 #[cfg_attr(not(test), allow(dead_code))]
60 pub fn assistant_text(content: String) -> Message {
61 Message {
62 role: "assistant".into(),
63 content: Some(content),
64 tool_calls: None,
65 tool_call_id: None,
66 name: None,
67 }
68 }
69 pub fn assistant_calls(content: Option<String>, calls: Vec<ToolCall>) -> Message {
70 Message {
71 role: "assistant".into(),
72 content,
73 tool_calls: Some(calls),
74 tool_call_id: None,
75 name: None,
76 }
77 }
78 pub fn tool_result(call_id: String, content: String) -> Message {
79 Message {
80 role: "tool".into(),
81 content: Some(content),
82 tool_calls: None,
83 tool_call_id: Some(call_id),
84 name: None,
85 }
86 }
87
88 /// Rough char length for context-budget accounting.
89 pub fn chars(&self) -> usize {
90 self.content.as_ref().map(|c| c.len()).unwrap_or(0)
91 + self
92 .tool_calls
93 .as_ref()
94 .map(|cs| cs.iter().map(|c| c.function.name.len() + c.function.arguments.len()).sum())
95 .unwrap_or(0)
96 }
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct ToolCall {
101 pub id: String,
102 #[serde(rename = "type")]
103 pub kind: String,
104 pub function: FunctionCall,
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct FunctionCall {
109 pub name: String,
110 pub arguments: String,
111}
112
113#[derive(Debug, Clone, Serialize)]
114pub struct ToolDef {
115 #[serde(rename = "type")]
116 pub kind: &'static str,
117 pub function: FunctionDef,
118}
119
120#[derive(Debug, Clone, Serialize)]
121pub struct FunctionDef {
122 pub name: &'static str,
123 pub description: &'static str,
124 pub parameters: serde_json::Value,
125}
126
127fn schema(props: &[(&str, &str, &str)], required: &[&str]) -> serde_json::Value {
128 let mut map = serde_json::Map::new();
129 for (name, ty, _desc) in props {
130 map.insert(
131 name.to_string(),
132 serde_json::json!({"type": ty, "description": _desc}),
133 );
134 }
135 serde_json::json!({
136 "type": "object",
137 "properties": serde_json::Value::Object(map),
138 "required": required,
139 "additionalProperties": false,
140 })
141}
142
143/// The tools the model may call: the base set plus the structured layer.
144pub fn tool_defs() -> Vec<ToolDef> {
145 let mut defs = vec![
146 ToolDef {
147 kind: "function",
148 function: FunctionDef {
149 name: "read_file",
150 description: "Read a file relative to the repo root. Returns content with line numbers.",
151 parameters: schema(
152 &[
153 ("path", "string", "Repo-relative path, e.g. notes/.../MainActivity.kt"),
154 ("start_line", "integer", "1-based first line (optional)"),
155 ("max_lines", "integer", "Max lines (optional)"),
156 ],
157 &["path"],
158 ),
159 },
160 },
161 ToolDef {
162 kind: "function",
163 function: FunctionDef {
164 name: "list_dir",
165 description: "List one directory level relative to the repo root.",
166 parameters: schema(
167 &[("path", "string", "Repo-relative directory, e.g. notes/")],
168 &["path"],
169 ),
170 },
171 },
172 ToolDef {
173 kind: "function",
174 function: FunctionDef {
175 name: "search",
176 description: "Search code with ripgrep. Stays inside the module scope.",
177 parameters: schema(
178 &[
179 ("pattern", "string", "Search pattern"),
180 ("path", "string", "Subdirectory (optional)"),
181 ("glob", "string", "e.g. *.kt (optional)"),
182 ("fixed_string", "boolean", "Literal match (optional)"),
183 ],
184 &["pattern"],
185 ),
186 },
187 },
188 ToolDef {
189 kind: "function",
190 function: FunctionDef {
191 name: "edit_file",
192 description: "Replace exactly one occurrence of `old` with `new` in a file.",
193 parameters: schema(
194 &[
195 ("path", "string", "Repo-relative path"),
196 ("old", "string", "Exact text to replace (must occur exactly once)"),
197 ("new", "string", "Replacement text"),
198 ],
199 &["path", "old", "new"],
200 ),
201 },
202 },
203 ToolDef {
204 kind: "function",
205 function: FunctionDef {
206 name: "write_file",
207 description: "Create or overwrite a file (parents created).",
208 parameters: schema(
209 &[
210 ("path", "string", "Repo-relative path"),
211 ("content", "string", "Full file content"),
212 ],
213 &["path", "content"],
214 ),
215 },
216 },
217 ToolDef {
218 kind: "function",
219 function: FunctionDef {
220 name: "git_diff",
221 description: "Show the working-tree diff vs the branch base.",
222 parameters: schema(&[], &[]),
223 },
224 },
225 ToolDef {
226 kind: "function",
227 function: FunctionDef {
228 name: "run_shell",
229 description: "Run a short shell command (<=60s). No builds, installs, adb, or cargo build/test — use `build` for those.",
230 parameters: schema(
231 &[("command", "string", "Shell command")],
232 &["command"],
233 ),
234 },
235 },
236 ToolDef {
237 kind: "function",
238 function: FunctionDef {
239 name: "build",
240 description: "Run an allowlisted build: structured {module, tasks} (preferred; e.g. {\"module\": \"notes\", \"tasks\": [\"lint\"]}), or legacy ./gradlew :<path>:<task> / ./check <module> string. Blocks while a production release runs.",
241 parameters: serde_json::json!({
242 "type": "object",
243 "properties": {
244 "command": {"type": "string", "description": "Legacy build command, e.g. ./gradlew :notes:compileDevKotlin"},
245 "module": {"type": "string", "description": "Structured form: module dir, e.g. notes, games/logicgate"},
246 "tasks": {"type": "array", "items": {"type": "string"}, "description": "Structured form: Gradle tasks, e.g. [\"lint\", \"detekt\"]"},
247 },
248 "additionalProperties": false,
249 }),
250 },
251 },
252 ToolDef {
253 kind: "function",
254 function: FunctionDef {
255 name: "ask_user",
256 description: "Ask the operator a question and wait for the answer. This must be the ONLY tool call in its turn: do not combine it with any other call. The answer arrives as this call's tool result when the task resumes.",
257 parameters: serde_json::json!({
258 "type": "object",
259 "properties": {
260 "question": {"type": "string", "description": "The question for the operator"},
261 "options": {"type": "array", "items": {"type": "string"}, "description": "Suggested answers shown as buttons (optional)"},
262 "multi_select": {"type": "boolean", "description": "Allow picking more than one option (optional)"}
263 },
264 "required": ["question"],
265 "additionalProperties": false,
266 }),
267 },
268 },
269 ToolDef {
270 kind: "function",
271 function: FunctionDef {
272 name: "propose_plan",
273 description: "Propose your step-by-step plan and wait for operator approval before editing or building. This must be the ONLY tool call in its turn. Required when the task says Plan first. The operator's decision (approval or requested changes) arrives as this call's tool result when the task resumes.",
274 parameters: serde_json::json!({
275 "type": "object",
276 "properties": {
277 "plan_markdown": {"type": "string", "description": "The plan in markdown: steps, files to touch, how you will verify"}
278 },
279 "required": ["plan_markdown"],
280 "additionalProperties": false,
281 }),
282 },
283 },
284 ToolDef {
285 kind: "function",
286 function: FunctionDef {
287 name: "update_todos",
288 description: "Update your todo list (does not wait). Call it as work progresses: pending -> in_progress -> done. The list appears in your system prompt.",
289 parameters: serde_json::json!({
290 "type": "object",
291 "properties": {
292 "items": {
293 "type": "array",
294 "description": "Todo items (max 30, each text max 200 chars)",
295 "items": {
296 "type": "object",
297 "properties": {
298 "text": {"type": "string"},
299 "status": {"type": "string", "description": "pending|in_progress|done"}
300 },
301 "required": ["text", "status"],
302 "additionalProperties": false,
303 }
304 }
305 },
306 "required": ["items"],
307 "additionalProperties": false,
308 }),
309 },
310 },
311 ToolDef {
312 kind: "function",
313 function: FunctionDef {
314 name: "finish",
315 description: "Submit the finished change for human review (does NOT push). This must be the ONLY tool call in its turn. Requires a non-empty diff and a `<module>: <desc>` commit message with a prose body. The operator Approves (push) or requests changes, which arrive as this call's tool result.",
316 parameters: schema(
317 &[
318 ("summary", "string", "One-paragraph summary of what changed"),
319 ("commit_message", "string", "Commit message: `<module>: <desc>` line <=80 chars, blank line, prose body"),
320 ],
321 &["summary", "commit_message"],
322 ),
323 },
324 },
325 ];
326 // One line: append the structured tool layer (run_tests, check, git_*,
327 // find_files, github_*). Kept in structured.rs so merges stay small.
328 defs.extend(crate::structured::tool_defs());
329 defs
330}
331
332#[derive(Debug, Clone, Deserialize)]
333pub struct Usage {
334 #[serde(default)]
335 pub prompt_tokens: i64,
336 #[serde(default)]
337 pub completion_tokens: i64,
338 #[serde(default)]
339 #[allow(dead_code)]
340 pub total_tokens: i64,
341 /// Provider-supplied cost in USD; absent on many models → 0.
342 #[serde(default)]
343 pub cost: f64,
344 #[serde(default)]
345 pub total_cost: f64,
346}
347
348impl Usage {
349 pub fn cost_usd(&self) -> f64 {
350 if self.cost != 0.0 {
351 self.cost
352 } else {
353 self.total_cost
354 }
355 }
356}
357
358#[derive(Debug, Clone, Deserialize)]
359struct ChoiceMessage {
360 #[serde(default)]
361 content: Option<serde_json::Value>,
362 #[serde(default)]
363 tool_calls: Option<Vec<ToolCall>>,
364}
365
366#[derive(Debug, Clone, Deserialize)]
367struct Choice {
368 message: ChoiceMessage,
369}
370
371#[derive(Debug, Clone, Deserialize)]
372struct ChatResponse {
373 #[serde(default)]
374 choices: Vec<Choice>,
375 #[serde(default)]
376 usage: Option<Usage>,
377 #[serde(default)]
378 error: Option<ProviderError>,
379}
380
381#[derive(Debug, Clone, Deserialize)]
382struct ProviderError {
383 #[serde(default)]
384 message: String,
385 #[serde(default)]
386 code: Option<serde_json::Value>,
387}
388
389/// A parsed assistant turn.
390#[derive(Debug, Clone)]
391pub struct AssistantTurn {
392 /// Plain text, if any (content may be a string or a content-parts array).
393 pub text: String,
394 pub tool_calls: Vec<ToolCall>,
395 pub usage: Usage,
396}
397
398fn content_to_string(v: &serde_json::Value) -> String {
399 match v {
400 serde_json::Value::String(s) => s.clone(),
401 serde_json::Value::Array(parts) => parts
402 .iter()
403 .filter_map(|p| {
404 p.get("text")
405 .and_then(|t| t.as_str())
406 .map(|s| s.to_string())
407 .or_else(|| {
408 p.get("content")
409 .and_then(|c| c.as_str())
410 .map(|s| s.to_string())
411 })
412 })
413 .collect::<Vec<_>>()
414 .join(""),
415 serde_json::Value::Null => String::new(),
416 other => other.to_string(),
417 }
418}
419
420/// Parse a raw chat-completions body into an [`AssistantTurn`]. Pure;
421/// unit-tested against JSON fixtures.
422pub fn parse_chat_response(body: &[u8]) -> Result<AssistantTurn, String> {
423 let resp: ChatResponse =
424 serde_json::from_slice(body).map_err(|e| format!("bad OpenRouter JSON: {e}"))?;
425 if let Some(err) = resp.error {
426 let code = err
427 .code
428 .map(|c| c.to_string())
429 .unwrap_or_else(|| "unknown".to_string());
430 return Err(format!("OpenRouter error {code}: {}", err.message));
431 }
432 let choice = resp
433 .choices
434 .into_iter()
435 .next()
436 .ok_or_else(|| "OpenRouter returned no choices".to_string())?;
437 let text = choice
438 .message
439 .content
440 .as_ref()
441 .map(content_to_string)
442 .unwrap_or_default();
443 Ok(AssistantTurn {
444 text,
445 tool_calls: choice.message.tool_calls.unwrap_or_default(),
446 usage: resp.usage.unwrap_or(Usage {
447 prompt_tokens: 0,
448 completion_tokens: 0,
449 total_tokens: 0,
450 cost: 0.0,
451 total_cost: 0.0,
452 }),
453 })
454}
455
456#[derive(Clone)]
457pub struct OpenRouter {
458 client: reqwest::Client,
459 base_url: String,
460 api_key: String,
461}
462
463impl OpenRouter {
464 pub fn new(base_url: String, api_key: String) -> OpenRouter {
465 OpenRouter {
466 client: reqwest::Client::new(),
467 base_url,
468 api_key,
469 }
470 }
471
472 pub async fn chat(
473 &self,
474 model: &str,
475 messages: &[Message],
476 tools: &[ToolDef],
477 ) -> Result<AssistantTurn, String> {
478 let url = format!("{}/chat/completions", self.base_url.trim_end_matches('/'));
479 let req = ChatRequest {
480 model,
481 messages,
482 tools,
483 tool_choice: None,
484 usage: UsageOpt { include: true },
485 };
486 let resp = self
487 .client
488 .post(&url)
489 .header("Authorization", format!("Bearer {}", self.api_key))
490 .header("Content-Type", "application/json")
491 .json(&req)
492 .send()
493 .await
494 .map_err(|e| format!("OpenRouter request failed: {e}"))?;
495 let status = resp.status();
496 let body = resp
497 .bytes()
498 .await
499 .map_err(|e| format!("OpenRouter read body: {e}"))?;
500 if !status.is_success() {
501 // Try to surface a provider message; never include the key
502 // (it is only in the request header, never in the body).
503 if let Ok(v) = serde_json::from_slice::<serde_json::Value>(&body) {
504 let msg = v
505 .get("error")
506 .and_then(|e| e.get("message").and_then(|m| m.as_str()))
507 .unwrap_or("unknown error");
508 return Err(format!("OpenRouter HTTP {status}: {msg}"));
509 }
510 return Err(format!("OpenRouter HTTP {status}"));
511 }
512 parse_chat_response(&body)
513 }
514}