acpgram 1.25.0 → 1.27.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 +41 -1
- package/README.ru.md +44 -0
- package/package.json +1 -1
- package/src/bot.mjs +28 -4
- package/src/db.mjs +31 -0
- package/src/engines.mjs +3 -2
- package/src/files.mjs +11 -0
- package/src/filesUi.mjs +293 -0
- package/src/git.mjs +226 -0
- package/src/gitAccess.mjs +112 -0
- package/src/gitHosts.mjs +195 -0
- package/src/gitUi.mjs +438 -0
- package/src/i18n.mjs +115 -0
- package/src/projectFiles.mjs +168 -0
- package/src/projectsUi.mjs +14 -2
- package/src/state.mjs +2 -0
- package/src/turn.mjs +3 -2
- package/src/ui.mjs +3 -1
package/README.md
CHANGED
|
@@ -50,6 +50,8 @@ Check it yourself after installing: `npm audit signatures` verifies the registry
|
|
|
50
50
|
- **Dialogs mode (topics)** — if topics in private chats are turned on for the bot (@BotFather), each topic of the chat is a separate dialog with the agent, with its own project, engine and history. You can work in several topics at once and come back to a topic later to continue where you left off: the agent session resumes by itself. `/new` creates a new topic, and the agent names it after the first answer (with a short project name in front); General works as a regular dialog, and `/project` there shows the dialogs of the chosen project as buttons that open the topic. A command sent from the chat list rather than from inside a topic (Telegram creates a new topic for such a message by itself) runs in General, and the empty topic is deleted. A topic stays in its own project. Everyone picks the mode with `/topics`: "Dialogs" or "One chat". A teammate runs up to `MAX_AGENTS_PER_USER` agents at once (2), the admin up to `ADMIN_MAX_AGENTS` (4); when there is no room, the user's own oldest idle agent is unloaded, and that dialog continues when the user comes back to it.
|
|
51
51
|
- **Language** — the bot talks to each user in their Telegram language (`ru`, `uk` or `en`; any other falls back to `DEFAULT_LANG`, English by default). `/language` changes it and takes priority over the Telegram language. The `acpgram` terminal commands (setup wizard, service, update, help) speak the system language: Russian, Ukrainian, otherwise English; on Windows the system UI language is used, not the regional format.
|
|
52
52
|
- **Projects** — `/project` picks the working folder by buttons, by name search or by path (`/project ~/projects/web`), with one-tap recent projects.
|
|
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.
|
|
53
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.
|
|
54
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.
|
|
55
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.
|
|
@@ -184,6 +186,8 @@ In the container the agent sees only the mounted projects folder (`PROJECTS_DIR`
|
|
|
184
186
|
| `/engine [gemini, claude, agy, codex, opencode]` | everyone | choose the engine |
|
|
185
187
|
| `/model [name]` | everyone | choose the model and reasoning level; with a name — search for a model (`/model sonnet`) |
|
|
186
188
|
| `/new` | everyone | new session |
|
|
189
|
+
| `/files` | everyone | project files: list, create, upload and delete — bypassing the agent |
|
|
190
|
+
| `/git` | everyone | Git: GitHub / GitLab accounts, clone, pull and push |
|
|
187
191
|
| `/sessions` | everyone | resume a previous session in this project |
|
|
188
192
|
| `/stop` | everyone | stop the running request |
|
|
189
193
|
| `/close`, `/exit` | everyone | close the session and unload the agent process |
|
|
@@ -207,6 +211,37 @@ OpenCode has only two modes (`plan` and `build`); what the agent may do is set b
|
|
|
207
211
|
|
|
208
212
|
New teammates get only the default engine; the admin grants other engines and can restrict models per user and per engine. At most `MAX_AGENTS` (3) teammate agents run at once across all engines (the admin is not counted); idle sessions close after `IDLE_MINUTES` (30).
|
|
209
213
|
|
|
214
|
+
### Project files and secrets
|
|
215
|
+
|
|
216
|
+
Everything a user types to the bot or sends as a file goes to the agent, and therefore into a model request. That is wrong for passwords, tokens and keys: free models may use requests for training. The `/files` command puts a file straight into the project folder, bypassing the agent.
|
|
217
|
+
|
|
218
|
+
- **List.** `/files` shows the files and folders of the current project (including hidden ones such as `.env`; without `.git`, `node_modules` and links); folders are browsed with buttons.
|
|
219
|
+
- **"📝 Create file".** The bot asks for a name (a subfolder is allowed: `config/.env`) and then for the contents in one message (up to 3500 characters). The message with the contents is deleted from the chat right away; it is not written to the database or the logs.
|
|
220
|
+
- **"⬆️ Upload file".** The next file you send (or an album) is saved to the open project folder under its own name, and the message with it is deleted from the chat. The wait is one-off and expires in 10 minutes. Without pressing the button, files and images go to the agent as before.
|
|
221
|
+
- **Delete** — from the file card, with a confirmation. An existing file is replaced only after a "Replace?" question.
|
|
222
|
+
- **Who can change files:** the administrator; a teammate inside their personal workspace, and in a shared root with the "Normal" or "Full" level. Anyone can view the list.
|
|
223
|
+
- **Inside the project only.** The bot never writes or deletes outside the project folder and does not follow links: a link planted in the project cannot make it overwrite someone else's file.
|
|
224
|
+
|
|
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.
|
|
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
|
+
- **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.
|
|
237
|
+
- **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".
|
|
238
|
+
|
|
239
|
+
**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.
|
|
240
|
+
|
|
241
|
+
**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.
|
|
242
|
+
|
|
243
|
+
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.
|
|
244
|
+
|
|
210
245
|
### Personal workspaces
|
|
211
246
|
|
|
212
247
|
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.
|
|
@@ -256,6 +291,9 @@ What the sandbox does not do:
|
|
|
256
291
|
| `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" |
|
|
257
292
|
| `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 |
|
|
258
293
|
| `BWRAP_COMMAND` | no | path to `bwrap` if it is not in `PATH` |
|
|
294
|
+
| `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") |
|
|
295
|
+
| `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 |
|
|
296
|
+
| `GIT_COMMAND` | no | path to `git` if it is not in `PATH` |
|
|
259
297
|
| `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 |
|
|
260
298
|
| `DEFAULT_ENGINE` | no | `gemini` (default), `claude`, `agy`, `codex` or `opencode`; the bot does not start if this engine is not installed |
|
|
261
299
|
| `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` |
|
|
@@ -302,7 +340,9 @@ src/
|
|
|
302
340
|
state.mjs per-user state: agent process, engine, project, limits, idle reaper
|
|
303
341
|
admin.mjs invites, access requests, /users, /active
|
|
304
342
|
projects.mjs project paths (inside the root or anywhere), recent projects, search
|
|
305
|
-
*Ui.mjs /project, /sessions, /engine, /model screens
|
|
343
|
+
*Ui.mjs /project, /files, /git, /sessions, /engine, /model screens
|
|
344
|
+
git*.mjs git commands run by the bot, GitHub / GitLab clients, accounts and what the agent gets from them
|
|
345
|
+
projectFiles.mjs project files bypassing the agent: safe writes and deletes inside the project, no links
|
|
306
346
|
ui.mjs rendering: drafts, steps, final message, screens
|
|
307
347
|
telegram.mjs Bot API calls, rich messages, long text splitting, file download and upload
|
|
308
348
|
sandbox.mjs agent sandbox (Linux, bubblewrap): what a teammate's agent can see, the startup check
|
package/README.ru.md
CHANGED
|
@@ -53,6 +53,8 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
53
53
|
- с `PROJECTS_ROOT` (командный сервер, например `C:\scripts`) — только папки внутри корня;
|
|
54
54
|
- с `PROJECTS_ROOT` и `USER_WORKSPACES=1` (личные пространства) — у каждого сотрудника своя папка в корне, чужие папки он не видит и выбрать не может; новый проект создаётся кнопкой «➕ Новый проект» (см. «Личные пространства»);
|
|
55
55
|
- без `PROJECTS_ROOT` (личная установка) — любая существующая папка, по умолчанию домашняя.
|
|
56
|
+
- **Файлы проекта в обход агента** (`/files`): список файлов проекта по папкам, создание файла из сообщения, загрузка файла с устройства и удаление. Содержимое таких файлов не попадает в запрос к модели — так в проект кладут секреты (`.env`, ключи), которые нельзя показывать бесплатным моделям. См. «Файлы проекта и секреты».
|
|
57
|
+
- **Git: GitHub и GitLab** (`/git`): подключение аккаунта по токену доступа, клонирование репозитория кнопкой из списка, «Получить», «Отправить» и «Сохранить и отправить». Токен хранится у бота и агенту не передаётся; файлы с секретами в коммиты не попадают. См. «Git: GitHub и GitLab».
|
|
56
58
|
- **Возврат к прошлой сессии** (`/sessions`): агент помнит весь диалог, сессию можно возобновить даже после перезапуска бота. У каждой сессии метка движка; сессия возобновляется в том движке, где была создана.
|
|
57
59
|
- **Доступ для сотрудников**: администратор выдаёт и забирает доступ, выбирая уровень, движки и модели.
|
|
58
60
|
- **База работы бота** (SQLite): сессии, запросы пользователей с моделью, токенами и стоимостью, вызовы инструментов, разрешения, ответы модели.
|
|
@@ -66,6 +68,8 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
66
68
|
| `/engine [gemini, claude, agy, codex, opencode]` | все | выбор движка кнопками или по названию |
|
|
67
69
|
| `/model [название]` | все | выбор модели и уровня рассуждений текущего движка; с названием — поиск модели (`/model sonnet`) |
|
|
68
70
|
| `/new` | все | новая сессия агента |
|
|
71
|
+
| `/files` | все | файлы проекта: список, создание, загрузка и удаление — в обход агента |
|
|
72
|
+
| `/git` | все | Git: аккаунты GitHub / GitLab, клонирование, получение и отправка изменений |
|
|
69
73
|
| `/sessions` | все | список прошлых сессий в текущем проекте и возврат в выбранную |
|
|
70
74
|
| `/stop` | все | остановить выполняющийся запрос |
|
|
71
75
|
| `/close`, `/exit` | все | закрыть сессию, выгрузить процесс агента и освободить слот |
|
|
@@ -97,6 +101,37 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
97
101
|
|
|
98
102
|
**Лимиты:** не более 3 одновременно работающих агентов сотрудников во всех движках вместе (администратор вне лимита), сессия закрывается через 30 минут простоя.
|
|
99
103
|
|
|
104
|
+
### Файлы проекта и секреты
|
|
105
|
+
|
|
106
|
+
Всё, что пользователь пишет боту или отправляет ему файлом, уходит агенту, а значит — в запрос к модели. Для паролей, токенов и ключей это не подходит: бесплатные модели могут использовать запросы для обучения. Команда `/files` кладёт файл прямо в папку проекта, минуя агента.
|
|
107
|
+
|
|
108
|
+
- **Список.** `/files` показывает файлы и папки текущего проекта (вместе со скрытыми вроде `.env`; без `.git`, `node_modules` и ссылок), по папкам можно ходить кнопками.
|
|
109
|
+
- **«📝 Создать файл».** Бот спрашивает имя (можно с подпапкой: `config/.env`), затем содержимое одним сообщением (до 3500 символов). Сообщение с содержимым сразу удаляется из чата; в базу и журналы оно не пишется.
|
|
110
|
+
- **«⬆️ Загрузить файл».** Следующий присланный файл (или альбом) сохраняется в открытую папку проекта под своим именем, а сообщение с ним удаляется из чата. Ожидание одноразовое и истекает через 10 минут. Без нажатия кнопки файлы и изображения, как и раньше, передаются агенту.
|
|
111
|
+
- **Удаление** — из карточки файла, с подтверждением. Существующий файл заменяется только после вопроса «Заменить?».
|
|
112
|
+
- **Кто может менять файлы:** администратор; сотрудник — в личном пространстве, а в общем корне — с уровнем «Обычный» или «Полный». Смотреть список может любой.
|
|
113
|
+
- **Только внутри проекта.** Бот не пишет и не удаляет за пределами папки проекта и не ходит по ссылкам: ссылка, подложенная в проект, не заставит его перезаписать чужой файл.
|
|
114
|
+
|
|
115
|
+
Что это даёт и чего не даёт. Секрет не попадает в запрос к модели *от пользователя*. Сам файл агенту доступен — иначе приложения, которые он пишет и запускает, не смогли бы им пользоваться. Чтобы агент не прочитал значения в диалог сам, бот регулярно напоминает ему: файлы с секретами не открывать и не выводить, ссылаться на настройки по именам, а за недостающим значением отправлять пользователя в `/files`. Это указание, а не запрет: для особо чувствительных данных используйте модель провайдера, который не обучается на запросах.
|
|
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
|
+
- **Секреты не уходят в репозиторий.** При «Сохранить и отправить» файлы с секретами (`.env`, ключи, учётные данные) из коммита исключаются и дописываются в `.gitignore`. Если такой файл закоммитил агент, перед отправкой бот предупреждает и отправляет только после «Отправить всё равно».
|
|
128
|
+
|
|
129
|
+
**Где лежит токен.** По умолчанию — только в базе бота: клонирование, получение и отправку делает бот, а агент работает с репозиторием локально (состояние, сравнение, коммиты, ветки, слияние) и на просьбу отправить изменения направляет пользователя в `/git`. В песочнице токен агенту недоступен совсем. Администратор может выбрать другой режим — `GIT_AGENT_AUTH=1`: вход передаётся и процессу агента, он сам получает и отправляет изменения. Это удобнее, но токен становится виден агенту и может попасть в запрос к модели; включайте его, только если доверяете моделям, с которыми работают сотрудники.
|
|
130
|
+
|
|
131
|
+
**Как бот запускает git.** Репозиторий лежит там, куда пишет агент, а настройки и хуки репозитория умеют запускать программы. Поэтому бот запускает git с отключёнными хуками и помощниками входа, без общего и системного конфига (на Linux и macOS), а при включённой песочнице — внутри песочницы того же сотрудника. Вход передаётся процессу git через окружение и только для адресов своего сервиса; в настройки репозитория и в адрес он не пишется. Остаточный риск: настройки самого репозитория (фильтры) выполняются при операциях, и намеренно вредоносный агент мог бы перехватить токен во время операции.
|
|
132
|
+
|
|
133
|
+
Подключаются только репозитории по HTTPS с перечисленных сервисов; репозиторий с адресом SSH или с другого сервера бот показывает, но получать и отправлять в него не может.
|
|
134
|
+
|
|
100
135
|
### Личные пространства
|
|
101
136
|
|
|
102
137
|
По умолчанию все сотрудники ходят по одному корню проектов. `USER_WORKSPACES=1` (вместе с `PROJECTS_ROOT`) даёт каждому сотруднику свою папку: `<корень>/<Telegram ID>`. Папка создаётся сама при первом обращении сотрудника к боту.
|
|
@@ -274,6 +309,9 @@ npm start # первый запуск без .env сам открое
|
|
|
274
309
|
| `AGENT_SANDBOX` | нет | `bwrap` — песочница агента (только Linux, нужен пакет `bubblewrap`): агент сотрудника видит только его папку проектов, его файлы и его домашнюю папку. См. «Песочница агента» |
|
|
275
310
|
| `SANDBOX_RO_PATHS` | нет | дополнительные папки, которые песочница видит на чтение (через `:`), — например, место установки движка, если он не запускается в песочнице |
|
|
276
311
|
| `BWRAP_COMMAND` | нет | путь к `bwrap`, если его нет в `PATH` |
|
|
312
|
+
| `GITLAB_URL`, `GITHUB_URL` | нет | адрес своего GitLab и своего GitHub Enterprise (`https://git.example.com`): появляются в `/git` рядом с GitHub и GitLab.com. `GITLAB_NAME`, `GITHUB_NAME` — названия в кнопках (по умолчанию — имя сервера). Не обязательны: администратор добавляет свои серверы и в самом боте (`/git` → «Свои серверы») |
|
|
313
|
+
| `GIT_AGENT_AUTH` | нет | `1` — вход в Git передаётся и агентам: они сами получают и отправляют изменения, но токены сотрудников им видны. По умолчанию токен только у бота |
|
|
314
|
+
| `GIT_COMMAND` | нет | путь к `git`, если его нет в `PATH` |
|
|
277
315
|
| `DEFAULT_ENGINE` | нет | движок по умолчанию: `gemini` (по умолчанию), `claude`, `agy`, `codex` или `opencode`. Если этот движок не установлен, бот не запускается |
|
|
278
316
|
| `DEFAULT_LANG` | нет | язык бота, если язык Telegram пользователя не `ru`, `uk` или `en`: `en` (по умолчанию), `ru` или `uk`. Пользователь может сменить язык командой `/language` |
|
|
279
317
|
| `ACPGRAM_LANG` | нет | язык команд `acpgram` в терминале: `ru`, `uk` или `en`. Обычно не нужен: язык берётся из системы (для Docker и CI, где у системы нет языка) |
|
|
@@ -378,6 +416,12 @@ src/
|
|
|
378
416
|
admin.mjs приглашения, запросы доступа, /users, /active
|
|
379
417
|
projects.mjs пути проектов: с корнем — безопасно внутри него, без корня — любая папка; недавние, поиск
|
|
380
418
|
projectsUi.mjs команда /project и навигация кнопками
|
|
419
|
+
projectFiles.mjs файлы проекта в обход агента: безопасная запись и удаление внутри проекта, без ссылок
|
|
420
|
+
filesUi.mjs команда /files: список, создание, загрузка и удаление файлов проекта
|
|
421
|
+
git.mjs команды git бота: клонирование, состояние, получение, отправка, коммит без секретов; безопасный запуск
|
|
422
|
+
gitHosts.mjs GitHub и GitLab: профиль и репозитории по токену, вход для git
|
|
423
|
+
gitAccess.mjs аккаунты Git пользователей; что из них получает агент (автор коммитов, вход при GIT_AGENT_AUTH)
|
|
424
|
+
gitUi.mjs команда /git: аккаунты, клонирование, получить / отправить / сохранить
|
|
381
425
|
sessionsUi.mjs команда /sessions: возврат к прошлой сессии
|
|
382
426
|
tools.mjs разбор событий вызовов инструментов агента
|
|
383
427
|
asks.mjs кнопки быстрого ответа от агента: метка [[ask: …]], разметка кнопок, выбор по нажатию
|
package/package.json
CHANGED
package/src/bot.mjs
CHANGED
|
@@ -11,6 +11,10 @@ import { adminCommand, handleUnknownUser, onAdminCallback, welcomeNote } from '.
|
|
|
11
11
|
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
|
+
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';
|
|
14
18
|
import { handleSessions, onSessionCallback } from './sessionsUi.mjs';
|
|
15
19
|
import { dropPermissions, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
|
|
16
20
|
import { handleTopics, newTopic, onTopicsCallback } from './topicsUi.mjs';
|
|
@@ -118,6 +122,8 @@ const COMMANDS = [
|
|
|
118
122
|
{ name: 'invite', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/invite') },
|
|
119
123
|
{ name: 'usage', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/usage') },
|
|
120
124
|
{ name: 'project', menu: true, button: true, run: (st, arg) => handleProject(st, arg) },
|
|
125
|
+
{ name: 'files', menu: true, button: true, run: (st) => handleFiles(st) },
|
|
126
|
+
{ name: 'git', menu: true, button: true, run: (st) => handleGit(st) },
|
|
121
127
|
{ name: 'engine', menu: true, button: true, run: (st, arg) => handleEngine(st, arg) },
|
|
122
128
|
{ name: 'model', menu: true, button: true, run: (st, arg) => handleModel(st, arg) },
|
|
123
129
|
{ name: 'new', menu: true, button: true, run: newCommand },
|
|
@@ -141,18 +147,22 @@ const sendToAgent = (st, text, opts = {}) => (st.busy ? enqueue(st, text, opts)
|
|
|
141
147
|
* команды не объявлял, это, скорее всего, опечатка: спрашиваем, а не тратим запрос.
|
|
142
148
|
* @param {{quote?: string|null}} [opts] quote — фрагмент прошлого сообщения, на который отвечает пользователь
|
|
143
149
|
*/
|
|
144
|
-
async function handleText(st, text, { quote = null } = {}) {
|
|
150
|
+
async function handleText(st, text, { quote = null, messageId = null } = {}) {
|
|
145
151
|
const m = /^\/(\w+)(?:@\w+)?(?:\s+([\s\S]*))?$/.exec(text);
|
|
146
152
|
const name = m?.[1]?.toLowerCase();
|
|
147
153
|
const command = name ? COMMANDS.find((c) => c.name === name || c.aliases?.includes(name)) : null;
|
|
148
154
|
const lang = langOf(st.userId);
|
|
149
|
-
if (name) st.pendingInput = null; // любая команда отменяет ожидание названия нового проекта
|
|
150
155
|
if (command) {
|
|
156
|
+
st.pendingInput = null; // команда бота отменяет ожидание названия проекта, имени или содержимого файла
|
|
151
157
|
if (command.admin && !isAdmin(st.userId)) return say(st.to, t('admin.only', lang));
|
|
152
158
|
return command.run(st, m[2]);
|
|
153
159
|
}
|
|
154
160
|
// бот ждёт название папки нового проекта (кнопка «Новый проект» в /project): этот текст — оно, а не запрос агенту
|
|
155
161
|
if (await onProjectNameInput(st, text)) return;
|
|
162
|
+
// бот ждёт имя или содержимое файла проекта (/files): содержимое агенту не передаётся и удаляется из чата
|
|
163
|
+
if (await onFileInput(st, text, { messageId })) return;
|
|
164
|
+
// бот ждёт токен доступа к GitHub / GitLab, строку поиска репозитория или описание изменений (/git)
|
|
165
|
+
if (await onGitInput(st, text, { messageId })) return;
|
|
156
166
|
if (name && !st.agent?.commands?.has(name)) {
|
|
157
167
|
const guess = nearCommand(name, COMMANDS.filter((c) => !c.admin || isAdmin(st.userId)).map((c) => c.name));
|
|
158
168
|
if (guess) {
|
|
@@ -315,6 +325,8 @@ async function handleUpdate(u) {
|
|
|
315
325
|
if (data.startsWith('tpc:')) return onTopicsCallback(st, cb);
|
|
316
326
|
if (data.startsWith('tpl:')) return onTopicListCallback(st, cb);
|
|
317
327
|
if (data.startsWith('nav:')) return onNavCallback(st, cb);
|
|
328
|
+
if (data.startsWith('fl:')) return onFilesCallback(st, cb);
|
|
329
|
+
if (data.startsWith('gt:')) return onGitCallback(st, cb);
|
|
318
330
|
if (data.startsWith('perm:')) return onPermissionCallback(st, cb);
|
|
319
331
|
if (data.startsWith('ask:')) return onAskCallback(st, cb);
|
|
320
332
|
if (data.startsWith('q:')) return onQueueCallback(st, cb);
|
|
@@ -331,8 +343,13 @@ async function handleUpdate(u) {
|
|
|
331
343
|
if (data.startsWith('lang:')) return onLangCallback(st, cb);
|
|
332
344
|
return;
|
|
333
345
|
}
|
|
334
|
-
if (msg?.text) return handleText(getState(from.id, chatId, threadId), msg.text, { quote: quoteOf(msg) });
|
|
335
|
-
if (msg?.photo || msg?.document)
|
|
346
|
+
if (msg?.text) return handleText(getState(from.id, chatId, threadId), msg.text, { quote: quoteOf(msg), messageId: msg.message_id });
|
|
347
|
+
if (msg?.photo || msg?.document) {
|
|
348
|
+
const st = getState(from.id, chatId, threadId);
|
|
349
|
+
// нажата «Загрузить файл» в /files: файл кладётся в проект, а не передаётся агенту
|
|
350
|
+
if (await onFileUpload(st, msg)) return;
|
|
351
|
+
return handleAttachment(st, msg);
|
|
352
|
+
}
|
|
336
353
|
// голосовое, видео, стикер и т. п.: раньше бот на них молчал
|
|
337
354
|
if (msg && unsupportedKind(msg)) return say(getState(from.id, chatId, threadId).to, t('msg.unsupported', langOf(from.id)));
|
|
338
355
|
}
|
|
@@ -421,6 +438,13 @@ async function main() {
|
|
|
421
438
|
}
|
|
422
439
|
log(`движок по умолчанию: ${DEFAULT_ENGINE}`);
|
|
423
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
|
+
);
|
|
424
448
|
log(
|
|
425
449
|
ROOT
|
|
426
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/files.mjs
CHANGED
|
@@ -117,6 +117,17 @@ export function outboxNote(outbox) {
|
|
|
117
117
|
);
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
+
/**
|
|
121
|
+
* Подсказка агенту о секретах проекта. Пользователь кладёт их в проект сам, в обход чата (/files), чтобы значения не
|
|
122
|
+
* попадали в запросы к модели; агент не должен свести это на нет, прочитав файл в диалог. Доступ к файлам не закрыт:
|
|
123
|
+
* приложения, которые агент пишет и запускает, читают секреты во время работы. Служебный текст — на английском.
|
|
124
|
+
*/
|
|
125
|
+
export const SECRETS_NOTE =
|
|
126
|
+
'[AcpGram] Files such as .env, .Renviron, private keys and credentials in the project hold the user\'s secrets. ' +
|
|
127
|
+
'Do not open or print them and never show, quote or repeat their values in replies, commands or commits; refer to settings by name. ' +
|
|
128
|
+
'Code you write may load them at run time, that is what they are for. If a secret value is needed or missing, do not ask the user ' +
|
|
129
|
+
'to send it in the chat: tell them to put it into the project file themselves with the /files command of this bot.';
|
|
130
|
+
|
|
120
131
|
const NO_TEXT_PROMPT = 'The user sent the attached file(s) without a message. Look at them, briefly say what they contain and ask what to do with them.';
|
|
121
132
|
|
|
122
133
|
/**
|