1

Тема: AHK v2: Клиент Google Translate

Это тема для вопросов и комментариев по скрипту из Коллекции Клиент Google Translate

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

2

Re: AHK v2: Клиент Google Translate

Большое спасибо, очень нужная вещь!

This chapter won’t be able to
tell you how to build a model to compete with ChatGPT

переводится так:
Эта глава не сможет
Я расскажу вам, как создать модель, способную конкурировать с ChatGPT.

Google переводчик переводит иначе ))

3

Re: AHK v2: Клиент Google Translate

Да, не любит переносы строк посреди предложения. Подумаю, как исправить.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

4

Re: AHK v2: Клиент Google Translate

Исправлено.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

5

Re: AHK v2: Клиент Google Translate

Отлично. Как вам можно задонатить?

6

Re: AHK v2: Клиент Google Translate

Мне можно на сбер или криптой.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

7

Re: AHK v2: Клиент Google Translate

Спасибо за донат!

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

8

Re: AHK v2: Клиент Google Translate

В новой версии исправлены баги, добавлена возможность сохранять размер и соотношение полей окна переводчика.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

9

Re: AHK v2: Клиент Google Translate

Версия 1.2.1

Новое:

  • Транскрипция (Options → Show Romanization, по умолчанию выключено). Для текста, написанного не латиницей, под полем показывается его латинская транскрипция: пиньинь, ромадзи, транслитерация кириллицы. Полоса набрана шрифтом того же размера, что и поле; длинная транскрипция прокручивается, полностью она видна при наведении указателя.

  • Переключение раскладки (Options → Switch Keyboard Layout, по умолчанию включено). При переходе в текстовое поле раскладка клавиатуры переключается на язык этого поля, если такая раскладка установлена, а в списках языков — на родной язык. Если в Windows одна раскладка для всех окон, при уходе из окна переводчика возвращается прежняя.

  • Ctrl+Tab в окне переводчика меняет местами исходный и целевой языки. Если исходный язык определяется автоматически, появится подсказка, что менять нечего.

  • Переключаемые настройки собраны в подменю Options меню в трее; Windowless Mode остался в самом меню.

  • При первом запуске программа всегда предлагает подтвердить пару языков; родным предлагается язык интерфейса Windows.

Исправления:

  • При масштабе экрана больше 100% кнопка смены языков совпадает по высоте со списком языков, а подписи стоят на одном уровне с текстом списка.

  • Окно меньше мигает при изменении размера и перетаскивании границы между полями и не мигает при отпускании мыши.

При первом запуске после обновления программа один раз переводит новые тексты интерфейса, поэтому ненадолго может появиться окно загрузки.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

10

Re: AHK v2: Клиент Google Translate

Привет!

Google Translate
Failed to fetch the language list:
HTTP 429 Too Many Requests
Check the internet connection. If you use a VPN or a proxy, try turning it off or excluding this program from it.

Это происходит, когда  сервер tribukvy.ltd, на других - нормально.

11

Re: AHK v2: Клиент Google Translate

Это ограничение со стороны Google. Ответ 429 значит, что Google ограничил запросы с IP-адреса этого VPN-сервера. Через публичные VPN-серверы ходит много пользователей и ботов, и Google иногда принимает такой трафик за автоматический.

Можно один раз запустить скрипт через другой сервер или без VPN. Список языков сохранится в langlist.json рядом со скриптом, и при запуске он больше запрашиваться не будет. Можно также просто скопировать этот файл с другого компьютера. Если перевод на этом сервере тоже не работает, добавьте скрипт в исключения VPN или выберите другой сервер.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

12

Re: AHK v2: Клиент Google Translate

Непонятно, почему на одном и том же VPN-сервере, в одно и тоже время 429 получается во время загрузки языков (всегда), но не во время перевода (никогда).

13

Re: AHK v2: Клиент Google Translate

Список языков и перевод запрашиваются с разных сервисов. Список берётся со старого общедоступного адреса без ключа. Вероятно, им пользуются все, кому не лень, поэтому есть ограничение.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

14

Re: AHK v2: Клиент Google Translate

teadrinker, а почему не такой код:

    static OnCopyPress() {
        if (A_PriorHotkey = "~^c" && A_TimeSincePriorHotkey < 400)
            this.Translate(A_Clipboard)
    }

15

Re: AHK v2: Клиент Google Translate

Честно говоря, уже не помню, первый вариант скрипта был написан давно. А разве сейчас неправильно работает? Ваш вариант может дать нежелательное поведение, например, если нажать С три раза, будет инициирован ещё один перевод.
В большом приложении всегда найдутся места, которые можно было бы записать оптимальнее, можно бесконечно улучшать.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

16

Re: AHK v2: Клиент Google Translate

Я как раз имел в виду, нет ли тут какого нежелательного поведения. Я же учусь по вашим образцам. Третий перевод можно отсечь использованием  счётчика.

17

Re: AHK v2: Клиент Google Translate

Ну, ещё если в таком варианте нажать Ctrl + C и удерживать C чуть дольше, будет инициирован перевод, так как клавиатура при удержании посылает автоповтор.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

18

Re: AHK v2: Клиент Google Translate

Точно, значит,

; Keyboard auto-repeat of a held Ctrl+C produces presses without releases, so
; a double press is only counted when C was released in between.
~*c up:: GoogleTranslator.RegisterCopyRelease()

по-любому остаётся.

19

Re: AHK v2: Клиент Google Translate

a header there that is not a record is taken for the lap end as well.

Ваш перевод:

Удар головой, не являющийся рекордом, также учитывается в конце круга.

Перевод Google:

Заголовок, который не является записью, также принимается за признак окончания круга.

20

Re: AHK v2: Клиент Google Translate

https://i.ibb.co/zYCrbwn/16f01bc5da4a.png

У вас, вероятно, стоит расширенная модель, которая использует Gemini, API в скрипте не может использовать этот вариант.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

21

Re: AHK v2: Клиент Google Translate

Не совсем понял. Переводчик обычный, https://translate.google.com. А Gemini в моём регионе недоступна.

22

Re: AHK v2: Клиент Google Translate

У меня на скриншоте тоже обычный. Или у вас какой-то другой? Смотрите что написано внизу справа в поле исходного языка.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

23

Re: AHK v2: Клиент Google Translate

А, понял.

24 (изменено: haridev, 2026-11-22 19:56:52)

Re: AHK v2: Клиент Google Translate

Gigachat перевёл
"Заголовок, который не является записью, также принимается за конец круга".

"у GigaChat есть API, который поддерживает функцию перевода текста. Это полноценный инструмент для интеграции нейросети в ваши приложения"

Лимиты: В Freemium-режиме физическим лицам предоставляется 365 млн токенов генерации текста на 12 месяцев (распределенных по моделям Lite, Pro, Max и Ultra).

500 страниц  - 200000 токенов. Получается 1825 книг по пятьсот страниц.

25

Re: AHK v2: Клиент Google Translate

Никакого специального API для перевода я там не обнаружил, есть обычное API для ведения диалога с моделью, так что в качестве переводчика без гарантии.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

26

Re: AHK v2: Клиент Google Translate

Если кто хочет попробовать модели GigaChat, я написал скрипт:

; GigaChatDialog.Standalone.ahk — однофайловая сборка GigaChatDialog.ahk.
; Сгенерировано tools\BuildStandalone.ahk 2026-11-24 10:48.
; Не редактировать вручную: правки вносить в исходники проекта и пересобирать.
; Встроено: AsyncProcessIO и AsyncWait (MIT, jollycoder), marked (MIT, Christopher Jeffrey).
; Рядом со скриптом нужны settings.ini и Russian_Trusted_Root_CA.cer.

#Requires AutoHotkey v2.0
#SingleInstance Force

try {
    StartDialog()
} catch Error as startupError {
    MsgBox(startupError.Message, "GigaChat: ошибка запуска", "Iconx")
    ExitApp(1)
}

; ============================================================================
; Окно диалога
; ============================================================================

StartDialog() {
    LightJson.Init()
    DialogState.sessionId := CreateUUID()
    DialogState.iniPath := A_ScriptDir "\settings.ini"
    DialogState.prompts := PromptPresets()
    ; 0x02000000 = WS_CLIPCHILDREN: окно не затирает фоном область ленты при перерисовке.
    dialogGui := Gui("+Resize +MinSize940x600 +0x02000000", "GigaChat — диалог")
    dialogGui.SetFont("s10", "Segoe UI")
    DialogState.window := dialogGui
    DialogState.promptCaption := dialogGui.Add("Text"        , "x0 y0 w140 h20", "Системный промпт:")
    DialogState.promptList    := dialogGui.Add("DropDownList", "x0 y0 w230 r10")
    DialogState.modelCaption  := dialogGui.Add("Text"        , "x0 y0 w64 h20 Right", "Модель:")
    DialogState.modelList     := dialogGui.Add("DropDownList", "x0 y0 w270 r12")
    ; Пометка справа от списка промптов; 0x4000 = SS_ENDELLIPSIS (не влезает — обрезается с «…»).
    dialogGui.SetFont("s9")
    DialogState.systemNote    := dialogGui.Add("Text"        , "x0 y0 w100 h20 cB35900 +0x4000", "")
    dialogGui.SetFont("s10")
    DialogState.systemEdit    := dialogGui.Add("Edit"        , "x0 y0 w100 h80 Multi WantReturn VScroll", "")
    ; 0x100 = SS_NOTIFY (нужен для щелчков мышью), 0x10 = SS_ETCHEDHORZ
    DialogState.splitter      := dialogGui.Add("Text"        , "x0 y0 w100 h8 +0x110")
    DialogState.view          := ChatView(dialogGui)
    DialogState.userLabel     := dialogGui.Add("Text"        , "x0 y0 w330 h20", "Сообщение  (Ctrl+Enter — отправить)")
    DialogState.userEdit      := dialogGui.Add("Edit"        , "x0 y0 w100 h70 Multi WantReturn VScroll", "")
    DialogState.sendButton    := dialogGui.Add("Button"      , "x0 y0 w120 h32", "Отправить")
    DialogState.resetButton   := dialogGui.Add("Button"      , "x0 y0 w150 h32", "Новый диалог")
    DialogState.historyCheck  := dialogGui.Add("CheckBox"    , "x0 y0 w300 h24", "Отправлять историю для ведения диалога")
    DialogState.statusBar     := dialogGui.AddStatusBar(, " Загрузка списка моделей…")

    SelectPrompt(SavedPromptIndex())
    DialogState.activeSystem := DialogState.systemEdit.Value
    ; До ответа сервера в списке запасной набор моделей.
    ApplyModels(FallbackModels())

    DialogState.promptList.OnEvent("Change", OnPromptSelect)
    DialogState.modelList.OnEvent("Change", OnModelSelect)
    DialogState.sendButton.OnEvent("Click", OnSendClick)
    DialogState.resetButton.OnEvent("Click", OnNewDialog)
    DialogState.historyCheck.OnEvent("Click", OnHistoryToggle)
    DialogState.systemEdit.OnEvent("Change", OnSystemChange)
    dialogGui.OnEvent("Size", OnDialogSize)
    dialogGui.OnEvent("Close", OnDialogClose)
    dialogGui.OnEvent("Escape", OnDialogClose)
    OnMessage(0x0201, OnSplitterDown) ; WM_LBUTTONDOWN
    OnMessage(0x0020, OnSetCursor)    ; WM_SETCURSOR

    HotIf(IsUserEditFocused)
    Hotkey("^Enter", OnCtrlEnter)
    Hotkey("^NumpadEnter", OnCtrlEnter)
    ; Элемент WebBrowser в окне AHK сам не обрабатывает сочетания с Ctrl.
    ; Ctrl+C в ленте пропускается дальше (~), как и глобальный Ctrl+C+C ниже:
    ; у вариантов одной горячей клавиши префикс ~ должен совпадать.
    HotIf(IsFeedFocused)
    Hotkey("~^c", OnFeedCopy)
    Hotkey("^a", OnFeedSelectAll)
    ; Ctrl+C+C в любом другом окне отправляет выделенный текст (как в GoogleTranslator):
    ; Ctrl+C копирует как обычно, второе нажатие отправляет скопированный текст.
    HotIf(IsCopyHotkeyAllowed)
    Hotkey("~^c", OnCopyPress)
    HotIf()
    ; Автоповтор удерживаемого Ctrl+C даёт нажатия без отпускания, поэтому
    ; двойное нажатие засчитывается, только если между нажатиями C отпустили.
    Hotkey("~*c up", OnCopyRelease)

    dialogGui.Show("Hide w1000 h760")
    Relayout()
    ; Окно показывается после загрузки списка моделей (или по таймауту).
    LoadModels()
}

ShowDialog() {
    if DialogState.shown
        return
    DialogState.shown := true
    DialogState.window.Show()
    DialogState.userEdit.Focus()
}

Relayout(fullRedraw := true) {
    DialogState.window.GetClientPos(, , &clientW, &clientH)
    OnDialogSize(DialogState.window, 0, clientW, clientH, fullRedraw)
}

OnDialogSize(guiObject, minMax, clientW, clientH, fullRedraw := true) {
    if (minMax = -1)
        return
    margin := 12
    gap := 8
    contentW := Max(300, clientW - 2 * margin)
    ; Строка состояния сама прижимается к низу окна; раскладка идёт над ней.
    DialogState.statusBar.GetPos(, , , &statusH)
    buttonY := clientH - statusH - margin - 32
    userH := 70
    userY := buttonY - gap - userH
    userLabelY := userY - 22

    y := margin
    DialogState.promptCaption.Move(margin, y + 4, 140, 20)
    DialogState.promptList.Move(margin + 140, y, 220)
    modelW := 250
    modelX := margin + contentW - modelW
    DialogState.modelList.Move(modelX, y, modelW)
    DialogState.modelCaption.Move(modelX - 70, y + 4, 64, 20)
    noteX := margin + 140 + 220 + 12
    DialogState.systemNote.Move(noteX, y + 5, Max(0, modelX - 70 - 12 - noteX), 20)
    y += 32
    ; Лента должна оставаться не ниже 120 пунктов, остальное может занять промпт.
    DialogState.systemMaxH := Max(40, userLabelY - gap - y - 8 - 120)
    systemH := Min(Max(DialogState.systemH, 40), DialogState.systemMaxH)
    DialogState.systemEdit.Move(margin, y, contentW, systemH)
    y += systemH
    DialogState.splitter.Move(margin, y + 3, contentW, 8)
    y += 12
    DialogState.view.Move(margin, y, contentW, Max(60, userLabelY - gap - y))
    DialogState.userLabel.Move(margin, userLabelY, contentW, 20)
    DialogState.userEdit.Move(margin, userY, contentW, userH)
    DialogState.sendButton.Move(margin, buttonY, 120, 32)
    DialogState.resetButton.Move(margin + 132, buttonY, 150, 32)
    DialogState.historyCheck.Move(margin + 300, buttonY + 4, contentW - 300, 24)
    ; При перетаскивании разделителя полная перерисовка окна на каждом шаге даёт мигание ленты.
    ; Строку состояния AHK перемещает уже после этого обработчика, поэтому перерисовка
    ; откладывается, иначе на старом месте строки остаётся её изображение.
    if fullRedraw
        SetTimer(RedrawDialog, -15)
}

RedrawDialog() {
    hwnd := DialogState.window.Hwnd
    ; 0x585 = RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN | RDW_UPDATENOW | RDW_FRAME
    if DllCall("IsWindowVisible", "Ptr", hwnd)
        DllCall("RedrawWindow", "Ptr", hwnd, "Ptr", 0, "Ptr", 0, "UInt", 0x585)
}

; Перетаскивание разделителя между системным промптом и лентой.
OnSplitterDown(wParam, lParam, msg, hwnd) {
    if !IsObject(DialogState.splitter) || (hwnd != DialogState.splitter.Hwnd)
        return
    CoordMode("Mouse", "Client")
    MouseGetPos(, &startY)
    startH := Min(DialogState.systemH, DialogState.systemMaxH)
    ; MouseGetPos даёт физические пиксели, Move работает в масштабированных.
    scale := A_ScreenDPI / 96
    ; Захват мыши: иначе движения с зажатой кнопкой попадают в ленту, и MSHTML
    ; начинает выделение текста, из-за чего лента мигает и может пропасть.
    DllCall("SetCapture", "Ptr", DialogState.splitter.Hwnd, "Ptr")
    try {
        while GetKeyState("LButton", "P") {
            MouseGetPos(, &currentY)
            newH := Min(Max(startH + Round((currentY - startY) / scale), 40), DialogState.systemMaxH)
            if (newH != DialogState.systemH) {
                DialogState.systemH := newH
                Relayout(false)
            }
            Sleep(15)
        }
    } finally {
        DllCall("ReleaseCapture")
        DialogState.view.Repaint()
    }
    return 0
}

OnSetCursor(wParam, lParam, msg, hwnd) {
    if IsObject(DialogState.splitter) && (wParam = DialogState.splitter.Hwnd) {
        ; 32645 = IDC_SIZENS
        DllCall("SetCursor", "Ptr", DllCall("LoadCursor", "Ptr", 0, "Ptr", 32645, "Ptr"))
        return true
    }
}

IsUserEditFocused(*) {
    try {
        if !WinActive(DialogState.window.Hwnd)
            return false
        return DllCall("GetFocus", "Ptr") = DialogState.userEdit.Hwnd
    }
    return false
}

IsFeedFocused(*) {
    try {
        if !WinActive(DialogState.window.Hwnd)
            return false
        focusHwnd := DllCall("GetFocus", "Ptr")
        return focusHwnd && DllCall("IsChild", "Ptr", DialogState.view.ctrl.Hwnd, "Ptr", focusHwnd, "Int")
    }
    return false
}

OnCtrlEnter(*) {
    if !DialogState.busy
        OnSend()
}

; Ctrl+C+C работает, когда окно уже показано и активно другое приложение:
; в собственном окне Ctrl+C остаётся обычным копированием.
IsCopyHotkeyAllowed(*) {
    try return DialogState.shown && !WinActive(DialogState.window.Hwnd)
    return false
}

OnCopyPress(*) {
    if RegisterCopyPress()
        SendCopiedText(A_Clipboard)
}

OnCopyRelease(*) {
    DialogState.copyKeyReleased := true
}

; Возвращает true, если это нажатие завершает двойное нажатие Ctrl+C+C.
RegisterCopyPress(pressTick := A_TickCount) {
    isDoublePress := DialogState.copyKeyReleased && DialogState.copyPressTick
        && pressTick - DialogState.copyPressTick < 400
    DialogState.copyKeyReleased := false
    ; Завершённое двойное нажатие начинает новую серию: третье нажатие
    ; не должно отправлять текст ещё раз.
    DialogState.copyPressTick := isDoublePress ? 0 : pressTick
    return isDoublePress
}

SendCopiedText(copiedText) {
    if (Trim(copiedText, " `t`r`n") = "")
        return
    DialogState.window.Show()
    if DialogState.busy {
        ; Пока идёт запрос, новый не отправляем; текст не теряется, если поле пустое.
        if (DialogState.userEdit.Value = "") {
            DialogState.userEdit.Value := copiedText
            SetStatus("Идёт запрос: скопированный текст вставлен в поле сообщения")
        } else {
            SetStatus("Идёт запрос: скопированный текст не отправлен")
        }
        return
    }
    ; Набранный в поле черновик не трогаем: отправляется скопированный текст.
    OnSend(copiedText)
}

OnFeedCopy(*) {
    DialogState.view.ExecCommand(12)  ; OLECMDID_COPY
}

OnFeedSelectAll(*) {
    DialogState.view.ExecCommand(17)  ; OLECMDID_SELECTALL
}

; ============================================================================
; Обработчики действий пользователя
; ============================================================================

OnSendClick(*) {
    if DialogState.busy
        OnStop()
    else
        OnSend()
}

