acpgram 1.28.0 → 1.30.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 CHANGED
@@ -230,11 +230,17 @@ The `/git` command connects projects to GitHub, GitLab.com and your own servers
230
230
 
231
231
  - **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
232
 
233
- - **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. Disconnecting removes the token from the bot.
233
+ - **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.
234
+ - **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
235
  - **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
236
  - **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.
236
237
  - **"📋 Changes".** The list of changed files with marks (new, modified, deleted, renamed) and the number of added and removed lines. Pressing a file shows what changed in it: short changes in the message, long ones as a file. The contents of files with secrets are not shown. The same screen lists the commits that are not pushed yet and those waiting on the server. All of this is visible without the agent and without model requests.
237
238
  - **"🌿 Branches".** Local and server branches in one list; pressing a branch switches to it, "➕ New branch" creates one from the current branch. With unsaved changes the bot does not switch and offers to save them first; the same while the agent is working. After switching, the next request starts a new agent session, because the project files have changed. "Push" creates a new branch on the server too.
239
+ - **Discarding changes.** The card of a changed file has "↩️ Restore as it was", and the "Changes" screen has "↩️ Discard all changes": modified and deleted files return to the last commit, new files are deleted. It cannot be undone, so it always asks for confirmation; files with secrets are not touched.
240
+ - **"🚀 Publish the project".** For a folder that is not connected to a server yet: the user chooses the service, the place (personal space, a GitLab group with subgroups or a GitHub organization — with search), the visibility (private, internal, public) and the name. The bot creates the repository, makes the first commit without files with secrets and pushes it.
241
+ - **"🔀 Merge request".** From the current branch into the main branch of the repository: the bot asks for a title (or suggests the last commit message), creates the request and gives the link; if an open request from this branch already exists, it shows that one.
242
+ - **The agent asks to push.** The agent has no sign-in for the server, so on "push it" it commits and puts the mark `[[git:push]]` (or `[[git:pull]]`) into its reply. The bot removes the mark and shows a button under the reply; nothing is sent without the user pressing it.
243
+ - **Token reminder.** A week before, a day before and when the token expires, the bot writes to the account owner.
238
244
  - **The commit author** is the account owner: the name and email are given to both the bot and the agent, so the agent's commits are signed by the user.
239
245
  - **Secrets do not go to the repository.** On "Save and push", files with secrets (`.env`, keys, credentials) are left out of the commit and appended to `.gitignore`. If the agent committed such a file, the bot warns before pushing and pushes only after "Push anyway".
240
246
 
@@ -294,6 +300,7 @@ What the sandbox does not do:
294
300
  | `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 |
295
301
  | `BWRAP_COMMAND` | no | path to `bwrap` if it is not in `PATH` |
296
302
  | `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") |
303
+ | `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 |
297
304
  | `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 |
298
305
  | `GIT_COMMAND` | no | path to `git` if it is not in `PATH` |
299
306
  | `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
@@ -120,11 +120,17 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
120
120
 
121
121
  - **Свои серверы** добавляет администратор прямо в `/git`: «⚙️ Свои серверы» → «➕ GitLab» или «➕ GitHub Enterprise» → адрес сервера (`https://git.example.com`). Бот проверяет, что по адресу отвечает сервер нужного вида, и после этого каждый пользователь может подключить на нём аккаунт. Там же сервер переименовывается и убирается — вместе с подключёнными к нему аккаунтами. Без этого в меню только GitHub и GitLab.com. Там, где настройки задаются файлом, сервер можно указать и в `.env` (`GITLAB_URL`, `GITHUB_URL`).
122
122
 
