Skip to main content

redstart_protocol/
lib.rs

1use serde::{Deserialize, Serialize};
2use serde_json::{Value, json};
3
4/// Metadata about a connected ACP agent server returned by `initialize`.
5#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
6pub struct AgentInfo {
7    pub name: String,
8    pub version: String,
9}
10
11/// Summary of an ACP session returned by `session/list`.
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct SessionSummary {
14    pub id: String,
15    pub title: Option<String>,
16    pub cwd: Option<String>,
17}
18
19/// A single step inside an ACP `plan` session update.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
21pub struct PlanEntry {
22    pub content: String,
23    pub status: String,
24}
25
26/// A slash command advertised via `available_commands_update`.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct SlashCommand {
29    pub name: String,
30    pub description: String,
31}
32
33/// A tool-call update emitted via `session/update`.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct ToolCallUpdate {
36    pub session_id: String,
37    pub tool_call_id: String,
38    pub title: String,
39    pub kind: Option<String>,
40    pub status: String,
41    pub detail: Option<String>,
42}
43
44/// An option presented in an agent `session/request_permission` prompt.
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct PermissionChoice {
47    pub option_id: String,
48    pub name: String,
49    pub kind: Option<String>,
50}
51
52/// A selectable choice within an ACP `configOption` (model, mode, reasoning effort, etc.).
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct ConfigChoice {
55    pub value: String,
56    pub name: String,
57    pub description: Option<String>,
58}
59
60/// An ACP session configuration option (e.g., model, mode, or thinking effort).
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct SessionConfigOption {
63    pub id: String,
64    pub name: String,
65    pub category: Option<String>,
66    pub current_value: String,
67    pub options: Vec<ConfigChoice>,
68}
69
70/// Context window / token usage reported by an ACP agent.
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72pub struct ContextUsage {
73    pub used_tokens: u64,
74    pub max_tokens: u64,
75}
76
77/// An inbound `session/request_permission` request from the ACP agent.
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub struct PermissionPrompt {
80    pub request_id: u64,
81    pub session_id: String,
82    pub title: String,
83    pub options: Vec<PermissionChoice>,
84}
85
86/// Pairing payload encoded in `redstart://connect?...` QR codes and deep links.
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88pub struct PairingUri {
89    pub url: String,
90    pub name: Option<String>,
91    pub cwd: Option<String>,
92    pub token: Option<String>,
93}
94
95impl PairingUri {
96    /// Serializes this pairing config as a `redstart://connect?...` URI.
97    #[must_use]
98    pub fn to_uri_string(&self) -> String {
99        let mut params = vec![format!("url={}", percent_encode(&self.url))];
100        if let Some(name) = &self.name
101            && !name.is_empty()
102        {
103            params.push(format!("name={}", percent_encode(name)));
104        }
105        if let Some(cwd) = &self.cwd
106            && !cwd.is_empty()
107        {
108            params.push(format!("cwd={}", percent_encode(cwd)));
109        }
110        if let Some(token) = &self.token
111            && !token.is_empty()
112        {
113            params.push(format!("token={}", percent_encode(token)));
114        }
115        format!("redstart://connect?{}", params.join("&"))
116    }
117
118    /// Parses a `redstart://connect?...` URI back into a `PairingUri`.
119    #[must_use]
120    pub fn parse_uri(raw: &str) -> Option<Self> {
121        let rest = raw.trim().strip_prefix("redstart://connect?")?;
122        let mut url = None;
123        let mut name = None;
124        let mut cwd = None;
125        let mut token = None;
126
127        for pair in rest.split('&') {
128            let (k, v) = pair.split_once('=')?;
129            let decoded = percent_decode(v)?;
130            match k {
131                "url" => url = Some(decoded),
132                "name" => name = Some(decoded),
133                "cwd" => cwd = Some(decoded),
134                "token" => token = Some(decoded),
135                _ => {}
136            }
137        }
138
139        let url = url.filter(|u| !u.is_empty())?;
140        Some(Self {
141            url,
142            name,
143            cwd,
144            token,
145        })
146    }
147}
148
149fn percent_encode(input: &str) -> String {
150    let mut out = String::with_capacity(input.len());
151    for byte in input.bytes() {
152        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
153            out.push(char::from(byte));
154        } else {
155            use std::fmt::Write;
156            let _ = write!(out, "%{byte:02X}");
157        }
158    }
159    out
160}
161
162fn percent_decode(input: &str) -> Option<String> {
163    let bytes = input.as_bytes();
164    let mut out = Vec::with_capacity(bytes.len());
165    let mut i = 0;
166    while i < bytes.len() {
167        match bytes[i] {
168            b'%' => {
169                if i + 2 >= bytes.len() {
170                    return None;
171                }
172                let hi = hex_val(bytes[i + 1])?;
173                let lo = hex_val(bytes[i + 2])?;
174                out.push((hi << 4) | lo);
175                i += 3;
176            }
177            b'+' => {
178                out.push(b' ');
179                i += 1;
180            }
181            b => {
182                out.push(b);
183                i += 1;
184            }
185        }
186    }
187    String::from_utf8(out).ok()
188}
189
190fn hex_val(b: u8) -> Option<u8> {
191    match b {
192        b'0'..=b'9' => Some(b - b'0'),
193        b'a'..=b'f' => Some(b - b'a' + 10),
194        b'A'..=b'F' => Some(b - b'A' + 10),
195        _ => None,
196    }
197}
198
199/// Builds a JSON-RPC 2.0 `initialize` request for ACP protocol version 1.
200#[must_use]
201pub fn build_initialize_request(id: u64, client_name: &str, client_version: &str) -> String {
202    json!({
203        "jsonrpc": "2.0",
204        "id": id,
205        "method": "initialize",
206        "params": {
207            "protocolVersion": 1,
208            "clientCapabilities": {},
209            "clientInfo": {
210                "name": client_name,
211                "version": client_version
212            }
213        }
214    })
215    .to_string()
216}
217
218/// Builds a JSON-RPC 2.0 `session/new` request.
219#[must_use]
220pub fn build_new_session_request(id: u64, cwd: &str) -> String {
221    json!({
222        "jsonrpc": "2.0",
223        "id": id,
224        "method": "session/new",
225        "params": {
226            "cwd": cwd,
227            "mcpServers": []
228        }
229    })
230    .to_string()
231}
232
233/// Builds a JSON-RPC 2.0 `session/load` request.
234#[must_use]
235pub fn build_load_session_request(id: u64, session_id: &str, cwd: &str) -> String {
236    json!({
237        "jsonrpc": "2.0",
238        "id": id,
239        "method": "session/load",
240        "params": {
241            "sessionId": session_id,
242            "cwd": cwd,
243            "mcpServers": []
244        }
245    })
246    .to_string()
247}
248
249/// Builds a JSON-RPC 2.0 `session/list` request.
250#[must_use]
251pub fn build_list_sessions_request(id: u64) -> String {
252    json!({
253        "jsonrpc": "2.0",
254        "id": id,
255        "method": "session/list",
256        "params": {}
257    })
258    .to_string()
259}
260
261/// Builds a JSON-RPC 2.0 `session/prompt` request with a single text block.
262#[must_use]
263pub fn build_prompt_request(id: u64, session_id: &str, text: &str) -> String {
264    json!({
265        "jsonrpc": "2.0",
266        "id": id,
267        "method": "session/prompt",
268        "params": {
269            "sessionId": session_id,
270            "prompt": [
271                {
272                    "type": "text",
273                    "text": text
274                }
275            ]
276        }
277    })
278    .to_string()
279}
280
281/// Builds a JSON-RPC 2.0 `$/ping` heartbeat request.
282#[must_use]
283pub fn build_ping_request(id: u64) -> String {
284    json!({
285        "jsonrpc": "2.0",
286        "id": id,
287        "method": "$/ping"
288    })
289    .to_string()
290}
291
292/// Builds a JSON-RPC 2.0 `session/set_config_option` request.
293#[must_use]
294pub fn build_set_config_option_request(
295    id: u64,
296    session_id: &str,
297    config_id: &str,
298    value: &str,
299) -> String {
300    json!({
301        "jsonrpc": "2.0",
302        "id": id,
303        "method": "session/set_config_option",
304        "params": {
305            "sessionId": session_id,
306            "configId": config_id,
307            "value": value
308        }
309    })
310    .to_string()
311}
312
313/// Builds a JSON-RPC 2.0 `session/cancel` notification to interrupt an active turn.
314#[must_use]
315pub fn build_cancel_notification(session_id: &str) -> String {
316    json!({
317        "jsonrpc": "2.0",
318        "method": "session/cancel",
319        "params": {
320            "sessionId": session_id
321        }
322    })
323    .to_string()
324}
325
326/// Builds a JSON-RPC 2.0 response to an agent `session/request_permission` request.
327#[must_use]
328pub fn build_permission_response(request_id: u64, option_id: Option<&str>) -> String {
329    let outcome = match option_id {
330        Some(selected) => json!({
331            "outcome": "selected",
332            "optionId": selected
333        }),
334        None => json!({
335            "outcome": "cancelled"
336        }),
337    };
338    json!({
339        "jsonrpc": "2.0",
340        "id": request_id,
341        "result": {
342            "outcome": outcome
343        }
344    })
345    .to_string()
346}
347
348/// If `raw` is a JSON-RPC `$/ping` request with an `id`, returns the serialized pong response.
349#[must_use]
350pub fn try_handle_ping(raw: &str) -> Option<String> {
351    let value: Value = serde_json::from_str(raw).ok()?;
352    let method = value.get("method")?.as_str()?;
353    if method != "$/ping" {
354        return None;
355    }
356    let id = value.get("id")?;
357    Some(
358        json!({
359            "jsonrpc": "2.0",
360            "id": id,
361            "result": {}
362        })
363        .to_string(),
364    )
365}
366
367/// Trims trailing whitespace/newlines and returns `None` for empty payloads.
368#[must_use]
369pub fn normalize_inbound_message(raw: &str) -> Option<String> {
370    let trimmed = raw.trim();
371    if trimmed.is_empty() {
372        return None;
373    }
374    Some(trimmed.to_owned())
375}
376
377/// Extracts `AgentInfo` from an ACP `initialize` JSON-RPC response payload.
378#[must_use]
379pub fn parse_agent_info(response: &Value) -> Option<AgentInfo> {
380    let info = response.get("result")?.get("agentInfo")?;
381    let name = info.get("name")?.as_str()?.to_owned();
382    let version = info
383        .get("version")
384        .and_then(Value::as_str)
385        .unwrap_or("unknown")
386        .to_owned();
387    Some(AgentInfo { name, version })
388}
389
390/// Extracts user prompt text delta from `user_message_chunk` (emitted during `session/load` replay).
391#[must_use]
392pub fn parse_user_text_delta(notification: &Value) -> Option<(String, String)> {
393    if notification.get("method")?.as_str()? != "session/update" {
394        return None;
395    }
396    let params = notification.get("params")?;
397    let session_id = params.get("sessionId")?.as_str()?.to_owned();
398    let update = params.get("update")?;
399    if update.get("sessionUpdate")?.as_str()? != "user_message_chunk" {
400        return None;
401    }
402    let text = update.get("content")?.get("text")?.as_str()?.to_owned();
403    Some((session_id, text))
404}
405
406/// Extracts text delta from a `session/update` ACP notification when present.
407#[must_use]
408pub fn parse_session_text_delta(notification: &Value) -> Option<(String, String)> {
409    if notification.get("method")?.as_str()? != "session/update" {
410        return None;
411    }
412    let params = notification.get("params")?;
413    let session_id = params.get("sessionId")?.as_str()?.to_owned();
414    let update = params.get("update")?;
415    let kind = update.get("sessionUpdate")?.as_str()?;
416    if kind != "agent_message_chunk" {
417        return None;
418    }
419    let text = update.get("content")?.get("text")?.as_str()?.to_owned();
420    Some((session_id, text))
421}
422
423/// Extracts a thought/reasoning text delta from `agent_thought_chunk`.
424#[must_use]
425pub fn parse_session_thought_delta(notification: &Value) -> Option<(String, String)> {
426    if notification.get("method")?.as_str()? != "session/update" {
427        return None;
428    }
429    let params = notification.get("params")?;
430    let session_id = params.get("sessionId")?.as_str()?.to_owned();
431    let update = params.get("update")?;
432    if update.get("sessionUpdate")?.as_str()? != "agent_thought_chunk" {
433        return None;
434    }
435    let text = update.get("content")?.get("text")?.as_str()?.to_owned();
436    Some((session_id, text))
437}
438
439/// Extracts a tool-call event from `tool_call` or `tool_call_update` notifications.
440#[must_use]
441pub fn parse_tool_call_update(notification: &Value) -> Option<ToolCallUpdate> {
442    if notification.get("method")?.as_str()? != "session/update" {
443        return None;
444    }
445    let params = notification.get("params")?;
446    let session_id = params.get("sessionId")?.as_str()?.to_owned();
447    let update = params.get("update")?;
448    let kind_tag = update.get("sessionUpdate")?.as_str()?;
449    if kind_tag != "tool_call" && kind_tag != "tool_call_update" {
450        return None;
451    }
452    let tool_call_id = update.get("toolCallId")?.as_str()?.to_owned();
453    let title = update
454        .get("title")
455        .and_then(Value::as_str)
456        .unwrap_or("Tool call")
457        .to_owned();
458    let kind = update
459        .get("kind")
460        .and_then(Value::as_str)
461        .map(ToOwned::to_owned);
462    let status = update
463        .get("status")
464        .and_then(Value::as_str)
465        .unwrap_or("in_progress")
466        .to_owned();
467    let detail = extract_tool_detail(update);
468    Some(ToolCallUpdate {
469        session_id,
470        tool_call_id,
471        title,
472        kind,
473        status,
474        detail,
475    })
476}
477
478fn extract_tool_detail(update: &Value) -> Option<String> {
479    let mut sections = Vec::new();
480
481    if let Some(content_arr) = update.get("content").and_then(Value::as_array) {
482        for item in content_arr {
483            let item_type = item.get("type").and_then(Value::as_str).unwrap_or("");
484            if item_type == "diff" {
485                let path = item.get("path").and_then(Value::as_str).unwrap_or("file");
486                let old_text = item.get("oldText").and_then(Value::as_str).unwrap_or("");
487                let new_text = item.get("newText").and_then(Value::as_str).unwrap_or("");
488                let mut diff = format!("--- {path}\n+++ {path}\n");
489                for line in old_text.lines().take(20) {
490                    diff.push('-');
491                    diff.push_str(line);
492                    diff.push('\n');
493                }
494                for line in new_text.lines().take(20) {
495                    diff.push('+');
496                    diff.push_str(line);
497                    diff.push('\n');
498                }
499                sections.push(diff);
500            } else if let Some(text) = item
501                .get("content")
502                .and_then(|c| c.get("text"))
503                .and_then(Value::as_str)
504                .or_else(|| item.get("text").and_then(Value::as_str))
505                && !text.trim().is_empty()
506            {
507                sections.push(truncate_detail(text, 1200));
508            }
509        }
510    }
511
512    if sections.is_empty()
513        && let Some(raw_output) = update.get("rawOutput")
514        && !raw_output.is_null()
515    {
516        let text = raw_output
517            .as_str()
518            .map_or_else(|| raw_output.to_string(), ToOwned::to_owned);
519        if !text.trim().is_empty() {
520            sections.push(truncate_detail(&text, 1200));
521        }
522    }
523
524    if sections.is_empty()
525        && let Some(raw_input) = update.get("rawInput")
526        && !raw_input.is_null()
527    {
528        let text = raw_input
529            .as_str()
530            .map_or_else(|| raw_input.to_string(), ToOwned::to_owned);
531        if !text.trim().is_empty() {
532            sections.push(truncate_detail(&text, 600));
533        }
534    }
535
536    if sections.is_empty() {
537        None
538    } else {
539        Some(sections.join("\n"))
540    }
541}
542
543fn truncate_detail(s: &str, max_chars: usize) -> String {
544    if s.chars().count() <= max_chars {
545        s.to_owned()
546    } else {
547        let mut out: String = s.chars().take(max_chars).collect();
548        out.push_str("\n… (truncated)");
549        out
550    }
551}
552
553/// Extracts a `plan` checklist from a `session/update` notification.
554#[must_use]
555pub fn parse_plan_update(notification: &Value) -> Option<(String, Vec<PlanEntry>)> {
556    if notification.get("method")?.as_str()? != "session/update" {
557        return None;
558    }
559    let params = notification.get("params")?;
560    let session_id = params.get("sessionId")?.as_str()?.to_owned();
561    let update = params.get("update")?;
562    if update.get("sessionUpdate")?.as_str()? != "plan" {
563        return None;
564    }
565    let entries = update
566        .get("entries")?
567        .as_array()?
568        .iter()
569        .filter_map(|item| {
570            let content = item.get("content")?.as_str()?.to_owned();
571            let status = item
572                .get("status")
573                .and_then(Value::as_str)
574                .unwrap_or("pending")
575                .to_owned();
576            Some(PlanEntry { content, status })
577        })
578        .collect();
579    Some((session_id, entries))
580}
581
582/// Extracts advertised slash commands from `available_commands_update`.
583#[must_use]
584pub fn parse_available_commands(notification: &Value) -> Option<(String, Vec<SlashCommand>)> {
585    if notification.get("method")?.as_str()? != "session/update" {
586        return None;
587    }
588    let params = notification.get("params")?;
589    let session_id = params.get("sessionId")?.as_str()?.to_owned();
590    let update = params.get("update")?;
591    if update.get("sessionUpdate")?.as_str()? != "available_commands_update" {
592        return None;
593    }
594    let commands = update
595        .get("availableCommands")?
596        .as_array()?
597        .iter()
598        .filter_map(|item| {
599            let name = item.get("name")?.as_str()?.to_owned();
600            let description = item
601                .get("description")
602                .and_then(Value::as_str)
603                .unwrap_or("")
604                .to_owned();
605            Some(SlashCommand { name, description })
606        })
607        .collect();
608    Some((session_id, commands))
609}
610
611/// Parses an inbound `session/request_permission` JSON-RPC request from the agent.
612#[must_use]
613pub fn parse_permission_request(request: &Value) -> Option<PermissionPrompt> {
614    if request.get("method")?.as_str()? != "session/request_permission" {
615        return None;
616    }
617    let request_id = request.get("id")?.as_u64()?;
618    let params = request.get("params")?;
619    let session_id = params.get("sessionId")?.as_str()?.to_owned();
620    let title = params
621        .get("toolCall")
622        .and_then(|tc| tc.get("title"))
623        .and_then(Value::as_str)
624        .unwrap_or("Permission requested")
625        .to_owned();
626    let options = params
627        .get("options")
628        .and_then(Value::as_array)
629        .map_or_default(|arr| {
630            arr.iter()
631                .filter_map(|opt| {
632                    let option_id = opt.get("optionId")?.as_str()?.to_owned();
633                    let name = opt.get("name")?.as_str()?.to_owned();
634                    let kind = opt
635                        .get("kind")
636                        .and_then(Value::as_str)
637                        .map(ToOwned::to_owned);
638                    Some(PermissionChoice {
639                        option_id,
640                        name,
641                        kind,
642                    })
643                })
644                .collect()
645        });
646    Some(PermissionPrompt {
647        request_id,
648        session_id,
649        title,
650        options,
651    })
652}
653
654/// Parses ACP `configOptions` (or legacy `models`/`modes`) from a `session/new`, `session/load`,
655/// `session/set_config_option` response, or `config_option_update` notification.
656#[must_use]
657pub fn parse_config_options(payload: &Value) -> Vec<SessionConfigOption> {
658    let container = payload
659        .get("result")
660        .or_else(|| payload.get("params").and_then(|p| p.get("update")))
661        .unwrap_or(payload);
662
663    if let Some(arr) = container.get("configOptions").and_then(Value::as_array) {
664        let parsed: Vec<SessionConfigOption> = arr
665            .iter()
666            .filter_map(|item| {
667                let id = item.get("id")?.as_str()?.to_owned();
668                let name = item.get("name")?.as_str()?.to_owned();
669                let category = item
670                    .get("category")
671                    .and_then(Value::as_str)
672                    .map(ToOwned::to_owned);
673                let current_value = item.get("currentValue")?.as_str()?.to_owned();
674                let options = item
675                    .get("options")
676                    .and_then(Value::as_array)
677                    .map_or_default(|opts| {
678                        opts.iter()
679                            .filter_map(|opt| {
680                                let value = opt.get("value")?.as_str()?.to_owned();
681                                let opt_name = opt.get("name")?.as_str()?.to_owned();
682                                let description = opt
683                                    .get("description")
684                                    .and_then(Value::as_str)
685                                    .map(ToOwned::to_owned);
686                                Some(ConfigChoice {
687                                    value,
688                                    name: opt_name,
689                                    description,
690                                })
691                            })
692                            .collect()
693                    });
694                Some(SessionConfigOption {
695                    id,
696                    name,
697                    category,
698                    current_value,
699                    options,
700                })
701            })
702            .collect();
703        if !parsed.is_empty() {
704            return parsed;
705        }
706    }
707
708    parse_legacy_models_and_modes(container)
709}
710
711fn parse_legacy_models_and_modes(container: &Value) -> Vec<SessionConfigOption> {
712    let mut synthesized = Vec::new();
713    if let Some(models) = container.get("models")
714        && let Some(current) = models.get("currentModelId").and_then(Value::as_str)
715    {
716        let opts = models
717            .get("availableModels")
718            .and_then(Value::as_array)
719            .map_or_default(|arr| {
720                arr.iter()
721                    .filter_map(|m| {
722                        let value = m.get("modelId")?.as_str()?.to_owned();
723                        let name = m
724                            .get("name")
725                            .and_then(Value::as_str)
726                            .unwrap_or(&value)
727                            .to_owned();
728                        let description = m
729                            .get("description")
730                            .and_then(Value::as_str)
731                            .map(ToOwned::to_owned);
732                        Some(ConfigChoice {
733                            value,
734                            name,
735                            description,
736                        })
737                    })
738                    .collect()
739            });
740        synthesized.push(SessionConfigOption {
741            id: "model".to_owned(),
742            name: "Model".to_owned(),
743            category: Some("model".to_owned()),
744            current_value: current.to_owned(),
745            options: opts,
746        });
747    }
748    if let Some(modes) = container.get("modes")
749        && let Some(current) = modes.get("currentModeId").and_then(Value::as_str)
750    {
751        let opts = modes
752            .get("availableModes")
753            .and_then(Value::as_array)
754            .map_or_default(|arr| {
755                arr.iter()
756                    .filter_map(|m| {
757                        let value = m.get("id")?.as_str()?.to_owned();
758                        let name = m
759                            .get("name")
760                            .and_then(Value::as_str)
761                            .unwrap_or(&value)
762                            .to_owned();
763                        let description = m
764                            .get("description")
765                            .and_then(Value::as_str)
766                            .map(ToOwned::to_owned);
767                        Some(ConfigChoice {
768                            value,
769                            name,
770                            description,
771                        })
772                    })
773                    .collect()
774            });
775        synthesized.push(SessionConfigOption {
776            id: "mode".to_owned(),
777            name: "Mode".to_owned(),
778            category: Some("mode".to_owned()),
779            current_value: current.to_owned(),
780            options: opts,
781        });
782    }
783    synthesized
784}
785
786/// Extracts context token usage from a `usage_update` notification or `session/prompt` result.
787#[must_use]
788pub fn parse_context_usage(payload: &Value) -> Option<ContextUsage> {
789    // 1) `session/update` with `sessionUpdate == "usage_update"` (`used` / `size`)
790    if let Some(update) = payload.get("params").and_then(|p| p.get("update"))
791        && update.get("sessionUpdate").and_then(Value::as_str) == Some("usage_update")
792    {
793        let used = update.get("used").and_then(Value::as_u64)?;
794        let size = update.get("size").and_then(Value::as_u64)?;
795        if size > 0 {
796            return Some(ContextUsage {
797                used_tokens: used,
798                max_tokens: size,
799            });
800        }
801    }
802
803    // 2) `result.usage` on `session/prompt` response (`totalTokens` / `contextWindow` or `inputTokens`)
804    let usage = payload.get("result").and_then(|r| r.get("usage"))?;
805    let used = usage
806        .get("totalTokens")
807        .or_else(|| usage.get("inputTokens"))
808        .and_then(Value::as_u64)?;
809    let max = usage
810        .get("contextWindow")
811        .or_else(|| usage.get("size"))
812        .and_then(Value::as_u64)
813        .unwrap_or(0);
814    Some(ContextUsage {
815        used_tokens: used,
816        max_tokens: max,
817    })
818}
819
820/// Extracts session summaries from an ACP `session/list` JSON-RPC response.
821#[must_use]
822pub fn parse_session_list(response: &Value) -> Vec<SessionSummary> {
823    response
824        .get("result")
825        .and_then(|r| r.get("sessions"))
826        .and_then(Value::as_array)
827        .map_or_default(|arr| {
828            arr.iter()
829                .filter_map(|item| {
830                    let id = item
831                        .get("sessionId")
832                        .or_else(|| item.get("id"))
833                        .and_then(Value::as_str)?
834                        .to_owned();
835                    let title = item
836                        .get("title")
837                        .and_then(Value::as_str)
838                        .map(ToOwned::to_owned);
839                    let cwd = item
840                        .get("cwd")
841                        .and_then(Value::as_str)
842                        .map(ToOwned::to_owned);
843                    Some(SessionSummary { id, title, cwd })
844                })
845                .collect()
846        })
847}
848
849#[cfg(test)]
850mod tests {
851    use super::*;
852
853    #[test]
854    fn handles_ping_requests() {
855        let req = build_ping_request(42);
856        let reply = try_handle_ping(&req).expect("pong reply");
857        let parsed: Value = serde_json::from_str(&reply).expect("valid json");
858        assert_eq!(parsed["id"], 42);
859        assert_eq!(parsed["result"], json!({}));
860    }
861
862    #[test]
863    fn ignores_non_ping_and_notifications() {
864        assert!(try_handle_ping(&build_initialize_request(1, "redstart", "0.1.0")).is_none());
865        assert!(try_handle_ping(r#"{"jsonrpc":"2.0","method":"$/ping"}"#).is_none());
866        assert!(try_handle_ping("bad").is_none());
867    }
868
869    #[test]
870    fn parses_agent_info_and_text_deltas() {
871        let init_resp = json!({
872            "jsonrpc": "2.0",
873            "id": 1,
874            "result": {
875                "agentInfo": { "name": "Antigravity ACP Server", "version": "1.5.22" }
876            }
877        });
878        assert_eq!(
879            parse_agent_info(&init_resp),
880            Some(AgentInfo {
881                name: "Antigravity ACP Server".to_owned(),
882                version: "1.5.22".to_owned()
883            })
884        );
885
886        let notif = json!({
887            "jsonrpc": "2.0",
888            "method": "session/update",
889            "params": {
890                "sessionId": "sess-1",
891                "update": {
892                    "sessionUpdate": "agent_message_chunk",
893                    "content": { "type": "text", "text": "Hello!" }
894                }
895            }
896        });
897        assert_eq!(
898            parse_session_text_delta(&notif),
899            Some(("sess-1".to_owned(), "Hello!".to_owned()))
900        );
901    }
902
903    #[test]
904    fn round_trips_pairing_uri() {
905        let pairing = PairingUri {
906            url: "wss://bazzite.tailc8ba29.ts.net/acp".to_owned(),
907            name: Some("bazzite dev".to_owned()),
908            cwd: Some("/home/brad/source/repos".to_owned()),
909            token: Some("tok+123/abc=".to_owned()),
910        };
911        let encoded = pairing.to_uri_string();
912        assert!(encoded.starts_with("redstart://connect?url="));
913        assert_eq!(PairingUri::parse_uri(&encoded), Some(pairing));
914        assert_eq!(PairingUri::parse_uri("https://example.com"), None);
915    }
916}