| 1 | import { ContextItem, ToolCall } 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 | |
| 7 | export interface ClientToolExtras { |
| 8 | getState: () => RootState; |
| 9 | dispatch: AppThunkDispatch; |
| 10 | ideMessenger: IIdeMessenger; |
| 11 | streamId?: string; |
| 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 | toolCall: ToolCall, |
| 31 | extras: ClientToolExtras, |
| 32 | ): Promise<ClientToolResult> { |
| 33 | const args = JSON.parse(toolCall.function.arguments || "{}"); |
| 34 | try { |
| 35 | let output: ClientToolOutput; |
| 36 | switch (toolCall.function.name) { |
| 37 | case BuiltInToolNames.EditExistingFile: |
| 38 | output = await editToolImpl(args, toolCall.id, extras); |
| 39 | break; |
| 40 | default: |
| 41 | throw new Error(`Invalid client tool name ${toolCall.function.name}`); |
| 42 | } |
| 43 | return { |
| 44 | ...output, |
| 45 | errorMessage: undefined, |
| 46 | }; |
| 47 | } catch (e) { |
| 48 | let errorMessage = `${e}`; |
| 49 | if (e instanceof Error) { |
| 50 | errorMessage = e.message; |
| 51 | } |
| 52 | return { |
| 53 | respondImmediately: true, |
| 54 | errorMessage, |
| 55 | output: undefined, |
| 56 | }; |
| 57 | } |
| 58 | } |