123
- - **Подключение аккаунта.** «➕ Подключить …» → бот даёт ссылку на страницу токенов и список нужных прав, пользователь присылает токен доступа одним сообщением. Сообщение сразу удаляется из чата и агенту не передаётся. Бот проверяет токен в сервисе, показывает, кто подключён и до какого числа токен действует, и предупреждает, если прав не хватает. Отключение удаляет токен из бота.
123
+ - **Вход в GitHub и GitLab.com без токена.** «➕ Подключить …» → «🔗 Войти без токена»: бот показывает ссылку и короткий код, пользователь вводит код на сайте сервиса и подтверждает доступ, а бот сам получает вход и подключает аккаунт. Ничего секретного в чат не попадает. Работает в любой установке без настройки: идентификаторы приложений AcpGram на GitHub.com и GitLab.com встроены (они открытые, секрета приложения для такого входа не нужно). У GitLab такой вход действует 2 часа — бот сам продлевает его перед каждой операцией; если сервис перестал его принимать, аккаунт отключается и бот просит подключить его заново. `GITHUB_CLIENT_ID` и `GITLAB_CLIENT_ID` задают свои приложения, значение `0` оставляет для сервиса только вход по токену. Свои серверы подключаются токеном.
124
+ - **Подключение аккаунта.** «➕ Подключить …» → бот даёт ссылку на страницу токенов и список нужных прав, пользователь присылает токен доступа одним сообщением. Сообщение сразу удаляется из чата и агенту не передаётся. Бот проверяет токен в сервисе, показывает, кто подключён и до какого числа токен действует, и предупреждает, если прав не хватает. Права нужны полные: у GitLab — `api`, `read_repository`, `write_repository` (без `api` не работают публикация и запросы на слияние), у GitHub — `repo`. Отключение удаляет токен из бота.
124
125
  - **Клонирование.** «⬇️ Клонировать репозиторий» (или «⬇️ Из Git» в `/project`) показывает репозитории пользователя кнопками, недавно менявшиеся первыми, с поиском по названию. Выбранный клонируется в личное пространство (без него — рядом с текущим проектом) и становится проектом.
125
126
  - **Репозиторий проекта.** Экран показывает ветку, число изменённых файлов, неотправленных коммитов и новых коммитов на сервере; при открытии и по кнопке «Обновить» он сверяется с сервером. «⬇️ Получить» забирает изменения, если это возможно без слияния; если истории разошлись, слияние делает агент. «⬆️ Отправить» отправляет коммиты. «💾 Сохранить и отправить» спрашивает описание, коммитит все изменения и отправляет.
126
127
  - **«📋 Изменения».** Список изменённых файлов с пометками (новый, изменён, удалён, переименован) и числом добавленных и убранных строк. Нажатие на файл показывает, что в нём изменилось: короткие изменения — в сообщении, длинные — файлом. Содержимое файлов с секретами не показывается. Там же — коммиты, которые ещё не отправлены, и те, что ждут на сервере. Всё это видно без агента и без запросов к модели.
127
128
  - **«🌿 Ветки».** Локальные ветки и ветки сервера одним списком; нажатие переключает на ветку, «➕ Новая ветка» создаёт её от текущей. При несохранённых изменениях бот не переключает, а предлагает сначала сохранить их; пока агент выполняет запрос — тоже. После переключения следующий запрос начинает новую сессию агента: файлы проекта сменились. «Отправить» создаёт новую ветку и на сервере.
129
+ - **Отмена изменений.** В карточке изменённого файла — «↩️ Вернуть как было», на экране «Изменения» — «↩️ Отменить все изменения»: изменённые и удалённые файлы возвращаются к последнему коммиту, новые удаляются. Действие необратимо, поэтому всегда с подтверждением; файлы с секретами не затрагиваются.
130
+ - **«🚀 Опубликовать проект».** Для папки, которая ещё не связана с сервером: пользователь выбирает сервис, место (личное пространство, группа GitLab с подгруппами или организация GitHub — с поиском), видимость (закрытый, внутренний, открытый) и название. Бот создаёт репозиторий, делает первый коммит без файлов с секретами и отправляет его.
131
+ - **«🔀 Запрос на слияние».** Из текущей ветки в основную ветку репозитория: бот спрашивает заголовок (или предлагает описание последнего коммита), создаёт запрос и даёт ссылку; если открытый запрос из этой ветки уже есть — показывает его.
132
+ - **Агент просит отправить.** У агента нет входа на сервер, поэтому «отправь на сервер» он выполняет так: коммитит и ставит в ответе метку `[[git:push]]` (или `[[git:pull]]`). Бот убирает метку и показывает под ответом кнопку; без нажатия пользователя ничего не уходит.
133
+ - **Напоминание о токене.** За неделю, за день и по истечении срока токена бот пишет владельцу аккаунта.
128
134
  - **Автор коммитов** — владелец аккаунта: его имя и почта передаются и боту, и агенту, так что коммиты агента подписаны пользователем.
