acpgram 1.26.0 → 1.28.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 +27 -1
- package/README.ru.md +31 -0
- package/package.json +1 -1
- package/src/bot.mjs +14 -0
- package/src/db.mjs +31 -0
- package/src/engines.mjs +3 -2
- package/src/git.mjs +235 -0
- package/src/gitAccess.mjs +112 -0
- package/src/gitHosts.mjs +195 -0
- package/src/gitInspect.mjs +163 -0
- package/src/gitRepoUi.mjs +189 -0
- package/src/gitUi.mjs +444 -0
- package/src/i18n.mjs +106 -0
- package/src/projectsUi.mjs +9 -2
- package/src/state.mjs +2 -0
- package/src/turn.mjs +2 -1
- package/src/ui.mjs +2 -1
package/README.md
CHANGED
|
@@ -51,6 +51,7 @@ Check it yourself after installing: `npm audit signatures` verifies the registry
|
|
|
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
52
|
- **Projects** — `/project` picks the working folder by buttons, by name search or by path (`/project ~/projects/web`), with one-tap recent projects.
|
|
53
53
|
- **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
|
+
- **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.
|
|
54
55
|
- **Personal workspaces** — with `USER_WORKSPACES=1` each teammate gets their own folder inside the projects root and chooses projects only there; a new project is created with the "➕ New project" button.
|
|
55
56
|
- **Sessions** — `/sessions` resumes a previous conversation (in the engine it was created in), even after a restart; `/new` starts fresh; `/close` unloads the agent process.
|
|
56
57
|
- **Team access** — invite links and access requests; per-user access levels, engines and model restrictions; `/active` shows who is working and lets the admin end any session.
|
|
@@ -186,6 +187,7 @@ In the container the agent sees only the mounted projects folder (`PROJECTS_DIR`
|
|
|
186
187
|
| `/model [name]` | everyone | choose the model and reasoning level; with a name — search for a model (`/model sonnet`) |
|
|
187
188
|
| `/new` | everyone | new session |
|
|
188
189
|
| `/files` | everyone | project files: list, create, upload and delete — bypassing the agent |
|
|
190
|
+
| `/git` | everyone | Git: GitHub / GitLab accounts, clone, pull and push |
|
|
189
191
|
| `/sessions` | everyone | resume a previous session in this project |
|
|
190
192
|
| `/stop` | everyone | stop the running request |
|
|
191
193
|
| `/close`, `/exit` | everyone | close the session and unload the agent process |
|
|
@@ -222,6 +224,26 @@ Everything a user types to the bot or sends as a file goes to the agent, and the
|
|
|
222
224
|
|
|
223
225
|
What this gives and what it does not. The secret does not get into a model request *from the user*. The file itself stays available to the agent — otherwise the applications it writes and runs could not use it. So that the agent does not read the values into the conversation by itself, the bot regularly reminds it: do not open or print files with secrets, refer to settings by name, and send the user to `/files` for a missing value. This is an instruction, not a ban: for especially sensitive data use a model from a provider that does not train on requests.
|
|
224
226
|
|
|
227
|
+
### Git: GitHub and GitLab
|
|
228
|
+
|
|
229
|
+
The `/git` command connects projects to GitHub, GitLab.com and your own servers — GitLab and GitHub Enterprise. It needs `git` installed: a system program, not a dependency of the bot; without it the section says it is unavailable.
|
|
230
|
+
|
|
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
|
+
|
|
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.
|
|
234
|
+
- **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
|
+
- **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
|
+
- **"📋 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
|
+
- **"🌿 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.
|
|
238
|
+
- **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
|
+
- **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
|
+
|
|
241
|
+
**Where the token lives.** By default only in the bot's database: the bot clones, pulls and pushes, while the agent works with the repository locally (status, diff, commits, branches, merges) and sends the user to `/git` when changes must be pushed. In the sandbox the token is not reachable by the agent at all. The administrator can choose another mode, `GIT_AGENT_AUTH=1`: the sign-in is also given to the agent process, which then pulls and pushes by itself. That is more convenient, but the token becomes visible to the agent and may end up in a model request; turn it on only if you trust the models your teammates use.
|
|
242
|
+
|
|
243
|
+
**How the bot runs git.** The repository lives where the agent writes, and repository settings and hooks can run programs. So the bot runs git with hooks and credential helpers turned off, without the global and system config (on Linux and macOS), and, when the sandbox is on, inside the same teammate's sandbox. The sign-in is passed to the git process through its environment and only for the addresses of its own service; it is never written to the repository settings or the URL. Residual risk: the repository's own settings (filters) run during operations, and a deliberately malicious agent could capture the token while an operation runs.
|
|
244
|
+
|
|
245
|
+
Only HTTPS repositories from the listed services can be connected; a repository with an SSH address or from another server is shown, but the bot cannot pull from or push to it.
|
|
246
|
+
|
|
225
247
|
### Personal workspaces
|
|
226
248
|
|
|
227
249
|
By default all teammates browse the same projects root. `USER_WORKSPACES=1` (together with `PROJECTS_ROOT`) gives each teammate a folder of their own: `<root>/<Telegram ID>`. The folder is created when the teammate first talks to the bot.
|
|
@@ -271,6 +293,9 @@ What the sandbox does not do:
|
|
|
271
293
|
| `AGENT_SANDBOX` | no | `bwrap` — agent sandbox (Linux only, needs the `bubblewrap` package): a teammate's agent sees only their projects folder, their files and their own home folder. See "Agent sandbox" |
|
|
272
294
|
| `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 |
|
|
273
295
|
| `BWRAP_COMMAND` | no | path to `bwrap` if it is not in `PATH` |
|
|
296
|
+
| `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") |
|
|
297
|
+
| `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
|
+
| `GIT_COMMAND` | no | path to `git` if it is not in `PATH` |
|
|
274
299
|
| `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 |
|
|
275
300
|
| `DEFAULT_ENGINE` | no | `gemini` (default), `claude`, `agy`, `codex` or `opencode`; the bot does not start if this engine is not installed |
|
|
276
301
|
| `DEFAULT_LANG` | no | bot language when the user's Telegram language is not `ru`, `uk` or `en`: `en` (default), `ru` or `uk`. Each user can change it with `/language` |
|
|
@@ -317,7 +342,8 @@ src/
|
|
|
317
342
|
state.mjs per-user state: agent process, engine, project, limits, idle reaper
|
|
318
343
|
admin.mjs invites, access requests, /users, /active
|
|
319
344
|
projects.mjs project paths (inside the root or anywhere), recent projects, search
|
|
320
|
-
*Ui.mjs /project, /files, /sessions, /engine, /model screens
|
|
345
|
+
*Ui.mjs /project, /files, /git, /sessions, /engine, /model screens
|
|
346
|
+
git*.mjs git commands run by the bot, GitHub / GitLab clients, accounts and what the agent gets from them
|
|
321
347
|
projectFiles.mjs project files bypassing the agent: safe writes and deletes inside the project, no links
|
|
322
348
|
ui.mjs rendering: drafts, steps, final message, screens
|
|
323
349
|
telegram.mjs Bot API calls, rich messages, long text splitting, file download and upload
|
package/README.ru.md
CHANGED
|
@@ -54,6 +54,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
54
54
|
- с `PROJECTS_ROOT` и `USER_WORKSPACES=1` (личные пространства) — у каждого сотрудника своя папка в корне, чужие папки он не видит и выбрать не может; новый проект создаётся кнопкой «➕ Новый проект» (см. «Личные пространства»);
|
|
55
55
|
- без `PROJECTS_ROOT` (личная установка) — любая существующая папка, по умолчанию домашняя.
|
|
56
56
|
- **Файлы проекта в обход агента** (`/files`): список файлов проекта по папкам, создание файла из сообщения, загрузка файла с устройства и удаление. Содержимое таких файлов не попадает в запрос к модели — так в проект кладут секреты (`.env`, ключи), которые нельзя показывать бесплатным моделям. См. «Файлы проекта и секреты».
|
|
57
|
+
- **Git: GitHub и GitLab** (`/git`): подключение аккаунта по токену доступа, клонирование репозитория кнопкой из списка, «Получить», «Отправить» и «Сохранить и отправить». Токен хранится у бота и агенту не передаётся; файлы с секретами в коммиты не попадают. См. «Git: GitHub и GitLab».
|
|
57
58
|
- **Возврат к прошлой сессии** (`/sessions`): агент помнит весь диалог, сессию можно возобновить даже после перезапуска бота. У каждой сессии метка движка; сессия возобновляется в том движке, где была создана.
|
|
58
59
|
- **Доступ для сотрудников**: администратор выдаёт и забирает доступ, выбирая уровень, движки и модели.
|
|
59
60
|
- **База работы бота** (SQLite): сессии, запросы пользователей с моделью, токенами и стоимостью, вызовы инструментов, разрешения, ответы модели.
|
|
@@ -68,6 +69,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
68
69
|
| `/model [название]` | все | выбор модели и уровня рассуждений текущего движка; с названием — поиск модели (`/model sonnet`) |
|
|
69
70
|
| `/new` | все | новая сессия агента |
|
|
70
71
|
| `/files` | все | файлы проекта: список, создание, загрузка и удаление — в обход агента |
|
|
72
|
+
| `/git` | все | Git: аккаунты GitHub / GitLab, клонирование, получение и отправка изменений |
|
|
71
73
|
| `/sessions` | все | список прошлых сессий в текущем проекте и возврат в выбранную |
|
|
72
74
|
| `/stop` | все | остановить выполняющийся запрос |
|
|
73
75
|
| `/close`, `/exit` | все | закрыть сессию, выгрузить процесс агента и освободить слот |
|
|
@@ -112,6 +114,26 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
112
114
|
|
|
113
115
|
Что это даёт и чего не даёт. Секрет не попадает в запрос к модели *от пользователя*. Сам файл агенту доступен — иначе приложения, которые он пишет и запускает, не смогли бы им пользоваться. Чтобы агент не прочитал значения в диалог сам, бот регулярно напоминает ему: файлы с секретами не открывать и не выводить, ссылаться на настройки по именам, а за недостающим значением отправлять пользователя в `/files`. Это указание, а не запрет: для особо чувствительных данных используйте модель провайдера, который не обучается на запросах.
|
|
114
116
|
|
|
117
|
+
### Git: GitHub и GitLab
|
|
118
|
+
|
|
119
|
+
Команда `/git` связывает проекты с GitHub, GitLab.com и своими серверами — GitLab и GitHub Enterprise. Нужен установленный `git`: это системная программа, а не зависимость бота; без неё раздел отвечает, что недоступен.
|
|
120
|
+
|
|
121
|
+
- **Свои серверы** добавляет администратор прямо в `/git`: «⚙️ Свои серверы» → «➕ GitLab» или «➕ GitHub Enterprise» → адрес сервера (`https://git.example.com`). Бот проверяет, что по адресу отвечает сервер нужного вида, и после этого каждый пользователь может подключить на нём аккаунт. Там же сервер переименовывается и убирается — вместе с подключёнными к нему аккаунтами. Без этого в меню только GitHub и GitLab.com. Там, где настройки задаются файлом, сервер можно указать и в `.env` (`GITLAB_URL`, `GITHUB_URL`).
|
|
122
|
+
|
|
123
|
+
- **Подключение аккаунта.** «➕ Подключить …» → бот даёт ссылку на страницу токенов и список нужных прав, пользователь присылает токен доступа одним сообщением. Сообщение сразу удаляется из чата и агенту не передаётся. Бот проверяет токен в сервисе, показывает, кто подключён и до какого числа токен действует, и предупреждает, если прав не хватает. Отключение удаляет токен из бота.
|
|
124
|
+
- **Клонирование.** «⬇️ Клонировать репозиторий» (или «⬇️ Из Git» в `/project`) показывает репозитории пользователя кнопками, недавно менявшиеся первыми, с поиском по названию. Выбранный клонируется в личное пространство (без него — рядом с текущим проектом) и становится проектом.
|
|
125
|
+
- **Репозиторий проекта.** Экран показывает ветку, число изменённых файлов, неотправленных коммитов и новых коммитов на сервере; при открытии и по кнопке «Обновить» он сверяется с сервером. «⬇️ Получить» забирает изменения, если это возможно без слияния; если истории разошлись, слияние делает агент. «⬆️ Отправить» отправляет коммиты. «💾 Сохранить и отправить» спрашивает описание, коммитит все изменения и отправляет.
|
|
126
|
+
- **«📋 Изменения».** Список изменённых файлов с пометками (новый, изменён, удалён, переименован) и числом добавленных и убранных строк. Нажатие на файл показывает, что в нём изменилось: короткие изменения — в сообщении, длинные — файлом. Содержимое файлов с секретами не показывается. Там же — коммиты, которые ещё не отправлены, и те, что ждут на сервере. Всё это видно без агента и без запросов к модели.
|
|
127
|
+
- **«🌿 Ветки».** Локальные ветки и ветки сервера одним списком; нажатие переключает на ветку, «➕ Новая ветка» создаёт её от текущей. При несохранённых изменениях бот не переключает, а предлагает сначала сохранить их; пока агент выполняет запрос — тоже. После переключения следующий запрос начинает новую сессию агента: файлы проекта сменились. «Отправить» создаёт новую ветку и на сервере.
|
|
128
|
+
- **Автор коммитов** — владелец аккаунта: его имя и почта передаются и боту, и агенту, так что коммиты агента подписаны пользователем.
|
|
129
|
+
- **Секреты не уходят в репозиторий.** При «Сохранить и отправить» файлы с секретами (`.env`, ключи, учётные данные) из коммита исключаются и дописываются в `.gitignore`. Если такой файл закоммитил агент, перед отправкой бот предупреждает и отправляет только после «Отправить всё равно».
|
|
130
|
+
|
|
131
|
+
**Где лежит токен.** По умолчанию — только в базе бота: клонирование, получение и отправку делает бот, а агент работает с репозиторием локально (состояние, сравнение, коммиты, ветки, слияние) и на просьбу отправить изменения направляет пользователя в `/git`. В песочнице токен агенту недоступен совсем. Администратор может выбрать другой режим — `GIT_AGENT_AUTH=1`: вход передаётся и процессу агента, он сам получает и отправляет изменения. Это удобнее, но токен становится виден агенту и может попасть в запрос к модели; включайте его, только если доверяете моделям, с которыми работают сотрудники.
|
|
132
|
+
|
|
133
|
+
**Как бот запускает git.** Репозиторий лежит там, куда пишет агент, а настройки и хуки репозитория умеют запускать программы. Поэтому бот запускает git с отключёнными хуками и помощниками входа, без общего и системного конфига (на Linux и macOS), а при включённой песочнице — внутри песочницы того же сотрудника. Вход передаётся процессу git через окружение и только для адресов своего сервиса; в настройки репозитория и в адрес он не пишется. Остаточный риск: настройки самого репозитория (фильтры) выполняются при операциях, и намеренно вредоносный агент мог бы перехватить токен во время операции.
|
|
134
|
+
|
|
135
|
+
Подключаются только репозитории по HTTPS с перечисленных сервисов; репозиторий с адресом SSH или с другого сервера бот показывает, но получать и отправлять в него не может.
|
|
136
|
+
|
|
115
137
|
### Личные пространства
|
|
116
138
|
|
|
117
139
|
По умолчанию все сотрудники ходят по одному корню проектов. `USER_WORKSPACES=1` (вместе с `PROJECTS_ROOT`) даёт каждому сотруднику свою папку: `<корень>/<Telegram ID>`. Папка создаётся сама при первом обращении сотрудника к боту.
|
|
@@ -289,6 +311,9 @@ npm start # первый запуск без .env сам открое
|
|
|
289
311
|
| `AGENT_SANDBOX` | нет | `bwrap` — песочница агента (только Linux, нужен пакет `bubblewrap`): агент сотрудника видит только его папку проектов, его файлы и его домашнюю папку. См. «Песочница агента» |
|
|
290
312
|
| `SANDBOX_RO_PATHS` | нет | дополнительные папки, которые песочница видит на чтение (через `:`), — например, место установки движка, если он не запускается в песочнице |
|
|
291
313
|
| `BWRAP_COMMAND` | нет | путь к `bwrap`, если его нет в `PATH` |
|
|
314
|
+
| `GITLAB_URL`, `GITHUB_URL` | нет | адрес своего GitLab и своего GitHub Enterprise (`https://git.example.com`): появляются в `/git` рядом с GitHub и GitLab.com. `GITLAB_NAME`, `GITHUB_NAME` — названия в кнопках (по умолчанию — имя сервера). Не обязательны: администратор добавляет свои серверы и в самом боте (`/git` → «Свои серверы») |
|
|
315
|
+
| `GIT_AGENT_AUTH` | нет | `1` — вход в Git передаётся и агентам: они сами получают и отправляют изменения, но токены сотрудников им видны. По умолчанию токен только у бота |
|
|
316
|
+
| `GIT_COMMAND` | нет | путь к `git`, если его нет в `PATH` |
|
|
292
317
|
| `DEFAULT_ENGINE` | нет | движок по умолчанию: `gemini` (по умолчанию), `claude`, `agy`, `codex` или `opencode`. Если этот движок не установлен, бот не запускается |
|
|
293
318
|
| `DEFAULT_LANG` | нет | язык бота, если язык Telegram пользователя не `ru`, `uk` или `en`: `en` (по умолчанию), `ru` или `uk`. Пользователь может сменить язык командой `/language` |
|
|
294
319
|
| `ACPGRAM_LANG` | нет | язык команд `acpgram` в терминале: `ru`, `uk` или `en`. Обычно не нужен: язык берётся из системы (для Docker и CI, где у системы нет языка) |
|
|
@@ -395,6 +420,12 @@ src/
|
|
|
395
420
|
projectsUi.mjs команда /project и навигация кнопками
|
|
396
421
|
projectFiles.mjs файлы проекта в обход агента: безопасная запись и удаление внутри проекта, без ссылок
|
|
397
422
|
filesUi.mjs команда /files: список, создание, загрузка и удаление файлов проекта
|
|
423
|
+
git.mjs команды git бота: клонирование, состояние, получение, отправка, коммит без секретов; безопасный запуск
|
|
424
|
+
gitHosts.mjs GitHub и GitLab: профиль и репозитории по токену, вход для git
|
|
425
|
+
gitAccess.mjs аккаунты Git пользователей; что из них получает агент (автор коммитов, вход при GIT_AGENT_AUTH)
|
|
426
|
+
gitUi.mjs команда /git: аккаунты, свои серверы, клонирование, получить / отправить / сохранить
|
|
427
|
+
gitInspect.mjs что изменилось и какие есть ветки: список файлов, изменения по файлу, коммиты, переключение ветки
|
|
428
|
+
gitRepoUi.mjs экраны /git «Изменения» и «Ветки»
|
|
398
429
|
sessionsUi.mjs команда /sessions: возврат к прошлой сессии
|
|
399
430
|
tools.mjs разбор событий вызовов инструментов агента
|
|
400
431
|
asks.mjs кнопки быстрого ответа от агента: метка [[ask: …]], разметка кнопок, выбор по нажатию
|
package/package.json
CHANGED
package/src/bot.mjs
CHANGED
|
@@ -12,6 +12,9 @@ import { LANGS, LANG_CODES, LANG_PICK, 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
|
+
import { checkGit, gitCommand } from './git.mjs';
|
|
16
|
+
import { GIT_AGENT_AUTH } from './gitAccess.mjs';
|
|
17
|
+
import { handleGit, onGitCallback, onGitInput } from './gitUi.mjs';
|
|
15
18
|
import { handleSessions, onSessionCallback } from './sessionsUi.mjs';
|
|
16
19
|
import { dropPermissions, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
|
|
17
20
|
import { handleTopics, newTopic, onTopicsCallback } from './topicsUi.mjs';
|
|
@@ -120,6 +123,7 @@ const COMMANDS = [
|
|
|
120
123
|
{ name: 'usage', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/usage') },
|
|
121
124
|
{ name: 'project', menu: true, button: true, run: (st, arg) => handleProject(st, arg) },
|
|
122
125
|
{ name: 'files', menu: true, button: true, run: (st) => handleFiles(st) },
|
|
126
|
+
{ name: 'git', menu: true, button: true, run: (st) => handleGit(st) },
|
|
123
127
|
{ name: 'engine', menu: true, button: true, run: (st, arg) => handleEngine(st, arg) },
|
|
124
128
|
{ name: 'model', menu: true, button: true, run: (st, arg) => handleModel(st, arg) },
|
|
125
129
|
{ name: 'new', menu: true, button: true, run: newCommand },
|
|
@@ -157,6 +161,8 @@ async function handleText(st, text, { quote = null, messageId = null } = {}) {
|
|
|
157
161
|
if (await onProjectNameInput(st, text)) return;
|
|
158
162
|
// бот ждёт имя или содержимое файла проекта (/files): содержимое агенту не передаётся и удаляется из чата
|
|
159
163
|
if (await onFileInput(st, text, { messageId })) return;
|
|
164
|
+
// бот ждёт токен доступа к GitHub / GitLab, строку поиска репозитория или описание изменений (/git)
|
|
165
|
+
if (await onGitInput(st, text, { messageId })) return;
|
|
160
166
|
if (name && !st.agent?.commands?.has(name)) {
|
|
161
167
|
const guess = nearCommand(name, COMMANDS.filter((c) => !c.admin || isAdmin(st.userId)).map((c) => c.name));
|
|
162
168
|
if (guess) {
|
|
@@ -320,6 +326,7 @@ async function handleUpdate(u) {
|
|
|
320
326
|
if (data.startsWith('tpl:')) return onTopicListCallback(st, cb);
|
|
321
327
|
if (data.startsWith('nav:')) return onNavCallback(st, cb);
|
|
322
328
|
if (data.startsWith('fl:')) return onFilesCallback(st, cb);
|
|
329
|
+
if (data.startsWith('gt:')) return onGitCallback(st, cb);
|
|
323
330
|
if (data.startsWith('perm:')) return onPermissionCallback(st, cb);
|
|
324
331
|
if (data.startsWith('ask:')) return onAskCallback(st, cb);
|
|
325
332
|
if (data.startsWith('q:')) return onQueueCallback(st, cb);
|
|
@@ -431,6 +438,13 @@ async function main() {
|
|
|
431
438
|
}
|
|
432
439
|
log(`движок по умолчанию: ${DEFAULT_ENGINE}`);
|
|
433
440
|
if (SANDBOX) await setupSandbox(checks);
|
|
441
|
+
// git — необязательная системная программа: без неё раздел /git отвечает, что недоступен
|
|
442
|
+
const git = await checkGit();
|
|
443
|
+
log(
|
|
444
|
+
git.ok
|
|
445
|
+
? `${git.version} | ${gitCommand()} — /git доступен${GIT_AGENT_AUTH ? '; ⚠️ GIT_AGENT_AUTH=1: вход в Git передаётся агентам, токены сотрудников им видны' : '; вход в Git агентам не передаётся'}`
|
|
446
|
+
: `ℹ️ git не найден (${gitCommand()}): /git недоступен. Установите git или укажите путь в GIT_COMMAND`,
|
|
447
|
+
);
|
|
434
448
|
log(
|
|
435
449
|
ROOT
|
|
436
450
|
? `корень проектов: ${ROOT} (проект — только папка внутри корня)`
|
package/src/db.mjs
CHANGED
|
@@ -121,6 +121,19 @@ export function openDb(path = 'data/bot.db') {
|
|
|
121
121
|
PRIMARY KEY (user_id, thread_id)
|
|
122
122
|
);
|
|
123
123
|
|
|
124
|
+
-- аккаунты Git пользователей (GitHub, GitLab): токен доступа и профиль; токен хранится только здесь
|
|
125
|
+
CREATE TABLE IF NOT EXISTS git_accounts (
|
|
126
|
+
user_id INTEGER NOT NULL,
|
|
127
|
+
host TEXT NOT NULL, -- id сервиса (gitHosts.mjs): github, gitlab, corp
|
|
128
|
+
login TEXT,
|
|
129
|
+
name TEXT,
|
|
130
|
+
email TEXT,
|
|
131
|
+
token TEXT NOT NULL,
|
|
132
|
+
expires_at TEXT, -- когда истекает токен (если сервис сообщил)
|
|
133
|
+
added_at TEXT NOT NULL,
|
|
134
|
+
PRIMARY KEY (user_id, host)
|
|
135
|
+
);
|
|
136
|
+
|
|
124
137
|
CREATE INDEX IF NOT EXISTS idx_requests_session ON requests(session_id);
|
|
125
138
|
CREATE INDEX IF NOT EXISTS idx_tool_calls_request ON tool_calls(request_id);
|
|
126
139
|
-- /sessions: сессии пользователя и поиск всех запусков одной ACP-сессии
|
|
@@ -230,6 +243,15 @@ export function openDb(path = 'data/bot.db') {
|
|
|
230
243
|
),
|
|
231
244
|
countTopics: db.prepare('SELECT COUNT(*) AS n FROM topics WHERE user_id = ? AND lower(project) = lower(?) AND hidden = 0'),
|
|
232
245
|
deleteTopic: db.prepare('DELETE FROM topics WHERE user_id = ? AND thread_id = ?'),
|
|
246
|
+
getGitAccount: db.prepare('SELECT * FROM git_accounts WHERE user_id = ? AND host = ?'),
|
|
247
|
+
listGitAccounts: db.prepare('SELECT * FROM git_accounts WHERE user_id = ? ORDER BY added_at'),
|
|
248
|
+
saveGitAccount: db.prepare(
|
|
249
|
+
`INSERT INTO git_accounts (user_id, host, login, name, email, token, expires_at, added_at) VALUES (?,?,?,?,?,?,?,?)
|
|
250
|
+
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`,
|
|
252
|
+
),
|
|
253
|
+
deleteGitAccount: db.prepare('DELETE FROM git_accounts WHERE user_id = ? AND host = ?'),
|
|
254
|
+
deleteGitAccountsByHost: db.prepare('DELETE FROM git_accounts WHERE host = ?'),
|
|
233
255
|
};
|
|
234
256
|
|
|
235
257
|
// Любая ошибка БД не должна ронять бота — журнал вторичен по отношению к работе.
|
|
@@ -301,6 +323,15 @@ export function openDb(path = 'data/bot.db') {
|
|
|
301
323
|
safe(() => ({ items: q.listTopics.all(userId, project, limit, offset), total: q.countTopics.get(userId, project).n }))() ?? { items: [], total: 0 },
|
|
302
324
|
/** Забывает тему (удалённую в Telegram). */
|
|
303
325
|
deleteTopic: safe((userId, threadId) => q.deleteTopic.run(userId, threadId)),
|
|
326
|
+
// --- аккаунты Git ---
|
|
327
|
+
getGitAccount: safe((userId, host) => q.getGitAccount.get(userId, host) ?? null),
|
|
328
|
+
listGitAccounts: (userId) => safe(() => q.listGitAccounts.all(userId))() ?? [],
|
|
329
|
+
/** Сохраняет аккаунт сервиса: {host, login, name, email, token, expiresAt}. Возвращает true, если записано. */
|
|
330
|
+
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,
|
|
332
|
+
deleteGitAccount: safe((userId, host) => q.deleteGitAccount.run(userId, host)),
|
|
333
|
+
/** Удаляет аккаунты всех пользователей на сервисе (сервис убран администратором). Возвращает число удалённых. */
|
|
334
|
+
deleteGitAccountsByHost: (host) => safe(() => Number(q.deleteGitAccountsByHost.run(host).changes))() ?? 0,
|
|
304
335
|
close: () => db.close(),
|
|
305
336
|
};
|
|
306
337
|
}
|
package/src/engines.mjs
CHANGED
|
@@ -502,8 +502,9 @@ export function parseUsage(res, usageUpdate) {
|
|
|
502
502
|
* wrap — запуск через программу-обёртку (песочница, sandbox.agentSandbox): {command, args, env}; её аргументы уже
|
|
503
503
|
* заканчиваются командой движка, аргументы движка добавляются следом, а окружение проходит через wrap.env.
|
|
504
504
|
*/
|
|
505
|
-
export function createAgent(engine, { who, wrap = null, ...opts }) {
|
|
506
|
-
|
|
505
|
+
export function createAgent(engine, { who, wrap = null, extraEnv = null, ...opts }) {
|
|
506
|
+
// extraEnv — переменные пользователя сверх общих (автор коммитов и вход git, gitAccess.agentGitEnv)
|
|
507
|
+
const base = { ...agentEnv(engine), ...(who && engine.processEnv ? engine.processEnv(who) : {}), ...(extraEnv ?? {}) };
|
|
507
508
|
const env = wrap ? wrap.env(base) : base;
|
|
508
509
|
const command = wrap ? wrap.command : engineCommand(engine);
|
|
509
510
|
const args = wrap ? [...wrap.args, ...engine.args] : engine.args;
|
package/src/git.mjs
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// Команды git, которые бот выполняет сам (/git): клонирование, состояние, получение и отправка изменений, коммит.
|
|
2
|
+
// Git — системная программа, не зависимость бота: нет её на сервере — раздел /git не показывается.
|
|
3
|
+
//
|
|
4
|
+
// Безопасность. Репозиторий лежит в папке, куда пишет агент, а настройки и хуки репозитория умеют запускать программы.
|
|
5
|
+
// Поэтому: хуки отключены, общий и системный конфиги не читаются (где это возможно), вход передаётся только через
|
|
6
|
+
// окружение процесса, а при включённой песочнице (AGENT_SANDBOX) git запускается в песочнице того же сотрудника.
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import { appendFileSync, existsSync, readFileSync } from 'node:fs';
|
|
9
|
+
import { devNull } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { checkCommand, killTree } from './acp.mjs';
|
|
12
|
+
import { agentEnv } from './engines.mjs';
|
|
13
|
+
import { isSecretName } from './files.mjs';
|
|
14
|
+
|
|
15
|
+
const IS_WIN = process.platform === 'win32';
|
|
16
|
+
|
|
17
|
+
/** Команда git: из GIT_COMMAND или из PATH. */
|
|
18
|
+
export const gitCommand = (env = process.env) => env.GIT_COMMAND?.trim() || 'git';
|
|
19
|
+
|
|
20
|
+
let available = false;
|
|
21
|
+
/** Проверка при старте: есть ли git на сервере. */
|
|
22
|
+
export async function checkGit() {
|
|
23
|
+
const r = await checkCommand(gitCommand(), ['--version'], 20_000);
|
|
24
|
+
available = r.ok;
|
|
25
|
+
return r;
|
|
26
|
+
}
|
|
27
|
+
/** Доступен ли git (по проверке при старте). */
|
|
28
|
+
export const gitAvailable = () => available;
|
|
29
|
+
/** Для тестов и повторной проверки. */
|
|
30
|
+
export const setGitAvailable = (on) => {
|
|
31
|
+
available = Boolean(on);
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Настройки git через окружение (GIT_CONFIG_COUNT / KEY_n / VALUE_n): действуют как «-c ключ=значение», но не видны
|
|
36
|
+
* в списке процессов. Добавляются к уже заданным в env.
|
|
37
|
+
* @param {[string, string][]} entries
|
|
38
|
+
*/
|
|
39
|
+
export function configEnv(entries, env = {}) {
|
|
40
|
+
const out = { ...env };
|
|
41
|
+
let n = Number(out.GIT_CONFIG_COUNT) || 0;
|
|
42
|
+
for (const [key, value] of entries) {
|
|
43
|
+
out[`GIT_CONFIG_KEY_${n}`] = key;
|
|
44
|
+
out[`GIT_CONFIG_VALUE_${n}`] = value;
|
|
45
|
+
n++;
|
|
46
|
+
}
|
|
47
|
+
out.GIT_CONFIG_COUNT = String(n);
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Настройки безопасного запуска: без хуков, без наблюдателя файлов, без помощников входа и внешних транспортов. */
|
|
52
|
+
export const SAFE_CONFIG = [
|
|
53
|
+
['core.hooksPath', devNull],
|
|
54
|
+
['core.fsmonitor', 'false'],
|
|
55
|
+
['credential.helper', ''],
|
|
56
|
+
['protocol.ext.allow', 'never'],
|
|
57
|
+
['advice.detachedHead', 'false'],
|
|
58
|
+
['core.quotePath', 'false'], // имена файлов не латиницей — как есть, а не восьмеричными кодами
|
|
59
|
+
];
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Окружение процесса git, который запускает бот: без токена бота и ключей API, без вопросов в терминале, с безопасными
|
|
63
|
+
* настройками; identity — автор коммитов {name, email}; auth — настройки входа (gitHosts.authConfig).
|
|
64
|
+
* На Linux и macOS общий и системный конфиги не читаются: в песочнице общий конфиг лежит в папке, куда пишет агент.
|
|
65
|
+
*/
|
|
66
|
+
export function gitEnv({ identity = null, auth = [], base = process.env } = {}) {
|
|
67
|
+
const env = { ...agentEnv({ apiKeys: [] }, base), GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_EDITOR: 'true', GIT_PAGER: 'cat', LC_ALL: 'C' };
|
|
68
|
+
if (!IS_WIN) Object.assign(env, { GIT_CONFIG_GLOBAL: devNull, GIT_CONFIG_NOSYSTEM: '1' });
|
|
69
|
+
if (identity?.name && identity?.email) {
|
|
70
|
+
Object.assign(env, { GIT_AUTHOR_NAME: identity.name, GIT_AUTHOR_EMAIL: identity.email, GIT_COMMITTER_NAME: identity.name, GIT_COMMITTER_EMAIL: identity.email });
|
|
71
|
+
}
|
|
72
|
+
return configEnv([...SAFE_CONFIG, ...auth], env);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Команда git завершилась с ошибкой: code — код выхода, stderr — её вывод (без секретов). */
|
|
76
|
+
export class GitError extends Error {
|
|
77
|
+
constructor(message, { code = null, stderr = '', timeout = false } = {}) {
|
|
78
|
+
super(message);
|
|
79
|
+
this.code = code;
|
|
80
|
+
this.stderr = stderr;
|
|
81
|
+
this.timeout = timeout;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Запускает git. Без оболочки: аргументы (описание коммита, имена файлов) передаются как есть.
|
|
87
|
+
* @param {string[]} args
|
|
88
|
+
* @param {{cwd: string, env?: object, wrap?: {command: string, args: string[], env: Function}|null, timeoutMs?: number, hide?: string[]}} o
|
|
89
|
+
* wrap — песочница (sandbox.agentSandbox с командой git); hide — строки, которые нужно вычистить из вывода (токены)
|
|
90
|
+
* @returns {Promise<string>} stdout
|
|
91
|
+
*/
|
|
92
|
+
export function runGit(args, { cwd, env = gitEnv(), wrap = null, timeoutMs = 120_000, hide = [], okCodes = [0], maxOut = 4 * 1024 * 1024 } = {}) {
|
|
93
|
+
// okCodes — коды выхода, которые не считаются ошибкой (git diff --no-index возвращает 1, когда различия есть);
|
|
94
|
+
// maxOut — сколько символов вывода хранить (остальное отбрасывается: большой diff целиком не нужен)
|
|
95
|
+
const command = wrap ? wrap.command : gitCommand();
|
|
96
|
+
const argv = wrap ? [...wrap.args, ...args] : args;
|
|
97
|
+
const clean = (s) => hide.filter(Boolean).reduce((acc, h) => acc.replaceAll(h, '***'), s);
|
|
98
|
+
return new Promise((resolve, reject) => {
|
|
99
|
+
let proc;
|
|
100
|
+
try {
|
|
101
|
+
proc = spawn(command, argv, { cwd, env: wrap ? wrap.env(env) : env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, detached: !IS_WIN });
|
|
102
|
+
} catch (e) {
|
|
103
|
+
return reject(new GitError(e.message));
|
|
104
|
+
}
|
|
105
|
+
let out = '';
|
|
106
|
+
let err = '';
|
|
107
|
+
let timedOut = false;
|
|
108
|
+
const timer = setTimeout(() => {
|
|
109
|
+
timedOut = true;
|
|
110
|
+
killTree(proc, 1000);
|
|
111
|
+
}, timeoutMs);
|
|
112
|
+
// кодировка задаётся потоку: иначе символ не из латиницы, попавший на границу порций, превращается в мусор
|
|
113
|
+
proc.stdout.setEncoding('utf8');
|
|
114
|
+
proc.stderr.setEncoding('utf8');
|
|
115
|
+
proc.stdout.on('data', (d) => {
|
|
116
|
+
if (out.length < maxOut) out += d;
|
|
117
|
+
});
|
|
118
|
+
proc.stderr.on('data', (d) => {
|
|
119
|
+
if (err.length < 64 * 1024) err += d;
|
|
120
|
+
});
|
|
121
|
+
proc.on('error', (e) => {
|
|
122
|
+
clearTimeout(timer);
|
|
123
|
+
reject(new GitError(e.message));
|
|
124
|
+
});
|
|
125
|
+
proc.on('close', (code) => {
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
if (timedOut) return reject(new GitError(`git ${args[0]}: нет ответа за ${Math.round(timeoutMs / 1000)} с`, { timeout: true }));
|
|
128
|
+
if (!okCodes.includes(code)) {
|
|
129
|
+
const stderr = clean(err.trim());
|
|
130
|
+
// подсказки git («hint: …») пользователю не нужны — в сообщение идут последние содержательные строки
|
|
131
|
+
const lines = stderr.split(/\r?\n/).filter((l) => l.trim() && !/^hint:/i.test(l));
|
|
132
|
+
return reject(new GitError(lines.slice(-3).join(' | ') || `git ${args[0]}: код ${code}`, { code, stderr }));
|
|
133
|
+
}
|
|
134
|
+
resolve(clean(out));
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Разбор `git status --porcelain=v2 --branch`.
|
|
141
|
+
* @returns {{branch: string|null, upstream: string|null, ahead: number, behind: number, changed: number}}
|
|
142
|
+
*/
|
|
143
|
+
export function parseStatus(text) {
|
|
144
|
+
const st = { branch: null, upstream: null, ahead: 0, behind: 0, changed: 0 };
|
|
145
|
+
for (const line of String(text ?? '').split(/\r?\n/)) {
|
|
146
|
+
if (line.startsWith('# branch.head ')) st.branch = line.slice(14) === '(detached)' ? null : line.slice(14);
|
|
147
|
+
else if (line.startsWith('# branch.upstream ')) st.upstream = line.slice(18);
|
|
148
|
+
else if (line.startsWith('# branch.ab ')) {
|
|
149
|
+
const m = /\+(\d+) -(\d+)/.exec(line);
|
|
150
|
+
if (m) [st.ahead, st.behind] = [Number(m[1]), Number(m[2])];
|
|
151
|
+
} else if (line && !line.startsWith('#')) st.changed++;
|
|
152
|
+
}
|
|
153
|
+
return st;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Состояние репозитория в папке cwd или null, если это не репозиторий git.
|
|
158
|
+
* @returns {Promise<null | {top: string, remote: string|null, branch: string|null, upstream: string|null, ahead: number, behind: number, changed: number}>}
|
|
159
|
+
*/
|
|
160
|
+
export async function repoState(cwd, opts = {}) {
|
|
161
|
+
let top;
|
|
162
|
+
try {
|
|
163
|
+
top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
164
|
+
} catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
// адрес как записан в настройках репозитория (без подстановок url.*.insteadOf): по нему определяется сервис
|
|
168
|
+
const remote = await runGit(['config', '--get', 'remote.origin.url'], { cwd, ...opts }).then((s) => s.trim() || null, () => null);
|
|
169
|
+
const status = parseStatus(await runGit(['status', '--porcelain=v2', '--branch'], { cwd, ...opts }));
|
|
170
|
+
return { top, remote, ...status };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Клонирует репозиторий url в папку dest (её ещё нет), запускается из её родительской папки cwd. Подмодули не тянутся. */
|
|
174
|
+
export const cloneRepo = (url, dest, { cwd, ...opts }) => runGit(['clone', '--no-recurse-submodules', '--', url, dest], { cwd, timeoutMs: 10 * 60_000, ...opts });
|
|
175
|
+
|
|
176
|
+
/** Сверяется с сервером (git fetch): рабочие файлы не трогает, обновляет сведения о ветках сервера. */
|
|
177
|
+
export const fetchRepo = (cwd, opts = {}) => runGit(['fetch', '--prune', 'origin'], { cwd, timeoutMs: 60_000, ...opts });
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Получает изменения с сервера: fetch и перемотка вперёд, если это возможно без слияния.
|
|
181
|
+
* @returns {Promise<'updated'|'uptodate'|'diverged'|'noupstream'>} diverged — истории разошлись, нужно слияние (его делает агент)
|
|
182
|
+
*/
|
|
183
|
+
export async function pullRepo(cwd, opts = {}) {
|
|
184
|
+
await fetchRepo(cwd, opts);
|
|
185
|
+
const before = parseStatus(await runGit(['status', '--porcelain=v2', '--branch'], { cwd, ...opts }));
|
|
186
|
+
if (!before.upstream) return 'noupstream';
|
|
187
|
+
if (!before.behind) return 'uptodate';
|
|
188
|
+
if (before.ahead) return 'diverged';
|
|
189
|
+
await runGit(['merge', '--ff-only', '@{u}'], { cwd, ...opts });
|
|
190
|
+
return 'updated';
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Файлы с секретами среди коммитов, которые ещё не отправлены на сервер (по именам: .env, ключи, учётные данные). */
|
|
194
|
+
export async function unpushedSecrets(cwd, opts = {}) {
|
|
195
|
+
const st = parseStatus(await runGit(['status', '--porcelain=v2', '--branch'], { cwd, ...opts }));
|
|
196
|
+
// без ветки на сервере сравнивать не с чем — смотрим все файлы текущего коммита
|
|
197
|
+
const args = st.upstream ? ['diff', '--name-only', '--diff-filter=AM', '@{u}', 'HEAD'] : ['ls-tree', '-r', '--name-only', 'HEAD'];
|
|
198
|
+
const names = await runGit(args, { cwd, ...opts }).then((s) => s.split(/\r?\n/).filter(Boolean), () => []);
|
|
199
|
+
return names.filter((n) => isSecretName(`/${n}`));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Отправляет текущую ветку на сервер (и связывает её с веткой сервера). */
|
|
203
|
+
export const pushRepo = (cwd, opts = {}) => runGit(['push', '-u', 'origin', 'HEAD'], { cwd, ...opts });
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Коммитит все изменения, кроме файлов с секретами: их из коммита убирает, новые — дописывает в .gitignore.
|
|
207
|
+
* @returns {Promise<{committed: boolean, skipped: string[], tracked: string[]}>} committed — коммит создан (было что
|
|
208
|
+
* коммитить); skipped — новые файлы с секретами, внесённые в .gitignore; tracked — файлы с секретами, которые уже
|
|
209
|
+
* были в репозитории: их изменения в коммит не вошли
|
|
210
|
+
*/
|
|
211
|
+
export async function commitAll(cwd, message, opts = {}) {
|
|
212
|
+
await runGit(['add', '-A'], { cwd, ...opts });
|
|
213
|
+
const staged = (await runGit(['diff', '--cached', '--name-status'], { cwd, ...opts }))
|
|
214
|
+
.split(/\r?\n/)
|
|
215
|
+
.filter(Boolean)
|
|
216
|
+
.map((l) => ({ status: l[0], name: l.split('\t').pop() }));
|
|
217
|
+
const secrets = staged.filter((f) => f.status !== 'D' && isSecretName(`/${f.name}`));
|
|
218
|
+
const skipped = secrets.filter((f) => f.status === 'A').map((f) => f.name);
|
|
219
|
+
const tracked = secrets.filter((f) => f.status !== 'A').map((f) => f.name);
|
|
220
|
+
if (secrets.length) {
|
|
221
|
+
await runGit(['reset', '-q', '--', ...secrets.map((f) => f.name)], { cwd, ...opts });
|
|
222
|
+
if (skipped.length) {
|
|
223
|
+
const top = (await runGit(['rev-parse', '--show-toplevel'], { cwd, ...opts })).trim();
|
|
224
|
+
const file = join(top, '.gitignore');
|
|
225
|
+
const have = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
226
|
+
const lines = skipped.map((n) => `/${n}`).filter((l) => !have.split(/\r?\n/).includes(l));
|
|
227
|
+
if (lines.length) appendFileSync(file, `${have && !have.endsWith('\n') ? '\n' : ''}${lines.join('\n')}\n`);
|
|
228
|
+
await runGit(['add', '--', '.gitignore'], { cwd: top, ...opts });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const left = (await runGit(['diff', '--cached', '--name-only'], { cwd, ...opts })).trim();
|
|
232
|
+
if (!left) return { committed: false, skipped, tracked };
|
|
233
|
+
await runGit(['commit', '-q', '-m', message], { cwd, ...opts });
|
|
234
|
+
return { committed: true, skipped, tracked };
|
|
235
|
+
}
|