acpgram 1.24.0 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -50,6 +50,7 @@ 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.
53
54
  - **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
55
  - **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
56
  - **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 +185,7 @@ In the container the agent sees only the mounted projects folder (`PROJECTS_DIR`
184
185
  | `/engine [gemini, claude, agy, codex, opencode]` | everyone | choose the engine |
185
186
  | `/model [name]` | everyone | choose the model and reasoning level; with a name — search for a model (`/model sonnet`) |
186
187
  | `/new` | everyone | new session |
188
+ | `/files` | everyone | project files: list, create, upload and delete — bypassing the agent |
187
189
  | `/sessions` | everyone | resume a previous session in this project |
188
190
  | `/stop` | everyone | stop the running request |
189
191
  | `/close`, `/exit` | everyone | close the session and unload the agent process |
@@ -207,6 +209,19 @@ OpenCode has only two modes (`plan` and `build`); what the agent may do is set b
207
209
 
208
210
  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
211
 
212
+ ### Project files and secrets
213
+
214
+ 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.
215
+
216
+ - **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.
217
+ - **"📝 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.
218
+ - **"⬆️ 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.
219
+ - **Delete** — from the file card, with a confirmation. An existing file is replaced only after a "Replace?" question.
220
+ - **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.
221
+ - **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.
222
+
223
+ What this gives and what it does not. The secret does not get into a model request *from the user*. The file itself stays available to the agent — otherwise the applications it writes and runs could not use it. So that the agent does not read the values into the conversation by itself, the bot regularly reminds it: do not open or print files with secrets, refer to settings by name, and send the user to `/files` for a missing value. This is an instruction, not a ban: for especially sensitive data use a model from a provider that does not train on requests.
224
+
210
225
  ### Personal workspaces
211
226
 
212
227
  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.
@@ -218,9 +233,33 @@ By default all teammates browse the same projects root. `USER_WORKSPACES=1` (tog
218
233
  - Projects a teammate selected before the mode was turned on and that lie outside their folder are reset to their workspace. The bot never moves or deletes the folders themselves, including when access is revoked.
219
234
  - Before every agent start the bot checks that the project folder exists and lies inside the teammate's workspace; otherwise the agent is not started.
220
235
 
221
- Personal workspaces limit which working folder can be chosen in the bot. They do not isolate the agent process itself — see the note below.
236
+ Personal workspaces limit which working folder can be chosen in the bot. The agent process itself is isolated by the sandbox (Linux, below); without it the note at the end of this section applies.
237
+
238
+ ### Agent sandbox (Linux)
239
+
240
+ `AGENT_SANDBOX=bwrap` runs each teammate's agent isolated with [bubblewrap](https://github.com/containers/bubblewrap), a Linux system utility (`apt install bubblewrap`). The bot gets no new dependencies. There is no sandbox on Windows and macOS: with this setting the bot does not start there, and without it it works as before.
241
+
242
+ A teammate's agent sees only:
243
+
244
+ - read-write — their projects folder (the personal workspace; without personal workspaces the projects root, without a root the project folder), their own home folder `<data dir>/homes/<id>` and the outgoing files folder;
245
+ - read-only — their uploaded files, the system (`/usr`, `/etc` and the like), Node and the engine programs.
246
+
247
+ The bot's `.env` and database, the home folder of the bot's account, other people's folders and other people's processes do not exist inside the sandbox: an attempt to read someone else's file ends with "No such file or directory".
248
+
249
+ - **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.
250
+ - **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.
251
+ - **The administrator works without the sandbox.**
252
+ - **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`.
253
+ - **Sessions started before the sandbox was turned on** are not resumed in it — a new one starts.
254
+ - **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.
255
+
256
+ What the sandbox does not do:
257
+
258
+ - it does not limit the network: the agent needs to reach the models, so it can also reach services on the server itself and in the local network;
259
+ - it does not hide the engine's API keys: they are passed to the agent in its environment and a teammate can ask to see them — set a spending limit on the key at the provider;
260
+ - it does not limit disk, memory or CPU.
222
261
 
223
- > An agent mode limits what the agent does, but it is **not a sandbox**: the agent runs with the rights of the account the bot runs under. The project folder is where it starts, not a jail. All users share the API keys and quotas. The agent process does not get the bot token, and of the API keys only those of its own engine (Claude Code — `ANTHROPIC_API_KEY`, Codex — `OPENAI_API_KEY`, Gemini CLI and Antigravity — the Google keys, OpenCode — all of them), but the agent can still read files on disk, including the bot's `.env`. Give the "Full" level (Claude Code `bypassPermissions`) deliberately.
262
+ > Without the sandbox an agent mode limits what the agent does, but does **not isolate** it: the agent runs with the rights of the account the bot runs under. The project folder is where it starts, not a jail. All users share the API keys and quotas. The agent process does not get the bot token, and of the API keys only those of its own engine (Claude Code — `ANTHROPIC_API_KEY`, Codex — `OPENAI_API_KEY`, Gemini CLI and Antigravity — the Google keys, OpenCode — all of them), but the agent can still read files on disk, including the bot's `.env`. Give the "Full" level (Claude Code `bypassPermissions`) deliberately.
224
263
 
225
264
  ## Configuration (`.env`)
226
265
 
@@ -229,6 +268,9 @@ Personal workspaces limit which working folder can be chosen in the bot. They do
229
268
  | `TELEGRAM_BOT_TOKEN` | yes | bot token |
230
269
  | `ALLOWED_USER_ID` | yes | Telegram ID of the main admin |
231
270
  | `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) |
271
+ | `AGENT_SANDBOX` | no | `bwrap` — agent sandbox (Linux only, needs the `bubblewrap` package): a teammate's agent sees only their projects folder, their files and their own home folder. See "Agent sandbox" |
272
+ | `SANDBOX_RO_PATHS` | no | extra folders the sandbox can read (separated by `:`), e.g. where an engine is installed if it does not start in the sandbox |
273
+ | `BWRAP_COMMAND` | no | path to `bwrap` if it is not in `PATH` |
232
274
  | `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 |
233
275
  | `DEFAULT_ENGINE` | no | `gemini` (default), `claude`, `agy`, `codex` or `opencode`; the bot does not start if this engine is not installed |
234
276
  | `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` |
@@ -275,9 +317,11 @@ src/
275
317
  state.mjs per-user state: agent process, engine, project, limits, idle reaper
276
318
  admin.mjs invites, access requests, /users, /active
277
319
  projects.mjs project paths (inside the root or anywhere), recent projects, search
278
- *Ui.mjs /project, /sessions, /engine, /model screens
320
+ *Ui.mjs /project, /files, /sessions, /engine, /model screens
321
+ projectFiles.mjs project files bypassing the agent: safe writes and deletes inside the project, no links
279
322
  ui.mjs rendering: drafts, steps, final message, screens
280
323
  telegram.mjs Bot API calls, rich messages, long text splitting, file download and upload
324
+ sandbox.mjs agent sandbox (Linux, bubblewrap): what a teammate's agent can see, the startup check
281
325
  files.mjs attachments: names, saving, prompt blocks, [[send:path]] markers, outgoing file checks, cleanup
282
326
  archive.mjs safe unpacking of zip, tar, tar.gz without dependencies
283
327
  albums.mjs collects Telegram albums (shared media_group_id) into one request
package/README.ru.md CHANGED
@@ -53,6 +53,7 @@ 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`, ключи), которые нельзя показывать бесплатным моделям. См. «Файлы проекта и секреты».
56
57
  - **Возврат к прошлой сессии** (`/sessions`): агент помнит весь диалог, сессию можно возобновить даже после перезапуска бота. У каждой сессии метка движка; сессия возобновляется в том движке, где была создана.