129
135
  - **Секреты не уходят в репозиторий.** При «Сохранить и отправить» файлы с секретами (`.env`, ключи, учётные данные) из коммита исключаются и дописываются в `.gitignore`. Если такой файл закоммитил агент, перед отправкой бот предупреждает и отправляет только после «Отправить всё равно».
130
136
 
@@ -312,6 +318,7 @@ npm start # первый запуск без .env сам открое
312
318
  | `SANDBOX_RO_PATHS` | нет | дополнительные папки, которые песочница видит на чтение (через `:`), — например, место установки движка, если он не запускается в песочнице |
313
319
  | `BWRAP_COMMAND` | нет | путь к `bwrap`, если его нет в `PATH` |
314
320
  | `GITLAB_URL`, `GITHUB_URL` | нет | адрес своего GitLab и своего GitHub Enterprise (`https://git.example.com`): появляются в `/git` рядом с GitHub и GitLab.com. `GITLAB_NAME`, `GITHUB_NAME` — названия в кнопках (по умолчанию — имя сервера). Не обязательны: администратор добавляет свои серверы и в самом боте (`/git` → «Свои серверы») |
321
+ | `GITHUB_CLIENT_ID`, `GITLAB_CLIENT_ID` | нет | идентификаторы своих приложений для входа по ссылке и коду: GitHub — OAuth App с включённым Device Flow, GitLab.com — приложение с включённым Device authorization grant (не конфиденциальное); `0` — выключить такой вход для сервиса. По умолчанию — приложения AcpGram |
315
322
  | `GIT_AGENT_AUTH` | нет | `1` — вход в Git передаётся и агентам: они сами получают и отправляют изменения, но токены сотрудников им видны. По умолчанию токен только у бота |
316
323
  | `GIT_COMMAND` | нет | путь к `git`, если его нет в `PATH` |
317
324
  | `DEFAULT_ENGINE` | нет | движок по умолчанию: `gemini` (по умолчанию), `claude`, `agy`, `codex` или `opencode`. Если этот движок не установлен, бот не запускается |
@@ -425,7 +432,12 @@ src/
425
432
  gitAccess.mjs аккаунты Git пользователей; что из них получает агент (автор коммитов, вход при GIT_AGENT_AUTH)
426
433
  gitUi.mjs команда /git: аккаунты, свои серверы, клонирование, получить / отправить / сохранить
427
434
  gitInspect.mjs что изменилось и какие есть ветки: список файлов, изменения по файлу, коммиты, переключение ветки
428
- gitRepoUi.mjs экраны /git «Изменения» и «Ветки»
435
+ gitRepoUi.mjs экраны /git «Изменения» и «Ветки», отмена изменений
436
+ gitApi.mjs GitHub и GitLab: создание репозитория, места для публикации, запрос на слияние
437
+ gitPublishUi.mjs экраны /git «Опубликовать проект» и «Запрос на слияние»
438
+ gitMarks.mjs метки агента [[git:push]] / [[git:pull]]: отправка и получение по просьбе агента
439
+ gitDevice.mjs вход в GitHub.com и GitLab.com по ссылке и коду, без токена; продление входа
440
+ gitKeys.mjs ключи кнопок списков /git: старая кнопка не укажет на другой файл или ветку
429
441
  sessionsUi.mjs команда /sessions: возврат к прошлой сессии
