acpgram 1.20.1 → 1.22.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
@@ -38,8 +38,14 @@ Check it yourself after installing: `npm audit signatures` verifies the registry
38
38
  - **Streaming replies** in a Telegram draft with a stop button: the agent's thoughts, the steps it takes (reading files, running commands, searching, editing) and the elapsed time, then the answer itself.
39
39
  - **Rich final answer** — headings, lists, tables, code blocks — with a collapsible "work log" of every step and a footer showing the engine, the actual model, reasoning level, tokens, cost (Claude Code and OpenCode) and time.
40
40
  - **Five engines, one interface** — `/engine` switches between Gemini CLI, Claude Code, Antigravity CLI, Codex and OpenCode; the default engine is set in `.env`.
41
+ - **Quick-reply buttons** — when the agent asks you to choose ("Which fix should I apply?"), buttons appear under its question; a tap sends the option to the agent as your message. The bot builds the buttons from the agent's `[[ask: Yes | No]]` marker; raw button tags in the agent's text do not work.
42
+ - **See the edit before you allow it** — a permission request for a file edit shows the diff, not only the path.
43
+ - **Plan** — if the agent keeps a plan, the draft shows "Plan: 3/7" and its items with check marks.
44
+ - **Messages sent while the agent is busy are not lost** — the bot queues the message and sends it as soon as the agent is done; the notice has "Stop and send this now" and "Do not send" buttons.
45
+ - **Reply with a quote** — reply to the agent's message with a selected fragment and the agent gets both your text and the fragment ("rewrite this part").
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.
41
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.
42
- - **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). File edits are allowed as a whole, commands by program name (allowing `git status` lets every `git …` through; every part of a compound command must be allowed); commands run through a shell wrapper (`bash -c`, `powershell`, `cmd /c`, `sudo`), with substitutions or writing to a file (`>`) match only exactly.
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`).
43
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`).
44
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.
45
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.
@@ -183,6 +189,7 @@ In the container the agent sees only the mounted projects folder (`PROJECTS_DIR`
183
189
  | `/users` | admin | teammates: level, engines, models, end session, revoke access |
184
190
  | `/active` | admin | active sessions with buttons to end them |
185
191
  | `/invite` | admin | one-time invite link (24 h) |
192
+ | `/usage` | admin | usage: requests, tokens and cost by user for 24 hours, 7 and 30 days |
186
193
 
187
194
  ## Access levels
188
195
 
@@ -199,7 +206,7 @@ OpenCode has only two modes (`plan` and `build`); what the agent may do is set b
199
206
 
200
207
  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).
201
208
 
202
- > 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. Give the "Full" level (Claude Code `bypassPermissions`) deliberately.
209
+ > 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.
203
210
 
204
211
  ## Configuration (`.env`)
205
212
 