57
58
  - **Доступ для сотрудников**: администратор выдаёт и забирает доступ, выбирая уровень, движки и модели.
58
59
  - **База работы бота** (SQLite): сессии, запросы пользователей с моделью, токенами и стоимостью, вызовы инструментов, разрешения, ответы модели.
@@ -66,6 +67,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
66
67
  | `/engine [gemini, claude, agy, codex, opencode]` | все | выбор движка кнопками или по названию |
67
68
  | `/model [название]` | все | выбор модели и уровня рассуждений текущего движка; с названием — поиск модели (`/model sonnet`) |
68
69
  | `/new` | все | новая сессия агента |
70
+ | `/files` | все | файлы проекта: список, создание, загрузка и удаление — в обход агента |
69
71
  | `/sessions` | все | список прошлых сессий в текущем проекте и возврат в выбранную |
70
72
  | `/stop` | все | остановить выполняющийся запрос |
71
73
  | `/close`, `/exit` | все | закрыть сессию, выгрузить процесс агента и освободить слот |
@@ -97,6 +99,19 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
97
99
 
98
100
  **Лимиты:** не более 3 одновременно работающих агентов сотрудников во всех движках вместе (администратор вне лимита), сессия закрывается через 30 минут простоя.
99
101
 
102
+ ### Файлы проекта и секреты
103
+
104
+ Всё, что пользователь пишет боту или отправляет ему файлом, уходит агенту, а значит — в запрос к модели. Для паролей, токенов и ключей это не подходит: бесплатные модели могут использовать запросы для обучения. Команда `/files` кладёт файл прямо в папку проекта, минуя агента.
105
+
106
+ - **Список.** `/files` показывает файлы и папки текущего проекта (вместе со скрытыми вроде `.env`; без `.git`, `node_modules` и ссылок), по папкам можно ходить кнопками.
107
+ - **«📝 Создать файл».** Бот спрашивает имя (можно с подпапкой: `config/.env`), затем содержимое одним сообщением (до 3500 символов). Сообщение с содержимым сразу удаляется из чата; в базу и журналы оно не пишется.
108
+ - **«⬆️ Загрузить файл».** Следующий присланный файл (или альбом) сохраняется в открытую папку проекта под своим именем, а сообщение с ним удаляется из чата. Ожидание одноразовое и истекает через 10 минут. Без нажатия кнопки файлы и изображения, как и раньше, передаются агенту.
109
+ - **Удаление** — из карточки файла, с подтверждением. Существующий файл заменяется только после вопроса «Заменить?».
110
+ - **Кто может менять файлы:** администратор; сотрудник — в личном пространстве, а в общем корне — с уровнем «Обычный» или «Полный». Смотреть список может любой.
111
+ - **Только внутри проекта.** Бот не пишет и не удаляет за пределами папки проекта и не ходит по ссылкам: ссылка, подложенная в проект, не заставит его перезаписать чужой файл.
112
+
113
+ Что это даёт и чего не даёт. Секрет не попадает в запрос к модели *от пользователя*. Сам файл агенту доступен — иначе приложения, которые он пишет и запускает, не смогли бы им пользоваться. Чтобы агент не прочитал значения в диалог сам, бот регулярно напоминает ему: файлы с секретами не открывать и не выводить, ссылаться на настройки по именам, а за недостающим значением отправлять пользователя в `/files`. Это указание, а не запрет: для особо чувствительных данных используйте модель провайдера, который не обучается на запросах.
114
+
100
115
  ### Личные пространства