430
442
  tools.mjs разбор событий вызовов инструментов агента
431
443
  asks.mjs кнопки быстрого ответа от агента: метка [[ask: …]], разметка кнопок, выбор по нажатию
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acpgram",
3
- "version": "1.28.0",
3
+ "version": "1.30.0",
4
4
  "type": "module",
5
5
  "description": "Telegram gateway to AI coding agents (Gemini CLI, Claude Code, Antigravity CLI, Codex, OpenCode) over the Agent Client Protocol",
6
6
  "license": "MIT",
package/src/bot.mjs CHANGED
@@ -8,12 +8,12 @@ import { choiceName, effectiveSelection, killProbes, refreshCatalogs } from './a
8
8
  import { handleModel, onModelCallback } from './modelUi.mjs';
9
9
  import { ADMIN_ID, IDLE_MINUTES, LEVEL_KEYS, MAX_AGENTS, botInfo, db, langOf, log, noteTgLang, say, setLang } from './ctx.mjs';
10
10
  import { adminCommand, handleUnknownUser, onAdminCallback, welcomeNote } from './admin.mjs';
11
- import { LANGS, LANG_CODES, LANG_PICK, errText, normLang, t } from './i18n.mjs';
11
+ import { LANGS, LANG_CODES, LANG_PICK, LOCALES, errText, normLang, t } from './i18n.mjs';
12
12
  import { HOME, ROOT, USER_WORKSPACES } from './projects.mjs';
13
13
  import { handleProject, onNavCallback, onProjectNameInput, onTopicListCallback } from './projectsUi.mjs';
14
14
  import { handleFiles, onFileInput, onFileUpload, onFilesCallback } from './filesUi.mjs';
15
15
  import { checkGit, gitCommand } from './git.mjs';
16
- import { GIT_AGENT_AUTH } from './gitAccess.mjs';
16
+ import { GIT_AGENT_AUTH, tokenReminders } from './gitAccess.mjs';
17
17
  import { handleGit, onGitCallback, onGitInput } from './gitUi.mjs';
18
18
  import { handleSessions, onSessionCallback } from './sessionsUi.mjs';