; sourceText передаётся при отправке по Ctrl+C+C; без него текст берётся из поля ввода.
OnSend(sourceText?) {
    fromField := !IsSet(sourceText)
    userText := fromField ? DialogState.userEdit.Value : sourceText
    if (Trim(userText, " `t`r`n") = "") {
        SetStatus("Введите сообщение пользователя")
        DialogState.userEdit.Focus()
        return
    }
    try {
        settings := LoadSettings()
    } catch Error as settingsError {
        SetStatus("Ошибка настроек")
        MsgBox(settingsError.Message, "GigaChat: ошибка", "Iconx")
        return
    }

    view := DialogState.view
    systemText := DialogState.systemEdit.Value
    if (DialogState.systemShown && systemText != DialogState.activeSystem) {
        ResetContext()
        view.Exec("chatAddDivider", "Системный промпт изменён · новый диалог")
    }
    ; Карточка показывает промпт, который реально уходит в запросе.
    if !DialogState.systemShown {
        DialogState.activeSystem := systemText
        view.Exec("chatAddSystem", systemText)
        DialogState.systemShown := true
    }

    historyOn := DialogState.historyCheck.Value
    modelId := CurrentModel()
    requestBody := BuildDialogRequest(modelId, systemText, historyOn ? DialogState.history : [], userText)
    userId := NextId()
    pendingId := NextId()
    view.Exec("chatAddUser", userId, userText, "Вы · " TimeLabel() (historyOn ? "" : " · без истории"))
    view.Exec("chatAddPending", pendingId, modelId)
    if fromField
        DialogState.userEdit.Value := ""
    DialogState.pendingId := pendingId
    DialogState.pendingUserText := userText
    DialogState.pendingModel := modelId
    DialogState.activeTurn := ApiRequest(settings, "POST", "https://api.giga.chat/v1/chat/completions",
        requestBody, ["X-Session-ID: " DialogState.sessionId], 120, "Запрос к GigaChat",
        OnTurnFinished.Bind(pendingId, userText, historyOn, modelId))
    SetBusy(true)
    SetStatus("Ожидание ответа…")
    UpdateSystemNote()
    DialogState.userEdit.Focus()
    DialogState.activeTurn.Start()
}

OnStop() {
    turnObj := DialogState.activeTurn
    if !IsObject(turnObj)
        return
    ; Сервер может успеть обработать запрос — токены за него всё равно спишутся.
    turnObj.Cancel()
    DialogState.activeTurn := ""
    DialogState.view.Exec("chatFail", DialogState.pendingId, "Запрос отменён", "cancel", DialogState.pendingModel)
    DialogState.pendingId := 0
    if (DialogState.userEdit.Value = "")
        DialogState.userEdit.Value := DialogState.pendingUserText
    SetBusy(false)
    SetStatus("Запрос отменён")
    DialogState.userEdit.Focus()
}

OnTurnFinished(pendingId, userText, historyOn, modelId, response) {
    if (pendingId != DialogState.pendingId)
        return
    DialogState.activeTurn := ""
    DialogState.pendingId := 0
    SetBusy(false)
    view := DialogState.view
    try {
        if (response is Error)
            throw response
        info := ParseChatAnswer(response.body)
    } catch Error as answerError {
        view.Exec("chatFail", pendingId, answerError.Message, "error", modelId)
        SetStatus("Ошибка запроса")
        if (DialogState.userEdit.Value = "")
            DialogState.userEdit.Value := userText
        DialogState.userEdit.Focus()
        return
    }
    ; В подписи — модель, которая фактически ответила (по данным сервера).
    meta := (info.model != "" ? info.model : modelId) " · " TimeLabel()
    if (info.totalTokens != "")
        meta .= " · токенов: " info.totalTokens
    if (info.finishReason = "length")
        meta .= " · ответ обрезан по длине"
    else if (info.finishReason = "blacklist")
        meta .= " · тема ограничена"
    view.Exec("chatResolve", pendingId, info.text, meta)
    if historyOn {
        DialogState.history.Push(Map("role", "user", "content", userText))
        DialogState.history.Push(Map("role", "assistant", "content", info.text))
        SetStatus("Ответ получен · реплик в истории: " DialogState.history.Length)
    } else {
        SetStatus("Ответ получен · без истории")
    }
    DialogState.userEdit.Focus()
}

OnNewDialog(*) {
    if DialogState.busy
        return
    ResetContext()
    DialogState.view.Exec("chatClear")
    SetStatus("Новый диалог")
    DialogState.userEdit.Focus()
}

OnHistoryToggle(*) {
    if DialogState.busy
        return
    hadMessages := DialogState.systemShown
    ResetContext()
    historyOn := DialogState.historyCheck.Value
    if hadMessages
        DialogState.view.Exec("chatAddDivider", historyOn ? "История включена · новый диалог" : "История выключена")
    SetStatus(historyOn ? "История включена: новый диалог" : "История выключена")
}

OnSystemChange(*) {
    ; Ручная правка помечает выбранный промпт в списке как изменённый.
    edited := DialogState.systemEdit.Value != DialogState.prompts[DialogState.promptIndex].text
    if (edited != DialogState.promptEdited) {
        DialogState.promptEdited := edited
        RefreshPromptList()
    }
    UpdateSystemNote()
}

OnPromptSelect(*) {
    index := DialogState.promptList.Value
    if !index
        return
    SelectPrompt(index)
    try IniWrite(DialogState.prompts[index].name, DialogState.iniPath, "Settings", "prompt")
}

OnModelSelect(*) {
    modelId := CurrentModel()
    try IniWrite(modelId, DialogState.iniPath, "Settings", "model")
    SetStatus("Модель: " modelId)
}

; ============================================================================
; Системные промпты и модели
; ============================================================================

SelectPrompt(index) {
    DialogState.promptIndex := index
    DialogState.systemEdit.Value := DialogState.prompts[index].text
    DialogState.promptEdited := false
    RefreshPromptList()
    UpdateSystemNote()
}

RefreshPromptList() {
    names := []
    for index, preset in DialogState.prompts {
        mark := (index = DialogState.promptIndex && DialogState.promptEdited) ? " (изменён)" : ""
        names.Push(preset.name mark)
    }
    DialogState.promptList.Delete()
    DialogState.promptList.Add(names)
    DialogState.promptList.Choose(DialogState.promptIndex)
}

SavedPromptIndex() {
    savedName := IniRead(DialogState.iniPath, "Settings", "prompt", "")
    for index, preset in DialogState.prompts {
        if (preset.name = savedName)
            return index
    }
    return 1
}

LoadModels() {
    try {
        settings := LoadSettings()
    } catch Error as settingsError {
        ShowModelsError("Ошибка настроек: " settingsError.Message)
        ShowDialog()
        return
    }
    DialogState.modelRequest := ApiRequest(settings, "GET", "https://api.giga.chat/v1/models",
        "", [], 15, "Список моделей", OnModelsLoaded)
    DialogState.modelRequest.Start()
    ; Если сервер отвечает долго, окно показываем, не дожидаясь списка.
    SetTimer(ShowDialog, -4000)
}

OnModelsLoaded(response) {
    DialogState.modelRequest := ""
    try {
        if (response is Error)
            throw response
        modelIds := ParseModelList(response.body)
        if !modelIds.Length
            throw Error("Сервер вернул пустой список моделей.")
        ApplyModels(modelIds)
        SetStatus("Готово · моделей в списке: " modelIds.Length)
    } catch Error as modelsError {
        ShowModelsError(modelsError.Message)
    }
    ShowDialog()
}

ShowModelsError(message) {
    SetStatus("Список моделей не загружен")
    DialogState.view.Exec("chatAddNotice",
        "Не удалось получить список моделей, показан запасной список.`n" message, "error")
}

; Заполняет список моделей; выбирает сохранённую, если она есть, иначе самую сильную.
ApplyModels(modelIds) {
    DialogState.modelIds := modelIds
    labels := []
    for modelId in modelIds
        labels.Push(RegExMatch(modelId, "i)-preview$") ? modelId "  (ранний доступ)" : modelId)
    savedModel := IniRead(DialogState.iniPath, "Settings", "model", "")
    chosen := 1
    for index, modelId in modelIds {
        if (modelId = savedModel) {
            chosen := index
            break
        }
    }
    DialogState.modelList.Delete()
    DialogState.modelList.Add(labels)
    DialogState.modelList.Choose(chosen)
}

CurrentModel() {
    index := DialogState.modelList.Value
    return index ? DialogState.modelIds[index] : DialogState.modelIds[1]
}

FallbackModels() {
    return ["GigaChat-3-Ultra", "GigaChat-2-Max", "GigaChat-2-Pro", "GigaChat-2"]
}

ParseModelList(body) {
    try {
        data := LightJson.Parse(body)
        items := data["data"]
    } catch {
        throw Error("Неожиданный ответ сервера:`n" SubStr(body, 1, 300))
    }
    modelIds := []
    for item in items {
        try
            modelId := item["id"]
        catch
            continue
        modelType := ""
        try modelType := item["type"]
        ; Нужны только модели для генерации (type = chat), без эмбеддингов и проверки на ИИ.
        if (modelType != "") {
            if (modelType != "chat")
                continue
        } else if RegExMatch(modelId, "i)embed|aicheck") {
            continue
        }
        modelIds.Push(modelId)
    }
    return SortModels(modelIds)
}

; Сервер не сообщает «силу» модели, поэтому порядок задаётся по названию:
; Ultra > Max > Pro > остальные; внутри ступени новая версия выше, -preview ниже обычной.
ModelRank(modelId) {
    if RegExMatch(modelId, "i)ultra")
        tier := 4
    else if RegExMatch(modelId, "i)max")
        tier := 3
    else if RegExMatch(modelId, "i)pro")
        tier := 2
    else
        tier := 1
    version := RegExMatch(modelId, "i)GigaChat-(\d+)", &versionMatch) ? Integer(versionMatch[1]) : 1
    isPreview := RegExMatch(modelId, "i)-preview$")
    return tier * 10000 + version * 10 + (isPreview ? 0 : 5)
}

; Сортировка вставками по убыванию ранга; при равном ранге сохраняется порядок сервера.
SortModels(modelIds) {
    sortedIds := []
    for modelId in modelIds {
        rank := ModelRank(modelId)
        position := sortedIds.Length + 1
        for index, existingId in sortedIds {
            if (rank > ModelRank(existingId)) {
                position := index
                break
            }
        }
        sortedIds.InsertAt(position, modelId)
    }
    return sortedIds
}

OnDialogClose(*) {
    if IsObject(DialogState.activeTurn)
        DialogState.activeTurn.Cancel()
    if IsObject(DialogState.modelRequest)
        DialogState.modelRequest.Cancel()
    ExitApp()
}

; Сбрасывает контекст: историю, идентификатор сессии и признак показанного промпта.
ResetContext() {
    DialogState.history := []
    DialogState.sessionId := CreateUUID()
    DialogState.systemShown := false
    DialogState.activeSystem := DialogState.systemEdit.Value
    UpdateSystemNote()
}

UpdateSystemNote() {
    changed := DialogState.systemShown && (DialogState.systemEdit.Value != DialogState.activeSystem)
    noteText := changed ? "при отправке начнётся новый диалог" : ""
    if (DialogState.systemNote.Text != noteText)
        DialogState.systemNote.Text := noteText
}

SetBusy(isBusy) {
    DialogState.busy := isBusy
    DialogState.sendButton.Text := isBusy ? "Остановить" : "Отправить"
    DialogState.resetButton.Enabled := !isBusy
    DialogState.historyCheck.Enabled := !isBusy
}

SetStatus(text) {
    DialogState.statusBar.SetText(" " text)
}

NextId() {
    DialogState.nextId += 1
    return DialogState.nextId
}

TimeLabel() {
    return FormatTime(, "HH:mm")
}

; ============================================================================
; Настройки, токен, разбор ответов
; ============================================================================

LoadSettings() {
    iniPath := A_ScriptDir "\settings.ini"
    certPath := A_ScriptDir "\Russian_Trusted_Root_CA.cer"
    authKey := Trim(IniRead(iniPath, "Settings", "key", ""))
    if (authKey = "")
        throw Error("Не найден ключ [Settings] key в " iniPath)
    if !RegExMatch(authKey, "^[A-Za-z0-9+/]+={0,2}$")
        throw Error("Некорректный Authorization Key в settings.ini.")
    if !FileExist(certPath)
        throw Error("Не найден сертификат: " certPath)
    return {iniPath: iniPath, certPath: certPath, authKey: authKey}
}

GetCachedToken(iniPath) {
    cachedToken := Trim(IniRead(iniPath, "GigaChatToken", "access_token", ""))
    validUntil := Trim(IniRead(iniPath, "GigaChatToken", "expires_at_utc", ""))
    if (cachedToken != "" && RegExMatch(validUntil, "^\d{14}$")
        && DateDiff(validUntil, A_NowUTC, "Seconds") > 60)
        return cachedToken
    return ""
}

SaveToken(iniPath, accessToken) {
    ; Токен действует 30 минут, храним с запасом в минуту.
    IniWrite(accessToken, iniPath, "GigaChatToken", "access_token")
    IniWrite(DateAdd(A_NowUTC, 29, "Minutes"), iniPath, "GigaChatToken", "expires_at_utc")
}

ParseAccessToken(body) {
    if !RegExMatch(body, '"access_token"\s*:\s*"([^" ]+)"', &tokenMatch)
        throw Error("Сервер не вернул access_token.")
    return tokenMatch[1]
}

ParseChatAnswer(body) {
    try {
        data := LightJson.Parse(body)
        choice := data["choices"][1]
        answerText := choice["message"]["content"]
    } catch {
        throw Error("Неожиданный ответ сервера:`n" SubStr(body, 1, 500))
    }
    finishReason := ""
    try finishReason := choice["finish_reason"]
    totalTokens := ""
    try totalTokens := data["usage"]["total_tokens"]
    answerModel := ""
    try answerModel := data["model"]
    return {text: answerText, finishReason: finishReason, totalTokens: totalTokens, model: answerModel}
}

DescribeHttpError(stepName, response) {
    message := ""
    try {
        data := LightJson.Parse(response.body)
        if (data is Map) && data.Has("message") && !IsObject(data["message"])
            message := data["message"]
    }
    if (message = "")
        message := Trim(SubStr(response.body, 1, 500), " `t`r`n")
    switch response.status {
        case 401: hint := "Ключ авторизации или токен не приняты."
        case 402: hint := "Закончились токены модели."
        case 413: hint := "Слишком большой запрос."
        case 429: hint := "Слишком много запросов: физлицам доступен один поток."
        default:  hint := ""
    }
    return stepName ": HTTP " response.status (hint != "" ? "`n" hint : "") (message != "" ? "`n" message : "")
}

; ============================================================================
; Запрос к API: получение токена (при необходимости) и основной запрос
; ============================================================================

; Результат передаётся в onFinish: {status, body} при коде 2xx либо объект Error.
class ApiRequest
{
    __New(settings, method, url, body, extraHeaders, maxTimeSec, stepName, onFinish) {
        this.settings := settings
        this.method := method
        this.url := url
        this.body := body
        this.extraHeaders := extraHeaders
        this.maxTimeSec := maxTimeSec
        this.stepName := stepName
        this.onFinish := onFinish
        this.retried := false
        this.cancelled := false
        this.request := ""
    }

    Start() {
        try {
            accessToken := GetCachedToken(this.settings.iniPath)
            if (accessToken != "")
                this.SendMain(accessToken)
            else
                this.RequestToken()
        } catch Error as startError {
            this.Fail(startError.Message)
        }
    }

    RequestToken() {
        this.request := CurlRequest("POST",
            "https://ngw.devices.sberbank.ru:9443/api/v2/oauth",
            ["Content-Type: application/x-www-form-urlencoded",
             "Accept: application/json",
             "RqUID: " CreateUUID(),
             "Authorization: Basic " this.settings.authKey],
            "scope=GIGACHAT_API_PERS", this.settings.certPath, 30,
            ObjBindMethod(this, "OnToken"))
    }

    OnToken(response) {
        this.request := ""
        if this.cancelled
            return
        try {
            if (response is Error)
                throw response
            if (response.status < 200 || response.status >= 300)
                throw Error(DescribeHttpError("Получение токена", response))
            accessToken := ParseAccessToken(response.body)
            SaveToken(this.settings.iniPath, accessToken)
            this.SendMain(accessToken)
        } catch Error as tokenError {
            this.Fail(tokenError.Message)
        }
    }

    SendMain(accessToken) {
        headers := ["Accept: application/json", "Authorization: Bearer " accessToken]
        if (this.body != "")
            headers.InsertAt(1, "Content-Type: application/json")
        for headerValue in this.extraHeaders
            headers.Push(headerValue)
        this.request := CurlRequest(this.method, this.url, headers, this.body,
            this.settings.certPath, this.maxTimeSec, ObjBindMethod(this, "OnMain"))
    }

    OnMain(response) {
        this.request := ""
        if this.cancelled
            return
        try {
            if (response is Error)
                throw response
            ; Токен мог быть отозван раньше срока: получаем новый и повторяем один раз.
            if (response.status = 401 && !this.retried) {
                this.retried := true
                this.RequestToken()
                return
            }
            if (response.status < 200 || response.status >= 300)
                throw Error(DescribeHttpError(this.stepName, response))
            this.Finish(response)
        } catch Error as mainError {
            this.Fail(mainError.Message)
        }
    }

    Cancel() {
        this.cancelled := true
        this.onFinish := ""
        if IsObject(this.request)
            this.request.Cancel()
        this.request := ""
    }

    Fail(message) {
        this.Finish(Error(message))
    }

    Finish(result) {
        callback := this.onFinish
        this.onFinish := ""
        if IsObject(callback)
            SetTimer(callback.Bind(result), -1)
    }
}

; Один вызов curl.exe без блокировки окна: вывод читается через AsyncProcessIO.
; Результат передаётся в onDone: {status, body} или объект Error.
class CurlRequest
{
    __New(method, url, headers, body, certPath, maxTimeSec, onDone) {
        curlExe := A_WinDir "\System32\curl.exe"
        if !FileExist(curlExe)
            throw Error("Не найден curl.exe: " curlExe)
        this.onDone := onDone
        this.finished := false
        this.outText := ""
        this.errText := ""
        this.outDone := false
        this.errDone := false
        this.proc := ""

        commandLine := '"' curlExe '" --silent --show-error --max-time ' maxTimeSec
            . ' --cacert "' certPath '" --write-out "%{http_code}" --config -'
        configText := CurlConfigLine("url", url) CurlConfigLine("request", method)
        for headerValue in headers
            configText .= CurlConfigLine("header", headerValue)
        if (body != "")
            configText .= CurlConfigLine("data-raw", body)

        ; Ссылка на this в обработчике образует цикл с proc; он разрывается в Release().
        this.proc := AsyncProcessIO(commandLine, ObjBindMethod(this, "OnChunk"),
            (maxTimeSec + 15) * 1000, "UTF-8")
        ; Конфигурация с ключом и токеном идёт только по stdin, не через командную строку.
        expectedBytes := StrPut(configText, "UTF-8") - 1
        writtenBytes := this.proc.WriteText(configText)
        this.proc.CloseStdIn()
        if (writtenBytes != expectedBytes) {
            this.Cancel()
            throw Error("curl не принял конфигурацию запроса.")
        }
    }

    OnChunk(pid, data, state, stream) {
        if this.finished
            return
        if (state = -1) {
            this.Complete(Error("curl не отвечает дольше отведённого времени."))
            return
        }
        if (stream = 0) {
            this.outText .= data
            if (state = 1)
                this.outDone := true
        } else {
            this.errText .= data
            if (state = 1)
                this.errDone := true
        }
        if (this.outDone && this.errDone)
            this.WaitForExit(0)
    }

    ; Конец вывода не означает, что процесс уже завершился: ждём код выхода.
    WaitForExit(attempt) {
        if this.finished
            return
        exitCode := this.proc.exitCode
        if (exitCode = "") {
            if (attempt < 150) {
                SetTimer(ObjBindMethod(this, "WaitForExit", attempt + 1), -20)
                return
            }
            this.Complete(Error("curl не завершился после окончания вывода."))
            return
        }
        if (exitCode != 0) {
            errorText := Trim(this.errText, " `t`r`n")
            this.Complete(Error("curl: код " exitCode (errorText != "" ? "`n" errorText : "")))
            return
        }
        statusText := SubStr(this.outText, -3)
        if !RegExMatch(statusText, "^\d{3}$") {
            this.Complete(Error("curl не вернул HTTP-статус."))
            return
        }
        this.Complete({status: Integer(statusText), body: SubStr(this.outText, 1, -3)})
    }

    Complete(response) {
        if this.finished
            return
        this.finished := true
        callback := this.onDone
        this.onDone := ""
        this.Release()
        if IsObject(callback)
            SetTimer(callback.Bind(response), -1)
    }

