solver-sdk 3.1.2 → 3.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,269 +0,0 @@
1
- # VS Code Extension Integration
2
-
3
- > **Практическое руководство интеграции SDK с VS Code Extension**
4
-
5
- ## 🚀 Быстрая интеграция
6
-
7
- ### 1. Базовая настройка
8
-
9
- ```typescript
10
- import { CodeSolverSDK } from 'solver-sdk';
11
- import * as vscode from 'vscode';
12
-
13
- // Инициализация SDK
14
- let sdk: CodeSolverSDK;
15
-
16
- export async function activate(context: vscode.ExtensionContext) {
17
- // Создание SDK
18
- sdk = await CodeSolverSDK.create({
19
- baseURL: 'http://localhost:3000'
20
- });
21
-
22
- // Регистрация команд
23
- const indexCommand = vscode.commands.registerCommand(
24
- 'myExtension.indexProject',
25
- indexCurrentWorkspace
26
- );
27
-
28
- const searchCommand = vscode.commands.registerCommand(
29
- 'myExtension.searchFunctions',
30
- searchAndNavigate
31
- );
32
-
33
- context.subscriptions.push(indexCommand, searchCommand);
34
- }
35
- ```
36
-
37
- ## 📊 Индексация с прогресс-баром
38
-
39
- ```typescript
40
- async function indexCurrentWorkspace() {
41
- if (!vscode.workspace.workspaceFolders) {
42
- vscode.window.showErrorMessage('Откройте папку проекта');
43
- return;
44
- }
45
-
46
- const folder = vscode.workspace.workspaceFolders[0];
47
- const projectPath = folder.uri.fsPath;
48
- const projectName = folder.name;
49
-
50
- return vscode.window.withProgress({
51
- location: vscode.ProgressLocation.Notification,
52
- title: 'Индексация проекта',
53
- cancellable: true
54
- }, async (progress, token) => {
55
- try {
56
- progress.report({ message: 'Создание проекта...' });
57
- const project = await sdk.projects.findOrCreateProject(projectPath, projectName);
58
-
59
- progress.report({ message: 'Запуск индексации...' });
60
- await sdk.projects.startIndexing(project.id);
61
-
62
- while (!token.isCancellationRequested) {
63
- const status = await sdk.projects.getProjectStatus(project.id);
64
-
65
- if (status.status === 'ready') {
66
- vscode.window.showInformationMessage('✅ Проект проиндексирован!');
67
- return project;
68
- }
69
-
70
- if (status.status === 'error') {
71
- throw new Error(status.error);
72
- }
73
-
74
- const percentage = status.progress || 0;
75
- progress.report({
76
- increment: percentage,
77
- message: `${percentage}% - ${status.currentFile || 'Обработка...'}`
78
- });
79
-
80
- await new Promise(resolve => setTimeout(resolve, 2000));
81
- }
82
-
83
- } catch (error) {
84
- vscode.window.showErrorMessage(`Ошибка: ${error.message}`);
85
- }
86
- });
87
- }
88
- ```
89
-
90
- ## 🔍 Поиск функций с навигацией
91
-
92
- ```typescript
93
- async function searchAndNavigate() {
94
- const projects = await sdk.projects.getReadyProjects();
95
-
96
- if (projects.length === 0) {
97
- vscode.window.showWarningMessage('Нет проиндексированных проектов');
98
- return;
99
- }
100
-
101
- const query = await vscode.window.showInputBox({
102
- prompt: 'Поиск функций',
103
- placeholder: 'Введите название функции или описание...'
104
- });
105
-
106
- if (!query) return;
107
-
108
- try {
109
- const results = await sdk.search.searchFunctions(projects[0].id, {
110
- query,
111
- limit: 20
112
- });
113
-
114
- if (results.results.length === 0) {
115
- vscode.window.showInformationMessage('Ничего не найдено');
116
- return;
117
- }
118
-
119
- const functionItems = results.results.map(fn => ({
120
- label: `$(symbol-function) ${fn.name}`,
121
- description: fn.signature,
122
- detail: `${fn.filePath}:${fn.startLine}`,
123
- function: fn
124
- }));
125
-
126
- const selectedFunction = await vscode.window.showQuickPick(functionItems);
127
-
128
- if (selectedFunction) {
129
- await navigateToFunction(selectedFunction.function);
130
- }
131
-
132
- } catch (error) {
133
- vscode.window.showErrorMessage(`Ошибка поиска: ${error.message}`);
134
- }
135
- }
136
-
137
- async function navigateToFunction(fn: any) {
138
- try {
139
- const doc = await vscode.workspace.openTextDocument(fn.filePath);
140
- const editor = await vscode.window.showTextDocument(doc);
141
-
142
- const range = new vscode.Range(
143
- fn.startLine - 1, 0,
144
- fn.endLine - 1, 0
145
- );
146
-
147
- editor.selection = new vscode.Selection(range.start, range.end);
148
- editor.revealRange(range, vscode.TextEditorRevealType.InCenter);
149
-
150
- } catch (error) {
151
- vscode.window.showErrorMessage(`Ошибка навигации: ${error.message}`);
152
- }
153
- }
154
- ```
155
-
156
- ## 💬 AI Chat интеграция
157
-
158
- ```typescript
159
- async function askAI() {
160
- const editor = vscode.window.activeTextEditor;
161
- if (!editor) {
162
- vscode.window.showWarningMessage('Откройте файл в редакторе');
163
- return;
164
- }
165
-
166
- const selection = editor.selection;
167
- const selectedText = editor.document.getText(selection);
168
-
169
- let contextText = '';
170
- if (selectedText) {
171
- contextText = `
172
-
173
- Выделенный код:
174
- \`\`\`${editor.document.languageId}
175
- ${selectedText}
176
- \`\`\``;
177
- }
178
-
179
- const question = await vscode.window.showInputBox({
180
- prompt: 'Задайте вопрос AI',
181
- placeholder: 'Что делает этот код? Как его улучшить?'
182
- });
183
-
184
- if (!question) return;
185
-
186
- return vscode.window.withProgress({
187
- location: vscode.ProgressLocation.Notification,
188
- title: 'AI анализирует код...',
189
- cancellable: false
190
- }, async (progress) => {
191
- try {
192
- const response = await sdk.chat.chat([{
193
- role: 'user',
194
- content: question + contextText
195
- }], {
196
- model: 'claude-3-5-sonnet-20241022',
197
- maxTokens: 8192
198
- });
199
-
200
- const doc = await vscode.workspace.openTextDocument({
201
- content: `Q: ${question}
202
-
203
- A: ${response.content[0].text}`,
204
- language: 'markdown'
205
- });
206
-
207
- await vscode.window.showTextDocument(doc);
208
-
209
- } catch (error) {
210
- vscode.window.showErrorMessage(`Ошибка AI: ${error.message}`);
211
- }
212
- });
213
- }
214
- ```
215
-
216
- ## ⚙️ Конфигурация package.json
217
-
218
- ```json
219
- {
220
- "name": "my-code-assistant",
221
- "displayName": "AI Code Assistant",
222
- "description": "AI помощник для анализа и поиска кода",
223
- "version": "1.0.0",
224
- "engines": {
225
- "vscode": "^1.60.0"
226
- },
227
- "categories": ["Other"],
228
- "activationEvents": [
229
- "onStartupFinished"
230
- ],
231
- "main": "./out/extension.js",
232
- "contributes": {
233
- "commands": [
234
- {
235
- "command": "myExtension.indexProject",
236
- "title": "📊 Проиндексировать проект",
237
- "category": "AI Assistant"
238
- },
239
- {
240
- "command": "myExtension.searchFunctions",
241
- "title": "🔍 Поиск функций",
242
- "category": "AI Assistant"
243
- },
244
- {
245
- "command": "myExtension.askAI",
246
- "title": "💬 Спросить AI",
247
- "category": "AI Assistant"
248
- }
249
- ],
250
- "keybindings": [
251
- {
252
- "command": "myExtension.searchFunctions",
253
- "key": "ctrl+shift+f",
254
- "mac": "cmd+shift+f"
255
- },
256
- {
257
- "command": "myExtension.askAI",
258
- "key": "ctrl+shift+a",
259
- "mac": "cmd+shift+a"
260
- }
261
- ]
262
- },
263
- "dependencies": {
264
- "solver-sdk": "^3.0.0"
265
- }
266
- }
267
- ```
268
-
269
- SDK готов для интеграции в VS Code Extension! 🚀
@@ -1,324 +0,0 @@
1
- # Anthropic Claude 4 Thinking + Tool Calling
2
-
3
- Полная поддержка Anthropic Claude 4 с расширенным мышлением (thinking) и инструментами (tool calling). SDK предоставляет все необходимые функции для работы с complex content, signature handling и правильным tool_choice.
4
-
5
- ## 🚀 Критические особенности
6
-
7
- ### ✅ **Complex Content поддержка**
8
- SDK поддерживает массивы `ContentBlock[]` вместо простых строк:
9
-
10
- ```typescript
11
- interface ChatMessage {
12
- role: 'system' | 'user' | 'assistant';
13
- content: string | ContentBlock[]; // ✅ Поддержка массива блоков
14
- }
15
- ```
16
-
17
- ### ✅ **Tool Choice ограничения**
18
- С thinking поддерживаются только `'auto'` и `'none'`:
19
-
20
- ```typescript
21
- // ✅ Правильно
22
- tool_choice: { type: 'auto' } // или { type: 'none' }
23
-
24
- // ❌ НЕ поддерживается с thinking
25
- tool_choice: { type: 'any' } // Ошибка!
26
- tool_choice: { type: 'tool', name: 'read_file' } // Ошибка!
27
- ```
28
-
29
- ### ✅ **Signature handling**
30
- Автоматическое сохранение и передача криптографических подписей:
31
-
32
- ```typescript
33
- {
34
- type: 'thinking',
35
- thinking: 'размышления модели...',
36
- signature: 'WaUjzkypQ2mUEVM36O2TxuC06KN8xyfbJwyem...' // ✅ Сохраняется
37
- }
38
- ```
39
-
40
- ## 📋 Основные функции
41
-
42
- ### Helper функции для complex content
43
-
44
- ```typescript
45
- import {
46
- createStandardDevelopmentTools,
47
- createToolResultMessage,
48
- extractThinkingBlocks,
49
- extractToolUseBlocks,
50
- createComplexAssistantMessage,
51
- createUserMessage
52
- } from 'solver-sdk';
53
- ```
54
-
55
- ## 🎯 Полный пример использования
56
-
57
- ### 1. **Первый запрос с thinking + tools**
58
-
59
- ```javascript
60
- const { CodeSolverSDK, createStandardDevelopmentTools, createUserMessage } = require('solver-sdk');
61
-
62
- const sdk = new CodeSolverSDK({
63
- baseURL: 'https://localhost:3001',
64
- apiKey: 'your-api-key'
65
- });
66
-
67
- async function demonstrateThinkingWithTools() {
68
- // 1. Получаем стандартные инструменты (как в Cursor)
69
- const tools = createStandardDevelopmentTools();
70
-
71
- // 2. Создаем запрос пользователя
72
- const userRequest = createUserMessage(
73
- 'Создай Node.js скрипт для чтения package.json'
74
- );
75
-
76
- // 3. Отправляем запрос с правильными параметрами
77
- const response = await sdk.chat.chat([userRequest], {
78
- model: 'claude-sonnet-4-20250514',
79
- max_tokens: 16000,
80
- thinking: {
81
- type: 'enabled',
82
- budget_tokens: 10000 // Минимум 1024
83
- },
84
- tools: tools,
85
- tool_choice: { type: 'auto' }, // ✅ ТОЛЬКО auto/none с thinking!
86
- beta: 'interleaved-thinking-2025-05-14' // Автоматически включается
87
- });
88
-
89
- return response;
90
- }
91
- ```
92
-
93
- ### 2. **Обработка thinking и tool_use блоков**
94
-
95
- ```javascript
96
- import { extractThinkingBlocks, extractToolUseBlocks } from 'solver-sdk';
97
-
98
- // Извлекаем блоки из ответа
99
- const thinkingBlocks = extractThinkingBlocks(response.content);
100
- const toolUseBlocks = extractToolUseBlocks(response.content);
101
-
102
- console.log('🧠 Блоков мышления:', thinkingBlocks.length);
103
- console.log('🔧 Блоков tool_use:', toolUseBlocks.length);
104
-
105
- // Показываем thinking с signature
106
- thinkingBlocks.forEach((block, idx) => {
107
- console.log(`Мышление ${idx + 1}:`, block.thinking);
108
- if (block.signature) {
109
- console.log('🔐 Signature:', block.signature);
110
- }
111
- });
112
- ```
113
-
114
- ### 3. **Выполнение инструментов и продолжение диалога**
115
-
116
- ```javascript
117
- import {
118
- createToolResultMessage,
119
- createComplexAssistantMessage
120
- } from 'solver-sdk';
121
-
122
- if (toolUseBlocks.length > 0) {
123
- const toolUse = toolUseBlocks[0];
124
-
125
- // Выполняем инструмент (здесь симуляция)
126
- const toolResult = await executeToolLocally(toolUse);
127
-
128
- // ✅ КРИТИЧНО: Создаем правильную последовательность сообщений
129
- const toolResultMessage = createToolResultMessage(
130
- toolUse.id,
131
- toolResult,
132
- false // не ошибка
133
- );
134
-
135
- // ✅ КРИТИЧНО: Создаем complex content сообщение от ассистента
136
- const assistantMessage = createComplexAssistantMessage(
137
- thinkingBlocks, // Сохраняем thinking с signature!
138
- toolUseBlocks, // Сохраняем tool_use
139
- [] // Текстовые блоки (если есть)
140
- );
141
-
142
- // Продолжаем диалог с сохранением thinking
143
- const messages = [
144
- userRequest,
145
- assistantMessage, // ✅ Complex content с thinking + tool_use
146
- toolResultMessage // Результат выполнения инструмента
147
- ];
148
-
149
- const finalResponse = await sdk.chat.chat(messages, {
150
- model: 'claude-sonnet-4-20250514',
151
- max_tokens: 16000,
152
- thinking: { type: 'enabled', budget_tokens: 10000 },
153
- tools: tools,
154
- tool_choice: { type: 'auto' },
155
- beta: 'interleaved-thinking-2025-05-14'
156
- });
157
- }
158
- ```
159
-
160
- ## 🌊 Потоковая передача
161
-
162
- ### Streaming с thinking + tools
163
-
164
- ```javascript
165
- async function streamingExample() {
166
- const stream = sdk.chat.streamChat([userRequest], {
167
- model: 'claude-sonnet-4-20250514',
168
- max_tokens: 16000,
169
- thinking: {
170
- type: 'enabled',
171
- budget_tokens: 8000
172
- },
173
- tools: tools,
174
- tool_choice: { type: 'auto' },
175
- beta: 'interleaved-thinking-2025-05-14',
176
- stream: true
177
- });
178
-
179
- // Обрабатываем поток
180
- for await (const chunk of stream) {
181
- if (chunk.type === 'content_block_delta' && chunk.delta) {
182
- // ✅ Thinking события
183
- if (chunk.delta.type === 'thinking_delta') {
184
- console.log('Мышление:', chunk.delta.thinking);
185
- }
186
- // ✅ Signature события
187
- else if (chunk.delta.type === 'signature_delta') {
188
- console.log('🔐 Signature:', chunk.delta.signature);
189
- }
190
- // ✅ Текстовые события
191
- else if (chunk.delta.type === 'text_delta') {
192
- console.log('Ответ:', chunk.delta.text);
193
- }
194
- }
195
- // ✅ Tool use события
196
- else if (chunk.type === 'content_block_start' && chunk.content_block?.type === 'tool_use') {
197
- console.log('🛠️ Инструмент:', chunk.content_block.name);
198
- }
199
- // Завершение потока
200
- else if (chunk.type === 'message_stop') {
201
- break;
202
- }
203
- }
204
- }
205
- ```
206
-
207
- ## 🛠️ Стандартные инструменты разработки
208
-
209
- ```javascript
210
- import { createStandardDevelopmentTools } from 'solver-sdk';
211
-
212
- const tools = createStandardDevelopmentTools();
213
- // Возвращает массив из 8 инструментов:
214
- // - read_file
215
- // - create_file
216
- // - edit_file
217
- // - search_files
218
- // - list_directory
219
- // - terminal_command
220
- // - semantic_search
221
- // - analyze_project_context
222
- ```
223
-
224
- ## 🚨 Обработка ошибок инструментов
225
-
226
- ```javascript
227
- import { createToolResultMessage } from 'solver-sdk';
228
-
229
- // При ошибке выполнения инструмента
230
- const errorResult = createToolResultMessage(
231
- toolUse.id,
232
- 'Ошибка: Файл не найден',
233
- true // ✅ КРИТИЧНО: флаг ошибки
234
- );
235
-
236
- // Продолжаем диалог с ошибкой
237
- const messages = [userRequest, assistantMessage, errorResult];
238
- const errorResponse = await sdk.chat.chat(messages, options);
239
- ```
240
-
241
- ## 📊 Типы событий в потоке
242
-
243
- ### **Thinking события**
244
- ```typescript
245
- 'content_block_start' + content_block.type === 'thinking'
246
- 'content_block_delta' + delta.type === 'thinking_delta'
247
- 'content_block_delta' + delta.type === 'signature_delta' // ✅ НОВОЕ!
248
- 'content_block_stop'
249
- ```
250
-
251
- ### **Tool use события**
252
- ```typescript
253
- 'content_block_start' + content_block.type === 'tool_use'
254
- 'content_block_delta' + delta.type === 'text_delta'
255
- 'content_block_stop'
256
- ```
257
-
258
- ### **Text ответ**
259
- ```typescript
260
- 'content_block_start' + content_block.type === 'text'
261
- 'content_block_delta' + delta.type === 'text_delta'
262
- 'content_block_stop'
263
- ```
264
-
265
- ## ⚙️ Правильная конфигурация
266
-
267
- ### Обязательные параметры
268
-
269
- ```typescript
270
- {
271
- model: 'claude-sonnet-4-20250514',
272
- thinking: {
273
- type: 'enabled',
274
- budget_tokens: 10000 // Минимум 1024
275
- },
276
- tools: createStandardDevelopmentTools(),
277
- tool_choice: { type: 'auto' }, // ТОЛЬКО auto/none
278
- beta: 'interleaved-thinking-2025-05-14',
279
- max_tokens: 16000
280
- }
281
- ```
282
-
283
- ### Дополнительные параметры
284
-
285
- ```typescript
286
- {
287
- top_p: 0.98, // От 0.95 до 1 с thinking
288
- stream: true,
289
- projectId: 'your-project-id', // Для автовыполнения инструментов
290
- // temperature НЕ поддерживается с thinking
291
- }
292
- ```
293
-
294
- ## 🎯 Готовность к тестированию
295
-
296
- ### ✅ **Готово в SDK:**
297
- - Complex Content поддержка с `ContentBlock[]`
298
- - Правильная валидация `tool_choice`
299
- - Signature preservation в thinking блоках
300
- - Все необходимые helper функции
301
- - Streaming обработка всех событий
302
- - Cursor-подобные стандартные инструменты
303
-
304
- ### 🚀 **Простые тесты для проверки:**
305
-
306
- ```javascript
307
- // 1. Простой tool calling
308
- "Прочитай файл package.json"
309
- → thinking → read_file → ответ
310
-
311
- // 2. Сложный multi-tool workflow
312
- "Найди все баги в коде и исправь их"
313
- → thinking → semantic_search → read_file → edit_file → thinking → ответ
314
-
315
- // 3. Cursor-подобные запросы
316
- "Добавь аутентификацию в это приложение"
317
- → thinking → analyze_project_context → semantic_search → create_file → edit_file
318
- ```
319
-
320
- ## 📞 Результат
321
-
322
- **SDK ПОЛНОСТЬЮ ГОТОВ** для работы с Anthropic Claude 4 thinking + tool calling. Все критические требования клиента реализованы и протестированы.
323
-
324
- **Статус:** ✅ ГОТОВ к немедленному тестированию