solver-sdk 2.3.0 → 2.5.0

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,328 +0,0 @@
1
- # Примеры интеграции SDK
2
-
3
- В этом документе приведены примеры использования SDK с расширениями VS Code/Cursor или другими приложениями.
4
-
5
- ## Содержание
6
- - [Инициализация SDK](#инициализация-sdk)
7
- - [Работа с проектами](#работа-с-проектами)
8
- - [Отслеживание прогресса индексации](#отслеживание-прогресса-индексации)
9
- - [Потоковый чат с мышлением](#потоковый-чат-с-мышлением)
10
- - [Поиск в коде](#поиск-в-коде)
11
-
12
- ## Инициализация SDK
13
-
14
- Пример инициализации SDK в расширении VS Code/Cursor:
15
-
16
- ```typescript
17
- import * as vscode from 'vscode';
18
- import { CodeSolverSDK } from 'solver-sdk';
19
-
20
- // Инициализация SDK
21
- const sdk = new CodeSolverSDK({
22
- baseURL: 'https://api.example.com',
23
- apiKey: 'your-api-key',
24
- websocket: {
25
- reconnect: true,
26
- reconnectAttempts: 5,
27
- reconnectDelay: 3000,
28
- rejectUnauthorized: false // для самоподписанных сертификатов
29
- }
30
- });
31
-
32
- // Проверка доступности API
33
- async function checkConnection() {
34
- try {
35
- const isHealthy = await sdk.checkHealth();
36
- if (isHealthy) {
37
- vscode.window.showInformationMessage('API доступен');
38
- } else {
39
- vscode.window.showErrorMessage('API недоступен');
40
- }
41
- } catch (error) {
42
- vscode.window.showErrorMessage(`Ошибка соединения: ${error.message}`);
43
- }
44
- }
45
- ```
46
-
47
- ## Работа с проектами
48
-
49
- Пример автоматической работы с проектом при открытии рабочей области:
50
-
51
- ```typescript
52
- import * as path from 'path';
53
-
54
- // Получение проекта по пути рабочей области
55
- async function handleWorkspace() {
56
- try {
57
- // Получаем путь к текущей рабочей области
58
- const workspaceFolders = vscode.workspace.workspaceFolders;
59
- if (!workspaceFolders || workspaceFolders.length === 0) {
60
- vscode.window.showWarningMessage('Откройте папку проекта');
61
- return;
62
- }
63
-
64
- const workspacePath = workspaceFolders[0].uri.fsPath;
65
- const projectName = path.basename(workspacePath);
66
-
67
- // Получаем проект или создаем новый
68
- const project = await sdk.projects.getOrCreateProject(
69
- workspacePath,
70
- projectName
71
- );
72
-
73
- if (project) {
74
- vscode.window.showInformationMessage(`Проект "${projectName}" идентифицирован (ID: ${project.id})`);
75
- return project;
76
- }
77
- } catch (error) {
78
- vscode.window.showErrorMessage(`Ошибка: ${error.message}`);
79
- }
80
-
81
- return null;
82
- }
83
- ```
84
-
85
- ## Отслеживание прогресса индексации
86
-
87
- Пример отслеживания прогресса индексации:
88
-
89
- ```typescript
90
- // Запуск индексации проекта
91
- async function indexProject(projectId, projectName) {
92
- try {
93
- // Запускаем индексацию
94
- await sdk.projects.indexProject(projectId);
95
-
96
- // Показываем прогресс
97
- vscode.window.withProgress({
98
- location: vscode.ProgressLocation.Notification,
99
- title: `Индексация проекта "${projectName}"`,
100
- cancellable: true
101
- }, async (progress, token) => {
102
- // Подключаемся к WebSocket для индексации
103
- await sdk.projects.connectWebSocket();
104
-
105
- return new Promise((resolve) => {
106
- // Отслеживаем прогресс
107
- sdk.projects.on('indexing_progress', (data) => {
108
- progress.report({
109
- message: `${data.progress}% (${data.processedFiles}/${data.totalFiles} файлов)`,
110
- increment: data.progress
111
- });
112
- });
113
-
114
- // Отслеживаем завершение
115
- sdk.projects.on('indexing_complete', (data) => {
116
- if (data.success) {
117
- vscode.window.showInformationMessage('Индексация успешно завершена!');
118
- } else {
119
- vscode.window.showWarningMessage(`Индексация завершена с ошибками: ${data.errorMessage || 'неизвестная ошибка'}`);
120
- }
121
- sdk.projects.disconnectWebSocket();
122
- resolve();
123
- });
124
-
125
- // Обработка отмены
126
- token.onCancellationRequested(() => {
127
- sdk.projects.stopIndexing(projectId)
128
- .then(() => {
129
- vscode.window.showInformationMessage('Индексация отменена');
130
- sdk.projects.disconnectWebSocket();
131
- resolve();
132
- });
133
- });
134
- });
135
- });
136
- } catch (error) {
137
- vscode.window.showErrorMessage(`Ошибка индексации: ${error.message}`);
138
- }
139
- }
140
- ```
141
-
142
- ## Потоковый чат с мышлением
143
-
144
- Пример использования потокового чата с мышлением:
145
-
146
- ```typescript
147
- // Регистрация команды чата с мышлением
148
- context.subscriptions.push(
149
- vscode.commands.registerCommand('solver.chatWithThinking', async () => {
150
- try {
151
- // Запрашиваем ввод от пользователя
152
- const question = await vscode.window.showInputBox({
153
- prompt: 'Введите вопрос'
154
- });
155
-
156
- if (!question) return;
157
-
158
- // Создаем и показываем панель для результата
159
- const panel = vscode.window.createWebviewPanel(
160
- 'chatWithThinking',
161
- 'Ответ с мышлением',
162
- vscode.ViewColumn.Beside,
163
- { enableScripts: true }
164
- );
165
-
166
- // Начальный HTML для панели
167
- panel.webview.html = `
168
- <!DOCTYPE html>
169
- <html>
170
- <head>
171
- <style>
172
- body { font-family: var(--vscode-font-family); padding: 10px; }
173
- .thinking { color: #666; font-style: italic; white-space: pre-wrap; }
174
- .answer { white-space: pre-wrap; }
175
- </style>
176
- </head>
177
- <body>
178
- <h3>Вопрос: ${question}</h3>
179
- <div class="thinking" id="thinking"></div>
180
- <h4>Ответ:</h4>
181
- <div class="answer" id="answer"></div>
182
-
183
- <script>
184
- const vscode = acquireVsCodeApi();
185
- window.addEventListener('message', event => {
186
- const message = event.data;
187
- if (message.command === 'appendThinking') {
188
- document.getElementById('thinking').textContent += message.content;
189
- } else if (message.command === 'appendAnswer') {
190
- document.getElementById('answer').textContent += message.content;
191
- }
192
- });
193
- </script>
194
- </body>
195
- </html>
196
- `;
197
-
198
- // Сообщения для чата
199
- const messages = [
200
- { role: 'user', content: question }
201
- ];
202
-
203
- // Опции для чата
204
- const options = {
205
- model: 'claude-3-7-sonnet-20240229',
206
- thinking: true,
207
- temperature: 0.7
208
- };
209
-
210
- // Обработчик событий чата
211
- const handleEvent = (eventType, data) => {
212
- if (eventType === 'thinking_delta' && data.thinking) {
213
- // Обновляем содержимое мышления
214
- panel.webview.postMessage({
215
- command: 'appendThinking',
216
- content: data.thinking
217
- });
218
- } else if (eventType === 'text_delta' && data.text) {
219
- // Обновляем содержимое ответа
220
- panel.webview.postMessage({
221
- command: 'appendAnswer',
222
- content: data.text
223
- });
224
- }
225
- };
226
-
227
- // Отправляем запрос с мышлением
228
- await sdk.chat.streamChatWithThinking(
229
- messages,
230
- options,
231
- handleEvent
232
- );
233
-
234
- } catch (error) {
235
- vscode.window.showErrorMessage(`Ошибка чата: ${error.message}`);
236
- }
237
- })
238
- );
239
- ```
240
-
241
- ## Поиск в коде
242
-
243
- Пример семантического поиска в проекте:
244
-
245
- ```typescript
246
- // Поиск в проекте
247
- async function searchInProject(projectId, query) {
248
- try {
249
- // Показываем индикатор прогресса
250
- return vscode.window.withProgress({
251
- location: vscode.ProgressLocation.Notification,
252
- title: 'Поиск в проекте...',
253
- cancellable: false
254
- }, async (progress) => {
255
- // Выполняем поиск
256
- const results = await sdk.search.semanticSearch(projectId, {
257
- query: query,
258
- limit: 10,
259
- includeContent: true
260
- });
261
-
262
- if (results.results.length === 0) {
263
- vscode.window.showInformationMessage('Результаты не найдены');
264
- return;
265
- }
266
-
267
- // Отображаем результаты
268
- const panel = vscode.window.createWebviewPanel(
269
- 'searchResults',
270
- 'Результаты поиска',
271
- vscode.ViewColumn.Beside,
272
- { enableScripts: true }
273
- );
274
-
275
- // Формируем HTML для отображения результатов
276
- let resultsHtml = '';
277
- results.results.forEach((result, index) => {
278
- resultsHtml += `
279
- <div class="result">
280
- <div class="path" data-path="${result.path}">${result.path}</div>
281
- <div class="snippet">${result.content || 'Содержимое недоступно'}</div>
282
- </div>
283
- `;
284
- });
285
-
286
- panel.webview.html = `
287
- <!DOCTYPE html>
288
- <html>
289
- <head>
290
- <style>
291
- body { font-family: var(--vscode-font-family); padding: 10px; }
292
- .result { margin-bottom: 15px; padding: 10px; border: 1px solid #ccc; }
293
- .path { cursor: pointer; color: var(--vscode-textLink-foreground); }
294
- .snippet { background: var(--vscode-editor-inactiveSelectionBackground); padding: 10px; margin-top: 5px; white-space: pre-wrap; }
295
- </style>
296
- </head>
297
- <body>
298
- <h3>Результаты для: ${query}</h3>
299
- ${resultsHtml}
300
-
301
- <script>
302
- const vscode = acquireVsCodeApi();
303
- document.querySelectorAll('.path').forEach(element => {
304
- element.addEventListener('click', () => {
305
- vscode.postMessage({
306
- command: 'openFile',
307
- path: element.getAttribute('data-path')
308
- });
309
- });
310
- });
311
- </script>
312
- </body>
313
- </html>
314
- `;
315
-
316
- // Обработчик сообщений от WebView
317
- panel.webview.onDidReceiveMessage(message => {
318
- if (message.command === 'openFile') {
319
- const filePath = message.path;
320
- vscode.workspace.openTextDocument(filePath)
321
- .then(doc => vscode.window.showTextDocument(doc));
322
- }
323
- });
324
- });
325
- } catch (error) {
326
- vscode.window.showErrorMessage(`Ошибка поиска: ${error.message}`);
327
- }
328
- }