From 7929867dc71e6257a4aa35934c23fc47308caa86 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 25 Nov 2026 22:17:59 +0800 Subject: [PATCH 1/4] Preserve full Claude tool failure output --- bt-daemon/src/translate/claude.rs | 15 ++++++++++++--- bt-daemon/tests/claude_translator.rs | 8 ++++++-- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/bt-daemon/src/translate/claude.rs b/bt-daemon/src/translate/claude.rs index 66db8853..b97f8ae1 100644 --- a/bt-daemon/src/translate/claude.rs +++ b/bt-daemon/src/translate/claude.rs @@ -721,7 +721,7 @@ impl ClaudeTranslator { let call_id = self.call_id(event); self.pending_nested_spawns.remove(&call_id); let input = tool_input(&event.payload); - let output = tool_output(&event.payload); + let output = tool_output(event); let error = (approval != ToolApproval::Denied) .then(|| forced_error.or_else(|| tool_error(&event.payload))) .flatten(); @@ -1918,12 +1918,21 @@ fn tool_input(payload: &Value) -> Value { .unwrap_or_else(|| json!({})) } -fn tool_output(payload: &Value) -> Option { +fn tool_output(event: &Envelope) -> Option { + let payload = &event.payload; payload .get("tool_response") .or_else(|| payload.get("output")) .cloned() - .or_else(|| payload.pointer("/tool_response/output").cloned()) + .or_else(|| { + if event.event != "PostToolUseFailure" { + return None; + } + payload + .get("error") + .filter(|value| value.as_str().is_some_and(|text| !text.trim().is_empty())) + .cloned() + }) } fn tool_name(payload: &Value) -> Option { diff --git a/bt-daemon/tests/claude_translator.rs b/bt-daemon/tests/claude_translator.rs index 39df0b2f..3c99d2b7 100644 --- a/bt-daemon/tests/claude_translator.rs +++ b/bt-daemon/tests/claude_translator.rs @@ -1152,7 +1152,7 @@ fn claude_tool_hook_outcomes_distinguish_denials_failures_and_successes() { ), event( "PostToolUseFailure", - json!({"session_id":"s","tool_name":"Read","tool_use_id":"failed","tool_input":{"file_path":"x"},"error":"missing","is_interrupt":true,"duration_ms":42}), + json!({"session_id":"s","tool_name":"Read","tool_use_id":"failed","tool_input":{"file_path":"x"},"error":"Exit code 1\nls: missing directory","is_interrupt":true,"duration_ms":42}), ), event( "PostToolUse", @@ -1193,7 +1193,7 @@ fn claude_tool_hook_outcomes_distinguish_denials_failures_and_successes() { assert_eq!(failed.start_ms, Some(1 - 42)); for (call_id, error) in [ ("denied", None), - ("failed", Some("missing")), + ("failed", Some("Exit code 1")), ("stderr-error", Some("disk full")), ("mcp-error", Some("Could not resolve issue 355")), ("stderr-success", None), @@ -1201,6 +1201,10 @@ fn claude_tool_hook_outcomes_distinguish_denials_failures_and_successes() { ] { assert_eq!(tool(call_id).error.as_deref(), error, "{call_id}"); } + assert_eq!( + tool("failed").output, + Some(json!("Exit code 1\nls: missing directory")) + ); assert_eq!( tool("stderr-success").output.as_ref().unwrap()["stdout"], json!("/tmp") From a30d590e37340a87366fd35910887cbfbb182f5a Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 25 Nov 2026 23:26:20 +0800 Subject: [PATCH 2/4] Serialize legacy journal migration during capture and recovery --- bt-daemon/src/collections/legacy.rs | 34 +++++++++++++++++++++-------- bt-daemon/src/collections/tests.rs | 27 +++++++++++++++++++++++ 2 files changed, 52 insertions(+), 9 deletions(-) diff --git a/bt-daemon/src/collections/legacy.rs b/bt-daemon/src/collections/legacy.rs index 60853be3..43564bfd 100644 --- a/bt-daemon/src/collections/legacy.rs +++ b/bt-daemon/src/collections/legacy.rs @@ -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, @@ -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?; @@ -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?; } diff --git a/bt-daemon/src/collections/tests.rs b/bt-daemon/src/collections/tests.rs index e3de1129..1974cc99 100644 --- a/bt-daemon/src/collections/tests.rs +++ b/bt-daemon/src/collections/tests.rs @@ -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()); + } +} From 009278a8a0f80eadc16e97616e92ec77fb3bbdac Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 25 Nov 2026 23:26:20 +0800 Subject: [PATCH 3/4] Keep Pi tracing compatible with Oh My Pi 19.2 --- bt-daemon/tests/agent_integration.rs | 7 +++++++ .../pi/content/src/daemon-adapter.test.ts | 18 ++++++------------ src/plugins/pi/content/src/index.ts | 18 ++++++------------ src/plugins/pi/content/src/pi-tui.ts | 18 ++++++++++++++++++ 4 files changed, 37 insertions(+), 24 deletions(-) create mode 100644 src/plugins/pi/content/src/pi-tui.ts diff --git a/bt-daemon/tests/agent_integration.rs b/bt-daemon/tests/agent_integration.rs index df5a5787..b26d3309 100644 --- a/bt-daemon/tests/agent_integration.rs +++ b/bt-daemon/tests/agent_integration.rs @@ -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", diff --git a/src/plugins/pi/content/src/daemon-adapter.test.ts b/src/plugins/pi/content/src/daemon-adapter.test.ts index fc081359..6a189f93 100644 --- a/src/plugins/pi/content/src/daemon-adapter.test.ts +++ b/src/plugins/pi/content/src/daemon-adapter.test.ts @@ -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(); - 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, diff --git a/src/plugins/pi/content/src/index.ts b/src/plugins/pi/content/src/index.ts index 96525040..21d82e68 100644 --- a/src/plugins/pi/content/src/index.ts +++ b/src/plugins/pi/content/src/index.ts @@ -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"; @@ -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; +async function terminalHyperlink(text: string, url: string): Promise { + const { getCapabilities, hyperlink } = await loadPiHyperlinkHelpers(PI_HOST_NAME); if (typeof getCapabilities !== "function" || typeof hyperlink !== "function") return undefined; return getCapabilities().hyperlinks ? hyperlink(text, url) : undefined; } @@ -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); }; diff --git a/src/plugins/pi/content/src/pi-tui.ts b/src/plugins/pi/content/src/pi-tui.ts new file mode 100644 index 00000000..6f9ecb53 --- /dev/null +++ b/src/plugins/pi/content/src/pi-tui.ts @@ -0,0 +1,18 @@ +type PiTui = typeof import("@earendil-works/pi-tui"); +type HyperlinkHelpers = Pick; + +/** Pi's UI helpers are optional for a tracing extension and unavailable in Oh My Pi. */ +export async function loadPiHyperlinkHelpers( + host: string | undefined, +): Promise> { + 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 {}; + } +} From 665278a681965bd82bc338844c6463fb92e7965c Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 26 Nov 2026 00:28:13 +0800 Subject: [PATCH 4/4] Read Claude tool failure output through a typed hook --- bt-daemon/src/translate/claude.rs | 17 ++----- .../translate/claude/tool_completion_hook.rs | 47 +++++++++++++++++++ 2 files changed, 50 insertions(+), 14 deletions(-) create mode 100644 bt-daemon/src/translate/claude/tool_completion_hook.rs diff --git a/bt-daemon/src/translate/claude.rs b/bt-daemon/src/translate/claude.rs index b97f8ae1..b7f10e37 100644 --- a/bt-daemon/src/translate/claude.rs +++ b/bt-daemon/src/translate/claude.rs @@ -14,6 +14,7 @@ mod native_field; mod parsed_transcript; mod subagent_hook; mod timestamp_envelope; +mod tool_completion_hook; mod transcript_envelope; mod transcript_tool; mod transcript_tool_outcome; @@ -26,6 +27,7 @@ use subagent_hook::SubagentHook; #[cfg(test)] use timestamp_envelope::parse_rfc3339_timestamp; use timestamp_envelope::parse_timestamp_ms; +use tool_completion_hook::ToolCompletionHook; use transcript_envelope::TranscriptEnvelope; use transcript_tool::TranscriptTool; @@ -1919,20 +1921,7 @@ fn tool_input(payload: &Value) -> Value { } fn tool_output(event: &Envelope) -> Option { - let payload = &event.payload; - payload - .get("tool_response") - .or_else(|| payload.get("output")) - .cloned() - .or_else(|| { - if event.event != "PostToolUseFailure" { - return None; - } - payload - .get("error") - .filter(|value| value.as_str().is_some_and(|text| !text.trim().is_empty())) - .cloned() - }) + decode::(&event.payload)?.into_output(event.event == "PostToolUseFailure") } fn tool_name(payload: &Value) -> Option { diff --git a/bt-daemon/src/translate/claude/tool_completion_hook.rs b/bt-daemon/src/translate/claude/tool_completion_hook.rs new file mode 100644 index 00000000..83938ba9 --- /dev/null +++ b/bt-daemon/src/translate/claude/tool_completion_hook.rs @@ -0,0 +1,47 @@ +use crate::json::Field; +use serde::{Deserialize, Deserializer}; +use serde_json::Value; + +#[derive(Deserialize)] +pub(super) struct ToolCompletionHook { + // Tool results have a tool-specific shape and are emitted as span output. + #[serde(default)] + tool_response: Field, + #[serde(default)] + output: Field, + #[serde(default, deserialize_with = "deserialize_error_text")] + error: Option, +} + +impl ToolCompletionHook { + pub(super) fn into_output(self, failed: bool) -> Option { + let output = if self.tool_response.is_missing() { + self.output + } else { + self.tool_response + }; + match output { + Field::Value(value) => Some(value), + Field::Null => Some(Value::Null), + Field::Missing if failed => self + .error + .filter(|error| !error.trim().is_empty()) + .map(Value::String), + Field::Missing => None, + } + } +} + +fn deserialize_error_text<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Error { + Text(String), + Other(serde::de::IgnoredAny), + } + + Ok(match Error::deserialize(d)? { + Error::Text(text) => Some(text), + Error::Other(_) => None, + }) +}