diff --git a/AGENTS.md b/AGENTS.md index acd2eaf8..7e83ef3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,6 +39,20 @@ limitation and preserve known parent totals rather than inventing attribution. ## Local development +Use concrete Rust types for every known schema. Decode JSON at the input +boundary, then pass typed structs and enums through the implementation; serialize +them at the output boundary. Share schema types across hooks, setup, managed +runs, transcript import, replay, and other consumers of the same data instead of +defining parallel shapes. Known IDs, flags, counters, messages, tool-call +envelopes, and configuration fields must not be stored or traversed as +`serde_json::Value`, including through string-keyed `.get()` or indexing. +Reserve `Value` for encoding boundaries and genuinely open-ended data such as +metadata, arbitrary tool arguments/results, JSON schemas, and unknown extension +fields that must round-trip. Document why each remaining dynamic field needs +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. + 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.rs b/bt-daemon/src/agents/antigravity.rs index 3358a58b..94d16caa 100644 --- a/bt-daemon/src/agents/antigravity.rs +++ b/bt-daemon/src/agents/antigravity.rs @@ -1,3 +1,4 @@ +pub(crate) mod schema; use super::{Agent, Identity, Register, Registrar}; use std::sync::Arc; diff --git a/bt-daemon/src/agents/antigravity/schema.rs b/bt-daemon/src/agents/antigravity/schema.rs new file mode 100644 index 00000000..115993c7 --- /dev/null +++ b/bt-daemon/src/agents/antigravity/schema.rs @@ -0,0 +1,125 @@ +//! Antigravity native records shared by live translation and transcript import. +use crate::agents::usage::ProviderUsage; +use crate::json::Extensions; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Native transcript records are decoded before entering translator state. +#[derive(Clone, Default, Serialize, Deserialize)] +pub(crate) struct TranscriptRecord { + #[serde(default, rename = "type")] + pub kind: String, + #[serde(default)] + pub source: String, + #[serde(default, alias = "stepIndex", deserialize_with = "optional_integer")] + pub step_index: Option, + #[serde(default, alias = "createdAt")] + pub created_at: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::agents::schema::deserialize_present" + )] + pub content: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::agents::schema::deserialize_present" + )] + pub message: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::agents::schema::deserialize_present" + )] + pub text: Option, + #[serde(default, alias = "toolCalls")] + pub tool_calls: Option, + #[serde(default)] + pub error: Option, + #[serde(default)] + pub status: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub usage: Option, + /// Unknown native extensions are retained without inspecting their contents. + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + 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), + } + 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(), + } + } +} + +#[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, +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + #[test] + fn persisted_records_keep_missing_content_distinct_from_null() { + for raw in [ + json!({"message":"fallback"}), + json!({"content":null,"message":"fallback"}), + ] { + let record: TranscriptRecord = serde_json::from_value(raw.clone()).unwrap(); + let restored: TranscriptRecord = + serde_json::from_value(serde_json::to_value(&record).unwrap()).unwrap(); + assert_eq!(restored.content, record.content); + assert_eq!(restored.message, record.message); + assert_eq!( + restored.content.is_some(), + raw.as_object().unwrap().contains_key("content") + ); + } + } +} diff --git a/bt-daemon/src/agents/cursor.rs b/bt-daemon/src/agents/cursor.rs index d975c4a6..c7f210da 100644 --- a/bt-daemon/src/agents/cursor.rs +++ b/bt-daemon/src/agents/cursor.rs @@ -1,3 +1,4 @@ +pub(crate) mod schema; use super::{Agent, Identity, Register, Registrar}; use std::sync::Arc; diff --git a/bt-daemon/src/agents/cursor/schema.rs b/bt-daemon/src/agents/cursor/schema.rs new file mode 100644 index 00000000..9764479c --- /dev/null +++ b/bt-daemon/src/agents/cursor/schema.rs @@ -0,0 +1,98 @@ +//! Native Cursor transcript schema shared by live translation and import. +use serde::Deserialize; + +#[derive(Deserialize)] +#[serde(untagged)] +pub(crate) enum TranscriptRecord { + Message { + role: Role, + message: TranscriptMessage, + }, + /// Marks the end of a turn. The translator reads turn status from hooks, + /// so only the marker's shape is checked. + TurnEnded { + #[serde(rename = "type")] + _kind: TurnEndedKind, + #[serde(rename = "status")] + status: String, + #[serde(rename = "error", default)] + error: Option, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum Role { + User, + Assistant, +} + +impl Role { + pub fn as_str(self) -> &'static str { + match self { + Self::User => "user", + Self::Assistant => "assistant", + } + } +} + +#[derive(Deserialize)] +pub(crate) struct TranscriptMessage { + pub content: MessageContent, +} + +#[derive(Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum TurnEndedKind { + TurnEnded, +} + +/// Message content: plain text, or content blocks. +#[derive(Deserialize)] +#[serde(untagged)] +pub(crate) enum MessageContent { + Text(String), + Blocks(Vec), +} + +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum ContentBlock { + Text { + text: String, + }, + /// Tool requests are reported by hooks; transcripts add nothing to them. + ToolUse, +} + +impl MessageContent { + /// The concatenated text of the content. + pub fn text(&self) -> String { + match self { + Self::Text(text) => text.clone(), + Self::Blocks(blocks) => blocks + .iter() + .filter_map(|block| match block { + ContentBlock::Text { text } => Some(text.as_str()), + ContentBlock::ToolUse => None, + }) + .collect(), + } + } +} + +impl TranscriptRecord { + pub fn role(&self) -> Option { + match self { + Self::Message { role, .. } => Some(*role), + Self::TurnEnded { .. } => None, + } + } + + pub fn text(&self) -> Option { + match self { + Self::Message { message, .. } => Some(message.content.text()), + Self::TurnEnded { .. } => None, + } + } +} diff --git a/bt-daemon/src/agents/mod.rs b/bt-daemon/src/agents/mod.rs index eca23c15..fbd70d4b 100644 --- a/bt-daemon/src/agents/mod.rs +++ b/bt-daemon/src/agents/mod.rs @@ -5,14 +5,17 @@ //! [`Register::register`]. A command looks up agents in its own registry, so //! an agent without a capability simply does not appear there. -mod antigravity; +pub(crate) mod antigravity; mod claude; mod codex; -mod cursor; +pub(crate) mod cursor; mod grok; mod muse; mod opencode; mod pi; +pub(crate) mod request; +pub(crate) mod schema; +pub(crate) mod usage; pub(crate) use antigravity::Antigravity; pub(crate) use claude::Claude; diff --git a/bt-daemon/src/agents/request.rs b/bt-daemon/src/agents/request.rs new file mode 100644 index 00000000..b525bb75 --- /dev/null +++ b/bt-daemon/src/agents/request.rs @@ -0,0 +1,208 @@ +//! The normalized request configuration retained by Pi, independent of the +//! provider-native payload. Unknown built-in tools remain provider-owned JSON; +//! function definitions and their arbitrary parameter schemas are distinguished. +use crate::json::{Extensions, Field}; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::{value::RawValue, Value}; + +#[derive(Default, Serialize, Deserialize)] +pub(crate) struct RequestConfig { + #[serde(skip_serializing_if = "Option::is_none")] + temperature: Option, + #[serde(skip_serializing_if = "Option::is_none")] + top_p: Option, + #[serde(skip_serializing_if = "Option::is_none")] + max_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + frequency_penalty: Option, + #[serde(skip_serializing_if = "Option::is_none")] + presence_penalty: Option, + #[serde(skip_serializing_if = "Option::is_none")] + stop: Option, + #[serde(skip_serializing_if = "Option::is_none")] + response_format: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + tools: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + tool_choice: Option, + #[serde(skip_serializing_if = "Option::is_none")] + parallel_tool_calls: Option, + #[serde(skip_serializing_if = "Option::is_none")] + max_tool_calls: Option, +} +impl RequestConfig { + pub fn is_empty(&self) -> bool { + self.temperature.is_none() + && self.top_p.is_none() + && self.max_tokens.is_none() + && self.frequency_penalty.is_none() + && self.presence_penalty.is_none() + && self.stop.is_none() + && self.response_format.is_none() + && self.tools.is_empty() + && self.tool_choice.is_none() + && self.parallel_tool_calls.is_none() + && self.max_tool_calls.is_none() + } +} +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum Stop { + One(String), + Many(Vec), +} +#[derive(Serialize)] +#[serde(untagged)] +enum ToolDefinition { + Function(FunctionTool), + BuiltIn(Extensions), +} +#[derive(Serialize, Deserialize)] +struct FunctionTool { + #[serde(rename = "type")] + kind: FunctionType, + function: FunctionDefinition, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, +} +#[derive(Serialize, Deserialize)] +enum FunctionType { + #[serde(rename = "function")] + Function, +} +#[derive(Serialize, Deserialize)] +struct FunctionDefinition { + name: String, + #[serde(skip_serializing_if = "Option::is_none")] + description: Option, + /// Tool-authored JSON Schema, intentionally unrestricted. + #[serde(skip_serializing_if = "Option::is_none")] + parameters: Option, + #[serde(skip_serializing_if = "Option::is_none")] + strict: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, +} +impl<'de> Deserialize<'de> for ToolDefinition { + fn deserialize>(d: D) -> Result { + let value = Value::deserialize(d)?; + if value.get("type").and_then(Value::as_str) == Some("function") { + serde_json::from_value(value) + .map(Self::Function) + .map_err(serde::de::Error::custom) + } else { + serde_json::from_value(value) + .map(Self::BuiltIn) + .map_err(serde::de::Error::custom) + } + } +} +#[derive(Serialize, Deserialize)] +#[serde(untagged)] +enum ToolChoice { + Mode(ChoiceMode), + Named(NamedChoice), +} +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +enum ChoiceMode { + Auto, + None, + Required, +} +#[derive(Serialize, Deserialize)] +struct NamedChoice { + #[serde(rename = "type")] + kind: FunctionType, + function: FunctionName, +} +#[derive(Serialize, Deserialize)] +struct FunctionName { + name: String, +} + +#[derive(Serialize)] +#[serde(untagged)] +enum ResponseFormat { + Known(KnownResponseFormat), + Other(Box), +} +#[derive(Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +enum KnownResponseFormat { + Text { + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, + JsonObject { + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, + JsonSchema { + json_schema: SchemaDefinition, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, +} +#[derive(Serialize, Deserialize)] +struct SchemaDefinition { + name: String, + #[serde(default, skip_serializing_if = "Field::is_missing")] + description: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + strict: Field, + /// Provider/user-authored JSON Schema, intentionally unrestricted. + schema: Value, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, +} +impl<'de> Deserialize<'de> for ResponseFormat { + fn deserialize>(d: D) -> Result { + let value = Value::deserialize(d)?; + if matches!( + value.get("type").and_then(Value::as_str), + Some("text" | "json_object" | "json_schema") + ) { + serde_json::from_value(value) + .map(Self::Known) + .map_err(serde::de::Error::custom) + } else { + serde_json::value::to_raw_value(&value) + .map(Self::Other) + .map_err(serde::de::Error::custom) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + #[test] + fn request_variants_preserve_schemas_and_provider_builtins() { + let raw = json!({"max_tokens":100,"stop":["END"],"tool_choice":{"type":"function","function":{"name":"read"}}, + "tools":[{"type":"function","function":{"name":"read","parameters":{"type":"object","future":true}}},{"type":"web_search","future":true}], + "response_format":{"type":"json_schema","json_schema":{"name":"answer","schema":{"type":"object","future":true}}}}); + let config: RequestConfig = serde_json::from_value(raw.clone()).unwrap(); + assert!(matches!(&config.tools[0], ToolDefinition::Function(_))); + assert!(matches!(&config.tools[1], ToolDefinition::BuiltIn(_))); + assert_eq!(serde_json::to_value(config).unwrap(), raw); + for format in [ + json!({"type":"text","future":null}), + json!({"type":"json_object","future":true}), + json!({"type":"json_schema","json_schema":{"name":"answer","description":null,"strict":null,"schema":{"type":"object"}},"future":true}), + json!({"type":"future","settings":[null,42]}), + ] { + let raw = json!({"response_format":format}); + let parsed: RequestConfig = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), raw); + } + for raw in [ + json!({"tools":[{"type":"function","function":{"name":42}}]}), + json!({"max_tokens":"100"}), + json!({"response_format":{"type":"json_schema","json_schema":{"name":42,"schema":{}}}}), + ] { + assert!(serde_json::from_value::(raw).is_err()); + } + } +} diff --git a/bt-daemon/src/agents/schema.rs b/bt-daemon/src/agents/schema.rs new file mode 100644 index 00000000..7e554edc --- /dev/null +++ b/bt-daemon/src/agents/schema.rs @@ -0,0 +1,264 @@ +//! 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/usage.rs b/bt-daemon/src/agents/usage.rs new file mode 100644 index 00000000..0f202535 --- /dev/null +++ b/bt-daemon/src/agents/usage.rs @@ -0,0 +1,562 @@ +//! 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/attachments.rs b/bt-daemon/src/attachments.rs index 1500d28d..195c2a9b 100644 --- a/bt-daemon/src/attachments.rs +++ b/bt-daemon/src/attachments.rs @@ -24,6 +24,30 @@ impl Attachment { } } +#[derive(Debug, Clone, Serialize)] +pub(crate) struct AttachmentReference { + #[serde(rename = "type")] + kind: AttachmentReferenceType, + key: String, + filename: crate::json::Field, + content_type: crate::json::Field, +} +#[derive(Debug, Clone, Serialize)] +enum AttachmentReferenceType { + #[serde(rename = "braintrust_attachment")] + BraintrustAttachment, +} +impl AttachmentReference { + pub fn uploaded(key: String, attachment: &Attachment) -> Self { + Self { + kind: AttachmentReferenceType::BraintrustAttachment, + key, + filename: crate::json::Field::Value(attachment.filename.clone()), + content_type: crate::json::Field::Value(attachment.content_type.clone()), + } + } +} + /// Recognize native attachment-bearing content without opening files or fetching URLs. pub(crate) fn contains(value: &Value) -> bool { match value { @@ -176,7 +200,7 @@ fn decode_url(url: &str) -> Option<(String, Vec)> { pub(crate) fn materialize( value: &mut Value, - references: &std::collections::HashMap, + references: &std::collections::HashMap, ) { if value.get("type").and_then(Value::as_str) == Some("_bt_attachment") { if let Some(reference) = value @@ -184,13 +208,24 @@ pub(crate) fn materialize( .and_then(Value::as_str) .and_then(|id| references.get(id)) { + #[derive(Deserialize)] + struct Marker { + #[serde(default)] + filename: crate::json::Field, + #[serde(default)] + content_type: crate::json::Field, + } + let Ok(marker) = Marker::deserialize(&*value) else { + return; + }; let mut replacement = reference.clone(); - for key in ["filename", "content_type"] { - if let Some(field) = value.get(key) { - replacement[key] = field.clone(); - } + if !marker.filename.is_missing() { + replacement.filename = marker.filename; } - *value = replacement; + if !marker.content_type.is_missing() { + replacement.content_type = marker.content_type; + } + *value = json!(replacement); } return; } @@ -224,10 +259,8 @@ mod tests { let references = attachments .into_iter() .map(|a| { - ( - a.digest, - json!({"type":"braintrust_attachment","key":"uploaded"}), - ) + let reference = AttachmentReference::uploaded("uploaded".into(), &a); + (a.digest, reference) }) .collect(); materialize(&mut value, &references); diff --git a/bt-daemon/src/codex_hooks.rs b/bt-daemon/src/codex_hooks.rs index 27952059..5c9a41b0 100644 --- a/bt-daemon/src/codex_hooks.rs +++ b/bt-daemon/src/codex_hooks.rs @@ -1,8 +1,11 @@ //! Inspect and activate Braintrust hooks through Codex's app-server protocol. //! Trust writes use the same exact-definition config API as Codex's /hooks UI. +use crate::agents::schema::{HookFile, HookGroup}; use anyhow::{anyhow, Context}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::{json, Value}; +use std::collections::BTreeMap; use std::path::Path; use std::process::Stdio; use std::time::Duration; @@ -30,6 +33,59 @@ const PLUGIN_EVENTS: &[&str] = &[ "interrupt", "sessionEnd", ]; +// The app-server transport is JSON; consumers only receive typed results. +#[derive(Deserialize)] +struct ConfigRead { + config: Config, +} +#[derive(Deserialize)] +struct Config { + #[serde(default)] + features: BTreeMap, +} +#[derive(Deserialize)] +struct PluginList { + marketplaces: Vec, +} +#[derive(Deserialize)] +struct PluginMarketplace { + plugins: Vec, +} +#[derive(Deserialize)] +struct Plugin { + id: String, + installed: bool, + enabled: bool, +} +#[derive(Debug, Deserialize)] +struct HooksList { + data: Vec, +} +#[derive(Debug, Deserialize)] +struct HookEntry { + errors: Option>, + hooks: Vec, +} +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Hook { + plugin_id: Option, + event_name: Option, + handler_type: Option, + command: Option, + enabled: Option, + is_managed: Option, + source: Option, + source_path: Option, + trust_status: Option, + key: Option, + current_hash: Option, +} +#[derive(Serialize)] +struct TrustState<'a> { + trusted_hash: &'a str, +} + pub(crate) async fn activate() -> anyhow::Result<()> { let cwd = std::env::current_dir()?; let mut command: tokio::process::Command = @@ -49,12 +105,12 @@ pub(crate) async fn activate() -> anyhow::Result<()> { let mut stdin = child.stdin.take().context("Codex stdin unavailable")?; let stdout = child.stdout.take().context("Codex stdout unavailable")?; let mut stdout = BufReader::new(stdout.take(8 * 1024 * 1024)); - request(&mut stdin, &mut stdout, 1, "initialize", json!({ + request::(&mut stdin, &mut stdout, 1, "initialize", json!({ "clientInfo":{"name":"braintrust_trace_setup","version":env!("CARGO_PKG_VERSION")}, "capabilities":{"experimentalApi":true} })).await?; stdin.write_all(b"{\"method\":\"initialized\"}\n").await?; - let config = request( + let config: ConfigRead = request( &mut stdin, &mut stdout, 2, @@ -62,12 +118,13 @@ pub(crate) async fn activate() -> anyhow::Result<()> { json!({"includeLayers":false}), ) .await?; - let features = &config["config"]["features"]; + let features = &config.config.features; anyhow::ensure!( - features["hooks"] != false && features["codex_hooks"] != false, + features.get("hooks") != Some(&false) + && features.get("codex_hooks") != Some(&false), "Codex hooks are disabled in config; enable hooks and retry setup" ); - let plugins = request( + let plugins: PluginList = request( &mut stdin, &mut stdout, 3, @@ -77,22 +134,16 @@ pub(crate) async fn activate() -> anyhow::Result<()> { }), ) .await?; - let installed = plugins["marketplaces"] - .as_array() - .into_iter() - .flatten() - .filter_map(|marketplace| marketplace["plugins"].as_array()) - .flatten() - .any(|plugin| { - plugin["id"] == PLUGIN - && plugin["installed"] == true - && plugin["enabled"] == true - }); + let installed = plugins + .marketplaces + .iter() + .flat_map(|marketplace| &marketplace.plugins) + .any(|plugin| plugin.id == PLUGIN && plugin.installed && plugin.enabled); anyhow::ensure!( installed, "Codex tracing plugin is not installed and enabled; rerun `bt trace install codex`" ); - let hooks = request( + let hooks: HooksList = request( &mut stdin, &mut stdout, 4, @@ -102,7 +153,7 @@ pub(crate) async fn activate() -> anyhow::Result<()> { .await?; let edits = trust_edits(&hooks)?; if !edits.is_empty() { - request( + request::( &mut stdin, &mut stdout, 5, @@ -114,7 +165,7 @@ pub(crate) async fn activate() -> anyhow::Result<()> { ) .await?; } - let hooks = request( + let hooks: HooksList = request( &mut stdin, &mut stdout, 6, @@ -163,12 +214,12 @@ pub(crate) async fn run_trust_override( let mut stdin = child.stdin.take().context("Codex stdin unavailable")?; let stdout = child.stdout.take().context("Codex stdout unavailable")?; let mut stdout = BufReader::new(stdout.take(8 * 1024 * 1024)); - request(&mut stdin, &mut stdout, 1, "initialize", json!({ + request::(&mut stdin, &mut stdout, 1, "initialize", json!({ "clientInfo":{"name":"braintrust_trace_run","version":env!("CARGO_PKG_VERSION")}, "capabilities":{"experimentalApi":true} })).await?; stdin.write_all(b"{\"method\":\"initialized\"}\n").await?; - let hooks = request( + let hooks: HooksList = request( &mut stdin, &mut stdout, 2, @@ -189,34 +240,28 @@ pub(crate) async fn run_trust_override( } fn managed_run_trust_state( - hooks: &Value, + hooks: &HooksList, expected_command: &str, ) -> anyhow::Result { - let expected: Value = serde_json::from_str(PACKAGED_HOOKS)?; - let expected_events: std::collections::HashSet = expected["hooks"] - .as_object() - .context("packaged hooks missing")? + let expected: HookFile = serde_json::from_str(PACKAGED_HOOKS)?; + let expected_events: std::collections::HashSet = expected + .hooks .keys() .map(|event| format!("{}{}", event[..1].to_ascii_lowercase(), &event[1..])) .collect(); - let entries = hooks["data"] - .as_array() - .context("hooks/list has no data array")?; + let entries = &hooks.data; let mut seen = std::collections::HashSet::new(); let mut trust = std::collections::BTreeMap::new(); for entry in entries { anyhow::ensure!( - entry["errors"].as_array().is_some_and(Vec::is_empty), + entry.errors.as_ref().is_some_and(Vec::is_empty), "Codex reported hook errors during managed-run setup" ); - for hook in entry["hooks"] - .as_array() - .context("hooks/list entry has no hooks array")? - { - if hook["source"] != "sessionFlags" { + for hook in &entry.hooks { + if hook.source.as_deref() != Some("sessionFlags") { continue; } - let Some(event) = hook["eventName"].as_str() else { + let Some(event) = hook.event_name.as_deref() else { continue; }; if !expected_events.contains(event) { @@ -224,25 +269,27 @@ fn managed_run_trust_state( } anyhow::ensure!( seen.insert(event.to_owned()) - && hook["handlerType"] == "command" - && hook["command"] == expected_command - && hook["enabled"] == true - && hook["isManaged"] == false, + && hook.handler_type.as_deref() == Some("command") + && hook.command.as_deref() == Some(expected_command) + && hook.enabled == Some(true) + && hook.is_managed == Some(false), "Codex changed a Braintrust hook while preparing this run" ); anyhow::ensure!( matches!( - hook["trustStatus"].as_str(), + hook.trust_status.as_deref(), Some("trusted" | "untrusted" | "modified") ), "Codex reported an unsupported trust state for a managed Braintrust hook" ); - let key = hook["key"] - .as_str() + let key = hook + .key + .as_deref() .filter(|value| !value.is_empty()) .context("Codex omitted a managed Braintrust hook key")?; - let hash = hook["currentHash"] - .as_str() + let hash = hook + .current_hash + .as_deref() .filter(|value| !value.is_empty()) .context("Codex omitted a managed Braintrust hook hash")?; anyhow::ensure!( @@ -273,35 +320,32 @@ fn managed_run_trust_state( /// Validate the complete installed file, including the other platform's command, /// before approving exact hashes returned by Codex. Never infer hashes or keys. -fn trust_edits(hooks: &Value) -> anyhow::Result> { +fn trust_edits(hooks: &HooksList) -> anyhow::Result>> { + // Full-file equality is an encoding-boundary check: absent and null + // fields must remain distinct before trusting Codex's exact hashes. let expected: Value = serde_json::from_str(PACKAGED_HOOKS)?; let mut checked_paths = std::collections::HashSet::new(); let mut events = std::collections::HashSet::new(); - let mut edits = serde_json::Map::new(); - for entry in hooks["data"] - .as_array() - .context("hooks/list has no data array")? - { - for hook in entry["hooks"] - .as_array() - .context("hooks/list entry has no hooks array")? - { - if hook["pluginId"].as_str() != Some(PLUGIN) { + let mut edits = BTreeMap::new(); + for entry in &hooks.data { + for hook in &entry.hooks { + if hook.plugin_id.as_deref() != Some(PLUGIN) { continue; } - let event = hook["eventName"].as_str().context("hook event missing")?; + let event = hook.event_name.as_deref().context("hook event missing")?; anyhow::ensure!( PLUGIN_EVENTS.contains(&event) && events.insert(event) - && hook["handlerType"] == "command" - && hook["command"] == "bt trace hook --source codex" - && hook["enabled"] == true - && hook["isManaged"] == false - && hook["source"] == "plugin", + && hook.handler_type.as_deref() == Some("command") + && hook.command.as_deref() == Some("bt trace hook --source codex") + && hook.enabled == Some(true) + && hook.is_managed == Some(false) + && hook.source.as_deref() == Some("plugin"), "Unexpected or disabled Braintrust hook definition; inspect /hooks" ); - let path = hook["sourcePath"] - .as_str() + let path = hook + .source_path + .as_deref() .context("hook source path missing")?; anyhow::ensure!( Path::new(path).is_absolute(), @@ -312,24 +356,27 @@ fn trust_edits(hooks: &Value) -> anyhow::Result> anyhow::ensure!(installed == expected, "Installed Braintrust hooks differ from this bt version; update bt and retry setup"); } - if hook["trustStatus"] == "trusted" { + if hook.trust_status.as_deref() == Some("trusted") { continue; } anyhow::ensure!( - hook["trustStatus"] == "untrusted" || hook["trustStatus"] == "modified", + hook.trust_status.as_deref() == Some("untrusted") + || hook.trust_status.as_deref() == Some("modified"), "Unknown Braintrust hook trust state" ); - let key = hook["key"] - .as_str() + let key = hook + .key + .as_deref() .filter(|s| !s.is_empty()) .context("hook key missing")?; - let hash = hook["currentHash"] - .as_str() + let hash = hook + .current_hash + .as_deref() .filter(|s| !s.is_empty()) .context("hook hash missing")?; anyhow::ensure!( edits - .insert(key.to_owned(), json!({"trusted_hash":hash})) + .insert(key.to_owned(), TrustState { trusted_hash: hash }) .is_none(), "Duplicate Braintrust hook key" ); @@ -342,13 +389,13 @@ fn trust_edits(hooks: &Value) -> anyhow::Result> Ok(edits) } -async fn request( +async fn request( stdin: &mut (impl AsyncWrite + Unpin), stdout: &mut (impl AsyncBufRead + Unpin), id: u64, method: &str, params: Value, -) -> anyhow::Result { +) -> anyhow::Result { let mut encoded = serde_json::to_vec(&json!({"id":id,"method":method,"params":params}))?; encoded.push(b'\n'); stdin.write_all(&encoded).await?; @@ -359,23 +406,32 @@ async fn request( stdout.read_line(&mut line).await? != 0, "Codex closed the probe stream" ); - let response: Value = serde_json::from_str(&line).context("invalid Codex response")?; - if response.get("id") != Some(&json!(id)) { + #[derive(Deserialize)] + struct Response { + id: Option, + error: Option, + #[serde( + default, + deserialize_with = "crate::agents::schema::deserialize_present" + )] + result: Option>, + } + #[derive(Deserialize)] + struct RpcError { + message: Option, + } + let response: Response = serde_json::from_str(&line).context("invalid Codex response")?; + if response.id != Some(json!(id)) { continue; } - if let Some(error) = response.get("error") { + if let Some(error) = response.error { return Err(anyhow!( "{method}: {}", - error - .get("message") - .and_then(Value::as_str) - .unwrap_or("request failed") + error.message.as_deref().unwrap_or("request failed") )); } - return response - .get("result") - .cloned() - .context("Codex response has no result"); + let result = response.result.context("Codex response has no result")?; + return serde_json::from_str(result.get()).context("invalid Codex result"); } } @@ -401,13 +457,33 @@ mod tests { ); } + #[tokio::test] + async fn rpc_distinguishes_null_results_from_missing_results() { + let mut input = Vec::new(); + let mut output = std::io::Cursor::new(b"{\"id\":1,\"result\":null}\n"); + assert_eq!( + request::(&mut input, &mut output, 1, "initialize", json!({})) + .await + .unwrap(), + Value::Null + ); + let mut output = std::io::Cursor::new(b"{\"id\":1}\n"); + assert!( + request::(&mut input, &mut output, 1, "initialize", json!({})) + .await + .unwrap_err() + .to_string() + .contains("no result") + ); + } + #[tokio::test] async fn rpc_ignores_notifications_and_reports_unsupported_methods() { let mut input = Vec::new(); let mut output = std::io::Cursor::new( b"{\"method\":\"notice\"}\n{\"id\":3,\"error\":{\"message\":\"Method not found\"}}\n", ); - let error = request(&mut input, &mut output, 3, "hooks/list", json!({})) + let error = request::(&mut input, &mut output, 3, "hooks/list", json!({})) .await .unwrap_err(); assert!(error.to_string().contains("Method not found")); diff --git a/bt-daemon/src/dispatch.rs b/bt-daemon/src/dispatch.rs index 1b62f7f5..f27facaa 100644 --- a/bt-daemon/src/dispatch.rs +++ b/bt-daemon/src/dispatch.rs @@ -9,6 +9,7 @@ use crate::pipeline::{ translation::Translation, }; use crate::sink::SinkFactory; +use crate::transcript_mirror::{GrokReferences, Reference, TranscriptPayload}; use crate::wire::Envelope; use parking_lot::Mutex; use std::path::PathBuf; @@ -357,17 +358,15 @@ pub(crate) async fn hydrate_transcript_reference(data_dir: &std::path::Path, env if env.source != "codex" { return; } - let field = if env.event == "SubagentStop" { - "agent_transcript_path" + let Ok(fields) = TranscriptPayload::decode(&env.payload) else { + return; + }; + let path = if env.event == "SubagentStop" { + fields.agent_transcript_path } else { - "transcript_path" + fields.transcript_path }; - let Some(path) = env - .payload - .get(field) - .and_then(serde_json::Value::as_str) - .map(str::to_owned) - else { + let Some(path) = path else { return; }; let mirror_session = crate::ids::session_namespace(&env.source, &env.session_id); @@ -382,33 +381,29 @@ pub(crate) async fn hydrate_transcript_reference(data_dir: &std::path::Path, env if let Some(payload) = env.payload.as_object_mut() { payload.insert( "_bt_transcript_mirror".to_string(), - serde_json::json!({ - "path": path, - "mirror": mirror.to_string_lossy(), - "through": through, - }), + serde_json::json!(Reference::captured(&path, &mirror, through)), ); } } async fn hydrate_cursor_transcript_reference(data_dir: &std::path::Path, env: &mut Envelope) { - if env.payload.get("_bt_transcript_mirror").is_some() { + let Ok(fields) = TranscriptPayload::decode(&env.payload) else { + return; + }; + if fields.mirror.is_some() { return; } - let path = env - .payload - .get("transcript_path") - .and_then(serde_json::Value::as_str); - let mut observation = serde_json::json!({}); - if let Some(path) = path.filter(|path| !path.is_empty()) { - let observed_bytes = env - .payload - .get("_bt_transcript_observation") - .filter(|observation| { - observation.get("path").and_then(serde_json::Value::as_str) == Some(path) - }) - .and_then(|observation| observation.get("observed_bytes")) - .and_then(serde_json::Value::as_u64); + let mut observation = Reference::default(); + if let Some(path) = fields + .transcript_path + .as_deref() + .filter(|path| !path.is_empty()) + { + let observed_bytes = fields + .observation + .as_ref() + .filter(|observation| observation.path.as_deref() == Some(path)) + .and_then(|observation| observation.observed_bytes); let mirror_session = crate::ids::session_namespace(&env.source, &env.session_id); match crate::transcript_mirror::capture_generation( data_dir, @@ -419,8 +414,7 @@ async fn hydrate_cursor_transcript_reference(data_dir: &std::path::Path, env: &m .await { Ok((mirror, through)) => { - observation = - serde_json::json!({"path": path, "mirror": mirror, "through": through}); + observation = Reference::captured(path, &mirror, through); } Err(error) => { tracing::debug!(session_id = %env.session_id, %error, "Cursor transcript mirror skipped"); @@ -430,17 +424,23 @@ async fn hydrate_cursor_transcript_reference(data_dir: &std::path::Path, env: &m if let Some(payload) = env.payload.as_object_mut() { // An empty observation is also durable: no transcript was available // at this boundary, even if the external path appears during replay. - payload.insert("_bt_transcript_mirror".to_string(), observation); + payload.insert( + "_bt_transcript_mirror".to_string(), + serde_json::json!(observation), + ); } } async fn hydrate_claude_transcript_references(data_dir: &std::path::Path, env: &mut Envelope) { // Historical snapshots and newly captured references are observations, // not invitations to reread an external file during journal recovery. - if env.payload.get("_bt_claude_transcript_mirrors").is_some() - || env.payload.get("_bt_transcript_mirror").is_some() - || env.payload.get("_bt_transcript_snapshot").is_some() - || env.payload.get("_bt_transcript_replay").is_some() + 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() { return; } @@ -481,11 +481,14 @@ 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 = serde_json::Map::new(); - for field in ["transcript_path", "agent_transcript_path"] { - let Some(path) = env.payload.get(field).and_then(serde_json::Value::as_str) else { - continue; - }; + let mut mirrors = std::collections::BTreeMap::new(); + for path in [ + fields.transcript_path.as_deref(), + fields.agent_transcript_path.as_deref(), + ] + .into_iter() + .flatten() + { if mirrors.contains_key(path) { continue; } @@ -493,7 +496,7 @@ async fn hydrate_claude_transcript_references(data_dir: &std::path::Path, env: & Ok((mirror, through)) => { mirrors.insert( path.to_string(), - serde_json::json!({"path": path, "mirror": mirror, "through": through}), + Reference::captured(path, &mirror, through), ); } Err(error) => { @@ -507,7 +510,7 @@ async fn hydrate_claude_transcript_references(data_dir: &std::path::Path, env: & if let Some(payload) = env.payload.as_object_mut() { payload.insert( "_bt_claude_transcript_mirrors".to_string(), - serde_json::Value::Object(mirrors), + serde_json::json!(mirrors), ); } } @@ -517,20 +520,17 @@ const GROK_TERMINAL_SNAPSHOT_QUIET_PERIOD: std::time::Duration = std::time::Duration::from_millis(10); async fn hydrate_grok_transcript_references(data_dir: &std::path::Path, env: &mut Envelope) { - let Some(transcript) = env - .payload - .get("transcriptPath") - .or_else(|| env.payload.get("transcript_path")) - .and_then(serde_json::Value::as_str) - .map(std::path::PathBuf::from) - else { + let Ok(fields) = TranscriptPayload::decode(&env.payload) else { + return; + }; + let Some(transcript) = fields.transcript_path.map(std::path::PathBuf::from) else { return; }; let Some(session_dir) = transcript.parent() else { return; }; let mirror_session = crate::ids::session_namespace(&env.source, &env.session_id); - let mut mirrors = serde_json::Map::new(); + let mut mirrors = GrokReferences::default(); capture_grok_transcript_pass( data_dir, session_dir, @@ -558,7 +558,7 @@ async fn hydrate_grok_transcript_references(data_dir: &std::path::Path, env: &mu if let Some(payload) = env.payload.as_object_mut() { payload.insert( "_bt_grok_transcript_mirrors".to_string(), - serde_json::Value::Object(mirrors), + serde_json::json!(mirrors), ); } } @@ -569,12 +569,12 @@ async fn capture_grok_transcript_pass( session_dir: &std::path::Path, mirror_session: &str, session_id: &str, - mirrors: &mut serde_json::Map, + mirrors: &mut GrokReferences, ) { - for (name, key) in [ - ("updates.jsonl", "updates"), - ("events.jsonl", "events"), - ("system_prompt.txt", "system_prompt"), + for (name, slot) in [ + ("updates.jsonl", &mut mirrors.updates), + ("events.jsonl", &mut mirrors.events), + ("system_prompt.txt", &mut mirrors.system_prompt), ] { let source = session_dir.join(name); let Some(source_str) = source.to_str() else { @@ -582,14 +582,7 @@ async fn capture_grok_transcript_pass( }; match crate::transcript_mirror::capture(data_dir, mirror_session, source_str).await { Ok((mirror, through)) => { - mirrors.insert( - key.to_string(), - serde_json::json!({ - "path": source, - "mirror": mirror, - "through": through, - }), - ); + *slot = Some(Reference::captured(source_str, &mirror, through)); } Err(error) => { tracing::debug!(%session_id, %error, file = name, "Grok transcript mirror skipped"); diff --git a/bt-daemon/src/hook.rs b/bt-daemon/src/hook.rs index e4b4ce23..39c63019 100644 --- a/bt-daemon/src/hook.rs +++ b/bt-daemon/src/hook.rs @@ -392,11 +392,9 @@ fn plugin_version_from_plugin_root(source: &str) -> Option { } fn plugin_version_from_manifest(path: &std::path::Path) -> Option { - serde_json::from_slice::(&std::fs::read(path).ok()?) + serde_json::from_slice::(&std::fs::read(path).ok()?) .ok()? - .get("version")? - .as_str() - .map(str::to_owned) + .version } fn now_ms() -> i64 { diff --git a/bt-daemon/src/muse/field.rs b/bt-daemon/src/json.rs similarity index 54% rename from bt-daemon/src/muse/field.rs rename to bt-daemon/src/json.rs index 229f061d..6a763ffc 100644 --- a/bt-daemon/src/muse/field.rs +++ b/bt-daemon/src/json.rs @@ -1,5 +1,6 @@ -//! Optional wire fields whose explicit null differs from absence in authored -//! metadata and replay fingerprints. Ordinary optional data uses Option instead. +//! Shared JSON-boundary helpers. Preserve explicit null versus absence in +//! authored metadata and replay fingerprints, and retain unknown extensions as +//! opaque encodings. Ordinary optional data uses Option instead. use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[derive(Debug, Clone, Default, PartialEq, Eq)] pub(crate) enum Field { @@ -45,3 +46,25 @@ impl<'de, T: Deserialize<'de>> Deserialize<'de> for Field { Ok(Option::::deserialize(d)?.into()) } } + +use serde_json::value::RawValue; +use std::collections::BTreeMap; + +pub(crate) type Extensions = BTreeMap>; + +/// Serde buffers flattened fields, so RawValue cannot deserialize them +/// directly. Materialize JSON only at this decoding boundary, then retain +/// unknown values as opaque encodings rather than traversable data bags. +pub(crate) fn deserialize_extensions<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + let fields = BTreeMap::::deserialize(deserializer)?; + fields + .into_iter() + .map(|(key, value)| { + serde_json::value::to_raw_value(&value) + .map(|raw| (key, raw)) + .map_err(serde::de::Error::custom) + }) + .collect() +} diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index 9ebcd76c..10d080ae 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -27,6 +27,7 @@ mod hook; mod hook_executable; mod ids; mod journal; +mod json; mod managed_run; mod muse; mod pipeline; diff --git a/bt-daemon/src/managed_run/codex.rs b/bt-daemon/src/managed_run/codex.rs index 8c0dab1a..0e94ca31 100644 --- a/bt-daemon/src/managed_run/codex.rs +++ b/bt-daemon/src/managed_run/codex.rs @@ -3,6 +3,7 @@ use std::ffi::OsString; use super::{managed_hook_shell_command, Injection, ManagedRun, Terminal}; +use crate::agents::schema::{HookFile, HookGroup}; use crate::agents::Codex; use crate::args::RunHookCommand; @@ -22,30 +23,20 @@ fn codex_managed_run_args( unix_command: &str, windows_command: &str, ) -> anyhow::Result> { - let manifest: serde_json::Value = serde_json::from_str(PACKAGED_HOOKS)?; + let manifest: HookFile = serde_json::from_str(PACKAGED_HOOKS)?; let mut args = vec![OsString::from("--enable"), OsString::from("hooks")]; - for (event, groups) in manifest["hooks"] - .as_object() - .ok_or_else(|| anyhow::anyhow!("Codex hook manifest has no hooks map"))? - { - let mut groups = groups.clone(); - for group in groups - .as_array_mut() - .ok_or_else(|| anyhow::anyhow!("Codex hook groups must be an array"))? - { - for hook in group["hooks"] - .as_array_mut() - .ok_or_else(|| anyhow::anyhow!("Codex hook group has no hooks array"))? - { - anyhow::ensure!(hook["type"] == "command", "Unsupported Codex hook type"); - hook["command"] = serde_json::Value::String(unix_command.to_owned()); - hook["commandWindows"] = serde_json::Value::String(windows_command.to_owned()); + for (event, mut groups) in manifest.hooks { + for group in &mut groups { + for hook in &mut group.hooks { + anyhow::ensure!(hook.kind == "command", "Unsupported Codex hook type"); + hook.command = unix_command.to_owned(); + hook.command_windows = Some(windows_command.to_owned()); } } args.push(OsString::from("-c")); args.push(OsString::from(format!( "hooks.{event}={}", - toml_literal(&groups)? + toml_literal(&serde_json::to_value(&groups)?)? ))); } Ok(args) diff --git a/bt-daemon/src/managed_run/cursor.rs b/bt-daemon/src/managed_run/cursor.rs index bbc6db2d..02dd1a1e 100644 --- a/bt-daemon/src/managed_run/cursor.rs +++ b/bt-daemon/src/managed_run/cursor.rs @@ -6,6 +6,7 @@ use super::{ managed_hook_shell_command, quote_unix_shell_arg, quote_windows_command_arg, Injection, ManagedRun, Terminal, }; +use crate::agents::schema::{CursorCommandHook, HookFile}; use crate::agents::Cursor; use crate::args::RunHookCommand; use crate::paths; @@ -72,12 +73,10 @@ const CURSOR_HOOKS_MANIFEST: &str = include_str!(concat!( "/../src/plugins/cursor/content/hooks/hooks.json" )); +#[cfg(test)] pub(super) fn cursor_hook_events() -> anyhow::Result> { - let manifest: serde_json::Value = serde_json::from_str(CURSOR_HOOKS_MANIFEST)?; - manifest["hooks"] - .as_object() - .map(|hooks| hooks.keys().cloned().collect()) - .ok_or_else(|| anyhow::anyhow!("Cursor hook manifest has no hooks object")) + let manifest: HookFile = serde_json::from_str(CURSOR_HOOKS_MANIFEST)?; + Ok(manifest.hooks.into_keys().collect()) } /// Build a private plugin that Cursor loads only for the managed invocation. @@ -108,10 +107,11 @@ fn write_cursor_managed_plugin_for_platform( }))?, )?; let script_path = hook_dir.join(if windows { "trace.ps1" } else { "trace.sh" }); - let source_manifest: serde_json::Value = serde_json::from_str(CURSOR_HOOKS_MANIFEST)?; - let hooks = cursor_hook_events()? - .iter() - .map(|event| { + let source_manifest: HookFile = serde_json::from_str(CURSOR_HOOKS_MANIFEST)?; + let hooks = source_manifest + .hooks + .into_iter() + .map(|(event, entries)| { let command = if windows { format!( "powershell.exe -NoProfile -ExecutionPolicy Bypass -File {} {event}", @@ -120,20 +120,17 @@ fn write_cursor_managed_plugin_for_platform( } else { format!("\"${{CURSOR_PLUGIN_ROOT}}/hooks/trace.sh\" {event}") }; - let mut registration = serde_json::json!({ - "command": command, - "timeout": 10, - "failClosed": false - }); - if let Some(matcher) = source_manifest["hooks"][event][0]["matcher"].as_str() { - registration["matcher"] = serde_json::json!(matcher); - } - (event.clone(), serde_json::json!([registration])) + let matcher = entries.first().and_then(|entry| entry.matcher.clone()); + (event, vec![CursorCommandHook::capture(command, matcher)]) }) - .collect::>(); + .collect(); std::fs::write( hook_dir.join("hooks.json"), - serde_json::to_vec(&serde_json::json!({ "version": 1, "hooks": hooks }))?, + serde_json::to_vec(&HookFile { + hooks, + version: crate::json::Field::Value(1), + extra: Default::default(), + })?, )?; if windows { diff --git a/bt-daemon/src/managed_run/opencode.rs b/bt-daemon/src/managed_run/opencode.rs index 4c0ce3af..26d06b8c 100644 --- a/bt-daemon/src/managed_run/opencode.rs +++ b/bt-daemon/src/managed_run/opencode.rs @@ -1,6 +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::OpenCode; use crate::args::RunHookCommand; use std::ffi::OsString; @@ -68,19 +69,12 @@ pub(super) fn inject_for_version(v2: bool, args: &[OsString]) -> anyhow::Result< } fn opencode_managed_config(existing: Option<&str>, v2: bool) -> anyhow::Result { - let mut config = match existing { - Some(raw) => serde_json::from_str::(raw) + let mut config: OpenCodeConfig = match existing { + Some(raw) => serde_json::from_str(raw) .map_err(|error| anyhow::anyhow!("invalid OPENCODE_CONFIG_CONTENT: {error}"))?, - None => serde_json::json!({}), + None => OpenCodeConfig::default(), }; - let object = config - .as_object_mut() - .ok_or_else(|| anyhow::anyhow!("OPENCODE_CONFIG_CONTENT must be a JSON object"))?; - let plugins = object - .entry("plugin") - .or_insert_with(|| serde_json::Value::Array(Vec::new())) - .as_array_mut() - .ok_or_else(|| anyhow::anyhow!("OPENCODE_CONFIG_CONTENT.plugin must be an array"))?; + 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" @@ -89,8 +83,8 @@ fn opencode_managed_config(existing: Option<&str>, v2: bool) -> anyhow::Result, #[serde(flatten)] extra: Extensions, } @@ -72,7 +74,7 @@ impl<'de> Deserialize<'de> for HookHandler { } impl HookHandler { fn is_owned(&self) -> bool { - matches!(self, Self::User(handler) if handler.extra.is_empty() + matches!(self, Self::User(handler) if handler.extra.is_empty() && handler.timeout.is_missing() && matches!(handler.command.as_str(), HOOK_COMMAND | LEGACY_HOOK_COMMAND)) } fn contains_braintrust(&self) -> bool { @@ -122,6 +124,7 @@ impl HookOverlay { hooks: vec![HookHandler::User(UserCommand { kind: CommandType::Command, command: command.into(), + timeout: Field::Missing, extra: BTreeMap::new(), })], }); diff --git a/bt-daemon/src/muse/config/ownership.rs b/bt-daemon/src/muse/config/ownership.rs index c364844c..675b4a2b 100644 --- a/bt-daemon/src/muse/config/ownership.rs +++ b/bt-daemon/src/muse/config/ownership.rs @@ -1,7 +1,7 @@ //! Strict owned-file recognition, separate from preservable foreign documents. use super::hooks::{opaque_contains_braintrust, CommandType, HookDocument}; use super::{HOOK_COMMAND, LEGACY_HOOK_COMMAND}; -use crate::muse::field::Field; +use crate::json::Field; use crate::muse::hooks::HookName; use anyhow::Context; use serde::{Deserialize, Serialize}; diff --git a/bt-daemon/src/muse/config/settings.rs b/bt-daemon/src/muse/config/settings.rs index 68327c0f..6181387f 100644 --- a/bt-daemon/src/muse/config/settings.rs +++ b/bt-daemon/src/muse/config/settings.rs @@ -1,10 +1,10 @@ //! Settings projection with lossless unrelated fields and explicit missing/null //! semantics. The caller holds Muse's native lock while loading and writing. use super::hooks::HookOverlay; -use crate::muse::field::Field; +use crate::json::Extensions; +use crate::json::Field; use anyhow::Context; use serde::{Deserialize, Serialize}; -use std::collections::BTreeMap; use std::path::{Path, PathBuf}; #[derive(Default, Serialize, Deserialize)] @@ -15,8 +15,8 @@ pub(crate) struct MuseSettings { pub managed_hooks_path: Field, #[serde(default, skip_serializing_if = "Field::is_missing")] pub hooks: Field, - #[serde(flatten)] - extra: BTreeMap, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extra: Extensions, } impl MuseSettings { pub fn load(path: &Path) -> anyhow::Result { diff --git a/bt-daemon/src/muse/hooks.rs b/bt-daemon/src/muse/hooks.rs index 9587250a..287ade17 100644 --- a/bt-daemon/src/muse/hooks.rs +++ b/bt-daemon/src/muse/hooks.rs @@ -1,10 +1,10 @@ //! Hook wire DTOs shared by live decoding and export synthesis. Unknown events //! are ignored; known events decode once before any tracing policy executes. -use super::field::Field; use super::ids::{RequestId, ToolCallId, TurnId}; pub(crate) use super::messages::*; pub(crate) use super::outcome::*; use super::usage::{TokenUsage, UsageScope}; +use crate::json::Field; use crate::wire::Envelope; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; diff --git a/bt-daemon/src/muse/messages.rs b/bt-daemon/src/muse/messages.rs index 63f5549c..df702073 100644 --- a/bt-daemon/src/muse/messages.rs +++ b/bt-daemon/src/muse/messages.rs @@ -1,7 +1,8 @@ //! Native hook message and provider payload contracts. +pub(crate) use super::provider_options::ProviderOptions; +use crate::json::{Extensions, Field}; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; -use std::collections::BTreeMap; /// These values have schemas owned by the tool or provider, not by Muse tracing. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -10,7 +11,6 @@ pub(crate) struct ToolInput(pub Value); #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(transparent)] pub(crate) struct ToolOutput(pub Value); -pub(crate) type ProviderOptions = BTreeMap; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub(crate) enum ModelOutput { @@ -28,8 +28,8 @@ pub(crate) struct NativeMessage { pub tool_call_id: Option, #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, - #[serde(flatten)] - pub extensions: BTreeMap, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extensions: Extensions, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(from = "String", into = "String")] @@ -72,75 +72,154 @@ pub(crate) enum MessageContent { Text(String), Blocks(Vec), } +/// Known content variants are validated before the unknown-content fallback. #[derive(Debug, Clone, Serialize)] -#[serde(tag = "type")] +#[serde(untagged)] pub(crate) enum ContentBlock { - #[serde(rename = "text")] + Known(KnownContentBlock), + Other { + #[serde(rename = "type")] + kind: String, + #[serde(flatten)] + fields: Extensions, + }, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub(crate) enum KnownContentBlock { Text { text: String, - #[serde(flatten)] - extensions: BTreeMap, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, }, - #[serde(rename = "assistant_message")] AssistantMessage { text: String, - #[serde(flatten)] - extensions: BTreeMap, + #[serde(default, skip_serializing_if = "Field::is_missing")] + provider_item_id: Field, + #[serde(default, skip_serializing_if = "Field::is_missing")] + phase: Field, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, }, - #[serde(untagged)] - Other { - #[serde(rename = "type")] - kind: String, - #[serde(flatten)] - fields: BTreeMap, + Image { + source: ImageSource, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, + ImageUrl { + image_url: ImageUrl, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, }, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum MessagePhase { + Analysis, + Commentary, + FinalAnswer, + #[serde(untagged)] + Other(String), +} impl<'de> Deserialize<'de> for ContentBlock { fn deserialize>(d: D) -> Result { - // Dispatch first so a malformed known block cannot hide in the fallback. #[derive(Deserialize)] struct Tag { #[serde(rename = "type")] kind: String, } - #[derive(Deserialize)] - struct Text { - text: String, - #[serde(rename = "type")] - _kind: String, - #[serde(flatten)] - extensions: BTreeMap, - } let value = Value::deserialize(d)?; let tag: Tag = serde_json::from_value(value.clone()).map_err(serde::de::Error::custom)?; - match tag.kind.as_str() { - "text" | "assistant_message" => { - let body: Text = serde_json::from_value(value).map_err(serde::de::Error::custom)?; - Ok(if tag.kind == "text" { - Self::Text { - text: body.text, - extensions: body.extensions, - } - } else { - Self::AssistantMessage { - text: body.text, - extensions: body.extensions, - } - }) - } - _ => { - let mut fields: BTreeMap = - serde_json::from_value(value).map_err(serde::de::Error::custom)?; - fields.remove("type"); - Ok(Self::Other { - kind: tag.kind, - fields, - }) + if matches!( + tag.kind.as_str(), + "text" | "assistant_message" | "image" | "image_url" + ) { + serde_json::from_value(value) + .map(Self::Known) + .map_err(serde::de::Error::custom) + } else { + let mut fields: Extensions = + serde_json::from_value(value).map_err(serde::de::Error::custom)?; + fields.remove("type"); + Ok(Self::Other { + kind: tag.kind, + fields, + }) + } + } +} + +#[derive(Debug, Clone, Serialize)] +#[serde(untagged)] +pub(crate) enum ImageSource { + Base64(Base64ImageSource), + Url(UrlImageSource), + /// Future source formats survive unchanged, without becoming known data. + Other(Box), +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct Base64ImageSource { + #[serde(rename = "type")] + kind: Base64Type, + media_type: String, + data: String, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +enum Base64Type { + #[serde(rename = "base64")] + Base64, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct UrlImageSource { + url: String, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, +} +impl<'de> Deserialize<'de> for ImageSource { + fn deserialize>(d: D) -> Result { + let value = Value::deserialize(d)?; + if !value.is_object() { + return Err(serde::de::Error::custom("image source must be an object")); + } + match value.get("type").and_then(Value::as_str) { + Some("base64") => serde_json::from_value(value) + .map(Self::Base64) + .map_err(serde::de::Error::custom), + kind @ (None | Some("url")) if kind.is_some() || value.get("url").is_some() => { + serde_json::from_value(value) + .map(Self::Url) + .map_err(serde::de::Error::custom) } + _ => serde_json::value::to_raw_value(&value) + .map(Self::Other) + .map_err(serde::de::Error::custom), } } } #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub(crate) enum ImageUrl { + Url(String), + Detailed { + url: String, + #[serde(default, skip_serializing_if = "Field::is_missing")] + detail: Field, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extensions: Extensions, + }, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum ImageDetail { + Auto, + Low, + High, + #[serde(untagged)] + Other(String), +} +#[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct AssistantToolCall { pub id: String, #[serde(rename = "type")] @@ -184,13 +263,60 @@ pub(crate) struct ToolDescription { pub strict: Option, #[serde(skip_serializing_if = "Option::is_none")] pub parameters: Option, - #[serde(flatten)] - pub extensions: BTreeMap, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extensions: Extensions, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub(crate) struct InputSummary { #[serde(skip_serializing_if = "Option::is_none")] pub request_message_count: Option, - #[serde(flatten)] - pub extensions: BTreeMap, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extensions: Extensions, +} + +#[cfg(test)] +mod extension_tests { + use super::*; + use serde_json::json; + + #[test] + fn known_assistant_fields_and_image_variants_round_trip() { + for raw in [ + json!({"type":"assistant_message","text":"done","provider_item_id":null,"phase":"final_answer","future":true}), + json!({"type":"assistant_message","text":"done","phase":"future-phase"}), + json!({"type":"image","source":{"url":"https://example.com/image","future":null},"future":true}), + json!({"type":"image","source":{"type":"base64","media_type":"image/png","data":"YWJj","future":true}}), + json!({"type":"image_url","image_url":{"url":"https://example.com/image","detail":"high","future":true}}), + json!({"type":"image","source":{"type":"future","opaque":[null,42]}}), + json!({"type":"future","opaque":[null,42]}), + ] { + let parsed: ContentBlock = serde_json::from_value(raw.clone()).unwrap(); + assert_eq!(serde_json::to_value(parsed).unwrap(), raw); + } + let parsed: ContentBlock = serde_json::from_value( + json!({"type":"assistant_message","text":"done","phase":"final_answer"}), + ) + .unwrap(); + assert!(matches!( + parsed, + ContentBlock::Known(KnownContentBlock::AssistantMessage { + phase: Field::Value(MessagePhase::FinalAnswer), + .. + }) + )); + } + + #[test] + fn malformed_known_fields_cannot_hide_as_unknown_content() { + for raw in [ + json!({"type":"image","source":42}), + json!({"type":"assistant_message","text":"done","provider_item_id":42}), + json!({"type":"assistant_message","text":"done","phase":42}), + json!({"type":"image","source":{"url":42}}), + json!({"type":"image","source":{"type":"base64","media_type":"image/png","data":42}}), + json!({"type":"image_url","image_url":{"url":"example","detail":42}}), + ] { + assert!(serde_json::from_value::(raw).is_err()); + } + } } diff --git a/bt-daemon/src/muse/metadata.rs b/bt-daemon/src/muse/metadata.rs index 7cca8923..82e6b17e 100644 --- a/bt-daemon/src/muse/metadata.rs +++ b/bt-daemon/src/muse/metadata.rs @@ -1,7 +1,7 @@ //! Authored Braintrust row shapes. Serialization into SpanRow is the final JSON //! boundary; lifecycle and metric policy never navigate these JSON values. -use super::field::Field; use super::hooks::*; +use crate::json::Field; use serde::Serialize; use serde_json::Value; diff --git a/bt-daemon/src/muse/mod.rs b/bt-daemon/src/muse/mod.rs index 0d24389b..16047b7b 100644 --- a/bt-daemon/src/muse/mod.rs +++ b/bt-daemon/src/muse/mod.rs @@ -2,7 +2,6 @@ //! schemas; only hooks and exports normalize into the same tracing events. pub(crate) mod config; pub(crate) mod export_v1; -pub(crate) mod field; pub(crate) mod hooks; pub(crate) mod ids; pub(crate) mod images; @@ -11,3 +10,5 @@ pub(crate) mod metadata; pub(crate) mod msp; pub(crate) mod outcome; pub(crate) mod usage; + +pub(crate) mod provider_options; diff --git a/bt-daemon/src/muse/outcome.rs b/bt-daemon/src/muse/outcome.rs index 71968eda..94948fb1 100644 --- a/bt-daemon/src/muse/outcome.rs +++ b/bt-daemon/src/muse/outcome.rs @@ -1,5 +1,5 @@ //! Native operation outcomes, including open future statuses. -use super::field::Field; +use crate::json::Field; use serde::{Deserialize, Serialize}; use serde_json::Value; diff --git a/bt-daemon/src/muse/provider_options.rs b/bt-daemon/src/muse/provider_options.rs new file mode 100644 index 00000000..7c8c0886 --- /dev/null +++ b/bt-daemon/src/muse/provider_options.rs @@ -0,0 +1,127 @@ +//! Dotted option keys observed in native Muse hooks. These options coexist: +//! selecting one provider variant for the entire object would discard others. +use crate::json::{Extensions, Field}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub(crate) struct ProviderOptions { + #[serde( + default, + rename = "anthropic.output_config.effort", + skip_serializing_if = "Field::is_missing" + )] + pub anthropic_effort: Field, + #[serde( + default, + rename = "anthropic.thinking", + skip_serializing_if = "Field::is_missing" + )] + pub anthropic_thinking: Field, + #[serde( + default, + rename = "anthropic.thinking.budget_tokens", + skip_serializing_if = "Field::is_missing" + )] + pub anthropic_thinking_budget: Field, + #[serde( + default, + rename = "local.reasoning.effort", + skip_serializing_if = "Field::is_missing" + )] + pub local_effort: Field, + #[serde( + default, + rename = "meta.reasoning.effort", + skip_serializing_if = "Field::is_missing" + )] + pub reasoning_effort: Field, + #[serde( + default, + rename = "openai.reasoning.effort", + skip_serializing_if = "Field::is_missing" + )] + pub openai_effort: Field, + #[serde( + default, + rename = "openrouter.reasoning.effort", + skip_serializing_if = "Field::is_missing" + )] + pub openrouter_effort: Field, + #[serde( + default, + rename = "meta.session_id", + skip_serializing_if = "Field::is_missing" + )] + pub session_id: Field, + #[serde( + default, + rename = "meta.traceparent", + skip_serializing_if = "Field::is_missing" + )] + pub traceparent: Field, + /// Provider-defined keys outside the recorded contract are never inspected. + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + pub extensions: Extensions, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum ReasoningEffort { + None, + Minimal, + Low, + Medium, + High, + Xhigh, + Max, + Ultra, + #[serde(untagged)] + Other(String), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum ThinkingMode { + Enabled, + Disabled, + Adaptive, + #[serde(untagged)] + Other(String), +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn provider_options_coexist_and_preserve_null_unknown_values_and_new_modes() { + let raw = json!({ + "anthropic.output_config.effort":"low", "anthropic.thinking":"enabled", + "anthropic.thinking.budget_tokens":4096, "openai.reasoning.effort":"high", + "meta.reasoning.effort":null, "local.reasoning.effort":"future", + "vendor.future":{"nested":[null,42]} + }); + let options: ProviderOptions = serde_json::from_value(raw.clone()).unwrap(); + assert!(matches!( + options.anthropic_effort, + Field::Value(ReasoningEffort::Low) + )); + assert!(matches!( + options.openai_effort, + Field::Value(ReasoningEffort::High) + )); + assert!(matches!(options.reasoning_effort, Field::Null)); + assert!(matches!( + options.local_effort, + Field::Value(ReasoningEffort::Other(_)) + )); + assert_eq!(serde_json::to_value(options).unwrap(), raw); + for raw in [ + json!({"anthropic.thinking.budget_tokens":"4096"}), + json!({"openai.reasoning.effort":42}), + ] { + assert!(serde_json::from_value::(raw).is_err()); + } + } +} diff --git a/bt-daemon/src/muse/usage.rs b/bt-daemon/src/muse/usage.rs index 5b282690..ee2e980f 100644 --- a/bt-daemon/src/muse/usage.rs +++ b/bt-daemon/src/muse/usage.rs @@ -1,5 +1,6 @@ //! Hook/export counters are snake_case, optional, and may be turn-cumulative. //! They are not the SDK's camelCase, required-counter MSP view types. +pub(crate) use crate::agents::usage::TokenMetrics; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)] @@ -26,22 +27,6 @@ pub(crate) enum UsageScope { Model, } -#[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 TokenUsage { pub fn delta_since(&self, previous: &Self) -> Self { fn delta(current: Option, previous: Option) -> Option { @@ -75,25 +60,3 @@ impl TokenUsage { } } } - -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/server/claude_transcripts.rs b/bt-daemon/src/server/claude_transcripts.rs index 61e9f0e6..e14f6fc1 100644 --- a/bt-daemon/src/server/claude_transcripts.rs +++ b/bt-daemon/src/server/claude_transcripts.rs @@ -3,12 +3,14 @@ //! written after the session's last hook are still translated. use super::*; +use crate::transcript_mirror::TranscriptPayload; #[derive(Clone)] pub(super) struct ClaudeTranscriptObservation { /// Synthetic-event provenance only: never retain native prompts or responses. pub(super) template: Envelope, pub(super) through: Option, + pub(super) path: String, pub(super) children: HashMap, } @@ -16,37 +18,50 @@ pub(super) struct ClaudeTranscriptObservation { pub(super) struct ClaudeChildObservation { pub(super) template: Envelope, pub(super) through: Option, + pub(super) path: String, } impl Daemon { pub(super) fn remember_claude_transcripts(&self, env: &Envelope) { - if env.source != "claude-code" || env.payload.get("_bt_import_through_offset").is_some() { + if env.source != "claude-code" { + return; + } + let Ok(fields) = TranscriptPayload::decode(&env.payload) else { + return; + }; + if fields.import_through_offset.is_some() { return; } let Some(route) = env.route.as_ref() else { return; }; - let Some(path) = env.payload.get("transcript_path").and_then(Value::as_str) else { + let Some(path) = fields.transcript_path.as_deref() else { return; }; let Ok(key) = DeliveryKey::new(&env.source, &env.session_id, route) else { return; }; - let through = env - .payload - .get("_bt_claude_transcript_mirrors") + let through = fields + .claude_mirrors + .as_ref() .and_then(|mirrors| mirrors.get(path)) .or_else(|| { - env.payload - .get("_bt_transcript_mirror") - .filter(|mirror| mirror.get("path").and_then(Value::as_str) == Some(path)) + fields + .mirror + .as_ref() + .filter(|mirror| mirror.path.as_deref() == Some(path)) }) - .and_then(|mirror| mirror.get("through")) - .and_then(Value::as_u64); - let mut payload = serde_json::json!({"transcript_path": path}); - if let Some(cwd) = env.payload.get("cwd").and_then(Value::as_str) { - payload["cwd"] = Value::String(cwd.to_string()); + .and_then(|mirror| mirror.through); + #[derive(serde::Serialize)] + struct PollPayload<'a> { + transcript_path: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + cwd: Option<&'a str>, } + let payload = serde_json::json!(PollPayload { + transcript_path: path, + cwd: fields.cwd.as_deref() + }); let template = Envelope { source: env.source.clone(), source_version: env.source_version.clone(), @@ -64,63 +79,47 @@ impl Daemon { let old = observations.remove(&key); let previous = old .as_ref() - .filter(|observation| { - observation - .template - .payload - .get("transcript_path") - .and_then(Value::as_str) - == Some(path) - }) + .filter(|observation| observation.path == path) .and_then(|observation| observation.through); let mut children = old .map(|observation| observation.children) .unwrap_or_default(); - if let Some(saved) = env - .payload - .get("_bt_claude_children") - .and_then(Value::as_object) - { + if let Some(saved) = fields.claude_children.as_ref() { for (agent_id, observation) in saved { - let Some(child_path) = observation.get("path").and_then(Value::as_str) else { - continue; - }; + let child_path = &observation.path; let mut child_template = template.clone(); - child_template.payload["agent_id"] = Value::String(agent_id.clone()); - child_template.payload["agent_transcript_path"] = - Value::String(child_path.to_string()); + child_template.payload["agent_id"] = serde_json::json!(agent_id); + child_template.payload["agent_transcript_path"] = serde_json::json!(child_path); children.insert( agent_id.clone(), ClaudeChildObservation { template: child_template, - through: observation.get("through").and_then(Value::as_u64), + through: observation.through, + path: child_path.clone(), }, ); } } if matches!(env.event.as_str(), "SubagentStop" | "TranscriptUpdate") { if let (Some(agent_id), Some(child_path)) = ( - env.payload.get("agent_id").and_then(Value::as_str), - env.payload - .get("agent_transcript_path") - .and_then(Value::as_str), + fields.agent_id.as_deref(), + fields.agent_transcript_path.as_deref(), ) { - let child_through = env - .payload - .get("_bt_claude_transcript_mirrors") + let child_through = fields + .claude_mirrors + .as_ref() .and_then(|mirrors| mirrors.get(child_path)) - .and_then(|mirror| mirror.get("through")) - .and_then(Value::as_u64); + .and_then(|mirror| mirror.through); let mut child_template = template.clone(); - child_template.payload["agent_id"] = Value::String(agent_id.to_string()); - child_template.payload["agent_transcript_path"] = - Value::String(child_path.to_string()); + child_template.payload["agent_id"] = serde_json::json!(agent_id); + child_template.payload["agent_transcript_path"] = serde_json::json!(child_path); let previous = children.get(agent_id).and_then(|child| child.through); children.insert( agent_id.to_string(), ClaudeChildObservation { template: child_template, through: child_through.or(previous), + path: child_path.to_owned(), }, ); } @@ -129,6 +128,7 @@ impl Daemon { key, ClaudeTranscriptObservation { template, + path: path.to_owned(), through: through.or(previous), children, }, @@ -172,22 +172,14 @@ impl Daemon { let Some(observation) = observation else { continue; }; - let mut targets = vec![(observation.template, observation.through, "transcript_path")]; + let mut targets = vec![(observation.template, observation.through, observation.path)]; targets.extend( observation .children .into_values() - .map(|child| (child.template, child.through, "agent_transcript_path")), + .map(|child| (child.template, child.through, child.path)), ); - for (mut env, previous, field) in targets { - let Some(path) = env - .payload - .get(field) - .and_then(Value::as_str) - .map(str::to_owned) - else { - continue; - }; + for (mut env, previous, path) in targets { let Ok(metadata) = tokio::fs::metadata(&path).await else { continue; }; @@ -196,12 +188,9 @@ impl Daemon { } env.ts_ms = now_ms(); hydrate_transcript_reference(&self.data_dir, &mut env).await; - let through = env - .payload - .get("_bt_claude_transcript_mirrors") - .and_then(|mirrors| mirrors.get(&path)) - .and_then(|mirror| mirror.get("through")) - .and_then(Value::as_u64); + let through = TranscriptPayload::decode(&env.payload) + .ok() + .and_then(|fields| fields.claude_mirrors?.get(&path)?.through); if through.is_none() || through == previous { continue; } diff --git a/bt-daemon/src/server/recovery.rs b/bt-daemon/src/server/recovery.rs index 29f80235..fb1e307e 100644 --- a/bt-daemon/src/server/recovery.rs +++ b/bt-daemon/src/server/recovery.rs @@ -177,29 +177,13 @@ pub(super) async fn discover_unprocessed_journals(daemon: &Arc) -> Vec

