| 1 | use anyhow::{Result, anyhow}; |
| 2 | use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig, SnapshotsConfig}; |
| 3 | use serde_json::{Value, json}; |
| 4 | use std::collections::HashMap; |
| 5 | use std::time::Duration; |
| 6 | use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream, ReadHalf, WriteHalf}; |
| 7 | |
| 8 | pub const STEP: Duration = Duration::from_secs(30); |
| 9 | |
| 10 | pub fn fixture_config() -> Config { |
| 11 | let mut config = Config::default(); |
| 12 | config.provider = Some("acp-fixture".into()); |
| 13 | config.providers = Some(ProvidersConfig { |
| 14 | custom: HashMap::from([( |
| 15 | "acp-fixture".into(), |
| 16 | ProviderConfig { |
| 17 | kind: Some("openai-compatible".into()), |
| 18 | base_url: Some("http://127.0.0.1:18181/v1".into()), |
| 19 | model: Some("fixture-model".into()), |
| 20 | api_key: Some("local-test-key".into()), |
| 21 | ..Default::default() |
| 22 | }, |
| 23 | )]), |
| 24 | ..Default::default() |
| 25 | }); |
| 26 | config.snapshots = Some(SnapshotsConfig { |
| 27 | enabled: false, |
| 28 | ..Default::default() |
| 29 | }); |
| 30 | config.set_feature("mcp", false).unwrap(); |
| 31 | config.set_feature("subagents", false).unwrap(); |
| 32 | config |
| 33 | } |
| 34 | |
| 35 | pub struct Client { |
| 36 | pub lines: tokio::io::Lines<BufReader<ReadHalf<DuplexStream>>>, |
| 37 | pub write: WriteHalf<DuplexStream>, |
| 38 | pub next_id: u64, |
| 39 | pub log: Option<Vec<(bool, Value)>>, |
| 40 | pub step: Duration, |
| 41 | received: usize, |
| 42 | } |
| 43 | |
| 44 | impl Client { |
| 45 | pub fn connect(record: bool) -> (Self, ReadHalf<DuplexStream>, WriteHalf<DuplexStream>) { |
| 46 | let (client, agent) = tokio::io::duplex(1 << 20); |
| 47 | let (agent_read, agent_write) = tokio::io::split(agent); |
| 48 | let (client_read, client_write) = tokio::io::split(client); |
| 49 | ( |
| 50 | Client { |
| 51 | lines: BufReader::new(client_read).lines(), |
| 52 | write: client_write, |
| 53 | next_id: 0, |
| 54 | log: record.then(Vec::new), |
| 55 | step: STEP, |
| 56 | received: 0, |
| 57 | }, |
| 58 | agent_read, |
| 59 | agent_write, |
| 60 | ) |
| 61 | } |
| 62 | pub async fn send(&mut self, message: Value) -> Result<()> { |
| 63 | let mut line = serde_json::to_vec(&message)?; |
| 64 | line.push(b'\n'); |
| 65 | self.write.write_all(&line).await?; |
| 66 | self.write.flush().await?; |
| 67 | if let Some(log) = &mut self.log { |
| 68 | log.push((true, message)); |
| 69 | } |
| 70 | Ok(()) |
| 71 | } |
| 72 | pub async fn recv(&mut self) -> Result<Value> { |
| 73 | let step = self.step; |
| 74 | let line = match tokio::time::timeout(step, self.lines.next_line()).await { |
| 75 | Ok(line) => line?.ok_or_else(|| anyhow!("agent closed the transport"))?, |
| 76 | Err(_) => { |
| 77 | return Err(anyhow!( |
| 78 | "agent produced no frame within {step:?} after {} frames; last traffic (true = sent): {:#?}", |
| 79 | self.received, |
| 80 | self.log |
| 81 | .as_deref() |
| 82 | .map(|log| &log[log.len().saturating_sub(8)..]) |
| 83 | .unwrap_or_default() |
| 84 | )); |
| 85 | } |
| 86 | }; |
| 87 | self.received += 1; |
| 88 | let frame: Value = serde_json::from_str(&line)?; |
| 89 | if let Some(log) = &mut self.log { |
| 90 | log.push((false, frame.clone())); |
| 91 | } |
| 92 | Ok(frame) |
| 93 | } |
| 94 | pub async fn request(&mut self, method: &str, params: Value) -> Result<(Value, Vec<Value>)> { |
| 95 | self.next_id += 1; |
| 96 | let id = self.next_id; |
| 97 | self.send(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params})) |
| 98 | .await?; |
| 99 | self.until_response(id).await |
| 100 | } |
| 101 | pub async fn until_permission(&mut self) -> Result<(Value, Vec<Value>)> { |
| 102 | let mut frames = Vec::new(); |
| 103 | loop { |
| 104 | let frame = self.recv().await?; |
| 105 | if frame["method"] == "session/request_permission" { |
| 106 | return Ok((frame, frames)); |
| 107 | } |
| 108 | frames.push(frame); |
| 109 | } |
| 110 | } |
| 111 | pub async fn until_response(&mut self, id: u64) -> Result<(Value, Vec<Value>)> { |
| 112 | let mut frames = Vec::new(); |
| 113 | loop { |
| 114 | let frame = self.recv().await?; |
| 115 | if frame["id"] == json!(id) && frame.get("method").is_none() { |
| 116 | return Ok((frame, frames)); |
| 117 | } |
| 118 | frames.push(frame); |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | pub fn updates<'a>(frames: &'a [Value], kind: &str) -> Vec<&'a Value> { |
| 124 | frames |
| 125 | .iter() |
| 126 | .filter(|frame| frame.pointer("/params/update/sessionUpdate") == Some(&json!(kind))) |
| 127 | .collect() |
| 128 | } |
| 129 | |
| 130 | pub fn text_of(frames: &[Value], kind: &str) -> String { |
| 131 | updates(frames, kind) |
| 132 | .iter() |
| 133 | .filter_map(|frame| frame.pointer("/params/update/content/text")?.as_str()) |
| 134 | .collect() |
| 135 | } |
| 136 |