Skip to main content

orch/engine/agents/opencode/
mod.rs

1//! OpenCode agent runner.
2//!
3//! ## CLI invocation
4//!
5//! ```bash
6//! opencode run --format json -m {model} - < "{msg_file}"
7//! ```
8//!
9//! ## Output format (`run --format json`)
10//!
11//! NDJSON stream:
12//! ```jsonl
13//! {"type":"step_start","timestamp":...,"part":{"type":"step-start","snapshot":"..."}}
14//! {"type":"text","timestamp":...,"part":{"type":"text","text":"hello"}}
15//! {"type":"step_finish","timestamp":...,"part":{"type":"step-finish","reason":"stop","cost":0,"tokens":{"total":17512,"input":17509,"output":3}}}
16//! ```
17//!
18//! ## Token extraction
19//!
20//! Tokens are in the `step_finish` event: `part.tokens.{input,output,total}`
21//!
22//! ## Free models
23//!
24//! Discoverable via: `opencode models | grep free`
25//! Discovered dynamically at startup with 1-hour cache.
26
27use super::{
28    AgentError, AgentRunner, ParsedResponse, PermissionRules, SandboxLevel, StreamEvent,
29    json_error_message, json_str,
30};
31use crate::engine::agents::parser;
32use crate::engine::agents::parser::AgentResponse;
33use crate::sys::cmd;
34use crate::sys::cmd_cache;
35
36use std::path::Path;
37use std::sync::atomic::{AtomicBool, Ordering};
38use std::sync::{Mutex, OnceLock};
39
40use tokio::process::Command;
41use tokio::runtime::Handle;
42use tokio::runtime::Runtime;
43use tokio::time;
44
45use std::collections::BTreeMap;
46use std::process::Stdio;
47use std::sync::PoisonError;
48use std::thread;
49use std::time::Duration;
50
51/// Module-level cache for discovered free opencode models.
52/// Shared across all callers (router, runner, failover).
53static FREE_MODELS_CACHE: OnceLock<Mutex<(i64, Vec<String>)>> = OnceLock::new();
54static FREE_MODELS_REFRESH_IN_PROGRESS: AtomicBool = AtomicBool::new(false);
55/// Module-level cache for all discovered opencode models.
56/// Shared across all callers (router, runner, failover).
57static ALL_MODELS_CACHE: OnceLock<Mutex<(i64, Vec<String>)>> = OnceLock::new();
58static ALL_MODELS_REFRESH_IN_PROGRESS: AtomicBool = AtomicBool::new(false);
59
60#[cfg(test)]
61pub(crate) fn reset_model_caches_for_test() {
62    if let Some(cache) = FREE_MODELS_CACHE.get()
63        && let Ok(mut guard) = cache.lock()
64    {
65        *guard = (0, Vec::new());
66    }
67    if let Some(cache) = ALL_MODELS_CACHE.get()
68        && let Ok(mut guard) = cache.lock()
69    {
70        *guard = (0, Vec::new());
71    }
72    FREE_MODELS_REFRESH_IN_PROGRESS.store(false, Ordering::Release);
73    ALL_MODELS_REFRESH_IN_PROGRESS.store(false, Ordering::Release);
74}
75
76/**
77 * Model discovery runs the real `opencode` binary, and opencode 2.2.1 starts an
78 * `opencode serve --service` child that outlives it, so a suite run left one server
79 * behind per test process. It also made the result depend on the machine, and CI has no
80 * opencode at all. A test that needs models passes them in, or uses `Router::new_for_test`.
81 * `cfg(test)` is unset when the integration tests link the library, so debug builds count
82 * too, and the run-time check keeps the live path compiled in every build
83 **/
84fn skip_live_opencode_discovery() -> bool {
85    cfg!(any(test, debug_assertions))
86}
87
88fn update_discovered_models_cache(
89    cache: &Mutex<(i64, Vec<String>)>,
90    discovered: Vec<String>,
91    cache_name: &'static str,
92    empty_reason: &'static str,
93) {
94    let now = chrono::Utc::now().timestamp();
95    let mut guard = cache.lock().unwrap_or_else(PoisonError::into_inner);
96
97    if discovered.is_empty() && !guard.1.is_empty() {
98        tracing::warn!(
99            cache = cache_name,
100            cached_models = guard.1.len(),
101            reason = empty_reason,
102            "opencode model discovery returned empty; preserving previous cache contents"
103        );
104        // Still advance the timestamp so a persistently-failing discovery
105        // backs off for the full TTL window instead of being retried on
106        // every subsequent call.
107        guard.0 = now;
108        return;
109    }
110
111    tracing::debug!(
112        cache = cache_name,
113        discovered_models = discovered.len(),
114        "opencode model discovery refreshed cache"
115    );
116    *guard = (now, discovered);
117}
118
119/// Runner for OpenCode agent.
120#[derive(Debug)]
121pub struct OpenCodeRunner;
122
123pub(crate) fn extract_ndjson_text(events: &[serde_json::Value]) -> Option<String> {
124    let mut texts = Vec::new();
125
126    for event in events {
127        let event_type = event.get("type").and_then(|v| v.as_str()).unwrap_or("");
128
129        // OpenCode emits several shapes across versions. Also scan assistant
130        // messages coming from Claude-like wrappers which use `type: "assistant"`
131        // with a `message.content` array containing text items.
132        // We intentionally restrict extraction to event/part/message types that
133        // represent assistant text output (not tool I/O).
134        if event_type == "text" || event_type == "message" || event_type == "assistant" {
135            if let Some(part) = event.get("part") {
136                texts.extend(extract_text_from_part(part));
137            }
138
139            // Handle opencode `text` events that put text at top-level
140            if let Some(text) = event.get("text").and_then(|v| v.as_str()) {
141                texts.push(text.to_string());
142            }
143
144            // Handle Claude-like assistant messages: message.content -> [{type:"text", text:...}]
145            if let Some(message) = event.get("message")
146                && let Some(items) = message.get("content").and_then(|v| v.as_array())
147            {
148                for item in items {
149                    let item_type = item.get("type").and_then(|v| v.as_str()).unwrap_or("");
150                    if item_type == "text"
151                        && let Some(text) = item.get("text").and_then(|v| v.as_str())
152                    {
153                        texts.push(text.to_string());
154                    }
155                }
156            }
157
158            continue;
159        }
160
161        // Some builds use a generic event type but keep a text-ish part.
162        if let Some(part) = event.get("part") {
163            let part_type = part.get("type").and_then(|v| v.as_str()).unwrap_or("");
164            if part_type == "text" || part_type == "output_text" || part_type == "message" {
165                texts.extend(extract_text_from_part(part));
166            }
167        }
168    }
169
170    // If we found no text-like events, try to look for a terminal `result` event
171    // which some opencode builds emit. Prefer the last result event (newest).
172    if texts.is_empty() {
173        for event in events.iter().rev() {
174            if let Some(event_type) = event.get("type").and_then(|v| v.as_str()) {
175                // Ignore system/init envelopes
176                if event_type == "system" {
177                    continue;
178                }
179            }
180
181            if let Some(result) = event.get("result") {
182                // If result is a string, return it; if object/array return its JSON
183                if let Some(s) = result.as_str() {
184                    return Some(s.to_string());
185                }
186                if result.is_object() || result.is_array() {
187                    return Some(result.to_string());
188                }
189            }
190
191            // Some events include direct text payloads outside of `part`
192            if let Some(text) = event.get("text").and_then(|v| v.as_str())
193                && !text.trim().is_empty()
194            {
195                return Some(text.to_string());
196            }
197        }
198
199        return None;
200    }
201
202    let full = texts.join("");
203    if let Some(json) = extract_json_object(&full) {
204        // Prefer a full-json payload that parses as an AgentResponse.
205        if parser::parse(&json).is_ok() {
206            return Some(json);
207        }
208
209        // Also accept JSON that looks like a router decision / agent envelope
210        // even when it's not a full AgentResponse (e.g. {"executor":"opencode"}).
211        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&json)
212            && let Some(obj) = val.as_object()
213            && (obj.contains_key("executor")
214                || obj.contains_key("status")
215                || obj.contains_key("complexity")
216                || obj.contains_key("decision"))
217        {
218            return Some(json);
219        }
220        // Otherwise fall through and try per-event heuristics below
221    }
222
223    for text in texts.iter().rev() {
224        let trimmed = text.trim();
225        if let Some(json) = extract_json_object(trimmed) {
226            // Prefer JSON blobs that parse as AgentResponse. This allows
227            // accepting payloads that don't include routing keys but are
228            // nevertheless valid task responses.
229            if parser::parse(&json).is_ok() {
230                return Some(json);
231            }
232
233            // Also accept routing-style JSON objects that don't match the
234            // AgentResponse schema (router decisions, etc.).
235            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&json)
236                && let Some(obj) = val.as_object()
237                && (obj.contains_key("executor") || obj.contains_key("status"))
238            {
239                return Some(json);
240            }
241        }
242        // As a conservative fallback, if the trimmed chunk contains a '{' and
243        // looks like it mentions routing keys, return it. We keep this branch
244        // minimal to avoid accidental acceptance of unrelated log blobs.
245        if trimmed.contains('{') {
246            // As a last-ditch conservative heuristic, accept the chunk if it
247            // can be interpreted as a valid AgentResponse or if it contains
248            // routing keys. This avoids accepting unrelated log blobs while
249            // remaining tolerant of router-style payloads.
250            if parser::parse(trimmed).is_ok() {
251                return Some(trimmed.to_string());
252            }
253
254            if let Ok(val) = serde_json::from_str::<serde_json::Value>(trimmed)
255                && let Some(obj) = val.as_object()
256                && (obj.contains_key("executor")
257                    || obj.contains_key("status")
258                    || obj.contains_key("complexity"))
259            {
260                return Some(trimmed.to_string());
261            }
262        }
263    }
264
265    Some(full)
266}
267
268fn extract_text_from_part(part: &serde_json::Value) -> Vec<String> {
269    let mut out = Vec::new();
270
271    if let Some(text) = part.get("text").and_then(|v| v.as_str()) {
272        out.push(text.to_string());
273    }
274
275    // Some schemas store text content as: {"content":[{"type":"text","text":"..."}, ...]}
276    if let Some(items) = part.get("content").and_then(|v| v.as_array()) {
277        for item in items {
278            let item_type = item.get("type").and_then(|v| v.as_str()).unwrap_or("");
279            if item_type == "text"
280                && let Some(text) = item.get("text").and_then(|v| v.as_str())
281            {
282                out.push(text.to_string());
283            }
284        }
285    }
286
287    out
288}
289
290fn extract_json_object(text: &str) -> Option<String> {
291    let trimmed = text.trim();
292    if serde_json::from_str::<serde_json::Value>(trimmed).is_ok() {
293        return Some(trimmed.to_string());
294    }
295
296    let start = trimmed.find('{')?;
297    let end = trimmed.rfind('}')?;
298    if end <= start {
299        return None;
300    }
301
302    let candidate = trimmed[start..=end].trim();
303    serde_json::from_str::<serde_json::Value>(candidate)
304        .ok()
305        .map(|_| candidate.to_string())
306}
307
308pub(crate) fn extract_router_text(raw: &str) -> Option<String> {
309    let events = super::parse_ndjson(raw.trim());
310    if events.is_empty() {
311        return None;
312    }
313    extract_ndjson_text(&events)
314}
315
316// Each worktree gets its own snapshot git repo under opencode's data dir and nothing removes it.
317// Orch commits the work itself, so turn snapshots off for orch runs only
318const NO_SNAPSHOT_CONFIG: &str = r#"{"snapshot":false}"#;
319
320impl OpenCodeRunner {
321    pub fn new() -> Self {
322        Self
323    }
324
325    /// Split an opencode model identifier into base model and optional variant.
326    ///
327    /// The identifier shape is: "provider/model[@variant]". Splitting is
328    /// performed on the LAST `@` so provider/model strings containing `@`
329    /// are handled correctly. Returns (base, Some(variant)) when a trailing
330    /// `@` is present (variant may be empty), or (s, None) when no `@` exists.
331    pub(crate) fn split_model_variant(s: &str) -> (&str, Option<&str>) {
332        if let Some(pos) = s.rfind('@') {
333            let base = &s[..pos];
334            let variant = &s[pos + 1..];
335            (base, Some(variant))
336        } else {
337            (s, None)
338        }
339    }
340
341    /// Extract text from `text` events.
342    ///
343    /// Concatenates all text events, then tries to find the structured
344    /// JSON response. If the concatenated text doesn't parse as JSON,
345    /// tries each text event individually (newest first) since earlier
346    /// events are often progress messages.
347    ///
348    /// Handles two text event formats emitted by different opencode versions:
349    /// - Format 1 (current): `{"type":"text","part":{"type":"text","text":"..."}}`
350    /// - Format 2 (newer):   `{"type":"text","text":"..."}`
351    fn extract_text_from_events(events: &[serde_json::Value]) -> Option<String> {
352        extract_ndjson_text(events)
353    }
354
355    /// Extract token usage from `step_finish` events.
356    fn extract_tokens(events: &[serde_json::Value]) -> (Option<u64>, Option<u64>) {
357        for event in events.iter().rev() {
358            let event_type = event.get("type").and_then(|v| v.as_str()).unwrap_or("");
359
360            if event_type == "step_finish"
361                && let Some(part) = event.get("part")
362                && let Some(tokens) = part.get("tokens").and_then(|v| v.as_object())
363            {
364                let input = tokens.get("input").and_then(serde_json::Value::as_u64);
365                let output = tokens.get("output").and_then(serde_json::Value::as_u64);
366                return (input, output);
367            }
368        }
369
370        (None, None)
371    }
372
373    /// Check for error events in the stream.
374    fn detect_error(events: &[serde_json::Value]) -> Option<AgentError> {
375        super::patterns::detect_ndjson_error(
376            events,
377            |event| {
378                let event_type = event.get("type").and_then(|v| v.as_str()).unwrap_or("");
379                match event_type {
380                    "error" => Some(opencode_error_text(event)),
381                    "step_finish" => {
382                        let part = event.get("part")?;
383                        let reason = part.get("reason").and_then(|v| v.as_str()).unwrap_or("");
384                        if reason == "error" || reason == "failed" {
385                            Some(
386                                part.get("error")
387                                    .map_or_else(|| "step failed".to_string(), error_value_text),
388                            )
389                        } else {
390                            None
391                        }
392                    }
393                    _ => None,
394                }
395            },
396            classify_opencode_message,
397        )
398    }
399}
400
401/// Render an error value as text: strings as-is, objects by their message/name or raw JSON
402fn error_value_text(v: &serde_json::Value) -> String {
403    if let Some(s) = v.as_str() {
404        return s.to_string();
405    }
406    v.get("data")
407        .and_then(|d| d.get("message").or(Some(d)))
408        .and_then(|m| m.as_str())
409        .or_else(|| v.get("message").and_then(|m| m.as_str()))
410        .or_else(|| v.get("name").and_then(|n| n.as_str()))
411        .map_or_else(|| v.to_string(), str::to_string)
412}
413
414/// Extract the message from an opencode `error` event, keeping the raw JSON when no shape matches
415fn opencode_error_text(event: &serde_json::Value) -> String {
416    if let Some(s) = event.get("message").and_then(|v| v.as_str()) {
417        return s.to_string();
418    }
419    if let Some(e) = event.get("error") {
420        let text = error_value_text(e);
421        if e.is_object() && text == *e {
422            tracing::warn!(event = %event, "unrecognized opencode error event shape");
423        }
424        text
425    } else {
426        tracing::warn!(event = %event, "unrecognized opencode error event shape");
427        event.to_string()
428    }
429}
430
431impl AgentRunner for OpenCodeRunner {
432    fn find_result(&self, ndjson: &str) -> Option<super::AgentResult> {
433        find_opencode_result(ndjson)
434    }
435
436    #[cfg(test)]
437    fn name(&self) -> &'static str {
438        "opencode"
439    }
440
441    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent> {
442        stream_events(event)
443    }
444
445    fn router_transcript(&self) -> super::RouterTranscript {
446        super::RouterTranscript::OpenCode
447    }
448
449    fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
450        let trimmed = raw.trim();
451        if trimmed.is_empty() {
452            return Ok(String::new());
453        }
454
455        let events = super::parse_ndjson(trimmed);
456        if events.is_empty() {
457            return Ok(trimmed.to_string());
458        }
459
460        // Propagate terminal errors so the review pipeline records cooldowns.
461        if let Some(err) = Self::detect_error(&events) {
462            return Err(err);
463        }
464
465        // Concatenate all text events; fall back to raw output if none found.
466        Ok(extract_ndjson_text(&events).unwrap_or_else(|| trimmed.to_string()))
467    }
468
469    fn build_command(
470        &self,
471        model: Option<&str>,
472        timeout_cmd: &str,
473        sys_file: &str,
474        msg_file: &str,
475        permissions: &PermissionRules,
476    ) -> String {
477        self.build_command_with_effort(model, None, timeout_cmd, sys_file, msg_file, permissions)
478    }
479
480    fn build_command_with_effort(
481        &self,
482        model: Option<&str>,
483        effort: Option<&str>,
484        timeout_cmd: &str,
485        sys_file: &str,
486        msg_file: &str,
487        permissions: &PermissionRules,
488    ) -> String {
489        // Support optional variant suffix on opencode model identifiers:
490        // provider/model[@variant]
491        let (model_flag, variant_flag) = if let Some(m) = model {
492            let (base, variant) = Self::split_model_variant(m);
493            let mf = format!("--model {}", super::shell_single_quote(base));
494            let vf = effort
495                .or(variant)
496                .map(|v| format!("--variant {}", super::shell_single_quote(v)));
497            (mf, vf)
498        } else {
499            (String::new(), None)
500        };
501
502        // OpenCode autonomous permission control.
503        //
504        // `--dangerously-skip-permissions` auto-approves any tool that isn't
505        // explicitly denied, which is what orch needs for unattended dispatch.
506        // It avoids the user's global ~/.config/opencode/opencode.json defaults
507        // (e.g. "edit":"ask", "external_directory":"ask") that would otherwise
508        // block agent file edits and git operations on the worktree.
509        //
510        // The previously-used .orch-opencode/opencode/opencode.json +
511        // XDG_CONFIG_HOME override is no longer needed: the only `deny` entries
512        // it set were for opencode's interactive-only features (todowrite,
513        // question, codesearch, list) which never fire under `opencode run`.
514        let skip_perms = if permissions.autonomous {
515            "--dangerously-skip-permissions "
516        } else {
517            ""
518        };
519
520        // `opencode run` is a client of a background service that runs every tool outside the
521        // sandbox. `--standalone` keeps the server in this process tree, and its pty helper's
522        // socket must sit where the sandbox allows one
523        let (pty_env, standalone) = if permissions.sandbox == SandboxLevel::Os {
524            (
525                r#"mkdir -p "$TMPDIR/pty" && OPENCODE_PTY_SOCKET_DIR="$TMPDIR/pty" "#,
526                "--standalone ",
527            )
528        } else {
529            ("", "")
530        };
531
532        // Append variant flag when present
533        let variant_part = variant_flag.unwrap_or_default();
534        // Feed both files via process substitution rather than a leading `cat |`
535        // pipe stage — a leading pipe would make `cat`, not opencode, the first
536        // stage in the runner script's pipeline, so PIPESTATUS[0] there would
537        // always report cat's (always-zero) exit code instead of opencode's.
538        format!(
539            r#"{pty_env}OPENCODE_CONFIG_CONTENT={config} {timeout_cmd} opencode run {standalone}{model_flag} {variant_part} {skip_perms}\
540  --format json - < <(cat "{sys_file}" "{msg_file}")"#,
541            config = super::shell_single_quote(NO_SNAPSHOT_CONFIG),
542            sys_file = sys_file,
543            msg_file = msg_file,
544            timeout_cmd = timeout_cmd,
545            model_flag = model_flag,
546            variant_part = variant_part,
547            skip_perms = skip_perms,
548        )
549    }
550
551    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError> {
552        let trimmed = raw.trim();
553        // Empty output with exit code 0 is a silent failure — return Unknown with
554        // a deterministic message matching what fallback.rs expects so the model
555        // gets a cooldown and free-model retry is attempted.
556        if trimmed.is_empty() {
557            return Err(AgentError::Unknown {
558                exit_code: 0,
559                message: "empty-output-exit0: opencode returned exit 0 with empty stdout"
560                    .to_string(),
561            });
562        }
563
564        let events = super::parse_ndjson(trimmed);
565
566        if events.is_empty() {
567            // Maybe direct JSON
568            if let Ok(resp) = parser::parse(trimmed) {
569                return Ok(ParsedResponse {
570                    response: resp,
571                    input_tokens: None,
572                    output_tokens: None,
573                    cost_usd: None,
574                    duration_ms: None,
575                });
576            }
577            return Err(AgentError::InvalidResponse {
578                raw: trimmed.to_string(),
579            });
580        }
581
582        // Check for errors first
583        if let Some(err) = Self::detect_error(&events) {
584            return Err(err);
585        }
586
587        // Extract tokens (needed for both the text path and the tool-only fallback)
588        let (input_tokens, output_tokens) = Self::extract_tokens(&events);
589
590        // Extract text — when opencode emits only tool_use/step events with no
591        // text content, synthesize a human-readable summary from the event
592        // stream instead of falling through to InvalidResponse. Otherwise the
593        // upstream `synthesize_response_from_text` heuristic gets handed the
594        // entire raw NDJSON, matches a "completed" substring inside tool state
595        // JSON, and emits 500 bytes of raw NDJSON as the task summary.
596        let Some(text) = Self::extract_text_from_events(&events) else {
597            let response = synthesize_response_from_events(&events);
598            return Ok(ParsedResponse {
599                response,
600                input_tokens,
601                output_tokens,
602                cost_usd: extract_cost(&events),
603                duration_ms: None,
604            });
605        };
606
607        // Parse the text through standard parser
608        let response = match parser::parse(&text) {
609            Ok(r) => r,
610            Err(_) => {
611                // Structured parse failed — try plain-text synthesis before
612                // giving up, same rescue path claude.rs uses (issue #3467).
613                super::synthesize_response_from_text(&text)
614                    .ok_or_else(|| AgentError::InvalidResponse { raw: text.clone() })?
615            }
616        };
617
618        Ok(ParsedResponse {
619            response,
620            input_tokens,
621            output_tokens,
622            cost_usd: extract_cost(&events),
623            duration_ms: None,
624        })
625    }
626
627    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError {
628        // Try parsing NDJSON events from stdout for structured errors
629        let events = super::parse_ndjson(stdout);
630        if let Some(err) = Self::detect_error(&events) {
631            return err;
632        }
633
634        let combined = format!("{stdout}\n{stderr}");
635        super::patterns::classify_from_text(exit_code, &combined)
636    }
637
638    fn free_models(&self) -> Vec<String> {
639        discover_free_opencode_models()
640    }
641
642    fn available_models(&self) -> Vec<String> {
643        // Known default models; could be extended with `opencode models` discovery
644        vec![
645            "anthropic/claude-sonnet-4-20250514".to_string(),
646            "openai/gpt-4.1".to_string(),
647        ]
648    }
649
650    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command> {
651        // Routing only needs text output — no tools fire.
652        // `--dangerously-skip-permissions` prevents the user's global
653        // ~/.config/opencode/opencode.json interactive defaults (e.g.
654        // "edit":"ask") from producing PermissionError events that the router
655        // would misclassify as model failures.
656        let mut cmd = Command::new("opencode");
657        cmd.env("OPENCODE_CONFIG_CONTENT", NO_SNAPSHOT_CONFIG)
658            .arg("run")
659            .arg("--format")
660            .arg("json")
661            .arg("--dangerously-skip-permissions");
662        if let Some(m) = model {
663            let (base, variant) = Self::split_model_variant(m);
664            cmd.arg("--model").arg(base);
665            if let Some(v) = variant {
666                // pass variant even if empty (last-token-wins semantics)
667                cmd.arg("--variant").arg(v);
668            }
669        }
670        cmd.arg(prompt);
671        Ok(cmd)
672    }
673}
674
675/// Classify an OpenCode error message.
676fn classify_opencode_message(message: &str) -> AgentError {
677    let lower = message.to_lowercase();
678
679    // Rate limit — delegate to shared helper
680    if let Some(e) = super::patterns::detect_rate_limit(message) {
681        return e;
682    }
683
684    // Context overflow — delegate to shared helper (covers "context overflow", "context length", etc.)
685    if let Some(e) = super::patterns::detect_context_overflow(message) {
686        return e;
687    }
688
689    // Auth errors — delegate to shared helper (includes HTTP 401/403, billing, etc.)
690    if let Some(e) = super::patterns::detect_auth_error(message) {
691        return e;
692    }
693
694    // Permission denied — delegate to shared helper
695    if let Some(e) = super::patterns::detect_permission_denied(message) {
696        return e;
697    }
698
699    // Model not available (opencode-specific extraction pattern)
700    //
701    // Patterns handled:
702    //   "Model not found: anthropic/claude-sonnet-4-6."
703    //   "Model not found: github-copilot/gemini-3.1-pro. Did you mean: gemini-3.1-pro-preview?"
704    //   "model not supported: X"
705    //   "The free model has been deprecated. Transition to qwen/qwen3.6-plus for continued paid access."
706    //   "No endpoints found for qwen/qwen3.6-plus:free."
707    //   "This model is unavailable for free. The paid version is available now - use this slug instead: X"
708    //   "This model is not available in your country."
709    let is_model_unavailable = (lower.contains("model")
710        && (lower.contains("not found")
711            || lower.contains("not supported")
712            || lower.contains("deprecated")
713            || lower.contains("unavailable for free")
714            || lower.contains("not available in your country")
715            || lower.contains("not available in your region")))
716        || lower.contains("no endpoints found");
717
718    if is_model_unavailable {
719        // Try to extract model name from patterns like "Model not found: anthropic/claude-sonnet-4-6."
720        // or "No endpoints found for qwen/qwen3.6-plus:free."
721        let model = if lower.contains("no endpoints found") {
722            // "No endpoints found for X." — extract X after "for "
723            message
724                .split(" for ")
725                .nth(1)
726                .map(|s| s.trim_end_matches('.').to_string())
727                .unwrap_or_default()
728        } else {
729            // Try "Model not found: X" or "model not supported: X" patterns
730            let from_colon = message
731                .split(": ")
732                .nth(1)
733                .map(|s| {
734                    // Strip opencode's "Did you mean: X?" suggestion suffix if present
735                    s.split(". Did you mean")
736                        .next()
737                        .unwrap_or(s)
738                        .trim_end_matches('.')
739                        .to_string()
740                })
741                .filter(|s| !s.is_empty());
742
743            // For deprecated messages like "The free model has been deprecated. Transition to X for..."
744            // extract the model from "Transition to X" when colon-based extraction yields nothing.
745            let from_transition = if lower.contains("deprecated") {
746                message
747                    .split("Transition to ")
748                    .nth(1)
749                    .and_then(|s| s.split(" for ").next())
750                    .map(|s| s.trim_end_matches('.').to_string())
751                    .filter(|s| !s.is_empty())
752            } else {
753                None
754            };
755
756            // For "unavailable for free" messages like "... use this slug instead: X"
757            // extract the suggested replacement slug.
758            let from_slug_suggestion = if lower.contains("unavailable for free") {
759                message
760                    .split("use this slug instead: ")
761                    .nth(1)
762                    .map(|s| s.trim_end_matches('.').trim().to_string())
763                    .filter(|s| !s.is_empty())
764            } else {
765                None
766            };
767
768            // Transition/slug extractions are tied to specific message shapes and take
769            // priority over the generic colon split, which would otherwise grab the
770            // wrong substring (e.g. the "[404] ..." text before the real slug).
771            from_transition
772                .or(from_slug_suggestion)
773                .or(from_colon)
774                .unwrap_or_default()
775        };
776        return AgentError::ModelUnavailable {
777            message: message.to_string(),
778            model,
779        };
780    }
781
782    // OpenCode surfaces opaque upstream provider failures as "Provider returned error".
783    // Treat this as a usage-limit class signal so fallback/error tracking records a
784    // rate-limit event (instead of a generic failure), allowing router health/degraded
785    // checks to react faster to unstable provider/model endpoints.
786    if lower.contains("provider returned error") {
787        return AgentError::RateLimit {
788            message: message.to_string(),
789        };
790    }
791
792    // Transient network/transport errors (e.g. "Upstream idle timeout exceeded")
793    if let Some(e) = super::patterns::detect_network_error(message) {
794        return e;
795    }
796
797    AgentError::AgentFailed {
798        message: message.to_string(),
799    }
800}
801
802/// Discover free opencode models, with 1-hour cache and background refresh.
803///
804/// This is the single source of truth for free model discovery. Called by
805/// the router (pool expansion, model_map), the runner (failover), and
806/// startup priming.
807///
808/// Non-blocking: returns cached data immediately. When the cache is cold
809/// or expired, spawns a background thread to refresh via `opencode models`.
810pub fn discover_free_opencode_models() -> Vec<String> {
811    if skip_live_opencode_discovery() {
812        return Vec::new();
813    }
814    let cache = FREE_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
815
816    let now = chrono::Utc::now().timestamp();
817    // Fast path: return cached data if still fresh (1-hour TTL).
818    {
819        let guard = cache.lock().unwrap_or_else(PoisonError::into_inner);
820        let (ts, models) = &*guard;
821        if *ts != 0 && now.saturating_sub(*ts) < 3600 {
822            return models.clone();
823        }
824    }
825
826    // Cache is cold or expired. Spawn a background task on the current runtime to refresh.
827    // Only one refresh runs at a time.
828    if !FREE_MODELS_REFRESH_IN_PROGRESS.swap(true, Ordering::AcqRel) {
829        let refresh = async {
830            let _guard = scopeguard::guard((), |()| {
831                FREE_MODELS_REFRESH_IN_PROGRESS.store(false, Ordering::Release);
832            });
833            let (models, empty_reason) = run_opencode_models_discovery_async().await;
834            let raw_count = models.len();
835            let discovered = models
836                .into_iter()
837                .filter(|m| m.to_lowercase().contains("free"))
838                .collect::<Vec<_>>();
839            let empty_reason = if discovered.is_empty() && raw_count > 0 {
840                "no_free_models_in_catalog"
841            } else {
842                empty_reason
843            };
844            let cache = FREE_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
845            update_discovered_models_cache(cache, discovered, "free", empty_reason);
846        };
847        match Handle::try_current() {
848            Ok(handle) => {
849                // Use the current tokio runtime's handle to spawn the async discovery task,
850                // avoiding the overhead of a std::thread + new tokio runtime.
851                handle.spawn(refresh);
852            }
853            _ => {
854                // No tokio runtime (e.g. called from a plain unit test). Spawn a thread
855                // with a dedicated runtime — this is the fallback path.
856                thread::spawn(move || {
857                    if let Ok(rt) = Runtime::new() {
858                        rt.block_on(refresh);
859                    }
860                });
861            }
862        }
863    }
864
865    // Return whatever is in cache (may be empty on first call).
866    let guard = cache.lock().unwrap_or_else(PoisonError::into_inner);
867    guard.1.clone()
868}
869
870/// Discover all opencode models, with 1-hour cache and background refresh.
871///
872/// Non-blocking: returns cached data immediately. When the cache is cold
873/// or expired, spawns a background refresh via `opencode models`.
874pub fn discover_opencode_models() -> Vec<String> {
875    if skip_live_opencode_discovery() {
876        return Vec::new();
877    }
878    let cache = ALL_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
879    let now = chrono::Utc::now().timestamp();
880
881    {
882        let guard = cache.lock().unwrap_or_else(PoisonError::into_inner);
883        let (ts, models) = &*guard;
884        if *ts != 0 && now.saturating_sub(*ts) < 3600 {
885            return models.clone();
886        }
887    }
888
889    if !ALL_MODELS_REFRESH_IN_PROGRESS.swap(true, Ordering::AcqRel) {
890        let refresh = async {
891            let _guard = scopeguard::guard((), |()| {
892                ALL_MODELS_REFRESH_IN_PROGRESS.store(false, Ordering::Release);
893            });
894            let (discovered, empty_reason) = run_opencode_models_discovery_async().await;
895            let cache = ALL_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
896            update_discovered_models_cache(cache, discovered, "all", empty_reason);
897        };
898        match Handle::try_current() {
899            Ok(handle) => {
900                handle.spawn(refresh);
901            }
902            _ => {
903                thread::spawn(move || {
904                    if let Ok(rt) = Runtime::new() {
905                        rt.block_on(refresh);
906                    }
907                });
908            }
909        }
910    }
911
912    let guard = cache.lock().unwrap_or_else(PoisonError::into_inner);
913    guard.1.clone()
914}
915
916/// Prime the free-model cache synchronously at startup.
917///
918/// Called from `Router::new()` via `spawn_blocking` so the initial
919/// blocking subprocess doesn't stall the Tokio runtime.
920/// Runs `run_opencode_models_discovery_async()` in a dedicated thread with its
921/// own tokio runtime, avoiding `block_on` restrictions when called from within
922/// an existing runtime (e.g. `#[tokio::test]` or a nested runtime context).
923pub fn prime_free_model_cache() {
924    if skip_live_opencode_discovery() {
925        return;
926    }
927    let discovered_all = thread::spawn(|| match Runtime::new() {
928        Ok(rt) => rt.block_on(run_opencode_models_discovery_async()).0,
929        _ => {
930            vec![]
931        }
932    })
933    .join()
934    .unwrap_or_default();
935    let cache = FREE_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
936    let now = chrono::Utc::now().timestamp();
937    if let Ok(mut guard) = cache.lock() {
938        *guard = (
939            now,
940            discovered_all
941                .iter()
942                .filter(|m| m.to_lowercase().contains("free"))
943                .cloned()
944                .collect(),
945        );
946    }
947    let all_cache = ALL_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
948    if let Ok(mut guard) = all_cache.lock() {
949        *guard = (now, discovered_all);
950    }
951}
952
953/// Async version of `run_opencode_models_discovery` that uses `tokio::time::sleep`
954/// instead of blocking `std::thread::sleep`.
955///
956/// Returns the discovered models plus a reason code describing why the list
957/// is empty (`"ok"` when discovery actually succeeded with a non-empty
958/// result). The reason is threaded into `update_discovered_models_cache` so
959/// the "returned empty" warning says which of the failure branches fired,
960/// without requiring `RUST_LOG=debug` in production.
961async fn run_opencode_models_discovery_async() -> (Vec<String>, &'static str) {
962    run_opencode_models_cli(Duration::from_secs(30)).await
963}
964
965/// Run `opencode models` and reap any process-group leftovers when it returns
966pub(crate) async fn run_opencode_models_cli(timeout: Duration) -> (Vec<String>, &'static str) {
967    run_opencode_models_cli_inner("opencode", timeout).await
968}
969
970fn opencode_program_available(program: &str) -> bool {
971    let path = Path::new(program);
972    if path.is_absolute() || program.contains('/') {
973        path.is_file()
974    } else {
975        cmd_cache::command_exists(program)
976    }
977}
978
979async fn run_opencode_models_cli_inner(
980    program: &str,
981    timeout: Duration,
982) -> (Vec<String>, &'static str) {
983    if !opencode_program_available(program) {
984        tracing::warn!("opencode not in PATH, skipping model discovery");
985        return (vec![], "command_not_found");
986    }
987
988    // A private server, since the background service can stay behind, and inside the sandbox,
989    // where an agent runs orch, a missing service makes opencode run `ps`, which the sandbox denies
990    let mut cmd = Command::new(program);
991    cmd.args(["models", "--standalone"])
992        .stdout(Stdio::piped())
993        .stderr(Stdio::piped())
994        .kill_on_drop(true);
995    #[cfg(unix)]
996    cmd.process_group(0);
997
998    let child = match cmd.spawn() {
999        Ok(c) => c,
1000        Err(e) => {
1001            tracing::warn!(error = %e, "failed to spawn opencode models");
1002            return (vec![], "spawn_failed");
1003        }
1004    };
1005    let pgid = child.id();
1006    let wait = time::timeout(timeout, child.wait_with_output()).await;
1007
1008    #[cfg(unix)]
1009    if let Some(pid) = pgid {
1010        cmd::kill_process_group(pid);
1011    }
1012
1013    match wait {
1014        Ok(Ok(output)) if output.status.success() => {
1015            let models: Vec<String> = String::from_utf8_lossy(&output.stdout)
1016                .lines()
1017                .map(|l| l.trim().to_string())
1018                .filter(|l| !l.is_empty())
1019                .collect();
1020            let reason = if models.is_empty() {
1021                "empty_output"
1022            } else {
1023                "ok"
1024            };
1025            (models, reason)
1026        }
1027        Ok(Ok(output)) => {
1028            let stderr = String::from_utf8_lossy(&output.stderr);
1029            let stderr = stderr.trim();
1030            let stderr_display = if stderr.len() > 500 {
1031                format!("{}...", &stderr[..stderr.floor_char_boundary(500)])
1032            } else {
1033                stderr.to_string()
1034            };
1035            tracing::warn!(
1036                status = ?output.status,
1037                stderr = %stderr_display,
1038                "opencode models command failed"
1039            );
1040            (vec![], "exit_status_failure")
1041        }
1042        Ok(Err(e)) => {
1043            tracing::warn!(error = %e, "failed to wait on opencode models");
1044            (vec![], "wait_failed")
1045        }
1046        Err(_) => {
1047            tracing::warn!(
1048                secs = timeout.as_secs(),
1049                "opencode models timed out, killing process group"
1050            );
1051            (vec![], "timeout")
1052        }
1053    }
1054}
1055
1056/// Build a synthetic `AgentResponse` summarizing an opencode NDJSON event
1057/// stream when no `text` events are present.
1058///
1059/// Opencode runs that produced tool calls but never emitted a text event
1060/// (model exited mid-tool, stop_reason without a final reply, etc.) would
1061/// otherwise be passed to `synthesize_response_from_text` as raw NDJSON.
1062/// That heuristic matches "completed" substrings inside tool state JSON and
1063/// emits the first 500 bytes of NDJSON as the notification summary — what
1064/// the user sees as garbage in Telegram/Discord/Slack.
1065///
1066/// Status is `needs_review` because there is no text confirming completion;
1067/// the agent did work but never reported on it.
1068fn synthesize_response_from_events(events: &[serde_json::Value]) -> AgentResponse {
1069    let mut counts: BTreeMap<String, u32> = BTreeMap::new();
1070    let mut tool_names: Vec<String> = Vec::new();
1071    let mut step_finish_reason: Option<String> = None;
1072
1073    for event in events {
1074        let event_type = event
1075            .get("type")
1076            .and_then(|v| v.as_str())
1077            .unwrap_or("unknown");
1078        *counts.entry(event_type.to_string()).or_insert(0) += 1;
1079
1080        if event_type == "step_finish"
1081            && let Some(reason) = event
1082                .get("part")
1083                .and_then(|p| p.get("reason"))
1084                .and_then(|r| r.as_str())
1085        {
1086            step_finish_reason = Some(reason.to_string());
1087        }
1088
1089        // Capture tool names from common opencode/claude-style shapes.
1090        if event_type == "tool_use"
1091            && let Some(name) = event
1092                .get("name")
1093                .and_then(|v| v.as_str())
1094                .or_else(|| event.get("tool").and_then(|v| v.as_str()))
1095                .or_else(|| {
1096                    event
1097                        .get("part")
1098                        .and_then(|p| p.get("name"))
1099                        .and_then(|v| v.as_str())
1100                })
1101                .or_else(|| {
1102                    event
1103                        .get("tool")
1104                        .and_then(|t| t.get("name"))
1105                        .and_then(|v| v.as_str())
1106                })
1107        {
1108            tool_names.push(name.to_string());
1109        }
1110    }
1111
1112    let total_events = events.len();
1113    let reason = step_finish_reason.as_deref().unwrap_or("unknown");
1114
1115    let tool_summary = if tool_names.is_empty() {
1116        String::new()
1117    } else {
1118        let mut tool_counts: BTreeMap<String, u32> = BTreeMap::new();
1119        for n in &tool_names {
1120            *tool_counts.entry(n.clone()).or_insert(0) += 1;
1121        }
1122        let parts: Vec<String> = tool_counts
1123            .iter()
1124            .map(|(k, v)| {
1125                if *v > 1 {
1126                    format!("{k}×{v}")
1127                } else {
1128                    k.clone()
1129                }
1130            })
1131            .collect();
1132        format!(" (tools: {})", parts.join(", "))
1133    };
1134
1135    let summary = format!(
1136        "opencode emitted {total_events} event(s) with no text output{tool_summary}; \
1137         step_finish reason: {reason}"
1138    );
1139
1140    AgentResponse {
1141        status: "needs_review".to_string(),
1142        summary,
1143        error: Some("agent emitted no text response — only tool/step events".to_string()),
1144        ..Default::default()
1145    }
1146}
1147
1148/// The cost opencode reports in the last `step_finish` event, if any.
1149fn extract_cost(events: &[serde_json::Value]) -> Option<f64> {
1150    events.iter().rev().find_map(|event| {
1151        if event.get("type").and_then(|v| v.as_str()) == Some("step_finish") {
1152            event
1153                .get("part")
1154                .and_then(|p| p.get("cost"))
1155                .and_then(serde_json::Value::as_f64)
1156                .filter(|&c| c > 0.0)
1157        } else {
1158            None
1159        }
1160    })
1161}
1162
1163/// Extract a structured `AgentResult` from OpenCode NDJSON output.
1164///
1165/// Concatenates text from `type:text` events (both `part.text` and direct
1166/// `text` field formats), extracts tokens from the last `step_finish` event,
1167/// and checks for `error` / `step_finish.reason=error` events.
1168///
1169/// Returns `None` only if no parseable NDJSON events are found.
1170pub fn find_opencode_result(ndjson: &str) -> Option<super::AgentResult> {
1171    let events = super::parse_ndjson(ndjson.trim());
1172    if events.is_empty() {
1173        return None;
1174    }
1175
1176    // Check for errors first
1177    let is_error;
1178    let error_text;
1179    if let Some(err) = OpenCodeRunner::detect_error(&events) {
1180        is_error = true;
1181        error_text = Some(err.to_string());
1182    } else {
1183        is_error = false;
1184        error_text = None;
1185    }
1186
1187    // Extract text content
1188    let result_text = if is_error {
1189        error_text.unwrap_or_default()
1190    } else {
1191        extract_ndjson_text(&events).unwrap_or_default()
1192    };
1193
1194    // Extract tokens from step_finish
1195    let (input_tokens, output_tokens) = OpenCodeRunner::extract_tokens(&events);
1196
1197    // The model was cut off for exceeding its output/reasoning token budget,
1198    // not because it produced malformed prose. Distinguish this from a
1199    // generic parse failure so callers don't apply the long
1200    // format-incapable-model cooldown for a token-budget fluke. A reasoning
1201    // model that spends its entire budget on hidden reasoning emits zero
1202    // text and a final step_finish of reason="length" (or opencode's
1203    // "unknown" with all-zero tokens) — same failure mode, must be computed
1204    // before the empty-text early return below or it never gets checked.
1205    let last_step_finish_reason = events
1206        .iter()
1207        .rev()
1208        .find(|event| event.get("type").and_then(|v| v.as_str()) == Some("step_finish"))
1209        .and_then(|event| {
1210            event
1211                .get("part")?
1212                .get("reason")?
1213                .as_str()
1214                .map(str::to_string)
1215        });
1216    let truncated_by_length = match last_step_finish_reason.as_deref() {
1217        Some("length") => true,
1218        Some("unknown") => output_tokens == Some(0),
1219        _ => false,
1220    };
1221
1222    if result_text.is_empty() && !is_error && !truncated_by_length {
1223        return None;
1224    }
1225
1226    let cost_usd = extract_cost(&events);
1227
1228    Some(super::AgentResult {
1229        is_error,
1230        result_text,
1231        input_tokens,
1232        output_tokens,
1233        cost_usd,
1234        duration_ms: None,
1235        truncated_by_length,
1236    })
1237}
1238
1239/// OpenCode `--format json`: a `tool_use` event carries both the call and its finished state
1240fn stream_events(v: &serde_json::Value) -> Vec<StreamEvent> {
1241    let text = || {
1242        v.pointer("/part/text")
1243            .or_else(|| v.get("text"))
1244            .and_then(serde_json::Value::as_str)
1245            .unwrap_or("")
1246            .to_string()
1247    };
1248    match json_str(v, "/type") {
1249        "text" => vec![StreamEvent::Text(text())],
1250        "reasoning" => vec![StreamEvent::Thinking(text())],
1251        "tool_use" => {
1252            let part = &v["part"];
1253            let state = &part["state"];
1254            let id = json_str(part, "/callID").to_string();
1255            let name = json_str(part, "/tool").to_string();
1256            let mut out = vec![StreamEvent::ToolCall {
1257                id: id.clone(),
1258                name: name.clone(),
1259                input: state["input"].clone(),
1260            }];
1261            let result = match json_str(state, "/status") {
1262                "completed" => Some((json_str(state, "/output").to_string(), false)),
1263                "error" => Some((json_error_message(state), true)),
1264                _ => None,
1265            };
1266            if let Some((output, is_error)) = result {
1267                out.push(StreamEvent::ToolResult {
1268                    id,
1269                    name,
1270                    output,
1271                    is_error,
1272                });
1273            }
1274
1275            out
1276        }
1277        "step_finish" if json_str(v, "/part/reason") == "stop" => {
1278            vec![StreamEvent::Done(String::new())]
1279        }
1280        "error" => vec![StreamEvent::Error(json_error_message(v))],
1281        _ => vec![],
1282    }
1283}
1284
1285#[cfg(test)]
1286mod router_text_tests;
1287
1288#[cfg(test)]
1289mod tests;
1290
1291#[cfg(test)]
1292mod error_text_tests;
1293
1294#[cfg(test)]
1295mod stream_tests;