@@ -224,6 +231,7 @@ New teammates get only the default engine; the admin grants other engines and ca
224
231
  | `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) |
225
232
  | `FILES_DIR` | no | folder for received (`uploads`) and outgoing (`outbox`) files (the bot's data folder) |
226
233
  | `FILES_KEEP_DAYS` | no | how many days to keep those files (7) |
234
+ | `WIDGETS` | no | `1` — show `/model` and `/sessions` as widgets when Telegram allows them for the bot (off by default) |
227
235
  | `ANIMATED_ICONS` | no | `0` — plain emoji instead of animated icons in drafts |
228
236
 
229
237
  `.env` is never committed. Keep the token and keys out of the code.
@@ -258,6 +266,12 @@ src/
258
266
  files.mjs attachments: names, saving, prompt blocks, [[send:path]] markers, outgoing file checks, cleanup
259
267
  archive.mjs safe unpacking of zip, tar, tar.gz without dependencies
260
268
  albums.mjs collects Telegram albums (shared media_group_id) into one request
269
+ asks.mjs quick-reply buttons from the agent: the [[ask: …]] marker, button markup, the tapped choice
270
+ diff.mjs line diff for file-edit permission requests
271
+ incoming.mjs incoming messages: quotes, unsupported kinds, command typos
272
+ widgets.mjs HTML widgets: model picker, project sessions, Telegram limits, query parsing
273
+ widgetHost.mjs sending a widget with a fallback to the plain menu, memory of widget messages
274
+ widgetsUi.mjs widget queries: model and reasoning level choice, resuming a session
261
275
  db.mjs SQLite: sessions, requests, tool calls, permissions, users, usage
262
276
  test/ node:test tests and a fake ACP agent
263
277
  .github/workflows CI (tests on Windows / Linux / macOS) and releases (archives, checksums, installer checks)
package/README.ru.md CHANGED
@@ -36,7 +36,13 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
36
36
  - затем заголовок размышлений агента и ход работы: последние 5 шагов (у выполняющегося — анимированная иконка из набора [AI Actions](https://t.me/addemoji/AIActions)), счётчик остальных и время выполнения;
37
37
  - как пошёл ответ — последний шаг и сам ответ.
38
38
  - **Итоговый ответ** в rich-форматировании: заголовки, списки, таблицы, блоки кода. В конце свёрнутый блок «Ход работы · N шагов» со всеми шагами и подвал: движок, реальная модель, уровень рассуждений, токены, стоимость (Claude Code и OpenCode), проект и время ответа — например `🤖 Claude · claude-haiku-5-5 · 🔢 36.8k ток. · 💲0.0046 · 📁 проект · ⏱ 4 с`. Если Telegram отклонит разметку, ответ уходит обычным текстом.
39
- - **Запросы разрешений** кнопками (режимы `default` и `plan`): «Разрешить», «Разрешить на эту сессию», «Отклонить». Команда показывается блоком кода. Вариант «навсегда» из чата не даётся. «На эту сессию» есть во всех движках: если у агента своего такого варианта нет (Claude Code), его даёт бот — правило живёт, пока работает процесс агента (до `/new`, `/close`, закрытия по простою или перезапуска бота). Правки файлов разрешаются целиком, команды — по имени программы (разрешили `git status` — без вопросов пойдут все `git …`; в составной команде должны быть разрешены все части); команды через оболочку (`bash -c`, `powershell`, `cmd /c`, `sudo`), с подстановками и записью в файл (`>`) — только точно такие же.
39
+ - **Запросы разрешений** кнопками (режимы `default` и `plan`): «Разрешить», «Разрешить на эту сессию», «Отклонить». Команда показывается блоком кода. Вариант «навсегда» из чата не даётся. «На эту сессию» есть во всех движках: если у агента своего такого варианта нет (Claude Code), его даёт бот — правило живёт, пока работает процесс агента (до `/new`, `/close`, закрытия по простою или перезапуска бота). На кнопке написано, что именно будет разрешено. Правки файлов разрешаются целиком, команды — по имени программы (разрешили `ls` — без вопросов пойдут все `ls …`), а у программ с подкомандами (`git`, `npm`, `docker` и т. п.) — по программе и подкоманде: разрешили `git status` — пойдут все `git status …`, но не `git push`. В составной команде должны быть разрешены все части. Только точно такие же команды разрешаются для оболочек (`bash -c`, `powershell`, `cmd /c`, `sudo`), интерпретаторов (`python`, `node`, `Rscript`, `npx` и т. п.), команд с подстановками, записью в файл (`>`) и переменными перед программой (`PATH=… git`).
40
+ - **Кнопки быстрого ответа**: когда агент предлагает выбор («Какой вариант применить?»), под его вопросом появляются кнопки — нажатие отправляет вариант агенту как ваше сообщение. Кнопки строит бот по метке агента `[[ask: Да | Нет]]`; собственные теги кнопок в тексте агента не работают.
41
+ - **Правка перед глазами**: в запросе разрешения на правку файла виден дифф — что именно агент изменит, а не только путь.
42
+ - **План работы**: если агент ведёт план, в черновике видно «План: 3/7» и пункты с отметками.
43
+ - **Сообщение во время работы** не теряется: бот поставит его в очередь и отправит агенту, как только тот закончит; под уведомлением — «Остановить и отправить это» и «Не отправлять».
44
+ - **Ответ с цитатой**: ответьте на сообщение агента, выделив фрагмент, — агент получит и ваш текст, и этот фрагмент («перепиши вот это»).
45
+ - **Виджеты** (Bot API 10.4, включаются `WIDGETS=1`): `/model` и `/sessions` открываются виджетом прямо в сообщении — весь каталог моделей с группами и вендорами листается мгновенно, без обращений к боту; сессии проекта — карточками с началом запроса. По умолчанию виджеты выключены: с 13 ноября 2026 Telegram не разрешает обычным ботам отправлять их, и в приложении они не проверены. С `WIDGETS=1` бот пробует виджет и сам показывает обычное меню с кнопками, если Telegram его не принял или каталог не поместился в лимит; оно же — по кнопке «Обычное меню» под виджетом.
40
46
  - **Выбор движка** (`/engine`): Gemini CLI, Claude Code, Antigravity CLI, Codex или OpenCode — из выданных пользователю. Выбор запоминается для каждого пользователя, смена движка начинает новую сессию. Движок по умолчанию — `DEFAULT_ENGINE`; недоступные на сервере движки не предлагаются, а запускающиеся, но не авторизованные (нет входа или ключа API) помечаются «⚠️ нужен вход».
41
47
  - **Выбор модели и уровня рассуждений** (`/model`): модели текущего движка (список присылает сам агент) и уровень рассуждений у Claude Code (`effort`) и Antigravity CLI (`thought_level`). По умолчанию «Авто» — как у агента. Выбор запоминается для каждого пользователя отдельно по движкам и применяется со следующего запроса, без перезапуска сессии. У OpenCode моделей сотни (все подключённые провайдеры), поэтому сначала выбирается группа — «🆓 Бесплатные» или провайдер, — а модели внутри неё листаются по 20; модели, которые не умеют вызывать инструменты (генерация картинок, музыки), не показываются. У агрегаторов вроде OpenRouter (сотни моделей) внутри группы ещё и разработчики моделей — OpenAI, Anthropic, Qwen… (у кого 1–2 модели — в «Прочих»). Быстрее всего — поиск: `/model sonnet` покажет все подходящие модели кнопками; а вверху экрана `/model` — кнопки «🕘» с последними выбранными моделями.
42
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`).
@@ -65,6 +71,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
65
71
  | `/active` | администратор | активные сессии и кнопки их завершения |
