diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/agent.rs | 2 | ||||
| -rw-r--r-- | src/config.rs | 61 | ||||
| -rw-r--r-- | src/git.rs | 57 | ||||
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/main.rs | 115 | ||||
| -rw-r--r-- | src/provider.rs | 81 | ||||
| -rw-r--r-- | src/session.rs | 25 |
7 files changed, 300 insertions, 42 deletions
diff --git a/src/agent.rs b/src/agent.rs index afd662c..c3d77c1 100644 --- a/src/agent.rs +++ b/src/agent.rs | |||
| @@ -185,7 +185,7 @@ pub fn run_turn( | |||
| 185 | push(session, history, user, None); | 185 | push(session, history, user, None); |
| 186 | 186 | ||
| 187 | let schemas = tools::schemas(); | 187 | let schemas = tools::schemas(); |
| 188 | let client = provider::agent(); | 188 | let client = provider::agent(cfg.system_ca); |
| 189 | let mut steps = 0usize; | 189 | let mut steps = 0usize; |
| 190 | let mut last: Option<Outcome> = None; | 190 | let mut last: Option<Outcome> = None; |
| 191 | let mut aborted = false; | 191 | let mut aborted = false; |
diff --git a/src/config.rs b/src/config.rs index 77bdc52..1d259c7 100644 --- a/src/config.rs +++ b/src/config.rs | |||
| @@ -3,6 +3,17 @@ use std::path::PathBuf; | |||
| 3 | pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; | 3 | pub const DEFAULT_BASE_URL: &str = "https://opencode.ai/inference/go/openai/v1"; |
| 4 | pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash"; | 4 | pub const DEFAULT_MODEL: &str = "deepseek-v4.1-flash"; |
| 5 | 5 | ||
| 6 | /// (name, base_url, default_model, lenient). Local gateways that omit `[DONE]` | ||
| 7 | /// or `usage` are marked lenient so a truncated-looking stream is not an error. | ||
| 8 | const PRESETS: &[(&str, &str, &str, bool)] = &[ | ||
| 9 | ("opencode-go", DEFAULT_BASE_URL, DEFAULT_MODEL, false), | ||
| 10 | ("openai", "https://api.openai.com/v1", "gpt-4o-mini", false), | ||
| 11 | ("openrouter", "https://openrouter.ai/api/v1", "", false), | ||
| 12 | ("ollama", "http://localhost:11434/v1", "", true), | ||
| 13 | ("llamacpp", "http://localhost:8080/v1", "", true), | ||
| 14 | ("vllm", "http://localhost:8000/v1", "", true), | ||
| 15 | ]; | ||
| 16 | |||
| 6 | #[derive(Debug, Clone, PartialEq, Eq)] | 17 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 7 | pub enum KeySource { | 18 | pub enum KeySource { |
| 8 | Env, | 19 | Env, |
| @@ -19,16 +30,24 @@ pub struct Config { | |||
| 19 | /// the session exists. | 30 | /// the session exists. |
| 20 | pub session: String, | 31 | pub session: String, |
| 21 | pub yolo: bool, | 32 | pub yolo: bool, |
| 33 | /// Tolerate providers that omit `[DONE]`/`usage`/`finish_reason`. | ||
| 34 | pub lenient: bool, | ||
| 35 | /// Verify TLS against the system trust store instead of bundled roots. | ||
| 36 | pub system_ca: bool, | ||
| 22 | } | 37 | } |
| 23 | 38 | ||
| 24 | impl Config { | 39 | impl Config { |
| 25 | /// CLI flags win over environment variables, which win over defaults. | 40 | /// CLI flags win over environment variables, which win over defaults. |
| 41 | #[allow(clippy::too_many_arguments)] | ||
| 26 | pub fn resolve( | 42 | pub fn resolve( |
| 27 | model: Option<String>, | 43 | model: Option<String>, |
| 28 | base_url: Option<String>, | 44 | base_url: Option<String>, |
| 29 | yolo: bool, | 45 | yolo: bool, |
| 46 | provider: Option<String>, | ||
| 47 | lenient: bool, | ||
| 48 | system_ca: bool, | ||
| 30 | ) -> Result<Config, String> { | 49 | ) -> Result<Config, String> { |
| 31 | let config = Self::resolve_lenient(model, base_url, yolo); | 50 | let config = Self::resolve_lenient(model, base_url, yolo, provider, lenient, system_ca); |
| 32 | if config.api_key.is_empty() { | 51 | if config.api_key.is_empty() { |
| 33 | return Err(format!( | 52 | return Err(format!( |
| 34 | "no API key: set OPENCODE_API_KEY or write one to {}", | 53 | "no API key: set OPENCODE_API_KEY or write one to {}", |
| @@ -42,17 +61,39 @@ impl Config { | |||
| 42 | 61 | ||
| 43 | /// Same as `resolve`, but tolerates a missing key so `--doctor` can report | 62 | /// Same as `resolve`, but tolerates a missing key so `--doctor` can report |
| 44 | /// the missing key instead of failing to start. | 63 | /// the missing key instead of failing to start. |
| 45 | pub fn resolve_lenient(model: Option<String>, base_url: Option<String>, yolo: bool) -> Config { | 64 | pub fn resolve_lenient( |
| 65 | model: Option<String>, | ||
| 66 | base_url: Option<String>, | ||
| 67 | yolo: bool, | ||
| 68 | provider: Option<String>, | ||
| 69 | lenient: bool, | ||
| 70 | system_ca: bool, | ||
| 71 | ) -> Config { | ||
| 72 | // Presets fill the base URL and a default model; explicit values win. | ||
| 73 | let provider = provider.or_else(|| env_nonempty("AGENT686_PROVIDER")); | ||
| 74 | let (preset_url, preset_model, preset_lenient) = provider | ||
| 75 | .as_deref() | ||
| 76 | .and_then(|name| PRESETS.iter().find(|(n, ..)| *n == name)) | ||
| 77 | .map(|(_, url, model, lenient)| (*url, *model, *lenient)) | ||
| 78 | .unwrap_or((DEFAULT_BASE_URL, "", false)); | ||
| 79 | |||
| 80 | let base_url = base_url | ||
| 81 | .or_else(|| env_nonempty("AGENT686_BASE_URL")) | ||
| 82 | .unwrap_or_else(|| preset_url.to_string()); | ||
| 83 | |||
| 84 | let model = model | ||
| 85 | .or_else(|| env_nonempty("AGENT686_MODEL")) | ||
| 86 | .or_else(|| (!preset_model.is_empty()).then(|| preset_model.to_string())) | ||
| 87 | .unwrap_or_else(|| DEFAULT_MODEL.to_string()); | ||
| 88 | |||
| 46 | Config { | 89 | Config { |
| 47 | api_key: api_key().unwrap_or_default(), | 90 | api_key: api_key().unwrap_or_default(), |
| 48 | base_url: base_url | 91 | base_url, |
| 49 | .or_else(|| env_nonempty("AGENT686_BASE_URL")) | 92 | model, |
| 50 | .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()), | ||
| 51 | model: model | ||
| 52 | .or_else(|| env_nonempty("AGENT686_MODEL")) | ||
| 53 | .unwrap_or_else(|| DEFAULT_MODEL.to_string()), | ||
| 54 | session: String::new(), | 93 | session: String::new(), |
| 55 | yolo, | 94 | yolo, |
| 95 | lenient: lenient || preset_lenient, | ||
| 96 | system_ca: system_ca || env_nonempty("AGENT686_SYSTEM_CA").is_some(), | ||
| 56 | } | 97 | } |
| 57 | } | 98 | } |
| 58 | 99 | ||
| @@ -61,6 +102,10 @@ impl Config { | |||
| 61 | } | 102 | } |
| 62 | } | 103 | } |
| 63 | 104 | ||
| 105 | pub fn provider_names() -> Vec<&'static str> { | ||
| 106 | PRESETS.iter().map(|(name, ..)| *name).collect() | ||
| 107 | } | ||
| 108 | |||
| 64 | fn env_nonempty(key: &str) -> Option<String> { | 109 | fn env_nonempty(key: &str) -> Option<String> { |
| 65 | std::env::var(key).ok().filter(|v| !v.trim().is_empty()) | 110 | std::env::var(key).ok().filter(|v| !v.trim().is_empty()) |
| 66 | } | 111 | } |
diff --git a/src/git.rs b/src/git.rs new file mode 100644 index 0000000..78348af --- /dev/null +++ b/src/git.rs | |||
| @@ -0,0 +1,57 @@ | |||
| 1 | //! Git helpers for the checkpoint/undo feature. In a separate module so they | ||
| 2 | //! are unit-testable without driving the whole CLI. | ||
| 3 | |||
| 4 | use std::path::Path; | ||
| 5 | use std::process::Command; | ||
| 6 | |||
| 7 | /// Runs `git -C <dir> <args>`, returning trimmed stdout on success. | ||
| 8 | pub fn run(dir: &Path, args: &[&str]) -> Option<String> { | ||
| 9 | Command::new("git") | ||
| 10 | .arg("-C") | ||
| 11 | .arg(dir) | ||
| 12 | .args(args) | ||
| 13 | .output() | ||
| 14 | .ok() | ||
| 15 | .and_then(|output| { | ||
| 16 | output | ||
| 17 | .status | ||
| 18 | .success() | ||
| 19 | .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string()) | ||
| 20 | }) | ||
| 21 | } | ||
| 22 | |||
| 23 | /// True when `dir` is inside a work tree (a `.git` dir or file up the tree). | ||
| 24 | pub fn in_repo(dir: &Path) -> bool { | ||
| 25 | let mut current = dir.to_path_buf(); | ||
| 26 | loop { | ||
| 27 | if current.join(".git").exists() { | ||
| 28 | return true; | ||
| 29 | } | ||
| 30 | if !current.pop() { | ||
| 31 | return false; | ||
| 32 | } | ||
| 33 | } | ||
| 34 | } | ||
| 35 | |||
| 36 | /// Snapshots the tree as a commit when it is dirty, and returns HEAD. Returns | ||
| 37 | /// `None` outside a repository. | ||
| 38 | pub fn checkpoint(dir: &Path) -> Option<String> { | ||
| 39 | if !in_repo(dir) { | ||
| 40 | return None; | ||
| 41 | } | ||
| 42 | run(dir, &["add", "-A"]); | ||
| 43 | let dirty = run(dir, &["status", "--porcelain"]) | ||
| 44 | .map(|status| !status.is_empty()) | ||
| 45 | .unwrap_or(false); | ||
| 46 | if dirty { | ||
| 47 | run(dir, &["commit", "-m", "agent686: checkpoint"]); | ||
| 48 | } | ||
| 49 | run(dir, &["rev-parse", "HEAD"]) | ||
| 50 | } | ||
| 51 | |||
| 52 | /// Resets to the checkpoint commit and drops untracked files, undoing a turn's | ||
| 53 | /// changes. | ||
| 54 | pub fn undo(dir: &Path, sha: &str) { | ||
| 55 | run(dir, &["reset", "--hard", sha]); | ||
| 56 | run(dir, &["clean", "-fd"]); | ||
| 57 | } | ||
| @@ -1,6 +1,7 @@ | |||
| 1 | pub mod agent; | 1 | pub mod agent; |
| 2 | pub mod config; | 2 | pub mod config; |
| 3 | pub mod doctor; | 3 | pub mod doctor; |
| 4 | pub mod git; | ||
| 4 | pub mod line; | 5 | pub mod line; |
| 5 | pub mod provider; | 6 | pub mod provider; |
| 6 | pub mod session; | 7 | pub mod session; |
diff --git a/src/main.rs b/src/main.rs index a425d71..8f53d9e 100644 --- a/src/main.rs +++ b/src/main.rs | |||
| @@ -1,4 +1,5 @@ | |||
| 1 | use std::io::{BufRead, IsTerminal, Write}; | 1 | use std::io::{BufRead, IsTerminal, Write}; |
| 2 | use std::path::Path; | ||
| 2 | use serde_json::json; | 3 | use serde_json::json; |
| 3 | use std::time::UNIX_EPOCH; | 4 | use std::time::UNIX_EPOCH; |
| 4 | use std::path::PathBuf; | 5 | use std::path::PathBuf; |
| @@ -37,6 +38,10 @@ OPTIONS: | |||
| 37 | --show [ID] print a transcript (most recent if no ID) and exit | 38 | --show [ID] print a transcript (most recent if no ID) and exit |
| 38 | --doctor check key, directories, provider and model, then exit | 39 | --doctor check key, directories, provider and model, then exit |
| 39 | --yolo approve every tool call without asking | 40 | --yolo approve every tool call without asking |
| 41 | --provider <NAME> preset: opencode-go, openai, openrouter, ollama, | ||
| 42 | llamacpp, vllm | ||
| 43 | --lenient tolerate providers that omit [DONE]/usage | ||
| 44 | --system-ca verify TLS with the system trust store | ||
| 40 | -V, --version print the version and exit | 45 | -V, --version print the version and exit |
| 41 | -h, --help this text | 46 | -h, --help this text |
| 42 | 47 | ||
| @@ -63,6 +68,9 @@ struct Args { | |||
| 63 | doctor: bool, | 68 | doctor: bool, |
| 64 | yolo: bool, | 69 | yolo: bool, |
| 65 | json: bool, | 70 | json: bool, |
| 71 | provider: Option<String>, | ||
| 72 | lenient: bool, | ||
| 73 | system_ca: bool, | ||
| 66 | } | 74 | } |
| 67 | 75 | ||
| 68 | fn main() { | 76 | fn main() { |
| @@ -88,6 +96,9 @@ fn parse_args() -> Result<Args, String> { | |||
| 88 | doctor: false, | 96 | doctor: false, |
| 89 | yolo: false, | 97 | yolo: false, |
| 90 | json: false, | 98 | json: false, |
| 99 | provider: None, | ||
| 100 | lenient: false, | ||
| 101 | system_ca: false, | ||
| 91 | }; | 102 | }; |
| 92 | let mut words: Vec<String> = Vec::new(); | 103 | let mut words: Vec<String> = Vec::new(); |
| 93 | let mut iter = std::env::args().skip(1).peekable(); | 104 | let mut iter = std::env::args().skip(1).peekable(); |
| @@ -118,6 +129,10 @@ fn parse_args() -> Result<Args, String> { | |||
| 118 | args.show = Some(Some(value.to_string())); | 129 | args.show = Some(Some(value.to_string())); |
| 119 | continue; | 130 | continue; |
| 120 | } | 131 | } |
| 132 | "--provider" => { | ||
| 133 | args.provider = Some(value.to_string()); | ||
| 134 | continue; | ||
| 135 | } | ||
| 121 | _ => return Err(format!("unknown flag {flag}\n\n{HELP}")), | 136 | _ => return Err(format!("unknown flag {flag}\n\n{HELP}")), |
| 122 | } | 137 | } |
| 123 | } | 138 | } |
| @@ -142,6 +157,9 @@ fn parse_args() -> Result<Args, String> { | |||
| 142 | "--doctor" => args.doctor = true, | 157 | "--doctor" => args.doctor = true, |
| 143 | "--yolo" => args.yolo = true, | 158 | "--yolo" => args.yolo = true, |
| 144 | "--json" => args.json = true, | 159 | "--json" => args.json = true, |
| 160 | "--provider" => args.provider = Some(take_value(&mut iter, "--provider")?), | ||
| 161 | "--lenient" => args.lenient = true, | ||
| 162 | "--system-ca" => args.system_ca = true, | ||
| 145 | "-V" | "--version" => { | 163 | "-V" | "--version" => { |
| 146 | println!("agent686 {}", env!("CARGO_PKG_VERSION")); | 164 | println!("agent686 {}", env!("CARGO_PKG_VERSION")); |
| 147 | std::process::exit(0); | 165 | std::process::exit(0); |
| @@ -216,13 +234,27 @@ fn run(args: Args) { | |||
| 216 | } | 234 | } |
| 217 | 235 | ||
| 218 | if args.doctor { | 236 | if args.doctor { |
| 219 | let mut config = Config::resolve_lenient(args.model, args.base_url, args.yolo); | 237 | let mut config = Config::resolve_lenient( |
| 238 | args.model, | ||
| 239 | args.base_url, | ||
| 240 | args.yolo, | ||
| 241 | args.provider, | ||
| 242 | args.lenient, | ||
| 243 | args.system_ca, | ||
| 244 | ); | ||
| 220 | // `/models` needs the session header too, even though this is not a turn. | 245 | // `/models` needs the session header too, even though this is not a turn. |
| 221 | config.session = session::new_id(); | 246 | config.session = session::new_id(); |
| 222 | std::process::exit(doctor::run(&config, args.json)); | 247 | std::process::exit(doctor::run(&config, args.json)); |
| 223 | } | 248 | } |
| 224 | 249 | ||
| 225 | let mut cfg = match Config::resolve(args.model, args.base_url, args.yolo) { | 250 | let mut cfg = match Config::resolve( |
| 251 | args.model, | ||
| 252 | args.base_url, | ||
| 253 | args.yolo, | ||
| 254 | args.provider, | ||
| 255 | args.lenient, | ||
| 256 | args.system_ca, | ||
| 257 | ) { | ||
| 226 | Ok(cfg) => cfg, | 258 | Ok(cfg) => cfg, |
| 227 | Err(message) => { | 259 | Err(message) => { |
| 228 | eprintln!("agent686: {message}"); | 260 | eprintln!("agent686: {message}"); |
| @@ -287,6 +319,7 @@ fn run(args: Args) { | |||
| 287 | 319 | ||
| 288 | let mut editor = Editor::new(); | 320 | let mut editor = Editor::new(); |
| 289 | let interactive = editor.is_interactive(); | 321 | let interactive = editor.is_interactive(); |
| 322 | let mut checkpoint: Option<String> = None; | ||
| 290 | if !interactive && !cfg.yolo { | 323 | if !interactive && !cfg.yolo { |
| 291 | eprintln!( | 324 | eprintln!( |
| 292 | "agent686: stdin is not a terminal, so write/edit/bash will be denied; \ | 325 | "agent686: stdin is not a terminal, so write/edit/bash will be denied; \ |
| @@ -330,6 +363,14 @@ fn run(args: Args) { | |||
| 330 | forget_sessions(&text, &session); | 363 | forget_sessions(&text, &session); |
| 331 | continue; | 364 | continue; |
| 332 | } | 365 | } |
| 366 | if text == "/undo" { | ||
| 367 | undo(checkpoint.as_deref()); | ||
| 368 | continue; | ||
| 369 | } | ||
| 370 | if text == "/compact" { | ||
| 371 | compact(&cfg, &mut session, &mut history); | ||
| 372 | continue; | ||
| 373 | } | ||
| 333 | 374 | ||
| 334 | match text.as_str() { | 375 | match text.as_str() { |
| 335 | "/exit" | "/quit" => break, | 376 | "/exit" | "/quit" => break, |
| @@ -364,6 +405,7 @@ fn run(args: Args) { | |||
| 364 | } | 405 | } |
| 365 | 406 | ||
| 366 | warn_if_changed(&watched, &mut warned); | 407 | warn_if_changed(&watched, &mut warned); |
| 408 | checkpoint = git_checkpoint(); | ||
| 367 | if let Err(error) = agent::run_turn( | 409 | if let Err(error) = agent::run_turn( |
| 368 | &cfg, | 410 | &cfg, |
| 369 | &mut session, | 411 | &mut session, |
| @@ -439,6 +481,63 @@ fn open_session( | |||
| 439 | 481 | ||
| 440 | /// The system prompt is frozen with the directory the session started in. If the | 482 | /// The system prompt is frozen with the directory the session started in. If the |
| 441 | /// user resumes from somewhere else, tools and prompt disagree. | 483 | /// user resumes from somewhere else, tools and prompt disagree. |
| 484 | /// Git is the documented undo, so before a turn we snapshot the tree with a | ||
| 485 | /// commit when it is dirty. `/undo` resets back to this. | ||
| 486 | fn git_checkpoint() -> Option<String> { | ||
| 487 | let Ok(cwd) = std::env::current_dir() else { | ||
| 488 | return None; | ||
| 489 | }; | ||
| 490 | agent686::git::checkpoint(&cwd) | ||
| 491 | } | ||
| 492 | |||
| 493 | fn undo(checkpoint: Option<&str>) { | ||
| 494 | let Some(sha) = checkpoint else { | ||
| 495 | eprintln!("agent686: /undo needs a git repository"); | ||
| 496 | return; | ||
| 497 | }; | ||
| 498 | let Ok(cwd) = std::env::current_dir() else { | ||
| 499 | return; | ||
| 500 | }; | ||
| 501 | agent686::git::undo(&cwd, sha); | ||
| 502 | eprintln!("agent686: restored to {sha}"); | ||
| 503 | } | ||
| 504 | |||
| 505 | /// `/compact`: summarise the conversation and start again from the summary, in | ||
| 506 | /// the same session id. The only sanctioned rewrite of the transcript (ADR 0003). | ||
| 507 | fn compact(cfg: &Config, session: &mut Session, history: &mut Vec<Value>) { | ||
| 508 | let system = history.first().cloned().unwrap_or_else(|| agent::system_prompt()); | ||
| 509 | let mut messages = history.clone(); | ||
| 510 | messages.push(json!({ | ||
| 511 | "role": "user", | ||
| 512 | "content": "Summarize the conversation so far into one concise paragraph that \ | ||
| 513 | preserves the goal, decisions made, files changed, and the current \ | ||
| 514 | state. Omit pleasantries." | ||
| 515 | })); | ||
| 516 | let summary = match agent686::provider::summarize(cfg, &messages) { | ||
| 517 | Ok(summary) if !summary.trim().is_empty() => summary, | ||
| 518 | Ok(_) => { | ||
| 519 | eprintln!("agent686: /compact produced an empty summary; aborting"); | ||
| 520 | return; | ||
| 521 | } | ||
| 522 | Err(error) => { | ||
| 523 | eprintln!("agent686: /compact failed: {error}"); | ||
| 524 | return; | ||
| 525 | } | ||
| 526 | }; | ||
| 527 | |||
| 528 | let user = json!({ | ||
| 529 | "role": "user", | ||
| 530 | "content": format!("[earlier conversation, summarized]\n{summary}"), | ||
| 531 | }); | ||
| 532 | let new_history = vec![system.clone(), user]; | ||
| 533 | if let Err(error) = session.rewrite(&system, &new_history[1..]) { | ||
| 534 | eprintln!("agent686: /compact could not rewrite the session: {error}"); | ||
| 535 | return; | ||
| 536 | } | ||
| 537 | *history = new_history; | ||
| 538 | eprintln!("agent686: compacted into a {}-character summary", summary.len()); | ||
| 539 | } | ||
| 540 | |||
| 442 | fn list_models(cfg: &Config) { | 541 | fn list_models(cfg: &Config) { |
| 443 | match agent686::provider::models(cfg) { | 542 | match agent686::provider::models(cfg) { |
| 444 | Ok(models) => { | 543 | Ok(models) => { |
| @@ -640,16 +739,8 @@ fn refuse_yolo(cfg: &Config) { | |||
| 640 | } | 739 | } |
| 641 | } | 740 | } |
| 642 | 741 | ||
| 643 | fn in_git_repo(dir: &std::path::Path) -> bool { | 742 | fn in_git_repo(dir: &Path) -> bool { |
| 644 | let mut current = dir.to_path_buf(); | 743 | agent686::git::in_repo(dir) |
| 645 | loop { | ||
| 646 | if current.join(".git").exists() { | ||
| 647 | return true; | ||
| 648 | } | ||
| 649 | if !current.pop() { | ||
| 650 | return false; | ||
| 651 | } | ||
| 652 | } | ||
| 653 | } | 744 | } |
| 654 | 745 | ||
| 655 | fn style(code: &str, text: &str, color: bool) -> String { | 746 | fn style(code: &str, text: &str, color: bool) -> String { |
diff --git a/src/provider.rs b/src/provider.rs index b08d1f2..c03dea2 100644 --- a/src/provider.rs +++ b/src/provider.rs | |||
| @@ -197,15 +197,22 @@ fn explain(status: u16, message: &str) -> String { | |||
| 197 | } | 197 | } |
| 198 | 198 | ||
| 199 | /// One client per turn: rebuilding it per step pays a TLS handshake on every | 199 | /// One client per turn: rebuilding it per step pays a TLS handshake on every |
| 200 | /// request, which is noticeable on an i686 core. | 200 | /// request, which is noticeable on an i686 core. `system_ca` verifies against |
| 201 | pub fn agent() -> ureq::Agent { | 201 | /// the OS trust store instead of bundled roots. |
| 202 | ureq::Agent::config_builder() | 202 | pub fn agent(system_ca: bool) -> ureq::Agent { |
| 203 | let mut builder = ureq::Agent::config_builder() | ||
| 203 | .http_status_as_error(false) | 204 | .http_status_as_error(false) |
| 204 | .timeout_connect(Some(Duration::from_secs(10))) | 205 | .timeout_connect(Some(Duration::from_secs(10))) |
| 205 | .timeout_recv_response(Some(Duration::from_secs(180))) | 206 | .timeout_recv_response(Some(Duration::from_secs(180))) |
| 206 | .timeout_per_read(Some(Duration::from_secs(180))) | 207 | .timeout_per_read(Some(Duration::from_secs(180))); |
| 207 | .build() | 208 | if system_ca { |
| 208 | .into() | 209 | builder = builder.tls_config( |
| 210 | ureq::tls::TlsConfig::builder() | ||
| 211 | .root_certs(ureq::tls::RootCerts::PlatformVerifier) | ||
| 212 | .build(), | ||
| 213 | ); | ||
| 214 | } | ||
| 215 | builder.build().into() | ||
| 209 | } | 216 | } |
| 210 | 217 | ||
| 211 | pub fn chat( | 218 | pub fn chat( |
| @@ -215,7 +222,7 @@ pub fn chat( | |||
| 215 | cancel: &AtomicBool, | 222 | cancel: &AtomicBool, |
| 216 | sink: &mut dyn Sink, | 223 | sink: &mut dyn Sink, |
| 217 | ) -> Result<Outcome, Error> { | 224 | ) -> Result<Outcome, Error> { |
| 218 | chat_with(&agent(), cfg, messages, tools, cancel, sink) | 225 | chat_with(&agent(cfg.system_ca), cfg, messages, tools, cancel, sink) |
| 219 | } | 226 | } |
| 220 | 227 | ||
| 221 | pub fn chat_with( | 228 | pub fn chat_with( |
| @@ -378,14 +385,18 @@ pub fn chat_with( | |||
| 378 | } | 385 | } |
| 379 | 386 | ||
| 380 | // A connection that closes early, or a 200 that is not SSE at all, must not | 387 | // A connection that closes early, or a 200 that is not SSE at all, must not |
| 381 | // be recorded as a complete answer. | 388 | // be recorded as a complete answer. Lenient mode tolerates local servers |
| 389 | // that finish with text but no [DONE]/finish_reason. | ||
| 382 | if !completed { | 390 | if !completed { |
| 383 | return Err(Error::Transport(format!( | 391 | let lenient_ok = cfg.lenient && outcome.tool_calls.is_empty() && !outcome.content.is_empty(); |
| 384 | "stream ended before completion ({} bytes of text, {} tool call(s)); \ | 392 | if !lenient_ok { |
| 385 | the turn was not recorded as answered", | 393 | return Err(Error::Transport(format!( |
| 386 | outcome.content.len(), | 394 | "stream ended before completion ({} bytes of text, {} tool call(s)); \ |
| 387 | outcome.tool_calls.len() | 395 | the turn was not recorded as answered", |
| 388 | ))); | 396 | outcome.content.len(), |
| 397 | outcome.tool_calls.len() | ||
| 398 | ))); | ||
| 399 | } | ||
| 389 | } | 400 | } |
| 390 | 401 | ||
| 391 | sink.done(&outcome, started.elapsed()); | 402 | sink.done(&outcome, started.elapsed()); |
| @@ -555,15 +566,43 @@ struct FunctionDelta { | |||
| 555 | arguments: Option<String>, | 566 | arguments: Option<String>, |
| 556 | } | 567 | } |
| 557 | 568 | ||
| 569 | /// A single non-streaming completion, used by `/compact` to summarise history. | ||
| 570 | pub fn summarize(cfg: &Config, messages: &[Value]) -> Result<String, Error> { | ||
| 571 | let body = serde_json::json!({ "model": cfg.model, "messages": messages, "stream": false }); | ||
| 572 | let bytes = serde_json::to_vec(&body).map_err(|e| Error::Transport(e.to_string()))?; | ||
| 573 | let mut response = agent(cfg.system_ca) | ||
| 574 | .post(&cfg.endpoint()) | ||
| 575 | .header("Content-Type", "application/json") | ||
| 576 | .header("Authorization", format!("Bearer {}", cfg.api_key)) | ||
| 577 | .header("User-Agent", concat!("agent686/", env!("CARGO_PKG_VERSION"))) | ||
| 578 | .header("x-opencode-session", &cfg.session) | ||
| 579 | .send(bytes) | ||
| 580 | .map_err(|e| Error::Transport(e.to_string()))?; | ||
| 581 | |||
| 582 | let status = response.status().as_u16(); | ||
| 583 | let text = response | ||
| 584 | .body_mut() | ||
| 585 | .with_config() | ||
| 586 | .limit(2 * 1024 * 1024) | ||
| 587 | .read_to_string() | ||
| 588 | .unwrap_or_default(); | ||
| 589 | if !(200..300).contains(&status) { | ||
| 590 | return Err(Error::Status { | ||
| 591 | code: status, | ||
| 592 | message: error_message(&text), | ||
| 593 | }); | ||
| 594 | } | ||
| 595 | let value: Value = serde_json::from_str(&text) | ||
| 596 | .map_err(|e| Error::Transport(format!("could not parse the completion: {e}")))?; | ||
| 597 | Ok(value["choices"][0]["message"]["content"] | ||
| 598 | .as_str() | ||
| 599 | .unwrap_or("") | ||
| 600 | .to_string()) | ||
| 601 | } | ||
| 602 | |||
| 558 | /// Lists the models the provider offers for this key, for `--doctor`. | 603 | /// Lists the models the provider offers for this key, for `--doctor`. |
| 559 | pub fn models(cfg: &Config) -> Result<Vec<String>, Error> { | 604 | pub fn models(cfg: &Config) -> Result<Vec<String>, Error> { |
| 560 | let agent: ureq::Agent = ureq::Agent::config_builder() | 605 | let agent = agent(cfg.system_ca); |
| 561 | .http_status_as_error(false) | ||
| 562 | .timeout_connect(Some(Duration::from_secs(10))) | ||
| 563 | .timeout_recv_response(Some(Duration::from_secs(20))) | ||
| 564 | .timeout_per_read(Some(Duration::from_secs(20))) | ||
| 565 | .build() | ||
| 566 | .into(); | ||
| 567 | 606 | ||
| 568 | let url = format!("{}/models", cfg.base_url.trim_end_matches('/')); | 607 | let url = format!("{}/models", cfg.base_url.trim_end_matches('/')); |
| 569 | let mut response = agent | 608 | let mut response = agent |
diff --git a/src/session.rs b/src/session.rs index 881b1ed..8fc6d29 100644 --- a/src/session.rs +++ b/src/session.rs | |||
| @@ -252,6 +252,31 @@ impl Session { | |||
| 252 | &self.path | 252 | &self.path |
| 253 | } | 253 | } |
| 254 | 254 | ||
| 255 | /// Rewrites the transcript from scratch: a fresh header plus the given | ||
| 256 | /// messages. This is the one sanctioned rewrite, called only by `/compact` | ||
| 257 | /// (see ADR 0003); everything else appends. | ||
| 258 | pub fn rewrite(&mut self, system: &Value, messages: &[Value]) -> Result<(), String> { | ||
| 259 | use std::io::{Seek, SeekFrom, Write}; | ||
| 260 | self.file.set_len(0).map_err(|e| e.to_string())?; | ||
| 261 | self.file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; | ||
| 262 | let header = json!({ | ||
| 263 | "t": "header", | ||
| 264 | "session": self.id, | ||
| 265 | "model": self.model, | ||
| 266 | "cwd": self.cwd, | ||
| 267 | "version": self.version, | ||
| 268 | "created": now_ms(), | ||
| 269 | "system": system, | ||
| 270 | }); | ||
| 271 | writeln!(self.file, "{header}").map_err(|e| e.to_string())?; | ||
| 272 | for message in messages { | ||
| 273 | let mut line = message.as_object().cloned().unwrap_or_default(); | ||
| 274 | line.insert("t".into(), json!("msg")); | ||
| 275 | writeln!(self.file, "{}", Value::Object(line)).map_err(|e| e.to_string())?; | ||
| 276 | } | ||
| 277 | self.file.flush().map_err(|e| e.to_string()) | ||
| 278 | } | ||
| 279 | |||
| 255 | /// Records a model switch so `--list` shows what the last turn used. Appending | 280 | /// Records a model switch so `--list` shows what the last turn used. Appending |
| 256 | /// is legal; the header itself is never rewritten. | 281 | /// is legal; the header itself is never rewritten. |
| 257 | pub fn record_model(&mut self, model: &str) -> Result<(), String> { | 282 | pub fn record_model(&mut self, model: &str) -> Result<(), String> { |
