Skip to content
Merged
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
38 changes: 38 additions & 0 deletions bt-daemon/src/collections/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,21 @@ pub(super) fn retain_references(identity: &mut RedactedEnvelope, previous: &Reda
payload.insert(key.into(), value.clone());
}
}
if let Some(old_children) = old
.get("_bt_claude_children")
.and_then(serde_json::Value::as_object)
{
let children = payload
.entry("_bt_claude_children")
.or_insert_with(|| serde_json::json!({}));
if let Some(children) = children.as_object_mut() {
for (agent, observation) in old_children {
children
.entry(agent.clone())
.or_insert_with(|| observation.clone());
}
}
}
}
}

Expand All @@ -213,6 +228,29 @@ pub(super) fn identity(event: &RedactedEnvelope) -> RedactedEnvelope {
.filter_map(|key| Some(((*key).into(), event.payload.get(*key)?.clone())))
.collect(),
);
if event.source == "claude-code"
&& matches!(event.event.as_str(), "SubagentStop" | "TranscriptUpdate")
{
if let (Some(agent), Some(path)) = (
event
.payload
.get("agent_id")
.and_then(serde_json::Value::as_str),
event
.payload
.get("agent_transcript_path")
.and_then(serde_json::Value::as_str),
) {
let through = event
.payload
.get("_bt_claude_transcript_mirrors")
.and_then(|m| m.get(path))
.and_then(|m| m.get("through"))
.cloned();
identity.payload["_bt_claude_children"] =
serde_json::json!({agent: {"path": path, "through": through}});
}
}
identity
}

Expand Down
136 changes: 99 additions & 37 deletions bt-daemon/src/server/claude_transcripts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,20 @@ pub(super) struct ClaudeTranscriptObservation {
/// Synthetic-event provenance only: never retain native prompts or responses.
pub(super) template: Envelope,
pub(super) through: Option<u64>,
pub(super) children: HashMap<String, ClaudeChildObservation>,
}

