All files / global/gigachat/tools JsonataTool.ts

97.56% Statements 40/41
97.87% Branches 46/47
75% Functions 3/4
97.14% Lines 34/35

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                                                7x 7x     7x                                 58x   58x   58x 106x 95x 95x 95x 95x 89x 89x                 89x 49x   58x                                     83x 83x   83x                       93x   93x   93x     93x 91x     93x     3x       90x 2x           90x 90x   59x 58x 58x   54x                    
/*
  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 { GigaChatFunctionSchema } from '../types/gigachat.types';
import { ToolInterface } from './types/ToolInterface';
import { ToolTypes } from './types/ToolTypes';
import { ToolConfigType } from './types/ToolConfigType';
import { RequestWithBenefits } from '@back/controllers/gigachat';
import { DocumentConfigType } from './types/DocumentConfigType';
import { getLoggerWithTag } from '@global/logger/v2/logger.mjs';
 
const LOGGER_NAME = 'JSONataTool';
const logger = getLoggerWithTag(LOGGER_NAME);
 
// Передаём модели только готовые сообщения об ошибках, поскольку текст JSONata может содержать значения данных.
const JSONATA_HINTS: Record<string, string> = {
  S0201: 'Лишний символ после выражения. Проверь скобки и разделители.',
  S0202: 'Неожиданный символ. Проверь синтаксис JSONata, скобки и разделители.',
  S0203: 'Выражение не завершено. Проверь закрывающие скобки.',
  S0204: 'Неизвестный оператор. Используй синтаксис JSONata.',
  S0211: 'Оператор недопустим в этой позиции. Срез: [[0..9]], не [:10]; фильтр: [условие], без ?(@...).',
  S0212: 'Слева от := должна быть переменная с префиксом $.',
  S0213: 'Параметры функции должны быть переменными с префиксом $.',
  S0214: 'Справа от @ или # должно быть имя переменной с префиксом $.',
  T1005: 'Вызвано нечто, не являющееся функцией. У функций есть префикс $: $count, $filter.',
  T1006: 'Функция не найдена или значение не является функцией. Проверь имя и префикс $. Условия: or и ? :, не $or(...), if(...) или if/then.',
  T0410: 'Аргумент не соответствует сигнатуре функции. Проверь тип; значения словаря получают через .*.',
  D3120: 'Ошибка синтаксиса внутри $eval. Проверь выражение JSONata. Позиция относится к внешнему $eval.',
  D3121: 'Ошибка выполнения внутри $eval. Проверь функции, типы аргументов и условия: or и ? :, не $or(...), if(...) или if/then. Позиция относится к внешнему $eval.'
};
 
function jsonataDiagnostic(error: unknown) {
  let current = error;
  let last;
  const seen = new Set<object>();
  // Если в пределах глубины поиска вложенный код не найден, сохраняем последний распознанный код обёртки.
  for (let depth = 0; depth < 8; depth++) {
    if (!current || typeof current !== 'object' || seen.has(current)) break;
    seen.add(current);
    const diagnostic = current as Record<string, unknown>;
    const code = diagnostic.code;
    if (typeof code !== 'string' || !/^[STD][0-9]{4}$/.test(code)) break;
    const position = diagnostic.position;
    last = {
      code,
      ...(typeof position === 'number' && Number.isSafeInteger(position) && position >= 0 ? { position } : {}),
      hint: code === 'S0202' && diagnostic.token === ':' && diagnostic.value === ']'
        ? 'Срез JSONata использует включительный диапазон: например, первые пять элементов — [[0..4]], не [0:5]. При исправлении сохрани нужные границы выборки.'
        : JSONATA_HINTS[code] ?? (code.startsWith('S')
        ? 'Ошибка синтаксиса JSONata. Проверь операторы и скобки.'
        : 'Ошибка выполнения JSONata. Проверь типы аргументов и используемые функции.')
    };
    if (code !== 'D3120' && code !== 'D3121') break;
    current = diagnostic.error;
  }
  return last;
}
 
export type JSONataToolCallback = (
  query: string,
  params?: unknown,
  origin?: string | Record<string, string>,
  options?: {
    storage: any,
    roleId: string | undefined
  }
) => Promise<unknown>;
 
export class JsonataTool implements ToolInterface {
  type: ToolTypes.jsonata;
  schema: GigaChatFunctionSchema;
  private callback: JSONataToolCallback;
 
  constructor(callback: JSONataToolCallback) {
    this.type = ToolTypes.jsonata;
    this.callback = callback;
 
    logger.debug(
      () => `JSONata tool registered with type: "${ToolTypes.jsonata}"`
    );
  }
 
  async execute(
    args: any,
    toolConfig: ToolConfigType,
    documentConfig: DocumentConfigType,
    sessionId: string,
    request?: RequestWithBenefits
  ) {
    const { params, origin } = documentConfig;
 
    const isCustomJsonata = toolConfig?.query && toolConfig?.schema;
 
    const jsonataExpression = isCustomJsonata ? toolConfig?.query : args?.query;
 
    let updatedParams;
    if (args && typeof args === 'object') {
      updatedParams = Object.assign({}, params, args);
    }
 
    if (
      !(typeof jsonataExpression === 'string' && jsonataExpression.length > 0)
    ) {
      throw new Error(`Invalid JSONata expression:\n${jsonataExpression}`);
    }
 
    let options;
    if(request && request.storage) {
      options = {
        storage: request.storage,
        roleId: request?.userProfile?.roleId
      };
    }
 
    try {
      return await this.callback(jsonataExpression, updatedParams, origin, options);
    } catch (error) {
      if (documentConfig.diagramWorkflow !== true) throw error;
      const diagnostic = jsonataDiagnostic(error);
      if (!diagnostic) throw error;
      // Возвращаем безопасное описание ошибки, чтобы агент мог исправить запрос без доступа к данным из исходного сообщения.
      return {
        function_call: {
          status: 'error',
          error_message: `Ошибка JSONata ${diagnostic.code}: ${diagnostic.hint}`,
          jsonata: diagnostic
        }
      };
    }
  }
}