| 1 | import { ContextItem, ToolCallState } from "core"; |
| 2 | import { BuiltInToolNames } from "core/tools/builtIn"; |
| 3 | import { IIdeMessenger } from "../../context/IdeMessenger"; |
| 4 | import { AppThunkDispatch, RootState } from "../../redux/store"; |
| 5 | import { editToolImpl } from "./editImpl"; |
| 6 | import { searchReplaceToolImpl } from "./searchReplaceImpl"; |
| 7 | |
| 8 | export interface ClientToolExtras { |
| 9 | getState: () => RootState; |
| 10 | dispatch: AppThunkDispatch; |
| 11 | ideMessenger: IIdeMessenger; |
| 12 | } |
| 13 | |
| 14 | export interface ClientToolOutput { |
| 15 | output: ContextItem[] | undefined; |
| 16 | respondImmediately: boolean; |
| 17 | } |
| 18 | |
| 19 | export interface ClientToolResult extends ClientToolOutput { |
| 20 | errorMessage: string | undefined; |
| 21 | } |
| 22 | |
| 23 | export type ClientToolImpl = ( |
| 24 | args: any, |
| 25 | toolCallId: string, |
| 26 | extras: ClientToolExtras, |
| 27 | ) => Promise<ClientToolOutput>; |
| 28 | |
| 29 | export async function callClientTool( |
| 30 | toolCallState: ToolCallState, |
| 31 | extras: ClientToolExtras, |
| 32 | ): Promise<ClientToolResult> { |
| 33 | const { toolCall, parsedArgs } = toolCallState; |
| 34 | try { |
| 35 | let output: ClientToolOutput; |
| 36 | switch (toolCall.function.name) { |
| 37 | case BuiltInToolNames.EditExistingFile: |
| 38 | output = await editToolImpl(parsedArgs, toolCall.id, extras); |
| 39 | break; |
| 40 | case BuiltInToolNames.SearchAndReplaceInFile: |
| 41 | output = await searchReplaceToolImpl(parsedArgs, toolCall.id, extras); |
| 42 | break; |
| 43 | default: |
| 44 | throw new Error(`Invalid client tool name ${toolCall.function.name}`); |
| 45 | } |
| 46 | return { |
| 47 | ...output, |
| 48 | errorMessage: undefined, |
| 49 | }; |
| 50 | } catch (e) { |
| 51 | let errorMessage = `${e}`; |
| 52 | if (e instanceof Error) { |
| 53 | errorMessage = e.message; |
| 54 | } |
| 55 | return { |
| 56 | respondImmediately: true, |
| 57 | errorMessage, |
| 58 | output: undefined, |
| 59 | }; |
| 60 | } |
| 61 | } |