agent_client_protocol/
util.rs1use futures::{
4 future::BoxFuture,
5 stream::{Stream, StreamExt},
6};
7
8mod typed;
9pub use typed::{MatchDispatch, MatchDispatchFrom};
10
11pub(crate) fn redacted_error(code: impl Into<i32>) -> impl std::fmt::Debug {
17 struct RedactedError {
18 code: i32,
19 reason: &'static str,
20 }
21
22 impl std::fmt::Debug for RedactedError {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 f.debug_struct("Error")
25 .field("code", &self.code)
26 .field("reason", &self.reason)
27 .finish()
28 }
29 }
30
31 let code = code.into();
32 let reason = match code {
33 -32700 => "Parse error",
34 -32600 => "Invalid request",
35 -32601 => "Method not found",
36 -32602 => "Invalid params",
37 -32603 => "Internal error",
38 _ => "Protocol or application error",
39 };
40 RedactedError { code, reason }
41}
42
43fn redact_env_and_header_values(value: &mut serde_json::Value) {
51 match value {
52 serde_json::Value::Object(object) => {
53 for (key, field) in object.iter_mut() {
54 if key == "env" || key == "headers" {
55 redact_name_value_pairs(field);
56 }
57 redact_env_and_header_values(field);
58 }
59 }
60 serde_json::Value::Array(values) => {
61 values.iter_mut().for_each(redact_env_and_header_values);
62 }
63 _ => {}
64 }
65}
66
67fn redact_name_value_pairs(field: &mut serde_json::Value) {
69 let redacted = || serde_json::Value::String("[REDACTED]".to_owned());
70 match field {
71 serde_json::Value::Array(entries) => {
72 for entry in entries {
73 if let Some(value) = entry.get_mut("value") {
74 *value = redacted();
75 }
76 }
77 }
78 serde_json::Value::Object(entries) => {
79 for value in entries.values_mut() {
80 *value = redacted();
81 }
82 }
83 _ => {}
84 }
85}
86
87pub(crate) fn redacted_json_line(line: &str) -> impl std::fmt::Display + '_ {
92 struct RedactedJsonLine<'a>(&'a str);
93
94 impl std::fmt::Display for RedactedJsonLine<'_> {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 match serde_json::from_str::<serde_json::Value>(self.0) {
97 Ok(mut value) => {
98 redact_env_and_header_values(&mut value);
99 write!(f, "{value}")
100 }
101 Err(_) => write!(f, "<{} bytes of invalid JSON omitted>", self.0.len()),
102 }
103 }
104 }
105
106 RedactedJsonLine(line)
107}
108
109pub fn json_cast<N, M>(params: N) -> Result<M, crate::Error>
120where
121 N: serde::Serialize,
122 M: serde::de::DeserializeOwned,
123{
124 let json = serde_json::to_value(params).map_err(|e| {
125 crate::Error::parse_error().data(serde_json::json!({
126 "error": e.to_string(),
127 "phase": "serialization"
128 }))
129 })?;
130 let m = serde_json::from_value(json.clone()).map_err(|e| {
131 crate::Error::parse_error().data(serde_json::json!({
132 "error": e.to_string(),
133 "json": json,
134 "phase": "deserialization"
135 }))
136 })?;
137 Ok(m)
138}
139
140pub fn json_cast_params<N, M>(params: N) -> Result<M, crate::Error>
149where
150 N: serde::Serialize,
151 M: serde::de::DeserializeOwned,
152{
153 let json = serde_json::to_value(params).map_err(|e| {
154 crate::Error::internal_error().data(serde_json::json!({
155 "error": e.to_string(),
156 "phase": "serialization"
157 }))
158 })?;
159 let m = serde_json::from_value(json.clone()).map_err(|e| {
160 crate::Error::invalid_params().data(serde_json::json!({
161 "error": e.to_string(),
162 "json": json,
163 "phase": "deserialization"
164 }))
165 })?;
166 Ok(m)
167}
168
169pub(crate) fn internal_error(message: impl ToString) -> crate::Error {
171 crate::Error::internal_error().data(message.to_string())
172}
173
174pub fn initialize_params_for_version(
191 params: &serde_json::Value,
192 selected: crate::schema::ProtocolVersion,
193) -> Result<serde_json::Map<String, serde_json::Value>, crate::Error> {
194 use crate::schema::ProtocolVersion;
195
196 let invalid_version = || {
197 crate::Error::invalid_params()
198 .data("initialize.protocolVersion must be a valid ACP protocol version")
199 };
200 let serde_json::Value::Object(object) = params else {
201 return Err(invalid_version());
202 };
203 let requested: ProtocolVersion = object
204 .get("protocolVersion")
205 .cloned()
206 .and_then(|version| serde_json::from_value(version).ok())
207 .ok_or_else(invalid_version)?;
208
209 let mut rewritten = if requested <= selected {
210 object.clone()
211 } else if selected == ProtocolVersion::V1 {
212 crate::jsonrpc::normalize_v1_initialize_request(params)?
213 } else {
214 #[cfg(feature = "unstable_protocol_v2")]
215 if selected == ProtocolVersion::V2 {
216 return crate::jsonrpc::normalize_newer_v2_initialize_request(object);
217 }
218 return Err(crate::Error::invalid_request().data(format!(
219 "cannot rewrite an initialize request for ACP protocol version {requested} to version {selected}",
220 )));
221 };
222 rewritten.insert(
223 "protocolVersion".into(),
224 serde_json::to_value(selected).map_err(crate::Error::into_internal_error)?,
225 );
226 Ok(rewritten)
227}
228
229pub(crate) fn batch_not_supported() -> crate::Error {
234 crate::Error::invalid_request()
235 .data("JSON-RPC batches are not supported; send each message individually")
236}
237
238pub(crate) fn instrumented_with_connection_name<F>(
239 name: String,
240 task: F,
241) -> tracing::instrument::Instrumented<F> {
242 use tracing::Instrument;
243
244 task.instrument(tracing::info_span!("connection", name = name))
245}
246
247pub(crate) async fn instrument_with_connection_name<R>(
248 name: Option<String>,
249 task: impl Future<Output = R>,
250) -> R {
251 if let Some(name) = name {
252 instrumented_with_connection_name(name.clone(), task).await
253 } else {
254 task.await
255 }
256}
257
258pub fn run_until<T, E>(
264 background: impl Future<Output = Result<(), E>>,
265 foreground: impl Future<Output = Result<T, E>>,
266) -> impl Future<Output = Result<T, E>> {
267 use futures::future::{Either, select};
268 use std::pin::pin;
269
270 Box::pin(async move {
271 match select(pin!(background), pin!(foreground)).await {
272 Either::Left((bg_result, fg_future)) => {
273 bg_result?; fg_future.await
276 }
277 Either::Right((fg_result, _bg_future)) => {
278 fg_result
280 }
281 }
282 })
283}
284
285pub(crate) async fn process_stream_concurrently<T, F>(
294 stream: impl Stream<Item = T>,
295 process_fn: F,
296 process_fn_hack: impl for<'a> Fn(&'a F, T) -> BoxFuture<'a, Result<(), crate::Error>>,
297) -> Result<(), crate::Error>
298where
299 F: AsyncFn(T) -> Result<(), crate::Error>,
300{
301 use std::pin::pin;
302
303 use futures::stream::{FusedStream, FuturesUnordered};
304 use futures_concurrency::future::Race;
305
306 enum Event<T> {
307 NewItem(Option<T>),
308 FutureCompleted(Option<Result<(), crate::Error>>),
309 }
310
311 let mut stream = pin!(stream.fuse());
312 let mut futures: FuturesUnordered<_> = FuturesUnordered::new();
313
314 loop {
315 if futures.is_empty() {
317 match stream.next().await {
318 Some(item) => futures.push(process_fn_hack(&process_fn, item)),
319 None => return Ok(()),
320 }
321 continue;
322 }
323
324 if stream.is_terminated() {
326 while let Some(result) = futures.next().await {
327 result?;
328 }
329 return Ok(());
330 }
331
332 let event = (async { Event::NewItem(stream.next().await) }, async {
334 Event::FutureCompleted(futures.next().await)
335 })
336 .race()
337 .await;
338
339 match event {
340 Event::NewItem(Some(item)) => {
341 futures.push(process_fn_hack(&process_fn, item));
342 }
343 Event::FutureCompleted(Some(result)) => {
344 result?;
345 }
346 Event::NewItem(None) | Event::FutureCompleted(None) => {
347 }
350 }
351 }
352}