19
19
  import { dropPermissions, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
@@ -482,6 +482,23 @@ async function main() {
482
482
  };
483
483
  sweep();
484
484
  setInterval(sweep, 24 * 3600_000).unref();
485
+ // токены доступа к Git истекают: владельцу аккаунта — напоминание за неделю, за день и по истечении
486
+ const remind = () => {
487
+ try {
488
+ for (const r of tokenReminders()) {
489
+ const lang = langOf(r.userId);
490
+ const date = new Date(r.account.expires_at).toLocaleDateString(LOCALES[lang] ?? LOCALES.en, { day: '2-digit', month: '2-digit', year: 'numeric' });
491
+ log('git: напоминание о токене:', r.userId, r.host.id, r.stage);
492
+ say(r.userId, t(r.stage === 'expired' ? 'git.exp.expired' : 'git.exp.soon', lang, { host: r.host.label, login: r.account.login, date, days: r.days }), {
493
+ reply_markup: { inline_keyboard: [[{ text: t('start.btn.git', lang), callback_data: 'ui:git' }]] },
494
+ });
495
+ }
496
+ } catch (e) {
497
+ log('напоминания о токенах git:', e.message);
498
+ }
499
+ };
500
+ remind();
501
+ setInterval(remind, 12 * 3600_000).unref();
485
502
  const admin = getState(ADMIN_ID, ADMIN_ID);
486
503
  log(`бот @${botInfo.username} запущен | администратор ${ADMIN_ID} | проект админа: ${admin.project} | сотрудников: ${db.listUsers().filter((x) => x.status === 'active').length} | лимит агентов сотрудников: ${MAX_AGENTS} | простой: ${IDLE_MINUTES} мин | уровни: ${LEVEL_KEYS.join('/')}`);
487
504
 
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 = ?'),
@@ -245,11 +250,14 @@ export function openDb(path = 'data/bot.db') {
245
250
  deleteTopic: db.prepare('DELETE FROM topics WHERE user_id = ? AND thread_id = ?'),
246
251
  getGitAccount: db.prepare('SELECT * FROM git_accounts WHERE user_id = ? AND host = ?'),
247
252
  listGitAccounts: db.prepare('SELECT * FROM git_accounts WHERE user_id = ? ORDER BY added_at'),
253
+ allGitAccounts: db.prepare('SELECT * FROM git_accounts'),
248
254
  saveGitAccount: db.prepare(
249
- `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 (?,?,?,?,?,?,?,?,?,?)
250
256
  ON CONFLICT(user_id, host) DO UPDATE SET login = excluded.login, name = excluded.name, email = excluded.email,
251
- 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`,
252
259
  ),
260
+ setGitTokens: db.prepare('UPDATE git_accounts SET token = ?, refresh_token = ?, access_until = ? WHERE user_id = ? AND host = ?'),
253
261
  deleteGitAccount: db.prepare('DELETE FROM git_accounts WHERE user_id = ? AND host = ?'),
254
262
  deleteGitAccountsByHost: db.prepare('DELETE FROM git_accounts WHERE host = ?'),
255
263
  };
@@ -326,9 +334,16 @@ export function openDb(path = 'data/bot.db') {
326
334
  // --- аккаунты Git ---
327
335
  getGitAccount: safe((userId, host) => q.getGitAccount.get(userId, host) ?? null),
328
336
  listGitAccounts: (userId) => safe(() => q.listGitAccounts.all(userId))() ?? [],
329
- /** Сохраняет аккаунт сервиса: {host, login, name, email, token, expiresAt}. Возвращает true, если записано. */
337
+ /** Аккаунты всех пользователей (для напоминаний об истекающих токенах). */
338
+ allGitAccounts: () => safe(() => q.allGitAccounts.all())() ?? [],
339
+ /**
340
+ * Сохраняет аккаунт сервиса: {host, login, name, email, token, expiresAt, refreshToken, accessUntil}.
341
+ * refreshToken и accessUntil — только у входа по коду с обновляемым токеном. Возвращает true, если записано.
342
+ */
330
343
  saveGitAccount: (userId, a) =>
331
- 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)),
332
347
  deleteGitAccount: safe((userId, host) => q.deleteGitAccount.run(userId, host)),
333
348
  /** Удаляет аккаунты всех пользователей на сервисе (сервис убран администратором). Возвращает число удалённых. */
