All files / global/gigachat/helpers createGigaChatClient.ts

89.79% Statements 88/98
83.78% Branches 31/37
85% Functions 17/20
95.45% Lines 84/88

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186                                        5x             26x 26x   26x 36x 36x   26x 4x 4x   26x 37x 37x 5x 5x 5x   32x     26x   26x 26x   26x       12x 12x   12x 12x 12x 12x   12x 7x 7x     7x 7x 7x   7x       12x   12x 5x 5x 5x   12x 12x     19x 19x 19x 13x 5x 5x 5x   8x                         36x 26x     26x 26x 26x 26x 26x           26x 26x 26x 22x 12x 12x 12x 12x       12x 1x   11x 11x   4x 4x       26x             36x       14x 4x     10x                 235x 235x 235x 18x 18x   235x 235x 23x 23x       235x    
/*
  Copyright (C) 2026 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import {GigaChat, GigaChatClientConfig} from 'gigachat';
import {AuthenticationError, ResponseError} from 'gigachat/exceptions';
import axios, {AxiosInstance} from 'axios-gigachat';
 
const MAX_BROWSER_TIMER_MS = 2_147_483_647;
 
export interface ArchToolGigaChatConfig extends GigaChatClientConfig {
  jetBrainsTransport?: boolean;
}
 
function createRequestDeadline(timeoutMs: number, callerSignal?: AbortSignal) {
  const controller = new AbortController();
  const deadline = performance.now() + timeoutMs;
  let timer: ReturnType<typeof setTimeout>;
  const dispose = () => {
    clearTimeout(timer);
    callerSignal?.removeEventListener('abort', abortFromCaller);
  };
  const abortFromCaller = () => {
    dispose();
    controller.abort(callerSignal.reason);
  };
  const schedule = () => {
    const remaining = deadline - performance.now();
    if (remaining <= 0) {
      dispose();
      controller.abort(Object.assign(new Error(`timeout of ${timeoutMs}ms exceeded`), {code: 'ETIMEDOUT'}));
      return;
    }
    timer = setTimeout(schedule, Math.min(Math.ceil(remaining), MAX_BROWSER_TIMER_MS));
  };
 
  Iif (callerSignal?.aborted) abortFromCaller();
  else {
    callerSignal?.addEventListener('abort', abortFromCaller, {once: true});
    schedule();
  }
  return {signal: controller.signal, abort: (reason?: unknown) => controller.abort(reason), dispose};
}
 
function trackResponseBody(body: ReadableStream<Uint8Array>, deadline: ReturnType<typeof createRequestDeadline>) {
  const reader = body.getReader();
  let closed = false;
  let abort: () => void;
  const close = () => {
    closed = true;
    deadline.dispose();
    deadline.signal.removeEventListener('abort', abort);
  };
  const cancel = async(reason?: unknown) => {
    close();
    try {
      // Axios может уже ждать следующий чанк. Прерываем fetch, чтобы
      // отмена чтения не ждала, пока сервер пришлёт данные.
      const cancellation = reader.cancel(reason);
      deadline.abort(reason);
      await cancellation;
    } finally {
      reader.releaseLock();
    }
  };
 
  return new ReadableStream<Uint8Array>({
    start(controller) {
      abort = () => {
        const reason: unknown = deadline.signal.reason;
        controller.error(reason);
        void cancel(reason).catch(() => undefined);
      };
      Iif (deadline.signal.aborted) abort();
      else deadline.signal.addEventListener('abort', abort, {once: true});
    },
    async pull(controller) {
      try {
        const result = await reader.read();
        if (closed) return;
        if (result.done) {
          close();
          reader.releaseLock();
          controller.close();
        } else {
          controller.enqueue(result.value);
        }
      } catch (error) {
        if (closed) return;
        controller.error(error);
        await cancel(error).catch(() => undefined);
      }
    },
    cancel
  }, {highWaterMark: 0});
}
 
function installLongTimeout(http: AxiosInstance) {
  http.interceptors.request.use(config => {
    const adapter = typeof config.adapter === 'function' ? config.adapter : axios.getAdapter('fetch');
    // Передаём исходную причину отмены через адаптер. Внешняя проверка
    // сигнала в Axios заменила бы её на CanceledError.
    const callerSignal = config.signal as AbortSignal | undefined;
    config.signal = undefined;
    config.adapter = async request => {
      const deadline = createRequestDeadline(request.timeout, callerSignal);
      const transportConfig = {
        ...request,
        timeout: 0,
        signal: deadline.signal
      };
 
      try {
        deadline.signal.throwIfAborted();
        const response = await adapter(transportConfig);
        if (request.responseType === 'stream' && response.data != null) {
          const body = trackResponseBody(response.data, deadline);
          response.data = body;
          const contentType = response.headers['content-type'];
          const invalidStream = response.status === 200 &&
            (typeof contentType !== 'string' || contentType.split(';')[0] !== 'text/event-stream');
          // При 401 SDK может повторить запрос. Остальные HTTP-ошибки
          // возвращают тело вызывающему коду, в том числе сообщение прокси о 504.
          if (response.status !== 401 && !invalidStream) return response;
          await body.cancel().catch(() => undefined);
        }
        deadline.dispose();
        return response;
      } catch (error) {
        deadline.dispose();
        deadline.signal.throwIfAborted();
        throw error;
      }
    };
    return config;
  });
}
 
type SdkResponse = ConstructorParameters<typeof ResponseError>[0];
 
function handleChatResponse(response: SdkResponse): SdkResponse {
  if (response.status === 200) return response;
 
  // Тип AuthenticationError позволяет SDK обновить токен после 401 от модели при автоавторизации.
  // Выбрасываем ошибку до того, как SDK запишет тело ответа в лог. Тело остаётся доступно обработчику чата.
  if (response.status === 401) {
    throw new AuthenticationError(response);
  }
 
  throw new ResponseError(response);
}
 
// При обновлении gigachat сверяйте с SDK внутренние клиенты _client и _authClient
// и пути /chat/completions и /token. Проверьте, что validateStatus по-прежнему
// пропускает ошибочные HTTP-ответы в обработчик успешного выполнения.
// Для длинного таймаута дополнительно проверьте, что OAuth и попытки модели
// проходят через эти клиенты, а поток читает и отменяет тело ответа адаптера.
export function createGigaChatClient(config: ArchToolGigaChatConfig): GigaChat {
  const longTimeout = config.jetBrainsTransport === true && config.timeout * 1000 > MAX_BROWSER_TIMER_MS;
  const client = new GigaChat(config);
  if (longTimeout) {
    installLongTimeout(client._authClient);
    installLongTimeout(client._client);
  }
  client._authClient.interceptors.response.use(handleChatResponse);
  client._client.interceptors.response.use((response) => {
    const url = response.config.url;
    return url === '/chat/completions' || url === '/token'
      ? handleChatResponse(response)
      : response;
  });
  return client;
}