Files

226 lines
6.5 KiB
Go

package claude
import (
"bufio"
"encoding/json"
"errors"
"io"
"os"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func applyToolMetadata(shell *protocol.ChatShell, name string, input json.RawMessage, timestamp string) {
if shell.StartedAt == 0 {
if stamp, ok := transcriptTime(timestamp); ok && stamp > 0 {
shell.StartedAt = stamp
}
}
if shell.TaskType == "" {
if name == "Bash" {
shell.TaskType = "shell"
} else {
shell.TaskType = "agent"
}
}
var fields struct {
Description string `json:"description"`
}
if json.Unmarshal(input, &fields) == nil && fields.Description != "" && shell.Description == "" {
shell.Description = boundedText(fields.Description, 2048)
}
}
// SDK task events identify the initiating tool use, then task_id correlates
// progress messages which omit tool_use_id. They do not all carry a timestamp.
// Missing event times stay absent: replay wall time is not task creation time.
func (s *session) handleTaskMetadata(raw []byte) {
var event struct {
TaskID string `json:"task_id"`
ToolUseID string `json:"tool_use_id"`
TaskType string `json:"task_type"`
Description string `json:"description"`
Summary string `json:"summary"`
LastTool string `json:"last_tool_name"`
Timestamp string `json:"timestamp"`
Usage struct {
DurationMS *int64 `json:"duration_ms"`
Tools *int64 `json:"tool_uses"`
Tokens *int64 `json:"total_tokens"`
} `json:"usage"`
}
if json.Unmarshal(raw, &event) != nil {
return
}
s.mu.Lock()
snapshot := s.shells[event.ToolUseID]
if snapshot == nil && event.TaskID != "" {
for _, candidate := range s.shells {
if candidate.taskID == event.TaskID {
snapshot = candidate
break
}
}
}
if snapshot == nil {
s.mu.Unlock()
return
}
if event.TaskID != "" {
snapshot.taskID = event.TaskID
}
// Out-of-order readback/progress must not replace newer recorded progress.
if event.Usage.DurationMS != nil && snapshot.shell.DurationMS != nil && *event.Usage.DurationMS < *snapshot.shell.DurationMS {
s.mu.Unlock()
return
}
shell := &snapshot.shell
if event.TaskType != "" {
shell.TaskType = boundedText(event.TaskType, 128)
}
if event.Description != "" {
shell.Description = boundedText(event.Description, 2048)
}
if event.Summary != "" {
shell.Progress = boundedText(event.Summary, 2048)
}
if event.LastTool != "" {
shell.LastTool = boundedText(event.LastTool, 256)
}
if stamp, ok := transcriptTime(event.Timestamp); ok && stamp > shell.UpdatedAt {
shell.UpdatedAt = stamp
}
keepCounter := func(target **int64, value *int64) {
if value != nil && *value >= 0 && (*target == nil || *value >= **target) {
copy := *value
*target = &copy
}
}
keepCounter(&shell.DurationMS, event.Usage.DurationMS)
keepCounter(&shell.ToolCount, event.Usage.Tools)
keepCounter(&shell.TokenCount, event.Usage.Tokens)
copy := *shell
s.mu.Unlock()
s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: &copy})
}
// The durable transcript records the timestamp of each initiating tool call.
// Enrich known tasks only; historical tool calls do not establish membership.
// The size/mtime key avoids repeatedly scanning an unchanged transcript when
// an older task has no recorded initiating message. Reads keep the existing
// transcript byte/line limits and never fail the primary task-list request.
func (s *session) enrichShellStarts() {
// A separate lock serializes optional metadata IO without holding the chat
// state lock. The clock below schedules retries only, never a task timestamp.
s.shellMetadataMu.Lock()
defer s.shellMetadataMu.Unlock()
s.mu.Lock()
wanted := map[string]bool{}
for id, snapshot := range s.shells {
if snapshot.shell.Status == protocol.ChatShellRunning && snapshot.shell.StartedAt == 0 {
wanted[id] = true
}
}
s.mu.Unlock()
if len(wanted) == 0 {
return
}
now := time.Now()
if now.Before(s.shellScanAfter) {
return
}
s.shellScanAfter = now.Add(5 * time.Second)
path := s.shellTranscriptPath
if path == "" {
if now.Before(s.shellLookupAfter) {
return
}
s.shellLookupAfter = now.Add(30 * time.Second)
path = findTranscriptFile(s.id)
if path == "" {
return
}
s.shellTranscriptPath = path
}
info, err := os.Stat(path)
if err != nil {
if !now.Before(s.shellLookupAfter) {
s.shellTranscriptPath = ""
}
return
}
covered := true
for id := range wanted {
if !s.shellTranscriptTargets[id] {
covered = false
break
}
}
if covered && s.shellTranscriptSize == info.Size() && s.shellTranscriptMtime == info.ModTime().UnixNano() {
return
}
// Cache failures too: an oversized/malformed unchanged file is not scanned
// again on every list refresh. A changed file gets another bounded attempt.
s.shellTranscriptSize, s.shellTranscriptMtime = info.Size(), info.ModTime().UnixNano()
s.shellTranscriptTargets = wanted
if info.Size() > maxTranscriptBytes {
return
}
records, err := readShellStartRecords(path, wanted)
if err != nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
for id, record := range records {
if snapshot := s.shells[id]; snapshot != nil {
applyToolMetadata(&snapshot.shell, record.name, record.input, record.timestamp)
}
}
}
type shellStartRecord struct {
name string
input json.RawMessage
timestamp string
}
// Retain only the targeted tool-call metadata, not an entire conversation.
func readShellStartRecords(path string, wanted map[string]bool) (map[string]shellStartRecord, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
bounded := &io.LimitedReader{R: file, N: maxTranscriptBytes + 1}
scanner := bufio.NewScanner(bounded)
scanner.Buffer(make([]byte, 0, 64<<10), maxLineBytes)
records := map[string]shellStartRecord{}
for scanner.Scan() {
var entry transcriptEntry
if json.Unmarshal(scanner.Bytes(), &entry) != nil || entry.Type != "assistant" || entry.IsSidechain {
continue
}
for _, block := range decodeBlocks(entry.Message.Content) {
if block.Type != "tool_use" || !wanted[block.ID] {
continue
}
if _, seen := records[block.ID]; seen {
continue
}
if stamp, ok := transcriptTime(entry.Timestamp); !ok || stamp <= 0 {
continue
}
records[block.ID] = shellStartRecord{name: block.Name, input: truncateJSON(block.Input, 64<<10), timestamp: entry.Timestamp}
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
if bounded.N <= 0 {
return nil, errors.New("Claude task transcript exceeded read limit")
}
return records, nil
}