From 62d07aa01de35cc06ec461edb0dff6ee77c77c8a Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Sun, 22 Nov 2026 19:00:50 +0100 Subject: [PATCH] refactor(cli-rs): match tools and events by type, not by string (#65595) --- packages/cli-rs/Cargo.lock | 1 + packages/cli-rs/crates/acp/Cargo.toml | 1 + packages/cli-rs/crates/acp/src/catalog.rs | 2 +- packages/cli-rs/crates/acp/src/child.rs | 103 +- packages/cli-rs/crates/acp/src/client.rs | 5 +- packages/cli-rs/crates/acp/src/compaction.rs | 181 ++-- packages/cli-rs/crates/acp/src/connection.rs | 92 +- packages/cli-rs/crates/acp/src/elicitation.rs | 8 +- packages/cli-rs/crates/acp/src/lib.rs | 1 + packages/cli-rs/crates/acp/src/perf.rs | 15 +- packages/cli-rs/crates/acp/src/permission.rs | 233 ++--- packages/cli-rs/crates/acp/src/replay.rs | 130 ++- packages/cli-rs/crates/acp/src/sessions.rs | 6 +- packages/cli-rs/crates/acp/src/tools.rs | 351 ++++--- packages/cli-rs/crates/acp/src/translate.rs | 622 ++++++------ packages/cli-rs/crates/acp/src/turn.rs | 46 +- packages/cli-rs/crates/acp/src/update.rs | 175 ++++ .../cli-rs/crates/acp/tests/acp/permission.rs | 15 +- .../cli-rs/crates/acp/tests/acp/translate.rs | 38 +- packages/cli-rs/crates/api-types/src/de.rs | 15 + packages/cli-rs/crates/api-types/src/kinds.rs | 50 + packages/cli-rs/crates/api-types/src/lib.rs | 2 + packages/cli-rs/crates/api-types/src/tool.rs | 268 +++++ .../crates/api-types/src/type_macros.rs | 32 + packages/cli-rs/crates/api-types/src/types.rs | 947 +++++++++++++----- .../crates/api-types/tests/event_names.rs | 19 +- packages/cli-rs/crates/api/src/events.rs | 10 +- packages/cli-rs/crates/api/src/lib.rs | 2 +- packages/cli-rs/crates/api/src/transport.rs | 4 +- packages/cli-rs/crates/api/tests/all/api.rs | 9 +- packages/cli-rs/crates/api/tests/all/live.rs | 3 +- .../cli-rs/crates/cli/src/commands/machine.rs | 7 +- .../cli-rs/crates/mini/src/prompt/parts.rs | 4 +- packages/cli-rs/crates/mini/src/replay.rs | 301 +++--- packages/cli-rs/crates/mini/src/shell.rs | 61 +- packages/cli-rs/crates/mini/src/subagents.rs | 86 +- packages/cli-rs/crates/mini/src/tools.rs | 251 +++-- packages/cli-rs/crates/plugin/src/canvas.rs | 40 +- packages/cli-rs/crates/plugin/src/interact.rs | 170 ++-- packages/cli-rs/crates/plugin/src/lib.rs | 11 +- .../cli-rs/crates/plugin/src/loader/tests.rs | 6 +- .../cli-rs/crates/plugin/src/pipe/guest.rs | 6 +- .../cli-rs/crates/store/src/connection.rs | 18 +- packages/cli-rs/crates/store/src/inbox.rs | 42 +- packages/cli-rs/crates/store/src/messages.rs | 28 +- packages/cli-rs/crates/store/src/sessions.rs | 8 +- packages/cli-rs/crates/store/src/state.rs | 42 +- .../cli-rs/crates/store/tests/all/data.rs | 6 +- .../crates/tui/src/dialogs/go_upsell.rs | 28 +- .../cli-rs/crates/tui/src/features/events.rs | 56 +- .../tui/src/features/update_notification.rs | 37 +- .../cli-rs/crates/tui/src/plugins/host.rs | 15 +- .../crates/tui/src/plugins/sidebar_mcp.rs | 9 +- .../crates/tui/src/routes/session/grouping.rs | 49 +- .../src/routes/session/messages/background.rs | 4 +- .../tui/src/routes/session/messages/shell.rs | 22 +- .../tui/src/routes/session/tools/dispatch.rs | 81 +- .../tui/src/routes/session/tools/edit.rs | 76 +- .../tui/src/routes/session/tools/generic.rs | 12 +- .../tui/src/routes/session/tools/inline.rs | 12 +- .../tui/src/routes/session/tools/patch.rs | 2 +- .../tui/src/routes/session/tools/question.rs | 12 +- .../tui/src/routes/session/tools/read.rs | 13 +- .../tui/src/routes/session/tools/shell.rs | 5 +- .../tui/src/routes/session/tools/subagent.rs | 12 +- .../tui/src/routes/session/tools/todo.rs | 4 +- .../tui/src/routes/session/tools/write.rs | 4 +- .../cli-rs/crates/tui/tests/all/plugins.rs | 25 +- packages/cli-rs/crates/tui/tests/all/pump.rs | 10 +- packages/cli-rs/crates/tui/tests/all/tabs.rs | 4 +- .../cli-rs/crates/ui/src/motion/scanner.rs | 59 +- packages/cli-rs/crates/ui/src/permission.rs | 117 +-- packages/cli-rs/crates/ui/src/tool_info.rs | 273 ++--- packages/cli-rs/script/gen/api.ts | 1 + packages/cli-rs/script/rust/types.ts | 89 +- 75 files changed, 3205 insertions(+), 2299 deletions(-) create mode 100644 packages/cli-rs/crates/acp/src/update.rs create mode 100644 packages/cli-rs/crates/api-types/src/kinds.rs create mode 100644 packages/cli-rs/crates/api-types/src/tool.rs diff --git a/packages/cli-rs/Cargo.lock b/packages/cli-rs/Cargo.lock index 2cdd03778e0..46dde7c1fd3 100644 --- a/packages/cli-rs/Cargo.lock +++ b/packages/cli-rs/Cargo.lock @@ -717,6 +717,7 @@ dependencies = [ "opencode-util", "percent-encoding", "regex", + "serde", "serde_json", "tokio", "tokio-util", diff --git a/packages/cli-rs/crates/acp/Cargo.toml b/packages/cli-rs/crates/acp/Cargo.toml index ada74678941..82983127d3a 100644 --- a/packages/cli-rs/crates/acp/Cargo.toml +++ b/packages/cli-rs/crates/acp/Cargo.toml @@ -19,6 +19,7 @@ opencode-service.workspace = true opencode-util.workspace = true percent-encoding.workspace = true regex.workspace = true +serde.workspace = true serde_json.workspace = true tokio = { workspace = true, features = ["io-std"] } tokio-util.workspace = true diff --git a/packages/cli-rs/crates/acp/src/catalog.rs b/packages/cli-rs/crates/acp/src/catalog.rs index bd38f56cd3f..604e8797f2d 100644 --- a/packages/cli-rs/crates/acp/src/catalog.rs +++ b/packages/cli-rs/crates/acp/src/catalog.rs @@ -92,7 +92,7 @@ impl Catalogs { } async fn follow(self: &Arc, connected: &watch::Sender) { - let mut stream = subscribe(&self.client); + let mut stream = subscribe::(&self.client); while let Some(event) = stream.next().await { let event = match event { Ok(event) => event, diff --git a/packages/cli-rs/crates/acp/src/child.rs b/packages/cli-rs/crates/acp/src/child.rs index 046eb5d4b90..6f616e0fac2 100644 --- a/packages/cli-rs/crates/acp/src/child.rs +++ b/packages/cli-rs/crates/acp/src/child.rs @@ -1,15 +1,24 @@ -use opencode_util::json_object; -use serde_json::{Value, json}; +use std::borrow::Cow; +use std::sync::Arc; + +use serde::ser::SerializeMap; +use serde::{Serialize, Serializer}; + +use crate::update::{self, Kind}; pub const UPDATE_METHOD: &str = "opencode/session/child_update"; -#[derive(Debug, Clone, PartialEq)] +/// A child session; it serializes as its `opencode/child-session` meta. +#[derive(Debug, Clone, PartialEq, Serialize)] pub struct Session { pub id: String, + #[serde(rename = "parentID")] pub parent_id: String, pub depth: u64, + #[serde(skip_serializing_if = "untitled")] pub title: Option, /// The inbox item of the prompt turn that started the family, if a prompt turn did. + #[serde(skip)] pub turn_id: Option, } @@ -20,54 +29,64 @@ impl Session { } } -/// A child status event: `{ type: "status", status, error? }`. -pub fn status(status: &str, error: Option) -> Value { - json_object! { "type": "status", "status": status, "error"?: error } +fn untitled(title: &Option) -> bool { + title.as_deref().is_none_or(str::is_empty) } -/// A child update event: `{ type: "update", update }`. -pub fn update_event(update: Value) -> Value { - json!({ "type": "update", "update": update }) +/// The `opencode/session/child_update` params. +#[derive(Debug, Clone)] +pub struct Update<'a> { + pub root_session_id: &'a str, + pub child: Arc, + pub event: Event<'a>, } -/// The `opencode/session/child_update` params for `event`. -pub fn update(root_session_id: &str, child: &Session, event: Value) -> Value { - json_object! { - "rootSessionId": root_session_id, - "childSessionId": child.id, - "parentSessionId": child.parent_id, - "depth": child.depth, - "title"?: child.title(), - ..event +#[derive(Debug, Clone)] +#[allow(clippy::large_enum_variant, reason = "built and written at once, never stored")] +pub enum Event<'a> { + Status(&'static str, Option<&'a serde_json::Value>), + Update(update::Update<'a>), +} + +impl Serialize for Update<'_> { + fn serialize(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(None)?; + map.serialize_entry("rootSessionId", self.root_session_id)?; + map.serialize_entry("childSessionId", &self.child.id)?; + map.serialize_entry("parentSessionId", &self.child.parent_id)?; + map.serialize_entry("depth", &self.child.depth)?; + if let Some(title) = self.child.title() { + map.serialize_entry("title", title)?; + } + match &self.event { + Event::Status(status, error) => { + map.serialize_entry("type", "status")?; + map.serialize_entry("status", status)?; + if let Some(error) = error { + map.serialize_entry("error", error)?; + } + } + Event::Update(update) => { + map.serialize_entry("type", "update")?; + map.serialize_entry("update", update)?; + } + } + map.end() } } /// A child's update as the parent session shows it: child metadata, and tool IDs and titles prefixed. -pub fn project(mut update: Value, child: &Session) -> Value { - let Some(object) = update.as_object_mut() else { return update }; - let mut merged = object.get("_meta").and_then(Value::as_object).cloned().unwrap_or_default(); - if let Value::Object(own) = meta(child) { - merged.extend(own); +pub fn project(update: &mut update::Update, child: &Arc) { + update.meta.child = Some(child.clone()); + let (id, title) = match &mut update.kind { + Kind::ToolCall(call) => (&mut call.tool_call_id, Some(&mut call.title)), + Kind::ToolCallUpdate(call) => (&mut call.tool_call_id, call.title.as_mut()), + _ => return, + }; + *id = Cow::Owned(tool_call_id(Some(&**child), id)); + if let Some(title) = title.filter(|title| !title.is_empty()) { + *title = prefix_title(Some(&**child), title); } - object.insert("_meta".to_owned(), Value::Object(merged)); - let kind = object.get("sessionUpdate").and_then(Value::as_str); - if matches!(kind, Some("tool_call" | "tool_call_update")) { - if let Some(id) = object.get("toolCallId").and_then(Value::as_str) { - let id = tool_call_id(Some(child), id); - object.insert("toolCallId".to_owned(), json!(id)); - } - if let Some(title) = object.get("title").and_then(Value::as_str).filter(|title| !title.is_empty()) { - let title = prefix_title(Some(child), title); - object.insert("title".to_owned(), json!(title)); - } - } - update -} - -pub fn meta(child: &Session) -> Value { - let session = - json_object! { "id": child.id, "parentID": child.parent_id, "depth": child.depth, "title"?: child.title() }; - json!({ "opencode/child-session": session }) } pub fn tool_call_id(child: Option<&Session>, id: &str) -> String { diff --git a/packages/cli-rs/crates/acp/src/client.rs b/packages/cli-rs/crates/acp/src/client.rs index 4bf6aa792dd..c3fe21ddc96 100644 --- a/packages/cli-rs/crates/acp/src/client.rs +++ b/packages/cli-rs/crates/acp/src/client.rs @@ -1,6 +1,7 @@ use futures_util::stream::BoxStream; use opencode_api::client::Client; use opencode_api::error::Error; +use serde::de::DeserializeOwned; use serde_json::Value; use crate::error::Failure; @@ -50,8 +51,8 @@ pub fn decode_session_id(value: &str) -> Result { Err(Failure::invalid_request("Invalid session ID", Some("sessionID"))) } -/// One `GET /api/event` stream of raw events. A failure to open the stream is its first item. -pub fn subscribe(client: &Client) -> BoxStream<'static, Result> { +/// One `GET /api/event` stream of events. A failure to open the stream is its first item. +pub fn subscribe(client: &Client) -> BoxStream<'static, Result> { opencode_api::events::raw(client) } diff --git a/packages/cli-rs/crates/acp/src/compaction.rs b/packages/cli-rs/crates/acp/src/compaction.rs index 7d926381f05..0a1fcf4c873 100644 --- a/packages/cli-rs/crates/acp/src/compaction.rs +++ b/packages/cli-rs/crates/acp/src/compaction.rs @@ -1,9 +1,13 @@ +use std::borrow::Cow; use std::collections::HashMap; -use opencode_util::json_object; +use opencode_api::generated::{ + SessionCompactionEnded, SessionCompactionFailed, SessionCompactionStarted, SessionMessageID, +}; +use serde::Serialize; use serde_json::{Value, json}; -const MARKER_META: &str = "opencode/compaction"; +use crate::update::{Content, Kind, Meta, Update}; /// A compaction that started and has not ended. #[derive(Debug, Clone, PartialEq)] @@ -15,16 +19,33 @@ pub struct Started { /// Open compactions by session ID. pub type Tracked = HashMap; -enum Status { +enum Status<'a> { Started, - Completed { summary: String }, - Failed { error: Value }, + Completed { summary: &'a str }, + Failed { error: Cow<'a, Value> }, } -struct Compaction { +/// A `compaction_update`. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CompactionUpdate<'a> { + compaction_id: String, + status: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + summary: Option; 1]>>, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option, +} + +/// The `opencode/compaction` marker that stands in for compaction updates. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Marker<'a> { + status: &'static str, message_id: String, reason: String, - status: Status, + #[serde(skip_serializing_if = "Option::is_none")] + error: Option>, } // Without child updates, a child's standard update would read as the parent's own. @@ -32,133 +53,111 @@ pub fn uses_standard_updates(compaction: bool, child_updates: bool, child: bool) compaction && (!child || child_updates) } -/// Applies a `session.compaction.started`, `ended`, or `failed` event. -pub fn apply(event: &Value, tracked: &Tracked, standard_updates: bool) -> (Tracked, Vec) { - let data = event.get("data").unwrap_or(&Value::Null); - let session_id = text(data, "sessionID"); - let reason = text(data, "reason"); - let mut remaining = tracked.clone(); - if event.get("type").and_then(Value::as_str) == Some("session.compaction.started") { - let started = open(event); - let update = update(&compaction(&started, Status::Started), standard_updates); - remaining.insert(session_id, started); - return (remaining, vec![update]); - } - let current = remaining.remove(&session_id); - if event.get("type").and_then(Value::as_str) == Some("session.compaction.ended") { - let Some(current) = current else { return (remaining, Vec::new()) }; - let completed = - Compaction { reason, ..compaction(¤t, Status::Completed { summary: text(data, "text") }) }; - return (remaining, vec![update(&completed, standard_updates)]); - } +pub fn started<'a>(tracked: &mut Tracked, event: &SessionCompactionStarted, standard_updates: bool) -> Update<'a> { + let data = &event.data; + let started = open(&event.id.0, data.input_id.as_ref(), data.reason.as_str()); + let update = update(&started.message_id, &started.reason, Status::Started, standard_updates); + tracked.insert(data.session_id.0.clone(), started); + update +} + +pub fn ended<'a>( + tracked: &mut Tracked, + event: &'a SessionCompactionEnded, + standard_updates: bool, +) -> Option> { + let current = tracked.remove(event.data.session_id.as_str())?; + let status = Status::Completed { summary: &event.data.text }; + Some(update(¤t.message_id, event.data.reason.as_str(), status, standard_updates)) +} + +pub fn failed<'a>( + tracked: &mut Tracked, + event: &SessionCompactionFailed, + error: &'a Value, + standard_updates: bool, +) -> Vec> { + let data = &event.data; + let current = tracked.remove(data.session_id.as_str()); // Auto compaction can fail without a started event; open it first for standard clients. let opened = current.is_none(); - let started = current.unwrap_or_else(|| open(event)); - let failed = Compaction { - reason, - ..compaction(&started, Status::Failed { error: data.get("error").cloned().unwrap_or(Value::Null) }) - }; + let started = current.unwrap_or_else(|| open(&event.id.0, data.input_id.as_ref(), data.reason.as_str())); let mut updates = Vec::new(); if opened && standard_updates { - updates.push(update(&compaction(&started, Status::Started), standard_updates)); + updates.push(update(&started.message_id, &started.reason, Status::Started, standard_updates)); } - updates.push(update(&failed, standard_updates)); - (remaining, updates) + let status = Status::Failed { error: Cow::Borrowed(error) }; + updates.push(update(&started.message_id, data.reason.as_str(), status, standard_updates)); + updates } /// The update for a `session.compaction.delta`. -pub fn chunk(started: Option<&Started>, text: &str, standard_updates: bool) -> Option { +pub fn chunk<'a>(started: Option<&Started>, text: &'a str, standard_updates: bool) -> Option> { let started = started.filter(|_| standard_updates)?; - Some(json!({ - "sessionUpdate": "compaction_summary_chunk", - "compactionId": started.message_id, - "content": { "type": "text", "text": text }, - })) + let content = Content::Text { text: Cow::Borrowed(text) }; + Some(Kind::CompactionSummaryChunk { compaction_id: started.message_id.clone(), content }.into()) } /// The update that ends a compaction a cancelled turn left open. -pub fn abandon(started: &Started, standard_updates: bool) -> Option { +pub fn abandon(started: &Started, standard_updates: bool) -> Option> { let error = json!({ "type": "aborted", "message": "Compaction cancelled" }); - Some(update(&compaction(started, Status::Failed { error }), standard_updates)) + let status = Status::Failed { error: Cow::Owned(error) }; + Some(update(&started.message_id, &started.reason, status, standard_updates)) } /// The update for a stored compaction message. A running one is skipped: nothing on this connection /// would settle it. -pub fn replay(message: &Value, standard_updates: bool) -> Option { +pub fn replay(message: &Value, standard_updates: bool) -> Option> { let status = match message.get("status").and_then(Value::as_str) { Some("running") => return None, - Some("failed") => Status::Failed { error: message.get("error").cloned().unwrap_or(Value::Null) }, + Some("failed") => Status::Failed { error: Cow::Borrowed(message.get("error").unwrap_or(&Value::Null)) }, _ => Status::Completed { summary: text(message, "summary") }, }; - Some(update( - &Compaction { message_id: text(message, "id"), reason: text(message, "reason"), status }, - standard_updates, - )) -} - -fn compaction(started: &Started, status: Status) -> Compaction { - Compaction { message_id: started.message_id.clone(), reason: started.reason.clone(), status } + Some(update(text(message, "id"), text(message, "reason"), status, standard_updates)) } // Matches core's compaction message ID, so live and replayed compactions line up. -fn open(event: &Value) -> Started { - let data = event.get("data").unwrap_or(&Value::Null); - let message_id = data.get("inputID").and_then(Value::as_str).map(str::to_owned).unwrap_or_else(|| { - let id = text(event, "id"); - match id.strip_prefix("evt_") { - Some(rest) => format!("msg_{rest}"), - None => id, - } - }); - Started { message_id, reason: text(data, "reason") } +fn open(event_id: &str, input_id: Option<&SessionMessageID>, reason: &str) -> Started { + let message_id = input_id.map_or_else( + || event_id.strip_prefix("evt_").map_or_else(|| event_id.to_owned(), |rest| format!("msg_{rest}")), + |id| id.0.clone(), + ); + Started { message_id, reason: reason.to_owned() } } -fn update(compaction: &Compaction, standard_updates: bool) -> Value { +fn update<'a>(message_id: &str, reason: &str, status: Status<'a>, standard_updates: bool) -> Update<'a> { if !standard_updates { - let (status, error) = match &compaction.status { + let (status, error) = match status { Status::Started => ("started", None), Status::Completed { .. } => ("completed", None), Status::Failed { error } => ("failed", Some(error)), }; - let marker = json_object! { - "status": status, - "messageId": compaction.message_id, - "reason": compaction.reason, - "error"?: error, - }; - return json!({ "sessionUpdate": "session_info_update", "_meta": { (MARKER_META): marker } }); + let marker = Marker { status, message_id: message_id.to_owned(), reason: reason.to_owned(), error }; + return Update { kind: Kind::SessionInfoUpdate {}, meta: Meta { compaction: Some(marker), ..Meta::default() } }; } - let id = &compaction.message_id; - match &compaction.status { - Status::Started => { - json!({ "sessionUpdate": "compaction_update", "compactionId": id, "status": "in_progress" }) - } + let (status, summary, error) = match status { + Status::Started => ("in_progress", None, None), Status::Completed { summary } => { - let summary = (!summary.is_empty()).then(|| json!([{ "type": "text", "text": summary }])); - json!({ "sessionUpdate": "compaction_update", "compactionId": id, "status": "completed", "summary": summary }) + ("completed", Some((!summary.is_empty()).then_some([Content::Text { text: Cow::Borrowed(summary) }])), None) } - Status::Failed { error } => { - if matches!(error.get("type").and_then(Value::as_str), Some("aborted" | "compaction.interrupted")) { - return json!({ "sessionUpdate": "compaction_update", "compactionId": id, "status": "cancelled", "summary": null }); - } - json!({ - "sessionUpdate": "compaction_update", "compactionId": id, "status": "failed", - "summary": null, "error": display_error(error), - }) + Status::Failed { error } if matches!(text(&error, "type"), "aborted" | "compaction.interrupted") => { + ("cancelled", Some(None), None) } - } + Status::Failed { error } => ("failed", Some(None), Some(display_error(&error))), + }; + Kind::CompactionUpdate(CompactionUpdate { compaction_id: message_id.to_owned(), status, summary, error }).into() } // Core reports a defect as `compaction.failed` with a multi-line pretty-printed cause. fn display_error(error: &Value) -> String { let message = text(error, "message"); - let defect = error.get("type").and_then(Value::as_str) == Some("compaction.failed") && message.contains('\n'); + let defect = text(error, "type") == "compaction.failed" && message.contains('\n'); if message.is_empty() || defect { return "Compaction failed".to_owned(); } - message + message.to_owned() } -fn text(value: &Value, key: &str) -> String { - value.get(key).and_then(Value::as_str).unwrap_or_default().to_owned() +fn text<'a>(value: &'a Value, key: &str) -> &'a str { + value.get(key).and_then(Value::as_str).unwrap_or_default() } diff --git a/packages/cli-rs/crates/acp/src/connection.rs b/packages/cli-rs/crates/acp/src/connection.rs index 232842afdfb..3ac6a1c6006 100644 --- a/packages/cli-rs/crates/acp/src/connection.rs +++ b/packages/cli-rs/crates/acp/src/connection.rs @@ -9,6 +9,7 @@ use std::time::Duration; use futures_util::future::BoxFuture; use opencode_util::lock; +use serde::Serialize; use serde_json::{Map, Value, json}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use tokio::sync::{mpsc, oneshot}; @@ -24,6 +25,10 @@ const CANCEL_REQUEST: &str = "$/cancel_request"; /// How long a closed input waits for queued messages to be written. const DRAIN_ON_EOF: Duration = Duration::from_millis(500); +/// Line buffers kept for reuse, and the largest kept. +const SPARE_LINES: usize = 8; +const SPARE_LINE_BYTES: usize = 64 * 1024; + /// Why the connection closed. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Closed { @@ -73,7 +78,8 @@ impl Responded { } struct Outgoing { - message: Value, + /// The message as JSON, ending in a newline. + line: Vec, response_to: Option<(String, bool)>, /// Told once the message is written. written: Option>, @@ -95,6 +101,23 @@ struct Inner { /// Messages queued and not yet written. unwritten: AtomicUsize, written: tokio::sync::Notify, + /// Line buffers the writer has emptied. + spare: Mutex>>, +} + +/// A JSON-RPC notification. +#[derive(Serialize)] +struct Notification<'a, P> { + jsonrpc: &'static str, + method: &'a str, + params: P, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct SessionUpdate<'a, U> { + session_id: &'a str, + update: U, } fn key(id: &Value) -> String { @@ -117,6 +140,7 @@ impl Connection { unwritten: AtomicUsize::new(0), written: tokio::sync::Notify::new(), closed: CancellationToken::new(), + spare: Mutex::default(), }), }; (connection, Writer(receiver)) @@ -127,33 +151,39 @@ impl Connection { self.inner.closed.clone() } - fn send(&self, message: Value, response_to: Option<(String, bool)>) -> Result<(), Failure> { - self.queue(Outgoing { message, response_to, written: None }) - } - - fn queue(&self, outgoing: Outgoing) -> Result<(), Failure> { + /// Writes `message` to a line buffer and queues it for the writer. + fn send( + &self, + message: &impl Serialize, + response_to: Option<(String, bool)>, + written: Option>, + ) -> Result<(), Failure> { if self.inner.closed.is_cancelled() { return Err(closed_failure()); } + let mut line = lock(&self.inner.spare).pop().unwrap_or_default(); + serde_json::to_writer(&mut line, message) + .map_err(|error| Failure::Defect { name: Some("Error".to_owned()), detail: error.to_string() })?; + line.push(b'\n'); self.inner.unwritten.fetch_add(1, Ordering::SeqCst); - self.inner.out.send(outgoing).map_err(|_| closed_failure()) + self.inner.out.send(Outgoing { line, response_to, written }).map_err(|_| closed_failure()) } - pub fn notify(&self, method: &str, params: Value) -> Result<(), Failure> { - self.send(json!({ "jsonrpc": "2.0", "method": method, "params": params }), None) + pub fn notify(&self, method: &str, params: &impl Serialize) -> Result<(), Failure> { + self.send(&Notification { jsonrpc: "2.0", method, params }, None, None) } /// `session/update`. - pub fn session_update(&self, session_id: &str, update: Value) -> Result<(), Failure> { - self.notify("session/update", json!({ "sessionId": session_id, "update": update })) + pub fn session_update(&self, session_id: &str, update: &impl Serialize) -> Result<(), Failure> { + self.notify("session/update", &SessionUpdate { session_id, update }) } /// `session/update`, resolving once it is written, as the SDK's `notify` does: a client that stops /// reading holds the caller back instead of letting the queue grow. - pub async fn session_update_written(&self, session_id: &str, update: Value) -> Result<(), Failure> { + pub async fn session_update_written(&self, session_id: &str, update: &impl Serialize) -> Result<(), Failure> { let (written, receiver) = oneshot::channel(); - let message = json!({ "jsonrpc": "2.0", "method": "session/update", "params": { "sessionId": session_id, "update": update } }); - self.queue(Outgoing { message, response_to: None, written: Some(written) })?; + let params = SessionUpdate { session_id, update }; + self.send(&Notification { jsonrpc: "2.0", method: "session/update", params }, None, Some(written))?; tokio::select! { biased; result = receiver => result.map_err(|_| closed_failure()), @@ -169,7 +199,7 @@ impl Connection { let (sender, receiver) = oneshot::channel(); lock(&self.inner.pending).insert(id_key.clone(), sender); let guard = CancelGuard { connection: self.clone(), id, key: id_key, done: false }; - self.send(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }), None)?; + self.send(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }), None, None)?; let mut guard = guard; let result = tokio::select! { result = receiver => result, @@ -194,11 +224,11 @@ impl Connection { }; lock(&self.inner.incoming).remove(&key(id)); // A closed connection drops the response, as the SDK does. - let _ = self.send(message, Some((key(id), ok))); + let _ = self.send(&message, Some((key(id), ok)), None); } fn protocol_error(&self, error: &RpcError) { - let _ = self.send(json!({ "jsonrpc": "2.0", "id": null, "error": error.to_json() }), None); + let _ = self.send(&json!({ "jsonrpc": "2.0", "id": null, "error": error.to_json() }), None, None); } fn close(&self) { @@ -314,7 +344,7 @@ impl Drop for CancelGuard { return; } lock(&self.connection.inner.pending).remove(&self.key); - let _ = self.connection.notify(CANCEL_REQUEST, json!({ "requestId": self.id })); + let _ = self.connection.notify(CANCEL_REQUEST, &json!({ "requestId": self.id })); } } @@ -359,26 +389,29 @@ async fn write_loop( mut output: W, closed: mpsc::UnboundedSender, ) { - let mut line = Vec::new(); - while let Some(outgoing) = writer.0.recv().await { - line.clear(); - let written = async { - serde_json::to_writer(&mut line, &outgoing.message)?; - line.push(b'\n'); + while let Some(Outgoing { mut line, response_to, written }) = writer.0.recv().await { + let result = async { output.write_all(&line).await?; output.flush().await } .await; - if let Err(error) = written { + if let Err(error) = result { let _ = closed.send(Closed::Write(error.to_string())); return; } connection.inner.unwritten.fetch_sub(1, Ordering::SeqCst); connection.inner.written.notify_waiters(); - if let Some(written) = outgoing.written { + if line.capacity() <= SPARE_LINE_BYTES { + let mut spare = lock(&connection.inner.spare); + if spare.len() < SPARE_LINES { + line.clear(); + spare.push(line); + } + } + if let Some(written) = written { let _ = written.send(()); } - if let Some((id, ok)) = outgoing.response_to + if let Some((id, ok)) = response_to && let Some(sender) = lock(&connection.inner.responded).remove(&id) { let _ = sender.send(ok); @@ -528,7 +561,8 @@ mod tests { #[tokio::test] async fn a_written_update_waits_for_the_writer() { let (connection, writer) = Connection::new(); - let update = connection.session_update_written("ses", json!({})); + let empty = json!({}); + let update = connection.session_update_written("ses", &empty); tokio::pin!(update); assert!(tokio::time::timeout(Duration::from_millis(20), &mut update).await.is_err(), "nothing was written"); let (client, agent) = tokio::io::duplex(1 << 16); @@ -537,7 +571,7 @@ mod tests { update.await.unwrap(); drop(client); served.await.unwrap(); - assert!(connection.session_update_written("ses", json!({})).await.is_err(), "closed"); + assert!(connection.session_update_written("ses", &json!({})).await.is_err(), "closed"); } #[tokio::test] diff --git a/packages/cli-rs/crates/acp/src/elicitation.rs b/packages/cli-rs/crates/acp/src/elicitation.rs index 17d2dd2f93c..75127711a6c 100644 --- a/packages/cli-rs/crates/acp/src/elicitation.rs +++ b/packages/cli-rs/crates/acp/src/elicitation.rs @@ -1,5 +1,5 @@ use std::collections::HashSet; -use std::sync::LazyLock; +use std::sync::{Arc, LazyLock}; use opencode_api::client::Client; use opencode_api::generated::{ @@ -34,7 +34,7 @@ pub struct Input { pub form: Value, pub requested_schema: Value, pub client_session_id: String, - pub child: Option, + pub child: Option>, pub tool_call_sent: bool, } @@ -100,13 +100,13 @@ pub async fn ask(input: &Input) -> Result { .tool_call_sent .then(|| input.form.get("metadata")?.get("tool")?.get("id")?.as_str()) .flatten() - .map(|id| child::tool_call_id(input.child.as_ref(), id)); + .map(|id| child::tool_call_id(input.child.as_deref(), id)); let title = input.form.get("title").and_then(Value::as_str).unwrap_or_default(); let params = json_object! { "mode": "form", "sessionId": input.client_session_id, "toolCallId"?: tool_call_id, - "message": child::prefix_title(input.child.as_ref(), title), + "message": child::prefix_title(input.child.as_deref(), title), "requestedSchema": input.requested_schema, }; let response = input.connection.request("elicitation/create", params).await?; diff --git a/packages/cli-rs/crates/acp/src/lib.rs b/packages/cli-rs/crates/acp/src/lib.rs index 90427fd235a..6c9100a553e 100644 --- a/packages/cli-rs/crates/acp/src/lib.rs +++ b/packages/cli-rs/crates/acp/src/lib.rs @@ -23,6 +23,7 @@ pub mod sessions; pub mod tools; pub mod translate; pub mod turn; +pub mod update; use std::ffi::OsString; use std::path::Path; diff --git a/packages/cli-rs/crates/acp/src/perf.rs b/packages/cli-rs/crates/acp/src/perf.rs index 0900799104d..61b8d52f775 100644 --- a/packages/cli-rs/crates/acp/src/perf.rs +++ b/packages/cli-rs/crates/acp/src/perf.rs @@ -61,15 +61,18 @@ fn acp_stream() { runtime.block_on(tokio::task::yield_now()); let probe = Probe::start(); let (terminal, sent) = runtime.block_on(async { - let mut events = - std::pin::pin!(opencode_api::sse::events::(futures_util::stream::iter(chunks), || {})); + let mut events = std::pin::pin!(opencode_api::sse::events::( + futures_util::stream::iter(chunks), + || {} + )); let (mut state, mut terminal, mut sent) = (TurnState::default(), None, 0); while let Some(event) = events.next().await { - let folded = translate::fold(&mut state, &event.unwrap(), &ctx); + let event = event.unwrap(); + let folded = translate::fold(&mut state, &event, &ctx); for output in folded.outputs { - if let Output::SessionUpdate { update, diff } = output { - let update = permission::with_completed_diffs(update, diff.as_ref(), &ctx.cwd).await; - connection.session_update(&ctx.session_id, update).unwrap(); + if let Output::SessionUpdate { mut update, diff } = output { + permission::add_completed_diffs(&mut update, diff.as_ref(), &ctx.cwd).await; + connection.session_update(&ctx.session_id, &update).unwrap(); sent += 1; } } diff --git a/packages/cli-rs/crates/acp/src/permission.rs b/packages/cli-rs/crates/acp/src/permission.rs index dcb839449dc..d15e3bd418f 100644 --- a/packages/cli-rs/crates/acp/src/permission.rs +++ b/packages/cli-rs/crates/acp/src/permission.rs @@ -2,97 +2,73 @@ mod unified; +use std::borrow::Cow; +use std::sync::Arc; + use opencode_api::client::Client; -use opencode_api::generated::{PermissionID, PermissionReply, PermissionReplyInput, SessionID}; +use opencode_api::generated::{PermissionAskedData, PermissionReply, PermissionReplyInput}; +use opencode_api::tool::{ExternalDirectoryInput, SearchInput, ToolInput, ToolKind, WebFetchInput, WebSearchInput}; +use serde::Serialize; use serde_json::{Value, json}; use crate::child; use crate::client::{check, is_declared}; use crate::connection::Connection; use crate::error::Failure; -use crate::tools::{ - DiffSource, absolute_path, canonical_name, file_path, locations, patch, patch_hunks, pending_tool_call, text, -}; +use crate::tools::{DiffSource, absolute_path, locations, patch, patch_hunks, pending_tool_call, tool_kind}; use crate::translate::Tool; +use crate::update::{Diff, Kind, Location, Meta, ToolCall, ToolCallContent, Update}; pub struct Input { pub client: Client, pub connection: Connection, - /// The `permission.asked` event. - pub event: Value, - pub session_id: String, + pub ask: PermissionAskedData, pub client_session_id: String, pub cwd: String, pub tool: Option, - pub child: Option, + pub child: Option>, } -impl Input { - fn data(&self, key: &str) -> Option<&Value> { - self.event.get("data").and_then(|data| data.get(key)) - } -} - -/// A `diff` tool call content item. -#[derive(Debug, Clone, PartialEq)] -struct Diff { - path: String, - old_text: Option, - new_text: String, -} - -impl Diff { - fn new(path: String, old_text: Option, new_text: String) -> Self { - Self { path, old_text, new_text } - } - - fn json(&self) -> Value { - json!({ "type": "diff", "path": self.path, "oldText": self.old_text, "newText": self.new_text }) - } +/// The tool call of a permission request. +#[derive(Serialize)] +struct Asked<'a> { + #[serde(flatten)] + call: ToolCall<'a>, + #[serde(rename = "_meta", skip_serializing_if = "Meta::is_empty")] + meta: Meta<'a>, } /// Asks the client and returns the decision: `once`, `always`, or `reject`. pub async fn ask(input: &Input) -> Result { - let tool_name = input.tool.as_ref().map_or_else( - || input.data("action").and_then(Value::as_str).unwrap_or_default().to_owned(), - |tool| tool.name.clone(), - ); + let ask = &input.ask; + let tool_name = input.tool.as_ref().map_or(ask.action.as_str(), |tool| tool.name.as_str()); let tool_input = input .tool .as_ref() - .map(|tool| tool.input.clone()) - .or_else(|| input.data("metadata").cloned()) - .unwrap_or_else(|| json!({})); - let previews = - permission_previews(&tool_name, &tool_input, input.data("metadata"), &input.cwd).await.unwrap_or_default(); - let request_id = input.data("id").and_then(Value::as_str).unwrap_or_default(); - let tool_call_id = - child::tool_call_id(input.child.as_ref(), input.tool.as_ref().map_or(request_id, |tool| tool.id.as_str())); - let title = permission_title(&tool_name, &tool_input, &previews) + .map_or_else(|| Arc::new(ask.metadata.clone().unwrap_or_default()), |tool| tool.input.clone()); + let fields = ToolInput::map(&tool_input); + let previews = permission_previews(tool_name, fields, ask.metadata.as_ref(), &input.cwd).await.unwrap_or_default(); + let tool_id = input.tool.as_ref().and(ask.source.as_ref()).map_or(ask.id.as_str(), |source| source.id.as_str()); + let tool_call_id = child::tool_call_id(input.child.as_deref(), tool_id); + let title = permission_title(tool_name, fields, &previews) .filter(|title| !title.is_empty()) - .map(|title| child::prefix_title(input.child.as_ref(), &title)) + .map(|title| child::prefix_title(input.child.as_deref(), &title)) .or_else(|| input.child.as_ref().and_then(|child| child.title.clone())); - let mut tool_call = pending_tool_call(&tool_call_id, &tool_name, &tool_input, title.as_deref(), &input.cwd); - if let Some(object) = tool_call.as_object_mut() { - if input.tool.is_none() { - object.shift_remove("name"); - object.shift_remove("rawInput"); - } - object.insert("locations".to_owned(), json!(permission_locations(&tool_name, &tool_input, input, &input.cwd))); - if !previews.is_empty() { - object.insert("content".to_owned(), json!(previews.iter().map(Diff::json).collect::>())); - } - if let Some(child) = &input.child { - object.insert("_meta".to_owned(), child::meta(child)); - } + let mut call = pending_tool_call(Cow::Owned(tool_call_id), tool_name, &tool_input, title.as_deref(), &input.cwd); + if input.tool.is_none() { + call.name = None; + call.raw_input = None; } + call.locations = permission_locations(tool_name, fields, input, &input.cwd); + call.content = previews.into_iter().map(ToolCallContent::Diff).collect(); + let meta = Meta { child: input.child.clone(), ..Meta::default() }; let result = input .connection .request( "session/request_permission", json!({ "sessionId": input.client_session_id, - "toolCall": tool_call, + "toolCall": Asked { call, meta }, "options": [ { "optionId": "once", "kind": "allow_once", "name": "Allow once" }, { "optionId": "always", "kind": "allow_always", "name": "Always allow" }, @@ -115,8 +91,8 @@ pub async fn respond(input: &Input, decision: &str) -> Result<(), Failure> { let result = input .client .permission_reply(&PermissionReplyInput { - session_id: SessionID(input.session_id.clone()), - request_id: PermissionID(input.data("id").and_then(Value::as_str).unwrap_or_default().to_owned()), + session_id: input.ask.session_id.clone(), + request_id: input.ask.id.clone(), decision: match decision { "once" => PermissionReply::Once, "always" => PermissionReply::Always, @@ -131,44 +107,33 @@ pub async fn respond(input: &Input, decision: &str) -> Result<(), Failure> { } } -/// A completed edit's update with full-file diffs added. -pub async fn with_completed_diffs(update: Value, source: Option<&DiffSource>, cwd: &str) -> Value { - let Some(source) = source else { return update }; - if update.get("sessionUpdate").and_then(Value::as_str) != Some("tool_call_update") { - return update; - } +/// Adds full-file diffs to a completed edit's update. +pub async fn add_completed_diffs(update: &mut Update<'_>, source: Option<&DiffSource>, cwd: &str) { + let Some(source) = source else { return }; + let Kind::ToolCallUpdate(call) = &mut update.kind else { return }; // A script lists each change it made, some without a diff, and the same file more than once; rebuilding them from // the file on disk would show its final text for every change. - if canonical_name(&source.tool_name) == "execute" { - return update; + let kind = tool_kind(&source.tool_name); + if kind == ToolKind::Execute { + return; } - let hunks = if canonical_name(&source.tool_name) == "patch" { patch_hunks(&source.input) } else { Vec::new() }; - let mut diffs = Vec::new(); + let hunks = if kind == ToolKind::Patch { patch_hunks(ToolInput::map(&source.input)) } else { Vec::new() }; for file in decode_files(source.metadata.as_ref().and_then(|metadata| metadata.get("files"))) { - diffs.extend(completed_diff(&file, &hunks, cwd).await); + if let Some(diff) = completed_diff(&file, &hunks, cwd).await { + call.content.get_or_insert_default().push(ToolCallContent::Diff(diff)); + } } - if diffs.is_empty() { - return update; - } - let mut update = update; - let mut content = update.get("content").and_then(Value::as_array).cloned().unwrap_or_default(); - content.extend(diffs.iter().map(Diff::json)); - update["content"] = Value::Array(content); - update } async fn completed_diff(file: &FileDiff, hunks: &[patch::Hunk], cwd: &str) -> Option { let path = absolute_path(&file.file, cwd); - let new_text = match file.status.as_str() { - "deleted" => String::new(), - _ => read_text(&path).await?, - }; - if file.status == "added" { - return Some(Diff::new(path, None, new_text)); + let new_text = if file.status == FileStatus::Deleted { String::new() } else { read_text(&path).await? }; + if file.status == FileStatus::Added { + return Some(Diff { path, old_text: None, new_text }); } let recorded = unified::parse_first(&file.patch)?; if let Some(old_text) = unified::apply(&new_text, &unified::reverse(&recorded)) { - return Some(Diff::new(path, Some(old_text), new_text)); + return Some(Diff { path, old_text: Some(old_text), new_text }); } // Core trims indentation from patch-tool diffs, so rebuild those from its hunks and keep them if the ranges agree. let chunks = hunks.iter().find_map(|hunk| match hunk { @@ -192,34 +157,39 @@ async fn completed_diff(file: &FileDiff, hunks: &[patch::Hunk], cwd: &str) -> Op }) .collect(); let rebuilt = patch::derive(from, &reversed, &new_text).ok()?; - (unified::structured_ranges(&rebuilt, &new_text) == unified::ranges(&recorded)) - .then(|| Diff::new(path, Some(rebuilt), new_text)) + (unified::structured_ranges(&rebuilt, &new_text) == unified::ranges(&recorded)).then_some(Diff { + path, + old_text: Some(rebuilt), + new_text, + }) } // Core trims the patch tool's diffs for display, which breaks `applyPatch`, so its previews come from its own hunks. // Any failure drops every preview, as the TS `Effect.forEach` does. -async fn permission_previews(tool_name: &str, input: &Value, metadata: Option<&Value>, cwd: &str) -> Option> { - if canonical_name(tool_name) == "patch" { +async fn permission_previews( + tool_name: &str, + input: ToolInput<'_>, + metadata: Option<&crate::update::Input>, + cwd: &str, +) -> Option> { + if tool_kind(tool_name) == ToolKind::Patch { return patch_previews(input, cwd).await; } let mut previews = Vec::new(); for file in decode_files(metadata.and_then(|metadata| metadata.get("files"))) { let path = absolute_path(&file.file, cwd); - let old_text = match file.status.as_str() { - "added" => None, - _ => Some(read_text(&path).await?), - }; + let old_text = if file.status == FileStatus::Added { None } else { Some(read_text(&path).await?) }; let files = unified::parse(&file.patch)?; // `applyPatch` throws on a patch of more than one file. let [hunks] = files.as_slice() else { return None }; if let Some(new_text) = unified::apply(old_text.as_deref().unwrap_or_default(), hunks) { - previews.push(Diff::new(path, old_text, new_text)); + previews.push(Diff { path, old_text, new_text }); } } Some(previews) } -async fn patch_previews(input: &Value, cwd: &str) -> Option> { +async fn patch_previews(input: ToolInput<'_>, cwd: &str) -> Option> { let mut previews = Vec::new(); for hunk in patch_hunks(input) { let path = absolute_path(hunk.path(), cwd); @@ -227,14 +197,16 @@ async fn patch_previews(input: &Value, cwd: &str) -> Option> { patch::Hunk::Add { contents, .. } => { let new_text = if contents.is_empty() || contents.ends_with('\n') { contents } else { format!("{contents}\n") }; - Diff::new(path, None, new_text) + Diff { path, old_text: None, new_text } + } + patch::Hunk::Delete { .. } => { + Diff { old_text: Some(read_text(&path).await?), path, new_text: String::new() } } - patch::Hunk::Delete { .. } => Diff::new(path.clone(), Some(read_text(&path).await?), String::new()), patch::Hunk::Update { path: from, move_path, chunks } => { let old_text = read_text(&path).await?; let derived = patch::derive(&from, &chunks, &old_text).ok()?; let target = move_path.map_or(path, |target| absolute_path(&target, cwd)); - Diff::new(target, Some(old_text), derived) + Diff { path: target, old_text: Some(old_text), new_text: derived } } }; previews.push(preview); @@ -242,36 +214,33 @@ async fn patch_previews(input: &Value, cwd: &str) -> Option> { Some(previews) } -fn permission_title(tool_name: &str, input: &Value, previews: &[Diff]) -> Option { +fn permission_title(tool_name: &str, fields: ToolInput, previews: &[Diff]) -> Option { if previews.len() > 1 { return Some(format!("{} files", previews.len())); } - match canonical_name(tool_name).as_str() { - "external_directory" => { - text(input, "description").or_else(|| text(input, "command")).or_else(|| text(input, "parentDir")) - } - "webfetch" => text(input, "url"), - "websearch" => text(input, "query"), - "grep" | "glob" => text(input, "pattern"), - "read" | "edit" | "write" | "patch" => { - file_path(input).or_else(|| previews.first().map(|preview| preview.path.clone())) + let dir = ExternalDirectoryInput(fields); + let text = match tool_kind(tool_name) { + ToolKind::ExternalDirectory => dir.description().str().or(dir.command().str()).or(dir.parent_dir().str()), + ToolKind::WebFetch => WebFetchInput(fields).url().str(), + ToolKind::WebSearch => WebSearchInput(fields).query().str(), + ToolKind::Grep | ToolKind::Glob => SearchInput(fields).pattern().str(), + ToolKind::Read | ToolKind::Edit | ToolKind::Write | ToolKind::Patch => { + fields.file_path().or(previews.first().map(|preview| preview.path.as_str())) } _ => None, - } + }; + text.map(str::to_owned) } -fn permission_locations(tool_name: &str, tool_input: &Value, input: &Input, cwd: &str) -> Vec { - let found = locations(tool_name, tool_input, cwd); - let action = input.data("action").and_then(Value::as_str); - if !found.is_empty() || !matches!(action, Some("read" | "edit" | "external_directory")) { +fn permission_locations(tool_name: &str, fields: ToolInput, input: &Input, cwd: &str) -> Vec { + let found = locations(tool_name, fields, cwd); + if !found.is_empty() || !matches!(input.ask.action.as_str(), "read" | "edit" | "external_directory") { return found; } let paths = input - .data("resources") - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter_map(Value::as_str) + .ask + .resources + .iter() .map(|resource| resource.strip_suffix("/*").unwrap_or(resource)) .filter(|path| !path.is_empty() && !path.contains(['*', '?'])) .map(|path| Some(absolute_path(path, cwd))); @@ -286,11 +255,17 @@ async fn read_text(path: &str) -> Option { } /// One `FileDiff.Info`. -#[derive(Debug, Clone, PartialEq)] struct FileDiff { file: String, patch: String, - status: String, + status: FileStatus, +} + +#[derive(PartialEq)] +enum FileStatus { + Added, + Deleted, + Modified, } /// `Schema.decodeUnknownOption(Schema.Array(FileDiff.Info))`, with an invalid value as no files. @@ -302,18 +277,18 @@ fn decode_files(value: Option<&Value>) -> Vec { fn decode_file(value: &Value) -> Option { let count = |key: &str| value.get(key).and_then(Value::as_f64).is_some_and(|number| number >= 0.0 && number.fract() == 0.0); - let status = value.get("status")?.as_str()?; - let more = value.get("more"); - if !count("additions") - || !count("deletions") - || !matches!(status, "added" | "deleted" | "modified") - || more.is_some_and(|more| more != &json!(true)) - { + let status = match value.get("status")?.as_str()? { + "added" => FileStatus::Added, + "deleted" => FileStatus::Deleted, + "modified" => FileStatus::Modified, + _ => return None, + }; + if !count("additions") || !count("deletions") || value.get("more").is_some_and(|more| more != &json!(true)) { return None; } Some(FileDiff { file: value.get("file")?.as_str()?.to_owned(), patch: value.get("patch")?.as_str()?.to_owned(), - status: status.to_owned(), + status, }) } diff --git a/packages/cli-rs/crates/acp/src/replay.rs b/packages/cli-rs/crates/acp/src/replay.rs index 08b5f3027d5..1d52d248d66 100644 --- a/packages/cli-rs/crates/acp/src/replay.rs +++ b/packages/cli-rs/crates/acp/src/replay.rs @@ -1,5 +1,8 @@ //! Replays stored messages on `session/load`. +use std::borrow::Cow; +use std::sync::Arc; + use opencode_api::client::Client; use opencode_api::generated::{MessageListInput, MessageListInputOrder}; use opencode_util::json_object; @@ -13,8 +16,10 @@ use crate::content::{PromptPart, ReplayPart, parts_to_content_chunks}; use crate::error::Failure; use crate::permission; use crate::sessions::Attached; -use crate::tools::{DiffSource, completed_tool_update, error_tool_update, pending_tool_call, running_tool_update}; -use crate::translate::reasoning_message_id; +use crate::tools::{ + DiffSource, Part, completed_tool_update, error_tool_update, pending_tool_call, running_tool_update, +}; +use crate::update::{Id, Input, Kind, Update}; const PAGE_SIZE: i64 = 200; @@ -29,10 +34,9 @@ pub async fn history( loop { let page = list(client, &attached.id, cursor.as_deref()).await?; for message in page.get("data").and_then(Value::as_array).into_iter().flatten() { - for update in updates(message, &attached.cwd, capabilities) { - let source = completed_source(message, &update); - let enriched = permission::with_completed_diffs(update, source.as_ref(), &attached.cwd).await; - connection.session_update_written(&attached.id, enriched).await?; + for (mut update, source) in updates(message, &attached.cwd, capabilities) { + permission::add_completed_diffs(&mut update, source.as_ref(), &attached.cwd).await; + connection.session_update_written(&attached.id, &update).await?; } } cursor = page.get("cursor").and_then(|cursor| cursor.get("next")).and_then(Value::as_str).map(str::to_owned); @@ -55,12 +59,19 @@ async fn list(client: &Client, session_id: &str, cursor: Option<&str>) -> Result client.json::(call).await.map_err(|error| classify(&error)) } -/// The updates that replay one stored message. -pub fn updates(message: &Value, cwd: &str, capabilities: &Capabilities) -> Vec { +/// The updates that replay one stored message, each with what a completed tool call's diffs come from. +pub fn updates<'a>( + message: &'a Value, + cwd: &'a str, + capabilities: &Capabilities, +) -> Vec<(Update<'a>, Option)> { let id = message.get("id").cloned().unwrap_or(Value::Null); + let json = |updates: Vec| updates.into_iter().map(|update| (Kind::Json(update).into(), None)).collect(); match message.get("type").and_then(Value::as_str) { - Some("user") => user_updates(message, &id), - Some("compaction") => compaction::replay(message, capabilities.compaction).into_iter().collect(), + Some("user") => json(user_updates(message, &id)), + Some("compaction") => { + compaction::replay(message, capabilities.compaction).into_iter().map(|update| (update, None)).collect() + } Some("assistant") => assistant_updates(message, &id, cwd), _ => Vec::new(), } @@ -76,13 +87,13 @@ fn user_updates(message: &Value, id: &Value) -> Vec { let mime = text(file, "mime"); let source = file.get("source"); let url = match source.and_then(|source| source.get("type")).and_then(Value::as_str) { - Some("uri") => text(source.unwrap_or(&Value::Null), "uri"), + Some("uri") => text(source.unwrap_or(&Value::Null), "uri").to_owned(), _ => format!("data:{mime};base64,{}", text(file, "data")), }; ReplayPart::Prompt(PromptPart::File { url, filename: file.get("name").and_then(Value::as_str).map(str::to_owned), - mime, + mime: mime.to_owned(), }) }) .collect(); @@ -99,7 +110,7 @@ fn user_updates(message: &Value, id: &Value) -> Vec { updates } -fn assistant_updates(message: &Value, id: &Value, cwd: &str) -> Vec { +fn assistant_updates<'a>(message: &'a Value, id: &Value, cwd: &'a str) -> Vec<(Update<'a>, Option)> { let message_id = id.as_str().unwrap_or_default(); let content = message.get("content").and_then(Value::as_array).map_or(&[][..], Vec::as_slice); // Live reasoning ordinals count only reasoning parts, not the mixed content array. @@ -107,79 +118,56 @@ fn assistant_updates(message: &Value, id: &Value, cwd: &str) -> Vec { content .iter() .flat_map(|part| match part.get("type").and_then(Value::as_str) { - Some("text") => vec![json!({ - "sessionUpdate": "agent_message_chunk", - "messageId": id, - "content": { "type": "text", "text": part.get("text").cloned().unwrap_or(Value::Null) }, - })], + Some("text") => vec![chunk("agent_message_chunk", id.clone(), part)], Some("reasoning") => { let ordinal = reasoning; reasoning += 1; - vec![json!({ - "sessionUpdate": "agent_thought_chunk", - "messageId": reasoning_message_id(message_id, &json!(ordinal)), - "content": { "type": "text", "text": part.get("text").cloned().unwrap_or(Value::Null) }, - })] + vec![chunk("agent_thought_chunk", json!(Id::Reasoning(message_id, ordinal)), part)] } _ => tool_updates(part, cwd), }) .collect() } -fn tool_updates(part: &Value, cwd: &str) -> Vec { - let id = text(part, "id"); - let name = text(part, "name"); +fn chunk<'a>(kind: &str, message_id: Value, part: &Value) -> (Update<'a>, Option) { + let text = part.get("text").cloned().unwrap_or(Value::Null); + let update = json!({ "sessionUpdate": kind, "messageId": message_id, "content": { "type": "text", "text": text } }); + (Kind::Json(update).into(), None) +} + +fn tool_updates<'a>(part: &'a Value, cwd: &'a str) -> Vec<(Update<'a>, Option)> { + let (id, name) = (Cow::Borrowed(text(part, "id")), text(part, "name")); let state = part.get("state").unwrap_or(&Value::Null); let status = state.get("status").and_then(Value::as_str); - let empty = json!({}); - let input = match status { - Some("streaming") => &empty, - _ => state.get("input").unwrap_or(&empty), - }; - let metadata = state.get("metadata").filter(|metadata| !metadata.is_null()); - let content = state.get("content").unwrap_or(&Value::Null); - let call = tagged("tool_call", pending_tool_call(&id, &name, input, None, cwd)); + let input = Arc::new(match status { + Some("streaming") => Input::new(), + _ => open(state.get("input")).unwrap_or_default(), + }); + let metadata = open(state.get("metadata")); + let parts: Vec = + state.get("content").and_then(Value::as_array).into_iter().flatten().map(Part::json).collect(); + let call = Kind::ToolCall(pending_tool_call(id.clone(), name, &input, None, cwd)).into(); let update = match status { - Some("completed") => completed_tool_update(&id, &name, input, content, metadata, cwd), - Some("running") => running_tool_update(&id, &name, input, cwd), - Some("error") => error_tool_update( - &id, - &name, - input, - content, - metadata, - state.get("error").and_then(|error| error.get("message")).and_then(Value::as_str).unwrap_or_default(), - cwd, - ), - _ => return vec![call], + Some("completed") => { + let source = DiffSource { tool_name: name.to_owned(), input: input.clone(), metadata: metadata.clone() }; + let update = completed_tool_update(id, name, &input, &parts, metadata.map(Cow::Owned), cwd); + return vec![(call, None), (Kind::ToolCallUpdate(update).into(), Some(source))]; + } + Some("running") => running_tool_update(id, name, &input, cwd), + Some("error") => { + let error = state.get("error").and_then(|error| error.get("message")).and_then(Value::as_str); + error_tool_update(id, name, &input, &parts, metadata.map(Cow::Owned), error.unwrap_or_default(), cwd) + } + _ => return vec![(call, None)], }; - vec![call, tagged("tool_call_update", update)] + vec![(call, None), (Kind::ToolCallUpdate(update).into(), None)] } -fn tagged(kind: &str, update: Value) -> Value { - json_object! { "sessionUpdate": kind, ..update } +/// An object of open data, as the live events decode it. +fn open(value: Option<&Value>) -> Option { + Some(value?.as_object()?.iter().map(|(key, value)| (key.clone(), value.clone())).collect()) } -fn completed_source(message: &Value, update: &Value) -> Option { - if message.get("type").and_then(Value::as_str) != Some("assistant") - || update.get("sessionUpdate").and_then(Value::as_str) != Some("tool_call_update") - { - return None; - } - let part = message.get("content")?.as_array()?.iter().find(|item| { - item.get("type").and_then(Value::as_str) == Some("tool") && item.get("id") == update.get("toolCallId") - })?; - let state = part.get("state")?; - if state.get("status").and_then(Value::as_str) != Some("completed") { - return None; - } - Some(DiffSource { - tool_name: text(part, "name"), - input: state.get("input").cloned().unwrap_or(Value::Null), - metadata: state.get("metadata").cloned(), - }) -} - -fn text(value: &Value, key: &str) -> String { - value.get(key).and_then(Value::as_str).unwrap_or_default().to_owned() +fn text<'a>(value: &'a Value, key: &str) -> &'a str { + value.get(key).and_then(Value::as_str).unwrap_or_default() } diff --git a/packages/cli-rs/crates/acp/src/sessions.rs b/packages/cli-rs/crates/acp/src/sessions.rs index df7354788ee..074891c6b99 100644 --- a/packages/cli-rs/crates/acp/src/sessions.rs +++ b/packages/cli-rs/crates/acp/src/sessions.rs @@ -95,7 +95,7 @@ impl Sessions { } async fn follow(&self, connected: &watch::Sender) { - let mut stream = subscribe(&self.client); + let mut stream = subscribe::(&self.client); while let Some(event) = stream.next().await { let event = match event { Ok(event) => event, @@ -208,7 +208,7 @@ impl Sessions { fn send_commands(&self, session_id: &str, catalog: &Catalog) -> Result<(), Failure> { self.connection.session_update( session_id, - json!({ + &json!({ "sessionUpdate": "available_commands_update", "availableCommands": available_commands(catalog), }), @@ -222,7 +222,7 @@ impl Sessions { if options != config_options(previous, &selection) { let _ = self.connection.session_update( &attached.id, - json!({ "sessionUpdate": "config_option_update", "configOptions": options }), + &json!({ "sessionUpdate": "config_option_update", "configOptions": options }), ); } if next.commands != previous.commands { diff --git a/packages/cli-rs/crates/acp/src/tools.rs b/packages/cli-rs/crates/acp/src/tools.rs index da1a27a3f3e..0d184eeb617 100644 --- a/packages/cli-rs/crates/acp/src/tools.rs +++ b/packages/cli-rs/crates/acp/src/tools.rs @@ -1,129 +1,166 @@ pub mod patch; -use std::sync::LazyLock; +use std::borrow::Cow; +use std::sync::{Arc, LazyLock}; use indexmap::IndexSet; -use opencode_util::json_object; +use opencode_api::generated::ToolContent; +use opencode_api::tool::{ + ExternalDirectoryInput, Field, PatchInput, ShellInput, ToolInput, ToolKind, read_display_text, +}; use regex::Regex; use serde_json::{Value, json}; use crate::paths; +use crate::update::{Content, Input, Location, RawOutput, ToolCall, ToolCallContent, ToolCallUpdate}; /// What a completed tool call's diffs are rebuilt from (`DiffSource`). #[derive(Debug, Clone, PartialEq)] pub struct DiffSource { pub tool_name: String, - pub input: Value, - pub metadata: Option, + pub input: Arc, + pub metadata: Option, } -pub fn pending_tool_call(tool_call_id: &str, tool_name: &str, input: &Value, title: Option<&str>, cwd: &str) -> Value { - json!({ - "toolCallId": tool_call_id, - "name": tool_name, - "title": tool_title(tool_name, input, title), - "kind": kind(tool_name), - "status": "pending", - "locations": locations(tool_name, input, cwd), - "rawInput": raw_input(tool_name, input, cwd), - }) +/// A part of a tool's result, as ACP reads it. +#[derive(Debug, Clone, Copy)] +pub enum Part<'a> { + Text(&'a str), + Uri(&'a str), + Other, } -pub fn running_tool_update(tool_call_id: &str, tool_name: &str, input: &Value, cwd: &str) -> Value { - json!({ - "toolCallId": tool_call_id, - "status": "in_progress", - "kind": kind(tool_name), - "title": tool_title(tool_name, input, None), - "locations": locations(tool_name, input, cwd), - "rawInput": raw_input(tool_name, input, cwd), - }) -} - -pub fn completed_tool_update( - tool_call_id: &str, - tool_name: &str, - input: &Value, - content: &Value, - metadata: Option<&Value>, - cwd: &str, -) -> Value { - let normalized = tool_content(content); - let first_text = - content.as_array().into_iter().flatten().find(|part| part.get("type").and_then(Value::as_str) == Some("text")); - let read = first_text - .filter(|_| canonical_name(tool_name) == "read") - .and_then(|part| read_display_text(part.get("text").and_then(Value::as_str)?)); - let (images, others): (Vec, Vec) = - normalized.into_iter().partition(|part| part["content"]["type"] == "image"); - let mut parts = match read { - Some(text) => { - vec![json!({ "type": "content", "content": { "type": "text", "text": text } })] +impl<'a> Part<'a> { + pub fn of(content: &'a ToolContent) -> Self { + match content { + ToolContent::Text(text) => Self::Text(&text.text), + ToolContent::File(file) => Self::Uri(&file.uri), + ToolContent::Unknown(value) => Self::json(value), } - None => others, - }; - parts.extend(images); - json!({ - "toolCallId": tool_call_id, - "status": "completed", - "locations": locations(tool_name, input, cwd), - "content": parts, - "rawOutput": raw_output(metadata, None), - }) -} + } -#[allow(clippy::too_many_arguments)] -pub fn error_tool_update( - tool_call_id: &str, - tool_name: &str, - input: &Value, - content: &Value, - metadata: Option<&Value>, - error: &str, - cwd: &str, -) -> Value { - let mut parts = tool_content(content); - parts.push(json!({ "type": "content", "content": { "type": "text", "text": error } })); - json!({ - "toolCallId": tool_call_id, - "status": "failed", - "kind": kind(tool_name), - "title": tool_title(tool_name, input, None), - "locations": locations(tool_name, input, cwd), - "rawInput": raw_input(tool_name, input, cwd), - "content": parts, - "rawOutput": raw_output(metadata, Some(error)), - }) -} - -pub fn canonical_name(tool_name: &str) -> String { - let name = tool_name.to_lowercase(); - match name.as_str() { - "bash" => "shell".to_owned(), - "task" => "subagent".to_owned(), - "apply_patch" => "patch".to_owned(), - _ => name, + pub fn json(value: &'a Value) -> Self { + let text = |key| value.get(key).and_then(Value::as_str); + match (text("type"), text("uri")) { + (Some("text"), _) => Self::Text(text("text").unwrap_or_default()), + (_, Some(uri)) => Self::Uri(uri), + _ => Self::Other, + } } } +pub fn pending_tool_call<'a>( + id: Cow<'a, str>, + tool_name: &'a str, + input: &Arc, + title: Option<&str>, + cwd: &str, +) -> ToolCall<'a> { + ToolCall { + tool_call_id: id, + name: Some(tool_name), + title: tool_title(tool_name, input, title), + kind: kind(tool_name), + status: "pending", + locations: locations(tool_name, ToolInput::map(input), cwd), + raw_input: Some(raw_input(tool_name, input, cwd)), + content: Vec::new(), + } +} + +pub fn running_tool_update<'a>(id: Cow<'a, str>, tool_name: &str, input: &Arc, cwd: &str) -> ToolCallUpdate<'a> { + ToolCallUpdate { + tool_call_id: id, + status: "in_progress", + kind: Some(kind(tool_name)), + title: Some(tool_title(tool_name, input, None)), + locations: locations(tool_name, ToolInput::map(input), cwd), + raw_input: Some(raw_input(tool_name, input, cwd)), + content: None, + raw_output: None, + } +} + +pub fn completed_tool_update<'a>( + id: Cow<'a, str>, + tool_name: &str, + input: &Input, + parts: &[Part<'a>], + metadata: Option>, + cwd: &str, +) -> ToolCallUpdate<'a> { + let first_text = parts.iter().find_map(|part| match part { + Part::Text(text) => Some(*text), + _ => None, + }); + let read = first_text.filter(|_| tool_kind(tool_name) == ToolKind::Read).and_then(read_display_text); + let (images, others): (Vec<_>, Vec<_>) = tool_content(parts) + .into_iter() + .partition(|part| matches!(part, ToolCallContent::Content { content: Content::Image { .. } })); + let mut content = match read { + Some(text) => vec![ToolCallContent::text(Cow::Owned(text))], + None => others, + }; + content.extend(images); + ToolCallUpdate { + tool_call_id: id, + status: "completed", + kind: None, + title: None, + locations: locations(tool_name, ToolInput::map(input), cwd), + raw_input: None, + content: Some(content), + raw_output: Some(RawOutput { metadata, error: None }), + } +} + +pub fn error_tool_update<'a>( + id: Cow<'a, str>, + tool_name: &str, + input: &Arc, + parts: &[Part<'a>], + metadata: Option>, + error: &'a str, + cwd: &str, +) -> ToolCallUpdate<'a> { + let mut content = tool_content(parts); + content.push(ToolCallContent::text(Cow::Borrowed(error))); + let raw_output = Some(RawOutput { metadata, error: Some(error) }); + ToolCallUpdate { + status: "failed", + content: Some(content), + raw_output, + ..running_tool_update(id, tool_name, input, cwd) + } +} + +/// What a tool is: ACP reads its name in any case. +pub fn tool_kind(tool_name: &str) -> ToolKind { + ToolKind::of(&tool_name.to_lowercase()) +} + fn kind(tool_name: &str) -> &'static str { - match canonical_name(tool_name).as_str() { - "shell" => "execute", - "webfetch" => "fetch", - "edit" | "patch" | "write" => "edit", - "grep" | "glob" | "context" | "context7_resolve_library_id" | "context7_get_library_docs" => "search", - "read" => "read", - "subagent" => "think", + match tool_kind(tool_name) { + ToolKind::Shell => "execute", + ToolKind::WebFetch => "fetch", + ToolKind::Edit | ToolKind::Patch | ToolKind::Write => "edit", + ToolKind::Grep | ToolKind::Glob | ToolKind::Context => "search", + ToolKind::Read => "read", + ToolKind::Subagent => "think", _ => "other", } } /// `toLocations`: the files and directories a tool call touches, absolute against `cwd`. -pub fn locations(tool_name: &str, input: &Value, cwd: &str) -> Vec { - let values: Vec> = match canonical_name(tool_name).as_str() { - "shell" => vec![Some(text(input, "workdir").or_else(|| text(input, "cwd")).unwrap_or_else(|| cwd.to_owned()))], - "read" | "edit" | "write" => vec![file_path(input)], - "patch" => patch_hunks(input) +pub fn locations(tool_name: &str, fields: ToolInput, cwd: &str) -> Vec { + let owned = |text: Option<&str>| text.map(str::to_owned); + let values: Vec> = match tool_kind(tool_name) { + ToolKind::Shell => { + let shell = ShellInput(fields); + vec![Some(shell.workdir().str().or(shell.cwd().str()).unwrap_or(cwd).to_owned())] + } + ToolKind::Read | ToolKind::Edit | ToolKind::Write => vec![owned(fields.file_path())], + ToolKind::Patch => patch_hunks(fields) .into_iter() .flat_map(|hunk| { let target = match &hunk { @@ -133,17 +170,15 @@ pub fn locations(tool_name: &str, input: &Value, cwd: &str) -> Vec { [Some(hunk.path().to_owned()), target] }) .collect(), - "external_directory" => vec![text(input, "filepath")], - "grep" | "glob" | "context" | "context7_resolve_library_id" | "context7_get_library_docs" => { - vec![text(input, "path")] - } + ToolKind::ExternalDirectory => vec![owned(ExternalDirectoryInput(fields).filepath().str())], + ToolKind::Grep | ToolKind::Glob | ToolKind::Context => vec![owned(fields.path().str())], _ => Vec::new(), }; location_from(cwd, values) } /// Unique, non-empty paths as ACP locations, in order. -pub fn location_from(cwd: &str, values: impl IntoIterator>) -> Vec { +pub fn location_from(cwd: &str, values: impl IntoIterator>) -> Vec { values .into_iter() .flatten() @@ -151,18 +186,13 @@ pub fn location_from(cwd: &str, values: impl IntoIterator> .map(|value| absolute_path(&value, cwd)) .collect::>() .into_iter() - .map(|path| json!({ "path": path })) + .map(|path| Location { path }) .collect() } -// Sessions migrated from V1 keep their original `filePath` tool inputs. -pub fn file_path(input: &Value) -> Option { - text(input, "path").or_else(|| text(input, "filePath")) -} - /// The hunks of a patch tool's `patchText`, empty when it is missing or does not parse. -pub fn patch_hunks(input: &Value) -> Vec { - text(input, "patchText").filter(|text| !text.is_empty()).and_then(|text| patch::parse(&text)).unwrap_or_default() +pub fn patch_hunks(input: ToolInput) -> Vec { + PatchInput(input).patch_text().non_empty().and_then(patch::parse).unwrap_or_default() } /// `absolutePath`: absolute paths stay as they are; relative ones resolve against `cwd`. @@ -173,84 +203,51 @@ pub fn absolute_path(path: &str, cwd: &str) -> String { paths::resolve_from(cwd, path) } -fn is_shell(tool_name: &str) -> bool { - canonical_name(tool_name) == "shell" -} - -pub fn text(value: &Value, key: &str) -> Option { - value.get(key).and_then(Value::as_str).map(str::to_owned) -} - -fn tool_title(tool_name: &str, input: &Value, fallback: Option<&str>) -> String { - if is_shell(tool_name) { - return text(input, "command") - .or_else(|| text(input, "cmd")) - .or_else(|| fallback.map(str::to_owned)) - .unwrap_or_else(|| tool_name.to_owned()); +fn tool_title(tool_name: &str, input: &Input, fallback: Option<&str>) -> String { + if tool_kind(tool_name) == ToolKind::Shell { + let shell = ShellInput(ToolInput::map(input)); + return shell.command().str().or(shell.cmd().str()).or(fallback).unwrap_or(tool_name).to_owned(); } fallback.filter(|title| !title.is_empty()).unwrap_or(tool_name).to_owned() } -fn raw_input(tool_name: &str, input: &Value, cwd: &str) -> Value { - let truthy = - |key: &str| input.get(key).is_some_and(|value| !value.is_null() && value != "" && value != &json!(false)); - if !is_shell(tool_name) || truthy("cwd") || truthy("workdir") { +fn raw_input(tool_name: &str, input: &Arc, cwd: &str) -> Arc { + let shell = ShellInput(ToolInput::map(input)); + let set = + |field: Field| field.value().is_some_and(|value| !value.is_null() && value != "" && value != &json!(false)); + if tool_kind(tool_name) != ToolKind::Shell || set(shell.cwd()) || set(shell.workdir()) { return input.clone(); } - json_object! { ..input.clone(), "cwd": cwd } -} - -fn raw_output(metadata: Option<&Value>, error: Option<&str>) -> Value { - json_object! { "metadata"?: metadata, "error"?: error } + let mut input = Input::clone(input); + input.insert("cwd".to_owned(), cwd.into()); + Arc::new(input) } static DATA_IMAGE: LazyLock = LazyLock::new(|| Regex::new(r"^data:([^;,]+)(?:;[^,]*)*;base64,(.*)$").expect("data URL pattern")); /// Text parts as text content, and `data:image/...;base64` file parts as images. -fn tool_content(content: &Value) -> Vec { - content - .as_array() - .into_iter() - .flatten() +fn tool_content<'a>(parts: &[Part<'a>]) -> Vec> { + parts + .iter() .filter_map(|part| { - if part.get("type").and_then(Value::as_str) == Some("text") { - return Some(json!({ - "type": "content", - "content": { "type": "text", "text": part.get("text").cloned().unwrap_or(Value::Null) }, - })); - } - let captures = DATA_IMAGE.captures(part.get("uri")?.as_str()?)?; + let uri = match *part { + Part::Text(text) => return Some(ToolCallContent::text(Cow::Borrowed(text))), + Part::Uri(uri) => uri, + Part::Other => return None, + }; + let captures = DATA_IMAGE.captures(uri)?; let mime = captures.get(1)?.as_str(); if !mime.starts_with("image/") { return None; } - Some(json!({ - "type": "content", - "content": { "type": "image", "mimeType": mime, "data": captures.get(2)?.as_str() }, - })) + Some(ToolCallContent::Content { + content: Content::Image { mime_type: mime, data: captures.get(2)?.as_str() }, + }) }) .collect() } -/// Extracts the human-readable text from a read tool's JSON page. -fn read_display_text(text: &str) -> Option { - if !text.starts_with('{') { - return None; - } - let envelope = serde_json::from_str::(text).ok().filter(Value::is_object).unwrap_or_else(|| json!({})); - if let Some(content) = envelope.get("content").and_then(Value::as_str) - && (envelope.get("type").and_then(Value::as_str) == Some("text-page") - || envelope.get("encoding").and_then(Value::as_str) == Some("utf8")) - { - return Some(content.to_owned()); - } - let entries = envelope.get("entries")?.as_array()?; - let lines: Vec<&str> = - entries.iter().filter_map(|entry| entry.as_str().or_else(|| entry.get("path")?.as_str())).collect(); - Some(lines.join("\n")) -} - #[cfg(test)] mod tests { use super::*; @@ -262,7 +259,10 @@ mod tests { { "type": "text", "text": "{\"type\":\"text-page\",\"content\":\"hello\"}" }, { "type": "file", "uri": "data:text/plain;base64,AAAA" }, ]); - let update = completed_tool_update("c", "read", &json!({ "path": "a.ts" }), &content, None, "/w"); + let parts: Vec = content.as_array().unwrap().iter().map(Part::json).collect(); + let input = serde_json::from_value(json!({ "path": "a.ts" })).unwrap(); + let update = completed_tool_update("c".into(), "read", &input, &parts, None, "/w"); + let update = serde_json::to_value(update).unwrap(); assert_eq!( update["content"], json!([ @@ -271,18 +271,17 @@ mod tests { ]) ); assert_eq!(update["locations"], json!([{ "path": paths::resolve_from("/w", "a.ts") }])); - assert_eq!(read_display_text("{\"entries\":[\"a\",{\"path\":\"b\"},3]}").as_deref(), Some("a\nb")); - assert_eq!(read_display_text("plain"), None); } #[test] fn locates_tool_paths() { // `path.resolve("/w", "a.ts")`: `/w/a.ts`, and on Windows `D:\w\a.ts` on the working directory's drive. - let at = |path: &str| json!({ "path": paths::resolve_from("/w", path) }); + let at = |path: &str| Location { path: paths::resolve_from("/w", path) }; + let locate = |name, input| locations(name, ToolInput::json(&input), "/w"); let patch = "*** Begin Patch\n*** Update File: a.ts\n*** Move to: b.ts\n@@\n-x\n+y\n*** Add File: a.ts\n+z\n*** End Patch"; - assert_eq!(locations("apply_patch", &json!({ "patchText": patch }), "/w"), vec![at("a.ts"), at("b.ts")]); - assert_eq!(locations("bash", &json!({ "cwd": "sub" }), "/w"), vec![at("sub")]); - assert_eq!(locations("glob", &json!({ "path": "/abs/../x" }), "/w"), vec![json!({ "path": "/abs/../x" })]); - assert!(locations("webfetch", &json!({ "url": "x" }), "/w").is_empty()); + assert_eq!(locate("apply_patch", json!({ "patchText": patch })), vec![at("a.ts"), at("b.ts")]); + assert_eq!(locate("bash", json!({ "cwd": "sub" })), vec![at("sub")]); + assert_eq!(locate("glob", json!({ "path": "/abs/../x" })), vec![Location { path: "/abs/../x".to_owned() }]); + assert!(locate("webfetch", json!({ "url": "x" })).is_empty()); } } diff --git a/packages/cli-rs/crates/acp/src/translate.rs b/packages/cli-rs/crates/acp/src/translate.rs index 6ab7492a94d..96dc549ad4f 100644 --- a/packages/cli-rs/crates/acp/src/translate.rs +++ b/packages/cli-rs/crates/acp/src/translate.rs @@ -1,15 +1,26 @@ //! Translates server events into ACP updates and the final prompt response. +use std::borrow::Cow; use std::collections::{HashMap, HashSet}; +use std::sync::Arc; -use indexmap::IndexMap; +use indexmap::{Equivalent, IndexMap}; +use opencode_api::de::Raw; +use opencode_api::generated::{ + FormInfo, PermissionAskedData, SessionCreatedData, SessionID, SessionInboxCancelled, SessionInboxDelivered, + SessionInboxEnqueuedData, SessionInboxItem, SessionMessageAssistantFinish, SessionStructuredError, TokenUsageInfo, + V2Event, +}; use opencode_util::json_object; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; use serde_json::{Value, json}; use crate::child; use crate::compaction; use crate::error::Failure; -use crate::tools::{DiffSource, completed_tool_update, error_tool_update, pending_tool_call, running_tool_update}; +use crate::tools::{self, DiffSource, Part}; +use crate::update::{Chunk, Content, Id, Input, Kind, Meta, Update}; const RETRY_META: &str = "opencode/retry"; @@ -45,11 +56,9 @@ pub struct TurnContext { #[derive(Debug, Clone, PartialEq)] pub struct Tool { - pub session_id: String, - pub id: String, pub name: String, - pub input: Value, - pub metadata: Value, + pub input: Arc, + pub metadata: Input, } #[derive(Debug, Clone, Copy, Default, PartialEq)] @@ -62,15 +71,13 @@ pub struct Tokens { } impl Tokens { - fn from_json(value: &Value) -> Self { - let number = |value: Option<&Value>| value.and_then(Value::as_f64).unwrap_or_default(); - let cache = value.get("cache"); + fn of(tokens: &TokenUsageInfo) -> Self { Self { - input: number(value.get("input")), - output: number(value.get("output")), - reasoning: number(value.get("reasoning")), - cache_read: number(cache.and_then(|cache| cache.get("read"))), - cache_write: number(cache.and_then(|cache| cache.get("write"))), + input: tokens.input, + output: tokens.output, + reasoning: tokens.reasoning, + cache_read: tokens.cache.read, + cache_write: tokens.cache.write, } } @@ -101,107 +108,141 @@ pub struct Usage { #[derive(Debug, Clone, Default)] pub struct TurnState { pub started: bool, - /// By `sessionID:toolID`, in the order the tools started. - pub tools: IndexMap, - pub retries: HashMap, + /// By session and tool call ID, in the order the tools started. + pub tools: IndexMap<(SessionID, String), Tool>, + pub retries: HashMap, pub compactions: compaction::Tracked, - pub children: HashMap, + pub children: HashMap>, pub open_children: HashSet, /// Background shells that will wake their session, with the inbox ID of their notice once it is queued. pub shells: HashMap>, pub asks: HashSet, - pub finish: Option, + pub finish: Option, pub usage: Option, - pub step_error: Option, - pub execution_error: Option, + pub step_error: Option, + pub execution_error: Option, +} + +/// A scheduled retry, as `_meta["opencode/retry"]` shows it. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Retry { + pub attempt: i64, + pub next_retry_at: Option, + pub error: Value, +} + +/// An event, with the error it carries as it arrived when ACP forwards that error whole (a retry's, a failed child's, +/// a failed compaction's), so the fields this client does not know pass through. +#[derive(Debug)] +pub struct Event { + pub event: V2Event, + pub error: Option, +} + +impl<'de> Deserialize<'de> for Event { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + struct Carries { + data: Error, + } + #[derive(Deserialize)] + struct Error { + error: Value, + } + let raw = Raw::deserialize(deserializer)?; + let event = V2Event::from_raw(&raw).map_err(D::Error::custom)?; + let forwards = matches!( + event, + V2Event::SessionRetryScheduled(_) + | V2Event::SessionExecutionFailed(_) + | V2Event::SessionCompactionFailed(_) + ); + let error = forwards.then(|| raw.decode::()).transpose().map_err(D::Error::custom)?; + Ok(Self { event, error: error.map(|carries| carries.data.error) }) + } +} + +/// A tool's key borrowed from an event, to find the tool without building its key. +#[derive(Hash)] +struct ToolRef<'a>(&'a str, &'a str); + +impl Equivalent<(SessionID, String)> for ToolRef<'_> { + fn equivalent(&self, key: &(SessionID, String)) -> bool { + self.0 == key.0.as_str() && self.1 == key.1 + } } #[derive(Debug, Clone)] -pub enum Output { - SessionUpdate { update: Value, diff: Option }, - ChildUpdate { update: Value, diff: Option }, - PermissionAsk { event: Value, tool: Option, child: Option }, - FormAsk { form: Value, child: Option }, - AskSettled { id: String }, +pub enum Output<'a> { + SessionUpdate { update: Update<'a>, diff: Option }, + ChildUpdate { update: child::Update<'a>, diff: Option }, + PermissionAsk { ask: PermissionAskedData, tool: Option, child: Option> }, + FormAsk { form: FormInfo, child: Option> }, + AskSettled { id: &'a str }, } #[derive(Debug, Clone, Default)] -pub struct Folded { - pub outputs: Vec, +pub struct Folded<'a> { + pub outputs: Vec>, pub terminal: Option, } -impl Folded { - fn new(outputs: Vec) -> Self { +impl<'a> Folded<'a> { + fn new(outputs: Vec>) -> Self { Self { outputs, terminal: None } } } -fn data(event: &Value) -> &Value { - event.get("data").unwrap_or(&Value::Null) -} - -fn text<'a>(value: &'a Value, key: &str) -> Option<&'a str> { - value.get(key).and_then(Value::as_str) -} - -fn kind(event: &Value) -> &str { - text(event, "type").unwrap_or_default() -} - -pub fn fold(state: &mut TurnState, event: &Value, ctx: &TurnContext) -> Folded { - if kind(event) == "session.created" { - return child_created(state, event, ctx); - } - let data = data(event); - let session_id = session_id_from_event(event); +pub fn fold<'a>(state: &mut TurnState, incoming: &'a Event, ctx: &'a TurnContext) -> Folded<'a> { + let event = &incoming.event; + let session_id = session_of(event); let child = session_id.and_then(|id| state.children.get(id)).cloned(); let open_child = child.clone().filter(|child| state.open_children.contains(&child.id)); - - match kind(event) { - "permission.asked" if text(data, "sessionID") == Some(ctx.session_id.as_str()) || open_child.is_some() => { + match event { + V2Event::SessionCreated(created) => return child_created(state, &created.data, ctx), + V2Event::PermissionAsked(asked) if asked.data.session_id.as_str() == ctx.session_id || open_child.is_some() => { + let data = &asked.data; let tool = data - .get("source") - .and_then(|source| text(source, "id")) - .filter(|id| !id.is_empty()) - .and_then(|id| state.tools.get(&tool_key(text(data, "sessionID").unwrap_or_default(), id))) + .source + .as_ref() + .filter(|source| !source.id.is_empty()) + .and_then(|source| state.tools.get(&ToolRef(data.session_id.as_str(), &source.id))) .cloned(); - state.asks.insert(text(data, "id").unwrap_or_default().to_owned()); - return Folded::new(vec![Output::PermissionAsk { event: event.clone(), tool, child: open_child }]); + state.asks.insert(data.id.0.clone()); + return Folded::new(vec![Output::PermissionAsk { ask: data.clone(), tool, child: open_child }]); } - "form.created" => { - let form = data.get("form").cloned().unwrap_or(Value::Null); - if text(&form, "sessionID") == Some(ctx.session_id.as_str()) || open_child.is_some() { - state.asks.insert(text(&form, "id").unwrap_or_default().to_owned()); - return Folded::new(vec![Output::FormAsk { form, child: open_child }]); - } + V2Event::FormCreated(created) if created.data.form.session_id == ctx.session_id || open_child.is_some() => { + state.asks.insert(created.data.form.id.0.clone()); + return Folded::new(vec![Output::FormAsk { form: created.data.form.clone(), child: open_child }]); } _ => {} } - let settled = match kind(event) { - "permission.replied" => text(data, "requestID"), - "form.replied" | "form.cancelled" => text(data, "id"), + let settled = match event { + V2Event::PermissionReplied(replied) => Some(replied.data.request_id.as_str()), + V2Event::FormReplied(replied) => Some(replied.data.id.as_str()), + V2Event::FormCancelled(cancelled) => Some(cancelled.data.id.as_str()), _ => None, }; if let Some(id) = settled.filter(|id| !id.is_empty() && state.asks.remove(*id)) { - return Folded::new(vec![Output::AskSettled { id: id.to_owned() }]); + return Folded::new(vec![Output::AskSettled { id }]); } let Some(session_id) = session_id else { return Folded::default() }; if session_id != ctx.session_id && child.is_none() { return Folded::default(); } - match kind(event) { - "session.inbox.enqueued" => { - shell_noticed(state, data); + match event { + V2Event::SessionInboxEnqueued(enqueued) => { + shell_noticed(state, &enqueued.data); return Folded::default(); } - "session.inbox.delivered" | "session.inbox.cancelled" => { - if let Some(inbox) = text(data, "inboxID") { - state.shells.retain(|_, notice| notice.as_deref() != Some(inbox)); - } + V2Event::SessionInboxDelivered(SessionInboxDelivered { data, .. }) + | V2Event::SessionInboxCancelled(SessionInboxCancelled { data, .. }) => { + let inbox = data.inbox_id.as_str(); + state.shells.retain(|_, notice| notice.as_deref() != Some(inbox)); if session_id == ctx.session_id - && kind(event) == "session.inbox.delivered" - && ctx.start.as_ref().is_none_or(|start| text(data, "inboxID") == Some(&start.id)) + && matches!(event, V2Event::SessionInboxDelivered(_)) + && ctx.start.as_ref().is_none_or(|start| inbox == start.id) { state.started = true; } @@ -213,8 +254,8 @@ pub fn fold(state: &mut TurnState, event: &Value, ctx: &TurnContext) -> Folded { return Folded::default(); } match child { - Some(child) => child_event(state, event, ctx, &child), - None => root_event(state, event, ctx), + Some(child) => child_event(state, incoming, ctx, &child), + None => root_event(state, incoming, ctx), } } @@ -225,14 +266,11 @@ pub fn pending(state: &TurnState) -> bool { /// A background shell's notice wakes the session once delivered, so the shell stays pending until then. Only a /// job's notice wakes it: a user's shell command queues one without a job ID that waits for the next prompt. -fn shell_noticed(state: &mut TurnState, data: &Value) { - let item = data.get("item").unwrap_or(&Value::Null); - if text(item, "type") != Some("synthetic") { - return; - } - let metadata = item.get("payload").and_then(|payload| payload.get("metadata")).unwrap_or(&Value::Null); - let (Some(shell), Some(_)) = (text(metadata, "shellID"), text(metadata, "jobID")) else { return }; - state.shells.insert(shell.to_owned(), text(data, "inboxID").map(str::to_owned)); +fn shell_noticed(state: &mut TurnState, data: &SessionInboxEnqueuedData) { + let SessionInboxItem::Synthetic(item) = &data.item else { return }; + let text = |key| item.payload.metadata.as_ref()?.get(key)?.as_str(); + let (Some(shell), Some(_)) = (text("shellID"), text("jobID")) else { return }; + state.shells.insert(shell.to_owned(), Some(data.inbox_id.0.clone())); } /// `projectChild`: without the child capability, only the prompt turn that started a child shows its work. @@ -242,20 +280,19 @@ pub fn project_child(ctx: &TurnContext, child: &child::Session) -> bool { pub fn failure(state: &TurnState) -> Option { let error = state.step_error.as_ref().or(state.execution_error.as_ref())?; - let error_type = text(error, "type").unwrap_or_default(); - if error_type == "provider.auth" { + if error.r#type == "provider.auth" { return Some(Failure::AuthRequired); } - if error_type == "aborted" || error_type == "provider.content-filter" { + if error.r#type == "aborted" || error.r#type == "provider.content-filter" { return None; } Some(Failure::ServiceFailure { - safe_message: text(error, "message") + safe_message: Some(error.message.as_str()) .filter(|message| !message.is_empty()) .unwrap_or("OpenCode prompt failed") .to_owned(), service: Some("session".to_owned()), - error_name: Some(error_type.to_owned()), + error_name: Some(error.r#type.clone()), }) } @@ -269,7 +306,7 @@ pub fn number(value: f64) -> Value { } pub fn response(state: &TurnState, session_id: &str, terminal: Terminal) -> Value { - let error = state.step_error.as_ref().or(state.execution_error.as_ref()).and_then(|error| text(error, "type")); + let error = state.step_error.as_ref().or(state.execution_error.as_ref()).map(|error| error.r#type.as_str()); let usage = state.usage.as_ref().map(|usage| { let tokens = usage.turn; let positive = |value: f64| (value > 0.0).then(|| number(value)); @@ -287,25 +324,19 @@ pub fn response(state: &TurnState, session_id: &str, terminal: Terminal) -> Valu Some(retry) => json!({ (RETRY_META): retry }), None => json!({}), }; - json_object! { "stopReason": stop_reason(terminal, state.finish.as_deref(), error), "usage"?: usage, "_meta": meta } + let finish = state.finish.as_ref().map(SessionMessageAssistantFinish::as_str); + json_object! { "stopReason": stop_reason(terminal, finish, error), "usage"?: usage, "_meta": meta } } // Child compactions are left to the background consumer. -pub fn abandon(state: &mut TurnState, ctx: &TurnContext) -> Folded { +pub fn abandon<'a>(state: &mut TurnState, ctx: &'a TurnContext) -> Folded<'a> { let mut outputs: Vec = std::mem::take(&mut state.tools) - .values() - .flat_map(|tool| { - let mut update = error_tool_update( - &tool.id, - &tool.name, - &tool.input, - &json!([]), - Some(&tool.metadata), - "Cancelled", - &ctx.cwd, - ); - tag(&mut update, "tool_call_update"); - route(ctx, state.children.get(&tool.session_id), update) + .into_iter() + .flat_map(|((session_id, id), tool)| { + let metadata = Some(Cow::Owned(tool.metadata)); + let id = Cow::Owned(id); + let update = tools::error_tool_update(id, &tool.name, &tool.input, &[], metadata, "Cancelled", &ctx.cwd); + route(ctx, state.children.get(session_id.as_str()), Kind::ToolCallUpdate(update).into()) }) .collect(); if let Some(started) = state.compactions.remove(&ctx.session_id) @@ -317,216 +348,246 @@ pub fn abandon(state: &mut TurnState, ctx: &TurnContext) -> Folded { Folded::new(outputs) } -pub fn reasoning_message_id(message_id: &str, ordinal: &Value) -> String { - format!("{message_id}:reasoning:{}", js_string(ordinal)) -} - -fn js_string(value: &Value) -> String { - match value { - Value::String(text) => text.clone(), - Value::Null => "undefined".to_owned(), - other => other.to_string(), - } -} - -fn child_created(state: &mut TurnState, event: &Value, ctx: &TurnContext) -> Folded { - let data = data(event); - let Some(parent_id) = text(data, "parentID").filter(|id| !id.is_empty()) else { return Folded::default() }; +fn child_created<'a>(state: &mut TurnState, data: &SessionCreatedData, ctx: &'a TurnContext) -> Folded<'a> { + let Some(parent_id) = data.parent_id.as_ref().map(SessionID::as_str).filter(|id| !id.is_empty()) else { + return Folded::default(); + }; let parent = (parent_id != ctx.session_id).then(|| state.children.get(parent_id)).flatten(); if parent.is_none() && parent_id != ctx.session_id { return Folded::default(); } - let child = child::Session { - id: text(data, "sessionID").unwrap_or_default().to_owned(), + let child = Arc::new(child::Session { + id: data.session_id.0.clone(), parent_id: parent_id.to_owned(), depth: parent.map_or(1, |parent| parent.depth + 1), - title: text(data, "title").map(str::to_owned), + title: data.title.clone(), turn_id: match parent { Some(parent) => parent.turn_id.clone(), None => ctx.start.as_ref().map(|start| start.id.clone()), }, - }; - let outputs = child_status(ctx, &child, child::status("created", None)); + }); + let outputs = child_status(ctx, &child, child::Event::Status("created", None)); state.open_children.insert(child.id.clone()); state.children.insert(child.id.clone(), child); Folded::new(outputs) } -fn root_event(state: &mut TurnState, event: &Value, ctx: &TurnContext) -> Folded { - let data = data(event); - match kind(event) { - "session.step.started" => { +fn root_event<'a>(state: &mut TurnState, incoming: &'a Event, ctx: &'a TurnContext) -> Folded<'a> { + match &incoming.event { + V2Event::SessionStepStarted(_) => { state.step_error = None; - session_event(state, event, ctx, None) + session_event(state, incoming, ctx, None) } - "session.step.ended" => { - record_step(state, data.get("tokens")); - state.finish = text(data, "finish").map(str::to_owned); + V2Event::SessionStepEnded(ended) => { + record_step(state, &ended.data.tokens); + state.finish = Some(ended.data.finish.clone()); Folded::default() } - "session.step.failed" => { - if let Some(tokens) = data.get("tokens").filter(|tokens| !tokens.is_null()) { - record_step(state, Some(tokens)); + V2Event::SessionStepFailed(failed) => { + if let Some(tokens) = &failed.data.tokens { + record_step(state, tokens); } - state.step_error = data.get("error").cloned(); + state.step_error = Some(failed.data.error.clone()); Folded::default() } // Following children, the next delivery starts the next parent turn. - "session.execution.succeeded" => terminal(state, ctx, Terminal::Succeeded), - "session.execution.interrupted" => terminal(state, ctx, Terminal::Interrupted), - "session.execution.failed" => { - state.execution_error = data.get("error").cloned(); + V2Event::SessionExecutionSucceeded(_) => terminal(state, ctx, Terminal::Succeeded), + V2Event::SessionExecutionInterrupted(_) => terminal(state, ctx, Terminal::Interrupted), + V2Event::SessionExecutionFailed(failed) => { + state.execution_error = Some(failed.data.error.clone()); terminal(state, ctx, Terminal::Failed) } - _ => session_event(state, event, ctx, None), + _ => session_event(state, incoming, ctx, None), } } -fn terminal(state: &mut TurnState, ctx: &TurnContext, terminal: Terminal) -> Folded { +fn terminal<'a>(state: &mut TurnState, ctx: &TurnContext, terminal: Terminal) -> Folded<'a> { state.started = ctx.start.is_some(); Folded { outputs: Vec::new(), terminal: Some(terminal) } } -fn child_event(state: &mut TurnState, event: &Value, ctx: &TurnContext, child: &child::Session) -> Folded { - match kind(event) { - "session.execution.started" => { +fn child_event<'a>( + state: &mut TurnState, + incoming: &'a Event, + ctx: &'a TurnContext, + child: &Arc, +) -> Folded<'a> { + match &incoming.event { + V2Event::SessionExecutionStarted(_) => { state.open_children.insert(child.id.clone()); - Folded::new(child_status(ctx, child, child::status("running", None))) + Folded::new(child_status(ctx, child, child::Event::Status("running", None))) } - "session.execution.succeeded" => child_ended(state, ctx, child, child::status("completed", None)), - "session.execution.interrupted" => child_ended(state, ctx, child, child::status("interrupted", None)), - "session.execution.failed" => { - child_ended(state, ctx, child, child::status("failed", data(event).get("error").cloned())) + V2Event::SessionExecutionSucceeded(_) => { + child_ended(state, ctx, child, child::Event::Status("completed", None)) } - _ => session_event(state, event, ctx, Some(child)), + V2Event::SessionExecutionInterrupted(_) => { + child_ended(state, ctx, child, child::Event::Status("interrupted", None)) + } + V2Event::SessionExecutionFailed(_) => { + child_ended(state, ctx, child, child::Event::Status("failed", Some(forwarded(incoming)))) + } + _ => session_event(state, incoming, ctx, Some(child)), } } -fn tag(update: &mut Value, session_update: &str) { - if update.is_object() { - *update = json_object! { "sessionUpdate": session_update, ..update.take() }; - } -} - -fn session_event(state: &mut TurnState, event: &Value, ctx: &TurnContext, child: Option<&child::Session>) -> Folded { - let data = data(event); +fn session_event<'a>( + state: &mut TurnState, + incoming: &'a Event, + ctx: &'a TurnContext, + child: Option<&Arc>, +) -> Folded<'a> { let session_id = child.map_or(ctx.session_id.as_str(), |child| child.id.as_str()); - let send = |update: Value| route(ctx, child, update); + let send = |updates: Vec>| Folded::new(updates.into_iter().flat_map(|u| route(ctx, child, u)).collect()); let standard = compaction::uses_standard_updates(ctx.compaction, ctx.child_updates, child.is_some()); - match kind(event) { - "session.step.started" => { + let info = + |retry| Update { kind: Kind::SessionInfoUpdate {}, meta: Meta { retry: Some(retry), ..Meta::default() } }; + let chunk = + |message_id, delta: &'a str| Chunk { message_id, content: Content::Text { text: Cow::Borrowed(delta) } }; + let cwd = ctx.cwd.as_str(); + let update = match &incoming.event { + V2Event::SessionStepStarted(_) => { if state.retries.remove(session_id).is_none() { return Folded::default(); } - Folded::new(send(json!({ "sessionUpdate": "session_info_update", "_meta": { (RETRY_META): null } }))) + info(None) } - "session.retry.scheduled" => { - let retry = json!({ - "attempt": data.get("attempt").cloned().unwrap_or(Value::Null), - "nextRetryAt": iso_time(data.get("at")), - "error": data.get("error").cloned().unwrap_or(Value::Null), - }); + V2Event::SessionRetryScheduled(scheduled) => { + let data = &scheduled.data; + let retry = Retry { + attempt: data.attempt, + next_retry_at: opencode_util::time::iso(data.at), + error: forwarded(incoming).clone(), + }; state.retries.insert(session_id.to_owned(), retry.clone()); - Folded::new(send(json!({ "sessionUpdate": "session_info_update", "_meta": { (RETRY_META): retry } }))) + info(Some(retry)) } - "session.compaction.started" | "session.compaction.ended" | "session.compaction.failed" => { - let (tracked, updates) = compaction::apply(event, &state.compactions, standard); - state.compactions = tracked; - Folded::new(updates.into_iter().flat_map(send).collect()) + V2Event::SessionCompactionStarted(started) => compaction::started(&mut state.compactions, started, standard), + V2Event::SessionCompactionEnded(ended) => { + return send(compaction::ended(&mut state.compactions, ended, standard).into_iter().collect()); } - "session.compaction.delta" => { - let update = - compaction::chunk(state.compactions.get(session_id), text(data, "text").unwrap_or_default(), standard); - Folded::new(update.map(send).unwrap_or_default()) + V2Event::SessionCompactionFailed(failed) => { + return send(compaction::failed(&mut state.compactions, failed, forwarded(incoming), standard)); } - "session.text.delta" => Folded::new(send(json!({ - "sessionUpdate": "agent_message_chunk", - "messageId": data.get("assistantMessageID").cloned().unwrap_or(Value::Null), - "content": { "type": "text", "text": data.get("delta").cloned().unwrap_or(Value::Null) }, - }))), - "session.reasoning.delta" => Folded::new(send(json!({ - "sessionUpdate": "agent_thought_chunk", - "messageId": reasoning_message_id( - text(data, "assistantMessageID").unwrap_or_default(), - data.get("ordinal").unwrap_or(&Value::Null), - ), - "content": { "type": "text", "text": data.get("delta").cloned().unwrap_or(Value::Null) }, - }))), - "session.tool.input.started" => { - let tool_session = text(data, "sessionID").unwrap_or_default(); - let id = text(data, "id").unwrap_or_default(); - let name = text(data, "name").unwrap_or("tool"); - state.tools.insert(tool_key(tool_session, id), new_tool(tool_session, id, Some(name))); - let mut update = pending_tool_call(id, name, &json!({}), None, &ctx.cwd); - tag(&mut update, "tool_call"); - Folded::new(send(update)) + V2Event::SessionCompactionDelta(delta) => { + let update = compaction::chunk(state.compactions.get(session_id), &delta.data.text, standard); + return send(update.into_iter().collect()); } - "session.tool.called" => { - let tool_session = text(data, "sessionID").unwrap_or_default(); - let id = text(data, "id").unwrap_or_default(); - let tool = - state.tools.entry(tool_key(tool_session, id)).or_insert_with(|| new_tool(tool_session, id, None)); - tool.input = data.get("input").cloned().unwrap_or_else(|| json!({})); - let mut update = running_tool_update(id, &tool.name, &tool.input, &ctx.cwd); - tag(&mut update, "tool_call_update"); - Folded::new(send(update)) + V2Event::SessionTextDelta(delta) => { + let data = &delta.data; + Kind::AgentMessageChunk(chunk(Id::Message(data.assistant_message_id.as_str()), &data.delta)).into() } - "session.tool.progress" => { - let id = text(data, "id").unwrap_or_default(); - let Some(tool) = state.tools.get_mut(&tool_key(text(data, "sessionID").unwrap_or_default(), id)) else { + V2Event::SessionReasoningDelta(delta) => { + let data = &delta.data; + Kind::AgentThoughtChunk(chunk(Id::Reasoning(data.assistant_message_id.as_str(), data.ordinal), &data.delta)) + .into() + } + V2Event::SessionToolInputStarted(started) => { + let data = &started.data; + let tool = new_tool(&data.name); + let update = tools::pending_tool_call(Cow::Borrowed(&data.id), &data.name, &tool.input, None, cwd); + state.tools.insert((data.session_id.clone(), data.id.clone()), tool); + Kind::ToolCall(update).into() + } + V2Event::SessionToolCalled(called) => { + let data = &called.data; + let tool = tool_mut(&mut state.tools, &data.session_id, &data.id); + tool.input = Arc::new(data.input.clone()); + Kind::ToolCallUpdate(tools::running_tool_update(Cow::Borrowed(&data.id), &tool.name, &tool.input, cwd)) + .into() + } + V2Event::SessionToolProgress(progress) => { + let data = &progress.data; + let Some(tool) = state.tools.get_mut(&ToolRef(data.session_id.as_str(), &data.id)) else { return Folded::default(); }; - tool.metadata = data.get("metadata").cloned().unwrap_or(Value::Null); - let mut update = running_tool_update(id, &tool.name, &tool.input, &ctx.cwd); - tag(&mut update, "tool_call_update"); - Folded::new(send(update)) + tool.metadata = data.metadata.clone(); + Kind::ToolCallUpdate(tools::running_tool_update(Cow::Borrowed(&data.id), &tool.name, &tool.input, cwd)) + .into() } - "session.tool.success" => { - let tool_session = text(data, "sessionID").unwrap_or_default(); - let id = text(data, "id").unwrap_or_default(); + V2Event::SessionToolSuccess(success) => { + let data = &success.data; let tool = state .tools - .shift_remove(&tool_key(tool_session, id)) - .unwrap_or_else(|| new_tool(tool_session, id, None)); - let metadata = data.get("metadata").filter(|value| !value.is_null()); + .shift_remove(&ToolRef(data.session_id.as_str(), &data.id)) + .unwrap_or_else(|| new_tool("tool")); + let metadata = data.metadata.as_ref(); + let text = |key| metadata?.get(key)?.as_str(); // A shell moved to the background reports its end through a notice that wakes the session. A command // that exits at once can queue its notice first; keep the notice it already has. - if let Some(metadata) = metadata.filter(|metadata| text(metadata, "status") == Some("running")) - && let Some(shell) = text(metadata, "shellID") + if text("status") == Some("running") + && let Some(shell) = text("shellID") { state.shells.entry(shell.to_owned()).or_insert(None); } - let mut update = completed_tool_update( - id, - &tool.name, - &tool.input, - data.get("content").unwrap_or(&json!([])), - metadata, - &ctx.cwd, - ); - tag(&mut update, "tool_call_update"); + let parts: Vec = data.content.iter().map(Part::of).collect(); + let id = Cow::Borrowed(data.id.as_str()); + let update = + tools::completed_tool_update(id, &tool.name, &tool.input, &parts, metadata.map(Cow::Borrowed), cwd); let source = DiffSource { tool_name: tool.name, input: tool.input, metadata: metadata.cloned() }; - Folded::new(send(update).into_iter().map(|output| with_diff(output, &source)).collect()) + let outputs = route(ctx, child, Kind::ToolCallUpdate(update).into()); + return Folded::new(outputs.into_iter().map(|output| with_diff(output, &source)).collect()); } - "session.tool.failed" => { - let tool_session = text(data, "sessionID").unwrap_or_default(); - let id = text(data, "id").unwrap_or_default(); + V2Event::SessionToolFailed(failed) => { + let data = &failed.data; let tool = state .tools - .shift_remove(&tool_key(tool_session, id)) - .unwrap_or_else(|| new_tool(tool_session, id, None)); - let metadata = data.get("metadata").filter(|value| !value.is_null()).unwrap_or(&tool.metadata); - let content = data.get("content").filter(|value| !value.is_null()).cloned().unwrap_or_else(|| json!([])); - let error = data.get("error").and_then(|error| text(error, "message")).unwrap_or_default(); - let mut update = error_tool_update(id, &tool.name, &tool.input, &content, Some(metadata), error, &ctx.cwd); - tag(&mut update, "tool_call_update"); - Folded::new(send(update)) + .shift_remove(&ToolRef(data.session_id.as_str(), &data.id)) + .unwrap_or_else(|| new_tool("tool")); + let metadata = data.metadata.as_ref().map_or(Cow::Owned(tool.metadata), Cow::Borrowed); + let parts: Vec = data.content.iter().flatten().map(Part::of).collect(); + let (id, message) = (Cow::Borrowed(data.id.as_str()), data.error.message.as_str()); + let update = tools::error_tool_update(id, &tool.name, &tool.input, &parts, Some(metadata), message, cwd); + Kind::ToolCallUpdate(update).into() } - _ => Folded::default(), - } + _ => return Folded::default(), + }; + Folded::new(route(ctx, child, update)) } -fn with_diff(output: Output, source: &DiffSource) -> Output { +/// The error an event carries as it arrived. +fn forwarded(event: &Event) -> &Value { + event.error.as_ref().unwrap_or(&Value::Null) +} + +/// The session an event is about, for the events the fold reads. +fn session_of(event: &V2Event) -> Option<&str> { + macro_rules! session { + ($($variant:ident),*) => { + match event { + $(V2Event::$variant(event) => Some(event.data.session_id.as_str()),)* + V2Event::FormCreated(event) => Some(event.data.form.session_id.as_str()), + _ => None, + } + }; + } + session!( + PermissionAsked, + SessionInboxEnqueued, + SessionInboxDelivered, + SessionInboxCancelled, + SessionStepStarted, + SessionStepEnded, + SessionStepFailed, + SessionExecutionStarted, + SessionExecutionSucceeded, + SessionExecutionFailed, + SessionExecutionInterrupted, + SessionRetryScheduled, + SessionCompactionStarted, + SessionCompactionDelta, + SessionCompactionEnded, + SessionCompactionFailed, + SessionTextDelta, + SessionReasoningDelta, + SessionToolInputStarted, + SessionToolCalled, + SessionToolProgress, + SessionToolSuccess, + SessionToolFailed + ) +} + +fn with_diff<'a>(output: Output<'a>, source: &DiffSource) -> Output<'a> { match output { Output::SessionUpdate { update, .. } => Output::SessionUpdate { update, diff: Some(source.clone()) }, Output::ChildUpdate { update, .. } => Output::ChildUpdate { update, diff: Some(source.clone()) }, @@ -534,66 +595,53 @@ fn with_diff(output: Output, source: &DiffSource) -> Output { } } -fn iso_time(at: Option<&Value>) -> Value { - let millis = at.and_then(Value::as_f64).unwrap_or_default(); - #[allow(clippy::cast_possible_truncation)] - opencode_util::time::iso(millis as i64).map_or(Value::Null, Value::from) +fn new_tool(name: &str) -> Tool { + Tool { name: name.to_owned(), input: Arc::default(), metadata: Input::new() } } -fn new_tool(session_id: &str, id: &str, name: Option<&str>) -> Tool { - Tool { - session_id: session_id.to_owned(), - id: id.to_owned(), - name: name.unwrap_or("tool").to_owned(), - input: json!({}), - metadata: json!({}), - } +/// The tool, started now if its input did not stream. +fn tool_mut<'s>(tools: &'s mut IndexMap<(SessionID, String), Tool>, session_id: &SessionID, id: &str) -> &'s mut Tool { + let index = tools + .get_index_of(&ToolRef(session_id.as_str(), id)) + .unwrap_or_else(|| tools.insert_full((session_id.clone(), id.to_owned()), new_tool("tool")).0); + &mut tools[index] } -fn route(ctx: &TurnContext, child: Option<&child::Session>, update: Value) -> Vec { +fn route<'a>(ctx: &'a TurnContext, child: Option<&Arc>, mut update: Update<'a>) -> Vec> { let Some(child) = child else { return vec![Output::SessionUpdate { update, diff: None }] }; - let projected = child::project(update, child); + child::project(&mut update, child); if ctx.child_updates { - return child_status(ctx, child, child::update_event(projected)); + return child_status(ctx, child, child::Event::Update(update)); } if !project_child(ctx, child) { return Vec::new(); } - vec![Output::SessionUpdate { update: projected, diff: None }] + vec![Output::SessionUpdate { update, diff: None }] } -fn child_status(ctx: &TurnContext, child: &child::Session, event: Value) -> Vec { +fn child_status<'a>(ctx: &'a TurnContext, child: &Arc, event: child::Event<'a>) -> Vec> { if !ctx.child_updates { return Vec::new(); } - vec![Output::ChildUpdate { update: child::update(&ctx.session_id, child, event), diff: None }] + let update = child::Update { root_session_id: &ctx.session_id, child: child.clone(), event }; + vec![Output::ChildUpdate { update, diff: None }] } -fn child_ended(state: &mut TurnState, ctx: &TurnContext, child: &child::Session, status: Value) -> Folded { +fn child_ended<'a>( + state: &mut TurnState, + ctx: &'a TurnContext, + child: &Arc, + status: child::Event<'a>, +) -> Folded<'a> { state.open_children.remove(&child.id); Folded::new(child_status(ctx, child, status)) } -fn record_step(state: &mut TurnState, tokens: Option<&Value>) { - let tokens = Tokens::from_json(tokens.unwrap_or(&Value::Null)); +fn record_step(state: &mut TurnState, tokens: &TokenUsageInfo) { + let tokens = Tokens::of(tokens); state.usage = Some(Usage { turn: state.usage.map_or(tokens, |usage| usage.turn.add(&tokens)), last: tokens }); } -fn session_id_from_event(event: &Value) -> Option<&str> { - let data = data(event); - if let Some(id) = text(data, "sessionID") { - return Some(id); - } - if kind(event) == "form.created" { - return data.get("form").and_then(|form| text(form, "sessionID")); - } - None -} - -fn tool_key(session_id: &str, id: &str) -> String { - format!("{session_id}:{id}") -} - fn stop_reason(terminal: Terminal, finish: Option<&str>, error: Option<&str>) -> &'static str { if terminal == Terminal::Interrupted || error == Some("aborted") { return "cancelled"; diff --git a/packages/cli-rs/crates/acp/src/turn.rs b/packages/cli-rs/crates/acp/src/turn.rs index 713601aab0c..99efbc2a0b0 100644 --- a/packages/cli-rs/crates/acp/src/turn.rs +++ b/packages/cli-rs/crates/acp/src/turn.rs @@ -9,6 +9,7 @@ use std::time::Duration; use futures_util::StreamExt; use futures_util::future::BoxFuture; use opencode_api::client::Client; +use opencode_api::events::CONNECTED; use opencode_api::generated::{ PromptInputFileAttachment, SessionCommandInput, SessionCompactInput, SessionGetInput, SessionID, SessionInboxDelivery, SessionInterruptInput, SessionMessageID, SessionPromptInput, SessionSyntheticInput, @@ -21,7 +22,7 @@ use tokio_util::sync::CancellationToken; use crate::capabilities::Capabilities; use crate::catalog::{Catalogs, find_model}; use crate::child; -use crate::client::{check, classify, decode_session_id, event_type, subscribe}; +use crate::client::{check, classify, decode_session_id, subscribe}; use crate::config_option::current_model; use crate::connection::{Connection, Responded}; use crate::elicitation; @@ -34,7 +35,7 @@ use crate::translate::{self, Output, StartKind, Terminal, TurnContext, TurnState /// Core acknowledges an interrupt before its cleanup settles, and its shell tool waits 3 s before SIGKILL. pub const CANCEL_DRAIN_TIMEOUT: Duration = Duration::from_secs(5); -type Event = Result; +type Event = Result; type Job = BoxFuture<'static, ()>; struct Subscription { @@ -301,10 +302,10 @@ impl Turns { }; match first { Err(failure) => return Exit::Failed(failure), - Ok(event) if event_type(&event) != "server.connected" => { + Ok(event) if event.event.tag() != CONNECTED => { return Exit::Failed(Failure::Defect { name: Some("Error".to_owned()), - detail: format!("expected server.connected, got {}", event_type(&event)), + detail: format!("expected server.connected, got {}", event.event.tag()), }); } Ok(_) => {} @@ -553,7 +554,7 @@ impl Turns { check(self.client.session_get(&SessionGetInput { session_id: SessionID(attached.id.clone()) }).await)?; self.connection.session_update( &attached.id, - json!({ + &json!({ "sessionUpdate": "usage_update", "used": translate::number(used), "size": size, @@ -598,34 +599,27 @@ impl Turns { } } - async fn interpret(self: &Arc, turn: &Turn, output: Output) -> Result<(), Failure> { + async fn interpret(self: &Arc, turn: &Turn, output: Output<'_>) -> Result<(), Failure> { match output { - Output::SessionUpdate { update, diff } => { - let update = permission::with_completed_diffs(update, diff.as_ref(), &turn.ctx.cwd).await; - self.connection.session_update(&turn.ctx.session_id, update) + Output::SessionUpdate { mut update, diff } => { + permission::add_completed_diffs(&mut update, diff.as_ref(), &turn.ctx.cwd).await; + self.connection.session_update(&turn.ctx.session_id, &update) } Output::ChildUpdate { mut update, diff } => { - if update.get("type").and_then(Value::as_str) == Some("update") - && let Some(inner) = update.get("update").cloned() - { - let enriched = permission::with_completed_diffs(inner, diff.as_ref(), &turn.ctx.cwd).await; - if let Some(object) = update.as_object_mut() { - object.insert("update".to_owned(), enriched); - } + if let child::Event::Update(update) = &mut update.event { + permission::add_completed_diffs(update, diff.as_ref(), &turn.ctx.cwd).await; } - if let Err(failure) = self.connection.notify(child::UPDATE_METHOD, update) { + if let Err(failure) = self.connection.notify(child::UPDATE_METHOD, &update) { log::warn!(cause = failure.tag(); "ACP child session update failed"); } Ok(()) } - Output::PermissionAsk { event, tool, child } => { - let data = event.get("data").cloned().unwrap_or(Value::Null); - let id = data.get("id").and_then(Value::as_str).unwrap_or_default().to_owned(); + Output::PermissionAsk { ask, tool, child } => { + let id = ask.id.0.clone(); let input = Arc::new(permission::Input { client: self.client.clone(), connection: self.connection.clone(), - session_id: data.get("sessionID").and_then(Value::as_str).unwrap_or_default().to_owned(), - event, + ask, client_session_id: turn.ctx.session_id.clone(), cwd: turn.ctx.cwd.clone(), tool, @@ -642,13 +636,15 @@ impl Turns { Ok(()) } Output::FormAsk { form, child } => { + // The form becomes a JSON Schema, which elicitation builds from its JSON. + let form = serde_json::to_value(&form).unwrap_or_default(); let capabilities = *lock(&self.capabilities); let Some(requested_schema) = elicitation::requested_schema(&form, &capabilities) else { elicitation::cancel_unshown(&self.client, &form).await; return Ok(()); }; let id = form.get("id").and_then(Value::as_str).unwrap_or_default().to_owned(); - let tool_call_sent = child.as_ref().is_none_or(|child| translate::project_child(&turn.ctx, child)); + let tool_call_sent = child.as_deref().is_none_or(|child| translate::project_child(&turn.ctx, child)); let input = Arc::new(elicitation::Input { client: self.client.clone(), connection: self.connection.clone(), @@ -669,7 +665,7 @@ impl Turns { Ok(()) } Output::AskSettled { id } => { - if let Some(settled) = lock(&turn.subscription.settled).remove(&id) { + if let Some(settled) = lock(&turn.subscription.settled).remove(id) { let _ = settled.send(()); } Ok(()) @@ -693,7 +689,7 @@ async fn join(result: &mut watch::Receiver>>) - } } -async fn take(subscription: &Subscription) -> Result { +async fn take(subscription: &Subscription) -> Result { match subscription.events.lock().await.recv().await { Some(Ok(event)) => Ok(event), Some(Err(error)) => Err(classify(&error)), diff --git a/packages/cli-rs/crates/acp/src/update.rs b/packages/cli-rs/crates/acp/src/update.rs new file mode 100644 index 00000000000..8e7ea388443 --- /dev/null +++ b/packages/cli-rs/crates/acp/src/update.rs @@ -0,0 +1,175 @@ +//! The updates of `session/update`, serialized straight to the connection's buffer, each field in its wire order. + +use std::borrow::Cow; +use std::sync::Arc; + +use indexmap::IndexMap; +use serde::{Serialize, Serializer}; +use serde_json::Value; + +use crate::child; +use crate::compaction::{CompactionUpdate, Marker}; +use crate::translate::Retry; + +/// A tool call's input or metadata: open data, in the order it arrived. +pub type Input = IndexMap; + +#[derive(Debug, Clone, Serialize)] +pub struct Update<'a> { + #[serde(flatten)] + pub kind: Kind<'a>, + #[serde(rename = "_meta", skip_serializing_if = "Meta::is_empty")] + pub meta: Meta<'a>, +} + +impl<'a> From> for Update<'a> { + fn from(kind: Kind<'a>) -> Self { + Self { kind, meta: Meta::default() } + } +} + +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "sessionUpdate", rename_all = "snake_case")] +pub enum Kind<'a> { + AgentMessageChunk(Chunk<'a>), + AgentThoughtChunk(Chunk<'a>), + ToolCall(ToolCall<'a>), + ToolCallUpdate(ToolCallUpdate<'a>), + SessionInfoUpdate {}, + CompactionUpdate(CompactionUpdate<'a>), + CompactionSummaryChunk { + #[serde(rename = "compactionId")] + compaction_id: String, + content: Content<'a>, + }, + /// A replayed update built as JSON, with its own `sessionUpdate`. + #[serde(untagged)] + Json(Value), +} + +#[derive(Debug, Clone, Default, Serialize)] +pub struct Meta<'a> { + /// `Some(None)` clears the retry. + #[serde(rename = "opencode/retry", skip_serializing_if = "Option::is_none")] + pub retry: Option>, + #[serde(rename = "opencode/compaction", skip_serializing_if = "Option::is_none")] + pub compaction: Option>, + #[serde(rename = "opencode/child-session", skip_serializing_if = "Option::is_none", serialize_with = "shared")] + pub child: Option>, +} + +impl Meta<'_> { + pub fn is_empty(&self) -> bool { + self.retry.is_none() && self.compaction.is_none() && self.child.is_none() + } +} + +fn shared(value: &Option>, serializer: S) -> Result { + value.as_deref().serialize(serializer) +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Chunk<'a> { + pub message_id: Id<'a>, + pub content: Content<'a>, +} + +/// A chunk's message ID. +#[derive(Debug, Clone)] +pub enum Id<'a> { + Message(&'a str), + /// A reasoning part's chunks: `{message}:reasoning:{ordinal}`. + Reasoning(&'a str, i64), +} + +impl Serialize for Id<'_> { + fn serialize(&self, serializer: S) -> Result { + match self { + Self::Message(id) => serializer.serialize_str(id), + Self::Reasoning(message, ordinal) => serializer.collect_str(&format_args!("{message}:reasoning:{ordinal}")), + } + } +} + +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Content<'a> { + Text { + text: Cow<'a, str>, + }, + Image { + #[serde(rename = "mimeType")] + mime_type: &'a str, + data: &'a str, + }, +} + +/// A `tool_call`, or the tool call of a permission request. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ToolCall<'a> { + pub tool_call_id: Cow<'a, str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option<&'a str>, + pub title: String, + pub kind: &'static str, + pub status: &'static str, + pub locations: Vec, + #[serde(skip_serializing_if = "Option::is_none", serialize_with = "shared")] + pub raw_input: Option>, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub content: Vec>, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ToolCallUpdate<'a> { + pub tool_call_id: Cow<'a, str>, + pub status: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + pub locations: Vec, + #[serde(skip_serializing_if = "Option::is_none", serialize_with = "shared")] + pub raw_input: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub content: Option>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub raw_output: Option>, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Location { + pub path: String, +} + +#[derive(Debug, Clone, Serialize)] +pub struct RawOutput<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option<&'a str>, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ToolCallContent<'a> { + Content { content: Content<'a> }, + Diff(Diff), +} + +impl<'a> ToolCallContent<'a> { + pub fn text(text: Cow<'a, str>) -> Self { + Self::Content { content: Content::Text { text } } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Diff { + pub path: String, + pub old_text: Option, + pub new_text: String, +} diff --git a/packages/cli-rs/crates/acp/tests/acp/permission.rs b/packages/cli-rs/crates/acp/tests/acp/permission.rs index e07e231beef..3258272eaf9 100644 --- a/packages/cli-rs/crates/acp/tests/acp/permission.rs +++ b/packages/cli-rs/crates/acp/tests/acp/permission.rs @@ -393,16 +393,19 @@ async fn previews_added_files_as_new_and_deleted_files_as_empty() { async fn leaves_a_scripts_changes_alone_some_have_no_diff_and_a_file_can_change_more_than_once() { let dir = opencode_util::temp::tempdir().unwrap(); std::fs::write(dir.path().join("a.txt"), "a\nb\nc\n").unwrap(); - let update = json!({ "sessionUpdate": "tool_call_update", "toolCallId": "call_1", "status": "completed" }); + let call = + opencode_acp::tools::completed_tool_update("call_1".into(), "execute", &Default::default(), &[], None, "/"); + let mut update = opencode_acp::update::Kind::ToolCallUpdate(call).into(); + let before = json!(update); let source = opencode_acp::tools::DiffSource { tool_name: "execute".to_owned(), - input: json!({ "code": "1" }), - metadata: Some(json!({ "files": [ + input: std::sync::Arc::new(serde_json::from_value(json!({ "code": "1" })).unwrap()), + metadata: Some(serde_json::from_value(json!({ "files": [ { "file": "a.txt", "status": "modified", "additions": 1, "deletions": 0, "patch": "@@ -1 +1,2 @@\n a\n+b\n" }, { "file": "a.txt", "status": "modified", "additions": 1, "deletions": 0, "patch": "@@ -1,2 +1,3 @@\n a\n b\n+c\n" }, - ] })), + ] })).unwrap()), }; let cwd = dir.path().to_string_lossy(); - let result = opencode_acp::permission::with_completed_diffs(update.clone(), Some(&source), &cwd).await; - assert_eq!(result, update); + opencode_acp::permission::add_completed_diffs(&mut update, Some(&source), &cwd).await; + assert_eq!(json!(update), before); } diff --git a/packages/cli-rs/crates/acp/tests/acp/translate.rs b/packages/cli-rs/crates/acp/tests/acp/translate.rs index c7c0067d356..f3b16a13b55 100644 --- a/packages/cli-rs/crates/acp/tests/acp/translate.rs +++ b/packages/cli-rs/crates/acp/tests/acp/translate.rs @@ -1,4 +1,4 @@ -use opencode_acp::translate::{self, Output, StartKind, Terminal, TurnContext, TurnStart, TurnState}; +use opencode_acp::translate::{self, Event, Output, StartKind, Terminal, TurnContext, TurnStart, TurnState}; use serde_json::{Value, json}; use crate::wire::{ @@ -26,17 +26,25 @@ fn live(events: Vec) -> Vec { struct Run { state: TurnState, - outputs: Vec, + updates: Vec, + children: Vec, terminal: Option, } fn run(events: &[Value], ctx: &TurnContext) -> Run { - let mut result = Run { state: TurnState::default(), outputs: Vec::new(), terminal: None }; + let mut result = Run { state: TurnState::default(), updates: Vec::new(), children: Vec::new(), terminal: None }; for (index, event) in events.iter().enumerate() { let mut event = event.clone(); event["id"] = json!(format!("evt_{}", index + 1)); + let event: Event = serde_json::from_value(event).unwrap(); let folded = translate::fold(&mut result.state, &event, ctx); - result.outputs.extend(folded.outputs); + for output in folded.outputs { + match output { + Output::SessionUpdate { update, .. } => result.updates.push(json!(update)), + Output::ChildUpdate { update, .. } => result.children.push(json!(update)), + _ => {} + } + } if folded.terminal.is_some() { result.terminal = folded.terminal; } @@ -49,7 +57,7 @@ fn updates(outputs: &[Output]) -> Value { outputs .iter() .filter_map(|output| match output { - Output::SessionUpdate { update, .. } => Some(update.clone()), + Output::SessionUpdate { update, .. } => Some(json!(update)), _ => None, }) .collect::>() @@ -73,11 +81,8 @@ fn translated(events: &[Value], ctx: &TurnContext) -> Value { }) }); json!({ - "updates": updates(&result.outputs), - "children": result.outputs.iter().filter_map(|output| match output { - Output::ChildUpdate { update, .. } => Some(update.clone()), - _ => None, - }).collect::>(), + "updates": result.updates, + "children": result.children, "terminal": terminal, "response": result.terminal.map(|terminal| translate::response(&result.state, ROOT, terminal)), "failure": translate::failure(&result.state).map(|failure| failure.tag()), @@ -391,14 +396,15 @@ fn turn_translation() { #[test] fn reports_a_pending_retry_and_clears_it_when_the_next_step_starts() { - let error = json!({ "type": "provider.transport", "message": "lost" }); + // `provider` stands for a field a newer server adds: the error passes through as it arrived. + let error = json!({ "type": "provider.transport", "message": "lost", "provider": { "id": "p" } }); let retry = durable_event( "session.retry.scheduled", json!({ "sessionID": ROOT, "assistantMessageID": "msg_1", "attempt": 2, "at": 1_000, "error": error }), ); let pending = run(&live(vec![retry.clone()]), &ctx(false)); assert_matches( - &updates(&pending.outputs), + &json!(pending.updates), &json!([{ "sessionUpdate": "session_info_update", "_meta": { "opencode/retry": { "attempt": 2, "nextRetryAt": "1970-01-01T00:00:01.000Z", "error": error } } }]), ); assert_eq!( @@ -409,12 +415,15 @@ fn reports_a_pending_retry_and_clears_it_when_the_next_step_starts() { let cleared = run( &live(vec![ retry, - durable_event("session.step.started", json!({ "sessionID": ROOT, "assistantMessageID": "msg_2" })), + durable_event( + "session.step.started", + json!({ "sessionID": ROOT, "assistantMessageID": "msg_2", "agent": "build", "model": { "providerID": "p", "id": "m" }, "started": 1 }), + ), ]), &ctx(false), ); assert_eq!( - updates(&cleared.outputs)[1], + cleared.updates[1], json!({ "sessionUpdate": "session_info_update", "_meta": { "opencode/retry": null } }) ); assert_eq!(translate::response(&cleared.state, ROOT, Terminal::Succeeded)["_meta"], json!({})); @@ -730,6 +739,7 @@ fn replay_rows() { messages .iter() .flat_map(|message| opencode_acp::replay::updates(message, "/workspace", &capabilities)) + .map(|(update, _)| json!(update)) .collect::>() ); assert!(crate::wire::matches(&actual, &expected), "{name}\n actual: {actual}\n expected: {expected}"); diff --git a/packages/cli-rs/crates/api-types/src/de.rs b/packages/cli-rs/crates/api-types/src/de.rs index 5088514e07f..d614f412c11 100644 --- a/packages/cli-rs/crates/api-types/src/de.rs +++ b/packages/cli-rs/crates/api-types/src/de.rs @@ -68,6 +68,21 @@ pub fn double_option<'de, T: Deserialize<'de>, D: Deserializer<'de>>( Option::::deserialize(deserializer).map(Some) } +/// Reads a union member's tag without keeping it: any string, as the `String` it replaces accepted. +pub fn tag<'de, D: Deserializer<'de>>(deserializer: D) -> Result<(), D::Error> { + struct TagVisitor; + impl Visitor<'_> for TagVisitor { + type Value = (); + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + fn visit_str(self, _: &str) -> Result<(), E> { + Ok(()) + } + } + deserializer.deserialize_str(TagVisitor) +} + /// The name serde_json's `RawValue` asks for. serde_json then hands over the value's text instead of /// parsing it; any other deserializer gives the value itself. const RAW_TOKEN: &str = "$serde_json::private::RawValue"; diff --git a/packages/cli-rs/crates/api-types/src/kinds.rs b/packages/cli-rs/crates/api-types/src/kinds.rs new file mode 100644 index 00000000000..fd78c55466a --- /dev/null +++ b/packages/cli-rs/crates/api-types/src/kinds.rs @@ -0,0 +1,50 @@ +//! Sets of event types, matched by [`EventKind`] rather than by name. + +use crate::types::{EventKind, V2Event}; + +const _: () = assert!(EventKind::COUNT <= 128, "a kind is a bit of a u128"); + +/// A set of [`V2Event`] types: a bit per kind, and the names asked for of the kinds whose events differ in their +/// `type` ([`EventKind::named`]: the `rpc.*` members and the types this client does not know). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct EventKinds { + bits: u128, + names: Vec, +} + +impl EventKinds { + /// The types `tags` name as on the wire (`session.deleted`). + pub fn named>(tags: impl IntoIterator) -> Self { + let mut kinds = Self::default(); + for tag in tags { + let kind = EventKind::from_tag(tag.as_ref()); + kinds.bits |= 1 << kind as u8; + if kind.named() { + kinds.names.push(tag.as_ref().to_owned()); + } + } + kinds + } + + /// Whether `event` is of a type in the set. + pub fn contains(&self, event: &V2Event) -> bool { + let kind = event.kind(); + self.bits >> kind as u8 & 1 == 1 && (!kind.named() || self.names.iter().any(|name| name == event.tag())) + } + + /// The indices of the kinds in the set, as `kind as usize`. + pub fn indices(&self) -> impl Iterator + '_ { + (0..EventKind::COUNT).filter(|index| self.bits >> index & 1 == 1) + } + + /// The names asked for of the [`EventKind::named`] kinds. + pub fn names(&self) -> &[String] { + &self.names + } +} + +impl From<[EventKind; N]> for EventKinds { + fn from(kinds: [EventKind; N]) -> Self { + Self { bits: kinds.iter().fold(0, |bits, kind| bits | 1 << *kind as u8), names: Vec::new() } + } +} diff --git a/packages/cli-rs/crates/api-types/src/lib.rs b/packages/cli-rs/crates/api-types/src/lib.rs index a410c527d4e..59a6c59eac9 100644 --- a/packages/cli-rs/crates/api-types/src/lib.rs +++ b/packages/cli-rs/crates/api-types/src/lib.rs @@ -5,7 +5,9 @@ pub mod call; pub mod client; pub mod de; pub mod js; +pub mod kinds; pub mod ser; +pub mod tool; #[macro_use] mod type_macros; pub mod types; diff --git a/packages/cli-rs/crates/api-types/src/tool.rs b/packages/cli-rs/crates/api-types/src/tool.rs new file mode 100644 index 00000000000..409580422d1 --- /dev/null +++ b/packages/cli-rs/crates/api-types/src/tool.rs @@ -0,0 +1,268 @@ +//! A tool call's kind, by its name, and borrowed views of its input, which each front end reads its own way. + +use indexmap::IndexMap; +use serde_json::{Map, Value}; + +use crate::SessionMessageAssistantToolState; +use crate::js::{js_string, truthy}; + +macro_rules! tool_kinds { + ($($kind:ident: $($name:literal)|+,)*) => { + /// What a tool is, by its name. Permission requests name their action the same way. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] + pub enum ToolKind { + $($kind,)* + #[default] + Other, + } + + impl ToolKind { + pub fn of(name: &str) -> Self { + match canonical_tool_name(name) { + $($($name)|+ => Self::$kind,)* + _ => Self::Other, + } + } + } + }; +} + +// `Context` is the Context7 tools, which ACP shows as searches. +tool_kinds! { + Invalid: "invalid", Shell: "shell", Read: "read", Write: "write", Edit: "edit", Patch: "patch", Batch: "batch", + Glob: "glob", Grep: "grep", List: "list", Lsp: "lsp", Subagent: "subagent", Todo: "todowrite", + Question: "question", WebFetch: "webfetch", WebSearch: "websearch", Skill: "skill", Execute: "execute", + Context: "context" | "context7_resolve_library_id" | "context7_get_library_docs", + ExternalDirectory: "external_directory", DoomLoop: "doom_loop", +} + +impl ToolKind { + /// [`Self::of`] the name with its ASCII letters lowercased. + pub fn of_ignore_ascii_case(name: &str) -> Self { + let mut lower = [0; 32]; + let Some(lower) = lower.get_mut(..name.len()) else { return Self::Other }; + lower.copy_from_slice(name.as_bytes()); + lower.make_ascii_lowercase(); + std::str::from_utf8(lower).map_or(Self::Other, Self::of) + } +} + +/// The current name of a tool whose persisted name is a legacy alias. +pub fn canonical_tool_name(name: &str) -> &str { + match name { + "bash" => "shell", + "task" => "subagent", + "apply_patch" => "patch", + _ => name, + } +} + +/// A tool call's input, borrowed from the part or from a JSON value. It is empty while the input streams as text. +#[derive(Debug, Clone, Copy, Default)] +pub struct ToolInput<'a>(Fields<'a>); + +#[derive(Debug, Clone, Copy, Default)] +enum Fields<'a> { + #[default] + Empty, + Typed(&'a IndexMap), + Json(&'a Map), +} + +impl<'a> ToolInput<'a> { + pub fn of(state: &'a SessionMessageAssistantToolState) -> Self { + Self(match state { + SessionMessageAssistantToolState::Streaming(_) => Fields::Empty, + SessionMessageAssistantToolState::Running(state) => Fields::Typed(&state.input), + SessionMessageAssistantToolState::Completed(state) => Fields::Typed(&state.input), + SessionMessageAssistantToolState::Error(state) => Fields::Typed(&state.input), + // A state this client does not know reads like a known one. + SessionMessageAssistantToolState::Unknown(state) => { + return state.get("input").map(Self::json).unwrap_or_default(); + } + }) + } + + pub fn map(map: &'a IndexMap) -> Self { + Self(Fields::Typed(map)) + } + + /// The input of a JSON object; any other value is an empty input. + pub fn json(value: &'a Value) -> Self { + Self(value.as_object().map_or(Fields::Empty, Fields::Json)) + } + + pub fn get(self, key: &str) -> Field<'a> { + Field(match self.0 { + Fields::Empty => None, + Fields::Typed(map) => map.get(key), + Fields::Json(map) => map.get(key), + }) + } + + /// The entries in wire order. + pub fn iter(self) -> impl Iterator { + let (typed, json) = match self.0 { + Fields::Empty => (None, None), + Fields::Typed(map) => (Some(map), None), + Fields::Json(map) => (None, Some(map)), + }; + typed.into_iter().flatten().chain(json.into_iter().flatten()) + } + + pub fn path(self) -> Field<'a> { + self.get("path") + } + + /// `normalizeInput`'s path: `path` when it is a string, else a non-empty `filePath`, which V1 sessions keep. + pub fn legacy_path(self) -> Field<'a> { + self.path().or_legacy(self.get("filePath")) + } + + /// The permission prompt's path: the first non-empty `path`, `filePath` or `filepath`. + pub fn any_path(self) -> Option<&'a str> { + ["path", "filePath", "filepath"].into_iter().find_map(|key| self.get(key).non_empty()) + } + + /// ACP's path: the string `path`, else the string `filePath`. + pub fn file_path(self) -> Option<&'a str> { + self.path().str().or(self.get("filePath").str()) + } +} + +/// One field of a tool's input. The front ends differ in what they accept, so each picks its own reading. +#[derive(Debug, Clone, Copy, Default)] +pub struct Field<'a>(Option<&'a Value>); + +impl<'a> Field<'a> { + pub fn value(self) -> Option<&'a Value> { + self.0 + } + + pub fn str(self) -> Option<&'a str> { + self.0.and_then(Value::as_str) + } + + /// The field when it is a string, else empty. + pub fn text(self) -> &'a str { + self.str().unwrap_or_default() + } + + pub fn non_empty(self) -> Option<&'a str> { + self.str().filter(|text| !text.is_empty()) + } + + /// JavaScript truthiness. + pub fn truthy(self) -> bool { + self.0.is_some_and(truthy) + } + + /// `${value ?? ""}` in a template literal. + pub fn js(self) -> String { + self.0.filter(|value| !value.is_null()).map(js_string).unwrap_or_default() + } + + pub fn array(self) -> &'a [Value] { + self.0.and_then(Value::as_array).map_or(&[], Vec::as_slice) + } + + /// `normalizeInput`: this field when it is a string, else a non-empty `legacy` one, else this field. + pub fn or_legacy(self, legacy: Self) -> Self { + if self.str().is_some() || legacy.non_empty().is_none() { self } else { legacy } + } +} + +macro_rules! input_views { + ($($view:ident { $($field:ident: $key:literal),* })*) => {$( + #[derive(Debug, Clone, Copy)] + pub struct $view<'a>(pub ToolInput<'a>); + + impl<'a> $view<'a> { + $(pub fn $field(self) -> Field<'a> { + self.0.get($key) + })* + } + )*}; +} + +// The fields of each tool's input. A file's path is on `ToolInput`, which every tool that names one shares. +input_views! { + ShellInput { command: "command", workdir: "workdir", cmd: "cmd", cwd: "cwd" } + ReadInput { offset: "offset", limit: "limit" } + WriteInput { content: "content" } + EditInput { patch_text: "patchText" } + PatchInput { patch_text: "patchText" } + SearchInput { pattern: "pattern" } + LspInput { operation: "operation", line: "line", character: "character" } + SubagentInput { agent: "agent", subagent_type: "subagent_type", description: "description", session_id: "sessionID", model: "model" } + TodoInput { todos: "todos" } + QuestionInput { questions: "questions" } + WebFetchInput { url: "url" } + WebSearchInput { query: "query" } + SkillInput { id: "id" } + BatchInput { tool_calls: "tool_calls" } + ExternalDirectoryInput { filepath: "filepath", description: "description", command: "command", parent_dir: "parentDir" } +} + +impl<'a> SubagentInput<'a> { + /// `normalizeInput`'s agent: `agent` when it is a string, else a non-empty `subagent_type`. + pub fn legacy_agent(self) -> Field<'a> { + self.agent().or_legacy(self.subagent_type()) + } +} + +impl TodoInput<'_> { + pub fn items(self) -> Vec { + parse_todos(self.todos().value().unwrap_or(&Value::Null)) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TodoStatus { + Pending, + InProgress, + Completed, + Cancelled, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Todo { + pub content: String, + pub status: TodoStatus, +} + +/// The items of a `todowrite` input; an unknown status reads as pending. +pub fn parse_todos(value: &Value) -> Vec { + let Some(items) = value.as_array() else { return Vec::new() }; + items + .iter() + .filter_map(|item| { + let content = item.as_object()?.get("content")?.as_str().filter(|content| !content.is_empty())?; + let status = match item.get("status").and_then(Value::as_str) { + Some("in_progress") => TodoStatus::InProgress, + Some("completed") => TodoStatus::Completed, + Some("cancelled") => TodoStatus::Cancelled, + _ => TodoStatus::Pending, + }; + Some(Todo { content: content.to_owned(), status }) + }) + .collect() +} + +/// Read's model content is a JSON page envelope; this unwraps the human-facing text. +pub fn read_display_text(text: &str) -> Option { + if !text.starts_with('{') { + return None; + } + let envelope = serde_json::from_str::>(text).unwrap_or_default(); + if let Some(content) = envelope.get("content").and_then(Value::as_str) { + let page = envelope.get("type").and_then(Value::as_str) == Some("text-page"); + if page || envelope.get("encoding").and_then(Value::as_str) == Some("utf8") { + return Some(content.to_owned()); + } + } + let entries = envelope.get("entries")?.as_array()?; + let lines: Vec<_> = + entries.iter().filter_map(|entry| entry.as_str().or_else(|| entry.get("path")?.as_str())).collect(); + Some(lines.join("\n")) +} diff --git a/packages/cli-rs/crates/api-types/src/type_macros.rs b/packages/cli-rs/crates/api-types/src/type_macros.rs index c49cb0d4d76..4d4dbedc80d 100644 --- a/packages/cli-rs/crates/api-types/src/type_macros.rs +++ b/packages/cli-rs/crates/api-types/src/type_macros.rs @@ -44,6 +44,38 @@ macro_rules! string_type { }; } +macro_rules! tags { + ($($name:ident = $wire:literal,)+) => {$( + #[derive(Clone, Copy, PartialEq, Eq, Hash, Default)] + pub struct $name; + + impl $name { + pub const fn as_str(&self) -> &'static str { + $wire + } + } + + // As the `String` it replaces, so a member's `Debug` text stays the same. + impl std::fmt::Debug for $name { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt($wire, f) + } + } + + impl serde::Serialize for $name { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str($wire) + } + } + + impl<'de> serde::Deserialize<'de> for $name { + fn deserialize>(deserializer: D) -> Result { + crate::de::tag(deserializer).map(|()| Self) + } + } + )+}; +} + macro_rules! literal_enum { ($(#[$attr:meta])* $name:ident { $($variant:ident => $wire:literal),+ $(,)? }) => { $(#[$attr])* diff --git a/packages/cli-rs/crates/api-types/src/types.rs b/packages/cli-rs/crates/api-types/src/types.rs index 19a8c618224..d33e0b14330 100644 --- a/packages/cli-rs/crates/api-types/src/types.rs +++ b/packages/cli-rs/crates/api-types/src/types.rs @@ -139,12 +139,12 @@ impl ProviderSettingsTimeout { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ProviderCompactionSummary { - pub r#type: String, + pub r#type: tag::Summary, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ProviderCompactionNative { - pub r#type: String, + pub r#type: tag::Native, } /// `Provider.Compaction`, tagged by `type`. @@ -164,7 +164,7 @@ impl<'de> Deserialize<'de> for ProviderCompaction { } impl ProviderCompaction { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("summary") => raw.variant().map(Self::Summary), Some("native") => raw.variant().map(Self::Native), @@ -362,12 +362,12 @@ string_type!(PluginID, "`Plugin.ID`"); #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct PluginSourceBuiltin { - pub r#type: String, + pub r#type: tag::Builtin, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct PluginSourcePackage { - pub r#type: String, + pub r#type: tag::Package, pub target: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option, @@ -379,13 +379,13 @@ pub struct PluginSourcePackage { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct PluginSourceLocal { - pub r#type: String, + pub r#type: tag::Local, pub path: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct PluginSourceSdk { - pub r#type: String, + pub r#type: tag::Sdk, } /// `Plugin.Source`, tagged by `type`. @@ -407,7 +407,7 @@ impl<'de> Deserialize<'de> for PluginSource { } impl PluginSource { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("builtin") => raw.variant().map(Self::Builtin), Some("package") => raw.variant().map(Self::Package), @@ -445,12 +445,12 @@ pub struct PluginFeatures { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct PluginStateActive { - pub status: String, + pub status: tag::Active, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct PluginStateFailed { - pub status: String, + pub status: tag::Failed, pub error: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub r#ref: Option, @@ -473,7 +473,7 @@ impl<'de> Deserialize<'de> for PluginState { } impl PluginState { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("status").as_str() { Some("active") => raw.variant().map(Self::Active), Some("failed") => raw.variant().map(Self::Failed), @@ -579,14 +579,14 @@ string_type!(SessionMessageID, "`Session.Message.ID`"); #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionForkBoundaryBefore { - pub r#type: String, + pub r#type: tag::Before, #[serde(rename = "messageID")] pub message_id: SessionMessageID, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionForkBoundaryThrough { - pub r#type: String, + pub r#type: tag::Through, #[serde(rename = "messageID")] pub message_id: SessionMessageID, } @@ -608,7 +608,7 @@ impl<'de> Deserialize<'de> for SessionForkBoundary { } impl SessionForkBoundary { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("before") => raw.variant().map(Self::Before), Some("through") => raw.variant().map(Self::Through), @@ -866,12 +866,12 @@ pub struct SessionMoveInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct PromptFileSourceInline { - pub r#type: String, + pub r#type: tag::Inline, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct PromptFileSourceUri { - pub r#type: String, + pub r#type: tag::Uri, pub uri: String, } @@ -892,7 +892,7 @@ impl<'de> Deserialize<'de> for PromptFileSource { } impl PromptFileSource { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("inline") => raw.variant().map(Self::Inline), Some("uri") => raw.variant().map(Self::Uri), @@ -1016,7 +1016,7 @@ pub struct SessionInboxUser { #[serde(rename = "sessionID")] pub session_id: SessionID, pub time: SessionInboxUserTime, - pub r#type: String, + pub r#type: tag::User, pub payload: SessionInboxUserPayload, pub delivery: SessionInboxDelivery, } @@ -1063,7 +1063,7 @@ pub struct SessionInboxSynthetic { #[serde(rename = "sessionID")] pub session_id: SessionID, pub time: SessionInboxUserTime, - pub r#type: String, + pub r#type: tag::Synthetic, pub payload: SessionInboxSyntheticPayload, pub delivery: SessionInboxDelivery, } @@ -1096,7 +1096,7 @@ pub struct SessionInboxCompaction { #[serde(rename = "sessionID")] pub session_id: SessionID, pub time: SessionInboxUserTime, - pub r#type: String, + pub r#type: tag::Compaction, pub payload: SessionInboxCompactionPayload, pub delivery: SessionInboxDelivery, } @@ -1139,7 +1139,7 @@ pub struct SessionMessageAgentSelected { #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionInboxUserTime, - pub r#type: String, + pub r#type: tag::AgentSwitched, pub agent: AgentID, #[serde(default, skip_serializing_if = "Option::is_none")] pub previous: Option, @@ -1151,7 +1151,7 @@ pub struct SessionMessageModelSelected { #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionInboxUserTime, - pub r#type: String, + pub r#type: tag::ModelSwitched, pub model: ModelRef, #[serde(default, skip_serializing_if = "Option::is_none")] pub previous: Option, @@ -1172,7 +1172,7 @@ pub struct SessionMessageLocationSwitched { #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionInboxUserTime, - pub r#type: String, + pub r#type: tag::LocationSwitched, #[serde(rename = "projectID", default, skip_serializing_if = "Option::is_none")] pub project_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1195,7 +1195,7 @@ pub struct SessionMessageUser { pub agents: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub skills: Option>, - pub r#type: String, + pub r#type: tag::User, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] @@ -1207,7 +1207,7 @@ pub struct SessionMessageSynthetic { pub text: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, - pub r#type: String, + pub r#type: tag::Synthetic, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] @@ -1216,7 +1216,7 @@ pub struct SessionMessageSystem { #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionInboxUserTime, - pub r#type: String, + pub r#type: tag::System, pub text: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option, @@ -1228,7 +1228,7 @@ pub struct SessionMessageSkill { #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionInboxUserTime, - pub r#type: String, + pub r#type: tag::Skill, pub skill: SkillID, pub name: SkillName, pub text: String, @@ -1294,7 +1294,7 @@ pub struct SessionMessageShell { #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionMessageShellTime, - pub r#type: String, + pub r#type: tag::Shell, #[serde(rename = "shellID")] pub shell_id: ShellID, pub command: String, @@ -1327,7 +1327,7 @@ pub type SessionMessageNative = IndexMap; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionMessageAssistantText { - pub r#type: String, + pub r#type: tag::Text, pub text: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub native: Option, @@ -1335,7 +1335,7 @@ pub struct SessionMessageAssistantText { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionMessageAssistantReasoning { - pub r#type: String, + pub r#type: tag::Reasoning, pub text: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub native: Option, @@ -1345,26 +1345,26 @@ pub struct SessionMessageAssistantReasoning { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionMessageToolStateStreaming { - pub status: String, + pub status: tag::Streaming, pub input: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionMessageToolStateRunning { - pub status: String, + pub status: tag::Running, pub input: IndexMap, pub metadata: IndexMap, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ToolTextContent { - pub r#type: String, + pub r#type: tag::Text, pub text: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ToolFileContent { - pub r#type: String, + pub r#type: tag::File, pub uri: String, pub mime: String, #[serde(default, deserialize_with = "crate::de::double_option", skip_serializing_if = "Option::is_none")] @@ -1388,7 +1388,7 @@ impl<'de> Deserialize<'de> for ToolContent { } impl ToolContent { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("text") => raw.variant().map(Self::Text), Some("file") => raw.variant().map(Self::File), @@ -1410,7 +1410,7 @@ impl ToolContent { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionMessageToolStateCompleted { - pub status: String, + pub status: tag::Completed, pub input: IndexMap, pub content: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1436,7 +1436,7 @@ pub struct SessionStructuredError { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionMessageToolStateError { - pub status: String, + pub status: tag::Error, pub input: IndexMap, pub error: SessionStructuredError, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1463,7 +1463,7 @@ impl<'de> Deserialize<'de> for SessionMessageAssistantToolState { } impl SessionMessageAssistantToolState { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("status").as_str() { Some("streaming") => raw.variant().map(Self::Streaming), Some("running") => raw.variant().map(Self::Running), @@ -1499,7 +1499,7 @@ pub struct SessionMessageAssistantToolTime { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SessionMessageAssistantTool { - pub r#type: String, + pub r#type: tag::Tool, pub id: String, pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1527,7 +1527,7 @@ impl<'de> Deserialize<'de> for SessionMessageAssistantContentItem { } impl SessionMessageAssistantContentItem { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("text") => raw.variant().map(Self::Text), Some("reasoning") => raw.variant().map(Self::Reasoning), @@ -1603,7 +1603,7 @@ pub struct SessionMessageAssistant { #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionMessageAssistantTime, - pub r#type: String, + pub r#type: tag::Assistant, pub agent: AgentID, pub model: ModelRef, pub content: Vec, @@ -1634,24 +1634,24 @@ SessionMessageCompactionRunningReason { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SessionMessageCompactionRunning { - pub r#type: String, + pub r#type: tag::Compaction, pub id: SessionMessageID, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionInboxUserTime, - pub status: String, + pub status: tag::Running, pub reason: SessionMessageCompactionRunningReason, pub summary: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SessionMessageCompactionCompleted { - pub r#type: String, + pub r#type: tag::Compaction, pub id: SessionMessageID, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionInboxUserTime, - pub status: String, + pub status: tag::Completed, pub reason: SessionMessageCompactionRunningReason, #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option, @@ -1666,12 +1666,12 @@ pub struct SessionMessageCompactionCompleted { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SessionMessageCompactionFailed { - pub r#type: String, + pub r#type: tag::Compaction, pub id: SessionMessageID, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionInboxUserTime, - pub status: String, + pub status: tag::Failed, pub reason: SessionMessageCompactionRunningReason, pub error: SessionStructuredError, #[serde(default, serialize_with = "crate::ser::option_number", skip_serializing_if = "Option::is_none")] @@ -1698,7 +1698,7 @@ impl<'de> Deserialize<'de> for SessionMessageCompaction { } impl SessionMessageCompaction { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("status").as_str() { Some("running") => raw.variant().map(Self::Running), Some("completed") => raw.variant().map(Self::Completed), @@ -1815,7 +1815,7 @@ pub struct SessionMessageIdle { #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, pub time: SessionInboxUserTime, - pub r#type: String, + pub r#type: tag::Idle, pub outcome: SessionInfoOutcome, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option, @@ -1847,7 +1847,7 @@ impl<'de> Deserialize<'de> for SessionMessageInfo { } impl SessionMessageInfo { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("agent-switched") => raw.variant().map(Self::AgentSwitched), Some("model-switched") => raw.variant().map(Self::ModelSwitched), @@ -2157,7 +2157,7 @@ pub struct SessionInboxMove { #[serde(rename = "sessionID")] pub session_id: SessionID, pub time: SessionInboxUserTime, - pub r#type: String, + pub r#type: tag::Move, pub delivery: SessionInboxDelivery, pub payload: SessionInboxMovePayload, } @@ -2181,7 +2181,7 @@ impl<'de> Deserialize<'de> for SessionInboxInfo { } impl SessionInboxInfo { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("user") => raw.variant().map(Self::User), Some("synthetic") => raw.variant().map(Self::Synthetic), @@ -2412,7 +2412,7 @@ pub struct FormStringField { pub hidden: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option>, - pub r#type: String, + pub r#type: tag::String, #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option, #[serde(rename = "minLength", default, skip_serializing_if = "Option::is_none")] @@ -2444,7 +2444,7 @@ pub struct FormNumberField { pub hidden: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option>, - pub r#type: String, + pub r#type: tag::Number, #[serde(default, skip_serializing_if = "Option::is_none")] pub minimum: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -2466,7 +2466,7 @@ pub struct FormIntegerField { pub hidden: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option>, - pub r#type: String, + pub r#type: tag::Integer, #[serde(default, skip_serializing_if = "Option::is_none")] pub minimum: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -2488,7 +2488,7 @@ pub struct FormBooleanField { pub hidden: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option>, - pub r#type: String, + pub r#type: tag::Boolean, #[serde(default, skip_serializing_if = "Option::is_none")] pub default: Option, } @@ -2506,7 +2506,7 @@ pub struct FormMultiselectField { pub hidden: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option>, - pub r#type: String, + pub r#type: tag::Multiselect, pub options: Vec, #[serde(rename = "minItems", default, skip_serializing_if = "Option::is_none")] pub min_items: Option, @@ -2521,7 +2521,7 @@ pub struct FormMultiselectField { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct FormExternalField { pub key: String, - pub r#type: String, + pub r#type: tag::External, pub url: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub title: Option, @@ -2550,7 +2550,7 @@ impl<'de> Deserialize<'de> for FormField { } impl FormField { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("string") => raw.variant().map(Self::String), Some("number") => raw.variant().map(Self::Number), @@ -2719,7 +2719,7 @@ pub struct SessionFormGetInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct FormStatePending { - pub status: String, + pub status: tag::Pending, } /// `Form.Value` @@ -2763,13 +2763,13 @@ pub type FormAnswer = IndexMap; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct FormStateAnswered { - pub status: String, + pub status: tag::Answered, pub answer: FormAnswer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct FormStateCancelled { - pub status: String, + pub status: tag::Cancelled, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, } @@ -2792,7 +2792,7 @@ impl<'de> Deserialize<'de> for FormState { } impl FormState { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("status").as_str() { Some("pending") => raw.variant().map(Self::Pending), Some("answered") => raw.variant().map(Self::Answered), @@ -2887,7 +2887,7 @@ pub struct SessionStatsInfoRange { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionStatsToolsNone { - pub mode: String, + pub mode: tag::None, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] @@ -2900,7 +2900,7 @@ pub struct SessionStatsToolTotals { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionStatsToolsSummary { - pub mode: String, + pub mode: tag::Summary, pub totals: SessionStatsToolTotals, } @@ -2922,7 +2922,7 @@ pub struct SessionStatsToolUsage { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionStatsToolsDetail { - pub mode: String, + pub mode: tag::Detail, pub totals: SessionStatsToolTotals, pub usage: Vec, } @@ -2945,7 +2945,7 @@ impl<'de> Deserialize<'de> for SessionStatsTools { } impl SessionStatsTools { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("mode").as_str() { Some("none") => raw.variant().map(Self::None), Some("summary") => raw.variant().map(Self::Summary), @@ -3183,7 +3183,7 @@ pub struct SessionCreated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionCreated, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3206,7 +3206,7 @@ pub struct SessionAgentSelected { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionAgentSelected, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3229,7 +3229,7 @@ pub struct SessionModelSelected { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionModelSelected, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3254,7 +3254,7 @@ pub struct SessionMoved { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionMoved, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3275,7 +3275,7 @@ pub struct SessionRenamed { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionRenamed, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3296,7 +3296,7 @@ pub struct SessionMetadataUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionMetadataUpdated, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3317,7 +3317,7 @@ pub struct SessionPermissions { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionPermissions, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3339,7 +3339,7 @@ pub struct SessionViewed { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionViewed, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3359,7 +3359,7 @@ pub struct SessionArchived { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionArchived, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3373,7 +3373,7 @@ pub struct SessionUnarchived { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionUnarchived, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3395,7 +3395,7 @@ pub struct SessionDeleted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionDeleted, pub durable: SessionDeletedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3434,7 +3434,7 @@ pub struct SessionForked { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionForked, pub durable: SessionDeletedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3456,7 +3456,7 @@ pub struct SessionInboxDelivered { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionInboxDelivered, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3465,21 +3465,21 @@ pub struct SessionInboxDelivered { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SessionInboxItemUser { - pub r#type: String, + pub r#type: tag::User, pub payload: SessionInboxUserPayload, pub delivery: SessionInboxDelivery, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SessionInboxItemSynthetic { - pub r#type: String, + pub r#type: tag::Synthetic, pub payload: SessionInboxSyntheticPayload, pub delivery: SessionInboxDelivery, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SessionInboxItemCompaction { - pub r#type: String, + pub r#type: tag::Compaction, pub payload: SessionInboxCompactionPayload, pub delivery: SessionInboxDelivery, } @@ -3495,7 +3495,7 @@ pub struct SessionInboxMovePayload1 { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SessionInboxItemMove { - pub r#type: String, + pub r#type: tag::Move, pub payload: SessionInboxMovePayload1, pub delivery: SessionInboxDelivery, } @@ -3519,7 +3519,7 @@ impl<'de> Deserialize<'de> for SessionInboxItem { } impl SessionInboxItem { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("user") => raw.variant().map(Self::User), Some("synthetic") => raw.variant().map(Self::Synthetic), @@ -3570,7 +3570,7 @@ pub struct SessionInboxEnqueued { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionInboxEnqueued, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3584,7 +3584,7 @@ pub struct SessionInboxCancelled { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionInboxCancelled, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3607,7 +3607,7 @@ pub struct SessionInboxDeliveryChanged { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionInboxDeliveryChanged, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3621,7 +3621,7 @@ pub struct SessionExecutionStarted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionExecutionStarted, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3635,7 +3635,7 @@ pub struct SessionExecutionSucceeded { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionExecutionSucceeded, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3656,7 +3656,7 @@ pub struct SessionExecutionFailed { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionExecutionFailed, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3686,7 +3686,7 @@ pub struct SessionExecutionInterrupted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionExecutionInterrupted, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3709,7 +3709,7 @@ pub struct SessionInstructionsUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionInstructionsUpdated, pub durable: SessionDeletedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3734,7 +3734,7 @@ pub struct SessionSynthetic { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionSynthetic, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3757,7 +3757,7 @@ pub struct SessionSkillActivated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionSkillActivated, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3804,7 +3804,7 @@ pub struct SessionShellStarted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionShellStarted, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3826,7 +3826,7 @@ pub struct SessionShellEnded { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionShellEnded, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3853,7 +3853,7 @@ pub struct SessionStepStarted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionStepStarted, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3875,7 +3875,7 @@ pub struct SessionStepFirstToken { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionStepFirstToken, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3889,7 +3889,7 @@ pub struct SessionStepStreamed { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionStepStreamed, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3923,7 +3923,7 @@ pub struct SessionStepEnded { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionStepEnded, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3960,7 +3960,7 @@ pub struct SessionStepFailed { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionStepFailed, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -3983,7 +3983,7 @@ pub struct SessionTextStarted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionTextStarted, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4009,7 +4009,7 @@ pub struct SessionTextEnded { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionTextEnded, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4034,7 +4034,7 @@ pub struct SessionReasoningStarted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionReasoningStarted, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4048,7 +4048,7 @@ pub struct SessionReasoningEnded { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionReasoningEnded, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4072,7 +4072,7 @@ pub struct SessionToolInputStarted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionToolInputStarted, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4096,7 +4096,7 @@ pub struct SessionToolInputEnded { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionToolInputEnded, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4123,7 +4123,7 @@ pub struct SessionToolCalled { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionToolCalled, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4152,7 +4152,7 @@ pub struct SessionToolSuccess { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionToolSuccess, pub durable: SessionDeletedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4183,7 +4183,7 @@ pub struct SessionToolFailed { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionToolFailed, pub durable: SessionDeletedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4208,7 +4208,7 @@ pub struct SessionRetryScheduled { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionRetryScheduled, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4231,7 +4231,7 @@ pub struct SessionCompactionStarted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionCompactionStarted, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4261,7 +4261,7 @@ pub struct SessionCompactionEnded { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionCompactionEnded, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4289,7 +4289,7 @@ pub struct SessionCompactionFailed { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionCompactionFailed, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4310,7 +4310,7 @@ pub struct SessionRevertStaged { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionRevertStaged, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4324,7 +4324,7 @@ pub struct SessionRevertCleared { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionRevertCleared, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4345,7 +4345,7 @@ pub struct SessionRevertCommitted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionRevertCommitted, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4377,7 +4377,7 @@ pub struct SessionUsageRecorded { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionUsageRecorded, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4402,7 +4402,7 @@ impl<'de> Deserialize<'de> for SessionMessageAssistantContentEncoded { } impl SessionMessageAssistantContentEncoded { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("text") => raw.variant().map(Self::Text), Some("reasoning") => raw.variant().map(Self::Reasoning), @@ -4459,7 +4459,7 @@ pub struct SessionMessageContentUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionMessageContentUpdated, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -4529,7 +4529,7 @@ impl<'de> Deserialize<'de> for SessionEventDurable { } impl SessionEventDurable { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("session.created") => raw.variant().map(Self::SessionCreated), Some("session.agent.selected") => raw.variant().map(Self::SessionAgentSelected), @@ -5091,7 +5091,7 @@ impl SessionEventDurable { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct EventLogSynced { - pub r#type: String, + pub r#type: tag::LogSynced, #[serde(rename = "aggregateID")] pub aggregate_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -5115,7 +5115,7 @@ impl<'de> Deserialize<'de> for SessionLogItem { } impl SessionLogItem { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("session.created") | Some("session.agent.selected") @@ -5543,7 +5543,7 @@ string_type!(GenerateVideoID, "`Generate.VideoID`"); #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GenerateVideoRunning { pub id: GenerateVideoID, - pub status: String, + pub status: tag::Running, } /// Output of `Client::experimental_generate_video_create`. @@ -5568,7 +5568,7 @@ pub struct BlobInfo { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GenerateVideoCompleted { pub id: GenerateVideoID, - pub status: String, + pub status: tag::Completed, pub blobs: Vec, } @@ -5585,7 +5585,7 @@ GenerateVideoErrorReason { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GenerateVideoError { pub id: GenerateVideoID, - pub status: String, + pub status: tag::Error, pub error: String, pub reason: GenerateVideoErrorReason, } @@ -5608,7 +5608,7 @@ impl<'de> Deserialize<'de> for GenerateVideoJob { } impl GenerateVideoJob { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("status").as_str() { Some("running") => raw.variant().map(Self::Running), Some("completed") => raw.variant().map(Self::Completed), @@ -5645,19 +5645,19 @@ pub type ExperimentalGenerateVideoGetOutput = GenerateVideoJob; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GenerateDecisionTextPart { - pub r#type: String, + pub r#type: tag::Text, pub text: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GenerateDecisionJsonPart { - pub r#type: String, + pub r#type: tag::Json, pub value: serde_json::Value, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GenerateDecisionFilePart { - pub r#type: String, + pub r#type: tag::File, pub data: PromptBase64, pub mime: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -5682,7 +5682,7 @@ impl<'de> Deserialize<'de> for GenerateDecisionPart { } impl GenerateDecisionPart { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("text") => raw.variant().map(Self::Text), Some("json") => raw.variant().map(Self::Json), @@ -5714,7 +5714,7 @@ pub struct GeneratePredicateQuestionCriteria { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GeneratePredicateQuestion { - pub r#type: String, + pub r#type: tag::Predicate, pub name: String, pub instructions: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -5758,7 +5758,7 @@ pub struct GenerateChoiceQuestionChoicesItem { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GenerateChoiceQuestion { - pub r#type: String, + pub r#type: tag::Choice, pub name: String, pub instructions: String, pub choices: Vec, @@ -5773,7 +5773,7 @@ pub struct GenerateScoreQuestionLevelsItem { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GenerateScoreQuestion { - pub r#type: String, + pub r#type: tag::Score, pub name: String, pub instructions: String, pub levels: Vec, @@ -5797,7 +5797,7 @@ impl<'de> Deserialize<'de> for GenerateDecisionQuestion { } impl GenerateDecisionQuestion { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("predicate") => raw.variant().map(Self::Predicate), Some("choice") => raw.variant().map(Self::Choice), @@ -5849,7 +5849,7 @@ pub struct ExperimentalGenerateDecisionsInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GeneratePredicateAnswer { - pub r#type: String, + pub r#type: tag::Predicate, pub name: String, #[serde(serialize_with = "crate::ser::number")] pub probability: f64, @@ -5864,7 +5864,7 @@ pub struct GenerateChoiceAnswerProbabilitiesItem { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GenerateChoiceAnswer { - pub r#type: String, + pub r#type: tag::Choice, pub name: String, pub choice: GenerateChoiceValue, pub probabilities: Vec, @@ -5882,7 +5882,7 @@ pub struct GenerateScoreAnswerProbabilitiesItem { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GenerateScoreAnswer { - pub r#type: String, + pub r#type: tag::Score, pub name: String, #[serde(serialize_with = "crate::ser::number")] pub score: f64, @@ -5893,7 +5893,7 @@ pub struct GenerateScoreAnswer { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct GenerateErrorAnswer { - pub r#type: String, + pub r#type: tag::Error, pub name: String, pub reason: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -5919,7 +5919,7 @@ impl<'de> Deserialize<'de> for GenerateDecisionAnswer { } impl GenerateDecisionAnswer { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("predicate") => raw.variant().map(Self::Predicate), Some("choice") => raw.variant().map(Self::Choice), @@ -6004,7 +6004,7 @@ pub struct ExperimentalVoiceModelsOutput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct VoiceWebRTCTransportInput { - pub r#type: String, + pub r#type: tag::Webrtc, pub sdp: String, #[serde(default, serialize_with = "crate::ser::option_number", skip_serializing_if = "Option::is_none")] pub dcid: Option, @@ -6012,7 +6012,7 @@ pub struct VoiceWebRTCTransportInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct VoiceWebSocketTransportInput { - pub r#type: String, + pub r#type: tag::Websocket, } /// `VoiceTransportInput`, tagged by `type`. @@ -6032,7 +6032,7 @@ impl<'de> Deserialize<'de> for VoiceTransportInput { } impl VoiceTransportInput { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("webrtc") => raw.variant().map(Self::Webrtc), Some("websocket") => raw.variant().map(Self::Websocket), @@ -6062,13 +6062,13 @@ pub struct ExperimentalVoiceSessionInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct VoiceWebRTCTransport { - pub r#type: String, + pub r#type: tag::Webrtc, pub sdp: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct VoiceWebSocketTransport { - pub r#type: String, + pub r#type: tag::Websocket, pub url: String, pub token: String, #[serde(rename = "expiresAt", serialize_with = "crate::ser::number")] @@ -6092,7 +6092,7 @@ impl<'de> Deserialize<'de> for VoiceTransport { } impl VoiceTransport { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("webrtc") => raw.variant().map(Self::Webrtc), Some("websocket") => raw.variant().map(Self::Websocket), @@ -6205,7 +6205,7 @@ string_type!(IntegrationMethodID, "`Integration.MethodID`"); #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct IntegrationOAuthMethod { pub id: IntegrationMethodID, - pub r#type: String, + pub r#type: tag::Oauth, pub label: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub form: Option, @@ -6214,14 +6214,14 @@ pub struct IntegrationOAuthMethod { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct IntegrationCommandMethod { pub id: IntegrationMethodID, - pub r#type: String, + pub r#type: tag::Command, pub label: String, pub command: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct IntegrationKeyMethod { - pub r#type: String, + pub r#type: tag::Key, #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -6231,7 +6231,7 @@ pub struct IntegrationKeyMethod { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct IntegrationExternalMethod { pub id: IntegrationMethodID, - pub r#type: String, + pub r#type: tag::External, pub label: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub form: Option, @@ -6239,7 +6239,7 @@ pub struct IntegrationExternalMethod { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct IntegrationEnvMethod { - pub r#type: String, + pub r#type: tag::Env, pub names: Vec, } @@ -6263,7 +6263,7 @@ impl<'de> Deserialize<'de> for IntegrationMethod { } impl IntegrationMethod { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("oauth") => raw.variant().map(Self::Oauth), Some("command") => raw.variant().map(Self::Command), @@ -6329,7 +6329,7 @@ pub struct ConnectionStatus { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ConnectionCredentialInfo { - pub r#type: String, + pub r#type: tag::Credential, pub id: CredentialID, pub label: String, pub method: ConnectionCredentialInfoMethod, @@ -6339,7 +6339,7 @@ pub struct ConnectionCredentialInfo { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ConnectionEnvInfo { - pub r#type: String, + pub r#type: tag::Env, pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option, @@ -6362,7 +6362,7 @@ impl<'de> Deserialize<'de> for ConnectionInfo { } impl ConnectionInfo { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("credential") => raw.variant().map(Self::Credential), Some("env") => raw.variant().map(Self::Env), @@ -6495,26 +6495,26 @@ pub struct IntegrationOauthStatusInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct IntegrationAttemptStatusPending { - pub status: String, + pub status: tag::Pending, pub time: IntegrationAttemptTime, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct IntegrationAttemptStatusComplete { - pub status: String, + pub status: tag::Complete, pub time: IntegrationAttemptTime, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct IntegrationAttemptStatusFailed { - pub status: String, + pub status: tag::Failed, pub message: String, pub time: IntegrationAttemptTime, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct IntegrationAttemptStatusExpired { - pub status: String, + pub status: tag::Expired, pub time: IntegrationAttemptTime, } @@ -6537,7 +6537,7 @@ impl<'de> Deserialize<'de> for IntegrationAttemptStatus { } impl IntegrationAttemptStatus { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("status").as_str() { Some("pending") => raw.variant().map(Self::Pending), Some("complete") => raw.variant().map(Self::Complete), @@ -6659,7 +6659,7 @@ pub struct IntegrationCommandAttemptStatusPendingTime { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct IntegrationCommandAttemptStatusPending { - pub status: String, + pub status: tag::Pending, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, pub time: IntegrationCommandAttemptStatusPendingTime, @@ -6667,20 +6667,20 @@ pub struct IntegrationCommandAttemptStatusPending { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct IntegrationCommandAttemptStatusComplete { - pub status: String, + pub status: tag::Complete, pub time: IntegrationCommandAttemptStatusPendingTime, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct IntegrationCommandAttemptStatusFailed { - pub status: String, + pub status: tag::Failed, pub message: String, pub time: IntegrationCommandAttemptStatusPendingTime, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct IntegrationCommandAttemptStatusExpired { - pub status: String, + pub status: tag::Expired, pub time: IntegrationCommandAttemptStatusPendingTime, } @@ -6703,7 +6703,7 @@ impl<'de> Deserialize<'de> for IntegrationCommandAttemptStatus { } impl IntegrationCommandAttemptStatus { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("status").as_str() { Some("pending") => raw.variant().map(Self::Pending), Some("complete") => raw.variant().map(Self::Complete), @@ -6789,28 +6789,28 @@ pub struct McpListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct McpStatusConnected { - pub status: String, + pub status: tag::Connected, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct McpStatusPending { - pub status: String, + pub status: tag::Pending, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct McpStatusDisabled { - pub status: String, + pub status: tag::Disabled, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct McpStatusFailed { - pub status: String, + pub status: tag::Failed, pub error: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct McpStatusNeedsAuth { - pub status: String, + pub status: tag::NeedsAuth, pub error: String, } @@ -6833,7 +6833,7 @@ impl<'de> Deserialize<'de> for McpServerStatus { } impl McpServerStatus { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("status").as_str() { Some("connected") => raw.variant().map(Self::Connected), Some("pending") => raw.variant().map(Self::Pending), @@ -6946,7 +6946,7 @@ McpProtocol { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ExperimentalMcpAddInputConfigLocal { - pub r#type: String, + pub r#type: tag::Local, pub command: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub cwd: Option, @@ -7009,7 +7009,7 @@ impl ExperimentalMcpAddInputConfigRemoteOauth { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ExperimentalMcpAddInputConfigRemote { - pub r#type: String, + pub r#type: tag::Remote, pub url: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub headers: Option>, @@ -7043,7 +7043,7 @@ impl<'de> Deserialize<'de> for ExperimentalMcpAddInputConfig { } impl ExperimentalMcpAddInputConfig { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("local") => raw.variant().map(Self::Local), Some("remote") => raw.variant().map(Self::Remote), @@ -7159,7 +7159,7 @@ pub struct ExperimentalMcpClientTokenOutput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct CredentialOAuth { - pub r#type: String, + pub r#type: tag::Oauth, #[serde(rename = "methodID")] pub method_id: IntegrationMethodID, pub refresh: String, @@ -7171,7 +7171,7 @@ pub struct CredentialOAuth { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct CredentialKey { - pub r#type: String, + pub r#type: tag::Key, pub key: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, @@ -7179,7 +7179,7 @@ pub struct CredentialKey { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct CredentialExternal { - pub r#type: String, + pub r#type: tag::External, #[serde(rename = "methodID")] pub method_id: IntegrationMethodID, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -7204,7 +7204,7 @@ impl<'de> Deserialize<'de> for CredentialValue { } impl CredentialValue { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("oauth") => raw.variant().map(Self::Oauth), Some("key") => raw.variant().map(Self::Key), @@ -7666,7 +7666,7 @@ pub struct LocationShutdown { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::LocationShutdown, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: LocationShutdownData, @@ -7682,7 +7682,7 @@ pub struct ModelsDevRefreshed { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ModelsDevRefreshed, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ModelsDevRefreshedData, @@ -7703,7 +7703,7 @@ pub struct CredentialUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::CredentialUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: CredentialUpdatedData, @@ -7724,7 +7724,7 @@ pub struct CredentialSwitched { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::CredentialSwitched, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: CredentialSwitchedData, @@ -7740,7 +7740,7 @@ pub struct IntegrationUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::IntegrationUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: IntegrationUpdatedData, @@ -7756,7 +7756,7 @@ pub struct ProviderUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ProviderUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ProviderUpdatedData, @@ -7772,7 +7772,7 @@ pub struct ModelUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ModelUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ModelUpdatedData, @@ -7788,7 +7788,7 @@ pub struct AgentUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::AgentUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: AgentUpdatedData, @@ -7810,7 +7810,7 @@ pub struct SessionUsageUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionUsageUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: SessionUsageUpdatedData, @@ -7833,7 +7833,7 @@ pub struct SessionTextDelta { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionTextDelta, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: SessionTextDeltaData, @@ -7846,7 +7846,7 @@ pub struct SessionReasoningDelta { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionReasoningDelta, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: SessionTextDeltaData, @@ -7869,7 +7869,7 @@ pub struct SessionToolInputDelta { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionToolInputDelta, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: SessionToolInputDeltaData, @@ -7892,7 +7892,7 @@ pub struct SessionToolProgress { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionToolProgress, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: SessionToolProgressData, @@ -7912,7 +7912,7 @@ pub struct SessionCompactionDelta { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionCompactionDelta, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: SessionCompactionDeltaData, @@ -7939,7 +7939,7 @@ pub struct FilesystemChanged { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::FilesystemChanged, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: FilesystemChangedData, @@ -7955,7 +7955,7 @@ pub struct ReferenceUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ReferenceUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ReferenceUpdatedData, @@ -7985,7 +7985,7 @@ pub struct PermissionAsked { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::PermissionAsked, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: PermissionAskedData, @@ -8007,7 +8007,7 @@ pub struct PermissionReplied { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::PermissionReplied, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: PermissionRepliedData, @@ -8023,7 +8023,7 @@ pub struct PluginUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::PluginUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: PluginUpdatedData, @@ -8052,7 +8052,7 @@ pub struct ProjectUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ProjectUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ProjectUpdatedData, @@ -8071,7 +8071,7 @@ pub struct WorktreeUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::WorktreeUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: WorktreeUpdatedData, @@ -8094,7 +8094,7 @@ pub struct WorktreeResolved { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::WorktreeResolved, pub durable: SessionCreatedDurable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, @@ -8111,7 +8111,7 @@ pub struct CommandUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::CommandUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: CommandUpdatedData, @@ -8127,7 +8127,7 @@ pub struct ConfigUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ConfigUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ConfigUpdatedData, @@ -8143,7 +8143,7 @@ pub struct SkillUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SkillUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: SkillUpdatedData, @@ -8183,7 +8183,7 @@ pub struct PtyCreated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::PtyCreated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: PtyCreatedData, @@ -8196,7 +8196,7 @@ pub struct PtyUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::PtyUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: PtyCreatedData, @@ -8216,7 +8216,7 @@ pub struct PtyExited { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::PtyExited, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: PtyExitedData, @@ -8234,7 +8234,7 @@ pub struct PtyDeleted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::PtyDeleted, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: PtyDeletedData, @@ -8287,7 +8287,7 @@ pub struct PersistentPtyAdded { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::PersistentPtyAdded, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: PersistentPtyAddedData, @@ -8308,7 +8308,7 @@ pub struct PersistentPtyRemoved { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::PersistentPtyRemoved, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: PersistentPtyRemovedData, @@ -8321,7 +8321,7 @@ pub struct PersistentPtyUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::PersistentPtyUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: PersistentPtyAddedData, @@ -8339,7 +8339,7 @@ pub struct ShellCreated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ShellCreated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ShellCreatedData, @@ -8360,7 +8360,7 @@ pub struct ShellExited { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ShellExited, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ShellExitedData, @@ -8378,7 +8378,7 @@ pub struct ShellDeleted { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ShellDeleted, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ShellDeletedData, @@ -8404,7 +8404,7 @@ pub struct JobTime { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct JobShell { - pub kind: String, + pub kind: tag::Shell, pub id: String, #[serde(rename = "sessionID")] pub session_id: SessionID, @@ -8419,7 +8419,7 @@ pub struct JobShell { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct JobSubagent { - pub kind: String, + pub kind: tag::Subagent, pub id: String, #[serde(rename = "sessionID")] pub session_id: SessionID, @@ -8435,7 +8435,7 @@ pub struct JobSubagent { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct JobImage { - pub kind: String, + pub kind: tag::Image, pub id: String, #[serde(rename = "sessionID")] pub session_id: SessionID, @@ -8449,7 +8449,7 @@ pub struct JobImage { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct JobVideo { - pub kind: String, + pub kind: tag::Video, pub id: String, #[serde(rename = "sessionID")] pub session_id: SessionID, @@ -8462,7 +8462,7 @@ pub struct JobVideo { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct JobCodeMode { - pub kind: String, + pub kind: tag::Codemode, pub id: String, #[serde(rename = "sessionID")] pub session_id: SessionID, @@ -8492,7 +8492,7 @@ impl<'de> Deserialize<'de> for JobInfo { } impl JobInfo { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("kind").as_str() { Some("shell") => raw.variant().map(Self::Shell), Some("subagent") => raw.variant().map(Self::Subagent), @@ -8625,7 +8625,7 @@ pub struct ExperimentalJobUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ExperimentalJobUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ExperimentalJobUpdatedData, @@ -8643,7 +8643,7 @@ pub struct FormCreated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::FormCreated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: FormCreatedData, @@ -8664,7 +8664,7 @@ pub struct FormReplied { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::FormReplied, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: FormRepliedData, @@ -8684,7 +8684,7 @@ pub struct FormCancelled { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::FormCancelled, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: FormCancelledData, @@ -8700,7 +8700,7 @@ pub struct WebsearchUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::WebsearchUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: WebsearchUpdatedData, @@ -8716,7 +8716,7 @@ pub struct ArtifactUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ArtifactUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ArtifactUpdatedData, @@ -8724,7 +8724,7 @@ pub struct ArtifactUpdated { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionStatusIdle { - pub r#type: String, + pub r#type: tag::Idle, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] @@ -8740,7 +8740,7 @@ pub struct SessionStatusRetryAction { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionStatusRetry { - pub r#type: String, + pub r#type: tag::Retry, pub attempt: i64, pub message: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -8750,7 +8750,7 @@ pub struct SessionStatusRetry { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct SessionStatusBusy { - pub r#type: String, + pub r#type: tag::Busy, } /// `SessionStatus`, tagged by `type`. @@ -8771,7 +8771,7 @@ impl<'de> Deserialize<'de> for SessionStatus { } impl SessionStatus { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("idle") => raw.variant().map(Self::Idle), Some("retry") => raw.variant().map(Self::Retry), @@ -8807,7 +8807,7 @@ pub struct SessionStatusUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionStatus, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: SessionStatusUpdatedData, @@ -8820,7 +8820,7 @@ pub struct SessionIdle { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::SessionIdle, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: SessionArchivedData, @@ -8838,7 +8838,7 @@ pub struct TuiPromptAppend { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::TuiPromptAppend, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: TuiPromptAppendData, @@ -8856,7 +8856,7 @@ pub struct TuiCommandExecute { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::TuiCommandExecute, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: TuiCommandExecuteData, @@ -8888,7 +8888,7 @@ pub struct TuiToastShow { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::TuiToastShow, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: TuiToastShowData, @@ -8901,7 +8901,7 @@ pub struct TuiSessionSelect { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::TuiSessionSelect, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: SessionArchivedData, @@ -8919,7 +8919,7 @@ pub struct InstallationUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::InstallationUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: InstallationUpdatedData, @@ -8932,7 +8932,7 @@ pub struct InstallationUpdateAvailable { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::InstallationUpdateAvailable, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: InstallationUpdatedData, @@ -8951,7 +8951,7 @@ pub struct VcsBranchUpdated { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::VcsBranchUpdated, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: VcsBranchUpdatedData, @@ -8969,7 +8969,7 @@ pub struct McpStatusChanged { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::McpStatusChanged, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: McpStatusChangedData, @@ -8982,7 +8982,7 @@ pub struct McpResourcesChanged { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::McpResourcesChanged, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: McpStatusChangedData, @@ -9010,7 +9010,7 @@ pub struct ExperimentalMcpEvent { pub created: f64, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option>, - pub r#type: String, + pub r#type: tag::ExperimentalMcpEvent, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, pub data: ExperimentalMcpEventData, @@ -9038,7 +9038,7 @@ pub struct V2EventServerConnected { pub metadata: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option, - pub r#type: String, + pub r#type: tag::ServerConnected, pub data: V2EventServerConnectedData, } @@ -9158,7 +9158,7 @@ impl<'de> Deserialize<'de> for V2Event { } impl V2Event { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("location.shutdown") => raw.variant().map(Self::LocationShutdown), Some("models-dev.refreshed") => raw.variant().map(Self::ModelsDevRefreshed), @@ -10023,6 +10023,342 @@ impl V2Event { } } +/// Which member of [`V2Event`] an event is. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum EventKind { + LocationShutdown, + ModelsDevRefreshed, + CredentialUpdated, + CredentialSwitched, + IntegrationUpdated, + ProviderUpdated, + ModelUpdated, + AgentUpdated, + SessionCreated, + SessionAgentSelected, + SessionModelSelected, + SessionMoved, + SessionRenamed, + SessionMetadataUpdated, + SessionPermissions, + SessionViewed, + SessionArchived, + SessionUnarchived, + SessionUsageUpdated, + SessionDeleted, + SessionForked, + SessionInboxDelivered, + SessionInboxEnqueued, + SessionInboxCancelled, + SessionInboxDeliveryChanged, + SessionExecutionStarted, + SessionExecutionSucceeded, + SessionExecutionFailed, + SessionExecutionInterrupted, + SessionInstructionsUpdated, + SessionSynthetic, + SessionSkillActivated, + SessionShellStarted, + SessionShellEnded, + SessionStepStarted, + SessionStepFirstToken, + SessionStepStreamed, + SessionStepEnded, + SessionStepFailed, + SessionTextStarted, + SessionTextDelta, + SessionTextEnded, + SessionReasoningStarted, + SessionReasoningDelta, + SessionReasoningEnded, + SessionToolInputStarted, + SessionToolInputDelta, + SessionToolInputEnded, + SessionToolCalled, + SessionToolProgress, + SessionToolSuccess, + SessionToolFailed, + SessionRetryScheduled, + SessionCompactionStarted, + SessionCompactionDelta, + SessionCompactionEnded, + SessionCompactionFailed, + SessionRevertStaged, + SessionRevertCleared, + SessionRevertCommitted, + FilesystemChanged, + ReferenceUpdated, + PermissionAsked, + PermissionReplied, + PluginUpdated, + ProjectUpdated, + WorktreeUpdated, + WorktreeResolved, + CommandUpdated, + ConfigUpdated, + SkillUpdated, + PtyCreated, + PtyUpdated, + PtyExited, + PtyDeleted, + PersistentPtyAdded, + PersistentPtyRemoved, + PersistentPtyUpdated, + ShellCreated, + ShellExited, + ShellDeleted, + ExperimentalJobUpdated, + FormCreated, + FormReplied, + FormCancelled, + WebsearchUpdated, + ArtifactUpdated, + SessionStatus, + SessionIdle, + TuiPromptAppend, + TuiCommandExecute, + TuiToastShow, + TuiSessionSelect, + InstallationUpdated, + InstallationUpdateAvailable, + VcsBranchUpdated, + McpStatusChanged, + McpResourcesChanged, + ExperimentalMcpEvent, + Rpc, + ServerConnected, + Unknown, +} + +impl EventKind { + /// How many kinds there are, `Unknown` included. + pub const COUNT: usize = 102; + + /// The kind an event whose `type` is `tag` decodes to. + pub fn from_tag(tag: &str) -> Self { + match tag { + "location.shutdown" => Self::LocationShutdown, + "models-dev.refreshed" => Self::ModelsDevRefreshed, + "credential.updated" => Self::CredentialUpdated, + "credential.switched" => Self::CredentialSwitched, + "integration.updated" => Self::IntegrationUpdated, + "provider.updated" => Self::ProviderUpdated, + "model.updated" => Self::ModelUpdated, + "agent.updated" => Self::AgentUpdated, + "session.created" => Self::SessionCreated, + "session.agent.selected" => Self::SessionAgentSelected, + "session.model.selected" => Self::SessionModelSelected, + "session.moved" => Self::SessionMoved, + "session.renamed" => Self::SessionRenamed, + "session.metadata.updated" => Self::SessionMetadataUpdated, + "session.permissions" => Self::SessionPermissions, + "session.viewed" => Self::SessionViewed, + "session.archived" => Self::SessionArchived, + "session.unarchived" => Self::SessionUnarchived, + "session.usage.updated" => Self::SessionUsageUpdated, + "session.deleted" => Self::SessionDeleted, + "session.forked" => Self::SessionForked, + "session.inbox.delivered" => Self::SessionInboxDelivered, + "session.inbox.enqueued" => Self::SessionInboxEnqueued, + "session.inbox.cancelled" => Self::SessionInboxCancelled, + "session.inbox.delivery.changed" => Self::SessionInboxDeliveryChanged, + "session.execution.started" => Self::SessionExecutionStarted, + "session.execution.succeeded" => Self::SessionExecutionSucceeded, + "session.execution.failed" => Self::SessionExecutionFailed, + "session.execution.interrupted" => Self::SessionExecutionInterrupted, + "session.instructions.updated" => Self::SessionInstructionsUpdated, + "session.synthetic" => Self::SessionSynthetic, + "session.skill.activated" => Self::SessionSkillActivated, + "session.shell.started" => Self::SessionShellStarted, + "session.shell.ended" => Self::SessionShellEnded, + "session.step.started" => Self::SessionStepStarted, + "session.step.first-token" => Self::SessionStepFirstToken, + "session.step.streamed" => Self::SessionStepStreamed, + "session.step.ended" => Self::SessionStepEnded, + "session.step.failed" => Self::SessionStepFailed, + "session.text.started" => Self::SessionTextStarted, + "session.text.delta" => Self::SessionTextDelta, + "session.text.ended" => Self::SessionTextEnded, + "session.reasoning.started" => Self::SessionReasoningStarted, + "session.reasoning.delta" => Self::SessionReasoningDelta, + "session.reasoning.ended" => Self::SessionReasoningEnded, + "session.tool.input.started" => Self::SessionToolInputStarted, + "session.tool.input.delta" => Self::SessionToolInputDelta, + "session.tool.input.ended" => Self::SessionToolInputEnded, + "session.tool.called" => Self::SessionToolCalled, + "session.tool.progress" => Self::SessionToolProgress, + "session.tool.success" => Self::SessionToolSuccess, + "session.tool.failed" => Self::SessionToolFailed, + "session.retry.scheduled" => Self::SessionRetryScheduled, + "session.compaction.started" => Self::SessionCompactionStarted, + "session.compaction.delta" => Self::SessionCompactionDelta, + "session.compaction.ended" => Self::SessionCompactionEnded, + "session.compaction.failed" => Self::SessionCompactionFailed, + "session.revert.staged" => Self::SessionRevertStaged, + "session.revert.cleared" => Self::SessionRevertCleared, + "session.revert.committed" => Self::SessionRevertCommitted, + "filesystem.changed" => Self::FilesystemChanged, + "reference.updated" => Self::ReferenceUpdated, + "permission.asked" => Self::PermissionAsked, + "permission.replied" => Self::PermissionReplied, + "plugin.updated" => Self::PluginUpdated, + "project.updated" => Self::ProjectUpdated, + "worktree.updated" => Self::WorktreeUpdated, + "worktree.resolved" => Self::WorktreeResolved, + "command.updated" => Self::CommandUpdated, + "config.updated" => Self::ConfigUpdated, + "skill.updated" => Self::SkillUpdated, + "pty.created" => Self::PtyCreated, + "pty.updated" => Self::PtyUpdated, + "pty.exited" => Self::PtyExited, + "pty.deleted" => Self::PtyDeleted, + "persistent-pty.added" => Self::PersistentPtyAdded, + "persistent-pty.removed" => Self::PersistentPtyRemoved, + "persistent-pty.updated" => Self::PersistentPtyUpdated, + "shell.created" => Self::ShellCreated, + "shell.exited" => Self::ShellExited, + "shell.deleted" => Self::ShellDeleted, + "experimental.job.updated" => Self::ExperimentalJobUpdated, + "form.created" => Self::FormCreated, + "form.replied" => Self::FormReplied, + "form.cancelled" => Self::FormCancelled, + "websearch.updated" => Self::WebsearchUpdated, + "artifact.updated" => Self::ArtifactUpdated, + "session.status" => Self::SessionStatus, + "session.idle" => Self::SessionIdle, + "tui.prompt.append" => Self::TuiPromptAppend, + "tui.command.execute" => Self::TuiCommandExecute, + "tui.toast.show" => Self::TuiToastShow, + "tui.session.select" => Self::TuiSessionSelect, + "installation.updated" => Self::InstallationUpdated, + "installation.update-available" => Self::InstallationUpdateAvailable, + "vcs.branch.updated" => Self::VcsBranchUpdated, + "mcp.status.changed" => Self::McpStatusChanged, + "mcp.resources.changed" => Self::McpResourcesChanged, + "experimental.mcp.event" => Self::ExperimentalMcpEvent, + "server.connected" => Self::ServerConnected, + tag if tag.starts_with("rpc.") => Self::Rpc, + _ => Self::Unknown, + } + } + + /// Whether the events of this kind differ in their `type`, so that a listener names the ones it wants. + pub fn named(self) -> bool { + matches!(self, Self::Rpc | Self::Unknown) + } +} + +impl V2Event { + /// Which member this is. + pub fn kind(&self) -> EventKind { + match self { + Self::LocationShutdown(_) => EventKind::LocationShutdown, + Self::ModelsDevRefreshed(_) => EventKind::ModelsDevRefreshed, + Self::CredentialUpdated(_) => EventKind::CredentialUpdated, + Self::CredentialSwitched(_) => EventKind::CredentialSwitched, + Self::IntegrationUpdated(_) => EventKind::IntegrationUpdated, + Self::ProviderUpdated(_) => EventKind::ProviderUpdated, + Self::ModelUpdated(_) => EventKind::ModelUpdated, + Self::AgentUpdated(_) => EventKind::AgentUpdated, + Self::SessionCreated(_) => EventKind::SessionCreated, + Self::SessionAgentSelected(_) => EventKind::SessionAgentSelected, + Self::SessionModelSelected(_) => EventKind::SessionModelSelected, + Self::SessionMoved(_) => EventKind::SessionMoved, + Self::SessionRenamed(_) => EventKind::SessionRenamed, + Self::SessionMetadataUpdated(_) => EventKind::SessionMetadataUpdated, + Self::SessionPermissions(_) => EventKind::SessionPermissions, + Self::SessionViewed(_) => EventKind::SessionViewed, + Self::SessionArchived(_) => EventKind::SessionArchived, + Self::SessionUnarchived(_) => EventKind::SessionUnarchived, + Self::SessionUsageUpdated(_) => EventKind::SessionUsageUpdated, + Self::SessionDeleted(_) => EventKind::SessionDeleted, + Self::SessionForked(_) => EventKind::SessionForked, + Self::SessionInboxDelivered(_) => EventKind::SessionInboxDelivered, + Self::SessionInboxEnqueued(_) => EventKind::SessionInboxEnqueued, + Self::SessionInboxCancelled(_) => EventKind::SessionInboxCancelled, + Self::SessionInboxDeliveryChanged(_) => EventKind::SessionInboxDeliveryChanged, + Self::SessionExecutionStarted(_) => EventKind::SessionExecutionStarted, + Self::SessionExecutionSucceeded(_) => EventKind::SessionExecutionSucceeded, + Self::SessionExecutionFailed(_) => EventKind::SessionExecutionFailed, + Self::SessionExecutionInterrupted(_) => EventKind::SessionExecutionInterrupted, + Self::SessionInstructionsUpdated(_) => EventKind::SessionInstructionsUpdated, + Self::SessionSynthetic(_) => EventKind::SessionSynthetic, + Self::SessionSkillActivated(_) => EventKind::SessionSkillActivated, + Self::SessionShellStarted(_) => EventKind::SessionShellStarted, + Self::SessionShellEnded(_) => EventKind::SessionShellEnded, + Self::SessionStepStarted(_) => EventKind::SessionStepStarted, + Self::SessionStepFirstToken(_) => EventKind::SessionStepFirstToken, + Self::SessionStepStreamed(_) => EventKind::SessionStepStreamed, + Self::SessionStepEnded(_) => EventKind::SessionStepEnded, + Self::SessionStepFailed(_) => EventKind::SessionStepFailed, + Self::SessionTextStarted(_) => EventKind::SessionTextStarted, + Self::SessionTextDelta(_) => EventKind::SessionTextDelta, + Self::SessionTextEnded(_) => EventKind::SessionTextEnded, + Self::SessionReasoningStarted(_) => EventKind::SessionReasoningStarted, + Self::SessionReasoningDelta(_) => EventKind::SessionReasoningDelta, + Self::SessionReasoningEnded(_) => EventKind::SessionReasoningEnded, + Self::SessionToolInputStarted(_) => EventKind::SessionToolInputStarted, + Self::SessionToolInputDelta(_) => EventKind::SessionToolInputDelta, + Self::SessionToolInputEnded(_) => EventKind::SessionToolInputEnded, + Self::SessionToolCalled(_) => EventKind::SessionToolCalled, + Self::SessionToolProgress(_) => EventKind::SessionToolProgress, + Self::SessionToolSuccess(_) => EventKind::SessionToolSuccess, + Self::SessionToolFailed(_) => EventKind::SessionToolFailed, + Self::SessionRetryScheduled(_) => EventKind::SessionRetryScheduled, + Self::SessionCompactionStarted(_) => EventKind::SessionCompactionStarted, + Self::SessionCompactionDelta(_) => EventKind::SessionCompactionDelta, + Self::SessionCompactionEnded(_) => EventKind::SessionCompactionEnded, + Self::SessionCompactionFailed(_) => EventKind::SessionCompactionFailed, + Self::SessionRevertStaged(_) => EventKind::SessionRevertStaged, + Self::SessionRevertCleared(_) => EventKind::SessionRevertCleared, + Self::SessionRevertCommitted(_) => EventKind::SessionRevertCommitted, + Self::FilesystemChanged(_) => EventKind::FilesystemChanged, + Self::ReferenceUpdated(_) => EventKind::ReferenceUpdated, + Self::PermissionAsked(_) => EventKind::PermissionAsked, + Self::PermissionReplied(_) => EventKind::PermissionReplied, + Self::PluginUpdated(_) => EventKind::PluginUpdated, + Self::ProjectUpdated(_) => EventKind::ProjectUpdated, + Self::WorktreeUpdated(_) => EventKind::WorktreeUpdated, + Self::WorktreeResolved(_) => EventKind::WorktreeResolved, + Self::CommandUpdated(_) => EventKind::CommandUpdated, + Self::ConfigUpdated(_) => EventKind::ConfigUpdated, + Self::SkillUpdated(_) => EventKind::SkillUpdated, + Self::PtyCreated(_) => EventKind::PtyCreated, + Self::PtyUpdated(_) => EventKind::PtyUpdated, + Self::PtyExited(_) => EventKind::PtyExited, + Self::PtyDeleted(_) => EventKind::PtyDeleted, + Self::PersistentPtyAdded(_) => EventKind::PersistentPtyAdded, + Self::PersistentPtyRemoved(_) => EventKind::PersistentPtyRemoved, + Self::PersistentPtyUpdated(_) => EventKind::PersistentPtyUpdated, + Self::ShellCreated(_) => EventKind::ShellCreated, + Self::ShellExited(_) => EventKind::ShellExited, + Self::ShellDeleted(_) => EventKind::ShellDeleted, + Self::ExperimentalJobUpdated(_) => EventKind::ExperimentalJobUpdated, + Self::FormCreated(_) => EventKind::FormCreated, + Self::FormReplied(_) => EventKind::FormReplied, + Self::FormCancelled(_) => EventKind::FormCancelled, + Self::WebsearchUpdated(_) => EventKind::WebsearchUpdated, + Self::ArtifactUpdated(_) => EventKind::ArtifactUpdated, + Self::SessionStatus(_) => EventKind::SessionStatus, + Self::SessionIdle(_) => EventKind::SessionIdle, + Self::TuiPromptAppend(_) => EventKind::TuiPromptAppend, + Self::TuiCommandExecute(_) => EventKind::TuiCommandExecute, + Self::TuiToastShow(_) => EventKind::TuiToastShow, + Self::TuiSessionSelect(_) => EventKind::TuiSessionSelect, + Self::InstallationUpdated(_) => EventKind::InstallationUpdated, + Self::InstallationUpdateAvailable(_) => EventKind::InstallationUpdateAvailable, + Self::VcsBranchUpdated(_) => EventKind::VcsBranchUpdated, + Self::McpStatusChanged(_) => EventKind::McpStatusChanged, + Self::McpResourcesChanged(_) => EventKind::McpResourcesChanged, + Self::ExperimentalMcpEvent(_) => EventKind::ExperimentalMcpEvent, + Self::Rpc(_) => EventKind::Rpc, + Self::ServerConnected(_) => EventKind::ServerConnected, + Self::Unknown(_) => EventKind::Unknown, + } + } +} + /// Output of `Client::event_subscribe`. pub type EventSubscribeOutput = V2Event; @@ -10258,7 +10594,7 @@ pub struct ExperimentalBlobGetInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct AutomationTriggerAt { - pub r#type: String, + pub r#type: tag::At, pub at: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub tz: Option, @@ -10268,7 +10604,7 @@ string_type!(AutomationDuration, "`Automation.Duration`"); #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct AutomationTriggerEvery { - pub r#type: String, + pub r#type: tag::Every, pub every: AutomationDuration, #[serde(default, skip_serializing_if = "Option::is_none")] pub tz: Option, @@ -10276,7 +10612,7 @@ pub struct AutomationTriggerEvery { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct AutomationTriggerCron { - pub r#type: String, + pub r#type: tag::Cron, pub cron: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub tz: Option, @@ -10284,7 +10620,7 @@ pub struct AutomationTriggerCron { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct AutomationTriggerEvent { - pub r#type: String, + pub r#type: tag::Event, pub server: String, pub event: String, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -10310,7 +10646,7 @@ impl<'de> Deserialize<'de> for AutomationTrigger { } impl AutomationTrigger { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("at") => raw.variant().map(Self::At), Some("every") => raw.variant().map(Self::Every), @@ -10384,7 +10720,7 @@ impl AutomationTarget { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct AutomationPromptActionInput { - pub r#type: String, + pub r#type: tag::Prompt, pub prompt: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub to: Option, @@ -10392,7 +10728,7 @@ pub struct AutomationPromptActionInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct AutomationCodeActionInput { - pub r#type: String, + pub r#type: tag::Code, pub code: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub args: Option, @@ -10400,7 +10736,7 @@ pub struct AutomationCodeActionInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct AutomationShellActionInput { - pub r#type: String, + pub r#type: tag::Shell, pub command: String, } @@ -10422,7 +10758,7 @@ impl<'de> Deserialize<'de> for AutomationActionInput { } impl AutomationActionInput { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("prompt") => raw.variant().map(Self::Prompt), Some("code") => raw.variant().map(Self::Code), @@ -10459,14 +10795,14 @@ string_type!(AutomationID, "`Automation.ID`"); #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct AutomationActionPrompt { - pub r#type: String, + pub r#type: tag::Prompt, pub prompt: String, pub to: AutomationTarget, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct AutomationActionCode { - pub r#type: String, + pub r#type: tag::Code, pub code: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub args: Option, @@ -10474,7 +10810,7 @@ pub struct AutomationActionCode { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct AutomationActionShell { - pub r#type: String, + pub r#type: tag::Shell, pub command: String, } @@ -10496,7 +10832,7 @@ impl<'de> Deserialize<'de> for AutomationAction { } impl AutomationAction { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("prompt") => raw.variant().map(Self::Prompt), Some("code") => raw.variant().map(Self::Code), @@ -10831,7 +11167,7 @@ pub type ExperimentalMachineListOutput = Vec; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct MachineReach { - pub r#type: String, + pub r#type: tag::Url, pub url: String, } @@ -10845,7 +11181,7 @@ pub struct ExperimentalMachineAddInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct MachineInviteReachItemIroh { - pub r#type: String, + pub r#type: tag::Iroh, } #[derive(Debug, Clone, PartialEq, Serialize)] @@ -10864,7 +11200,7 @@ impl<'de> Deserialize<'de> for MachineInviteReachItem { } impl MachineInviteReachItem { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("url") => raw.variant().map(Self::Url), Some("iroh") => raw.variant().map(Self::Iroh), @@ -10972,13 +11308,13 @@ pub struct ReferenceListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ReferenceLocalSource { - pub r#type: String, + pub r#type: tag::Local, pub path: AbsolutePath, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ReferenceGitSource { - pub r#type: String, + pub r#type: tag::Git, pub repository: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub branch: Option, @@ -11001,7 +11337,7 @@ impl<'de> Deserialize<'de> for ReferenceSource { } impl ReferenceSource { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("local") => raw.variant().map(Self::Local), Some("git") => raw.variant().map(Self::Git), @@ -11279,13 +11615,13 @@ pub struct ExperimentalMigrationV1StatusOutput2RunningProgress { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ExperimentalMigrationV1StatusOutput2Running { - pub status: String, + pub status: tag::Running, pub progress: ExperimentalMigrationV1StatusOutput2RunningProgress, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ExperimentalMigrationV1StatusOutput2Error { - pub status: String, + pub status: tag::Error, pub error: String, } @@ -11306,7 +11642,7 @@ impl<'de> Deserialize<'de> for ExperimentalMigrationV1StatusOutput2 { } impl ExperimentalMigrationV1StatusOutput2 { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("status").as_str() { Some("required") | Some("completed") => raw.variant().map(Self::Variant1), Some("running") => raw.variant().map(Self::Running), @@ -12063,7 +12399,7 @@ impl<'de> Deserialize<'de> for ConfigModelReasoning { } impl ConfigModelReasoning { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("supported").as_bool() { Some(false) => raw.variant().map(Self::False), Some(true) => raw.variant().map(Self::True), @@ -12365,7 +12701,7 @@ pub struct ConfigEntryDocumentInfo { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ConfigEntryDocument { - pub r#type: String, + pub r#type: tag::Document, #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option, pub info: ConfigEntryDocumentInfo, @@ -12373,7 +12709,7 @@ pub struct ConfigEntryDocument { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] pub struct ConfigEntryDirectory { - pub r#type: String, + pub r#type: tag::Directory, pub path: AbsolutePath, } @@ -12394,7 +12730,7 @@ impl<'de> Deserialize<'de> for ConfigEntry { } impl ConfigEntry { - fn from_raw(raw: &crate::de::Raw) -> Result { + pub fn from_raw(raw: &crate::de::Raw) -> Result { match raw.field("type").as_str() { Some("document") => raw.variant().map(Self::Document), Some("directory") => raw.variant().map(Self::Directory), @@ -13031,3 +13367,74 @@ pub struct VcsInitNotSupportedError { impl crate::TaggedError for VcsInitNotSupportedError { const TAG: &'static str = "VcsInitNotSupportedError"; } + +/// Union members' tags. Each serializes as its literal and decodes from any string, since the union has picked the member. +pub mod tag { + tags! { + Active = "active", AgentSwitched = "agent-switched", AgentUpdated = "agent.updated", Answered = "answered", + ArtifactUpdated = "artifact.updated", Assistant = "assistant", At = "at", Before = "before", + Boolean = "boolean", Builtin = "builtin", Busy = "busy", Cancelled = "cancelled", Choice = "choice", + Code = "code", Codemode = "codemode", Command = "command", CommandUpdated = "command.updated", + Compaction = "compaction", Complete = "complete", Completed = "completed", ConfigUpdated = "config.updated", + Connected = "connected", Credential = "credential", CredentialSwitched = "credential.switched", + CredentialUpdated = "credential.updated", Cron = "cron", Detail = "detail", Directory = "directory", + Disabled = "disabled", Document = "document", Env = "env", Error = "error", Event = "event", Every = "every", + ExperimentalJobUpdated = "experimental.job.updated", ExperimentalMcpEvent = "experimental.mcp.event", + Expired = "expired", External = "external", Failed = "failed", File = "file", + FilesystemChanged = "filesystem.changed", FormCancelled = "form.cancelled", FormCreated = "form.created", + FormReplied = "form.replied", Git = "git", Idle = "idle", Image = "image", Inline = "inline", + InstallationUpdateAvailable = "installation.update-available", InstallationUpdated = "installation.updated", + Integer = "integer", IntegrationUpdated = "integration.updated", Iroh = "iroh", Json = "json", Key = "key", + Local = "local", LocationShutdown = "location.shutdown", LocationSwitched = "location-switched", + LogSynced = "log.synced", McpResourcesChanged = "mcp.resources.changed", + McpStatusChanged = "mcp.status.changed", ModelSwitched = "model-switched", ModelUpdated = "model.updated", + ModelsDevRefreshed = "models-dev.refreshed", Move = "move", Multiselect = "multiselect", Native = "native", + NeedsAuth = "needs_auth", None = "none", Number = "number", Oauth = "oauth", Package = "package", + Pending = "pending", PermissionAsked = "permission.asked", PermissionReplied = "permission.replied", + PersistentPtyAdded = "persistent-pty.added", PersistentPtyRemoved = "persistent-pty.removed", + PersistentPtyUpdated = "persistent-pty.updated", PluginUpdated = "plugin.updated", Predicate = "predicate", + ProjectUpdated = "project.updated", Prompt = "prompt", ProviderUpdated = "provider.updated", + PtyCreated = "pty.created", PtyDeleted = "pty.deleted", PtyExited = "pty.exited", PtyUpdated = "pty.updated", + Reasoning = "reasoning", ReferenceUpdated = "reference.updated", Remote = "remote", Retry = "retry", + Running = "running", Score = "score", Sdk = "sdk", ServerConnected = "server.connected", + SessionAgentSelected = "session.agent.selected", SessionArchived = "session.archived", + SessionCompactionDelta = "session.compaction.delta", SessionCompactionEnded = "session.compaction.ended", + SessionCompactionFailed = "session.compaction.failed", SessionCompactionStarted = "session.compaction.started", + SessionCreated = "session.created", SessionDeleted = "session.deleted", + SessionExecutionFailed = "session.execution.failed", + SessionExecutionInterrupted = "session.execution.interrupted", + SessionExecutionStarted = "session.execution.started", + SessionExecutionSucceeded = "session.execution.succeeded", SessionForked = "session.forked", + SessionIdle = "session.idle", SessionInboxCancelled = "session.inbox.cancelled", + SessionInboxDelivered = "session.inbox.delivered", + SessionInboxDeliveryChanged = "session.inbox.delivery.changed", SessionInboxEnqueued = "session.inbox.enqueued", + SessionInstructionsUpdated = "session.instructions.updated", + SessionMessageContentUpdated = "session.message.content.updated", + SessionMetadataUpdated = "session.metadata.updated", SessionModelSelected = "session.model.selected", + SessionMoved = "session.moved", SessionPermissions = "session.permissions", + SessionReasoningDelta = "session.reasoning.delta", SessionReasoningEnded = "session.reasoning.ended", + SessionReasoningStarted = "session.reasoning.started", SessionRenamed = "session.renamed", + SessionRetryScheduled = "session.retry.scheduled", SessionRevertCleared = "session.revert.cleared", + SessionRevertCommitted = "session.revert.committed", SessionRevertStaged = "session.revert.staged", + SessionShellEnded = "session.shell.ended", SessionShellStarted = "session.shell.started", + SessionSkillActivated = "session.skill.activated", SessionStatus = "session.status", + SessionStepEnded = "session.step.ended", SessionStepFailed = "session.step.failed", + SessionStepFirstToken = "session.step.first-token", SessionStepStarted = "session.step.started", + SessionStepStreamed = "session.step.streamed", SessionSynthetic = "session.synthetic", + SessionTextDelta = "session.text.delta", SessionTextEnded = "session.text.ended", + SessionTextStarted = "session.text.started", SessionToolCalled = "session.tool.called", + SessionToolFailed = "session.tool.failed", SessionToolInputDelta = "session.tool.input.delta", + SessionToolInputEnded = "session.tool.input.ended", SessionToolInputStarted = "session.tool.input.started", + SessionToolProgress = "session.tool.progress", SessionToolSuccess = "session.tool.success", + SessionUnarchived = "session.unarchived", SessionUsageRecorded = "session.usage.recorded", + SessionUsageUpdated = "session.usage.updated", SessionViewed = "session.viewed", Shell = "shell", + ShellCreated = "shell.created", ShellDeleted = "shell.deleted", ShellExited = "shell.exited", Skill = "skill", + SkillUpdated = "skill.updated", Streaming = "streaming", String = "string", Subagent = "subagent", + Summary = "summary", Synthetic = "synthetic", System = "system", Text = "text", Through = "through", + Tool = "tool", TuiCommandExecute = "tui.command.execute", TuiPromptAppend = "tui.prompt.append", + TuiSessionSelect = "tui.session.select", TuiToastShow = "tui.toast.show", Uri = "uri", Url = "url", + User = "user", VcsBranchUpdated = "vcs.branch.updated", Video = "video", Webrtc = "webrtc", + WebsearchUpdated = "websearch.updated", Websocket = "websocket", WorktreeResolved = "worktree.resolved", + WorktreeUpdated = "worktree.updated", + } +} diff --git a/packages/cli-rs/crates/api-types/tests/event_names.rs b/packages/cli-rs/crates/api-types/tests/event_names.rs index c79906cfab2..0a721f00faa 100644 --- a/packages/cli-rs/crates/api-types/tests/event_names.rs +++ b/packages/cli-rs/crates/api-types/tests/event_names.rs @@ -1,5 +1,5 @@ -//! Event names that client code matches as raw strings, outside the typed [`V2Event`]: ACP's translation, the -//! TUI's event table and plugins, mini, and the example plugins. If the protocol renames an event, such code still +//! Event names that client code matches as raw strings, outside the typed [`V2Event`]: ACP's catalog and selection +//! followers, the TUI's plugins, and mini. If the protocol renames an event, such code still //! compiles and its handler goes quiet. This test reads those sources and requires every name it finds in an //! event position (a match arm, a comparison, or an `on_event` list) to be a member of the generated union. @@ -7,13 +7,18 @@ use std::path::{Path, PathBuf}; use opencode_api_types::types::V2Event; -const SOURCES: &[&str] = - &["acp/src", "mini/src", "tui/src/features/events.rs", "tui/src/plugins", "plugin/examples", "plugin-abi/src"]; +const SOURCES: &[&str] = &["acp/src", "mini/src", "tui/src/plugins"]; /// Dotted names in the same positions that are session error types (`error.type`), not events. TS keeps them as /// plain strings too, so there is no generated list to check them against. -const ERROR_TYPES: &[&str] = - &["compaction.interrupted", "provider.auth", "provider.content-filter", "provider.free-limit", "provider.go-limit"]; +const ERROR_TYPES: &[&str] = &[ + "compaction.failed", + "compaction.interrupted", + "provider.auth", + "provider.content-filter", + "provider.free-limit", + "provider.go-limit", +]; #[test] fn every_raw_event_name_is_in_the_generated_union() { @@ -31,7 +36,7 @@ fn every_raw_event_name_is_in_the_generated_union() { .collect(); names.sort(); names.dedup(); - assert!(names.len() > 30, "the scan found only {} names: {names:?}", names.len()); + assert!(names.len() > 12, "the scan found only {} names: {names:?}", names.len()); let unknown: Vec<_> = names.iter().filter(|(_, name)| !known(name) && !ERROR_TYPES.contains(&name.as_str())).collect(); assert!(unknown.is_empty(), "event names outside the generated union: {unknown:?}"); diff --git a/packages/cli-rs/crates/api/src/events.rs b/packages/cli-rs/crates/api/src/events.rs index e419cfd2146..d0944716448 100644 --- a/packages/cli-rs/crates/api/src/events.rs +++ b/packages/cli-rs/crates/api/src/events.rs @@ -21,7 +21,7 @@ pub const CONNECTED: &str = "server.connected"; /// A server event. pub trait Event: Clone + Send + 'static { /// The wire `type` tag. - fn kind(&self) -> &str; + fn tag(&self) -> &str; /// Folds `next` into `self` when both continue the same delta stream (for example two text deltas /// of one message part), and reports whether it did. Only adjacent events of one batch merge. @@ -31,7 +31,7 @@ pub trait Event: Clone + Send + 'static { } impl Event for serde_json::Value { - fn kind(&self) -> &str { + fn tag(&self) -> &str { self.get("type").and_then(serde_json::Value::as_str).unwrap_or_default() } } @@ -285,7 +285,7 @@ impl> Runner { let first = match first { None => return failed("Event stream disconnected", None), Some(Err(error)) => return failed(&error.to_string(), None), - Some(Ok(first)) if first.kind() != CONNECTED => { + Some(Ok(first)) if first.tag() != CONNECTED => { return failed("Event stream did not start with server.connected", None); } Some(Ok(first)) => first, @@ -401,7 +401,7 @@ mod tests { } impl Event for Ev { - fn kind(&self) -> &str { + fn tag(&self) -> &str { self.kind } @@ -771,7 +771,7 @@ mod tests { let deadline = Instant::now() + Duration::from_secs(20); while kinds.len() < 5 { let Ok(Some(batch)) = tokio::time::timeout_at(deadline, batches.recv()).await else { break }; - kinds.extend(batch.iter().map(|event| event.kind().to_owned())); + kinds.extend(batch.iter().map(|event| event.tag().to_owned())); } println!("live: {server} state {:?}", connection.state()); println!("live: event types {}", serde_json::to_string(&kinds).unwrap()); diff --git a/packages/cli-rs/crates/api/src/lib.rs b/packages/cli-rs/crates/api/src/lib.rs index c0a6440a04c..53269e5cfe2 100644 --- a/packages/cli-rs/crates/api/src/lib.rs +++ b/packages/cli-rs/crates/api/src/lib.rs @@ -13,4 +13,4 @@ pub mod sse; pub mod transport; pub mod ws; -pub use opencode_api_types::{de, js, ser}; +pub use opencode_api_types::{de, js, kinds, ser, tool}; diff --git a/packages/cli-rs/crates/api/src/transport.rs b/packages/cli-rs/crates/api/src/transport.rs index 870497d8e6c..875340fec8a 100644 --- a/packages/cli-rs/crates/api/src/transport.rs +++ b/packages/cli-rs/crates/api/src/transport.rs @@ -107,8 +107,8 @@ impl SseResponse { } impl crate::events::Event for V2Event { - fn kind(&self) -> &str { - self.tag() + fn tag(&self) -> &str { + V2Event::tag(self) } /// Joins adjacent deltas of one text or reasoning part (same session, message, and ordinal) or of diff --git a/packages/cli-rs/crates/api/tests/all/api.rs b/packages/cli-rs/crates/api/tests/all/api.rs index 46946c4345a..da9d79ffe83 100644 --- a/packages/cli-rs/crates/api/tests/all/api.rs +++ b/packages/cli-rs/crates/api/tests/all/api.rs @@ -6,7 +6,6 @@ use bytes::Bytes; use futures_util::StreamExt; use opencode_api::client::{Auth, Client}; use opencode_api::error::Error; -use opencode_api::events::Event; use opencode_api::generated::*; use opencode_api::transport::{BoxFuture, Request, Response, Transport}; use serde_json::{Value, json}; @@ -67,7 +66,11 @@ fn tagged_union_decodes_known_rpc_and_unknown_members() { let connected: V2Event = serde_json::from_value(json!({ "id": "evt_1", "type": "server.connected", "data": {} })).unwrap(); assert!(matches!(connected, V2Event::ServerConnected(_)), "{connected:?}"); - assert_eq!(connected.kind(), "server.connected"); + assert_eq!(connected.tag(), "server.connected"); + // A member decoded on its own takes any tag, since only the union checks it, and writes its own. + let member: V2EventServerConnected = + serde_json::from_value(json!({ "id": "evt_1", "type": "other", "data": {} })).unwrap(); + assert_eq!(serde_json::to_value(member).unwrap()["type"], "server.connected"); let rpc = json!({ "id": "evt_2", "created": 1.5, "type": "rpc.plugin.ping", @@ -214,7 +217,7 @@ async fn event_stream_decodes_generated_events() { let script = Script::new(200, "text/event-stream", body); let response = client(&script).event_subscribe(&EventSubscribeInput::default()).await.unwrap(); let events: Vec<_> = response.events(|| {}).collect().await; - let kinds: Vec<_> = events.iter().map(|event| event.as_ref().unwrap().kind().to_owned()).collect(); + let kinds: Vec<_> = events.iter().map(|event| event.as_ref().unwrap().tag().to_owned()).collect(); assert_eq!(kinds, ["server.connected", "future.event", "skill.updated"]); let script = Script::new(200, "", "{}"); diff --git a/packages/cli-rs/crates/api/tests/all/live.rs b/packages/cli-rs/crates/api/tests/all/live.rs index aff412b6db4..63ec09ca056 100644 --- a/packages/cli-rs/crates/api/tests/all/live.rs +++ b/packages/cli-rs/crates/api/tests/all/live.rs @@ -9,7 +9,6 @@ use std::time::Duration; use futures_util::StreamExt; use opencode_api::client::{Auth, Client}; use opencode_api::error::Error; -use opencode_api::events::Event; use opencode_api::generated::*; #[derive(Default)] @@ -209,7 +208,7 @@ async fn live_reads_decode() { let first = tokio::time::timeout(Duration::from_secs(10), events.next()).await; match first { Ok(Some(Ok(event))) => { - report.rows.push(("event.subscribe first".to_owned(), format!("ok {}", event.kind()))) + report.rows.push(("event.subscribe first".to_owned(), format!("ok {}", event.tag()))) } other => report.failures.push(format!("event.subscribe first: {other:?}")), } diff --git a/packages/cli-rs/crates/cli/src/commands/machine.rs b/packages/cli-rs/crates/cli/src/commands/machine.rs index 58b3bd8c87c..b6262922d4d 100644 --- a/packages/cli-rs/crates/cli/src/commands/machine.rs +++ b/packages/cli-rs/crates/cli/src/commands/machine.rs @@ -7,7 +7,7 @@ use opencode_api::client::Client; use opencode_api::error::Error as ApiError; use opencode_api::generated::{ ConflictError, ExperimentalMachineAddInput, ExperimentalMachineRemoveInput, ForbiddenError, InvalidRequestError, - MachineInfo, MachineInvite, MachineInviteReachItem, MachineNotFoundError, MachineReach, + MachineInfo, MachineInvite, MachineInviteReachItem, MachineNotFoundError, MachineReach, tag, }; use opencode_util::time::{Zone, now_ms}; use opencode_util::{bail, error}; @@ -110,7 +110,7 @@ fn reach(urls: &[String]) -> Vec { seen.push(href); } } - seen.into_iter().map(|url| MachineReach { r#type: "url".into(), url: url.into() }).collect() + seen.into_iter().map(|url| MachineReach { r#type: tag::Url, url: url.into() }).collect() } /// `formatMachineAdd`: only the join string when stdout is not a terminal. @@ -128,7 +128,7 @@ fn add_text(invite: &MachineInvite, tty: bool, now: i64, zone: Zone) -> String { } _ => false, }; - let access = if invite.reach.iter().any(|entry| entry.tag() == "iroh") { + let access = if invite.reach.iter().any(|entry| matches!(entry, MachineInviteReachItem::Iroh(_))) { "Works from any network." } else if invite.reach.iter().any(reachable) { "Works from computers that can reach one of these addresses." @@ -268,7 +268,6 @@ mod tests { "ws://[::1]:4096/api/experimental/machine/link", ] ); - assert!(reach(&servers.map(String::from)).iter().all(|entry| entry.r#type == "url")); } /// machine.test.ts "machine output formatting". diff --git a/packages/cli-rs/crates/mini/src/prompt/parts.rs b/packages/cli-rs/crates/mini/src/prompt/parts.rs index bf23a59c24a..9478f5bb6e3 100644 --- a/packages/cli-rs/crates/mini/src/prompt/parts.rs +++ b/packages/cli-rs/crates/mini/src/prompt/parts.rs @@ -1,7 +1,7 @@ //! Converts between editable prompts, wire requests and history entries. use opencode_api::generated::{ - PromptBase64, PromptFileAttachment, PromptFileSource, PromptFileSourceInline, PromptMention, + PromptBase64, PromptFileAttachment, PromptFileSource, PromptFileSourceInline, PromptMention, tag, }; use opencode_ui::prompt_input::editor::Mention; use serde_json::{Map, Value, json}; @@ -95,7 +95,7 @@ impl RunPrompt { Some(PromptFileAttachment { data: PromptBase64(data.to_owned()), mime: file.mime.clone().unwrap_or_else(|| mime.to_owned()), - source: PromptFileSource::Inline(PromptFileSourceInline { r#type: "inline".into() }), + source: PromptFileSource::Inline(PromptFileSourceInline { r#type: tag::Inline }), name: file.filename.clone(), description: file.description.clone(), mention: file.mention.as_ref().map(|mention| PromptMention { diff --git a/packages/cli-rs/crates/mini/src/replay.rs b/packages/cli-rs/crates/mini/src/replay.rs index 16756207c36..5bf0f4ae7b3 100644 --- a/packages/cli-rs/crates/mini/src/replay.rs +++ b/packages/cli-rs/crates/mini/src/replay.rs @@ -12,7 +12,7 @@ use opencode_api::generated::{ SessionMessageAssistantContentItem as ContentItem, SessionMessageAssistantToolState, SessionMessageAssistantToolState as ToolPartState, SessionMessageAssistantToolTime, SessionMessageCompaction, SessionMessageShellExit, SessionMessageShellOutput, SessionMessageToolStateCompleted, SessionMessageToolStateError, - SessionMessageToolStateRunning, SessionMessageToolStateStreaming, SessionStructuredError, + SessionMessageToolStateRunning, SessionMessageToolStateStreaming, SessionStructuredError, tag, }; use opentui::app::ProxyError; use serde::Deserialize; @@ -32,19 +32,43 @@ pub const RESIZE_DELAY: Duration = Duration::from_millis(250); /// Maximum events buffered during a resize replay. pub const RELIST_LIMIT: usize = 4096; -/// A part of a message whose text arrives in pieces (`FragmentRef`). -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct Fragment { - pub message_id: String, - pub part_id: String, +/// The part of a message whose text arrives in pieces, displayed as its part ID (`text:0`, `compaction:summary`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PartRef { + Text(u32), + Reasoning(u32), + Summary, } -impl Fragment { - pub fn new(message_id: &str, kind: &str, ordinal: u64) -> Self { - Self { message_id: message_id.to_owned(), part_id: format!("{kind}:{ordinal}") } +impl PartRef { + /// The part of an ID this client displayed. + fn parse(id: &str) -> Option { + Some(match id.split_once(':')? { + ("text", ordinal) => Self::Text(ordinal.parse().ok()?), + ("reasoning", ordinal) => Self::Reasoning(ordinal.parse().ok()?), + ("compaction", "summary") => Self::Summary, + _ => return None, + }) } } +impl std::fmt::Display for PartRef { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Text(ordinal) => write!(f, "text:{ordinal}"), + Self::Reasoning(ordinal) => write!(f, "reasoning:{ordinal}"), + Self::Summary => f.write_str("compaction:summary"), + } + } +} + +/// A fragment (`FragmentRef`): the message's index in [`Fragments`]' table and the part. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct Fragment { + message: u32, + part: PartRef, +} + #[derive(Clone, Debug, Default)] struct FragmentState { text: String, @@ -70,12 +94,6 @@ impl FragmentState { } } -/// What a fragment held before an update. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Update { - pub previous: String, -} - #[derive(Clone, Debug, PartialEq, Eq)] pub enum Restore { Append(String), @@ -84,27 +102,40 @@ pub enum Restore { } #[derive(Clone, Debug, Default)] -pub struct Fragments(HashMap); +pub struct Fragments { + /// Each message's index, which its fragments are keyed by. + messages: HashMap, + states: HashMap, +} impl Fragments { pub fn clear(&mut self) { - self.0.clear(); + self.messages.clear(); + self.states.clear(); } - pub fn value(&self, fragment: &Fragment) -> Option<&str> { - self.0.get(fragment).map(|state| state.text.as_str()) + fn key(&mut self, id: &str, part: PartRef) -> Fragment { + let next = self.messages.len() as u32; + let message = self.messages.get(id).copied().unwrap_or_else(|| *self.messages.entry(id.into()).or_insert(next)); + Fragment { message, part } } - /// The fragment's whole text from a list; `visible` when it was shown. - pub fn project(&mut self, fragment: &Fragment, text: &str, visible: bool) -> Update { - let current = self.0.remove(fragment).unwrap_or_default(); + pub fn value(&self, message: &str, part: PartRef) -> Option<&str> { + let message = *self.messages.get(message)?; + self.states.get(&Fragment { message, part }).map(|state| state.text.as_str()) + } + + /// The fragment's whole text from a list; `visible` when it was shown. Returns the text it held. + pub fn project(&mut self, message: &str, part: PartRef, text: &str, visible: bool) -> String { + let fragment = self.key(message, part); + let current = self.states.remove(&fragment).unwrap_or_default(); let state = if visible { FragmentState::listed(text) } else { FragmentState { text: text.to_owned(), projected: current.projected } }; - self.0.insert(fragment.clone(), state); - Update { previous: current.text } + self.states.insert(fragment, state); + current.text } /// A live delta: the length of the text before it and the text to show, or `None` when there is nothing to show @@ -112,8 +143,9 @@ impl Fragments { /// /// TS drops a delta found anywhere in the listed text, so a list of "a b" and the deltas " " and "c" showed /// "a bc" (`parity/deviations/M06-mini-covered-deltas.md`). - pub fn delta<'a>(&mut self, fragment: &Fragment, delta: &'a str) -> Option<(usize, Cow<'a, str>)> { - let state = self.0.entry(fragment.clone()).or_default(); + pub fn delta<'a>(&mut self, message: &str, part: PartRef, delta: &'a str) -> Option<(usize, Cow<'a, str>)> { + let fragment = self.key(message, part); + let state = self.states.entry(fragment).or_default(); let shown = match &mut state.projected { None => Cow::Borrowed(delta), Some(projected) => { @@ -135,26 +167,24 @@ impl Fragments { Some((previous, shown)) } - /// The final text of a fragment. - pub fn end(&mut self, fragment: &Fragment, text: &str) -> Update { - let previous = self - .0 - .insert(fragment.clone(), FragmentState { text: text.to_owned(), projected: None }) - .map(|state| state.text) - .unwrap_or_default(); - Update { previous } + /// The final text of a fragment. Returns the text it held. + pub fn end(&mut self, message: &str, part: PartRef, text: &str) -> String { + let fragment = self.key(message, part); + let state = FragmentState { text: text.to_owned(), projected: None }; + self.states.insert(fragment, state).map(|state| state.text).unwrap_or_default() } /// A locally printed text, replayed after the list (`restore`). The deltas that waited for the list may repeat /// its end, as they may a listed text's. - pub fn restore(&mut self, fragment: &Fragment, text: &str) -> Restore { - let Some(current) = self.0.get(fragment) else { - self.0.insert(fragment.clone(), FragmentState::listed(text)); + pub fn restore(&mut self, message: &str, part: PartRef, text: &str) -> Restore { + let fragment = self.key(message, part); + let Some(current) = self.states.get(&fragment) else { + self.states.insert(fragment, FragmentState::listed(text)); return Restore::Append(text.to_owned()); }; if let Some(suffix) = text.strip_prefix(current.text.as_str()) { let suffix = suffix.to_owned(); - self.0.insert(fragment.clone(), FragmentState::listed(text)); + self.states.insert(fragment, FragmentState::listed(text)); return Restore::Append(suffix); } if current.text.starts_with(text) { @@ -168,7 +198,7 @@ impl Fragments { #[derive(Clone, Debug, Default, PartialEq)] pub struct Patch { pub running: Option, - pub status: Option, + pub status: Option>, pub usage: Option>, } @@ -200,9 +230,9 @@ impl Output { Self { commits, ..Self::default() } } - fn patch(running: bool, status: &str) -> Self { + pub(crate) fn patch(running: bool, status: impl Into>) -> Self { Self { - patch: Some(Patch { running: Some(running), status: Some(status.to_owned()), usage: None }), + patch: Some(Patch { running: Some(running), status: Some(status.into()), usage: None }), ..Self::default() } } @@ -237,10 +267,7 @@ pub struct Transcript { pub tools: bool, pub replay: bool, pub replay_limit: u32, - /// The first hydration has not happened yet; its rows are not remembered locally. - pub initial: bool, - pub connected: bool, - pub root_active: bool, + pub link: Link, message_ids: HashSet, errors: HashSet, fragments: Fragments, @@ -258,9 +285,9 @@ pub struct Transcript { local: Vec, /// With tools hidden, a message's text waits for its step to end, and is dropped when the message turns out /// to call tools (`quietText`, `toolMessages`). - quiet: Vec<(String, Vec<(String, String)>)>, + quiet: Vec<(String, Vec<(PartRef, String)>)>, /// With tools hidden, the length of the text a list showed per part: an end buffers only what follows it. - quiet_shown: HashMap, + quiet_shown: HashMap<(String, PartRef), usize>, tool_messages: HashSet, /// The session's directory, which tool paths are shown relative to. pub directory: Option, @@ -279,6 +306,15 @@ pub struct Transcript { wait: Option, } +/// Where the stream stands. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Link { + /// The first hydration has not happened yet; its rows are not remembered locally. + Initial, + Connected, + Disconnected, +} + /// A resize replay in flight. Its read applies only while it holds the current ticket. #[derive(Debug)] struct Relist { @@ -331,9 +367,7 @@ impl Transcript { tools, replay, replay_limit: replay_limit.unwrap_or(DEFAULT_REPLAY_LIMIT), - initial: true, - connected: false, - root_active: false, + link: Link::Initial, message_ids: HashSet::new(), errors: HashSet::new(), fragments: Fragments::default(), @@ -410,7 +444,7 @@ impl Transcript { /// The first or a reconnecting hydration (`hydrate`): every listed message, shown unless this is the first /// hydration and replay is off. A reconnect's rows are remembered as live rows are. pub fn hydrate(&mut self, messages: &[SessionMessageInfo], active: bool) -> Output { - let reconnect = !self.initial; + let reconnect = self.link != Link::Initial; let output = self.list(messages, active); if reconnect { self.remember_all(&output.commits); @@ -430,19 +464,13 @@ impl Transcript { } fn list(&mut self, messages: &[SessionMessageInfo], active: bool) -> Output { - let render = !self.initial || self.replay; + let render = self.link != Link::Initial || self.replay; let mut output = Output::default(); for message in messages { output.extend(self.message(message, render)); } - self.root_active = active; - self.initial = false; - self.connected = true; - output.patch = Some(Patch { - running: Some(active), - status: Some(if active { "assistant responding" } else { "" }.to_owned()), - usage: None, - }); + self.link = Link::Connected; + output.extend(Output::patch(active, if active { "assistant responding" } else { "" })); output } @@ -484,7 +512,7 @@ impl Transcript { /// The stream dropped. A resize replay in flight is abandoned, with its events, as TS abandons one of a stale /// attempt: the reconnect lists everything again, and a resize relist must not apply its older list after it. pub fn disconnected(&mut self) { - self.connected = false; + self.link = Link::Disconnected; self.relist = None; } @@ -554,16 +582,15 @@ impl Transcript { return self.image_ids.insert(part_key(message, part)).then(|| commit.clone()); } if let (Some(message), Some(part), EntryKind::Assistant | EntryKind::Reasoning) = - (&commit.message_id, &commit.part_id, commit.kind) + (&commit.message_id, commit.part_id.as_deref().and_then(PartRef::parse), commit.kind) { let prefix = if commit.kind == EntryKind::Reasoning { "Thinking: " } else { "" }; let text = commit.text.strip_prefix(prefix).unwrap_or(&commit.text); - let fragment = Fragment { message_id: message.clone(), part_id: part.clone() }; // The list shows this message without the part, as it shows an aborted compaction. - if self.message_ids.contains(message) && self.fragments.value(&fragment).is_none() { + if self.message_ids.contains(message) && self.fragments.value(message, part).is_none() { return None; } - match self.fragments.restore(&fragment, text) { + match self.fragments.restore(message, part, text) { Restore::Covered => return None, Restore::Append(suffix) if suffix.is_empty() => return None, Restore::Append(suffix) if suffix == text => return Some(commit.clone()), @@ -602,13 +629,13 @@ impl Transcript { /// Commits of a live event remembered as local rows: streamed text is remembered whole. fn remember_all(&mut self, commits: &[Commit]) { - if self.initial || self.relist.is_some() { + if self.link == Link::Initial || self.relist.is_some() { return; } for commit in commits { - let whole = match (&commit.message_id, &commit.part_id, commit.kind) { + let whole = match (&commit.message_id, commit.part_id.as_deref().and_then(PartRef::parse), commit.kind) { (Some(message), Some(part), EntryKind::Assistant | EntryKind::Reasoning) => { - self.fragments.value(&Fragment { message_id: message.clone(), part_id: part.clone() }) + self.fragments.value(message, part) } _ => None, }; @@ -701,7 +728,7 @@ impl Transcript { self.quiet.retain(|(id, _)| id != message); } - fn buffer_quiet(&mut self, message: &str, part: &str, text: &str, replace: bool) { + fn buffer_quiet(&mut self, message: &str, part: PartRef, text: &str, replace: bool) { if text.is_empty() || self.tool_messages.contains(message) { return; } @@ -712,10 +739,10 @@ impl Transcript { &mut self.quiet.last_mut().expect("just pushed").1 } }; - match parts.iter_mut().find(|(id, _)| id == part) { + match parts.iter_mut().find(|(id, _)| *id == part) { Some((_, current)) if replace => *current = text.to_owned(), Some((_, current)) => current.push_str(text), - None => parts.push((part.to_owned(), text.to_owned())), + None => parts.push((part, text.to_owned())), } } @@ -732,7 +759,7 @@ impl Transcript { .map(|(part, text)| { Commit::new(EntryKind::Assistant, Source::Assistant, Phase::Progress, text) .message(message) - .part_id(part) + .part_id(part.to_string()) }) .collect() } @@ -780,7 +807,7 @@ impl Transcript { let ready = name != "websearch" || state.metadata.get("provider").is_some_and(Value::is_string); if render && !started && ready { result.commits.push(crate::tools::commit(part, message, Phase::Start, None, directory, version)); - result.extend(Output::patch(true, &format!("running {name}"))); + result.extend(Output::patch(true, format!("running {name}"))); } if render && !delta.is_empty() { result.commits.push(crate::tools::commit( @@ -901,36 +928,25 @@ impl Transcript { if visible { return Output::default(); } - let header = || { - let mut commit = Commit::new(EntryKind::System, Source::System, Phase::Start, "Compaction") - .message(id) - .part_id("compaction:header"); - commit.compaction = true; - commit - }; if let SessionMessageCompaction::Failed(failed) = message { if !render || failed.error.r#type == "aborted" { return Output::default(); } self.errors.insert(id.to_owned()); let error = Commit::error(&failed.error.message).message(id).part_id("compaction:error"); - return Output::commits(vec![header(), error]); + return Output::commits(vec![compaction_header(id), error]); } let show = render || matches!(message, SessionMessageCompaction::Running(_)); - let fragment = Fragment { message_id: id.to_owned(), part_id: "compaction:summary".into() }; - self.fragments.project(&fragment, summary, show); + self.fragments.project(id, PartRef::Summary, summary, show); if !show { return Output::default(); } - let part = |text: &str, phase| { - Commit::new(EntryKind::Assistant, Source::Assistant, phase, text).message(id).part_id("compaction:summary") - }; - let mut commits = vec![header()]; + let mut commits = vec![compaction_header(id)]; if !summary.is_empty() { - commits.push(part(summary, Phase::Progress)); + commits.push(compaction_summary(id, summary, Phase::Progress)); } if completed { - commits.push(part("", Phase::Final)); + commits.push(compaction_summary(id, "", Phase::Final)); } Output::commits(commits) } @@ -948,29 +964,29 @@ impl Transcript { match item { ContentItem::Text(part) => { let text = part.text.as_str(); - let fragment = Fragment::new(id, "text", text_ordinal); + let fragment = PartRef::Text(text_ordinal); text_ordinal += 1; let visible = render && (self.tools || !has_tools); - let update = self.fragments.project(&fragment, text, visible); - if visible && text.len() > update.previous.len() { - commits.push(text_commit(&fragment, suffix(text, &update.previous))); + let previous = self.fragments.project(id, fragment, text, visible); + if visible && text.len() > previous.len() { + commits.push(text_commit(id, fragment, suffix(text, &previous))); } if visible && !self.tools { - self.quiet_shown.insert(part_key(id, &fragment.part_id), text.len()); + self.quiet_shown.insert((id.to_owned(), fragment), text.len()); } } ContentItem::Reasoning(part) => { let text = part.text.as_str(); - let fragment = Fragment::new(id, "reasoning", reasoning_ordinal); + let fragment = PartRef::Reasoning(reasoning_ordinal); reasoning_ordinal += 1; - let update = self.fragments.project(&fragment, text, render); - if render && self.thinking && text.len() > update.previous.len() { - let delta = if update.previous.is_empty() { + let previous = self.fragments.project(id, fragment, text, render); + if render && self.thinking && text.len() > previous.len() { + let delta = if previous.is_empty() { format!("Thinking: {text}") } else { - suffix(text, &update.previous).to_owned() + suffix(text, &previous).to_owned() }; - commits.push(reasoning_commit(&fragment, delta)); + commits.push(reasoning_commit(id, fragment, delta)); } } ContentItem::Tool(tool) => commits.extend(self.render_tool(id, tool, render).commits), @@ -1051,38 +1067,38 @@ impl Transcript { V2Event::SessionTextDelta(delta) => { let data = &delta.data; let message = data.assistant_message_id.as_str(); - let fragment = Fragment::new(message, "text", data.ordinal as u64); - let Some((_, shown)) = self.fragments.delta(&fragment, &data.delta) else { + let fragment = PartRef::Text(data.ordinal as u32); + let Some((_, shown)) = self.fragments.delta(message, fragment, &data.delta) else { return Output::default(); }; if !self.tools { - self.buffer_quiet(message, &fragment.part_id, &shown, false); + self.buffer_quiet(message, fragment, &shown, false); return Output::default(); } - Output::commits(vec![text_commit(&fragment, shown)]) + Output::commits(vec![text_commit(message, fragment, shown)]) } V2Event::SessionTextEnded(ended) => { let data = &ended.data; let message = data.assistant_message_id.as_str(); - let fragment = Fragment::new(message, "text", data.ordinal as u64); - let update = self.fragments.end(&fragment, &data.text); + let fragment = PartRef::Text(data.ordinal as u32); + let previous = self.fragments.end(message, fragment, &data.text); if !self.tools { - let shown = self.quiet_shown.get(&part_key(message, &fragment.part_id)).copied().unwrap_or(0); - self.buffer_quiet(message, &fragment.part_id, data.text.get(shown..).unwrap_or_default(), true); + let shown = self.quiet_shown.get(&(message.to_owned(), fragment)).copied().unwrap_or(0); + self.buffer_quiet(message, fragment, data.text.get(shown..).unwrap_or_default(), true); return Output::default(); } - if data.text.len() <= update.previous.len() { + if data.text.len() <= previous.len() { return Output::default(); } - Output::commits(vec![text_commit(&fragment, suffix(&data.text, &update.previous))]) + Output::commits(vec![text_commit(message, fragment, suffix(&data.text, &previous))]) } V2Event::SessionReasoningDelta(delta) => { let data = &delta.data; - let fragment = Fragment::new(data.assistant_message_id.as_str(), "reasoning", data.ordinal as u64); - match self.fragments.delta(&fragment, &data.delta) { + let (message, fragment) = (data.assistant_message_id.as_str(), PartRef::Reasoning(data.ordinal as u32)); + match self.fragments.delta(message, fragment, &data.delta) { Some((previous, shown)) if self.thinking => { let text = if previous == 0 { format!("Thinking: {shown}") } else { shown.into_owned() }; - Output::commits(vec![reasoning_commit(&fragment, text)]) + Output::commits(vec![reasoning_commit(message, fragment, text)]) } _ => Output::default(), } @@ -1090,17 +1106,14 @@ impl Transcript { V2Event::SessionReasoningEnded(ended) => { let data = &ended.data; let text = data.text.as_str(); - let fragment = Fragment::new(data.assistant_message_id.as_str(), "reasoning", data.ordinal as u64); - let update = self.fragments.end(&fragment, text); - if !self.thinking || text.len() <= update.previous.len() { + let (message, fragment) = (data.assistant_message_id.as_str(), PartRef::Reasoning(data.ordinal as u32)); + let previous = self.fragments.end(message, fragment, text); + if !self.thinking || text.len() <= previous.len() { return Output::default(); } - let text = if update.previous.is_empty() { - format!("Thinking: {text}") - } else { - suffix(text, &update.previous).to_owned() - }; - Output::commits(vec![reasoning_commit(&fragment, text)]) + let text = + if previous.is_empty() { format!("Thinking: {text}") } else { suffix(text, &previous).to_owned() }; + Output::commits(vec![reasoning_commit(message, fragment, text)]) } V2Event::SessionStepEnded(ended) => { let data = &ended.data; @@ -1131,13 +1144,11 @@ impl Transcript { Output::commits(commits) } V2Event::SessionExecutionStarted(_) => { - self.root_active = true; Output { patch: Some(Patch { running: Some(true), ..Patch::default() }), ..Output::default() } } V2Event::SessionExecutionSucceeded(_) | V2Event::SessionExecutionFailed(_) | V2Event::SessionExecutionInterrupted(_) => { - self.root_active = false; let messages: Vec = self.quiet.iter().map(|(id, _)| id.clone()).collect(); let commits = messages.iter().flat_map(|id| self.flush_quiet(id)).collect(); if let Some(wait) = &mut self.wait { @@ -1224,21 +1235,19 @@ impl Transcript { } V2Event::SessionCompactionDelta(delta) => { let mut output = footer(); - let Some(message) = self.active_compaction.clone() else { return output }; - let fragment = Fragment { message_id: message.clone(), part_id: "compaction:summary".into() }; - if let Some((_, shown)) = self.fragments.delta(&fragment, &delta.data.text) { - output.commits.push(compaction_summary(&message, &shown, Phase::Progress)); + let Some(message) = self.active_compaction.as_deref() else { return output }; + if let Some((_, shown)) = self.fragments.delta(message, PartRef::Summary, &delta.data.text) { + output.commits.push(compaction_summary(message, &shown, Phase::Progress)); } output } V2Event::SessionCompactionEnded(ended) => { let mut output = footer(); let Some(message) = self.active_compaction.take() else { return output }; - let fragment = Fragment { message_id: message.clone(), part_id: "compaction:summary".into() }; let text = &ended.data.text; - let update = self.fragments.end(&fragment, text); - if text.len() > update.previous.len() { - output.commits.push(compaction_summary(&message, suffix(text, &update.previous), Phase::Progress)); + let previous = self.fragments.end(&message, PartRef::Summary, text); + if text.len() > previous.len() { + output.commits.push(compaction_summary(&message, suffix(text, &previous), Phase::Progress)); } output.commits.push(compaction_summary(&message, "", Phase::Final)); output @@ -1280,7 +1289,7 @@ impl Transcript { }; let tool = |id: &str, name: String, state: SessionMessageAssistantToolState, time| SessionMessageAssistantTool { - r#type: "tool".into(), + r#type: tag::Tool, id: id.to_owned(), name, executed: None, @@ -1297,7 +1306,7 @@ impl Transcript { V2Event::SessionToolInputStarted(started) => { let data = &started.data; let state = ToolPartState::Streaming(SessionMessageToolStateStreaming { - status: "streaming".into(), + status: tag::Streaming, input: String::new(), }); tool(&data.id, data.name.clone(), state, time(started.created, None, None)) @@ -1323,7 +1332,7 @@ impl Transcript { } let part = current(&data.id); let state = ToolPartState::Running(SessionMessageToolStateRunning { - status: "running".into(), + status: tag::Running, input: data.input.clone(), metadata: Default::default(), }); @@ -1341,7 +1350,7 @@ impl Transcript { } let part = current(&data.id); let state = ToolPartState::Running(SessionMessageToolStateRunning { - status: "running".into(), + status: tag::Running, input: input_of(&part), metadata: data.metadata.clone(), }); @@ -1357,7 +1366,7 @@ impl Transcript { let data = &success.data; let part = current(&data.id); let state = ToolPartState::Completed(SessionMessageToolStateCompleted { - status: "completed".into(), + status: tag::Completed, input: input_of(&part), content: data.content.clone(), metadata: data.metadata.clone(), @@ -1369,7 +1378,7 @@ impl Transcript { let data = &failed.data; let part = current(&data.id); let state = ToolPartState::Error(SessionMessageToolStateError { - status: "error".into(), + status: tag::Error, input: input_of(&part), error: data.error.clone(), content: data.content.clone(), @@ -1402,7 +1411,7 @@ impl Transcript { None => previous, }; SessionMessageAssistantTool { - r#type: "tool".into(), + r#type: tag::Tool, id: id.to_owned(), name: part.as_ref().map_or("tool".into(), |part| part.name.clone()), executed: None, @@ -1478,16 +1487,16 @@ fn suffix<'a>(text: &'a str, previous: &str) -> &'a str { text.get(previous.len()..).unwrap_or_default() } -fn text_commit(fragment: &Fragment, text: impl Into) -> Commit { +pub(crate) fn text_commit(message: &str, part: PartRef, text: impl Into) -> Commit { Commit::new(EntryKind::Assistant, Source::Assistant, Phase::Progress, text) - .message(&fragment.message_id) - .part_id(&fragment.part_id) + .message(message) + .part_id(part.to_string()) } -fn reasoning_commit(fragment: &Fragment, text: impl Into) -> Commit { +pub(crate) fn reasoning_commit(message: &str, part: PartRef, text: impl Into) -> Commit { Commit::new(EntryKind::Reasoning, Source::Reasoning, Phase::Progress, text) - .message(&fragment.message_id) - .part_id(&fragment.part_id) + .message(message) + .part_id(part.to_string()) } /// `errorMessage`: the message, else a fallback (the structured error has no `_tag`). @@ -2355,7 +2364,7 @@ mod tests { /// `Mini::replay_on_resize`. fn resize(&mut self) { - if !self.transcript.replay || !self.transcript.connected { + if !self.transcript.replay || self.transcript.link != Link::Connected { return; } if self.transcript.replaying() { diff --git a/packages/cli-rs/crates/mini/src/shell.rs b/packages/cli-rs/crates/mini/src/shell.rs index fda668755b2..2757494b3c2 100644 --- a/packages/cli-rs/crates/mini/src/shell.rs +++ b/packages/cli-rs/crates/mini/src/shell.rs @@ -1,6 +1,7 @@ //! Paints the footer before resolving the session. On exit, flush queued rows, leave split mode and place the shell //! below the transcript. +use std::borrow::Cow; use std::time::Instant; use opencode_local::cli_config::{CliConfig, MiniWorkSpinner, NewLocation, ThemeMode as ConfigMode, Visibility}; @@ -18,7 +19,7 @@ use crate::prelude::*; use crate::prompt::queue::{Queue, Submitted, Work}; use crate::prompt::status::{self, mono_shortcut}; use crate::prompt::{Delivery, Hooks, PROMPT_MAX_ROWS, Prompt, RunPrompt}; -use crate::replay::{self, Envelope, Incoming, Output, Transcript}; +use crate::replay::{self, Envelope, Incoming, Link, Output, Transcript}; use crate::scrollback::{Flags, Writer}; use crate::settings::{Change, MiniSettings}; use crate::signals::{self, Trace}; @@ -101,7 +102,7 @@ pub fn run(input: Input) -> error::Result<()> { animations: input.config.animations != Some(false), providers: RefCell::new(None), variants: RefCell::new(Vec::new()), - catalog_refresh: Cell::new(None), + catalog_refresh: Cell::new(Refresh::Idle), preferences: ModelPreferences::new(&input.paths.state), config_store: CliConfig::new(&input.paths), queue: RefCell::new(Queue::default()), @@ -209,7 +210,7 @@ struct Session { #[derive(Debug, Default)] struct State { running: bool, - status: String, + status: Cow<'static, str>, notice: String, notice_timer: Option, model: Option<(String, Option, Option)>, @@ -236,6 +237,13 @@ struct ShellWait { grace: Option, } +#[derive(Clone, Copy, PartialEq, Eq)] +enum Refresh { + Idle, + Running, + RunningThenAgain, +} + struct Mini { app: App, client: Client, @@ -256,7 +264,7 @@ struct Mini { /// The current model's variants (`state.variants`). variants: RefCell>, /// A catalog refresh in flight, and whether another follows it (`requestCatalogRefresh`). - catalog_refresh: Cell>, + catalog_refresh: Cell, preferences: ModelPreferences, config_store: CliConfig, queue: RefCell, @@ -331,7 +339,9 @@ impl Mini { mini.paint_status(); }))), status: Some(Box::new(bind!(self, |mini, text| mini.set_notice(text)))), - blocker: Some(Box::new(bind!(self, |mini, text| mini.patch(|state| state.status = text.to_owned())))), + blocker: Some( + Box::new(bind!(self, |mini, text| mini.patch(|state| state.status = text.to_owned().into()))), + ), summary: Some(Box::new(bind!(self, |mini| mini.summary()))), agent: Some(Box::new(bind!(self, |mini, id| mini.select_agent(id)))), clear_screen: Some(Box::new(with(|mini| mini.clear_screen()))), @@ -478,7 +488,7 @@ impl Mini { } mini.footers.models_changed(); mini.paint_status(); - if mini.transcript.borrow().as_ref().is_some_and(|transcript| transcript.connected) { + if mini.transcript.borrow().as_ref().is_some_and(|transcript| transcript.link == Link::Connected) { mini.send_waiting(cx); } }); @@ -767,7 +777,7 @@ impl Mini { Incoming::Hydrated { messages, active, inbox, .. } => { let running = active.contains(&transcript.session_id); self.trace("recv.hydrate", json!({ "messages": messages.len(), "active": running })); - let reconnect = !transcript.initial; + let reconnect = transcript.link != Link::Initial; transcript.inbox(&inbox); let output = self.blocked(transcript.hydrate(&messages, running)); hydrated = Some((messages, active, inbox, reconnect)); @@ -791,19 +801,12 @@ impl Mini { Incoming::Disconnected(error) => { self.trace("recv.reconnect", json!({ "error": error })); transcript.disconnected(); - Output { - patch: Some(replay::Patch { - running: Some(true), - status: Some("reconnecting".into()), - usage: None, - }), - ..Output::default() - } + Output::patch(true, "reconnecting") } } }; - let connected = - output.patch.is_some() && self.transcript.borrow().as_ref().is_some_and(|transcript| transcript.connected); + let connected = output.patch.is_some() + && self.transcript.borrow().as_ref().is_some_and(|transcript| transcript.link == Link::Connected); let relist = output.relist; self.output(cx, output); let session = self.transcript.borrow().as_ref().map(|transcript| transcript.session_id.clone()); @@ -852,12 +855,12 @@ impl Mini { /// `requestCatalogRefresh`: reads the agents, references, commands, and providers again, then the default /// model when none is chosen. A request while one runs queues one more. fn refresh_catalog(self: &Rc) { - if self.catalog_refresh.get().is_some() { - self.catalog_refresh.set(Some(true)); + if self.catalog_refresh.get() != Refresh::Idle { + self.catalog_refresh.set(Refresh::RunningThenAgain); return; } let Some(directory) = self.session.borrow().as_ref().map(|session| session.directory.clone()) else { return }; - self.catalog_refresh.set(Some(false)); + self.catalog_refresh.set(Refresh::Running); let client = self.client.clone(); let mini = self.clone(); let read = directory.clone(); @@ -870,7 +873,7 @@ impl Mini { .await }, move |_, (catalog, providers)| { - let queued = mini.catalog_refresh.take() == Some(true); + let queued = mini.catalog_refresh.replace(Refresh::Idle) == Refresh::RunningThenAgain; if mini.state.borrow().closed || mini.session.borrow().as_ref().is_none_or(|session| session.directory != directory) { @@ -904,7 +907,7 @@ impl Mini { /// A hydration's idle status names the request shown (`blockerStatus`). fn blocked(&self, mut output: Output) -> Output { if let Some(patch) = output.patch.as_mut().filter(|patch| patch.running == Some(false)) { - patch.status = Some(self.footers.blocker_status().to_owned()); + patch.status = Some(self.footers.blocker_status().into()); } output } @@ -1021,7 +1024,7 @@ impl Mini { /// The stream is connected and the model catalog loaded once, so a prompt uses the model's variant. fn ready(&self) -> bool { self.providers.borrow().is_some() - && self.transcript.borrow().as_ref().is_some_and(|transcript| transcript.connected) + && self.transcript.borrow().as_ref().is_some_and(|transcript| transcript.link == Link::Connected) } fn send_waiting(self: &Rc, _cx: &mut Cx<'_>) { @@ -1076,16 +1079,10 @@ impl Mini { return; } self.patch(|state| state.turn = false); - self.output( - cx, - Output { - patch: Some(replay::Patch { running: Some(false), status: Some(String::new()), usage: None }), - ..Output::default() - }, - ); + self.output(cx, Output::patch(false, "")); } - fn sending(&self, status: &str) { + fn sending(&self, status: &'static str) { self.patch(|state| { state.running = true; state.turn = true; @@ -1665,7 +1662,7 @@ impl Mini { let (session, ticket) = { let mut transcript = self.transcript.borrow_mut(); let Some(transcript) = transcript.as_mut() else { return }; - if !self.input.replay || !transcript.connected { + if !self.input.replay || transcript.link != Link::Connected { return; } // The last size wins: a resize during a replay replays once more after it (`queuedResizeReplay`). diff --git a/packages/cli-rs/crates/mini/src/subagents.rs b/packages/cli-rs/crates/mini/src/subagents.rs index 3f3c4585e77..fcd6bc8a294 100644 --- a/packages/cli-rs/crates/mini/src/subagents.rs +++ b/packages/cli-rs/crates/mini/src/subagents.rs @@ -8,13 +8,13 @@ use opencode_api::generated::{ FormInfo, PromptFileAttachment, SessionInboxInfo, SessionInboxItem, SessionInfo, SessionMessageAssistantContentItem as ContentItem, SessionMessageAssistantToolState as ToolPartState, SessionMessageAssistantToolTime, SessionMessageToolStateCompleted, SessionMessageToolStateError, - SessionMessageToolStateRunning, SessionMessageToolStateStreaming, + SessionMessageToolStateRunning, SessionMessageToolStateStreaming, tag, }; -use opencode_ui::tool_info::{canonical_tool_name, titlecase, tool_display_content, tool_output_text}; +use opencode_ui::tool_info::{ToolKind, titlecase, tool_display_content, tool_output_text}; use crate::footers::permission::Request; use crate::prelude::*; -use crate::replay::{Fragment, Fragments, session_of, user_image_commits}; +use crate::replay::{Fragments, PartRef, reasoning_commit, session_of, text_commit, user_image_commits}; use crate::scrollback::{EntryKind, Phase, Source}; /// `CHILD_MESSAGE_LIMIT`: the messages a child's transcript lists. @@ -187,16 +187,15 @@ impl Child { self.tools.insert(key, part); return; } - let name = canonical_tool_name(&part.name).to_owned(); - let output = tool_output_text(&name, &tool_display_content(&part.state)); + let output = tool_output_text(&part.name, &tool_display_content(&part.state)); let commit = |phase, value: Option<&str>| crate::tools::commit(&part, message, phase, value, directory, 0); if let ToolPartState::Running(state) = &part.state { let provider = |state: &SessionMessageToolStateRunning| state.metadata.get("provider").is_some_and(Value::is_string); - let ready = name != "websearch" || provider(state); + let ready = ToolKind::of(&part.name) != ToolKind::WebSearch || provider(state); let current = self.tools.get(&key); let awaiting = current.is_some_and(|current| { - canonical_tool_name(¤t.name) == "websearch" + ToolKind::of(¤t.name) == ToolKind::WebSearch && matches!(¤t.state, ToolPartState::Running(state) if !provider(state)) }); let fresh = current.is_none_or(|current| matches!(current.state, ToolPartState::Streaming(_))); @@ -248,17 +247,17 @@ impl Child { for item in &assistant.content { match item { ContentItem::Text(part) => { - let fragment = Fragment::new(id, "text", text_ordinal); + let fragment = PartRef::Text(text_ordinal); text_ordinal += 1; - self.fragments.project(&fragment, &part.text, true); - self.set_frame(fragment_key(&fragment), text_commit(&fragment, part.text.clone())); + self.fragments.project(id, fragment, &part.text, true); + self.set_frame(fragment_key(id, fragment), text_commit(id, fragment, part.text.clone())); } ContentItem::Reasoning(part) => { - let fragment = Fragment::new(id, "reasoning", reasoning_ordinal); + let fragment = PartRef::Reasoning(reasoning_ordinal); reasoning_ordinal += 1; - self.fragments.project(&fragment, &part.text, true); + self.fragments.project(id, fragment, &part.text, true); if thinking { - self.set_frame(fragment_key(&fragment), reasoning_commit(&fragment, &part.text)); + self.set_frame(fragment_key(id, fragment), thinking_commit(id, fragment, &part.text)); } } ContentItem::Tool(tool) => self.tool(tool.clone(), id, directory), @@ -480,7 +479,7 @@ impl Tracker { pub fn main(&mut self, event: &V2Event) -> Vec { let (message, id, metadata, created, success) = match event { V2Event::SessionToolInputStarted(started) => { - if canonical_tool_name(&started.data.name) == "subagent" { + if ToolKind::of(&started.data.name) == ToolKind::Subagent { let key = source_key(started.data.assistant_message_id.as_str(), &started.data.id); self.calls.insert(key, None); } @@ -732,7 +731,7 @@ impl Tracker { /// `mainTool`: a listed subagent call of the parent. fn main_tool(&mut self, tool: &SessionMessageAssistantTool) { - if canonical_tool_name(&tool.name) != "subagent" { + if ToolKind::of(&tool.name) != ToolKind::Subagent { return; } let (input, metadata) = match &tool.state { @@ -839,37 +838,38 @@ impl Tracker { } V2Event::SessionTextDelta(delta) => { let data = &delta.data; - let fragment = Fragment::new(data.assistant_message_id.as_str(), "text", data.ordinal as u64); - if child.fragments.delta(&fragment, &data.delta).is_some() { - let text = child.fragments.value(&fragment).unwrap_or_default().to_owned(); - child.set_frame(fragment_key(&fragment), text_commit(&fragment, text)); + let (message, fragment) = (data.assistant_message_id.as_str(), PartRef::Text(data.ordinal as u32)); + if child.fragments.delta(message, fragment, &data.delta).is_some() { + let text = child.fragments.value(message, fragment).unwrap_or_default().to_owned(); + child.set_frame(fragment_key(message, fragment), text_commit(message, fragment, text)); child.touch(delta.created); detail = true; } } V2Event::SessionTextEnded(ended) => { let data = &ended.data; - let fragment = Fragment::new(data.assistant_message_id.as_str(), "text", data.ordinal as u64); - child.fragments.end(&fragment, &data.text); - child.set_frame(fragment_key(&fragment), text_commit(&fragment, data.text.clone())); + let (message, fragment) = (data.assistant_message_id.as_str(), PartRef::Text(data.ordinal as u32)); + child.fragments.end(message, fragment, &data.text); + child.set_frame(fragment_key(message, fragment), text_commit(message, fragment, data.text.clone())); child.touch(ended.created); detail = true; } V2Event::SessionReasoningDelta(delta) => { let data = &delta.data; - let fragment = Fragment::new(data.assistant_message_id.as_str(), "reasoning", data.ordinal as u64); - if child.fragments.delta(&fragment, &data.delta).is_some() && thinking { - let text = child.fragments.value(&fragment).unwrap_or_default().to_owned(); - child.set_frame(fragment_key(&fragment), reasoning_commit(&fragment, &text)); + let (message, fragment) = (data.assistant_message_id.as_str(), PartRef::Reasoning(data.ordinal as u32)); + if child.fragments.delta(message, fragment, &data.delta).is_some() && thinking { + let text = child.fragments.value(message, fragment).unwrap_or_default(); + let commit = thinking_commit(message, fragment, text); + child.set_frame(fragment_key(message, fragment), commit); detail = true; } } V2Event::SessionReasoningEnded(ended) => { let data = &ended.data; - let fragment = Fragment::new(data.assistant_message_id.as_str(), "reasoning", data.ordinal as u64); - child.fragments.end(&fragment, &data.text); + let (message, fragment) = (data.assistant_message_id.as_str(), PartRef::Reasoning(data.ordinal as u32)); + child.fragments.end(message, fragment, &data.text); if thinking { - child.set_frame(fragment_key(&fragment), reasoning_commit(&fragment, &data.text)); + child.set_frame(fragment_key(message, fragment), thinking_commit(message, fragment, &data.text)); detail = true; } } @@ -878,7 +878,7 @@ impl Tracker { let message = data.assistant_message_id.as_str(); if !child.finished.contains(&source_key(message, &data.id)) { let state = ToolPartState::Streaming(SessionMessageToolStateStreaming { - status: "streaming".into(), + status: tag::Streaming, input: String::new(), }); let part = tool_part(&data.id, data.name.clone(), state, time(started.created, None, None)); @@ -914,7 +914,7 @@ impl Tracker { let name = current.map_or_else(|| "tool".to_owned(), |part| part.name.clone()); let created = current.map_or(called.created, |part| part.time.created); let state = ToolPartState::Running(SessionMessageToolStateRunning { - status: "running".into(), + status: tag::Running, input: data.input.clone(), metadata: IndexMap::new(), }); @@ -933,7 +933,7 @@ impl Tracker { if !child.finished.contains(&key) { let current = child.tools.get(&key).cloned(); let state = ToolPartState::Running(SessionMessageToolStateRunning { - status: "running".into(), + status: tag::Running, input: input_of(current.as_ref()), metadata: data.metadata.clone(), }); @@ -966,7 +966,7 @@ impl Tracker { let input = input_of(current.as_ref()); let state = match event { V2Event::SessionToolFailed(failed) => ToolPartState::Error(SessionMessageToolStateError { - status: "error".into(), + status: tag::Error, input, error: failed.data.error.clone(), content: failed.data.content.clone(), @@ -974,7 +974,7 @@ impl Tracker { }), V2Event::SessionToolSuccess(success) => { ToolPartState::Completed(SessionMessageToolStateCompleted { - status: "completed".into(), + status: tag::Completed, input, content: success.data.content.clone(), metadata: success.data.metadata.clone(), @@ -1094,24 +1094,16 @@ fn source_key(message: &str, id: &str) -> String { format!("{message}\u{0}{id}") } -fn fragment_key(fragment: &Fragment) -> String { - source_key(&fragment.message_id, &fragment.part_id) +fn fragment_key(message: &str, part: PartRef) -> String { + format!("{message}\u{0}{part}") } fn prompt(text: &str, files: Option<&[PromptFileAttachment]>) -> Prompt { Prompt { text: text.to_owned(), files: files.unwrap_or_default().to_vec() } } -fn text_commit(fragment: &Fragment, text: String) -> Commit { - Commit::new(EntryKind::Assistant, Source::Assistant, Phase::Progress, text) - .message(&fragment.message_id) - .part_id(&fragment.part_id) -} - -fn reasoning_commit(fragment: &Fragment, text: &str) -> Commit { - Commit::new(EntryKind::Reasoning, Source::Reasoning, Phase::Progress, format!("Thinking: {text}")) - .message(&fragment.message_id) - .part_id(&fragment.part_id) +fn thinking_commit(message: &str, part: PartRef, text: &str) -> Commit { + reasoning_commit(message, part, format!("Thinking: {text}")) } fn to_value(value: &impl serde::Serialize) -> Value { @@ -1134,7 +1126,7 @@ fn tool_part( time: SessionMessageAssistantToolTime, ) -> SessionMessageAssistantTool { SessionMessageAssistantTool { - r#type: "tool".into(), + r#type: tag::Tool, id: id.to_owned(), name, executed: None, diff --git a/packages/cli-rs/crates/mini/src/tools.rs b/packages/cli-rs/crates/mini/src/tools.rs index 0e479b5837a..293e5e1d3cd 100644 --- a/packages/cli-rs/crates/mini/src/tools.rs +++ b/packages/cli-rs/crates/mini/src/tools.rs @@ -3,8 +3,10 @@ use opencode_api::generated::{SessionMessageAssistantToolState as State, ToolContent}; use opencode_ui::tool_info::{ - Todo, TodoStatus, canonical_tool_name, normalize_input, normalize_metadata, parse_todos, primitive_input_summary, - todo_marker, tool_display_content, tool_display_metadata, tool_output_text, tool_path, web_search_provider_label, + LspInput, QuestionInput, SearchInput, ShellInput, SkillInput, SubagentInput, Todo, TodoInput, TodoStatus, + ToolInput, ToolKind, WebFetchInput, WebSearchInput, WriteInput, canonical_tool_name, normalize_metadata, + primitive_input_summary, todo_marker, tool_display_content, tool_display_metadata, tool_output_text, tool_path, + web_search_provider_label, }; use opentui::input::strip_ansi_sequences; use opentui::widget::{Code, DiffColors, DiffView, LineNumbers}; @@ -33,20 +35,23 @@ pub struct DiffItem { /// `ToolFrame`: a tool part normalized for display. #[derive(Clone, Debug, Default)] -struct Frame { +struct Frame<'a> { directory: Option, raw: String, name: String, - input: Map, + kind: ToolKind, + input: ToolInput<'a>, meta: Map, - status: String, + /// `None` for no part; streaming counts as running. + status: Option, error: String, output: String, start: Option, end: Option, } -fn frame(part: &SessionMessageAssistantTool, directory: Option<&str>) -> Frame { +fn frame<'a>(part: &'a SessionMessageAssistantTool, directory: Option<&str>) -> Frame<'a> { + let kind = ToolKind::of(&part.name); let name = canonical_tool_name(&part.name).to_owned(); let directory = directory.map(str::to_owned); if let State::Streaming(state) = &part.state { @@ -54,19 +59,20 @@ fn frame(part: &SessionMessageAssistantTool, directory: Option<&str>) -> Frame { directory, raw: state.input.clone(), name, - status: "streaming".into(), + kind, + status: Some(ToolState::Running), start: Some(part.time.created), ..Frame::default() }; } let output = tool_output_text(&name, &tool_display_content(&part.state)); - let state = serde_json::to_value(&part.state).unwrap_or_default(); Frame { directory, raw: output.clone(), - input: normalize_input(&name, state.get("input")), - meta: normalize_metadata(&name, tool_display_metadata(&part.state)), - status: part.state.tag().to_owned(), + kind, + input: ToolInput::of(&part.state), + meta: normalize_metadata(kind, tool_display_metadata(&part.state)), + status: state_of(&part.state), error: match &part.state { State::Error(state) => state.error.message.clone(), _ => String::new(), @@ -79,41 +85,36 @@ fn frame(part: &SessionMessageAssistantTool, directory: Option<&str>) -> Frame { } /// `toolFrame`: a commit's frame, with the commit's own state and text taking precedence. -fn tool_frame(commit: &Commit, raw: &str) -> Frame { +fn tool_frame<'a>(commit: &'a Commit, raw: &str) -> Frame<'a> { let current = commit.part.as_ref().map(|part| frame(part, commit.directory.as_deref())).unwrap_or_default(); let name = commit.tool.as_deref().filter(|name| !name.is_empty()).unwrap_or(match current.name.as_str() { "" => "tool", name => name, }); - let status = match commit.tool_state { - Some(state) => state_name(state).to_owned(), - None => current.status.clone(), - }; let error = commit.tool_error.clone().unwrap_or(current.error.clone()).trim().to_owned(); Frame { directory: commit.directory.clone(), raw: raw.to_owned(), name: canonical_tool_name(name).to_owned(), + kind: ToolKind::of(name), output: if commit.part.is_some() { current.output.clone() } else { raw.to_owned() }, - status, + status: commit.tool_state.or(current.status), error, ..current } } -fn state_name(state: ToolState) -> &'static str { - match state { - ToolState::Running => "running", - ToolState::Completed => "completed", - ToolState::Error => "error", +/// A part's state by its tag: streaming, and any state this client does not know, counts as running. +fn state_of(state: &State) -> Option { + match state.tag() { + "" => None, + "completed" => Some(ToolState::Completed), + "error" => Some(ToolState::Error), + _ => Some(ToolState::Running), } } -impl Frame { - fn input(&self, key: &str) -> &str { - self.input.get(key).and_then(Value::as_str).unwrap_or_default() - } - +impl Frame<'_> { fn path(&self, input: &str, home: bool) -> String { let home = home.then(opencode_local::paths::home); tool_path(input, self.directory.as_deref(), home.as_deref()) @@ -140,79 +141,64 @@ struct ToolView { snap: bool, } -/// The tools of `TOOL_RULES`. -const KNOWN: [&str; 17] = [ - "invalid", - "shell", - "write", - "edit", - "patch", - "batch", - "subagent", - "todowrite", - "question", - "read", - "glob", - "grep", - "list", - "lsp", - "webfetch", - "websearch", - "skill", -]; - -fn tool_view(name: &str) -> ToolView { - let view = |output, final_, snap| ToolView { output, final_, snap }; - match canonical_tool_name(name) { - "invalid" | "shell" | "batch" => view(true, false, false), - "write" | "edit" | "patch" | "subagent" | "todowrite" | "question" => view(false, true, true), - "read" | "glob" | "grep" | "list" | "lsp" | "webfetch" | "websearch" | "skill" => view(false, false, false), - _ => view(true, true, false), +/// `TOOL_RULES`' view of a tool, `None` for a tool without rules. +fn rule(kind: ToolKind) -> Option { + let view = |output, final_, snap| Some(ToolView { output, final_, snap }); + match kind { + ToolKind::Invalid | ToolKind::Shell | ToolKind::Batch => view(true, false, false), + ToolKind::Write | ToolKind::Edit | ToolKind::Patch => view(false, true, true), + ToolKind::Subagent | ToolKind::Todo | ToolKind::Question => view(false, true, true), + ToolKind::Read | ToolKind::Glob | ToolKind::Grep | ToolKind::List | ToolKind::Lsp => view(false, false, false), + ToolKind::WebFetch | ToolKind::WebSearch | ToolKind::Skill => view(false, false, false), + _ => None, } } /// `toolScroll`: the text of one phase, by the tool's rule or the fallback. fn scroll(phase: Phase, frame: &Frame) -> String { let name = frame.name.as_str(); - let rule = match (name, phase) { - ("invalid" | "write" | "edit" | "patch" | "batch" | "subagent" | "todowrite" | "question", Phase::Start) => { + let rule = match (frame.kind, phase) { + (ToolKind::Invalid | ToolKind::Write | ToolKind::Edit | ToolKind::Patch, Phase::Start) => Some(String::new()), + (ToolKind::Batch | ToolKind::Subagent | ToolKind::Todo | ToolKind::Question, Phase::Start) => { Some(String::new()) } - ("shell", Phase::Start) => Some(shell_start(frame)), - ("shell", Phase::Progress) => Some(shell_progress(frame)), - ("shell", Phase::Final) => Some(shell_final(frame)), - ("patch", Phase::Final) => Some(patch_final(frame)), - ("subagent", Phase::Final) => Some(task_final(frame)), - ("question", Phase::Final) => Some(question_final(frame)), - ("read", Phase::Start) => { - let extra = primitive_input_summary(&frame.input, &["path"]); + (ToolKind::Shell, Phase::Start) => Some(shell_start(frame)), + (ToolKind::Shell, Phase::Progress) => Some(shell_progress(frame)), + (ToolKind::Shell, Phase::Final) => Some(shell_final(frame)), + (ToolKind::Patch, Phase::Final) => Some(patch_final(frame)), + (ToolKind::Subagent, Phase::Final) => Some(task_final(frame)), + (ToolKind::Question, Phase::Final) => Some(question_final(frame)), + (ToolKind::Read, Phase::Start) => { + let extra = primitive_input_summary(frame.input.iter(), &["path"]); let tail = if extra.is_empty() { String::new() } else { format!(" {extra}") }; - Some(format!("→ Read {}{tail}", frame.path(frame.input("path"), false)).trim().to_owned()) + Some(format!("→ Read {}{tail}", frame.path(frame.input.legacy_path().text(), false)).trim().to_owned()) } - ("glob" | "grep", Phase::Start) => { - let label = if name == "glob" { "Glob" } else { "Grep" }; - let pattern = frame.input("pattern"); + (kind @ (ToolKind::Glob | ToolKind::Grep), Phase::Start) => { + let label = if kind == ToolKind::Glob { "Glob" } else { "Grep" }; + let pattern = SearchInput(frame.input).pattern().text(); let head = if pattern.is_empty() { format!("✱ {label}") } else { format!("✱ {label} \"{pattern}\"") }; - let dir = frame.input("path"); + let dir = frame.input.path().text(); Some(if dir.is_empty() { head } else { format!("{head} in {}", frame.path(dir, false)) }) } - ("glob", Phase::Final) => Some(if tool_error(frame).is_empty() { fail(frame) } else { tool_error(frame) }), - ("list", Phase::Start) => { - let dir = frame.input("path"); + (ToolKind::Glob, Phase::Final) => { + Some(if tool_error(frame).is_empty() { fail(frame) } else { tool_error(frame) }) + } + (ToolKind::List, Phase::Start) => { + let dir = frame.input.path().text(); Some(if dir.is_empty() { "→ List".into() } else { format!("→ List {}", frame.path(dir, false)) }) } - ("lsp", Phase::Start) => Some(format!("→ {}", lsp_title(frame))), - ("webfetch", Phase::Start) => { - let url = frame.input("url"); + (ToolKind::Lsp, Phase::Start) => Some(format!("→ {}", lsp_title(frame))), + (ToolKind::WebFetch, Phase::Start) => { + let url = WebFetchInput(frame.input).url().text(); Some(if url.is_empty() { "% WebFetch".into() } else { format!("% WebFetch {url}") }) } - ("websearch", Phase::Start) => { + (ToolKind::WebSearch, Phase::Start) => { let title = web_search_provider_label(frame.meta.get("provider").unwrap_or(&Value::Null)); - let query = frame.input("query"); + let query = WebSearchInput(frame.input).query().text(); Some(if query.is_empty() { format!("◈ {title}") } else { format!("◈ {title} \"{query}\"") }) } - ("skill", Phase::Start) => { - let name = [frame.meta.get("name"), frame.input.get("id")] + (ToolKind::Skill, Phase::Start) => { + let name = [frame.meta.get("name"), SkillInput(frame.input).id().value()] .into_iter() .flatten() .find(|name| !name.is_null()) @@ -224,7 +210,7 @@ fn scroll(phase: Phase, frame: &Frame) -> String { }; rule.unwrap_or_else(|| match phase { Phase::Start => { - let extra = primitive_input_summary(&frame.input, &[]); + let extra = primitive_input_summary(frame.input.iter(), &[]); if extra.is_empty() { format!("⚙ {name}") } else { format!("⚙ {name} {extra}") } } Phase::Progress => frame.raw.clone(), @@ -248,10 +234,10 @@ fn tool_error(frame: &Frame) -> String { } fn fallback_final(frame: &Frame) -> String { - if frame.status == "error" { + if frame.status == Some(ToolState::Error) { return fail(frame); } - if !frame.status.is_empty() && frame.status != "completed" { + if frame.status == Some(ToolState::Running) { return frame.raw.trim().to_owned(); } match frame.span() { @@ -261,8 +247,8 @@ fn fallback_final(frame: &Frame) -> String { } fn shell_start(frame: &Frame) -> String { - let command = frame.input("command"); - let workdir = frame.input("workdir"); + let input = ShellInput(frame.input); + let (command, workdir) = (input.command().text(), input.workdir().text()); let formatted = if !workdir.is_empty() && workdir != "." { frame.path(workdir, true) } else { String::new() }; let dir = if formatted == "." { "" } else { formatted.as_str() }; match (command.is_empty(), dir.is_empty()) { @@ -275,7 +261,8 @@ fn shell_start(frame: &Frame) -> String { fn shell_progress(frame: &Frame) -> String { let out = strip_ansi_sequences(&frame.raw); - let command = frame.input("command").trim(); + let input = ShellInput(frame.input); + let command = input.command().text().trim(); let format = |text: &str| { let body = text.trim_start_matches('\n').trim_end_matches('\n'); if body.is_empty() { String::new() } else { format!("\n{body}") } @@ -283,7 +270,7 @@ fn shell_progress(frame: &Frame) -> String { if command.is_empty() { return out.trim_end_matches('\n').to_owned(); } - let raw_dir = frame.input("workdir").trim(); + let raw_dir = input.workdir().text().trim(); let dir = if raw_dir.is_empty() { String::new() } else { frame.path(raw_dir, true) }; let lines: Vec<&str> = out.split('\n').collect(); let first = lines.first().copied().unwrap_or_default().trim(); @@ -302,7 +289,7 @@ fn shell_progress(frame: &Frame) -> String { } fn shell_final(frame: &Frame) -> String { - if frame.status == "error" { + if frame.status == Some(ToolState::Error) { return fail(frame); } let time = frame.span(); @@ -338,7 +325,7 @@ fn patch_title(file: &Map, frame: &Frame) -> String { } fn patch_final(frame: &Frame) -> String { - if frame.status == "error" { + if frame.status == Some(ToolState::Error) { return fail(frame); } let files = frame.files(); @@ -362,25 +349,25 @@ fn patch_final(frame: &Frame) -> String { } fn agent_kind(frame: &Frame, fallback: &str) -> String { - opencode_ui::tool_info::titlecase(match frame.input("agent") { + opencode_ui::tool_info::titlecase(match SubagentInput(frame.input).legacy_agent().text() { "" => fallback, agent => agent, }) } fn task_final(frame: &Frame) -> String { - if frame.status == "error" { + if frame.status == Some(ToolState::Error) { return fail(frame); } let kind = agent_kind(frame, "general"); - match frame.input("description") { + match SubagentInput(frame.input).description().text() { "" => format!("# {kind} Subagent"), row => format!("# {kind} Subagent\n{row}"), } } fn questions(frame: &Frame) -> Vec { - let list = frame.input.get("questions").and_then(Value::as_array).cloned().unwrap_or_default(); + let list = QuestionInput(frame.input).questions().array(); list.iter().map(|item| item.get("question").and_then(Value::as_str).unwrap_or_default().to_owned()).collect() } @@ -414,16 +401,17 @@ fn question_final(frame: &Frame) -> String { } fn lsp_title(frame: &Frame) -> String { - let operation = match frame.input("operation") { + let input = LspInput(frame.input); + let operation = match input.operation().text() { "" => "request", operation => operation, }; - let file = frame.input("path"); + let file = frame.input.legacy_path().text(); if file.is_empty() { return format!("LSP {operation}"); } - let number = |key| frame.input.get(key).filter(|value| value.is_number()).map(opencode_api::js::js_string); - let position = match (number("line"), number("character")) { + let number = |value: Option<&Value>| value.filter(|value| value.is_number()).map(opencode_api::js::js_string); + let position = match (number(input.line().value()), number(input.character().value())) { (Some(line), Some(character)) => format!(":{line}:{character}"), _ => String::new(), }; @@ -431,9 +419,9 @@ fn lsp_title(frame: &Frame) -> String { } fn snapshot(frame: &Frame) -> Option { - match frame.name.as_str() { - "write" => { - let (file, content) = (frame.input("path"), frame.input("content")); + match frame.kind { + ToolKind::Write => { + let (file, content) = (frame.input.legacy_path().text(), WriteInput(frame.input).content().text()); if file.is_empty() && content.is_empty() { return None; } @@ -443,10 +431,10 @@ fn snapshot(frame: &Frame) -> Option { file: file.to_owned(), }) } - "edit" => { + ToolKind::Edit => { let item = frame.files().first().copied(); let file = item.map(|item| file_text(item, "file")).filter(|file| !file.is_empty()); - let file = file.unwrap_or(frame.input("path")); + let file = file.unwrap_or(frame.input.legacy_path().text()); let diff = item.map(|item| file_text(item, "patch")).filter(|diff| !diff.is_empty()); let diff = diff.unwrap_or(frame.meta.get("diff").and_then(Value::as_str).unwrap_or_default()); if file.is_empty() || diff.trim().is_empty() { @@ -457,7 +445,7 @@ fn snapshot(frame: &Frame) -> Option { items: vec![DiffItem { title, diff: diff.to_owned(), file: file.to_owned(), deletions: None }], }) } - "patch" => { + ToolKind::Patch => { let files = frame.files(); let items: Vec = files .iter() @@ -471,16 +459,17 @@ fn snapshot(frame: &Frame) -> Option { .collect(); (!files.is_empty() && items.len() == files.len()).then_some(Snapshot::Diff { items }) } - "subagent" => { - let rows = Some(frame.input("description")).filter(|row| !row.is_empty()).map(str::to_owned); + ToolKind::Subagent => { + let rows = + Some(SubagentInput(frame.input).description().text()).filter(|row| !row.is_empty()).map(str::to_owned); Some(Snapshot::Task { title: format!("# {} Subagent", agent_kind(frame, "general")), rows: rows.into_iter().collect(), tail: String::new(), }) } - "todowrite" => Some(Snapshot::Todo { items: parse_todos(frame.input.get("todos").unwrap_or(&Value::Null)) }), - "question" => { + ToolKind::Todo => Some(Snapshot::Todo { items: TodoInput(frame.input).items() }), + ToolKind::Question => { let items = questions(frame) .into_iter() .enumerate() @@ -553,17 +542,18 @@ pub fn entry_body(commit: &Commit, raw: &str, options: BodyOptions) -> Option Option Body { /// `toolStructuredFinal`: whether a final tool commit draws a structured body, which groups on its own. pub fn structured_final(commit: &Commit) -> bool { - let state = commit.tool_state.map(state_name).or_else(|| commit.part.as_ref().map(|part| part.state.tag())); + let state = commit.tool_state.or_else(|| commit.part.as_ref().and_then(|part| state_of(&part.state))); let name = commit.tool.as_deref().or(commit.part.as_ref().map(|part| part.name.as_str())); commit.kind == EntryKind::Tool && commit.phase == Phase::Final - && state == Some("completed") - && name.is_some_and(|name| tool_view(name).snap) + && state == Some(ToolState::Completed) + && name.and_then(|name| rule(ToolKind::of(name))).is_some_and(|rule| rule.snap) } /// `toolCommit`: one commit of a tool part. @@ -649,10 +639,7 @@ pub fn commit( ) -> Commit { let name = canonical_tool_name(&part.name); let partial = matches!(part.state, State::Error(_)) && phase == Phase::Progress && value.is_some(); - let running = || match name { - "subagent" => "running subagent".to_owned(), - name => format!("running {name}"), - }; + let running = || format!("running {name}"); let text = match &part.state { State::Running(_) => value.map(str::to_owned).unwrap_or_else(running), State::Error(_) if partial => value.map(str::to_owned).unwrap_or_else(running), @@ -682,8 +669,8 @@ pub fn commit( /// `toolFinalPhase`: a completed tool whose output already streamed ends with that output as progress. pub fn final_phase(part: &SessionMessageAssistantTool) -> Phase { let State::Completed(state) = &part.state else { return Phase::Final }; - let name = canonical_tool_name(&part.name); - if tool_view(name).output && !tool_output_text(name, &state.content).is_empty() { + let output = rule(ToolKind::of(&part.name)).is_none_or(|rule| rule.output); + if output && !tool_output_text(&part.name, &state.content).is_empty() { return Phase::Progress; } Phase::Final @@ -858,8 +845,10 @@ mod tests { "content": [{ "type": "text", "text": "task_id: x\n\nFound.\n" }] }), ); assert_eq!(body(&commit(&task, "m", Phase::Final, None, None, 0)), Some(Body::Markdown("Found.".into()))); - let frame = tool_frame(&commit(&task, "m", Phase::Final, None, None, 0), ""); - assert_eq!(task_final(&frame), "# Explore Subagent\nFind it"); + assert_eq!( + task_final(&tool_frame(&commit(&task, "m", Phase::Final, None, None, 0), "")), + "# Explore Subagent\nFind it" + ); let launch = part( "subagent", json!({ "status": "completed", "input": { "agent": "explore", "description": "Inspect reducer" }, @@ -877,14 +866,18 @@ mod tests { json!({ "status": "completed", "input": {}, "content": [], "metadata": { "files": [{ "file": "a", "status": "added" }, { "file": "b", "status": "modified" }] } }), ); - let frame = tool_frame(&commit(&patch, "m", Phase::Final, None, Some("/w"), 0), ""); - assert_eq!(patch_final(&frame), "+ Created a"); + assert_eq!( + patch_final(&tool_frame(&commit(&patch, "m", Phase::Final, None, Some("/w"), 0), "")), + "+ Created a" + ); let question = part( "question", json!({ "status": "completed", "input": { "questions": [{ "question": "Why?" }, {}] }, "content": [], "metadata": { "answers": [["Because"]] } }), ); - let frame = tool_frame(&commit(&question, "m", Phase::Final, None, None, 0), ""); - assert_eq!(question_final(&frame), "? Why?\n Because\n? Question 2\n (no answer)"); + assert_eq!( + question_final(&tool_frame(&commit(&question, "m", Phase::Final, None, None, 0), "")), + "? Why?\n Because\n? Question 2\n (no answer)" + ); } } diff --git a/packages/cli-rs/crates/plugin/src/canvas.rs b/packages/cli-rs/crates/plugin/src/canvas.rs index 0ccc89974f1..b06d4cbc480 100644 --- a/packages/cli-rs/crates/plugin/src/canvas.rs +++ b/packages/cli-rs/crates/plugin/src/canvas.rs @@ -161,13 +161,19 @@ struct State { frame: Cell>, /// The part of the canvas the last paint showed, in screen cells. visible: Cell<(i32, i32, u32, u32)>, - driving: Cell, - /// The driver stopped because something covered the canvas: it starts again once nothing does. - rested: Cell, + drive: Cell, /// The canvas's widget, for its coverage: given up when the widget goes, so it holds no cycle past it. widget: RefCell>, } +#[derive(Clone, Copy, PartialEq)] +enum Drive { + Stopped, + Running, + /// Stopped because something covered the canvas: it starts again once nothing does. + Covered, +} + enum Shown { Empty, List(Kept), @@ -231,8 +237,7 @@ impl Canvas { animate: Cell::new(animate), frame: Cell::new(None), visible: Cell::new((0, 0, 0, 0)), - driving: Cell::new(false), - rested: Cell::new(false), + drive: Cell::new(Drive::Stopped), widget: RefCell::new(None), }); book(|ledger| ledger.canvases += 1); @@ -341,8 +346,9 @@ impl State { hold(&drawer.owner, kept - old, i64::from(kept > 0) - i64::from(old > 0)); } - fn set_driving(&self, on: bool) { - if self.driving.replace(on) != on { + fn set_drive(&self, drive: Drive) { + let on = drive == Drive::Running; + if (self.drive.replace(drive) == Drive::Running) != on { book(|ledger| ledger.driving += if on { 1 } else { -1 }); } } @@ -387,7 +393,7 @@ fn hold(owner: &Rc, bytes: i64, lists: i64) { /// Runs a canvas's animation: a frame for its paint to draw, until the last frame did not show it, it stops animating, /// or the `animations` switch is off. Its time is the time between its ticks, less what follows a [`handover`]. fn drive(state: &Rc) { - state.set_driving(true); + state.set_drive(Drive::Running); let weak = Rc::downgrade(state); let mut last = state.app.now(); state.app.animate(move |cx, _| { @@ -395,13 +401,12 @@ fn drive(state: &Rc) { let app = cx.app(); // A frame left waiting is not drawn: the paint draws one only while the canvas animates. if !state.animate.get() || !opencode_ui::motion::running() { - state.set_driving(false); + state.set_drive(Drive::Stopped); return false; } if state.covered(state.visible.get()) { state.frame.set(None); - state.rested.set(true); - state.set_driving(false); + state.set_drive(Drive::Covered); return false; } let now = app.now(); @@ -417,19 +422,14 @@ fn drive(state: &Rc) { /// a paint reads is the last frame's, so a covered canvas reads it again once this frame is presented, and asks for a /// frame only when nothing covers it then: a covered canvas asks for no frame. fn resume(state: &Rc) { - if !state.rested.get() { - drive(state); - return; - } - if !state.covered(state.visible.get()) { - state.rested.set(false); + if state.drive.get() != Drive::Covered || !state.covered(state.visible.get()) { drive(state); return; } let weak = Rc::downgrade(state); state.app.defer(move |cx| { if let Some(state) = weak.upgrade() - && state.rested.get() + && state.drive.get() == Drive::Covered && !state.covered(state.visible.get()) { cx.request_redraw(); @@ -446,7 +446,7 @@ impl Drop for State { if let Some(drawer) = &self.drawer { hold(&drawer.owner, -bytes, -i64::from(bytes > 0)); } - let driving = self.driving.get(); + let driving = self.drive.get() == Drive::Running; book(|ledger| { ledger.canvases -= 1; if driving { @@ -472,7 +472,7 @@ impl Component for Board { let (left, top) = origin.map_or((0, 0), |rect| (rect.screen_x.floor() as i32, rect.screen_y.floor() as i32)); state.visible.set((left + visible.0, top + visible.1, visible.2, visible.3)); - if state.animate.get() && !state.driving.get() && opencode_ui::motion::running() { + if state.animate.get() && state.drive.get() != Drive::Running && opencode_ui::motion::running() { resume(state); } } diff --git a/packages/cli-rs/crates/plugin/src/interact.rs b/packages/cli-rs/crates/plugin/src/interact.rs index adcae7c6d01..c31c14ab067 100644 --- a/packages/cli-rs/crates/plugin/src/interact.rs +++ b/packages/cli-rs/crates/plugin/src/interact.rs @@ -32,25 +32,17 @@ pub(crate) type Reveal = Rc; /// What one owner holds of the input. pub struct Owner { plugin: String, - /// The surface a mount shows; empty for an activation. - surface: String, host: Weak, - /// The mount's handler, which its nodes' pointer and hover and its overlays' closes reach; `None` for an - /// activation, whose layers each have their own. - deliver: Option, - /// The mount's surface root; `None` for an activation. - root: Option, + /// What a mount's owner holds of its mount; `None` for an activation, whose layers each have their own handler. + mounted: Option, /// Where a layer of its surface's own scope holds (`LayerScope::Surface`). held: RefCell, - lookup: Option, - nearest: Option, - alive: Cell, - /// What it held is gone. - ended: Cell, + life: Cell, /// It has a layer of the composer, so its mode holds while the composer has the focus. composer: Cell, - /// A dialog surface's mount: its layers of no mode are the host dialogs' mode's, and it sets no mode of its own. - dialog: Cell, + /// A dialog surface's mount, and when it began: its layers of no mode are the host dialogs' mode's, it sets no + /// mode of its own, and input waits for its focus only that soon after ([`OPENING`]). + dialog: Cell>, /// Brings a widget of the mount's tree into view in the scrolls of the tree that hold it. reveal: RefCell>, /// What waits for the mount's first tree of the plugin's, and the focus it asked for with it, or for the mount's @@ -58,8 +50,6 @@ pub struct Owner { focus_waiters: RefCell>>, /// The mount showed a tree of the plugin's, not only the pipe's stand-in. viewed: Cell, - /// When a dialog surface's mount began: input waits for its focus only that soon after ([`OPENING`]). - born: Cell>, layers: RefCell>, mode: RefCell>, /// The ids of its tree's nodes, and of its focusable ones. @@ -69,10 +59,29 @@ pub struct Owner { /// one call, and the focus applies before the view that shows it. It waits for the mount's next view and no /// longer ([`Owner::settle_pending`]), one at a time. pending: RefCell>, - /// The mount it holds the input of, as long as it lives; `None` for an activation. - mount: Option>, +} + +/// A mount's surface, its lookups, and its handler: its nodes' pointer and hover and its overlays' closes reach it. +struct Mounted { + surface: String, + root: View, + lookup: Lookup, + nearest: Nearest, + deliver: Option, + /// The mount it holds the input of, as long as it lives. + mount: Weak<()>, /// That mount's ID, which a call for it names to the plugin. - id: Option, + id: opencode_plugin_abi::v2::MountId, +} + +/// Where an owner is in its life, in order. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Life { + Alive, + /// Its handlers stopped; [`Owner::end`] follows. + Revoked, + /// What it held is gone. + Ended, } struct Mode { @@ -238,55 +247,46 @@ impl Owner { deliver: Option, (id, mount): (opencode_plugin_abi::v2::MountId, Weak<()>), ) -> Rc { - let mut owner = Self::new(plugin, surface, host, Some(root), Some((lookup, nearest)), deliver, Some(mount)); - owner.id = Some(id); - Rc::new(owner) + let surface = surface.to_owned(); + Rc::new(Self::new(plugin, host, Some(Mounted { surface, root, lookup, nearest, deliver, mount, id }))) } /// An activation's owner, which has no surface. pub(crate) fn activation(plugin: &str, host: Weak) -> Rc { - Rc::new(Self::new(plugin, "", host, None, None, None, None)) + Rc::new(Self::new(plugin, host, None)) } - fn new( - plugin: &str, - surface: &str, - host: Weak, - root: Option, - lookups: Option<(Lookup, Nearest)>, - deliver: Option, - mount: Option>, - ) -> Self { - let (lookup, nearest) = lookups.unzip(); + fn new(plugin: &str, host: Weak, mounted: Option) -> Self { Self { plugin: plugin.to_owned(), - surface: surface.to_owned(), host, - deliver, - held: RefCell::new(root.clone().map_or(Held::Route, Held::Within)), - root, - lookup, - nearest, - alive: Cell::new(true), - ended: Cell::new(false), + held: RefCell::new(mounted.as_ref().map_or(Held::Route, |mounted| Held::Within(mounted.root.clone()))), + mounted, + life: Cell::new(Life::Alive), composer: Cell::new(false), - dialog: Cell::new(false), + dialog: Cell::new(None), reveal: RefCell::default(), focus_waiters: RefCell::default(), viewed: Cell::new(false), - born: Cell::new(None), layers: RefCell::default(), mode: RefCell::default(), ids: RefCell::default(), focusable: RefCell::default(), pending: RefCell::default(), - mount, - id: None, } } pub fn alive(&self) -> bool { - self.alive.get() + self.life.get() == Life::Alive + } + + /// The mount's surface root; `None` for an activation. + fn root(&self) -> Option<&View> { + self.mounted.as_ref().map(|mounted| &mounted.root) + } + + fn lookup(&self, id: &str) -> Option { + (self.mounted.as_ref()?.lookup)(id) } /// The scope of the surface is the focus in `view`, the container the host shows it in: a panel, an overlay. @@ -298,8 +298,7 @@ impl Owner { /// A dialog surface's mount, before its layers register: they hold in the host dialogs' mode. pub(crate) fn mark_dialog(&self) { - self.dialog.set(true); - self.born.set(Some(std::time::Instant::now())); + self.dialog.set(Some(std::time::Instant::now())); } /// The scope of the surface is the dialog whose body is `view`, while it is on top. @@ -321,7 +320,7 @@ impl Owner { /// Whether a focus may go to it now: it lives and no host dialog but its own is over it. pub(crate) fn eligible(&self, host: &dyn Host) -> bool { - self.alive() && self.root.is_some() && !self.modal_over(host) + self.alive() && self.root().is_some() && !self.modal_over(host) } /// Whether its tree names a node: the pipe's mount shows a placeholder of none until the JS host's first revision. @@ -348,14 +347,14 @@ impl Owner { /// The scope of the surface is the focus in its root: a slot claim. pub(crate) fn hold_root(&self) { - if let Some(root) = self.root.clone() { - self.hold_in(root); + if let Some(root) = self.root() { + self.hold_in(root.clone()); } } /// The scope of the surface is its route's showing; a paste in it is its. pub(crate) fn hold_route(&self) { - if let Some(root) = &self.root { + if let Some(root) = self.root() { self.pastes_in(root); } *self.held.borrow_mut() = Held::Route; @@ -378,7 +377,7 @@ impl Owner { /// The view whose focus is the surface's, if its scope is one. fn within(&self) -> Option { match &*self.held.borrow() { - Held::Within(view) | Held::Dialog(view) if self.root.is_some() => Some(view.clone()), + Held::Within(view) | Held::Dialog(view) if self.root().is_some() => Some(view.clone()), _ => None, } } @@ -386,7 +385,7 @@ impl Owner { /// Whether the focus is in the surface's scope, or its route shows with no dialog or overlay over it, or its /// dialog is on top. fn in_surface(&self, host: &dyn Host) -> bool { - match (&*self.held.borrow(), &self.root) { + match (&*self.held.borrow(), self.root()) { (_, None) => false, (Held::Within(view), Some(_)) => focus_within(host.app(), view.id()), (Held::Route, Some(_)) => !host.modal_open() && !host.router().is_some_and(|router| router.overlaid(host)), @@ -396,7 +395,7 @@ impl Owner { /// The view the focus is in while it is in the surface: its container, or its root. fn scope_view(&self) -> Option { - self.within().or_else(|| self.root.clone()) + self.within().or_else(|| self.root().cloned()) } /// Registers `layers`, whose keys reach `deliver`. @@ -413,7 +412,7 @@ impl Owner { router.owners.borrow_mut().push(me.clone()); } for layer in layers { - if matches!((&layer.scope, &self.root), (LayerScope::Surface | LayerScope::Node(_), None)) { + if matches!((&layer.scope, self.root()), (LayerScope::Surface | LayerScope::Node(_), None)) { log::warn!("plugin {}: a layer of setup has no surface; use the composer or global scope", self.plugin); continue; } @@ -478,7 +477,7 @@ impl Owner { /// Whether `bind` of a dialog surface's layer would take escape, which closes the dialog as it closes the host's own: /// such a bind is left out. fn closing_key(&self, host: &dyn Host, bind: &Bind) -> bool { - let closes = self.dialog.get() && escapes(host, &bind.key); + let closes = self.dialog.get().is_some() && escapes(host, &bind.key); if closes { log::warn!("plugin {}: a dialog surface's bind may not take escape, which closes the dialog", self.plugin); } @@ -523,7 +522,7 @@ impl Owner { match mode { Some(mode) => format!("{}:{mode}", self.plugin), // A dialog's own keys hold in the mode its dialog pushed, beside its escape and `ctrl+c`. - None if self.dialog.get() => MODAL_MODE.to_owned(), + None if self.dialog.get().is_some() => MODAL_MODE.to_owned(), None => BASE_MODE.to_owned(), } } @@ -542,17 +541,14 @@ impl Owner { LayerScope::Global => !host.router().is_some_and(|router| router.overlaid_by_other(&*host, &self.plugin)), LayerScope::Composer => host.composer_focused(), LayerScope::Surface => self.in_surface(&*host), - LayerScope::Node(id) => { - let node = self.lookup.as_ref().and_then(|lookup| lookup(id)); - node.is_some_and(|node| focus_within(host.app(), node.id())) - } + LayerScope::Node(id) => self.lookup(id).is_some_and(|node| focus_within(host.app(), node.id())), } } /// The scope a mode set now holds in: the surface while the focus is in it, else the composer for an owner with a /// layer there while it has the focus, else everywhere for an activation with no composer layer. fn mode_scope(&self) -> Option { - match (&self.root, self.composer.get()) { + match (self.root(), self.composer.get()) { (Some(_), _) if self.holds(&LayerScope::Surface) => Some(LayerScope::Surface), (_, true) if self.holds(&LayerScope::Composer) => Some(LayerScope::Composer), (None, false) if self.holds(&LayerScope::Global) => Some(LayerScope::Global), @@ -577,7 +573,7 @@ impl Owner { old.disposer.dispose(); } // A mode over the host dialogs' would take their escape and `ctrl+c`. - if mode.is_some() && self.dialog.get() { + if mode.is_some() && self.dialog.get().is_some() { log::warn!("plugin {}: a dialog surface sets no mode", self.plugin); return; } @@ -612,7 +608,7 @@ impl Owner { /// Where the node with id `id` is. pub fn rect(&self, id: &str) -> Option { - let widget = self.lookup.as_ref()?(id)?; + let widget = self.lookup(id)?; let rect = widget.rect(); Some(input::Rect { x: rect.screen_x as i32, @@ -624,13 +620,13 @@ impl Owner { /// Where the focus is, for this owner. pub fn focused(&self) -> input::Focused { - let (Some(host), Some(_), Some(nearest)) = (self.host.upgrade(), &self.root, &self.nearest) else { + let (Some(host), Some(mounted)) = (self.host.upgrade(), &self.mounted) else { return input::Focused::default(); }; let path: Vec = std::iter::successors(host.app().focused(), |widget| widget.parent()).map(|widget| widget.id()).collect(); // The nearest node with an id that holds the focus. - let node = nearest(&path); + let node = (mounted.nearest)(&path); input::Focused { node, surface: self.scope_view().is_some_and(|view| path.contains(&view.id())) } } @@ -641,7 +637,7 @@ impl Owner { return; } let kept = node.filter(|id| self.focusable.borrow().iter().any(|known| known == id)); - match kept.and_then(|id| self.lookup.as_ref()?(id)) { + match kept.and_then(|id| self.lookup(id)) { Some(widget) => host.app().focus(&widget), None => { if let Some(view) = self.within() { @@ -682,7 +678,7 @@ impl Owner { return; } let focusable = self.focusable.borrow().iter().any(|known| known == id); - match self.lookup.as_ref().and_then(|lookup| lookup(id)).filter(|_| focusable && self.alive()) { + match self.lookup(id).filter(|_| focusable && self.alive()) { Some(widget) => { refocus(host, || host.app().focus(&widget)); // What takes the focus shows: the scrolls of the tree that hold it, then the host's around the mount. @@ -694,7 +690,7 @@ impl Owner { } // A node the tree does not hold yet waits for the mount's next view, which may show it; one it holds that // takes no focus (a text, a node in a hidden box) is refused. - None if self.alive() && self.lookup.is_some() && !self.has(id) => { + None if self.alive() && self.mounted.is_some() && !self.has(id) => { *self.pending.borrow_mut() = Some(Pending { id: id.to_owned(), from: focused(host.app()) }); } None => log::warn!("plugin {}: {id:?} is not a focusable node of its mount", self.plugin), @@ -731,7 +727,7 @@ impl Owner { pub(crate) fn blur(&self, host: &dyn Host) { self.pending.borrow_mut().take(); let Some(view) = self.scope_view().filter(|view| focus_within(host.app(), view.id())) else { return }; - match self.dialog.get() { + match self.dialog.get().is_some() { true => refocus(host, || host.app().focus(&view)), false => host.focus_composer(), } @@ -744,12 +740,12 @@ impl Owner { /// The mount it holds the input of; `None` for an activation. pub(crate) fn mounted(&self) -> Option> { - self.mount.clone() + self.mounted.as_ref().map(|mounted| mounted.mount.clone()) } /// The ID of the mount it holds the input of; `None` for an activation. pub(crate) fn id(&self) -> Option<&opencode_plugin_abi::v2::MountId> { - self.id.as_ref() + self.mounted.as_ref().map(|mounted| &mounted.id) } /// Calls the mount's handler with what one of its widgets or scrolls sends: an edit, a scroll. @@ -761,7 +757,7 @@ impl Owner { /// Calls the mount's handler with `event`. fn send(self: &Rc, host: &dyn Host, event: &Event) -> Handled { - match (&self.deliver, self.alive()) { + match (self.mounted.as_ref().and_then(|mounted| mounted.deliver.as_ref()), self.alive()) { // What the handler asks for is one deeper than what made the router send it. (Some(deliver), true) => crate::deeper(|| delivered(deliver, host, self, event)), _ => Handled::Pass, @@ -771,15 +767,15 @@ impl Owner { /// Stops the owner's handlers at once: its plugin failed or left `active`. [`Owner::end`] follows once the event /// that ended it is handled. pub(crate) fn revoke(&self) { - self.alive.set(false); + self.life.set(self.life.get().max(Life::Revoked)); } /// Ends the owner: everything it holds of the input goes. The host gives a focus that was inside it to the /// composer as it mounts the route again, and an overlay's close does too. pub(crate) fn end(self: &Rc) { - self.alive.set(false); + let life = self.life.replace(Life::Ended); self.focused_now(); - if self.ended.replace(true) { + if life == Life::Ended { return; } let Some(host) = self.host.upgrade() else { return }; @@ -912,7 +908,8 @@ impl Router { visited.push(address); *self.listened.borrow_mut() = Some((*event, visited.clone())); // A dialog surface's listener hears escape and does not take it: it closes the dialog as the host's own. - if delivered(&deliver, host, &owner, &key) == Handled::Consume && !(escape && owner.dialog.get()) { + if delivered(&deliver, host, &owner, &key) == Handled::Consume && !(escape && owner.dialog.get().is_some()) + { taken = true; break; } @@ -1136,7 +1133,7 @@ impl Router { let owners: Vec> = self.owners.borrow().iter().filter_map(Weak::upgrade).collect(); owners.into_iter().rev().find(|owner| { owner.alive() - && owner.born.get().is_some_and(|born| born.elapsed() < OPENING) + && owner.dialog.get().is_some_and(|born| born.elapsed() < OPENING) && !owner.viewed.get() && owner.on_top(host) }) @@ -1188,17 +1185,20 @@ impl Router { std::iter::successors(Some(source.clone()), |widget| widget.parent()).map(|widget| widget.id()).collect(); let owners: Vec> = self.owners.borrow().iter().filter_map(Weak::upgrade).collect(); owners.into_iter().filter(|owner| owner.alive() && owner.plugin == plugin).find_map(|owner| { - let node = owner.nearest.as_ref()?(&path)?; - Some(input::Dragged { surface: owner.surface.clone(), node }) + let mounted = owner.mounted.as_ref()?; + Some(input::Dragged { surface: mounted.surface.clone(), node: (mounted.nearest)(&path)? }) }) } /// The area of `plugin`'s surface `surface` on the screen, if it shows. fn area(&self, plugin: &str, surface: &str) -> Option<(u16, u16, u16, u16)> { let owners: Vec> = self.owners.borrow().iter().filter_map(Weak::upgrade).collect(); - let owner = - owners.into_iter().find(|owner| owner.alive() && owner.plugin == plugin && owner.surface == surface)?; - let view = owner.within().or_else(|| owner.root.clone())?; + let owner = owners.into_iter().find(|owner| { + owner.alive() + && owner.plugin == plugin + && owner.mounted.as_ref().is_some_and(|mounted| mounted.surface == surface) + })?; + let view = owner.within().or_else(|| owner.root().cloned())?; let rect = view.rect(); let clamp = |value: f64| value.max(0.0).min(f64::from(u16::MAX)) as u16; Some((clamp(rect.screen_x), clamp(rect.screen_y), clamp(f64::from(rect.width)), clamp(f64::from(rect.height)))) @@ -1214,7 +1214,7 @@ impl Router { fn prune_capture(&self, host: &dyn Host) { let stale = self.capture.borrow().as_ref().is_some_and(|capture| { let Some(owner) = capture.owner.upgrade().filter(|owner| owner.alive()) else { return true }; - let node = owner.lookup.as_ref().and_then(|lookup| lookup(&capture.node)); + let node = owner.lookup(&capture.node); node.is_none() || owner.modal_over(host) || host.app().focused().map(|widget| widget.id()) != capture.focus }); if stale { diff --git a/packages/cli-rs/crates/plugin/src/lib.rs b/packages/cli-rs/crates/plugin/src/lib.rs index 484c0e1257d..589543c4fb7 100644 --- a/packages/cli-rs/crates/plugin/src/lib.rs +++ b/packages/cli-rs/crates/plugin/src/lib.rs @@ -39,6 +39,7 @@ use std::sync::Arc; use activation::{Activation, Drawn}; pub use opencode_plugin_abi as abi; +use opencode_plugin_abi::types::kinds::EventKinds; use opencode_ui::dialog::DialogKeymap; use opencode_ui::keymap::{Bind, Slash, TuiCommand}; use opencode_ui::markdown::CodeBlockRenderers; @@ -137,8 +138,8 @@ pub trait Host: 'static { /// Asks for the user's attention. Called outside every plugin callback. fn attention(&self, _attention: &abi::Attention) {} /// Calls `run` with each server event, after the host has applied it, until the disposer is dropped. `run` gets at - /// least the events whose type is in `types`, and may get others. - fn on_event(&self, _types: &[String], _run: Rc) -> Option { + /// least the events whose type is in `kinds`, and may get others. + fn on_event(&self, _kinds: EventKinds, _run: Rc) -> Option { None } /// Mounts slot `path` with `input` into `parent`, for a claim's [`abi::Node::Slot`]. @@ -565,11 +566,11 @@ pub(crate) fn linked(id: impl Into, run: LinkedSetup, external: bool) -> } let revoked = &scope.revoked; for (types, run) in api.events() { - let (kinds, run, scope) = (types.to_vec(), run.clone(), scope.clone()); + let (kinds, run, scope) = (EventKinds::named(types), run.clone(), scope.clone()); let subscription = setup.host().on_event( - types, + kinds.clone(), Rc::new(move |event| { - if kinds.iter().any(|kind| kind == event.tag()) { + if kinds.contains(event) { scope.run("on-event", |host| run(host, event)); } }), diff --git a/packages/cli-rs/crates/plugin/src/loader/tests.rs b/packages/cli-rs/crates/plugin/src/loader/tests.rs index 4c6329cd4fc..df8827270b7 100644 --- a/packages/cli-rs/crates/plugin/src/loader/tests.rs +++ b/packages/cli-rs/crates/plugin/src/loader/tests.rs @@ -229,7 +229,11 @@ impl Host for TestHost { self.attention.borrow_mut().push(attention.clone()); } - fn on_event(&self, _types: &[String], run: Rc) -> Option { + fn on_event( + &self, + _: crate::EventKinds, + run: Rc, + ) -> Option { self.events.borrow_mut().push(run.clone()); let events = Rc::downgrade(&self.events); Some(opentui::keymap::Disposer::new(move || { diff --git a/packages/cli-rs/crates/plugin/src/pipe/guest.rs b/packages/cli-rs/crates/plugin/src/pipe/guest.rs index d1b761d8785..f006295634c 100644 --- a/packages/cli-rs/crates/plugin/src/pipe/guest.rs +++ b/packages/cli-rs/crates/plugin/src/pipe/guest.rs @@ -1063,11 +1063,11 @@ fn register(setup: &mut Setup<'_>, guest: &Rc) { }); } for (handler, types) in manifest.events.iter().enumerate() { - let (called, kinds) = (Rc::downgrade(guest), types.clone()); + let (called, kinds) = (Rc::downgrade(guest), crate::EventKinds::named(types)); let subscription = setup.host().on_event( - types, + kinds.clone(), Rc::new(move |event| { - if let Some(called) = called.upgrade().filter(|_| kinds.iter().any(|kind| kind == event.tag())) { + if let Some(called) = called.upgrade().filter(|_| kinds.contains(event)) { called.call("on-event", Request::Event { handler, event: Box::new(event.clone()) }, false); } }), diff --git a/packages/cli-rs/crates/store/src/connection.rs b/packages/cli-rs/crates/store/src/connection.rs index df4d63dead8..cf0438c251c 100644 --- a/packages/cli-rs/crates/store/src/connection.rs +++ b/packages/cli-rs/crates/store/src/connection.rs @@ -58,14 +58,12 @@ impl Data { for follow in follows { self.follow(follow); } - // Each other event of a type someone listens to. - let mut listened = None; - for event in events { - if is_delta(event) { - continue; - } - let listened = listened.get_or_insert_with(|| opencode_util::lock(&self.inner.listened)); - if listened.contains_key(event.tag()) { + // Each other event of a type someone listens to: of its kind, and of its name for a named kind. + for event in events.iter().filter(|event| !is_delta(event)) { + let kind = event.kind(); + if self.inner.listened[kind as usize].load(std::sync::atomic::Ordering::SeqCst) > 0 + && (!kind.named() || opencode_util::lock(&self.inner.named).contains_key(event.tag())) + { // No receiver is not an error: views subscribe when they need to. let _ = self.inner.signals.send(std::sync::Arc::new(event.clone())); } @@ -216,7 +214,7 @@ impl State { let keys: Vec<&str> = event.data.delta.keys().map(String::as_str).collect(); let row = SessionMessageSystem { id: crate::messages::from_event(&event.id), - r#type: "system".into(), + r#type: tag::System, text: text.clone(), description: Some(format!("Instructions updated: {}", keys.join(", "))), metadata: event.metadata.clone(), @@ -228,7 +226,7 @@ impl State { V2Event::SessionSynthetic(event) => { let row = SessionMessageSynthetic { id: crate::messages::from_event(&event.id), - r#type: "synthetic".into(), + r#type: tag::Synthetic, text: event.data.text.clone(), description: event.data.description.clone(), metadata: event.data.metadata.clone(), diff --git a/packages/cli-rs/crates/store/src/inbox.rs b/packages/cli-rs/crates/store/src/inbox.rs index 5c17848fcf9..3ffd969b014 100644 --- a/packages/cli-rs/crates/store/src/inbox.rs +++ b/packages/cli-rs/crates/store/src/inbox.rs @@ -88,31 +88,35 @@ impl State { /// Pending user and synthetic inputs (`input.list`); compactions are control items. pub fn inputs(&self, session: &SessionID) -> Vec<&str> { - self.pending(session).iter().filter(|item| item.tag() != "compaction").map(SessionInboxInfo::id).collect() + self.pending(session) + .iter() + .filter(|item| !matches!(item, SessionInboxInfo::Compaction(_))) + .map(SessionInboxInfo::id) + .collect() } pub fn has_input(&self, session: &SessionID, inbox: &str) -> bool { - self.pending(session).iter().any(|item| item.id() == inbox && item.tag() != "compaction") + self.pending(session).iter().any(|item| item.id() == inbox && !matches!(item, SessionInboxInfo::Compaction(_))) } /// `pending.status`: an execution's idle boundary promotes every pending steer at once, so a /// steer only waits behind work once the current execution has delivered input. pub fn pending_status(&self, session: &SessionID, inbox: &str) -> Option { let pending = self.pending(session); - let item = pending.iter().find(|item| item.id() == inbox && item.tag() == "user")?; + let item = pending.iter().find(|item| item.id() == inbox && matches!(item, SessionInboxInfo::User(_)))?; if item.delivery() == Some(&SessionInboxDelivery::Queue) { return Some(PendingStatus::Queued); } let messages = self.messages(session); - let boundary = messages.iter().rposition(|item| item.tag() == "idle"); + let boundary = messages.iter().rposition(|item| matches!(item, SessionMessageInfo::Idle(_))); if self.status(session) == SessionStatus::Idle { let stranded = boundary.is_some_and(|at| item.created() <= messages[at].created()); return Some(if stranded { PendingStatus::Stranded } else { PendingStatus::Starting }); } let after = boundary.map_or(0, |at| at + 1); - let delivered = messages[after..] - .iter() - .any(|entry| entry.tag() == "user" && !pending.iter().any(|other| other.id() == entry.id())); + let delivered = messages[after..].iter().any(|entry| { + matches!(entry, SessionMessageInfo::User(_)) && !pending.iter().any(|other| other.id() == entry.id()) + }); Some(if delivered { PendingStatus::Steering } else { PendingStatus::Starting }) } @@ -130,7 +134,7 @@ impl State { None => pending.push(item.clone()), } self.touch_key(key, Touched::PENDING); - if item.tag() != "compaction" { + if !matches!(item, SessionInboxInfo::Compaction(_)) { self.materialize(&item); } } @@ -140,7 +144,7 @@ impl State { let row = match item { SessionInboxInfo::User(item) => SessionMessageInfo::User(SessionMessageUser { id: item.id.clone(), - r#type: "user".into(), + r#type: tag::User, text: item.payload.text.clone(), files: item.payload.files.clone(), agents: item.payload.agents.clone(), @@ -150,7 +154,7 @@ impl State { }), SessionInboxInfo::Synthetic(item) => SessionMessageInfo::Synthetic(SessionMessageSynthetic { id: item.id.clone(), - r#type: "synthetic".into(), + r#type: tag::Synthetic, text: item.payload.text.clone(), description: item.payload.description.clone(), metadata: item.payload.metadata.clone(), @@ -222,7 +226,7 @@ impl State { if let Some((_, updates)) = self.sessions.get_mut(session).and_then(|session| session.pending_read.as_mut()) { updates.insert(item.id().to_owned(), PendingUpdate::Item(Box::new(item.clone()))); } - let compaction = item.tag() == "compaction"; + let compaction = matches!(item, SessionInboxInfo::Compaction(_)); self.admit_local(item); if !compaction { return; @@ -279,11 +283,11 @@ impl State { self.remove_pending(session, input.as_str()); } let row = SessionMessageCompactionRunning { - r#type: "compaction".into(), + r#type: tag::Compaction, id: data.input_id.clone().unwrap_or_else(|| from_event(&event.id)), metadata: None, time: SessionInboxUserTime { created: event.created }, - status: "running".into(), + status: tag::Running, reason: data.reason.clone(), summary: String::new(), }; @@ -331,7 +335,7 @@ fn optimistic_files(files: Option<&Vec>) -> Option = state .pending(&session) .iter() - .filter(|item| item.tag() == "compaction") + .filter(|item| matches!(item, SessionInboxInfo::Compaction(_))) .map(|item| item.id().to_owned()) .collect(); for id in local { @@ -484,7 +488,7 @@ impl Data { id: id.clone(), session_id: session.clone(), time: SessionInboxUserTime { created: now() }, - r#type: "user".into(), + r#type: tag::User, delivery: request.delivery.clone().flatten().unwrap_or(SessionInboxDelivery::Steer), payload: SessionInboxUserPayload { text: request.text.clone(), @@ -525,13 +529,13 @@ impl Data { if let Some(active) = state.sessions.get(session).and_then(|session| session.compacting.as_ref()) { return Some(active.request.clone()); } - if !state.pending(session).iter().any(|item| item.tag() == "compaction") { + if !state.pending(session).iter().any(|item| matches!(item, SessionInboxInfo::Compaction(_))) { state.outbox.insert(id.0.clone()); state.admit_local(SessionInboxInfo::Compaction(SessionInboxCompaction { id: id.clone(), session_id: session.clone(), time: SessionInboxUserTime { created: now() }, - r#type: "compaction".into(), + r#type: tag::Compaction, delivery: SessionInboxDelivery::Steer, payload: SessionInboxCompactionPayload::default(), })); diff --git a/packages/cli-rs/crates/store/src/messages.rs b/packages/cli-rs/crates/store/src/messages.rs index 22911092641..e00b32842d9 100644 --- a/packages/cli-rs/crates/store/src/messages.rs +++ b/packages/cli-rs/crates/store/src/messages.rs @@ -425,7 +425,7 @@ impl State { let admitted: HashSet<&str> = self .pending(session) .iter() - .filter(|item| matches!(item.tag(), "user" | "synthetic")) + .filter(|item| matches!(item, SessionInboxInfo::User(_) | SessionInboxInfo::Synthetic(_))) .map(|item| item.id()) .collect(); let local: Vec<_> = self @@ -606,7 +606,7 @@ impl State { } let assistant = SessionMessageAssistant { id: data.assistant_message_id.clone(), - r#type: "assistant".into(), + r#type: tag::Assistant, agent: data.agent.clone(), model: data.model.clone(), metadata: event.metadata.clone(), @@ -678,7 +678,7 @@ impl State { return; } assistant.content.push(SessionMessageAssistantContentItem::Text(SessionMessageAssistantText { - r#type: "text".into(), + r#type: tag::Text, ..Default::default() })); }); @@ -704,7 +704,7 @@ impl State { return; } assistant.content.push(SessionMessageAssistantContentItem::Reasoning(SessionMessageAssistantReasoning { - r#type: "reasoning".into(), + r#type: tag::Reasoning, text: String::new(), native: data.native.clone(), time: Some(SessionMessageShellTime { created: event.created, completed: None }), @@ -743,14 +743,14 @@ impl State { return; } assistant.content.push(SessionMessageAssistantContentItem::Tool(SessionMessageAssistantTool { - r#type: "tool".into(), + r#type: tag::Tool, id: data.id.clone(), name: data.name.clone(), executed: None, native: None, time: SessionMessageAssistantToolTime { created: event.created, ..Default::default() }, state: SessionMessageAssistantToolState::Streaming(SessionMessageToolStateStreaming { - status: "streaming".into(), + status: tag::Streaming, input: String::new(), }), })); @@ -780,7 +780,7 @@ impl State { tool.executed = Some(data.executed); tool.native = data.native.clone(); tool.state = SessionMessageAssistantToolState::Running(SessionMessageToolStateRunning { - status: "running".into(), + status: tag::Running, input: data.input.clone(), metadata: Default::default(), }); @@ -805,7 +805,7 @@ impl State { omit_file_data(&mut content); } tool.state = SessionMessageAssistantToolState::Completed(SessionMessageToolStateCompleted { - status: "completed".into(), + status: tag::Completed, input: state.input.clone(), metadata: data.metadata.clone(), content, @@ -830,7 +830,7 @@ impl State { omit_file_data(content); } tool.state = SessionMessageAssistantToolState::Error(SessionMessageToolStateError { - status: "error".into(), + status: tag::Error, error: data.error.clone(), input, metadata: data.metadata.clone(), @@ -886,7 +886,7 @@ impl State { } let message = SessionMessageShell { id: from_event(&event.id), - r#type: "shell".into(), + r#type: tag::Shell, shell_id: shell.id.clone(), command: shell.command.clone(), status: shell.status.clone(), @@ -947,11 +947,11 @@ impl State { let transcript = self.transcript_mut(session); let completed = |id: SessionMessageID, metadata, time| { SessionMessageInfo::Compaction(SessionMessageCompaction::Completed(SessionMessageCompactionCompleted { - r#type: "compaction".into(), + r#type: tag::Compaction, id, metadata, time, - status: "completed".into(), + status: tag::Completed, reason: data.reason.clone(), model: data.model.clone(), native: data.native.clone(), @@ -988,11 +988,11 @@ impl State { }); let failed = |id, metadata, time| { SessionMessageInfo::Compaction(SessionMessageCompaction::Failed(SessionMessageCompactionFailed { - r#type: "compaction".into(), + r#type: tag::Compaction, id, metadata, time, - status: "failed".into(), + status: tag::Failed, reason: data.reason.clone(), error: data.error.clone(), cost: data.cost, diff --git a/packages/cli-rs/crates/store/src/sessions.rs b/packages/cli-rs/crates/store/src/sessions.rs index 713ca63b24e..851a4131ed0 100644 --- a/packages/cli-rs/crates/store/src/sessions.rs +++ b/packages/cli-rs/crates/store/src/sessions.rs @@ -588,7 +588,7 @@ impl State { self.touch_selected(&data.session_id); let row = SessionMessageAgentSelected { id: from_event(&event.id), - r#type: "agent-switched".into(), + r#type: tag::AgentSwitched, agent: data.agent.clone(), previous, metadata: None, @@ -611,7 +611,7 @@ impl State { let id = from_event(&event.id); let row = SessionMessageModelSelected { id: id.clone(), - r#type: "model-switched".into(), + r#type: tag::ModelSwitched, model: data.model.clone(), previous, metadata: None, @@ -637,7 +637,7 @@ impl State { }); let row = SessionMessageLocationSwitched { id: from_event(&event.id), - r#type: "location-switched".into(), + r#type: tag::LocationSwitched, project_id: Some(data.project_id.clone()), subpath: data.subpath.clone(), location, @@ -704,7 +704,7 @@ impl State { // Mirror the projected idle marker so turn boundaries match before the next read. let row = SessionMessageIdle { id: from_event(event_id), - r#type: "idle".into(), + r#type: tag::Idle, outcome: match outcome { Outcome::Succeeded => SessionInfoOutcome::Succeeded, Outcome::Failed => SessionInfoOutcome::Failed, diff --git a/packages/cli-rs/crates/store/src/state.rs b/packages/cli-rs/crates/store/src/state.rs index dbdfd5dcce0..020c8d6f355 100644 --- a/packages/cli-rs/crates/store/src/state.rs +++ b/packages/cli-rs/crates/store/src/state.rs @@ -12,6 +12,7 @@ use futures_util::future::{BoxFuture, Shared}; use indexmap::{IndexMap, IndexSet}; use opencode_api::client::Client; use opencode_api::generated::{JobInfo, Project, ProjectID, SessionID, SessionInboxCompaction, SessionMessageID}; +use opencode_api::kinds::EventKinds; use opencode_util::lock; use tokio::runtime::Handle; use tokio::sync::{broadcast, watch}; @@ -246,8 +247,10 @@ pub(crate) struct Inner { revision: watch::Sender, /// The events views act on themselves, sent after their batch is applied. pub(crate) signals: broadcast::Sender>, - /// How many [`Listening`]s want each event type on [`Data::signals`]. - pub(crate) listened: Mutex>, + /// How many [`Listening`]s want each event kind on [`Data::signals`], by `kind as usize`. + pub(crate) listened: [AtomicUsize; opencode_api::generated::EventKind::COUNT], + /// How many [`Listening`]s want each name of the kinds a listener names (`EventKind::named`). + pub(crate) named: Mutex>, /// The streaming deltas kept for the [`DeltaListening`]s. pub(crate) deltas: Mutex, /// How many [`DeltaListening`]s live, as `deltas` counts them: a hint the hot path reads without the lock. @@ -278,7 +281,8 @@ impl Data { state: Mutex::new(state), revision: watch::channel(0).0, signals: broadcast::channel(SIGNALS).0, - listened: Mutex::default(), + listened: std::array::from_fn(|_| AtomicUsize::new(0)), + named: Mutex::default(), deltas: Mutex::default(), delta_listeners: AtomicUsize::new(0), online: AtomicBool::new(true), @@ -337,14 +341,17 @@ impl Data { self.inner.signals.subscribe() } - /// Sends the events of each type in `tags` on [`Data::signals`] until the returned guard drops. - pub fn listen>(&self, tags: impl IntoIterator) -> Listening { - let tags: Vec = tags.into_iter().map(Into::into).collect(); - let mut listened = lock(&self.inner.listened); - for tag in &tags { - *listened.entry(tag.clone()).or_default() += 1; + /// Sends the events of each type in `kinds` on [`Data::signals`] until the returned guard drops. + pub fn listen(&self, kinds: impl Into) -> Listening { + let kinds = kinds.into(); + let mut named = lock(&self.inner.named); + for name in kinds.names() { + *named.entry(name.clone()).or_default() += 1; } - Listening { inner: Arc::downgrade(&self.inner), tags } + for index in kinds.indices() { + self.inner.listened[index].fetch_add(1, Ordering::SeqCst); + } + Listening { inner: Arc::downgrade(&self.inner), kinds } } /// Keeps the streaming deltas (`session.*.delta`), which [`Data::signals`] never sends, for @@ -673,21 +680,22 @@ impl std::ops::DerefMut for Locked<'_> { #[must_use = "the types stop being sent when this drops"] pub struct Listening { inner: std::sync::Weak, - tags: Vec, + kinds: EventKinds, } impl Drop for Listening { fn drop(&mut self) { let Some(inner) = self.inner.upgrade() else { return }; - let mut listened = lock(&inner.listened); - for tag in &self.tags { - if let Some(count) = listened.get_mut(tag) { + let mut named = lock(&inner.named); + for index in self.kinds.indices() { + inner.listened[index].fetch_sub(1, Ordering::SeqCst); + } + for name in self.kinds.names() { + if let Some(count) = named.get_mut(name) { *count -= 1; - if *count == 0 { - listened.remove(tag); - } } } + named.retain(|_, count| *count > 0); } } diff --git a/packages/cli-rs/crates/store/tests/all/data.rs b/packages/cli-rs/crates/store/tests/all/data.rs index 4327e57684f..92b7410d6ae 100644 --- a/packages/cli-rs/crates/store/tests/all/data.rs +++ b/packages/cli-rs/crates/store/tests/all/data.rs @@ -988,9 +988,9 @@ async fn signals_carry_the_listened_events_but_no_deltas() { let data = data(handler(|_req: Req| async { ok(json!({ "data": [] })) }), Options::default()); data.remember(info(session(0))); let mut signals = data.signals(); - let _steps = data.listen(["session.step.started", "session.text.delta"]); - let renamed = data.listen(["session.renamed"]); - let again = data.listen(["session.renamed"]); + let _steps = data.listen([EventKind::SessionStepStarted, EventKind::SessionTextDelta]); + let renamed = data.listen([EventKind::SessionRenamed]); + let again = data.listen([EventKind::SessionRenamed]); let step = json!({ "sessionID": SESSION, "assistantMessageID": "msg_a", "agent": "build", "model": { "providerID": "p", "id": "m" }, "started": 1, diff --git a/packages/cli-rs/crates/tui/src/dialogs/go_upsell.rs b/packages/cli-rs/crates/tui/src/dialogs/go_upsell.rs index c708344ca3a..004c609855f 100644 --- a/packages/cli-rs/crates/tui/src/dialogs/go_upsell.rs +++ b/packages/cli-rs/crates/tui/src/dialogs/go_upsell.rs @@ -498,12 +498,7 @@ impl Connect { *self.label.borrow_mut() = Some(label); if self.valid() { - self.sync( - false, - bind!(self, |state, outcome| if outcome.is_none() && !state.closed.get() { - state.start_oauth(&form); - }), - ); + self.sync(false, bind!(self, |state| state.start_oauth(&form))); return; } self.start_oauth(&form); @@ -561,21 +556,16 @@ impl Connect { } state.settled.set(true); match result { - Ok(_) => state.sync( - true, - bind!(state, |state, outcome| if outcome.is_none() && !state.closed.get() { - state.local.dialogs.clear(); - }), - ), + Ok(_) => state.sync(true, bind!(state, |state| state.local.dialogs.clear())), Err(error) => state.fail(error), } }), ); } - // Reloads the integrations, models, and providers into the store, one after another. `done` gets `Some(true)` - // after finishing, `Some(false)` when closed or failed, and `None` when the connection is not valid yet. - fn sync(self: &Rc, announce: bool, done: impl FnOnce(Option) + 'static) { + // Reloads the integrations, models, and providers into the store, one after another, and finishes. `invalid` runs + // instead when the dialog is open and the connection is not valid yet. + fn sync(self: &Rc, announce: bool, invalid: impl FnOnce() + 'static) { let local = &self.local; let (integrations, models, providers) = (local.reload(Catalog::Integration), local.reload(Catalog::Model), local.reload(Catalog::Provider)); @@ -587,14 +577,13 @@ impl Connect { }, bind!(self, |state, _, result| { if state.closed.get() || state.local.dialogs.is_empty() { - return done(Some(false)); + return; } if let Err(error) = result { - state.fail(error.to_string()); - return done(Some(false)); + return state.fail(error.to_string()); } if !state.valid() { - return done(None); + return invalid(); } if announce { let name = @@ -602,7 +591,6 @@ impl Connect { state.local.toasts.show(ToastOptions::new(Variant::Success, format!("Connected {name}"))); } state.finish(); - done(Some(true)); }), ); } diff --git a/packages/cli-rs/crates/tui/src/features/events.rs b/packages/cli-rs/crates/tui/src/features/events.rs index 200396f0ba3..c9d2455d25f 100644 --- a/packages/cli-rs/crates/tui/src/features/events.rs +++ b/packages/cli-rs/crates/tui/src/features/events.rs @@ -3,7 +3,10 @@ use std::sync::Arc; -use opencode_api::generated::{McpServerStatus, SessionArchivedData, SessionDeleted, V2Event, V2EventServerConnected}; +use opencode_api::generated::{ + EventKind, McpServerStatus, SessionArchivedData, SessionDeleted, V2Event, V2EventServerConnected, +}; +use opencode_api::kinds::EventKinds; use crate::prelude::*; @@ -29,10 +32,10 @@ pub(crate) struct Signal(pub Arc); #[derive(Clone)] pub(crate) struct Lagged; -/// Declares [`Handled`], the events [`handle`] and the handlers it calls act on, and [`HANDLED`], their tags, which the -/// store passes on. The handlers match on [`Handled`], so acting on a type means adding it here. +/// Declares [`Handled`], the events [`handle`] and the handlers it calls act on, and [`HANDLED`], their kinds, which +/// the store passes on. The handlers match on [`Handled`], so acting on a type means adding it here. macro_rules! handled { - ($($tag:literal => $variant:ident($payload:ident)),* $(,)?) => { + ($($variant:ident($payload:ident)),* $(,)?) => { #[allow(dead_code, reason = "a handler may match a variant without reading its payload")] pub(crate) enum Handled<'a> { $($variant(&'a opencode_api::generated::$payload),)* @@ -47,27 +50,27 @@ macro_rules! handled { } } - const HANDLED: &[(&str, &str)] = &[$(($tag, stringify!($variant))),*]; + const HANDLED: [EventKind; [$(EventKind::$variant),*].len()] = [$(EventKind::$variant),*]; }; } handled! { - "server.connected" => ServerConnected(V2EventServerConnected), - "session.deleted" => SessionDeleted(SessionDeleted), - "session.inbox.enqueued" => SessionInboxEnqueued(SessionInboxEnqueued), - "session.execution.succeeded" => SessionExecutionSucceeded(SessionExecutionSucceeded), - "worktree.updated" => WorktreeUpdated(WorktreeUpdated), - "persistent-pty.added" => PersistentPtyAdded(PersistentPtyAdded), - "persistent-pty.removed" => PersistentPtyRemoved(PersistentPtyRemoved), - "persistent-pty.updated" => PersistentPtyUpdated(PersistentPtyUpdated), - "tui.command.execute" => TuiCommandExecute(TuiCommandExecute), - "tui.toast.show" => TuiToastShow(TuiToastShow), - "tui.prompt.append" => TuiPromptAppend(TuiPromptAppend), - "tui.session.select" => TuiSessionSelect(TuiSessionSelect), + ServerConnected(V2EventServerConnected), + SessionDeleted(SessionDeleted), + SessionInboxEnqueued(SessionInboxEnqueued), + SessionExecutionSucceeded(SessionExecutionSucceeded), + WorktreeUpdated(WorktreeUpdated), + PersistentPtyAdded(PersistentPtyAdded), + PersistentPtyRemoved(PersistentPtyRemoved), + PersistentPtyUpdated(PersistentPtyUpdated), + TuiCommandExecute(TuiCommandExecute), + TuiToastShow(TuiToastShow), + TuiPromptAppend(TuiPromptAppend), + TuiSessionSelect(TuiSessionSelect), } pub fn install(tui: &Tui) { - std::mem::forget(tui.data.listen(HANDLED.iter().map(|(tag, _)| *tag))); + std::mem::forget(tui.data.listen(HANDLED)); tui.app.on_message(bind!(tui, |tui, _, Signal(event)| { // Flush the previous signal's plugin actions before the next signal can navigate. opencode_plugin::flush(); @@ -108,19 +111,12 @@ fn resync(tui: &Tui) { let deleted: Vec = tui.data.read(|state| open.into_iter().map(SessionID).filter(|id| state.is_missing(id)).collect()); for id in deleted { - let event = SessionDeleted { - r#type: "session.deleted".to_owned(), - data: SessionArchivedData { session_id: id }, - ..SessionDeleted::default() - }; + let event = SessionDeleted { data: SessionArchivedData { session_id: id }, ..SessionDeleted::default() }; handle(tui, &Handled::SessionDeleted(&event)); } tui.resync(); // Notify subscribers to resync after a missed broadcast, as on reconnect. - let event = V2Event::ServerConnected(V2EventServerConnected { - r#type: "server.connected".to_owned(), - ..V2EventServerConnected::default() - }); + let event = V2Event::ServerConnected(V2EventServerConnected::default()); let subscribers: Vec<_> = tui.events.subscribers.borrow().iter().map(|(_, subscriber)| subscriber.clone()).collect(); for subscriber in subscribers { @@ -130,11 +126,7 @@ fn resync(tui: &Tui) { /// Calls `subscriber` with each store signal, after the TUI's own handling, until the disposer drops. The store passes /// on the events of each type in `types`; `subscriber` also sees the types other subscribers asked for. -pub fn subscribe>( - tui: &Tui, - types: impl IntoIterator, - subscriber: impl Fn(&Tui, &V2Event) + 'static, -) -> Disposer { +pub fn subscribe(tui: &Tui, types: impl Into, subscriber: impl Fn(&Tui, &V2Event) + 'static) -> Disposer { let id = tui.events.next.get(); tui.events.next.set(id + 1); tui.events.subscribers.borrow_mut().push((id, Rc::new(subscriber))); diff --git a/packages/cli-rs/crates/tui/src/features/update_notification.rs b/packages/cli-rs/crates/tui/src/features/update_notification.rs index 025db736a39..b37a81f1c02 100644 --- a/packages/cli-rs/crates/tui/src/features/update_notification.rs +++ b/packages/cli-rs/crates/tui/src/features/update_notification.rs @@ -1,6 +1,6 @@ //! Register update actions only when an updater is available. Keep dismissed notices in shared storage. -use opencode_api::generated::V2Event; +use opencode_api::generated::{EventKind, V2Event}; use opencode_ui::motion::FadeInText; use crate::prelude::*; @@ -43,16 +43,20 @@ pub trait Source { struct Notice { kind: Kind, version: String, - server: Option, + by: By, +} + +/// Who announced an update: this client, or its server on this machine or on another. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum By { + Client, + Server, + RemoteServer, } impl Notice { - fn remote(&self) -> bool { - self.server == Some(true) - } - fn key(&self) -> String { - let source = if self.server.is_some() { "server" } else { "client" }; + let source = if self.by == By::Client { "client" } else { "server" }; format!("{source}:{}", self.version) } } @@ -84,14 +88,15 @@ pub fn set_source(tui: &Rc, source: Rc) { .slash("update"); tui.keymap .install("update", [KeymapLayer::global(vec![command]), KeymapLayer::default().bindings(["opencode.update"])]); - crate::features::events::subscribe(tui, ["installation.update-available", "installation.updated"], |tui, event| { + let kinds = [EventKind::InstallationUpdateAvailable, EventKind::InstallationUpdated]; + crate::features::events::subscribe(tui, kinds, |tui, event| { let (kind, version) = match event { V2Event::InstallationUpdateAvailable(event) => (Kind::Available, event.data.version.clone()), V2Event::InstallationUpdated(event) => (Kind::Installed, event.data.version.clone()), _ => return, }; - let remote = tui.updates.source().is_some_and(|source| source.remote()); - notify(tui, Notice { kind, version, server: Some(remote) }); + let by = if tui.updates.source().is_some_and(|source| source.remote()) { By::RemoteServer } else { By::Server }; + notify(tui, Notice { kind, version, by }); }) .forget(); } @@ -114,7 +119,7 @@ impl Updates { } pub fn client_notice(tui: &Tui, notice: ClientNotice) { - notify(tui, Notice { kind: notice.kind, version: notice.version, server: None }); + notify(tui, Notice { kind: notice.kind, version: notice.version, by: By::Client }); } fn notify(tui: &Tui, notice: Notice) { @@ -122,16 +127,16 @@ fn notify(tui: &Tui, notice: Notice) { return; } // Every way out of the TUI after a local install tells the user to start the new version. - if notice.kind == Kind::Installed && !notice.remote() { + if notice.kind == Kind::Installed && notice.by != By::RemoteServer { tui.epilogue.updated_version(notice.version.clone()); } let dismissed = dismissed(tui); - if dismissed.contains(¬ice.key()) || (notice.server.is_none() && dismissed.contains(¬ice.version)) { + if dismissed.contains(¬ice.key()) || (notice.by == By::Client && dismissed.contains(¬ice.version)) { return; } { let mut current = tui.updates.notification.borrow_mut(); - let keep = notice.server.is_some() && current.as_ref().is_some_and(|current| current.server.is_none()); + let keep = notice.by != By::Client && current.as_ref().is_some_and(|current| current.by == By::Client); if !keep { *current = Some(notice); } @@ -260,7 +265,7 @@ pub fn open(tui: &Tui, origin: Origin) { if tui.updates.source().is_none() { return; } - let known = tui.updates.notification.borrow().clone().filter(|notice| !notice.remote()); + let known = tui.updates.notification.borrow().clone().filter(|notice| notice.by != By::RemoteServer); if origin == Origin::Notification && known.is_none() { return; } @@ -308,7 +313,7 @@ fn render(tui: &Tui) { tui.updates.row.take(); tui.updates.parts.borrow_mut().clear(); let Some(notice) = tui.updates.notification.borrow().clone() else { return }; - let remote = notice.remote(); + let remote = notice.by == By::RemoteServer; if remote && notice.kind != Kind::Available { return; } diff --git a/packages/cli-rs/crates/tui/src/plugins/host.rs b/packages/cli-rs/crates/tui/src/plugins/host.rs index 5afc5064a2e..b9bc13a9735 100644 --- a/packages/cli-rs/crates/tui/src/plugins/host.rs +++ b/packages/cli-rs/crates/tui/src/plugins/host.rs @@ -5,9 +5,10 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use opencode_api::generated::{ - IntegrationInfo, LocationQueryInput, McpServer, ModelInfo, ModelRef, PluginInfo, PluginListInput, PluginSource, - PluginState, ProviderID, ProviderInfo, SessionInboxDelivery, UsageLimitsInfo, V2Event, VcsInfo, + EventKind, IntegrationInfo, LocationQueryInput, McpServer, ModelInfo, ModelRef, PluginInfo, PluginListInput, + PluginSource, PluginState, ProviderID, ProviderInfo, SessionInboxDelivery, UsageLimitsInfo, V2Event, VcsInfo, }; +use opencode_api::kinds::EventKinds; use opencode_local::cli_config::AttentionSoundName; use opencode_local::serial::Serial; use opencode_local::storage::Storage; @@ -248,8 +249,8 @@ impl Host for Tui { notify::notify(self, &request); } - fn on_event(&self, types: &[String], run: Rc) -> Option { - Some(crate::features::events::subscribe(self, types.iter().cloned(), move |_, event| run(event))) + fn on_event(&self, kinds: EventKinds, run: Rc) -> Option { + Some(crate::features::events::subscribe(self, kinds, move |_, event| run(event))) } fn slot(&self, parent: &View, path: &str, input: &SlotInput) -> Option { @@ -1233,7 +1234,7 @@ pub fn install(tui: &Rc) { // Notify plugin keymap readers when pending keys, layers, or focus change. let keymap = tui.keymap.keymap().on_state(bind!(tui, |tui| local_changed(&tui))); tui.layers.borrow_mut().push(keymap); - crate::features::events::subscribe(tui, ["plugin.updated", "server.connected"], |tui, event| { + crate::features::events::subscribe(tui, [EventKind::PluginUpdated, EventKind::ServerConnected], |tui, event| { if matches!(event, V2Event::PluginUpdated(_) | V2Event::ServerConnected(_)) { sync_server_plugins(tui); } @@ -1434,9 +1435,7 @@ fn server_name(plugin: &PluginInfo) -> String { match &plugin.source { PluginSource::Package(package) => package.target.clone(), PluginSource::Local(local) => local.path.clone(), - PluginSource::Builtin(source) => source.r#type.clone(), - PluginSource::Sdk(source) => source.r#type.clone(), - PluginSource::Unknown(value) => value.get("type").and_then(Value::as_str).unwrap_or_default().to_owned(), + source => source.tag().to_owned(), } } diff --git a/packages/cli-rs/crates/tui/src/plugins/sidebar_mcp.rs b/packages/cli-rs/crates/tui/src/plugins/sidebar_mcp.rs index 1df13bdf9a0..4c6bfae346d 100644 --- a/packages/cli-rs/crates/tui/src/plugins/sidebar_mcp.rs +++ b/packages/cli-rs/crates/tui/src/plugins/sidebar_mcp.rs @@ -1,6 +1,6 @@ //! Foldable MCP status list for the session's location. -use opencode_api::generated::McpServer; +use opencode_api::generated::{McpServer, McpServerStatus}; use opencode_plugin::abi::v2::{Node, Place, Surface}; use opencode_plugin::abi::{self, Click, Command, Layout, Placement, Span, Wrap}; use opencode_plugin::slot; @@ -43,8 +43,11 @@ fn setup(setup: &mut abi::Setup) -> Result<(), String> { } fn view(list: &[McpServer], open: bool) -> Node { - let on = list.iter().filter(|item| item.status.tag() == "connected").count(); - let bad = list.iter().filter(|item| matches!(item.status.tag(), "failed" | "needs_auth")).count(); + let on = list.iter().filter(|item| matches!(item.status, McpServerStatus::Connected(_))).count(); + let bad = list + .iter() + .filter(|item| matches!(item.status, McpServerStatus::Failed(_) | McpServerStatus::NeedsAuth(_))) + .count(); let mut title = vec![Span::new("MCP").fg("text.base").bold()]; if !open { let errors = match bad { diff --git a/packages/cli-rs/crates/tui/src/routes/session/grouping.rs b/packages/cli-rs/crates/tui/src/routes/session/grouping.rs index b4f621b4e82..2f58130a41b 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/grouping.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/grouping.rs @@ -8,7 +8,7 @@ use opencode_api::generated::{ }; use opencode_local::cli_config::{Grouping, Info, Verbosity}; use opencode_ui::motion::Spinner; -use opencode_ui::tool_info::{canonical_tool_name, tool_display_metadata}; +use opencode_ui::tool_info::{ToolKind, canonical_tool_name, tool_display_metadata}; use opentui::widget::Markdown; use opencode_store::MessageKey; @@ -221,8 +221,6 @@ pub fn rows_after(weights: &[usize], start: usize, budget: usize) -> usize { index } -const EXPLORATION_TOOLS: [&str; 5] = ["read", "glob", "grep", "webfetch", "websearch"]; - pub fn project(rows: Vec, index: Messages<'_>, verbosity: Verbosity) -> Vec { let mut nodes: Vec<(Node, bool)> = Vec::new(); for spec in rows { @@ -324,14 +322,17 @@ fn path(spec: &Spec, index: Messages<'_>, verbosity: Verbosity) -> (&'static [Ki (path, !running) } Spec::Part { message, part } => { - let name = match part { - Part::Tool(_) => tool(index, *message, part).map_or("", |tool| tool.name.as_str()), - _ => "", + let kind = match part { + Part::Tool(_) => tool(index, *message, part).map(|tool| ToolKind::of_ignore_ascii_case(&tool.name)), + _ => None, }; - let exploration = EXPLORATION_TOOLS.iter().any(|tool| name.eq_ignore_ascii_case(tool)); + let exploration = matches!( + kind, + Some(ToolKind::Read | ToolKind::Glob | ToolKind::Grep | ToolKind::WebFetch | ToolKind::WebSearch) + ); let path: &[Kind] = match part { Part::Text(_) => &[], - Part::Tool(_) if name.eq_ignore_ascii_case("question") => &[], + Part::Tool(_) if kind == Some(ToolKind::Question) => &[], Part::Reasoning(_) if low => &[Kind::Activity, Kind::Reasoning], Part::Reasoning(_) => &[Kind::Reasoning], Part::Tool(_) if exploration && low => &[Kind::Activity, Kind::Exploration], @@ -379,10 +380,11 @@ pub fn instruction_paths(message: Option<&SessionMessageInfo>) -> Vec { pub fn exploration_label(tools: &[&SessionMessageAssistantTool], completed: bool) -> String { let mut counts: Vec<(&str, usize)> = Vec::new(); for tool in tools { - let name = match canonical_tool_name(&tool.name) { - "grep" | "glob" | "websearch" => "search", - "webfetch" => "fetch", - name @ ("shell" | "read") => name, + let name = match ToolKind::of(&tool.name) { + ToolKind::Grep | ToolKind::Glob | ToolKind::WebSearch => "search", + ToolKind::WebFetch => "fetch", + ToolKind::Shell => "shell", + ToolKind::Read => "read", _ => "generic", }; match counts.iter_mut().find(|(other, _)| *other == name) { @@ -441,11 +443,11 @@ pub fn activity_summary(items: &[Activity<'_>], instructions: usize, closed: boo } } Activity::Tool(tool) => { - let name = canonical_tool_name(&tool.name); - if name == "execute" { + let kind = ToolKind::of(&tool.name); + if kind == ToolKind::Execute { let calls = execute_calls(tool); for call in &calls { - add(if canonical_tool_name(call) == "read" { "read" } else { "tool" }); + add(if ToolKind::of(call) == ToolKind::Read { "read" } else { "tool" }); } if calls.is_empty() && !active { add("tool"); @@ -455,10 +457,10 @@ pub fn activity_summary(items: &[Activity<'_>], instructions: usize, closed: boo if active { continue; } - add(match name { - "shell" => "command", - "read" => "read", - "edit" | "write" | "patch" => "edit", + add(match kind { + ToolKind::Shell => "command", + ToolKind::Read => "read", + ToolKind::Edit | ToolKind::Write | ToolKind::Patch => "edit", _ => "tool", }); } @@ -480,11 +482,10 @@ pub fn activity_summary(items: &[Activity<'_>], instructions: usize, closed: boo fn busy_label(item: &Activity<'_>) -> String { let Activity::Tool(tool) = item else { return "Thinking…".to_owned() }; - let name = canonical_tool_name(&tool.name); - let noun = match name { - "shell" => "command", - "execute" => "code", - name => name, + let noun = match ToolKind::of(&tool.name) { + ToolKind::Shell => "command", + ToolKind::Execute => "code", + _ => canonical_tool_name(&tool.name), }; let verb = match tool.state { SessionMessageAssistantToolState::Streaming(_) => "Preparing", diff --git a/packages/cli-rs/crates/tui/src/routes/session/messages/background.rs b/packages/cli-rs/crates/tui/src/routes/session/messages/background.rs index 17da20afaa7..e50d5b6e3b1 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/messages/background.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/messages/background.rs @@ -1,7 +1,7 @@ //! Offer to background a running shell after three seconds. Subagents already run in the background. use opencode_api::generated::{SessionMessageAssistantContentItem, SessionMessageAssistantToolState}; -use opencode_ui::tool_info::canonical_tool_name; +use opencode_ui::tool_info::ToolKind; use crate::prelude::*; @@ -121,7 +121,7 @@ fn running(messages: &[SessionMessageInfo]) -> Option<(String, f64)> { current.content.iter().find_map(|item| match item { SessionMessageAssistantContentItem::Tool(tool) if matches!(tool.state, SessionMessageAssistantToolState::Running(_)) - && canonical_tool_name(&tool.name) == "shell" => + && ToolKind::of(&tool.name) == ToolKind::Shell => { Some((format!("{}:{}", current.id.as_str(), tool.id), tool.time.ran.unwrap_or(tool.time.created))) } diff --git a/packages/cli-rs/crates/tui/src/routes/session/messages/shell.rs b/packages/cli-rs/crates/tui/src/routes/session/messages/shell.rs index 8a55498a5b2..70e698e46fc 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/messages/shell.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/messages/shell.rs @@ -66,8 +66,15 @@ pub(crate) struct Output { pub(crate) text: String, pub(crate) truncated: bool, cursor: i64, - loading: bool, - drain_requested: bool, + reading: Reading, +} + +#[derive(Default, PartialEq)] +enum Reading { + #[default] + Idle, + Running, + ThenDrain, } /// What one [`Output::start`] read: the pages' output, the cursor after them, and whether it skipped ahead. @@ -83,11 +90,13 @@ impl Output { directory: Option, drain: bool, ) -> Option + Send + use<>> { - if self.loading { - self.drain_requested |= drain; + if self.reading != Reading::Idle { + if drain { + self.reading = Reading::ThenDrain; + } return None; } - self.loading = true; + self.reading = Reading::Running; let client = client.clone(); let start = self.cursor; let location = directory.map(|directory| LocationQueryInput { directory: Some(directory) }); @@ -138,8 +147,7 @@ impl Output { } self.truncated |= skipped; self.cursor = cursor; - self.loading = false; - std::mem::take(&mut self.drain_requested) + std::mem::take(&mut self.reading) == Reading::ThenDrain } } diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/dispatch.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/dispatch.rs index 1027019ed04..fc716fd61e6 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/dispatch.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/dispatch.rs @@ -5,7 +5,7 @@ use opencode_api::generated::{ }; use opencode_plugin::claim; use opencode_ui::motion::Spinner; -use opencode_ui::tool_info::{canonical_tool_name, tool_display_content, tool_display_metadata}; +use opencode_ui::tool_info::{ToolInput, ToolKind, tool_display_content, tool_display_metadata}; use serde_json::Map; use unicode_width::UnicodeWidthStr; @@ -24,7 +24,7 @@ pub const ICON_WIDTH: u16 = 2; pub struct Tool { root: View, body: View, - view: RefCell)>>, + view: RefCell)>>, /// Claim mount and whether its tree replaces the normal tool view. claim: Rc>>, /// `ToolImages`: the call's image results under its row. @@ -110,25 +110,30 @@ impl Tool { self.images.update(cx, tool_images(part)); return; } - let display = display(&part.name); + // `toolDisplay`: every tool without a view of its own shares the generic one. + let display = match ToolKind::of(&part.name) { + ToolKind::Invalid | ToolKind::Batch | ToolKind::List | ToolKind::Lsp => ToolKind::Other, + ToolKind::Context | ToolKind::ExternalDirectory | ToolKind::DoomLoop => ToolKind::Other, + kind => kind, + }; let mut view = self.view.borrow_mut(); if view.as_ref().is_none_or(|(current, _)| *current != display) { self.body.clear(); let body: Box = match display { - "shell" => Box::new(shell::Shell::new(cx)), - "glob" => inline::row(cx, inline::glob), - "read" => Box::new(read::Read::new(cx)), - "grep" => inline::row(cx, inline::grep), - "write" => Box::new(write::Write::new(cx)), - "edit" => Box::new(edit::Edit::new(cx)), - "webfetch" => inline::row(cx, inline::webfetch), - "websearch" => inline::row(cx, inline::websearch), - "subagent" => Box::new(subagent::Subagent::new(cx)), - "execute" => Box::new(execute::Execute::new(cx)), - "patch" => Box::new(patch::Patch::new(cx)), - "todowrite" => Box::new(todo::Todo::new(cx)), - "question" => Box::new(question::Question::new(cx)), - "skill" => inline::row(cx, inline::skill), + ToolKind::Shell => Box::new(shell::Shell::new(cx)), + ToolKind::Glob => inline::row(cx, inline::glob), + ToolKind::Read => Box::new(read::Read::new(cx)), + ToolKind::Grep => inline::row(cx, inline::grep), + ToolKind::Write => Box::new(write::Write::new(cx)), + ToolKind::Edit => Box::new(edit::Edit::new(cx)), + ToolKind::WebFetch => inline::row(cx, inline::webfetch), + ToolKind::WebSearch => inline::row(cx, inline::websearch), + ToolKind::Subagent => Box::new(subagent::Subagent::new(cx)), + ToolKind::Execute => Box::new(execute::Execute::new(cx)), + ToolKind::Patch => Box::new(patch::Patch::new(cx)), + ToolKind::Todo => Box::new(todo::Todo::new(cx)), + ToolKind::Question => Box::new(question::Question::new(cx)), + ToolKind::Skill => inline::row(cx, inline::skill), _ => Box::new(generic::Generic::new(cx)), }; self.body.add(body.root()); @@ -181,32 +186,11 @@ impl Tool { } } -/// `toolDisplay`: the view for a tool name. -fn display(name: &str) -> &'static str { - match canonical_tool_name(name) { - "shell" => "shell", - "glob" => "glob", - "read" => "read", - "grep" => "grep", - "webfetch" => "webfetch", - "websearch" => "websearch", - "write" => "write", - "edit" => "edit", - "subagent" => "subagent", - "execute" => "execute", - "patch" => "patch", - "todowrite" => "todowrite", - "question" => "question", - "skill" => "skill", - _ => "generic", - } -} - /// `ToolProps`: what every view reads from the call. pub struct Props<'a> { pub part: &'a SessionMessageAssistantTool, /// The input, or empty while it streams as text. - pub input: Map, + pub input: ToolInput<'a>, pub metadata: Map, /// The text of the content items, `None` while the input streams. pub output: Option, @@ -216,8 +200,6 @@ pub struct Props<'a> { impl<'a> Props<'a> { fn new(cx: &Context<'_>, part: &'a SessionMessageAssistantTool) -> Self { - let state = serde_json::to_value(&part.state).unwrap_or_default(); - let input = state.get("input").and_then(Value::as_object).cloned().unwrap_or_default(); let streaming = matches!(part.state, SessionMessageAssistantToolState::Streaming(_)); let output = (!streaming).then(|| { tool_display_content(&part.state) @@ -232,7 +214,7 @@ impl<'a> Props<'a> { }); Self { part, - input, + input: ToolInput::of(&part.state), metadata: tool_display_metadata(&part.state), output, permission: permission::tool_pending(cx.tui, cx.state, cx.session, &part.id), @@ -256,11 +238,6 @@ impl<'a> Props<'a> { _ => None, } } - - /// `stringValue(props.input[key])`. - pub fn input_str(&self, key: &str) -> Option<&str> { - self.input.get(key).and_then(Value::as_str) - } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -298,16 +275,6 @@ pub fn number(value: f64) -> String { opencode_api::query::js_string(&Value::from(value)) } -/// JavaScript truthiness. -pub fn truthy(value: Option<&Value>) -> bool { - match value { - None | Some(Value::Null) | Some(Value::Bool(false)) => false, - Some(Value::Number(number)) => number.as_f64().is_some_and(|number| number != 0.0), - Some(Value::String(text)) => !text.is_empty(), - Some(_) => true, - } -} - /// `finiteNumber(value)`, when it is not 0 (`finiteNumber(x) || …`). pub fn finite(value: Option<&Value>) -> Option { value.and_then(opencode_ui::tool_info::finite_number).filter(|number| *number != 0.0) diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/edit.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/edit.rs index 5a30478d7d5..f898d79a194 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/edit.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/edit.rs @@ -1,10 +1,10 @@ //! Display the edit diff when a patch is available. -use opencode_local::cli_config::{DiffView as ConfigDiffView, DiffWrap}; use opentui::widget::DiffView; use super::diagnostics; use super::dispatch::{Block, BlockTool, Header, Props, Status, content_width, fingerprint, format_path}; +use super::patch::{diff_layout, parse_files}; use crate::prelude::*; use crate::routes::session::messages::list::Context; @@ -39,9 +39,10 @@ impl Edit { } pub fn update(&self, cx: &Context<'_>, props: &Props<'_>) { - let input_path = props.input_str("path"); - let file = first_file(props.metadata.get("files")); - let path = file.as_ref().map(|file| file.path.as_str()).or(input_path); + let input_path = props.input.path().str(); + // `parseApplyPatchFiles(...)[0]`: the first complete file. + let file = parse_files(props.metadata.get("files")).into_iter().next(); + let path = file.as_ref().map(|file| file.relative_path.as_str()).or(input_path); let header = if file.is_some() || input_path.is_some_and(|path| !path.is_empty()) { Header::Path { label: "← Edit".to_owned(), value: format_path(cx, path) } } else { @@ -61,21 +62,10 @@ impl Edit { self.shown.take(); return; }; - let diffs = cx.tui.config().info.diffs.clone(); - let diffs = diffs.as_ref(); - let view = match diffs.and_then(|diffs| diffs.view) { - Some(ConfigDiffView::Unified) => DiffView::Unified, - Some(ConfigDiffView::Split) => DiffView::Split, - _ if content_width(cx) > 120 => DiffView::Split, - _ => DiffView::Unified, - }; - let wrap = match diffs.and_then(|diffs| diffs.wrap) { - Some(DiffWrap::None) => WrapMode::None, - _ => WrapMode::Word, - }; + let (view, wrap) = diff_layout(cx, content_width(cx)); let shown = Shown { patch: fingerprint(&file.patch), - path: file.path, + path: file.relative_path, view, wrap, diagnostics: props.metadata.get("diagnostics").cloned(), @@ -106,55 +96,3 @@ impl Edit { *self.shown.borrow_mut() = Some(shown); } } - -/// The first file of `parseApplyPatchFiles`: its relative path and patch. -struct File { - path: String, - patch: String, -} - -fn first_file(files: Option<&Value>) -> Option { - files?.as_array()?.iter().find_map(|item| { - let file = item.as_object()?; - let text = |key: &str| file.get(key).and_then(Value::as_str); - let number = |key: &str| file.get(key).and_then(opencode_ui::tool_info::finite_number); - let kind = text("type").or(match text("status") { - Some("added") => Some("add"), - Some("deleted") => Some("delete"), - Some("modified") => Some("update"), - _ => None, - }); - let relative = text("file").or(text("relativePath")); - let absolute = text("filePath").or(relative); - let complete = kind.is_some_and(|kind| !kind.is_empty()) - && absolute.is_some_and(|path| !path.is_empty()) - && number("additions").is_some() - && number("deletions").is_some(); - let relative = relative.filter(|path| !path.is_empty() && complete)?; - Some(File { path: relative.to_owned(), patch: text("patch")?.to_owned() }) - }) -} - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::first_file; - - #[test] - fn the_first_complete_file_has_the_patch() { - let files = json!([ - { "file": "a.rs", "type": "update", "patch": "@@", "additions": 1 }, - { "relativePath": "b.rs", "status": "modified", "patch": "@@ -1 +1 @@", "additions": 1, "deletions": 1 }, - ]); - let file = first_file(Some(&files)).unwrap(); - assert_eq!((file.path.as_str(), file.patch.as_str()), ("b.rs", "@@ -1 +1 @@")); - assert!( - first_file(Some( - &json!([{ "file": "c.rs", "status": "renamed", "patch": "", "additions": 0, "deletions": 0 }]) - )) - .is_none() - ); - assert!(first_file(Some(&json!({}))).is_none()); - } -} diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/generic.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/generic.rs index d820c15fdda..3b9e5576e26 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/generic.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/generic.rs @@ -1,6 +1,6 @@ //! Fallback view for unrecognized tools. -use opencode_ui::tool_info::primitive_input_summary; +use opencode_ui::tool_info::call_summary; use super::dispatch::{ICON_WIDTH, Inline, InlineTool, Props, Status}; use crate::prelude::*; @@ -69,7 +69,7 @@ impl Generic { let tool = props.part.name.as_str(); inner.inline.set(Inline { spinner: matches!(status, Status::Streaming | Status::Running), - text: summary(tool, &props.input), + text: call_summary(tool, props.input.iter()), clickable: !entries.is_empty() || !output.is_empty(), ..Inline::new(props, if status == Status::Error { "✗" } else { "✓" }, tool, status == Status::Completed) }); @@ -105,11 +105,3 @@ impl Inner { } } } - -pub fn summary(tool: &str, input: &serde_json::Map) -> String { - let args = primitive_input_summary(input, &[]).split_whitespace().collect::>().join(" "); - if args.is_empty() { - return tool.to_owned(); - } - format!("{tool} {args}") -} diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/inline.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/inline.rs index ba7171f6014..c8656a2f889 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/inline.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/inline.rs @@ -1,6 +1,6 @@ use super::dispatch::{Inline, InlineTool, Props, ToolView, finite, format_path, number}; use crate::routes::session::messages::list::Context; -use opencode_ui::tool_info::web_search_provider_name; +use opencode_ui::tool_info::{SearchInput, SkillInput, WebFetchInput, WebSearchInput, web_search_provider_name}; use opentui::prelude::View; type Line = fn(&Context<'_>, &Props<'_>) -> Inline; @@ -30,9 +30,9 @@ pub(super) fn glob(cx: &Context<'_>, props: &Props<'_>) -> Inline { /// The line Glob and Grep share: `Glob "" in ( matches)`. fn search(cx: &Context<'_>, props: &Props<'_>, name: &str, pending: &str, matches: Option) -> Inline { - let pattern = props.input_str("pattern"); + let pattern = SearchInput(props.input).pattern().str(); let mut text = format!("{name} \"{}\" ", pattern.unwrap_or_default()); - if let Some(path) = props.input_str("path").filter(|path| !path.is_empty()) { + if let Some(path) = props.input.path().non_empty() { text.push_str(&format!("in {} ", format_path(cx, Some(path)))); } if let Some(matches) = matches { @@ -48,7 +48,7 @@ pub(super) fn grep(cx: &Context<'_>, props: &Props<'_>) -> Inline { } pub(super) fn webfetch(_cx: &Context<'_>, props: &Props<'_>) -> Inline { - let url = props.input_str("url"); + let url = WebFetchInput(props.input).url().str(); Inline { text: format!("WebFetch {}", url.unwrap_or_default()), ..Inline::new(props, "%", "Fetching from the web…", url.is_some_and(|url| !url.is_empty())) @@ -56,7 +56,7 @@ pub(super) fn webfetch(_cx: &Context<'_>, props: &Props<'_>) -> Inline { } pub(super) fn websearch(_cx: &Context<'_>, props: &Props<'_>) -> Inline { - let query = props.input_str("query"); + let query = WebSearchInput(props.input).query().str(); // ``: an empty name is no provider. let provider = props.metadata.get("provider").filter(|value| value.as_str().is_some_and(|value| !value.is_empty())); let label = match provider { @@ -70,7 +70,7 @@ pub(super) fn websearch(_cx: &Context<'_>, props: &Props<'_>) -> Inline { } pub(super) fn skill(_cx: &Context<'_>, props: &Props<'_>) -> Inline { - let name = props.metadata.get("name").and_then(serde_json::Value::as_str).or(props.input_str("id")); + let name = props.metadata.get("name").and_then(serde_json::Value::as_str).or(SkillInput(props.input).id().str()); Inline { text: format!("Skill \"{}\"", name.unwrap_or_default()), ..Inline::new(props, "→", "Loading skill…", name.is_some_and(|name| !name.is_empty())) diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/patch.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/patch.rs index 05aaa8a6ba4..cf3c8d531c1 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/patch.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/patch.rs @@ -248,7 +248,7 @@ fn shown(cx: &Context<'_>, props: &Props<'_>) -> Shown { return Shown::Applied { applied, common }; } Shown::Pending { - targets: targets(props.input_str("patchText").unwrap_or_default()), + targets: targets(opencode_ui::tool_info::PatchInput(props.input).patch_text().text()), status: props.status(), error: props.error().map(str::to_owned), common, diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/question.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/question.rs index 5743ba9a43b..0c5e0a298ea 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/question.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/question.rs @@ -30,7 +30,7 @@ impl Question { } pub fn update(&self, cx: &Context<'_>, props: &Props<'_>) { - let questions = questions(props.input.get("questions")); + let questions = questions(opencode_ui::tool_info::QuestionInput(props.input).questions().array()); let answers = answers(props.metadata.get("answers")); self.inline.root().visible(answers.is_none()); self.block.root().visible(answers.is_some()); @@ -81,11 +81,9 @@ impl Question { } } -fn questions(value: Option<&Value>) -> Vec { - value - .and_then(Value::as_array) - .into_iter() - .flatten() +fn questions(items: &[Value]) -> Vec { + items + .iter() .filter_map(|item| item.get("question")?.as_str()) .filter(|question| !question.is_empty()) .map(str::to_owned) @@ -113,7 +111,7 @@ mod tests { #[test] fn questions_and_answers_parse_as_ts_does() { let input = json!([{ "question": "Which?" }, { "question": "" }, { "header": "x" }, "y"]); - assert_eq!(questions(Some(&input)), ["Which?"]); + assert_eq!(questions(input.as_array().unwrap()), ["Which?"]); assert_eq!(answers(Some(&json!({}))), None); assert_eq!(answers(None), None); assert_eq!( diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/read.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/read.rs index 9835da8424f..d1a0080b3a4 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/read.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/read.rs @@ -1,6 +1,6 @@ //! File-read status and loaded paths. -use super::dispatch::{Inline, InlineTool, Props, Status, finite, format_path, number, truthy}; +use super::dispatch::{Inline, InlineTool, Props, Status, finite, format_path, number}; use crate::prelude::*; use crate::routes::session::messages::list::Context; @@ -29,13 +29,14 @@ impl Read { } pub fn update(&self, cx: &Context<'_>, props: &Props<'_>) { - let path = props.input_str("path"); + let path = props.input.path().str(); + let input = opencode_ui::tool_info::ReadInput(props.input); let mut text = format!("Read {}", format_path(cx, path)); - if props.input.contains_key("offset") || props.input.contains_key("limit") { - let offset = finite(props.input.get("offset")).unwrap_or(1.0); + if input.offset().value().is_some() || input.limit().value().is_some() { + let offset = finite(input.offset().value()).unwrap_or(1.0); text.push_str(&format!(":{}-", number(offset))); - if truthy(props.input.get("limit")) { - let limit = finite(props.input.get("limit")).unwrap_or(0.0); + if input.limit().truthy() { + let limit = finite(input.limit().value()).unwrap_or(0.0); text.push_str(&number(offset + limit - 1.0)); } } diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/shell.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/shell.rs index 62580fcba46..78f27e9f8ac 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/shell.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/shell.rs @@ -2,6 +2,7 @@ use opencode_api::generated::ShellID; use opencode_ui::motion::Spinner; +use opencode_ui::tool_info::ShellInput; use opentui::input::strip_ansi_sequences; use super::dispatch::{Block, BlockTool, Header, Props, Status, content_width, format_path, paint_badge, status_badge}; @@ -116,8 +117,8 @@ impl Shell { None => props.output.clone(), }, shell, - command: props.input_str("command").map(str::to_owned), - workdir: format_path(cx, props.input_str("workdir")), + command: ShellInput(props.input).command().str().map(str::to_owned), + workdir: format_path(cx, ShellInput(props.input).workdir().str()), status, background: status == Status::Completed && props.metadata.get("status").and_then(serde_json::Value::as_str) == Some("running"), diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/subagent.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/subagent.rs index 894b417ae53..f2f9e9d01e8 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/subagent.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/subagent.rs @@ -2,7 +2,7 @@ use opencode_api::generated::ModelInfo; use opencode_store::SessionStatus; -use opencode_ui::tool_info::titlecase; +use opencode_ui::tool_info::{SubagentInput, titlecase}; use super::dispatch::{Inline, InlineTool, Props, Status}; use crate::prelude::*; @@ -38,7 +38,8 @@ impl Subagent { pub fn update(&self, cx: &Context<'_>, props: &Props<'_>) { let status = props.status(); let text = |key: &str| props.metadata.get(key).and_then(Value::as_str); - let continued = props.input_str("sessionID"); + let input = SubagentInput(props.input); + let continued = input.session_id().str(); let session = text("sessionID") .or(text("sessionId")) .or(continued.filter(|_| status != Status::Error)) @@ -48,12 +49,11 @@ impl Subagent { || session.as_deref().is_some_and(|id| { !id.is_empty() && cx.state.status(&SessionID(id.to_owned())) == SessionStatus::Running }); - let description = props.input_str("description"); - let agent = props.input_str("agent").or(props.input_str("subagent_type")).unwrap_or("General"); + let description = input.description().str(); + let agent = input.agent().str().or(input.subagent_type().str()).unwrap_or("General"); let title = if continuation { "Continue subagent".to_owned() } else { format!("{} Subagent", titlecase(agent)) }; - let model = - model_label(props.input_str("model"), cx.models).map(|model| format!(" · {model}")).unwrap_or_default(); + let model = model_label(input.model().str(), cx.models).map(|model| format!(" · {model}")).unwrap_or_default(); let icon = match (running, continuation, status) { (true, _, _) => "│", (_, true, _) => "↳", diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/todo.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/todo.rs index 3aae0ab3ee1..dec9522a476 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/todo.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/todo.rs @@ -1,6 +1,6 @@ //! Todo tool summary and checklist. -use opencode_ui::tool_info::{Todo as Item, TodoStatus, parse_todos, todo_marker}; +use opencode_ui::tool_info::{Todo as Item, TodoInput, TodoStatus, todo_marker}; use super::dispatch::{Block, BlockTool, Header, Inline, InlineTool, Props, Status, content_width}; use crate::prelude::*; @@ -33,7 +33,7 @@ impl Todo { pub fn update(&self, cx: &Context<'_>, props: &Props<'_>) { let status = props.status(); - let todos = parse_todos(props.input.get("todos").unwrap_or(&Value::Null)); + let todos = TodoInput(props.input).items(); let listed = status == Status::Completed && !todos.is_empty(); self.inline.root().visible(!listed); self.block.root().visible(listed); diff --git a/packages/cli-rs/crates/tui/src/routes/session/tools/write.rs b/packages/cli-rs/crates/tui/src/routes/session/tools/write.rs index d4dcbc9ad04..2949a379eff 100644 --- a/packages/cli-rs/crates/tui/src/routes/session/tools/write.rs +++ b/packages/cli-rs/crates/tui/src/routes/session/tools/write.rs @@ -34,7 +34,7 @@ impl Write { } pub fn update(&self, cx: &Context<'_>, props: &Props<'_>) { - let path = props.input_str("path"); + let path = props.input.path().str(); let completed = props.status() == Status::Completed; self.inline.root().visible(!completed); self.block.root().visible(completed); @@ -54,7 +54,7 @@ impl Write { width: content_width(cx), }); let path = path.unwrap_or_default(); - let content = props.input_str("content").unwrap_or_default(); + let content = opencode_ui::tool_info::WriteInput(props.input).content().text(); let shown = fingerprint(&(content, path, props.metadata.get("diagnostics"))); if self.shown.get() == Some(shown) { return; diff --git a/packages/cli-rs/crates/tui/tests/all/plugins.rs b/packages/cli-rs/crates/tui/tests/all/plugins.rs index ed828a18f26..8f06faeda11 100644 --- a/packages/cli-rs/crates/tui/tests/all/plugins.rs +++ b/packages/cli-rs/crates/tui/tests/all/plugins.rs @@ -268,11 +268,15 @@ fn one_call_of_many_effects_and_a_chain_of_closes_are_bounded() { } fn updates(setup: &mut abi::Setup) -> Result<(), String> { - let seen = Rc::new(Cell::new(0)); - let counted = seen.clone(); - setup.on_event(&["rpc.example.updated"], move |_, _| counted.set(counted.get() + 1)); + let seen = Rc::new(RefCell::new(Vec::new())); + let heard = seen.clone(); + // A type this client does not know reaches the handler that names it, and only that one. + setup.on_event(&["rpc.example.updated", "future.example.updated"], move |_, event| { + heard.borrow_mut().push(event.tag().to_owned()); + }); + setup.on_event(&["future.example.other"], |_, _| {}); setup.slot(abi::Placement::append("home.footer"), move |_, _, _| { - abi::Render::Show(abi::Node::text([abi::Span::new(format!("updates {}", seen.get()))])) + abi::Render::Show(abi::Node::text([abi::Span::new(format!("updates: {}", seen.borrow().join(" ")))])) }); Ok(()) } @@ -287,12 +291,13 @@ fn an_event_handler_renders_its_plugins_claims_again() { )]); let deps = Deps { events: true, ..support::deps(Arc::new(memory.clone())) }; let h = home_with(updates, deps); - h.wait_for("updates 0"); - memory.emit(&json!({ - "id": "evt_rpc", "created": 1, "type": "rpc.example.updated", - "location": { "directory": support::DIRECTORY }, "data": {}, - })); - h.wait_for("updates 1"); + h.wait_for("updates:"); + for tag in ["future.example.other", "future.example.updated", "rpc.example.updated"] { + let location = json!({ "directory": support::DIRECTORY }); + memory + .emit(&json!({ "id": format!("evt_{tag}"), "created": 1, "type": tag, "location": location, "data": {} })); + } + h.wait_for("updates: future.example.updated rpc.example.updated"); } thread_local! { diff --git a/packages/cli-rs/crates/tui/tests/all/pump.rs b/packages/cli-rs/crates/tui/tests/all/pump.rs index 733899e40b0..a571248c1cf 100644 --- a/packages/cli-rs/crates/tui/tests/all/pump.rs +++ b/packages/cli-rs/crates/tui/tests/all/pump.rs @@ -7,6 +7,7 @@ use std::rc::Rc; use std::sync::Arc; use std::time::Duration; +use opencode_api::generated::EventKind; use opencode_api::memory::{Memory, Route as MemoryRoute}; use opencode_tui::{Deps, Route}; use opentui::app::ProxyError; @@ -49,7 +50,7 @@ fn a_burst_while_the_ui_is_busy_does_not_stop_later_events() { // Someone listens to the burst, so it goes through the pump. let heard = Rc::new(Cell::new(0)); let count = heard.clone(); - let _listening = opencode_tui::features::events::subscribe(&h.tui, ["filesystem.changed"], move |_, _| { + let _listening = opencode_tui::features::events::subscribe(&h.tui, [EventKind::FilesystemChanged], move |_, _| { count.set(count.get() + 1); }); // The UI thread is busy: nothing drains its queue until it is full. @@ -74,9 +75,10 @@ fn an_event_nobody_listens_to_stays_in_the_store() { h.wait_for("Demo Model"); let heard = Rc::new(RefCell::new(Vec::new())); let record = heard.clone(); - let _listening = opencode_tui::features::events::subscribe(&h.tui, ["tui.prompt.append"], move |_, event| { - record.borrow_mut().push(event.tag().to_owned()); - }); + let _listening = + opencode_tui::features::events::subscribe(&h.tui, [EventKind::TuiPromptAppend], move |_, event| { + record.borrow_mut().push(event.tag().to_owned()); + }); memory.emit(&changed(0)); memory.emit(&append("evt_after", "after")); h.wait("the append", || h.text() == "after"); diff --git a/packages/cli-rs/crates/tui/tests/all/tabs.rs b/packages/cli-rs/crates/tui/tests/all/tabs.rs index 4438fff077d..71e2792b3a7 100644 --- a/packages/cli-rs/crates/tui/tests/all/tabs.rs +++ b/packages/cli-rs/crates/tui/tests/all/tabs.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::Arc; -use opencode_api::generated::SessionID; +use opencode_api::generated::{EventKind, SessionID}; use opencode_api::memory::{Memory, Route as MemoryRoute}; use opencode_plugin::abi::{self, v2}; use opencode_tui::panel::{Presentation, Target}; @@ -316,7 +316,7 @@ fn a_deletion_lost_in_a_signal_overflow_still_closes_its_tab() { h.open("ses_b"); h.tui.navigate(support::session_route("ses_a")); h.wait_for("Write the docs"); - let _listening = opencode_tui::features::events::subscribe(&h.tui, ["filesystem.changed"], |_, _| {}); + let _listening = opencode_tui::features::events::subscribe(&h.tui, [EventKind::FilesystemChanged], |_, _| {}); let deleted = json!({ "id": "evt_deleted", "created": 3, "type": "session.deleted", "durable": { "aggregateID": "ses_b", "seq": 1, "version": 1 }, diff --git a/packages/cli-rs/crates/ui/src/motion/scanner.rs b/packages/cli-rs/crates/ui/src/motion/scanner.rs index 366934a3161..4981b2399fc 100644 --- a/packages/cli-rs/crates/ui/src/motion/scanner.rs +++ b/packages/cli-rs/crates/ui/src/motion/scanner.rs @@ -103,12 +103,14 @@ fn trail_colors(color: Color, steps: usize) -> Vec { /// `getScannerState` for the bidirectional scanner. struct State { position: i64, - holding: bool, - hold_progress: i64, - hold_total: i64, - movement_progress: i64, - movement_total: i64, forward: bool, + phase: Phase, +} + +/// What the head does, and how far through it the frame is. +enum Phase { + Holding { progress: i64, total: i64 }, + Moving { progress: i64, total: i64 }, } impl State { @@ -116,42 +118,25 @@ impl State { let chars = options.width as i64; let (hold_end, hold_start) = (options.hold_end as i64, options.hold_start as i64); let backward = chars - 1; - let still = |position, progress, total, forward| Self { - position, - holding: true, - hold_progress: progress, - hold_total: total, - movement_progress: 0, - movement_total: 0, - forward, - }; - let moving = |position, progress, total, forward| Self { - position, - holding: false, - hold_progress: 0, - hold_total: 0, - movement_progress: progress, - movement_total: total, - forward, - }; + let state = |position, forward, phase| Self { position, forward, phase }; if frame < chars { - return moving(frame, frame, chars, true); + return state(frame, true, Phase::Moving { progress: frame, total: chars }); } if frame < chars + hold_end { - return still(chars - 1, frame - chars, hold_end, true); + return state(chars - 1, true, Phase::Holding { progress: frame - chars, total: hold_end }); } if frame < chars + hold_end + backward { let index = frame - chars - hold_end; - return moving(chars - 2 - index, index, backward, false); + return state(chars - 2 - index, false, Phase::Moving { progress: index, total: backward }); } - still(0, frame - chars - hold_end - backward, hold_start, false) + state(0, false, Phase::Holding { progress: frame - chars - hold_end - backward, total: hold_start }) } /// `calculateColorIndex`: 0 at the head, the distance behind it along the trail, or -1 when unlit. fn color_index(&self, char: i64, trail: i64) -> i64 { let distance = if self.forward { self.position - char } else { char - self.position }; - if self.holding { - return distance + self.hold_progress; + if let Phase::Holding { progress, .. } = self.phase { + return distance + progress; } if distance > 0 && distance < trail { return distance; @@ -165,14 +150,14 @@ impl State { if !options.enable_fading { return 1.0; } - if self.holding && self.hold_total > 0 { - let progress = (self.hold_progress as f64 / self.hold_total as f64).min(1.0); - return min.max(1.0 - progress * (1.0 - min)); + match self.phase { + Phase::Holding { progress, total } if total > 0 => { + min.max(1.0 - (progress as f64 / total as f64).min(1.0) * (1.0 - min)) + } + Phase::Moving { progress, total } if total > 0 => { + min + (progress as f64 / 1.max(total - 1) as f64).min(1.0) * (1.0 - min) + } + _ => 1.0, } - if !self.holding && self.movement_total > 0 { - let progress = (self.movement_progress as f64 / 1.max(self.movement_total - 1) as f64).min(1.0); - return min + progress * (1.0 - min); - } - 1.0 } } diff --git a/packages/cli-rs/crates/ui/src/permission.rs b/packages/cli-rs/crates/ui/src/permission.rs index ec17d916a5d..9f559251d31 100644 --- a/packages/cli-rs/crates/ui/src/permission.rs +++ b/packages/cli-rs/crates/ui/src/permission.rs @@ -1,7 +1,9 @@ -use opencode_api_types::js::truthy; use serde_json::{Map, Value}; -use crate::tool_info::{canonical_tool_name, finite_number, web_search_provider_label}; +use crate::tool_info::{ + EditInput, LspInput, SearchInput, ShellInput, SubagentInput, ToolInput, ToolKind, WebFetchInput, WebSearchInput, + finite_number, web_search_provider_label, +}; #[derive(Debug, Default, PartialEq)] pub struct Presentation { @@ -22,8 +24,7 @@ pub fn presentation( tool_metadata: &Value, format_path: &dyn Fn(&str) -> String, ) -> Presentation { - let canonical = canonical_tool_name(action); - let input = normalize_input(canonical, input); + let input = ToolInput::json(input); let mut metadata = dict(tool_metadata); if let Some(extra) = request_metadata { metadata.extend(extra.iter().map(|(key, value)| (key.clone(), value.clone()))); @@ -32,29 +33,30 @@ pub fn presentation( map.get(key).and_then(Value::as_str).unwrap_or_default().to_owned() }; let first = resources.first().cloned().unwrap_or_default(); - let or = |value: String, fallback: &str| { - if value.is_empty() { fallback.to_owned() } else { value } + let or = |value: &str, fallback: &str| { + if value.is_empty() { fallback.to_owned() } else { value.to_owned() } }; let some = |value: String| (!value.is_empty()).then_some(value); + let path = input.any_path().unwrap_or_default(); - match canonical { - "edit" => { - let file = or(text(&input, "path"), &first); + match ToolKind::of(action) { + ToolKind::Edit => { + let file = or(path, &first); let files = metadata.get("files").and_then(Value::as_array); let changed = dict(files.and_then(|files| files.first()).unwrap_or(&Value::Null)); - let diff = some(or(or(text(&changed, "patch"), &text(&changed, "diff")), &text(&metadata, "diff"))); + let diff = some(or(&or(&text(&changed, "patch"), &text(&changed, "diff")), &text(&metadata, "diff"))); Presentation { icon: "→", title: format!("Edit {}", format_path(&file)), - patch: if diff.is_some() { None } else { some(text(&input, "patchText")) }, + patch: if diff.is_some() { None } else { EditInput(input).patch_text().non_empty().map(str::to_owned) }, diff, file: Some(file), ..Presentation::default() } } - "read" | "list" => { - let value = or(text(&input, "path"), &first); - let title = if canonical == "read" { "Read" } else { "List" }; + kind @ (ToolKind::Read | ToolKind::List) => { + let value = or(path, &first); + let title = if kind == ToolKind::Read { "Read" } else { "List" }; Presentation { icon: "→", title: format!("{title} {}", format_path(&value)), @@ -62,9 +64,9 @@ pub fn presentation( ..Presentation::default() } } - "glob" | "grep" => { - let pattern = or(text(&input, "pattern"), &first); - let title = if canonical == "glob" { "Glob" } else { "Grep" }; + kind @ (ToolKind::Glob | ToolKind::Grep) => { + let pattern = or(SearchInput(input).pattern().text(), &first); + let title = if kind == ToolKind::Glob { "Glob" } else { "Grep" }; Presentation { icon: "✱", title: format!("{title} \"{pattern}\""), @@ -72,31 +74,31 @@ pub fn presentation( ..Presentation::default() } } - "shell" => { - let command = text(&input, "command"); + ToolKind::Shell => Presentation { + icon: "#", + title: "Shell command".to_owned(), + lines: match ShellInput(input).command().non_empty() { + Some(command) => vec![format!("$ {command}")], + None => resources.iter().map(|item| format!("- {item}")).collect(), + }, + ..Presentation::default() + }, + ToolKind::Subagent => { + let input = SubagentInput(input); + let agent = input.agent().non_empty().or(input.subagent_type().non_empty()).unwrap_or("general"); Presentation { icon: "#", - title: "Shell command".to_owned(), - lines: match some(command) { - Some(command) => vec![format!("$ {command}")], - None => resources.iter().map(|item| format!("- {item}")).collect(), - }, - ..Presentation::default() - } - } - "subagent" => { - let agent = or(text(&input, "agent"), "general"); - Presentation { - icon: "#", - title: format!("{} Subagent", crate::tool_info::titlecase(&agent)), - lines: some(text(&input, "description")) + title: format!("{} Subagent", crate::tool_info::titlecase(agent)), + lines: input + .description() + .non_empty() .map(|description| vec![format!("◉ {description}")]) .unwrap_or_default(), ..Presentation::default() } } - "webfetch" => { - let url = or(text(&input, "url"), &text(&metadata, "url")); + ToolKind::WebFetch => { + let url = or(WebFetchInput(input).url().text(), &text(&metadata, "url")); Presentation { icon: "%", title: format!("WebFetch {url}"), @@ -104,8 +106,8 @@ pub fn presentation( ..Presentation::default() } } - "websearch" => { - let query = or(text(&input, "query"), &text(&metadata, "query")); + ToolKind::WebSearch => { + let query = or(WebSearchInput(input).query().text(), &text(&metadata, "query")); let title = web_search_provider_label(metadata.get("provider").unwrap_or(&Value::Null)); Presentation { icon: "◈", @@ -114,31 +116,32 @@ pub fn presentation( ..Presentation::default() } } - "lsp" => { - let file = text(&input, "path"); - let operation = or(text(&input, "operation"), "request"); - let number = |key: &str| input.get(key).and_then(finite_number); - let position = - number("line").zip(number("character")).map(|(line, character)| format!("{line}:{character}")); + ToolKind::Lsp => { + let lsp = LspInput(input); + let operation = or(lsp.operation().text(), "request"); + let number = |value: Option<&Value>| value.and_then(finite_number); + let position = number(lsp.line().value()) + .zip(number(lsp.character().value())) + .map(|(line, character)| format!("{line}:{character}")); let mut title = format!("LSP {operation}"); let mut lines = Vec::new(); - if input.get("operation").is_some_and(truthy) { + if lsp.operation().truthy() { lines.push(format!("Operation: {operation}")); } - if !file.is_empty() { - title.push_str(&format!(" {}", format_path(&file))); + if !path.is_empty() { + title.push_str(&format!(" {}", format_path(path))); if let Some(position) = &position { title.push_str(&format!(":{position}")); } - lines.push(format!("Path: {}", format_path(&file))); + lines.push(format!("Path: {}", format_path(path))); } if let Some(position) = position { lines.push(format!("Position: {position}")); } Presentation { icon: "→", title, lines, ..Presentation::default() } } - "external_directory" => { - let raw = or(or(text(&metadata, "parentDir"), &text(&metadata, "filepath")), &first); + ToolKind::ExternalDirectory => { + let raw = or(&or(&text(&metadata, "parentDir"), &text(&metadata, "filepath")), &first); Presentation { icon: "←", title: format!("Access external directory {}", format_path(&wildcard_directory(&raw))), @@ -146,7 +149,7 @@ pub fn presentation( ..Presentation::default() } } - "doom_loop" => Presentation { + ToolKind::DoomLoop => Presentation { icon: "⟳", title: "Continue after repeated failures".to_owned(), lines: vec!["This keeps the session running despite repeated failures.".to_owned()], @@ -185,20 +188,6 @@ fn wildcard_directory(value: &str) -> String { prefix.trim_end_matches(['/', '\\']).to_owned() } -fn normalize_input(action: &str, value: &Value) -> Map { - let mut input = dict(value); - let text = |key: &str| input.get(key).and_then(Value::as_str).filter(|text| !text.is_empty()).map(str::to_owned); - let path = text("path").or_else(|| text("filePath")).or_else(|| text("filepath")); - let agent = text("agent").or_else(|| text("subagent_type")); - if let Some(path) = path.filter(|_| matches!(action, "read" | "edit" | "list" | "lsp")) { - input.insert("path".to_owned(), Value::String(path)); - } - if let Some(agent) = agent.filter(|_| action == "subagent") { - input.insert("agent".to_owned(), Value::String(agent)); - } - input -} - fn dict(value: &Value) -> Map { value.as_object().cloned().unwrap_or_default() } diff --git a/packages/cli-rs/crates/ui/src/tool_info.rs b/packages/cli-rs/crates/ui/src/tool_info.rs index 51a821286de..7dee23d8718 100644 --- a/packages/cli-rs/crates/ui/src/tool_info.rs +++ b/packages/cli-rs/crates/ui/src/tool_info.rs @@ -1,6 +1,8 @@ //! One-line tool summaries shared by `run`, mini and the full TUI. -use opencode_api_types::js::{js_string, truthy}; +use indexmap::IndexMap; +use opencode_api_types::js::js_string; +pub use opencode_api_types::tool::*; use opencode_api_types::{SessionMessageAssistantTool, SessionMessageAssistantToolState, ToolContent}; use opencode_util::json_object; use serde_json::{Map, Value}; @@ -19,47 +21,37 @@ pub struct ToolInline { /// The summary of `part`. Paths are shown relative to `directory`, else to the current directory. pub fn tool_inline_info(part: &SessionMessageAssistantTool, directory: Option<&str>) -> ToolInline { let frame = Frame::new(part, directory); - let draw = match frame.name { - "invalid" => run_invalid, - "shell" => run_shell, - "write" => run_write, - "edit" => run_edit, - "patch" => run_patch, - "batch" => run_batch, - "subagent" => run_task, - "todowrite" => run_todo, - "question" => run_question, - "read" => run_read, - "glob" => run_glob, - "grep" => run_grep, - "list" => run_list, - "lsp" => run_lsp, - "webfetch" => run_webfetch, - "websearch" => run_web_search, - "skill" => run_skill, + let draw = match frame.kind { + ToolKind::Invalid => run_invalid, + ToolKind::Shell => run_shell, + ToolKind::Write => run_write, + ToolKind::Edit => run_edit, + ToolKind::Patch => run_patch, + ToolKind::Batch => run_batch, + ToolKind::Subagent => run_task, + ToolKind::Todo => run_todo, + ToolKind::Question => run_question, + ToolKind::Read => run_read, + ToolKind::Glob => run_glob, + ToolKind::Grep => run_grep, + ToolKind::List => run_list, + ToolKind::Lsp => run_lsp, + ToolKind::WebFetch => run_webfetch, + ToolKind::WebSearch => run_web_search, + ToolKind::Skill => run_skill, _ => return fallback_inline(&frame), }; draw(&frame).unwrap_or_else(|| fallback_inline(&frame)) } -/// The current name of a tool whose persisted name is a legacy alias. -pub fn canonical_tool_name(name: &str) -> &str { - match name { - "bash" => "shell", - "task" => "subagent", - "apply_patch" => "patch", - _ => name, - } -} - pub fn finite_number(value: &Value) -> Option { value.as_f64().filter(|number| number.is_finite()) } /// `[key=value, …]` over the string, number, and boolean entries of `input`, in wire order. -pub fn primitive_input_summary(input: &Map, omit: &[&str]) -> String { +pub fn primitive_input_summary<'a>(input: impl IntoIterator, omit: &[&str]) -> String { let entries: Vec<_> = input - .iter() + .into_iter() .filter(|(key, value)| { !omit.contains(&key.as_str()) && matches!(value, Value::String(_) | Value::Number(_) | Value::Bool(_)) }) @@ -108,13 +100,16 @@ pub fn execute_calls(value: &Value) -> Vec { } pub fn execute_call_summary(call: &ExecuteCall) -> String { - let args = primitive_input_summary(call.input.as_ref().unwrap_or(&Map::new()), &[]); - let args = args.split(char::is_whitespace).filter(|part| !part.is_empty()); - let args = args.collect::>().join(" "); + call_summary(&call.tool, call.input.iter().flatten()) +} + +/// `tool [key=value …]`: a call by its name and the primitive entries of its input, on one line. +pub fn call_summary<'a>(tool: &str, input: impl IntoIterator) -> String { + let args = primitive_input_summary(input, &[]).split_whitespace().collect::>().join(" "); if args.is_empty() { - return call.tool.clone(); + return tool.to_owned(); } - format!("{} {args}", call.tool) + format!("{tool} {args}") } pub fn web_search_provider_name(provider: &Value) -> String { @@ -145,7 +140,7 @@ pub fn tool_display_metadata(state: &SessionMessageAssistantToolState) -> Map String { _ => None, } } - let name = canonical_tool_name(name); + let kind = ToolKind::of(name); // V2 shell content appends model-only status after the user-visible command output. - if name == "shell" { + if kind == ToolKind::Shell { return content.iter().find_map(text_of).flatten().unwrap_or_default().to_owned(); } let joined = content @@ -189,30 +184,12 @@ pub fn tool_output_text(name: &str, content: &[ToolContent]) -> String { .filter(|text| !text.is_empty()) .collect::>() .join("\n"); - if name == "read" { + if kind == ToolKind::Read { return read_display_text(&joined).unwrap_or(joined); } joined } -/// Read's model content is a JSON page envelope; this unwraps the human-facing text. -pub fn read_display_text(text: &str) -> Option { - if !text.starts_with('{') { - return None; - } - let envelope = dict(serde_json::from_str::(text).ok().as_ref()); - if let Some(content) = envelope.get("content").and_then(Value::as_str) { - let page = envelope.get("type").and_then(Value::as_str) == Some("text-page"); - if page || envelope.get("encoding").and_then(Value::as_str) == Some("utf8") { - return Some(content.to_owned()); - } - } - let entries = envelope.get("entries")?.as_array()?; - let lines: Vec<_> = - entries.iter().filter_map(|entry| entry.as_str().or_else(|| entry.get("path")?.as_str())).collect(); - Some(lines.join("\n")) -} - /// Show paths inside the working directory as relative paths; leave outside paths absolute. pub fn tool_path(input: &str, directory: Option<&str>, home: Option<&str>) -> String { if let Some(directory) = directory { @@ -222,38 +199,6 @@ pub fn tool_path(input: &str, directory: Option<&str>, home: Option<&str>) -> St crate::path::format_path(input, &cwd.to_string_lossy(), home, true) } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TodoStatus { - Pending, - InProgress, - Completed, - Cancelled, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Todo { - pub content: String, - pub status: TodoStatus, -} - -/// The items of a `todowrite` input; an unknown status reads as pending. -pub fn parse_todos(value: &Value) -> Vec { - let Some(items) = value.as_array() else { return Vec::new() }; - items - .iter() - .filter_map(|item| { - let content = item.as_object()?.get("content")?.as_str().filter(|content| !content.is_empty())?; - let status = match item.get("status").and_then(Value::as_str) { - Some("in_progress") => TodoStatus::InProgress, - Some("completed") => TodoStatus::Completed, - Some("cancelled") => TodoStatus::Cancelled, - _ => TodoStatus::Pending, - }; - Some(Todo { content: content.to_owned(), status }) - }) - .collect() -} - pub fn todo_marker(status: TodoStatus, ascii: bool) -> &'static str { match (status, ascii) { (TodoStatus::Completed, false) => "[✓]", @@ -269,7 +214,8 @@ pub fn todo_marker(status: TodoStatus, ascii: bool) -> &'static str { struct Frame<'a> { directory: Option<&'a str>, name: &'a str, - input: Map, + kind: ToolKind, + input: ToolInput<'a>, meta: Map, status: &'a str, output: String, @@ -277,20 +223,15 @@ struct Frame<'a> { impl<'a> Frame<'a> { fn new(part: &'a SessionMessageAssistantTool, directory: Option<&'a str>) -> Self { - let name = canonical_tool_name(&part.name); - let status = part.state.tag(); - if let SessionMessageAssistantToolState::Streaming(_) = part.state { - return Frame { directory, name, input: Map::new(), meta: Map::new(), status, output: String::new() }; - } - // Read the input as JSON so that a member this client does not know reads like a known one. - let state = serde_json::to_value(&part.state).unwrap_or_default(); + let kind = ToolKind::of(&part.name); Frame { directory, - name, - input: normalize_input(name, state.get("input")), - meta: normalize_metadata(name, tool_display_metadata(&part.state)), - status, - output: tool_output_text(name, &tool_display_content(&part.state)), + name: canonical_tool_name(&part.name), + kind, + input: ToolInput::of(&part.state), + meta: normalize_metadata(kind, tool_display_metadata(&part.state)), + status: part.state.tag(), + output: tool_output_text(&part.name, &tool_display_content(&part.state)), } } @@ -299,37 +240,17 @@ impl<'a> Frame<'a> { } /// `displayPath(p, value)`: `None` where the TS would throw on a value that is not a string. - fn path(&self, value: Option<&Value>) -> Option { - if !value.is_some_and(truthy) { + fn path(&self, value: Field) -> Option { + if !value.truthy() { return Some(String::new()); } - Some(tool_path(value?.as_str()?, self.directory, None)) + Some(tool_path(value.str()?, self.directory, None)) } } -/// `normalizeInput`: legacy `filePath` and `subagent_type` as `path` and `agent`. -pub fn normalize_input(name: &str, value: Option<&Value>) -> Map { - let mut input = dict(value); - let path = match input.get("path") { - Some(Value::String(path)) => path.clone(), - _ => text(input.get("filePath")).to_owned(), - }; - let agent = match input.get("agent") { - Some(Value::String(agent)) => agent.clone(), - _ => text(input.get("subagent_type")).to_owned(), - }; - if ["read", "write", "edit", "lsp"].contains(&name) && !path.is_empty() { - input.insert("path".to_owned(), Value::String(path)); - } - if name == "subagent" && !agent.is_empty() { - input.insert("agent".to_owned(), Value::String(agent)); - } - input -} - /// `normalizeMetadata`: the files of edit and patch metadata with legacy field names mapped. -pub fn normalize_metadata(name: &str, mut metadata: Map) -> Map { - if !["edit", "patch"].contains(&name) { +pub fn normalize_metadata(kind: ToolKind, mut metadata: Map) -> Map { + if !matches!(kind, ToolKind::Edit | ToolKind::Patch) { return metadata; } if let Some(Value::Array(files)) = metadata.get("files") { @@ -341,7 +262,7 @@ pub fn normalize_metadata(name: &str, mut metadata: Map) -> Map Option { - let field = |key| text(value.get(key)); + let field = |key| value.get(key).and_then(Value::as_str).unwrap_or_default(); let name = [field("file"), field("relativePath"), field("filePath")].into_iter().find(|name| !name.is_empty())?; let status = match (field("status"), field("type")) { ("", "add") => "added", @@ -361,11 +282,8 @@ fn normalize_file(value: &Value) -> Option { } fn fallback_inline(frame: &Frame) -> ToolInline { - let input = if frame.input.is_empty() { - "Unknown".to_owned() - } else { - serde_json::to_string(&frame.input).unwrap_or_default() - }; + let input = frame.input.iter().collect::>(); + let input = if input.is_empty() { "Unknown".to_owned() } else { serde_json::to_string(&input).unwrap_or_default() }; inline("⚙", format!("{} {input}", frame.name)) } @@ -378,8 +296,8 @@ fn run_grep(frame: &Frame) -> Option { } fn search(frame: &Frame, label: &str, metadata: &str) -> Option { - let root = frame.input.get("path").filter(|root| !root.is_null()); - let suffix = if root.is_some_and(truthy) { format!("in {}", frame.path(root)?) } else { String::new() }; + let root = frame.input.path(); + let suffix = if root.truthy() { format!("in {}", frame.path(root)?) } else { String::new() }; let description = match frame.meta.get(metadata) { None => suffix, Some(matches) => { @@ -388,12 +306,12 @@ fn search(frame: &Frame, label: &str, metadata: &str) -> Option { format!("{suffix}{separator}{} match{plural}", js_string(matches)) } }; - let title = format!("{label} \"{}\"", or_empty(frame.input.get("pattern"))); + let title = format!("{label} \"{}\"", SearchInput(frame.input).pattern().js()); Some(ToolInline { description: non_empty(description), ..inline("✱", title) }) } fn run_list(frame: &Frame) -> Option { - let dir = text(frame.input.get("path")); + let dir = frame.input.path().text(); if dir.is_empty() { return Some(inline("→", "List".to_owned())); } @@ -401,59 +319,63 @@ fn run_list(frame: &Frame) -> Option { } fn run_read(frame: &Frame) -> Option { - let file = frame.path(frame.input.get("path"))?; - let description = non_empty(primitive_input_summary(&frame.input, &["path"])); + let file = frame.path(frame.input.legacy_path())?; + let description = non_empty(primitive_input_summary(frame.input.iter(), &["path"])); Some(ToolInline { description, ..inline("→", format!("Read {file}")) }) } fn run_write(frame: &Frame) -> Option { - let title = format!("Write {}", frame.path(frame.input.get("path"))?); + let title = format!("Write {}", frame.path(frame.input.legacy_path())?); Some(block("←", title, frame.completed_output())) } fn run_webfetch(frame: &Frame) -> Option { - let url = frame.input.get("url"); - if !url.is_some_and(truthy) { + let url = WebFetchInput(frame.input).url(); + if !url.truthy() { return Some(inline("%", "WebFetch".to_owned())); } - Some(inline("%", format!("WebFetch {}", or_empty(url)))) + Some(inline("%", format!("WebFetch {}", url.js()))) } fn run_edit(frame: &Frame) -> Option { let file = frame.meta.get("files").and_then(Value::as_array).and_then(|files| files.first()); let patch = file.and_then(|file| file.get("patch")).filter(|patch| !patch.is_null()); let body = patch.or_else(|| frame.meta.get("diff")).and_then(Value::as_str).map(str::to_owned); - let title = format!("Edit {}", frame.path(frame.input.get("path"))?); + let title = format!("Edit {}", frame.path(frame.input.legacy_path())?); Some(block("←", title, body)) } fn run_web_search(frame: &Frame) -> Option { let title = web_search_provider_label(frame.meta.get("provider").unwrap_or(&Value::Null)); - let query = frame.input.get("query"); - if !query.is_some_and(truthy) { + let query = WebSearchInput(frame.input).query(); + if !query.truthy() { return Some(inline("◈", title)); } - Some(inline("◈", format!("{title} \"{}\"", or_empty(query)))) + Some(inline("◈", format!("{title} \"{}\"", query.js()))) } fn run_task(frame: &Frame) -> Option { - let agent = frame.input.get("agent"); - let kind = titlecase(if agent.is_some_and(truthy) { agent?.as_str()? } else { "unknown" }); + let input = SubagentInput(frame.input); + let agent = input.legacy_agent(); + let kind = titlecase(if agent.truthy() { agent.str()? } else { "unknown" }); let icon = match frame.status { "error" => "✗", "running" => "•", _ => "✓", }; - let description = frame.input.get("description"); - if !description.is_some_and(truthy) { + let description = input.description(); + if !description.truthy() { return Some(inline(icon, format!("{kind} Subagent"))); } - Some(ToolInline { description: Some(format!("{kind} Agent")), ..inline(icon, or_empty(description)) }) + Some(ToolInline { description: Some(format!("{kind} Agent")), ..inline(icon, description.js()) }) } fn run_skill(frame: &Frame) -> Option { - let name = [frame.meta.get("name"), frame.input.get("id")].into_iter().flatten().find(|name| !name.is_null()); - Some(inline("→", format!("Skill \"{}\"", or_empty(name)))) + let name = [frame.meta.get("name"), SkillInput(frame.input).id().value()] + .into_iter() + .flatten() + .find(|name| !name.is_null()); + Some(inline("→", format!("Skill \"{}\"", name.map(js_string).unwrap_or_default()))) } fn run_patch(frame: &Frame) -> Option { @@ -470,8 +392,8 @@ fn run_patch(frame: &Frame) -> Option { } fn run_todo(frame: &Frame) -> Option { - let todos = parse_todos(frame.input.get("todos").unwrap_or(&Value::Null)); - let body = todos + let body = TodoInput(frame.input) + .items() .iter() .map(|todo| format!("{} {}", todo_marker(todo.status, false), todo.content)) .collect::>() @@ -480,7 +402,7 @@ fn run_todo(frame: &Frame) -> Option { } fn run_question(frame: &Frame) -> Option { - let total = list_len(frame.input.get("questions")); + let total = QuestionInput(frame.input).questions().array().len(); Some(inline("→", format!("Asked {total} question{}", plural(total)))) } @@ -489,29 +411,29 @@ fn run_invalid(frame: &Frame) -> Option { } fn run_batch(frame: &Frame) -> Option { - let calls = list_len(frame.input.get("tool_calls")); + let calls = BatchInput(frame.input).tool_calls().array().len(); let title = if calls > 0 { format!("Batch {calls} tool{}", plural(calls)) } else { "Batch".to_owned() }; Some(block("#", title, frame.completed_output())) } fn run_lsp(frame: &Frame) -> Option { - let operation = frame.input.get("operation"); - let operation = if operation.is_some_and(truthy) { or_empty(operation) } else { "request".to_owned() }; - let file = frame.path(frame.input.get("path"))?; + let input = LspInput(frame.input); + let operation = if input.operation().truthy() { input.operation().js() } else { "request".to_owned() }; + let file = frame.path(frame.input.legacy_path())?; if file.is_empty() { return Some(inline("→", format!("LSP {operation}"))); } - let number = |key| frame.input.get(key).filter(|value| value.is_number()); - let position = match (number("line"), number("character")) { - (Some(line), Some(character)) => format!(":{}:{}", js_string(line), js_string(character)), + let number = |value: Option<&Value>| value.filter(|value| value.is_number()).map(js_string); + let position = match (number(input.line().value()), number(input.character().value())) { + (Some(line), Some(character)) => format!(":{line}:{character}"), _ => String::new(), }; Some(inline("→", format!("LSP {operation} {file}{position}"))) } fn run_shell(frame: &Frame) -> Option { - let command = frame.input.get("command"); - let title = if command.is_some_and(truthy) { or_empty(command) } else { String::new() }; + let command = ShellInput(frame.input).command(); + let title = if command.truthy() { command.js() } else { String::new() }; let body = (frame.status == "completed").then(|| frame.output.trim().to_owned()); Some(block("$", title, body)) } @@ -532,23 +454,6 @@ fn non_empty(text: String) -> Option { (!text.is_empty()).then_some(text) } -fn dict(value: Option<&Value>) -> Map { - value.and_then(Value::as_object).cloned().unwrap_or_default() -} - -fn text(value: Option<&Value>) -> &str { - value.and_then(Value::as_str).unwrap_or_default() -} - -fn list_len(value: Option<&Value>) -> usize { - value.and_then(Value::as_array).map_or(0, Vec::len) -} - -/// `${value ?? ""}` in a template literal. -fn or_empty(value: Option<&Value>) -> String { - value.filter(|value| !value.is_null()).map(js_string).unwrap_or_default() -} - /// `Locale.titlecase`: uppercases every ASCII word character that starts a word. pub fn titlecase(text: &str) -> String { let word = |char: char| char.is_ascii_alphanumeric() || char == '_'; diff --git a/packages/cli-rs/script/gen/api.ts b/packages/cli-rs/script/gen/api.ts index 54326cc0398..9606cf7b073 100644 --- a/packages/cli-rs/script/gen/api.ts +++ b/packages/cli-rs/script/gen/api.ts @@ -129,6 +129,7 @@ for (const ref of Object.keys(document.references)) { `impl crate::TaggedError for ${name} {\n const TAG: &'static str = ${JSON.stringify(tag.literal)};\n}`, ) } +types.items.push(types.tagModule()) const header = "// Generated by script/gen/api.ts from ClientApi. Do not edit.\n" await Bun.write( diff --git a/packages/cli-rs/script/rust/types.ts b/packages/cli-rs/script/rust/types.ts index 025861eb3da..6abbc77d56d 100644 --- a/packages/cli-rs/script/rust/types.ts +++ b/packages/cli-rs/script/rust/types.ts @@ -59,6 +59,11 @@ export class Types { ]) // The common-field accessors of every generated tagged enum, so an outer enum can delegate to an inner one. private readonly accessors = new Map>() + // Where each struct's item is, each tagged enum's member types and the literals of the tag types, so a union can + // retype its members' tags. + private readonly structItems = new Map() + private readonly members = new Map>() + private readonly tags = new Set() constructor(private readonly references: SchemaRepresentation.References) {} @@ -237,6 +242,7 @@ export class Types { const defaults = types.every((type) => this.isDefault(type) || type === "IndexMap") if (defaults) this.defaultable.add(name) this.structs.set(name, record) + this.structItems.set(name, this.items.length) this.items.push( `#[derive(Debug, Clone, PartialEq, Serialize, Deserialize${defaults ? ", Default" : ""})]\npub struct ${name} {\n${lines.join("\n")}\n}`, ) @@ -483,6 +489,12 @@ export class Types { if (member._tag === "Reference") return this.type(member, `${name}${variants[index]}`) return this.objects(resolved as Objects, this.name(`${name}${variants[index]}`), `${name}${variants[index]}`) }) + tag.values.forEach((value, index) => { + const literal = value.exact[0] + if (value.exact.length === 1 && value.prefixes.length === 0 && typeof literal === "string") + this.staticTag(types[index], tag.key, literal) + }) + this.members.set(name, types) const kind = typeof tag.values.find((value) => value.exact.length > 0)?.exact[0] const access = kind === "boolean" ? "as_bool" : "as_str" const arms = tag.values.flatMap((value, index) => [ @@ -524,11 +536,42 @@ export class Types { const tagMethod = methods.length === 0 ? "" : `\n\nimpl ${name} {\n${methods.join("\n\n")}\n}` const doc = ref === undefined ? "" : `/// \`${ref}\`, tagged by \`${tag.key}\`.\n` this.items.push( - `${doc}#[derive(Debug, Clone, PartialEq, Serialize)]\n#[serde(untagged)]\npub enum ${name} {\n${variants.map((variant, index) => ` ${variant}(${types[index]}),`).join("\n")}\n /// A member this client does not know, kept as it arrived.\n Unknown(serde_json::Value),\n}\n\nimpl<'de> Deserialize<'de> for ${name} {\n fn deserialize>(deserializer: D) -> Result {\n crate::de::union(deserializer, Self::from_raw)\n }\n}\n\nimpl ${name} {\n fn from_raw(raw: &crate::de::Raw) -> Result {\n match raw.field(${JSON.stringify(tag.key)}).${access}() {\n${ordered.join("\n")}\n _ => raw.unknown().map(Self::Unknown),\n }\n }\n}${tagMethod}`, + `${doc}#[derive(Debug, Clone, PartialEq, Serialize)]\n#[serde(untagged)]\npub enum ${name} {\n${variants.map((variant, index) => ` ${variant}(${types[index]}),`).join("\n")}\n /// A member this client does not know, kept as it arrived.\n Unknown(serde_json::Value),\n}\n\nimpl<'de> Deserialize<'de> for ${name} {\n fn deserialize>(deserializer: D) -> Result {\n crate::de::union(deserializer, Self::from_raw)\n }\n}\n\nimpl ${name} {\n pub fn from_raw(raw: &crate::de::Raw) -> Result {\n match raw.field(${JSON.stringify(tag.key)}).${access}() {\n${ordered.join("\n")}\n _ => raw.unknown().map(Self::Unknown),\n }\n }\n}${tagMethod}`, ) + if (name === "V2Event") this.items.push(eventKind(variants, tag.values)) return name } + /** + * Retypes the `key` field of a member struct, or of every struct of a nested union, from `String` to the zero-sized + * type of its one literal. The union has read the tag already, so the member keeps it without an allocation. + */ + private staticTag(type: string, key: string, literal: string) { + const nested = this.members.get(type) + if (nested !== undefined) return nested.forEach((member) => this.staticTag(member, key, literal)) + const field = this.structs.get(type)?.find((field) => field.key === key) + if (field === undefined || field.type !== "String") return + // Two literals with one name would define the type twice, which the Rust build rejects. + this.tags.add(literal) + field.type = `tag::${pascal(literal)}` + this.strings.add(field.type) + const at = this.structItems.get(type)! + this.items[at] = this.items[at].replace(` pub ${field.ident}: String,`, ` pub ${field.ident}: ${field.type},`) + } + + /** The tag types' module: each serializes as its literal and decodes from any string. */ + tagModule() { + const lines = [...this.tags] + .map((literal) => `${pascal(literal)} = ${JSON.stringify(literal)},`) + .sort() + .reduce>((lines, pair) => { + if (lines.length > 0 && lines[lines.length - 1].length + pair.length < 112) lines[lines.length - 1] += ` ${pair}` + else lines.push(pair) + return lines + }, []) + return `/// Union members' tags. Each serializes as its literal and decodes from any string, since the union has picked the member.\npub mod tag {\n tags! {\n${lines.map((line) => ` ${line}`).join("\n")}\n }\n}` + } + /** * A method for every field that at least two members share with one Rust type, and for every field one level * down that all members with its parent share (`time_created` for `time.created`). It returns the value itself when @@ -739,6 +782,50 @@ function literalType(literal: unknown) { return "serde_json::Value" } +/** `EventKind`: which member of `V2Event` an event is, as a `u8`, so that listeners are counted in an array. */ +function eventKind(variants: Array, values: Array<{ exact: Array; prefixes: Array }>) { + const arms = values.flatMap((value, index) => [ + ...(value.exact.length === 0 ? [] : [`${value.exact.map((item) => JSON.stringify(item)).join(" | ")}`]), + ...value.prefixes.map((prefix) => `tag if tag.starts_with(${JSON.stringify(prefix)})`), + ].map((pattern) => ` ${pattern} => Self::${variants[index]},`)) + const named = variants.filter((_, index) => values[index].prefixes.length > 0 || values[index].exact.length > 1) + return `/// Which member of [\`V2Event\`] an event is. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum EventKind { +${variants.map((variant) => ` ${variant},`).join("\n")} + Unknown, +} + +impl EventKind { + /// How many kinds there are, \`Unknown\` included. + pub const COUNT: usize = ${variants.length + 1}; + + /// The kind an event whose \`type\` is \`tag\` decodes to. + pub fn from_tag(tag: &str) -> Self { + match tag { +${[...arms.filter((arm) => !arm.includes("starts_with")), ...arms.filter((arm) => arm.includes("starts_with"))].join("\n")} + _ => Self::Unknown, + } + } + + /// Whether the events of this kind differ in their \`type\`, so that a listener names the ones it wants. + pub fn named(self) -> bool { + matches!(self, ${[...named, "Unknown"].map((variant) => `Self::${variant}`).join(" | ")}) + } +} + +impl V2Event { + /// Which member this is. + pub fn kind(&self) -> EventKind { + match self { +${variants.map((variant) => ` Self::${variant}(_) => EventKind::${variant},`).join("\n")} + Self::Unknown(_) => EventKind::Unknown, + } + } +}` +} + function newtype(name: string, ref: string) { return `string_type!(${name}, ${JSON.stringify("`" + ref + "`")});` }