Skip to main content

mockql_core/llm_provider/cli/
opencode.rs

1// Copyright 2026 Expedia, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::GraphQLResponse;
16use crate::ProviderError;
17use crate::graphql::mock_response_prompt::MockResponsePrompt;
18use std::process::Stdio;
19use std::time::Duration;
20use tokio::process::Command;
21
22/// Anomaly OpenCode CLI provider.
23#[derive(Debug, Clone)]
24pub struct OpenCodeCliProvider {
25  /// Model identifier forwarded to the CLI in the form of provider/model.
26  pub model: String,
27}
28
29impl OpenCodeCliProvider {
30  const BINARY: &str = "opencode";
31
32  /// Runs the OpenCode CLI, passing the rendered prompt as a positional argument
33  /// to `opencode run` rather than through stdin.
34  pub(crate) async fn run(
35    &self,
36    prompt: &MockResponsePrompt,
37    timeout_duration: Duration,
38  ) -> Result<GraphQLResponse, ProviderError> {
39    let prompt_markdown = prompt.to_markdown()?;
40
41    let mut command = Command::new(Self::BINARY);
42    command.args(self.get_args(prompt_markdown));
43    command.stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
44
45    let child = command
46      .spawn()
47      .map_err(|error| ProviderError::Request(format!("failed to execute OpenCode CLI: {error}")))?;
48
49    let output = super::exec_cli(timeout_duration, child).await?;
50    let stdout = String::from_utf8_lossy(&output.stdout);
51    Self::parse_response(stdout.as_ref())
52  }
53
54  fn get_args(&self, prompt: String) -> Vec<String> {
55    vec!["run".into(), prompt, "--model".into(), self.model.clone()]
56  }
57
58  fn parse_response(output: &str) -> Result<GraphQLResponse, ProviderError> {
59    let trimmed = output.trim();
60    if trimmed.is_empty() {
61      return Err(ProviderError::Request("OpenCode CLI returned empty output".to_string()));
62    }
63    crate::llm_provider::parse_llm_json(trimmed)
64  }
65}
66
67#[cfg(test)]
68mod tests {
69  use super::*;
70
71  #[test]
72  fn builds_run_args() {
73    let provider = OpenCodeCliProvider {
74      model: "github-copilot/gemini-3-flash-preview".into(),
75    };
76    let args = provider.get_args("test prompt".into());
77    assert_eq!(
78      args,
79      vec!["run", "test prompt", "--model", "github-copilot/gemini-3-flash-preview"]
80    );
81  }
82
83  #[test]
84  fn parses_fixture_response() {
85    let response =
86      OpenCodeCliProvider::parse_response(include_str!("mock-response.opencode.json")).expect("fixture should parse");
87
88    let data = response.data.expect("response should contain data");
89    assert_eq!(data["allFilms"]["films"][0]["director"], "George Lucas");
90  }
91
92  #[test]
93  fn rejects_empty_output() {
94    let error = OpenCodeCliProvider::parse_response("").unwrap_err();
95    assert!(error.to_string().contains("empty output"));
96  }
97}