package claude import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "os" "path/filepath" "strconv" "strings" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // maxTranscriptBytes bounds one history read. A Claude session file grows with // every turn; past this bound only its newest maxTranscriptBytes are read, and // the history says plainly that earlier turns are not shown instead of // refusing the whole chat. var maxTranscriptBytes int64 = 64 << 20 type transcriptEntry struct { Type string `json:"type"` Subtype string `json:"subtype"` UUID string `json:"uuid"` IsSidechain bool `json:"isSidechain"` Timestamp string `json:"timestamp"` Cwd string `json:"cwd"` Message struct { ID string `json:"id"` Role string `json:"role"` Model string `json:"model"` Content json.RawMessage `json:"content"` } `json:"message"` // 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. Attachment 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) { entries, _, err := readTranscriptTail(path) return entries, err } // readTranscriptTail reads the session file's entries, or only those in its // newest maxTranscriptBytes when it is larger. skipped is how many leading // bytes were not read (0 for the whole file); a read that starts mid-file // begins at the first whole line. func readTranscriptTail(path string) (entries []transcriptEntry, skipped int64, err error) { file, err := os.Open(path) if err != nil { return nil, 0, err } defer file.Close() info, err := file.Stat() if err != nil { return nil, 0, err } reader := bufio.NewReaderSize(file, 64<<10) if info.Size() > maxTranscriptBytes { skipped = info.Size() - maxTranscriptBytes if _, err := file.Seek(skipped, io.SeekStart); err != nil { return nil, 0, err } reader.Reset(file) // The cut lands inside a line: drop that partial line. partial, err := reader.ReadBytes('\n') if err != nil && err != io.EOF { return nil, 0, err } skipped += int64(len(partial)) } scanner := bufio.NewScanner(reader) scanner.Buffer(make([]byte, 0, 64<<10), maxLineBytes) for scanner.Scan() { line := scanner.Bytes() if len(line) == 0 { continue } var entry transcriptEntry if json.Unmarshal(line, &entry) == nil { entries = append(entries, entry) } } if err := scanner.Err(); err != nil { return nil, 0, err } return entries, skipped, nil } // earlierHistoryNotice is the first message of a history read from the tail of // an oversized session file: it says how much was left out and where it is. func earlierHistoryNotice(sessionID string, skipped int64, created int64) protocol.ChatMessage { id := sessionID + "#earlier-history" text := fmt.Sprintf("Earlier history is not shown: this session's transcript is larger than %d MiB, so only its newest %d MiB are loaded (%d MiB earlier are left out). The full conversation is in Claude Code's session file; `claude --resume %s` opens it in a terminal.", maxTranscriptBytes>>20, maxTranscriptBytes>>20, (skipped+(1<<20)-1)>>20, sessionID) part := protocol.ChatPart{Type: protocol.ChatPartText, ID: protocol.ChatDeltaPartID(id, protocol.ChatPartText, 0), Text: text} return protocol.ChatMessage{ID: id, SessionID: sessionID, Role: protocol.ChatRoleAssistant, Kind: protocol.ChatMessageKindNotice, CreatedAt: created, Parts: []protocol.ChatPart{part}} } // transcriptSession describes a session from its retained file, so the manager // can resolve a registry row after a restart. func transcriptSession(id string) (protocol.ChatSession, bool) { path := findTranscriptFile(id) if path == "" { return protocol.ChatSession{}, false } session := protocol.ChatSession{ID: id, Backend: Backend, ModelProvider: Backend, Tag: protocol.ChatSessionTagOperator} meta, ok := indexedTranscriptMeta(path) if !ok { entries, err := readTranscript(path) if err != nil { return session, true } 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 } parsed, err := time.Parse(time.RFC3339Nano, text) if err != nil { return 0, false } return parsed.UnixMilli(), true } // transcriptMessages maps the CLI's own session file 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. func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHistoryPage, error) { newest := strings.TrimSpace(cursor) == "" || cursor == "0" // Taken before the file is read: a block completing in between is then // whole in the file, never missing from both (see live.go). overlay := s.liveOverlaySnapshot() page, err := s.transcriptPage(limit, cursor) if err == nil && newest { overlay.apply(&page, s.id) } return page, err } func (s *session) transcriptPage(limit int, cursor string) (protocol.ChatHistoryPage, error) { path := findTranscriptFile(s.id) 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 } builder := newTranscriptBuilder(sessionID, promptMatcher(prompts)) if skipped > 0 { created := int64(0) for _, entry := range entries { if stamp, ok := transcriptTime(entry.Timestamp); ok { created = stamp break } } builder.messages = append(builder.messages, earlierHistoryNotice(sessionID, skipped, created)) } for _, entry := range entries { builder.add(entry) } 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 } if strings.TrimSpace(cursor) != "" { if parsed, err := strconv.Atoi(cursor); err == nil && parsed >= 0 { offset = parsed } } if offset > total { offset = total } end = total - offset start = end - limit if start < 0 { start = 0 } 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 } // 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. type blockOrdinals map[string]map[string]int func (o blockOrdinals) next(messageID, kind string) int { counts := o[messageID] if counts == nil { counts = map[string]int{} o[messageID] = counts } ordinal := counts[kind] counts[kind] = ordinal + 1 return ordinal } func applyTranscriptToolResult(messages *[]protocol.ChatMessage, toolIndex map[string][2]int, block contentBlock) { position, ok := toolIndex[block.ToolUseID] if !ok || position[0] >= len(*messages) { return } message := &(*messages)[position[0]] if position[1] >= len(message.Parts) { return } part := &message.Parts[position[1]] if part.State == nil { part.State = &protocol.ChatToolState{} } text, images := toolResultContent(block.Content) status := protocol.ChatToolCompleted var toolErr *protocol.ChatError exit := exitCode(text) if block.IsError || (exit != nil && *exit != 0) { status = protocol.ChatToolError detail := strings.TrimSpace(text) if detail == "" { detail = "the tool returned an error" } toolErr = &protocol.ChatError{Type: "tool", Message: boundedText(detail, 2<<10)} } part.State.Status = status part.State.Error = toolErr if text != "" { part.State.Content = append(part.State.Content, protocol.ChatToolContent{Type: "text", Text: boundedText(text, 128<<10)}) } part.State.Content = append(part.State.Content, images...) } // Messages serves the authoritative transcript history. func (c *Chat) Messages(ctx context.Context, id string, limit int, cursor string) (protocol.ChatHistoryPage, error) { s := c.session(id) if s == nil { meta, ok := transcriptSession(id) if !ok { return protocol.ChatHistoryPage{}, errors.New("unknown Claude session " + id) } s = c.sessionFor(id, meta.Directory) } return s.transcriptMessages(limit, cursor) } // sessionTranscriptPath is used by tests and diagnostics. func sessionTranscriptPath(id string) string { path := findTranscriptFile(id) if path == "" { return "" } return filepath.Clean(path) }