diff --git a/bt-daemon/src/agents/request.rs b/bt-daemon/src/agents/request.rs deleted file mode 100644 index b525bb75..00000000 --- a/bt-daemon/src/agents/request.rs +++ /dev/null @@ -1,208 +0,0 @@ -//! The normalized request configuration retained by Pi, independent of the -//! provider-native payload. Unknown built-in tools remain provider-owned JSON; -//! function definitions and their arbitrary parameter schemas are distinguished. -use crate::json::{Extensions, Field}; -use serde::{Deserialize, Deserializer, Serialize}; -use serde_json::{value::RawValue, Value}; - -#[derive(Default, Serialize, Deserialize)] -pub(crate) struct RequestConfig { - #[serde(skip_serializing_if = "Option::is_none")] - temperature: Option, - #[serde(skip_serializing_if = "Option::is_none")] - top_p: Option, - #[serde(skip_serializing_if = "Option::is_none")] - max_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - frequency_penalty: Option, - #[serde(skip_serializing_if = "Option::is_none")] - presence_penalty: Option, - #[serde(skip_serializing_if = "Option::is_none")] - stop: Option, - #[serde(skip_serializing_if = "Option::is_none")] - response_format: Option, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - tools: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - tool_choice: Option, - #[serde(skip_serializing_if = "Option::is_none")] - parallel_tool_calls: Option, - #[serde(skip_serializing_if = "Option::is_none")] - max_tool_calls: Option, -} -impl RequestConfig { - pub fn is_empty(&self) -> bool { - self.temperature.is_none() - && self.top_p.is_none() - && self.max_tokens.is_none() - && self.frequency_penalty.is_none() - && self.presence_penalty.is_none() - && self.stop.is_none() - && self.response_format.is_none() - && self.tools.is_empty() - && self.tool_choice.is_none() - && self.parallel_tool_calls.is_none() - && self.max_tool_calls.is_none() - } -} -#[derive(Serialize, Deserialize)] -#[serde(untagged)] -enum Stop { - One(String), - Many(Vec), -} -#[derive(Serialize)] -#[serde(untagged)] -enum ToolDefinition { - Function(FunctionTool), - BuiltIn(Extensions), -} -#[derive(Serialize, Deserialize)] -struct FunctionTool { - #[serde(rename = "type")] - kind: FunctionType, - function: FunctionDefinition, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, -} -#[derive(Serialize, Deserialize)] -enum FunctionType { - #[serde(rename = "function")] - Function, -} -#[derive(Serialize, Deserialize)] -struct FunctionDefinition { - name: String, - #[serde(skip_serializing_if = "Option::is_none")] - description: Option, - /// Tool-authored JSON Schema, intentionally unrestricted. - #[serde(skip_serializing_if = "Option::is_none")] - parameters: Option, - #[serde(skip_serializing_if = "Option::is_none")] - strict: Option, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, -} -impl<'de> Deserialize<'de> for ToolDefinition { - fn deserialize>(d: D) -> Result { - let value = Value::deserialize(d)?; - if value.get("type").and_then(Value::as_str) == Some("function") { - serde_json::from_value(value) - .map(Self::Function) - .map_err(serde::de::Error::custom) - } else { - serde_json::from_value(value) - .map(Self::BuiltIn) - .map_err(serde::de::Error::custom) - } - } -} -#[derive(Serialize, Deserialize)] -#[serde(untagged)] -enum ToolChoice { - Mode(ChoiceMode), - Named(NamedChoice), -} -#[derive(Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -enum ChoiceMode { - Auto, - None, - Required, -} -#[derive(Serialize, Deserialize)] -struct NamedChoice { - #[serde(rename = "type")] - kind: FunctionType, - function: FunctionName, -} -#[derive(Serialize, Deserialize)] -struct FunctionName { - name: String, -} - -#[derive(Serialize)] -#[serde(untagged)] -enum ResponseFormat { - Known(KnownResponseFormat), - Other(Box), -} -#[derive(Serialize, Deserialize)] -#[serde(tag = "type", rename_all = "snake_case")] -enum KnownResponseFormat { - Text { - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, - }, - JsonObject { - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, - }, - JsonSchema { - json_schema: SchemaDefinition, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, - }, -} -#[derive(Serialize, Deserialize)] -struct SchemaDefinition { - name: String, - #[serde(default, skip_serializing_if = "Field::is_missing")] - description: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - strict: Field, - /// Provider/user-authored JSON Schema, intentionally unrestricted. - schema: Value, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, -} -impl<'de> Deserialize<'de> for ResponseFormat { - fn deserialize>(d: D) -> Result { - let value = Value::deserialize(d)?; - if matches!( - value.get("type").and_then(Value::as_str), - Some("text" | "json_object" | "json_schema") - ) { - serde_json::from_value(value) - .map(Self::Known) - .map_err(serde::de::Error::custom) - } else { - serde_json::value::to_raw_value(&value) - .map(Self::Other) - .map_err(serde::de::Error::custom) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - #[test] - fn request_variants_preserve_schemas_and_provider_builtins() { - let raw = json!({"max_tokens":100,"stop":["END"],"tool_choice":{"type":"function","function":{"name":"read"}}, - "tools":[{"type":"function","function":{"name":"read","parameters":{"type":"object","future":true}}},{"type":"web_search","future":true}], - "response_format":{"type":"json_schema","json_schema":{"name":"answer","schema":{"type":"object","future":true}}}}); - let config: RequestConfig = serde_json::from_value(raw.clone()).unwrap(); - assert!(matches!(&config.tools[0], ToolDefinition::Function(_))); - assert!(matches!(&config.tools[1], ToolDefinition::BuiltIn(_))); - assert_eq!(serde_json::to_value(config).unwrap(), raw); - for format in [ - json!({"type":"text","future":null}), - json!({"type":"json_object","future":true}), - json!({"type":"json_schema","json_schema":{"name":"answer","description":null,"strict":null,"schema":{"type":"object"}},"future":true}), - json!({"type":"future","settings":[null,42]}), - ] { - let raw = json!({"response_format":format}); - let parsed: RequestConfig = serde_json::from_value(raw.clone()).unwrap(); - assert_eq!(serde_json::to_value(parsed).unwrap(), raw); - } - for raw in [ - json!({"tools":[{"type":"function","function":{"name":42}}]}), - json!({"max_tokens":"100"}), - json!({"response_format":{"type":"json_schema","json_schema":{"name":42,"schema":{}}}}), - ] { - assert!(serde_json::from_value::(raw).is_err()); - } - } -} diff --git a/bt-daemon/src/agents/request/function_definition.rs b/bt-daemon/src/agents/request/function_definition.rs new file mode 100644 index 00000000..c254022e --- /dev/null +++ b/bt-daemon/src/agents/request/function_definition.rs @@ -0,0 +1,17 @@ +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Serialize, Deserialize)] +pub(super) struct FunctionDefinition { + name: String, + #[serde(skip_serializing_if = "Option::is_none")] + description: Option, + /// Tool-authored JSON Schema, intentionally unrestricted. + #[serde(skip_serializing_if = "Option::is_none")] + parameters: Option, + #[serde(skip_serializing_if = "Option::is_none")] + strict: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, +} diff --git a/bt-daemon/src/agents/request/function_tool.rs b/bt-daemon/src/agents/request/function_tool.rs new file mode 100644 index 00000000..24dddcc7 --- /dev/null +++ b/bt-daemon/src/agents/request/function_tool.rs @@ -0,0 +1,18 @@ +use super::FunctionDefinition; +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub(super) struct FunctionTool { + #[serde(rename = "type")] + kind: FunctionType, + function: FunctionDefinition, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, +} + +#[derive(Serialize, Deserialize)] +pub(super) enum FunctionType { + #[serde(rename = "function")] + Function, +} diff --git a/bt-daemon/src/agents/request/mod.rs b/bt-daemon/src/agents/request/mod.rs new file mode 100644 index 00000000..050b702b --- /dev/null +++ b/bt-daemon/src/agents/request/mod.rs @@ -0,0 +1,22 @@ +//! The normalized request configuration retained by Pi, independent of the +//! provider-native payload. Unknown built-in tools remain provider-owned JSON; +//! function definitions and their arbitrary parameter schemas are distinguished. + +mod function_definition; +mod function_tool; +mod request_config; +mod response_format; +mod schema_definition; +mod stop; +mod tool_choice; +mod tool_definition; + +use function_definition::FunctionDefinition; +use function_tool::FunctionTool; +use function_tool::FunctionType; +pub(crate) use request_config::RequestConfig; +use response_format::ResponseFormat; +use schema_definition::SchemaDefinition; +use stop::Stop; +use tool_choice::ToolChoice; +use tool_definition::ToolDefinition; diff --git a/bt-daemon/src/agents/request/request_config.rs b/bt-daemon/src/agents/request/request_config.rs new file mode 100644 index 00000000..20251475 --- /dev/null +++ b/bt-daemon/src/agents/request/request_config.rs @@ -0,0 +1,77 @@ +use super::{ResponseFormat, Stop, ToolChoice, ToolDefinition}; +use serde::{Deserialize, Serialize}; + +#[derive(Default, Serialize, Deserialize)] +pub(crate) struct RequestConfig { + #[serde(skip_serializing_if = "Option::is_none")] + temperature: Option, + #[serde(skip_serializing_if = "Option::is_none")] + top_p: Option, + #[serde(skip_serializing_if = "Option::is_none")] + max_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + frequency_penalty: Option, + #[serde(skip_serializing_if = "Option::is_none")] + presence_penalty: Option, + #[serde(skip_serializing_if = "Option::is_none")] + stop: Option, + #[serde(skip_serializing_if = "Option::is_none")] + response_format: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + tools: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + tool_choice: Option, + #[serde(skip_serializing_if = "Option::is_none")] + parallel_tool_calls: Option, + #[serde(skip_serializing_if = "Option::is_none")] + max_tool_calls: Option, +} + +impl RequestConfig { + pub fn is_empty(&self) -> bool { + self.temperature.is_none() + && self.top_p.is_none() + && self.max_tokens.is_none() + && self.frequency_penalty.is_none() + && self.presence_penalty.is_none() + && self.stop.is_none() + && self.response_format.is_none() + && self.tools.is_empty() + && self.tool_choice.is_none() + && self.parallel_tool_calls.is_none() + && self.max_tool_calls.is_none() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + #[test] + fn request_variants_preserve_schemas_and_provider_builtins() { + let raw = json!({"max_tokens":100,"stop":["END"],"tool_choice":{"type":"function","function":{"name":"read"}}, + "tools":[{"type":"function","function":{"name":"read","parameters":{"type":"object","future":true}}},{"type":"web_search","future":true}], + "response_format":{"type":"json_schema","json_schema":{"name":"answer","schema":{"type":"object","future":true}}}}); + let config: RequestConfig = serde_json::from_value(raw.clone()).unwrap(); + assert!(matches!(&config.tools[0], ToolDefinition::Function(_))); + assert!(matches!(&config.tools[1], ToolDefinition::BuiltIn(_))); + assert_eq!(serde_json::to_value(config).unwrap(), raw); + for format in [ + json!({"type":"text","future":null}), + json!({"type":"json_object","future":true}), + json!({"type":"json_schema","json_schema":{"name":"answer","description":null,"strict":null,"schema":{"type":"object"}},"future":true}), + json!({"type":"future","settings":[null,42]}), + ] { + let raw = json!({"response_format":format}); + let parsed: RequestConfig = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), raw); + } + for raw in [ + json!({"tools":[{"type":"function","function":{"name":42}}]}), + json!({"max_tokens":"100"}), + json!({"response_format":{"type":"json_schema","json_schema":{"name":42,"schema":{}}}}), + ] { + assert!(serde_json::from_value::(raw).is_err()); + } + } +} diff --git a/bt-daemon/src/agents/request/response_format.rs b/bt-daemon/src/agents/request/response_format.rs new file mode 100644 index 00000000..3ce98ce2 --- /dev/null +++ b/bt-daemon/src/agents/request/response_format.rs @@ -0,0 +1,48 @@ +use super::SchemaDefinition; +use crate::json::Extensions; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::value::RawValue; +use serde_json::Value; + +#[derive(Serialize)] +#[serde(untagged)] +pub(super) enum ResponseFormat { + Known(KnownResponseFormat), + Other(Box), +} + +#[derive(Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(super) enum KnownResponseFormat { + Text { + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, + JsonObject { + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, + JsonSchema { + json_schema: SchemaDefinition, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, +} + +impl<'de> Deserialize<'de> for ResponseFormat { + fn deserialize>(d: D) -> Result { + let value = Value::deserialize(d)?; + if matches!( + value.get("type").and_then(Value::as_str), + Some("text" | "json_object" | "json_schema") + ) { + serde_json::from_value(value) + .map(Self::Known) + .map_err(serde::de::Error::custom) + } else { + serde_json::value::to_raw_value(&value) + .map(Self::Other) + .map_err(serde::de::Error::custom) + } + } +} diff --git a/bt-daemon/src/agents/request/schema_definition.rs b/bt-daemon/src/agents/request/schema_definition.rs new file mode 100644 index 00000000..8466c892 --- /dev/null +++ b/bt-daemon/src/agents/request/schema_definition.rs @@ -0,0 +1,16 @@ +use crate::json::{Extensions, Field}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Serialize, Deserialize)] +pub(super) struct SchemaDefinition { + name: String, + #[serde(default, skip_serializing_if = "Field::is_missing")] + description: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + strict: Field, + /// Provider/user-authored JSON Schema, intentionally unrestricted. + schema: Value, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, +} diff --git a/bt-daemon/src/agents/request/stop.rs b/bt-daemon/src/agents/request/stop.rs new file mode 100644 index 00000000..4b1716a2 --- /dev/null +++ b/bt-daemon/src/agents/request/stop.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +pub(super) enum Stop { + One(String), + Many(Vec), +} diff --git a/bt-daemon/src/agents/request/tool_choice.rs b/bt-daemon/src/agents/request/tool_choice.rs new file mode 100644 index 00000000..02adbed3 --- /dev/null +++ b/bt-daemon/src/agents/request/tool_choice.rs @@ -0,0 +1,29 @@ +use super::FunctionType; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +pub(super) enum ToolChoice { + Mode(ChoiceMode), + Named(NamedChoice), +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(super) enum ChoiceMode { + Auto, + None, + Required, +} + +#[derive(Serialize, Deserialize)] +pub(super) struct NamedChoice { + #[serde(rename = "type")] + kind: FunctionType, + function: FunctionName, +} + +#[derive(Serialize, Deserialize)] +struct FunctionName { + name: String, +} diff --git a/bt-daemon/src/agents/request/tool_definition.rs b/bt-daemon/src/agents/request/tool_definition.rs new file mode 100644 index 00000000..7580c2c1 --- /dev/null +++ b/bt-daemon/src/agents/request/tool_definition.rs @@ -0,0 +1,26 @@ +use super::FunctionTool; +use crate::json::Extensions; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +#[derive(Serialize)] +#[serde(untagged)] +pub(super) enum ToolDefinition { + Function(FunctionTool), + BuiltIn(Extensions), +} + +impl<'de> Deserialize<'de> for ToolDefinition { + fn deserialize>(d: D) -> Result { + let value = Value::deserialize(d)?; + if value.get("type").and_then(Value::as_str) == Some("function") { + serde_json::from_value(value) + .map(Self::Function) + .map_err(serde::de::Error::custom) + } else { + serde_json::from_value(value) + .map(Self::BuiltIn) + .map_err(serde::de::Error::custom) + } + } +} diff --git a/bt-daemon/src/codex_hooks/config.rs b/bt-daemon/src/codex_hooks/config.rs new file mode 100644 index 00000000..c3d5b48f --- /dev/null +++ b/bt-daemon/src/codex_hooks/config.rs @@ -0,0 +1,15 @@ +use serde::Deserialize; +use std::collections::BTreeMap; + +#[derive(Deserialize)] +pub(super) struct Config { + #[serde(default)] + pub(super) features: BTreeMap, +} + +impl Config { + pub(super) fn hooks_enabled(&self) -> bool { + self.features.get("hooks") != Some(&false) + && self.features.get("codex_hooks") != Some(&false) + } +} diff --git a/bt-daemon/src/codex_hooks/config_read.rs b/bt-daemon/src/codex_hooks/config_read.rs new file mode 100644 index 00000000..18ea12f9 --- /dev/null +++ b/bt-daemon/src/codex_hooks/config_read.rs @@ -0,0 +1,7 @@ +use super::config::Config; +use serde::Deserialize; + +#[derive(Deserialize)] +pub(super) struct ConfigRead { + pub(super) config: Config, +} diff --git a/bt-daemon/src/codex_hooks/hook.rs b/bt-daemon/src/codex_hooks/hook.rs new file mode 100644 index 00000000..6d66151d --- /dev/null +++ b/bt-daemon/src/codex_hooks/hook.rs @@ -0,0 +1,27 @@ +use serde::Deserialize; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct Hook { + pub(super) plugin_id: Option, + pub(super) event_name: Option, + pub(super) handler_type: Option, + pub(super) command: Option, + pub(super) enabled: Option, + pub(super) is_managed: Option, + pub(super) source: Option, + pub(super) source_path: Option, + pub(super) trust_status: Option, + pub(super) key: Option, + pub(super) current_hash: Option, +} +impl Hook { + /// Both installed and invocation-local trust require an enabled, unmanaged + /// command matching the exact definition the caller intended to approve. + pub(super) fn is_enabled_command(&self, command: &str) -> bool { + self.handler_type.as_deref() == Some("command") + && self.command.as_deref() == Some(command) + && self.enabled == Some(true) + && self.is_managed == Some(false) + } +} diff --git a/bt-daemon/src/codex_hooks/hook_entry.rs b/bt-daemon/src/codex_hooks/hook_entry.rs new file mode 100644 index 00000000..eb29fd76 --- /dev/null +++ b/bt-daemon/src/codex_hooks/hook_entry.rs @@ -0,0 +1,9 @@ +use super::hook::Hook; +use serde::Deserialize; +use serde_json::Value; + +#[derive(Debug, Deserialize)] +pub(super) struct HookEntry { + pub(super) errors: Option>, + pub(super) hooks: Vec, +} diff --git a/bt-daemon/src/codex_hooks/hooks_list.rs b/bt-daemon/src/codex_hooks/hooks_list.rs new file mode 100644 index 00000000..3cc45d07 --- /dev/null +++ b/bt-daemon/src/codex_hooks/hooks_list.rs @@ -0,0 +1,139 @@ +use super::hook_entry::HookEntry; +use super::PACKAGED_HOOKS; +use crate::agents::schema::{HookFile, HookGroup}; +use anyhow::Context; +use serde::Deserialize; + +#[derive(Debug, Deserialize)] +pub(super) struct HooksList { + pub(super) data: Vec, +} + +impl HooksList { + pub(super) fn managed_run_trust_state( + &self, + expected_command: &str, + ) -> anyhow::Result { + let expected: HookFile = serde_json::from_str(PACKAGED_HOOKS)?; + let expected_events: std::collections::HashSet = expected + .hooks + .keys() + .map(|event| format!("{}{}", event[..1].to_ascii_lowercase(), &event[1..])) + .collect(); + let entries = &self.data; + let mut seen = std::collections::HashSet::new(); + let mut trust = std::collections::BTreeMap::new(); + for entry in entries { + anyhow::ensure!( + entry.errors.as_ref().is_some_and(Vec::is_empty), + "Codex reported hook errors during managed-run setup" + ); + for hook in &entry.hooks { + if hook.source.as_deref() != Some("sessionFlags") { + continue; + } + let Some(event) = hook.event_name.as_deref() else { + continue; + }; + if !expected_events.contains(event) { + continue; + } + anyhow::ensure!( + seen.insert(event.to_owned()) && hook.is_enabled_command(expected_command), + "Codex changed a Braintrust hook while preparing this run" + ); + anyhow::ensure!( + matches!( + hook.trust_status.as_deref(), + Some("trusted" | "untrusted" | "modified") + ), + "Codex reported an unsupported trust state for a managed Braintrust hook" + ); + let key = hook + .key + .as_deref() + .filter(|value| !value.is_empty()) + .context("Codex omitted a managed Braintrust hook key")?; + let hash = hook + .current_hash + .as_deref() + .filter(|value| !value.is_empty()) + .context("Codex omitted a managed Braintrust hook hash")?; + anyhow::ensure!( + trust.insert(key.to_owned(), hash.to_owned()).is_none(), + "duplicate managed Braintrust hook key" + ); + } + } + anyhow::ensure!( + seen == expected_events, + "Codex did not load the complete Braintrust hook set for this run" + ); + let fields = trust + .iter() + .map(|(key, hash)| { + Ok(format!( + "{}={{trusted_hash={}}}", + serde_json::to_string(key)?, + serde_json::to_string(hash)? + )) + }) + .collect::>>()? + .join(","); + Ok(std::ffi::OsString::from(format!( + "hooks.state={{{fields}}}" + ))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{json, Value}; + + fn captured_hooks() -> Value { + json!({"data":[{"errors":[],"hooks":super::super::PLUGIN_EVENTS.iter().map(|event|json!({ + "eventName":event,"source":"sessionFlags","handlerType":"command", + "command":"expected", "enabled":true,"isManaged":false, + "trustStatus":"untrusted", "key":format!("key-{event}"),"currentHash":format!("hash-{event}") + })).collect::>()}]}) + } + + #[test] + fn managed_trust_requires_the_complete_unchanged_hook_set() { + let raw = captured_hooks(); + let observed: HooksList = serde_json::from_value(raw.clone()).unwrap(); + let state = observed.managed_run_trust_state("expected").unwrap(); + let state = state.to_str().unwrap(); + for event in super::super::PLUGIN_EVENTS { + assert!(state.contains(&format!("hash-{event}"))); + } + for (field, value) in [ + ("command", json!("changed")), + ("enabled", json!(false)), + ("isManaged", json!(true)), + ("trustStatus", json!("future")), + ("currentHash", json!("")), + ] { + let mut changed = raw.clone(); + changed["data"][0]["hooks"][0][field] = value; + let observed: HooksList = serde_json::from_value(changed).unwrap(); + assert!( + observed.managed_run_trust_state("expected").is_err(), + "{field}" + ); + } + let mut missing = raw.clone(); + missing["data"][0]["hooks"].as_array_mut().unwrap().pop(); + let observed: HooksList = serde_json::from_value(missing).unwrap(); + assert!(observed.managed_run_trust_state("expected").is_err()); + let mut duplicated = raw; + let entry = duplicated["data"][0]["hooks"][0].clone(); + duplicated["data"][0]["hooks"] + .as_array_mut() + .unwrap() + .push(entry); + let observed: HooksList = serde_json::from_value(duplicated).unwrap(); + assert!(observed.managed_run_trust_state("expected").is_err()); + } +} diff --git a/bt-daemon/src/codex_hooks.rs b/bt-daemon/src/codex_hooks/mod.rs similarity index 51% rename from bt-daemon/src/codex_hooks.rs rename to bt-daemon/src/codex_hooks/mod.rs index 5c9a41b0..432d2fb5 100644 --- a/bt-daemon/src/codex_hooks.rs +++ b/bt-daemon/src/codex_hooks/mod.rs @@ -1,17 +1,13 @@ //! Inspect and activate Braintrust hooks through Codex's app-server protocol. //! Trust writes use the same exact-definition config API as Codex's /hooks UI. -use crate::agents::schema::{HookFile, HookGroup}; use anyhow::{anyhow, Context}; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::BTreeMap; use std::path::Path; use std::process::Stdio; use std::time::Duration; -use tokio::io::{ - AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, -}; +use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader}; const PLUGIN: &str = "trace-codex@braintrust-codex-plugins"; const PACKAGED_HOOKS: &str = include_str!(concat!( @@ -33,58 +29,23 @@ const PLUGIN_EVENTS: &[&str] = &[ "interrupt", "sessionEnd", ]; -// The app-server transport is JSON; consumers only receive typed results. -#[derive(Deserialize)] -struct ConfigRead { - config: Config, -} -#[derive(Deserialize)] -struct Config { - #[serde(default)] - features: BTreeMap, -} -#[derive(Deserialize)] -struct PluginList { - marketplaces: Vec, -} -#[derive(Deserialize)] -struct PluginMarketplace { - plugins: Vec, -} -#[derive(Deserialize)] -struct Plugin { - id: String, - installed: bool, - enabled: bool, -} -#[derive(Debug, Deserialize)] -struct HooksList { - data: Vec, -} -#[derive(Debug, Deserialize)] -struct HookEntry { - errors: Option>, - hooks: Vec, -} -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -struct Hook { - plugin_id: Option, - event_name: Option, - handler_type: Option, - command: Option, - enabled: Option, - is_managed: Option, - source: Option, - source_path: Option, - trust_status: Option, - key: Option, - current_hash: Option, -} -#[derive(Serialize)] -struct TrustState<'a> { - trusted_hash: &'a str, -} +mod config; +mod config_read; +mod hook; +mod hook_entry; +mod hooks_list; +mod plugin; +mod plugin_list; +mod plugin_marketplace; +mod response; +mod transport; +mod trust_state; + +use config_read::ConfigRead; +use hooks_list::HooksList; +use plugin_list::PluginList; +use transport::request; +use trust_state::TrustState; pub(crate) async fn activate() -> anyhow::Result<()> { let cwd = std::env::current_dir()?; @@ -118,10 +79,8 @@ pub(crate) async fn activate() -> anyhow::Result<()> { json!({"includeLayers":false}), ) .await?; - let features = &config.config.features; anyhow::ensure!( - features.get("hooks") != Some(&false) - && features.get("codex_hooks") != Some(&false), + config.config.hooks_enabled(), "Codex hooks are disabled in config; enable hooks and retry setup" ); let plugins: PluginList = request( @@ -134,13 +93,8 @@ pub(crate) async fn activate() -> anyhow::Result<()> { }), ) .await?; - let installed = plugins - .marketplaces - .iter() - .flat_map(|marketplace| &marketplace.plugins) - .any(|plugin| plugin.id == PLUGIN && plugin.installed && plugin.enabled); anyhow::ensure!( - installed, + plugins.has_active_plugin(PLUGIN), "Codex tracing plugin is not installed and enabled; rerun `bt trace install codex`" ); let hooks: HooksList = request( @@ -227,7 +181,7 @@ pub(crate) async fn run_trust_override( json!({"cwds":[cwd]}), ) .await?; - managed_run_trust_state(&hooks, expected_command) + hooks.managed_run_trust_state(expected_command) }) .await; let _ = child.kill().await; @@ -239,85 +193,6 @@ pub(crate) async fn run_trust_override( } } -fn managed_run_trust_state( - hooks: &HooksList, - expected_command: &str, -) -> anyhow::Result { - let expected: HookFile = serde_json::from_str(PACKAGED_HOOKS)?; - let expected_events: std::collections::HashSet = expected - .hooks - .keys() - .map(|event| format!("{}{}", event[..1].to_ascii_lowercase(), &event[1..])) - .collect(); - let entries = &hooks.data; - let mut seen = std::collections::HashSet::new(); - let mut trust = std::collections::BTreeMap::new(); - for entry in entries { - anyhow::ensure!( - entry.errors.as_ref().is_some_and(Vec::is_empty), - "Codex reported hook errors during managed-run setup" - ); - for hook in &entry.hooks { - if hook.source.as_deref() != Some("sessionFlags") { - continue; - } - let Some(event) = hook.event_name.as_deref() else { - continue; - }; - if !expected_events.contains(event) { - continue; - } - anyhow::ensure!( - seen.insert(event.to_owned()) - && hook.handler_type.as_deref() == Some("command") - && hook.command.as_deref() == Some(expected_command) - && hook.enabled == Some(true) - && hook.is_managed == Some(false), - "Codex changed a Braintrust hook while preparing this run" - ); - anyhow::ensure!( - matches!( - hook.trust_status.as_deref(), - Some("trusted" | "untrusted" | "modified") - ), - "Codex reported an unsupported trust state for a managed Braintrust hook" - ); - let key = hook - .key - .as_deref() - .filter(|value| !value.is_empty()) - .context("Codex omitted a managed Braintrust hook key")?; - let hash = hook - .current_hash - .as_deref() - .filter(|value| !value.is_empty()) - .context("Codex omitted a managed Braintrust hook hash")?; - anyhow::ensure!( - trust.insert(key.to_owned(), hash.to_owned()).is_none(), - "duplicate managed Braintrust hook key" - ); - } - } - anyhow::ensure!( - seen == expected_events, - "Codex did not load the complete Braintrust hook set for this run" - ); - let fields = trust - .iter() - .map(|(key, hash)| { - Ok(format!( - "{}={{trusted_hash={}}}", - serde_json::to_string(key)?, - serde_json::to_string(hash)? - )) - }) - .collect::>>()? - .join(","); - Ok(std::ffi::OsString::from(format!( - "hooks.state={{{fields}}}" - ))) -} - /// Validate the complete installed file, including the other platform's command, /// before approving exact hashes returned by Codex. Never infer hashes or keys. fn trust_edits(hooks: &HooksList) -> anyhow::Result>> { @@ -336,10 +211,7 @@ fn trust_edits(hooks: &HooksList) -> anyhow::Result anyhow::Result( - stdin: &mut (impl AsyncWrite + Unpin), - stdout: &mut (impl AsyncBufRead + Unpin), - id: u64, - method: &str, - params: Value, -) -> anyhow::Result { - let mut encoded = serde_json::to_vec(&json!({"id":id,"method":method,"params":params}))?; - encoded.push(b'\n'); - stdin.write_all(&encoded).await?; - stdin.flush().await?; - loop { - let mut line = String::new(); - anyhow::ensure!( - stdout.read_line(&mut line).await? != 0, - "Codex closed the probe stream" - ); - #[derive(Deserialize)] - struct Response { - id: Option, - error: Option, - #[serde( - default, - deserialize_with = "crate::agents::schema::deserialize_present" - )] - result: Option>, - } - #[derive(Deserialize)] - struct RpcError { - message: Option, - } - let response: Response = serde_json::from_str(&line).context("invalid Codex response")?; - if response.id != Some(json!(id)) { - continue; - } - if let Some(error) = response.error { - return Err(anyhow!( - "{method}: {}", - error.message.as_deref().unwrap_or("request failed") - )); - } - let result = response.result.context("Codex response has no result")?; - return serde_json::from_str(result.get()).context("invalid Codex result"); - } -} - #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn required_events_match_the_packaged_plugin() { - let hooks: Value = serde_json::from_str(PACKAGED_HOOKS).unwrap(); - let events: std::collections::BTreeSet<_> = hooks["hooks"] - .as_object() - .unwrap() - .keys() - .map(|key| format!("{}{}", key[..1].to_ascii_lowercase(), &key[1..])) - .collect(); - assert_eq!( - events, - PLUGIN_EVENTS - .iter() - .map(|event| (*event).to_owned()) - .collect() - ); - } - - #[tokio::test] - async fn rpc_distinguishes_null_results_from_missing_results() { - let mut input = Vec::new(); - let mut output = std::io::Cursor::new(b"{\"id\":1,\"result\":null}\n"); - assert_eq!( - request::(&mut input, &mut output, 1, "initialize", json!({})) - .await - .unwrap(), - Value::Null - ); - let mut output = std::io::Cursor::new(b"{\"id\":1}\n"); - assert!( - request::(&mut input, &mut output, 1, "initialize", json!({})) - .await - .unwrap_err() - .to_string() - .contains("no result") - ); - } - - #[tokio::test] - async fn rpc_ignores_notifications_and_reports_unsupported_methods() { - let mut input = Vec::new(); - let mut output = std::io::Cursor::new( - b"{\"method\":\"notice\"}\n{\"id\":3,\"error\":{\"message\":\"Method not found\"}}\n", - ); - let error = request::(&mut input, &mut output, 3, "hooks/list", json!({})) - .await - .unwrap_err(); - assert!(error.to_string().contains("Method not found")); - assert_eq!( - serde_json::from_slice::(&input).unwrap()["method"], - "hooks/list" - ); - } -} +mod tests; diff --git a/bt-daemon/src/codex_hooks/plugin.rs b/bt-daemon/src/codex_hooks/plugin.rs new file mode 100644 index 00000000..e0316eb4 --- /dev/null +++ b/bt-daemon/src/codex_hooks/plugin.rs @@ -0,0 +1,13 @@ +use serde::Deserialize; + +#[derive(Deserialize)] +pub(super) struct Plugin { + pub(super) id: String, + pub(super) installed: bool, + pub(super) enabled: bool, +} +impl Plugin { + pub(super) fn is_active(&self, id: &str) -> bool { + self.id == id && self.installed && self.enabled + } +} diff --git a/bt-daemon/src/codex_hooks/plugin_list.rs b/bt-daemon/src/codex_hooks/plugin_list.rs new file mode 100644 index 00000000..bfcfbc5c --- /dev/null +++ b/bt-daemon/src/codex_hooks/plugin_list.rs @@ -0,0 +1,15 @@ +use super::plugin_marketplace::PluginMarketplace; +use serde::Deserialize; + +#[derive(Deserialize)] +pub(super) struct PluginList { + pub(super) marketplaces: Vec, +} +impl PluginList { + pub(super) fn has_active_plugin(&self, id: &str) -> bool { + self.marketplaces + .iter() + .flat_map(|marketplace| &marketplace.plugins) + .any(|plugin| plugin.is_active(id)) + } +} diff --git a/bt-daemon/src/codex_hooks/plugin_marketplace.rs b/bt-daemon/src/codex_hooks/plugin_marketplace.rs new file mode 100644 index 00000000..0fa296ce --- /dev/null +++ b/bt-daemon/src/codex_hooks/plugin_marketplace.rs @@ -0,0 +1,7 @@ +use super::plugin::Plugin; +use serde::Deserialize; + +#[derive(Deserialize)] +pub(super) struct PluginMarketplace { + pub(super) plugins: Vec, +} diff --git a/bt-daemon/src/codex_hooks/response.rs b/bt-daemon/src/codex_hooks/response.rs new file mode 100644 index 00000000..76681f85 --- /dev/null +++ b/bt-daemon/src/codex_hooks/response.rs @@ -0,0 +1,35 @@ +use anyhow::{anyhow, Context}; +use serde::{de::DeserializeOwned, Deserialize}; +use serde_json::{json, Value}; + +#[derive(Deserialize)] +pub(super) struct Response { + id: Option, + error: Option, + #[serde( + default, + deserialize_with = "crate::agents::schema::deserialize_present" + )] + result: Option>, +} +#[derive(Deserialize)] +struct RpcError { + message: Option, +} + +impl Response { + pub(super) fn matches_request(&self, id: u64) -> bool { + self.id == Some(json!(id)) + } + + pub(super) fn into_result(self, method: &str) -> anyhow::Result { + if let Some(error) = self.error { + return Err(anyhow!( + "{method}: {}", + error.message.as_deref().unwrap_or("request failed") + )); + } + let result = self.result.context("Codex response has no result")?; + serde_json::from_str(result.get()).context("invalid Codex result") + } +} diff --git a/bt-daemon/src/codex_hooks/tests.rs b/bt-daemon/src/codex_hooks/tests.rs new file mode 100644 index 00000000..0ecc412b --- /dev/null +++ b/bt-daemon/src/codex_hooks/tests.rs @@ -0,0 +1,55 @@ +use super::*; + +#[test] +fn required_events_match_the_packaged_plugin() { + let hooks: Value = serde_json::from_str(PACKAGED_HOOKS).unwrap(); + let events: std::collections::BTreeSet<_> = hooks["hooks"] + .as_object() + .unwrap() + .keys() + .map(|key| format!("{}{}", key[..1].to_ascii_lowercase(), &key[1..])) + .collect(); + assert_eq!( + events, + PLUGIN_EVENTS + .iter() + .map(|event| (*event).to_owned()) + .collect() + ); +} + +#[tokio::test] +async fn rpc_distinguishes_null_results_from_missing_results() { + let mut input = Vec::new(); + let mut output = std::io::Cursor::new(b"{\"id\":1,\"result\":null}\n"); + assert_eq!( + request::(&mut input, &mut output, 1, "initialize", json!({})) + .await + .unwrap(), + Value::Null + ); + let mut output = std::io::Cursor::new(b"{\"id\":1}\n"); + assert!( + request::(&mut input, &mut output, 1, "initialize", json!({})) + .await + .unwrap_err() + .to_string() + .contains("no result") + ); +} + +#[tokio::test] +async fn rpc_ignores_notifications_and_reports_unsupported_methods() { + let mut input = Vec::new(); + let mut output = std::io::Cursor::new( + b"{\"method\":\"notice\"}\n{\"id\":3,\"error\":{\"message\":\"Method not found\"}}\n", + ); + let error = request::(&mut input, &mut output, 3, "hooks/list", json!({})) + .await + .unwrap_err(); + assert!(error.to_string().contains("Method not found")); + assert_eq!( + serde_json::from_slice::(&input).unwrap()["method"], + "hooks/list" + ); +} diff --git a/bt-daemon/src/codex_hooks/transport.rs b/bt-daemon/src/codex_hooks/transport.rs new file mode 100644 index 00000000..af9887f3 --- /dev/null +++ b/bt-daemon/src/codex_hooks/transport.rs @@ -0,0 +1,30 @@ +use super::response::Response; +use anyhow::Context; +use serde::de::DeserializeOwned; +use serde_json::{json, Value}; +use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt}; + +pub(super) async fn request( + stdin: &mut (impl AsyncWrite + Unpin), + stdout: &mut (impl AsyncBufRead + Unpin), + id: u64, + method: &str, + params: Value, +) -> anyhow::Result { + let mut encoded = serde_json::to_vec(&json!({"id":id,"method":method,"params":params}))?; + encoded.push(b'\n'); + stdin.write_all(&encoded).await?; + stdin.flush().await?; + loop { + let mut line = String::new(); + anyhow::ensure!( + stdout.read_line(&mut line).await? != 0, + "Codex closed the probe stream" + ); + let response: Response = serde_json::from_str(&line).context("invalid Codex response")?; + if !response.matches_request(id) { + continue; + } + return response.into_result(method); + } +} diff --git a/bt-daemon/src/codex_hooks/trust_state.rs b/bt-daemon/src/codex_hooks/trust_state.rs new file mode 100644 index 00000000..ea1065d1 --- /dev/null +++ b/bt-daemon/src/codex_hooks/trust_state.rs @@ -0,0 +1,6 @@ +use serde::Serialize; + +#[derive(Serialize)] +pub(super) struct TrustState<'a> { + pub(super) trusted_hash: &'a str, +} diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index 355280ec..6a4e0224 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -5,789 +5,28 @@ //! consistently and JSON mode never falls back to human prose. mod auth_diagnostic; -pub use auth_diagnostic::AuthDiagnostic; - -use crate::wire::{SessionRoute, StatusResult, TraceDestination}; -use serde::Serialize; -use std::path::PathBuf; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum OutputFormat { - Human, - Json, -} - -impl From for OutputFormat { - fn from(json: bool) -> Self { - if json { - Self::Json - } else { - Self::Human - } - } -} - -#[derive(Debug, Clone, Serialize)] -pub struct StatusCommandOutput { - pub running: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub daemon_version: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub uptime_ms: Option, - pub sessions: Vec, -} - -impl From> for StatusCommandOutput { - fn from(status: Option) -> Self { - match status { - Some(status) => Self { - running: true, - daemon_version: Some(status.daemon_version), - uptime_ms: Some(status.uptime_ms), - sessions: status.sessions, - }, - None => Self { - running: false, - daemon_version: None, - uptime_ms: None, - sessions: Vec::new(), - }, - } - } -} - -#[derive(Debug, Clone, Serialize)] -pub struct InstallCommandOutput { - pub source: String, - pub display_name: String, - pub settings_path: PathBuf, - pub restart_required: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub configuration: Option<&'static str>, - pub scope: &'static str, - #[serde(skip_serializing_if = "is_false")] - pub applies_to_all_agents: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub enabled: Option, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub warnings: Vec, -} - -/// Backwards-compatible name for the shared install and enable output. -pub type SetupCommandOutput = InstallCommandOutput; - -fn is_false(value: &bool) -> bool { - !value -} - -#[derive(Debug, Clone, Serialize)] -pub struct UpdateCommandOutput { - pub source: String, - pub display_name: String, - pub restart_required: bool, -} - -#[derive(Debug, Clone, Serialize)] -pub struct StopCommandOutput { - pub running: bool, - pub stopped: bool, -} - -#[derive(Debug, Clone, Serialize)] -pub struct ImportSummary { - pub session_id: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub destination: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub root_span_id: Option, - pub span_count: usize, - pub finalized: bool, -} - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] -#[serde(rename_all = "snake_case")] -pub enum DaemonStatus { - Running, - #[default] - NotRunning, - Unreachable, -} - -/// What the running daemon, rather than the doctor's own process, sees. The -/// two can read different credential stores or environments. -#[derive(Debug, Clone, Default, Serialize)] -pub struct DaemonDiagnostic { - pub status: DaemonStatus, - #[serde(skip_serializing_if = "Option::is_none")] - pub version: Option, - /// The daemon's own resolution of the route's credentials. - #[serde(skip_serializing_if = "Option::is_none")] - pub auth: Option, - /// Distinct latest errors the daemon recorded for this agent's sessions. - #[serde(skip_serializing_if = "Vec::is_empty")] - pub session_errors: Vec, - /// Current holds, separate from persisted historical plugin errors. - #[serde(skip_serializing_if = "Vec::is_empty")] - pub recovering_sessions: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, -} - -impl DaemonDiagnostic { - /// ` ()` when the daemon reported one. - pub fn version_suffix(&self) -> String { - self.version - .as_deref() - .map(|version| format!(" ({version})")) - .unwrap_or_default() - } - - /// The daemon answered and could not authenticate the route. - pub fn auth_failed(&self) -> bool { - self.auth.as_ref().is_some_and(AuthDiagnostic::is_error) - } -} - -#[derive(Debug, Clone, Serialize)] -pub struct DoctorCommandOutput { - pub source: String, - pub display_name: String, - pub settings_path: PathBuf, - pub settings_present: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub project_settings_path: Option, - #[serde(skip_serializing_if = "Vec::is_empty")] - pub project_settings_fields: Vec, - pub enabled: bool, - pub route_source: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub route: Option, - pub auth: AuthDiagnostic, - pub daemon: DaemonDiagnostic, - pub warnings: Vec, - pub plugin_diagnostics: Vec, -} - -#[derive(Debug, Clone, Serialize)] -#[serde(tag = "command", rename_all = "snake_case")] -pub enum TraceCommandOutput { - Status(StatusCommandOutput), - Doctor(Box), - Install(InstallCommandOutput), - Enable(InstallCommandOutput), - Disable(InstallCommandOutput), - Uninstall(InstallCommandOutput), - Update(UpdateCommandOutput), - Stop(StopCommandOutput), - Import { - /// Summaries for the imported sessions. - summaries: Vec, - }, -} - -impl TraceCommandOutput { - pub fn status(status: Option) -> Self { - Self::Status(status.into()) - } - - pub fn doctor(output: DoctorCommandOutput) -> Self { - Self::Doctor(Box::new(output)) - } - - pub fn install( - source: impl Into, - display_name: impl Into, - settings_path: impl Into, - ) -> Self { - let source = source.into(); - Self::Install(InstallCommandOutput { - source, - display_name: display_name.into(), - settings_path: settings_path.into(), - restart_required: true, - configuration: None, - scope: "user", - applies_to_all_agents: false, - enabled: None, - warnings: Vec::new(), - }) - } - - /// Compatibility alias for creating install output. - pub fn setup( - source: impl Into, - display_name: impl Into, - settings_path: impl Into, - ) -> Self { - Self::install(source, display_name, settings_path) - } - - pub fn enable( - source: impl Into, - display_name: impl Into, - settings_path: impl Into, - ) -> Self { - Self::Enable(InstallCommandOutput { - source: source.into(), - display_name: display_name.into(), - settings_path: settings_path.into(), - restart_required: true, - configuration: Some("reused"), - scope: "user", - applies_to_all_agents: false, - enabled: None, - warnings: Vec::new(), - }) - } - - pub fn project_install( - source: impl Into, - display_name: impl Into, - settings_path: impl Into, - ) -> Self { - let mut output = Self::install(source, display_name, settings_path).with_scope("project"); - if let Self::Install(setup) = &mut output { - setup.warnings.push("Settings not specified here must be supplied by each user's configuration. Each user needs a user-level installation and usable Braintrust credentials for their sessions to be captured.".into()); - setup.warnings.push( - "This shared project configuration applies to all coding agents in the repository." - .into(), - ); - } - output - } - - pub(crate) fn with_scope(mut self, scope: &'static str) -> Self { - match &mut self { - Self::Install(output) - | Self::Enable(output) - | Self::Disable(output) - | Self::Uninstall(output) => { - output.scope = scope; - output.applies_to_all_agents = scope == "project"; - } - _ => {} - } - self - } - - pub(crate) fn with_enabled(mut self, enabled: bool) -> Self { - if let Self::Install(output) = &mut self { - output.enabled = Some(enabled); - } - self - } - - pub(crate) fn into_enable(mut self, configuration: &'static str) -> Self { - match &mut self { - Self::Install(output) | Self::Enable(output) => { - output.configuration = Some(configuration) - } - _ => return self, - } - match self { - Self::Install(output) => Self::Enable(output), - _ => self, - } - } - - pub fn stop(running: bool, stopped: bool) -> Self { - Self::Stop(StopCommandOutput { running, stopped }) - } - - pub fn import(summaries: Vec) -> Self { - Self::Import { summaries } - } - - pub fn disable( - source: impl Into, - display_name: impl Into, - settings_path: impl Into, - ) -> Self { - Self::Disable(InstallCommandOutput { - source: source.into(), - display_name: display_name.into(), - settings_path: settings_path.into(), - restart_required: true, - configuration: None, - scope: "user", - applies_to_all_agents: false, - enabled: None, - warnings: Vec::new(), - }) - } - - pub fn uninstall( - source: impl Into, - display_name: impl Into, - settings_path: impl Into, - ) -> Self { - Self::Uninstall(InstallCommandOutput { - source: source.into(), - display_name: display_name.into(), - settings_path: settings_path.into(), - restart_required: true, - configuration: None, - scope: "user", - applies_to_all_agents: false, - enabled: None, - warnings: Vec::new(), - }) - } - - pub fn update(source: impl Into, display_name: impl Into) -> Self { - let source = source.into(); - Self::Update(UpdateCommandOutput { - source, - display_name: display_name.into(), - restart_required: true, - }) - } - - pub fn render(&self, format: OutputFormat) -> anyhow::Result { - match format { - OutputFormat::Json => Ok(serde_json::to_string(self)?), - OutputFormat::Human => self.render_human(), - } - } - - fn render_human(&self) -> anyhow::Result { - match self { - Self::Status(status) if !status.running => Ok("bt-daemon is not running".into()), - Self::Status(status) => Ok(serde_json::to_string_pretty(&StatusResult { - daemon_version: status.daemon_version.clone().unwrap_or_default(), - uptime_ms: status.uptime_ms.unwrap_or_default(), - sessions: status.sessions.clone(), - })?), - Self::Doctor(doctor) => { - let route = doctor - .route - .as_ref() - .map(serde_json::to_string_pretty) - .transpose()? - .unwrap_or_else(|| "(unresolved)".into()); - let mut rendered = format!( - "Braintrust tracing doctor: {}\nEnabled: {}\nSettings: {}{}\nRoute source: {}\nRoute: {}", - doctor.display_name, - doctor.enabled, - doctor.settings_path.display(), - if doctor.settings_present { "" } else { " (missing)" }, - doctor.route_source, - route, - ); - if let Some(path) = &doctor.project_settings_path { - rendered.push_str(&format!("\nProject settings: {}", path.display())); - if !doctor.project_settings_fields.is_empty() { - rendered.push_str(&format!("\nProject overrides: {}", doctor.project_settings_fields.join(", "))); - } - } - push_auth_lines(&mut rendered, "", &doctor.auth); - let daemon = &doctor.daemon; - let status = match daemon.status { - DaemonStatus::Running => "running", - DaemonStatus::NotRunning => "not running", - DaemonStatus::Unreachable => "unreachable", - }; - rendered.push_str(&format!("\nDaemon: {status}{}", daemon.version_suffix())); - if let Some(error) = &daemon.error { - rendered.push_str(&format!("\nDaemon error: {error}")); - } - if let Some(auth) = &daemon.auth { - push_auth_lines(&mut rendered, "Daemon ", auth); - } - for error in &daemon.session_errors { - rendered.push_str(&format!("\nDaemon session error: {error}")); - } - for session in &daemon.recovering_sessions { - if let Some(recovery) = &session.recovery { - rendered.push_str(&format!( - "\nActive delivery hold: {} / {}\nStage: {}\nQueued span operations: {}\nRetry attempts: {}\nWaiting for: {}", - session.source, session.session_id, recovery.stage, - session.queued_span_ops.map_or_else(|| "unknown".into(), |count| count.to_string()), recovery.attempt, recovery.retry - )); - } - } - for warning in &doctor.warnings { - rendered.push_str(&format!("\nWarning: {warning}")); - } - for diagnostic in &doctor.plugin_diagnostics { - rendered.push_str(&format!( - "\nHistorical plugin error: {} ({} recorded occurrence{}; not an affected-span count)\nFirst seen: {}\nLast seen: {}\n{}", - diagnostic.plugin_path.display(), - diagnostic.occurrences, - if diagnostic.occurrences == 1 { "" } else { "s" }, - render_timestamp(diagnostic.first_seen_ms), - render_timestamp(diagnostic.last_seen_ms), - diagnostic.exception - )); - } - Ok(rendered) - } - Self::Enable(enable) if enable.scope == "project" => Ok(format!( - "Braintrust tracing is enabled for all coding agents in this repository. Project configuration {} at {}.", - enable.configuration.unwrap_or("reused"), enable.settings_path.display() - )), - Self::Disable(disable) if disable.scope == "project" => Ok(format!( - "Braintrust tracing is disabled for all coding agents in this repository at {}.", disable.settings_path.display() - )), - Self::Enable(setup) if setup.configuration.is_some_and(|value| value != "reused") => Ok(format!( - "Braintrust tracing configuration {} for {} at {} scope in {}.\nRestart the coding agent to apply the change.", - setup.configuration.unwrap_or_default(), setup.display_name, setup.scope, setup.settings_path.display() - )), - Self::Install(setup) if setup.scope == "project" => Ok(format!( - "Project tracing settings for {} were written to {}.\nTracing is {}.\n{}", setup.display_name, setup.settings_path.display(), if setup.enabled == Some(false) { "disabled" } else { "enabled" }, setup.warnings.join("\n") - )), - Self::Install(setup) => Ok(format!( - "The Braintrust tracing plugin is installed for {} and configured in {}.{}\nRestart the coding agent to load the tracing plugin.", - setup.display_name, - setup.settings_path.display(), - if setup.enabled == Some(false) { " Tracing is disabled by default." } else { "" }, - )), - Self::Enable(enable) => Ok(format!( - "Braintrust tracing is enabled for {} at {} scope in {}.\nRestart the coding agent to apply the change.", - enable.display_name, enable.scope, enable.settings_path.display() - )), - Self::Disable(disable) => Ok(format!( - "Braintrust tracing is disabled for {} at {} scope in {}.\nRestart the coding agent to apply the change.", - disable.display_name, - disable.scope, - disable.settings_path.display() - )), - Self::Uninstall(uninstall) if uninstall.scope == "project" => Ok(format!( - "The shared repository tracing configuration was removed from {}. User-level settings now apply to all agents in this repository.", uninstall.settings_path.display() - )), - Self::Uninstall(uninstall) => Ok(format!( - "The Braintrust tracing plugin and configuration were removed for {} from {}.\nRestart the coding agent to apply the change.", - uninstall.display_name, uninstall.settings_path.display() - )), - Self::Update(update) => Ok(format!( - "The Braintrust tracing plugin was updated for {}.\nRestart the coding agent to load the update.", - update.display_name, - )), - Self::Stop(stop) if stop.stopped => Ok("Tracing daemon stopped.".into()), - Self::Stop(_) => Ok("No tracing daemon is running.".into()), - Self::Import { summaries } => Ok(summaries - .iter() - .map(|summary| { - let destination = summary - .destination - .as_ref() - .map(render_destination) - .unwrap_or_else(|| "the configured destination".into()); - let root = summary - .root_span_id - .as_deref() - .map(|id| format!(", root span {id}")) - .unwrap_or_default(); - format!( - "Imported session {} to {}: {} spans{}.", - summary.session_id, destination, summary.span_count, root - ) - }) - .collect::>() - .join("\n")), - } - } -} - -/// Render one auth view; `prefix` distinguishes the daemon's from the local. -fn push_auth_lines(rendered: &mut String, prefix: &str, auth: &AuthDiagnostic) { - let label = |name: &str| { - if prefix.is_empty() { - name.to_string() - } else { - format!("{prefix}{}", name.to_lowercase()) - } - }; - rendered.push_str(&format!( - "\n{}: {} ({})", - label("Auth"), - auth.status, - auth.source - )); - for (name, value) in [ - ("Profile", &auth.profile), - ("Organization", &auth.org_name), - ("Auth error", &auth.error), - ] { - if let Some(value) = value { - rendered.push_str(&format!("\n{}: {value}", label(name))); - } - } -} - -fn render_timestamp(timestamp_ms: i64) -> String { - chrono::DateTime::from_timestamp_millis(timestamp_ms) - .map(|timestamp| timestamp.to_rfc3339()) - .unwrap_or_else(|| timestamp_ms.to_string()) -} - -fn render_destination(destination: &TraceDestination) -> String { - match destination { - TraceDestination::ProjectLogs { - project_id, - project_name, - } => project_name - .as_ref() - .map(|name| format!("project {name}")) - .or_else(|| project_id.as_ref().map(|id| format!("project {id}"))) - .unwrap_or_else(|| "project logs".into()), - TraceDestination::Experiment { experiment_id } => { - format!("experiment {experiment_id}") - } - TraceDestination::ParentSpan { components } => components - .span_id - .as_ref() - .map(|id| format!("parent span {id}")) - .unwrap_or_else(|| "a parent span".into()), - } -} - +mod daemon_diagnostic; +mod daemon_status; +mod doctor_command_output; +mod import_summary; +mod install_command_output; +mod output_format; +mod status_command_output; +mod stop_command_output; #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn absent_status_is_machine_readable_in_json_mode() { - let output = TraceCommandOutput::status(None); - let rendered = output.render(OutputFormat::Json).unwrap(); - let value: serde_json::Value = serde_json::from_str(&rendered).unwrap(); - assert_eq!(value["command"], "status"); - assert_eq!(value["running"], false); - assert_eq!(value["sessions"], serde_json::json!([])); - assert!(value.get("daemon_version").is_none()); - assert!(!rendered.contains("not running")); - } - - #[test] - fn install_json_contains_stable_selection_fields_without_prose() { - let output = TraceCommandOutput::install( - "opencode", - "OpenCode", - PathBuf::from("/tmp/opencode/braintrust.json"), - ); - let rendered = output.render(OutputFormat::Json).unwrap(); - let value: serde_json::Value = serde_json::from_str(&rendered).unwrap(); - assert_eq!(value["command"], "install"); - assert_eq!(value["source"], "opencode"); - assert_eq!(value["restart_required"], true); - assert!(!rendered.contains("installed for")); - } - - #[test] - fn resume_output_reports_enable() { - let output = TraceCommandOutput::enable("pi", "Pi", PathBuf::from("braintrust.json")); - let json: serde_json::Value = - serde_json::from_str(&output.render(OutputFormat::Json).unwrap()).unwrap(); - assert_eq!(json["command"], "enable"); - assert_eq!(json["configuration"], "reused"); - assert!(output - .render(OutputFormat::Human) - .unwrap() - .contains("tracing is enabled")); - } - - #[test] - fn disable_output_is_explicit() { - let output = TraceCommandOutput::disable( - "antigravity", - "Google Antigravity", - PathBuf::from("/tmp/antigravity/braintrust.json"), - ); - let value: serde_json::Value = - serde_json::from_str(&output.render(OutputFormat::Json).unwrap()).unwrap(); - assert_eq!(value["command"], "disable"); - assert!(output - .render(OutputFormat::Human) - .unwrap() - .contains("disabled for Google Antigravity")); - } +mod tests; +mod trace_command_output; +mod update_command_output; - #[test] - fn codex_setup_and_updates_do_not_request_manual_trust() { - for output in [ - TraceCommandOutput::install("codex", "Codex", PathBuf::from("braintrust.json")), - TraceCommandOutput::update("codex", "Codex"), - ] { - let human = output.render(OutputFormat::Human).unwrap(); - assert!(!human.contains("Open /hooks")); - let json: serde_json::Value = - serde_json::from_str(&output.render(OutputFormat::Json).unwrap()).unwrap(); - assert!(json.get("next_steps").is_none()); - } - let disabled = - TraceCommandOutput::disable("codex", "Codex", PathBuf::from("braintrust.json")); - assert!(!disabled - .render(OutputFormat::Human) - .unwrap() - .contains("Open /hooks")); - } - - #[test] - fn stop_json_reports_idempotent_and_successful_shutdowns() { - let absent: serde_json::Value = serde_json::from_str( - &TraceCommandOutput::stop(false, false) - .render(OutputFormat::Json) - .unwrap(), - ) - .unwrap(); - assert_eq!( - absent, - serde_json::json!({ - "command": "stop", - "running": false, - "stopped": false - }) - ); - - let stopped: serde_json::Value = serde_json::from_str( - &TraceCommandOutput::stop(true, true) - .render(OutputFormat::Json) - .unwrap(), - ) - .unwrap(); - assert_eq!( - stopped, - serde_json::json!({ - "command": "stop", - "running": true, - "stopped": true - }) - ); - } - - #[test] - fn import_summary_has_stable_human_and_json_output() { - let output = TraceCommandOutput::import(vec![ImportSummary { - session_id: "session-1".into(), - destination: Some(TraceDestination::ProjectLogs { - project_id: None, - project_name: Some("Agents".into()), - }), - root_span_id: Some("root-1".into()), - span_count: 3, - finalized: true, - }]); - assert_eq!( - output.render(OutputFormat::Human).unwrap(), - "Imported session session-1 to project Agents: 3 spans, root span root-1." - ); - let value: serde_json::Value = - serde_json::from_str(&output.render(OutputFormat::Json).unwrap()).unwrap(); - assert_eq!(value["command"], "import"); - assert_eq!(value["summaries"][0]["session_id"], "session-1"); - assert_eq!(value["summaries"][0]["span_count"], 3); - assert_eq!(value["summaries"][0]["finalized"], true); - } - - #[test] - fn human_output_preserves_existing_messages() { - assert_eq!( - TraceCommandOutput::status(None) - .render(OutputFormat::Human) - .unwrap(), - "bt-daemon is not running" - ); - assert_eq!( - TraceCommandOutput::stop(false, false) - .render(OutputFormat::Human) - .unwrap(), - "No tracing daemon is running." - ); - } - - #[test] - fn doctor_json_is_structured_and_contains_no_credentials() { - let output = TraceCommandOutput::doctor(DoctorCommandOutput { - source: "codex".into(), - display_name: "Codex".into(), - settings_path: PathBuf::from("/tmp/braintrust.json"), - settings_present: true, - project_settings_path: None, - project_settings_fields: Vec::new(), - enabled: true, - route_source: "settings_file".into(), - route: Some(SessionRoute::default()), - auth: AuthDiagnostic { - status: "ready".into(), - source: "saved_profile".into(), - kind: Some("oauth".into()), - profile: Some("test-profile".into()), - org_name: Some("test-org".into()), - expires_at_ms: Some(123), - error: None, - }, - daemon: DaemonDiagnostic { - status: DaemonStatus::Running, - version: Some("1.2.3".into()), - auth: Some(AuthDiagnostic { - status: "error".into(), - source: "saved_profile".into(), - kind: None, - profile: None, - org_name: None, - expires_at_ms: None, - error: Some("saved profile ID 'p' no longer exists".into()), - }), - session_errors: vec!["could not resolve Braintrust auth for codex".into()], - recovering_sessions: vec![crate::wire::SessionStatus { - session_id: "held-session".into(), - source: "codex".into(), - route: None, - recovery: Some(crate::wire::RecoveryInfo { - stage: "plugin".into(), - position: 1, - reason: "deadline".into(), - retry: "bounded retry".into(), - eligible: false, - attempt: 1, - }), - queued: 8, - queued_span_ops: Some(7), - spans_emitted: 0, - permalink: None, - last_error: None, - }], - error: None, - }, - warnings: Vec::new(), - plugin_diagnostics: vec![crate::PluginDiagnostic { - source: "codex".into(), - plugin_path: PathBuf::from("/tmp/redact.mjs"), - plugin_digest: Some("abc".into()), - exception: "Error: raw secret\n at redact (redact.mjs:1)".into(), - first_seen_ms: 1, - last_seen_ms: 2, - occurrences: 3, - }], - }); - let rendered = output.render(OutputFormat::Json).unwrap(); - let value: serde_json::Value = serde_json::from_str(&rendered).unwrap(); - assert_eq!(value["command"], "doctor"); - assert_eq!(value["auth"]["source"], "saved_profile"); - assert_eq!(value["daemon"]["status"], "running"); - assert_eq!(value["daemon"]["auth"]["status"], "error"); - assert_eq!( - value["daemon"]["session_errors"][0], - "could not resolve Braintrust auth for codex" - ); - assert_eq!( - value["daemon"]["recovering_sessions"][0]["queued_span_ops"], - 7 - ); - assert_eq!( - value["daemon"]["recovering_sessions"][0]["recovery"]["attempt"], - 1 - ); - let human = output.render(OutputFormat::Human).unwrap(); - assert!(human.contains("Active delivery hold: codex / held-session")); - assert!(human.contains("Queued span operations: 7")); - assert!(human.contains("Historical plugin error:")); - assert!(human.contains("not an affected-span count")); - assert!(!rendered.contains("token")); - assert!(!rendered.contains("api_key")); - assert_eq!( - value["plugin_diagnostics"][0]["exception"], - "Error: raw secret\n at redact (redact.mjs:1)" - ); - } -} +pub use auth_diagnostic::AuthDiagnostic; +pub use daemon_diagnostic::DaemonDiagnostic; +pub use daemon_status::DaemonStatus; +pub use doctor_command_output::DoctorCommandOutput; +pub use import_summary::ImportSummary; +pub use install_command_output::InstallCommandOutput; +pub use install_command_output::SetupCommandOutput; +pub use output_format::OutputFormat; +pub use status_command_output::StatusCommandOutput; +pub use stop_command_output::StopCommandOutput; +pub use trace_command_output::TraceCommandOutput; +pub use update_command_output::UpdateCommandOutput; diff --git a/bt-daemon/src/command_output/auth_diagnostic.rs b/bt-daemon/src/command_output/auth_diagnostic.rs index a4269929..835f5de4 100644 --- a/bt-daemon/src/command_output/auth_diagnostic.rs +++ b/bt-daemon/src/command_output/auth_diagnostic.rs @@ -63,4 +63,30 @@ impl AuthDiagnostic { pub fn is_error(&self) -> bool { self.status == "error" } + + /// Render one auth view; `prefix` distinguishes the daemon's from the local. + pub(super) fn append_human(&self, rendered: &mut String, prefix: &str) { + let label = |name: &str| { + if prefix.is_empty() { + name.to_string() + } else { + format!("{prefix}{}", name.to_lowercase()) + } + }; + rendered.push_str(&format!( + "\n{}: {} ({})", + label("Auth"), + self.status, + self.source + )); + for (name, value) in [ + ("Profile", &self.profile), + ("Organization", &self.org_name), + ("Auth error", &self.error), + ] { + if let Some(value) = value { + rendered.push_str(&format!("\n{}: {value}", label(name))); + } + } + } } diff --git a/bt-daemon/src/command_output/daemon_diagnostic.rs b/bt-daemon/src/command_output/daemon_diagnostic.rs new file mode 100644 index 00000000..5fc7dc7c --- /dev/null +++ b/bt-daemon/src/command_output/daemon_diagnostic.rs @@ -0,0 +1,63 @@ +use super::{AuthDiagnostic, DaemonStatus}; +use serde::Serialize; + +/// What the running daemon, rather than the doctor's own process, sees. The +/// two can read different credential stores or environments. +#[derive(Debug, Clone, Default, Serialize)] +pub struct DaemonDiagnostic { + pub status: DaemonStatus, + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, + /// The daemon's own resolution of the route's credentials. + #[serde(skip_serializing_if = "Option::is_none")] + pub auth: Option, + /// Distinct latest errors the daemon recorded for this agent's sessions. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub session_errors: Vec, + /// Current holds, separate from persisted historical plugin errors. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub recovering_sessions: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl DaemonDiagnostic { + /// ` ()` when the daemon reported one. + pub fn version_suffix(&self) -> String { + self.version + .as_deref() + .map(|version| format!(" ({version})")) + .unwrap_or_default() + } + + /// The daemon answered and could not authenticate the route. + pub fn auth_failed(&self) -> bool { + self.auth.as_ref().is_some_and(AuthDiagnostic::is_error) + } + + pub(super) fn append_human(&self, rendered: &mut String) { + rendered.push_str(&format!( + "\nDaemon: {}{}", + self.status, + self.version_suffix() + )); + if let Some(error) = &self.error { + rendered.push_str(&format!("\nDaemon error: {error}")); + } + if let Some(auth) = &self.auth { + auth.append_human(rendered, "Daemon "); + } + for error in &self.session_errors { + rendered.push_str(&format!("\nDaemon session error: {error}")); + } + for session in &self.recovering_sessions { + if let Some(recovery) = &session.recovery { + rendered.push_str(&format!( + "\nActive delivery hold: {} / {}\nStage: {}\nQueued span operations: {}\nRetry attempts: {}\nWaiting for: {}", + session.source, session.session_id, recovery.stage, + session.queued_span_ops.map_or_else(|| "unknown".into(), |count| count.to_string()), recovery.attempt, recovery.retry + )); + } + } + } +} diff --git a/bt-daemon/src/command_output/daemon_status.rs b/bt-daemon/src/command_output/daemon_status.rs new file mode 100644 index 00000000..9ae90a27 --- /dev/null +++ b/bt-daemon/src/command_output/daemon_status.rs @@ -0,0 +1,20 @@ +use serde::Serialize; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum DaemonStatus { + Running, + #[default] + NotRunning, + Unreachable, +} + +impl std::fmt::Display for DaemonStatus { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(match self { + Self::Running => "running", + Self::NotRunning => "not running", + Self::Unreachable => "unreachable", + }) + } +} diff --git a/bt-daemon/src/command_output/doctor_command_output.rs b/bt-daemon/src/command_output/doctor_command_output.rs new file mode 100644 index 00000000..4ac51171 --- /dev/null +++ b/bt-daemon/src/command_output/doctor_command_output.rs @@ -0,0 +1,76 @@ +use super::{AuthDiagnostic, DaemonDiagnostic}; +use crate::wire::SessionRoute; +use serde::Serialize; +use std::path::PathBuf; + +#[derive(Debug, Clone, Serialize)] +pub struct DoctorCommandOutput { + pub source: String, + pub display_name: String, + pub settings_path: PathBuf, + pub settings_present: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub project_settings_path: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub project_settings_fields: Vec, + pub enabled: bool, + pub route_source: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub route: Option, + pub auth: AuthDiagnostic, + pub daemon: DaemonDiagnostic, + pub warnings: Vec, + pub plugin_diagnostics: Vec, +} + +impl DoctorCommandOutput { + pub(super) fn render_human(&self) -> anyhow::Result { + let route = self + .route + .as_ref() + .map(serde_json::to_string_pretty) + .transpose()? + .unwrap_or_else(|| "(unresolved)".into()); + let mut rendered = format!( + "Braintrust tracing doctor: {}\nEnabled: {}\nSettings: {}{}\nRoute source: {}\nRoute: {}", + self.display_name, + self.enabled, + self.settings_path.display(), + if self.settings_present { "" } else { " (missing)" }, + self.route_source, + route, + ); + if let Some(path) = &self.project_settings_path { + rendered.push_str(&format!("\nProject settings: {}", path.display())); + if !self.project_settings_fields.is_empty() { + rendered.push_str(&format!( + "\nProject overrides: {}", + self.project_settings_fields.join(", ") + )); + } + } + self.auth.append_human(&mut rendered, ""); + self.daemon.append_human(&mut rendered); + for warning in &self.warnings { + rendered.push_str(&format!("\nWarning: {warning}")); + } + for diagnostic in &self.plugin_diagnostics { + rendered.push_str(&format!( + "\nHistorical plugin error: {} ({} recorded occurrence{}; not an affected-span count)\nFirst seen: {}\nLast seen: {}\n{}", + diagnostic.plugin_path.display(), + diagnostic.occurrences, + if diagnostic.occurrences == 1 { "" } else { "s" }, + render_timestamp(diagnostic.first_seen_ms), + render_timestamp(diagnostic.last_seen_ms), + diagnostic.exception + )); + } + Ok(rendered) + } +} + +fn render_timestamp(timestamp_ms: i64) -> String { + chrono::DateTime::from_timestamp_millis(timestamp_ms) + .map(|timestamp| timestamp.to_rfc3339()) + .unwrap_or_else(|| timestamp_ms.to_string()) +} diff --git a/bt-daemon/src/command_output/import_summary.rs b/bt-daemon/src/command_output/import_summary.rs new file mode 100644 index 00000000..50a3d5fe --- /dev/null +++ b/bt-daemon/src/command_output/import_summary.rs @@ -0,0 +1,53 @@ +use crate::wire::TraceDestination; +use serde::Serialize; + +#[derive(Debug, Clone, Serialize)] +pub struct ImportSummary { + pub session_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub destination: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub root_span_id: Option, + pub span_count: usize, + pub finalized: bool, +} + +impl ImportSummary { + pub(super) fn render_human(&self) -> String { + let destination = self + .destination + .as_ref() + .map(render_destination) + .unwrap_or_else(|| "the configured destination".into()); + let root = self + .root_span_id + .as_deref() + .map(|id| format!(", root span {id}")) + .unwrap_or_default(); + format!( + "Imported session {} to {}: {} spans{}.", + self.session_id, destination, self.span_count, root + ) + } +} + +fn render_destination(destination: &TraceDestination) -> String { + match destination { + TraceDestination::ProjectLogs { + project_id, + project_name, + } => project_name + .as_ref() + .map(|name| format!("project {name}")) + .or_else(|| project_id.as_ref().map(|id| format!("project {id}"))) + .unwrap_or_else(|| "project logs".into()), + TraceDestination::Experiment { experiment_id } => { + format!("experiment {experiment_id}") + } + TraceDestination::ParentSpan { components } => components + .span_id + .as_ref() + .map(|id| format!("parent span {id}")) + .unwrap_or_else(|| "a parent span".into()), + } +} diff --git a/bt-daemon/src/command_output/install_command_output.rs b/bt-daemon/src/command_output/install_command_output.rs new file mode 100644 index 00000000..1c758cff --- /dev/null +++ b/bt-daemon/src/command_output/install_command_output.rs @@ -0,0 +1,135 @@ +use serde::Serialize; +use std::path::PathBuf; + +#[derive(Debug, Clone, Serialize)] +pub struct InstallCommandOutput { + pub source: String, + pub display_name: String, + pub settings_path: PathBuf, + pub restart_required: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub configuration: Option<&'static str>, + pub scope: &'static str, + #[serde(skip_serializing_if = "is_false")] + pub applies_to_all_agents: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub warnings: Vec, +} + +/// Backwards-compatible name for the shared install and enable output. +pub type SetupCommandOutput = InstallCommandOutput; + +fn is_false(value: &bool) -> bool { + !value +} + +impl InstallCommandOutput { + pub(super) fn new( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self { + source: source.into(), + display_name: display_name.into(), + settings_path: settings_path.into(), + restart_required: true, + configuration: None, + scope: "user", + applies_to_all_agents: false, + enabled: None, + warnings: Vec::new(), + } + } + + pub(super) fn enabling( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self { + configuration: Some("reused"), + ..Self::new(source, display_name, settings_path) + } + } + + pub(super) fn set_scope(&mut self, scope: &'static str) { + self.scope = scope; + self.applies_to_all_agents = scope == "project"; + } + + pub(super) fn for_project(mut self) -> Self { + self.set_scope("project"); + self.warnings.push("Settings not specified here must be supplied by each user's configuration. Each user needs a user-level installation and usable Braintrust credentials for their sessions to be captured.".into()); + self.warnings.push( + "This shared project configuration applies to all coding agents in the repository." + .into(), + ); + self + } + + pub(super) fn render_install(&self) -> String { + if self.scope == "project" { + return format!( + "Project tracing settings for {} were written to {}.\nTracing is {}.\n{}", + self.display_name, + self.settings_path.display(), + if self.enabled == Some(false) { + "disabled" + } else { + "enabled" + }, + self.warnings.join("\n") + ); + } + format!( + "The Braintrust tracing plugin is installed for {} and configured in {}.{}\nRestart the coding agent to load the tracing plugin.", + self.display_name, self.settings_path.display(), + if self.enabled == Some(false) { " Tracing is disabled by default." } else { "" }, + ) + } + + pub(super) fn render_enable(&self) -> String { + if self.scope == "project" { + return format!( + "Braintrust tracing is enabled for all coding agents in this repository. Project configuration {} at {}.", + self.configuration.unwrap_or("reused"), self.settings_path.display() + ); + } + if self.configuration.is_some_and(|value| value != "reused") { + return format!( + "Braintrust tracing configuration {} for {} at {} scope in {}.\nRestart the coding agent to apply the change.", + self.configuration.unwrap_or_default(), self.display_name, self.scope, self.settings_path.display() + ); + } + format!( + "Braintrust tracing is enabled for {} at {} scope in {}.\nRestart the coding agent to apply the change.", + self.display_name, self.scope, self.settings_path.display() + ) + } + + pub(super) fn render_disable(&self) -> String { + if self.scope == "project" { + return format!( + "Braintrust tracing is disabled for all coding agents in this repository at {}.", + self.settings_path.display() + ); + } + format!( + "Braintrust tracing is disabled for {} at {} scope in {}.\nRestart the coding agent to apply the change.", + self.display_name, self.scope, self.settings_path.display() + ) + } + + pub(super) fn render_uninstall(&self) -> String { + if self.scope == "project" { + return format!("The shared repository tracing configuration was removed from {}. User-level settings now apply to all agents in this repository.", self.settings_path.display()); + } + format!( + "The Braintrust tracing plugin and configuration were removed for {} from {}.\nRestart the coding agent to apply the change.", + self.display_name, self.settings_path.display() + ) + } +} diff --git a/bt-daemon/src/command_output/output_format.rs b/bt-daemon/src/command_output/output_format.rs new file mode 100644 index 00000000..b90c52c1 --- /dev/null +++ b/bt-daemon/src/command_output/output_format.rs @@ -0,0 +1,15 @@ +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OutputFormat { + Human, + Json, +} + +impl From for OutputFormat { + fn from(json: bool) -> Self { + if json { + Self::Json + } else { + Self::Human + } + } +} diff --git a/bt-daemon/src/command_output/status_command_output.rs b/bt-daemon/src/command_output/status_command_output.rs new file mode 100644 index 00000000..295e49eb --- /dev/null +++ b/bt-daemon/src/command_output/status_command_output.rs @@ -0,0 +1,44 @@ +use crate::wire::StatusResult; +use serde::Serialize; + +#[derive(Debug, Clone, Serialize)] +pub struct StatusCommandOutput { + pub running: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub daemon_version: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub uptime_ms: Option, + pub sessions: Vec, +} + +impl From> for StatusCommandOutput { + fn from(status: Option) -> Self { + match status { + Some(status) => Self { + running: true, + daemon_version: Some(status.daemon_version), + uptime_ms: Some(status.uptime_ms), + sessions: status.sessions, + }, + None => Self { + running: false, + daemon_version: None, + uptime_ms: None, + sessions: Vec::new(), + }, + } + } +} + +impl StatusCommandOutput { + pub(super) fn render_human(&self) -> anyhow::Result { + if !self.running { + return Ok("bt-daemon is not running".into()); + } + Ok(serde_json::to_string_pretty(&StatusResult { + daemon_version: self.daemon_version.clone().unwrap_or_default(), + uptime_ms: self.uptime_ms.unwrap_or_default(), + sessions: self.sessions.clone(), + })?) + } +} diff --git a/bt-daemon/src/command_output/stop_command_output.rs b/bt-daemon/src/command_output/stop_command_output.rs new file mode 100644 index 00000000..07fe1eeb --- /dev/null +++ b/bt-daemon/src/command_output/stop_command_output.rs @@ -0,0 +1,18 @@ +use serde::Serialize; + +#[derive(Debug, Clone, Serialize)] +pub struct StopCommandOutput { + pub running: bool, + pub stopped: bool, +} + +impl StopCommandOutput { + pub(super) fn render_human(&self) -> String { + if self.stopped { + "Tracing daemon stopped." + } else { + "No tracing daemon is running." + } + .into() + } +} diff --git a/bt-daemon/src/command_output/tests.rs b/bt-daemon/src/command_output/tests.rs new file mode 100644 index 00000000..9c06e087 --- /dev/null +++ b/bt-daemon/src/command_output/tests.rs @@ -0,0 +1,248 @@ +use crate::wire::{SessionRoute, TraceDestination}; +use std::path::PathBuf; + +use super::*; + +#[test] +fn absent_status_is_machine_readable_in_json_mode() { + let output = TraceCommandOutput::status(None); + let rendered = output.render(OutputFormat::Json).unwrap(); + let value: serde_json::Value = serde_json::from_str(&rendered).unwrap(); + assert_eq!(value["command"], "status"); + assert_eq!(value["running"], false); + assert_eq!(value["sessions"], serde_json::json!([])); + assert!(value.get("daemon_version").is_none()); + assert!(!rendered.contains("not running")); +} + +#[test] +fn install_json_contains_stable_selection_fields_without_prose() { + let output = TraceCommandOutput::install( + "opencode", + "OpenCode", + PathBuf::from("/tmp/opencode/braintrust.json"), + ); + let rendered = output.render(OutputFormat::Json).unwrap(); + let value: serde_json::Value = serde_json::from_str(&rendered).unwrap(); + assert_eq!(value["command"], "install"); + assert_eq!(value["source"], "opencode"); + assert_eq!(value["restart_required"], true); + assert!(!rendered.contains("installed for")); +} + +#[test] +fn resume_output_reports_enable() { + let output = TraceCommandOutput::enable("pi", "Pi", PathBuf::from("braintrust.json")); + let json: serde_json::Value = + serde_json::from_str(&output.render(OutputFormat::Json).unwrap()).unwrap(); + assert_eq!(json["command"], "enable"); + assert_eq!(json["configuration"], "reused"); + assert!(output + .render(OutputFormat::Human) + .unwrap() + .contains("tracing is enabled")); +} + +#[test] +fn disable_output_is_explicit() { + let output = TraceCommandOutput::disable( + "antigravity", + "Google Antigravity", + PathBuf::from("/tmp/antigravity/braintrust.json"), + ); + let value: serde_json::Value = + serde_json::from_str(&output.render(OutputFormat::Json).unwrap()).unwrap(); + assert_eq!(value["command"], "disable"); + assert!(output + .render(OutputFormat::Human) + .unwrap() + .contains("disabled for Google Antigravity")); +} + +#[test] +fn codex_setup_and_updates_do_not_request_manual_trust() { + for output in [ + TraceCommandOutput::install("codex", "Codex", PathBuf::from("braintrust.json")), + TraceCommandOutput::update("codex", "Codex"), + ] { + let human = output.render(OutputFormat::Human).unwrap(); + assert!(!human.contains("Open /hooks")); + let json: serde_json::Value = + serde_json::from_str(&output.render(OutputFormat::Json).unwrap()).unwrap(); + assert!(json.get("next_steps").is_none()); + } + let disabled = TraceCommandOutput::disable("codex", "Codex", PathBuf::from("braintrust.json")); + assert!(!disabled + .render(OutputFormat::Human) + .unwrap() + .contains("Open /hooks")); +} + +#[test] +fn stop_json_reports_idempotent_and_successful_shutdowns() { + let absent: serde_json::Value = serde_json::from_str( + &TraceCommandOutput::stop(false, false) + .render(OutputFormat::Json) + .unwrap(), + ) + .unwrap(); + assert_eq!( + absent, + serde_json::json!({ + "command": "stop", + "running": false, + "stopped": false + }) + ); + + let stopped: serde_json::Value = serde_json::from_str( + &TraceCommandOutput::stop(true, true) + .render(OutputFormat::Json) + .unwrap(), + ) + .unwrap(); + assert_eq!( + stopped, + serde_json::json!({ + "command": "stop", + "running": true, + "stopped": true + }) + ); +} + +#[test] +fn import_summary_has_stable_human_and_json_output() { + let output = TraceCommandOutput::import(vec![ImportSummary { + session_id: "session-1".into(), + destination: Some(TraceDestination::ProjectLogs { + project_id: None, + project_name: Some("Agents".into()), + }), + root_span_id: Some("root-1".into()), + span_count: 3, + finalized: true, + }]); + assert_eq!( + output.render(OutputFormat::Human).unwrap(), + "Imported session session-1 to project Agents: 3 spans, root span root-1." + ); + let value: serde_json::Value = + serde_json::from_str(&output.render(OutputFormat::Json).unwrap()).unwrap(); + assert_eq!(value["command"], "import"); + assert_eq!(value["summaries"][0]["session_id"], "session-1"); + assert_eq!(value["summaries"][0]["span_count"], 3); + assert_eq!(value["summaries"][0]["finalized"], true); +} + +#[test] +fn human_output_preserves_existing_messages() { + assert_eq!( + TraceCommandOutput::status(None) + .render(OutputFormat::Human) + .unwrap(), + "bt-daemon is not running" + ); + assert_eq!( + TraceCommandOutput::stop(false, false) + .render(OutputFormat::Human) + .unwrap(), + "No tracing daemon is running." + ); +} + +#[test] +fn doctor_json_is_structured_and_contains_no_credentials() { + let output = TraceCommandOutput::doctor(DoctorCommandOutput { + source: "codex".into(), + display_name: "Codex".into(), + settings_path: PathBuf::from("/tmp/braintrust.json"), + settings_present: true, + project_settings_path: None, + project_settings_fields: Vec::new(), + enabled: true, + route_source: "settings_file".into(), + route: Some(SessionRoute::default()), + auth: AuthDiagnostic { + status: "ready".into(), + source: "saved_profile".into(), + kind: Some("oauth".into()), + profile: Some("test-profile".into()), + org_name: Some("test-org".into()), + expires_at_ms: Some(123), + error: None, + }, + daemon: DaemonDiagnostic { + status: DaemonStatus::Running, + version: Some("1.2.3".into()), + auth: Some(AuthDiagnostic { + status: "error".into(), + source: "saved_profile".into(), + kind: None, + profile: None, + org_name: None, + expires_at_ms: None, + error: Some("saved profile ID 'p' no longer exists".into()), + }), + session_errors: vec!["could not resolve Braintrust auth for codex".into()], + recovering_sessions: vec![crate::wire::SessionStatus { + session_id: "held-session".into(), + source: "codex".into(), + route: None, + recovery: Some(crate::wire::RecoveryInfo { + stage: "plugin".into(), + position: 1, + reason: "deadline".into(), + retry: "bounded retry".into(), + eligible: false, + attempt: 1, + }), + queued: 8, + queued_span_ops: Some(7), + spans_emitted: 0, + permalink: None, + last_error: None, + }], + error: None, + }, + warnings: Vec::new(), + plugin_diagnostics: vec![crate::PluginDiagnostic { + source: "codex".into(), + plugin_path: PathBuf::from("/tmp/redact.mjs"), + plugin_digest: Some("abc".into()), + exception: "Error: raw secret\n at redact (redact.mjs:1)".into(), + first_seen_ms: 1, + last_seen_ms: 2, + occurrences: 3, + }], + }); + let rendered = output.render(OutputFormat::Json).unwrap(); + let value: serde_json::Value = serde_json::from_str(&rendered).unwrap(); + assert_eq!(value["command"], "doctor"); + assert_eq!(value["auth"]["source"], "saved_profile"); + assert_eq!(value["daemon"]["status"], "running"); + assert_eq!(value["daemon"]["auth"]["status"], "error"); + assert_eq!( + value["daemon"]["session_errors"][0], + "could not resolve Braintrust auth for codex" + ); + assert_eq!( + value["daemon"]["recovering_sessions"][0]["queued_span_ops"], + 7 + ); + assert_eq!( + value["daemon"]["recovering_sessions"][0]["recovery"]["attempt"], + 1 + ); + let human = output.render(OutputFormat::Human).unwrap(); + assert!(human.contains("Active delivery hold: codex / held-session")); + assert!(human.contains("Queued span operations: 7")); + assert!(human.contains("Historical plugin error:")); + assert!(human.contains("not an affected-span count")); + assert!(!rendered.contains("token")); + assert!(!rendered.contains("api_key")); + assert_eq!( + value["plugin_diagnostics"][0]["exception"], + "Error: raw secret\n at redact (redact.mjs:1)" + ); +} diff --git a/bt-daemon/src/command_output/trace_command_output.rs b/bt-daemon/src/command_output/trace_command_output.rs new file mode 100644 index 00000000..7fd36b65 --- /dev/null +++ b/bt-daemon/src/command_output/trace_command_output.rs @@ -0,0 +1,174 @@ +use super::{ + DoctorCommandOutput, ImportSummary, InstallCommandOutput, OutputFormat, StatusCommandOutput, + StopCommandOutput, UpdateCommandOutput, +}; +use crate::wire::StatusResult; +use serde::Serialize; +use std::path::PathBuf; + +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "command", rename_all = "snake_case")] +pub enum TraceCommandOutput { + Status(StatusCommandOutput), + Doctor(Box), + Install(InstallCommandOutput), + Enable(InstallCommandOutput), + Disable(InstallCommandOutput), + Uninstall(InstallCommandOutput), + Update(UpdateCommandOutput), + Stop(StopCommandOutput), + Import { + /// Summaries for the imported sessions. + summaries: Vec, + }, +} + +impl TraceCommandOutput { + pub fn status(status: Option) -> Self { + Self::Status(status.into()) + } + + pub fn doctor(output: DoctorCommandOutput) -> Self { + Self::Doctor(Box::new(output)) + } + + pub fn install( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::Install(InstallCommandOutput::new( + source, + display_name, + settings_path, + )) + } + + /// Compatibility alias for creating install output. + pub fn setup( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::install(source, display_name, settings_path) + } + + pub fn enable( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::Enable(InstallCommandOutput::enabling( + source, + display_name, + settings_path, + )) + } + + pub fn project_install( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::Install(InstallCommandOutput::new(source, display_name, settings_path).for_project()) + } + + pub(crate) fn with_scope(mut self, scope: &'static str) -> Self { + match &mut self { + Self::Install(output) + | Self::Enable(output) + | Self::Disable(output) + | Self::Uninstall(output) => { + output.set_scope(scope); + } + _ => {} + } + self + } + + pub(crate) fn with_enabled(mut self, enabled: bool) -> Self { + if let Self::Install(output) = &mut self { + output.enabled = Some(enabled); + } + self + } + + pub(crate) fn into_enable(mut self, configuration: &'static str) -> Self { + match &mut self { + Self::Install(output) | Self::Enable(output) => { + output.configuration = Some(configuration) + } + _ => return self, + } + match self { + Self::Install(output) => Self::Enable(output), + _ => self, + } + } + + pub fn stop(running: bool, stopped: bool) -> Self { + Self::Stop(StopCommandOutput { running, stopped }) + } + + pub fn import(summaries: Vec) -> Self { + Self::Import { summaries } + } + + pub fn disable( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::Disable(InstallCommandOutput::new( + source, + display_name, + settings_path, + )) + } + + pub fn uninstall( + source: impl Into, + display_name: impl Into, + settings_path: impl Into, + ) -> Self { + Self::Uninstall(InstallCommandOutput::new( + source, + display_name, + settings_path, + )) + } + + pub fn update(source: impl Into, display_name: impl Into) -> Self { + let source = source.into(); + Self::Update(UpdateCommandOutput { + source, + display_name: display_name.into(), + restart_required: true, + }) + } + + pub fn render(&self, format: OutputFormat) -> anyhow::Result { + match format { + OutputFormat::Json => Ok(serde_json::to_string(self)?), + OutputFormat::Human => self.render_human(), + } + } + + fn render_human(&self) -> anyhow::Result { + match self { + Self::Status(output) => output.render_human(), + Self::Doctor(output) => output.render_human(), + Self::Install(output) => Ok(output.render_install()), + Self::Enable(output) => Ok(output.render_enable()), + Self::Disable(output) => Ok(output.render_disable()), + Self::Uninstall(output) => Ok(output.render_uninstall()), + Self::Update(output) => Ok(output.render_human()), + Self::Stop(output) => Ok(output.render_human()), + Self::Import { summaries } => Ok(summaries + .iter() + .map(ImportSummary::render_human) + .collect::>() + .join("\n")), + } + } +} diff --git a/bt-daemon/src/command_output/update_command_output.rs b/bt-daemon/src/command_output/update_command_output.rs new file mode 100644 index 00000000..12df7bd8 --- /dev/null +++ b/bt-daemon/src/command_output/update_command_output.rs @@ -0,0 +1,14 @@ +use serde::Serialize; + +#[derive(Debug, Clone, Serialize)] +pub struct UpdateCommandOutput { + pub source: String, + pub display_name: String, + pub restart_required: bool, +} + +impl UpdateCommandOutput { + pub(super) fn render_human(&self) -> String { + format!("The Braintrust tracing plugin was updated for {}.\nRestart the coding agent to load the update.", self.display_name) + } +} diff --git a/bt-daemon/src/muse/export_v1.rs b/bt-daemon/src/muse/export_v1.rs deleted file mode 100644 index be0f01bc..00000000 --- a/bt-daemon/src/muse/export_v1.rs +++ /dev/null @@ -1,247 +0,0 @@ -//! Durable export-v1 DTOs. This is a separate native schema from MSP views. -use super::hooks::{ErrorDetail, InputSummary, ToolArguments, ToolOutput}; -use super::usage::TokenUsage; -use serde::Deserialize; - -#[derive(Deserialize)] -pub(crate) struct Header { - pub export_schema_version: u64, - pub exporter_version: Option, - pub sessions: Vec, - #[serde(default)] - pub session_terminated_abnormally: bool, -} - -#[derive(Deserialize)] -#[serde(untagged)] -pub(crate) enum Version { - String(String), - Object { semver: String }, -} - -impl Version { - pub(crate) fn into_string(self) -> String { - match self { - Self::String(value) | Self::Object { semver: value } => value, - } - } -} - -#[derive(Clone, Deserialize)] -pub(crate) struct Session { - pub session_id: String, - pub trajectory_id: Option, - pub root_session_id: Option, - pub session_end: Option, -} - -#[derive(Clone, Deserialize)] -pub(crate) struct SessionEnd { - pub exit_reason: Option, -} - -/// Export timestamps are microseconds; daemon envelopes use milliseconds. -#[derive(Clone, Copy, Deserialize)] -#[serde(transparent)] -pub(crate) struct UnixMicros(i64); -impl UnixMicros { - pub fn millis(self) -> i64 { - self.0 / 1_000 - } -} -#[derive(Deserialize)] -pub(crate) struct ExportRecord { - pub recorded_at: Option, - pub envelope: Option, -} -#[derive(Deserialize)] -pub(crate) struct NativeEnvelope { - pub recorded_at: Option, - pub payload: Option, -} -pub(crate) enum NativePayload { - Metadata { record: Option }, - RunModel { record: Option }, - Run { run_id: String, event: RunEvent }, - Task { event: Option }, - SessionEnd, - Ignored, -} -// Some retained envelopes contain non-event payloads without a kind. Select -// the schema before decoding: unknown bodies stay opaque, malformed *known* -// bodies still fail. RawValue is confined to this codec and never enters state. -impl<'de> Deserialize<'de> for NativePayload { - fn deserialize>(d: D) -> Result { - use serde_json::value::RawValue; - #[derive(Default, Deserialize)] - #[serde(rename_all = "snake_case")] - enum Kind { - Metadata, - RunModel, - Run, - Task, - SessionEnd, - #[default] - #[serde(other)] - Ignored, - } - #[derive(Deserialize)] - struct Payload { - #[serde(default)] - kind: Option, - run_id: Option, - event: Option>, - record: Option>, - } - fn decode( - value: Option>, - ) -> Result, E> { - value - .map(|raw| serde_json::from_str(raw.get()).map_err(E::custom)) - .transpose() - } - let raw = Payload::deserialize(d)?; - Ok(match raw.kind.unwrap_or_default() { - Kind::Ignored => Self::Ignored, - Kind::SessionEnd => Self::SessionEnd, - Kind::Metadata => Self::Metadata { - record: decode(raw.record)?, - }, - Kind::RunModel => Self::RunModel { - record: decode(raw.record)?, - }, - Kind::Task => Self::Task { - event: decode(raw.event)?, - }, - Kind::Run => match decode(raw.event)? { - None | Some(RunEvent::Ignored) => Self::Ignored, - Some(event) => Self::Run { - run_id: raw - .run_id - .ok_or_else(|| serde::de::Error::missing_field("run_id"))?, - event, - }, - }, - }) - } -} -#[derive(Clone, Default, Deserialize)] -pub(crate) struct ExportMetadata { - pub model_id: Option, - pub provider_id: Option, - pub workspace_root: Option, -} -#[derive(Clone, Deserialize)] -pub(crate) struct RunModelRecord { - pub run_stream: RunStream, - #[serde(flatten)] - pub metadata: ExportMetadata, -} -#[derive(Clone, Deserialize)] -pub(crate) struct RunStream { - pub id: String, -} -#[derive(Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub(crate) enum RunEvent { - Started { - prompt: Option, - }, - ModelInputTraceRecorded { - request_record_id: String, - model_step: Option, - bounded: Option, - }, - ModelResponseCreated { - response_id: Option, - }, - ModelCompleted { - usage: Option, - }, - AssistantToolCallsCommitted { - tool_calls: Vec, - response_id: Option, - }, - ToolResultBatchCommitted { - results: Vec, - }, - ModelFailureTerminalIntent { - reason: Option, - }, - // Resource samples are not provider token usage. Their unused body is skipped. - ResourceUsageSampled, - AssistantMessageCommitted { - text: String, - response_id: Option, - }, - Terminal { - terminal: String, - reason: Option, - }, - #[serde(other)] - Ignored, -} -#[derive(Deserialize)] -pub(crate) struct ExportToolCall { - pub call_id: String, - pub name: String, - pub args: Option, -} -#[derive(Deserialize)] -pub(crate) struct ExportToolResult { - pub tool_call_id: String, - pub text: Option, -} -#[derive(Deserialize)] -pub(crate) struct TaskEvent { - #[serde(default)] - pub kind: TaskEventKind, - pub task_id: Option, - pub idempotency_key: Option, - pub origin: Option, - pub reason: Option, -} -#[derive(Default, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum TaskEventKind { - Scheduled, - Started, - Completed, - Failed, - #[serde(alias = "canceled")] - Cancelled, - Rejected, - #[default] - #[serde(other)] - Ignored, -} -#[derive(Deserialize)] -pub(crate) struct TaskOrigin { - pub tool_call_id: Option, -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - #[test] - fn non_event_payloads_and_future_records_are_ignored_but_known_records_are_checked() { - for payload in [ - json!({"record":{"future":true}}), - json!({"kind":null,"record":{"future":true}}), - json!({"kind":"future_payload","event":{"future":true}}), - json!({"kind":"run","event":{"kind":"future_event"}}), - json!({"kind":"run"}), - ] { - assert!(matches!( - serde_json::from_str::(&payload.to_string()).unwrap(), - NativePayload::Ignored - )); - } - assert!(serde_json::from_str::(r#"{"kind":"run","run_id":"r","event":{"kind":"model_completed","usage":{"input_tokens":"wrong"}}}"#).is_err()); - assert!(serde_json::from_str::( - r#"{"kind":"run","event":{"kind":"started"}}"# - ) - .is_err()); - } -} diff --git a/bt-daemon/src/muse/export_v1/export_metadata.rs b/bt-daemon/src/muse/export_v1/export_metadata.rs new file mode 100644 index 00000000..705c0d77 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/export_metadata.rs @@ -0,0 +1,8 @@ +use serde::Deserialize; + +#[derive(Clone, Default, Deserialize)] +pub(crate) struct ExportMetadata { + pub model_id: Option, + pub provider_id: Option, + pub workspace_root: Option, +} diff --git a/bt-daemon/src/muse/export_v1/export_record.rs b/bt-daemon/src/muse/export_v1/export_record.rs new file mode 100644 index 00000000..4add641f --- /dev/null +++ b/bt-daemon/src/muse/export_v1/export_record.rs @@ -0,0 +1,8 @@ +use super::{NativeEnvelope, UnixMicros}; +use serde::Deserialize; + +#[derive(Deserialize)] +pub(crate) struct ExportRecord { + pub recorded_at: Option, + pub envelope: Option, +} diff --git a/bt-daemon/src/muse/export_v1/export_tool_call.rs b/bt-daemon/src/muse/export_v1/export_tool_call.rs new file mode 100644 index 00000000..e114dd93 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/export_tool_call.rs @@ -0,0 +1,9 @@ +use crate::muse::hooks::ToolArguments; +use serde::Deserialize; + +#[derive(Deserialize)] +pub(crate) struct ExportToolCall { + pub call_id: String, + pub name: String, + pub args: Option, +} diff --git a/bt-daemon/src/muse/export_v1/export_tool_result.rs b/bt-daemon/src/muse/export_v1/export_tool_result.rs new file mode 100644 index 00000000..ebfa5a80 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/export_tool_result.rs @@ -0,0 +1,8 @@ +use crate::muse::hooks::ToolOutput; +use serde::Deserialize; + +#[derive(Deserialize)] +pub(crate) struct ExportToolResult { + pub tool_call_id: String, + pub text: Option, +} diff --git a/bt-daemon/src/muse/export_v1/header.rs b/bt-daemon/src/muse/export_v1/header.rs new file mode 100644 index 00000000..ec3d9c7b --- /dev/null +++ b/bt-daemon/src/muse/export_v1/header.rs @@ -0,0 +1,11 @@ +use super::{Session, Version}; +use serde::Deserialize; + +#[derive(Deserialize)] +pub(crate) struct Header { + pub export_schema_version: u64, + pub exporter_version: Option, + pub sessions: Vec, + #[serde(default)] + pub session_terminated_abnormally: bool, +} diff --git a/bt-daemon/src/muse/export_v1/mod.rs b/bt-daemon/src/muse/export_v1/mod.rs new file mode 100644 index 00000000..f193421b --- /dev/null +++ b/bt-daemon/src/muse/export_v1/mod.rs @@ -0,0 +1,37 @@ +//! Durable export-v1 DTOs. This is a separate native schema from MSP views. + +mod export_metadata; +mod export_record; +mod export_tool_call; +mod export_tool_result; +mod header; +mod native_envelope; +mod native_payload; +mod run_event; +mod run_model_record; +mod run_stream; +mod session; +mod session_end; +mod task_event; +mod task_event_kind; +mod task_origin; +mod unix_micros; +mod version; + +pub(crate) use export_metadata::ExportMetadata; +pub(crate) use export_record::ExportRecord; +pub(crate) use export_tool_call::ExportToolCall; +pub(crate) use export_tool_result::ExportToolResult; +pub(crate) use header::Header; +pub(crate) use native_envelope::NativeEnvelope; +pub(crate) use native_payload::NativePayload; +pub(crate) use run_event::RunEvent; +pub(crate) use run_model_record::RunModelRecord; +pub(crate) use run_stream::RunStream; +pub(crate) use session::Session; +pub(crate) use session_end::SessionEnd; +pub(crate) use task_event::TaskEvent; +pub(crate) use task_event_kind::TaskEventKind; +pub(crate) use task_origin::TaskOrigin; +pub(crate) use unix_micros::UnixMicros; +pub(crate) use version::Version; diff --git a/bt-daemon/src/muse/export_v1/native_envelope.rs b/bt-daemon/src/muse/export_v1/native_envelope.rs new file mode 100644 index 00000000..4683ce61 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/native_envelope.rs @@ -0,0 +1,8 @@ +use super::{NativePayload, UnixMicros}; +use serde::Deserialize; + +#[derive(Deserialize)] +pub(crate) struct NativeEnvelope { + pub recorded_at: Option, + pub payload: Option, +} diff --git a/bt-daemon/src/muse/export_v1/native_payload.rs b/bt-daemon/src/muse/export_v1/native_payload.rs new file mode 100644 index 00000000..c63b9d87 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/native_payload.rs @@ -0,0 +1,93 @@ +use super::{ExportMetadata, RunEvent, RunModelRecord, TaskEvent}; +use serde::Deserialize; + +pub(crate) enum NativePayload { + Metadata { record: Option }, + RunModel { record: Option }, + Run { run_id: String, event: RunEvent }, + Task { event: Option }, + SessionEnd, + Ignored, +} + +impl<'de> Deserialize<'de> for NativePayload { + fn deserialize>(d: D) -> Result { + use serde_json::value::RawValue; + #[derive(Default, Deserialize)] + #[serde(rename_all = "snake_case")] + enum Kind { + Metadata, + RunModel, + Run, + Task, + SessionEnd, + #[default] + #[serde(other)] + Ignored, + } + #[derive(Deserialize)] + struct Payload { + #[serde(default)] + kind: Option, + run_id: Option, + event: Option>, + record: Option>, + } + fn decode( + value: Option>, + ) -> Result, E> { + value + .map(|raw| serde_json::from_str(raw.get()).map_err(E::custom)) + .transpose() + } + let raw = Payload::deserialize(d)?; + Ok(match raw.kind.unwrap_or_default() { + Kind::Ignored => Self::Ignored, + Kind::SessionEnd => Self::SessionEnd, + Kind::Metadata => Self::Metadata { + record: decode(raw.record)?, + }, + Kind::RunModel => Self::RunModel { + record: decode(raw.record)?, + }, + Kind::Task => Self::Task { + event: decode(raw.event)?, + }, + Kind::Run => match decode(raw.event)? { + None | Some(RunEvent::Ignored) => Self::Ignored, + Some(event) => Self::Run { + run_id: raw + .run_id + .ok_or_else(|| serde::de::Error::missing_field("run_id"))?, + event, + }, + }, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + #[test] + fn non_event_payloads_and_future_records_are_ignored_but_known_records_are_checked() { + for payload in [ + json!({"record":{"future":true}}), + json!({"kind":null,"record":{"future":true}}), + json!({"kind":"future_payload","event":{"future":true}}), + json!({"kind":"run","event":{"kind":"future_event"}}), + json!({"kind":"run"}), + ] { + assert!(matches!( + serde_json::from_str::(&payload.to_string()).unwrap(), + NativePayload::Ignored + )); + } + assert!(serde_json::from_str::(r#"{"kind":"run","run_id":"r","event":{"kind":"model_completed","usage":{"input_tokens":"wrong"}}}"#).is_err()); + assert!(serde_json::from_str::( + r#"{"kind":"run","event":{"kind":"started"}}"# + ) + .is_err()); + } +} diff --git a/bt-daemon/src/muse/export_v1/run_event.rs b/bt-daemon/src/muse/export_v1/run_event.rs new file mode 100644 index 00000000..3f0923d3 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/run_event.rs @@ -0,0 +1,45 @@ +use super::{ExportToolCall, ExportToolResult}; +use crate::muse::hooks::{ErrorDetail, InputSummary}; +use crate::muse::usage::TokenUsage; +use serde::Deserialize; + +#[derive(Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub(crate) enum RunEvent { + Started { + prompt: Option, + }, + ModelInputTraceRecorded { + request_record_id: String, + model_step: Option, + bounded: Option, + }, + ModelResponseCreated { + response_id: Option, + }, + ModelCompleted { + usage: Option, + }, + AssistantToolCallsCommitted { + tool_calls: Vec, + response_id: Option, + }, + ToolResultBatchCommitted { + results: Vec, + }, + ModelFailureTerminalIntent { + reason: Option, + }, + // Resource samples are not provider token usage. Their unused body is skipped. + ResourceUsageSampled, + AssistantMessageCommitted { + text: String, + response_id: Option, + }, + Terminal { + terminal: String, + reason: Option, + }, + #[serde(other)] + Ignored, +} diff --git a/bt-daemon/src/muse/export_v1/run_model_record.rs b/bt-daemon/src/muse/export_v1/run_model_record.rs new file mode 100644 index 00000000..819822c1 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/run_model_record.rs @@ -0,0 +1,9 @@ +use super::{ExportMetadata, RunStream}; +use serde::Deserialize; + +#[derive(Clone, Deserialize)] +pub(crate) struct RunModelRecord { + pub run_stream: RunStream, + #[serde(flatten)] + pub metadata: ExportMetadata, +} diff --git a/bt-daemon/src/muse/export_v1/run_stream.rs b/bt-daemon/src/muse/export_v1/run_stream.rs new file mode 100644 index 00000000..a6a0ed2d --- /dev/null +++ b/bt-daemon/src/muse/export_v1/run_stream.rs @@ -0,0 +1,6 @@ +use serde::Deserialize; + +#[derive(Clone, Deserialize)] +pub(crate) struct RunStream { + pub id: String, +} diff --git a/bt-daemon/src/muse/export_v1/session.rs b/bt-daemon/src/muse/export_v1/session.rs new file mode 100644 index 00000000..5c620a05 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/session.rs @@ -0,0 +1,10 @@ +use super::SessionEnd; +use serde::Deserialize; + +#[derive(Clone, Deserialize)] +pub(crate) struct Session { + pub session_id: String, + pub trajectory_id: Option, + pub root_session_id: Option, + pub session_end: Option, +} diff --git a/bt-daemon/src/muse/export_v1/session_end.rs b/bt-daemon/src/muse/export_v1/session_end.rs new file mode 100644 index 00000000..83148729 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/session_end.rs @@ -0,0 +1,6 @@ +use serde::Deserialize; + +#[derive(Clone, Deserialize)] +pub(crate) struct SessionEnd { + pub exit_reason: Option, +} diff --git a/bt-daemon/src/muse/export_v1/task_event.rs b/bt-daemon/src/muse/export_v1/task_event.rs new file mode 100644 index 00000000..b5d0a63f --- /dev/null +++ b/bt-daemon/src/muse/export_v1/task_event.rs @@ -0,0 +1,12 @@ +use super::{TaskEventKind, TaskOrigin}; +use serde::Deserialize; + +#[derive(Deserialize)] +pub(crate) struct TaskEvent { + #[serde(default)] + pub kind: TaskEventKind, + pub task_id: Option, + pub idempotency_key: Option, + pub origin: Option, + pub reason: Option, +} diff --git a/bt-daemon/src/muse/export_v1/task_event_kind.rs b/bt-daemon/src/muse/export_v1/task_event_kind.rs new file mode 100644 index 00000000..5e6475c9 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/task_event_kind.rs @@ -0,0 +1,16 @@ +use serde::Deserialize; + +#[derive(Default, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum TaskEventKind { + Scheduled, + Started, + Completed, + Failed, + #[serde(alias = "canceled")] + Cancelled, + Rejected, + #[default] + #[serde(other)] + Ignored, +} diff --git a/bt-daemon/src/muse/export_v1/task_origin.rs b/bt-daemon/src/muse/export_v1/task_origin.rs new file mode 100644 index 00000000..20b3a603 --- /dev/null +++ b/bt-daemon/src/muse/export_v1/task_origin.rs @@ -0,0 +1,6 @@ +use serde::Deserialize; + +#[derive(Deserialize)] +pub(crate) struct TaskOrigin { + pub tool_call_id: Option, +} diff --git a/bt-daemon/src/muse/export_v1/unix_micros.rs b/bt-daemon/src/muse/export_v1/unix_micros.rs new file mode 100644 index 00000000..cf9f91ea --- /dev/null +++ b/bt-daemon/src/muse/export_v1/unix_micros.rs @@ -0,0 +1,12 @@ +use serde::Deserialize; + +/// Export timestamps are microseconds; daemon envelopes use milliseconds. +#[derive(Clone, Copy, Deserialize)] +#[serde(transparent)] +pub(crate) struct UnixMicros(i64); + +impl UnixMicros { + pub fn millis(self) -> i64 { + self.0 / 1_000 + } +} diff --git a/bt-daemon/src/muse/export_v1/version.rs b/bt-daemon/src/muse/export_v1/version.rs new file mode 100644 index 00000000..6dbb12ef --- /dev/null +++ b/bt-daemon/src/muse/export_v1/version.rs @@ -0,0 +1,16 @@ +use serde::Deserialize; + +#[derive(Deserialize)] +#[serde(untagged)] +pub(crate) enum Version { + String(String), + Object { semver: String }, +} + +impl Version { + pub(crate) fn into_string(self) -> String { + match self { + Self::String(value) | Self::Object { semver: value } => value, + } + } +} diff --git a/bt-daemon/src/muse/hooks.rs b/bt-daemon/src/muse/hooks.rs deleted file mode 100644 index 287ade17..00000000 --- a/bt-daemon/src/muse/hooks.rs +++ /dev/null @@ -1,304 +0,0 @@ -//! Hook wire DTOs shared by live decoding and export synthesis. Unknown events -//! are ignored; known events decode once before any tracing policy executes. -use super::ids::{RequestId, ToolCallId, TurnId}; -pub(crate) use super::messages::*; -pub(crate) use super::outcome::*; -use super::usage::{TokenUsage, UsageScope}; -use crate::json::Field; -use crate::wire::Envelope; -use serde::{Deserialize, Deserializer, Serialize}; -use serde_json::Value; - -macro_rules! hook_events { - ($($name:ident($body:ty)),+ $(,)?) => { - #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] - pub(crate) enum HookName { $($name),+ } - impl HookName { - pub const ALL: &'static [Self] = &[$(Self::$name),+]; - pub fn as_str(self) -> &'static str { match self { $(Self::$name => stringify!($name)),+ } } - pub fn parse(name: &str) -> Option { match name { - $(stringify!($name) => Some(Self::$name),)+ - "ToolUseStart" => Some(Self::PreToolUse), - _ => None, - }} - } - #[derive(Debug, Clone)] - pub(crate) enum MuseEvent { $($name(Hook<$body>)),+ } - impl MuseEvent { - pub fn name(&self) -> HookName { match self { $(Self::$name(_) => HookName::$name),+ } } - pub fn context(&self) -> &HookContext { match self { $(Self::$name(hook) => &hook.context),+ } } - pub fn payload(&self) -> serde_json::Result { match self { $(Self::$name(hook) => serde_json::to_value(hook)),+ } } - pub fn decode(envelope: &Envelope) -> serde_json::Result> { - Ok(match HookName::parse(&envelope.event) { - $(Some(HookName::$name) => Some(Self::$name(serde_json::from_value(envelope.payload.clone())?)),)+ - None => None, - }) - } - } - } -} -hook_events! { - SessionStart(Empty), UserPromptSubmit(PromptSubmitted), - PreToolUse(ToolStarted), PermissionRequest(PermissionObserved), - PostToolUse(ToolFinished), PostToolUseFailure(ToolFinished), - PostToolBatch(ToolBatchFinished), PreLLMCall(ModelStarted), PostLLMCall(ModelFinished), - PreCompact(Compaction), PostCompact(Compaction), - SubagentStart(SubagentStarted), SubagentStop(SubagentFinished), - Stop(TurnFinished), StopFailure(TurnFinished), SessionEnd(SessionFinished), - Notification(NotificationObserved), -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct Empty {} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct Hook { - #[serde(flatten)] - pub context: HookContext, - #[serde(flatten)] - pub body: B, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct HookContext { - #[serde(skip_serializing_if = "Option::is_none")] - pub session_id: Option, - #[serde( - default, - deserialize_with = "optional_id", - skip_serializing_if = "Option::is_none" - )] - pub turn_id: Option, - #[serde( - default, - deserialize_with = "optional_id", - skip_serializing_if = "Option::is_none" - )] - pub request_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub transcript_path: Option, - #[serde(flatten)] - pub session: SessionMetadata, -} -impl HookContext { - pub fn turn(&self) -> Option<&str> { - self.turn_id.as_deref().filter(|s| !s.is_empty()) - } - pub fn request(&self) -> Option<&str> { - self.request_id.as_deref().filter(|s| !s.is_empty()) - } -} -// The native optional identifiers have historically tolerated non-string values. -// Keep this compatibility at decoding, never inside correlation logic. -fn optional_id<'de, D: Deserializer<'de>, T: From>(d: D) -> Result, D::Error> { - #[derive(Deserialize)] - #[serde(untagged)] - enum Id { - Text(String), - Other(serde::de::IgnoredAny), - } - Ok(match Id::deserialize(d)? { - Id::Text(s) if !s.is_empty() => Some(T::from(s)), - _ => None, - }) -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct SessionMetadata { - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub cwd: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub model: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub provider: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub permission_mode: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub trajectory_id: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub root_session_id: Field, -} -impl SessionMetadata { - pub fn update(&mut self, incoming: &Self) { - macro_rules! update { ($($field:ident),+) => { $(if !incoming.$field.is_missing() { self.$field.clone_from(&incoming.$field); })+ }; } - update!( - cwd, - model, - provider, - permission_mode, - trajectory_id, - root_session_id - ); - } -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct PromptSubmitted { - pub prompt: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub image_content: Option, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct ModelDetails { - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub step: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub attempt: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub message_count: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub tool_count: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub options: Field, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct ModelStarted { - #[serde(flatten)] - pub details: ModelDetails, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub request_record_id: Field, - pub messages: Option>, - pub tools: Option>, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub input_summary: Field, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct ModelFinished { - pub usage: Option, - #[serde(default)] - pub usage_scope: UsageScope, - pub output_text_preview: Option, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub response_id: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub finish_reason: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub tool_call_count: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub options: Field, - #[serde(flatten)] - pub outcome: NativeOutcome, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct ToolStarted { - #[serde(default, deserialize_with = "optional_id")] - pub tool_use_id: Option, - pub tool_name: Option, - pub tool_input: Option, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct ToolFinished { - #[serde(flatten)] - pub tool: ToolStarted, - pub tool_response: Option, - pub duration_ms: Option, - #[serde(flatten)] - pub outcome: NativeOutcome, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct ToolBatchFinished { - #[serde(default)] - pub tool_calls: Vec, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct PermissionObserved { - pub tool_name: Option, - pub tool_input: Option, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct NotificationObserved { - pub notification_type: Option, - pub title: Option, - pub message: Option, - #[serde(flatten)] - pub tool: PermissionObserved, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct SubagentStarted { - pub child_session_id: Option, - pub subagent_id: Option, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct SubagentFinished { - #[serde(flatten)] - pub child: SubagentStarted, - pub last_assistant_message: Option, - #[serde(flatten)] - pub outcome: NativeOutcome, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct Compaction { - pub trigger: Option, - #[serde(flatten)] - pub outcome: NativeOutcome, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct TurnFinished { - pub last_assistant_message: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub terminal: Option, - #[serde(flatten)] - pub outcome: NativeOutcome, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct SessionFinished { - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub reason: Field, - #[serde(flatten)] - pub outcome: NativeOutcome, -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - fn envelope(name: &str, payload: Value) -> Envelope { - Envelope { - source: "muse".into(), - session_id: "session".into(), - event: name.into(), - ts_ms: 100, - source_version: None, - plugin_version: None, - managed_run_id: None, - capture: None, - route: None, - config: None, - payload, - } - } - #[test] - fn all_hook_names_decode_and_optional_ids_remain_tolerant() { - for name in HookName::ALL { - let e = envelope( - name.as_str(), - json!({"turn_id":{},"request_id":4,"future_field":true}), - ); - let decoded = MuseEvent::decode(&e).unwrap().unwrap(); - assert_eq!(decoded.name(), *name); - assert_eq!(decoded.context().turn(), None); - assert_eq!(decoded.context().request(), None); - } - assert!(matches!( - MuseEvent::decode(&envelope("ToolUseStart", json!({}))).unwrap(), - Some(MuseEvent::PreToolUse(_)) - )); - assert!(MuseEvent::decode(&envelope("FutureEvent", json!({}))) - .unwrap() - .is_none()); - assert!(MuseEvent::decode(&envelope("PreLLMCall", json!({"step":"wrong"}))).is_err()); - } - #[test] - fn known_content_is_validated_and_unknown_content_is_lossless() { - let block = json!({"type":"image","source":{"url":"example"},"future":true}); - let decoded: ContentBlock = serde_json::from_value(block.clone()).unwrap(); - assert_eq!(serde_json::to_value(decoded).unwrap(), block); - assert!(serde_json::from_value::(json!({"type":"text","text":42})).is_err()); - let args = ToolArguments::Encoded("{\"x\":1}".into()); - assert_eq!(args.input().0, json!({"x":1})); - assert_eq!( - ToolArguments::Encoded("invalid json".into()).input().0, - json!("invalid json") - ); - } -} diff --git a/bt-daemon/src/muse/hooks/compaction.rs b/bt-daemon/src/muse/hooks/compaction.rs new file mode 100644 index 00000000..425fd552 --- /dev/null +++ b/bt-daemon/src/muse/hooks/compaction.rs @@ -0,0 +1,9 @@ +use super::NativeOutcome; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct Compaction { + pub trigger: Option, + #[serde(flatten)] + pub outcome: NativeOutcome, +} diff --git a/bt-daemon/src/muse/hooks/empty.rs b/bt-daemon/src/muse/hooks/empty.rs new file mode 100644 index 00000000..22641520 --- /dev/null +++ b/bt-daemon/src/muse/hooks/empty.rs @@ -0,0 +1,4 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct Empty {} diff --git a/bt-daemon/src/muse/hooks/events.rs b/bt-daemon/src/muse/hooks/events.rs new file mode 100644 index 00000000..99fe509d --- /dev/null +++ b/bt-daemon/src/muse/hooks/events.rs @@ -0,0 +1,43 @@ +use super::*; +use crate::wire::Envelope; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +macro_rules! hook_events { + ($($name:ident($body:ty)),+ $(,)?) => { + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] + pub(crate) enum HookName { $($name),+ } + impl HookName { + pub const ALL: &'static [Self] = &[$(Self::$name),+]; + pub fn as_str(self) -> &'static str { match self { $(Self::$name => stringify!($name)),+ } } + pub fn parse(name: &str) -> Option { match name { + $(stringify!($name) => Some(Self::$name),)+ + "ToolUseStart" => Some(Self::PreToolUse), + _ => None, + }} + } + #[derive(Debug, Clone)] + pub(crate) enum MuseEvent { $($name(Hook<$body>)),+ } + impl MuseEvent { + pub fn name(&self) -> HookName { match self { $(Self::$name(_) => HookName::$name),+ } } + pub fn context(&self) -> &HookContext { match self { $(Self::$name(hook) => &hook.context),+ } } + pub fn payload(&self) -> serde_json::Result { match self { $(Self::$name(hook) => serde_json::to_value(hook)),+ } } + pub fn decode(envelope: &Envelope) -> serde_json::Result> { + Ok(match HookName::parse(&envelope.event) { + $(Some(HookName::$name) => Some(Self::$name(serde_json::from_value(envelope.payload.clone())?)),)+ + None => None, + }) + } + } + } +} +hook_events! { + SessionStart(Empty), UserPromptSubmit(PromptSubmitted), + PreToolUse(ToolStarted), PermissionRequest(PermissionObserved), + PostToolUse(ToolFinished), PostToolUseFailure(ToolFinished), + PostToolBatch(ToolBatchFinished), PreLLMCall(ModelStarted), PostLLMCall(ModelFinished), + PreCompact(Compaction), PostCompact(Compaction), + SubagentStart(SubagentStarted), SubagentStop(SubagentFinished), + Stop(TurnFinished), StopFailure(TurnFinished), SessionEnd(SessionFinished), + Notification(NotificationObserved), +} diff --git a/bt-daemon/src/muse/hooks/hook.rs b/bt-daemon/src/muse/hooks/hook.rs new file mode 100644 index 00000000..92429b11 --- /dev/null +++ b/bt-daemon/src/muse/hooks/hook.rs @@ -0,0 +1,10 @@ +use super::HookContext; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct Hook { + #[serde(flatten)] + pub context: HookContext, + #[serde(flatten)] + pub body: B, +} diff --git a/bt-daemon/src/muse/hooks/hook_context.rs b/bt-daemon/src/muse/hooks/hook_context.rs new file mode 100644 index 00000000..e30e4122 --- /dev/null +++ b/bt-daemon/src/muse/hooks/hook_context.rs @@ -0,0 +1,37 @@ +use super::optional_id; +use super::SessionMetadata; +use crate::muse::ids::{RequestId, TurnId}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct HookContext { + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, + #[serde( + default, + deserialize_with = "optional_id", + skip_serializing_if = "Option::is_none" + )] + pub turn_id: Option, + #[serde( + default, + deserialize_with = "optional_id", + skip_serializing_if = "Option::is_none" + )] + pub request_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub transcript_path: Option, + #[serde(flatten)] + pub session: SessionMetadata, +} + +impl HookContext { + pub fn turn(&self) -> Option<&str> { + self.turn_id.as_deref().filter(|s| !s.is_empty()) + } + pub fn request(&self) -> Option<&str> { + self.request_id.as_deref().filter(|s| !s.is_empty()) + } +} diff --git a/bt-daemon/src/muse/hooks/mod.rs b/bt-daemon/src/muse/hooks/mod.rs new file mode 100644 index 00000000..5837e613 --- /dev/null +++ b/bt-daemon/src/muse/hooks/mod.rs @@ -0,0 +1,65 @@ +//! Hook wire DTOs shared by live decoding and export synthesis. Unknown events +//! are ignored; known events decode once before any tracing policy executes. + +use serde::{Deserialize, Deserializer}; + +mod compaction; +mod empty; +mod hook; +mod hook_context; +mod model_details; +mod model_finished; +mod model_started; +mod notification_observed; +mod permission_observed; +mod prompt_submitted; +mod session_finished; +mod session_metadata; +mod subagent_finished; +mod subagent_started; +mod tool_batch_finished; +mod tool_finished; +mod tool_started; +mod turn_finished; + +pub(crate) use compaction::Compaction; +pub(crate) use empty::Empty; +pub(crate) use hook::Hook; +pub(crate) use hook_context::HookContext; +pub(crate) use model_details::ModelDetails; +pub(crate) use model_finished::ModelFinished; +pub(crate) use model_started::ModelStarted; +pub(crate) use notification_observed::NotificationObserved; +pub(crate) use permission_observed::PermissionObserved; +pub(crate) use prompt_submitted::PromptSubmitted; +pub(crate) use session_finished::SessionFinished; +pub(crate) use session_metadata::SessionMetadata; +pub(crate) use subagent_finished::SubagentFinished; +pub(crate) use subagent_started::SubagentStarted; +pub(crate) use tool_batch_finished::ToolBatchFinished; +pub(crate) use tool_finished::ToolFinished; +pub(crate) use tool_started::ToolStarted; +pub(crate) use turn_finished::TurnFinished; + +pub(crate) use super::messages::*; +pub(crate) use super::outcome::*; +mod events; +pub(crate) use events::{HookName, MuseEvent}; + +// The native optional identifiers have historically tolerated non-string values. +// Keep this compatibility at decoding, never inside correlation logic. +fn optional_id<'de, D: Deserializer<'de>, T: From>(d: D) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Id { + Text(String), + Other(serde::de::IgnoredAny), + } + Ok(match Id::deserialize(d)? { + Id::Text(s) if !s.is_empty() => Some(T::from(s)), + _ => None, + }) +} + +#[cfg(test)] +mod tests; diff --git a/bt-daemon/src/muse/hooks/model_details.rs b/bt-daemon/src/muse/hooks/model_details.rs new file mode 100644 index 00000000..c37f483c --- /dev/null +++ b/bt-daemon/src/muse/hooks/model_details.rs @@ -0,0 +1,17 @@ +use super::ProviderOptions; +use crate::json::Field; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct ModelDetails { + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub step: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub attempt: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub message_count: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub tool_count: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub options: Field, +} diff --git a/bt-daemon/src/muse/hooks/model_finished.rs b/bt-daemon/src/muse/hooks/model_finished.rs new file mode 100644 index 00000000..b8f00c9f --- /dev/null +++ b/bt-daemon/src/muse/hooks/model_finished.rs @@ -0,0 +1,22 @@ +use super::{ModelOutput, NativeOutcome, ProviderOptions}; +use crate::json::Field; +use crate::muse::usage::{TokenUsage, UsageScope}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct ModelFinished { + pub usage: Option, + #[serde(default)] + pub usage_scope: UsageScope, + pub output_text_preview: Option, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub response_id: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub finish_reason: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub tool_call_count: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub options: Field, + #[serde(flatten)] + pub outcome: NativeOutcome, +} diff --git a/bt-daemon/src/muse/hooks/model_started.rs b/bt-daemon/src/muse/hooks/model_started.rs new file mode 100644 index 00000000..252e56e6 --- /dev/null +++ b/bt-daemon/src/muse/hooks/model_started.rs @@ -0,0 +1,16 @@ +use super::ModelDetails; +use super::{InputSummary, NativeMessage, ToolDescription}; +use crate::json::Field; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct ModelStarted { + #[serde(flatten)] + pub details: ModelDetails, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub request_record_id: Field, + pub messages: Option>, + pub tools: Option>, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub input_summary: Field, +} diff --git a/bt-daemon/src/muse/hooks/notification_observed.rs b/bt-daemon/src/muse/hooks/notification_observed.rs new file mode 100644 index 00000000..6651a906 --- /dev/null +++ b/bt-daemon/src/muse/hooks/notification_observed.rs @@ -0,0 +1,11 @@ +use super::PermissionObserved; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct NotificationObserved { + pub notification_type: Option, + pub title: Option, + pub message: Option, + #[serde(flatten)] + pub tool: PermissionObserved, +} diff --git a/bt-daemon/src/muse/hooks/permission_observed.rs b/bt-daemon/src/muse/hooks/permission_observed.rs new file mode 100644 index 00000000..9e8cc141 --- /dev/null +++ b/bt-daemon/src/muse/hooks/permission_observed.rs @@ -0,0 +1,8 @@ +use super::ToolInput; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct PermissionObserved { + pub tool_name: Option, + pub tool_input: Option, +} diff --git a/bt-daemon/src/muse/hooks/prompt_submitted.rs b/bt-daemon/src/muse/hooks/prompt_submitted.rs new file mode 100644 index 00000000..7a5728a5 --- /dev/null +++ b/bt-daemon/src/muse/hooks/prompt_submitted.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct PromptSubmitted { + pub prompt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub image_content: Option, +} diff --git a/bt-daemon/src/muse/hooks/session_finished.rs b/bt-daemon/src/muse/hooks/session_finished.rs new file mode 100644 index 00000000..a6805a97 --- /dev/null +++ b/bt-daemon/src/muse/hooks/session_finished.rs @@ -0,0 +1,11 @@ +use super::{ErrorDetail, NativeOutcome}; +use crate::json::Field; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct SessionFinished { + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub reason: Field, + #[serde(flatten)] + pub outcome: NativeOutcome, +} diff --git a/bt-daemon/src/muse/hooks/session_metadata.rs b/bt-daemon/src/muse/hooks/session_metadata.rs new file mode 100644 index 00000000..64f732ea --- /dev/null +++ b/bt-daemon/src/muse/hooks/session_metadata.rs @@ -0,0 +1,32 @@ +use crate::json::Field; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct SessionMetadata { + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub cwd: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub model: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub provider: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub permission_mode: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub trajectory_id: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub root_session_id: Field, +} + +impl SessionMetadata { + pub fn update(&mut self, incoming: &Self) { + macro_rules! update { ($($field:ident),+) => { $(if !incoming.$field.is_missing() { self.$field.clone_from(&incoming.$field); })+ }; } + update!( + cwd, + model, + provider, + permission_mode, + trajectory_id, + root_session_id + ); + } +} diff --git a/bt-daemon/src/muse/hooks/subagent_finished.rs b/bt-daemon/src/muse/hooks/subagent_finished.rs new file mode 100644 index 00000000..675d9f18 --- /dev/null +++ b/bt-daemon/src/muse/hooks/subagent_finished.rs @@ -0,0 +1,12 @@ +use super::SubagentStarted; +use super::{ModelOutput, NativeOutcome}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct SubagentFinished { + #[serde(flatten)] + pub child: SubagentStarted, + pub last_assistant_message: Option, + #[serde(flatten)] + pub outcome: NativeOutcome, +} diff --git a/bt-daemon/src/muse/hooks/subagent_started.rs b/bt-daemon/src/muse/hooks/subagent_started.rs new file mode 100644 index 00000000..1c043d13 --- /dev/null +++ b/bt-daemon/src/muse/hooks/subagent_started.rs @@ -0,0 +1,7 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct SubagentStarted { + pub child_session_id: Option, + pub subagent_id: Option, +} diff --git a/bt-daemon/src/muse/hooks/tests.rs b/bt-daemon/src/muse/hooks/tests.rs new file mode 100644 index 00000000..7a2554e8 --- /dev/null +++ b/bt-daemon/src/muse/hooks/tests.rs @@ -0,0 +1,53 @@ +use super::*; +use crate::wire::Envelope; +use serde_json::json; +use serde_json::Value; +fn envelope(name: &str, payload: Value) -> Envelope { + Envelope { + source: "muse".into(), + session_id: "session".into(), + event: name.into(), + ts_ms: 100, + source_version: None, + plugin_version: None, + managed_run_id: None, + capture: None, + route: None, + config: None, + payload, + } +} +#[test] +fn all_hook_names_decode_and_optional_ids_remain_tolerant() { + for name in HookName::ALL { + let e = envelope( + name.as_str(), + json!({"turn_id":{},"request_id":4,"future_field":true}), + ); + let decoded = MuseEvent::decode(&e).unwrap().unwrap(); + assert_eq!(decoded.name(), *name); + assert_eq!(decoded.context().turn(), None); + assert_eq!(decoded.context().request(), None); + } + assert!(matches!( + MuseEvent::decode(&envelope("ToolUseStart", json!({}))).unwrap(), + Some(MuseEvent::PreToolUse(_)) + )); + assert!(MuseEvent::decode(&envelope("FutureEvent", json!({}))) + .unwrap() + .is_none()); + assert!(MuseEvent::decode(&envelope("PreLLMCall", json!({"step":"wrong"}))).is_err()); +} +#[test] +fn known_content_is_validated_and_unknown_content_is_lossless() { + let block = json!({"type":"image","source":{"url":"example"},"future":true}); + let decoded: ContentBlock = serde_json::from_value(block.clone()).unwrap(); + assert_eq!(serde_json::to_value(decoded).unwrap(), block); + assert!(serde_json::from_value::(json!({"type":"text","text":42})).is_err()); + let args = ToolArguments::Encoded("{\"x\":1}".into()); + assert_eq!(args.input().0, json!({"x":1})); + assert_eq!( + ToolArguments::Encoded("invalid json".into()).input().0, + json!("invalid json") + ); +} diff --git a/bt-daemon/src/muse/hooks/tool_batch_finished.rs b/bt-daemon/src/muse/hooks/tool_batch_finished.rs new file mode 100644 index 00000000..4dbc1cba --- /dev/null +++ b/bt-daemon/src/muse/hooks/tool_batch_finished.rs @@ -0,0 +1,8 @@ +use super::ToolFinished; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct ToolBatchFinished { + #[serde(default)] + pub tool_calls: Vec, +} diff --git a/bt-daemon/src/muse/hooks/tool_finished.rs b/bt-daemon/src/muse/hooks/tool_finished.rs new file mode 100644 index 00000000..b667356c --- /dev/null +++ b/bt-daemon/src/muse/hooks/tool_finished.rs @@ -0,0 +1,13 @@ +use super::ToolStarted; +use super::{NativeOutcome, ToolOutput}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct ToolFinished { + #[serde(flatten)] + pub tool: ToolStarted, + pub tool_response: Option, + pub duration_ms: Option, + #[serde(flatten)] + pub outcome: NativeOutcome, +} diff --git a/bt-daemon/src/muse/hooks/tool_started.rs b/bt-daemon/src/muse/hooks/tool_started.rs new file mode 100644 index 00000000..2818414c --- /dev/null +++ b/bt-daemon/src/muse/hooks/tool_started.rs @@ -0,0 +1,11 @@ +use super::{optional_id, ToolInput}; +use crate::muse::ids::ToolCallId; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct ToolStarted { + #[serde(default, deserialize_with = "optional_id")] + pub tool_use_id: Option, + pub tool_name: Option, + pub tool_input: Option, +} diff --git a/bt-daemon/src/muse/hooks/turn_finished.rs b/bt-daemon/src/muse/hooks/turn_finished.rs new file mode 100644 index 00000000..786a359e --- /dev/null +++ b/bt-daemon/src/muse/hooks/turn_finished.rs @@ -0,0 +1,11 @@ +use super::{ModelOutput, NativeOutcome}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct TurnFinished { + pub last_assistant_message: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub terminal: Option, + #[serde(flatten)] + pub outcome: NativeOutcome, +} diff --git a/bt-daemon/src/muse/messages.rs b/bt-daemon/src/muse/messages.rs deleted file mode 100644 index df702073..00000000 --- a/bt-daemon/src/muse/messages.rs +++ /dev/null @@ -1,322 +0,0 @@ -//! Native hook message and provider payload contracts. -pub(crate) use super::provider_options::ProviderOptions; -use crate::json::{Extensions, Field}; -use serde::{Deserialize, Deserializer, Serialize}; -use serde_json::Value; - -/// These values have schemas owned by the tool or provider, not by Muse tracing. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(transparent)] -pub(crate) struct ToolInput(pub Value); -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(transparent)] -pub(crate) struct ToolOutput(pub Value); -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum ModelOutput { - Text(String), - Messages(Vec), -} -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(crate) struct NativeMessage { - pub role: MessageRole, - #[serde(skip_serializing_if = "Option::is_none")] - pub content: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub tool_calls: Option>, - #[serde(skip_serializing_if = "Option::is_none")] - pub tool_call_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extensions: Extensions, -} -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(from = "String", into = "String")] -pub(crate) enum MessageRole { - System, - Developer, - User, - Assistant, - Tool, - Other(String), -} -impl From for MessageRole { - fn from(s: String) -> Self { - match s.as_str() { - "system" => Self::System, - "developer" => Self::Developer, - "user" => Self::User, - "assistant" => Self::Assistant, - "tool" => Self::Tool, - _ => Self::Other(s), - } - } -} -impl From for String { - fn from(role: MessageRole) -> Self { - match role { - MessageRole::System => "system", - MessageRole::Developer => "developer", - MessageRole::User => "user", - MessageRole::Assistant => "assistant", - MessageRole::Tool => "tool", - MessageRole::Other(s) => return s, - } - .into() - } -} -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum MessageContent { - Text(String), - Blocks(Vec), -} -/// Known content variants are validated before the unknown-content fallback. -#[derive(Debug, Clone, Serialize)] -#[serde(untagged)] -pub(crate) enum ContentBlock { - Known(KnownContentBlock), - Other { - #[serde(rename = "type")] - kind: String, - #[serde(flatten)] - fields: Extensions, - }, -} -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(tag = "type", rename_all = "snake_case")] -pub(crate) enum KnownContentBlock { - Text { - text: String, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, - }, - AssistantMessage { - text: String, - #[serde(default, skip_serializing_if = "Field::is_missing")] - provider_item_id: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - phase: Field, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, - }, - Image { - source: ImageSource, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, - }, - ImageUrl { - image_url: ImageUrl, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, - }, -} -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum MessagePhase { - Analysis, - Commentary, - FinalAnswer, - #[serde(untagged)] - Other(String), -} -impl<'de> Deserialize<'de> for ContentBlock { - fn deserialize>(d: D) -> Result { - #[derive(Deserialize)] - struct Tag { - #[serde(rename = "type")] - kind: String, - } - let value = Value::deserialize(d)?; - let tag: Tag = serde_json::from_value(value.clone()).map_err(serde::de::Error::custom)?; - if matches!( - tag.kind.as_str(), - "text" | "assistant_message" | "image" | "image_url" - ) { - serde_json::from_value(value) - .map(Self::Known) - .map_err(serde::de::Error::custom) - } else { - let mut fields: Extensions = - serde_json::from_value(value).map_err(serde::de::Error::custom)?; - fields.remove("type"); - Ok(Self::Other { - kind: tag.kind, - fields, - }) - } - } -} - -#[derive(Debug, Clone, Serialize)] -#[serde(untagged)] -pub(crate) enum ImageSource { - Base64(Base64ImageSource), - Url(UrlImageSource), - /// Future source formats survive unchanged, without becoming known data. - Other(Box), -} -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(crate) struct Base64ImageSource { - #[serde(rename = "type")] - kind: Base64Type, - media_type: String, - data: String, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, -} -#[derive(Debug, Clone, Serialize, Deserialize)] -enum Base64Type { - #[serde(rename = "base64")] - Base64, -} -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(crate) struct UrlImageSource { - url: String, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, -} -impl<'de> Deserialize<'de> for ImageSource { - fn deserialize>(d: D) -> Result { - let value = Value::deserialize(d)?; - if !value.is_object() { - return Err(serde::de::Error::custom("image source must be an object")); - } - match value.get("type").and_then(Value::as_str) { - Some("base64") => serde_json::from_value(value) - .map(Self::Base64) - .map_err(serde::de::Error::custom), - kind @ (None | Some("url")) if kind.is_some() || value.get("url").is_some() => { - serde_json::from_value(value) - .map(Self::Url) - .map_err(serde::de::Error::custom) - } - _ => serde_json::value::to_raw_value(&value) - .map(Self::Other) - .map_err(serde::de::Error::custom), - } - } -} -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum ImageUrl { - Url(String), - Detailed { - url: String, - #[serde(default, skip_serializing_if = "Field::is_missing")] - detail: Field, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extensions: Extensions, - }, -} -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub(crate) enum ImageDetail { - Auto, - Low, - High, - #[serde(untagged)] - Other(String), -} -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(crate) struct AssistantToolCall { - pub id: String, - #[serde(rename = "type")] - pub call_type: FunctionCallType, - pub function: FunctionCall, -} -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub(crate) enum FunctionCallType { - Function, -} -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(crate) struct FunctionCall { - pub name: String, - pub arguments: ToolArguments, -} -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum ToolArguments { - Encoded(String), - Json(Value), -} -impl ToolArguments { - pub fn input(&self) -> ToolInput { - ToolInput(match self { - Self::Encoded(s) => { - serde_json::from_str(s).unwrap_or_else(|_| Value::String(s.clone())) - } - Self::Json(v) => v.clone(), - }) - } -} -#[derive(Debug, Clone, Serialize, Deserialize)] -pub(crate) struct ToolDescription { - pub name: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub has_parameters: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub strict: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub parameters: Option, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extensions: Extensions, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct InputSummary { - #[serde(skip_serializing_if = "Option::is_none")] - pub request_message_count: Option, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extensions: Extensions, -} - -#[cfg(test)] -mod extension_tests { - use super::*; - use serde_json::json; - - #[test] - fn known_assistant_fields_and_image_variants_round_trip() { - for raw in [ - json!({"type":"assistant_message","text":"done","provider_item_id":null,"phase":"final_answer","future":true}), - json!({"type":"assistant_message","text":"done","phase":"future-phase"}), - json!({"type":"image","source":{"url":"https://example.com/image","future":null},"future":true}), - json!({"type":"image","source":{"type":"base64","media_type":"image/png","data":"YWJj","future":true}}), - json!({"type":"image_url","image_url":{"url":"https://example.com/image","detail":"high","future":true}}), - json!({"type":"image","source":{"type":"future","opaque":[null,42]}}), - json!({"type":"future","opaque":[null,42]}), - ] { - let parsed: ContentBlock = serde_json::from_value(raw.clone()).unwrap(); - assert_eq!(serde_json::to_value(parsed).unwrap(), raw); - } - let parsed: ContentBlock = serde_json::from_value( - json!({"type":"assistant_message","text":"done","phase":"final_answer"}), - ) - .unwrap(); - assert!(matches!( - parsed, - ContentBlock::Known(KnownContentBlock::AssistantMessage { - phase: Field::Value(MessagePhase::FinalAnswer), - .. - }) - )); - } - - #[test] - fn malformed_known_fields_cannot_hide_as_unknown_content() { - for raw in [ - json!({"type":"image","source":42}), - json!({"type":"assistant_message","text":"done","provider_item_id":42}), - json!({"type":"assistant_message","text":"done","phase":42}), - json!({"type":"image","source":{"url":42}}), - json!({"type":"image","source":{"type":"base64","media_type":"image/png","data":42}}), - json!({"type":"image_url","image_url":{"url":"example","detail":42}}), - ] { - assert!(serde_json::from_value::(raw).is_err()); - } - } -} diff --git a/bt-daemon/src/muse/messages/assistant_tool_call.rs b/bt-daemon/src/muse/messages/assistant_tool_call.rs new file mode 100644 index 00000000..423627f6 --- /dev/null +++ b/bt-daemon/src/muse/messages/assistant_tool_call.rs @@ -0,0 +1,10 @@ +use super::{FunctionCall, FunctionCallType}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct AssistantToolCall { + pub id: String, + #[serde(rename = "type")] + pub call_type: FunctionCallType, + pub function: FunctionCall, +} diff --git a/bt-daemon/src/muse/messages/base64_image_source.rs b/bt-daemon/src/muse/messages/base64_image_source.rs new file mode 100644 index 00000000..2672df7a --- /dev/null +++ b/bt-daemon/src/muse/messages/base64_image_source.rs @@ -0,0 +1,18 @@ +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct Base64ImageSource { + #[serde(rename = "type")] + kind: Base64Type, + media_type: String, + data: String, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +enum Base64Type { + #[serde(rename = "base64")] + Base64, +} diff --git a/bt-daemon/src/muse/messages/content_block.rs b/bt-daemon/src/muse/messages/content_block.rs new file mode 100644 index 00000000..0fc34838 --- /dev/null +++ b/bt-daemon/src/muse/messages/content_block.rs @@ -0,0 +1,45 @@ +use super::KnownContentBlock; +use crate::json::Extensions; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +/// Known content variants are validated before the unknown-content fallback. +#[derive(Debug, Clone, Serialize)] +#[serde(untagged)] +pub(crate) enum ContentBlock { + Known(KnownContentBlock), + Other { + #[serde(rename = "type")] + kind: String, + #[serde(flatten)] + fields: Extensions, + }, +} + +impl<'de> Deserialize<'de> for ContentBlock { + fn deserialize>(d: D) -> Result { + #[derive(Deserialize)] + struct Tag { + #[serde(rename = "type")] + kind: String, + } + let value = Value::deserialize(d)?; + let tag: Tag = serde_json::from_value(value.clone()).map_err(serde::de::Error::custom)?; + if matches!( + tag.kind.as_str(), + "text" | "assistant_message" | "image" | "image_url" + ) { + serde_json::from_value(value) + .map(Self::Known) + .map_err(serde::de::Error::custom) + } else { + let mut fields: Extensions = + serde_json::from_value(value).map_err(serde::de::Error::custom)?; + fields.remove("type"); + Ok(Self::Other { + kind: tag.kind, + fields, + }) + } + } +} diff --git a/bt-daemon/src/muse/messages/function_call.rs b/bt-daemon/src/muse/messages/function_call.rs new file mode 100644 index 00000000..e3a8b49b --- /dev/null +++ b/bt-daemon/src/muse/messages/function_call.rs @@ -0,0 +1,8 @@ +use super::ToolArguments; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct FunctionCall { + pub name: String, + pub arguments: ToolArguments, +} diff --git a/bt-daemon/src/muse/messages/function_call_type.rs b/bt-daemon/src/muse/messages/function_call_type.rs new file mode 100644 index 00000000..e058aeb6 --- /dev/null +++ b/bt-daemon/src/muse/messages/function_call_type.rs @@ -0,0 +1,7 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum FunctionCallType { + Function, +} diff --git a/bt-daemon/src/muse/messages/image_detail.rs b/bt-daemon/src/muse/messages/image_detail.rs new file mode 100644 index 00000000..5bb78853 --- /dev/null +++ b/bt-daemon/src/muse/messages/image_detail.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum ImageDetail { + Auto, + Low, + High, + #[serde(untagged)] + Other(String), +} diff --git a/bt-daemon/src/muse/messages/image_source.rs b/bt-daemon/src/muse/messages/image_source.rs new file mode 100644 index 00000000..ac1f8d10 --- /dev/null +++ b/bt-daemon/src/muse/messages/image_source.rs @@ -0,0 +1,34 @@ +use super::{Base64ImageSource, UrlImageSource}; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; + +#[derive(Debug, Clone, Serialize)] +#[serde(untagged)] +pub(crate) enum ImageSource { + Base64(Base64ImageSource), + Url(UrlImageSource), + /// Future source formats survive unchanged, without becoming known data. + Other(Box), +} + +impl<'de> Deserialize<'de> for ImageSource { + fn deserialize>(d: D) -> Result { + let value = Value::deserialize(d)?; + if !value.is_object() { + return Err(serde::de::Error::custom("image source must be an object")); + } + match value.get("type").and_then(Value::as_str) { + Some("base64") => serde_json::from_value(value) + .map(Self::Base64) + .map_err(serde::de::Error::custom), + kind @ (None | Some("url")) if kind.is_some() || value.get("url").is_some() => { + serde_json::from_value(value) + .map(Self::Url) + .map_err(serde::de::Error::custom) + } + _ => serde_json::value::to_raw_value(&value) + .map(Self::Other) + .map_err(serde::de::Error::custom), + } + } +} diff --git a/bt-daemon/src/muse/messages/image_url.rs b/bt-daemon/src/muse/messages/image_url.rs new file mode 100644 index 00000000..45e94c47 --- /dev/null +++ b/bt-daemon/src/muse/messages/image_url.rs @@ -0,0 +1,16 @@ +use super::ImageDetail; +use crate::json::{Extensions, Field}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum ImageUrl { + Url(String), + Detailed { + url: String, + #[serde(default, skip_serializing_if = "Field::is_missing")] + detail: Field, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, +} diff --git a/bt-daemon/src/muse/messages/input_summary.rs b/bt-daemon/src/muse/messages/input_summary.rs new file mode 100644 index 00000000..72779fad --- /dev/null +++ b/bt-daemon/src/muse/messages/input_summary.rs @@ -0,0 +1,10 @@ +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct InputSummary { + #[serde(skip_serializing_if = "Option::is_none")] + pub request_message_count: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extensions: Extensions, +} diff --git a/bt-daemon/src/muse/messages/known_content_block.rs b/bt-daemon/src/muse/messages/known_content_block.rs new file mode 100644 index 00000000..e356c3e9 --- /dev/null +++ b/bt-daemon/src/muse/messages/known_content_block.rs @@ -0,0 +1,32 @@ +use super::{ImageSource, ImageUrl, MessagePhase}; +use crate::json::{Extensions, Field}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum KnownContentBlock { + Text { + text: String, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, + AssistantMessage { + text: String, + #[serde(default, skip_serializing_if = "Field::is_missing")] + provider_item_id: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + phase: Field, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, + Image { + source: ImageSource, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, + ImageUrl { + image_url: ImageUrl, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, +} diff --git a/bt-daemon/src/muse/messages/message_content.rs b/bt-daemon/src/muse/messages/message_content.rs new file mode 100644 index 00000000..d4d37497 --- /dev/null +++ b/bt-daemon/src/muse/messages/message_content.rs @@ -0,0 +1,9 @@ +use super::ContentBlock; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum MessageContent { + Text(String), + Blocks(Vec), +} diff --git a/bt-daemon/src/muse/messages/message_phase.rs b/bt-daemon/src/muse/messages/message_phase.rs new file mode 100644 index 00000000..2e694801 --- /dev/null +++ b/bt-daemon/src/muse/messages/message_phase.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum MessagePhase { + Analysis, + Commentary, + FinalAnswer, + #[serde(untagged)] + Other(String), +} diff --git a/bt-daemon/src/muse/messages/message_role.rs b/bt-daemon/src/muse/messages/message_role.rs new file mode 100644 index 00000000..0688061c --- /dev/null +++ b/bt-daemon/src/muse/messages/message_role.rs @@ -0,0 +1,39 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(from = "String", into = "String")] +pub(crate) enum MessageRole { + System, + Developer, + User, + Assistant, + Tool, + Other(String), +} + +impl From for MessageRole { + fn from(s: String) -> Self { + match s.as_str() { + "system" => Self::System, + "developer" => Self::Developer, + "user" => Self::User, + "assistant" => Self::Assistant, + "tool" => Self::Tool, + _ => Self::Other(s), + } + } +} + +impl From for String { + fn from(role: MessageRole) -> Self { + match role { + MessageRole::System => "system", + MessageRole::Developer => "developer", + MessageRole::User => "user", + MessageRole::Assistant => "assistant", + MessageRole::Tool => "tool", + MessageRole::Other(s) => return s, + } + .into() + } +} diff --git a/bt-daemon/src/muse/messages/mod.rs b/bt-daemon/src/muse/messages/mod.rs new file mode 100644 index 00000000..0e29189b --- /dev/null +++ b/bt-daemon/src/muse/messages/mod.rs @@ -0,0 +1,47 @@ +//! Native hook message and provider payload contracts. +pub(crate) use super::provider_options::ProviderOptions; + +mod assistant_tool_call; +mod base64_image_source; +mod content_block; +mod function_call; +mod function_call_type; +mod image_detail; +mod image_source; +mod image_url; +mod input_summary; +mod known_content_block; +mod message_content; +mod message_phase; +mod message_role; +mod model_output; +mod native_message; +mod tool_arguments; +mod tool_description; +mod tool_input; +mod tool_output; +mod url_image_source; + +pub(crate) use assistant_tool_call::AssistantToolCall; +pub(crate) use base64_image_source::Base64ImageSource; +pub(crate) use content_block::ContentBlock; +pub(crate) use function_call::FunctionCall; +pub(crate) use function_call_type::FunctionCallType; +pub(crate) use image_detail::ImageDetail; +pub(crate) use image_source::ImageSource; +pub(crate) use image_url::ImageUrl; +pub(crate) use input_summary::InputSummary; +pub(crate) use known_content_block::KnownContentBlock; +pub(crate) use message_content::MessageContent; +pub(crate) use message_phase::MessagePhase; +pub(crate) use message_role::MessageRole; +pub(crate) use model_output::ModelOutput; +pub(crate) use native_message::NativeMessage; +pub(crate) use tool_arguments::ToolArguments; +pub(crate) use tool_description::ToolDescription; +pub(crate) use tool_input::ToolInput; +pub(crate) use tool_output::ToolOutput; +pub(crate) use url_image_source::UrlImageSource; + +#[cfg(test)] +mod tests; diff --git a/bt-daemon/src/muse/messages/model_output.rs b/bt-daemon/src/muse/messages/model_output.rs new file mode 100644 index 00000000..171816af --- /dev/null +++ b/bt-daemon/src/muse/messages/model_output.rs @@ -0,0 +1,9 @@ +use super::NativeMessage; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum ModelOutput { + Text(String), + Messages(Vec), +} diff --git a/bt-daemon/src/muse/messages/native_message.rs b/bt-daemon/src/muse/messages/native_message.rs new file mode 100644 index 00000000..b333e91f --- /dev/null +++ b/bt-daemon/src/muse/messages/native_message.rs @@ -0,0 +1,18 @@ +use super::{AssistantToolCall, MessageContent, MessageRole}; +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct NativeMessage { + pub role: MessageRole, + #[serde(skip_serializing_if = "Option::is_none")] + pub content: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_calls: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_call_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extensions: Extensions, +} diff --git a/bt-daemon/src/muse/messages/tests.rs b/bt-daemon/src/muse/messages/tests.rs new file mode 100644 index 00000000..48d94712 --- /dev/null +++ b/bt-daemon/src/muse/messages/tests.rs @@ -0,0 +1,44 @@ +use super::*; +use crate::json::Field; +use serde_json::json; + +#[test] +fn known_assistant_fields_and_image_variants_round_trip() { + for raw in [ + json!({"type":"assistant_message","text":"done","provider_item_id":null,"phase":"final_answer","future":true}), + json!({"type":"assistant_message","text":"done","phase":"future-phase"}), + json!({"type":"image","source":{"url":"https://example.com/image","future":null},"future":true}), + json!({"type":"image","source":{"type":"base64","media_type":"image/png","data":"YWJj","future":true}}), + json!({"type":"image_url","image_url":{"url":"https://example.com/image","detail":"high","future":true}}), + json!({"type":"image","source":{"type":"future","opaque":[null,42]}}), + json!({"type":"future","opaque":[null,42]}), + ] { + let parsed: ContentBlock = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), raw); + } + let parsed: ContentBlock = serde_json::from_value( + json!({"type":"assistant_message","text":"done","phase":"final_answer"}), + ) + .unwrap(); + assert!(matches!( + parsed, + ContentBlock::Known(KnownContentBlock::AssistantMessage { + phase: Field::Value(MessagePhase::FinalAnswer), + .. + }) + )); +} + +#[test] +fn malformed_known_fields_cannot_hide_as_unknown_content() { + for raw in [ + json!({"type":"image","source":42}), + json!({"type":"assistant_message","text":"done","provider_item_id":42}), + json!({"type":"assistant_message","text":"done","phase":42}), + json!({"type":"image","source":{"url":42}}), + json!({"type":"image","source":{"type":"base64","media_type":"image/png","data":42}}), + json!({"type":"image_url","image_url":{"url":"example","detail":42}}), + ] { + assert!(serde_json::from_value::(raw).is_err()); + } +} diff --git a/bt-daemon/src/muse/messages/tool_arguments.rs b/bt-daemon/src/muse/messages/tool_arguments.rs new file mode 100644 index 00000000..648d148f --- /dev/null +++ b/bt-daemon/src/muse/messages/tool_arguments.rs @@ -0,0 +1,21 @@ +use super::ToolInput; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum ToolArguments { + Encoded(String), + Json(Value), +} + +impl ToolArguments { + pub fn input(&self) -> ToolInput { + ToolInput(match self { + Self::Encoded(s) => { + serde_json::from_str(s).unwrap_or_else(|_| Value::String(s.clone())) + } + Self::Json(v) => v.clone(), + }) + } +} diff --git a/bt-daemon/src/muse/messages/tool_description.rs b/bt-daemon/src/muse/messages/tool_description.rs new file mode 100644 index 00000000..5c05997a --- /dev/null +++ b/bt-daemon/src/muse/messages/tool_description.rs @@ -0,0 +1,18 @@ +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct ToolDescription { + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub has_parameters: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub strict: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub parameters: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extensions: Extensions, +} diff --git a/bt-daemon/src/muse/messages/tool_input.rs b/bt-daemon/src/muse/messages/tool_input.rs new file mode 100644 index 00000000..556a875a --- /dev/null +++ b/bt-daemon/src/muse/messages/tool_input.rs @@ -0,0 +1,7 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// These values have schemas owned by the tool or provider, not by Muse tracing. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(transparent)] +pub(crate) struct ToolInput(pub Value); diff --git a/bt-daemon/src/muse/messages/tool_output.rs b/bt-daemon/src/muse/messages/tool_output.rs new file mode 100644 index 00000000..273bcdec --- /dev/null +++ b/bt-daemon/src/muse/messages/tool_output.rs @@ -0,0 +1,6 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(transparent)] +pub(crate) struct ToolOutput(pub Value); diff --git a/bt-daemon/src/muse/messages/url_image_source.rs b/bt-daemon/src/muse/messages/url_image_source.rs new file mode 100644 index 00000000..0c9e9b9c --- /dev/null +++ b/bt-daemon/src/muse/messages/url_image_source.rs @@ -0,0 +1,9 @@ +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct UrlImageSource { + url: String, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, +} diff --git a/bt-daemon/src/muse/outcome.rs b/bt-daemon/src/muse/outcome.rs deleted file mode 100644 index 94948fb1..00000000 --- a/bt-daemon/src/muse/outcome.rs +++ /dev/null @@ -1,134 +0,0 @@ -//! Native operation outcomes, including open future statuses. -use crate::json::Field; -use serde::{Deserialize, Serialize}; -use serde_json::Value; - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum ErrorDetail { - Text(String), - Structured(Value), -} -impl ErrorDetail { - pub fn render(&self) -> Option { - match self { - Self::Text(s) => (!s.is_empty()).then(|| s.clone()), - Self::Structured(Value::Null) => None, - Self::Structured(value) => Some(value.to_string()), - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(from = "String", into = "String")] -pub(crate) enum OperationStatus { - Success, - Completed, - ToolCalls, - Stop, - Failed, - Failure, - Error, - Cancelled, - Canceled, - Interrupted, - Timeout, - TimedOut, - Denied, - Rejected, - Other(String), -} -impl From for OperationStatus { - fn from(s: String) -> Self { - match s.as_str() { - "success" => Self::Success, - "completed" => Self::Completed, - "tool_calls" => Self::ToolCalls, - "stop" => Self::Stop, - "failed" => Self::Failed, - "failure" => Self::Failure, - "error" => Self::Error, - "cancelled" => Self::Cancelled, - "canceled" => Self::Canceled, - "interrupted" => Self::Interrupted, - "timeout" => Self::Timeout, - "timed_out" => Self::TimedOut, - "denied" => Self::Denied, - "rejected" => Self::Rejected, - _ => Self::Other(s), - } - } -} -impl From for String { - fn from(s: OperationStatus) -> Self { - match s { - OperationStatus::Success => "success", - OperationStatus::Completed => "completed", - OperationStatus::ToolCalls => "tool_calls", - OperationStatus::Stop => "stop", - OperationStatus::Failed => "failed", - OperationStatus::Failure => "failure", - OperationStatus::Error => "error", - OperationStatus::Cancelled => "cancelled", - OperationStatus::Canceled => "canceled", - OperationStatus::Interrupted => "interrupted", - OperationStatus::Timeout => "timeout", - OperationStatus::TimedOut => "timed_out", - OperationStatus::Denied => "denied", - OperationStatus::Rejected => "rejected", - OperationStatus::Other(s) => return s, - } - .into() - } -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct NativeOutcome { - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub status: Field, - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub error_details: Option, -} -impl NativeOutcome { - pub fn error_message(&self) -> Option { - let error = self - .error - .as_ref() - .and_then(ErrorDetail::render) - .or_else(|| { - self.status - .as_ref() - .filter(|s| { - matches!( - s, - OperationStatus::Failed - | OperationStatus::Failure - | OperationStatus::Error - | OperationStatus::Canceled - | OperationStatus::TimedOut - | OperationStatus::Cancelled - | OperationStatus::Interrupted - | OperationStatus::Timeout - | OperationStatus::Denied - | OperationStatus::Rejected - ) - }) - .map(|s| format!("Muse operation {}", String::from(s.clone()))) - }); - match ( - error, - self.error_details.as_ref().and_then(ErrorDetail::render), - ) { - (Some(error), Some(details)) => Some(format!("{error}: {details}")), - (Some(error), None) => Some(error), - (None, details) => details, - } - } -} -#[derive(Debug, Clone, PartialEq)] -pub(crate) enum ToolOutcome { - Success, - Failure(String), - Unknown, -} diff --git a/bt-daemon/src/muse/outcome/error_detail.rs b/bt-daemon/src/muse/outcome/error_detail.rs new file mode 100644 index 00000000..009a4545 --- /dev/null +++ b/bt-daemon/src/muse/outcome/error_detail.rs @@ -0,0 +1,19 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum ErrorDetail { + Text(String), + Structured(Value), +} + +impl ErrorDetail { + pub fn render(&self) -> Option { + match self { + Self::Text(s) => (!s.is_empty()).then(|| s.clone()), + Self::Structured(Value::Null) => None, + Self::Structured(value) => Some(value.to_string()), + } + } +} diff --git a/bt-daemon/src/muse/outcome/mod.rs b/bt-daemon/src/muse/outcome/mod.rs new file mode 100644 index 00000000..89bad9f6 --- /dev/null +++ b/bt-daemon/src/muse/outcome/mod.rs @@ -0,0 +1,11 @@ +//! Native operation outcomes, including open future statuses. + +mod error_detail; +mod native_outcome; +mod operation_status; +mod tool_outcome; + +pub(crate) use error_detail::ErrorDetail; +pub(crate) use native_outcome::NativeOutcome; +pub(crate) use operation_status::OperationStatus; +pub(crate) use tool_outcome::ToolOutcome; diff --git a/bt-daemon/src/muse/outcome/native_outcome.rs b/bt-daemon/src/muse/outcome/native_outcome.rs new file mode 100644 index 00000000..ae165fc0 --- /dev/null +++ b/bt-daemon/src/muse/outcome/native_outcome.rs @@ -0,0 +1,36 @@ +use super::{ErrorDetail, OperationStatus}; +use crate::json::Field; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct NativeOutcome { + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub status: Field, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error_details: Option, +} + +impl NativeOutcome { + pub fn error_message(&self) -> Option { + let error = self + .error + .as_ref() + .and_then(ErrorDetail::render) + .or_else(|| { + self.status + .as_ref() + .filter(|status| status.is_failure()) + .map(|s| format!("Muse operation {}", String::from(s.clone()))) + }); + match ( + error, + self.error_details.as_ref().and_then(ErrorDetail::render), + ) { + (Some(error), Some(details)) => Some(format!("{error}: {details}")), + (Some(error), None) => Some(error), + (None, details) => details, + } + } +} diff --git a/bt-daemon/src/muse/outcome/operation_status.rs b/bt-daemon/src/muse/outcome/operation_status.rs new file mode 100644 index 00000000..842a3432 --- /dev/null +++ b/bt-daemon/src/muse/outcome/operation_status.rs @@ -0,0 +1,84 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(from = "String", into = "String")] +pub(crate) enum OperationStatus { + Success, + Completed, + ToolCalls, + Stop, + Failed, + Failure, + Error, + Cancelled, + Canceled, + Interrupted, + Timeout, + TimedOut, + Denied, + Rejected, + Other(String), +} + +impl From for OperationStatus { + fn from(s: String) -> Self { + match s.as_str() { + "success" => Self::Success, + "completed" => Self::Completed, + "tool_calls" => Self::ToolCalls, + "stop" => Self::Stop, + "failed" => Self::Failed, + "failure" => Self::Failure, + "error" => Self::Error, + "cancelled" => Self::Cancelled, + "canceled" => Self::Canceled, + "interrupted" => Self::Interrupted, + "timeout" => Self::Timeout, + "timed_out" => Self::TimedOut, + "denied" => Self::Denied, + "rejected" => Self::Rejected, + _ => Self::Other(s), + } + } +} + +impl From for String { + fn from(s: OperationStatus) -> Self { + match s { + OperationStatus::Success => "success", + OperationStatus::Completed => "completed", + OperationStatus::ToolCalls => "tool_calls", + OperationStatus::Stop => "stop", + OperationStatus::Failed => "failed", + OperationStatus::Failure => "failure", + OperationStatus::Error => "error", + OperationStatus::Cancelled => "cancelled", + OperationStatus::Canceled => "canceled", + OperationStatus::Interrupted => "interrupted", + OperationStatus::Timeout => "timeout", + OperationStatus::TimedOut => "timed_out", + OperationStatus::Denied => "denied", + OperationStatus::Rejected => "rejected", + OperationStatus::Other(s) => return s, + } + .into() + } +} + +impl OperationStatus { + pub fn is_failure(&self) -> bool { + matches!( + self, + Self::Failed + | Self::Failure + | Self::Error + | Self::Canceled + | Self::TimedOut + | Self::Cancelled + | Self::Interrupted + | Self::Timeout + | Self::Denied + | Self::Rejected + ) + } +} diff --git a/bt-daemon/src/muse/outcome/tool_outcome.rs b/bt-daemon/src/muse/outcome/tool_outcome.rs new file mode 100644 index 00000000..7d65c5cf --- /dev/null +++ b/bt-daemon/src/muse/outcome/tool_outcome.rs @@ -0,0 +1,6 @@ +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum ToolOutcome { + Success, + Failure(String), + Unknown, +} diff --git a/bt-daemon/src/muse/provider_options.rs b/bt-daemon/src/muse/provider_options/mod.rs similarity index 88% rename from bt-daemon/src/muse/provider_options.rs rename to bt-daemon/src/muse/provider_options/mod.rs index 7c8c0886..9d8d4608 100644 --- a/bt-daemon/src/muse/provider_options.rs +++ b/bt-daemon/src/muse/provider_options/mod.rs @@ -1,5 +1,12 @@ //! Dotted option keys observed in native Muse hooks. These options coexist: //! selecting one provider variant for the entire object would discard others. + +mod reasoning_effort; +mod thinking_mode; + +pub(crate) use reasoning_effort::ReasoningEffort; +pub(crate) use thinking_mode::ThinkingMode; + use crate::json::{Extensions, Field}; use serde::{Deserialize, Serialize}; @@ -64,31 +71,6 @@ pub(crate) struct ProviderOptions { pub extensions: Extensions, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub(crate) enum ReasoningEffort { - None, - Minimal, - Low, - Medium, - High, - Xhigh, - Max, - Ultra, - #[serde(untagged)] - Other(String), -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub(crate) enum ThinkingMode { - Enabled, - Disabled, - Adaptive, - #[serde(untagged)] - Other(String), -} - #[cfg(test)] mod tests { use super::*; diff --git a/bt-daemon/src/muse/provider_options/reasoning_effort.rs b/bt-daemon/src/muse/provider_options/reasoning_effort.rs new file mode 100644 index 00000000..1fb86d54 --- /dev/null +++ b/bt-daemon/src/muse/provider_options/reasoning_effort.rs @@ -0,0 +1,16 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum ReasoningEffort { + None, + Minimal, + Low, + Medium, + High, + Xhigh, + Max, + Ultra, + #[serde(untagged)] + Other(String), +} diff --git a/bt-daemon/src/muse/provider_options/thinking_mode.rs b/bt-daemon/src/muse/provider_options/thinking_mode.rs new file mode 100644 index 00000000..c4759f5f --- /dev/null +++ b/bt-daemon/src/muse/provider_options/thinking_mode.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum ThinkingMode { + Enabled, + Disabled, + Adaptive, + #[serde(untagged)] + Other(String), +} diff --git a/bt-daemon/src/translate/claude.rs b/bt-daemon/src/translate/claude.rs index 3722d146..66db8853 100644 --- a/bt-daemon/src/translate/claude.rs +++ b/bt-daemon/src/translate/claude.rs @@ -6,6 +6,29 @@ //! the hook timestamp; this is essential when replaying a journal against a //! transcript that already contains the completed session. +mod history_message; +mod hook_context; +mod llm_call; +mod message_history; +mod native_field; +mod parsed_transcript; +mod subagent_hook; +mod timestamp_envelope; +mod transcript_envelope; +mod transcript_tool; +mod transcript_tool_outcome; + +use hook_context::HookContext; +use llm_call::LlmCall; +use message_history::MessageHistory; +use parsed_transcript::ParsedTranscript; +use subagent_hook::SubagentHook; +#[cfg(test)] +use timestamp_envelope::parse_rfc3339_timestamp; +use timestamp_envelope::parse_timestamp_ms; +use transcript_envelope::TranscriptEnvelope; +use transcript_tool::TranscriptTool; + use super::git::GitMetadataCache; use super::recent::{RecentMap, RecentSet, RECENT_ID_CAPACITY}; use super::tool::{ @@ -15,7 +38,6 @@ use super::tool::{ use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, }; -use crate::agents::usage::SnakeCaseUsage; use crate::ids; use crate::transcript_mirror::TranscriptPayload; use crate::wire::Envelope; @@ -26,116 +48,10 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::io::{BufRead, Seek, SeekFrom}; use std::sync::Arc; -#[derive(Default, Deserialize, Serialize)] -struct HookContext { - #[serde(default, deserialize_with = "deserialize_optional_string")] - cwd: Option, - #[serde(default, deserialize_with = "deserialize_optional_string")] - transcript_path: Option, - #[serde(default, deserialize_with = "deserialize_optional_string")] - source: Option, - #[serde(default, deserialize_with = "deserialize_optional_string")] - model: Option, - #[serde(default, deserialize_with = "deserialize_optional_string")] - permission_mode: Option, - #[serde(default, deserialize_with = "deserialize_optional_effort")] - effort: Option, - #[serde(default, deserialize_with = "deserialize_optional_string")] - system_prompt: Option, -} - -#[derive(Deserialize, Serialize)] -struct SubagentHook { - #[serde(deserialize_with = "deserialize_nonempty_string")] - agent_id: String, - #[serde(default, deserialize_with = "deserialize_optional_string")] - agent_type: Option, - #[serde(default, deserialize_with = "deserialize_optional_string")] - agent_transcript_path: Option, -} - -/// Stable routing fields from one Claude transcript row. Message and tool -/// blocks intentionally remain raw because they are preserved in span I/O. -#[derive(Deserialize, Serialize)] -struct TranscriptEnvelope { - #[serde(rename = "type", default)] - kind: Option, - #[serde(default)] - subtype: Option, - #[serde(rename = "isCompactSummary", default)] - is_compact_summary: bool, -} - -/// Timestamp decoding is deliberately separate from transcript routing. A -/// future change to an unrelated routing field must not cause bounded reads to -/// consume records from after a hook's capture point. -#[derive(Deserialize, Serialize)] -struct TimestampEnvelope { - #[serde( - rename = "timestamp", - default, - deserialize_with = "deserialize_optional_timestamp" - )] - timestamp_ms: Option, -} - fn decode(value: &Value) -> Option { serde_json::from_value(value.clone()).ok() } -fn deserialize_optional_string<'de, D>(deserializer: D) -> Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - Ok(Option::::deserialize(deserializer)? - .as_ref() - .and_then(value_as_nonempty_string)) -} - -/// Claude hooks report effort as `{"level": "high"}`. -fn deserialize_optional_effort<'de, D>(deserializer: D) -> Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - Ok(Option::::deserialize(deserializer)? - .as_ref() - .and_then(|effort| effort.get("level")) - .and_then(value_as_nonempty_string)) -} - -fn deserialize_nonempty_string<'de, D>(deserializer: D) -> Result -where - D: serde::Deserializer<'de>, -{ - let value = Value::deserialize(deserializer)?; - value_as_nonempty_string(&value) - .ok_or_else(|| serde::de::Error::custom("expected a non-empty string or number")) -} - -fn deserialize_optional_timestamp<'de, D>(deserializer: D) -> Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - Ok(Option::::deserialize(deserializer)? - .as_ref() - .and_then(Value::as_str) - .and_then(parse_rfc3339_timestamp)) -} - -fn parse_rfc3339_timestamp(value: &str) -> Option { - chrono::DateTime::parse_from_rfc3339(value) - .ok() - .map(|timestamp| timestamp.timestamp_millis()) -} - -fn value_as_nonempty_string(value: &Value) -> Option { - match value { - Value::String(value) if !value.is_empty() => Some(value.clone()), - Value::Number(value) => Some(value.to_string()), - _ => None, - } -} - impl TranslatorFactory for crate::agents::Claude { fn create(&self, session_id: &str) -> Box { Box::new(ClaudeTranslator::new( @@ -191,77 +107,6 @@ enum PendingHistory { Owned(MessageHistory), } -#[derive(Default, Serialize, Deserialize)] -struct MessageHistory { - messages: Vec, - preserved_after_compaction: Vec, - fork_context_prefix: bool, -} -#[derive(Serialize, Deserialize)] -struct HistoryMessage { - value: Value, - source_uuids: Vec, -} - -impl MessageHistory { - fn active(&self) -> Vec { - self.messages - .iter() - .map(|message| message.value.clone()) - .collect() - } - - fn push(&mut self, value: Value, source_uuid: Option) -> usize { - let index = self.messages.len(); - self.messages.push(HistoryMessage { - value, - source_uuids: source_uuid.into_iter().collect(), - }); - index - } - - fn update(&mut self, index: usize, value: Value, source_uuid: Option) { - let Some(message) = self.messages.get_mut(index) else { - return; - }; - message.value = value; - if let Some(source_uuid) = source_uuid { - if !message.source_uuids.contains(&source_uuid) { - message.source_uuids.push(source_uuid); - } - } - } - - fn observe_compact_boundary(&mut self, record: &Value) { - self.preserved_after_compaction = record - .pointer("/compactMetadata/preservedMessages/uuids") - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter_map(Value::as_str) - .map(str::to_owned) - .collect(); - } - - fn begin_compacted(&mut self, summary: Value, source_uuid: Option) { - let preserved = std::mem::take(&mut self.preserved_after_compaction); - let kept = self - .messages - .drain(..) - .filter(|message| { - message - .source_uuids - .iter() - .any(|uuid| preserved.contains(uuid)) - }) - .collect::>(); - self.messages.push(HistoryMessage { - value: summary, - source_uuids: source_uuid.into_iter().collect(), - }); - self.messages.extend(kept); - } -} #[derive(Serialize, Deserialize)] struct PendingEmission { segments: VecDeque>, @@ -1104,7 +949,7 @@ impl ClaudeTranslator { calls, tools, history, - } = parse_transcript(&records, history); + } = history.parse_records(&records); match &mut pending.history { PendingHistory::Main => self.main_history = history, PendingHistory::Owned(pending_history) => *pending_history = history, @@ -1559,9 +1404,9 @@ impl AgentTranslator for ClaudeTranslator { .and_then(|path| self.transcripts.get_mut(path)) { let records = std::mem::take(&mut cursor.buffered); - self.main_history = - parse_transcript(&records, std::mem::take(&mut self.main_history)) - .history; + self.main_history = std::mem::take(&mut self.main_history) + .parse_records(&records) + .history; } } } @@ -1775,207 +1620,16 @@ fn assistant_request_id(record: &Value) -> Option { .flatten() .filter(|id| !id.is_empty()) } -#[derive(Serialize, Deserialize)] -struct ParsedTranscript { - calls: Vec, - tools: Vec, - history: MessageHistory, -} - -fn parse_transcript(records: &[Value], mut history: MessageHistory) -> ParsedTranscript { - let mut calls = Vec::::new(); - let mut call_indexes = HashMap::::new(); - let mut assistant_history_indexes = HashMap::::new(); - let mut tools = HashMap::::new(); - let mut tool_order = Vec::::new(); - - for record in records { - let Some(envelope) = decode::(record) else { - continue; - }; - match envelope.kind.as_deref() { - Some("assistant") => { - let request_id = record - .get("message") - .and_then(|message| string_field(message, "id")) - .or_else(|| string_field(record, "requestId")) - .or_else(|| string_field(record, "uuid")) - .unwrap_or_default(); - if request_id.is_empty() { - continue; - } - let index = *call_indexes.entry(request_id.clone()).or_insert_with(|| { - let index = calls.len(); - calls.push(LlmCall::new( - request_id.clone(), - parse_timestamp_ms(record).unwrap_or(0), - if history.fork_context_prefix { - Vec::new() - } else { - history.active() - }, - history.fork_context_prefix, - )); - index - }); - calls[index].observe(record); - let output = calls[index].output_message(); - let source_uuid = string_field(record, "uuid"); - if let Some(history_index) = assistant_history_indexes.get(&request_id) { - history.update(*history_index, output, source_uuid); - } else { - let history_index = history.push(output, source_uuid); - assistant_history_indexes.insert(request_id.clone(), history_index); - } - // Fork transcripts copy the launching response before their - // first user row. It is input context, not child work or usage. - if calls[index].inherited { - continue; - } - if let Some(content) = record.pointer("/message/content").and_then(Value::as_array) - { - for block in content { - if block.get("type").and_then(Value::as_str) == Some("tool_use") { - let Some(call_id) = string_field(block, "id") else { - continue; - }; - if !tools.contains_key(&call_id) { - tool_order.push(call_id.clone()); - tools.insert( - call_id.clone(), - TranscriptTool { - call_id, - tool_name: string_field(block, "name") - .unwrap_or_else(|| "Tool".into()), - input: block - .get("input") - .cloned() - .unwrap_or_else(|| json!({})), - output: None, - approval: None, - cancelled: false, - terminal: false, - error: None, - start_ms: parse_timestamp_ms(record).unwrap_or(0), - end_ms: parse_timestamp_ms(record).unwrap_or(0), - }, - ); - } - } - } - } - } - Some("user") => { - history.fork_context_prefix = false; - // Claude persists a synthetic user message containing the new - // active context immediately after a compact_boundary record. - // It is the first model-visible message after the boundary. - if envelope.is_compact_summary { - let content = record - .pointer("/message/content") - .cloned() - .unwrap_or(Value::Null); - history.begin_compacted( - json!({ - "role": "user", - "content": if content.is_null() { - json!("[compaction summary unavailable]") - } else { - content - }, - "message_type": "compaction_summary" - }), - string_field(record, "uuid"), - ); - continue; - } - let content = record - .pointer("/message/content") - .cloned() - .unwrap_or(Value::Null); - if let Some(blocks) = content.as_array() { - let mut had_tool_result = false; - for block in blocks { - if block.get("type").and_then(Value::as_str) != Some("tool_result") { - continue; - } - had_tool_result = true; - let call_id = string_field(block, "tool_use_id").unwrap_or_default(); - let result = block.get("content").cloned().unwrap_or(Value::Null); - history.push( - json!({ - "role": "tool", - "tool_call_id": call_id, - "content": result - }), - string_field(record, "uuid"), - ); - if let Some(tool) = tools.get_mut(&call_id) { - tool.output = Some(result); - tool.end_ms = parse_timestamp_ms(record).unwrap_or(tool.start_ms); - tool.terminal = true; - match transcript_tool_outcome(block, record) { - TranscriptToolOutcome::Succeeded => { - tool.approval = Some(ToolApproval::Approved); - } - TranscriptToolOutcome::Failed(error) => { - tool.approval = Some(ToolApproval::Approved); - tool.error = Some(error); - } - TranscriptToolOutcome::Denied => { - tool.approval = Some(ToolApproval::Denied); - } - TranscriptToolOutcome::Cancelled => { - tool.cancelled = true; - } - } - } - } - if !had_tool_result { - history.push( - json!({ "role": "user", "content": content }), - string_field(record, "uuid"), - ); - } - } else if !content.is_null() { - history.push( - json!({ "role": "user", "content": content }), - string_field(record, "uuid"), - ); - } - } - Some("system") if envelope.subtype.as_deref() == Some("compact_boundary") => { - history.observe_compact_boundary(record); - } - Some("fork-context-ref") => history.fork_context_prefix = true, - _ => {} - } - } - calls.retain(|call| !call.inherited); - ParsedTranscript { - calls, - tools: tool_order - .into_iter() - .filter_map(|id| tools.remove(&id)) - .collect(), - history, - } -} - /// Returns the most recent SubagentHandback report whose matching transcript /// result proves that the tool completed successfully. pub(crate) fn successful_subagent_handback_message(records: &[Value]) -> Option { - parse_transcript(records, MessageHistory::default()) + MessageHistory::default() + .parse_records(records) .tools .into_iter() .rev() - .find(|tool| { - tool.tool_name == "SubagentHandback" - && tool.approval == Some(ToolApproval::Approved) - && tool.error.is_none() - && !tool.cancelled - }) - .and_then(|tool| tool.input.get("message").cloned()) + .find(TranscriptTool::is_successful_handback) + .and_then(|tool| tool.handback_message()) } fn continuation_origin(payload: &Value) -> Option<(&'static str, &str)> { @@ -2056,382 +1710,6 @@ fn is_real_user_record(record: &Value) -> bool { .any(|block| block.get("type").and_then(Value::as_str) == Some("tool_result")) }) } -#[derive(Serialize, Deserialize)] -struct LlmCall { - request_id: String, - inherited: bool, - model: String, - start_ms: i64, - end_ms: i64, - input: Vec, - text: Vec, - tool_calls: Vec, - prompt_tokens: u64, - completion_tokens: u64, - cache_creation_tokens: u64, - cache_creation_5m_tokens: u64, - cache_creation_1h_tokens: u64, - cache_read_tokens: u64, - error: Option, - api_error_status: Option, -} - -impl LlmCall { - fn new(request_id: String, start_ms: i64, input: Vec, inherited: bool) -> Self { - Self { - request_id, - inherited, - model: "claude".into(), - start_ms, - end_ms: start_ms, - input, - text: Vec::new(), - tool_calls: Vec::new(), - prompt_tokens: 0, - completion_tokens: 0, - cache_creation_tokens: 0, - cache_creation_5m_tokens: 0, - cache_creation_1h_tokens: 0, - cache_read_tokens: 0, - error: None, - api_error_status: None, - } - } - - fn observe(&mut self, record: &Value) { - self.end_ms = parse_timestamp_ms(record).unwrap_or(self.end_ms); - if record - .get("isApiErrorMessage") - .and_then(Value::as_bool) - .unwrap_or(false) - { - self.error = string_field(record, "error") - .or_else(|| { - record - .pointer("/message/content") - .and_then(Value::as_array) - .and_then(|content| { - content.iter().find_map(|block| { - (block.get("type").and_then(Value::as_str) == Some("text")) - .then(|| block.get("text").and_then(Value::as_str)) - .flatten() - }) - }) - .map(str::to_owned) - }) - .or_else(|| Some("Claude API error".into())); - self.api_error_status = record.get("apiErrorStatus").and_then(Value::as_u64); - } - let Some(message) = record.get("message") else { - return; - }; - if let Some(model) = string_field(message, "model") { - self.model = model; - } - if let Some(content) = message.get("content").and_then(Value::as_array) { - for block in content { - match block.get("type").and_then(Value::as_str) { - Some("text") => { - if let Some(text) = block.get("text").and_then(Value::as_str) { - if !self.text.iter().any(|seen| seen == text) { - self.text.push(text.to_string()); - } - } - } - Some("tool_use") => { - let arguments = - serde_json::to_string(block.get("input").unwrap_or(&Value::Null)) - .unwrap_or_else(|_| "{}".into()); - let call = json!({ - "id": block.get("id").cloned().unwrap_or(Value::Null), - "type": "function", - "function": { - "name": block.get("name").cloned().unwrap_or(Value::Null), - "arguments": arguments - } - }); - if !self.tool_calls.contains(&call) { - self.tool_calls.push(call); - } - } - _ => {} - } - } - } - #[derive(Deserialize)] - struct UsageRecord { - message: Option, - } - #[derive(Deserialize)] - struct UsageMessage { - usage: Option, - } - if let Some(usage) = decode::(record) - .and_then(|record| record.message) - .and_then(|message| message.usage) - { - self.prompt_tokens = self.prompt_tokens.max(usage.input_tokens.unwrap_or(0)); - self.completion_tokens = self.completion_tokens.max(usage.output_tokens.unwrap_or(0)); - self.cache_creation_tokens = self - .cache_creation_tokens - .max(usage.cache_creation_input_tokens.unwrap_or(0)); - self.cache_read_tokens = self - .cache_read_tokens - .max(usage.cache_read_input_tokens.unwrap_or(0)); - if let Some(cache) = usage.cache_creation { - self.cache_creation_5m_tokens = self - .cache_creation_5m_tokens - .max(cache.ephemeral_5m_input_tokens.unwrap_or(0)); - self.cache_creation_1h_tokens = self - .cache_creation_1h_tokens - .max(cache.ephemeral_1h_input_tokens.unwrap_or(0)); - } - } - } - - fn output_message(&self) -> Value { - let content = self.text.join("\n"); - if self.tool_calls.is_empty() { - json!({ "role": "assistant", "content": content }) - } else { - json!({ "role": "assistant", "content": content, "tool_calls": self.tool_calls }) - } - } - - fn into_row(self, span_id: String, root_span_id: String, parent: String) -> SpanRow { - let has_split = self.cache_creation_5m_tokens > 0 || self.cache_creation_1h_tokens > 0; - let creation = if has_split { - self.cache_creation_5m_tokens + self.cache_creation_1h_tokens - } else { - self.cache_creation_tokens - }; - let prompt = self.prompt_tokens + self.cache_read_tokens + creation; - let mut metrics = Map::new(); - metrics.insert("prompt_tokens".into(), json!(prompt)); - metrics.insert("completion_tokens".into(), json!(self.completion_tokens)); - metrics.insert("tokens".into(), json!(prompt + self.completion_tokens)); - metrics.insert("prompt_cached_tokens".into(), json!(self.cache_read_tokens)); - if has_split { - metrics.insert( - "prompt_cache_creation_5m_tokens".into(), - json!(self.cache_creation_5m_tokens), - ); - metrics.insert( - "prompt_cache_creation_1h_tokens".into(), - json!(self.cache_creation_1h_tokens), - ); - } else { - metrics.insert( - "prompt_cache_creation_tokens".into(), - json!(self.cache_creation_tokens), - ); - } - let output = self.output_message(); - let mut metadata = Map::new(); - metadata.insert("model".into(), json!(self.model)); - metadata.insert("request_id".into(), json!(self.request_id)); - if let Some(status) = self.api_error_status { - metadata.insert("api_error_status".into(), json!(status)); - } - SpanRow { - span_id, - root_span_id, - parent_span_ids: vec![parent], - name: self.model.clone(), - span_type: SpanType::Llm, - start_ms: Some(self.start_ms), - end_ms: Some(self.end_ms), - input: Some(Value::Array(self.input)), - output: Some(output), - metadata: Some(Value::Object(metadata)), - metrics: Some(Value::Object(metrics)), - error: self.error, - ..Default::default() - } - } -} -#[derive(Serialize, Deserialize)] -enum TranscriptToolOutcome { - Succeeded, - Failed(String), - Denied, - Cancelled, -} - -fn transcript_tool_outcome(block: &Value, record: &Value) -> TranscriptToolOutcome { - let native_result = record.get("toolUseResult"); - let values = [block.get("content"), native_result] - .into_iter() - .flatten() - .collect::>(); - - let error_signalled = block.get("is_error").and_then(Value::as_bool) == Some(true) - || block.get("isError").and_then(Value::as_bool) == Some(true) - || values.iter().any(|value| has_structured_error(value)); - let structured_denial = values - .iter() - .any(|value| has_structured_outcome(value, &["denied", "deny", "rejected", "reject"])); - let denial_text = values.iter().any(|value| { - (has_outcome_phrase(value, &["permission to use"]) - && has_outcome_phrase(value, &["has been denied"])) - || has_outcome_phrase( - value, - &[ - "tool use was rejected", - "tool use was denied", - "user rejected", - "user denied", - "user doesn't want to proceed", - "user does not want to proceed", - "permission request was rejected", - "permission request was denied", - ], - ) - }); - if structured_denial || (error_signalled && denial_text) { - return TranscriptToolOutcome::Denied; - } - - let structured_cancellation = values.iter().any(|value| { - has_structured_outcome(value, &["cancelled", "canceled", "aborted", "interrupted"]) - || has_structured_cancellation(value) - }); - let cancellation_text = values.iter().any(|value| { - has_outcome_phrase( - value, - &[ - "request interrupted by user", - "tool use was cancelled", - "tool use was canceled", - "operation was cancelled", - "operation was canceled", - "operation was aborted", - "user cancelled", - "user canceled", - ], - ) - }); - if structured_cancellation || (error_signalled && cancellation_text) { - return TranscriptToolOutcome::Cancelled; - } - - if error_signalled { - let error = values - .iter() - .find_map(|value| nonempty_error_text(value)) - .unwrap_or_else(|| "Tool execution failed".into()); - TranscriptToolOutcome::Failed(error) - } else { - TranscriptToolOutcome::Succeeded - } -} - -fn has_structured_outcome(value: &Value, outcomes: &[&str]) -> bool { - let Some(object) = value.as_object() else { - return false; - }; - ["status", "outcome", "type"] - .into_iter() - .filter_map(|key| object.get(key).and_then(Value::as_str)) - .any(|status| outcomes.contains(&status.trim().to_ascii_lowercase().as_str())) -} - -fn has_structured_error(value: &Value) -> bool { - value.as_object().is_some_and(|object| { - object.get("is_error").and_then(Value::as_bool) == Some(true) - || object.get("isError").and_then(Value::as_bool) == Some(true) - || object.get("error").is_some_and(|error| { - error.as_bool() == Some(true) || nonempty_error_text(error).is_some() - }) - || has_structured_outcome(value, &["error", "failed", "failure"]) - }) -} - -fn has_structured_cancellation(value: &Value) -> bool { - value.as_object().is_some_and(|object| { - ["interrupted", "cancelled", "canceled", "aborted"] - .into_iter() - .any(|key| object.get(key).and_then(Value::as_bool) == Some(true)) - }) -} - -fn has_outcome_phrase(value: &Value, phrases: &[&str]) -> bool { - match value { - Value::String(text) => { - let text = text.to_ascii_lowercase(); - phrases.iter().any(|phrase| text.contains(phrase)) - } - Value::Array(values) => values - .iter() - .any(|value| has_outcome_phrase(value, phrases)), - Value::Object(object) => object - .values() - .any(|value| has_outcome_phrase(value, phrases)), - _ => false, - } -} -#[derive(Serialize, Deserialize)] -struct TranscriptTool { - call_id: String, - tool_name: String, - input: Value, - output: Option, - approval: Option, - cancelled: bool, - terminal: bool, - error: Option, - start_ms: i64, - end_ms: i64, -} - -impl TranscriptTool { - fn metadata(&self) -> Value { - let mut metadata = Map::new(); - metadata.insert("tool_name".into(), json!(self.tool_name)); - add_tool_approval(&mut metadata, self.approval); - metadata.insert("tool_call_id".into(), json!(self.call_id)); - metadata.insert("recovered_from_transcript".into(), json!(true)); - if self.cancelled || !self.terminal { - metadata.insert("cancelled".into(), json!(true)); - } - Value::Object(metadata) - } - - fn into_row(self, span_id: String, root_span_id: String, parent: String) -> SpanRow { - SpanRow { - span_id, - root_span_id, - parent_span_ids: vec![parent], - name: tool_span_name( - &self.tool_name, - &self.input, - skill_load(&self.tool_name, &self.input).as_ref(), - ), - span_type: SpanType::Tool, - start_ms: Some(self.start_ms), - end_ms: Some(self.end_ms), - input: Some(self.input.clone()), - output: self.output.clone(), - metadata: Some(self.metadata()), - error: self.error.clone(), - ..Default::default() - } - } - - fn into_update(self, span_id: String, root_span_id: String, parent_id: String) -> SpanRow { - SpanRow { - span_id, - root_span_id, - parent_span_ids: vec![parent_id], - end_ms: Some(self.end_ms), - output: self.output.clone(), - metadata: Some(self.metadata()), - error: self.error.clone(), - ..Default::default() - } - } -} - /// Read newline-delimited records forward from `offset`, advancing it past /// everything consumed. /// @@ -2652,10 +1930,6 @@ fn tool_name(payload: &Value) -> Option { string_field(payload, "tool_name").or_else(|| string_field(payload, "tool")) } -fn parse_timestamp_ms(value: &Value) -> Option { - decode::(value).and_then(|value| value.timestamp_ms) -} - fn string_field(value: &Value, key: &str) -> Option { value.get(key).and_then(|value| match value { Value::String(text) if !text.is_empty() => Some(text.clone()), diff --git a/bt-daemon/src/translate/claude/history_message.rs b/bt-daemon/src/translate/claude/history_message.rs new file mode 100644 index 00000000..51f831e1 --- /dev/null +++ b/bt-daemon/src/translate/claude/history_message.rs @@ -0,0 +1,34 @@ +//! One model-visible history message and the native rows contributing to it. +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Serialize, Deserialize)] +pub(super) struct HistoryMessage { + value: Value, + source_uuids: Vec, +} + +impl HistoryMessage { + pub(super) fn new(value: Value, source_uuid: Option) -> Self { + Self { + value, + source_uuids: source_uuid.into_iter().collect(), + } + } + pub(super) fn value(&self) -> &Value { + &self.value + } + pub(super) fn update(&mut self, value: Value, source_uuid: Option) { + self.value = value; + if let Some(source_uuid) = source_uuid { + if !self.source_uuids.contains(&source_uuid) { + self.source_uuids.push(source_uuid); + } + } + } + pub(super) fn is_preserved_by(&self, source_uuids: &[String]) -> bool { + self.source_uuids + .iter() + .any(|uuid| source_uuids.contains(uuid)) + } +} diff --git a/bt-daemon/src/translate/claude/hook_context.rs b/bt-daemon/src/translate/claude/hook_context.rs new file mode 100644 index 00000000..b9484335 --- /dev/null +++ b/bt-daemon/src/translate/claude/hook_context.rs @@ -0,0 +1,20 @@ +use super::native_field::{deserialize_optional_effort, deserialize_optional_string}; +use serde::{Deserialize, Serialize}; + +#[derive(Default, Deserialize, Serialize)] +pub(super) struct HookContext { + #[serde(default, deserialize_with = "deserialize_optional_string")] + pub(super) cwd: Option, + #[serde(default, deserialize_with = "deserialize_optional_string")] + pub(super) transcript_path: Option, + #[serde(default, deserialize_with = "deserialize_optional_string")] + pub(super) source: Option, + #[serde(default, deserialize_with = "deserialize_optional_string")] + pub(super) model: Option, + #[serde(default, deserialize_with = "deserialize_optional_string")] + pub(super) permission_mode: Option, + #[serde(default, deserialize_with = "deserialize_optional_effort")] + pub(super) effort: Option, + #[serde(default, deserialize_with = "deserialize_optional_string")] + pub(super) system_prompt: Option, +} diff --git a/bt-daemon/src/translate/claude/llm_call.rs b/bt-daemon/src/translate/claude/llm_call.rs new file mode 100644 index 00000000..8522b9a5 --- /dev/null +++ b/bt-daemon/src/translate/claude/llm_call.rs @@ -0,0 +1,206 @@ +//! One native model request, including streamed output and monotonic usage. +use super::{decode, parse_timestamp_ms, string_field}; +use crate::agents::usage::SnakeCaseUsage; +use crate::translate::{SpanRow, SpanType}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; + +#[derive(Serialize, Deserialize)] +pub(super) struct LlmCall { + pub(super) request_id: String, + pub(super) inherited: bool, + model: String, + start_ms: i64, + end_ms: i64, + input: Vec, + text: Vec, + tool_calls: Vec, + prompt_tokens: u64, + completion_tokens: u64, + cache_creation_tokens: u64, + cache_creation_5m_tokens: u64, + cache_creation_1h_tokens: u64, + cache_read_tokens: u64, + error: Option, + api_error_status: Option, +} + +impl LlmCall { + pub(super) fn new( + request_id: String, + start_ms: i64, + input: Vec, + inherited: bool, + ) -> Self { + Self { + request_id, + inherited, + model: "claude".into(), + start_ms, + end_ms: start_ms, + input, + text: Vec::new(), + tool_calls: Vec::new(), + prompt_tokens: 0, + completion_tokens: 0, + cache_creation_tokens: 0, + cache_creation_5m_tokens: 0, + cache_creation_1h_tokens: 0, + cache_read_tokens: 0, + error: None, + api_error_status: None, + } + } + + pub(super) fn observe(&mut self, record: &Value) { + self.end_ms = parse_timestamp_ms(record).unwrap_or(self.end_ms); + if record + .get("isApiErrorMessage") + .and_then(Value::as_bool) + .unwrap_or(false) + { + self.error = string_field(record, "error") + .or_else(|| { + record + .pointer("/message/content") + .and_then(Value::as_array) + .and_then(|content| { + content.iter().find_map(|block| { + (block.get("type").and_then(Value::as_str) == Some("text")) + .then(|| block.get("text").and_then(Value::as_str)) + .flatten() + }) + }) + .map(str::to_owned) + }) + .or_else(|| Some("Claude API error".into())); + self.api_error_status = record.get("apiErrorStatus").and_then(Value::as_u64); + } + let Some(message) = record.get("message") else { + return; + }; + if let Some(model) = string_field(message, "model") { + self.model = model; + } + if let Some(content) = message.get("content").and_then(Value::as_array) { + for block in content { + match block.get("type").and_then(Value::as_str) { + Some("text") => { + if let Some(text) = block.get("text").and_then(Value::as_str) { + if !self.text.iter().any(|seen| seen == text) { + self.text.push(text.to_string()); + } + } + } + Some("tool_use") => { + let arguments = + serde_json::to_string(block.get("input").unwrap_or(&Value::Null)) + .unwrap_or_else(|_| "{}".into()); + let call = json!({ + "id": block.get("id").cloned().unwrap_or(Value::Null), + "type": "function", + "function": { + "name": block.get("name").cloned().unwrap_or(Value::Null), + "arguments": arguments + } + }); + if !self.tool_calls.contains(&call) { + self.tool_calls.push(call); + } + } + _ => {} + } + } + } + #[derive(Deserialize)] + struct UsageRecord { + message: Option, + } + #[derive(Deserialize)] + struct UsageMessage { + usage: Option, + } + if let Some(usage) = decode::(record) + .and_then(|record| record.message) + .and_then(|message| message.usage) + { + self.prompt_tokens = self.prompt_tokens.max(usage.input_tokens.unwrap_or(0)); + self.completion_tokens = self.completion_tokens.max(usage.output_tokens.unwrap_or(0)); + self.cache_creation_tokens = self + .cache_creation_tokens + .max(usage.cache_creation_input_tokens.unwrap_or(0)); + self.cache_read_tokens = self + .cache_read_tokens + .max(usage.cache_read_input_tokens.unwrap_or(0)); + if let Some(cache) = usage.cache_creation { + self.cache_creation_5m_tokens = self + .cache_creation_5m_tokens + .max(cache.ephemeral_5m_input_tokens.unwrap_or(0)); + self.cache_creation_1h_tokens = self + .cache_creation_1h_tokens + .max(cache.ephemeral_1h_input_tokens.unwrap_or(0)); + } + } + } + + pub(super) fn output_message(&self) -> Value { + let content = self.text.join("\n"); + if self.tool_calls.is_empty() { + json!({ "role": "assistant", "content": content }) + } else { + json!({ "role": "assistant", "content": content, "tool_calls": self.tool_calls }) + } + } + + pub(super) fn into_row(self, span_id: String, root_span_id: String, parent: String) -> SpanRow { + let has_split = self.cache_creation_5m_tokens > 0 || self.cache_creation_1h_tokens > 0; + let creation = if has_split { + self.cache_creation_5m_tokens + self.cache_creation_1h_tokens + } else { + self.cache_creation_tokens + }; + let prompt = self.prompt_tokens + self.cache_read_tokens + creation; + let mut metrics = Map::new(); + metrics.insert("prompt_tokens".into(), json!(prompt)); + metrics.insert("completion_tokens".into(), json!(self.completion_tokens)); + metrics.insert("tokens".into(), json!(prompt + self.completion_tokens)); + metrics.insert("prompt_cached_tokens".into(), json!(self.cache_read_tokens)); + if has_split { + metrics.insert( + "prompt_cache_creation_5m_tokens".into(), + json!(self.cache_creation_5m_tokens), + ); + metrics.insert( + "prompt_cache_creation_1h_tokens".into(), + json!(self.cache_creation_1h_tokens), + ); + } else { + metrics.insert( + "prompt_cache_creation_tokens".into(), + json!(self.cache_creation_tokens), + ); + } + let output = self.output_message(); + let mut metadata = Map::new(); + metadata.insert("model".into(), json!(self.model)); + metadata.insert("request_id".into(), json!(self.request_id)); + if let Some(status) = self.api_error_status { + metadata.insert("api_error_status".into(), json!(status)); + } + SpanRow { + span_id, + root_span_id, + parent_span_ids: vec![parent], + name: self.model.clone(), + span_type: SpanType::Llm, + start_ms: Some(self.start_ms), + end_ms: Some(self.end_ms), + input: Some(Value::Array(self.input)), + output: Some(output), + metadata: Some(Value::Object(metadata)), + metrics: Some(Value::Object(metrics)), + error: self.error, + ..Default::default() + } + } +} diff --git a/bt-daemon/src/translate/claude/message_history.rs b/bt-daemon/src/translate/claude/message_history.rs new file mode 100644 index 00000000..edb5da97 --- /dev/null +++ b/bt-daemon/src/translate/claude/message_history.rs @@ -0,0 +1,211 @@ +//! Active model-visible context, fork inheritance and compaction preservation. +use super::history_message::HistoryMessage; +use super::llm_call::LlmCall; +use super::parsed_transcript::ParsedTranscript; +use super::transcript_envelope::TranscriptEnvelope; +use super::transcript_tool::TranscriptTool; +use super::{decode, parse_timestamp_ms, string_field}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::HashMap; + +#[derive(Default, Serialize, Deserialize)] +pub(super) struct MessageHistory { + messages: Vec, + preserved_after_compaction: Vec, + fork_context_prefix: bool, +} +impl MessageHistory { + fn active(&self) -> Vec { + self.messages + .iter() + .map(|message| message.value().clone()) + .collect() + } + + fn push(&mut self, value: Value, source_uuid: Option) -> usize { + let index = self.messages.len(); + self.messages.push(HistoryMessage::new(value, source_uuid)); + index + } + + fn update(&mut self, index: usize, value: Value, source_uuid: Option) { + let Some(message) = self.messages.get_mut(index) else { + return; + }; + message.update(value, source_uuid); + } + + fn observe_compact_boundary(&mut self, record: &Value) { + self.preserved_after_compaction = record + .pointer("/compactMetadata/preservedMessages/uuids") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(); + } + + fn begin_compacted(&mut self, summary: Value, source_uuid: Option) { + let preserved = std::mem::take(&mut self.preserved_after_compaction); + let kept = self + .messages + .drain(..) + .filter(|message| message.is_preserved_by(&preserved)) + .collect::>(); + self.messages + .push(HistoryMessage::new(summary, source_uuid)); + self.messages.extend(kept); + } +} +impl MessageHistory { + pub(super) fn parse_records(mut self, records: &[Value]) -> ParsedTranscript { + let mut calls = Vec::::new(); + let mut call_indexes = HashMap::::new(); + let mut assistant_history_indexes = HashMap::::new(); + let mut tools = HashMap::::new(); + let mut tool_order = Vec::::new(); + + for record in records { + let Some(envelope) = decode::(record) else { + continue; + }; + match envelope.kind.as_deref() { + Some("assistant") => { + let request_id = record + .get("message") + .and_then(|message| string_field(message, "id")) + .or_else(|| string_field(record, "requestId")) + .or_else(|| string_field(record, "uuid")) + .unwrap_or_default(); + if request_id.is_empty() { + continue; + } + let index = *call_indexes.entry(request_id.clone()).or_insert_with(|| { + let index = calls.len(); + calls.push(LlmCall::new( + request_id.clone(), + parse_timestamp_ms(record).unwrap_or(0), + if self.fork_context_prefix { + Vec::new() + } else { + self.active() + }, + self.fork_context_prefix, + )); + index + }); + calls[index].observe(record); + let output = calls[index].output_message(); + let source_uuid = string_field(record, "uuid"); + if let Some(history_index) = assistant_history_indexes.get(&request_id) { + self.update(*history_index, output, source_uuid); + } else { + let history_index = self.push(output, source_uuid); + assistant_history_indexes.insert(request_id.clone(), history_index); + } + // Fork transcripts copy the launching response before their + // first user row. It is input context, not child work or usage. + if calls[index].inherited { + continue; + } + if let Some(content) = + record.pointer("/message/content").and_then(Value::as_array) + { + for block in content { + if block.get("type").and_then(Value::as_str) == Some("tool_use") { + let Some(call_id) = string_field(block, "id") else { + continue; + }; + if !tools.contains_key(&call_id) { + tool_order.push(call_id.clone()); + tools.insert( + call_id.clone(), + TranscriptTool::from_call(call_id, block, record), + ); + } + } + } + } + } + Some("user") => { + self.fork_context_prefix = false; + // Claude persists a synthetic user message containing the new + // active context immediately after a compact_boundary record. + // It is the first model-visible message after the boundary. + if envelope.is_compact_summary { + let content = record + .pointer("/message/content") + .cloned() + .unwrap_or(Value::Null); + self.begin_compacted( + json!({ + "role": "user", + "content": if content.is_null() { + json!("[compaction summary unavailable]") + } else { + content + }, + "message_type": "compaction_summary" + }), + string_field(record, "uuid"), + ); + continue; + } + let content = record + .pointer("/message/content") + .cloned() + .unwrap_or(Value::Null); + if let Some(blocks) = content.as_array() { + let mut had_tool_result = false; + for block in blocks { + if block.get("type").and_then(Value::as_str) != Some("tool_result") { + continue; + } + had_tool_result = true; + let call_id = string_field(block, "tool_use_id").unwrap_or_default(); + let result = block.get("content").cloned().unwrap_or(Value::Null); + self.push( + json!({ + "role": "tool", + "tool_call_id": call_id, + "content": result + }), + string_field(record, "uuid"), + ); + if let Some(tool) = tools.get_mut(&call_id) { + tool.observe_result(result, block, record); + } + } + if !had_tool_result { + self.push( + json!({ "role": "user", "content": content }), + string_field(record, "uuid"), + ); + } + } else if !content.is_null() { + self.push( + json!({ "role": "user", "content": content }), + string_field(record, "uuid"), + ); + } + } + Some("system") if envelope.subtype.as_deref() == Some("compact_boundary") => { + self.observe_compact_boundary(record); + } + Some("fork-context-ref") => self.fork_context_prefix = true, + _ => {} + } + } + calls.retain(|call| !call.inherited); + ParsedTranscript { + calls, + tools: tool_order + .into_iter() + .filter_map(|id| tools.remove(&id)) + .collect(), + history: self, + } + } +} diff --git a/bt-daemon/src/translate/claude/native_field.rs b/bt-daemon/src/translate/claude/native_field.rs new file mode 100644 index 00000000..4dfa36ae --- /dev/null +++ b/bt-daemon/src/translate/claude/native_field.rs @@ -0,0 +1,44 @@ +//! Compatibility decoding for native Claude hook scalar fields. +use serde::Deserialize; +use serde_json::Value; + +pub(super) fn deserialize_optional_string<'de, D>( + deserializer: D, +) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + Ok(Option::::deserialize(deserializer)? + .as_ref() + .and_then(value_as_nonempty_string)) +} + +/// Claude hooks report effort as `{"level": "high"}`. +pub(super) fn deserialize_optional_effort<'de, D>( + deserializer: D, +) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + Ok(Option::::deserialize(deserializer)? + .as_ref() + .and_then(|effort| effort.get("level")) + .and_then(value_as_nonempty_string)) +} + +pub(super) fn deserialize_nonempty_string<'de, D>(deserializer: D) -> Result +where + D: serde::Deserializer<'de>, +{ + let value = Value::deserialize(deserializer)?; + value_as_nonempty_string(&value) + .ok_or_else(|| serde::de::Error::custom("expected a non-empty string or number")) +} + +fn value_as_nonempty_string(value: &Value) -> Option { + match value { + Value::String(value) if !value.is_empty() => Some(value.clone()), + Value::Number(value) => Some(value.to_string()), + _ => None, + } +} diff --git a/bt-daemon/src/translate/claude/parsed_transcript.rs b/bt-daemon/src/translate/claude/parsed_transcript.rs new file mode 100644 index 00000000..907405dc --- /dev/null +++ b/bt-daemon/src/translate/claude/parsed_transcript.rs @@ -0,0 +1,9 @@ +use super::{llm_call::LlmCall, message_history::MessageHistory, transcript_tool::TranscriptTool}; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub(super) struct ParsedTranscript { + pub(super) calls: Vec, + pub(super) tools: Vec, + pub(super) history: MessageHistory, +} diff --git a/bt-daemon/src/translate/claude/subagent_hook.rs b/bt-daemon/src/translate/claude/subagent_hook.rs new file mode 100644 index 00000000..de74a472 --- /dev/null +++ b/bt-daemon/src/translate/claude/subagent_hook.rs @@ -0,0 +1,12 @@ +use super::native_field::{deserialize_nonempty_string, deserialize_optional_string}; +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, Serialize)] +pub(super) struct SubagentHook { + #[serde(deserialize_with = "deserialize_nonempty_string")] + pub(super) agent_id: String, + #[serde(default, deserialize_with = "deserialize_optional_string")] + pub(super) agent_type: Option, + #[serde(default, deserialize_with = "deserialize_optional_string")] + pub(super) agent_transcript_path: Option, +} diff --git a/bt-daemon/src/translate/claude/timestamp_envelope.rs b/bt-daemon/src/translate/claude/timestamp_envelope.rs new file mode 100644 index 00000000..eec47f7e --- /dev/null +++ b/bt-daemon/src/translate/claude/timestamp_envelope.rs @@ -0,0 +1,36 @@ +use super::decode; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Timestamp decoding is deliberately separate from transcript routing. A +/// future change to an unrelated routing field must not cause bounded reads to +/// consume records from after a hook's capture point. +#[derive(Deserialize, Serialize)] +struct TimestampEnvelope { + #[serde( + rename = "timestamp", + default, + deserialize_with = "deserialize_optional_timestamp" + )] + timestamp_ms: Option, +} + +fn deserialize_optional_timestamp<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + Ok(Option::::deserialize(deserializer)? + .as_ref() + .and_then(Value::as_str) + .and_then(parse_rfc3339_timestamp)) +} + +pub(super) fn parse_rfc3339_timestamp(value: &str) -> Option { + chrono::DateTime::parse_from_rfc3339(value) + .ok() + .map(|timestamp| timestamp.timestamp_millis()) +} + +pub(super) fn parse_timestamp_ms(value: &Value) -> Option { + decode::(value).and_then(|value| value.timestamp_ms) +} diff --git a/bt-daemon/src/translate/claude/transcript_envelope.rs b/bt-daemon/src/translate/claude/transcript_envelope.rs new file mode 100644 index 00000000..1bbfa928 --- /dev/null +++ b/bt-daemon/src/translate/claude/transcript_envelope.rs @@ -0,0 +1,13 @@ +use serde::{Deserialize, Serialize}; + +/// Stable routing fields from one Claude transcript row. Message and tool +/// blocks intentionally remain raw because they are preserved in span I/O. +#[derive(Deserialize, Serialize)] +pub(super) struct TranscriptEnvelope { + #[serde(rename = "type", default)] + pub(super) kind: Option, + #[serde(default)] + pub(super) subtype: Option, + #[serde(rename = "isCompactSummary", default)] + pub(super) is_compact_summary: bool, +} diff --git a/bt-daemon/src/translate/claude/transcript_tool.rs b/bt-daemon/src/translate/claude/transcript_tool.rs new file mode 100644 index 00000000..92d30383 --- /dev/null +++ b/bt-daemon/src/translate/claude/transcript_tool.rs @@ -0,0 +1,115 @@ +//! One transcript-recovered tool call and its terminal transitions. +use super::transcript_tool_outcome::TranscriptToolOutcome; +use super::{parse_timestamp_ms, skill_load, string_field, tool_span_name}; +use crate::translate::tool::{add_tool_approval, ToolApproval}; +use crate::translate::{SpanRow, SpanType}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; + +#[derive(Serialize, Deserialize)] +pub(super) struct TranscriptTool { + pub(super) call_id: String, + tool_name: String, + input: Value, + output: Option, + approval: Option, + cancelled: bool, + pub(super) terminal: bool, + error: Option, + start_ms: i64, + end_ms: i64, +} + +impl TranscriptTool { + pub(super) fn from_call(call_id: String, block: &Value, record: &Value) -> Self { + Self { + call_id, + tool_name: string_field(block, "name").unwrap_or_else(|| "Tool".into()), + input: block.get("input").cloned().unwrap_or_else(|| json!({})), + output: None, + approval: None, + cancelled: false, + terminal: false, + error: None, + start_ms: parse_timestamp_ms(record).unwrap_or(0), + end_ms: parse_timestamp_ms(record).unwrap_or(0), + } + } + + pub(super) fn observe_result(&mut self, result: Value, block: &Value, record: &Value) { + self.output = Some(result); + self.end_ms = parse_timestamp_ms(record).unwrap_or(self.start_ms); + self.terminal = true; + match TranscriptToolOutcome::from_result(block, record) { + TranscriptToolOutcome::Succeeded => self.approval = Some(ToolApproval::Approved), + TranscriptToolOutcome::Failed(error) => { + self.approval = Some(ToolApproval::Approved); + self.error = Some(error); + } + TranscriptToolOutcome::Denied => self.approval = Some(ToolApproval::Denied), + TranscriptToolOutcome::Cancelled => self.cancelled = true, + } + } + + pub(super) fn is_successful_handback(&self) -> bool { + self.tool_name == "SubagentHandback" + && self.approval == Some(ToolApproval::Approved) + && self.error.is_none() + && !self.cancelled + } + + pub(super) fn handback_message(&self) -> Option { + self.input.get("message").cloned() + } + + fn metadata(&self) -> Value { + let mut metadata = Map::new(); + metadata.insert("tool_name".into(), json!(self.tool_name)); + add_tool_approval(&mut metadata, self.approval); + metadata.insert("tool_call_id".into(), json!(self.call_id)); + metadata.insert("recovered_from_transcript".into(), json!(true)); + if self.cancelled || !self.terminal { + metadata.insert("cancelled".into(), json!(true)); + } + Value::Object(metadata) + } + + pub(super) fn into_row(self, span_id: String, root_span_id: String, parent: String) -> SpanRow { + SpanRow { + span_id, + root_span_id, + parent_span_ids: vec![parent], + name: tool_span_name( + &self.tool_name, + &self.input, + skill_load(&self.tool_name, &self.input).as_ref(), + ), + span_type: SpanType::Tool, + start_ms: Some(self.start_ms), + end_ms: Some(self.end_ms), + input: Some(self.input.clone()), + output: self.output.clone(), + metadata: Some(self.metadata()), + error: self.error.clone(), + ..Default::default() + } + } + + pub(super) fn into_update( + self, + span_id: String, + root_span_id: String, + parent_id: String, + ) -> SpanRow { + SpanRow { + span_id, + root_span_id, + parent_span_ids: vec![parent_id], + end_ms: Some(self.end_ms), + output: self.output.clone(), + metadata: Some(self.metadata()), + error: self.error.clone(), + ..Default::default() + } + } +} diff --git a/bt-daemon/src/translate/claude/transcript_tool_outcome.rs b/bt-daemon/src/translate/claude/transcript_tool_outcome.rs new file mode 100644 index 00000000..eb09c0ce --- /dev/null +++ b/bt-daemon/src/translate/claude/transcript_tool_outcome.rs @@ -0,0 +1,127 @@ +//! Interpret native tool completion without treating cancellation as failure. +use crate::translate::tool::nonempty_error_text; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Serialize, Deserialize)] +pub(super) enum TranscriptToolOutcome { + Succeeded, + Failed(String), + Denied, + Cancelled, +} + +impl TranscriptToolOutcome { + pub(super) fn from_result(block: &Value, record: &Value) -> Self { + let native_result = record.get("toolUseResult"); + let values = [block.get("content"), native_result] + .into_iter() + .flatten() + .collect::>(); + + let error_signalled = block.get("is_error").and_then(Value::as_bool) == Some(true) + || block.get("isError").and_then(Value::as_bool) == Some(true) + || values.iter().any(|value| has_structured_error(value)); + let structured_denial = values + .iter() + .any(|value| has_structured_outcome(value, &["denied", "deny", "rejected", "reject"])); + let denial_text = values.iter().any(|value| { + (has_outcome_phrase(value, &["permission to use"]) + && has_outcome_phrase(value, &["has been denied"])) + || has_outcome_phrase( + value, + &[ + "tool use was rejected", + "tool use was denied", + "user rejected", + "user denied", + "user doesn't want to proceed", + "user does not want to proceed", + "permission request was rejected", + "permission request was denied", + ], + ) + }); + if structured_denial || (error_signalled && denial_text) { + return TranscriptToolOutcome::Denied; + } + + let structured_cancellation = values.iter().any(|value| { + has_structured_outcome(value, &["cancelled", "canceled", "aborted", "interrupted"]) + || has_structured_cancellation(value) + }); + let cancellation_text = values.iter().any(|value| { + has_outcome_phrase( + value, + &[ + "request interrupted by user", + "tool use was cancelled", + "tool use was canceled", + "operation was cancelled", + "operation was canceled", + "operation was aborted", + "user cancelled", + "user canceled", + ], + ) + }); + if structured_cancellation || (error_signalled && cancellation_text) { + return TranscriptToolOutcome::Cancelled; + } + + if error_signalled { + let error = values + .iter() + .find_map(|value| nonempty_error_text(value)) + .unwrap_or_else(|| "Tool execution failed".into()); + TranscriptToolOutcome::Failed(error) + } else { + TranscriptToolOutcome::Succeeded + } + } +} + +fn has_structured_outcome(value: &Value, outcomes: &[&str]) -> bool { + let Some(object) = value.as_object() else { + return false; + }; + ["status", "outcome", "type"] + .into_iter() + .filter_map(|key| object.get(key).and_then(Value::as_str)) + .any(|status| outcomes.contains(&status.trim().to_ascii_lowercase().as_str())) +} + +fn has_structured_error(value: &Value) -> bool { + value.as_object().is_some_and(|object| { + object.get("is_error").and_then(Value::as_bool) == Some(true) + || object.get("isError").and_then(Value::as_bool) == Some(true) + || object.get("error").is_some_and(|error| { + error.as_bool() == Some(true) || nonempty_error_text(error).is_some() + }) + || has_structured_outcome(value, &["error", "failed", "failure"]) + }) +} + +fn has_structured_cancellation(value: &Value) -> bool { + value.as_object().is_some_and(|object| { + ["interrupted", "cancelled", "canceled", "aborted"] + .into_iter() + .any(|key| object.get(key).and_then(Value::as_bool) == Some(true)) + }) +} + +fn has_outcome_phrase(value: &Value, phrases: &[&str]) -> bool { + match value { + Value::String(text) => { + let text = text.to_ascii_lowercase(); + phrases.iter().any(|phrase| text.contains(phrase)) + } + Value::Array(values) => values + .iter() + .any(|value| has_outcome_phrase(value, phrases)), + Value::Object(object) => object + .values() + .any(|value| has_outcome_phrase(value, phrases)), + _ => false, + } +} diff --git a/bt-daemon/src/translate/codex.rs b/bt-daemon/src/translate/codex.rs index 40abc68d..fc4d8194 100644 --- a/bt-daemon/src/translate/codex.rs +++ b/bt-daemon/src/translate/codex.rs @@ -38,6 +38,22 @@ use serde_json::{json, Map, Value}; use std::collections::HashMap; use std::sync::{Arc, OnceLock}; +mod compact_hook; +mod payload_kind; +mod read_lines; +mod rollout_record; +mod session_start_hook; +mod subagent_start_hook; +mod turn_context_payload; +mod working_directory_payload; + +use compact_hook::CompactHook; +use read_lines::read_new_lines; +use rollout_record::RolloutRecord; +use session_start_hook::SessionStartHook; +use subagent_start_hook::SubagentStartHook; +use turn_context_payload::TurnContextPayload; + mod tool_output; const SPAWN_AGENT_TOOL: &str = "spawn_agent"; @@ -47,69 +63,6 @@ const MAX_OPEN_TOOL_SPAN_MS: i64 = 24 * 60 * 60 * 1000; /// Keep a single translator batch small even when the unread suffix is large. const CATCH_UP_BYTE_BUDGET: usize = 64 * 1024; -// Codex hooks are triggers for the rollout reader. These partial types cover -// the hook-owned correlation fields while preserving raw rollout JSON for the -// separately bounded transcript reducer. -#[derive(Deserialize, Serialize)] -struct SessionStartHook { - #[serde(default)] - source: Option, - #[serde(default)] - permission_mode: Option, -} - -#[derive(Deserialize, Serialize)] -struct CompactHook { - turn_id: String, - #[serde(default)] - trigger: Option, -} - -#[derive(Deserialize, Serialize)] -struct SubagentStartHook { - agent_id: String, - #[serde(default)] - agent_type: Option, -} - -/// The stable outer shape of a rollout JSONL row. The payload deliberately -/// stays untyped here: Codex adds response-item fields regularly and several -/// handlers preserve those native objects in span input/output. -#[derive(Deserialize, Serialize)] -struct RolloutRecord { - #[serde( - rename = "timestamp", - default, - deserialize_with = "deserialize_timestamp" - )] - timestamp_ms: Option, - #[serde(rename = "type", default)] - kind: Option, - #[serde(default)] - payload: Value, -} - -/// Event and response rows use a second discriminator inside their payload. -#[derive(Deserialize, Serialize)] -struct PayloadKind { - #[serde(rename = "type", default)] - kind: Option, -} - -#[derive(Deserialize, Serialize)] -struct WorkingDirectoryPayload { - #[serde(default)] - cwd: Option, -} - -#[derive(Deserialize, Serialize)] -struct TurnContextPayload { - #[serde(default)] - model: Option, - #[serde(default)] - turn_id: Option, -} - fn decode(value: &Value) -> Option { serde_json::from_value(value.clone()).ok() } @@ -677,10 +630,8 @@ impl CodexTranslator { let ts = rec.timestamp_ms.unwrap_or(hook_ts); let kind = rec.kind.as_deref().unwrap_or(""); let payload = &rec.payload; - if matches!(kind, "session_meta" | "turn_context") { - if let Some(cwd) = decode::(payload).and_then(|v| v.cwd) { - scope.current_cwd = Some(cwd); - } + if let Some(cwd) = rec.working_directory() { + scope.current_cwd = Some(cwd); } match kind { @@ -730,9 +681,7 @@ impl CodexTranslator { } } "event_msg" => { - let sub = decode::(payload) - .and_then(|v| v.kind) - .unwrap_or_default(); + let sub = rec.payload_kind(); match sub.as_str() { "task_started" => self.open_turn(scope, payload, ts, ops), "user_message" => self.set_turn_input(scope, payload, ops), @@ -743,9 +692,7 @@ impl CodexTranslator { } } "response_item" => { - let sub = decode::(payload) - .and_then(|v| v.kind) - .unwrap_or_default(); + let sub = rec.payload_kind(); match sub.as_str() { "message" => self.on_message(scope, payload, ts, ops), "reasoning" => self.on_reasoning(scope, payload, ts, ops), @@ -2077,168 +2024,9 @@ fn compaction_history(payload: &Value, replacement: Option<&Vec>) -> Vec< })] } -fn parse_ts(rec: &Value) -> Option { - rec.get("timestamp").and_then(normalize_timestamp) -} - -/// Deserialize Codex rollout timestamps into Unix milliseconds. Rollouts have -/// historically used RFC 3339 strings, but imported or newer producers may -/// supply numeric epoch seconds, milliseconds, microseconds, or nanoseconds. -/// Unknown values remain absent so the caller can use the hook timestamp. -fn deserialize_timestamp<'de, D>(deserializer: D) -> Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - Ok(Option::::deserialize(deserializer)? - .as_ref() - .and_then(normalize_timestamp)) -} - -fn normalize_timestamp(value: &Value) -> Option { - match value { - Value::String(value) => { - parse_rfc3339_timestamp(value).or_else(|| normalize_numeric_timestamp(value)) - } - Value::Number(value) => { - if let Some(value) = value.as_i64() { - normalize_epoch_integer(value) - } else if let Some(value) = value.as_u64() { - i64::try_from(value).ok().and_then(normalize_epoch_integer) - } else { - value.as_f64().and_then(normalize_epoch_float) - } - } - _ => None, - } -} - -fn normalize_numeric_timestamp(value: &str) -> Option { - value - .parse::() - .ok() - .and_then(normalize_epoch_integer) - .or_else(|| value.parse::().ok().and_then(normalize_epoch_float)) -} - -fn normalize_epoch_integer(value: i64) -> Option { - let magnitude = value.unsigned_abs(); - if magnitude < 100_000_000_000 { - value.checked_mul(1_000) - } else if magnitude < 100_000_000_000_000 { - Some(value) - } else if magnitude < 100_000_000_000_000_000 { - Some(value / 1_000) - } else { - Some(value / 1_000_000) - } -} - -fn normalize_epoch_float(value: f64) -> Option { - if !value.is_finite() { - return None; - } - let magnitude = value.abs(); - let milliseconds = if magnitude < 100_000_000_000.0 { - value * 1_000.0 - } else if magnitude < 100_000_000_000_000.0 { - value - } else if magnitude < 100_000_000_000_000_000.0 { - value / 1_000.0 - } else { - value / 1_000_000.0 - }; - if milliseconds < i64::MIN as f64 || milliseconds > i64::MAX as f64 { - None - } else { - Some(milliseconds.trunc() as i64) - } -} - -fn parse_rfc3339_timestamp(value: &str) -> Option { - chrono::DateTime::parse_from_rfc3339(value) - .ok() - .map(|dt| dt.timestamp_millis()) -} -#[derive(Serialize, Deserialize)] -struct ReadLines { - lines: Vec, - complete: bool, -} - -fn read_new_lines( - path: &str, - offset: &mut u64, - through_ms: Option, - through_bytes: Option, - byte_budget: usize, -) -> ReadLines { - use std::io::{BufRead, BufReader, Seek, SeekFrom}; - let Ok(mut f) = std::fs::File::open(path) else { - return ReadLines { - lines: Vec::new(), - complete: true, - }; - }; - if let Ok(meta) = f.metadata() { - if *offset > meta.len() { - *offset = 0; - } - } - if f.seek(SeekFrom::Start(*offset)).is_err() { - return ReadLines { - lines: Vec::new(), - complete: true, - }; - } - let mut reader = BufReader::new(f); - let mut lines = Vec::new(); - let mut consumed = 0usize; - loop { - if through_bytes.is_some_and(|limit| *offset >= limit) { - break; - } - if consumed >= byte_budget && !lines.is_empty() { - return ReadLines { - lines, - complete: false, - }; - } - let mut line = String::new(); - let Ok(bytes) = reader.read_line(&mut line) else { - break; - }; - if bytes == 0 || !line.ends_with('\n') { - break; - } - if through_bytes.is_some_and(|limit| offset.saturating_add(bytes as u64) > limit) { - break; - } - let trimmed = line.trim_end_matches(['\r', '\n']); - if let Some(limit) = through_ms { - if serde_json::from_str::(trimmed) - .ok() - .and_then(|record| parse_ts(&record)) - .is_some_and(|timestamp| timestamp > limit) - { - break; - } - } - *offset += bytes as u64; - consumed += bytes; - if !trimmed.trim().is_empty() { - lines.push(trimmed.to_string()); - } - } - ReadLines { - lines, - complete: true, - } -} - #[cfg(test)] mod tests { - use super::{basename, normalize_timestamp, RolloutRecord}; - use serde_json::json; + use super::basename; #[test] fn basename_accepts_unix_and_windows_paths() { @@ -2246,49 +2034,4 @@ mod tests { assert_eq!(basename(r"C:\Users\agent\project"), "project"); assert_eq!(basename(r"C:\Users\agent\project\\"), "project"); } - - #[test] - fn rollout_timestamps_normalize_supported_formats() { - let milliseconds = 1_704_067_202_000_i64; - assert_eq!( - normalize_timestamp(&json!(1_704_067_202_i64)), - Some(milliseconds) - ); - assert_eq!( - normalize_timestamp(&json!(milliseconds)), - Some(milliseconds) - ); - assert_eq!( - normalize_timestamp(&json!(1_704_067_202_000_000_i64)), - Some(milliseconds) - ); - assert_eq!( - normalize_timestamp(&json!(1_704_067_202_000_000_000_i64)), - Some(milliseconds) - ); - assert_eq!( - normalize_timestamp(&json!("2024-01-01T00:00:02Z")), - Some(milliseconds) - ); - assert_eq!( - normalize_timestamp(&json!("1704067202000")), - Some(milliseconds) - ); - assert_eq!( - normalize_timestamp(&json!(1_704_067_202.25_f64)), - Some(milliseconds + 250) - ); - assert_eq!(normalize_timestamp(&json!({ "seconds": 1 })), None); - } - - #[test] - fn rollout_record_treats_unknown_timestamp_formats_as_missing() { - let record: RolloutRecord = serde_json::from_value(json!({ - "timestamp": { "future": "format" }, - "type": "event_msg", - "payload": { "type": "task_started" }, - })) - .unwrap(); - assert_eq!(record.timestamp_ms, None); - } } diff --git a/bt-daemon/src/translate/codex/compact_hook.rs b/bt-daemon/src/translate/codex/compact_hook.rs new file mode 100644 index 00000000..50adae7d --- /dev/null +++ b/bt-daemon/src/translate/codex/compact_hook.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, Serialize)] +pub(super) struct CompactHook { + pub(super) turn_id: String, + #[serde(default)] + pub(super) trigger: Option, +} diff --git a/bt-daemon/src/translate/codex/payload_kind.rs b/bt-daemon/src/translate/codex/payload_kind.rs new file mode 100644 index 00000000..19f69ee3 --- /dev/null +++ b/bt-daemon/src/translate/codex/payload_kind.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +/// Event and response rows use a second discriminator inside their payload. +#[derive(Deserialize, Serialize)] +pub(super) struct PayloadKind { + #[serde(rename = "type", default)] + pub(super) kind: Option, +} diff --git a/bt-daemon/src/translate/codex/read_lines.rs b/bt-daemon/src/translate/codex/read_lines.rs new file mode 100644 index 00000000..03156c29 --- /dev/null +++ b/bt-daemon/src/translate/codex/read_lines.rs @@ -0,0 +1,80 @@ +//! Bounded rollout reads preserve partial lines and capture-time cutoffs. +use super::rollout_record::parse_ts; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Serialize, Deserialize)] +pub(super) struct ReadLines { + pub(super) lines: Vec, + pub(super) complete: bool, +} + +pub(super) fn read_new_lines( + path: &str, + offset: &mut u64, + through_ms: Option, + through_bytes: Option, + byte_budget: usize, +) -> ReadLines { + use std::io::{BufRead, BufReader, Seek, SeekFrom}; + let Ok(mut f) = std::fs::File::open(path) else { + return ReadLines { + lines: Vec::new(), + complete: true, + }; + }; + if let Ok(meta) = f.metadata() { + if *offset > meta.len() { + *offset = 0; + } + } + if f.seek(SeekFrom::Start(*offset)).is_err() { + return ReadLines { + lines: Vec::new(), + complete: true, + }; + } + let mut reader = BufReader::new(f); + let mut lines = Vec::new(); + let mut consumed = 0usize; + loop { + if through_bytes.is_some_and(|limit| *offset >= limit) { + break; + } + if consumed >= byte_budget && !lines.is_empty() { + return ReadLines { + lines, + complete: false, + }; + } + let mut line = String::new(); + let Ok(bytes) = reader.read_line(&mut line) else { + break; + }; + if bytes == 0 || !line.ends_with('\n') { + break; + } + if through_bytes.is_some_and(|limit| offset.saturating_add(bytes as u64) > limit) { + break; + } + let trimmed = line.trim_end_matches(['\r', '\n']); + if let Some(limit) = through_ms { + if serde_json::from_str::(trimmed) + .ok() + .and_then(|record| parse_ts(&record)) + .is_some_and(|timestamp| timestamp > limit) + { + break; + } + } + *offset += bytes as u64; + consumed += bytes; + if !trimmed.trim().is_empty() { + lines.push(trimmed.to_string()); + } + } + ReadLines { + lines, + complete: true, + } +} diff --git a/bt-daemon/src/translate/codex/rollout_record.rs b/bt-daemon/src/translate/codex/rollout_record.rs new file mode 100644 index 00000000..0279b443 --- /dev/null +++ b/bt-daemon/src/translate/codex/rollout_record.rs @@ -0,0 +1,172 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// The stable outer shape of a rollout JSONL row. The payload deliberately +/// stays untyped here: Codex adds response-item fields regularly and several +/// handlers preserve those native objects in span input/output. +#[derive(Deserialize, Serialize)] +pub(super) struct RolloutRecord { + #[serde( + rename = "timestamp", + default, + deserialize_with = "deserialize_timestamp" + )] + pub(super) timestamp_ms: Option, + #[serde(rename = "type", default)] + pub(super) kind: Option, + #[serde(default)] + pub(super) payload: Value, +} + +impl RolloutRecord { + /// Only metadata and turn-context rows establish this scope's directory. + pub(super) fn working_directory(&self) -> Option { + if matches!(self.kind.as_deref(), Some("session_meta" | "turn_context")) { + super::decode::( + &self.payload, + ) + .and_then(|payload| payload.cwd) + } else { + None + } + } + + /// Event and response rows carry a second native discriminator. A malformed + /// or missing discriminator remains an unhandled event, as with future kinds. + pub(super) fn payload_kind(&self) -> String { + super::decode::(&self.payload) + .and_then(|payload| payload.kind) + .unwrap_or_default() + } +} +pub(super) fn parse_ts(rec: &Value) -> Option { + rec.get("timestamp").and_then(normalize_timestamp) +} + +/// Deserialize Codex rollout timestamps into Unix milliseconds. Rollouts have +/// historically used RFC 3339 strings, but imported or newer producers may +/// supply numeric epoch seconds, milliseconds, microseconds, or nanoseconds. +/// Unknown values remain absent so the caller can use the hook timestamp. +fn deserialize_timestamp<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + Ok(Option::::deserialize(deserializer)? + .as_ref() + .and_then(normalize_timestamp)) +} + +fn normalize_timestamp(value: &Value) -> Option { + match value { + Value::String(value) => { + parse_rfc3339_timestamp(value).or_else(|| normalize_numeric_timestamp(value)) + } + Value::Number(value) => { + if let Some(value) = value.as_i64() { + normalize_epoch_integer(value) + } else if let Some(value) = value.as_u64() { + i64::try_from(value).ok().and_then(normalize_epoch_integer) + } else { + value.as_f64().and_then(normalize_epoch_float) + } + } + _ => None, + } +} + +fn normalize_numeric_timestamp(value: &str) -> Option { + value + .parse::() + .ok() + .and_then(normalize_epoch_integer) + .or_else(|| value.parse::().ok().and_then(normalize_epoch_float)) +} + +fn normalize_epoch_integer(value: i64) -> Option { + let magnitude = value.unsigned_abs(); + if magnitude < 100_000_000_000 { + value.checked_mul(1_000) + } else if magnitude < 100_000_000_000_000 { + Some(value) + } else if magnitude < 100_000_000_000_000_000 { + Some(value / 1_000) + } else { + Some(value / 1_000_000) + } +} + +fn normalize_epoch_float(value: f64) -> Option { + if !value.is_finite() { + return None; + } + let magnitude = value.abs(); + let milliseconds = if magnitude < 100_000_000_000.0 { + value * 1_000.0 + } else if magnitude < 100_000_000_000_000.0 { + value + } else if magnitude < 100_000_000_000_000_000.0 { + value / 1_000.0 + } else { + value / 1_000_000.0 + }; + if milliseconds < i64::MIN as f64 || milliseconds > i64::MAX as f64 { + None + } else { + Some(milliseconds.trunc() as i64) + } +} + +fn parse_rfc3339_timestamp(value: &str) -> Option { + chrono::DateTime::parse_from_rfc3339(value) + .ok() + .map(|dt| dt.timestamp_millis()) +} +#[cfg(test)] +mod tests { + use super::{normalize_timestamp, RolloutRecord}; + use serde_json::json; + #[test] + fn rollout_timestamps_normalize_supported_formats() { + let milliseconds = 1_704_067_202_000_i64; + assert_eq!( + normalize_timestamp(&json!(1_704_067_202_i64)), + Some(milliseconds) + ); + assert_eq!( + normalize_timestamp(&json!(milliseconds)), + Some(milliseconds) + ); + assert_eq!( + normalize_timestamp(&json!(1_704_067_202_000_000_i64)), + Some(milliseconds) + ); + assert_eq!( + normalize_timestamp(&json!(1_704_067_202_000_000_000_i64)), + Some(milliseconds) + ); + assert_eq!( + normalize_timestamp(&json!("2024-01-01T00:00:02Z")), + Some(milliseconds) + ); + assert_eq!( + normalize_timestamp(&json!("1704067202000")), + Some(milliseconds) + ); + assert_eq!( + normalize_timestamp(&json!(1_704_067_202.25_f64)), + Some(milliseconds + 250) + ); + assert_eq!(normalize_timestamp(&json!({ "seconds": 1 })), None); + } + + #[test] + fn rollout_record_treats_unknown_timestamp_formats_as_missing() { + let record: RolloutRecord = serde_json::from_value(json!({ + "timestamp": { "future": "format" }, + "type": "event_msg", + "payload": { "type": "task_started" }, + })) + .unwrap(); + assert_eq!(record.timestamp_ms, None); + } +} diff --git a/bt-daemon/src/translate/codex/session_start_hook.rs b/bt-daemon/src/translate/codex/session_start_hook.rs new file mode 100644 index 00000000..42390222 --- /dev/null +++ b/bt-daemon/src/translate/codex/session_start_hook.rs @@ -0,0 +1,12 @@ +use serde::{Deserialize, Serialize}; + +// Codex hooks are triggers for the rollout reader. These partial types cover +// the hook-owned correlation fields while preserving raw rollout JSON for the +// separately bounded transcript reducer. +#[derive(Deserialize, Serialize)] +pub(super) struct SessionStartHook { + #[serde(default)] + pub(super) source: Option, + #[serde(default)] + pub(super) permission_mode: Option, +} diff --git a/bt-daemon/src/translate/codex/subagent_start_hook.rs b/bt-daemon/src/translate/codex/subagent_start_hook.rs new file mode 100644 index 00000000..ff6000ea --- /dev/null +++ b/bt-daemon/src/translate/codex/subagent_start_hook.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Deserialize, Serialize)] +pub(super) struct SubagentStartHook { + pub(super) agent_id: String, + #[serde(default)] + pub(super) agent_type: Option, +} diff --git a/bt-daemon/src/translate/codex/turn_context_payload.rs b/bt-daemon/src/translate/codex/turn_context_payload.rs new file mode 100644 index 00000000..15b1e49f --- /dev/null +++ b/bt-daemon/src/translate/codex/turn_context_payload.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, Serialize)] +pub(super) struct TurnContextPayload { + #[serde(default)] + pub(super) model: Option, + #[serde(default)] + pub(super) turn_id: Option, +} diff --git a/bt-daemon/src/translate/codex/working_directory_payload.rs b/bt-daemon/src/translate/codex/working_directory_payload.rs new file mode 100644 index 00000000..09eecfed --- /dev/null +++ b/bt-daemon/src/translate/codex/working_directory_payload.rs @@ -0,0 +1,7 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, Serialize)] +pub(super) struct WorkingDirectoryPayload { + #[serde(default)] + pub(super) cwd: Option, +} diff --git a/bt-daemon/src/wire/methods.rs b/bt-daemon/src/wire/methods.rs deleted file mode 100644 index 0f331753..00000000 --- a/bt-daemon/src/wire/methods.rs +++ /dev/null @@ -1,185 +0,0 @@ -//! Method names and their param/result types. - -use serde::{Deserialize, Serialize}; - -/// Method name constants — one source of truth for both sides. -pub mod method { - pub const INITIALIZE: &str = "initialize"; - pub const EVENT_LOG: &str = "event.log"; - pub const SESSION_FLUSH: &str = "session.flush"; - pub const MANAGED_RUN_FLUSH: &str = "managed_run.flush"; - pub const STATUS_GET: &str = "status.get"; - pub const AUTH_DIAGNOSE: &str = "auth.diagnose"; - pub const DAEMON_SHUTDOWN: &str = "daemon.shutdown"; - pub const IMPORT_FINISH: &str = "import.finish"; - pub const IMPORT_RESET: &str = "import.reset"; -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct InitializeParams { - pub protocol_version: u32, - pub client: ClientInfo, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ClientInfo { - pub source: String, - /// Version of the executable that would host a replacement daemon. - /// Distinct from the instrumentation plugin version below. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub daemon_version: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub plugin_version: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub pid: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct InitializeResult { - pub protocol_version: u32, - pub daemon_version: String, - #[serde(default)] - pub capabilities: Capabilities, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct Capabilities { - #[serde(default)] - pub sources: Vec, - /// A failed event closes the connection before any later event is accepted. - #[serde(default)] - pub ordered_event_pipeline: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EventLogResult { - pub accepted: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct FlushParams { - pub session_id: String, - #[serde(default = "default_flush_timeout_ms")] - pub timeout_ms: u64, -} - -/// Deliver one imported source session's captured events through its route. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ImportFinishParams { - pub source: String, - pub session_id: String, - pub route: crate::wire::SessionRoute, - /// Close the session's open spans, as a completed transcript does. - /// Otherwise only flush, leaving it open for later capture. - pub finalize: bool, - #[serde(default = "default_flush_timeout_ms")] - pub timeout_ms: u64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ImportFinishResult { - pub flushed: bool, - pub pending: u64, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub root_span_id: Option, - /// Distinct spans this route has delivered since its actor started. - pub span_count: u64, -} - -/// Restart translation for a source session whose transcript was rewritten. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ImportResetParams { - pub source: String, - pub session_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ManagedRunFlushParams { - pub managed_run_id: String, - #[serde(default = "default_flush_timeout_ms")] - pub timeout_ms: u64, -} - -fn default_flush_timeout_ms() -> u64 { - 10_000 -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct FlushResult { - pub flushed: bool, - pub pending: u64, - #[serde(default)] - pub accepted_sessions: u64, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct StatusParams { - /// Omit for daemon-wide status. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub session_id: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct StatusResult { - pub daemon_version: String, - pub uptime_ms: u64, - pub sessions: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RecoveryInfo { - /// Retry attempts already made for this held delivery. - #[serde(default)] - pub attempt: u32, - pub stage: String, - pub position: u64, - pub reason: String, - pub retry: String, - pub eligible: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SessionStatus { - pub session_id: String, - pub source: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub route: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub recovery: Option, - pub queued: u64, - /// Canonical span operations not yet acknowledged for this route. Distinct - /// from native events still awaiting translation and from unique spans. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub queued_span_ops: Option, - pub spans_emitted: u64, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub permalink: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub last_error: Option, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct AuthDiagnoseParams { - #[serde(default)] - pub auth: crate::wire::AuthSelection, -} - -/// The daemon's own resolution of a route's credentials. Never carries the -/// credential itself. Resolution succeeded when `error` is absent. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct AuthDiagnoseResult { - /// The canonical selection the daemon resolved. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub selection: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub org_name: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub expires_at_ms: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub error: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ShutdownResult { - pub ok: bool, -} diff --git a/bt-daemon/src/wire/methods/auth_diagnose_params.rs b/bt-daemon/src/wire/methods/auth_diagnose_params.rs new file mode 100644 index 00000000..02253947 --- /dev/null +++ b/bt-daemon/src/wire/methods/auth_diagnose_params.rs @@ -0,0 +1,7 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct AuthDiagnoseParams { + #[serde(default)] + pub auth: crate::wire::AuthSelection, +} diff --git a/bt-daemon/src/wire/methods/auth_diagnose_result.rs b/bt-daemon/src/wire/methods/auth_diagnose_result.rs new file mode 100644 index 00000000..34afceb4 --- /dev/null +++ b/bt-daemon/src/wire/methods/auth_diagnose_result.rs @@ -0,0 +1,16 @@ +use serde::{Deserialize, Serialize}; + +/// The daemon's own resolution of a route's credentials. Never carries the +/// credential itself. Resolution succeeded when `error` is absent. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct AuthDiagnoseResult { + /// The canonical selection the daemon resolved. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub selection: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub org_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expires_at_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} diff --git a/bt-daemon/src/wire/methods/capabilities.rs b/bt-daemon/src/wire/methods/capabilities.rs new file mode 100644 index 00000000..9c4da3c8 --- /dev/null +++ b/bt-daemon/src/wire/methods/capabilities.rs @@ -0,0 +1,10 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Capabilities { + #[serde(default)] + pub sources: Vec, + /// A failed event closes the connection before any later event is accepted. + #[serde(default)] + pub ordered_event_pipeline: bool, +} diff --git a/bt-daemon/src/wire/methods/client_info.rs b/bt-daemon/src/wire/methods/client_info.rs new file mode 100644 index 00000000..d4cc6edb --- /dev/null +++ b/bt-daemon/src/wire/methods/client_info.rs @@ -0,0 +1,14 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ClientInfo { + pub source: String, + /// Version of the executable that would host a replacement daemon. + /// Distinct from the instrumentation plugin version below. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub daemon_version: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plugin_version: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pid: Option, +} diff --git a/bt-daemon/src/wire/methods/event_log_result.rs b/bt-daemon/src/wire/methods/event_log_result.rs new file mode 100644 index 00000000..a154403d --- /dev/null +++ b/bt-daemon/src/wire/methods/event_log_result.rs @@ -0,0 +1,6 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EventLogResult { + pub accepted: bool, +} diff --git a/bt-daemon/src/wire/methods/flush_params.rs b/bt-daemon/src/wire/methods/flush_params.rs new file mode 100644 index 00000000..0b1c0317 --- /dev/null +++ b/bt-daemon/src/wire/methods/flush_params.rs @@ -0,0 +1,9 @@ +use super::default_flush_timeout_ms; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FlushParams { + pub session_id: String, + #[serde(default = "default_flush_timeout_ms")] + pub timeout_ms: u64, +} diff --git a/bt-daemon/src/wire/methods/flush_result.rs b/bt-daemon/src/wire/methods/flush_result.rs new file mode 100644 index 00000000..330c3623 --- /dev/null +++ b/bt-daemon/src/wire/methods/flush_result.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FlushResult { + pub flushed: bool, + pub pending: u64, + #[serde(default)] + pub accepted_sessions: u64, +} diff --git a/bt-daemon/src/wire/methods/import_finish_params.rs b/bt-daemon/src/wire/methods/import_finish_params.rs new file mode 100644 index 00000000..d837e345 --- /dev/null +++ b/bt-daemon/src/wire/methods/import_finish_params.rs @@ -0,0 +1,15 @@ +use super::default_flush_timeout_ms; +use serde::{Deserialize, Serialize}; + +/// Deliver one imported source session's captured events through its route. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ImportFinishParams { + pub source: String, + pub session_id: String, + pub route: crate::wire::SessionRoute, + /// Close the session's open spans, as a completed transcript does. + /// Otherwise only flush, leaving it open for later capture. + pub finalize: bool, + #[serde(default = "default_flush_timeout_ms")] + pub timeout_ms: u64, +} diff --git a/bt-daemon/src/wire/methods/import_finish_result.rs b/bt-daemon/src/wire/methods/import_finish_result.rs new file mode 100644 index 00000000..43c78467 --- /dev/null +++ b/bt-daemon/src/wire/methods/import_finish_result.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ImportFinishResult { + pub flushed: bool, + pub pending: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub root_span_id: Option, + /// Distinct spans this route has delivered since its actor started. + pub span_count: u64, +} diff --git a/bt-daemon/src/wire/methods/import_reset_params.rs b/bt-daemon/src/wire/methods/import_reset_params.rs new file mode 100644 index 00000000..036c4505 --- /dev/null +++ b/bt-daemon/src/wire/methods/import_reset_params.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +/// Restart translation for a source session whose transcript was rewritten. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ImportResetParams { + pub source: String, + pub session_id: String, +} diff --git a/bt-daemon/src/wire/methods/initialize_params.rs b/bt-daemon/src/wire/methods/initialize_params.rs new file mode 100644 index 00000000..8fed5b59 --- /dev/null +++ b/bt-daemon/src/wire/methods/initialize_params.rs @@ -0,0 +1,8 @@ +use super::ClientInfo; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct InitializeParams { + pub protocol_version: u32, + pub client: ClientInfo, +} diff --git a/bt-daemon/src/wire/methods/initialize_result.rs b/bt-daemon/src/wire/methods/initialize_result.rs new file mode 100644 index 00000000..f103fe01 --- /dev/null +++ b/bt-daemon/src/wire/methods/initialize_result.rs @@ -0,0 +1,10 @@ +use super::Capabilities; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct InitializeResult { + pub protocol_version: u32, + pub daemon_version: String, + #[serde(default)] + pub capabilities: Capabilities, +} diff --git a/bt-daemon/src/wire/methods/managed_run_flush_params.rs b/bt-daemon/src/wire/methods/managed_run_flush_params.rs new file mode 100644 index 00000000..d3a2b93f --- /dev/null +++ b/bt-daemon/src/wire/methods/managed_run_flush_params.rs @@ -0,0 +1,9 @@ +use super::default_flush_timeout_ms; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ManagedRunFlushParams { + pub managed_run_id: String, + #[serde(default = "default_flush_timeout_ms")] + pub timeout_ms: u64, +} diff --git a/bt-daemon/src/wire/methods/method.rs b/bt-daemon/src/wire/methods/method.rs new file mode 100644 index 00000000..f00ef316 --- /dev/null +++ b/bt-daemon/src/wire/methods/method.rs @@ -0,0 +1,10 @@ +/// Method names shared by clients and the daemon. +pub const INITIALIZE: &str = "initialize"; +pub const EVENT_LOG: &str = "event.log"; +pub const SESSION_FLUSH: &str = "session.flush"; +pub const MANAGED_RUN_FLUSH: &str = "managed_run.flush"; +pub const STATUS_GET: &str = "status.get"; +pub const AUTH_DIAGNOSE: &str = "auth.diagnose"; +pub const DAEMON_SHUTDOWN: &str = "daemon.shutdown"; +pub const IMPORT_FINISH: &str = "import.finish"; +pub const IMPORT_RESET: &str = "import.reset"; diff --git a/bt-daemon/src/wire/methods/mod.rs b/bt-daemon/src/wire/methods/mod.rs new file mode 100644 index 00000000..a7ca89d9 --- /dev/null +++ b/bt-daemon/src/wire/methods/mod.rs @@ -0,0 +1,44 @@ +//! Request and result schemas, each owned by its matching type module. + +mod auth_diagnose_params; +mod auth_diagnose_result; +mod capabilities; +mod client_info; +mod event_log_result; +mod flush_params; +mod flush_result; +mod import_finish_params; +mod import_finish_result; +mod import_reset_params; +mod initialize_params; +mod initialize_result; +mod managed_run_flush_params; +pub mod method; +mod recovery_info; +mod session_status; +mod shutdown_result; +mod status_params; +mod status_result; + +pub use auth_diagnose_params::AuthDiagnoseParams; +pub use auth_diagnose_result::AuthDiagnoseResult; +pub use capabilities::Capabilities; +pub use client_info::ClientInfo; +pub use event_log_result::EventLogResult; +pub use flush_params::FlushParams; +pub use flush_result::FlushResult; +pub use import_finish_params::ImportFinishParams; +pub use import_finish_result::ImportFinishResult; +pub use import_reset_params::ImportResetParams; +pub use initialize_params::InitializeParams; +pub use initialize_result::InitializeResult; +pub use managed_run_flush_params::ManagedRunFlushParams; +pub use recovery_info::RecoveryInfo; +pub use session_status::SessionStatus; +pub use shutdown_result::ShutdownResult; +pub use status_params::StatusParams; +pub use status_result::StatusResult; + +fn default_flush_timeout_ms() -> u64 { + 10_000 +} diff --git a/bt-daemon/src/wire/methods/recovery_info.rs b/bt-daemon/src/wire/methods/recovery_info.rs new file mode 100644 index 00000000..ec93d39a --- /dev/null +++ b/bt-daemon/src/wire/methods/recovery_info.rs @@ -0,0 +1,13 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RecoveryInfo { + /// Retry attempts already made for this held delivery. + #[serde(default)] + pub attempt: u32, + pub stage: String, + pub position: u64, + pub reason: String, + pub retry: String, + pub eligible: bool, +} diff --git a/bt-daemon/src/wire/methods/session_status.rs b/bt-daemon/src/wire/methods/session_status.rs new file mode 100644 index 00000000..5ea4afea --- /dev/null +++ b/bt-daemon/src/wire/methods/session_status.rs @@ -0,0 +1,22 @@ +use super::RecoveryInfo; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SessionStatus { + pub session_id: String, + pub source: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub route: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub recovery: Option, + pub queued: u64, + /// Canonical span operations not yet acknowledged for this route. Distinct + /// from native events still awaiting translation and from unique spans. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub queued_span_ops: Option, + pub spans_emitted: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub permalink: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_error: Option, +} diff --git a/bt-daemon/src/wire/methods/shutdown_result.rs b/bt-daemon/src/wire/methods/shutdown_result.rs new file mode 100644 index 00000000..a8e80da1 --- /dev/null +++ b/bt-daemon/src/wire/methods/shutdown_result.rs @@ -0,0 +1,6 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ShutdownResult { + pub ok: bool, +} diff --git a/bt-daemon/src/wire/methods/status_params.rs b/bt-daemon/src/wire/methods/status_params.rs new file mode 100644 index 00000000..4e1d29c1 --- /dev/null +++ b/bt-daemon/src/wire/methods/status_params.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct StatusParams { + /// Omit for daemon-wide status. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session_id: Option, +} diff --git a/bt-daemon/src/wire/methods/status_result.rs b/bt-daemon/src/wire/methods/status_result.rs new file mode 100644 index 00000000..fba608f2 --- /dev/null +++ b/bt-daemon/src/wire/methods/status_result.rs @@ -0,0 +1,9 @@ +use super::SessionStatus; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct StatusResult { + pub daemon_version: String, + pub uptime_ms: u64, + pub sessions: Vec, +} diff --git a/bt-daemon/src/wire/rpc.rs b/bt-daemon/src/wire/rpc.rs deleted file mode 100644 index a87d93fa..00000000 --- a/bt-daemon/src/wire/rpc.rs +++ /dev/null @@ -1,247 +0,0 @@ -//! JSON-RPC 2.0 message types, newline-delimited on the wire. - -use serde::{Deserialize, Serialize}; - -/// A JSON-RPC request id: an integer or a string. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(untagged)] -pub enum RequestId { - Int(i64), - Str(String), -} - -/// A single JSON-RPC frame. Untagged so one type round-trips a request, a -/// response, or a notification; disambiguated by which fields are present. -/// -/// Note: `Response` must come before `Notification` in the enum. A response -/// carries `id` but no `method`; a notification carries `method` but no `id`; -/// a request carries both. Serde's untagged matching tries variants in order, -/// so ordering here plus `deny_unknown_fields`-free structs keeps them -/// unambiguous. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum Message { - Request(Request), - Response(Response), - Notification(Notification), -} - -impl Message { - /// Parse one newline-delimited frame. - pub fn from_line(line: &str) -> Result { - serde_json::from_str(line) - } - - /// Serialize to a single line (no trailing newline). - pub fn to_line(&self) -> Result { - serde_json::to_string(self) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Request { - pub jsonrpc: JsonRpcV2, - pub id: RequestId, - pub method: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub params: Option, -} - -impl Request { - pub fn new(id: RequestId, method: impl Into, params: serde_json::Value) -> Self { - Self { - jsonrpc: JsonRpcV2, - id, - method: method.into(), - params: Some(params), - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Notification { - pub jsonrpc: JsonRpcV2, - pub method: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub params: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Response { - pub jsonrpc: JsonRpcV2, - pub id: RequestId, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub result: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub error: Option, -} - -impl Response { - /// Serialize a successful result, returning an internal RPC error if serialization fails. - pub(crate) fn serialized(id: RequestId, result: impl Serialize) -> Self { - match serde_json::to_value(result) { - Ok(value) => Self::ok(id, value), - Err(error) => Self::err( - id, - RpcError::new( - error_code::INTERNAL, - format!("could not serialize RPC response: {error}"), - ), - ), - } - } - - pub fn ok(id: RequestId, result: serde_json::Value) -> Self { - Self { - jsonrpc: JsonRpcV2, - id, - result: Some(result), - error: None, - } - } - - pub fn err(id: RequestId, error: RpcError) -> Self { - Self { - jsonrpc: JsonRpcV2, - id, - result: None, - error: Some(error), - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RpcError { - pub code: i32, - pub message: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub data: Option, -} - -impl RpcError { - pub fn new(code: i32, message: impl Into) -> Self { - Self { - code, - message: message.into(), - data: None, - } - } -} - -/// Reserved JSON-RPC error codes plus the application range. -pub mod error_code { - pub const PARSE: i32 = -32700; - pub const INVALID_REQUEST: i32 = -32600; - pub const METHOD_NOT_FOUND: i32 = -32601; - pub const INVALID_PARAMS: i32 = -32602; - pub const INTERNAL: i32 = -32603; - /// Application errors: -32000 ..= -32099. - pub const APP: i32 = -32000; -} - -/// A zero-sized marker that serializes to the string `"2.0"` and refuses any -/// other value, so the `jsonrpc` field is validated for free. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct JsonRpcV2; - -impl Serialize for JsonRpcV2 { - fn serialize(&self, s: S) -> Result { - s.serialize_str("2.0") - } -} - -impl<'de> Deserialize<'de> for JsonRpcV2 { - fn deserialize>(d: D) -> Result { - let v = String::deserialize(d)?; - if v == "2.0" { - Ok(JsonRpcV2) - } else { - Err(serde::de::Error::custom(format!( - "unsupported jsonrpc version {v:?}" - ))) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn result_serialization_failure_returns_internal_error() { - struct FailingResult; - impl Serialize for FailingResult { - fn serialize(&self, _: S) -> Result { - Err(serde::ser::Error::custom("fixture serialization failure")) - } - } - let response = Response::serialized(RequestId::Int(17), FailingResult); - assert_eq!(response.id, RequestId::Int(17)); - assert!(response.result.is_none()); - let error = response.error.unwrap(); - assert_eq!(error.code, error_code::INTERNAL); - assert!(error.message.contains("fixture serialization failure")); - let line = Message::Response(Response::serialized(RequestId::Int(17), FailingResult)) - .to_line() - .unwrap(); - assert!(matches!( - Message::from_line(&line).unwrap(), - Message::Response(_) - )); - } - - #[test] - fn result_serialization_preserves_successful_payload() { - let result = serde_json::json!({"accepted": true}); - let response = Response::serialized(RequestId::Int(18), &result); - assert_eq!(response.id, RequestId::Int(18)); - assert_eq!(response.result, Some(result)); - assert!(response.error.is_none()); - } - - #[test] - fn request_round_trips() { - let req = Request::new( - RequestId::Int(7), - "event.log", - serde_json::json!({ "a": 1 }), - ); - let line = Message::Request(req).to_line().unwrap(); - match Message::from_line(&line).unwrap() { - Message::Request(r) => { - assert_eq!(r.method, "event.log"); - assert_eq!(r.id, RequestId::Int(7)); - } - other => panic!("expected request, got {other:?}"), - } - } - - #[test] - fn response_and_notification_disambiguate() { - let resp = Message::Response(Response::ok(RequestId::Int(1), serde_json::json!({}))) - .to_line() - .unwrap(); - assert!(matches!( - Message::from_line(&resp).unwrap(), - Message::Response(_) - )); - - let note = Message::Notification(Notification { - jsonrpc: JsonRpcV2, - method: "event.log".into(), - params: Some(serde_json::json!({})), - }) - .to_line() - .unwrap(); - assert!(matches!( - Message::from_line(¬e).unwrap(), - Message::Notification(_) - )); - } - - #[test] - fn bad_jsonrpc_version_rejected() { - let line = r#"{"jsonrpc":"1.0","id":1,"method":"x"}"#; - assert!(Message::from_line(line).is_err()); - } -} diff --git a/bt-daemon/src/wire/rpc/error_code.rs b/bt-daemon/src/wire/rpc/error_code.rs new file mode 100644 index 00000000..641021ca --- /dev/null +++ b/bt-daemon/src/wire/rpc/error_code.rs @@ -0,0 +1,9 @@ +//! Reserved JSON-RPC error codes and application errors. + +pub const PARSE: i32 = -32700; +pub const INVALID_REQUEST: i32 = -32600; +pub const METHOD_NOT_FOUND: i32 = -32601; +pub const INVALID_PARAMS: i32 = -32602; +pub const INTERNAL: i32 = -32603; +/// Application errors: -32000 ..= -32099. +pub const APP: i32 = -32000; diff --git a/bt-daemon/src/wire/rpc/json_rpc_v2.rs b/bt-daemon/src/wire/rpc/json_rpc_v2.rs new file mode 100644 index 00000000..b804e7ec --- /dev/null +++ b/bt-daemon/src/wire/rpc/json_rpc_v2.rs @@ -0,0 +1,25 @@ +use serde::{Deserialize, Serialize}; + +/// A zero-sized marker that serializes to the string `"2.0"` and refuses any +/// other value, so the `jsonrpc` field is validated for free. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct JsonRpcV2; + +impl Serialize for JsonRpcV2 { + fn serialize(&self, s: S) -> Result { + s.serialize_str("2.0") + } +} + +impl<'de> Deserialize<'de> for JsonRpcV2 { + fn deserialize>(d: D) -> Result { + let v = String::deserialize(d)?; + if v == "2.0" { + Ok(JsonRpcV2) + } else { + Err(serde::de::Error::custom(format!( + "unsupported jsonrpc version {v:?}" + ))) + } + } +} diff --git a/bt-daemon/src/wire/rpc/message.rs b/bt-daemon/src/wire/rpc/message.rs new file mode 100644 index 00000000..5158c0c7 --- /dev/null +++ b/bt-daemon/src/wire/rpc/message.rs @@ -0,0 +1,30 @@ +use super::{Notification, Request, Response}; +use serde::{Deserialize, Serialize}; + +/// A single JSON-RPC frame. Untagged so one type round-trips a request, a +/// response, or a notification; disambiguated by which fields are present. +/// +/// Note: `Response` must come before `Notification` in the enum. A response +/// carries `id` but no `method`; a notification carries `method` but no `id`; +/// a request carries both. Serde's untagged matching tries variants in order, +/// so ordering here plus `deny_unknown_fields`-free structs keeps them +/// unambiguous. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum Message { + Request(Request), + Response(Response), + Notification(Notification), +} + +impl Message { + /// Parse one newline-delimited frame. + pub fn from_line(line: &str) -> Result { + serde_json::from_str(line) + } + + /// Serialize to a single line (no trailing newline). + pub fn to_line(&self) -> Result { + serde_json::to_string(self) + } +} diff --git a/bt-daemon/src/wire/rpc/mod.rs b/bt-daemon/src/wire/rpc/mod.rs new file mode 100644 index 00000000..efc2c83d --- /dev/null +++ b/bt-daemon/src/wire/rpc/mod.rs @@ -0,0 +1,20 @@ +//! JSON-RPC framing with each frame and codec owned by its type. + +pub mod error_code; +mod json_rpc_v2; +mod message; +mod notification; +mod request; +mod request_id; +mod response; +mod rpc_error; +#[cfg(test)] +mod tests; + +pub use json_rpc_v2::JsonRpcV2; +pub use message::Message; +pub use notification::Notification; +pub use request::Request; +pub use request_id::RequestId; +pub use response::Response; +pub use rpc_error::RpcError; diff --git a/bt-daemon/src/wire/rpc/notification.rs b/bt-daemon/src/wire/rpc/notification.rs new file mode 100644 index 00000000..f659ed6c --- /dev/null +++ b/bt-daemon/src/wire/rpc/notification.rs @@ -0,0 +1,10 @@ +use super::JsonRpcV2; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Notification { + pub jsonrpc: JsonRpcV2, + pub method: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub params: Option, +} diff --git a/bt-daemon/src/wire/rpc/request.rs b/bt-daemon/src/wire/rpc/request.rs new file mode 100644 index 00000000..6a2fa8c6 --- /dev/null +++ b/bt-daemon/src/wire/rpc/request.rs @@ -0,0 +1,22 @@ +use super::{JsonRpcV2, RequestId}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Request { + pub jsonrpc: JsonRpcV2, + pub id: RequestId, + pub method: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub params: Option, +} + +impl Request { + pub fn new(id: RequestId, method: impl Into, params: serde_json::Value) -> Self { + Self { + jsonrpc: JsonRpcV2, + id, + method: method.into(), + params: Some(params), + } + } +} diff --git a/bt-daemon/src/wire/rpc/request_id.rs b/bt-daemon/src/wire/rpc/request_id.rs new file mode 100644 index 00000000..2e536b7f --- /dev/null +++ b/bt-daemon/src/wire/rpc/request_id.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +/// A JSON-RPC request id: an integer or a string. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RequestId { + Int(i64), + Str(String), +} diff --git a/bt-daemon/src/wire/rpc/response.rs b/bt-daemon/src/wire/rpc/response.rs new file mode 100644 index 00000000..5de371d1 --- /dev/null +++ b/bt-daemon/src/wire/rpc/response.rs @@ -0,0 +1,46 @@ +use super::{error_code, JsonRpcV2, RequestId, RpcError}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Response { + pub jsonrpc: JsonRpcV2, + pub id: RequestId, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub result: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl Response { + /// Serialize a successful result, returning an internal RPC error if serialization fails. + pub(crate) fn serialized(id: RequestId, result: impl Serialize) -> Self { + match serde_json::to_value(result) { + Ok(value) => Self::ok(id, value), + Err(error) => Self::err( + id, + RpcError::new( + error_code::INTERNAL, + format!("could not serialize RPC response: {error}"), + ), + ), + } + } + + pub fn ok(id: RequestId, result: serde_json::Value) -> Self { + Self { + jsonrpc: JsonRpcV2, + id, + result: Some(result), + error: None, + } + } + + pub fn err(id: RequestId, error: RpcError) -> Self { + Self { + jsonrpc: JsonRpcV2, + id, + result: None, + error: Some(error), + } + } +} diff --git a/bt-daemon/src/wire/rpc/rpc_error.rs b/bt-daemon/src/wire/rpc/rpc_error.rs new file mode 100644 index 00000000..5b2b6856 --- /dev/null +++ b/bt-daemon/src/wire/rpc/rpc_error.rs @@ -0,0 +1,19 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RpcError { + pub code: i32, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub data: Option, +} + +impl RpcError { + pub fn new(code: i32, message: impl Into) -> Self { + Self { + code, + message: message.into(), + data: None, + } + } +} diff --git a/bt-daemon/src/wire/rpc/tests.rs b/bt-daemon/src/wire/rpc/tests.rs new file mode 100644 index 00000000..8563f87b --- /dev/null +++ b/bt-daemon/src/wire/rpc/tests.rs @@ -0,0 +1,80 @@ +use super::*; +use serde::Serialize; + +#[test] +fn result_serialization_failure_returns_internal_error() { + struct FailingResult; + impl Serialize for FailingResult { + fn serialize(&self, _: S) -> Result { + Err(serde::ser::Error::custom("fixture serialization failure")) + } + } + let response = Response::serialized(RequestId::Int(17), FailingResult); + assert_eq!(response.id, RequestId::Int(17)); + assert!(response.result.is_none()); + let error = response.error.unwrap(); + assert_eq!(error.code, error_code::INTERNAL); + assert!(error.message.contains("fixture serialization failure")); + let line = Message::Response(Response::serialized(RequestId::Int(17), FailingResult)) + .to_line() + .unwrap(); + assert!(matches!( + Message::from_line(&line).unwrap(), + Message::Response(_) + )); +} + +#[test] +fn result_serialization_preserves_successful_payload() { + let result = serde_json::json!({"accepted": true}); + let response = Response::serialized(RequestId::Int(18), &result); + assert_eq!(response.id, RequestId::Int(18)); + assert_eq!(response.result, Some(result)); + assert!(response.error.is_none()); +} + +#[test] +fn request_round_trips() { + let req = Request::new( + RequestId::Int(7), + "event.log", + serde_json::json!({ "a": 1 }), + ); + let line = Message::Request(req).to_line().unwrap(); + match Message::from_line(&line).unwrap() { + Message::Request(r) => { + assert_eq!(r.method, "event.log"); + assert_eq!(r.id, RequestId::Int(7)); + } + other => panic!("expected request, got {other:?}"), + } +} + +#[test] +fn response_and_notification_disambiguate() { + let resp = Message::Response(Response::ok(RequestId::Int(1), serde_json::json!({}))) + .to_line() + .unwrap(); + assert!(matches!( + Message::from_line(&resp).unwrap(), + Message::Response(_) + )); + + let note = Message::Notification(Notification { + jsonrpc: JsonRpcV2, + method: "event.log".into(), + params: Some(serde_json::json!({})), + }) + .to_line() + .unwrap(); + assert!(matches!( + Message::from_line(¬e).unwrap(), + Message::Notification(_) + )); +} + +#[test] +fn bad_jsonrpc_version_rejected() { + let line = r#"{"jsonrpc":"1.0","id":1,"method":"x"}"#; + assert!(Message::from_line(line).is_err()); +} diff --git a/bt-daemon/tests/root_provenance.rs b/bt-daemon/tests/root_provenance.rs index af0bd5aa..81069411 100644 --- a/bt-daemon/tests/root_provenance.rs +++ b/bt-daemon/tests/root_provenance.rs @@ -453,7 +453,10 @@ async fn legacy_acknowledged_spans_receive_late_updates_without_inventing_origin .any(|row| row["span_id"] == *span && row["metrics"]["end"] == 1.0)); } - let data_dir = tmp.path().join("data"); + // Build the legacy fixture independently of the modern daemon's SQLite + // files, which can still be closing on Windows after shutdown returns. + let legacy = tempfile::tempdir().unwrap(); + let data_dir = legacy.path().join("data"); let journal = source_journal_path(&data_dir, "claude-code", session); // Model a released pre-SpanOp-journal daemon: accepted native history and // a legacy delivery checkpoint, with no newer durable partition. @@ -466,11 +469,10 @@ async fn legacy_acknowledged_spans_receive_late_updates_without_inventing_origin let through = history.len() as u64; history.push_str(&format!("{}\n",json!({"_bt_record_type":"delivery_checkpoint", "route":capture("UserPromptSubmit","v1","native1",1_000).route, "through":through}))); std::fs::write(&journal, &history).unwrap(); - std::fs::remove_dir_all(data_dir.join("pipeline")).unwrap(); let acknowledged_history = history.into_bytes(); assert_eq!(std::fs::read(&journal).unwrap(), acknowledged_history); - let second = Daemon::start(tmp.path(), &server, "bt2").await; + let second = Daemon::start(legacy.path(), &server, "bt2").await; let mut late_stop = capture("Stop", "v2", "native2", 2_000); late_stop.payload["last_assistant_message"] = json!("late legacy answer"); second.send(&late_stop).await; @@ -529,7 +531,7 @@ async fn legacy_acknowledged_spans_receive_late_updates_without_inventing_origin // Repeated recovery must not turn historical capture versions into a // fabricated birth snapshot, or restore SDK provenance on the next merge. let before_restart = rows.len(); - let third = Daemon::start(tmp.path(), &server, "bt3").await; + let third = Daemon::start(legacy.path(), &server, "bt3").await; third .send(&capture("SessionEnd", "v5", "native5", 5_000)) .await;