#[derive(Clone)]
pub(super) struct ClaudeChildObservation {
pub(super) template: Envelope,
pub(super) through: Option<u64>,
}

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() {
return;
}
if env.event == "SessionEnd" {
self.claude_transcripts
.lock()
.retain(|key, _| key.source != env.source || key.session_id != env.session_id);
return;
}
let Some(route) = env.route.as_ref() else {
return;
};
Expand Down Expand Up @@ -60,8 +61,9 @@ impl Daemon {
config: None,
};
let mut observations = self.claude_transcripts.lock();
let previous = observations
.get(&key)
let old = observations.remove(&key);
let previous = old
.as_ref()
.filter(|observation| {
observation
.template
Expand All @@ -71,11 +73,64 @@ impl Daemon {
== Some(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)
{
for (agent_id, observation) in saved {
let Some(child_path) = observation.get("path").and_then(Value::as_str) else {
continue;
};
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());
children.insert(
agent_id.clone(),
ClaudeChildObservation {
template: child_template,
through: observation.get("through").and_then(Value::as_u64),
},
);
}
}
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),
) {
let child_through = env
.payload
.get("_bt_claude_transcript_mirrors")
.and_then(|mirrors| mirrors.get(child_path))
.and_then(|mirror| mirror.get("through"))
.and_then(Value::as_u64);
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());
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),
},
);
}
}
observations.insert(
key,
ClaudeTranscriptObservation {
template,
through: through.or(previous),
children,
},
);
}
Expand Down Expand Up @@ -117,35 +172,42 @@ impl Daemon {
let Some(observation) = observation else {
continue;
};
let Some(path) = observation
.template
.payload
.get("transcript_path")
.and_then(Value::as_str)
else {
tracing::warn!(session_id = %key.session_id, "Claude transcript observation has no transcript path");
continue;
};
let Ok(metadata) = tokio::fs::metadata(path).await else {
continue;
};
if observation.through == Some(metadata.len()) {
continue;
}
let mut env = observation.template;
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(env.payload.get("transcript_path")?.as_str()?))
.and_then(|mirror| mirror.get("through"))
.and_then(Value::as_u64);
if through.is_none() || through == observation.through {
continue;
}
if let Err(error) = self.journal_and_enqueue(env).await {
tracing::warn!(session_id = %key.session_id, %error, "Claude transcript observation failed");
let mut targets = vec![(observation.template, observation.through, "transcript_path")];
targets.extend(
observation
.children
.into_values()
.map(|child| (child.template, child.through, "agent_transcript_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;
};
let Ok(metadata) = tokio::fs::metadata(&path).await else {
continue;
};
if previous == Some(metadata.len()) {
continue;
}
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);
if through.is_none() || through == previous {
continue;
}
if let Err(error) = self.journal_and_enqueue(env).await {
tracing::warn!(session_id = %key.session_id, %error, "Claude transcript observation failed");
}
}
}
}
Expand Down
14 changes: 13 additions & 1 deletion bt-daemon/src/server/recovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,21 @@ pub(super) async fn discover_unprocessed_journals(daemon: &Arc<Daemon>) -> Vec<P
tracing::warn!(session_id = %key.session_id, "Claude transcript observation has no transcript path");
continue;
};
let changed = tokio::fs::metadata(path)
let mut changed = tokio::fs::metadata(path)
.await
.is_ok_and(|metadata| observation.through != Some(metadata.len()));
for child in observation.children.values() {
if let Some(path) = child
.template
.payload
.get("agent_transcript_path")
.and_then(Value::as_str)
{
changed |= tokio::fs::metadata(path)
.await
.is_ok_and(|metadata| child.through != Some(metadata.len()));
}
}
if !changed {
daemon.claude_transcripts.lock().remove(&key);
}
Expand Down
38 changes: 34 additions & 4 deletions bt-daemon/src/translate/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,8 @@ struct ClaudeTranslator {
pending_tools: HashMap<String, PendingTool>,
subagents: HashMap<String, Subagent>,
subagent_handbacks: HashMap<String, Value>,
#[serde(default)]
observe_stopped_subagents: bool,
/// Skills the user asked for on the current (or next) turn: `/skill`
/// expansions and `SKILL.md` paths named in the prompt. Cleared when a
/// turn stops, so a turn that ends without a Stop hands its skills to the
Expand Down Expand Up @@ -360,6 +362,7 @@ impl ClaudeTranslator {
pending_tools: HashMap::new(),
subagents: HashMap::new(),
subagent_handbacks: HashMap::new(),
observe_stopped_subagents: false,
requested_skills: Vec::new(),
pending_emission: None,
claude_version: None,
Expand Down Expand Up @@ -941,6 +944,11 @@ impl ClaudeTranslator {
}

fn stop_subagent(&mut self, event: &Envelope, hook: SubagentHook, ops: &mut Vec<SpanOp>) {
if event.payload.get("_bt_import_through_offset").is_none()
&& hook.agent_transcript_path.is_some()
{
self.observe_stopped_subagents = true;
}
let agent_id = hook.agent_id.clone();
let parent = self.ensure_subagent(&hook, event, ops);
let parent_span_ids = self
Expand Down Expand Up @@ -1081,6 +1089,7 @@ impl ClaudeTranslator {
}

fn release_terminal_state(&mut self) {
self.observe_stopped_subagents = false;
self.main_history = MessageHistory::default();
self.transcripts.clear();
self.subagents.clear();
Expand Down Expand Up @@ -1426,10 +1435,14 @@ impl ClaudeTranslator {
}
self.end_root(event.ts_ms, ops);
self.root_open = false;
if let Some(pending) = &mut self.pending_emission {
pending.clear_after = true;
} else {
self.release_terminal_state();
// A stopped live subagent may append after session end. Keep its
// deduplication state until the observer is finalized.
if !self.observe_stopped_subagents {
if let Some(pending) = &mut self.pending_emission {
pending.clear_after = true;
} else {
self.release_terminal_state();
}
}
}
}
Expand Down Expand Up @@ -1556,6 +1569,23 @@ impl AgentTranslator for ClaudeTranslator {
self.stop_subagent(event, hook, &mut ops);
}
}
"TranscriptUpdate" if event.payload.get("agent_transcript_path").is_some() => {
if let (Some(agent_id), Some(path)) = (
string_field(&event.payload, "agent_id"),
string_field(&event.payload, "agent_transcript_path"),
) {
Comment on lines +1572 to +1576

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the internal-agent filter for transcript updates

When an internal Claude agent (such as prompt suggestions) appends transcript records after its unpaired, empty-type SubagentStop, remember_claude_transcripts now registers it for polling, and this branch emits its model calls unconditionally. This bypasses the deliberate filter in handle that ignores these stops, covered by claude_ignores_untracked_empty_type_subagent_stops. The resulting LLM spans include unwanted internal activity and reference a subagent parent that was never created. Retain eligibility information for accepted delegated agents and apply it to child transcript updates as well.

Useful? React with 👍 / 👎.

let mut offset = 0;
let records = read_event_records(event, &path, &mut offset);
self.queue_transcript(
records,
PendingHistory::Owned(MessageHistory::default()),
format!("subagent:{agent_id}"),
ids::span_id(&self.session_id, &format!("subagent:{agent_id}")),
self.current_cwd.clone(),
&mut ops,
);
}
}
"TranscriptUpdate" if self.turn.is_none() => {
if let Some(parent) = self.last_turn_id.clone() {
self.emit_main(&parent, &mut ops);
Expand Down
Loading
Loading