, + #[serde(skip_serializing_if = "Option::is_none")] pub route: Option, + /// Unrelated settings and legacy fields survive route migration. + #[serde(flatten)] + pub extra: Map, } impl AgentSettings { @@ -245,6 +250,7 @@ impl AgentSettings { return Ok(Self { trace_to_braintrust: Some(settings.trace_to_braintrust), route: Some(settings.route), + ..Self::default() }); } let raw = std::fs::read_to_string(path).map_err(|error| { @@ -374,19 +380,18 @@ fn migrate_persisted_route_at( Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), Err(error) => return Err(error.into()), }; - let mut settings: Map = serde_json::from_str(&raw)?; - let Some(stored) = settings.get("route") else { + let mut settings: AgentSettings = serde_json::from_str(&raw)?; + let Some(stored) = settings.route.as_ref() else { return Ok(false); }; - let stored: SessionRoute = serde_json::from_value(stored.clone())?; // Do not overwrite a route that setup changed while resolution was in // flight. `same_route` deliberately treats a legacy route and its // stable-ID successor as equivalent for journal replay, so the // persistence guard must compare their exact serialized forms. - if serde_json::to_value(&stored)? != serde_json::to_value(legacy_route)? { + if serde_json::to_value(stored)? != serde_json::to_value(legacy_route)? { return Ok(false); } - settings.insert("route".into(), serde_json::to_value(canonical_route)?); + settings.route = Some(canonical_route.clone()); write_json_atomic(path, &settings)?; Ok(true) }) @@ -444,11 +449,11 @@ pub(crate) fn with_settings_lock( result } -fn write_json_atomic(path: &Path, settings: &Map) -> anyhow::Result<()> { +fn write_json_atomic(path: &Path, settings: &AgentSettings) -> anyhow::Result<()> { let parent = path .parent() .ok_or_else(|| anyhow::anyhow!("configuration path has no parent: {}", path.display()))?; - let mut encoded = serde_json::to_string_pretty(&Value::Object(settings.clone()))?; + let mut encoded = serde_json::to_string_pretty(settings)?; encoded.push('\n'); let mut temporary = tempfile::NamedTempFile::new_in(parent)?; // Protect the replacement before it takes the settings file's place; diff --git a/bt-daemon/src/setup/antigravity.rs b/bt-daemon/src/setup/antigravity.rs index 79dafa97..32209e74 100644 --- a/bt-daemon/src/setup/antigravity.rs +++ b/bt-daemon/src/setup/antigravity.rs @@ -5,6 +5,7 @@ use crate::agents::Antigravity; use crate::paths; use crate::setup::Setup; use anyhow::bail; +#[cfg(test)] use serde_json::Value; use std::path::Path; @@ -68,15 +69,17 @@ fn disable_at(runner: &mut dyn CommandRunner, config_dir: &Path) -> anyhow::Resu fn update_at(runner: &mut dyn CommandRunner, config_dir: &Path) -> anyhow::Result<()> { let home = home(config_dir)?; - let plugins = runner.json_in_home("agy", &["plugin", "list"], home)?; - let installed = plugins - .get("imports") - .and_then(Value::as_array) - .is_some_and(|imports| { - imports - .iter() - .any(|plugin| plugin.get("name").and_then(Value::as_str) == Some(PLUGIN)) - }); + #[derive(serde::Deserialize)] + struct PluginList { + imports: Vec, + } + #[derive(serde::Deserialize)] + struct Plugin { + name: String, + } + let plugins: PluginList = + serde_json::from_value(runner.json_in_home("agy", &["plugin", "list"], home)?)?; + let installed = plugins.imports.iter().any(|plugin| plugin.name == PLUGIN); if !installed { bail!( "Google Antigravity tracing plugin is not installed; run `bt trace install antigravity`" diff --git a/bt-daemon/src/setup/claude.rs b/bt-daemon/src/setup/claude.rs index 1212065c..54861d75 100644 --- a/bt-daemon/src/setup/claude.rs +++ b/bt-daemon/src/setup/claude.rs @@ -7,7 +7,7 @@ use crate::agents::Claude; use crate::paths; use crate::setup::Setup; use anyhow::{bail, Context}; -use serde_json::Value; +use serde::Deserialize; use std::path::Path; const MARKETPLACE_NAME: &str = "braintrust-claude-plugin"; @@ -17,35 +17,45 @@ const PLUGIN_MANIFEST: &str = plugin_source!("claude/content/plugins/trace-claude-code/.claude-plugin/plugin.json"); const LEGACY_TRACING_ENV_KEYS: [&str; 2] = ["BRAINTRUST_CC_PROJECT", "BRAINTRUST_CC_DEBUG"]; -const MARKETPLACE: Marketplace = Marketplace { +#[derive(Deserialize)] +struct MarketplaceEntry { + name: String, + source: Option, + repo: Option, +} + +#[derive(Deserialize)] +struct InstalledPlugin { + id: String, + version: Option, + enabled: Option, +} + +type InstalledPlugins = Vec; + +const MARKETPLACE: Marketplace, MarketplaceEntry> = Marketplace { program: "claude", name: MARKETPLACE_NAME, source: MARKETPLACE_SOURCE, refresh: "update", - find: |value| { - value - .as_array()? - .iter() - .find(|item| item.get("name").and_then(Value::as_str) == Some(MARKETPLACE_NAME)) - }, - is_published: |item| { - item.get("source").and_then(Value::as_str) == Some("github") - && item - .get("repo") - .and_then(Value::as_str) + find: |entries| entries.iter().find(|entry| entry.name == MARKETPLACE_NAME), + is_published: |entry| { + entry.source.as_deref() == Some("github") + && entry + .repo + .as_deref() .is_some_and(|repo| github_repo_matches(repo, MARKETPLACE_SOURCE)) }, }; -fn installed_plugin(value: &Value) -> Option<&Value> { - value - .as_array()? - .iter() - .find(|item| item.get("id").and_then(Value::as_str) == Some(PLUGIN)) +fn installed_plugin(plugins: &InstalledPlugins) -> Option<&InstalledPlugin> { + plugins.iter().find(|plugin| plugin.id == PLUGIN) } -fn list_plugins(runner: &mut dyn CommandRunner) -> anyhow::Result { - runner.json("claude", &["plugin", "list", "--json"]) +fn list_plugins(runner: &mut dyn CommandRunner) -> anyhow::Result { + Ok(serde_json::from_value( + runner.json("claude", &["plugin", "list", "--json"])?, + )?) } impl Setup for Claude { @@ -74,11 +84,7 @@ impl Setup for Claude { installed_json_version_is_older( "claude", &["plugin", "list", "--json"], - |value| { - installed_plugin(value) - .and_then(|plugin| plugin.get("version")) - .and_then(Value::as_str) - }, + |value| installed_plugin(value).and_then(|plugin| plugin.version.as_deref()), PLUGIN_MANIFEST, ) } @@ -94,7 +100,7 @@ fn install(runner: &mut dyn CommandRunner) -> anyhow::Result<()> { None => runner.run("claude", &["plugin", "install", PLUGIN])?, Some(plugin) => { runner.run("claude", &["plugin", "update", PLUGIN])?; - if plugin.get("enabled").and_then(Value::as_bool) == Some(false) { + if plugin.enabled == Some(false) { runner.run("claude", &["plugin", "enable", PLUGIN])?; } } @@ -112,9 +118,13 @@ fn legacy_tracing_env_keys(path: &Path) -> anyhow::Result> { .with_context(|| format!("failed to inspect Claude settings: {}", path.display())); } }; - let value: Value = serde_json::from_slice(&raw) + #[derive(Deserialize)] + struct Settings { + env: Option>, + } + let settings: Settings = serde_json::from_slice(&raw) .with_context(|| format!("Claude settings are not valid JSON: {}", path.display()))?; - let env = value.get("env").and_then(Value::as_object); + let env = settings.env.as_ref(); Ok(LEGACY_TRACING_ENV_KEYS .into_iter() .filter(|key| env.is_some_and(|env| env.contains_key(*key))) diff --git a/bt-daemon/src/setup/codex.rs b/bt-daemon/src/setup/codex.rs index 576ccf3e..6ab09f92 100644 --- a/bt-daemon/src/setup/codex.rs +++ b/bt-daemon/src/setup/codex.rs @@ -5,7 +5,7 @@ use super::common::{ }; use crate::agents::Codex; use crate::setup::Setup; -use serde_json::Value; +use serde::Deserialize; const MARKETPLACE_NAME: &str = "braintrust-codex-plugins"; const MARKETPLACE_SOURCE: &str = "braintrustdata/braintrust-codex-plugin"; @@ -22,36 +22,65 @@ const LIST_PLUGINS_ARGS: &[&str] = &[ const PLUGIN_MANIFEST: &str = plugin_source!("codex/content/plugins/trace-codex/.codex-plugin/plugin.json"); -const MARKETPLACE: Marketplace = Marketplace { +#[derive(Deserialize)] +struct MarketplaceList { + marketplaces: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct MarketplaceEntry { + name: String, + marketplace_source: Option, +} + +#[derive(Deserialize)] +struct MarketplaceSource { + source: Option, +} + +#[derive(Deserialize)] +struct InstalledPlugins { + installed: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct InstalledPlugin { + plugin_id: String, + version: Option, +} + +const MARKETPLACE: Marketplace = Marketplace { program: "codex", name: MARKETPLACE_NAME, source: MARKETPLACE_SOURCE, refresh: "upgrade", - find: |value| { - value - .get("marketplaces") - .and_then(Value::as_array)? + find: |list| { + list.marketplaces .iter() - .find(|item| item.get("name").and_then(Value::as_str) == Some(MARKETPLACE_NAME)) + .find(|entry| entry.name == MARKETPLACE_NAME) }, - is_published: |item| { - item.get("marketplaceSource") - .and_then(|source| source.get("source")) - .and_then(Value::as_str) + is_published: |entry| { + entry + .marketplace_source + .as_ref() + .and_then(|source| source.source.as_deref()) .is_some_and(|source| github_repo_matches(source, MARKETPLACE_SOURCE)) }, }; -fn installed_plugin(value: &Value) -> Option<&Value> { - value - .get("installed") - .and_then(Value::as_array)? +fn installed_plugin(plugins: &InstalledPlugins) -> Option<&InstalledPlugin> { + plugins + .installed .iter() - .find(|item| item.get("pluginId").and_then(Value::as_str) == Some(PLUGIN)) + .find(|plugin| plugin.plugin_id == PLUGIN) } -fn list_plugins(runner: &mut dyn CommandRunner) -> anyhow::Result { - runner.json("codex", LIST_PLUGINS_ARGS) +fn list_plugins(runner: &mut dyn CommandRunner) -> anyhow::Result { + Ok(serde_json::from_value( + runner.json("codex", LIST_PLUGINS_ARGS)?, + )?) } impl Setup for Codex { @@ -83,11 +112,7 @@ impl Setup for Codex { installed_json_version_is_older( "codex", LIST_PLUGINS_ARGS, - |value| { - installed_plugin(value) - .and_then(|plugin| plugin.get("version")) - .and_then(Value::as_str) - }, + |value| installed_plugin(value).and_then(|plugin| plugin.version.as_deref()), PLUGIN_MANIFEST, ) } diff --git a/bt-daemon/src/setup/common.rs b/bt-daemon/src/setup/common.rs index 78b47f17..887e86dc 100644 --- a/bt-daemon/src/setup/common.rs +++ b/bt-daemon/src/setup/common.rs @@ -85,21 +85,24 @@ impl CommandRunner for SystemCommandRunner { /// An agent marketplace that distributes a Braintrust plugin. Codex and /// Claude Code share this flow; they differ in verbs and listing shapes. -pub(super) struct Marketplace { +pub(super) struct Marketplace { pub program: &'static str, pub name: &'static str, pub source: &'static str, /// The subcommand that refreshes a configured marketplace. pub refresh: &'static str, /// Find this marketplace in ` plugin marketplace list --json`. - pub find: fn(&Value) -> Option<&Value>, + pub find: fn(&List) -> Option<&Entry>, /// Whether a configured marketplace points at the published source. - pub is_published: fn(&Value) -> bool, + pub is_published: fn(&Entry) -> bool, } -impl Marketplace { - fn list(&self, runner: &mut dyn CommandRunner) -> anyhow::Result { - runner.json(self.program, &["plugin", "marketplace", "list", "--json"]) +impl Marketplace { + fn list(&self, runner: &mut dyn CommandRunner) -> anyhow::Result { + Ok(serde_json::from_value(runner.json( + self.program, + &["plugin", "marketplace", "list", "--json"], + )?)?) } /// Configure the published marketplace, refreshing it when it is already @@ -169,11 +172,8 @@ pub(super) fn github_repo_matches(source: &str, expected: &str) -> bool { } pub(super) fn package_version(manifest: &str) -> anyhow::Result { - let manifest = serde_json::from_str::(manifest)?; - manifest - .get("version") - .and_then(Value::as_str) - .map(str::to_owned) + serde_json::from_str::(manifest)? + .version .ok_or_else(|| anyhow::anyhow!("package manifest has no string version")) } @@ -204,10 +204,10 @@ pub(super) fn version_is_older(installed: &str, expected: &str) -> bool { /// Whether the plugin version an agent CLI reports as JSON is older than the /// version in `manifest`. Any failure to determine it reports `false`. -pub(super) fn installed_json_version_is_older( +pub(super) fn installed_json_version_is_older( program: &str, args: &[&str], - find_version: impl Fn(&Value) -> Option<&str>, + find_version: impl Fn(&List) -> Option<&str>, manifest: &str, ) -> bool { let Ok(expected) = package_version(manifest) else { @@ -222,7 +222,7 @@ pub(super) fn installed_json_version_is_older( if !output.status.success() { return false; } - serde_json::from_slice::(&output.stdout) + serde_json::from_slice::(&output.stdout) .ok() .and_then(|value| find_version(&value).map(str::to_owned)) .is_some_and(|installed| version_is_older(&installed, &expected)) @@ -256,25 +256,50 @@ pub(super) fn edit_object( access: FileAccess, mut edit: impl FnMut(&mut Map, bool) -> anyhow::Result<()>, ) -> anyhow::Result<()> { + edit_json(path, access, |config, existed| edit(config, existed)) +} + +/// Edit a typed agent configuration while preserving its extension fields. +pub(super) fn edit_json( + path: &Path, + access: FileAccess, + mut edit: impl FnMut(&mut T, bool) -> anyhow::Result<()>, +) -> anyhow::Result<()> +where + T: serde::de::DeserializeOwned + serde::Serialize + Default + PartialEq + Clone, +{ if !path.exists() { - let mut probe = Map::new(); + let mut probe = T::default(); edit(&mut probe, false)?; - if probe.is_empty() { + if probe == T::default() { return Ok(()); } } crate::settings::with_settings_lock(path, || { let existed = path.exists(); - let mut object = load_object(path)?; - let original = object.clone(); - edit(&mut object, existed)?; - if object != original { - write_object_atomic_unlocked(path, object, access)?; + let mut config = load_json::(path)?; + let original = config.clone(); + edit(&mut config, existed)?; + if config != original { + write_json_atomic_unlocked(path, &config, access)?; } Ok(()) }) } +pub(super) fn load_json( + path: &Path, +) -> anyhow::Result { + match std::fs::read(path) { + Ok(raw) => serde_json::from_slice(&raw) + .with_context(|| format!("invalid JSON configuration: {}", path.display())), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(T::default()), + Err(error) => { + Err(error).with_context(|| format!("failed to read configuration: {}", path.display())) + } + } +} + /// Whether an atomic replacement keeps the directory's inherited access or is /// restricted to the current user before it is written and published. #[derive(Clone, Copy)] @@ -283,6 +308,7 @@ pub(super) enum FileAccess { OwnerOnly, } +#[cfg(test)] pub(super) fn write_object_atomic_with( path: &Path, object: Map, @@ -291,6 +317,7 @@ pub(super) fn write_object_atomic_with( crate::settings::with_settings_lock(path, || write_object_atomic_unlocked(path, object, access)) } +#[cfg(test)] pub(super) fn write_object_atomic_unlocked( path: &Path, object: Map, diff --git a/bt-daemon/src/setup/cursor/hooks.rs b/bt-daemon/src/setup/cursor/hooks.rs index a8d37739..9a4b06c8 100644 --- a/bt-daemon/src/setup/cursor/hooks.rs +++ b/bt-daemon/src/setup/cursor/hooks.rs @@ -5,8 +5,14 @@ //! marked with their process identity, which later runs remove once that //! process has exited. -use crate::setup::common::{edit_object, load_object, FileAccess}; +use crate::agents::schema::{ + CursorCommandHook, CursorHookEntries, CursorHookEntry, CursorHooks, HookFile, +}; +#[cfg(test)] +use crate::setup::common::load_object; +use crate::setup::common::{edit_json, load_json, FileAccess}; use crate::wire::ProcessIdentity; +#[cfg(test)] use serde_json::{Map, Value}; use std::path::{Path, PathBuf}; @@ -62,15 +68,10 @@ fn capture_specs_from_manifest( manifest: &str, windows: bool, ) -> anyhow::Result> { - let manifest: Value = serde_json::from_str(manifest)?; - let hooks = manifest - .get("hooks") - .and_then(Value::as_object) - .ok_or_else(|| anyhow::anyhow!("Cursor hooks must be an object"))?; - hooks.iter().map(|(event, entries)| { - let command = entries.as_array().and_then(|entries| entries.first()) - .and_then(|entry| entry.get("command")).and_then(Value::as_str) - .ok_or_else(|| anyhow::anyhow!("Cursor hook {event:?} is missing its command"))?; + let manifest: HookFile = serde_json::from_str(manifest)?; + manifest.hooks.iter().map(|(event, entries)| { + let command = &entries.first() + .ok_or_else(|| anyhow::anyhow!("Cursor hook {event:?} is missing its command"))?.command; let response = cursor_hook_response(event); let command = if windows { powershell_encoded_command(&format!( @@ -91,18 +92,24 @@ fn cursor_hook_response(event: &str) -> &'static str { } } +fn capture_registration(event: &str, command: &str) -> anyhow::Result { + let manifest: HookFile = serde_json::from_str(super::HOOKS_MANIFEST)?; + let matcher = manifest + .hooks + .get(event) + .and_then(|entries| entries.first()) + .and_then(|entry| entry.matcher.clone()); + Ok(CursorCommandHook::capture(command.to_owned(), matcher)) +} + +#[cfg(test)] pub(crate) fn capture_hook_entry(event: &str, command: &str) -> anyhow::Result { - let manifest: Value = serde_json::from_str(super::HOOKS_MANIFEST)?; - let mut entry = hook_entry(command); - if let Some(matcher) = manifest["hooks"][event][0]["matcher"].as_str() { - entry["matcher"] = Value::String(matcher.to_owned()); - } - Ok(entry) + Ok(serde_json::to_value(capture_registration(event, command)?)?) } /// Suppress a plugin registration only when this event has a user capture hook. pub(crate) fn user_capture_hook_is_installed_at(config_dir: &Path, event: &str) -> bool { - let Ok(config) = load_object(&config_dir.join("hooks.json")) else { + let Ok(config) = load_json::(&config_dir.join("hooks.json")) else { return false; }; let Ok(specs) = persistent_specs() else { @@ -114,15 +121,12 @@ pub(crate) fn user_capture_hook_is_installed_at(config_dir: &Path, event: &str) .is_some_and(|(event, command)| capture_entry_is_registered(&config, event, command)) } -fn capture_entry_is_registered(config: &Map, event: &str, command: &str) -> bool { - let Ok(expected) = capture_hook_entry(event, command) else { +fn capture_entry_is_registered(config: &CursorHooks, event: &str, command: &str) -> bool { + let Ok(expected) = capture_registration(event, command) else { return false; }; - config - .get("hooks") - .and_then(|hooks| hooks.get(event)) - .and_then(Value::as_array) - .is_some_and(|entries| entries.iter().any(|entry| entry == &expected)) + 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))) } fn powershell_encoded_command(script: &str) -> String { @@ -179,100 +183,70 @@ fn managed_process_identity(command: &str) -> Option { } fn remove_stale_managed_hooks( - config: &mut Map, + config: &mut CursorHooks, mut process_is_alive: impl FnMut(&ProcessIdentity) -> bool, ) { - let Some(hooks) = config.get_mut("hooks").and_then(Value::as_object_mut) else { + let Some(hooks) = &mut config.hooks else { return; }; - for entries in hooks.values_mut().filter_map(Value::as_array_mut) { - entries.retain(|entry| { - managed_process_identity( - entry - .get("command") - .and_then(Value::as_str) - .unwrap_or_default(), - ) - .is_none_or(|identity| process_is_alive(&identity)) - }); + 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)) + }); + } } } +#[cfg(test)] fn hook_entry(command: &str) -> Value { - serde_json::json!({ - "command": command, - "timeout": 10, - "failClosed": false - }) + serde_json::json!(CursorCommandHook::capture(command.to_owned(), None)) } -/// Add (`enable`) or remove the entries for `specs`, preserving every other -/// hook. Persistent entries are replaced by ownership marker; managed entries -/// are replaced by exact command. +/// Add or remove owned entries while preserving unrelated native definitions. fn apply_specs( - config: &mut Map, + config: &mut CursorHooks, path: &Path, specs: &[(String, String)], enable: bool, ) -> anyhow::Result<()> { if enable { - config - .entry("version") - .or_insert_with(|| Value::Number(1.into())); + config.version.get_or_insert(1); } - - if enable || config.contains_key("hooks") { - let hooks = config - .entry("hooks") - .or_insert_with(|| Value::Object(Map::new())) - .as_object_mut() - .ok_or_else(|| { - anyhow::anyhow!("Cursor hooks must be a JSON object: {}", path.display()) - })?; - + 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().filter_map(Value::as_array_mut) { - entries.retain(|entry| { - !entry - .get("command") - .and_then(Value::as_str) - .is_some_and(is_persistent_command) - }); + for entries in hooks.values_mut() { + if let CursorHookEntries::Entries(entries) = entries { + entries.retain(|entry| !entry.command().is_some_and(is_persistent_command)); + } } } - for (event, command) in specs { - let Some(entries) = hooks.get_mut(event) else { - if enable { - let entry = if persistent { - capture_hook_entry(event, command)? - } else { - hook_entry(command) - }; - hooks.insert(event.clone(), Value::Array(vec![entry])); - } + if !enable && !hooks.contains_key(event) { continue; - }; - let entries = entries.as_array_mut().ok_or_else(|| { - anyhow::anyhow!( + } + 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.get("command").and_then(Value::as_str) != Some(command.as_str()) - }); + ); + }; + entries.retain(|entry| entry.command() != Some(command.as_str())); if enable { - entries.push(if persistent { - capture_hook_entry(event, command)? + entries.push(CursorHookEntry::Command(if persistent { + capture_registration(event, command)? } else { - hook_entry(command) - }); + CursorCommandHook::capture(command.clone(), None) + })); } } } - Ok(()) } @@ -283,7 +257,7 @@ pub(super) fn validate( enable: bool, ) -> anyhow::Result<()> { let path = config_dir.join("hooks.json"); - let mut config = load_object(&path)?; + let mut config = load_json::(&path)?; apply_specs(&mut config, &path, specs, enable) } @@ -293,7 +267,7 @@ pub(super) fn apply( enable: bool, ) -> anyhow::Result<()> { let path = config_dir.join("hooks.json"); - edit_object(&path, FileAccess::Inherited, |config, _| { + edit_json(&path, FileAccess::Inherited, |config, _| { apply_specs(config, &path, specs, enable) }) } @@ -301,7 +275,7 @@ pub(super) fn apply( /// Whether every persistent capture entry is registered. pub(crate) fn capture_hooks_are_installed_at(config_dir: &Path) -> bool { let path = config_dir.join("hooks.json"); - let Ok(config) = load_object(&path) else { + let Ok(config) = load_json::(&path) else { return false; }; let Ok(specs) = persistent_specs() else { @@ -335,7 +309,7 @@ impl CursorManagedHooks { ); let specs = specs(&marker, cfg!(windows)); let path = config_dir.join("hooks.json"); - edit_object(&path, FileAccess::Inherited, |config, _| { + edit_json(&path, FileAccess::Inherited, |config, _| { remove_stale_managed_hooks(config, crate::process::process_is_alive); apply_specs(config, &path, &specs, true) })?; diff --git a/bt-daemon/src/setup/cursor/mod.rs b/bt-daemon/src/setup/cursor/mod.rs index 030a2708..e197cadc 100644 --- a/bt-daemon/src/setup/cursor/mod.rs +++ b/bt-daemon/src/setup/cursor/mod.rs @@ -11,6 +11,7 @@ pub(crate) use hooks::{ #[cfg(test)] pub(crate) use hooks::{capture_hook_entry, persistent_specs}; +use crate::agents::schema::PluginManifest; use crate::agents::Cursor; use crate::paths; use crate::setup::common::{ @@ -18,7 +19,6 @@ use crate::setup::common::{ }; use crate::setup::Setup; use anyhow::{bail, Context}; -use serde_json::Value; use std::path::Path; const PLUGIN_NAME: &str = "trace-cursor"; @@ -58,23 +58,22 @@ fn write_embedded_plugin_at(plugin: &Path) -> anyhow::Result<()> { Ok(()) } -fn installed_manifest_at(plugin: &Path) -> Option { +fn installed_manifest_at(plugin: &Path) -> Option { let raw = std::fs::read(plugin.join(".cursor-plugin/plugin.json")).ok()?; serde_json::from_slice(&raw).ok() } -fn is_ours(manifest: &Value) -> bool { - matches!( - manifest.get("name").and_then(Value::as_str), - Some("braintrust" | PLUGIN_NAME) - ) && manifest - .get("repository") - .and_then(Value::as_str) - .is_some_and(|repo| { - github_repo_matches(repo, MONOREPO_SOURCE) - || github_repo_matches(repo, PLUGIN_SOURCE) - || github_repo_matches(repo, LEGACY_PLUGIN_SOURCE) - }) +fn is_ours(manifest: &PluginManifest) -> bool { + matches!(manifest.name.as_deref(), Some("braintrust" | PLUGIN_NAME)) + && manifest + .repository + .as_ref() + .and_then(|repository| repository.url()) + .is_some_and(|repo| { + github_repo_matches(repo, MONOREPO_SOURCE) + || github_repo_matches(repo, PLUGIN_SOURCE) + || github_repo_matches(repo, LEGACY_PLUGIN_SOURCE) + }) } /// Fail unless the plugin at `plugin_dir` is the Braintrust plugin, so setup @@ -82,7 +81,7 @@ fn is_ours(manifest: &Value) -> bool { /// `unrecognized` describes a missing or unreadable manifest and `different` /// a manifest for another plugin. fn ensure_ours(plugin_dir: &Path, unrecognized: &str, different: &str) -> anyhow::Result<()> { - let installed: Value = std::fs::read(plugin_dir.join(".cursor-plugin/plugin.json")) + let installed: PluginManifest = std::fs::read(plugin_dir.join(".cursor-plugin/plugin.json")) .context(unrecognized.to_owned()) .and_then(|raw| { serde_json::from_slice(&raw).context("installed plugin manifest is invalid") @@ -122,7 +121,7 @@ impl Setup for Cursor { return false; } let expected = package_version(PLUGIN_MANIFEST).ok(); - let installed = installed_manifest.get("version").and_then(Value::as_str); + let installed = installed_manifest.version.as_deref(); installed .zip(expected.as_deref()) .is_some_and(|(installed, expected)| version_is_older(installed, expected)) @@ -208,12 +207,22 @@ fn install_plugin_at(runner: &mut dyn CommandRunner, plugin_dir: &Path) -> anyho // distribution, including components added after this bt build shipped. for (relative, field) in [("hooks/hooks.json", "hooks"), ("mcp.json", "mcpServers")] { let path = staged_plugin.join(relative); - let manifest: Value = serde_json::from_slice( + #[derive(serde::Deserialize)] + struct Components { + hooks: Option>, + #[serde(rename = "mcpServers")] + mcp_servers: Option>, + } + let manifest: Components = serde_json::from_slice( &std::fs::read(&path) .with_context(|| format!("published Cursor plugin is missing {relative}"))?, ) .with_context(|| format!("published Cursor plugin has invalid {relative}"))?; - if !manifest.get(field).is_some_and(Value::is_object) { + let present = match field { + "hooks" => manifest.hooks.is_some(), + _ => manifest.mcp_servers.is_some(), + }; + if !present { bail!("published Cursor plugin {relative} must contain a {field} object"); } } diff --git a/bt-daemon/src/setup/cursor/tests.rs b/bt-daemon/src/setup/cursor/tests.rs index e9dd426b..24db2dbc 100644 --- a/bt-daemon/src/setup/cursor/tests.rs +++ b/bt-daemon/src/setup/cursor/tests.rs @@ -1,5 +1,6 @@ use super::*; use serde_json::json; +use serde_json::Value; use std::collections::BTreeMap; /// Models a distribution newer than this bt build, with OAuth MCP and an diff --git a/bt-daemon/src/setup/grok.rs b/bt-daemon/src/setup/grok.rs index a3c42275..14a5662e 100644 --- a/bt-daemon/src/setup/grok.rs +++ b/bt-daemon/src/setup/grok.rs @@ -4,26 +4,32 @@ use super::common::{github_repo_matches, CommandRunner}; use crate::agents::Grok; use crate::setup::Setup; use anyhow::bail; -use serde_json::Value; +use serde::Deserialize; const PLUGIN: &str = "trace-grok"; const PLUGIN_SOURCE: &str = "braintrustdata/braintrust-grok-plugin"; -fn installed_plugin(value: &Value) -> Option<&Value> { - value - .as_array()? - .iter() - .find(|item| item.get("name").and_then(Value::as_str) == Some(PLUGIN)) +#[derive(Deserialize)] +struct InstalledPlugin { + name: String, + source: Option, } -fn is_published(item: &Value) -> bool { - item.get("source") - .and_then(Value::as_str) +fn installed_plugin(plugins: &[InstalledPlugin]) -> Option<&InstalledPlugin> { + plugins.iter().find(|plugin| plugin.name == PLUGIN) +} + +fn is_published(plugin: &InstalledPlugin) -> bool { + plugin + .source + .as_deref() .is_some_and(|source| github_repo_matches(source, PLUGIN_SOURCE)) } -fn list_plugins(runner: &mut dyn CommandRunner) -> anyhow::Result { - runner.json("grok", &["plugin", "list", "--json"]) +fn list_plugins(runner: &mut dyn CommandRunner) -> anyhow::Result> { + Ok(serde_json::from_value( + runner.json("grok", &["plugin", "list", "--json"])?, + )?) } impl Setup for Grok { diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index 36e8f410..43cd3175 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -16,12 +16,13 @@ pub(crate) mod pi; use crate::agents::{registrar, Agent}; use crate::paths; +use crate::settings::AgentSettings; use crate::trace_command::{SettingsScope, SetupAgent, SetupArgs}; use crate::wire::SessionRoute; use crate::TraceCommandOutput; use anyhow::Context; pub(crate) use common::CommandRunner; -use common::{load_object, write_object_atomic_with, FileAccess, SystemCommandRunner}; +use common::{load_object, FileAccess, SystemCommandRunner}; use serde_json::Value; use std::path::{Path, PathBuf}; @@ -366,38 +367,35 @@ fn write_tracing_at( enabled: bool, replace_plugins: bool, ) -> anyhow::Result<()> { - let mut settings = load_object(path)?; + let raw = load_object(path)?; + #[derive(serde::Deserialize, Default)] + struct LegacyFields { + additional_metadata: Option, + tags: Option>, + } + let legacy: LegacyFields = serde_json::from_value(Value::Object(raw.clone()))?; + let mut settings: AgentSettings = serde_json::from_value(Value::Object(raw))?; + let stored = settings.route.as_ref(); if route.additional_metadata.is_none() { - route.additional_metadata = settings - .get("route") - .and_then(|route| route.get("additional_metadata")) - .or_else(|| settings.get("additional_metadata")) + route.additional_metadata = stored + .and_then(|route| route.additional_metadata.as_ref()) + .or(legacy.additional_metadata.as_ref()) .filter(|metadata| metadata.is_object()) .cloned(); } if route.tags.is_empty() { - route.tags = settings - .get("route") - .and_then(|route| route.get("tags")) - .or_else(|| settings.get("tags")) - .and_then(Value::as_array) - .map(|tags| { - tags.iter() - .filter_map(Value::as_str) - .map(ToOwned::to_owned) - .collect() - }) + route.tags = stored + .map(|route| route.tags.clone()) + .or(legacy.tags) .unwrap_or_default(); } if route.span_plugins.is_empty() && !replace_plugins { - route.span_plugins = settings - .get("route") - .and_then(|route| route.get("span_plugins")) - .and_then(|plugins| serde_json::from_value(plugins.clone()).ok()) + route.span_plugins = stored + .map(|route| route.span_plugins.clone()) .unwrap_or_default(); } - settings.insert("trace_to_braintrust".into(), Value::Bool(enabled)); - settings.insert("route".into(), serde_json::to_value(route)?); + settings.trace_to_braintrust = Some(enabled); + settings.route = Some(route); for key in [ "traceToBraintrust", "profile", @@ -410,10 +408,12 @@ fn write_tracing_at( "additional_metadata", "tags", ] { - settings.remove(key); + settings.extra.remove(key); } - write_object_atomic_with(path, settings, FileAccess::OwnerOnly) - .with_context(|| format!("failed to write agent settings: {}", path.display())) + crate::settings::with_settings_lock(path, || { + common::write_json_atomic_unlocked(path, &settings, FileAccess::OwnerOnly) + }) + .with_context(|| format!("failed to write agent settings: {}", path.display())) } fn remove_tracing_settings(path: &Path) -> anyhow::Result<()> { @@ -772,4 +772,23 @@ mod tests { serde_json::json!(["first.mjs", "second.mjs"]) ); } + + #[test] + fn typed_settings_keep_disable_and_explicit_plugin_replacement() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("braintrust.json"); + std::fs::write( + &path, + r#"{"route":{"span_plugins":["old.mjs"],"tags":["saved"]},"custom":1}"#, + ) + .unwrap(); + write_tracing_at(&path, SessionRoute::default(), false, true).unwrap(); + let settings: AgentSettings = + serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(settings.trace_to_braintrust, Some(false)); + let route = settings.route.unwrap(); + assert!(route.span_plugins.is_empty()); + assert!(route.tags.contains("saved")); + assert_eq!(settings.extra["custom"], 1); + } } diff --git a/bt-daemon/src/setup/muse.rs b/bt-daemon/src/setup/muse.rs index 0caaabae..5976c248 100644 --- a/bt-daemon/src/setup/muse.rs +++ b/bt-daemon/src/setup/muse.rs @@ -3,11 +3,11 @@ use super::common::{write_json_atomic_unlocked, CommandRunner, FileAccess}; use super::Setup; use crate::agents::Muse; +use crate::json::Field; use crate::muse::config::{ inspect_hook_file, HookFileInspection, HookOverlay, MuseSettings, HOOK_COMMAND as MUSE_HOOK_COMMAND, }; -use crate::muse::field::Field; use crate::paths; use anyhow::{bail, Context}; use fs2::FileExt; diff --git a/bt-daemon/src/setup/opencode.rs b/bt-daemon/src/setup/opencode.rs index acab192c..b472eb94 100644 --- a/bt-daemon/src/setup/opencode.rs +++ b/bt-daemon/src/setup/opencode.rs @@ -1,12 +1,14 @@ //! OpenCode: the npm plugin listed in `opencode.json`. OpenCode installs it //! from that entry, so no OpenCode CLI is involved. -use super::common::{edit_object, npm_major_spec, plugin_source, CommandRunner, FileAccess}; +use super::common::{edit_json, npm_major_spec, plugin_source, CommandRunner, FileAccess}; +use crate::agents::schema::{OpenCodeConfig, OpenCodePlugin}; use crate::agents::OpenCode; use crate::paths; use crate::setup::Setup; use anyhow::bail; -use serde_json::{Map, Value}; +#[cfg(test)] +use serde_json::Value; use std::path::{Path, PathBuf}; const PACKAGE: &str = "@braintrust/trace-opencode"; @@ -27,8 +29,8 @@ fn config_path() -> PathBuf { .join("opencode.json") } -fn is_ours(plugin: &Value) -> bool { - plugin.as_str().is_some_and(|plugin| { +fn is_ours(plugin: &OpenCodePlugin) -> bool { + plugin.package().is_some_and(|plugin| { plugin == PACKAGE || plugin .strip_prefix(PACKAGE) @@ -36,56 +38,50 @@ fn is_ours(plugin: &Value) -> bool { }) } -fn plugin_list<'a>( - config: &'a mut Map, - path: &Path, -) -> anyhow::Result<&'a mut Vec> { - config - .entry("plugin") - .or_insert_with(|| Value::Array(Vec::new())) - .as_array_mut() - .ok_or_else(|| { - anyhow::anyhow!( - "OpenCode `plugin` config must be an array: {}", - path.display() - ) - }) -} - /// Replace any entry for the plugin with the bundled major version. -fn pin_plugin(plugins: &mut Vec) -> anyhow::Result<()> { +fn pin_plugin(plugins: &mut Vec) -> anyhow::Result<()> { plugins.retain(|plugin| !is_ours(plugin)); - plugins.push(Value::String(plugin_spec()?)); + plugins.push(OpenCodePlugin::Package(plugin_spec()?)); Ok(()) } fn enable_at(path: &Path) -> anyhow::Result<()> { - edit_object(path, FileAccess::Inherited, |config, _| { - pin_plugin(plugin_list(config, path)?) - }) + edit_json( + path, + FileAccess::Inherited, + |config: &mut OpenCodeConfig, _| pin_plugin(config.plugin.get_or_insert_with(Vec::new)), + ) } fn update_at(path: &Path) -> anyhow::Result<()> { - edit_object(path, FileAccess::Inherited, |config, existed| { - if !existed { - bail!(NOT_INSTALLED); - } - let plugins = config - .get_mut("plugin") - .and_then(Value::as_array_mut) - .filter(|plugins| plugins.iter().any(is_ours)) - .ok_or_else(|| anyhow::anyhow!(NOT_INSTALLED))?; - pin_plugin(plugins) - }) + edit_json( + path, + FileAccess::Inherited, + |config: &mut OpenCodeConfig, existed| { + 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) + }, + ) } fn disable_at(path: &Path) -> anyhow::Result<()> { - edit_object(path, FileAccess::Inherited, |config, _| { - if config.contains_key("plugin") { - plugin_list(config, path)?.retain(|plugin| !is_ours(plugin)); - } - Ok(()) - }) + edit_json( + path, + FileAccess::Inherited, + |config: &mut OpenCodeConfig, _| { + if let Some(plugins) = &mut config.plugin { + plugins.retain(|plugin| !is_ours(plugin)); + } + Ok(()) + }, + ) } impl Setup for OpenCode { @@ -106,15 +102,15 @@ impl Setup for OpenCode { let Ok(raw) = std::fs::read(config_path()) else { return false; }; - let Ok(config) = serde_json::from_slice::(&raw) else { + let Ok(config) = serde_json::from_slice::(&raw) else { return false; }; let expected = plugin_spec().ok(); config - .get("plugin") - .and_then(Value::as_array) + .plugin + .as_ref() .and_then(|plugins| plugins.iter().find(|plugin| is_ours(plugin))) - .and_then(Value::as_str) + .and_then(OpenCodePlugin::package) .is_some_and(|plugin| Some(plugin) != expected.as_deref()) } } diff --git a/bt-daemon/src/sink/braintrust.rs b/bt-daemon/src/sink/braintrust.rs index 547eaa0a..fb739f61 100644 --- a/bt-daemon/src/sink/braintrust.rs +++ b/bt-daemon/src/sink/braintrust.rs @@ -400,7 +400,8 @@ impl BraintrustSink { format!("{api}/{}/{}", creds.org_id, attachment.digest).as_bytes(), ) .to_string(); - let reference = json!({"type":"braintrust_attachment", "key":key, "filename":attachment.filename, "content_type":attachment.content_type}); + let reference = + crate::attachments::AttachmentReference::uploaded(key.clone(), attachment); if !uploads.completed.contains(&key) { uploads .backend @@ -427,7 +428,7 @@ impl BraintrustSink { if let Some(metadata) = metadata.as_object_mut() { metadata.insert( "braintrust.attachments".into(), - Value::Array(references.into_values().collect()), + json!(references.into_values().collect::>()), ); } row.attachments.clear(); diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 7a9eb9a8..816ca498 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -1705,6 +1705,7 @@ mod tests { let settings = crate::settings::AgentSettings { trace_to_braintrust: Some(true), route: None, + ..Default::default() }; let error = run_hook_command(hook_args(), &host, settings) .await @@ -1743,6 +1744,7 @@ mod tests { let settings = crate::settings::AgentSettings { trace_to_braintrust: Some(true), route: None, + ..Default::default() }; let result = tokio::time::timeout( Duration::from_secs(1), @@ -1758,6 +1760,7 @@ mod tests { let settings = crate::settings::AgentSettings { trace_to_braintrust: Some(false), route: None, + ..Default::default() }; run_hook_command(hook_args(), &test_host(Arc::new(PanicHost)), settings) .await diff --git a/bt-daemon/src/transcript_import/antigravity.rs b/bt-daemon/src/transcript_import/antigravity.rs index 85cb5e48..71d1689a 100644 --- a/bt-daemon/src/transcript_import/antigravity.rs +++ b/bt-daemon/src/transcript_import/antigravity.rs @@ -2,8 +2,10 @@ use super::{ envelope, validate_session_id, IncrementalRecords, TailSession, TranscriptImport, TranscriptLayout, }; +use crate::agents::antigravity::schema::TranscriptRecord as AntigravityRecord; use crate::wire::Envelope; use anyhow::bail; +use serde::Deserialize; use serde_json::{json, Value}; use std::collections::VecDeque; use std::path::{Path, PathBuf}; @@ -117,20 +119,20 @@ pub(super) fn envelopes( if records.is_empty() { bail!("Antigravity transcript {} is empty", path.display()); } - let (start_ms, end_ms) = timestamp_bounds_created(records); + let records = records + .iter() + .map(AntigravityRecord::deserialize) + .collect::, _>>()?; + let (start_ms, end_ms) = timestamp_bounds_created(&records); let transcript_path = path.to_string_lossy().into_owned(); let mut events = Vec::new(); let mut planned_calls = VecDeque::new(); let mut invocation_num = 0i64; for (index, record) in records.iter().enumerate() { - let record_type = record.get("type").and_then(Value::as_str); - let step = record - .get("step_index") - .or_else(|| record.get("stepIndex")) - .and_then(Value::as_i64) - .unwrap_or(index as i64); + 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); - if record_type == Some("PLANNER_RESPONSE") { + if record_type == "PLANNER_RESPONSE" { let before = index .checked_sub(1) .and_then(|index| record_end_offsets.get(index)) @@ -164,11 +166,7 @@ pub(super) fn envelopes( )); invocation_num += 1; } - if let Some(calls) = record - .get("tool_calls") - .or_else(|| record.get("toolCalls")) - .and_then(Value::as_array) - { + if let Some(calls) = &record.tool_calls { planned_calls.extend(calls.iter().cloned()); } if !is_tool_result(record) { @@ -176,7 +174,7 @@ pub(super) fn envelopes( } let mut extra = json!({"stepIdx": step}); if let Some(call) = planned_calls.pop_front() { - extra["toolCall"] = call; + extra["toolCall"] = json!(call); } if is_denied(record) { extra["toolApproval"] = json!("denied"); @@ -226,24 +224,22 @@ fn bounded_payload(session_id: &str, transcript_path: &str, through: u64, extra: payload } -fn is_denied(record: &Value) -> bool { +fn is_denied(record: &AntigravityRecord) -> bool { record - .get("content") + .content + .as_ref() .and_then(Value::as_str) .is_some_and(|content| content.to_ascii_lowercase().contains("denied")) } -fn is_tool_result(record: &Value) -> bool { +fn is_tool_result(record: &AntigravityRecord) -> bool { !matches!( - record.get("type").and_then(Value::as_str), - Some("USER_INPUT" | "PLANNER_RESPONSE" | "CONVERSATION_HISTORY" | "CHECKPOINT") - ) && record - .get("step_index") - .or_else(|| record.get("stepIndex")) - .is_some() + record.kind.as_str(), + "USER_INPUT" | "PLANNER_RESPONSE" | "CONVERSATION_HISTORY" | "CHECKPOINT" + ) && record.step_index.is_some() } -fn timestamp_bounds_created(records: &[Value]) -> (i64, i64) { +fn timestamp_bounds_created(records: &[AntigravityRecord]) -> (i64, i64) { let timestamps = records.iter().filter_map(created_at_ms).collect::>(); timestamps .iter() @@ -257,11 +253,10 @@ fn timestamp_bounds_created(records: &[Value]) -> (i64, i64) { }) } -fn created_at_ms(record: &Value) -> Option { +fn created_at_ms(record: &AntigravityRecord) -> Option { record - .get("created_at") - .or_else(|| record.get("createdAt")) - .and_then(Value::as_str) + .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_import/cursor.rs b/bt-daemon/src/transcript_import/cursor.rs index 508ad2b4..841a639d 100644 --- a/bt-daemon/src/transcript_import/cursor.rs +++ b/bt-daemon/src/transcript_import/cursor.rs @@ -2,9 +2,11 @@ use super::{ envelope, validate_session_id, IncrementalRecords, TailSession, TranscriptImport, TranscriptLayout, }; +use crate::agents::cursor::schema::TranscriptRecord; use crate::translate::cursor::{IMPORT_CHECKPOINT, IMPORT_START, IMPORT_STOP}; use crate::wire::Envelope; use anyhow::{bail, Context}; +use serde::Deserialize; use serde_json::{json, Value}; use std::io::Write; use std::path::{Path, PathBuf}; @@ -56,14 +58,8 @@ fn filename_matches(path: &Path, session_id: &str) -> bool { == Some("agent-transcripts") } -fn is_conversation_record(record: &Value) -> bool { - matches!( - record.get("role").and_then(Value::as_str), - Some("user" | "assistant") - ) && record - .get("message") - .and_then(Value::as_object) - .is_some_and(|message| message.get("content").is_some()) +fn is_conversation_record(record: &TranscriptRecord) -> bool { + matches!(record, TranscriptRecord::Message { .. }) } impl TranscriptImport for crate::agents::Cursor { @@ -184,17 +180,19 @@ fn envelopes_with_snapshot( if records.is_empty() { bail!("Cursor transcript {} is empty", path.display()); } - for (index, record) in records.iter().enumerate() { - let supported = is_conversation_record(record); - let terminal = record.get("type").and_then(Value::as_str) == Some("turn_ended"); - if !supported && !terminal { - bail!( - "unsupported Cursor transcript record in {} at record {}", - path.display(), - index + 1 - ); - } - } + let records = records + .iter() + .enumerate() + .map(|(index, record)| { + TranscriptRecord::deserialize(record).with_context(|| { + format!( + "unsupported Cursor transcript record in {} at record {}", + path.display(), + index + 1 + ) + }) + }) + .collect::>>()?; // Cursor's transcript records have no per-record timestamps. File mtime // is the only available clock and is explicitly an estimate for import. @@ -212,7 +210,7 @@ fn envelopes_with_snapshot( // turn unless no conversation records follow the latest marker. let final_terminal = records .iter() - .rposition(|record| record.get("type").and_then(Value::as_str) == Some("turn_ended")) + .rposition(|record| matches!(record, TranscriptRecord::TurnEnded { .. })) .filter(|marker| !records[*marker + 1..].iter().any(is_conversation_record)) .map(|marker| &records[marker]); let boundary = |event: &str, through: Option| { @@ -225,14 +223,11 @@ fn envelopes_with_snapshot( "historical_fidelity": "user_and_assistant_text_and_terminal_status" }); if event == IMPORT_STOP { - if let Some(status) = final_terminal.and_then(|record| record.get("status")) { - payload["status"] = status.clone(); - } - if let Some(error) = final_terminal - .and_then(|record| record.get("error")) - .filter(|error| error.is_string()) - { - payload["error_message"] = error.clone(); + if let Some(TranscriptRecord::TurnEnded { status, error, .. }) = final_terminal { + payload["status"] = json!(status); + if let Some(error) = error { + payload["error_message"] = json!(error); + } } } if let Some(through) = through { diff --git a/bt-daemon/src/transcript_mirror.rs b/bt-daemon/src/transcript_mirror.rs index 2a098485..21462d81 100644 --- a/bt-daemon/src/transcript_mirror.rs +++ b/bt-daemon/src/transcript_mirror.rs @@ -20,6 +20,101 @@ 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() + } +} + +#[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) + } +} + /// 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/translate/antigravity.rs b/bt-daemon/src/translate/antigravity.rs index 589c8613..ed983c25 100644 --- a/bt-daemon/src/translate/antigravity.rs +++ b/bt-daemon/src/translate/antigravity.rs @@ -10,15 +10,49 @@ use super::tool::{with_tool_approval, without_nulls, ToolApproval}; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, }; +use crate::agents::antigravity::schema::{optional_integer, ToolCall, ToolCalls, TranscriptRecord}; +use crate::agents::usage::UsageMetrics; use crate::ids; +use crate::transcript_mirror::TranscriptPayload; use crate::wire::Envelope; use serde::{Deserialize, Serialize}; -use serde_json::{json, Map, Value}; +use serde_json::{json, Value}; use std::collections::HashMap; use std::io::{BufRead, Seek, SeekFrom}; use std::path::Path; use std::sync::Arc; +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct HookPayload { + workspace_paths: Option>, + model_name: Option, + artifact_directory_path: Option, + #[serde(default, deserialize_with = "optional_integer")] + invocation_num: Option, + #[serde(default, deserialize_with = "optional_integer")] + initial_num_steps: Option, + #[serde(default, deserialize_with = "optional_integer")] + step_idx: Option, + tool_call: Option, + error: Option, + fully_idle: Option, + tool_approval: Option, +} + +#[derive(Clone, Serialize, Deserialize)] +struct Message { + role: String, + content: Value, + #[serde(skip_serializing_if = "Option::is_none")] + tool_calls: Option, + #[serde(skip_serializing_if = "Option::is_none")] + name: Option, + step_type: String, + #[serde(skip_serializing_if = "Option::is_none")] + message_type: Option, +} + impl TranslatorFactory for crate::agents::Antigravity { fn create(&self, session_id: &str) -> Box { Box::new(AntigravityTranslator::new( @@ -58,9 +92,9 @@ struct AntigravityTranslator { turn: Option, turn_count: u32, transcript_offsets: HashMap, - records: Vec, - records_by_step: HashMap, - history: Vec, + records: Vec, + records_by_step: HashMap, + history: Vec, invocations: HashMap, tools: HashMap, last_ts_ms: i64, @@ -91,17 +125,22 @@ impl AntigravityTranslator { } } - fn ensure_root(&mut self, event: &Envelope, ctx: &SessionCtx, ops: &mut Vec) { + fn ensure_root( + &mut self, + event: &Envelope, + hook: &HookPayload, + ctx: &SessionCtx, + ops: &mut Vec, + ) { if self.root_open { return; } self.root_open = true; - let workspace = event - .payload - .get("workspacePaths") - .and_then(Value::as_array) + let workspace = hook + .workspace_paths + .as_ref() .and_then(|paths| paths.first()) - .and_then(Value::as_str); + .map(String::as_str); let mut metadata = serde_json::Map::new(); metadata.retain(|key, _| !key.starts_with("_bt_")); metadata.insert("session_id".into(), json!(ctx.session_id)); @@ -109,13 +148,13 @@ impl AntigravityTranslator { metadata.insert("source".into(), json!("antigravity")); metadata.insert("_bt_defer_root".into(), json!(true)); metadata.insert("username".into(), json!(local_username())); - if let Some(model) = string_field(&event.payload, "modelName") { + if let Some(model) = hook.model_name.clone() { metadata.insert("model".into(), json!(model)); } - if let Some(workspaces) = event.payload.get("workspacePaths") { - metadata.insert("workspace_paths".into(), workspaces.clone()); + if let Some(workspaces) = hook.workspace_paths.as_ref() { + metadata.insert("workspace_paths".into(), json!(workspaces)); } - if let Some(path) = string_field(&event.payload, "artifactDirectoryPath") { + if let Some(path) = hook.artifact_directory_path.clone() { metadata.insert("artifact_directory_path".into(), json!(path)); } if let Some(version) = &event.source_version { @@ -149,7 +188,7 @@ impl AntigravityTranslator { .entry(source.path.clone()) .or_default(); let records = if let Some(contents) = source.snapshot { - read_snapshot_records(contents, offset, source.through) + read_snapshot_records(&contents, offset, source.through) } else { read_file_records(&source.path, offset, source.through) }; @@ -158,12 +197,10 @@ impl AntigravityTranslator { } } - fn observe_record(&mut self, record: Value, ts_ms: i64, ops: &mut Vec) { + fn observe_record(&mut self, record: TranscriptRecord, ts_ms: i64, ops: &mut Vec) { let record_type = normalized_record_type(&record); - let source = string_field(&record, "source").unwrap_or_default(); - if let Some(step) = - integer_field(&record, "step_index").or_else(|| integer_field(&record, "stepIndex")) - { + let source = &record.source; + if let Some(step) = record.step_index { self.records_by_step.insert(step, record.clone()); } @@ -174,10 +211,8 @@ impl AntigravityTranslator { } if record_type == "CHECKPOINT" { - if let Some(mut message) = transcript_message(&record, &record_type, &source) { - if let Some(message) = message.as_object_mut() { - message.insert("message_type".into(), json!("compaction_summary")); - } + if let Some(mut message) = transcript_message(&record, &record_type, source) { + message.message_type = Some("compaction_summary".into()); self.history.clear(); self.history.push(message); // A checkpoint can be observed while an invocation is open. Its @@ -186,10 +221,10 @@ impl AntigravityTranslator { invocation.history_start = 0; } } - } else if let Some(message) = transcript_message(&record, &record_type, &source) { + } else if let Some(message) = transcript_message(&record, &record_type, source) { if record_type == "PLANNER_RESPONSE" { if let Some(turn) = &mut self.turn { - turn.last_output = message.get("content").cloned(); + turn.last_output = Some(message.content.clone()); } } self.history.push(message); @@ -232,8 +267,8 @@ impl AntigravityTranslator { .unwrap_or_else(|| self.session_span_id.clone()) } - fn pre_invocation(&mut self, event: &Envelope, ops: &mut Vec) { - let Some(invocation_num) = integer_field(&event.payload, "invocationNum") else { + fn pre_invocation(&mut self, event: &Envelope, hook: &HookPayload, ops: &mut Vec) { + let Some(invocation_num) = hook.invocation_num else { return; }; if self.invocations.contains_key(&invocation_num) { @@ -249,11 +284,13 @@ impl AntigravityTranslator { &self.session_id, &format!("turn:{turn_number}:invocation:{invocation_num}"), ); - let model = string_field(&event.payload, "modelName") + let model = hook + .model_name + .clone() .unwrap_or_else(|| "Antigravity model".to_string()); let mut metadata = json!({ "invocation_num": invocation_num, - "initial_num_steps": integer_field(&event.payload, "initialNumSteps"), + "initial_num_steps": hook.initial_num_steps, "turn_number": turn_number, "model": model }); @@ -266,7 +303,7 @@ impl AntigravityTranslator { name: model, span_type: SpanType::Llm, start_ms: Some(event.ts_ms), - input: Some(Value::Array(self.history.clone())), + input: Some(json!(self.history)), metadata: Some(metadata), ..Default::default() })); @@ -281,8 +318,8 @@ impl AntigravityTranslator { ); } - fn post_invocation(&mut self, event: &Envelope, ops: &mut Vec) { - let Some(invocation_num) = integer_field(&event.payload, "invocationNum") else { + fn post_invocation(&mut self, event: &Envelope, hook: &HookPayload, ops: &mut Vec) { + let Some(invocation_num) = hook.invocation_num else { return; }; let Some(invocation) = self.invocations.remove(&invocation_num) else { @@ -290,7 +327,7 @@ impl AntigravityTranslator { }; let output = self.history[invocation.history_start.min(self.history.len())..] .iter() - .filter(|message| message.get("role").and_then(Value::as_str) == Some("assistant")) + .filter(|message| message.role == "assistant") .cloned() .collect::>(); let metrics = @@ -300,23 +337,25 @@ impl AntigravityTranslator { root_span_id: self.root_span_id.clone(), parent_span_ids: vec![invocation.parent_span_id], end_ms: Some(event.ts_ms), - output: (!output.is_empty()).then_some(Value::Array(output)), + output: (!output.is_empty()).then(|| json!(output)), metrics, ..Default::default() })); } - fn pre_tool(&mut self, event: &Envelope, ops: &mut Vec) { - let Some(step) = integer_field(&event.payload, "stepIdx") else { + fn pre_tool(&mut self, event: &Envelope, hook: &HookPayload, ops: &mut Vec) { + let Some(step) = hook.step_idx else { return; }; if self.tools.contains_key(&step) { return; } let parent = self.ensure_turn(event.ts_ms, ops); - let call = event.payload.get("toolCall").unwrap_or(&Value::Null); - let name = string_field(call, "name").unwrap_or_else(|| format!("Tool step {step}")); - let input = call.get("args").cloned(); + let call = hook.tool_call.as_ref(); + let name = call + .and_then(|call| call.name.clone()) + .unwrap_or_else(|| format!("Tool step {step}")); + let input = call.and_then(|call| call.args.clone()); let span_id = ids::span_id(&self.session_id, &format!("tool:{step}")); ops.push(SpanOp::Insert(SpanRow { span_id: span_id.clone(), @@ -340,17 +379,17 @@ impl AntigravityTranslator { ); } - fn post_tool(&mut self, event: &Envelope, ops: &mut Vec) { - let Some(step) = integer_field(&event.payload, "stepIdx") else { + fn post_tool(&mut self, event: &Envelope, hook: &HookPayload, ops: &mut Vec) { + let Some(step) = hook.step_idx else { return; }; let transcript = self.records_by_step.get(&step); let mut details = transcript.map(tool_details).unwrap_or_default(); - if let Some(call) = event.payload.get("toolCall") { - if let Some(name) = string_field(call, "name") { + if let Some(call) = hook.tool_call.as_ref() { + if let Some(name) = call.name.clone() { details.name = Some(name); } - if let Some(input) = call.get("args") { + if let Some(input) = call.args.as_ref() { details.input = Some(input.clone()); } } @@ -375,7 +414,9 @@ impl AntigravityTranslator { let span_id = pending .map(|tool| tool.span_id) .unwrap_or_else(|| ids::span_id(&self.session_id, &format!("tool:{step}"))); - let error = string_field(&event.payload, "error") + let error = hook + .error + .clone() .filter(|error| !error.is_empty()) .or(details.error); if !was_pending { @@ -409,23 +450,18 @@ impl AntigravityTranslator { json!({ "step_index": step, }), - tool_approval_from_event(event).or(Some(ToolApproval::Approved)), + tool_approval_from_hook(hook).or(Some(ToolApproval::Approved)), )), error, ..Default::default() })); } - fn stop(&mut self, event: &Envelope, ops: &mut Vec) { - let error = string_field(&event.payload, "error").filter(|error| !error.is_empty()); + fn stop(&mut self, event: &Envelope, hook: &HookPayload, ops: &mut Vec) { + let error = hook.error.clone().filter(|error| !error.is_empty()); self.close_pending(event.ts_ms, error.clone(), ops); self.close_turn(event.ts_ms, error.clone(), ops); - if event - .payload - .get("fullyIdle") - .and_then(Value::as_bool) - .unwrap_or(true) - { + if hook.fully_idle.unwrap_or(true) { self.close_root(event.ts_ms, error, ops); } } @@ -497,6 +533,7 @@ impl AntigravityTranslator { impl AgentTranslator for AntigravityTranslator { fn handle(&mut self, event: &Envelope, ctx: &SessionCtx) -> anyhow::Result> { + let hook: HookPayload = serde::Deserialize::deserialize(&event.payload)?; self.last_ts_ms = self.last_ts_ms.max(event.ts_ms); let mut ops = Vec::new(); // A later Antigravity process can resume the same conversation after a @@ -505,22 +542,21 @@ impl AgentTranslator for AntigravityTranslator { if self.root_ended && event.event != "Stop" { self.root_ended = false; } - self.ensure_root(event, ctx, &mut ops); + self.ensure_root(event, &hook, ctx, &mut ops); self.tail_transcript(event, &mut ops); match event.event.as_str() { - "PreInvocation" => self.pre_invocation(event, &mut ops), - "PostInvocation" => self.post_invocation(event, &mut ops), - "PreToolUse" => self.pre_tool(event, &mut ops), - "PostToolUse" => self.post_tool(event, &mut ops), - "Stop" => self.stop(event, &mut ops), + "PreInvocation" => self.pre_invocation(event, &hook, &mut ops), + "PostInvocation" => self.post_invocation(event, &hook, &mut ops), + "PreToolUse" => self.pre_tool(event, &hook, &mut ops), + "PostToolUse" => self.post_tool(event, &hook, &mut ops), + "Stop" => self.stop(event, &hook, &mut ops), _ => {} } - let cwd = event - .payload - .get("workspacePaths") - .and_then(Value::as_array) + let cwd = hook + .workspace_paths + .as_ref() .and_then(|paths| paths.first()) - .and_then(Value::as_str); + .map(String::as_str); self.git.enrich_rows(cwd, &mut ops); Ok(ops) } @@ -534,40 +570,35 @@ impl AgentTranslator for AntigravityTranslator { } } -fn tool_approval_from_event(event: &Envelope) -> Option { - match string_field(&event.payload, "toolApproval").as_deref() { +fn tool_approval_from_hook(hook: &HookPayload) -> Option { + match hook.tool_approval.as_deref() { Some("approved") => Some(ToolApproval::Approved), Some("denied") => Some(ToolApproval::Denied), _ => None, } } -struct TranscriptSource<'a> { +struct TranscriptSource { path: String, through: u64, - snapshot: Option<&'a str>, + snapshot: Option, } -fn transcript_source(event: &Envelope) -> Option> { - let observation = event.payload.get("_bt_transcript_observation"); +fn transcript_source(event: &Envelope) -> Option { + let fields = TranscriptPayload::decode(&event.payload).ok()?; + let observation = fields.observation.as_ref(); let compact_path = observation - .and_then(|value| value.get("path")) - .and_then(Value::as_str) - .or_else(|| event.payload.get("transcriptPath").and_then(Value::as_str))?; - let full_path = observation - .and_then(|value| value.get("full_path")) - .and_then(Value::as_str); + .and_then(|value| value.path.as_deref()) + .or(fields.transcript_path.as_deref())?; + let full_path = observation.and_then(|value| value.full_path.as_deref()); let (path, through) = if let (Some(path), Some(through)) = ( full_path, - observation - .and_then(|value| value.get("full_observed_bytes")) - .and_then(Value::as_u64), + observation.and_then(|value| value.full_observed_bytes), ) { (path, through) } else { let through = observation - .and_then(|value| value.get("observed_bytes")) - .and_then(Value::as_u64) + .and_then(|value| value.observed_bytes) .or_else(|| { std::fs::metadata(compact_path) .ok() @@ -575,20 +606,18 @@ fn transcript_source(event: &Envelope) -> Option> { })?; (compact_path, through) }; - let snapshot = event - .payload - .get("_bt_transcript_snapshot") - .filter(|value| value.get("path").and_then(Value::as_str) == Some(path)) - .and_then(|value| value.get("contents")) - .and_then(Value::as_str); + let snapshot = fields + .snapshot + .filter(|value| value.path == path) + .map(|value| value.contents); Some(TranscriptSource { - path: path.to_string(), + path: path.to_owned(), through, snapshot, }) } -fn read_file_records(path: &str, offset: &mut u64, through: u64) -> Vec { +fn read_file_records(path: &str, offset: &mut u64, through: u64) -> Vec { let Ok(mut file) = std::fs::File::open(path) else { return Vec::new(); }; @@ -602,7 +631,7 @@ fn read_file_records(path: &str, offset: &mut u64, through: u64) -> Vec { read_records(&mut std::io::BufReader::new(file), offset, through.min(len)) } -fn read_snapshot_records(contents: &str, offset: &mut u64, through: u64) -> Vec { +fn read_snapshot_records(contents: &str, offset: &mut u64, through: u64) -> Vec { if *offset > contents.len() as u64 { *offset = 0; } @@ -617,7 +646,7 @@ fn read_records( reader: &mut std::io::BufReader, offset: &mut u64, through: u64, -) -> Vec { +) -> Vec { let mut records = Vec::new(); let mut line = String::new(); while *offset < through { @@ -630,30 +659,33 @@ fn read_records( break; } *offset += read as u64; - if let Ok(value) = serde_json::from_str::(line.trim()) { + if let Ok(value) = serde_json::from_str::(line.trim()) { records.push(value); } } records } -fn normalized_record_type(record: &Value) -> String { - let record_type = string_field(record, "type").unwrap_or_default(); +fn normalized_record_type(record: &TranscriptRecord) -> String { + let record_type = &record.kind; record_type .strip_prefix("CORTEX_STEP_TYPE_") - .unwrap_or(&record_type) + .unwrap_or(record_type) .to_string() } -fn transcript_message(record: &Value, record_type: &str, source: &str) -> Option { +fn transcript_message( + record: &TranscriptRecord, + record_type: &str, + source: &str, +) -> Option { let role = match (record_type, source) { ("USER_INPUT", _) | (_, "USER_EXPLICIT") | (_, "USER") => "user", ("PLANNER_RESPONSE", _) => "assistant", (_, "SYSTEM") => "system", - _ if record.get("content").is_some() => "tool", + _ if record.content.is_some() => "tool", _ => return None, }; - let mut message = Map::new(); let content = match role { "user" => clean_user_input(record_content(record)), "tool" => clean_tool_content(record_content(record)), @@ -662,23 +694,22 @@ fn transcript_message(record: &Value, record_type: &str, source: &str) -> Option if role == "system" && content.is_null() { return None; } - message.insert("role".into(), json!(role)); - message.insert("content".into(), content); - if let Some(tool_calls) = record.get("tool_calls").or_else(|| record.get("toolCalls")) { - message.insert("tool_calls".into(), tool_calls.clone()); - } - if role == "tool" { - message.insert("name".into(), json!(record_type.to_ascii_lowercase())); - } - message.insert("step_type".into(), json!(record_type)); - Some(Value::Object(message)) + Some(Message { + role: role.into(), + content, + tool_calls: record.tool_calls.clone(), + name: (role == "tool").then(|| record_type.to_ascii_lowercase()), + step_type: record_type.into(), + message_type: None, + }) } -fn record_content(record: &Value) -> Value { +fn record_content(record: &TranscriptRecord) -> Value { record - .get("content") - .or_else(|| record.get("message")) - .or_else(|| record.get("text")) + .content + .as_ref() + .or(record.message.as_ref()) + .or(record.text.as_ref()) .cloned() .unwrap_or(Value::Null) } @@ -709,38 +740,23 @@ struct ToolDetails { error: Option, } -fn tool_details(record: &Value) -> ToolDetails { +fn tool_details(record: &TranscriptRecord) -> ToolDetails { let call = record - .get("tool_calls") - .or_else(|| record.get("toolCalls")) - .and_then(|calls| { - calls - .as_array() - .and_then(|calls| calls.first()) - .or(Some(calls)) - }); + .tool_calls + .as_ref() + .and_then(|calls| calls.iter().next()); let record_type = normalized_record_type(record); - let name = call - .and_then(|call| { - string_field(call, "name") - .or_else(|| string_field(call, "tool_name")) - .or_else(|| string_field(call, "toolName")) - }) - .or_else(|| { - (!matches!(record_type.as_str(), "USER_INPUT" | "PLANNER_RESPONSE")) - .then(|| record_type.to_ascii_lowercase()) - }); - let input = call.and_then(|call| { - call.get("args") - .or_else(|| call.get("arguments")) - .or_else(|| call.get("input")) - .cloned() + 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()) }); + let input = call.and_then(|call| call.args.clone()); let output = call - .and_then(|call| call.get("output").or_else(|| call.get("result"))) - .cloned() + .and_then(|call| call.output.clone()) .or_else(|| nonempty_value(clean_tool_content(record_content(record)))); - let error = string_field(record, "error") + let error = record + .error + .clone() .filter(|error| !error.is_empty()) .or_else(|| { (record_type == "ERROR_MESSAGE") @@ -748,11 +764,13 @@ fn tool_details(record: &Value) -> ToolDetails { .and_then(|content| content.as_str().map(str::to_owned)) }) .or_else(|| { - string_field(record, "status") + record + .status + .as_ref() .filter(|status| matches!(status.to_ascii_lowercase().as_str(), "error" | "failed")) .map(|status| match record_content(record) { Value::String(content) if !content.is_empty() => content, - _ => status, + _ => status.clone(), }) }); ToolDetails { @@ -778,89 +796,34 @@ fn clean_tool_content(content: Value) -> Value { Value::String(text) } -fn planned_tool_start(records: &[Value], name: Option<&str>, step: i64) -> Option { +fn planned_tool_start(records: &[TranscriptRecord], name: Option<&str>, step: i64) -> Option { let name = name?; records.iter().rev().find_map(|record| { - let record_step = - integer_field(record, "step_index").or_else(|| integer_field(record, "stepIndex"))?; - if record_step >= step { + if record.step_index? >= step { return None; } - let calls = record - .get("tool_calls") - .or_else(|| record.get("toolCalls"))? - .as_array()?; - calls + record + .tool_calls + .as_ref()? .iter() - .any(|call| string_field(call, "name").as_deref() == Some(name)) + .any(|call| call.name.as_deref() == Some(name)) .then(|| parse_created_at(record)) .flatten() }) } -fn parse_created_at(record: &Value) -> Option { - let timestamp = - string_field(record, "created_at").or_else(|| string_field(record, "createdAt"))?; - chrono::DateTime::parse_from_rfc3339(×tamp) +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: &[Value]) -> Option { - let mut found = HashMap::<&'static str, f64>::new(); - for record in records { - collect_token_metrics(record, &mut found); - } - if found.is_empty() { - return None; +fn token_metrics(records: &[TranscriptRecord]) -> Option { + let mut metrics = UsageMetrics::default(); + for usage in records.iter().filter_map(|record| record.usage.as_ref()) { + metrics.observe(usage.metrics()); } - let mut metrics = Map::new(); - for (key, value) in found { - metrics.insert(key.to_string(), json!(value)); - } - Some(Value::Object(metrics)) -} - -fn collect_token_metrics(value: &Value, found: &mut HashMap<&'static str, f64>) { - match value { - Value::Object(object) => { - for (key, value) in object { - if let Some(number) = value.as_f64() { - let metric = match key.as_str() { - "input_tokens" | "inputTokens" | "prompt_tokens" | "promptTokens" => { - Some("prompt_tokens") - } - "output_tokens" | "outputTokens" | "completion_tokens" - | "completionTokens" => Some("completion_tokens"), - "total_tokens" | "totalTokens" => Some("tokens"), - "thinking_tokens" | "thinkingTokens" => Some("thinking_tokens"), - "cache_read_tokens" | "cacheReadTokens" => Some("prompt_cached_tokens"), - _ => None, - }; - if let Some(metric) = metric { - found.insert(metric, number); - } - } - collect_token_metrics(value, found); - } - } - Value::Array(values) => { - for value in values { - collect_token_metrics(value, found); - } - } - _ => {} - } -} - -fn string_field(value: &Value, field: &str) -> Option { - value.get(field).and_then(Value::as_str).map(str::to_owned) -} - -fn integer_field(value: &Value, field: &str) -> Option { - value - .get(field) - .and_then(|value| value.as_i64().or_else(|| value.as_str()?.parse().ok())) + (!metrics.is_empty()).then(|| json!(metrics)) } fn nonempty_value(value: Value) -> Option { @@ -872,3 +835,40 @@ fn nonempty_value(value: Value) -> Option { _ => Some(value), } } + +#[cfg(test)] +mod usage_tests { + use super::*; + + #[test] + fn only_explicit_usage_fields_become_metrics() { + let records: Vec = serde_json::from_value(json!([ + {"usage":{"inputTokens":10,"outputTokens":2,"totalTokens":12}, + "content":{"inputTokens":10000}, + "future":{"input_tokens":20000}, + "tool_calls":[{"name":"test","args":{"totalTokens":30000}}]}, + {"content":{"outputTokens":40000}}, + {"usage":{"vendor":{"inputTokens":50000}}} + ])) + .unwrap(); + assert_eq!( + token_metrics(&records).unwrap(), + json!({"prompt_tokens":10.0,"completion_tokens":2.0,"tokens":12.0}) + ); + assert!(token_metrics(&records[1..]).is_none()); + } + + #[test] + fn usage_snapshots_merge_known_counts_without_summing_or_inventing_totals() { + let records: Vec = serde_json::from_value(json!([ + {"usage":{"inputTokens":10,"cacheReadTokens":3}}, + {"usage":{"outputTokens":2}}, + {"usage":{"inputTokens":12}} + ])) + .unwrap(); + assert_eq!( + token_metrics(&records).unwrap(), + json!({"prompt_tokens":12.0,"completion_tokens":2.0,"prompt_cached_tokens":3.0}) + ); + } +} diff --git a/bt-daemon/src/translate/claude.rs b/bt-daemon/src/translate/claude.rs index 3a2b0432..dc23fd29 100644 --- a/bt-daemon/src/translate/claude.rs +++ b/bt-daemon/src/translate/claude.rs @@ -15,7 +15,9 @@ use super::tool::{ use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, }; +use crate::agents::usage::SnakeCaseUsage; use crate::ids; +use crate::transcript_mirror::TranscriptPayload; use crate::wire::Envelope; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; @@ -2156,24 +2158,33 @@ impl LlmCall { } } } - if let Some(usage) = message.get("usage") { - self.prompt_tokens = self.prompt_tokens.max(u64_field(usage, "input_tokens")); - self.completion_tokens = self - .completion_tokens - .max(u64_field(usage, "output_tokens")); + #[derive(Deserialize)] + struct UsageRecord { + message: Option, + } + #[derive(Deserialize)] + struct UsageMessage { + usage: Option, + } + if let Some(usage) = decode::(record) + .and_then(|record| record.message) + .and_then(|message| message.usage) + { + self.prompt_tokens = self.prompt_tokens.max(usage.input_tokens.unwrap_or(0)); + self.completion_tokens = self.completion_tokens.max(usage.output_tokens.unwrap_or(0)); self.cache_creation_tokens = self .cache_creation_tokens - .max(u64_field(usage, "cache_creation_input_tokens")); + .max(usage.cache_creation_input_tokens.unwrap_or(0)); self.cache_read_tokens = self .cache_read_tokens - .max(u64_field(usage, "cache_read_input_tokens")); - if let Some(cache) = usage.get("cache_creation") { + .max(usage.cache_read_input_tokens.unwrap_or(0)); + if let Some(cache) = usage.cache_creation { self.cache_creation_5m_tokens = self .cache_creation_5m_tokens - .max(u64_field(cache, "ephemeral_5m_input_tokens")); + .max(cache.ephemeral_5m_input_tokens.unwrap_or(0)); self.cache_creation_1h_tokens = self .cache_creation_1h_tokens - .max(u64_field(cache, "ephemeral_1h_input_tokens")); + .max(cache.ephemeral_1h_input_tokens.unwrap_or(0)); } } } @@ -2520,24 +2531,23 @@ fn read_snapshot_bounded( /// order: the daemon's own mirror, then an inline snapshot (older journals), /// then the live path. fn read_event_records(event: &Envelope, path: &str, offset: &mut u64) -> Vec { - let import_through_offset = event - .payload - .get("_bt_import_through_offset") - .and_then(Value::as_u64); - if let Some(mirrors) = event.payload.get("_bt_claude_transcript_mirrors") { + let Ok(fields) = TranscriptPayload::decode(&event.payload) else { + return Vec::new(); + }; + let import_through_offset = fields.import_through_offset; + if let Some(mirrors) = &fields.claude_mirrors { // This marker records even an absent/unreadable file. Never replace a // captured absence with bytes appended later to the mutable native path. let Some(reference) = mirrors.get(path) else { return Vec::new(); }; - let Some(mirror) = reference.get("mirror").and_then(Value::as_str) else { + let Some(mirror) = reference.mirror.as_deref() else { return Vec::new(); }; - let Some(through) = reference.get("through").and_then(Value::as_u64) else { + let Some(through) = reference.through else { return Vec::new(); }; - let through = if event.payload.get("transcript_path").and_then(Value::as_str) == Some(path) - { + let through = if fields.transcript_path.as_deref() == Some(path) { import_through_offset.map_or(through, |offset| offset.min(through)) } else { through @@ -2545,13 +2555,13 @@ fn read_event_records(event: &Envelope, path: &str, offset: &mut u64) -> Vec Vec { read_snapshot_bounded(contents, offset, None, through) } (Some(contents), None) => read_snapshot_bounded(contents, offset, Some(event.ts_ms), None), (None, through @ Some(_)) => read_file_bounded(path, offset, None, through), - (None, None) - if event - .payload - .get("_bt_transcript_replay") - .and_then(Value::as_bool) - == Some(true) => - { - Vec::new() - } + (None, None) if fields.replay == Some(true) => Vec::new(), (None, None) => read_file_bounded(path, offset, Some(event.ts_ms), None), } } @@ -2675,10 +2676,6 @@ fn string_field(value: &Value, key: &str) -> Option { }) } -fn u64_field(value: &Value, key: &str) -> u64 { - value.get(key).and_then(Value::as_u64).unwrap_or(0) -} - fn basename(path: &str) -> String { std::path::Path::new(path) .file_name() diff --git a/bt-daemon/src/translate/codex.rs b/bt-daemon/src/translate/codex.rs index 93a6485b..806db3f9 100644 --- a/bt-daemon/src/translate/codex.rs +++ b/bt-daemon/src/translate/codex.rs @@ -27,7 +27,9 @@ use super::tool::{ use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, }; +use crate::agents::usage::SnakeCaseUsage; use crate::ids; +use crate::transcript_mirror::TranscriptPayload; use crate::wire::Envelope; use regex::Regex; use serde::de::DeserializeOwned; @@ -313,10 +315,9 @@ impl AgentTranslator for CodexTranslator { self.main_path.get_or_insert(path.clone()); self.ensure_main_scope(&path); } - let import_through_ms = payload.get("_bt_import_through_ms").and_then(Value::as_i64); - let through_bytes = payload - .pointer("/_bt_transcript_mirror/through") - .and_then(Value::as_u64); + let fields = TranscriptPayload::decode(payload)?; + let import_through_ms = fields.import_through_ms; + let through_bytes = fields.mirror.and_then(|mirror| mirror.through); let after = self.deferred_hook(event, agent_id.is_none()); if self.catch_up_chunk( &path, @@ -1287,13 +1288,25 @@ impl CodexTranslator { let Some(llm) = scope.open_llm.take() else { return; }; - let usage = payload.get("info").and_then(|i| i.get("last_token_usage")); - let metrics = usage.map(token_metrics).filter(|m| !m.is_empty()); + #[derive(Deserialize)] + struct TokenCount { + info: Option, + } + #[derive(Deserialize)] + struct TokenCountInfo { + last_token_usage: Option, + } + let decoded = decode::(payload); + let usage = decoded + .as_ref() + .and_then(|event| event.info.as_ref()) + .and_then(|info| info.last_token_usage.as_ref()); + let metrics = usage + .map(|usage| usage.metrics().with_total()) + .filter(|metrics| !metrics.is_empty()); let usage_metadata = if metrics.is_none() { Some(json!({ - "usage_unavailable_reason": if usage - .and_then(Value::as_object) - .is_none_or(Map::is_empty) + "usage_unavailable_reason": if usage.is_none_or(SnakeCaseUsage::is_empty) { "codex_token_count_missing_usage" } else { @@ -1323,7 +1336,7 @@ impl CodexTranslator { end_ms: Some(end), output, metadata: usage_metadata, - metrics: metrics.map(Value::Object), + metrics: metrics.map(|metrics| json!(metrics)), ..Default::default() })); let _ = ts; @@ -1678,19 +1691,14 @@ fn is_injected_user_context(text: &str) -> bool { } fn effective_transcript_path(event: &Envelope) -> Option { - event - .payload - .pointer("/_bt_transcript_mirror/mirror") - .and_then(Value::as_str) - .map(str::to_owned) - .or_else(|| { - if event.event == "SubagentStop" { - str_field(&event.payload, "agent_transcript_path") - } else { - str_field(&event.payload, "transcript_path") - .or_else(|| str_field(&event.payload, "agent_transcript_path")) - } - }) + 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) + } + }) } impl Scope { @@ -2231,86 +2239,6 @@ fn read_new_lines( } } -fn token_metrics(usage: &Value) -> Map { - const MAP: &[(&str, &str)] = &[ - ("input_tokens", "prompt_tokens"), - ("prompt_tokens", "prompt_tokens"), - ("output_tokens", "completion_tokens"), - ("completion_tokens", "completion_tokens"), - ("total_tokens", "tokens"), - ("tokens", "tokens"), - ("cached_input_tokens", "prompt_cached_tokens"), - ("prompt_cached_tokens", "prompt_cached_tokens"), - ("input_tokens_details.cached_tokens", "prompt_cached_tokens"), - ( - "prompt_tokens_details.cached_tokens", - "prompt_cached_tokens", - ), - ( - "prompt_cache_creation_tokens", - "prompt_cache_creation_tokens", - ), - ( - "input_tokens_details.cache_creation_tokens", - "prompt_cache_creation_tokens", - ), - ( - "input_tokens_details.cache_write_tokens", - "prompt_cache_creation_tokens", - ), - ( - "prompt_tokens_details.cache_creation_tokens", - "prompt_cache_creation_tokens", - ), - ( - "prompt_tokens_details.cache_write_tokens", - "prompt_cache_creation_tokens", - ), - ("reasoning_output_tokens", "completion_reasoning_tokens"), - ("completion_reasoning_tokens", "completion_reasoning_tokens"), - ("reasoning_tokens", "completion_reasoning_tokens"), - ( - "output_tokens_details.reasoning_tokens", - "completion_reasoning_tokens", - ), - ( - "completion_tokens_details.reasoning_tokens", - "completion_reasoning_tokens", - ), - ("cost", "cost"), - ("cost", "estimated_cost"), - ("estimated_cost", "estimated_cost"), - ("total_cost", "estimated_cost"), - ("cost_usd", "estimated_cost"), - ]; - let mut metrics = Map::new(); - for (from, to) in MAP { - if metrics.contains_key(*to) { - continue; - } - if let Some(v) = num_at(usage, from) { - metrics.insert((*to).to_string(), json!(v)); - } - } - if !metrics.contains_key("tokens") { - if let (Some(p), Some(c)) = ( - metrics.get("prompt_tokens").and_then(Value::as_f64), - metrics.get("completion_tokens").and_then(Value::as_f64), - ) { - metrics.insert("tokens".to_string(), json!(p + c)); - } - } - metrics -} - -fn num_at(v: &Value, path: &str) -> Option { - let mut cur = v; - for part in path.split('.') { - cur = cur.get(part)?; - } - cur.as_f64().filter(|n| n.is_finite()) -} - #[cfg(test)] mod tests { use super::{basename, normalize_timestamp, RolloutRecord}; diff --git a/bt-daemon/src/translate/cursor/hooks.rs b/bt-daemon/src/translate/cursor/hooks.rs index bdc3c77b..aeff40c8 100644 --- a/bt-daemon/src/translate/cursor/hooks.rs +++ b/bt-daemon/src/translate/cursor/hooks.rs @@ -441,107 +441,6 @@ pub(super) struct ImportStopHook { pub error_message: Option, } -/// One line of Cursor's saved transcript. -#[derive(Deserialize)] -#[serde(untagged)] -pub(super) enum TranscriptRecord { - Message { - role: Role, - message: TranscriptMessage, - }, - /// Marks the end of a turn. The translator reads turn status from hooks, - /// so only the marker's shape is checked. - TurnEnded { - #[serde(rename = "type")] - _kind: TurnEndedKind, - #[serde(rename = "status")] - _status: String, - #[serde(rename = "error", default)] - _error: Option, - }, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] -#[serde(rename_all = "lowercase")] -pub(super) enum Role { - User, - Assistant, -} - -impl Role { - pub fn as_str(self) -> &'static str { - match self { - Self::User => "user", - Self::Assistant => "assistant", - } - } -} - -#[derive(Deserialize)] -pub(super) struct TranscriptMessage { - pub content: MessageContent, -} - -#[derive(Deserialize)] -#[serde(rename_all = "snake_case")] -pub(super) enum TurnEndedKind { - TurnEnded, -} - -/// Message content: plain text, or content blocks. -#[derive(Deserialize)] -#[serde(untagged)] -pub(super) enum MessageContent { - Text(String), - Blocks(Vec), -} - -#[derive(Deserialize)] -#[serde(tag = "type", rename_all = "snake_case")] -pub(super) enum ContentBlock { - Text { - text: String, - }, - /// Tool requests are reported by hooks; transcripts add nothing to them. - ToolUse, -} - -impl MessageContent { - /// The concatenated text of the content. - pub fn text(&self) -> String { - match self { - Self::Text(text) => text.clone(), - Self::Blocks(blocks) => blocks - .iter() - .filter_map(|block| match block { - ContentBlock::Text { text } => Some(text.as_str()), - ContentBlock::ToolUse => None, - }) - .collect(), - } - } -} - -impl TranscriptRecord { - pub fn decode(record: &Value) -> Result { - decode("cursor", "transcript record", record) - } - - pub fn role(&self) -> Option { - match self { - Self::Message { role, .. } => Some(*role), - Self::TurnEnded { .. } => None, - } - } - - pub fn text(&self) -> Option { - match self { - Self::Message { message, .. } => Some(message.content.text()), - Self::TurnEnded { .. } => None, - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/bt-daemon/src/translate/cursor/mod.rs b/bt-daemon/src/translate/cursor/mod.rs index 1d61e0cc..a3a6b3a9 100644 --- a/bt-daemon/src/translate/cursor/mod.rs +++ b/bt-daemon/src/translate/cursor/mod.rs @@ -10,11 +10,13 @@ use super::recent::{RecentMap, RecentSet}; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, }; +use crate::agents::cursor::schema::{Role, TranscriptRecord}; +use crate::agents::usage::TokenMetrics; use crate::{ids, wire::Envelope}; use hooks::{ - CursorHook, Hook, ImportStopHook, PromptHook, ResponseHook, Role, SessionEndHook, Specialized, + CursorHook, Hook, ImportStopHook, PromptHook, ResponseHook, SessionEndHook, Specialized, StopHook, SubagentStartHook, SubagentStopHook, ToolHook, ToolPhase, TranscriptMirror, - TranscriptRecord, TurnUsage, + TurnUsage, }; pub(crate) use hooks::{IMPORT_CHECKPOINT, IMPORT_START, IMPORT_STOP}; use serde::{Deserialize, Serialize}; @@ -112,46 +114,64 @@ struct Turn { boundary: i64, model_seq: u64, emitted_text: String, - usage: serde_json::Map, + usage: TokenMetrics, } +#[derive(PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +enum ModelContent { + Text { + text: String, + }, + Thinking { + text: String, + }, + ToolUse { + id: String, + name: String, + input: Option, + }, +} +impl ModelContent { + fn text(&self) -> Option<&str> { + match self { + Self::Text { text } => Some(text), + _ => None, + } + } + fn encoded_len(&self) -> usize { + serde_json::to_vec(self).map_or(0, |encoded| encoded.len()) + } +} + #[derive(Serialize, Deserialize)] struct ModelStep { #[serde(with = "super::state::row")] row: SpanRow, - content: Vec, + content: Vec, text: String, bytes: usize, truncated: bool, } impl ModelStep { - fn push(&mut self, value: Value) { - if let Some(text) = value - .get("text") - .and_then(Value::as_str) - .filter(|_| value.get("type").and_then(Value::as_str) == Some("text")) - { - // afterAgentResponse repeats the concatenation of transcript text - // fragments. Retain one authoritative copy of that exact content. + fn push(&mut self, value: ModelContent) { + if let Some(text) = value.text() { if !self.text.is_empty() && self.text == text { - self.content - .retain(|v| v.get("type").and_then(Value::as_str) != Some("text")); + self.content.retain(|part| part.text().is_none()); self.text.clear(); - self.bytes = self.content.iter().map(|v| v.to_string().len()).sum(); + self.bytes = self.content.iter().map(ModelContent::encoded_len).sum(); } } if self.content.contains(&value) { return; } - let size = value.to_string().len(); + let size = value.encoded_len(); if self.bytes + size > MAX_HISTORY_BYTES || self.content.len() >= MAX_HISTORY_MESSAGES { self.truncated = true; return; } self.bytes += size; - if value.get("type").and_then(Value::as_str) == Some("text") { - if let Some(text) = value.get("text").and_then(Value::as_str) { - self.text.push_str(text); - } + if let Some(text) = value.text() { + self.text.push_str(text); } self.content.push(value); } @@ -380,7 +400,7 @@ impl CursorTranslator { boundary: ts, model_seq: 0, emitted_text: String::new(), - usage: serde_json::Map::new(), + usage: TokenMetrics::default(), }; if let Some(g) = generation { self.prompt_generations.insert(g.into(), turn.clone()); @@ -528,15 +548,11 @@ impl CursorTranslator { metadata["history_truncated"] = json!(true); } } - fn model_content(&mut self, content: Value, ts: i64, ops: &mut Vec) { + fn model_content(&mut self, content: ModelContent, ts: i64, ops: &mut Vec) { if let Some(turn) = self.turn.as_mut().filter(|turn| turn.end.is_some()) { // Late output belongs to the closed turn. Its receipt time does // not establish another model request or extend model latency. - if let Some(text) = content - .get("text") - .and_then(Value::as_str) - .filter(|_| content.get("type").and_then(Value::as_str) == Some("text")) - { + if let Some(text) = content.text() { self.history .push(json!({"role":"assistant","content":text})); self.seen.insert(format!( @@ -570,20 +586,14 @@ impl CursorTranslator { let text = step .content .iter() - .filter(|v| v.get("type").and_then(Value::as_str) == Some("text")) - .filter_map(|v| v.get("text").and_then(Value::as_str)) + .filter_map(ModelContent::text) .collect::(); if turn.emitted_text.len() + text.len() <= MAX_HISTORY_BYTES { turn.emitted_text.push_str(&text); } } if let Some(owner) = step.row.parent_span_ids.first() { - for text in step - .content - .iter() - .filter(|v| v.get("type").and_then(Value::as_str) == Some("text")) - .filter_map(|v| v.get("text").and_then(Value::as_str)) - { + for text in step.content.iter().filter_map(ModelContent::text) { self.seen.insert(format!( "output-text:{owner}:{}", ids::span_id(&self.namespace, text) @@ -732,7 +742,11 @@ impl CursorTranslator { return; } self.model_content( - json!({"type":"tool_use","id":call_id,"name":tool.row.name,"input":tool.row.input}), + ModelContent::ToolUse { + id: call_id.to_owned(), + name: tool.row.name.clone(), + input: tool.row.input.clone(), + }, e.ts_ms, ops, ); @@ -766,12 +780,11 @@ impl CursorTranslator { // Without preToolUse, the duration is the only available // tool-request boundary. Tool execution is not model latency. self.model_content( - json!({ - "type":"tool_use", - "id":call_id, - "name":name, - "input":input, - }), + ModelContent::ToolUse { + id: call_id, + name, + input, + }, boundary, ops, ); @@ -973,7 +986,8 @@ impl CursorTranslator { let (records, truncated, complete) = self.transcript.read_batch(path, through)?; self.history.truncated |= truncated; for raw in records { - let record = TranscriptRecord::decode(&raw)?; + let record = + super::decode::decode::("cursor", "transcript record", &raw)?; let role = record.role(); if role == Some(Role::User) { self.transcript.assistant_records = 0; @@ -1156,7 +1170,7 @@ impl CursorTranslator { { return; } - self.model_content(json!({"type":"text","text":text}), ts, ops); + self.model_content(ModelContent::Text { text: text.clone() }, ts, ops); if let Some(t) = &mut self.turn { t.output = Some(text); } @@ -1320,32 +1334,34 @@ impl CursorTranslator { else { return; }; - let mut metrics = serde_json::Map::new(); - for (count, metric) in [ - (usage.input_tokens, "prompt_tokens"), - (usage.output_tokens, "completion_tokens"), - (usage.cache_read_tokens, "prompt_cached_tokens"), - (usage.cache_write_tokens, "prompt_cache_creation_tokens"), - ] { - if let Some(count) = count { - metrics.insert(metric.into(), json!(count)); - } - } - if metrics.is_empty() { + if usage.input_tokens.is_none() + && usage.output_tokens.is_none() + && usage.cache_read_tokens.is_none() + && usage.cache_write_tokens.is_none() + { return; } - // Response and stop can report partial snapshots for the same turn. - // Merge known counts rather than fabricating missing values or summing - // repeated observations. Cache counts remain subsets of prompt usage. - turn.usage.extend(metrics); + // Response and stop carry partial snapshots. Replace known fields, + // never sum snapshots or fabricate counters missing from both. + if let Some(count) = usage.input_tokens { + turn.usage.prompt_tokens = Some(count); + } + if let Some(count) = usage.output_tokens { + turn.usage.completion_tokens = Some(count); + } + if let Some(count) = usage.cache_read_tokens { + turn.usage.prompt_cached_tokens = Some(count); + } + if let Some(count) = usage.cache_write_tokens { + turn.usage.prompt_cache_creation_tokens = Some(count); + } if let Some(total) = turn .usage - .get("prompt_tokens") - .and_then(Value::as_u64) - .zip(turn.usage.get("completion_tokens").and_then(Value::as_u64)) + .prompt_tokens + .zip(turn.usage.completion_tokens) .and_then(|(prompt, completion)| prompt.checked_add(completion)) { - turn.usage.insert("tokens".into(), json!(total)); + turn.usage.tokens = Some(total); } let mut row = self.row( turn.id.clone(), @@ -1353,7 +1369,7 @@ impl CursorTranslator { &format!("Turn {}", turn.ordinal), SpanType::Task, ); - let metrics = Value::Object(turn.usage.clone()); + let metrics = json!(turn.usage); let metrics_id = ids::span_id(&self.namespace, &metrics.to_string()); row.metrics = Some(metrics); row.metadata = Some(json!({"token_usage_scope":"turn"})); @@ -1404,7 +1420,13 @@ impl CursorTranslator { CursorHook::BeforeSubmitPrompt(prompt) => self.prompt(e, hook, prompt, ops), CursorHook::Tool(phase, tool) => self.tool(e, hook, phase, tool, ops), CursorHook::AfterAgentThought(thought) => { - self.model_content(json!({"type":"thinking","text":thought.text}), e.ts_ms, ops); + self.model_content( + ModelContent::Thinking { + text: thought.text.clone(), + }, + e.ts_ms, + ops, + ); } CursorHook::AfterAgentResponse(response) => { self.response(e, generation, response, &native, ops) @@ -1460,7 +1482,13 @@ impl CursorTranslator { .and_then(|t| text.strip_prefix(&t.emitted_text)) .unwrap_or(text); if !unseen.is_empty() { - self.model_content(json!({"type":"text","text":unseen}), e.ts_ms, ops); + self.model_content( + ModelContent::Text { + text: unseen.to_owned(), + }, + e.ts_ms, + ops, + ); } if let Some(t) = &mut self.turn { t.output = Some(text.into()); @@ -1652,28 +1680,20 @@ fn user_prompt(text: &str) -> Value { json!([{ "role": "user", "content": text }]) } -fn assistant_message(content: &[Value]) -> Value { +fn assistant_message(content: &[ModelContent]) -> Value { let mut text = String::new(); let mut reasoning = Vec::new(); let mut calls = Vec::new(); for part in content { - match part.get("type").and_then(Value::as_str) { - Some("text") => { - if let Some(value) = part.get("text").and_then(Value::as_str) { - text.push_str(value); - } - } - Some("thinking") => { - if let Some(value) = part.get("text").and_then(Value::as_str) { - reasoning.push(json!({"type":"summary_text", "text":value})); - } + match part { + ModelContent::Text { text: value } => text.push_str(value), + ModelContent::Thinking { text: value } => { + reasoning.push(json!({"type":"summary_text", "text":value})) } - Some("tool_use") => calls.push(json!({ - "id": part.get("id"), "type": "function", - "function": {"name": part.get("name"), - "arguments": tool_result_content(part.get("input"))}, + ModelContent::ToolUse { id, name, input } => calls.push(json!({ + "id": id, "type": "function", + "function": {"name": name, "arguments": tool_result_content(input.as_ref())}, })), - _ => {} } } let mut message = json!({"role":"assistant", "content":text}); diff --git a/bt-daemon/src/translate/git.rs b/bt-daemon/src/translate/git.rs index fa85debe..4aa69b8a 100644 --- a/bt-daemon/src/translate/git.rs +++ b/bt-daemon/src/translate/git.rs @@ -25,12 +25,24 @@ struct GitFingerprint { worktree_config: Option, } +#[derive(Clone, Default)] +struct GitMetadata { + origin_url: Option, + branch: Option, + commit_sha: Option, +} +impl GitMetadata { + fn is_empty(&self) -> bool { + self.origin_url.is_none() && self.branch.is_none() && self.commit_sha.is_none() + } +} + #[derive(Clone)] struct RepoEntry { git_dir: PathBuf, common_dir: PathBuf, fingerprint: GitFingerprint, - metadata: Map, + metadata: GitMetadata, } struct NegativeEntry { @@ -98,16 +110,16 @@ impl GitMetadataCache { SHARED.get_or_init(Arc::default).clone() } - pub(super) fn metadata(&self, cwd: &str) -> Map { + fn metadata(&self, cwd: &str) -> GitMetadata { if cwd.is_empty() { - return Map::new(); + return GitMetadata::default(); } let cwd = canonical_or_original(Path::new(cwd)); let mut state = self.state.lock(); if let Some(negative) = state.negative.get(&cwd) { if negative.observed_at.elapsed() < NEGATIVE_TTL { - return Map::new(); + return GitMetadata::default(); } state.negative.remove(&cwd); state.negative_order.retain(|key| key != &cwd); @@ -140,7 +152,7 @@ impl GitMetadataCache { ); touch(&mut state.negative_order, &cwd); state.trim_negative(); - return Map::new(); + return GitMetadata::default(); }; let metadata = entry.metadata.clone(); state.cwd_to_repo.insert(cwd.clone(), repo_root.clone()); @@ -168,15 +180,21 @@ impl GitMetadataCache { } } -fn merge_metadata(row: &mut SpanRow, git: &Map) { +fn merge_metadata(row: &mut SpanRow, git: &GitMetadata) { let metadata = row .metadata .get_or_insert_with(|| Value::Object(Map::new())); let Some(metadata) = metadata.as_object_mut() else { return; }; - for (key, value) in git { - metadata.insert(key.clone(), value.clone()); + for (key, value) in [ + ("git_origin_url", &git.origin_url), + ("git_branch", &git.branch), + ("git_commit_sha", &git.commit_sha), + ] { + if let Some(value) = value { + metadata.insert(key.into(), Value::String(value.clone())); + } } } @@ -188,19 +206,11 @@ fn discover_repo(cwd: &Path) -> Option<(PathBuf, RepoEntry)> { fn inspect_repo(cwd: &Path) -> Option { let git_dir = absolute_git_path(cwd, &git(cwd, &["rev-parse", "--absolute-git-dir"])?); let common_dir = absolute_git_path(cwd, &git(cwd, &["rev-parse", "--git-common-dir"])?); - let mut metadata = Map::new(); - if let Some(origin) = git(cwd, &["remote", "get-url", "origin"]) { - metadata.insert( - "git_origin_url".into(), - Value::String(redact_remote(origin)), - ); - } - if let Some(branch) = git(cwd, &["symbolic-ref", "--quiet", "--short", "HEAD"]) { - metadata.insert("git_branch".into(), Value::String(branch)); - } - if let Some(commit) = git(cwd, &["rev-parse", "HEAD"]) { - metadata.insert("git_commit_sha".into(), Value::String(commit)); - } + let metadata = GitMetadata { + origin_url: git(cwd, &["remote", "get-url", "origin"]).map(redact_remote), + branch: git(cwd, &["symbolic-ref", "--quiet", "--short", "HEAD"]), + commit_sha: git(cwd, &["rev-parse", "HEAD"]), + }; Some(RepoEntry { fingerprint: fingerprint(&git_dir, &common_dir), git_dir, @@ -330,8 +340,11 @@ mod tests { let cache = GitMetadataCache::default(); let first = cache.metadata(subdir.to_str().unwrap()); - assert_eq!(first["git_branch"], "main"); - assert_eq!(first["git_origin_url"], "https://example.com/acme/a.git"); + assert_eq!(first.branch.as_deref(), Some("main")); + assert_eq!( + first.origin_url.as_deref(), + Some("https://example.com/acme/a.git") + ); run(&repo, &["checkout", "-b", "feature"]); fs::write(repo.join("b"), "b").unwrap(); @@ -347,8 +360,11 @@ mod tests { ], ); let second = cache.metadata(subdir.to_str().unwrap()); - assert_eq!(second["git_branch"], "feature"); - assert_eq!(second["git_origin_url"], "https://example.com/acme/b.git"); - assert_ne!(first["git_commit_sha"], second["git_commit_sha"]); + assert_eq!(second.branch.as_deref(), Some("feature")); + assert_eq!( + second.origin_url.as_deref(), + Some("https://example.com/acme/b.git") + ); + assert_ne!(first.commit_sha, second.commit_sha); } } diff --git a/bt-daemon/src/translate/grok.rs b/bt-daemon/src/translate/grok.rs index 7e13a56a..832bb750 100644 --- a/bt-daemon/src/translate/grok.rs +++ b/bt-daemon/src/translate/grok.rs @@ -10,7 +10,10 @@ use super::tool::nonempty_error_text; use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, }; +use crate::agents::usage::CamelCaseUsage as NativeUsage; use crate::ids; +use crate::json::Extensions; +use crate::transcript_mirror::{Reference, TranscriptPayload}; use crate::wire::Envelope; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; @@ -27,6 +30,103 @@ const MAX_OUTPUT_CHUNKS: usize = 2_048; const MAX_OUTPUT_BYTES: usize = 2 * 1024 * 1024; const MAX_SYSTEM_PROMPT_BYTES: u64 = 2 * 1024 * 1024; +#[derive(Clone, Default, Serialize, Deserialize)] +struct NativeRecord { + #[serde(default, skip_serializing_if = "Option::is_none")] + params: Option, + #[serde(default, skip_serializing_if = "Option::is_none", rename = "type")] + kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + tool_call_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + outcome: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + duration_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + ts: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + timestamp: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extra: Extensions, +} +#[derive(Clone, Default, Serialize, Deserialize)] +struct NativeParams { + #[serde(default, skip_serializing_if = "Option::is_none")] + update: Option, + #[serde(default, skip_serializing_if = "Option::is_none", rename = "_meta")] + meta: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extra: Extensions, +} +#[derive(Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct NativeUpdate { + #[serde(default, skip_serializing_if = "Option::is_none")] + session_update: Option, + #[serde(default, skip_serializing_if = "Option::is_none", rename = "_meta")] + meta: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::agents::schema::deserialize_present" + )] + content: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + tool_call_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + status: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + title: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::agents::schema::deserialize_present" + )] + raw_input: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "crate::agents::schema::deserialize_present" + )] + raw_output: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + usage: Option, + #[serde(default, skip_serializing_if = "Option::is_none", rename = "prompt_id")] + prompt_id: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + rename = "stop_reason" + )] + stop_reason: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extra: Extensions, +} +#[derive(Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct NativeMeta { + #[serde(default, skip_serializing_if = "Option::is_none")] + prompt_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + prompt_index: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + model_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + stream_start_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + agent_timestamp_ms: Option, + #[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")] + extra: Extensions, +} +#[derive(Clone, Serialize, Deserialize)] +#[serde(untagged)] +enum PromptIndex { + Text(String), + Number(serde_json::Number), +} + impl TranslatorFactory for crate::agents::Grok { fn create(&self, session_id: &str) -> Box { Box::new(GrokTranslator::new(session_id, GitMetadataCache::shared())) @@ -183,7 +283,7 @@ impl TranscriptCursor { #[derive(Serialize, Deserialize)] struct TranscriptRecord { end_offset: u64, - value: Value, + value: NativeRecord, } #[derive(Serialize, Deserialize)] struct TranscriptBatch { @@ -211,7 +311,7 @@ struct GrokTranslator { open_llm: Option, open_tools: BTreeMap, completed_tools: RecentMap, - pending_tool_events: RecentMap, + pending_tool_events: RecentMap, emitted_turns: RecentSet, emitted_chunks: RecentSet, updates: TranscriptCursor, @@ -387,19 +487,19 @@ impl GrokTranslator { fn process_update( &mut self, - record: &Value, + record: &NativeRecord, record_end_offset: u64, event: &Envelope, ctx: &SessionCtx, ops: &mut Vec, ) { - let Some(params) = record.get("params") else { + let Some(params) = record.params.as_ref() else { return; }; - let Some(update) = params.get("update") else { + let Some(update) = params.update.as_ref() else { return; }; - let Some(kind) = update.get("sessionUpdate").and_then(Value::as_str) else { + let Some(kind) = update.session_update.as_deref() else { return; }; let ts_ms = record_ts_ms(record).unwrap_or(event.ts_ms); @@ -411,7 +511,9 @@ impl GrokTranslator { if kind != "user_message_chunk" && self.current_turn.is_none() { return; } - let serialized = serde_json::to_string(record).unwrap_or_default(); + let serialized = serde_json::to_value(record) + .and_then(|value| serde_json::to_string(&value)) + .unwrap_or_default(); let chunk_identity = if kind == "user_message_chunk" { serialized } else { @@ -428,10 +530,7 @@ impl GrokTranslator { } match kind { "user_message_chunk" => { - let meta = update - .get("_meta") - .or_else(|| params.get("_meta")) - .and_then(Value::as_object); + let meta = update.meta.as_ref().or(params.meta.as_ref()); let next_number = self.turn_seq.saturating_add(1); let turn_key = turn_key(meta, next_number); if self @@ -439,7 +538,7 @@ impl GrokTranslator { .as_ref() .is_some_and(|turn| turn.key == turn_key) { - if let Some(content) = update.get("content") { + if let Some(content) = update.content.as_ref() { let Some(turn) = self.current_turn.as_mut() else { return; }; @@ -456,16 +555,10 @@ impl GrokTranslator { self.ensure_root(ts_ms, event, ctx, ops); self.turn_seq = next_number; let span_id = ids::span_id(&self.session_id, &format!("turn:{turn_key}")); - let model = meta - .and_then(|m| m.get("modelId")) - .and_then(Value::as_str) - .map(str::to_owned); - let prompt_id = meta - .and_then(|m| m.get("promptId")) - .and_then(Value::as_str) - .map(str::to_owned); + let model = meta.and_then(|m| m.model_id.clone()); + let prompt_id = meta.and_then(|m| m.prompt_id.clone()); let mut user_input = BoundedOutput::default(); - if let Some(content) = update.get("content") { + if let Some(content) = update.content.as_ref() { user_input.push(content_value(content)); } let input = user_input.message_content(); @@ -500,17 +593,9 @@ impl GrokTranslator { if self.current_turn.is_none() { return; } - let meta = params - .get("_meta") - .or_else(|| update.get("_meta")) - .and_then(Value::as_object); - let prompt_id = meta - .and_then(|m| m.get("promptId")) - .and_then(Value::as_str) - .map(str::to_owned); - let stream_start_ms = meta - .and_then(|m| m.get("streamStartMs")) - .and_then(Value::as_i64); + let meta = params.meta.as_ref().or(update.meta.as_ref()); + let prompt_id = meta.and_then(|m| m.prompt_id.clone()); + let stream_start_ms = meta.and_then(|m| m.stream_start_ms); let needs_new = self.open_llm.as_ref().is_none_or(|llm| { identities_differ( llm.prompt_id.as_deref(), @@ -612,7 +697,7 @@ impl GrokTranslator { turn.prompt_id.get_or_insert(prompt_id); } let is_reasoning = kind == "agent_thought_chunk"; - if let Some(content) = update.get("content") { + if let Some(content) = update.content.as_ref() { if let Some(llm) = self.open_llm.as_mut() { llm.last_ms = llm.last_ms.max(ts_ms); if is_reasoning { @@ -635,7 +720,7 @@ impl GrokTranslator { else { return; }; - let Some(call_id) = update.get("toolCallId").and_then(Value::as_str) else { + let Some(call_id) = update.tool_call_id.as_deref() else { return; }; if self.open_tools.contains_key(call_id) { @@ -648,11 +733,7 @@ impl GrokTranslator { } self.evict_open_tool_if_needed(ts_ms, ops); let span_id = ids::span_id(&self.session_id, &format!("tool:{call_id}")); - let name = update - .get("title") - .and_then(Value::as_str) - .unwrap_or("Tool") - .to_string(); + let name = update.title.as_deref().unwrap_or("Tool").to_string(); ops.push(SpanOp::Insert(SpanRow { span_id: span_id.clone(), root_span_id: self.root_span_id.clone(), @@ -661,7 +742,7 @@ impl GrokTranslator { name, span_type: SpanType::Tool, start_ms: Some(ts_ms), - input: update.get("rawInput").cloned(), + input: update.raw_input.as_ref().cloned(), metadata: Some(json!({"tool_call_id": call_id})), ..Default::default() })); @@ -676,10 +757,10 @@ impl GrokTranslator { } "tool_call_update" => { self.close_llm(ts_ms, "tool_update", Some("llm:tool_update".into()), ops); - let Some(call_id) = update.get("toolCallId").and_then(Value::as_str) else { + let Some(call_id) = update.tool_call_id.as_deref() else { return; }; - let status = update.get("status").and_then(Value::as_str); + let status = update.status.as_deref(); if !matches!(status, Some("completed" | "failed" | "error" | "cancelled")) { return; } @@ -710,14 +791,10 @@ impl GrokTranslator { root_span_id: self.root_span_id.clone(), parent_span_ids: vec![parent_span_id.clone()], turn_span_id: Some(parent_span_id.clone()), - name: update - .get("title") - .and_then(Value::as_str) - .unwrap_or("Tool") - .to_string(), + name: update.title.as_deref().unwrap_or("Tool").to_string(), span_type: SpanType::Tool, start_ms: Some(ts_ms), - input: update.get("rawInput").cloned(), + input: update.raw_input.as_ref().cloned(), metadata: Some(json!({ "tool_call_id": call_id, "missing_start": true @@ -747,8 +824,8 @@ impl GrokTranslator { ); let cancelled = status == Some("cancelled"); let mut metadata = Map::new(); - if let Some(kind) = update.get("kind") { - metadata.insert("kind".into(), kind.clone()); + if let Some(kind) = update.kind.as_ref() { + metadata.insert("kind".into(), json!(kind)); } if let Some(status) = status { metadata.insert("status".into(), json!(status)); @@ -766,8 +843,9 @@ impl GrokTranslator { parent_span_ids: vec![tool.parent_span_id], end_ms: Some(end_ms), output: update - .get("rawOutput") - .or_else(|| update.get("content")) + .raw_output + .as_ref() + .or(update.content.as_ref()) .cloned(), error: failed.then(|| { tool_failure_text(update) @@ -783,11 +861,9 @@ impl GrokTranslator { let Some(turn) = self.current_turn.as_ref() else { return; }; - let usage = update.get("usage"); + let usage = update.usage.as_ref(); let metrics = usage.map(usage_metrics); - let native_model_calls = usage - .and_then(|value| value.get("modelCalls")) - .and_then(Value::as_u64); + let native_model_calls = usage.and_then(|value| value.model_calls); let reconstructed_model_calls = turn.llm_span_ids.len() as u64; if let (Some(llm_span_id), Some(metrics)) = (turn.llm_span_ids.last(), &metrics) { ops.push(SpanOp::Merge(SpanRow { @@ -804,14 +880,14 @@ impl GrokTranslator { })); } let mut metadata = Map::new(); - if let Some(prompt_id) = update.get("prompt_id") { - metadata.insert("prompt_id".into(), prompt_id.clone()); + if let Some(prompt_id) = update.prompt_id.as_ref() { + metadata.insert("prompt_id".into(), json!(prompt_id)); } - if let Some(stop_reason) = update.get("stop_reason") { - metadata.insert("stop_reason".into(), stop_reason.clone()); + if let Some(stop_reason) = update.stop_reason.as_ref() { + metadata.insert("stop_reason".into(), json!(stop_reason)); } - if let Some(model_usage) = usage.and_then(|value| value.get("modelUsage")) { - metadata.insert("model_usage".into(), model_usage.clone()); + if let Some(model_usage) = usage.and_then(|value| value.model_usage.as_ref()) { + metadata.insert("model_usage".into(), json!(model_usage)); } if native_model_calls.is_some_and(|native| native != reconstructed_model_calls) { metadata.insert( @@ -822,10 +898,9 @@ impl GrokTranslator { }), ); } - if let (Some(expected), Some(actual)) = ( - turn.prompt_id.as_deref(), - update.get("prompt_id").and_then(Value::as_str), - ) { + if let (Some(expected), Some(actual)) = + (turn.prompt_id.as_deref(), update.prompt_id.as_deref()) + { if expected != actual { metadata.insert( "prompt_id_mismatch".into(), @@ -849,11 +924,11 @@ impl GrokTranslator { } } - fn process_event(&mut self, record: &Value, ops: &mut Vec) { - if record.get("type").and_then(Value::as_str) != Some("tool_completed") { + fn process_event(&mut self, record: &NativeRecord, ops: &mut Vec) { + if record.kind.as_deref() != Some("tool_completed") { return; } - let Some(call_id) = record.get("tool_call_id").and_then(Value::as_str) else { + let Some(call_id) = record.tool_call_id.as_deref() else { return; }; let key = call_id.to_string(); @@ -874,18 +949,18 @@ impl GrokTranslator { failure_recorded: completed.failure_recorded, }, ); - let outcome = record.get("outcome").and_then(Value::as_str); + let outcome = record.outcome.as_deref(); let cancelled = matches!(outcome, Some("cancelled" | "canceled")); // Keep the precise message from the terminal update instead of // overwriting it with the hook's bare outcome. let failed = !cancelled && !matches!(outcome, Some("success") | None) && !completed.failure_recorded; let mut metadata = Map::new(); - if let Some(duration) = record.get("duration_ms") { - metadata.insert("duration_ms".into(), duration.clone()); + if let Some(duration) = record.duration_ms.as_ref() { + metadata.insert("duration_ms".into(), json!(duration)); } - if let Some(outcome) = record.get("outcome") { - metadata.insert("outcome".into(), outcome.clone()); + if let Some(outcome) = record.outcome.as_ref() { + metadata.insert("outcome".into(), json!(outcome)); } if cancelled { metadata.insert("cancelled".into(), json!(true)); @@ -1074,7 +1149,7 @@ impl GrokTranslator { ); } - fn process_system_prompt(&mut self, reference: Option<&Value>, ops: &mut Vec) { + fn process_system_prompt(&mut self, reference: Option<&Reference>, ops: &mut Vec) { if self.system_prompt.is_some() { return; } @@ -1112,7 +1187,7 @@ impl GrokTranslator { fn process_event_enrichment( &mut self, - reference: Option<&Value>, + reference: Option<&Reference>, ops: &mut Vec, ) -> bool { let Some(reference) = reference else { @@ -1146,23 +1221,24 @@ impl GrokTranslator { ctx: &SessionCtx, ) -> anyhow::Result<(Vec, bool)> { let mut ops = Vec::new(); - let Some(mirrors) = event.payload.get("_bt_grok_transcript_mirrors") else { + let fields = TranscriptPayload::decode(&event.payload)?; + let Some(mirrors) = fields.grok_mirrors else { return Ok((ops, true)); }; // Updates are authoritative and advance before optional event // enrichment. Both fixed captured boundaries are drained before a // terminal hook is finalized. - let updates = read_new_records(mirrors.get("updates"), &self.updates)?; + let updates = read_new_records(mirrors.updates.as_ref(), &self.updates)?; if updates.reset { self.reset_transcript_state(); } let updates_complete = updates.complete; self.updates = updates.cursor; - self.process_system_prompt(mirrors.get("system_prompt"), &mut ops); + self.process_system_prompt(mirrors.system_prompt.as_ref(), &mut ops); for record in updates.records { self.process_update(&record.value, record.end_offset, event, ctx, &mut ops); } - let events_complete = self.process_event_enrichment(mirrors.get("events"), &mut ops); + let events_complete = self.process_event_enrichment(mirrors.events.as_ref(), &mut ops); Ok((ops, updates_complete && events_complete)) } @@ -1314,23 +1390,16 @@ fn add_first_llm_input_metadata( } } -fn read_text_snapshot(reference: Option<&Value>) -> anyhow::Result> { +fn read_text_snapshot(reference: Option<&Reference>) -> anyhow::Result> { let Some(reference) = reference else { return Ok(None); }; - let Some(path) = reference - .get("mirror") - .and_then(Value::as_str) - .or_else(|| reference.get("path").and_then(Value::as_str)) - else { + let Some(path) = reference.read_path() else { return Ok(None); }; let mut file = std::fs::File::open(path)?; let file_len = file.metadata()?.len(); - let through = reference - .get("through") - .and_then(Value::as_u64) - .unwrap_or(file_len); + let through = reference.through.unwrap_or(file_len); anyhow::ensure!( file_len >= through, "Grok system prompt mirror {path} is shorter than captured boundary {through}" @@ -1346,7 +1415,7 @@ fn read_text_snapshot(reference: Option<&Value>) -> anyhow::Result, + reference: Option<&Reference>, cursor: &TranscriptCursor, ) -> anyhow::Result { let Some(reference) = reference else { @@ -1357,11 +1426,7 @@ fn read_new_records( reset: false, }); }; - let Some(path) = reference - .get("mirror") - .and_then(Value::as_str) - .or_else(|| reference.get("path").and_then(Value::as_str)) - else { + let Some(path) = reference.read_path() else { return Ok(TranscriptBatch { cursor: cursor.clone(), records: Vec::new(), @@ -1370,7 +1435,7 @@ fn read_new_records( }); }; - let captured_through = reference.get("through").and_then(Value::as_u64); + let captured_through = reference.through; let mut file = match std::fs::File::open(path) { Ok(file) => file, Err(error) @@ -1491,15 +1556,14 @@ fn cursor_tail_matches( Ok(observed == cursor.tail) } -fn turn_key(meta: Option<&Map>, sequence: u32) -> String { - if let Some(prompt_id) = meta - .and_then(|value| value.get("promptId")) - .and_then(Value::as_str) - { +fn turn_key(meta: Option<&NativeMeta>, sequence: u32) -> String { + if let Some(prompt_id) = meta.and_then(|value| value.prompt_id.as_deref()) { return format!("prompt:{prompt_id}"); } - if let Some(prompt_index) = meta.and_then(|value| value.get("promptIndex")) { - return format!("prompt-index:{prompt_index}"); + if let Some(index) = meta.and_then(|value| value.prompt_index.as_ref()) { + if let Ok(index) = serde_json::to_string(index) { + return format!("prompt-index:{index}"); + } } format!("sequence:{sequence}") } @@ -1517,23 +1581,20 @@ fn identities_differ( ) } -fn record_ts_ms(record: &Value) -> Option { +fn record_ts_ms(record: &NativeRecord) -> Option { record - .pointer("/params/_meta/agentTimestampMs") - .and_then(Value::as_i64) + .params + .as_ref() + .and_then(|params| params.meta.as_ref()) + .and_then(|meta| meta.agent_timestamp_ms) .or_else(|| { record - .get("ts") - .and_then(Value::as_str) + .ts + .as_deref() .and_then(|ts| chrono::DateTime::parse_from_rfc3339(ts).ok()) .map(|ts| ts.timestamp_millis()) }) - .or_else(|| { - record - .get("timestamp") - .and_then(Value::as_i64) - .map(|seconds| seconds.saturating_mul(1000)) - }) + .or_else(|| record.timestamp.map(|seconds| seconds.saturating_mul(1000))) } fn content_value(content: &Value) -> Value { @@ -1543,30 +1604,42 @@ fn content_value(content: &Value) -> Value { .unwrap_or_else(|| content.clone()) } -fn usage_metrics(usage: &Value) -> Value { +fn usage_metrics(usage: &NativeUsage) -> Value { let mut metrics = Map::new(); - for (native, common) in [ - ("inputTokens", "prompt_tokens"), - ("outputTokens", "completion_tokens"), - ("totalTokens", "tokens"), - ("cachedReadTokens", "prompt_cached_tokens"), - ("cacheCreationTokens", "prompt_cache_creation_tokens"), - ("reasoningTokens", "completion_reasoning_tokens"), - ("apiDurationMs", "api_duration_ms"), - ("costUsdTicks", "cost_usd_ticks"), - ("modelCalls", "model_calls"), - ] { - if let Some(value) = usage.get(native) { - metrics.insert(common.into(), value.clone()); - } + if let Some(value) = &usage.input_tokens { + metrics.insert("prompt_tokens".into(), json!(value)); + } + if let Some(value) = &usage.output_tokens { + metrics.insert("completion_tokens".into(), json!(value)); + } + if let Some(value) = &usage.total_tokens { + metrics.insert("tokens".into(), json!(value)); + } + if let Some(value) = &usage.cached_read_tokens { + metrics.insert("prompt_cached_tokens".into(), json!(value)); + } + if let Some(value) = &usage.cache_creation_tokens { + metrics.insert("prompt_cache_creation_tokens".into(), json!(value)); + } + if let Some(value) = &usage.reasoning_tokens { + metrics.insert("completion_reasoning_tokens".into(), json!(value)); + } + if let Some(value) = &usage.api_duration_ms { + metrics.insert("api_duration_ms".into(), json!(value)); + } + if let Some(value) = &usage.cost_usd_ticks { + metrics.insert("cost_usd_ticks".into(), json!(value)); + } + if let Some(value) = &usage.model_calls { + metrics.insert("model_calls".into(), json!(value)); } Value::Object(metrics) } /// Grok's readable failure text is in ACP `content`; `rawOutput` is its /// serialized `ToolOutput` enum, which only carries text in a variant payload. -fn tool_failure_text(update: &Value) -> Option { - let raw = update.get("rawOutput"); +fn tool_failure_text(update: &NativeUpdate) -> Option { + let raw = update.raw_output.as_ref(); if let Some(raw) = raw.filter(|raw| raw["type"] == "Bash") { if raw["timed_out"] == true { return Some("Command timed out".into()); @@ -1575,7 +1648,7 @@ fn tool_failure_text(update: &Value) -> Option { return Some(format!("Command terminated by signal {signal}")); } } - if let Some(text) = update.get("content").and_then(nonempty_error_text) { + if let Some(text) = update.content.as_ref().and_then(nonempty_error_text) { return Some(text); } let raw = raw?; diff --git a/bt-daemon/src/translate/opencode.rs b/bt-daemon/src/translate/opencode.rs index 8cfd5303..fcd64dec 100644 --- a/bt-daemon/src/translate/opencode.rs +++ b/bt-daemon/src/translate/opencode.rs @@ -10,6 +10,7 @@ use super::tool::{ use super::{ local_username, AgentTranslator, SessionCtx, SpanOp, SpanRow, SpanType, TranslatorFactory, }; +use crate::agents::usage::OpenCodeTokens as MessageTokens; use crate::ids; use crate::wire::Envelope; use serde::de::DeserializeOwned; @@ -401,26 +402,6 @@ struct MessageTime { completed: Option, } -#[derive(Clone, Default, Deserialize, Serialize)] -struct MessageTokens { - #[serde(default)] - input: i64, - #[serde(default)] - output: i64, - #[serde(default)] - reasoning: i64, - #[serde(default)] - cache: MessageCacheTokens, -} - -#[derive(Clone, Default, Deserialize, Serialize)] -struct MessageCacheTokens { - #[serde(default)] - read: i64, - #[serde(default)] - write: i64, -} - fn decode(value: &Value) -> Option { serde_json::from_value(value.clone()).ok() } diff --git a/bt-daemon/src/translate/opencode_v2/event.rs b/bt-daemon/src/translate/opencode_v2/event.rs index e1b1b094..953d9fab 100644 --- a/bt-daemon/src/translate/opencode_v2/event.rs +++ b/bt-daemon/src/translate/opencode_v2/event.rs @@ -1,5 +1,7 @@ //! Partial OpenCode 2 wire types. Unknown fields are accepted; arbitrary tool //! inputs, outputs and provider-specific content remain JSON values. +pub(super) use crate::agents::usage::OpenCodeTokens as Tokens; +use crate::json::{Extensions, Field}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -153,24 +155,6 @@ pub(super) struct StepEnded { pub tokens: Option, pub error: Option, } -#[derive(Default, Deserialize, Serialize)] -pub(super) struct Tokens { - #[serde(default)] - pub input: i64, - #[serde(default)] - pub output: i64, - #[serde(default)] - pub reasoning: i64, - #[serde(default)] - pub cache: CacheTokens, -} -#[derive(Default, Deserialize, Serialize)] -pub(super) struct CacheTokens { - #[serde(default)] - pub read: i64, - #[serde(default)] - pub write: i64, -} #[derive(Deserialize)] pub(super) struct TextEnded { #[serde(rename = "sessionID")] @@ -339,19 +323,48 @@ pub(super) struct ContextMessage { pub role: String, pub content: MessageContent, } -#[derive(Deserialize, Serialize)] +#[derive(Serialize)] #[serde(untagged)] pub(super) enum MessageContent { Text(String), Parts(Vec), Other(Value), } -#[derive(Deserialize, Serialize)] +#[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 { @@ -359,12 +372,18 @@ pub(super) enum KnownContextPart { Text { text: String }, #[serde(rename = "media")] Media { - #[serde(rename = "mediaType")] - media_type: Option, - data: Option, - media: Option, - #[serde(flatten)] - extra: serde_json::Map, + #[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 { @@ -377,19 +396,44 @@ pub(super) enum KnownContextPart { } #[derive(Clone, Deserialize, Serialize)] pub(super) struct Media { - pub source: Option, - #[serde(flatten)] - pub extra: serde_json::Map, + #[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(rename = "mediaType")] - pub media_type: Option, - pub data: Option, - #[serde(flatten)] - pub extra: serde_json::Map, + #[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/pi.rs b/bt-daemon/src/translate/pi.rs index 8ca849e9..08e38bb6 100644 --- a/bt-daemon/src/translate/pi.rs +++ b/bt-daemon/src/translate/pi.rs @@ -9,6 +9,8 @@ use super::tool::{ 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; @@ -149,37 +151,6 @@ struct AssistantMessage { provider_thinking_level: Option, } -#[derive(Default, Deserialize)] -#[serde(rename_all = "camelCase")] -#[derive(Serialize)] -struct Usage { - #[serde(default)] - input: i64, - #[serde(default)] - output: i64, - // Pi reports `reasoning` as a subset of `output`, and only for providers - // that expose the breakdown. - #[serde(default)] - reasoning: Option, - #[serde(default)] - cache_read: i64, - // `cacheWrite1h` is the subset of `cacheWrite` written with 1h retention. - #[serde(default)] - cache_write: i64, - #[serde(default)] - cache_write1h: Option, - #[serde(default)] - total_tokens: Option, - #[serde(default)] - cost: Option, -} - -#[derive(Default, Deserialize, Serialize)] -struct Cost { - #[serde(default)] - total: Option, -} - #[derive(Deserialize)] #[serde(tag = "type")] #[derive(Serialize)] @@ -197,9 +168,9 @@ enum AssistantContent { #[serde(rename = "toolCall")] ToolCall { #[serde(default)] - id: Option, + id: Option, #[serde(default)] - name: Option, + name: Option, #[serde(default)] arguments: Option, }, @@ -259,11 +230,11 @@ struct SessionCompact { #[derive(Serialize)] struct CompactionEntry { #[serde(default)] - summary: Option, + summary: Option, #[serde(default)] - tokens_before: Option, + tokens_before: Option, #[serde(default)] - timestamp: Option, + timestamp: Option, } #[derive(Default, Deserialize)] @@ -271,29 +242,29 @@ struct CompactionEntry { #[derive(Serialize)] struct Preparation { #[serde(default)] - tokens_before: Option, + tokens_before: Option, #[serde(default)] - first_kept_entry_id: Option, + first_kept_entry_id: Option, #[serde(default)] - is_split_turn: Option, + is_split_turn: Option, #[serde(default)] messages_to_summarize: Option>, #[serde(default)] turn_prefix_messages: Option>, #[serde(default)] - target_id: Option, + target_id: Option, #[serde(default)] - old_leaf_id: Option, + old_leaf_id: Option, #[serde(default)] - common_ancestor_id: Option, + common_ancestor_id: Option, #[serde(default)] user_wants_summary: Option, #[serde(default)] - custom_instructions: Option, + custom_instructions: Option, #[serde(default)] - replace_instructions: Option, + replace_instructions: Option, #[serde(default)] - label: Option, + label: Option, #[serde(default)] entries_to_summarize: Option>, } @@ -303,11 +274,11 @@ struct Preparation { #[derive(Serialize)] struct BeforeCompact { #[serde(default)] - reason: Option, + reason: Option, #[serde(default)] - will_retry: Option, + will_retry: Option, #[serde(default)] - custom_instructions: Option, + custom_instructions: Option, #[serde(default)] preparation: Option, #[serde(default)] @@ -338,7 +309,7 @@ struct PendingLlm { start_ms: i64, input: Value, first_token_ms: Option, - request_config: Map, + request_config: RequestConfig, selected_model: Option, } #[derive(Clone, Serialize, Deserialize)] @@ -407,8 +378,9 @@ impl AgentTranslator for PiTranslator { } "before_provider_request" => { if let Some(call) = self.pending_llms.last_mut() { - call.request_config = - request_config(event.get("payload").unwrap_or(&Value::Null)); + call.request_config = serde_json::from_value(Value::Object(request_config( + event.get("payload").unwrap_or(&Value::Null), + )))?; } } "message_update" => { @@ -531,7 +503,7 @@ impl PiTranslator { end_ms: Some(ts), input: Some(pending.input), metadata: (!pending.request_config.is_empty()) - .then_some(Value::Object(pending.request_config)), + .then(|| json!(pending.request_config)), error: Some(error.into()), ..Default::default() })); @@ -751,7 +723,7 @@ impl PiTranslator { start_ms: ts, input, first_token_ms: None, - request_config: Map::new(), + request_config: RequestConfig::default(), selected_model, }); } @@ -786,7 +758,7 @@ impl PiTranslator { start_ms: ts, input: json!([]), first_token_ms: None, - request_config: Map::new(), + request_config: RequestConfig::default(), selected_model: None, } } else { @@ -819,17 +791,20 @@ impl PiTranslator { || message.model.as_deref() != Some(&selected.id) }) .map(|selected| format!("{}/{}", selected.provider, selected.id)); - let mut metadata = pending.request_config; - if let Value::Object(fields) = without_nulls(json!({ - "model": model, - "provider": message.provider, - "api": message.api, - "stop_reason": message.stop_reason, - "thinking_level": message.thinking_level.as_ref().or(self.thinking_level.as_ref()), - "provider_thinking_level": message.provider_thinking_level, - "selected_model": selected_model, - "response_id": message.response_id, - })) { + let mut metadata = json!(pending.request_config); + if let (Value::Object(metadata), Value::Object(fields)) = ( + &mut metadata, + without_nulls(json!({ + "model": model, + "provider": message.provider, + "api": message.api, + "stop_reason": message.stop_reason, + "thinking_level": message.thinking_level.as_ref().or(self.thinking_level.as_ref()), + "provider_thinking_level": message.provider_thinking_level, + "selected_model": selected_model, + "response_id": message.response_id, + })), + ) { metadata.extend(fields); } // Pi prices unknown models at zero, which would override the backend's @@ -853,7 +828,7 @@ impl PiTranslator { end_ms: Some(ts), input: Some(pending.input), output: Some(json!([output])), - metadata: Some(Value::Object(metadata)), + metadata: Some(metadata), metrics: Some(without_nulls(json!({ "prompt_tokens": prompt, "completion_tokens": completion, @@ -1059,29 +1034,31 @@ struct LegacyContinuation { } fn legacy_continuation(payload: &Value) -> Option { - let value = payload.get("legacy_resume")?; - let root_span_id = value.get("span")?.as_str()?.to_owned(); - if root_span_id.is_empty() { + #[derive(Deserialize)] + struct ResumePayload { + legacy_resume: Option, + } + #[derive(Deserialize)] + struct Resume { + span: String, + trace: Option, + parent: Option, + turns: u32, + tools: u32, + } + let resume = decode::(payload)?.legacy_resume?; + if resume.span.is_empty() { return None; } - let trace_root_span_id = value - .get("trace") - .and_then(Value::as_str) - .filter(|id| !id.is_empty()) - .unwrap_or(&root_span_id) - .to_owned(); - let total_turns = u32::try_from(value.get("turns")?.as_u64()?).ok()?; - let total_tool_calls = u32::try_from(value.get("tools")?.as_u64()?).ok()?; Some(LegacyContinuation { - root_span_id, - trace_root_span_id, - parent_span_id: value - .get("parent") - .and_then(Value::as_str) + trace_root_span_id: resume + .trace .filter(|id| !id.is_empty()) - .map(str::to_owned), - total_turns, - total_tool_calls, + .unwrap_or_else(|| resume.span.clone()), + root_span_id: resume.span, + parent_span_id: resume.parent.filter(|id| !id.is_empty()), + total_turns: resume.turns, + total_tool_calls: resume.tools, }) } @@ -1091,8 +1068,8 @@ fn compaction_message(event: &SessionCompact) -> Option { Some(json!({ "role": "compactionSummary", "summary": summary, - "tokensBefore": entry.tokens_before.clone().unwrap_or(Value::Null), - "timestamp": entry.timestamp.clone().unwrap_or(Value::Null), + "tokensBefore": entry.tokens_before, + "timestamp": entry.timestamp, })) } @@ -1102,9 +1079,9 @@ fn compaction_input(event: &BeforeCompact) -> Value { "reason": event.reason.clone(), "willRetry": event.will_retry.clone(), "customInstructions": event.custom_instructions.clone(), - "tokensBefore": preparation.and_then(|value| value.tokens_before.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.clone()), + "isSplitTurn": preparation.and_then(|value| value.is_split_turn), "messagesToSummarizeCount": preparation .and_then(|value| value.messages_to_summarize.as_ref()) .map(Vec::len), @@ -1123,7 +1100,7 @@ fn branch_summary_input(event: &BeforeTree) -> Value { "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.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())