acpgram 1.29.0 → 1.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/README.ru.md +5 -0
- package/package.json +1 -1
- package/src/bot.mjs +9 -2
- package/src/db.mjs +16 -4
- package/src/gitAccess.mjs +45 -1
- package/src/gitDevice.mjs +121 -0
- package/src/gitHosts.mjs +2 -2
- package/src/gitUi.mjs +89 -14
- package/src/i18n.mjs +16 -0
- package/src/state.mjs +3 -1
- package/src/ui.mjs +9 -0
package/README.md
CHANGED
|
@@ -49,6 +49,7 @@ Check it yourself after installing: `npm audit signatures` verifies the registry
|
|
|
49
49
|
- **Files and images** — send the bot a photo or a file (text, PDF, spreadsheet, etc., up to 20 MB); the caption becomes the request. The file is saved to `<data dir>/uploads/<user id>/` and the agent gets its path and reads it with its own tools. An album of several photos or files is handled as one request. `.zip`, `.tar`, `.tar.gz` and `.tgz` archives are unpacked next to the file (`…_unpacked`, at most 500 files and 100 MB; unsafe paths and links are skipped) and the agent gets the file list; `.7z` and `.rar` stay a plain file; images are also passed as an `image` block when the agent supports it. In the other direction the agent can create a file and send it to the chat: it saves the file to `<data dir>/outbox/<user id>/` (or the project folder) and puts a `[[send:path]]` marker in its reply. The file appears right inside the reply, where the marker was: JPEG and PNG as an image, everything else as a document. If Telegram rejects such a message or the files together exceed 45 MB, they arrive as separate messages after the reply. A marker inside code (backticks or a code block) is ignored. Only files from these two folders are sent, never secrets (`.env`, the bot's database and logs, `.git`). Files are kept for 7 days (`FILES_KEEP_DAYS`).
|
|
50
50
|
- **Dialogs mode (topics)** — if topics in private chats are turned on for the bot (@BotFather), each topic of the chat is a separate dialog with the agent, with its own project, engine and history. You can work in several topics at once and come back to a topic later to continue where you left off: the agent session resumes by itself. `/new` creates a new topic, and the agent names it after the first answer (with a short project name in front); General works as a regular dialog, and `/project` there shows the dialogs of the chosen project as buttons that open the topic. A command sent from the chat list rather than from inside a topic (Telegram creates a new topic for such a message by itself) runs in General, and the empty topic is deleted. A topic stays in its own project. Everyone picks the mode with `/topics`: "Dialogs" or "One chat". A teammate runs up to `MAX_AGENTS_PER_USER` agents at once (2), the admin up to `ADMIN_MAX_AGENTS` (4); when there is no room, the user's own oldest idle agent is unloaded, and that dialog continues when the user comes back to it.
|
|
51
51
|
- **Language** — the bot talks to each user in their Telegram language (`ru`, `uk` or `en`; any other falls back to `DEFAULT_LANG`, English by default). `/language` changes it and takes priority over the Telegram language. The `acpgram` terminal commands (setup wizard, service, update, help) speak the system language: Russian, Ukrainian, otherwise English; on Windows the system UI language is used, not the regional format.
|
|
52
|
+
- **Documentation** — `/help` and the bot's menu button open the docs page with an AI chat; the `/help` message offers to open it in a browser or as a mini app.
|
|
52
53
|
- **Projects** — `/project` picks the working folder by buttons, by name search or by path (`/project ~/projects/web`), with one-tap recent projects.
|
|
53
54
|
- **Project files, bypassing the agent** — `/files` lists the project files, creates a file from a message, uploads a file from your device and deletes files. The contents never go into a model request, which is how secrets (`.env`, keys) get into a project.
|
|
54
55
|
- **Git: GitHub and GitLab** — `/git` connects an account with an access token, clones a repository picked from a list, and pulls, pushes or "saves and pushes" changes. The token stays with the bot and is not given to the agent; files with secrets never get into commits.
|
|
@@ -182,6 +183,7 @@ In the container the agent sees only the mounted projects folder (`PROJECTS_DIR`
|
|
|
182
183
|
| Command | Who | What |
|
|
183
184
|
|---|---|---|
|
|
184
185
|
| `/start` | everyone | welcome screen: engine, model, access level, project |
|
|
186
|
+
| `/help` | everyone | docs with an AI chat: link and mini app |
|
|
185
187
|
| `/project [name or path]` | everyone | choose the working folder |
|
|
186
188
|
| `/engine [gemini, claude, agy, codex, opencode]` | everyone | choose the engine |
|
|
187
189
|
| `/model [name]` | everyone | choose the model and reasoning level; with a name — search for a model (`/model sonnet`) |
|
|
@@ -230,6 +232,7 @@ The `/git` command connects projects to GitHub, GitLab.com and your own servers
|
|
|
230
232
|
|
|
231
233
|
- **Own servers** are added by the administrator right in `/git`: "⚙️ Own servers" → "➕ GitLab" or "➕ GitHub Enterprise" → the server address (`https://git.example.com`). The bot checks that a server of that kind answers at the address, and after that every user can connect an account on it. The same screen renames and removes a server — together with the accounts connected to it. Without this the menu has only GitHub and GitLab.com. Where settings are kept in a file, a server can also be set in `.env` (`GITLAB_URL`, `GITHUB_URL`).
|
|
232
234
|
|
|
235
|
+
- **Signing in to GitHub and GitLab.com without a token.** "➕ Connect …" → "🔗 Sign in without a token": the bot shows a link and a short code, the user enters the code on the service's site and confirms access, and the bot gets the sign-in itself and connects the account. Nothing secret gets into the chat. It works in any installation without setup: the identifiers of the AcpGram applications on GitHub.com and GitLab.com are built in (they are public, and no application secret is needed for this kind of sign-in). On GitLab such a sign-in lasts 2 hours — the bot renews it by itself before every operation; if the service stops accepting it, the account is disconnected and the bot asks to connect it again. `GITHUB_CLIENT_ID` and `GITLAB_CLIENT_ID` set your own applications, and the value `0` leaves only the token sign-in for that service. Own servers are connected with a token.
|
|
233
236
|
- **Connecting an account.** "➕ Connect …" → the bot gives a link to the tokens page and the list of permissions, and the user sends the access token in one message. The message is deleted from the chat right away and is not passed to the agent. The bot checks the token with the service, shows who is connected and until when the token is valid, and warns if permissions are missing. Full permissions are needed: on GitLab `api`, `read_repository`, `write_repository` (without `api` publishing and merge requests do not work), on GitHub `repo`. Disconnecting removes the token from the bot.
|
|
234
237
|
- **Cloning.** "⬇️ Clone a repository" (or "⬇️ From Git" in `/project`) lists the user's repositories as buttons, recently changed first, with search by name. The chosen one is cloned into the personal workspace (without it, next to the current project) and becomes the project.
|
|
235
238
|
- **The project repository.** The screen shows the branch, the number of changed files, of commits not pushed and of new commits on the server; it checks the server when opened and on "Refresh". "⬇️ Pull" takes the changes when that is possible without a merge; if the histories diverged, the agent does the merge. "⬆️ Push" sends the commits. "💾 Save and push" asks for a description, commits all changes and pushes.
|
|
@@ -299,6 +302,7 @@ What the sandbox does not do:
|
|
|
299
302
|
| `SANDBOX_RO_PATHS` | no | extra folders the sandbox can read (separated by `:`), e.g. where an engine is installed if it does not start in the sandbox |
|
|
300
303
|
| `BWRAP_COMMAND` | no | path to `bwrap` if it is not in `PATH` |
|
|
301
304
|
| `GITLAB_URL`, `GITHUB_URL` | no | address of your own GitLab and your own GitHub Enterprise (`https://git.example.com`): they appear in `/git` next to GitHub and GitLab.com. `GITLAB_NAME`, `GITHUB_NAME` are the names on the buttons (the host name by default). Optional: the administrator can also add own servers in the bot itself (`/git` → "Own servers") |
|
|
305
|
+
| `GITHUB_CLIENT_ID`, `GITLAB_CLIENT_ID` | no | identifiers of your own applications for signing in with a link and a code: on GitHub an OAuth App with Device Flow enabled, on GitLab.com an application with Device authorization grant enabled (not confidential); `0` turns that sign-in off for the service. By default the AcpGram applications are used |
|
|
302
306
|
| `GIT_AGENT_AUTH` | no | `1` — the Git sign-in is also given to agents: they pull and push by themselves, but teammates' tokens are visible to them. By default the token stays with the bot |
|
|
303
307
|
| `GIT_COMMAND` | no | path to `git` if it is not in `PATH` |
|
|
304
308
|
| `USER_WORKSPACES` | no | `1` — personal workspaces: each teammate chooses projects only inside their own folder `<root>/<Telegram ID>`, the administrator sees the whole root. Requires `PROJECTS_ROOT`; the bot does not start without it |
|
package/README.ru.md
CHANGED
|
@@ -49,6 +49,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
49
49
|
- **Режим «диалоги» (темы)**: если боту включены темы в личном чате (@BotFather), каждая тема чата — отдельный диалог с агентом со своим проектом, движком и историей. Можно работать в нескольких темах одновременно, а вернувшись в тему позже — продолжить с того же места: сессия агента возобновляется сама. `/new` создаёт новую тему, название ей даёт агент по первому ответу (с коротким именем проекта в начале); General работает как обычный диалог, а `/project` в нём показывает диалоги выбранного проекта кнопками, открывающими тему. Тема закреплена за своим проектом. Команда, отправленная из общего списка чатов, а не изнутри темы (Telegram сам заводит под такое сообщение новую тему), выполняется в General, а пустая тема удаляется. Режим каждый выбирает сам: `/topics` — «Диалоги» или «Один чат». Одновременно у сотрудника работает до `MAX_AGENTS_PER_USER` агентов (2), у администратора до `ADMIN_MAX_AGENTS` (4); если места нет, выгружается самый давний простаивающий агент этого же пользователя — его диалог продолжится, когда пользователь в него вернётся.
|
|
50
50
|
- **Язык**: бот говорит с пользователем на языке его Telegram (`ru`, `uk` или `en`, для остальных — `DEFAULT_LANG`, по умолчанию английский). Сменить язык можно командой `/language`: выбор важнее языка Telegram. Команды `acpgram` в терминале (мастер настройки, служба, обновление, справка) говорят на языке системы: русский, украинский, в остальных случаях английский; на Windows берётся язык интерфейса системы, а не региональные настройки.
|
|
51
51
|
- **Экран `/start`** с кнопками: проект, движок, модель, новая сессия, прошлые сессии, завершение сессии (у администратора — сотрудники, приглашение, активные сессии).
|
|
52
|
+
- **Документация**: команда `/help` и кнопка меню бота открывают страницу справки с ИИ-чатом; в сообщении `/help` можно открыть её в браузере или мини-приложением.
|
|
52
53
|
- **Выбор проекта** (`/project`): агент запускается в папке выбранного проекта — кнопками, поиском по названию или путём (`/project C:\my-app`, `/project ~/projects/web`). Вверху — кнопки «🕘» с последними проектами пользователя. Выбор запоминается для каждого пользователя.
|
|
53
54
|
- с `PROJECTS_ROOT` (командный сервер, например `C:\scripts`) — только папки внутри корня;
|
|
54
55
|
- с `PROJECTS_ROOT` и `USER_WORKSPACES=1` (личные пространства) — у каждого сотрудника своя папка в корне, чужие папки он не видит и выбрать не может; новый проект создаётся кнопкой «➕ Новый проект» (см. «Личные пространства»);
|
|
@@ -64,6 +65,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
64
65
|
| Команда | Для кого | Действие |
|
|
65
66
|
|---|---|---|
|
|
66
67
|
| `/start` | все | приветствие, движок, модель, уровень доступа, текущий проект |
|
|
68
|
+
| `/help` | все | документация с ИИ-чатом: ссылка и мини-приложение |
|
|
67
69
|
| `/project [название или путь]` | все | выбор проекта кнопками или поиском по названию |
|
|
68
70
|
| `/engine [gemini, claude, agy, codex, opencode]` | все | выбор движка кнопками или по названию |
|
|
69
71
|
| `/model [название]` | все | выбор модели и уровня рассуждений текущего движка; с названием — поиск модели (`/model sonnet`) |
|
|
@@ -120,6 +122,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
120
122
|
|
|
121
123
|
- **Свои серверы** добавляет администратор прямо в `/git`: «⚙️ Свои серверы» → «➕ GitLab» или «➕ GitHub Enterprise» → адрес сервера (`https://git.example.com`). Бот проверяет, что по адресу отвечает сервер нужного вида, и после этого каждый пользователь может подключить на нём аккаунт. Там же сервер переименовывается и убирается — вместе с подключёнными к нему аккаунтами. Без этого в меню только GitHub и GitLab.com. Там, где настройки задаются файлом, сервер можно указать и в `.env` (`GITLAB_URL`, `GITHUB_URL`).
|
|
122
124
|
|
|
125
|
+
- **Вход в GitHub и GitLab.com без токена.** «➕ Подключить …» → «🔗 Войти без токена»: бот показывает ссылку и короткий код, пользователь вводит код на сайте сервиса и подтверждает доступ, а бот сам получает вход и подключает аккаунт. Ничего секретного в чат не попадает. Работает в любой установке без настройки: идентификаторы приложений AcpGram на GitHub.com и GitLab.com встроены (они открытые, секрета приложения для такого входа не нужно). У GitLab такой вход действует 2 часа — бот сам продлевает его перед каждой операцией; если сервис перестал его принимать, аккаунт отключается и бот просит подключить его заново. `GITHUB_CLIENT_ID` и `GITLAB_CLIENT_ID` задают свои приложения, значение `0` оставляет для сервиса только вход по токену. Свои серверы подключаются токеном.
|
|
123
126
|
- **Подключение аккаунта.** «➕ Подключить …» → бот даёт ссылку на страницу токенов и список нужных прав, пользователь присылает токен доступа одним сообщением. Сообщение сразу удаляется из чата и агенту не передаётся. Бот проверяет токен в сервисе, показывает, кто подключён и до какого числа токен действует, и предупреждает, если прав не хватает. Права нужны полные: у GitLab — `api`, `read_repository`, `write_repository` (без `api` не работают публикация и запросы на слияние), у GitHub — `repo`. Отключение удаляет токен из бота.
|
|
124
127
|
- **Клонирование.** «⬇️ Клонировать репозиторий» (или «⬇️ Из Git» в `/project`) показывает репозитории пользователя кнопками, недавно менявшиеся первыми, с поиском по названию. Выбранный клонируется в личное пространство (без него — рядом с текущим проектом) и становится проектом.
|
|
125
128
|
- **Репозиторий проекта.** Экран показывает ветку, число изменённых файлов, неотправленных коммитов и новых коммитов на сервере; при открытии и по кнопке «Обновить» он сверяется с сервером. «⬇️ Получить» забирает изменения, если это возможно без слияния; если истории разошлись, слияние делает агент. «⬆️ Отправить» отправляет коммиты. «💾 Сохранить и отправить» спрашивает описание, коммитит все изменения и отправляет.
|
|
@@ -317,6 +320,7 @@ npm start # первый запуск без .env сам открое
|
|
|
317
320
|
| `SANDBOX_RO_PATHS` | нет | дополнительные папки, которые песочница видит на чтение (через `:`), — например, место установки движка, если он не запускается в песочнице |
|
|
318
321
|
| `BWRAP_COMMAND` | нет | путь к `bwrap`, если его нет в `PATH` |
|
|
319
322
|
| `GITLAB_URL`, `GITHUB_URL` | нет | адрес своего GitLab и своего GitHub Enterprise (`https://git.example.com`): появляются в `/git` рядом с GitHub и GitLab.com. `GITLAB_NAME`, `GITHUB_NAME` — названия в кнопках (по умолчанию — имя сервера). Не обязательны: администратор добавляет свои серверы и в самом боте (`/git` → «Свои серверы») |
|
|
323
|
+
| `GITHUB_CLIENT_ID`, `GITLAB_CLIENT_ID` | нет | идентификаторы своих приложений для входа по ссылке и коду: GitHub — OAuth App с включённым Device Flow, GitLab.com — приложение с включённым Device authorization grant (не конфиденциальное); `0` — выключить такой вход для сервиса. По умолчанию — приложения AcpGram |
|
|
320
324
|
| `GIT_AGENT_AUTH` | нет | `1` — вход в Git передаётся и агентам: они сами получают и отправляют изменения, но токены сотрудников им видны. По умолчанию токен только у бота |
|
|
321
325
|
| `GIT_COMMAND` | нет | путь к `git`, если его нет в `PATH` |
|
|
322
326
|
| `DEFAULT_ENGINE` | нет | движок по умолчанию: `gemini` (по умолчанию), `claude`, `agy`, `codex` или `opencode`. Если этот движок не установлен, бот не запускается |
|
|
@@ -434,6 +438,7 @@ src/
|
|
|
434
438
|
gitApi.mjs GitHub и GitLab: создание репозитория, места для публикации, запрос на слияние
|
|
435
439
|
gitPublishUi.mjs экраны /git «Опубликовать проект» и «Запрос на слияние»
|
|
436
440
|
gitMarks.mjs метки агента [[git:push]] / [[git:pull]]: отправка и получение по просьбе агента
|
|
441
|
+
gitDevice.mjs вход в GitHub.com и GitLab.com по ссылке и коду, без токена; продление входа
|
|
437
442
|
gitKeys.mjs ключи кнопок списков /git: старая кнопка не укажет на другой файл или ветку
|
|
438
443
|
sessionsUi.mjs команда /sessions: возврат к прошлой сессии
|
|
439
444
|
tools.mjs разбор событий вызовов инструментов агента
|
package/package.json
CHANGED
package/src/bot.mjs
CHANGED
|
@@ -27,7 +27,7 @@ import { createAlbumBuffer } from './albums.mjs';
|
|
|
27
27
|
import { dropQueue, enqueue, onAskCallback, onPermissionCallback, onQueueCallback, runTurn } from './turn.mjs';
|
|
28
28
|
import { nearCommand, quoteOf, unsupportedKind } from './incoming.mjs';
|
|
29
29
|
import { onWidgetQuery } from './widgetsUi.mjs';
|
|
30
|
-
import { startView } from './ui.mjs';
|
|
30
|
+
import { DOCS_URL, docsMenuButton, helpMarkup, startView } from './ui.mjs';
|
|
31
31
|
|
|
32
32
|
if (!process.env.TELEGRAM_BOT_TOKEN || !ADMIN_ID) {
|
|
33
33
|
console.error('Нужны TELEGRAM_BOT_TOKEN и ALLOWED_USER_ID (см. .env)');
|
|
@@ -56,6 +56,11 @@ const sendStart = (st) => {
|
|
|
56
56
|
return sendRich(st.to, startView({ level: levelLabel(st.userId), project: userPath(st.userId, st.project, lang), engine: engineOf(st).label, model: modelLabel(st), isAdmin: admin, note: admin ? null : welcomeNote(lang), topics, lang })).catch((e) => log('start:', e.message));
|
|
57
57
|
};
|
|
58
58
|
|
|
59
|
+
function helpCommand(st) {
|
|
60
|
+
const lang = langOf(st.userId);
|
|
61
|
+
return say(st.to, t('help.text', lang, { url: DOCS_URL }), { reply_markup: helpMarkup(lang) });
|
|
62
|
+
}
|
|
63
|
+
|
|
59
64
|
/** Кнопка «⏹ Остановить» под сообщениями «запрос ещё выполняется» — вместо набора /stop. */
|
|
60
65
|
const stopMarkup = (lang) => ({ inline_keyboard: [[{ text: t('btn.stop', lang), callback_data: 'ui:stop' }]] });
|
|
61
66
|
/** Кнопка «Сессии» — вместо набора /sessions. */
|
|
@@ -132,6 +137,7 @@ const COMMANDS = [
|
|
|
132
137
|
{ name: 'close', aliases: ['exit'], menu: true, button: true, run: closeCommand },
|
|
133
138
|
{ name: 'topics', menu: () => topicsSupport.enabled, button: true, run: (st) => handleTopics(st) }, // в меню — если у бота включены темы
|
|
134
139
|
{ name: 'language', aliases: ['lang'], menu: true, button: true, run: languageCommand },
|
|
140
|
+
{ name: 'help', menu: true, run: helpCommand },
|
|
135
141
|
{ name: 'start', menu: true, run: (st) => sendStart(st) },
|
|
136
142
|
];
|
|
137
143
|
|
|
@@ -268,6 +274,7 @@ async function setupCommands() {
|
|
|
268
274
|
await tg('setMyCommands', { scope: { type: 'default' }, language_code: code, commands: menuFor(code, false) });
|
|
269
275
|
await tg('setMyCommands', { scope: { type: 'chat', chat_id: ADMIN_ID }, language_code: code, commands: menuFor(code, true) });
|
|
270
276
|
}
|
|
277
|
+
await tg('setChatMenuButton', { menu_button: docsMenuButton() });
|
|
271
278
|
}
|
|
272
279
|
|
|
273
280
|
async function handleUpdate(u) {
|
|
@@ -466,7 +473,7 @@ async function main() {
|
|
|
466
473
|
? `темы в личном чате включены (режим «диалоги», /topics)${topicsSupport.usersCreate ? '' : ' — пользователи не могут создавать темы сами, только через /new'}`
|
|
467
474
|
: 'темы в личном чате выключены — режим «диалоги» недоступен',
|
|
468
475
|
);
|
|
469
|
-
await setupCommands().catch((e) => log('
|
|
476
|
+
await setupCommands().catch((e) => log('настройка меню:', e.message));
|
|
470
477
|
// пропускаем накопившиеся до запуска обновления
|
|
471
478
|
const old = await tg('getUpdates', { offset: -1, timeout: 0 });
|
|
472
479
|
let offset = old.length ? old[old.length - 1].update_id + 1 : 0;
|
package/src/db.mjs
CHANGED
|
@@ -171,6 +171,11 @@ export function openDb(path = 'data/bot.db') {
|
|
|
171
171
|
]);
|
|
172
172
|
// v1.19: тему можно убрать из списка тем проекта (Telegram не сообщает боту об удалении темы)
|
|
173
173
|
addColumns('topics', [['hidden', 'INTEGER NOT NULL DEFAULT 0']]);
|
|
174
|
+
// v1.30: вход по ссылке и коду — у GitLab такой токен живёт 2 часа и обновляется токеном обновления
|
|
175
|
+
addColumns('git_accounts', [
|
|
176
|
+
['refresh_token', 'TEXT'], // токен обновления (есть только у входа по коду)
|
|
177
|
+
['access_until', 'TEXT'], // до какого времени действует текущий токен (у бессрочного — пусто)
|
|
178
|
+
]);
|
|
174
179
|
|
|
175
180
|
const q = {
|
|
176
181
|
getUser: db.prepare('SELECT * FROM users WHERE user_id = ?'),
|
|
@@ -247,10 +252,12 @@ export function openDb(path = 'data/bot.db') {
|
|
|
247
252
|
listGitAccounts: db.prepare('SELECT * FROM git_accounts WHERE user_id = ? ORDER BY added_at'),
|
|
248
253
|
allGitAccounts: db.prepare('SELECT * FROM git_accounts'),
|
|
249
254
|
saveGitAccount: db.prepare(
|
|
250
|
-
`INSERT INTO git_accounts (user_id, host, login, name, email, token, expires_at, added_at) VALUES (
|
|
255
|
+
`INSERT INTO git_accounts (user_id, host, login, name, email, token, expires_at, added_at, refresh_token, access_until) VALUES (?,?,?,?,?,?,?,?,?,?)
|
|
251
256
|
ON CONFLICT(user_id, host) DO UPDATE SET login = excluded.login, name = excluded.name, email = excluded.email,
|
|
252
|
-
token = excluded.token, expires_at = excluded.expires_at, added_at = excluded.added_at
|
|
257
|
+
token = excluded.token, expires_at = excluded.expires_at, added_at = excluded.added_at,
|
|
258
|
+
refresh_token = excluded.refresh_token, access_until = excluded.access_until`,
|
|
253
259
|
),
|
|
260
|
+
setGitTokens: db.prepare('UPDATE git_accounts SET token = ?, refresh_token = ?, access_until = ? WHERE user_id = ? AND host = ?'),
|
|
254
261
|
deleteGitAccount: db.prepare('DELETE FROM git_accounts WHERE user_id = ? AND host = ?'),
|
|
255
262
|
deleteGitAccountsByHost: db.prepare('DELETE FROM git_accounts WHERE host = ?'),
|
|
256
263
|
};
|
|
@@ -329,9 +336,14 @@ export function openDb(path = 'data/bot.db') {
|
|
|
329
336
|
listGitAccounts: (userId) => safe(() => q.listGitAccounts.all(userId))() ?? [],
|
|
330
337
|
/** Аккаунты всех пользователей (для напоминаний об истекающих токенах). */
|
|
331
338
|
allGitAccounts: () => safe(() => q.allGitAccounts.all())() ?? [],
|
|
332
|
-
/**
|
|
339
|
+
/**
|
|
340
|
+
* Сохраняет аккаунт сервиса: {host, login, name, email, token, expiresAt, refreshToken, accessUntil}.
|
|
341
|
+
* refreshToken и accessUntil — только у входа по коду с обновляемым токеном. Возвращает true, если записано.
|
|
342
|
+
*/
|
|
333
343
|
saveGitAccount: (userId, a) =>
|
|
334
|
-
safe(() => q.saveGitAccount.run(userId, a.host, a.login ?? null, a.name ?? null, a.email ?? null, a.token, a.expiresAt ?? null, now()).changes === 1)() ?? false,
|
|
344
|
+
safe(() => q.saveGitAccount.run(userId, a.host, a.login ?? null, a.name ?? null, a.email ?? null, a.token, a.expiresAt ?? null, now(), a.refreshToken ?? null, a.accessUntil ?? null).changes === 1)() ?? false,
|
|
345
|
+
/** Записывает обновлённую пару токенов аккаунта. */
|
|
346
|
+
setGitTokens: safe((userId, host, { token, refreshToken, accessUntil }) => q.setGitTokens.run(token, refreshToken ?? null, accessUntil ?? null, userId, host)),
|
|
335
347
|
deleteGitAccount: safe((userId, host) => q.deleteGitAccount.run(userId, host)),
|
|
336
348
|
/** Удаляет аккаунты всех пользователей на сервисе (сервис убран администратором). Возвращает число удалённых. */
|
|
337
349
|
deleteGitAccountsByHost: (host) => safe(() => Number(q.deleteGitAccountsByHost.run(host).changes))() ?? 0,
|
package/src/gitAccess.mjs
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
// бот по кнопкам в /git, а агент работает с репозиторием локально. Администратор может выбрать другой режим —
|
|
5
5
|
// GIT_AGENT_AUTH=1: тогда вход передаётся и процессу агента (через его окружение), и агент сам тянет и отправляет
|
|
6
6
|
// изменения. Это удобнее, но токен становится виден агенту, а значит может попасть в запрос к модели.
|
|
7
|
-
import { db } from './ctx.mjs';
|
|
7
|
+
import { db, log } from './ctx.mjs';
|
|
8
|
+
import { DeviceError, deviceLogin, refreshLogin } from './gitDevice.mjs';
|
|
8
9
|
import { configEnv, gitAvailable } from './git.mjs';
|
|
9
10
|
import { authConfig, customHost, gitHosts, hostById, hostOfUrl } from './gitHosts.mjs';
|
|
10
11
|
|
|
@@ -91,6 +92,49 @@ export function agentGitEnv(userId, { agentAuth = GIT_AGENT_AUTH, base = process
|
|
|
91
92
|
return agentAuth ? { ...env, GIT_TERMINAL_PROMPT: '0' } : env;
|
|
92
93
|
}
|
|
93
94
|
|
|
95
|
+
// ---- обновление входа, полученного по ссылке и коду (GitLab: токен живёт 2 часа) ----
|
|
96
|
+
|
|
97
|
+
/** За сколько до истечения токен обновляется заранее: операция (клонирование, отправка) должна успеть с ним закончиться. */
|
|
98
|
+
const REFRESH_AHEAD_MS = 15 * 60_000;
|
|
99
|
+
const refreshing = new Map(); // «пользователь:сервис» → идущее обновление (второе не запускаем: токен обновления одноразовый)
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Обновляет токены аккаунтов пользователя, которым пора (вход по коду с истекающим токеном). Вызывается перед любой
|
|
103
|
+
* операцией /git: дальше код читает из базы уже свежий токен. Токен обновления одноразовый, поэтому одновременные
|
|
104
|
+
* вызовы ждут одно и то же обновление.
|
|
105
|
+
* @returns {Promise<{host: object, login: string}[]>} аккаунты, вход в которые больше не действует — они отключены,
|
|
106
|
+
* пользователю нужно подключить их заново
|
|
107
|
+
*/
|
|
108
|
+
export async function refreshAccounts(userId, { now = Date.now(), refresh = refreshLogin } = {}) {
|
|
109
|
+
const lost = [];
|
|
110
|
+
for (const { host, account } of accountsOf(userId)) {
|
|
111
|
+
if (!account.refresh_token || !account.access_until || Date.parse(account.access_until) - now > REFRESH_AHEAD_MS) continue;
|
|
112
|
+
const cfg = deviceLogin(host);
|
|
113
|
+
const key = `${userId}:${host.id}`;
|
|
114
|
+
if (!refreshing.has(key)) {
|
|
115
|
+
const run = (async () => {
|
|
116
|
+
if (!cfg) throw new DeviceError('expired', 'вход по коду для сервиса выключен');
|
|
117
|
+
const g = await refresh(cfg, account.refresh_token);
|
|
118
|
+
db.setGitTokens(userId, host.id, { token: g.token, refreshToken: g.refreshToken ?? account.refresh_token, accessUntil: g.expiresIn ? new Date(Date.now() + g.expiresIn * 1000).toISOString() : null });
|
|
119
|
+
log('git: вход обновлён:', userId, host.id);
|
|
120
|
+
})().finally(() => refreshing.delete(key));
|
|
121
|
+
refreshing.set(key, run);
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
await refreshing.get(key);
|
|
125
|
+
} catch (e) {
|
|
126
|
+
log('git: вход не обновлён:', userId, host.id, '|', e.code ?? '', e.message);
|
|
127
|
+
// сервис больше не принимает токен обновления: аккаунт бесполезен — отключаем, пользователь подключит заново.
|
|
128
|
+
// Сбой сети — не повод отключать: попробуем при следующей операции
|
|
129
|
+
if (e instanceof DeviceError && e.code === 'expired') {
|
|
130
|
+
db.deleteGitAccount(userId, host.id);
|
|
131
|
+
lost.push({ host, login: account.login });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return lost;
|
|
136
|
+
}
|
|
137
|
+
|
|
94
138
|
const DAY_MS = 24 * 3600_000;
|
|
95
139
|
|
|
96
140
|
/**
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Вход в сервис Git без токена доступа — «по ссылке и коду» (OAuth 2.0 Device Authorization Grant).
|
|
2
|
+
// Пользователь открывает страницу сервиса, вводит короткий код и подтверждает доступ; бот в это время опрашивает
|
|
3
|
+
// сервис и получает токен сам. Ничего секретного в чат не попадает вовсе.
|
|
4
|
+
//
|
|
5
|
+
// Для этого у сервиса должно быть зарегистрировано приложение. Его идентификатор (client_id) — открытый, секрета
|
|
6
|
+
// приложения для такого входа не нужно. Идентификаторы приложений AcpGram на GitHub.com и GitLab.com встроены: вход
|
|
7
|
+
// работает в любой установке без настройки. GITHUB_CLIENT_ID и GITLAB_CLIENT_ID задают свои приложения, значение
|
|
8
|
+
// «0» выключает вход по коду для сервиса. У своих серверов такого входа нет — только токен доступа.
|
|
9
|
+
//
|
|
10
|
+
// У GitLab токен, полученный так, живёт 2 часа и обновляется токеном обновления (refreshLogin); у GitHub — бессрочный.
|
|
11
|
+
|
|
12
|
+
const TIMEOUT_MS = 15_000;
|
|
13
|
+
const GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
|
|
14
|
+
|
|
15
|
+
/** Приложения AcpGram в общих сервисах. Идентификаторы открытые, не секреты. */
|
|
16
|
+
const APPS = {
|
|
17
|
+
// github.com: OAuth App с включённым Device Flow
|
|
18
|
+
github: { clientId: 'Ov23linzwgdPFp8u76Qq', env: 'GITHUB_CLIENT_ID', code: '/login/device/code', token: '/login/oauth/access_token', scope: 'repo read:org' },
|
|
19
|
+
// gitlab.com: приложение с включённым Device authorization grant, не конфиденциальное
|
|
20
|
+
gitlab: { clientId: 'da562dbf4a08da1dc4f0b1fcc52259edb60ebb7aaa0a158e36c76dbe3b07f41d', env: 'GITLAB_CLIENT_ID', code: '/oauth/authorize_device', token: '/oauth/token', scope: 'api read_repository write_repository' },
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Настройки входа по коду для сервиса или null, если такого входа у него нет (тогда — только токен доступа).
|
|
25
|
+
* @returns {{clientId: string, codeUrl: string, tokenUrl: string, scope: string} | null}
|
|
26
|
+
*/
|
|
27
|
+
export function deviceLogin(host, env = process.env) {
|
|
28
|
+
const app = host && Object.hasOwn(APPS, host.id) ? APPS[host.id] : null; // свои серверы — только по токену
|
|
29
|
+
if (!app) return null;
|
|
30
|
+
const id = (env[app.env] ?? '').trim() || app.clientId;
|
|
31
|
+
if (id === '0' || id.toLowerCase() === 'off') return null;
|
|
32
|
+
return { clientId: id, codeUrl: `${host.web}${app.code}`, tokenUrl: `${host.web}${app.token}`, scope: app.scope };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Вход не состоялся: code — 'expired' (код или вход устарел), 'denied' (пользователь отказал), 'cancelled', 'failed'. */
|
|
36
|
+
export class DeviceError extends Error {
|
|
37
|
+
constructor(code, message = code) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.code = code;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function post(url, body, fetchImpl) {
|
|
44
|
+
let res;
|
|
45
|
+
try {
|
|
46
|
+
res = await fetchImpl(url, {
|
|
47
|
+
method: 'POST',
|
|
48
|
+
headers: { accept: 'application/json', 'content-type': 'application/json', 'user-agent': 'acpgram' },
|
|
49
|
+
body: JSON.stringify(body),
|
|
50
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
51
|
+
});
|
|
52
|
+
} catch (e) {
|
|
53
|
+
throw new DeviceError('failed', e.message);
|
|
54
|
+
}
|
|
55
|
+
// сервисы отвечают JSON и при отказе (GitLab — с кодом 400): разбираем тело при любом коде ответа
|
|
56
|
+
const data = await res.json().catch(() => null);
|
|
57
|
+
if (!data) throw new DeviceError('failed', `HTTP ${res.status}`);
|
|
58
|
+
return data;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Вход из ответа сервиса: {token, refreshToken, expiresIn} (refreshToken и expiresIn — null у бессрочного токена). */
|
|
62
|
+
const grantOf = (d) => ({ token: d.access_token, refreshToken: d.refresh_token || null, expiresIn: Number(d.expires_in) > 0 ? Number(d.expires_in) : null });
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Начинает вход: сервис выдаёт код для пользователя и код для опроса.
|
|
66
|
+
* @returns {Promise<{deviceCode: string, userCode: string, url: string, interval: number, expiresIn: number}>}
|
|
67
|
+
* url — страница, где вводится код (у GitLab — уже с кодом); interval — как часто можно опрашивать (с); expiresIn — срок кода (с)
|
|
68
|
+
*/
|
|
69
|
+
export async function startDeviceLogin(cfg, { fetchImpl = fetch } = {}) {
|
|
70
|
+
const d = await post(cfg.codeUrl, { client_id: cfg.clientId, scope: cfg.scope }, fetchImpl);
|
|
71
|
+
if (!d.device_code || !d.user_code) throw new DeviceError('failed', d.error_description || d.error || 'сервис не выдал код');
|
|
72
|
+
return { deviceCode: d.device_code, userCode: d.user_code, url: d.verification_uri_complete || d.verification_uri, interval: Number(d.interval) || 5, expiresIn: Number(d.expires_in) || 900 };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Один опрос: подтвердил ли пользователь вход.
|
|
77
|
+
* @returns {Promise<{token: string, refreshToken: string|null, expiresIn: number|null} | {pending: true, slowDown: boolean}>}
|
|
78
|
+
* бросает DeviceError, если вход не состоится
|
|
79
|
+
*/
|
|
80
|
+
export async function pollDeviceLogin(cfg, deviceCode, { fetchImpl = fetch } = {}) {
|
|
81
|
+
const d = await post(cfg.tokenUrl, { client_id: cfg.clientId, device_code: deviceCode, grant_type: GRANT }, fetchImpl);
|
|
82
|
+
if (d.access_token) return grantOf(d);
|
|
83
|
+
if (d.error === 'authorization_pending') return { pending: true, slowDown: false };
|
|
84
|
+
if (d.error === 'slow_down') return { pending: true, slowDown: true };
|
|
85
|
+
if (d.error === 'expired_token') throw new DeviceError('expired');
|
|
86
|
+
if (d.error === 'access_denied') throw new DeviceError('denied');
|
|
87
|
+
throw new DeviceError('failed', d.error_description || d.error || 'неизвестный ответ сервиса');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Пауза между опросами; в тестах подменяется, чтобы не ждать. */
|
|
91
|
+
export const deviceTiming = { sleep: (ms) => new Promise((r) => setTimeout(r, ms)) };
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Ждёт подтверждения входа: опрашивает сервис с его интервалом, пока код действует.
|
|
95
|
+
* @param {() => boolean} cancelled вход отменён пользователем — опрос прекращается (DeviceError 'cancelled')
|
|
96
|
+
* @returns {Promise<{token: string, refreshToken: string|null, expiresIn: number|null}>}
|
|
97
|
+
*/
|
|
98
|
+
export async function waitDeviceLogin(cfg, login, { cancelled = () => false, fetchImpl = fetch, now = () => Date.now() } = {}) {
|
|
99
|
+
const deadline = now() + login.expiresIn * 1000;
|
|
100
|
+
let interval = login.interval;
|
|
101
|
+
while (now() < deadline) {
|
|
102
|
+
await deviceTiming.sleep(interval * 1000);
|
|
103
|
+
if (cancelled()) throw new DeviceError('cancelled');
|
|
104
|
+
const r = await pollDeviceLogin(cfg, login.deviceCode, { fetchImpl });
|
|
105
|
+
if (r.token) return r;
|
|
106
|
+
if (r.slowDown) interval += 5; // сервис просит опрашивать реже
|
|
107
|
+
}
|
|
108
|
+
throw new DeviceError('expired');
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Обновляет вход токеном обновления: сервис выдаёт новую пару (прежние токены после этого недействительны).
|
|
113
|
+
* @returns {Promise<{token: string, refreshToken: string|null, expiresIn: number|null}>}
|
|
114
|
+
* DeviceError 'expired' — токен обновления больше не принимается: аккаунт нужно подключить заново
|
|
115
|
+
*/
|
|
116
|
+
export async function refreshLogin(cfg, refreshToken, { fetchImpl = fetch } = {}) {
|
|
117
|
+
const d = await post(cfg.tokenUrl, { client_id: cfg.clientId, refresh_token: refreshToken, grant_type: 'refresh_token' }, fetchImpl);
|
|
118
|
+
if (d.access_token) return grantOf(d);
|
|
119
|
+
if (d.error === 'invalid_grant' || d.error === 'invalid_token') throw new DeviceError('expired', d.error_description || d.error);
|
|
120
|
+
throw new DeviceError('failed', d.error_description || d.error || 'неизвестный ответ сервиса');
|
|
121
|
+
}
|
package/src/gitHosts.mjs
CHANGED
|
@@ -25,7 +25,7 @@ export function normalizeHostUrl(input) {
|
|
|
25
25
|
/** Id своего сервера: вид и адрес («gitlab-git-example-com») — одинаковый, откуда бы сервер ни был задан. */
|
|
26
26
|
const hostId = (kind, web) => `${kind}-${web.replace(/^https:\/\//, '')}`.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-+$/, '').slice(0, 40);
|
|
27
27
|
|
|
28
|
-
const githubHost = (id, label, web, api) => ({ id, kind: 'github', label, web, api, tokenUrl: `${web}/settings/tokens`, user: 'x-access-token', scopes: 'repo' });
|
|
28
|
+
const githubHost = (id, label, web, api) => ({ id, kind: 'github', label, web, api, tokenUrl: `${web}/settings/tokens`, user: 'x-access-token', scopes: 'repo, read:org' });
|
|
29
29
|
const gitlabHost = (id, label, web) => ({ id, kind: 'gitlab', label, web, api: `${web}/api/v4`, tokenUrl: `${web}/-/user_settings/personal_access_tokens`, user: 'oauth2', scopes: 'api, read_repository, write_repository' });
|
|
30
30
|
|
|
31
31
|
/**
|
|
@@ -119,7 +119,7 @@ function errorDetail(data) {
|
|
|
119
119
|
export async function api(host, token, path, { fetchImpl = fetch, method = null, body = null } = {}) {
|
|
120
120
|
const headers = host.kind === 'github'
|
|
121
121
|
? { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'user-agent': 'acpgram' }
|
|
122
|
-
: {
|
|
122
|
+
: { authorization: `Bearer ${token}`, accept: 'application/json', 'user-agent': 'acpgram' }; // так GitLab принимает и токен доступа, и токен входа по коду
|
|
123
123
|
const init = { headers, signal: AbortSignal.timeout(TIMEOUT_MS) };
|
|
124
124
|
if (body) Object.assign(init, { method: method ?? 'POST', body: JSON.stringify(body), headers: { ...headers, 'content-type': 'application/json' } });
|
|
125
125
|
else if (method) init.method = method;
|
package/src/gitUi.mjs
CHANGED
|
@@ -5,8 +5,9 @@ import { join } from 'node:path';
|
|
|
5
5
|
import { db, langOf, log, say } from './ctx.mjs';
|
|
6
6
|
import { canManageFiles } from './filesUi.mjs';
|
|
7
7
|
import { GitError, cloneRepo, commitAll, fetchRepo, gitAvailable, gitCommand, gitEnv, pullRepo, pushRepo, repoState, unpushedSecrets } from './git.mjs';
|
|
8
|
+
import { DeviceError, deviceLogin, startDeviceLogin, waitDeviceLogin } from './gitDevice.mjs';
|
|
8
9
|
import { recall, remember } from './gitKeys.mjs';
|
|
9
|
-
import { accountsOf, addCustomHost, findHost, hostFor, hosts as allHosts, identityOf, removeCustomHost, renameCustomHost } from './gitAccess.mjs';
|
|
10
|
+
import { accountsOf, addCustomHost, findHost, hostFor, hosts as allHosts, identityOf, refreshAccounts, removeCustomHost, renameCustomHost } from './gitAccess.mjs';
|
|
10
11
|
import { PUBLISH_ACTIONS, PUBLISH_INPUTS, canPublish, onPublishCallback, onPublishInput } from './gitPublishUi.mjs';
|
|
11
12
|
import { REPO_ACTIONS, onBranchInput, onRepoCallback } from './gitRepoUi.mjs';
|
|
12
13
|
import { HostError, authConfig, customHost, fetchProfile, listRepos, missingScopes, probeHost, repoFolder, showRemote } from './gitHosts.mjs';
|
|
@@ -117,10 +118,20 @@ function hostsView(lang, note = '') {
|
|
|
117
118
|
return { text: `${note ? `${note}\n\n` : ''}${th('git.hosts.head', lang)}\n\n${list}`, markup: { inline_keyboard: rows } };
|
|
118
119
|
}
|
|
119
120
|
|
|
121
|
+
/**
|
|
122
|
+
* Перед любой операцией /git: обновить входы, которым пора (вход по коду с истекающим токеном). Если сервис больше
|
|
123
|
+
* не принимает вход, аккаунт отключён — пользователю об этом сообщение.
|
|
124
|
+
*/
|
|
125
|
+
async function freshen(st) {
|
|
126
|
+
const lost = await refreshAccounts(st.userId).catch((e) => (log('git: обновление входа:', e.message), []));
|
|
127
|
+
for (const x of lost) await say(st.to, t('git.dv.lost', langOf(st.userId), { host: x.host.label, login: x.login }));
|
|
128
|
+
}
|
|
129
|
+
|
|
120
130
|
/** /git */
|
|
121
131
|
export async function handleGit(st) {
|
|
122
132
|
const lang = langOf(st.userId);
|
|
123
133
|
if (!gitAvailable()) return say(st.to, t('git.none', lang));
|
|
134
|
+
await freshen(st);
|
|
124
135
|
const v = await gitView(st, lang, { sync: true });
|
|
125
136
|
return tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup }).catch((e) => log('git:', e.message));
|
|
126
137
|
}
|
|
@@ -133,6 +144,7 @@ export async function handleGit(st) {
|
|
|
133
144
|
*/
|
|
134
145
|
export async function offerGitActions(st, actions) {
|
|
135
146
|
if (!gitAvailable() || !actions.length) return;
|
|
147
|
+
await freshen(st);
|
|
136
148
|
const lang = langOf(st.userId);
|
|
137
149
|
const project = projectOf(st);
|
|
138
150
|
const repo = project ? await repoOf(st, project).catch(() => null) : null;
|
|
@@ -243,6 +255,66 @@ async function repoAction(st, action, lang, edit, { message = null } = {}) {
|
|
|
243
255
|
}
|
|
244
256
|
}
|
|
245
257
|
|
|
258
|
+
/** Сохраняет подключённый аккаунт и сообщает об этом: кто подключён, срок токена, чего не хватает; затем — экран /git. */
|
|
259
|
+
async function finishConnect(st, host, grant, profile, lang, send, key) {
|
|
260
|
+
// вход по коду с токеном, который истекает и не обновляется, через пару часов перестал бы работать — не подключаем
|
|
261
|
+
if (grant.expiresIn && !grant.refreshToken) {
|
|
262
|
+
log('⚠️ git: вход по коду без токена обновления — аккаунт не подключён:', st.userId, host.id, `| срок ${grant.expiresIn} с`);
|
|
263
|
+
return send({ text: th('git.dv.noRefresh', lang, { host: host.label }) });
|
|
264
|
+
}
|
|
265
|
+
const accessUntil = grant.expiresIn ? new Date(Date.now() + grant.expiresIn * 1000).toISOString() : null;
|
|
266
|
+
// срок, который сервис сообщает о продлеваемом входе, — это срок текущего токена, а не аккаунта: напоминать о нём незачем
|
|
267
|
+
const expiresAt = grant.refreshToken ? null : profile.expiresAt;
|
|
268
|
+
if (!db.saveGitAccount(st.userId, { host: host.id, login: profile.login, name: profile.name, email: profile.email, token: grant.token, expiresAt, refreshToken: grant.refreshToken ?? null, accessUntil })) {
|
|
269
|
+
return send({ text: th('access.saveFail', lang) });
|
|
270
|
+
}
|
|
271
|
+
log('аккаунт git подключён:', st.userId, host.id, profile.login, grant.refreshToken ? `| вход обновляемый, срок токена ${grant.expiresIn} с` : '');
|
|
272
|
+
const lack = missingScopes(host, profile.scopes);
|
|
273
|
+
const parts = [
|
|
274
|
+
th(key, lang, { host: host.label, login: profile.login, name: profile.name }),
|
|
275
|
+
...(expiresAt ? [th('git.expires', lang, { date: dateOf(expiresAt, lang) })] : []),
|
|
276
|
+
...(lack.length ? [th('git.scopesWarn', lang, { scopes: lack.join(', ') })] : []),
|
|
277
|
+
];
|
|
278
|
+
await send({ text: parts.join('\n') });
|
|
279
|
+
return send(await gitView(st, lang));
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Вход по ссылке и коду: бот показывает страницу сервиса и код, а сам ждёт подтверждения и подключает аккаунт.
|
|
284
|
+
* Ожидание идёт в фоне (до срока кода); «Отмена» или новый вход прекращают его.
|
|
285
|
+
*/
|
|
286
|
+
async function startCodeLogin(st, host, cfg, lang, edit) {
|
|
287
|
+
let login;
|
|
288
|
+
try {
|
|
289
|
+
login = await startDeviceLogin(cfg);
|
|
290
|
+
} catch (e) {
|
|
291
|
+
log('git: вход по коду:', e.message, '| пользователь', st.userId);
|
|
292
|
+
return edit({ text: th('git.dv.fail', lang, { msg: e.message }) });
|
|
293
|
+
}
|
|
294
|
+
const attempt = { host: host.id };
|
|
295
|
+
st.gitDevice = attempt; // новый вход или «Отмена» заменяют запись — прежнее ожидание это видит и прекращается
|
|
296
|
+
await edit({
|
|
297
|
+
text: th('git.dv.how', lang, { host: host.label, url: login.url, code: hCode(login.userCode), min: Math.round(login.expiresIn / 60) }),
|
|
298
|
+
markup: { inline_keyboard: [[{ text: t('git.dv.open', lang, { host: host.label }), url: login.url }], [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]] },
|
|
299
|
+
});
|
|
300
|
+
const send = (v) => tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('git:', e.message));
|
|
301
|
+
// не ждём здесь: обработка нажатия заканчивается сразу, подтверждение придёт позже
|
|
302
|
+
waitDeviceLogin(cfg, login, { cancelled: () => st.gitDevice !== attempt })
|
|
303
|
+
.then(async (grant) => {
|
|
304
|
+
st.gitDevice = null;
|
|
305
|
+
const profile = await fetchProfile(host, grant.token);
|
|
306
|
+
await edit({ text: th('git.dv.ok', lang, { host: host.label }) });
|
|
307
|
+
await finishConnect(st, host, grant, profile, lang, send, 'git.connectedCode');
|
|
308
|
+
})
|
|
309
|
+
.catch((e) => {
|
|
310
|
+
if (st.gitDevice === attempt) st.gitDevice = null;
|
|
311
|
+
if (e instanceof DeviceError && e.code === 'cancelled') return null;
|
|
312
|
+
log('git: вход по коду:', e.code ?? '', e.message, '| пользователь', st.userId);
|
|
313
|
+
const key = e instanceof DeviceError && e.code === 'expired' ? 'git.dv.expired' : e instanceof DeviceError && e.code === 'denied' ? 'git.dv.denied' : 'git.dv.fail';
|
|
314
|
+
return edit({ text: th(key, lang, { msg: e.message }) });
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
246
318
|
/** Кнопки /git (gt:<действие>[:<аргумент>[:<страница>]]). */
|
|
247
319
|
export async function onGitCallback(st, cb) {
|
|
248
320
|
const [, action, arg, pageStr] = (cb.data || '').split(':');
|
|
@@ -252,8 +324,10 @@ export async function onGitCallback(st, cb) {
|
|
|
252
324
|
const ack = (text) => tg('answerCallbackQuery', { callback_query_id: cb.id, ...(text ? { text, show_alert: true } : {}) }).catch(() => {});
|
|
253
325
|
const edit = (v) => tg('editMessageText', { chat_id: chatId, message_id: messageId, text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => /not modified/i.test(e.message) || log('git:', e.message));
|
|
254
326
|
if (!gitAvailable()) return ack(t('git.none', lang));
|
|
327
|
+
await freshen(st);
|
|
255
328
|
if (action === 'x') {
|
|
256
329
|
st.pendingInput = null;
|
|
330
|
+
st.gitDevice = null; // и ожидание входа по коду, если оно шло
|
|
257
331
|
await ack();
|
|
258
332
|
return edit({ text: th('files.cancelled', lang) });
|
|
259
333
|
}
|
|
@@ -297,7 +371,18 @@ export async function onGitCallback(st, cb) {
|
|
|
297
371
|
if (action === 'c' && host) {
|
|
298
372
|
await ack();
|
|
299
373
|
st.pendingInput = { kind: 'gitToken', host: host.id, at: Date.now() };
|
|
300
|
-
|
|
374
|
+
// у сервиса с входом по коду токен не обязателен: кнопка «Войти без токена» (сам токен тоже можно прислать)
|
|
375
|
+
const byCode = deviceLogin(host);
|
|
376
|
+
const text = th('git.tokenAsk', lang, { host: host.label, url: host.tokenUrl, scopes: hCode(host.scopes) }) + (byCode ? `\n\n${th('git.dv.or', lang)}` : '');
|
|
377
|
+
const rows = [...(byCode ? [[{ text: t('git.dv.btn', lang), callback_data: `gt:dv:${host.id}`, style: 'success' }]] : []), [{ text: t('btn.cancel', lang), callback_data: 'gt:x' }]];
|
|
378
|
+
return say(st.to, text, { ...HTML, reply_markup: { inline_keyboard: rows } });
|
|
379
|
+
}
|
|
380
|
+
if (action === 'dv' && host) {
|
|
381
|
+
const cfg = deviceLogin(host);
|
|
382
|
+
if (!cfg) return ack(t('proj.stale', lang));
|
|
383
|
+
await ack();
|
|
384
|
+
st.pendingInput = null; // токен больше не ждём: вход идёт по коду
|
|
385
|
+
return startCodeLogin(st, host, cfg, lang, edit);
|
|
301
386
|
}
|
|
302
387
|
if ((action === 'a' || action === 'd') && account) {
|
|
303
388
|
await ack();
|
|
@@ -385,6 +470,7 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
|
|
|
385
470
|
const wait = st.pendingInput;
|
|
386
471
|
if (!['gitToken', 'gitSearch', 'gitMessage', 'gitHostUrl', 'gitHostName', 'gitBranch', ...PUBLISH_INPUTS].includes(wait?.kind)) return false;
|
|
387
472
|
const lang = langOf(st.userId);
|
|
473
|
+
await freshen(st);
|
|
388
474
|
const expired = now - wait.at > GIT_WAIT_MS;
|
|
389
475
|
const send = (v) => tg('sendMessage', { ...dest(st.to), text: v.text, ...HTML, reply_markup: v.markup ?? { inline_keyboard: [] } }).catch((e) => log('git:', e.message));
|
|
390
476
|
|
|
@@ -406,18 +492,7 @@ export async function onGitInput(st, text, { messageId, now = Date.now() } = {})
|
|
|
406
492
|
return (await say(st.to, textFail, { reply_markup: cancelMarkup(lang) }), true); // ожидание остаётся: можно прислать ещё раз
|
|
407
493
|
}
|
|
408
494
|
st.pendingInput = null;
|
|
409
|
-
|
|
410
|
-
return (await say(st.to, t('access.saveFail', lang)), true);
|
|
411
|
-
}
|
|
412
|
-
log('аккаунт git подключён:', st.userId, host.id, profile.login);
|
|
413
|
-
const lack = missingScopes(host, profile.scopes);
|
|
414
|
-
const parts = [
|
|
415
|
-
th('git.connected', lang, { host: host.label, login: profile.login, name: profile.name }),
|
|
416
|
-
...(profile.expiresAt ? [th('git.expires', lang, { date: dateOf(profile.expiresAt, lang) })] : []),
|
|
417
|
-
...(lack.length ? [th('git.scopesWarn', lang, { scopes: lack.join(', ') })] : []),
|
|
418
|
-
];
|
|
419
|
-
await send({ text: parts.join('\n') });
|
|
420
|
-
await send(await gitView(st, lang));
|
|
495
|
+
await finishConnect(st, host, { token }, profile, lang, send, 'git.connected');
|
|
421
496
|
return true;
|
|
422
497
|
}
|
|
423
498
|
|
package/src/i18n.mjs
CHANGED
|
@@ -99,6 +99,7 @@ const M = {
|
|
|
99
99
|
'menu.close': { en: 'Close the session and free the slot', ru: 'Закрыть сессию и освободить слот', uk: 'Закрити сесію та звільнити слот' },
|
|
100
100
|
'menu.language': { en: 'Choose the interface language', ru: 'Выбрать язык интерфейса', uk: 'Обрати мову інтерфейсу' },
|
|
101
101
|
'menu.start': { en: 'Welcome and the current project', ru: 'Приветствие и текущий проект', uk: 'Привітання та поточний проєкт' },
|
|
102
|
+
'menu.help': { en: 'Documentation with AI chat', ru: 'Документация с ИИ-чатом', uk: 'Документація з AI-чатом' },
|
|
102
103
|
'menu.active': { en: 'Active sessions: who holds the slots', ru: 'Активные сессии: кто занимает слоты', uk: 'Активні сесії: хто займає слоти' },
|
|
103
104
|
'menu.users': { en: 'Users with access: levels and revocation', ru: 'Сотрудники с доступом: уровни и отзыв', uk: 'Співробітники з доступом: рівні та відкликання' },
|
|
104
105
|
'menu.usage': { en: 'Usage: requests and tokens by user', ru: 'Расход: запросы и токены по сотрудникам', uk: 'Витрати: запити й токени по співробітниках' },
|
|
@@ -130,6 +131,10 @@ const M = {
|
|
|
130
131
|
'help.active': { en: '/active — active sessions', ru: '/active — активные сессии', uk: '/active — активні сесії' },
|
|
131
132
|
'help.usage': { en: '/usage — requests and tokens by user', ru: '/usage — запросы и токены по сотрудникам', uk: '/usage — запити й токени по співробітниках' },
|
|
132
133
|
'help.invite': { en: '/invite — invite a user', ru: '/invite — пригласить сотрудника', uk: '/invite — запросити співробітника' },
|
|
134
|
+
'help.help': { en: '/help — full documentation with an AI chat', ru: '/help — полная документация с ИИ-чатом', uk: '/help — повна документація з AI-чатом' },
|
|
135
|
+
'help.text': { en: '📖 Full documentation with an AI chat: {url}\n\nAsk a question and get an answer with links to the right section.', ru: '📖 Полная документация с ИИ-чатом: {url}\n\nЗадайте вопрос — ответ придёт со ссылкой на нужный раздел.', uk: '📖 Повна документація з AI-чатом: {url}\n\nЗадайте запитання — відповідь буде з посиланням на потрібний розділ.' },
|
|
136
|
+
'help.btn.browser': { en: 'Open in browser', ru: 'Открыть в браузере', uk: 'Відкрити у браузері' },
|
|
137
|
+
'help.btn.app': { en: 'Open mini app', ru: 'Открыть мини-приложение', uk: 'Відкрити мінізастосунок' },
|
|
133
138
|
|
|
134
139
|
// ---------- уровни доступа ----------
|
|
135
140
|
'level.read.label': { en: 'Read-only', ru: 'Чтение', uk: 'Читання' },
|
|
@@ -429,6 +434,17 @@ const M = {
|
|
|
429
434
|
'git.offer.noAccount': { en: "ℹ️ The agent suggests pushing or pulling changes, but the project is not connected to a Git server or the account is not connected. Open /git.", ru: "ℹ️ Агент предлагает отправить или получить изменения, но проект не связан с сервером Git или аккаунт не подключён. Откройте /git.", uk: "ℹ️ Агент пропонує надіслати або отримати зміни, але проєкт не пов’язаний із сервером Git або акаунт не підключено. Відкрийте /git." },
|
|
430
435
|
'git.exp.soon': { en: "⏰ The access token for {host} ({login}) expires on {date} — days left: {days}. Create a new one and connect the account again in /git, otherwise cloning and pushing will stop working.", ru: "⏰ Токен доступа к {host} ({login}) истекает {date} — осталось дней: {days}. Создайте новый и подключите аккаунт заново в /git, иначе клонирование и отправка перестанут работать.", uk: "⏰ Токен доступу до {host} ({login}) спливає {date} — залишилося днів: {days}. Створіть новий і підключіть акаунт знову в /git, інакше клонування й надсилання перестануть працювати." },
|
|
431
436
|
'git.exp.expired': { en: "⛔ The access token for {host} ({login}) expired on {date}. Connect the account again in /git with a new token.", ru: "⛔ Токен доступа к {host} ({login}) истёк {date}. Подключите аккаунт заново в /git с новым токеном.", uk: "⛔ Токен доступу до {host} ({login}) сплив {date}. Підключіть акаунт знову в /git із новим токеном." },
|
|
437
|
+
'git.dv.or': { en: "Or sign in without a token — with the button below.", ru: "Или войдите без токена — кнопкой ниже.", uk: "Або увійдіть без токена — кнопкою нижче." },
|
|
438
|
+
'git.dv.btn': { en: "🔗 Sign in without a token", ru: "🔗 Войти без токена", uk: "🔗 Увійти без токена" },
|
|
439
|
+
'git.dv.how': { en: "🔗 Signing in to {host} without a token\n\n1. Open {url}\n2. Enter the code: {code}\n3. Confirm access for AcpGram.\n\nThe bot is waiting for the confirmation and will connect the account by itself. The code is valid for {min} min.", ru: "🔗 Вход в {host} без токена\n\n1. Откройте {url}\n2. Введите код: {code}\n3. Подтвердите доступ для AcpGram.\n\nБот ждёт подтверждения и подключит аккаунт сам. Код действует {min} мин.", uk: "🔗 Вхід у {host} без токена\n\n1. Відкрийте {url}\n2. Введіть код: {code}\n3. Підтвердьте доступ для AcpGram.\n\nБот чекає підтвердження й підключить акаунт сам. Код дійсний {min} хв." },
|
|
440
|
+
'git.dv.open': { en: "🔗 Open {host}", ru: "🔗 Открыть {host}", uk: "🔗 Відкрити {host}" },
|
|
441
|
+
'git.dv.ok': { en: "✅ Access to {host} confirmed.", ru: "✅ Доступ к {host} подтверждён.", uk: "✅ Доступ до {host} підтверджено." },
|
|
442
|
+
'git.dv.expired': { en: "⌛ The code has expired — the sign-in was not confirmed. Start again in /git.", ru: "⌛ Код устарел — вход не подтверждён. Начните заново в /git.", uk: "⌛ Код застарів — вхід не підтверджено. Почніть знову в /git." },
|
|
443
|
+
'git.dv.denied': { en: "✖ Access was not confirmed.", ru: "✖ Доступ не подтверждён.", uk: "✖ Доступ не підтверджено." },
|
|
444
|
+
'git.dv.fail': { en: "⚠️ Could not sign in: {msg}", ru: "⚠️ Не удалось войти: {msg}", uk: "⚠️ Не вдалося увійти: {msg}" },
|
|
445
|
+
'git.connectedCode': { en: "✅ {host} connected: {login} ({name}).", ru: "✅ {host} подключён: {login} ({name}).", uk: "✅ {host} підключено: {login} ({name})." },
|
|
446
|
+
'git.dv.noRefresh': { en: "⚠️ {host} gave a sign-in that expires and cannot be renewed, so the account was not connected. Connect it with an access token instead.", ru: "⚠️ {host} выдал вход, который истекает и не продлевается, поэтому аккаунт не подключён. Подключите его токеном доступа.", uk: "⚠️ {host} видав вхід, який спливає й не продовжується, тому акаунт не підключено. Підключіть його токеном доступу." },
|
|
447
|
+
'git.dv.lost': { en: "⚠️ The sign-in to {host} ({login}) is no longer valid, the account was disconnected. Connect it again in /git.", ru: "⚠️ Вход в {host} ({login}) больше не действует, аккаунт отключён. Подключите его заново в /git.", uk: "⚠️ Вхід у {host} ({login}) більше не діє, акаунт відключено. Підключіть його знову в /git." },
|
|
432
448
|
'proj.notFound': { en: '⚠️ The folder was not found or is unavailable', ru: '⚠️ Папка не найдена или недоступна', uk: '⚠️ Папку не знайдено або вона недоступна' },
|
|
433
449
|
'proj.same': { en: '📁 Project already selected: {p}', ru: '📁 Проект уже выбран: {p}', uk: '📁 Проєкт уже обрано: {p}' },
|
|
434
450
|
'proj.set': { en: '📁 Project: {p}\nA new session starts with the next request.', ru: '📁 Проект: {p}\nНовая сессия начнётся со следующего запроса.', uk: '📁 Проєкт: {p}\nНова сесія почнеться з наступного запиту.' },
|
package/src/state.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { canUseEngine, parseJson } from './access.mjs';
|
|
|
6
6
|
import { DEFAULT_ENGINE, ENGINES, createAgent, engineCommand, engineMode, getEngine, modeAllowed, resolveEngine } from './engines.mjs';
|
|
7
7
|
import { HOME, ROOT, insideRoot, isPersonalRoot, pushRecent, samePath, showPath, userRoot } from './projects.mjs';
|
|
8
8
|
import { SANDBOX, agentSandbox } from './sandbox.mjs';
|
|
9
|
-
import { agentGitEnv } from './gitAccess.mjs';
|
|
9
|
+
import { GIT_AGENT_AUTH, agentGitEnv, refreshAccounts } from './gitAccess.mjs';
|
|
10
10
|
|
|
11
11
|
const states = new Map(); // userId -> состояние
|
|
12
12
|
|
|
@@ -337,6 +337,8 @@ async function startAgent(st, { resume } = {}) {
|
|
|
337
337
|
log('⚠️ папка проекта недоступна или вне корня пользователя — агент не запущен | пользователь', st.userId, '| проект', st.project);
|
|
338
338
|
throw new ProjectError(t('state.projectGone', langOf(st.userId)));
|
|
339
339
|
}
|
|
340
|
+
// в режиме «вход у агента» токен должен быть свежим на старте сессии (вход по коду у GitLab живёт 2 часа)
|
|
341
|
+
if (GIT_AGENT_AUTH) await refreshAccounts(st.userId).catch((e) => log('git: обновление входа перед запуском агента:', e.message));
|
|
340
342
|
releaseSessionElsewhere(st, resume);
|
|
341
343
|
reserveSlot(st);
|
|
342
344
|
const engine = engineOf(st);
|
package/src/ui.mjs
CHANGED
|
@@ -4,6 +4,14 @@ import { DEFAULT_LANG, LOCALES, plural, t } from './i18n.mjs';
|
|
|
4
4
|
import { RICH_LIMIT, balanceMarkdown, escHtml } from './telegram.mjs';
|
|
5
5
|
import { splitCode } from './files.mjs';
|
|
6
6
|
|
|
7
|
+
export const DOCS_URL = 'https://alexey-seleznev.pro/acpgram/docs/';
|
|
8
|
+
|
|
9
|
+
export const helpMarkup = (lang = DEFAULT_LANG) => ({
|
|
10
|
+
inline_keyboard: [[{ text: t('help.btn.browser', lang), url: DOCS_URL }, { text: t('help.btn.app', lang), web_app: { url: DOCS_URL } }]],
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
export const docsMenuButton = () => ({ type: 'web_app', text: '📖 Docs', web_app: { url: DOCS_URL } });
|
|
14
|
+
|
|
7
15
|
// Rich-разметка Telegram превращает теги <tg-button> в настоящие кнопки с callback_data — в любом месте текста,
|
|
8
16
|
// в любом регистре, и без <tg-button-row>. Текст агента (а в него попадает содержимое файлов и веб-страниц) не должен
|
|
9
17
|
// уметь рисовать кнопки бота: иначе нажатие «Продолжить» в ответе могло бы выполнить adm:… от имени администратора.
|
|
@@ -739,6 +747,7 @@ const button = (text, data) => `<tg-button type="callback_data" data="${data}">$
|
|
|
739
747
|
export function startView({ level, project, engine, model, isAdmin, note, topics = null, lang = DEFAULT_LANG }) {
|
|
740
748
|
const cmd = (key) => t(`help.${key}`, lang);
|
|
741
749
|
const commands = [
|
|
750
|
+
cmd('help'),
|
|
742
751
|
cmd('project'),
|
|
743
752
|
cmd('files'),
|
|
744
753
|
cmd('git'),
|