import { GrokMessage, GrokToolCall } from "../grok/client.js"; import type { ChatCompletionContentPart } from "openai/resources/chat/completions.js"; import { ToolResult } from "../types/index.js"; import { EventEmitter } from "events"; export interface ChatEntry { type: "user" | "assistant" | "tool_result" | "tool_call" | "system"; content?: string | ChatCompletionContentPart[]; originalContent?: string | ChatCompletionContentPart[]; timestamp: Date; tool_calls?: GrokToolCall[]; toolCall?: GrokToolCall; toolResult?: { success: boolean; output?: string; error?: string; displayOutput?: string; }; isStreaming?: boolean; preserveFormatting?: boolean; metadata?: { rephrased_note?: string; [key: string]: any; }; } export interface StreamingChunk { type: "content" | "tool_calls" | "tool_result" | "done" | "token_count" | "user_message"; content?: string; tool_calls?: GrokToolCall[]; toolCall?: GrokToolCall; toolResult?: ToolResult; tokenCount?: number; userEntry?: ChatEntry; systemMessages?: ChatEntry[]; } export declare class GrokAgent extends EventEmitter { private grokClient; private textEditor; private morphEditor; private zsh; private confirmationTool; private search; private env; private introspect; private clearCacheTool; private characterTool; private taskTool; private internetTool; private imageTool; private fileConversionTool; private restartTool; private chatHistory; private messages; private tokenCounter; private abortController; private mcpInitialized; private maxToolRounds; private temperature; private maxTokens; private firstMessageProcessed; private contextWarningAt80; private contextWarningAt90; private persona; private personaColor; private mood; private moodColor; private activeTask; private activeTaskAction; private activeTaskColor; private apiKeyEnvVar; private pendingContextEditSession; private rephraseState; private hookPrefillText; constructor(apiKey: string, baseURL?: string, model?: string, maxToolRounds?: number, debugLogFile?: string, startupHookOutput?: string, temperature?: number, maxTokens?: number); private startupHookOutput?; private systemPrompt; private hasRunInstanceHook; /** * Initialize the agent with dynamic system prompt * Must be called after construction */ initialize(): Promise; /** * Build/rebuild the system message with current tool availability * Updates this.systemPrompt which is always used for messages[0] */ buildSystemMessage(): Promise; loadInitialHistory(history: ChatEntry[], systemPrompt?: string): Promise; private initializeMCP; private isGrokModel; private shouldUseSearchFor; processUserMessage(message: string): Promise; /** * Parse XML-formatted tool calls from message content (x.ai format) * Converts elements to standard GrokToolCall format */ private parseXMLToolCalls; private messageReducer; processUserMessageStream(message: string): AsyncGenerator; /** * Apply default parameter values for tools * This ensures the approval hook sees the same parameters that will be used during execution */ private applyToolParameterDefaults; /** * Validate tool arguments against the tool's schema * Returns null if valid, or an error message if invalid */ private validateToolArguments; private executeTool; private executeMCPTool; getChatHistory(): ChatEntry[]; setChatHistory(history: ChatEntry[]): void; getSystemPrompt(): string; setSystemPrompt(prompt: string): void; getMessages(): any[]; getCurrentTokenCount(): number; getMaxContextSize(): number; getContextUsagePercent(): number; /** * Convert context messages to markdown format for viewing * Format: (N) Name (role) - timestamp */ convertContextToMarkdown(): Promise; getPersona(): string; getPersonaColor(): string; getMood(): string; getMoodColor(): string; getActiveTask(): string; getActiveTaskAction(): string; getActiveTaskColor(): string; setPendingContextEditSession(tmpJsonPath: string, contextFilePath: string): void; getPendingContextEditSession(): { tmpJsonPath: string; contextFilePath: string; } | null; clearPendingContextEditSession(): void; setRephraseState(originalAssistantMessageIndex: number, rephraseRequestIndex: number, newResponseIndex: number, messageType: "user" | "system", prefillText?: string): void; getRephraseState(): { originalAssistantMessageIndex: number; rephraseRequestIndex: number; newResponseIndex: number; messageType: "user" | "system"; prefillText?: string; } | null; clearRephraseState(): void; setPersona(persona: string, color?: string): Promise<{ success: boolean; error?: string; }>; setMood(mood: string, color?: string): Promise<{ success: boolean; error?: string; }>; startActiveTask(activeTask: string, action: string, color?: string): Promise<{ success: boolean; error?: string; }>; transitionActiveTaskStatus(action: string, color?: string): Promise<{ success: boolean; error?: string; }>; stopActiveTask(reason: string, documentationFile: string, color?: string): Promise<{ success: boolean; error?: string; }>; private emitContextChange; private addContextWarningIfNeeded; executeCommand(command: string, skipConfirmation?: boolean): Promise; getCurrentModel(): string; setModel(model: string): void; /** * Strip in-progress tool calls from messages for backend/model testing * Removes tool_calls from the last assistant message and any corresponding tool results * @returns Cleaned copy of messages array, or original if no stripping needed */ static stripInProgressToolCalls(messages: GrokMessage[]): GrokMessage[]; /** * Test a model change by making a test API call with current conversation context * Rolls back to previous model if test fails * @param newModel Model to test * @returns Promise with success status and optional error message */ testModel(newModel: string): Promise<{ success: boolean; error?: string; }>; /** * Test backend/baseUrl/model changes by making a test API call with current conversation context * Rolls back all changes if test fails * @param backend Backend display name * @param baseUrl Base URL for API calls * @param apiKeyEnvVar Name of environment variable containing API key * @param model Model to use (optional, uses current model if not specified) * @returns Promise with success status and optional error message */ testBackendModelChange(backend: string, baseUrl: string, apiKeyEnvVar: string, model?: string): Promise<{ success: boolean; error?: string; }>; /** * Process hook result including commands and transformations * Handles ENV transformations, model/backend testing, and error messaging * @param hookResult Hook execution result * @param envKey Optional ENV key to check for transformation (e.g., ZDS_AI_AGENT_PERSONA) * @returns Object with success status and transformed value (if any) */ private processHookResult; /** * Process hook commands (MODEL, BACKEND, BASE_URL, SYSTEM, ENV) * Handles model/backend testing and error messaging * @param commands Hook commands from applyHookCommands() */ private processHookCommands; getBackend(): string; abortCurrentOperation(): void; clearCache(): Promise; /** * Get current session state for persistence */ getSessionState(): { session: string; persona: string; personaColor: string; mood: string; moodColor: string; activeTask: string; activeTaskAction: string; activeTaskColor: string; cwd: string; contextCurrent: number; contextMax: number; backend: string; baseUrl: string; apiKeyEnvVar: string; model: string; supportsVision: boolean; }; /** * Restore session state from persistence */ restoreSessionState(state: { session?: string; persona: string; personaColor: string; mood: string; moodColor: string; activeTask: string; activeTaskAction: string; activeTaskColor: string; cwd: string; contextCurrent?: number; contextMax?: number; backend?: string; baseUrl?: string; apiKeyEnvVar?: string; model?: string; supportsVision?: boolean; }): Promise; /** * Compact conversation context by keeping system prompt and last N messages * Reduces context size when it grows too large for backend to handle * @returns Number of messages removed */ compactContext(keepLastMessages?: number): number; /** * Get all tool instances and their class names for display purposes */ getToolClassInfo(): Array<{ className: string; methods: string[]; }>; /** * Get all tool instances via reflection */ private getToolInstances; }