66
72
  | `/users` | администратор | список сотрудников: уровень, движки, модели, завершение сессии, отзыв доступа |
67
73
  | `/invite` | администратор | одноразовая ссылка-приглашение (24 часа) |
74
+ | `/usage` | администратор | расход: запросы, токены и стоимость по сотрудникам за 24 часа, 7 и 30 дней |
68
75
 
69
76
  ## Доступ и уровни
70
77
 
@@ -89,7 +96,7 @@ Telegram-шлюз к AI-агентам разработки **Gemini CLI**, **Cl
89
96
 
90
97
  **Лимиты:** не более 3 одновременно работающих агентов сотрудников во всех движках вместе (администратор вне лимита), сессия закрывается через 30 минут простоя.
91
98
 
92
- > Режим агента ограничивает его действия, но не является песочницей: агент работает с правами учётной записи, под которой запущен бот. Рабочая папка проекта задаёт, где он начинает работу, но не запрещает читать и писать за её пределами. Все сотрудники используют общие ключи API и квоты движков. Уровень «Полный» у Claude Code (`bypassPermissions`) выполняет любые команды без подтверждения — выдавайте его осознанно.
99
+ > Режим агента ограничивает его действия, но не является песочницей: агент работает с правами учётной записи, под которой запущен бот. Рабочая папка проекта задаёт, где он начинает работу, но не запрещает читать и писать за её пределами. Все сотрудники используют общие ключи API и квоты движков. Процесс агента не получает токен бота, а из ключей API — только ключи своего движка (Claude Code — `ANTHROPIC_API_KEY`, Codex — `OPENAI_API_KEY`, Gemini CLI и Antigravity — ключи Google, OpenCode — все), но файлы на диске, включая `.env` бота, агент прочитать может. Уровень «Полный» у Claude Code (`bypassPermissions`) выполняет любые команды без подтверждения — выдавайте его осознанно.
93
100
 
94
101
  ## Требования
95
102
 
@@ -250,6 +257,7 @@ npm start # первый запуск без .env сам открое
250
257
  | `ACPGRAM_DEBUG` | нет | `1` — подробный журнал отправляемого в Telegram в `data/debug.log` (до 5 МБ и один прошлый файл; по умолчанию выключен) |
251
258
  | `FILES_DIR` | нет | каталог принятых (`uploads`) и исходящих (`outbox`) файлов (по умолчанию — каталог данных бота) |
252
259
  | `FILES_KEEP_DAYS` | нет | сколько дней хранить такие файлы (по умолчанию 7) |
260
+ | `WIDGETS` | нет | `1` — показывать `/model` и `/sessions` виджетами, если Telegram разрешает их боту (по умолчанию выключено) |
253
261
  | `ANIMATED_ICONS` | нет | `0` — обычные эмодзи вместо анимированных иконок в черновике (если клиент Telegram показывает вместо них 🙂). По умолчанию включены |
254
262
 
255
263
  `.env` не попадает в Git. Токен и ключи API нельзя хранить в коде и коммитить.
