diff --git a/AGENTS.md b/AGENTS.md index 7e83ef3c..32b6cc20 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,6 +53,13 @@ that flexibility; do not use an opaque JSON fallback for a known schema merely to avoid modeling it. Preserve native format variants and unknown extensions explicitly when introducing shared types. +Put shared schema interpretation, validated lookup, lossless edits, and common +projections on the type that owns those rules. Keep filesystem, credential, +process, and event-ordering policy in the services that coordinate them. Organize +shared schemas around one primary owner per file, with small private companion +types alongside that owner. Keep single-use transport shapes data-only when +methods would merely duplicate field access. + Install the pinned tools with [mise](https://mise.jdx.dev). `mise install` reads `.tool-versions` and `mise.toml`, then runs `make install-deps`: diff --git a/bt-daemon/src/agents/antigravity/schema/mod.rs b/bt-daemon/src/agents/antigravity/schema/mod.rs new file mode 100644 index 00000000..c4987942 --- /dev/null +++ b/bt-daemon/src/agents/antigravity/schema/mod.rs @@ -0,0 +1,27 @@ +//! Antigravity native records shared by live translation and transcript import. +use serde::Deserialize; + +mod tool_call; +mod tool_calls; +mod transcript_record; + +pub(crate) use tool_call::ToolCall; +pub(crate) use tool_calls::ToolCalls; +pub(crate) use transcript_record::TranscriptRecord; + +pub(crate) fn optional_integer<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Integer { + Number(i64), + Text(String), + } + Option::::deserialize(deserializer)? + .map(|value| match value { + Integer::Number(value) => Ok(value), + Integer::Text(value) => value.parse().map_err(serde::de::Error::custom), + }) + .transpose() +} diff --git a/bt-daemon/src/agents/antigravity/schema/tool_call.rs b/bt-daemon/src/agents/antigravity/schema/tool_call.rs new file mode 100644 index 00000000..ee178fb6 --- /dev/null +++ b/bt-daemon/src/agents/antigravity/schema/tool_call.rs @@ -0,0 +1,26 @@ +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Serialize, Deserialize)] +pub(crate) struct ToolCall { + #[serde(default, alias = "tool_name", alias = "toolName")] + pub name: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "arguments", + alias = "input", + deserialize_with = "crate::agents::schema::deserialize_present" + )] + pub args: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "result", + deserialize_with = "crate::agents::schema::deserialize_present" + )] + pub output: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} diff --git a/bt-daemon/src/agents/antigravity/schema/tool_calls.rs b/bt-daemon/src/agents/antigravity/schema/tool_calls.rs new file mode 100644 index 00000000..f7961339 --- /dev/null +++ b/bt-daemon/src/agents/antigravity/schema/tool_calls.rs @@ -0,0 +1,17 @@ +use super::ToolCall; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum ToolCalls { + Many(Vec), + One(ToolCall), +} +impl ToolCalls { + pub fn iter(&self) -> std::slice::Iter<'_, ToolCall> { + match self { + Self::Many(calls) => calls.iter(), + Self::One(call) => std::slice::from_ref(call).iter(), + } + } +} diff --git a/bt-daemon/src/agents/antigravity/schema.rs b/bt-daemon/src/agents/antigravity/schema/transcript_record.rs similarity index 59% rename from bt-daemon/src/agents/antigravity/schema.rs rename to bt-daemon/src/agents/antigravity/schema/transcript_record.rs index 115993c7..37f6fb63 100644 --- a/bt-daemon/src/agents/antigravity/schema.rs +++ b/bt-daemon/src/agents/antigravity/schema/transcript_record.rs @@ -1,4 +1,4 @@ -//! Antigravity native records shared by live translation and transcript import. +use super::{optional_integer, ToolCalls}; use crate::agents::usage::ProviderUsage; use crate::json::Extensions; use serde::{Deserialize, Serialize}; @@ -46,59 +46,29 @@ pub(crate) struct TranscriptRecord { pub extra: Extensions, } -pub(crate) fn optional_integer<'de, D: serde::Deserializer<'de>>( - deserializer: D, -) -> Result, D::Error> { - #[derive(Deserialize)] - #[serde(untagged)] - enum Integer { - Number(i64), - Text(String), +impl TranscriptRecord { + pub fn normalized_kind(&self) -> &str { + self.kind + .strip_prefix("CORTEX_STEP_TYPE_") + .unwrap_or(&self.kind) } - Option::::deserialize(deserializer)? - .map(|value| match value { - Integer::Number(value) => Ok(value), - Integer::Text(value) => value.parse().map_err(serde::de::Error::custom), - }) - .transpose() -} -#[derive(Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum ToolCalls { - Many(Vec), - One(ToolCall), -} -impl ToolCalls { - pub fn iter(&self) -> std::slice::Iter<'_, ToolCall> { - match self { - Self::Many(calls) => calls.iter(), - Self::One(call) => std::slice::from_ref(call).iter(), - } + /// Native formats use three alternative content fields. Explicit null is + /// still content and must not accidentally expose a lower-priority field. + pub fn message_content(&self) -> Value { + self.content + .as_ref() + .or(self.message.as_ref()) + .or(self.text.as_ref()) + .cloned() + .unwrap_or(Value::Null) } -} -#[derive(Clone, Serialize, Deserialize)] -pub(crate) struct ToolCall { - #[serde(default, alias = "tool_name", alias = "toolName")] - pub name: Option, - #[serde( - default, - skip_serializing_if = "Option::is_none", - alias = "arguments", - alias = "input", - deserialize_with = "crate::agents::schema::deserialize_present" - )] - pub args: Option, - #[serde( - default, - skip_serializing_if = "Option::is_none", - alias = "result", - deserialize_with = "crate::agents::schema::deserialize_present" - )] - pub output: Option, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, + pub fn created_at_ms(&self) -> Option { + chrono::DateTime::parse_from_rfc3339(self.created_at.as_deref()?) + .ok() + .map(|timestamp| timestamp.timestamp_millis()) + } } #[cfg(test)] diff --git a/bt-daemon/src/agents/schema.rs b/bt-daemon/src/agents/schema.rs deleted file mode 100644 index 7e554edc..00000000 --- a/bt-daemon/src/agents/schema.rs +++ /dev/null @@ -1,264 +0,0 @@ -//! Schemas shared by capture, setup, managed runs, and transcript import. -//! -//! Unknown extension fields are preserved when editing an agent-owned file. -//! Known fields are decoded here and used as concrete Rust values internally. -use crate::json::Field; -use serde::{Deserialize, Serialize}; -use serde_json::{Map, Value}; -use std::collections::BTreeMap; - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub(crate) struct HookFile { - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub version: Field, - pub hooks: BTreeMap>, - #[serde(flatten)] - pub extra: Map, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub(crate) struct HookGroup { - pub hooks: Vec, - #[serde(skip_serializing_if = "Option::is_none")] - pub matcher: Option, - #[serde(flatten)] - pub extra: Map, -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct CommandHook { - #[serde(rename = "type")] - pub kind: String, - pub command: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub command_windows: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub args: Option>, - #[serde(rename = "async", skip_serializing_if = "Option::is_none")] - pub asynchronous: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub status_message: Option, - #[serde(flatten)] - pub extra: Map, -} - -#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] -pub(crate) struct OpenCodeConfig { - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub model: Field, - #[serde( - default, - skip_serializing_if = "Option::is_none", - deserialize_with = "deserialize_present" - )] - pub plugin: Option>, - #[serde(flatten)] - pub extra: Map, -} - -/// OpenCode also accepts plugin tuples with provider-specific options. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum OpenCodePlugin { - Package(String), - Configured((String, Value)), -} -impl OpenCodePlugin { - pub fn package(&self) -> Option<&str> { - match self { - Self::Package(package) => Some(package), - Self::Configured(_) => None, - } - } -} - -#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] -pub(crate) struct CursorHooks { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub version: Option, - #[serde( - default, - skip_serializing_if = "Option::is_none", - deserialize_with = "deserialize_present" - )] - pub hooks: Option>, - #[serde(flatten)] - pub extra: Map, -} - -/// Unrecognized native hook definitions belong to the user, and survive edits. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum CursorHookEntries { - Entries(Vec), - Other(Value), -} -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(untagged)] -pub(crate) enum CursorHookEntry { - Command(CursorCommandHook), - Other(Value), -} -impl CursorHookEntry { - pub fn command(&self) -> Option<&str> { - match self { - Self::Command(hook) => Some(&hook.command), - Self::Other(_) => None, - } - } -} -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct CursorCommandHook { - pub command: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub timeout: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub fail_closed: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub matcher: Option, - #[serde(flatten)] - pub extra: Map, -} -impl CursorCommandHook { - pub fn capture(command: String, matcher: Option) -> Self { - Self { - command, - timeout: Some(10), - fail_closed: Some(false), - matcher, - extra: Map::new(), - } - } -} - -/// The manifest identity fields used by setup and capture version detection. -#[derive(Debug, Deserialize)] -pub(crate) struct PluginManifest { - pub name: Option, - pub version: Option, - pub repository: Option, -} - -#[derive(Debug, Deserialize)] -#[serde(untagged)] -pub(crate) enum Repository { - Url(String), - Package { - #[serde(rename = "type")] - _kind: Option, - #[serde(rename = "url")] - _url: String, - }, -} -impl Repository { - pub fn url(&self) -> Option<&str> { - match self { - Self::Url(url) => Some(url), - Self::Package { .. } => None, - } - } -} - -/// Preserve explicit null for opaque JSON fields while a missing field remains -/// None. Used only when native null has different semantics from absence. -pub(crate) fn deserialize_present<'de, T: Deserialize<'de>, D: serde::Deserializer<'de>>( - deserializer: D, -) -> Result, D::Error> { - T::deserialize(deserializer).map(Some) -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn hook_file_round_trips_extensions_and_rejects_malformed_commands() { - let raw = json!({"future": true, "hooks": {"Stop": [{ - "matcher": "*", "futureGroup": [1], "hooks": [{ - "type": "command", "command": "bt trace hook", "commandWindows": "bt.exe trace hook", - "futureHook": {"enabled": true} - }] - }]}}); - let parsed: HookFile = serde_json::from_value(raw.clone()).unwrap(); - assert_eq!(serde_json::to_value(parsed).unwrap(), raw); - assert!(serde_json::from_value::>(json!({ - "hooks": {"Stop": [{"hooks": [{"type":"command","command":42}]}]} - })) - .is_err()); - } - - #[test] - fn opencode_config_preserves_configured_plugins_and_extensions() { - let raw = - json!({"plugin": ["other", ["custom", {"setting": true}]], "model": "vendor/model"}); - let mut config: OpenCodeConfig = serde_json::from_value(raw.clone()).unwrap(); - config - .plugin - .as_mut() - .unwrap() - .push(OpenCodePlugin::Package("tracing".into())); - let encoded = serde_json::to_value(config).unwrap(); - assert_eq!(encoded["plugin"][1], raw["plugin"][1]); - assert_eq!(encoded["model"], raw["model"]); - assert!(serde_json::from_value::(json!({"plugin": "invalid"})).is_err()); - } - - #[test] - fn cursor_preserves_unrecognized_user_hooks_when_adding_capture() { - let raw = json!({"version":1,"hooks":{"stop":[{"command":42},{"type":"future","data":true}]},"future":true}); - let mut config: CursorHooks = serde_json::from_value(raw.clone()).unwrap(); - let CursorHookEntries::Entries(entries) = - config.hooks.as_mut().unwrap().get_mut("stop").unwrap() - else { - panic!() - }; - entries.push(CursorHookEntry::Command(CursorCommandHook::capture( - "bt trace hook".into(), - None, - ))); - let encoded = serde_json::to_value(config).unwrap(); - assert_eq!(encoded["hooks"]["stop"][0], raw["hooks"]["stop"][0]); - assert_eq!(encoded["hooks"]["stop"][1], raw["hooks"]["stop"][1]); - assert_eq!(encoded["future"], true); - } - - #[test] - fn known_config_fields_are_typed_without_normalizing_missing_or_null() { - for raw in [ - serde_json::json!({"hooks":{}}), - serde_json::json!({"hooks":{},"version":null}), - serde_json::json!({"hooks":{},"version":1}), - ] { - let file: HookFile = serde_json::from_value(raw.clone()).unwrap(); - assert!(!file.extra.contains_key("version")); - assert_eq!(serde_json::to_value(file).unwrap(), raw); - } - for raw in [ - serde_json::json!({}), - serde_json::json!({"model":null}), - serde_json::json!({"model":"vendor/model"}), - ] { - let config: OpenCodeConfig = serde_json::from_value(raw.clone()).unwrap(); - assert!(!config.extra.contains_key("model")); - assert_eq!(serde_json::to_value(config).unwrap(), raw); - } - assert!(serde_json::from_value::(serde_json::json!({"model":42})).is_err()); - } - - #[test] - fn manifests_accept_both_plugin_and_npm_repository_shapes() { - for repository in [ - json!("https://github.com/org/repo"), - json!({"type":"git","url":"git+https://github.com/org/repo.git"}), - ] { - let manifest: PluginManifest = serde_json::from_value( - json!({"name":"plugin","version":"1.2.3","repository":repository}), - ) - .unwrap(); - assert_eq!(manifest.version.as_deref(), Some("1.2.3")); - } - } -} diff --git a/bt-daemon/src/agents/schema/command_hook.rs b/bt-daemon/src/agents/schema/command_hook.rs new file mode 100644 index 00000000..d5cf7ccd --- /dev/null +++ b/bt-daemon/src/agents/schema/command_hook.rs @@ -0,0 +1,20 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct CommandHook { + #[serde(rename = "type")] + pub kind: String, + pub command: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub command_windows: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub args: Option>, + #[serde(rename = "async", skip_serializing_if = "Option::is_none")] + pub asynchronous: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub status_message: Option, + #[serde(flatten)] + pub extra: Map, +} diff --git a/bt-daemon/src/agents/schema/cursor_command_hook.rs b/bt-daemon/src/agents/schema/cursor_command_hook.rs new file mode 100644 index 00000000..1e591329 --- /dev/null +++ b/bt-daemon/src/agents/schema/cursor_command_hook.rs @@ -0,0 +1,27 @@ +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct CursorCommandHook { + pub command: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub fail_closed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub matcher: Option, + #[serde(flatten)] + pub extra: Map, +} +impl CursorCommandHook { + pub fn capture(command: String, matcher: Option) -> Self { + Self { + command, + timeout: Some(10), + fail_closed: Some(false), + matcher, + extra: Map::new(), + } + } +} diff --git a/bt-daemon/src/agents/schema/cursor_hook_entries.rs b/bt-daemon/src/agents/schema/cursor_hook_entries.rs new file mode 100644 index 00000000..4c718e21 --- /dev/null +++ b/bt-daemon/src/agents/schema/cursor_hook_entries.rs @@ -0,0 +1,11 @@ +use super::CursorHookEntry; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Unrecognized native hook definitions belong to the user, and survive edits. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum CursorHookEntries { + Entries(Vec), + Other(Value), +} diff --git a/bt-daemon/src/agents/schema/cursor_hook_entry.rs b/bt-daemon/src/agents/schema/cursor_hook_entry.rs new file mode 100644 index 00000000..8e06dc53 --- /dev/null +++ b/bt-daemon/src/agents/schema/cursor_hook_entry.rs @@ -0,0 +1,18 @@ +use super::CursorCommandHook; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum CursorHookEntry { + Command(CursorCommandHook), + Other(Value), +} +impl CursorHookEntry { + pub fn command(&self) -> Option<&str> { + match self { + Self::Command(hook) => Some(&hook.command), + Self::Other(_) => None, + } + } +} diff --git a/bt-daemon/src/agents/schema/cursor_hooks.rs b/bt-daemon/src/agents/schema/cursor_hooks.rs new file mode 100644 index 00000000..557c641d --- /dev/null +++ b/bt-daemon/src/agents/schema/cursor_hooks.rs @@ -0,0 +1,68 @@ +use super::{deserialize_present, CursorCommandHook, CursorHookEntries, CursorHookEntry}; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub(crate) struct CursorHooks { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_present" + )] + pub hooks: Option>, + #[serde(flatten)] + pub extra: Map, +} + +impl CursorHooks { + /// Compare the complete known registration, including timeout and matcher. + pub fn contains_registration(&self, event: &str, expected: &CursorCommandHook) -> bool { + matches!(self.hooks.as_ref().and_then(|hooks| hooks.get(event)), Some(CursorHookEntries::Entries(entries)) + if entries.iter().any(|entry| matches!(entry, CursorHookEntry::Command(hook) if hook == expected))) + } + + /// Filter known commands without changing unknown event or entry formats. + pub fn retain_commands(&mut self, mut keep: impl FnMut(&str) -> bool) { + if let Some(hooks) = &mut self.hooks { + for entries in hooks.values_mut() { + if let CursorHookEntries::Entries(entries) = entries { + entries.retain(|entry| entry.command().is_none_or(&mut keep)); + } + } + } + } + + /// Replace one command's registrations, or remove them without creating a + /// missing hook map/event. Unknown event formats cannot be safely edited. + pub fn replace_registration( + &mut self, + event: &str, + command: &str, + replacement: Option, + ) -> anyhow::Result<()> { + if replacement.is_none() + && self + .hooks + .as_ref() + .is_none_or(|hooks| !hooks.contains_key(event)) + { + return Ok(()); + } + let entries = self + .hooks + .get_or_insert_with(Default::default) + .entry(event.to_owned()) + .or_insert_with(|| CursorHookEntries::Entries(Vec::new())); + let CursorHookEntries::Entries(entries) = entries else { + anyhow::bail!("Cursor hook event `{event}` must be an array"); + }; + entries.retain(|entry| entry.command() != Some(command)); + if let Some(replacement) = replacement { + entries.push(CursorHookEntry::Command(replacement)); + } + Ok(()) + } +} diff --git a/bt-daemon/src/agents/schema/hook_file.rs b/bt-daemon/src/agents/schema/hook_file.rs new file mode 100644 index 00000000..4aff033c --- /dev/null +++ b/bt-daemon/src/agents/schema/hook_file.rs @@ -0,0 +1,13 @@ +use crate::json::Field; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub(crate) struct HookFile { + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub version: Field, + pub hooks: BTreeMap>, + #[serde(flatten)] + pub extra: Map, +} diff --git a/bt-daemon/src/agents/schema/hook_group.rs b/bt-daemon/src/agents/schema/hook_group.rs new file mode 100644 index 00000000..256562ea --- /dev/null +++ b/bt-daemon/src/agents/schema/hook_group.rs @@ -0,0 +1,12 @@ +use super::CommandHook; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub(crate) struct HookGroup { + pub hooks: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub matcher: Option, + #[serde(flatten)] + pub extra: Map, +} diff --git a/bt-daemon/src/agents/schema/mod.rs b/bt-daemon/src/agents/schema/mod.rs new file mode 100644 index 00000000..893948d6 --- /dev/null +++ b/bt-daemon/src/agents/schema/mod.rs @@ -0,0 +1,40 @@ +//! Schemas shared by capture, setup, managed runs, and transcript import. +//! +//! Unknown extension fields are preserved when editing an agent-owned file. +//! Known fields are decoded here and used as concrete Rust values internally. +use serde::Deserialize; + +mod command_hook; +mod cursor_command_hook; +mod cursor_hook_entries; +mod cursor_hook_entry; +mod cursor_hooks; +mod hook_file; +mod hook_group; +mod opencode_config; +mod opencode_plugin; +mod plugin_manifest; +mod repository; + +pub(crate) use command_hook::CommandHook; +pub(crate) use cursor_command_hook::CursorCommandHook; +pub(crate) use cursor_hook_entries::CursorHookEntries; +pub(crate) use cursor_hook_entry::CursorHookEntry; +pub(crate) use cursor_hooks::CursorHooks; +pub(crate) use hook_file::HookFile; +pub(crate) use hook_group::HookGroup; +pub(crate) use opencode_config::OpenCodeConfig; +pub(crate) use opencode_plugin::OpenCodePlugin; +pub(crate) use plugin_manifest::PluginManifest; +pub(crate) use repository::Repository; + +/// Preserve explicit null for opaque JSON fields while a missing field remains +/// None. Used only when native null has different semantics from absence. +pub(crate) fn deserialize_present<'de, T: Deserialize<'de>, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + T::deserialize(deserializer).map(Some) +} + +#[cfg(test)] +mod tests; diff --git a/bt-daemon/src/agents/schema/opencode_config.rs b/bt-daemon/src/agents/schema/opencode_config.rs new file mode 100644 index 00000000..400b2546 --- /dev/null +++ b/bt-daemon/src/agents/schema/opencode_config.rs @@ -0,0 +1,56 @@ +use super::{deserialize_present, OpenCodePlugin}; +use crate::json::Field; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub(crate) struct OpenCodeConfig { + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub model: Field, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_present" + )] + pub(super) plugin: Option>, + #[serde(flatten)] + pub extra: Map, +} + +impl OpenCodeConfig { + pub fn find_plugin( + &self, + mut matches: impl FnMut(&OpenCodePlugin) -> bool, + ) -> Option<&OpenCodePlugin> { + self.plugin.as_ref()?.iter().find(|plugin| matches(plugin)) + } + + /// Preserve absence when removing plugins from an unconfigured document. + pub fn retain_plugins(&mut self, keep: impl FnMut(&OpenCodePlugin) -> bool) { + if let Some(plugins) = &mut self.plugin { + plugins.retain(keep); + } + } + + pub fn replace_plugin( + &mut self, + mut matches: impl FnMut(&OpenCodePlugin) -> bool, + plugin: OpenCodePlugin, + ) { + self.retain_plugins(|entry| !matches(entry)); + self.plugin.get_or_insert_with(Vec::new).push(plugin); + } + + /// Managed runs add an exact spec only once; differently configured specs + /// are left alone because their options belong to the user's invocation. + pub fn ensure_plugin(&mut self, package: String) { + if self + .find_plugin(|plugin| plugin.package() == Some(&package)) + .is_none() + { + self.plugin + .get_or_insert_with(Vec::new) + .push(OpenCodePlugin::Package(package)); + } + } +} diff --git a/bt-daemon/src/agents/schema/opencode_plugin.rs b/bt-daemon/src/agents/schema/opencode_plugin.rs new file mode 100644 index 00000000..259a38b7 --- /dev/null +++ b/bt-daemon/src/agents/schema/opencode_plugin.rs @@ -0,0 +1,31 @@ +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// OpenCode also accepts plugin tuples with provider-specific options. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum OpenCodePlugin { + Package(String), + Configured((String, Value)), +} +impl OpenCodePlugin { + pub fn package(&self) -> Option<&str> { + match self { + Self::Package(package) => Some(package), + Self::Configured(_) => None, + } + } +} + +impl OpenCodePlugin { + /// Match a plain package entry, including a version suffix. Configured + /// tuples carry caller-owned options and are deliberately not replaced. + pub fn matches_package(&self, package: &str) -> bool { + self.package().is_some_and(|entry| { + entry == package + || entry + .strip_prefix(package) + .is_some_and(|suffix| suffix.starts_with('@')) + }) + } +} diff --git a/bt-daemon/src/agents/schema/plugin_manifest.rs b/bt-daemon/src/agents/schema/plugin_manifest.rs new file mode 100644 index 00000000..7c948786 --- /dev/null +++ b/bt-daemon/src/agents/schema/plugin_manifest.rs @@ -0,0 +1,10 @@ +use super::Repository; +use serde::Deserialize; + +/// The manifest identity fields used by setup and capture version detection. +#[derive(Debug, Deserialize)] +pub(crate) struct PluginManifest { + pub name: Option, + pub version: Option, + pub repository: Option, +} diff --git a/bt-daemon/src/agents/schema/repository.rs b/bt-daemon/src/agents/schema/repository.rs new file mode 100644 index 00000000..ba39a0b7 --- /dev/null +++ b/bt-daemon/src/agents/schema/repository.rs @@ -0,0 +1,21 @@ +use serde::Deserialize; + +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub(crate) enum Repository { + Url(String), + Package { + #[serde(rename = "type")] + _kind: Option, + #[serde(rename = "url")] + _url: String, + }, +} +impl Repository { + pub fn url(&self) -> Option<&str> { + match self { + Self::Url(url) => Some(url), + Self::Package { .. } => None, + } + } +} diff --git a/bt-daemon/src/agents/schema/tests.rs b/bt-daemon/src/agents/schema/tests.rs new file mode 100644 index 00000000..7698a44f --- /dev/null +++ b/bt-daemon/src/agents/schema/tests.rs @@ -0,0 +1,134 @@ +use super::*; +use serde_json::json; + +#[test] +fn hook_file_round_trips_extensions_and_rejects_malformed_commands() { + let raw = json!({"future": true, "hooks": {"Stop": [{ + "matcher": "*", "futureGroup": [1], "hooks": [{ + "type": "command", "command": "bt trace hook", "commandWindows": "bt.exe trace hook", + "futureHook": {"enabled": true} + }] + }]}}); + let parsed: HookFile = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), raw); + assert!(serde_json::from_value::>(json!({ + "hooks": {"Stop": [{"hooks": [{"type":"command","command":42}]}]} + })) + .is_err()); +} + +#[test] +fn opencode_config_preserves_configured_plugins_and_extensions() { + let raw = json!({"plugin": ["other", ["custom", {"setting": true}]], "model": "vendor/model"}); + let mut config: OpenCodeConfig = serde_json::from_value(raw.clone()).unwrap(); + config + .plugin + .as_mut() + .unwrap() + .push(OpenCodePlugin::Package("tracing".into())); + let encoded = serde_json::to_value(config).unwrap(); + assert_eq!(encoded["plugin"][1], raw["plugin"][1]); + assert_eq!(encoded["model"], raw["model"]); + assert!(serde_json::from_value::(json!({"plugin": "invalid"})).is_err()); +} + +#[test] +fn cursor_preserves_unrecognized_user_hooks_when_adding_capture() { + let raw = json!({"version":1,"hooks":{"stop":[{"command":42},{"type":"future","data":true}]},"future":true}); + let mut config: CursorHooks = serde_json::from_value(raw.clone()).unwrap(); + let CursorHookEntries::Entries(entries) = + config.hooks.as_mut().unwrap().get_mut("stop").unwrap() + else { + panic!() + }; + entries.push(CursorHookEntry::Command(CursorCommandHook::capture( + "bt trace hook".into(), + None, + ))); + let encoded = serde_json::to_value(config).unwrap(); + assert_eq!(encoded["hooks"]["stop"][0], raw["hooks"]["stop"][0]); + assert_eq!(encoded["hooks"]["stop"][1], raw["hooks"]["stop"][1]); + assert_eq!(encoded["future"], true); +} + +#[test] +fn known_config_fields_are_typed_without_normalizing_missing_or_null() { + for raw in [ + serde_json::json!({"hooks":{}}), + serde_json::json!({"hooks":{},"version":null}), + serde_json::json!({"hooks":{},"version":1}), + ] { + let file: HookFile = serde_json::from_value(raw.clone()).unwrap(); + assert!(!file.extra.contains_key("version")); + assert_eq!(serde_json::to_value(file).unwrap(), raw); + } + for raw in [ + serde_json::json!({}), + serde_json::json!({"model":null}), + serde_json::json!({"model":"vendor/model"}), + ] { + let config: OpenCodeConfig = serde_json::from_value(raw.clone()).unwrap(); + assert!(!config.extra.contains_key("model")); + assert_eq!(serde_json::to_value(config).unwrap(), raw); + } + assert!(serde_json::from_value::(serde_json::json!({"model":42})).is_err()); +} + +#[test] +fn manifests_accept_both_plugin_and_npm_repository_shapes() { + for repository in [ + json!("https://github.com/org/repo"), + json!({"type":"git","url":"git+https://github.com/org/repo.git"}), + ] { + let manifest: PluginManifest = serde_json::from_value( + json!({"name":"plugin","version":"1.2.3","repository":repository}), + ) + .unwrap(); + assert_eq!(manifest.version.as_deref(), Some("1.2.3")); + } +} + +#[test] +fn cursor_registration_edits_preserve_unknown_entries_and_absent_events() { + let mut absent = CursorHooks::default(); + absent.replace_registration("stop", "owned", None).unwrap(); + assert!(absent.hooks.is_none()); + + let raw = json!({"hooks":{"stop":[{"type":"future","payload":true},{"command":"owned"},{"command":"owned"},{"command":"foreign"}],"future":{"new":true}}}); + let mut config: CursorHooks = serde_json::from_value(raw.clone()).unwrap(); + let expected = CursorCommandHook::capture("owned".into(), None); + config + .replace_registration("stop", "owned", Some(expected.clone())) + .unwrap(); + assert!(config.contains_registration("stop", &expected)); + config.retain_commands(|command| command != "owned"); + let before = serde_json::to_value(&config).unwrap(); + assert_eq!( + before["hooks"]["stop"], + json!([{"type":"future","payload":true},{"command":"foreign"}]) + ); + assert_eq!(before["hooks"]["future"], raw["hooks"]["future"]); + assert!(config + .replace_registration("future", "owned", Some(expected)) + .is_err()); + assert_eq!(serde_json::to_value(config).unwrap(), before); +} + +#[test] +fn opencode_plugin_edits_preserve_configured_options_and_exact_specs() { + let mut absent = OpenCodeConfig::default(); + absent.retain_plugins(|_| false); + assert!(absent.plugin.is_none()); + + let raw = json!({"plugin":[["@vendor/plugin",{"setting":null}],"@vendor/plugin@1","@vendor/plugin-other"],"model":null}); + let mut config: OpenCodeConfig = serde_json::from_value(raw).unwrap(); + config.replace_plugin( + |plugin| plugin.matches_package("@vendor/plugin"), + OpenCodePlugin::Package("@vendor/plugin@2".into()), + ); + config.ensure_plugin("@vendor/plugin@2".into()); + assert_eq!( + serde_json::to_value(config).unwrap(), + json!({"plugin":[["@vendor/plugin",{"setting":null}],"@vendor/plugin-other","@vendor/plugin@2"],"model":null}) + ); +} diff --git a/bt-daemon/src/agents/usage.rs b/bt-daemon/src/agents/usage.rs deleted file mode 100644 index 0f202535..00000000 --- a/bt-daemon/src/agents/usage.rs +++ /dev/null @@ -1,562 +0,0 @@ -//! Native usage schemas shared by agent capture, transcript parsing, and reducers. -//! -//! Agents usually normalize providers themselves. The enum identifies the wire -//! format, not a guessed provider identity: OpenAI-compatible and Anthropic -//! payloads can share field names. Only explicitly modeled usage fields become -//! metrics. Unknown extensions round-trip as opaque JSON and are never scanned. -use crate::json::Extensions; -use serde::{Deserialize, Serialize}; -use serde_json::value::RawValue; -use std::collections::BTreeMap; - -#[derive(Debug, Clone, Serialize)] -#[serde(untagged)] -pub(crate) enum ProviderUsage { - SnakeCase(Box), - CamelCase(Box), - Unknown(Extensions), -} - -impl<'de> Deserialize<'de> for ProviderUsage { - fn deserialize>(deserializer: D) -> Result { - // Inspect field names only at the decoding boundary. Optional-only - // untagged structs would otherwise accept and swallow other variants. - let raw = Box::::deserialize(deserializer)?; - let fields: BTreeMap = - serde_json::from_str(raw.get()).map_err(serde::de::Error::custom)?; - let snake = SNAKE_FIELDS.iter().any(|field| fields.contains_key(*field)); - let camel = CAMEL_FIELDS.iter().any(|field| fields.contains_key(*field)); - match (snake, camel) { - (true, false) => serde_json::from_str(raw.get()) - .map(Self::SnakeCase) - .map_err(serde::de::Error::custom), - (false, true) => serde_json::from_str(raw.get()) - .map(Self::CamelCase) - .map_err(serde::de::Error::custom), - (false, false) => serde_json::from_str(raw.get()) - .map(Self::Unknown) - .map_err(serde::de::Error::custom), - (true, true) => Err(serde::de::Error::custom( - "mixed snake_case and camelCase usage fields", - )), - } - } -} -impl ProviderUsage { - pub fn metrics(&self) -> UsageMetrics { - match self { - Self::SnakeCase(usage) => usage.metrics(), - Self::CamelCase(usage) => usage.metrics(), - Self::Unknown(_) => UsageMetrics::default(), - } - } -} - -const SNAKE_FIELDS: &[&str] = &[ - "input_tokens", - "prompt_tokens", - "output_tokens", - "completion_tokens", - "total_tokens", - "tokens", - "cached_input_tokens", - "prompt_cached_tokens", - "cache_read_tokens", - "cache_read_input_tokens", - "cache_creation_input_tokens", - "prompt_cache_creation_tokens", - "reasoning_output_tokens", - "completion_reasoning_tokens", - "reasoning_tokens", - "thinking_tokens", - "input_tokens_details", - "prompt_tokens_details", - "output_tokens_details", - "completion_tokens_details", - "cache_creation", -]; -const CAMEL_FIELDS: &[&str] = &[ - "inputTokens", - "promptTokens", - "outputTokens", - "completionTokens", - "totalTokens", - "cachedReadTokens", - "cacheReadTokens", - "cacheCreationTokens", - "reasoningTokens", - "thinkingTokens", - "apiDurationMs", - "costUsdTicks", - "modelCalls", - "modelUsage", -]; - -/// Snake-case input/output usage (Codex/OpenAI-compatible and Claude fields). -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct SnakeCaseUsage { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub output_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub total_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cached_input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_cached_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_read_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_read_input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_creation_input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_cache_creation_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub reasoning_output_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_reasoning_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub reasoning_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub thinking_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub input_tokens_details: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_tokens_details: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub output_tokens_details: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_tokens_details: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_creation: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub estimated_cost: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub total_cost: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost_usd: Option, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct TokenDetails { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cached_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_creation_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_write_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub reasoning_tokens: Option, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, -} -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub(crate) struct CacheCreation { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub ephemeral_5m_input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub ephemeral_1h_input_tokens: Option, -} -/// Camel-case counters emitted by Antigravity and Grok's ACP transcripts. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct CamelCaseUsage { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub input_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub output_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub total_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cached_read_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_read_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cache_creation_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub reasoning_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub thinking_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub api_duration_ms: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost_usd_ticks: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_calls: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_usage: Option>, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, -} -/// Typed normalized metrics for the readers that historically emit floats. -#[derive(Debug, Clone, Default, Serialize)] -pub(crate) struct UsageMetrics { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_cached_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt_cache_creation_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub completion_reasoning_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub thinking_tokens: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub estimated_cost: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub api_duration_ms: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost_usd_ticks: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub model_calls: Option, -} -impl UsageMetrics { - pub fn is_empty(&self) -> bool { - [ - self.prompt_tokens, - self.completion_tokens, - self.tokens, - self.prompt_cached_tokens, - self.prompt_cache_creation_tokens, - self.completion_reasoning_tokens, - self.thinking_tokens, - self.cost, - self.estimated_cost, - self.api_duration_ms, - self.cost_usd_ticks, - self.model_calls, - ] - .iter() - .all(Option::is_none) - } - pub fn with_total(mut self) -> Self { - if self.tokens.is_none() { - self.tokens = self - .prompt_tokens - .zip(self.completion_tokens) - .map(|(p, c)| p + c); - } - self - } - pub fn observe(&mut self, other: Self) { - if other.prompt_tokens.is_some() { - self.prompt_tokens = other.prompt_tokens; - } - if other.completion_tokens.is_some() { - self.completion_tokens = other.completion_tokens; - } - if other.tokens.is_some() { - self.tokens = other.tokens; - } - if other.prompt_cached_tokens.is_some() { - self.prompt_cached_tokens = other.prompt_cached_tokens; - } - if other.prompt_cache_creation_tokens.is_some() { - self.prompt_cache_creation_tokens = other.prompt_cache_creation_tokens; - } - if other.completion_reasoning_tokens.is_some() { - self.completion_reasoning_tokens = other.completion_reasoning_tokens; - } - if other.thinking_tokens.is_some() { - self.thinking_tokens = other.thinking_tokens; - } - if other.cost.is_some() { - self.cost = other.cost; - } - if other.estimated_cost.is_some() { - self.estimated_cost = other.estimated_cost; - } - if other.api_duration_ms.is_some() { - self.api_duration_ms = other.api_duration_ms; - } - if other.cost_usd_ticks.is_some() { - self.cost_usd_ticks = other.cost_usd_ticks; - } - if other.model_calls.is_some() { - self.model_calls = other.model_calls; - } - } -} -impl SnakeCaseUsage { - pub fn metrics(&self) -> UsageMetrics { - let input_details = self.input_tokens_details.as_ref(); - let prompt_details = self.prompt_tokens_details.as_ref(); - let output_details = self.output_tokens_details.as_ref(); - let completion_details = self.completion_tokens_details.as_ref(); - UsageMetrics { - prompt_tokens: self.input_tokens.or(self.prompt_tokens).map(|n| n as f64), - completion_tokens: self - .output_tokens - .or(self.completion_tokens) - .map(|n| n as f64), - tokens: self.total_tokens.or(self.tokens).map(|n| n as f64), - prompt_cached_tokens: self - .cached_input_tokens - .or(self.prompt_cached_tokens) - .or_else(|| input_details.and_then(|d| d.cached_tokens)) - .or_else(|| prompt_details.and_then(|d| d.cached_tokens)) - .or(self.cache_read_tokens) - .or(self.cache_read_input_tokens) - .map(|n| n as f64), - prompt_cache_creation_tokens: self - .prompt_cache_creation_tokens - .or_else(|| { - input_details.and_then(|d| d.cache_creation_tokens.or(d.cache_write_tokens)) - }) - .or_else(|| { - prompt_details.and_then(|d| d.cache_creation_tokens.or(d.cache_write_tokens)) - }) - .or(self.cache_creation_input_tokens) - .map(|n| n as f64), - completion_reasoning_tokens: self - .reasoning_output_tokens - .or(self.completion_reasoning_tokens) - .or(self.reasoning_tokens) - .or_else(|| output_details.and_then(|d| d.reasoning_tokens)) - .or_else(|| completion_details.and_then(|d| d.reasoning_tokens)) - .map(|n| n as f64), - thinking_tokens: self.thinking_tokens.map(|n| n as f64), - cost: self.cost, - estimated_cost: self - .cost - .or(self.estimated_cost) - .or(self.total_cost) - .or(self.cost_usd), - ..UsageMetrics::default() - } - } - pub fn is_empty(&self) -> bool { - self.metrics().is_empty() - && self.extra.is_empty() - && self.cache_creation.is_none() - && self.input_tokens_details.is_none() - && self.prompt_tokens_details.is_none() - && self.output_tokens_details.is_none() - && self.completion_tokens_details.is_none() - } -} -impl CamelCaseUsage { - pub fn metrics(&self) -> UsageMetrics { - UsageMetrics { - prompt_tokens: self.input_tokens.or(self.prompt_tokens).map(|n| n as f64), - completion_tokens: self - .output_tokens - .or(self.completion_tokens) - .map(|n| n as f64), - tokens: self.total_tokens.map(|n| n as f64), - prompt_cached_tokens: self - .cached_read_tokens - .or(self.cache_read_tokens) - .map(|n| n as f64), - prompt_cache_creation_tokens: self.cache_creation_tokens.map(|n| n as f64), - completion_reasoning_tokens: self.reasoning_tokens.map(|n| n as f64), - thinking_tokens: self.thinking_tokens.map(|n| n as f64), - api_duration_ms: self - .api_duration_ms - .as_ref() - .and_then(serde_json::Number::as_f64), - cost_usd_ticks: self - .cost_usd_ticks - .as_ref() - .and_then(serde_json::Number::as_f64), - model_calls: self.model_calls.map(|n| n as f64), - ..UsageMetrics::default() - } - } -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -pub(crate) struct TokenMetrics { - #[serde(skip_serializing_if = "Option::is_none")] - pub prompt_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub completion_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub prompt_cached_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub prompt_cache_creation_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub completion_reasoning_tokens: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub tokens: Option, -} - -impl TokenMetrics { - pub(crate) fn add(&mut self, other: &Self) { - fn add(to: &mut Option, from: Option) { - if let Some(from) = from { - *to = Some(to.unwrap_or(0).saturating_add(from)); - } - } - add(&mut self.prompt_tokens, other.prompt_tokens); - add(&mut self.completion_tokens, other.completion_tokens); - add(&mut self.prompt_cached_tokens, other.prompt_cached_tokens); - add( - &mut self.prompt_cache_creation_tokens, - other.prompt_cache_creation_tokens, - ); - add( - &mut self.completion_reasoning_tokens, - other.completion_reasoning_tokens, - ); - add(&mut self.tokens, other.tokens); - } -} - -#[derive(Clone, Default, Serialize, Deserialize)] -pub(crate) struct OpenCodeTokens { - #[serde(default)] - pub input: i64, - #[serde(default)] - pub output: i64, - #[serde(default)] - pub reasoning: i64, - #[serde(default)] - pub cache: OpenCodeCacheTokens, -} -#[derive(Clone, Default, Serialize, Deserialize)] -pub(crate) struct OpenCodeCacheTokens { - #[serde(default)] - pub read: i64, - #[serde(default)] - pub write: i64, -} - -/// Pi normalizes provider usage before forwarding events to the daemon. -#[derive(Default, Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -pub(crate) struct PiUsage { - #[serde(default)] - pub input: i64, - #[serde(default)] - pub output: i64, - // Pi reports `reasoning` as a subset of `output`, and only for providers - // that expose the breakdown. - #[serde(default)] - pub reasoning: Option, - #[serde(default)] - pub cache_read: i64, - // `cacheWrite1h` is the subset of `cacheWrite` written with 1h retention. - #[serde(default)] - pub cache_write: i64, - #[serde(default)] - pub cache_write1h: Option, - #[serde(default)] - pub total_tokens: Option, - #[serde(default)] - pub cost: Option, -} - -#[derive(Default, Deserialize, Serialize)] -pub(crate) struct PiCost { - #[serde(default)] - pub total: Option, -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn provider_usage_selects_the_wire_format_and_round_trips_extensions() { - for (raw, camel) in [ - ( - json!({"input_tokens":10,"output_tokens":2,"future":{"deep":[true,null]}}), - false, - ), - ( - json!({"inputTokens":10,"outputTokens":2,"future":{"deep":[true,null]}}), - true, - ), - (json!({"inputTokens":10,"outputTokens":2,"cost":0.25}), true), - ( - json!({"prompt_tokens":10,"completion_tokens":2,"future":{"deep":[true,null]}}), - false, - ), - ] { - let usage: ProviderUsage = serde_json::from_value(raw.clone()).unwrap(); - assert_eq!(matches!(&usage, ProviderUsage::CamelCase(_)), camel); - assert_eq!(usage.metrics().prompt_tokens, Some(10.0)); - assert_eq!(usage.metrics().completion_tokens, Some(2.0)); - assert_eq!(serde_json::to_value(usage).unwrap(), raw); - } - } - - #[test] - fn unknown_usage_is_opaque_and_malformed_known_usage_is_an_error() { - let raw = json!({"vendorExtension":{"inputTokens":999}}); - let usage: ProviderUsage = serde_json::from_value(raw.clone()).unwrap(); - assert!(matches!(&usage, ProviderUsage::Unknown(_))); - assert!(usage.metrics().is_empty()); - assert_eq!(serde_json::to_value(usage).unwrap(), raw); - for raw in [ - json!({"inputTokens":"10"}), - json!({"output_tokens":{}}), - json!({"input_tokens":1,"outputTokens":2}), - json!({"input_tokens":-1}), - ] { - assert!(serde_json::from_value::(raw).is_err()); - } - } - - #[test] - fn codex_alias_precedence_details_and_cost_remain_typed() { - let usage: SnakeCaseUsage = serde_json::from_value(json!({ - "input_tokens":10,"prompt_tokens":999,"output_tokens":2, - "cached_input_tokens":3,"input_tokens_details":{"cached_tokens":999,"cache_write_tokens":4}, - "output_tokens_details":{"reasoning_tokens":1},"cost":0.25,"total_cost":99 - })).unwrap(); - let metrics = usage.metrics().with_total(); - assert_eq!(metrics.prompt_tokens, Some(10.0)); - assert_eq!(metrics.tokens, Some(12.0)); - assert_eq!(metrics.prompt_cached_tokens, Some(3.0)); - assert_eq!(metrics.prompt_cache_creation_tokens, Some(4.0)); - assert_eq!(metrics.completion_reasoning_tokens, Some(1.0)); - assert_eq!(metrics.estimated_cost, Some(0.25)); - } - - #[test] - fn grok_per_model_usage_is_typed_and_preserves_partial_counts() { - let raw = - json!({"inputTokens":10,"modelUsage":{"model-a":{"outputTokens":2,"future":null}}}); - let usage: CamelCaseUsage = serde_json::from_value(raw.clone()).unwrap(); - let model = &usage.model_usage.as_ref().unwrap()["model-a"]; - assert_eq!(model.input_tokens, None); - assert_eq!(model.output_tokens, Some(2)); - assert_eq!(serde_json::to_value(usage).unwrap(), raw); - } - - #[test] - fn both_opencode_protocols_keep_the_same_cache_counter_shape() { - let tokens: OpenCodeTokens = serde_json::from_value(json!({ - "input":5,"output":2,"reasoning":1,"cache":{"read":3,"write":4} - })) - .unwrap(); - assert_eq!(tokens.input + tokens.cache.read + tokens.cache.write, 12); - assert_eq!(tokens.output, 2); - assert_eq!(tokens.reasoning, 1); - } -} diff --git a/bt-daemon/src/agents/usage/camel_case_usage.rs b/bt-daemon/src/agents/usage/camel_case_usage.rs new file mode 100644 index 00000000..dfc1146b --- /dev/null +++ b/bt-daemon/src/agents/usage/camel_case_usage.rs @@ -0,0 +1,69 @@ +use super::UsageMetrics; +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Camel-case counters emitted by Antigravity and Grok's ACP transcripts. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct CamelCaseUsage { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub total_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cached_read_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_read_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_creation_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thinking_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_duration_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost_usd_ticks: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_calls: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_usage: Option>, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} +impl CamelCaseUsage { + pub fn metrics(&self) -> UsageMetrics { + UsageMetrics { + prompt_tokens: self.input_tokens.or(self.prompt_tokens).map(|n| n as f64), + completion_tokens: self + .output_tokens + .or(self.completion_tokens) + .map(|n| n as f64), + tokens: self.total_tokens.map(|n| n as f64), + prompt_cached_tokens: self + .cached_read_tokens + .or(self.cache_read_tokens) + .map(|n| n as f64), + prompt_cache_creation_tokens: self.cache_creation_tokens.map(|n| n as f64), + completion_reasoning_tokens: self.reasoning_tokens.map(|n| n as f64), + thinking_tokens: self.thinking_tokens.map(|n| n as f64), + api_duration_ms: self + .api_duration_ms + .as_ref() + .and_then(serde_json::Number::as_f64), + cost_usd_ticks: self + .cost_usd_ticks + .as_ref() + .and_then(serde_json::Number::as_f64), + model_calls: self.model_calls.map(|n| n as f64), + ..UsageMetrics::default() + } + } +} diff --git a/bt-daemon/src/agents/usage/mod.rs b/bt-daemon/src/agents/usage/mod.rs new file mode 100644 index 00000000..2066b0c6 --- /dev/null +++ b/bt-daemon/src/agents/usage/mod.rs @@ -0,0 +1,108 @@ +//! Native usage schemas shared by agent capture, transcript parsing, and reducers. +//! +//! Agents usually normalize providers themselves. The enum identifies the wire +//! format, not a guessed provider identity: OpenAI-compatible and Anthropic +//! payloads can share field names. Only explicitly modeled usage fields become +//! metrics. Unknown extensions round-trip as opaque JSON and are never scanned. + +mod camel_case_usage; +mod opencode_tokens; +mod pi_usage; +mod provider_usage; +mod snake_case_usage; +mod token_metrics; +mod usage_metrics; + +pub(crate) use camel_case_usage::CamelCaseUsage; +pub(crate) use opencode_tokens::OpenCodeTokens; +pub(crate) use pi_usage::PiUsage; +pub(crate) use provider_usage::ProviderUsage; +pub(crate) use snake_case_usage::SnakeCaseUsage; +pub(crate) use token_metrics::TokenMetrics; +pub(crate) use usage_metrics::UsageMetrics; + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn provider_usage_selects_the_wire_format_and_round_trips_extensions() { + for (raw, camel) in [ + ( + json!({"input_tokens":10,"output_tokens":2,"future":{"deep":[true,null]}}), + false, + ), + ( + json!({"inputTokens":10,"outputTokens":2,"future":{"deep":[true,null]}}), + true, + ), + (json!({"inputTokens":10,"outputTokens":2,"cost":0.25}), true), + ( + json!({"prompt_tokens":10,"completion_tokens":2,"future":{"deep":[true,null]}}), + false, + ), + ] { + let usage: ProviderUsage = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(matches!(&usage, ProviderUsage::CamelCase(_)), camel); + assert_eq!(usage.metrics().prompt_tokens, Some(10.0)); + assert_eq!(usage.metrics().completion_tokens, Some(2.0)); + assert_eq!(serde_json::to_value(usage).unwrap(), raw); + } + } + + #[test] + fn unknown_usage_is_opaque_and_malformed_known_usage_is_an_error() { + let raw = json!({"vendorExtension":{"inputTokens":999}}); + let usage: ProviderUsage = serde_json::from_value(raw.clone()).unwrap(); + assert!(matches!(&usage, ProviderUsage::Unknown(_))); + assert!(usage.metrics().is_empty()); + assert_eq!(serde_json::to_value(usage).unwrap(), raw); + for raw in [ + json!({"inputTokens":"10"}), + json!({"output_tokens":{}}), + json!({"input_tokens":1,"outputTokens":2}), + json!({"input_tokens":-1}), + ] { + assert!(serde_json::from_value::(raw).is_err()); + } + } + + #[test] + fn codex_alias_precedence_details_and_cost_remain_typed() { + let usage: SnakeCaseUsage = serde_json::from_value(json!({ + "input_tokens":10,"prompt_tokens":999,"output_tokens":2, + "cached_input_tokens":3,"input_tokens_details":{"cached_tokens":999,"cache_write_tokens":4}, + "output_tokens_details":{"reasoning_tokens":1},"cost":0.25,"total_cost":99 + })).unwrap(); + let metrics = usage.metrics().with_total(); + assert_eq!(metrics.prompt_tokens, Some(10.0)); + assert_eq!(metrics.tokens, Some(12.0)); + assert_eq!(metrics.prompt_cached_tokens, Some(3.0)); + assert_eq!(metrics.prompt_cache_creation_tokens, Some(4.0)); + assert_eq!(metrics.completion_reasoning_tokens, Some(1.0)); + assert_eq!(metrics.estimated_cost, Some(0.25)); + } + + #[test] + fn grok_per_model_usage_is_typed_and_preserves_partial_counts() { + let raw = + json!({"inputTokens":10,"modelUsage":{"model-a":{"outputTokens":2,"future":null}}}); + let usage: CamelCaseUsage = serde_json::from_value(raw.clone()).unwrap(); + let model = &usage.model_usage.as_ref().unwrap()["model-a"]; + assert_eq!(model.input_tokens, None); + assert_eq!(model.output_tokens, Some(2)); + assert_eq!(serde_json::to_value(usage).unwrap(), raw); + } + + #[test] + fn both_opencode_protocols_keep_the_same_cache_counter_shape() { + let tokens: OpenCodeTokens = serde_json::from_value(json!({ + "input":5,"output":2,"reasoning":1,"cache":{"read":3,"write":4} + })) + .unwrap(); + assert_eq!(tokens.input + tokens.cache.read + tokens.cache.write, 12); + assert_eq!(tokens.output, 2); + assert_eq!(tokens.reasoning, 1); + } +} diff --git a/bt-daemon/src/agents/usage/opencode_tokens.rs b/bt-daemon/src/agents/usage/opencode_tokens.rs new file mode 100644 index 00000000..e3e4cbb5 --- /dev/null +++ b/bt-daemon/src/agents/usage/opencode_tokens.rs @@ -0,0 +1,32 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Default, Serialize, Deserialize)] +pub(crate) struct OpenCodeTokens { + #[serde(default)] + pub input: i64, + #[serde(default)] + pub output: i64, + #[serde(default)] + pub reasoning: i64, + #[serde(default)] + pub cache: OpenCodeCacheTokens, +} + +impl OpenCodeTokens { + /// OpenCode reports uncached input separately from cache reads and writes. + pub fn prompt_tokens(&self) -> i64 { + self.input + self.cache.read + self.cache.write + } + + pub fn total_tokens(&self) -> i64 { + self.prompt_tokens() + self.output + self.reasoning + } +} + +#[derive(Clone, Default, Serialize, Deserialize)] +pub(crate) struct OpenCodeCacheTokens { + #[serde(default)] + pub read: i64, + #[serde(default)] + pub write: i64, +} diff --git a/bt-daemon/src/agents/usage/pi_usage.rs b/bt-daemon/src/agents/usage/pi_usage.rs new file mode 100644 index 00000000..c14a6d5c --- /dev/null +++ b/bt-daemon/src/agents/usage/pi_usage.rs @@ -0,0 +1,33 @@ +use serde::{Deserialize, Serialize}; + +/// Pi normalizes provider usage before forwarding events to the daemon. +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(crate) struct PiUsage { + #[serde(default)] + pub input: i64, + #[serde(default)] + pub output: i64, + // Pi reports `reasoning` as a subset of `output`, and only for providers + // that expose the breakdown. + #[serde(default)] + pub reasoning: Option, + #[serde(default)] + pub cache_read: i64, + // `cacheWrite1h` is the subset of `cacheWrite` written with 1h retention. + #[serde(default)] + pub cache_write: i64, + #[serde(default)] + pub cache_write1h: Option, + #[serde(default)] + pub total_tokens: Option, + #[serde(default)] + pub cost: Option, +} + +#[derive(Default, Deserialize, Serialize)] +pub(crate) struct PiCost { + #[serde(default)] + pub total: Option, +} diff --git a/bt-daemon/src/agents/usage/provider_usage.rs b/bt-daemon/src/agents/usage/provider_usage.rs new file mode 100644 index 00000000..8a9d4330 --- /dev/null +++ b/bt-daemon/src/agents/usage/provider_usage.rs @@ -0,0 +1,88 @@ +use super::{CamelCaseUsage, SnakeCaseUsage, UsageMetrics}; +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use std::collections::BTreeMap; + +#[derive(Debug, Clone, Serialize)] +#[serde(untagged)] +pub(crate) enum ProviderUsage { + SnakeCase(Box), + CamelCase(Box), + Unknown(Extensions), +} + +impl<'de> Deserialize<'de> for ProviderUsage { + fn deserialize>(deserializer: D) -> Result { + // Inspect field names only at the decoding boundary. Optional-only + // untagged structs would otherwise accept and swallow other variants. + let raw = Box::::deserialize(deserializer)?; + let fields: BTreeMap = + serde_json::from_str(raw.get()).map_err(serde::de::Error::custom)?; + let snake = SNAKE_FIELDS.iter().any(|field| fields.contains_key(*field)); + let camel = CAMEL_FIELDS.iter().any(|field| fields.contains_key(*field)); + match (snake, camel) { + (true, false) => serde_json::from_str(raw.get()) + .map(Self::SnakeCase) + .map_err(serde::de::Error::custom), + (false, true) => serde_json::from_str(raw.get()) + .map(Self::CamelCase) + .map_err(serde::de::Error::custom), + (false, false) => serde_json::from_str(raw.get()) + .map(Self::Unknown) + .map_err(serde::de::Error::custom), + (true, true) => Err(serde::de::Error::custom( + "mixed snake_case and camelCase usage fields", + )), + } + } +} +impl ProviderUsage { + pub fn metrics(&self) -> UsageMetrics { + match self { + Self::SnakeCase(usage) => usage.metrics(), + Self::CamelCase(usage) => usage.metrics(), + Self::Unknown(_) => UsageMetrics::default(), + } + } +} + +const SNAKE_FIELDS: &[&str] = &[ + "input_tokens", + "prompt_tokens", + "output_tokens", + "completion_tokens", + "total_tokens", + "tokens", + "cached_input_tokens", + "prompt_cached_tokens", + "cache_read_tokens", + "cache_read_input_tokens", + "cache_creation_input_tokens", + "prompt_cache_creation_tokens", + "reasoning_output_tokens", + "completion_reasoning_tokens", + "reasoning_tokens", + "thinking_tokens", + "input_tokens_details", + "prompt_tokens_details", + "output_tokens_details", + "completion_tokens_details", + "cache_creation", +]; +const CAMEL_FIELDS: &[&str] = &[ + "inputTokens", + "promptTokens", + "outputTokens", + "completionTokens", + "totalTokens", + "cachedReadTokens", + "cacheReadTokens", + "cacheCreationTokens", + "reasoningTokens", + "thinkingTokens", + "apiDurationMs", + "costUsdTicks", + "modelCalls", + "modelUsage", +]; diff --git a/bt-daemon/src/agents/usage/snake_case_usage.rs b/bt-daemon/src/agents/usage/snake_case_usage.rs new file mode 100644 index 00000000..5d6d67ad --- /dev/null +++ b/bt-daemon/src/agents/usage/snake_case_usage.rs @@ -0,0 +1,138 @@ +use super::UsageMetrics; +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; + +/// Snake-case input/output usage (Codex/OpenAI-compatible and Claude fields). +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct SnakeCaseUsage { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub total_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cached_input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_cached_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_read_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_read_input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_creation_input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_cache_creation_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_output_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_reasoning_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thinking_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input_tokens_details: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_tokens_details: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_tokens_details: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_tokens_details: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_creation: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub estimated_cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub total_cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost_usd: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct TokenDetails { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cached_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_creation_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_write_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_tokens: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct CacheCreation { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ephemeral_5m_input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ephemeral_1h_input_tokens: Option, +} +impl SnakeCaseUsage { + pub fn metrics(&self) -> UsageMetrics { + let input_details = self.input_tokens_details.as_ref(); + let prompt_details = self.prompt_tokens_details.as_ref(); + let output_details = self.output_tokens_details.as_ref(); + let completion_details = self.completion_tokens_details.as_ref(); + UsageMetrics { + prompt_tokens: self.input_tokens.or(self.prompt_tokens).map(|n| n as f64), + completion_tokens: self + .output_tokens + .or(self.completion_tokens) + .map(|n| n as f64), + tokens: self.total_tokens.or(self.tokens).map(|n| n as f64), + prompt_cached_tokens: self + .cached_input_tokens + .or(self.prompt_cached_tokens) + .or_else(|| input_details.and_then(|d| d.cached_tokens)) + .or_else(|| prompt_details.and_then(|d| d.cached_tokens)) + .or(self.cache_read_tokens) + .or(self.cache_read_input_tokens) + .map(|n| n as f64), + prompt_cache_creation_tokens: self + .prompt_cache_creation_tokens + .or_else(|| { + input_details.and_then(|d| d.cache_creation_tokens.or(d.cache_write_tokens)) + }) + .or_else(|| { + prompt_details.and_then(|d| d.cache_creation_tokens.or(d.cache_write_tokens)) + }) + .or(self.cache_creation_input_tokens) + .map(|n| n as f64), + completion_reasoning_tokens: self + .reasoning_output_tokens + .or(self.completion_reasoning_tokens) + .or(self.reasoning_tokens) + .or_else(|| output_details.and_then(|d| d.reasoning_tokens)) + .or_else(|| completion_details.and_then(|d| d.reasoning_tokens)) + .map(|n| n as f64), + thinking_tokens: self.thinking_tokens.map(|n| n as f64), + cost: self.cost, + estimated_cost: self + .cost + .or(self.estimated_cost) + .or(self.total_cost) + .or(self.cost_usd), + ..UsageMetrics::default() + } + } + pub fn is_empty(&self) -> bool { + self.metrics().is_empty() + && self.extra.is_empty() + && self.cache_creation.is_none() + && self.input_tokens_details.is_none() + && self.prompt_tokens_details.is_none() + && self.output_tokens_details.is_none() + && self.completion_tokens_details.is_none() + } +} diff --git a/bt-daemon/src/agents/usage/token_metrics.rs b/bt-daemon/src/agents/usage/token_metrics.rs new file mode 100644 index 00000000..05bd2e30 --- /dev/null +++ b/bt-daemon/src/agents/usage/token_metrics.rs @@ -0,0 +1,39 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +pub(crate) struct TokenMetrics { + #[serde(skip_serializing_if = "Option::is_none")] + pub prompt_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub completion_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub prompt_cached_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub prompt_cache_creation_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub completion_reasoning_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub tokens: Option, +} + +impl TokenMetrics { + pub(crate) fn add(&mut self, other: &Self) { + fn add(to: &mut Option, from: Option) { + if let Some(from) = from { + *to = Some(to.unwrap_or(0).saturating_add(from)); + } + } + add(&mut self.prompt_tokens, other.prompt_tokens); + add(&mut self.completion_tokens, other.completion_tokens); + add(&mut self.prompt_cached_tokens, other.prompt_cached_tokens); + add( + &mut self.prompt_cache_creation_tokens, + other.prompt_cache_creation_tokens, + ); + add( + &mut self.completion_reasoning_tokens, + other.completion_reasoning_tokens, + ); + add(&mut self.tokens, other.tokens); + } +} diff --git a/bt-daemon/src/agents/usage/usage_metrics.rs b/bt-daemon/src/agents/usage/usage_metrics.rs new file mode 100644 index 00000000..c4d392bc --- /dev/null +++ b/bt-daemon/src/agents/usage/usage_metrics.rs @@ -0,0 +1,97 @@ +use serde::Serialize; + +/// Typed normalized metrics for the readers that historically emit floats. +#[derive(Debug, Clone, Default, Serialize)] +pub(crate) struct UsageMetrics { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_cached_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt_cache_creation_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub completion_reasoning_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub thinking_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub estimated_cost: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_duration_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost_usd_ticks: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_calls: Option, +} +impl UsageMetrics { + pub fn is_empty(&self) -> bool { + [ + self.prompt_tokens, + self.completion_tokens, + self.tokens, + self.prompt_cached_tokens, + self.prompt_cache_creation_tokens, + self.completion_reasoning_tokens, + self.thinking_tokens, + self.cost, + self.estimated_cost, + self.api_duration_ms, + self.cost_usd_ticks, + self.model_calls, + ] + .iter() + .all(Option::is_none) + } + pub fn with_total(mut self) -> Self { + if self.tokens.is_none() { + self.tokens = self + .prompt_tokens + .zip(self.completion_tokens) + .map(|(p, c)| p + c); + } + self + } + pub fn observe(&mut self, other: Self) { + if other.prompt_tokens.is_some() { + self.prompt_tokens = other.prompt_tokens; + } + if other.completion_tokens.is_some() { + self.completion_tokens = other.completion_tokens; + } + if other.tokens.is_some() { + self.tokens = other.tokens; + } + if other.prompt_cached_tokens.is_some() { + self.prompt_cached_tokens = other.prompt_cached_tokens; + } + if other.prompt_cache_creation_tokens.is_some() { + self.prompt_cache_creation_tokens = other.prompt_cache_creation_tokens; + } + if other.completion_reasoning_tokens.is_some() { + self.completion_reasoning_tokens = other.completion_reasoning_tokens; + } + if other.thinking_tokens.is_some() { + self.thinking_tokens = other.thinking_tokens; + } + if other.cost.is_some() { + self.cost = other.cost; + } + if other.estimated_cost.is_some() { + self.estimated_cost = other.estimated_cost; + } + if other.api_duration_ms.is_some() { + self.api_duration_ms = other.api_duration_ms; + } + if other.cost_usd_ticks.is_some() { + self.cost_usd_ticks = other.cost_usd_ticks; + } + if other.model_calls.is_some() { + self.model_calls = other.model_calls; + } + } +} diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index cb401e61..355280ec 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -4,6 +4,9 @@ //! the output shape to this crate so every front-end reports daemon commands //! 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; @@ -101,22 +104,6 @@ pub struct ImportSummary { pub finalized: bool, } -#[derive(Debug, Clone, Serialize)] -pub struct AuthDiagnostic { - pub status: String, - pub source: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub kind: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub profile: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub org_name: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub expires_at_ms: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, -} - #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum DaemonStatus { @@ -157,9 +144,7 @@ impl DaemonDiagnostic { /// The daemon answered and could not authenticate the route. pub fn auth_failed(&self) -> bool { - self.auth - .as_ref() - .is_some_and(|auth| auth.status == "error") + self.auth.as_ref().is_some_and(AuthDiagnostic::is_error) } } diff --git a/bt-daemon/src/command_output/auth_diagnostic.rs b/bt-daemon/src/command_output/auth_diagnostic.rs new file mode 100644 index 00000000..a4269929 --- /dev/null +++ b/bt-daemon/src/command_output/auth_diagnostic.rs @@ -0,0 +1,66 @@ +use crate::wire::{AuthSelection, AuthSource}; +use serde::Serialize; + +#[derive(Debug, Clone, Serialize)] +pub struct AuthDiagnostic { + pub status: String, + pub source: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub profile: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub org_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub expires_at_ms: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl AuthDiagnostic { + pub(crate) fn source_label(selection: &AuthSelection) -> &'static str { + match selection.effective_source() { + AuthSource::SavedProfile => "saved_profile", + AuthSource::Environment => "environment", + AuthSource::Auto => "command_context", + } + } + + pub(crate) fn ready( + selection: AuthSelection, + org_name: Option, + expires_at_ms: Option, + ) -> Self { + Self { + status: "ready".into(), + source: Self::source_label(&selection).into(), + kind: None, + profile: selection.profile, + org_name, + expires_at_ms, + error: None, + } + } + + pub(crate) fn unconfirmed(status: &str, source: &str, error: Option) -> Self { + Self { + status: status.into(), + source: source.into(), + kind: None, + profile: None, + org_name: None, + expires_at_ms: None, + error, + } + } + + /// Authentication resolved successfully in the reporting process. + pub fn is_ready(&self) -> bool { + self.status == "ready" + } + + /// Authentication was checked and failed, rather than remaining unknown. + pub fn is_error(&self) -> bool { + self.status == "error" + } +} diff --git a/bt-daemon/src/dispatch.rs b/bt-daemon/src/dispatch.rs index f27facaa..a75875e4 100644 --- a/bt-daemon/src/dispatch.rs +++ b/bt-daemon/src/dispatch.rs @@ -437,11 +437,7 @@ async fn hydrate_claude_transcript_references(data_dir: &std::path::Path, env: & let Ok(fields) = TranscriptPayload::decode(&env.payload) else { return; }; - if fields.claude_mirrors.is_some() - || fields.mirror.is_some() - || fields.snapshot.is_some() - || fields.replay.is_some() - { + if fields.has_claude_capture() { return; } // Claude writes the subagent's ancestry alongside its transcript by the @@ -482,13 +478,7 @@ async fn hydrate_claude_transcript_references(data_dir: &std::path::Path, env: & } let mirror_session = crate::ids::session_namespace(&env.source, &env.session_id); let mut mirrors = std::collections::BTreeMap::new(); - for path in [ - fields.transcript_path.as_deref(), - fields.agent_transcript_path.as_deref(), - ] - .into_iter() - .flatten() - { + for path in fields.native_paths() { if mirrors.contains_key(path) { continue; } diff --git a/bt-daemon/src/hook.rs b/bt-daemon/src/hook.rs index 39c63019..faa97004 100644 --- a/bt-daemon/src/hook.rs +++ b/bt-daemon/src/hook.rs @@ -7,7 +7,6 @@ use std::time::{SystemTime, UNIX_EPOCH}; use crate::args::HookArgs; use crate::client::{forward_envelope, HostInfo}; -use crate::route::apply_additional_metadata; use crate::wire::{self, Envelope, SessionRoute}; use crate::{paths, settings}; @@ -287,7 +286,7 @@ async fn capture_hook( if route.destination.is_none() { anyhow::bail!("trace destination is not configured for {}", args.source); } - apply_additional_metadata(&mut route, args.additional_metadata.as_deref())?; + route.apply_additional_metadata(args.additional_metadata.as_deref())?; let mut env = build_hook_envelope(&args, route, payload, session_id, event); if let Some(context) = &managed_context { env.managed_run_id = Some(context.managed_run_id.clone()); diff --git a/bt-daemon/src/journal.rs b/bt-daemon/src/journal.rs index 8ddcde93..01211698 100644 --- a/bt-daemon/src/journal.rs +++ b/bt-daemon/src/journal.rs @@ -5,7 +5,7 @@ //! Managed-run acceptance records remain separate so flush can discover //! pipelines after the daemon that accepted them has restarted or idle-exited. -use crate::wire::{BackendAuth, Envelope, RedactedEnvelope, SessionRoute}; +use crate::wire::SessionRoute; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use std::path::{Path, PathBuf}; @@ -187,39 +187,10 @@ pub async fn gc_old_managed_runs(data_dir: &Path, max_age: std::time::Duration) } } -/// Reconstruct a translator-usable [`Envelope`] from a redacted journal entry. -/// The live token is gone (redacted), so `auth.token` is empty — fine for -/// rebuilding translator state; the sink must be re-supplied live credentials -/// if replay needs to actually deliver. -pub fn envelope_from_redacted(r: RedactedEnvelope) -> Envelope { - let route = r.route; - let config = route.as_ref().map(|route| { - route.with_auth(BackendAuth { - token: String::new(), - api_url: None, - app_url: None, - org_name: route.auth.org_name.clone(), - org_id: None, - }) - }); - Envelope { - source: r.source, - source_version: r.source_version, - plugin_version: r.plugin_version, - session_id: r.session_id, - event: r.event, - ts_ms: r.ts_ms, - managed_run_id: r.managed_run_id, - capture: r.capture, - payload: r.payload, - route, - config, - } -} - #[cfg(test)] mod tests { use super::*; + use crate::wire::Envelope; #[test] fn pi_journaled_request_configuration_replays_unchanged() { diff --git a/bt-daemon/src/managed_run/opencode.rs b/bt-daemon/src/managed_run/opencode.rs index 26d06b8c..041059e9 100644 --- a/bt-daemon/src/managed_run/opencode.rs +++ b/bt-daemon/src/managed_run/opencode.rs @@ -1,7 +1,7 @@ //! OpenCode managed runs add the tracing plugin to inline config. use super::{Injection, ManagedRun}; -use crate::agents::schema::{OpenCodeConfig, OpenCodePlugin}; +use crate::agents::schema::OpenCodeConfig; use crate::agents::OpenCode; use crate::args::RunHookCommand; use std::ffi::OsString; @@ -74,7 +74,6 @@ fn opencode_managed_config(existing: Option<&str>, v2: bool) -> anyhow::Result OpenCodeConfig::default(), }; - let plugins = config.plugin.get_or_insert_with(Vec::new); let plugin = crate::env::var("BRAINTRUST_TRACE_OPENCODE_PLUGIN_SPEC").unwrap_or_else(|| { if v2 { "@braintrust/trace-opencode" @@ -83,9 +82,7 @@ fn opencode_managed_config(existing: Option<&str>, v2: bool) -> anyhow::Result { - SourceEvent::Event(Box::new(crate::journal::envelope_from_redacted(event))) - } + EventRecord::Event(event) => SourceEvent::Event(Box::new(event.into_envelope())), EventRecord::Control(control) => SourceEvent::Control(control), }; Ok(Some(SourceRecord { diff --git a/bt-daemon/src/route.rs b/bt-daemon/src/route.rs index 9b49f83d..a97365cf 100644 --- a/bt-daemon/src/route.rs +++ b/bt-daemon/src/route.rs @@ -3,47 +3,9 @@ use std::path::PathBuf; +#[cfg(test)] use crate::wire::SessionRoute; -/// Apply one invocation-local JSON metadata override to a non-secret route. -/// -/// The route is then carried unchanged through live hooks, managed runs, and -/// transcript import. Keeping validation here gives every public command the -/// same contract and prevents individual agent shims from parsing JSON. -pub(crate) fn apply_additional_metadata( - route: &mut SessionRoute, - additional_metadata: Option<&str>, -) -> anyhow::Result<()> { - let Some(metadata) = additional_metadata else { - return Ok(()); - }; - let value: serde_json::Value = serde_json::from_str(metadata) - .map_err(|e| anyhow::anyhow!("invalid --additional-metadata JSON: {e}"))?; - if !value.is_object() { - anyhow::bail!("--additional-metadata must be a JSON object"); - } - route.additional_metadata = Some(value); - Ok(()) -} - -/// Apply invocation-local root-span tags to a route. Trim whitespace and reject -/// empty tags here; the set keeps route tags unique. -pub(crate) fn apply_tags(route: &mut SessionRoute, tags: &[String]) -> anyhow::Result<()> { - if tags.is_empty() { - return Ok(()); - } - let mut normalized = std::collections::BTreeSet::new(); - for tag in tags { - let tag = tag.trim(); - if tag.is_empty() { - anyhow::bail!("--tag must not be empty"); - } - normalized.insert(tag.to_string()); - } - route.tags = normalized; - Ok(()) -} - pub(crate) fn resolve_span_plugin_paths(paths: &[PathBuf]) -> anyhow::Result> { let paths: Vec<_> = paths .iter() @@ -95,15 +57,19 @@ mod tests { additional_metadata: Some(serde_json::json!({"saved": true})), ..SessionRoute::default() }; - apply_additional_metadata(&mut route, Some(r#"{"run_id":"123"}"#)).unwrap(); + route + .apply_additional_metadata(Some(r#"{"run_id":"123"}"#)) + .unwrap(); assert_eq!( route.additional_metadata, Some(serde_json::json!({"run_id": "123"})) ); - let error = apply_additional_metadata(&mut route, Some("[]")).unwrap_err(); + let error = route.apply_additional_metadata(Some("[]")).unwrap_err(); assert!(error.to_string().contains("must be a JSON object")); - let error = apply_additional_metadata(&mut route, Some("not-json")).unwrap_err(); + let error = route + .apply_additional_metadata(Some("not-json")) + .unwrap_err(); assert!(error .to_string() .contains("invalid --additional-metadata JSON")); @@ -115,13 +81,15 @@ mod tests { tags: ["saved".into()].into_iter().collect(), ..SessionRoute::default() }; - apply_tags(&mut route, &[" ci ".into(), "ci".into(), "docs".into()]).unwrap(); + route + .apply_tags(&[" ci ".into(), "ci".into(), "docs".into()]) + .unwrap(); assert_eq!( route.tags, ["ci".into(), "docs".into()].into_iter().collect() ); - let error = apply_tags(&mut route, &[" ".into()]).unwrap_err(); + let error = route.apply_tags(&[" ".into()]).unwrap_err(); assert!(error.to_string().contains("must not be empty")); } } diff --git a/bt-daemon/src/server/claude_transcripts.rs b/bt-daemon/src/server/claude_transcripts.rs index e14f6fc1..fc7a6196 100644 --- a/bt-daemon/src/server/claude_transcripts.rs +++ b/bt-daemon/src/server/claude_transcripts.rs @@ -42,16 +42,8 @@ impl Daemon { return; }; let through = fields - .claude_mirrors - .as_ref() - .and_then(|mirrors| mirrors.get(path)) - .or_else(|| { - fields - .mirror - .as_ref() - .filter(|mirror| mirror.path.as_deref() == Some(path)) - }) - .and_then(|mirror| mirror.through); + .claude_reference(path) + .and_then(|reference| reference.through); #[derive(serde::Serialize)] struct PollPayload<'a> { transcript_path: &'a str, diff --git a/bt-daemon/src/server/ingress.rs b/bt-daemon/src/server/ingress.rs index 6aa6a6b6..381507f4 100644 --- a/bt-daemon/src/server/ingress.rs +++ b/bt-daemon/src/server/ingress.rs @@ -122,7 +122,7 @@ async fn next_evicted_event( .ok_or_else(|| anyhow::anyhow!("replay range ends inside a record"))?; anyhow::ensure!(entry.id <= through, "invalid replay end boundary"); if let EventRecord::Event(redacted) = entry.record { - let mut env = journal::envelope_from_redacted(redacted); + let mut env = redacted.into_envelope(); let Some(source) = daemon.translators.canonical_source(&env.source) else { continue; }; diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index b6e22ec4..a6b44521 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -197,7 +197,7 @@ async fn retained_references(data_dir: &std::path::Path) -> anyhow::Result) -> Vec

= HashMap::new(); if let Ok(Some(template)) = events.identity().await { - let env = journal::envelope_from_redacted(template); + let env = template.into_envelope(); daemon.remember_claude_transcripts(&env); if let Some(route) = &env.route { latest_by_route.insert( @@ -64,7 +64,7 @@ pub(super) async fn discover_unprocessed_journals(daemon: &Arc) -> Vec

{ - let mut env = journal::envelope_from_redacted(redacted); + let mut env = redacted.into_envelope(); let Some(source) = daemon.translators.canonical_source(&env.source) else { before = through; continue; diff --git a/bt-daemon/src/setup/cursor/hooks.rs b/bt-daemon/src/setup/cursor/hooks.rs index 9a4b06c8..6f96fa56 100644 --- a/bt-daemon/src/setup/cursor/hooks.rs +++ b/bt-daemon/src/setup/cursor/hooks.rs @@ -5,9 +5,7 @@ //! marked with their process identity, which later runs remove once that //! process has exited. -use crate::agents::schema::{ - CursorCommandHook, CursorHookEntries, CursorHookEntry, CursorHooks, HookFile, -}; +use crate::agents::schema::{CursorCommandHook, CursorHooks, HookFile}; #[cfg(test)] use crate::setup::common::load_object; use crate::setup::common::{edit_json, load_json, FileAccess}; @@ -125,8 +123,7 @@ fn capture_entry_is_registered(config: &CursorHooks, event: &str, command: &str) let Ok(expected) = capture_registration(event, command) else { return false; }; - matches!(config.hooks.as_ref().and_then(|hooks| hooks.get(event)), Some(CursorHookEntries::Entries(entries)) - if entries.iter().any(|entry| matches!(entry, CursorHookEntry::Command(entry) if entry == &expected))) + config.contains_registration(event, &expected) } fn powershell_encoded_command(script: &str) -> String { @@ -186,17 +183,9 @@ fn remove_stale_managed_hooks( config: &mut CursorHooks, mut process_is_alive: impl FnMut(&ProcessIdentity) -> bool, ) { - let Some(hooks) = &mut config.hooks else { - return; - }; - for entries in hooks.values_mut() { - if let CursorHookEntries::Entries(entries) = entries { - entries.retain(|entry| { - managed_process_identity(entry.command().unwrap_or_default()) - .is_none_or(|identity| process_is_alive(&identity)) - }); - } - } + config.retain_commands(|command| { + managed_process_identity(command).is_none_or(|identity| process_is_alive(&identity)) + }); } #[cfg(test)] @@ -215,36 +204,23 @@ fn apply_specs( config.version.get_or_insert(1); } if enable || config.hooks.is_some() { - let hooks = config.hooks.get_or_insert_with(Default::default); let persistent = specs == persistent_specs()?; if persistent { - for entries in hooks.values_mut() { - if let CursorHookEntries::Entries(entries) = entries { - entries.retain(|entry| !entry.command().is_some_and(is_persistent_command)); - } - } + config.retain_commands(|command| !is_persistent_command(command)); } for (event, command) in specs { - if !enable && !hooks.contains_key(event) { - continue; - } - let entries = hooks - .entry(event.clone()) - .or_insert_with(|| CursorHookEntries::Entries(Vec::new())); - let CursorHookEntries::Entries(entries) = entries else { - anyhow::bail!( - "Cursor hook event `{event}` must be an array: {}", - path.display() - ); - }; - entries.retain(|entry| entry.command() != Some(command.as_str())); - if enable { - entries.push(CursorHookEntry::Command(if persistent { + let replacement = if enable { + Some(if persistent { capture_registration(event, command)? } else { CursorCommandHook::capture(command.clone(), None) - })); - } + }) + } else { + None + }; + config + .replace_registration(event, command, replacement) + .map_err(|error| anyhow::anyhow!("{error}: {}", path.display()))?; } } Ok(()) diff --git a/bt-daemon/src/setup/opencode.rs b/bt-daemon/src/setup/opencode.rs index b472eb94..ec71a000 100644 --- a/bt-daemon/src/setup/opencode.rs +++ b/bt-daemon/src/setup/opencode.rs @@ -30,26 +30,17 @@ fn config_path() -> PathBuf { } fn is_ours(plugin: &OpenCodePlugin) -> bool { - plugin.package().is_some_and(|plugin| { - plugin == PACKAGE - || plugin - .strip_prefix(PACKAGE) - .is_some_and(|version| version.starts_with('@')) - }) -} - -/// Replace any entry for the plugin with the bundled major version. -fn pin_plugin(plugins: &mut Vec) -> anyhow::Result<()> { - plugins.retain(|plugin| !is_ours(plugin)); - plugins.push(OpenCodePlugin::Package(plugin_spec()?)); - Ok(()) + plugin.matches_package(PACKAGE) } fn enable_at(path: &Path) -> anyhow::Result<()> { edit_json( path, FileAccess::Inherited, - |config: &mut OpenCodeConfig, _| pin_plugin(config.plugin.get_or_insert_with(Vec::new)), + |config: &mut OpenCodeConfig, _| { + config.replace_plugin(is_ours, OpenCodePlugin::Package(plugin_spec()?)); + Ok(()) + }, ) } @@ -61,12 +52,11 @@ fn update_at(path: &Path) -> anyhow::Result<()> { if !existed { bail!(NOT_INSTALLED); } - let plugins = config - .plugin - .as_mut() - .filter(|plugins| plugins.iter().any(is_ours)) - .ok_or_else(|| anyhow::anyhow!(NOT_INSTALLED))?; - pin_plugin(plugins) + if config.find_plugin(is_ours).is_none() { + bail!(NOT_INSTALLED); + } + config.replace_plugin(is_ours, OpenCodePlugin::Package(plugin_spec()?)); + Ok(()) }, ) } @@ -76,9 +66,7 @@ fn disable_at(path: &Path) -> anyhow::Result<()> { path, FileAccess::Inherited, |config: &mut OpenCodeConfig, _| { - if let Some(plugins) = &mut config.plugin { - plugins.retain(|plugin| !is_ours(plugin)); - } + config.retain_plugins(|plugin| !is_ours(plugin)); Ok(()) }, ) @@ -107,9 +95,7 @@ impl Setup for OpenCode { }; let expected = plugin_spec().ok(); config - .plugin - .as_ref() - .and_then(|plugins| plugins.iter().find(|plugin| is_ours(plugin))) + .find_plugin(is_ours) .and_then(OpenCodePlugin::package) .is_some_and(|plugin| Some(plugin) != expected.as_deref()) } diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 816ca498..8cc4ee8d 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -5,9 +5,11 @@ //! behavior, setup, managed runs, imports, and output contracts stay here with //! the coding-agent integrations. -use crate::route::{apply_additional_metadata, apply_tags, resolve_span_plugin_paths}; +use crate::route::resolve_span_plugin_paths; use crate::trace_command::{DoctorAgent, DoctorArgs, SettingsScope, SetupAgent, TraceCommand}; -use crate::wire::{AuthSelection, AuthSource, SessionConfig, SessionRoute, TraceDestination}; +#[cfg(test)] +use crate::wire::AuthSource; +use crate::wire::{AuthSelection, SessionConfig, SessionRoute, TraceDestination}; use crate::{ braintrust_serve_options, paths, run_disable, run_enable, run_import, run_serve, run_status, run_traced_with_host, shutdown_daemon, AuthDiagnostic, AuthLease, AuthProvider, @@ -62,46 +64,6 @@ impl HostRouteSelection { } } -fn auth_source_label(selection: &AuthSelection) -> &'static str { - match selection.effective_source() { - AuthSource::SavedProfile => "saved_profile", - AuthSource::Environment => "environment", - AuthSource::Auto => "command_context", - } -} - -fn ready_auth_diagnostic( - selection: AuthSelection, - org_name: Option, - expires_at_ms: Option, -) -> AuthDiagnostic { - AuthDiagnostic { - status: "ready".into(), - source: auth_source_label(&selection).into(), - kind: None, - profile: selection.profile, - org_name, - expires_at_ms, - error: None, - } -} - -fn unconfirmed_auth_diagnostic( - status: &str, - source: &str, - error: Option, -) -> AuthDiagnostic { - AuthDiagnostic { - status: status.into(), - source: source.into(), - kind: None, - profile: None, - org_name: None, - expires_at_ms: None, - error, - } -} - /// Host-owned services used by the integration runtime. /// /// Implementations resolve Braintrust profiles and destination choices but do @@ -137,14 +99,14 @@ pub trait TraceHostServices: Send + Sync { .await { Ok(lease) => { - ready_auth_diagnostic(lease.selection, lease.auth.org_name, lease.expires_at_ms) + AuthDiagnostic::ready(lease.selection, lease.auth.org_name, lease.expires_at_ms) } Err(error) => AuthDiagnostic { profile: selection.profile.clone(), org_name: selection.org_name.clone(), - ..unconfirmed_auth_diagnostic( + ..AuthDiagnostic::unconfirmed( "error", - auth_source_label(selection), + AuthDiagnostic::source_label(selection), Some(error.to_string()), ) }, @@ -410,20 +372,20 @@ async fn diagnose_daemon_auth(socket: &Path, selection: &AuthSelection) -> AuthD }); // The route already shows what was requested; report only what the // daemon actually resolved. - let source = auth_source_label(selection); + let source = AuthDiagnostic::source_label(selection); match result { Err(error) if error .downcast_ref::() .is_some_and(|error| error.code == crate::wire::error_code::METHOD_NOT_FOUND) => { - unconfirmed_auth_diagnostic("unsupported", source, None) + AuthDiagnostic::unconfirmed("unsupported", source, None) } - Err(error) => unconfirmed_auth_diagnostic("unknown", source, Some(error.to_string())), + Err(error) => AuthDiagnostic::unconfirmed("unknown", source, Some(error.to_string())), Ok(result) if result.error.is_some() => { - unconfirmed_auth_diagnostic("error", source, result.error) + AuthDiagnostic::unconfirmed("error", source, result.error) } - Ok(result) => ready_auth_diagnostic( + Ok(result) => AuthDiagnostic::ready( result.selection.unwrap_or_else(|| selection.clone()), result.org_name, result.expires_at_ms, @@ -450,7 +412,7 @@ fn daemon_warnings( } let mut warnings = Vec::new(); match &daemon.auth { - Some(daemon_auth) if daemon_auth.status == "error" => { + Some(daemon_auth) if daemon_auth.is_error() => { warnings.push(format!( "the running tracing daemon cannot authenticate, so it rejects {display_name} events: {}", daemon_auth.error.as_deref().unwrap_or("unknown error") @@ -461,7 +423,7 @@ fn daemon_warnings( ); } } - Some(daemon_auth) if daemon_auth.status == "ready" && auth.status == "ready" => { + Some(daemon_auth) if daemon_auth.is_ready() && auth.is_ready() => { for (label, shell, daemon) in [ ("profile", &auth.profile, &daemon_auth.profile), ("organization", &auth.org_name, &daemon_auth.org_name), @@ -625,7 +587,7 @@ async fn doctor_output_at( let local_auth = async { match &route { Some(route) => host.services.diagnose_auth(&route.auth).await, - None => unconfirmed_auth_diagnostic( + None => AuthDiagnostic::unconfirmed( "unresolved", "unresolved", Some("route is unresolved".into()), @@ -643,7 +605,7 @@ async fn doctor_output_at( // what separates divergent credential views from failures both processes // share. Skip it when the local check already failed. let resolves_locally = match &route { - Some(route) if daemon.auth_failed() && auth.status == "ready" => { + Some(route) if daemon.auth_failed() && auth.is_ready() => { let local = HostAuthProvider { services: host.services.clone(), }; @@ -729,8 +691,8 @@ async fn run_install_command( }, ) .await?; - apply_additional_metadata(&mut route, args.additional_metadata.as_deref())?; - apply_tags(&mut route, &args.tags)?; + route.apply_additional_metadata(args.additional_metadata.as_deref())?; + route.apply_tags(&args.tags)?; if !args.plugin.is_empty() { route.span_plugins = resolve_span_plugin_paths(&args.plugin)?; } @@ -946,8 +908,8 @@ pub async fn run_trace_with_matches( }, ) .await?; - apply_additional_metadata(&mut route, import_args.additional_metadata.as_deref())?; - apply_tags(&mut route, &import_args.tags)?; + route.apply_additional_metadata(import_args.additional_metadata.as_deref())?; + route.apply_tags(&import_args.tags)?; // Resolve credentials up front, interactively if needed, so the // daemon can authenticate this route when it delivers. session_config(&host, &route).await?; @@ -1032,7 +994,7 @@ pub async fn run_trace_with_matches( } else { None }; - apply_additional_metadata(&mut route, run_args.additional_metadata.as_deref())?; + route.apply_additional_metadata(run_args.additional_metadata.as_deref())?; if let Some(mut metadata) = inherited_metadata { if let Some(overlay) = route.additional_metadata.take() { crate::settings::merge_json(&mut metadata, overlay); @@ -1040,7 +1002,7 @@ pub async fn run_trace_with_matches( route.additional_metadata = Some(metadata); } let inherited_tags = run_args.inherit.then(|| route.tags.clone()); - apply_tags(&mut route, &run_args.tags)?; + route.apply_tags(&run_args.tags)?; if let Some(tags) = inherited_tags { route.tags.extend(tags); } diff --git a/bt-daemon/src/transcript_import/antigravity.rs b/bt-daemon/src/transcript_import/antigravity.rs index 71d1689a..182a81bf 100644 --- a/bt-daemon/src/transcript_import/antigravity.rs +++ b/bt-daemon/src/transcript_import/antigravity.rs @@ -131,7 +131,7 @@ pub(super) fn envelopes( for (index, record) in records.iter().enumerate() { let record_type = record.kind.as_str(); let step = record.step_index.unwrap_or(index as i64); - let ts = created_at_ms(record).unwrap_or(start_ms); + let ts = record.created_at_ms().unwrap_or(start_ms); if record_type == "PLANNER_RESPONSE" { let before = index .checked_sub(1) @@ -240,7 +240,10 @@ fn is_tool_result(record: &AntigravityRecord) -> bool { } fn timestamp_bounds_created(records: &[AntigravityRecord]) -> (i64, i64) { - let timestamps = records.iter().filter_map(created_at_ms).collect::>(); + let timestamps = records + .iter() + .filter_map(AntigravityRecord::created_at_ms) + .collect::>(); timestamps .iter() .copied() @@ -252,11 +255,3 @@ fn timestamp_bounds_created(records: &[AntigravityRecord]) -> (i64, i64) { } }) } - -fn created_at_ms(record: &AntigravityRecord) -> Option { - record - .created_at - .as_deref() - .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok()) - .map(|value| value.timestamp_millis()) -} diff --git a/bt-daemon/src/transcript_mirror/claude_child_reference.rs b/bt-daemon/src/transcript_mirror/claude_child_reference.rs new file mode 100644 index 00000000..bf85554e --- /dev/null +++ b/bt-daemon/src/transcript_mirror/claude_child_reference.rs @@ -0,0 +1,5 @@ +#[derive(serde::Deserialize)] +pub(crate) struct ClaudeChildReference { + pub path: String, + pub through: Option, +} diff --git a/bt-daemon/src/transcript_mirror/grok_references.rs b/bt-daemon/src/transcript_mirror/grok_references.rs new file mode 100644 index 00000000..bf3bb415 --- /dev/null +++ b/bt-daemon/src/transcript_mirror/grok_references.rs @@ -0,0 +1,17 @@ +use super::Reference; + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub(crate) struct GrokReferences { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub updates: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub events: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub system_prompt: Option, +} + +impl GrokReferences { + pub fn is_empty(&self) -> bool { + self.updates.is_none() && self.events.is_none() && self.system_prompt.is_none() + } +} diff --git a/bt-daemon/src/transcript_mirror.rs b/bt-daemon/src/transcript_mirror/mod.rs similarity index 80% rename from bt-daemon/src/transcript_mirror.rs rename to bt-daemon/src/transcript_mirror/mod.rs index 21462d81..c3666305 100644 --- a/bt-daemon/src/transcript_mirror.rs +++ b/bt-daemon/src/transcript_mirror/mod.rs @@ -20,100 +20,19 @@ use std::path::{Path, PathBuf}; use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; use uuid::Uuid; -/// Journaled transcript reference. An empty object records captured absence. -#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] -pub(crate) struct Reference { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub path: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub mirror: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub through: Option, -} - -impl Reference { - pub fn captured(path: &str, mirror: &Path, through: u64) -> Self { - Self { - path: Some(path.to_owned()), - mirror: Some(mirror.to_string_lossy().into_owned()), - through: Some(through), - } - } - pub fn read_path(&self) -> Option<&str> { - self.mirror.as_deref().or(self.path.as_deref()) - } -} - -#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] -pub(crate) struct GrokReferences { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub updates: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub events: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub system_prompt: Option, -} - -impl GrokReferences { - pub fn is_empty(&self) -> bool { - self.updates.is_none() && self.events.is_none() && self.system_prompt.is_none() - } -} +mod claude_child_reference; +mod grok_references; +mod observation; +mod payload; +mod reference; +mod snapshot; -#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] -pub(crate) struct Observation { - pub path: Option, - pub observed_bytes: Option, - pub full_path: Option, - pub full_observed_bytes: Option, -} - -#[derive(Debug, Clone, serde::Deserialize)] -pub(crate) struct Snapshot { - pub path: String, - pub contents: String, -} - -/// Decode the known capture protocol once at the envelope boundary. Native -/// agent data remains in the raw journal and is decoded by its own translator. -#[derive(Default, serde::Deserialize)] -pub(crate) struct TranscriptPayload { - #[serde(default, alias = "transcriptPath")] - pub transcript_path: Option, - pub agent_transcript_path: Option, - pub agent_id: Option, - #[serde(rename = "_bt_claude_children")] - pub claude_children: Option>, - pub cwd: Option, - #[serde(rename = "_bt_transcript_mirror")] - pub mirror: Option, - #[serde(rename = "_bt_claude_transcript_mirrors")] - pub claude_mirrors: Option>, - #[serde(rename = "_bt_grok_transcript_mirrors")] - pub grok_mirrors: Option, - #[serde(rename = "_bt_transcript_observation")] - pub observation: Option, - #[serde(rename = "_bt_transcript_snapshot")] - pub snapshot: Option, - #[serde(rename = "_bt_transcript_replay")] - pub replay: Option, - #[serde(rename = "_bt_import_through_offset")] - pub import_through_offset: Option, - #[serde(rename = "_bt_import_through_ms")] - pub import_through_ms: Option, -} - -#[derive(serde::Deserialize)] -pub(crate) struct ClaudeChildReference { - pub path: String, - pub through: Option, -} - -impl TranscriptPayload { - pub fn decode(payload: &serde_json::Value) -> serde_json::Result { - serde::Deserialize::deserialize(payload) - } -} +pub(crate) use claude_child_reference::ClaudeChildReference; +pub(crate) use grok_references::GrokReferences; +pub(crate) use observation::Observation; +pub(crate) use payload::TranscriptPayload; +pub(crate) use reference::Reference; +pub(crate) use snapshot::Snapshot; /// Namespace for mirror file names (distinct from the span-id namespace). const NAMESPACE: Uuid = Uuid::from_u128(0x3d51_9a02_7c64_4b8f_9e17_a2c5_0d63_88f1); diff --git a/bt-daemon/src/transcript_mirror/observation.rs b/bt-daemon/src/transcript_mirror/observation.rs new file mode 100644 index 00000000..51e3fd46 --- /dev/null +++ b/bt-daemon/src/transcript_mirror/observation.rs @@ -0,0 +1,7 @@ +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub(crate) struct Observation { + pub path: Option, + pub observed_bytes: Option, + pub full_path: Option, + pub full_observed_bytes: Option, +} diff --git a/bt-daemon/src/transcript_mirror/payload.rs b/bt-daemon/src/transcript_mirror/payload.rs new file mode 100644 index 00000000..1b999e7e --- /dev/null +++ b/bt-daemon/src/transcript_mirror/payload.rs @@ -0,0 +1,156 @@ +use super::{ClaudeChildReference, GrokReferences, Observation, Reference, Snapshot}; + +/// Decode the known capture protocol once at the envelope boundary. Native +/// agent data remains in the raw journal and is decoded by its own translator. +#[derive(Default, serde::Deserialize)] +pub(crate) struct TranscriptPayload { + #[serde(default, alias = "transcriptPath")] + pub transcript_path: Option, + pub agent_transcript_path: Option, + pub agent_id: Option, + #[serde(rename = "_bt_claude_children")] + pub claude_children: Option>, + pub cwd: Option, + #[serde(rename = "_bt_transcript_mirror")] + pub mirror: Option, + #[serde(rename = "_bt_claude_transcript_mirrors")] + pub claude_mirrors: Option>, + #[serde(rename = "_bt_grok_transcript_mirrors")] + pub grok_mirrors: Option, + #[serde(rename = "_bt_transcript_observation")] + pub observation: Option, + #[serde(rename = "_bt_transcript_snapshot")] + pub snapshot: Option, + #[serde(rename = "_bt_transcript_replay")] + pub replay: Option, + #[serde(rename = "_bt_import_through_offset")] + pub import_through_offset: Option, + #[serde(rename = "_bt_import_through_ms")] + pub import_through_ms: Option, +} + +impl TranscriptPayload { + pub fn decode(payload: &serde_json::Value) -> serde_json::Result { + serde::Deserialize::deserialize(payload) + } + + /// Modern Claude observations include a map even when capture found no + /// readable files. Its presence must prevent a later native-file reread. + pub fn has_claude_capture(&self) -> bool { + self.claude_mirrors.is_some() + || self.mirror.is_some() + || self.snapshot.is_some() + || self.replay.is_some() + } + + /// The latest observation for the poller, including the legacy single + /// reference format. Readers still distinguish a modern map's absence + /// from a missing entry so captured absence never falls back to live data. + pub fn claude_reference(&self, path: &str) -> Option<&Reference> { + self.claude_mirrors + .as_ref() + .and_then(|mirrors| mirrors.get(path)) + .or_else(|| self.matching_mirror(path)) + } + + pub fn matching_mirror(&self, path: &str) -> Option<&Reference> { + self.mirror + .as_ref() + .filter(|mirror| mirror.matches_path(path)) + } + + pub fn snapshot_for(&self, path: &str) -> Option<&str> { + self.snapshot + .as_ref() + .filter(|snapshot| snapshot.path == path) + .map(|snapshot| snapshot.contents.as_str()) + } + + pub fn native_paths(&self) -> impl Iterator { + [ + self.transcript_path.as_deref(), + self.agent_transcript_path.as_deref(), + ] + .into_iter() + .flatten() + } + + /// Codex stop hooks must read the child transcript; other hooks prefer + /// the main path. A captured mirror takes precedence in either case. + pub fn codex_read_path(&self, subagent_stop: bool) -> Option<&str> { + self.mirror + .as_ref() + .and_then(|reference| reference.mirror.as_deref()) + .or_else(|| { + if subagent_stop { + self.agent_transcript_path.as_deref() + } else { + self.transcript_path + .as_deref() + .or(self.agent_transcript_path.as_deref()) + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn codex_selects_captured_or_native_path_for_the_event_scope() { + for (raw, main, child) in [ + ( + json!({"transcript_path":"main","agent_transcript_path":"child"}), + Some("main"), + Some("child"), + ), + (json!({"transcript_path":"main"}), Some("main"), None), + ( + json!({"agent_transcript_path":"child"}), + Some("child"), + Some("child"), + ), + ( + json!({"transcript_path":"main","_bt_transcript_mirror":{"mirror":"captured","through":12}}), + Some("captured"), + Some("captured"), + ), + ] { + let payload = TranscriptPayload::decode(&raw).unwrap(); + assert_eq!(payload.codex_read_path(false), main); + assert_eq!(payload.codex_read_path(true), child); + } + } + + #[test] + fn captured_absence_and_legacy_references_keep_their_meaning() { + let payload = TranscriptPayload::decode(&json!({ + "_bt_claude_transcript_mirrors":{}, + "_bt_transcript_mirror":{"path":"main","mirror":"legacy","through":42}, + "_bt_transcript_snapshot":{"path":"main","contents":"snapshot"} + })) + .unwrap(); + assert!(payload.has_claude_capture()); + assert!(payload + .claude_mirrors + .as_ref() + .unwrap() + .get("main") + .is_none()); + // Pollers can reuse a legacy checkpoint; readers still treat the + // explicit empty modern capture as absence instead of falling back. + assert_eq!( + payload.claude_reference("main").unwrap().captured_prefix(), + Some(("legacy", 42)) + ); + assert!(payload.claude_reference("child").is_none()); + assert_eq!(payload.snapshot_for("main"), Some("snapshot")); + assert_eq!(payload.snapshot_for("child"), None); + let absent = TranscriptPayload::decode(&json!({"_bt_transcript_mirror":{}})).unwrap(); + assert!(absent.has_claude_capture()); + assert!(absent.mirror.unwrap().captured_prefix().is_none()); + assert!(!TranscriptPayload::default().has_claude_capture()); + } +} diff --git a/bt-daemon/src/transcript_mirror/reference.rs b/bt-daemon/src/transcript_mirror/reference.rs new file mode 100644 index 00000000..9f0ba8a0 --- /dev/null +++ b/bt-daemon/src/transcript_mirror/reference.rs @@ -0,0 +1,35 @@ +use std::path::Path; + +/// Journaled transcript reference. An empty object records captured absence. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +pub(crate) struct Reference { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mirror: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub through: Option, +} + +impl Reference { + pub fn captured(path: &str, mirror: &Path, through: u64) -> Self { + Self { + path: Some(path.to_owned()), + mirror: Some(mirror.to_string_lossy().into_owned()), + through: Some(through), + } + } + pub fn read_path(&self) -> Option<&str> { + self.mirror.as_deref().or(self.path.as_deref()) + } + + /// Only a daemon mirror with a recorded byte boundary is safe for a + /// captured read. An empty reference records absence, not a live fallback. + pub fn captured_prefix(&self) -> Option<(&str, u64)> { + Some((self.mirror.as_deref()?, self.through?)) + } + + pub fn matches_path(&self, path: &str) -> bool { + self.path.as_deref() == Some(path) + } +} diff --git a/bt-daemon/src/transcript_mirror/snapshot.rs b/bt-daemon/src/transcript_mirror/snapshot.rs new file mode 100644 index 00000000..331aab27 --- /dev/null +++ b/bt-daemon/src/transcript_mirror/snapshot.rs @@ -0,0 +1,5 @@ +#[derive(Debug, Clone, serde::Deserialize)] +pub(crate) struct Snapshot { + pub path: String, + pub contents: String, +} diff --git a/bt-daemon/src/translate/antigravity.rs b/bt-daemon/src/translate/antigravity.rs index ed983c25..0f765d01 100644 --- a/bt-daemon/src/translate/antigravity.rs +++ b/bt-daemon/src/translate/antigravity.rs @@ -198,7 +198,7 @@ impl AntigravityTranslator { } fn observe_record(&mut self, record: TranscriptRecord, ts_ms: i64, ops: &mut Vec) { - let record_type = normalized_record_type(&record); + let record_type = record.normalized_kind().to_owned(); let source = &record.source; if let Some(step) = record.step_index { self.records_by_step.insert(step, record.clone()); @@ -207,7 +207,7 @@ impl AntigravityTranslator { if record_type == "USER_INPUT" && (source.is_empty() || source == "USER_EXPLICIT" || source == "USER") { - self.start_turn(clean_user_input(record_content(&record)), ts_ms, ops); + self.start_turn(clean_user_input(record.message_content()), ts_ms, ops); } if record_type == "CHECKPOINT" { @@ -608,8 +608,8 @@ fn transcript_source(event: &Envelope) -> Option { }; let snapshot = fields .snapshot - .filter(|value| value.path == path) - .map(|value| value.contents); + .filter(|snapshot| snapshot.path == path) + .map(|snapshot| snapshot.contents); Some(TranscriptSource { path: path.to_owned(), through, @@ -666,14 +666,6 @@ fn read_records( records } -fn normalized_record_type(record: &TranscriptRecord) -> String { - let record_type = &record.kind; - record_type - .strip_prefix("CORTEX_STEP_TYPE_") - .unwrap_or(record_type) - .to_string() -} - fn transcript_message( record: &TranscriptRecord, record_type: &str, @@ -687,9 +679,9 @@ fn transcript_message( _ => return None, }; let content = match role { - "user" => clean_user_input(record_content(record)), - "tool" => clean_tool_content(record_content(record)), - _ => record_content(record), + "user" => clean_user_input(record.message_content()), + "tool" => clean_tool_content(record.message_content()), + _ => record.message_content(), }; if role == "system" && content.is_null() { return None; @@ -704,16 +696,6 @@ fn transcript_message( }) } -fn record_content(record: &TranscriptRecord) -> Value { - record - .content - .as_ref() - .or(record.message.as_ref()) - .or(record.text.as_ref()) - .cloned() - .unwrap_or(Value::Null) -} - fn clean_user_input(content: Value) -> Value { let Value::String(text) = content else { return content; @@ -745,7 +727,7 @@ fn tool_details(record: &TranscriptRecord) -> ToolDetails { .tool_calls .as_ref() .and_then(|calls| calls.iter().next()); - let record_type = normalized_record_type(record); + let record_type = record.normalized_kind().to_owned(); let name = call.and_then(|call| call.name.clone()).or_else(|| { (!matches!(record_type.as_str(), "USER_INPUT" | "PLANNER_RESPONSE")) .then(|| record_type.to_ascii_lowercase()) @@ -753,14 +735,14 @@ fn tool_details(record: &TranscriptRecord) -> ToolDetails { let input = call.and_then(|call| call.args.clone()); let output = call .and_then(|call| call.output.clone()) - .or_else(|| nonempty_value(clean_tool_content(record_content(record)))); + .or_else(|| nonempty_value(clean_tool_content(record.message_content()))); let error = record .error .clone() .filter(|error| !error.is_empty()) .or_else(|| { (record_type == "ERROR_MESSAGE") - .then(|| record_content(record)) + .then(|| record.message_content()) .and_then(|content| content.as_str().map(str::to_owned)) }) .or_else(|| { @@ -768,7 +750,7 @@ fn tool_details(record: &TranscriptRecord) -> ToolDetails { .status .as_ref() .filter(|status| matches!(status.to_ascii_lowercase().as_str(), "error" | "failed")) - .map(|status| match record_content(record) { + .map(|status| match record.message_content() { Value::String(content) if !content.is_empty() => content, _ => status.clone(), }) @@ -807,17 +789,11 @@ fn planned_tool_start(records: &[TranscriptRecord], name: Option<&str>, step: i6 .as_ref()? .iter() .any(|call| call.name.as_deref() == Some(name)) - .then(|| parse_created_at(record)) + .then(|| record.created_at_ms()) .flatten() }) } -fn parse_created_at(record: &TranscriptRecord) -> Option { - chrono::DateTime::parse_from_rfc3339(record.created_at.as_deref()?) - .ok() - .map(|timestamp| timestamp.timestamp_millis()) -} - fn token_metrics(records: &[TranscriptRecord]) -> Option { let mut metrics = UsageMetrics::default(); for usage in records.iter().filter_map(|record| record.usage.as_ref()) { diff --git a/bt-daemon/src/translate/claude.rs b/bt-daemon/src/translate/claude.rs index dc23fd29..3722d146 100644 --- a/bt-daemon/src/translate/claude.rs +++ b/bt-daemon/src/translate/claude.rs @@ -9,8 +9,8 @@ use super::git::GitMetadataCache; use super::recent::{RecentMap, RecentSet, RECENT_ID_CAPACITY}; use super::tool::{ - add_tool_approval, explicit_skill_metadata, insert_skill_metadata, nonempty_error_text, - prompt_skill_names, push_unique, skill_file_load, skill_md_paths, SkillLoad, ToolApproval, + add_tool_approval, explicit_skill_metadata, nonempty_error_text, prompt_skill_names, + push_unique, skill_file_load, skill_md_paths, SkillLoad, ToolApproval, }; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, @@ -2541,10 +2541,7 @@ fn read_event_records(event: &Envelope, path: &str, offset: &mut u64) -> Vec Vec Vec { read_snapshot_bounded(contents, offset, None, through) @@ -2619,7 +2607,7 @@ fn tool_metadata( } } if let Some(skill) = skill { - insert_skill_metadata(&mut metadata, skill, requested_skills); + skill.insert_metadata(&mut metadata, requested_skills); } Value::Object(metadata) } @@ -2743,10 +2731,7 @@ fn command_output(cwd: &str, command: &str, args: &[&str]) -> Option { fn tool_span_name(tool: &str, input: &Value, skill: Option<&SkillLoad>) -> String { if let Some(skill) = skill { - return skill - .name - .as_ref() - .map_or_else(|| "skill".into(), |name| format!("skill: {name}")); + return skill.display_name(); } match tool { "Read" | "Write" | "Edit" | "MultiEdit" => string_field(input, "file_path") diff --git a/bt-daemon/src/translate/codex.rs b/bt-daemon/src/translate/codex.rs index 806db3f9..40abc68d 100644 --- a/bt-daemon/src/translate/codex.rs +++ b/bt-daemon/src/translate/codex.rs @@ -20,9 +20,9 @@ use super::git::GitMetadataCache; use super::recent::{RecentMap, RecentSet}; use super::tool::{ - add_tool_approval, compile_skill_regex, explicit_skill_metadata, insert_skill_metadata, - is_skill_name, prompt_skill_names, push_unique, skill_md_paths, tool_approval_metadata, - SkillLoad, ToolApproval, + add_tool_approval, compile_skill_regex, explicit_skill_metadata, is_skill_name, + prompt_skill_names, push_unique, skill_md_paths, tool_approval_metadata, SkillLoad, + ToolApproval, }; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, @@ -1203,7 +1203,7 @@ impl CodexTranslator { if let Some(skill_name) = &skill.name { name = format!("skill: {skill_name}"); } - insert_skill_metadata(&mut metadata, skill, &explicit_skills); + skill.insert_metadata(&mut metadata, &explicit_skills); } if let Some(permission) = permission { metadata.insert("permission".into(), permission); @@ -1692,13 +1692,9 @@ fn is_injected_user_context(text: &str) -> bool { fn effective_transcript_path(event: &Envelope) -> Option { let fields = TranscriptPayload::decode(&event.payload).ok()?; - fields.mirror.and_then(|mirror| mirror.mirror).or_else(|| { - if event.event == "SubagentStop" { - fields.agent_transcript_path - } else { - fields.transcript_path.or(fields.agent_transcript_path) - } - }) + fields + .codex_read_path(event.event == "SubagentStop") + .map(str::to_owned) } impl Scope { diff --git a/bt-daemon/src/translate/opencode.rs b/bt-daemon/src/translate/opencode.rs index fcd64dec..9e7ba3b7 100644 --- a/bt-daemon/src/translate/opencode.rs +++ b/bt-daemon/src/translate/opencode.rs @@ -1,11 +1,14 @@ //! OpenCode translator. The JavaScript package forwards native hook payloads; //! this module owns span construction, correlation, and recovery. +mod permission; +use permission::{PermissionProperties, PermissionRequest}; + use super::git::GitMetadataCache; use super::recent::{RecentMap, RecentSet}; use super::tool::{ - error_text, insert_skill_metadata, prompt_skill_names, push_unique, skill_file_load, - skill_md_paths, with_tool_approval, SkillLoad, ToolApproval, + error_text, prompt_skill_names, push_unique, skill_file_load, skill_md_paths, + with_tool_approval, SkillLoad, ToolApproval, }; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, @@ -220,100 +223,6 @@ impl From for ToolAfter { } } -#[derive(Clone, Default, Deserialize, Serialize)] -struct PermissionToolRecord { - #[serde(default, rename = "sessionID")] - session_id: Option, - #[serde(default, rename = "callID")] - call_id: Option, - #[serde(default)] - name: Option, - #[serde(default)] - tool: Option, - #[serde(default)] - input: Option, -} - -#[derive(Clone, Deserialize)] -#[serde(untagged)] -#[derive(Serialize)] -enum PermissionTool { - Name(String), - Record(PermissionToolRecord), -} - -#[derive(Clone, Default, Deserialize, Serialize)] -struct PermissionFields { - #[serde(default)] - id: Option, - #[serde(default, rename = "sessionID")] - session_id: Option, - #[serde(default, rename = "callID")] - call_id: Option, - #[serde(default)] - tool: Option, - #[serde(default, rename = "toolName")] - tool_name: Option, - #[serde(default, rename = "permission")] - permission: Option, - #[serde(default)] - input: Option, - #[serde(default)] - args: Option, - #[serde(default)] - title: Option, - #[serde(default, rename = "type", alias = "permissionType")] - permission_type: Option, -} - -#[derive(Deserialize)] -#[serde(untagged)] -#[derive(Serialize)] -enum PermissionPayload { - Record(Box), - Kind(String), -} - -#[derive(Default, Deserialize, Serialize)] -struct PermissionProperties { - #[serde(default)] - permission: Option, - #[serde(default)] - info: Option, - #[serde(default, rename = "permissionID")] - permission_id: Option, - #[serde(default, rename = "requestID")] - request_id: Option, - #[serde(default)] - reply: Option, - #[serde(default)] - response: Option, - #[serde(default)] - status: Option, - #[serde(flatten)] - direct: PermissionFields, -} - -impl PermissionTool { - fn record(&self) -> Option<&PermissionToolRecord> { - match self { - Self::Record(record) => Some(record), - Self::Name(_) => None, - } - } - - fn name(&self) -> Option<&str> { - match self { - Self::Name(name) => Some(name), - Self::Record(_) => None, - } - } -} - -fn permission_properties(payload: &Value) -> Option { - decode(payload.get("properties").unwrap_or(payload)) -} - #[derive(Deserialize)] #[serde(rename_all = "camelCase")] #[derive(Serialize)] @@ -570,16 +479,6 @@ impl MessageHistory { } } -#[derive(Clone, Default, Serialize, Deserialize)] -struct PermissionRequest { - id: Option, - session_id: Option, - call_id: Option, - tool: Option, - input: Option, - title: Option, - permission_type: Option, -} #[derive(Serialize, Deserialize)] struct OpenCodeTranslator { daemon_session_id: String, @@ -611,10 +510,10 @@ impl AgentTranslator for OpenCodeTranslator { .map(ToolAfter::from) .map(|tool| self.tool_after(tool, event.ts_ms)) .unwrap_or_default(), - "permission.asked" => permission_properties(&event.payload) + "permission.asked" => PermissionProperties::decode(&event.payload) .map(|permission| self.permission_asked(permission)) .unwrap_or_default(), - "permission.replied" => permission_properties(&event.payload) + "permission.replied" => PermissionProperties::decode(&event.payload) .map(|permission| self.permission_replied(permission, event.ts_ms)) .unwrap_or_default(), "session.idle" => self.finish_session_event(event, false, None), @@ -1038,7 +937,7 @@ impl OpenCodeTranslator { let tokens = info.tokens.as_ref().cloned().unwrap_or_default(); let cache_read = tokens.cache.read; let cache_write = tokens.cache.write; - let prompt = tokens.input + cache_read + cache_write; + let prompt = tokens.prompt_tokens(); let completion = tokens.output; let reasoning = tokens.reasoning; let content = state.output_parts.remove(mid).unwrap_or_default(); @@ -1121,7 +1020,7 @@ impl OpenCodeTranslator { output: Some(Value::Array(vec![assistant])), metadata: Some(metadata), metrics: Some( - json!({"prompt_tokens":prompt,"completion_tokens":completion,"tokens":prompt+completion+reasoning,"prompt_cached_tokens":cache_read,"prompt_cache_creation_tokens":cache_write,"reasoning_tokens":reasoning}), + json!({"prompt_tokens":prompt,"completion_tokens":completion,"tokens":tokens.total_tokens(),"prompt_cached_tokens":cache_read,"prompt_cache_creation_tokens":cache_write,"reasoning_tokens":reasoning}), ), error: info.error.as_ref().map(|error| format_error(Some(error))), tags: (info.summary || info.compaction).then(|| vec!["compaction".into()]), @@ -1152,7 +1051,7 @@ impl OpenCodeTranslator { .tool_args .get(&call) .and_then(|args| skill_load(&tool, args)) - .map_or_else(|| tool.clone(), |skill| skill_span_name(&skill)); + .map_or_else(|| tool.clone(), |skill| skill.display_name()); return vec![SpanOp::Insert(SpanRow { span_id: ids::span_id(&self.daemon_session_id, &format!("tool:{sid}:{call}")), root_span_id: s.effective_root_span_id.clone(), @@ -1203,7 +1102,7 @@ impl OpenCodeTranslator { let args = s.tool_args.remove(&call); let skill = args.as_ref().and_then(|args| skill_load(&tool, args)); let name = if let Some(skill) = &skill { - skill_span_name(skill) + skill.display_name() } else { event .result @@ -1217,7 +1116,7 @@ impl OpenCodeTranslator { Some(ToolApproval::Approved), ); if let (Some(skill), Some(fields)) = (&skill, metadata.as_object_mut()) { - insert_skill_metadata(fields, skill, &s.requested_skills); + skill.insert_metadata(fields, &s.requested_skills); } let had_start = s.tool_starts.contains_key(&call); let parent_span_id = s.tool_parent_span_ids.remove(&call).unwrap_or(turn); @@ -1256,56 +1155,8 @@ impl OpenCodeTranslator { }] } - fn permission_record(properties: &PermissionProperties) -> PermissionRequest { - let permission_kind = match &properties.permission { - Some(PermissionPayload::Kind(kind)) => Some(kind.clone()), - _ => None, - }; - let source = match &properties.permission { - Some(PermissionPayload::Record(record)) => record, - _ => properties.info.as_ref().unwrap_or(&properties.direct), - }; - let tool_record = source.tool.as_ref().and_then(PermissionTool::record); - PermissionRequest { - id: source - .id - .clone() - .or_else(|| properties.direct.id.clone()) - .or_else(|| properties.permission_id.clone()) - .or_else(|| properties.request_id.clone()), - session_id: source - .session_id - .clone() - .or_else(|| properties.direct.session_id.clone()) - .or_else(|| tool_record.and_then(|tool| tool.session_id.clone())), - call_id: source - .call_id - .clone() - .or_else(|| tool_record.and_then(|tool| tool.call_id.clone())), - tool: source - .tool - .as_ref() - .and_then(PermissionTool::name) - .map(str::to_owned) - .or_else(|| source.tool_name.clone()) - .or_else(|| tool_record.and_then(|tool| tool.name.clone())) - .or_else(|| tool_record.and_then(|tool| tool.tool.clone())) - // OpenCode's native permission events put the requested tool - // kind in `permission`, separate from `tool.callID`. - .or_else(|| source.permission.clone()) - .or(permission_kind), - input: source - .input - .clone() - .or_else(|| source.args.clone()) - .or_else(|| tool_record.and_then(|tool| tool.input.clone())), - title: source.title.clone(), - permission_type: source.permission_type.clone(), - } - } - fn permission_asked(&mut self, properties: PermissionProperties) -> Vec { - let request = Self::permission_record(&properties); + let request = properties.request(); if let Some(id) = &request.id { self.permission_requests.insert(id.clone(), request); } @@ -1313,13 +1164,8 @@ impl OpenCodeTranslator { } fn permission_replied(&mut self, properties: PermissionProperties, ts_ms: i64) -> Vec { - let reply = properties - .reply - .as_deref() - .or(properties.response.as_deref()) - .or(properties.status.as_deref()) - .unwrap_or(""); - let direct = Self::permission_record(&properties); + let reply = properties.reply(); + let direct = properties.request(); let request = direct .id .as_ref() @@ -1570,13 +1416,6 @@ pub(super) fn requested_skills(input: &str) -> Vec { names } -fn skill_span_name(skill: &SkillLoad) -> String { - skill - .name - .as_ref() - .map_or_else(|| "skill".into(), |name| format!("skill: {name}")) -} - /// OpenCode loads a skill through its `skill` tool, or by reading the skill's /// `SKILL.md` directly with `read` or `bash`. pub(super) fn skill_load(tool: &str, args: &Value) -> Option { diff --git a/bt-daemon/src/translate/opencode/permission.rs b/bt-daemon/src/translate/opencode/permission.rs new file mode 100644 index 00000000..63157ba8 --- /dev/null +++ b/bt-daemon/src/translate/opencode/permission.rs @@ -0,0 +1,163 @@ +//! OpenCode permission variants own their normalized request and reply precedence. +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Default, Deserialize, Serialize)] +struct PermissionToolRecord { + #[serde(default, rename = "sessionID")] + session_id: Option, + #[serde(default, rename = "callID")] + call_id: Option, + #[serde(default)] + name: Option, + #[serde(default)] + tool: Option, + #[serde(default)] + input: Option, +} + +#[derive(Clone, Deserialize)] +#[serde(untagged)] +#[derive(Serialize)] +enum PermissionTool { + Name(String), + Record(PermissionToolRecord), +} + +#[derive(Clone, Default, Deserialize, Serialize)] +struct PermissionFields { + #[serde(default)] + id: Option, + #[serde(default, rename = "sessionID")] + session_id: Option, + #[serde(default, rename = "callID")] + call_id: Option, + #[serde(default)] + tool: Option, + #[serde(default, rename = "toolName")] + tool_name: Option, + #[serde(default, rename = "permission")] + permission: Option, + #[serde(default)] + input: Option, + #[serde(default)] + args: Option, + #[serde(default)] + title: Option, + #[serde(default, rename = "type", alias = "permissionType")] + permission_type: Option, +} + +#[derive(Deserialize)] +#[serde(untagged)] +#[derive(Serialize)] +enum PermissionPayload { + Record(Box), + Kind(String), +} + +#[derive(Default, Deserialize, Serialize)] +pub(super) struct PermissionProperties { + #[serde(default)] + permission: Option, + #[serde(default)] + info: Option, + #[serde(default, rename = "permissionID")] + permission_id: Option, + #[serde(default, rename = "requestID")] + request_id: Option, + #[serde(default)] + reply: Option, + #[serde(default)] + response: Option, + #[serde(default)] + status: Option, + #[serde(flatten)] + direct: PermissionFields, +} + +impl PermissionTool { + fn record(&self) -> Option<&PermissionToolRecord> { + match self { + Self::Record(record) => Some(record), + Self::Name(_) => None, + } + } + + fn name(&self) -> Option<&str> { + match self { + Self::Name(name) => Some(name), + Self::Record(_) => None, + } + } +} + +impl PermissionProperties { + pub(super) fn decode(payload: &Value) -> Option { + super::decode(payload.get("properties").unwrap_or(payload)) + } + pub(super) fn reply(&self) -> &str { + self.reply + .as_deref() + .or(self.response.as_deref()) + .or(self.status.as_deref()) + .unwrap_or("") + } + pub(super) fn request(&self) -> PermissionRequest { + let permission_kind = match &self.permission { + Some(PermissionPayload::Kind(kind)) => Some(kind.clone()), + _ => None, + }; + let source = match &self.permission { + Some(PermissionPayload::Record(record)) => record, + _ => self.info.as_ref().unwrap_or(&self.direct), + }; + let tool_record = source.tool.as_ref().and_then(PermissionTool::record); + PermissionRequest { + id: source + .id + .clone() + .or_else(|| self.direct.id.clone()) + .or_else(|| self.permission_id.clone()) + .or_else(|| self.request_id.clone()), + session_id: source + .session_id + .clone() + .or_else(|| self.direct.session_id.clone()) + .or_else(|| tool_record.and_then(|tool| tool.session_id.clone())), + call_id: source + .call_id + .clone() + .or_else(|| tool_record.and_then(|tool| tool.call_id.clone())), + tool: source + .tool + .as_ref() + .and_then(PermissionTool::name) + .map(str::to_owned) + .or_else(|| source.tool_name.clone()) + .or_else(|| tool_record.and_then(|tool| tool.name.clone())) + .or_else(|| tool_record.and_then(|tool| tool.tool.clone())) + // OpenCode's native permission events put the requested tool + // kind in `permission`, separate from `tool.callID`. + .or_else(|| source.permission.clone()) + .or(permission_kind), + input: source + .input + .clone() + .or_else(|| source.args.clone()) + .or_else(|| tool_record.and_then(|tool| tool.input.clone())), + title: source.title.clone(), + permission_type: source.permission_type.clone(), + } + } +} +#[derive(Clone, Default, Serialize, Deserialize)] +pub(super) struct PermissionRequest { + pub(super) id: Option, + pub(super) session_id: Option, + pub(super) call_id: Option, + pub(super) tool: Option, + pub(super) input: Option, + pub(super) title: Option, + pub(super) permission_type: Option, +} diff --git a/bt-daemon/src/translate/opencode_v2.rs b/bt-daemon/src/translate/opencode_v2.rs index 81adb29f..58776cc9 100644 --- a/bt-daemon/src/translate/opencode_v2.rs +++ b/bt-daemon/src/translate/opencode_v2.rs @@ -1,6 +1,8 @@ //! OpenCode 2 native event translation. +mod context; mod event; mod span; +mod tool_content; use self::event::*; use self::span::*; @@ -9,7 +11,7 @@ use super::{ local_username, opencode::{requested_skills, skill_load}, recent::RecentSet, - tool::{push_unique, skill_was_requested, SkillLoad, ToolApproval}, + tool::{push_unique, SkillLoad, ToolApproval}, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, }; use crate::{ids, wire::Envelope}; @@ -526,7 +528,12 @@ impl AgentTranslator for OpenCodeV2Translator { })] } NativeEvent::ToolSuccess(data) => { - let output = normalize_tool_content(data.content.unwrap_or_default()); + let output = data + .content + .unwrap_or_default() + .into_iter() + .map(ToolContent::into_span_part) + .collect(); self.finish_tool( &data.session_id, &data.message_id, @@ -796,11 +803,7 @@ impl OpenCodeV2Translator { metadata.tool_kind = Some("skill"); metadata.skill_name = Some(skill.name.as_deref()); metadata.skill_path = skill.path.as_deref(); - metadata.skill_load_trigger = skill - .name - .as_deref() - .is_some_and(|name| skill_was_requested(&s.turn_skills, name)) - .then_some("explicit"); + metadata.skill_load_trigger = skill.was_requested(&s.turn_skills).then_some("explicit"); } vec![SpanOp::Merge(SpanRow { span_id: tool.span_id, @@ -849,7 +852,7 @@ impl OpenCodeV2Translator { content: reasoning, }]); } - let input = step.context.map(normalize_context).unwrap_or_else(|| { + let input = step.context.map(Context::into_messages).unwrap_or_else(|| { let window = s .native_window .as_ref() @@ -960,7 +963,7 @@ impl OpenCodeV2Translator { ); let output = match native_messages { Some(NativeMessages::Messages(messages)) => { - let messages = normalize_context(Context { + let messages = Context { session_id: sid.to_owned(), system: Vec::new(), messages: messages @@ -970,7 +973,8 @@ impl OpenCodeV2Translator { content: message.content, }) .collect(), - }); + } + .into_messages(); if error.is_none() { s.native_window = Some(NativeWindow { model: model.clone(), @@ -1034,103 +1038,3 @@ impl OpenCodeV2Translator { })] } } -fn normalize_context(context: Context) -> Vec { - let mut messages = Vec::new(); - let system = context.system.join("\n\n"); - if !system.is_empty() { - messages.push(Message::new("system", Content::Text(system))); - } - for message in context.messages { - match message.content { - MessageContent::Text(text) => { - messages.push(Message::new(message.role, Content::Text(text))) - } - MessageContent::Other(content) => { - messages.push(Message::new(message.role, Content::Dynamic(content))) - } - MessageContent::Parts(parts) => { - let mut content = Vec::new(); - let mut calls = Vec::new(); - let mut single_text = None; - for part in parts { - match part { - ContextPart::Known(KnownContextPart::Text { text }) => { - single_text = Some(text.clone()); - content.push(ContentPart::text(text)); - } - ContextPart::Known(KnownContextPart::Media { - media_type, - data, - media, - extra, - }) => { - let source = media.as_ref().and_then(|media| media.source.as_ref()); - let mime = source - .and_then(|source| source.media_type.as_deref()) - .or(media_type.as_deref()); - let bytes = source - .and_then(|source| source.data.as_deref()) - .or(data.as_deref()); - if let Some((mime, bytes)) = mime - .zip(bytes) - .filter(|(mime, _)| mime.starts_with("image/")) - { - content.push(ContentPart::image(format!( - "data:{mime};base64,{bytes}" - ))); - } else { - content.push(ContentPart::Native(KnownContextPart::Media { - media_type, - data, - media, - extra, - })); - } - } - ContextPart::Known(KnownContextPart::ToolCall { id, name, input }) => { - calls.push(ToolCall::new(id, name, &input)) - } - ContextPart::Known(KnownContextPart::ToolResult { id, result }) => { - let value = match serde_json::from_value::>( - result.value.clone(), - ) { - Ok(parts) => Content::Parts(normalize_tool_content(parts)), - Err(_) => Content::Dynamic(result.value), - }; - messages.push(Message::tool(id, value)); - } - ContextPart::Other(value) => content.push(ContentPart::Dynamic(value)), - } - } - if message.role == "tool" && content.is_empty() && calls.is_empty() { - continue; - } - let value = if content.is_empty() { - Content::Text(String::new()) - } else if content.len() == 1 && single_text.is_some() { - Content::Text(single_text.unwrap_or_default()) - } else { - Content::Parts(content) - }; - let mut normalized = Message::new(message.role, value); - normalized.tool_calls = calls; - messages.push(normalized); - } - } - } - messages -} - -fn normalize_tool_content(parts: Vec) -> Vec { - parts - .into_iter() - .map(|part| match part { - ToolContent::Known(KnownToolContent::File { mime, uri, .. }) - if mime.starts_with("image/") => - { - ContentPart::image(uri) - } - other => ContentPart::Tool(other), - }) - .collect() -} diff --git a/bt-daemon/src/translate/opencode_v2/context.rs b/bt-daemon/src/translate/opencode_v2/context.rs new file mode 100644 index 00000000..053ea23f --- /dev/null +++ b/bt-daemon/src/translate/opencode_v2/context.rs @@ -0,0 +1,229 @@ +//! Native OpenCode context and its conversion to Braintrust messages. +use super::event::ToolContent; +use super::span::{Content, ContentPart, Message, ToolCall}; +use crate::json::{Extensions, Field}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Deserialize, Serialize)] +pub(super) struct Context { + #[serde(rename = "sessionID")] + pub session_id: String, + #[serde(default)] + pub system: Vec, + #[serde(default)] + pub messages: Vec, +} +#[derive(Deserialize, Serialize)] +pub(super) struct ContextMessage { + pub role: String, + pub content: MessageContent, +} +#[derive(Serialize)] +#[serde(untagged)] +pub(super) enum MessageContent { + Text(String), + Parts(Vec), + Other(Value), +} +#[derive(Serialize)] +#[serde(untagged)] +pub(super) enum ContextPart { + Known(KnownContextPart), + Other(Value), +} +// Select the known schema before deserializing it. An untagged fallback +// must not turn a malformed known media or tool part into arbitrary JSON. +impl<'de> Deserialize<'de> for MessageContent { + fn deserialize>(deserializer: D) -> Result { + let value = Value::deserialize(deserializer)?; + match value { + Value::String(text) => Ok(Self::Text(text)), + Value::Array(parts) => serde_json::from_value(Value::Array(parts)) + .map(Self::Parts) + .map_err(serde::de::Error::custom), + other => Ok(Self::Other(other)), + } + } +} +impl<'de> Deserialize<'de> for ContextPart { + fn deserialize>(deserializer: D) -> Result { + let value = Value::deserialize(deserializer)?; + if matches!( + value.get("type").and_then(Value::as_str), + Some("text" | "media" | "tool-call" | "tool-result") + ) { + serde_json::from_value(value) + .map(Self::Known) + .map_err(serde::de::Error::custom) + } else { + Ok(Self::Other(value)) + } + } +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(tag = "type")] +pub(super) enum KnownContextPart { + #[serde(rename = "text")] + Text { text: String }, + #[serde(rename = "media")] + Media { + #[serde( + default, + rename = "mediaType", + skip_serializing_if = "Field::is_missing" + )] + media_type: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + data: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + media: Field, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extra: Extensions, + }, + #[serde(rename = "tool-call")] + ToolCall { + id: String, + name: String, + input: Value, + }, + #[serde(rename = "tool-result")] + ToolResult { id: String, result: ToolResult }, +} +#[derive(Clone, Deserialize, Serialize)] +pub(super) struct Media { + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub source: Field, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} +#[derive(Clone, Deserialize, Serialize)] +pub(super) struct MediaSource { + #[serde( + default, + rename = "mediaType", + skip_serializing_if = "Field::is_missing" + )] + pub media_type: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + pub data: Field, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extra: Extensions, +} +#[derive(Clone, Deserialize, Serialize)] +pub(super) struct ToolResult { + pub value: Value, +} + +impl Context { + pub(super) fn into_messages(self) -> Vec { + let mut messages = Vec::new(); + let system = self.system.join("\n\n"); + if !system.is_empty() { + messages.push(Message::new("system", Content::Text(system))); + } + for message in self.messages { + match message.content { + MessageContent::Text(text) => { + messages.push(Message::new(message.role, Content::Text(text))) + } + MessageContent::Other(content) => { + messages.push(Message::new(message.role, Content::Dynamic(content))) + } + MessageContent::Parts(parts) => { + let mut content = Vec::new(); + let mut calls = Vec::new(); + let mut single_text = None; + for part in parts { + match part { + ContextPart::Known(KnownContextPart::Text { text }) => { + single_text = Some(text.clone()); + content.push(ContentPart::text(text)); + } + ContextPart::Known(KnownContextPart::Media { + media_type, + data, + media, + extra, + }) => { + let source = media.as_ref().and_then(|media| media.source.as_ref()); + let mime = source + .and_then(|source| source.media_type.as_deref()) + .or(media_type.as_deref()); + let bytes = source + .and_then(|source| source.data.as_deref()) + .or(data.as_deref()); + if let Some((mime, bytes)) = mime + .zip(bytes) + .filter(|(mime, _)| mime.starts_with("image/")) + { + content.push(ContentPart::image(format!( + "data:{mime};base64,{bytes}" + ))); + } else { + content.push(ContentPart::Native(KnownContextPart::Media { + media_type, + data, + media, + extra, + })); + } + } + ContextPart::Known(KnownContextPart::ToolCall { id, name, input }) => { + calls.push(ToolCall::new(id, name, &input)) + } + ContextPart::Known(KnownContextPart::ToolResult { id, result }) => { + let value = match serde_json::from_value::>( + result.value.clone(), + ) { + Ok(parts) => Content::Parts( + parts + .into_iter() + .map(ToolContent::into_span_part) + .collect(), + ), + Err(_) => Content::Dynamic(result.value), + }; + messages.push(Message::tool(id, value)); + } + ContextPart::Other(value) => content.push(ContentPart::Dynamic(value)), + } + } + if message.role == "tool" && content.is_empty() && calls.is_empty() { + continue; + } + let value = if content.is_empty() { + Content::Text(String::new()) + } else if content.len() == 1 && single_text.is_some() { + Content::Text(single_text.unwrap_or_default()) + } else { + Content::Parts(content) + }; + let mut normalized = Message::new(message.role, value); + normalized.tool_calls = calls; + messages.push(normalized); + } + } + } + messages + } +} + +#[cfg(test)] +mod extension_tests { + use super::*; + use serde_json::json; + #[test] + fn media_extensions_round_trip_but_known_fields_remain_typed() { + let raw = json!([{"type":"media","media":{"source":{"mediaType":"application/pdf","data":"YWJj","future":true},"future":null},"future":[42]}]); + let parsed: MessageContent = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), raw); + assert!(serde_json::from_value::(json!([ + {"type":"media","media":{"source":{"data":42}}} + ])) + .is_err()); + let future = json!([{"type":"future","payload":{"data":42}}]); + let parsed: MessageContent = serde_json::from_value(future.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), future); + } +} diff --git a/bt-daemon/src/translate/opencode_v2/event.rs b/bt-daemon/src/translate/opencode_v2/event.rs index 953d9fab..a41165ab 100644 --- a/bt-daemon/src/translate/opencode_v2/event.rs +++ b/bt-daemon/src/translate/opencode_v2/event.rs @@ -1,7 +1,8 @@ //! Partial OpenCode 2 wire types. Unknown fields are accepted; arbitrary tool //! inputs, outputs and provider-specific content remain JSON values. +pub(super) use super::context::*; +pub(super) use super::tool_content::*; pub(super) use crate::agents::usage::OpenCodeTokens as Tokens; -use crate::json::{Extensions, Field}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -214,25 +215,6 @@ pub(super) struct NativeError { pub(super) struct ErrorResponse { pub body: String, } -#[derive(Clone, Deserialize, Serialize)] -#[serde(untagged)] -pub(super) enum ToolContent { - Known(KnownToolContent), - Other(Value), -} -#[derive(Clone, Deserialize, Serialize)] -#[serde(tag = "type")] -pub(super) enum KnownToolContent { - #[serde(rename = "text")] - Text { text: String }, - #[serde(rename = "file")] - File { - mime: String, - uri: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - name: Option, - }, -} #[derive(Deserialize)] pub(super) struct PermissionAsked { #[serde(rename = "sessionID")] @@ -308,132 +290,3 @@ pub(super) struct Interrupted { pub session_id: String, pub reason: Option, } - -#[derive(Deserialize, Serialize)] -pub(super) struct Context { - #[serde(rename = "sessionID")] - pub session_id: String, - #[serde(default)] - pub system: Vec, - #[serde(default)] - pub messages: Vec, -} -#[derive(Deserialize, Serialize)] -pub(super) struct ContextMessage { - pub role: String, - pub content: MessageContent, -} -#[derive(Serialize)] -#[serde(untagged)] -pub(super) enum MessageContent { - Text(String), - Parts(Vec), - Other(Value), -} -#[derive(Serialize)] -#[serde(untagged)] -pub(super) enum ContextPart { - Known(KnownContextPart), - Other(Value), -} -// Select the known schema before deserializing it. An untagged fallback -// must not turn a malformed known media or tool part into arbitrary JSON. -impl<'de> Deserialize<'de> for MessageContent { - fn deserialize>(deserializer: D) -> Result { - let value = Value::deserialize(deserializer)?; - match value { - Value::String(text) => Ok(Self::Text(text)), - Value::Array(parts) => serde_json::from_value(Value::Array(parts)) - .map(Self::Parts) - .map_err(serde::de::Error::custom), - other => Ok(Self::Other(other)), - } - } -} -impl<'de> Deserialize<'de> for ContextPart { - fn deserialize>(deserializer: D) -> Result { - let value = Value::deserialize(deserializer)?; - if matches!( - value.get("type").and_then(Value::as_str), - Some("text" | "media" | "tool-call" | "tool-result") - ) { - serde_json::from_value(value) - .map(Self::Known) - .map_err(serde::de::Error::custom) - } else { - Ok(Self::Other(value)) - } - } -} -#[derive(Clone, Deserialize, Serialize)] -#[serde(tag = "type")] -pub(super) enum KnownContextPart { - #[serde(rename = "text")] - Text { text: String }, - #[serde(rename = "media")] - Media { - #[serde( - default, - rename = "mediaType", - skip_serializing_if = "Field::is_missing" - )] - media_type: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - data: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - media: Field, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - extra: Extensions, - }, - #[serde(rename = "tool-call")] - ToolCall { - id: String, - name: String, - input: Value, - }, - #[serde(rename = "tool-result")] - ToolResult { id: String, result: ToolResult }, -} -#[derive(Clone, Deserialize, Serialize)] -pub(super) struct Media { - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub source: Field, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, -} -#[derive(Clone, Deserialize, Serialize)] -pub(super) struct MediaSource { - #[serde( - default, - rename = "mediaType", - skip_serializing_if = "Field::is_missing" - )] - pub media_type: Field, - #[serde(default, skip_serializing_if = "Field::is_missing")] - pub data: Field, - #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] - pub extra: Extensions, -} -#[derive(Clone, Deserialize, Serialize)] -pub(super) struct ToolResult { - pub value: Value, -} - -#[cfg(test)] -mod extension_tests { - use super::*; - use serde_json::json; - #[test] - fn media_extensions_round_trip_but_known_fields_remain_typed() { - let raw = json!([{"type":"media","media":{"source":{"mediaType":"application/pdf","data":"YWJj","future":true},"future":null},"future":[42]}]); - let parsed: MessageContent = serde_json::from_value(raw.clone()).unwrap(); - assert_eq!(serde_json::to_value(parsed).unwrap(), raw); - assert!(serde_json::from_value::(json!([ - {"type":"media","media":{"source":{"data":42}}} - ])) - .is_err()); - let future = json!([{"type":"future","payload":{"data":42}}]); - let parsed: MessageContent = serde_json::from_value(future.clone()).unwrap(); - assert_eq!(serde_json::to_value(parsed).unwrap(), future); - } -} diff --git a/bt-daemon/src/translate/opencode_v2/span.rs b/bt-daemon/src/translate/opencode_v2/span.rs index 18a18c90..7c77c7bf 100644 --- a/bt-daemon/src/translate/opencode_v2/span.rs +++ b/bt-daemon/src/translate/opencode_v2/span.rs @@ -198,11 +198,11 @@ pub(super) struct Metrics { } impl Metrics { pub fn from_tokens(t: super::event::Tokens) -> Self { - let prompt = t.input + t.cache.read + t.cache.write; + let prompt = t.prompt_tokens(); Self { prompt_tokens: prompt, completion_tokens: t.output, - tokens: prompt + t.output + t.reasoning, + tokens: t.total_tokens(), prompt_cached_tokens: t.cache.read, prompt_cache_creation_tokens: t.cache.write, reasoning_tokens: t.reasoning, diff --git a/bt-daemon/src/translate/opencode_v2/tool_content.rs b/bt-daemon/src/translate/opencode_v2/tool_content.rs new file mode 100644 index 00000000..9c3b81c3 --- /dev/null +++ b/bt-daemon/src/translate/opencode_v2/tool_content.rs @@ -0,0 +1,34 @@ +//! Native tool result blocks own their span-content conversion. +use super::span::ContentPart; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub(super) enum ToolContent { + Known(KnownToolContent), + Other(Value), +} +#[derive(Clone, Deserialize, Serialize)] +#[serde(tag = "type")] +pub(super) enum KnownToolContent { + #[serde(rename = "text")] + Text { text: String }, + #[serde(rename = "file")] + File { + mime: String, + uri: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + name: Option, + }, +} +impl ToolContent { + pub(super) fn into_span_part(self) -> ContentPart { + match self { + Self::Known(KnownToolContent::File { mime, uri, .. }) if mime.starts_with("image/") => { + ContentPart::image(uri) + } + other => ContentPart::Tool(other), + } + } +} diff --git a/bt-daemon/src/translate/pi.rs b/bt-daemon/src/translate/pi.rs index 08e38bb6..1d04dd2f 100644 --- a/bt-daemon/src/translate/pi.rs +++ b/bt-daemon/src/translate/pi.rs @@ -1,16 +1,22 @@ //! Pi coding-agent translator. Pi forwards native extension callbacks and this //! state machine owns all span construction and recovery. +mod assistant_message; +mod compaction; +mod event; +use assistant_message::AssistantMessage; +use compaction::*; +use event::*; + use super::git::GitMetadataCache; use super::tool::{ - error_text, explicit_skill_metadata, insert_skill_metadata, skill_file_load, - with_tool_approval, without_nulls, SkillLoad, ToolApproval, + error_text, explicit_skill_metadata, skill_file_load, with_tool_approval, without_nulls, + SkillLoad, ToolApproval, }; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, }; use crate::agents::request::RequestConfig; -use crate::agents::usage::PiUsage as Usage; use crate::ids; use crate::wire::Envelope; use serde::de::DeserializeOwned; @@ -48,259 +54,6 @@ impl TranslatorFactory for crate::agents::Pi { } } -// These are deliberately partial native event types. Serde ignores fields we -// do not model, while `Value` remains at the user-controlled JSON boundaries -// that we forward without interpreting (messages, tool arguments, results). -// Keeping this vocabulary local lets the raw journal remain forward-compatible -// and makes each translator reducer explicit about the fields it consumes. -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct BeforeAgentStart { - #[serde(default)] - prompt: Option, - #[serde(default)] - message: Option, - #[serde(default)] - images: Option>, -} - -/// Pi's before_agent_start images contain base64 data, separate from the prompt. -#[derive(Deserialize, Serialize)] -#[serde(rename_all = "camelCase")] -struct PromptImage { - data: String, - mime_type: String, -} - -/// `ctx.model`: the selected model, which may be a Pi 1.0 virtual model that -/// routes each request to a physical model. -#[derive(Deserialize, Serialize)] -struct SelectedModel { - provider: String, - id: String, -} - -#[derive(Deserialize, Serialize)] -struct ContextEvent { - #[serde(default)] - messages: Vec, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct MessageUpdate { - #[serde(default)] - assistant_message_event: Option, - #[serde(default, rename = "type")] - kind: Option, -} - -#[derive(Deserialize, Serialize)] -struct MessageDelta { - #[serde(default, rename = "type")] - kind: Option, -} - -#[derive(Deserialize, Serialize)] -struct ThinkingLevel { - #[serde(default)] - level: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct AssistantMessage { - #[serde(default)] - role: Option, - #[serde(default)] - provider: Option, - #[serde(default)] - api: Option, - #[serde(default)] - response_model: Option, - #[serde(default)] - routed_model: Option, - #[serde(default)] - resolved_model: Option, - #[serde(default)] - actual_model: Option, - #[serde(default)] - concrete_model: Option, - #[serde(default)] - output_model: Option, - #[serde(default)] - model: Option, - #[serde(default)] - usage: Usage, - #[serde(default)] - content: Vec, - #[serde(default)] - error_message: Option, - #[serde(default)] - stop_reason: Option, - #[serde(default)] - response_id: Option, - // Pi 1.0 records the level dispatched for this response, which a virtual - // model's router may choose independently of the selected level. - #[serde(default)] - thinking_level: Option, - #[serde(default)] - provider_thinking_level: Option, -} - -#[derive(Deserialize)] -#[serde(tag = "type")] -#[derive(Serialize)] -enum AssistantContent { - #[serde(rename = "text")] - Text { - #[serde(default)] - text: Option, - }, - #[serde(rename = "thinking")] - Thinking { - #[serde(default)] - thinking: Option, - }, - #[serde(rename = "toolCall")] - ToolCall { - #[serde(default)] - id: Option, - #[serde(default)] - name: Option, - #[serde(default)] - arguments: Option, - }, - #[serde(other)] - Other, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct ToolExecutionStart { - tool_call_id: String, - #[serde(default)] - tool_name: Option, - #[serde(default)] - args: Value, - // Pi 1.0 sets this on calls another tool made through - // `ctx.executeTool()`, such as codemode's `tools.()`. - #[serde(default)] - parent_tool_call_id: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct ToolExecutionEnd { - #[serde(default)] - tool_call_id: Option, - #[serde(default)] - tool_name: Option, - #[serde(default)] - result: Option, - #[serde(default)] - is_error: bool, - #[serde(default)] - parent_tool_call_id: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct AgentEnd { - #[serde(default)] - will_retry: bool, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct SessionCompact { - #[serde(default)] - compaction_entry: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct CompactionEntry { - #[serde(default)] - summary: Option, - #[serde(default)] - tokens_before: Option, - #[serde(default)] - timestamp: Option, -} - -#[derive(Default, Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct Preparation { - #[serde(default)] - tokens_before: Option, - #[serde(default)] - first_kept_entry_id: Option, - #[serde(default)] - is_split_turn: Option, - #[serde(default)] - messages_to_summarize: Option>, - #[serde(default)] - turn_prefix_messages: Option>, - #[serde(default)] - target_id: Option, - #[serde(default)] - old_leaf_id: Option, - #[serde(default)] - common_ancestor_id: Option, - #[serde(default)] - user_wants_summary: Option, - #[serde(default)] - custom_instructions: Option, - #[serde(default)] - replace_instructions: Option, - #[serde(default)] - label: Option, - #[serde(default)] - entries_to_summarize: Option>, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct BeforeCompact { - #[serde(default)] - reason: Option, - #[serde(default)] - will_retry: Option, - #[serde(default)] - custom_instructions: Option, - #[serde(default)] - preparation: Option, - #[serde(default)] - branch_entries: Option>, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct BeforeTree { - #[serde(default)] - preparation: Option, -} - -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct SessionTree { - #[serde(default)] - summary_entry: Option, -} - fn decode(value: &Value) -> Option { serde_json::from_value(value.clone()).ok() } @@ -408,35 +161,30 @@ impl AgentTranslator for PiTranslator { ops.extend(self.close_turn(envelope.ts_ms, None)); } "session_before_compact" => { - if let Some(event) = decode(event) { + if let Some(event) = decode::(event) { self.compaction = Some(( ids::span_id(&self.session_id, &format!("compaction:{}", envelope.ts_ms)), envelope.ts_ms, - compaction_input(&event), + event.input(), )); } } "session_compact" => { if let Some(typed) = decode::(event) { - self.active_compaction_message = compaction_message(&typed); + self.active_compaction_message = typed.summary_message(); } ops.extend(self.finish_special("Compaction", true, event, envelope.ts_ms)) } "session_before_tree" => { if let Some(event) = decode::(event) { - if event - .preparation - .as_ref() - .and_then(|preparation| preparation.user_wants_summary) - == Some(true) - { + if event.wants_summary() { self.branch_summary = Some(( ids::span_id( &self.session_id, &format!("branch-summary:{}", envelope.ts_ms), ), envelope.ts_ms, - branch_summary_input(&event), + event.input(), )); } } @@ -764,12 +512,12 @@ impl PiTranslator { } else { self.pending_llms.remove(0) }; - let model = response_model(&message); + let model = message.response_model(); let usage = &message.usage; let prompt = usage.input + usage.cache_read + usage.cache_write; let completion = usage.output; let total = usage.total_tokens.unwrap_or(prompt + completion); - let output = normalize_assistant(&message); + let output = message.normalized(); let failed = matches!(message.stop_reason.as_deref(), Some("error" | "aborted")); let error = failed.then(|| message.error_message.clone()).flatten(); if failed { @@ -786,10 +534,7 @@ impl PiTranslator { // Only a virtual selection differs from the physical model that answered. let selected_model = pending .selected_model - .filter(|selected| { - message.provider.as_deref() != Some(&selected.provider) - || message.model.as_deref() != Some(&selected.id) - }) + .filter(|selected| !message.matches_model(&selected.provider, &selected.id)) .map(|selected| format!("{}/{}", selected.provider, selected.id)); let mut metadata = json!(pending.request_config); if let (Value::Object(metadata), Value::Object(fields)) = ( @@ -915,7 +660,7 @@ impl PiTranslator { .unwrap_or_else(|| tracked.name.clone()); let mut skill_metadata = serde_json::Map::new(); if let Some(skill) = &skill { - insert_skill_metadata(&mut skill_metadata, skill, requested_skills); + skill.insert_metadata(&mut skill_metadata, requested_skills); } let row = SpanRow { span_id: self.tool_span_id(&call), @@ -1062,67 +807,6 @@ fn legacy_continuation(payload: &Value) -> Option { }) } -fn compaction_message(event: &SessionCompact) -> Option { - let entry = event.compaction_entry.as_ref()?; - let summary = entry.summary.clone()?; - Some(json!({ - "role": "compactionSummary", - "summary": summary, - "tokensBefore": entry.tokens_before, - "timestamp": entry.timestamp, - })) -} - -fn compaction_input(event: &BeforeCompact) -> Value { - let preparation = event.preparation.as_ref(); - json!({ - "reason": event.reason.clone(), - "willRetry": event.will_retry.clone(), - "customInstructions": event.custom_instructions.clone(), - "tokensBefore": preparation.and_then(|value| value.tokens_before), - "firstKeptEntryId": preparation.and_then(|value| value.first_kept_entry_id.clone()), - "isSplitTurn": preparation.and_then(|value| value.is_split_turn), - "messagesToSummarizeCount": preparation - .and_then(|value| value.messages_to_summarize.as_ref()) - .map(Vec::len), - "turnPrefixMessagesCount": preparation - .and_then(|value| value.turn_prefix_messages.as_ref()) - .map(Vec::len), - "branchEntryCount": event.branch_entries.as_ref().map(Vec::len), - }) -} - -fn branch_summary_input(event: &BeforeTree) -> Value { - let preparation = event.preparation.as_ref(); - json!({ - "targetId": preparation.and_then(|value| value.target_id.clone()), - "oldLeafId": preparation.and_then(|value| value.old_leaf_id.clone()), - "commonAncestorId": preparation.and_then(|value| value.common_ancestor_id.clone()), - "userWantsSummary": preparation.and_then(|value| value.user_wants_summary), - "customInstructions": preparation.and_then(|value| value.custom_instructions.clone()), - "replaceInstructions": preparation.and_then(|value| value.replace_instructions), - "label": preparation.and_then(|value| value.label.clone()), - "entriesToSummarizeCount": preparation - .and_then(|value| value.entries_to_summarize.as_ref()) - .map(Vec::len), - }) -} - -fn response_model(message: &AssistantMessage) -> Option { - [ - &message.response_model, - &message.routed_model, - &message.resolved_model, - &message.actual_model, - &message.concrete_model, - &message.output_model, - &message.model, - ] - .into_iter() - .flatten() - .next() - .cloned() -} /// The request configuration the instrumentation spec allows on LLM spans, /// read individually from the provider-native payload: sampling settings plus /// the available tool definitions and controls. Pi's API adapters name these @@ -1332,45 +1016,6 @@ fn tool_metadata(name: &str, call: &str, parent_call: Option<&str>, extra: Value } with_tool_approval(without_nulls(metadata), Some(ToolApproval::Approved)) } -fn normalize_assistant(message: &AssistantMessage) -> Value { - let mut text = String::new(); - let mut reasoning = String::new(); - let mut calls = Vec::new(); - for part in &message.content { - match part { - AssistantContent::Text { - text: Some(content), - } => text.push_str(content), - AssistantContent::Thinking { - thinking: Some(content), - } => reasoning.push_str(content), - AssistantContent::ToolCall { - id, - name, - arguments, - } => calls.push(json!({ - "id": id, - "type": "function", - "function": { - "name": name, - "arguments": serde_json::to_string( - arguments.as_ref().unwrap_or(&Value::Null), - ) - .unwrap_or_default(), - }, - })), - _ => {} - } - } - let mut out = json!({"role":"assistant","content":text}); - if !reasoning.is_empty() { - out["reasoning"] = json!([{"id":"reasoning","content":reasoning}]) - } - if !calls.is_empty() { - out["tool_calls"] = Value::Array(calls) - } - out -} fn skill_from_read(tool: &str, args: &Value) -> Option { if tool != "read" { return None; diff --git a/bt-daemon/src/translate/pi/assistant_message.rs b/bt-daemon/src/translate/pi/assistant_message.rs new file mode 100644 index 00000000..4b57516c --- /dev/null +++ b/bt-daemon/src/translate/pi/assistant_message.rs @@ -0,0 +1,136 @@ +//! Pi assistant messages own physical-model selection and span-message projection. +use crate::agents::usage::PiUsage as Usage; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct AssistantMessage { + #[serde(default)] + pub(super) role: Option, + #[serde(default)] + pub(super) provider: Option, + #[serde(default)] + pub(super) api: Option, + #[serde(default)] + response_model: Option, + #[serde(default)] + routed_model: Option, + #[serde(default)] + resolved_model: Option, + #[serde(default)] + actual_model: Option, + #[serde(default)] + concrete_model: Option, + #[serde(default)] + output_model: Option, + #[serde(default)] + model: Option, + #[serde(default)] + pub(super) usage: Usage, + #[serde(default)] + content: Vec, + #[serde(default)] + pub(super) error_message: Option, + #[serde(default)] + pub(super) stop_reason: Option, + #[serde(default)] + pub(super) response_id: Option, + // Pi 1.0 records the level dispatched for this response, which a virtual + // model's router may choose independently of the selected level. + #[serde(default)] + pub(super) thinking_level: Option, + #[serde(default)] + pub(super) provider_thinking_level: Option, +} + +#[derive(Deserialize)] +#[serde(tag = "type")] +#[derive(Serialize)] +enum AssistantContent { + #[serde(rename = "text")] + Text { + #[serde(default)] + text: Option, + }, + #[serde(rename = "thinking")] + Thinking { + #[serde(default)] + thinking: Option, + }, + #[serde(rename = "toolCall")] + ToolCall { + #[serde(default)] + id: Option, + #[serde(default)] + name: Option, + #[serde(default)] + arguments: Option, + }, + #[serde(other)] + Other, +} + +impl AssistantMessage { + /// Compare the native provider/model identity, independently of any routed + /// response-model aliases used for display metadata. + pub(super) fn matches_model(&self, provider: &str, id: &str) -> bool { + self.provider.as_deref() == Some(provider) && self.model.as_deref() == Some(id) + } + + pub(super) fn response_model(&self) -> Option { + [ + &self.response_model, + &self.routed_model, + &self.resolved_model, + &self.actual_model, + &self.concrete_model, + &self.output_model, + &self.model, + ] + .into_iter() + .flatten() + .next() + .cloned() + } + pub(super) fn normalized(&self) -> Value { + let mut text = String::new(); + let mut reasoning = String::new(); + let mut calls = Vec::new(); + for part in &self.content { + match part { + AssistantContent::Text { + text: Some(content), + } => text.push_str(content), + AssistantContent::Thinking { + thinking: Some(content), + } => reasoning.push_str(content), + AssistantContent::ToolCall { + id, + name, + arguments, + } => calls.push(json!({ + "id": id, + "type": "function", + "function": { + "name": name, + "arguments": serde_json::to_string( + arguments.as_ref().unwrap_or(&Value::Null), + ) + .unwrap_or_default(), + }, + })), + _ => {} + } + } + let mut out = json!({"role":"assistant","content":text}); + if !reasoning.is_empty() { + out["reasoning"] = json!([{"id":"reasoning","content":reasoning}]) + } + if !calls.is_empty() { + out["tool_calls"] = Value::Array(calls) + } + out + } +} diff --git a/bt-daemon/src/translate/pi/compaction.rs b/bt-daemon/src/translate/pi/compaction.rs new file mode 100644 index 00000000..51b88210 --- /dev/null +++ b/bt-daemon/src/translate/pi/compaction.rs @@ -0,0 +1,144 @@ +//! Native Pi compaction and branch-summary payloads and their span inputs. +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct SessionCompact { + #[serde(default)] + compaction_entry: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +struct CompactionEntry { + #[serde(default)] + summary: Option, + #[serde(default)] + tokens_before: Option, + #[serde(default)] + timestamp: Option, +} + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +struct Preparation { + #[serde(default)] + tokens_before: Option, + #[serde(default)] + first_kept_entry_id: Option, + #[serde(default)] + is_split_turn: Option, + #[serde(default)] + messages_to_summarize: Option>, + #[serde(default)] + turn_prefix_messages: Option>, + #[serde(default)] + target_id: Option, + #[serde(default)] + old_leaf_id: Option, + #[serde(default)] + common_ancestor_id: Option, + #[serde(default)] + user_wants_summary: Option, + #[serde(default)] + custom_instructions: Option, + #[serde(default)] + replace_instructions: Option, + #[serde(default)] + label: Option, + #[serde(default)] + entries_to_summarize: Option>, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct BeforeCompact { + #[serde(default)] + reason: Option, + #[serde(default)] + will_retry: Option, + #[serde(default)] + custom_instructions: Option, + #[serde(default)] + preparation: Option, + #[serde(default)] + branch_entries: Option>, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct BeforeTree { + #[serde(default)] + preparation: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct SessionTree { + #[serde(default)] + pub(super) summary_entry: Option, +} + +impl SessionCompact { + pub(super) fn summary_message(&self) -> Option { + let entry = self.compaction_entry.as_ref()?; + let summary = entry.summary.clone()?; + Some(json!({ + "role": "compactionSummary", + "summary": summary, + "tokensBefore": entry.tokens_before, + "timestamp": entry.timestamp, + })) + } +} +impl BeforeCompact { + pub(super) fn input(&self) -> Value { + let preparation = self.preparation.as_ref(); + json!({ + "reason": self.reason.clone(), + "willRetry": self.will_retry.clone(), + "customInstructions": self.custom_instructions.clone(), + "tokensBefore": preparation.and_then(|value| value.tokens_before), + "firstKeptEntryId": preparation.and_then(|value| value.first_kept_entry_id.clone()), + "isSplitTurn": preparation.and_then(|value| value.is_split_turn), + "messagesToSummarizeCount": preparation + .and_then(|value| value.messages_to_summarize.as_ref()) + .map(Vec::len), + "turnPrefixMessagesCount": preparation + .and_then(|value| value.turn_prefix_messages.as_ref()) + .map(Vec::len), + "branchEntryCount": self.branch_entries.as_ref().map(Vec::len), + }) + } +} +impl BeforeTree { + pub(super) fn wants_summary(&self) -> bool { + self.preparation + .as_ref() + .and_then(|preparation| preparation.user_wants_summary) + == Some(true) + } + + pub(super) fn input(&self) -> Value { + let preparation = self.preparation.as_ref(); + json!({ + "targetId": preparation.and_then(|value| value.target_id.clone()), + "oldLeafId": preparation.and_then(|value| value.old_leaf_id.clone()), + "commonAncestorId": preparation.and_then(|value| value.common_ancestor_id.clone()), + "userWantsSummary": preparation.and_then(|value| value.user_wants_summary), + "customInstructions": preparation.and_then(|value| value.custom_instructions.clone()), + "replaceInstructions": preparation.and_then(|value| value.replace_instructions), + "label": preparation.and_then(|value| value.label.clone()), + "entriesToSummarizeCount": preparation + .and_then(|value| value.entries_to_summarize.as_ref()) + .map(Vec::len), + }) + } +} diff --git a/bt-daemon/src/translate/pi/event.rs b/bt-daemon/src/translate/pi/event.rs new file mode 100644 index 00000000..302450ba --- /dev/null +++ b/bt-daemon/src/translate/pi/event.rs @@ -0,0 +1,103 @@ +//! Partial Pi callback payloads. Correlation remains in the parent reducer. +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +// These are deliberately partial native event types. Serde ignores fields we +// do not model, while `Value` remains at the user-controlled JSON boundaries +// that we forward without interpreting (messages, tool arguments, results). +// Keeping this vocabulary local lets the raw journal remain forward-compatible +// and makes each translator reducer explicit about the fields it consumes. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct BeforeAgentStart { + #[serde(default)] + pub(super) prompt: Option, + #[serde(default)] + pub(super) message: Option, + #[serde(default)] + pub(super) images: Option>, +} + +/// Pi's before_agent_start images contain base64 data, separate from the prompt. +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct PromptImage { + pub(super) data: String, + pub(super) mime_type: String, +} + +/// `ctx.model`: the selected model, which may be a Pi 1.0 virtual model that +/// routes each request to a physical model. +#[derive(Deserialize, Serialize)] +pub(super) struct SelectedModel { + pub(super) provider: String, + pub(super) id: String, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct ContextEvent { + #[serde(default)] + pub(super) messages: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct MessageUpdate { + #[serde(default)] + pub(super) assistant_message_event: Option, + #[serde(default, rename = "type")] + pub(super) kind: Option, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct MessageDelta { + #[serde(default, rename = "type")] + pub(super) kind: Option, +} + +#[derive(Deserialize, Serialize)] +pub(super) struct ThinkingLevel { + #[serde(default)] + pub(super) level: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct ToolExecutionStart { + pub(super) tool_call_id: String, + #[serde(default)] + pub(super) tool_name: Option, + #[serde(default)] + pub(super) args: Value, + // Pi 1.0 sets this on calls another tool made through + // `ctx.executeTool()`, such as codemode's `tools.()`. + #[serde(default)] + pub(super) parent_tool_call_id: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct ToolExecutionEnd { + #[serde(default)] + pub(super) tool_call_id: Option, + #[serde(default)] + pub(super) tool_name: Option, + #[serde(default)] + pub(super) result: Option, + #[serde(default)] + pub(super) is_error: bool, + #[serde(default)] + pub(super) parent_tool_call_id: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +#[derive(Serialize)] +pub(super) struct AgentEnd { + #[serde(default)] + pub(super) will_retry: bool, +} diff --git a/bt-daemon/src/translate/tool.rs b/bt-daemon/src/translate/tool.rs index 6c5e5a4b..5cc0f653 100644 --- a/bt-daemon/src/translate/tool.rs +++ b/bt-daemon/src/translate/tool.rs @@ -4,6 +4,9 @@ //! This module only encodes the common Braintrust representation once that //! source-specific interpretation has been made. +mod skill_load; +pub use skill_load::SkillLoad; + use regex::Regex; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; @@ -61,32 +64,6 @@ pub fn compile_skill_regex(pattern: &str) -> Option { } } -/// A tool call that loaded a skill, as far as the source reveals it. -#[derive(Default, Serialize, Deserialize)] -pub struct SkillLoad { - pub name: Option, - pub path: Option, -} - -/// Records a skill load on a tool span. Only a load the user asked for is -/// explicit; the model choosing a skill on its own carries no trigger. -pub fn insert_skill_metadata( - metadata: &mut Map, - load: &SkillLoad, - requested: &[String], -) { - metadata.insert("tool_kind".into(), json!("skill")); - if let Some(name) = &load.name { - metadata.insert("skill_name".into(), json!(name)); - if skill_was_requested(requested, name) { - metadata.insert("skill_load_trigger".into(), json!("explicit")); - } - } - if let Some(path) = &load.path { - metadata.insert("skill_path".into(), json!(path)); - } -} - /// Appends `name` unless it is already present, keeping first-seen order. pub fn push_unique(names: &mut Vec, name: String) { if !names.contains(&name) { diff --git a/bt-daemon/src/translate/tool/skill_load.rs b/bt-daemon/src/translate/tool/skill_load.rs new file mode 100644 index 00000000..12690077 --- /dev/null +++ b/bt-daemon/src/translate/tool/skill_load.rs @@ -0,0 +1,39 @@ +//! The identity and common span representation of a skill load. +use super::skill_was_requested; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Map, Value}; + +/// A tool call that loaded a skill, as far as the source reveals it. +#[derive(Default, Serialize, Deserialize)] +pub struct SkillLoad { + pub name: Option, + pub path: Option, +} + +impl SkillLoad { + pub fn display_name(&self) -> String { + self.name + .as_ref() + .map_or_else(|| "skill".into(), |name| format!("skill: {name}")) + } + + pub fn was_requested(&self, requested: &[String]) -> bool { + self.name + .as_deref() + .is_some_and(|name| skill_was_requested(requested, name)) + } + + /// Only a load the user asked for carries an explicit trigger. + pub fn insert_metadata(&self, metadata: &mut Map, requested: &[String]) { + metadata.insert("tool_kind".into(), json!("skill")); + if let Some(name) = &self.name { + metadata.insert("skill_name".into(), json!(name)); + if self.was_requested(requested) { + metadata.insert("skill_load_trigger".into(), json!("explicit")); + } + } + if let Some(path) = &self.path { + metadata.insert("skill_path".into(), json!(path)); + } + } +} diff --git a/bt-daemon/src/wire/auth_selection.rs b/bt-daemon/src/wire/auth_selection.rs new file mode 100644 index 00000000..e2df06c5 --- /dev/null +++ b/bt-daemon/src/wire/auth_selection.rs @@ -0,0 +1,48 @@ +use super::AuthSource; +use serde::{Deserialize, Serialize}; + +/// Non-secret auth selection. An optional organization constrains credentials +/// that can address more than one organization. +#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct AuthSelection { + #[serde(default, skip_serializing_if = "AuthSource::is_auto")] + pub source: AuthSource, + /// Immutable profile identifier. Preferred over the legacy display name. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub org_name: Option, +} + +impl AuthSelection { + /// Interpret old `profile: "environment"` routes as environment auth + /// without preserving the synthetic value as a saved profile name. + pub fn effective_source(&self) -> AuthSource { + match self.source { + AuthSource::Auto if self.profile.as_deref() == Some("environment") => { + AuthSource::Environment + } + AuthSource::Auto if self.profile_id.is_some() || self.profile.is_some() => { + AuthSource::SavedProfile + } + source => source, + } + } + + pub fn canonicalized(mut self) -> anyhow::Result { + self.source = self.effective_source(); + match self.source { + AuthSource::SavedProfile if self.profile_id.is_none() && self.profile.is_none() => { + anyhow::bail!("saved-profile auth requires a profile ID or name") + } + AuthSource::Environment => { + self.profile_id = None; + self.profile = None; + } + AuthSource::Auto | AuthSource::SavedProfile => {} + } + Ok(self) + } +} diff --git a/bt-daemon/src/wire/auth_source.rs b/bt-daemon/src/wire/auth_source.rs new file mode 100644 index 00000000..d4abf0a0 --- /dev/null +++ b/bt-daemon/src/wire/auth_source.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +/// The non-secret credential source selected for a session route. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AuthSource { + /// Resolve using the host's ordinary precedence rules. Retained for old + /// profile-less routes; newly resolved command routes are canonicalized. + #[default] + Auto, + /// Resolve a named credential from the host's saved profile store. + SavedProfile, + /// Resolve BRAINTRUST_API_KEY from the process environment at delivery + /// time. The key itself is never serialized into the route. + Environment, +} + +impl AuthSource { + pub(super) fn is_auto(&self) -> bool { + *self == Self::Auto + } +} diff --git a/bt-daemon/src/wire/backend_auth.rs b/bt-daemon/src/wire/backend_auth.rs new file mode 100644 index 00000000..8738c298 --- /dev/null +++ b/bt-daemon/src/wire/backend_auth.rs @@ -0,0 +1,19 @@ +use serde::{Deserialize, Serialize}; + +/// Backend credentials. `token` is an API key or an OAuth access token; the +/// daemon does not care which. Never serialized or persisted. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct BackendAuth { + pub token: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub api_url: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub app_url: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub org_name: Option, + /// Optional org id. `bt` may or may not know it; the SDK's project + /// registration works from `org_name` alone, so this is best-effort and + /// only feeds the SDK's per-session credential/batch key. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub org_id: Option, +} diff --git a/bt-daemon/src/wire/capture_context.rs b/bt-daemon/src/wire/capture_context.rs new file mode 100644 index 00000000..317e555e --- /dev/null +++ b/bt-daemon/src/wire/capture_context.rs @@ -0,0 +1,16 @@ +use super::ProcessIdentity; +use serde::{Deserialize, Serialize}; + +/// Process evidence captured at the hook or in-process adapter boundary. +/// +/// `process_chain` is ordered from the process that connected to the daemon +/// toward the operating-system root. It intentionally excludes full command +/// lines, environment variables, and working directories. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CaptureContext { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub process_chain: Vec, + /// The process walk stopped before reaching the operating-system root. + #[serde(default)] + pub truncated: bool, +} diff --git a/bt-daemon/src/wire/envelope.rs b/bt-daemon/src/wire/envelope.rs index 89193d28..6bdfc2cb 100644 --- a/bt-daemon/src/wire/envelope.rs +++ b/bt-daemon/src/wire/envelope.rs @@ -1,36 +1,7 @@ -//! The `event.log` envelope and its session config, plus auth redaction for -//! the journal. +//! Native capture envelope and its journal-safe projection. -use braintrust_sdk_rust::SpanComponents; +use super::{CaptureContext, RedactedEnvelope, SessionConfig, SessionRoute}; use serde::{Deserialize, Serialize}; -use std::{collections::BTreeSet, path::PathBuf}; - -/// One operating-system process observed while capturing an event. -/// -/// A PID alone is not a stable identity because operating systems reuse it. -/// `start_time_secs`, when available, distinguishes different occupants of the -/// same PID. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct ProcessIdentity { - pub pid: u32, - /// Epoch seconds reported by the operating system, or zero if unavailable. - #[serde(default)] - pub start_time_secs: u64, -} - -/// Process evidence captured at the hook or in-process adapter boundary. -/// -/// `process_chain` is ordered from the process that connected to the daemon -/// toward the operating-system root. It intentionally excludes full command -/// lines, environment variables, and working directories. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct CaptureContext { - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub process_chain: Vec, - /// The process walk stopped before reaching the operating-system root. - #[serde(default)] - pub truncated: bool, -} /// One captured hook event, forwarded from a shim to the daemon. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -71,265 +42,6 @@ pub struct Envelope { pub config: Option, } -/// The non-secret credential source selected for a session route. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum AuthSource { - /// Resolve using the host's ordinary precedence rules. Retained for old - /// profile-less routes; newly resolved command routes are canonicalized. - #[default] - Auto, - /// Resolve a named credential from the host's saved profile store. - SavedProfile, - /// Resolve BRAINTRUST_API_KEY from the process environment at delivery - /// time. The key itself is never serialized into the route. - Environment, -} - -/// Non-secret auth selection. An optional organization constrains credentials -/// that can address more than one organization. -#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct AuthSelection { - #[serde(default, skip_serializing_if = "AuthSource::is_auto")] - pub source: AuthSource, - /// Immutable profile identifier. Preferred over the legacy display name. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub profile_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub profile: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub org_name: Option, -} - -impl AuthSource { - fn is_auto(&self) -> bool { - *self == Self::Auto - } -} - -impl AuthSelection { - /// Interpret old `profile: "environment"` routes as environment auth - /// without preserving the synthetic value as a saved profile name. - pub fn effective_source(&self) -> AuthSource { - match self.source { - AuthSource::Auto if self.profile.as_deref() == Some("environment") => { - AuthSource::Environment - } - AuthSource::Auto if self.profile_id.is_some() || self.profile.is_some() => { - AuthSource::SavedProfile - } - source => source, - } - } - - pub fn canonicalized(mut self) -> anyhow::Result { - self.source = self.effective_source(); - match self.source { - AuthSource::SavedProfile if self.profile_id.is_none() && self.profile.is_none() => { - anyhow::bail!("saved-profile auth requires a profile ID or name") - } - AuthSource::Environment => { - self.profile_id = None; - self.profile = None; - } - AuthSource::Auto | AuthSource::SavedProfile => {} - } - Ok(self) - } -} - -/// Immutable, journal-safe routing and trace settings for one agent session. -/// Credentials are deliberately absent and are resolved inside the daemon. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct SessionRoute { - #[serde(default)] - pub auth: AuthSelection, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub destination: Option, - #[serde(default)] - pub flush_mode: FlushMode, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub additional_metadata: Option, - /// Tags applied to each root span for this session. - #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] - pub tags: BTreeSet, - /// Ordered JavaScript span transforms. Paths are resolved by explicit - /// setup, run, and import commands before entering a session route. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub span_plugins: Vec, -} - -impl SessionRoute { - pub fn with_auth(&self, auth: BackendAuth) -> SessionConfig { - SessionConfig { - auth, - destination: self.destination.clone(), - flush_mode: self.flush_mode, - additional_metadata: self.additional_metadata.clone(), - tags: self.tags.clone(), - span_plugins: self.span_plugins.clone(), - } - } - - pub fn same_route(&self, other: &Self) -> bool { - let mut left = self.clone(); - let mut right = other.clone(); - if left - .auth - .profile_id - .as_ref() - .zip(right.auth.profile_id.as_ref()) - .is_some_and(|(left, right)| left != right) - { - return false; - } - // A stable-ID route is the canonical successor to an old named route. - // Journals can legitimately contain both forms for the same session, - // so replay compares their unchanged routing intent, not the newly - // learned identifier. - left.auth.profile_id = None; - right.auth.profile_id = None; - left.auth.source = left.auth.effective_source(); - right.auth.source = right.auth.effective_source(); - serde_json::to_value(left).ok() == serde_json::to_value(right).ok() - } - - /// Delivery settings may change without moving held work to another destination. - pub(crate) fn same_destination(&self, other: &Self) -> bool { - let identity = |route: &Self| Self { - auth: route.auth.clone(), - destination: route.destination.clone(), - ..Self::default() - }; - identity(self).same_route(&identity(other)) - } - - /// Raw journal entries can be replayed through a newer plugin chain as - /// long as their Braintrust delivery route is otherwise unchanged. - pub fn same_replay_route(&self, other: &Self) -> bool { - let mut left = self.clone(); - let mut right = other.clone(); - left.span_plugins.clear(); - right.span_plugins.clear(); - left.same_route(&right) - } -} - -/// Trace settings and backend credentials resolved by the shim. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SessionConfig { - pub auth: BackendAuth, - /// Typed trace destination. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub destination: Option, - #[serde(default)] - pub flush_mode: FlushMode, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub additional_metadata: Option, - #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] - pub tags: BTreeSet, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub span_plugins: Vec, -} - -/// Where a session's root span should be logged. -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(tag = "type", rename_all = "snake_case")] -pub enum TraceDestination { - /// Project logs selected by stable id, display name, or both. - ProjectLogs { - #[serde(default, skip_serializing_if = "Option::is_none")] - project_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - project_name: Option, - }, - /// An existing experiment. - Experiment { experiment_id: String }, - /// A child of an exported Braintrust span. - ParentSpan { components: SpanComponents }, -} - -impl SessionConfig { - /// External parent/root ids used to shape translator rows. The sink keeps - /// the full destination components for object routing and propagation. - pub fn attached_span_ids(&self) -> (Option, Option) { - if let Some(TraceDestination::ParentSpan { components }) = &self.destination { - return (components.span_id.clone(), components.root_span_id.clone()); - } - (None, None) - } - - pub fn project_name(&self) -> Option<&str> { - match &self.destination { - Some(TraceDestination::ProjectLogs { project_name, .. }) => project_name.as_deref(), - _ => None, - } - } -} - -impl std::str::FromStr for TraceDestination { - type Err = String; - - fn from_str(value: &str) -> Result { - let (kind, id) = value.split_once(':').ok_or_else(|| { - "destination must be project_logs: or experiment:" - .to_string() - })?; - if id.is_empty() { - return Err("destination id must not be empty".to_string()); - } - match kind { - "project_logs" => Ok(Self::ProjectLogs { - project_id: Some(id.to_string()), - project_name: None, - }), - "experiment" => Ok(Self::Experiment { - experiment_id: id.to_string(), - }), - _ => Err(format!( - "unsupported destination {kind:?}; expected project_logs or experiment" - )), - } - } -} - -impl TraceDestination { - pub fn project_name(&self) -> Option<&str> { - match self { - Self::ProjectLogs { project_name, .. } => project_name.as_deref(), - _ => None, - } - } -} - -/// Backend credentials. `token` is an API key or an OAuth access token; the -/// daemon does not care which. Never serialized or persisted. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct BackendAuth { - pub token: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub api_url: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub app_url: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub org_name: Option, - /// Optional org id. `bt` may or may not know it; the SDK's project - /// registration works from `org_name` alone, so this is best-effort and - /// only feeds the SDK's per-session credential/batch key. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub org_id: Option, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum FlushMode { - /// Deliver in the background; flush on session end / idle. The default. - #[default] - FireAndForget, - /// Additionally block on `session.flush` at each turn boundary. - FlushOnTurnEnd, -} - impl Envelope { /// A copy safe to journal. Only the non-secret route is serializable; the /// daemon-internal resolved config is excluded by construction. @@ -348,231 +60,3 @@ impl Envelope { } } } - -/// Journal form of [`Envelope`] with the token redacted. Deserializable so a -/// replay pass can read it back (and re-supply live credentials separately). -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RedactedEnvelope { - pub source: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub source_version: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub plugin_version: Option, - pub session_id: String, - pub event: String, - pub ts_ms: i64, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub managed_run_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub capture: Option, - pub payload: serde_json::Value, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub route: Option, -} - -#[cfg(test)] -mod tests { - use super::*; - - fn sample() -> Envelope { - Envelope { - source: "codex".into(), - source_version: Some("1.2.3".into()), - plugin_version: Some("0.4.0".into()), - session_id: "sess-1".into(), - event: "PostToolUse".into(), - ts_ms: 1_753_639_552_123, - managed_run_id: Some("run-1".into()), - capture: Some(CaptureContext { - process_chain: vec![ProcessIdentity { - pid: 42, - start_time_secs: 1_753_639_500, - }], - truncated: false, - }), - payload: serde_json::json!({ "session_id": "sess-1", "tool_name": "shell" }), - route: Some(SessionRoute { - auth: AuthSelection { - source: AuthSource::SavedProfile, - profile_id: None, - profile: Some("work".into()), - org_name: Some("acme".into()), - }, - destination: Some(TraceDestination::ProjectLogs { - project_id: None, - project_name: Some("codex".into()), - }), - ..SessionRoute::default() - }), - config: Some(SessionConfig { - auth: BackendAuth { - token: "sk-super-secret".into(), - api_url: Some("https://api.braintrust.dev".into()), - app_url: None, - org_name: Some("acme".into()), - org_id: None, - }, - destination: None, - flush_mode: FlushMode::FireAndForget, - tags: Default::default(), - additional_metadata: None, - span_plugins: Vec::new(), - }), - } - } - - #[test] - fn envelope_round_trips() { - let e = sample(); - let s = serde_json::to_string(&e).unwrap(); - let back: Envelope = serde_json::from_str(&s).unwrap(); - assert_eq!(back.session_id, "sess-1"); - assert_eq!(back.managed_run_id.as_deref(), Some("run-1")); - assert_eq!( - back.capture.as_ref().unwrap().process_chain[0], - ProcessIdentity { - pid: 42, - start_time_secs: 1_753_639_500, - } - ); - assert_eq!(back.route.unwrap().auth.profile.as_deref(), Some("work")); - assert!(back.config.is_none()); - assert!(!s.contains("sk-super-secret")); - } - - #[test] - fn journal_form_contains_only_the_route() { - let e = sample(); - let r = e.redacted(); - let s = serde_json::to_string(&r).unwrap(); - assert!( - !s.contains("sk-super-secret"), - "token leaked into journal form: {s}" - ); - assert_eq!(r.route.unwrap().auth.profile.as_deref(), Some("work")); - assert_eq!(r.managed_run_id.as_deref(), Some("run-1")); - assert_eq!(r.capture.unwrap().process_chain[0].pid, 42); - } - - #[test] - fn capture_context_is_backward_compatible() { - let mut value = serde_json::to_value(sample()).unwrap(); - value.as_object_mut().unwrap().remove("capture"); - - let envelope: Envelope = serde_json::from_value(value).unwrap(); - - assert!(envelope.capture.is_none()); - } - - #[test] - fn route_is_journal_safe_and_builds_resolved_config() { - let route = SessionRoute { - auth: AuthSelection { - source: AuthSource::SavedProfile, - profile_id: None, - profile: Some("work".into()), - org_name: Some("acme".into()), - }, - destination: Some(TraceDestination::ProjectLogs { - project_id: None, - project_name: Some("agent-traces".into()), - }), - ..SessionRoute::default() - }; - let config = route.with_auth(BackendAuth { - token: "secret".into(), - api_url: None, - app_url: None, - org_name: Some("acme".into()), - org_id: None, - }); - assert!(matches!( - config.destination, - Some(TraceDestination::ProjectLogs { project_name: Some(ref name), .. }) - if name == "agent-traces" - )); - assert_eq!(route.auth.profile.as_deref(), Some("work")); - - let mut envelope = sample(); - envelope.route = Some(route); - envelope.config = Some(config); - let journal = serde_json::to_string(&envelope.redacted()).unwrap(); - assert!(journal.contains("work")); - assert!(!journal.contains("secret")); - } - - #[test] - fn environment_auth_serializes_without_a_profile_or_secret() { - let selection = AuthSelection { - source: AuthSource::Environment, - profile_id: None, - profile: None, - org_name: Some("acme".into()), - }; - let json = serde_json::to_string(&selection).unwrap(); - assert_eq!(json, r#"{"source":"environment","org_name":"acme"}"#); - assert!(!json.contains("BRAINTRUST_API_KEY")); - } - - #[test] - fn legacy_environment_profile_canonicalizes_to_environment_auth() { - let selection: AuthSelection = - serde_json::from_str(r#"{"profile":"environment","org_name":"acme"}"#).unwrap(); - assert_eq!(selection.effective_source(), AuthSource::Environment); - let canonical = selection.canonicalized().unwrap(); - assert_eq!(canonical.source, AuthSource::Environment); - assert_eq!(canonical.profile, None); - assert_eq!(canonical.org_name.as_deref(), Some("acme")); - } - - #[test] - fn stable_profile_id_route_matches_its_legacy_name_route() { - let legacy = SessionRoute { - auth: AuthSelection { - source: AuthSource::Auto, - profile_id: None, - profile: Some("test-profile".into()), - org_name: Some("test-org".into()), - }, - destination: Some(TraceDestination::ProjectLogs { - project_id: None, - project_name: Some("test-project".into()), - }), - ..SessionRoute::default() - }; - let mut canonical = legacy.clone(); - canonical.auth.source = AuthSource::SavedProfile; - canonical.auth.profile_id = Some("00000000-0000-4000-8000-000000000001".into()); - - assert!(legacy.same_route(&canonical)); - canonical.auth.profile = Some("other-profile".into()); - assert!(!legacy.same_route(&canonical)); - } - - #[test] - fn flush_mode_defaults_to_fire_and_forget() { - let json = serde_json::json!({ - "auth": { "token": "t" }, - }); - let cfg: SessionConfig = serde_json::from_value(json).unwrap(); - assert_eq!(cfg.flush_mode, FlushMode::FireAndForget); - } - - #[test] - fn import_destination_references_are_typed() { - let project: TraceDestination = "project_logs:proj-123".parse().unwrap(); - assert!(matches!( - project, - TraceDestination::ProjectLogs { - project_id: Some(ref id), - project_name: None - } if id == "proj-123" - )); - let experiment: TraceDestination = "experiment:exp-456".parse().unwrap(); - assert!(matches!( - experiment, - TraceDestination::Experiment { ref experiment_id } if experiment_id == "exp-456" - )); - assert!("project:ambiguous".parse::().is_err()); - } -} diff --git a/bt-daemon/src/wire/envelope_tests.rs b/bt-daemon/src/wire/envelope_tests.rs new file mode 100644 index 00000000..c75e9599 --- /dev/null +++ b/bt-daemon/src/wire/envelope_tests.rs @@ -0,0 +1,220 @@ +use super::*; + +fn sample() -> Envelope { + Envelope { + source: "codex".into(), + source_version: Some("1.2.3".into()), + plugin_version: Some("0.4.0".into()), + session_id: "sess-1".into(), + event: "PostToolUse".into(), + ts_ms: 1_753_639_552_123, + managed_run_id: Some("run-1".into()), + capture: Some(CaptureContext { + process_chain: vec![ProcessIdentity { + pid: 42, + start_time_secs: 1_753_639_500, + }], + truncated: false, + }), + payload: serde_json::json!({ "session_id": "sess-1", "tool_name": "shell" }), + route: Some(SessionRoute { + auth: AuthSelection { + source: AuthSource::SavedProfile, + profile_id: None, + profile: Some("work".into()), + org_name: Some("acme".into()), + }, + destination: Some(TraceDestination::ProjectLogs { + project_id: None, + project_name: Some("codex".into()), + }), + ..SessionRoute::default() + }), + config: Some(SessionConfig { + auth: BackendAuth { + token: "sk-super-secret".into(), + api_url: Some("https://api.braintrust.dev".into()), + app_url: None, + org_name: Some("acme".into()), + org_id: None, + }, + destination: None, + flush_mode: FlushMode::FireAndForget, + tags: Default::default(), + additional_metadata: None, + span_plugins: Vec::new(), + }), + } +} + +#[test] +fn envelope_round_trips() { + let e = sample(); + let s = serde_json::to_string(&e).unwrap(); + let back: Envelope = serde_json::from_str(&s).unwrap(); + assert_eq!(back.session_id, "sess-1"); + assert_eq!(back.managed_run_id.as_deref(), Some("run-1")); + assert_eq!( + back.capture.as_ref().unwrap().process_chain[0], + ProcessIdentity { + pid: 42, + start_time_secs: 1_753_639_500, + } + ); + assert_eq!(back.route.unwrap().auth.profile.as_deref(), Some("work")); + assert!(back.config.is_none()); + assert!(!s.contains("sk-super-secret")); +} + +#[test] +fn journal_form_contains_only_the_route() { + let e = sample(); + let r = e.redacted(); + let s = serde_json::to_string(&r).unwrap(); + assert!( + !s.contains("sk-super-secret"), + "token leaked into journal form: {s}" + ); + assert_eq!(r.route.unwrap().auth.profile.as_deref(), Some("work")); + assert_eq!(r.managed_run_id.as_deref(), Some("run-1")); + assert_eq!(r.capture.unwrap().process_chain[0].pid, 42); +} + +#[test] +fn capture_context_is_backward_compatible() { + let mut value = serde_json::to_value(sample()).unwrap(); + value.as_object_mut().unwrap().remove("capture"); + + let envelope: Envelope = serde_json::from_value(value).unwrap(); + + assert!(envelope.capture.is_none()); +} + +#[test] +fn route_is_journal_safe_and_builds_resolved_config() { + let route = SessionRoute { + auth: AuthSelection { + source: AuthSource::SavedProfile, + profile_id: None, + profile: Some("work".into()), + org_name: Some("acme".into()), + }, + destination: Some(TraceDestination::ProjectLogs { + project_id: None, + project_name: Some("agent-traces".into()), + }), + ..SessionRoute::default() + }; + let config = route.with_auth(BackendAuth { + token: "secret".into(), + api_url: None, + app_url: None, + org_name: Some("acme".into()), + org_id: None, + }); + assert!(matches!( + config.destination, + Some(TraceDestination::ProjectLogs { project_name: Some(ref name), .. }) + if name == "agent-traces" + )); + assert_eq!(route.auth.profile.as_deref(), Some("work")); + + let mut envelope = sample(); + envelope.route = Some(route); + envelope.config = Some(config); + let journal = serde_json::to_string(&envelope.redacted()).unwrap(); + assert!(journal.contains("work")); + assert!(!journal.contains("secret")); +} + +#[test] +fn environment_auth_serializes_without_a_profile_or_secret() { + let selection = AuthSelection { + source: AuthSource::Environment, + profile_id: None, + profile: None, + org_name: Some("acme".into()), + }; + let json = serde_json::to_string(&selection).unwrap(); + assert_eq!(json, r#"{"source":"environment","org_name":"acme"}"#); + assert!(!json.contains("BRAINTRUST_API_KEY")); +} + +#[test] +fn legacy_environment_profile_canonicalizes_to_environment_auth() { + let selection: AuthSelection = + serde_json::from_str(r#"{"profile":"environment","org_name":"acme"}"#).unwrap(); + assert_eq!(selection.effective_source(), AuthSource::Environment); + let canonical = selection.canonicalized().unwrap(); + assert_eq!(canonical.source, AuthSource::Environment); + assert_eq!(canonical.profile, None); + assert_eq!(canonical.org_name.as_deref(), Some("acme")); +} + +#[test] +fn stable_profile_id_route_matches_its_legacy_name_route() { + let legacy = SessionRoute { + auth: AuthSelection { + source: AuthSource::Auto, + profile_id: None, + profile: Some("test-profile".into()), + org_name: Some("test-org".into()), + }, + destination: Some(TraceDestination::ProjectLogs { + project_id: None, + project_name: Some("test-project".into()), + }), + ..SessionRoute::default() + }; + let mut canonical = legacy.clone(); + canonical.auth.source = AuthSource::SavedProfile; + canonical.auth.profile_id = Some("00000000-0000-4000-8000-000000000001".into()); + + assert!(legacy.same_route(&canonical)); + canonical.auth.profile = Some("other-profile".into()); + assert!(!legacy.same_route(&canonical)); +} + +#[test] +fn flush_mode_defaults_to_fire_and_forget() { + let json = serde_json::json!({ + "auth": { "token": "t" }, + }); + let cfg: SessionConfig = serde_json::from_value(json).unwrap(); + assert_eq!(cfg.flush_mode, FlushMode::FireAndForget); +} + +#[test] +fn import_destination_references_are_typed() { + let project: TraceDestination = "project_logs:proj-123".parse().unwrap(); + assert!(matches!( + project, + TraceDestination::ProjectLogs { + project_id: Some(ref id), + project_name: None + } if id == "proj-123" + )); + let experiment: TraceDestination = "experiment:exp-456".parse().unwrap(); + assert!(matches!( + experiment, + TraceDestination::Experiment { ref experiment_id } if experiment_id == "exp-456" + )); + assert!("project:ambiguous".parse::().is_err()); +} + +#[test] +fn replay_restores_non_secret_route_configuration_without_credentials() { + let native = sample(); + let redacted = native.redacted(); + let recorded = serde_json::to_value(&redacted).unwrap(); + let replay = redacted.into_envelope(); + assert_eq!(serde_json::to_value(replay.redacted()).unwrap(), recorded); + let config = replay.config.unwrap(); + assert!(config.auth.token.is_empty()); + assert_eq!(config.auth.org_name.as_deref(), Some("acme")); + assert_eq!(config.project_name(), Some("codex")); + + let mut without_route = native.redacted(); + without_route.route = None; + assert!(without_route.into_envelope().config.is_none()); +} diff --git a/bt-daemon/src/wire/flush_mode.rs b/bt-daemon/src/wire/flush_mode.rs new file mode 100644 index 00000000..6154208c --- /dev/null +++ b/bt-daemon/src/wire/flush_mode.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FlushMode { + /// Deliver in the background; flush on session end / idle. The default. + #[default] + FireAndForget, + /// Additionally block on `session.flush` at each turn boundary. + FlushOnTurnEnd, +} diff --git a/bt-daemon/src/wire/mod.rs b/bt-daemon/src/wire/mod.rs index b6a74357..e4975645 100644 --- a/bt-daemon/src/wire/mod.rs +++ b/bt-daemon/src/wire/mod.rs @@ -1,25 +1,45 @@ //! bt-daemon wire protocol: the envelope types and JSON-RPC framing shared by //! the daemon (`serve`) and the plugin shims (`hook`). //! -//! This module is pure data + (de)serialization — no I/O, no async. The +//! Wire types own serialization and shared in-memory interpretation, without +//! I/O or async operations. The //! canonical description of the protocol lives in `docs/protocol.md`; keep //! the two in sync. +mod auth_selection; +mod auth_source; +mod backend_auth; +mod capture_context; mod envelope; +#[cfg(test)] +mod envelope_tests; +mod flush_mode; mod methods; +mod process_identity; +mod redacted_envelope; mod rpc; +mod session_config; +mod session_route; +mod trace_destination; -pub use envelope::{ - AuthSelection, AuthSource, BackendAuth, CaptureContext, Envelope, FlushMode, ProcessIdentity, - RedactedEnvelope, SessionConfig, SessionRoute, TraceDestination, -}; +pub use auth_selection::AuthSelection; +pub use auth_source::AuthSource; +pub use backend_auth::BackendAuth; +pub use capture_context::CaptureContext; +pub use envelope::Envelope; +pub use flush_mode::FlushMode; pub use methods::{ method, AuthDiagnoseParams, AuthDiagnoseResult, Capabilities, ClientInfo, EventLogResult, FlushParams, FlushResult, ImportFinishParams, ImportFinishResult, ImportResetParams, InitializeParams, InitializeResult, ManagedRunFlushParams, RecoveryInfo, SessionStatus, ShutdownResult, StatusParams, StatusResult, }; +pub use process_identity::ProcessIdentity; +pub use redacted_envelope::RedactedEnvelope; pub use rpc::{error_code, Message, Request, RequestId, Response, RpcError}; +pub use session_config::SessionConfig; +pub use session_route::SessionRoute; +pub use trace_destination::TraceDestination; /// The protocol version this build speaks. Bumped on any breaking change to /// the envelope or method contracts. See `docs/protocol.md`. diff --git a/bt-daemon/src/wire/process_identity.rs b/bt-daemon/src/wire/process_identity.rs new file mode 100644 index 00000000..96598f87 --- /dev/null +++ b/bt-daemon/src/wire/process_identity.rs @@ -0,0 +1,14 @@ +use serde::{Deserialize, Serialize}; + +/// One operating-system process observed while capturing an event. +/// +/// A PID alone is not a stable identity because operating systems reuse it. +/// `start_time_secs`, when available, distinguishes different occupants of the +/// same PID. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct ProcessIdentity { + pub pid: u32, + /// Epoch seconds reported by the operating system, or zero if unavailable. + #[serde(default)] + pub start_time_secs: u64, +} diff --git a/bt-daemon/src/wire/redacted_envelope.rs b/bt-daemon/src/wire/redacted_envelope.rs new file mode 100644 index 00000000..669147f3 --- /dev/null +++ b/bt-daemon/src/wire/redacted_envelope.rs @@ -0,0 +1,53 @@ +use super::{BackendAuth, CaptureContext, Envelope, SessionRoute}; +use serde::{Deserialize, Serialize}; + +/// Journal form of [`Envelope`] with the token redacted. Deserializable so a +/// replay pass can read it back (and re-supply live credentials separately). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RedactedEnvelope { + pub source: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_version: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plugin_version: Option, + pub session_id: String, + pub event: String, + pub ts_ms: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub managed_run_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub capture: Option, + pub payload: serde_json::Value, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub route: Option, +} + +impl RedactedEnvelope { + /// Restore translator state without credentials. A replay route supplies + /// non-secret configuration; live delivery must resolve credentials again. + pub fn into_envelope(self) -> Envelope { + let route = self.route; + let config = route.as_ref().map(|route| { + route.with_auth(BackendAuth { + token: String::new(), + api_url: None, + app_url: None, + org_name: route.auth.org_name.clone(), + org_id: None, + }) + }); + Envelope { + source: self.source, + source_version: self.source_version, + plugin_version: self.plugin_version, + session_id: self.session_id, + event: self.event, + ts_ms: self.ts_ms, + managed_run_id: self.managed_run_id, + capture: self.capture, + payload: self.payload, + route, + config, + } + } +} diff --git a/bt-daemon/src/wire/session_config.rs b/bt-daemon/src/wire/session_config.rs new file mode 100644 index 00000000..9af02245 --- /dev/null +++ b/bt-daemon/src/wire/session_config.rs @@ -0,0 +1,37 @@ +use super::{BackendAuth, FlushMode, TraceDestination}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeSet, path::PathBuf}; + +/// Trace settings and backend credentials resolved by the shim. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SessionConfig { + pub auth: BackendAuth, + /// Typed trace destination. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub destination: Option, + #[serde(default)] + pub flush_mode: FlushMode, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub additional_metadata: Option, + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub tags: BTreeSet, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub span_plugins: Vec, +} + +impl SessionConfig { + /// External parent/root ids used to shape translator rows. The sink keeps + /// the full destination components for object routing and propagation. + pub fn attached_span_ids(&self) -> (Option, Option) { + if let Some(TraceDestination::ParentSpan { components }) = &self.destination { + return (components.span_id.clone(), components.root_span_id.clone()); + } + (None, None) + } + + pub fn project_name(&self) -> Option<&str> { + self.destination + .as_ref() + .and_then(TraceDestination::project_name) + } +} diff --git a/bt-daemon/src/wire/session_route.rs b/bt-daemon/src/wire/session_route.rs new file mode 100644 index 00000000..610985a8 --- /dev/null +++ b/bt-daemon/src/wire/session_route.rs @@ -0,0 +1,119 @@ +use super::{AuthSelection, BackendAuth, FlushMode, SessionConfig, TraceDestination}; +use serde::{Deserialize, Serialize}; +use std::{collections::BTreeSet, path::PathBuf}; + +/// Immutable, journal-safe routing and trace settings for one agent session. +/// Credentials are deliberately absent and are resolved inside the daemon. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct SessionRoute { + #[serde(default)] + pub auth: AuthSelection, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub destination: Option, + #[serde(default)] + pub flush_mode: FlushMode, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub additional_metadata: Option, + /// Tags applied to each root span for this session. + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub tags: BTreeSet, + /// Ordered JavaScript span transforms. Paths are resolved by explicit + /// setup, run, and import commands before entering a session route. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub span_plugins: Vec, +} + +impl SessionRoute { + pub fn with_auth(&self, auth: BackendAuth) -> SessionConfig { + SessionConfig { + auth, + destination: self.destination.clone(), + flush_mode: self.flush_mode, + additional_metadata: self.additional_metadata.clone(), + tags: self.tags.clone(), + span_plugins: self.span_plugins.clone(), + } + } + + pub fn same_route(&self, other: &Self) -> bool { + let mut left = self.clone(); + let mut right = other.clone(); + if left + .auth + .profile_id + .as_ref() + .zip(right.auth.profile_id.as_ref()) + .is_some_and(|(left, right)| left != right) + { + return false; + } + // A stable-ID route is the canonical successor to an old named route. + // Journals can legitimately contain both forms for the same session, + // so replay compares their unchanged routing intent, not the newly + // learned identifier. + left.auth.profile_id = None; + right.auth.profile_id = None; + left.auth.source = left.auth.effective_source(); + right.auth.source = right.auth.effective_source(); + serde_json::to_value(left).ok() == serde_json::to_value(right).ok() + } + + /// Delivery settings may change without moving held work to another destination. + pub(crate) fn same_destination(&self, other: &Self) -> bool { + let identity = |route: &Self| Self { + auth: route.auth.clone(), + destination: route.destination.clone(), + ..Self::default() + }; + identity(self).same_route(&identity(other)) + } + + /// Raw journal entries can be replayed through a newer plugin chain as + /// long as their Braintrust delivery route is otherwise unchanged. + pub fn same_replay_route(&self, other: &Self) -> bool { + let mut left = self.clone(); + let mut right = other.clone(); + left.span_plugins.clear(); + right.span_plugins.clear(); + left.same_route(&right) + } + + /// Apply one invocation-local JSON metadata override to a non-secret route. + /// + /// The route is then carried unchanged through live hooks, managed runs, and + /// transcript import. Keeping validation here gives every public command the + /// same contract and prevents individual agent shims from parsing JSON. + pub(crate) fn apply_additional_metadata( + &mut self, + additional_metadata: Option<&str>, + ) -> anyhow::Result<()> { + let Some(metadata) = additional_metadata else { + return Ok(()); + }; + let value: serde_json::Value = serde_json::from_str(metadata) + .map_err(|e| anyhow::anyhow!("invalid --additional-metadata JSON: {e}"))?; + if !value.is_object() { + anyhow::bail!("--additional-metadata must be a JSON object"); + } + self.additional_metadata = Some(value); + Ok(()) + } + + /// Apply invocation-local root-span tags to a route. Trim whitespace and reject + /// empty tags here; the set keeps route tags unique. + pub(crate) fn apply_tags(&mut self, tags: &[String]) -> anyhow::Result<()> { + if tags.is_empty() { + return Ok(()); + } + let mut normalized = std::collections::BTreeSet::new(); + for tag in tags { + let tag = tag.trim(); + if tag.is_empty() { + anyhow::bail!("--tag must not be empty"); + } + normalized.insert(tag.to_string()); + } + self.tags = normalized; + Ok(()) + } +} diff --git a/bt-daemon/src/wire/trace_destination.rs b/bt-daemon/src/wire/trace_destination.rs new file mode 100644 index 00000000..0871db50 --- /dev/null +++ b/bt-daemon/src/wire/trace_destination.rs @@ -0,0 +1,54 @@ +use braintrust_sdk_rust::SpanComponents; +use serde::{Deserialize, Serialize}; + +/// Where a session's root span should be logged. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum TraceDestination { + /// Project logs selected by stable id, display name, or both. + ProjectLogs { + #[serde(default, skip_serializing_if = "Option::is_none")] + project_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + project_name: Option, + }, + /// An existing experiment. + Experiment { experiment_id: String }, + /// A child of an exported Braintrust span. + ParentSpan { components: SpanComponents }, +} + +impl std::str::FromStr for TraceDestination { + type Err = String; + + fn from_str(value: &str) -> Result { + let (kind, id) = value.split_once(':').ok_or_else(|| { + "destination must be project_logs: or experiment:" + .to_string() + })?; + if id.is_empty() { + return Err("destination id must not be empty".to_string()); + } + match kind { + "project_logs" => Ok(Self::ProjectLogs { + project_id: Some(id.to_string()), + project_name: None, + }), + "experiment" => Ok(Self::Experiment { + experiment_id: id.to_string(), + }), + _ => Err(format!( + "unsupported destination {kind:?}; expected project_logs or experiment" + )), + } + } +} + +impl TraceDestination { + pub fn project_name(&self) -> Option<&str> { + match self { + Self::ProjectLogs { project_name, .. } => project_name.as_deref(), + _ => None, + } + } +}