    Cancel() {
        this.finished := true
        this.onDone := ""
        this.Release()
    }

    ; Удаление AsyncProcessIO закрывает каналы и завершает curl, если он ещё работает.
    Release() {
        this.proc := ""
    }
}

; ============================================================================
; Лента сообщений: ActiveX WebBrowser (MSHTML) + marked
; ============================================================================

class ChatView
{
    __New(guiObj) {
        this.ready := false
        this.failed := false
        this.stage := 0
        this.queue := []
        css := ScaleCssPx(LoadUiFile("chat.css"), A_ScreenDPI / 96)
        this.pageHtml := '<!DOCTYPE html><html><head>'
            . '<meta http-equiv="X-UA-Compatible" content="IE=edge">'
            . '<style>' css '</style></head><body><div id="feed"></div></body></html>'
        this.chatJs := LoadUiFile("chat.js")
        this.markedJs := LoadUiFile("marked.js")
        bootstrap := 'about:<!DOCTYPE html><html><head>'
            . '<meta http-equiv="X-UA-Compatible" content="IE=edge"></head>'
            . '<body style="margin:0;background:#ffffff"></body></html>'
        ; Элемент виден сразу: пока документа нет, MSHTML заливает его белым, как и ленту.
        this.ctrl := guiObj.AddActiveX("x0 y0 w100 h100", bootstrap)
        this.wb := this.ctrl.Value
        this.wb.Silent := true
        ComObjConnect(this.wb, this)
        this.pollStart := A_TickCount
        this.pollFn := ObjBindMethod(this, "PollReady")
        SetTimer(this.pollFn, 30)
    }

    Move(x, y, w, h) {
        this.ctrl.Move(x, y, w, h)
        ; После изменения размера MSHTML может оставить на экране следы прежнего
        ; изображения ленты: страница перестраивает ленту сама (chatRefresh).
        if this.ready
            this.Invoke("chatRefresh", [])
    }

    ; Вызывает функцию страницы; до готовности страницы вызовы ставятся в очередь.
    Exec(functionName, args*) {
        if this.failed
            return
        if !this.ready {
            this.queue.Push([functionName, args])
            return
        }
        this.Invoke(functionName, args)
    }

    Invoke(functionName, args) {
        try {
            this.wb.document.parentWindow.%functionName%(args*)
        } catch Error as callError {
            SetStatus("Ошибка ленты: " callError.Message)
        }
    }

    ExecCommand(commandId) {
        try this.wb.ExecWB(commandId, 0, 0, 0)
    }

    PollReady() {
        if (A_TickCount - this.pollStart > 15000) {
            SetTimer(this.pollFn, 0)
            this.failed := true
            SetStatus("Не удалось подготовить ленту сообщений")
            return
        }
        try {
            if (this.stage = 0) {
                if (this.wb.ReadyState != 4 || this.wb.document.readyState != "complete")
                    return
                doc := this.wb.document
                doc.open()
                doc.write(this.pageHtml)
                doc.close()
                this.stage := 1
                return
            }
            doc := this.wb.document
            pageState := doc.readyState
            if !(pageState = "interactive" || pageState = "complete")
                return
            if !doc.parentWindow.eval("!!document.getElementById('feed')")
                return
        } catch {
            return
        }
        SetTimer(this.pollFn, 0)
        try {
            pageWindow := this.wb.document.parentWindow
            pageWindow.eval(this.chatJs)
            pageWindow.eval(this.markedJs)
            pageWindow.chatInit()
        } catch Error as scriptError {
            this.failed := true
            SetStatus("Ошибка скрипта ленты: " scriptError.Message)
            return
        }
        this.ready := true
        pending := this.queue
        this.queue := []
        for item in pending
            this.Invoke(item[1], item[2])
        this.Repaint()
    }

    ; MSHTML иногда не дорисовывает первый кадр, пока элемент не изменит размер.
    Repaint() {
        this.ctrl.GetPos(&x, &y, &w, &h)
        if (w > 1 && h > 1) {
            this.ctrl.Move(x, y, w, h - 1)
            this.ctrl.Move(x, y, w, h)
        }
    }

    ; События WebBrowser. Все переходы, кроме служебных about:, отменяются:
    ; ahk:copy — копирование ответа, внешние ссылки открываются в браузере по умолчанию.
    BeforeNavigate2(pDisp, &url, flags, targetFrame, postData, headers, &cancel, *) {
        if (url ~= "i)^about:")
            return
        cancel := true
        if (url ~= "i)^ahk:copy")
            SetTimer(ObjBindMethod(this, "CopyFromPage"), -1)
        else if (url ~= "i)^(https?|mailto):")
            SetTimer(ObjBindMethod(this, "OpenExternal", url), -1)
    }

    CopyFromPage() {
        try A_Clipboard := this.wb.document.parentWindow.copyText
    }

    OpenExternal(url) {
        try Run(url)
    }
}

; Ресурсы ленты встроены в скрипт (сборка tools\BuildStandalone.ahk).
LoadUiFile(fileName) {
    switch fileName {
        case "chat.css":  return EmbeddedChatCss()
        case "chat.js":   return EmbeddedChatJs()
        case "marked.js": return EmbeddedMarkedJs()
    }
    throw Error("Неизвестный встроенный ресурс: " fileName)
}

; Масштабирует значения в px под DPI: MSHTML в окне AHK сам их не масштабирует.
ScaleCssPx(css, ratio) {
    result := ""
    pos := 1
    while found := RegExMatch(css, "(-?\d+(?:\.\d+)?)px\b", &pxMatch, pos) {
        result .= SubStr(css, pos, found - pos) Round(pxMatch[1] * ratio) "px"
        pos := found + StrLen(pxMatch[0])
    }
    return result SubStr(css, pos)
}

; ============================================================================
; Состояние окна
; ============================================================================

class DialogState
{
    static history := []
    static activeSystem := ""
    static sessionId := ""
    static busy := false
    static systemShown := false
    static nextId := 0
    static pendingId := 0
    static pendingUserText := ""
    static activeTurn := ""
    static systemH := 84
    static systemMaxH := 300
    static iniPath := ""
    static prompts := []
    static promptIndex := 1
    static promptEdited := false
    static modelIds := []
    static modelRequest := ""
    static pendingModel := ""
    static shown := false
    static copyPressTick := 0
    static copyKeyReleased := true
    static window := 0
    static view := 0
    static promptCaption := 0
    static promptList := 0
    static modelCaption := 0
    static modelList := 0
    static systemNote := 0
    static systemEdit := 0
    static splitter := 0
    static userLabel := 0
    static statusBar := 0
    static userEdit := 0
    static sendButton := 0
    static resetButton := 0
    static historyCheck := 0
}

; ============================================================================
; Промпт, тело запроса, вспомогательные функции
; ============================================================================

PromptPresets() {
    return [
        {name: "Переводчик", text: TranslatorPrompt()},
        {name: "Корректор", text: ProofreaderPrompt()}
    ]
}

TranslatorPrompt() {
    return "Ты - профессиональный переводчик."
        . "`n## Задача: перевести текст текущего сообщения пользователя."
        . "`nОпредели основной язык текста в текущем сообщении. Если это русский язык, переведи текст на английский. Если это любой другой язык, переведи текст на русский."
        . "`nОпределяй направление перевода заново для каждого сообщения, независимо от предыдущих сообщений диалога."
        . "`n## Правила:"
        . "`n- Все нетекстовые фрагменты (код, формулы и т.д.) переводить не нужно."
        . "`n- Орфографические и пунктуационные ошибки исправлять не нужно. Они должны оставаться такими же, как в оригинальном тексте."
        . "`n## Формат ответа:"
        . "`nТвой ответ должен содержать только переведенный текст. Никакие дополнительные пояснения или комментарии не допускаются. "
        . "`n## Примеры ответа:"
        . "`nuser:  Please, write Python function to generate random number from 10 to 999"
        . "`nassistant: Пожалуйста, напишите функцию в Питоне для генерации случайного числа от 10 до 999"
        . "`nuser: Пожалуйста, напишите функцию для генерации случайного числа."
        . "`nassistant: Please write a function to generate a random number."
}

ProofreaderPrompt() {
    return "Ты - профессиональный корректор и литературный редактор."
        . "`n## Задача: исправить текст текущего сообщения пользователя."
        . "`n## Правила:"
        . "`n- Исправляй орфографические, пунктуационные и грамматические ошибки, опечатки."
        . "`n- Устраняй явные стилистические недочёты (тавтологию, неудачный порядок слов, канцелярит), не меняя смысл, тон и терминологию."
        . "`n- Сохраняй язык оригинала. Текст не переводи."
        . "`n- Не добавляй новых сведений и не сокращай содержание."
        . "`n- Сохраняй исходное форматирование: абзацы, списки, разметку Markdown."
        . "`n- Не изменяй нетекстовые фрагменты: код, формулы, ссылки, имена файлов."
        . "`n- Если текст содержит вопрос или просьбу, не отвечай на них, а только исправь сам текст."
        . "`n- Если исправлять нечего, верни текст без изменений."
        . "`n## Формат ответа:"
        . "`nТвой ответ должен содержать только исправленный текст. Никакие пояснения, комментарии и перечни исправлений не допускаются."
        . "`n## Примеры ответа:"
        . "`nuser: Превет, как дела.Я вчера, ходил в магазин и купил хлеб"
        . "`nassistant: Привет, как дела? Я вчера ходил в магазин и купил хлеб."
        . "`nuser: Подскажите пожалуста, как настроить роутер?"
        . "`nassistant: Подскажите, пожалуйста, как настроить роутер?"
}

BuildDialogRequest(modelId, systemText, history, userText) {
    messages := []
    if (Trim(systemText) != "")
        messages.Push(Map("role", "system", "content", systemText))
    for previousMessage in history
        messages.Push(previousMessage)
    messages.Push(Map("role", "user", "content", userText))
    return LightJson.Stringify(Map("model", modelId, "messages", messages))
}

