acpgram 1.31.7 → 1.32.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 +9 -3
- package/README.ru.md +10 -3
- package/package.json +1 -1
- package/src/access.mjs +9 -0
- package/src/bot.mjs +81 -24
- package/src/cli-i18n.mjs +19 -6
- package/src/clip.mjs +15 -0
- package/src/ctx.mjs +6 -0
- package/src/db.mjs +41 -3
- package/src/engines.mjs +14 -3
- package/src/filesUi.mjs +5 -4
- package/src/forceStop.mjs +18 -0
- package/src/git.mjs +50 -5
- package/src/gitCtx.mjs +68 -0
- package/src/gitInspect.mjs +7 -2
- package/src/gitPublishUi.mjs +25 -28
- package/src/gitRepoUi.mjs +43 -33
- package/src/gitUi.mjs +49 -58
- package/src/i18n.mjs +10 -0
- package/src/log.mjs +27 -2
- package/src/pending.mjs +62 -0
- package/src/projectFiles.mjs +10 -4
- package/src/protect.mjs +18 -0
- package/src/queue.mjs +42 -0
- package/src/quota.mjs +40 -0
- package/src/safety.mjs +20 -0
- package/src/sandbox.mjs +16 -1
- package/src/setup.mjs +14 -0
- package/src/state.mjs +28 -8
- package/src/turn.mjs +26 -4
- package/src/warnings.mjs +38 -0
package/README.md
CHANGED
|
@@ -46,7 +46,7 @@ Check it yourself after installing: `npm audit signatures` verifies the registry
|
|
|
46
46
|
- **Widgets** (Bot API 10.4, enabled with `WIDGETS=1`) — `/model` and `/sessions` open as a widget right in the message: the whole model catalog with groups and vendors is browsed instantly, with no round trips to the bot; project sessions are cards with the start of the request. Widgets are off by default: since November 13, 2026 Telegram does not let ordinary bots send them, and they have not been verified in the app. With `WIDGETS=1` the bot tries the widget and shows the plain button menu if Telegram refuses it or the catalog does not fit the size limit; the same menu is behind the "Plain menu" button under the widget.
|
|
47
47
|
- **Model and reasoning level** — `/model` lists the models the agent itself reports (plus `effort` for Claude Code and `thought_level` for Antigravity); the choice is remembered per user and per engine. OpenCode reports hundreds of models (every connected provider), so `/model` first offers groups — "🆓 Free" and the providers — and pages through 20 models at a time; models that cannot call tools (image or music generation) are hidden. Aggregators like OpenRouter (hundreds of models) are split further by model vendor — OpenAI, Anthropic, Qwen… (vendors with 1–2 models go to "Other"). The quickest way is search: `/model sonnet` lists every matching model as buttons; the top of `/model` also has "🕘" buttons with your recently chosen models.
|
|
48
48
|
- **Permission requests as buttons** — "Allow", "Allow for this session", "Reject". Options that would persist a rule forever or raise the session above the user's access level are never shown. "Allow for this session" is available in every engine: when the agent has no such option of its own (Claude Code), the bot adds it and keeps the rule for as long as the agent process lives (until `/new`, `/close`, the idle timeout or a bot restart). The button says exactly what will be allowed. File edits are allowed as a whole, commands by program name (allowing `ls` lets every `ls …` through), and for programs with subcommands (`git`, `npm`, `docker` and the like) by program and subcommand: allowing `git status` lets every `git status …` through, but not `git push`. Every part of a compound command must be allowed. Only the exact same command is allowed for shell wrappers (`bash -c`, `powershell`, `cmd /c`, `sudo`), interpreters (`python`, `node`, `Rscript`, `npx` and the like), commands with substitutions, writing to a file (`>`) or variables before the program (`PATH=… git`).
|
|
49
|
-
- **Files and images** — send the bot a photo or a file (text, PDF, spreadsheet, etc., up to 20 MB); the caption becomes the request. The file is saved to `<data dir>/uploads/<user id>/` and the agent gets its path and reads it with its own tools. An album of several photos or files is handled as one request. `.zip`, `.tar`, `.tar.gz` and `.tgz` archives are unpacked next to the file (`…_unpacked`, at most 500 files and 100 MB; unsafe paths and links are skipped) and the agent gets the file list; `.7z` and `.rar` stay a plain file; images are also passed as an `image` block when the agent supports it. In the other direction the agent can create a file and send it to the chat: it saves the file to `<data dir>/outbox/<user id>/` (or the project folder) and puts a `[[send:path]]` marker in its reply. The file appears right inside the reply, where the marker was: JPEG and PNG as an image, everything else as a document. If Telegram rejects such a message or the files together exceed 45 MB, they arrive as separate messages after the reply. A marker inside code (backticks or a code block) is ignored. Only files from these two folders are sent, never secrets (`.env`, the bot's database and logs, `.git`). Files are kept for 7 days (`FILES_KEEP_DAYS`).
|
|
49
|
+
- **Files and images** — send the bot a photo or a file (text, PDF, spreadsheet, etc., up to 20 MB); the caption becomes the request. The file is saved to `<data dir>/uploads/<user id>/` and the agent gets its path and reads it with its own tools. An album of several photos or files is handled as one request. `.zip`, `.tar`, `.tar.gz` and `.tgz` archives are unpacked next to the file (`…_unpacked`, at most 500 files and 100 MB; unsafe paths and links are skipped) and the agent gets the file list; `.7z` and `.rar` stay a plain file; images are also passed as an `image` block when the agent supports it. In the other direction the agent can create a file and send it to the chat: it saves the file to `<data dir>/outbox/<user id>/` (or the project folder) and puts a `[[send:path]]` marker in its reply. The file appears right inside the reply, where the marker was: JPEG and PNG as an image, everything else as a document. If Telegram rejects such a message or the files together exceed 45 MB, they arrive as separate messages after the reply. A marker inside code (backticks or a code block) is ignored. Only files from these two folders are sent, never secrets (`.env`, the bot's database and logs, `.git`). Files are kept for 7 days (`FILES_KEEP_DAYS`). Uploads and archive extraction run one at a time; a message that looks like a token is deleted and never reaches the agent.
|
|
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
|
- **Documentation** — `/help` and the bot's menu button open the docs page with an AI chat; the `/help` message offers to open it in a browser or as a mini app.
|
|
@@ -250,7 +250,7 @@ The `/git` command connects projects to GitHub, GitLab.com and your own servers
|
|
|
250
250
|
|
|
251
251
|
**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.
|
|
252
252
|
|
|
253
|
-
**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
|
|
253
|
+
**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, credential helpers and password prompts turned off, without the global and system config (on Linux and macOS), over HTTPS only, and, when the sandbox is on, inside the same teammate's sandbox. Before operations with sign-in and commits, the local `.git/config` is checked: commands, external includes, filters (except Git LFS) and disabled TLS verification are rejected, and only setting names are shown in the reply. The sign-in is needed only for cloning, pulling, pushing, switching branches and creating a merge request; local commands run without it and it is never written to the repository settings or the URL. Only one git operation runs per repository folder, and a failed clone leaves no partial folder behind. Residual risk: on Windows the global and system config is still read, Git LFS filters run during operations, and without the sandbox a deliberately malicious agent could change the local config between the check and the command.
|
|
254
254
|
|
|
255
255
|
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.
|
|
256
256
|
|
|
@@ -280,7 +280,7 @@ The bot's `.env` and database, the home folder of the bot's account, other peopl
|
|
|
280
280
|
|
|
281
281
|
- **Everyone has their own engine settings.** Each teammate has a home folder of their own, so session history, settings and engine logins are separate. The engine must work without a login stored in the home folder of the bot's account: OpenCode on its free models needs no keys at all, the others use an API key from `.env`. A subscription login (`codex login`, Google sign-in, a Claude subscription) is not visible in the sandbox.
|
|
282
282
|
- **The "Full" level becomes safer.** The agent asks for no permissions, but can change only its teammate's workspace — convenient for people who do not want to deal with permission requests.
|
|
283
|
-
- **The administrator works without the sandbox
|
|
283
|
+
- **The administrator works without the sandbox** unless `ADMIN_SANDBOX=1` is set. With it, the administrator's agent is isolated in folders inside `PROJECTS_ROOT` too: a teammate cannot leave an engine config in a shared folder that would run with the bot's rights. The bot tells the administrator once when teammates have no sandbox, when the administrator works without one in a shared folder, or when `.env` is readable by local user groups on Windows.
|
|
284
284
|
- **Startup check.** The bot checks that bubblewrap runs, that the bot's secrets are not visible from inside, and that the engines start in the sandbox. If the sandbox or the default engine does not work, the bot does not start and says why. Other engines that failed in the sandbox are not offered to teammates. If an engine is installed in an unusual place, add its folder to `SANDBOX_RO_PATHS`.
|
|
285
285
|
- **Sessions started before the sandbox was turned on** are not resumed in it — a new one starts.
|
|
286
286
|
- **Ubuntu 24.04 and later:** user namespaces may be blocked by AppArmor. If the bot reports at startup that the sandbox does not work, run `sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0` (a file in `/etc/sysctl.d/` makes it permanent) or add an AppArmor profile for `bwrap`. The sandbox is not supported in Docker: the container separates the bot from the system, but not teammates from each other.
|
|
@@ -301,6 +301,8 @@ What the sandbox does not do:
|
|
|
301
301
|
| `ALLOWED_USER_ID` | yes | Telegram ID of the main admin |
|
|
302
302
|
| `PROJECTS_ROOT` | no | projects root: projects can be chosen only inside it (team server). Without it any folder on the machine can be chosen, the home folder by default (personal install) |
|
|
303
303
|
| `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" |
|
|
304
|
+
| `ADMIN_SANDBOX` | no | `1` — sandbox the administrator too in folders inside `PROJECTS_ROOT` (only with `AGENT_SANDBOX=bwrap`; off by default) |
|
|
305
|
+
| `AGENT_ENV_HIDE`, `AGENT_ENV_PASS` | no | extra environment variables to hide from the agent or, respectively, to pass through (comma-separated lists) |
|
|
304
306
|
| `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 |
|
|
305
307
|
| `BWRAP_COMMAND` | no | path to `bwrap` if it is not in `PATH` |
|
|
306
308
|
| `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") |
|
|
@@ -321,6 +323,10 @@ What the sandbox does not do:
|
|
|
321
323
|
| `ADMIN_MAX_AGENTS` | no | the same for the admin (4) |
|
|
322
324
|
| `IDLE_MINUTES` | no | idle session timeout, minutes (30) |
|
|
323
325
|
| `AGENT_START_TIMEOUT` | no | how many seconds to wait for an agent to start; after that the process is stopped (120) |
|
|
326
|
+
| `UPLOADS_QUOTA_MB` | no | quota for the uploads folder in MB; `0` (default) means no quota |
|
|
327
|
+
| `TURN_IDLE_MINUTES` | no | stop a request when the agent sends no updates for this many minutes; `0` (default) disables the timer |
|
|
328
|
+
| `HISTORY_KEEP_DAYS` | no | delete request history and closed sessions older than this many days; `0` (default) keeps everything |
|
|
329
|
+
| `LOGS_KEEP` | no | delete `data/debug.log.N` archives older than this many days; `0` (default) keeps everything |
|
|
324
330
|
| `ACPGRAM_DEBUG` | no | `1` — detailed log of what the bot sends to Telegram in `data/debug.log` (up to 5 MB plus one previous file; off by default) |
|
|
325
331
|
| `FILES_DIR` | no | folder for received (`uploads`) and outgoing (`outbox`) files (the bot's data folder) |
|
|
326
332
|
| `FILES_KEEP_DAYS` | no | how many days to keep those files (7) |
|
package/README.ru.md
CHANGED
|
@@ -45,7 +45,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
45
45
|
- **Виджеты** (Bot API 10.4, включаются `WIDGETS=1`): `/model` и `/sessions` открываются виджетом прямо в сообщении — весь каталог моделей с группами и вендорами листается мгновенно, без обращений к боту; сессии проекта — карточками с началом запроса. По умолчанию виджеты выключены: с 13 ноября 2026 Telegram не разрешает обычным ботам отправлять их, и в приложении они не проверены. С `WIDGETS=1` бот пробует виджет и сам показывает обычное меню с кнопками, если Telegram его не принял или каталог не поместился в лимит; оно же — по кнопке «Обычное меню» под виджетом.
|
|
46
46
|
- **Выбор движка** (`/engine`): Gemini CLI, Claude Code, Antigravity CLI, Codex или OpenCode — из выданных пользователю. Выбор запоминается для каждого пользователя, смена движка начинает новую сессию. Движок по умолчанию — `DEFAULT_ENGINE`; недоступные на сервере движки не предлагаются, а запускающиеся, но не авторизованные (нет входа или ключа API) помечаются «⚠️ нужен вход».
|
|
47
47
|
- **Выбор модели и уровня рассуждений** (`/model`): модели текущего движка (список присылает сам агент) и уровень рассуждений у Claude Code (`effort`) и Antigravity CLI (`thought_level`). По умолчанию «Авто» — как у агента. Выбор запоминается для каждого пользователя отдельно по движкам и применяется со следующего запроса, без перезапуска сессии. У OpenCode моделей сотни (все подключённые провайдеры), поэтому сначала выбирается группа — «🆓 Бесплатные» или провайдер, — а модели внутри неё листаются по 20; модели, которые не умеют вызывать инструменты (генерация картинок, музыки), не показываются. У агрегаторов вроде OpenRouter (сотни моделей) внутри группы ещё и разработчики моделей — OpenAI, Anthropic, Qwen… (у кого 1–2 модели — в «Прочих»). Быстрее всего — поиск: `/model sonnet` покажет все подходящие модели кнопками; а вверху экрана `/model` — кнопки «🕘» с последними выбранными моделями.
|
|
48
|
-
- **Файлы и изображения**: фото или файл (текст, PDF, таблицы и т. д., до 20 МБ) можно отправить боту, подпись становится запросом. Файл сохраняется в `<каталог данных>/uploads/<id пользователя>/`, агент получает путь и читает его своими инструментами. Альбом из нескольких фото или файлов обрабатывается одним запросом. Архивы `.zip`, `.tar`, `.tar.gz`, `.tgz` бот распаковывает рядом (`…_unpacked`, не больше 500 файлов и 100 МБ; небезопасные пути и ссылки пропускаются), агенту передаётся список файлов; `.7z` и `.rar` остаются обычным файлом; изображения агент получает ещё и блоком `image`, если он это поддерживает. В обратную сторону: агент может создать файл и прислать его в чат — он кладёт файл в `<каталог данных>/outbox/<id пользователя>/` (или в папку проекта) и ставит в ответе метку `[[send:путь]]`. Файл появляется прямо в ответе, на месте метки: JPEG и PNG — изображением, остальное — документом. Если Telegram не принял такое сообщение или файлы вместе больше 45 МБ, они приходят отдельными сообщениями после ответа. Метка внутри кода (в обратных кавычках или блоке кода) не срабатывает. Отправляются только файлы из этих двух папок, без секретов (`.env`, база и логи бота, `.git`). Файлы хранятся 7 дней (`FILES_KEEP_DAYS`).
|
|
48
|
+
- **Файлы и изображения**: фото или файл (текст, PDF, таблицы и т. д., до 20 МБ) можно отправить боту, подпись становится запросом. Файл сохраняется в `<каталог данных>/uploads/<id пользователя>/`, агент получает путь и читает его своими инструментами. Альбом из нескольких фото или файлов обрабатывается одним запросом. Архивы `.zip`, `.tar`, `.tar.gz`, `.tgz` бот распаковывает рядом (`…_unpacked`, не больше 500 файлов и 100 МБ; небезопасные пути и ссылки пропускаются), агенту передаётся список файлов; `.7z` и `.rar` остаются обычным файлом; изображения агент получает ещё и блоком `image`, если он это поддерживает. В обратную сторону: агент может создать файл и прислать его в чат — он кладёт файл в `<каталог данных>/outbox/<id пользователя>/` (или в папку проекта) и ставит в ответе метку `[[send:путь]]`. Файл появляется прямо в ответе, на месте метки: JPEG и PNG — изображением, остальное — документом. Если Telegram не принял такое сообщение или файлы вместе больше 45 МБ, они приходят отдельными сообщениями после ответа. Метка внутри кода (в обратных кавычках или блоке кода) не срабатывает. Отправляются только файлы из этих двух папок, без секретов (`.env`, база и логи бота, `.git`). Файлы хранятся 7 дней (`FILES_KEEP_DAYS`). Загрузки и распаковка архивов идут по очереди; сообщение, похожее на токен, удаляется и не передаётся агенту.
|
|
49
49
|
- **Режим «диалоги» (темы)**: если боту включены темы в личном чате (@BotFather), каждая тема чата — отдельный диалог с агентом со своим проектом, движком и историей. Можно работать в нескольких темах одновременно, а вернувшись в тему позже — продолжить с того же места: сессия агента возобновляется сама. `/new` создаёт новую тему, название ей даёт агент по первому ответу (с коротким именем проекта в начале); General работает как обычный диалог, а `/project` в нём показывает диалоги выбранного проекта кнопками, открывающими тему. Тема закреплена за своим проектом. Команда, отправленная из общего списка чатов, а не изнутри темы (Telegram сам заводит под такое сообщение новую тему), выполняется в General, а пустая тема удаляется. Режим каждый выбирает сам: `/topics` — «Диалоги» или «Один чат». Одновременно у сотрудника работает до `MAX_AGENTS_PER_USER` агентов (2), у администратора до `ADMIN_MAX_AGENTS` (4); если места нет, выгружается самый давний простаивающий агент этого же пользователя — его диалог продолжится, когда пользователь в него вернётся.
|
|
50
50
|
- **Язык**: бот говорит с пользователем на языке его Telegram (`ru`, `uk` или `en`, для остальных — `DEFAULT_LANG`, по умолчанию английский). Сменить язык можно командой `/language`: выбор важнее языка Telegram. Команды `acpgram` в терминале (мастер настройки, служба, обновление, справка) говорят на языке системы: русский, украинский, в остальных случаях английский; на Windows берётся язык интерфейса системы, а не региональные настройки.
|
|
51
51
|
- **Экран `/start`** с кнопками: проект, движок, модель, новая сессия, прошлые сессии, завершение сессии (у администратора — сотрудники, приглашение, активные сессии).
|
|
@@ -138,7 +138,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
138
138
|
|
|
139
139
|
**Где лежит токен.** По умолчанию — только в базе бота: клонирование, получение и отправку делает бот, а агент работает с репозиторием локально (состояние, сравнение, коммиты, ветки, слияние) и на просьбу отправить изменения направляет пользователя в `/git`. В песочнице токен агенту недоступен совсем. Администратор может выбрать другой режим — `GIT_AGENT_AUTH=1`: вход передаётся и процессу агента, он сам получает и отправляет изменения. Это удобнее, но токен становится виден агенту и может попасть в запрос к модели; включайте его, только если доверяете моделям, с которыми работают сотрудники.
|
|
140
140
|
|
|
141
|
-
**Как бот запускает git.** Репозиторий лежит там, куда пишет агент, а настройки и хуки репозитория умеют запускать программы. Поэтому бот запускает git с отключёнными
|
|
141
|
+
**Как бот запускает git.** Репозиторий лежит там, куда пишет агент, а настройки и хуки репозитория умеют запускать программы. Поэтому бот запускает git с отключёнными хуками, помощниками входа и запросом пароля, без общего и системного конфига (на Linux и macOS), только по HTTPS, а при включённой песочнице — внутри песочницы того же сотрудника. Перед операциями со входом и коммитом проверяется локальный `.git/config`: команды, внешние include, фильтры (кроме Git LFS) и отключённая проверка TLS отклоняются, в ответе показываются только имена параметров. Вход нужен только для клонирования, получения, отправки, смены ветки и запроса на слияние; локальные команды запускаются без него и в настройки репозитория он не пишется. На одну папку репозитория одновременно работает одна операция, а неудавшийся клон не оставляет частичную папку. Остаточный риск: на Windows читается глобальный и системный конфиг, фильтры Git LFS выполняются при операциях, а без песочницы намеренно вредоносный агент мог бы изменить локальный конфиг между проверкой и командой.
|
|
142
142
|
|
|
143
143
|
Подключаются только репозитории по HTTPS с перечисленных сервисов; репозиторий с адресом SSH или с другого сервера бот показывает, но получать и отправлять в него не может.
|
|
144
144
|
|
|
@@ -168,7 +168,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
|
|
|
168
168
|
|
|
169
169
|
- **У каждого свои настройки движка.** Домашняя папка у сотрудника своя, поэтому история сессий, настройки и входы движков у всех раздельные. Движок должен работать без входа, сохранённого в домашней папке учётной записи бота: OpenCode на бесплатных моделях — вообще без ключей, остальные — по ключу API из `.env`. Вход по подписке (`codex login`, вход Google, подписка Claude) в песочнице не виден.
|
|
170
170
|
- **Уровень «Полный» становится безопаснее.** Агент не спрашивает разрешений, но изменить может только пространство своего сотрудника — удобно для тех, кто не хочет разбираться в запросах разрешений.
|
|
171
|
-
- **Администратор работает без
|
|
171
|
+
- **Администратор работает без песочницы**, если не включён `ADMIN_SANDBOX=1`. С этой настройкой его агент тоже изолируется в папках внутри `PROJECTS_ROOT`: сотрудник не сможет оставить в общей папке файл настроек движка, который выполнится с правами бота. Бот один раз предупреждает администратора в чате, если песочница выключена, администратор работает без неё в общей папке или `.env` доступен локальным группам пользователей Windows.
|
|
172
172
|
- **Проверка при старте.** Бот проверяет, что bubblewrap запускается, секреты бота изнутри не видны, а движки в песочнице стартуют. Не работает песочница или движок по умолчанию — бот не запускается и пишет причину. Остальные движки, не запустившиеся в песочнице, сотрудникам не предлагаются. Если движок установлен в нестандартном месте, добавьте его папку в `SANDBOX_RO_PATHS`.
|
|
173
173
|
- **Сессии, начатые до включения песочницы,** в ней не возобновляются — начинается новая.
|
|
174
174
|
- **Ubuntu 24.04 и новее:** пространства имён пользователя могут быть закрыты AppArmor. Если бот при старте сообщает, что песочница не работает, выполните `sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0` (для постоянства — файл в `/etc/sysctl.d/`) или добавьте профиль AppArmor для `bwrap`. В Docker песочница не поддерживается: контейнер отделяет бота от системы, но не сотрудников друг от друга.
|
|
@@ -319,6 +319,8 @@ npm start # первый запуск без .env сам открое
|
|
|
319
319
|
| `PROJECTS_ROOT` | нет | корень проектов: агент выбирает рабочую папку только внутри него (`C:\scripts`, `/home/user/projects`). Без него — любая папка на машине, по умолчанию домашняя |
|
|
320
320
|
| `USER_WORKSPACES` | нет | `1` — личные пространства: каждый сотрудник выбирает проекты только в своей папке `<корень>/<Telegram ID>`, администратор видит весь корень. Нужен `PROJECTS_ROOT`, без него бот не запускается |
|
|
321
321
|
| `AGENT_SANDBOX` | нет | `bwrap` — песочница агента (только Linux, нужен пакет `bubblewrap`): агент сотрудника видит только его папку проектов, его файлы и его домашнюю папку. См. «Песочница агента» |
|
|
322
|
+
| `ADMIN_SANDBOX` | нет | `1` — песочнить также администратора в папках внутри `PROJECTS_ROOT` (только вместе с `AGENT_SANDBOX=bwrap`; по умолчанию выключено) |
|
|
323
|
+
| `AGENT_ENV_HIDE`, `AGENT_ENV_PASS` | нет | дополнительные переменные окружения, которые соответственно скрыть от агента или, наоборот, передать ему (списки через запятую) |
|
|
322
324
|
| `SANDBOX_RO_PATHS` | нет | дополнительные папки, которые песочница видит на чтение (через `:`), — например, место установки движка, если он не запускается в песочнице |
|
|
323
325
|
| `BWRAP_COMMAND` | нет | путь к `bwrap`, если его нет в `PATH` |
|
|
324
326
|
| `GITLAB_URL`, `GITHUB_URL` | нет | адрес своего GitLab и своего GitHub Enterprise (`https://git.example.com`): появляются в `/git` рядом с GitHub и GitLab.com. `GITLAB_NAME`, `GITHUB_NAME` — названия в кнопках (по умолчанию — имя сервера). Не обязательны: администратор добавляет свои серверы и в самом боте (`/git` → «Свои серверы») |
|
|
@@ -347,6 +349,10 @@ npm start # первый запуск без .env сам открое
|
|
|
347
349
|
| `ADMIN_MAX_AGENTS` | нет | то же для администратора (по умолчанию 4) |
|
|
348
350
|
| `IDLE_MINUTES` | нет | закрытие простаивающей сессии, минут (по умолчанию 30) |
|
|
349
351
|
| `AGENT_START_TIMEOUT` | нет | сколько секунд ждать запуска агента, дольше — процесс завершается (по умолчанию 120) |
|
|
352
|
+
| `UPLOADS_QUOTA_MB` | нет | квота каталога загрузок в МБ; `0` (по умолчанию) — без квоты |
|
|
353
|
+
| `TURN_IDLE_MINUTES` | нет | завершать запрос, если агент не присылает обновлений дольше указанного числа минут; `0` (по умолчанию) — таймер выключен |
|
|
354
|
+
| `HISTORY_KEEP_DAYS` | нет | удалять историю запросов и закрытых сессий старше указанного числа дней; `0` (по умолчанию) — не удалять |
|
|
355
|
+
| `LOGS_KEEP` | нет | удалять архивы `data/debug.log.N` старше указанного числа дней; `0` (по умолчанию) — не удалять |
|
|
350
356
|
| `ACPGRAM_DEBUG` | нет | `1` — подробный журнал отправляемого в Telegram в `data/debug.log` (до 5 МБ и один прошлый файл; по умолчанию выключен) |
|
|
351
357
|
| `FILES_DIR` | нет | каталог принятых (`uploads`) и исходящих (`outbox`) файлов (по умолчанию — каталог данных бота) |
|
|
352
358
|
| `FILES_KEEP_DAYS` | нет | сколько дней хранить такие файлы (по умолчанию 7) |
|
|
@@ -432,6 +438,7 @@ src/
|
|
|
432
438
|
projectFiles.mjs файлы проекта в обход агента: безопасная запись и удаление внутри проекта, без ссылок
|
|
433
439
|
filesUi.mjs команда /files: список, создание, загрузка и удаление файлов проекта
|
|
434
440
|
git.mjs команды git бота: клонирование, состояние, получение, отправка, коммит без секретов; безопасный запуск
|
|
441
|
+
gitCtx.mjs общие настройки запуска, выбор аккаунта и блокировки для экранов git
|
|
435
442
|
gitHosts.mjs GitHub и GitLab: профиль и репозитории по токену, вход для git
|
|
436
443
|
gitAccess.mjs аккаунты Git пользователей; что из них получает агент (автор коммитов, вход при GIT_AGENT_AUTH)
|
|
437
444
|
gitUi.mjs команда /git: аккаунты, свои серверы, клонирование, получить / отправить / сохранить
|
package/package.json
CHANGED
package/src/access.mjs
CHANGED
|
@@ -201,6 +201,15 @@ export function allowedModels(userId, engineId) {
|
|
|
201
201
|
return r ? models.filter((m) => r.includes(m.id)) : models;
|
|
202
202
|
}
|
|
203
203
|
|
|
204
|
+
export function modelAllowed(userId, engineId, actualId) {
|
|
205
|
+
const restriction = modelRestriction(userId, engineId);
|
|
206
|
+
if (!restriction || !actualId) return true;
|
|
207
|
+
const actual = String(actualId).toLowerCase();
|
|
208
|
+
const models = allowedModels(userId, engineId);
|
|
209
|
+
const ids = models.length ? models.flatMap((m) => [m.id, m.name, m.short]) : restriction;
|
|
210
|
+
return ids.some((id) => id != null && String(id).toLowerCase() === actual);
|
|
211
|
+
}
|
|
212
|
+
|
|
204
213
|
/**
|
|
205
214
|
* Включает или выключает модель в ограничении сотрудника. Если включены все — ограничение снимается.
|
|
206
215
|
* Последнюю разрешённую модель выключить нельзя. Возвращает {ok, restriction}.
|
package/src/bot.mjs
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
// Telegram-интерфейс к AI-агентам разработки (Gemini CLI, Claude Code, Antigravity CLI, Codex, OpenCode) через ACP.
|
|
2
2
|
// Доступ: главный администратор (ALLOWED_USER_ID) и сотрудники, которым он выдал доступ. Остальным бот не отвечает,
|
|
3
3
|
// кроме запроса доступа администратору.
|
|
4
|
+
import { rmSync } from 'node:fs';
|
|
4
5
|
import { DEFAULT_ENGINE, agentEnv, checkEngines, isRequired, setAvailability, setSandboxBroken } from './engines.mjs';
|
|
5
6
|
import { SANDBOX, checkInSandbox, probeSandbox } from './sandbox.mjs';
|
|
6
7
|
import { handleEngine, onEngineCallback } from './engineUi.mjs';
|
|
7
8
|
import { choiceName, effectiveSelection, killProbes, refreshCatalogs } from './access.mjs';
|
|
8
9
|
import { handleModel, onModelCallback } from './modelUi.mjs';
|
|
9
|
-
import { ADMIN_ID, IDLE_MINUTES, LEVEL_KEYS, MAX_AGENTS, botInfo, db, langOf, log, noteTgLang, say, setLang } from './ctx.mjs';
|
|
10
|
+
import { ADMIN_ID, DATA_DIR, HISTORY_KEEP_DAYS, IDLE_MINUTES, LEVEL_KEYS, LOGS_KEEP_DAYS, MAX_AGENTS, botInfo, db, langOf, log, noteTgLang, say, setLang } from './ctx.mjs';
|
|
10
11
|
import { adminCommand, handleUnknownUser, onAdminCallback, welcomeNote } from './admin.mjs';
|
|
11
12
|
import { LANGS, LANG_CODES, LANG_PICK, LOCALES, errText, normLang, t } from './i18n.mjs';
|
|
12
13
|
import { HOME, ROOT, USER_WORKSPACES } from './projects.mjs';
|
|
@@ -16,7 +17,7 @@ import { checkGit, gitCommand } from './git.mjs';
|
|
|
16
17
|
import { GIT_AGENT_AUTH, tokenReminders } from './gitAccess.mjs';
|
|
17
18
|
import { handleGit, onGitCallback, onGitInput } from './gitUi.mjs';
|
|
18
19
|
import { handleSessions, onSessionCallback } from './sessionsUi.mjs';
|
|
19
|
-
import { dropPermissions, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
|
|
20
|
+
import { ADMIN_SANDBOX, dropPermissions, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
|
|
20
21
|
import { handleTopics, newTopic, onTopicsCallback } from './topicsUi.mjs';
|
|
21
22
|
import { deleteTopic, isAutoTopicCommand, topicInfoOf } from './topics.mjs';
|
|
22
23
|
import { setSyncKill } from './acp.mjs';
|
|
@@ -28,6 +29,18 @@ import { dropQueue, enqueue, onAskCallback, onPermissionCallback, onQueueCallbac
|
|
|
28
29
|
import { nearCommand, quoteOf, unsupportedKind } from './incoming.mjs';
|
|
29
30
|
import { onWidgetQuery } from './widgetsUi.mjs';
|
|
30
31
|
import { DOCS_URL, docsMenuButton, helpMarkup, startView } from './ui.mjs';
|
|
32
|
+
import { positiveEnv } from './app.mjs';
|
|
33
|
+
import { createQueue } from './queue.mjs';
|
|
34
|
+
import { directorySize, fitsUpload, freeBytes } from './quota.mjs';
|
|
35
|
+
import { forceStopAfter } from './forceStop.mjs';
|
|
36
|
+
import { looksLikeSecret } from './pending.mjs';
|
|
37
|
+
import { cleanupLogs } from './log.mjs';
|
|
38
|
+
import { maybeNotifySafety } from './warnings.mjs';
|
|
39
|
+
|
|
40
|
+
const UPLOADS_QUOTA_MB = positiveEnv('UPLOADS_QUOTA_MB', 0);
|
|
41
|
+
const MIN_FREE_MB = positiveEnv('MIN_FREE_MB', 100);
|
|
42
|
+
const receiveQueue = createQueue(1);
|
|
43
|
+
const reservedUploads = new Map();
|
|
31
44
|
|
|
32
45
|
if (!process.env.TELEGRAM_BOT_TOKEN || !ADMIN_ID) {
|
|
33
46
|
console.error('Нужны TELEGRAM_BOT_TOKEN и ALLOWED_USER_ID (см. .env)');
|
|
@@ -97,6 +110,7 @@ function stopCommand(st) {
|
|
|
97
110
|
const queued = dropQueue(st); // «стоп» отменяет и сообщение, которое ждало своей очереди
|
|
98
111
|
if (!st.busy) return queued ? undefined : say(st.to, t('stop.none', langOf(st.userId)));
|
|
99
112
|
st.agent?.cancel();
|
|
113
|
+
forceStopAfter(st);
|
|
100
114
|
dropPermissions(st);
|
|
101
115
|
}
|
|
102
116
|
|
|
@@ -169,6 +183,10 @@ async function handleText(st, text, { quote = null, messageId = null } = {}) {
|
|
|
169
183
|
if (await onFileInput(st, text, { messageId })) return;
|
|
170
184
|
// бот ждёт токен доступа к GitHub / GitLab, строку поиска репозитория или описание изменений (/git)
|
|
171
185
|
if (await onGitInput(st, text, { messageId })) return;
|
|
186
|
+
if (looksLikeSecret(text)) {
|
|
187
|
+
if (messageId) await tg('deleteMessage', { chat_id: st.chatId, message_id: messageId }).catch(() => {});
|
|
188
|
+
return say(st.to, t('secret.detected', lang));
|
|
189
|
+
}
|
|
172
190
|
if (name && !st.agent?.commands?.has(name)) {
|
|
173
191
|
const guess = nearCommand(name, COMMANDS.filter((c) => !c.admin || isAdmin(st.userId)).map((c) => c.name));
|
|
174
192
|
if (guess) {
|
|
@@ -191,15 +209,32 @@ async function onRawCommandCallback(st, cb) {
|
|
|
191
209
|
return sendToAgent(st, text);
|
|
192
210
|
}
|
|
193
211
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
212
|
+
const reservedFor = (userId) => reservedUploads.get(String(userId)) ?? 0;
|
|
213
|
+
const reserveUpload = (userId, bytes) => reservedUploads.set(String(userId), reservedFor(userId) + bytes);
|
|
214
|
+
const releaseUpload = (userId, bytes) => reservedUploads.set(String(userId), Math.max(0, reservedFor(userId) - bytes));
|
|
215
|
+
|
|
216
|
+
function dropReceived(files) {
|
|
217
|
+
for (const f of files) {
|
|
218
|
+
try {
|
|
219
|
+
if (f.unpacked?.dir) rmSync(f.unpacked.dir, { recursive: true, force: true });
|
|
220
|
+
rmSync(f.path, { force: true });
|
|
221
|
+
} catch (e) {
|
|
222
|
+
log('удаление непринятого файла:', e.message);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
198
227
|
async function receiveFile(st, meta, lang) {
|
|
199
228
|
if (meta.size > MAX_FILE_BYTES) {
|
|
200
229
|
await say(st.to, t('file.tooBig', lang));
|
|
201
230
|
return null;
|
|
202
231
|
}
|
|
232
|
+
const dir = uploadsDir(st.userId);
|
|
233
|
+
if (!fitsUpload({ usedBytes: directorySize(dir), incomingBytes: meta.size, limitMb: UPLOADS_QUOTA_MB, free: freeBytes(dir), minFreeMb: MIN_FREE_MB, reservedBytes: reservedFor(st.userId) })) {
|
|
234
|
+
await say(st.to, t('file.quota', lang));
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
reserveUpload(st.userId, meta.size);
|
|
203
238
|
let data;
|
|
204
239
|
try {
|
|
205
240
|
data = await downloadFile(meta.id);
|
|
@@ -207,22 +242,23 @@ async function receiveFile(st, meta, lang) {
|
|
|
207
242
|
log('скачивание файла:', e.message, '| пользователь', st.userId);
|
|
208
243
|
await say(st.to, t('file.downloadFail', lang, { msg: errText(e, lang) }));
|
|
209
244
|
return null;
|
|
245
|
+
} finally {
|
|
246
|
+
releaseUpload(st.userId, meta.size);
|
|
210
247
|
}
|
|
211
248
|
if (data.length > MAX_FILE_BYTES) {
|
|
212
249
|
await say(st.to, t('file.tooBig', lang));
|
|
213
250
|
return null;
|
|
214
251
|
}
|
|
215
|
-
const path = saveUpload(
|
|
252
|
+
const path = saveUpload(dir, meta.name, data);
|
|
216
253
|
log('файл принят', st.userId, path, `${data.length} Б`);
|
|
217
254
|
const file = { path, name: meta.name, mime: meta.mime, size: data.length };
|
|
218
|
-
if (isImageMime(meta.mime) && data.length <= IMAGE_BLOCK_MAX) file.data = data;
|
|
255
|
+
if (isImageMime(meta.mime) && data.length <= IMAGE_BLOCK_MAX) file.data = data;
|
|
219
256
|
const kind = archiveKind(meta.name);
|
|
220
257
|
if (kind) {
|
|
221
|
-
|
|
222
|
-
const dir = `${path}_unpacked`;
|
|
258
|
+
const unpacked = `${path}_unpacked`;
|
|
223
259
|
try {
|
|
224
|
-
file.unpacked = { dir, ...(await extractArchiveAsync(data, kind,
|
|
225
|
-
log('архив распакован', st.userId,
|
|
260
|
+
file.unpacked = { dir: unpacked, ...(await extractArchiveAsync(data, kind, unpacked)) };
|
|
261
|
+
log('архив распакован', st.userId, unpacked, `${file.unpacked.files.length} файлов, пропущено ${file.unpacked.skipped}`);
|
|
226
262
|
} catch (e) {
|
|
227
263
|
log('архив не распакован:', e.reason ?? e.message, '| пользователь', st.userId);
|
|
228
264
|
await say(st.to, t('file.archiveSkipped', lang, { name: meta.name, why: t(`file.archiveWhy.${e.reason ?? 'corrupt'}`, lang) }));
|
|
@@ -231,20 +267,32 @@ async function receiveFile(st, meta, lang) {
|
|
|
231
267
|
return file;
|
|
232
268
|
}
|
|
233
269
|
|
|
234
|
-
/**
|
|
235
|
-
* Фото или файлы от пользователя (одно сообщение или целый альбом): скачиваем, сохраняем и передаём агенту
|
|
236
|
-
* вместе с подписью (первая найденная подпись). Изображения уходят блоком image (если агент это умеет), остальное — путём.
|
|
237
|
-
*/
|
|
238
270
|
async function processAttachments(st, msgs) {
|
|
239
271
|
const lang = langOf(st.userId);
|
|
272
|
+
if (st.receiving) return say(st.to, t('file.receiving', lang));
|
|
240
273
|
if (st.busy) return say(st.to, t('busy.running', lang), { reply_markup: stopMarkup(lang) });
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
274
|
+
st.receiving = true;
|
|
275
|
+
try {
|
|
276
|
+
const files = await receiveQueue.add(async () => {
|
|
277
|
+
const out = [];
|
|
278
|
+
for (const msg of msgs) {
|
|
279
|
+
const meta = describeAttachment(msg);
|
|
280
|
+
if (!meta) continue;
|
|
281
|
+
const file = await receiveFile(st, meta, lang);
|
|
282
|
+
if (file) out.push(file);
|
|
283
|
+
}
|
|
284
|
+
return out;
|
|
285
|
+
});
|
|
286
|
+
if (!files.length) return;
|
|
287
|
+
if (st.busy) {
|
|
288
|
+
dropReceived(files);
|
|
289
|
+
return say(st.to, t('busy.running', lang), { reply_markup: stopMarkup(lang) });
|
|
290
|
+
}
|
|
291
|
+
const caption = msgs.map((m) => m.caption?.trim()).find(Boolean) ?? '';
|
|
292
|
+
return await runTurn(st, caption, { files });
|
|
293
|
+
} finally {
|
|
294
|
+
st.receiving = false;
|
|
295
|
+
}
|
|
248
296
|
}
|
|
249
297
|
|
|
250
298
|
// альбом приходит отдельными сообщениями с общим media_group_id: собираем и обрабатываем одним запросом
|
|
@@ -411,7 +459,7 @@ async function setupSandbox(checks) {
|
|
|
411
459
|
${probe.hint}`);
|
|
412
460
|
process.exit(1);
|
|
413
461
|
}
|
|
414
|
-
log(
|
|
462
|
+
log(`песочница агентов включена (bubblewrap): агент видит только папку проектов сотрудника, его файлы и его домашнюю папку; администратор ${ADMIN_SANDBOX ? 'песочнится в папках сотрудников (ADMIN_SANDBOX=1)' : 'работает без песочницы'}`);
|
|
415
463
|
const usable = checks.filter((r) => r.ok || r.timeout);
|
|
416
464
|
const inside = await Promise.all(usable.map((r) => checkInSandbox(r.command, r.engine.versionArgs, agentEnv(r.engine))));
|
|
417
465
|
const broken = [];
|
|
@@ -430,6 +478,10 @@ ${probe.hint}`);
|
|
|
430
478
|
}
|
|
431
479
|
|
|
432
480
|
async function main() {
|
|
481
|
+
if (SANDBOX && !ROOT) {
|
|
482
|
+
console.error('AGENT_SANDBOX=bwrap: задайте PROJECTS_ROOT — без корня сотрудник может выбрать проектом любую папку сервера');
|
|
483
|
+
process.exit(1);
|
|
484
|
+
}
|
|
433
485
|
// все движки проверяем параллельно; без движка по умолчанию (DEFAULT_ENGINE) бот не запускается, остальные — по возможности
|
|
434
486
|
const asked = process.env.DEFAULT_ENGINE?.trim().toLowerCase();
|
|
435
487
|
if (asked && asked !== DEFAULT_ENGINE) log(`⚠️ DEFAULT_ENGINE=${asked} не распознан (gemini | claude | agy | codex | opencode), используется ${DEFAULT_ENGINE}`);
|
|
@@ -475,6 +527,7 @@ async function main() {
|
|
|
475
527
|
: 'темы в личном чате выключены — режим «диалоги» недоступен',
|
|
476
528
|
);
|
|
477
529
|
await setupCommands().catch((e) => log('настройка меню:', e.message));
|
|
530
|
+
maybeNotifySafety();
|
|
478
531
|
// пропускаем накопившиеся до запуска обновления
|
|
479
532
|
const old = await tg('getUpdates', { offset: -1, timeout: 0 });
|
|
480
533
|
let offset = old.length ? old[old.length - 1].update_id + 1 : 0;
|
|
@@ -487,6 +540,10 @@ async function main() {
|
|
|
487
540
|
} catch (e) {
|
|
488
541
|
log('очистка файлов:', e.message);
|
|
489
542
|
}
|
|
543
|
+
const h = db.cleanupHistory(HISTORY_KEEP_DAYS);
|
|
544
|
+
if (h) log(`удалено старых записей истории: ${h}`);
|
|
545
|
+
const l = cleanupLogs(DATA_DIR, LOGS_KEEP_DAYS);
|
|
546
|
+
if (l) log(`удалено старых файлов журнала: ${l}`);
|
|
490
547
|
};
|
|
491
548
|
sweep();
|
|
492
549
|
setInterval(sweep, 24 * 3600_000).unref();
|
package/src/cli-i18n.mjs
CHANGED
|
@@ -190,6 +190,11 @@ https://github.com/{repo}`,
|
|
|
190
190
|
ru: 'Песочница агента (Linux, bubblewrap): агент сотрудника видит только его папку проектов, его файлы и его домашнюю папку',
|
|
191
191
|
uk: 'Пісочниця агента (Linux, bubblewrap): агент співробітника бачить лише його теку проєктів, його файли та його домашню теку',
|
|
192
192
|
},
|
|
193
|
+
'env.c.adminSandbox': {
|
|
194
|
+
en: 'ADMIN_SANDBOX=1: sandbox the administrator too when working in folders writable by teammates',
|
|
195
|
+
ru: 'ADMIN_SANDBOX=1: песочнить также администратора в папках, куда пишут сотрудники',
|
|
196
|
+
uk: 'ADMIN_SANDBOX=1: пісочнити також адміністратора в теках, куди пишуть співробітники',
|
|
197
|
+
},
|
|
193
198
|
'env.c.engine': { en: 'Default engine: gemini | claude | agy | codex | opencode', ru: 'Движок по умолчанию: gemini | claude | agy | codex | opencode', uk: 'Рушій за замовчуванням: gemini | claude | agy | codex | opencode' },
|
|
194
199
|
'env.c.keys': { en: 'API keys are passed to the agents through the bot environment', ru: 'Ключи API передаются агентам через окружение бота', uk: 'Ключі API передаються агентам через оточення бота' },
|
|
195
200
|
'env.rest': { en: 'Other settings', ru: 'Прочие настройки', uk: 'Інші налаштування' },
|
|
@@ -258,9 +263,9 @@ https://github.com/{repo}`,
|
|
|
258
263
|
},
|
|
259
264
|
'setup.wsAsk': { en: ' Give each employee a personal workspace?', ru: ' Выдать каждому сотруднику личное пространство?', uk: ' Видати кожному співробітнику особистий простір?' },
|
|
260
265
|
'setup.sbNote': {
|
|
261
|
-
en: ' Agent sandbox: a teammate’s agent runs isolated (bubblewrap) and cannot read the bot settings, its database or other people’s folders.
|
|
262
|
-
ru: ' Песочница агента: агент сотрудника запускается изолированно (bubblewrap) и не может прочитать настройки бота, его базу и чужие папки.
|
|
263
|
-
uk: ' Пісочниця агента: агент співробітника запускається ізольовано (bubblewrap) і не може прочитати налаштування бота, його базу та чужі теки.
|
|
266
|
+
en: ' Agent sandbox: a teammate’s agent runs isolated (bubblewrap) and cannot read the bot settings, its database or other people’s folders. By default the administrator works without it; ADMIN_SANDBOX=1 sandboxes them in shared folders too.',
|
|
267
|
+
ru: ' Песочница агента: агент сотрудника запускается изолированно (bubblewrap) и не может прочитать настройки бота, его базу и чужие папки. По умолчанию администратор работает без неё; ADMIN_SANDBOX=1 песочнит и его в общих папках.',
|
|
268
|
+
uk: ' Пісочниця агента: агент співробітника запускається ізольовано (bubblewrap) і не може прочитати налаштування бота, його базу та чужі теки. Типово адміністратор працює без неї; ADMIN_SANDBOX=1 пісочнить і його у спільних теках.',
|
|
264
269
|
},
|
|
265
270
|
'setup.sbMissing': {
|
|
266
271
|
en: 'bubblewrap is not installed — the sandbox is off. Install it (apt install bubblewrap) and run the setup again to turn it on',
|
|
@@ -269,6 +274,14 @@ https://github.com/{repo}`,
|
|
|
269
274
|
},
|
|
270
275
|
'setup.sbAsk': { en: ' Run teammates’ agents in the sandbox?', ru: ' Запускать агентов сотрудников в песочнице?', uk: ' Запускати агентів співробітників у пісочниці?' },
|
|
271
276
|
'setup.sbOn': { en: 'the agent sandbox is on', ru: 'песочница агента включена', uk: 'пісочницю агента увімкнено' },
|
|
277
|
+
'setup.adminSbNote': {
|
|
278
|
+
en: ' The administrator is usually unrestricted. In a shared root a teammate can leave an engine config that runs with bot rights. Sandbox the administrator there too?',
|
|
279
|
+
ru: ' Администратор обычно работает без ограничений. В общем корне сотрудник может оставить файл настроек движка, который выполнится с правами бота. Песочнить администратора в таких папках?',
|
|
280
|
+
uk: ' Адміністратор зазвичай працює без обмежень. У спільному корні співробітник може залишити файл налаштувань движка, який виконається з правами бота. Пісочнити адміністратора в таких теках?',
|
|
281
|
+
},
|
|
282
|
+
'setup.adminSbAsk': { en: ' Sandbox the administrator in shared folders?', ru: ' Песочнить администратора в общих папках?', uk: ' Пісочнити адміністратора у спільних теках?' },
|
|
283
|
+
'setup.adminSbOn': { en: 'ADMIN_SANDBOX=1: the administrator is sandboxed in shared folders', ru: 'ADMIN_SANDBOX=1: администратор песочнится в общих папках', uk: 'ADMIN_SANDBOX=1: адміністратор пісочниться у спільних теках' },
|
|
284
|
+
'setup.adminSbOff': { en: 'the administrator works without a sandbox', ru: 'администратор работает без песочницы', uk: 'адміністратор працює без пісочниці' },
|
|
272
285
|
'setup.wsOn': { en: 'personal workspaces are on', ru: 'личные пространства включены', uk: 'особисті простори увімкнено' },
|
|
273
286
|
'setup.s4': { en: 'AI engines (checking what is installed)', ru: 'AI-движки (проверяю установленные)', uk: 'AI-рушії (перевіряю встановлені)' },
|
|
274
287
|
'setup.engineOk': { en: '{label} {version} — {path}', ru: '{label} {version} — {path}', uk: '{label} {version} — {path}' },
|
|
@@ -469,9 +482,9 @@ https://github.com/{repo}`,
|
|
|
469
482
|
uk: ' ❌ Запустіть у терміналі (запитає обліковий запис) або додайте --system, щоб служба працювала від LocalSystem.',
|
|
470
483
|
},
|
|
471
484
|
'svc.localSystem': {
|
|
472
|
-
en: ' ⚠️ The service will run as LocalSystem: the agents must be signed in for this account (API keys in .env).',
|
|
473
|
-
ru: ' ⚠️ Служба будет работать от LocalSystem: агенты должны быть авторизованы для этой учётной записи (ключи API в .env).',
|
|
474
|
-
uk: ' ⚠️ Служба працюватиме від LocalSystem: агенти мають бути авторизовані для цього облікового запису (ключі API в .env).',
|
|
485
|
+
en: ' ⚠️ The service will run as System (LocalSystem): the agents will also get SYSTEM rights, not just the bot. They must be signed in for this account (API keys in .env). Use a separate non-privileged account instead.',
|
|
486
|
+
ru: ' ⚠️ Служба будет работать от системы (LocalSystem): агенты тоже получат права SYSTEM, а не только бот. Они должны быть авторизованы для этой учётной записи (ключи API в .env). Лучше использовать отдельную непривилегированную учётную запись.',
|
|
487
|
+
uk: ' ⚠️ Служба працюватиме від системи (LocalSystem): агенти також отримають права SYSTEM, а не лише бот. Вони мають бути авторизовані для цього облікового запису (ключі API в .env). Краще використати окремий непривілейований обліковий запис.',
|
|
475
488
|
},
|
|
476
489
|
'svc.createFailed': { en: ' ❌ Could not create the service: {text}.', ru: ' ❌ Не удалось создать службу: {text}.', uk: ' ❌ Не вдалося створити службу: {text}.' },
|
|
477
490
|
'svc.checkPassword': {
|
package/src/clip.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export function clipText(value, head, tail, marker = '…') {
|
|
2
|
+
const s = String(value);
|
|
3
|
+
if (s.length <= head + tail) return s;
|
|
4
|
+
return `${s.slice(0, head)}${marker}${tail > 0 ? s.slice(-tail) : ''}`;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function clipLogLine(value, max = 2000) {
|
|
8
|
+
const s = String(value ?? '');
|
|
9
|
+
const head = Math.floor(max / 2);
|
|
10
|
+
const tail = max - head;
|
|
11
|
+
return s
|
|
12
|
+
.split(/\r?\n/)
|
|
13
|
+
.map((line) => (line.length > max ? clipText(line, head, tail, ' … обрезано … ') : line))
|
|
14
|
+
.join('\n');
|
|
15
|
+
}
|
package/src/ctx.mjs
CHANGED
|
@@ -4,6 +4,8 @@ import { appendFile, rename, stat } from 'node:fs/promises';
|
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { DATA_DIR, positiveEnv } from './app.mjs';
|
|
6
6
|
import { openDb } from './db.mjs';
|
|
7
|
+
import { createPendingStore } from './pending.mjs';
|
|
8
|
+
import { protectWindowsPath } from './protect.mjs';
|
|
7
9
|
import { normLang, pickLang, t } from './i18n.mjs';
|
|
8
10
|
import { log } from './log.mjs';
|
|
9
11
|
|
|
@@ -56,8 +58,11 @@ export { log }; // журнал — log.mjs (им же пользуются acp,
|
|
|
56
58
|
// ACPGRAM_DEBUG=1: черновик пишется каждую секунду, без выключателя и ротации файл рос бесконечно.
|
|
57
59
|
// Запись асинхронная, по очереди; больше DEBUG_MAX_BYTES — файл переименовывается в debug.log.1 (хранится один прошлый).
|
|
58
60
|
mkdirSync(DATA_DIR, { recursive: true });
|
|
61
|
+
protectWindowsPath(DATA_DIR, { directory: true });
|
|
59
62
|
export const DEBUG = process.env.ACPGRAM_DEBUG === '1';
|
|
60
63
|
export const DEBUG_MAX_BYTES = 5 * 1024 * 1024;
|
|
64
|
+
export const HISTORY_KEEP_DAYS = positiveEnv('HISTORY_KEEP_DAYS', 0);
|
|
65
|
+
export const LOGS_KEEP_DAYS = positiveEnv('LOGS_KEEP', 0);
|
|
61
66
|
export const createDebugLog = (path, maxBytes = DEBUG_MAX_BYTES) => {
|
|
62
67
|
let queue = Promise.resolve();
|
|
63
68
|
let size = null;
|
|
@@ -83,6 +88,7 @@ export const dbg = (kind, text) => debugLog?.(kind, text);
|
|
|
83
88
|
|
|
84
89
|
// база работы бота: сессии, запросы, вызовы инструментов, разрешения, ответы, сотрудники
|
|
85
90
|
export const db = openDb(join(DATA_DIR, 'bot.db'));
|
|
91
|
+
export const pending = createPendingStore(db);
|
|
86
92
|
|
|
87
93
|
/** Сообщение пользователю: to — id чата или {chat_id, message_thread_id} (тема), обычно st.to. */
|
|
88
94
|
export const say = (to, text, extra = {}) => tg('sendMessage', { ...dest(to), text, ...extra }).catch((e) => log('sendMessage:', e.message));
|
package/src/db.mjs
CHANGED
|
@@ -1,16 +1,29 @@
|
|
|
1
1
|
// База работы бота (SQLite): сессии, запросы пользователя, вызовы инструментов, разрешения, ответы модели.
|
|
2
2
|
// Используется встроенный в Node модуль node:sqlite — без внешних зависимостей.
|
|
3
3
|
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
-
import { mkdirSync } from 'node:fs';
|
|
4
|
+
import { chmodSync, existsSync, mkdirSync } from 'node:fs';
|
|
5
5
|
import { dirname } from 'node:path';
|
|
6
6
|
import { logError } from './log.mjs';
|
|
7
7
|
|
|
8
8
|
const now = () => new Date().toISOString();
|
|
9
9
|
const cut = (s, n) => (s == null ? null : String(s).slice(0, n));
|
|
10
10
|
|
|
11
|
+
const securePath = (path, mode) => {
|
|
12
|
+
if (process.platform === 'win32' || !existsSync(path)) return;
|
|
13
|
+
try {
|
|
14
|
+
chmodSync(path, mode);
|
|
15
|
+
} catch (e) {
|
|
16
|
+
logError('не удалось ограничить права:', path, e.message);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
11
20
|
export function openDb(path = 'data/bot.db') {
|
|
12
|
-
|
|
21
|
+
const dir = dirname(path);
|
|
22
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
13
23
|
const db = new DatabaseSync(path);
|
|
24
|
+
securePath(dir, 0o700);
|
|
25
|
+
securePath(path, 0o600);
|
|
26
|
+
for (const suffix of ['-wal', '-shm']) securePath(path + suffix, 0o600);
|
|
14
27
|
db.exec(`
|
|
15
28
|
PRAGMA journal_mode = WAL;
|
|
16
29
|
-- при WAL безопасно: база не повреждается, после сбоя питания теряются лишь последние записи журнала;
|
|
@@ -210,6 +223,8 @@ export function openDb(path = 'data/bot.db') {
|
|
|
210
223
|
GROUP BY s.acp_session_id ORDER BY last_at DESC LIMIT ?`,
|
|
211
224
|
),
|
|
212
225
|
getSetting: db.prepare('SELECT value FROM settings WHERE key = ?'),
|
|
226
|
+
allSettings: db.prepare('SELECT key, value FROM settings'),
|
|
227
|
+
deleteGitAccounts: db.prepare('DELETE FROM git_accounts WHERE user_id = ?'),
|
|
213
228
|
setSetting: db.prepare('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'),
|
|
214
229
|
startSession: db.prepare('INSERT INTO sessions (acp_session_id, user_id, chat_id, mode, cwd, started_at, engine) VALUES (?,?,?,?,?,?,?)'),
|
|
215
230
|
endSession: db.prepare('UPDATE sessions SET ended_at = ?, end_reason = ? WHERE id = ? AND ended_at IS NULL'),
|
|
@@ -232,6 +247,10 @@ export function openDb(path = 'data/bot.db') {
|
|
|
232
247
|
),
|
|
233
248
|
addPermission: db.prepare('INSERT INTO permissions (request_id, tool_call_id, title, options, asked_at) VALUES (?,?,?,?,?)'),
|
|
234
249
|
answerPermission: db.prepare('UPDATE permissions SET chosen_option = ?, outcome = ?, answered_at = ? WHERE id = ?'),
|
|
250
|
+
cleanupPermissions: db.prepare('DELETE FROM permissions WHERE asked_at < ?'),
|
|
251
|
+
cleanupTools: db.prepare('DELETE FROM tool_calls WHERE started_at < ?'),
|
|
252
|
+
cleanupRequests: db.prepare('DELETE FROM requests WHERE started_at < ?'),
|
|
253
|
+
cleanupSessions: db.prepare('DELETE FROM sessions WHERE started_at < ? AND ended_at IS NOT NULL'),
|
|
235
254
|
// расход по пользователям с момента since: запросы, токены, стоимость (что прислали агенты)
|
|
236
255
|
usageSummary: db.prepare(
|
|
237
256
|
`SELECT s.user_id AS user_id, COUNT(r.id) AS requests, COALESCE(SUM(r.total_tokens), 0) AS tokens, SUM(r.cost_usd) AS cost
|
|
@@ -281,7 +300,11 @@ export function openDb(path = 'data/bot.db') {
|
|
|
281
300
|
upsertUser: safe((u) => q.upsertUser.run(u.user_id, u.username ?? null, u.first_name ?? null, u.level, u.added_by ?? null, now())),
|
|
282
301
|
setUserLevel: safe((id, level) => q.setUserLevel.run(level, id)),
|
|
283
302
|
touchUser: safe((id, username, firstName) => q.touchUser.run(username ?? null, firstName ?? null, id)),
|
|
284
|
-
revokeUser: safe((id) =>
|
|
303
|
+
revokeUser: safe((id) => {
|
|
304
|
+
const result = q.revokeUser.run(now(), id);
|
|
305
|
+
if (result.changes) q.deleteGitAccounts.run(id);
|
|
306
|
+
return result;
|
|
307
|
+
}),
|
|
285
308
|
createInvite: safe((code, level, createdBy, expiresAt) => q.createInvite.run(code, level, createdBy, now(), expiresAt)),
|
|
286
309
|
/** Гасит приглашение и возвращает его уровень; null — если код неверный, уже использован или просрочен. */
|
|
287
310
|
consumeInvite: safe((code, userId) => {
|
|
@@ -297,6 +320,7 @@ export function openDb(path = 'data/bot.db') {
|
|
|
297
320
|
usageSummary: (since) => safe(() => q.usageSummary.all(since))() ?? [],
|
|
298
321
|
// --- прочее ---
|
|
299
322
|
getSetting: safe((key) => q.getSetting.get(key)?.value ?? null),
|
|
323
|
+
allSettings: safe(() => q.allSettings.all() ?? []),
|
|
300
324
|
setSetting: safe((key, value) => q.setSetting.run(key, value)),
|
|
301
325
|
startSession: safe((acpSessionId, userId, chatId, mode, cwd, engine) =>
|
|
302
326
|
Number(q.startSession.run(acpSessionId, userId, chatId, mode ?? null, cwd ?? null, now(), engine ?? null).lastInsertRowid)),
|
|
@@ -318,6 +342,20 @@ export function openDb(path = 'data/bot.db') {
|
|
|
318
342
|
permissionAsked: safe((requestId, toolCallId, title, options) =>
|
|
319
343
|
Number(q.addPermission.run(requestId, toolCallId ?? null, cut(title, 2000), JSON.stringify(options), now()).lastInsertRowid)),
|
|
320
344
|
permissionAnswered: safe((id, chosen, outcome) => id && q.answerPermission.run(chosen ?? null, outcome, now(), id)),
|
|
345
|
+
cleanupHistory: safe((days) => {
|
|
346
|
+
if (!(Number(days) > 0)) return 0;
|
|
347
|
+
const before = new Date(Date.now() - Number(days) * 86400_000).toISOString();
|
|
348
|
+
db.exec('BEGIN');
|
|
349
|
+
try {
|
|
350
|
+
const removed = q.cleanupPermissions.run(before).changes + q.cleanupTools.run(before).changes +
|
|
351
|
+
q.cleanupRequests.run(before).changes + q.cleanupSessions.run(before).changes;
|
|
352
|
+
db.exec('COMMIT');
|
|
353
|
+
return removed;
|
|
354
|
+
} catch (e) {
|
|
355
|
+
db.exec('ROLLBACK');
|
|
356
|
+
throw e;
|
|
357
|
+
}
|
|
358
|
+
}),
|
|
321
359
|
// --- темы ---
|
|
322
360
|
getTopic: safe((userId, threadId) => q.getTopic.get(userId, threadId) ?? null),
|
|
323
361
|
/** Создаёт тему, если её нет, и обновляет переданные поля (name, named, project, engine, acpSessionId); остальные не трогает. */
|