334
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,73 @@ 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
+
138
+ const DAY_MS = 24 * 3600_000;
139
+
140
+ /**
141
+ * Кому пора напомнить об истекающем токене: за 7 дней, за день и когда срок вышел. Каждое напоминание — один раз
142
+ * (отметка в настройках: срок токена и ступень); новый токен с другим сроком начинает отсчёт заново.
143
+ * @returns {{userId: number, host: object, account: object, stage: '7'|'1'|'expired', days: number}[]}
144
+ */
145
+ export function tokenReminders(now = Date.now()) {
146
+ const out = [];
147
+ for (const account of db.allGitAccounts()) {
148
+ const host = account.expires_at ? findHost(account.host) : null;
149
+ if (!host) continue;
150
+ const days = Math.ceil((Date.parse(account.expires_at) - now) / DAY_MS);
151
+ const stage = days <= 0 ? 'expired' : days <= 1 ? '1' : days <= 7 ? '7' : null;
152
+ if (!stage) continue;
153
+ const key = `gitexp:${account.user_id}:${account.host}`;
154
+ const mark = `${account.expires_at}|${stage}`;
155
+ if (db.getSetting(key) === mark) continue;
156
+ db.setSetting(key, mark);
157
+ out.push({ userId: account.user_id, host, account, stage, days });
158
+ }
159
+ return out;
160
+ }
161
+
94
162
  /**
95
163
  * Подсказка агенту о git (служебный текст — на английском). Без входа: не пытаться получать и отправлять, а направлять
96
164
  * пользователя в /git. Со входом (GIT_AGENT_AUTH): работать можно, показывать вход нельзя. Нет git на сервере — null.
@@ -107,6 +175,7 @@ export function gitNote(userId, { agentAuth = GIT_AGENT_AUTH } = {}) {
107
175
  return (
108
176
  '[AcpGram] Git: use git locally as usual (status, diff, add, commit, branches, merge). You have no credentials for the remote: ' +
109
177
  'do not try to fetch, pull, push or clone private repositories and do not ask the user for tokens or passwords. ' +
110
- 'When changes must be received or sent, tell the user to use the /git command of this bot (buttons to pull and push). Never commit files with secrets (.env, keys).'
178
+ 'When changes must be sent to or received from the server, put [[git:push]] or [[git:pull]] on its own line at the end of your reply: ' +
179
+ 'the bot then shows the user a button that does it (commit first — the button only pushes). The user can also open /git. Never commit files with secrets (.env, keys).'
111
180
  );
112
181
  }
package/src/gitApi.mjs ADDED
@@ -0,0 +1,79 @@
1
+ // GitHub и GitLab: создание репозитория (публикация проекта) и запрос на слияние — действия, которым нужен API
2
+ // сервиса, а не git. Запросы идут от имени владельца токена (gitHosts.api); у GitLab для них нужно право api.
3
+ import { api, showRemote } from './gitHosts.mjs';
4
+
5
+ /**
6
+ * Где пользователь может создать репозиторий: личное пространство и группы (GitLab, вместе с подгруппами) или
7
+ * организации (GitHub). search — часть названия группы.
8
+ * @returns {Promise<{id: string|number|null, path: string, kind: 'user'|'group'}[]>} id — для createRepo (у личного — null)
9
+ */
10
+ export async function listNamespaces(host, token, login, { search = '', ...opts } = {}) {
11
+ const q = search.trim().toLowerCase();
12
+ const own = { id: null, path: login, kind: 'user' };
13
+ if (host.kind === 'gitlab') {
14
+ // 30 — уровень Developer: с него группа может разрешать создание проектов
15
+ const { data } = await api(host, token, `/groups?min_access_level=30&order_by=path&per_page=50${q ? `&search=${encodeURIComponent(q)}` : ''}`, opts);
16
+ return [...(!q || login.toLowerCase().includes(q) ? [own] : []), ...data.map((g) => ({ id: g.id, path: g.full_path, kind: 'group' }))];
17
+ }
18
+ const { data } = await api(host, token, '/user/orgs?per_page=100', opts);
19
+ const orgs = data.map((o) => ({ id: o.login, path: o.login, kind: 'group' })).filter((o) => !q || o.path.toLowerCase().includes(q));
20
+ return [...(!q || login.toLowerCase().includes(q) ? [own] : []), ...orgs];
21
+ }
22
+
23
+ /** Видимость нового репозитория, которую умеет сервис: «внутренний» (виден всем пользователям сервера) — только GitLab. */
24
+ export const visibilities = (host) => (host.kind === 'gitlab' ? ['private', 'internal', 'public'] : ['private', 'public']);
25
+
26
+ /**
27
+ * Имя репозитория в адресе из названия папки: латиница, цифры, «.», «-», «_»; остальное — в «-». Не получилось
28
+ * (например, название целиком кириллицей) — null: имя нужно спросить у пользователя.
29
+ */
30
+ export function repoSlug(name) {
31
+ const slug = String(name ?? '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').replace(/\.git$/, '').slice(0, 100);
32
+ return slug && /[a-z0-9]/.test(slug) ? slug : null;
33
+ }
34
+
35
+ /**
36
+ * Создаёт пустой репозиторий. namespace — запись из listNamespaces; visibility — private | internal | public.
37
+ * @returns {Promise<{url: string, web: string, path: string}>} url — адрес для git (https), web — страница репозитория
38
+ */
39
+ export async function createRepo(host, token, { name, slug, namespace = null, visibility = 'private' }, opts = {}) {
40
+ if (host.kind === 'gitlab') {
41
+ const body = { name, path: slug, visibility, initialize_with_readme: false, ...(namespace?.id ? { namespace_id: namespace.id } : {}) };
42
+ const { data } = await api(host, token, '/projects', { ...opts, body });
43
+ return { url: data.http_url_to_repo, web: data.web_url, path: data.path_with_namespace };
44
+ }
45
+ const body = { name: slug, private: visibility !== 'public', auto_init: false };
46
+ const { data } = await api(host, token, namespace?.id ? `/orgs/${encodeURIComponent(namespace.id)}/repos` : '/user/repos', { ...opts, body });
47
+ return { url: data.clone_url, web: data.html_url, path: data.full_name };
48
+ }
49
+
50
+ /** Путь репозитория на сервисе по адресу origin: «group/sub/app» (у GitHub — «owner/repo»). */
51
+ export const repoPath = (host, remote) => showRemote(remote).slice(showRemote(host.web).length).replace(/^\/+|\/+$/g, '');
52
+
53
+ const projectRef = (host, remote) => (host.kind === 'gitlab' ? `/projects/${encodeURIComponent(repoPath(host, remote))}` : `/repos/${repoPath(host, remote).split('/').map(encodeURIComponent).join('/')}`);
54
+
55
+ /** Основная ветка репозитория на сервере и адрес его страницы. */
56
+ export async function repoInfo(host, token, remote, opts = {}) {
57
+ const { data } = await api(host, token, projectRef(host, remote), opts);
58
+ return { defaultBranch: data.default_branch ?? null, web: data.web_url ?? data.html_url ?? null };
59
+ }
60
+
61
+ /**
62
+ * Запрос на слияние ветки branch в ветку target (у GitHub — pull request). Если открытый запрос из этой ветки уже есть,
63
+ * возвращает его, а не создаёт второй.
64
+ * @returns {Promise<{url: string, number: number, existed: boolean}>}
65
+ */
66
+ export async function openMergeRequest(host, token, remote, { branch, target, title }, opts = {}) {
67
+ const ref = projectRef(host, remote);
68
+ if (host.kind === 'gitlab') {
69
+ const found = await api(host, token, `${ref}/merge_requests?state=opened&source_branch=${encodeURIComponent(branch)}&target_branch=${encodeURIComponent(target)}`, opts);
70
+ if (found.data[0]) return { url: found.data[0].web_url, number: found.data[0].iid, existed: true };
71
+ const { data } = await api(host, token, `${ref}/merge_requests`, { ...opts, body: { source_branch: branch, target_branch: target, title } });
72
+ return { url: data.web_url, number: data.iid, existed: false };
73
+ }
74
+ const owner = repoPath(host, remote).split('/')[0];
75
+ const found = await api(host, token, `${ref}/pulls?state=open&head=${encodeURIComponent(`${owner}:${branch}`)}&base=${encodeURIComponent(target)}`, opts);
76
+ if (found.data[0]) return { url: found.data[0].html_url, number: found.data[0].number, existed: true };
77
+ const { data } = await api(host, token, `${ref}/pulls`, { ...opts, body: { title, head: branch, base: target } });
78
+ return { url: data.html_url, number: data.number, existed: false };
79
+ }
@@ -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,8 +25,8 @@ 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' });
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: 'read_api, read_repository, write_repository' });
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
+ 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
  /**
32
32
  * Свой сервер: GitLab или GitHub Enterprise по адресу. name — название для кнопок (по умолчанию — имя сервера).
@@ -104,19 +104,38 @@ export class HostError extends Error {
104
104
  }
105
105
  }
106
106
 
107
- async function api(host, token, path, { fetchImpl = fetch } = {}) {
107
+ /** Что сервис написал в ответе с ошибкой: у GitLab — message (строка, список или {поле: [причины]}), у GitHub — message и errors. */
108
+ function errorDetail(data) {
109
+ const m = data?.message ?? data?.error_description ?? data?.error;
110
+ const flat = (v) => (v == null ? [] : typeof v === 'string' ? [v] : Array.isArray(v) ? v.flatMap(flat) : Object.entries(v).flatMap(([k, x]) => flat(x).map((s) => `${k} ${s}`)));
111
+ const extra = Array.isArray(data?.errors) ? data.errors.map((e) => (typeof e === 'string' ? e : e?.message || [e?.field, e?.code].filter(Boolean).join(' '))).filter(Boolean) : [];
112
+ return [...flat(m), ...extra].join('; ').slice(0, 300);
113
+ }
114
+
115
+ /**
116
+ * Запрос к API сервиса от имени владельца токена. body — объект: отправляется JSON методом POST (или method).
117
+ * Ошибки — HostError: 'auth' (401), 'forbidden' (403: токену не хватает прав), 'http' (с текстом сервиса), 'network'.
118
+ */
119
+ export async function api(host, token, path, { fetchImpl = fetch, method = null, body = null } = {}) {
108
120
  const headers = host.kind === 'github'
109
121
  ? { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'user-agent': 'acpgram' }
110
- : { 'private-token': token, accept: 'application/json', 'user-agent': 'acpgram' };
122
+ : { authorization: `Bearer ${token}`, accept: 'application/json', 'user-agent': 'acpgram' }; // так GitLab принимает и токен доступа, и токен входа по коду
123
+ const init = { headers, signal: AbortSignal.timeout(TIMEOUT_MS) };
124
+ if (body) Object.assign(init, { method: method ?? 'POST', body: JSON.stringify(body), headers: { ...headers, 'content-type': 'application/json' } });
125
+ else if (method) init.method = method;
111
126
  let res;
112
127
  try {
113
- res = await fetchImpl(`${host.api}${path}`, { headers, signal: AbortSignal.timeout(TIMEOUT_MS) });
128
+ res = await fetchImpl(`${host.api}${path}`, init);
114
129
  } catch (e) {
115
130
  throw new HostError('network', `${host.label}: ${e.message}`);
116
131
  }
117
- if (res.status === 401 || res.status === 403) throw new HostError('auth', `${host.label}: HTTP ${res.status}`, res.status);
118
- if (!res.ok) throw new HostError('http', `${host.label}: HTTP ${res.status}`, res.status);
119
- return { data: await res.json(), headers: res.headers };
132
+ if (res.status === 401) throw new HostError('auth', `${host.label}: HTTP 401`, 401);
133
+ if (!res.ok) {
134
+ const detail = errorDetail(await res.json().catch(() => null));
135
+ // 403 при чтении профиля — тоже «токен не подошёл»; при остальном — не хватает прав
136
+ throw new HostError(res.status === 403 ? 'forbidden' : 'http', `${host.label}: ${detail || `HTTP ${res.status}`}`, res.status);
137
+ }
138
+ return { data: res.status === 204 ? null : await res.json(), headers: res.headers };
120
139
  }
121
140
 
122
141
  const isoDate = (v) => {
@@ -158,8 +177,8 @@ export function missingScopes(host, scopes) {
158
177
  if (!Array.isArray(scopes)) return [];
159
178
  const has = (s) => scopes.includes(s);
160
179
  if (host.kind === 'github') return has('repo') || !scopes.length ? [] : ['repo']; // у fine-grained токенов список пуст
161
- if (has('api')) return [];
162
- return ['read_api', 'read_repository', 'write_repository'].filter((s) => !has(s));
180
+ // api — создание репозиториев и запросов на слияние; с ним работают и клонирование, и отправка
181
+ return has('api') ? [] : ['api'];
163
182
  }
164
183
 
165
184
  export const REPOS_PAGE = 10;