Server: serve a Claude chat's history page from a per-file line index
Reading a history page parsed the whole session file (tens of MB) on every chat_messages. A per-file index now records which lines build each shown message; a page re-reads and replays only its own messages' lines, and the index follows appends by reading only the new bytes. Results match the whole-file read (compared page by page on synthetic transcripts); shapes the index cannot replay exactly fall back to the whole-file read. chat_subscribe may ask (history: true) for the newest page in its reply, read once the subscription is attached, saving the client a round trip. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+370
-245
@@ -35,8 +35,8 @@ type transcriptEntry struct {
|
||||
Model string `json:"model"`
|
||||
Content json.RawMessage `json:"content"`
|
||||
} `json:"message"`
|
||||
ToolUseResult json.RawMessage `json:"toolUseResult"`
|
||||
Compact json.RawMessage `json:"compactMetadata"`
|
||||
// toolUseResult (a tool's structured output, often a whole file) is not
|
||||
// read: decoding skips it instead of copying it.
|
||||
// Attachment is set on "attachment" entries; a queued_command with
|
||||
// commandMode "prompt" is a user message the CLI read mid-turn. Prompt is
|
||||
// either a string or an array of content blocks.
|
||||
@@ -124,29 +124,46 @@ func transcriptSession(id string) (protocol.ChatSession, bool) {
|
||||
return protocol.ChatSession{}, false
|
||||
}
|
||||
session := protocol.ChatSession{ID: id, Backend: Backend, ModelProvider: Backend, Tag: protocol.ChatSessionTagOperator}
|
||||
entries, err := readTranscript(path)
|
||||
if err != nil {
|
||||
return session, true
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.Cwd != "" && session.Directory == "" {
|
||||
session.Directory = entry.Cwd
|
||||
meta, ok := indexedTranscriptMeta(path)
|
||||
if !ok {
|
||||
entries, err := readTranscript(path)
|
||||
if err != nil {
|
||||
return session, true
|
||||
}
|
||||
if stamp, ok := transcriptTime(entry.Timestamp); ok {
|
||||
if session.CreatedAt == 0 || stamp < session.CreatedAt {
|
||||
session.CreatedAt = stamp
|
||||
}
|
||||
if stamp > session.UpdatedAt {
|
||||
session.UpdatedAt = stamp
|
||||
}
|
||||
}
|
||||
if entry.Type == "assistant" && entry.Message.Model != "" && !entry.IsSidechain {
|
||||
session.Model = entry.Message.Model
|
||||
meta = transcriptMeta{}
|
||||
for _, entry := range entries {
|
||||
meta.note(entry)
|
||||
}
|
||||
}
|
||||
session.Directory, session.CreatedAt, session.UpdatedAt, session.Model = meta.directory, meta.created, meta.updated, meta.model
|
||||
return session, true
|
||||
}
|
||||
|
||||
// transcriptMeta is what a session file says about its session: the first
|
||||
// working directory, the first and last times, and the main thread's model.
|
||||
type transcriptMeta struct {
|
||||
directory string
|
||||
created, updated int64
|
||||
model string
|
||||
}
|
||||
|
||||
func (m *transcriptMeta) note(entry transcriptEntry) {
|
||||
if entry.Cwd != "" && m.directory == "" {
|
||||
m.directory = entry.Cwd
|
||||
}
|
||||
if stamp, ok := transcriptTime(entry.Timestamp); ok {
|
||||
if m.created == 0 || stamp < m.created {
|
||||
m.created = stamp
|
||||
}
|
||||
if stamp > m.updated {
|
||||
m.updated = stamp
|
||||
}
|
||||
}
|
||||
if entry.Type == "assistant" && entry.Message.Model != "" && !entry.IsSidechain {
|
||||
m.model = entry.Message.Model
|
||||
}
|
||||
}
|
||||
|
||||
func transcriptTime(text string) (int64, bool) {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return 0, false
|
||||
@@ -178,35 +195,25 @@ func (s *session) transcriptPage(limit int, cursor string) (protocol.ChatHistory
|
||||
if path == "" {
|
||||
return protocol.ChatHistoryPage{Messages: []protocol.ChatMessage{}}, nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
prompts := append([]promptRecord(nil), s.prompts...)
|
||||
s.mu.Unlock()
|
||||
// The file's message index serves a page by re-reading only that page's
|
||||
// lines; the whole file is read only when the index cannot serve it.
|
||||
if page, ok, err := indexedTranscriptPage(path, s.id, prompts, limit, cursor); ok || err != nil {
|
||||
return page, err
|
||||
}
|
||||
return fullTranscriptPage(path, s.id, prompts, limit, cursor)
|
||||
}
|
||||
|
||||
// fullTranscriptPage builds every message of the session file and pages them.
|
||||
// It is the reference the indexed read matches, and its fallback.
|
||||
func fullTranscriptPage(path, sessionID string, prompts []promptRecord, limit int, cursor string) (protocol.ChatHistoryPage, error) {
|
||||
entries, skipped, err := readTranscriptTail(path)
|
||||
if err != nil {
|
||||
return protocol.ChatHistoryPage{}, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
prompts := append([]promptRecord(nil), s.prompts...)
|
||||
s.mu.Unlock()
|
||||
promptIDs := map[string][]string{}
|
||||
for _, prompt := range prompts {
|
||||
if prompt.id == "" || prompt.text == "" {
|
||||
continue
|
||||
}
|
||||
promptIDs[prompt.text] = append(promptIDs[prompt.text], prompt.id)
|
||||
}
|
||||
usedPrompts := map[string]int{}
|
||||
takePromptID := func(text string) string {
|
||||
text = strings.TrimSpace(text)
|
||||
ids := promptIDs[text]
|
||||
if len(ids) == 0 {
|
||||
return ""
|
||||
}
|
||||
index := usedPrompts[text]
|
||||
if index >= len(ids) {
|
||||
return ""
|
||||
}
|
||||
usedPrompts[text] = index + 1
|
||||
return ids[index]
|
||||
}
|
||||
messages := []protocol.ChatMessage{}
|
||||
builder := newTranscriptBuilder(sessionID, promptMatcher(prompts))
|
||||
if skipped > 0 {
|
||||
created := int64(0)
|
||||
for _, entry := range entries {
|
||||
@@ -215,229 +222,347 @@ func (s *session) transcriptPage(limit int, cursor string) (protocol.ChatHistory
|
||||
break
|
||||
}
|
||||
}
|
||||
messages = append(messages, earlierHistoryNotice(s.id, skipped, created))
|
||||
}
|
||||
messageIndex := map[string]int{}
|
||||
ordinals := blockOrdinals{}
|
||||
toolIndex := map[string][2]int{} // tool id -> message/part index
|
||||
addUser := func(entry transcriptEntry, text string, files []protocol.ChatPart) {
|
||||
id := takePromptID(text)
|
||||
if id == "" {
|
||||
id = entry.UUID
|
||||
}
|
||||
if id == "" {
|
||||
return
|
||||
}
|
||||
created, _ := transcriptTime(entry.Timestamp)
|
||||
parts := []protocol.ChatPart{}
|
||||
if text != "" {
|
||||
parts = append(parts, protocol.ChatPart{Type: protocol.ChatPartText, ID: id + "#text", Text: text})
|
||||
}
|
||||
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))
|
||||
builder.messages = append(builder.messages, earlierHistoryNotice(sessionID, skipped, created))
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.IsSidechain {
|
||||
continue
|
||||
}
|
||||
switch entry.Type {
|
||||
case "assistant":
|
||||
messageID := strings.TrimSpace(entry.Message.ID)
|
||||
if messageID == "" {
|
||||
messageID = entry.UUID
|
||||
}
|
||||
if messageID == "" {
|
||||
continue
|
||||
}
|
||||
created, _ := transcriptTime(entry.Timestamp)
|
||||
index, exists := messageIndex[messageID]
|
||||
if !exists {
|
||||
messages = append(messages, protocol.ChatMessage{ID: messageID, SessionID: s.id, Role: protocol.ChatRoleAssistant, Model: entry.Message.Model, CreatedAt: created, Parts: []protocol.ChatPart{}})
|
||||
index = len(messages) - 1
|
||||
messageIndex[messageID] = index
|
||||
}
|
||||
if entry.Message.Model != "" {
|
||||
messages[index].Model = entry.Message.Model
|
||||
}
|
||||
blocks := decodeBlocks(entry.Message.Content)
|
||||
for _, block := range blocks {
|
||||
switch block.Type {
|
||||
case "text":
|
||||
// Every block of a kind takes an ordinal, empty or not, as
|
||||
// the live stream numbers them when they start: a part keeps
|
||||
// one id live and in history.
|
||||
ordinal := ordinals.next(messageID, protocol.ChatPartText)
|
||||
if strings.TrimSpace(block.Text) == "" {
|
||||
continue
|
||||
}
|
||||
part := protocol.ChatPart{Type: protocol.ChatPartText, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartText, ordinal), Text: block.Text}
|
||||
messages[index].Parts = append(messages[index].Parts, part)
|
||||
case "thinking":
|
||||
// An empty (display-omitted) thinking block often precedes
|
||||
// the one with text; it is counted, not shown.
|
||||
ordinal := ordinals.next(messageID, protocol.ChatPartReasoning)
|
||||
if strings.TrimSpace(block.Thinking) == "" {
|
||||
continue
|
||||
}
|
||||
part := protocol.ChatPart{Type: protocol.ChatPartReasoning, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartReasoning, ordinal), Text: block.Thinking}
|
||||
messages[index].Parts = append(messages[index].Parts, part)
|
||||
case "tool_use":
|
||||
if block.ID == "" {
|
||||
continue
|
||||
}
|
||||
part := protocol.ChatPart{
|
||||
Type: protocol.ChatPartTool,
|
||||
ID: block.ID,
|
||||
Name: block.Name,
|
||||
State: &protocol.ChatToolState{
|
||||
Status: protocol.ChatToolRunning,
|
||||
Input: truncateJSON(block.Input, 64<<10),
|
||||
},
|
||||
}
|
||||
messages[index].Parts = append(messages[index].Parts, part)
|
||||
toolIndex[block.ID] = [2]int{index, len(messages[index].Parts) - 1}
|
||||
}
|
||||
}
|
||||
case "user":
|
||||
origin := decodeOrigin(entry.Origin)
|
||||
if len(entry.Message.Content) > 0 && entry.Message.Content[0] == '"' {
|
||||
// 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)
|
||||
var text string
|
||||
files := []protocol.ChatPart{}
|
||||
hasResult := false
|
||||
for _, block := range blocks {
|
||||
switch block.Type {
|
||||
case "tool_result":
|
||||
hasResult = true
|
||||
applyTranscriptToolResult(&messages, toolIndex, block)
|
||||
case "text":
|
||||
if strings.TrimSpace(block.Text) == "" {
|
||||
continue
|
||||
}
|
||||
if text != "" {
|
||||
text += "\n"
|
||||
}
|
||||
text += block.Text
|
||||
case "image":
|
||||
if block.Source != nil && block.Source.Data != "" && len(block.Source.Data) <= 512<<10 {
|
||||
files = append(files, protocol.ChatPart{Type: protocol.ChatPartFile, Mime: block.Source.MediaType, Name: "image", URI: "data:" + block.Source.MediaType + ";base64," + block.Source.Data})
|
||||
}
|
||||
}
|
||||
}
|
||||
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, 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
|
||||
for _, block := range decodeBlocks(entry.Attachment.Prompt) {
|
||||
if block.Type == "text" && strings.TrimSpace(block.Text) != "" {
|
||||
if text != "" {
|
||||
text += "\n"
|
||||
}
|
||||
text += block.Text
|
||||
}
|
||||
}
|
||||
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{})
|
||||
}
|
||||
builder.add(entry)
|
||||
}
|
||||
// Drop assistant messages that ended with no renderable part (for example a
|
||||
// signature-only thinking entry).
|
||||
filtered := messages[:0]
|
||||
for _, message := range messages {
|
||||
if len(message.Parts) > 0 {
|
||||
filtered = append(filtered, message)
|
||||
}
|
||||
}
|
||||
messages = filtered
|
||||
messages := builder.shown()
|
||||
start, end, offset := pageBounds(len(messages), limit, cursor)
|
||||
return historyPage(messages[start:end], start, offset), nil
|
||||
}
|
||||
|
||||
// pageBounds selects, out of total messages, the newest limit below cursor (the
|
||||
// count of newest messages already served).
|
||||
func pageBounds(total, limit int, cursor string) (start, end, offset int) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > 100 {
|
||||
limit = 100
|
||||
}
|
||||
offset := 0
|
||||
if strings.TrimSpace(cursor) != "" {
|
||||
if parsed, err := strconv.Atoi(cursor); err == nil && parsed >= 0 {
|
||||
offset = parsed
|
||||
}
|
||||
}
|
||||
if offset > len(messages) {
|
||||
offset = len(messages)
|
||||
if offset > total {
|
||||
offset = total
|
||||
}
|
||||
end := len(messages) - offset
|
||||
start := end - limit
|
||||
end = total - offset
|
||||
start = end - limit
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
page := protocol.ChatHistoryPage{Messages: append([]protocol.ChatMessage{}, messages[start:end]...)}
|
||||
return start, end, offset
|
||||
}
|
||||
|
||||
func historyPage(messages []protocol.ChatMessage, start, offset int) protocol.ChatHistoryPage {
|
||||
page := protocol.ChatHistoryPage{Messages: append([]protocol.ChatMessage{}, messages...)}
|
||||
if start > 0 {
|
||||
page.HasMore = true
|
||||
page.NextCursor = strconv.Itoa(offset + len(page.Messages))
|
||||
}
|
||||
return page, nil
|
||||
return page
|
||||
}
|
||||
|
||||
// promptIDs lists, per prompt text, the ids the operator's client sent that
|
||||
// text with, oldest first.
|
||||
func promptIDs(prompts []promptRecord) map[string][]string {
|
||||
ids := map[string][]string{}
|
||||
for _, prompt := range prompts {
|
||||
if prompt.id == "" || prompt.text == "" {
|
||||
continue
|
||||
}
|
||||
ids[prompt.text] = append(ids[prompt.text], prompt.id)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// promptMatcher names user turns in file order: the n-th turn with a prompt's
|
||||
// text takes that text's n-th recorded id, any other turn its entry's uuid.
|
||||
func promptMatcher(prompts []promptRecord) func(entry transcriptEntry, text string) string {
|
||||
ids := promptIDs(prompts)
|
||||
used := map[string]int{}
|
||||
return func(entry transcriptEntry, text string) string {
|
||||
text = strings.TrimSpace(text)
|
||||
index := used[text]
|
||||
if index >= len(ids[text]) {
|
||||
return entry.UUID
|
||||
}
|
||||
used[text] = index + 1
|
||||
return ids[text][index]
|
||||
}
|
||||
}
|
||||
|
||||
// transcriptBuilder maps the CLI's session file entries, in file order, into
|
||||
// chat messages. It merges the JSONL's one-entry-per-content-block shape by
|
||||
// message id, attaches tool results to the call that produced them, and never
|
||||
// invents a turn.
|
||||
type transcriptBuilder struct {
|
||||
sessionID string
|
||||
messages []protocol.ChatMessage
|
||||
messageIndex map[string]int
|
||||
ordinals blockOrdinals
|
||||
toolIndex map[string][2]int // tool id -> message/part index
|
||||
injectedSeen map[string]bool
|
||||
// userID names a user turn; an empty name drops the turn.
|
||||
userID func(entry transcriptEntry, text string) string
|
||||
}
|
||||
|
||||
func newTranscriptBuilder(sessionID string, userID func(transcriptEntry, string) string) *transcriptBuilder {
|
||||
return &transcriptBuilder{
|
||||
sessionID: sessionID,
|
||||
messages: []protocol.ChatMessage{},
|
||||
messageIndex: map[string]int{},
|
||||
ordinals: blockOrdinals{},
|
||||
toolIndex: map[string][2]int{},
|
||||
injectedSeen: map[string]bool{},
|
||||
userID: userID,
|
||||
}
|
||||
}
|
||||
|
||||
// shown is the built messages less assistant messages that ended with no
|
||||
// renderable part (for example a signature-only thinking entry).
|
||||
func (b *transcriptBuilder) shown() []protocol.ChatMessage {
|
||||
filtered := b.messages[:0]
|
||||
for _, message := range b.messages {
|
||||
if len(message.Parts) > 0 {
|
||||
filtered = append(filtered, message)
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
func (b *transcriptBuilder) add(entry transcriptEntry) {
|
||||
if entry.IsSidechain {
|
||||
return
|
||||
}
|
||||
switch entry.Type {
|
||||
case "assistant":
|
||||
b.addAssistant(entry)
|
||||
case "user", "attachment":
|
||||
input := entryInputOf(entry)
|
||||
for _, block := range input.results {
|
||||
applyTranscriptToolResult(&b.messages, b.toolIndex, block)
|
||||
}
|
||||
if input.injected.id != "" {
|
||||
b.addInjected(entry, input.injected)
|
||||
} else if input.user {
|
||||
b.addUser(entry, input.text, input.files)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *transcriptBuilder) addUser(entry transcriptEntry, text string, files []protocol.ChatPart) {
|
||||
id := b.userID(entry, text)
|
||||
if id == "" {
|
||||
return
|
||||
}
|
||||
created, _ := transcriptTime(entry.Timestamp)
|
||||
parts := []protocol.ChatPart{}
|
||||
if text != "" {
|
||||
parts = append(parts, protocol.ChatPart{Type: protocol.ChatPartText, ID: id + "#text", Text: text})
|
||||
}
|
||||
parts = append(parts, files...)
|
||||
b.messages = append(b.messages, protocol.ChatMessage{ID: id, SessionID: b.sessionID, Role: protocol.ChatRoleUser, CreatedAt: created, Parts: parts})
|
||||
}
|
||||
|
||||
func (b *transcriptBuilder) addInjected(entry transcriptEntry, item injected) {
|
||||
if b.injectedSeen[item.id] {
|
||||
return
|
||||
}
|
||||
b.injectedSeen[item.id] = true
|
||||
created, _ := transcriptTime(entry.Timestamp)
|
||||
b.messages = append(b.messages, item.message(b.sessionID, created))
|
||||
}
|
||||
|
||||
func (b *transcriptBuilder) addAssistant(entry transcriptEntry) {
|
||||
messageID := assistantMessageID(entry)
|
||||
if messageID == "" {
|
||||
return
|
||||
}
|
||||
created, _ := transcriptTime(entry.Timestamp)
|
||||
index, exists := b.messageIndex[messageID]
|
||||
if !exists {
|
||||
b.messages = append(b.messages, protocol.ChatMessage{ID: messageID, SessionID: b.sessionID, Role: protocol.ChatRoleAssistant, Model: entry.Message.Model, CreatedAt: created, Parts: []protocol.ChatPart{}})
|
||||
index = len(b.messages) - 1
|
||||
b.messageIndex[messageID] = index
|
||||
}
|
||||
if entry.Message.Model != "" {
|
||||
b.messages[index].Model = entry.Message.Model
|
||||
}
|
||||
for _, block := range decodeBlocks(entry.Message.Content) {
|
||||
switch block.Type {
|
||||
case "text":
|
||||
// Every block of a kind takes an ordinal, empty or not, as the
|
||||
// live stream numbers them when they start: a part keeps one id
|
||||
// live and in history.
|
||||
ordinal := b.ordinals.next(messageID, protocol.ChatPartText)
|
||||
if !shownAssistantBlock(block) {
|
||||
continue
|
||||
}
|
||||
part := protocol.ChatPart{Type: protocol.ChatPartText, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartText, ordinal), Text: block.Text}
|
||||
b.messages[index].Parts = append(b.messages[index].Parts, part)
|
||||
case "thinking":
|
||||
// An empty (display-omitted) thinking block often precedes the
|
||||
// one with text; it is counted, not shown.
|
||||
ordinal := b.ordinals.next(messageID, protocol.ChatPartReasoning)
|
||||
if !shownAssistantBlock(block) {
|
||||
continue
|
||||
}
|
||||
part := protocol.ChatPart{Type: protocol.ChatPartReasoning, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartReasoning, ordinal), Text: block.Thinking}
|
||||
b.messages[index].Parts = append(b.messages[index].Parts, part)
|
||||
case "tool_use":
|
||||
if !shownAssistantBlock(block) {
|
||||
continue
|
||||
}
|
||||
part := protocol.ChatPart{
|
||||
Type: protocol.ChatPartTool,
|
||||
ID: block.ID,
|
||||
Name: block.Name,
|
||||
State: &protocol.ChatToolState{
|
||||
Status: protocol.ChatToolRunning,
|
||||
Input: truncateJSON(block.Input, 64<<10),
|
||||
},
|
||||
}
|
||||
b.messages[index].Parts = append(b.messages[index].Parts, part)
|
||||
b.toolIndex[block.ID] = [2]int{index, len(b.messages[index].Parts) - 1}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// assistantMessageID is the id an assistant entry's blocks merge under.
|
||||
func assistantMessageID(entry transcriptEntry) string {
|
||||
if messageID := strings.TrimSpace(entry.Message.ID); messageID != "" {
|
||||
return messageID
|
||||
}
|
||||
return entry.UUID
|
||||
}
|
||||
|
||||
// shownAssistantBlock reports whether an assistant content block becomes a part.
|
||||
func shownAssistantBlock(block contentBlock) bool {
|
||||
switch block.Type {
|
||||
case "text":
|
||||
return strings.TrimSpace(block.Text) != ""
|
||||
case "thinking":
|
||||
return strings.TrimSpace(block.Thinking) != ""
|
||||
case "tool_use":
|
||||
return block.ID != ""
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// entryInput is what one user or attachment entry contributes: results for
|
||||
// earlier tool calls, then at most one message, either an injected report or
|
||||
// notice (injected.id set) or the operator's turn (user set).
|
||||
type entryInput struct {
|
||||
results []contentBlock
|
||||
injected injected
|
||||
user bool
|
||||
text string
|
||||
files []protocol.ChatPart
|
||||
}
|
||||
|
||||
func entryInputOf(entry transcriptEntry) entryInput {
|
||||
if entry.Type == "attachment" {
|
||||
return attachmentEntryInput(entry)
|
||||
}
|
||||
return userEntryInput(entry)
|
||||
}
|
||||
|
||||
func userEntryInput(entry transcriptEntry) (input entryInput) {
|
||||
origin := decodeOrigin(entry.Origin)
|
||||
if len(entry.Message.Content) > 0 && entry.Message.Content[0] == '"' {
|
||||
// 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 {
|
||||
input.injected = item
|
||||
}
|
||||
}
|
||||
return input
|
||||
}
|
||||
var text string
|
||||
files := []protocol.ChatPart{}
|
||||
for _, block := range decodeBlocks(entry.Message.Content) {
|
||||
switch block.Type {
|
||||
case "tool_result":
|
||||
input.results = append(input.results, block)
|
||||
case "text":
|
||||
if strings.TrimSpace(block.Text) == "" {
|
||||
continue
|
||||
}
|
||||
if text != "" {
|
||||
text += "\n"
|
||||
}
|
||||
text += block.Text
|
||||
case "image":
|
||||
if block.Source != nil && block.Source.Data != "" && len(block.Source.Data) <= 512<<10 {
|
||||
files = append(files, protocol.ChatPart{Type: protocol.ChatPartFile, Mime: block.Source.MediaType, Name: "image", URI: "data:" + block.Source.MediaType + ";base64," + block.Source.Data})
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(input.results) > 0 || (text == "" && len(files) == 0) {
|
||||
return input
|
||||
}
|
||||
if text != "" {
|
||||
switch item := classifyInjected(text, origin, entry.IsMeta); item.class {
|
||||
case classAgentReport, classNotice:
|
||||
input.injected = item
|
||||
return input
|
||||
case classHidden:
|
||||
return input
|
||||
default:
|
||||
text = item.text
|
||||
}
|
||||
} else if entry.IsMeta {
|
||||
return input
|
||||
}
|
||||
input.user, input.text, input.files = true, text, files
|
||||
return input
|
||||
}
|
||||
|
||||
// attachmentEntryInput reads an attachment entry. 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, 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.
|
||||
func attachmentEntryInput(entry transcriptEntry) (input entryInput) {
|
||||
if entry.Attachment.Type != "queued_command" {
|
||||
return input
|
||||
}
|
||||
mode := entry.Attachment.CommandMode
|
||||
if mode != "prompt" && mode != "task-notification" {
|
||||
return input
|
||||
}
|
||||
var text string
|
||||
for _, block := range decodeBlocks(entry.Attachment.Prompt) {
|
||||
if block.Type == "text" && strings.TrimSpace(block.Text) != "" {
|
||||
if text != "" {
|
||||
text += "\n"
|
||||
}
|
||||
text += block.Text
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return input
|
||||
}
|
||||
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:
|
||||
input.injected = item
|
||||
case classHidden:
|
||||
default:
|
||||
input.user, input.text, input.files = true, item.text, []protocol.ChatPart{}
|
||||
}
|
||||
return input
|
||||
}
|
||||
|
||||
// blockOrdinals counts each message's text and thinking blocks by kind.
|
||||
|
||||
Reference in New Issue
Block a user