@adpal/shared-lib 1.0.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.
@@ -0,0 +1,776 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Кастомные классы ошибок
5
+ *
6
+ * Иерархия ошибок для структурированной обработки исключений.
7
+ * Каждый класс содержит дополнительный контекст для отладки.
8
+ *
9
+ * @module errors
10
+ */
11
+ /**
12
+ * Базовый класс для всех ошибок приложения
13
+ *
14
+ * Расширяет стандартный Error с дополнительными полями:
15
+ * - code: машиночитаемый код ошибки
16
+ * - context: дополнительные данные для отладки
17
+ * - retryable: можно ли повторить операцию
18
+ */
19
+ declare class AppError extends Error {
20
+ /** Машиночитаемый код ошибки */
21
+ readonly code: string;
22
+ /** Дополнительный контекст для отладки */
23
+ readonly context?: Record<string, unknown>;
24
+ /** Можно ли повторить операцию */
25
+ readonly retryable: boolean;
26
+ /** Временная метка создания ошибки */
27
+ readonly timestamp: Date;
28
+ constructor(message: string, options?: {
29
+ code?: string;
30
+ context?: Record<string, unknown>;
31
+ retryable?: boolean;
32
+ cause?: Error;
33
+ });
34
+ /**
35
+ * Преобразовать в JSON для логирования
36
+ */
37
+ toJSON(): Record<string, unknown>;
38
+ }
39
+ /**
40
+ * Ошибка при вызове внешнего API
41
+ *
42
+ * Используется для Voyage AI, Anthropic, Turbopuffer.
43
+ */
44
+ declare class ApiError extends AppError {
45
+ /** HTTP статус код */
46
+ readonly statusCode: number;
47
+ /** Имя сервиса */
48
+ readonly service: string;
49
+ constructor(message: string, options: {
50
+ statusCode: number;
51
+ service: string;
52
+ context?: Record<string, unknown>;
53
+ retryable?: boolean;
54
+ cause?: Error;
55
+ });
56
+ }
57
+ /**
58
+ * Ошибка Voyage AI API
59
+ */
60
+ declare class VoyageApiError extends ApiError {
61
+ constructor(message: string, statusCode: number, context?: Record<string, unknown>);
62
+ }
63
+ /**
64
+ * Ошибка Anthropic API
65
+ */
66
+ declare class AnthropicApiError extends ApiError {
67
+ constructor(message: string, statusCode: number, context?: Record<string, unknown>);
68
+ }
69
+ /**
70
+ * Ошибка Turbopuffer API
71
+ */
72
+ declare class TurbopufferApiError extends ApiError {
73
+ constructor(message: string, statusCode: number, context?: Record<string, unknown>);
74
+ }
75
+ /**
76
+ * Ошибка валидации данных
77
+ *
78
+ * Используется при невалидных входных данных или ответах API.
79
+ */
80
+ declare class ValidationError extends AppError {
81
+ /** Поле, в котором обнаружена ошибка */
82
+ readonly field?: string;
83
+ /** Ожидаемое значение или тип */
84
+ readonly expected?: string;
85
+ /** Полученное значение */
86
+ readonly received?: unknown;
87
+ constructor(message: string, options?: {
88
+ field?: string;
89
+ expected?: string;
90
+ received?: unknown;
91
+ context?: Record<string, unknown>;
92
+ });
93
+ }
94
+ /**
95
+ * Ошибка отсутствующей конфигурации
96
+ *
97
+ * Используется при отсутствии обязательных переменных окружения.
98
+ */
99
+ declare class ConfigError extends AppError {
100
+ /** Имя отсутствующей переменной */
101
+ readonly variableName: string;
102
+ constructor(variableName: string);
103
+ }
104
+ /**
105
+ * Проверить, является ли ошибка экземпляром AppError
106
+ */
107
+ declare function isAppError(error: unknown): error is AppError;
108
+ /**
109
+ * Обернуть неизвестную ошибку в AppError
110
+ */
111
+ declare function wrapError(error: unknown, defaultMessage?: string): AppError;
112
+
113
+ /**
114
+ * Структурированное логирование
115
+ *
116
+ * Централизованный логгер с уровнями и форматированием.
117
+ * В продакшене выводит JSON для парсинга CloudWatch/Datadog.
118
+ * В dev режиме — читаемый формат с цветами.
119
+ *
120
+ * @module logger
121
+ */
122
+ /** Уровни логирования */
123
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
124
+ /** Метаданные для структурированного логирования */
125
+ interface LogMeta {
126
+ /** Имя модуля/компонента */
127
+ module?: string;
128
+ /** ID операции для трейсинга */
129
+ operationId?: string;
130
+ /** ID пользователя */
131
+ userId?: string;
132
+ /** Длительность операции в мс */
133
+ durationMs?: number;
134
+ /** Дополнительные поля */
135
+ [key: string]: unknown;
136
+ }
137
+ /**
138
+ * Класс логгера
139
+ *
140
+ * Создаёт экземпляр с привязкой к модулю.
141
+ *
142
+ * @example
143
+ * const log = new Logger('voyage');
144
+ * log.info('Запрос отправлен', { tokens: 1500 });
145
+ * log.error('Ошибка API', new Error('timeout'));
146
+ */
147
+ declare class Logger {
148
+ private readonly module;
149
+ private readonly minLevel;
150
+ constructor(module: string);
151
+ /**
152
+ * Проверить, включён ли данный уровень
153
+ */
154
+ private isEnabled;
155
+ /**
156
+ * Записать лог
157
+ */
158
+ private log;
159
+ /**
160
+ * Debug уровень — детальная информация для отладки
161
+ */
162
+ debug(message: string, meta?: LogMeta): void;
163
+ /**
164
+ * Info уровень — информационные сообщения
165
+ */
166
+ info(message: string, meta?: LogMeta): void;
167
+ /**
168
+ * Warn уровень — предупреждения
169
+ */
170
+ warn(message: string, meta?: LogMeta): void;
171
+ /**
172
+ * Error уровень — ошибки
173
+ */
174
+ error(message: string, error?: Error | unknown, meta?: LogMeta): void;
175
+ /**
176
+ * Создать child logger с дополнительным контекстом
177
+ */
178
+ child(context: LogMeta): ChildLogger;
179
+ }
180
+ /**
181
+ * Child logger с привязанным контекстом
182
+ */
183
+ declare class ChildLogger {
184
+ private readonly parent;
185
+ private readonly context;
186
+ constructor(parent: Logger, context: LogMeta);
187
+ debug(message: string, meta?: LogMeta): void;
188
+ info(message: string, meta?: LogMeta): void;
189
+ warn(message: string, meta?: LogMeta): void;
190
+ error(message: string, error?: Error | unknown, meta?: LogMeta): void;
191
+ }
192
+ /** Логгер для Voyage AI */
193
+ declare const voyageLogger: Logger;
194
+ /** Логгер для Turbopuffer */
195
+ declare const turbopufferLogger: Logger;
196
+ /** Логгер для Anthropic */
197
+ declare const anthropicLogger: Logger;
198
+ /** Логгер для API запросов */
199
+ declare const apiLogger: Logger;
200
+ /** Логгер общего назначения */
201
+ declare const logger: Logger;
202
+ /**
203
+ * Создать таймер для измерения длительности операции
204
+ *
205
+ * @example
206
+ * const timer = createTimer();
207
+ * await doSomething();
208
+ * log.info('Операция завершена', { durationMs: timer() });
209
+ */
210
+ declare function createTimer(): () => number;
211
+
212
+ /**
213
+ * Retry логика с exponential backoff
214
+ *
215
+ * Утилиты для повторения неудачных операций с экспоненциальной
216
+ * задержкой и джиттером для предотвращения thundering herd.
217
+ *
218
+ * @module retry
219
+ */
220
+
221
+ /**
222
+ * Опции для retry
223
+ */
224
+ interface RetryOptions {
225
+ /** Максимальное количество попыток (включая первую) */
226
+ maxAttempts?: number;
227
+ /** Базовая задержка в мс (удваивается с каждой попыткой) */
228
+ baseDelayMs?: number;
229
+ /** Максимальная задержка в мс */
230
+ maxDelayMs?: number;
231
+ /** Добавлять случайный джиттер (0-1, доля от задержки) */
232
+ jitter?: number;
233
+ /** Функция для определения, нужно ли повторять */
234
+ shouldRetry?: (error: unknown, attempt: number) => boolean;
235
+ /** Callback при каждой неудачной попытке */
236
+ onRetry?: (error: unknown, attempt: number, delayMs: number) => void;
237
+ /** Логгер для записи попыток */
238
+ logger?: Logger;
239
+ }
240
+ /**
241
+ * Результат выполнения с retry
242
+ */
243
+ interface RetryResult<T> {
244
+ /** Результат успешного выполнения */
245
+ data: T;
246
+ /** Количество попыток (1 = успех с первого раза) */
247
+ attempts: number;
248
+ /** Общее время выполнения в мс */
249
+ totalTimeMs: number;
250
+ }
251
+ /**
252
+ * Ожидать указанное количество миллисекунд
253
+ */
254
+ declare function sleep(ms: number): Promise<void>;
255
+ /**
256
+ * Выполнить функцию с retry и exponential backoff
257
+ *
258
+ * @param fn - Асинхронная функция для выполнения
259
+ * @param options - Опции retry
260
+ * @returns Результат выполнения с метаданными
261
+ * @throws Последняя ошибка, если все попытки исчерпаны
262
+ *
263
+ * @example
264
+ * const result = await withRetry(
265
+ * () => fetch('https://api.example.com/data'),
266
+ * { maxAttempts: 3, baseDelayMs: 1000 }
267
+ * );
268
+ * console.log(`Успех за ${result.attempts} попыток`);
269
+ */
270
+ declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<RetryResult<T>>;
271
+ /**
272
+ * Retry для API запросов с предустановленными параметрами
273
+ *
274
+ * Оптимизировано для внешних API (Voyage, Anthropic, Turbopuffer).
275
+ *
276
+ * @example
277
+ * const response = await retryApiCall(
278
+ * () => fetch(VOYAGE_API_URL, { method: 'POST', body }),
279
+ * { logger: voyageLogger }
280
+ * );
281
+ */
282
+ declare function retryApiCall<T>(fn: () => Promise<T>, options?: Pick<RetryOptions, 'logger' | 'onRetry' | 'maxAttempts'>): Promise<T>;
283
+ /**
284
+ * Retry для критичных операций с более агрессивными параметрами
285
+ *
286
+ * Используется для операций, которые обязательно должны выполниться.
287
+ *
288
+ * @example
289
+ * await retryCritical(
290
+ * () => saveToDatabase(data),
291
+ * { logger }
292
+ * );
293
+ */
294
+ declare function retryCritical<T>(fn: () => Promise<T>, options?: Pick<RetryOptions, 'logger' | 'onRetry'>): Promise<T>;
295
+
296
+ /**
297
+ * Zod схемы для валидации API ответов
298
+ *
299
+ * Типобезопасная валидация ответов от внешних API.
300
+ * Гарантирует соответствие данных ожидаемой структуре.
301
+ *
302
+ * @module schemas
303
+ */
304
+
305
+ /**
306
+ * Схема ответа Voyage Embeddings API
307
+ *
308
+ * @see https://docs.voyageai.com/docs/embeddings
309
+ */
310
+ declare const VoyageEmbeddingResponseSchema: z.ZodObject<{
311
+ /** Массив эмбеддингов */
312
+ data: z.ZodArray<z.ZodObject<{
313
+ /** Вектор эмбеддинга */
314
+ embedding: z.ZodArray<z.ZodNumber, "many">;
315
+ /** Индекс в исходном массиве */
316
+ index: z.ZodOptional<z.ZodNumber>;
317
+ }, "strip", z.ZodTypeAny, {
318
+ embedding: number[];
319
+ index?: number | undefined;
320
+ }, {
321
+ embedding: number[];
322
+ index?: number | undefined;
323
+ }>, "many">;
324
+ /** Статистика использования */
325
+ usage: z.ZodObject<{
326
+ /** Общее количество токенов */
327
+ total_tokens: z.ZodNumber;
328
+ }, "strip", z.ZodTypeAny, {
329
+ total_tokens: number;
330
+ }, {
331
+ total_tokens: number;
332
+ }>;
333
+ /** Модель, использованная для генерации */
334
+ model: z.ZodOptional<z.ZodString>;
335
+ }, "strip", z.ZodTypeAny, {
336
+ data: {
337
+ embedding: number[];
338
+ index?: number | undefined;
339
+ }[];
340
+ usage: {
341
+ total_tokens: number;
342
+ };
343
+ model?: string | undefined;
344
+ }, {
345
+ data: {
346
+ embedding: number[];
347
+ index?: number | undefined;
348
+ }[];
349
+ usage: {
350
+ total_tokens: number;
351
+ };
352
+ model?: string | undefined;
353
+ }>;
354
+ type VoyageEmbeddingResponse = z.infer<typeof VoyageEmbeddingResponseSchema>;
355
+ /**
356
+ * Схема ответа Voyage Rerank API
357
+ *
358
+ * @see https://docs.voyageai.com/docs/reranker
359
+ */
360
+ declare const VoyageRerankResponseSchema: z.ZodObject<{
361
+ /** Массив результатов реранкинга */
362
+ data: z.ZodArray<z.ZodObject<{
363
+ /** Индекс документа в исходном массиве */
364
+ index: z.ZodNumber;
365
+ /** Оценка релевантности (0-1) */
366
+ relevance_score: z.ZodNumber;
367
+ }, "strip", z.ZodTypeAny, {
368
+ index: number;
369
+ relevance_score: number;
370
+ }, {
371
+ index: number;
372
+ relevance_score: number;
373
+ }>, "many">;
374
+ /** Статистика использования */
375
+ usage: z.ZodObject<{
376
+ /** Общее количество токенов */
377
+ total_tokens: z.ZodNumber;
378
+ }, "strip", z.ZodTypeAny, {
379
+ total_tokens: number;
380
+ }, {
381
+ total_tokens: number;
382
+ }>;
383
+ /** Модель, использованная для реранкинга */
384
+ model: z.ZodOptional<z.ZodString>;
385
+ }, "strip", z.ZodTypeAny, {
386
+ data: {
387
+ index: number;
388
+ relevance_score: number;
389
+ }[];
390
+ usage: {
391
+ total_tokens: number;
392
+ };
393
+ model?: string | undefined;
394
+ }, {
395
+ data: {
396
+ index: number;
397
+ relevance_score: number;
398
+ }[];
399
+ usage: {
400
+ total_tokens: number;
401
+ };
402
+ model?: string | undefined;
403
+ }>;
404
+ type VoyageRerankResponse = z.infer<typeof VoyageRerankResponseSchema>;
405
+ /**
406
+ * Базовая схема атрибутов вектора
407
+ */
408
+ declare const VectorAttributesSchema: z.ZodObject<{
409
+ /** ID записи в Supabase */
410
+ supabase_id: z.ZodNumber;
411
+ /** Уникальный ID сообщения/документа */
412
+ message_id: z.ZodString;
413
+ /** Тип источника */
414
+ source_type: z.ZodEnum<["email", "pdf", "website"]>;
415
+ /** Тип чанка */
416
+ chunk_type: z.ZodString;
417
+ /** Email отправителя */
418
+ sender: z.ZodOptional<z.ZodString>;
419
+ /** Email получателя */
420
+ recipient: z.ZodOptional<z.ZodString>;
421
+ /** Дата источника */
422
+ source_date: z.ZodOptional<z.ZodString>;
423
+ /** ID цепочки писем */
424
+ thread_id: z.ZodOptional<z.ZodString>;
425
+ /** ID клиента */
426
+ client_id: z.ZodOptional<z.ZodString>;
427
+ /** URL источника */
428
+ source_url: z.ZodOptional<z.ZodString>;
429
+ /** Номер страницы */
430
+ page_number: z.ZodOptional<z.ZodNumber>;
431
+ /** Заголовок секции */
432
+ section_title: z.ZodOptional<z.ZodString>;
433
+ /** ID в content_sources */
434
+ content_source_id: z.ZodOptional<z.ZodNumber>;
435
+ /** Тема письма */
436
+ subject: z.ZodOptional<z.ZodString>;
437
+ /** Превью контента */
438
+ content_preview: z.ZodOptional<z.ZodString>;
439
+ /** Заголовок документа */
440
+ title: z.ZodOptional<z.ZodString>;
441
+ /** Полный контент */
442
+ content: z.ZodOptional<z.ZodString>;
443
+ /** Категория */
444
+ category: z.ZodOptional<z.ZodString>;
445
+ /** Тональность */
446
+ sentiment: z.ZodOptional<z.ZodEnum<["positive", "negative", "neutral"]>>;
447
+ /** Дата создания */
448
+ created_at: z.ZodOptional<z.ZodString>;
449
+ }, "strip", z.ZodTypeAny, {
450
+ supabase_id: number;
451
+ message_id: string;
452
+ source_type: "email" | "pdf" | "website";
453
+ chunk_type: string;
454
+ sender?: string | undefined;
455
+ recipient?: string | undefined;
456
+ source_date?: string | undefined;
457
+ thread_id?: string | undefined;
458
+ client_id?: string | undefined;
459
+ source_url?: string | undefined;
460
+ page_number?: number | undefined;
461
+ section_title?: string | undefined;
462
+ content_source_id?: number | undefined;
463
+ subject?: string | undefined;
464
+ content_preview?: string | undefined;
465
+ title?: string | undefined;
466
+ content?: string | undefined;
467
+ category?: string | undefined;
468
+ sentiment?: "positive" | "negative" | "neutral" | undefined;
469
+ created_at?: string | undefined;
470
+ }, {
471
+ supabase_id: number;
472
+ message_id: string;
473
+ source_type: "email" | "pdf" | "website";
474
+ chunk_type: string;
475
+ sender?: string | undefined;
476
+ recipient?: string | undefined;
477
+ source_date?: string | undefined;
478
+ thread_id?: string | undefined;
479
+ client_id?: string | undefined;
480
+ source_url?: string | undefined;
481
+ page_number?: number | undefined;
482
+ section_title?: string | undefined;
483
+ content_source_id?: number | undefined;
484
+ subject?: string | undefined;
485
+ content_preview?: string | undefined;
486
+ title?: string | undefined;
487
+ content?: string | undefined;
488
+ category?: string | undefined;
489
+ sentiment?: "positive" | "negative" | "neutral" | undefined;
490
+ created_at?: string | undefined;
491
+ }>;
492
+ type VectorAttributes = z.infer<typeof VectorAttributesSchema>;
493
+ /**
494
+ * Схема результата поиска Turbopuffer
495
+ */
496
+ declare const TurbopufferSearchResultSchema: z.ZodObject<{
497
+ /** ID вектора */
498
+ id: z.ZodString;
499
+ /** Расстояние до запроса */
500
+ dist: z.ZodNumber;
501
+ /** Атрибуты вектора */
502
+ attributes: z.ZodObject<{
503
+ supabase_id: z.ZodOptional<z.ZodNumber>;
504
+ message_id: z.ZodOptional<z.ZodString>;
505
+ source_type: z.ZodOptional<z.ZodEnum<["email", "pdf", "website"]>>;
506
+ chunk_type: z.ZodOptional<z.ZodString>;
507
+ sender: z.ZodOptional<z.ZodOptional<z.ZodString>>;
508
+ recipient: z.ZodOptional<z.ZodOptional<z.ZodString>>;
509
+ source_date: z.ZodOptional<z.ZodOptional<z.ZodString>>;
510
+ thread_id: z.ZodOptional<z.ZodOptional<z.ZodString>>;
511
+ client_id: z.ZodOptional<z.ZodOptional<z.ZodString>>;
512
+ source_url: z.ZodOptional<z.ZodOptional<z.ZodString>>;
513
+ page_number: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
514
+ section_title: z.ZodOptional<z.ZodOptional<z.ZodString>>;
515
+ content_source_id: z.ZodOptional<z.ZodOptional<z.ZodNumber>>;
516
+ subject: z.ZodOptional<z.ZodOptional<z.ZodString>>;
517
+ content_preview: z.ZodOptional<z.ZodOptional<z.ZodString>>;
518
+ title: z.ZodOptional<z.ZodOptional<z.ZodString>>;
519
+ content: z.ZodOptional<z.ZodOptional<z.ZodString>>;
520
+ category: z.ZodOptional<z.ZodOptional<z.ZodString>>;
521
+ sentiment: z.ZodOptional<z.ZodOptional<z.ZodEnum<["positive", "negative", "neutral"]>>>;
522
+ created_at: z.ZodOptional<z.ZodOptional<z.ZodString>>;
523
+ }, "strip", z.ZodTypeAny, {
524
+ supabase_id?: number | undefined;
525
+ message_id?: string | undefined;
526
+ source_type?: "email" | "pdf" | "website" | undefined;
527
+ chunk_type?: string | undefined;
528
+ sender?: string | undefined;
529
+ recipient?: string | undefined;
530
+ source_date?: string | undefined;
531
+ thread_id?: string | undefined;
532
+ client_id?: string | undefined;
533
+ source_url?: string | undefined;
534
+ page_number?: number | undefined;
535
+ section_title?: string | undefined;
536
+ content_source_id?: number | undefined;
537
+ subject?: string | undefined;
538
+ content_preview?: string | undefined;
539
+ title?: string | undefined;
540
+ content?: string | undefined;
541
+ category?: string | undefined;
542
+ sentiment?: "positive" | "negative" | "neutral" | undefined;
543
+ created_at?: string | undefined;
544
+ }, {
545
+ supabase_id?: number | undefined;
546
+ message_id?: string | undefined;
547
+ source_type?: "email" | "pdf" | "website" | undefined;
548
+ chunk_type?: string | undefined;
549
+ sender?: string | undefined;
550
+ recipient?: string | undefined;
551
+ source_date?: string | undefined;
552
+ thread_id?: string | undefined;
553
+ client_id?: string | undefined;
554
+ source_url?: string | undefined;
555
+ page_number?: number | undefined;
556
+ section_title?: string | undefined;
557
+ content_source_id?: number | undefined;
558
+ subject?: string | undefined;
559
+ content_preview?: string | undefined;
560
+ title?: string | undefined;
561
+ content?: string | undefined;
562
+ category?: string | undefined;
563
+ sentiment?: "positive" | "negative" | "neutral" | undefined;
564
+ created_at?: string | undefined;
565
+ }>;
566
+ }, "strip", z.ZodTypeAny, {
567
+ id: string;
568
+ dist: number;
569
+ attributes: {
570
+ supabase_id?: number | undefined;
571
+ message_id?: string | undefined;
572
+ source_type?: "email" | "pdf" | "website" | undefined;
573
+ chunk_type?: string | undefined;
574
+ sender?: string | undefined;
575
+ recipient?: string | undefined;
576
+ source_date?: string | undefined;
577
+ thread_id?: string | undefined;
578
+ client_id?: string | undefined;
579
+ source_url?: string | undefined;
580
+ page_number?: number | undefined;
581
+ section_title?: string | undefined;
582
+ content_source_id?: number | undefined;
583
+ subject?: string | undefined;
584
+ content_preview?: string | undefined;
585
+ title?: string | undefined;
586
+ content?: string | undefined;
587
+ category?: string | undefined;
588
+ sentiment?: "positive" | "negative" | "neutral" | undefined;
589
+ created_at?: string | undefined;
590
+ };
591
+ }, {
592
+ id: string;
593
+ dist: number;
594
+ attributes: {
595
+ supabase_id?: number | undefined;
596
+ message_id?: string | undefined;
597
+ source_type?: "email" | "pdf" | "website" | undefined;
598
+ chunk_type?: string | undefined;
599
+ sender?: string | undefined;
600
+ recipient?: string | undefined;
601
+ source_date?: string | undefined;
602
+ thread_id?: string | undefined;
603
+ client_id?: string | undefined;
604
+ source_url?: string | undefined;
605
+ page_number?: number | undefined;
606
+ section_title?: string | undefined;
607
+ content_source_id?: number | undefined;
608
+ subject?: string | undefined;
609
+ content_preview?: string | undefined;
610
+ title?: string | undefined;
611
+ content?: string | undefined;
612
+ category?: string | undefined;
613
+ sentiment?: "positive" | "negative" | "neutral" | undefined;
614
+ created_at?: string | undefined;
615
+ };
616
+ }>;
617
+ type TurbopufferSearchResult = z.infer<typeof TurbopufferSearchResultSchema>;
618
+ /**
619
+ * Схема сообщения в ответе Claude
620
+ */
621
+ declare const ClaudeMessageSchema: z.ZodObject<{
622
+ /** ID сообщения */
623
+ id: z.ZodString;
624
+ /** Тип объекта */
625
+ type: z.ZodLiteral<"message">;
626
+ /** Роль */
627
+ role: z.ZodEnum<["assistant", "user"]>;
628
+ /** Контент */
629
+ content: z.ZodArray<z.ZodObject<{
630
+ type: z.ZodEnum<["text", "tool_use"]>;
631
+ text: z.ZodOptional<z.ZodString>;
632
+ }, "strip", z.ZodTypeAny, {
633
+ type: "text" | "tool_use";
634
+ text?: string | undefined;
635
+ }, {
636
+ type: "text" | "tool_use";
637
+ text?: string | undefined;
638
+ }>, "many">;
639
+ /** Модель */
640
+ model: z.ZodString;
641
+ /** Причина остановки */
642
+ stop_reason: z.ZodNullable<z.ZodEnum<["end_turn", "max_tokens", "stop_sequence", "tool_use"]>>;
643
+ /** Использование токенов */
644
+ usage: z.ZodObject<{
645
+ input_tokens: z.ZodNumber;
646
+ output_tokens: z.ZodNumber;
647
+ }, "strip", z.ZodTypeAny, {
648
+ input_tokens: number;
649
+ output_tokens: number;
650
+ }, {
651
+ input_tokens: number;
652
+ output_tokens: number;
653
+ }>;
654
+ }, "strip", z.ZodTypeAny, {
655
+ type: "message";
656
+ usage: {
657
+ input_tokens: number;
658
+ output_tokens: number;
659
+ };
660
+ model: string;
661
+ content: {
662
+ type: "text" | "tool_use";
663
+ text?: string | undefined;
664
+ }[];
665
+ id: string;
666
+ role: "assistant" | "user";
667
+ stop_reason: "tool_use" | "end_turn" | "max_tokens" | "stop_sequence" | null;
668
+ }, {
669
+ type: "message";
670
+ usage: {
671
+ input_tokens: number;
672
+ output_tokens: number;
673
+ };
674
+ model: string;
675
+ content: {
676
+ type: "text" | "tool_use";
677
+ text?: string | undefined;
678
+ }[];
679
+ id: string;
680
+ role: "assistant" | "user";
681
+ stop_reason: "tool_use" | "end_turn" | "max_tokens" | "stop_sequence" | null;
682
+ }>;
683
+ type ClaudeMessage = z.infer<typeof ClaudeMessageSchema>;
684
+ /**
685
+ * Схема входящего запроса к Chat API
686
+ */
687
+ declare const ChatRequestSchema: z.ZodObject<{
688
+ /** Сообщение пользователя */
689
+ message: z.ZodString;
690
+ /** История сообщений */
691
+ history: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodObject<{
692
+ role: z.ZodEnum<["user", "assistant"]>;
693
+ content: z.ZodString;
694
+ }, "strip", z.ZodTypeAny, {
695
+ content: string;
696
+ role: "assistant" | "user";
697
+ }, {
698
+ content: string;
699
+ role: "assistant" | "user";
700
+ }>, "many">>>;
701
+ /** ID сессии */
702
+ sessionId: z.ZodOptional<z.ZodString>;
703
+ /** Режим (customer/internal) */
704
+ mode: z.ZodDefault<z.ZodOptional<z.ZodEnum<["customer", "internal"]>>>;
705
+ }, "strip", z.ZodTypeAny, {
706
+ message: string;
707
+ history: {
708
+ content: string;
709
+ role: "assistant" | "user";
710
+ }[];
711
+ mode: "customer" | "internal";
712
+ sessionId?: string | undefined;
713
+ }, {
714
+ message: string;
715
+ history?: {
716
+ content: string;
717
+ role: "assistant" | "user";
718
+ }[] | undefined;
719
+ sessionId?: string | undefined;
720
+ mode?: "customer" | "internal" | undefined;
721
+ }>;
722
+ type ChatRequest = z.infer<typeof ChatRequestSchema>;
723
+ /**
724
+ * Схема источника в ответе
725
+ */
726
+ declare const SourceSchema: z.ZodObject<{
727
+ /** Тип источника */
728
+ type: z.ZodEnum<["email", "pdf", "website"]>;
729
+ /** Заголовок */
730
+ title: z.ZodString;
731
+ /** URL или идентификатор */
732
+ url: z.ZodOptional<z.ZodString>;
733
+ /** Превью контента */
734
+ preview: z.ZodOptional<z.ZodString>;
735
+ /** Оценка релевантности */
736
+ relevance: z.ZodOptional<z.ZodNumber>;
737
+ }, "strip", z.ZodTypeAny, {
738
+ type: "email" | "pdf" | "website";
739
+ title: string;
740
+ url?: string | undefined;
741
+ preview?: string | undefined;
742
+ relevance?: number | undefined;
743
+ }, {
744
+ type: "email" | "pdf" | "website";
745
+ title: string;
746
+ url?: string | undefined;
747
+ preview?: string | undefined;
748
+ relevance?: number | undefined;
749
+ }>;
750
+ type Source = z.infer<typeof SourceSchema>;
751
+ /**
752
+ * Безопасно распарсить данные по схеме
753
+ *
754
+ * @param schema - Zod схема
755
+ * @param data - Данные для валидации
756
+ * @returns Результат парсинга или null при ошибке
757
+ *
758
+ * @example
759
+ * const response = await fetch(url);
760
+ * const data = await response.json();
761
+ * const parsed = safeParse(VoyageEmbeddingResponseSchema, data);
762
+ * if (!parsed) throw new ValidationError('Invalid API response');
763
+ */
764
+ declare function safeParse<T>(schema: z.ZodType<T>, data: unknown): T | null;
765
+ /**
766
+ * Распарсить данные по схеме с выбросом ошибки
767
+ *
768
+ * @param schema - Zod схема
769
+ * @param data - Данные для валидации
770
+ * @param errorMessage - Сообщение об ошибке
771
+ * @returns Валидные данные
772
+ * @throws Error при невалидных данных
773
+ */
774
+ declare function parseOrThrow<T>(schema: z.ZodType<T>, data: unknown, errorMessage?: string): T;
775
+
776
+ export { AnthropicApiError, ApiError, AppError, type ChatRequest, ChatRequestSchema, type ClaudeMessage, ClaudeMessageSchema, ConfigError, type LogLevel, type LogMeta, Logger, type RetryOptions, type RetryResult, type Source, SourceSchema, TurbopufferApiError, type TurbopufferSearchResult, TurbopufferSearchResultSchema, ValidationError, type VectorAttributes, VectorAttributesSchema, VoyageApiError, type VoyageEmbeddingResponse, VoyageEmbeddingResponseSchema, type VoyageRerankResponse, VoyageRerankResponseSchema, anthropicLogger, apiLogger, createTimer, isAppError, logger, parseOrThrow, retryApiCall, retryCritical, safeParse, sleep, turbopufferLogger, voyageLogger, withRetry, wrapError };