package server import ( "context" "encoding/json" "reflect" "slices" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // awaitToolCallSession attributes a call on a shared harness endpoint (one // OpenCode service serves every chat, and its MCP requests carry no session) // to the chat whose retained stream shows a running tool part with one of // names and exactly these arguments. The harness reports the part as running // before or while it calls the tool, so this waits up to wait for it. It // returns "" when no chat matches, and ambiguous when several distinct chats // do: a call is never guessed into a chat. func (h *chatHub) awaitToolCallSession(ctx context.Context, names []string, arguments json.RawMessage, wait time.Duration) (string, bool) { var want any if json.Unmarshal(arguments, &want) != nil { return "", false } deadline := time.Now().Add(wait) for { sessions := h.runningToolCallSessions(names, want) switch { case len(sessions) == 1: return sessions[0], false case len(sessions) > 1: return "", true } if time.Now().After(deadline) { return "", false } select { case <-ctx.Done(): return "", false case <-time.After(50 * time.Millisecond): } } } func (h *chatHub) runningToolCallSessions(names []string, want any) []string { h.mu.Lock() defer h.mu.Unlock() var sessions []string for sessionID, turn := range h.turns { if turnHasToolCall(turn, names, want) { sessions = append(sessions, sessionID) } } slices.Sort(sessions) return sessions } func turnHasToolCall(turn *chatTurn, names []string, want any) bool { for _, message := range turn.messages { for _, part := range message.parts { p := part.part if p.Type != "tool" || p.State == nil || !slices.Contains(names, p.Name) { continue } if p.State.Status != protocol.ChatToolRunning && p.State.Status != "pending" { continue } var got any if json.Unmarshal(p.State.Input, &got) == nil && reflect.DeepEqual(got, want) { return true } } } return false }