101
116
 
102
117
  По умолчанию все сотрудники ходят по одному корню проектов. `USER_WORKSPACES=1` (вместе с `PROJECTS_ROOT`) даёт каждому сотруднику свою папку: `<корень>/<Telegram ID>`. Папка создаётся сама при первом обращении сотрудника к боту.
@@ -108,9 +123,33 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
108
123
  - Проекты, выбранные сотрудником до включения режима и лежащие вне его папки, сбрасываются на его пространство. Сами папки бот не переносит и не удаляет — в том числе при отзыве доступа.
109
124
  - Перед каждым запуском агента бот проверяет, что папка проекта существует и лежит в пространстве сотрудника; иначе агент не запускается.
110
125
 
111
- Личные пространства ограничивают выбор рабочей папки в боте. Сам процесс агента они не изолируют — см. примечание ниже.
126
+ Личные пространства ограничивают выбор рабочей папки в боте. Сам процесс агента изолирует песочница (на Linux, ниже); без неё действует примечание в конце раздела.
127
+
128
+ ### Песочница агента (Linux)
129
+
130
+ `AGENT_SANDBOX=bwrap` запускает агента каждого сотрудника изолированно — через [bubblewrap](https://github.com/containers/bubblewrap), системную утилиту Linux (`apt install bubblewrap`). Зависимостей у бота не прибавляется. На Windows и macOS песочницы нет: с этой настройкой бот там не запустится, без неё работает как раньше.
131
+
132
+ Агент сотрудника видит только:
133
+
134
+ - на запись — свою папку проектов (личное пространство; без личных пространств — корень проектов, без корня — папку проекта), свою домашнюю папку `<каталог данных>/homes/<id>` и каталог исходящих файлов;
135
+ - на чтение — свои загруженные файлы, систему (`/usr`, `/etc` и т. п.), Node и программы движка.
136
+
137
+ `.env` и база бота, домашняя папка учётной записи бота, чужие папки и чужие процессы в песочнице отсутствуют: на попытку прочитать чужой файл агент получает «No such file or directory».
138
+
139
+ - **У каждого свои настройки движка.** Домашняя папка у сотрудника своя, поэтому история сессий, настройки и входы движков у всех раздельные. Движок должен работать без входа, сохранённого в домашней папке учётной записи бота: OpenCode на бесплатных моделях — вообще без ключей, остальные — по ключу API из `.env`. Вход по подписке (`codex login`, вход Google, подписка Claude) в песочнице не виден.
140
+ - **Уровень «Полный» становится безопаснее.** Агент не спрашивает разрешений, но изменить может только пространство своего сотрудника — удобно для тех, кто не хочет разбираться в запросах разрешений.
141
+ - **Администратор работает без песочницы.**
142
+ - **Проверка при старте.** Бот проверяет, что bubblewrap запускается, секреты бота изнутри не видны, а движки в песочнице стартуют. Не работает песочница или движок по умолчанию — бот не запускается и пишет причину. Остальные движки, не запустившиеся в песочнице, сотрудникам не предлагаются. Если движок установлен в нестандартном месте, добавьте его папку в `SANDBOX_RO_PATHS`.
143
+ - **Сессии, начатые до включения песочницы,** в ней не возобновляются — начинается новая.
144
+ - **Ubuntu 24.04 и новее:** пространства имён пользователя могут быть закрыты AppArmor. Если бот при старте сообщает, что песочница не работает, выполните `sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0` (для постоянства — файл в `/etc/sysctl.d/`) или добавьте профиль AppArmor для `bwrap`. В Docker песочница не поддерживается: контейнер отделяет бота от системы, но не сотрудников друг от друга.
145
+
146
+ Чего песочница не делает:
147
+
148
+ - не ограничивает сеть: агенту нужен доступ к моделям, поэтому он достаёт и до служб на самом сервере и в локальной сети;
149
+ - не прячет ключи API движка: они передаются агенту в окружении, и сотрудник может попросить их показать — ставьте на ключ лимит расхода у провайдера;
150
+ - не ограничивает диск, память и процессор.
112
151
 
113
- > Режим агента ограничивает его действия, но не является песочницей: агент работает с правами учётной записи, под которой запущен бот. Рабочая папка проекта задаёт, где он начинает работу, но не запрещает читать и писать за её пределами. Все сотрудники используют общие ключи API и квоты движков. Процесс агента не получает токен бота, а из ключей API — только ключи своего движка (Claude Code — `ANTHROPIC_API_KEY`, Codex — `OPENAI_API_KEY`, Gemini CLI и Antigravity — ключи Google, OpenCode — все), но файлы на диске, включая `.env` бота, агент прочитать может. Уровень «Полный» у Claude Code (`bypassPermissions`) выполняет любые команды без подтверждения — выдавайте его осознанно.
152
+ > Без песочницы режим агента ограничивает его действия, но не изолирует его: агент работает с правами учётной записи, под которой запущен бот. Рабочая папка проекта задаёт, где он начинает работу, но не запрещает читать и писать за её пределами. Все сотрудники используют общие ключи API и квоты движков. Процесс агента не получает токен бота, а из ключей API — только ключи своего движка (Claude Code — `ANTHROPIC_API_KEY`, Codex — `OPENAI_API_KEY`, Gemini CLI и Antigravity — ключи Google, OpenCode — все), но файлы на диске, включая `.env` бота, агент прочитать может. Уровень «Полный» у Claude Code (`bypassPermissions`) выполняет любые команды без подтверждения — выдавайте его осознанно.
114
153
 
115
154
  ## Требования
116
155
 
@@ -247,6 +286,9 @@ npm start # первый запуск без .env сам открое
247
286
  | `ALLOWED_USER_ID` | да | числовой Telegram ID главного администратора |
248
287
  | `PROJECTS_ROOT` | нет | корень проектов: агент выбирает рабочую папку только внутри него (`C:\scripts`, `/home/user/projects`). Без него — любая папка на машине, по умолчанию домашняя |
249
288
  | `USER_WORKSPACES` | нет | `1` — личные пространства: каждый сотрудник выбирает проекты только в своей папке `<корень>/<Telegram ID>`, администратор видит весь корень. Нужен `PROJECTS_ROOT`, без него бот не запускается |
289
+ | `AGENT_SANDBOX` | нет | `bwrap` — песочница агента (только Linux, нужен пакет `bubblewrap`): агент сотрудника видит только его папку проектов, его файлы и его домашнюю папку. См. «Песочница агента» |
290
+ | `SANDBOX_RO_PATHS` | нет | дополнительные папки, которые песочница видит на чтение (через `:`), — например, место установки движка, если он не запускается в песочнице |
291
+ | `BWRAP_COMMAND` | нет | путь к `bwrap`, если его нет в `PATH` |
250
292
  | `DEFAULT_ENGINE` | нет | движок по умолчанию: `gemini` (по умолчанию), `claude`, `agy`, `codex` или `opencode`. Если этот движок не установлен, бот не запускается |
251
293
  | `DEFAULT_LANG` | нет | язык бота, если язык Telegram пользователя не `ru`, `uk` или `en`: `en` (по умолчанию), `ru` или `uk`. Пользователь может сменить язык командой `/language` |
252
294
  | `ACPGRAM_LANG` | нет | язык команд `acpgram` в терминале: `ru`, `uk` или `en`. Обычно не нужен: язык берётся из системы (для Docker и CI, где у системы нет языка) |
@@ -351,6 +393,8 @@ src/
351
393
  admin.mjs приглашения, запросы доступа, /users, /active
352
394
  projects.mjs пути проектов: с корнем — безопасно внутри него, без корня — любая папка; недавние, поиск
353
395
  projectsUi.mjs команда /project и навигация кнопками
396
+ projectFiles.mjs файлы проекта в обход агента: безопасная запись и удаление внутри проекта, без ссылок
397
+ filesUi.mjs команда /files: список, создание, загрузка и удаление файлов проекта
354
398
  sessionsUi.mjs команда /sessions: возврат к прошлой сессии
355
399
  tools.mjs разбор событий вызовов инструментов агента
356
400
  asks.mjs кнопки быстрого ответа от агента: метка [[ask: …]], разметка кнопок, выбор по нажатию
@@ -364,6 +408,7 @@ src/
364
408
  access.mjs права сотрудников на движки и модели, каталоги моделей, применение выбора к сессии
365
409
  ui.mjs оформление: черновик, шаги, итоговое сообщение, экраны /start, /engine и /active
366
410
  telegram.mjs вызовы Bot API, rich-сообщения, разбиение длинных текстов, скачивание и отправка файлов
411
+ sandbox.mjs песочница агента (Linux, bubblewrap): что видит агент сотрудника, проверка при старте
367
412
  files.mjs вложения: имена, сохранение, блоки промпта, метки [[send:путь]], проверка отправляемых файлов, очистка
368
413
  archive.mjs безопасная распаковка zip, tar, tar.gz без зависимостей
369
414
  albums.mjs сбор альбомов Telegram (общий media_group_id) в один запрос
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acpgram",
3
- "version": "1.24.0",
3
+ "version": "1.26.0",
4
4
  "type": "module",
5
5
  "description": "Telegram gateway to AI coding agents (Gemini CLI, Claude Code, Antigravity CLI, Codex, OpenCode) over the Agent Client Protocol",
6
6
  "license": "MIT",
package/src/access.mjs CHANGED
@@ -8,7 +8,7 @@ import { createHash } from 'node:crypto';
8
8
  import { tmpdir } from 'node:os';
9
9
  import { ADMIN_ID, db, langOf, log } from './ctx.mjs';
10
10
  import { checkCommand } from './acp.mjs';
11
- import { DEFAULT_ENGINE, ENGINES, agentEnv, autoValue, createAgent, engineCommand, engineVersion, isAuthError, isAvailable, parseCatalog, selectionRequest, setNeedsLogin } from './engines.mjs';
11
+ import { DEFAULT_ENGINE, ENGINES, agentEnv, autoValue, brokenInSandbox, createAgent, engineCommand, engineVersion, isAuthError, isAvailable, parseCatalog, selectionRequest, setNeedsLogin } from './engines.mjs';
12
12
  import { t } from './i18n.mjs';
13
13
 
14
14
  /** JSON из строки; пусто или не разобралось — fallback. */
@@ -165,11 +165,14 @@ export function grantedEngines(userId) {
165
165
  return [DEFAULT_ENGINE, ...Object.keys(ENGINES).filter((id) => id !== DEFAULT_ENGINE && Array.isArray(extra) && extra.includes(id))];
166
166
  }
167
167
 
168
+ /** Запускается ли движок для этого пользователя: есть на сервере, а сотруднику — ещё и работает в песочнице, если она включена. */
169
+ const runsFor = (userId, id) => isAvailable(id) && (userId === ADMIN_ID || !brokenInSandbox(id));
170
+
168
171
  /** Можно ли пользователю работать в движке сейчас: выдан и запускается на сервере. */
169
- export const canUseEngine = (userId, id) => isEngineId(id) && isAvailable(id) && grantedEngines(userId).includes(id);
172
+ export const canUseEngine = (userId, id) => isEngineId(id) && runsFor(userId, id) && grantedEngines(userId).includes(id);
170
173
 
171
174
  /** Движки, которые пользователь может выбрать в /engine. */
172
- export const userEngines = (userId) => grantedEngines(userId).filter((id) => isAvailable(id)).map((id) => ENGINES[id]);
175
+ export const userEngines = (userId) => grantedEngines(userId).filter((id) => runsFor(userId, id)).map((id) => ENGINES[id]);
173
176
 
174
177
  /** Выдаёт или забирает у сотрудника движок (кроме движка по умолчанию). Возвращает новый список выданных. */
175
178
  export function setEngineGrant(userId, engineId, on) {
package/src/bot.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  // Telegram-интерфейс к AI-агентам разработки (Gemini CLI, Claude Code, Antigravity CLI, Codex, OpenCode) через ACP.
2
2
  // Доступ: главный администратор (ALLOWED_USER_ID) и сотрудники, которым он выдал доступ. Остальным бот не отвечает,
3
3
  // кроме запроса доступа администратору.
4
- import { DEFAULT_ENGINE, checkEngines, isRequired, setAvailability } from './engines.mjs';
4
+ import { DEFAULT_ENGINE, agentEnv, checkEngines, isRequired, setAvailability, setSandboxBroken } from './engines.mjs';
5
+ import { SANDBOX, checkInSandbox, probeSandbox } from './sandbox.mjs';
5
6
  import { handleEngine, onEngineCallback } from './engineUi.mjs';
6
7
  import { choiceName, effectiveSelection, killProbes, refreshCatalogs } from './access.mjs';
7
8
  import { handleModel, onModelCallback } from './modelUi.mjs';
@@ -10,6 +11,7 @@ import { adminCommand, handleUnknownUser, onAdminCallback, welcomeNote } from '.
10
11
  import { LANGS, LANG_CODES, LANG_PICK, errText, normLang, t } from './i18n.mjs';
11
12
  import { HOME, ROOT, USER_WORKSPACES } from './projects.mjs';
12
13
  import { handleProject, onNavCallback, onProjectNameInput, onTopicListCallback } from './projectsUi.mjs';
14
+ import { handleFiles, onFileInput, onFileUpload, onFilesCallback } from './filesUi.mjs';
13
15
  import { handleSessions, onSessionCallback } from './sessionsUi.mjs';
14
16
  import { dropPermissions, findState, getState, isAdmin, levelLabel, shutdownAll, startIdleReaper, endAgent, closeSession, engineOf, topicsOn, topicsSupport, userPath } from './state.mjs';
15
17
  import { handleTopics, newTopic, onTopicsCallback } from './topicsUi.mjs';
@@ -117,6 +119,7 @@ const COMMANDS = [
117
119
  { name: 'invite', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/invite') },
118
120
  { name: 'usage', admin: true, menu: true, button: true, run: (st) => adminCommand(st.to, '/usage') },
119
121
  { name: 'project', menu: true, button: true, run: (st, arg) => handleProject(st, arg) },
122
+ { name: 'files', menu: true, button: true, run: (st) => handleFiles(st) },
120
123
  { name: 'engine', menu: true, button: true, run: (st, arg) => handleEngine(st, arg) },
121
124
  { name: 'model', menu: true, button: true, run: (st, arg) => handleModel(st, arg) },
122
125
  { name: 'new', menu: true, button: true, run: newCommand },
@@ -140,18 +143,20 @@ const sendToAgent = (st, text, opts = {}) => (st.busy ? enqueue(st, text, opts)
140
143
  * команды не объявлял, это, скорее всего, опечатка: спрашиваем, а не тратим запрос.
141
144
  * @param {{quote?: string|null}} [opts] quote — фрагмент прошлого сообщения, на который отвечает пользователь
142
145
  */
143
- async function handleText(st, text, { quote = null } = {}) {
146
+ async function handleText(st, text, { quote = null, messageId = null } = {}) {
144
147
  const m = /^\/(\w+)(?:@\w+)?(?:\s+([\s\S]*))?$/.exec(text);
145
148
  const name = m?.[1]?.toLowerCase();
146
149
  const command = name ? COMMANDS.find((c) => c.name === name || c.aliases?.includes(name)) : null;
147
150
  const lang = langOf(st.userId);
148
- if (name) st.pendingInput = null; // любая команда отменяет ожидание названия нового проекта
149
151
  if (command) {
152
+ st.pendingInput = null; // команда бота отменяет ожидание названия проекта, имени или содержимого файла
150
153
  if (command.admin && !isAdmin(st.userId)) return say(st.to, t('admin.only', lang));
151
154
  return command.run(st, m[2]);
152
155
  }
153
156
  // бот ждёт название папки нового проекта (кнопка «Новый проект» в /project): этот текст — оно, а не запрос агенту
154
157
  if (await onProjectNameInput(st, text)) return;
158
+ // бот ждёт имя или содержимое файла проекта (/files): содержимое агенту не передаётся и удаляется из чата
159
+ if (await onFileInput(st, text, { messageId })) return;
155
160
  if (name && !st.agent?.commands?.has(name)) {
156
161
  const guess = nearCommand(name, COMMANDS.filter((c) => !c.admin || isAdmin(st.userId)).map((c) => c.name));
157
162
  if (guess) {
@@ -314,6 +319,7 @@ async function handleUpdate(u) {
314
319
  if (data.startsWith('tpc:')) return onTopicsCallback(st, cb);
315
320
  if (data.startsWith('tpl:')) return onTopicListCallback(st, cb);
316
321
  if (data.startsWith('nav:')) return onNavCallback(st, cb);
322
+ if (data.startsWith('fl:')) return onFilesCallback(st, cb);
317
323
  if (data.startsWith('perm:')) return onPermissionCallback(st, cb);
318
324
  if (data.startsWith('ask:')) return onAskCallback(st, cb);
319
325
  if (data.startsWith('q:')) return onQueueCallback(st, cb);
@@ -330,8 +336,13 @@ async function handleUpdate(u) {
330
336
  if (data.startsWith('lang:')) return onLangCallback(st, cb);
331
337
  return;
332
338
  }
333
- if (msg?.text) return handleText(getState(from.id, chatId, threadId), msg.text, { quote: quoteOf(msg) });
334
- if (msg?.photo || msg?.document) return handleAttachment(getState(from.id, chatId, threadId), msg);
339
+ if (msg?.text) return handleText(getState(from.id, chatId, threadId), msg.text, { quote: quoteOf(msg), messageId: msg.message_id });
340
+ if (msg?.photo || msg?.document) {
341
+ const st = getState(from.id, chatId, threadId);
342
+ // нажата «Загрузить файл» в /files: файл кладётся в проект, а не передаётся агенту
343
+ if (await onFileUpload(st, msg)) return;
344
+ return handleAttachment(st, msg);
345
+ }
335
346
  // голосовое, видео, стикер и т. п.: раньше бот на них молчал
336
347
  if (msg && unsupportedKind(msg)) return say(getState(from.id, chatId, threadId).to, t('msg.unsupported', langOf(from.id)));
337
348
  }
@@ -373,6 +384,36 @@ function noteTopic(userId, threadId, msg) {
373
384
  return Boolean(msg.forum_topic_created);
374
385
  }
375
386
 
387
+ /**
388
+ * Песочница агентов сотрудников (AGENT_SANDBOX): проверка при старте. Не работает сама песочница или в ней не
389
+ * запускается движок по умолчанию — бот не запускается: без этого сотрудники работали бы без изоляции или не работали
390
+ * вовсе. Остальные движки, не запустившиеся в песочнице, сотрудникам не предлагаются.
391
+ */
392
+ async function setupSandbox(checks) {
393
+ const probe = probeSandbox();
394
+ if (!probe.ok) {
395
+ console.error(`AGENT_SANDBOX=${SANDBOX}: песочница не работает — ${probe.error}
396
+ ${probe.hint}`);
397
+ process.exit(1);
398
+ }
399
+ log('песочница агентов сотрудников включена (bubblewrap): агент видит только папку проектов сотрудника, его файлы и его домашнюю папку; администратор работает без песочницы');
400
+ const usable = checks.filter((r) => r.ok || r.timeout);
401
+ const inside = await Promise.all(usable.map((r) => checkInSandbox(r.command, r.engine.versionArgs, agentEnv(r.engine))));
402
+ const broken = [];
403
+ usable.forEach((r, i) => {
404
+ const s = inside[i];
405
+ if (s.ok || s.timeout) return;
406
+ const text = `${r.engine.label} не запускается в песочнице (${r.command}): ${s.error}. Если движок установлен в нестандартном месте, добавьте его папку в SANDBOX_RO_PATHS`;
407
+ if (isRequired(r.engine)) {
408
+ console.error(text);
409
+ process.exit(1);
410
+ }
411
+ log(`⚠️ ${text} — сотрудникам он не предлагается`);
412
+ broken.push(r.engine.id);
413
+ });
414
+ setSandboxBroken(broken);
415
+ }
416
+
376
417
  async function main() {
377
418
  // все движки проверяем параллельно; без движка по умолчанию (DEFAULT_ENGINE) бот не запускается, остальные — по возможности
378
419
  const asked = process.env.DEFAULT_ENGINE?.trim().toLowerCase();
@@ -389,6 +430,7 @@ async function main() {
389
430
  } else log(`ℹ️ ${e.label} недоступен (${command}): ${r.error}. Установка: ${e.install}; путь — ${e.envVar}`);
390
431
  }
391
432
  log(`движок по умолчанию: ${DEFAULT_ENGINE}`);
433
+ if (SANDBOX) await setupSandbox(checks);
392
434
  log(
393
435
  ROOT
394
436
  ? `корень проектов: ${ROOT} (проект — только папка внутри корня)`
package/src/cli-i18n.mjs CHANGED
@@ -181,6 +181,11 @@ https://github.com/{repo}`,
181
181
  ru: 'Личные пространства: каждый сотрудник работает только в своей папке <корень>/<Telegram ID>',
182
182
  uk: 'Особисті простори: кожен співробітник працює лише у своїй теці <корінь>/<Telegram ID>',
183
183
  },
184
+ 'env.c.sandbox': {
185
+ en: 'Agent sandbox (Linux, bubblewrap): a teammate’s agent sees only their projects folder, their files and their own home folder',
186
+ ru: 'Песочница агента (Linux, bubblewrap): агент сотрудника видит только его папку проектов, его файлы и его домашнюю папку',
187
+ uk: 'Пісочниця агента (Linux, bubblewrap): агент співробітника бачить лише його теку проєктів, його файли та його домашню теку',
188
+ },
184
189
  'env.c.engine': { en: 'Default engine: gemini | claude | agy | codex | opencode', ru: 'Движок по умолчанию: gemini | claude | agy | codex | opencode', uk: 'Рушій за замовчуванням: gemini | claude | agy | codex | opencode' },
185
190
  'env.c.keys': { en: 'API keys are passed to the agents through the bot environment', ru: 'Ключи API передаются агентам через окружение бота', uk: 'Ключі API передаються агентам через оточення бота' },
186
191
  'env.rest': { en: 'Other settings', ru: 'Прочие настройки', uk: 'Інші налаштування' },
@@ -248,6 +253,18 @@ https://github.com/{repo}`,
248
253
  uk: ' Особисті простори: у кожного співробітника своя тека в корені (ім’я — його Telegram ID), проєкти він обирає лише в ній; адміністратор бачить увесь корінь.',
249
254
  },
250
255
  'setup.wsAsk': { en: ' Give each employee a personal workspace?', ru: ' Выдать каждому сотруднику личное пространство?', uk: ' Видати кожному співробітнику особистий простір?' },
256
+ 'setup.sbNote': {
257
+ en: ' Agent sandbox: a teammate’s agent runs isolated (bubblewrap) and cannot read the bot settings, its database or other people’s folders. The administrator works without it.',
258
+ ru: ' Песочница агента: агент сотрудника запускается изолированно (bubblewrap) и не может прочитать настройки бота, его базу и чужие папки. Администратор работает без неё.',
259
+ uk: ' Пісочниця агента: агент співробітника запускається ізольовано (bubblewrap) і не може прочитати налаштування бота, його базу та чужі теки. Адміністратор працює без неї.',
260
+ },
261
+ 'setup.sbMissing': {
262
+ en: 'bubblewrap is not installed — the sandbox is off. Install it (apt install bubblewrap) and run the setup again to turn it on',
263
+ ru: 'bubblewrap не установлен — песочница выключена. Установите его (apt install bubblewrap) и запустите настройку снова, чтобы включить',
264
+ uk: 'bubblewrap не встановлено — пісочницю вимкнено. Встановіть його (apt install bubblewrap) і запустіть налаштування знову, щоб увімкнути',
265
+ },
266
+ 'setup.sbAsk': { en: ' Run teammates’ agents in the sandbox?', ru: ' Запускать агентов сотрудников в песочнице?', uk: ' Запускати агентів співробітників у пісочниці?' },
267
+ 'setup.sbOn': { en: 'the agent sandbox is on', ru: 'песочница агента включена', uk: 'пісочницю агента увімкнено' },
251
268
  'setup.wsOn': { en: 'personal workspaces are on', ru: 'личные пространства включены', uk: 'особисті простори увімкнено' },
252
269
  'setup.s4': { en: 'AI engines (checking what is installed)', ru: 'AI-движки (проверяю установленные)', uk: 'AI-рушії (перевіряю встановлені)' },
253
270
  'setup.engineOk': { en: '{label} {version} — {path}', ru: '{label} {version} — {path}', uk: '{label} {version} — {path}' },
package/src/engines.mjs CHANGED
@@ -308,6 +308,18 @@ export const engineVersion = (id) => versions.get(id) ?? null;
308
308
 
309
309
  export const isAvailable = (id) => Boolean(ENGINES[id]) && !unavailable.has(id);
310
310
 
311
+ // ---- песочница (AGENT_SANDBOX): движки, которые при проверке на старте не запустились внутри неё ----
312
+ const sandboxBroken = new Set();
313
+
314
+ /** Отмечает движки, не запустившиеся в песочнице: сотрудникам (их агенты работают в ней) они не предлагаются. */
315
+ export function setSandboxBroken(ids) {
316
+ sandboxBroken.clear();
317
+ for (const id of ids) sandboxBroken.add(id);
318
+ }
319
+
320
+ /** Движок не запускается в песочнице (администратору, работающему без неё, он доступен). */
321
+ export const brokenInSandbox = (id) => sandboxBroken.has(id);
322
+
311
323
  // ---- вход и ключи API (определяется по ошибке запуска сессии при получении каталога моделей) ----
312
324
  const loginNeeded = new Set();
313
325
 
@@ -487,10 +499,15 @@ export function parseUsage(res, usageUpdate) {
487
499
  * @param {{cwd: string, who?: {admin?: boolean, level?: string}, onUpdate?: Function, onPermission?: Function, onExit?: Function}} opts
488
500
  * who — кто работает в сессии: от этого зависят переменные окружения движка (processEnv; у OpenCode — конфиг прав).
489
501
  * Без who (запуск за списком моделей) — только общее окружение агента (agentEnv).
502
+ * wrap — запуск через программу-обёртку (песочница, sandbox.agentSandbox): {command, args, env}; её аргументы уже
503
+ * заканчиваются командой движка, аргументы движка добавляются следом, а окружение проходит через wrap.env.
490
504
  */
491
- export function createAgent(engine, { who, ...opts }) {
492
- const env = { ...agentEnv(engine), ...(who && engine.processEnv ? engine.processEnv(who) : {}) };
493
- const agent = new AcpAgent({ ...opts, env, command: engineCommand(engine), args: engine.args, name: engine.label, quietStderr: engine.quietStderr ?? null, quietStderrBlock: engine.quietStderrBlock ?? null });
505
+ export function createAgent(engine, { who, wrap = null, ...opts }) {
506
+ const base = { ...agentEnv(engine), ...(who && engine.processEnv ? engine.processEnv(who) : {}) };
507
+ const env = wrap ? wrap.env(base) : base;
508
+ const command = wrap ? wrap.command : engineCommand(engine);
509
+ const args = wrap ? [...wrap.args, ...engine.args] : engine.args;
510
+ const agent = new AcpAgent({ ...opts, env, command, args, name: engine.label, quietStderr: engine.quietStderr ?? null, quietStderrBlock: engine.quietStderrBlock ?? null });
494
511
  agent.engine = engine;
495
512
  return agent;
496
513
  }
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
  /**