CurlConfigLine(optionName, optionValue) {
    if (InStr(optionValue, "`r") || InStr(optionValue, "`n"))
        throw Error("Недопустимый перенос строки в параметре curl: " optionName)
    escapedValue := StrReplace(StrReplace(optionValue, '\', '\\'), '"', '\"')
    return optionName ' = "' escapedValue '"`n'
}

CreateUUID() {
    static uuidBuffer := Buffer(16)
    result := DllCall("Rpcrt4\UuidCreate", "Ptr", uuidBuffer.Ptr, "UInt")
    if (result != 0 && result != 1824)
        throw Error("UuidCreate: код " result)

    uuidStringPtr := 0
    result := DllCall("Rpcrt4\UuidToStringW", "Ptr", uuidBuffer.Ptr, "Ptr*", &uuidStringPtr, "UInt")
    if (result != 0)
        throw Error("UuidToStringW: код " result)

    try {
        return StrGet(uuidStringPtr, "UTF-16")
    } finally {
        DllCall("Rpcrt4\RpcStringFreeW", "Ptr*", &uuidStringPtr)
    }
}

class LightJson
{
    static Init() {
        this.JS    := this.GetJS()
        this.true  := {}
        this.false := {}
        this.null  := {}
    }

    static Parse(json, objIsMap := true, _rec?) {
        switch {
            case !IsSet(_rec)    : obj := this.Parse(this.JS.JSON.parse(json), objIsMap, true)
            case !IsObject(json) : obj := json
            case this.JS.Object.prototype.toString.call(json) == '[object Array]':
                obj := []
                Loop json.length
                    obj.Push(this.Parse(json.%A_Index - 1%, objIsMap, true))
            default:
                obj := objIsMap ? Map() : {}
                keys := this.JS.Object.keys(json)
                Loop keys.length {
                    k := keys.%A_Index - 1%
                    ( objIsMap && obj[k]  := this.Parse(json.%k%, true , true))
                    (!objIsMap && obj.%k% := this.Parse(json.%k%, false, true))
                }
        }
        return obj
    }

    static Stringify(obj, indent := '') {
        if indent = true {
            for k, v in ['true', 'false', 'null']
                if (obj = this.%v%)
                    return v

            if IsObject(obj) {
                isArray := Type(obj) = 'Array'
                enumerable := Type(obj) = 'Object' ? obj.OwnProps() : obj
                str := ''
                for k, v in enumerable
                    str .= (A_Index = 1 ? '' : ',') . (isArray ? '' : this.Stringify(k, true) . ':') . this.Stringify(v, true)

                return isArray ? '[' str ']' : '{' str '}'
            }
            if IsNumber(obj) && Type(obj) != 'String'
                return obj

            return this._EscapeString(obj)
        }
        sObj := this.Stringify(obj, true)
        return this.JS.eval('JSON.stringify(' . sObj . ',"","' . indent . '")')
    }

    ; Escape a string as a JSON string literal that is also safe to embed into
    ; JS source for eval(). Returns the value wrapped in double quotes.
    static _EscapeString(s) {
        out := ''
        loop parse s {
            cp := Ord(A_LoopField)
            switch cp {
                case 0x5C: out .= '\\'          ; backslash (must come first conceptually)
                case 0x22: out .= '\"'          ; double quote
                case 0x2F: out .= '\/'          ; forward slash (kept for parity)
                case 0x08: out .= '\b'
                case 0x09: out .= '\t'
                case 0x0A: out .= '\n'
                case 0x0C: out .= '\f'
                case 0x0D: out .= '\r'
                case 0x2028, 0x2029: out .= Format('\u{:04x}', cp)   ; JS line terminators
                default:
                    ; Remaining control chars must be \u-escaped; everything
                    ; else (incl. surrogate code units of valid pairs) passes through.
                    out .= (cp < 0x20) ? Format('\u{:04x}', cp) : A_LoopField
            }
        }
        return '"' out '"'
    }

    static Beautify(json, indent) => this.JS.eval('JSON.stringify(' . json . ',"","' . indent . '")')

    static GetJS() {
        static document := '', JS
        if !document {
            document := ComObject('HTMLFILE')
            document.write('<meta http-equiv="X-UA-Compatible" content="IE=9">')
            JS := document.parentWindow
            (document.documentMode < 9 && JS.execScript())
        }
        return JS
    }
}


; ============================================================================
; Встроенная библиотека AsyncProcessIO (lib\AsyncProcessIO.ahk, lib\AsyncWait.ahk)
; ============================================================================

; =============================================================================
; AsyncProcessIO   — spawn a child process with async stdout/stderr reading
;                    and synchronous stdin writing.
; AsyncStdinReader — read inherited stdin asynchronously in a child process.
; StreamReader     — shared engine for async pipe reading (used by both above).
; AsyncWait        — thread-pool wait → GUI thread marshalling via PostMessageW.
;
; Version: 1.0.0
; Date:    2026-04-10
; Forum:   https://www.autohotkey.com/boards/viewtopic.php?f=83&t=122732
; =============================================================================

class AsyncProcessIO
{
    /**
     * Spawns a child process, reads its stdout and stderr asynchronously
     * without blocking the AHK thread, and allows writing to stdin synchronously.
     *
     * cmd:      command line of the process to create.
     * callback: function called when a new data chunk arrives on stdout or stderr.
     *           Text mode: callback(PID, str, state, stream)
     *           Raw mode:  callback(PID, buf, state, stream)
     *               state  — 0 (data incoming), 1 (completed), -1 (timed out)
     *               stream — 0 (stdout), 1 (stderr)
     *           When no callback is supplied, data is accumulated in outData/errData.
     * timeout:  max milliseconds of silence on both streams before firing state=-1.
     *           The timer is shared: any data on either stream resets it.
     * encoding: text encoding for stdin/stdout/stderr; defaults to system OEM codepage.
     *           In raw mode, encoding is only used by WriteText.
     * raw:      when true, stdout is delivered as raw Buffer objects instead of
     *           decoded strings; UTF-8 boundary fixing is skipped.
     *           stderr is always delivered as decoded text regardless of this flag.
     */

    static BUF_STDOUT_SIZE := 0x10000
         , BUF_STDERR_SIZE := 0x01000

    __New(cmd, callback?, timeout?, encoding?, raw?, stdinOverlapped := false) {
        this._ownerRef := {ptr: ObjPtr(this)}
        raw      := raw      ?? false
        encoding := encoding ?? 'cp' . DllCall('GetOEMCP')
        this._raw       := raw
        this._encoding  := encoding
        this._startTime := A_TickCount
        if IsSet(callback)
            this._callback := callback
        if IsSet(timeout)
            this._timeout  := timeout

        ; Accumulation buffers (no-callback mode)
        this._outData := raw ? Buffer(AsyncProcessIO.BUF_STDOUT_SIZE) : ''
        this._errData := ''
        this._outPos  := 0
        this._outState := 0
        this._errState := 0

        this.hEvent    := DllCall('CreateEvent', 'Int', 0, 'Int', 0, 'Int', 0, 'Int', 0, 'Ptr')
        this.hEventErr := DllCall('CreateEvent', 'Int', 0, 'Int', 0, 'Int', 0, 'Int', 0, 'Ptr')

        stdoutBuf := Buffer(AsyncProcessIO.BUF_STDOUT_SIZE, 0)
        stderrBuf := Buffer(AsyncProcessIO.BUF_STDERR_SIZE, 0)

        this.process := AsyncProcessIO.Process(cmd, stdoutBuf.Size, stderrBuf.Size, stdinOverlapped)

        t := this.HasProp('_timeout') ? this._timeout : -1
        this._stdout := StreamReader(
            this.process.hPipeRead, this.hEvent, stdoutBuf,
            ObjBindMethod(AsyncProcessIO, '_DispatchStream', this._ownerRef, 0), encoding, raw, t)
        this._stderr := StreamReader(
            this.process.hPipeReadErr, this.hEventErr, stderrBuf,
            ObjBindMethod(AsyncProcessIO, '_DispatchStream', this._ownerRef, 1), encoding, false, t)

        this._stdout.start()
        this._stderr.start()
    }

    processID => this.process.PID

    ; Empty until the child exits; otherwise its unsigned Windows exit code.
    exitCode => this.process.GetExitCode()

    ; True only when both stdout and stderr are fully drained
    complete => this._stdout.complete && this._stderr.complete

    ; Per-stream completion state: 0 = running, 1 = EOF, -1 = timed out
    outState => this._outState
    errState => this._errState

    ; Aggregate state: -1 if any stream timed out, 1 if both reached EOF, 0 otherwise
    state => (this._outState = -1 || this._errState = -1) ? -1
           : (this._outState =  1 && this._errState =  1) ?  1 : 0

    outData  => this._outData
    errData  => this._errData

    ; Byte count of accumulated data in raw mode; string length in text mode
    outSize  => this._raw ? this._outPos : StrLen(this._outData)
    errSize  => StrLen(this._errData)

    /**
     * Write a text string to the child's stdin.
     * Encoding matches the one supplied to the constructor.
     * The null terminator is never sent to the child.
     * Returns the number of bytes actually written.
     */
    WriteText(str) {
        byteCount := StrPut(str, this._encoding)
        buf := Buffer(byteCount)
        StrPut(str, buf, this._encoding)
        return this.WriteData(buf, byteCount - (InStr(this._encoding, '16') ? 2 : 1))
    }

    /**
     * Write raw bytes to the child's stdin.
     * size defaults to buf.Size if omitted.
     * Returns the number of bytes actually written.
     */
    WriteData(buf, size?) {
        if !IsSet(size)
            size := buf.Size
        DllCall('WriteFile', 'Ptr', this.process.hInPipeWrite,
                             'Ptr', buf, 'UInt', size,
                             'UIntP', &written := 0, 'Ptr', 0)
        return written
    }

    /**
     * Close the write end of stdin, sending EOF to the child.
     * Call this when no more input will be written.
     */
    CloseStdIn() {
        if this.process.hInPipeWrite {
            DllCall('CloseHandle', 'Ptr', this.process.hInPipeWrite)
            this.process.hInPipeWrite := 0
        }
    }

    ; -------------------------------------------------------------------------

    ; Readers and their queued timers hold only this record, not their owner.
    ; Pin a live owner before allowing another AHK thread to release it.
    static _DispatchStream(ownerRef, stream, data, state) {
        wasCritical := A_IsCritical
        Critical
        try {
            if !ownerRef.ptr
                return
            owner := ObjFromPtrAddRef(ownerRef.ptr)
        } finally {
            Critical wasCritical
        }
        owner._streamCallback(stream, data, state)
    }

    ; Prepends PID and stream index, dispatches to user callback or accumulates.
    _streamCallback(stream, data, state) {
        if state = -1 {
            this._handleTimeout(stream)
            return
        }
        this._startTime := A_TickCount
        if state = 1 {
            if stream = 0
                this._outState := 1
            else
                this._errState := 1
        }
        if this.HasProp('_callback') {
            SetTimer(this._callback.Bind(this.process.PID, data, state, stream), -10)
            return
        }
        ; No-callback mode: accumulate
        if stream = 0 {
            if this._raw {
                if data.Size > 0
                    this._appendRaw(data)
            } else if data != ''
                this._outData .= data
        } else if data != ''
            this._errData .= data
    }

    ; The silence timer is shared: activity on either stream resets _startTime.
    _handleTimeout(stream) {
        reader := stream = 0 ? this._stdout : this._stderr
        if this.HasProp('_timeout') {
            remaining := this._timeout - (A_TickCount - this._startTime)
            if remaining > 0 {
                reader._registerWait(remaining)
                return
            }
        }
        if stream = 0
            this._outState := -1
        else
            this._errState := -1
        if this.HasProp('_callback') {
            emptyData := (stream = 0 && this._raw) ? Buffer(0) : ''
            SetTimer(this._callback.Bind(this.process.PID, emptyData, -1, stream), -10)
        }
    }

    ; Append a raw Buffer to the stdout accumulation buffer (no-callback, raw mode).
    ; Uses amortized doubling to minimize reallocations.
    _appendRaw(dataBuf) {
        pos  := this._outPos
        buf  := this._outData
        size := dataBuf.Size
        if pos + size > buf.Size {
            newSize := Max(buf.Size * 2, pos + size)
            newBuf  := Buffer(newSize)
            (pos > 0) && DllCall('RtlMoveMemory', 'Ptr', newBuf, 'Ptr', buf, 'Ptr', pos)
            this._outData := newBuf
            buf := newBuf
        }
        DllCall('RtlMoveMemory', 'Ptr', buf.Ptr + pos, 'Ptr', dataBuf, 'Ptr', size)
        this._outPos := pos + size
    }

    __Delete() {
        ; Invalidate queued stream callbacks before cleanup pumps messages.
        if this.HasProp('_ownerRef')
            this._ownerRef.ptr := 0
        if !this.HasProp('process')
            return
        ; Cancel both streams simultaneously, then wait once for in-flight
        ; PostMessageW callbacks to arrive and be silenced by the sentinel.
        this._stdout.prepareDelete()
        this._stderr.prepareDelete()
        Sleep 50
        this._stdout.finishDelete()
        this._stderr.finishDelete()
        this.process.TerminateIfRunning()
        this.process.Clear()
        DllCall('CloseHandle', 'Ptr', this.hEvent)
        DllCall('CloseHandle', 'Ptr', this.hEventErr)
        this._outData := ''
        this._errData := ''
    }

    ; =========================================================================
    class Process
    {
        ; Static counter to avoid pipe name collisions when multiple
        ; instances are created within the same millisecond tick.
        static _pipeId := 0

        __New(cmd, stdoutBufSize, stderrBufSize, stdinOverlapped := false) {
            this.CreatePipes(stdoutBufSize, stderrBufSize, stdinOverlapped)
            if !this.PID := this.CreateProcess(cmd)
                throw OSError('Failed to create process')
        }

        CreatePipes(stdoutBufSize, stderrBufSize, stdinOverlapped := false) {
            static GENERIC_READ := 0x80000000, GENERIC_WRITE := 0x40000000
            id := ++AsyncProcessIO.Process._pipeId

            ; --- stdout: overlapped read, inheritable write ---
            this.hPipeRead := this._createReadPipe(
                pipeName := '\\.\pipe\StdOut_' A_TickCount '_' id, stdoutBufSize)
            this.hPipeWrite := this._createChildEnd(pipeName, GENERIC_WRITE, stdinOverlapped)

            ; --- stderr: overlapped read, inheritable write ---
            this.hPipeReadErr := this._createReadPipe(
                pipeName := '\\.\pipe\StdErr_' A_TickCount '_' id, stderrBufSize)
            this.hErrPipeWrite := this._createChildEnd(pipeName, GENERIC_WRITE, stdinOverlapped)

            ; --- stdin: synchronous write on our side ---
            ; Child's read end must NOT be overlapped: child processes read stdin
            ; with a NULL OVERLAPPED pointer, which is undefined behaviour on an
            ; overlapped handle (MSDN KB 156932).
            this.hInPipeWrite := this._createWritePipe(
                pipeName := '\\.\pipe\StdIn_' A_TickCount '_' id, stdoutBufSize)
            this.hInPipeRead :=  this._createChildEnd(pipeName, GENERIC_READ, stdinOverlapped)
        }

        ; Create the parent's read end of a pipe (overlapped, non-inheritable).
        _createReadPipe(pipeName, bufSize) {
            return DllCall('CreateNamedPipe',
                'Str', pipeName, 'UInt', 0x40000001,  ; PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED
                'UInt', 0, 'UInt', 1,
                'UInt', bufSize, 'UInt', bufSize,
                'UInt', 120000, 'Ptr', 0, 'Ptr')
        }

        ; Create the parent's write end of a pipe (synchronous, non-inheritable).
        _createWritePipe(pipeName, bufSize) {
            return DllCall('CreateNamedPipe',
                'Str', pipeName, 'UInt', 0x2,  ; PIPE_ACCESS_OUTBOUND (no overlapped)
                'UInt', 0, 'UInt', 1,
                'UInt', 0, 'UInt', bufSize,
                'UInt', 120000, 'Ptr', 0, 'Ptr')
        }

        ; Open the child-facing end of an existing named pipe (inheritable).
        ; access: GENERIC_READ (0x80000000) or GENERIC_WRITE (0x40000000)
        ; overlapped: whether to open with FILE_FLAG_OVERLAPPED
        _createChildEnd(pipeName, access, overlapped) {
            h := DllCall('CreateFile',
                'Str', pipeName, 'UInt', access,
                'UInt', 0, 'Ptr', 0, 'UInt', 0x3,  ; OPEN_EXISTING
                'UInt', 0x80 | (overlapped ? 0x40000000 : 0),  ; FILE_ATTRIBUTE_NORMAL [| FILE_FLAG_OVERLAPPED]
                'Ptr', 0, 'Ptr')
            DllCall('SetHandleInformation', 'Ptr', h, 'UInt', 1, 'UInt', 1)  ; HANDLE_FLAG_INHERIT
            return h
        }

        CreateProcess(cmd) {
            static STARTF_USESTDHANDLES := 0x100
                 , CREATE_NO_WINDOW     := 0x8000000

            STARTUPINFO := Buffer(siSize := A_PtrSize * 9 + 32, 0)
            NumPut('UInt', siSize,               STARTUPINFO)
            NumPut('UInt', STARTF_USESTDHANDLES, STARTUPINFO, A_PtrSize * 4 + 28)
            NumPut('Ptr', this.hInPipeRead, 'Ptr', this.hPipeWrite, 'Ptr', this.hErrPipeWrite,
                   STARTUPINFO, siSize - A_PtrSize * 3)

            PROCESS_INFORMATION := Buffer(A_PtrSize * 2 + 8, 0)
            if !DllCall('CreateProcess',
                'Ptr', 0, 'Str', cmd, 'Ptr', 0, 'Ptr', 0, 'UInt', true,
                'UInt', CREATE_NO_WINDOW, 'Ptr', 0, 'Ptr', 0,
                'Ptr', STARTUPINFO, 'Ptr', PROCESS_INFORMATION)
                return this.Clear()

            ; Close the parent's copies of child-facing handles immediately after spawn.
            ; Keeping hPipeWrite/hErrPipeWrite open would prevent EOF detection;
            ; keeping hInPipeRead open would leak a handle.
            for h in ['hPipeWrite', 'hErrPipeWrite', 'hInPipeRead']
                DllCall('CloseHandle', 'Ptr', this.%h%), this.%h% := 0

            pid := NumGet(PROCESS_INFORMATION, A_PtrSize * 2, 'UInt')
            this.hProcess := NumGet(PROCESS_INFORMATION, 0, 'Ptr')
            DllCall('CloseHandle', 'Ptr', NumGet(PROCESS_INFORMATION, A_PtrSize, 'Ptr'))   ; hThread
            return pid
        }

        GetExitCode() {
            if !this.HasProp('hProcess') || !this.hProcess
                return ''
            if DllCall('WaitForSingleObject', 'Ptr', this.hProcess, 'UInt', 0, 'UInt') != 0
                return ''
            exitCode := 0
            if !DllCall('GetExitCodeProcess', 'Ptr', this.hProcess, 'UInt*', &exitCode)
                return ''
            return exitCode
        }

        TerminateIfRunning() {
            if this.HasProp('hProcess') && this.hProcess
                && DllCall('WaitForSingleObject', 'Ptr', this.hProcess, 'UInt', 0, 'UInt') = 0x102
                DllCall('TerminateProcess', 'Ptr', this.hProcess, 'UInt', 1)
        }

        Clear() {
            for h in ['hPipeRead', 'hPipeReadErr', 'hPipeWrite',
                      'hErrPipeWrite', 'hInPipeWrite', 'hInPipeRead', 'hProcess'] {
                if this.HasProp(h) && this.%h% {
                    DllCall('CloseHandle', 'Ptr', this.%h%)
                    this.%h% := 0
                }
            }
        }
    }
}

; =============================================================================
class AsyncStdinReader
{
    /**
     * Reads inherited stdin asynchronously without blocking the AHK thread.
     * Intended for use in child processes spawned via AsyncProcessIO.
     *
     * The parent writes to stdin via AsyncProcessIO.WriteText / WriteData,
     * and this class picks up the data on the child side without blocking.
     *
     * callback: called when a new data chunk arrives on stdin.
     *     Text mode: callback(str, state)
     *         str   — decoded string (empty on EOF)
     *         state — 0 (data incoming), 1 (EOF)
     *     Raw mode:  callback(buf, state)
     *         buf   — Buffer with raw bytes (Buffer(0) on EOF)
     *         state — 0 (data incoming), 1 (EOF)
     * encoding: text encoding for StrGet; defaults to system OEM codepage.
     * raw:      deliver raw Buffer objects instead of decoded strings.
     * 
     * Version: 1.0.0
     * Date:    2026-04-10
     */

    static BUF_STDIN_SIZE := 0x10000

    __New(callback, encoding?, raw?) {
        encoding := encoding ?? 'cp' . DllCall('GetOEMCP')
        raw      := raw      ?? false

        ; GetStdHandle returns the inherited pipe handle from the parent.
        ; The parent must have created the stdin pipe with FILE_FLAG_OVERLAPPED
        ; (stdinOverlapped := true in AsyncProcessIO) for overlapped reads to work.
        this._hStdin := DllCall('GetStdHandle', 'Int', -10, 'Ptr')  ; STD_INPUT_HANDLE

        this._hEvent := DllCall('CreateEvent', 'Int', 0, 'Int', 0, 'Int', 0, 'Int', 0, 'Ptr')
        buf := Buffer(AsyncStdinReader.BUF_STDIN_SIZE, 0)

        ; No timeout — stdin stays open as long as the parent keeps writing.
        ; The -1 timeout in _onSignal will never fire because StreamReader
        ; passes it to RegisterWaitForSingleObject as INFINITE.
        this._reader := StreamReader(
            this._hStdin, this._hEvent, buf, callback, encoding, raw)
        this._reader.start()
    }

    complete => this._reader.complete

    __Delete() {
        if !this.HasProp('_reader')
            return
        this._reader.prepareDelete()
        Sleep 50
        this._reader.finishDelete()
        DllCall('CloseHandle', 'Ptr', this._hEvent)
    }
}

; =============================================================================
class StreamReader
{
    /**
     * Async reader for a single overlapped pipe. Shared engine used by both
     * AsyncProcessIO (for stdout/stderr) and AsyncStdinReader (for stdin).
     *
     * Does not own any handles — the caller creates and destroys hPipe, hEvent,
     * and buf. This class only manages the OVERLAPPED state, thread-pool waits,
     * and data decoding.
     *
     * hPipe:    overlapped pipe handle to read from.
     * hEvent:   auto-reset event for OVERLAPPED signalling (owned by caller).
     * buf:      read buffer (owned by caller).
     * callback: called on each data chunk or stream event.
     *               Text mode: callback(str, state)
     *               Raw mode:  callback(buf, state)
     *           state: 0 = data incoming, 1 = completed/EOF, -1 = timed out
     * encoding: text encoding for StrGet.
     * raw:      deliver raw Buffer objects instead of decoded strings.
     * timeout:  default wait timeout in ms for RegisterWaitForSingleObject.
     *           -1 = wait indefinitely (INFINITE).
     *
     * Version: 1.0.0
     * Date:    2026-04-10
     */
    __New(hPipe, hEvent, buf, callback, encoding, raw, timeout := -1) {
        this._hPipe       := hPipe
        this._hEvent      := hEvent
        this._buf         := buf
        this._callback    := callback
        this._encoding    := encoding
        this._raw         := raw
        this._timeout     := timeout
        this._complete    := false
        this._gen         := 0
        this._watchdogGen := 0
        this._sentinel    := {alive: true}

        this._overlapped := Buffer(A_PtrSize * 3 + 8, 0)
        this._carry      := Buffer(4, 0)
        this._carrySize  := 0

        ; Watchdog closure — created once, reused by SetTimer on each _registerWait.
        ; Captures a weak reference (raw ObjPtr) + sentinel to avoid preventing GC.
        weakPtr  := ObjPtr(this)
        sentinel := this._sentinel
        this._watchdogFn := () => (
            sentinel.alive && (
                obj := ObjFromPtrAddRef(weakPtr),
                obj._watchdogTick()
            )
        )
    }

    complete => this._complete

    ; Begin the first async read.
    start() {
        switch this._issueRead() {
            case  1 : this._registerWait()      ; ASYNC — waiting for kernel signal
            case -1 : this._onSignal(0, false)  ; SYNC  — data already in pipe buffer
            case  0 :                           ; DONE  — pipe already closed
                this._complete := true
                emptyData := this._raw ? Buffer(0) : ''
                SetTimer(this._callback.Bind(emptyData, 1), -10)
        }
    }

    ; -------------------------------------------------------------------------
    ; ReadFile + OVERLAPPED management
    ; -------------------------------------------------------------------------

    ; Issue an overlapped ReadFile on the pipe.
    ; Returns: 1 (ASYNC — kernel will signal hEvent when data is ready),
    ;         -1 (SYNC  — data was already in the pipe buffer),
    ;          0 (DONE  — pipe closed or unrecoverable error).
    _issueRead() {
        static ERROR_IO_PENDING := 997
        ovlp := this._overlapped
        ; Zero the OVERLAPPED fields before reuse; hEvent is set explicitly below.
        DllCall('RtlZeroMemory', 'Ptr', ovlp, 'Ptr', A_PtrSize * 2 + 8)
        ; Reset the event before issuing ReadFile. When ReadFile completes
        ; synchronously it signals hEvent as a side effect; without this reset
        ; that leftover signal would cause _onSignal to fire spuriously.
        DllCall('ResetEvent', 'Ptr', this._hEvent)
        NumPut('Ptr', this._hEvent, ovlp, A_PtrSize * 2 + 8)  ; OVERLAPPED.hEvent
        ; Request buf.Size-4 bytes, leaving headroom for UTF-8 carry prepend.
        res := DllCall('ReadFile', 'Ptr', this._hPipe,
                       'Ptr', this._buf, 'UInt', this._buf.Size - 4,
                       'UIntP', &size := 0, 'Ptr', ovlp)
        switch {
            case res                            : return -1   ; SYNC
            case A_LastError = ERROR_IO_PENDING : return  1   ; ASYNC
            default                             : return  0   ; DONE
        }
    }

    ; -------------------------------------------------------------------------
    ; Thread-pool wait + watchdog
    ; -------------------------------------------------------------------------

    ; Register a one-shot thread-pool wait for the OVERLAPPED event.
    ; Each registration bumps a generation counter; stale callbacks from
    ; previous registrations silently exit when the generation doesn't match.
    _registerWait(timeout?) {
        if !IsSet(timeout)
            timeout := this._timeout
        gen       := ++this._gen
        this._watchdogGen := gen
        weakPtr   := ObjPtr(this)
        sentinel  := this._sentinel
        ; AsyncWait's active map owns pending registrations, including lost messages.
        ; Replacing our reference alone would leave the previous wait registered.
        if this.HasProp('_regWait')
            this._regWait.Unregister()
        this._regWait := AsyncWait.Register(this._hEvent,
            (handle, timedOut) => (
                sentinel.alive && (
                    obj := ObjFromPtrAddRef(weakPtr),
                    (obj._gen = gen) && (
                        obj._gen++,
                        obj._onSignal(handle, timedOut)
                    )
                )
            ),
            AsyncWait.WT_EXECUTEONLYONCE, timeout, 0)
        ; Watchdog: recover if PostMessageW is lost (e.g. message queue overflow).
        ; The closure is pre-allocated in __New; SetTimer just resets the countdown.
        SetTimer(this._watchdogFn, -500)
    }

    ; If the overlapped IO completed but PostMessageW was lost,
    ; re-enter _onSignal directly to recover.
    _watchdogTick() {
        if this._complete
            return
        if this._gen != this._watchdogGen  ; normal callback already advanced gen
            return
        ; OVERLAPPED.Internal == STATUS_PENDING (0x103) means IO is still
        ; in progress; any other value means it completed but the signal
        ; was lost (e.g. message queue overflow under heavy IO).
        if NumGet(this._overlapped, 0, 'UPtr') != 0x103 {
            this._gen++
            this._onSignal(0, false)
        }
    }

    ; -------------------------------------------------------------------------
    ; Signal handling
    ; -------------------------------------------------------------------------

    ; Entry point when the OVERLAPPED event fires or watchdog recovers.
    _onSignal(handle, timedOut) {
        if timedOut {
            ; Deliver timeout to caller; for AsyncProcessIO the outer
            ; _streamCallback routes this through _handleTimeout which
            ; checks the shared silence timer before actually firing.
            emptyData := this._raw ? Buffer(0) : ''
            SetTimer(this._callback.Bind(emptyData, -1), -10)
            return
        }
        if !DllCall('GetOverlappedResult', 'Ptr', this._hPipe,
                    'Ptr', this._overlapped, 'UIntP', &size := 0, 'UInt', false) {
            this._onReadError()
            return
        }
        this._processData(size)
    }

    ; GetOverlappedResult failed — either a spurious signal or pipe closed.
    _onReadError() {
        ; ERROR_IO_INCOMPLETE: the overlapped operation is still pending.
        ; This can happen if a spurious signal slipped through despite
        ; the ResetEvent guard. Re-register to catch the real completion.
        if A_LastError = 996 {
            this._registerWait()
            return
        }
        this._complete := true
        remainder := this._raw ? Buffer(0) : this._flushCarry()
        SetTimer(this._callback.Bind(remainder, 1), -10)
    }

    ; Data is available — drain all synchronous completions and deliver as one batch.
    _processData(size) {
        if this._raw
            batch := this._drainRaw(size, &pending)
        else
            batch := this._drainText(size, &pending)
        done := (pending = 0)
        if done
            this._complete := true  ; set BEFORE SetTimer — closes the race window
        SetTimer(this._callback.Bind(batch, done ? 1 : 0), -10)
        if !done
            this._registerWait()
    }

    ; -------------------------------------------------------------------------
    ; Data draining
    ; -------------------------------------------------------------------------

    ; Drain all synchronously available data in raw mode.
    ; Returns a single Buffer containing all batched chunks.
    _drainRaw(size, &pending) {
        buf      := this._buf
        batchBuf := Buffer(size)
        DllCall('RtlMoveMemory', 'Ptr', batchBuf, 'Ptr', buf, 'Ptr', size)
        batchPos := size
        pending := this._issueRead()
        while pending = -1 {
            size := NumGet(this._overlapped, A_PtrSize, 'UPtr')
            if batchPos + size > batchBuf.Size {
                newBuf := Buffer(Max(batchBuf.Size * 2, batchPos + size))
                DllCall('RtlMoveMemory', 'Ptr', newBuf, 'Ptr', batchBuf, 'Ptr', batchPos)
                batchBuf := newBuf
            }
            DllCall('RtlMoveMemory', 'Ptr', batchBuf.Ptr + batchPos, 'Ptr', buf, 'Ptr', size)
            batchPos += size
            pending := this._issueRead()
        }
        batchBuf.Size := batchPos
        return batchBuf
    }

    ; Drain all synchronously available data in text mode.
    ; Returns a single string with UTF-8 boundary fixing applied.
    _drainText(size, &pending) {
        size  := this._fixBoundary(size)
        batch := size > 0 ? StrGet(this._buf, size, this._encoding) : ''
        pending := this._issueRead()
        while pending = -1 {
            size  := NumGet(this._overlapped, A_PtrSize, 'UPtr')  ; InternalHigh
            size  := this._fixBoundary(size)
            batch .= size > 0 ? StrGet(this._buf, size, this._encoding) : ''
            pending := this._issueRead()
        }
        ; Flush leftover carry bytes when the pipe is closed
        if pending = 0 {
            remainder := this._flushCarry()
            if remainder != ''
                batch .= remainder
        }
        return batch
    }

    ; -------------------------------------------------------------------------
    ; UTF-8 boundary fixing (text mode only)
    ; -------------------------------------------------------------------------

    ; Prepend carry-over from the previous read and strip any incomplete
    ; trailing UTF-8 sequence. Returns the number of decodable bytes in buf.
    _fixBoundary(size) {
        if !this._isUTF8()
            return size
        carry     := this._carry
        carrySize := this._carrySize
        ; Prepend leftover bytes from the previous read.
        ; RtlMoveMemory is memmove — safe for overlapping regions.
        if carrySize > 0 {
            DllCall('RtlMoveMemory', 'Ptr', this._buf.Ptr + carrySize, 'Ptr', this._buf, 'Ptr', size)
            DllCall('RtlMoveMemory', 'Ptr', this._buf, 'Ptr', carry, 'Ptr', carrySize)
            size += carrySize
        }
        ; Tail scan only when ReadFile filled the buffer completely —
        ; a partial read means the kernel delivered all available data
        ; and the byte sequence is intact.
        maxRead := this._buf.Size - 4
        tail    := size >= maxRead ? this._utf8Tail(this._buf.Ptr, size) : 0
        ; Save incomplete bytes for the next read
        if tail > 0
            DllCall('RtlMoveMemory', 'Ptr', carry, 'Ptr', this._buf.Ptr + size - tail, 'Ptr', tail)
        this._carrySize := tail
        return size - tail
    }

    ; Decode and return any remaining carry-over bytes when a stream completes.
    _flushCarry() {
        if !this._isUTF8()
            return ''
        size := this._carrySize
        if size = 0
            return ''
        this._carrySize := 0
        return StrGet(this._carry, size, this._encoding)
    }

    _isUTF8() => this._encoding ~= 'i)utf-8|cp65001'

    ; Return the number of bytes belonging to an incomplete UTF-8 sequence
    ; at the end of the buffer, or 0 if the boundary is clean.
    _utf8Tail(ptr, size) {
        if size = 0
            return 0
        last := NumGet(ptr + size - 1, 'UChar')
        ; ASCII — no split possible
        if last < 0x80
            return 0
        ; Leading byte with no continuation bytes after it — incomplete
        if last >= 0xC0
            return 1
        ; Continuation byte (10xxxxxx) — scan backward for the leading byte;
        ; a valid UTF-8 sequence is at most 4 bytes, so look back up to 4.
        i     := size - 1
        limit := Max(0, size - 4)
        loop {
            if --i < limit
                return 0  ; no valid leading byte found, likely corrupted
            b := NumGet(ptr + i, 'UChar')
        } until (b & 0xC0) != 0x80
        expected := (b & 0xE0) = 0xC0 ? 2
                  : (b & 0xF0) = 0xE0 ? 3
                  : (b & 0xF8) = 0xF0 ? 4 : 0
        if !expected
            return 0  ; invalid leading byte
        actual := size - i
        return actual < expected ? actual : 0
    }

    ; -------------------------------------------------------------------------
    ; Lifecycle management
    ; -------------------------------------------------------------------------

    ; Step 1 of coordinated cleanup: cancel pending IO and poison the sentinel.
    ; When cleaning up multiple StreamReaders (e.g. stdout+stderr), call
    ; prepareDelete() on all of them first, Sleep 50 once, then finishDelete().
    prepareDelete() {
        if this.HasProp('_cancelled')
            return
        this._cancelled := true
        this._sentinel.alive := false
        SetTimer(this._watchdogFn, 0)
        if !this._complete {
            DllCall('CancelIoEx', 'Ptr', this._hPipe, 'Ptr', this._overlapped)
            DllCall('SetEvent',   'Ptr', this._hEvent)
        }
    }

    ; Step 2 of coordinated cleanup: unregister the thread-pool wait.
    finishDelete() {
        if this.HasProp('_regWait')
            this._regWait.Unregister()
    }

    ; Standalone cleanup — used when only one StreamReader needs to be torn
    ; down (e.g. AsyncStdinReader). Skipped if prepareDelete() was already called.
    __Delete() {
        if this.HasProp('_cancelled')
            return
        this.prepareDelete()
        Sleep 50
        this.finishDelete()
    }
}

class AsyncWait
{
    /**
     * Wraps RegisterWaitForSingleObject so that the system thread-pool callback
     * is safely delivered to the AHK GUI thread via PostMessageW.
     *
     * Public API:
     *     AsyncWait.Register(handle, callback, flags, timeout, completionEvent) -> RegisteredWait
     *         completionEvent: -1 (INVALID_HANDLE_VALUE) — block until callback completes (default)
     *                           0 (NULL) — return immediately, callback may still be running
     *     RegisteredWait.Unregister()
     *
     * Suitable kernel objects:
     *     OVERLAPPED I/O events (files, named pipes, sockets)
     *     Manual/auto-reset events created with CreateEvent
     *     Process/thread handles (wait for exit)
     *     Semaphores, mutexes (wait for release)
     *
     * Lifetime model:
     *     Every registration gets a unique, never reused integer id. The thread-pool
     *     thunk posts only that id (wParam) and reads nothing but constants baked
     *     into its own code, so it never touches AHK-managed memory. The AHK side
     *     resolves the id through the _active map; a message that arrives after
     *     Unregister() (or after the object is gone) is simply ignored.
     *     The map holds a strong reference while the wait is registered, so the
     *     caller does not have to keep the returned object alive. A one-shot wait
     *     (WT_EXECUTEONLYONCE) is dropped from the map once delivered; any other
     *     wait stays there until Unregister() is called.
     *
     * Based on lexikos's code: https://www.autohotkey.com/boards/viewtopic.php?t=110691
     *
     * Version: 1.1.0
     * Date:    2026-09-22
     *     1.1.0 — fix use-after-free when a posted message outlived its
     *             RegisteredWait (crash in _messaged on resume from sleep).
     */

    static WT_EXECUTEDEFAULT      := 0x00000000
         , WT_EXECUTEINWAITTHREAD := 0x00000004
         , WT_EXECUTEONLYONCE     := 0x00000008

    ; Custom window message used to marshal callbacks to the AHK thread
         , WM_ASYNCWAIT_CALLBACK  := 0x5743

         , _inited := false
         , _nextId := 0
         , _active := Map()

    static Register(handle, callback, flags := this.WT_EXECUTEONLYONCE, timeout := -1, completionEvent := -1) {
        this._init()
        id := ++this._nextId
        rw := this.RegisteredWait(id, handle, callback, flags, completionEvent)
        ; Publish before registering: the message cannot be dispatched until this
        ; thread pumps, but keeping the map authoritative from the start is simpler.
        this._active[id] := rw
        if !DllCall('RegisterWaitForSingleObject',
                    'Ptr*', &wh := 0, 'Ptr', handle,
                    'Ptr',  this._waitCallback, 'Ptr', id,
                    'UInt', timeout, 'UInt', flags) {
            err := A_LastError
            this._active.Delete(id)
            rw.callback := ''
            throw OSError(err)
        }
        rw.waitHandle := wh
        return rw
    }

    static _init() {
        static HWND_MESSAGE := -3
        if this._inited
            return
        this._wnd  := Gui()
        DllCall('SetParent', 'Ptr', this._wnd.hwnd, 'Ptr', HWND_MESSAGE)
        this._nmsg := AsyncWait.WM_ASYNCWAIT_CALLBACK
        hLib := DllCall('GetModuleHandle', 'Str', 'user32', 'Ptr')
        pm   := DllCall('GetProcAddress', 'Ptr', hLib, 'AStr', 'PostMessageW', 'Ptr')
        this._waitCallback := this._buildThunk(pm, this._wnd.hwnd, this._nmsg)
        OnMessage(this._nmsg, ObjBindMethod(this, '_messaged'), 255)
        this._inited := true
    }

    /**
     * Builds the WAITORTIMERCALLBACK thunk with PostMessageW, hwnd and msg
     * embedded as immediates. Context carries the registration id.
     *
     * VOID CALLBACK WaitCallback(PVOID id, BOOLEAN waitFired) {
     *     PostMessageW(HWND_CONST, MSG_CONST, (WPARAM)id, (LPARAM)waitFired);
     * }
     * ---- 64-bit (tail call, caller's shadow space is reused)
     * 00  44 0F B6 CA        movzx r9d, dl        ; lParam = waitFired
     * 04  4C 8B C1           mov   r8, rcx        ; wParam = id
     * 07  BA imm32           mov   edx, msg
     * 0C  48 B9 imm64        mov   rcx, hwnd
     * 16  48 B8 imm64        mov   rax, PostMessageW
     * 20  FF E0              jmp   rax
     * ---- 32-bit (stdcall)
     * 00  0F B6 44 24 08     movzx eax, byte [esp+8]  ; waitFired
     * 05  50                 push  eax                ; lParam
     * 06  FF 74 24 08        push  dword [esp+8]      ; wParam = id
     * 0A  68 imm32           push  msg
     * 0F  68 imm32           push  hwnd
     * 14  B8 imm32           mov   eax, PostMessageW
     * 19  FF D0              call  eax
     * 1B  C2 08 00           ret   8
     *
     * The code block is allocated once and never freed: a thread-pool callback
     * may still be executing it after UnregisterWaitEx(wh, NULL) returns.
     */
    static _buildThunk(pm, hwnd, msg) {
        static MEM_COMMIT := 0x1000, MEM_RESERVE := 0x2000
             , PAGE_READWRITE := 0x04, PAGE_EXECUTE_READ := 0x20
        if A_PtrSize = 8 {
            hex  := '440FB6CA' . '4C8BC1' . 'BA00000000'
                  . '48B90000000000000000' . '48B80000000000000000' . 'FFE0'
            imms := [[0x08, 'UInt', msg], [0x0E, 'Ptr', hwnd], [0x18, 'Ptr', pm]]
        } else {
            hex  := '0FB6442408' . '50' . 'FF742408'
                  . '6800000000' . '6800000000' . 'B800000000' . 'FFD0' . 'C20800'
            imms := [[0x0B, 'UInt', msg], [0x10, 'Ptr', hwnd], [0x15, 'Ptr', pm]]
        }
        size := StrLen(hex) // 2
        p := DllCall('VirtualAlloc', 'Ptr', 0, 'Ptr', size,
                     'UInt', MEM_COMMIT | MEM_RESERVE, 'UInt', PAGE_READWRITE, 'Ptr')
        if !p
            throw OSError()
        loop size
            NumPut('UChar', Integer('0x' . SubStr(hex, A_Index * 2 - 1, 2)), p, A_Index - 1)
        for imm in imms
            NumPut(imm[2], imm[3], p, imm[1])
        DllCall('VirtualProtect', 'Ptr', p, 'Ptr', size, 'UInt', PAGE_EXECUTE_READ, 'UInt*', 0)
        DllCall('FlushInstructionCache', 'Ptr', DllCall('GetCurrentProcess', 'Ptr'), 'Ptr', p, 'Ptr', size)
        return p
    }

    static _messaged(wParam, lParam, nmsg, hwnd) {
        if hwnd != this._wnd.hwnd
            return
        ; Stale message: the wait was unregistered after the callback had
        ; already posted. Nothing to deliver, and nothing unsafe was read.
        if !this._active.Has(wParam)
            return 0
        rw := this._active[wParam]
        if rw.flags & this.WT_EXECUTEONLYONCE
            this._active.Delete(wParam)
        try (rw.callback)(rw.handle, lParam)
        return 0
    }

    ; -------------------------------------------------------------------------
    class RegisteredWait {
        static prototype.waitHandle := 0

        __New(id, handle, callback, flags, completionEvent) {
            this.id              := id
            this.handle          := handle
            this.callback        := callback
            this.flags           := flags
            this.completionEvent := completionEvent
        }

        __Delete() => this.Unregister()

        Unregister() {
            wh := this.waitHandle, this.waitHandle := 0
            ; Any message still queued for this id will be ignored from now on.
            if AsyncWait._active.Has(this.id)
                AsyncWait._active.Delete(this.id)
            (wh) && DllCall('UnregisterWaitEx', 'Ptr', wh, 'Ptr', this.completionEvent)
            this.callback := ''
        }
    }
}

; ============================================================================
; Встроенные ресурсы ленты (ui\chat.css, ui\chat.js, ui\marked.js)
; ============================================================================

EmbeddedChatCss() {
    return "
( LTrim0 RTrim0 `
/* Лента сообщений GigaChatDialog. Значения в px масштабируются скриптом под DPI. */
* { box-sizing: border-box; }
html, body {
    margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden;
    background: #ffffff; color: #1f2328;
    font-family: "Segoe UI", Tahoma, sans-serif; font-size: 13px; line-height: 1.4;
}
#feed {
    position: relative; height: 100%; overflow-y: auto; overflow-x: hidden;
    padding: 10px 12px 4px 12px;
}

/* Карточка системного промпта */
.system {
    margin: 0 0 12px 0; padding: 6px 10px;
    border: 1px dashed #c4cad3; border-radius: 6px; background: #fafbfc;
    color: #57606a; font-size: 12px;
}
.system-label { font-weight: bold; margin-bottom: 2px; }
.system-text { white-space: pre-wrap; word-wrap: break-word; max-height: 96px; overflow-y: auto; }
.system-text.empty { font-style: italic; }

/* Служебные сообщения программы */
.notice {
    margin: 0 0 12px 0; padding: 6px 10px; border-radius: 6px;
    background: #f6f8fa; color: #57606a; font-size: 12px; white-space: pre-wrap; word-wrap: break-word;
}
.notice-error { background: #fff4e5; color: #8a4b00; border: 1px solid #f5d9a8; }

/* Разделитель «контекст сброшен» */
.divider { position: relative; margin: 14px 0; text-align: center; font-size: 11px; color: #8b949e; }
.divider:before {
    content: ""; position: absolute; left: 0; right: 0; top: 50%;
    border-top: 1px solid #e1e4e8;
}
.divider span { position: relative; padding: 0 8px; background: #ffffff; }

/* Сообщения */
.msg { margin: 0 0 10px 0; overflow: hidden; }
.bubble { padding: 6px 10px 7px 10px; border: 1px solid transparent; }
.msg-user .bubble {
    float: right; max-width: 80%;
    background: #dbeafe; border-color: #bcd5f5; border-radius: 10px 10px 2px 10px;
}
.msg-assistant .bubble {
    float: left; max-width: 90%;
    background: #f4f5f7; border-color: #e1e4e8; border-radius: 10px 10px 10px 2px;
}
.msg-assistant.error .bubble { background: #fdecea; border-color: #f3c2bf; color: #86181d; }
.msg-assistant.cancelled .bubble { background: #f6f8fa; color: #8b949e; font-style: italic; }
.meta { margin-bottom: 3px; font-size: 11px; color: #6a737d; }
.msg-user .meta { text-align: right; }
.copy { margin-left: 10px; color: #0969da; cursor: pointer; }
.copy:hover { text-decoration: underline; }
.text-plain { white-space: pre-wrap; word-wrap: break-word; }

/* Индикатор ожидания ответа */
.typing span { display: inline-block; width: 6px; height: 6px; margin-right: 3px;
    border-radius: 3px; background: #8b949e; animation: chat-blink 1.4s infinite both; }
.typing .d2 { animation-delay: 0.2s; }
.typing .d3 { animation-delay: 0.4s; }
@keyframes chat-blink { 0% { opacity: 0.2; } 20% { opacity: 1; } 100% { opacity: 0.2; } }

/* Markdown в ответах модели */
.md { word-wrap: break-word; }
.md p { margin: 0 0 6px 0; }
.md > :last-child { margin-bottom: 0; }
.md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { margin: 8px 0 4px 0; font-size: 14px; }
.md h1 { font-size: 16px; }
.md ul, .md ol { margin: 0 0 6px 0; padding-left: 22px; }
.md li { margin: 1px 0; }
.md blockquote { margin: 0 0 6px 0; padding-left: 8px; border-left: 3px solid #d0d7de; color: #57606a; }
.md code { font-family: Consolas, "Courier New", monospace; font-size: 12px;
    background: #e8eaed; padding: 0 3px; border-radius: 3px; }
.md pre { margin: 0 0 6px 0; padding: 6px 8px; overflow-x: auto;
    background: #ffffff; border: 1px solid #e1e4e8; border-radius: 4px; }
.md pre code { background: none; padding: 0; white-space: pre; }
.md table { border-collapse: collapse; margin: 0 0 6px 0; }
.md th, .md td { border: 1px solid #d0d7de; padding: 3px 6px; }
.md th { background: #eef0f3; }
.md a { color: #0969da; }
.md hr { border: 0; border-top: 1px solid #d0d7de; margin: 8px 0; }
)"
}

EmbeddedChatJs() {
    return "
( LTrim0 RTrim0 `
// Лента сообщений GigaChatDialog (движок IE/MSHTML, только ES5).
// AHK вызывает функции chat*; идентификаторы сообщений выдаёт AHK.

// Полифиллы: без открытых средств разработчика console в MSHTML может отсутствовать,
// а marked вызывает trimRight, которого нет в старом JScript.
if (!window.console) {
    window.console = { log: function () {}, warn: function () {}, error: function () {} };
}
if (!String.prototype.trimRight) {
    String.prototype.trimRight = function () { return this.replace(/\s+$/, ''); };
}

var chatFeed = null;
var chatRawTexts = {};
var chatAtBottom = true;

function chatInit() {
    chatFeed = document.getElementById('feed');
    chatFeed.onscroll = function () {
        chatAtBottom = chatFeed.scrollHeight - chatFeed.scrollTop - chatFeed.clientHeight < 4;
    };
    document.body.onclick = chatOnClick;
}

// Вызывается из AHK после изменения размера элемента: перестраивает ленту,
// чтобы MSHTML не оставлял следов старого изображения, и сохраняет позицию:
// если лента была прокручена до конца, остаётся прижатой к последнему сообщению.
function chatRefresh() {
    if (!chatFeed)
        return;
    var top = chatFeed.scrollTop;
    var stick = chatAtBottom;
    chatFeed.style.display = 'none';
    var unused = chatFeed.offsetHeight;
    chatFeed.style.display = '';
    if (stick)
        chatScrollToEnd();
    else
        chatFeed.scrollTop = top;
    chatAtBottom = stick;
}

function chatEl(tag, cls, text) {
    var node = document.createElement(tag);
    if (cls)
        node.className = cls;
    if (text !== undefined && text !== null)
        node.appendChild(document.createTextNode(String(text)));
    return node;
}

function chatScrollToEnd() {
    chatFeed.scrollTop = chatFeed.scrollHeight;
}

// Длинный ответ показываем с начала, короткий — просто прокручиваем вниз.
function chatRevealAnswer(row) {
    if (row.offsetHeight > chatFeed.clientHeight - 20)
        chatFeed.scrollTop = row.offsetTop - 8;
    else
        chatScrollToEnd();
}

function chatAddSystem(text) {
    var box = chatEl('div', 'system');
    box.appendChild(chatEl('div', 'system-label', 'Системный промпт'));
    if (text)
        box.appendChild(chatEl('div', 'system-text', text));
    else
        box.appendChild(chatEl('div', 'system-text empty', 'не задан'));
    chatFeed.appendChild(box);
    chatScrollToEnd();
}

function chatAddDivider(text) {
    var line = chatEl('div', 'divider');
    line.appendChild(chatEl('span', null, text));
    chatFeed.appendChild(line);
    chatScrollToEnd();
}

function chatAddUser(id, text, meta) {
    var row = chatEl('div', 'msg msg-user');
    row.id = 'm' + id;
    var bubble = chatEl('div', 'bubble');
    bubble.appendChild(chatEl('div', 'meta', meta));
    bubble.appendChild(chatEl('div', 'text-plain', text));
    row.appendChild(bubble);
    chatFeed.appendChild(row);
    chatScrollToEnd();
}

function chatAddPending(id, label) {
    var row = chatEl('div', 'msg msg-assistant pending');
    row.id = 'm' + id;
    var bubble = chatEl('div', 'bubble');
    bubble.appendChild(chatEl('div', 'meta', label || 'GigaChat'));
    var dots = chatEl('div', 'typing');
    dots.appendChild(chatEl('span', 'd1'));
    dots.appendChild(chatEl('span', 'd2'));
    dots.appendChild(chatEl('span', 'd3'));
    bubble.appendChild(dots);
    row.appendChild(bubble);
    chatFeed.appendChild(row);
    chatScrollToEnd();
}

function chatResetRow(id, cls) {
    var row = document.getElementById('m' + id);
    if (!row)
        return null;
    row.className = cls;
    while (row.firstChild)
        row.removeChild(row.firstChild);
    return row;
}

function chatResolve(id, markdown, meta) {
    var row = chatResetRow(id, 'msg msg-assistant');
    if (!row)
        return;
    chatRawTexts[id] = markdown;
    var bubble = chatEl('div', 'bubble');
    var metaLine = chatEl('div', 'meta', meta);
    var copy = chatEl('span', 'copy', 'копировать');
    copy.setAttribute('data-role', 'copy');
    copy.setAttribute('data-id', String(id));
    metaLine.appendChild(copy);
    bubble.appendChild(metaLine);
    var body = chatEl('div', 'md');
    body.innerHTML = chatRenderMarkdown(markdown);
    bubble.appendChild(body);
    row.appendChild(bubble);
    chatRevealAnswer(row);
}

function chatFail(id, message, kind, label) {
    var row = chatResetRow(id, 'msg msg-assistant ' + (kind === 'cancel' ? 'cancelled' : 'error'));
    if (!row)
        return;
    var bubble = chatEl('div', 'bubble');
    bubble.appendChild(chatEl('div', 'meta', label || 'GigaChat'));
    bubble.appendChild(chatEl('div', 'text-plain', message));
    row.appendChild(bubble);
    chatScrollToEnd();
}

// Служебное сообщение программы (не модели), например об ошибке загрузки списка моделей.
function chatAddNotice(text, kind) {
    var box = chatEl('div', 'notice' + (kind === 'error' ? ' notice-error' : ''), text);
    chatFeed.appendChild(box);
    chatScrollToEnd();
}

function chatClear() {
    while (chatFeed.firstChild)
        chatFeed.removeChild(chatFeed.firstChild);
    chatRawTexts = {};
}

// sanitize экранирует сырой HTML из ответа модели и отбрасывает ссылки javascript:,
// silent отключает предупреждение marked об устаревшей опции.
function chatRenderMarkdown(markdown) {
    try {
        return marked(markdown, {
            gfm: true, breaks: true, sanitize: true, silent: true,
            headerIds: false, mangle: false
        });
    } catch (e) {
        var holder = document.createElement('div');
        holder.appendChild(document.createTextNode(markdown));
        return '<div class="text-plain">' + holder.innerHTML + '</div>';
    }
}

// Клик по «копировать»: текст кладём в window.copyText, AHK забирает его
// после навигации на ahk:copy (перехват в BeforeNavigate2).
function chatOnClick(e) {
    e = e || window.event;
    var node = e.target || e.srcElement;
    while (node && node !== document.body) {
        if (node.getAttribute && node.getAttribute('data-role') === 'copy') {
            window.copyText = chatRawTexts[node.getAttribute('data-id')] || '';
            window.location.href = 'ahk:copy';
            chatFlashCopied(node);
            if (e.preventDefault)
                e.preventDefault();
            e.returnValue = false;
            return false;
        }
        node = node.parentNode;
    }
}

function chatFlashCopied(node) {
    node.innerText = 'скопировано';
    setTimeout(function () { node.innerText = 'копировать'; }, 1500);
}
)"
}

EmbeddedMarkedJs() {
    return "
( LTrim0 RTrim0 `
/**
 * marked - a markdown parser
 * Copyright (c) 2011-2020, Christopher Jeffrey. (MIT Licensed)
 * https://github.com/markedjs/marked
 */

/**
 * DO NOT EDIT THIS FILE
 * The code in this file is generated from files in ./src/
 */

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global = global || self, global.marked = factory());
}(this, (function () { 'use strict';

  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }

  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
  }

  function createCommonjsModule(fn, module) {
  	return module = { exports: {} }, fn(module, module.exports), module.exports;
  }

  var defaults = createCommonjsModule(function (module) {
    function getDefaults() {
      return {
        baseUrl: null,
        breaks: false,
        gfm: true,
        headerIds: true,
        headerPrefix: '',
        highlight: null,
        langPrefix: 'language-',
        mangle: true,
        pedantic: false,
        renderer: null,
        sanitize: false,
        sanitizer: null,
        silent: false,
        smartLists: false,
        smartypants: false,
        tokenizer: null,
        xhtml: false
      };
    }

    function changeDefaults(newDefaults) {
      module.exports.defaults = newDefaults;
    }

    module.exports = {
      defaults: getDefaults(),
      getDefaults: getDefaults,
      changeDefaults: changeDefaults
    };
  });
  var defaults_1 = defaults.defaults;
  var defaults_2 = defaults.getDefaults;
  var defaults_3 = defaults.changeDefaults;

  /**
   * Helpers
   */
  var escapeTest = /[&<>"']/;
  var escapeReplace = /[&<>"']/g;
  var escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
  var escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
  var escapeReplacements = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;'
  };

  var getEscapeReplacement = function getEscapeReplacement(ch) {
    return escapeReplacements[ch];
  };

  function escape(html, encode) {
    if (encode) {
      if (escapeTest.test(html)) {
        return html.replace(escapeReplace, getEscapeReplacement);
      }
    } else {
      if (escapeTestNoEncode.test(html)) {
        return html.replace(escapeReplaceNoEncode, getEscapeReplacement);
      }
    }

    return html;
  }

  var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;

  function unescape(html) {
    // explicitly match decimal, hex, and named HTML entities
    return html.replace(unescapeTest, function (_, n) {
      n = n.toLowerCase();
      if (n === 'colon') return ':';

      if (n.charAt(0) === '#') {
        return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1));
      }

      return '';
    });
  }

  var caret = /(^|[^\[])\^/g;

  function edit(regex, opt) {
    regex = regex.source || regex;
    opt = opt || '';
    var obj = {
      replace: function replace(name, val) {
        val = val.source || val;
        val = val.replace(caret, '$1');
        regex = regex.replace(name, val);
        return obj;
      },
      getRegex: function getRegex() {
        return new RegExp(regex, opt);
      }
    };
    return obj;
  }

  var nonWordAndColonTest = /[^\w:]/g;
  var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;

  function cleanUrl(sanitize, base, href) {
    if (sanitize) {
      var prot;

      try {
        prot = decodeURIComponent(unescape(href)).replace(nonWordAndColonTest, '').toLowerCase();
      } catch (e) {
        return null;
      }

      if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
        return null;
      }
    }

    if (base && !originIndependentUrl.test(href)) {
      href = resolveUrl(base, href);
    }

    try {
      href = encodeURI(href).replace(/%25/g, '%');
    } catch (e) {
      return null;
    }

    return href;
  }

  var baseUrls = {};
  var justDomain = /^[^:]+:\/*[^/]*$/;
  var protocol = /^([^:]+:)[\s\S]*$/;
  var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/;

  function resolveUrl(base, href) {
    if (!baseUrls[' ' + base]) {
      // we can ignore everything in base after the last slash of its path component,
      // but we might need to add _that_
      // https://tools.ietf.org/html/rfc3986#section-3
      if (justDomain.test(base)) {
        baseUrls[' ' + base] = base + '/';
      } else {
        baseUrls[' ' + base] = rtrim(base, '/', true);
      }
    }

    base = baseUrls[' ' + base];
    var relativeBase = base.indexOf(':') === -1;

    if (href.substring(0, 2) === '//') {
      if (relativeBase) {
        return href;
      }

      return base.replace(protocol, '$1') + href;
    } else if (href.charAt(0) === '/') {
      if (relativeBase) {
        return href;
      }

      return base.replace(domain, '$1') + href;
    } else {
      return base + href;
    }
  }

  var noopTest = {
    exec: function noopTest() {}
  };

  function merge(obj) {
    var i = 1,
        target,
        key;

    for (; i < arguments.length; i++) {
      target = arguments[i];

      for (key in target) {
        if (Object.prototype.hasOwnProperty.call(target, key)) {
          obj[key] = target[key];
        }
      }
    }

    return obj;
  }

  function splitCells(tableRow, count) {
    // ensure that every cell-delimiting pipe has a space
    // before it to distinguish it from an escaped pipe
    var row = tableRow.replace(/\|/g, function (match, offset, str) {
      var escaped = false,
          curr = offset;

      while (--curr >= 0 && str[curr] === '\\') {
        escaped = !escaped;
      }

      if (escaped) {
        // odd number of slashes means | is escaped
        // so we leave it alone
        return '|';
      } else {
        // add space before unescaped |
        return ' |';
      }
    }),
        cells = row.split(/ \|/);
    var i = 0;

    if (cells.length > count) {
      cells.splice(count);
    } else {
      while (cells.length < count) {
        cells.push('');
      }
    }

    for (; i < cells.length; i++) {
      // leading or trailing whitespace is ignored per the gfm spec
      cells[i] = cells[i].trim().replace(/\\\|/g, '|');
    }

    return cells;
  } // Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
  // /c*$/ is vulnerable to REDOS.
  // invert: Remove suffix of non-c chars instead. Default falsey.


  function rtrim(str, c, invert) {
    var l = str.length;

    if (l === 0) {
      return '';
    } // Length of suffix matching the invert condition.


    var suffLen = 0; // Step left until we fail to match the invert condition.

    while (suffLen < l) {
      var currChar = str.charAt(l - suffLen - 1);

      if (currChar === c && !invert) {
        suffLen++;
      } else if (currChar !== c && invert) {
        suffLen++;
      } else {
        break;
      }
    }

    return str.substr(0, l - suffLen);
  }

  function findClosingBracket(str, b) {
    if (str.indexOf(b[1]) === -1) {
      return -1;
    }

    var l = str.length;
    var level = 0,
        i = 0;

    for (; i < l; i++) {
      if (str[i] === '\\') {
        i++;
      } else if (str[i] === b[0]) {
        level++;
      } else if (str[i] === b[1]) {
        level--;

        if (level < 0) {
          return i;
        }
      }
    }

    return -1;
  }

  function checkSanitizeDeprecation(opt) {
    if (opt && opt.sanitize && !opt.silent) {
      console.warn('marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options');
    }
  }

  var helpers = {
    escape: escape,
    unescape: unescape,
    edit: edit,
    cleanUrl: cleanUrl,
    resolveUrl: resolveUrl,
    noopTest: noopTest,
    merge: merge,
    splitCells: splitCells,
    rtrim: rtrim,
    findClosingBracket: findClosingBracket,
    checkSanitizeDeprecation: checkSanitizeDeprecation
  };

  var defaults$1 = defaults.defaults;
  var rtrim$1 = helpers.rtrim,
      splitCells$1 = helpers.splitCells,
      _escape = helpers.escape,
      findClosingBracket$1 = helpers.findClosingBracket;

  function outputLink(cap, link, raw) {
    var href = link.href;
    var title = link.title ? _escape(link.title) : null;

    if (cap[0].charAt(0) !== '!') {
      return {
        type: 'link',
        raw: raw,
        href: href,
        title: title,
        text: cap[1]
      };
    } else {
      return {
        type: 'image',
        raw: raw,
        text: _escape(cap[1]),
        href: href,
        title: title
      };
    }
  }
  /**
   * Tokenizer
   */


  var Tokenizer_1 = /*#__PURE__*/function () {
    function Tokenizer(options) {
      this.options = options || defaults$1;
    }

    var _proto = Tokenizer.prototype;

    _proto.space = function space(src) {
      var cap = this.rules.block.newline.exec(src);

      if (cap) {
        if (cap[0].length > 1) {
          return {
            type: 'space',
            raw: cap[0]
          };
        }

        return {
          raw: '\n'
        };
      }
    };

    _proto.code = function code(src, tokens) {
      var cap = this.rules.block.code.exec(src);

      if (cap) {
        var lastToken = tokens[tokens.length - 1]; // An indented code block cannot interrupt a paragraph.

        if (lastToken && lastToken.type === 'paragraph') {
          tokens.pop();
          lastToken.text += '\n' + cap[0].trimRight();
          lastToken.raw += '\n' + cap[0];
          return lastToken;
        } else {
          var text = cap[0].replace(/^ {4}/gm, '');
          return {
            type: 'code',
            raw: cap[0],
            codeBlockStyle: 'indented',
            text: !this.options.pedantic ? rtrim$1(text, '\n') : text
          };
        }
      }
    };

    _proto.fences = function fences(src) {
      var cap = this.rules.block.fences.exec(src);

      if (cap) {
        return {
          type: 'code',
          raw: cap[0],
          lang: cap[2] ? cap[2].trim() : cap[2],
          text: cap[3] || ''
        };
      }
    };

    _proto.heading = function heading(src) {
      var cap = this.rules.block.heading.exec(src);

      if (cap) {
        return {
          type: 'heading',
          raw: cap[0],
          depth: cap[1].length,
          text: cap[2]
        };
      }
    };

    _proto.nptable = function nptable(src) {
      var cap = this.rules.block.nptable.exec(src);

      if (cap) {
        var item = {
          type: 'table',
          header: splitCells$1(cap[1].replace(/^ *| *\| *$/g, '')),
          align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
          cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : [],
          raw: cap[0]
        };

        if (item.header.length === item.align.length) {
          var l = item.align.length;
          var i;

          for (i = 0; i < l; i++) {
            if (/^ *-+: *$/.test(item.align[i])) {
              item.align[i] = 'right';
            } else if (/^ *:-+: *$/.test(item.align[i])) {
              item.align[i] = 'center';
            } else if (/^ *:-+ *$/.test(item.align[i])) {
              item.align[i] = 'left';
            } else {
              item.align[i] = null;
            }
          }

          l = item.cells.length;

          for (i = 0; i < l; i++) {
            item.cells[i] = splitCells$1(item.cells[i], item.header.length);
          }

          return item;
        }
      }
    };

    _proto.hr = function hr(src) {
      var cap = this.rules.block.hr.exec(src);

      if (cap) {
        return {
          type: 'hr',
          raw: cap[0]
        };
      }
    };

    _proto.blockquote = function blockquote(src) {
      var cap = this.rules.block.blockquote.exec(src);

      if (cap) {
        var text = cap[0].replace(/^ *> ?/gm, '');
        return {
          type: 'blockquote',
          raw: cap[0],
          text: text
        };
      }
    };

    _proto.list = function list(src) {
      var cap = this.rules.block.list.exec(src);

      if (cap) {
        var raw = cap[0];
        var bull = cap[2];
        var isordered = bull.length > 1;
        var list = {
          type: 'list',
          raw: raw,
          ordered: isordered,
          start: isordered ? +bull : '',
          loose: false,
          items: []
        }; // Get each top-level item.

        var itemMatch = cap[0].match(this.rules.block.item);
        var next = false,
            item,
            space,
            b,
            addBack,
            loose,
            istask,
            ischecked;
        var l = itemMatch.length;

        for (var i = 0; i < l; i++) {
          item = itemMatch[i];
          raw = item; // Remove the list item's bullet
          // so it is seen as the next token.

          space = item.length;
          item = item.replace(/^ *([*+-]|\d+\.) */, ''); // Outdent whatever the
          // list item contains. Hacky.

          if (~item.indexOf('\n ')) {
            space -= item.length;
            item = !this.options.pedantic ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') : item.replace(/^ {1,4}/gm, '');
          } // Determine whether the next list item belongs here.
          // Backpedal if it does not belong in this list.


          if (i !== l - 1) {
            b = this.rules.block.bullet.exec(itemMatch[i + 1])[0];

            if (bull.length > 1 ? b.length === 1 : b.length > 1 || this.options.smartLists && b !== bull) {
              addBack = itemMatch.slice(i + 1).join('\n');
              list.raw = list.raw.substring(0, list.raw.length - addBack.length);
              i = l - 1;
            }
          } // Determine whether item is loose or not.
          // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
          // for discount behavior.


          loose = next || /\n\n(?!\s*$)/.test(item);

          if (i !== l - 1) {
            next = item.charAt(item.length - 1) === '\n';
            if (!loose) loose = next;
          }

          if (loose) {
            list.loose = true;
          } // Check for task list items


          istask = /^\[[ xX]\] /.test(item);
          ischecked = undefined;

          if (istask) {
            ischecked = item[1] !== ' ';
            item = item.replace(/^\[[ xX]\] +/, '');
          }

          list.items.push({
            raw: raw,
            task: istask,
            checked: ischecked,
            loose: loose,
            text: item
          });
        }

        return list;
      }
    };

    _proto.html = function html(src) {
      var cap = this.rules.block.html.exec(src);

      if (cap) {
        return {
          type: this.options.sanitize ? 'paragraph' : 'html',
          raw: cap[0],
          pre: !this.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
          text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0]
        };
      }
    };

    _proto.def = function def(src) {
      var cap = this.rules.block.def.exec(src);

      if (cap) {
        if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1);
        var tag = cap[1].toLowerCase().replace(/\s+/g, ' ');
        return {
          tag: tag,
          raw: cap[0],
          href: cap[2],
          title: cap[3]
        };
      }
    };

    _proto.table = function table(src) {
      var cap = this.rules.block.table.exec(src);

      if (cap) {
        var item = {
          type: 'table',
          header: splitCells$1(cap[1].replace(/^ *| *\| *$/g, '')),
          align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
          cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : []
        };

        if (item.header.length === item.align.length) {
          item.raw = cap[0];
          var l = item.align.length;
          var i;

          for (i = 0; i < l; i++) {
            if (/^ *-+: *$/.test(item.align[i])) {
              item.align[i] = 'right';
            } else if (/^ *:-+: *$/.test(item.align[i])) {
              item.align[i] = 'center';
            } else if (/^ *:-+ *$/.test(item.align[i])) {
              item.align[i] = 'left';
            } else {
              item.align[i] = null;
            }
          }

          l = item.cells.length;

          for (i = 0; i < l; i++) {
            item.cells[i] = splitCells$1(item.cells[i].replace(/^ *\| *| *\| *$/g, ''), item.header.length);
          }

          return item;
        }
      }
    };

    _proto.lheading = function lheading(src) {
      var cap = this.rules.block.lheading.exec(src);

      if (cap) {
        return {
          type: 'heading',
          raw: cap[0],
          depth: cap[2].charAt(0) === '=' ? 1 : 2,
          text: cap[1]
        };
      }
    };

    _proto.paragraph = function paragraph(src) {
      var cap = this.rules.block.paragraph.exec(src);

      if (cap) {
        return {
          type: 'paragraph',
          raw: cap[0],
          text: cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1]
        };
      }
    };

    _proto.text = function text(src) {
      var cap = this.rules.block.text.exec(src);

      if (cap) {
        return {
          type: 'text',
          raw: cap[0],
          text: cap[0]
        };
      }
    };

    _proto.escape = function escape(src) {
      var cap = this.rules.inline.escape.exec(src);

      if (cap) {
        return {
          type: 'escape',
          raw: cap[0],
          text: _escape(cap[1])
        };
      }
    };

    _proto.tag = function tag(src, inLink, inRawBlock) {
      var cap = this.rules.inline.tag.exec(src);

      if (cap) {
        if (!inLink && /^<a /i.test(cap[0])) {
          inLink = true;
        } else if (inLink && /^<\/a>/i.test(cap[0])) {
          inLink = false;
        }

        if (!inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
          inRawBlock = true;
        } else if (inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
          inRawBlock = false;
        }

        return {
          type: this.options.sanitize ? 'text' : 'html',
          raw: cap[0],
          inLink: inLink,
          inRawBlock: inRawBlock,
          text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0]
        };
      }
    };

    _proto.link = function link(src) {
      var cap = this.rules.inline.link.exec(src);

      if (cap) {
        var lastParenIndex = findClosingBracket$1(cap[2], '()');

        if (lastParenIndex > -1) {
          var start = cap[0].indexOf('!') === 0 ? 5 : 4;
          var linkLen = start + cap[1].length + lastParenIndex;
          cap[2] = cap[2].substring(0, lastParenIndex);
          cap[0] = cap[0].substring(0, linkLen).trim();
          cap[3] = '';
        }

        var href = cap[2];
        var title = '';

        if (this.options.pedantic) {
          var link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);

          if (link) {
            href = link[1];
            title = link[3];
          } else {
            title = '';
          }
        } else {
          title = cap[3] ? cap[3].slice(1, -1) : '';
        }

        href = href.trim().replace(/^<([\s\S]*)>$/, '$1');
        var token = outputLink(cap, {
          href: href ? href.replace(this.rules.inline._escapes, '$1') : href,
          title: title ? title.replace(this.rules.inline._escapes, '$1') : title
        }, cap[0]);
        return token;
      }
    };

    _proto.reflink = function reflink(src, links) {
      var cap;

      if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
        var link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
        link = links[link.toLowerCase()];

        if (!link || !link.href) {
          var text = cap[0].charAt(0);
          return {
            type: 'text',
            raw: text,
            text: text
          };
        }

        var token = outputLink(cap, link, cap[0]);
        return token;
      }
    };

    _proto.strong = function strong(src) {
      var cap = this.rules.inline.strong.exec(src);

      if (cap) {
        return {
          type: 'strong',
          raw: cap[0],
          text: cap[4] || cap[3] || cap[2] || cap[1]
        };
      }
    };

    _proto.em = function em(src) {
      var cap = this.rules.inline.em.exec(src);

      if (cap) {
        return {
          type: 'em',
          raw: cap[0],
          text: cap[6] || cap[5] || cap[4] || cap[3] || cap[2] || cap[1]
        };
      }
    };

    _proto.codespan = function codespan(src) {
      var cap = this.rules.inline.code.exec(src);

      if (cap) {
        return {
          type: 'codespan',
          raw: cap[0],
          text: _escape(cap[2].trim(), true)
        };
      }
    };

    _proto.br = function br(src) {
      var cap = this.rules.inline.br.exec(src);

      if (cap) {
        return {
          type: 'br',
          raw: cap[0]
        };
      }
    };

    _proto.del = function del(src) {
      var cap = this.rules.inline.del.exec(src);

      if (cap) {
        return {
          type: 'del',
          raw: cap[0],
          text: cap[1]
        };
      }
    };

    _proto.autolink = function autolink(src, mangle) {
      var cap = this.rules.inline.autolink.exec(src);

      if (cap) {
        var text, href;

        if (cap[2] === '@') {
          text = _escape(this.options.mangle ? mangle(cap[1]) : cap[1]);
          href = 'mailto:' + text;
        } else {
          text = _escape(cap[1]);
          href = text;
        }

        return {
          type: 'link',
          raw: cap[0],
          text: text,
          href: href,
          tokens: [{
            type: 'text',
            raw: text,
            text: text
          }]
        };
      }
    };

    _proto.url = function url(src, mangle) {
      var cap;

      if (cap = this.rules.inline.url.exec(src)) {
        var text, href;

        if (cap[2] === '@') {
          text = _escape(this.options.mangle ? mangle(cap[0]) : cap[0]);
          href = 'mailto:' + text;
        } else {
          // do extended autolink path validation
          var prevCapZero;

          do {
            prevCapZero = cap[0];
            cap[0] = this.rules.inline._backpedal.exec(cap[0])[0];
          } while (prevCapZero !== cap[0]);

          text = _escape(cap[0]);

          if (cap[1] === 'www.') {
            href = 'http://' + text;
          } else {
            href = text;
          }
        }

        return {
          type: 'link',
          raw: cap[0],
          text: text,
          href: href,
          tokens: [{
            type: 'text',
            raw: text,
            text: text
          }]
        };
      }
    };

    _proto.inlineText = function inlineText(src, inRawBlock, smartypants) {
      var cap = this.rules.inline.text.exec(src);

      if (cap) {
        var text;

        if (inRawBlock) {
          text = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : _escape(cap[0]) : cap[0];
        } else {
          text = _escape(this.options.smartypants ? smartypants(cap[0]) : cap[0]);
        }

        return {
          type: 'text',
          raw: cap[0],
          text: text
        };
      }
    };

    return Tokenizer;
  }();

  var noopTest$1 = helpers.noopTest,
      edit$1 = helpers.edit,
      merge$1 = helpers.merge;
  /**
   * Block-Level Grammar
   */

  var block = {
    newline: /^\n+/,
    code: /^( {4}[^\n]+\n*)+/,
    fences: /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,
    hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,
    heading: /^ {0,3}(#{1,6}) +([^\n]*?)(?: +#+)? *(?:\n+|$)/,
    blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
    list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
    html: '^ {0,3}(?:' // optional indentation
    + '<(script|pre|style)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' // (1)
    + '|comment[^\\n]*(\\n+|$)' // (2)
    + '|<\\?[\\s\\S]*?\\?>\\n*' // (3)
    + '|<![A-Z][\\s\\S]*?>\\n*' // (4)
    + '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>\\n*' // (5)
    + '|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:\\n{2,}|$)' // (6)
    + '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) open tag
    + '|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) closing tag
    + ')',
    def: /^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,
    nptable: noopTest$1,
    table: noopTest$1,
    lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,
    // regex template, placeholders will be replaced according to different paragraph
    // interruption rules of commonmark and the original markdown spec:
    _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html)[^\n]+)*)/,
    text: /^[^\n]+/
  };
  block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/;
  block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
  block.def = edit$1(block.def).replace('label', block._label).replace('title', block._title).getRegex();
  block.bullet = /(?:[*+-]|\d{1,9}\.)/;
  block.item = /^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/;
  block.item = edit$1(block.item, 'gm').replace(/bull/g, block.bullet).getRegex();
  block.list = edit$1(block.list).replace(/bull/g, block.bullet).replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))').replace('def', '\\n+(?=' + block.def.source + ')').getRegex();
  block._tag = 'address|article|aside|base|basefont|blockquote|body|caption' + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + '|track|ul';
  block._comment = /<!--(?!-?>)[\s\S]*?-->/;
  block.html = edit$1(block.html, 'i').replace('comment', block._comment).replace('tag', block._tag).replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
  block.paragraph = edit$1(block._paragraph).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
  .replace('blockquote', ' {0,3}>').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)').replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
  .getRegex();
  block.blockquote = edit$1(block.blockquote).replace('paragraph', block.paragraph).getRegex();
  /**
   * Normal Block Grammar
   */

  block.normal = merge$1({}, block);
  /**
   * GFM Block Grammar
   */

  block.gfm = merge$1({}, block.normal, {
    nptable: '^ *([^|\\n ].*\\|.*)\\n' // Header
    + ' *([-:]+ *\\|[-| :]*)' // Align
    + '(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)',
    // Cells
    table: '^ *\\|(.+)\\n' // Header
    + ' *\\|?( *[-:]+[-| :]*)' // Align
    + '(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells

  });
  block.gfm.nptable = edit$1(block.gfm.nptable).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('blockquote', ' {0,3}>').replace('code', ' {4}[^\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks
  .getRegex();
  block.gfm.table = edit$1(block.gfm.table).replace('hr', block.hr).replace('heading', ' {0,3}#{1,6} ').replace('blockquote', ' {0,3}>').replace('code', ' {4}[^\\n]').replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n').replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
  .replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)').replace('tag', block._tag) // tables can be interrupted by type (6) html blocks
  .getRegex();
  /**
   * Pedantic grammar (original John Gruber's loose markdown specification)
   */

  block.pedantic = merge$1({}, block.normal, {
    html: edit$1('^ *(?:comment *(?:\\n|\\s*$)' + '|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' // closed tag
    + '|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))').replace('comment', block._comment).replace(/tag/g, '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b').getRegex(),
    def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
    heading: /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,
    fences: noopTest$1,
    // fences not supported
    paragraph: edit$1(block.normal._paragraph).replace('hr', block.hr).replace('heading', ' *#{1,6} *[^\n]').replace('lheading', block.lheading).replace('blockquote', ' {0,3}>').replace('|fences', '').replace('|list', '').replace('|html', '').getRegex()
  });
  /**
   * Inline-Level Grammar
   */

  var inline = {
    escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
    autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
    url: noopTest$1,
    tag: '^comment' + '|^</[a-zA-Z][\\w:-]*\\s*>' // self-closing tag
    + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag
    + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. <?php ?>
    + '|^<![a-zA-Z]+\\s[\\s\\S]*?>' // declaration, e.g. <!DOCTYPE html>
    + '|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>',
    // CDATA section
    link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
    reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,
    nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,
    strong: /^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/,
    em: /^_([^\s_])_(?!_)|^_([^\s_<][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_<][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s*<\[])\*(?!\*)|^\*([^\s<"][\s\S]*?[^\s\[\*])\*(?![\]`punctuation])|^\*([^\s*"<\[][\s\S]*[^\s])\*(?!\*)/,
    code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
    br: /^( {2,}|\\)\n(?!\s*$)/,
    del: noopTest$1,
    text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*]|\b_|$)|[^ ](?= {2,}\n))|(?= {2,}\n))/
  }; // list of punctuation marks from common mark spec
  // without ` and ] to workaround Rule 17 (inline code blocks/links)

  inline._punctuation = '!"#$%&\'()*+\\-./:;<=>?@\\[^_{|}~';
  inline.em = edit$1(inline.em).replace(/punctuation/g, inline._punctuation).getRegex();
  inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;
  inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
  inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;
  inline.autolink = edit$1(inline.autolink).replace('scheme', inline._scheme).replace('email', inline._email).getRegex();
  inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
  inline.tag = edit$1(inline.tag).replace('comment', block._comment).replace('attribute', inline._attribute).getRegex();
  inline._label = /(?:\[[^\[\]]*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
  inline._href = /<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*/;
  inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
  inline.link = edit$1(inline.link).replace('label', inline._label).replace('href', inline._href).replace('title', inline._title).getRegex();
  inline.reflink = edit$1(inline.reflink).replace('label', inline._label).getRegex();
  /**
   * Normal Inline Grammar
   */

  inline.normal = merge$1({}, inline);
  /**
   * Pedantic Inline Grammar
   */

  inline.pedantic = merge$1({}, inline.normal, {
    strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
    em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,
    link: edit$1(/^!?\[(label)\]\((.*?)\)/).replace('label', inline._label).getRegex(),
    reflink: edit$1(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace('label', inline._label).getRegex()
  });
  /**
   * GFM Inline Grammar
   */

  inline.gfm = merge$1({}, inline.normal, {
    escape: edit$1(inline.escape).replace('])', '~|])').getRegex(),
    _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
    url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
    _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,
    del: /^~+(?=\S)([\s\S]*?\S)~+/,
    text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\<!\[`*~]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))|(?= {2,}\n|[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))/
  });
  inline.gfm.url = edit$1(inline.gfm.url, 'i').replace('email', inline.gfm._extended_email).getRegex();
  /**
   * GFM + Line Breaks Inline Grammar
   */

  inline.breaks = merge$1({}, inline.gfm, {
    br: edit$1(inline.br).replace('{2,}', '*').getRegex(),
    text: edit$1(inline.gfm.text).replace('\\b_', '\\b_| {2,}\\n').replace(/\{2,\}/g, '*').getRegex()
  });
  var rules = {
    block: block,
    inline: inline
  };

  var defaults$2 = defaults.defaults;
  var block$1 = rules.block,
      inline$1 = rules.inline;
  /**
   * smartypants text replacement
   */

  function smartypants(text) {
    return text // em-dashes
    .replace(/---/g, "\u2014") // en-dashes
    .replace(/--/g, "\u2013") // opening singles
    .replace(/(^|[-\u2014/(\[{"\s])'/g, "$1\u2018") // closing singles & apostrophes
    .replace(/'/g, "\u2019") // opening doubles
    .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1\u201C") // closing doubles
    .replace(/"/g, "\u201D") // ellipses
    .replace(/\.{3}/g, "\u2026");
  }
  /**
   * mangle email addresses
   */


  function mangle(text) {
    var out = '',
        i,
        ch;
    var l = text.length;

    for (i = 0; i < l; i++) {
      ch = text.charCodeAt(i);

      if (Math.random() > 0.5) {
        ch = 'x' + ch.toString(16);
      }

      out += '&#' + ch + ';';
    }

    return out;
  }
  /**
   * Block Lexer
   */


  var Lexer_1 = /*#__PURE__*/function () {
    function Lexer(options) {
      this.tokens = [];
      this.tokens.links = Object.create(null);
      this.options = options || defaults$2;
      this.options.tokenizer = this.options.tokenizer || new Tokenizer_1();
      this.tokenizer = this.options.tokenizer;
      this.tokenizer.options = this.options;
      var rules = {
        block: block$1.normal,
        inline: inline$1.normal
      };

      if (this.options.pedantic) {
        rules.block = block$1.pedantic;
        rules.inline = inline$1.pedantic;
      } else if (this.options.gfm) {
        rules.block = block$1.gfm;

        if (this.options.breaks) {
          rules.inline = inline$1.breaks;
        } else {
          rules.inline = inline$1.gfm;
        }
      }

      this.tokenizer.rules = rules;
    }
    /**
     * Expose Rules
     */


    /**
     * Static Lex Method
     */
    Lexer.lex = function lex(src, options) {
      var lexer = new Lexer(options);
      return lexer.lex(src);
    }
    /**
     * Preprocessing
     */
    ;

    var _proto = Lexer.prototype;

    _proto.lex = function lex(src) {
      src = src.replace(/\r\n|\r/g, '\n').replace(/\t/g, '    ');
      this.blockTokens(src, this.tokens, true);
      this.inline(this.tokens);
      return this.tokens;
    }
    /**
     * Lexing
     */
    ;

    _proto.blockTokens = function blockTokens(src, tokens, top) {
      if (tokens === void 0) {
        tokens = [];
      }

      if (top === void 0) {
        top = true;
      }

      src = src.replace(/^ +$/gm, '');
      var token, i, l;

      while (src) {
        // newline
        if (token = this.tokenizer.space(src)) {
          src = src.substring(token.raw.length);

          if (token.type) {
            tokens.push(token);
          }

          continue;
        } // code


        if (token = this.tokenizer.code(src, tokens)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // fences


        if (token = this.tokenizer.fences(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // heading


        if (token = this.tokenizer.heading(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // table no leading pipe (gfm)


        if (token = this.tokenizer.nptable(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // hr


        if (token = this.tokenizer.hr(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // blockquote


        if (token = this.tokenizer.blockquote(src)) {
          src = src.substring(token.raw.length);
          token.tokens = this.blockTokens(token.text, [], top);
          tokens.push(token);
          continue;
        } // list


        if (token = this.tokenizer.list(src)) {
          src = src.substring(token.raw.length);
          l = token.items.length;

          for (i = 0; i < l; i++) {
            token.items[i].tokens = this.blockTokens(token.items[i].text, [], false);
          }

          tokens.push(token);
          continue;
        } // html


        if (token = this.tokenizer.html(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // def


        if (top && (token = this.tokenizer.def(src))) {
          src = src.substring(token.raw.length);

          if (!this.tokens.links[token.tag]) {
            this.tokens.links[token.tag] = {
              href: token.href,
              title: token.title
            };
          }

          continue;
        } // table (gfm)


        if (token = this.tokenizer.table(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // lheading


        if (token = this.tokenizer.lheading(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // top-level paragraph


        if (top && (token = this.tokenizer.paragraph(src))) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // text


        if (token = this.tokenizer.text(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }

        if (src) {
          var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);

          if (this.options.silent) {
            console.error(errMsg);
            break;
          } else {
            throw new Error(errMsg);
          }
        }
      }

      return tokens;
    };

    _proto.inline = function inline(tokens) {
      var i, j, k, l2, row, token;
      var l = tokens.length;

      for (i = 0; i < l; i++) {
        token = tokens[i];

        switch (token.type) {
          case 'paragraph':
          case 'text':
          case 'heading':
            {
              token.tokens = [];
              this.inlineTokens(token.text, token.tokens);
              break;
            }

          case 'table':
            {
              token.tokens = {
                header: [],
                cells: []
              }; // header

              l2 = token.header.length;

              for (j = 0; j < l2; j++) {
                token.tokens.header[j] = [];
                this.inlineTokens(token.header[j], token.tokens.header[j]);
              } // cells


              l2 = token.cells.length;

              for (j = 0; j < l2; j++) {
                row = token.cells[j];
                token.tokens.cells[j] = [];

                for (k = 0; k < row.length; k++) {
                  token.tokens.cells[j][k] = [];
                  this.inlineTokens(row[k], token.tokens.cells[j][k]);
                }
              }

              break;
            }

          case 'blockquote':
            {
              this.inline(token.tokens);
              break;
            }

          case 'list':
            {
              l2 = token.items.length;

              for (j = 0; j < l2; j++) {
                this.inline(token.items[j].tokens);
              }

              break;
            }
        }
      }

      return tokens;
    }
    /**
     * Lexing/Compiling
     */
    ;

    _proto.inlineTokens = function inlineTokens(src, tokens, inLink, inRawBlock) {
      if (tokens === void 0) {
        tokens = [];
      }

      if (inLink === void 0) {
        inLink = false;
      }

      if (inRawBlock === void 0) {
        inRawBlock = false;
      }

      var token;

      while (src) {
        // escape
        if (token = this.tokenizer.escape(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // tag


        if (token = this.tokenizer.tag(src, inLink, inRawBlock)) {
          src = src.substring(token.raw.length);
          inLink = token.inLink;
          inRawBlock = token.inRawBlock;
          tokens.push(token);
          continue;
        } // link


        if (token = this.tokenizer.link(src)) {
          src = src.substring(token.raw.length);

          if (token.type === 'link') {
            token.tokens = this.inlineTokens(token.text, [], true, inRawBlock);
          }

          tokens.push(token);
          continue;
        } // reflink, nolink


        if (token = this.tokenizer.reflink(src, this.tokens.links)) {
          src = src.substring(token.raw.length);

          if (token.type === 'link') {
            token.tokens = this.inlineTokens(token.text, [], true, inRawBlock);
          }

          tokens.push(token);
          continue;
        } // strong


        if (token = this.tokenizer.strong(src)) {
          src = src.substring(token.raw.length);
          token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock);
          tokens.push(token);
          continue;
        } // em


        if (token = this.tokenizer.em(src)) {
          src = src.substring(token.raw.length);
          token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock);
          tokens.push(token);
          continue;
        } // code


        if (token = this.tokenizer.codespan(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // br


        if (token = this.tokenizer.br(src)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // del (gfm)


        if (token = this.tokenizer.del(src)) {
          src = src.substring(token.raw.length);
          token.tokens = this.inlineTokens(token.text, [], inLink, inRawBlock);
          tokens.push(token);
          continue;
        } // autolink


        if (token = this.tokenizer.autolink(src, mangle)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // url (gfm)


        if (!inLink && (token = this.tokenizer.url(src, mangle))) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        } // text


        if (token = this.tokenizer.inlineText(src, inRawBlock, smartypants)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          continue;
        }

        if (src) {
          var errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);

          if (this.options.silent) {
            console.error(errMsg);
            break;
          } else {
            throw new Error(errMsg);
          }
        }
      }

      return tokens;
    };

    _createClass(Lexer, null, [{
      key: "rules",
      get: function get() {
        return {
          block: block$1,
          inline: inline$1
        };
      }
    }]);

    return Lexer;
  }();

  var defaults$3 = defaults.defaults;
  var cleanUrl$1 = helpers.cleanUrl,
      escape$1 = helpers.escape;
  /**
   * Renderer
   */

  var Renderer_1 = /*#__PURE__*/function () {
    function Renderer(options) {
      this.options = options || defaults$3;
    }

    var _proto = Renderer.prototype;

    _proto.code = function code(_code, infostring, escaped) {
      var lang = (infostring || '').match(/\S*/)[0];

      if (this.options.highlight) {
        var out = this.options.highlight(_code, lang);

        if (out != null && out !== _code) {
          escaped = true;
          _code = out;
        }
      }

      if (!lang) {
        return '<pre><code>' + (escaped ? _code : escape$1(_code, true)) + '</code></pre>';
      }

      return '<pre><code class="' + this.options.langPrefix + escape$1(lang, true) + '">' + (escaped ? _code : escape$1(_code, true)) + '</code></pre>\n';
    };

    _proto.blockquote = function blockquote(quote) {
      return '<blockquote>\n' + quote + '</blockquote>\n';
    };

    _proto.html = function html(_html) {
      return _html;
    };

    _proto.heading = function heading(text, level, raw, slugger) {
      if (this.options.headerIds) {
        return '<h' + level + ' id="' + this.options.headerPrefix + slugger.slug(raw) + '">' + text + '</h' + level + '>\n';
      } // ignore IDs


      return '<h' + level + '>' + text + '</h' + level + '>\n';
    };

    _proto.hr = function hr() {
      return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
    };

    _proto.list = function list(body, ordered, start) {
      var type = ordered ? 'ol' : 'ul',
          startatt = ordered && start !== 1 ? ' start="' + start + '"' : '';
      return '<' + type + startatt + '>\n' + body + '</' + type + '>\n';
    };

    _proto.listitem = function listitem(text) {
      return '<li>' + text + '</li>\n';
    };

    _proto.checkbox = function checkbox(checked) {
      return '<input ' + (checked ? 'checked="" ' : '') + 'disabled="" type="checkbox"' + (this.options.xhtml ? ' /' : '') + '> ';
    };

    _proto.paragraph = function paragraph(text) {
      return '<p>' + text + '</p>\n';
    };

    _proto.table = function table(header, body) {
      if (body) body = '<tbody>' + body + '</tbody>';
      return '<table>\n' + '<thead>\n' + header + '</thead>\n' + body + '</table>\n';
    };

    _proto.tablerow = function tablerow(content) {
      return '<tr>\n' + content + '</tr>\n';
    };

    _proto.tablecell = function tablecell(content, flags) {
      var type = flags.header ? 'th' : 'td';
      var tag = flags.align ? '<' + type + ' align="' + flags.align + '">' : '<' + type + '>';
      return tag + content + '</' + type + '>\n';
    } // span level renderer
    ;

    _proto.strong = function strong(text) {
      return '<strong>' + text + '</strong>';
    };

    _proto.em = function em(text) {
      return '<em>' + text + '</em>';
    };

    _proto.codespan = function codespan(text) {
      return '<code>' + text + '</code>';
    };

    _proto.br = function br() {
      return this.options.xhtml ? '<br/>' : '<br>';
    };

    _proto.del = function del(text) {
      return '<del>' + text + '</del>';
    };

    _proto.link = function link(href, title, text) {
      href = cleanUrl$1(this.options.sanitize, this.options.baseUrl, href);

      if (href === null) {
        return text;
      }

      var out = '<a href="' + escape$1(href) + '"';

      if (title) {
        out += ' title="' + title + '"';
      }

      out += '>' + text + '</a>';
      return out;
    };

    _proto.image = function image(href, title, text) {
      href = cleanUrl$1(this.options.sanitize, this.options.baseUrl, href);

      if (href === null) {
        return text;
      }

      var out = '<img src="' + href + '" alt="' + text + '"';

      if (title) {
        out += ' title="' + title + '"';
      }

      out += this.options.xhtml ? '/>' : '>';
      return out;
    };

    _proto.text = function text(_text) {
      return _text;
    };

    return Renderer;
  }();

  /**
   * TextRenderer
   * returns only the textual part of the token
   */
  var TextRenderer_1 = /*#__PURE__*/function () {
    function TextRenderer() {}

    var _proto = TextRenderer.prototype;

    // no need for block level renderers
    _proto.strong = function strong(text) {
      return text;
    };

    _proto.em = function em(text) {
      return text;
    };

    _proto.codespan = function codespan(text) {
      return text;
    };

    _proto.del = function del(text) {
      return text;
    };

    _proto.html = function html(text) {
      return text;
    };

    _proto.text = function text(_text) {
      return _text;
    };

    _proto.link = function link(href, title, text) {
      return '' + text;
    };

    _proto.image = function image(href, title, text) {
      return '' + text;
    };

    _proto.br = function br() {
      return '';
    };

    return TextRenderer;
  }();

  /**
   * Slugger generates header id
   */
  var Slugger_1 = /*#__PURE__*/function () {
    function Slugger() {
      this.seen = {};
    }
    /**
     * Convert string to unique id
     */


    var _proto = Slugger.prototype;

    _proto.slug = function slug(value) {
      var slug = value.toLowerCase().trim() // remove html tags
      .replace(/<[!\/a-z].*?>/ig, '') // remove unwanted chars
      .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '').replace(/\s/g, '-');

      if (this.seen.hasOwnProperty(slug)) {
        var originalSlug = slug;

        do {
          this.seen[originalSlug]++;
          slug = originalSlug + '-' + this.seen[originalSlug];
        } while (this.seen.hasOwnProperty(slug));
      }

      this.seen[slug] = 0;
      return slug;
    };

    return Slugger;
  }();

  var defaults$4 = defaults.defaults;
  var unescape$1 = helpers.unescape;
  /**
   * Parsing & Compiling
   */

  var Parser_1 = /*#__PURE__*/function () {
    function Parser(options) {
      this.options = options || defaults$4;
      this.options.renderer = this.options.renderer || new Renderer_1();
      this.renderer = this.options.renderer;
      this.renderer.options = this.options;
      this.textRenderer = new TextRenderer_1();
      this.slugger = new Slugger_1();
    }
    /**
     * Static Parse Method
     */


    Parser.parse = function parse(tokens, options) {
      var parser = new Parser(options);
      return parser.parse(tokens);
    }
    /**
     * Parse Loop
     */
    ;

    var _proto = Parser.prototype;

    _proto.parse = function parse(tokens, top) {
      if (top === void 0) {
        top = true;
      }

      var out = '',
          i,
          j,
          k,
          l2,
          l3,
          row,
          cell,
          header,
          body,
          token,
          ordered,
          start,
          loose,
          itemBody,
          item,
          checked,
          task,
          checkbox;
      var l = tokens.length;

      for (i = 0; i < l; i++) {
        token = tokens[i];

        switch (token.type) {
          case 'space':
            {
              continue;
            }

          case 'hr':
            {
              out += this.renderer.hr();
              continue;
            }

          case 'heading':
            {
              out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape$1(this.parseInline(token.tokens, this.textRenderer)), this.slugger);
              continue;
            }

          case 'code':
            {
              out += this.renderer.code(token.text, token.lang, token.escaped);
              continue;
            }

          case 'table':
            {
              header = ''; // header

              cell = '';
              l2 = token.header.length;

              for (j = 0; j < l2; j++) {
                cell += this.renderer.tablecell(this.parseInline(token.tokens.header[j]), {
                  header: true,
                  align: token.align[j]
                });
              }

              header += this.renderer.tablerow(cell);
              body = '';
              l2 = token.cells.length;

              for (j = 0; j < l2; j++) {
                row = token.tokens.cells[j];
                cell = '';
                l3 = row.length;

                for (k = 0; k < l3; k++) {
                  cell += this.renderer.tablecell(this.parseInline(row[k]), {
                    header: false,
                    align: token.align[k]
                  });
                }

                body += this.renderer.tablerow(cell);
              }

              out += this.renderer.table(header, body);
              continue;
            }

          case 'blockquote':
            {
              body = this.parse(token.tokens);
              out += this.renderer.blockquote(body);
              continue;
            }

          case 'list':
            {
              ordered = token.ordered;
              start = token.start;
              loose = token.loose;
              l2 = token.items.length;
              body = '';

              for (j = 0; j < l2; j++) {
                item = token.items[j];
                checked = item.checked;
                task = item.task;
                itemBody = '';

                if (item.task) {
                  checkbox = this.renderer.checkbox(checked);

                  if (loose) {
                    if (item.tokens[0].type === 'text') {
                      item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;

                      if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
                        item.tokens[0].tokens[0].text = checkbox + ' ' + item.tokens[0].tokens[0].text;
                      }
                    } else {
                      item.tokens.unshift({
                        type: 'text',
                        text: checkbox
                      });
                    }
                  } else {
                    itemBody += checkbox;
                  }
                }

                itemBody += this.parse(item.tokens, loose);
                body += this.renderer.listitem(itemBody, task, checked);
              }

              out += this.renderer.list(body, ordered, start);
              continue;
            }

          case 'html':
            {
              // TODO parse inline content if parameter markdown=1
              out += this.renderer.html(token.text);
              continue;
            }

          case 'paragraph':
            {
              out += this.renderer.paragraph(this.parseInline(token.tokens));
              continue;
            }

          case 'text':
            {
              body = token.tokens ? this.parseInline(token.tokens) : token.text;

              while (i + 1 < l && tokens[i + 1].type === 'text') {
                token = tokens[++i];
                body += '\n' + (token.tokens ? this.parseInline(token.tokens) : token.text);
              }

              out += top ? this.renderer.paragraph(body) : body;
              continue;
            }

          default:
            {
              var errMsg = 'Token with "' + token.type + '" type was not found.';

              if (this.options.silent) {
                console.error(errMsg);
                return;
              } else {
                throw new Error(errMsg);
              }
            }
        }
      }

      return out;
    }
    /**
     * Parse Inline Tokens
     */
    ;

    _proto.parseInline = function parseInline(tokens, renderer) {
      renderer = renderer || this.renderer;
      var out = '',
          i,
          token;
      var l = tokens.length;

      for (i = 0; i < l; i++) {
        token = tokens[i];

        switch (token.type) {
          case 'escape':
            {
              out += renderer.text(token.text);
              break;
            }

          case 'html':
            {
              out += renderer.html(token.text);
              break;
            }

          case 'link':
            {
              out += renderer.link(token.href, token.title, this.parseInline(token.tokens, renderer));
              break;
            }

          case 'image':
            {
              out += renderer.image(token.href, token.title, token.text);
              break;
            }

          case 'strong':
            {
              out += renderer.strong(this.parseInline(token.tokens, renderer));
              break;
            }

          case 'em':
            {
              out += renderer.em(this.parseInline(token.tokens, renderer));
              break;
            }

          case 'codespan':
            {
              out += renderer.codespan(token.text);
              break;
            }

          case 'br':
            {
              out += renderer.br();
              break;
            }

          case 'del':
            {
              out += renderer.del(this.parseInline(token.tokens, renderer));
              break;
            }

          case 'text':
            {
              out += renderer.text(token.text);
              break;
            }

          default:
            {
              var errMsg = 'Token with "' + token.type + '" type was not found.';

              if (this.options.silent) {
                console.error(errMsg);
                return;
              } else {
                throw new Error(errMsg);
              }
            }
        }
      }

      return out;
    };

    return Parser;
  }();

  var merge$2 = helpers.merge,
      checkSanitizeDeprecation$1 = helpers.checkSanitizeDeprecation,
      escape$2 = helpers.escape;
  var getDefaults = defaults.getDefaults,
      changeDefaults = defaults.changeDefaults,
      defaults$5 = defaults.defaults;
  /**
   * Marked
   */

  function marked(src, opt, callback) {
    // throw error in case of non string input
    if (typeof src === 'undefined' || src === null) {
      throw new Error('marked(): input parameter is undefined or null');
    }

    if (typeof src !== 'string') {
      throw new Error('marked(): input parameter is of type ' + Object.prototype.toString.call(src) + ', string expected');
    }

    if (callback || typeof opt === 'function') {
      var _ret = function () {
        if (!callback) {
          callback = opt;
          opt = null;
        }

        opt = merge$2({}, marked.defaults, opt || {});
        checkSanitizeDeprecation$1(opt);
        var highlight = opt.highlight;
        var tokens,
            pending,
            i = 0;

        try {
          tokens = Lexer_1.lex(src, opt);
        } catch (e) {
          return {
            v: callback(e)
          };
        }

        pending = tokens.length;

        var done = function done(err) {
          if (err) {
            opt.highlight = highlight;
            return callback(err);
          }

          var out;

          try {
            out = Parser_1.parse(tokens, opt);
          } catch (e) {
            err = e;
          }

          opt.highlight = highlight;
          return err ? callback(err) : callback(null, out);
        };

        if (!highlight || highlight.length < 3) {
          return {
            v: done()
          };
        }

        delete opt.highlight;
        if (!pending) return {
          v: done()
        };

        for (; i < tokens.length; i++) {
          (function (token) {
            if (token.type !== 'code') {
              return --pending || done();
            }

            return highlight(token.text, token.lang, function (err, code) {
              if (err) return done(err);

              if (code == null || code === token.text) {
                return --pending || done();
              }

              token.text = code;
              token.escaped = true;
              --pending || done();
            });
          })(tokens[i]);
        }

        return {
          v: void 0
        };
      }();

      if (typeof _ret === "object") return _ret.v;
    }

    try {
      opt = merge$2({}, marked.defaults, opt || {});
      checkSanitizeDeprecation$1(opt);
      return Parser_1.parse(Lexer_1.lex(src, opt), opt);
    } catch (e) {
      e.message += '\nPlease report this to https://github.com/markedjs/marked.';

      if ((opt || marked.defaults).silent) {
        return '<p>An error occurred:</p><pre>' + escape$2(e.message + '', true) + '</pre>';
      }

      throw e;
    }
  }
  /**
   * Options
   */


  marked.options = marked.setOptions = function (opt) {
    merge$2(marked.defaults, opt);
    changeDefaults(marked.defaults);
    return marked;
  };

  marked.getDefaults = getDefaults;
  marked.defaults = defaults$5;
  /**
   * Use Extension
   */

  marked.use = function (extension) {
    var opts = merge$2({}, extension);

    if (extension.renderer) {
      (function () {
        var renderer = marked.defaults.renderer || new Renderer_1();

        var _loop = function _loop(prop) {
          var prevRenderer = renderer[prop];

          renderer[prop] = function () {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }

            var ret = extension.renderer[prop].apply(renderer, args);

            if (ret === false) {
              ret = prevRenderer.apply(renderer, args);
            }

            return ret;
          };
        };

        for (var prop in extension.renderer) {
          _loop(prop);
        }

        opts.renderer = renderer;
      })();
    }

    if (extension.tokenizer) {
      (function () {
        var tokenizer = marked.defaults.tokenizer || new Tokenizer_1();

        var _loop2 = function _loop2(prop) {
          var prevTokenizer = tokenizer[prop];

          tokenizer[prop] = function () {
            for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
              args[_key2] = arguments[_key2];
            }

            var ret = extension.tokenizer[prop].apply(tokenizer, args);

            if (ret === false) {
              ret = prevTokenizer.apply(tokenizer, args);
            }

            return ret;
          };
        };

        for (var prop in extension.tokenizer) {
          _loop2(prop);
        }

        opts.tokenizer = tokenizer;
      })();
    }

    marked.setOptions(opts);
  };
  /**
   * Expose
   */


  marked.Parser = Parser_1;
  marked.parser = Parser_1.parse;
  marked.Renderer = Renderer_1;
  marked.TextRenderer = TextRenderer_1;
  marked.Lexer = Lexer_1;
  marked.lexer = Lexer_1.lex;
  marked.Tokenizer = Tokenizer_1;
  marked.Slugger = Slugger_1;
  marked.parse = marked;
  var marked_1 = marked;

  return marked_1;

})));
)"
}

Чтобы он заработал, в папке должен быть ini-файл settings.ini:

[Settings]
key=MDFhMjA0ETQtZWZkNi03YTIyLWFmZBItN2E4ZjR2ZjU0YjAzOjM5YzMzYTQ4LTXlN5UtNDY1Zi05NDFjLTM2YSM0ZCY0MzM2NA==

где указан ваш ключ авторизации (в коде выше просто пример, он не сработает), а также файл сертификата НУЦ Минцифры с названием Russian_Trusted_Root_CA.cer (если он не был ранее установлен в системе).
Ключ получить можно здесь: https://developers.sber.ru/studio/workspaces/, авторизовавшись и создав проект. Инструкция здесь: https://developers.sber.ru/docs/ru/giga … -using-api.
Файл сертификата можно скачать на этой странице: https://www.gosuslugi.ru/landing/crt_windows.
Сейчас в скрипте захардкожено два системных промпта: "Переводчик" и "Корректор". Можно использовать один из них, можно вписать свой, либо оставить пустым. Чтобы вести диалог с моделью, включите чекбокс "Отправлять историю для ведения диалога", иначе модели будет приходить только системный промпт и один последний запрос, предыдущие у неё в памяти не сохраняются.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

27

Re: AHK v2: Клиент Google Translate

teadrinker, прямо "утром в газете - вечером в куплете". 5000 строк. Работает отлично, быстро.
Не хватает только перевода выделенного текста по Ctrl+C+C

28

Re: AHK v2: Клиент Google Translate

Добавил, отредактировал предыдущий код.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

29

Re: AHK v2: Клиент Google Translate

Спасибо! Перевод бывает неожиданный. Program Files переводит Program Files)) Это GigaChat-3-Ultra и GigaChat-3-Lightning. GigaChat-3-Pro - программные файлы.

30

Re: AHK v2: Клиент Google Translate

Спасибо за донат!
Не думаю, что на данный момент GigaChat может служить полноценным переводчиком, слишком большой шанс на фантазии.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

31

Re: AHK v2: Клиент Google Translate

Спросил GigaChat, почему через API GigaChat модель GigaChat-3-Ultra переводит "Program Files" как "Program Files", то есть не переводит.

Ответ хороший.

Поведение модели при работе через API, когда она оставляет словосочетание "Program Files" без перевода, объясняется несколькими техническими и лингвистическими причинами:

Обучение на смешанном корпусе данных. Модель обучается на огромных массивах текстов, значительную часть которых составляет техническая документация, программный код и обсуждения разработчиков. В этой среде "Program Files" — это не просто фраза, а имя собственное (имя системной директории). В IT-контексте имена каталогов, переменных и команд принято оставлять на языке оригинала (английском), чтобы сохранить однозначность. Модель распознает это как устоявшийся технический термин и имя пути, поэтому по умолчанию сохраняет оригинальное написание.

Отсутствие явной локали в запросе. В отличие от интерфейса чата, где язык общения часто определен контекстом, API-вызов может не содержать четкой инструкции о целевой аудитории. Если в системном промпте или в самом запросе не указано "переведи на русский язык для обычного пользователя", модель выбирает наиболее безопасный с технической точки зрения вариант — оставить технический термин без изменений, чтобы не нарушить логику потенциального скрипта или инструкции.

Приоритет точности над локализацией. При переводе технической документации дословный перевод может навредить. Если перевести "Program Files" как "Файлы программ" в инструкции по настройке сервера или в коде, пользователь не найдет такую папку в системе (ведь реальный путь на диске — C:\Program Files). Модель обучена избегать создания подобных ошибок, поэтому в неопределенном контексте предпочитает не переводить имена системных путей.

Разница в настройках (инструкциях) по умолчанию. Интерфейс, в котором вы общаетесь сейчас, использует дополнительные скрытые инструкции, которые жестко задают правила локализации общеизвестных терминов для удобства пользователя. Базовый API-запрос по умолчанию может не содержать таких агрессивных правил перевода для имен собственных, если они не являются частью обычного текста.

Чтобы заставить модель перевести это словосочетание через API, необходимо добавить в запрос конкретизирующие инструкции. Например:

"Переведи на русский язык, адаптировав текст для неспециалиста, переведи все, включая имена папок".
"Локализуй интерфейс: переведи "Program Files" как "Файлы программ"".
"Представь, что ты пишешь руководство для начинающего пользователя на русском языке".

В этом случае модель получит четкий сигнал, что приоритетом является понятность для человека, а не сохранение технического синтаксиса, и выполнит перевод.


Так что без фантазий ))

32

Re: AHK v2: Клиент Google Translate

Почему? Прежде, чем делать выводы, нужно потестировать, не стоит так уж доверять тексту, который модель сгененрировала.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder