Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions bt-daemon/src/agents/usage/snake_case_usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ pub(crate) struct TokenDetails {
pub cache_write_tokens: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning_tokens: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thinking_tokens: Option<u64>,
#[serde(flatten, deserialize_with = "crate::json::deserialize_extensions")]
pub extra: Extensions,
}
Expand Down
34 changes: 25 additions & 9 deletions bt-daemon/src/collections/legacy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ const IMPORT_RECORDS: usize = 1024;
const IMPORT_BYTES: usize = 8 * 1024 * 1024;
const PI_MESSAGES_DELTA: &str = "_bt_messages_delta";

// Recovery and live capture can both discover a legacy journal. Serialize
// reading, committing and removing those files. Modern sessions bypass this.
static IMPORT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// Import any legacy journals that hold records for this source session.
pub(super) async fn import_session(
data_dir: &Path,
Expand All @@ -30,14 +34,19 @@ pub(super) async fn import_session(
events: &SessionStorage,
) -> anyhow::Result<()> {
let unqualified = journal_path(data_dir, session_id);
if unqualified
let unqualified_supported = unqualified
.file_name()
.is_some_and(|name| name.len() <= crate::journal::MAX_FILE_NAME_BYTES)
&& tokio::fs::try_exists(&unqualified).await?
.is_some_and(|name| name.len() <= crate::journal::MAX_FILE_NAME_BYTES);
let qualified = source_journal_path(data_dir, source, session_id);
if !(unqualified_supported && tokio::fs::try_exists(&unqualified).await?)
&& !tokio::fs::try_exists(&qualified).await?
{
return Ok(());
}
let _guard = IMPORT_LOCK.lock().await;
if unqualified_supported && tokio::fs::try_exists(&unqualified).await? {
import_unqualified(data_dir, &unqualified).await?;
}
let qualified = source_journal_path(data_dir, source, session_id);
if tokio::fs::try_exists(&qualified).await? {
import_file(&qualified, source, events, None).await?;
tokio::fs::remove_file(&qualified).await?;
Expand All @@ -57,11 +66,18 @@ pub(crate) async fn import_all(data_dir: &Path) {
continue;
}
let result = async {
let owners = sessions(&path).await?;
if owners.is_empty() {
// Nothing was ever acknowledged from a file without events.
tokio::fs::remove_file(&path).await?;
}
let owners = {
let _guard = IMPORT_LOCK.lock().await;
if !tokio::fs::try_exists(&path).await? {
return Ok(());
}
let owners = sessions(&path).await?;
if owners.is_empty() {
// Nothing was ever acknowledged from a file without events.
tokio::fs::remove_file(&path).await?;
}
owners
};
for (source, session_id) in owners {
SessionStorage::open(data_dir, &source, &session_id).await?;
}
Expand Down
27 changes: 27 additions & 0 deletions bt-daemon/src/collections/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,3 +434,30 @@ async fn compaction_returns_deleted_space_to_the_file_system() {
assert_eq!(pragma("freelist_count"), 0);
assert!(size() < bloated / 4, "{} of {bloated} bytes remain", size());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn simultaneous_legacy_open_preserves_capture() {
for qualified in [true, false] {
let temp = tempfile::tempdir().unwrap();
let path = if qualified {
source_journal_path(temp.path(), "debug", "session")
} else {
journal_path(temp.path(), "session")
};
let record = line(
&json!({"source":"debug","session_id":"session","event":"e","ts_ms":1,"payload":{}}),
);
write_legacy(&path, &record).await;
let outcomes = futures::future::join_all(
(0..16).map(|_| SessionStorage::open(temp.path(), "debug", "session")),
)
.await;
for storage in outcomes {
assert_eq!(
storage.unwrap().status().await.unwrap().event_tail,
record.len() as u64
);
}
assert!(!path.exists());
}
}
43 changes: 38 additions & 5 deletions bt-daemon/src/translate/claude/llm_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ pub(super) struct LlmCall {
end_ms: i64,
input: Vec<Value>,
text: Vec<String>,
#[serde(default)]
thinking: Vec<String>,
#[serde(default)]
reasoning_tokens: Option<u64>,
tool_calls: Vec<Value>,
prompt_tokens: u64,
completion_tokens: u64,
Expand All @@ -40,6 +44,8 @@ impl LlmCall {
end_ms: start_ms,
input,
text: Vec::new(),
thinking: Vec::new(),
reasoning_tokens: None,
tool_calls: Vec::new(),
prompt_tokens: 0,
completion_tokens: 0,
Expand Down Expand Up @@ -92,6 +98,19 @@ impl LlmCall {
}
}
}
Some("thinking") => {
#[derive(Deserialize)]
struct ThinkingBlock<'a> {
thinking: &'a str,
}
if let Ok(block) = ThinkingBlock::deserialize(block) {
if !block.thinking.is_empty()
&& !self.thinking.iter().any(|seen| seen == block.thinking)
{
self.thinking.push(block.thinking.to_owned());
}
}
}
Some("tool_use") => {
let arguments =
serde_json::to_string(block.get("input").unwrap_or(&Value::Null))
Expand Down Expand Up @@ -126,6 +145,15 @@ impl LlmCall {
{
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));
if let Some(tokens) = usage
.output_tokens_details
.and_then(|details| details.thinking_tokens)
{
self.reasoning_tokens = Some(
self.reasoning_tokens
.map_or(tokens, |prev| prev.max(tokens)),
);
}
self.cache_creation_tokens = self
.cache_creation_tokens
.max(usage.cache_creation_input_tokens.unwrap_or(0));
Expand All @@ -144,12 +172,14 @@ impl LlmCall {
}

pub(super) fn output_message(&self) -> Value {
let content = self.text.join("\n");
if self.tool_calls.is_empty() {
json!({ "role": "assistant", "content": content })
} else {
json!({ "role": "assistant", "content": content, "tool_calls": self.tool_calls })
let mut output = json!({ "role": "assistant", "content": self.text.join("\n") });
if !self.tool_calls.is_empty() {
output["tool_calls"] = json!(self.tool_calls);
}
if !self.thinking.is_empty() {
output["reasoning"] = json!([{"id":"reasoning","content":self.thinking.join("\n")}]);
}
output
}

pub(super) fn into_row(self, span_id: String, root_span_id: String, parent: String) -> SpanRow {
Expand All @@ -164,6 +194,9 @@ impl LlmCall {
metrics.insert("prompt_tokens".into(), json!(prompt));
metrics.insert("completion_tokens".into(), json!(self.completion_tokens));
metrics.insert("tokens".into(), json!(prompt + self.completion_tokens));
if let Some(tokens) = self.reasoning_tokens {
metrics.insert("completion_reasoning_tokens".into(), json!(tokens));
}
metrics.insert("prompt_cached_tokens".into(), json!(self.cache_read_tokens));
if has_split {
metrics.insert(
Expand Down
7 changes: 7 additions & 0 deletions bt-daemon/tests/agent_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,13 @@ async fn pi_session_emits_traces() {
if request.has_function_output("call_pi_1") {
return MockReply::response(OpenAiTurn::text("PI_MOCK_OK"));
}
// Oh My Pi sends auxiliary requests without tools to the same
// provider before the actual prompt. Only drive the shell turn when
// tools are offered. The assertions below still require the tool
// call, its result, and their delivered trace.
if request.tool_names().is_empty() {
return MockReply::response(OpenAiTurn::text("Integration test"));
}
MockReply::response(shell_tool_call(
&request,
"call_pi_1",
Expand Down
47 changes: 47 additions & 0 deletions bt-daemon/tests/claude_translator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3108,3 +3108,50 @@ fn claude_expansion_before_submit_reaches_the_incoming_turn_while_another_is_ope
let skill = tool_span(&rows, "review").metadata.as_ref().unwrap();
assert_eq!(skill["skill_load_trigger"], json!("explicit"));
}

#[test]
fn claude_preserves_reported_thinking_without_double_counting_tokens() {
let records = [
json!({"type":"assistant","message":{"id":"first","content":[{"type":"thinking","thinking":"Check the file."},{"type":"text","text":"done"}],"usage":{"input_tokens":2,"output_tokens":10,"output_tokens_details":{"thinking_tokens":4}}}}),
json!({"type":"assistant","message":{"id":"second","content":[{"type":"thinking","signature":"opaque"},{"type":"text","text":"answer"}],"usage":{"output_tokens":3,"output_tokens_details":{"thinking_tokens":0}}}}),
];
let transcript = records
.iter()
.map(|row| format!("{row}\n"))
.collect::<String>();
let rows = replay_continuation_events(
vec![
("UserPromptSubmit", 10, json!({"prompt":"answer"})),
(
"Stop",
30,
json!({"transcript_path":"main.jsonl","_bt_transcript_snapshot":{"path":"main.jsonl","contents":transcript}}),
),
],
false,
);
let call = |id| {
rows.values()
.find(|row| {
row.metadata
.as_ref()
.and_then(|metadata| metadata.get("request_id"))
== Some(&json!(id))
})
.unwrap()
};
let first = call("first");
let thinking = json!([{"id":"reasoning","content":"Check the file."}]);
assert_eq!(first.output.as_ref().unwrap()["reasoning"], thinking);
let metrics = first.metrics.as_ref().unwrap();
assert_eq!(metrics["completion_reasoning_tokens"], 4);
assert_eq!(metrics["completion_tokens"], 10);
assert_eq!(metrics["tokens"], 12);
let second = call("second");
assert_eq!(second.input.as_ref().unwrap()[0]["reasoning"], thinking);
assert!(second.output.as_ref().unwrap().get("reasoning").is_none());
assert_eq!(
second.metrics.as_ref().unwrap()["completion_reasoning_tokens"],
0
);
}
18 changes: 6 additions & 12 deletions src/plugins/pi/content/src/daemon-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,12 @@ const mockState = vi.hoisted(() => ({
permalink: "https://www.braintrust.dev/trace/1" as string | undefined,
}));

vi.mock("@earendil-works/pi-tui", async (importOriginal) => {
const original = await importOriginal<typeof import("@earendil-works/pi-tui")>();
return {
...original,
get getCapabilities() {
return mockState.ompTui ? undefined : () => ({ hyperlinks: mockState.hyperlinks });
},
get hyperlink() {
return mockState.ompTui ? undefined : original.hyperlink;
},
};
});
vi.mock("./pi-tui.ts", () => ({
loadPiHyperlinkHelpers: async () =>
mockState.ompTui
? {}
: { getCapabilities: () => ({ hyperlinks: mockState.hyperlinks }), hyperlink },
}));

vi.mock("./runtime/daemon-client.ts", () => ({
claimManagedTracingInstance: () => mockState.claim,
Expand Down
18 changes: 6 additions & 12 deletions src/plugins/pi/content/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { createHash, randomUUID } from "node:crypto";
import { resolve } from "node:path";
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
import * as piTui from "@earendil-works/pi-tui";
import { loadConfig } from "./config.ts";
import { legacyContinuationFor, type LegacyContinuation } from "./legacy-session.ts";
import { runningPiPackage } from "./pi-package.ts";
import { loadPiHyperlinkHelpers } from "./pi-tui.ts";
import { claimManagedTracingInstance, DaemonClient } from "./runtime/daemon-client.ts";
import { EXTENSION_VERSION } from "./version.ts";

Expand All @@ -18,13 +18,8 @@ const TRACE_LINK_POLL_TIMEOUT_MS = 40_000;
const PI_VERSION = runningPiPackage().version;
const PI_HOST_NAME = runningPiPackage().name;

/**
* Oh My Pi resolves this package to its own pi-tui, which exports neither
* helper. A named import would fail to link and OMP would silently drop the
* extension, so read them from the namespace and fall back to plain text.
*/
function terminalHyperlink(text: string, url: string): string | undefined {
const { getCapabilities, hyperlink } = piTui as Partial<typeof piTui>;
async function terminalHyperlink(text: string, url: string): Promise<string | undefined> {
const { getCapabilities, hyperlink } = await loadPiHyperlinkHelpers(PI_HOST_NAME);
if (typeof getCapabilities !== "function" || typeof hyperlink !== "function") return undefined;
return getCapabilities().hyperlinks ? hyperlink(text, url) : undefined;
}
Expand Down Expand Up @@ -149,10 +144,9 @@ export default function braintrustPiExtension(pi: ExtensionAPI): void {
if (daemonSession?.last_error) {
ctx.ui.setStatus(STATUS_KEY, `Braintrust: ${daemonSession.last_error}`);
} else {
ctx.ui.setStatus(
STATUS_KEY,
(permalink && terminalHyperlink(traceLabel, permalink)) || "Braintrust: connected",
);
const label = permalink ? await terminalHyperlink(traceLabel, permalink) : undefined;
if (uiGeneration !== refreshGeneration || sessionId !== refreshSessionId) return;
ctx.ui.setStatus(STATUS_KEY, label ?? "Braintrust: connected");
}
traceLinkShown = Boolean(permalink);
};
Expand Down
18 changes: 18 additions & 0 deletions src/plugins/pi/content/src/pi-tui.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
type PiTui = typeof import("@earendil-works/pi-tui");
type HyperlinkHelpers = Pick<PiTui, "getCapabilities" | "hyperlink">;

/** Pi's UI helpers are optional for a tracing extension and unavailable in Oh My Pi. */
export async function loadPiHyperlinkHelpers(
host: string | undefined,
): Promise<Partial<HyperlinkHelpers>> {
if (host === "@oh-my-pi/pi-coding-agent") return {};
try {
// Resolve only in the Pi UI path. Oh My Pi rejects package imports of
// the old TUI at extension load time, including literal dynamic imports.
const url = import.meta.resolve("@earendil-works/pi-tui");
return (await import(url)) as PiTui;
} catch {
// Some hosts supply the extension API without Pi's optional UI helpers.
return {};
}
}
Loading