|
| 1 | +/** |
| 2 | + * Hook for core SDK message execution. |
| 3 | + * Handles agent resolution, client acquisition, and SDK run execution. |
| 4 | + */ |
| 5 | + |
| 6 | +import { useCallback } from 'react' |
| 7 | + |
| 8 | +import { |
| 9 | + resolveAgent, |
| 10 | + buildPromptWithContext, |
| 11 | +} from '../utils/agent-resolution' |
| 12 | +import { getCodebuffClient } from '../utils/codebuff-client' |
| 13 | +import { createEventHandlerState } from '../utils/create-event-handler-state' |
| 14 | +import { createRunConfig } from '../utils/create-run-config' |
| 15 | +import { loadAgentDefinitions } from '../utils/local-agent-registry' |
| 16 | +import { logger } from '../utils/logger' |
| 17 | + |
| 18 | +import type { StreamController } from './stream-state' |
| 19 | +import type { StreamStatus } from './use-message-queue' |
| 20 | +import type { AgentMode } from '../utils/constants' |
| 21 | +import type { MessageUpdater } from '../utils/message-updater' |
| 22 | +import type { MessageContent, RunState } from '@codebuff/sdk' |
| 23 | +import type { MutableRefObject } from 'react' |
| 24 | + |
| 25 | +// ----------------------------------------------------------------------------- |
| 26 | +// Types |
| 27 | +// ----------------------------------------------------------------------------- |
| 28 | + |
| 29 | +/** Core message data to be sent */ |
| 30 | +export interface MessageData { |
| 31 | + /** The final prompt content to send */ |
| 32 | + prompt: string |
| 33 | + /** Optional bash context to prepend to the prompt */ |
| 34 | + bashContext: string |
| 35 | + /** Message content (images, etc.) */ |
| 36 | + messageContent: MessageContent[] | undefined |
| 37 | + /** Current agent mode (DEFAULT, MAX, PLAN) */ |
| 38 | + agentMode: AgentMode |
| 39 | +} |
| 40 | + |
| 41 | +/** Context for managing streaming state and UI updates */ |
| 42 | +export interface StreamingContext { |
| 43 | + /** AI message ID for the response */ |
| 44 | + aiMessageId: string |
| 45 | + /** Stream controller for managing stream state */ |
| 46 | + streamRefs: StreamController |
| 47 | + /** Message updater for updating AI message blocks */ |
| 48 | + updater: MessageUpdater |
| 49 | + /** Ref tracking whether content has been received */ |
| 50 | + hasReceivedContentRef: MutableRefObject<boolean> |
| 51 | +} |
| 52 | + |
| 53 | +/** Context for SDK execution */ |
| 54 | +export interface ExecutionContext { |
| 55 | + /** Previous run state for continuation */ |
| 56 | + previousRunState: RunState | null |
| 57 | + /** Abort signal for cancellation */ |
| 58 | + signal: AbortSignal |
| 59 | +} |
| 60 | + |
| 61 | +export interface StreamingCallbacks { |
| 62 | + setStreamingAgents: (updater: (prev: Set<string>) => Set<string>) => void |
| 63 | + setStreamStatus: (status: StreamStatus) => void |
| 64 | + setHasReceivedPlanResponse: (value: boolean) => void |
| 65 | + setIsRetrying: (value: boolean) => void |
| 66 | +} |
| 67 | + |
| 68 | +export interface SubagentCallbacks { |
| 69 | + addActiveSubagent: (id: string) => void |
| 70 | + removeActiveSubagent: (id: string) => void |
| 71 | +} |
| 72 | + |
| 73 | +export interface ExecuteMessageParams { |
| 74 | + /** Core message data */ |
| 75 | + message: MessageData |
| 76 | + /** Streaming state and UI update context */ |
| 77 | + streaming: StreamingContext |
| 78 | + /** SDK execution context */ |
| 79 | + execution: ExecutionContext |
| 80 | + /** Callbacks for streaming state updates */ |
| 81 | + streamingCallbacks: StreamingCallbacks |
| 82 | + /** Callbacks for subagent tracking */ |
| 83 | + subagentCallbacks: SubagentCallbacks |
| 84 | + /** Callback for tracking total cost */ |
| 85 | + onTotalCost?: (cost: number) => void |
| 86 | +} |
| 87 | + |
| 88 | +export interface ExecuteMessageResult { |
| 89 | + success: true |
| 90 | + runState: RunState |
| 91 | +} |
| 92 | + |
| 93 | +export interface ExecuteMessageError { |
| 94 | + success: false |
| 95 | + error: 'no_client' | 'execution_error' |
| 96 | + message?: string |
| 97 | +} |
| 98 | + |
| 99 | +export type ExecuteMessageOutcome = ExecuteMessageResult | ExecuteMessageError |
| 100 | + |
| 101 | +export interface UseMessageExecutionOptions { |
| 102 | + /** Explicit agent ID to use (overrides mode-based selection) */ |
| 103 | + agentId?: string |
| 104 | +} |
| 105 | + |
| 106 | +export interface UseMessageExecutionReturn { |
| 107 | + /** Execute a message and return the run state or error */ |
| 108 | + executeMessage: (params: ExecuteMessageParams) => Promise<ExecuteMessageOutcome> |
| 109 | +} |
| 110 | + |
| 111 | +/** |
| 112 | + * Hook for executing messages via the SDK. |
| 113 | + * Encapsulates agent resolution, client acquisition, and run execution. |
| 114 | + */ |
| 115 | +export function useMessageExecution({ |
| 116 | + agentId, |
| 117 | +}: UseMessageExecutionOptions): UseMessageExecutionReturn { |
| 118 | + const executeMessage = useCallback( |
| 119 | + async (params: ExecuteMessageParams): Promise<ExecuteMessageOutcome> => { |
| 120 | + const { |
| 121 | + message, |
| 122 | + streaming, |
| 123 | + execution, |
| 124 | + streamingCallbacks, |
| 125 | + subagentCallbacks, |
| 126 | + onTotalCost, |
| 127 | + } = params |
| 128 | + |
| 129 | + // Destructure from grouped objects |
| 130 | + const { prompt, bashContext, messageContent, agentMode } = message |
| 131 | + const { aiMessageId, streamRefs, updater, hasReceivedContentRef } = streaming |
| 132 | + const { previousRunState, signal } = execution |
| 133 | + |
| 134 | + // Get SDK client |
| 135 | + const client = await getCodebuffClient() |
| 136 | + |
| 137 | + if (!client) { |
| 138 | + logger.error( |
| 139 | + {}, |
| 140 | + '[message-execution] No Codebuff client available. Please ensure you are authenticated.', |
| 141 | + ) |
| 142 | + return { |
| 143 | + success: false, |
| 144 | + error: 'no_client', |
| 145 | + message: |
| 146 | + 'Unable to connect to Codebuff. Please check your authentication and try again.', |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + // Resolve agent and build prompt |
| 151 | + const agentDefinitions = loadAgentDefinitions() |
| 152 | + const resolvedAgent = resolveAgent(agentMode, agentId, agentDefinitions) |
| 153 | + |
| 154 | + const promptWithBashContext = bashContext |
| 155 | + ? bashContext + prompt |
| 156 | + : prompt |
| 157 | + const effectivePrompt = buildPromptWithContext( |
| 158 | + promptWithBashContext, |
| 159 | + messageContent, |
| 160 | + ) |
| 161 | + |
| 162 | + // Create event handler state |
| 163 | + const eventHandlerState = createEventHandlerState({ |
| 164 | + streamRefs, |
| 165 | + setStreamingAgents: streamingCallbacks.setStreamingAgents, |
| 166 | + setStreamStatus: streamingCallbacks.setStreamStatus, |
| 167 | + aiMessageId, |
| 168 | + updater, |
| 169 | + hasReceivedContentRef, |
| 170 | + addActiveSubagent: subagentCallbacks.addActiveSubagent, |
| 171 | + removeActiveSubagent: subagentCallbacks.removeActiveSubagent, |
| 172 | + agentMode, |
| 173 | + setHasReceivedPlanResponse: |
| 174 | + streamingCallbacks.setHasReceivedPlanResponse, |
| 175 | + logger, |
| 176 | + setIsRetrying: streamingCallbacks.setIsRetrying, |
| 177 | + onTotalCost, |
| 178 | + }) |
| 179 | + |
| 180 | + // Create run config |
| 181 | + const runConfig = createRunConfig({ |
| 182 | + logger, |
| 183 | + agent: resolvedAgent, |
| 184 | + prompt: effectivePrompt, |
| 185 | + content: messageContent, |
| 186 | + previousRunState, |
| 187 | + agentDefinitions, |
| 188 | + eventHandlerState, |
| 189 | + signal, |
| 190 | + }) |
| 191 | + |
| 192 | + logger.info({ runConfig }, '[message-execution] Executing SDK run') |
| 193 | + |
| 194 | + // Execute the run with error handling |
| 195 | + try { |
| 196 | + const runState = await client.run(runConfig) |
| 197 | + |
| 198 | + return { |
| 199 | + success: true, |
| 200 | + runState, |
| 201 | + } |
| 202 | + } catch (error) { |
| 203 | + const errorMessage = |
| 204 | + error instanceof Error ? error.message : 'Unknown execution error' |
| 205 | + logger.error( |
| 206 | + { error }, |
| 207 | + '[message-execution] SDK run execution failed', |
| 208 | + ) |
| 209 | + return { |
| 210 | + success: false, |
| 211 | + error: 'execution_error', |
| 212 | + message: errorMessage, |
| 213 | + } |
| 214 | + } |
| 215 | + }, |
| 216 | + [agentId], |
| 217 | + ) |
| 218 | + |
| 219 | + return { |
| 220 | + executeMessage, |
| 221 | + } |
| 222 | +} |
0 commit comments