acpgram 1.12.0 → 1.12.1

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/src/winsvc.mjs CHANGED
@@ -1,122 +1,122 @@
1
- // Windows: разбор вывода sc.exe / tasklist / reg.exe и поиск программ — БЕЗ зависимости от языка системы и кодовой страницы консоли.
2
- //
3
- // Почему так. На русской Windows sc.exe печатает подписи по-русски («Состояние», «Код_выхода_Win32», …), в кодовой
4
- // странице OEM (cp866), а `where` — пути в ней же. Регулярки по подписям не срабатывают, и AcpGram «не видел» уже
5
- // существующую службу. Поэтому решения принимаются только по тому, что не переводится:
6
- // • код выхода sc.exe — это код ошибки Windows (0 — служба есть, 1060 — службы нет);
7
- // • значения состояний (RUNNING, STOP_PENDING…) и формат «число (0xHEX)» зашиты в sc.exe;
8
- // • ключи и значения реестра (DeleteFlag), столбцы CSV tasklist.
9
- // Текст вывода используется только для показа пользователю.
10
- import { win32 } from 'node:path';
11
-
12
- /** Код Windows «служба не существует» (ERROR_SERVICE_DOES_NOT_EXIST) — его возвращает sc.exe как код выхода. */
13
- export const ERROR_SERVICE_DOES_NOT_EXIST = 1060;
14
-
15
- /**
16
- * Есть ли служба — по коду выхода `sc.exe query`: true (0), false (1060) или null — не удалось узнать
17
- * (запуск sc.exe запрещён, нет прав — 5 и т.п.). null нельзя путать ни с «есть», ни с «нет».
18
- * @param {{status: number|null, error?: string}} r
19
- */
20
- export function serviceExists(r) {
21
- if (r?.error || r?.status == null) return null;
22
- if (r.status === 0) return true;
23
- return r.status === ERROR_SERVICE_DOES_NOT_EXIST ? false : null;
24
- }
25
-
26
- const STATES = 'STOPPED|START_PENDING|STOP_PENDING|RUNNING|CONTINUE_PENDING|PAUSE_PENDING|PAUSED';
27
-
28
- /**
29
- * Состояние службы из `sc query`: по «: N ЗНАЧЕНИЕ» из закрытого списка значений, подпись не нужна
30
- * («Состояние», «STATE», …). Строка «ТИП : 10 WIN32_OWN_PROCESS» под список не подходит. null — не нашли.
31
- */
32
- export function serviceState(scQueryOutput) {
33
- const m = new RegExp(`:\\s*[1-7]\\s+(${STATES})\\b`).exec(scQueryOutput ?? '');
34
- return m ? m[1] : null;
35
- }
36
-
37
- /**
38
- * Код ошибки службы из вывода sc.exe:
39
- * `sc start` → «[SC] StartService FAILED 1069:» (слово FAILED на другом языке — другое, число то же);
40
- * `sc query` → первая пара «число (0xHEX)» — WIN32_EXIT_CODE, вторая — SERVICE_EXIT_CODE (его берём при 1066).
41
- * Подписи не нужны. null — ошибки нет.
42
- */
43
- export function serviceErrorCode(scOutput) {
44
- const text = scOutput ?? '';
45
- const start = /StartService\D{0,40}?(\d{3,5})\s*:/.exec(text);
46
- if (start) return Number(start[1]) || null;
47
- const pairs = [...text.matchAll(/:\s*(\d+)\s+\(0x[0-9a-fA-F]+\)/g)].map((m) => Number(m[1]));
48
- const code = pairs[0] === 1066 ? pairs[1] : pairs[0];
49
- return code || null;
50
- }
51
-
52
- /** PID процесса службы из `tasklist /svc /fi "SERVICES eq имя" /fo csv /nh`; строки без кавычек (сообщение «нет задач» на любом языке) пропускаются. */
53
- export function parseTasklistPid(output) {
54
- const m = /^"[^"]*","(\d+)",/m.exec(output ?? '');
55
- return m && Number(m[1]) ? Number(m[1]) : null;
56
- }
57
-
58
- /** Аргументы `reg query` для флага «помечена для удаления». Путь собирается без String.raw: он не может заканчиваться на «\». */
59
- export const deleteFlagArgs = (name) => ['query', `HKLM\\SYSTEM\\CurrentControlSet\\Services\\${name}`, '/v', 'DeleteFlag'];
60
-
61
- /** Служба помечена для удаления (DeleteFlag = 1): код выхода 0 и «REG_DWORD 0x1». Без значения reg.exe возвращает 1. */
62
- export const parseDeleteFlag = (r) => r?.status === 0 && /DeleteFlag\s+REG_DWORD\s+0x0*1\b/i.test(r.stdout ?? '');
63
-
64
- /**
65
- * Причина отказа `nssm install` (сам nssm пишет только «CreateService(): …» без номера, а текст на русской Windows
66
- * превращается в «????»). Определяется по состоянию службы, а не по сообщению nssm.
67
- * @param {{exists: boolean|null, marked: boolean, keyNameTaken: boolean, nssmStatus?: number|null, name: string}} d
68
- */
69
- export function diagnoseCreate({ exists, marked, keyNameTaken, nssmStatus = null, name }) {
70
- if (exists && marked) return { code: 1072, text: `служба ${name} помечена для удаления (ошибка Windows 1072)` };
71
- if (exists) return { code: 1073, text: `служба ${name} уже существует (ошибка Windows 1073): выполните acpgram service uninstall` };
72
- if (keyNameTaken) return { code: 1078, text: `имя ${name} или отображаемое имя службы уже занято другой службой (ошибка Windows 1078)` };
73
- if (exists === null) return { code: null, text: `не удалось определить причину: sc.exe недоступен${nssmStatus != null ? ` (nssm вернул код ${nssmStatus})` : ''}` };
74
- return { code: null, text: `Windows отказал в создании службы${nssmStatus != null ? ` (nssm вернул код ${nssmStatus})` : ''}` };
75
- }
76
-
77
- /** Сообщение Windows, нечитаемое в этой кодировке: nssm выводит «?», а UTF-8-разбор OEM-текста даёт U+FFFD. */
78
- export const isGarbled = (text) => /\?{4,}|�{3,}/.test(text ?? '');
79
-
80
- /**
81
- * Текст вывода консольной программы Windows:
82
- * UTF-16LE (нули между символами) → utf16le; корректный UTF-8 → как есть;
83
- * иначе — кодовая страница OEM (cp866 на русской Windows; 437/850 браузерный TextDecoder не знает — latin1).
84
- */
85
- export function decodeOutput(buf, oemcp = 0) {
86
- if (!buf?.length) return '';
87
- const b = Buffer.from(buf);
88
- let zeroOdd = 0;
89
- for (let i = 1; i < b.length; i += 2) if (b[i] === 0) zeroOdd++;
90
- if (b.length >= 4 && zeroOdd >= b.length / 4) return b.toString('utf16le').replace(/^/, '');
91
- const plain = b.includes(0) ? Buffer.from(b.filter((x) => x !== 0)) : b;
92
- try {
93
- return new TextDecoder('utf-8', { fatal: true }).decode(plain);
94
- } catch {
95
- /* не UTF-8 — кодовая страница консоли */
96
- }
97
- for (const label of [`ibm${oemcp}`, `windows-${oemcp}`]) {
98
- try {
99
- return new TextDecoder(label).decode(plain);
100
- } catch {
101
- /* кодировка неизвестна */
102
- }
103
- }
104
- return plain.toString('latin1');
105
- }
106
-
107
- /** Кодовая страница OEM из вывода `reg query …\Nls\CodePage /v OEMCP` («OEMCP REG_SZ 866»). */
108
- export const parseOemCp = (output) => Number(/OEMCP\s+REG_SZ\s+(\d+)/.exec(output ?? '')?.[1]) || 0;
109
-
110
- /**
111
- * Поиск программы по PATH средствами Node (строки без кодовых страниц, в отличие от `where`, который в профиле
112
- * с кириллицей выдаёт пути в cp866). Возвращает первый найденный файл или null.
113
- * @param {string} cmd имя без расширения («gemini») или с ним («gemini.cmd»)
114
- * @param {{pathVar?: string, exts?: string[], exists: (p: string) => boolean, extra?: string[]}} o
115
- */
116
- export function findOnPath(cmd, { pathVar = process.env.PATH ?? process.env.Path ?? '', exts = ['.exe', '.cmd', '.bat'], exists, extra = [] } = {}) {
117
- const dirs = [...pathVar.split(';').map((d) => d.trim().replace(/^"|"$/g, '')).filter(Boolean), ...extra];
118
- // имя уже с расширением («gemini.cmd», «codex-acp.cmd») — проверяем как есть, иначе получилось бы «codex-acp.cmd.cmd»
119
- const hasExt = exts.some((e) => cmd.toLowerCase().endsWith(e));
120
- for (const dir of dirs) for (const ext of hasExt ? [''] : exts) if (exists(win32.join(dir, cmd + ext))) return win32.join(dir, cmd + ext);
121
- return null;
122
- }
1
+ // Windows: разбор вывода sc.exe / tasklist / reg.exe и поиск программ — БЕЗ зависимости от языка системы и кодовой страницы консоли.
2
+ //
3
+ // Почему так. На русской Windows sc.exe печатает подписи по-русски («Состояние», «Код_выхода_Win32», …), в кодовой
4
+ // странице OEM (cp866), а `where` — пути в ней же. Регулярки по подписям не срабатывают, и AcpGram «не видел» уже
5
+ // существующую службу. Поэтому решения принимаются только по тому, что не переводится:
6
+ // • код выхода sc.exe — это код ошибки Windows (0 — служба есть, 1060 — службы нет);
7
+ // • значения состояний (RUNNING, STOP_PENDING…) и формат «число (0xHEX)» зашиты в sc.exe;
8
+ // • ключи и значения реестра (DeleteFlag), столбцы CSV tasklist.
9
+ // Текст вывода используется только для показа пользователю.
10
+ import { win32 } from 'node:path';
11
+
12
+ /** Код Windows «служба не существует» (ERROR_SERVICE_DOES_NOT_EXIST) — его возвращает sc.exe как код выхода. */
13
+ export const ERROR_SERVICE_DOES_NOT_EXIST = 1060;
14
+
15
+ /**
16
+ * Есть ли служба — по коду выхода `sc.exe query`: true (0), false (1060) или null — не удалось узнать
17
+ * (запуск sc.exe запрещён, нет прав — 5 и т.п.). null нельзя путать ни с «есть», ни с «нет».
18
+ * @param {{status: number|null, error?: string}} r
19
+ */
20
+ export function serviceExists(r) {
21
+ if (r?.error || r?.status == null) return null;
22
+ if (r.status === 0) return true;
23
+ return r.status === ERROR_SERVICE_DOES_NOT_EXIST ? false : null;
24
+ }
25
+
26
+ const STATES = 'STOPPED|START_PENDING|STOP_PENDING|RUNNING|CONTINUE_PENDING|PAUSE_PENDING|PAUSED';
27
+
28
+ /**
29
+ * Состояние службы из `sc query`: по «: N ЗНАЧЕНИЕ» из закрытого списка значений, подпись не нужна
30
+ * («Состояние», «STATE», …). Строка «ТИП : 10 WIN32_OWN_PROCESS» под список не подходит. null — не нашли.
31
+ */
32
+ export function serviceState(scQueryOutput) {
33
+ const m = new RegExp(`:\\s*[1-7]\\s+(${STATES})\\b`).exec(scQueryOutput ?? '');
34
+ return m ? m[1] : null;
35
+ }
36
+
37
+ /**
38
+ * Код ошибки службы из вывода sc.exe:
39
+ * `sc start` → «[SC] StartService FAILED 1069:» (слово FAILED на другом языке — другое, число то же);
40
+ * `sc query` → первая пара «число (0xHEX)» — WIN32_EXIT_CODE, вторая — SERVICE_EXIT_CODE (его берём при 1066).
41
+ * Подписи не нужны. null — ошибки нет.
42
+ */
43
+ export function serviceErrorCode(scOutput) {
44
+ const text = scOutput ?? '';
45
+ const start = /StartService\D{0,40}?(\d{3,5})\s*:/.exec(text);
46
+ if (start) return Number(start[1]) || null;
47
+ const pairs = [...text.matchAll(/:\s*(\d+)\s+\(0x[0-9a-fA-F]+\)/g)].map((m) => Number(m[1]));
48
+ const code = pairs[0] === 1066 ? pairs[1] : pairs[0];
49
+ return code || null;
50
+ }
51
+
52
+ /** PID процесса службы из `tasklist /svc /fi "SERVICES eq имя" /fo csv /nh`; строки без кавычек (сообщение «нет задач» на любом языке) пропускаются. */
53
+ export function parseTasklistPid(output) {
54
+ const m = /^"[^"]*","(\d+)",/m.exec(output ?? '');
55
+ return m && Number(m[1]) ? Number(m[1]) : null;
56
+ }
57
+
58
+ /** Аргументы `reg query` для флага «помечена для удаления». Путь собирается без String.raw: он не может заканчиваться на «\». */
59
+ export const deleteFlagArgs = (name) => ['query', `HKLM\\SYSTEM\\CurrentControlSet\\Services\\${name}`, '/v', 'DeleteFlag'];
60
+
61
+ /** Служба помечена для удаления (DeleteFlag = 1): код выхода 0 и «REG_DWORD 0x1». Без значения reg.exe возвращает 1. */
62
+ export const parseDeleteFlag = (r) => r?.status === 0 && /DeleteFlag\s+REG_DWORD\s+0x0*1\b/i.test(r.stdout ?? '');
63
+
64
+ /**
65
+ * Причина отказа `nssm install` (сам nssm пишет только «CreateService(): …» без номера, а текст на русской Windows
66
+ * превращается в «????»). Определяется по состоянию службы, а не по сообщению nssm.
67
+ * @param {{exists: boolean|null, marked: boolean, keyNameTaken: boolean, nssmStatus?: number|null, name: string}} d
68
+ */
69
+ export function diagnoseCreate({ exists, marked, keyNameTaken, nssmStatus = null, name }) {
70
+ if (exists && marked) return { code: 1072, text: `служба ${name} помечена для удаления (ошибка Windows 1072)` };
71
+ if (exists) return { code: 1073, text: `служба ${name} уже существует (ошибка Windows 1073): выполните acpgram service uninstall` };
72
+ if (keyNameTaken) return { code: 1078, text: `имя ${name} или отображаемое имя службы уже занято другой службой (ошибка Windows 1078)` };
73
+ if (exists === null) return { code: null, text: `не удалось определить причину: sc.exe недоступен${nssmStatus != null ? ` (nssm вернул код ${nssmStatus})` : ''}` };
74
+ return { code: null, text: `Windows отказал в создании службы${nssmStatus != null ? ` (nssm вернул код ${nssmStatus})` : ''}` };
75
+ }
76
+
77
+ /** Сообщение Windows, нечитаемое в этой кодировке: nssm выводит «?», а UTF-8-разбор OEM-текста даёт U+FFFD. */
78
+ export const isGarbled = (text) => /\?{4,}|�{3,}/.test(text ?? '');
79
+
80
+ /**
81
+ * Текст вывода консольной программы Windows:
82
+ * UTF-16LE (нули между символами) → utf16le; корректный UTF-8 → как есть;
83
+ * иначе — кодовая страница OEM (cp866 на русской Windows; 437/850 браузерный TextDecoder не знает — latin1).
84
+ */
85
+ export function decodeOutput(buf, oemcp = 0) {
86
+ if (!buf?.length) return '';
87
+ const b = Buffer.from(buf);
88
+ let zeroOdd = 0;
89
+ for (let i = 1; i < b.length; i += 2) if (b[i] === 0) zeroOdd++;
90
+ if (b.length >= 4 && zeroOdd >= b.length / 4) return b.toString('utf16le').replace(/^/, '');
91
+ const plain = b.includes(0) ? Buffer.from(b.filter((x) => x !== 0)) : b;
92
+ try {
93
+ return new TextDecoder('utf-8', { fatal: true }).decode(plain);
94
+ } catch {
95
+ /* не UTF-8 — кодовая страница консоли */
96
+ }
97
+ for (const label of [`ibm${oemcp}`, `windows-${oemcp}`]) {
98
+ try {
99
+ return new TextDecoder(label).decode(plain);
100
+ } catch {
101
+ /* кодировка неизвестна */
102
+ }
103
+ }
104
+ return plain.toString('latin1');
105
+ }
106
+
107
+ /** Кодовая страница OEM из вывода `reg query …\Nls\CodePage /v OEMCP` («OEMCP REG_SZ 866»). */
108
+ export const parseOemCp = (output) => Number(/OEMCP\s+REG_SZ\s+(\d+)/.exec(output ?? '')?.[1]) || 0;
109
+
110
+ /**
111
+ * Поиск программы по PATH средствами Node (строки без кодовых страниц, в отличие от `where`, который в профиле
112
+ * с кириллицей выдаёт пути в cp866). Возвращает первый найденный файл или null.
113
+ * @param {string} cmd имя без расширения («gemini») или с ним («gemini.cmd»)
114
+ * @param {{pathVar?: string, exts?: string[], exists: (p: string) => boolean, extra?: string[]}} o
115
+ */
116
+ export function findOnPath(cmd, { pathVar = process.env.PATH ?? process.env.Path ?? '', exts = ['.exe', '.cmd', '.bat'], exists, extra = [] } = {}) {
117
+ const dirs = [...pathVar.split(';').map((d) => d.trim().replace(/^"|"$/g, '')).filter(Boolean), ...extra];
118
+ // имя уже с расширением («gemini.cmd», «codex-acp.cmd») — проверяем как есть, иначе получилось бы «codex-acp.cmd.cmd»
119
+ const hasExt = exts.some((e) => cmd.toLowerCase().endsWith(e));
120
+ for (const dir of dirs) for (const ext of hasExt ? [''] : exts) if (exists(win32.join(dir, cmd + ext))) return win32.join(dir, cmd + ext);
121
+ return null;
122
+ }
package/README.en.md DELETED
@@ -1,230 +0,0 @@
1
- # AcpGram
2
-
3
- [![npm version](https://img.shields.io/npm/v/acpgram.svg)](https://www.npmjs.com/package/acpgram)
4
- [![Node.js](https://img.shields.io/badge/node-%3E%3D22.13.0-brightgreen.svg)](https://nodejs.org)
5
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
-
7
- **English** · [Русский](README.md)
8
-
9
- A Telegram gateway to AI coding agents — **Gemini CLI**, **Claude Code**, **Antigravity CLI** and **OpenAI Codex**. The bot runs the agent as a subprocess on the machine where it is installed and talks to it over the [Agent Client Protocol](https://agentclientprotocol.com) (JSON-RPC over stdin/stdout). You write a task in Telegram; the agent works in the selected project on your server, PC or laptop, and you watch its progress, approve its actions and get the answer right in the chat.
10
-
11
- - No npm dependencies — plain Node.js 24 (built-in `node:sqlite`, `fetch`).
12
- - Windows, Linux and macOS. Tested on Windows Server and Linux (Ubuntu in WSL); macOS uses the same code as Linux.
13
- - Multi-user: the main admin invites teammates and controls what each of them can do.
14
-
15
- > The bot's interface is currently in Russian.
16
-
17
- ## Features
18
-
19
- - **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.
20
- - **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 time.
21
- - **Four engines, one interface** — `/engine` switches between Gemini CLI, Claude Code, Antigravity CLI and Codex; the default engine is set in `.env`.
22
- - **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.
23
- - **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.
24
- - **Projects** — `/project` picks the working folder by buttons, by name search or by path (`/project ~/projects/web`), with one-tap recent projects.
25
- - **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.
26
- - **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.
27
- - **Audit log** — SQLite database with sessions, requests, tool calls, permissions, answers, token usage and cost.
28
-
29
- ## Supported engines
30
-
31
- | Engine | How it is started | Install | Auth |
32
- |---|---|---|---|
33
- | [Gemini CLI](https://github.com/google-gemini/gemini-cli) | `gemini --acp` | `npm i -g @google/gemini-cli` | `GEMINI_API_KEY` or Gemini CLI login |
34
- | [Claude Code](https://www.anthropic.com/claude-code) | `claude-agent-acp` ([ACP bridge](https://www.npmjs.com/package/@agentclientprotocol/claude-agent-acp)) | `npm i -g @agentclientprotocol/claude-agent-acp` | `ANTHROPIC_API_KEY` or Claude Code login |
35
- | [Antigravity CLI](https://antigravity.google/docs/cli/acp/) 1.5+ | `agy acp` | see Antigravity docs | Google sign-in once: `agy acp --login` |
36
- | [OpenAI Codex](https://github.com/openai/codex) | `codex-acp` ([ACP bridge](https://www.npmjs.com/package/@agentclientprotocol/codex-acp)) | `npm i -g @agentclientprotocol/codex-acp` (Codex CLI required) | `OPENAI_API_KEY` or `codex login`; on Windows `read-only`/`workspace-write` need a working Codex sandbox |
37
-
38
- Only the default engine (`DEFAULT_ENGINE`, Gemini CLI unless set) is required; the others are optional — engines that are not installed are simply not offered.
39
-
40
- ## Quick start
41
-
42
- You need at least one engine from the table above and a Telegram bot token from [@BotFather](https://t.me/BotFather) (Bot API 10.1+ — rich messages and drafts).
43
-
44
- ### Option 1. Install via npm (requires Node.js 22.13+)
45
-
46
- ```bash
47
- npm install -g acpgram
48
- ```
49
-
50
- Then run the setup wizard:
51
- ```bash
52
- acpgram setup
53
- ```
54
-
55
- Settings (`.env`) and SQLite database (`data/bot.db`) are stored in `~/.acpgram` (or `ACPGRAM_HOME`), so updating via `npm install -g acpgram@latest` keeps all settings and history intact.
56
-
57
- #### Migrating from install.ps1 (resolving PATH conflict)
58
- The `install.ps1` script adds `%LOCALAPPDATA%\acpgram\bin` to the user `PATH`. If you switch to the npm installation, Windows might still invoke the old script due to `PATH` order.
59
-
60
- To switch:
61
- 1. Stop and uninstall any previous service:
62
- ```powershell
63
- acpgram service uninstall
64
- ```
65
- 2. Check which binary is resolved:
66
- ```powershell
67
- Get-Command acpgram
68
- ```
69
- 3. Remove `%LOCALAPPDATA%\acpgram\bin` from user `PATH`:
70
- ```powershell
71
- [Environment]::SetEnvironmentVariable("Path", (([Environment]::GetEnvironmentVariable("Path", "User") -split ';') | Where-Object { $_ -notlike '*\acpgram\bin' }) -join ';', "User")
72
- ```
73
- 4. Optionally copy your previous settings and database:
74
- ```powershell
75
- New-Item -ItemType Directory -Force "$HOME\.acpgram"
76
- Copy-Item "$env:LOCALAPPDATA\acpgram\.env" "$HOME\.acpgram\.env"
77
- if (Test-Path "$env:LOCALAPPDATA\acpgram\data") { Copy-Item -Recurse "$env:LOCALAPPDATA\acpgram\data" "$HOME\.acpgram\" }
78
- ```
79
- 5. Restart your terminal window.
80
-
81
- ### Option 2. One-line installer
82
-
83
- **Windows** (PowerShell):
84
-
85
- ```powershell
86
- irm https://raw.githubusercontent.com/selesnow/acpgram/main/install.ps1 | iex
87
- ```
88
-
89
- **Linux / macOS**:
90
-
91
- ```bash
92
- curl -fsSL https://raw.githubusercontent.com/selesnow/acpgram/main/install.sh | bash
93
- ```
94
-
95
- The installer downloads the latest [release](https://github.com/selesnow/acpgram/releases) (checksum verified) into `%LOCALAPPDATA%\acpgram` or `~/.local/share/acpgram`, installs a private Node.js 24 if yours is missing or older (official build, checksum verified, no admin rights), adds the `acpgram` command to your PATH and starts the setup wizard. Run it again — or `acpgram update` — to update; your settings and data are kept.
96
-
97
- ```text
98
- acpgram start the bot
99
- acpgram setup settings wizard
100
- acpgram service install run as a service (also: restart, status, uninstall)
101
- acpgram update update to the latest release
102
- ```
103
-
104
- From source instead (Node.js 24+): `git clone https://github.com/selesnow/acpgram.git && cd acpgram && npm start` — npm scripts mirror the commands: `npm run setup`, `npm run service:install`.
105
-
106
- The **setup wizard** (`acpgram setup` / `npm run setup`, safe to re-run — current values are suggested):
107
-
108
- 1. bot token — checked right away with `getMe`;
109
- 2. main admin — just send any message to your bot, the wizard picks up your Telegram ID;
110
- 3. projects root — optional (see `PROJECTS_ROOT` below);
111
- 4. engines — finds installed Gemini CLI, Claude Code and Antigravity CLI, stores their full paths (so they are found under a service too), asks for the default engine;
112
- 5. API keys — optional; the token, keys and passwords are typed hidden;
113
- 6. writes `.env` (owner-only permissions; the previous one goes to `data/.env.bak`), creates the database and sends you a test message;
114
- 7. offers to install the bot as a service.
115
-
116
- ### Run as a service
117
-
118
- Autostart with the system and restart on failure — one command:
119
-
120
- | OS | How | Command |
121
- |---|---|---|
122
- | Windows | Windows service via [nssm](https://nssm.cc) (`winget install --id NSSM.NSSM -e`); run the terminal as administrator; you will be offered to run the service under your account (where the agents are signed in) | `npm run service:install` |
123
- | Linux | `systemd --user` (to keep it running without a login session: `sudo loginctl enable-linger $USER`) | `npm run service:install` |
124
- | macOS | LaunchAgent (`launchd`) | `npm run service:install` |
125
-
126
- Also: `acpgram service restart` (after an update; a hung service is force-stopped), `acpgram service status`, `acpgram service uninstall` (npm: `npm run service:status`, `npm run service:uninstall`). Options go after `--` (otherwise npm takes them for itself): `npm run service:install -- --dry-run` prints the commands without running them, `-- --name <name>` sets another service name (default `acpgram`; Windows and Linux), `-- --system` installs a Windows service under LocalSystem without a terminal. Logs: `data/service.log` (Linux: `journalctl --user -u acpgram -f`; Windows PowerShell 5.1: `Get-Content <path>\data\service.log -Tail 30 -Encoding UTF8`, otherwise non-English text looks garbled).
127
-
128
- > On Windows the service needs your account's **password**: if you sign in with a Microsoft account, that is the Microsoft account password, not the Windows PIN (with a PIN the service fails to log on — the wizard detects this and asks again). Accounts without a password cannot run services.
129
- >
130
- > The account password is passed to `nssm` as a command-line argument — this is how nssm grants the "Log on as a service" right. It is never printed or stored by the bot and is visible in the process list only to administrators and the same user for the fraction of a second the command runs. Without a terminal the service can only be installed with `--system` (LocalSystem).
131
-
132
- ### Docker
133
-
134
- ```bash
135
- cp .env.example .env # set TELEGRAM_BOT_TOKEN, ALLOWED_USER_ID, engine API keys and uncomment PROJECTS_DIR
136
- docker compose up -d --build
137
- ```
138
-
139
- In the container the agent sees only the mounted projects folder (`PROJECTS_DIR` → `/projects`). The image ships all four engines: Gemini CLI, Claude Code (`claude-agent-acp` bridge), OpenAI Codex (`codex` + `codex-acp` bridge) and Antigravity CLI. To build a lighter image, list only the engines you need in `ENGINES` in `.env` (e.g. `ENGINES=gemini claude`); `DEFAULT_ENGINE` must be one of them.
140
-
141
- - Authentication: Gemini - `GEMINI_API_KEY`, Claude Code - `ANTHROPIC_API_KEY`, Codex - `OPENAI_API_KEY` (all from `.env`).
142
- - Antigravity CLI has no API keys: log in once with your Google account (a link and a code, no browser needed on the server): `docker compose exec -it bot agy acp --login`. The login is kept in the `gemini-home` volume. The build fails if Antigravity cannot be installed or lacks the `acp` subcommand (1.5+) - then drop `agy` from `ENGINES`.
143
- - Volumes: `bot-data`, `gemini-home`, `claude-home`, `codex-home` survive container re-creation; `docker compose down -v` removes them.
144
- - An engine that starts but is not authenticated is shown as "login needed" in `/engine`.
145
-
146
- ## Bot commands
147
-
148
- | Command | Who | What |
149
- |---|---|---|
150
- | `/start` | everyone | welcome screen: engine, model, access level, project |
151
- | `/project [name or path]` | everyone | choose the working folder |
152
- | `/engine [gemini, claude, agy, codex]` | everyone | choose the engine |
153
- | `/model` | everyone | choose the model and reasoning level |
154
- | `/new` | everyone | new session |
155
- | `/sessions` | everyone | resume a previous session in this project |
156
- | `/stop` | everyone | stop the running request |
157
- | `/close`, `/exit` | everyone | close the session and unload the agent process |
158
- | `/users` | admin | teammates: level, engines, models, end session, revoke access |
159
- | `/active` | admin | active sessions with buttons to end them |
160
- | `/invite` | admin | one-time invite link (24 h) |
161
-
162
- ## Access levels
163
-
164
- The main admin is set by `ALLOWED_USER_ID`. Everyone else gets access through an invite link or by asking (the request goes to the admin with buttons).
165
-
166
- | Level | Gemini CLI | Claude Code | Antigravity CLI | Codex | Meaning |
167
- |---|---|---|---|---|---|
168
- | Read | `plan` | `plan` | `plan` | `read-only` | the agent only reads and analyzes |
169
- | Normal | `default` | `default` | `default` | `workspace-write` | permission requests go to the user |
170
- | Full | `autoEdit` | `bypassPermissions` | `accept-edits` | `agent-full-access` | edits without confirmation (Claude Code: no confirmations at all) |
171
- | Admin | `autoEdit` | `bypassPermissions` | `accept-edits` | `agent-full-access` | change with `ACP_MODE`/`GEMINI_ADMIN_MODE`, `CLAUDE_ADMIN_MODE`, `AGY_ADMIN_MODE` |
172
-
173
- 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).
174
-
175
- > 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.
176
-
177
- ## Configuration (`.env`)
178
-
179
- | Variable | Required | Description |
180
- |---|---|---|
181
- | `TELEGRAM_BOT_TOKEN` | yes | bot token |
182
- | `ALLOWED_USER_ID` | yes | Telegram ID of the main admin |
183
- | `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) |
184
- | `DEFAULT_ENGINE` | no | `gemini` (default), `claude`, `agy` or `codex`; the bot does not start if this engine is not installed |
185
- | `DEFAULT_LANG` | no | interface language by default: `en` (default), `ru` or `uk`. Each user changes their language with `/language` |
186
- | `GEMINI_API_KEY` | no | Gemini API key, passed to the agent through the bot's environment |
187
- | `ANTHROPIC_API_KEY` | no | Anthropic API key for Claude Code (API billing instead of a subscription) |
188
- | `GEMINI_COMMAND`, `CLAUDE_COMMAND`, `AGY_COMMAND`, `CODEX_COMMAND` | no | full paths to the engines if they are not in `PATH` (typical for services) |
189
- | `ACP_MODE` / `GEMINI_ADMIN_MODE`, `CLAUDE_ADMIN_MODE`, `AGY_ADMIN_MODE`, `CODEX_ADMIN_MODE` | no | admin session mode per engine |
190
- | `MAX_AGENTS` | no | concurrent teammate agents (3) |
191
- | `IDLE_MINUTES` | no | idle session timeout, minutes (30) |
192
- | `ANIMATED_ICONS` | no | `0` — plain emoji instead of animated icons in drafts |
193
-
194
- `.env` is never committed. Keep the token and keys out of the code.
195
-
196
- ## Development
197
-
198
- ```bash
199
- npm test # node:test, no dependencies, no Telegram
200
- ```
201
-
202
- ```
203
- install.ps1 one-line installer for Windows
204
- install.sh one-line installer for Linux and macOS
205
- src/
206
- cli.mjs the acpgram command: start, setup, service, update, version
207
- main.mjs entry point: loads .env, runs the setup wizard on first start
208
- setup.mjs setup wizard
209
- service.mjs service: nssm (Windows), systemd --user (Linux), launchd (macOS)
210
- bot.mjs message and button routing, access checks
211
- engines.mjs engine registry: commands, modes per level, catalogs, usage parsing
212
- acp.mjs Agent Client Protocol client (agent subprocess)
213
- access.mjs per-user engines and models, model catalogs, applying the choice
214
- turn.mjs one request: streaming draft, work log, permissions, final answer
215
- state.mjs per-user state: agent process, engine, project, limits, idle reaper
216
- admin.mjs invites, access requests, /users, /active
217
- projects.mjs project paths (inside the root or anywhere), recent projects, search
218
- *Ui.mjs /project, /sessions, /engine, /model screens
219
- ui.mjs rendering: drafts, steps, final message, screens
220
- telegram.mjs Bot API calls, rich messages, long text splitting
221
- db.mjs SQLite: sessions, requests, tool calls, permissions, users, usage
222
- test/ node:test tests and a fake ACP agent
223
- .github/workflows CI (tests on Windows / Linux / macOS) and releases (archives, checksums, installer checks)
224
- ```
225
-
226
- Releases are built by GitHub Actions on a version tag: tests on all three OSes, `.zip` / `.tar.gz` archives with `SHA256SUMS`, then both installers are verified on Windows, Linux and macOS against the published release. Installers can be tested against a local build with `ACPGRAM_RELEASE_URL=file:///path/to/dist`, `ACPGRAM_VERSION`, `ACPGRAM_NO_SETUP=1`, `ACPGRAM_YES=1`, `ACPGRAM_HOME`.
227
-
228
- ## License
229
-
230
- [MIT](LICENSE) © 2026 Alexey Seleznev