@@ -330,6 +338,12 @@ src/
330
338
  projectsUi.mjs команда /project и навигация кнопками
331
339
  sessionsUi.mjs команда /sessions: возврат к прошлой сессии
332
340
  tools.mjs разбор событий вызовов инструментов агента
341
+ asks.mjs кнопки быстрого ответа от агента: метка [[ask: …]], разметка кнопок, выбор по нажатию
342
+ diff.mjs построчный дифф для запроса разрешения на правку файла
343
+ incoming.mjs входящие сообщения: цитата, неподдерживаемые виды, опечатки в командах
344
+ widgets.mjs HTML-виджеты: выбор модели, сессии проекта, лимиты Telegram, разбор запросов
345
+ widgetHost.mjs отправка виджета с откатом на обычное меню, память о сообщениях с виджетами
346
+ widgetsUi.mjs запросы от виджетов: выбор модели и уровня рассуждений, возобновление сессии
333
347
  engineUi.mjs команда /engine: выбор движка пользователя
334
348
  modelUi.mjs команда /model: модель и уровень рассуждений
335
349
  access.mjs права сотрудников на движки и модели, каталоги моделей, применение выбора к сессии
@@ -340,6 +354,7 @@ src/
340
354
  albums.mjs сбор альбомов Telegram (общий media_group_id) в один запрос
341
355
  db.mjs SQLite: сессии, запросы, инструменты, разрешения, сотрудники
342
356
  ctx.mjs общие настройки, база, логирование
357
+ log.mjs вывод в журнал с отметкой времени (общий для всех модулей)
343
358
  test/ тесты node:test и фиктивный ACP-агент (fixtures/)
344
359
  Dockerfile образ: Node 24, пять движков (Gemini CLI, Claude Code, Codex, Antigravity CLI, OpenCode; набор задаёт ENGINES), git, ripgrep, tini
345
360
  docker-compose.yml запуск в Docker: .env, папка проектов, тома для базы и настроек движков
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acpgram",
3
- "version": "1.20.1",
3
+ "version": "1.22.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,10 +8,11 @@ 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, autoValue, createAgent, engineCommand, engineVersion, isAuthError, isAvailable, parseCatalog, selectionRequest, setNeedsLogin } from './engines.mjs';
11
+ import { DEFAULT_ENGINE, ENGINES, agentEnv, autoValue, createAgent, engineCommand, engineVersion, isAuthError, isAvailable, parseCatalog, selectionRequest, setNeedsLogin } from './engines.mjs';
12
12
  import { t } from './i18n.mjs';
13
13
 
