From 6eb068f2fe5fa327c87f572b79078ab80135724e Mon Sep 17 00:00:00 2001 From: abhinavgautam01 Date: Fri, 20 Nov 2026 12:59:48 +0530 Subject: [PATCH 1/2] Match Claude subagent lines to task events on agent_id --- README.md | 11 ++++--- claude.go | 83 +++++++++++++++++++++++++++++++++++++-------------- event_test.go | 79 ++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 144 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 6e6aa42..ec7d618 100644 --- a/README.md +++ b/README.md @@ -145,10 +145,13 @@ Kinds are `thinking`, `text`, `tool`, `result`, `usage`, `error`, `session`, `rate_limit`, `egress` and `subagent`. `FormatEvent` renders an event for a plain-text log. -Claude prints the tool calls of its subagents, tagged with the Agent call that -started them, and reports each subagent's start and end as `task_started` and -`task_notification` system lines. The Claude parser sets `Agent` to the -subagent's task description on every event that subagent produced, emits a +Claude prints the tool calls of its subagents, tagged with the subagent's +`agent_id`, and reports each subagent's start and end as `task_started` and +`task_notification` system lines whose `task_id` equals that `agent_id`. The +parser matches the two on that id, which survives a resumed subagent, and falls +back to `parent_tool_use_id` for older CLIs that omit `agent_id`. It sets +`Agent` to the subagent's task description on every event that subagent +produced, emits a `subagent` event when it starts and ends, and `FormatEvent` prefixes those lines with `[agent:]`. The other backends never set `Agent`, and the Codex and OpenCode CLIs print nothing from their subagents' sessions. diff --git a/claude.go b/claude.go index c4eda0b..08ace13 100644 --- a/claude.go +++ b/claude.go @@ -1,6 +1,7 @@ package harness import ( + "cmp" "encoding/json" "io" "path/filepath" @@ -158,15 +159,21 @@ type claudeLine struct { RateLimitInfo *RateLimitInfo `json:"rate_limit_info"` Event *claudeStreamEvent `json:"event"` APIMessageID string `json:"api_message_id"` - // ParentToolUseID is the tool call that started the subagent this line - // comes from, and null on the main conversation. + // ParentToolUseID is the tool call that first started the subagent this + // line comes from, and null on the main conversation. A resumed subagent + // keeps it, so it can differ from the tool_use_id on its task events. ParentToolUseID string `json:"parent_tool_use_id"` + // AgentID names the subagent this line comes from, and is absent on the + // main conversation and from older CLIs. It equals the task_id on the + // subagent's task events and survives resumes. + AgentID string `json:"agent_id"` } // claudeTask is the payload of the task_started and task_notification system // lines. It is decoded on its own so an unexpected field type on any other // line cannot make the whole line fail to parse. type claudeTask struct { + TaskID string `json:"task_id"` ToolUseID string `json:"tool_use_id"` Description string `json:"description"` TaskType string `json:"task_type"` @@ -226,9 +233,14 @@ type claudeStreamState struct { current string // sessionCostUSD is the latest cumulative total_cost_usd in the stream. sessionCostUSD float64 - // agents holds the subagents task_started announced, keyed by the Agent - // tool call that started them. + // agents holds the subagents task_started announced, keyed by task_id, + // which a line's agent_id matches and which stays the same when the + // subagent is resumed. agents map[string]*claudeAgent + // toolAgents maps each tool call that started or resumed a subagent to + // its entry in agents. It labels lines without agent_id and ends tasks + // whose notification lacks task_id. + toolAgents map[string]*claudeAgent } type claudeAgent struct { @@ -244,50 +256,75 @@ type claudeReported struct { func newClaudeStreamState() *claudeStreamState { return &claudeStreamState{ - reported: map[string]claudeReported{}, - models: map[string]string{}, - agents: map[string]*claudeAgent{}, + reported: map[string]claudeReported{}, + models: map[string]string{}, + agents: map[string]*claudeAgent{}, + toolAgents: map[string]*claudeAgent{}, } } -// agentLabel names the subagent a line belongs to. A subagent whose -// task_started has not been seen keeps its tool call id, so its events still -// stand apart from the main conversation. -func (state *claudeStreamState) agentLabel(parentToolUseID string) string { - if agent := state.agents[parentToolUseID]; agent != nil { +// agentLabel names the subagent a line belongs to. It matches agent_id +// against task_id first, since a resumed subagent's lines keep the +// parent_tool_use_id of the call that first started it. Lines from older CLIs +// carry no agent_id and fall back to parent_tool_use_id. A subagent whose +// task_started has not been seen keeps its raw id, so its events still stand +// apart from the main conversation. +func (state *claudeStreamState) agentLabel(agentID, parentToolUseID string) string { + if agent := state.agents[agentID]; agent != nil { return agent.description } + if agent := state.toolAgents[parentToolUseID]; agent != nil { + return agent.description + } + if agentID != "" { + return agentID + } return parentToolUseID } func (state *claudeStreamState) handleTask(raw []byte, subtype string, emit func(Event)) { var task claudeTask - if json.Unmarshal(raw, &task) != nil || task.ToolUseID == "" { + if json.Unmarshal(raw, &task) != nil { return } if subtype == "task_notification" { - state.endAgent(task.ToolUseID, task.Status, emit) + state.endAgent(task, emit) return } // Background Bash commands and Monitor watches report tasks too. if task.TaskType != "local_agent" { return } - description := task.Description - if description == "" { - description = task.ToolUseID + key := cmp.Or(task.TaskID, task.ToolUseID) + if key == "" { + return } - state.agents[task.ToolUseID] = &claudeAgent{description: description} - emit(Event{Kind: KindSubagent, Agent: description, Text: "started"}) + // A resumed subagent announces a new run under the same task_id. It + // keeps its first description so all of its lines share one label. + agent := state.agents[key] + if agent == nil { + agent = &claudeAgent{description: cmp.Or(task.Description, task.ToolUseID, key)} + state.agents[key] = agent + } + agent.ended = false + if task.ToolUseID != "" { + state.toolAgents[task.ToolUseID] = agent + } + emit(Event{Kind: KindSubagent, Agent: agent.description, Text: "started"}) } -func (state *claudeStreamState) endAgent(toolUseID, status string, emit func(Event)) { - agent := state.agents[toolUseID] +// endAgent ends the subagent run a task_notification reports. tool_use_id is +// optional on it, so it is matched on task_id first. +func (state *claudeStreamState) endAgent(task claudeTask, emit func(Event)) { + agent := state.agents[task.TaskID] + if agent == nil { + agent = state.toolAgents[task.ToolUseID] + } if agent == nil || agent.ended { return } agent.ended = true - emit(Event{Kind: KindSubagent, Agent: agent.description, Text: status}) + emit(Event{Kind: KindSubagent, Agent: agent.description, Text: task.Status}) } // reportUsage emits a usage event for the growth of id's usage over what was @@ -382,7 +419,7 @@ func (state *claudeStreamState) parseLine(raw []byte, emit func(Event)) { state.handleTask(raw, message.Subtype, emit) } case "assistant": - agent := state.agentLabel(message.ParentToolUseID) + agent := state.agentLabel(message.AgentID, message.ParentToolUseID) emitClaudeAssistant(message.Message, agent, emit) // Subagent calls emit no stream_event lines, so they only reach here // and their output tokens are a lower bound until the result event. diff --git a/event_test.go b/event_test.go index 7af48ec..988d323 100644 --- a/event_test.go +++ b/event_test.go @@ -411,7 +411,8 @@ func TestClaudeStreamWithoutSubagentsIsUnlabelled(t *testing.T) { } // Without task_started, a subagent's lines fall back to its tool call id, and -// a tool_result ends no subagent. +// a tool_result ends no subagent. tool_use_id is optional on task events, so a +// task_started without it is still tracked by task_id. func TestClaudeStreamSubagentWithoutTaskStarted(t *testing.T) { t.Parallel() @@ -424,7 +425,81 @@ func TestClaudeStreamSubagentWithoutTaskStarted(t *testing.T) { `{"type":"system","subtype":"task_started","task_id":"c2","task_type":"local_agent","description":"no tool call"}`, }, "\n") - want := []string{"[agent:toolu_x] [grep] TODO", "[agent:toolu_y] started"} + want := []string{"[agent:toolu_x] [grep] TODO", "[agent:toolu_y] started", "[agent:no tool call] started"} + if got := claudeLogLines(input); !slices.Equal(got, want) { + t.Errorf("log lines = %q, want %q", got, want) + } +} + +// A resumed subagent's task events carry the resuming call's tool_use_id, +// while its lines keep the parent_tool_use_id of the call that first started +// it. agent_id equals task_id across both runs, so every line keeps one label +// and each run reports its own start and end. +func TestClaudeStreamLabelsResumedSubagentByAgentID(t *testing.T) { + t.Parallel() + + input := strings.Join([]string{ + `{"type":"system","subtype":"task_started","task_id":"a1","tool_use_id":"toolu_first","description":"Audit batch A","task_type":"local_agent"}`, + `{"type":"assistant","parent_tool_use_id":"toolu_first","agent_id":"a1","message":{"content":[{"type":"text","text":"first run"}]}}`, + `{"type":"system","subtype":"task_notification","task_id":"a1","tool_use_id":"toolu_first","status":"completed","summary":"x"}`, + `{"type":"system","subtype":"task_started","task_id":"a1","tool_use_id":"toolu_resume","description":"Continue batch A","task_type":"local_agent"}`, + `{"type":"assistant","parent_tool_use_id":"toolu_first","agent_id":"a1","message":{"id":"msg_r","usage":{"input_tokens":4,"output_tokens":2},"content":[{"type":"text","text":"resumed run"}]}}`, + `{"type":"system","subtype":"task_notification","task_id":"a1","status":"completed","summary":"x"}`, + }, "\n") + + want := []string{ + "[agent:Audit batch A] started", + "[agent:Audit batch A] first run", + "[agent:Audit batch A] completed", + "[agent:Audit batch A] started", + "[agent:Audit batch A] resumed run", + "[agent:Audit batch A] [usage] in=4 out=2 cache_read=0 cache_write=0 cost=$0.0000", + "[agent:Audit batch A] completed", + } + if got := claudeLogLines(input); !slices.Equal(got, want) { + t.Errorf("log lines =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } +} + +// After --resume the stream state starts empty. The resumed subagent's lines +// still carry the parent_tool_use_id of a call from the earlier process, so +// only agent_id ties them to the task_started of this process. +func TestClaudeStreamLabelsSubagentAcrossSessionResume(t *testing.T) { + t.Parallel() + + input := strings.Join([]string{ + `{"type":"system","subtype":"task_started","task_id":"a1","tool_use_id":"toolu_resume","description":"Continue batch A","task_type":"local_agent"}`, + `{"type":"assistant","parent_tool_use_id":"toolu_earlier_process","agent_id":"a1","message":{"content":[{"type":"tool_use","name":"Bash","input":{"command":"ls"}}]}}`, + `{"type":"system","subtype":"task_notification","task_id":"a1","tool_use_id":"toolu_resume","status":"stopped","summary":"x"}`, + }, "\n") + + want := []string{ + "[agent:Continue batch A] started", + "[agent:Continue batch A] [bash] ls", + "[agent:Continue batch A] stopped", + } + if got := claudeLogLines(input); !slices.Equal(got, want) { + t.Errorf("log lines = %q, want %q", got, want) + } +} + +// A line with an agent_id whose task_started was never seen keeps the +// agent_id as its label, and a notification without tool_use_id still ends +// its subagent through task_id. +func TestClaudeStreamUnknownAgentIDAndNotificationWithoutToolUseID(t *testing.T) { + t.Parallel() + + input := strings.Join([]string{ + `{"type":"assistant","parent_tool_use_id":"toolu_gone","agent_id":"a9","message":{"content":[{"type":"text","text":"orphan"}]}}`, + `{"type":"system","subtype":"task_started","task_id":"a2","tool_use_id":"toolu_2","description":"Audit batch B","task_type":"local_agent"}`, + `{"type":"system","subtype":"task_notification","task_id":"a2","status":"failed","summary":"x"}`, + }, "\n") + + want := []string{ + "[agent:a9] orphan", + "[agent:Audit batch B] started", + "[agent:Audit batch B] failed", + } if got := claudeLogLines(input); !slices.Equal(got, want) { t.Errorf("log lines = %q, want %q", got, want) } From 0651974b9de1b04c6cc4f34c5acf11f6e5ed3c33 Mon Sep 17 00:00:00 2001 From: Andrew Nesbitt Date: Fri, 20 Nov 2026 14:11:09 +0000 Subject: [PATCH 2/2] Trim subagent labelling comments --- claude.go | 26 ++++++++------------------ event_test.go | 15 +++------------ 2 files changed, 11 insertions(+), 30 deletions(-) diff --git a/claude.go b/claude.go index 08ace13..d506e8a 100644 --- a/claude.go +++ b/claude.go @@ -160,12 +160,9 @@ type claudeLine struct { Event *claudeStreamEvent `json:"event"` APIMessageID string `json:"api_message_id"` // ParentToolUseID is the tool call that first started the subagent this - // line comes from, and null on the main conversation. A resumed subagent - // keeps it, so it can differ from the tool_use_id on its task events. + // line comes from, and null on the main conversation. ParentToolUseID string `json:"parent_tool_use_id"` - // AgentID names the subagent this line comes from, and is absent on the - // main conversation and from older CLIs. It equals the task_id on the - // subagent's task events and survives resumes. + // AgentID equals the task_id on the subagent's task events. Older CLIs omit it. AgentID string `json:"agent_id"` } @@ -233,13 +230,10 @@ type claudeStreamState struct { current string // sessionCostUSD is the latest cumulative total_cost_usd in the stream. sessionCostUSD float64 - // agents holds the subagents task_started announced, keyed by task_id, - // which a line's agent_id matches and which stays the same when the - // subagent is resumed. + // agents holds the subagents task_started announced, keyed by task_id. agents map[string]*claudeAgent // toolAgents maps each tool call that started or resumed a subagent to - // its entry in agents. It labels lines without agent_id and ends tasks - // whose notification lacks task_id. + // its entry in agents. toolAgents map[string]*claudeAgent } @@ -263,12 +257,10 @@ func newClaudeStreamState() *claudeStreamState { } } -// agentLabel names the subagent a line belongs to. It matches agent_id -// against task_id first, since a resumed subagent's lines keep the -// parent_tool_use_id of the call that first started it. Lines from older CLIs -// carry no agent_id and fall back to parent_tool_use_id. A subagent whose -// task_started has not been seen keeps its raw id, so its events still stand -// apart from the main conversation. +// agentLabel names the subagent a line belongs to. agent_id is tried first +// because a resumed subagent's lines keep the parent_tool_use_id of the call +// that first started it. A subagent whose task_started has not been seen +// keeps its raw id, so its events still stand apart from the main conversation. func (state *claudeStreamState) agentLabel(agentID, parentToolUseID string) string { if agent := state.agents[agentID]; agent != nil { return agent.description @@ -313,8 +305,6 @@ func (state *claudeStreamState) handleTask(raw []byte, subtype string, emit func emit(Event{Kind: KindSubagent, Agent: agent.description, Text: "started"}) } -// endAgent ends the subagent run a task_notification reports. tool_use_id is -// optional on it, so it is matched on task_id first. func (state *claudeStreamState) endAgent(task claudeTask, emit func(Event)) { agent := state.agents[task.TaskID] if agent == nil { diff --git a/event_test.go b/event_test.go index 988d323..ca5e8ae 100644 --- a/event_test.go +++ b/event_test.go @@ -411,8 +411,7 @@ func TestClaudeStreamWithoutSubagentsIsUnlabelled(t *testing.T) { } // Without task_started, a subagent's lines fall back to its tool call id, and -// a tool_result ends no subagent. tool_use_id is optional on task events, so a -// task_started without it is still tracked by task_id. +// a tool_result ends no subagent. func TestClaudeStreamSubagentWithoutTaskStarted(t *testing.T) { t.Parallel() @@ -431,10 +430,7 @@ func TestClaudeStreamSubagentWithoutTaskStarted(t *testing.T) { } } -// A resumed subagent's task events carry the resuming call's tool_use_id, -// while its lines keep the parent_tool_use_id of the call that first started -// it. agent_id equals task_id across both runs, so every line keeps one label -// and each run reports its own start and end. +// A subagent resumed in one stream keeps one label across both runs. func TestClaudeStreamLabelsResumedSubagentByAgentID(t *testing.T) { t.Parallel() @@ -461,9 +457,7 @@ func TestClaudeStreamLabelsResumedSubagentByAgentID(t *testing.T) { } } -// After --resume the stream state starts empty. The resumed subagent's lines -// still carry the parent_tool_use_id of a call from the earlier process, so -// only agent_id ties them to the task_started of this process. +// After --resume, parent_tool_use_id names a call from the earlier process. func TestClaudeStreamLabelsSubagentAcrossSessionResume(t *testing.T) { t.Parallel() @@ -483,9 +477,6 @@ func TestClaudeStreamLabelsSubagentAcrossSessionResume(t *testing.T) { } } -// A line with an agent_id whose task_started was never seen keeps the -// agent_id as its label, and a notification without tool_use_id still ends -// its subagent through task_id. func TestClaudeStreamUnknownAgentIDAndNotificationWithoutToolUseID(t *testing.T) { t.Parallel()