summaryrefslogtreecommitdiff
path: root/packages/cli/src/core/historyUpdater.ts
blob: 39eaca6a7b8447c6647afb8616675d2fb5cdf36f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import { Part } from "@google/genai";
import { toolRegistry } from "../tools/tool-registry.js";
import { HistoryItem, IndividualToolCallDisplay, ToolCallEvent, ToolCallStatus, ToolConfirmationOutcome, ToolEditConfirmationDetails, ToolExecuteConfirmationDetails } from "../ui/types.js";
import { ToolResultDisplay } from "../tools/ToolResult.js";

/**
 * Processes a tool call chunk and updates the history state accordingly.
 * Manages adding new tool groups or updating existing ones.
 * Resides here as its primary effect is updating history based on tool events.
 */
export const handleToolCallChunk = (
    chunk: ToolCallEvent,
    setHistory: React.Dispatch<React.SetStateAction<HistoryItem[]>>,
    submitQuery: (query: Part) => Promise<void>,
    getNextMessageId: () => number,
    currentToolGroupIdRef: React.MutableRefObject<number | null>
): void => {
    const toolDefinition = toolRegistry.getTool(chunk.name);
    const description = toolDefinition?.getDescription
        ? toolDefinition.getDescription(chunk.args)
        : '';
    const toolDisplayName = toolDefinition?.displayName ?? chunk.name;
    let confirmationDetails = chunk.confirmationDetails;
    if (confirmationDetails) {
        const originalConfirmationDetails = confirmationDetails;
        const historyUpdatingConfirm = async (outcome: ToolConfirmationOutcome) => {
            originalConfirmationDetails.onConfirm(outcome);

            if (outcome === ToolConfirmationOutcome.Cancel) {
                let resultDisplay: ToolResultDisplay | undefined;
                if ('fileDiff' in originalConfirmationDetails) {
                    resultDisplay = { fileDiff: (originalConfirmationDetails as ToolEditConfirmationDetails).fileDiff };
                } else {
                    resultDisplay = `~~${(originalConfirmationDetails as ToolExecuteConfirmationDetails).command}~~`;
                }
                handleToolCallChunk({ ...chunk, status: ToolCallStatus.Canceled, confirmationDetails: undefined, resultDisplay, }, setHistory, submitQuery, getNextMessageId, currentToolGroupIdRef);
                const functionResponse: Part = {
                    functionResponse: {
                        name: chunk.name,
                        response: { "error": "User rejected function call." },
                    },
                }
                await submitQuery(functionResponse);
            } else {
                const tool = toolRegistry.getTool(chunk.name)
                if (!tool) {
                    throw new Error(`Tool "${chunk.name}" not found or is not registered.`);
                }
                
                handleToolCallChunk({ ...chunk, status: ToolCallStatus.Invoked, resultDisplay: "Executing...", confirmationDetails: undefined }, setHistory, submitQuery, getNextMessageId, currentToolGroupIdRef);
                
                const result = await tool.execute(chunk.args);

                handleToolCallChunk({ ...chunk, status: ToolCallStatus.Invoked, resultDisplay: result.returnDisplay, confirmationDetails: undefined }, setHistory, submitQuery, getNextMessageId, currentToolGroupIdRef);

                const functionResponse: Part = {
                    functionResponse: {
                        name: chunk.name,
                        id: chunk.callId,
                        response: { "output": result.llmContent },
                    },
                }

                await submitQuery(functionResponse);
            }
        }

        confirmationDetails = {
            ...originalConfirmationDetails,
            onConfirm: historyUpdatingConfirm,
        };
    }
    const toolDetail: IndividualToolCallDisplay = {
        callId: chunk.callId,
        name: toolDisplayName,
        description,
        resultDisplay: chunk.resultDisplay,
        status: chunk.status,
        confirmationDetails: confirmationDetails,
    };

    const activeGroupId = currentToolGroupIdRef.current;
    setHistory(prev => {
        if (chunk.status === ToolCallStatus.Pending) {
            if (activeGroupId === null) {
                // Start a new tool group
                const newGroupId = getNextMessageId();
                currentToolGroupIdRef.current = newGroupId;
                return [
                    ...prev,
                    { id: newGroupId, type: 'tool_group', tools: [toolDetail] } as HistoryItem
                ];
            }

            // Add to existing tool group
            return prev.map(item =>
                item.id === activeGroupId && item.type === 'tool_group'
                    ? item.tools.some(t => t.callId === toolDetail.callId)
                        ? item // Tool already listed as pending
                        : { ...item, tools: [...item.tools, toolDetail] }
                    : item
            );
        }

        // Update the status of a pending tool within the active group
        if (activeGroupId === null) {
            // Log if an invoked tool arrives without an active group context
            console.warn("Received invoked tool status without an active tool group ID:", chunk);
            return prev;
        }

        return prev.map(item =>
            item.id === activeGroupId && item.type === 'tool_group'
                ? {
                    ...item,
                    tools: item.tools.map(t =>
                        t.callId === toolDetail.callId
                            ? { ...t, ...toolDetail, status: chunk.status } // Update details & status
                            : t
                    )
                }
                : item
        );
    });
};

/**
 * Appends an error or informational message to the history, attempting to attach
 * it to the last non-user message or creating a new entry.
 */
export const addErrorMessageToHistory = (
    error: any,
    setHistory: React.Dispatch<React.SetStateAction<HistoryItem[]>>,
    getNextMessageId: () => number
): void => {
    const isAbort = error.name === 'AbortError';
    const errorType = isAbort ? 'info' : 'error';
    const errorText = isAbort
        ? '[Request cancelled by user]'
        : `[Error: ${error.message || 'Unknown error'}]`;

    setHistory(prev => {
        const reversedHistory = [...prev].reverse();
        // Find the last message that isn't from the user to append the error/info to
        const lastBotMessageIndex = reversedHistory.findIndex(item => item.type !== 'user');
        const originalIndex = lastBotMessageIndex !== -1 ? prev.length - 1 - lastBotMessageIndex : -1;

        if (originalIndex !== -1) {
            // Append error to the last relevant message
            return prev.map((item, index) => {
                if (index === originalIndex) {
                    let baseText = '';
                    // Determine base text based on item type
                    if (item.type === 'gemini') baseText = item.text ?? '';
                    else if (item.type === 'tool_group') baseText = `Tool execution (${item.tools.length} calls)`;
                    else if (item.type === 'error' || item.type === 'info') baseText = item.text ?? '';
                    // Safely handle potential undefined text

                    const updatedText = (baseText + (baseText && !baseText.endsWith('\n') ? '\n' : '') + errorText).trim();
                    // Reuse existing ID, update type and text
                    return { ...item, type: errorType, text: updatedText };
                }
                return item;
            });
        } else {
            // No previous message to append to, add a new error item
            return [
                ...prev,
                { id: getNextMessageId(), type: errorType, text: errorText } as HistoryItem
            ];
        }
    });
};