From cc6c3e3406523d14f8d3de94f8b82da215a47795 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 25 Nov 2026 22:14:47 +0800 Subject: [PATCH 1/4] Keep Claude bookkeeping records inside imported turns --- bt-daemon/src/transcript_import/claude.rs | 66 +++++++++++++++++++++-- bt-daemon/src/transcript_import/mod.rs | 38 +++++++++++++ 2 files changed, 100 insertions(+), 4 deletions(-) diff --git a/bt-daemon/src/transcript_import/claude.rs b/bt-daemon/src/transcript_import/claude.rs index c85ffaf4..1e63e0ca 100644 --- a/bt-daemon/src/transcript_import/claude.rs +++ b/bt-daemon/src/transcript_import/claude.rs @@ -5,6 +5,7 @@ use super::{ }; use crate::wire::Envelope; use anyhow::bail; +use serde::Deserialize; use serde_json::{json, Value}; use std::collections::{HashMap, HashSet}; use std::io::BufRead; @@ -307,7 +308,16 @@ pub(super) fn envelopes( record_end_offsets[record_index], )); } - let error = last_assistant_error(segment); + let error = if segment + .iter() + .rev() + .take_while(|record| record.get("type").and_then(Value::as_str) != Some("assistant")) + .any(is_interrupt_record) + { + Some("Request interrupted by user".to_owned()) + } else { + last_assistant_error(segment) + }; let stop_event = if error.is_some() { "StopFailure" } else { @@ -675,11 +685,59 @@ fn import_envelope( ) } +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct UserRecord { + #[serde(rename = "type")] + kind: Option, + #[serde(default)] + is_compact_summary: bool, + #[serde(default)] + is_meta: bool, + #[serde(default)] + queue_transcript_only: bool, +} + +fn user_text(record: &Value) -> Option<&str> { + let content = record.pointer("/message/content")?; + content.as_str().or_else(|| { + let [block] = content.as_array()?.as_slice() else { + return None; + }; + (block.get("type")?.as_str()? == "text") + .then(|| block.get("text")?.as_str()) + .flatten() + }) +} + +fn is_interrupt_record(record: &Value) -> bool { + record.get("type").and_then(Value::as_str) == Some("user") + && matches!( + user_text(record).map(str::trim), + Some("[Request interrupted by user]" | "[Request interrupted by user for tool use]") + ) +} + fn is_real_user(record: &Value) -> bool { - if record.get("type").and_then(Value::as_str) != Some("user") { + let Ok(user) = UserRecord::deserialize(record) else { return false; - } - if record.get("isCompactSummary").and_then(Value::as_bool) == Some(true) { + }; + if user.kind.as_deref() != Some("user") + || user.is_compact_summary + || user.is_meta + || user.queue_transcript_only + || is_interrupt_record(record) + || user_text(record).is_some_and(|text| { + [ + "", + "", + "", + "", + ] + .iter() + .any(|tag| text.trim_start().starts_with(tag)) + }) + { return false; } !record diff --git a/bt-daemon/src/transcript_import/mod.rs b/bt-daemon/src/transcript_import/mod.rs index 117a1669..f703b5ee 100644 --- a/bt-daemon/src/transcript_import/mod.rs +++ b/bt-daemon/src/transcript_import/mod.rs @@ -1592,6 +1592,44 @@ mod tests { assert!(!tail.retry_envelopes); } + #[test] + fn claude_import_distinguishes_prompts_from_native_bookkeeping() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("session.jsonl"); + let records = [ + json!({"type":"user","sessionId":"session","message":{"content":"read the skill"}}), + json!({"type":"user","isMeta":true,"message":{"content":"injected skill body"}}), + json!({"type":"user","isMeta":true,"message":{"content":"[Image: source: image.png]"}}), + json!({"type":"assistant","message":{"content":"working"}}), + json!({"type":"user","message":{"content":[{"type":"text","text":"[Request interrupted by user]"}]}}), + json!({"type":"user","message":{"content":"local only"}}), + json!({"type":"user","message":{"content":"/context"}}), + json!({"type":"user","message":{"content":"result"}}), + json!({"type":"user","message":{"content":"next question"}}), + json!({"type":"assistant","message":{"content":"answer"}}), + ]; + std::fs::write( + &path, + records + .iter() + .map(|row| format!("{row}\n")) + .collect::(), + ) + .unwrap(); + let events = transcript_envelopes(&path, ImportSource::Claude).unwrap(); + let prompts = events + .iter() + .filter(|event| event.event == "UserPromptSubmit") + .map(|event| event.payload["prompt"].as_str().unwrap()) + .collect::>(); + assert_eq!(prompts, ["read the skill", "next question"]); + let failure = events + .iter() + .find(|event| event.event == "StopFailure") + .unwrap(); + assert_eq!(failure.payload["error"], "Request interrupted by user"); + } + #[test] fn claude_tail_closes_only_completed_turns() { let temp = tempfile::tempdir().unwrap(); From 0b5eb6643a4c928d99c58d12a5dddf4ba5d9c6f4 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 5223a205252472e182d2cc618ace771221daa7fb 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 7244e18d6e2ae5f6a235a0a0a89383271090111d Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Thu, 26 Nov 2026 00:28:12 +0800 Subject: [PATCH 4/4] Share Claude transcript prompt classification --- bt-daemon/src/transcript_import/claude.rs | 62 +------------ bt-daemon/src/translate/claude.rs | 20 +---- .../translate/claude/transcript_envelope.rs | 88 +++++++++++++++++-- bt-daemon/src/translate/mod.rs | 4 +- 4 files changed, 91 insertions(+), 83 deletions(-) diff --git a/bt-daemon/src/transcript_import/claude.rs b/bt-daemon/src/transcript_import/claude.rs index 1e63e0ca..b60c80e7 100644 --- a/bt-daemon/src/transcript_import/claude.rs +++ b/bt-daemon/src/transcript_import/claude.rs @@ -3,6 +3,7 @@ use super::{ string_at, timestamp_bounds, timestamp_ms, validate_session_id, IncrementalRecords, TailSession, TranscriptImport, TranscriptLayout, }; +use crate::translate::ClaudeTranscriptEnvelope; use crate::wire::Envelope; use anyhow::bail; use serde::Deserialize; @@ -685,69 +686,12 @@ fn import_envelope( ) } -#[derive(Deserialize)] -#[serde(rename_all = "camelCase")] -struct UserRecord { - #[serde(rename = "type")] - kind: Option, - #[serde(default)] - is_compact_summary: bool, - #[serde(default)] - is_meta: bool, - #[serde(default)] - queue_transcript_only: bool, -} - -fn user_text(record: &Value) -> Option<&str> { - let content = record.pointer("/message/content")?; - content.as_str().or_else(|| { - let [block] = content.as_array()?.as_slice() else { - return None; - }; - (block.get("type")?.as_str()? == "text") - .then(|| block.get("text")?.as_str()) - .flatten() - }) -} - fn is_interrupt_record(record: &Value) -> bool { - record.get("type").and_then(Value::as_str) == Some("user") - && matches!( - user_text(record).map(str::trim), - Some("[Request interrupted by user]" | "[Request interrupted by user for tool use]") - ) + ClaudeTranscriptEnvelope::deserialize(record).is_ok_and(|row| row.is_interrupt()) } fn is_real_user(record: &Value) -> bool { - let Ok(user) = UserRecord::deserialize(record) else { - return false; - }; - if user.kind.as_deref() != Some("user") - || user.is_compact_summary - || user.is_meta - || user.queue_transcript_only - || is_interrupt_record(record) - || user_text(record).is_some_and(|text| { - [ - "", - "", - "", - "", - ] - .iter() - .any(|tag| text.trim_start().starts_with(tag)) - }) - { - return false; - } - !record - .pointer("/message/content") - .and_then(Value::as_array) - .is_some_and(|blocks| { - blocks - .iter() - .any(|block| block.get("type").and_then(Value::as_str) == Some("tool_result")) - }) + ClaudeTranscriptEnvelope::deserialize(record).is_ok_and(|row| row.is_import_turn_start()) } fn last_assistant_text(records: &[Value]) -> Option { diff --git a/bt-daemon/src/translate/claude.rs b/bt-daemon/src/translate/claude.rs index 66db8853..73960d59 100644 --- a/bt-daemon/src/translate/claude.rs +++ b/bt-daemon/src/translate/claude.rs @@ -26,7 +26,7 @@ use subagent_hook::SubagentHook; #[cfg(test)] use timestamp_envelope::parse_rfc3339_timestamp; use timestamp_envelope::parse_timestamp_ms; -use transcript_envelope::TranscriptEnvelope; +pub(crate) use transcript_envelope::TranscriptEnvelope; use transcript_tool::TranscriptTool; use super::git::GitMetadataCache; @@ -1692,23 +1692,7 @@ fn prompt_matches(prompt: &Value, content: &Value) -> bool { } fn is_real_user_record(record: &Value) -> bool { - let Some(envelope) = decode::(record) else { - return false; - }; - if envelope.kind.as_deref() != Some("user") { - return false; - } - if envelope.is_compact_summary { - return false; - } - !record - .pointer("/message/content") - .and_then(Value::as_array) - .is_some_and(|blocks| { - blocks - .iter() - .any(|block| block.get("type").and_then(Value::as_str) == Some("tool_result")) - }) + decode::(record).is_some_and(|row| row.is_user_prompt()) } /// Read newline-delimited records forward from `offset`, advancing it past /// everything consumed. diff --git a/bt-daemon/src/translate/claude/transcript_envelope.rs b/bt-daemon/src/translate/claude/transcript_envelope.rs index 1bbfa928..1942c1af 100644 --- a/bt-daemon/src/translate/claude/transcript_envelope.rs +++ b/bt-daemon/src/translate/claude/transcript_envelope.rs @@ -1,13 +1,91 @@ -use serde::{Deserialize, Serialize}; +use serde::Deserialize; -/// Stable routing fields from one Claude transcript row. Message and tool -/// blocks intentionally remain raw because they are preserved in span I/O. -#[derive(Deserialize, Serialize)] -pub(super) struct TranscriptEnvelope { +/// Stable routing fields from one Claude transcript row. +#[derive(Deserialize)] +pub(crate) struct TranscriptEnvelope { #[serde(rename = "type", default)] pub(super) kind: Option, #[serde(default)] pub(super) subtype: Option, #[serde(rename = "isCompactSummary", default)] pub(super) is_compact_summary: bool, + #[serde(rename = "isMeta", default)] + is_meta: bool, + #[serde(rename = "queueTranscriptOnly", default)] + queue_transcript_only: bool, + message: Option, +} + +#[derive(Deserialize)] +struct TranscriptMessage { + content: Option, +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum TranscriptContent { + Text(String), + Blocks(Vec), + Other(serde::de::IgnoredAny), +} + +#[derive(Deserialize)] +struct TranscriptBlock { + #[serde(rename = "type")] + kind: Option, + text: Option, +} + +impl TranscriptEnvelope { + pub(super) fn is_user_prompt(&self) -> bool { + self.kind.as_deref() == Some("user") + && !self.is_compact_summary + && !matches!( + self.content(), + Some(TranscriptContent::Blocks(blocks)) + if blocks.iter().any(|block| block.kind.as_deref() == Some("tool_result")) + ) + } + + pub(crate) fn is_import_turn_start(&self) -> bool { + self.is_user_prompt() + && !self.is_meta + && !self.queue_transcript_only + && !self.is_interrupt() + && !self.user_text().is_some_and(|text| { + [ + "", + "", + "", + "", + ] + .iter() + .any(|tag| text.trim_start().starts_with(tag)) + }) + } + + pub(crate) fn is_interrupt(&self) -> bool { + self.kind.as_deref() == Some("user") + && matches!( + self.user_text().map(str::trim), + Some( + "[Request interrupted by user]" | "[Request interrupted by user for tool use]" + ) + ) + } + + fn content(&self) -> Option<&TranscriptContent> { + self.message.as_ref()?.content.as_ref() + } + + fn user_text(&self) -> Option<&str> { + match self.content()? { + TranscriptContent::Text(text) => Some(text), + TranscriptContent::Blocks(blocks) => match blocks.as_slice() { + [block] if block.kind.as_deref() == Some("text") => block.text.as_deref(), + _ => None, + }, + TranscriptContent::Other(_) => None, + } + } } diff --git a/bt-daemon/src/translate/mod.rs b/bt-daemon/src/translate/mod.rs index 87e8d6c9..a42e78ac 100644 --- a/bt-daemon/src/translate/mod.rs +++ b/bt-daemon/src/translate/mod.rs @@ -22,7 +22,9 @@ mod muse; mod opencode; mod opencode_v2; mod pi; -pub(crate) use claude::successful_subagent_handback_message; +pub(crate) use claude::{ + successful_subagent_handback_message, TranscriptEnvelope as ClaudeTranscriptEnvelope, +}; pub(crate) use pi::request_config as pi_request_config; mod origins; pub(crate) mod recent;