Skip to main content

orch/engine/runner/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::cmd;
32use crate::cmd_cache;
33use crate::parser;
34use crate::parser::AgentResponse;
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    #[cfg(test)]
433    fn name(&self) -> &'static str {
434        "opencode"
435    }
436
437    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent> {
438        stream_events(event)
439    }
440
441    fn router_transcript(&self) -> super::RouterTranscript {
442        super::RouterTranscript::OpenCode
443    }
444
445    fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
446        let trimmed = raw.trim();
447        if trimmed.is_empty() {
448            return Ok(String::new());
449        }
450
451        let events = super::parse_ndjson(trimmed);
452        if events.is_empty() {
453            return Ok(trimmed.to_string());
454        }
455
456        // Propagate terminal errors so the review pipeline records cooldowns.
457        if let Some(err) = Self::detect_error(&events) {
458            return Err(err);
459        }
460
461        // Concatenate all text events; fall back to raw output if none found.
462        Ok(extract_ndjson_text(&events).unwrap_or_else(|| trimmed.to_string()))
463    }
464
465    fn build_command(
466        &self,
467        model: Option<&str>,
468        timeout_cmd: &str,
469        sys_file: &str,
470        msg_file: &str,
471        permissions: &PermissionRules,
472    ) -> String {
473        self.build_command_with_effort(model, None, timeout_cmd, sys_file, msg_file, permissions)
474    }
475
476    fn build_command_with_effort(
477        &self,
478        model: Option<&str>,
479        effort: Option<&str>,
480        timeout_cmd: &str,
481        sys_file: &str,
482        msg_file: &str,
483        permissions: &PermissionRules,
484    ) -> String {
485        // Support optional variant suffix on opencode model identifiers:
486        // provider/model[@variant]
487        let (model_flag, variant_flag) = if let Some(m) = model {
488            let (base, variant) = Self::split_model_variant(m);
489            let mf = format!("--model {}", super::shell_single_quote(base));
490            let vf = effort
491                .or(variant)
492                .map(|v| format!("--variant {}", super::shell_single_quote(v)));
493            (mf, vf)
494        } else {
495            (String::new(), None)
496        };
497
498        // OpenCode autonomous permission control.
499        //
500        // `--dangerously-skip-permissions` auto-approves any tool that isn't
501        // explicitly denied, which is what orch needs for unattended dispatch.
502        // It avoids the user's global ~/.config/opencode/opencode.json defaults
503        // (e.g. "edit":"ask", "external_directory":"ask") that would otherwise
504        // block agent file edits and git operations on the worktree.
505        //
506        // The previously-used .orch-opencode/opencode/opencode.json +
507        // XDG_CONFIG_HOME override is no longer needed: the only `deny` entries
508        // it set were for opencode's interactive-only features (todowrite,
509        // question, codesearch, list) which never fire under `opencode run`.
510        let skip_perms = if permissions.autonomous {
511            "--dangerously-skip-permissions "
512        } else {
513            ""
514        };
515
516        // `opencode run` is a client of a background service that runs every tool outside the
517        // sandbox. `--standalone` keeps the server in this process tree, and its pty helper's
518        // socket must sit where the sandbox allows one
519        let (pty_env, standalone) = if permissions.sandbox == SandboxLevel::Os {
520            (
521                r#"mkdir -p "$TMPDIR/pty" && OPENCODE_PTY_SOCKET_DIR="$TMPDIR/pty" "#,
522                "--standalone ",
523            )
524        } else {
525            ("", "")
526        };
527
528        // Append variant flag when present
529        let variant_part = variant_flag.unwrap_or_default();
530        // Feed both files via process substitution rather than a leading `cat |`
531        // pipe stage — a leading pipe would make `cat`, not opencode, the first
532        // stage in the runner script's pipeline, so PIPESTATUS[0] there would
533        // always report cat's (always-zero) exit code instead of opencode's.
534        format!(
535            r#"{pty_env}OPENCODE_CONFIG_CONTENT={config} {timeout_cmd} opencode run {standalone}{model_flag} {variant_part} {skip_perms}\
536  --format json - < <(cat "{sys_file}" "{msg_file}")"#,
537            config = super::shell_single_quote(NO_SNAPSHOT_CONFIG),
538            sys_file = sys_file,
539            msg_file = msg_file,
540            timeout_cmd = timeout_cmd,
541            model_flag = model_flag,
542            variant_part = variant_part,
543            skip_perms = skip_perms,
544        )
545    }
546
547    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError> {
548        let trimmed = raw.trim();
549        // Empty output with exit code 0 is a silent failure — return Unknown with
550        // a deterministic message matching what fallback.rs expects so the model
551        // gets a cooldown and free-model retry is attempted.
552        if trimmed.is_empty() {
553            return Err(AgentError::Unknown {
554                exit_code: 0,
555                message: "empty-output-exit0: opencode returned exit 0 with empty stdout"
556                    .to_string(),
557            });
558        }
559
560        let events = super::parse_ndjson(trimmed);
561
562        if events.is_empty() {
563            // Maybe direct JSON
564            if let Ok(resp) = parser::parse(trimmed) {
565                return Ok(ParsedResponse {
566                    response: resp,
567                    input_tokens: None,
568                    output_tokens: None,
569                    cost_usd: None,
570                    duration_ms: None,
571                });
572            }
573            return Err(AgentError::InvalidResponse {
574                raw: trimmed.to_string(),
575            });
576        }
577
578        // Check for errors first
579        if let Some(err) = Self::detect_error(&events) {
580            return Err(err);
581        }
582
583        // Extract tokens (needed for both the text path and the tool-only fallback)
584        let (input_tokens, output_tokens) = Self::extract_tokens(&events);
585
586        // Extract text — when opencode emits only tool_use/step events with no
587        // text content, synthesize a human-readable summary from the event
588        // stream instead of falling through to InvalidResponse. Otherwise the
589        // upstream `synthesize_response_from_text` heuristic gets handed the
590        // entire raw NDJSON, matches a "completed" substring inside tool state
591        // JSON, and emits 500 bytes of raw NDJSON as the task summary.
592        let Some(text) = Self::extract_text_from_events(&events) else {
593            let response = synthesize_response_from_events(&events);
594            return Ok(ParsedResponse {
595                response,
596                input_tokens,
597                output_tokens,
598                cost_usd: extract_cost(&events),
599                duration_ms: None,
600            });
601        };
602
603        // Parse the text through standard parser
604        let response = match parser::parse(&text) {
605            Ok(r) => r,
606            Err(_) => {
607                // Structured parse failed — try plain-text synthesis before
608                // giving up, same rescue path claude.rs uses (issue #3467).
609                super::synthesize_response_from_text(&text)
610                    .ok_or_else(|| AgentError::InvalidResponse { raw: text.clone() })?
611            }
612        };
613
614        Ok(ParsedResponse {
615            response,
616            input_tokens,
617            output_tokens,
618            cost_usd: extract_cost(&events),
619            duration_ms: None,
620        })
621    }
622
623    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError {
624        // Try parsing NDJSON events from stdout for structured errors
625        let events = super::parse_ndjson(stdout);
626        if let Some(err) = Self::detect_error(&events) {
627            return err;
628        }
629
630        let combined = format!("{stdout}\n{stderr}");
631        super::patterns::classify_from_text(exit_code, &combined)
632    }
633
634    fn free_models(&self) -> Vec<String> {
635        discover_free_opencode_models()
636    }
637
638    fn available_models(&self) -> Vec<String> {
639        // Known default models; could be extended with `opencode models` discovery
640        vec![
641            "anthropic/claude-sonnet-4-20250514".to_string(),
642            "openai/gpt-4.1".to_string(),
643        ]
644    }
645
646    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command> {
647        // Routing only needs text output — no tools fire.
648        // `--dangerously-skip-permissions` prevents the user's global
649        // ~/.config/opencode/opencode.json interactive defaults (e.g.
650        // "edit":"ask") from producing PermissionError events that the router
651        // would misclassify as model failures.
652        let mut cmd = Command::new("opencode");
653        cmd.env("OPENCODE_CONFIG_CONTENT", NO_SNAPSHOT_CONFIG)
654            .arg("run")
655            .arg("--format")
656            .arg("json")
657            .arg("--dangerously-skip-permissions");
658        if let Some(m) = model {
659            let (base, variant) = Self::split_model_variant(m);
660            cmd.arg("--model").arg(base);
661            if let Some(v) = variant {
662                // pass variant even if empty (last-token-wins semantics)
663                cmd.arg("--variant").arg(v);
664            }
665        }
666        cmd.arg(prompt);
667        Ok(cmd)
668    }
669}
670
671/// Classify an OpenCode error message.
672fn classify_opencode_message(message: &str) -> AgentError {
673    let lower = message.to_lowercase();
674
675    // Rate limit — delegate to shared helper
676    if let Some(e) = super::patterns::detect_rate_limit(message) {
677        return e;
678    }
679
680    // Context overflow — delegate to shared helper (covers "context overflow", "context length", etc.)
681    if let Some(e) = super::patterns::detect_context_overflow(message) {
682        return e;
683    }
684
685    // Auth errors — delegate to shared helper (includes HTTP 401/403, billing, etc.)
686    if let Some(e) = super::patterns::detect_auth_error(message) {
687        return e;
688    }
689
690    // Permission denied — delegate to shared helper
691    if let Some(e) = super::patterns::detect_permission_denied(message) {
692        return e;
693    }
694
695    // Model not available (opencode-specific extraction pattern)
696    //
697    // Patterns handled:
698    //   "Model not found: anthropic/claude-sonnet-4-6."
699    //   "Model not found: github-copilot/gemini-3.1-pro. Did you mean: gemini-3.1-pro-preview?"
700    //   "model not supported: X"
701    //   "The free model has been deprecated. Transition to qwen/qwen3.6-plus for continued paid access."
702    //   "No endpoints found for qwen/qwen3.6-plus:free."
703    //   "This model is unavailable for free. The paid version is available now - use this slug instead: X"
704    //   "This model is not available in your country."
705    let is_model_unavailable = (lower.contains("model")
706        && (lower.contains("not found")
707            || lower.contains("not supported")
708            || lower.contains("deprecated")
709            || lower.contains("unavailable for free")
710            || lower.contains("not available in your country")
711            || lower.contains("not available in your region")))
712        || lower.contains("no endpoints found");
713
714    if is_model_unavailable {
715        // Try to extract model name from patterns like "Model not found: anthropic/claude-sonnet-4-6."
716        // or "No endpoints found for qwen/qwen3.6-plus:free."
717        let model = if lower.contains("no endpoints found") {
718            // "No endpoints found for X." — extract X after "for "
719            message
720                .split(" for ")
721                .nth(1)
722                .map(|s| s.trim_end_matches('.').to_string())
723                .unwrap_or_default()
724        } else {
725            // Try "Model not found: X" or "model not supported: X" patterns
726            let from_colon = message
727                .split(": ")
728                .nth(1)
729                .map(|s| {
730                    // Strip opencode's "Did you mean: X?" suggestion suffix if present
731                    s.split(". Did you mean")
732                        .next()
733                        .unwrap_or(s)
734                        .trim_end_matches('.')
735                        .to_string()
736                })
737                .filter(|s| !s.is_empty());
738
739            // For deprecated messages like "The free model has been deprecated. Transition to X for..."
740            // extract the model from "Transition to X" when colon-based extraction yields nothing.
741            let from_transition = if lower.contains("deprecated") {
742                message
743                    .split("Transition to ")
744                    .nth(1)
745                    .and_then(|s| s.split(" for ").next())
746                    .map(|s| s.trim_end_matches('.').to_string())
747                    .filter(|s| !s.is_empty())
748            } else {
749                None
750            };
751
752            // For "unavailable for free" messages like "... use this slug instead: X"
753            // extract the suggested replacement slug.
754            let from_slug_suggestion = if lower.contains("unavailable for free") {
755                message
756                    .split("use this slug instead: ")
757                    .nth(1)
758                    .map(|s| s.trim_end_matches('.').trim().to_string())
759                    .filter(|s| !s.is_empty())
760            } else {
761                None
762            };
763
764            // Transition/slug extractions are tied to specific message shapes and take
765            // priority over the generic colon split, which would otherwise grab the
766            // wrong substring (e.g. the "[404] ..." text before the real slug).
767            from_transition
768                .or(from_slug_suggestion)
769                .or(from_colon)
770                .unwrap_or_default()
771        };
772        return AgentError::ModelUnavailable {
773            message: message.to_string(),
774            model,
775        };
776    }
777
778    // OpenCode surfaces opaque upstream provider failures as "Provider returned error".
779    // Treat this as a usage-limit class signal so fallback/error tracking records a
780    // rate-limit event (instead of a generic failure), allowing router health/degraded
781    // checks to react faster to unstable provider/model endpoints.
782    if lower.contains("provider returned error") {
783        return AgentError::RateLimit {
784            message: message.to_string(),
785        };
786    }
787
788    // Transient network/transport errors (e.g. "Upstream idle timeout exceeded")
789    if let Some(e) = super::patterns::detect_network_error(message) {
790        return e;
791    }
792
793    AgentError::AgentFailed {
794        message: message.to_string(),
795    }
796}
797
798/// Discover free opencode models, with 1-hour cache and background refresh.
799///
800/// This is the single source of truth for free model discovery. Called by
801/// the router (pool expansion, model_map), the runner (failover), and
802/// startup priming.
803///
804/// Non-blocking: returns cached data immediately. When the cache is cold
805/// or expired, spawns a background thread to refresh via `opencode models`.
806pub fn discover_free_opencode_models() -> Vec<String> {
807    if skip_live_opencode_discovery() {
808        return Vec::new();
809    }
810    let cache = FREE_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
811
812    let now = chrono::Utc::now().timestamp();
813    // Fast path: return cached data if still fresh (1-hour TTL).
814    {
815        let guard = cache.lock().unwrap_or_else(PoisonError::into_inner);
816        let (ts, models) = &*guard;
817        if *ts != 0 && now.saturating_sub(*ts) < 3600 {
818            return models.clone();
819        }
820    }
821
822    // Cache is cold or expired. Spawn a background task on the current runtime to refresh.
823    // Only one refresh runs at a time.
824    if !FREE_MODELS_REFRESH_IN_PROGRESS.swap(true, Ordering::AcqRel) {
825        let refresh = async {
826            let _guard = scopeguard::guard((), |()| {
827                FREE_MODELS_REFRESH_IN_PROGRESS.store(false, Ordering::Release);
828            });
829            let (models, empty_reason) = run_opencode_models_discovery_async().await;
830            let raw_count = models.len();
831            let discovered = models
832                .into_iter()
833                .filter(|m| m.to_lowercase().contains("free"))
834                .collect::<Vec<_>>();
835            let empty_reason = if discovered.is_empty() && raw_count > 0 {
836                "no_free_models_in_catalog"
837            } else {
838                empty_reason
839            };
840            let cache = FREE_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
841            update_discovered_models_cache(cache, discovered, "free", empty_reason);
842        };
843        match Handle::try_current() {
844            Ok(handle) => {
845                // Use the current tokio runtime's handle to spawn the async discovery task,
846                // avoiding the overhead of a std::thread + new tokio runtime.
847                handle.spawn(refresh);
848            }
849            _ => {
850                // No tokio runtime (e.g. called from a plain unit test). Spawn a thread
851                // with a dedicated runtime — this is the fallback path.
852                thread::spawn(move || {
853                    if let Ok(rt) = Runtime::new() {
854                        rt.block_on(refresh);
855                    }
856                });
857            }
858        }
859    }
860
861    // Return whatever is in cache (may be empty on first call).
862    let guard = cache.lock().unwrap_or_else(PoisonError::into_inner);
863    guard.1.clone()
864}
865
866/// Discover all opencode models, with 1-hour cache and background refresh.
867///
868/// Non-blocking: returns cached data immediately. When the cache is cold
869/// or expired, spawns a background refresh via `opencode models`.
870pub fn discover_opencode_models() -> Vec<String> {
871    if skip_live_opencode_discovery() {
872        return Vec::new();
873    }
874    let cache = ALL_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
875    let now = chrono::Utc::now().timestamp();
876
877    {
878        let guard = cache.lock().unwrap_or_else(PoisonError::into_inner);
879        let (ts, models) = &*guard;
880        if *ts != 0 && now.saturating_sub(*ts) < 3600 {
881            return models.clone();
882        }
883    }
884
885    if !ALL_MODELS_REFRESH_IN_PROGRESS.swap(true, Ordering::AcqRel) {
886        let refresh = async {
887            let _guard = scopeguard::guard((), |()| {
888                ALL_MODELS_REFRESH_IN_PROGRESS.store(false, Ordering::Release);
889            });
890            let (discovered, empty_reason) = run_opencode_models_discovery_async().await;
891            let cache = ALL_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
892            update_discovered_models_cache(cache, discovered, "all", empty_reason);
893        };
894        match Handle::try_current() {
895            Ok(handle) => {
896                handle.spawn(refresh);
897            }
898            _ => {
899                thread::spawn(move || {
900                    if let Ok(rt) = Runtime::new() {
901                        rt.block_on(refresh);
902                    }
903                });
904            }
905        }
906    }
907
908    let guard = cache.lock().unwrap_or_else(PoisonError::into_inner);
909    guard.1.clone()
910}
911
912/// Prime the free-model cache synchronously at startup.
913///
914/// Called from `Router::new()` via `spawn_blocking` so the initial
915/// blocking subprocess doesn't stall the Tokio runtime.
916/// Runs `run_opencode_models_discovery_async()` in a dedicated thread with its
917/// own tokio runtime, avoiding `block_on` restrictions when called from within
918/// an existing runtime (e.g. `#[tokio::test]` or a nested runtime context).
919pub fn prime_free_model_cache() {
920    if skip_live_opencode_discovery() {
921        return;
922    }
923    let discovered_all = thread::spawn(|| match Runtime::new() {
924        Ok(rt) => rt.block_on(run_opencode_models_discovery_async()).0,
925        _ => {
926            vec![]
927        }
928    })
929    .join()
930    .unwrap_or_default();
931    let cache = FREE_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
932    let now = chrono::Utc::now().timestamp();
933    if let Ok(mut guard) = cache.lock() {
934        *guard = (
935            now,
936            discovered_all
937                .iter()
938                .filter(|m| m.to_lowercase().contains("free"))
939                .cloned()
940                .collect(),
941        );
942    }
943    let all_cache = ALL_MODELS_CACHE.get_or_init(|| Mutex::new((0, Vec::new())));
944    if let Ok(mut guard) = all_cache.lock() {
945        *guard = (now, discovered_all);
946    }
947}
948
949/// Async version of `run_opencode_models_discovery` that uses `tokio::time::sleep`
950/// instead of blocking `std::thread::sleep`.
951///
952/// Returns the discovered models plus a reason code describing why the list
953/// is empty (`"ok"` when discovery actually succeeded with a non-empty
954/// result). The reason is threaded into `update_discovered_models_cache` so
955/// the "returned empty" warning says which of the failure branches fired,
956/// without requiring `RUST_LOG=debug` in production.
957async fn run_opencode_models_discovery_async() -> (Vec<String>, &'static str) {
958    run_opencode_models_cli(Duration::from_secs(30)).await
959}
960
961/// Run `opencode models` and reap any process-group leftovers when it returns
962pub(crate) async fn run_opencode_models_cli(timeout: Duration) -> (Vec<String>, &'static str) {
963    run_opencode_models_cli_inner("opencode", timeout).await
964}
965
966fn opencode_program_available(program: &str) -> bool {
967    let path = Path::new(program);
968    if path.is_absolute() || program.contains('/') {
969        path.is_file()
970    } else {
971        cmd_cache::command_exists(program)
972    }
973}
974
975async fn run_opencode_models_cli_inner(
976    program: &str,
977    timeout: Duration,
978) -> (Vec<String>, &'static str) {
979    if !opencode_program_available(program) {
980        tracing::warn!("opencode not in PATH, skipping model discovery");
981        return (vec![], "command_not_found");
982    }
983
984    let mut cmd = Command::new(program);
985    cmd.args(["models"])
986        .stdout(Stdio::piped())
987        .stderr(Stdio::piped())
988        .kill_on_drop(true);
989    #[cfg(unix)]
990    cmd.process_group(0);
991
992    let child = match cmd.spawn() {
993        Ok(c) => c,
994        Err(e) => {
995            tracing::warn!(error = %e, "failed to spawn opencode models");
996            return (vec![], "spawn_failed");
997        }
998    };
999    let pgid = child.id();
1000    let wait = time::timeout(timeout, child.wait_with_output()).await;
1001
1002    #[cfg(unix)]
1003    if let Some(pid) = pgid {
1004        cmd::kill_process_group(pid);
1005    }
1006
1007    match wait {
1008        Ok(Ok(output)) if output.status.success() => {
1009            let models: Vec<String> = String::from_utf8_lossy(&output.stdout)
1010                .lines()
1011                .map(|l| l.trim().to_string())
1012                .filter(|l| !l.is_empty())
1013                .collect();
1014            let reason = if models.is_empty() {
1015                "empty_output"
1016            } else {
1017                "ok"
1018            };
1019            (models, reason)
1020        }
1021        Ok(Ok(output)) => {
1022            let stderr = String::from_utf8_lossy(&output.stderr);
1023            let stderr = stderr.trim();
1024            let stderr_display = if stderr.len() > 500 {
1025                format!("{}...", &stderr[..stderr.floor_char_boundary(500)])
1026            } else {
1027                stderr.to_string()
1028            };
1029            tracing::warn!(
1030                status = ?output.status,
1031                stderr = %stderr_display,
1032                "opencode models command failed"
1033            );
1034            (vec![], "exit_status_failure")
1035        }
1036        Ok(Err(e)) => {
1037            tracing::warn!(error = %e, "failed to wait on opencode models");
1038            (vec![], "wait_failed")
1039        }
1040        Err(_) => {
1041            tracing::warn!(
1042                secs = timeout.as_secs(),
1043                "opencode models timed out, killing process group"
1044            );
1045            (vec![], "timeout")
1046        }
1047    }
1048}
1049
1050/// Build a synthetic `AgentResponse` summarizing an opencode NDJSON event
1051/// stream when no `text` events are present.
1052///
1053/// Opencode runs that produced tool calls but never emitted a text event
1054/// (model exited mid-tool, stop_reason without a final reply, etc.) would
1055/// otherwise be passed to `synthesize_response_from_text` as raw NDJSON.
1056/// That heuristic matches "completed" substrings inside tool state JSON and
1057/// emits the first 500 bytes of NDJSON as the notification summary — what
1058/// the user sees as garbage in Telegram/Discord/Slack.
1059///
1060/// Status is `needs_review` because there is no text confirming completion;
1061/// the agent did work but never reported on it.
1062fn synthesize_response_from_events(events: &[serde_json::Value]) -> AgentResponse {
1063    let mut counts: BTreeMap<String, u32> = BTreeMap::new();
1064    let mut tool_names: Vec<String> = Vec::new();
1065    let mut step_finish_reason: Option<String> = None;
1066
1067    for event in events {
1068        let event_type = event
1069            .get("type")
1070            .and_then(|v| v.as_str())
1071            .unwrap_or("unknown");
1072        *counts.entry(event_type.to_string()).or_insert(0) += 1;
1073
1074        if event_type == "step_finish"
1075            && let Some(reason) = event
1076                .get("part")
1077                .and_then(|p| p.get("reason"))
1078                .and_then(|r| r.as_str())
1079        {
1080            step_finish_reason = Some(reason.to_string());
1081        }
1082
1083        // Capture tool names from common opencode/claude-style shapes.
1084        if event_type == "tool_use"
1085            && let Some(name) = event
1086                .get("name")
1087                .and_then(|v| v.as_str())
1088                .or_else(|| event.get("tool").and_then(|v| v.as_str()))
1089                .or_else(|| {
1090                    event
1091                        .get("part")
1092                        .and_then(|p| p.get("name"))
1093                        .and_then(|v| v.as_str())
1094                })
1095                .or_else(|| {
1096                    event
1097                        .get("tool")
1098                        .and_then(|t| t.get("name"))
1099                        .and_then(|v| v.as_str())
1100                })
1101        {
1102            tool_names.push(name.to_string());
1103        }
1104    }
1105
1106    let total_events = events.len();
1107    let reason = step_finish_reason.as_deref().unwrap_or("unknown");
1108
1109    let tool_summary = if tool_names.is_empty() {
1110        String::new()
1111    } else {
1112        let mut tool_counts: BTreeMap<String, u32> = BTreeMap::new();
1113        for n in &tool_names {
1114            *tool_counts.entry(n.clone()).or_insert(0) += 1;
1115        }
1116        let parts: Vec<String> = tool_counts
1117            .iter()
1118            .map(|(k, v)| {
1119                if *v > 1 {
1120                    format!("{k}×{v}")
1121                } else {
1122                    k.clone()
1123                }
1124            })
1125            .collect();
1126        format!(" (tools: {})", parts.join(", "))
1127    };
1128
1129    let summary = format!(
1130        "opencode emitted {total_events} event(s) with no text output{tool_summary}; \
1131         step_finish reason: {reason}"
1132    );
1133
1134    AgentResponse {
1135        status: "needs_review".to_string(),
1136        summary,
1137        error: Some("agent emitted no text response — only tool/step events".to_string()),
1138        ..Default::default()
1139    }
1140}
1141
1142/// The cost opencode reports in the last `step_finish` event, if any.
1143fn extract_cost(events: &[serde_json::Value]) -> Option<f64> {
1144    events.iter().rev().find_map(|event| {
1145        if event.get("type").and_then(|v| v.as_str()) == Some("step_finish") {
1146            event
1147                .get("part")
1148                .and_then(|p| p.get("cost"))
1149                .and_then(serde_json::Value::as_f64)
1150                .filter(|&c| c > 0.0)
1151        } else {
1152            None
1153        }
1154    })
1155}
1156
1157/// Extract a structured `AgentResult` from OpenCode NDJSON output.
1158///
1159/// Concatenates text from `type:text` events (both `part.text` and direct
1160/// `text` field formats), extracts tokens from the last `step_finish` event,
1161/// and checks for `error` / `step_finish.reason=error` events.
1162///
1163/// Returns `None` only if no parseable NDJSON events are found.
1164pub fn find_opencode_result(ndjson: &str) -> Option<super::AgentResult> {
1165    let events = super::parse_ndjson(ndjson.trim());
1166    if events.is_empty() {
1167        return None;
1168    }
1169
1170    // Check for errors first
1171    let is_error;
1172    let error_text;
1173    if let Some(err) = OpenCodeRunner::detect_error(&events) {
1174        is_error = true;
1175        error_text = Some(err.to_string());
1176    } else {
1177        is_error = false;
1178        error_text = None;
1179    }
1180
1181    // Extract text content
1182    let result_text = if is_error {
1183        error_text.unwrap_or_default()
1184    } else {
1185        extract_ndjson_text(&events).unwrap_or_default()
1186    };
1187
1188    // Extract tokens from step_finish
1189    let (input_tokens, output_tokens) = OpenCodeRunner::extract_tokens(&events);
1190
1191    // The model was cut off for exceeding its output/reasoning token budget,
1192    // not because it produced malformed prose. Distinguish this from a
1193    // generic parse failure so callers don't apply the long
1194    // format-incapable-model cooldown for a token-budget fluke. A reasoning
1195    // model that spends its entire budget on hidden reasoning emits zero
1196    // text and a final step_finish of reason="length" (or opencode's
1197    // "unknown" with all-zero tokens) — same failure mode, must be computed
1198    // before the empty-text early return below or it never gets checked.
1199    let last_step_finish_reason = events
1200        .iter()
1201        .rev()
1202        .find(|event| event.get("type").and_then(|v| v.as_str()) == Some("step_finish"))
1203        .and_then(|event| {
1204            event
1205                .get("part")?
1206                .get("reason")?
1207                .as_str()
1208                .map(str::to_string)
1209        });
1210    let truncated_by_length = match last_step_finish_reason.as_deref() {
1211        Some("length") => true,
1212        Some("unknown") => output_tokens == Some(0),
1213        _ => false,
1214    };
1215
1216    if result_text.is_empty() && !is_error && !truncated_by_length {
1217        return None;
1218    }
1219
1220    let cost_usd = extract_cost(&events);
1221
1222    Some(super::AgentResult {
1223        is_error,
1224        result_text,
1225        input_tokens,
1226        output_tokens,
1227        cost_usd,
1228        duration_ms: None,
1229        truncated_by_length,
1230    })
1231}
1232
1233/// OpenCode `--format json`: a `tool_use` event carries both the call and its finished state
1234fn stream_events(v: &serde_json::Value) -> Vec<StreamEvent> {
1235    let text = || {
1236        v.pointer("/part/text")
1237            .or_else(|| v.get("text"))
1238            .and_then(serde_json::Value::as_str)
1239            .unwrap_or("")
1240            .to_string()
1241    };
1242    match json_str(v, "/type") {
1243        "text" => vec![StreamEvent::Text(text())],
1244        "reasoning" => vec![StreamEvent::Thinking(text())],
1245        "tool_use" => {
1246            let part = &v["part"];
1247            let state = &part["state"];
1248            let id = json_str(part, "/callID").to_string();
1249            let name = json_str(part, "/tool").to_string();
1250            let mut out = vec![StreamEvent::ToolCall {
1251                id: id.clone(),
1252                name: name.clone(),
1253                input: state["input"].clone(),
1254            }];
1255            let result = match json_str(state, "/status") {
1256                "completed" => Some((json_str(state, "/output").to_string(), false)),
1257                "error" => Some((json_error_message(state), true)),
1258                _ => None,
1259            };
1260            if let Some((output, is_error)) = result {
1261                out.push(StreamEvent::ToolResult {
1262                    id,
1263                    name,
1264                    output,
1265                    is_error,
1266                });
1267            }
1268
1269            out
1270        }
1271        "step_finish" if json_str(v, "/part/reason") == "stop" => {
1272            vec![StreamEvent::Done(String::new())]
1273        }
1274        "error" => vec![StreamEvent::Error(json_error_message(v))],
1275        _ => vec![],
1276    }
1277}
1278
1279#[cfg(test)]
1280mod router_text_tests;
1281
1282#[cfg(test)]
1283mod tests;
1284
1285#[cfg(test)]
1286mod error_text_tests;
1287
1288#[cfg(test)]
1289mod stream_tests;