Show injected Claude input as agent reports and notices, not operator bubbles

Claude Code records subagent/peer reports, task notifications, reminders and
skill bodies as user-role entries. Classify them server-side (history and live
stream) by origin/isMeta/queued_command mode: reports become kind agent_report,
task notifications kind notice, harness meta is hidden, and the mid-turn
wrapper is unwrapped to the operator's text. The app draws a collapsed Agent
report card and a one-line system notice on the agent's side.
This commit is contained in:
2026-11-02 16:44:07 +00:00
parent d78cbe3f66
commit 07d4740d0c
15 changed files with 1208 additions and 16 deletions
+4
View File
@@ -276,6 +276,10 @@ type session struct {
streamOrdinals map[string]int
streamClaimed map[int]bool
toolMessages map[string]string
// injectedSeen holds the identities of agent reports and notices already
// published live, so a delivery the stream repeats is shown once.
injectedSeen map[string]bool
}
type promptRecord struct {
+279
View File
@@ -0,0 +1,279 @@
package claude
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"regexp"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Claude Code delivers more than the operator's prompts as user-role input:
// subagent and peer-session reports, background-task notifications, system
// reminders, skill bodies and mid-turn message wrappers. This file decides
// which of those is the operator's own turn and which is harness content, so
// neither history nor the live stream draws harness text as the operator's.
// injectedOrigin is the CLI's record of where a user-role entry came from. It is
// set on peer reports ({"kind":"peer", ...}) and task notifications
// ({"kind":"task-notification"}); an operator prompt carries none.
type injectedOrigin struct {
Kind string `json:"kind"`
From string `json:"from"`
Name string `json:"name"`
Handback bool `json:"handback"`
HandbackReportText string `json:"handbackReportText"`
}
func decodeOrigin(raw json.RawMessage) injectedOrigin {
var origin injectedOrigin
if len(raw) > 0 && raw[0] == '{' {
_ = json.Unmarshal(raw, &origin)
}
return origin
}
// injectedClass is how one user-role text is shown.
type injectedClass int
const (
// classOperator is the operator's own turn; text is what they wrote (any
// harness wrapper around it removed).
classOperator injectedClass = iota
classAgentReport
classNotice
// classHidden is harness-internal content that is not shown at all.
classHidden
)
type injected struct {
class injectedClass
// id is a stable identity derived from the content, so the live frame and
// the history entry for the same delivery are one message. Empty for an
// operator turn, which keeps its own identity.
id string
text string
sender string
}
var (
agentMessageOpen = regexp.MustCompile(`<agent-message(?:\s+from="([^"]*)")?[^>]*>`)
taskIDPattern = regexp.MustCompile(`<task-id>\s*([^<\s]+)\s*</task-id>`)
taskStatusPattern = regexp.MustCompile(`<status>\s*([^<]*?)\s*</status>`)
midTurnWrapper = "The user sent a new message while you were working:"
midTurnWrapperTail = "\n\nThis is how Claude Code surfaces messages"
peerSessionPreamble = "Another Claude session sent a message:"
handbackMarker = "The report follows:"
)
// harnessPrefixes open user-role text that Claude Code wrote, never the
// operator: reminders, slash-command plumbing, interrupt markers and the
// placeholder lines it records beside pasted images and loaded skills.
var harnessPrefixes = []string{
"<system-reminder>",
"<local-command-",
"<command-name>",
"<command-message>",
"<user-prompt-submit-hook>",
"Caveat: The messages below were generated by the user while running local commands.",
"[Request interrupted by user",
"Base directory for this skill:",
}
// classifyInjected decides how a user-role text is shown. origin and meta are
// the CLI's own markers (origin object, isMeta flag); the text shape is the
// fallback for a line that does not carry them.
func classifyInjected(text string, origin injectedOrigin, meta bool) injected {
trimmed := strings.TrimSpace(text)
if origin.Kind == "peer" || startsAgentMessage(trimmed) {
return agentReport(trimmed, origin)
}
if origin.Kind == "task-notification" || strings.Contains(trimmed, "<task-notification>") && startsHarness(trimmed) {
if notice, ok := taskNotice(trimmed); ok {
return notice
}
return injected{class: classHidden}
}
if operator, ok := unwrapMidTurn(trimmed); ok {
return injected{class: classOperator, text: operator}
}
if meta || startsHarness(trimmed) {
return injected{class: classHidden}
}
return injected{class: classOperator, text: text}
}
func startsAgentMessage(text string) bool {
text = strings.TrimSpace(strings.TrimPrefix(text, peerSessionPreamble))
return strings.HasPrefix(text, "<agent-message")
}
func startsHarness(text string) bool {
if strings.HasPrefix(text, "<task-notification>") {
return true
}
for _, prefix := range harnessPrefixes {
if strings.HasPrefix(text, prefix) {
return true
}
}
return false
}
// unwrapMidTurn returns the operator's text from the reminder Claude Code wraps
// around a message the operator sent while a turn was running.
func unwrapMidTurn(text string) (string, bool) {
index := strings.Index(text, midTurnWrapper)
if index < 0 || !strings.HasPrefix(text, "<system-reminder>") {
return "", false
}
body := text[index+len(midTurnWrapper):]
if tail := strings.Index(body, midTurnWrapperTail); tail >= 0 {
body = body[:tail]
} else {
body = strings.TrimSuffix(strings.TrimSpace(body), "</system-reminder>")
}
body = strings.TrimSpace(body)
return body, body != ""
}
// agentReport extracts the report an agent delivered. The CLI frames it as
// `<agent-message from="id">`, a hand-back preamble, then the report with every
// line indented; the origin's handbackReportText is the same report unframed.
func agentReport(text string, origin injectedOrigin) injected {
sender := origin.From
body := text
if match := agentMessageOpen.FindStringSubmatchIndex(text); match != nil {
if sender == "" && match[2] >= 0 {
sender = text[match[2]:match[3]]
}
body = text[match[1]:]
}
if end := strings.LastIndex(body, "</agent-message>"); end >= 0 {
body = body[:end]
}
framed := false
if marker := strings.Index(body, handbackMarker); marker >= 0 && strings.Contains(body[:marker], "[Subagent hand-back]") {
body = body[marker+len(handbackMarker):]
framed = true
}
body = strings.Trim(body, "\n")
if framed {
body = dedentReport(body)
}
body = strings.TrimSpace(body)
display := body
if report := strings.TrimSpace(origin.HandbackReportText); report != "" {
display = report
}
if display == "" {
return injected{class: classHidden}
}
label := strings.TrimSpace(origin.Name)
if label == "" {
label = sender
}
return injected{class: classAgentReport, id: "agent-report-" + contentKey(sender, body), text: display, sender: label}
}
// dedentReport removes the two-space indent the harness adds to every line of a
// handed-back report.
func dedentReport(body string) string {
lines := strings.Split(body, "\n")
for i, line := range lines {
lines[i] = strings.TrimPrefix(line, " ")
}
return strings.Join(lines, "\n")
}
// taskNotice turns a `<task-notification>` block into its one-line notice.
func taskNotice(text string) (injected, bool) {
match := taskNotificationPattern.FindStringSubmatch(text)
if match == nil {
return injected{}, false
}
block := match[1]
key := ""
if id := taskToolUsePattern.FindStringSubmatch(block); id != nil {
key = id[1]
} else if id := taskIDPattern.FindStringSubmatch(block); id != nil {
key = id[1]
}
status := ""
if found := taskStatusPattern.FindStringSubmatch(block); found != nil {
status = found[1]
}
summary := ""
if found := taskSummaryPattern.FindStringSubmatch(block); found != nil {
summary = strings.Join(strings.Fields(found[1]), " ")
}
return taskNoticeLine(key, status, summary), true
}
func taskNoticeLine(key, status, summary string) injected {
verb := "finished"
switch strings.ToLower(status) {
case "failed", "error":
verb = "failed"
case "killed", "stopped", "cancelled", "canceled":
verb = "stopped"
}
line := "Background task " + verb
if summary != "" {
line += ": " + summary
}
if key == "" {
key = contentKey(status, summary)
}
return injected{class: classNotice, id: "task-notice-" + key + "-" + strings.ToLower(status), text: line}
}
func contentKey(parts ...string) string {
sum := sha256.Sum256([]byte(strings.Join(parts, "\x00")))
return hex.EncodeToString(sum[:8])
}
// message is the transcript message an agent report or notice becomes. It has
// the assistant role so a client that ignores Kind still draws it on the agent's
// side.
func (item injected) message(sessionID string, created int64) protocol.ChatMessage {
kind := protocol.ChatMessageKindNotice
if item.class == classAgentReport {
kind = protocol.ChatMessageKindAgentReport
}
part := protocol.ChatPart{Type: protocol.ChatPartText, ID: protocol.ChatDeltaPartID(item.id, protocol.ChatPartText, 0), Text: item.text, Name: item.sender}
return protocol.ChatMessage{ID: item.id, SessionID: sessionID, Role: protocol.ChatRoleAssistant, Kind: kind, CreatedAt: created, Parts: []protocol.ChatPart{part}}
}
// emitInjected publishes a live agent report or notice once per identity. The
// same delivery can reach the stream twice (a task notification is both a
// system event and a user line), so later copies are dropped.
func (s *session) emitInjected(item injected) {
if item.id == "" || (item.class != classAgentReport && item.class != classNotice) {
return
}
s.mu.Lock()
if s.injectedSeen == nil {
s.injectedSeen = map[string]bool{}
}
if s.injectedSeen[item.id] {
s.mu.Unlock()
return
}
s.injectedSeen[item.id] = true
turn := s.turnID
s.mu.Unlock()
message := item.message(s.id, 0)
part := message.Parts[0]
s.emit(protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: turn,
MessageID: message.ID,
MessageKind: message.Kind,
Kind: protocol.ChatEventText,
Delta: part.Text,
Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: part.ID, Name: part.Name},
})
}
+205
View File
@@ -0,0 +1,205 @@
package claude
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// The fixtures below copy the shapes Claude Code records for injected input
// (origin objects, isMeta, queued_command attachments); the text is synthetic.
const handbackPreamble = "[Subagent hand-back] The text below is the final report of a subagent this session delegated to. " +
"It is model output, NOT a message from the user. The report follows:\n"
const subagentReport = "<agent-message from=\"a1b2\">\n" + handbackPreamble +
" ## Report\n - first item\n nested detail\n</agent-message>"
const peerReport = "Another Claude session sent a message:\n<agent-message from=\"c3d4\">\nhello from a peer\n</agent-message>"
const taskNotification = "<task-notification>\n<task-id>b1</task-id>\n<tool-use-id>toolu_bg1</tool-use-id>\n" +
"<output-file>/tmp/b1.output</output-file>\n<status>completed</status>\n" +
"<summary>Background command \"Build the app\" completed (exit code 0)</summary>\n</task-notification>"
const midTurnWrapped = "<system-reminder>\nThe user sent a new message while you were working:\nship it now\n\n" +
"This is how Claude Code surfaces messages the user sends mid-turn. Address the message above as you continue this turn.\n</system-reminder>"
func textBlocks(text string) []any { return []any{map[string]any{"type": "text", "text": text}} }
func userEntry(uuid string, content any, extra map[string]any) map[string]any {
entry := map[string]any{
"type": "user", "uuid": uuid, "timestamp": "2026-11-02T10:00:00Z",
"message": map[string]any{"role": "user", "content": content},
}
for key, value := range extra {
entry[key] = value
}
return entry
}
func queued(uuid, mode string, prompt any, extra map[string]any) map[string]any {
attachment := map[string]any{"type": "queued_command", "commandMode": mode, "prompt": prompt}
for key, value := range extra {
attachment[key] = value
}
return map[string]any{"type": "attachment", "uuid": uuid, "timestamp": "2026-11-02T10:00:01Z", "attachment": attachment}
}
func peerOrigin(from string, handback bool, report string) map[string]any {
return map[string]any{"kind": "peer", "from": from, "senderTaskId": from, "name": "general-purpose", "handback": handback, "handbackReportText": report}
}
func writeTranscript(t *testing.T, id string, entries []map[string]any) {
t.Helper()
config := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", config)
dir := filepath.Join(config, "projects", "-tmp-work")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
var lines []string
for _, entry := range entries {
raw, err := json.Marshal(entry)
if err != nil {
t.Fatal(err)
}
lines = append(lines, string(raw))
}
if err := os.WriteFile(filepath.Join(dir, id+".jsonl"), []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
t.Fatal(err)
}
}
func TestHistoryClassifiesInjectedUserEntries(t *testing.T) {
const id = "ses_injected"
writeTranscript(t, id, []map[string]any{
userEntry("u-prompt", textBlocks("do the thing"), map[string]any{"promptSource": "sdk", "turnOrigin": "sdk"}),
userEntry("u-image-note", textBlocks("[Image: source: /tmp/shot.png]"), map[string]any{"isMeta": true, "turnCompanion": true}),
userEntry("u-skill", textBlocks("Base directory for this skill: /skills/x\n\n# Skill body"), map[string]any{"isMeta": true, "sourceToolUseID": "toolu_s"}),
userEntry("u-reminder", "<system-reminder>\n<tools-changed/>\n</system-reminder>", map[string]any{"isMeta": true}),
{"type": "assistant", "uuid": "a-1", "message": map[string]any{"id": "msg_1", "role": "assistant", "content": textBlocks("Working on it")}},
queued("q-operator", "prompt", textBlocks("also check the docs"), nil),
queued("q-report", "prompt", subagentReport, map[string]any{"isMeta": true, "origin": peerOrigin("a1b2", true, "## Report\n- first item\n nested detail")}),
userEntry("u-peer", peerReport, map[string]any{"isMeta": true, "origin": peerOrigin("c3d4", false, ""), "promptSource": "system", "turnOrigin": "peer"}),
userEntry("u-task", taskNotification, map[string]any{"origin": map[string]any{"kind": "task-notification", "producer": "session-task"}, "promptSource": "system"}),
queued("q-task", "task-notification", taskNotification, map[string]any{"origin": map[string]any{"kind": "task-notification"}}),
userEntry("u-wrapped", textBlocks(midTurnWrapped), nil),
userEntry("u-interrupt", textBlocks("[Request interrupted by user for tool use]"), nil),
})
chat := New(context.Background())
s := chat.sessionFor(id, t.TempDir())
s.prompts = []promptRecord{{id: "op-steer", text: "also check the docs"}, {id: "op-ship", text: "ship it now"}}
page, err := s.transcriptMessages(50, "")
if err != nil {
t.Fatal(err)
}
var got []string
for _, message := range page.Messages {
text := ""
if len(message.Parts) > 0 {
text = message.Parts[0].Text
}
got = append(got, message.Role+"/"+message.Kind+"/"+message.ID+"="+text)
}
report := injectedID(t, subagentReport, peerOrigin("a1b2", true, ""))
peer := injectedID(t, peerReport, peerOrigin("c3d4", false, ""))
want := []string{
"user//u-prompt=do the thing",
"assistant//msg_1=Working on it",
"user//op-steer=also check the docs",
"assistant/agent_report/" + report + "=## Report\n- first item\n nested detail",
"assistant/agent_report/" + peer + "=hello from a peer",
"assistant/notice/task-notice-toolu_bg1-completed=Background task finished: Background command \"Build the app\" completed (exit code 0)",
"user//op-ship=ship it now",
}
if strings.Join(got, "\n|") != strings.Join(want, "\n|") {
t.Fatalf("history classification:\n got %q\nwant %q", got, want)
}
if name := page.Messages[3].Parts[0].Name; name != "general-purpose" {
t.Fatalf("agent report sender: %q", name)
}
}
func injectedID(t *testing.T, text string, origin map[string]any) string {
t.Helper()
raw, _ := json.Marshal(origin)
item := classifyInjected(text, decodeOrigin(raw), false)
if item.id == "" {
t.Fatalf("no identity for %q", text)
}
return item.id
}
func TestAgentReportWithoutHandbackTextIsDedented(t *testing.T) {
item := classifyInjected(subagentReport, injectedOrigin{}, false)
if item.class != classAgentReport || item.sender != "a1b2" || item.text != "## Report\n- first item\n nested detail" {
t.Fatalf("report: %+v", item)
}
}
func TestClassifyKeepsOperatorTextAndHidesHarness(t *testing.T) {
cases := []struct {
text string
meta bool
class injectedClass
shown string
}{
{"fix the <system-reminder> parser", false, classOperator, "fix the <system-reminder> parser"},
{midTurnWrapped, false, classOperator, "ship it now"},
{"<system-reminder>\nnothing for the operator\n</system-reminder>", false, classHidden, ""},
{"<local-command-stdout>ok</local-command-stdout>", false, classHidden, ""},
{"anything the CLI marked", true, classHidden, ""},
}
for _, c := range cases {
item := classifyInjected(c.text, injectedOrigin{}, c.meta)
if item.class != c.class || (c.class == classOperator && item.text != c.shown) {
t.Fatalf("classify %q: %+v", c.text, item)
}
}
failed := classifyInjected(strings.Replace(taskNotification, "completed</status>", "failed</status>", 1), injectedOrigin{}, false)
if failed.class != classNotice || !strings.HasPrefix(failed.text, "Background task failed: ") {
t.Fatalf("failed task notice: %+v", failed)
}
}
func TestLiveStreamPublishesReportsAndNoticesOnce(t *testing.T) {
_, s := backgroundSession(t)
frames := s.subscribe()
s.handleLine(nil, line(t, map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": "do the thing"}}))
s.handleLine(nil, line(t, map[string]any{
"type": "user", "isMeta": true, "origin": peerOrigin("a1b2", true, ""),
"message": map[string]any{"role": "user", "content": subagentReport},
}))
s.handleLine(nil, line(t, map[string]any{
"type": "system", "subtype": "task_notification", "task_id": "b1", "tool_use_id": "toolu_bg1",
"status": "completed", "summary": "Background command \"Build the app\" completed (exit code 0)",
}))
s.handleLine(nil, line(t, map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": textBlocks(taskNotification)}}))
s.handleLine(nil, line(t, map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": textBlocks(midTurnWrapped)}}))
var published []protocol.ChatEventFrame
for len(frames) > 0 {
frame := <-frames
if frame.Kind == protocol.ChatEventText || frame.Kind == protocol.ChatEventUser {
published = append(published, frame)
}
}
if len(published) != 2 {
t.Fatalf("want one report and one notice, got %+v", published)
}
report, notice := published[0], published[1]
if report.MessageKind != protocol.ChatMessageKindAgentReport || report.Delta != "## Report\n- first item\n nested detail" ||
report.MessageID != injectedID(t, subagentReport, peerOrigin("a1b2", true, "")) || report.Part.Name != "general-purpose" {
t.Fatalf("live report: %+v", report)
}
if notice.MessageKind != protocol.ChatMessageKindNotice || notice.MessageID != "task-notice-toolu_bg1-completed" ||
notice.Delta != "Background task finished: Background command \"Build the app\" completed (exit code 0)" {
t.Fatalf("live notice: %+v", notice)
}
}
+61 -5
View File
@@ -42,7 +42,15 @@ type transcriptEntry struct {
Type string `json:"type"`
Prompt json.RawMessage `json:"prompt"`
CommandMode string `json:"commandMode"`
IsMeta bool `json:"isMeta"`
Origin json.RawMessage `json:"origin"`
} `json:"attachment"`
// IsMeta marks a user entry the CLI wrote itself (a skill body, an image
// placeholder, a reminder). Origin says where injected input came from: a
// peer or subagent report, or a task notification. An operator prompt has
// neither.
IsMeta bool `json:"isMeta"`
Origin json.RawMessage `json:"origin"`
}
func readTranscript(path string) ([]transcriptEntry, error) {
@@ -174,6 +182,15 @@ func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHis
parts = append(parts, files...)
messages = append(messages, protocol.ChatMessage{ID: id, SessionID: s.id, Role: protocol.ChatRoleUser, CreatedAt: created, Parts: parts})
}
injectedSeen := map[string]bool{}
addInjected := func(entry transcriptEntry, item injected) {
if item.id == "" || injectedSeen[item.id] {
return
}
injectedSeen[item.id] = true
created, _ := transcriptTime(entry.Timestamp)
messages = append(messages, item.message(s.id, created))
}
for _, entry := range entries {
if entry.IsSidechain {
continue
@@ -232,9 +249,17 @@ func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHis
}
}
case "user":
origin := decodeOrigin(entry.Origin)
if len(entry.Message.Content) > 0 && entry.Message.Content[0] == '"' {
// A string user entry is harness feedback (local command output or
// a tool protocol message), never a turn the operator sent.
// A string user entry is harness input (local command output, a
// reminder, a task notification or an agent's report), never a
// turn the operator sent. Reports and notices are shown as such.
var raw string
if json.Unmarshal(entry.Message.Content, &raw) == nil {
if item := classifyInjected(raw, origin, entry.IsMeta); item.class == classAgentReport || item.class == classNotice {
addInjected(entry, item)
}
}
continue
}
blocks := decodeBlocks(entry.Message.Content)
@@ -263,14 +288,32 @@ func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHis
if hasResult || (text == "" && len(files) == 0) {
continue
}
if text != "" {
switch item := classifyInjected(text, origin, entry.IsMeta); item.class {
case classAgentReport, classNotice:
addInjected(entry, item)
continue
case classHidden:
continue
default:
text = item.text
}
} else if entry.IsMeta {
continue
}
addUser(entry, text, files)
case "attachment":
// A message the operator sent while the turn was running is recorded
// as a queued_command attachment where the CLI surfaced it to the
// model, so it is the user's turn at that point of the transcript.
// Other queued commands (task notifications, agent messages) are
// harness input, not the operator's.
if entry.Attachment.Type != "queued_command" || entry.Attachment.CommandMode != "prompt" {
// Other queued commands (task notifications, and agent reports the
// CLI also queues as "prompt" with an origin) are harness input:
// they are shown as notices and report cards, never as the operator's.
if entry.Attachment.Type != "queued_command" {
continue
}
mode := entry.Attachment.CommandMode
if mode != "prompt" && mode != "task-notification" {
continue
}
var text string
@@ -285,6 +328,19 @@ func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHis
if strings.TrimSpace(text) == "" {
continue
}
origin := decodeOrigin(entry.Attachment.Origin)
if mode == "task-notification" && origin.Kind == "" {
origin.Kind = "task-notification"
}
switch item := classifyInjected(text, origin, entry.Attachment.IsMeta); item.class {
case classAgentReport, classNotice:
addInjected(entry, item)
continue
case classHidden:
continue
default:
text = item.text
}
addUser(entry, text, []protocol.ChatPart{})
}
}
+14 -1
View File
@@ -34,6 +34,10 @@ type lineEnvelope struct {
IsError bool `json:"is_error"`
TotalCostUSD float64 `json:"total_cost_usd"`
Usage json.RawMessage `json:"usage"`
// Origin and IsMeta mark a user line the harness injected (an agent report,
// a task notification, a reminder); see classifyInjected.
Origin json.RawMessage `json:"origin"`
IsMeta bool `json:"isMeta"`
}
type contentBlock struct {
@@ -470,10 +474,18 @@ func (s *session) handleUser(envelope lineEnvelope) {
return
}
blocks := decodeBlocks(body.Content)
origin := decodeOrigin(envelope.Origin)
for _, block := range blocks {
if block.Type == "text" && strings.Contains(block.Text, "<task-notification>") {
if block.Type != "text" {
continue
}
if strings.Contains(block.Text, "<task-notification>") {
s.finishBackgroundTasks(block.Text)
}
// The operator's own prompts are published when they are sent, so the
// stream echo is never drawn again. Harness input that the operator did
// not send is drawn as a report card or a notice, never as a prompt.
s.emitInjected(classifyInjected(block.Text, origin, envelope.IsMeta))
}
for _, block := range blocks {
if block.Type != "tool_result" || block.ToolUseID == "" {
@@ -768,6 +780,7 @@ func (s *session) finishNotifiedTask(line []byte) {
if json.Unmarshal(line, &notice) != nil || notice.ToolUseID == "" {
return
}
s.emitInjected(taskNoticeLine(notice.ToolUseID, notice.Status, strings.Join(strings.Fields(notice.Summary), " ")))
s.finishBackgroundTasks(fmt.Sprintf(
"<task-notification><tool-use-id>%s</tool-use-id><status>%s</status><summary>%s</summary></task-notification>",
notice.ToolUseID, notice.Status, notice.Summary,
+24 -3
View File
@@ -184,6 +184,21 @@ const (
ChatRoleAssistant = "assistant"
)
// ChatMessage.Kind (and ChatEventFrame.MessageKind) values. A message with a
// kind is content the harness delivered into the session, never a turn the
// operator sent: it carries role assistant so an older client that ignores the
// kind still draws it on the agent's side, never as the operator's bubble.
//
// ChatMessageKindAgentReport is a report another agent (a delegated subagent or
// a peer session) delivered; its one text part is the report, and the part's
// Name carries the sender's label when the harness recorded one.
// ChatMessageKindNotice is a one-line harness notice, such as a background task
// finishing; its one text part is the line.
const (
ChatMessageKindAgentReport = "agent_report"
ChatMessageKindNotice = "notice"
)
// ChatModel is one model the current chat harness can switch to. ID is the
// provider's model id, Provider its provider id, Name the harness's display name.
type ChatModel struct {
@@ -436,9 +451,12 @@ type ChatMessage struct {
// Client is the sending device's label on a user turn the server echoed, so a
// resumed transcript still says who sent the message. It is empty on an
// assistant turn.
Client string `json:"client,omitempty"`
OperationID string `json:"operation_id,omitempty"`
Parts []ChatPart `json:"parts"`
Client string `json:"client,omitempty"`
OperationID string `json:"operation_id,omitempty"`
// Kind is empty for an ordinary user or assistant turn, or one of the
// ChatMessageKind values for content the harness injected.
Kind string `json:"kind,omitempty"`
Parts []ChatPart `json:"parts"`
}
// ChatDeltaPartID is the stable part id an incremental text or reasoning delta
@@ -539,6 +557,9 @@ type ChatEventFrame struct {
// transcript can say who sent the message. It is empty on assistant frames.
Client string `json:"client,omitempty"`
OperationID string `json:"operation_id,omitempty"`
// MessageKind is the ChatMessage.Kind of the message a text frame starts,
// so a live agent report or notice is never drawn as an answer or a prompt.
MessageKind string `json:"message_kind,omitempty"`
}
// ChatCompaction is session activity, never a transcript message or tool.
+10 -3
View File
@@ -79,8 +79,11 @@ type chatMessage struct {
role string
client string
operationID string
order []string
parts map[string]*chatPart
// kind is the ChatMessage.Kind of harness-injected content (an agent
// report or a notice); empty for an ordinary turn.
kind string
order []string
parts map[string]*chatPart
}
type chatTurn struct {
@@ -232,6 +235,9 @@ func (h *chatHub) applyLocked(frame protocol.ChatEventFrame) {
if message.operationID == "" && frame.Kind == protocol.ChatEventUser {
message.operationID = frame.OperationID
}
if message.kind == "" && frame.MessageKind != "" && frame.Kind != protocol.ChatEventUser {
message.kind = frame.MessageKind
}
switch frame.Kind {
case protocol.ChatEventUser:
if frame.Part == nil || frame.Part.ID == "" || frame.Part.Text == "" || turn.overflow {
@@ -260,7 +266,7 @@ func (h *chatHub) applyLocked(frame protocol.ChatEventFrame) {
}
part, ok := message.parts[id]
if !ok {
part = &chatPart{part: protocol.ChatPart{Type: frame.Kind, ID: id}}
part = &chatPart{part: protocol.ChatPart{Type: frame.Kind, ID: id, Name: frame.Part.Name}}
message.order = append(message.order, id)
message.parts[id] = part
}
@@ -553,6 +559,7 @@ func (h *chatHub) snapshot(sessionID string) []protocol.ChatMessage {
}
out.Client = message.client
out.OperationID = message.operationID
out.Kind = message.kind
for _, partID := range message.order {
if part, ok := message.parts[partID]; ok {
piece := part.part
+29
View File
@@ -0,0 +1,29 @@
package server
import (
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// A live agent report keeps its kind and sender across a resume snapshot, and
// is never mistaken for the agent's final reply.
func TestHubKeepsInjectedMessageKind(t *testing.T) {
h := newChatHub()
h.apply(protocol.ChatEventFrame{SessionID: "s", MessageID: "msg_1", Kind: protocol.ChatEventText, Delta: "The answer", Part: &protocol.ChatPart{ID: "msg_1#text#0"}})
h.apply(protocol.ChatEventFrame{
SessionID: "s", MessageID: "agent-report-x", MessageKind: protocol.ChatMessageKindAgentReport, Kind: protocol.ChatEventText,
Delta: "## Report", Part: &protocol.ChatPart{ID: "agent-report-x#text#0", Name: "general-purpose"},
})
messages := h.snapshot("s")
if len(messages) != 2 || messages[0].Kind != "" || messages[1].Kind != protocol.ChatMessageKindAgentReport ||
messages[1].Role != protocol.ChatRoleAssistant || messages[1].Parts[0].Name != "general-purpose" || messages[1].Parts[0].Text != "## Report" {
t.Fatalf("snapshot: %+v", messages)
}
h.mu.Lock()
reply := h.finalReplyTextLocked("s")
h.mu.Unlock()
if reply != "The answer" {
t.Fatalf("final reply must skip the report, got %q", reply)
}
}
+4
View File
@@ -62,6 +62,10 @@ func (h *chatHub) finalReplyTextLocked(sessionID string) string {
if message.role == protocol.ChatRoleUser {
return ""
}
if message.kind != "" {
// An agent report or notice the harness delivered is not the reply.
continue
}
var text strings.Builder
for _, id := range message.order {
part := message.parts[id]