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:
@@ -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},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user