| 1 | import { ToolCallDelta } from "core"; |
| 2 | import { createRuleBlock } from "core/tools/definitions/createRuleBlock"; |
| 3 | import { CreateRuleBlockArgs } from "core/tools/implementations/createRuleBlock"; |
| 4 | import { useCallback, useContext, useState } from "react"; |
| 5 | import { IdeMessengerContext } from "../../context/IdeMessenger"; |
| 6 | import { useAppSelector } from "../../redux/hooks"; |
| 7 | import { selectSelectedChatModel } from "../../redux/slices/configSlice"; |
| 8 | import { constructMessages } from "../../redux/util/constructMessages"; |
| 9 | import { addToolCallDeltaToState } from "../../util/toolCallState"; |
| 10 | |
| 11 | const RULE_GENERATION_SYSTEM_MESSAGE = `You are an expert at creating effective rules for AI coding assistants. Create concise, actionable rules that follow these guidelines: |
| 12 | |
| 13 | FOCUS: |
| 14 | - Keep rules focused on a single, specific concern |
| 15 | - Be specific and actionable - avoid vague guidance |
| 16 | - Write in imperative language ("Use X", "Always do Y", "Avoid Z") |
| 17 | |
| 18 | EXAMPLES FROM CHAT HISTORY: |
| 19 | - Use concrete examples from the chat history when possible |
| 20 | - If they say "don't do X", find instances where "X" was done incorrectly |
| 21 | - Include before/after code examples using this format: |
| 22 | |
| 23 | **Example** |
| 24 | \`\`\`typescript |
| 25 | // Bad: Don't do this |
| 26 | const badExample = "from chat history"; |
| 27 | |
| 28 | // Good: Do this instead |
| 29 | const goodExample = "corrected version"; |
| 30 | \`\`\` |
| 31 | |
| 32 | Be concise but comprehensive. The chat history contains real examples of what to do or avoid.`; |
| 33 | |
| 34 | export interface UseRuleGenerationReturn { |
| 35 | generateRule: () => Promise<void>; |
| 36 | isGenerating: boolean; |
| 37 | error: string | null; |
| 38 | reset: () => void; |
| 39 | } |
| 40 | |
| 41 | export function useRuleGeneration( |
| 42 | inputPrompt: string, |
| 43 | onGenerate?: (args: CreateRuleBlockArgs) => void, |
| 44 | ): UseRuleGenerationReturn { |
| 45 | const [isGenerating, setIsGenerating] = useState(false); |
| 46 | const [error, setError] = useState<string | null>(null); |
| 47 | |
| 48 | const ideMessenger = useContext(IdeMessengerContext); |
| 49 | const currentHistory = useAppSelector((state) => state.session.history); |
| 50 | const selectedChatModel = useAppSelector(selectSelectedChatModel); |
| 51 | |
| 52 | const generateRule = useCallback(async () => { |
| 53 | if (!selectedChatModel) { |
| 54 | setError("No chat model selected"); |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | setIsGenerating(true); |
| 59 | setError(null); |
| 60 | |
| 61 | try { |
| 62 | // Convert current history to ChatHistoryItem format |
| 63 | |
| 64 | // Add our rule generation prompt with instruction to use the tool |
| 65 | const history = [ |
| 66 | { |
| 67 | message: { |
| 68 | role: "system" as const, |
| 69 | content: RULE_GENERATION_SYSTEM_MESSAGE, |
| 70 | }, |
| 71 | contextItems: [], |
| 72 | }, |
| 73 | ...currentHistory, |
| 74 | { |
| 75 | message: { |
| 76 | role: "user" as const, |
| 77 | content: `The user has requested that we write a new rule. You MUST USE the create_rule_block tool to generate a well-structured rule. Do not say anything else, only call this tool. Here is their request: ${inputPrompt}`, |
| 78 | }, |
| 79 | contextItems: [], |
| 80 | }, |
| 81 | ]; |
| 82 | |
| 83 | const { messages } = constructMessages(history, undefined, [], {}); |
| 84 | |
| 85 | // Create abort controller for this request |
| 86 | const abortController = new AbortController(); |
| 87 | |
| 88 | // Stream the response with createRuleBlock tool |
| 89 | const gen = ideMessenger.llmStreamChat( |
| 90 | { |
| 91 | messages, |
| 92 | completionOptions: { |
| 93 | tools: [createRuleBlock], |
| 94 | }, |
| 95 | title: selectedChatModel.title, |
| 96 | }, |
| 97 | abortController.signal, |
| 98 | ); |
| 99 | |
| 100 | let toolCallState: any = undefined; |
| 101 | |
| 102 | // Process each chunk |
| 103 | for await (const chunks of gen) { |
| 104 | for (const chunk of chunks) { |
| 105 | // Handle tool calls - this is what we care about |
| 106 | if (chunk.role === "assistant" && chunk.toolCalls?.length) { |
| 107 | const toolCallDelta: ToolCallDelta = chunk.toolCalls[0]; |
| 108 | toolCallState = addToolCallDeltaToState( |
| 109 | toolCallDelta, |
| 110 | toolCallState, |
| 111 | ); |
| 112 | |
| 113 | // Call the callback if provided with the parsed args |
| 114 | if (toolCallState?.parsedArgs) { |
| 115 | onGenerate?.(toolCallState.parsedArgs); |
| 116 | } |
| 117 | } |
| 118 | // Ignore regular assistant content - we only care about the tool call |
| 119 | } |
| 120 | } |
| 121 | } catch (err) { |
| 122 | setError(err instanceof Error ? err.message : "An error occurred"); |
| 123 | } finally { |
| 124 | setIsGenerating(false); |
| 125 | } |
| 126 | }, [ideMessenger, currentHistory, selectedChatModel, inputPrompt]); |
| 127 | |
| 128 | const reset = useCallback(() => { |
| 129 | setError(null); |
| 130 | setIsGenerating(false); |
| 131 | }, []); |
| 132 | |
| 133 | return { |
| 134 | generateRule, |
| 135 | isGenerating, |
| 136 | error, |
| 137 | reset, |
| 138 | }; |
| 139 | } |