package claude import ( "bufio" "bytes" "encoding/json" "io" "os" "path/filepath" "strings" "git.a-wan.net/alan/pipelines/internal/claudehost" "git.a-wan.net/alan/pipelines/internal/protocol" ) // reconcileHostTasks runs only after replay reaches the status snapshot's End. // It restores native identities even when their starting records were trimmed // from the bounded spool. Old hosts omit Tasks, which means unknown, not idle. func (s *session) reconcileHostTasks(tasks *[]claudehost.Task) { if tasks == nil { return } finished := s.finishedHostTasks(*tasks) s.mu.Lock() present := make(map[string]bool, len(*tasks)) var frames []protocol.ChatShell for _, task := range *tasks { if finished[task.ToolUseID] { continue } id := task.ToolUseID if id == "" && task.TaskID != "" { id = "task:" + task.TaskID } if id == "" { continue } present[id] = true command := boundedText(task.Command, 64<<10) if command == "" && (task.Name == "Agent" || task.Name == "Task") && task.Description != "" { command = "Agent: " + boundedText(task.Description, 2048) } s.recordShellLocked(id, command) snapshot := s.shells[id] snapshot.background = true snapshot.taskID = task.TaskID snapshot.shell.Status = protocol.ChatShellRunning snapshot.shell.Exit = nil if task.Description != "" { snapshot.shell.Description = boundedText(task.Description, 2048) } if task.TaskType != "" { snapshot.shell.TaskType = boundedText(task.TaskType, 128) } else if snapshot.shell.TaskType == "" { switch task.Name { case "Bash": snapshot.shell.TaskType = "shell" case "Agent", "Task": snapshot.shell.TaskType = "agent" } } if snapshot.shell.StartedAt == 0 { if stamp, ok := transcriptTime(task.Timestamp); ok && stamp > 0 { snapshot.shell.StartedAt = stamp } } frames = append(frames, snapshot.shell) } for id, snapshot := range s.shells { if !snapshot.background || snapshot.shell.Status != protocol.ChatShellRunning || present[id] { continue } // The host says this background identity is no longer running, but // supplies neither an exit code nor a completion time. Keep both absent. snapshot.shell.Status = protocol.ChatShellExited frames = append(frames, snapshot.shell) } s.mu.Unlock() for i := range frames { s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: &frames[i]}) } } // resolveHostedTaskLine correlates a completion that carries only the native // task id with the tool identity restored from the authoritative snapshot. // This is translation inside the server; no altered event is sent to the CLI. func (s *session) resolveHostedTaskLine(line []byte) []byte { if !bytes.Contains(line, []byte(`"task_notification"`)) { return line } var event struct { Subtype string `json:"subtype"` TaskID string `json:"task_id"` ToolUseID string `json:"tool_use_id"` } if json.Unmarshal(line, &event) != nil || event.Subtype != "task_notification" || event.TaskID == "" || event.ToolUseID != "" { return line } s.mu.Lock() id := "" for toolID, snapshot := range s.shells { if snapshot.taskID == event.TaskID { id = toolID break } } s.mu.Unlock() if id == "" { return line } var fields map[string]json.RawMessage if json.Unmarshal(line, &fields) != nil { return line } fields["tool_use_id"], _ = json.Marshal(id) normalized, err := json.Marshal(fields) if err != nil { return line } return normalized } // finishedHostTasks checks host-reported tasks the CLI never identified (no // native task id) against the session's transcripts, the main one and every // subagent's. Hosts built before launch detection was strict count a // foreground Bash whose output merely quotes "running in background with ID" // (a subagent reading fake-claude.py, say) as a background task, and keep a // subagent's background command whose completion preceded its launch result; // neither ever ends. A tool call whose result is not a launch acknowledgement, // or whose completion notification is recorded, is finished. func (s *session) finishedHostTasks(tasks []claudehost.Task) map[string]bool { wanted := map[string]bool{} for _, task := range tasks { if task.TaskID == "" && task.ToolUseID != "" { wanted[task.ToolUseID] = true } } if len(wanted) == 0 { return nil } path := findTranscriptFile(s.id) if path == "" { return nil } files := []string{path} if agents, err := filepath.Glob(filepath.Join(strings.TrimSuffix(path, ".jsonl"), "subagents", "*.jsonl")); err == nil { files = append(files, agents...) } finished := map[string]bool{} for _, file := range files { scanFinishedToolCalls(file, wanted, finished) if len(finished) == len(wanted) { break } } return finished } // scanFinishedToolCalls reads the newest maxTranscriptBytes of one transcript // and marks each wanted tool call that finished there. Errors only end the scan. func scanFinishedToolCalls(path string, wanted, finished map[string]bool) { file, err := os.Open(path) if err != nil { return } defer file.Close() partial := false if info, err := file.Stat(); err == nil && info.Size() > maxTranscriptBytes { if _, err := file.Seek(info.Size()-maxTranscriptBytes, io.SeekStart); err != nil { return } partial = true } scanner := bufio.NewScanner(&io.LimitedReader{R: file, N: maxTranscriptBytes}) scanner.Buffer(make([]byte, 0, 64<<10), maxLineBytes) resultMarker := []byte(`"tool_result"`) noticeMarker := []byte("") for scanner.Scan() { line := scanner.Bytes() if partial { partial = false // the first line read from mid-file is a fragment continue } if bytes.Contains(line, resultMarker) { var entry transcriptEntry parsed := false for id := range wanted { if finished[id] || !bytes.Contains(line, []byte(id)) { continue } if !parsed { if json.Unmarshal(line, &entry) != nil { break } parsed = true } for _, block := range decodeBlocks(entry.Message.Content) { if block.Type != "tool_result" || block.ToolUseID != id { continue } if text, _ := toolResultContent(block.Content); !launchedInBackground(text) { finished[id] = true } } } continue } if bytes.Contains(line, noticeMarker) { for id := range wanted { if !finished[id] && bytes.Contains(line, []byte(""+id+"")) { finished[id] = true } } } } } // settleUnlistedTasks applies the CLI's background_tasks_changed event: the // complete set of background tasks still running, subagents' included. A // tracked task with a native id the CLI no longer lists has ended. func (s *session) settleUnlistedTasks(line []byte) { var event struct { Tasks []struct { TaskID string `json:"task_id"` } `json:"tasks"` } if json.Unmarshal(line, &event) != nil { return } listed := make(map[string]bool, len(event.Tasks)) for _, task := range event.Tasks { listed[task.TaskID] = true } var frames []protocol.ChatShell s.mu.Lock() for _, snapshot := range s.shells { if snapshot.taskID == "" || listed[snapshot.taskID] || snapshot.shell.Status != protocol.ChatShellRunning { continue } snapshot.shell.Status = protocol.ChatShellExited frames = append(frames, snapshot.shell) } s.mu.Unlock() for i := range frames { s.emit(protocol.ChatEventFrame{SessionID: s.id, Kind: protocol.ChatEventShell, Shell: &frames[i]}) } }