14
- const parseJson = (s, fallback) => {
14
+ /** JSON из строки; пусто или не разобралось — fallback. */
15
+ export const parseJson = (s, fallback) => {
15
16
  try {
16
17
  return s ? JSON.parse(s) : fallback;
17
18
  } catch {
@@ -93,7 +94,7 @@ export function killProbes() {
93
94
  */
94
95
  async function modelMeta(engine) {
95
96
  if (!engine.modelMeta) return null;
96
- const r = await checkCommand(engineCommand(engine), engine.modelMeta.args, 60_000);
97
+ const r = await checkCommand(engineCommand(engine), engine.modelMeta.args, 60_000, agentEnv(engine));
97
98
  if (!r.ok) {
98
99
  log(`${engine.label}: сведения о моделях не получены — ${r.error}`);
99
100
  return null;
package/src/acp.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  // для запуска ACP-агента (Gemini CLI, Claude Code, Antigravity CLI, Codex, OpenCode) как подпроцесса. Движки — в engines.mjs.
3
3
  import { spawn, spawnSync } from 'node:child_process';
4
4
  import readline from 'node:readline';
5
+ import { logError } from './log.mjs';
5
6
 
6
7
  const IS_WIN = process.platform === 'win32';
7
8
 
@@ -31,7 +32,7 @@ export function killTree(proc, graceMs = 3000) {
31
32
  if (IS_WIN) {
32
33
  const args = ['/pid', String(proc.pid), '/T', '/F'];
33
34
  if (syncKill) spawnSync('taskkill', args, { windowsHide: true });
34
- else spawn('taskkill', args, { windowsHide: true, stdio: 'ignore' }).on('error', (e) => console.error('[acp] taskkill:', e.message));
35
+ else spawn('taskkill', args, { windowsHide: true, stdio: 'ignore' }).on('error', (e) => logError('[acp] taskkill:', e.message));
35
36
  return;
36
37
  }
37
38
  const signal = (sig) => {
@@ -47,15 +48,16 @@ export function killTree(proc, graceMs = 3000) {
47
48
 
48
49
  /**
49
50
  * Проверяет, что команда агента запускается: `<команда> --version`.
51
+ * env — окружение процесса целиком (без него — окружение бота как есть).
50
52
  * @returns {Promise<{ok: boolean, version?: string, error?: string, timeout?: boolean}>}
51
53
  */
52
- export function checkCommand(command, args = ['--version'], timeoutMs = 60_000) {
54
+ export function checkCommand(command, args = ['--version'], timeoutMs = 60_000, env = null) {
53
55
  return new Promise((resolve) => {
54
56
  let out = '';
55
57
  let err = '';
56
58
  let proc;
57
59
  try {
58
- proc = spawnCommand(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
60
+ proc = spawnCommand(command, args, { stdio: ['ignore', 'pipe', 'pipe'], ...(env ? { env } : {}) });
59
61
  } catch (e) {
60
62
  return resolve({ ok: false, error: e.message });
61
63
  }
@@ -105,7 +107,7 @@ export class AcpAgent {
105
107
  * @param {string} o.command команда запуска агента
106
108
  * @param {string[]} [o.args] аргументы режима ACP
107
109
  * @param {string} [o.name] название агента для логов
108
- * @param {Record<string,string>} [o.env] дополнительные переменные окружения процесса агента (поверх окружения бота)
110
+ * @param {Record<string,string>} [o.env] окружение процесса агента целиком (engines.agentEnv: без токена бота); без него — окружение бота
109
111
  * @param {(p:object)=>Promise<object>} [o.onPermission] обработчик session/request_permission, возвращает outcome
110
112
  * @param {(u:object)=>void} [o.onUpdate] обработчик session/update
111
113
  * @param {(code:number|null)=>void} [o.onExit]
@@ -130,16 +132,15 @@ export class AcpAgent {
130
132
  }
131
133
 
132
134
  start() {
133
- // без своих переменных процесс наследует окружение бота как есть
134
- const env = this.env ? { ...process.env, ...this.env } : undefined;
135
- this.proc = spawnCommand(this.command, this.args, { cwd: this.cwd, stdio: ['pipe', 'pipe', 'pipe'], ...(env ? { env } : {}) });
135
+ // окружение задаётся целиком: с окружением бота не смешивается, иначе в него вернулся бы токен бота
136
+ this.proc = spawnCommand(this.command, this.args, { cwd: this.cwd, stdio: ['pipe', 'pipe', 'pipe'], ...(this.env ? { env: this.env } : {}) });
136
137
  readline.createInterface({ input: this.proc.stdout }).on('line', (l) => this.#onLine(l));
137
138
  const skip = quietStderrFilter(this.quietStderr, this.quietStderrBlock);
138
139
  readline.createInterface({ input: this.proc.stderr }).on('line', (l) => {
139
- if (!skip(l)) console.error(`[${this.name}:stderr]`, l);
140
+ if (!skip(l)) logError(`[${this.name}:stderr]`, l);
140
141
  });
141
142
  // запись в уже завершившийся процесс (EPIPE) не должна ронять бота
142
- this.proc.stdin.on('error', (e) => console.error('[acp] stdin:', e.message));
143
+ this.proc.stdin.on('error', (e) => logError('[acp] stdin:', e.message));
143
144
  // команда не найдена и т.п.: без обработчика 'error' Node уронит весь бот, а 'exit' может не прийти
144
145
  this.proc.on('error', (e) => this.#finish(null, `не удалось запустить ${this.command}: ${e.message}`));
145
146
  this.proc.on('exit', (code) => this.#finish(code, `${this.name} завершился (код ${code})`));
@@ -279,7 +280,7 @@ export class AcpAgent {
279
280
  try {
280
281
  this.onUpdate?.(msg.params.update);
281
282
  } catch (e) {
282
- console.error('[acp] ошибка в обработчике обновления:', e.message); // не роняем бота
283
+ logError('[acp] ошибка в обработчике обновления:', e.message); // не роняем бота
283
284
  }
284
285
  }
285
286
  }
package/src/admin.mjs CHANGED
@@ -7,8 +7,8 @@ import { DEFAULT_ENGINE, ENGINES } from './engines.mjs';
7
7
  import { t } from './i18n.mjs';
8
8
  import { activeSessions, closeSession, saveEngine, statesOf, stopUser } from './state.mjs';
9
9
  import { showPath } from './projects.mjs';
10
- import { activeSessionsView, engineGrants, modelGrantsOverview, modelGrantsView, sessionStatus } from './ui.mjs';
11
- import { tg } from './telegram.mjs';
10
+ import { activeSessionsView, engineGrants, modelGrantsOverview, modelGrantsView, sessionStatus, usageView } from './ui.mjs';
11
+ import { isNotModified, tg } from './telegram.mjs';
12
12
 
13
13
  const INVITE_TTL_MS = 24 * 3600_000;
14
14
  const REQUEST_COOLDOWN_MS = 3600_000; // повторный запрос доступа от одного человека — не чаще раза в час
@@ -37,7 +37,10 @@ export async function handleUnknownUser(from, chatId, text) {
37
37
  if (m) {
38
38
  const level = db.consumeInvite(m[1], from.id);
39
39
  if (!level) return say(chatId, t('access.inviteBad', lang));
40
- db.upsertUser({ user_id: from.id, username: from.username, first_name: from.first_name, level, added_by: ADMIN_ID });
40
+ if (!db.upsertUser({ user_id: from.id, username: from.username, first_name: from.first_name, level, added_by: ADMIN_ID })) {
41
+ log('доступ по приглашению не сохранён (ошибка базы)', from.id);
42
+ return say(chatId, t('access.saveFail', lang));
43
+ }
41
44
  db.setRequestStatus(from.id, 'approved');
42
45
  log('подключён по приглашению', from.id, from.username, level);
43
46
  await say(chatId, grantedText(level, lang, false));
@@ -77,8 +80,10 @@ export async function adminCommand(chatId, command) {
77
80
  reply_markup: { inline_keyboard: LEVEL_KEYS.map((key) => [{ text: `${levelName(key, al)} — ${levelHint(key, al)}`, callback_data: `adm:i:${key}` }]) },
78
81
  });
79
82
  }
80
- if (command === '/active') return say(chatId, activeView().text, { reply_markup: activeView().markup });
81
- if (command === '/users') return say(chatId, usersView().text, { reply_markup: usersView().markup });
83
+ if (command === '/active' || command === '/users' || command === '/usage') {
84
+ const v = command === '/active' ? activeView() : command === '/usage' ? usageScreen(1) : usersView();
85
+ return say(chatId, v.text, { reply_markup: v.markup });
86
+ }
82
87
  }
83
88
 
84
89
  function usersView() {
@@ -98,6 +103,10 @@ const ownerName = (id) => (id === ADMIN_ID ? t('active.owner', adminLang()) : db
98
103
  /** Активные сессии: кто занимает слоты, с кнопками точечного завершения (для сотрудников). */
99
104
  const activeView = () => activeSessionsView({ sessions: activeSessions(), adminId: ADMIN_ID, maxAgents: MAX_AGENTS, nameOf: ownerName, projectOf: (p) => showPath(p, adminLang()), lang: adminLang() });
100
105
 
106
+ /** Расход по пользователям за days суток (экран /usage, кнопки периода adm:us:<дни>). */
107
+ const usageScreen = (days, now = Date.now()) =>
108
+ usageView({ rows: db.usageSummary(new Date(now - days * 24 * 3600_000).toISOString()), days, nameOf: ownerName, lang: adminLang() });
109
+
101
110
  /** Движки сотрудника для карточки: все движки реестра, отметка выданных. */
102
111
  const engineList = (userId) => {
103
112
  const granted = grantedEngines(userId);
@@ -130,17 +139,17 @@ function userCard(u) {
130
139
  };
131
140
  }
132
141
 
133
- /** Все кнопки adm:* — только от главного администратора (проверяется в bot.mjs). */
134
142
  /** Открытая администратором группа и страница моделей сотрудника в движке (`${userId}:${движок}` → {group, page}). */
135
143
  const grantsPage = new Map();
136
144
 
145
+ /** Все кнопки adm:* — только от главного администратора (проверяется в bot.mjs). */
137
146
  export async function onAdminCallback(cb) {
138
147
  const [, action, a, b] = cb.data.split(':');
139
148
  const al = adminLang();
140
149
  const chatId = cb.message?.chat?.id;
141
150
  const messageId = cb.message?.message_id;
142
151
  const ack = (text) => tg('answerCallbackQuery', { callback_query_id: cb.id, ...(text ? { text } : {}) }).catch(() => {});
143
- const edit = (text, markup) => tg('editMessageText', { chat_id: chatId, message_id: messageId, text, reply_markup: markup ?? { inline_keyboard: [] } }).catch((e) => log('adm edit:', e.message));
152
+ const edit = (text, markup) => tg('editMessageText', { chat_id: chatId, message_id: messageId, text, reply_markup: markup ?? { inline_keyboard: [] } }).catch((e) => isNotModified(e) || log('adm edit:', e.message));
144
153
  const id = Number(a);
145
154
 
146
155
  // ссылка-приглашение
@@ -165,7 +174,10 @@ export async function onAdminCallback(cb) {
165
174
  return edit(t('adm.reqRejected', al, { name }));
166
175
  }
167
176
  if (!isLevel(b)) return ack(t('adm.ackNoLevel', al));
168
- db.upsertUser({ user_id: id, username: req.username, first_name: req.first_name, level: b, added_by: ADMIN_ID });
177
+ if (!db.upsertUser({ user_id: id, username: req.username, first_name: req.first_name, level: b, added_by: ADMIN_ID })) {
178
+ log('доступ по запросу не сохранён (ошибка базы)', id);
179
+ return ack(t('access.saveFail', al));
180
+ }
169
181
  db.setRequestStatus(id, 'approved');
170
182
  log('доступ выдан по запросу', id, b);
171
183
  await ack();
@@ -184,6 +196,11 @@ export async function onAdminCallback(cb) {
184
196
  const v = activeView();
185
197
  return edit(v.text, v.markup);
186
198
  }
199
+ if (action === 'us') {
200
+ await ack();
201
+ const v = usageScreen([1, 7, 30].includes(id) ? id : 1);
202
+ return edit(v.text, v.markup);
203
+ }
187
204
  const user = db.getUser(id);
188
205
  if (!user || user.status !== 'active') {
189
206
  await ack(t('adm.ackNoUser', al));
package/src/app.mjs CHANGED
@@ -32,6 +32,15 @@ export function resolveHomeDir(env = process.env, appDir = APP_DIR) {
32
32
  return appDir;
33
33
  }
34
34
 
35
+ /**
36
+ * Положительное число из переменной окружения; пусто, не число, ноль или отрицательное — значение по умолчанию.
37
+ * Без этой проверки «MAX_AGENTS=abc» давало NaN: сравнение с ним всегда ложно, и лимит молча отключался.
38
+ */
39
+ export function positiveEnv(name, fallback, env = process.env) {
40
+ const n = Number(env[name]);
41
+ return Number.isFinite(n) && n > 0 ? n : fallback;
42
+ }
43
+
35
44
  export const HOME_DIR = resolveHomeDir();
36
45
  export const ENV_PATH = join(HOME_DIR, '.env');
37
46
  export const DATA_DIR = join(HOME_DIR, 'data');
package/src/asks.mjs ADDED
@@ -0,0 +1,107 @@
1
+ // Кнопки быстрого ответа от агента. Агент не может рисовать кнопки сам (теги <tg-button> в его тексте обезвреживаются,
2
+ // ui.neutralizeTgTags): он пишет метку [[ask: Вариант А | Вариант Б]], а кнопки строит бот. Нажатие отправляет текст
3
+ // варианта агенту как следующее сообщение пользователя — ничего, кроме этого, такая кнопка сделать не может.
4
+ import { splitCode } from './files.mjs';
5
+ import { escHtml } from './telegram.mjs';
6
+
7
+ /** Сколько вариантов в одной метке и меток в одном ответе; длина подписи кнопки. */
8
+ export const MAX_OPTIONS = 6;
9
+ export const MAX_ASKS = 3;
10
+ export const MAX_LABEL = 48;
11
+ /** Сколько наборов вариантов помнит диалог (кнопки более старых ответов — «устарели»). */
12
+ const KEEP_ASKS = 20;
13
+
14
+ /** Подсказка агенту (служебный текст — на английском), уходит вместе с подсказкой об отправке файлов. */
15
+ export const ASK_NOTE =
16
+ '[AcpGram] To offer the user quick-reply buttons, put [[ask: Option A | Option B]] on its own line in your reply ' +
17
+ `(2-${MAX_OPTIONS} short options, in the language of the conversation). A tap sends the option text as the user's next message. ` +
18
+ 'Use it when you ask the user to choose or confirm something; do not add it to every reply.';
19
+
20
+ const MARK = /\[\[ask:([^\]\r\n]*)\]\]/gi;
21
+
22
+ /** Заглушка на месте метки: туда встанут кнопки. Символ \u0001 в ответе агента не встречается. */
23
+ // eslint-disable-next-line no-control-regex -- \u0001 — служебная метка места кнопок в тексте ответа
24
+ export const ASK_PLACEHOLDER = /\u0001(\d+)\u0001/g;
25
+
26
+ const cleanOption = (s) => {
27
+ const one = s.replace(/\s+/g, ' ').trim();
28
+ const chars = [...one];
29
+ return chars.length > MAX_LABEL ? `${chars.slice(0, MAX_LABEL - 1).join('')}…` : one;
30
+ };
31
+
32
+ /**
33
+ * Достаёт из ответа агента метки [[ask: …]] (вне кода): на их месте остаются заглушки, варианты возвращаются списком.
34
+ * Метка без вариантов или сверх MAX_ASKS просто убирается.
35
+ * @returns {{text: string, asks: string[][]}}
36
+ */
37
+ export function extractAsks(text) {
38
+ const src = String(text ?? '');
39
+ if (!/\[\[ask:/i.test(src)) return { text: src, asks: [] };
40
+ const asks = [];
41
+ const out = splitCode(src)
42
+ .map(({ code, s }) => {
43
+ if (code) return s;
44
+ return s.replace(MARK, (_, body) => {
45
+ const options = [...new Set(body.split('|').map(cleanOption).filter(Boolean))].slice(0, MAX_OPTIONS);
46
+ if (!options.length || asks.length >= MAX_ASKS) return '';
47
+ asks.push(options);
48
+ return `\u0001${asks.length - 1}\u0001`;
49
+ });
50
+ })
51
+ .join('');
52
+ return { text: out, asks };
53
+ }
54
+
55
+ /** Для черновика: убирает метки, в том числе ещё не дописанные в потоке («[[ask: Да | Н», «[[as»). Код не трогает. */
56
+ export function stripAskMarks(text) {
57
+ const src = String(text ?? '');
58
+ if (!src.includes('[')) return src;
59
+ const parts = splitCode(src);
60
+ return parts
61
+ .map(({ code, s }, i) => {
62
+ if (code) return s;
63
+ const r = s.replace(/\[\[ask:[^\]\r\n]*(?:\]\]?)?/gi, '');
64
+ return i === parts.length - 1 ? r.replace(/\[{1,2}(?:a(?:s(?:k)?)?)?$/i, '') : r;
65
+ })
66
+ .join('');
67
+ }
68
+
69
+ /**
70
+ * Разметка кнопок набора вариантов: callback_data — ask:<id набора>:<номер варианта>, текст варианта в неё не попадает.
71
+ * Короткие варианты — до трёх в ряд, длинные — по одному.
72
+ */
73
+ export function askButtons(id, options) {
74
+ const perRow = options.every((o) => [...o].length <= 16) ? 3 : 1;
75
+ const rows = [];
76
+ for (let i = 0; i < options.length; i += perRow) {
77
+ const buttons = options.slice(i, i + perRow).map((o, k) => `<tg-button type="callback_data" data="ask:${id}:${i + k}">${escHtml(o)}</tg-button>`);
78
+ rows.push(`<tg-button-row>${buttons.join('')}</tg-button-row>`);
79
+ }
80
+ return rows.join('\n');
81
+ }
82
+
83
+ let askSeq = 0;
84
+
85
+ /**
86
+ * Ставит кнопки на место заглушек и запоминает варианты в диалоге (st.asks: id → варианты).
87
+ * @param {{asks?: Map<number, string[]>}} st состояние диалога
88
+ */
89
+ export function placeAsks(st, text, asks) {
90
+ if (!asks.length) return String(text ?? '').replace(ASK_PLACEHOLDER, '');
91
+ st.asks ??= new Map();
92
+ const out = String(text ?? '').replace(ASK_PLACEHOLDER, (_, n) => {
93
+ const options = asks[Number(n)];
94
+ if (!options) return '';
95
+ const id = ++askSeq;
96
+ st.asks.set(id, options);
97
+ return `\n\n${askButtons(id, options)}\n\n`;
98
+ });
99
+ while (st.asks.size > KEEP_ASKS) st.asks.delete(st.asks.keys().next().value);
100
+ return out.replace(/\n{3,}/g, '\n\n').trim();
101
+ }
102
+
103
+ /** Текст варианта по данным кнопки (ask:<id>:<номер>) или null, если кнопка устарела. */
104
+ export function askChoice(st, data) {
105
+ const m = /^ask:(\d+):(\d+)$/.exec(data || '');
106
+ return (m && st.asks?.get(Number(m[1]))?.[Number(m[2])]) || null;
107
+ }