### Install and Run CortexOne Source: https://github.com/itachi-1824/cortexone/blob/main/README.md Clone the repository, install dependencies, and start the development server. ```bash git clone https://github.com/Itachi-1824/CortexOne.git cd CortexOne npm install npm run dev ``` -------------------------------- ### Configure MCP Servers Source: https://github.com/itachi-1824/cortexone/blob/main/README.md Configure MCP servers for extended capabilities. This example shows filesystem and sequential-thinking servers. ```json { "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/directory"], "alwaysAllowTools": ["*"] }, "sequential-thinking": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"] } } } ``` -------------------------------- ### MCP Server Management (DesktopApi) Source: https://context7.com/itachi-1824/cortexone/llms.txt Provides methods to manage MCP (Model Context Protocol) server processes, including starting, stopping, checking status, and sending requests. ```APIDOC ## MCP Server Management (DesktopApi) ### `window.desktopApi.startMcpServer` Spawns an external MCP server process via stdio, managed in the Electron main process. Servers communicate using JSON-RPC 2.0 over stdin/stdout. #### Parameters - **serverName** (string) - Required - The name of the MCP server to start (e.g., 'filesystem'). - **options** (object) - Required - Configuration options for the server process: - **command** (string) - Required - The command to execute (e.g., 'npx'). - **args** (string[]) - Required - Arguments for the command. - **env** (object) - Optional - Environment variables for the server process. - **workingDirectory** (string) - Optional - The working directory for the server process. #### Returns - **Promise** - Resolves to `true` if the server started successfully, `false` otherwise. ### `window.desktopApi.stopMcpServer` Stops a running MCP server process. #### Parameters - **serverName** (string) - Required - The name of the MCP server to stop. #### Returns - **Promise** - Resolves to `true` if the server stopped successfully, `false` otherwise. ### `window.desktopApi.getMcpServerStatus` Retrieves the current status of an MCP server. #### Parameters - **serverName** (string) - Required - The name of the MCP server to check. #### Returns - **Promise<'running' | 'stopped' | 'error'>** - The status of the server. ### `window.desktopApi.sendMcpRequest` Sends a JSON-RPC 2.0 request to a running MCP server. #### Parameters - **serverName** (string) - Required - The name of the MCP server to send the request to. - **request** (object) - Required - The JSON-RPC request object: - **method** (string) - Required - The method to call on the server. - **params** (object) - Optional - Parameters for the method call. #### Returns - **Promise** - The JSON-RPC response from the server. ### Request Example ```typescript // Start a filesystem MCP server const started = await window.desktopApi.startMcpServer('filesystem', { command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/home/user/docs'], env: { NODE_ENV: 'production' }, workingDirectory: '/home/user' }); console.log('Started:', started); // true // Check status const status = await window.desktopApi.getMcpServerStatus('filesystem'); console.log('Status:', status); // 'running' | 'stopped' | 'error' // Send a JSON-RPC request to the running server to list tools const tools = await window.desktopApi.sendMcpRequest('filesystem', { method: 'tools/list', params: {} }); // { tools: [{ name: 'read_file', description: '...', inputSchema: {...} }, ...] } // Invoke a tool const result = await window.desktopApi.sendMcpRequest('filesystem', { method: 'tools/call', params: { name: 'read_file', arguments: { path: '/home/user/docs/readme.txt' } } }); // { content: [{ type: 'text', text: 'File contents here...' }] } // Stop the server const stopped = await window.desktopApi.stopMcpServer('filesystem'); console.log('Stopped:', stopped); // true ``` ``` -------------------------------- ### CortexOne Development Scripts Source: https://github.com/itachi-1824/cortexone/blob/main/README.md Common npm scripts for developing and building the CortexOne application. Use 'npm run dev' to start the development environment. ```bash npm run dev # Start development environment npm run build # Build for production npm run preview # Preview production build npm run lint # Run ESLint npm run type-check # TypeScript type checking ``` -------------------------------- ### Get System Message (TypeScript) Source: https://context7.com/itachi-1824/cortexone/llms.txt Retrieves the system message used at the start of conversations, which includes instructions for shell command execution and tool availability. ```typescript import { getSystemMessage, SYSTEM_INSTRUCTIONS } from './utils/systemPrompt'; // Get the formatted system message to prepend to the messages array const systemMsg = getSystemMessage(); // { // role: 'system', // content: "You can execute shell commands by wrapping them in tags: // command - Safe commands execute automatically // command - Risky commands need user approval // ..." // } // Use directly in an API call const messages = [systemMsg, ...userMessages]; // Access the raw instructions string console.log(SYSTEM_INSTRUCTIONS); ``` -------------------------------- ### Configure AI Provider and Application Settings in TypeScript Source: https://context7.com/itachi-1824/cortexone/llms.txt Defines the structure for AI provider configurations and the overall application settings, including model assignments and MCP server setups. Essential for connecting to and managing AI services. ```typescript import { Provider, Settings, ModelAssignment, McpServer } from './types'; // Define a provider const myProvider: Provider = { id: 'my-openai', name: 'OpenAI GPT-4o', baseURL: 'https://api.openai.com/v1/chat/completions', apiKey: 'sk-...', headers: {}, parameters: { temperature: 0.7, max_tokens: 4000, top_p: 1 }, stream: true, providerType: 'openai', useRandomSeed: false, retrySettings: { enabled: true, maxRetries: 3 } }; // Full settings object const appSettings: Settings = { providers: [myProvider], modelAssignments: { main: { providerId: 'my-openai', modelId: 'gpt-4o' }, background: { providerId: 'my-openai', modelId: 'gpt-4o-mini' } }, claudeDesktopConfig: { mcpServers: { filesystem: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/home/user/projects'], alwaysAllowTools: ['*'] }, 'sequential-thinking': { command: 'npx', args: ['-y', '@modelcontextprotocol/server-sequential-thinking'] } } }, pluginServers: [], pluginSettings: {}, memorySettings: { enabled: true, maxMemories: 1000, retentionDays: 30 } }; ``` -------------------------------- ### Memory Service for Conversation Fact Extraction and Retrieval Source: https://context7.com/itachi-1824/cortexone/llms.txt The `memoryService` is a singleton for an in-memory store persisted to `localStorage`. It extracts, scores, and retrieves important facts from conversation history to inject relevant context into new conversations. Initialize it on app start. ```typescript import { memoryService } from './services/memoryService'; import { Message, Role } from './types'; // Initialize on app start (loads from localStorage) memoryService.init(); // Add a memory manually memoryService.addMemory({ content: 'User prefers TypeScript over JavaScript', context: 'user: I prefer TypeScript | model: Great choice!', importance: 7, sessionId: 'sess_001', messageId: 'msg_042' }); // Auto-extract memories from conversation messages const messages: Message[] = [ { id: 'm1', role: Role.USER, content: 'My name is Alice and I work at Acme Corp', timestamp: Date.now() }, { id: 'm2', role: Role.MODEL, content: 'Nice to meet you Alice!', timestamp: Date.now() } ]; memoryService.extractMemoriesFromMessages(messages, 'sess_001'); // Extracts message m1 with importance=9 (personal info detected) // Retrieve relevant memories for a new query const relevant = memoryService.getRelevantMemories('What is my name?', 'sess_002', 5); // [{ content: 'My name is Alice and I work at Acme Corp', importance: 9, ... }] // Build context string for system prompt injection const context = memoryService.getConversationContext(messages, 'sess_002'); // "Previous conversation context:\n- My name is Alice...\n\nRecent conversation topics:\n- ..." // Save a session summary memoryService.addSummary('sess_001', messages); // Get stats const stats = memoryService.getStats(); // { memoryCount: 42, summaryCount: 5, oldestMemory: 1700000000000 } // Clear all memories (privacy) memoryService.clearMemories(); ``` -------------------------------- ### Manage MCP Server Processes via Electron IPC Source: https://context7.com/itachi-1824/cortexone/llms.txt Control external MCP server processes using Electron's IPC. This includes starting servers with specific commands and arguments, checking their status, sending JSON-RPC requests, and stopping them. ```typescript // Available via window.desktopApi in the renderer, or directly via IPC in the main process // Start a filesystem MCP server const started = await window.desktopApi.startMcpServer('filesystem', { command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/home/user/docs'], env: { NODE_ENV: 'production' }, workingDirectory: '/home/user' }); console.log('Started:', started); // true // Check status const status = await window.desktopApi.getMcpServerStatus('filesystem'); console.log('Status:', status); // 'running' | 'stopped' | 'error' // Send a JSON-RPC request to the running server const tools = await window.desktopApi.sendMcpRequest('filesystem', { method: 'tools/list', params: {} }); // { tools: [{ name: 'read_file', description: '...', inputSchema: {...} }, ...] } // Invoke a tool const result = await window.desktopApi.sendMcpRequest('filesystem', { method: 'tools/call', params: { name: 'read_file', arguments: { path: '/home/user/docs/readme.txt' } } }); // { content: [{ type: 'text', text: 'File contents here...' }] } // Stop the server const stopped = await window.desktopApi.stopMcpServer('filesystem'); console.log('Stopped:', stopped); // true ``` -------------------------------- ### Build CortexOne for Production Source: https://github.com/itachi-1824/cortexone/blob/main/README.md Build the application for production. Packaging for distribution is coming soon. ```bash npm run build npm run package ``` -------------------------------- ### CortexOne Project Structure Source: https://github.com/itachi-1824/cortexone/blob/main/README.md Overview of the directory structure for the CortexOne project. It highlights key directories like src/components, src/services, and src/electron. ```bash cortexone/ ├── src/ │ ├── components/ # React components │ │ ├── ChatView.tsx # Main chat interface │ │ ├── Sidebar.tsx # Navigation sidebar │ │ ├── SettingsView.tsx # Settings management │ │ └── modals/ # Modal dialogs │ ├── hooks/ # Custom React hooks │ ├── services/ # Business logic │ │ ├── memoryService.ts │ │ ├── mcpService.ts │ │ └── providerService.ts │ ├── types/ # TypeScript definitions │ └── electron/ # Electron main process ├── public/ # Static assets └── package.json ``` -------------------------------- ### Configure OpenAI Provider Source: https://github.com/itachi-1824/cortexone/blob/main/README.md Add your OpenAI provider configuration in the settings. Ensure you replace 'your-api-key-here' with your actual API key. ```json { "id": "openai-gpt4", "name": "OpenAI GPT-4", "baseURL": "https://api.openai.com/v1", "apiKey": "your-api-key-here", "models": ["gpt-4o", "gpt-4-turbo", "gpt-4"] } ``` -------------------------------- ### Save and Load App State with desktopApi Source: https://context7.com/itachi-1824/cortexone/llms.txt Use `window.desktopApi` to save and retrieve application settings, chat sessions, and projects. Settings and projects are loaded as their full objects, while sessions are loaded as an array of `Session` objects. ```typescript // Save and load settings await window.desktopApi.saveSettings(appSettings); const loadedSettings = await window.desktopApi.getSettings(); // Returns the full Settings object, or null if not yet saved // Save and load chat sessions const sessions: Session[] = [ { id: 'sess_1', title: 'Research Session', messages: [], isTemporary: false, projectId: null } ]; await window.desktopApi.saveSessions(sessions); const allSessions = await window.desktopApi.getSessions(); // Session[] // Save and load projects const projects: Project[] = [{ id: 'proj_1', name: 'Work' }]; await window.desktopApi.saveProjects(projects); const allProjects = await window.desktopApi.getProjects(); // Project[] ``` -------------------------------- ### getSystemMessage / SYSTEM_INSTRUCTIONS Source: https://context7.com/itachi-1824/cortexone/llms.txt Retrieves the system message that is prepended to every conversation. This message includes instructions for shell command execution and details about MCP tool availability. ```APIDOC ## getSystemMessage / SYSTEM_INSTRUCTIONS ### Description Returns the system message injected at the start of every conversation. The instructions enable shell command execution via tagged syntax and describe MCP tool availability. ### Usage ```typescript import { getSystemMessage, SYSTEM_INSTRUCTIONS } from './utils/systemPrompt'; // Get the formatted system message const systemMsg = getSystemMessage(); console.log(systemMsg); // Access the raw instructions string console.log(SYSTEM_INSTRUCTIONS); ``` ### System Message Content Example ```json { "role": "system", "content": "You can execute shell commands by wrapping them in tags:\ncommand - Safe commands execute automatically\ncommand - Risky commands need user approval\n..." } ``` ``` -------------------------------- ### fetchPluginsFromServer Source: https://context7.com/itachi-1824/cortexone/llms.txt Fetches a plugin manifest from a URL and returns an array of Plugin objects. It supports custom manifest formats and the ai-plugin.json spec. Returns an empty array on any fetch or parse error. ```APIDOC ## fetchPluginsFromServer ### Description Fetches a plugin manifest (`mcp.json`) from a URL and returns an array of `Plugin` objects. Supports both the custom `{ plugins: [...] }` manifest format and the `ai-plugin.json` spec. ### Parameters * **url** (string) - Required - The URL to fetch the plugin manifest from. ### Returns * `Array` - An array of Plugin objects, or an empty array if an error occurs. ### Request Example ```typescript import { fetchPluginsFromServer } from './services/pluginService'; const plugins = await fetchPluginsFromServer('http://localhost:3001/mcp.json'); console.log(plugins); ``` ### Response Example ```json [ { "id": "weather-tool", "name": "Weather Tool", "description": "Get current weather for a location", "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Returns weather data", "parameters": { "type": "object", "properties": { "city": { "type": "string" } } }, "endpoint": "http://localhost:3001/tools/get_weather" } } ] } ] ``` ### Error Handling Returns `[]` on any fetch or parse error. ``` -------------------------------- ### Fetch Plugins from Server (TypeScript) Source: https://context7.com/itachi-1824/cortexone/llms.txt Fetches plugin manifests from a URL, supporting custom and ai-plugin.json formats. Returns an empty array on errors. ```typescript import { fetchPluginsFromServer } from './services/pluginService'; // Fetch plugins from a running plugin server const plugins = await fetchPluginsFromServer('http://localhost:3001/mcp.json'); // [ // { // id: 'weather-tool', // name: 'Weather Tool', // description: 'Get current weather for a location', // tools: [ // { // type: 'function', // function: { // name: 'get_weather', // description: 'Returns weather data', // parameters: { type: 'object', properties: { city: { type: 'string' } } }, // endpoint: 'http://localhost:3001/tools/get_weather' // } // } // ] // } // ] // Returns [] on any fetch/parse error (safe for use in useEffect) const safePlugins = await fetchPluginsFromServer('http://unreachable:9999/mcp.json'); console.log(safePlugins); // [] ``` -------------------------------- ### Git Workflow for Contributions Source: https://github.com/itachi-1824/cortexone/blob/main/README.md Standard Git commands for contributing to the CortexOne project. Follow these steps to submit your changes via a Pull Request. ```bash 1. Fork the repository 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ``` -------------------------------- ### Fetch Available Models in TypeScript Source: https://context7.com/itachi-1824/cortexone/llms.txt Retrieves a list of models from a provider. Handles Electron environments by delegating to `window.desktopApi.fetchModels` to bypass CORS, otherwise uses a direct browser fetch. ```typescript import { fetchModels } from './services/apiService'; import { Provider } from './types'; const provider: Provider = { id: 'groq-1', name: 'Groq', baseURL: 'https://api.groq.com/openai/v1/chat/completions', apiKey: 'gsk_...', headers: {}, parameters: {}, stream: true }; try { const models = await fetchModels(provider); // [{ id: 'llama-3.1-70b-versatile' }, { id: 'mixtral-8x7b-32768' }, ...] console.log('Available models:', models.map(m => m.id)); } catch (error) { console.error('Failed to fetch models:', error.message); // "Network Error in fetchModels: This is often a CORS issue..." } ``` -------------------------------- ### Manage AI Provider Templates in TypeScript Source: https://context7.com/itachi-1824/cortexone/llms.txt Utilize helper functions to manage and instantiate AI provider templates. Excludes templates with 'disabled: true'. ```typescript import { PROVIDER_TEMPLATES, getProviderTemplate, getEnabledProviderTemplates, createProviderFromTemplate, isProviderTypeDisabled } from './services/providerTemplates'; // List all enabled templates (excludes disabled: true entries like google-gemini) const enabled = getEnabledProviderTemplates(); console.log(enabled.map(t => t.name)); // ['OpenAI Compatible', 'OpenAI', 'Anthropic Claude', 'Ollama', 'Groq', 'Together AI', ...] // Look up a specific template const groqTemplate = getProviderTemplate('groq'); // { // id: 'groq', name: 'Groq', baseURL: 'https://api.groq.com/openai/v1/chat/completions', // authType: 'bearer', stream: true, responseFormat: 'openai', ... // } // Check if a provider type is disabled console.log(isProviderTypeDisabled('google-gemini')); // true console.log(isProviderTypeDisabled('groq')); // false // Create a Provider object from a template const anthropicTemplate = getProviderTemplate('anthropic')!; const newProvider = createProviderFromTemplate(anthropicTemplate, 'My Claude', 'sk-ant-...'); // Returns Omit ready to push into settings.providers after adding an id: // { // name: 'My Claude', // baseURL: 'https://api.anthropic.com/v1/messages', // headers: { 'anthropic-version': '2023-06-01' }, // parameters: { max_tokens: 4000, temperature: 0.7 }, // stream: true, providerType: 'anthropic', // retrySettings: { enabled: true, maxRetries: 3 }, ... // } ``` -------------------------------- ### Define Core Data Types in TypeScript Source: https://context7.com/itachi-1824/cortexone/llms.txt Illustrates the structure for Message, Session, and Project objects, including roles, tool calls, and image attachments. Used for managing chat data. ```typescript import { Role, Message, Session, Project, ToolCall, ImageAttachment } from './types'; // Create a user message with an image attachment const userMessage: Message = { id: 'msg_001', role: Role.USER, content: 'What is in this image?', timestamp: Date.now(), images: [ { url: 'data:image/png;base64,iVBORw0KGgo...', // base64 data URL mimeType: 'image/png' } ] }; // Create a session const session: Session = { id: 'sess_abc123', title: 'Image Analysis', messages: [userMessage], isTemporary: false, projectId: 'proj_xyz' // null if unassigned }; // Create a project const project: Project = { id: 'proj_xyz', name: 'Research' }; // Tool call from model const toolCall: ToolCall = { id: 'call_001', type: 'function', function: { name: 'read_file', arguments: '{"path": "/home/user/notes.txt"}' } }; ``` -------------------------------- ### Synchronize State with Electron Storage using useElectronStorage Hook Source: https://context7.com/itachi-1824/cortexone/llms.txt The `useElectronStorage` hook synchronizes React state with Electron's `desktopApi` persistence layer, falling back to `localStorage`. It debounces writes to minimize I/O operations. Requires async getter and setter functions. ```typescript import useElectronStorage from './hooks/useElectronStorage'; import { Session } from './types'; import { useCallback } from 'react'; function MyComponent() { const getSessionsFn = useCallback( () => window.desktopApi?.getSessions() ?? Promise.resolve([]), [] ); const saveSessionsFn = useCallback( (sessions: Session[]) => window.desktopApi?.saveSessions(sessions) ?? Promise.resolve({ success: true }), [] ); const [sessions, setSessions] = useElectronStorage( 'chat-sessions', // localStorage key (fallback) [], // initial value getSessionsFn, // async getter saveSessionsFn // async setter → { success: boolean; error?: string } ); // sessions is auto-loaded on mount; setSessions triggers a debounced save const addSession = () => { setSessions(prev => [...prev, { id: 'new_' + Date.now(), title: 'New Chat', messages: [], isTemporary: false, projectId: null }]); }; return ; } ``` -------------------------------- ### Simple Local Storage Persistence with useLocalStorage Hook Source: https://context7.com/itachi-1824/cortexone/llms.txt The `useLocalStorage` hook provides a straightforward way to persist React state directly to `localStorage`, suitable for web or fallback scenarios. It takes a key and an initial value. ```typescript import useLocalStorage from './hooks/useLocalStorage'; function ThemeSelector() { const [theme, setTheme] = useLocalStorage<'dark' | 'light'>('ui-theme', 'dark'); return ( ); } ``` -------------------------------- ### sendMessageStream Source: https://context7.com/itachi-1824/cortexone/llms.txt Sends a full conversation to the active provider with streaming callbacks. Handles multi-modal messages, tool/function calls, and provider-specific message format normalization. When running in Electron, it simulates word-level streaming for a smooth user experience. ```APIDOC ## sendMessageStream ### Description Sends a full conversation to the active provider with streaming callbacks. Handles multi-modal messages (text + images), tool/function calls, and provider-specific message format normalization. When running in Electron, simulates word-level streaming from the non-streaming Electron IPC response for a smooth UX. ### Method Signature `sendMessageStream(provider: Provider, model: string, messages: Message[], tools?: Tool[], callbacks?: { onChunk?: (text: string) => void; onToolCall?: (toolCalls: any[]) => void; onComplete?: () => void; onError?: (error: any) => void; }, requestId?: string): Promise` ### Parameters - **provider** (Provider) - Required - The provider configuration to use for the API call. - **model** (string) - Required - The model identifier to use (e.g., 'gpt-4o'). - **messages** (Message[]) - Required - An array of message objects representing the conversation history. - **tools** (Tool[]) - Optional - An array of tool definitions that the model can use. - **callbacks** (object) - Optional - An object containing callback functions for handling streaming responses: - **onChunk** (function) - Called with each text chunk received. - **onToolCall** (function) - Called when the model requests to call a tool. - **onComplete** (function) - Called when the stream is completed. - **onError** (function) - Called if an error occurs during the stream. - **requestId** (string) - Optional - A unique identifier for the request, used for cancellation. ### Request Example ```typescript import { sendMessageStream } from './services/apiService'; import { Provider, Message, Role, Tool } from './types'; const provider: Provider = { id: 'openai-1', name: 'OpenAI', baseURL: 'https://api.openai.com/v1/chat/completions', apiKey: 'sk-...', headers: {}, parameters: { temperature: 0.7, max_tokens: 4000 }, stream: true }; const messages: Message[] = [ { id: 'm1', role: Role.USER, content: 'List the files in the current directory.', timestamp: Date.now() } ]; const tools: Tool[] = [ { type: 'function', function: { name: 'list_directory', description: 'Lists files in a directory', parameters: { type: 'object', properties: { path: { type: 'string', description: 'Directory path' } }, required: ['path'] } } } ]; let responseText = ''; await sendMessageStream( provider, 'gpt-4o', messages, tools, { onChunk: (text) => { responseText += text; process.stdout.write(text); // Stream to console }, onToolCall: (toolCalls) => { console.log('Tool call requested:', toolCalls[0].function.name); }, onComplete: () => { console.log('\nFull response:', responseText); }, onError: (error) => { console.error('Stream error:', error); } }, 'request-id-001' // Optional: used with cancelRequest() ); ``` ``` -------------------------------- ### Execute Tool Call (TypeScript) Source: https://context7.com/itachi-1824/cortexone/llms.txt Executes a remote plugin tool call by POSTing arguments to a tool's endpoint. Returns stringified JSON results or a JSON-encoded error object. ```typescript import { executeToolCall } from './services/pluginService'; import { ToolCall } from './types'; const toolCall: ToolCall = { id: 'call_xyz', type: 'function', function: { name: 'get_weather', arguments: '{"city": "San Francisco"}' } }; const result = await executeToolCall(toolCall, 'http://localhost:3001/tools/get_weather'); // On success: '{ // "temperature": 65, // "condition": "Partly Cloudy", // "humidity": 72 // }' // On HTTP error: // '{"error":"Tool execution failed with status 500","details":"Internal Server Error"}' // On network error: // '{"error":"Failed to execute tool at http://...","details":"fetch failed"}' ``` -------------------------------- ### executeToolCall Source: https://context7.com/itachi-1824/cortexone/llms.txt Executes a remote plugin tool call by POSTing the model-provided JSON arguments to the tool's endpoint URL. Returns the stringified JSON result or a JSON-encoded error object. ```APIDOC ## executeToolCall ### Description Executes a remote plugin tool call by POSTing the model-provided JSON arguments to the tool's `endpoint` URL. Returns the stringified JSON result or a JSON-encoded error object. ### Parameters * **toolCall** (`ToolCall`) - Required - The tool call object containing information about the function to execute. * **endpointUrl** (string) - Required - The URL of the tool's endpoint. ### Returns * `string` - The stringified JSON result of the tool execution, or a JSON-encoded error object. ### Request Example ```typescript import { executeToolCall } from './services/pluginService'; import { ToolCall } from './types'; const toolCall: ToolCall = { id: 'call_xyz', type: 'function', function: { name: 'get_weather', arguments: '{"city": "San Francisco"}' } }; const result = await executeToolCall(toolCall, 'http://localhost:3001/tools/get_weather'); console.log(result); ``` ### Response Example (Success) ```json { "temperature": 65, "condition": "Partly Cloudy", "humidity": 72 } ``` ### Error Handling * **HTTP error**: Returns a JSON-encoded error object like `{"error":"Tool execution failed with status 500","details":"Internal Server Error"}`. * **Network error**: Returns a JSON-encoded error object like `{"error":"Failed to execute tool at http://...","details":"fetch failed"}`. ``` -------------------------------- ### Send Message with Streaming Callbacks Source: https://context7.com/itachi-1824/cortexone/llms.txt Use `sendMessageStream` to send a conversation to a provider with streaming callbacks for real-time updates. It supports multi-modal messages, tool calls, and handles provider-specific normalization. For Electron, it simulates word-level streaming. ```typescript import { sendMessageStream } from './services/apiService'; import { Provider, Message, Role, Tool } from './types'; const provider: Provider = { id: 'openai-1', name: 'OpenAI', baseURL: 'https://api.openai.com/v1/chat/completions', apiKey: 'sk-...', headers: {}, parameters: { temperature: 0.7, max_tokens: 4000 }, stream: true }; const messages: Message[] = [ { id: 'm1', role: Role.USER, content: 'List the files in the current directory.', timestamp: Date.now() } ]; const tools: Tool[] = [ { type: 'function', function: { name: 'list_directory', description: 'Lists files in a directory', parameters: { type: 'object', properties: { path: { type: 'string', description: 'Directory path' } }, required: ['path'] } } } ]; let responseText = ''; await sendMessageStream( provider, 'gpt-4o', messages, tools, { onChunk: (text) => { responseText += text; process.stdout.write(text); // Stream to console }, onToolCall: (toolCalls) => { // Model wants to call a tool // toolCalls: [{ id: 'call_abc', type: 'function', function: { name: 'list_directory', arguments: '{"path":"."}' } }] console.log('Tool call requested:', toolCalls[0].function.name); }, onComplete: () => { console.log('\nFull response:', responseText); }, onError: (error) => { console.error('Stream error:', error); // "API Error: 401 Unauthorized - ..." } }, 'request-id-001' // Optional: used with cancelRequest() ); ``` -------------------------------- ### cancelRequest Source: https://context7.com/itachi-1824/cortexone/llms.txt Aborts an in-flight API request using the AbortController registered for that requestId in the Electron main process. ```APIDOC ## `window.desktopApi.cancelRequest` ### Description Aborts an in-flight API request using the `AbortController` registered for that `requestId` in the Electron main process. ### Method Signature `cancelRequest(requestId: string): Promise<{ success: boolean }>` ### Parameters - **requestId** (string) - Required - The unique identifier of the request to cancel. ### Returns - **Promise<{ success: boolean }>** - An object indicating whether the cancellation was successful. ### Request Example ```typescript // Assume sendMessageStream is defined elsewhere and accepts a requestId // import { sendMessageStream } from './services/apiService'; const requestId = 'user-req-' + Date.now(); // Start a long-running request with a known ID // sendMessageStream(provider, 'gpt-4o', messages, [], callbacks, requestId); // Cancel it after 5 seconds setTimeout(async () => { const result = await window.desktopApi.cancelRequest(requestId); console.log('Cancelled:', result.success); // true }, 5000); ``` ``` -------------------------------- ### Generate Session Title in TypeScript Source: https://context7.com/itachi-1824/cortexone/llms.txt Generates a concise session title (3-5 words) from the user's first message using the active provider. Falls back to 'Untitled Chat' on any error. ```typescript import { generateTitle } from './services/apiService'; import { Provider } from './types'; const provider: Provider = { id: 'openai-1', name: 'OpenAI', baseURL: 'https://api.openai.com/v1/chat/completions', apiKey: 'sk-...', headers: {}, parameters: { temperature: 0.7, max_tokens: 4000 }, stream: true }; const title = await generateTitle(provider, 'gpt-4o', 'How do I implement a binary search tree in Python?'); console.log(title); // "Binary Search Tree Python" ``` -------------------------------- ### Cancel In-flight API Request Source: https://context7.com/itachi-1824/cortexone/llms.txt Abort a long-running API request using `window.desktopApi.cancelRequest` by providing the unique `requestId` associated with the request. This is useful for user-initiated cancellations. ```typescript // Start a long-running request with a known ID const requestId = 'user-req-' + Date.now(); sendMessageStream(provider, 'gpt-4o', messages, [], callbacks, requestId); // Cancel it after 5 seconds setTimeout(async () => { const result = await window.desktopApi.cancelRequest(requestId); console.log('Cancelled:', result.success); // true }, 5000); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.