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
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());
}
}
12 changes: 5 additions & 7 deletions bt-daemon/src/translate/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -721,7 +723,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();
Expand Down Expand Up @@ -1918,12 +1920,8 @@ fn tool_input(payload: &Value) -> Value {
.unwrap_or_else(|| json!({}))
}

fn tool_output(payload: &Value) -> Option<Value> {
payload
.get("tool_response")
.or_else(|| payload.get("output"))
.cloned()
.or_else(|| payload.pointer("/tool_response/output").cloned())
fn tool_output(event: &Envelope) -> Option<Value> {
decode::<ToolCompletionHook>(&event.payload)?.into_output(event.event == "PostToolUseFailure")
}

fn tool_name(payload: &Value) -> Option<String> {
Expand Down
47 changes: 47 additions & 0 deletions bt-daemon/src/translate/claude/tool_completion_hook.rs
Original file line number Diff line number Diff line change
@@ -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<Value>,
#[serde(default)]
output: Field<Value>,
#[serde(default, deserialize_with = "deserialize_error_text")]
error: Option<String>,
}

impl ToolCompletionHook {
pub(super) fn into_output(self, failed: bool) -> Option<Value> {
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<Option<String>, 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,
})
}
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
8 changes: 6 additions & 2 deletions bt-daemon/tests/claude_translator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -1193,14 +1193,18 @@ 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),
("task-stop", None),
] {
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")
Expand Down
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